GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / tools/vicinity/src

UI Atlas V9 and 11 more files

A JavaScript module in GridAtlas that maps Renewable Energy Planning Database (REPD) clusters and REPD cluster count, and uses data from OpenStreetMap tiles. Served with the page at https://gridatlas.globalgrid2050.com/ui/site/.

676 lines of JavaScript and HTML from gridatlas, gridmachine1, legislation, in 12 files. Topic: Maps, GIS and field navigation. Section 698 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. Model geodesy · gridatlas / tools/vicinity/src/model.mjs lines 1–140
  2. UK Gazetteer Flyto other · gridatlas / ui/cartridges/202608301136-uk-gazetteer-flyto.mjs lines 1–10
  3. Global Gazetteer Flyto V9 5 other · gridatlas / ui/cartridges/202609011141-global-gazetteer-flyto-v9-5.mjs lines 1–16
  4. Global Gazetteer Flyto V9 106 other · gridatlas / ui/cartridges/202609040337-global-gazetteer-flyto-v9-106.mjs lines 1–17
  5. Streaming Parquet Bridge V9 5 other · gridatlas / ui/cartridges/202609241251-streaming-parquet-bridge-v9-5.mjs lines 1–12
  6. UI Atlas V9 render · gridatlas / ui/site/atlas-v9.mjs lines 1–183
  7. GridAtlas — UI Page render · gridatlas / ui/site/index.html lines 1–40
  8. GridAtlas Webkit Arrival Probe render · gridatlas / webkit-arrival-probe.mjs lines 1–48
  9. GridAtlas Webkit Register Probe energy-data · gridatlas / webkit-register-probe.mjs lines 1–35
  10. Geodesy Check geodesy · gridmachine1 / reports/20260907T180500Z-maths-and-linkage-study/geodesy-check.mjs lines 1–75
  11. GridAtlas Browser render · legislation / apps/gridatlas/browser.cjs lines 1–51
  12. GridAtlas Test test · legislation / apps/gridatlas/test.cjs lines 1–49

Model

A JavaScript module in the vicinity folder of GridAtlas that works with substations and the Renewable Energy Planning Database (REPD) register.

geodesygridatlas / tools/vicinity/src/model.mjs · lines 1–140 of 140 · pattern validateNewsContextBase (shared by 2 files)

What it does
It calculates substations and the REPD register. Defines 12 functions or classes, including validCoordinate, radiusKm, normaliseOrigin, parseVicinityIntent, numberText.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: substations, the REPD register, 400kV, 275kV, 132kV, 66kV. README: "`build.mjs` deterministically assembles `src/model.mjs`, `src/bootstrap.js` and `src/vicinity.css` into one bounded module."
Inputs & outputs
Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
Downstream impact
Used directly by 2 files: Browser Test (gridatlas); Model Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It normalises origin (`normaliseOrigin`), parses vicinity intent (`parseVicinityIntent`) and validates news context base (`validateNewsContextBase`). Spatial exploration only. Canonical Atlas geodesy is injected, never forked. Its code works with 11 kV, 132 kV and 275 kV.
Why it matters
Checked by 2 tests, including Browser Test.
Application
gridatlas · tools/vicinity/src · JavaScript module
Uses
none found
Used by
run by Browser Test (script call), imported by Model Test (import)
Produces
VOLTAGE_BANDS, validCoordinate, radiusKm, normaliseOrigin, parseVicinityIntent, validateNewsContextBase, normaliseNewsTopic, newsContextHref, voltageBands, stationRecords, exploreVicinity, vicinityGeoJSON
Defines here
validCoordinate, radiusKm, normaliseOrigin, parseVicinityIntent, numberText, validateNewsContextBase, normaliseNewsTopic, newsContextHref, voltageBands, stationRecords, exploreVicinity, vicinityGeoJSON
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/vicinity/src/model.mjs:1-140 · blob 4e6573e3798e4f6483ed546b29020da8992f194d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Spatial exploration only. Canonical Atlas geodesy is injected, never forked. */
export const VOLTAGE_BANDS = Object.freeze([
  ['400', '400 kV', '#ff5555'], ['275', '275 kV', '#ff8a3d'],
  ['132', '132 kV', '#ffd84d'], ['66', '66 kV', '#8be28b'],
  ['33', '33 kV', '#48d8df'], ['11', '11 kV', '#b8b8ed'],
  ['other', 'Other stated voltage', '#e6e6e6'], ['unknown', 'Voltage not stated', '#8b9ca0']
]);

export function validCoordinate(at) {
  return Array.isArray(at) && at.length >= 2 && at.slice(0, 2).every(v => typeof v === 'number' && Number.isFinite(v))
    && Math.abs(at[0]) <= 180 && Math.abs(at[1]) <= 90
    && !(Math.abs(at[0]) < 1e-9 && Math.abs(at[1]) < 1e-9);
}

export function radiusKm(value) {
  if (typeof value !== 'number' && typeof value !== 'string') throw new Error('Choose a whole-kilometre radius from 1 to 50 km.');
  if (typeof value === 'string' && !value.trim()) throw new Error('Choose a radius from 1 to 50 km.');
  const n = Number(value);
  if (!Number.isInteger(n) || n < 1 || n > 50) throw new Error('Choose a whole-kilometre radius from 1 to 50 km.');
  return n;
}

export function normaliseOrigin(origin, {requireIdentity = false} = {}) {
  if (!validCoordinate(origin?.at)) throw new Error('A valid located origin is required; no coordinates were inferred.');
  const type = String(origin.type || 'map-centre');
  const id = origin.id == null ? null : String(origin.id).trim();
  if (requireIdentity && (!['repd', 'datacentre', 'substation'].includes(type) || !id || id.length > 256 || /[\u0000-\u001f\u007f]/.test(id))) {
    throw new Error('Journey origin type and stable source ID are required.');
  }
  return {at: [origin.at[0], origin.at[1]], type, id, name: String(origin.name || (id ? `${type} ${id}` : 'Map centre')).slice(0, 240)};
}

