GLOBALGRID2050 / EXPLORE CODE

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

Route Plan Test and 9 more files

A test in the train folder of GridAtlas that checks Route Plan and Learning Networks. It is built from the bus network helper (`busNetwork`).

582 lines of JavaScript from gridatlas, in 10 files. Topic: Maps, GIS and field navigation. Section 691 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. Regional Interface Test test · gridatlas / tools/secondary/regional-interface.test.mjs lines 1–136
  2. Regional Preview storage · gridatlas / tools/secondary/regional-preview.mjs lines 1–45
  3. Viewport Query storage · gridatlas / tools/secondary/viewport-query.mjs lines 1–30
  4. Viewport Query Test test · gridatlas / tools/secondary/viewport-query.test.mjs lines 1–8
  5. Browser Test test · gridatlas / tools/train/browser.test.mjs lines 1–99
  6. Build storage · gridatlas / tools/train/gazetteer/build.mjs lines 1–10
  7. Painted Observation Test test · gridatlas / tools/train/painted-observation.test.mjs lines 1–8
  8. Route Plan Test test · gridatlas / tools/train/route-plan.test.mjs lines 1–159
  9. Itinerary transform · gridatlas / tools/train/src/itinerary.mjs lines 1–54
  10. Place Bridge transform · gridatlas / tools/train/src/place-bridge.mjs lines 1–33

Regional Interface Test

A test in the secondary folder of GridAtlas that checks Regional Interface and UK Power Networks (UKPN) Secondary Substations. It makes element (`makeElement`), makes popup (`makePopup`) and gets card (`getCard`).

testgridatlas / tools/secondary/regional-interface.test.mjs · lines 1–136 of 136 · Entry point · pattern harness (shared by 3 files)

What it does
It tests 11kV, transformers, solar and substations. Defines 8 functions or classes, including harness, makeElement, site, makePopup, click. Uses libraries node:test, node:assert/strict, node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
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: 11kV, transformers, solar, substations, 400kV.
Inputs & outputs
Voltage levels named: 400kV, 11kV.
Downstream impact
Used directly by 2 files: CI PR Gate (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas). Reached from 1 other entry point, including Map Promotion Rehearsal (gridatlas).
What it achieves
Defines `harness`, `makeElement`, `site` and 5 more. Its code works with 11 kV and 400 kV.
Why it matters
Run by CI PR Gate and GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/secondary · test
Uses
Regional Interface (import), UKPN Secondary Substations (new URL import.meta.url), node:test, node:assert/strict, node:fs, node:vm
Used by
run by CI PR Gate (script call), run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
harness, makeElement, site, makePopup, click, changeZoom, getCard, flatten
Defines here
harness, makeElement, site, makePopup, click, changeZoom, getCard, flatten
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/secondary/regional-interface.test.mjs:1-136 · blob 86f3dfaf8a5065e605febc9201dbfe2160007abb · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import {buildRegional,assertDataBoundary,patchNativeEngine,readPinnedEngine} from './regional-interface.mjs';
const {engine,data,card}=buildRegional();
test('historical menu interference is rejected; new adapter is DOM-free',()=>{
  assert.throws(()=>assertDataBoundary(fs.readFileSync(new URL('./src/202612010912-native-layer.js',import.meta.url),'utf8')));
  assert.doesNotThrow(()=>assertDataBoundary(data));
  assert.doesNotMatch(card,/stopImmediatePropagation|dispatchEvent|\.checked\s*=|\.disabled\s*=/);
});
test('native registration preserves unrelated rows, both opt-in at zoom 7',()=>{
  const W={fetch(){},initVentusMap:o=>o};
  vm.runInNewContext(data,{window:W});
  const unrelated={id:'400',label:'400 kV'};
  const old={id:'11kv',label:'11kV (UKPN)',color:'#ff00ff',url:'historical.geojson'};
  const original={config:[{group:'Grid',layers:[unrelated,old]}]};
  const result=W.initVentusMap(original);
  const [a,b,c]=result.config[0].layers;
  assert.equal(a,unrelated);assert.equal(original.config[0].layers.length,2);
  assert.equal(b.url,old.url);assert.equal(b.color,old.color);
  assert.equal(c.id,'ukpn_secondary');assert.notEqual(c.color,b.color);
  for(const l of [b,c]){assert.equal(l.minzoom,7);assert.equal(l.acquireMinZoom,7);assert.equal(l.preload,false);}
  assert.equal(W.initVentusMap(result),result);
});
test('engine patch refuses unrecognised baseline',()=>assert.throws(()=>patchNativeEngine('invalid')));
test('regional engine preserves the exact assembled production predecessor outside the acquisition section',()=>{
  const predecessor=readPinnedEngine();
  const start='    function handleLayerToggle(layerId, isVisible) {';
  const end="    map.on('load', () => {\n        buildDOM();";
  assert.ok(predecessor.includes('substation-intelligence-v9-63'));
  assert.ok(predecessor.includes('202609031958-menu-bar.js'));
  assert.ok(predecessor.includes('202609051624-teleprint-controls.js'));
  const before=predecessor.indexOf(start), after=predecessor.indexOf(end);
  assert.ok(before>=0&&after>before);
  assert.ok(engine.startsWith(predecessor.slice(0,before)));
  // Only the explicit inventory contract may change after the acquisition section.
  const restored=engine.replace('var EXPECTED_ENGINE_LAYERS = 61;','var EXPECTED_ENGINE_LAYERS = 60;')
    .replace('var EXPECTED_LAYER_CONTROLS = 64;','var EXPECTED_LAYER_CONTROLS = 63;')
    .replace("        && unique.has('engine:ukpn_secondary')\n",'')
    .replace('menu not installed: expected 61 engine + 3 Pipeline News layer controls; found ','menu not installed: expected 60 engine + 3 Pipeline News layer controls; found ');
  assert.ok(restored.endsWith(predecessor.slice(after)));
  assert.match(engine,/var EXPECTED_ENGINE_LAYERS = 61;/);
  assert.match(engine,/var EXPECTED_LAYER_CONTROLS = 64;/);
  assert.match(engine,/unique\.has\('engine:ukpn_secondary'\)/);
  assert.equal(engine,patchNativeEngine(predecessor));
});
function harness(){
  let zoom=6.99,requests=[],queue=[],visibility=new Map(),events=new Map();
  const cfg=new Map([['11kv',{url:'old',acquireMinZoom:7}],['ukpn_secondary',{url:'new',acquireMinZoom:7}],['solar',{url:'solar'}]]);
  const states=Object.fromEntries([...cfg.keys()].map(id=>[id,{loaded:false,loading:false}]));
  const map={getZoom:()=>zoom,getLayer:id=>id.endsWith('-glow')?null:{},setLayoutProperty:(id,k,v)=>visibility.set(id,v),getSource:()=>({setData(){}}),on:(id,fn)=>events.set(id,fn)};
  const start=engine.indexOf('    const regionalSelected = new Set();');
  const end=engine.indexOf('    // ── Map Load',start);
  const zStart=engine.indexOf("    map.on('zoomend', () => {",end);
  const zEnd=engine.indexOf("    map.on('load', () => {",zStart);
  assert.ok(start>=0&&end>start&&zStart>end&&zEnd>zStart);
  const context={map,layerConfigById:cfg,RUNTIME_STATE:states,statusMode:false,_visibleInteractiveIds:[],_visibleHoverIds:[],REPD_IDS:[],TRANSIT_IDS:[],TRANSIT_SOURCE_MAP:{},updateUIState(){},console,networkQueue:{add:fn=>new Promise((resolve,reject)=>queue.push(()=>fn().then(resolve,reject)))},fetchAndParseGeoJSON:async url=>{requests.push(url);return [{properties:{}}]}};
  const control=vm.runInNewContext(engine.slice(start,end)+engine.slice(zStart,zEnd)+';({toggle:handleLayerToggle})',context);
  return {requests,states,visibility,toggle:control.toggle,zoom(v){zoom=v;events.get('zoomend')();},async drain(){while(queue.length)await queue.shift()();}};
}
test('independent selection below zoom 7, simultaneous load, cache across zoom',async()=>{
  const h=harness();h.toggle('11kv',true);h.toggle('ukpn_secondary',true);await h.drain();
  assert.deepEqual(h.requests,[]);h.zoom(7);await h.drain();
  assert.deepEqual(h.requests,['old','new']);h.zoom(6.99);h.zoom(7);await h.drain();
  assert.deepEqual(h.requests,['old','new']);h.toggle('11kv',false);
  assert.equal(h.visibility.get('l-11kv'),'none');assert.equal(h.visibility.get('l-ukpn_secondary'),'visible');
});
test('deselection before threshold and queue-time eligibility changes',async()=>{
  const h=harness();h.toggle('11kv',true);h.toggle('11kv',false);h.zoom(7);await h.drain();
  assert.deepEqual(h.requests,[]);h.toggle('ukpn_secondary',true);h.zoom(6.99);await h.drain();
  assert.deepEqual(h.requests,[]);assert.equal(h.states.ukpn_secondary.loading,false);
  h.zoom(7);await h.drain();assert.deepEqual(h.requests,['new']);
});
test('unrelated native layers retain immediate acquisition',async()=>{
  const h=harness();h.toggle('solar',true);await h.drain();assert.deepEqual(h.requests,['solar']);
});

