GLOBALGRID2050 / EXPLORE CODE

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

Secondary Neon Engine and 1 more file

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 2 files. Topic: Maps, GIS and field navigation. Section 555 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. G203 04 SatNav Walk Saved Plan interaction · gridatlas / atlas/modules/20261202-g203-04-satnav-walk-saved-plan.js lines 1–253
  2. Secondary Neon Engine geodesy · gridatlas / atlas/modules/202612020205-secondary-neon-engine.js lines 1–447

G203 04 SatNav Walk Saved Plan

A JavaScript file in the atlas folder of GridAtlas that formats distance (`formatDistance`), shows pin (`showPin`), mounts offline plan (`mountOfflinePlan`) and draws SVG graphics.

interactiongridatlas / atlas/modules/20261202-g203-04-satnav-walk-saved-plan.js · lines 1–253 of 253 · version 2026-12-02 · pattern offlinePlanDocument (shared by 2 files)

What it does
It draws its content. Defines 12 functions or classes, including fieldPlan, displayPlan, byId, formatDistance, showPin. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
Out: SVG drawing.
Downstream impact
Used directly by 1 file: SatNav G203 04 Saved Plan Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It formats distance (`formatDistance`) and shows pin (`showPin`). G203-04: immutable successor; original offline-plan helper inlined to pin all executable mount code. It responds to statechange and satnav events.
Why it matters
Checked by SatNav G203 04 Saved Plan Test.
Application
gridatlas · atlas/modules · script
VEDIC
SAVE OFFLINE PLAN (GG2050-VEDIC-000100): SatNav · Location and navigation data. DOM container, selected pins callback, distance and bearing functions, secure browser with service worker and Cache Storage → Offline plan controls and a locally cached standalone HTML plan after the user presses Save.
Uses
none found
Used by
referenced by SatNav G203 04 Saved Plan Test (new URL import.meta.url), mentioned in Standalone (comment link)
Produces
fieldPlan, displayPlan, byId, formatDistance, showPin, offlinePlanDocument, activateWorker, finish, cleanup, mountOfflinePlan, change, mount
Defines here
fieldPlan, displayPlan, byId, formatDistance, showPin, offlinePlanDocument, activateWorker, finish, cleanup, mountOfflinePlan, change, mount
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/20261202-g203-04-satnav-walk-saved-plan.js:1-253 · blob db012f7aa5ce0bedba9e59bfe2f5d99c89331090 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
/* G203-04: immutable successor; original offline-plan helper inlined to pin all executable mount code. */
void function () {
// SPDX-License-Identifier: Apache-2.0
// Saves the planned pins on this device only, after the user presses Save.
const cacheName = 'ventus-satnav-offline-plans-v1';

function fieldPlan(pins, maths) {
  if (!Array.isArray(pins) || pins.length < 2 || pins.length > 20000) {
    throw new Error('Choose between 2 and 20,000 plan pins before saving.');
  }
  const coordinates = pins.map(pin => {
    const at = pin?.coordinate ?? pin;
    if (!Array.isArray(at) || at.length !== 2 || !at.every(Number.isFinite)
        || Math.abs(at[0]) > 180 || Math.abs(at[1]) > 90) {
      throw new Error('A plan pin has invalid coordinates.');
    }
    return [at[0], at[1]];
  });
  let totalM = 0;
  const legs = coordinates.slice(1).map((to, i) => {
    const from = coordinates[i];
    const metres = maths.distanceKm(...from, ...to) * 1000;
    const bearing = metres > 0 ? maths.initialBearingDeg(...from, ...to) : null;
    if (!Number.isFinite(metres) || metres < 0 || (bearing !== null && !Number.isFinite(bearing))) {
      throw new Error('Unable to measure the selected plan.');
    }
    totalM += metres;
    return [Math.round(metres), bearing === null ? null : (Math.round(bearing) + 360) % 360];
  });
  return {coordinates, legs, totalM: Math.round(totalM), savedAt: new Date().toISOString()};
}

// This function is embedded in the saved HTML so it can run without a network or dependencies.
function displayPlan() {
  const plan = JSON.parse(document.getElementById('saved-plan').textContent);
  const points = plan.coordinates;
  const byId = id => document.getElementById(id);
  const formatDistance = m => m < 1000 ? m + ' m' : (m / 1000).toLocaleString('en-GB', {maximumFractionDigits: 2}) + ' km';
  const scope = new URL('./', location.href);
  const previous = byId('previous'), next = byId('next');
  let index = 0;
  let x = points[0][0];
  const projected = points.map(([lng, lat], i) => {
    if (i) x += ((lng - points[i - 1][0] + 540) % 360) - 180;
    return [x, lat];
  });
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  for (const [lng, lat] of projected) {
    minX = Math.min(minX, lng); maxX = Math.max(maxX, lng);
    minY = Math.min(minY, lat); maxY = Math.max(maxY, lat);
  }
  const cos = Math.max(0.000001, Math.cos((minY + maxY) * Math.PI / 360));
  const scaleX = (maxX - minX) * cos;
  const scaleY = maxY - minY;
  const scale = Math.min(scaleX ? 284 / scaleX : Infinity, scaleY ? 150 / scaleY : Infinity);
  const factor = Number.isFinite(scale) ? scale : 1;
  const chart = projected.map(([lng, lat]) => [
    +(160 + (lng - (minX + maxX) / 2) * cos * factor).toFixed(2),
    +(90 - (lat - (minY + maxY) / 2) * factor).toFixed(2),
  ]);
  byId('line').setAttribute('points', chart.map(p => p.join(',')).join(' '));
  byId('summary').textContent = points.length.toLocaleString('en-GB') + ' pins · ' + formatDistance(plan.totalM) + ' planned';
  byId('saved-at').textContent = 'Saved ' + new Date(plan.savedAt).toLocaleString('en-GB');
  function showPin() {
    const [lng, lat] = points[index], leg = plan.legs[index];
    byId('pin').textContent = 'Pin ' + (index + 1) + ' of ' + points.length;
    byId('coordinate').textContent = lat.toFixed(5) + '°, ' + lng.toFixed(5) + '°';
    byId('leg').textContent = leg
      ? 'To next pin: ' + formatDistance(leg[0]) + (leg[1] === null ? '' : ' · ' + leg[1] + '° true')
      : 'Last planned pin';
    byId('marker').setAttribute('cx', chart[index][0]);
    byId('marker').setAttribute('cy', chart[index][1]);
    previous.disabled = index === 0; next.disabled = index === points.length - 1;
  }
  previous.onclick = () => { if (index > 0) index--; showPin(); };
  next.onclick = () => { if (index < points.length - 1) index++; showPin(); };
  byId('reload').onclick = () => location.reload();
  byId('forget').onclick = async () => {
    try {
      const cache = await caches.open('ventus-satnav-offline-plans-v1');
      await cache.delete(new URL('__saved-field-plan__', scope));
      const message = document.createElement('p');
      message.textContent = 'Saved plan removed from this device.';
      document.querySelector('main').replaceChildren(message, byId('reload'));
    } catch {
      byId('saved-at').textContent = 'Could not remove the saved plan. Try again.';
    }
  };
  showPin();
}

function offlinePlanDocument(pins, maths) {
  const data = fieldPlan(pins, maths);
  // Only validated number pairs, measured legs and our own ISO date reach the data element.
  return `<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><title>Saved field plan · Ventus SatNav</title>
<style>
*{box-sizing:border-box}body{margin:0;background:#07151a;color:#e4f6f7;font:1rem/1.45 system-ui,sans-serif}
main{max-width:40rem;margin:auto;padding:1rem}h1{margin:.4rem 0}p{margin:.5rem 0}svg{display:block;width:100%;max-height:38vh;border:1px solid #48777c;border-radius:.5rem;background:#0a2026}
button{min-height:44px;margin:.2rem .25rem .2rem 0;padding:.35rem .85rem;color:inherit;background:#123239;border:1px solid #56868a;border-radius:.4rem;font:inherit}
button:focus-visible{outline:2px solid white}button:disabled{opacity:.48}small{color:#b1ced0}footer{margin-top:.8rem}
</style></head><body><main><h1>Saved field plan</h1><p id="summary"></p>
<svg viewBox="0 0 320 180" role="img" aria-label="North-up diagram of the planned pins"><polyline id="line" fill="none" stroke="#58d9e3" stroke-width="2.5"/><circle id="marker" r="5.5" fill="#ffdc73" stroke="#07151a" stroke-width="2"/></svg>
<p><small>Planned straight lines · North up · GPS off</small></p>
<section aria-live="polite"><strong id="pin"></strong><p id="coordinate"></p><p id="leg"></p></section>
<button id="previous" type="button">Previous pin</button><button id="next" type="button">Next pin</button>
<footer><p><small id="saved-at"></small></p><button id="reload" type="button">Reopen live map</button><button id="forget" type="button">Forget saved plan</button>
<p><small>Check access rights, restrictions and safe working arrangements before entering land.</small></p></footer>
</main><script type="application/json" id="saved-plan">${JSON.stringify(data)}</script>
<script>(${displayPlan.toString()})()</script></body></html>`;
}

async function activateWorker(scope) {
  const workerURL = new URL('../satnav-offline-plan-202611281315-worker.js', scope);
  const previousWorkerURL = new URL('../satnav-offline-plan-20261128-worker.js', scope);
  const existing = await navigator.serviceWorker.getRegistration(scope);
  if (existing?.scope === scope.href) {
    for (const worker of [existing.active, existing.installing, existing.waiting]) {
      if (worker && worker.scriptURL !== workerURL.href && worker.scriptURL !== previousWorkerURL.href) throw new Error('This version uses a different offline map.');
    }
    if (existing.active?.state === 'activated' && existing.active.scriptURL === workerURL.href) return;
  }
  const registration = await navigator.serviceWorker.register(workerURL, {scope: scope.pathname});
  const worker = registration.installing || registration.waiting || registration.active;
  if (!worker) throw new Error('Offline access did not start. Try again while online.');
  if (worker.state === 'activated') return;
  await new Promise((resolve, reject) => {
    const finish = () => {
      if (worker.state === 'activated') { cleanup(); resolve(); }
      if (worker.state === 'redundant') { cleanup(); reject(new Error('Offline access could not start.')); }
    };
    const cleanup = () => { clearTimeout(timeout); worker.removeEventListener('statechange', finish); };
    const timeout = setTimeout(() => { cleanup(); reject(new Error('Offline access timed out. Try again.')); }, 15000);
    worker.addEventListener('statechange', finish);
    finish();
  });
}

function mountOfflinePlan({container, getPins, maths}) {
  const scope = new URL('./', location.href);
  if (!/\/atlas\/v\/(?:satnav-[\w.-]+|\d{12})\/$/.test(scope.pathname)) throw new Error('A versioned SatNav entry is required.');
  const key = new URL('__saved-field-plan__', scope);
  const area = document.createElement('details');
  area.innerHTML = '<summary>Offline plan</summary><p>Save selected pins on this device for offline reading.</p><button type="button">Save plan</button> <button type="button">Forget saved plan</button><p role="status"></p>';
  const [save, forget] = area.querySelectorAll('button');
  const status = area.querySelector('[role="status"]');
  container.append(area);
  if (!window.isSecureContext || !('serviceWorker' in navigator) || !('caches' in window)) {
    save.disabled = forget.disabled = true;
    status.textContent = 'Offline saving is unavailable in this browser.';
    return area;
  }

  async function change(action) {
    save.disabled = forget.disabled = true;
    try {
      if (action === 'save') {
        const html = offlinePlanDocument(getPins(), maths);
        await activateWorker(scope);
        const cache = await caches.open(cacheName);
        await cache.put(key, new Response(html, {headers: {
          'Content-Type': 'text/html; charset=utf-8',
          'Content-Security-Policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'",
          'Cache-Control': 'no-store',
        }}));
        status.textContent = 'Saved. Reopen this map address offline to read the plan.';
      } else {
        const cache = await caches.open(cacheName);
        await cache.delete(key);
        status.textContent = 'Saved plan removed from this device.';
      }
    } catch (error) {
      status.textContent = error?.message || 'Could not change the saved plan on this device.';
    } finally {
      save.disabled = forget.disabled = false;
    }
  }
  save.onclick = () => change('save');
  forget.onclick = () => change('forget');
  return area;
}

/* Restore this version's saved design pins to the same map used for a hand-placed walk. */
void function () {
  const scope = new URL('./', location.href);
  let mounted = false;

  async function mount() {
    const host = document.getElementById('satnav-field-tools');
    const survey = document.getElementById('satnav-compact')?.satnavSurvey;
    if (!host || !survey || mounted) return;
    mounted = true;
    document.removeEventListener('satnav:ready', mount);

    try {

      const area = mountOfflinePlan({container: host, getPins: survey.getPins, maths: survey.maths});
      const [save, forget] = area.querySelectorAll('button');
      if (save.disabled) return;

      const status = area.querySelector('[role="status"]');
      const restore = document.createElement('button');
      restore.type = 'button';
      restore.textContent = 'Use saved plan';
      forget.before(restore, ' ');
      // Saving and forgetting already lock these controls while the cache is changing.
      new MutationObserver(() => { restore.disabled = save.disabled; })
        .observe(save, {attributes: true, attributeFilter: ['disabled']});

      restore.onclick = async () => {
        if (save.disabled) return;
        const previous = survey.getPins();
        save.disabled = forget.disabled = restore.disabled = true;
        try {
          const key = new URL('__saved-field-plan__', scope);
          const response = await caches.match(key, {cacheName: 'ventus-satnav-offline-plans-v1'});
          if (!response) {
            status.textContent = 'No saved plan for this map.';
            return;
          }
          // The existing offline document stores design coordinates as JSON.
          // Read its data in an inert template, without loading its offline viewer.
          const snapshot = document.createElement('template');
          snapshot.innerHTML = await response.text();
          const data = snapshot.content.querySelector('script#saved-plan[type="application/json"]');
          const coordinates = JSON.parse(data?.textContent ?? 'null')?.coordinates;
          if (!Array.isArray(coordinates) || coordinates.length < 2) throw Error('Invalid saved plan');
          if (survey.getPins() !== previous) {
            status.textContent = 'The plan changed. Tap Use saved plan again to replace it.';
            return;
          }
          // replacePlan validates every pin before changing endpoints and notifying walking guidance.
          survey.replacePlan(coordinates);
          status.textContent = 'Saved plan loaded · ' + coordinates.length.toLocaleString('en-GB') + ' pins.';
        } catch {
          status.textContent = 'Could not load the saved plan.';
        } finally {
          save.disabled = forget.disabled = restore.disabled = false;
        }
      };
    } catch (error) {
      console.error('Saved plan mount failed', error?.name || 'Error');
      const message = document.createElement('p');
      message.setAttribute('role', 'status');
      message.textContent = 'Saved plan controls could not load.';
      host.append(message);
    }
  }
  document.addEventListener('satnav:ready', mount);
  void mount();
}();

}();