export function parseVicinityIntent(search) {
  const q = new URLSearchParams(search);
  if (q.get('journey') !== 'vicinity') return null;
  if (q.getAll('journey').length !== 1 || q.getAll('radius_km').length > 1) throw new Error('Journey link has duplicate intent or radius fields.');
  const fields = ['origin_type', 'origin_id', 'latitude', 'longitude'];
  const hasOrigin = fields.some(k => q.has(k));
  let origin = null;
  if (hasOrigin) {
    if (fields.some(k => q.getAll(k).length !== 1) || !q.has('radius_km')) throw new Error('Journey link has missing or duplicate origin fields.');
    const latitude = q.get('latitude'), longitude = q.get('longitude');
    const numberText = value => typeof value === 'string' && /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(value.trim());
    if (!numberText(latitude) || !numberText(longitude)) throw new Error('Journey link has invalid coordinates.');
    origin = normaliseOrigin({at: [Number(longitude), Number(latitude)], type: q.get('origin_type'), id: q.get('origin_id'), name: q.get('name')}, {requireIdentity: true});
  }
  const intent = origin ? {origin, radiusKm: radiusKm(q.get('radius_km'))} : {manual: true, radiusKm: q.has('radius_km') ? radiusKm(q.get('radius_km')) : 10};
  if (q.has('news_context_url')) {
    try {
      if (q.getAll('news_context_url').length !== 1 || q.getAll('news_topic').length > 1) throw new Error('News context has duplicate fields.');
      intent.newsContextUrl = validateNewsContextBase(q.get('news_context_url'));
      intent.newsTopic = normaliseNewsTopic(q.get('news_topic'), origin);
    } catch (error) {
      delete intent.newsContextUrl; delete intent.newsTopic;
      intent.newsContextError = 'News context link was not applied: ' + error.message;
    }
  }
  return intent;
}

