GLOBALGRID2050 / EXPLORE CODE

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

Secondary Neon Engine (part 9)

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 564 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 6048–6747

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 6048–6747 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
trayTarget, engineLayerBox, installMobileTray, quickChip, reflect, installGbConditions, setSourceData, interactiveLayerIds, install, selectAt, validPoint, classifyEngine, answerArrival, waitForResolvedIdentity, runDeepLink
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:6048-6747 · 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
      injectStatusStyle();
      showStatus('Reading the substation data for this area.', 'waiting');
    }
    const subs = await loadSubstations();
    if (!subs.length) {
      injectStatusStyle();
      showStatus('The substation data did not load, so nothing can be counted '
        + 'here. This is usually the network rather than the place.', 'failed');
      return;
    }
    clearStatus();
    const result = scope.scope(origin, subs, { nearestCount: 5 });

    /* Ask what could have answered, before saying what did.
       ------------------------------------------------------------------
       The deep scan of 202609012230 found this path reporting only what
       OpenStreetMap has mapped while the cartridge holding NESO's 886
       published connection points sat loaded in the same page. The scope
       still counts only what it can count - widening the computation is a
       separate, provable change - but it no longer stays silent about the
       sources it did not use. */
    const registry = window.__GRIDATLAS_MODULES__?.sourceRegistry || null;
    if (registry) {
      try { result.sources = registry.survey(window); }
      catch (error) { noteFailure('source registry: ' + String(error?.message || error)); }
    }

    scopeResult = result;
    link.grid_scope = { counted: result.counted, radius_km: result.radius_km,
      nearest_km: result.nearest[0]?.km ?? null,
      sources_ready: result.sources?.ready || null,
      sources_missing: result.sources?.missing || null };

    if (ensureScopeLayers(map)) {
      /* The bands are drawn in metres-per-pixel at the current zoom, so a
         ring means the distance it says at the zoom it was drawn. */
      const metresPerPixel = 156543.03392
        * Math.cos(origin[1] * Math.PI / 180) / Math.pow(2, map.getZoom());
      const features = result.bands.map(band => ({
        type: 'Feature',
        properties: { kind: 'band', pixels: (band.within_km * 1000) / metresPerPixel },
        geometry: { type: 'Point', coordinates: origin }
      })).concat(result.nearest.map(entry => ({
        type: 'Feature', properties: { kind: 'site' },
        geometry: { type: 'Point', coordinates: entry.at }
      })));
      setSourceData(map, SCOPE_SRC, { type: 'FeatureCollection', features });
    }

    const gl = window.maplibregl;
    if (gl?.Popup) {
      try {
        new gl.Popup({ maxWidth: '360px', closeOnClick: false })
          .setLngLat(origin)
          .setHTML(scopeHtml(result))
          .addTo(map);
      } catch (error) {
        noteFailure('grid scope card: ' + String(error?.message || error));
      }
    }
  }

  /* ── the mobile tray ──────────────────────────────────────────────────
     Vikram's phone acceptance, 2026-09-01: the six shell tool buttons at
     44px touch height are the right size to hit and the wrong size to keep
     on screen - a third of a portrait map behind buttons - and the switches
     that turn the grid lines and substations on live below the map, where a
     phone never looks. Both are composition faults, not engine faults: the
     44px rule is this cartridge's own coarse-pointer override, and the
     engine's switches work - toggled live in Chrome, the lines drew at once.

     So on a touch screen or a narrow window the six tool buttons collapse
     behind one chip, and two first-class chips - GRID and SUBS - stand on
     the map itself. They drive the engine's own checkboxes with real
     clicks, the same path enableTechnologyLayer has used all along, so the
     scada panel, the fullscreen curtain and these chips cannot disagree. */
  const TRAY_ID = 'gridatlas-mobile-tray';
  const GRID_LINE_LAYERS = ['400', '275', '220', '132', '66'];

  function trayTarget() {
    try {
      return matchMedia('(pointer: coarse)').matches || window.innerWidth <= 700;
    } catch (_) { return false; }
  }

  function engineLayerBox(id) {
    return document.querySelector(
      '#scada-ui-container input[type=checkbox][data-layer-id="' + id + '"]');
  }

  function installMobileTray() {
    if (document.getElementById(TRAY_ID)) return;
    // V9.202: same native quick chips are available on wide screens too.
    const stack = document.querySelector('.map-controls');
    if (!stack) { link.failures.push('no map-controls for the tray'); return; }

    const style = document.createElement('style');
    style.id = TRAY_ID + '-style';
    style.textContent = SLD_STYLES.mobileTray(TRAY_ID);
    document.head.appendChild(style);

    stack.classList.add('gm-tools-collapsed');

    const tray = document.createElement('div');
    tray.id = TRAY_ID;

    const tools = document.createElement('button');
    tools.type = 'button';
    tools.textContent = 'Tools \u25b8';
    tools.setAttribute('aria-expanded', 'false');
    tools.addEventListener('click', (event) => {
      event.stopPropagation();
      const collapsed = stack.classList.toggle('gm-tools-collapsed');
      tools.textContent = collapsed ? 'Tools \u25b8' : 'Tools \u25be';
      tools.setAttribute('aria-expanded', String(!collapsed));
    });

    function quickChip(labelText, ids) {
      const chip = document.createElement('button');
      chip.type = 'button';
      chip.textContent = labelText;
      chip.disabled = true;
      chip.setAttribute('aria-pressed', 'false');
      function reflect() {
        const boxes = ids.map(engineLayerBox).filter(Boolean);
        chip.disabled = boxes.length === 0;
        chip.setAttribute('aria-pressed',
          String(boxes.length > 0 && boxes.every((box) => box.checked)));
      }
      chip.addEventListener('click', (event) => {
        event.stopPropagation();
        const boxes = ids.map(engineLayerBox).filter(Boolean);
        if (!boxes.length) return;
        const turnOn = boxes.some((box) => !box.checked);
        boxes.forEach((box) => { if (box.checked !== turnOn) box.click(); });
        reflect();
      });
      chip.gmReflect = reflect;
      return chip;
    }

    /* The tray tool. The shell owns .map-controls and the shell is
       immutable, so the button is added by this cartridge at runtime and
       removed again if the cartridge is not composed - there is no orphan
       control left behind claiming a feature that is not present. */
    (function addGridPointTool() {
      const tray = document.querySelector('.map-controls');
      if (!tray || document.getElementById('btn-gridpoint')) return;
      const button = document.createElement('button');
      button.className = 'map-ctrl-btn';
      button.id = 'btn-gridpoint';
      button.type = 'button';
      button.textContent = '\u25c8 Grid At Point';
      button.setAttribute('aria-pressed', 'false');
      button.title = 'Click anywhere on the map for the published network at the nearest mapped connection point';
      button.addEventListener('click', (event) => {
        event.stopPropagation();
        pointArmed = !pointArmed;
        button.setAttribute('aria-pressed', String(pointArmed));
        button.style.outline = pointArmed ? '1px solid currentColor' : '';
        link.grid_point_armed = pointArmed;
        if (!pointArmed) clearScope();
      });
      tray.appendChild(button);
    }());

    const grid = quickChip('\u26a1 Grid', GRID_LINE_LAYERS);
    const subs = quickChip('\u25c9 Subs', ['subs']);

    /* Arming is explicit. A map that analysed every stray tap would put a
       card over the thing the reader was trying to look at. */
    const scopeChip = document.createElement('button');
    scopeChip.type = 'button';
    scopeChip.textContent = '\u25ce Scope';
    scopeChip.setAttribute('aria-pressed', 'false');
    scopeChip.addEventListener('click', (event) => {
      event.stopPropagation();
      scopeArmed = !scopeArmed;
      scopeChip.setAttribute('aria-pressed', String(scopeArmed));
      if (!scopeArmed) clearScope();
      link.grid_scope_armed = scopeArmed;
    });

    const clearChip = document.createElement('button');
    clearChip.type = 'button';
    clearChip.textContent = '\u2715 Clear';
    clearChip.addEventListener('click', (event) => {
      event.stopPropagation();
      clearScope();
      clearLinks();
    });

    tray.appendChild(tools);
    tray.appendChild(grid);
    tray.appendChild(subs);
    tray.appendChild(scopeChip);
    tray.appendChild(clearChip);
    tray.addEventListener('click', (event) => event.stopPropagation());
    stack.insertBefore(tray, stack.firstChild);

    // The engine builds its switches only after the map loads; the chips
    // wake when the switches exist and follow them wherever they are
    // toggled from - scada panel, fullscreen curtain, or a deep link.
    document.addEventListener('change', (event) => {
      if (event.target?.dataset?.layerId) { grid.gmReflect(); subs.gmReflect(); }
    });
    let polls = 0;
    const poll = setInterval(() => {
      grid.gmReflect(); subs.gmReflect(); polls += 1;
      if (!grid.disabled || polls > 200) clearInterval(poll);
    }, 300);

    link.mobile_tray = {
      installed: true,
      tools_collapsed: true,
      grid_quick_layers: GRID_LINE_LAYERS.length,
      subs_quick: true
    };
  }

  function installGbConditions() {
    if (document.getElementById(GB_ID)) return;
    const stack = document.querySelector('.map-controls');
    if (!stack) { link.failures.push('no map-controls for the GB panel'); return; }

    const style = document.createElement('style');
    style.id = GB_ID + '-style';
    style.textContent = SLD_STYLES.gbConditions(GB_ID);
    document.head.appendChild(style);

    const panel = document.createElement('div');
    panel.id = GB_ID;
    panel.dataset.open = '0';
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = 'GB prices · historic ▸';
    button.setAttribute('aria-expanded', 'false');
    const body = document.createElement('div');
    body.className = 'gb-body';
    panel.appendChild(button);
    panel.appendChild(body);

    let loaded = false;
    button.addEventListener('click', (event) => {
      // The panel lives inside the map container, so without this the click
      // carries on to the map underneath and selects whatever is there.
      event.stopPropagation();
      event.preventDefault();
      const open = panel.dataset.open === '1';
      panel.dataset.open = open ? '0' : '1';
      button.textContent = open ? 'GB prices · historic ▸' : 'GB prices · historic ▾';
      button.setAttribute('aria-expanded', String(!open));
      // Fetched on first open, never at boot: nothing about the map should
      // wait on a third party, and most sessions never open this.
      if (!open && !loaded) {
        loaded = true;
        body.innerHTML = '<p class="gb-note">Reading the decade…</p>';
        renderGbConditions(body);
      }
    });
    panel.addEventListener('click', (event) => event.stopPropagation());
    stack.appendChild(panel);
    link.gb_panel_installed = true;
  }

  /* Never dereference a source without checking it is there.
     ----------------------------------------------------------------------
     addSource throws if the style is not loaded, and a source that failed to
     add reads back as null. Both happen: the basemap CDN served style.json and
     then no tiles at all on this estate tonight, and the cartridge now boots on
     the style rather than a painted frame precisely so it can work in that
     condition.

     The pin was guarded when that was found. Five call sites were not, and
     they are the ones that draw the links, the nodes and the whole layout — so
     the guarded convenience survived while the substance would have thrown.
     Codex's gate has been finding this class all night; this is the last of it
     in this file.

     Returning false rather than throwing means a missing source costs the
     drawing, not the card, the distances or the session. */
  function setSourceData(map, id, data) {
    try {
      const source = map?.getSource?.(id);
      if (!source || typeof source.setData !== 'function') {
        link.failures.push('source missing, nothing drawn: ' + id);
        return false;
      }
      source.setData(data);
      return true;
    } catch (error) {
      link.failures.push('source ' + id + ': ' + String(error?.message || error));
      return false;
    }
  }

  function interactiveLayerIds(map) {
    // Whatever the engine has made visible and interactive. Reading the style
    // rather than hard-coding ids keeps this working as layers come and go.
    try {
      return map.getStyle().layers
        .filter(layer => /^l-/.test(layer.id) && layer.type !== 'background')
        .map(layer => layer.id)
        .filter(id => {
          try { return map.getLayoutProperty(id, 'visibility') !== 'none'; }
          catch (_) { return false; }
        });
    } catch (_) {
      return [];
    }
  }

  function install(map) {
    const computeObserver = globalThis.VentusGridCompute.createComputeObserver({
      onEvent(receipt) {
        if (computeObserver.snapshot()?.id !== receipt.id) return;
        link.compute_receipt = receipt;
        renderComputeReceipt();
      }
    });
    installStyles();
    ensureLayers(map);

    /* Warm the substation payload immediately. It is 1.2 MB and every
       measurement needs it; until v9.54 it was first requested only after
       the arrival had finished waiting for the engine's layer controls,
       so a phone paid for the wait AND the fetch in series. The promise is
       cached, so the arrival reuses whatever this started. */
    try { loadSubstations(); } catch (_) { /* the arrival will retry */ }

    // The lines belong to the card. When the card closes, they go with it --
    // leaving neon on the map with nothing explaining it is how a screenshot
    // ends up quoted without its caveat.
    const popupWatcher = new MutationObserver(() => {
      if (link.links_drawn > 0 && !document.querySelector('.maplibregl-popup')) clearLinks();
    });
    try {
      popupWatcher.observe(map.getContainer(), { childList: true, subtree: true });
    } catch (error) {
      link.failures.push(String(error?.message || error));
    }

    // Registered after the engine's own click handler, so the engine's popup
    // opens first and this decorates it rather than racing it.
    // Measure and draw for one selection. Split out of the click handler so a
    // deep link, which opens a card without anybody clicking, goes through
    // exactly the same path.
    async function selectAt(origin, name, tech, fromSubstation, statedMw,
      expectedArrivalEpoch = null) {
      const fromCurrentArrival = Number.isInteger(expectedArrivalEpoch);
      if (fromCurrentArrival) {
        if (!arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
      } else {
        invalidatePendingArrival('new-selection');
      }
      clearScope();
      // Keep a provisional declared block standing until the measured one
      // replaces it; clearing here would blank the card mid-arrival.
      if (!currentDeclared?.pending) currentDeclared = null;
      currentNearest400 = null;
      currentPolicy = null;
      if (fromSubstation) {
        // No fetch needed: the projects are already in the engine's own
        // source, and reading them there keeps one set of coordinates.
        const found = nearestProjects(map, origin[0], origin[1]);
        drawLinks(map, origin, name, tech, found.links, 'from-substation',
          null, found.loaded);
        /* drawLinks deliberately skips the sentinel for this direction, because
           the engine class is read from the project's technology and a
           substation has none. The question was still asked and still answered,
           so it is named here with its own class rather than left blank and
           counted as an engine that went quiet. */
        try {
          answerArrival('substation-origin', found.links.length > 0,
            found.links.length ? null : 'NO_PROJECTS_NEAR_SUBSTATION', null);
        } catch (_) {}
        return true;
      }
      /* OFFSHORE MEASURES NOW.
         --------------------------------------------------------------------
         This used to return here with an empty link list and a card that
         explained why nothing was measured. It measures instead. An offshore
         project reaches an offshore substation, an export cable and a
         landfall before anything onshore - every word of that is still true
         and still printed - but the export cable does land at an onshore
         substation, so the distance to the nearest mapped one is a
         measurement of a real thing rather than a number with nothing behind
         it. Withholding it was over-caution.

         The route reasoning is not deleted; it moves from being the reason
         there is no number to being the caveat beside the number, which is
         where the estate puts every other thing a distance cannot answer.

         No onshore-only filter is applied, and the card says so. The pinned
         substation product carries the OSM `location` tag on zero of its
         5,800 features, and of the 14 whose NAME contains "offshore" at least
         4 are onshore substations serving an offshore farm - Hornsea at
         400/220 kV among them, which is exactly a landfall connection. A
         name-based filter would drop those four from the search it was meant
         to sharpen. Measured, not assumed; the module carries the counts. */
      const policy = coverage.policy(tech);
      currentPolicy = policy;
      if (!link.substations_qualifying) {
        injectStatusStyle();
        showStatus('Loading the substation data \u2014 the links need it.',
          'waiting');
      }
      const computeEntity = { kind: currentRepdRef ? 'repd' : 'location',
        id: currentRepdRef || JSON.stringify(origin) };
      const computeOrigin = { lon: origin[0], lat: origin[1] };
      const computeId = computeObserver.request({ entity: computeEntity, location: computeOrigin,
        dataset: 'GridAtlas pinned substation payload; geometric nearest screening' });
      const subs = await loadSubstations();
      if (fromCurrentArrival && !arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
      if (!subs.length) {
        /* The register carries 5,800 substations; zero qualifying means the
           payload did not arrive, not that the map is empty here. Drawing
           nothing silently is how this looked broken on a phone. */
        injectStatusStyle();
        showStatus('The substation data did not load, so no links can be '
          + 'drawn. This is usually the network rather than the project.',
          'failed');
        /* The single terminus for every network failure on this path:
           loadSubstations() catches its own rejection and returns [], so a
           dead CDN, a blocked fetch and a corrupt payload all arrive here.
           It was also the highest-traffic way an arrival ended with nothing
           on the record. `return false`, not a bare return, because a bare
           return is undefined and the caller reads undefined as success. */
        try {
          answerArrival(classifyEngine(String(tech || ''), null), false,
            'SUBSTATION_PAYLOAD_ABSENT', null);
          await computeObserver.run(computeId, () => { throw new Error('Substation payload unavailable'); });
        } catch (_) {}
        return false;
      }
      clearStatus();
      currentDeclared = resolveDeclaredConnection(currentRepdRef, origin, subs);
      currentNearest400 = nearestTransmission(origin, subs);
      /* Awaited before the card is drawn, because a connection the authority
         has issued is the headline fact and arriving after the measurement
         would make it look like an afterthought. The file is 130 KB and
         cached, so this costs one request per session. */
      try { currentNeso = await resolveNesoConnection(currentRepdRef, origin, subs); }
      catch (_) { currentNeso = null; }
      let measured;
      const receipt = await computeObserver.run(computeId, () => {
        measured = nearestSubstations(origin[0], origin[1], subs);
        const answer = measured.length ? measured : (measured.beyondRadiusNearest ? [measured.beyondRadiusNearest] : []);
        return { entity: computeEntity, origin: computeOrigin, search_completed: true, scanned_count: subs.length,
          measurements: answer.map((node, index) => ({ node_id: String(node.id || node.name || index),
            lon: node.at[0], lat: node.at[1], km: node.km })) };
      });
      if (!computeObserver.assess(computeId, { entity: computeEntity, location: computeOrigin }).passed) {
        if (receipt.status !== 'completed_empty') return false;
      }
      if (fromCurrentArrival && !arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
      drawLinks(map, origin, name, tech, measured, 'to-substation', statedMw);
      return true;
    }
    link.selectAt = selectAt;
    // Secondary assets share the native renderer but are not REPD projects.
    link.drawSecondaryLinks = ({site, origin, nodes} = {}) => {
      const validPoint = p => Array.isArray(p) && p.length===2 && p.every(Number.isFinite) && Math.abs(p[0])<=180 && Math.abs(p[1])<=90;
      const card = map.getContainer().querySelector('[data-ukpn-detail][data-site]');
      if (typeof site !== 'string' || card?.dataset.site !== site || !validPoint(origin) || !Array.isArray(nodes) || !nodes.length || nodes.length>5) return false;
      const feature = map.getSource('src-ukpn_secondary')?.serialize()?.data?.features?.find(f => String(f.id)===site);
      if (feature?.geometry?.type!=='Point' || feature.geometry.coordinates.some((v,i)=>v!==origin[i])) return false;
      if (!nodes.every(n=>validPoint(n.at)&&Number.isFinite(n.km)&&n.km>0&&Number.isFinite(n.kv)&&n.kv>=33)) return false;
      clearLinks(); clearScope(); lastSelection=null; currentPolicy=null;
      const links = nodes.map(n=>({name:String(n.name),at:n.at.slice(),km:n.km,kv:[n.kv]}));
      return drawLinks(map, origin.slice(), site, null, links, 'from-secondary', null) === true;
    };
    link.clearSecondaryLinks = site => {
      if (link.last_selection?.direction==='from-secondary' && (!site || link.last_selection.name===site)) clearLinks();
    };

    /* The class selects the question. It never selects whether a question is
       answered: every arrival leaves one of these behind, and an engine that
       cannot answer names its reason instead of going quiet. */
    function classifyEngine(tech, q) {
      try {
        if (q && (q.get('interconnector') || String(q.get('technology') || '') === 'interconnector')) return 'interconnector';
      } catch (_) { /* no query is not an interconnector */ }
      try { return coverage.policy(tech)?.offshore ? 'offshore' : 'onshore'; }
      catch (_) { return 'onshore'; }
    }
    /* Delegates. There is one writer of this record and it lives at module
       scope, because the paths that most need it - install() throwing, no
       style at all - are outside install() and cannot see anything declared
       in here. Two writers would drift, and the epoch and the DOM mirror
       would end up on one of them. */
    function answerArrival(engine, answered, reason, fallbackFrom, pending = false) {
      return recordArrivalEngine(engine, answered, reason, fallbackFrom, pending);
    }
    link.measure.answerArrival = answerArrival;
    link.measure.classifyEngine = classifyEngine;

    map.on('click', async (event) => {
      try {
        if (fromOwnUi(event)) return;
        const ids = interactiveLayerIds(map);
        if (!ids.length) {
          /* A click on a project the reader can plainly see, at a moment when
             no interactive layer is registered - the layers are still off, or
             the style is being repopulated. Nothing happens and nothing is
             said, which reads as a dead map. Only written when no answer is
             standing, so a working answer is never overwritten by a stray
             click on the basemap. */
          if (!link.arrival_engine) {
            try { answerArrival('onshore', false, 'NO_INTERACTIVE_LAYERS', null); } catch (_) {}
          }
          return;
        }
        let features = [];
        try { features = map.queryRenderedFeatures(event.point, { layers: ids }); }
        catch (_) {
          try { answerArrival('onshore', false, 'QUERY_RENDERED_FEATURES_THREW', null); } catch (_) {}
          return;
        }
        if (!features.length) { clearLinks(); return; }

        // Either end of a link is a valid place to start. Whichever pixel was
        // clicked, the card that came up is the one the distances are written
        // onto, and the lines run to the other end.
        const hit = features.find(feature => {
          const properties = feature.properties || {};
          const tech = String(properties.tech || properties.type || '');
          return isProjectTech(tech) || feature.layer?.id === SUBS_LAYER_ID;
        });
        if (!hit) {
          /* The anchor is untouched: a project or substation click still
             draws the neons. Only a click that hit NEITHER reaches here,
             and only then if the reader armed the scope. */
          clearLinks();
          if (pointArmed) await runGridAtPoint(map, event.lngLat.lng, event.lngLat.lat);
          if (scopeArmed) await runGridScope(map, [event.lngLat.lng, event.lngLat.lat]);
          return;
        }

        const properties = hit.properties || {};
        const fromSubstation = hit.layer?.id === SUBS_LAYER_ID;
        const tech = String(properties.tech || properties.type || '');
        const origin = representativePoint(hit.geometry)
          || [event.lngLat.lng, event.lngLat.lat];
        const name = properties.name || properties.SiteName || properties['Site Name']
          || (fromSubstation ? 'Unnamed substation' : 'Unnamed project');
        const stated = Number(properties.capacity);
        currentRepdRef = fromSubstation
          ? null : String(properties.repd_ref || properties.repdRef || '');
        await selectAt(origin, name, tech, fromSubstation,
          Number.isFinite(stated) && stated > 0 ? stated : null);
      } catch (error) {
        /* A click that throws leaves the reader looking at an unchanged map.
           The failure was already recorded where only a developer would find
           it; the engine now names it too. */
        try { answerArrival('onshore', false, 'MAP_CLICK_THREW', null); } catch (_) {}
        link.failures.push(String(error?.message || error));
      }
    });

  /* ── arrival by identity ─────────────────────────────────────────────
     The search cartridge resolves repd_ref against the register - DuckDB
     over the pinned parquet - flies there and opens the card. When a link
     carries only that identity, this lane used to stop at its URL guards
     while the card opened anyway, which reads as a broken map. The register
     knows the coordinates and technology better than any URL restatement,
     so when the identity lane has resolved, its published result is the
     arrival. One resolver per composition; this lane only consumes.

     The budget is generous because the identity lane boots a 35.7 MB query
     engine first on a cold phone. Terminal failure or absence returns null
     and is the caller's decision to record. */
  async function waitForResolvedIdentity(options = {}) {
    const announce = options.announce !== false;
    /* v9.44 gave this a fixed 120s budget and Vikram's phone exceeded it:
       the identity lane boots a 35.7 MB query engine first, the budget
       expired, this lane gave up permanently, and the card then opened
       anyway - a resolved identity with nothing computed for it. The
       estate's own late-layers lesson, relearned: a fixed budget is always
       the wrong number. RESOLVED, FAILED and ABSENT are terminal; the only
       unbounded case is "still working", and waiting through it is the
       correct behaviour. The user is told what is being waited for; ten
       minutes is kept as a last-resort stop for a lane that died silently. */
    const started = Date.now();
    let told = false;
    for (;;) {
      const dl = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link;
      if (dl) {
        if (dl.status === 'RESOLVED') { if (told) clearStatus(); return dl; }
        /* RESOLVED_UNMAPPED was missing from this list, and it is terminal: the
           identity lane has finished, found the project in the register, and
           established that neither REPD nor a Crown Estate lease gives it a
           location. Treating it as "still working" made this loop spin for its
           full ten minutes and then report an identity failure that had not
           happened - so the page sat at the default GB view saying nothing at
           all. Measured on REPD 13432 (Marram), reported live by the owner:
           "Didn't even go to anything". */
        if (dl.status === 'FAILED' || dl.status === 'ABSENT'
            || dl.status === 'NOT_IN_ACTIVE_REGISTER'
            || dl.status === 'RESOLVED_UNMAPPED'
            || dl.status === 'CANCELLED') {
          if (told) clearStatus();
          return dl;
        }
      }
      const waited = Date.now() - started;
      if (announce && !told && waited > 6000) {
        told = true;
        injectStatusStyle();
        showStatus('Resolving the project against the register \u2014 a cold '
          + 'phone boots the query engine first, and this can take a minute.',
          'waiting');
      }
      if (waited > 600000) {
        link.failures.push('identity lane still not terminal after 10 minutes');
        if (told) clearStatus();
        return null;
      }
      await new Promise(resolve => setTimeout(resolve, 250));
    }
  }

    // A deep link opens the project card on its own, with no click anywhere.
    // Arriving that way is how most people reach the Atlas -- the MAP button in
    // Pipeline News sends them here -- so the measurement has to run for it
    // too, or the card that brought them arrives with nothing on it.
    async function runDeepLink(expectedArrivalEpoch = null) {
      try {
        const q = new URLSearchParams(window.location.search);
        /* An interconnector arrival is not a project arrival. Pipeline News'
           INTERCONNECTORS tab sends interconnector=<BMRS>&technology=
           interconnector with a label anchor - the node drawn mid-line, or
           the GB converter - and measuring a generator from that point would
           report the sea (a BritNed midpoint is 59.2 km from the nearest
           substation). The interconnectors module owns this arrival: it
           frames the span and measures each converter within its own search
           budget. This lane records the handover and does nothing else. */
        if (q.get('interconnector') || String(q.get('technology') || '') === 'interconnector') {
          link.arrival_reconciliation = {
            status: 'HANDED_TO_INTERCONNECTORS',
            interconnector: q.get('interconnector') || null,
            statement: 'interconnector arrival; the project engine does not measure from a label anchor'
          };
          /* v9.148 recorded this handover as a comment reading "answered by the
             interconnector engine, not unanswered" and wrote nothing. It was
             the only claim in that version that was not implemented, and it
             left every interconnector arrival with arrival_engine === null in
             every branch - indistinguishable from an engine that never ran.

             So the handover writes the record itself: the interconnector engine
             owns this arrival and has not answered yet. The interconnectors
             module overwrites it with the real outcome, and if that module
             never boots, this stands and says which engine went quiet. */
          recordArrivalEngine('interconnector', false, 'HANDED_TO_INTERCONNECTORS', null, true);
          // the interconnectors module measures the GB converter against this payload
          try { void loadSubstations(); } catch (_) { /* best effort; the module reports absent coverage honestly */ }
          return false;
        }
        const epoch = Number.isInteger(expectedArrivalEpoch)
          ? expectedArrivalEpoch : claimPendingArrival(window.location.search);
        if (!arrivalGate.isCurrent(epoch)) return false;
        link.arrival_reconciliation = {
          status: 'MEASUREMENT_CLAIMED', epoch,
          owner_epoch: window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.owner_epoch ?? null
        };
        /* Number(null) is 0, not NaN, so a link with no coordinates used to
           pass the finite guard as Null Island and only the technology
           guard stopped it. Absent now means absent. */
        const rawLon = q.get('longitude');
        const rawLat = q.get('latitude');
        const receiverPlan = deepLinkPlan(rawLon, rawLat, q.get('repd_ref'));
        let lon = receiverPlan.longitude;
        let lat = receiverPlan.latitude;
        const repdRef = receiverPlan.repd_ref;
        let tech = String(q.get('technology') || '');
        let name = q.get('project') || 'Deep-linked project';
        let stated = Number(q.get('capacity_mw'));
        const suppliedStatus = String(q.get('status') || '').trim();
        currentCapacityMw = Number.isFinite(stated) && stated > 0 ? stated : null;

        /* zoom: set on every deep link, and until now read by nobody.
           ------------------------------------------------------------------
           The deep scan of 202609012230 compared both sides of the contract:
           Pipeline News sets seven parameters and GridAtlas read six. There is
           no get('zoom') anywhere in this repository. Arrival zoom came from
           `map.flyTo({ zoom: 12 })` hard-coded in the immutable shell, and
           Pipeline News happens to send 12 - so the two agreed by coincidence,
           and the day somebody tuned the sending side nothing would have moved.

           The shell cannot be edited, so the cartridge honours the parameter
           after the shell has finished its own move. Bounded to what MapLibre
           and the payload can actually render, and a value outside that range
           is recorded rather than clamped silently. */
        const rawZoom = q.get('zoom');
        const requestedZoom = rawZoom === null ? null : Number(rawZoom);
        const zoomUsable = requestedZoom !== null && Number.isFinite(requestedZoom)
          && requestedZoom >= 3 && requestedZoom <= 18;
        if (rawZoom !== null && !zoomUsable) {
          link.failures.push('deep link: unusable zoom "' + rawZoom + '"');
        }