In this section
- UK Lightning Preview Browser interaction · gridatlas / tools/proofs/uk-lightning-preview.browser.mjs lines 1–184
- Unified Catalogue Independent Test test · gridatlas / tools/proofs/unified-catalogue-independent.test.mjs lines 1–72
- Unified Destination Contract Test test · gridatlas / tools/proofs/unified-destination-contract.test.mjs lines 1–55
- Unified Layer Catalogue Test test · gridatlas / tools/proofs/unified-layer-catalogue.test.mjs lines 1–100
- Verify Layers Local automation · gridatlas / tools/proofs/verify-layers-local.ps1 lines 1–31
UK Lightning Preview Browser
A JavaScript module in the proofs folder of GridAtlas that reads comparison from the lightning repository. It opens profile (`openProfile`).
interactiongridatlas / tools/proofs/uk-lightning-preview.browser.mjs · lines 1–184 of 184 · Not reached from any entry point (candidate for review)
- What it does
- It loads comparison. Defines openProfile. Uses libraries node:assert/strict, node:fs, node:path, node:http, playwright. Side effects: changes the web page (DOM); 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: data source: lightning data; GeoJSON file uk_lightning.geojson. Out: JSON file comparison.json.
- What it achieves
- Compare the restored live Atlas with isolated UK lightning V2.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- node:assert/strict, node:fs, node:path, node:http, playwright
- Used by
- none found
- Produces
- openProfile
- Defines here
- openProfile
- 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/proofs/uk-lightning-preview.browser.mjs:1-184 · blob 7e4c4b33373c2ad660c8084bd4844e388d32abad · 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
/**
* Compare the restored live Atlas with isolated UK lightning V2.
* Browser test fixtures reproduce real EUMETSAT observations but are NEVER
* included in production data: intercepted requests exist only inside CI.
*/
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import {createServer} from 'node:http';
import {chromium} from 'playwright';
const root=path.resolve(import.meta.dirname,'../..');
const out=path.join(root,'work','uk-lightning-preview');
fs.mkdirSync(out,{recursive:true});
const mime={'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json','.geojson':'application/geo+json','.css':'text/css','.wasm':'application/wasm','.png':'image/png','.svg':'image/svg+xml'};
const server=createServer((req,res)=>{
try {
let p=path.resolve(root,'.'+decodeURIComponent(new URL(req.url,'http://localhost').pathname));
if(!p.startsWith(root+path.sep))throw new Error('outside repository');
if(fs.statSync(p).isDirectory())p=path.join(p,'index.html');
res.setHeader('content-type',mime[path.extname(p)]||'application/octet-stream');
res.setHeader('cache-control','no-store');
res.end(fs.readFileSync(p));
} catch {res.writeHead(404).end();}
});
await new Promise(done=>server.listen(0,'127.0.0.1',done));
const origin='http://127.0.0.1:'+server.address().port;
const browser=await chromium.launch({headless:true});
const result={baseline:'202609241334',preview:'202610261500',profiles:[]};
const sourceUrl='https://raw.githubusercontent.com/Ventusltd/lightning/main/data/uk_lightning.geojson';
const fixture={type:'FeatureCollection',features:[
{type:'Feature',id:'test-real-observation-1',geometry:{type:'Point',coordinates:[-3.9177,49.515301]},properties:{name:'Lightning flash 2026-10-21 12:32 UTC',time_utc:'2026-10-21T12:32:19.282Z',raw_tech:'EUMETSAT optical flash (not a confirmed ground strike)',status:'Satellite detection',source:'EUMETSAT',source_product:'MTG LI L2-LFL'}},
{type:'Feature',id:'test-real-observation-2',geometry:{type:'Point',coordinates:[-2.052,50.079601]},properties:{name:'Lightning flash 2026-10-22 22:10 UTC',time_utc:'2026-10-22T22:10:13.082Z',raw_tech:'EUMETSAT optical flash (not a confirmed ground strike)',status:'Satellite detection',source:'EUMETSAT',source_product:'MTG LI L2-LFL'}}
]};
const menus=['File','Edit','View','Scope','Grid','About'];
async function openProfile(width,mode) {
const mobile=width<700;
const context=await browser.newContext({viewport:{width,height:mobile?852:1000},isMobile:mobile,hasTouch:mobile,...(mobile?{userAgent:'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Mobile Safari/537.36'}:{})});
let requests=0;
const jsErrors=[];
const page=await context.newPage();
const networkFailures=[];
const consoleErrors=[];
page.on('pageerror',e=>jsErrors.push(String(e)));
page.on('requestfailed',r=>networkFailures.push(r.url()+' '+(r.failure()?.errorText||'')));
page.on('console',m=>{if(m.type()==='error')consoleErrors.push(m.text().slice(0,260));});
await page.route(sourceUrl,async route=>{
requests++;
await route.fulfill({status:200,contentType:'application/geo+json',headers:{'Access-Control-Allow-Origin':'*'},body:JSON.stringify(fixture)});
});
const url=origin+(mode==='baseline'?'/atlas/':'/atlas/preview/lightning/');
await page.goto(url,{waitUntil:'domcontentloaded',timeout:60000});
try {
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__&&document.querySelectorAll('[data-gridatlas-layer-proxy]').length>=60,null,{timeout:35000});
} catch(error) {
const state=await page.evaluate(()=>({title:document.title,url:location.href,router:document.body?.dataset?.gridatlasRouter,body:document.body?.innerText?.slice(0,1400),generation:window.__GRIDATLAS_ATLAS__?.generation,map:!!window.__GRIDATLAS_V9_MAP__,proxies:document.querySelectorAll('[data-gridatlas-layer-proxy]').length,scripts:[...document.scripts].map(s=>s.src?.slice(-160)).filter(Boolean) … [line shortened here: 415 characters; full line on GitHub]
console.error('GRIDATLAS_LOAD_DIAGNOSTIC',JSON.stringify({mode,width,state,networkFailures:networkFailures.slice(-25),consoleErrors:consoleErrors.slice(-25),jsErrors:jsErrors.slice(-25)}));
await page.screenshot({path:path.join(out,mode+'-'+width+'-load-failure.png'),fullPage:true}).catch(()=>{});
throw error;
}
if(mode==='preview')await page.waitForFunction(()=>window.__GRIDATLAS_WEATHER_LIGHTNING__?.installed,null,{timeout:15000});
const gen=await page.evaluate(()=>window.__GRIDATLAS_ATLAS__.generation);
assert.equal(gen,mode==='baseline'?result.baseline:result.preview,mode+' generation mismatch');
const layerIds=await page.locator('#scada-ui-container input[data-layer-id]').evaluateAll(xs=>xs.map(x=>x.dataset.layerId).sort());
const allIds=await page.locator('[data-gridatlas-layer-proxy]').evaluateAll(xs=>xs.map(x=>x.getAttribute('data-gridatlas-layer-proxy')).sort());
const menuInventory={};
for(const name of menus) {
const btn=page.getByRole('button',{name,exact:true});
await btn.click();
assert.equal(await btn.getAttribute('aria-expanded'),'true',mode+' cannot open menu '+name);
menuInventory[name]=await page.locator('.gm-open .gm-panel').evaluateAll(xs=>xs.map(x=>({
headings:[...x.querySelectorAll('h1,h2,h3,summary')].map(n=>n.textContent.trim()),
ids:[...x.querySelectorAll('button,input,select')].map(n=>n.id).filter(Boolean).sort()
})));
}
await page.screenshot({path:path.join(out,mode+'-'+width+'-menus.png')});
return {context,page,gen,layerIds,allIds,menuInventory,requests:()=>requests,jsErrors};
}
try {
for(const width of [1440,393]) {
const record={width,baseline:null,preview:null,pass:false};
result.profiles.push(record);
const baseline=await openProfile(width,'baseline');
record.baseline={generation:baseline.gen,layers:baseline.layerIds.length,menus:Object.keys(baseline.menuInventory)};
assert(!baseline.layerIds.includes('uk_lightning'),'restored baseline unexpectedly has lightning');
await baseline.context.close();
const preview=await openProfile(width,'preview');
record.preview={generation:preview.gen,layers:preview.layerIds.length};
assert(!preview.layerIds.includes('uk_lightning'),'Weather must NOT mutate ukConfig');
assert.deepEqual(preview.layerIds,baseline.layerIds,'Original 60 GridAtlas controls changed');
assert.deepEqual(preview.allIds.filter(id=>id!=='weather:uk_lightning'),baseline.allIds,'Original layer proxies changed');
for(const name of menus){
const newInventory=preview.menuInventory[name].map(panel=>({...panel,ids:panel.ids.filter(id=>id!=='gridatlas-weather-lightning-toggle')}));
assert.deepEqual(newInventory,baseline.menuInventory[name],'Original menu controls changed: '+name);
}
const menuContract=await preview.page.evaluate(()=>window.__GRIDATLAS_MODULES__?.menuBar?.inspect?.());
assert(menuContract?.complete&&menuContract?.engine===60&&menuContract?.pipeline===3,'Menu 60+3 contract violated');
const page=preview.page;
const native=page.locator('#scada-ui-container input[data-weather-layer="uk_lightning"]');
const fs=page.locator('#fs-curtain-keys input[data-weather-layer="uk_lightning"]');
assert.equal(await native.count(),1,'Lightning missing from the actual LAYERS panel');
assert.equal(await fs.count(),1,'Lightning missing from fullscreen layer controls');
const nativeStructure=await page.evaluate(()=>({
firstGroup:document.querySelector('#scada-ui-container')?.firstElementChild?.getAttribute('data-weather-native-group'),
fullFirst:document.querySelector('#fs-curtain-keys')?.firstElementChild?.getAttribute('data-weather-native-group')
}));
assert.equal(nativeStructure.firstGroup,'layers','Weather is not the first native LAYERS group');
assert.equal(nativeStructure.fullFirst,'fullscreen','Weather is not the first fullscreen layer group');
record.preview.nativeStructure=nativeStructure;
const grid=page.getByRole('button',{name:'Grid',exact:true});
if(await grid.getAttribute('aria-expanded')!=='true')await grid.click();
const toggle=page.locator('[data-gridatlas-layer-proxy="weather:uk_lightning"]');
assert.equal(await toggle.count(),1,'independent lightning toggle missing from Grid menu');
// Crucial UX regression gate: the toggle MUST be visible on initial Grid
// opening without scrolling past the 63 original layer controls.
const weatherPosition=await page.evaluate(()=>{
const body=document.querySelector('#gridatlas-menu-bar-panel-4 .gm-panel-body');
const toggle=document.querySelector('[data-gridatlas-layer-proxy="weather:uk_lightning"]');
if(!body||!toggle)return null;
body.scrollTop=0;
const root=body.getBoundingClientRect();
const rect=toggle.getBoundingClientRect();
return {firstGroup:body.firstElementChild?.getAttribute('data-weather-group'),
visibleWithoutScroll:rect.top>=root.top-1&&rect.bottom<=root.bottom+1,
headerText:body.firstElementChild?.textContent,scrollTop:body.scrollTop};
});
assert.equal(weatherPosition?.firstGroup,'uk_lightning','Weather is not the first Grid menu group');
assert.equal(weatherPosition?.visibleWithoutScroll,true,'Lightning toggle is below the fold on first Grid open');
record.preview.weatherPosition=weatherPosition;
await page.screenshot({path:path.join(out,'preview-'+width+'-weather-first.png')});
await toggle.click();
assert.equal(await native.isChecked(),true,'Menu ON not synchronised to actual LAYERS');
assert.equal(await fs.isChecked(),true,'Menu ON not synchronised to fullscreen');
await page.waitForFunction(()=>/\[(OK|FAIL|EMPTY)\]/.test(document.getElementById('lbl-uk_lightning')?.textContent||''),null,{timeout:60000});
const status=await page.locator('#lbl-uk_lightning').textContent();
assert(status.includes('[OK]'),'UK lightning hydration failed: '+status);
assert.equal(preview.requests(),1,'lightning URL was not fetched externally');
const features=await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-uk_lightning')._data.features.length);
assert.equal(features,2,'unexpected test observation count');
await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.jumpTo({center:[-3.9177,49.515301],zoom:9}));
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.queryRenderedFeatures({layers:['l-uk_lightning']}).length>0,null,{timeout:20000});
record.preview={...record.preview,status:status.trim(),features,rendered:await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.queryRenderedFeatures({layers:['l-uk_lightning']}).length),externalRequests:preview.requests()};
await page.screenshot({path:path.join(out,'preview-'+width+'-lightning-on.png')});
if(await grid.getAttribute('aria-expanded')!=='true')await grid.click();
await toggle.scrollIntoViewIfNeeded();
await toggle.click();
assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getLayoutProperty('l-uk_lightning','visibility')),'none');
assert.equal(await native.isChecked(),false,'Menu OFF not synchronised to actual LAYERS');
if(await grid.getAttribute('aria-expanded')==='true')await grid.click();
const dash=page.locator('#gridatlas-dash-toggle');
const wrapper=page.locator('.scada-wrapper');
// On mobile the native panel starts COLLAPSED, but Playwright isVisible()
// still sees layout inside its clipped, zero-height ancestor. Explicitly
// OPEN the user's real ▲ LAYERS control before asking for a real tap.
if(await wrapper.getAttribute('data-gridatlas-collapsed')==='1'){
assert.equal(await dash.isVisible(),true,'Mobile LAYERS expand control is hidden');
await dash.click();
}
assert.notEqual(await wrapper.getAttribute('data-gridatlas-collapsed'),'1','Native LAYERS failed to expand');
assert.equal(await native.isVisible(),true,'Actual LAYERS Weather checkbox is not visible');
await native.scrollIntoViewIfNeeded();
await page.screenshot({path:path.join(out,'preview-'+width+'-native-layers-weather-visible.png')});
await native.click();
assert.equal(await toggle.isChecked(),true,'LAYERS ON not synchronised to Grid dropdown');
assert.equal(await fs.isChecked(),true,'LAYERS ON not synchronised to fullscreen');
assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getLayoutProperty('l-uk_lightning','visibility')),'visible');
await native.click();
assert.equal(await toggle.isChecked(),false,'LAYERS OFF not synchronised to Grid dropdown');
assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getLayoutProperty('l-uk_lightning','visibility')),'none');
record.preview.nativeLayersToggle='PASS: visible, clickable, synchronised in both directions';
record.pass=true;
await preview.context.close();
console.log(JSON.stringify(record));
}
fs.writeFileSync(path.join(out,'comparison.json'),JSON.stringify(result,null,2)+'\n');
console.log('PASS: desktop/mobile baseline menu parity, native lightning GeoJSON and map paint');
} finally {
await browser.close();
await new Promise(resolve=>server.close(resolve));
}Unified Catalogue Independent Test
A test in the proofs folder of GridAtlas that checks Unified Layer Catalogue. It is built from the check step (`check`), the ids step (`ids`) and the expect step (`expect`).
testgridatlas / tools/proofs/unified-catalogue-independent.test.mjs · lines 1–72 of 72 · Entry point · pattern expect (shared by 3 files)
- What it does
- It tests 211kV, 133kV and transformers. Defines check, ids, expect. Uses libraries node:assert/strict.
- 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: 211kV, 133kV, transformers, 400kV, 33kV, 11kV.
- Inputs & outputs
- Voltage levels named: 400kV, 211kV, 133kV, 33kV, 11kV, 4kV, 0.4kV, 400V.
- Downstream impact
- Used directly by 2 files: Unified Owner Test Proof (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- G201-06: independent acceptance oracle; run with Node, no browser or network. Its code works with 11 kV, 0.11 kV and 33 kV.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow. Checked by Unified Owner Test Proof.
- Application
- gridatlas · tools/proofs · test
- Uses
- Unified Layer Catalogue (dynamic import), node:assert/strict
- Used by
- run by Unified Owner Test Proof (script call), run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- check, ids, expect
- Defines here
- check, ids, expect
- 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/proofs/unified-catalogue-independent.test.mjs:1-72 · blob 084e08420acdd27526850bac4d3855bfbf80cdc8 · 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
// G201-06: independent acceptance oracle; run with Node, no browser or network.
import assert from 'node:assert/strict';
let networkCalls = 0;
const originalFetch = globalThis.fetch;
globalThis.fetch = () => { networkCalls++; throw new Error('Metadata search attempted a download'); };
const {createLayerCatalogue} = await import('../../atlas/modules/unified-layer-catalogue.mjs');
const failures = [];
let passed = 0;
function check(name, fn) {
try { fn(); passed++; } catch (error) { failures.push({name, message:error.message}); }
}
const fixture = [
{id:'engine:11',label:'UKPN 11 kV',voltage:'11 kV',aliases:['UK Power Networks']},
{id:'engine:211',label:'UKPN 211 kV',voltage:'211 kV'},
{id:'engine:33',label:'33 kV distribution',voltage:'33 kV'},
{id:'engine:133',label:'133 kV distribution',voltage:'133 kV'},
{id:'engine:4',label:'4 kV transformer',voltage:'4 kV'},
{id:'engine:lv',label:'400 V transformer',voltage:'400 V'},
{id:'engine:low',label:'0.11 kV',voltage:'0.11 kV'},
{id:'engine:hyphen',label:'11-kV feeder'},
{id:'engine:kva',label:'11 kVA transformer'},
{id:'engine:400',label:'400-kV transmission'},
{id:'engine:1400',label:'1400 kV transmission'},
{id:'pipeline:11',label:'Pipeline news',aliases:['UKPN']}
];
const index = createLayerCatalogue(fixture);
const ids = (q, options) => index.search(q,options).rows.map(r=>r.id).sort();
const expect = (q, expected) => check('query '+q,()=>assert.deepEqual(ids(q),expected.slice().sort()));
expect('33 kV',['engine:33']);
expect('11 kV',['engine:11','engine:hyphen']);
expect('11000 V',['engine:11','engine:hyphen']);
expect('11-kV',['engine:11','engine:hyphen']);
expect('UKPN 11 kV',['engine:11']);
expect('4 kV',['engine:4']);
expect('400 V',['engine:lv']);
expect('0.4 kV',['engine:lv']);
expect('0.11 kV',['engine:low']);
expect('400 kV',['engine:400']);
expect('UKPN.',['engine:11','engine:211','pipeline:11']);
expect('UK Power Networks',['engine:11']);
expect('former',['engine:4','engine:lv','engine:kva']);
check('exact id precedes other ranks',()=>assert.equal(index.search('engine:11').rows[0].id,'engine:11'));
check('selection is live external state, not filtered projection',()=>{
const selected = new Set(['engine:33','pipeline:11']);
assert.deepEqual(ids('UKPN',{selectedOnly:true,selectedIds:selected}),['pipeline:11']);
assert.deepEqual([...selected],['engine:33','pipeline:11']);
assert.deepEqual(ids('',{selectedOnly:true,selectedIds:selected,pageSize:1,page:2}),['pipeline:11']);
selected.delete('pipeline:11'); selected.add('engine:211');
assert.deepEqual(ids('UKPN',{selectedOnly:true,selectedIds:selected}),['engine:211']);
});
check('caller metadata mutation cannot alter indexed aliases',()=>{
const source={id:'test:immutable',label:'Original',aliases:['Stable']};
index.register([source]); source.aliases[0]='Changed'; source.label='Changed';
const row=index.search('Stable').rows[0];
assert.equal(row.label,'Original'); assert.ok(Object.isFrozen(row.aliases));
assert.equal(index.search('Changed').total,0);
});
check('10,000 identities are exhaustive and pages are bounded',()=>{
const rows=Array.from({length:10000},(_,i)=>({id:'engine:'+String(i).padStart(5,'0'),label:'Asset '+String(i).padStart(5,'0')}));
const large=createLayerCatalogue(rows), seen=new Set();
for(let page=1;page<=100;page++){
const result=large.search('',{page}); assert.equal(result.total,10000); assert.equal(result.rows.length,100);
for(const row of result.rows){assert.ok(!seen.has(row.id));seen.add(row.id);}
}
assert.deepEqual([...seen],rows.map(row=>row.id));
assert.equal(large.search('',{page:101}).rows.length,0);
assert.throws(()=>large.search('',{pageSize:101}),RangeError);
});
check('zero fetch calls during metadata import, register and search',()=>assert.equal(networkCalls,0));
globalThis.fetch=originalFetch;
console.log(JSON.stringify({passed,failed:failures.length,failures,networkCalls},null,2));
if(failures.length) process.exitCode=1;Unified Destination Contract Test
A test in the proofs folder of GridAtlas that checks Unified Destination Contract. It runs tests (`runTests`).
testgridatlas / tools/proofs/unified-destination-contract.test.mjs · lines 1–55 of 55 · Entry point · pattern runTests (shared by 7 files)
- What it does
- It tests the REPD register. Defines runTests, commit. Uses libraries node:assert/strict.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
- Downstream impact
- Used directly by 2 files: Unified Owner Test Proof (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- Defines `runTests` and `commit`.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow. Checked by Unified Owner Test Proof.
- Application
- gridatlas · tools/proofs · test
- Uses
- Unified Destination Contract (import), node:assert/strict
- Used by
- run by Unified Owner Test Proof (script call), run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- runTests, commit
- Defines here
- runTests, commit
- 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/proofs/unified-destination-contract.test.mjs:1-55 · blob c1256be5899b5cfa1b001230cb237c9518b5cef7 · 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 assert from 'node:assert/strict';
import {createDestinationGate, validDestinationCoordinate, validateDestinationLeg} from '../../atlas/modules/unified-destination-contract.mjs';
function runTests(check, throws) {
const a = createDestinationGate();
const b = createDestinationGate();
const data = {id:'repd:1018',at:[-.4,51.55],label:'Site',provider:'REPD',precision:'project'};
let calls=0;
const commit = () => {calls++; return {ok:true};};
const first = a.onInput(' A ');
check(first.query==='A','trim query');
const ra = a.beginRequest(first);
const firstHandle = a.publish(ra,[data])[0];
check(Object.isFrozen(firstHandle) && Object.isFrozen(firstHandle.at),'frozen handle');
data.at[0]=1;
check(firstHandle.at[0]===-.4,'copy coordinates');
check(firstHandle.provider==='REPD' && firstHandle.precision==='project','retain provenance');
const second = a.onInput('B');
check(a.transfer(firstHandle,commit).reason==='stale-result','invalidate synchronously before debounce');
check(a.publish(ra,[data])===null,'reject delayed A');
check(a.beginRequest(first)===null,'reject stale input');
check(a.beginRequest(b.onInput('B'))===null,'reject foreign input');
const rb=a.beginRequest(second);
const third=a.onInput('A');
const rc=a.beginRequest(third);
check(a.publish(rb,[data])===null,'A-B-A rejects B');
check(a.publish(ra,[data])===null,'A-B-A rejects original A');
const same=a.beginRequest(third);
check(a.publish(rc,[data])===null,'retry invalidates old request');
const handles=a.publish(same,[data,{id:'address:2',at:[0,0]}]);
check(handles.length===2 && Object.isFrozen(handles),'immutable result batch');
check(a.transfer({...handles[0]},commit).reason==='stale-result','reject fabricated result');
check(a.transfer(handles[0],()=>({ok:false,reason:'poor-fix'})).reason==='poor-fix','propagate controller refusal');
check(calls===0,'no invocation for stale results');
throws(()=>a.publish(same,[data,data]),'reject duplicate identities');
throws(()=>a.publish(same,[{id:'invalid',at:[181,0]}]),'reject invalid coordinates');
check(a.transfer(handles[0],commit).ok && calls===1,'valid transfer exactly once');
check(a.transfer(handles[1],commit).reason==='stale-result' && calls===1,'consume result batch');
const escape=a.beginRequest(a.onInput('postcode'));
a.invalidate();
check(a.publish(escape,[data])===null,'Escape/dismissal cancels request');
check(a.beginRequest(a.onInput(' '))===null,'empty query no request');
check(!validDestinationCoordinate([NaN,0]) && !validDestinationCoordinate([0,Infinity]),'nonfinite coordinates');
check(!validDestinationCoordinate(['0',0]) && !validDestinationCoordinate([0,91]),'type and latitude');
check(!validDestinationCoordinate([0,0,0]) && validDestinationCoordinate([180,-90]),'coordinate arity and bounds');
check(validateDestinationLeg(null,[0,0],()=>{throw Error('unexpected');}).ok,'destination only when no predecessor');
check(validateDestinationLeg([0,0],[1,1],()=>2).ok,'2 km inclusive');
check(validateDestinationLeg([0,0],[1,1],()=>2.000001).reason==='over-limit','over 2 km');
check(validateDestinationLeg([0,0],[1,1],()=>NaN).reason==='invalid-distance','invalid distance');
check(validateDestinationLeg([0,0],[1,1],()=>-1).reason==='invalid-distance','negative distance');
check(validateDestinationLeg([0,0],[0,100],()=>0).reason==='invalid-coordinate','invalid destination');
}
let count = 0;
runTests((ok,label)=>{assert.ok(ok,label); count++;},(fn,label)=>{assert.throws(fn,undefined,label); count++;});
console.log(`${count} destination-contract assertions passed`);Unified Layer Catalogue Test
A test in the proofs folder of GridAtlas that checks Unified Layer Catalogue. It runs catalogue checks (`runCatalogueChecks`) and is built from the sorted ids helper (`sortedIds`).
testgridatlas / tools/proofs/unified-layer-catalogue.test.mjs · lines 1–100 of 100 · Entry point · pattern throws (shared by 12 files)
- What it does
- It tests 11kV, 400kV, solar and 33kV. Defines runCatalogueChecks, eq, throws, id, sortedIds.
- 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, 400kV, solar, 33kV, 211kV, 133kV.
- Inputs & outputs
- Voltage levels named: 400kV, 211kV, 133kV, 33kV, 11kV, 4kV, 0.4kV, 400V.
- Downstream impact
- Used directly by 2 files: Unified Owner Test Proof (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- Defines `runCatalogueChecks`, `throws` and `sortedIds`. Its code works with 11 kV, 33 kV and 400 kV.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow. Checked by Unified Owner Test Proof.
- Application
- gridatlas · tools/proofs · test
- Uses
- Unified Layer Catalogue (import)
- Used by
- run by Unified Owner Test Proof (script call), run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- runCatalogueChecks, eq, throws, id, sortedIds
- Defines here
- runCatalogueChecks, eq, throws, id, sortedIds
- 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/proofs/unified-layer-catalogue.test.mjs:1-100 · blob 3860ed8a2e7843c4c8f425fb14ddb53a0ccd3936 · 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 {createLayerCatalogue,normalizeLayerText} from '../../atlas/modules/unified-layer-catalogue.mjs';
function runCatalogueChecks(createLayerCatalogue,normalizeLayerText) {
let checks=0;
function eq(actual,expected,message) {
checks++;
if(JSON.stringify(actual)!==JSON.stringify(expected)) throw new Error(`${message}: ${JSON.stringify(actual)} != ${JSON.stringify(expected)}`);
}
function throws(fn,message) {checks++;let caught=false;try{fn()}catch{caught=true}if(!caught)throw new Error(message);}
const id = r => r.rows.map(x=>x.id);
const selected = new Set(['secondary']);
const catalogue=createLayerCatalogue([
{id:'secondary',label:'UKPN secondary substations',voltage:'11 kV',aliases:['UK Power Networks'],category:'Distribution'},
{id:'11kv',label:'11kV network',voltage:'11000 V',category:'Distribution'},
{id:'solar',label:'Solar farms',category:'Renewables'},
{id:'tx',label:'400 kV transmission',category:'Transmission'},
{id:'a',label:'Same name'},{id:'b',label:'Same name'}
]);
eq(normalizeLayerText(' 11 kV / 11000 V / 11kV '),'11kv 11kv 11kv','voltage aliases');
eq(id(catalogue.search('11000 V')),id(catalogue.search('11kV')),'equivalent voltage searches');
eq(id(catalogue.search('11 kV')),['11kv','secondary'],'rank');
eq(id(catalogue.search('UKPN 11kv')),['secondary'],'cross-field tokens');
eq(id(catalogue.search('uk power networks')),['secondary'],'alias');
eq(id(catalogue.search('same name')),['a','b'],'deterministic duplicate labels');
eq(catalogue.search('nonexistent').total,0,'no results');
eq(id(catalogue.search('',{selectedOnly:true,selectedIds:selected})),['secondary'],'selected-only');
catalogue.search('solar',{selectedOnly:true,selectedIds:selected});
eq([...selected],['secondary'],'selection unchanged');
eq(catalogue.search('',{page:3,pageSize:2}).rows.length,2,'pagination');
eq(catalogue.search('',{page:4,pageSize:2}).rows.length,0,'out of range page');
throws(()=>catalogue.search('',{pageSize:101}),'page bound');
throws(()=>catalogue.register([{id:'x',label:'X'},{id:'x',label:'Y'}]),'duplicate registration');
throws(()=>catalogue.register([{id:'x',label:'X'},{id:'y',label:''}]),'atomic invalid registration');
eq(catalogue.size,6,'atomic registration unchanged');
catalogue.register([{id:'late',label:'Late arrival',operator:'UKPN'}]);
eq(id(catalogue.search('late')),['late'],'late registration');
catalogue.register([{id:'late',label:'Renamed'}]);
eq(catalogue.search('late arrival').total,0,'stale metadata removed');
eq(id(catalogue.search('renamed')),['late'],'metadata updated');
eq(catalogue.remove('late'),true,'remove');
eq(catalogue.search('renamed').total,0,'removed');
eq(Object.isFrozen(catalogue.search('solar').rows[0]),true,'immutable row');
// Independent adversarial oracle: complete voltage tokens must never fuzzy-match.
const voltages=createLayerCatalogue([
{id:'lv',label:'400 V LV'},
{id:'4',label:'4 kV'},
{id:'11',label:'11-kV',operator:'UKPN'},
{id:'211',label:'211 kV',operator:'UKPN'},
{id:'33',label:'33 kV'},
{id:'133',label:'133 kV'},
{id:'400',label:'400 kV'},
{id:'1400',label:'1400 kV'},
{id:'low',label:'0.11 kV'},
{id:'power',label:'11 kVA transformer'},
{id:'mixed',label:'33/11 kV substation',voltage:'33 kV / 11 kV'},
{id:'fraction',label:'333.3 V'}
]);
const sortedIds=q=>id(voltages.search(q)).sort();
for(const q of ['11 kV','11000 V','11kV','11-kV','11–kV','11 kV.','011.00 kV'])
eq(sortedIds(q),['11','mixed'],'exact '+q);
eq(sortedIds('UKPN. 11 kV'),['11'],'mixed punctuation and voltage');
eq(sortedIds('33 kV'),['33','mixed'],'33 not 133');
eq(sortedIds('4 kV'),['4'],'4 not 400 V');
eq(sortedIds('400 kV'),['400'],'400 not 1400 kV');
eq(sortedIds('400 V'),['lv'],'400 V equivalence');
eq(sortedIds('.4 kV'),['lv'],'leading decimal');
eq(sortedIds('0.4kV'),['lv'],'decimal');
eq(sortedIds('110 V'),['low'],'small decimal');
eq(sortedIds('0.3333 kV'),['fraction'],'fractional V exact conversion');
eq(sortedIds('33 kV 11 kV'),['mixed'],'multiple complete voltage constraints');
eq(sortedIds('transform'),['power'],'ordinary text prefix');
eq(sortedIds('nsform'),['power'],'ordinary text substring');
eq(sortedIds('UKPN.'),['11','211'],'trailing punctuation');
eq(Object.isFrozen(catalogue.search('solar').rows[0].aliases),true,'immutable aliases');
throws(()=>catalogue.search('',{page:Number.MAX_SAFE_INTEGER,pageSize:100}),'unsafe offset');
const benchmarks=[];
for(const n of [1000,5000,10000]){
const fixture=Array.from({length:n},(_,i)=>({id:`layer-${String(i).padStart(5,'0')}`,label:`Asset ${String(i).padStart(5,'0')}`,category:i%2?'Transmission':'Distribution',operator:i%5?'Other':'UKPN',voltage:i%3?'400 kV':'11 kV',aliases:[`sector ${i%7}`]}));
const start=Date.now(), index=createLayerCatalogue(fixture), buildMs=Date.now()-start;
const expected=fixture.filter((_,i)=>i%5===0&&i%3===0).map(x=>x.id);
const actual=[];
for(let page=1;page<=Math.ceil(expected.length/100);page++){
const r=index.search('ukpn 11000v',{page});
eq(r.total,expected.length,`oracle count ${n}`);
actual.push(...id(r));
}
eq(actual,expected,`oracle identities ${n}`);
eq(index.search('').total,n,'total');
eq(index.search('').rows.length,100,'bounded page');
const times=[];
const queries=['','ukpn 11kv','distribution','sector 5','400kv','asset 00001','not a real layer'];
for(let i=0;i<70;i++){const before=Date.now();index.search(queries[i%queries.length]);times.push(Date.now()-before);}
times.sort((a,b)=>a-b);
benchmarks.push({entries:n,buildMs,p95QueryMs:times[Math.ceil(times.length*.95)-1],samples:times.length});
}
return {checks,benchmarks};
}
console.log(JSON.stringify(runCatalogueChecks(createLayerCatalogue,normalizeLayerText),null,2));Verify Layers Local
A PowerShell script in the proofs folder of GridAtlas.
automationgridatlas / tools/proofs/verify-layers-local.ps1 · lines 1–31 of 31 · Not reached from any entry point (candidate for review)
- What it does
- Side effects: starts processes.
- 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
- Its name says it verifies layers local. Described from its file name only (a candidate, not yet checked against the code).
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/proofs · PowerShell script
- Uses
- none found
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/verify-layers-local.ps1:1-31 · blob e6003fc2df1d7088c9e38ba8de4d62b7f1bcf256 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
param(
[Parameter(Mandatory=$true)][string]$DataRoot,
[Parameter(Mandatory=$true)][string]$GpuPython,
[string]$CpuPython = 'python',
[string]$OutputDirectory = 'work/local-layer-ci'
)
$ErrorActionPreference = 'Stop'
Push-Location (Resolve-Path (Join-Path $PSScriptRoot '../..'))
try {
New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null
function Invoke-Checked {
param([string]$Executable, [string[]]$Arguments)
# Windows PowerShell wraps native stderr warnings as errors. The native
# exit code, not a CuPy environment warning, determines success.
$PreviousPreference = $ErrorActionPreference
try { $ErrorActionPreference = 'Continue'; & $Executable @Arguments }
finally { $ErrorActionPreference = $PreviousPreference }
if ($LASTEXITCODE -ne 0) { throw "Verification failed: $Executable $Arguments" }
}
Invoke-Checked node @('tools/scope/verify-compose.mjs')
Invoke-Checked node @('tools/proofs/run-current.mjs')
Invoke-Checked node @('tools/proofs/prepare-layer-census.mjs')
Invoke-Checked $CpuPython @('tools/proofs/layer-census.py','--data-root',$DataRoot,'--out',"$OutputDirectory/census")
Invoke-Checked $GpuPython @('tools/proofs/layer-census-gpu.py','--input',"$OutputDirectory/census")
foreach ($Width in @(1440,393)) {
Invoke-Checked node @('tools/proofs/all-layer-clicks.browser.mjs','--width',"$Width",'--out',"$OutputDirectory/browser-$Width")
}
Invoke-Checked node @('tools/proofs/all-controls.browser.mjs','--out',"$OutputDirectory/controls")
Invoke-Checked node @('tools/scope/loop.mjs','lint')
Write-Output "PASS: CPU/CuPy parity and real Chrome desktop/Android touch-emulation layer interactions. Receipts: $OutputDirectory"
} finally { Pop-Location }