export function validateNewsContextBase(value) {
  if (typeof value !== 'string' || value.length > 200 || !/^https:\/\/globalgrid2050\.com\//.test(value)) throw new Error('News context must use a dated GlobalGrid2050 edition.');
  const url = new URL(value);
  if (url.origin !== 'https://globalgrid2050.com' || url.username || url.password || url.port || url.search || url.hash
    || !/^\/uk_renewables_pipeline\/\d{12}\/(?:index\.html)?$/.test(url.pathname)) throw new Error('News context must use a dated GlobalGrid2050 edition without extra URL fields.');
  return url.href;
}

export function normaliseNewsTopic(value, origin) {
  const allowed = ['datacentre','grid','renewables','storage','solar','wind'];
  if (value != null && value !== '') {
    if (!allowed.includes(value)) throw new Error('News topic is not supported.');
    return value;
  }
  return origin?.type === 'datacentre' ? 'datacentre' : origin?.type === 'substation' ? 'grid' : 'renewables';
}

export function newsContextHref(base, origin, topic) {
  const url = new URL(validateNewsContextBase(base));
  if (['repd','datacentre','substation'].includes(origin?.type) && origin?.id) {
    url.searchParams.set('news_origin_type', origin.type);
    url.searchParams.set('news_origin_id', String(origin.id).slice(0,256));
  }
  url.searchParams.set('news_topic', normaliseNewsTopic(topic, origin));
  url.hash = 'headlinesHeading';
  return url.href;
}

export function voltageBands(kv) {
  if (!kv.length) return ['unknown'];
  return [...new Set(kv.map(v => VOLTAGE_BANDS.some(b => b[0] === String(v)) ? String(v) : 'other'))];
}

export function stationRecords(features, geodesy) {
  const seen = new Set(), records = [];
  for (const feature of features || []) {
    const p = feature?.properties || {}, at = geodesy.representativePoint(feature?.geometry);
    if (!validCoordinate(at)) continue;
    const kv = Array.from(geodesy.voltagesKv(p)).filter(v => Number.isFinite(v) && v > 0);
    // This key deduplicates display rows only. It is never exported as source identity.
    const id = feature.id ?? p.id ?? null;
    const key = `${at[0]}|${at[1]}|${p.name || ''}`;
    if (seen.has(key)) continue;
    seen.add(key);
    records.push({id: id == null ? null : String(id), at: [at[0], at[1]], name: String(p.name || 'Unnamed mapped substation'),
      operator: String(p.operator || ''), kv, bands: voltageBands(kv), source: String(p.source || 'Existing Atlas substation layer')});
  }
  return records;
}

export function exploreVicinity({origin, radius, records, bands, geodesy, limit = 200}) {
  const o = normaliseOrigin(origin), r = radiusKm(radius), selected = new Set(bands);
  const ordered = [];
  for (const row of records) {
    if (!row.bands.some(b => selected.has(b))) continue;
    const km = geodesy.distanceKm(o.at[0], o.at[1], row.at[0], row.at[1]);
    if (!Number.isFinite(km) || km < 0 || km > r) continue;
    ordered.push({...row, km});
  }
  ordered.sort((a, b) => a.km - b.km || a.name.localeCompare(b.name, 'en') || String(a.id).localeCompare(String(b.id), 'en'));
  return {origin: o, radiusKm: r, matching: ordered.length, loadedRecords: records.length,
    shown: ordered.slice(0, limit), truncated: ordered.length > limit,
    statement: 'Spatial vicinity, connectivity unknown. Distances are straight-line; mapped voltage is a source tag, not capacity or an electrical path.'};
}

/** A radius boundary is spatial geometry, never a circuit or route. */
export function vicinityGeoJSON(result, geodesy) {
  const [lon, lat] = result.origin.at;
  const ring = [];
  for (let i = 0; i <= 96; i++) {
    ring.push(geodesy.destinationPoint(lon, lat, result.radiusKm, i * 360 / 96));
  }
  return {type: 'FeatureCollection', features: [
    {type: 'Feature', properties: {kind: 'radius', meaning: 'Spatial boundary; not a circuit'}, geometry: {type: 'LineString', coordinates: ring}},
    {type: 'Feature', properties: {kind: 'origin', name: result.origin.name}, geometry: {type: 'Point', coordinates: result.origin.at}},
    ...result.shown.map(row => ({type: 'Feature', properties: {kind: 'substation', name: row.name, km: row.km,
      voltage: row.kv.length ? row.kv.join(' / ') + ' kV' : 'Not stated', colour: VOLTAGE_BANDS.find(b => b[0] === row.bands[0])?.[2] || '#e6e6e6'},
      geometry: {type: 'Point', coordinates: row.at}}))
  ]};
}

UK Gazetteer Flyto

A JavaScript module in the cartridges folder of GridAtlas.

othergridatlas / ui/cartridges/202608301136-uk-gazetteer-flyto.mjs · lines 1–10 of 10 · version 2026-08-30 11:36 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · ui/cartridges · JavaScript module
Uses
none found
Used by
none found
Produces
ATLAS_V9_UK_GAZETTEER_FLYTO_CONTRACT
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 ui/cartridges/202608301136-uk-gazetteer-flyto.mjs:1-10 · blob 610439bd0a26b3d8e9c6b2b52734aa11770e95ea · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
export const ATLAS_V9_UK_GAZETTEER_FLYTO_CONTRACT = Object.freeze({
  schema: 'gridatlas.cartridge.v1',
  generation: '202608301136',
  activation: 'explicit-user-query-only',
  externalGeocoderRequests: 2,
  provider: 'postcodes.io',
  resultClass: 'LOCATION_ONLY',
  proximityEstablishesIdentity: false,
  setsDeepLink: false
});

Global Gazetteer Flyto V9 5

A JavaScript module in the cartridges folder of GridAtlas.

othergridatlas / ui/cartridges/202609011141-global-gazetteer-flyto-v9-5.mjs · lines 1–16 of 16 · version 2026-09-01 11:41 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · ui/cartridges · JavaScript module
Uses
none found
Used by
none found
Produces
ATLAS_V9_5_GLOBAL_GAZETTEER_FLYTO_CONTRACT
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 ui/cartridges/202609011141-global-gazetteer-flyto-v9-5.mjs:1-16 · blob eb39073811dda9430c217b57ccde6be7f6db58b7 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
export const ATLAS_V9_5_GLOBAL_GAZETTEER_FLYTO_CONTRACT = Object.freeze({
  schema: 'gridatlas.cartridge.v1',
  generation: '202609011141',
  version: 'v9.5',
  activation: 'explicit-user-query',
  providers: ['postcodes.io', 'Nominatim / OpenStreetMap'],
  repdResultsFirst: true,
  staleResponseGuard: true,
  resultClass: 'LOCATION_ONLY',
  proximityEstablishesIdentity: false,
  setsDeepLink: false,
  // Additive since 202609011141: a resolved deep link and a
  // selection publish the technology and capacity they resolved,
  // so the measurement cartridge needs no second resolver.
  publishesResolvedTechnologyAndCapacity: true
});

Global Gazetteer Flyto V9 106

A JavaScript module in the cartridges folder of GridAtlas.

othergridatlas / ui/cartridges/202609040337-global-gazetteer-flyto-v9-106.mjs · lines 1–17 of 17 · version 2026-09-04 03:37 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · ui/cartridges · JavaScript module
Uses
none found
Used by
none found
Produces
ATLAS_V9_106_GLOBAL_GAZETTEER_FLYTO_CONTRACT
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 ui/cartridges/202609040337-global-gazetteer-flyto-v9-106.mjs:1-17 · blob 62ecae3f41eda2905a534eef0264675c35d970c5 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
export const ATLAS_V9_106_GLOBAL_GAZETTEER_FLYTO_CONTRACT = Object.freeze({
  schema: 'gridatlas.cartridge.v1',
  generation: '202609040337',
  sourceGeneration: '202609040229',
  version: 'v9.106',
  activation: 'explicit-user-query-or-exact-repd-arrival',
  providers: ['postcodes.io', 'Nominatim / OpenStreetMap'],
  repdResultsFirst: true,
  staleResponseGuard: true,
  resultClass: 'LOCATION_ONLY',
  proximityEstablishesIdentity: false,
  setsDeepLink: false,
  publishesResolvedTechnologyAndCapacity: true,
  expectedActiveRegisterAbsenceIsNotFailure: true,
  suppliedArrivalFieldsRemainLinkProvenance: true,
  identityFailureRetryRequiresSharedArrivalEpoch: true
});

Streaming Parquet Bridge V9 5

A JavaScript module in the cartridges folder of GridAtlas.

othergridatlas / ui/cartridges/202609241251-streaming-parquet-bridge-v9-5.mjs · lines 1–12 of 12 · version 2026-09-24 12:51 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: 400kV.
Inputs & outputs
Voltage levels named: 400kV.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · ui/cartridges · JavaScript module
Uses
none found
Used by
none found
Produces
STREAMING_PARQUET_BRIDGE_V9_5_CONTRACT
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 ui/cartridges/202609241251-streaming-parquet-bridge-v9-5.mjs:1-12 · blob 7920120d7fc849778f6a335e5e51bcc1088b5886 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
export const STREAMING_PARQUET_BRIDGE_V9_5_CONTRACT = Object.freeze({
  schema: 'gridatlas.cartridge.v1',
  generation: '202608301825',
  version: 'v9.5',
  slot: '202608292311-maplibre-worker-bridge.js',
  responseEstablishedBeforeBodyReconstruction: true,
  payloadCacheReleasedAfterSerialisation: true,
  duckdbPrewarm: 'after-critical-400kv-source',
  metroPartitionAlias: 'uk_metros_trams_local_unwired',
  immutableShellModified: false,
  fullApplicationCopiesCreated: 0
});

UI Atlas V9

A JavaScript module in GridAtlas that maps Renewable Energy Planning Database (REPD) clusters and REPD cluster count, and uses data from OpenStreetMap tiles. Served with the page at https://gridatlas.globalgrid2050.com/ui/site/.

rendergridatlas / ui/site/atlas-v9.mjs · lines 1–183 of 183 · Not reached from any entry point (candidate for review) · pattern markMapUnavailable (shared by 2 files)

What it does
It maps REPD clusters, REPD cluster count, REPD points and REPD selected. Defines 7 functions or classes, including popupNode, setSelectedUrl, select, markMapUnavailable, addProjectLayers. Side effects: changes the web page (DOM); makes network requests.
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.
Inputs & outputs
In: data source: OpenStreetMap tiles. Out: interactive map.
What it achieves
It sets selected URL (`setSelectedUrl`), marks map unavailable (`markMapUnavailable`) and adds project layers (`addProjectLayers`). Defines `popupNode`, `setSelectedUrl`, `select` and 4 more.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · ui/site · JavaScript module
Uses
Renewable Energy Planning Database (REPD) Address Flyto (import)
Used by
none found
Produces
popupNode, setSelectedUrl, select, markMapUnavailable, addProjectLayers, initialiseMap, boot
Defines here
popupNode, setSelectedUrl, select, markMapUnavailable, addProjectLayers, initialiseMap, boot
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 ui/site/atlas-v9.mjs:1-183 · blob 1b46be5b3805bb2dcd9db090e01a3c8b04d04180 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import { mountRepdAddressFlyTo } from "../cartridges/202608290716-repd-address-flyto.mjs";

const GENERATION = "202608290716";
const status = document.querySelector("[data-registry-status]");
const live = document.querySelector("[data-atlas-live]");
const mapStatus = document.querySelector("[data-map-status]");
let map = null;
let mapReady = false;
let featureByRef = new Map();

function popupNode(record) {
  const node = document.createElement("div");
  for (const value of [
    record.name,
    record.repd_address_display || "Address not supplied by REPD",
    [record.repd_postcode, record.county].filter(Boolean).join(" · "),
    `${record.capacity_mw} MW · ${record.status}`,
    `REPD operator or applicant: ${record.repd_operator_or_applicant || "Not supplied / withheld"}`,
    `REPD ${record.repd_ref}`
  ]) {
    const line = document.createElement("div");
    line.textContent = value;
    node.append(line);
  }
  return node;
}

function setSelectedUrl(record) {
  const url = new URL(location.href);
  url.searchParams.set("repd_ref", record.repd_ref);
  history.replaceState(null, "", url);
}

function select(record) {
  setSelectedUrl(record);
  if (!mapReady || !map) {
    live.textContent = `REPD ${record.repd_ref} selected · map unavailable; official search remains active`;
    return;
  }
  map.getSource("repd-selected").setData({
    type: "Feature",
    properties: {},
    geometry: { type: "Point", coordinates: [record.longitude, record.latitude] }
  });
  new globalThis.maplibregl.Popup({ offset: 12 })
    .setLngLat([record.longitude, record.latitude])
    .setDOMContent(popupNode(record))
    .addTo(map);
}

const mapAdapter = {
  flyTo(options) {
    if (!mapReady || !map) {
      live.textContent = "Map unavailable in this browser; the official REPD match remains selected.";
      return;
    }
    map.flyTo(options);
  }
};

function markMapUnavailable(error) {
  mapReady = false;
  mapStatus.dataset.mapState = "unavailable";
  mapStatus.textContent = "MAP UNAVAILABLE IN THIS BROWSER · OFFICIAL REPD ADDRESS SEARCH REMAINS ACTIVE";
  console.warn("Atlas V9 map isolated:", error instanceof Error ? error.message : String(error));
}

function addProjectLayers(records) {
  const geojson = {
    type: "FeatureCollection",
    features: records.map(record => ({
      type: "Feature",
      id: Number(record.repd_ref) || undefined,
      properties: { repd_ref: String(record.repd_ref), technology: record.technology, status: record.status },
      geometry: { type: "Point", coordinates: [record.longitude, record.latitude] }
    }))
  };
  map.addSource("repd-v9", { type: "geojson", data: geojson, cluster: true, clusterMaxZoom: 9, clusterRadius: 45 });
  map.addLayer({
    id: "repd-clusters", type: "circle", source: "repd-v9", filter: ["has", "point_count"],
    paint: {
      "circle-color": ["step", ["get", "point_count"], "#00b7c7", 100, "#ffae00", 500, "#ff5b5b"],
      "circle-radius": ["step", ["get", "point_count"], 16, 100, 22, 500, 28],
      "circle-stroke-width": 2, "circle-stroke-color": "#001014"
    }
  });
  map.addLayer({
    id: "repd-cluster-count", type: "symbol", source: "repd-v9", filter: ["has", "point_count"],
    layout: { "text-field": ["get", "point_count_abbreviated"], "text-size": 11 },
    paint: { "text-color": "#001014" }
  });
  map.addLayer({
    id: "repd-points", type: "circle", source: "repd-v9", filter: ["!", ["has", "point_count"]],
    paint: {
      "circle-color": ["match", ["get", "technology"], "solar", "#ffe600", "bess", "#ff7ab6", "wind_onshore", "#00e5ff", "wind_offshore", "#0068ff", "#8dff7a"],
      "circle-radius": 5, "circle-stroke-width": 1.5, "circle-stroke-color": "#001014"
    }
  });
  map.addSource("repd-selected", { type: "geojson", data: { type: "FeatureCollection", features: [] } });
  map.addLayer({
    id: "repd-selected", type: "circle", source: "repd-selected",
    paint: { "circle-color": "#00ffff", "circle-radius": 11, "circle-stroke-width": 4, "circle-stroke-color": "#000" }
  });
  map.on("click", "repd-clusters", event => {
    const feature = event.features[0];
    map.getSource("repd-v9").getClusterExpansionZoom(feature.properties.cluster_id, (error, zoom) => {
      if (!error) map.easeTo({ center: feature.geometry.coordinates, zoom });
    });
  });
  map.on("click", "repd-points", event => {
    const record = featureByRef.get(String(event.features[0].properties.repd_ref));
    if (record) select(record);
  });
}

function initialiseMap(records) {
  if (!globalThis.maplibregl?.Map) throw new Error("MapLibre did not load");
  map = new globalThis.maplibregl.Map({
    container: "map",
    center: [-3.5, 54.2],
    zoom: 4.4,
    style: {
      version: 8,
      sources: {
        osm: {
          type: "raster",
          tiles: ["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],
          tileSize: 256,
          attribution: "© OpenStreetMap contributors"
        }
      },
      layers: [{ id: "osm", type: "raster", source: "osm" }]
    }
  });
  map.addControl(new globalThis.maplibregl.NavigationControl(), "top-right");
  map.on("load", () => {
    try {
      addProjectLayers(records);
      mapReady = true;
      mapStatus.dataset.mapState = "ready";
      mapStatus.textContent = "REPD viable projects · clusters expand on click · selected project in cyan";
      const requested = new URLSearchParams(location.search).get("repd_ref");
      if (requested && featureByRef.has(requested)) {
        const record = featureByRef.get(requested);
        map.jumpTo({ center: [record.longitude, record.latitude], zoom: 13 });
        select(record);
      }
    } catch (error) {
      markMapUnavailable(error);
    }
  });
}

async function boot() {
  const response = await fetch(`data/repd_browser_registry_${GENERATION}.json`, { cache: "no-store" });
  if (!response.ok) throw new Error(`registry HTTP ${response.status}`);
  const registry = await response.json();
  if (registry.schema !== "gridatlas.browser-registry.v1" || registry.generation !== GENERATION || !Array.isArray(registry.records)) {
    throw new Error("registry contract mismatch");
  }
  const records = registry.records;
  featureByRef = new Map(records.map(record => [String(record.repd_ref), record]));
  status.textContent = `${records.length.toLocaleString()} official viable REPD projects ready`;
  mountRepdAddressFlyTo({
    map: mapAdapter,
    records,
    root: document.querySelector("[data-atlas-search-root]"),
    onSelected: select
  });
  try {
    initialiseMap(records);
  } catch (error) {
    markMapUnavailable(error);
    const requested = new URLSearchParams(location.search).get("repd_ref");
    if (requested && featureByRef.has(requested)) select(featureByRef.get(requested));
  }
}

boot().catch(error => {
  console.error(error);
  status.textContent = "REPD registry failed closed — no project claim has been made";
  markMapUnavailable(error);
});

GridAtlas — UI Page

A web page that reads inputs for atlas query, covering the Renewable Energy Planning Database (REPD) register and postcodes. Published at https://gridatlas.globalgrid2050.com/ui/site/.

rendergridatlas / ui/site/index.html · lines 1–40 of 40 · Entry point

What it does
It draws the REPD register and postcodes. Uses libraries assets/atlas-v9.css, assets/atlas-v9.mjs. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: the REPD register, postcodes.
Inputs & outputs
In: JSON file repd_v9_manifest_202608290716.json; DuckDB queries; form fields (user input). Out: web page.
Downstream impact
It is itself an entry point, published at https://gridatlas.globalgrid2050.com/ui/site/.
What it achieves
Grid Atlas V9 — official REPD address and postcode search with deterministic project fly-to.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · ui/site · page
Uses
https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.css, assets/atlas-v9.css, https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js, assets/atlas-v9.mjs
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 ui/site/index.html:1-40 · blob 9998589a3d03d19bd6db11b5e1cad787f6e5b7fe · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <meta name="description" content="Grid Atlas V9 — official REPD address and postcode search with deterministic project fly-to.">
  <title>Grid Atlas V9 · REPD Address Search</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.css">
  <link rel="stylesheet" href="assets/atlas-v9.css">
</head>
<body>
  <header class="topbar">
    <div><strong>GRID ATLAS V9</strong><span>OFFICIAL REPD LOCATION INTELLIGENCE</span></div>
    <a href="data/repd_v9_manifest_202608290716.json">BUILD PROOF</a>
  </header>
  <main>
    <section class="search-panel" data-atlas-search-root>
      <div class="version-line">LIVE CANDIDATE · 202608290716 · V8 PRESERVED</div>
      <h1>Find a UK energy project by place</h1>
      <p class="intro">Search the Official REPD address, project name, postcode, county, planning authority or REPD reference. Fly-to uses the published project coordinates.</p>
      <label for="atlas-query">Project, address, postcode or county</label>
      <div class="search-row">
        <input id="atlas-query" data-atlas-query autocomplete="off" placeholder="e.g. solar being built Cranfield/Marston Bedfordshire" aria-describedby="search-help">
        <button type="button" data-atlas-search>SEARCH REPD</button>
      </div>
      <p id="search-help" class="help">Slash means OR: <code>cranfield/marston bedfordshire</code>. No query is sent to an external geocoder.</p>
      <div class="status-row"><span data-registry-status>Loading authenticated REPD registry…</span><span data-atlas-live aria-live="polite"></span></div>
      <div class="results" data-atlas-results></div>
      <aside class="truth-note">“Operator or applicant” is the REPD role label—not proof of current ownership. A location or nearby project never establishes involvement.</aside>
    </section>
    <section class="map-panel" aria-label="Grid Atlas V9 map">
      <div id="map"></div>
      <div class="map-legend" data-map-status data-map-state="initialising" aria-live="polite">MAP INITIALISING · OFFICIAL REPD ADDRESS SEARCH LOADS INDEPENDENTLY</div>
    </section>
  </main>
  <footer>DESNZ REPD Q2 2026 · ZSTD Parquet · DuckDB 1.3.2 typed readback · V8 immutable oracle</footer>
  <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js"></script>
  <script type="module" src="assets/atlas-v9.mjs"></script>
</body>
</html>

GridAtlas Webkit Arrival Probe

A JavaScript module covering solar. Served with the page at https://gridatlas.globalgrid2050.com/.

rendergridatlas / webkit-arrival-probe.mjs · lines 1–48 of 48 · Not reached from any entry point (candidate for review)

What it does
Defines run. Uses libraries playwright. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: solar.
What it achieves
Defines `run`.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · / · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL), playwright
Used by
none found
Produces
run
Defines here
run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 webkit-arrival-probe.mjs:1-48 · blob f21ca9f99722cd852830634a86ffe240d4614dc3 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import { webkit, chromium } from 'playwright';

const URL = 'https://ventusltd.github.io/gridatlas/atlas/?repd_ref=20388&project=Berden+Hall+Solar+Farm&technology=solar&capacity_mw=56&latitude=51.9369457&longitude=0.1309736&zoom=12';

async function run(engine, name) {
  const browser = await engine.launch();
  const ctx = await browser.newContext({
    viewport: { width: 393, height: 852 },
    deviceScaleFactor: 3,
    isMobile: name === 'webkit',
    hasTouch: name === 'webkit',
  });
  const page = await ctx.newPage();
  const errors = [], logs = [], failed = [];
  page.on('pageerror', e => errors.push(String(e && e.stack || e).slice(0, 400)));
  page.on('console', m => { if (/error|fail|warn/i.test(m.type() + m.text())) logs.push(m.type() + ': ' + m.text().slice(0, 220)); });
  page.on('requestfailed', r => failed.push(r.url().slice(0, 120) + ' :: ' + (r.failure()?.errorText || '')));

  await page.goto(URL, { waitUntil: 'load', timeout: 60000 }).catch(e => errors.push('goto: ' + e.message));
  await page.waitForTimeout(20000);

  const state = await page.evaluate(() => {
    const L = window.__GRIDATLAS_NEON_LINKS__;
    const m = window.__GRIDATLAS_V9_MAP__;
    const ans = [...document.querySelectorAll('body *')]
      .find(e => e.children.length < 6 && /Nearest .* substation/.test(e.innerText || ''));
    return {
      mapGlobal: !!m,
      centre: m ? [+m.getCenter().lng.toFixed(3), +m.getCenter().lat.toFixed(3)] : null,
      zoom: m ? +m.getZoom().toFixed(2) : null,
      styleLayers: m ? m.getStyle().layers.length : null,
      neon: L ? { drawn: L.links_drawn, fail: L.failures, proj: L.project_layer_enabled } : null,
      card: !!ans,
      checkboxes: document.querySelectorAll('#scada-ui-container input[type=checkbox]').length,
      bodyStart: document.body.innerText.replace(/\s+/g, ' ').slice(0, 160),
    };
  }).catch(e => ({ evalError: e.message }));

  await browser.close();
  return { engine: name, state, pageErrors: errors.slice(0, 6), consoleErrors: logs.slice(0, 10), requestFailures: failed.slice(0, 8) };
}

const wk = await run(webkit, 'webkit');
console.log('================ WEBKIT (iOS Safari engine) ================');
console.log(JSON.stringify(wk, null, 1));
const ch = await run(chromium, 'chromium');
console.log('================ CHROMIUM (control) ================');
console.log(JSON.stringify(ch, null, 1));

GridAtlas Webkit Register Probe

A JavaScript module covering solar. Served with the page at https://gridatlas.globalgrid2050.com/.

energy-datagridatlas / webkit-register-probe.mjs · lines 1–35 of 35 · Not reached from any entry point (candidate for review)

What it does
Uses libraries playwright. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: solar.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · / · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL), playwright
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 webkit-register-probe.mjs:1-35 · blob e24f3e66250421a148f71e06094cd1e4acc0c2a8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import { webkit } from 'playwright';
const B='https://ventusltd.github.io/gridatlas/atlas/?';
const CASES=[
 ['12588','Botley West','solar','51.8132088','-1.3489728','WORKS on his phone'],
 ['14293','Houston Solar','solar','55.8676363','-4.5501937','FAILED on his phone'],
 ['20388','Berden Hall Solar Farm','solar','51.9369457','0.1309736','FAILED'],
 ['15530','Braston New Energy','bess','55.4430887','-4.5945148','FAILED'],
 ['6564','Birkhall Estate','hydro','57.00447','-3.08141','FAILED'],
 ['15543','Cruachan Upgrade Project','hydro','56.3959','-5.11752','FAILED'],
];
const br=await webkit.launch();
for(const [ref,name,tech,lat,lon,label] of CASES){
  const ctx=await br.newContext({viewport:{width:393,height:852},deviceScaleFactor:3,isMobile:true,hasTouch:true});
  const p=await ctx.newPage();
  const errs=[],deep=[];
  p.on('pageerror',e=>errs.push(String(e).slice(0,200)));
  p.on('console',m=>{const t=m.text(); if(/DEEP LINK|register|absent|retry|identity/i.test(t)) deep.push(t.slice(0,160));});
  const u=`${B}repd_ref=${ref}&project=${encodeURIComponent(name)}&technology=${tech}&capacity_mw=1&latitude=${lat}&longitude=${lon}&zoom=12`;
  await p.goto(u,{waitUntil:'load',timeout:60000}).catch(e=>errs.push('goto '+e.message));
  await p.waitForTimeout(14000);
  const s=await p.evaluate(()=>{
    const L=window.__GRIDATLAS_NEON_LINKS__, P=window.__GRIDATLAS_PLACE_SEARCH__||window.placeSearch;
    const m=window.__GRIDATLAS_V9_MAP__;
    const ans=[...document.querySelectorAll('body *')].find(e=>e.children.length<6&&/Nearest .* substation/.test(e.innerText||''));
    const dl=(P&&P.deep_link)||null;
    return {card:!!ans,drawn:L?L.links_drawn:null,fail:L?L.failures:null,
      centre:m?[+m.getCenter().lng.toFixed(3),+m.getCenter().lat.toFixed(3)]:null,zoom:m?+m.getZoom().toFixed(1):null,
      dlStatus:dl?dl.status:null,identity:dl?dl.identity_source:null,
      notInRegister:/not in the active-register snapshot/i.test(document.body.innerText)};
  }).catch(e=>({evalError:e.message}));
  console.log(`${ref.padEnd(6)} ${label.padEnd(20)} card=${s.card} drawn=${s.drawn} zoom=${s.zoom} centre=${JSON.stringify(s.centre)} dl=${s.dlStatus} identity=${s.identity} notInRegister=${s.notInRegister} errs=${errs.length}`);
  if(errs.length) console.log('        ERR:',errs[0]);
  await ctx.close();
}
await br.close();

