In this section
- Overlay Smoke test · energy-transition-simulator / tests/overlay-smoke.cjs lines 1–50
- Plan View test · energy-transition-simulator / tests/plan-view.cjs lines 1–246
- Privacy Scan test · energy-transition-simulator / tests/privacy-scan.cjs lines 1–41
- Procedural test · energy-transition-simulator / tests/procedural.cjs lines 1–198
- Scanner Rows Test test · energy-transition-simulator / tests/scanner-rows.test.cjs lines 1–69
- Tables test · energy-transition-simulator / tests/tables.cjs lines 1–58
Overlay Smoke
A JavaScript module in the tests folder of Energy Transition Simulator that tests solar and 400kV.
testenergy-transition-simulator / tests/overlay-smoke.cjs · lines 1–50 of 50 · Entry point
- What it does
- It tests solar and 400kV. Uses libraries http, fs, path, playwright. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (voltage levels 400kV (all 132kV or above)): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, 400kV.
- Inputs & outputs
- Out: JSON file results.json. Voltage levels named: 400kV.
- Downstream impact
- It is itself an entry point (JavaScript module); no other file was found loading it.
- What it achieves
- Smoke test for the GridAtlas overlay: serves `prototype/` on a local port, opens `overlay.html` headless, and checks what a player would see. Its code works with 400 kV.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- energy-transition-simulator · tests · JavaScript module
- Uses
- http, fs, path, playwright
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/overlay-smoke.cjs:1-50 · blob 982ca95e654f702dcd8e9fdc2bf80d3bf5c34fe0 · 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: unknown
// Smoke test for the GridAtlas overlay: serves prototype/ on a local port, opens overlay.html headless, and checks
// what a player would see. Runs the same on a PC (GPU or not) and in GitHub Actions (software WebGL).
// Every check is PASS or FAIL with evidence; screenshots go to test-output/ (uploaded as a CI artifact).
const http = require('http'), fs = require('fs'), path = require('path');
const { chromium } = require('playwright');
const ROOT = path.join(__dirname, '..', 'prototype'), OUT = path.join(__dirname, '..', 'test-output');
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json' };
fs.mkdirSync(OUT, { recursive: true });
const server = http.createServer((q, s) => {
const f = path.join(ROOT, decodeURIComponent(q.url.split('?')[0]).replace(/^\/+/, '') || 'overlay.html');
if (!f.startsWith(ROOT) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { s.writeHead(404); return s.end(); }
s.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(s);
});
const results = []; const check = (name, ok, evidence) => results.push({ name, ok: !!ok, evidence: String(evidence).slice(0, 200) });
(async () => {
await new Promise(r => server.listen(0, '127.0.0.1', r));
const base = `http://127.0.0.1:${server.address().port}/overlay.html`;
const b = await chromium.launch({ channel: process.env.CI ? undefined : 'chrome', args: process.env.CI ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist'] });
const p = await b.newPage({ viewport: { width: 1280, height: 800 } });
const errs = [], missing = []; p.on('pageerror', e => errs.push(e.message));
p.on('response', r => { if (r.status() === 404 && r.url().startsWith('http://127.0.0.1')) missing.push(r.url().replace(/^http:\/\/127\.0\.0\.1:\d+/, '')); });
// 1. The map loads at a 400 kV line (GridAtlas coordinates) and the core buttons exist.
await p.goto(`${base}?lat=52.2441634&lon=-1.0453368`, { waitUntil: 'load' }); await p.waitForTimeout(9000);
check('no missing local files (404)', missing.length === 0, missing.join(' | ') || 'none');
check('window.SIM exists (the app started)', await p.evaluate(() => !!window.SIM), 'window.SIM');
const btns = await p.$$eval('button', bs => bs.map(x => x.textContent.trim())); // controls live in the menu bar now (lane/ui), so look anywhere on the page
for (const need of ['Satellite', 'Dark', 'Wire', 'Walk', 'Drone', 'Map', 'Pylons']) check(`button ${need}`, btns.some(t => t.startsWith(need)), btns.join(' | '));
check('map canvas', await p.$('canvas.maplibregl-canvas'), 'maplibre canvas present');
// 2. Pylons stand on GridAtlas line vertices.
await p.evaluate(() => document.querySelector('#pylons').click()); await p.waitForTimeout(3000);
const pl = await p.textContent('#pylons'); const n = Number((pl.match(/\((\d+)\)/) || [])[1] || 0);
check('pylons on the 400 kV line', n > 0, pl); await p.screenshot({ path: path.join(OUT, '1-pylons.png') });
// 3. Walk and drone move you (the readout changes).
const before = await p.textContent('#here-readout').catch(() => '');
await p.evaluate(() => document.querySelector('#walk').click()); await p.waitForTimeout(2500); await p.keyboard.down('w'); await p.waitForTimeout(1500); await p.keyboard.up('w'); await p.waitForTimeout(800);
const after = await p.textContent('#here-readout').catch(() => '');
check('walking moves you', before && after && before !== after, `${before} -> ${after}`); await p.screenshot({ path: path.join(OUT, '2-walk.png') });
await p.evaluate(() => document.querySelector('#drone').click()); await p.waitForTimeout(2500); await p.screenshot({ path: path.join(OUT, '3-drone.png') });
// 4. The wire view (morning engine look) keeps the objects.
await p.evaluate(() => document.querySelector('#wire').click()); await p.waitForTimeout(2500); await p.screenshot({ path: path.join(OUT, '4-wire.png') });
// 5. No names on screen: the page text holds no project name words from the public register (spot check: no "Solar Farm" label).
const text = await p.evaluate(() => document.body.innerText);
check('no project names on screen', !/solar farm|solar park/i.test(text), 'page text scanned');
check('no page errors', errs.length === 0, errs.join(' | ') || 'none');
await b.close(); server.close();
fs.writeFileSync(path.join(OUT, 'results.json'), JSON.stringify(results, null, 1));
for (const r of results) console.log(`${r.ok ? 'PASS' : 'FAIL'} ${r.name} -- ${r.evidence}`);
const failed = results.filter(r => !r.ok).length; console.log(`\n${results.length - failed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
})().catch(e => { console.error(e); server.close(); process.exit(2); });Plan View
A JavaScript module in the tests folder of Energy Transition Simulator that tests 400kV, the Renewable Energy Planning Database (REPD) register, substations and LiDAR terrain.
testenergy-transition-simulator / tests/plan-view.cjs · lines 1–246 of 246 · Not reached from any entry point (candidate for review) · pattern modList (shared by 3 files)
- What it does
- It tests 400kV, the REPD register, substations and LiDAR terrain. Defines 12 functions or classes, including modList, launch, state, ready, idle. Uses libraries http, fs, path, playwright. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (voltage levels 400kV (all 132kV or above)): 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, the REPD register, substations, LiDAR terrain.
- Inputs & outputs
- In: JSON file index.json; command-line arguments. Voltage levels named: 400kV.
- What it achieves
- It is built from the mod list helper (`modList`), the launch step (`launch`) and the state step (`state`). Plan view check (`mod/plan-view.js` + `mod/morph.js`). Its code works with 400 kV. It reads `mod/index.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · tests · JavaScript module
- Uses
- http, fs, path, playwright
- Used by
- none found
- Produces
- modList, launch, state, ready, idle, shot, grab, diff, settle, pc, press, viaMode
- Defines here
- modList, launch, state, ready, idle, shot, grab, diff, settle, pc, press, viaMode
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/plan-view.cjs:1-246 · blob 122c883c1f089d9dc8169fb25cf8836f862cb0d7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// Plan view check (mod/plan-view.js + mod/morph.js). What it proves:
// - View > Plan, the key P and the typed "plan"; north-up and flat; the scale bar and north arrow; imagery dimmed, the
// 3D wire hidden not restyled; the 2D drawing comes from the blocks on the map; the grid-reference line is kept.
// - Something by default at a register asset: P at the farm switches the scanner rows, the procedural fill and the AC
// trench model on by itself, one label per object class.
// - The MORPH into the wireframe: past z17.5 the world rises from flat to 3D over about 1.2 s (heights 0 -> 1 with the
// pitch 0 -> 60) and back out past z16.5; held frames of a real morph change by under 10 % of pixels between
// consecutive frames, the plan frame to the first morph frame included (the wire fades in, it does not pop).
// - The state machine: P from Walk (deeper than z17.5) eases out to z16.5 flat, a wheel in then ends at pitch 60 with
// every height back at 1; a "go" from plan leaves plan, legend included.
// - Leaving plan: Walk, Drone and Map (View menu or keys 1 2 3) give plan off and the mode's own camera; a Drone key
// pressed while plan is still switching modules on gives Drone's camera and presses no further module button.
// Serves prototype/ on a local port. mod/index.json is NOT edited: the server answers it with the SHIPPED list (minus
// morph and plan-view if present) plus morph and plan-view before menu-bar, which stays last, exactly as the lead
// switches them on. No other module is added.
// node tests/plan-view.cjs [outDir]
// Env: UI_LAUNCHER (a module exporting launch(); default playwright Chrome with ANGLE d3d11), SHOTS=1 for the
// review pictures (a solar farm in plan, three frames of the ease at a substation, a 400 kV line in plan).
// Every check prints PASS or FAIL with evidence; exit code 1 on any FAIL.
const http = require('http'), fs = require('fs'), path = require('path');
const ROOT = path.join(__dirname, '..', 'prototype');
const OUT = process.argv[2] || path.join(__dirname, '..', 'test-output', 'plan-view');
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json' };
const FARM = { lat: 51.33877, lon: 0.91389 }; // REPD 6502 register point (public register)
const LINE = { lat: 52.2441634, lon: -1.0453368 }; // on a mapped 400 kV line (the UI check's default)
const SHOTS = process.env.SHOTS === '1';
fs.mkdirSync(OUT, { recursive: true });
function modList() {
const l = JSON.parse(fs.readFileSync(path.join(ROOT, 'mod', 'index.json'), 'utf8')).filter(n => n !== 'plan-view' && n !== 'morph');
const i = l.indexOf('menu-bar'); if (i >= 0) l.splice(i, 0, 'morph', 'plan-view'); else l.push('morph', 'plan-view');
return l;
}
const server = http.createServer((q, s) => {
const u = decodeURIComponent(q.url.split('?')[0]).replace(/^\/+/, '') || 'overlay.html';
if (u === 'mod/index.json') { s.writeHead(200, { 'Content-Type': 'application/json' }); return s.end(JSON.stringify(modList())); }
const f = path.join(ROOT, u);
if (!f.startsWith(ROOT) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { s.writeHead(404); return s.end(); }
s.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(s);
});
const results = []; const check = (name, ok, evidence) => { results.push({ name, ok: !!ok }); console.log(`${ok ? 'PASS' : 'FAIL'} ${name} :: ${String(evidence).slice(0, 400)}`); };
async function launch() {
if (process.env.UI_LAUNCHER) return require(process.env.UI_LAUNCHER).launch();
const { chromium } = require('playwright');
return chromium.launch({ channel: process.env.CI ? undefined : 'chrome', args: process.env.CI ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist'] });
}
const state = p => p.evaluate(() => window.SIM.plan.state());
async function ready(p) {
await p.waitForFunction(() => window.SIM && document.querySelector('canvas.maplibregl-canvas') && window.SIM.plan, null, { timeout: 30000 });
await p.waitForTimeout(6000);
}
const idle = p => p.evaluate(() => new Promise(r => { const m = window.SIM.map; let done = false; const f = () => { if (!done) { done = true; r(); } }; m.once('idle', f); setTimeout(f, 8000); m.triggerRepaint(); }));
const shot = async (p, name) => { if (SHOTS) { await p.screenshot({ path: path.join(OUT, name) }); console.log('shot ' + name); } };
(async () => {
await new Promise(r => server.listen(0, '127.0.0.1', r));
const port = server.address().port, url = at => `http://127.0.0.1:${port}/overlay.html?lat=${at.lat}&lon=${at.lon}`;
const b = await launch(), errs = [];
const p = await b.newPage({ viewport: { width: 1600, height: 1000 } }); p.on('pageerror', e => errs.push(e.message));
await p.goto(url(FARM), { waitUntil: 'load' }); await ready(p);
check('window.SIM and the map canvas', await p.evaluate(() => !!window.SIM && !!document.querySelector('canvas.maplibregl-canvas')), 'SIM + canvas');
const where = await p.evaluate(() => { const el = document.getElementById('plan-view'); const pan = el && el.closest('.gm-panel'); return { found: !!el, menu: pan ? pan.dataset.menu : (el && el.parentElement ? el.parentElement.id : ''), label: el ? el.textContent : '' }; });
check('View > Plan is in the View menu', where.found && where.menu === 'View', JSON.stringify(where));
const mods = await p.evaluate(() => fetch('mod/index.json').then(r => r.json()));
const shipped = JSON.parse(fs.readFileSync(path.join(ROOT, 'mod', 'index.json'), 'utf8'));
check('module list = shipped index.json + morph + plan-view before menu-bar, nothing else', JSON.stringify(mods.filter(n => n !== 'plan-view' && n !== 'morph')) === JSON.stringify(shipped.filter(n => n !== 'plan-view' && n !== 'morph')) && mods.indexOf('plan-view') === mods.indexOf('menu-bar') - 1 && mods.indexOf('morph') === mods.indexOf('plan-view') - 1 && !mods.includes('gpu-rows'), mods.join … [line shortened here: 407 characters; full line on GitHub]
// 0. Something by default: P on arrival at the farm (Drone first, as the lead's look does), nothing else pressed.
await p.evaluate(() => document.querySelector('#drone').click()); await p.waitForTimeout(4000); await idle(p);
await p.mouse.click(800, 600); await p.keyboard.press('p'); await p.waitForTimeout(16000); await idle(p);
let s = await state(p);
const dflt = await p.evaluate(() => ({ scanner: window.SIM.blocks.filter(b => b.scannerRows && !b.registerPoint).length, procedural: window.__procedural ? window.__procedural.ghostBlocks : 0,
trenches: window.__acTrenches ? window.__acTrenches.state().on : null, bunds: window.SIM.map.getLayer('act-bunds') ? 1 : 0,
labels: Array.from(document.querySelectorAll('#plan-labels .plan-label')).map(e => e.textContent) }));
const uniq = new Set(dflt.labels.map(t => t.replace(/ x\d+$/, '')));
check('P at the farm shows rows, the procedural fill and the trench model by itself', s.on && dflt.scanner > 0 && dflt.procedural > 0 && dflt.trenches === true && s.auto && s.auto.scanner && s.auto.procedural && s.auto.trenches,
JSON.stringify({ scanner: dflt.scanner, procedural: dflt.procedural, trenches: dflt.trenches, auto: s.auto, pitch: s.pitch, zoom: s.zoom }));
check('one label per object class', dflt.labels.length > 0 && uniq.size === dflt.labels.length && dflt.labels.length <= 12, dflt.labels.join(' | '));
await shot(p, '00-farm-P-default.png');
// 0b. A real morph, frame by frame (SIM.plan.frame holds one frame of it), the canvas read back after each paint and
// compared with the frame before: the share of sampled pixels that changed (any channel by more than 32). Steps of
// 0.02 in eased progress, above the largest step a 60 fps 1.2 s cubic makes (0.021). Two series: `fixed` is the
// change the morph itself makes at each step (the same camera, heights and wire fade one step apart; the plan lines
// fade 2 % a step, under the threshold), which is what must stay under 10 %, the plan frame to the first morph frame
// (frame 0: the wire shown, faded to nothing) included; `moving` is the raw consecutive change with the camera
// pitching 1.2 degrees a step, printed as evidence (the imagery itself moves; it is not the criterion).
const px = await p.evaluate(async () => {
const m = window.SIM.map, gl = m.painter.context.gl, W = gl.drawingBufferWidth, H = gl.drawingBufferHeight, S = 4;
const grab = () => new Promise(r => { m.once('render', () => { const b = new Uint8Array(W * H * 4); gl.readPixels(0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE, b); r(b); }); m.triggerRepaint(); });
const diff = (a, b) => { let n = 0, d = 0; for (let y = 0; y < H; y += S) for (let x = 0; x < W; x += S) { const i = (y * W + x) * 4; n++; if (Math.abs(a[i] - b[i]) > 32 || Math.abs(a[i + 1] - b[i + 1]) > 32 || Math.abs(a[i + 2] - b[i + 2]) > 32) d++; } return +(d / n).toFixed(4); };
const settle = () => new Promise(r => setTimeout(r, 60));
const plan = await grab(); let prev = plan; const fixed = [], moving = [];
for (let k = 0; k <= 50; k++) {
const e = k / 50; window.SIM.plan.frame(e); await settle(); const cur = await grab(); moving.push(diff(prev, cur));
if (k === 0) fixed.push(diff(plan, cur)); else { window.SIM.morph.set((k - 1) / 50); await settle(); const back = await grab(); fixed.push(diff(back, cur)); window.SIM.morph.set(e); }
prev = cur;
}
const st = window.SIM.morph.state();
window.SIM.plan.frame(0); await settle(); await grab();
return { fixed, moving, first: fixed[0], max: Math.max(...fixed), movingMax: Math.max(...moving), fade: st.fade, faded: st.totals.faded };
});
const pc = v => Math.round(v * 1000) / 10;
check('a real morph changes under 10 % of pixels a frame at a fixed camera, the plan frame to the first morph frame included', px.first < 0.1 && px.max < 0.1 && px.fade.includes('wire') && px.faded > 0,
JSON.stringify({ first: pc(px.first), maxFixed: pc(px.max), maxMovingCamera: pc(px.movingMax), fadedDraws: px.faded, fade: px.fade, fixed: px.fixed.map(pc).join(' '), moving: px.moving.map(pc).join(' ') }));
await p.waitForTimeout(400);
await p.keyboard.press('p'); await p.waitForTimeout(1800);
// What the SHIPPED modules give at the farm, switched on by their own buttons: scanner rows, the procedural wire,
// Connect here (then trench-measure's "trench auto"), the lidar-stream ground tile. Pylons and substations are on by default.
const press = t => p.evaluate(t => { const b = Array.from(document.querySelectorAll('button')).find(x => x.textContent.trim().startsWith(t)); if (b && !b.classList.contains('on')) b.click(); return !!b; }, t);
const pressed = {}; for (const t of ['Connect here', 'Stream ground']) { pressed[t] = await press(t); await p.waitForTimeout(2500); }
await p.evaluate(() => new Promise(r => { const t0 = Date.now(); (function go() { if (window.__connect && window.__trench) { window.__trench.cmd('trench auto'); setTimeout(r, 2500); } else if (Date.now() - t0 < 20000) setTimeout(go, 500); else r(); })(); }));
await p.evaluate(at => window.SIM.map.jumpTo({ center: [at.lon, at.lat], zoom: 14.6, pitch: 55, bearing: -20 }), FARM); await p.waitForTimeout(3000); await idle(p);
const give = await p.evaluate(() => ({ scanner: window.SIM.blocks.filter(b => b.scannerRows === 'REPD 6502' && !b.registerPoint).length,
procedural: window.__procedural ? window.__procedural.ghostBlocks : 0, connect: !!window.__connect, trench: window.__trench ? window.__trench.blocks().length : 0,
lidar: window.SIM.blocks.filter(b => b.lidarStream).length + (window.SIM.map.getLayer('lidar-stream-sat') ? '+sat layer' : '') }));
console.log('shipped modules at REPD 6502: ' + JSON.stringify({ pressed, give }));
// 1. The key P: plan, north-up, flat, dimmed, wire hidden, scale bar.
await p.mouse.click(800, 600); await p.keyboard.press('p'); await p.waitForTimeout(1800); await idle(p);
s = await state(p);
check('P: plan on, pitch 0 and bearing 0', s.on && Math.abs(s.pitch) < 0.01 && Math.abs(s.bearing) < 0.01, JSON.stringify({ on: s.on, pitch: s.pitch, bearing: s.bearing }));
check('the scale bar is present', s.scaleBar && s.scaleM > 0 && s.scalePx > 20 && s.scalePx <= 120, `${s.scaleM} m = ${s.scalePx} px`);
const north = await p.evaluate(() => { const n = document.querySelector('#plan-hud .plan-north'); return !!n && getComputedStyle(document.getElementById('plan-hud')).display !== 'none'; });
check('the north arrow is present', north, 'svg.plan-north');
check('imagery dimmed and the 3D wire hidden, not restyled', s.dimmed >= 1 && s.hidden.includes('wire'), JSON.stringify({ dimmed: s.dimmed, hidden: s.hidden }));
check('the 2D drawing comes from blocks on the map', s.lines > 0, `${s.lines} plan segments, ${s.labels} labels [${Array.from(new Set(s.labelProv)).join(',')}] kinds ${JSON.stringify(s.kinds)}`);
const rowsAt = !!s.kinds['scanner-rows'];
console.log(rowsAt ? `ROWS: scanner-rows (shipped) gives ${s.kinds['scanner-rows']} row blocks at REPD 6502 in plan (estimated from imagery)` : 'ROWS: NO rows at REPD 6502 in plan from the shipped modules; plan shows only ' + JSON.stringify(s.kinds));
await p.evaluate(txt => { let c = document.getElementById('plan-test-caption'); if (!c) { c = document.createElement('div'); c.id = 'plan-test-caption'; c.style.cssText = 'position:fixed;left:10px;bottom:40px;z-index:30;font:12px ui-monospace,Consolas,monospace;color:#d5dcea;background:rgba(9,12,19,.85);padding:4px 8px;border:1px solid #1a2030;pointer-events:none'; document.body.appendChild(c); … [line shortened here: 425 characters; full line on GitHub]
'TEST SHOT. Shipped modules only (index.json + plan-view). Plan draws: ' + Object.entries(s.kinds).map(([k, v]) => k + ' ' + v).join(', ') + (rowsAt ? '' : '. No rows at REPD 6502 from shipped modules.'));
const gref = await p.evaluate(() => { const w = document.getElementById('where'); return w ? w.textContent : ''; });
check('the grid-reference line is kept', /^[A-Z]{2} \d{4} \d{4}/.test(gref), gref);
await shot(p, '01-farm-6502-plan.png');
await p.evaluate(() => { const c = document.getElementById('plan-test-caption'); if (c) c.remove(); });
// 1b. Leaving plan by a mode: plan off, the mode's own pitch and zoom, bearing kept (turned to 30 in plan first).
const MODES = { walk: [80, 18.5], drone: [60, 16.5], map: [0, 14] };
const viaMode = async (how, m) => {
await p.evaluate(at => window.SIM.map.jumpTo({ center: [at.lon, at.lat], zoom: 14.6 }), FARM);
if (!(await state(p)).on) await p.evaluate(() => window.SIM.plan.on());
await p.waitForTimeout(1600); await p.evaluate(() => window.SIM.map.jumpTo({ bearing: 30 })); await p.waitForTimeout(300);
const before = await state(p);
if (how === 'menu') await p.evaluate(m => { window.SIM.menu.open('View'); const it = Array.from(document.querySelectorAll('.gm-panel[data-menu="View"] button')).find(b => b.textContent.startsWith(m[0].toUpperCase() + m.slice(1) + ' (')); it.click(); }, m);
else { await p.mouse.click(800, 600); await p.keyboard.press(how); }
await p.waitForTimeout(2200);
const a = await state(p), spd = await p.evaluate(() => (document.getElementById('spd') || {}).textContent || '');
const [P, Z] = MODES[m];
check(`from plan, ${m} (${how === 'menu' ? 'View menu' : 'key ' + how}): plan off, pitch ${P}, zoom ${Z}, bearing kept, ${m} speed`,
before.on && !a.on && !a.in3d && Math.abs(a.pitch - P) < 0.5 && Math.abs(a.zoom - Z) < 0.05 && Math.abs(a.bearing - 30) < 0.5 && spd.startsWith(m + ' ') &&
a.eases.length === before.eases.length && a.dimmed === 0 && a.hidden.length === 0 && a.morphT === 1 && a.morphActive === false,
JSON.stringify({ before: before.on, on: a.on, pitch: a.pitch, zoom: a.zoom, bearing: a.bearing, spd, newEases: a.eases.length - before.eases.length, left: a.left.slice(-1) }));
};
await viaMode('menu', 'walk'); await shot(p, '01b-walk-from-plan.png');
await viaMode('1', 'walk'); await viaMode('2', 'drone'); await viaMode('menu', 'drone'); await viaMode('3', 'map'); await viaMode('menu', 'map');
await p.evaluate(at => window.SIM.map.jumpTo({ center: [at.lon, at.lat], zoom: 14.6, pitch: 55, bearing: -20 }), FARM); await p.waitForTimeout(1500);
await p.mouse.click(800, 600); await p.keyboard.press('p'); await p.waitForTimeout(1800); await idle(p);
// 1c. The state machine from Walk: P deeper than z17.5 eases out to z16.5 flat; a wheel in then morphs to pitch 60
// with every height back at 1 (the overlay's u_zscale read back from the GPU where the wire's own program is in use).
await p.keyboard.press('p'); await p.waitForTimeout(1800);
await p.evaluate(at => window.SIM.map.jumpTo({ center: [at.lon, at.lat] }), FARM); await p.keyboard.press('1'); await p.waitForTimeout(1500);
const walkS = await state(p);
await p.keyboard.press('p'); await p.waitForTimeout(2000); await idle(p);
const flatS = await state(p);
check('P from Walk (z18.5): plan on, eased out to z16.5, flat, north-up', !walkS.on && Math.abs(walkS.zoom - 18.5) < 0.05 && flatS.on && !flatS.in3d && Math.abs(flatS.zoom - 16.5) < 0.05 && Math.abs(flatS.pitch) < 0.01 && Math.abs(flatS.bearing) < 0.01 && flatS.hidden.includes('wire'),
JSON.stringify({ walk: { zoom: walkS.zoom, pitch: walkS.pitch }, plan: { zoom: flatS.zoom, pitch: flatS.pitch, on: flatS.on, morphT: flatS.morphT } }));
await p.evaluate(() => window.SIM.map.zoomTo(18, { duration: 300 })); await p.waitForTimeout(2200); await idle(p);
const upS = await state(p), zsc = await p.evaluate(() => { try { const m = window.SIM.map, gl = m.painter.context.gl, pr = m.getLayer('wire').implementation.pr, l = gl.getUniformLocation(pr, 'u_zscale'); return l ? gl.getUniform(pr, l) : 'no u_zscale in the current program (wire-look draws the wire with its own fading program; the morph scales the matrix there)'; } catch (e) { return 'err ' + e. … [line shortened here: 414 characters; full line on GitHub]
const up = upS.morphs.filter(m => m.dir === 'up').pop();
check('wheel in from that plan ends at pitch 60 with every height at 1 (morph up over about 1.2 s)', upS.on && upS.in3d && Math.abs(upS.pitch - 60) < 0.5 && upS.morphT === 1 && upS.morphActive === false && !upS.hidden.includes('wire') && up && up.full && up.ms >= 1100 && up.ms <= 1800 && up.frames >= 20 && (zsc === 1 || typeof zsc === 'string'),
JSON.stringify({ pitch: upS.pitch, zoom: upS.zoom, morphT: upS.morphT, active: upS.morphActive, morph: up, u_zscale: zsc }));
// "go" from plan leaves plan, legend included (a lat, lon go: no network; the same flyTo path as a postcode go).
await p.evaluate(() => window.SIM.map.zoomTo(16, { duration: 300 })); await p.waitForTimeout(2200); await idle(p);
const backS = await state(p);
await p.evaluate(() => { const i = document.getElementById('fg-in'); i.value = 'go 51.5014, -0.1419'; i.focus(); i.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); });
await p.waitForTimeout(1500);
const goS = await state(p), legend = await p.evaluate(() => ({ hud: document.getElementById('plan-hud').hidden, layers: ['plan-measured', 'plan-documented', 'plan-estimated', 'plan-g400', 'plan-subs'].filter(id => !!window.SIM.map.getLayer(id)), labels: document.querySelectorAll('#plan-labels .plan-label').length }));
check('"go" from plan leaves plan: legend gone, plan layers removed, dim and hides restored, heights at 1', backS.on && !backS.in3d && !goS.on && legend.hud === true && legend.layers.length === 0 && legend.labels === 0 && goS.dimmed === 0 && goS.hidden.length === 0 && goS.morphT === 1 && goS.left.slice(-1)[0].why === 'go',
JSON.stringify({ wasPlan: backS.on, on: goS.on, legend, left: goS.left.slice(-1)[0], morphT: goS.morphT }));
await p.waitForTimeout(4000); await shot(p, '01c-after-go.png');
await p.evaluate(at => window.SIM.map.jumpTo({ center: [at.lon, at.lat], zoom: 14.6, pitch: 55, bearing: -20 }), FARM); await p.waitForTimeout(1500);
await p.mouse.click(800, 600); await p.keyboard.press('p'); await p.waitForTimeout(1800); await idle(p);
// 2. Typed "plan" in a box toggles it (off, then on again).
const typed = async () => { await p.evaluate(() => { let i = document.getElementById('plan-test-box'); if (!i) { i = document.createElement('input'); i.id = 'plan-test-box'; i.style.cssText = 'position:fixed;left:300px;top:300px;z-index:50'; document.body.appendChild(i); } i.value = ''; i.focus(); }); await p.keyboard.type('plan'); await p.keyboard.press('Enter'); await p.waitForTimeout(1600); } … [line shortened here: 401 characters; full line on GitHub]
await typed(); const offS = await state(p);
await typed(); const onS = await state(p);
await p.evaluate(() => { const i = document.getElementById('plan-test-box'); i.blur(); i.remove(); });
check('typed "plan" toggles off and on', !offS.on && onS.on && Math.abs(onS.pitch) < 0.01, JSON.stringify({ off: offS.on, on: onS.on, pitch: onS.pitch }));
// 3. Zoom into the wireframe at the nearest substation: past z17.5 the pitch eases to 60 (sampled mid-ease).
await p.evaluate(() => window.SIM.map.jumpTo({ zoom: 11.5 })); await p.waitForTimeout(2500); await idle(p);
const sub = await p.evaluate(() => { const m = window.SIM.map, c = m.getCenter(); let best = null, bd = 1e9;
for (const f of m.querySourceFeatures('subs')) { if (f.geometry.type !== 'Point') continue; const [x, y] = f.geometry.coordinates, d = (x - c.lng) ** 2 + (y - c.lat) ** 2; if (d < bd) { bd = d; best = [x, y]; } }
return best; });
await p.evaluate(at => window.SIM.map.jumpTo(at ? { center: at, zoom: 16.9 } : { zoom: 16.9 }), sub); await p.waitForTimeout(2500); await idle(p);
await p.evaluate(() => { const e = window.SIM.menu && window.SIM.menu.element('substations'); if (e && !e.classList.contains('on')) e.click(); window.SIM.map.jumpTo({ pitch: 0, bearing: 0 }); });
await p.waitForTimeout(2500); await idle(p);
await shot(p, '02-station-plan-z16.9.png');
await p.evaluate(() => { window.__pz = []; const m = window.SIM.map, t0 = performance.now(); const f = () => { window.__pz.push([Math.round(performance.now() - t0), +m.getPitch().toFixed(1)]); if (performance.now() - t0 < 2500) requestAnimationFrame(f); }; requestAnimationFrame(f); m.zoomTo(18, { duration: 300 }); });
await p.waitForTimeout(700); await shot(p, '03-morph-frame-1.png');
await p.waitForTimeout(400); await shot(p, '04-morph-frame-2.png');
await p.waitForTimeout(1500); await idle(p); await shot(p, '05-morph-frame-3-3d.png');
s = await state(p); const pz = await p.evaluate(() => window.__pz);
const mid = pz.filter(([, v]) => v > 1 && v < 59).length, ease = s.eases.filter(e => e.why === 'zoom-in').pop(), mo = s.morphs.filter(m => m.why === 'zoom-in').pop();
check('zoom-in past z17.5 morphs into the 3D wire (pitch 0 -> 60 and heights 0 -> 1 together, about 1.2 s)', s.in3d && Math.abs(s.pitch - 60) < 0.5 && !s.hidden.includes('wire') && mid >= 5 && ease && ease.ms >= 1000 && ease.ms <= 1800 && mo && mo.full && mo.frames >= 20 && s.morphT === 1 && s.morphActive === false,
JSON.stringify({ in3d: s.in3d, pitch: s.pitch, zoom: s.zoom, midFrames: mid, easeMs: ease && ease.ms, morph: mo, sub }));
// 4. Zoom back out past z16.5: plan again (the reverse morph).
await p.evaluate(() => window.SIM.map.zoomTo(16, { duration: 300 })); await p.waitForTimeout(2200); await idle(p);
s = await state(p); const back = s.eases.filter(e => e.why === 'zoom-out').pop(), mb = s.morphs.filter(m => m.why === 'zoom-out').pop();
check('zoom-out past z16.5 morphs back to plan', s.on && !s.in3d && Math.abs(s.pitch) < 0.01 && Math.abs(s.bearing) < 0.01 && s.scaleBar && !!back && mb && mb.full && s.hidden.includes('wire') && s.morphT === 1 && s.fade === 1,
JSON.stringify({ on: s.on, in3d: s.in3d, pitch: s.pitch, zoom: s.zoom, easeMs: back && back.ms, morph: mb }));
await p.keyboard.press('p'); await p.waitForTimeout(1800); s = await state(p);
check('P again leaves plan (morph up) and restores the look', !s.on && s.dimmed === 0 && s.hidden.length === 0 && s.morphT === 1 && s.morphActive === false && !(await p.evaluate(() => !!window.SIM.map.getLayer('plan-documented'))), JSON.stringify({ on: s.on, pitch: s.pitch, morphT: s.morphT }));
// 4b. Leave while plan is still switching modules on: a fresh page at the farm, Drone, P, then the real key 2 at 1.5 s.
// 15 s later Drone's camera stands (pitch 60, zoom 16.5 or more: no module framing move got through) and no module
// button was pressed after the leave (the auto flags are as they were at the key).
await p.goto(url(FARM), { waitUntil: 'load' }); await ready(p);
await p.evaluate(() => document.querySelector('#drone').click()); await p.waitForTimeout(4000); await idle(p);
await p.mouse.click(800, 600); await p.keyboard.press('p'); await p.waitForTimeout(1500);
const atKey = await state(p); await p.keyboard.press('2');
const justLeft = await p.evaluate(() => ({ auto: window.SIM.plan.state().auto, procOn: !!document.querySelector('#procedural.on'), trench: window.__acTrenches ? window.__acTrenches.state().on : null, busy: window.SIM.plan.state().autoBusy }));
await p.waitForTimeout(15000); await idle(p);
const later = await state(p), laterMods = await p.evaluate(() => ({ procOn: !!document.querySelector('#procedural.on'), trench: window.__acTrenches ? window.__acTrenches.state().on : null, spd: (document.getElementById('spd') || {}).textContent || '' }));
const same = JSON.stringify(justLeft.auto) === JSON.stringify(later.auto) && justLeft.procOn === laterMods.procOn && justLeft.trench === laterMods.trench;
check('key 2 while plan switches modules on: Drone camera stands 15 s later, no module button pressed after the leave', atKey.on && !later.on && Math.abs(later.pitch - 60) < 0.5 && later.zoom >= 16.45 && same && !later.autoBusy && laterMods.spd.startsWith('drone'),
JSON.stringify({ atKey: { on: atKey.on, busy: atKey.autoBusy, auto: atKey.auto }, justLeft, later: { on: later.on, pitch: later.pitch, zoom: later.zoom, auto: later.auto, busy: later.autoBusy, left: later.left.slice(-1) }, laterMods }));
// 5. The 400 kV line in plan (View > Plan clicked from its menu).
await p.goto(url(LINE), { waitUntil: 'load' }); await ready(p);
await p.evaluate(() => window.SIM.map.jumpTo({ zoom: 14.2 }));
await p.evaluate(() => { window.SIM.menu.open('View'); document.getElementById('plan-view').click(); }); await p.waitForTimeout(1800); await idle(p);
s = await state(p);
check('View > Plan by click: plan on at the 400 kV line', s.on && Math.abs(s.pitch) < 0.01, JSON.stringify({ on: s.on, pitch: s.pitch, labels: s.labels }));
const kv = await p.evaluate(() => Array.from(document.querySelectorAll('#plan-labels .plan-label')).map(e => e.textContent).filter(t => /kV line/.test(t)));
check('the line is labelled with its voltage', kv.some(t => /^400 kV/.test(t)), kv.slice(0, 6).join(' | '));
await shot(p, '06-400kv-line-plan.png');
check('no page errors', errs.length === 0, errs.slice(0, 3).join(' | ') || 'none');
await b.close(); server.close();
const bad = results.filter(r => !r.ok).length; console.log(`${results.length - bad}/${results.length} PASS`); process.exit(bad ? 1 : 0);
})().catch(e => { console.error(e); process.exit(1); });Privacy Scan
A JavaScript module in the tests folder of Energy Transition Simulator that tests privacy hashes, using SHA-256. It is built from the sha step (`sha`).
testenergy-transition-simulator / tests/privacy-scan.cjs · lines 1–41 of 41 · Entry point
- What it does
- It tests privacy hashes. Defines sha. Uses libraries child_process, fs, path, crypto. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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 privacy-hashes.json.
- Downstream impact
- Used directly by 1 file: Overlay Workflow (energy-transition-simulator).
- What it achieves
- Privacy scan for the PUBLIC repo.
- Why it matters
- Run by Overlay Workflow.
- Application
- energy-transition-simulator · tests · JavaScript module
- Uses
- child_process, fs, path, crypto
- Used by
- run by Overlay Workflow (workflow run)
- Produces
- sha
- Defines here
- sha
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/privacy-scan.cjs:1-41 · blob 6f6dd599285552d739775393dc32911a68951b1e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
// Privacy scan for the PUBLIC repo. Fails (exit 1) when any tracked text file carries:
// (a) a local drive path (a drive letter, then Users, swarm, gw or private: the operator's machine, never the public site);
// (b) an e-mail address;
// (c) a token whose sha256 is listed in tests/privacy-hashes.json (private place and project names; only hashes are
// committed, so the list itself says nothing). Tokens are lowercased runs of 6+ letters, and runs of 2 to 6 such
// words joined by one space (whole names). The report prints file:line and the first 12 hex of the hash, never
// the token, so the CI log stays clean too.
// Usage: node tests/privacy-scan.cjs (from anywhere inside the repo; scans `git ls-files`)
const { execSync } = require('child_process'), fs = require('fs'), path = require('path'), crypto = require('crypto');
const ROOT = path.join(__dirname, '..');
const HASHES = new Set(JSON.parse(fs.readFileSync(path.join(__dirname, 'privacy-hashes.json'), 'utf8')).hashes);
const DRIVE = /[A-Z]:[\\/](Users|swarm|gw|private)\b/g;
const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
const TEXT_EXT = new Set(['.js', '.mjs', '.cjs', '.json', '.html', '.css', '.md', '.txt', '.yml', '.yaml', '.py', '.csv', '.svg', '.geojson', '.sh', '.ps1', '.toml', '.cfg', '.ini', '']);
const SKIP = new Set(['tests/privacy-hashes.json', 'package-lock.json']);
const sha = t => crypto.createHash('sha256').update(t).digest('hex');
const files = execSync('git ls-files', { cwd: ROOT, encoding: 'utf8' }).split(/\r?\n/).filter(Boolean)
.filter(f => !SKIP.has(f) && TEXT_EXT.has(path.extname(f).toLowerCase()) && !f.startsWith('node_modules/'));
const findings = [];
for (const f of files) {
const abs = path.join(ROOT, f); if (!fs.existsSync(abs) || fs.statSync(abs).isDirectory()) continue;
const buf = fs.readFileSync(abs); if (buf.includes(0)) continue; // binary
const lines = buf.toString('utf8').split(/\r?\n/);
lines.forEach((line, i) => {
const at = `${f}:${i + 1}`;
for (const m of line.matchAll(DRIVE)) findings.push(`${at} drive path ${m[0]}`);
for (const m of line.matchAll(EMAIL)) findings.push(`${at} e-mail address (${m[0].length} chars)`);
if (HASHES.size) {
const words = (line.toLowerCase().match(/[a-z]+/g) || []);
for (let a = 0; a < words.length; a++) {
if (words[a].length >= 6) { const h = sha(words[a]); if (HASHES.has(h)) findings.push(`${at} private word ${h.slice(0, 12)}`); }
for (let n = 2; n <= 6 && a + n <= words.length; n++) {
const h = sha(words.slice(a, a + n).join(' ')); if (HASHES.has(h)) findings.push(`${at} private name ${h.slice(0, 12)}`);
}
}
}
});
}
console.log(`privacy scan: ${files.length} files, ${HASHES.size} hashes, ${findings.length} finding(s)`);
for (const x of findings) console.log(' FAIL ' + x);
process.exit(findings.length ? 1 : 0);Procedural
A JavaScript module in the tests folder of Energy Transition Simulator that tests grid 400kV, overhead lines (OHL), solar and battery storage (BESS).
testenergy-transition-simulator / tests/procedural.cjs · lines 1–198 of 198 · Not reached from any entry point (candidate for review) · pattern browser (shared by 8 files)
- What it does
- It tests grid 400kV, overhead lines (OHL), solar and battery storage (BESS). Defines 8 functions or classes, including browser, shot, state, waitDrawn, sd. Uses libraries http, fs, path, playwright. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (voltage levels 400kV (all 132kV or above)): 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: overhead lines (OHL), solar, battery storage (BESS), 400kV.
- Inputs & outputs
- In: JSON file index.json; GeoJSON file grid_400kv.geojson. Out: WebGL/WebGPU drawing. Voltage levels named: 400kV.
- What it achieves
- It is built from the browser step (`browser`), the shot step (`shot`) and the state step (`state`). Check for `mod/procedural.js`: serves `prototype/` with the module switched on (`mod/index.json` answered with procedural added, the file on disk untouched), opens a register solar farm and a register battery site, switches Procedural on, walks and flies. Its code works with 400 kV, 400 MW and 3.7 MWh.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · tests · JavaScript module
- Uses
- http, fs, path, playwright
- Used by
- none found
- Produces
- browser, shot, state, waitDrawn, sd, inBox, ax, snap
- Defines here
- browser, shot, state, waitDrawn, sd, inBox, ax, snap
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/procedural.cjs:1-198 · blob ca7461d72eaa773106eed3f926d9576fa2a9ac94 · 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
// Check for mod/procedural.js: serves prototype/ with the module switched on (mod/index.json answered with procedural
// added, the file on disk untouched), opens a register solar farm and a register battery site, switches Procedural on,
// walks and flies, and checks what was drawn. PASS or FAIL with evidence; screenshots to SHOTS (default test-output/procedural).
// Local runs use the GPU launcher when CHROME_GPU_LAUNCHER names it; CI uses software WebGL. No network beyond the map tiles.
const http = require('http'), fs = require('fs'), path = require('path');
const ROOT = path.join(__dirname, '..', 'prototype'), OUT = process.env.SHOTS || path.join(__dirname, '..', 'test-output', 'procedural');
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json' };
fs.mkdirSync(OUT, { recursive: true });
const server = http.createServer((q, s) => {
const u = decodeURIComponent(q.url.split('?')[0]).replace(/^\/+/, '');
if (u === 'mod/index.json') { const l = JSON.parse(fs.readFileSync(path.join(ROOT, u), 'utf8')); if (!l.includes('procedural')) l.push('procedural');
s.writeHead(200, { 'Content-Type': 'application/json' }); return s.end(JSON.stringify(l)); }
const f = path.join(ROOT, u || 'overlay.html');
if (!f.startsWith(ROOT) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { s.writeHead(404); return s.end(); }
s.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' }); fs.createReadStream(f).pipe(s);
});
const results = []; const check = (name, ok, ev) => results.push({ name, ok: !!ok, evidence: String(ev).slice(0, 300) });
// Pure unit check (round r8): lift keptSay out of procedural.js and feed it kept <= 0; the caption must carry no minus and no 'fewer'.
{ const src = fs.readFileSync(path.join(ROOT, 'mod', 'procedural.js'), 'utf8'), m = src.match(/\/\/ keptSay:begin[^\n]*\n([\s\S]*?)\/\/ keptSay:end/);
const keptSay = m && new Function(m[1] + '\nreturn keptSay;')();
const cases = keptSay ? [[0, 339], [-4, 339], [-1234, 12]].map(([k, z]) => ({ k, z, t: keptSay(k, z) })) : [];
check('unit: keptSay with kept <= 0 has no minus sign and no "fewer", and says no tables lost with the zone count',
cases.length === 3 && cases.every(c => !/[-−]/.test(c.t) && !/fewer/.test(c.t) && /^no tables lost to the line \(the [\d,]+ positions inside the line zones were placed on free ground in the box; illustrative\)$/.test(c.t) && c.t.includes(c.z.toLocaleString('en-GB'))),
JSON.stringify(cases));
const pos = keptSay && keptSay(5, 339);
check('unit: keptSay with kept > 0 still gives the drawn difference', pos === '5 fewer tables drawn than without the line (339 positions inside the line zones left empty, the rest placed on free ground in the box; illustrative)', pos); }
async function browser() {
if (process.env.CHROME_GPU_LAUNCHER) return require(process.env.CHROME_GPU_LAUNCHER).launch();
const { chromium } = require('playwright');
return chromium.launch({ channel: process.env.CI ? undefined : 'chrome', args: process.env.CI ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist'] });
}
(async () => {
await new Promise(r => server.listen(0, '127.0.0.1', r));
const base = `http://127.0.0.1:${server.address().port}/overlay.html`;
const b = await browser(), p = await b.newPage({ viewport: { width: 1280, height: 800 } });
const errs = []; p.on('pageerror', e => errs.push(e.message));
const shot = n => p.screenshot({ path: path.join(OUT, n + '.png') });
const state = () => p.evaluate(() => window.__procedural || null);
const waitDrawn = async ms => { const t = Date.now(); let s; while (Date.now() - t < ms) { s = await state(); if (s && s.shown.length) return s; await p.waitForTimeout(500); } return s; };
// 0. Round r5: a kV line file that fails to load is UNKNOWN, never "no mapped overhead line within reach". One page with the
// 400 kV file answered 404; 6502 and 5394 must say not loaded / partial, and __proceduralOhl must report loaded:false.
let kv404Fit = null;
{ const q = await b.newPage({ viewport: { width: 1280, height: 800 } }); let hit = 0;
await q.route('**/grid_400kv.geojson', r => { hit++; return r.fulfill({ status: 404, body: 'not found' }); });
await q.goto(`${base}?lat=51.33877&lon=0.91388&zoom=15`, { waitUntil: 'load' }); await q.waitForTimeout(8000);
const rd = await q.evaluate(() => ({ SIM: !!window.SIM, canvas: !!document.querySelector('canvas.maplibregl-canvas') }));
check('404 run: window.SIM and the map canvas present before any shot', rd.SIM && rd.canvas, JSON.stringify(rd));
await q.$eval('#procedural', x => x.click());
let f = null; for (let t = 0; t < 60 && !(f && f.a && f.b && f.a.ohlMissing && f.a.fitN > 0); t++) { await q.waitForTimeout(1000);
f = await q.evaluate(() => { const S = window.__procedural; if (!S) return null; const g = ref => { const x = S.shown.find(z => z.ref === ref); return x && { ohlMissing: x.geom.ohlMissing, loaded: x.geom.ohlLoaded, clr: x.text.split('; ').find(z => /overhead line/.test(z)), fitN: x.geom.formula ? x.geom.formula.fitN : null, rowAz: x.geom.formula ? x.geom.formula.rowAzDeg : null, layout: x.ge … [line shortened here: 525 characters; full line on GitHub]
return { a: g(6502), b: g(5394), oa: window.__proceduralOhl(6502), ob: window.__proceduralOhl(5394) }; }); }
console.log('KV404', hit, JSON.stringify(f && { a: f.a, b: f.b, oa: f.oa && { loaded: f.oa.loaded, missing: f.oa.missing, http: f.oa.http, spans: f.oa.spans }, ob: f.ob && { loaded: f.ob.loaded, missing: f.ob.missing } }));
const say = /overhead line data for 400 kV not loaded: clearance (not applied|partial)/;
check('404 on the 400 kV line file: 6502 and 5394 say not loaded or partial, never "nothing kept out"', hit > 0 && f && f.a && f.b && say.test(f.a.clr) && say.test(f.b.clr) && !/nothing kept out/.test(f.a.clr + f.b.clr) && !f.a.loaded && !f.b.loaded,
JSON.stringify(f && { hit, a: f.a, b: f.b }));
check('404: __proceduralOhl reports loaded:false with 400 kV missing, for 6502 and 5394', f && f.oa && f.ob && f.oa.loaded === false && f.ob.loaded === false && f.oa.missing.includes('400') && f.ob.missing.includes('400'),
JSON.stringify(f && f.oa && { a: { loaded: f.oa.loaded, missing: f.oa.missing, http: f.oa.http }, b: f.ob && { loaded: f.ob.loaded, missing: f.ob.missing } }));
kv404Fit = f && f.a && { fitN: f.a.fitN, rowAz: f.a.rowAz, layout: f.a.layout, pressedScanner: false, tables: f.a.tables, spans: f.a.spans, kept: f.a.kept };
check('404 run, Scanner rows never pressed: 6502 still fits its rows (fitN > 0), rows loaded on arrival', kv404Fit && kv404Fit.fitN > 0, JSON.stringify(kv404Fit));
const rd2 = await q.evaluate(() => ({ SIM: !!window.SIM, canvas: !!document.querySelector('canvas.maplibregl-canvas') }));
check('404 run: window.SIM and the map canvas present before the shot', rd2.SIM && rd2.canvas, JSON.stringify(rd2));
await q.evaluate(() => { window.SIM.removeWhere(b => b.scannerRows); window.SIM.map.jumpTo({ center: [0.91388, 51.33877], zoom: 15, pitch: 0, bearing: 0 }); }); await q.waitForTimeout(4000);
await q.screenshot({ path: path.join(OUT, '0-kv404-solar-top.png') }); await q.close(); }
// 1. A register solar farm (REPD 6502, 373 MW at its published point).
await p.goto(`${base}?lat=51.33877&lon=0.91388&zoom=15`, { waitUntil: 'load' }); await p.waitForTimeout(8000);
const ready = await p.evaluate(() => ({ SIM: !!window.SIM, canvas: !!document.querySelector('canvas.maplibregl-canvas'), gl: (() => { const g = document.querySelector('canvas.maplibregl-canvas').getContext('webgl2') || document.querySelector('canvas.maplibregl-canvas').getContext('webgl'); const e = g && g.getExtension('WEBGL_debug_renderer_info'); return e ? g.getParameter(e.UNMASKED_RENDERER_W … [line shortened here: 424 characters; full line on GitHub]
console.log('READY', JSON.stringify(ready));
check('window.SIM and the map canvas present before any shot', ready.SIM && ready.canvas, JSON.stringify(ready));
check('Procedural button present', await p.$('#procedural'), 'button #procedural');
await p.$eval('#procedural', x => x.click()); const s1 = await waitDrawn(60000);
const farm = s1 && s1.shown.find(x => x.ref === 6502);
check('solar farm at REPD 6502 drawn', farm && farm.segments > 1000, JSON.stringify(farm && { mw: farm.mw, segments: farm.segments, text: farm.text }));
check('anchored at the register point', farm && farm.lat === 51.33877 && farm.lon === 0.91388, farm && `${farm.lat}, ${farm.lon}`);
// Round r6: the row file is loaded on arrival by procedural itself (Scanner rows' own loader), so the fit does not wait for
// the Scanner rows button. Wait for it before pressing anything else.
let s1a = s1; for (let t = 0; t < 30 && !(s1a && s1a.shown.some(x => x.ref === 6502 && x.geom.formula.fitN > 0)); t++) { await p.waitForTimeout(1000); s1a = await state(); }
const farmA = s1a && s1a.shown.find(x => x.ref === 6502);
check('6502 on arrival, Scanner rows not pressed: rows fitted (fitN > 0), not the south formula', farmA && farmA.geom.formula.fitN > 0 && !/south formula/.test(farmA.geom.formula.rowTag),
farmA && `${farmA.geom.formula.layout}, az ${farmA.geom.formula.rowAzDeg}, fitN ${farmA.geom.formula.fitN}`);
// Load the measured rows the page offers (Scanner rows: the lab's row file), so the formula can fit to them.
await p.evaluate(() => window.SIM.scannerRows.run()); await p.waitForTimeout(1500);
// Wait for pylons-real's lines and the row fit to reach the layout (both load async; procedural redoes the site when they arrive).
let s1b = s1; for (let t = 0; t < 90 && !(s1b && s1b.shown.some(x => x.ref === 6502 && x.geom.ohl.length && x.geom.formula.fitN > 0)); t++) { await p.waitForTimeout(1000);
await p.evaluate(() => window.__proceduralRefresh && window.__proceduralRefresh()); s1b = await state(); }
// Clearance: no table corner within reachM + the engine's margin of any real line span (distances in the site's local metres).
const clr = await p.evaluate(() => { const f = window.__procedural.shown.find(x => x.ref === 6502); if (!f) return null; const g = f.geom;
const sd = (px, py, [ax, ay], [bx, by]) => { const dx = bx - ax, dy = by - ay, L = dx * dx + dy * dy, t = L ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / L)) : 0; return Math.hypot(px - ax - t * dx, py - ay - t * dy); };
let worst = Infinity, bad = 0, containers = 0; for (const h of window.__procedural.shown) { const G = h.geom; containers += G.containers.length;
for (const c of [...G.tables, ...G.containers]) for (const z of G.ohl) { const m = Math.min(...c.map(q => sd(q[0], q[1], ...z.pts))) - (z.reachM + G.marginM);
if (m < worst) worst = m; if (m < 0) bad++; } }
return { spans: g.ohl.length, reach: [...new Set(g.ohl.map(z => z.kv + ' kV ' + z.reachM + ' m'))], tables: g.tables.length, containers, others: window.__procedural.shown.map(h => h.ref + ': ' + h.geom.ohl.length + ' spans, ' + h.geom.skipped + ' kept out'), skipped: g.skipped, bad, worstSlackM: +worst.toFixed(2), text: f.text }; });
check('6502: real overhead line spans passed to the layout', clr && clr.spans > 0, JSON.stringify(clr && { spans: clr.spans, reach: clr.reach }));
check('6502 view: no table and no container within reachM + margin of any line span', clr && clr.bad === 0 && clr.tables > 1000, JSON.stringify(clr && { tables: clr.tables, containers: clr.containers, bad: clr.bad, worstSlackM: clr.worstSlackM, others: clr.others }));
check('6502: kept-out readout is the drawn difference, with the positions in the zones named separately', clr && Number.isInteger(clr.skipped) && (clr.skipped > 0 ? new RegExp(`${clr.skipped.toLocaleString('en-GB')} fewer tables drawn than without the line \\([\\d,]+ positions inside the line zones left empty`) : /no tables lost to the line \(the [\d,]+ positions inside the line zones were place … [line shortened here: 555 characters; full line on GitHub]
const dr = await p.evaluate(() => { const g = window.__procedural.shown.find(x => x.ref === 6502).geom; return { withLine: g.tables.length, withoutLine: g.tablesWithoutLine, kept: g.skipped, inZones: g.positionsInZones }; });
check('6502: tables drawn without the line minus tables drawn with it == kept out (own no-line layout)', dr.withoutLine - dr.withLine === dr.kept, JSON.stringify(dr));
check('6502: drawn(404 page, no 400 kV, no spans) - drawn(normal) == kept out reported on the normal page', kv404Fit && kv404Fit.spans === 0 && kv404Fit.tables - dr.withLine === dr.kept,
JSON.stringify({ drawn404: kv404Fit && kv404Fit.tables, spans404: kv404Fit && kv404Fit.spans, drawnNormal: dr.withLine, keptOut: dr.kept, inZones: dr.inZones }));
console.log('CLEARANCE 6502', JSON.stringify(clr));
const info = await p.textContent('#procedural-caption');
const gs = await p.evaluate(() => ({ style: window.__procedural.style, ghost: window.__proceduralGhost(), layer: !!window.SIM.map.getLayer('procedural-ghost'),
solid: window.SIM.blocks.filter(x => x.procedural).length, info: document.getElementById('info').textContent.includes('procedural estimate') }));
check('drawn in the GHOST style by its own layer, none in the solid (measured) wire, #info left alone', gs.style === 'ghost' && gs.ghost > 0 && gs.layer && gs.solid === 0 && !gs.info, JSON.stringify(gs));
const N = await p.evaluate(() => window.__procedural.calibN);
check('label says procedural estimate with the real calibration N', Number.isInteger(N) && info.includes(`procedural estimate (formula calibrated on ${N} measured samples`), `N=${N}: ${info.slice(0, 200)}`);
// The formula readout, checked against what was drawn (not against itself).
const fm = await p.evaluate(() => { const f = window.__procedural.shown.find(x => x.ref === 6502); return f && { ...f.geom.formula, mw: f.mw }; });
const gaps = fm ? fm.rowsV.slice(1).map((v, i) => v - fm.rowsV[i]).filter(d => d > 0.5 * fm.pitchM && d < 1.5 * fm.pitchM).sort((a, b) => a - b) : [];
const drawnPitch = gaps.length ? gaps[Math.floor(gaps.length / 2)] : NaN;
check('drawn row pitch equals the published pitch within 1 cm', fm && gaps.length > 20 && Math.abs(drawnPitch - fm.pitchM) < 0.01,
fm && `drawn median ${drawnPitch.toFixed(4)} m over ${gaps.length} row gaps; published ${fm.pitchM.toFixed(4)} m (${fm.pitchTag})`);
const shoe = fm ? Math.abs(fm.boundary.reduce((a, q, i) => { const r = fm.boundary[(i + 1) % fm.boundary.length]; return a + q[0] * r[1] - r[0] * q[1]; }, 0)) / 2 / 1e4 : NaN;
check('site box area equals MW divided by the published MW/ha within 1%', fm && Math.abs(shoe - fm.mw / fm.mwPerHa) / shoe < 0.01,
fm && `boundary ${shoe.toFixed(2)} ha; ${fm.mw} MW / ${fm.mwPerHa.toFixed(3)} MW/ha = ${(fm.mw / fm.mwPerHa).toFixed(2)} ha (${fm.mwPerHaTag})`);
console.log('FORMULA 6502', JSON.stringify(fm && { pitchM: fm.pitchM, areaHa: fm.areaHa, mwPerHa: fm.mwPerHa, N: fm.N, rows: fm.rowsV.length, drawnPitch }));
// Row azimuth: drawn (from the table corners the layout placed) against the median of the measured rows INSIDE the site's own
// box (half side fitBoxHalfM about the register point), each read here on its own from the row file's lon/lat with a plain
// equirectangular metre scale (not PF.toLocal, not the module's fit), and independent of the camera.
const inBox = () => window.__inBox = (f) => { const ax = d => ((d % 180) + 180) % 180, med = a => a.sort((p, q) => p - q)[a.length >> 1];
const h = f.geom.formula.fitBoxHalfM, k = Math.cos(f.lat * Math.PI / 180), M = 111320, m = [];
for (const doc of Object.values(window.SIM.scannerRows.state.docs)) for (const [[lo0, la0], [lo1, la1]] of doc.rows) {
const x = ((lo0 + lo1) / 2 - f.lon) * M * k, y = ((la0 + la1) / 2 - f.lat) * M; if (Math.abs(x) > h || Math.abs(y) > h) continue;
m.push(ax(Math.atan2((lo1 - lo0) * k, la1 - la0) * 180 / Math.PI)); }
return { n: m.length, measured: m.length ? med(m) : null }; };
await p.evaluate(inBox);
const az = await p.evaluate(() => { const f = window.__procedural.shown.find(x => x.ref === 6502); if (!f) return null;
const ax = d => ((d % 180) + 180) % 180, med = a => a.sort((p, q) => p - q)[a.length >> 1];
const drawn = med(f.geom.tables.map(([a, b]) => ax(Math.atan2(b[0] - a[0], b[1] - a[1]) * 180 / Math.PI))), ib = window.__inBox(f);
const diff = Math.abs(((drawn - ib.measured) % 180 + 270) % 180 - 90);
return { drawn: +drawn.toFixed(2), measured: +ib.measured.toFixed(2), nInBoxTest: ib.n, nFit: f.geom.formula.fitN, boxHalfM: +f.geom.formula.fitBoxHalfM.toFixed(1), diff: +diff.toFixed(2), rowTag: f.geom.formula.rowTag, layout: f.geom.formula.layout }; });
check('6502: drawn row azimuth within 5 deg of the median measured row azimuth inside its own site box', az && az.nFit > 0 && Math.abs(az.nFit - az.nInBoxTest) <= 0.02 * az.nInBoxTest && az.diff <= 5 && new RegExp(`fitted to [\\d,]+ measured rows inside a ${Math.round(2 * az.boxHalfM).toLocaleString('en-GB')} m square around the register point`).test(az.rowTag), JSON.stringify(az));
console.log('AZIMUTH 6502', JSON.stringify(az));
const normAz = await p.evaluate(() => { const f = window.__procedural.shown.find(x => x.ref === 6502); return f && { fitN: f.geom.formula.fitN, rowAz: f.geom.formula.rowAzDeg, layout: f.geom.formula.layout }; });
const dAz = kv404Fit && normAz ? Math.abs(((kv404Fit.rowAz - normAz.rowAz) % 180 + 270) % 180 - 90) : NaN;
check('404 on the 400 kV file does not move the row fit: 6502 row azimuth within 1 deg of the normal run, same layout, same fitN', kv404Fit && normAz && kv404Fit.fitN > 0 && dAz <= 1 && kv404Fit.layout === normAz.layout && kv404Fit.fitN === normAz.fitN,
JSON.stringify({ kv404: kv404Fit, normal: normAz, dAz }));
// A neighbouring solar site in the same view with no runs inside ITS OWN box is not credited with 6502's rows.
const nb = await p.evaluate(() => window.__procedural.shown.filter(x => x.tech !== 'bess' && x.ref !== 6502).map(x => ({ ref: x.ref, mw: x.mw, fitN: x.geom.formula.fitN, inBoxTest: window.__inBox(x).n, boxHalfM: +x.geom.formula.fitBoxHalfM.toFixed(1), tag: x.geom.formula.rowTag })));
check('neighbouring small solar site with no runs in its own box: south formula, not calibrated', nb.some(x => x.fitN === 0 && x.inBoxTest === 0 && /^south formula, not calibrated/.test(x.tag)), JSON.stringify(nb));
// Anchored, not camera-bound: pan far away (6502 out of view) and back at the same zoom; the fit read away from the site and
// the drawn azimuth, pitch and table count must be identical.
const snap = () => p.evaluate(() => { const f = window.__procedural.shown.find(x => x.ref === 6502); const fit = window.__proceduralFit(6502);
if (!f) return null; const g = f.geom, sd = (px, py, [ax, ay], [bx, by]) => { const dx = bx - ax, dy = by - ay, L = dx * dx + dy * dy, t = L ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / L)) : 0; return Math.hypot(px - ax - t * dx, py - ay - t * dy); };
let worst = Infinity; for (const c of g.tables) for (const z of g.ohl) worst = Math.min(worst, Math.min(...c.map(q => sd(q[0], q[1], ...z.pts))) - (z.reachM + g.marginM));
const nb = window.__procedural.shown.find(x => x.ref === 5394);
return { rowAz: g.formula.rowAzDeg, pitch: g.formula.pitchM, tables: g.tables.length, fit: JSON.stringify(fit), spans: g.ohl.length, kept: g.skipped, worstSlackM: +worst.toFixed(3),
ohlFresh: JSON.stringify(window.__proceduralOhl(6502)), nb: nb && { loaded: nb.geom.ohlLoaded, spans: nb.geom.ohl.length, kept: nb.geom.skipped, clr: nb.text.split('; ').find(z => /overhead line/.test(z)), fresh: JSON.stringify(window.__proceduralOhl(5394)) } }; });
const before = await snap();
await p.evaluate(() => window.SIM.map.jumpTo({ center: [1.05, 51.40], zoom: 15 })); await p.waitForTimeout(3000);
const awayFit = await p.evaluate(() => ({ fit: JSON.stringify(window.__proceduralFit(6502)), shown6502: window.__procedural.shown.some(x => x.ref === 6502),
ohl6502: JSON.stringify(window.__proceduralOhl(6502)), ohl5394: JSON.stringify(window.__proceduralOhl(5394)) }));
await p.evaluate(() => window.SIM.map.jumpTo({ center: [0.91388, 51.33877], zoom: 15 })); await p.waitForTimeout(3000);
await p.evaluate(() => window.__proceduralRefresh()); await p.waitForTimeout(3000);
const after = await snap();
check('pan away and back: identical azimuth, pitch, table count; fit read with 6502 out of view is identical', before && after && !awayFit.shown6502 && before.rowAz === after.rowAz && before.pitch === after.pitch && before.tables === after.tables && before.fit === after.fit && awayFit.fit === before.fit,
JSON.stringify({ before: before && { ...before, fit: before.fit.slice(0, 90) }, awayShown: awayFit.shown6502, awayFitSame: before && awayFit.fit === before.fit, after: after && { rowAz: after.rowAz, pitch: after.pitch, tables: after.tables } }));
check('clearance anchored: pan away and back at zoom 15, identical span count, tables kept out, worst slack; spans read with 6502 out of view identical', before && after && before.spans > 0 && before.spans === after.spans && before.kept === after.kept && before.worstSlackM === after.worstSlackM && before.ohlFresh === after.ohlFresh && awayFit.ohl6502 === before.ohlFresh,
JSON.stringify({ before: before && { spans: before.spans, kept: before.kept, worst: before.worstSlackM }, after: after && { spans: after.spans, kept: after.kept, worst: after.worstSlackM }, awayOhlSame: before && awayFit.ohl6502 === before.ohlFresh }));
check('neighbour 5394: clearance status identical at both cameras and when read away, never "in view"', before && after && before.nb && after.nb && JSON.stringify(before.nb) === JSON.stringify(after.nb) && awayFit.ohl5394 === before.nb.fresh && before.nb.loaded && !/in view/.test(before.nb.clr),
JSON.stringify({ before: before && before.nb, afterSame: before && after && JSON.stringify(before.nb) === JSON.stringify(after.nb), awaySame: before && before.nb && awayFit.ohl5394 === before.nb.fresh }));
console.log('CLEARANCE PAN', JSON.stringify({ before: before && { spans: before.spans, kept: before.kept, worst: before.worstSlackM, nb: before.nb }, after: after && { spans: after.spans, kept: after.kept, worst: after.worstSlackM } }));
await p.evaluate(() => { window.SIM.removeWhere(b => b.scannerRows); window.SIM.map.jumpTo({ center: [0.91388, 51.33877], zoom: 15, pitch: 0, bearing: 0 }); });
await p.waitForTimeout(4000);
await shot('1-solar-top');
await p.$eval('#wire', x => x.click()); await p.waitForTimeout(2500); await shot('2-solar-wire');
const wt = await p.evaluate(() => { const f = window.__procedural.shown.find(x => x.ref === 6502); const c = f.geom.tables.map(t => t[0]).sort((a, b) => Math.abs(Math.hypot(...a) - 500) - Math.abs(Math.hypot(...b) - 500))[0];
const k = Math.cos(f.lat * Math.PI / 180); return [f.lon + c[0] / (111320 * k), f.lat + c[1] / 111320, c]; });
console.log('WALK AT TABLE (local m)', JSON.stringify(wt[2]));
await p.evaluate(([lo, la]) => window.SIM.map.jumpTo({ center: [lo, la], zoom: 18, pitch: 0, bearing: 0 }), wt); await p.waitForTimeout(3000);
const surveyOn = await p.$eval('#survey', x => x.classList.contains('on')).catch(() => false); if (surveyOn) await p.$eval('#survey', x => x.click()); // the survey grid hides the faint ghost rows at eye level
await p.$eval('#walk', x => x.click()); await p.waitForTimeout(2500); await p.keyboard.down('w'); await p.waitForTimeout(600); await p.keyboard.up('w'); await p.waitForTimeout(1500); await shot('3-solar-walk');
await p.$eval('#drone', x => x.click()); await p.waitForTimeout(3000); await shot('4-solar-fly');
// 2. A register battery site (REPD 16769, 400 MW): the assumed container yard.
await p.goto(`${base}?lat=51.93835&lon=0.10570&zoom=16.5`, { waitUntil: 'load' }); await p.waitForTimeout(8000);
await p.$eval('#procedural', x => x.click()); const s2 = await waitDrawn(30000);
const bess = s2 && s2.shown.find(x => x.ref === 16769);
// 400 MW x 2 h / 3.7 MWh = 216.2 -> 217 containers; 3 segments per edge x 4 edges = 12 per box, plus the fence box.
check('battery yard sized from capacity (217 containers less any kept out of line zones, assumed rule)', bess && bess.segments === 12 * (218 - bess.geom.skipped), JSON.stringify(bess && { segments: bess.segments, skipped: bess.geom.skipped, text: bess.text }));
await p.$eval('#wire', x => x.click()); await p.waitForTimeout(2500); await shot('5-bess-wire');
const cb = await p.evaluate(() => { const f = window.__procedural.shown.find(x => x.ref === 16769); return f && { spans: f.geom.ohl.length, skipped: f.geom.skipped, text: f.text }; });
check('storage: clearance stated', cb && (cb.spans ? /container positions kept out/.test(cb.text) : /no mapped overhead line within reach of this site box: nothing kept out|no overhead line data loaded for this site box: clearance not applied|overhead line data for [\d ,and]+ kV not loaded/.test(cb.text)), JSON.stringify(cb));
await p.$eval('#walk', x => x.click()); await p.waitForTimeout(2500); await p.keyboard.down('w'); await p.waitForTimeout(1500); await p.keyboard.up('w'); await p.waitForTimeout(1500); await shot('6a-bess-walk');
await p.$eval('#drone', x => x.click()); await p.waitForTimeout(3000); await shot('6-bess-fly');
// 3. A register solar site with no measured rows loaded (REPD 1335, 49.6 MW): the south formula, said so.
await p.goto(`${base}?lat=51.37343&lon=-2.08967&zoom=15`, { waitUntil: 'load' }); await p.waitForTimeout(8000);
await p.$eval('#procedural', x => x.click()); const s3 = await waitDrawn(60000);
const nr = s3 && s3.shown.find(x => x.ref === 1335);
check('solar site with no measured rows: south formula, row azimuth 90, tagged not calibrated', nr && nr.geom.formula.fitN === 0 && nr.geom.formula.layout === 'south' && nr.geom.formula.rowAzDeg === 90 && /south formula, not calibrated/.test(nr.text),
JSON.stringify(nr && { layout: nr.geom.formula.layout, az: nr.geom.formula.rowAzDeg, text: nr.text.slice(0, 160) }));
// 4. Switching off removes every procedural block.
await p.$eval('#procedural', x => x.click()); await p.waitForTimeout(500);
check('off removes the blocks', await p.evaluate(() => !window.SIM.blocks.some(x => x.procedural) && window.__proceduralGhost() === 0 && document.getElementById('procedural-caption').style.display === 'none'), 'no procedural blocks left, caption hidden');
check('no page errors', errs.length === 0, errs.join(' | ') || 'none');
await b.close(); server.close();
for (const r of results) console.log(`${r.ok ? 'PASS' : 'FAIL'} ${r.name} -- ${r.evidence}`);
const failed = results.filter(r => !r.ok).length; console.log(`\n${results.length - failed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
})().catch(e => { console.error(e); server.close(); process.exit(2); });Scanner Rows Test
A test in the tests folder of Energy Transition Simulator that checks Scanner Rows, using Web Mercator.
testenergy-transition-simulator / tests/scanner-rows.test.cjs · lines 1–69 of 69 · Not reached from any entry point (candidate for review)
- What it does
- It tests LiDAR terrain. Uses libraries path, fs. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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: LiDAR terrain.
- Inputs & outputs
- In: JSON file scanner-rows.farms.json. Coordinate systems named: Web Mercator / EPSG:3857.
- What it achieves
- Checks for `prototype/mod/scanner-rows.js` against known references.
- Why it matters
- Guards the behaviour of Scanner Rows.
- Application
- energy-transition-simulator · tests · test
- Uses
- Scanner Rows (require), path, fs
- 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
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/scanner-rows.test.cjs:1-69 · blob 5b6c9c703375a1c0132d1c2eda7b3a62444b372d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// Checks for prototype/mod/scanner-rows.js against known references. Node only, no network, no browser.
// node tests/scanner-rows.test.cjs
const path = require('path'), fs = require('fs');
const M = require('../prototype/mod/scanner-rows.js');
const MOD = path.join(__dirname, '..', 'prototype', 'mod');
const farms = JSON.parse(fs.readFileSync(path.join(MOD, 'scanner-rows.farms.json'), 'utf8')).farms;
const results = []; const check = (name, ok, ev) => results.push({ name, ok: !!ok, ev: String(ev) });
const R = 6371008.8, D2R = Math.PI / 180;
// 1. Every farm's rows sit on the farm: the rows' bounding box overlaps the register point.
for (const f of farms) {
const doc = JSON.parse(fs.readFileSync(path.join(MOD, f.rows), 'utf8'));
const r = M.checkFarm(f, doc);
check(`${f.register}: rows' box overlaps the register point`, r.ok, JSON.stringify({ inside: r.inside, distToBboxM: r.distToBboxM, nearestRowM: r.nearestRowM, bboxM: r.bboxM, runs: r.runs }));
// Negative control: the same rows moved 0.05 deg east (about 3.5 km) must FAIL the check.
const moved = { rows: doc.rows.map(s => s.map(([lo, la]) => [lo + 0.05, la])) };
const m = M.checkFarm(f, moved);
check(`${f.register}: negative control (rows moved 3.5 km) fails`, !m.ok && m.distToBboxM > 1000, `distToBboxM ${m.distToBboxM} m`);
// Known reference: Web Mercator ground resolution at zoom z = 156543.03392 * cos(lat) / 2^z (m per px).
const mpp = 156543.03392 * Math.cos(doc.centre[1] * D2R) / 2 ** doc.zoom;
check(`${f.register}: metres per pixel matches the Web Mercator formula`, Math.abs(mpp - doc.metres_per_pixel) < 1e-4, `${mpp.toFixed(5)} vs ${doc.metres_per_pixel}`);
// Strips tile without overlap: the across-row spacing of neighbouring runs equals the derived strip width (5 cm).
const W = M.stripWidthM(f, doc), c = doc.centre, kx = D2R * R * Math.cos(c[1] * D2R), ky = D2R * R;
const th = doc.row_azimuth_deg_from_east * D2R, ux = Math.cos(th), uy = Math.sin(th), nx = -uy, ny = ux;
const offs = [...new Set(doc.rows.map(([[lo, la]]) => Math.round((((lo - c[0]) * kx) * nx + ((la - c[1]) * ky) * ny) * 100) / 100))].sort((a, b) => a - b);
const gaps = []; for (let i = 1; i < offs.length; i++) { const g = offs[i] - offs[i - 1]; if (g > 0.5 && g < 1.5 * W) gaps.push(g); }
gaps.sort((a, b) => a - b); const med = gaps[gaps.length >> 1];
check(`${f.register}: neighbouring runs are one strip width apart`, Math.abs(med - W) < 0.05, `median gap ${med && med.toFixed(3)} m vs strip ${W.toFixed(3)} m (${gaps.length} gaps)`);
}
// 2. distToBboxM against a hand reference: 0.001 deg of latitude = R * 0.001 * pi/180 = 111.195 m.
const b = { w: 0, s: 51, e: 0.01, n: 51.001 };
check('distance to box: 0.001 deg north of the box = 111.195 m', Math.abs(M.distToBboxM(b, 51.002, 0.005) - R * 0.001 * D2R) < 0.01, M.distToBboxM(b, 51.002, 0.005).toFixed(3));
check('distance to box: a point inside is 0', M.distToBboxM(b, 51.0005, 0.005) === 0, 'inside');
// 3. Tilted table geometry, exact to 1 cm: a 10 m north-south run and a 10 m east-west run, strip width 2.238 m.
const W = 2.238, rise = W * Math.tan(M.TILT_DEG * D2R);
const ns = M.tableLines(0, 0, 0, 10, W), [lo, hi] = ns;
check('table: 8 lines (2 edges, 2 ends, 4 legs)', ns.length === 8, ns.length);
check('table: low edge length 10 m', Math.abs(Math.hypot(lo[3] - lo[0], lo[4] - lo[1]) - 10) < 0.01, Math.hypot(lo[3] - lo[0], lo[4] - lo[1]));
check('table: plan width = strip width', Math.abs(Math.abs(lo[0] - hi[0]) - W) < 0.01, Math.abs(lo[0] - hi[0]));
check(`table: rise = width x tan(${M.TILT_DEG} deg), low edge ${M.LOW_M} m`, Math.abs(hi[2] - lo[2] - rise) < 0.01 && Math.abs(lo[2] - M.LOW_M) < 1e-9, `${(hi[2] - lo[2]).toFixed(4)} vs ${rise.toFixed(4)}`);
check('table: north-south run faces east (low edge east of high edge)', lo[0] > hi[0], `${lo[0]} > ${hi[0]}`);
const ew = M.tableLines(0, 0, 10, 0, W);
check('table: east-west run faces south (low edge south of high edge)', ew[0][1] < ew[1][1], `${ew[0][1]} < ${ew[1][1]}`);
check('table: legs stand on the ground (z = 0)', ns.slice(4).every(l => l[2] === 0), 'legs');
// 4. Rule R5-9 gate: LiDAR rows only where every DSM and DTM survey is later than the build year.
const G = M.surveyGate;
check('R5-9: survey 2022 under a 2025 build is pre-construction', !G(2025, [2022], [2022]).lidarRows && G(2025, [2022], [2022]).ground === 'pre-construction', G(2025, [2022], [2022]).reason);
check('R5-9: survey in the build year itself is pre-construction ("same as or later")', !G(2024, [2024], [2024]).lidarRows, G(2024, [2024], [2024]).reason);
check('R5-9: surveys 2025 and 2026 after a 2024 build allow LiDAR rows', G(2024, [2025], [2026]).lidarRows, G(2024, [2025], [2026]).reason);
check('R5-9: one early year among later ones blocks LiDAR rows', !G(2021, [2022, 2019], [2022]).lidarRows, G(2021, [2022, 2019], [2022]).reason);
check('R5-9: unknown build year blocks LiDAR rows', !G(null, [2025], [2025]).lidarRows, G(null, [2025], [2025]).reason);
check('R5-9: missing DTM year blocks LiDAR rows', !G(2020, [2025], []).lidarRows, G(2020, [2025], []).reason);
for (const f of farms) {
const doc = JSON.parse(fs.readFileSync(path.join(MOD, f.rows), 'utf8')), a = M.rowsAllowed(f, doc);
check(`${f.register}: every farm carries build year, survey years and imagery capture, each tagged`,
f.build_year && f.build_year.tag && f.lidar_survey_years && f.lidar_survey_years.tag && f.imagery && f.imagery.capture_date && f.imagery.tag, JSON.stringify({ b: f.build_year && f.build_year.value, s: f.lidar_survey_years, i: f.imagery && f.imagery.capture_date }));
check(`${f.register}: row file is imagery, drawn and labelled estimated`, a.source === 'imagery' && a.allowed && /estimated/i.test(doc.estimate || ''), `${a.source}, ${a.reason}`);
// Negative control: the same rows claimed as a LiDAR DSM scan must be REFUSED where the survey predates the build.
const lid = Object.assign({}, doc, { source: 'EA LiDAR composite DSM', method: 'DSM minus DTM height mask' }), b = M.rowsAllowed(f, lid);
const pre = f.lidar_survey_years.dsm.concat(f.lidar_survey_years.dtm).some(y => y <= f.build_year.value);
check(`${f.register}: LiDAR-claimed rows ${pre ? 'refused' : 'allowed'} by R5-9`, b.source === 'lidar' && b.allowed === !pre, `${b.source}, allowed ${b.allowed}: ${b.reason}`);
}
for (const r of results) console.log(`${r.ok ? 'PASS' : 'FAIL'} ${r.name} -- ${r.ev}`);
const failed = results.filter(r => !r.ok).length; console.log(`\n${results.length - failed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);Tables
A JavaScript module in the tests folder of Energy Transition Simulator that tests scanner rows farms, AC trenches and solar. It is built from the near step (`near`).
testenergy-transition-simulator / tests/tables.cjs · lines 1–58 of 58 · Not reached from any entry point (candidate for review)
- What it does
- It tests scanner rows farms, AC trenches and solar. Defines near. Uses libraries fs, path. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
- Inputs & outputs
- In: JSON file scanner-rows.farms.json; JSON file ac-trenches-6502.json.
- What it achieves
- Check for `prototype/mod/tables.js`: the pure helpers run in Node on the real row file (no browser, no network). - rows from the 5,077 measured runs.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · tests · JavaScript module
- Uses
- fs, path
- Used by
- none found
- Produces
- near
- Defines here
- near
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a tests/tables.cjs:1-58 · blob 7e0a8bff438bc82b192ea1b62d050ba01c4bf17b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// Check for prototype/mod/tables.js: the pure helpers run in Node on the real row file (no browser, no network).
// - the farm parameters against the library defaults: width 24.27 m, pitch 26.77 m, ridge 3.00 m (the measured ridge);
// - rows from the 5,077 measured runs: axis about 2.4 deg E of N, pitch 26.5 to 27.2 m, a few hundred rows 6 to 11 strips wide;
// - tables cut where the measured extent steps or breaks, then to the library span; at least 95 % of table area on runs;
// - route ends of the AC trench model (about 660 of 668 routes) claimed by the tables whose footprint (+2.6 m) holds them;
// - geometry builders return the expected segment counts; no names or drive paths in the module.
const fs = require('fs'), path = require('path');
const ROOT = path.join(__dirname, '..', 'prototype'), MOD = path.join(ROOT, 'mod');
const T = require(path.join(MOD, 'tables.js'));
const results = []; const check = (name, ok, ev) => { results.push({ name, ok: !!ok }); console.log(`${ok ? 'PASS' : 'FAIL'} ${name} :: ${String(ev).slice(0, 300)}`); };
const near = (a, b, t) => Math.abs(a - b) <= t;
// The library defaults, as the header of the station library's station.mjs states them (not the file: the module imports it by URL).
const DEFAULTS = { height: 1.2, tilt: 10, tables: 23, columns: 90, rows: 5, moduleWidth: 1.303, moduleLength: 2.384, moduleGap: 0.02, rowGap: 8, aisleGap: 10, ridgeGap: 0.5, stringsPerInverter: 24, inverters: 28, modulesPerString: 30 };
const fp = T.farmParams(DEFAULTS);
check('farm parameters: width 24.27 m, pitch 26.77 m, ridge 3.00 m (measured), tilt 8, low edge 1.33', near(fp.width, 24.27, 0.01) && near(fp.pitch, 26.77, 0.01) && near(fp.ridge, T.RIDGE_MEASURED_M, 0.01) && fp.params.tilt === 8 && fp.params.height === 1.33, JSON.stringify({ width: fp.width, pitch: fp.pitch, ridge: fp.ridge }));
check('changed from the library: height, tilt, rowGap only (ridgeGap kept at 0.5)', fp.params.rowGap === 2.5 && fp.params.ridgeGap === 0.5 && fp.params.columns === 90 && fp.params.rows === 5, JSON.stringify(T.FARM));
// rows from the real runs
const farms = JSON.parse(fs.readFileSync(path.join(MOD, 'scanner-rows.farms.json'), 'utf8')).farms, f = farms[0];
const doc = JSON.parse(fs.readFileSync(path.join(MOD, f.rows), 'utf8'));
const R = 6371008.8, D2R = Math.PI / 180, kx = R * Math.cos(f.point.lat * D2R) * D2R, ky = R * D2R;
const runs = doc.rows.map(([[a, b], [c, d]]) => [(a - f.point.lon) * kx, (b - f.point.lat) * ky, (c - f.point.lon) * kx, (d - f.point.lat) * ky]);
const t0 = Date.now(), rr = T.rowsFromRuns(runs, { step: f.sample_step_px.value * doc.metres_per_pixel }), ms = Date.now() - t0;
check('row axis about 2.4 deg E of N (mean run direction)', near(rr.axis / D2R, 2.4, 0.3), (rr.axis / D2R).toFixed(2));
check('strip step 2.238 m (3 px at 0.7461 m/px, from the farms file), the estimate from the runs within 0.05 m', near(rr.step, 2.238, 0.001) && near(T.stripStep(runs.map(r => T.toRow(rr.axis, r[0], r[1])[0])), 2.238, 0.06), rr.step.toFixed(4));
check('row spacing from the rows 26.2 to 27.2 m (the row file reads 26.86; a strip-quantised mask reads about 0.4 m short, said in BUILD)', rr.pitch > 26.2 && rr.pitch < 27.2, rr.pitch);
check('rows: 150 to 700 found, all 6 to 12 strips wide, in under 2 s', rr.rows.length >= 150 && rr.rows.length <= 700 && rr.rows.every(r => r.cols >= 6 && r.cols <= 12) && ms < 2000, `${rr.rows.length} rows, dropped ${JSON.stringify(rr.dropped)}, ${ms} ms`);
const lens = rr.rows.map(r => r.v1 - r.v0).sort((a, b) => a - b);
check('row lengths 15 to 800 m, median over 60 m', lens[0] >= 15 && lens[lens.length - 1] <= 800 && lens[lens.length >> 1] > 60, `min ${lens[0].toFixed(1)} median ${lens[lens.length >> 1].toFixed(1)} max ${lens[lens.length - 1].toFixed(1)}`);
const tb = T.tablesFromRows(rr.rows, fp.params, rr.raster), halfW = T.halfWidthOf(fp.params);
check('tables: none longer than the library span, each inside its row, cut where the extent steps or the row breaks', tb.length >= rr.rows.length && tb.every(t => t.span <= 119.11 && t.columns >= 1 && t.columns <= 90 && t.v0 >= rr.rows[t.row].v0 - 1e-6 && t.v0 + t.span <= rr.rows[t.row].v1 + 1e-6), `${tb.length} tables from ${rr.rows.length} rows, dropped ${JSON.stringify(tb.dropped)}`);
check('most tables carry 40 to 90 columns (cut to fit the measured run)', tb.filter(t => t.columns >= 40).length > tb.length / 2, `${tb.filter(t => t.columns >= 40).length} of ${tb.length} tables with 40+ columns`);
check('each row centre from its own unbridged crossings: rows carry cells, most cells unbridged (10 to 12 strips)', rr.rows.every(r => r.cells && r.cells.length) && rr.cells.unbridged > rr.cells.bridged + rr.cells.partial, JSON.stringify(rr.cells));
check('bridged blocks comb-fitted to both edges: comb cells have fractional or whole columns 11 wide', rr.rows.every(r => r.cells.filter(c => c.bridged).every(c => near(c.c1 - c.c0, 10, 1e-9))), rr.rows.reduce((n, r) => n + r.cells.filter(c => c.bridged).length, 0) + ' comb cells');
let area = 0, onRuns = 0; for (const t of tb) { area += t.span * 2 * halfW; onRuns += t.span * 2 * halfW * t.cov; }
check('at least 95 % of table area on measured runs; no piece under 70 %', onRuns / area >= 0.95 && tb.every(t => t.cov >= T.MIN_COVER), `${(100 * onRuns / area).toFixed(2)} % of ${(area / 1e4).toFixed(1)} ha on runs; min piece ${Math.min(...tb.map(t => t.cov)).toFixed(3)}`);
// route ends of the trench model
const trench = JSON.parse(fs.readFileSync(path.join(MOD, 'ac-trenches-6502.json'), 'utf8')), ends = T.routeEnds(trench, 'A4');
check('route ends: 640 to 668 (the model has 668 routes in A4)', ends.length >= 640 && ends.length <= 668 && ends.every(p => p.length === 2), ends.length);
const FR = trench.frame, endsLocal = ends.map(([e, n]) => [(FR.lon0 + e / FR.KX - f.point.lon) * kx, (FR.lat0 + n / FR.KY - f.point.lat) * ky]); // the trench frame into the farm's local frame
const tabs = tb.map(t => ({ ...t, at: T.fromRow(rr.axis, t.u, t.v0) })), cl = T.claimPoles(tabs, endsLocal, rr.axis, halfW);
const nPoles = cl.sites.reduce((n, s) => n + s.length, 0), multi = cl.sites.filter(s => s.length > 1).length;
check('poles: every route end within a footprint + 2.6 m claimed (some tables claim several); claimed + free = ends', nPoles + cl.free.length === ends.length && nPoles > 30 && multi > 0 && cl.sites.every((s, i) => s.every(([x, y]) => Math.abs(x) <= halfW + T.CLAIM_M + 1e-6 && y >= -T.CLAIM_M - 1e-6 && y <= tabs[i].span + T.CLAIM_M + 1e-6)), `${nPoles} poles on ${cl.sites.filter(s => s.length).leng … [line shortened here: 567 characters; full line on GitHub]
// geometry
const shape = { run: fp.run, depth: fp.depth, span: 90 * 1.323 - 0.02, ridge: fp.ridge, halfRidgeGap: 0.25 };
const ol = T.outlineLines(shape, fp.params), gl = T.gridLines(shape, fp.params), sl = T.structureLines(shape, fp.params);
check('outline: 8 segments, low edges at 1.33 m and ridge lines at 3.00 m', ol.length === 8 && ol.filter(l => l[2] === 1.33 && l[5] === 1.33).length === 2 && ol.filter(l => near(l[2], 3.0, 0.01) && near(l[5], 3.0, 0.01)).length === 2, JSON.stringify(ol[0]));
check('module grid: (rows + 1) + (columns + 1) lines per face', gl.length === 2 * (6 + 91), gl.length);
check('structure: dashed posts and diagonals plus rafters and beams, under 1,000 segments', sl.length > 100 && sl.length < 1000, sl.length);
const L = []; T.poleLines([0, -1, 3], L); check('pole and inverter box: 12 box edges plus dashes', L.length >= 15, L.length);
const G = []; T.poleLines([0, -1, 3], G, true); check('library-site pole: a distinct ghost (fine dashes, dashed box), more segments than the solid box', G.length > L.length && G.length > 40, G.length);
const D = []; T.dashed(D, [0, 0, 0], [0, 0, 3], 0.4); check('dashed: half the length drawn', D.length === 4, D.length);
// names and paths
const src = fs.readFileSync(path.join(MOD, 'tables.js'), 'utf8');
check('no drive paths or names in the module', !/[A-Z]:[\/]/.test(src) && !/solar farm|solar park/i.test(src), 'scanned');
check('labels: low edge DERIVED, purlins named, rails said not drawn, bare poles split, plan hides the caption, no moveend build', /DERIVED \(measured 3\.0 m ridge minus the documented 8 deg rise; documented 1\.3-1\.5 m\)/.test(src) && /purlins and rafters assumed, solid; rails are not drawn/.test(src) && /beside a table but unclaimed \(\$\{st\.freeBeside\}\), no measured rows there/.test(src) && … [line shortened here: 655 characters; full line on GitHub]
check('the library is imported by URL, not copied', /import\(LIB_URL\)/.test(src) && /globalgrid2050\.com\/solar-design-studio\/202609271853-site-world\/world\/station\.mjs/.test(src) && !/export function tableShape/.test(src), 'import(LIB_URL)');
const fails = results.filter(r => !r.ok).length;
console.log(`${results.length - fails}/${results.length} PASS`); process.exit(fails ? 1 : 0);