GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / iterations/34-cpu-floorplan

Journey and 4 more files

A JavaScript module in the iterations folder of Galaxies Wafers that builds rows, paints row, verifies v9 and draws on a canvas, covering cables. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.

700 lines of JavaScript and HTML and CSS from galaxies-wafers, in 5 files. Topic: Kuiper, cosmos and drawing engines. Section 1212 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. Floorplan render · galaxies-wafers / iterations/34-cpu-floorplan/floorplan.mjs lines 701–710
  2. Iterations — 34 Cpu Floorplan Page render · galaxies-wafers / iterations/34-cpu-floorplan/index.html lines 1–89
  3. Iterations — 35 System Journey Page render · galaxies-wafers / iterations/35-system-journey/index.html lines 1–42
  4. Journey render · galaxies-wafers / iterations/35-system-journey/journey.css lines 1–70
  5. Journey interaction · galaxies-wafers / iterations/35-system-journey/journey.mjs lines 1–489

Floorplan

A JavaScript module in the iterations folder of Galaxies Wafers that draws engine and cables, and uses data from the stars repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/34-cpu-floorplan/.

rendergalaxies-wafers / iterations/34-cpu-floorplan/floorplan.mjs · lines 701–710 of 710 (continued from section 1211) · Entry point · pattern loadSource (shared by 2 files)

What it does
It draws engine and cables. Defines 39 functions or classes, including $, FetchQueue, fetchTimed, fetchText, fetchRange. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain terms in the code: cables.
Inputs & outputs
In: data source: stars data; JSON file engine.json. Out: canvas drawing.
Downstream impact
Used directly by 1 file: Iterations — 34 Cpu Floorplan Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/34-cpu-floorplan/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/34-cpu-floorplan/.
What it achieves
It fetches queue (`FetchQueue`), fetches timed (`fetchTimed`) and fetches text (`fetchText`). Logical Floorplan — iteration 34. It responds to change, click and input events.
Why it matters
Loaded by the 34 Cpu Floorplan page at https://ventusltd.github.io/galaxies-wafers/iterations/34-cpu-floorplan/.
Application
galaxies-wafers · iterations/34-cpu-floorplan · JavaScript module
Uses
none found
Used by
loaded by Iterations — 34 Cpu Floorplan Page (script src)
Produces
$, FetchQueue, fetchTimed, fetchText, fetchRange, tokenize, push, exportedFunctions, analyse, layout, resize, px
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/34-cpu-floorplan/floorplan.mjs:701-710 · blob 1bd56513b97b08a9bfad12ba17678caa195170c4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
  });
  if (!hit) return;
  S.selected = hit; paintDetail(); draw();
});
window.addEventListener('resize', resize);
$('rules').textContent = `Loading: one queue, at most ${QUEUE_MAX} requests at once, ${TIMEOUT_MS / 1000} s timeout each; the source and the engine layer at start; the numbered database only on FIND LINE KEYS, in ${CHUNK / 1024} KB probes and one ${WINDOW / 1024} KB window. Drawing: one canvas; no DOM node per token or per line.`;

window.__floorplan = { S, queue, tokenize, analyse };
resize();
loadSource();

Iterations — 34 Cpu Floorplan Page

A web page in Galaxies Wafers that reads inputs for speed. Published at https://ventusltd.github.io/galaxies-wafers/iterations/34-cpu-floorplan/.

rendergalaxies-wafers / iterations/34-cpu-floorplan/index.html · lines 1–89 of 89 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
In: form fields (user input). Out: web page.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/34-cpu-floorplan/.
What it achieves
Logical Floorplan — the estate's code through a textbook processor.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
galaxies-wafers · iterations/34-cpu-floorplan · page
Uses
Floorplan (stylesheet), Galaxies Wafers — Iterations Page (link), Galaxies Wafers — Index Page (link), Floorplan (script src)
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/34-cpu-floorplan/index.html:1-89 · blob 3269f0e98ca86f6f0105e39643ec610058dd9552 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<title>Logical Floorplan — the estate's code through a textbook processor</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="floorplan.css">
</head>
<body>
<main id="page">
  <header>
    <h1>LOGICAL FLOORPLAN</h1>
    <p class="warn">Illustrative architecture, not a model of any specific chip.</p>
    <p class="dim">A real grid-engine module, read as text and cut into tokens, walked line by line through a
      classic five-stage pipeline (fetch, decode, execute, memory, write-back) as taught in Patterson and Hennessy.
      Everything drawn in the stages is derived from the source text by the tokenizer on this page.</p>
  </header>

  <section id="source" aria-label="Source">
    <div class="row">
      <span>source</span>
      <span id="srcstate" class="state">WAIT</span>
      <label class="sel">function <select id="fn" disabled></select></label>
    </div>
    <div id="srcline" class="dim small"></div>
  </section>

  <div id="dieWrap">
    <canvas id="die" aria-label="Floorplan of an illustrative processor. Tap a block to see what it handles."></canvas>
  </div>

  <section id="controls" aria-label="Controls">
    <button id="step" disabled>STEP</button>
    <button id="play" disabled>PLAY</button>
    <button id="reset" disabled>RESET</button>
    <label class="speed">speed <input id="speed" type="range" min="0" max="4" step="1" value="2"> <span id="speedv">1x</span></label>
  </section>

  <section id="detail" aria-live="polite">
    <div class="row"><b id="dtitle">Tap a block on the die</b> <span id="dcycle" class="dim small"></span></div>
    <pre id="dbody" class="body">The pipeline is empty until the source loads.</pre>
    <div class="row keyrow">
      <span id="dkey" class="small"></span>
    </div>
    <div class="row links">
      <a id="lcard" class="btn" hidden>open in code card</a>
      <a id="lwafer" class="btn" hidden>open on the wafer</a>
    </div>
  </section>

  <section id="keys" aria-label="Line keys">
    <div class="row">
      <span>line keys</span>
      <span id="keystate" class="state">WAIT</span>
      <button id="findkeys" disabled>FIND LINE KEYS</button>
    </div>
    <p class="dim small" id="keynote">Nothing is fetched until you ask. The keys come from the numbered database
      (LINES.md from the modular star): this page binary-searches it with small byte-range reads through a queue
      of at most three requests, each with a 15 s timeout, and reads one window of rows around the function's first
      line. The file is never downloaded whole.</p>
  </section>

  <section id="honest">
    <p><b>A teaching mapping, not how JavaScript runs.</b> A real JavaScript engine parses the source into
      bytecode for an interpreter, and a JIT compiler turns hot functions into machine code; only those machine
      instructions pass through a processor's pipeline, many of them per source line. Here each source line is
      treated as if it were one instruction so the stages can be seen.</p>
    <p class="dim small" id="rules"></p>
  </section>

  <details id="questions">
    <summary>Questions</summary>
    <ol>
      <li><b>How does this help draw a system or a single-line diagram?</b> <span id="q1"></span></li>
      <li><b>What is this code used for?</b> <span id="q2"></span></li>
      <li><b>Where does it lead next?</b> <span id="q3"></span></li>
    </ol>
    <p><b>Machine detail.</b> <span id="q4"></span></p>
  </details>

  <footer class="dim small">
    <a href="../">all iterations</a> · <a href="../../">the Line Wafer</a>
  </footer>