Geodesy Check

A JavaScript module in the reports folder of Gridmachine1 that reads interconnector endpoints, using Vincenty and haversine.

geodesygridmachine1 / reports/20260907T180500Z-maths-and-linkage-study/geodesy-check.mjs · lines 1–75 of 75 · version 2026-09-07 18:05 · Not reached from any entry point (candidate for review) · pattern haversine (shared by 24 files)

What it does
It loads interconnector endpoints. Defines rad, haversine, vincenty, radii, pick. Uses libraries node:fs. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
Inputs & outputs
In: JSON file interconnector-endpoints.json. Coordinate systems named: WGS84 / EPSG:4326.
What it achieves
It is built from the rad step (`rad`), the haversine step (`haversine`) and the vincenty step (`vincenty`). Measure the radius question instead of arguing it.
Why it matters
No other file in the estate was found to import it.
Application
gridmachine1 · reports/20260907T180500Z-maths-and-linkage-study · JavaScript module
Uses
node:fs
Used by
none found
Produces
rad, haversine, vincenty, radii, pick
Defines here
rad, haversine, vincenty, radii, pick
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridmachine1@16cd3db49d03e6faa0e4e24f06f08184422049be reports/20260907T180500Z-maths-and-linkage-study/geodesy-check.mjs:1-75 · blob 6ae7dda7d1ffc5bc565f68f5f36f90a1c015973b · GitHub at these lines
State
achieves: comment · context: auto · stage: ingest · effects: filesystem · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unreached_review
// Measure the radius question instead of arguing it.
// Vincenty inverse on WGS84 is the reference; haversine on each radius is compared to it.
import fs from "node:fs";
const F = "C:/Users/vikra/testcode-clone/sandbox/pairs/20260907T190239Z-W/atlas/data/interconnector-endpoints.json";
const raw = JSON.parse(fs.readFileSync(F, "utf8"));
const rad = (d) => (d * Math.PI) / 180;

