GLOBALGRID2050 / EXPLORE CODE

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

Secondary Neon Engine (part 10)

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 565 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 6748–7447

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 6748–7447 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
framed, honourRequestedZoom, apply, isFalseOrigin, coordsUsable, enableBoth, arrive, runArrivalSelection, arrivalHasVisibleOutcome, attemptArrival, attach, boot, bootOnce, PatchedMap
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:6748-7447 · 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
        link.requested_zoom = zoomUsable ? requestedZoom : null;

        /* 12 shows 3.6x more ground at 1400 px than at 393, so a shared
           link opens wide on a desktop. Frame by viewport, not by number. */
        const framed = () => Math.min(18, Math.max(3, requestedZoom
          + Math.log2(Math.max(innerWidth, 320) / 393)));
        function honourRequestedZoom(map) {
          if (!zoomUsable) return;
          /* One shot, after the shell's own flyTo has settled. Racing it
             would be a fight the shell wins, and re-applying on every idle
             would take the map away from a user who has since zoomed. */
          let done = false;
          const apply = () => {
            if (done) return;
            done = true;
            try {
              map.off('idle', apply);
              /* The link asked for a zoom; the declared connection asked for a
                 frame that holds both ends. The frame wins, because a zoom the
                 link chose before it knew the far end was 80 km away would cut
                 that end off - measured in Chromium on Hornsea 3, where this
                 eased in from the fitted view and pushed the array above the
                 top edge. WebKit only escaped by timing. */
              if (link.declared_connection_framed) {
                link.zoom_applied = 'declared frame kept';
                return;
              }
              if (Math.abs(map.getZoom() - framed()) < 0.01) {
                link.zoom_applied = 'already there';
                return;
              }
              map.easeTo({ zoom: framed(), duration: 400 });
              link.zoom_applied = framed();
            } catch (error) {
              noteFailure('deep link zoom: ' + String(error?.message || error));
            }
          };
          try { map.once('idle', apply); } catch (_) { /* shimmed map in a proof */ }
          // A map that never goes idle must not swallow the request.
          setTimeout(apply, 2600);
        }
        /* Null Island is not the only placeholder. The register carries a
           second one - 49.766807 N, 7.55716 W, in the Western Approaches
           south-west of the Scillies - on fifteen of its ninety-seven offshore
           wind rows, among them Dogger Bank South East and West, Morgan,
           Ossian, Muir Mhor and North Falls. The search cartridge has rejected
           it since v9.145 as FALSE_ORIGIN; this engine did not, so a project in
           the North Sea could be measured to Isles Of Scilly Primary
           Substation and the distance printed as fact. A false measurement is
           worse than a stated silence. */
        const FALSE_ORIGIN = { longitude: -7.55716, latitude: 49.766807 };
        const isFalseOrigin = (x, y) => Math.abs(x - FALSE_ORIGIN.longitude) < 1e-4
          && Math.abs(y - FALSE_ORIGIN.latitude) < 1e-4;
        const coordsUsable = () => Number.isFinite(lon) && Number.isFinite(lat)
          && Math.abs(lon) <= 180 && Math.abs(lat) <= 90
          && !(Math.abs(lon) < 1e-9 && Math.abs(lat) < 1e-9)
          && !isFalseOrigin(lon, lat);

        /* Vikram, phone acceptance 13:01: "arrive in full screen mode from
           pipeline news with all the clutter minimised". On a touch screen
           the normal page is a small map fighting a popup, chips, a HUD and
           a panel below; fullscreen is the only honest arrival surface. The
           shell's own control does it - CSS classes, and on an iPhone the
           element fullscreen API simply does not exist, so nothing here is
           gesture-gated - and the tray keeps the tool buttons collapsed. */
        if ((q.get('repd_ref') !== null || coordsUsable()) && trayTarget()) {
          try {
            window.enterFullscreen?.();
            link.arrival_fullscreen = true;
            setTimeout(() => { try { map.resize(); } catch (_) { /* cosmetic */ } }, 120);
          } catch (error) {
            link.failures.push('arrival fullscreen: ' + String(error?.message || error));
          }
        }

        /* A VALID LINK POINT ANSWERS FIRST; THE REGISTER VERIFIES IT.
           ---------------------------------------------------------
           v9.91 put `await waitForResolvedIdentity()` before selectAt for every
           repd_ref. Across Pipeline News that serialized a 35.7 MB query
           engine ahead of 8,743 links that already carried a usable point;
           2,430 then waited only to fall back to that same point. Coordinates
           are enough for a geometric measurement. They are therefore used at
           once, explicitly as link-supplied, while the one identity owner
           verifies them concurrently. A different resolved point replaces the
           selection and is measured again; FAILED/ABSENT never erases a valid
           supplied point. A ref-only link still waits because it has no point
           from which an honest measurement can be made. */
        let identityVerification = null;
        if (receiverPlan.route === 'MEASURE_LINK_FIRST' && repdRef) {
          link.origin_source = 'link-supplied';
          link.deep_link_identity = 'verifying-concurrently';
          link.identity_verification = {
            status: 'PENDING', repd_ref: repdRef, supplied_coordinates_used: true
          };
          identityVerification = waitForResolvedIdentity({ announce: false })
            .then((owner) => ({
              resolved: owner?.status === 'RESOLVED' ? owner : null,
              terminal: owner?.status || 'UNKNOWN'
            }))
            .catch((error) => ({ resolved: null, terminal: 'FAILED', error }));
        } else if (receiverPlan.route === 'WAIT_FOR_REGISTER') {
          /* A ref-only link has no safe provisional geometry. This is the one
             case that must await the identity owner before measuring. */
          const owner = await waitForResolvedIdentity();
          /* Split, because these are two different facts wearing one guard. A
             stale epoch means a newer arrival has taken the map and is about to
             publish its own answer, so this one must say nothing or it would
             overwrite a live answer with a dead one. A CANCELLED owner means
             this arrival really did end, and that has to be named. */
          if (!arrivalGate.isCurrent(epoch)) return;
          if (owner?.status === 'CANCELLED') {
            try { answerArrival(classifyEngine(String(tech || ''), q), false, 'IDENTITY_OWNER_CANCELLED', null); } catch (_) {}
            return;
          }
          if (owner?.status === 'RESOLVED') {
            const resolved = owner;
            const rLon = Number(resolved.longitude);
            const rLat = Number(resolved.latitude);
            if (Number.isFinite(rLon) && Number.isFinite(rLat)
              && Math.abs(rLon) <= 180 && Math.abs(rLat) <= 90
              && !(Math.abs(rLon) < 1e-9 && Math.abs(rLat) < 1e-9)) {
              lon = rLon;
              lat = rLat;
              link.origin_source = 'register';
            }
            if (typeof resolved.technology === 'string' && resolved.technology) {
              tech = resolved.technology;
            }
            if (resolved.name) name = String(resolved.name);
            const cap = Number(resolved.capacity_mw);
            if (Number.isFinite(cap) && cap > 0) stated = cap;
            currentCapacityMw = Number.isFinite(stated) && stated > 0 ? stated : null;
            link.deep_link_identity = 'resolved-by-search-lane';
          } else if (owner?.status === 'RESOLVED_UNMAPPED') {
            /* The register knows this project and cannot place it. That is a
               different fact from "not in the register" and a different fact
               again from "the identity check failed", and it deserves its own
               words: the name, capacity and reference are real and are shown;
               the location is absent, so nothing is measured and nothing is
               claimed. Thirteen offshore wind rows are in this state today,
               including Marram, Muir Mhor and Morecombe.

               The engine is not silent about it and the camera does not move,
               because moving it would put the reader somewhere that is not the
               project. */
            link.origin_source = 'register-resolved-without-a-coordinate';
            link.deep_link_identity = 'terminal-resolved-unmapped';
            link.identity_verification = {
              status: 'RESOLVED_UNMAPPED', repd_ref: repdRef,
              official_active_register_match: true,
              supplied_coordinates_kept: false,
              coordinate_source: 'NONE'
            };
            injectStatusStyle();
            const known = [owner?.name ? String(owner.name) : null,
              Number.isFinite(Number(owner?.capacity_mw)) && Number(owner.capacity_mw) > 0
                ? Number(owner.capacity_mw).toLocaleString('en-GB') + ' MW' : null,
              owner?.status_value ? String(owner.status_value) : null]
              .filter(Boolean).join(' · ');
            showStatus((known ? known + '. ' : '')
              + 'REPD ' + repdRef + ' is in the active register and publishes no '
              + 'coordinate for it, and no seabed lease locates it either. The '
              + 'identity is confirmed; the location is not, so no distance is '
              + 'measured and no grid connection is implied.',
              'unavailable');
            try { answerArrival(classifyEngine(String(tech || ''), q), false, 'REGISTER_PUBLISHES_NO_COORDINATE', 'derived_lease_point'); } catch (_) {}
            return;
          } else if (owner?.status === 'NOT_IN_ACTIVE_REGISTER') {
            link.origin_source = 'not-in-active-register-no-supplied-point';
            link.deep_link_identity = 'terminal-not-in-active-register';
            link.identity_verification = {
              status: 'NOT_IN_ACTIVE_REGISTER', repd_ref: repdRef,
              supplied_coordinates_kept: false,
              official_active_register_match: false
            };
            injectStatusStyle();
            showStatus('REPD ' + repdRef + ' is not in the active-register '
              + 'snapshot, and this link supplies no coordinates from which '
              + 'to measure. No official status or location is inferred.',
              'unavailable');
            try { answerArrival(classifyEngine(String(tech || ''), q), false, 'NOT_IN_ACTIVE_REGISTER_NO_SUPPLIED_POINT', null); } catch (_) {}
            return;
          } else {
            injectStatusStyle();
            const message = String(owner?.message || 'identity loader unavailable');
            showStatus('The active-register identity check failed: ' + message
              + '. No location was supplied, so the grid measurement cannot '
              + 'start until the check succeeds.', 'failed');
            retryArrival = retryIdentityOwnerThenArrival;
            try { answerArrival(classifyEngine(String(tech || ''), q), false, 'IDENTITY_CHECK_FAILED', null); } catch (_) {}
            return;
          }
        } else {
          link.origin_source = 'link-supplied';
        }

        if (!coordsUsable()) {
          /* A PLAIN VISIT SAYS NOTHING. Vikram, 2026-09-20: "gridatlas still has random text near the top when no
             project is loaded". This branch ran for every visitor, so an address with no project in it at all was
             told that no usable coordinate had reached the map for "this project". The refusal below is right when a
             link arrived and its coordinate could not be used, and only then. With nothing in the address that names
             a project, a place or a technology, nobody asked, so nothing is said; the record says so in its own word
             rather than reporting a failed project that never existed. */
          const projectKeys = ['repd_ref', 'longitude', 'latitude', 'project', 'technology', 'capacity_mw', 'status'];
          if (!projectKeys.some(key => q.get(key) !== null)) {
            link.origin_source = 'none: a plain visit';
            try { answerArrival(classifyEngine('', q), false, 'NO_PROJECT_IN_ADDRESS', null); } catch (_) {}
            return;
          }
          const placeholder = Number.isFinite(lon) && Number.isFinite(lat) && isFalseOrigin(lon, lat);
          const why = placeholder ? 'PLACEHOLDER_COORDINATES_FALSE_ORIGIN' : 'NO_USABLE_COORDINATES';
          /* Refusing to measure is right and refusing in silence is not. The
             record alone is not a surface a reader can see, and a page that
             does nothing looks broken whatever the reason was. */
          injectStatusStyle();
          showStatus(placeholder
            ? 'The coordinate supplied for REPD ' + (repdRef || 'this project')
              + ' is the register’s placeholder point, not a location. '
              + 'Measuring from it would report a distance to the Isles of Scilly, '
              + 'so nothing is measured and nothing is claimed.'
            : 'No usable coordinate reached this map for '
              + (repdRef ? 'REPD ' + repdRef : 'this project')
              + ', so there is nothing to measure from.',
            'unavailable');
          try { answerArrival(classifyEngine(String(tech || ''), q), false, why, null); } catch (_) {}
          return;
        }

        /* Put the supplied point on screen with the supplied-point answer.
           The old rule flew only links without repd_ref and therefore left a
           valid coordinate link waiting for the register just to move the
           camera. If verification later finds a different point, the identity
           lane and the reconciliation below replace it together. */
        try {
          const arrivalZoom = zoomUsable ? requestedZoom : 12;
          map.flyTo({ center: [lon, lat], zoom: arrivalZoom,
            duration: 1200, essential: true });
          link.camera_from_link = { longitude: lon, latitude: lat,
            zoom: arrivalZoom, reason: identityVerification
              ? 'supplied coordinates while register verification runs'
              : (repdRef ? 'resolved repd_ref coordinates'
                : 'no repd_ref, so no other lane flies') };
        } catch (error) {
          noteFailure('deep link camera: ' + String(error?.message || error));
        }
        honourRequestedZoom(map);
        /* An unrecognised technology used to abandon the whole arrival.
           `return` cost the card, the ring, the nearest-substation
           measurement, the declared connection and the substation layer -
           all arithmetic over two coordinates and a register row. Only the
           one technology layer needs the id, so that is all it costs now.
           PROJECT_TECHS accepts 11,065 of the 11,069 ids the register
           writes. What the guard really catches is a link that omits or
           garbles the parameter, or carries an id from a newer register,
           and for all three the answer is the map, not a blank. Recorded on
           its own surface, not in `link.failures`, which since 202609011434
           means the arrival lost something. This one did not. */
        let technologyKnown = isProjectTech(tech);
        /* enabled starts false and STAYS false until enableTechnologyLayer()
           actually turns a control on -- that is the one place the truth
           lives. It used to read `enabled: technologyKnown`, which is
           membership of PROJECT_TECHS, not the state of any control: for
           wind_onshore, wind_offshore and other, that set says true while
           no such data-layer-id has ever existed, so the field read green
           on 2,508 of 7,680 register rows while the layer sat off. A field
           nothing else corrects is a field that lies for as long as the
           page is open, and this was read by every prior proof. */
        link.technology_layer = {
          requested: tech || null,
          layer_id: technologyKnown ? layerIdForBucket(tech) : null,
          enabled: false,
          reason: technologyKnown ? null
            : 'deep link: unknown technology "' + tech + '" - the arrival '
              + 'continues and this layer alone is not switched on'
        };
        // Turn the substations on. Arriving from the MAP button in Pipeline
        // News, the whole point is to see the project against the network, and
        // a user who has to find a checkbox first has been handed a puzzle
        // rather than an answer. The engine owns the layer, so this ticks its
        // own control rather than reaching past it into the map.
        // The dashboard is built from the engine's own data and does not
        // exist yet on a cold load -- measured at zero checkboxes twenty
        // seconds in. Ticking a control that has not been rendered silently
        // did nothing, and the layers the arrival depends on stayed off.
        // Named, so Try again re-runs exactly the arrival rather than
        // reloading and paying for the whole engine a second time.
        let currentArrival = Object.freeze({ lon, lat, name, tech, stated, repdRef, suppliedStatus });
        const enableBoth = () => {
          if (!arrivalGate.isCurrent(epoch)) return false;
          enableSubstationLayer();
          if (technologyKnown) enableTechnologyLayer(currentArrival.tech);
          return true;
        };
        const arrive = async () => {
          clearStatus();
          const ready = await waitForLayerControls(12000);
          enableBoth();
          // Late is not never. If the dashboard turns up after the budget, the
          // layers still go on, without the user having to do anything.
          if (!ready) watchForLayerControls(enableBoth);
          return ready;
        };
        retryArrival = () => { runDeepLink(); };
        /* Measure first. The distances are arithmetic over substation
           coordinates and need no layer control, no dashboard and no
           painted basemap; only the layers need the engine's controls.
           Until v9.54 this awaited arrive() - up to twelve seconds - before
           the measurement was even attempted, and Vikram's West Burton
           journey on a phone showed exactly what that buys: a card, and
           nothing beside it, for long enough to conclude the map is
           broken. The layer switch-on runs alongside and finishes whenever
           the engine is ready. */
        const layersReady = arrive();
        async function runArrivalSelection(arrival, waitForOwnerCard = false,
          expectedArrivalEpoch = epoch) {
          if (!arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
          /* A ref-only arrival already paid for canonical identity, so it can
             briefly yield to that owner's richer card. A supplied coordinate
             arrival must not wait for a card before it can measure: it creates
             the explicit link-provenance card below on the same turn. */
          if (waitForOwnerCard) {
            for (let i = 0; i < 40; i += 1) {
              if (document.querySelector('.maplibregl-popup-content')) break;
              const idStatus = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.status;
              if (idStatus === 'FAILED' || idStatus === 'ABSENT') break;
              await new Promise(resolve => setTimeout(resolve, 250));
              if (!arrivalGate.isCurrent(expectedArrivalEpoch)) return false;
            }
          }
          /* The card must exist BEFORE the lines. The popup watcher enforces
             "the lines belong to the card" and clears any drawing standing
             with no card on screen - watched live: a register-absent arrival
             drew five links and the watcher wiped them in the same breath,
             because the fallback card was opened after the measurement.
             ensureArrivalCard is a no-op when a card is already up, so the
             resolved-register path is unchanged. */
          currentRepdRef = arrival.repdRef;
          ensureArrivalCard(arrival.lon, arrival.lat, arrival.name,
            arrival.tech, arrival.stated, arrival.repdRef, arrival.suppliedStatus);
          /* Answer now, measure next. Everything in this block came from
             the made Order and the link; nothing here waits on a network. */
          currentDeclared = provisionalDeclaredConnection(currentRepdRef);
          if (currentDeclared) injectDeclaredOnly();
          try {
            if (capturedMap) setPin(capturedMap,
              [arrival.lon, arrival.lat], arrival.name, arrival.tech);
          }
          catch (_) { /* the measurement will draw it */ }
          link.deep_linked = true;
          const selected = await selectAt([arrival.lon, arrival.lat], arrival.name,
            arrival.tech, false,
            Number.isFinite(arrival.stated) && arrival.stated > 0
              ? arrival.stated : null, expectedArrivalEpoch);
          /* `selected === true`, not `!== false`. selectAt used to return bare
             undefined on two silent paths, and `undefined !== false` is true,
             so a wholly silent arrival reported itself current, runDeepLink
             returned true, and the retry lane recorded RESOLVED for an arrival
             that had measured nothing at all. Those returns are now explicit
             booleans; this reads the success value rather than everything that
             is not the failure value. */
          return selected === true && arrivalGate.isCurrent(expectedArrivalEpoch);
        }
        const firstStarted = performance.now();
        const firstSelectionCurrent = await runArrivalSelection(currentArrival,
          Boolean(repdRef && !identityVerification), epoch);
        if (!firstSelectionCurrent) return;
        link.first_coordinate_answer_ms = Math.round((performance.now() - firstStarted) * 10) / 10;
        link.first_coordinate_origin = link.origin_source;

        if (identityVerification) {
          /* Attach reconciliation only after the supplied-point selection has
             completed. A warm identity can resolve on the first microtask;
             sequencing it here prevents two selections racing each other. */
          continueVerifiedArrival(arrivalGate, epoch, identityVerification,
            async ({ resolved, terminal, error }) => {
            if (!resolved) {
              const ownerState = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link || null;
              const message = error ? String(error?.message || error)
                : String(ownerState?.message || '');
              link.origin_source = terminal === 'NOT_IN_ACTIVE_REGISTER'
                ? 'link-supplied-not-in-active-register'
                : 'link-supplied-register-' + String(terminal).toLowerCase();
              link.deep_link_identity = 'terminal-' + String(terminal).toLowerCase();
              link.identity_verification = {
                status: terminal, repd_ref: repdRef,
                supplied_coordinates_kept: true,
                arrival_fields: {
                  name: currentArrival.name,
                  technology: currentArrival.tech,
                  capacity_mw: Number.isFinite(currentArrival.stated)
                    ? currentArrival.stated : null,
                  supplied_status: currentArrival.suppliedStatus || null
                },
                official_active_register_match: false,
                message: message || null
              };
              markArrivalIdentityState(terminal, repdRef, message);
              if (terminal === 'FAILED') {
                injectStatusStyle();
                retryArrival = retryIdentityOwnerThenArrival;
                showStatus('The active-register identity check failed'
                  + (message ? ': ' + message : '.')
                  + ' The supplied point and measurement remain on the map.',
                  'failed');
              }
              return;
            }

            const rLon = Number(resolved.longitude);
            const rLat = Number(resolved.latitude);
            const resolvedPointUsable = Number.isFinite(rLon) && Number.isFinite(rLat)
              && Math.abs(rLon) <= 180 && Math.abs(rLat) <= 90
              && !(Math.abs(rLon) < 1e-9 && Math.abs(rLat) < 1e-9);
            if (!resolvedPointUsable) {
              link.origin_source = 'link-supplied-register-without-point';
              link.deep_link_identity = 'resolved-without-usable-point';
              link.identity_verification = {
                status: 'RESOLVED_WITHOUT_USABLE_POINT', repd_ref: repdRef,
                supplied_coordinates_kept: true
              };
              return;
            }

            const discrepancyKm = Math.round(
              distanceKm(currentArrival.lon, currentArrival.lat, rLon, rLat) * 1000
            ) / 1000;
            link.origin_discrepancy_km = discrepancyKm;
            link.deep_link_identity = 'resolved-by-search-lane';
            if (discrepancyKm <= 0.001) {
              link.origin_source = 'link-supplied-register-verified';
              markArrivalIdentityState('VERIFIED', repdRef);
              link.identity_verification = {
                status: 'VERIFIED', repd_ref: repdRef,
                discrepancy_km: discrepancyKm, recomputed: false
              };
              return;
            }

            const rTech = typeof resolved.technology === 'string' && resolved.technology
              ? resolved.technology : currentArrival.tech;
            const rName = resolved.name ? String(resolved.name) : currentArrival.name;
            const rCap = Number(resolved.capacity_mw);
            const rStated = Number.isFinite(rCap) && rCap > 0 ? rCap : currentArrival.stated;
            const verifiedArrival = Object.freeze({
              lon: rLon, lat: rLat, name: rName, tech: rTech,
              stated: rStated, repdRef, suppliedStatus: currentArrival.suppliedStatus
            });
            currentArrival = verifiedArrival;
            technologyKnown = isProjectTech(verifiedArrival.tech);
            currentCapacityMw = Number.isFinite(verifiedArrival.stated)
              && verifiedArrival.stated > 0 ? verifiedArrival.stated : null;
            link.origin_source = 'register-corrected-after-link';
            link.identity_verification = {
              status: 'RECOMPUTING', repd_ref: repdRef,
              discrepancy_km: discrepancyKm, recomputed: false
            };
            try {
              map.flyTo({ center: [verifiedArrival.lon, verifiedArrival.lat],
                zoom: zoomUsable ? requestedZoom : 12,
                duration: 800, essential: true });
              await runArrivalSelection(verifiedArrival, false, epoch);
              enableBoth();
              link.identity_verification.status = 'RECOMPUTED';
              link.identity_verification.recomputed = true;
            } catch (reconcileError) {
              link.identity_verification.status = 'RECOMPUTE_FAILED';
              link.identity_verification.message =
                String(reconcileError?.message || reconcileError);
              noteFailure('deep link identity reconciliation: '
                + link.identity_verification.message);
            }
          }).catch((reconcileError) => {
            if (!arrivalGate.isCurrent(epoch)) return;
            link.identity_verification = {
              status: 'RECONCILIATION_FAILED', repd_ref: repdRef,
              supplied_coordinates_kept: true,
              message: String(reconcileError?.message || reconcileError)
            };
            noteFailure('deep link identity reconciliation: '
              + link.identity_verification.message);
          });
        }
        await layersReady;
        return arrivalGate.isCurrent(epoch);
      } catch (error) {
        /* `q` and `tech` are declared inside the try, so they are not in scope
           here and classifyEngine cannot be called - reading them would throw a
           ReferenceError inside the very handler that exists to stop an arrival
           disappearing. The query is still on the URL, so read the class from
           there instead of guessing onshore. */
        let engine = 'onshore';
        try {
          const q2 = new URLSearchParams(window.location.search);
          if (q2.get('interconnector') || String(q2.get('technology') || '') === 'interconnector') engine = 'interconnector';
          else if (coverage.policy(String(q2.get('technology') || ''))?.offshore) engine = 'offshore';
        } catch (_) { engine = 'onshore'; }
        try { answerArrival(engine, false, 'ARRIVAL_THREW', null); } catch (_) {}
        link.failures.push('deep link: ' + String(error?.message || error));
        return false;
      }
    }
    rerunDeepLink = runDeepLink;

    /* THE ARRIVAL MUST NEVER RUN WHILE NOBODY CAN SEE IT, AND MUST NEVER
       BE ONE-SHOT.
       --------------------------------------------------------------------
       Reported live by the architect on his own iPhone, twice, on two
       different projects: menu bar fine, attribution fine, basemap fully
       painted -- and the camera sat at the default UK-wide view, no card,
       no links. Both arrivals were opened from Pipeline News' MAP control,
       which carries target="_blank" on touch devices. An independent audit
       today reproduced the mechanism exactly: a deep link loaded with
       document.hidden === true drew zero layer controls at 40s, the camera
       never left its default position, and it recovered 2.5s after being
       made visible -- because MapLibre's flyTo() and the engine's own
       paint-driven boot both depend on requestAnimationFrame, which iOS
       Safari does not tick in a tab that is not composited. Calling
       map.flyTo() there does not throw and is not a failure this cartridge
       can see: the animation is simply never given a frame to advance, so
       the camera stays exactly where it started, forever, even once the
       tab is later brought to the front -- because this function had
       already run to its own conclusion and nothing called it again.

       So: never START the arrival until the document is actually visible,
       and never leave an arrival that has not produced a visible outcome
       stranded -- run it again the first time the tab is genuinely seen. */
    let arrivalAttempts = 0;
    const MAX_AUTO_ARRIVAL_ATTEMPTS = 5;   // a real, non-visibility failure must still stop retrying
    function arrivalHasVisibleOutcome() {
      // Both already-published, already-relied-upon fields: links_drawn is
      // read the same way by the electron-flow visibility listener just
      // below, and the not-in-active-register message is this cartridge's
      // own genuine "nothing more to show" terminal state.
      /* The sentinel belongs in this test. An offshore farm whose nearest
         substation lies beyond the draw radius is ANSWERED with a real
         distance and a real name, and it draws no line - so links_drawn is 0
         and, before this, every visibilitychange re-ran the whole arrival on a
         question that was already answered, up to five times. An answer is an
         outcome whether or not it put lines on the map. */
      return link.links_drawn > 0
        || link.declared_connection_framed === true
        || link.arrival_engine?.answered === true
        || link.origin_source === 'not-in-active-register-no-supplied-point';
    }
    function attemptArrival() {
      if (document.visibilityState !== 'visible') {
        /* Not a failure - the tab is not composited, so an arrival started here
           would fly a camera that never moves. It is still a state a reader can
           be sitting in, so it is named rather than left blank, and it is
           replaced the moment the tab is genuinely seen. */
        if (!link.arrival_engine) {
          try { answerArrival('onshore', false, 'DEFERRED_FOR_VISIBILITY', null); } catch (_) {}
        }
        return;
      }
      arrivalAttempts += 1;
      link.arrival_attempts = arrivalAttempts;
      void runDeepLink();
    }
    if (document.visibilityState === 'visible') {
      attemptArrival();
    } else {
      link.arrival_deferred_for_visibility = true;
    }
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState !== 'visible') return;
      if (arrivalHasVisibleOutcome()) return;
      if (arrivalAttempts >= MAX_AUTO_ARRIVAL_ATTEMPTS) {
        /* Five attempts spent and still no outcome. The arrival is now
           permanently over, and this is the last chance anything has to say so
           - after this the map simply sits there. */
        try { answerArrival('onshore', false, 'ARRIVAL_ATTEMPTS_EXHAUSTED', null); } catch (_) {}
        return;
      }
      link.arrival_resumed_on_visibility = (link.arrival_resumed_on_visibility || 0) + 1;
      attemptArrival();
    });

    // Escape clears, the way a game HUD does.
    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape') clearLinks();
    });

    installGbConditions();
    installVersionLedger();
    installMobileTray();

    window.addEventListener('resize', boundCardToMap);
    map.on('resize', boundCardToMap);
    boundCardToMap();

    // A backgrounded tab should not keep an animation frame loop alive.
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) stopAnimation();
      else if (link.links_drawn > 0 && capturedMap) startAnimation(capturedMap);
    });
  }

  /* ── capture the map ─────────────────────────────────────────────────── */

  function attach(map) {
    if (capturedMap) {
      /* A second map was constructed and the arrival is bound to the first.
         Whatever the reader is looking at, it is not the map this engine
         measures on, and that has to be said rather than left as silence. */
      if (!link.arrival_engine) recordArrivalEngine('onshore', false, 'SECOND_MAP_NOT_CAPTURED', null);
      return;
    }
    capturedMap = map;
    link.map_captured = true;
    const boot = () => {
      try { install(map); }
      catch (error) {
        /* install() throwing is the engine failing to exist: the click handler
           and the arrival scheduler are registered inside it, below the throw,
           so nothing downstream will ever answer. Without this the page looks
           like a map that simply found nothing. */
        recordArrivalEngine('onshore', false, 'ENGINE_INSTALL_THREW', null);
        link.failures.push(String(error?.message || error));
      }
      try { installSld(map); }
      catch (error) { link.failures.push('sld: ' + String(error?.message || error)); }
    };
    /* Boot when the style is ready, not when a frame has painted.
       ------------------------------------------------------------------
       This waited on map.once('load'), which maplibre fires only after the
       first frame is on screen -- and that needs basemap tiles. Watched live:
       the CARTO style.json, tiles.json and sprite all returned 200 and then
       not one vector tile was fetched, so the map stayed black, 'load' never
       came, and the whole grid-maths layer never installed. The bare shell
       failed identically, which is how the cartridge was ruled out.

       Nothing here needs a painted frame. Sources and layers need a parsed
       STYLE, and the distances need no map at all: they are arithmetic over
       substation coordinates. Tying them to the basemap made an unrelated CDN
       a single point of failure for the measurement.

       So: whichever of style.load or load arrives first, and failing both, a
       timer. A basemap that never paints is a bad map, not a reason to have
       no maths. */
    if (map.isStyleLoaded?.()) { link.boot_trigger = 'already-loaded'; boot(); }
    else {
      let booted = false;
      const bootOnce = (trigger) => {
        if (booted) return;
        booted = true;
        link.boot_trigger = trigger;
        boot();
      };
      map.once('style.load', () => bootOnce('style.load'));
      map.once('load', () => bootOnce('load'));
      setTimeout(() => {
        // Only if a style is actually there to hang layers on. Booting without
        // one would fail on the first addSource and lose the real reason.
        if (booted) return;
        let hasStyle = false;
        try { hasStyle = Boolean(map.getStyle?.()); } catch (error) { hasStyle = false; }
        if (hasStyle) {
          link.failures.push('basemap never finished painting; booted on the style alone');
          bootOnce('timeout');
        } else {
          /* This is the literal "the engine did not launch": install() is never
             called, so the click handler, the arrival scheduler and the helper
             that would name a failure do not exist. Everything downstream is
             structurally incapable of reporting, which is why this one has to
             be written here, at module scope, by hand. */
          recordArrivalEngine('onshore', false, 'ENGINE_NEVER_INSTALLED_NO_STYLE', null);
          link.failures.push('no style after 8s; the grid maths cannot install');
        }
      }, 8000);
    }
  }

  // The engine keeps its map in a closure and returns nothing, so the only
  // clean handle is the constructor -- and the engine builds its map inside
  // initVentusMap, which runs after this file, so it is still ours to wrap.
  try {
    const gl = window.maplibregl;
    if (gl && typeof gl.Map === 'function' && !gl.Map.__gridatlasNeonWrapped) {
      const OriginalMap = gl.Map;
      function PatchedMap(...args) {
        const instance = new OriginalMap(...args);
        try { attach(instance); }
        catch (error) { link.failures.push(String(error?.message || error)); }
        return instance;
      }
      PatchedMap.prototype = OriginalMap.prototype;
      PatchedMap.__gridatlasNeonWrapped = true;
      Object.setPrototypeOf(PatchedMap, OriginalMap);
      gl.Map = PatchedMap;
    } else if (!gl) {
      link.failures.push('maplibregl unavailable when the neon cartridge loaded');
    }
  } catch (error) {
    link.failures.push(String(error?.message || error));
  }

  /* ══════════════════════════════════════════════════════════════════════
     PART 3 — the SLD sandbox, ported from
     globalgrid2050/solar-bess-topology-v7/gis-sld-financial-sandbox.