GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atlas/modules

Secondary Neon Engine (part 7)

A JavaScript file in the atlas 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: Maps, GIS and field navigation. Section 562 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. Secondary Neon Engine geodesy · gridatlas / atlas/modules/202612020205-secondary-neon-engine.js lines 4648–5347

Secondary Neon Engine

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

geodesygridatlas / atlas/modules/202612020205-secondary-neon-engine.js · lines 4648–5347 of 9008 · version 2026-12-02 02:05 (continued from section 555) · 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 274 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 upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. 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/modules · 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
none found
Produces
distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver
Defines here
stopAnimation, startAnimation, step, recordArrivalEngine, clearArrivalEngine, clearLinks, drawLinks, holds, noteInput, onStart, onEnd, enableSubstationLayer, fromOwnUi, statusHost, showStatus, placeStatus, clear, settle, clearStatus, retryArrival, retryIdentityOwnerThenArrival, injectStatusStyle, watchForLayerControls, waitForLayerControls
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/modules/202612020205-secondary-neon-engine.js:4648-5347 · blob 26e5045a356c11088820207d3cbe95eb4b89374f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
      paint: {
        'line-color': FLOW_COLOUR,
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 1.2, 12, 2.4],
        'line-opacity': 0.8,
        'line-dasharray': [0.2, 3.2]
      }
    });
    map.addLayer({
      id: L_FLOW_B, type: 'line', source: SRC,
      layout: { 'line-cap': 'round' },
      paint: {
        'line-color': FLOW_COLOUR,
        'line-width': ['interpolate', ['linear'], ['zoom'], 6, 0.9, 12, 1.8],
        'line-opacity': 0.45,
        'line-dasharray': [0.2, 3.2]
      }
    });

    map.addLayer({
      id: L_NODE_RING, type: 'circle', source: SRC_NODES,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 6, 12, 13],
        'circle-color': 'rgba(0,0,0,0)',
        'circle-stroke-color': SUBSTATION_COLOUR,
        'circle-stroke-width': 1,
        'circle-stroke-opacity': 0.4
      }
    });
    map.addLayer({
      id: L_NODE, type: 'circle', source: SRC_NODES,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 2.2, 12, 4],
        'circle-color': SUBSTATION_COLOUR,
        'circle-opacity': 0.8
      }
    });
    const neonFont = styleTextFont(map);
    if (!neonFont) {
      link.labels_drawn = false;
      link.failures.push('the basemap serves no glyphs, so link labels are omitted');
    } else {
      // Defer until a glyph range actually comes back. Nothing waits on
      // labels: the links are already drawn and the distances are on the
      // card.
      addLabelLayerWhenDrawable(map, neonFont, {
          id: L_LABEL, type: 'symbol', source: SRC_NODES,
          layout: {
            'text-field': ['get', 'label'],
            'text-size': 10,
            'text-offset': [0, -1.5],
            'text-anchor': 'bottom',
            'text-allow-overlap': false,
            'text-font': neonFont
          },
          paint: {
            'text-color': '#a9c4c9',
            'text-halo-color': '#000c10',
            'text-halo-width': 1.5,
            'text-opacity': 0.9
          }
        }, 'link');
    }
        link.installed = true;
  }

  function stopAnimation() {
    forgetDashMemo();
    if (animationHandle !== null) {
      cancelAnimationFrame(animationHandle);
      animationHandle = null;
    }
  }

  function startAnimation(map) {
    stopAnimation();
    const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true;
    link.reduced_motion = reduced;
    if (reduced) {
      // Motion is a preference, not a requirement. The lines, the nodes and
      // every number stay; only the travelling dash stops.
      try {
        map.setPaintProperty(L_FLOW, 'line-opacity', 0);
        map.setPaintProperty(L_FLOW_B, 'line-opacity', 0);
      } catch (_) { /* layer gone */ }
      return;
    }
    const step = () => {
      dashPhase = (dashPhase + FLOW_SPEED) % FLOW_PERIOD;
      const half = (dashPhase + FLOW_PERIOD / 2) % FLOW_PERIOD;
      try {
        setFlowDash(map, L_FLOW, dashPhase);
        setFlowDash(map, L_FLOW_B, half);
      } catch (_) {
        stopAnimation();
        return;
      }
      animationHandle = requestAnimationFrame(step);
    };
    animationHandle = requestAnimationFrame(step);
  }

  /* One writer for the sentinel, at module scope.
     ---------------------------------------------------------------------
     v9.148 introduced `arrival_engine` and wrote it from two places: a
     literal inside drawLinks() and a helper inside install(). Two writers of
     one record is a maintenance trap - an epoch added to one and not the
     other makes the success path and the failure paths disagree - and, worse,
     neither writer existed on the paths where the engine never installs at
     all, which is precisely the "it did not launch" case. So the record has
     one writer, it lives at module scope where every path can reach it, and
     install()'s answerArrival() delegates to it rather than duplicating it.

     It also mirrors to the DOM. A sentinel readable only from the JavaScript
     console is not a surface anyone can open, and the whole point of this
     record is that a person - not just a test - can tell a silent map from a
     broken one. */
  function recordArrivalEngine(engine, answered, reason, fallbackFrom, pending = false) {
    let epoch = null;
    try { epoch = arrivalGate.snapshot().epoch; } catch (_) { epoch = null; }
    /* `reason` is not "why it failed", it is "what happened", and it survives a
       true answer. An arrival answered from beyond the draw radius answered -
       there is a real distance and a real named substation - and it is also a
       materially different answer from one with five lines on the map. v9.148
       carried that distinction and nulling the reason on success would throw it
       away. An unanswered arrival with nothing to say is UNSTATED, which is a
       defect, not a state to be tolerated quietly. */
    /* `terminal` separates "this engine has finished with this arrival" from
       "this engine has taken the arrival and is still working". Without it a
       handover looks exactly like a refusal: an interconnector arrival is
       passed to the interconnector module in the first milliseconds, and a
       reader - or a test - that stops at the first record written would call
       every interconnector in the country unanswered while its measurement was
       still running. A non-terminal record is a receipt, not a verdict. */
    link.arrival_engine = {
      engine: engine || 'onshore',
      answered: Boolean(answered),
      reason: reason || (answered ? null : 'UNSTATED'),
      fallback_from: fallbackFrom || null,
      terminal: !pending,
      epoch,
      at: new Date().toISOString(),
    };
    try {
      capturedMap?.getContainer?.().setAttribute('data-gridatlas-arrival',
        link.arrival_engine.answered ? 'answered' : String(link.arrival_engine.reason));
      capturedMap?.getContainer?.().setAttribute('data-gridatlas-arrival-engine',
        String(link.arrival_engine.engine));
    } catch (_) { /* the object on window is the record; the attribute is a convenience */ }
    return link.arrival_engine;
  }
  link.measure.recordArrivalEngine = recordArrivalEngine;

  function clearArrivalEngine() {
    link.arrival_engine = null;
    try {
      capturedMap?.getContainer?.().removeAttribute('data-gridatlas-arrival');
      capturedMap?.getContainer?.().removeAttribute('data-gridatlas-arrival-engine');
    } catch (_) { /* nothing to clear */ }
  }

  function clearLinks() {
    invalidatePendingArrival('clear');
    stopAnimation();
    const map = capturedMap;
    if (map && map.getSource(SRC)) {
      setSourceData(map, SRC, emptyCollection());
      setSourceData(map, SRC_NODES, emptyCollection());
    }
    disarmCardKeeper();
    removeArrivalFallback();
    removeCardBlock();
    clearPin(capturedMap);
    link.links_drawn = 0;
    clearArrivalEngine();
    link.last_selection = null;
    currentRepdRef = null;
    currentDeclared = null;
    currentNeso = null;
    currentNearest400 = null;
  }

  function drawLinks(map, origin, name, tech, links, direction, statedMw, layerLoaded = true) {
    cardSelectionKey = JSON.stringify([origin, name, tech, direction]);
    ensureLayers(map);
    // A link takes the colour of the project end, whichever end was clicked.
    const colour = direction === 'from-substation'
      ? SUBSTATION_COLOUR
      : (TECH_COLOUR[tech] || SUBSTATION_COLOUR);

    const lines = links.map((l, index) => ({
      type: 'Feature',
      properties: {
        colour,
        // The nearest link burns brightest; the rest fade back in order, so
        // rank is legible without reading the numbers.
        strength: Math.max(0.20, 0.62 - index * 0.10),
        km: l.km
      },
      geometry: { type: 'LineString', coordinates: [origin, l.at] }
    }));

    const nodes = links.map(l => {
      const tail = l.kv && l.kv.length ? `${l.kv[0]} kV`
        : (l.mw != null ? `${l.mw} MW` : '');
      return {
        type: 'Feature',
        properties: {
          colour,
          label: tail ? `${l.km.toFixed(2)} km · ${tail}` : `${l.km.toFixed(2)} km`
        },
        geometry: { type: 'Point', coordinates: l.at }
      };
    });

    if (direction === 'to-substation' && currentDeclared?.at) {
      // The declared link is public record, drawn in its own colour so it
      // never reads as one more nearest-neighbour measurement.
      const unbuilt = currentDeclared.poc_status === 'not_built'
        || currentDeclared.poc_status === 'under_construction';
      const declaredColour = unbuilt ? DECLARED_UNBUILT_COLOUR : DECLARED_COLOUR;
      lines.push({ type: 'Feature',
        properties: { colour: declaredColour, strength: 0.85, km: currentDeclared.km },
        geometry: { type: 'LineString', coordinates: [origin, currentDeclared.at] } });
      nodes.push({ type: 'Feature',
        properties: { colour: declaredColour,
          label: `PoC \u00b7 ${currentDeclared.km.toFixed(2)} km \u00b7 ${currentDeclared.kv} kV` },
        geometry: { type: 'Point', coordinates: currentDeclared.at } });
    }
    /* THE DECLARED CONNECTION IS DRAWN, NOT ONLY PRINTED.
       ------------------------------------------------------------------
       v9.151 read the NESO register and put the connection site on the card,
       and the owner opened Berwick Bank on his phone and saw a dot in the sea
       with a collapsed sheet under it: "didn't fire". He was right. The engine
       had answered - Branxton, 80.57 km - and the answer was a sentence behind
       a plus sign while the map showed nothing at all, because the rule since
       v9.14x is that nothing beyond the 40 km draw radius is drawn.

       That rule exists so a 217 km straight line to whatever happens to be
       nearest is never mistaken for a cable. A declared connection is not
       that. It is the substation the connection authority has contracted this
       project to, so a line to it is a picture of a real thing - drawn in the
       declared gold rather than the neon of a measurement, and labelled as the
       declared connection, so it can never read as one more nearest-neighbour
       result. It stays a straight line and the card still says so. The owner
       then measured it himself along the water via Neart na Gaoithe: 88.56 km
       against this line's 80.57 km straight, which is the difference between a
       route and a chord, and the card names it as a chord. */
    let nesoDrawn = false;
    if (direction === 'to-substation' && currentNeso?.at && !currentDeclared?.at
        && Number.isFinite(currentNeso.km)) {
      lines.push({ type: 'Feature',
        properties: { colour: DECLARED_COLOUR, strength: 0.85, km: currentNeso.km },
        geometry: { type: 'LineString', coordinates: [origin, currentNeso.at] } });
      nodes.push({ type: 'Feature',
        properties: { colour: DECLARED_COLOUR,
          label: 'Declared \u00b7 ' + currentNeso.km.toFixed(2) + ' km'
            + (currentNeso.kv ? ' \u00b7 ' + currentNeso.kv + ' kV' : '') },
        geometry: { type: 'Point', coordinates: currentNeso.at } });
      nesoDrawn = true;
    }
    const secondary = direction === 'from-secondary';
    const lineOK = setSourceData(map, SRC, { type: 'FeatureCollection', features: lines });
    const nodeOK = setSourceData(map, SRC_NODES, { type: 'FeatureCollection', features: nodes });
    if (secondary) {
      if (!lineOK || !nodeOK) { clearLinks(); return false; }
      startAnimation(map);
      link.links_drawn = links.length;
      link.last_selection = {name, tech: null, direction, count: links.length,
        nearest_km: links.length ? Number(links[0].km.toFixed(3)) : null,
        nearest_name: links[0]?.name || null};
      return true; // no REPD receipt, declared connection, project pin or project card
    }
    /* And framed. A line whose far end is 80 km outside the viewport is as
       invisible as no line. When the declared connection is the only thing
       drawn, the camera fits both ends; when nearest links are drawn too the
       reader already has something in view and the camera is left alone. The
       bottom padding keeps the far end above a phone's docked card. */
    if (nesoDrawn && !links.length) {
      try {
        let sheet = false;
        try { sheet = Boolean(sheetTarget()); } catch (_) { sheet = false; }
        map.fitBounds(
          [[Math.min(origin[0], currentNeso.at[0]), Math.min(origin[1], currentNeso.at[1])],
           [Math.max(origin[0], currentNeso.at[0]), Math.max(origin[1], currentNeso.at[1])]],
          { padding: { top: 90, left: 40, right: 40, bottom: sheet ? 220 : 90 },
            maxZoom: 10, duration: 900, essential: true });
        link.declared_connection_framed = true;
        /* And kept. The identity lane resolves the project against the
           register over the network and flies to it at zoom 12 when it does -
           1.2 s, essential - and on a real connection that lands AFTER this
           frame, not before. Measured on Hornsea 3 in Chromium on the live
           root: framed at zoom 7.06, then carried to 11.17 on the array with
           Norwich Main gone off the bottom. Locally the register answered first
           and the race never showed, which is the usual way a race hides.

           So the frame re-asserts itself, at most twice and only within the
           arrival window, if the camera leaves it without a person touching the
           map. MapLibre sets originalEvent on user-initiated moves and leaves
           it undefined on programmatic ones, and that is the whole test: a
           reader who drags or pinches owns the camera from that moment on. */
        const both = [
          [Math.min(origin[0], currentNeso.at[0]), Math.min(origin[1], currentNeso.at[1])],
          [Math.max(origin[0], currentNeso.at[0]), Math.max(origin[1], currentNeso.at[1])]];
        const holds = () => {
          try { const b = map.getBounds(); return b.contains(both[0]) && b.contains(both[1]); }
          catch (_) { return true; }
        };
        /* v9.153 held this guard for twelve seconds and it never fired on the
           live root: a cold DuckDB identity boot over a real connection takes
           longer than that, so the late flight landed after the listeners were
           gone. Measured in Chromium on Berwick Bank and Hornsea 3, both ending
           at zoom 11 on the array with the far end lost. A clock is the wrong
           shape for this. The guard now lives as long as the arrival does - it
           is detached when the arrival gate moves, by clearLinks or a new
           selection - and stands down the moment a person takes the map.

           Two kinds of person. A drag or a pinch arrives with originalEvent on
           the map's movestart. A tap on a control that then moves the camera
           programmatically - the layout button, the scope tools - does not, so
           any pointer, touch, key or wheel anywhere in the document within the
           last three seconds is also read as the reader taking over. Otherwise
           the frame would win a fight against a button the reader just
           pressed, and that is the one fight it must lose. */
        if (typeof declaredFrameGuard === 'function') { try { declaredFrameGuard(); } catch (_) {} }
        let userOwned = false, reasserted = 0, lastInput = 0;
        const noteInput = () => { lastInput = Date.now(); };
        const onStart = (e) => { if (e && e.originalEvent) userOwned = true; };
        const onEnd = () => {
          if (userOwned || Date.now() - lastInput < 3000 || reasserted >= 2 || holds()) return;
          reasserted += 1;
          link.declared_frame_reasserted = reasserted;
          try {
            map.fitBounds(both, { padding: { top: 90, left: 40, right: 40, bottom: sheet ? 220 : 90 },
              maxZoom: 10, duration: 600, essential: true });
          } catch (_) { /* the first frame stands */ }
        };
        const inputEvents = ['pointerdown', 'touchstart', 'keydown', 'wheel'];
        inputEvents.forEach(t => document.addEventListener(t, noteInput, { capture: true, passive: true }));
        map.on('movestart', onStart);
        map.on('moveend', onEnd);
        declaredFrameGuard = () => {
          try { map.off('movestart', onStart); map.off('moveend', onEnd); } catch (_) { /* gone */ }
          inputEvents.forEach(t => { try { document.removeEventListener(t, noteInput, { capture: true }); } catch (_) {} });
          declaredFrameGuard = null;
        };
      } catch (error) {
        link.failures.push('declared frame: ' + String(error?.message || error));
      }
    }

    // The popup is built by the engine and rendered synchronously in its own
    // click handler, but MapLibre attaches it on the next frame in some paths.
    // One retry covers that without polling forever.
    armCardKeeper(links, direction, layerLoaded);
    if (!injectIntoCard(links, direction, layerLoaded)) {
      requestAnimationFrame(() => injectIntoCard(links, direction, layerLoaded));
    }
    startAnimation(map);

    link.links_drawn = links.length;
    /* The engine has finished. Offshore is a different question from onshore -
       an export cable lands at a declared point - and until that declaration
       exists offshore is answered by the onshore engine. That is a legitimate
       fallback and it is named as one rather than passed off as the answer. */
    if (direction !== 'from-substation') {
      let offshore = false;
      try { offshore = Boolean(coverage.policy(tech)?.offshore); } catch (_) { offshore = false; }
      recordArrivalEngine(
        offshore ? 'offshore' : 'onshore',
        links.length > 0 || Boolean(links.beyondRadiusNearest),
        links.length ? null
          : (nesoDrawn ? 'DECLARED_CONNECTION_DRAWN'
            : (links.beyondRadiusNearest ? 'NEAREST_BEYOND_' + MAX_LINK_KM + '_KM' : 'NO_SUBSTATION_DATA')),
        /* Only a fallback while nothing declares the connection. Now that the
           NESO register is read, an offshore project with a connection site is
           answered by its declared point and says so, and only a project with
           neither is falling back to a nearest-substation search. */
        offshore && !currentDeclared && !currentNeso?.site ? 'declared_connection_point' : null
      );
    }
    /* Two different facts, never collapsed into one null. `nearest_km` is the
       nearest mapped substation whether or not it was close enough to draw;
       `nearest_beyond_radius` says which of the two it is, so a reader can tell
       "nothing within the draw radius" from "no substation data at all". */
    const beyond = links.length ? null : (links.beyondRadiusNearest || null);
    link.last_selection = {
      name, tech, direction, count: links.length,
      nearest_km: links.length
        ? Number(links[0].km.toFixed(3))
        : (beyond ? Number(beyond.km.toFixed(3)) : null),
      nearest_beyond_radius: links.length ? false : Boolean(beyond),
      nearest_name: links.length ? (links[0].name || null) : (beyond ? (beyond.name || null) : null),
      draw_radius_km: links.radiusKm != null ? links.radiusKm : null,
    };
    lastSelection = { origin, name, tech, direction, links, statedMw: statedMw || null };
    if (direction !== 'from-substation') setPin(map, origin, name, tech);
  }

  /* ── selection ───────────────────────────────────────────────────────── */

  // Tick the engine's own Subs control. Going through the checkbox means the
  // engine hydrates the layer, updates its UI state and stays the owner of it;
  // adding the source here instead would leave its panel lying about what is on.
  function enableSubstationLayer() {
    try {
      /* The engine tags its own controls with data-layer-id, and that is
         what enableTechnologyLayer and the mobile tray have both used for
         generations. This searched LABEL TEXT for "subs " instead, which
         is the one part of a control guaranteed to change: the labels
         carry live counts and a [WAIT]/[OK]/[LOAD] state. Attribute
         first; the label stays only as a fallback for a control that
         somehow lacks it. Codex, 202609011823. */
      const box = document.querySelector('input[type=checkbox][data-layer-id="subs"]')
        || [...document.querySelectorAll('input[type=checkbox]')].find((input) => {
          const label = (input.closest('label') || input.parentElement)?.textContent || '';
          return label.replace(/\s+/g, ' ').trim().toLowerCase().startsWith('subs ');
        });
      if (!box) { noteFailure('subs: control not found'); return false; }
      if (!box.checked) box.click();
      link.substation_layer_enabled = true;
      recoverFailures(/^subs: control not found$/);
      return true;
    } catch (error) {
      link.failures.push('subs: ' + String(error?.message || error));
      return false;
    }
  }

  // True when a click came from one of our own surfaces -- the card block or
  // the layout panel -- rather than from the map itself. MapLibre delivers
  // container clicks as map clicks, so without this every button we add fires
  // whatever is under it.
  function fromOwnUi(event) {
    const target = event?.originalEvent?.target;
    if (!target || typeof target.closest !== 'function') return false;
    return Boolean(target.closest('.maplibregl-popup')
      || target.closest('#gridatlas-sld-panel'));
  }

  // The engine's own layer control for a technology. Arriving from Pipeline
  // News the project itself was invisible: the deep link switched the
  // substations on and left the project's layer off, so the card described a
  // scheme with no pixel under it and the links appeared to start from nowhere.
  // The engine tags each layer control with the layer it drives:
  //   <input type=checkbox data-layer-id="solar">
  // so the technology IS the hook, and no mapping table is needed. Matching on
  // the label text worked, but the labels carry live counts -- "Solar PV [2819
  // | 52.3GW]" -- so it was matching prose that changes with the data. The
  // label match stays as a fallback for a control the engine has not tagged.
  const TECH_LABEL_FALLBACK = {
    solar: "Solar PV [", solar_operational: "Solar PV (Operational",
    solar_roof: "Solar Roof [",
    bess: "Battery Storage [", bess_operational: "Battery Storage (Operational",
    wind: "Wind [", wind_onshore_operational: "Onshore Wind (Operational",
  };

  /* ── say what is happening ────────────────────────────────────────────
     Vikram, tonight: "the map feature from pipelinenews doesnt load on
     iphone". Reproduced in kind on the desktop: a black rectangle, no
     controls, and a deep link waiting for substations that could not arrive.
     Nothing on screen said so. A black map is indistinguishable from a broken
     one, and the reader is left to guess which they have.

     The Atlas boots a 35.7 MB query engine before it can answer anything. On
     a phone over cellular that is a long wait and sometimes not a wait at all,
     and the honest thing is to say which. This chip says what is being waited
     for, and when the wait has failed it says that too, with a way to try
     again -- because a retry after the network recovers is usually all it
     needs, and a reload throws away the deep link.

     It removes itself the moment the controls arrive, so a working Atlas is
     never decorated with news about itself. */

  const STATUS_ID = 'gridatlas-boot-status';

  function statusHost() {
    return document.querySelector('.maplibregl-map') || document.body;
  }

  function showStatus(message, kind) {
    try {
      let el = document.getElementById(STATUS_ID);
      if (!el) {
        el = document.createElement('div');
        el.id = STATUS_ID;
        el.setAttribute('role', 'status');
        el.setAttribute('aria-live', 'polite');
        statusHost().appendChild(el);
      }
      el.dataset.kind = kind || 'waiting';
      el.textContent = message;
      if (kind === 'failed') {
        const again = document.createElement('button');
        again.type = 'button';
        again.textContent = 'Try again';
        again.addEventListener('click', (event) => {
          event.stopPropagation();
          event.preventDefault();
          retryArrival();
        });
        el.appendChild(again);
      }
      link.status_message = message;
      placeStatus(el);
    } catch (error) {
      link.failures.push('status: ' + String(error?.message || error));
    }
  }

  /* THE STATUS BOX IS READ, OR IT IS NOT A STATUS. It sat at a fixed top:14px inside the map, and the menu bar, the
     search box and the search results all lie over the top of the map: on a phone the placeholder sentence was printed
     underneath three other things and a reader got its last line. It was also 195 px wide on a 390 px screen, because
     a box centred with left:50% can only ever be as wide as the half of the map to its right.

     So it is given the width of the screen less a margin, and it finds its own height: it starts where it always did
     and moves down until the page itself says that a finger on its centre and on each of its corners would touch the
     box and nothing else. No selector is named, because the furniture above it has changed before and will again. It
     asks again after the search results have had time to appear, and when the window changes shape. */
  function placeStatus(el) {
    try {
      if (!document.getElementById(STATUS_ID + '-place')) {
        const style = document.createElement('style');
        style.id = STATUS_ID + '-place';
        style.textContent = '#' + STATUS_ID + '{left:4vw;right:4vw;transform:none;margin:0 auto;'
          + 'width:fit-content;max-width:min(92vw,420px);box-sizing:border-box}';
        document.head.appendChild(style);
      }
      const clear = () => {
        const r = el.getBoundingClientRect();
        if (r.width < 2 || r.height < 2) return true;
        /* A GRID of points, not the centre and the corners: the search box lies across the lower middle of this
           box, between all five of those, and the first version of this rule declared the box clear with a text
           field printed straight over its sentence. Nine columns by five rows leaves no gap a control can hide in. */
        const points = [];
        for (let i = 0; i < 9; i++) for (let j = 0; j < 5; j++) {
          points.push([r.left + 3 + (r.width - 6) * i / 8, r.top + 3 + (r.height - 6) * j / 4]);
        }
        return points.every(([x, y]) => {
          const hit = document.elementFromPoint(Math.min(Math.max(x, 1), innerWidth - 1),
            Math.min(Math.max(y, 1), innerHeight - 1));
          return !hit || hit === el || el.contains(hit);
        });
      };
      const settle = () => {
        if (!el.isConnected) return;
        let top = 14;
        el.style.top = top + 'px';
        const limit = Math.max(160, innerHeight * 0.6);
        while (!clear() && top < limit) { top += 8; el.style.top = top + 'px'; }
        link.status_top_px = top;
      };
      settle();
      for (const ms of [300, 1200, 3000, 6000]) setTimeout(settle, ms);
      if (!placeStatus.listening) {
        placeStatus.listening = true;
        window.addEventListener('resize', () => {
          const live = document.getElementById(STATUS_ID);
          if (live) placeStatus(live);
        });
      }
    } catch (error) {
      link.failures.push('status placement: ' + String(error?.message || error));
    }
  }

  function clearStatus() {
    document.getElementById(STATUS_ID)?.remove();
    link.status_message = null;
  }

  // Re-run the arrival rather than reloading: a reload on a phone repeats the
  // whole 35.7 MB boot, and the deep link is in the URL either way.
  let retryArrival = () => {};
  let rerunDeepLink = null;

  async function retryIdentityOwnerThenArrival() {
    clearStatus();
    const owner = window.__GRIDATLAS_PLACE_SEARCH__;
    if (typeof owner?.retry_exact_deep_link !== 'function') {
      showStatus('The active-register identity owner cannot retry in this composition.',
        'failed');
      return false;
    }
    const invalidatedEpoch = invalidatePendingArrival('identity-retry');
    const retryEpoch = claimPendingArrival(window.location.search);
    link.arrival_retry = {
      status: 'OWNER_PENDING', invalidated_epoch: invalidatedEpoch,
      owner_epoch: retryEpoch, measurement_epoch: retryEpoch
    };
    try {
      await owner.retry_exact_deep_link(retryEpoch);
    } catch (error) {
      link.arrival_retry.status = 'FAILED';
      showStatus('The active-register identity retry failed: '
        + String(error?.message || error), 'failed');
      return false;
    }
    const terminal = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link;
    if (!arrivalGate.isCurrent(retryEpoch)
        || terminal?.owner_epoch !== retryEpoch
        || terminal?.status === 'CANCELLED') {
      link.arrival_retry.status = 'CANCELLED';
      return false;
    }
    if (terminal?.status === 'FAILED') {
      link.arrival_retry.status = 'FAILED';
      showStatus('The active-register identity check failed: '
        + String(terminal.message || 'identity loader unavailable'), 'failed');
      return false;
    }
    if (typeof rerunDeepLink !== 'function') {
      link.arrival_retry.status = 'FAILED';
      showStatus('The grid measurement owner cannot retry in this composition.',
        'failed');
      return false;
    }
    link.arrival_retry.status = 'MEASUREMENT_PENDING';
    const completed = await rerunDeepLink(retryEpoch);
    if (!arrivalGate.isCurrent(retryEpoch)) {
      link.arrival_retry.status = 'CANCELLED';
      return false;
    }
    link.arrival_retry.status = terminal.status === 'NOT_IN_ACTIVE_REGISTER'
      ? 'NOT_IN_ACTIVE_REGISTER' : (completed === false ? 'FAILED' : 'RESOLVED');
    return completed !== false;
  }

  function injectStatusStyle() {
    if (document.getElementById(STATUS_ID + '-style')) return;
    const style = document.createElement('style');
    style.id = STATUS_ID + '-style';
    style.textContent = SLD_STYLES.bootStatus(STATUS_ID);
    document.head.appendChild(style);
  }

  // Resolve when the engine has rendered its layer dashboard, or when the
  // wait is up. Returning false is a fact worth having, not an error: it says
  // the engine had not finished, which is a different problem from the layer
  // being missing.
  /* Watch for the controls; do not guess how long they will take.
     ----------------------------------------------------------------------
     A fixed budget is always the wrong number. Twelve seconds was generous on
     one load and hopeless on the next: the engine builds its layer dashboard
     from its own data, and that has been measured arriving in two seconds and
     not arriving at all in eighty-six.

     Giving up after a budget also gave up permanently. If the dashboard
     appeared at thirteen seconds -- which it often does -- the layers the
     arrival depends on stayed off for the rest of the session, with a card on
     screen saying the grid data had not loaded while the controls sat there.

     So: the wait still bounds how long the user is asked to look at a spinner,
     because that is a promise about the interface. But an observer keeps
     watching afterwards, and switches the layers on whenever they arrive,
     however late. The status line is cleared at the same moment, because a
     failure notice that outlives the failure is its own bug.

     The observer disconnects the first time it fires. It is not a subscription
     to the page; it is one deferred question. */

  const LAYER_CONTROL = 'input[type=checkbox][data-layer-id]';
  let layerWatcher = null;

  function watchForLayerControls(onReady) {
    if (layerWatcher || typeof MutationObserver !== 'function') return;
    try {
      layerWatcher = new MutationObserver(() => {
        if (!document.querySelector(LAYER_CONTROL)) return;
        layerWatcher.disconnect();
        layerWatcher = null;
        link.layer_controls_arrived_late = true;
        recoverFailures(/^the engine had not rendered its layer controls within/);
        clearStatus();
        try { onReady(); } catch (error) {
          link.failures.push('late layers: ' + String(error?.message || error));
        }
      });
      layerWatcher.observe(document.body, { childList: true, subtree: true });
    } catch (error) {
      link.failures.push('layer watcher: ' + String(error?.message || error));
      layerWatcher = null;
    }
  }

  /* iOS Safari, reported live by the architect and reproduced independently
     against a page opened hidden: this budget used to be charged in WALL
     CLOCK time regardless of whether anyone could see the result of
     spending it. Pipeline News' MAP control opens on touch devices with
     target="_blank", and on iOS Safari a background tab is not guaranteed
     to be composited while the reader is still looking at the page they
     tapped from -- requestAnimationFrame does not tick there, so the
     engine's own dashboard build (which the boot trigger gates behind
     style.load/load, both paint-driven) can stall for the WHOLE budget
     without ever having had a real chance. Elapsed time while hidden buys
     nothing observable and is not charged against the budget; only time
     the tab was actually visible counts down. */
  async function waitForLayerControls(budgetMs) {
    let elapsed = 0;
    const started = Date.now();
    /* Visible time governs the BUDGET; wall clock still bounds the WAIT.