</main>
<script type="module" src="floorplan.mjs"></script>
</body>
</html>

Iterations — 35 System Journey Page

A web page in Galaxies Wafers that draws SVG graphics. Published at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.

rendergalaxies-wafers / iterations/35-system-journey/index.html · lines 1–42 of 42 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
Out: web page; SVG drawing.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.
What it achieves
One System, Stop by Stop.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
galaxies-wafers · iterations/35-system-journey · page
Uses
Journey (stylesheet), Galaxies Wafers — Iterations Page (link), Journey (script src)
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/35-system-journey/index.html:1-42 · blob 43da7fc91fc7176dbf6953986c6cbf55f6346c07 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<title>One System, Stop by Stop</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="journey.css">
</head>
<body>
<main>
  <header>
    <h1>ONE SYSTEM, STOP BY STOP</h1>
    <p class="dim small">Five published engine calculations, walked in the order a single-line diagram is drawn: a load, the nearest mapped node, the cable route between them, the physics along that feeder, and the rating labels at a busbar. Each stop adds its element to the diagram. Where one calculation's output becomes the next one's input, the wire is drawn with its unit and meaning, and refus  … [line shortened here: 430 characters; full line on GitHub]
    <details id="srcs" class="srcs">
      <summary>engine sources&nbsp;·&nbsp;<span id="srcsum">WAIT</span></summary>
      <ul id="mods" class="mods"></ul>
      <p class="dim small">Fetched only when a stop that needs them is opened (and every earlier stop, because the chain reads their outputs). At most three requests at once; each has a 15 s timeout; a failed row can be tapped to retry.</p>
    </details>
  </header>

  <div class="sldwrap" id="sldwrap">
    <svg id="sld" viewBox="0 0 360 262" role="img" aria-label="Single-line diagram that grows stop by stop"></svg>
    <div id="dots" class="dots" role="tablist" aria-label="Stops"></div>
  </div>

  <section id="card" class="card" aria-live="polite"></section>

  <footer class="dim small">
    <p class="final">each stop is a separate published calculation; the chain is an illustration, not a connection study</p>
    <p>Modules and proof fixtures are read from ventus-grid-engine at commit <span id="pin"></span>, imported at run time, never copied. Nothing here reads real grid data. <a href="../">every version</a></p>
  </footer>
</main>
<nav class="nav" aria-label="Stop navigation">
  <button id="prev" type="button">‹ previous</button>
  <span id="where" class="dim"></span>
  <button id="next" type="button">next ›</button>
</nav>
<script type="module" src="journey.mjs"></script>
</body>
</html>

Journey

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

rendergalaxies-wafers / iterations/35-system-journey/journey.css · lines 1–70 of 70 · Entry point

What it does
Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Iterations — 35 System Journey Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Loaded by the 35 System Journey page at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.
Application
galaxies-wafers · iterations/35-system-journey · style sheet
Uses
none found
Used by
loaded by Iterations — 35 System Journey Page (stylesheet)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/35-system-journey/journey.css:1-70 · blob b32bd6c41fbc350d98f0b2f64cbb8062f5e08d75 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
:root{--ink:#d8dee9;--dim:#8b93a7;--ground:#0b0d12;--edge:#1b2030;--lit:#ffd54a;--beam:#5ec8f2;--grey:#8a8f98}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
  padding:calc(env(safe-area-inset-top,0px) + .7rem) 1rem calc(env(safe-area-inset-bottom,0px) + 5rem)}
