In this section
- Assembler Proof storage · gridatlas / tools/proofs/modules/202609012010-assembler.proof.mjs lines 1–202
- Grid Scope Proof render · gridatlas / tools/proofs/modules/202609012040-grid-scope.proof.mjs lines 1–194
- Declared Connections Proof render · gridatlas / tools/proofs/modules/202609012130-declared-connections.proof.mjs lines 1–181
Assembler Proof
A JavaScript module in the proofs folder of GridAtlas that uses SHA-256. It is built from the check step (`check`), the run step (`run`) and the sha256 step (`sha256`).
storagegridatlas / tools/proofs/modules/202609012010-assembler.proof.mjs · lines 1–202 of 202 · version 2026-09-01 20:10 · Not reached from any entry point (candidate for review) · pattern cleanup (shared by 5 files)
- What it does
- It loads data. Defines 7 functions or classes, including check, run, sha256, outputFor, manifestFor. Uses libraries node:fs/promises, node:fs, node:crypto, node:child_process, node:path. 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.
- Downstream impact
- Used directly by 1 file: Local CI (gridatlas).
- What it achieves
- Proof for `tools/build-cartridge.mjs`.
- Why it matters
- Run by Local CI.
- Application
- gridatlas · tools/proofs/modules · JavaScript module
- Uses
- node:fs/promises, node:fs, node:crypto, node:child_process, node:path, node:url
- Used by
- run by Local CI (script call)
- Produces
- check, run, sha256, outputFor, manifestFor, existsForProof, cleanup
- Defines here
- check, run, sha256, outputFor, manifestFor, existsForProof, cleanup
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/modules/202609012010-assembler.proof.mjs:1-202 · blob 4d13958a0a5eed6e0596f0aa10bd1fd908668007 · 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
/**
* Proof for tools/build-cartridge.mjs.
*
* Codex, 202609011955: the assembler is untrusted until it has its own
* fail-fast and immutability coverage. Fair — it is the thing that will
* write every future cartridge, and an assembler that silently produces
* something plausible is worse than no assembler.
*
* What this proves, by running it as a subprocess against real files:
* - it refuses a missing part rather than emitting a short cartridge
* - it refuses a malformed or absent generation
* - it refuses to overwrite an existing generation (cartridges are
* immutable here)
* - it refuses to assemble nothing
* - the output contains every part, in the order given, and the parts
* manifest hashes each one and the whole
* - a rebuild from the same inputs is byte-identical
* - CRLF on disk does not change a hash: every digest is over LF
*
* node tools/proofs/modules/202609012010-assembler.proof.mjs
*/
import { readFile, writeFile, rm, mkdir, access, readdir } from 'node:fs/promises';
import { constants } from 'node:fs';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = resolve(HERE, '..', '..', '..');
const BUILDER = join(REPO, 'tools', 'build-cartridge.mjs');
const SCRATCH = join(REPO, 'tools', 'proofs', 'modules', '.assembler-scratch');
let passed = 0;
const failures = [];
function check(label, condition, detail) {
if (condition) { passed += 1; console.log(' [PASS] ' + label); }
else {
failures.push(label + (detail ? ` — ${detail}` : ''));
console.log(' [FAIL] ' + label + (detail ? ` — ${detail}` : ''));
}
}
function run(args, extraEnv = {}) {
const result = spawnSync(process.execPath, [BUILDER, ...args],
{ cwd: REPO, encoding: 'utf8', env: { ...process.env, ...extraEnv } });
return { code: result.status, out: result.stdout || '', err: result.stderr || '' };
}
const sha256 = (text) => createHash('sha256').update(text, 'utf8').digest('hex');
await mkdir(SCRATCH, { recursive: true });
const PART_A = 'tools/proofs/modules/.assembler-scratch/part-a.js';
const PART_B = 'tools/proofs/modules/.assembler-scratch/part-b.js';
await writeFile(join(REPO, PART_A), "/* A */\nconst A = 1;\n", 'utf8');
// Written with CRLF deliberately: the estate hashes LF bytes, and a
// Windows working copy is where that promise gets broken.
await writeFile(join(REPO, PART_B), "/* B */\r\nconst B = 2;\r\n", 'utf8');
const GEN_OK = '209912310101';
const GEN_TWO = '209912310202';
const GEN_MANIFEST = '209912310303';
const GEN_FAIL = '209912310404';
const NAME = 'assembler-proof';
const outputFor = (generation) =>
join(REPO, 'atlas', 'cartridges', `${generation}-${NAME}.js`);
const manifestFor = (generation) =>
join(REPO, 'atlas', 'manifests', `${generation}-${NAME}-parts.json`);
async function existsForProof(path) {
try { await access(path, constants.F_OK); return true; }
catch { return false; }
}
async function cleanup() {
for (const generation of [GEN_OK, GEN_TWO, GEN_MANIFEST, GEN_FAIL]) {
await rm(outputFor(generation), { force: true });
await rm(manifestFor(generation), { force: true });
}
await rm(SCRATCH, { recursive: true, force: true });
}
console.log('\nit refuses rather than guessing\n');
check('a missing generation is refused',
run(['--name', NAME, '--part', PART_A]).code !== 0);
check('a malformed generation is refused',
run(['--generation', 'tomorrow', '--name', NAME, '--part', PART_A]).code !== 0);
check('a missing name is refused',
run(['--generation', GEN_OK, '--part', PART_A]).code !== 0);
check('assembling nothing is refused',
run(['--generation', GEN_OK, '--name', NAME]).code !== 0);
const missing = run(['--generation', GEN_OK, '--name', NAME,
'--part', 'tools/proofs/modules/.assembler-scratch/not-here.js']);
check('a missing part is refused, loudly',
missing.code !== 0 && /missing part/.test(missing.err));
let wroteAnyway = true;
try { await access(outputFor(GEN_OK), constants.F_OK); }
catch { wroteAnyway = false; }
check('and nothing is written when it refuses', wroteAnyway === false);
console.log('\nit assembles exactly what it was given\n');
const first = run(['--generation', GEN_OK, '--name', NAME,
'--carry', PART_A, '--module', PART_B]);
check('a valid assembly succeeds', first.code === 0, first.err.slice(0, 120));
const assembled = await readFile(outputFor(GEN_OK), 'utf8');
check('every part is present', assembled.includes('const A = 1;')
&& assembled.includes('const B = 2;'));
check('parts appear in the order given',
assembled.indexOf('const A = 1;') < assembled.indexOf('const B = 2;'));
check('the header names the parts and their roles',
/carried_shell_script\s+tools\/proofs\/modules\/\.assembler-scratch\/part-a\.js/.test(assembled)
&& /module\s+tools\/proofs\/modules\/\.assembler-scratch\/part-b\.js/.test(assembled));
check('the header tells a reader not to edit the output',
/Do not edit\s*\n?\s*\*?\s*this file/.test(assembled));
const manifest = JSON.parse(await readFile(manifestFor(GEN_OK), 'utf8'));
check('the manifest hashes the whole cartridge correctly',
manifest.sha256 === sha256(assembled), manifest.sha256.slice(0, 12));
check('the manifest hashes each part', manifest.assembled_from.length === 2
&& manifest.assembled_from.every(part => /^[0-9a-f]{64}$/.test(part.sha256)));
check('a carried shell script is recorded as carried, not as a module',
manifest.assembled_from[0].role === 'carried_shell_script'
&& manifest.assembled_from[1].role === 'module');
console.log('\nCRLF on disk does not change a digest\n');
const partBSource = await readFile(join(REPO, PART_B), 'utf8');
check('the part really is CRLF on disk', partBSource.includes('\r\n'));
check('its recorded digest is over LF bytes',
manifest.assembled_from[1].sha256 === sha256(partBSource.replace(/\r\n/g, '\n')));
check('the assembled cartridge carries no CR', !assembled.includes('\r'));
console.log('\nimmutability, and repeatability\n');
const again = run(['--generation', GEN_OK, '--name', NAME,
'--carry', PART_A, '--module', PART_B]);
check('it refuses to overwrite an existing generation',
again.code !== 0 && /refusing to overwrite/.test(again.err));
check('the existing cartridge is untouched by the refusal',
(await readFile(outputFor(GEN_OK), 'utf8')) === assembled);
console.log('\nboth members, or neither\n');
/* Carried from Claude's v9.63 attempt, which Codex's implementation
superseded: the cases below prove nothing is left behind on failure,
and these three prove the successful pair really is a pair - a manifest
that names the cartridge beside it and hashes the bytes on disk. */
check('a successful assembly leaves BOTH the cartridge and its manifest',
assembled.length > 0 && /^[0-9a-f]{64}$/.test(manifest.sha256));
check('the manifest names the cartridge it was written beside',
manifest.cartridge.endsWith(`${GEN_OK}-${NAME}.js`));
check('the manifest digest matches the bytes on disk',
manifest.sha256 === sha256(await readFile(outputFor(GEN_OK), 'utf8')));
const manifestSentinel = 'manifest owned by another invocation\n';
await writeFile(manifestFor(GEN_MANIFEST), manifestSentinel, { encoding: 'utf8', flag: 'wx' });
const manifestCollision = run(['--generation', GEN_MANIFEST, '--name', NAME,
'--carry', PART_A, '--module', PART_B]);
check('a manifest-only collision is refused before publishing a cartridge',
manifestCollision.code !== 0 && /existing manifest/.test(manifestCollision.err));
check('the pre-existing manifest is byte-identical after refusal',
(await readFile(manifestFor(GEN_MANIFEST), 'utf8')) === manifestSentinel);
check('a manifest collision leaves no orphan cartridge',
!(await existsForProof(outputFor(GEN_MANIFEST))));
const injected = run(['--generation', GEN_FAIL, '--name', NAME,
'--carry', PART_A, '--module', PART_B], {
NODE_ENV: 'test', GRIDATLAS_ASSEMBLER_FAIL_STAGE: 'after-cartridge'
});
check('an injected second-stage publication failure is reported',
injected.code !== 0 && /injected failure/.test(injected.err));
check('a failed second-stage publication removes the cartridge',
!(await existsForProof(outputFor(GEN_FAIL))));
check('a failed second-stage publication leaves no manifest',
!(await existsForProof(manifestFor(GEN_FAIL))));
const leftovers = [
...(await readdir(join(REPO, 'atlas', 'cartridges'))),
...(await readdir(join(REPO, 'atlas', 'manifests')))
].filter(file => file.includes(GEN_FAIL) && file.includes('.tmp-'));
check('failed publication removes both staged files', leftovers.length === 0,
leftovers.join(', '));
const second = run(['--generation', GEN_TWO, '--name', NAME,
'--carry', PART_A, '--module', PART_B]);
check('the same inputs under a new generation assemble again', second.code === 0);
const assembledTwo = await readFile(outputFor(GEN_TWO), 'utf8');
check('and differ only by the generation stamp',
assembledTwo.split('\n').filter(line => !line.includes(GEN_TWO)).join('\n')
=== assembled.split('\n').filter(line => !line.includes(GEN_OK)).join('\n'));
await cleanup();
console.log('\nscratch and test artefacts removed');
console.log(`\n${passed}/${passed + failures.length} checks passed`);
if (failures.length) {
console.error('\nFAILURES');
for (const failure of failures) console.error(' ' + failure);
process.exit(1);
}
console.log('the assembler refuses what it cannot verify, records what it used, '
+ 'and will not rewrite a generation that already exists.');Grid Scope Proof
A JavaScript module in the proofs folder of GridAtlas that reads substations, 400kV, 750kV and 110kV, using haversine.
rendergridatlas / tools/proofs/modules/202609012040-grid-scope.proof.mjs · lines 1–194 of 194 · version 2026-09-01 20:40 · Not reached from any entry point (candidate for review)
- What it does
- It loads substations, 400kV, 750kV and 110kV. Defines check, at, list. Uses libraries node:fs/promises, node:url, node:path, node:vm. 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, 400kV, 750kV, 110kV, 132kV, 66kV.
- Inputs & outputs
- Voltage levels named: 750kV, 400kV, 132kV, 110kV, 66kV, 50kV, 33kV, 32kV.
- Downstream impact
- Used directly by 1 file: Local CI (gridatlas).
- What it achieves
- It is built from the check step (`check`) and the list step (`list`). The arithmetic is easy; the discipline is the point. Its code works with 110 kV, 400 kV and 50 kV.
- Why it matters
- Run by Local CI.
- Application
- gridatlas · tools/proofs/modules · JavaScript module
- Uses
- node:fs/promises, node:url, node:path, node:vm
- Used by
- run by Local CI (script call)
- Produces
- check, at, list
- Defines here
- check, at, list
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/modules/202609012040-grid-scope.proof.mjs:1-194 · blob 1a5541229d4d82a8b694b33831ea8a02c37240f9 · 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
/**
* Proof for the grid-scope module.
*
* The arithmetic is easy; the discipline is the point. A scope that
* counts substations near a blank patch of farmland is one careless
* sentence away from reading as "there is capacity here", which is the
* one claim this estate must never make. So the checks below test the
* counting AND test that the refusal travels inside the result.
*
* node tools/proofs/modules/202609012010-grid-scope.proof.mjs
*/
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import vm from 'node:vm';
const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = resolve(HERE, '..', '..', '..');
let passed = 0;
const failures = [];
function check(label, condition, detail) {
if (condition) { passed += 1; console.log(' [PASS] ' + label); }
else {
failures.push(label + (detail ? ` — ${detail}` : ''));
console.log(' [FAIL] ' + label + (detail ? ` — ${detail}` : ''));
}
}
const scopeSource = await readFile(
join(REPO, 'atlas', 'modules', '202609012040-grid-scope.js'), 'utf8');
const box = { window: {}, console, Math, JSON, Number, String, Array, Object,
Map, Set, Boolean, Error, RegExp };
box.window.window = box.window;
box.globalThis = box;
vm.createContext(box);
for (const name of ['202609011950-geodesy.js', '202609012040-grid-scope.js']) {
vm.runInContext(await readFile(join(REPO, 'atlas', 'modules', name), 'utf8'),
box, { filename: name });
}
const modules = box.window.__GRIDATLAS_MODULES__;
const gridScope = modules.gridScope;
console.log('\nit loads, and refuses to load alone\n');
check('the module registers',
gridScope?.schema === 'gridatlas.module.grid-scope.v2');
check('it refuses without geodesy', (() => {
const bare = { window: {}, console, Math, JSON, Number, String, Array, Object,
Map, Set, Boolean, Error, RegExp };
bare.window.window = bare.window;
bare.globalThis = bare;
vm.createContext(bare);
try {
vm.runInContext(
// read again rather than reuse, so this is the real file
scopeSource, bare, { filename: 'alone.js' });
return false;
} catch (error) { return /requires the geodesy module/.test(String(error.message)); }
})());
/* A synthetic network with known geometry: everything is placed by
construction so the expected answer is arithmetic, not observation.
0.01 degrees of latitude is about 1.11 km. */
const HOME = [-0.7, 53.3];
const at = (dLat) => [HOME[0], HOME[1] + dLat];
const SUBSTATIONS = [
{ name: 'Very Near 400', at: at(0.009), kv: [400], operator: 'NGET' }, // ~1.0 km
{ name: 'Near 132', at: at(0.03), kv: [132], operator: 'DNO' }, // ~3.3 km
{ name: '', at: at(0.035), kv: [275], operator: '' }, // ~3.9 km unnamed
{ name: 'Mid 33', at: at(0.08), kv: [33], operator: 'DNO' }, // ~8.9 km
{ name: 'Far 400', at: at(0.2), kv: [400], operator: 'NGET' }, // ~22.2 km
{ name: 'Beyond', at: at(0.4), kv: [400], operator: 'NGET' }, // ~44.5 km
{ name: 'Malformed', at: null, kv: [400] }
];
console.log('\nit counts what is there, in bands\n');
const result = gridScope.scope(HOME, SUBSTATIONS, {});
check('the far substation beyond the outer band is excluded',
result.counted === 5, String(result.counted));
check('a malformed entry is skipped rather than throwing',
result.nearest.every(entry => Array.isArray(entry.at)));
check('bands are cumulative and ordered',
result.bands.map(band => band.within_km).join(',') === '2,5,10,25'
&& result.bands.every((band, index) =>
index === 0 || band.substations >= result.bands[index - 1].substations));
check('the 2 km band holds only the one substation that is inside it',
result.bands[0].substations === 1 && result.bands[0].highest_class_kv === 400);
check('the 5 km band adds the 132 and the unnamed 275',
result.bands[1].substations === 3
&& result.bands[1].by_class_kv['132'] === 1
&& result.bands[1].by_class_kv['275'] === 1);
check('the 25 km band reaches the far 400',
result.bands[3].substations === 5 && result.bands[3].by_class_kv['400'] === 2);
check('nearest is sorted by measured distance',
result.nearest.every((entry, index) =>
index === 0 || entry.km >= result.nearest[index - 1].km));
check('the nearest is the one placed nearest, at about a kilometre',
result.nearest[0].name === 'Very Near 400'
&& Math.abs(result.nearest[0].km - 1.0) < 0.1,
result.nearest[0].km.toFixed(3));
console.log('\nnamed and unnamed are both reported, and kept apart\n');
check('an unnamed node can be the nearest of all',
result.nearest.some(entry => !entry.name));
check('but the named list contains only named sites',
result.nearest_named.every(entry => entry.name));
check('the nearest transmission-class site is identified separately',
result.nearest_transmission?.kv >= 275);
console.log('\nthe voltage floor is honoured\n');
const only400 = gridScope.scope(HOME, SUBSTATIONS, { minimumKv: 400 });
check('a 400 kV floor excludes everything below it',
only400.nearest.every(entry => entry.kv >= 400) && only400.counted === 2,
String(only400.counted));
check('classOf maps a voltage to its class, and refuses below the floor',
gridScope.classOf(400) === 400 && gridScope.classOf(132) === 132
&& gridScope.classOf(11) === null);
console.log('\na voltage is never labelled as a class it is not\n');
/* Codex stop-ship 202609012025, on the committed v1 module: it walked the
class list and returned the first class the value exceeded, so it
labelled 750 kV as 400, 110 kV as 66 and 50 kV as 33. These are its
exact counterexamples. */
check('750 kV is not labelled 400 kV', gridScope.classOf(750) === null);
check('110 kV is not labelled 66 kV', gridScope.classOf(110) === null);
check('50 kV is not labelled 33 kV', gridScope.classOf(50) === null);
check('32 kV, just below a class, is not rounded up',
gridScope.classOf(32) === null);
check('a fraction within tolerance still classifies',
gridScope.classOf(400.4) === 400 && gridScope.classOf(131.6) === 132);
check('the tolerance is a tolerance, not a bucket',
gridScope.classOf(399.6) === 400 && gridScope.classOf(399.4) === null
&& gridScope.classOf(132.4) === 132 && gridScope.classOf(132.6) === null);
check('an infinity classifies as nothing',
gridScope.classOf(Infinity) === null && gridScope.classOf(-Infinity) === null);
check('a voltage that did not parse cannot pass a voltage floor', (() => {
/* Codex, 202609012055: Math.max over NaN is NaN, and NaN < 132 is
false, so an unparseable voltage used to survive the floor and be
censused as a 132 kV+ site. */
const censused = gridScope.scope(HOME, [
{ name: 'Unparseable', at: at(0.01), kv: [NaN] },
{ name: 'Real 400', at: at(0.012), kv: [400] }
], { minimumKv: 132 });
return censused.nearest.length === 1 && censused.nearest[0].name === 'Real 400';
})());
check('nonsense classifies as nothing',
gridScope.classOf(NaN) === null && gridScope.classOf(undefined) === null);
check('an off-class site is counted as unclassified, not folded into a class', (() => {
const odd = gridScope.scope(HOME, [
{ name: 'Odd 110', at: at(0.01), kv: [110] },
{ name: 'Real 400', at: at(0.012), kv: [400] }
], {});
const band = odd.bands[0];
return band.substations === 2 && band.unclassified_voltage === 1
&& band.by_class_kv['400'] === 1 && !band.by_class_kv['66']
&& band.unclassified_kv.includes(110) && band.highest_class_kv === 400;
})());
console.log('\nwhat it refuses to say travels inside the result\n');
check('the result states what it is',
/census of the substations/.test(result.what_this_is));
check('the result states what it is not, in the same object',
/Not a statement about capacity, headroom/.test(result.what_this_is_not)
&& /Distance is not capacity/.test(result.what_this_is_not));
check('it names queue position and consent as the things it cannot see',
/queue position/.test(result.what_this_is_not)
&& /consent/.test(result.what_this_is_not));
check('the method and the radius are carried with the numbers',
/haversine/.test(result.method) && /6378\.137/.test(result.method));
check('no grading language anywhere in the module', (() => {
const code = scopeSource.replace(/\/\*[\s\S]*?\*\//g, ' ')
.split('\n').map(line => line.replace(/(^|[^:])\/\/.*$/, '$1')).join('\n');
return !/\b(available|opportunity|suitable|viable|good|strong|attractive|headroom exists)\b/i
.test(code);
})());
console.log('\nedge cases\n');
check('an empty network scopes to nothing rather than throwing',
gridScope.scope(HOME, [], {}).counted === 0);
check('an empty scope still carries its refusal',
/Not a statement about capacity/.test(gridScope.scope(HOME, [], {}).what_this_is_not));
check('a null network is survivable',
gridScope.scope(HOME, null, {}).counted === 0);
console.log(`\n${passed}/${passed + failures.length} checks passed`);
if (failures.length) {
console.error('\nFAILURES');
for (const failure of failures) console.error(' ' + failure);
process.exit(1);
}
console.log('the scope counts what is mapped, names what it cannot know, and '
+ 'carries both together.');Declared Connections Proof
A JavaScript module in the proofs folder of GridAtlas that reads substations and 400kV.
rendergridatlas / tools/proofs/modules/202609012130-declared-connections.proof.mjs · lines 1–181 of 181 · version 2026-09-01 21:30 · Not reached from any entry point (candidate for review) · pattern plain (shared by 5 files)
- What it does
- It loads substations and 400kV. Defines 6 functions or classes, including plain, same, check, fresh, inlineObject. Uses libraries node:fs/promises, node:path, node:url, node:vm, node:util. 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, 400kV, 132kV.
- Inputs & outputs
- Voltage levels named: 400kV, 132kV.
- Downstream impact
- Used directly by 1 file: Local CI (gridatlas).
- What it achieves
- It is built from the plain step (`plain`), the same step (`same`) and the check step (`check`). The module was cut out of the single-line diagram (SLD)-sandbox body, so the question that matters most is PARITY: does the module hold exactly the records the served cartridge held. Its code works with 400 kV and 132 kV.
- Why it matters
- Run by Local CI.
- Application
- gridatlas · tools/proofs/modules · JavaScript module
- Uses
- node:fs/promises, node:path, node:url, node:vm, node:util
- Used by
- run by Local CI (script call)
- Produces
- plain, same, check, fresh, inlineObject, servedFunctions
- Defines here
- plain, same, check, fresh, inlineObject, servedFunctions
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/modules/202609012130-declared-connections.proof.mjs:1-181 · blob 5085035e0063d19f6fe8275897f1215bd811cfeb · 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
/**
* Proof for the declared-connections module.
*
* The module was cut out of the sld-sandbox body, so the question that
* matters most is PARITY: does the module hold exactly the records the
* served cartridge held, and do its three functions answer exactly as the
* served functions answered, on the same inputs? Both halves are read from
* the last cartridge that carried the table inline (v9.67, 202609012250),
* evaluated, and compared value for value. A transcription slip in a DCO
* citation would fail here, not on a card.
*
* node tools/proofs/modules/202609012130-declared-connections.proof.mjs
*/
import { readFile } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import vm from 'node:vm';
import { isDeepStrictEqual } from 'node:util';
/* Values from two vm realms have two Object.prototypes, and a strict deep
comparison would call every record different for that reason alone. A
JSON round-trip strips the realm and keeps key order, which is exactly
the comparison wanted: same keys, same order, same values. */
const plain = (value) => JSON.parse(JSON.stringify(value === undefined ? null : value));
const same = (a, b) => isDeepStrictEqual(plain(a), plain(b));
const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = resolve(HERE, '..', '..', '..');
const MODULE = join(REPO, 'atlas', 'modules', '202609012128-declared-connections.js');
const GEODESY = join(REPO, 'atlas', 'modules', '202609011950-geodesy.js');
const BODY = join(REPO, 'atlas', 'parts', '202609012045-sld-sandbox-body.js');
/* The last served bytes that carried the table inline. Pinned on purpose:
this is the record the module must reproduce, and it does not move. */
const LAST_INLINE = join(REPO, 'atlas', 'cartridges', '202609012250-sld-sandbox-v9-8.js');
let passed = 0;
const failures = [];
function check(label, condition, detail) {
if (condition) { passed += 1; console.log(' [PASS] ' + label); }
else {
failures.push(label + (detail ? ` — ${detail}` : ''));
console.log(' [FAIL] ' + label + (detail ? ` — ${detail}` : ''));
}
}
function fresh() {
const box = { window: {}, console, Math, JSON, Number, String, Array, Object,
Map, Set, Boolean, Error, RegExp };
box.window.window = box.window;
vm.createContext(box);
return box;
}
const moduleSource = await readFile(MODULE, 'utf8');
const geodesySource = await readFile(GEODESY, 'utf8');
const body = await readFile(BODY, 'utf8');
const shipped = await readFile(LAST_INLINE, 'utf8');
console.log('\nit loads, and only after geodesy\n');
check('without geodesy it refuses to load, by name', (() => {
try { vm.runInContext(moduleSource, fresh()); return false; }
catch (error) { return /requires the geodesy module/.test(error.message); }
})());
const box = fresh();
vm.runInContext(geodesySource, box);
vm.runInContext(moduleSource, box);
const mod = box.window.__GRIDATLAS_MODULES__.declaredConnections;
check('with geodesy it registers a frozen surface',
!!mod && Object.isFrozen(mod) && Object.isFrozen(mod.records));
check('loading it twice is a no-op, not a second table', (() => {
vm.runInContext(moduleSource, box);
return box.window.__GRIDATLAS_MODULES__.declaredConnections === mod;
})());
/* ── the record, value for value ─────────────────────────────────────── */
function inlineObject(text, name) {
const start = text.indexOf(`const ${name} = Object.freeze({`);
if (start < 0) throw new Error(`${name} not found in the served cartridge`);
const end = text.indexOf('\n });\n', start);
const literal = text.slice(start + `const ${name} = Object.freeze(`.length, end + '\n }'.length);
return vm.runInNewContext(`(${literal})`, { Object });
}
const servedRecords = inlineObject(shipped, 'DECLARED_CONNECTIONS');
const servedWorks = inlineObject(shipped, 'SUBSTATION_WORKS');
console.log('\nparity with the last cartridge that carried the table inline\n');
check(`the served table had ${Object.keys(servedRecords).length} records and the module has the same count`,
Object.keys(servedRecords).length === mod.count && mod.count === 19);
check('every record is identical, key for key and value for value',
same(servedRecords, mod.records),
Object.keys(servedRecords).filter(k => !same(servedRecords[k], mod.records[k])).join(', '));
check('the substation-works sentences are identical',
same(servedWorks, mod.substationWorks));
/* ── the behaviour, answer for answer ────────────────────────────────── */
/* Evaluate the SERVED functions with their own table, and the module's
geodesy for distance, so the only thing under comparison is the code
that moved. */
function servedFunctions() {
const from = shipped.indexOf(' function provisionalDeclaredConnection(repdRef) {');
const to = shipped.indexOf(' function declaredBlockHtml(toSubstations) {');
const code = shipped.slice(from, to);
const ctx = { DECLARED_CONNECTIONS: servedRecords, SUBSTATION_WORKS: servedWorks,
distanceKm: box.window.__GRIDATLAS_MODULES__.geodesy.distanceKm, Math, String, Array, Object };
vm.createContext(ctx);
vm.runInContext(code + '\nthis.__fns = { provisionalDeclaredConnection, resolveDeclaredConnection, nearestTransmission };', ctx);
return ctx.__fns;
}
const served = servedFunctions();
const ORIGIN = [-0.7500, 53.3200];
const SUBS = [
{ name: 'Cottam Substation', kv: [400, 132], at: [-0.7815, 53.3045] },
{ name: 'Cottam Substation', kv: [132], at: [-0.7900, 53.3000] }, // same name, wrong class
{ name: 'West Burton Substation', kv: [400], at: [-0.8090, 53.3620] },
{ name: 'High Marnham Substation', kv: [400], at: [-0.7860, 53.2320] },
{ name: 'Bicker Fen Substation', kv: [400], at: [-0.2560, 52.9230] },
{ name: 'Thorpe Marsh Substation', kv: [400], at: [-1.0810, 53.5760] },
{ name: '', kv: [400], at: [-0.7520, 53.3190] }, // unnamed, nearest
{ name: 'Sturton Le Steeple', kv: [33], at: [-0.8300, 53.3300] }
];
const refs = [...Object.keys(servedRecords), '0', '', null, undefined, 'not-a-ref'];
console.log('\nthe module answers exactly as the served code answered\n');
check('provisional(): identical for every declared ref and for unknown refs',
refs.every(r => same(mod.provisional(r), served.provisionalDeclaredConnection(r))),
refs.filter(r => !same(mod.provisional(r), served.provisionalDeclaredConnection(r))).join(', '));
check('resolve(): identical with a full payload',
refs.every(r => same(mod.resolve(r, ORIGIN, SUBS), served.resolveDeclaredConnection(r, ORIGIN, SUBS))));
check('resolve(): identical with an empty payload (every substation unmatched)',
refs.every(r => same(mod.resolve(r, ORIGIN, []), served.resolveDeclaredConnection(r, ORIGIN, []))));
check('nearestTransmission(): identical, including the unnamed-wins-on-distance case',
same(mod.nearestTransmission(ORIGIN, SUBS), served.nearestTransmission(ORIGIN, SUBS))
&& mod.nearestTransmission(ORIGIN, SUBS).name === 'Unnamed substation'
&& mod.nearestTransmission(ORIGIN, SUBS).named.name === 'Cottam Substation');
check('nearestTransmission(): null on a payload with nothing at 400 kV',
mod.nearestTransmission(ORIGIN, SUBS.filter(s => s.kv[0] < 400)) === null
&& served.nearestTransmission(ORIGIN, SUBS.filter(s => s.kv[0] < 400)) === null);
console.log('\nwhat the record says about itself\n');
const records = Object.values(mod.records);
check('every record cites a public source', records.every(r => typeof r.source === 'string' && r.source.length > 10));
check('every record names a substation or a circuit, never neither',
records.every(r => (r.poc_kind === 'circuit' ? !!r.circuit : !!r.substation)));
check('poc_status is one of the three states or absent',
records.every(r => r.poc_status === undefined || ['existing', 'not_built', 'under_construction'].includes(r.poc_status)));
check('a far end that is not built carries a note saying so',
records.filter(r => r.poc_status === 'not_built' || r.poc_status === 'under_construction')
.every(r => typeof r.poc_status_note === 'string'));
check('a declared 400 kV substation match ignores a 132 kV site of the same name', (() => {
const only132 = SUBS.filter(s => s.name === 'Cottam Substation' && s.kv[0] === 132);
return mod.resolve('10914', ORIGIN, only132).at === null;
})());
check('isDeclared() is true for every record and false otherwise',
Object.keys(mod.records).every(k => mod.isDeclared(k)) && !mod.isDeclared('0') && !mod.isDeclared(undefined));
console.log('\nthe body no longer carries the table\n');
check('the body declares no DECLARED_CONNECTIONS or SUBSTATION_WORKS of its own',
!/const DECLARED_CONNECTIONS\b/.test(body) && !/const SUBSTATION_WORKS\b/.test(body));
check('the body throws by name when the module is absent',
/throw new Error\('sld-sandbox requires the declared-connections module'\)/.test(body));
check('the body delegates all three functions',
/return DECLARED\.provisional\(/.test(body) && /return DECLARED\.resolve\(/.test(body)
&& /return DECLARED\.nearestTransmission\(/.test(body));
console.log('\nit reads and nothing else\n');
check('it never fetches', !/\bfetch\s*\(/.test(moduleSource));
check('it never renders', !/document\.|innerHTML|appendChild/.test(moduleSource));
check('it never grades a connection',
!/\b(likely|unlikely|feasible|viable|adequate|sufficient|strong|weak)\b/i.test(moduleSource.replace(/\/\*[\s\S]*?\*\//g, '')));
console.log(`\n${passed}/${passed + failures.length} checks passed`);
if (failures.length) {
console.error('\nFAILURES');
for (const failure of failures) console.error(' ' + failure);
process.exit(1);
}
console.log('the public record moved without changing a single value, and the body binds to it or does not load.');