test('generated UKPN card defers detailed queries to zoom 16 and rejects stale selection results',async()=>{
  const makeElement=()=>({
    dataset:{},style:{},children:[],textContent:'',isConnected:true,
    appendChild(child){this.children.push(child);return child;},
    replaceChildren(){for(const child of this.children)child.isConnected=false;this.children=[];},
    setAttribute(){}
  });
  const site=id=>({id,geometry:{coordinates:[0.1,51.5]},properties:{transformer_count:1}});
  const features=[site('A'),site('B')];
  const requests=[],events=new Map();
  let zoom=7,visible=true,closed=0;
  const makePopup=id=>{
    const node=makeElement();
    node.textContent='Secondary substation (transformer register)';
    const heading={textContent:id};
    node.querySelector=selector=>selector==='b'?heading:node.children.find(child=>child.dataset.ukpnDetail==='1');
    return node;
  };
  let popup=makePopup('A');
  const map={
    getContainer:()=>({querySelector:()=>popup}),
    getZoom:()=>zoom,getLayer:()=>({}),
    getLayoutProperty:()=>visible?'visible':'none',
    getSource:()=>({serialize:()=>({data:{features}})}),
    on:(event,fn)=>events.set(event,fn)
  };
  const W={
    document:{createElement:makeElement},__GRIDATLAS_V9_MAP__:map,
    __GRIDATLAS_MODULES__:{ukpnSecondary:{detailsFor(id){return new Promise(resolve=>requests.push({id,resolve}));}}},
    setTimeout:fn=>fn(),_closePopupKeepShape:()=>{closed++;}
  };
  vm.runInNewContext(card,{window:W});
  const click=()=>events.get('click')();
  const changeZoom=value=>{zoom=value;events.get('zoomend')();};
  const getCard=()=>popup.querySelector('[data-ukpn-detail]');
  const flatten=node=>[node.textContent,...node.children.flatMap(flatten)].join(' ');
  click();
  assert.equal(getCard().dataset.site,'A');
  assert.equal(getCard().dataset.level,'summary');
  assert.equal(requests.length,0);
  changeZoom(15.99);assert.equal(requests.length,0);
  changeZoom(16);assert.equal(requests.length,1);
  const old=getCard(), oldDetails=old.children.find(child=>child.textContent.includes('Loading transformer'));
  old.isConnected=false;
  popup=makePopup('B');click();
  assert.deepEqual(requests.map(r=>r.id),['A','B']);
  requests[0].resolve([['A-TRANSFORMER',11,0.4,500,400]]);
  await Promise.resolve();await Promise.resolve();
  assert.doesNotMatch(flatten(oldDetails),/A-TRANSFORMER/);
  assert.doesNotMatch(flatten(getCard()),/A-TRANSFORMER/);
  requests[1].resolve([['B-TRANSFORMER',11,0.4,500,400]]);
  await Promise.resolve();await Promise.resolve();
  assert.match(flatten(getCard()),/B-TRANSFORMER/);
  changeZoom(15);assert.equal(getCard().dataset.level,'summary');
  assert.doesNotMatch(flatten(getCard()),/B-TRANSFORMER/);
  assert.equal(requests.length,2);
  visible=false;click();assert.equal(closed,1);
});

Regional Preview

A JavaScript module in the secondary folder of GridAtlas that reads substations, using SHA-256. It is built from the sha step (`sha`) and the pin step (`pin`).

storagegridatlas / tools/secondary/regional-preview.mjs · lines 1–45 of 45 · Entry point

What it does
It loads substations. Defines sha, pin. Uses libraries node:fs, node:path, node:assert/strict, node:crypto. Side effects: reads or writes files.
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.
Inputs & outputs
In: JSON file current.json. Out: JSON file current.json.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Build a disposable, hashed browser candidate using the existing immutable v2 loader. It reads `/current.json` and writes `/current.json`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/secondary · JavaScript module
Uses
Regional Interface (import), node:fs, node:path, node:assert/strict, node:crypto
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
sha, pin
Defines here
sha, pin
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/secondary/regional-preview.mjs:1-45 · blob eaff7eabe0a1a1cd3332196f5e285d0285cb3109 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// Build a disposable, hashed browser candidate using the existing immutable v2 loader.
// No production or historical files are written. Not a release or promotion.
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {buildRegional} from './regional-interface.mjs';
const route='atlas/v/regional-interface-ci';
const predecessor='atlas/v/202612010912';
assert.ok(!fs.existsSync(route),'refusing to overwrite candidate');
const current=JSON.parse(fs.readFileSync(predecessor+'/current.json','utf8'));
assert.equal(current.composition_version,'v9.198');
const liveBefore=fs.readFileSync('atlas/current.json');
const generation=new Date().toISOString().replace(/[-:T]/g,'').slice(0,12);
const built=buildRegional();
fs.mkdirSync(route);
try {
  fs.copyFileSync(predecessor+'/index.html',route+'/index.html',fs.constants.COPYFILE_EXCL);
  const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
  const pin=(entry,filename,source)=>{
    const bytes=Buffer.from(source,'utf8');
    fs.writeFileSync(route+'/'+filename,bytes,{flag:'wx'});
    const next={...entry,path:'./'+filename,sha256:sha(bytes),bytes:bytes.length,generation};
    // Do not misrepresent the predecessor's parts ledger or proof as current.
    for(const key of ['assembled_from','contract','proof','byte_budget'])delete next[key];
    return next;
  };
  const native=current.cartridges.find(c=>c.id==='substation-intelligence');
  const secondary=current.cartridges.find(c=>c.id==='ukpn-secondary-substations');
  assert.ok(native && secondary && !current.cartridge_order.includes('ukpn-secondary-card'));
  current.cartridges=current.cartridges.map(c=>c===native?pin(c,'engine.js',built.engine):c===secondary?pin(c,'data.js',built.data):c);
  current.cartridges.push(pin({id:'ukpn-secondary-card',type:'script',slot:'after-cartridge',after:secondary.id},'card.js',built.card));
  current.cartridge_order.push('ukpn-secondary-card');
  current.previous_generation=current.generation;
  current.generation=generation;
  current.composition_id=generation+'-regional-interface-ci';
  current.composition_version='regional-interface-ci';
  delete current.composition_manifest;
  for(const c of current.cartridges){
    assert.equal(sha(fs.readFileSync(path.resolve(route,c.path))),c.sha256,c.id);
  }
  fs.writeFileSync(route+'/current.json',JSON.stringify(current,null,1)+'\n',{flag:'wx'});
  assert.deepEqual(fs.readFileSync('atlas/current.json'),liveBefore);
  console.log('REGIONAL CI COMPOSITION '+JSON.stringify({generation,route,components:current.cartridges.map(({id,sha256,bytes})=>({id,sha256,bytes})),productionUnchanged:true}));
} catch(error){fs.rmSync(route,{recursive:true,force:true});throw error;}

Viewport Query

A JavaScript module in the secondary folder of GridAtlas that reads grid UK Power Networks (UKPN) secondary.

storagegridatlas / tools/secondary/viewport-query.mjs · lines 1–30 of 30 · pattern viewportBounds (shared by 2 files)

