In this section
- Injection Response Proof render · gridatlas / tools/proofs/modules/202609020015-injection-response.proof.mjs lines 352–429
- Offtakers Cartridge storage · gridatlas / tools/proofs/offtakers-cartridge.mjs lines 1–100
- Prepare Layer Census storage · gridatlas / tools/proofs/prepare-layer-census.mjs lines 1–12
- Regional Interface Browser interaction · gridatlas / tools/proofs/regional-interface.browser.mjs lines 1–269
- Renewable Energy Planning Database (REPD) Deep Link Sweep Browser energy-data · gridatlas / tools/proofs/repd-deep-link-sweep.browser.mjs lines 1–140
- Run Current electrical · gridatlas / tools/proofs/run-current.mjs lines 1–62
Injection Response Proof
A JavaScript module in the proofs folder of GridAtlas that reads GB transmission network and 400kV.
rendergridatlas / tools/proofs/modules/202609020015-injection-response.proof.mjs · lines 352–429 of 429 · version 2026-09-02 00:15 (continued from section 661) · Not reached from any entry point (candidate for review) · pattern graphOf (shared by 2 files)
- What it does
- It loads GB transmission network and 400kV. Defines 6 functions or classes, including check, close, graphOf, X, shareOn. Uses libraries node:fs, node:path, node:url. Side effects: changes the web page (DOM); reads or writes files; 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. Domain terms in the code: 400kV.
- Inputs & outputs
- In: JSON file gb-transmission-network.v1.json. Voltage levels named: 400kV.
- Downstream impact
- Used directly by 1 file: Local CI (gridatlas).
- What it achieves
- It is built from the check step (`check`), the close step (`close`) and the graph of helper (`graphOf`). Codex's standing condition on any load-flow work is validation against a trusted solver. Its code works with 400 kV, 100 MW and 17.97 MW.
- Why it matters
- Run by Local CI.
- Application
- gridatlas · tools/proofs/modules · JavaScript module
- Uses
- node:fs, node:path, node:url
- Used by
- run by Local CI (script call)
- Produces
- check, close, graphOf, X, shareOn, add
- 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/modules/202609020015-injection-response.proof.mjs:352-429 · blob e04107f557b526e5b8f14c87f8854c4a3228cf0d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
for (const b of flow.respond(model, { atNode: wbur, slackNode: slack, mw: 500, minimumShare: 0 }).branches) {
add(b.from_node, b.flow_mw);
add(b.to_node, -b.flow_mw);
}
const injectionBus = model.busOf(wbur);
const slackBus = model.busOf(slack);
let worst = 0;
let worstAt = null;
let checked = 0;
for (const [bus, net] of netAt) {
if (bus === injectionBus || bus === slackBus) continue;
checked += 1;
if (Math.abs(net) > worst) { worst = Math.abs(net); worstAt = bus; }
}
check(`every intermediate bus on the real network conserves power to 1e-6 (${checked} buses)`,
worst < 1e-6, `worst ${worst.toExponential(3)} at ${worstAt}`);
check('the injection bus carries exactly what was injected',
close(netAt.get(injectionBus), 500, 1e-6), String(netAt.get(injectionBus)));
check('the slack bus withdraws exactly what was injected',
close(netAt.get(slackBus), -500, 1e-6), String(netAt.get(slackBus)));
check('enough intermediate buses were checked for this to mean something',
checked > 50, `${checked}`);
}
/* THE PRODUCTION PATH ITSELF, on the real product.
------------------------------------------------------------------------
The old proof never ran this. It chose a connected distant slack by hand
while the live caller took the first lexicographic bus, and that gap is
the whole reason a broken composition shipped with a green proof. */
console.log('\nthe production caller, on the real network\n');
{
check('the real 400 kV graph is NOT connected, which is why a slack must be chosen with care',
model.counts.components > 1, `${model.counts.components} components`);
const firstBus = model.buses.find(b => b !== model.busOf(wbur));
check('the bus the OLD caller would have picked is in a different component',
model.componentOf(firstBus) !== model.componentOf(model.busOf(wbur)),
`${firstBus}`);
const wrong = flow.respond(model, { atNode: wbur, slackNode: firstBus, mw: 480, minimumShare: 0 });
check('and asking for that transfer is refused rather than answered',
wrong.publishable === false);
const sink = flow.sinkFor(model, wbur);
check('the declared sink is in the same component as the injection',
sink && model.componentOf(sink) === model.componentOf(model.busOf(wbur)), String(sink));
const real = flow.respond(model, { atNode: wbur, slackNode: sink, mw: 480, minimumShare: 0.05 });
check('the production path now converges on the real network', real.convergence.converged);
check('and is available by all three acceptance conditions', real.publishable === true);
check('every bus in the real solve conserves power to 1e-6 MW',
real.validation.worst_bus_error_mw < 1e-6,
`worst ${real.validation.worst_bus_error_mw.toExponential(3)} MW at ${real.validation.worst_bus}`);
check('it reports flows a reader can act on', real.branches.length > 0);
check('parallel circuits are counted: the model has more branches than the collapsed version had',
model.counts.branches > 437, `${model.counts.branches} branches`);
}
check('the answer carries its declared model with it, not just in the docs',
answer.declared_model && answer.declared_model.base_mva === 100);
check('the answer carries the two refusals with it',
/not a loading/i.test(answer.not_a_loading)
&& /not permission/.test(answer.not_a_connection_offer));
check('published ratings travel with the branches, uncombined',
answer.branches.some(b => b.published_ratings_mva
&& Number.isFinite(b.published_ratings_mva.winter)));
check('nothing in the answer claims headroom or spare capacity', (() => {
const stripped = JSON.stringify(Object.assign({}, answer,
{ not_a_loading: '', not_a_connection_offer: '', declared_model: {} }));
return !/headroom|spare|available/i.test(stripped);
})());
console.log(`\n${passed}/${passed + failures.length} checks passed`);
if (failures.length) {
console.log('FAILURES');
for (const f of failures) console.log(` ${f}`);
process.exit(1);
}
console.log('the model states its equations, its base, its slack and its assumptions,');
console.log('reproduces the exact analytic answers, conserves power at every bus on');
console.log('the real network, and says plainly that it is not a loading.');Offtakers Cartridge
A JavaScript module in the proofs folder of GridAtlas that fetches generations and the Renewable Energy Planning Database (REPD) register, using SHA-256.
storagegridatlas / tools/proofs/offtakers-cartridge.mjs · lines 1–100 of 100 · Not reached from any entry point (candidate for review) · pattern readJson (shared by 43 files)
- What it does
- It fetches generations and the REPD register. Defines sha, readJson, proveOfftakersCartridge. Uses libraries node:assert/strict, node:fs, node:path, node:vm, node:crypto. Side effects: reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (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.
- Inputs & outputs
- In: JSON file current.json; JSON file generations.json.
- What it achieves
- It reads JSON (`readJson`) and is built from the sha step (`sha`). The proof of a generation that composes the potential-offtakers overlay as its OWN cartridge ('UK-offtakers-overlay', slot after-cartridge, after UK-lightning-overlay). It reads `atlas/current.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- Loader Composition (import), GridAtlas — Scope (dynamic import), Build (dynamic import), GridAtlas — Index Page (estate URL), node:assert/strict, node:fs, node:path, node:vm, node:crypto
- Used by
- none found
- Produces
- OFFTAKERS_ID, proveOfftakersCartridge
- Defines here
- sha, readJson, proveOfftakersCartridge
- 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/offtakers-cartridge.mjs:1-100 · blob 033b934be1b1cde108e1e534d237bbf53894372b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
* The proof of a generation that composes the potential-offtakers overlay as its OWN cartridge ('uk-offtakers-overlay',
* slot after-cartridge, after uk-lightning-overlay). docs/OFFTAKERS-SOURCE.md. Each such generation has a two-line
* tools/proofs/<G>-uk-offtakers-overlay.proof.mjs that calls this with G.
*
* identity G, the slot, the anchor (directly after uk-lightning-overlay, last in cartridge_order), every hash;
* module the cartridge IS atlas/modules/<M>-uk-offtakers-overlay.js (no copy), within its owner-approved 80,000-byte budget, names
* generation M, rebuilds from tools/offtakers/src byte for byte while listed in generations.json, parses, one strict IIFE that is one expression;
* contract static negatives (no engine, menu, layer-control, storage, lightning or place-search contract; no emission
* figure; the banned vicinity words) and positives (OFF by default, the pinned SHA-256s, the original measure);
* loader the route's loader is registered and supports the slots, and composes it: the offtakers tag directly after
* the uk-lightning-overlay tag, its blob byte-identical to the module, every other script unchanged and in order.
*/
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { createHash } from 'node:crypto';
import { compose, ROOT } from './loader-composition.mjs';
export const OFFTAKERS_ID = 'uk-offtakers-overlay', ANCHOR = 'uk-lightning-overlay', BUDGET = 80000; // Owner-approved 80,000 bytes, 29 Oct 2026, issue #73 (tools/scope/lib.mjs)
const sha = b => createHash('sha256').update(b).digest('hex');
const readJson = rel => JSON.parse(fs.readFileSync(path.join(ROOT, rel), 'utf8'));
const BANNED = /\b(viable|feasible|opportunity|offtake agreement|PPA|private wire|supply|capacity available|demand of|consumes|MWh|large user|best|recommended|suitable)\b/i;
export async function proveOfftakersCartridge(G) {
process.chdir(ROOT);
const { registeredLoader, slotsUsed, CARTRIDGE_BYTE_BUDGETS } = await import('../scope/lib.mjs');
const { build } = await import('../offtakers/build.mjs');
const live = readJson('atlas/current.json'), route = String(live.generation) === G ? 'atlas/' : `atlas/v/${G}/`;
const current = readJson(`${route}current.json`), at = p => path.resolve(ROOT, route, p);
assert.equal(String(current.generation), G);
const order = current.cartridge_order, e = current.cartridges.find(c => c.id === OFFTAKERS_ID);
assert.ok(e, 'the offtakers cartridge is composed');
assert.equal(order.filter(id => id === OFFTAKERS_ID).length, 1);
assert.equal(order.indexOf(OFFTAKERS_ID), order.indexOf(ANCHOR) + 1, 'directly after the lightning overlay');
assert.equal(order.at(-1), OFFTAKERS_ID, 'last in cartridge_order');
assert.equal(e.type, 'script'); assert.equal(e.slot, 'after-cartridge'); assert.equal(e.after, ANCHOR); assert.equal(e.generation, G);
const M = String(e.module_generation || ''); assert.match(M, /^\d{12}$/);
const modulePath = path.join(ROOT, 'atlas', 'modules', `${M}-uk-offtakers-overlay.js`);
assert.equal(at(e.path), modulePath, 'the cartridge path is the module itself');
const module = fs.readFileSync(modulePath), text = module.toString('utf8');
assert.equal(sha(module), e.sha256); assert.equal(module.length, e.bytes);
assert.ok(module.length <= BUDGET && module.length <= CARTRIDGE_BYTE_BUDGETS[OFFTAKERS_ID], `${module.length} B over the ${BUDGET}-byte budget`);
assert.ok(text.startsWith(`/* uk-offtakers-overlay, generation ${M} (UTC).`), 'header names the generation');
// Files this site serves itself (data/...) are declared in site_data_sources: data_sources is read by the data-contract
// parity proof (202609012214) as Ventusltd product repositories, and a same-site entry there crashed it once G was live.
// Each one is named by the bytes; a declared SHA-256 is pinned in the bytes and is the hash of the file in this tree.
if (G > '202610290400') assert.ok(Array.isArray(e.site_data_sources) && e.site_data_sources.length, 'site_data_sources declared');
for (const d of e.data_sources || []) if (e.site_data_sources) assert.ok(d.repository && d.product, 'data_sources lists Ventusltd product repositories only; same-site files go in site_data_sources');
for (const d of e.site_data_sources || []) {
assert.match(d.url, /^https:\/\/ventusltd\.github\.io\/gridatlas\/data\//, 'a same-site data file');
assert.ok(text.includes(d.url), `the bytes name ${d.url}`);
if (d.sha256) {
assert.ok(text.includes(d.sha256), `the bytes pin ${d.id || d.url} by its SHA-256`);
assert.equal(sha(fs.readFileSync(path.join(ROOT, new URL(d.url).pathname.replace(/^\/gridatlas\//, '')))), d.sha256, `${d.url} in this tree hashes to the pin`);
}
}
// while M is listed in tools/offtakers/generations.json, it must rebuild from the committed source (the PR gate's
// offtakers-source step checks the same); a generation the source has moved past is pinned by its hash alone
const regM = (JSON.parse(fs.readFileSync(path.join(ROOT, 'tools/offtakers/generations.json'), 'utf8')).generations || {})[M], listed = !!regM && !regM.historical;
if (listed) assert.equal(build(M), text, 'rebuilds from tools/offtakers/src byte for byte');
new vm.Script(text, { filename: modulePath });
const body = text.replace(/^(\s*\/\*[\s\S]*?\*\/)*\s*/, '');
assert.ok(body.startsWith("(()=>{'use strict';") && /\}\)\(\);\s*$/.test(body), 'one strict arrow IIFE');
assert.equal((text.match(/\(\(\)=>\{'use strict'/g) || []).length, 1);
new vm.Script(`(${body.trim().replace(/;\s*$/, '')}\n)`, { filename: modulePath + '#single-expression' });
assert.equal(/ukConfig|initVentusMap|window\.fetch|data-layer-id|data-pn-layer|data-gridatlas-layer|lbl-|prepend\(|name=["']bm|<style|createElement\(['"]style|localStorage|sessionStorage|document\.cookie|ukLightning|gridatlas-lightning|__GRIDATLAS_PLACE_SEARCH__/.test(text), false, 'touches another contract');
assert.equal(/tCO2e|emission_tco2e/.test(text), false, 'no emission figure (method unverified)');
assert.equal(BANNED.test(text.replace("'Not shown here: electricity use, connection terms, consent, viability.'", '')), false, 'banned wording: ' + (text.match(BANNED) || [])[0]);
for (const needle of ['data-offtakers-control="toggle"', 'scada-ui-container', 'fs-curtain-keys', 'NS.ukOfftakers=Object.freeze(', "on:false", 'nearestSubstations', 'XMLHttpRequest', 'SHA-256',
'A listing is not electricity demand', 'Vicinity only', 'not a cable route', 'address not in register', 'not a confirmed demand, contract or connection'])
assert.ok(text.includes(needle), 'module must contain ' + JSON.stringify(needle));
/* data: the module's one data URL is a file in this repository, and its pinned SHA-256 matches the committed bytes */
const du = text.match(/DATA='https:\/\/ventusltd\.github\.io\/gridatlas\/(data\/offtakers_filtered_\d{12}\.geojson)',DSHA='([0-9a-f]{64})'/);
assert.ok(du, 'one pinned data URL under https://ventusltd.github.io/gridatlas/data/ with its SHA-256');
assert.equal(sha(fs.readFileSync(path.join(ROOT, du[1]))), du[2], du[1] + ' is committed and matches the pin');
// the URLs in the bytes: the data file and the two REPD record files of the M5 join, plus (from #73 steps 7-8) only
// same-site data files declared in site_data_sources with a SHA-256 pinned in the bytes (checked above)
const pinned = new Set((e.site_data_sources || []).filter(d => d.sha256).map(d => d.url)), urls = text.match(/https:\/\/[^'"`\s)]+/g) || [];
assert.equal(urls.filter(u => !pinned.has(u) || u === 'https://ventusltd.github.io/gridatlas/' + du[1]).length, 3, 'three URLs besides pinned same-site data files: the data file and the two REPD record files of the M5 join');
const loader = registeredLoader(path.join(ROOT, route, 'index.html'));
assert.ok(loader, `${route}index.html is not a registered loader`);
for (const slot of slotsUsed(current)) assert.ok(loader.slots.includes(slot), `${loader.name} does not support ${slot}`);
const g = await compose({ loaderHtml: fs.readFileSync(path.join(ROOT, route, 'index.html'), 'utf8'), route });
assert.equal(g.failed, false, `${route}: ${g.message} ${g.errors.join(' ')}`);
const ids = g.scripts.map(s => s.id), k = ids.indexOf(ANCHOR);
assert.equal(ids[k + 1], OFFTAKERS_ID, 'the offtakers script runs directly after the lightning overlay');
assert.equal(sha(g.scripts[k + 1].source), e.sha256, 'composed blob == module');
const tagL = g.html.match(/<script data-gridatlas-cartridge="uk-lightning-overlay" src="blob:gridatlas\/\d+"><\/script>/)[0];
const tagO = g.html.match(/\n<script data-gridatlas-cartridge="uk-offtakers-overlay" src="blob:gridatlas\/\d+"><\/script>/g);
assert.equal(tagO?.length, 1); assert.ok(g.html.includes(tagL + tagO[0]), 'tag directly after the lightning tag');
for (const c of current.cartridges.filter(c => c.id !== OFFTAKERS_ID)) {
const s = g.scripts.find(x => x.id === c.id); assert.ok(s, c.id + ' composed'); assert.equal(sha(s.source), c.sha256, c.id + ' unchanged');
}
console.log(`${G} uk-offtakers-overlay: atlas/modules/${M}-uk-offtakers-overlay.js (${module.length} B <= ${BUDGET}), ${listed ? 'rebuilt from source' : regM && regM.historical ? `historical (source: ${regM.historical})` : 'not listed, not rebuilt'}; after ${ANCHOR}; loader ${loader.name}; ${ids.length} scripts composed, every other cartridge unchanged. PASS`);
}Prepare Layer Census
A JavaScript module in the proofs folder of GridAtlas.
storagegridatlas / tools/proofs/prepare-layer-census.mjs · lines 1–12 of 12 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Uses libraries node:fs, node:vm, node:path. 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 current.json. Out: JSON file layer-config.json.
- What it achieves
- Its name says it prepares layer census.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- node:fs, node:vm, node:path
- 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/prepare-layer-census.mjs:1-12 · blob ffa53711b40bb5398547b7d0911cd6e8bdd80018 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import fs from 'node:fs';
import vm from 'node:vm';
import path from 'node:path';
const root=path.resolve(import.meta.dirname,'../..');
const current=JSON.parse(fs.readFileSync(path.join(root,'atlas/current.json')));
const html=fs.readFileSync(path.join(root,'atlas',current.shell.index),'utf8');
const code=html.slice(html.indexOf(' const ukConfig ='),html.lastIndexOf('</script>'));
let config;
vm.runInNewContext(code,{window:{initVentusMap:o=>{config=o.config;}}},{timeout:1000});
fs.mkdirSync(path.join(root,'work'),{recursive:true});
fs.writeFileSync(path.join(root,'work/layer-config.json'),JSON.stringify(config,null,2));
console.log('Captured',config.flatMap(g=>g.layers).length,'real shell layer definitions');Regional Interface Browser
A JavaScript module in the proofs folder of GridAtlas that reads grid UK Power Networks (UKPN) secondary, UKPN transformers, secondary click and 11kV.
interactiongridatlas / tools/proofs/regional-interface.browser.mjs · lines 1–269 of 269 · Entry point · pattern closed (shared by 3 files)
- What it does
- It loads grid UKPN secondary, UKPN transformers, secondary click and 11kV. Defines 9 functions or classes, including capture, readMenu, verifyFileAndMenus, open, closed. Uses libraries node:assert/strict, node:fs, playwright. Side effects: changes the web page (DOM); reads or writes files; 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. Domain terms in the code: 11kV.
- Inputs & outputs
- In: Parquet file grid_ukpn_secondary.parquet; Parquet file ukpn_transformers.parquet. Out: JSON file -secondary-click.json; JSON file receipt.json. Voltage levels named: 11kV.
- Downstream impact
- Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- It reads menu (`readMenu`) and verifies file menus (`verifyFileAndMenus`). Defines `capture`, `readMenu`, `verifyFileAndMenus` and 6 more. It writes `-secondary-click.json`.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- Serve (import), node:assert/strict, node:fs, playwright
- Used by
- run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- capture, readMenu, verifyFileAndMenus, open, closed, waitFileClosed, deny, memory, zoomTo
- Defines here
- capture, readMenu, verifyFileAndMenus, open, closed, waitFileClosed, deny, memory, zoomTo
- 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/regional-interface.browser.mjs:1-269 · blob 20c976e26d002d49724d93beca5693c943142050 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import assert from 'node:assert/strict';
import fs from 'node:fs';
import {chromium,webkit} from 'playwright';
import {createPreviewServer} from '../journey/serve.mjs';
const engine=process.env.UKPN_BROWSER==='webkit'?'webkit':'chromium';
const browser=await (engine==='webkit'?webkit:chromium).launch({headless:true,...(engine==='chromium'?{args:['--use-gl=angle','--use-angle=swiftshader','--enable-webgl','--ignore-gpu-blocklist']}: {})});
const server=await createPreviewServer();
const out='work/regional-interface-'+engine;
fs.mkdirSync(out,{recursive:true});
const receipts=[];
const archive='/grid_ukpn_secondary.parquet';
const transformer='/ukpn_transformers.parquet';
const oldArchive='/ukpn-secondary-site-transformers.zip';
try {
for(const viewport of [{width:393,height:852},{width:852,height:393},{width:1280,height:900}]){
const context=await browser.newContext({viewport,isMobile:viewport.width<1000,hasTouch:viewport.width<1000,reducedMotion:'reduce'});
const page=await context.newPage();
const base='http://127.0.0.1:'+server.address().port;
const diagnostics=[];
let stage='V9.197 baseline';
page.on('pageerror',error=>diagnostics.push({stage,event:'pageerror',message:error.message}));
page.on('console',message=>{if(message.type()==='error')diagnostics.push({stage,event:'console',message:message.text()});});
page.on('requestfailed',request=>diagnostics.push({stage,event:'requestfailed',url:request.url(),message:request.failure()?.errorText}));
const capture=async(label)=>{
const state=await page.evaluate(()=>({url:location.href,generation:window.__GRIDATLAS_ATLAS__?.generation,router:document.body?.dataset.gridatlasRouter,loader:document.querySelector('#gridatlas-loader')?.textContent,menus:[...document.querySelectorAll('#gridatlas-menu-bar .gm-panel')].map(n=>n.id),controls:[...document.querySelectorAll('#scada-ui-container input[data-layer-id]')].map(n=>({id … [line shortened here: 601 characters; full line on GitHub]
fs.writeFileSync(out+'/'+viewport.width+'-'+label+'.json',JSON.stringify({stage,state,diagnostics},null,2));
await page.screenshot({path:out+'/'+viewport.width+'-'+label+'.png',timeout:15000});
};
try {
const readMenu=()=>page.evaluate(()=>({menus:[...document.querySelectorAll('#gridatlas-menu-bar .gm-panel')].map(n=>n.id),controls:[...document.querySelectorAll('#scada-ui-container input[data-layer-id]')].filter(n=>n.dataset.layerId!=='ukpn_secondary').map(n=>[n.dataset.layerId,n.disabled]),search:!!document.querySelector('#search-input')}));
// Compare the working release and candidate by real menu interactions, not
// merely by the presence of hidden panels. Platform boundaries are labelled.
const verifyFileAndMenus=async()=>{
const titles=page.locator('#gridatlas-menu-bar .gm-title');
const names=await titles.allTextContents();
assert.deepEqual(names,['File','Edit','View','Scope','Grid','About']);
const open=async(name)=>{
const title=page.getByRole('button',{name,exact:true}).and(titles);
assert.equal(await title.count(),1);
if(await title.getAttribute('aria-expanded')!=='true')await title.click();
const panelId=await title.getAttribute('aria-controls');
const panel=page.locator('#'+panelId);
assert.equal(await title.getAttribute('aria-expanded'),'true');
assert.equal(await panel.isVisible(),true);
assert.equal(await panel.getAttribute('aria-labelledby'),await title.getAttribute('id'));
assert.equal(await page.locator('#gridatlas-menu-bar .gm-panel:not([hidden])').count(),1);
const bounds=await panel.evaluate(el=>{
const r=el.getBoundingClientRect();
return {x:r.x,y:r.y,right:r.right,bottom:r.bottom,width:r.width,height:r.height,vw:innerWidth,vh:innerHeight};
});
assert.ok(bounds.width>0&&bounds.height>0&&bounds.x>=-1&&bounds.y>=-1&&bounds.right<=bounds.vw+1&&bounds.bottom<=bounds.vh+1, name+' panel outside viewport '+JSON.stringify(bounds));
return {title,panel};
};
const closed=async(title,panel)=>{
assert.equal(await title.getAttribute('aria-expanded'),'false');
assert.equal(await panel.isVisible(),false);
};
for(const name of names){
const {title,panel}=await open(name);
await title.click();
await closed(title,panel);
await open(name);
await title.focus();
await page.keyboard.press('Escape');
await closed(title,panel);
}
const ids=['gridatlas-export-print','gridatlas-export-pdf','gridatlas-export-image','gridatlas-teleprint-pdf','gridatlas-teleprint-source'];
for(const id of ids)await page.locator('#'+id).waitFor({state:'attached',timeout:60000});
const {panel}=await open('File');
const controls=await panel.evaluate((el,ids)=>[...el.querySelectorAll('button')].filter(b=>ids.includes(b.id)).map(b=>({id:b.id,label:b.textContent.trim(),disabled:b.disabled})),ids);
assert.equal(controls.length,ids.length);
assert.ok(controls.every(c=>c.label&&!c.disabled));
// The OS print dialog is the mocked boundary; production click handler,
// capture preparation and afterprint cleanup remain active.
await page.evaluate(()=>{
window.__regionalPrintCalls=0;
window.print=()=>{window.__regionalPrintCalls++;window.dispatchEvent(new Event('afterprint'));};
});
await panel.locator('#gridatlas-export-print').click();
await page.waitForFunction(()=>window.__regionalPrintCalls===1,null,{timeout:30000});
assert.equal(await page.evaluate(()=>document.body.classList.contains('gridatlas-print-raster')),false);
// Menu actions close via a zero-delay document listener. Wait for that
// transition, rather than opening against the outgoing panel.
const fileTitle=page.getByRole('button',{name:'File',exact:true}).and(titles);
const waitFileClosed=()=>page.waitForFunction(()=>[...document.querySelectorAll('#gridatlas-menu-bar .gm-title')].find(el=>el.textContent==='File')?.getAttribute('aria-expanded')==='false');
await waitFileClosed();
// Let speculative source collection finish before checking the shared
// status element. Its asynchronous receipt must not overwrite PDF status.
await page.waitForFunction(()=>document.querySelector('#gridatlas-teleprint-status')?.textContent.startsWith('Source ready'),null,{timeout:120000});
// Override the property on Navigator itself, not a potentially ephemeral
// native MediaDevices wrapper. Preserve the boundary on both engines.
await page.evaluate(()=>{
window.__regionalCaptureCalls=0;
const deny=async()=>{window.__regionalCaptureCalls++;throw new DOMException('Permission denied','NotAllowedError');};
Object.defineProperty(navigator,'mediaDevices',{configurable:true,value:{getDisplayMedia:deny}});
if(navigator.mediaDevices.getDisplayMedia!==deny)throw new Error('capture boundary installation failed');
});
await open('File');
await page.locator('#gridatlas-teleprint-pdf').click();
await page.waitForFunction(()=>window.__regionalCaptureCalls===1&&document.querySelector('#gridatlas-teleprint-status')?.textContent.includes('Screen capture was not allowed'),null,{timeout:30000});
assert.equal(await page.evaluate(()=>window.__regionalCaptureCalls),1);
await waitFileClosed();
assert.equal(await fileTitle.getAttribute('aria-expanded'),'false');
// Real source delivery: compare downloaded bytes to the app's own panel.
await open('File');
const downloadWait=page.waitForEvent('download',{timeout:120000});
await page.locator('#gridatlas-teleprint-source').click();
const download=await downloadWait;
const source=fs.readFileSync(await download.path(),'utf8');
assert.match(download.suggestedFilename(),/\.txt$/i);
assert.ok(source.length>10000,'source delivery unexpectedly small');
const copy=page.locator('[data-teleprint="copy"]');
await copy.waitFor({state:'visible',timeout:30000});
const sourceBox=copy.locator('../..');
assert.equal(await sourceBox.locator('textarea').inputValue(),source.replace(/\r\n?/g,'\n'));
await sourceBox.getByRole('button',{name:'Close',exact:true}).click();
return {names,controls,printBoundary:'mocked window.print',pdfBoundary:'mocked permission denial',sourceBytes:Buffer.byteLength(source),sourceDelivery:'real download equals panel'};
};
await page.goto(base+'/atlas/v/202611222343/',{waitUntil:'domcontentloaded',timeout:90000});
await page.waitForFunction(()=>document.querySelectorAll('#gridatlas-menu-bar .gm-panel').length===6 && document.querySelector('#scada-ui-container input[data-layer-id="11kv"]'),null,{timeout:120000});
const baseline=await readMenu();
const baselineFile=await verifyFileAndMenus();
await capture('v9197');
stage='V9.198 historical comparison';
await page.goto(base+'/atlas/v/202612010912/',{waitUntil:'domcontentloaded',timeout:90000});
// V9.198 is the known defective comparator, not the interface oracle.
// Require its genuine native layer/control readiness (the inherited UKPN test),
// then record the actual menu state even when it differs from V9.197.
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getLayer('l-ukpn_secondary')&&document.querySelector('#scada-ui-container input[data-layer-id="ukpn_secondary"]')&&document.querySelector('#fs-curtain-keys input[data-layer-id="ukpn_secondary"]'),null,{timeout:120000});
await capture('v9198');
const historicalMenu=await readMenu();
stage='corrected candidate';
let downloads=0, bytes=0, detailDownloads=0, zipDownloads=0;
page.on('request',r=>{const p=new URL(r.url()).pathname;if(p.endsWith(archive)) downloads++;if(p.endsWith(transformer))detailDownloads++;if(p.endsWith(oldArchive))zipDownloads++;});
const cdp=engine==='chromium'?await context.newCDPSession(page):null;
const memory=async()=>cdp?await cdp.send('Runtime.getHeapUsage'):null;
page.on('response',r=>{if(new URL(r.url()).pathname.endsWith(archive)) bytes=Number(r.headers()['content-length'])||0;});
const began=Date.now();
await page.goto('http://127.0.0.1:'+server.address().port+ (process.env.UKPN_TEST_ROUTE || '/atlas/v/regional-interface-ci/'),{waitUntil:'domcontentloaded',timeout:90000});
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getLayer('l-ukpn_secondary')&&document.querySelector('#scada-ui-container input[data-layer-id="ukpn_secondary"]')&&document.querySelector('#fs-curtain-keys input[data-layer-id="ukpn_secondary"]'),null,{timeout:120000});
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__?.getSource('src-400')&&window.__GRIDATLAS_V9_MAP__.isSourceLoaded('src-400'),null,{timeout:120000});
await page.waitForFunction(()=>document.querySelectorAll('#gridatlas-menu-bar .gm-panel').length===6,null,{timeout:120000});
const candidateMenu=await readMenu();
await capture('candidate-initial');
assert.deepEqual(candidateMenu,baseline,'existing native controls and menus differ from V9.197');
const candidateFile=await verifyFileAndMenus();
assert.deepEqual(candidateFile.controls,baselineFile.controls,'File control identities, order or labels changed');
assert.equal(await page.locator('[data-ukpn-zoom-hint]').count(),0);
const startupMs=Date.now()-began;
const heapStartup=await memory();
assert.equal(detailDownloads,0);assert.equal(zipDownloads,0);
const normal=page.locator('#scada-ui-container input[data-layer-id="ukpn_secondary"]');
const full=page.locator('#fs-curtain-keys input[data-layer-id="ukpn_secondary"]');
assert.equal(await normal.isChecked(),false);
assert.equal(await full.isChecked(),false);
assert.equal(downloads,0,'secondary data must not be fetched at startup');
assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getLayer('l-ukpn_secondary').minzoom),7);
const zoomTo=zoom=>page.evaluate(z=>window.__GRIDATLAS_V9_MAP__.jumpTo({zoom:z}),zoom);
assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getLayer('l-11kv').minzoom),7);
assert.equal(await page.locator('#scada-ui-container input[data-layer-id="11kv"]').isDisabled(),false);
await zoomTo(6.99);
await normal.evaluate(el=>el.click());
assert.equal(await full.isChecked(),true,'deferred mirrored control');
assert.equal(await page.locator('[data-ukpn-zoom-hint]').count(),0);
await page.waitForTimeout(350);
assert.equal(downloads,0,'enabled below threshold must not fetch');
await normal.evaluate(el=>el.click());
await zoomTo(7);
await page.waitForTimeout(350);
assert.equal(downloads,0,'disabled layer must not fetch upon reaching threshold');
await zoomTo(6.99);
await full.evaluate(el=>el.click());
assert.equal(await normal.isChecked(),true,'deferred fullscreen mirrored control');
assert.equal(downloads,0);
const activated=Date.now();
await zoomTo(7);
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-ukpn_secondary').serialize().data?.features?.length===54558,null,{timeout:120000});
const hydrationMs=Date.now()-activated;
const historical=page.locator('#scada-ui-container input[data-layer-id="11kv"]');
await historical.evaluate(el=>el.click());
assert.equal(await normal.isChecked(),true);
assert.equal(await historical.isChecked(),true);
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.getSource('src-11kv').serialize().data?.features?.length>0,null,{timeout:120000});
assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getLayoutProperty('l-11kv','visibility')),'visible');
await historical.evaluate(el=>el.click());
assert.equal(await normal.isChecked(),true);
const heapHydrated=await memory();
assert.equal(downloads,1);assert.equal(detailDownloads,0);assert.equal(zipDownloads,0);
assert.equal(await page.evaluate(()=>window.__GRIDATLAS_UKPN_DATA__.sharedRuntime),true);
await page.evaluate(()=>{
const map=window.__GRIDATLAS_V9_MAP__;
const first=map.getSource('src-ukpn_secondary').serialize().data.features[0];
map.jumpTo({center:first.geometry.coordinates,zoom:16});
});
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.queryRenderedFeatures({layers:['l-ukpn_secondary']}).length>0,null,{timeout:60000});
// Click a real rendered feature through the browser, not through a DOM toggle.
// Pick a genuinely clickable rendered feature, not a clipped or UI-covered
// point from an arbitrary tile. Keep the real browser mouse and identity check.
const click=await page.waitForFunction(()=>{
const map=window.__GRIDATLAS_V9_MAP__, canvas=map.getCanvas();
const rect=canvas.getBoundingClientRect();
const candidates=map.queryRenderedFeatures({layers:['l-ukpn_secondary']});
for(const f of candidates){
const p=map.project(f.geometry.coordinates);
const x=rect.left+p.x,y=rect.top+p.y;
if(x<rect.left+8||x>rect.right-8||y<rect.top+8||y>rect.bottom-8||
x<8||x>innerWidth-8||y<8||y>innerHeight-8)continue;
if(document.elementFromPoint(x,y)!==canvas)continue;
const hit=map.queryRenderedFeatures(p,{layers:['l-ukpn_secondary']})[0];
if(hit?.properties?.name!==f.properties.name)continue;
return {x,y,site:f.properties.name,rendered:candidates.length};
}
return false;
},null,{timeout:60000}).then(handle=>handle.jsonValue());
fs.writeFileSync(out+'/'+viewport.width+'-secondary-click.json',JSON.stringify(click,null,2));
await page.mouse.click(click.x,click.y);
await page.waitForFunction(()=>document.querySelector('[data-ukpn-detail][data-level="full"]'),null,{timeout:15000});
const detail=page.locator('[data-ukpn-detail]');
assert.equal(await detail.getAttribute('data-site'),click.site,'selected native feature identity');
assert.match(await detail.innerText(),/Transformer count/);
await page.waitForFunction(()=>document.querySelector('[data-ukpn-detail]')?.textContent.includes('ONAN rating'),null,{timeout:60000});
assert.match(await detail.innerText(),/ONAN rating/);
assert.equal(detailDownloads,1);assert.equal(zipDownloads,0);
const heapDetails=await memory();
assert.match(await detail.innerText(),/CC BY 4.0/);
await zoomTo(15);
await page.waitForFunction(()=>document.querySelector('[data-ukpn-detail][data-level="summary"]'));
assert.doesNotMatch(await detail.innerText(),/ONAN rating/);
await zoomTo(6.99);
await page.waitForFunction(()=>!document.querySelector('[data-ukpn-detail]'));
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.queryRenderedFeatures({layers:['l-ukpn_secondary']}).length===0);
assert.equal(downloads,1);
await zoomTo(16);
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.queryRenderedFeatures({layers:['l-ukpn_secondary']}).length>0);
assert.equal(downloads,1,'zoom revisit must reuse validated native source');
for(const z of [6,11,13,14,15,16,18,6,14,16,18,13,16]){
await zoomTo(z);
if(z<7)await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__.queryRenderedFeatures({layers:['l-ukpn_secondary']}).length===0);
assert.equal(downloads,1,'zoom cycle must not reacquire archive');
}
await page.evaluate(()=>window.enterFullscreen());
await page.waitForFunction(()=>document.body.classList.contains('fs-active'));
await page.evaluate(()=>document.getElementById('fs-curtain-tab').click());
await full.evaluate(el=>el.click());
assert.equal(await normal.isChecked(),false);
assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getLayoutProperty('l-ukpn_secondary','visibility')),'none');
await full.evaluate(el=>el.click());
assert.equal(await normal.isChecked(),true);
assert.equal(downloads,1,'repeat activation must not reacquire archive');
assert.equal(await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getLayoutProperty('l-ukpn_secondary','visibility')),'visible');
await page.screenshot({path:out+'/'+viewport.width+'.png'});
assert.equal(detailDownloads,1);assert.equal(zipDownloads,0);
const heapAfterCycles=await memory();
const dataPlane=await page.evaluate(()=>window.__GRIDATLAS_UKPN_DATA__);
receipts.push({viewport,startupMs,hydrationMs,downloads,parquetContentLength:bytes,detailDownloads,zipDownloads,dataPlane,heapStartup,heapHydrated,heapDetails,heapAfterCycles,memoryScope:cdp?'Chromium page JS/V8 heap only; excludes complete worker/GPU/OS footprint':'Unavailable in WebKit',rendered:true,mirroredControls:true,transformerCard:true,zoomCycle:true,physicalSafari:false,baselineFile, … [line shortened here: 467 characters; full line on GitHub]
} catch(error) {
console.error('REGIONAL ACCEPTANCE FAILURE '+JSON.stringify({stage,viewport,message:error.message}));
await capture('failure').catch(captureError=>console.error('Failure capture: '+captureError.message));
throw error;
} finally {await context.close();}
}
console.log('UKPN browser PASS '+JSON.stringify(receipts));
} finally {
fs.writeFileSync(out+'/receipt.json',JSON.stringify(receipts,null,2));
await browser.close();
await new Promise(resolve=>server.close(resolve));
}Renewable Energy Planning Database (REPD) Deep Link Sweep Browser
A JavaScript module in the proofs folder of GridAtlas that reads REPD browser registry and the REPD register. It is built from the arg step (`arg`).
energy-datagridatlas / tools/proofs/repd-deep-link-sweep.browser.mjs · lines 1–140 of 140 · Not reached from any entry point (candidate for review)
- What it does
- It loads REPD browser registry and the REPD register. Defines arg. Uses libraries node:http, node:fs/promises, node:path, node:module, node:url. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): 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.
- Inputs & outputs
- In: JSON file current.json; JSON file repd_browser_registry_202608290716.json; command-line arguments.
- What it achieves
- Arrive on many REPD deep links, not five.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- node:http, node:fs/promises, node:path, node:module, node:url, playwright
- Used by
- none found
- Produces
- arg
- Defines here
- arg
- 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/repd-deep-link-sweep.browser.mjs:1-140 · blob 5c53d1938a7f541ff609fd5650a386abcb985a19 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* repd-deep-link-sweep.browser.mjs — arrive on many REPD deep links, not five.
*
* "test as many REPD deep links as you can" -- the architect, 2026-09-05.
*
* The existing arrival proofs check a small golden set. This sweeps a large
* sample of the published REPD corpus through the SAME arrival path and
* reports what actually happened on each one, so a defect that only shows on,
* say, the fourth technology bucket or a project with no coordinates cannot
* hide behind five green cases.
*
* It reports measurements. It does not grade a project's grid position and it
* does not decide whether a run is acceptable -- it prints per-case outcomes
* and a tally, and exits non-zero only when a case ERRORS (a thrown page
* error or a blank arrival), never merely because a project is unusual.
*
* node tools/proofs/repd-deep-link-sweep.browser.mjs [--cases 60] [--engine chromium|webkit]
* [--width 393] [--height 852]
*
* Defaults are 393x852 -- the phone -- because that is the environment the
* architect asked to be prioritised, and because this estate's defects have
* repeatedly been invisible at desktop width. WebKit is available locally and
* is a closer proxy to iOS Safari than Chromium is, but it is NOT iOS: a real
* iPhone remains the only evidence for an iOS-only fault.
*/
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const require = createRequire(import.meta.url);
const playwright = require('playwright');
function arg(flag, fallback) {
const i = process.argv.indexOf(flag);
return i > -1 && process.argv[i + 1] ? process.argv[i + 1] : fallback;
}
const CASES = Number(arg('--cases', '60'));
const ENGINE = arg('--engine', 'chromium');
const VIEWPORT = { width: Number(arg('--width', '393')), height: Number(arg('--height', '852')) };
const MIME = new Map([
['.html', 'text/html; charset=utf-8'], ['.js', 'text/javascript; charset=utf-8'],
['.mjs', 'text/javascript; charset=utf-8'], ['.json', 'application/json; charset=utf-8'],
['.css', 'text/css; charset=utf-8'], ['.wasm', 'application/wasm'],
['.parquet', 'application/octet-stream']
]);
const server = createServer(async (request, response) => {
try {
const url = new URL(request.url, 'http://127.0.0.1');
const rel = decodeURIComponent(url.pathname).replace(/^\/+/, '');
const file = path.join(ROOT, rel);
if (!file.startsWith(ROOT)) { response.writeHead(403).end(); return; }
const body = await readFile(file);
response.writeHead(200, { 'content-type': MIME.get(path.extname(file)) || 'application/octet-stream' });
response.end(body);
} catch {
response.writeHead(404).end();
}
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const current = JSON.parse(await readFile(path.join(ROOT, 'atlas', 'current.json'), 'utf8'));
console.log(`generation ${current.generation} · ${ENGINE} · ${VIEWPORT.width}x${VIEWPORT.height} · ${CASES} cases\n`);
/* This used to read the rows out of repd_v9_manifest_202608290716.json, which
has never contained any: it is a descriptor carrying generation, schema,
closure counts and the paths to the real data. `manifest.projects ||
manifest.rows || manifest.features` was therefore always [], the sample was
always empty, and this sweep printed "arrived 0 · no identity 0 · page error
0 (of 0)" and exited 0 — reporting green having tested nothing, on every run
since it was written. The corpus is the browser registry, which is on disk,
so this now needs no network at all. */
const registry = JSON.parse(await readFile(path.join(ROOT, 'data', 'repd_browser_registry_202608290716.json'), 'utf8'));
const rows = (registry.records || []).filter(r => r && (r.repd_ref || r.ref || r.repd_id));
/* Spread the sample across the corpus rather than taking the first N, so a
defect confined to one technology or one region cannot be sampled away. */
const step = Math.max(1, Math.floor(rows.length / CASES));
const sample = [];
for (let i = 0; i < rows.length && sample.length < CASES; i += step) sample.push(rows[i]);
/* An empty sample is a broken harness, not a passing run. */
if (!sample.length) {
console.error(`no cases selected from ${rows.length} registry rows — harness fault, not a green run`);
server.close();
process.exit(2);
}
const browser = await playwright[ENGINE].launch();
const context = await browser.newContext({ viewport: VIEWPORT, deviceScaleFactor: 3, isMobile: true, hasTouch: true });
const tally = { arrived: 0, no_identity: 0, page_error: 0 };
const failures = [];
for (const row of sample) {
const ref = row.repd_ref || row.ref || row.repd_id;
const lat = row.latitude ?? row.lat;
const lon = row.longitude ?? row.lon;
const tech = row.technology || row.tech || '';
const params = new URLSearchParams({ repd_ref: String(ref) });
if (tech) params.set('technology', String(tech));
if (lat != null && lon != null) { params.set('latitude', String(lat)); params.set('longitude', String(lon)); params.set('zoom', '9'); }
const page = await context.newPage();
const errors = [];
page.on('pageerror', e => errors.push(String(e && e.message || e)));
try {
await page.goto(`${base}/atlas/index.html?${params}`, { waitUntil: 'domcontentloaded', timeout: 45000 });
/* The arrival is identified by the page itself; wait for the identity to
appear rather than for a fixed time, and cap the wait so one bad case
cannot stall the sweep. */
const identity = await page.waitForFunction(() => {
const t = document.body ? document.body.innerText : '';
return /REPD|repd_ref|Measuring|measured/i.test(t) ? t.slice(0, 400) : null;
}, { timeout: 30000 }).then(h => h.jsonValue()).catch(() => null);
if (errors.length) { tally.page_error += 1; failures.push({ ref, why: 'page error', detail: errors[0].slice(0, 160) }); }
else if (!identity) { tally.no_identity += 1; failures.push({ ref, why: 'no arrival identity within 30s', detail: `${tech} ${lat},${lon}` }); }
else { tally.arrived += 1; }
} catch (e) {
tally.page_error += 1;
failures.push({ ref, why: 'navigation failed', detail: String(e.message || e).slice(0, 160) });
}
await page.close();
process.stdout.write(`${tally.arrived + tally.no_identity + tally.page_error}/${sample.length}\r`);
}
await browser.close();
server.close();
console.log(`\narrived ${tally.arrived} · no identity ${tally.no_identity} · page error ${tally.page_error} (of ${sample.length})\n`);
for (const f of failures.slice(0, 25)) console.log(` ref ${f.ref}: ${f.why} -- ${f.detail}`);
if (failures.length > 25) console.log(` … and ${failures.length - 25} more`);
process.exit(tally.page_error > 0 ? 1 : 0);Run Current
A JavaScript module in the proofs folder of GridAtlas that runs the proof belonging to the cartridge that is actually composed.
electricalgridatlas / tools/proofs/run-current.mjs · lines 1–62 of 62 · Entry point
- What it does
- It loads data. Uses libraries node:fs, node:path, node:url. 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 current.json.
- Downstream impact
- Used directly by 7 files: Local CI (gridatlas); CI PR Gate (gridatlas); Shift (gridatlas); GridAtlas — Release (gridatlas); and 3 more. Reached from 25 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); GridAtlas Verify Live Workflow (gridatlas); Acceptance (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 7 workflows and scripts, including Local CI, CI PR Gate and Shift.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- node:fs, node:path, node:url
- Used by
- run by Local CI (script call), run by CI PR Gate (script call), run by Shift (script call), run by GridAtlas — Release (script call), run by GridAtlas Scope Loop Workflow (workflow run), run by GridAtlas Cartridge Proof Workflow (workflow run), run by GridAtlas Rollback Composition 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/proofs/run-current.mjs:1-62 · blob 1085c55925157abb1740d303aa0edc14c91c858e · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
* Run the proof belonging to the cartridge that is actually composed.
*
* The proofs are timestamped and so is the cartridge, so a workflow that names
* either one goes stale the next time a generation is cut -- and a stale proof
* step is worse than none, because it passes while testing a file nobody
* serves. This resolves the generation from atlas/current.json, which is the
* thing the loader reads, and runs the proof that matches it.
*
* A cartridge with no proof is a failure, not a skip. Every cartridge in this
* repository has carried one, and the moment that stops being enforced is the
* moment one ships without.
*
* node tools/proofs/run-current.mjs
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const current = JSON.parse(
fs.readFileSync(path.join(ROOT, 'atlas', 'current.json'), 'utf8'));
const failures = [];
let ran = 0;
for (const id of current.cartridge_order || []) {
const cartridge = (current.cartridges || []).find(entry => entry.id === id);
if (!cartridge) {
failures.push(`${id}: named in cartridge_order but absent from cartridges`);
continue;
}
const proof = path.join(ROOT, 'tools', 'proofs',
`${cartridge.generation}-${id}.proof.mjs`);
if (!fs.existsSync(proof)) {
failures.push(`${id} ${cartridge.generation}: no proof at ${path.relative(ROOT, proof)}`);
continue;
}
console.log(`\n=== ${id} ${cartridge.generation} ===`);
try {
await import(pathToFileURL(proof).href);
ran += 1;
} catch (error) {
failures.push(`${id}: ${error?.message || error}`);
}
if (process.exitCode) {
failures.push(`${id}: proof reported failures`);
process.exitCode = 0;
}
}
console.log(`\nproofs run: ${ran}`);
if (failures.length) {
for (const failure of failures) console.error(` FAIL ${failure}`);
process.exitCode = 1;
} else if (ran === 0) {
console.error(' FAIL no proof ran for any composed cartridge');
process.exitCode = 1;
} else {
console.log('every composed cartridge passed its generation-matched proof');
}