GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / iterations/28-nearest-search-trap

Envelope and 3 more files

A JavaScript module in the iterations folder of Galaxies Wafers that paints mods (`paintMods`) and questions (`paintQuestions`) and builds seasons (`buildSeasons`), covering transformers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/29-rating-envelope/.

625 lines of JavaScript and CSS and HTML from galaxies-wafers, in 4 files. Topic: Kuiper, cosmos and drawing engines. Section 1200 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. Trap render · galaxies-wafers / iterations/28-nearest-search-trap/trap.mjs lines 391–445
  2. Envelope render · galaxies-wafers / iterations/29-rating-envelope/envelope.css lines 1–88
  3. Envelope interaction · galaxies-wafers / iterations/29-rating-envelope/envelope.mjs lines 1–414
  4. Iterations — 29 Rating Envelope Page render · galaxies-wafers / iterations/29-rating-envelope/index.html lines 1–68

Trap

A JavaScript module in the iterations folder of Galaxies Wafers that paints mods, builds steps and renders steps, covering substations and 33kV, using haversine. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/.

rendergalaxies-wafers / iterations/28-nearest-search-trap/trap.mjs · lines 391–445 of 445 (continued from section 1199) · Entry point · pattern paintKey (shared by 2 files)

What it does
It draws substations and 33kV. Defines 43 functions or classes, including near, $, el, f, paintMods. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (voltage levels 33kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: substations, 33kV.
Inputs & outputs
Out: canvas drawing. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Iterations — 28 Nearest Search Trap Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/.
What it achieves
It paints mods (`paintMods`), builds steps (`buildSteps`) and renders steps (`renderSteps`). The Nearest-Search Trap — the ring-search bug class from `proofs/v9-engine.proof`.mjs, made visible. Its code works with 33 kV. It responds to pointerdown, pointermove and pointerup events.
Why it matters
Loaded by the 28 Nearest Search Trap page at https://ventusltd.github.io/galaxies-wafers/iterations/28-nearest-search-trap/.
Application
galaxies-wafers · iterations/28-nearest-search-trap · JavaScript module
Uses
none found
Used by
loaded by Iterations — 28 Nearest Search Trap Page (script src)
Produces
near, $, el, f, paintMods, load, inBox, searchA, searchB, buildSteps, kmOf, renderSteps
Defines here
play, len, tick, stepOnce, start, moveTo, end
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/28-nearest-search-trap/trap.mjs:391-445 · blob be5297c56db4a51c203a0b496f9b8701292d1226 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
function play(which) {
  stopRun(); S.run = which; S.step = 0; renderPanels(); draw(); publish();
  const len = () => (which === 'a' ? stepsA : stepsB).length;
  const tick = () => {
    if (S.step < len() - 1) { S.step++; renderPanels(); draw(); publish(); S.timer = setTimeout(tick, 750); }
    else S.timer = 0;
  };
  S.timer = setTimeout(tick, 750);
}
function stepOnce() {
  stopRun();
  if (!S.run) { S.run = 'a'; S.step = 0; }
  else {
    const len = (S.run === 'a' ? stepsA : stepsB).length;
    if (S.step < len - 1) S.step++;
    else if (S.run === 'a') { S.run = 'b'; S.step = 0; }
    else { S.run = null; S.step = -1; }
  }
  renderPanels(); draw(); publish();
}

function start() {
  fullIdx = ns.index(NODES);
  window.__trap.located = fullIdx.located;
  paintKey(); notes();
  $('mdR').textContent = String(geo.EARTH_RADIUS_KM);
  buildSteps(); renderPanels(); renderGate(); runGrid(); resize(); publish();
  $('runA').onclick = () => play('a');
  $('runB').onclick = () => play('b');
  $('step').onclick = stepOnce;
  $('reset').onclick = () => { stopRun(); S.run = null; S.step = -1; S.lon = QUERY[0]; S.lat = QUERY[1]; refresh(); };
  $('gridBtn').onclick = () => { S.showGrid = !S.showGrid; $('gridBtn').setAttribute('aria-pressed', String(S.showGrid)); draw(); };

  let dragging = false, raf = 0, pending = null;
  window.__trap.moves = 0; window.__trap.drags = 0;
  const moveTo = e => {
    const r = cv.getBoundingClientRect();
    let [lon, lat] = unpx(e.clientX - r.left, e.clientY - r.top);
    pending = [Math.min(GRID.lonMax, Math.max(GRID.lonMin, lon)), Math.min(GRID.latMax, Math.max(GRID.latMin, lat))];
    if (!raf) raf = requestAnimationFrame(() => { raf = 0; [S.lon, S.lat] = pending; window.__trap.moves++; refresh(); });
  };
  cv.addEventListener('pointerdown', e => {
    dragging = true; stopRun(); S.run = null; S.step = -1;
    try { cv.setPointerCapture(e.pointerId); } catch (_) { /* capture is a convenience */ }
    moveTo(e); e.preventDefault();
  });
  cv.addEventListener('pointermove', e => { if (dragging) { moveTo(e); e.preventDefault(); } });
  const end = () => { if (dragging) window.__trap.drags++; dragging = false; };
  cv.addEventListener('pointerup', end); cv.addEventListener('pointercancel', end);
  window.__trap.ready = true;
}

window.addEventListener('resize', resize);
resize();
load();

Envelope

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

rendergalaxies-wafers / iterations/29-rating-envelope/envelope.css · lines 1–88 of 88 · Entry point

What it does
Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Iterations — 29 Rating Envelope Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/29-rating-envelope/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/29-rating-envelope/.
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 29 Rating Envelope page at https://ventusltd.github.io/galaxies-wafers/iterations/29-rating-envelope/.
Application
galaxies-wafers · iterations/29-rating-envelope · style sheet
Uses
none found
Used by
loaded by Iterations — 29 Rating Envelope 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/29-rating-envelope/envelope.css:1-88 · blob 6b083f89800de6dc91eb01d5069a22bb3cafcaaf · 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}
.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;color:var(--ink);font-size:11.5px}
.questions code,.machine code{color:var(--beam)}
.machine{border-left:3px solid var(--beam);padding:.35rem .6rem;background:#07080c;color:var(--ink)}
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) + .8rem) 1rem calc(env(safe-area-inset-bottom,0px) + 11rem)}
main{max-width:72rem;margin:0 auto}
h1{font-size:13px;letter-spacing:.16em;font-weight:600;margin:0 0 .3rem}
h2{font-size:11px;letter-spacing:.14em;font-weight:400;color:var(--dim);margin:1.1rem 0 .4rem}
.dim{color:var(--dim)} .small{font-size:11.5px}
a{color:var(--beam)}
.mods{margin:.5rem 0 0;display:flex;flex-wrap:wrap;gap:.3rem .8rem;font-size:11.5px}
.mods span b{font-weight:600}
.boundary{border:1px solid var(--edge);border-left:3px solid #ffffff;background:#10131b;padding:.5rem .6rem;margin:.6rem 0;font-size:11.5px}
.note{border-left:2px solid var(--edge);padding-left:.6rem;color:var(--ink)}
.tag{font-size:10px;letter-spacing:.1em;color:var(--dim)}
.ctl{margin:.5rem 0}
.seg{display:flex;flex-wrap:wrap;gap:.35rem;margin-top:.3rem}
.seg button{font:inherit;color:var(--ink);background:#07080c;border:1px solid var(--edge);border-radius:.35rem;padding:.45rem .6rem;min-height:40px;min-width:3.2rem}
.seg button[aria-pressed=true]{border-color:#fff;box-shadow:inset 0 0 0 1px #fff}
.circuits{list-style:none;margin:0;padding:0;display:grid;gap:.55rem}
.circ{border:1px solid var(--edge);border-radius:.45rem;background:#07080c;padding:.45rem .55rem .55rem}
.circ.in{border-color:#3a4258;background:#0d1018}
.circ .top{display:flex;align-items:center;gap:.5rem}
.circ .name{font-weight:600;flex:1;min-width:0}
.grip{font:inherit;font-size:18px;line-height:1;color:var(--ink);background:#10131b;border:1px solid var(--edge);border-radius:.35rem;
  min-width:44px;min-height:44px;touch-action:none;cursor:grab;user-select:none;-webkit-user-select:none}
.act{font:inherit;color:var(--beam);background:none;border:1px solid var(--edge);border-radius:.35rem;min-height:44px;padding:0 .6rem}
.wire{position:relative;height:26px;margin:.35rem 9px .1rem}
.wire .core{position:absolute;left:0;right:0;top:11px;height:4px;border-radius:2px;
  background:linear-gradient(90deg,var(--c1),var(--c2));box-shadow:0 0 6px var(--c1),0 0 10px var(--c2)}
.wire .halo{position:absolute;left:0;right:0;top:8px;height:10px;border-radius:5px;background:linear-gradient(90deg,var(--c1),var(--c2));opacity:.18}
.wire.ph .core{background:repeating-linear-gradient(90deg,var(--grey) 0 12px,transparent 12px 20px);box-shadow:none}
.wire.np .core{background:repeating-linear-gradient(90deg,var(--grey) 0 3px,transparent 3px 8px);box-shadow:none}
.wire.ph .halo,.wire.np .halo{display:none}
.wire .sub{position:absolute;top:6px;width:14px;height:14px;border-radius:50%;background:#fff;box-shadow:0 0 0 2px #07080c,0 0 8px #fff}
.wire .sub.a{left:-7px} .wire .sub.b{right:-7px}
.ends{display:flex;justify-content:space-between;gap:.5rem;font-size:11px}
.ends span:last-child{text-align:right}
.fields{display:flex;flex-wrap:wrap;gap:.3rem;margin-top:.35rem}
.f{border:1px solid var(--edge);border-radius:.3rem;padding:.15rem .4rem;font-size:11.5px;color:var(--dim)}
.f b{color:var(--ink);font-weight:600}
.f.on{border-color:#fff;color:var(--ink)} .f.on b{color:var(--lit)}
.f.ph{border-style:dashed;border-color:var(--grey)} .f.ph b{color:var(--grey);text-decoration:line-through}
.reason{margin-top:.35rem;font-size:11px;color:var(--ink);border-left:2px dashed var(--grey);padding-left:.5rem}
.reason i{color:var(--dim);font-style:normal}
.legend{margin-top:.5rem}
.sum{border:1px solid var(--edge);border-radius:.45rem;background:#10131b;padding:.55rem .65rem;margin:.6rem 0}
.sum .plain{font-size:14px;font-weight:600;color:#fff;margin:0 0 .35rem}
.sum q{display:block;color:var(--ink);quotes:none}
.sum .by{color:var(--dim);font-size:11px;margin-top:.2rem}
.empty b{letter-spacing:.08em}
.calls{display:grid;gap:.6rem}
.call{border:1px solid var(--edge);border-radius:.45rem;padding:.5rem .6rem;background:#07080c}
.call code{color:var(--beam)}
.call table{border-collapse:collapse;width:100%;font-size:11.5px;margin:.35rem 0}
.call th,.call td{border-bottom:1px solid var(--edge);padding:.25rem .3rem;text-align:left;vertical-align:top}
.call th{color:var(--dim);font-weight:400}
.call tr.on td{color:var(--lit)}
.call .v{margin:.3rem 0;font-size:11.5px}
.call .v i{font-style:normal;color:var(--dim)}
.scroll{overflow-x:auto}
pre{margin:.3rem 0 0;font-size:10.5px;white-space:pre;overflow-x:auto;max-height:22rem;background:#05060a;border:1px solid var(--edge);border-radius:.3rem;padding:.4rem}
details summary{cursor:pointer;color:var(--beam);min-height:36px;display:flex;align-items:center}
.tray{position:fixed;left:0;right:0;bottom:0;z-index:5;background:#0b0d12;border-top:1px solid #3a4258;
  padding:.5rem 1rem calc(env(safe-area-inset-bottom,0px) + .5rem);min-height:6.5rem}
.tray.over{border-top-color:#fff;background:#141824;box-shadow:0 -2px 16px rgba(255,255,255,.12)}
.trayhead{display:flex;gap:.6rem;align-items:baseline;max-width:72rem;margin:0 auto}
.trayhead a{margin-left:auto}
.chips{display:flex;flex-wrap:wrap;gap:.35rem;margin:.35rem auto 0;max-width:72rem;min-height:44px;border:1px dashed var(--edge);border-radius:.4rem;padding:.25rem}
.chip{display:flex;align-items:center;gap:.25rem;border:1px solid #3a4258;border-radius:.35rem;padding:0 0 0 .1rem;background:#07080c;font-size:11.5px}
.chip .grip{min-width:36px;min-height:40px;font-size:15px;border:none;background:none}
.chip .x{font:inherit;color:var(--beam);background:none;border:none;min-width:40px;min-height:40px}
.chips .hint{color:var(--dim);font-size:11.5px;align-self:center;padding:0 .3rem}
.ghost{position:fixed;z-index:9;pointer-events:none;border:1px solid #fff;border-radius:.35rem;background:#10131b;padding:.35rem .55rem;font-size:12px;transform:translate(-50%,-120%)}
footer{margin-top:1.4rem}
@media (min-width:900px){
  .cols{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:1.4rem;align-items:start}
}
.cols>section,.calls>*,.circuits>*,.sum,.call,details{min-width:0}
.call,.sum,.questions{overflow-wrap:anywhere}
.machine,.v,#provenance{overflow-wrap:anywhere}
.call table{overflow-wrap:normal}.call th,.call td{white-space:nowrap}

Envelope

A JavaScript module in the iterations folder of Galaxies Wafers that paints mods (`paintMods`) and questions (`paintQuestions`) and builds seasons (`buildSeasons`), covering transformers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/29-rating-envelope/.

interactiongalaxies-wafers / iterations/29-rating-envelope/envelope.mjs · lines 1–414 of 414 · Entry point · pattern fixtureFrom (shared by 2 files)

What it does
It draws transformers. Defines 25 functions or classes, including colourOf, $, el, paintMods, load. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain terms in the code: transformers.
Downstream impact
Used directly by 1 file: Iterations — 29 Rating Envelope Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/29-rating-envelope/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/29-rating-envelope/.
What it achieves
It paints mods (`paintMods`), paints questions (`paintQuestions`) and builds seasons (`buildSeasons`). Ratings That Do Not Add — `engine/rating-envelope.js`, called as it is. Its code works with 100 MVA. It responds to click, pointerdown and pointermove events.
Why it matters
Loaded by the 29 Rating Envelope page at https://ventusltd.github.io/galaxies-wafers/iterations/29-rating-envelope/.
Application
galaxies-wafers · iterations/29-rating-envelope · JavaScript module
Uses
none found
Used by
loaded by Iterations — 29 Rating Envelope Page (script src)
Produces
colourOf, $, el, paintMods, load, fixtureFrom, idOf, boot, paintQuestions, emptyAll, segment, buildSeasons
Defines here
colourOf, $, el, paintMods, load, fixtureFrom, idOf, boot, paintQuestions, emptyAll, segment, buildSeasons, buildVolts, nodeLine, buildCircuits, paintCard, toggle, paintTray, attachDrag, over, end, siteCodesOf, paintResult, callCard, line
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/29-rating-envelope/envelope.mjs:1-414 · blob 198c8e167a2c1368006c37bc4b9c4ad04c197987 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* Ratings That Do Not Add — engine/rating-envelope.js, called as it is.
   The circuits come from the fixture written in the module's own proof,
   read from the proof's served bytes at the pinned commit. The page never
   adds, averages or ranks a rating: every derived figure on screen is a
   field the module returned. */

const COMMIT = 'd9cd18b0e2034325814924e6e4a0e958014f2748';
const BASE = `https://cdn.jsdelivr.net/gh/Ventusltd/ventus-grid-engine@${COMMIT}/`;
const ENVELOPE = 'engine/rating-envelope.js';
const TOPOLOGY = 'engine/network-topology.js';
const PROOF = 'proofs/rating-envelope.proof.mjs';
const SOURCES = [ENVELOPE, TOPOLOGY, PROOF];

/* Lifted from the Grid Atlas v8 topology config (ukConfig, "Topology
   (GeoJSON)"): the voltage levels the Atlas draws and the colour of each.
   Substations are #ffffff. */
const ATLAS_VOLTAGES = [
  { kv: 400, color: '#0054ff' },
  { kv: 275, color: '#ff0000' },
  { kv: 220, color: '#ff9900' },
  { kv: 132, color: '#00cc00' },
  { kv: 66,  color: '#b200ff' },
  { kv: 11,  color: '#ff00ff' }
];
const GREY = '#8a8f98';
const colourOf = kv => (ATLAS_VOLTAGES.find(v => v.kv === kv) || { color: GREY }).color;

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;
};

/* ── loading, Grid Atlas grammar ─────────────────────────────────────────── */
const state = Object.fromEntries(SOURCES.map(s => [s, 'WAIT']));
function paintMods() {
  const box = $('mods');
  box.textContent = '';
  for (const s of SOURCES) {
    const st = state[s];
    const sp = st.indexOf(' ');
    const span = el('span');
    span.dataset.src = s;
    span.append(el('b', null, sp < 0 ? st : st.slice(0, sp)), ` ${s}` + (sp < 0 ? '' : ' — ' + st.slice(sp + 1)));
    box.append(span);
  }
}
paintMods();
$('pin').textContent = `The module, its proof and network-topology.js are read from ventus-grid-engine at commit ${COMMIT.slice(0, 12)}.`;

/* Three sources, loaded together: never more than three requests at once. */
async function load(src, job) {
  state[src] = 'LOAD'; paintMods();
  try {
    const out = await job();
    state[src] = 'OK'; paintMods();
    return out;
  } catch (err) {
    state[src] = 'FAIL ' + (err && err.message ? err.message : String(err)); paintMods();
    return null;
  }
}

/* The proof declares its fixture as a JavaScript object literal named
   PRODUCT. It is read as text and converted to JSON without evaluating
   any code; the one identifier in it, ACCEPTS, is the value
   network-topology.js exports under that name. */
function fixtureFrom(text, accepts) {
  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, '');
  if (/\bACCEPTS\b/.test(src)) {
    if (typeof accepts !== 'string') throw new Error('the fixture names ACCEPTS but network-topology.js did not load');
    src = src.replace(/\bACCEPTS\b/g, JSON.stringify(accepts));
  }
  src = src.replace(/'([^'\\\n]*)'/g, (_, s) => JSON.stringify(s))
    .replace(/([{,]\s*)([A-Za-z_]\w*)\s*:/g, '$1"$2":')
    .replace(/,(\s*[}\]])/g, '$1');
  return { product: JSON.parse(src), firstLine: start + 1, lastLine: end + 1 };
}

const S = { season: null, voltageKv: null, corridor: [] };
let ENV = null, TOPO = null, FIX = null, IDX = null, GRAPH = null;
const cards = new Map();     // circuit id -> card parts
const flagsById = new Map(); // circuit id -> what at() reported for it

const idOf = rec => [rec.node_1, rec.node_2].sort().join('|');

async function boot() {
  const [env, topo, proofText] = await Promise.all([
    load(ENVELOPE, () => import(BASE + ENVELOPE)),
    load(TOPOLOGY, () => import(BASE + TOPOLOGY)),
    load(PROOF, async () => {
      const r = await fetch(BASE + PROOF);
      if (!r.ok) throw new Error('HTTP ' + r.status);
      return r.text();
    })
  ]);
  ENV = env; TOPO = topo;
  if (proofText != null) {
    try { FIX = fixtureFrom(proofText, topo && topo.ACCEPTS); }
    catch (err) { state[PROOF] = 'FAIL fixture could not be read: ' + err.message; paintMods(); }
  }
  if (!ENV || !TOPO || !FIX) return emptyAll();
  IDX = TOPO.index(FIX.product);
  if (!IDX) { state[TOPOLOGY] = 'FAIL index() returned null for the fixture'; paintMods(); return emptyAll(); }
  GRAPH = IDX.graph();

  $('provenance').textContent = `Scenario input: the PRODUCT records at ${PROOF} lines ${FIX.firstLine}–${FIX.lastLine}, ventus-grid-engine commit ${COMMIT.slice(0, 12)}. Test records written for the proof, not real network data.`;
  $('notcap').textContent = ENV.NOT_A_CAPACITY;

  /* Flags and unpublished seasons, exactly as at() reports them, collected
     by calling at() once for every site in the fixture. */
  for (const site of FIX.product.sites || []) {
    const r = ENV.at(IDX, site.code);
    if (!r) continue;
    for (const c of r.circuits) {
      const id = [c.from_node, c.to_node].sort().join('|');
      if (!flagsById.has(id)) flagsById.set(id, { flags: c.flags, seasons_not_published: c.seasons_not_published });
    }
  }

  paintQuestions();
  S.season = ENV.SEASONS[0];
  buildSeasons();
  buildVolts();
  buildCircuits();
  paintTray();
  paintResult();
  document.documentElement.dataset.ready = '1';
}

/* Questions panel and machine line: the cited text is in index.html; the
   values below are read from the loaded module, not typed. */
function paintQuestions() {
  const never = String(ENV.NEVER_SUMMED).split('. ');
  $('q-never').textContent = never[never.length - 1];
  $('q-exports').textContent = Object.keys(ENV).sort().join(', ');
  document.querySelectorAll('.pin12').forEach(n => { n.textContent = COMMIT.slice(0, 12); });
  $('machine').textContent = `Machine detail · inputs: index (a network-topology index whose graph().schema is "${ENV.requires}"), key (site code or exact site name), options.voltageKv (kV, optional); per circuit record ${ENV.SEASONS.map(s => s + '_mva').join(', ')} (MVA, seasonal thermal rating as published) · outputs (schema "${ENV.schema}"): circuits[].ratings_mva (MVA per season), circuits[].f  … [line shortened here: 1,360 characters; full line on GitHub]
  try { if (window.matchMedia('(min-width: 900px)').matches) $('questions').open = true; } catch (_) { /* stays collapsed */ }
}

function emptyAll() {
  $('circuits').replaceChildren(el('li', 'empty', 'EMPTY — nothing is drawn: a source above did not load, and no circuit or rating is invented in its place.'));
  $('sum').replaceChildren(el('div', 'empty', 'EMPTY — the module is not available to call.'));
  document.documentElement.dataset.ready = 'empty';
}

/* ── controls ────────────────────────────────────────────────────────────── */
function segment(box, opts, isOn, onPick) {
  box.textContent = '';
  const buttons = opts.map(o => {
    const b = el('button', null, o.label);
    b.type = 'button';
    b.dataset.v = o.label;
    b.addEventListener('click', () => {
      onPick(o);
      buttons.forEach((bb, j) => bb.setAttribute('aria-pressed', String(isOn(opts[j]))));
    });
    b.setAttribute('aria-pressed', String(isOn(o)));
    box.append(b);
    return b;
  });
}

function buildSeasons() {
  segment($('seasons'), ENV.SEASONS.map(s => ({ label: s, s })), o => o.s === S.season,
    o => { S.season = o.s; for (const id of cards.keys()) paintCard(id); paintResult(); });
}

function buildVolts() {
  const kvs = [...new Set((FIX.product.nodes || []).map(n => GRAPH.nodeVoltageKv(n.node)).filter(Number.isFinite))].sort((a, b) => b - a);
  const opts = [{ label: 'not passed', kv: null }, ...kvs.map(kv => ({ label: kv + ' kV', kv }))];
  segment($('volts'), opts, o => o.kv === S.voltageKv, o => { S.voltageKv = o.kv; paintResult(); });
}

/* ── circuits ────────────────────────────────────────────────────────────── */
function nodeLine(name) {
  const kv = GRAPH.nodeVoltageKv(name);
  const code = GRAPH.nodeSiteCode(name);
  const site = code ? GRAPH.siteByCode(code) : null;
  return `${name} · ${kv == null ? 'voltage undeclared' : kv + ' kV'}${site && site.name ? ' · ' + site.name : ''}`;
}

function buildCircuits() {
  const ul = $('circuits');
  ul.textContent = '';
  for (const rec of FIX.product.circuits || []) {
    const id = idOf(rec);
    const li = el('li', 'circ');
    li.dataset.id = id;
    const top = el('div', 'top');
    const grip = el('button', 'grip', '⠿');
    grip.type = 'button';
    grip.setAttribute('aria-label', `drag circuit ${rec.node_1} to ${rec.node_2} into the corridor`);
    const meta = [rec.circuit_type, ...['ohl_km', 'cable_km'].filter(k => Number.isFinite(rec[k])).map(k => `${k} ${rec[k]}`)].filter(Boolean).join(' · ');
    const name = el('span', 'name', `${rec.node_1} — ${rec.node_2}`);
    const act = el('button', 'act', '+ corridor');
    act.type = 'button';
    act.addEventListener('click', () => toggle(id));
    top.append(grip, name, act);

    const wire = el('div', 'wire');
    wire.style.setProperty('--c1', colourOf(GRAPH.nodeVoltageKv(rec.node_1)));
    wire.style.setProperty('--c2', colourOf(GRAPH.nodeVoltageKv(rec.node_2)));
    wire.append(el('div', 'halo'), el('div', 'core'), el('div', 'sub a'), el('div', 'sub b'));

    const ends = el('div', 'ends dim');
    ends.append(el('span', null, nodeLine(rec.node_1)), el('span', null, nodeLine(rec.node_2)));
    const metaLine = el('div', 'dim small', meta);
    const fields = el('div', 'fields');
    const reason = el('div', 'reasons');
    li.append(top, wire, ends, metaLine, fields, reason);
    ul.append(li);
    cards.set(id, { li, rec, wire, fields, reason, act });
    attachDrag(grip, id, `${rec.node_1} — ${rec.node_2}`, false);
    paintCard(id);
  }
  $('legend').textContent = `Drawn: ${cards.size} circuit records from the fixture. Dashed grey: the shown season's value is flagged by the module as a placeholder. Dotted grey: the record publishes no value for that season. The fixture's ${(FIX.product.transformers || []).length} transformer record(s) are not drawn: at() reads circuits only.`;
}

function paintCard(id) {
  const c = cards.get(id);
  const known = flagsById.has(id);
  const info = flagsById.get(id) || { flags: [], seasons_not_published: [] };
  const flagged = new Map(info.flags.map(f => [f.season, f]));
  const season = S.season;
  const notPublished = !known || info.seasons_not_published.includes(season);
  c.wire.classList.toggle('ph', flagged.has(season));
  c.wire.classList.toggle('np', !flagged.has(season) && notPublished);
  const inside = S.corridor.includes(id);
  c.li.classList.toggle('in', inside);
  c.act.textContent = inside ? '− corridor' : '+ corridor';

  c.fields.textContent = '';
  for (const key of Object.keys(c.rec).filter(k => /_mva$/.test(k))) {
    const f = el('span', 'f');
    const s = ENV.SEASONS.find(x => key.startsWith(x + '_'));
    if (s === season) f.classList.add('on');
    if (s && flagged.has(s)) f.classList.add('ph');
    f.append(key + ' ', el('b', null, String(c.rec[key])));
    c.fields.append(f);
  }
  c.reason.textContent = '';
  for (const f of info.flags) {
    const r = el('div', 'reason');
    r.append(el('i', null, `module flag · ${f.season} · ${f.value} · reason: `), f.reason);
    c.reason.append(r);
  }
  if (!known) {
    const r = el('div', 'reason');
    r.append(el('i', null, 'EMPTY · '), 'at() returned no row for this circuit at any fixture site, so no flag can be read for it.');
    c.reason.append(r);
  }
}

/* ── corridor ────────────────────────────────────────────────────────────── */
function toggle(id, want) {
  const has = S.corridor.includes(id);
  const add = want == null ? !has : want;
  if (add === has) return;
  S.corridor = add ? [...S.corridor, id] : S.corridor.filter(x => x !== id);
  paintCard(id);
  paintTray();
  paintResult();
}

function paintTray() {
  const box = $('traychips');
  box.textContent = '';
  const n = S.corridor.length;
  $('traycount').textContent = `${n} circuit${n === 1 ? '' : 's'} · total: none offered by the module`;
  if (!n) box.append(el('span', 'hint', 'drop circuits here (drag by ⠿, or tap + corridor)'));
  for (const id of S.corridor) {
    const { rec } = cards.get(id);
    const chip = el('span', 'chip');
    chip.dataset.id = id;
    const grip = el('button', 'grip', '⠿');
    grip.type = 'button';
    grip.setAttribute('aria-label', 'drag out of the corridor');
    const x = el('button', 'x', '×');
    x.type = 'button';
    x.setAttribute('aria-label', `remove ${rec.node_1} to ${rec.node_2}`);
    x.addEventListener('click', () => toggle(id, false));
    chip.append(grip, `${rec.node_1}—${rec.node_2}`, x);
    box.append(chip);
    attachDrag(grip, id, `${rec.node_1} — ${rec.node_2}`, true);
  }
}

function attachDrag(grip, id, label, fromTray) {
  let ghost = null;
  const tray = $('tray');
  const over = e => {
    const r = tray.getBoundingClientRect();
    return e.clientY >= r.top && e.clientY <= r.bottom && e.clientX >= r.left && e.clientX <= r.right;
  };
  grip.addEventListener('pointerdown', e => {
    e.preventDefault();
    try { grip.setPointerCapture(e.pointerId); } catch (_) { /* capture is optional */ }
    ghost = el('div', 'ghost', label);
    ghost.style.left = e.clientX + 'px'; ghost.style.top = e.clientY + 'px';
    document.body.append(ghost);
  });
  grip.addEventListener('pointermove', e => {
    if (!ghost) return;
    ghost.style.left = e.clientX + 'px'; ghost.style.top = e.clientY + 'px';
    tray.classList.toggle('over', over(e));
  });
  const end = (e, cancelled) => {
    if (!ghost) return;
    ghost.remove(); ghost = null;
    tray.classList.remove('over');
    if (cancelled) return;
    if (over(e)) toggle(id, true);
    else if (fromTray) toggle(id, false);
  };
  grip.addEventListener('pointerup', e => end(e, false));
  grip.addEventListener('pointercancel', e => end(e, true));
}

/* ── the module's answer ─────────────────────────────────────────────────── */
function siteCodesOf(id) {
  const { rec } = cards.get(id);
  return new Set([rec.node_1, rec.node_2].map(n => GRAPH.nodeSiteCode(n)).filter(Boolean));
}

function paintResult() {
  const sum = $('sum');
  const calls = $('calls');
  sum.textContent = ''; calls.textContent = '';

  /* What the module exports, read from the live namespace. */
  const exportsList = Object.keys(ENV).sort();
  const fns = exportsList.filter(k => typeof ENV[k] === 'function');
  const adders = fns.filter(k => /sum|total|add|aggregate/i.test(k));

  if (adders.length) {
    sum.append(el('p', 'plain', `The module exports a function named ${adders.join(', ')}; this page was not written to call it.`));
  } else {
    sum.append(el('p', 'plain', 'This module offers no way to add these ratings.'));
    const parts = String(ENV.NEVER_SUMMED).split('. ');
    sum.append(el('q', null, parts[parts.length - 1]));
    sum.append(el('div', 'by', 'from NEVER_SUMMED, exported by ' + ENVELOPE));
  }
  sum.append(el('div', 'by', `Exports read from the live module (${exportsList.length}): ${exportsList.map(k => k + (typeof ENV[k] === 'function' ? `(${ENV[k].length} parameters)` : '')).join(', ')}. Functions: ${fns.length} (${fns.join(', ')}).`));

  if (!S.corridor.length) {
    calls.append(el('div', 'call empty', 'EMPTY — no circuit is in the corridor yet. Drag a circuit by ⠿ into the corridor bar, or tap + corridor.'));
    return;
  }
  let shared = null;
  for (const id of S.corridor) {
    const codes = siteCodesOf(id);
    shared = shared == null ? codes : new Set([...shared].filter(c => codes.has(c)));
  }
  if (!shared.size) {
    calls.append(el('div', 'call empty', `EMPTY — the circuits in the corridor share no site. The module's function${fns.length === 1 ? '' : 's'} ${fns.map(f => f + '(index, key, options)').join(', ')} read${fns.length === 1 ? 's' : ''} the circuits landing at one site; there is no call that takes a chosen set of circuits, so nothing is called.`));
    return;
  }
  for (const code of [...shared].sort()) calls.append(callCard(code));
}

function callCard(code) {
  const box = el('div', 'call');
  const opts = S.voltageKv == null ? undefined : { voltageKv: S.voltageKv };
  const callText = `at(index, ${JSON.stringify(code)}${opts ? ', ' + JSON.stringify(opts) : ''})`;
  box.append(el('div', 'small', `Every circuit in the corridor lands at site ${code}. The page calls`), el('code', null, callText));
  let result;
  try { result = ENV.at(IDX, code, opts); }
  catch (err) { box.append(el('div', 'v', 'FAIL — at() threw: ' + (err && err.message))); return box; }
  if (result === null) { box.append(el('div', 'v', 'at() returned: null')); return box; }

  const chosen = new Set(S.corridor);
  const returned = result.circuits.map(c => [c.from_node, c.to_node].sort().join('|'));
  const extra = returned.filter(id => !chosen.has(id)).length;
  const missing = S.corridor.filter(id => !returned.includes(id)).length;
  const rows = result.circuits.length;
  box.append(el('div', 'v', `at() returned ${rows} circuit row${rows === 1 ? '' : 's'}. It reads every circuit at the site${opts ? ' on that voltage' : ''}, not the corridor you built: ${extra} returned row${extra === 1 ? ' is' : 's are'} not in your corridor, ${missing} of your corridor ${missing === 1 ? 'is' : 'are'} not returned.`));

  const wrap = el('div', 'scroll');
  const t = el('table');
  const keys = [...new Set(Object.values(result.by_season).flatMap(o => Object.keys(o)))];
  const head = el('tr');
  head.append(el('th', null, 'by_season'), ...keys.map(k => el('th', null, k)));
  t.append(head);
  for (const s of ENV.SEASONS) {
    const tr = el('tr', s === S.season ? 'on' : null);
    const o = result.by_season[s] || {};
    tr.append(el('td', null, s), ...keys.map(k => el('td', null, k in o ? String(o[k]) : '—')));
    t.append(tr);
  }
  wrap.append(t);
  box.append(wrap);

  const line = (k, v) => { const d = el('div', 'v'); d.append(el('i', null, k + ': '), String(v)); return d; };
  box.append(line('scope', result.scope), line('counts', JSON.stringify(result.counts)),
    line('never_summed', result.never_summed), line('not_a_capacity', result.not_a_capacity));
  const det = el('details');
  det.append(el('summary', null, 'the whole returned object, verbatim'), el('pre', null, JSON.stringify(result, null, 2)));
  box.append(det);
  return box;
}

boot();

Iterations — 29 Rating Envelope Page

A web page in Galaxies Wafers covering substations. Published at https://ventusltd.github.io/galaxies-wafers/iterations/29-rating-envelope/.

rendergalaxies-wafers / iterations/29-rating-envelope/index.html · lines 1–68 of 68 · Entry point

What it does
It draws substations. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain terms in the code: substations, 400kV, 275kV, 220kV, 132kV, 66kV. README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
Out: web page. Voltage levels named: 400kV, 275kV, 220kV, 132kV, 66kV, 11kV.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/29-rating-envelope/.
What it achieves
Ratings That Do Not Add. Its code works with 100 kW, 11 kV and 132 kV.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
galaxies-wafers · iterations/29-rating-envelope · page
Uses
Envelope (stylesheet), Galaxies Wafers — Iterations Page (link), Envelope (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/29-rating-envelope/index.html:1-68 · blob 99d4b3449229f12c4b2a71064df6ba83d5534256 · 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>Ratings That Do Not Add</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="envelope.css">
</head>
<body>
<main>
  <header>
    <h1>RATINGS THAT DO NOT ADD</h1>
    <div class="dim">Each lit line is one circuit with the seasonal ratings its record publishes. Drag circuits into the corridor below to try to make a total. When the chosen circuits share a site, the page calls the rating-envelope module's at() for that site on the whole fixture index and shows what it returns, in its own words; the page then says which returned circuits were and were not chose  … [line shortened here: 441 characters; full line on GitHub]
    <div id="mods" class="mods" aria-live="polite"></div>
  </header>

  <div class="cols">
    <section>
      <h2>CIRCUITS · <span id="fixlabel">fixture from the module's proof</span></h2>
      <div id="provenance" class="dim small"></div>
      <p id="notcap" class="note small"></p>
      <div class="ctl">
        <span class="tag">SEASON SHOWN</span>
        <div id="seasons" class="seg"></div>
      </div>
      <ul id="circuits" class="circuits"></ul>
      <div id="legend" class="dim small legend"></div>
    </section>

    <section id="read">
      <h2>WHAT THE MODULE RETURNS</h2>
      <p class="boundary">Illustrative physics drawn by a computer from published data. Not an engineering design or certified calculation. Any real design above 100 kW needs study and approval by a qualified chartered electrical engineer under the applicable standards.</p>
      <div class="ctl">
        <span class="tag">SCENARIO INPUT · options.voltageKv passed to at()</span>
        <div id="volts" class="seg"></div>
      </div>
      <div id="sum" class="sum"></div>
      <div id="calls" class="calls"></div>
      <details id="questions" class="questions">
        <summary>Questions</summary>
        <dl>
          <dt>1. How does this help draw a system or a single-line diagram?</dt>
          <dd>It feeds the <b>feeder (circuit) annotations</b> at a busbar, never a busbar figure. On a single-line diagram each circuit leaving a busbar carries its own rating label; <code>at()</code> supplies it per circuit as <code>circuits[].ratings_mva</code> (read from the record fields <code>winter_mva</code>, <code>spring_mva</code>, <code>summer_mva</code>, <code>autumn_mva</code>), with   … [line shortened here: 684 characters; full line on GitHub]
          <dt>2. What is this code used for?</dt>
          <dd>Module <code>engine/rating-envelope.js</code>, ventus-grid-engine commit <span class="pin12"></span>; exported function <code>at(index, key, options)</code> (source line 86) with exports <span id="q-exports"></span>. It was promoted from gridatlas <code>atlas/modules/202609012250-rating-envelope.js</code> (its header, lines 4–20). Caller in the estate, read from source: the gridatlas  … [line shortened here: 870 characters; full line on GitHub]
          <dt>3. Where does it lead next?</dt>
          <dd>To conductor current: <code>engine/current-from-power.js</code> <code>currentFromMvaAtKv({ mva, kv, phases })</code>, whose own comment (lines 131–133, same commit) says "This is the call a rating-envelope result feeds". No code at this commit wires the two together (searched by name), so the link is the comment's statement, not an established call.</dd>
        </dl>
      </details>
      <p id="machine" class="machine small"></p>
      <footer class="dim small">
        Line colours are the Grid Atlas v8 topology colours (repd_grid_atlasv8 layer config: 400kV, 275kV, 220kV, 132kV, 66kV, 11kV); each end of a line takes the colour of the voltage its node declares, and substations are white as the Atlas draws them. A node with no declared voltage, a season with no published value, and a value the module flags as a placeholder are drawn grey. Every line is dr  … [line shortened here: 452 characters; full line on GitHub]
        <span id="pin"></span>
        <a href="../">every version</a>
      </footer>
    </section>
  </div>
</main>

<div id="tray" class="tray" aria-label="Corridor: drop circuits here">
  <div class="trayhead"><b>CORRIDOR</b> <span id="traycount" class="dim"></span> <a href="#read" class="small">read the result</a></div>
  <div id="traychips" class="chips"></div>
</div>
<script type="module" src="envelope.mjs"></script>
</body>
</html>