function haversine(a, b, R) {
  const dLat = rad(b.lat - a.lat), dLon = rad(b.lon - a.lon);
  const s = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
  return 2 * R * Math.asin(Math.min(1, Math.sqrt(s)));
}
// Vincenty inverse, WGS84
function vincenty(p1, p2) {
  const a = 6378137, f = 1 / 298.257223563, b = (1 - f) * a;
  const L = rad(p2.lon - p1.lon);
  const U1 = Math.atan((1 - f) * Math.tan(rad(p1.lat))), U2 = Math.atan((1 - f) * Math.tan(rad(p2.lat)));
  const sU1 = Math.sin(U1), cU1 = Math.cos(U1), sU2 = Math.sin(U2), cU2 = Math.cos(U2);
  let lam = L, lamP, i = 0, sinSig, cosSig, sig, sinAlpha, cos2Alpha, cos2SigM, C;
  do {
    const sinLam = Math.sin(lam), cosLam = Math.cos(lam);
    sinSig = Math.sqrt((cU2 * sinLam) ** 2 + (cU1 * sU2 - sU1 * cU2 * cosLam) ** 2);
    if (sinSig === 0) return 0;
    cosSig = sU1 * sU2 + cU1 * cU2 * cosLam;
    sig = Math.atan2(sinSig, cosSig);
    sinAlpha = (cU1 * cU2 * sinLam) / sinSig;
    cos2Alpha = 1 - sinAlpha ** 2;
    cos2SigM = cos2Alpha !== 0 ? cosSig - (2 * sU1 * sU2) / cos2Alpha : 0;
    C = (f / 16) * cos2Alpha * (4 + f * (4 - 3 * cos2Alpha));
    lamP = lam;
    lam = L + (1 - C) * f * sinAlpha * (sig + C * sinSig * (cos2SigM + C * cosSig * (-1 + 2 * cos2SigM ** 2)));
  } while (Math.abs(lam - lamP) > 1e-12 && ++i < 200);
  const u2 = (cos2Alpha * (a * a - b * b)) / (b * b);
  const A = 1 + (u2 / 16384) * (4096 + u2 * (-768 + u2 * (320 - 175 * u2)));
  const B = (u2 / 1024) * (256 + u2 * (-128 + u2 * (74 - 47 * u2)));
  const dSig = B * sinSig * (cos2SigM + (B / 4) * (cosSig * (-1 + 2 * cos2SigM ** 2) - (B / 6) * cos2SigM * (-3 + 4 * sinSig ** 2) * (-3 + 4 * cos2SigM ** 2)));
  return (b * A * (sig - dSig)) / 1000;
}
// local radii of curvature
function radii(latDeg) {
  const a = 6378.137, f = 1 / 298.257223563, e2 = f * (2 - f), s = Math.sin(rad(latDeg));
  const W = Math.sqrt(1 - e2 * s * s);
  const N = a / W, M = (a * (1 - e2)) / W ** 3;
  return { N, M, gauss: Math.sqrt(M * N) };
}

