In this section
- About Estate and Attribution Proof interaction · gridatlas / tools/proofs/about-estate-and-attribution.proof.mjs lines 1–329
- All Controls Browser render · gridatlas / tools/proofs/all-controls.browser.mjs lines 1–119
- All Layer Clicks Browser render · gridatlas / tools/proofs/all-layer-clicks.browser.mjs lines 1–92
About Estate and Attribution Proof
A JavaScript module in the proofs folder of GridAtlas that reads engine graph and substations from the ventus-grid-engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.
interactiongridatlas / tools/proofs/about-estate-and-attribution.proof.mjs · lines 1–329 of 329 · Not reached from any entry point (candidate for review) · pattern report (shared by 21 files)
- What it does
- It loads engine graph and substations. Defines check, runValue, report. Uses libraries node:fs/promises, 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: substations.
- Inputs & outputs
- In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; JSON file current.json; JSON file engine-graph.json.
- What it achieves
- It is built from the check step (`check`), the run value helper (`runValue`) and the report step (`report`). The About panel carries the attribution and the estate's published method. It responds to afterprint events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- Spider Full Po Test (estate URL), node:fs/promises, node:path, node:url
- Used by
- none found
- Produces
- check, runValue, report
- Defines here
- check, runValue, report
- 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/about-estate-and-attribution.proof.mjs:1-329 · blob dd5eaf9010ac702e93f60e8742671c209c726144 · 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
/**
* The About panel carries the attribution and the estate's published method.
*
* Two things this generation exists to do, both asserted against the COMPOSED
* bytes named by atlas/current.json -- never against the module part. A fix
* written into a part and never composed is this estate's most expensive
* recurring defect: the iOS arrival fix of 202609041957 existed in a part for
* hours while the served cartridge did not have it.
*
* 1. `.custom-map-attrib` is moved into the About panel. Measured live at
* generation 202609042123 it rendered at x=15 y=47, 401x24 px -- a boxed
* band under the menu bar, over the top-left of the map, exactly where a
* reader arriving on a deep link looks first.
*
* 2. About gains an Estate group linking the estate's published method: the
* engine graph, the federation map and the spider printer. The
* publication boundary is explicit that method is never withheld
* (seed-data/07_CRITICALITY_AND_PUBLICATION_BOUNDARY.md, section 6).
*
* Run: node tools/proofs/about-estate-and-attribution.proof.mjs
*/
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const ATLAS = path.join(ROOT, 'atlas');
const checks = [];
function check(name, ok, detail) {
checks.push({ name, ok: Boolean(ok), detail: detail === undefined ? '' : String(detail) });
}
const current = JSON.parse(await readFile(path.join(ATLAS, 'current.json'), 'utf8'));
/* The cartridge the menu bar is composed into, read from the composition
rather than named here, so this proof cannot drift onto a stale file. */
const entry = (current.cartridges || []).find(c => /substation-intelligence/.test(c.path || ''));
check('composition names a substation-intelligence cartridge', Boolean(entry), entry && entry.path);
if (!entry) { report(); }
const composedPath = path.join(ATLAS, entry.path.replace(/^\.\//, ''));
const composed = await readFile(composedPath, 'utf8');
check('composed cartridge is readable', composed.length > 0, `${entry.path} ${composed.length} bytes`);
/* 1. The attribution move. */
check(
'composed bytes move .custom-map-attrib into the About panel',
/var attrib = doc\.querySelector\('\.custom-map-attrib'\);/.test(composed)
&& /if \(!bar \|\| !bar\.contains\(attrib\)\) move\(panels\.About, attrib\);/.test(composed),
'the node is adopted into About, not cloned or rewritten'
);
check(
'composed bytes style the attribution once inside a panel',
composed.includes(".gm-panel .custom-map-attrib{position:static!important;"),
'panel-scoped rule present'
);
/* His instruction was "in small print at the bottom", so bottom is asserted,
not assumed: the estate links must be appended before it, and the
attribution must be re-appended on later passes so a late DOM rebuild
cannot float it back above the controls. */
const iLinks = composed.indexOf('state.estate_links = appendEstateLinks(panels.About)');
const iAttrib = composed.indexOf("var attrib = doc.querySelector('.custom-map-attrib')");
check(
'the attribution is appended AFTER the estate links, so it sits at the bottom',
iLinks > -1 && iAttrib > iLinks,
`estate links at ${iLinks}, attribution at ${iAttrib}`
);
/* This one is here because getting it wrong crashed the tab.
adoptLate runs from a MutationObserver. An unconditional appendChild inside
it is itself a mutation, so it re-enters adoptLate and appends again -- a
feedback loop that crashed the renderer under the 393x852 arrival gate while
the previous generation passed the same gate in the same harness. The guard
must make the second and every later pass a NO-OP. */
check(
'a later adoption pass only re-appends when the node is not already last',
/panels\.About\.lastElementChild !== attrib/.test(composed),
'lastElementChild guard closes the MutationObserver feedback loop'
);
check(
'the engine fetch is guarded synchronously, not by the DOM it has yet to write',
/var engineFetchStarted = false;/.test(composed)
&& /if \(!panel \|\| !window\.fetch \|\| engineFetchStarted\) return;/.test(composed)
&& /engineFetchStarted = true;/.test(composed),
'one request, not one per mutation'
);
check(
'it is small print',
/\.gm-panel \.custom-map-attrib\{[^}]*font:10px/.test(composed.replace(/',\s*'/g, '')),
'10px in the panel-scoped rule'
);
/* 2. The Estate group. Each URL is asserted individually: a single combined
check would pass while two of the three had been dropped. */
const links = [
['engine graph', 'https://ventusltd.github.io/ventus-grid-engine/?graph=engine-graph'],
['federation map', 'https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/dashboard/sandbox/spider_full_po_test.html'],
['spider printer', 'https://ventusltd.github.io/spiders/spider_printer_v1/']
];
for (const [name, href] of links) {
check(`composed bytes carry the ${name} link`, composed.includes(href), href);
}
check('estate links are marked so they are appended once', composed.includes('data-gm-estate'), 'data-gm-estate');
check('estate links sit under an Estate group heading', /appendGroup\(panel,\s*'Estate'\)/.test(composed), "appendGroup(panel, 'Estate')");
check(
'estate links are anchors carrying the panel button role',
/a\.setAttribute\('role',\s*'button'\)/.test(composed),
'role="button" so they inherit the panel look'
);
/* 2b. The File panel lists the engine's own modules.
"the menus must be neat, it should allow AI and humans to develop and
use" -- the architect, 2026-09-05. The list is fetched from the engine's
published graph rather than restated in this repository, so the menu
cannot drift away from the maths it names. Both surfaces are served from
ventusltd.github.io, so the request is same-origin. */
check(
'composed bytes fetch the engine graph rather than restating its modules',
composed.includes('https://ventusltd.github.io/ventus-grid-engine/genome/engine-graph.json'),
'ENGINE_GRAPH_URL'
);
check(
'each module links into the graph focused on itself',
composed.includes('https://ventusltd.github.io/ventus-grid-engine/?graph=engine-graph&focus='),
'uses the ?focus= contract published 202609050305'
);
/* The first cut of this listed only `type === 'canonical'` and the architect
caught it in one line: "Why are the mjs files not there?" Every .mjs in the
estate is an extract, a reference or a fragment, so filtering to canonical
hid all four of them. The fragments matter most: they are where a
calculation has been copied and left to drift. */
check(
'every kind of node is listed, not only the canonical ones',
!/node\.type === 'canonical'/.test(composed)
&& /var ORDER = \['canonical', 'extract', 'reference', 'fragment'\]/.test(composed),
'canonical first, then extract, reference, fragment, then anything new'
);
check(
'a kind the graph adds later still appears rather than being dropped',
/Object\.keys\(byKind\)\.filter\(function \(k\) \{ return ORDER\.indexOf\(k\) < 0; \}\)/.test(composed),
'unknown kinds are appended, not filtered out'
);
check(
'the menu hands over a command that can actually be run',
composed.includes('git clone https://github.com/Ventusltd/ventus-grid-engine')
&& composed.includes('node verify.mjs'),
'clone, then run the engine\'s own fail-closed gate'
);
/* Measured 202609050250: the engine declares no dependencies and no proof in it
opens a socket, so the gate runs from a clone with no install and no network.
An install step in this command would imply a dependency that does not exist
and would make the offline claim false, so its absence is asserted. */
/* Assert the COMMAND, not the file: the note above it explains why there is no
install step, so a file-wide search for "npm install" matches the
explanation and fails on prose. Read the string the button actually copies. */
const runValue = (() => {
const at = composed.indexOf('var RUN_COMMAND =');
if (at < 0) return null;
const end = composed.indexOf(';', at);
return end < 0 ? null : composed.slice(at, end);
})();
check(
'the command claims no install step, because none is needed',
Boolean(runValue) && !/npm\s+(install|i)\b/.test(runValue),
runValue ? runValue.replace(/\s+/g, ' ').slice(17, 140) : 'RUN_COMMAND not found'
);
check(
'it is copied, never executed, and says so by doing nothing else',
/navigator\.clipboard\.writeText\(RUN_COMMAND\)/.test(composed)
&& !/eval\(/.test(composed.slice(composed.indexOf('RUN_COMMAND'), composed.indexOf('RUN_COMMAND') + 2000)),
'the person who pastes it is the one who approves it'
);
check(
'a browser with no clipboard permission shows the command instead of failing silently',
composed.includes("done(false);"),
'the control reveals its own payload'
);
check('the engine rows are marked so they are appended once', composed.includes('data-gm-engine'), 'data-gm-engine');
check(
'the modules are listed alphabetically, as every non-version group here is',
/localeCompare\(String\(b\.label\), 'en-GB'\)/.test(composed),
'en-GB localeCompare'
);
check(
'an unreachable engine leaves the menu exactly as it was',
/\.catch\(function \(\) \{/.test(composed) && /state\.engine_modules = 0;/.test(composed),
'the fetch failure path adds no group and throws nothing'
);
check(
'the engine group goes in File, not About',
composed.includes('appendEngineModules(panels.File)'),
'appendEngineModules(panels.File)'
);
/* 2c. The published study, in View.
"add this to the appropriate menuw on gridatlas and pipeline news" -- the
architect, 2026-09-05, of the GB electricity price and grid constraint
series. View is where this application already keeps readings of the
network over time: GB prices · historic is moved into it by adoptLate.
About would have filed it as provenance, which it is not. */
check(
'the GB price and constraint study is carried',
composed.includes('great_britain_electricity_price_grid_constraint_trends_2016_2026.html'),
'globalgrid2050.com/data/grid_studies_public/'
);
check(
'it is in View, beside the price control, not in About',
composed.includes('state.studies = appendStudies(panels.View)'),
'appendStudies(panels.View)'
);
check(
'the studies group is appended once',
/panel\.querySelector\('\[data-gm-study\]'\)/.test(composed),
'data-gm-study guard'
);
/* 2d. Export: print a slide, or save an image of what is on screen.
Two obligations, both of which this estate has already broken once:
THE IMAGE MUST NOT BE BLANK. The map is a WebGL canvas created without
preserveDrawingBuffer, so a read outside a render frame returns a fully
transparent image that still encodes to a valid PNG and downloads
happily. The capture happens inside a render frame AND the result is
sampled before it is offered.
THE CREDIT MUST TRAVEL WITH THE ARTEFACT. This generation moved the
attribution into About, which is right for the screen and wrong for an
export: OpenStreetMap and CARTO require attribution on the thing that
leaves the building. */
check(
'the File panel offers print and image export',
composed.includes('data-gm-export') && /appendExport\(panels\.File, doc\)/.test(composed),
'appendExport(panels.File, doc)'
);
check(
'the image is captured inside a render frame, not after compositing',
/map\.once\('render', grab\)/.test(composed) && /map\.triggerRepaint\(\)/.test(composed),
'the canvas has no preserveDrawingBuffer, so the frame is where the pixels are'
);
check(
'a blank capture is refused rather than downloaded',
/function looksBlank\(canvas\)/.test(composed)
&& /looksBlank\(canvas\)/.test(composed)
&& composed.includes('The map could not be captured'),
'sampled for non-transparent pixels before it is offered'
);
check(
'a tainted canvas is not mistaken for a blank one',
composed.includes('A tainted canvas throws here'),
'the catch returns false, so the reader is not sent to print for no reason'
);
check(
'the exported artefact carries the attribution the screen moved into About',
/function attributionText\(doc\)/.test(composed)
&& composed.includes('gpf-attrib')
&& composed.includes('OpenStreetMap contributors'),
'credit travels with the thing that leaves the building'
);
check(
'the print slide carries the generation and a UTC stamp',
/function generationText\(\)/.test(composed) && /function exportStamp\(\)/.test(composed)
&& composed.includes('gpf-stamp'),
'an exported slide says which build and when'
);
/* "make sure print always fits to page in landscape or portrait on mobile, or
desktop and sizes to fit the page". Forcing A4 landscape, which the first
version did, is the OPPOSITE of fitting: it overrides the reader's own paper
and clips on anything smaller. */
check(
'the print takes whatever page the reader chose, rather than forcing one',
composed.includes('@page{size:auto;margin:8mm}')
&& !composed.includes('size:A4 landscape'),
'size:auto, so portrait or landscape and any paper both fit'
);
check(
'the map sizes to the printable area instead of a fixed height',
composed.includes('flex:1 1 auto!important;min-height:0!important')
&& !/height:170mm/.test(composed),
'min-height:0 or the flex child refuses to shrink and pushes the footer off the sheet'
);
check(
'a slide is one page, never two',
composed.includes('break-inside:avoid;page-break-inside:avoid'),
'nothing spills onto a second sheet'
);
check(
'printing hides the interface',
composed.includes("display:none!important"),
'the bar is interface, not content'
);
check(
'the print furniture is removed afterwards, and does not rely on afterprint alone',
composed.includes("window.addEventListener('afterprint', clean)")
&& /window\.setTimeout\(clean, 20000\)/.test(composed),
'some mobile browsers never fire afterprint'
);
/* 3. Nothing this generation touched may remove what was already proven.
The v8 layers panel and the six menu titles are the two things earlier
generations exist to protect; assert them here so this cut cannot pass
by having quietly dropped them. */
check('the six menu titles survive', /'File',\s*'Edit',\s*'View',\s*'Scope',\s*'Grid',\s*'About'/.test(composed), 'MENUS unchanged');
check('the Scope tools survive', /move\(panels\.Scope,\s*ready\.nodes\.zoneButton\)/.test(composed), 'zoneButton still routed to Scope');
check('the v8 layer controls survive', composed.includes('buildLayerControls(ready.found)'), 'buildLayerControls still called');
/* 4. The part and the composed bytes must agree. If they do not, the
composition did not pick up the edit, which is the failure mode this
whole proof exists to catch. */
const part = await readFile(path.join(ATLAS, 'modules', '202609031958-menu-bar.js'), 'utf8');
check(
'the module part and the composed cartridge agree on the estate links',
part.includes('data-gm-estate') === composed.includes('data-gm-estate'),
'part and composed bytes both carry it, or neither do'
);
report();
function report() {
const failed = checks.filter(c => !c.ok);
for (const c of checks) {
console.log(`${c.ok ? 'ok ' : 'FAIL'} ${c.name}${c.detail ? ' -- ' + c.detail : ''}`);
}
console.log(`\n${checks.length - failed.length}/${checks.length} checks passed`);
if (failed.length) {
console.error(`\n${failed.length} FAILED`);
process.exit(1);
}
process.exit(0);
}All Controls Browser
A JavaScript module in the proofs folder of GridAtlas that works with pipeline frame (`pipelineFrame`) and settled frame (`settledFrame`), covering solar, using SHA-256.
rendergridatlas / tools/proofs/all-controls.browser.mjs · lines 1–119 of 119 · Entry point
- What it does
- It draws solar. Defines 7 functions or classes, including save, tap, snap, check, menu. Uses libraries playwright, node:fs, node:path, node:http, node:assert/strict. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
- Inputs & outputs
- In: JSON file current.json; command-line arguments. Out: JSON file report.json.
- Downstream impact
- Used directly by 1 file: GridAtlas Cartridge Proof Workflow (gridatlas).
- What it achieves
- It is built from the check step (`check`), the menu step (`menu`) and the pipeline frame helper (`pipelineFrame`). Defines `save`, `tap`, `snap` and 4 more. It responds to beforeprint events.
- Why it matters
- Run by GridAtlas Cartridge Proof Workflow.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- playwright, node:fs, node:path, node:http, node:assert/strict, node:crypto
- Used by
- run by GridAtlas Cartridge Proof Workflow (workflow run)
- Produces
- save, tap, snap, check, menu, pipelineFrame, settledFrame
- Defines here
- save, tap, snap, check, menu, pipelineFrame, settledFrame
- 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/all-controls.browser.mjs:1-119 · blob 46ecdbdebf74073fd7a22212322074b923b873fe · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import {chromium} from 'playwright';
import fs from 'node:fs';
import path from 'node:path';
import {createServer} from 'node:http';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
const root=path.resolve(import.meta.dirname,'../..');
const out=path.resolve(process.argv.includes('--out')?process.argv[process.argv.indexOf('--out')+1]:path.join(root,'work/controls-audit'));fs.mkdirSync(out,{recursive:true});
const server=createServer((req,res)=>{try{let p=path.resolve(root,'.'+decodeURIComponent(new URL(req.url,'http://localhost').pathname));if(!p.startsWith(root+path.sep))throw Error();if(fs.statSync(p).isDirectory())p=path.join(p,'index.html');res.setHeader('content-type',({'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json','.geojson':'application/geo+jso … [line shortened here: 560 characters; full line on GitHub]
await new Promise(r=>server.listen(0,'127.0.0.1',r));
const baseUrl=process.argv.includes('--url')?process.argv[process.argv.indexOf('--url')+1]:`http://127.0.0.1:${server.address().port}/atlas/`;
const browser=await chromium.launch({channel:process.argv.includes('--channel')?process.argv[process.argv.indexOf('--channel')+1]:process.platform==='win32'?'chrome':undefined,headless:true});
const report={startedAt:new Date().toISOString(),compositionSha256:createHash('sha256').update(fs.readFileSync(path.join(root,'atlas/current.json'))).digest('hex'),browser:await browser.version(),physicalAndroid:false,profiles:[]};
const profiles=process.argv.includes('--mobile')?[393]:process.argv.includes('--desktop')?[1440]:[1440,393];
try{for(const width of profiles){
const mobile=width<700,prefix=mobile?'android-emulation':'desktop';
const context=await browser.newContext({viewport:{width,height:mobile?852:1000},isMobile:mobile,hasTouch:mobile,acceptDownloads:true,...(mobile?{userAgent:'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Mobile Safari/537.36'}:{})});
await context.addInitScript(()=>{window.__auditPrints=0;addEventListener('beforeprint',()=>window.__auditPrints++);});
const page=await context.newPage();page.setDefaultTimeout(6000);
const r={profile:prefix,width,errors:[],dialogs:[],downloads:[],menus:{},checks:[]};report.profiles.push(r);
page.on('pageerror',e=>r.errors.push(String(e)));page.on('dialog',async d=>{r.dialogs.push(d.message());await d.dismiss();});page.on('download',async d=>{r.downloads.push(d.suggestedFilename());await d.saveAs(path.join(out,prefix+'-'+d.suggestedFilename()));});
const save=()=>fs.writeFileSync(path.join(out,prefix+'.json'),JSON.stringify({browser:report.browser,...r},null,2));
const tap=async loc=>mobile?await loc.tap():await loc.click();
const snap=async name=>page.screenshot({path:path.join(out,prefix+'-'+name+'.png')});
const state=()=>page.evaluate(()=>({fullscreen:document.fullscreenElement?.id,bodyClass:document.body.className,visible:[...document.querySelectorAll('button,input,select,[role=button]')].filter(e=>e.getBoundingClientRect().width&&e.getBoundingClientRect().height&&getComputedStyle(e).visibility!=='hidden').map(e=>({id:e.id,text:(e.innerText||e.getAttribute('aria-label')||e.getAttribute('placehold … [line shortened here: 713 characters; full line on GitHub]
async function check(name,fn){const c={name};r.checks.push(c);try{c.before=await state();await fn(c);await page.waitForTimeout(200);c.after=await state();c.completed=true;await snap(name.replace(/[^a-z0-9-]/gi,'-'));}catch(e){c.completed=false;c.error=String(e);await snap(name+'-failed').catch(()=>{});}save();console.log(prefix,name,c.completed,c.error||'');}
async function menu(name){const l=page.getByRole('button',{name,exact:true});if(await l.getAttribute('aria-expanded')!=='true')await tap(l);}
await page.goto(baseUrl,{waitUntil:'domcontentloaded',timeout:60000});
await page.waitForFunction(()=>window.__GRIDATLAS_V9_MAP__&&document.querySelectorAll('[data-gridatlas-layer-proxy]').length>=60,null,{timeout:90000});
r.generation=await page.evaluate(()=>window.__GRIDATLAS_ATLAS__.generation);r.inventory=await state();save();
for(const name of ['File','Edit','View','Scope','Grid','About'])await check('menu-'+name,async c=>{await menu(name);r.menus[name]=await page.locator('.gm-open .gm-panel').evaluateAll(xs=>xs.map(x=>({text:x.innerText,controls:[...x.querySelectorAll('button,input,select,summary,a')].map(e=>({tag:e.tagName,id:e.id,text:e.innerText||e.getAttribute('aria-label'),type:e.type,href:e.getAttribute('href') … [line shortened here: 517 characters; full line on GitHub]
for(const [name,id] of [['Edit','btn-status'],['Scope','btn-radius'],['Scope','btn-radius-area'],['Scope','btn-zonedraw'],['Scope','btn-measure']])await check(id,async c=>{
for(const close of await page.locator('.maplibregl-popup-close-button').all())if(await close.isVisible())await tap(close);
await menu(name);await tap(page.locator('#'+id));await page.keyboard.press('Escape');
const canvas=page.locator('.maplibregl-canvas');const b=await canvas.boundingBox();
if(id!=='btn-status')for(const [fx,fy] of [[.45,.48],[.62,.55],[.53,.66]]){if(mobile)await page.touchscreen.tap(b.x+b.width*fx,b.y+b.height*fy);else await page.mouse.click(b.x+b.width*fx,b.y+b.height*fy);await page.waitForTimeout(400);}
await page.waitForTimeout(500);c.activated=await state();c.sources=await page.evaluate(()=>Object.fromEntries(Object.entries(window.__GRIDATLAS_V9_MAP__.getStyle().sources).filter(([k])=>/measure|radius|zone/.test(k)).map(([k])=>[k,window.__GRIDATLAS_V9_MAP__.getSource(k)._data])));await snap(id+'-active');
const undo=id==='btn-measure'?'btn-measure-undo':id==='btn-zonedraw'?'btn-zonedraw-undo':null;
if(undo&&await page.locator('#'+undo).isVisible()){await tap(page.locator('#'+undo));await page.waitForTimeout(150);c.undo=await state();c.pointsAfterUndo=await page.evaluate(id=>window.__GRIDATLAS_V9_MAP__.getSource(id==='btn-measure'?'src-measure-points':'src-zonedraw-points')._data.features.length,id);}
const sourceFor={'btn-radius':'src-radius-circle','btn-radius-area':'src-radius-area','btn-zonedraw':'src-zonedraw-fill','btn-measure':'src-measure-line'}[id];if(sourceFor)assert.ok(c.sources[sourceFor]?.features?.length>0,'tool geometry must exist');
if(id==='btn-status')assert.equal(await page.locator('#btn-status').getAttribute('aria-pressed'),'true');
await menu(name);await tap(page.locator('#'+id));
});
await check('fullscreen',async c=>{await menu('View');await tap(page.locator('#btn-fullscreen'));await page.waitForFunction(()=>!!document.fullscreenElement);c.entered=await state();await menu('View');await tap(page.locator('#btn-fullscreen-exit'));await page.waitForFunction(()=>!document.fullscreenElement);});
await check('basemaps',async c=>{c.radios=[];for(const value of ['sat','dark']){await menu('Grid');const input=page.locator('input[name="gridatlas-menu-basemap"][value="'+value+'"]');await input.scrollIntoViewIfNeeded();await tap(input);await page.waitForTimeout(300);c.radios.push({value,checked:await input.isChecked(),layers:await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getStyle().layers.f … [line shortened here: 439 characters; full line on GitHub]
await check('csv-export',async c=>{await menu('File');await tap(page.locator('#btn-export'));await page.waitForTimeout(800);c.downloads=[...r.downloads];c.dialogs=[...r.dialogs];});
for(const [men,sel] of [['View','#gridatlas-gb-conditions button'],['About','#gridatlas-version-ledger button']])await check('expand-'+men,async c=>{await menu(men);await tap(page.locator(sel).first());c.text=await page.locator('.gm-open .gm-panel').innerText();await tap(page.locator(sel).first());});
await check('layer-panel-toggle',async c=>{await page.keyboard.press('Escape');await tap(page.locator('#gridatlas-dash-toggle'));c.hidden=await state();await tap(page.locator('#gridatlas-dash-toggle'));});
for(const id of ['gridatlas-export-image','gridatlas-export-pdf','gridatlas-export-print'])await check(id,async c=>{
await menu('File');const downloads=r.downloads.length;
if(id.endsWith('print'))await page.evaluate(()=>{
// Native headless print can clean its temporary raster before a later DOM
// sample. Observe the real call and decoded raster, then invoke native print.
const nativePrint=window.print.bind(window);
window.__auditPrintCall=null;
window.print=function(...args){
const image=document.getElementById('gridatlas-print-map');
window.__auditPrintCall={width:image?.naturalWidth||0,height:image?.naturalHeight||0,png:!!image?.src.startsWith('data:image/png')};
return nativePrint(...args);
};
});
const downloadPromise=id.endsWith('print')?null:page.waitForEvent('download',{timeout:15000});
await tap(page.locator('#'+id));
if(id.endsWith('print')){
await page.waitForFunction(()=>window.__auditPrintCall,null,{timeout:15000});
c.printCall=await page.evaluate(()=>window.__auditPrintCall);
assert.ok(c.printCall.png&&c.printCall.width>0&&c.printCall.height>0,'native print must receive a decoded map raster');
c.limitation='Native OS print dialog and physical printer not verified in headless Chrome';
}else{await downloadPromise;c.downloads=r.downloads.slice(downloads);assert.equal(c.downloads.length,1);}
c.label=await page.locator('#'+id).innerText();
});
await check('csv-export-loaded',async c=>{await menu('Grid');const solar=page.locator('[data-gridatlas-layer-proxy="engine:solar"]');c.available=await solar.count();if(!c.available)throw Error('solar selector unavailable');await solar.scrollIntoViewIfNeeded();await tap(solar);await page.waitForFunction(()=>/\[(OK|\d)/.test(document.getElementById('lbl-solar')?.textContent||''),null,{timeout:60000 … [line shortened here: 643 characters; full line on GitHub]
await check('search',async c=>{await page.keyboard.press('Escape');await page.locator('#search-input').fill('London');await tap(page.locator('#search-btn'));await page.locator('.search-result-item').first().waitFor({timeout:20000});c.results=await page.locator('#search-results').innerText();c.beforeCenter=await page.evaluate(()=>window.__GRIDATLAS_V9_MAP__.getCenter());await tap(page.locator('.se … [line shortened here: 582 characters; full line on GitHub]
await page.goto(`${baseUrl.split('?' )[0]}?technology=solar&latitude=52.6369&longitude=-1.1398&zoom=10&project=GRIDATLAS_PROOF_controls&capacity_mw=10`,{waitUntil:'domcontentloaded'});
await page.locator('.gridatlas-card-bar .min').first().waitFor({timeout:60000});
await page.waitForFunction(()=>window.__GRIDATLAS_PIPELINE_LAYERS__?.selection,null,{timeout:60000});
async function pipelineFrame(id){return page.evaluate(id=>{
const m=window.__GRIDATLAS_V9_MAP__,l=m.getLayer('l-pn-'+id),source=l&&m.getSource(l.source),bounds=m.getBounds(),canvas=m.getCanvas(),rect=canvas.getBoundingClientRect();
const points=(source?._data?.features||[]).map(f=>({coordinates:f.geometry?.coordinates,name:f.properties?.name}));
const inBounds=points.filter(f=>Array.isArray(f.coordinates)&&bounds.contains(f.coordinates));
return {center:m.getCenter(),zoom:m.getZoom(),bounds:bounds.toArray(),canvas:{x:rect.x,y:rect.y,width:rect.width,height:rect.height},moving:m.isMoving(),zooming:m.isZooming(),loaded:m.loaded(),tilesLoaded:m.areTilesLoaded(),sourceLoaded:!!l&&m.isSourceLoaded(l.source),layer:l?{id:l.id,minzoom:l.minzoom,maxzoom:l.maxzoom,filter:l.filter,visibility:m.getLayoutProperty(l.id,'visibility')||'visible' … [line shortened here: 524 characters; full line on GitHub]
},id);}
async function settledFrame(id){
let previous='',stable=0;const samples=[];
for(let i=0;i<40;i++){
const frame=await pipelineFrame(id);samples.push({center:frame.center,zoom:frame.zoom,moving:frame.moving,sourceLoaded:frame.sourceLoaded,rendered:frame.rendered,inBounds:frame.inBounds,tilesLoaded:frame.tilesLoaded});
const signature=JSON.stringify([frame.center,frame.zoom]);stable=!frame.moving&&signature===previous?stable+1:0;previous=signature;
if(stable>=3)return {frame,samples};await page.waitForTimeout(200);
}
throw Error('Pipeline camera did not settle: '+JSON.stringify(samples));
}
for(const id of ['same','wider','all'])await check('pipeline-'+id,async c=>{
await menu('Grid');const input=page.locator('[data-gridatlas-layer-proxy="pipeline:'+id+'"]');assert.equal(await input.count(),1);
await input.scrollIntoViewIfNeeded();c.initialChecked=await input.isChecked();if(!c.initialChecked)await tap(input);
await page.waitForFunction(id=>{const m=window.__GRIDATLAS_V9_MAP__,l=m.getLayer('l-pn-'+id);return l&&m.getSource(l.source)?._data?.features?.length>0;},id,{timeout:60000});
c.label=await input.getAttribute('aria-label');await tap(page.getByRole('button',{name:'Grid',exact:true}));
c.beforeFraming=await settledFrame(id);c.zoomOut=[];
// A 25 km search is not a promise that its points lie inside the arrival's
// tighter camera. Exercise real wheel input until all source points fit;
// record the original bounds so zero offscreen results cannot mask a failure.
for(let attempt=0;c.beforeFraming.frame.features>0&&attempt<8;attempt++){
const frame=attempt?c.zoomOut.at(-1).settled.frame:c.beforeFraming.frame;
if(frame.inBounds===frame.features)break;
const hit=await page.evaluate(()=>{const canvas=window.__GRIDATLAS_V9_MAP__.getCanvas(),r=canvas.getBoundingClientRect();for(const [fx,fy] of [[.5,.18],[.25,.3],[.75,.3],[.15,.55]]){const x=r.x+r.width*fx,y=r.y+r.height*fy;if(document.elementFromPoint(x,y)===canvas)return{x,y};}return null;});
assert.ok(hit,'zoom gesture needs an unobstructed canvas point');await page.mouse.move(hit.x,hit.y);await page.mouse.wheel(0,500);
await page.waitForTimeout(250);c.zoomOut.push({hit,deltaY:500,settled:await settledFrame(id)});
}
c.framed=await pipelineFrame(id);save();
assert.equal(c.framed.inBounds,c.framed.features,'test must frame the whole 25 km cohort before asserting paint');
await page.waitForFunction(id=>{const m=window.__GRIDATLAS_V9_MAP__,l=m.getLayer('l-pn-'+id);return l&&m.isSourceLoaded(l.source)&&m.queryRenderedFeatures({layers:[l.id]}).length>0;},id,{timeout:30000});
c.afterRender=await settledFrame(id);c.data={features:c.afterRender.frame.features,visibility:c.afterRender.frame.layer.visibility,rendered:c.afterRender.frame.rendered};
assert.ok(c.data.features>0);assert.ok(c.data.rendered>0);assert.equal(c.data.visibility,'visible');
await menu('Grid');await input.scrollIntoViewIfNeeded();await tap(input);await page.waitForFunction(id=>window.__GRIDATLAS_V9_MAP__.getLayoutProperty('l-pn-'+id,'visibility')==='none',id);assert.equal(await input.isChecked(),false);
});
await check('card-minimise-restore-close',async c=>{if(await page.getByRole('button',{name:'Grid',exact:true}).getAttribute('aria-expanded')==='true')await tap(page.getByRole('button',{name:'Grid',exact:true}));const popup=page.locator('.maplibregl-popup').filter({has:page.locator('.gridatlas-card-bar')}).first();c.initialMin=(await popup.getAttribute('class')).includes('gridatlas-min');await tap … [line shortened here: 868 characters; full line on GitHub]
for(const name of ['File','View','Scope','About']){await menu(name);r.menus[name]=await page.locator('.gm-open .gm-panel').evaluateAll(xs=>xs.map(x=>({text:x.innerText,controls:[...x.querySelectorAll('button,input,select,summary,a')].map(e=>({tag:e.tagName,id:e.id,text:e.innerText||e.getAttribute('aria-label'),type:e.type,href:e.getAttribute('href'),disabled:e.disabled}))})));}
r.final=await state();save();await context.close();
}}finally{fs.writeFileSync(path.join(out,'report.json'),JSON.stringify(report,null,2));await browser.close();await new Promise(r=>server.close(r));}
if(report.profiles.some(r=>r.errors.length||r.checks.some(c=>!c.completed)))process.exitCode=1;All Layer Clicks Browser
A JavaScript module in the proofs folder of GridAtlas. It is built from the arg step (`arg`), the open step (`open`) and the point step (`point`).
rendergridatlas / tools/proofs/all-layer-clicks.browser.mjs · lines 1–92 of 92 · Entry point · pattern point (shared by 35 files)
- What it does
- It fetches data. Defines arg, open, point. Uses libraries playwright, node:fs, node:path, node:http. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: command-line arguments. Out: JSON file results.json.
- Downstream impact
- Used directly by 1 file: GridAtlas Cartridge Proof Workflow (gridatlas).
- What it achieves
- Drive every real Grid control and verify paint, feature picking and off-state.
- Why it matters
- Run by GridAtlas Cartridge Proof Workflow.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- playwright, node:fs, node:path, node:http
- Used by
- run by GridAtlas Cartridge Proof Workflow (workflow run)
- Produces
- arg, open, point
- Defines here
- arg, open, point
- 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/all-layer-clicks.browser.mjs:1-92 · blob bbe2fb43d63483c91621c476501591971b6feeef · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Drive every real Grid control and verify paint, feature picking and off-state. */
import {chromium} from 'playwright';
import fs from 'node:fs';
import path from 'node:path';
import {createServer} from 'node:http';
const arg=(key,fallback)=>process.argv.includes(key)?process.argv[process.argv.indexOf(key)+1]:fallback;
const root=path.resolve(import.meta.dirname,'../..');
const out=path.resolve(arg('--out',path.join(root,'work/layer-clicks')));
fs.mkdirSync(out,{recursive:true});
let server;
let url=arg('--url','');
if(!url){
server=createServer((req,res)=>{
try{
let p=path.resolve(root,'.'+decodeURIComponent(new URL(req.url,'http://localhost').pathname));
if(!p.startsWith(root+path.sep))throw Error('outside root');
if(fs.statSync(p).isDirectory())p=path.join(p,'index.html');
res.setHeader('content-type',({'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json','.geojson':'application/geo+json','.css':'text/css','.wasm':'application/wasm'})[path.extname(p)]||'application/octet-stream');
res.setHeader('cache-control','no-store');res.end(fs.readFileSync(p));
}catch{res.writeHead(404).end();}
});
await new Promise(r=>server.listen(0,'127.0.0.1',r));url=`http://127.0.0.1:${server.address().port}/atlas/`;
}
const width=Number(arg('--width','1440'));
const browser=await chromium.launch({channel:arg('--channel',process.platform==='win32'?'chrome':undefined),headless:true});
const results=[];
const requested=arg('--ids','');
let ids=requested?requested.split(','):null;
async function open(){
const context=await browser.newContext({viewport:{width,height:width<700?852:1000},hasTouch:width<700,isMobile:width<700,...(width<700?{userAgent:'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Mobile Safari/537.36'}:{})});
const page=await context.newPage();page.setDefaultTimeout(15000);
await page.goto(url,{waitUntil:'domcontentloaded',timeout:60000});
await page.waitForFunction(()=>document.querySelectorAll('[data-gridatlas-layer-proxy]').length>=60&&window.__GRIDATLAS_V9_MAP__,null,{timeout:60000});
return {context,page};
}
try{
if(!ids){const {context,page}=await open();ids=await page.locator('#scada-ui-container input[data-layer-id]').evaluateAll(xs=>xs.map(x=>x.dataset.layerId));await context.close();}
for(const id of ids){
const r={id};let context,page;
try{
({context,page}=await open());r.errors=[];page.on('pageerror',e=>r.errors.push(String(e)));
r.generation=await page.evaluate(()=>window.__GRIDATLAS_ATLAS__.generation);
const proxy=page.locator(`[data-gridatlas-layer-proxy="engine:${id}"]`),grid=page.getByRole('button',{name:'Grid',exact:true});
await grid.click();await proxy.scrollIntoViewIfNeeded();
r.initialLabel=await proxy.getAttribute('aria-label');
await proxy.click();
await page.waitForFunction(id=>/\[(OK|EMPTY|FAIL|\d)/.test(document.getElementById('lbl-'+id)?.textContent||''),id,{timeout:60000,polling:200});
r.label=await proxy.getAttribute('aria-label');r.checked=await proxy.isChecked();r.disabled=await proxy.isDisabled();
await page.screenshot({path:path.join(out,`${id}-control.png`)});
await grid.click();
const source=await page.evaluate(async id=>{
const m=window.__GRIDATLAS_V9_MAP__,layer=m.getStyle().layers.find(x=>x.id==='l-'+id);let data=m.getSource(layer.source)._data;
if(typeof data==='string')data=await(await fetch(new URL(data,document.baseURI))).json();
function value(e,f){if(!Array.isArray(e))return e;const [op,...a]=e;if(op==='get')return f.properties?.[a[0]];if(op==='literal')return a[0];if(op==='coalesce')return a.map(x=>value(x,f)).find(x=>x!=null);if(op==='to-number')return Number(value(a[0],f));if(op==='all')return a.every(x=>value(x,f));if(op==='any')return a.some(x=>value(x,f));if(op==='!')return !value(a[0],f);if(op==='==')return va … [line shortened here: 632 characters; full line on GitHub]
const eligible=(data.features||[]).filter(f=>(layer.type==='circle'?['Point','MultiPoint']:['LineString','MultiLineString']).includes(f.geometry?.type)&&(!layer.filter||value(layer.filter,f)));
function point(g){let c=g.coordinates;while(Array.isArray(c[0]))c=c[Math.floor(c.length/2)];return c;}
const sample=eligible.find(f=>{const c=point(f.geometry);return c[0]>-8&&c[0]<2&&c[1]>50&&c[1]<59;})||eligible[0];
const target=sample?point(sample.geometry):null;
if(target)m.jumpTo({center:target,zoom:Math.max(layer.minzoom||0,layer.type==='line'?10:9)+.5});
return {layer,featureCount:data.features?.length,eligible:eligible.length,target,sample:sample?{id:sample.id,properties:sample.properties}:null};
},id);
Object.assign(r,source);
if(source.eligible&&r.checked&&!r.disabled){
await page.waitForFunction(id=>{const m=window.__GRIDATLAS_V9_MAP__,l=m.getLayer('l-'+id);return m.isSourceLoaded(l.source)&&m.queryRenderedFeatures({layers:['l-'+id]}).length>0;},id,{timeout:30000});
await page.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r))));
r.rendered=await page.evaluate(id=>window.__GRIDATLAS_V9_MAP__.queryRenderedFeatures({layers:['l-'+id]}).length,id);
await page.screenshot({path:path.join(out,`${id}-map.png`)});
const hit=await page.evaluate(target=>{const m=window.__GRIDATLAS_V9_MAP__,p=m.project(target),b=m.getCanvas().getBoundingClientRect();return {x:b.left+p.x,y:b.top+p.y};},source.target);
if(width<700)await page.touchscreen.tap(hit.x,hit.y);else await page.mouse.click(hit.x,hit.y);
await page.waitForTimeout(250);
r.popup=await page.locator('.maplibregl-popup').count();
r.popupText=r.popup?await page.locator('.maplibregl-popup').allTextContents():[];
await page.screenshot({path:path.join(out,`${id}-picked.png`)});
// Close any card through its real close button before testing the off switch.
for(const popup of await page.locator('.maplibregl-popup').all()){
const custom=popup.locator('.gridatlas-card-bar .close');
const close=await custom.count()?custom:popup.locator('.maplibregl-popup-close-button');
const box=await close.boundingBox();
if(!box||box.x<0||box.y<0||box.x+box.width>width||box.y+box.height>(width<700?852:1000))throw Error('card close control is clipped by the viewport');
if(width<700)await close.tap();else await close.click();
}
await grid.click();await proxy.scrollIntoViewIfNeeded();await proxy.click();
r.off=!(await proxy.isChecked())&&await page.evaluate(id=>window.__GRIDATLAS_V9_MAP__.getLayoutProperty('l-'+id,'visibility')==='none',id);
}
r.pass=!!(r.checked&&!r.disabled&&r.eligible>0&&r.rendered>0&&r.popup>0&&r.off&&r.errors.length===0);
}catch(e){r.error=String(e);r.pass=false;}
finally{if(context)await context.close();}
results.push(r);fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({url,width,results},null,2));
console.log(JSON.stringify({id:r.id,label:r.label,eligible:r.eligible,rendered:r.rendered,popup:r.popup,off:r.off,pass:r.pass,error:r.error}));
}
}finally{await browser.close();if(server)await new Promise(r=>server.close(r));}
if(results.some(r=>!r.pass))process.exitCode=1;