What it does
It loads grid UKPN secondary. Defines viewportBounds, outward, viewportSQL, includesPoint. Side effects: uses storage (browser storage, DuckDB or Parquet).
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.
Inputs & outputs
In: Parquet file grid_ukpn_secondary.parquet.
Downstream impact
Used directly by 1 file: Viewport Query Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It is built from the viewport bounds helper (`viewportBounds`), the outward step (`outward`) and the viewport SQL helper (`viewportSQL`). G203-05: bounded query candidate for the existing pinned map Parquet. It reads `grid_ukpn_secondary.parquet`.
Why it matters
Checked by Viewport Query Test.
Application
gridatlas · tools/secondary · JavaScript module
Uses
none found
Used by
imported by Viewport Query Test (import)
Produces
viewportBounds, viewportSQL, includesPoint
Defines here
viewportBounds, outward, viewportSQL, includesPoint
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/secondary/viewport-query.mjs:1-30 · blob f3118b8f37df0b9db4e8d1f36cb83f0e93155f40 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// G203-05: bounded query candidate for the existing pinned map parquet.
// Not wired to native hydration: the native source/cache lifecycle must be validated first.
// Numeric-only validated predicates; no invented coordinates, LIMIT or source replacement.
export function viewportBounds(west,south,east,north,padding=0.15) {
  if (![west,south,east,north,padding].every(Number.isFinite) || south>north || south < -90 || north > 90 || padding<0 || padding>1) throw new RangeError('Invalid viewport');
  let width=east-west;
  if(width<0) width=((width%360)+360)%360;
  const latitudePad=(north-south)*padding;
  const lo=Math.max(-90,south-latitudePad), hi=Math.min(90,north+latitudePad);
  const padded=width*(1+2*padding);
  if(padded>=360) return {south:lo,north:hi,intervals:[[-180,180]]};
  const rawStart=west-width*padding;
  const start=rawStart>=-180&&rawStart<180?rawStart:(((rawStart+180)%360)+360)%360-180;
  const end=start+padded;
  // Round outward to avoid excluding boundary points through longitude wrapping.
  const outward=(a,z)=>[Math.max(-180,Math.floor((a-1e-12)*1e9)/1e9),Math.min(180,Math.ceil((z+1e-12)*1e9)/1e9)];
  return {south:lo,north:hi,intervals:end<=180?[outward(start,end)]:[outward(start,180),outward(-180,end-360)]};
}
export function viewportSQL(west,south,east,north,padding=0.15) {
  const b=viewportBounds(west,south,east,north,padding);
  const lng=b.intervals.map(([a,z])=>`(lon BETWEEN ${a} AND ${z})`).join(' OR ');
  return `WITH points AS (SELECT feature_index, feature_id, geometry_json, properties_json,
  TRY_CAST(json_extract(geometry_json,'$.coordinates[0]') AS DOUBLE) AS lon,
  TRY_CAST(json_extract(geometry_json,'$.coordinates[1]') AS DOUBLE) AS lat
  FROM read_parquet('grid_ukpn_secondary.parquet'))
SELECT feature_id, geometry_json, properties_json FROM points
WHERE lat BETWEEN ${b.south} AND ${b.north} AND (${lng})
ORDER BY feature_index`;
}
export function includesPoint(b,lon,lat) { return lat>=b.south && lat<=b.north && b.intervals.some(([a,z])=>lon>=a && lon<=z); }

Viewport Query Test

A test in the secondary folder of GridAtlas that checks Viewport Query.

testgridatlas / tools/secondary/viewport-query.test.mjs · lines 1–8 of 8 · Entry point

