GLOBALGRID2050 / EXPLORE CODE

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

Grid Vicinity and 1 more file

A JavaScript file in the atlas folder of GridAtlas that maps notice, grid substations, the Renewable Energy Planning Database (REPD) register and transformers, using SHA-256.

700 lines of JavaScript from gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 533 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. Grid Journey Preview render · gridatlas / atlas/modules/202611172355-grid-journey-preview.js lines 701–859
  2. Grid Vicinity geodesy · gridatlas / atlas/modules/202611180026-grid-vicinity.js lines 1–541

Grid Journey Preview

A JavaScript file in the atlas folder of GridAtlas that maps network, transformers and cables, using SHA-256. It validates product (`validateProduct`), validates ledger (`validateLedger`) and classifies edges (`classifyEdges`).

rendergridatlas / atlas/modules/202611172355-grid-journey-preview.js · lines 701–859 of 859 · version 2026-11-17 23:55 (continued from section 532) · Not reached from any entry point (candidate for review) · pattern createJourneyController (shared by 2 files)

What it does
It maps network, transformers and cables. Defines 67 functions or classes, including JourneyTopology, voltageOf, bandKey, ratingsOf, physicalUnits. Side effects: changes the web page (DOM); reads or writes files.
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: transformers, cables.
Inputs & outputs
In: JSON file network.json. Coordinate systems named: WGS84 / EPSG:4326.
What it achieves
Canonical engine Ventusltd/ventus-grid-engine. No live pointer writes. Its code works with 100 MVA. It responds to change events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
JourneyTopology, voltageOf, bandKey, ratingsOf, physicalUnits, parametersOf, index, land, siteOf, graph, resolve, at
Defines here
writeCursor, lineFor, frameRoute, showStep, advance, resetPlan, animate, frame, choose, installLayerControls, setOrigin, open, styleLoad, preferenceChange, mapRemoved, destroy, mount, attach
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/202611172355-grid-journey-preview.js:701-859 · blob 455c32ec542a2ac0bb637361093742af8e6e7ede · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
  }
  function writeCursor(coordinates) {
    cursorData = {type: 'FeatureCollection', features: coordinates ? [{type: 'Feature', properties: {meaning: 'learning cursor only'}, geometry: {type: 'Point', coordinates}}] : []};
    if (ownedSources.has(cursor) && ownedSources.get(cursor) === map.getSource(cursor)) map.getSource(cursor).setData(cursorData);
  }
  function lineFor(s) { const e = plan.edgeCatalog.find(e => e.edgeUid === s.edgeUid); if (!e?.coordinates) return null; const coords = e.coordinates.map(p => [...p]); if (s.direction === 'reverse') coords.reverse(); return {e, coords}; }
  function frameRoute() {
    if (!alive || !opened || !plan) return;
    const pts = plan.edgeCatalog.flatMap(e => e.coordinates || []);
    const r = map.getContainer?.().getBoundingClientRect?.(), q = panel.getBoundingClientRect?.();
    let padding = 65;
    if (r && q) { const top = Math.max(45, q.bottom - r.top + 12); padding = q.width > r.width * .6 && r.height - top > 130 ? {left: 35, right: 35, top, bottom: 50} : {left: 45, right: Math.min(r.width * .6, q.width + 25), top: 55, bottom: 55}; }
    if (pts.length && map.fitBounds) { map.setPadding?.({top: 0, right: 0, bottom: 0, left: 0}); map.fitBounds([[Math.min(...pts.map(p => p[0])), Math.min(...pts.map(p => p[1]))], [Math.max(...pts.map(p => p[0])), Math.max(...pts.map(p => p[1]))]], {padding, maxZoom: 9, duration: 0}); }
  }
  function showStep(index) {
    const s = plan.steps[index], line = lineFor(s);
    writeCursor(line?.coords.at(-1) || null);
    report(`SYNTHETIC ONLY · ${index + 1}/${plan.steps.length} · ${s.traversal} ${s.nearNode} → ${s.farNode} · ${s.geometryStatus === 'published_node_unlocated' ? 'UNLOCATED: text only' : line?.e.schematic ? 'DOTTED SCHEMATIC: not a cable route' : 'synthetic reviewed polyline'} · journey heading, flow direction unavailable`);
    step = index + 1; controlsState();
  }
  function advance() { pauseMotion(); if (plan && step < plan.steps.length) showStep(step); }
  function resetPlan() { pauseMotion(); step = 0; writeCursor(null); if (plan) report(`SYNTHETIC ONLY · ready · ${plan.visitedUniqueEdges} source-row edges; ${plan.steps.length} moves including explicit backtracking; physical units unknown`); controlsState(); }
  function animate() {
    if (!alive || !opened || !plan || step >= plan.steps.length) { pauseMotion(); controlsState(); return; }
    if (isReduced()) { pauseMotion(); controlsState(); return; }
    const index = step, s = plan.steps[index], line = lineFor(s); let began;
    function frame(now) {
      if (!alive || !opened || !playing) return;
      if (isReduced()) { pauseMotion(); controlsState(); return; }
      began ??= now; const t = Math.min(1, (now - began) / 1000);
      // Only a reviewed polyline gets a travelling light. Schematic/unlocated moves are discrete.
      if (line && !line.e.schematic) {
        const p = t * (line.coords.length - 1), i = Math.min(line.coords.length - 2, Math.floor(p)), f = p - i;
        writeCursor(line.coords[i].map((v, k) => v + (line.coords[i + 1][k] - v) * f));
      }
      if (t < 1) raf = W.requestAnimationFrame(frame);
      else { showStep(index); if (playing) animate(); }
    }
    raf = W.requestAnimationFrame(frame);
  }
  async function choose() {
    const ticket = ++epoch; pauseMotion(); plan = null; routeData = empty(); cursorData = empty(); removeMap(); controlsState();
    if (!select.value || !demo) { report('Choose an explicit reviewed synthetic node. No nearest-node or project connection is inferred.'); return; }
    report('Checking exact source bytes and review ledger…');
    try {
      const candidate = await planner({sourceBytes: fixture.networkText, ledger: fixture.ledger, query: {seed: {chosenNode: select.value}, bounds: {maxNodes: 25, maxEdges: 30, maxMoves: 60, maxGeometryBytes: 16000}}});
      if (!alive || ticket !== epoch || !opened) return;
      if (candidate.status === 'refused' || !candidate.steps.length) { report('WITHHELD: ' + (candidate.refusal || 'no eligible reviewed edges')); return; }
      // The engine classifies evidence. Presentation refuses unsupported output as well.
      if (candidate.edgeCatalog.some(e => !['verified_circuit_and_polyline', 'published_topology_only', 'published_node_unlocated'].includes(e.geometryStatus))) throw new Error('Unsupported geometry evidence');
      plan = candidate;
      routeData = {type: 'FeatureCollection', features: plan.edgeCatalog.filter(e => e.coordinates).map(e => ({type: 'Feature', properties: {edgeUid: e.edgeUid, schematic: e.schematic, meaning: e.label}, geometry: {type: 'LineString', coordinates: e.coordinates}}))};
      receipt.textContent = `SYNTHETIC TEST ONLY; no real assets or third-party approval\nsource SHA256 ${plan.sourceBundleSha}\nreview SHA256 ${plan.reviewLedgerSha}\nplan SHA256 ${plan.planSha256}\n${plan.edgeCatalog.filter(e => e.geometryStatus === 'verified_circuit_and_polyline').length} synthetic polylines; ${plan.edgeCatalog.filter(e => e.schematic).length} schematic; ${plan.edgeCatalog.filt  … [line shortened here: 760 characters; full line on GitHub]
      if (!installMap()) return;
      resetPlan();
      frameRoute();
    } catch (e) { if (alive && ticket === epoch) report('WITHHELD: ' + e.message); }
  }
  function installLayerControls() {
    const hosts = ['scada-ui-container', 'fs-curtain-keys'].map(id => [id, D.getElementById(id)]);
    hosts.push(['native-grid-menu', D.querySelector?.('#gridatlas-menu-bar-panel-4 .gm-panel-body')]);
    for (const [id, host] of hosts) {
      if (!host || layerGroups.some(g => g.parentNode === host || g.parent === host)) continue;
      // Other native modules use .key-group as the engine-dashboard ready marker.
      // Never create that marker before the engine's original controls exist.
      if (id !== 'native-grid-menu' && !host.querySelector?.('input[data-layer-id]')) continue;
      const group = el('div', null, host, {class: 'key-group', 'data-journey-group': id});
      const title = el('div', 'Grid Journeys', group, {class: 'key-title'});
      const button = el('button', 'Open Grid Journey', group, {type: 'button', class: 'map-ctrl-btn', 'aria-controls': NS + '-panel', 'aria-expanded': String(opened)});
      button.style.cssText = 'min-height:44px;min-width:44px;';
      el('p', 'Exploratory only; real routes require reviewed circuit evidence.', group);
      listen(button, 'click', e => { e.stopPropagation?.(); returnFocus = button; W.__GRIDATLAS_MODULES__?.menuBar?.closeAll?.(); const curtain = D.getElementById('fs-curtain'); if (id === 'fs-curtain-keys' && curtain?.classList?.contains('curtain-open')) D.getElementById('fs-curtain-tab')?.click(); open(); });
      layerGroups.push(group); layerLaunchers.push(button);
    }
  }
  function setOrigin(origin) {
    originContext = null;
    if (origin && typeof origin === 'object') {
      const name = typeof origin.name === 'string' ? origin.name.slice(0, 160) : '';
      const id = typeof origin.id === 'string' || typeof origin.id === 'number' ? String(origin.id).slice(0, 80) : '';
      if (name || id) { originContext = {name, id}; if (Array.isArray(origin.at) && origin.at.length === 2 && origin.at.every(Number.isFinite) && Math.abs(origin.at[0]) <= 180 && Math.abs(origin.at[1]) <= 90 && (origin.at[0] !== 0 || origin.at[1] !== 0)) originContext.at = [...origin.at]; if (['repd', 'datacentre', 'substation'].includes(origin.type)) originContext.type = origin.type; }
    }
    context.textContent = originContext ? 'Selected asset: ' + [originContext.name, originContext.id].filter(Boolean).join(' ? ') + '. Nearby assets are map context; connections need source evidence.' : 'Select an asset on the map to explore its surroundings.';
    realSelection(false);
  }
  function shut() { ++epoch; pauseMotion(); opened = false; panel.hidden = true; opener.setAttribute('aria-expanded', 'false'); removeMap(); if (initialPadding) map.setPadding(initialPadding); for (const b of layerLaunchers) b.setAttribute('aria-expanded', 'false'); const target = returnFocus?.isConnected === false || (returnFocus?.getClientRects && !returnFocus.getClientRects().length) ? D.getEle  … [line shortened here: 491 characters; full line on GitHub]
  function open(options) { if (!alive) return; if (options?.origin) setOrigin(options.origin); opened = true; panel.hidden = false; opener.setAttribute('aria-expanded', 'true'); for (const b of layerLaunchers) b.setAttribute('aria-expanded', 'true'); installMap(); frameRoute(); close.focus(); }
  function realSelection(clearContext = true) { if (clearContext) { originContext = null; context.textContent = 'Selected asset has no reviewed circuit identity. Real circuit journeys remain withheld.'; } ++epoch; pauseMotion(); plan = null; demo = false; select.value = ''; select.disabled = true; removeMap(); controlsState(); report('Explore this asset and the surrounding grid. Nearby assets do n  … [line shortened here: 431 characters; full line on GitHub]
  listen(opener, 'click', () => {returnFocus = opener; opened ? shut() : open();}); listen(close, 'click', shut);
  listen(panel, 'keydown', e => { if (e.key === 'Escape') { e.preventDefault(); shut(); } });
  listen(demoButton, 'click', () => { ++epoch; pauseMotion(); plan = null; removeMap(); demo = true; select.disabled = false; select.replaceChildren(); el('option', 'Choose a reviewed synthetic node…', select, {value: ''}); for (const n of fixture.ledger.nodes) el('option', 'SYNTHETIC ' + n.nodeId, select, {value: n.nodeId}); report('SYNTHETIC DEMONSTRATION LOADED. These are invented assets; choos  … [line shortened here: 453 characters; full line on GitHub]
  listen(realGrid, 'click', event => {
    event.stopPropagation?.();
    const vicinity = W.__GRIDATLAS_MODULES__?.gridVicinity;
    if (!vicinity?.open) {
      const grid = D.getElementById('gridatlas-menu-bar-title-4');
      if (!grid?.click) {
        const layers = D.getElementById('scada-ui-container');
        if (!layers?.scrollIntoView) { report('Grid layers are loading. Try Explore grid again when the map controls appear.'); return; }
        if (originContext?.at) map.flyTo?.({center: [...originContext.at], duration: 0});
        shut(); layers.scrollIntoView({block: 'start', behavior: 'instant'});
        layers.querySelector?.('input[data-layer-id]')?.focus();
        return;
      }
      if (originContext?.at) map.flyTo?.({center: [...originContext.at], duration: 0});
      shut();
      if (grid.getAttribute?.('aria-expanded') !== 'true') grid.click();
      grid.focus();
      return;
    }
    pauseMotion(); vicinity.open({origin: originContext?.at ? {...originContext, at: [...originContext.at]} : undefined, radiusKm: 10}); shut();
  });
  listen(select, 'change', choose); listen(next, 'click', advance); listen(reset, 'click', resetPlan);
  listen(start, 'click', () => { if (!plan) return; if (isReduced()) { advance(); return; } playing = true; controlsState(); animate(); });
  listen(pause, 'click', () => { pauseMotion(); controlsState(); });
  listen(W, 'gridatlas:card-open', e => { if (e.detail?.origin) setOrigin(e.detail.origin); else realSelection(); });
  listen(W, 'gridatlas:journey-open', e => open(e.detail));
  installLayerControls();
  if (W.MutationObserver && D.documentElement) { layerObserver = new W.MutationObserver(installLayerControls); layerObserver.observe(D.documentElement, {childList: true, subtree: true}); }
  const styleLoad = () => { pauseMotion(); installMap(); controlsState(); }; map.on('style.load', styleLoad);
  map.on('resize', frameRoute);
  const preferenceChange = () => { if (isReduced()) pauseMotion(); controlsState(); };
  if (media?.addEventListener) { media.addEventListener('change', preferenceChange); on.push(() => media.removeEventListener('change', preferenceChange)); }
  function mapRemoved() { destroy(true); }
  function destroy(mapWasRemoved = false) {
    if (!alive) return; alive = false; ++epoch; pauseMotion();
    try {
      map.off('style.load', styleLoad); map.off('resize', frameRoute); map.off('remove', mapRemoved); for (const off of on.splice(0)) off();
      // MapLibre fires remove AFTER destroying its style. Its layers/sources have already gone.
      if (mapWasRemoved) { ownedLayers.clear(); ownedSources.clear(); } else { removeMap(); if (initialPadding) map.setPadding(initialPadding); }
    } finally { layerObserver?.disconnect(); for (const group of layerGroups) group.remove(); root.remove(); }
  }
  map.on('remove', mapRemoved);
  controlsState();
  return Object.freeze({open, setOrigin, close: shut, snapshot: () => ({alive, opened, playing, step, status: plan?.status || 'withheld', synthetic: demo, origin: originContext ? {...originContext} : null, layerControls: layerGroups.length, steps: plan?.steps.length || 0, edgeCount: plan?.edgeCatalog.length || 0}), destroy});
}

// Bounded public-map attachment. No private card closures, new map or network fetch.
const registry = window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {};
if (!registry.gridJourneyPreview) {
  let controller = null, timer = null, attempts = 0, stopped = false;
  function mount(map = window.__GRIDATLAS_V9_MAP__) {
    stopped = false;
    if (controller?.snapshot().alive) return controller;
    controller = null;
    controller = createJourneyController({map, document, window, planner: JourneyEngine.planJourney, fixture: JourneyFixture, css: JourneyCSS, generation: JourneyGeneration});
    return controller;
  }
  function attach() {
    if (stopped) return;
    if (window.__GRIDATLAS_V9_MAP__) { try { mount(); } catch (e) { console.warn('[Grid Journey preview]', e.message); } return; }
    if (++attempts < 120) timer = setTimeout(attach, 250);
    else console.warn('[Grid Journey preview] native map unavailable; no replacement map created');
  }
  registry.gridJourneyPreview = Object.freeze({schema: 'gridatlas.journey.preview.v1', generation: JourneyGeneration, mount, open(options) { return mount().open(options); }, setOrigin(origin) { return mount().setOrigin(origin); }, snapshot: () => controller?.snapshot() || {status: 'map-unavailable'}, destroy() { stopped = true; clearTimeout(timer); controller?.destroy(); controller = null; }});
  attach();
}

})();

Grid Vicinity

A JavaScript file in the atlas folder of GridAtlas that maps notice, grid substations, the Renewable Energy Planning Database (REPD) register and transformers, using SHA-256.

geodesygridatlas / atlas/modules/202611180026-grid-vicinity.js · lines 1–541 of 1277 · version 2026-11-18 00:26 · Not reached from any entry point (candidate for review) · pattern createScenarioStationStore (shared by 2 files)

What it does
It maps notice, grid substations, the REPD register and transformers. Defines 127 functions or classes, including validCoordinate, radiusKm, normaliseOrigin, parseVicinityIntent, numberText. Side effects: changes the web page (DOM); reads or writes files.
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: the REPD register, transformers, 400kV, 275kV, 132kV, 66kV.
Inputs & outputs
In: JSON file notice.json; GeoJSON file grid_substations.geojson. Out: interactive map. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
What it achieves
It normalises origin (`normaliseOrigin`), parses vicinity intent (`parseVicinityIntent`) and validates news context base (`validateNewsContextBase`). GridAtlas vicinity : source-built spatial context, no inferred circuits. Its code works with 33 kV, 11 kV and 132 kV. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
Declared Connections (estate URL)
Used by
mentioned in Standalone (comment link)
Produces
validCoordinate, radiusKm, normaliseOrigin, parseVicinityIntent, numberText, validateNewsContextBase, normaliseNewsTopic, newsContextHref, voltageBands, stationRecords, exploreVicinity, vicinityGeoJSON
Defines here
validCoordinate, radiusKm, normaliseOrigin, parseVicinityIntent, numberText, validateNewsContextBase, normaliseNewsTopic, newsContextHref, voltageBands, stationRecords, exploreVicinity, vicinityGeoJSON, collectAssetContext, assetCoordinate, statedMw, assetId, collectAssetContext, get, add, documentContextFor, freezeDocumentContext, documentOrigin, documentContextFor, TrainCore, trainCoordinate, normaliseTrainStop, buildStationIndex, copy, limitValue, result
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/202611180026-grid-vicinity.js:1-541 · blob 419758cc50731538e44cf604067a2ef2ecf67950 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* GridAtlas vicinity 202611180026: source-built spatial context, no inferred circuits. */
(() => {
'use strict';
const VICINITY_GENERATION="202611180026";
const VICINITY_CSS="#gridatlas-vicinity{position:absolute;inset:0;pointer-events:none;z-index:32;font:12px/1.4 monospace;color:#bfe9ee}#gridatlas-vicinity *{box-sizing:border-box}#gridatlas-vicinity button,#gridatlas-vicinity input{font:inherit;pointer-events:auto}#gridatlas-vicinity button{min-height:44px;padding:7px 10px;color:#0ff;background:#061216;border:1px solid #367078;cursor:pointer}#grid  … [line shortened here: 4,988 characters; full line on GitHub]
/** Spatial exploration only. Canonical Atlas geodesy is injected, never forked. */
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']
]);

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);
}

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;
}

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)};
}

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;
}

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;
}

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';
}

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;
}

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'))];
}

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;
}

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. */
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}}))
  ]};
}

const collectAssetContext = (() => {
/** Read-only context from existing Atlas source owners. No fetching or electrical inference. */
const ASSET_CONTEXT_CATEGORIES = Object.freeze([
 ['generation','REPD generation context'],['storage','REPD storage context'],['datacentre','Data-centre listings'],
 ['conventional','Listed conventional power context'],['demand-context','Other potential demand context']
]);
const assetCoordinate = at => 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&&(at[0]!==0||at[1]!==0);
const statedMw = value => {const v=value&&typeof value==='object'?value.value:value;if(typeof v!=='number'&&typeof v!=='string')return null;if(typeof v==='string'&&!/^\d+(?:\.\d+)?$/.test(v.trim()))return null;const n=Number(v);return Number.isFinite(n)&&n>0?n:null;};
const assetId = value => (typeof value==='string'||typeof value==='number')&&String(value).trim()&&String(value).length<=256?String(value).trim():null;
function assetPrecision(p){for(const [field,value]of[['location.precision',p.location?.precision],['coordinate_precision',p.coordinate_precision],['location_precision',p.location_precision]])if(typeof value==='string'&&value.trim())return{precision:value,precisionField:field,approximateLocation:/approx|centroid|postcode|settlement|area/i.test(value)};return{precision:null,precisionField:null,appro  … [line shortened here: 423 characters; full line on GitHub]
function collectAssetContext({map,registry={},origin,radiusKm,geodesy,limit=200}={}){
 const at=origin?.at;
 if(!assetCoordinate(at)||!Number.isInteger(radiusKm)||radiusKm<1||radiusKm>50)throw Error('Located origin and integer radius 1-50 km are required.');
 if(!geodesy?.distanceKm||!geodesy?.representativePoint)throw Error('Canonical Atlas geodesy is required.');
 if(!Number.isInteger(limit)||limit<1||limit>200)throw Error('Asset result limit must be 1-200.');
 const categories=ASSET_CONTEXT_CATEGORIES.map(([id,label])=>({id,label,availability:'NOT_LOADED',source:null,count:0,loadedRecords:0,truncated:false,rows:[]}));
 const get=id=>categories.find(c=>c.id===id),seen=new Map(categories.map(c=>[c.id,new Set()]));
 function add(category,row){
  const c=get(category);c.loadedRecords++;
  if(!assetCoordinate(row.at))return;
  // Source IDs deduplicate records; coincident coordinates alone never merge facilities.
  const key=row.id===null?null:row.source+'|'+row.id;
  if(key!==null){if(seen.get(category).has(key))return;seen.get(category).add(key);}
  const km=geodesy.distanceKm(at[0],at[1],row.at[0],row.at[1]);
  if(!Number.isFinite(km)||km<0||km>radiusKm)return;
  c.rows.push({...row,at:row.at.slice(0,2),km,demandMw:null,facilityVerified:null,connection:null});
 }
 let features=null;
 try{const data=map?.getSource?.('src-repd')?.serialize?.().data;if(data?.type==='FeatureCollection'&&Array.isArray(data.features)&&data.features.length)features=data.features;}catch{/* Explicit NOT_LOADED below; no replacement fetch. */}
 if(features){
  for(const id of ['generation','storage'])Object.assign(get(id),{availability:'LOADED',source:'Existing loaded src-repd GeoJSON'});
  features.forEach((f,i)=>{
   const p=f?.properties||{},point=geodesy.representativePoint(f?.geometry),tech=String(p.tech||p.technology||p.technology_type||'Not stated');
   const category=/^(?:bess(?:[_ -].*)?|battery(?:[_ -].*)?|storage|flywheel|caes)$/i.test(tech)?'storage':'generation';
   const ref=assetId(p.repd_ref??p.ref_id),id=ref??assetId(p.id??f?.id);
   add(category,{id,originId:ref&&/^\d+$/.test(ref)?'repd:'+ref:null,name:String(p.name||'Unnamed REPD record'),at:point,kind:category,status:String(p.status||'Not stated'),technology:tech,
    capacityMw:statedMw(p.capacity_mw??p.capacity),capacityBasis:typeof p.capacity_basis==='string'?p.capacity_basis:'REGISTER_STATED_POWER_BASIS_NOT_DECLARED',
    metrics:{itLoadMw:null,gridConnectionMw:null,unclassifiedMw:null},...assetPrecision(p),source:'src-repd',sourceRow:i});
  });
 }
 const owner=registry.ukOfftakers?.state, data=owner?.data, dots=Array.isArray(data?.dots)?data.dots:null;
 if(dots){
  for(const id of ['datacentre','conventional','demand-context'])Object.assign(get(id),{availability:'LOADED',source:id==='conventional'?'Loaded potential-offtaker power-station listing; not the full conventional dataset':'Existing loaded off-taker owner records'});
  dots.forEach((r,i)=>{
   const p=r?.p||{},category=r?.k==='c'?'datacentre':r?.k==='b'?'conventional':['a','d','s','e'].includes(r?.k)?'demand-context':null;if(!category)return;
   const id=assetId(p.id??r.id),size=p.size_metric;
   const capacity=category==='conventional'?(typeof size?.unit==='string'&&/^MW(?:\b|_)/.test(size.unit)?statedMw(size.value):statedMw(p.mw)):null;
   add(category,{id,originId:id,name:String(r.n||p.name||'Unnamed listed site'),at:r.a,kind:category,status:String(p.status||'Not stated'),technology:String(p.technology||p.fuel||r.sub||'Not stated'),
    capacityMw:capacity,capacityBasis:capacity===null?null:'SOURCE_STATED_POWER_NOT_CURRENT_OUTPUT',metrics:category==='datacentre'?{itLoadMw:statedMw(p.it_load_mw),gridConnectionMw:statedMw(p.grid_connection_mw),unclassifiedMw:statedMw(p.unclassified_mw)}:{itLoadMw:null,gridConnectionMw:null,unclassifiedMw:null},
    ...assetPrecision(p),source:category==='datacentre'&&r.dc?'ukOfftakers.data-centre-pipeline':'ukOfftakers.loaded-listing',sourceRow:i});
  });
 }
 for(const c of categories){c.rows.sort((a,b)=>a.km-b.km||a.name.localeCompare(b.name,'en')||String(a.id).localeCompare(String(b.id),'en'));c.count=c.rows.length;c.truncated=c.count>limit;c.rows=c.rows.slice(0,limit);}
 return{categories,radiusKm,connectionsInferred:0,limitations:['Loaded source records only; NOT_LOADED is not zero nearby assets.','Register power, IT load and connection figures remain separate; demand and present output are unknown.','A supplied location and source ID do not verify a facility or its connections; source precision is retained.']};
}

return collectAssetContext;
})();
const documentContextFor = (() => {
/** Existing documentary context only. No fetch, name matching or spatial joins. */
function freezeDocumentContext(value) {
  if (value && typeof value === 'object') { for (const child of Object.values(value)) freezeDocumentContext(child); Object.freeze(value); }
  return value;
}

const DOCUMENT_CONTEXT_PROVENANCE = freezeDocumentContext({
  declaredModule: {
    repository: 'Ventusltd/gridatlas', commit: 'b52693aaf513e63240acd8ab99a698df5b738cc6',
    path: 'atlas/modules/202609012128-declared-connections.js', bytes: 15461,
    sha256: 'a44520ebd644e725f644e7f3aea76839982c82d577022ac04583c5bc3346a371',
    sourceUrl: 'https://github.com/Ventusltd/gridatlas/blob/b52693aaf513e63240acd8ab99a698df5b738cc6/atlas/modules/202609012128-declared-connections.js'
  },
  noticeProducer: {
    repository: 'Ventusltd/globalgrid2050', commit: '07bff3a6d1cdc4d845062cafa1cf49161b135c96',
    path: 'automation/grid_notice_ui/20261117-v938/notice.json', bytes: 5300,
    sha256: 'bef90e1a64e4f1921c62f85ee61d636d1fe02fcebd30ea1570a7b3bfd49f5148',
    factsSha256: 'f9802c96444c21e84b328d612475353861c8053cde31f55196d1ea5862918afb',
    sourceUrl: 'https://github.com/Ventusltd/globalgrid2050/blob/07bff3a6d1cdc4d845062cafa1cf49161b135c96/automation/grid_notice_ui/20261117-v938/notice.json',
    reviewReferences: ['https://github.com/Ventusltd/neural-link-between-agents/issues/42#issuecomment-6953350836', 'https://github.com/Ventusltd/neural-link-between-agents/issues/42#issuecomment-6953404444']
  }
});

const DOCUMENT_CONTEXT_NOTICES = freezeDocumentContext([{
  id: 'government:EN020026:consented:2026-10-30', title: 'Sea Link development consent',
  applicationRef: 'EN020026', status: 'NARROW_FACTS_REVIEWED_NO_ASSET_ASSOCIATION',
  sourceUrl: 'https://www.gov.uk/government/publications/sea-link-development-consent-order-planning-act-2008',
  sourceTitle: 'Department for Energy Security and Net Zero: Sea Link development consent order',
  date: {value: '2026-10-30', precision: 'DAY'},
  statement: 'Government decision records development consent for the Suffolk–Kent transmission proposal. Its planned transmission upper bound is 2,000 MW; current capacity, commissioning and available headroom are unknown.',
  scope: 'Standalone official planning context. No association with the selected asset or its vicinity has been established.',
  plannedMetric: {value: 2000, unit: 'MW', kind: 'planned_transmission_upper_bound'},
  currentCapacityMw: null, commissioned: null, connection: null, repdRef: null, coordinates: null,
  verifiedAssetJoins: 0,
  rightsScope: 'government_html_facts_only_no_images_or_third_party_material',
  licenceUrl: 'https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/',
  sources: [
    {title: 'Planning Inspectorate: Sea Link development consent decision announced', url: 'https://www.gov.uk/government/news/sea-link-development-consent-decision-announced',
      publishedDate: {value: '2026-10-30', precision: 'DAY'}, sourceUpdatedAt: null,
      archivedReceipt: {retrievedAt: '2026-11-17T15:48:11Z', bytes: 68432, sha256: 'b9ba26b90820292e0b181da7993d2d3a2180fc2de0ac53cc6239adeb4cccfaeb'},
      currentObservation: {retrievedAt: '2026-11-18T00:35:01.291330Z', bytes: 68432, sha256: 'b404ca2c91a4b84def5c521ceccab617c4b3bda860d40d2da32fd3e9298f599a', scope: 'Decision day and stated OGL footer reconfirmed; current HTML differs from archived receipt.'}},
    {title: 'Department for Energy Security and Net Zero: Sea Link development consent order', url: 'https://www.gov.uk/government/publications/sea-link-development-consent-order-planning-act-2008',
      publishedDate: {value: '2026-10-30', precision: 'DAY'}, sourceUpdatedAt: null,
      archivedReceipt: {retrievedAt: '2026-11-17T15:48:11Z', bytes: 69536, sha256: 'c26f93aa307740f8b4ec8ad150b152fb6d30e77f201e5bc31a6da52bba16e0d0'},
      currentObservation: {retrievedAt: '2026-11-18T00:35:01.437596Z', bytes: 69536, sha256: 'f15b12f35fa4fd1364894d550d3f053dfa680550ad7d83a56fa5b794624e4084', scope: 'Decision day and stated OGL footer reconfirmed; current HTML differs from archived receipt.'}}
  ]
}]);

function documentOrigin(origin) {
  if (!origin || !['repd', 'datacentre', 'substation'].includes(origin.type) || typeof origin.id !== 'string'
      || !origin.id || origin.id.length > 256 || /[\s\u0000-\u001f\u007f]/.test(origin.id)) return null;
  return {type: origin.type, id: origin.id};
}

function documentContextFor(origin, {declaredConnections} = {}) {
  const identity = documentOrigin(origin), matchedRecords = [];
  const limitations = [
    'No independently verified asset-to-upgrade or asset-to-notice crosswalk is supplied by this adapter.',
    'A published declaration or planning consent does not establish construction, energisation, a surveyed route, electrical connection, power flow or available capacity.',
    'The standalone Sea Link notice is not linked to the selected asset, nearby substations or a distance radius.'
  ];
  // Read the canonical already-published owner table; do not fork its records or
  // attach works to a nearby/name-matching substation. Its status stays verbatim.
  const ref = identity?.type === 'repd' && /^repd:[1-9]\d*$/.test(identity.id) ? identity.id.slice(5) : null;
  const canonical = declaredConnections?.schema === 'gridatlas.module.declared-connections.v1' ? declaredConnections.records : null;
  const declaration = ref && canonical && Object.hasOwn(canonical, ref) ? canonical[ref] : null;
  if (declaration && typeof declaration.source === 'string') {
    const statement = [declaration.works, declaration.poc_works, declaration.via].filter(v => typeof v === 'string' && v).join('; ');
    if (statement) matchedRecords.push({
      id: 'existing-atlas-declaration:' + ref, originId: identity.id,
      title: 'Existing published declaration for REPD ' + ref,
      sourceUrl: DOCUMENT_CONTEXT_PROVENANCE.declaredModule.sourceUrl, sourceTitle: declaration.source,
      statement, status: 'EXISTING_PUBLISHED_DECLARATION_UNREVALIDATED',
      scope: 'Existing published declaration; source citation not revalidated here. Exact REPD key only; not an independently verified asset-to-document association.',
      matchBasis: 'EXACT_REPD_KEY_IN_CANONICAL_OWNER_MODULE', verifiedAssetAssociation: false,
      date: null, datePrecision: 'UNKNOWN',
      declaredStatus: declaration.poc_status ?? null,
      // Preserve the original owner's fields and classification separately from
      // this adapter's review status. Never infer an absent status or date.
      declaration: Object.fromEntries(['works', 'poc_works', 'substation', 'circuit', 'via', 'source', 'poc_status', 'poc_status_note', 'poc_kind', 'kv']
        .filter(k => Object.hasOwn(declaration, k)).map(k => [k, declaration[k]]))
    });
  }
  if (!identity) limitations.unshift('No supported stable source identity was supplied; names and coordinates were not used to create a match.');
  else if (!matchedRecords.length) limitations.unshift('No exact existing documentary declaration is available for this source identity.');
  return freezeDocumentContext({
    schema: 'gridatlas.vicinity.document-context.v1', origin: identity,
    status: matchedRecords.length ? 'EXISTING_DECLARATION_ONLY' : 'NO_EXACT_ASSET_DOCUMENT_CONTEXT',
    matchedRecords, unassociatedNotices: DOCUMENT_CONTEXT_NOTICES,
    verifiedAssetJoins: 0, realConnectionsInferred: 0,
    counts: {existingDeclarations: matchedRecords.length, unassociatedNotices: 1, governmentDocuments: 2, verifiedAssetJoins: 0},
    limitations, provenance: DOCUMENT_CONTEXT_PROVENANCE
  });
}

return documentContextFor;
})();
const TRAIN_STATION_SOURCE_PIN={"path":"atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson","bytes":1192748,"sha256":"87976435766a58ddf19c99540b58cd7f18a224148af42ba55075d8851f9e6251","features":5800,"basis":"Expected immutable loader input; not a runtime payload revalidation"};
const TrainCore=(()=>{
/** Full source inventory. Display limits never change inventory or itinerary limits. */
function trainCoordinate(at) {
  return Array.isArray(at) && at.length === 2 && at.every(v => typeof v === 'number' && Number.isFinite(v)) && Math.abs(at[0]) <= 180 && Math.abs(at[1]) <= 90 && !(at[0] === 0 && at[1] === 0);
}
function normaliseTrainStop(stop) {
  const stationId = stop?.stationId ?? stop?.id;
  if (typeof stationId !== 'string' || !stationId.trim() || /[\u0000-\u001f\u007f]/.test(stationId) || (stop.id != null && stop.id !== stationId) || !trainCoordinate(stop.at)) throw new Error('A stable source station ID and valid source point are required.');
  const row = {stationId, id: stationId, name: String(stop.name || 'Unnamed mapped substation'), at: stop.at.slice(), kv: [...new Set((stop.kv || []).filter(v => typeof v === 'number' && Number.isFinite(v) && v > 0))], operator: String(stop.operator || ''), source: String(stop.source || 'Existing Atlas substation layer')};
  if (stop.place) {
    const p = stop.place;
    if (typeof p.label !== 'string' || !p.label.trim() || !trainCoordinate(p.at) || typeof p.provider !== 'string' || !p.provider || typeof p.distanceKm !== 'number' || !Number.isFinite(p.distanceKm) || p.distanceKm < 0) throw new Error('Place binding requires label, resolved point, provider and measured distance.');
    row.place = {label: p.label, at: p.at.slice(), provider: p.provider, precision: p.precision == null ? null : String(p.precision), distanceKm: p.distanceKm, ...(p.resolvedLabel ? {resolvedLabel: String(p.resolvedLabel)} : {})};
  }
  return row;
}
function buildStationIndex(features, {geodesy, datasetPin = null} = {}) {
  if (!Array.isArray(features) || typeof geodesy?.representativePoint !== 'function' || typeof geodesy?.voltagesKv !== 'function' || typeof geodesy?.distanceKm !== 'function') throw new Error('Full source features and canonical geodesy are required.');
  const sourceRecords = features.length, rows = [], ids = new Map(), conflictingIds = new Set();
  let invalidRecords = 0, duplicateRecords = 0;
  for (const feature of features) {
    const p = feature?.properties || {}, stationId = feature?.id ?? p.id, at = geodesy.representativePoint(feature?.geometry);
    if (stationId == null) { invalidRecords++; continue; }
    let row;
    try { row = normaliseTrainStop({stationId: String(stationId), at, name: p.name, kv: Array.from(geodesy.voltagesKv(p)), operator: p.operator, source: p.source}); } catch { invalidRecords++; continue; }
    if (ids.has(row.stationId)) {
      duplicateRecords++;
      if (JSON.stringify(ids.get(row.stationId)) !== JSON.stringify(row)) conflictingIds.add(row.stationId);
      continue;
    }
    ids.set(row.stationId, row); rows.push(row);
  }
  // Conflicting identities are visible as a coverage gap, never silently selectable.
  const inventory = rows.filter(row => !conflictingIds.has(row.stationId));
  const pin = datasetPin == null ? null : JSON.parse(JSON.stringify(datasetPin));
  const copy = row => normaliseTrainStop(row), folded = s => String(s).normalize('NFKC').toLocaleLowerCase('en').trim();
  const limitValue = limit => { if (limit == null) return Infinity; if (!Number.isInteger(limit) || limit < 1) throw new Error('Result limit must be a positive integer.'); return limit; };
  function result(matches, limit, query = null) {
    const n = limitValue(limit);
    return {schema: 'gridatlas.station-search.v1', query, sourceRecords, indexedRecords: inventory.length, matched: matches.length, truncated: matches.length > n, ambiguous: matches.length > 1, rows: matches.slice(0,n).map(row => ({...copy(row), ...(row.distanceKm == null ? {} : {distanceKm: row.distanceKm})}))};
  }
  return Object.freeze({
    search(query, {limit} = {}) {
      const q = folded(query ?? '');
      const matches = q ? inventory.filter(row => folded(row.stationId).includes(q) || folded(row.name).includes(q)) : [];
      matches.sort((a,b) => Number(folded(b.stationId) === q) - Number(folded(a.stationId) === q) || Number(folded(b.name) === q) - Number(folded(a.name) === q) || a.name.localeCompare(b.name,'en') || a.stationId.localeCompare(b.stationId,'en'));
      return result(matches, limit, String(query ?? ''));
    },
    near(at, {radiusKm, limit} = {}) {
      if (!trainCoordinate(at) || !Number.isInteger(radiusKm) || radiusKm < 1 || radiusKm > 50) throw new Error('Choose a valid place point and whole radius from 1 to 50 km.');
      const matches = inventory.map(row => ({...row, distanceKm: geodesy.distanceKm(at[0],at[1],row.at[0],row.at[1])})).filter(row => Number.isFinite(row.distanceKm) && row.distanceKm >= 0 && row.distanceKm <= radiusKm).sort((a,b) => a.distanceKm-b.distanceKm || a.stationId.localeCompare(b.stationId,'en'));
      return result(matches, limit);
    },
    get(stationId) { const row = ids.get(stationId); return row && !conflictingIds.has(stationId) ? copy(row) : null; },
    snapshot() { return {schema:'gridatlas.station-index.v1', sourceRecords, indexedRecords:inventory.length, invalidRecords, duplicateRecords, conflictingIds:[...conflictingIds], datasetPin: pin == null ? null : JSON.parse(JSON.stringify(pin)), datasetPinStatus:pin == null ? 'NOT_SUPPLIED' : 'CALLER_SUPPLIED_NOT_REVALIDATED', coordinatePrecision:'SOURCE_PROVIDED_NOT_INDEPENDENTLY_VERIFIED', conne  … [line shortened here: 420 characters; full line on GitHub]
  });
}



/** Session-owned drawing input. Never an official station, inventory or connection. */
function createScenarioStationStore({sessionId=globalThis.crypto?.randomUUID?.()}={}) {
 if(typeof sessionId!=='string'||!/^[A-Za-z0-9_-]{1,80}$/.test(sessionId))throw new Error('A valid unique session ID is required.');
 let revision=0,serial=0;const rows=new Map(),prefix='scenario:'+sessionId+':';
 const clone=row=>({...normaliseTrainStop(row),proposed:true,sessionId,scenarioRevision:row.scenarioRevision,evidence:'SESSION_ONLY_USER_PROPOSED_NOT_OFFICIAL'});
 function record(id,value){if(typeof value.name!=='string'||!value.name.trim()||!trainCoordinate(value.at)||!Array.isArray(value.kv)||value.kv.length!==1||![11,33].includes(value.kv[0]))throw new Error('Name, pin point and explicit11 or33kV choice are required.');return{stationId:id,id,name:value.name.trim(),at:value.at.slice(),kv:value.kv.slice(),operator:'',source:'SESSION_ONLY_USER_PROPOSED',pr  … [line shortened here: 452 characters; full line on GitHub]
 return Object.freeze({create(value){if(value?.stationId!=null||value?.id!=null)throw new Error('Proposed IDs are assigned by the current session.');const id=prefix+(serial+1),row=record(id,value);serial++;revision++;rows.set(id,row);return clone(row);},edit(id,patch){const old=rows.get(id);if(!old)throw new Error('No proposed station owned by this session.');if(patch?.id!=null||patch?.stationId!=  … [line shortened here: 933 characters; full line on GitHub]
}


/** Selected stops, including endpoints. Intermediate traversal nodes are not stored here. */
function createItinerary({mode = 'journey', stationIndex, scenarioStore = null, law: initialLaw = {}} = {}) {
  if (typeof stationIndex?.get !== 'function') throw new Error('The full canonical station index is required.');
  let law=normaliseJourneyLaw(initialLaw);
  const copyStation=row=>({...normaliseTrainStop(row),...(row.proposed?{proposed:true,sessionId:row.sessionId,scenarioRevision:row.scenarioRevision,evidence:'SESSION_ONLY_USER_PROPOSED_NOT_OFFICIAL'}:{})});
  function selectedStation(stop) {
    const id=stop?.stationId ?? stop?.id, canonical=stationIndex.get(id) || (law.fallback === 'user-opted-hypothetical' ? scenarioStore?.get(id) : null);
    if(!canonical)throw new Error('Selected stops must exist by stable ID in the station inventory.');
    if(stop.at && (!Array.isArray(stop.at)||stop.at.length!==2||stop.at.some((v,i)=>v!==canonical.at[i])))throw new Error('Selected station point differs from its canonical source point.');
    if(stop.id != null && stop.id !== id)throw new Error('Conflicting station identity.');
    return copyStation({...canonical,...(stop.place?{place:stop.place}:{})});
  }
  const caps = {journey:10,vicinity:90};
  if (!Object.hasOwn(caps,mode)) throw new Error('Choose journey or vicinity mode.');
  let stops = [], revision = 0, serial = 0;
  const snapshot = () => {
    const invalidStopIds=[];
    const selected=stops.map(s=>{
      const current=s.proposed?scenarioStore?.get(s.stationId):stationIndex.get(s.stationId);
      const valid=!!current && (!s.proposed || law.fallback==='user-opted-hypothetical');
      if(!valid)invalidStopIds.push(s.stopId);
      return {...copyStation(current?{...current,...(s.place?{place:s.place}:{})}:s),stopId:s.stopId,...(!valid?{invalid:true}:{})};
    });
    return {schema:'gridatlas.user-itinerary.v1',mode,limit:caps[mode],selectedCount:stops.length,revision,planEpoch:revision+(scenarioStore?.snapshot().revision||0),law:normaliseJourneyLaw(law),valid:invalidStopIds.length===0,invalidStopIds,evidence:'USER_SELECTED_ITINERARY_NOT_CONFIRMED_CONNECTION',stops:selected,start:stops[0]?.stopId||null,finish:stops.at(-1)?.stopId||null};
  };
  function setLaw(value){const next=normaliseJourneyLaw(value);if(next.fallback!=='user-opted-hypothetical'&&stops.some(s=>s.proposed))throw new Error('Remove proposed stops explicitly before choosing documented-only.');law=next;revision++;return snapshot();}
  function position(value) {
    if (Number.isInteger(value) && value >= 0 && value < stops.length) return value;
    if (typeof value === 'string') { const exact = stops.findIndex(s=>s.stopId===value); if (exact>=0) return exact; const found=stops.map((s,i)=>s.stationId===value?i:-1).filter(i=>i>=0); if(found.length===1)return found[0]; }
    throw new Error('Choose one unambiguous selected stop.');
  }
  function insert(stop,index=stops.length) {
    if(stops.length>=caps[mode])throw new Error('Selected stop limit is '+caps[mode]+' including start and finish.');
    if(!Number.isInteger(index)||index<0||index>stops.length)throw new Error('Invalid selected stop position.');
    const row=selectedStation(stop);stops.splice(index,0,{...row,stopId:'selected-stop-'+(++serial)});revision++;return snapshot();
  }
  function replace(value,stop){const index=position(value),row=selectedStation(stop);stops[index]={...row,stopId:stops[index].stopId};revision++;return snapshot();}
  return Object.freeze({snapshot,setLaw,add(stop,{index}={}){return insert(stop,index);},remove(value){stops.splice(position(value),1);revision++;return snapshot();},move(value,index){const from=position(value);if(!Number.isInteger(index)||index<0||index>=stops.length)throw new Error('Invalid selected stop position.');const [row]=stops.splice(from,1);stops.splice(index,0,row);revision++;return sna  … [line shortened here: 858 characters; full line on GitHub]
}
/** Declarative user constraints only; execution and electrical enforcement belong to the planner. */
function normaliseJourneyLaw(value = {}) {
  if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !['schema','mustVisitStationIds','allowedVoltageBands','fallback','allowTransformers'].includes(key))) throw new Error('Journey law must use the supported declarative fields only.');
  if(value.schema != null && value.schema !== 'gridatlas.journey-law.v1') throw new Error('Unknown journey law schema.');
  const ids=value.mustVisitStationIds ?? [],bands=value.allowedVoltageBands ?? null,fallback=value.fallback ?? 'documented-only',allowTransformers=value.allowTransformers ?? true;
  if(!Array.isArray(ids)||ids.length>90||ids.some(id=>typeof id!=='string'||!id.trim()||/[\u0000-\u001f\u007f]/.test(id)))throw new Error('Ordered must-visit entries require stable station IDs.');
  const supported=new Set(['400','275','220','132','66','33','11','other','unknown']);
  if(bands!==null&&(!Array.isArray(bands)||bands.some(b=>typeof b!=='string'||!supported.has(b))))throw new Error('Choose supported source voltage bands.');
  if(!['documented-only','user-opted-hypothetical'].includes(fallback)||typeof allowTransformers!=='boolean')throw new Error('Choose documented-only or explicit user hypothetical fallback and a boolean transformer gate.');
  return {schema:'gridatlas.journey-law.v1',mustVisitStationIds:ids.slice(),allowedVoltageBands:bands===null?null:[...new Set(bands)],fallback,allowTransformers};
}





/** Adapter to the existing gazetteer result shape. No provider fetch or station auto-selection. */
function createPlaceBridge({resolve,index,geodesy}={}) {
  if(typeof resolve!=='function'||!index?.near||!index?.get||typeof geodesy?.distanceKm!=='function')throw new Error('Existing gazetteer resolver, station index and canonical geodesy are required.');
  let epoch=0,current=null;const offered=new Map();
  function invalidate(){epoch++;current=null;offered.clear();}
  return Object.freeze({invalidate,
    async lookup(label,{radiusKm=10,limit}={}) {
      invalidate();if(typeof label!=='string'||!label.trim())throw new Error('Type a place or postcode.');
      if(!Number.isInteger(radiusKm)||radiusKm<1||radiusKm>50)throw new Error('Choose a whole radius from 1 to 50 km.');
      const request=epoch;current={label,status:'RESOLVING',epoch:request};
      let raw;try{raw=await resolve(label);}catch(error){if(request!==epoch)return{stale:true,epoch:request};current={label,status:'FAILED',epoch:request,error:String(error?.message||error)};throw error;}
      if(request!==epoch)return{stale:true,epoch:request};
      const places=[];
      for(const [i,result]of (Array.isArray(raw)?raw:[]).entries()) {
        const at=result.at || [result.longitude,result.latitude];
        if(!trainCoordinate(at)||typeof result.provider!=='string'||!result.provider)continue;
        const place={label, resolvedLabel:String(result.label||label),at:at.slice(),provider:result.provider,precision:result.precision==null?null:String(result.precision),kind:String(result.kind||'location'),token:request+':'+i};
        const nearby=index.near(at,{radiusKm,limit});offered.set(place.token,{place,stationIds:new Set(nearby.rows.map(s=>s.stationId))});places.push({...place,at:place.at.slice(),nearby});
      }
      current={label,status:places.length?'CHOOSE_PLACE_AND_STATION':'NO_RESULTS',epoch:request};return{...current,places,stationAutomaticallySelected:false};
    },
    bind(token,stationId) {
      const choice=offered.get(token);if(!choice||!token.startsWith(epoch+':'))throw new Error('Place result is stale; search again.');
      if(!choice.stationIds.has(stationId))throw new Error('Explicitly choose a station offered within this place radius.');
      const station=index.get(stationId);if(!station)throw new Error('Station identity is unavailable or ambiguous.');
      const p=choice.place,distanceKm=geodesy.distanceKm(p.at[0],p.at[1],station.at[0],station.at[1]);
      return normaliseTrainStop({...station,place:{label:p.label,resolvedLabel:p.resolvedLabel,at:p.at,provider:p.provider,precision:p.precision,distanceKm}});
    },snapshot(){return current?{...current}:{status:'IDLE',epoch};}
  });
}



/** Ordered user itinerary; proximity never establishes electrical connectivity. */
function buildRoutePlan({stops, stationIndex = null, scenarioStore = null, planEpoch = null, synthetic = false, geodesy, allowSimulated = false, network = null, rules = {}, law = null} = {}) {
  if (!Array.isArray(stops) || stops.length < 2 || stops.length > 90) throw Error('Choose 2–90 station stops.');
  if (typeof geodesy?.distanceKm !== 'function') throw Error('Canonical geodesy is required.');
  const ids = new Set();
  const selected = stops.map(stop => {
    const id = stop.stationId || stop.id;
    if (typeof id !== 'string' || !id) throw Error('Each stop needs a stable station identity.');
    if (stop.id != null && stop.id !== id) throw Error('Conflicting station identity.');
    const canonical = stationIndex?.get(id);
    const proposed = !canonical && law?.fallback === 'user-opted-hypothetical' ? scenarioStore?.get(id) : null;
    if (proposed && (proposed.proposed !== true || proposed.source !== 'SESSION_ONLY_USER_PROPOSED'
      || !id.startsWith('scenario:') || proposed.kv.length !== 1 || ![11,33].includes(proposed.kv[0]))) throw Error('Invalid session-owned proposal.');
    const owned = canonical || proposed;
    if (stop.invalid || !synthetic && (!owned || !same(owned.at, stop.at))) throw Error('Choose an existing canonical station from the station index or an opted-in current session proposal.');
    if (synthetic && !String(stop.source).startsWith('SYNTHETIC')) throw Error('Fictional stops need an explicit synthetic source.');
    const stopId = stop.stopId || 'visit-' + ids.size;
    if (ids.has(stopId)) throw Error('Each visit needs a distinct stop identity.');
    ids.add(stopId);
    if (!Array.isArray(stop.at) || stop.at.length !== 2 || !stop.at.every(Number.isFinite)
      || Math.abs(stop.at[0]) > 180 || Math.abs(stop.at[1]) > 90) throw Error('A station stop is unlocated.');
    const trusted = owned || stop;
    const kv = (Array.isArray(trusted.kv) ? trusted.kv : [trusted.kv]).filter(kv => Number.isFinite(kv) && kv > 0);
    if (stop.selectedVoltageKv != null && !kv.includes(stop.selectedVoltageKv)) throw Error('Selected journey voltage must belong to the canonical station.');
    return {...trusted, ...(stop.place ? {place: stop.place} : {}), id, stationId: id, stopId, at: [...trusted.at],
      kv, ...(stop.selectedVoltageKv != null ? {selectedVoltageKv: stop.selectedVoltageKv} : {})};
  });
  if (law) {
    rules = {...rules, allowedVoltages: law.allowedVoltageBands == null ? null : law.allowedVoltageBands.filter(v => /^\d+$/.test(String(v))).map(Number),
      allowOtherVoltage: law.allowedVoltageBands?.includes('other') === true, allowTransformers: law.allowTransformers !== false};
    allowSimulated = law.fallback === 'user-opted-hypothetical';
    let at = 0;
    for (const id of law.mustVisitStationIds || []) {
      while (at < selected.length && selected[at].id !== id) at++;
      if (at === selected.length) throw Error('Required stations must appear in their declared order.');
      at++;
    }
  }
  const allowedVoltages = rules.allowedVoltages === undefined ? null : rules.allowedVoltages;
  if (allowedVoltages !== null && (!Array.isArray(allowedVoltages) || allowedVoltages.some(kv => !Number.isFinite(kv) || kv <= 0))) throw Error('Choose valid voltage levels.');
  const eligible = network?.index && createEligibleTrainIndex(network.index,
    {allowedVoltages, allowOtherVoltage:rules.allowOtherVoltage===true, allowTransformers: rules.allowTransformers === true}, network.isReviewedEdge);
  const sequence = planTrainBuses(selected, eligible, network, allowedVoltages, allowSimulated,rules.allowOtherVoltage===true);
  const legs = selected.slice(1).map((to, i) => {
    const from = selected[i];
    const choice = sequence[i];
    let evidence = choice?.topology ? 'TOPOLOGY_ONLY' : choice?.simulated ? 'SIMULATED' : 'MISSING';
    let coordinates = choice ? [[...from.at], [...to.at]] : null;
    const topology = choice?.topology || null, source = choice?.source || null;
    if (topology) {
      const joined = topology.path.map(hop => {
        const id = hop.circuit_id, join = id && network.geometryByCircuit?.[id];
        return join?.reviewed === true && join.source && join.circuitId === id
          && join.fromNode === hop.from_node && join.toNode === hop.to_node
          && join.geometry?.type === 'LineString' && validLine(join.geometry.coordinates)
          ? join.geometry.coordinates.map(at => [...at]) : null;
      });
      if (joined.length && joined.every(Boolean) && joined.every((line, n) => !n || same(line[0], joined[n - 1].at(-1)))) {
        evidence = 'GIS_REVIEWED'; coordinates = joined.flatMap((line, n) => n ? line.slice(1) : line);
      }
    }
    const km = coordinates ? coordinates.slice(1).reduce((sum, at, n) => sum
      + geodesy.distanceKm(...coordinates[n], ...at), 0) : null;
    if (km !== null && (!Number.isFinite(km) || km < 0)) throw Error('Invalid route distance.');
    return {id: 'leg-' + i, index: i, fromId: from.id, toId: to.id, evidence, coordinates, km,
      topology, source, simulationVoltageKv: choice?.simulated ? choice.kv : null, fromBus: choice?.fromBus || null, toBus: choice?.toBus || null,
      electricalTopology: topology ? 'PUBLISHED_REVIEWED_PATH' : 'UNKNOWN',
      geometry: evidence === 'GIS_REVIEWED' ? 'REVIEWED_SOURCE_GIS' : coordinates ? 'SCHEMATIC' : 'UNKNOWN',
      surveyConstructability: 'UNKNOWN', accessStatus: 'UNKNOWN', direction: 'USER_JOURNEY_HEADING_ONLY', electricalFlow: 'UNKNOWN',
      label: evidence === 'SIMULATED' ? 'User-assumed simulated leg; not a cable route'
        : evidence === 'TOPOLOGY_ONLY' ? 'Published topology; schematic line, not a cable route'
        : evidence === 'GIS_REVIEWED' ? 'Reviewed circuit identity and source GIS geometry'
        : 'No reviewed route for this leg'};
  });
  return {schema: 'gridatlas.train.route-plan.v1', planEpoch, rules: {allowedVoltages: allowedVoltages === null ? null : [...allowedVoltages], allowOtherVoltage:rules.allowOtherVoltage===true, allowTransformers: rules.allowTransformers === true}, stops: selected, legs,
    totalKm: legs.every(leg => leg.km !== null) ? legs.reduce((sum, leg) => sum + leg.km, 0) : null,
    synthetic: !!synthetic, playable: legs.every(leg => leg.coordinates !== null), simulated: legs.some(leg => leg.evidence === 'SIMULATED')};
}
function trainVoltageAllowed(kv, allowed,other=false) { return Number.isFinite(kv) && kv > 0 && (allowed === null || allowed.includes(kv)
  ||other&&![400,275,220,132,66,33,11].includes(kv)); }