GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / globalgrid2050 / testcode/202609051152/atlas/cartridges

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

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

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Grid network and substations. Section 347 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Single-Line Diagram (SLD) Sandbox V9 8 geodesy · globalgrid2050 / testcode/202609051152/atlas/cartridges/202609050354-sld-sandbox-v9-8.js lines 5601–6300

Single-Line Diagram (SLD) Sandbox V9 8

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

Set aside from the main view: 95% of its lines are the same as testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with Single-Line Diagram (SLD) Sandbox; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9509 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js:1-7736 b9451a6d240116dae04211c0cc8216a75da78ad1
  • sha256 7c2df5dabb0082d4cef941b98bf31e92161d1e79a7d22bd6c84e81b171507022
  • target sha256 93d81bebf3d1cf8f799ccf6f117f1565777ed88110481c284713589539586605
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesyglobalgrid2050 / testcode/202609051152/atlas/cartridges/202609050354-sld-sandbox-v9-8.js · lines 5601–6300 of 7382 · version 2026-09-05 03:54 (continued from section 339) · Not reached from any entry point (candidate for review) · pattern widerFleetBuckets (shared by 6 files)

What it does
It maps connection points, GB transmission network, price decade rollup and grid substations. Defines 217 functions or classes, including classOf, scope, survey, ready, worksAt. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
Inputs & outputs
In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; GeoJSON file grid_substations.geojson; browser storage (getItem); DuckDB queries; form fields (user input). 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 builds stats (`buildStats`), applies development stage defaults (`applyDevelopmentStageDefaults`) and applies mounting bifacial (`applyMountingBifacial`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. 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
globalgrid2050 · testcode/202609051152/atlas/cartridges · script
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
classOf, scope, survey, ready, worksAt, provisional, resolve, nearestTransmission, physicalInputs, buildStats, consistency, stringStats
Defines here
waitForResolvedIdentity, runDeepLink, framed, honourRequestedZoom, apply, 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
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/atlas/cartridges/202609050354-sld-sandbox-v9-8.js:5601-6300 · blob f66bb0bcbf98ce7cd519581375865ca92f816b61 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
           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');
        return;
      }
      clearStatus();
      currentDeclared = resolveDeclaredConnection(currentRepdRef, origin, subs);
      currentNearest400 = nearestTransmission(origin, subs);
      drawLinks(map, origin, name, tech,
        nearestSubstations(origin[0], origin[1], subs), 'to-substation', statedMw);
      return true;
    }
    link.selectAt = selectAt;

    map.on('click', async (event) => {
      try {
        if (fromOwnUi(event)) return;
        const ids = interactiveLayerIds(map);
        if (!ids.length) return;
        let features = [];
        try { features = map.queryRenderedFeatures(event.point, { layers: ids }); }
        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) {
        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; }
        if (dl.status === 'FAILED' || dl.status === 'ABSENT'
            || dl.status === 'NOT_IN_ACTIVE_REGISTER'
            || 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);
        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 + '"');
        }
        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);
              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);
        }
        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);

        /* 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();
          if (!arrivalGate.isCurrent(epoch) || owner?.status === 'CANCELLED') 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 === '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');
            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;
            return;
          }
        } else {
          link.origin_source = 'link-supplied';
        }

        if (!coordsUsable()) 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);
          return selected !== false && 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) {
        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.
      return link.links_drawn > 0
        || link.origin_source === 'not-in-active-register-no-supplied-point';
    }
    function attemptArrival() {
      if (document.visibilityState !== 'visible') 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) 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) return;
    capturedMap = map;
    link.map_captured = true;
    const boot = () => {
      try { install(map); }
      catch (error) { 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 {
          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));