Secondary Neon Engine

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

geodesygridatlas / atlas/modules/202612020205-secondary-neon-engine.js · lines 1–447 of 9008 · version 2026-12-02 02:05 · Not reached from any entry point (candidate for review) · pattern isInterconnectorArrival (shared by 3 files)

What it does
It maps connection points, GB transmission network, price decade rollup and grid substations. Defines 274 functions or classes, including distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
Inputs & outputs
In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; GeoJSON file grid_substations.geojson; JSON file neso-connection-sites.lean.json; GeoJSON file interconnectors.geojson; browser storage (getItem); DuckDB queries. Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 110kV, 66kV.
What it achieves
It creates compute observer (`createComputeObserver`), describes compute receipt (`describeComputeReceipt`) and builds stats (`buildStats`). Receipt and distance owner: Ventusltd/ventus-grid-engine. Its code works with 400 kV, 132 kV and 33 kV. It responds to click, keydown and touchstart events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
Uses
none found
Used by
none found
Produces
distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver
Defines here
distanceKm, distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver, publish, get, describeComputeReceipt, classOf, scope
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202612020205-secondary-neon-engine.js:1-447 · blob 26e5045a356c11088820207d3cbe95eb4b89374f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* Receipt and distance owner: Ventusltd/ventus-grid-engine 487ec7bd38dfa5aecb1c75da53b4a866ab2101cb */
/* Ventus Grid Engine: generated receipt observer; not a substitute nearest engine. */
(() => {
'use strict';
const distanceKm = (() => {
/**
 * Module: geodesy
 *
 * Extracted verbatim (formula and constant unchanged) from
 * gridatlas/atlas/modules/202609011950-geodesy.js.
 *
 * One Earth radius for the whole estate, and the three operations every
 * measurement here is built from. This existed three times tonight - in
 * the sandbox, in the substation cartridge and in the data repository -
 * which is exactly how two of them end up on different radii without
 * anyone noticing.
 *
 * Radius 6378.137 km, matching Ventusltd/grid-distance-maths. Haversine.
 * No projection, no turf, no second radius for geometry.
 *
 * Pure functions. No DOM, no network, no state.
 *
 * CHANGED: source wraps this in `(() => { ... NS.geodesy = Object.freeze({...}) })()`
 * and registers itself on `window.__GRIDATLAS_MODULES__.geodesy`. That
 * closure/global-namespace wiring is removed; every function below is
 * otherwise byte-identical to the source, including the atan2 argument
 * order that the source's own comment insists on for numerical parity
 * with ventus-corev8engine.js haversine() (see distanceKm below).
 */

const EARTH_RADIUS_KM = 6378.137;
const DEG = Math.PI / 180;

function distanceKm(lon1, lat1, lon2, lat2) {
  const dLat = (lat2 - lat1) * DEG;
  const dLon = (lon2 - lon1) * DEG;
  const a = Math.sin(dLat / 2) ** 2
    + Math.cos(lat1 * DEG) * Math.cos(lat2 * DEG) * Math.sin(dLon / 2) ** 2;
  /* atan2, in this operand order, because that is the form every version
     of this estate has shipped - ventus-corev8engine.js haversine() and
     every cartridge carried from it.
     -------------------------------------------------------------------
     The extraction wrote 2 * R * asin(sqrt(a)) instead. Algebraically the
     same; numerically one unit in the last place apart, which the
     all-versions proof caught on West Burton Solar to Cottam:
     7.050150827184836 shipped, 7.050150827184837 from the module. It is
     1e-15 km and changes no figure any reader will ever see - and it is
     still wrong, because the claim being made is PARITY. A module that is
     nearly the incumbent is a module that has to be argued about every
     time a digit differs. */
  return EARTH_RADIUS_KM * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}

/* A polygon reduces to the mean of its outer ring, not its first corner.
   A substation drawn as a compound outline would otherwise be measured
   from whichever vertex the mapper happened to start at.

   Point, Polygon and MultiPolygon, and NOTHING ELSE. The first draft of
   this module accepted any nested coordinate array and so returned a
   mean for a LineString where the incumbent returns null; the parity
   proof caught it against the live cartridge. Extraction is not the
   moment to change behaviour, so the behaviour is pinned here and any
   widening becomes its own version with its own reasoning.

   One deliberate difference, on malformed input only: this returns null
   where the incumbent would throw on a Point with no coordinates. No
   real geometry reaches that path, and a proof asserts it. */
function representativePoint(geometry) {
  if (!geometry) return null;
  const { type, coordinates } = geometry;
  if (type === 'Point') {
    return Array.isArray(coordinates) && coordinates.length >= 2
      ? [coordinates[0], coordinates[1]] : null;
  }
  const ring = type === 'Polygon' ? coordinates && coordinates[0]
    : type === 'MultiPolygon' ? coordinates && coordinates[0] && coordinates[0][0]
      : null;
  if (!Array.isArray(ring) || !ring.length) return null;
  let sumLon = 0;
  let sumLat = 0;
  for (const point of ring) {
    sumLon += point[0];
    sumLat += point[1];
  }
  return [sumLon / ring.length, sumLat / ring.length];
}

/* OpenStreetMap's `voltage` is VOLTS at every magnitude, and a feature
   may carry several separated by a semicolon. Magnitude is not the unit:
   750 is a DC traction supply at a railway depot, not 750 kV. An audit
   of the served payload found 229 features (3.95%) carrying a token
   below 1,000, every one of which had been misread. An explicit `kv`
   property is already kilovolts and is trusted as such. */
function voltagesKv(properties) {
  if (!properties) return [];
  const out = [];
  const explicit = properties.kv ?? properties.KV;
  if (explicit != null && String(explicit).trim() !== '') {
    for (const token of String(explicit).match(/\d+(?:\.\d+)?/g) || []) {
      const value = Number(token);
      if (Number.isFinite(value) && value > 0) out.push(value);
    }
  }
  const volts = properties.voltage ?? properties.VOLTAGE;
  if (volts != null) {
    for (const token of String(volts).match(/\d+(?:\.\d+)?/g) || []) {
      const value = Number(token);
      if (Number.isFinite(value) && value > 0) out.push(value / 1000);
    }
  }
  return [...new Set(out)].sort((a, b) => b - a);
}

/* Projection and bearing, carried in from the sandbox verbatim.
   ----------------------------------------------------------------------
   The deep scan found the body carrying a SECOND geodesy section - "the
   geodesy the layout needs, all on R_ATLAS" - four hundred lines away
   from the first. Two geodesies in one file, on a constant that must
   never differ, is the configuration that produced the divergence the
   all-versions proof caught. Both belong here, on the one radius, and
   the body now delegates rather than defining.

   The bodies below are the incumbent's, character for character apart
   from the radius identifier, so parity is a property of the move rather
   than something to argue about afterwards. */
function destinationPoint(lon, lat, km, bearingDeg) {
  const ad = km / EARTH_RADIUS_KM;
  const brg = bearingDeg * DEG;
  const p1 = lat * DEG;
  const p2 = Math.asin(Math.sin(p1) * Math.cos(ad)
    + Math.cos(p1) * Math.sin(ad) * Math.cos(brg));
  const l2 = lon * DEG + Math.atan2(
    Math.sin(brg) * Math.sin(ad) * Math.cos(p1),
    Math.cos(ad) - Math.sin(p1) * Math.sin(p2));
  return [l2 / DEG, p2 / DEG];
}

function initialBearingDeg(lon1, lat1, lon2, lat2) {
  const p1 = lat1 * DEG; const p2 = lat2 * DEG;
  const dl = (lon2 - lon1) * DEG;
  const y = Math.sin(dl) * Math.cos(p2);
  const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
  return (Math.atan2(y, x) / DEG + 360) % 360;
}

const schema = 'gridatlas.module.geodesy.v1';

return distanceKm;
})();
/** Actual-computation receipts, shared by Node and browsers. No DOM or network. */

const schema = 'ventus.grid-compute-receipt.v1';
const copy = value => JSON.parse(JSON.stringify(value));
const finite = value => typeof value === 'number' && Number.isFinite(value);
const located = point => point && finite(point.lon) && finite(point.lat)
  && Math.abs(point.lon) <= 180 && Math.abs(point.lat) <= 90;
const sameLocation = (a, b) => located(a) && located(b) && a.lon === b.lon && a.lat === b.lat;
const sameEntity = (a, b) => a && b && a.kind === b.kind && String(a.id) === String(b.id);

/**
 * Create one observer per selection surface, not one per project. Every request
 * invalidates the previous selection for assessment, including repeated IDs.
 * Receipts are evidence about the supplied callback, not proof that a renderer
 * used this module. Attach run() at the real calculation call site.
 */
function createComputeObserver({ onEvent = () => {}, now = () => Date.now() } = {}) {
  const attempts = new Map();
  let sequence = 0;
  let latest = null;
  const publish = (attempt, status, extra = {}) => {
    Object.assign(attempt, extra, { status, sequence: ++sequence, updated_at_ms: now() });
    attempt.events.push({ status, sequence: attempt.sequence, at_ms: attempt.updated_at_ms });
    // A broken logging consumer must never break the grid calculation itself.
    try { onEvent(copy(attempt)); } catch { /* receipt remains queryable */ }
    return copy(attempt);
  };
  const get = id => {
    const attempt = attempts.get(id);
    if (!attempt) throw new Error('Unknown computation attempt: ' + id);
    return attempt;
  };
  return {
    request({ entity, location = null, operation = 'nearest-grid', dataset = null }) {
      if (!entity || typeof entity.kind !== 'string' || !entity.kind.trim()
          || entity.id == null || !String(entity.id).trim()) {
        throw new TypeError('A computation request requires an entity kind and ID');
      }
      const id = 'compute-' + (sequence + 1);
      const attempt = {
        schema, id, entity: { kind: entity.kind, id: String(entity.id) },
        location: located(location) ? { lon: location.lon, lat: location.lat } : null,
        operation, dataset, requested_at_ms: now(), events: []
      };
      attempts.set(id, attempt);
      latest = id;
      publish(attempt, 'requested');
      return id;
    },
    unsupported(id, reason) {
      const attempt = get(id);
      if (attempt.status !== 'requested') throw new Error('Attempt already invoked or terminal');
      return publish(attempt, 'unsupported', { reason: String(reason || 'Unsupported input') });
    },
    async run(id, compute) {
      const attempt = get(id);
      if (attempt.status !== 'requested') throw new Error('Attempt already invoked or terminal');
      if (!attempt.location) return publish(attempt, 'unsupported', { reason: 'No valid project location' });
      if (typeof compute !== 'function') return publish(attempt, 'failed', { reason: 'No computation callback' });
      publish(attempt, 'started');
      try {
        const result = await compute(copy(attempt));
        if (!sameLocation(result?.origin, attempt.location)) throw new Error('Result origin does not match this request');
        if (!sameEntity(result?.entity, attempt.entity)) throw new Error('Result entity does not match this request');
        if (!Array.isArray(result.measurements)) throw new Error('Computation returned no measurements array');
        if (result.measurements.length === 0) {
          if (result.search_completed !== true || !Number.isInteger(result.scanned_count) || result.scanned_count < 0) {
            throw new Error('Empty result lacks completed-search and scanned-count evidence');
          }
          return publish(attempt, 'completed_empty', { measurements: [],
            summary: { measured_count: 0, scanned_count: result.scanned_count, nearest_km: null } });
        }
        const measurements = result.measurements.map(row => {
          if (!row || row.node_id == null || !String(row.node_id).trim()
              || !located(row) || !finite(row.km) || row.km < 0) {
            throw new Error('Computation returned an invalid grid measurement');
          }
          const expected = distanceKm(attempt.location.lon, attempt.location.lat, row.lon, row.lat);
          // Receipts carry unrounded values from the shared geodesy, not UI text.
          if (Math.abs(expected - row.km) > Math.max(1e-6, expected * 1e-9)) {
            throw new Error('Grid distance does not match the request and measured node');
          }
          return { node_id: String(row.node_id), lon: row.lon, lat: row.lat, km: row.km };
        });
        return publish(attempt, 'completed', { measurements,
          summary: { measured_count: measurements.length, nearest_km: Math.min(...measurements.map(row => row.km)) } });
      } catch (error) {
        return publish(attempt, 'failed', { reason: String(error?.message || error) });
      }
    },
    snapshot(id = latest) { return id == null ? null : copy(get(id)); },
    assess(id, expected) {
      if (!attempts.has(id)) return { passed: false, reason: 'never-requested' };
      const attempt = get(id);
      if (id !== latest) return { passed: false, reason: 'stale-attempt' };
      if (!sameEntity(attempt.entity, expected?.entity) || !sameLocation(attempt.location, expected?.location)) {
        return { passed: false, reason: 'selection-mismatch' };
      }
      return { passed: attempt.status === 'completed', reason: attempt.status };
    }
  };
}

/** Honest UI projection of computation receipts. No inference from a URL. */
function describeComputeReceipt(receipt) {
  const status = receipt?.status || 'not_requested';
  const summary = receipt?.summary;
  const nearest = summary?.nearest_km;
  const labels = {
    not_requested: 'Grid calculation not requested', requested: 'Grid calculation queued',
    started: 'Calculating nearest mapped substations', completed_empty: 'Search completed: no mapped substations returned',
    unsupported: 'Grid calculation unavailable', failed: 'Grid calculation failed',
  };
  if (status === 'completed' && Number.isFinite(nearest) && nearest >= 0) {
    return { status, text: `Nearest mapped substation: ${nearest.toFixed(2)} km`,
      distance_km: nearest, unit: 'km', scope: 'Geometric screening only; not an electrical connection, capacity or offer.' };
  }
  return { status, text: labels[status] || 'Grid calculation result unavailable',
    reason: receipt?.reason || null, distance_km: null, unit: null,
    scope: 'Geometric screening only; not an electrical connection, capacity or offer.' };
}

globalThis.VentusGridCompute = Object.freeze({ schema, distanceKm, createComputeObserver, describeComputeReceipt });
})();

