GLOBALGRID2050 / EXPLORE CODE

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

Single-Line Diagram (SLD) Sandbox Arrival Identity (part 2)

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 421 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 Arrival Identity geodesy · gridatlas / atlas/parts/202609040229-sld-sandbox-arrival-identity.js lines 1087–1786

Single-Line Diagram (SLD) Sandbox Arrival Identity

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

geodesygridatlas / atlas/parts/202609040229-sld-sandbox-arrival-identity.js · lines 1087–1786 of 5948 · version 2026-09-04 02:29 (continued from section 419) · Not reached from any entry point (candidate for review) · pattern retryIdentityOwnerThenArrival (shared by 8 files)

What it does
It maps grid substations, solar, transformers and 400kV. Defines 187 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
fillTopologyBlocks, topologyInnerHtml, caveat, ratings, ownership, planned, injection, reach, FLOW_PATTERNS, setFlowDash, forgetDashMemo, flowIndex, flowDash, noteFailure, recoverFailures, distanceKm, voltagesKv, push, representativePoint, deepLinkPlan, createArrivalGate, continueVerifiedArrival, arrivalKey, claimPendingArrival, invalidatePendingArrival, loadSubstations, nearestSubstations, nearestProjects
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/202609040229-sld-sandbox-arrival-identity.js:1087-1786 · blob 2c1486ea5aef879022fc222d4363b779d22e165b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: duplicate_candidate
  function fillTopologyBlocks() {
    document.querySelectorAll('.' + TOPOLOGY_BLOCK).forEach(node => {
      try {
        node.innerHTML = topologyInnerHtml(JSON.parse(node.getAttribute('data-queries') || '[]'));
        topology.blocks_filled += 1;
      } catch (error) {
        noteFailure('topology block: ' + String(error?.message || error));
      }
    });
  }

  function topologyInnerHtml(queries) {
    const caveat = (text) => `<p class="neon-caveat">${text}</p>`;
    if (topology.state === 'idle' || topology.state === 'loading') {
      return caveat(`<b>Transmission network:</b> loading the published node/branch `
        + `model (about 10 MB, once per session). This card fills in when it arrives.`);
    }
    if (topology.state === 'failed') {
      return caveat(`<b>Transmission network:</b> not available - `
        + `${escapeHtml(topology.error || 'unknown failure')}. Nothing here is inferred from its absence.`);
    }
    const network = window.__GRIDATLAS_NETWORK__ || null;
    if (!network?.loaded) {
      return caveat(`<b>Transmission network:</b> indexed (${topology.sites} sites), but the `
        + `connection-points cartridge that joins a mapped name to a published site `
        + `${network?.failed ? 'failed to load' : 'has not loaded yet'}, so no site is named.`);
    }
    let out = '';
    let shown = 0;
    const module = topologyModule();
    for (const q of queries) {
      const kv = Number.isFinite(q.kv) ? q.kv : null;
      let point = null;
      try { point = network.byName(q.name); } catch (_) { point = null; }
      if (!point?.site_code) continue;
      const facts = topology.index.at(point.site_code, kv != null ? { voltageKv: kv } : undefined);
      if (!facts) continue;
      shown += 1;
      out += `<div class="neon-hd">${escapeHtml(facts.site.name)}`
        + `<span class="neon-beta">ETYS topology</span></div>`
        + caveat(`Joined by name from <i>${escapeHtml(q.name)}</i> to NESO site `
          + `${escapeHtml(facts.site.code)}`
          + (facts.site.transmission_owner ? ` (${escapeHtml(facts.site.transmission_owner)})` : '')
          + `; declared voltages ${facts.site.voltages_kv.length
            ? escapeHtml(facts.site.voltages_kv.join(', ')) + ' kV' : 'not stated'}.`);
      if (!facts.by_voltage.length) {
        out += caveat(kv != null
          ? `No published branch lands at ${kv} kV at this site.`
          : `No published branch lands at this site.`);
      } else {
        /* Site totals are UNITS; the lines below are landings and will
           not add up, because a transformer with both windings here
           appears under each of its voltages. */
        const c = facts.counts;
        out += caveat(`<b>At the site:</b> ${c.circuits} circuit`
          + `${c.circuits === 1 ? '' : 's'} and ${c.transformers} transformer`
          + `${c.transformers === 1 ? '' : 's'}, counted as units. `
          + `The per-voltage lines below count landings, one for each end held `
          + `here, so a transformer with both windings at this site appears `
          + `under both of its voltages.`);
      }
      for (const band of facts.by_voltage) {
        const label = band.voltage_kv == null ? 'an undeclared voltage' : `${band.voltage_kv} kV`;
        const years = [...new Set(band.planned_changes.map(c => c.year).filter(Boolean))].sort();
        out += caveat(`<b>At ${label}:</b> ${band.circuits.length} circuit${band.circuits.length === 1 ? '' : 's'}, `
          + `${band.transformers.length} transformer${band.transformers.length === 1 ? '' : 's'}`
          + (band.planned_changes.length
            ? `, ${band.planned_changes.length} published change${band.planned_changes.length === 1 ? '' : 's'}`
              + (years.length ? ` (${escapeHtml(years.join(', '))})` : '')
            : '')
          + `.`);
      }
      /* Seasonal ratings, per circuit, never added together.
         ---------------------------------------------------------------
         The lowest and the highest are two REAL published values, not a
         range around a mean, and each is labelled with the season it
         belongs to. Where the operator publishes a placeholder rather
         than a rating, the card says so rather than quietly carrying the
         larger number into the maximum. */
      const ratings = (() => {
        const mod = ratingModule();
        if (!mod) return null;
        try { return mod.at(topology.index, point.site_code, kv != null ? { voltageKv: kv } : undefined); }
        catch (_) { return null; }
      })();
      if (ratings && ratings.circuits.length) {
        const said = [];
        for (const season of ['winter', 'summer']) {
          const band = ratings.by_season[season];
          if (!band || !band.circuits) continue;
          said.push(`${season} ${band.lowest_circuit_mva === band.highest_circuit_mva
            ? band.lowest_circuit_mva
            : `${band.lowest_circuit_mva}-${band.highest_circuit_mva}`} MVA`);
        }
        if (said.length) {
          const flagged = ratings.counts.with_a_flagged_value;
          out += caveat(`<b>Circuit ratings:</b> ${escapeHtml(said.join(', '))}, `
            + `across ${ratings.counts.circuits} circuit${ratings.counts.circuits === 1 ? '' : 's'}. `
            + `Each figure is one circuit's rating in that season. They are not added `
            + `together: the sum of the circuits at a site is not a quantity that exists `
            + `in the network, and a rating is not what is free on the circuit.`
            + (flagged ? ` ${flagged} circuit${flagged === 1 ? ' publishes a value' : 's publish values'} `
              + `at or above 9,999 MVA on spans of a kilometre or less; `
              + `${flagged === 1 ? 'it reads' : 'they read'} as a placeholder and `
              + `${flagged === 1 ? 'is' : 'are'} excluded from the range above.` : ''));
          rating.answered += 1;
          rating.flagged += flagged;
        }
      }

      /* Who owns what lands here, and whether two owners meet.
         ---------------------------------------------------------------
         Printed before the planned sentence because it is a fact about
         what is there now. A single owner is a small fact; two owners on
         one circuit is a seam, and a connection across a seam involves
         more than one party. */
      const ownership = (() => {
        const mod = ownerModule();
        if (!mod || !topology.parsedProduct) return null;
        try {
          if (ownerIndex === undefined) ownerIndex = mod.index(topology.parsedProduct);
          if (!ownerIndex) return null;
          return ownerIndex.at(point.site_code, kv != null ? { voltageKv: kv } : undefined);
        } catch (_) { return null; }
      })();
      if (ownership && Array.isArray(ownership.owners_present) && ownership.owners_present.length) {
        const owners = ownership.owners_present.map((o) => escapeHtml(String(o)));
        const seams = (ownership.boundary_circuits || []).length
          + (ownership.boundary_transformers || []).length;
        const counts = ownership.counts || {};
        out += caveat(`<b>Transmission owner${owners.length === 1 ? '' : 's'}:</b> `
          + `${owners.join(', ')}.`
          + (seams
            ? ` ${seams} branch${seams === 1 ? '' : 'es'} here ${seams === 1 ? 'is' : 'are'} `
              + `a boundary: the two ends are published under different owners.`
            : '')
          + (counts.nodes_with_unknown_owner
            ? ` ${counts.nodes_with_unknown_owner} node here publishes no owner and is `
              + `reported as unknown, never taken from the site.`
            : '')
          + (counts.asset_owner_differs_from_both_ends
            ? ` ${counts.asset_owner_differs_from_both_ends} asset carries an owner `
              + `matching neither of its ends; that is reported as itself, not as a boundary.`
            : '')
          + ` Ownership is a published fact about an asset. It is not a statement `
          + `about who a project would contract with, which depends on connection `
          + `agreements and commercial terms no appendix contains.`);
        ownerState.answered += 1;
        ownerState.seams += seams;
      }

      /* What is published as planned, in its own sentence.
         ---------------------------------------------------------------
         Never folded into the counts above. A row published for 2030 is
         a statement about a future year; presenting it beside today's
         circuits would let a reader take it for one. */
      const planned = (() => {
        const mod = plannedModule();
        if (!mod || !topology.parsedProduct) return null;
        try {
          if (plannedIndex === undefined) plannedIndex = mod.index(topology.parsedProduct);
          if (!plannedIndex) return null;
          return plannedIndex.at(point.site_code, kv != null ? { voltageKv: kv } : undefined);
        } catch (_) { return null; }
      })();
      if (planned && planned.counts && planned.counts.planned_changes) {
        /* by_year is an ORDERED ARRAY of { year, by_status: [{ status,
           entries }] }, not a map - the module keeps publication order
           rather than letting object key order decide what the reader
           sees first. */
        const years = (planned.by_year || []).map((band) => {
          const parts = (band.by_status || []).map((s) =>
            `${(s.entries || []).length} ${escapeHtml(String(s.status).toLowerCase())}`);
          return `<b>${escapeHtml(String(band.year))}</b> ${parts.join(', ')}`;
        });
        if (years.length) {
          out += caveat(`<b>Published as planned:</b> ${years.join('; ')}. `
            + `These are rows NESO publishes for a future year. None of them is a `
            + `circuit today, a commitment, a consent, or a connection date, and `
            + `none is counted among the circuits above.`);
          plannedState.answered += 1;
          plannedState.rows += planned.counts.planned_changes;
        }
      }

      /* Where the project's own power would go.
         ---------------------------------------------------------------
         Pipeline News sends capacity_mw on every deep link, so the
         question "where would MY output flow" is answerable the moment a
         project is selected. The slack is NAMED in the sentence: a
         transfer has two ends and quoting one of them is meaningless.
         What is deliberately absent is any statement about room. */
      const injection = (() => {
        const mod = flowModule();
        if (!mod || kv !== 400) return null;
        /* The project's own stated capacity where the deep link carried
           one, and a declared 100 MW probe otherwise - labelled as such in
           the sentence, never presented as the project's figure. */
        const mw = Number.isFinite(currentCapacityMw) && currentCapacityMw > 0
          ? currentCapacityMw : 100;
        const model = flowModelFor(topology.index);
        if (!model) return null;
        try {
          const graph = topology.index.graph();
          const here = graph.nodesOfSite(point.site_code)
            .filter(n => graph.nodeVoltageKv(n) === 400).sort()[0];
          if (!here) return null;
          /* The withdrawal bus is DECLARED, not the first one to hand.
             ------------------------------------------------------------
             This took model.buses.find(b => b !== injection), which on a
             network with 238 components is almost always a bus the
             injection cannot reach. Codex found it at 202609020030. The
             module now publishes the rule it uses and the component it
             solved in, and refuses a cross-component transfer outright. */
          const slackNode = typeof mod.sinkFor === 'function'
            ? mod.sinkFor(model, here) : null;
          if (!slackNode) return null;
          const r = mod.respond(model, { atNode: here, slackNode, mw, minimumShare: 0.05 });
          /* publishable, not validation.passes: a disconnected pair can
             balance at the injection bus while the solve has not converged
             at all, and the old gate would have let that print. */
          return r && r.publishable === true ? r : (r || null);
        } catch (_) { return null; }
      })();
      if (injection && injection.publishable !== true) {
        /* Saying nothing looks identical to having nothing to say. When
           the model cannot solve this transfer the reader is told, with
           the reason, rather than left with a card that quietly lost a
           section. */
        out += caveat(`<b>Where the power would flow:</b> not available here. `
          + escapeHtml(String(injection.reason
            || 'the solve did not meet its acceptance conditions'))
          + ` No figure is shown rather than one that has not converged.`);
        powerflow.refused += 1;
      }
      if (injection && injection.publishable === true && injection.branches.length) {
        const top = injection.branches.slice(0, 3);
        out += caveat(`<b>Where ${injection.injected_mw} MW would flow</b> `
          + `(declared DC model, 100 MVA base, transfer to ${escapeHtml(injection.slack_node)}, `
          + `solved in a component of ${injection.component
            ? injection.component.buses_in_component : '?'} buses): `
          + top.map(b => `${escapeHtml(b.from_node)}-${escapeHtml(b.to_node)} `
            + `${Math.round(Math.abs(b.share_of_injection) * 100)}%`
            + (b.published_ratings_mva && b.published_ratings_mva.summer
              ? ` (summer rating ${b.published_ratings_mva.summer} MVA)` : '')).join(', ')
          + `. Flat 1.0 pu voltages, small angles, no losses, no taps, intact network. `
          + `This is the response to a NEW injection, not a loading: what is already `
          + `flowing on these circuits is published nowhere, so whether there is room `
          + `for it cannot be computed here by anyone.`);
        powerflow.answered += 1;
        powerflow.worst_kirchhoff_error = Math.max(powerflow.worst_kirchhoff_error,
          injection.validation.kirchhoff_error);
      }

      /* Electrical distance, beside the one-hop view.
         ---------------------------------------------------------------
         "Circuits reach" above is one hop. This is the second, and it is
         reported as a COUNT of sites at each hop rather than as a claim
         about any of them: naming a site two hops away and nothing else
         would read as a recommendation, which no published appendix
         supports. The hop count is never called a distance. */
      const reach = (() => {
        const mod = distanceModule();
        if (!mod) return null;
        try { return mod.within(topology.index, point.site_code, { hops: 2, voltageKv: kv }); }
        catch (_) { return null; }
      })();
      if (reach && reach.sites.length) {
        const atOne = reach.counts.by_hop[1] || 0;
        const atTwo = reach.counts.by_hop[2] || 0;
        out += caveat(`<b>On the published network:</b> ${atOne} site${atOne === 1 ? '' : 's'} `
          + `one circuit away${atTwo ? `, ${atTwo} more at two` : ''}. `
          + `A hop is a published circuit, not a distance - a site one hop away may be a `
          + `hundred kilometres away.${reach.refusals.length
            ? ` ${reach.refusals.length} branch${reach.refusals.length === 1 ? ' was' : 'es were'} `
              + `not walked because a circuit cannot change voltage; only a transformer can.`
            : ''}`);
        electrical.answered += 1;
        electrical.refusals += reach.refusals.length;
      }
      if (facts.neighbours.length) {
        const shownNeighbours = facts.neighbours.slice(0, 6);
        out += caveat(`<b>Circuits reach:</b> `
          + shownNeighbours.map(n => `${escapeHtml(n.site_name || n.site_code)} (${n.circuits})`).join(', ')
          + (facts.neighbours.length > shownNeighbours.length
            ? ` and ${facts.neighbours.length - shownNeighbours.length} more` : '')
          + `.`);
      }
    }
    if (!shown) {
      return caveat(`<b>Transmission network:</b> none of the substations named here joins by `
        + `name to a published NESO site, so nothing is stated about their circuits.`);
    }
    link.topology = { shown, sites: topology.sites, bytes: topology.bytes };
    out += caveat(`${escapeHtml(module ? module.not_an_assessment : '')} `
      + `Counts are branches landing on this site's nodes at the stated voltage, from `
      + `ETYS Appendix B via Ventusltd/data-grid-gb.`);
    return out;
  }

  const FLOW_COLOUR = '#bfe9ee';         // pale cyan travelling pulse, not white

  // The flow. MapLibre repeats a dash array along the line, so a short period
  // puts several electrons on the wire at once instead of one dot going round.
  // Two layers half a period apart double the density without doubling the
  // speed, which would only look frantic.
  const FLOW_PERIOD = 1.5;
  const FLOW_SPEED = 0.055;
  const FLOW_PULSE = 0.42;

  /* A fixed set of dash patterns, cycled — not a new one every frame.
     ----------------------------------------------------------------------
     MapLibre rasterises every distinct line-dasharray into a texture atlas
     (its LineAtlas) and keeps it for the lifetime of the map. A continuously
     varying dasharray therefore asks for a NEW entry sixty times a second,
     and the atlas fills: it runs out of space in about twenty seconds, after
     which lines stop drawing correctly and the renderer spends its time
     managing a texture nobody will reuse.

     Reported by the Codex session's LineAtlas cardinality gate, which counted
     five continuously varying writes and refused to call the storm fixed. It
     was right: the glyph fault in v9.21 and v9.22 was a different fault with a
     similar symptom, and fixing one did not fix the other.

     The animation only needs to LOOK continuous. Twenty-four phases around the
     cycle is finer than the eye resolves on a moving dash at this speed, and
     it bounds the atlas at twenty-four entries forever. The patterns are built
     once, at module load, so the running loop only ever hands back an array it
     has already handed back before, and MapLibre reuses the raster.

     Interpolating the phase against a frame index rather than a clock also
     makes the flow independent of frame rate, which it was not: a slow phone
     ran the electrons slower than a desktop. */
  const FLOW_STEPS = 24;

  const FLOW_PATTERNS = (() => {
    const patterns = [];
    for (let step = 0; step < FLOW_STEPS; step += 1) {
      const phase = (step / FLOW_STEPS) * FLOW_PERIOD;
      const lead = Math.max(0.001, phase);
      const tail = Math.max(0.001, FLOW_PERIOD - phase);
      // Frozen: a caller that mutated one of these would poison every frame
      // that reuses it, and the reuse is the whole point.
      patterns.push(Object.freeze([0.001, lead, FLOW_PULSE, tail]));
    }
    return Object.freeze(patterns);
  })();

  // Quantise to one of the prepared patterns. Same input band, same array
  // identity, so the atlas never grows past FLOW_STEPS.
  /* Write a dash only when it changes.
     ----------------------------------------------------------------------
     Bounding the atlas to twenty-four patterns stopped it filling, but the
     call sites still handed MapLibre a value sixty times a second, and
     twenty-three of every twenty-four of those were the value it already had.

     Codex's cardinality gate went on failing on exactly that, and it was
     asking the right question: a paint-property write per frame is a promise
     to the renderer that something changed, and it is cheaper not to make it
     when nothing has.

     MEASURED, and smaller than it looks. At FLOW_SPEED 0.055 over a period of
     1.5 the phase advances 3.7% of the cycle per frame while a step is 4.2%,
     so the pattern really does change on most frames: 3,168 writes in 3,600
     frames, a reduction of 1.1x rather than the 3.5x this comment first
     claimed. The saving grows with frame rate, which is the case it is for --
     at 120 Hz half the frames become redundant, and on a slow phone almost
     none do.

     The bound on the atlas is the substantive fix. This is tidiness on top of
     it, and worth having because it is free.

     The index is remembered per layer, because the two flow layers run half a
     period apart and would otherwise fight over one memo. */
  const lastDashIndex = new Map();

  function setFlowDash(map, layerId, phase) {
    const index = flowIndex(phase);
    if (lastDashIndex.get(layerId) === index) return false;
    lastDashIndex.set(layerId, index);
    map.setPaintProperty(layerId, 'line-dasharray', FLOW_PATTERNS[index]);
    return true;
  }

  // Forgotten when the layers go, or a rebuilt layer keeps a stale memo and
  // misses its first write.
  function forgetDashMemo() { lastDashIndex.clear(); }

  function flowIndex(phase) {
    const wrapped = ((phase % FLOW_PERIOD) + FLOW_PERIOD) % FLOW_PERIOD;
    return Math.floor((wrapped / FLOW_PERIOD) * FLOW_STEPS) % FLOW_STEPS;
  }

  function flowDash(phase) {
    return FLOW_PATTERNS[flowIndex(phase)];
  }
  flowDash.patterns = FLOW_PATTERNS;

  const SRC = 'gridatlas-neon-links';
  const SRC_NODES = 'gridatlas-neon-nodes';
  const L_GLOW = 'l-neon-glow';
  const L_CORE = 'l-neon-core';
  const L_FLOW = 'l-neon-flow';
  const L_FLOW_B = 'l-neon-flow-b';
  const L_NODE = 'l-neon-node';
  const L_NODE_RING = 'l-neon-node-ring';
  const L_LABEL = 'l-neon-label';

  const link = {
    schema: 'gridatlas.neon-substation-links.v1',
    generation: GENERATION,
    minimum_kv: MIN_KV,
    map_captured: false,
    installed: false,
    substations_loaded: 0,
    substations_qualifying: 0,
    last_selection: null,
    links_drawn: 0,
    deep_linked: false,
    boot_trigger: null,
    layer_controls_ready_ms: null,
    layer_controls_arrived_late: false,
    status_message: null,
    labels_drawn: null,
    gb_panel_installed: false,
    version_ledger: null,
    gb_conditions: null,
    project_layer_enabled: null,
    project_pin: { shown: false, name: null },
    substation_layer_enabled: false,
    reduced_motion: false,
    failures: [],
    /* Codex supervision, 202609011446: entries that later recovered stayed
       in `failures`, making a recovered event indistinguishable from a
       terminal fault. Recovery moves an entry here, at the moment the late
       control actually arrives - the entry is preserved as history, and
       `failures` speaks only for what is still failing. */
    recovered: [],
    grid_scope: null,
    grid_scope_armed: false
  };
  window.__GRIDATLAS_NEON_LINKS__ = link;

  /* One entry per distinct active failure. A retry loop used to append the
     same sentence on every attempt, so three tries read as three faults
     and a reader could not tell repetition from spread. Deduplicated
     against what is CURRENTLY failing, never against what has already
     recovered - a fault that comes back deserves to be recorded again. */
  function noteFailure(message) {
    if (!link.failures.includes(message)) link.failures.push(message);
    return false;
  }

  function recoverFailures(pattern) {
    const kept = [];
    for (const entry of link.failures) {
      if (pattern.test(entry)) link.recovered.push(entry);
      else kept.push(entry);
    }
    link.failures = kept;
  }

  /* ── geodesy ─────────────────────────────────────────────────────────── */

  /* Delegated, not reimplemented. Kept as a function declaration rather
     than a const binding so that hoisting behaves exactly as it did before
     - callers earlier in the file are unchanged. */
  function distanceKm(lon1, lat1, lon2, lat2) {
    return GEODESY.distanceKm(lon1, lat1, lon2, lat2);
  }

  /* ── substation layer ────────────────────────────────────────────────── */

  // `33000`, `33000;11000` (two voltages) and `33000:11000` (a transformer
  // ratio) all mean 33 kV is present. Splitting only on ';' drops the ratios.
  /* The unit comes from the property, never from the size of the number.
     ----------------------------------------------------------------------
     This guessed: anything over 1,000 was volts, anything under was already
     kilovolts. That is not what the source says. OSM's `voltage` tag is in
     VOLTS throughout, including its small values, while an explicit `kv`
     property is already kilovolts. Magnitude is not the unit.

     Audited by the Codex session against the pinned 5,800-feature substation
     payload: all 5,800 use `voltage`, 229 of them (3.95%) carry a token below
     1,000, and every one of those was misread. 204 then displayed a primary
     voltage ABOVE 400 kV, which does not exist anywhere on this network. The
     low tokens are 230 (10), 240 (1), 400 (14), 415 (2) and 750 (202) volts —
     the 750s are DC traction supplies at railway depots, so a depot's third
     rail was being shown as a 750 kV substation.

     Measured project impact, from that audit:

       19709  Selhurst Traincare Depot     33000;750       750 kV  ->  33 kV
       18128  Thames Way, Northfleet       33000;750       750 kV  ->  33 kV
       14596  Ford Halewood Transmissions  33000;11000;415 415 kV  ->  33 kV

     Each of those is a real project whose nearest displayed candidate carried
     an impossible voltage, on a card that also carries a distance. A wrong
     voltage beside a right distance is worse than either alone, because the
     distance lends it credibility.

     A bare `33` under `voltage` is therefore 33 volts and correctly falls out
     of a 33 kV-and-above scope. That reads oddly until you remember it is the
     source's own unit; and Codex confirmed the pinned payload contains no such
     token, so nothing real is lost by obeying the contract rather than
     second-guessing it. */
  function voltagesKv(properties) {
    const out = [];
    const push = (raw, divisor) => {
      for (const token of String(raw ?? '').split(/[;,|:\s]+/)) {
        if (!token) continue;
        const value = Number(token);
        if (!Number.isFinite(value) || value <= 0) continue;
        out.push(value / divisor);
      }
    };
    // OSM `voltage` is volts. Always, at every magnitude.
    push(properties?.voltage, 1000);
    // An explicit `kv` is already kilovolts.
    if (!out.length) push(properties?.kv, 1);
    return out;
  }

  // A polygon's first ring vertex is a corner, not the site.
  function representativePoint(geometry) {
    if (!geometry) return null;
    const { type, coordinates } = geometry;
    if (type === 'Point') return [coordinates[0], coordinates[1]];
    const ring = type === 'Polygon' ? coordinates[0]
      : type === 'MultiPolygon' ? coordinates[0]?.[0] : null;
    if (!Array.isArray(ring) || !ring.length) return null;
    let x = 0; let y = 0;
    for (const p of ring) { x += p[0]; y += p[1]; }
    return [x / ring.length, y / ring.length];
  }

  // Exposed so a proof can check this arithmetic against
  // Ventusltd/grid-distance-maths rather than trusting the comment above it.
  // Pure functions only; nothing here touches the map or the DOM.
  link.measure = { distanceKm, voltagesKv, representativePoint };

  /* The receiver decision is pure and exported because Pipeline News owns
     the complete link corpus. The product path below consumes this exact
     plan; the corpus proof can therefore pass all 8,756 derived source
     points (8,753 served coordinate rows and 8,743 clickable actions)
     through the same decision without booting a map or a 35.7 MB register. */
  function deepLinkPlan(rawLon, rawLat, rawRepdRef) {
    const longitude = rawLon === null ? NaN : Number(rawLon);
    const latitude = rawLat === null ? NaN : Number(rawLat);
    const repdRef = String(rawRepdRef || '').trim();
    const coordinatesUsable = Number.isFinite(longitude) && Number.isFinite(latitude)
      && Math.abs(longitude) <= 180 && Math.abs(latitude) <= 90
      && !(Math.abs(longitude) < 1e-9 && Math.abs(latitude) < 1e-9);
    return Object.freeze({
      longitude, latitude, repd_ref: repdRef, coordinates_usable: coordinatesUsable,
      route: coordinatesUsable ? 'MEASURE_LINK_FIRST'
        : (repdRef ? 'WAIT_FOR_REGISTER' : 'NO_USABLE_POINT')
    });
  }
  link.measure.deepLinkPlan = deepLinkPlan;

  /* A resolved register identity is an asynchronous continuation of one
     particular arrival, not permission to take the map back later. User
     selection and clear paths invalidate the token. The same coordinator is
     exported so the generation proof can resolve a deliberately late promise
     through the production gate rather than restating this race in a mock. */
  function createArrivalGate() {
    let epoch = 0;
    let activeKey = null;
    const invalidations = [];
    return Object.freeze({
      begin(key = null) {
        const candidate = key == null ? null : String(key);
        /* The search owner and the measurement owner claim the same URL
           independently as their scripts boot. A keyed claim is idempotent,
           so whichever starts first gives both halves one cancellation
           epoch rather than making the second half stale immediately. */
        if (candidate && candidate === activeKey) return epoch;
        epoch += 1;
        activeKey = candidate;
        return epoch;
      },
      invalidate(reason) {
        epoch += 1;
        activeKey = null;
        invalidations.push({ epoch, reason: String(reason || 'unspecified') });
        return epoch;
      },
      isCurrent(candidate) { return candidate === epoch; },
      snapshot() { return Object.freeze({ epoch, activeKey,
        invalidations: [...invalidations] }); }
    });
  }
  async function continueVerifiedArrival(gate, epoch, verification, apply) {
    const result = await verification;
    if (!gate.isCurrent(epoch)) return false;
    await apply(result);
    return gate.isCurrent(epoch);
  }
  const arrivalGate = createArrivalGate();
  function arrivalKey(search = window.location.search) {
    return 'deep-link:' + String(search || '');
  }
  function claimPendingArrival(search = window.location.search) {
    return arrivalGate.begin(arrivalKey(search));
  }
  function invalidatePendingArrival(reason) {
    const epoch = arrivalGate.invalidate(reason);
    link.arrival_reconciliation = { status: 'INVALIDATED', reason, epoch };
    try {
      window.dispatchEvent(new CustomEvent('gridatlas:arrival-invalidated', {
        detail: { reason: String(reason || 'unspecified'), epoch }
      }));
    } catch (_) { /* cancellation still lives in the shared gate */ }
    return epoch;
  }
  link.measure.createArrivalGate = createArrivalGate;
  link.measure.continueVerifiedArrival = continueVerifiedArrival;
  link.measure.arrivalGate = arrivalGate;
  link.measure.arrivalKey = arrivalKey;
  link.measure.claimPendingArrival = claimPendingArrival;
  link.measure.invalidatePendingArrival = invalidatePendingArrival;
  link.enableSubstationLayer = () => enableSubstationLayer();
  link.armGridScope = (on) => { scopeArmed = Boolean(on); return scopeArmed; };
  link.clearGridScope = () => clearScope();
  link.noteFailure = (message) => noteFailure(message);

  /* A browser-history move is a user navigation, not permission for the
     asynchronous identity query from the URL being left to reclaim the map.
     replaceState used by the owner does not emit these events. */
  window.addEventListener('popstate', () => invalidatePendingArrival('history-navigation'));
  window.addEventListener('hashchange', () => invalidatePendingArrival('history-navigation'));

  let substationsPromise = null;
  function loadSubstations() {
    if (substationsPromise) return substationsPromise;
    substationsPromise = (async () => {
      // The engine may already hold the layer; prefer that over a second fetch.
      const response = await fetch(new URL(SUBS_URL, document.baseURI), { cache: 'force-cache' });
      if (!response.ok) throw new Error(`substations HTTP ${response.status}`);
      const collection = await response.json();
      const features = Array.isArray(collection?.features) ? collection.features : [];
      link.substations_loaded = features.length;
      const out = [];
      for (const feature of features) {
        const kv = voltagesKv(feature.properties);
        if (!kv.length || Math.max(...kv) < MIN_KV - 0.5) continue;
        const at = representativePoint(feature.geometry);
        if (!at) continue;
        out.push({
          at,
          kv: kv.filter(v => v >= MIN_KV - 0.5).sort((a, b) => b - a),
          name: feature.properties?.name || '',
          operator: feature.properties?.operator
            || feature.properties?.['operator:short'] || ''
        });
      }
      link.substations_qualifying = out.length;
      return out;
    })().catch(error => {
      link.failures.push(String(error?.message || error));
      substationsPromise = null;
      return [];
    });
    return substationsPromise;
  }

  function nearestSubstations(lon, lat, subs) {
    const scored = [];
    for (const sub of subs) {
      const km = distanceKm(lon, lat, sub.at[0], sub.at[1]);
      if (km > MAX_LINK_KM) continue;
      scored.push({ ...sub, km });
    }
    scored.sort((a, b) => a.km - b.km);
    return scored.slice(0, LINK_COUNT);
  }

  // The mirror of nearestSubstations: given a substation, the projects around
  // it. Read from the loaded source rather than the viewport, so panning the
  // map does not change the answer -- querySourceFeatures returns what the
  // GeoJSON source holds, queryRenderedFeatures returns only what is on screen.
  function nearestProjects(map, lon, lat) {
    let features = [];
    try { features = map.querySourceFeatures('src-repd') || []; }
    catch (_) { return { loaded: false, links: [] }; }
    // querySourceFeatures reads loaded tiles. With every project layer switched
    // off there are none, and returning an empty list here made the card say
    // "no mapped project within 40 km" of a substation with a 840 MW scheme
    // beside it. Absence from a layer that is not loaded is not absence on the
    // ground, and this is exactly where that rule has to hold.
    if (!features.length) return { loaded: false, links: [] };
    const seen = new Set();
    const scored = [];
    for (const feature of features) {
      const properties = feature.properties || {};
      const tech = String(properties.tech || properties.type || '');
      if (!isProjectTech(tech)) continue;
      const at = representativePoint(feature.geometry);
      if (!at) continue;