GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / gridatlas / atlas/cartridges

Single-Line Diagram (SLD) Sandbox V9 8 (part 15)

A JavaScript file in the cartridges folder of GridAtlas that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Grid network and substations. Section 374 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. Single-Line Diagram (SLD) Sandbox V9 8 geodesy · gridatlas / atlas/cartridges/202611180026-sld-sandbox-v9-8.js lines 2622–3321

Single-Line Diagram (SLD) Sandbox V9 8

A JavaScript file in the cartridges folder of GridAtlas that maps connection points, GB transmission network, price decade rollup and grid substations, using haversine.

Set aside from the main view: 99% of its lines are the same as atlas/modules/202612020205-secondary-neon-engine.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Secondary Neon Engine; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9877 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612020205-secondary-neon-engine.js:1-9008 26e5045a356c11088820207d3cbe95eb4b89374f
  • sha256 d8b2e61b4b14f7af456a2c0c1721efc4d0bb2e9d43fbadc8cac6075b8465eccb
  • target sha256 b9e2b3ce36d3f46184c4a0f0416d70892feb49507d1c93833d3ab00a27c84263
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/cartridges/202611180026-sld-sandbox-v9-8.js · lines 2622–3321 of 9047 · version 2026-11-18 00:26 (continued from section 370) · Not reached from any entry point (candidate for review) · pattern isInterconnectorArrival (shared by 3 files)