/**
 * CARRIED FORWARD AND EDITED, NOT ASSEMBLED. The notice below was true at generation 202609050354. Every generation
 * since has been cut by copying the previous cartridge and editing the copy; the parts it names were not touched again
 * and no longer reproduce this file (they build 363 KB; this is over 420 KB). Do NOT rebuild this cartridge from those
 * parts: that would silently discard everything added since 5 September. Said here at 202609200022 because a header
 * that misdescribes how a file is made is the kind of false record this estate keeps finding.
 *
 * sld-sandbox-v9-8, generation 202609050354 (UTC).
 *
 * ASSEMBLED by tools/build-cartridge.mjs from the parts below. Do not edit
 * this file: edit a part and rebuild under a new generation. Each part is
 * hashed in manifests/202609050354-sld-sandbox-v9-8-parts.json.
 *
 *   module                 atlas/modules/202609012040-grid-scope.js
 *   module                 atlas/modules/202609012217-source-registry.js
 *   module                 atlas/modules/202609012128-declared-connections.js
 *   module                 atlas/modules/202609012205-sizing-arithmetic.js
 *   module                 atlas/modules/202609031310-technology-coverage.js
 *   part                   atlas/parts/202609041234-sld-sandbox-technology-buckets.js
 */

/**
 * Module: grid-scope
 *
 * "When you click on a blank space, the user should be able to see grid in
 * the vicinity. Call it the GRID FINDING SCOPE — analysis of what is
 * there, NOT indicative of capacity." — Vikram, 2026-09-01.
 *
 * So this answers exactly one question: WHAT IS MAPPED HERE. It counts
 * what the served payload contains around a point, by voltage class and
 * by distance band, and names the nearest few. It is a census of the map,
 * not a study of the network.
 *
 * WHAT IT WILL NOT DO, EVER
 * It does not say whether a connection is available, likely, cheap or
 * possible. Nothing in a payload of substation positions can support any
 * of that: capacity depends on queue position, committed connections,
 * thermal and fault headroom, consent and commercial terms, and none of
 * those is a distance. A scope that counted substations and implied
 * opportunity would be the most dangerous thing this estate could ship,
 * because it would look like analysis.
 *
 * Pure. No DOM, no network, no state. Depends on: geodesy.
 */
