GLOBALGRID2050 / EXPLORE CODE

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

Single-Line Diagram (SLD) Sandbox Body (part 6)

A JavaScript file in the parts folder of GridAtlas that maps grid substations, solar, transformers and 400kV, using haversine.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Grid network and substations. Section 416 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 Body geodesy · gridatlas / atlas/parts/202609012045-sld-sandbox-body.js lines 3919–4618

Single-Line Diagram (SLD) Sandbox Body

A JavaScript file in the parts folder of GridAtlas that maps grid substations, solar, transformers and 400kV, using haversine.

Set aside from the main view: 96% of its lines are the same as atlas/parts/202609040229-sld-sandbox-arrival-identity.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Single-Line Diagram (SLD) Sandbox Arrival Identity; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9622 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/parts/202609040229-sld-sandbox-arrival-identity.js:1-5948 2c1486ea5aef879022fc222d4363b779d22e165b
  • sha256 4494ff9a6fd9db05b7208e2e420f65705b1eaac919f77995f13ff45c3e9e69b9
  • target sha256 7c0d4eb1ef95c845bb8bcbf9fa7020eb009c025ed3edbb34afa0cc085c20b5d5
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/parts/202609012045-sld-sandbox-body.js · lines 3919–4618 of 5782 · version 2026-09-01 20:45 (continued from section 410) · Not reached from any entry point (candidate for review) · pattern provisionalDeclaredConnection (shared by 9 files)

What it does
It maps grid substations, solar, transformers and 400kV. Defines 183 functions or classes, including coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission. 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: solar, transformers, 400kV, 750kV, 415kV, 275kV.
Inputs & outputs
In: 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, 66kV, 33kV.
What it achieves
It resolves declared connection (`resolveDeclaredConnection`), opens corridor sheet (`openCorridorSheet`) and runs grid point (`runGridAtPoint`). GridAtlas cartridge — neon substation links and the SLD layout sandbox. Its code works with 400 kV, 33 kV and 132 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/parts · 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
none found
Produces
coverage, isProjectTech, provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission, corridorBeside, module, corridorTargets, corridorAction, installCorridorSheet, close, openCorridorSheet
Defines here
setSourceData, interactiveLayerIds, install, selectAt, waitForResolvedIdentity, runDeepLink, framed, honourRequestedZoom, apply, coordsUsable, enableBoth, arrive, runArrivalSelection, 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/parts/202609012045-sld-sandbox-body.js:3919-4618 · blob e1451b1f9330cecde3e94fbe6ad608a6425c028d · 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
  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) {
    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);
        return;
      }
      /* 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 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');
        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') {
          if (told) clearStatus();
          return null;
        }
      }
      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() {
      try {
        const epoch = arrivalGate.begin();
        const q = new URLSearchParams(window.location.search);
        /* 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'));
        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((resolved) => ({
              resolved,
              terminal: window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.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 resolved = await waitForResolvedIdentity();
          if (resolved) {
            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 {
            injectStatusStyle();
            showStatus('The project in this link could not be resolved '
              + 'against the register. This is usually the network rather '
              + 'than the link.', 'failed');
            retryArrival = () => { clearStatus(); runDeepLink(); };
            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);
        link.technology_layer = {
          requested: tech || null,
          enabled: technologyKnown,
          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 });
        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);
          /* 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) {
              link.origin_source = '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,
                message: error ? String(error?.message || error) : null
              };
              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';
              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
            });
            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;
      } catch (error) {
        link.failures.push('deep link: ' + String(error?.message || error));
      }
    }
    runDeepLink();

    // 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) {