const R_EQ = 6378.137, R_MEAN = 6371.0088;
console.log("Local radii of curvature (km)");
for (const lat of [51.5, 53.5, 55, 58]) {
  const r = radii(lat);
  console.log(`  ${lat}N  meridian M ${r.M.toFixed(1)}  prime vertical N ${r.N.toFixed(1)}  Gaussian sqrt(MN) ${r.gauss.toFixed(1)}`);
}

// find the two links in the data
const text = JSON.stringify(raw);
const links = raw.endpoints || [];
const pick = (re) => (Array.isArray(links) ? links : Object.values(links)).find((l) => re.test(JSON.stringify(l)));
const cases = [];
for (const [name, re] of [["BritNed", /INTNED|BritNed/i], ["ElecLink", /INTELE|ElecLink/i]]) {
  const l = pick(re);
  if (!l) { console.log(`\n${name}: not found in the endpoint file`); continue; }
  const gl = l.gb_lat, gn = l.gb_lon, fl = l.far_lat, fn = l.far_lon;
  if (![gl, gn, fl, fn].every(Number.isFinite)) { console.log(`\n${name}: endpoints incomplete`, JSON.stringify(l).slice(0, 160)); continue; }
  cases.push({ name, a: { lat: gl, lon: gn }, b: { lat: fl, lon: fn } });
}
console.log("\nSpan, measured three ways (km)");
for (const c of cases) {
  const v = vincenty(c.a, c.b), hm = haversine(c.a, c.b, R_MEAN), he = haversine(c.a, c.b, R_EQ);
  const midLat = (c.a.lat + c.b.lat) / 2;
  const best = (v / (haversine(c.a, c.b, 1))) ;   // the sphere radius that would reproduce the geodesic
  console.log(`  ${c.name}: ellipsoid (Vincenty) ${v.toFixed(3)}`);
  console.log(`     haversine R=6371.0088 ${hm.toFixed(3)}  error ${((hm - v) * 1000).toFixed(0)} m`);
  console.log(`     haversine R=6378.137  ${he.toFixed(3)}  error ${((he - v) * 1000).toFixed(0)} m`);
  console.log(`     radius that reproduces the geodesic: ${best.toFixed(1)} km   (Gaussian at ${midLat.toFixed(1)}N: ${radii(midLat).gauss.toFixed(1)})`);
}