(() => {
  'use strict';

  const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  if (NS.gridScope) return;

  const geodesy = NS.geodesy;
  if (!geodesy) throw new Error('grid-scope requires the geodesy module');

  /* Bands, not a single radius. A reader asking "what is around here"
     wants the shape of the answer - is the nearest thing on top of me or
     twenty kilometres away - and one number hides that. */
  const DEFAULT_BANDS_KM = [2, 5, 10, 25];
  const CLASSES_KV = [400, 275, 220, 132, 66, 33];

  /* A voltage is classified ONLY as a class it actually is.
     ------------------------------------------------------------------
     The first version walked the classes and returned the first one the
     value exceeded, so it labelled 750 kV as 400, 110 kV as 66 and 50 kV
     as 33 - a false label on anything the list does not contain, which is
     exactly the sort of quiet relabelling this estate exists to avoid.
     Codex caught it on the committed module before it reached a card
     (stop-ship 202609012025).

     Now: membership, within a tolerance for the fractions OSM carries.
     Anything else is UNCLASSIFIED and counted as such, because a voltage
     the standard classes do not contain is a fact about the data, not a
     value to be rounded into the nearest familiar number. */
  const CLASS_TOLERANCE_KV = 0.5;

  function classOf(kv) {
    if (!Number.isFinite(kv)) return null;
    for (const known of CLASSES_KV) {
      if (Math.abs(kv - known) <= CLASS_TOLERANCE_KV) return known;
    }
    return null;
  }

  /**
   * @param origin [lon, lat]
   * @param substations  [{ at:[lon,lat], kv:[numbers], name, operator }]
   * @param options { bandsKm, minimumKv, nearestCount }
   */
  function scope(origin, substations, options) {
    const bandsKm = (options && options.bandsKm) || DEFAULT_BANDS_KM;
    const minimumKv = (options && options.minimumKv) || 0;
    const nearestCount = (options && options.nearestCount) || 5;
    const maximumKm = bandsKm[bandsKm.length - 1];

    const within = [];
    for (const substation of substations || []) {
      if (!substation || !Array.isArray(substation.at)) continue;
      const voltages = (Array.isArray(substation.kv) ? substation.kv : [])
        .filter(Number.isFinite);
      /* Non-finite voltages are dropped BEFORE the maximum.
         ----------------------------------------------------------------
         Codex, 202609012055: Math.max over a NaN gives NaN, and NaN < floor
         is false, so a substation whose voltage did not parse survived a
         132 kV floor and was censused as though it qualified. A voltage
         that is not a number is not a voltage above the floor. */
      const top = voltages.length ? Math.max(...voltages) : 0;
      if (top < minimumKv) continue;
      const km = geodesy.distanceKm(origin[0], origin[1],
        substation.at[0], substation.at[1]);
      if (km > maximumKm) continue;
      within.push({
        name: substation.name || '',
        operator: substation.operator || '',
        kv: top,
        class_kv: classOf(top),
        km,
        at: substation.at
      });
    }
    within.sort((a, b) => a.km - b.km);

    const bands = bandsKm.map((band) => {
      const inBand = within.filter(entry => entry.km <= band);
      const counts = {};
      let unclassified = 0;
      const unclassifiedKv = [];
      for (const entry of inBand) {
        if (entry.class_kv == null) {
          // Counted, never folded into a class it is not.
          unclassified += 1;
          if (Number.isFinite(entry.kv) && !unclassifiedKv.includes(entry.kv)) {
            unclassifiedKv.push(entry.kv);
          }
          continue;
        }
        counts[entry.class_kv] = (counts[entry.class_kv] || 0) + 1;
      }
      const highest = inBand.reduce(
        (best, entry) => (entry.class_kv != null && (best == null || entry.class_kv > best)
          ? entry.class_kv : best), null);
      return {
        within_km: band,
        substations: inBand.length,
        by_class_kv: counts,
        highest_class_kv: highest,
        unclassified_voltage: unclassified,
        unclassified_kv: unclassifiedKv.sort((a, b) => b - a)
      };
    });

    /* Named first, because an unnamed OSM node is a fact about the map
       rather than a place anyone can look up. Both are reported: the
       nearest thing, and the nearest thing with an identity. */
    const named = within.filter(entry => entry.name);
    return {
      schema: 'gridatlas.grid-scope.v1',
      origin: [origin[0], origin[1]],
      radius_km: maximumKm,
      minimum_kv: minimumKv,
      counted: within.length,
      bands,
      nearest: within.slice(0, nearestCount),
      nearest_named: named.slice(0, nearestCount),
      nearest_transmission: within.find(entry => entry.kv >= 275 - 0.5) || null,
      /* Carried in the result itself so it cannot be separated from the
         numbers by a renderer, a screenshot or a quote. */
      what_this_is: 'A census of the substations in the served map payload '
        + 'around this point, by voltage class and distance band.',
      what_this_is_not: 'Not a statement about capacity, headroom, '
        + 'availability or the cost of connecting here. Distance is not '
        + 'capacity: queue position, committed connections, thermal and '
        + 'fault headroom, consent and commercial terms decide that, and '
        + 'none of them is in this payload.',
      method: 'haversine on a single Earth radius of '