What it does
It tests its inputs. Uses libraries node:assert/strict. Side effects: uses storage (browser storage, DuckDB or Parquet).
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.
Inputs & outputs
In: Parquet file grid_ukpn_secondary.parquet.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/secondary · test
Uses
Viewport Query (import), node:assert/strict
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
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 tools/secondary/viewport-query.test.mjs:1-8 · blob 51c5c04cb0b132bcf2e64192ba0b4f11b88cd7b6 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import assert from 'node:assert/strict';
import {viewportBounds,viewportSQL,includesPoint} from './viewport-query.mjs';
const cases=[[-0.4,51.4,0.1,51.7,0,-0.1,51.5,true],[-0.4,51.4,0.1,51.7,0,0.2,51.5,false],[-0.4,51.4,0.1,51.7,0,-0.4,51.4,true],[-0.4,51.4,0.1,51.7,0,0.1,51.7,true],[-0.4,51.4,0.1,51.7,0.2,0.15,51.5,true],[170,-10,-170,10,0,179,0,true],[170,-10,-170,10,0,-179,0,true],[170,-10,-170,10,0,0,0,false],[359,50,361,53,0,-0.5,51,true],[-180,-90,180,90,0,0,51,true],[-180,-90,180,90,1,179,89,true],[-1,89,1,9  … [line shortened here: 474 characters; full line on GitHub]
for(const [w,s,e,n,p,x,y,expected] of cases) assert.equal(includesPoint(viewportBounds(w,s,e,n,p),x,y),expected);
for(const args of [[NaN,50,1,51],[0,51,1,50],[0,-91,1,50],[0,0,1,91],[0,0,1,2,-1],[0,0,1,2,2]]) assert.throws(()=>viewportSQL(...args),RangeError);
const sql=viewportSQL(-1,50,1,52,0);
assert.ok(sql.includes('ORDER BY feature_index')&&!sql.includes(' LIMIT ')&&sql.includes('TRY_CAST')&&sql.includes('grid_ukpn_secondary.parquet'));
console.log('21 synthetic viewport/query contract checks passed');

Browser Test

A test in the train folder of GridAtlas covering substations and postcodes, using SHA-256.

testgridatlas / tools/train/browser.test.mjs · lines 1–99 of 99 · pattern state (shared by 17 files)

What it does
It tests substations and postcodes. Defines 9 functions or classes, including sampleRenderedTrainCursor, waitForPaintedCursorProgress, runTrainUiAcceptance, state, clear. Uses libraries node:assert/strict. 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: substations, postcodes.
Downstream impact
Used directly by 2 files: Painted Observation Test (gridatlas); Browser Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It runs train ui acceptance (`runTrainUiAcceptance`) and is built from the sample rendered train cursor helper (`sampleRenderedTrainCursor`) and the state step (`state`). Native new-UI acceptance helper. No route graph/provider interception or scripted selection.
Why it matters
Checked by 2 tests, including Painted Observation Test.
Application
gridatlas · tools/train · test
Uses
node:assert/strict
Used by
imported by Painted Observation Test (import), run by Browser Test (script call)
Produces
sampleRenderedTrainCursor, waitForPaintedCursorProgress, runTrainUiAcceptance
Defines here
sampleRenderedTrainCursor, waitForPaintedCursorProgress, runTrainUiAcceptance, state, clear, find, choose, cursor, ownedCounts
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/train/browser.test.mjs:1-99 · blob 88bfca59a4549a5d298371db2591815e85950440 · 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
/** Native new-UI acceptance helper. No route graph/provider interception or scripted selection. */
import assert from 'node:assert/strict';
// Read painted feature geometry, not the newer serialized source point or its hit halo.
export function sampleRenderedTrainCursor(){
 const m=window.__GRIDATLAS_V9_MAP__,ride=window.__GRIDATLAS_MODULES__.gridVicinity.snapshot().train.ride,r=m.getContainer().getBoundingClientRect(),center=m.getCenter(),id='gridatlas-train-cursor';
 const rendered=(m.getLayer(id)?m.queryRenderedFeatures(undefined,{layers:[id]}):[]).filter(f=>f.geometry?.type==='Point').map(f=>{const at=f.geometry.coordinates.slice(0,2),p=m.project(at),screen=[r.left+p.x,r.top+p.y],hit=document.elementFromPoint(...screen);return{at,screen,uncovered:screen[0]>0&&screen[1]>0&&screen[0]<innerWidth&&screen[1]<innerHeight&&hit?.tagName==='CANVAS',hit:hit?.tagName|  … [line shortened here: 410 characters; full line on GitHub]
 return{timestamp:performance.now(),visibility:document.visibilityState,ride,rendered,serialized:m.getSource(id)?.serialize().data.features[0]?.geometry.coordinates||null,camera:[center.lng,center.lat,m.getZoom(),m.getBearing(),m.getPitch()],viewport:{width:innerWidth,height:innerHeight,canvas:[r.left,r.top,r.width,r.height]},sourceLoaded:m.isSourceLoaded?.(id)??null,styleLoaded:m.isStyleLoaded?.(  … [line shortened here: 409 characters; full line on GitHub]
}
export async function waitForPaintedCursorProgress({page,diagnostics,timeoutMs=15000,intervalMs=100,minimumPixels=2,now=Date.now}){
 const start=now(),samples=[];let baseline=null;
 diagnostics.paintObservation={minimumPixels,timeoutMs,samples};
 while(now()-start<timeoutMs){
  const sample=await page.evaluate(sampleRenderedTrainCursor);if(samples.length<200)samples.push(sample);
  const point=sample.rendered.find(p=>p.uncovered),valid=point&&sample.visibility==='visible'&&sample.ride.playing===true&&sample.ride.cameraFollow===false;
  if(valid){
   const value={...point,timestamp:sample.timestamp,fraction:sample.ride.fraction,camera:sample.camera,viewport:sample.viewport};
   if(!baseline){baseline=value;diagnostics.paintObservation.baseline=value;}
   else{
    const fixed=sample.camera.every((n,i)=>Math.abs(n-baseline.camera[i])<1e-7)&&sample.viewport.canvas.every((n,i)=>Math.abs(n-baseline.viewport.canvas[i])<0.5);
    assert.ok(fixed,'Follow is OFF: rendered cursor comparison requires the same fitted camera and viewport');
    const pixels=Math.hypot(value.screen[0]-baseline.screen[0],value.screen[1]-baseline.screen[1]);
    if(pixels>=minimumPixels&&value.fraction>baseline.fraction&&value.at.some((n,i)=>n!==baseline.at[i])){diagnostics.paintObservation.accepted={...value,pixels};return{firstRendered:baseline,secondRendered:value,pixels};}
   }
  }
  await page.waitForTimeout(intervalMs);
 }
 assert.fail('No two actual painted, uncovered cursor positions advanced at least '+minimumPixels+' CSS pixels with active Play and advancing fraction; diagnostic samples preserved.');
}

export async function runTrainUiAcceptance({page,panel,snapshot,visibleTap,output,pageErrors=[],diagnostics={}}) {
 const train=panel.locator('.train-panel'),query=train.locator('#gridatlas-train-query'),role=train.getByRole('combobox',{name:'Use search choice as',exact:true}),results=train.locator('.train-search-results');
 const readings={scope:'LOCAL_NATIVE_UI_REAL_STATION_SOURCE',caps:[],places:[],motion:{}};
 const state=async()=>(await snapshot()).train;
 const clear=async()=>{await visibleTap(train.getByRole('button',{name:'Clear selected stops',exact:true}));assert.equal((await state()).itinerary.selectedCount,0);};
 const find=async(id)=>{await query.fill(id);await visibleTap(train.getByRole('button',{name:'Find stations',exact:true}));assert.ok(await results.getByRole('button').count());};
 const choose=async(id,position)=>{await role.selectOption(position);await find(id);await visibleTap(results.getByRole('button').first());};
 const source=await page.evaluate(()=>{const ns=window.__GRIDATLAS_MODULES__,g=ns.geodesy,features=window.__GRIDATLAS_V9_MAP__.getSource('src-subs').serialize().data.features;return features.filter(f=>f.id&&f.properties?.name&&Array.from(g.voltagesKv(f.properties)).includes(33)).map(f=>({id:String(f.id),name:f.properties.name,at:g.representativePoint(f.geometry),kv:Array.from(g.voltagesKv(f.proper  … [line shortened here: 588 characters; full line on GitHub]
 assert.equal(source.length,2);readings.canonicalStations=source;assert.equal((await state()).index.sourceRecords,5800);assert.equal((await state()).index.indexedRecords,5800);assert.equal((await state()).index.datasetPin.sha256,'87976435766a58ddf19c99540b58cd7f18a224148af42ba55075d8851f9e6251');
 await clear();await query.fill('Kearsley');await visibleTap(train.getByRole('button',{name:'Find stations',exact:true}));assert.match(await results.innerText(),/grid_substations:5799/);await query.fill('qa-no-such-station-uniquely-missing');await visibleTap(train.getByRole('button',{name:'Find stations',exact:true}));assert.equal(await results.getByRole('button').count(),0);await visibleTap(train  … [line shortened here: 452 characters; full line on GitHub]
 await choose(source[0].id,'start');await choose(source[1].id,'finish');
 let current=await state();assert.deepEqual(current.itinerary.stops.map(s=>s.stationId),source.map(s=>s.id));assert.deepEqual(current.itinerary.stops.map(s=>s.at),source.map(s=>s.at));
 await visibleTap(train.locator('.train-stops > li').first().getByRole('button',{name:/^Move down /}));assert.deepEqual((await state()).itinerary.stops.map(s=>s.stationId),source.map(s=>s.id).reverse());await visibleTap(train.locator('.train-stops > li').last().getByRole('button',{name:/^Move up /}));assert.deepEqual((await state()).itinerary.stops.map(s=>s.stationId),source.map(s=>s.id));
 for(const select of await train.locator('.train-stops select').all())await select.selectOption('33');
 await visibleTap(train.getByRole('button',{name:'Draw itinerary',exact:true}));current=await state();assert.equal(current.plan.simulated,false);assert.ok(current.plan.legs.some(l=>l.evidence==='MISSING'),'missing documented joins remain missing before opt-in');assert.equal(current.plan.playable,false);
 const fallback=train.getByRole('checkbox',{name:/Allow my SIMULATED straight-line legs/});await visibleTap(fallback.locator('..'));assert.equal(await fallback.isChecked(),true);
 await visibleTap(train.getByRole('button',{name:'Draw itinerary',exact:true}));await visibleTap(train.getByRole('button',{name:'Draw itinerary',exact:true}));current=await state();assert.equal(current.plan.playable,true);assert.equal(current.plan.simulated,true);assert.ok(current.plan.legs.every(leg=>leg.electricalFlow==='UNKNOWN'));
 await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-train-cursor')?.serialize().data.features.length===1,null,{timeout:15000});
 const cursor=()=>page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-train-cursor')?.serialize().data.features[0]?.geometry.coordinates);
 await visibleTap(train.getByRole('button',{name:'Fit itinerary on map',exact:true}));
 const mapControls=page.getByRole('region',{name:'Journey map controls',exact:true});await visibleTap(mapControls.getByRole('button',{name:'Edit journey',exact:true}));
 const before=await cursor();const speed=train.getByRole('slider',{name:'Seconds per leg',exact:true});await speed.focus();await page.keyboard.press('End');const actualSpeed=Number(await speed.inputValue());assert.equal(actualSpeed,20,'native range End selects 20 seconds per leg');diagnostics.actualSpeedSeconds=actualSpeed;
 await visibleTap(train.getByRole('button',{name:'Play',exact:true}));const compact=page.getByRole('region',{name:'Journey map controls',exact:true});assert.equal(await compact.isVisible(),true);
 const {firstRendered,secondRendered}=await waitForPaintedCursorProgress({page,diagnostics});
 const moving=await cursor();await page.screenshot({path:output+'/train-native-playing.png'});await visibleTap(compact.getByRole('button',{name:'Pause journey',exact:true}));assert.equal((await state()).ride.playing,false);const paused=await cursor();await page.waitForTimeout(150);assert.deepEqual(await cursor(),paused);
 await visibleTap(compact.getByRole('button',{name:'Next journey stop',exact:true}));assert.equal((await state()).ride.stopIndex,1);await visibleTap(compact.getByRole('button',{name:'Edit journey',exact:true}));readings.motion={actualSpeed,paintObservation:diagnostics.paintObservation,firstRendered,secondRendered,before,moving,paused,afterStep:await cursor(),ride:(await state()).ride};
 await page.screenshot({path:output+'/train-native-drawn.png'});
 // Close an active ride through the focused compact Escape control, spanning deferred work.
 const visitsBeforeClose=(await state()).itinerary.stops.map(stop=>stop.stopId);await visibleTap(train.getByRole('button',{name:'Play',exact:true}));assert.equal((await state()).ride.playing,true);await page.keyboard.press('Escape');assert.equal((await snapshot()).opened,false);
 const ownedCounts=()=>page.evaluate(()=>Object.fromEntries(['routes','stops','cursor'].map(suffix=>[suffix,window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-train-'+suffix)?.serialize().data.features.length||0])));
 assert.deepEqual(await ownedCounts(),{routes:0,stops:0,cursor:0});assert.equal((await state()).plan,null);assert.equal((await state()).ride.playing,false);await page.waitForTimeout(1200);assert.deepEqual(await ownedCounts(),{routes:0,stops:0,cursor:0});assert.deepEqual(pageErrors,[]);
 await visibleTap(page.locator('#gridatlas-menu-bar-title-4'));await visibleTap(page.locator('#gridatlas-menu-bar-panel-4').getByRole('button',{name:'Great Grid Journeys',exact:true}));assert.deepEqual((await state()).itinerary.stops.map(stop=>stop.stopId),visitsBeforeClose);assert.equal((await state()).plan,null);assert.deepEqual(await ownedCounts(),{routes:0,stops:0,cursor:0});readings.close={ob  … [line shortened here: 500 characters; full line on GitHub]
 // Place lookup uses the existing live provider; failure is retained, never replaced by a fixture.
 await clear();await role.selectOption('start');const typed='SW1A 1AA';await query.fill(typed);await visibleTap(train.getByRole('button',{name:'Find place / postcode',exact:true}));
 await page.waitForFunction(()=>{const e=document.querySelector('.train-status');return e&&!e.textContent.includes('Looking up');},null,{timeout:90000});
 const places=results.getByRole('button',{name:'Choose stations near this place',exact:true});assert.ok(await places.count(),'existing provider must resolve the typed postcode for positive binding coverage');const selectedProviderCaption=await results.locator('li').first().innerText();await visibleTap(places.first());await visibleTap(results.getByRole('button').first());current=await state();const  … [line shortened here: 863 characters; full line on GitHub]
 // Both caps are selected visit limits; repeat visits are intentional and remain separate.
 await clear();await visibleTap(train.getByRole('button',{name:/^Journey .*10 stops$/}));await role.selectOption('waypoint');await find(source[0].id);
 for(let n=0;n<10;n++)await visibleTap(results.getByRole('button').first());const atTen=(await state()).itinerary;await visibleTap(results.getByRole('button').first());assert.deepEqual((await state()).itinerary,atTen);readings.caps.push({mode:'journey',count:atTen.selectedCount,refused:11});
 await visibleTap(train.getByRole('button',{name:/^Vicinity .*90 stops$/}));for(let n=10;n<90;n++)await visibleTap(results.getByRole('button').first());const atNinety=(await state()).itinerary;await visibleTap(results.getByRole('button').first());assert.deepEqual((await state()).itinerary,atNinety);assert.equal(atNinety.selectedCount,90);readings.caps.push({mode:'vicinity',count:90,refused:91});
 await visibleTap(train.getByRole('button',{name:/^Journey .*10 stops$/}));assert.deepEqual((await state()).itinerary,atNinety,'mode downgrade never truncates');
 await clear();
 // Pin a real user-chosen map point; only the separate session proposed store changes.
 await role.selectOption('start');await visibleTap(train.locator('.train-proposed > summary'));await train.getByRole('textbox',{name:'Proposed customer substation label',exact:true}).fill('QA customer screening');await train.getByRole('combobox',{name:'Proposed customer substation voltage',exact:true}).selectOption('11');
 if(!(await fallback.isChecked()))await visibleTap(fallback.locator('..'));
 await visibleTap(train.getByRole('button',{name:'Pin proposed FEED concept',exact:true}));assert.equal((await state()).proposedPicking,true);assert.equal(await panel.isVisible(),false,'pin mode exposes map touch surface');
 const canvas=page.locator('canvas.maplibregl-canvas');const bounds=await canvas.boundingBox();await page.touchscreen.tap(bounds.x+bounds.width/2,bounds.y+bounds.height/2);await page.waitForFunction(()=>window.__GRIDATLAS_MODULES__.gridVicinity.snapshot().train.proposals.count===1);
 await page.waitForFunction(()=>{const m=window.__GRIDATLAS_V9_MAP__,id='gridatlas-train-proposed-point';return m.getLayer(id)&&m.queryRenderedFeatures(undefined,{layers:[id]}).some(f=>f.properties.evidence==='SESSION_ONLY_USER_PROPOSED'&&f.properties.role==='customer_substation');});
 const feed=await page.evaluate(()=>{const m=window.__GRIDATLAS_V9_MAP__,e=document.querySelector('.train-proposed-map-label'),r=e?.getBoundingClientRect(),style=e?getComputedStyle(e):null;return{colour:m.getPaintProperty('gridatlas-train-proposed-point','circle-color'),marker:e?{text:e.textContent,colour:style.color,borderStyle:style.borderTopStyle,visible:style.display!=='none'&&style.visibility  … [line shortened here: 639 characters; full line on GitHub]
 assert.equal(String(feed.colour).toLowerCase(),'#e0b050');assert.ok(feed.marker?.visible,'the proposed FEED label is visibly on the map');assert.match(feed.marker.text,/Proposed.*FEED/);assert.equal(feed.marker.borderStyle,'dashed');assert.equal(feed.marker.colour,'rgb(224, 176, 80)');assert.equal(feed.source.length,1);assert.ok(feed.source.every(p=>p.evidence==='SESSION_ONLY_USER_PROPOSED'&&p.ro  … [line shortened here: 453 characters; full line on GitHub]
await page.screenshot({path:output+'/train-proposed-session-map.png'});
 await visibleTap(compact.getByRole('button',{name:'Edit journey',exact:true}));current=await state();assert.equal(current.proposals.count,1);const proposal=current.proposals.stations[0];assert.match(proposal.id,/^scenario:/);assert.deepEqual(proposal.kv,[11]);assert.equal(proposal.source,'SESSION_ONLY_USER_PROPOSED');assert.equal(current.itinerary.stops[0].stationId,proposal.id);assert.equal(curr  … [line shortened here: 430 characters; full line on GitHub]
 const proposalEpochBeforeEdit=current.itinerary.planEpoch;
 const proposedList=train.getByRole('list',{name:'Session proposed substations',exact:true});await proposedList.getByRole('combobox').selectOption('33');await visibleTap(proposedList.getByRole('button',{name:'Apply proposed label / voltage',exact:true}));current=await state();assert.deepEqual(current.proposals.stations[0].kv,[33]);assert.ok(current.itinerary.planEpoch>proposalEpochBeforeEdit,'the   … [line shortened here: 452 characters; full line on GitHub]
 await visibleTap(fallback.locator('..'));assert.equal(await fallback.isChecked(),true,'documented-only refuses active proposed stops');
 await visibleTap(proposedList.getByRole('button',{name:'Remove proposed pin',exact:true}));current=await state();assert.equal(current.proposals.count,0);assert.equal(current.itinerary.valid,false);assert.equal(current.itinerary.selectedCount,1);await visibleTap(train.getByRole('button',{name:'Draw itinerary',exact:true}));assert.equal((await state()).plan,null,'a deleted proposed station cannot b  … [line shortened here: 777 characters; full line on GitHub]
 await clear();await visibleTap(train.getByRole('button',{name:/^Vicinity .*90 stops$/}));

 // Reduced motion uses the real public controller lifecycle and the same unchanged source inventory.
 const contextBefore=await snapshot();await page.emulateMedia({reducedMotion:'reduce'});
 await page.evaluate(options=>{const module=window.__GRIDATLAS_MODULES__.gridVicinity;module.destroy();module.mount().open(options);},{origin:contextBefore.origin,radiusKm:contextBefore.radiusKm,mode:'journey'});
 await page.waitForFunction(()=>window.__GRIDATLAS_MODULES__.gridVicinity.snapshot().train?.index?.indexedRecords===5800);
 await choose(source[0].id,'start');await choose(source[1].id,'finish');for(const select of await train.locator('.train-stops select').all())await select.selectOption('33');
 const reducedFallback=train.getByRole('checkbox',{name:/Allow my SIMULATED straight-line legs/});await visibleTap(reducedFallback.locator('..'));await visibleTap(train.getByRole('button',{name:'Draw itinerary',exact:true}));await visibleTap(train.getByRole('button',{name:'Play',exact:true}));
 current=await state();assert.equal(current.ride.reducedMotion,true);assert.equal(current.ride.playing,false);const staticAt=await cursor();await page.waitForTimeout(250);assert.deepEqual(await cursor(),staticAt);readings.reducedMotion={ride:current.ride,staticAt};
 await visibleTap(compact.getByRole('button',{name:'Edit journey',exact:true}));await clear();await visibleTap(train.getByRole('button',{name:/^Vicinity .*90 stops$/}));
 const sourceBands=panel.getByRole('group',{name:'Source voltage tags',exact:true});for(const box of await sourceBands.getByRole('checkbox').all()){const wanted=contextBefore.selectedBands.includes(await box.getAttribute('value'));if(await box.isChecked()!==wanted)await visibleTap(box.locator('..'));}
 const contextAfter=await snapshot();assert.deepEqual(contextAfter.origin,contextBefore.origin);assert.equal(contextAfter.radiusKm,contextBefore.radiusKm);assert.equal(contextAfter.loadedRecords,5800);readings.contextPreserved={origin:contextAfter.origin,radiusKm:contextAfter.radiusKm,loadedRecords:contextAfter.loadedRecords};await page.emulateMedia({reducedMotion:'no-preference'});
 return readings;
}

Build

A JavaScript module in the gazetteer folder of GridAtlas that reads generations, using SHA-256. It builds gazetteer (`buildGazetteer`).

storagegridatlas / tools/train/gazetteer/build.mjs · lines 1–10 of 10 · Not reached from any entry point (candidate for review) · pattern buildGazetteer (shared by 2 files)

What it does
It loads generations. Defines buildGazetteer. Uses libraries node:fs. Side effects: reads or writes files.
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.
Inputs & outputs
In: JSON file generations.json; command-line arguments.
Downstream impact
Used directly by 2 files: Cut Grid Explorer (gridatlas); Grid Explorer Proof (gridatlas).
What it achieves
Successor-only public seam, derived from the exact currently composed gazetteer.
Why it matters
Run by Cut Grid Explorer and Grid Explorer Proof.
Application
gridatlas · tools/train/gazetteer · JavaScript module
Uses
node:fs
Used by
run by Cut Grid Explorer (script call), run by Grid Explorer Proof (script call)
Produces
buildGazetteer
Defines here
buildGazetteer
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/train/gazetteer/build.mjs:1-10 · blob 0e079e53723cc1b054e01477e030cb6325b95c80 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/** Successor-only public seam, derived from the exact currently composed gazetteer. */
import fs from 'node:fs';import path from 'node:path';import assert from 'node:assert/strict';import {createHash} from 'node:crypto';import {fileURLToPath} from 'node:url';
const ROOT=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../../..');
export function buildGazetteer(generation,root=ROOT) {
 const registry=JSON.parse(fs.readFileSync(path.join(root,'tools/train/gazetteer/generations.json'))),entry=registry.generations[generation];assert.ok(entry,'Unknown gazetteer successor generation '+generation);
 const bytes=fs.readFileSync(path.join(root,entry.base.path)),hash=b=>createHash('sha256').update(b).digest('hex');assert.equal(bytes.length,entry.base.bytes,'Gazetteer base length drift');assert.equal(hash(bytes),entry.base.sha256,'Gazetteer base pin drift');let body=bytes.toString('utf8');
 for(const [i,edit]of JSON.parse(fs.readFileSync(path.join(root,entry.edits))).entries()){assert.ok(typeof edit.before==='string'&&edit.before.length&&typeof edit.after==='string');const at=body.indexOf(edit.before);assert.ok(at>=0,'Gazetteer edit missing '+i);assert.equal(body.indexOf(edit.before,at+1),-1,'Gazetteer edit ambiguous '+i);body=body.slice(0,at)+edit.after+body.slice(at+edit.before.le  … [line shortened here: 407 characters; full line on GitHub]
 const built=Buffer.from(body);assert.equal(built.length,entry.output_bytes,'Gazetteer output length drift');assert.equal(hash(built),entry.output_sha256,'Gazetteer output pin drift');return built;
}
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){const arg=k=>process.argv[process.argv.indexOf(k)+1];assert.ok(process.argv.includes('--gen')&&process.argv.includes('--out'),'Use --gen G --out NEW_FILE');const bytes=buildGazetteer(arg('--gen'));fs.writeFileSync(arg('--out'),bytes,{flag:'wx'});console.log(JSON.stringify({bytes:bytes.length,sha256:createHash('sha2  … [line shortened here: 437 characters; full line on GitHub]

Painted Observation Test

A test in the train folder of GridAtlas that checks Browser Test.

testgridatlas / tools/train/painted-observation.test.mjs · lines 1–8 of 8 · Entry point · pattern sample (shared by 18 files)

What it does
It tests its inputs. Defines sample, fake.
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.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Defines `sample` and `fake`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/train · test
Uses
Browser Test (import)
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
sample, fake
Defines here
sample, fake
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/train/painted-observation.test.mjs:1-8 · blob 08d33b1801ae083a1d8cd1f3cb401b7a1c301057 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import test from 'node:test';import assert from 'node:assert/strict';import vm from 'node:vm';
import {sampleRenderedTrainCursor,waitForPaintedCursorProgress} from './browser.test.mjs';
const sample=(x,fraction=.1,playing=true)=>({timestamp:x,visibility:'visible',ride:{fraction,playing,cameraFollow:false},rendered:[{at:[x,51],screen:[x,50],uncovered:true}],serialized:[99,88],camera:[0,51,10,0,0],viewport:{canvas:[0,0,400,800]}});
function fake(samples){let time=0,index=0;return{now:()=>time,page:{evaluate:async()=>structuredClone(samples[Math.min(index++,samples.length-1)]),waitForTimeout:async ms=>{time+=ms;}}};}
test('sampler projects actual rendered feature geometry separately from newer serialized source',()=>{const c={window:{__GRIDATLAS_MODULES__:{gridVicinity:{snapshot:()=>({train:{ride:{playing:true,fraction:.2}}})}},__GRIDATLAS_V9_MAP__:{getContainer:()=>({getBoundingClientRect:()=>({left:5,top:6,width:400,height:800})}),getCenter:()=>({lng:0,lat:51}),getLayer:()=>({}),queryRenderedFeatures:()=>[{g  … [line shortened here: 1,062 characters; full line on GitHub]
test('repeated painted frame/source changes cannot pass; later2pxactualpaint plus fraction does',async()=>{const diagnostics={},f=fake([sample(10,.1),sample(10,.2),sample(12.5,.3)]);const r=await waitForPaintedCursorProgress({...f,diagnostics,timeoutMs:500});assert.equal(r.pixels,2.5);assert.equal(diagnostics.paintObservation.samples.length,3);});
test('stalledpaint fails with diagnostics despite advancing playback/source data',async()=>{const diagnostics={},f=fake([sample(10,.1),sample(10,.5)]);await assert.rejects(waitForPaintedCursorProgress({...f,diagnostics,timeoutMs:300}),/No two actual painted/);assert.equal(diagnostics.paintObservation.samples.length,3);assert.equal(diagnostics.paintObservation.accepted,undefined);});
test('finishedorpausedride and movingcamera cannot satisfy activefixed-camera paintedprogress',async()=>{const f=fake([sample(10,.1),sample(100,1,false)]);await assert.rejects(waitForPaintedCursorProgress({...f,diagnostics:{},timeoutMs:300}),/No two actual painted/);const changed=sample(13,.3);changed.camera[0]=1;await assert.rejects(waitForPaintedCursorProgress({...fake([sample(10),changed]),diag  … [line shortened here: 452 characters; full line on GitHub]

Route Plan Test

A test in the train folder of GridAtlas that checks Route Plan and Learning Networks. It is built from the bus network helper (`busNetwork`).

testgridatlas / tools/train/route-plan.test.mjs · lines 1–159 of 159 · Entry point · pattern network (shared by 67 files)

What it does
It tests transformers and the REPD register. Defines stop, network, busNetwork. Uses libraries node:test, node:assert/strict, node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: transformers, the REPD register.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Defines `stop`, `network` and `busNetwork`.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/train · test
Uses
Route Plan (import), Learning Networks (import), Scenario Stations (import), Itinerary (import), Electrical Distance (new URL import.meta.url), node:test, node:assert/strict, node:fs, node:vm
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
stop, network, busNetwork
Defines here
stop, network, busNetwork
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/train/route-plan.test.mjs:1-159 · blob 6c23c2bfe2e3ffe26677dec0e5af42ec9cb6d29f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import {buildRoutePlan} from './src/route-plan.mjs';
import {trainLearningFixture} from './fixtures/learning-networks.mjs';
import {createScenarioStationStore} from './src/scenario-stations.mjs';
import {createItinerary} from './src/itinerary.mjs';
const geodesy = {distanceKm: (a,b,c,d) => Math.hypot(c-a,d-b)*100};
const stop = (id,kv=400) => ({source:'SYNTHETIC_TEST',stationId:id,at:[id.charCodeAt(0)/100,51],kv});
const context = {window:{}}; vm.createContext(context);
vm.runInContext(fs.readFileSync(new URL('../../atlas/modules/202609012245-electrical-distance.js',import.meta.url),'utf8'),context);
const electricalDistance = context.window.__GRIDATLAS_MODULES__.electricalDistance;
function network(removeTransformer=false) {
  const nodes={A:400,AL:132,BL:132,B:400,C:132,D:400,E:400,F:400,Z:400};
  const rows=[['A','AL','transformer'],['AL','BL','circuit'],['BL','B','transformer'],
    ['A','D','circuit'],['D','E','circuit'],['E','F','circuit'],['F','B','circuit'],
    ...(!removeTransformer?[['B','C','transformer']]:[])].map(([node_1,node_2,kind],i)=>({node_1,node_2,kind,id:'row-'+i}));
  const graph={schema:'gridatlas.module.network-topology.graph.v1',has:n=>n in nodes,
    nodeVoltageKv:n=>nodes[n],nodeSiteCode:n=>n,nodesOfSite:n=>n in nodes?[n]:[],
    edgesAt:n=>rows.filter(r=>r.node_1===n||r.node_2===n).map(row=>({kind:row.kind,row,far:row.node_1===n?'node_2':'node_1'})),
    ratingsOf:()=>null,parametersOf:()=>null};
  return {index:{graph:()=>graph,site:code=>code in nodes?{code,name:code}:null},electricalDistance,
    stationBindings:Object.fromEntries(Object.keys(nodes).map(id=>[id,{stationId:id,siteCode:id,reviewed:true,source:'SYNTHETIC_REVIEW_LEDGER'}])),
    isReviewedEdge:()=>true,rows};
}
test('400-only filters every node before shortest-path search and chooses longer all-400 route',()=>{
 const n=network(), before=JSON.stringify(n.rows);
 const p=buildRoutePlan({synthetic:true,stops:[stop('A'),stop('B')],geodesy,network:n,rules:{allowedVoltages:[400],allowTransformers:true}});
 assert.equal(p.legs[0].topology.hops,4);assert.equal(p.legs[0].evidence,'TOPOLOGY_ONLY');
 assert.ok(p.legs[0].topology.path.every(h=>h.from_voltage_kv===400&&h.to_voltage_kv===400));assert.equal(JSON.stringify(n.rows),before);
});
test('mixed allowed voltages require the explicitly reviewed transformer; removing it refuses',()=>{
 const options={stops:[stop('B'),stop('C',132)],geodesy,rules:{allowedVoltages:[400,132],allowTransformers:true}};
 assert.equal(buildRoutePlan({synthetic:true,...options,network:network()}).legs[0].topology.path[0].kind,'transformer');
 assert.equal(buildRoutePlan({synthetic:true,...options,network:network(true),allowSimulated:true}).legs[0].evidence,'MISSING');
 assert.equal(buildRoutePlan({synthetic:true,...options,network:network(),rules:{...options.rules,allowTransformers:false}}).legs[0].evidence,'MISSING');
 const n=network();n.isReviewedEdge=e=>e.kind!=='transformer';
 assert.equal(buildRoutePlan({synthetic:true,...options,network:n}).legs[0].evidence,'MISSING');
});
test('disconnected same-voltage pair needs explicit hypothetical opt-in and never edits source graph',()=>{
 const n=network(), opts={stops:[stop('A'),stop('Z')],geodesy,network:n};
 assert.equal(buildRoutePlan({synthetic:true,...opts}).playable,false);const before=JSON.stringify(n.rows);
 const p=buildRoutePlan({synthetic:true,...opts,allowSimulated:true});assert.equal(p.legs[0].evidence,'SIMULATED');assert.match(p.legs[0].label,/not a cable/);assert.equal(JSON.stringify(n.rows),before);
});
test('registry site-name proximity is insufficient; unknown voltage cannot simulate a conversion',()=>{
 const n=network();n.stationBindings.A.reviewed=false;
 assert.equal(buildRoutePlan({synthetic:true,stops:[stop('A'),stop('B')],geodesy,network:n}).legs[0].evidence,'MISSING');
 assert.equal(buildRoutePlan({synthetic:true,stops:[stop('A'),stop('B',132)],geodesy,allowSimulated:true}).playable,false);
});
test('geometry needs exact circuit identity, direction and reviewed join; topology stays schematic otherwise',()=>{
 const n=network(),opts={stops:[stop('D'),stop('E')],geodesy,network:n,rules:{allowedVoltages:[400]}};
 n.geometryByCircuit={'row-4':{reviewed:true,source:'SYNTHETIC_GIS',circuitId:'wrong',fromNode:'D',toNode:'E',geometry:{type:'LineString',coordinates:[[0,51],[1,51]]}}};
 assert.equal(buildRoutePlan({synthetic:true,...opts}).legs[0].evidence,'TOPOLOGY_ONLY');n.geometryByCircuit['row-4'].circuitId='row-4';
 assert.equal(buildRoutePlan({synthetic:true,...opts}).legs[0].evidence,'GIS_REVIEWED');
});
test('ordered required visits/revisits and all original teaching presets use the same opt-in planner',()=>{
 for(const kind of ['local','express','branch']){const f=trainLearningFixture(kind);assert.equal(buildRoutePlan({synthetic:true,...f,geodesy}).playable,false);assert.equal(buildRoutePlan({synthetic:true,...f,geodesy,allowSimulated:true}).playable,true);}
 assert.throws(()=>buildRoutePlan({synthetic:true,stops:[stop('A'),stop('B')],geodesy,law:{allowedVoltageBands:['400'],mustVisitStationIds:['B','A'],fallback:'documented-only'}}),/declared order/);
});
test('production stations require canonical membership and points; selected voltage must be source-declared',()=>{
 const a={id:'source-a',stationId:'source-a',at:[-1,51],kv:[400,132]},b={id:'source-b',stationId:'source-b',at:[0,51],kv:[132]};
 const index={get:id=>id===a.id?a:id===b.id?b:null},opts={stops:[a,b],stationIndex:index,geodesy,allowSimulated:true};
 const p=buildRoutePlan(opts);assert.equal(p.legs[0].simulationVoltageKv,132);assert.equal(p.legs[0].accessStatus,'UNKNOWN');assert.equal(p.legs[0].surveyConstructability,'UNKNOWN');
 assert.equal(buildRoutePlan({...opts,stops:[{...a,selectedVoltageKv:400},b]}).playable,false);
 assert.throws(()=>buildRoutePlan({...opts,stops:[{...a,selectedVoltageKv:275},b]}),/canonical station/);
 assert.throws(()=>buildRoutePlan({...opts,stops:[{...a,at:[3,51]},b]}),/canonical station/);
 assert.throws(()=>buildRoutePlan({...opts,stops:[{...a,id:'repd:2470',stationId:'repd:2470'},b]}),/canonical station/);
});
test('crossed source-looking line geometry cannot establish topology or land rights without reviewed edges',()=>{
 const n=network();n.isReviewedEdge=()=>false;
 n.geometryByCircuit={crossing:{reviewed:true,source:'SOURCE_GIS',circuitId:'crossing',geometry:{type:'LineString',coordinates:[[0,50],[2,52]]}}};
 const p=buildRoutePlan({synthetic:true,stops:[stop('A'),stop('B')],geodesy,network:n});
 assert.equal(p.legs[0].evidence,'MISSING');assert.equal(p.legs[0].geometry,'UNKNOWN');assert.equal(p.legs[0].electricalTopology,'UNKNOWN');assert.equal(p.legs[0].accessStatus,'UNKNOWN');
});
test('two selected stops may traverse more than ninety source nodes; selected caps are not traversal caps',()=>{
 const rows=Array.from({length:100},(_,i)=>({node_1:'N'+i,node_2:'N'+(i+1),id:'c'+i}));
 const graph={schema:'gridatlas.module.network-topology.graph.v1',has:n=>/^N(?:\d|\d\d|100)$/.test(n),
  nodeVoltageKv:()=>400,nodeSiteCode:n=>n,nodesOfSite:n=>[n],ratingsOf:()=>null,parametersOf:()=>null,
  edgesAt:n=>rows.filter(r=>r.node_1===n||r.node_2===n).map(row=>({kind:'circuit',row,far:row.node_1===n?'node_2':'node_1'}))};
 const network={index:{graph:()=>graph,site:code=>({code,name:code})},electricalDistance,isReviewedEdge:()=>true,
  stationBindings:Object.fromEntries(['N0','N100'].map(id=>[id,{stationId:id,siteCode:id,reviewed:true,source:'SYNTHETIC_LEDGER'}]))};
 const p=buildRoutePlan({synthetic:true,stops:[stop('N0'),stop('N100')],network,geodesy});
 assert.equal(p.stops.length,2);assert.equal(p.legs[0].topology.hops,100);
});
test('whole-leg verification refuses a provider result that escapes the eligible voltage view',()=>{
 const n=network();n.electricalDistance={between:()=>({schema:'gridatlas.module.electrical-distance.v1',reached:true,from:{code:'A'},to:{code:'B'},path:[{from_node:'A',to_node:'AL',kind:'transformer'},{from_node:'AL',to_node:'B',kind:'circuit'}]})};
 const p=buildRoutePlan({synthetic:true,stops:[stop('A'),stop('B')],network:n,geodesy,rules:{allowedVoltages:[400],allowTransformers:true}});
 assert.equal(p.legs[0].evidence,'MISSING');assert.equal(p.playable,false);
});
function busNetwork(nodes,edges){
 const rows=edges.map(([node_1,node_2,kind='circuit'],i)=>({node_1,node_2,kind,id:'busrow-'+i}));
 const graph={schema:'gridatlas.module.network-topology.graph.v1',has:n=>!!nodes[n],nodeVoltageKv:n=>nodes[n].kv,
  nodeSiteCode:n=>nodes[n].site,nodesOfSite:site=>Object.keys(nodes).filter(n=>nodes[n].site===site).sort(),ratingsOf:()=>null,parametersOf:()=>null,
  edgesAt:n=>rows.filter(r=>r.node_1===n||r.node_2===n).map(row=>({kind:row.kind,row,far:row.node_1===n?'node_2':'node_1'}))};
 const sites=[...new Set(Object.values(nodes).map(n=>n.site))];
 return {index:{graph:()=>graph,site:code=>sites.includes(code)?{code,name:code}:null},electricalDistance,isReviewedEdge:()=>true,
  stationBindings:Object.fromEntries(sites.map(id=>[id,{stationId:id,siteCode:id,reviewed:true,source:'SYNTHETIC_BUS_LEDGER'}]))};
}
test('arrival bus survives a waypoint: unconnected B400/B132 cannot teleport, reviewed transformer permits it',()=>{
 const nodes={a:{site:'A',kv:400},b400:{site:'B',kv:400},b132:{site:'B',kv:132},c:{site:'C',kv:132}};
 const edges=[['a','b400'],['b132','c']],opts={synthetic:true,stops:[stop('A'),stop('B',[400,132]),stop('C',132)],geodesy,rules:{allowedVoltages:[400,132],allowTransformers:true}};
 const refused=buildRoutePlan({...opts,network:busNetwork(nodes,edges)});assert.equal(refused.playable,false);assert.equal(refused.legs[1].evidence,'MISSING');
 const accepted=buildRoutePlan({...opts,network:busNetwork(nodes,[...edges,['b400','b132','transformer']])});assert.equal(accepted.playable,true);
 assert.equal(accepted.legs[0].toBus,accepted.legs[1].fromBus);assert.ok(accepted.legs.some(l=>l.topology.path.some(h=>h.kind==='transformer')));
 const reordered=buildRoutePlan({...opts,stops:[stop('A'),stop('B',[132,400]),stop('C',132)],network:busNetwork(nodes,[...edges,['b400','b132','transformer']])});
 assert.deepEqual(reordered.legs.map(l=>l.topology.path),accepted.legs.map(l=>l.topology.path));
});
test('same-voltage distinct waypoint buses still require a documented edge',()=>{
 const n={a:{site:'A',kv:400},b1:{site:'B',kv:400},b2:{site:'B',kv:400},c:{site:'C',kv:400}};
 const opts={synthetic:true,stops:[stop('A'),stop('B'),stop('C')],geodesy};
 assert.equal(buildRoutePlan({...opts,network:busNetwork(n,[['a','b1'],['b2','c']])}).playable,false);
 assert.equal(buildRoutePlan({...opts,network:busNetwork(n,[['a','b1'],['b2','c'],['b1','b2']])}).playable,true);
});
test('whole itinerary keeps a longer reachable alternative bus instead of greedy dead-end arrival',()=>{
 const n={a:{site:'A',kv:400},dead:{site:'B',kv:400},x:{site:'X',kv:400},good:{site:'B',kv:400},c:{site:'C',kv:400}};
 const p=buildRoutePlan({synthetic:true,stops:[stop('A'),stop('B'),stop('C')],geodesy,
  network:busNetwork(n,[['a','dead'],['a','x'],['x','good'],['good','c']])});
 assert.equal(p.playable,true);assert.equal(p.legs[0].toBus,'good');assert.equal(p.legs[0].topology.hops,2);assert.equal(p.legs[1].fromBus,'good');
});
test('untouched null voltage law means all known bands, explicit empty means none',()=>{
 const opts={synthetic:true,stops:[stop('A'),stop('B')],geodesy,law:{allowedVoltageBands:null,mustVisitStationIds:[],fallback:'user-opted-hypothetical',allowTransformers:true}};
 assert.equal(buildRoutePlan(opts).playable,true);
 const none=buildRoutePlan({...opts,law:{...opts.law,allowedVoltageBands:[]}});assert.equal(none.playable,false);assert.equal(none.legs[0].evidence,'MISSING');
});
test('session-owned proposed11→source11/33→proposed33 cannot convert voltage at the middle station',()=>{
 const a={id:'scenario:owned:1',stationId:'scenario:owned:1',at:[-1,51],kv:[11],source:'SESSION_ONLY_USER_PROPOSED',proposed:true};
 const c={...a,id:'scenario:owned:2',stationId:'scenario:owned:2',at:[1,51],kv:[33]};
 const b={id:'grid_substations:1',stationId:'grid_substations:1',at:[0,51],kv:[11,33],source:'EXISTING_SOURCE'};
 const owned=new Map([[a.id,a],[c.id,c]]),scenarioStore={get:id=>owned.get(id)},stationIndex={get:id=>id===b.id?b:null};
 const opts={stops:[a,b,c],scenarioStore,stationIndex,geodesy,law:{allowedVoltageBands:null,fallback:'user-opted-hypothetical',allowTransformers:true}};
 const plan=buildRoutePlan(opts);assert.equal(plan.legs[0].evidence,'SIMULATED');assert.equal(plan.legs[1].evidence,'MISSING');assert.equal(plan.playable,false);
 assert.throws(()=>buildRoutePlan({...opts,law:{...opts.law,fallback:'documented-only'}}),/canonical station/);
 assert.throws(()=>buildRoutePlan({...opts,scenarioStore:{get:()=>null}}),/canonical station/);
 owned.delete(c.id);assert.throws(()=>buildRoutePlan(opts),/canonical station/);
});
test('current owned proposal remains hypothetical and stale pin edits are refused',()=>{
 const a={id:'scenario:owned:1',stationId:'scenario:owned:1',at:[-1,51],kv:[33],source:'SESSION_ONLY_USER_PROPOSED',proposed:true};
 const b={id:'grid_substations:1',stationId:'grid_substations:1',at:[0,51],kv:[33]};let current=a;
 const opts={stops:[a,b],scenarioStore:{get:id=>id===a.id?current:null},stationIndex:{get:id=>id===b.id?b:null},geodesy,law:{allowedVoltageBands:null,fallback:'user-opted-hypothetical'}};
 assert.equal(buildRoutePlan(opts).legs[0].electricalTopology,'UNKNOWN');
 current={...a,at:[-2,51]};assert.throws(()=>buildRoutePlan(opts),/canonical station/);
 assert.equal(buildRoutePlan({...opts,stops:[current,b]}).playable,true);
});
test('explicit Other permits only source-known nonstandard bands; Unknown never creates voltage',()=>{
 const opts={synthetic:true,stops:[stop('A',6.6),stop('B',6.6)],geodesy,law:{allowedVoltageBands:['other'],fallback:'user-opted-hypothetical'}};
 assert.equal(buildRoutePlan(opts).playable,true);
 assert.equal(buildRoutePlan({...opts,law:{...opts.law,allowedVoltageBands:['unknown']}}).playable,false);
 assert.equal(buildRoutePlan({...opts,stops:[stop('A',[]),stop('B',[])],law:{...opts.law,allowedVoltageBands:null}}).playable,false);
});
test('real session store and itinerary enforce the11→11/33→33 no-transformer rule and current owned pins',()=>{
 const store=createScenarioStationStore({sessionId:'native-law'}),a=store.create({name:'User A',at:[-1,51],kv:[11]}),c=store.create({name:'User C',at:[1,51],kv:[33]});
 const b={id:'grid_substations:1',stationId:'grid_substations:1',at:[0,51],kv:[11,33]},stationIndex={get:id=>id===b.id?b:null};
 const itinerary=createItinerary({stationIndex,scenarioStore:store,law:{fallback:'user-opted-hypothetical'}});itinerary.add(a);itinerary.add(b);itinerary.add(c);
 const selected=itinerary.snapshot(),opts={...selected,stationIndex,scenarioStore:store,geodesy};
 const plan=buildRoutePlan(opts);assert.equal(plan.legs[0].evidence,'SIMULATED');assert.equal(plan.legs[1].evidence,'MISSING');assert.equal(plan.playable,false);assert.equal(plan.planEpoch,selected.planEpoch);
 store.edit(a.id,{at:[-2,51]});assert.throws(()=>buildRoutePlan(opts),/canonical station/);
 assert.doesNotThrow(()=>buildRoutePlan({...itinerary.snapshot(),stationIndex,scenarioStore:store,geodesy}));
});

Itinerary

A JavaScript module in the train folder of GridAtlas that sets law (`setLaw`) and normalises journey law (`normaliseJourneyLaw`). It copies station (`copyStation`), sets law (`setLaw`) and normalises journey law (`normaliseJourneyLaw`).

transformgridatlas / tools/train/src/itinerary.mjs · lines 1–54 of 54 · pattern normaliseJourneyLaw (shared by 2 files)

What it does
It calculates its inputs. Defines 9 functions or classes, including createItinerary, copyStation, selectedStation, snapshot, setLaw.
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.
Downstream impact
Used directly by 1 file: Route Plan Test (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Selected stops, including endpoints. Intermediate traversal nodes are not stored here.
Why it matters
Checked by Route Plan Test.
Application
gridatlas · tools/train/src · JavaScript module
Uses
Station Index (import)
Used by
imported by Route Plan Test (import)
Produces
createItinerary, normaliseJourneyLaw
Defines here
createItinerary, copyStation, selectedStation, snapshot, setLaw, position, insert, replace, normaliseJourneyLaw
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/train/src/itinerary.mjs:1-54 · blob 684046121091b3a805533c8df85f5bc55b44aed2 · 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
import {normaliseTrainStop} from './station-index.mjs';
/** Selected stops, including endpoints. Intermediate traversal nodes are not stored here. */
export 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. */
export 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};
}


Place Bridge

A JavaScript module in the train folder of GridAtlas. It is built from the invalidate step (`invalidate`).

transformgridatlas / tools/train/src/place-bridge.mjs · lines 1–33 of 33 · Not reached from any entry point (candidate for review) · pattern createPlaceBridge (shared by 2 files)

What it does
It calculates its inputs. Defines createPlaceBridge, invalidate.
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
Adapter to the existing gazetteer result shape.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/train/src · JavaScript module
Uses
Station Index (import)
Used by
none found
Produces
createPlaceBridge
Defines here
createPlaceBridge, invalidate
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/train/src/place-bridge.mjs:1-33 · blob 8796efdced60ed25b9de0fc5fbb6af8a73398cc4 · 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: unreached_review
import {normaliseTrainStop,trainCoordinate} from './station-index.mjs';
/** Adapter to the existing gazetteer result shape. No provider fetch or station auto-selection. */
export 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};}
  });
}