GridAtlas Browser

A JavaScript module in Legislation that draws adapter pin, exercise, catalogue and regulatory references, using SHA-256.

renderlegislation / apps/gridatlas/browser.cjs · lines 1–51 of 51 · Not reached from any entry point (candidate for review)

What it does
It draws adapter pin, exercise, catalogue and regulatory references. Uses libraries playwright, node:assert/strict, node:fs, node:path, node:crypto. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'gridatlas'): 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.
Inputs & outputs
In: JSON file adapter-pin.json; JSON file exercise.json; JSON file catalogue.json; JSON file regulatory-references.json; JSON file ia6.json.
What it achieves
It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
legislation · apps/gridatlas · JavaScript module
Uses
playwright, node:assert/strict, node:fs, node:path, node:crypto, ./adapter-pin.json, ./exercise.json
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 apps/gridatlas/browser.cjs:1-51 · blob 65d72e750f970c60a20bb9f15663f4c3c8130c7f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
const {chromium}=require('playwright'),assert=require('node:assert/strict');
const fs=require('node:fs'),path=require('node:path'),{createHash}=require('node:crypto');
const pin=require('./adapter-pin.json'), fixture=require('./exercise.json');
const adapter=process.env.GRIDATLAS_LEGAL_ADAPTER, focus=process.env.GRIDATLAS_VICINITY_FOCUS;
const root=path.resolve(__dirname,'../..');
for (const [file,digest] of [[adapter,pin.sha256],[focus,pin.focus_sha256]]) {
  assert.equal(createHash('sha256').update(fs.readFileSync(file)).digest('hex'),digest);
}
(async()=>{
 const browser=await chromium.launch({executablePath:process.env.CHROMIUM_EXECUTABLE_PATH,args:['--no-sandbox']});
 try{
  const page=await browser.newPage({viewport:{width:393,height:852},isMobile:true,hasTouch:true});
  const errors=[];page.on('pageerror',e=>errors.push(e.message));
  const f=fixture;
  await page.context().route('**/*',route=>{
    const u=new URL(route.request().url());
    if (u.origin!=='https://ventusltd.github.io') return route.abort();
    if (u.pathname==='/gridatlas/atlas/') return route.fulfill({body:'<!DOCTYPE html><html><head></head><body></body></html>',contentType:'text/html'});
    const relative=u.pathname.slice('/legislation/'.length);
    const allowed={'legal-evidence/':'legal-evidence/index.html','legal-evidence/reader.js':'legal-evidence/reader.js','legal-evidence/reader.css':'legal-evidence/reader.css','data/catalogue.json':'data/catalogue.json','data/regulatory-references.json':'data/regulatory-references.json','case/ia6.json':'case/ia6.json'};
    if (!u.pathname.startsWith('/legislation/') || !Object.hasOwn(allowed,relative)) return route.abort();
    return route.fulfill({path:path.join(root,allowed[relative])});
  });
  await page.goto(f.gridatlas_arrival);
  await page.evaluate(ref=>{
    const d=document,e=(parent,tag)=>parent.appendChild(d.createElement(tag)),card=e(d.body,'section');
    const head=e(card,'div'),nav=e(head,'div'),prev=e(nav,'button'),label=e(nav,'span'),next=e(nav,'button');
    prev.textContent='Previous';next.textContent='Next';
    const tl=e(head,'div'),pn=e(head,'div'),csv=e(head,'div'),details=e(head,'details');
    Object.assign(card,{project:true,r:{n:'Training Meadow',p:{repd_ref:ref,technology:'Solar PV + battery',capacity_mw:48}},head,tl,pn,csv,d:details,swipe:{prev,label,next,index:0,entries:[{tab:'s',name:'Synthetic neighbour',km:2.1}]},k:[{name:'Synthetic neighbour',kv:33}]});
    next.addEventListener('click',()=>{label.textContent='1 of 1';});
    window.__GRIDATLAS_MODULES__={ukOfftakers:{state:{pp:card}}};
  },f.test_only_ref);
  await page.addScriptTag({path:focus});
  await page.addScriptTag({path:adapter});
  const anchor=page.getByRole('link',{name:'Legal evidence'});await anchor.waitFor();
  assert.deepEqual(Object.fromEntries(new URL(await anchor.getAttribute('href')).searchParams),f.expected_context);
  const [reader] = await Promise.all([page.context().waitForEvent('page'),anchor.click()]);
  await reader.locator('#context').getByText(f.test_only_ref,{exact:true}).waitFor();
  for(const text of ['solar photovoltaic development','battery energy storage']) {
    await reader.getByRole('button',{name:text,exact:true}).click();
    await reader.locator('#results article').first().waitFor();
  }
  assert.equal(await reader.locator('#context').getByText('Unknown',{exact:true}).count(),1);
  await page.getByRole('button',{name:'Next'}).click();
  await anchor.waitFor({state:'detached',timeout:5000});
  assert.equal(await page.locator('[data-vicinity-focus-title]').innerText(),'Synthetic neighbour');
  assert.deepEqual(errors,[]);
  console.log('PASS Chromium mobile-sized fixture, actual GridAtlas focus cartridge + candidate. Opened the local reader, checked exact identity and both technology filters; neighbour removes link. No JS errors.');
 }finally{await browser.close()}
})().catch(e=>{console.error(e);process.exitCode=1});