main{max-width:60rem;margin:0 auto}
h1{font-size:13px;letter-spacing:.16em;font-weight:600;margin:0 0 .3rem}
h2{font-size:12px;letter-spacing:.14em;font-weight:600;color:#fff;margin:.2rem 0 .35rem}
h3{font-size:11px;letter-spacing:.12em;font-weight:400;color:var(--dim);margin:.9rem 0 .35rem;text-transform:uppercase}
p{margin:.35rem 0}
.dim{color:var(--dim)} .small{font-size:11.5px}
a{color:var(--beam)}
code{color:var(--beam)}
.srcs{margin:.3rem 0 .5rem}
details summary{cursor:pointer;color:var(--beam);min-height:36px;display:flex;align-items:center}
.mods{list-style:none;margin:0;padding:0;display:grid;gap:.15rem;font-size:11.5px}
.mods li{overflow-wrap:anywhere;min-height:24px}
.mods li b{font-weight:600;display:inline-block;min-width:3.2em}
.mods li.fail{cursor:pointer;text-decoration:underline dotted}
.sldwrap{position:sticky;top:env(safe-area-inset-top,0px);z-index:3;background:var(--ground);border-bottom:1px solid var(--edge);padding:.2rem 0 .3rem;margin:0 -1rem;padding-left:1rem;padding-right:1rem}
#sld{display:block;width:100%;max-width:40rem;height:auto;max-height:30vh;margin:0 auto;touch-action:pan-y}
#sld text{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:8.4px;fill:var(--ink);paint-order:stroke;stroke:#0b0d12;stroke-width:2.4px}
#sld .d{fill:var(--dim)} #sld .w{fill:#fff} #sld .y{fill:var(--lit)} #sld .ph{fill:#3a4258} #sld .b{font-weight:600}
#sld .rf{fill:#fff;font-weight:600;letter-spacing:.06em}
.dots{display:flex;justify-content:center;gap:.3rem;margin-top:.15rem}
.dots button{font:inherit;font-size:11px;color:var(--dim);background:#07080c;border:1px solid var(--edge);border-radius:.35rem;min-width:44px;min-height:34px;padding:0 .35rem}
.dots button[aria-current=step]{color:#fff;border-color:#fff}
.card{margin-top:.7rem;touch-action:pan-y;min-height:50vh}
.boundary{border:1px solid var(--edge);border-left:3px solid #fff;background:#10131b;padding:.5rem .6rem;margin:.6rem 0;font-size:11.5px}
.note{border-left:2px solid var(--edge);padding-left:.6rem;font-size:11.5px}
.in{margin:.55rem 0}
.in .row{display:flex;justify-content:space-between;gap:.5rem;align-items:baseline}
.tag{font-size:10px;letter-spacing:.1em;color:var(--dim)}
input[type=range]{width:100%;min-height:36px;accent-color:#fff}
output{color:#fff;font-weight:600}
.seg{display:flex;flex-wrap:wrap;gap:.35rem;margin-top:.3rem}
.seg button,.act{font:inherit;color:var(--ink);background:#07080c;border:1px solid var(--edge);border-radius:.35rem;padding:.4rem .6rem;min-height:40px;min-width:3rem}
.seg button[aria-pressed=true]{border-color:#fff;box-shadow:inset 0 0 0 1px #fff;color:#fff}
.act{color:var(--beam)}
.results{list-style:none;margin:.3rem 0;padding:0;display:grid;gap:.4rem}
.results li{border:1px solid var(--edge);border-radius:.4rem;background:#07080c;padding:.4rem .55rem}
.results .k{display:flex;justify-content:space-between;gap:.6rem;align-items:baseline}
.results .v{color:var(--lit);font-weight:600;text-align:right;overflow-wrap:anywhere}
.results .fn{color:var(--beam);font-size:11px;overflow-wrap:anywhere}
.results .basis{color:var(--dim);font-size:11px;overflow-wrap:anywhere}
.results li.empty .v{color:#fff}
.results li.empty{border-style:dashed}
.wires{list-style:none;margin:.3rem 0;padding:0;display:grid;gap:.4rem}
.wire{border:1px solid #3a4258;border-radius:.4rem;padding:.4rem .55rem;background:#0d1018;overflow-wrap:anywhere}
.wire .ends{font-size:11.5px;color:#fff}
.wire .q{font-size:11.5px}
.wire .st{font-weight:600;letter-spacing:.08em;color:#fff}
.wire .why{font-size:11px;color:var(--ink)}
.wire.refused,.wire.empty{border-style:dashed;border-color:var(--grey);background:#07080c}
.plane{display:block;width:100%;height:230px;background:#07080c;border:1px solid var(--edge);border-radius:.4rem;touch-action:none}
.questions{border:1px solid var(--edge);border-radius:.45rem;background:#10131b;padding:0 .65rem;margin:1rem 0 .5rem}
.questions summary{font-size:11px;letter-spacing:.14em;text-transform:uppercase}
.questions dt{color:#fff;margin-top:.5rem;font-size:12px}
.questions dd{margin:.2rem 0 .6rem;font-size:11.5px;overflow-wrap:anywhere}
.machine{border-left:3px solid var(--beam);padding:.35rem .6rem;background:#07080c;font-size:11.5px;overflow-wrap:anywhere}
.final{color:#fff;border-top:1px solid var(--edge);padding-top:.6rem}
pre{margin:.3rem 0 0;font-size:10.5px;white-space:pre;overflow-x:auto;max-height:18rem;background:#05060a;border:1px solid var(--edge);border-radius:.3rem;padding:.4rem}
footer{margin-top:1.2rem}
.nav{position:fixed;left:0;right:0;bottom:0;z-index:5;display:flex;align-items:center;justify-content:space-between;gap:.5rem;
  background:#0b0d12;border-top:1px solid #3a4258;padding:.45rem 1rem calc(env(safe-area-inset-bottom,0px) + .45rem)}
.nav button{font:inherit;color:#fff;background:#10131b;border:1px solid #3a4258;border-radius:.4rem;min-height:44px;min-width:7.5rem;padding:0 .8rem}
.nav button:disabled{color:#3a4258;border-color:var(--edge)}
@media (min-width:900px){
  #sld{max-height:44vh}
}

Journey

A JavaScript module in the iterations folder of Galaxies Wafers that builds rows, paints row, verifies v9 and draws on a canvas, covering cables. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.

interactiongalaxies-wafers / iterations/35-system-journey/journey.mjs · lines 1–489 of 959 · Entry point · pattern buildInputs (shared by 2 files)

What it does
It draws cables, substations, transformers and 33kV. Defines 53 functions or classes, including $, el, nf, esc, attempt. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain terms in the code: cables, substations, transformers, 33kV, 100kV, 1kV.
Inputs & outputs
Out: canvas drawing. Voltage levels named: 100kV, 33kV, 1kV.
Downstream impact
Used directly by 1 file: Iterations — 35 System Journey Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.
What it achieves
It builds rows (`buildRows`), paints row (`paintRow`) and verifies v9 (`verifyV9`). One System, Stop by Stop. Five published engine calculations chained into one illustrative system and drawn as a single-line diagram that grows stop by stop. Its code works with 33 kV, 0 kV and 0.001 MVA. It responds to click, input and pointerdown events.
Why it matters
Loaded by the 35 System Journey page at https://ventusltd.github.io/galaxies-wafers/iterations/35-system-journey/.
Application
galaxies-wafers · iterations/35-system-journey · JavaScript module
Uses
none found
Used by
loaded by Iterations — 35 System Journey Page (script src)
Produces
$, el, nf, esc, attempt, colourOf, enqueue, pump, timed, hydrate, M, why
Defines here
$, el, nf, esc, attempt, colourOf, enqueue, pump, timed, hydrate, M, why, buildRows, paintRow, verifyV9, fixtureFrom, inject, unsound, INJECTED, connect, gate, chain, drawSld, T, L, ghost
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/35-system-journey/journey.mjs:1-489 · blob a773b440d5a6bf6634a4eccd674ec9e28f26661e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* One System, Stop by Stop.
   Five published engine calculations chained into one illustrative system and
   drawn as a single-line diagram that grows stop by stop. Every PRIMARY
   calculation (demand, nearest node and its distance, route length, corridor
   estimate, apparent and reactive power, current, voltage drop, drop percent,
   losses, rating labels) is returned by ventus-grid-engine at the pinned
   commit, imported at run time. This file does some arithmetic of its own,
   each piece stated where it happens: thermal output times units (the thermal
   quantity offered on the stop 1 wire), differences between two returned
   numbers (stop 2 ranks, stop 3 radius comparisons), the named unit
   conversions (km to m, kVA to MVA, kV to V) applied only when the reader
   leaves "stated conversions" on, and the display projection of the stop 2
   plane. It also checks unit, meaning, voltage basis and numeric finiteness
   on every wire between two calculations, and it draws. */

const COMMIT = 'd9cd18b0e2034325814924e6e4a0e958014f2748';
const BASE = `https://cdn.jsdelivr.net/gh/Ventusltd/ventus-grid-engine@${COMMIT}/`;
const PIN = COMMIT.slice(0, 12);

const $ = id => document.getElementById(id);
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const nf = (v, sig = 4) => (typeof v === 'number' && Number.isFinite(v)) ? v.toLocaleString('en-GB', { maximumSignificantDigits: sig }) : String(v);
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const attempt = fn => { try { return { ok: fn() }; } catch (e) { return { err: (e && e.message) || String(e) }; } };

const BOUNDARY = 'Illustrative physics drawn by a computer from published data. Not an engineering design or certified calculation. Project policy: any real design above 100 kW needs study and approval by a qualified chartered electrical engineer under the applicable standards.';
const PRIMARY_ONLY = 'Primary calculations come from the engine modules. This page itself computes thermal output times units, differences between two returned numbers, and the stated unit conversions, each shown where it is used.';
const FINAL = 'each stop is a separate published calculation; the chain is an illustration, not a connection study';

/* Grid Atlas v8 topology colours; substations white. A voltage the Atlas does
   not draw is grey. */
const ATLAS = [{ kv: 400, c: '#0054ff' }, { kv: 275, c: '#ff0000' }, { kv: 220, c: '#ff9900' }, { kv: 132, c: '#00cc00' }, { kv: 66, c: '#b200ff' }, { kv: 11, c: '#ff00ff' }];
const GREY = '#8a8f98';
const colourOf = kv => (ATLAS.find(a => a.kv === kv) || { c: GREY }).c;

/* ── sources, loaded the Grid Atlas way ─────────────────────────────────── */
const SRC = {
  em: { path: 'engine/electrification-model.js', kind: 'module' },
  geo9: { path: 'engine/v9-geodesy.js', kind: 'module' },
  ns: { path: 'engine/v9-nearest-search.js', kind: 'module' },
  pv9: { path: 'proofs/v9-engine.proof.mjs', kind: 'text' },
  gc: { path: 'engine/geo-core.js', kind: 'module' },
  ce: { path: 'engine/corridor-estimate.js', kind: 'module' },
  pf: { path: 'engine/power-factor.js', kind: 'module' },
  cfp: { path: 'engine/current-from-power.js', kind: 'module' },
  vd: { path: 'engine/voltage-drop.js', kind: 'module' },
  topo: { path: 'engine/network-topology.js', kind: 'module' },
  re: { path: 'engine/rating-envelope.js', kind: 'module' },
  pre: { path: 'proofs/rating-envelope.proof.mjs', kind: 'text' }
};
const STOP_SRC = [null, ['em'], ['geo9', 'ns', 'pv9'], ['gc', 'ce'], ['pf', 'cfp', 'vd'], ['topo', 're', 'pre']];
const RT = Object.fromEntries(Object.keys(SRC).map(k => [k, { status: 'WAIT', value: null, error: '', promise: null }]));
const TIMEOUT_MS = 15000;

const queue = { active: 0, max: 3, waiting: [], peak: 0 };
function enqueue(job) {
  return new Promise((res, rej) => { queue.waiting.push({ job, res, rej }); pump(); });
}
function pump() {
  while (queue.active < queue.max && queue.waiting.length) {
    const t = queue.waiting.shift();
    queue.active++; queue.peak = Math.max(queue.peak, queue.active);
    t.job().then(t.res, t.rej).finally(() => { queue.active--; pump(); });
  }
}
function timed(p, what) {
  let timer;
  return Promise.race([p, new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`${what} timed out after ${TIMEOUT_MS / 1000} s`)), TIMEOUT_MS); })])
    .finally(() => clearTimeout(timer));
}
function hydrate(id) {
  const r = RT[id];
  if (r.status === 'OK' || r.promise) return r.promise || Promise.resolve(r.value);
  r.status = 'LOAD'; r.error = ''; paintRow(id);
  const s = SRC[id];
  r.promise = enqueue(async () => {
    if (s.kind === 'module') return timed(import(BASE + s.path), s.path);
    const ac = new AbortController();
    const t = setTimeout(() => ac.abort(), TIMEOUT_MS);
    try {
      const res = await fetch(BASE + s.path, { signal: ac.signal });
      if (!res.ok) throw new Error('HTTP ' + res.status);
      return await res.text();
    } catch (e) { throw new Error(e && e.name === 'AbortError' ? `${s.path} timed out after ${TIMEOUT_MS / 1000} s` : (e && e.message) || String(e)); }
    finally { clearTimeout(t); }
  }).then(v => { r.value = v; r.status = 'OK'; paintRow(id); update(); return v; },
    e => { r.status = 'FAIL'; r.error = (e && e.message) || String(e); r.promise = null; paintRow(id); update(); return null; });
  return r.promise;
}
const M = id => (RT[id].status === 'OK' ? RT[id].value : null);
const why = id => {
  const r = RT[id];
  if (r.status === 'FAIL') return `engine source ${SRC[id].path} did not load: ${r.error}`;
  return `waiting for ${SRC[id].path} (${r.status})`;
};

const rows = {};
function buildRows() {
  const ul = $('mods');
  for (const id of Object.keys(SRC)) {
    const li = el('li'); li.dataset.src = id;
    const b = el('b'); const t = el('span');
    li.append(b, ' ', t);
    li.addEventListener('click', () => { if (RT[id].status === 'FAIL') hydrate(id); });
    ul.append(li); rows[id] = { li, b, t };
  }
  for (const id of Object.keys(SRC)) paintRow(id);
}
function paintRow(id) {
  const r = RT[id], row = rows[id];
  if (!row) return;
  const stop = STOP_SRC.findIndex(a => a && a.includes(id));
  row.b.textContent = r.status;
  row.t.textContent = `${SRC[id].path} · stop ${stop}` + (r.status === 'FAIL' ? ` — ${r.error} (tap to retry)` : r.status === 'WAIT' ? ' — not fetched until that stop is opened' : '');
  row.li.classList.toggle('fail', r.status === 'FAIL');
  const counts = {};
  for (const k of Object.keys(RT)) counts[RT[k].status] = (counts[RT[k].status] || 0) + 1;
  $('srcsum').textContent = ['OK', 'LOAD', 'WAIT', 'FAIL'].filter(s => counts[s]).map(s => `${counts[s]} ${s}`).join(' · ');
}

/* ── fixtures, from the proofs' own served bytes ─────────────────────────── */
/* The nearest-search trap fixture, written with the proof's own expressions.
   It is only used after every declaration line below is found verbatim in the
   served proofs/v9-engine.proof.mjs at the pinned commit. */
const QUERY = [0, 55];
const DECOY_NORTH = { name: 'Decoy North Grid Substation', voltages_kv: [400], location: { lon: 0, lat: 55 + 6.6 / 111.32 } };
const TRUE_EAST = { name: 'True East Substation', voltages_kv: [400], location: { lon: 6.0 / (111.32 * Math.cos(55 * Math.PI / 180)), lat: 55 } };
const FAR = { name: 'Far Away Substation', voltages_kv: [400], location: { lon: 1.5, lat: 56.2 } };
const LOW_VOLTAGE = { name: 'Local 33kV Point', voltages_kv: [33], location: { lon: 0.001, lat: 55.001 } };
const NODES = [DECOY_NORTH, TRUE_EAST, FAR, LOW_VOLTAGE];
const V9_LINES = [
  'const QUERY = [0, 55];',
  "const DECOY_NORTH = { name: 'Decoy North Grid Substation', voltages_kv: [400],",
  'location: { lon: 0, lat: 55 + 6.6 / 111.32 } };',
  "const TRUE_EAST = { name: 'True East Substation', voltages_kv: [400],",
  'location: { lon: 6.0 / (111.32 * Math.cos(55 * Math.PI / 180)), lat: 55 } };',
  "const FAR = { name: 'Far Away Substation', voltages_kv: [400],",
  'location: { lon: 1.5, lat: 56.2 } };',
  "const LOW_VOLTAGE = { name: 'Local 33kV Point', voltages_kv: [33],",
  'location: { lon: 0.001, lat: 55.001 } };',
  'const best = idx.nearest(QUERY[0], QUERY[1], { minimumKv: 100 });'
];
let v9check = null;
function verifyV9(text) {
  if (v9check && v9check.text === text) return v9check;
  const lines = text.split('\n').map(s => s.trim());
  const at = [];
  let missing = null;
  for (const L of V9_LINES) { const i = lines.indexOf(L); if (i < 0) { missing = L; break; } at.push(i + 1); }
  v9check = missing ? { text, ok: false, missing } : { text, ok: true, first: Math.min(...at), last: Math.max(...at) };
  return v9check;
}

/* The rating-envelope proof declares its fixture as an object literal named
   PRODUCT. It is read as text and turned into JSON without evaluating code;
   ACCEPTS is the value network-topology.js exports under that name. */
let reFix = null;
function fixtureFrom(text, accepts) {
  if (reFix && reFix.text === text) return reFix;
  const lines = text.split('\n');
  const start = lines.findIndex(l => /^const PRODUCT = \{/.test(l));
  if (start < 0) throw new Error('no "const PRODUCT = {" line in the proof');
  let end = -1;
  for (let i = start + 1; i < lines.length; i++) if (/^\};/.test(lines[i])) { end = i; break; }
  if (end < 0) throw new Error('the PRODUCT literal has no closing line');
  let src = lines.slice(start, end + 1).join('\n').replace(/^const PRODUCT = /, '').replace(/;\s*$/, '').replace(/\/\/[^\n]*/g, '');
  src = src.replace(/\bACCEPTS\b/g, JSON.stringify(accepts))
    .replace(/'([^'\\\n]*)'/g, (_, s) => JSON.stringify(s))
    .replace(/([{,]\s*)([A-Za-z_]\w*)\s*:/g, '$1"$2":')
    .replace(/,(\s*[}\]])/g, '$1');
  reFix = { text, product: JSON.parse(src), firstLine: start + 1, lastLine: end + 1 };
  return reFix;
}

/* ── state: every value here is a scenario input ─────────────────────────── */
const S = {
  stop: 1,
  heat: 12.25, scop: 3.5, div: 1.7, units: 2000, carry: 'after_diversity', tryAdd: false,
  lon: QUERY[0], lat: QUERY[1], minKv: 100,
  kv: null, kvFollow: true, pf: 0.95, r: 0.16, x: 0.1, phases: 'three', convert: true,
  site: 'COWL', season: 'winter'
};
{
  const m = /stop=([1-5])/.exec(location.hash);
  if (m) S.stop = +m[1];
  /* Fault injection, visible on the page: #nan=<wire id> replaces the value
     carried on that one wire with NaN so the finiteness refusal can be seen. */
  const f = /nan=([a-z]+)/.exec(location.hash);
  S.nan = f ? f[1] : null;
}

/* ── wires: the page's own check between two calculations ────────────────── */
const CONVERSIONS = {
  'km->m': { factor: 1000, text: '1 km = 1,000 m' },
  'kVA->MVA': { factor: 0.001, text: '1 kVA = 0.001 MVA' }, /* a conversion factor: skipping it overstates MVA 1000x */
  'kV->V': { factor: 1000, text: '1 kV = 1,000 V' }
};
/* Fault injection and the finiteness gate, shared by every wire. q.nums lists
   every number the wire carries (default [q.value]); a text value must be a
   non-empty string. unsound() returns a refusal reason, or '' when sound. */
function inject(id, q) {
  if (!q || S.nan !== id) return q;
  return { ...q, value: NaN, nums: q.nums ? [NaN, ...q.nums.slice(1)] : undefined, show: undefined, injected: true };
}
function unsound(q) {
  if (typeof q.value === 'string' && !q.nums) return q.value ? '' : 'The carried text is empty, so nothing crosses this wire.';
  const nums = q.nums || [q.value];
  const bad = nums.find(v => typeof v !== 'number' || !Number.isFinite(v));
  if (bad === undefined && nums.length) return '';
  return `The carried value ${String(bad)} is not a finite number, so nothing crosses this wire. Finiteness is checked before unit and meaning: a matching label is not a sound value.`;
}
const INJECTED = id => `fault injection from the page address (#nan=${id}): the value on this wire was replaced with NaN to show the refusal.`;

/* q: { value, unit, meaning, basis?, nums? } or null with emptyWhy.
   accepts: { unit, meanings, basis?, basisWhy?, why, okWhy } */
function connect({ id, from, to, q, emptyWhy, accepts }) {
  q = inject(id, q);
  const w = { id, from, to, q, accepts, state: 'EMPTY', reason: '', direct: '', out: null };
  if (!q) { w.reason = emptyWhy || 'nothing was returned upstream'; return w; }
  const bad = unsound(q);
  if (bad) { w.state = 'REFUSED'; w.reason = (q.injected ? INJECTED(id) + ' ' : '') + bad; return w; }
  if (accepts.meanings && !accepts.meanings.includes(q.meaning)) {
    w.state = 'REFUSED';
    w.reason = `meaning "${q.meaning}" is not one this input accepts (${accepts.meanings.map(m => `"${m}"`).join(', ')}). ${accepts.why || ''}`.trim();
    return w;
  }
  if (accepts.basis && q.basis !== accepts.basis) {
    w.state = 'REFUSED';
    w.reason = accepts.basisWhy || `voltage basis "${q.basis || 'not stated'}" is not the "${accepts.basis}" basis this input takes.`;
    return w;
  }
  if (q.unit !== accepts.unit) {
    const conv = CONVERSIONS[`${q.unit}->${accepts.unit}`];
    const skip = conv ? (conv.factor < 1 ? `overstates ${accepts.unit} ${nf(1 / conv.factor)}×` : `understates ${accepts.unit} ${nf(conv.factor)}×`) : '';
    w.direct = `direct connection REFUSED: ${nf(q.value, 6)} ${q.unit} into an input that takes ${accepts.unit}` + (conv ? ` would be read as ${nf(q.value, 6)} ${accepts.unit}. ${nf(conv.factor)} is a conversion factor; skipping it ${skip}.` : '; no stated conversion exists.');
    if (conv && S.convert) {
      w.state = 'CONVERTED';
      w.out = { value: q.value * conv.factor, unit: accepts.unit, meaning: q.meaning, basis: q.basis };
      w.reason = `stated unit conversion by this page: ${conv.text}, so ${nf(q.value, 6)} ${q.unit} crosses as ${nf(w.out.value, 6)} ${accepts.unit}; the meaning is unchanged.`;
    } else {
      w.state = 'REFUSED';
      w.reason = conv ? 'stated conversions are switched off, so nothing crosses this wire.' : 'the units differ and this page states no conversion between them.';
    }
    return w;
  }
  w.state = 'ACCEPTED';
  w.out = { value: q.value, unit: q.unit, meaning: q.meaning, basis: q.basis };
  w.reason = accepts.okWhy || 'unit and meaning match what the input takes.';
  return w;
}

/* A wire built by hand (a text key, or a fixed refusal) passes the same
   injection and finiteness gate as connect(). */
function gate(w) {
  if (!w.q) return w;
  w.q = inject(w.id, w.q);
  const bad = unsound(w.q);
  if (bad) { w.state = 'REFUSED'; w.reason = (w.q.injected ? INJECTED(w.id) + ' ' : '') + bad; w.unsound = true; }
  return w;
}

/* The voltage basis. current-from-power.js states that for phases "three" the
   voltage is line-to-line and for phases "single" it is line-to-neutral. The
   fixture node declares kV with no line-neutral or service basis. No
   line-to-neutral connection is inferred and no sqrt(3) is inserted: the
   joined path stays three-phase and single phase is refused on that wire. */
const BASIS_OF_PHASES = { three: 'line-to-line', single: 'line-to-neutral' };
const NO_LN = 'the node declares line-to-line kV only; no line-neutral basis is established';

/* ── the chain: the primary calculations below are module calls ─────────── */
function chain() {
  const R = { wires: {} };

  /* STOP 1 · DEMAND */
  const em = M('em');
  if (!em) R.s1 = { empty: why('em') };
  else {
    const q = em.MEANING;
    const thermal = attempt(() => em.quantity(S.heat, 'kW', q.THERMAL_OUTPUT));
    const elec = thermal.ok ? attempt(() => em.electricalInputFromHeat({ thermal: thermal.ok, scop: S.scop })) : thermal;
    const fleet = elec.ok ? attempt(() => em.fleetDemand({ units: S.units, perUnitNameplate: elec.ok, perUnitAfterDiversity: em.quantity(S.div, 'kW', q.AFTER_DIVERSITY) })) : elec;
    const plateOnly = elec.ok ? attempt(() => em.fleetDemand({ units: S.units, perUnitNameplate: elec.ok })) : elec;
    const thermalFleet = thermal.ok ? attempt(() => em.fleetDemand({ units: S.units, perUnitNameplate: thermal.ok })) : thermal;
    const added = (fleet.ok && plateOnly.ok) ? attempt(() => em.combinedPeak({ fleets: [plateOnly.ok, fleet.ok] })) : { err: 'upstream refused' };
    let carried = null, carryWhy = '';
    if (S.carry === 'after_diversity') {
      if (fleet.ok && fleet.ok.diversified) carried = { value: fleet.ok.diversified.value, unit: fleet.ok.diversified.unit, meaning: fleet.ok.diversified.meaning, label: fleet.ok.diversified.label };
      else carryWhy = `fleetDemand refused: ${fleet.err}`;
    } else if (S.carry === 'nameplate') {
      if (fleet.ok) carried = { value: fleet.ok.simultaneous.value, unit: fleet.ok.simultaneous.unit, meaning: fleet.ok.simultaneous.meaning, label: fleet.ok.simultaneous.label };
      else carryWhy = `fleetDemand refused: ${fleet.err}`;
    } else {
      if (thermal.ok) carried = { value: thermal.ok.value * S.units, unit: thermal.ok.unit, meaning: thermal.ok.meaning, label: 'heat delivered, units × per-unit thermal output' };
      else carryWhy = `quantity refused: ${thermal.err}`;
    }
    R.s1 = { thermal, elec, fleet, plateOnly, thermalFleet, added, carried, carryWhy, em };
  }

  /* STOP 2 · SITE POINT AND NEAREST MAPPED NODE */
  const ns = M('ns'), pv9 = M('pv9'), geo9 = M('geo9');
  if (!ns || !geo9 || pv9 == null) R.s2 = { empty: !ns ? why('ns') : !geo9 ? why('geo9') : why('pv9') };
  else {
    const chk = verifyV9(pv9);
    if (!chk.ok) R.s2 = { empty: `the fixture could not be verified against the served proof: the line "${chk.missing}" was not found in ${SRC.pv9.path}` };
    else {
      const idx = ns.index(NODES);
      const best = idx.nearest(S.lon, S.lat, { minimumKv: S.minKv });
      const list = idx.nearest(S.lon, S.lat, { minimumKv: S.minKv, limit: NODES.length });
      R.s2 = { idx, best, list, chk, radius: geo9.EARTH_RADIUS_KM };
    }
  }
  const node = R.s2 && R.s2.best ? R.s2.best.point : null;
  if (node && S.kvFollow) S.kv = Math.max(...node.voltages_kv);

  /* STOP 3 · ROUTE LENGTH */
  const gc = M('gc'), ce = M('ce');
  R.wires.loc = connect({
    id: 'loc', from: 'stop 2 · nearest().point.location', to: 'stop 3 · distanceKm(lon1, lat1, lon2, lat2)',
    q: node ? { value: node.location.lon, nums: [node.location.lon, node.location.lat], unit: 'degrees (lon, lat)', meaning: 'mapped node location, GeoJSON order' } : null,
    emptyWhy: R.s2 && R.s2.empty ? R.s2.empty : 'no mapped node was returned at stop 2',
    accepts: { unit: 'degrees (lon, lat)', meanings: ['mapped node location, GeoJSON order'], okWhy: `location.lon and location.lat are passed as lon2, lat2, in the (lon, lat) order distanceKm documents.` }
  });
  if (R.wires.loc.q && !R.wires.loc.q.injected) R.wires.loc.q.show = `lon ${nf(node.location.lon, 7)}°, lat ${nf(node.location.lat, 7)}°`;
  if (!node) R.s3 = { empty: R.wires.loc.reason };
  else if (R.wires.loc.state !== 'ACCEPTED') R.s3 = { empty: `the location wire is ${R.wires.loc.state}: ${R.wires.loc.reason}` };
  else if (!geo9 || !gc || !ce) R.s3 = { empty: !geo9 ? why('geo9') : !gc ? why('gc') : why('ce') };
  else {
    const straight = geo9.distanceKm(S.lon, S.lat, node.location.lon, node.location.lat);
    const atlas = gc.haversine(S.lon, S.lat, node.location.lon, node.location.lat);
    const uk = gc.haversineUK(S.lon, S.lat, node.location.lon, node.location.lat);
    const corridor = ce.forCable(straight);
    R.s3 = { straight, atlas, uk, corridor, ce, gc, geo9, agrees: straight === R.s2.best.km };
  }

  /* STOP 4 · FEEDER PHYSICS */
  const pf = M('pf'), cfp = M('cfp'), vd = M('vd');
  R.wires.load = connect({
    id: 'load', from: 'stop 1 · fleetDemand()', to: 'stop 4 · power-factor apparentPowerKva({ kw })',
    q: R.s1 && R.s1.carried, emptyWhy: R.s1 ? (R.s1.empty || R.s1.carryWhy) : 'stop 1 has not run',
    accepts: { unit: 'kW', meanings: ['after_diversity'], why: 'This wire asks what the load contributes to a network peak: electricity drawn, after diversity. A nameplate sum is the module\'s stress test and a thermal output is heat, not electricity; neither is fed to the feeder, and neither is ever added to the after-diversity figure.', okWhy: 'kW of electricity drawn after diversity becomes the  … [line shortened here: 466 characters; full line on GitHub]
  });
  const declared = node ? node.voltages_kv.includes(S.kv) : false;
  R.wires.kv = connect({
    id: 'kv', from: 'stop 2 · nearest().point.voltages_kv', to: 'stop 4 · currentFromMvaAtKv({ kv })',
    q: node && S.kv != null ? { value: S.kv, unit: 'kV', meaning: declared ? 'voltage declared by the node' : 'voltage not declared by the node', basis: 'line-to-line' } : null,
    emptyWhy: 'no mapped node was returned at stop 2',
    accepts: {
      unit: 'kV', meanings: ['voltage declared by the node'], basis: BASIS_OF_PHASES[S.phases],
      basisWhy: `${NO_LN}. phases "${S.phases}" takes a ${BASIS_OF_PHASES[S.phases]} voltage (current-from-power.js: three-phase is line-to-line, single-phase is line-to-neutral). No line-to-neutral voltage is inferred and no sqrt(3) is inserted, so nothing crosses this wire; the joined path stays three-phase.`,
      why: node ? `The node declares ${node.voltages_kv.join(', ')} kV. No transformer is modelled in this chain, so a feeder at another voltage is not joined to that busbar.` : '',
      okWhy: `the feeder is asked at a voltage the node declares, basis line-to-line, which is the voltage currentFromMvaAtKv takes for phases "three".`
    }
  });
  const corrQ = R.s3 && !R.s3.empty && R.s3.corridor && R.s3.corridor.km != null ? { value: R.s3.corridor.km, unit: 'km', meaning: 'cable corridor estimate' } : null;
  R.wires.len = connect({
    id: 'len', from: 'stop 3 · forCable(km).km', to: 'stop 4 · voltageDropVolts({ lengthM })',
    q: corrQ,
    emptyWhy: R.s3 ? (R.s3.empty || (R.s3.corridor == null ? 'forCable returned null: no finite distance above zero' : `forCable withheld the estimate: "${R.s3.corridor.withheld}"`)) : 'stop 3 has not run',
    accepts: { unit: 'm', meanings: ['cable corridor estimate'], okWhy: '' }
  });
  if (!pf || !cfp || !vd) R.s4 = { empty: !pf ? why('pf') : !cfp ? why('cfp') : why('vd') };
  else {
    const s4 = { pf, cfp, vd };
    const kw = R.wires.load.out;
    s4.S = kw ? attempt(() => pf.apparentPowerKva({ kw: kw.value, powerFactor: S.pf })) : { empty: `the load wire is ${R.wires.load.state}: ${R.wires.load.reason}` };
    s4.Q = kw ? attempt(() => pf.reactivePowerKvar({ kw: kw.value, powerFactor: S.pf })) : { empty: s4.S.empty };
    R.wires.mva = connect({
      id: 'mva', from: 'stop 4 · apparentPowerKva().value', to: 'stop 4 · currentFromMvaAtKv({ mva })',
      q: s4.S.ok ? { value: s4.S.ok.value, unit: s4.S.ok.unit, meaning: 'apparent power' } : null,
      emptyWhy: s4.S.err ? `apparentPowerKva refused: ${s4.S.err}` : s4.S.empty,
      accepts: { unit: 'MVA', meanings: ['apparent power'] }
    });
    const kvIn = R.wires.kv.out;
    s4.I = R.wires.mva.out && kvIn ? attempt(() => cfp.currentFromMvaAtKv({ mva: R.wires.mva.out.value, kv: kvIn.value, phases: S.phases }))
      : { empty: !R.wires.mva.out ? `the apparent-power wire is ${R.wires.mva.state}: ${R.wires.mva.reason}` : `the voltage wire is ${R.wires.kv.state}: ${R.wires.kv.reason}` };
    R.wires.amps = connect({
      id: 'amps', from: 'stop 4 · currentFromMvaAtKv().value', to: 'stop 4 · voltageDropVolts({ currentA }) and lossesWatts({ currentA })',
      q: s4.I.ok ? { value: s4.I.ok.value, unit: s4.I.ok.unit, meaning: 'current implied by a stated power' } : null,
      emptyWhy: s4.I.err ? `currentFromMvaAtKv refused: ${s4.I.err}` : s4.I.empty,
      accepts: { unit: 'A', meanings: ['current implied by a stated power'], okWhy: 'amps into amps. The module states this is not what a circuit carries: ' + cfp.NOT_COMPUTED.actualCurrent }
    });
    const A = R.wires.amps.out, Lm = R.wires.len.out;
    s4.D = A && Lm ? attempt(() => vd.voltageDropVolts({ currentA: A.value, lengthM: Lm.value, resistanceOhmPerKm: S.r, reactanceOhmPerKm: S.x, powerFactor: S.pf, phases: S.phases }))
      : { empty: !A ? `the current wire is ${R.wires.amps.state}: ${R.wires.amps.reason}` : `the length wire is ${R.wires.len.state}: ${R.wires.len.reason}` };
    s4.W = A && Lm ? attempt(() => vd.lossesWatts({ currentA: A.value, lengthM: Lm.value, resistanceOhmPerKm: S.r, phases: S.phases })) : { empty: s4.D.empty };
    R.wires.nom = connect({
      id: 'nom', from: 'stop 4 · the kV that crossed the voltage wire', to: 'stop 4 · dropPercent({ nominalVolts })',
      q: kvIn ? { value: kvIn.value, unit: 'kV', meaning: 'nominal voltage', basis: kvIn.basis } : null,
      emptyWhy: `the voltage wire is ${R.wires.kv.state}: ${R.wires.kv.reason}`,
      accepts: { unit: 'V', meanings: ['nominal voltage'], basis: 'line-to-line' }
    });
    s4.P = s4.D.ok && R.wires.nom.out ? attempt(() => vd.dropPercent({ dropVolts: s4.D.ok.value, nominalVolts: R.wires.nom.out.value }))
      : { empty: !s4.D.ok ? (s4.D.err ? `voltageDropVolts refused: ${s4.D.err}` : s4.D.empty) : `the nominal-voltage wire is ${R.wires.nom.state}: ${R.wires.nom.reason}` };
    R.s4 = s4;
  }

  /* STOP 5 · RATING LABELS */
  const topo = M('topo'), re = M('re'), pre = M('pre');
  if (!topo || !re || pre == null) R.s5 = { empty: !topo ? why('topo') : !re ? why('re') : why('pre') };
  else {
    const fx = attempt(() => fixtureFrom(pre, topo.ACCEPTS));
    if (fx.err) R.s5 = { empty: `the rating fixture could not be read from ${SRC.pre.path}: ${fx.err}` };
    else {
      const IDX = topo.index(fx.ok.product);
      if (!IDX) R.s5 = { empty: 'network-topology index() returned null for the proof fixture' };
      else {
        const byName = node ? re.at(IDX, node.name) : undefined;
        R.wires.name = gate({
          id: 'name', from: 'stop 2 · nearest().point.name', to: 'stop 5 · rating-envelope at(index, key)',
          q: node ? { value: node.name, unit: 'site key (text)', meaning: 'name of the nearest mapped node' } : null,
          state: !node ? 'EMPTY' : byName ? 'ACCEPTED' : 'REFUSED', direct: '',
          reason: !node ? 'no mapped node was returned at stop 2'
            : byName ? 'at() found a site of that name in the rating fixture.'
              : `at(index, ${JSON.stringify(node.name)}) returned ${String(byName)}. The node comes from the nearest-search proof fixture and the rating-envelope proof fixture has no site of that name or code, so the two are not joined. The labels below belong to a stand-in fixture site chosen by the reader, drawn on its own busbar.`
        });
        const kvW = R.wires.kv.out;
        R.wires.rkv = gate({
          id: 'rkv', from: 'stop 4 · the kV that crossed the voltage wire', to: 'stop 5 · at(index, key, { voltageKv })',
          q: kvW ? { value: kvW.value, unit: 'kV', meaning: 'nominal voltage', basis: kvW.basis } : null, direct: '',
          state: kvW ? 'ACCEPTED' : 'EMPTY',
          reason: kvW ? `kV (basis ${kvW.basis}) into voltageKv (kV): the module keeps only the stand-in site's nodes at that voltage.` : ''
        });
        const opts = R.wires.rkv.state === 'ACCEPTED' ? { voltageKv: R.wires.rkv.q.value } : undefined;
        const result = re.at(IDX, S.site, opts);
        if (R.wires.rkv.state === 'EMPTY') R.wires.rkv.reason = `the voltage wire is ${R.wires.kv.state}, so at() is called with no voltage and reads every voltage at the site; ${result ? result.scope : ''}`;
        else if (R.wires.rkv.unsound) R.wires.rkv.reason += ` at() is called with no voltage; ${result ? result.scope : ''}`;
        const amps = R.wires.amps && R.wires.amps.out;
        R.wires.head = gate({
          id: 'head', from: 'stop 4 · current (A)', to: 'stop 5 · circuit ratings (MVA)',
          q: amps ? { value: amps.value, unit: 'A', meaning: 'current implied by a stated power' } : null, direct: '',
          state: 'REFUSED',
          reason: `No comparison is made and no headroom is drawn. current-from-power.js: "${cfp ? cfp.NOT_A_HEADROOM : '(not loaded)'}" rating-envelope.js: "${re.NOT_A_CAPACITY}"`
        });
        R.s5 = { re, topo, IDX, fx: fx.ok, result, opts, sites: fx.ok.product.sites.map(s => s.code) };
      }
    }
  }
  return R;
}

/* ── the single-line diagram ──────────────────────────────────────────────── */
function drawSld(R) {
  const n = S.stop, p = [];
  const T = (x, y, t, cls = '', anchor = 'start') => p.push(`<text x="${x}" y="${y}" class="${cls}" text-anchor="${anchor}">${esc(t)}</text>`);
  const L = (x1, y1, x2, y2, stroke, w = 2, dash = '') => p.push(`<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${stroke}" stroke-width="${w}"${dash ? ` stroke-dasharray="${dash}"` : ''} stroke-linecap="round"/>`);
  const ghost = (x, y, t, anchor = 'start') => T(x, y, t, 'ph', anchor);
  const FX = 232, BUS = 104, LOADY = 212;
  const node = R.s2 && R.s2.best ? R.s2.best.point : null;
  const w = R.wires;

  /* stop 5: rating labels on a stand-in busbar of their own */
  if (n >= 5 && R.s5 && !R.s5.empty && R.s5.result) {
    const res = R.s5.result, cs = res.circuits;
    L(14, 48, 346, 48, '#ffffff', 4);
    T(14, 60, `${S.site} · ${R.s5.opts ? R.s5.opts.voltageKv + ' kV nodes' : 'every voltage'} · rating proof fixture · stand-in, not joined`, 'd');
    if (!cs.length) T(180, 30, `EMPTY · at() returned 0 circuits${R.s5.opts ? ' at ' + R.s5.opts.voltageKv + ' kV' : ''}`, 'rf', 'middle');
    const step = 332 / Math.max(cs.length, 1);
    cs.forEach((c, i) => {
      const x = 14 + step * (i + 0.5);
      const v = c.ratings_mva[S.season];
      const flagged = c.flags.some(f => f.season === S.season);
      const col = flagged || v == null ? GREY : colourOf(c.voltage_kv);
      L(x, 46, x, 24, col, 2.4, flagged || v == null ? '3 3' : '');
      T(x, 9, `→ ${c.to_node}`, 'w', 'middle');
      T(x, 19, v == null ? `${S.season}: not published` : flagged ? `${S.season} ${v} flagged` : `${S.season} ${v} MVA`, flagged || v == null ? 'd' : 'y', 'middle');
    });
    T(346, 71, 'per circuit · never summed · not a capacity', 'd', 'end');
    const nm = w.name;
    if (nm) { L(40, 76, 40, 98, GREY, 1.5, '3 3'); T(48, 90, nm.state === 'REFUSED' ? (nm.unsound ? 'REFUSED · carried key not sound' : 'REFUSED · at(node name) → null · not joined') : nm.state, 'rf'); }
  } else if (n >= 5) {
    T(180, 36, `EMPTY · ${(R.s5 && R.s5.empty) || 'stop 5 has not run'}`.slice(0, 70), 'd', 'middle');
  } else {
    L(14, 48, 346, 48, '#1b2030', 3, '4 4'); ghost(180, 36, 'stop 5 · rating labels at a busbar', 'middle');
  }

  /* stop 2: the nearest mapped node, as a busbar */
  if (n >= 2 && node) {
    L(14, BUS, 346, BUS, '#ffffff', 4);
    T(14, BUS + 13, node.name, 'w b');
    T(14, BUS + 24, `${node.voltages_kv.join(', ')} kV · nearest mapped · fixture`, 'd');
    T(14, BUS + 35, `site lon ${nf(S.lon, 5)}°, lat ${nf(S.lat, 5)}°`, 'd');
  } else if (n >= 2) {
    L(14, BUS, 346, BUS, GREY, 2, '3 3');
    T(14, BUS + 13, `EMPTY · ${(R.s2 && R.s2.empty) || `no mapped node at or above ${S.minKv} kV`}`.slice(0, 64), 'd');
  } else {
    L(14, BUS, 346, BUS, '#1b2030', 3, '4 4'); ghost(14, BUS + 13, 'stop 2 · nearest mapped node (busbar)');
  }

  /* stop 3: the cable route */