In this section
- Verify Overnight Candidate render · gridatlas / orchestration/202608310015-gridatlas-overnight-next-versions/202608310015-verify-overnight-candidate.mjs lines 1–301
- G203 03 Gps Camera Test test · gridatlas / tests/g203-03-gps-camera.test.mjs lines 1–50
- GridAtlas Build Cartridge storage · gridatlas / tools/build-cartridge.mjs lines 1–182
- Audit ingest · gridatlas / tools/cartridges/audit.mjs lines 1–110
Verify Overnight Candidate
A JavaScript module in the orchestration folder of GridAtlas that draws GridAtlas overnight candidate proof, UK motorways, UK trunk roads and UK primary roads.
rendergridatlas / orchestration/202608310015-gridatlas-overnight-next-versions/202608310015-verify-overnight-candidate.mjs · lines 1–301 of 301 · version 2026-08-31 00:15 · Entry point · pattern record (shared by 46 files)
- What it does
- It draws GridAtlas overnight candidate proof, UK motorways, UK trunk roads and UK primary roads. Defines 6 functions or classes, including invariant, record, ensureParent, waitCompositionReady, openCandidate. Uses libraries node:fs/promises, node:path, playwright. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV.
- Inputs & outputs
- In: JSON file 202608310015-gridatlas-overnight-candidate-proof.json; GeoJSON file uk_motorways.geojson; GeoJSON file uk_trunk_roads.geojson; GeoJSON file uk_primary_roads.geojson. Voltage levels named: 400kV.
- Downstream impact
- Used directly by 1 file: GridAtlas Overnight Next Versions Workflow (gridatlas).
- What it achieves
- It opens candidate (`openCandidate`) and is built from the ensure parent helper (`ensureParent`) and the wait composition ready helper (`waitCompositionReady`). Its name says it verifies overnight candidate. Defines `invariant`, `record`, `ensureParent` and 3 more. Its code works with 400 kV.
- Why it matters
- Run by GridAtlas Overnight Next Versions Workflow.
- Application
- gridatlas · orchestration/202608310015-gridatlas-overnight-next-versions · JavaScript module
- Uses
- node:fs/promises, node:path, playwright
- Used by
- run by GridAtlas Overnight Next Versions Workflow (workflow run)
- Produces
- invariant, record, ensureParent, waitCompositionReady, openCandidate, submitQuery
- Defines here
- invariant, record, ensureParent, waitCompositionReady, openCandidate, submitQuery
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 orchestration/202608310015-gridatlas-overnight-next-versions/202608310015-verify-overnight-candidate.mjs:1-301 · blob b8c3d7c7aef55b921b463e42a7364f82f21e0eac · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import fs from 'node:fs/promises';
import path from 'node:path';
import { chromium } from 'playwright';
const base = String(process.env.GRIDATLAS_URL || '').replace(/\/?$/, '/');
const expectedGeneration = String(process.env.EXPECTED_GENERATION || '');
const expectedSearchGeneration = String(process.env.EXPECTED_SEARCH_GENERATION || '');
const output = String(process.env.OUTPUT || 'work/202608310015-gridatlas-overnight-candidate-proof.json');
const screenshot = String(process.env.SCREENSHOT || output.replace(/\.json$/, '.png'));
if (!base || !expectedGeneration) throw new Error('GRIDATLAS_URL and EXPECTED_GENERATION are required');
const expectedRoads = new Map([
['motorways', { rows: 17713, path: '/uk_motorways.geojson' }],
['trunk_roads', { rows: 130228, path: '/uk_trunk_roads.geojson' }],
['primary_roads', { rows: 163790, path: '/uk_primary_roads.geojson' }]
]);
const proof = {
schema: 'gridatlas.overnight-candidate-browser-proof.v1',
tested_at: new Date().toISOString(),
url: base,
expected_generation: expectedGeneration,
expected_search_generation: expectedSearchGeneration,
status: 'RUNNING',
hard_failures: 0,
soft_failures: 0,
tests: [],
console_errors: [],
page_errors: [],
runtime: null
};
function invariant(condition, message) {
if (!condition) throw new Error(message);
}
async function record(name, severity, action) {
const row = { name, severity, status: 'RUNNING', started_at: new Date().toISOString() };
proof.tests.push(row);
try {
row.evidence = await action();
row.status = 'PASS';
} catch (error) {
row.status = severity === 'soft' ? 'SOFT_FAIL' : 'FAIL';
row.error = String(error?.stack || error);
if (severity === 'soft') proof.soft_failures += 1;
else proof.hard_failures += 1;
}
row.finished_at = new Date().toISOString();
console.log(JSON.stringify({ test: name, severity, status: row.status, error: row.error || null }));
return row;
}
async function ensureParent(filePath) {
await fs.mkdir(path.dirname(filePath), { recursive: true });
}
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
const page = await context.newPage();
const cdp = await context.newCDPSession(page);
page.on('console', message => {
if (message.type() === 'error') proof.console_errors.push(message.text());
});
page.on('pageerror', error => proof.page_errors.push(String(error?.message || error)));
async function waitCompositionReady() {
await page.waitForFunction(({ generation, searchGeneration }) => {
const atlas = window.__GRIDATLAS_ATLAS__;
const search = window.__GRIDATLAS_PLACE_SEARCH__;
return atlas?.generation === generation &&
window.__GRIDATLAS_V9_MAP__ &&
search?.ready === true &&
(!searchGeneration || search.generation === searchGeneration);
}, { generation: expectedGeneration, searchGeneration: expectedSearchGeneration }, { timeout: 120_000 });
}
async function openCandidate(search = '') {
const separator = search ? (search.startsWith('?') ? '' : '?') : '?';
const suffix = search ? `${separator}${search.replace(/^\?/, '')}&proof=${Date.now()}` : `?proof=${Date.now()}`;
await page.goto(`${base}${suffix}`, { waitUntil: 'domcontentloaded', timeout: 120_000 });
await waitCompositionReady();
}
async function submitQuery(text, { sequential = false } = {}) {
const input = page.locator('#search-input');
await input.waitFor({ state: 'visible', timeout: 30_000 });
await input.fill('');
if (sequential) await input.pressSequentially(text, { delay: 220 });
else await input.fill(text);
await input.press('Enter');
await page.waitForFunction(expected => window.__GRIDATLAS_PLACE_SEARCH__?.last_query === expected, text, { timeout: 120_000 });
await page.locator('#search-results').waitFor({ state: 'visible', timeout: 120_000 });
}
await record('composition loads frozen shell and required cartridges', 'hard', async () => {
await openCandidate();
const state = await page.evaluate(() => ({
atlas: window.__GRIDATLAS_ATLAS__,
search_generation: window.__GRIDATLAS_PLACE_SEARCH__?.generation,
search_ready: window.__GRIDATLAS_PLACE_SEARCH__?.ready,
map_ready: Boolean(window.__GRIDATLAS_V9_MAP__)
}));
const order = state.atlas?.cartridge_order || [];
invariant(state.atlas?.generation === expectedGeneration, 'candidate composition generation mismatch');
invariant(state.map_ready, 'map object missing');
invariant(state.search_ready, 'search cartridge not ready');
if (expectedSearchGeneration) invariant(state.search_generation === expectedSearchGeneration, 'search cartridge generation mismatch');
invariant(order.includes('streaming-parquet-bridge'), 'streaming road cartridge missing');
invariant(order.includes('uk-gazetteer-flyto'), 'search cartridge missing');
invariant(order.indexOf('streaming-parquet-bridge') < order.indexOf('uk-gazetteer-flyto'), 'required cartridge order reversed');
return state;
});
await record('direct repd_ref=13599 resolves Beacon Fen', 'hard', async () => {
await openCandidate('repd_ref=13599');
await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.status === 'RESOLVED', null, { timeout: 120_000 });
await page.locator('.maplibregl-popup-content').filter({ hasText: 'Beacon Fen Energy Park' }).waitFor({ state: 'visible', timeout: 30_000 });
const state = await page.evaluate(() => ({
deep_link: window.__GRIDATLAS_PLACE_SEARCH__?.deep_link,
selection: window.__GRIDATLAS_PLACE_SEARCH__?.last_selection,
url: location.href,
popup: document.querySelector('.maplibregl-popup-content')?.textContent || ''
}));
invariant(state.deep_link?.repd_ref === '13599' && state.deep_link?.mapped === true, 'deep link did not map');
invariant(new URL(state.url).searchParams.get('repd_ref') === '13599', 'repd_ref was lost');
invariant(state.popup.includes('Beacon Fen Energy Park'), 'Beacon Fen popup missing');
return state;
});
await record('Beacon Fen search is REPD-first and sets identity', 'hard', async () => {
await openCandidate();
await submitQuery('Beacon Fen');
const exact = page.locator('.search-result-item[data-repd-ref="13599"]').first();
await exact.waitFor({ state: 'visible', timeout: 60_000 });
const firstRef = await page.locator('.search-result-item').first().getAttribute('data-repd-ref');
invariant(firstRef === '13599', `first result was ${firstRef || 'missing'}`);
await exact.click();
await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.last_selection?.repd_ref === '13599', null, { timeout: 30_000 });
const state = await page.evaluate(() => ({ selection: window.__GRIDATLAS_PLACE_SEARCH__?.last_selection, url: location.href }));
invariant(new URL(state.url).searchParams.get('repd_ref') === '13599', 'Beacon Fen selection did not set repd_ref');
return state;
});
await record('SW1A 1AA remains LOCATION_ONLY', 'soft', async () => {
await openCandidate();
await submitQuery('SW1A 1AA', { sequential: true });
const postcode = page.locator('.search-result-item[data-location-kind="postcode"]').first();
await postcode.waitFor({ state: 'visible', timeout: 90_000 });
await page.waitForTimeout(2500);
invariant(await postcode.isVisible(), 'postcode result was overwritten');
await postcode.click();
await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection?.kind === 'postcode' && window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection?.mapped === true, null, { timeout: 30_000 });
const state = await page.evaluate(() => ({
location: window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection,
popup: document.querySelector('.maplibregl-popup-content')?.textContent || '',
url: location.href
}));
invariant(!new URL(state.url).searchParams.has('repd_ref'), 'postcode claimed project identity');
invariant(state.popup.includes('Location only') && state.popup.includes('postcodes.io'), 'postcode provenance missing');
return state;
});
await record('Truro flies as a UK location', 'soft', async () => {
await submitQuery('Truro');
const result = page.locator('.search-result-item[data-location-kind="place"]').filter({ hasText: 'Truro' }).first();
await result.waitFor({ state: 'visible', timeout: 90_000 });
await result.click();
await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection?.kind === 'place' && window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection?.mapped === true, null, { timeout: 30_000 });
const state = await page.evaluate(() => ({ location: window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection, url: location.href }));
invariant(/truro/i.test(state.location?.label || ''), 'Truro label missing');
invariant(!new URL(state.url).searchParams.has('repd_ref'), 'Truro claimed project identity');
return state;
});
await record('Oxford, England, UK flies without identity', 'soft', async () => {
await submitQuery('Oxford, England, UK');
const result = page.locator('.search-result-item[data-location-kind]').filter({ hasText: 'Oxford' }).first();
await result.waitFor({ state: 'visible', timeout: 90_000 });
await result.click();
await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection?.mapped === true, null, { timeout: 30_000 });
const state = await page.evaluate(() => ({ location: window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection, url: location.href }));
invariant(state.location.latitude > 51.5 && state.location.latitude < 52.0, 'Oxford latitude out of range');
invariant(state.location.longitude > -1.6 && state.location.longitude < -0.8, 'Oxford longitude out of range');
invariant(!new URL(state.url).searchParams.has('repd_ref'), 'Oxford claimed project identity');
return state;
});
await record('Delhi flies through Nominatim', 'soft', async () => {
await submitQuery('Delhi');
const result = page.locator('.search-result-item[data-location-kind="global_place"]').filter({ hasText: 'Delhi' }).first();
await result.waitFor({ state: 'visible', timeout: 120_000 });
await result.click();
await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection?.kind === 'global_place' && window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection?.mapped === true, null, { timeout: 30_000 });
const state = await page.evaluate(() => ({ location: window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection, url: location.href }));
invariant(state.location.latitude > 27.5 && state.location.latitude < 29.8, 'Delhi latitude out of range');
invariant(state.location.longitude > 76.0 && state.location.longitude < 78.5, 'Delhi longitude out of range');
invariant(state.location.provider === 'Nominatim / OpenStreetMap', 'unexpected global provider');
invariant(!new URL(state.url).searchParams.has('repd_ref'), 'Delhi claimed project identity');
return state;
});
await record('Parquet runtime prewarms after 400 kV readiness', 'hard', async () => {
await openCandidate();
await page.waitForFunction(() => document.querySelectorAll('#scada-ui-container input[data-layer-id]').length > 0, null, { timeout: 120_000 });
await page.waitForFunction(() => {
const state = window.__GRIDATLAS_MAP_READY__;
return state?.runtime_prewarm?.completed === true || state?.runtime_prewarm?.failed;
}, null, { timeout: 120_000 });
const state = await page.evaluate(() => window.__GRIDATLAS_MAP_READY__?.runtime_prewarm);
invariant(state?.completed === true, `runtime prewarm failed: ${JSON.stringify(state)}`);
return state;
});
for (const [layerId, target] of expectedRoads) {
await record(`${layerId} streams, loads and stays inside browser budgets`, 'hard', async () => {
const selector = `#scada-ui-container input[data-layer-id="${layerId}"]`;
const control = page.locator(selector);
invariant(await control.count() === 1, `${layerId}: layer control missing`);
if (await control.isChecked()) await control.uncheck({ force: true });
const started = performance.now();
await control.check({ force: true });
await page.waitForFunction(id => {
const label = document.querySelector(`#lbl-${CSS.escape(id)}`)?.textContent || '';
return /\[(OK|EMPTY|FAIL)\]/.test(label);
}, layerId, { timeout: 60_000 });
const terminal = await page.evaluate(id => {
const map = window.__GRIDATLAS_V9_MAP__;
const mapLayer = map?.getLayer(`l-${id}`);
return {
source_id: mapLayer?.source || null,
label: document.querySelector(`#lbl-${CSS.escape(id)}`)?.textContent || ''
};
}, layerId);
if (terminal.source_id && terminal.label.includes('[OK]')) {
await page.waitForFunction(sourceId => {
try { return window.__GRIDATLAS_V9_MAP__?.isSourceLoaded(sourceId) === true; } catch { return false; }
}, terminal.source_id, { timeout: 60_000 });
}
const seconds = (performance.now() - started) / 1000;
await page.waitForTimeout(250);
await cdp.send('HeapProfiler.collectGarbage');
const heapMb = (await cdp.send('Runtime.getHeapUsage')).usedSize / 1e6;
const state = await page.evaluate(({ id, pathname }) => {
const map = window.__GRIDATLAS_V9_MAP__;
const mapLayer = map?.getLayer(`l-${id}`);
const sourceId = mapLayer?.source || null;
let loaded = false;
let rendered = 0;
try {
loaded = Boolean(sourceId && map.isSourceLoaded(sourceId));
rendered = map.queryRenderedFeatures({ layers: [`l-${id}`] }).length;
} catch {}
const transport = window.__GRIDATLAS_MAP_READY__;
const entry = Object.entries(transport?.loaded_on_demand || {}).find(([key]) => key.endsWith(pathname));
return {
source_id: sourceId,
loaded,
rendered,
rows: entry?.[1]?.rows ?? -1,
parquet: entry?.[1]?.parquet ?? null,
streamed_responses: transport?.streamed_responses ?? -1,
released_payloads: transport?.released_payloads ?? -1,
stream_failures: transport?.stream_failures || [],
label: document.querySelector(`#lbl-${CSS.escape(id)}`)?.textContent || ''
};
}, { id: layerId, pathname: target.path });
invariant(state.label.includes('[OK]'), `${layerId}: terminal label ${state.label}`);
invariant(state.loaded, `${layerId}: source not loaded`);
invariant(state.rows === target.rows, `${layerId}: ${state.rows} rows, expected ${target.rows}`);
invariant(state.streamed_responses >= 1, `${layerId}: no streamed response recorded`);
invariant(state.released_payloads >= state.streamed_responses, `${layerId}: payload cache not released`);
invariant(state.stream_failures.length === 0, `${layerId}: stream failures present`);
invariant(seconds <= 15, `${layerId}: ${seconds.toFixed(2)}s exceeded 15s`);
invariant(heapMb <= 400, `${layerId}: ${heapMb.toFixed(1)}MB exceeded 400MB`);
await control.uncheck({ force: true }).catch(() => {});
return { layer_id: layerId, expected_rows: target.rows, seconds, heap_mb: heapMb, ...state };
});
}
proof.runtime = await page.evaluate(() => ({
atlas: window.__GRIDATLAS_ATLAS__ || null,
search: window.__GRIDATLAS_PLACE_SEARCH__ || null,
transport: window.__GRIDATLAS_MAP_READY__ || null,
ready_state: document.readyState
})).catch(() => null);
proof.status = proof.hard_failures > 0
? 'FAIL'
: proof.soft_failures > 0
? 'CORE_PASS_EXTERNAL_UNAVAILABLE'
: 'PASS';
await ensureParent(output);
await ensureParent(screenshot);
await page.screenshot({ path: screenshot, fullPage: true }).catch(error => {
proof.screenshot_error = String(error?.message || error);
});
await fs.writeFile(output, `${JSON.stringify(proof, null, 2)}\n`);
await browser.close();
console.log(JSON.stringify({ status: proof.status, hard_failures: proof.hard_failures, soft_failures: proof.soft_failures, output, screenshot }));
process.exit(proof.hard_failures > 0 ? 1 : 0);G203 03 Gps Camera Test
A test in the tests folder of GridAtlas that checks G203 03 Gps Camera Candidate. It runs gps regression (`runGpsRegression`) and sets fix (`setFix`).
testgridatlas / tests/g203-03-gps-camera.test.mjs · lines 1–50 of 50 · Entry point · pattern fieldState (shared by 8 files)
- What it does
- It tests its inputs. Defines runGpsRegression, cut, fieldState, setFix, make. Uses libraries node:fs. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'gps'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Downstream impact
- Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- G203-03: deterministic GPS callback/camera tests against the actual candidate source.
- Why it matters
- Run by GridAtlas PR File Size Guard Workflow.
- Application
- gridatlas · tests · test
- Uses
- G203 03 Gps Camera Candidate (new URL import.meta.url), node:fs
- Used by
- run by GridAtlas PR File Size Guard Workflow (workflow run)
- Produces
- runGpsRegression, cut, fieldState, setFix, make
- Defines here
- runGpsRegression, cut, fieldState, setFix, make
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tests/g203-03-gps-camera.test.mjs:1-50 · blob 78c4f498d0fa98df336f6434676f2bf8acf80a3d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
// G203-03: deterministic GPS callback/camera tests against the actual candidate source.
// Run: node tests/g203-03-gps-camera.test.mjs
import { readFileSync } from 'node:fs';
function runGpsRegression(source){
const cut=(a,b)=>{const i=source.indexOf(a),j=source.indexOf(b,i+1);if(i<0||j<0)throw Error("missing anchor "+a);return source.slice(i,j)};
const helpers=cut(" let locationRequestedAt = null"," let resumedAt = null");
const handlers=cut(" function stopTracking(message)"," document.addEventListener('visibilitychange'");
const code=`
let clock=10000, zoom=8, max=22, watch=null,generation=0,pendingLocation=false,followCamera=false,fix=null,lastFixMs=-Infinity,permissionDenied=false,picking=null,notice='', roles={from:null}, watchCalls=0, clears=0, nextId=0, renders=0, callbacks=[], jumps=[], pinCalls=0;
const Date={now:()=>clock}, document={hidden:false}, isSecureContext=true;
const controls={location:{},stop:{}}, notify=()=>{}, render=()=>renders++;
const map={getZoom:()=>zoom,getMaxZoom:()=>max,jumpTo:(v)=>{jumps.push(v);if('zoom'in v)zoom=v.zoom;pauseGesture({});}};
const fieldState=f=>({gpsState:!f?'missing':document.hidden?'background':clock-f.timestampMs>10000?'stale':f.accuracyM>30?'poor':'usable',showMeasuredFix:!!f&&!document.hidden&&clock-f.timestampMs<=10000});
const setFix=f=>fix=f, setPin=()=>{roles.from='gps';pinCalls++;};
const navigator={geolocation:{watchPosition:(ok,fail,options)=>{watchCalls++;callbacks.push({ok,fail,options});return ++nextId;},clearWatch:()=>clears++}};
${helpers}
${handlers}
return {start:()=>controls.location.onclick(),stop:()=>controls.stop.onclick(),drag:()=>pauseFollow(),pinch:()=>pauseGesture({originalEvent:{}}),programmatic:()=>pauseGesture({}),clock:v=>clock=v,zoom:v=>zoom=v,max:v=>max=v,hidden:v=>document.hidden=v,manualFrom:()=>roles.from='manual',sample:(t,accuracy=5,longitude=-0.1,i=callbacks.length-1)=>callbacks[i].ok({timestamp:t,coords:{longitude,lat … [line shortened here: 629 characters; full line on GitHub]
`;
const make=()=>new Function(code)();
let n=0;const checks=[];function check(label,value){if(!value)throw Error(label);checks.push(label);n++;}
new Function(source);check("complete cartridge parses",true);
let h=make();h.start();h.start();check("single GPS watch",h.state().watchCalls===1);
check("no cached fixes requested",h.state().options.maximumAge===0);
h.sample(9999);check("pre-request fix does not move camera",h.state().jumps.length===0);
h.clock(10001);h.sample(10001,80);check("poor fix does not move camera",h.state().jumps.length===0);
h.clock(10002);h.sample(10002);check("first fresh fix zooms to 17",h.state().jumps[0].zoom===17);
check("empty FROM established once",h.state().pinCalls===1);
h.zoom(19);h.clock(10003);h.sample(10003,5,-.1003);check("measured movement recentres without changing zoom",h.state().jumps.length===2&&!('zoom'in h.state().jumps[1])&&h.state().jumps[1].center[0]===-.1003);
h.sample(10003);check("duplicate timestamp ignored",h.state().jumps.length===2);
h.sample(10002);check("out-of-order timestamp ignored",h.state().jumps.length===2);
h.pinch();check("pinch pauses follow",!h.state().followCamera);
h.clock(10004);h.sample(10004);check("paused camera stays put",h.state().jumps.length===2);
h.start();check("resume follows without another watch or zoom",h.state().watchCalls===1&&h.state().followCamera&&h.state().jumps.length===3&&!('zoom'in h.state().jumps[2]));
h.programmatic();check("programmatic zoom does not pause follow",h.state().followCamera);
h.drag();check("drag pauses follow",!h.state().followCamera);
h.hidden(true);h.clock(10005);h.sample(10005);check("background sample does not move camera",h.state().jumps.length===3);
h.hidden(false);h.stop();check("stop clears watch",h.state().clears===1&&h.state().watch===null);
h.start();h.clock(10006);h.sample(10006,5,-.2,0);check("old watch callback rejected",h.state().jumps.length===3);
h.error(1);check("permission denial stops current watch",h.state().watch===null&&h.state().clears===2&&h.state().notice.includes('denied'));
h=make();h.manualFrom();h.zoom(19);h.start();h.sample(10000);check("existing closer zoom preserved",h.state().jumps[0].zoom===19);check("manual FROM preserved",h.state().from==='manual'&&h.state().pinCalls===0);
h=make();h.max(15);h.start();h.sample(10000);check("street zoom respects map maximum",h.state().jumps[0].zoom===15);
h=make();h.start();h.drag();h.sample(10000);check("drag before first fix prevents camera jump",h.state().jumps.length===0&&h.state().pinCalls===1);
h=make();h.start();h.error(2);check("temporary loss retains watch",h.state().watchCalls===1&&h.state().watch!==null);h.clock(10001);h.sample(10001);check("fresh signal recovers after loss",h.state().jumps[0].zoom===17);
check("symmetric gesture registration",['zoomstart','rotatestart','pitchstart'].every(e=>source.includes("map.on('"+e+"',pauseGesture)")&&source.includes("map?.off('"+e+"',pauseGesture)")));
return {n,checks};
}
const source=readFileSync(new URL('../atlas/modules/g203-03-gps-camera-candidate.js',import.meta.url),'utf8');
const result=runGpsRegression(source);
console.log(JSON.stringify(result,null,2));GridAtlas Build Cartridge
A JavaScript module in the tools folder that reads substations, using SHA-256. It reads lf (`readLf`) and is built from the argv step (`argv`) and the sha256 step (`sha256`).
storagegridatlas / tools/build-cartridge.mjs · lines 1–182 of 182 · Not reached from any entry point (candidate for review) · pattern exists (shared by 14 files)
- What it does
- It loads substations. Defines argv, sha256, readLf, exists. Uses libraries node:fs/promises, node:fs, node:crypto, node:path, node:url. Side effects: 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: command-line arguments.
- What it achieves
- Assemble a cartridge from modules, and record what went into it.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools · JavaScript module
- Uses
- node:fs/promises, node:fs, node:crypto, node:path, node:url
- Used by
- none found
- Produces
- argv, sha256, readLf, exists
- Defines here
- argv, sha256, readLf, exists
- 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/build-cartridge.mjs:1-182 · blob 94b20bb9a853da8861de254cdd8cfca164eabcda · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
* Assemble a cartridge from modules, and record what went into it.
*
* The composer's contract is one file per shell script slot, so a
* cartridge must arrive as one file. That does not mean it has to be
* WRITTEN as one file. This assembles a generation-stamped cartridge from
* a named list of parts and emits a manifest recording each part's
* SHA-256, so the thing that ships is one file and the thing that is
* maintained is a list of small ones.
*
* It does not decide anything. It concatenates in the order given, with a
* header naming the parts, and refuses to run if any part is missing or if
* the output would collide with a generation that already exists -
* cartridges are immutable here.
*
* node tools/build-cartridge.mjs \
* --generation 202609012000 \
* --name substation-intelligence-v9-62 \
* --carry atlas/releases/<id>/ventus-corev8engine.js \
* --module atlas/modules/202609011950-geodesy.js \
* --module atlas/modules/202609011950-substation-lookup.js \
* --part atlas/parts/202609012000-substation-intelligence-body.js
*
* --carry is a shell script carried forward verbatim for a replace-script
* slot; it is hashed separately and recorded as such, because carrying a
* shell file forward unchanged is a promise the manifest has to keep.
*/
import { readFile, writeFile, access, mkdir, rm } from 'node:fs/promises';
import { constants } from 'node:fs';
import { createHash } from 'node:crypto';
import { dirname, join, resolve, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = resolve(HERE, '..');
function argv(flag, { many = false } = {}) {
const values = [];
for (let i = 2; i < process.argv.length; i += 1) {
if (process.argv[i] === flag) values.push(process.argv[i + 1]);
}
if (many) return values;
return values[0];
}
const generation = argv('--generation');
const name = argv('--name');
const carry = argv('--carry');
const modules = argv('--module', { many: true });
const parts = argv('--part', { many: true });
if (!generation || !/^\d{12}$/.test(generation)) {
console.error('--generation YYYYMMDDHHMM is required');
process.exit(1);
}
if (!name) {
console.error('--name is required');
process.exit(1);
}
if (!modules.length && !parts.length && !carry) {
console.error('nothing to assemble: pass --carry, --module or --part');
process.exit(1);
}
const sha256 = (text) => createHash('sha256').update(text, 'utf8').digest('hex');
async function readLf(relativePath) {
const absolute = join(REPO, relativePath);
try { await access(absolute, constants.R_OK); }
catch { console.error(`missing part: ${relativePath}`); process.exit(1); }
// Every digest in this estate is over LF bytes: the blob is LF and a
// Windows working copy may not be.
return (await readFile(absolute, 'utf8')).replace(/\r\n/g, '\n');
}
const pieces = [];
const record = [];
if (carry) {
const source = await readLf(carry);
pieces.push(source);
record.push({ role: 'carried_shell_script', path: carry,
bytes: Buffer.byteLength(source), sha256: sha256(source) });
}
for (const modulePath of modules) {
const source = await readLf(modulePath);
pieces.push(source);
record.push({ role: 'module', path: modulePath,
bytes: Buffer.byteLength(source), sha256: sha256(source) });
}
for (const partPath of parts) {
const source = await readLf(partPath);
pieces.push(source);
record.push({ role: 'part', path: partPath,
bytes: Buffer.byteLength(source), sha256: sha256(source) });
}
const header = `/**
* ${name}, generation ${generation} (UTC).
*
* ASSEMBLED by tools/build-cartridge.mjs from the parts below. Do not edit
* this file: edit a part and rebuild under a new generation. Each part is
* hashed in manifests/${generation}-${name}-parts.json.
*
${record.map(r => ` * ${r.role.padEnd(22)} ${r.path}`).join('\n')}
*/
`;
const assembled = header + pieces.join('\n');
const outputPath = join(REPO, 'atlas', 'cartridges', `${generation}-${name}.js`);
const manifest = {
schema: 'gridatlas.cartridge-parts.v1',
generation,
cartridge: `./cartridges/${generation}-${name}.js`,
sha256: sha256(assembled),
bytes: Buffer.byteLength(assembled),
assembled_from: record,
rule: 'edit a part and rebuild under a new generation; this file is not edited by hand'
};
const manifestDir = join(REPO, 'atlas', 'manifests');
const manifestPath = join(manifestDir, `${generation}-${name}-parts.json`);
const manifestText = `${JSON.stringify(manifest, null, 1)}\n`;
const outputTemp = `${outputPath}.tmp-${process.pid}`;
const manifestTemp = `${manifestPath}.tmp-${process.pid}`;
async function exists(path) {
try { await access(path, constants.F_OK); return true; }
catch { return false; }
}
await mkdir(manifestDir, { recursive: true });
for (const [kind, path] of [['cartridge', outputPath], ['manifest', manifestPath]]) {
if (await exists(path)) {
console.error(`refusing to overwrite an existing ${kind}: ${relative(REPO, path).replace(/\\/g, '/')}`);
process.exit(1);
}
}
let createdOutput = false;
let createdManifest = false;
try {
// Stage and verify both members before either final path becomes visible.
await writeFile(outputTemp, assembled, { encoding: 'utf8', flag: 'wx' });
await writeFile(manifestTemp, manifestText, { encoding: 'utf8', flag: 'wx' });
if (sha256(await readFile(outputTemp, 'utf8')) !== manifest.sha256) {
throw new Error('staged cartridge hash does not match its manifest');
}
if ((await readFile(manifestTemp, 'utf8')) !== manifestText) {
throw new Error('staged manifest bytes changed before publication');
}
// Exclusive final writes close the race between preflight and publication.
await writeFile(outputPath, assembled, { encoding: 'utf8', flag: 'wx' });
createdOutput = true;
if (process.env.NODE_ENV === 'test'
&& process.env.GRIDATLAS_ASSEMBLER_FAIL_STAGE === 'after-cartridge') {
throw new Error('injected failure after cartridge publication');
}
await writeFile(manifestPath, manifestText, { encoding: 'utf8', flag: 'wx' });
createdManifest = true;
} catch (error) {
// A failed command must never leave one plausible member of a release pair.
if (createdManifest) await rm(manifestPath, { force: true });
if (createdOutput) await rm(outputPath, { force: true });
console.error(`assembly failed: ${error.message}`);
process.exitCode = 1;
} finally {
await rm(outputTemp, { force: true });
await rm(manifestTemp, { force: true });
}
if (process.exitCode) process.exit(process.exitCode);
console.log(JSON.stringify({
status: 'ASSEMBLED',
cartridge: relative(REPO, outputPath).replace(/\\/g, '/'),
bytes: manifest.bytes,
sha256: manifest.sha256.slice(0, 16),
parts: record.length
}, null, 2));Audit
A JavaScript module in the cartridges folder of GridAtlas that reads shift log.
ingestgridatlas / tools/cartridges/audit.mjs · lines 1–110 of 110 · Entry point · pattern classify (shared by 27 files)
- What it does
- It loads shift log. Defines walk, classify, mb. Uses libraries node:fs, node:path, node:url. Side effects: 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.
- Inputs & outputs
- In: JSON file shift-log.json; JSON file current.json; command-line arguments.
- Downstream impact
- It is itself an entry point (JavaScript module); no other file was found loading it.
- What it achieves
- Defines `walk` and `classify`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gridatlas · tools/cartridges · JavaScript module
- Uses
- node:fs, node:path, node:url
- Used by
- none found
- Produces
- walk, classify, mb
- Defines here
- walk, classify, mb
- 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/cartridges/audit.mjs:1-110 · blob 750adbcc869eed11a18c1bf9cee49a747c2b89a2 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
// Audit atlas/cartridges: which timestamped copies are live, which are only
// reachable through a published versioned route, and which exist only so a
// past composition can be rolled back to.
//
// WHY THIS EXISTS
//
// Every cut of a cartridge lands as a new timestamped file next to the old one
// (141 files, 44 MB, seventy of them sld-sandbox-v9-8.js at ~17k lines each on
// 2026-09-29). Nothing here deletes anything: atlas/releases/ is immutable,
// tools/rollback.mjs refuses a generation whose cartridges are absent, and the
// routes under atlas/v/<generation>/ are published. This script only tells you
// what each file is for, so a decision to retire one is made with the facts.
//
// Usage:
// node tools/cartridges/audit.mjs human-readable table
// node tools/cartridges/audit.mjs --json machine-readable
// node tools/cartridges/audit.mjs --rollback-only list only the files that
// exist solely for rollback
//
// Classes, most to least protected:
// LIVE named in atlas/current.json (served at the live route)
// VERSIONED named in atlas/v/<generation>/current.json (a published route)
// TOOLING named by a proof, CI script, .gitattributes or a workflow
// ROLLBACK named only by atlas/manifests/*-composition.json (rollback target)
// ORPHAN named by nothing at all outside its own directory
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const CARTRIDGES = path.join(ROOT, 'atlas', 'cartridges');
const args = new Set(process.argv.slice(2));
const SKIP_DIRS = new Set(['.git', 'node_modules', 'cartridges']);
const IGNORE_PREFIXES = ['nightly/', 'reports/', 'governance/', 'docs/', 'scope-of-works/', 'STATE.md', 'tools/overnight/shift-log.json'];
function walk(dir, out) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.isDirectory()) {
if (SKIP_DIRS.has(entry.name) && dir !== ROOT) continue;
if (entry.name === '.git' || entry.name === 'node_modules') continue;
walk(path.join(dir, entry.name), out);
} else if (entry.isFile()) {
out.push(path.join(dir, entry.name));
}
}
return out;
}
function classify(refs) {
const rel = refs.map(r => r.split(path.sep).join('/'));
if (rel.includes('atlas/current.json')) return 'LIVE';
if (rel.some(r => /^atlas\/v\/\d{12}\/current\.json$/.test(r))) return 'VERSIONED';
const tooling = rel.filter(r => !r.startsWith('atlas/manifests/') && !IGNORE_PREFIXES.some(p => r.startsWith(p)));
if (tooling.length) return 'TOOLING';
if (rel.some(r => r.startsWith('atlas/manifests/'))) return 'ROLLBACK';
return 'ORPHAN';
}
const cartridges = fs.readdirSync(CARTRIDGES).filter(name => name.endsWith('.js')).sort();
const files = walk(ROOT, []).filter(file => !file.startsWith(CARTRIDGES + path.sep));
const texts = new Map();
for (const file of files) {
try {
const stat = fs.statSync(file);
if (stat.size > 50 * 1024 * 1024) continue;
texts.set(path.relative(ROOT, file), fs.readFileSync(file, 'latin1'));
} catch {
// unreadable files cannot reference anything we can act on
}
}
const rows = cartridges.map(name => {
const size = fs.statSync(path.join(CARTRIDGES, name)).size;
const refs = [];
for (const [rel, text] of texts) if (text.includes(name)) refs.push(rel);
const family = name.replace(/^\d{12}-/, '').replace(/\.js$/, '');
return { name, family, bytes: size, class: classify(refs), refs: refs.sort() };
});
if (args.has('--json')) {
process.stdout.write(JSON.stringify(rows, null, 1) + '\n');
process.exit(0);
}
const selected = args.has('--rollback-only') ? rows.filter(r => r.class === 'ROLLBACK') : rows;
const mb = bytes => (bytes / 1048576).toFixed(2).padStart(6);
for (const row of selected) {
const first = row.refs.find(r => !r.startsWith('atlas/manifests/')) || row.refs[0] || '-';
console.log(`${row.class.padEnd(10)} ${mb(row.bytes)} MB ${row.name.padEnd(48)} ${first}`);
}
if (!args.has('--rollback-only')) {
const byClass = {};
for (const row of rows) {
byClass[row.class] ??= { count: 0, bytes: 0 };
byClass[row.class].count += 1;
byClass[row.class].bytes += row.bytes;
}
console.log('');
for (const cls of ['LIVE', 'VERSIONED', 'TOOLING', 'ROLLBACK', 'ORPHAN']) {
const item = byClass[cls] || { count: 0, bytes: 0 };
console.log(`${cls.padEnd(10)} ${String(item.count).padStart(4)} files ${mb(item.bytes)} MB`);
}
const total = rows.reduce((sum, r) => sum + r.bytes, 0);
console.log(`${'TOTAL'.padEnd(10)} ${String(rows.length).padStart(4)} files ${mb(total)} MB`);
console.log('\nROLLBACK files exist only so tools/rollback.mjs can restore that generation; removing one makes that generation unrestorable. See atlas/cartridges/README.md.');
}