GLOBALGRID2050 / EXPLORE CODE

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

Single-Line Diagram (SLD) Without Layout (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: Grid network and substations. Section 406 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) Without Layout geodesy · gridatlas / atlas/modules/202611222130-sld-without-layout.js lines 6301–7000

Single-Line Diagram (SLD) Without Layout

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

Set aside from the main view: 100% of its lines are the same as atlas/modules/202612020205-secondary-neon-engine.js (gridatlas), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Secondary Neon Engine; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9961 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612020205-secondary-neon-engine.js:1-9008 26e5045a356c11088820207d3cbe95eb4b89374f
  • sha256 6870cfb365c18b90363b664f89623c9217c3d0111a67b87fdd1b6b3a26aeba6b
  • target sha256 b9e2b3ce36d3f46184c4a0f0416d70892feb49507d1c93833d3ab00a27c84263
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesygridatlas / atlas/modules/202611222130-sld-without-layout.js · lines 6301–7000 of 8986 · version 2026-11-22 21:30 (continued from section 397) · 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 273 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 sub33kv_design (path word 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. 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
setSourceData, interactiveLayerIds, install, selectAt, classifyEngine, answerArrival, waitForResolvedIdentity, runDeepLink, framed, honourRequestedZoom, apply, isFalseOrigin, coordsUsable
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/202611222130-sld-without-layout.js:6301-7000 · blob ab6fc6992aa26e51a3c82d7e2d26172a50798c60 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
    panel.addEventListener('click', (event) => event.stopPropagation());
    stack.appendChild(panel);
    link.gb_panel_installed = true;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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