GridAtlas Test

A JavaScript module in Legislation that tests adapter pin, exercise, the Renewable Energy Planning Database (REPD) register and substations, using SHA-256.

testlegislation / apps/gridatlas/test.cjs · lines 1–49 of 49 · Not reached from any entry point (candidate for review)

What it does
It tests adapter pin, exercise, the REPD register and substations. Uses libraries node:test, node:assert/strict, node:fs, node:vm, node:crypto. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'gridatlas'): 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: the REPD register, substations.
Inputs & outputs
In: JSON file adapter-pin.json; JSON file exercise.json.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
legislation · apps/gridatlas · JavaScript module
Uses
Legislation — Legal Evidence Page (estate URL), node:test, node:assert/strict, node:fs, node:vm, node:crypto, ./adapter-pin.json, ./exercise.json
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 apps/gridatlas/test.cjs:1-49 · blob 4a18754f341ea8654fa9318ee9f1c7b92755627c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
const {test} = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const {createHash} = require('node:crypto');
const pin = require('./adapter-pin.json');
const path = process.env.GRIDATLAS_LEGAL_ADAPTER;
if (!path) throw Error('Set GRIDATLAS_LEGAL_ADAPTER to the GridAtlas module named in adapter-pin.json');
const code = fs.readFileSync(path);
assert.equal(createHash('sha256').update(code).digest('hex'),pin.sha256);
const script = {module:{exports:{}},URL};
vm.runInNewContext(code.toString('utf8'),script);
const {evidenceUrl,render} = script.module.exports;
const fixture = require('./exercise.json');
const arrival = fixture.gridatlas_arrival;
const ref = fixture.test_only_ref;

test('synthetic Solar/BESS arrival keeps identity and drops map coordinates and unsupported legal assertions', () => {
  const url = new URL(evidenceUrl(arrival,ref));
  assert.equal(url.origin + url.pathname,'https://ventusltd.github.io/legislation/legal-evidence/');
  assert.deepEqual(Object.fromEntries(url.searchParams),fixture.expected_context);
});
test('immutable release label follows the inspected path and is absent on the moving current route', () => {
  const versioned = arrival.replace('/atlas/?','/atlas/v/202611222343/?');
  assert.equal(new URL(evidenceUrl(versioned,ref)).searchParams.get('source_release'),'202611222343');
  assert.equal(new URL(evidenceUrl(arrival+'&source_release=000000000000',ref)).searchParams.has('source_release'),false);
});
test('duplicate refs, neighbouring assets, false coordinates and non-REPD arrivals refuse', () => {
  assert.equal(evidenceUrl(arrival,'1'),null);
  for (const [key,value] of [['repd_ref','1'],['latitude','3'],['origin_type','substation']]) {
    const u = new URL(arrival); u.searchParams.append(key,value);
    assert.equal(evidenceUrl(u.href,ref),null);
  }
  for (const [key,value] of [['latitude','NaN'],['longitude','-99'],['origin_type','substation'],['origin_id','repd:1']]) {
    const u = new URL(arrival); u.searchParams.set(key,value);
    assert.equal(evidenceUrl(u.href,ref),null);
  }
  assert.equal(evidenceUrl(arrival.replace('ventusltd.github.io','example.org'),ref),null);
});
test('Vicinity adds once on the origin and drops the link when the user swipes', () => {
  let link;
  const box = {querySelector:()=>link,ownerDocument:{createElement:()=>({dataset:{},remove(){link=null;}})},
               appendChild:l=>{assert.ok(!link);link=l;}};
  const card = {isConnected:true,project:true,r:{p:{repd_ref:ref}},__vicFocus:{box,origin:true}};
  render(card,arrival);render(card,arrival);
  assert.equal(link.textContent,'Legal evidence');
  card.__vicFocus.origin=false;
  render(card,arrival);assert.equal(link,null);
});