What it does
It maps connection points, GB transmission network, price decade rollup and grid substations. Defines 276 functions or classes, including distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
Inputs & outputs
In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; GeoJSON file grid_substations.geojson; JSON file neso-connection-sites.lean.json; GeoJSON file interconnectors.geojson; browser storage (getItem); DuckDB queries. Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 110kV, 66kV.
What it achieves
It creates compute observer (`createComputeObserver`), describes compute receipt (`describeComputeReceipt`) and builds stats (`buildStats`). Receipt and distance owner: Ventusltd/ventus-grid-engine. Its code works with 400 kV, 132 kV and 33 kV. It responds to click, keydown and touchstart events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/cartridges · script
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver
Defines here
publishedUnits, published, publishedHtml, coarse, reflect, reflectFullscreen, topologyModule, ensureTopology, distanceModule, ownerModule, plannedModule, flowModule, flowModelFor, ratingModule, runGridAtPoint, show, topologyBlockHtml, fillTopologyBlocks, topologyInnerHtml, caveat, ratings, ownership, planned, injection
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-sld-sandbox-v9-8.js:2622-3321 · blob 4336ae8ea8d1eafcf57a97906bbb6c661f9c8318 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
       names. The sandbox asks; the substation cartridge answers from
       Ventusltd/data-grid-gb, which is ETYS restated. Absent is absent:
       no sentence at all rather than an empty one. */
    const networkName = currentDeclared?.kind !== 'circuit'
      ? (currentDeclared?.poc || currentNearest400?.name) : currentNearest400?.name;
    /* Tell it the voltage the connection is actually made at: the declared
       point of connection's class where there is one, otherwise the class
       of the substation being measured to. Without this the answer can
       only be a site-wide envelope. */
    const connectionKv = currentDeclared?.kind !== 'circuit'
      ? (currentDeclared?.kv || currentNearest400?.kv || null)
      : null;
    /* connection-points counts LANDINGS: a transformer's windings are both
       at the site, so Cowley's five read as ten and 484 of 525 sites were
       1.90x over. Only the node/branch model holds the pairs. */
    const publishedUnits = (() => {
      if (topology.state !== 'ready' || !topology.index) return null;
      try {
        const point = window.__GRIDATLAS_NETWORK__?.byName?.(networkName);
        if (!point?.site_code) return null;
        const facts = topology.index.at(point.site_code);
        if (!facts?.counts) return null;
        return { circuits: facts.counts.circuits,
          transformers: facts.counts.transformers };
      } catch (_) { return null; }
    })();
    const published = (() => {
      try {
        return window.__GRIDATLAS_NETWORK__?.summarise?.(
          networkName, { connectionKv, units: publishedUnits }) || null;
      } catch (_) { return null; }
    })();
    /* The envelope is built HERE and appended BELOW the measurement.
       ---------------------------------------------------------------------
       WHY THE ORDER CHANGED. Driven on a verified iPhone-class device
       (393x852, pointer:coarse, hover:none, 5 touch points), 101 MAP taps
       across all 25 technologies: the distance was on the page 99 times out
       of 99 and on the first screen zero times. Measured here, it landed at
       y=907 in an 852px viewport with about 270px of published-envelope
       detail above it. The envelope is neither deleted nor shortened; it
       moves below the answer it is context for. The measurement paragraph
       names the substation, so nothing above it is needed to read it. It is
       still built before the block is emitted, because link.network_published
       and the topology block both depend on it having been asked for. */
    const publishedHtml = (() => {
      if (!published) return '';
      link.network_published = { name: networkName, site: published.site_code };
      /* The scope label goes FIRST. A site-wide envelope printed under a
         400 kV declared connection reads as a 400 kV result unless the
         reader is told otherwise before the numbers, not after. */
      return `<div class="neon-hd">${escapeHtml(networkName)}`
        + (published.fault_scope === 'bus'
          ? `<span class="neon-beta" style="background:#12323a;color:#8fd8e0">`
            + `${published.fault_kv} kV bus</span>`
          : (published.site_wide
            ? `<span class="neon-beta" style="background:#3a3a2a;color:#d8c96a">Site-wide</span>`
            : ''))
        + `<span class="neon-beta">NESO published</span></div>`
        + `<p class="neon-caveat"><b>${escapeHtml(published.scope_label)}.</b></p>`
        + `<p class="neon-caveat">${escapeHtml(published.sentence)}.</p>`
        + `<p class="neon-caveat">${escapeHtml(published.metrics_not_interchangeable)} `
        + `${escapeHtml(published.attribution)}. `
        + `${escapeHtml(published.not_an_assessment)}</p>`;
    })();
    if (currentNearest400) {
      const n = currentNearest400;
      /* The measurement and everything that makes it honest are ONE element,
         which is why nearestScope(n) is inside the wrapper rather than
         appended after it. Whatever a layout does to this block - move it,
         dock it, put it in a sheet - the number cannot arrive without the
         word "straight", without the corridor estimate's own caveat, and
         without the sentence naming the sample the superlative searched. */
      out += `<div class="neon-answer">`
        + `<p class="neon-caveat"><b>Nearest 400 kV substation:</b> `
        + `${escapeHtml(n.name)} · ${n.km.toFixed(2)} km straight`
        + corridorBeside(n.km)
        + (n.works ? `. ${escapeHtml(n.works)}` : '')
        + (n.named
          ? ` (nearest named: ${escapeHtml(n.named.name)} · ${n.named.km.toFixed(2)} km`
            + (n.named.works ? `. ${escapeHtml(n.named.works)}` : '') + `)`
          : '')
        + `</p>`
        + nearestScope(n)
        + `</div>`;
    }
    out += publishedHtml;
    if (networkName) {
      out += topologyBlockHtml([{ name: networkName, kv: connectionKv }]);
    }
    out += corridorAction();
    return out;
  }

  /* ── the transmission network, on demand ─────────────────────────────
     Vikram: click anywhere and the neons should "look for cartridges and
     code". Until this generation the looking stopped at NESO's connection
     points - one row per site. The node/branch model behind them (ETYS
     Appendix B as Ventusltd/data-grid-gb's gb-transmission-network.v1) was
     indexed by the network-topology module, proven 47/47, and composed
     into nothing: the module was on disk and not in any served cartridge.
     The deep scan of 202609012230 listed it as alive; it was alive the way
     a book on a shelf is.

     The product is ten megabytes. It is NOT fetched at load: a phone on a
     hillside should not pay for it until a click asks a question it
     answers. Fetched once, indexed once by the module, every state on
     __GRIDATLAS_TOPOLOGY__ so the source registry can say whether this
     source answered, and the cards fill in when it arrives rather than
     waiting for it.

     The join from a mapped substation to a published site is BY NAME,
     through the connection-points cartridge's own join, and the block says
     which site it joined to - Codex's WBUR finding stands: exact text
     equality is not exact identity, so the reader is shown the identity. */
  /* Pinned; the table and the reasoning are in the pinned-products module. */
  const PINS = (window.__GRIDATLAS_MODULES__ || {}).pinnedProducts || null;
  const TOPOLOGY_ID = 'gb-transmission-network.v1';
  const TOPOLOGY_PRODUCT = PINS ? PINS.url(TOPOLOGY_ID) : null;
  const TOPOLOGY_BLOCK = 'gridatlas-topology';
  const topology = { state: 'idle', product: TOPOLOGY_PRODUCT, schema: null,
    schema_required: topologyModule()?.accepts || null,
    bytes: null, sites: null, index: null, error: null,
    started_at: null, ready_at: null, blocks_filled: 0 };
  window.__GRIDATLAS_TOPOLOGY__ = topology;

  /* Published so a reviewer can ask the page how many cards the traversal
     actually answered, and how many published branches it refused to walk.
     A refusal is a finding about the data, not a failure of the page. */
  const electrical = { answered: 0, refusals: 0 };
  window.__GRIDATLAS_ELECTRICAL__ = electrical;

  /* How many cards quoted a seasonal rating, and how many placeholder
     values the published record turned out to contain. */
  const rating = { answered: 0, flagged: 0 };
  window.__GRIDATLAS_RATINGS__ = rating;

  /* Published so a reviewer can ask the page whether any answer it gave
     failed its own conservation check. A solve that has not converged
     produces plausible-looking flows that are wrong, so the error is
     surfaced rather than trusted. */
  const powerflow = { answered: 0, refused: 0, worst_kirchhoff_error: 0 };
  window.__GRIDATLAS_POWERFLOW__ = powerflow;

  /* How many point queries the reader ran. A feature nobody can reach is
     indistinguishable from a feature that does not work, and this is the
     number that tells them apart. */
  const pointQuery = { answered: 0 };
  window.__GRIDATLAS_POINT_QUERY__ = pointQuery;

  /* How many cards reported published plans, and how many rows they came
     from. A count of zero where the product has 2,230 rows would mean the
     wiring is broken, not that nothing is planned. */
  const plannedState = { answered: 0, rows: 0 };
  window.__GRIDATLAS_PLANNED__ = plannedState;

  /* How many cards named an owner, and how many seams they found. */
  const ownerState = { answered: 0, seams: 0 };
  window.__GRIDATLAS_OWNERSHIP__ = ownerState;

  /* The layers dash collapses without entering fullscreen.
     ---------------------------------------------------------------------
     The dash is 816 px tall on a desktop and takes most of a phone, and
     the only way past it has been fullscreen - a different mode with a
     different layout, which is a large thing to ask of a reader who just
     wants to see the map. This collapses it in place and leaves a tab to
     bring it back.

     The choice is remembered per browser and every storage access is
     wrapped: a private window, cleared site data or a browser set to
     block storage all throw here, and a thrown error must not take the
     control with it. */
  (function dashCollapse() {
    const KEY = 'gridatlas.dash.collapsed';
    /* HIDE LAYERS collapsed `.dashboard`, which is the whole app: in the
       shipped shell it opens at index.html:22 and holds BOTH
       `.map-container` (line 36, containing #map) and `.scada-wrapper`
       (line 112, the layer keys and legend), so max-height:0 took the WebGL
       canvas down with the checkboxes - and the choice is remembered, so
       the reload a reader reaches for blanked the page again.

       It targets `.scada-wrapper` now, with NO fallback: the last fallback
       is what blanked the map. It also hides itself in fullscreen, because
       the keeper below MOVES the panel into the fullscreen element. */
    const dash = document.querySelector('.scada-wrapper');
    if (!dash) {
      /* `link` is declared further down this file and is in its temporal
         dead zone here, so the refusal is published on its own surface
         rather than through the failure ledger. */
      window.__GRIDATLAS_DASH__ = { installed: false, target: '.scada-wrapper',
        reason: 'no .scada-wrapper in this shell; the control was not installed '
          + 'rather than pointed at .dashboard, which contains the map' };
      return;
    }
    if (document.getElementById('gridatlas-dash-toggle')) return;

    const style = document.createElement('style');
    style.textContent = '.scada-wrapper[data-gridatlas-collapsed="1"]{max-height:0;'
      + 'overflow:hidden;padding-top:0;padding-bottom:0;border:0;}'
      + '#gridatlas-dash-toggle{position:fixed;right:12px;bottom:12px;z-index:9999;'
      + 'min-height:44px;min-width:44px;'
      + 'font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;'
      + 'letter-spacing:.08em;padding:8px 12px;border-radius:6px;cursor:pointer;'
      + 'background:#0d1117;color:#7fe3d0;border:1px solid #2b3a44;}'
      + '#gridatlas-dash-toggle[hidden]{display:none !important;}'
      + '#gridatlas-dash-toggle:focus-visible{outline:2px solid #7fe3d0;outline-offset:2px;}';
    document.head.appendChild(style);

    const toggle = document.createElement('button');
    toggle.id = 'gridatlas-dash-toggle';
    toggle.type = 'button';

    /* Closed on a FIRST arrival ON A PHONE only - measured, the panel held
       31.6% of a 393x852 screen against the map's 29.3%, which is the wrong
       trade on the surface most readers arrive on. A desktop has the room and
       opens with the panel showing, exactly as v8 always did: that is the
       product surface, and hiding it made the Atlas look less capable than the
       version it replaced. A choice once made still wins over both defaults.

       An UNKNOWN width is not a phone - the width has to be a real positive
       number before it argues for starting collapsed, so a host that publishes
       no width gets the desktop default rather than an empty-looking page. */
    const width = Number(window.innerWidth);
    const coarse = (() => {
      try { return !!(window.matchMedia
        && window.matchMedia('(pointer: coarse)').matches); } catch (_) { return false; }
    })();
    let collapsed = coarse || (isFinite(width) && width > 0 && width <= 700);
    try {
      const v = window.localStorage.getItem(KEY);
      if (v !== null) collapsed = v === '1';
    } catch (_) { /* the width-derived default above stands */ }

    function reflect() {
      if (collapsed) dash.setAttribute('data-gridatlas-collapsed', '1');
      else dash.removeAttribute('data-gridatlas-collapsed');
      toggle.textContent = collapsed ? '\u25b4 LAYERS' : '\u25be HIDE LAYERS';
      toggle.setAttribute('aria-pressed', String(collapsed));
      toggle.setAttribute('aria-label', collapsed
        ? 'Show the layers panel' : 'Hide the layers panel');
      /* MapLibre sizes itself to its container and will not notice the
         page reflowing under it. */
      try { if (window.map && typeof window.map.resize === 'function') window.map.resize(); }
      catch (_) { /* the control still works without the resize */ }
    }

    toggle.addEventListener('click', () => {
      collapsed = !collapsed;
      try { window.localStorage.setItem(KEY, collapsed ? '1' : '0'); } catch (_) { /* per-viewer nicety only */ }
      reflect();
    });

    document.body.appendChild(toggle);
    reflect();

    const reflectFullscreen = () => {
      const full = !!(document.fullscreenElement || document.webkitFullscreenElement);
      toggle.hidden = full;
    };
    document.addEventListener('fullscreenchange', reflectFullscreen);
    document.addEventListener('webkitfullscreenchange', reflectFullscreen);
    reflectFullscreen();

    window.__GRIDATLAS_DASH__ = {
      /* Named so a reader - and a proof - can see WHAT collapses. */
      installed: true,
      target: '.scada-wrapper',
      get collapsed() { return collapsed; },
      get hidden_by_fullscreen() { return toggle.hidden; },
      toggle: () => { toggle.click(); return collapsed; }
    };
  }());
  let topologyPromise = null;

  function topologyModule() {
    try { return window.__GRIDATLAS_MODULES__?.networkTopology || null; }
    catch (_) { return null; }
  }

  function ensureTopology() {
    if (topologyPromise) return topologyPromise;
    const module = topologyModule();
    if (!module) {
      topology.state = 'failed';
      topology.error = 'network-topology module absent from this composition';
      noteFailure('transmission network: ' + topology.error);
      return Promise.resolve(null);
    }
    topology.state = 'loading';
    topology.started_at = Date.now();
    if (!TOPOLOGY_PRODUCT) {
      topology.state = 'failed';
      topology.error = 'no pinned ref: pinned-products is not composed';
      noteFailure('transmission network: ' + topology.error);
      return Promise.resolve(null);
    }
    topologyPromise = fetch(TOPOLOGY_PRODUCT)
      .then(async response => {
        if (!response.ok) throw new Error('HTTP ' + response.status);
        const text = await response.text();
        topology.bytes = text.length;
        topology.pin = await PINS.verify(TOPOLOGY_ID, text);
        if (topology.pin.state === 'MISMATCH') throw new Error(topology.pin.detail);
        return JSON.parse(text);
      })
      .then(product => {
        const index = module.index(product);
        if (!index) {
          throw new Error('schema ' + String(product?.schema || 'absent')
            + ' is not ' + module.accepts + '; this cartridge answers nothing from it');
        }
        topology.index = index;
        /* the buses the declared DC model is built over. 400 kV only:
           a DC model that walks a transformer without its tap position
           is modelling something the product does not describe, and the
           taps are not published. */
        /* Kept because the planned-change and owner-boundary readers
           take the PRODUCT, not the graph - graph() withholds planned
           rows by design and does not carry transmission_owner. This is
           one reference to an object already in memory, not a copy. */
        topology.parsedProduct = product;
        topology.nodes400 = (product.nodes || [])
          .filter(n => n && n.voltage_consistent_with_site === true && n.voltage_kv === 400)
          .map(n => n.node);
        topology.schema = product.schema;
        topology.sites = index.counts.sites;
        topology.state = 'ready';
        topology.ready_at = Date.now();
        return index;
      })
      .catch(error => {
        topology.state = 'failed';
        topology.error = String(error?.message || error);
        noteFailure('transmission network: ' + topology.error);
        return null;
      });
    return topologyPromise;
  }

  /* Render for a list of { name, kv } queries: the mapped substation's
     name and the voltage the question is about. Every card that names a
     substation gets one of these; it is a placeholder until the product
     is indexed and is filled in place, so no card holds a reference to
     another card. */
  /* The electrical-distance module, read the same way the topology
     module is read: absent is absent, never an excuse to guess. */
  function distanceModule() {
    try { return window.__GRIDATLAS_MODULES__?.electricalDistance || null; }
    catch (_) { return null; }
  }

  /* The planned-change module takes the PRODUCT, not the topology
     index: graph() deliberately withholds planned rows, which is the
     right default and the reason this needs its own reader. The parsed
     product is not kept alive after indexing, so the index is built once
     and cached here beside the others. */
  let ownerIndex;
  function ownerModule() {
    try { return window.__GRIDATLAS_MODULES__?.ownerBoundary || null; }
    catch (_) { return null; }
  }

  let plannedIndex;
  function plannedModule() {
    try { return window.__GRIDATLAS_MODULES__?.plannedChange || null; }
    catch (_) { return null; }
  }

  function flowModule() {
    try { return window.__GRIDATLAS_MODULES__?.injectionResponse || null; }
    catch (_) { return null; }
  }

  /* The 400 kV model is built once per session and kept: assembling it
     walks every published node, and a card that rebuilt it per click
     would be doing that work again for an answer it already had.

     The node list comes from topology.nodes400, which ensureTopology
     records while it already has the parsed product in hand. Rebuilding
     it here would mean either keeping a second copy of the 10 MB payload
     alive or asking the graph for something it does not expose. */
  let flowModel = null;
  function flowModelFor(index) {
    if (flowModel) return flowModel;
    const mod = flowModule();
    if (!mod || !index || typeof index.graph !== 'function') return null;
    const names = topology.nodes400;
    if (!Array.isArray(names) || !names.length) return null;
    try {
      flowModel = mod.assemble(index.graph(), names,
        { voltageKv: 400, includeTransformers: false });
      return flowModel;
    } catch (_) { return null; }
  }

  function ratingModule() {
    try { return window.__GRIDATLAS_MODULES__?.ratingEnvelope || null; }
    catch (_) { return null; }
  }

  /* The published network at an arbitrary point.
     ---------------------------------------------------------------------
     The connection-points cartridge already resolves a position to the
     nearest published sites, so this does not measure anything itself -
     a second distance implementation in this file is exactly the drift
     that put two geodesies in one cartridge. It resolves, states the
     limit of what "nearest" can mean here, and hands the nearest name to
     the block that already renders circuits, ratings, hops and flow. */
  async function runGridAtPoint(map, lon, lat) {
    const gl = window.maplibregl;
    if (!gl?.Popup) return;
    const network = window.__GRIDATLAS_NETWORK__ || null;
    const show = (html) => {
      try {
        return new gl.Popup({ maxWidth: '380px', closeOnClick: false })
          .setLngLat([lon, lat]).setHTML(html).addTo(map);
      } catch (error) {
        noteFailure('grid at point: ' + String(error?.message || error));
        return null;
      }
    };

    if (!network || typeof network.nearest !== 'function' || !network.loaded) {
      show('<p class="neon-caveat"><b>Grid at point:</b> the connection-points '
        + 'cartridge has not loaded, so no published site can be named. '
        + 'Nothing is inferred from its absence.</p>');
      return;
    }

    /* nearest() returns { point, km } pairs, sorted. It owns the distance;
       measuring again here would be the second implementation that put
       two geodesies in one cartridge earlier tonight. */
    let found = [];
    try { found = network.nearest(lon, lat, { limit: 5 }) || []; }
    catch (_) { found = []; }
    if (!Array.isArray(found)) found = found ? [found] : [];

    const points = Number(network.points || 0);
    const located = Number(network.located || 0);
    const unlocated = points - located;

    if (!found.length) {
      show('<p class="neon-caveat"><b>Grid at point:</b> no published connection '
        + 'point with coordinates resolved here. ' + unlocated + ' of the '
        + points + ' published points carry no coordinates at all, so this is '
        + 'a statement about the mapped set and not about the network.</p>');
      pointQuery.answered += 1;
      return;
    }

    const rows = found.map(entry => escapeHtml(String(entry.point?.name || '?'))
      + (Number.isFinite(entry.km) ? ' \u00b7 ' + entry.km.toFixed(1) + ' km' : ''));

    const popup = show('<div class="neon-hd">Grid at this point'
      + '<span class="neon-beta">published network</span></div>'
      + '<p class="neon-caveat"><b>Nearest mapped connection points:</b> '
      + rows.join(', ') + '.</p>'
      + '<p class="neon-caveat">Straight-line distance from where you clicked - '
      + 'not a cable route, and not a statement that anything can connect at any '
      + 'of them. ' + unlocated + ' of the ' + points + ' published connection '
      + 'points have no coordinates, so the nearest <i>mapped</i> point may not '
      + 'be the nearest point.</p>'
      /* fillTopologyBlocks() selects by CLASS, not by a data attribute.
         Getting that wrong would have produced a block that renders its
         loading line forever and never fills. */
      + '<div class="' + TOPOLOGY_BLOCK + '" data-queries="'
      + escapeHtml(JSON.stringify([{ name: String(found[0].point?.name || ''), kv: null }])) + '">'
      + '<p class="neon-caveat"><b>Transmission network:</b> loading\u2026</p></div>');

    pointQuery.answered += 1;
    if (!popup) return;
    try { await ensureTopology(); } catch (_) { /* the block reports its own state */ }
    fillTopologyBlocks();
  }

  function topologyBlockHtml(queries) {
    const wanted = (queries || []).filter(q => q && q.name);
    if (!wanted.length) return '';
    const attr = escapeHtml(JSON.stringify(wanted.map(q => ({ name: q.name, kv: q.kv ?? null }))));
    if (topology.state === 'idle' || topology.state === 'loading') {
      ensureTopology().then(() => fillTopologyBlocks());
    }
    return `<div class="${TOPOLOGY_BLOCK}" data-queries="${attr}">`
      + topologyInnerHtml(wanted) + `</div>`;
  }

  function fillTopologyBlocks() {
    document.querySelectorAll('.' + TOPOLOGY_BLOCK).forEach(node => {
      try {
        node.innerHTML = topologyInnerHtml(JSON.parse(node.getAttribute('data-queries') || '[]'));
        topology.blocks_filled += 1;
      } catch (error) {
        noteFailure('topology block: ' + String(error?.message || error));
      }
    });
  }

  function topologyInnerHtml(queries) {
    const caveat = (text) => `<p class="neon-caveat">${text}</p>`;
    if (topology.state === 'idle' || topology.state === 'loading') {
      return caveat(`<b>Transmission network:</b> loading the published node/branch `
        + `model (about 10 MB, once per session). This card fills in when it arrives.`);
    }
    if (topology.state === 'failed') {
      return caveat(`<b>Transmission network:</b> not available - `
        + `${escapeHtml(topology.error || 'unknown failure')}. Nothing here is inferred from its absence.`);
    }
    const network = window.__GRIDATLAS_NETWORK__ || null;
    if (!network?.loaded) {
      return caveat(`<b>Transmission network:</b> indexed (${topology.sites} sites), but the `
        + `connection-points cartridge that joins a mapped name to a published site `
        + `${network?.failed ? 'failed to load' : 'has not loaded yet'}, so no site is named.`);
    }
    let out = '';
    let shown = 0;
    const module = topologyModule();
    for (const q of queries) {
      const kv = Number.isFinite(q.kv) ? q.kv : null;
      let point = null;
      try { point = network.byName(q.name); } catch (_) { point = null; }
      if (!point?.site_code) continue;
      const facts = topology.index.at(point.site_code, kv != null ? { voltageKv: kv } : undefined);
      if (!facts) continue;
      shown += 1;
      out += `<div class="neon-hd">${escapeHtml(facts.site.name)}`
        + `<span class="neon-beta">ETYS topology</span></div>`
        + caveat(`Joined by name from <i>${escapeHtml(q.name)}</i> to NESO site `
          + `${escapeHtml(facts.site.code)}`
          + (facts.site.transmission_owner ? ` (${escapeHtml(facts.site.transmission_owner)})` : '')
          + `; declared voltages ${facts.site.voltages_kv.length
            ? escapeHtml(facts.site.voltages_kv.join(', ')) + ' kV' : 'not stated'}.`);
      if (!facts.by_voltage.length) {
        out += caveat(kv != null
          ? `No published branch lands at ${kv} kV at this site.`
          : `No published branch lands at this site.`);
      } else {
        /* Site totals are UNITS; the lines below are landings and will
           not add up, because a transformer with both windings here
           appears under each of its voltages. */
        const c = facts.counts;
        out += caveat(`<b>At the site:</b> ${c.circuits} circuit`
          + `${c.circuits === 1 ? '' : 's'} and ${c.transformers} transformer`
          + `${c.transformers === 1 ? '' : 's'}, counted as units. `
          + `The per-voltage lines below count landings, one for each end held `
          + `here, so a transformer with both windings at this site appears `
          + `under both of its voltages.`);
      }
      for (const band of facts.by_voltage) {
        const label = band.voltage_kv == null ? 'an undeclared voltage' : `${band.voltage_kv} kV`;
        const years = [...new Set(band.planned_changes.map(c => c.year).filter(Boolean))].sort();
        out += caveat(`<b>At ${label}:</b> ${band.circuits.length} circuit${band.circuits.length === 1 ? '' : 's'}, `
          + `${band.transformers.length} transformer${band.transformers.length === 1 ? '' : 's'}`
          + (band.planned_changes.length
            ? `, ${band.planned_changes.length} published change${band.planned_changes.length === 1 ? '' : 's'}`
              + (years.length ? ` (${escapeHtml(years.join(', '))})` : '')
            : '')
          + `.`);
      }
      /* Seasonal ratings, per circuit, never added together.
         ---------------------------------------------------------------
         The lowest and the highest are two REAL published values, not a
         range around a mean, and each is labelled with the season it
         belongs to. Where the operator publishes a placeholder rather
         than a rating, the card says so rather than quietly carrying the
         larger number into the maximum. */
      const ratings = (() => {
        const mod = ratingModule();
        if (!mod) return null;
        try { return mod.at(topology.index, point.site_code, kv != null ? { voltageKv: kv } : undefined); }
        catch (_) { return null; }
      })();
      if (ratings && ratings.circuits.length) {
        const said = [];
        for (const season of ['winter', 'summer']) {
          const band = ratings.by_season[season];
          if (!band || !band.circuits) continue;
          said.push(`${season} ${band.lowest_circuit_mva === band.highest_circuit_mva
            ? band.lowest_circuit_mva
            : `${band.lowest_circuit_mva}-${band.highest_circuit_mva}`} MVA`);
        }
        if (said.length) {
          const flagged = ratings.counts.with_a_flagged_value;
          out += caveat(`<b>Circuit ratings:</b> ${escapeHtml(said.join(', '))}, `
            + `across ${ratings.counts.circuits} circuit${ratings.counts.circuits === 1 ? '' : 's'}. `
            + `Each figure is one circuit's rating in that season. They are not added `
            + `together: the sum of the circuits at a site is not a quantity that exists `
            + `in the network, and a rating is not what is free on the circuit.`
            + (flagged ? ` ${flagged} circuit${flagged === 1 ? ' publishes a value' : 's publish values'} `
              + `at or above 9,999 MVA on spans of a kilometre or less; `
              + `${flagged === 1 ? 'it reads' : 'they read'} as a placeholder and `
              + `${flagged === 1 ? 'is' : 'are'} excluded from the range above.` : ''));
          rating.answered += 1;
          rating.flagged += flagged;
        }
      }

      /* Who owns what lands here, and whether two owners meet.
         ---------------------------------------------------------------
         Printed before the planned sentence because it is a fact about
         what is there now. A single owner is a small fact; two owners on
         one circuit is a seam, and a connection across a seam involves
         more than one party. */
      const ownership = (() => {
        const mod = ownerModule();
        if (!mod || !topology.parsedProduct) return null;
        try {
          if (ownerIndex === undefined) ownerIndex = mod.index(topology.parsedProduct);
          if (!ownerIndex) return null;
          return ownerIndex.at(point.site_code, kv != null ? { voltageKv: kv } : undefined);
        } catch (_) { return null; }
      })();
      if (ownership && Array.isArray(ownership.owners_present) && ownership.owners_present.length) {
        const owners = ownership.owners_present.map((o) => escapeHtml(String(o)));
        const seams = (ownership.boundary_circuits || []).length
          + (ownership.boundary_transformers || []).length;
        const counts = ownership.counts || {};
        out += caveat(`<b>Transmission owner${owners.length === 1 ? '' : 's'}:</b> `
          + `${owners.join(', ')}.`
          + (seams
            ? ` ${seams} branch${seams === 1 ? '' : 'es'} here ${seams === 1 ? 'is' : 'are'} `
              + `a boundary: the two ends are published under different owners.`
            : '')
          + (counts.nodes_with_unknown_owner
            ? ` ${counts.nodes_with_unknown_owner} node here publishes no owner and is `
              + `reported as unknown, never taken from the site.`
            : '')
          + (counts.asset_owner_differs_from_both_ends
            ? ` ${counts.asset_owner_differs_from_both_ends} asset carries an owner `
              + `matching neither of its ends; that is reported as itself, not as a boundary.`
            : '')
          + ` Ownership is a published fact about an asset. It is not a statement `
          + `about who a project would contract with, which depends on connection `
          + `agreements and commercial terms no appendix contains.`);
        ownerState.answered += 1;
        ownerState.seams += seams;
      }

      /* What is published as planned, in its own sentence.
         ---------------------------------------------------------------
         Never folded into the counts above. A row published for 2030 is
         a statement about a future year; presenting it beside today's
         circuits would let a reader take it for one. */
      const planned = (() => {
        const mod = plannedModule();
        if (!mod || !topology.parsedProduct) return null;
        try {
          if (plannedIndex === undefined) plannedIndex = mod.index(topology.parsedProduct);
          if (!plannedIndex) return null;
          return plannedIndex.at(point.site_code, kv != null ? { voltageKv: kv } : undefined);
        } catch (_) { return null; }
      })();
      if (planned && planned.counts && planned.counts.planned_changes) {
        /* by_year is an ORDERED ARRAY of { year, by_status: [{ status,
           entries }] }, not a map - the module keeps publication order
           rather than letting object key order decide what the reader
           sees first. */
        const years = (planned.by_year || []).map((band) => {
          const parts = (band.by_status || []).map((s) =>
            `${(s.entries || []).length} ${escapeHtml(String(s.status).toLowerCase())}`);
          return `<b>${escapeHtml(String(band.year))}</b> ${parts.join(', ')}`;
        });
        if (years.length) {
          out += caveat(`<b>Published as planned:</b> ${years.join('; ')}. `
            + `These are rows NESO publishes for a future year. None of them is a `
            + `circuit today, a commitment, a consent, or a connection date, and `
            + `none is counted among the circuits above.`);
          plannedState.answered += 1;
          plannedState.rows += planned.counts.planned_changes;
        }
      }

      /* Where the project's own power would go.
         ---------------------------------------------------------------
         Pipeline News sends capacity_mw on every deep link, so the
         question "where would MY output flow" is answerable the moment a
         project is selected. The slack is NAMED in the sentence: a
         transfer has two ends and quoting one of them is meaningless.
         What is deliberately absent is any statement about room. */
      const injection = (() => {
        const mod = flowModule();
        if (!mod || kv !== 400) return null;
        /* The project's own stated capacity where the deep link carried
           one, and a declared 100 MW probe otherwise - labelled as such in
           the sentence, never presented as the project's figure. */
        const mw = Number.isFinite(currentCapacityMw) && currentCapacityMw > 0
          ? currentCapacityMw : 100;
        const model = flowModelFor(topology.index);
        if (!model) return null;
        try {
          const graph = topology.index.graph();
          const here = graph.nodesOfSite(point.site_code)
            .filter(n => graph.nodeVoltageKv(n) === 400).sort()[0];
          if (!here) return null;
          /* The withdrawal bus is DECLARED, not the first one to hand.
             ------------------------------------------------------------
             This took model.buses.find(b => b !== injection), which on a
             network with 238 components is almost always a bus the
             injection cannot reach. Codex found it at 202609020030. The
             module now publishes the rule it uses and the component it
             solved in, and refuses a cross-component transfer outright. */
          const slackNode = typeof mod.sinkFor === 'function'