In this section
- Advance interaction · gridatlas / tools/scope/advance.mjs lines 424–432
- Bootstrap storage · gridatlas / tools/scope/bootstrap.mjs lines 1–75
- GridAtlas — Scope storage · gridatlas / tools/scope/lib.mjs lines 1–308
- Loop render · gridatlas / tools/scope/loop.mjs lines 1–307
Advance
A JavaScript module in the scope folder of GridAtlas that fetches grid 400kV and CVAA ratchets, using SHA-256 from postcodes.io.
interactiongridatlas / tools/scope/advance.mjs · lines 424–432 of 432 (continued from section 688) · Entry point · pattern replaceExactlyOnce (shared by 3 files)
- What it does
- It fetches grid 400kV and CVAA ratchets. Defines 18 functions or classes, including moveDirectory, removePath, runNodeCheck, finishScope, finishFinal. Uses libraries node:fs, node:path, node:child_process. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: data source: postcodes.io; JSON file current-v5.json; JSON file live-set.json; JSON file current.json; GeoJSON file grid_400kv.geojson; JSON file modules.json; JSON file cvaa-ratchets.json; DuckDB queries.
- Downstream impact
- Used directly by 1 file: GridAtlas Scope Loop Workflow (gridatlas).
- What it achieves
- It removes path (`removePath`), runs node check (`runNodeCheck`) and replaces exactly once (`replaceExactlyOnce`). Defines `moveDirectory`, `removePath`, `runNodeCheck` and 15 more. It reads `./current.json`.
- Why it matters
- Run by GridAtlas Scope Loop Workflow.
- Application
- gridatlas · tools/scope · JavaScript module
- Uses
- GridAtlas — Scope (script call), Verify Compose (script call), Loop (script call), GridAtlas — Atlas Page (estate URL), node:fs, node:path, node:child_process
- Used by
- run by GridAtlas Scope Loop Workflow (workflow run)
- Produces
- moveDirectory, removePath, runNodeCheck, finishScope, finishFinal, temporaryAtlasRouter, rootRouter, rewriteLivePointers, scope1, scope2, scope3, replaceExactlyOnce
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/scope/advance.mjs:424-432 · blob 60f6981de167c45f5576217c6790d6ea9ddcd057 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
successor_scope_file: result.nextName,
successor_generation: result.generation,
commit_message: commitMessage
});
console.log(JSON.stringify({ completed: document.name, successor: result.nextName || null, generation: result.generation }));
} catch (error) {
console.error(`[scope-advance] ${error?.stack || error}`);
process.exitCode = 1;
}Bootstrap
A JavaScript module in the scope folder of GridAtlas that reads scope bootstrap, using SHA-256. It writes output (`writeOutput`).
storagegridatlas / tools/scope/bootstrap.mjs · lines 1–75 of 75 · Entry point
- What it does
- It loads scope bootstrap. Defines writeOutput, sha256. Uses libraries node:fs, node:path, node:zlib, node:crypto. 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 scope-bootstrap.json.
- Downstream impact
- Used directly by 1 file: GridAtlas Scope Loop Workflow (gridatlas).
- What it achieves
- Defines `writeOutput` and `sha256`.
- Why it matters
- Run by GridAtlas Scope Loop Workflow.
- Application
- gridatlas · tools/scope · JavaScript module
- Uses
- node:fs, node:path, node:zlib, node:crypto
- Used by
- run by GridAtlas Scope Loop Workflow (workflow run)
- Produces
- writeOutput, sha256
- Defines here
- writeOutput, sha256
- 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/scope/bootstrap.mjs:1-75 · blob f66a23f0b47b0af4ba3e32f372f4a1224c4c0407 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
import crypto from 'node:crypto';
const ROOT = process.cwd();
const MARKER = path.join(ROOT, 'state', 'scope-bootstrap.json');
const PARTS_DIR = path.join(ROOT, 'tools', 'scope', 'bootstrap-payload');
const PAYLOAD_SHA256 = '36bebe95281d401eff590ffaacd6dfc89171a3eca6d5096c8845c470214f9102';
function writeOutput(values) {
if (!process.env.GITHUB_OUTPUT) return;
fs.appendFileSync(
process.env.GITHUB_OUTPUT,
Object.entries(values).map(([key, value]) => `${key}=${value}`).join('\n') + '\n'
);
}
function sha256(bytes) {
return crypto.createHash('sha256').update(bytes).digest('hex');
}
try {
if (fs.existsSync(MARKER)) {
const marker = JSON.parse(fs.readFileSync(MARKER, 'utf8'));
if (marker.payload_sha256 !== PAYLOAD_SHA256) {
throw new Error('scope bootstrap marker payload mismatch');
}
writeOutput({ bootstrapped: false, payload_sha256: PAYLOAD_SHA256 });
console.log('scope-bootstrap=ALREADY_MATERIALISED');
process.exit(0);
}
const parts = fs.readdirSync(PARTS_DIR)
.filter(name => /^\d{2}\.part$/.test(name))
.sort();
if (parts.length !== 5) throw new Error(`scope bootstrap part closure mismatch: ${parts.length}`);
const encoded = parts
.map(name => fs.readFileSync(path.join(PARTS_DIR, name), 'utf8').trim())
.join('');
const raw = zlib.gunzipSync(Buffer.from(encoded, 'base64'));
if (sha256(raw) !== PAYLOAD_SHA256) throw new Error('scope bootstrap payload SHA-256 mismatch');
const payload = JSON.parse(raw.toString('utf8'));
if (payload.schema !== 'gridatlas.scope-bootstrap-payload.v1' || payload.generation !== '202608301321') {
throw new Error('scope bootstrap payload contract mismatch');
}
const entries = Object.entries(payload.files);
for (const [relative, content] of entries) {
if (relative.startsWith('/') || relative.split('/').includes('..')) {
throw new Error(`unsafe bootstrap path ${relative}`);
}
const target = path.join(ROOT, ...relative.split('/'));
if (fs.existsSync(target) && fs.readFileSync(target, 'utf8') !== content) {
throw new Error(`bootstrap refuses to overwrite ${relative}`);
}
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, content, 'utf8');
}
fs.mkdirSync(path.dirname(MARKER), { recursive: true });
fs.writeFileSync(MARKER, JSON.stringify({
schema: 'gridatlas.scope-bootstrap.v1',
generation: '202608301321',
payload_sha256: PAYLOAD_SHA256,
files: entries.length,
status: 'MATERIALISED'
}, null, 2) + '\n', 'utf8');
writeOutput({ bootstrapped: true, payload_sha256: PAYLOAD_SHA256, files: entries.length });
console.log(`scope-bootstrap=MATERIALISED files=${entries.length} sha256=${PAYLOAD_SHA256}`);
} catch (error) {
console.error(`[scope-bootstrap] ${error?.stack || error}`);
process.exitCode = 1;
}GridAtlas — Scope
A JavaScript module in the tools folder that normalises newlines (`normaliseNewlines`) and parses scalar (`parseScalar`) and front matter (`parseFrontMatterText`), using SHA-256.
storagegridatlas / tools/scope/lib.mjs · lines 1–308 of 308 · pattern londonGeneration (shared by 2 files)
- What it does
- It loads data. Defines 28 functions or classes, including registeredLoader, slotsUsed, invariant, normaliseNewlines, parseScalar. Uses libraries node:fs, node:path, node:crypto. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Downstream impact
- Used directly by 11 files: CI PR Gate (gridatlas); Lightning Cartridge (gridatlas); Loader Equivalence Proof (gridatlas); Offtakers Cartridge (gridatlas); and 7 more. Reached from 28 other entry points, including GridAtlas Cartridge Proof Workflow (gridatlas); GridAtlas Next Version Builders Workflow (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- It normalises newlines (`normaliseNewlines`), parses scalar (`parseScalar`) and serialises scalar (`serialiseScalar`). Defines `registeredLoader`, `slotsUsed`, `invariant` and 25 more.
- Why it matters
- Imported by 7 files, including Lightning Cartridge, Loader Equivalence Proof and Offtakers Cartridge. Run by CI PR Gate, GridAtlas — Release and Advance. Checked by Loader Swap Test.
- Application
- gridatlas · tools/scope · JavaScript module
- Uses
- node:fs, node:path, node:crypto
- Used by
- run by CI PR Gate (script call), imported by Lightning Cartridge (dynamic import), imported by Loader Equivalence Proof (dynamic import), imported by Offtakers Cartridge (dynamic import), run by GridAtlas — Release (script call), imported by Loader Swap (import), run by Loader Swap Test (script call), run by Advance (script call), and 3 more
- Produces
- ROOT, SCOPE_DIR, MASTER_NAME, CURRENT_RELEASE, SHARED_400KV_CARTRIDGE, EXPECTED_RELEASES, ACTIVE_WORKFLOWS, ATLAS_LOADERS, registeredLoader, slotsUsed, CARTRIDGE_BYTE_BUDGETS, invariant
- Defines here
- registeredLoader, slotsUsed, invariant, normaliseNewlines, parseScalar, serialiseScalar, parseFrontMatterText, readFrontMatter, writeFrontMatter, writeText, writeJson, readJson, listScopeDocuments, masterDocument, numberedScopes, activeScope, sha256Buffer, sha256File, sha256PublishedFile, londonGeneration, pick, addMinute, pad, nextGeneration, scopeFileName, scopeMarkdown, githubOutput, relativePosix
- 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/scope/lib.mjs:1-308 · blob 2bcd4c5fead19d99b1c0bc9e5aec2c31021305cc · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
export const ROOT = process.cwd();
export const SCOPE_DIR = path.join(ROOT, 'scope-of-works');
export const MASTER_NAME = '202608301321-scope-of-works.md';
export const CURRENT_RELEASE = '202608300453-atlas-v9';
export const SHARED_400KV_CARTRIDGE = '5f5fbec83f9ce307b47ddc6e7277743f0bba1a2445b0f3ca50a9a1806146e993';
export const EXPECTED_RELEASES = Object.freeze([
'202608291237-atlas-v9',
'202608291239-atlas-v9',
'202608291430-atlas-v9',
'202608291758-atlas-v9',
'202608291818-atlas-v9',
'202608292126-atlas-v9',
'202608292311-atlas-v9',
'202608300453-atlas-v9'
]);
// The budget exists because this repository once accumulated one-off
// workflows faster than it retired them -- 21 sit in the archive. It is a cap
// on sprawl, not a ban on automation, so adding to it is a decision that gets
// written down rather than a number that gets nudged.
//
// 202608312212-cartridge-proof.yml earns its place: the scope loop is retired
// and fires only on workflow_dispatch, and verify-live triggers on a path list
// that excludes atlas/, so a cartridge could be composed, hashed, pushed and
// served with nobody having run its proof. It is node-only and takes seconds,
// so there is never a reason to skip it.
//
// rollback-composition.yml earns its place because every other entry on this
// list can only move the live pointer FORWARD. Ten generations were cut in
// three hours on 2026-09-03, each one repointing the live route, and undoing
// any of them meant hand-editing atlas/current.json at whatever hour it was
// noticed -- the hand-editing habit tools/recompose.mjs exists to end. v9.83
// pinned the runtime products so a bad product cannot reach a shipped
// release; this is the other half, so a bad release cannot stay on the
// pointer. It is the only entry with no 12-digit prefix, and deliberately: it
// belongs to no release, it is a perpetual single-purpose path like the scope
// loop, and stamping it for one night would make a permanent mechanism look
// like the per-release sprawl this budget exists to cap.
export const ACTIVE_WORKFLOWS = Object.freeze([
'202608301321-scope-loop.yml',
'202608301321-verify-live.yml',
'202608310015-gridatlas-overnight-next-versions.yml',
'202608310050-gridatlas-next-version-builders.yml',
'202608312212-cartridge-proof.yml',
/* Added by 98dd908 as the annual offshore coordinate reconciliation, and left
unregistered exactly as the parse gate below was, so the budget invariant
kept failing and STATE.md still could not be regenerated. Intended
workflow, missing registration. */
'offshore-coordinate-reconcile.yml',
'rollback-composition.yml',
/* Added 2026-09-05 by 78e49b0 when the parse gate left the laptop, but never
registered here, so the budget invariant has failed on every run since -
which also meant STATE.md could not be regenerated and the AGENTS.md rule
requiring it alongside a current.json change became unsatisfiable. The
workflow is intended; the list had simply not been told about it. */
'teleprint-parse-gate.yml',
/* Added 2026-09-29. Fails a pull request that adds a file over 5 MB unless
the path is in .github/large-files-allowlist.txt. Runs on pull_request
only, so nothing that pushes to main is affected. Perpetual, so it carries
no 12-digit prefix, like rollback-composition.yml.
28 Oct 2026: it also carries the cartridge-gate job (tools/ci/pr-gate.mjs,
docs/CI.md). Extended rather than added because it is the only entry here
still enabled in the repository settings, so the budget stays at nine. */
'pr-file-size-guard.yml'
]);
/* The registered composers (docs/LIGHTNING-CARTRIDGE.md). A served loader --
atlas/index.html or any atlas/v/<gen>/index.html -- must be byte-identical
to exactly one of these payloads, and must support every slot type its
current.json uses.
v1 the composer every generation up to 202610290050 is served by; the
live atlas/index.html. It knows only 'replace-script'.
v2 v1 plus 'after-cartridge': a verified cartridge as its own script tag
straight after a cartridge composed before it. For every composition
that uses only 'replace-script' it writes byte-for-byte what v1 writes
(tools/proofs/loader-equivalence.proof.mjs).
Existing loaders are never rewritten: a generation keeps the loader bytes it
was cut with, and the live atlas/index.html changes either in the release
commit of a generation whose own loader differs (LOADER_FOLLOWS), or alone,
to a registered loader proven to compose the unchanged live pointer byte for
byte as the old one does (tools/release/loader-swap.mjs; docs/RELEASE.md). */
export const ATLAS_LOADERS = Object.freeze({
v1: Object.freeze({ payload: 'tools/scope/payloads/atlas-loader.html', slots: Object.freeze(['replace-script']) }),
v2: Object.freeze({ payload: 'tools/scope/payloads/atlas-loader-v2.html', slots: Object.freeze(['replace-script', 'after-cartridge']) })
});
/** The registered loader whose payload is byte-identical (served LF bytes)
to the file at filePath, as { name, payload, slots }, or null. */
export function registeredLoader(filePath) {
const digest = sha256PublishedFile(filePath);
for (const [name, loader] of Object.entries(ATLAS_LOADERS)) {
if (sha256PublishedFile(path.join(ROOT, loader.payload)) === digest) return { name, ...loader };
}
return null;
}
/** The slot types the ordered cartridges of a current.json use. */
export function slotsUsed(current) {
const byId = new Map((current.cartridges || []).map(c => [c.id, c]));
return [...new Set((current.cartridge_order || []).map(id => byId.get(id)?.slot))].filter(Boolean).sort();
}
/* Per-cartridge byte budgets, checked by `loop.mjs lint` IN ADDITION to the
single recorded ceiling there (the one --prep-gate-kb edits). The lightning
overlay is its own cartridge from the modular generations on, so it gets
the room the owner gave it inside sld-sandbox, and no more:
500,000 (ceiling, 28 Oct 2026) - 435,218 (sld-sandbox 202609241334) - 1
(the joining newline) = 64,781 bytes, the module budget every
<gen>-sld-sandbox proof already enforces. Changing a figure is an owner
decision, recorded in the commit. */
export const CARTRIDGE_BYTE_BUDGETS = Object.freeze({
'uk-lightning-overlay': 64_781,
// Owner approval, 29 Oct 2026, issue #73: raise the potential-offtakers
// module budget to 80,000 B for the data-centre 30/30/30 engine.
'uk-offtakers-overlay': 80_000
});
export function invariant(condition, message) {
if (!condition) throw new Error(message);
}
export function normaliseNewlines(value) {
return String(value).replace(/\r\n/g, '\n');
}
function parseScalar(raw) {
const value = raw.trim();
if (value === 'null' || value === '~') return null;
if (value === 'true') return true;
if (value === 'false') return false;
if (/^-?\d+$/.test(value)) return Number(value);
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
if (value.startsWith('"')) return JSON.parse(value);
return value.slice(1, -1).replaceAll("''", "'");
}
return value;
}
function serialiseScalar(value) {
if (value === null || value === undefined) return 'null';
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
return JSON.stringify(String(value));
}
export function parseFrontMatterText(text, file = '<memory>') {
const source = normaliseNewlines(text);
const match = source.match(/^---\n([\s\S]*?)\n---\n?/);
invariant(match, `${file}: missing YAML front matter`);
const data = {};
const order = [];
for (const line of match[1].split('\n')) {
if (!line.trim() || line.trimStart().startsWith('#')) continue;
const index = line.indexOf(':');
invariant(index > 0, `${file}: malformed front-matter line ${JSON.stringify(line)}`);
const key = line.slice(0, index).trim();
invariant(/^[a-z][a-z0-9_]*$/i.test(key), `${file}: invalid front-matter key ${key}`);
invariant(!(key in data), `${file}: duplicate front-matter key ${key}`);
data[key] = parseScalar(line.slice(index + 1));
order.push(key);
}
return { data, body: source.slice(match[0].length), order };
}
export function readFrontMatter(filePath) {
const text = fs.readFileSync(filePath, 'utf8');
return { ...parseFrontMatterText(text, path.relative(ROOT, filePath)), text };
}
export function writeFrontMatter(filePath, patch) {
const current = readFrontMatter(filePath);
const data = { ...current.data, ...patch };
const preferred = ['schema', 'generation', 'status', 'scope', 'active_scope', 'parent', 'next', 'closure_generation'];
const keys = [...preferred.filter(key => key in data), ...current.order.filter(key => !preferred.includes(key) && key in data)];
for (const key of Object.keys(data)) if (!keys.includes(key)) keys.push(key);
const header = keys.map(key => `${key}: ${serialiseScalar(data[key])}`).join('\n');
writeText(filePath, `---\n${header}\n---\n${current.body.replace(/^\n+/, '')}`);
}
export function writeText(filePath, content) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
const next = normaliseNewlines(content).replace(/\s*$/, '\n');
if (fs.existsSync(filePath) && normaliseNewlines(fs.readFileSync(filePath, 'utf8')) === next) return false;
fs.writeFileSync(filePath, next, 'utf8');
return true;
}
export function writeJson(filePath, value) {
return writeText(filePath, `${JSON.stringify(value, null, 2)}\n`);
}
export function readJson(filePath) {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
}
export function listScopeDocuments() {
invariant(fs.existsSync(SCOPE_DIR), 'scope-of-works/ is missing');
const files = fs.readdirSync(SCOPE_DIR)
.filter(name => /^\d{12}-(?:\d{2}-[a-z0-9-]+|scope-of-works)\.md$/.test(name))
.sort();
return files.map(name => {
const filePath = path.join(SCOPE_DIR, name);
const parsed = readFrontMatter(filePath);
return { name, filePath, ...parsed };
});
}
export function masterDocument(documents = listScopeDocuments()) {
const master = documents.find(item => item.name === MASTER_NAME);
invariant(master, `${MASTER_NAME} is missing`);
return master;
}
export function numberedScopes(documents = listScopeDocuments()) {
return documents.filter(item => Number(item.data.scope) > 0).sort((a, b) => Number(a.data.scope) - Number(b.data.scope));
}
export function activeScope(documents = listScopeDocuments()) {
const active = numberedScopes(documents).filter(item => item.data.status === 'active');
invariant(active.length <= 1, `expected at most one active numbered scope, found ${active.map(item => item.name).join(', ')}`);
return active[0] || null;
}
export function sha256Buffer(bytes) {
return crypto.createHash('sha256').update(bytes).digest('hex');
}
export function sha256File(filePath) {
return sha256Buffer(fs.readFileSync(filePath));
}
// Text assets in this repository are hashed as they are PUBLISHED, which is LF:
// the sums were generated from git blob content and GitHub Pages serves those
// same bytes. A Windows checkout with core.autocrlf=true writes CRLF into the
// working copy, so hashing the file on disk disagrees with every published
// digest and the release verifier fails on a tree nobody has touched.
//
// This is the same defect that made pipelinenews .sha256 sidecars attest bytes
// that were never served. Normalising here makes the check answer the question
// that matters -- do the bytes we publish match what we said we published --
// instead of a question about the reader's line-ending settings.
const LF_NORMALISED_EXTENSIONS = new Set([
'.js', '.mjs', '.cjs', '.css', '.html', '.htm', '.json', '.geojson',
'.txt', '.md', '.yml', '.yaml', '.svg'
]);
export function sha256PublishedFile(filePath) {
const bytes = fs.readFileSync(filePath);
if (!LF_NORMALISED_EXTENSIONS.has(path.extname(filePath).toLowerCase())) {
return sha256Buffer(bytes);
}
const normalised = Buffer.from(
bytes.toString('binary').replace(/\r\n/g, '\n'), 'binary');
return sha256Buffer(normalised);
}
export function londonGeneration(date = new Date()) {
const parts = new Intl.DateTimeFormat('en-GB', {
timeZone: 'Europe/London',
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', hourCycle: 'h23'
}).formatToParts(date);
const pick = type => parts.find(part => part.type === type)?.value;
return `${pick('year')}${pick('month')}${pick('day')}${pick('hour')}${pick('minute')}`;
}
function addMinute(generation) {
invariant(/^\d{12}$/.test(generation), `invalid generation ${generation}`);
const date = new Date(Date.UTC(
Number(generation.slice(0, 4)),
Number(generation.slice(4, 6)) - 1,
Number(generation.slice(6, 8)),
Number(generation.slice(8, 10)),
Number(generation.slice(10, 12))
));
date.setUTCMinutes(date.getUTCMinutes() + 1);
const pad = value => String(value).padStart(2, '0');
return `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}`;
}
export function nextGeneration(previous) {
const now = londonGeneration();
return Number(now) > Number(previous) ? now : addMinute(previous);
}
export function scopeFileName(generation, scope, slug) {
invariant(/^\d{12}$/.test(generation), `invalid scope generation ${generation}`);
invariant(Number.isInteger(scope) && scope > 0 && scope < 100, `invalid scope number ${scope}`);
invariant(/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug), `invalid scope slug ${slug}`);
return `${generation}-${String(scope).padStart(2, '0')}-${slug}.md`;
}
export function scopeMarkdown({ generation, scope, parent, title, body }) {
return `---\nschema: "gridatlas.scope-of-works.v1"\ngeneration: "${generation}"\nstatus: "active"\nscope: ${scope}\nparent: "${parent}"\nnext: null\n---\n# ${title}\n\n${body.trim()}\n`;
}
export function githubOutput(values) {
const file = process.env.GITHUB_OUTPUT;
if (!file) return;
const lines = Object.entries(values).map(([key, value]) => `${key}=${String(value).replaceAll('\n', '%0A')}`);
fs.appendFileSync(file, `${lines.join('\n')}\n`, 'utf8');
}
export function relativePosix(filePath) {
return path.relative(ROOT, filePath).split(path.sep).join('/');
}Loop
A JavaScript module in the scope folder of GridAtlas that reads grid 400kV and substations, using SHA-256.
rendergridatlas / tools/scope/loop.mjs · lines 1–307 of 307 · Entry point
- What it does
- It loads grid 400kV and substations. Defines 9 functions or classes, including existingDirectories, existingFiles, verifyReleaseChecksums, validateScopeLedger, validateWorkflowBudget. Uses libraries node:fs, node:path. 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.
- Inputs & outputs
- In: GeoJSON file grid_400kv.geojson; JSON file current.json; JSON file current-v5.json; JSON file live-set.json; command-line arguments. Voltage levels named: 400kV.
- Downstream impact
- Used directly by 8 files: Local CI (gridatlas); CI PR Gate (gridatlas); GridAtlas — Release (gridatlas); Advance (gridatlas); and 4 more. Reached from 25 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); GridAtlas Verify Live Workflow (gridatlas); Acceptance (gridatlas).
- What it achieves
- It verifies release checksums (`verifyReleaseChecksums`), validates scope ledger (`validateScopeLedger`) and validates workflow budget (`validateWorkflowBudget`). Defines `existingDirectories`, `existingFiles`, `verifyReleaseChecksums` and 6 more. Its code works with 400 kV.
- Why it matters
- Run by 8 workflows and scripts, including Local CI, CI PR Gate and GridAtlas — Release.
- Application
- gridatlas · tools/scope · JavaScript module
- Uses
- GridAtlas — Scope (import), GridAtlas — Atlas Page (estate URL), node:fs, node:path
- Used by
- run by Local CI (script call), run by CI PR Gate (script call), run by GridAtlas — Release (script call), run by Advance (script call), run by GridAtlas Scope Loop Workflow (workflow run), run by GridAtlas Next Version Builders Workflow (workflow run), run by GridAtlas Cartridge Proof Workflow (workflow run), run by GridAtlas Rollback Composition Workflow (workflow run)
- Produces
- existingDirectories, existingFiles, verifyReleaseChecksums, validateScopeLedger, validateWorkflowBudget, validateAtlasLayout, lint, renderState, next
- Defines here
- existingDirectories, existingFiles, verifyReleaseChecksums, validateScopeLedger, validateWorkflowBudget, validateAtlasLayout, lint, renderState, next
- 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/scope/loop.mjs:1-307 · blob 4c254479cbcb86ef9d44e73eee890d3bcc572040 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import fs from 'node:fs';
import path from 'node:path';
import {
ROOT, SCOPE_DIR, MASTER_NAME, CURRENT_RELEASE, SHARED_400KV_CARTRIDGE,
EXPECTED_RELEASES, ACTIVE_WORKFLOWS, CARTRIDGE_BYTE_BUDGETS, invariant, listScopeDocuments,
registeredLoader, slotsUsed,
masterDocument, numberedScopes, activeScope, readJson, sha256File, sha256PublishedFile,
writeText, githubOutput, relativePosix
} from './lib.mjs';
const RELEASE_PATTERN = /^\d{12}-atlas-v9$/;
const ALLOWED_STATUS = new Set(['active', 'done', 'blocked']);
function existingDirectories(directory) {
if (!fs.existsSync(directory)) return [];
return fs.readdirSync(directory, { withFileTypes: true })
.filter(entry => entry.isDirectory())
.map(entry => entry.name)
.sort();
}
function existingFiles(directory, pattern = null) {
if (!fs.existsSync(directory)) return [];
return fs.readdirSync(directory, { withFileTypes: true })
.filter(entry => entry.isFile() && (!pattern || pattern.test(entry.name)))
.map(entry => entry.name)
.sort();
}
function verifyReleaseChecksums(releaseDirectory) {
const sumsPath = path.join(releaseDirectory, 'sha256sums.txt');
invariant(fs.existsSync(sumsPath), `${relativePosix(sumsPath)} is missing`);
const lines = fs.readFileSync(sumsPath, 'utf8').trim().split(/\r?\n/).filter(Boolean);
invariant(lines.length >= 20, `${relativePosix(sumsPath)} has an implausible entry count`);
for (const line of lines) {
const match = line.match(/^([a-f0-9]{64}) (.+)$/);
invariant(match, `${relativePosix(sumsPath)}: malformed checksum line ${JSON.stringify(line)}`);
const target = path.resolve(releaseDirectory, match[2]);
invariant(target.startsWith(`${path.resolve(releaseDirectory)}${path.sep}`), `${relativePosix(sumsPath)}: path escapes release: ${match[2]}`);
invariant(fs.existsSync(target), `${relativePosix(target)} is missing`);
// Compare against the published (LF) content rather than the working copy,
// so a Windows CRLF checkout cannot fail an untouched immutable release.
invariant(sha256PublishedFile(target) === match[1], `${relativePosix(target)} SHA-256 mismatch`);
}
}
function validateScopeLedger() {
const documents = listScopeDocuments();
const byName = new Map(documents.map(item => [item.name, item]));
const master = masterDocument(documents);
const scopes = numberedScopes(documents);
invariant(master.data.schema === 'gridatlas.scope-of-works.v1', `${MASTER_NAME}: schema mismatch`);
invariant(master.data.scope === 0, `${MASTER_NAME}: scope must be 0`);
invariant(['active', 'done'].includes(master.data.status), `${MASTER_NAME}: invalid status`);
const seenScopeNumbers = new Set();
for (const document of documents) {
invariant(document.data.schema === 'gridatlas.scope-of-works.v1', `${document.name}: schema mismatch`);
invariant(ALLOWED_STATUS.has(document.data.status), `${document.name}: invalid status ${document.data.status}`);
invariant(/^\d{12}$/.test(String(document.data.generation)), `${document.name}: invalid generation`);
invariant(document.name.startsWith(String(document.data.generation)), `${document.name}: filename/generation mismatch`);
invariant(Number.isInteger(document.data.scope), `${document.name}: scope must be an integer`);
if (document.data.scope > 0) {
invariant(!seenScopeNumbers.has(document.data.scope), `${document.name}: duplicate scope ${document.data.scope}`);
seenScopeNumbers.add(document.data.scope);
invariant(document.data.scope >= 1 && document.data.scope <= 6, `${document.name}: scope outside 1..6`);
}
if (document.data.parent !== null) invariant(byName.has(document.data.parent), `${document.name}: missing parent ${document.data.parent}`);
if (document.data.next !== null) invariant(byName.has(document.data.next), `${document.name}: missing next ${document.data.next}`);
}
scopes.forEach((document, index) => {
const expectedScope = index + 1;
invariant(document.data.scope === expectedScope, `${document.name}: expected contiguous scope ${expectedScope}`);
const expectedParent = expectedScope === 1 ? MASTER_NAME : scopes[index - 1].name;
invariant(document.data.parent === expectedParent, `${document.name}: parent must be ${expectedParent}`);
if (index > 0) {
invariant(Number(document.data.generation) > Number(scopes[index - 1].data.generation), `${document.name}: generation must advance beyond its parent scope`);
}
if (document.data.status === 'done' && document.data.scope < 6) {
invariant(document.data.next !== null, `${document.name}: completed scope must point to successor`);
}
if (document.data.status === 'active') invariant(document.data.next === null, `${document.name}: active scope must not pre-name its successor`);
});
const active = activeScope(documents);
if (master.data.status === 'active') {
invariant(active, 'master is active but no numbered scope is active');
invariant(master.data.active_scope === active.data.scope, `${MASTER_NAME}: active_scope does not match ${active.name}`);
invariant(scopes.filter(item => item.data.status === 'active').length === 1, 'exactly one numbered scope must be active');
invariant(scopes.filter(item => item.data.status === 'blocked').length === 0, 'blocked scope requires human repair before loop continues');
} else {
invariant(!active, 'master is done but a numbered scope remains active');
invariant(scopes.length === 6 && scopes.every(item => item.data.status === 'done'), 'closed master requires six completed scopes');
invariant(master.data.active_scope === null, 'closed master active_scope must be null');
}
invariant(master.data.next === scopes[0]?.name, `${MASTER_NAME}: next must identify Scope 1`);
return { documents, master, scopes, active };
}
function validateWorkflowBudget(master) {
const workflowDirectory = path.join(ROOT, '.github', 'workflows');
const activeFiles = existingFiles(workflowDirectory, /\.ya?ml$/);
invariant(JSON.stringify(activeFiles) === JSON.stringify([...ACTIVE_WORKFLOWS].sort()), `active workflow budget mismatch: ${JSON.stringify(activeFiles)}`);
const archiveDirectory = path.join(ROOT, '.github', 'workflow-archive', '202608301321-hostile-amnesia');
const archived = existingFiles(archiveDirectory, /\.ya?ml$/);
invariant(archived.length === 21, `expected 21 archived one-off workflows, found ${archived.length}`);
const loopWorkflow = fs.readFileSync(path.join(workflowDirectory, ACTIVE_WORKFLOWS[0]), 'utf8');
invariant(loopWorkflow.includes('11bd71901bbe5b1630ceea73d27597364c9af683'), 'checkout action must be pinned by full SHA');
if (master.data.status === 'done') {
invariant(loopWorkflow.includes('scope-loop-mode: retired'), 'closed scope loop must be retired');
invariant(!/^\s*schedule:/m.test(loopWorkflow), 'retired scope loop must not retain a schedule');
} else {
invariant(loopWorkflow.includes('scope-loop-mode: active'), 'active scope loop marker is missing');
invariant(/^\s*schedule:/m.test(loopWorkflow), 'active scope loop requires its bounded fallback schedule');
}
}
function validateAtlasLayout(scopeState) {
const rootReleases = existingDirectories(ROOT).filter(name => RELEASE_PATTERN.test(name));
const scope1Done = scopeState.scopes.some(item => item.data.scope === 1 && item.data.status === 'done');
const scope2Done = scopeState.scopes.some(item => item.data.scope === 2 && item.data.status === 'done');
if (!scope1Done) {
invariant(JSON.stringify(rootReleases) === JSON.stringify([...EXPECTED_RELEASES].sort()), `pre-migration root release set changed: ${JSON.stringify(rootReleases)}`);
return;
}
invariant(rootReleases.length === 0, `top-level release directories remain: ${rootReleases.join(', ')}`);
const releaseRoot = path.join(ROOT, 'atlas', 'releases');
const movedReleases = existingDirectories(releaseRoot).filter(name => RELEASE_PATTERN.test(name));
invariant(JSON.stringify(movedReleases) === JSON.stringify([...EXPECTED_RELEASES].sort()), `atlas/releases immutable baseline mismatch: ${JSON.stringify(movedReleases)}`);
invariant(fs.existsSync(path.join(releaseRoot, 'cartridges', SHARED_400KV_CARTRIDGE, 'grid_400kv.geojson')), 'shared 400 kV cartridge was not moved with the release baseline');
invariant(!fs.existsSync(path.join(ROOT, 'cartridges', SHARED_400KV_CARTRIDGE)), 'old shared 400 kV cartridge path still exists');
const rootIndex = fs.readFileSync(path.join(ROOT, 'index.html'), 'utf8');
invariant(rootIndex.includes('./atlas/'), 'root index does not redirect to ./atlas/');
invariant(!rootIndex.includes(CURRENT_RELEASE), 'root index still hard-codes a full release');
const currentPath = path.join(ROOT, 'atlas', 'current.json');
const atlasIndexPath = path.join(ROOT, 'atlas', 'index.html');
invariant(fs.existsSync(currentPath), 'atlas/current.json is missing');
invariant(fs.existsSync(atlasIndexPath), 'atlas/index.html is missing');
const current = readJson(currentPath);
invariant(current.release_id === CURRENT_RELEASE, 'atlas/current.json release_id mismatch');
invariant(current.live_route === '/gridatlas/atlas/', 'atlas/current.json live_route mismatch');
invariant(current.release_route === `/gridatlas/atlas/releases/${CURRENT_RELEASE}/`, 'atlas/current.json release_route mismatch');
const pointerA = readJson(path.join(ROOT, 'releases', 'current-v5.json'));
const pointerB = readJson(path.join(ROOT, 'state', 'live-set.json'));
invariant(JSON.stringify(pointerA) === JSON.stringify(pointerB), 'releases/current-v5.json and state/live-set.json diverged');
invariant(pointerA.current?.live_url === 'https://ventusltd.github.io/gridatlas/atlas/', 'live pointer does not name stable atlas route');
invariant(pointerA.current?.route === '/gridatlas/atlas/', 'live pointer route mismatch');
invariant(pointerA.current?.release_route === `/gridatlas/atlas/releases/${CURRENT_RELEASE}/`, 'live pointer release route mismatch');
verifyReleaseChecksums(path.join(releaseRoot, CURRENT_RELEASE));
if (scope2Done) {
invariant(current.schema === 'gridatlas.current.v2', 'modular atlas/current.json schema is not v2');
invariant(current.architecture === 'IMMUTABLE_SHELL_PLUS_HASHED_CARTRIDGES', 'modular architecture marker is missing');
invariant(current.shell?.index === `./releases/${CURRENT_RELEASE}/index.html`, 'shell index mismatch');
invariant(current.shell?.base === `./releases/${CURRENT_RELEASE}/`, 'shell base mismatch');
invariant(Array.isArray(current.cartridge_order) && Array.isArray(current.cartridges), 'cartridge registry is malformed');
invariant(new Set(current.cartridge_order).size === current.cartridge_order.length, 'cartridge_order contains duplicates');
const byId = new Map(current.cartridges.map(item => [item.id, item]));
invariant(byId.size === current.cartridges.length, 'cartridge IDs are not unique');
for (const id of current.cartridge_order) {
const cartridge = byId.get(id);
invariant(cartridge, `cartridge_order references missing ${id}`);
invariant(/^[a-f0-9]{64}$/.test(cartridge.sha256 || ''), `${id}: invalid SHA-256`);
const cartridgePath = path.resolve(path.join(ROOT, 'atlas'), cartridge.path);
invariant(cartridgePath.startsWith(`${path.resolve(path.join(ROOT, 'atlas'))}${path.sep}`), `${id}: path escapes atlas/`);
invariant(fs.existsSync(cartridgePath), `${id}: ${relativePosix(cartridgePath)} is missing`);
// The browser fetches the served bytes and hashes those, so verify the
// same thing here rather than the CRLF working copy.
invariant(sha256PublishedFile(cartridgePath) === cartridge.sha256, `${id}: SHA-256 mismatch`);
/* The 400 kB figure stopped describing reality on 202609051503, when
substation-intelligence went 382 kB -> 425 kB, and every composition
published since - including the one root has been serving live all
week - has been over it. So the invariant has not been holding a line;
it has been failing on every run, which silently made `state`
unrunnable and the AGENTS.md rule tying STATE.md to a current.json
change impossible to satisfy. A budget that only ever reports the same
known breach measures nothing.
The ceiling is therefore recorded at what is actually shipping, and
400 kB stays the target rather than the gate. The real fix is to split
substation-intelligence into parts and assemble it the way the
gazetteer already does (`assembled_from`); until that is done this
number must not be raised again to admit further growth. */
invariant(fs.statSync(cartridgePath).size <= 500_000, `${id}: cartridge exceeds the 500 kB recorded ceiling (400 kB target; raised from 460 kB by the owner on 27 Oct 2026 and to 500 kB on 28 Oct 2026 for the lightning overlay)`);
if (Object.hasOwn(CARTRIDGE_BYTE_BUDGETS, id)) {
invariant(fs.statSync(cartridgePath).size <= CARTRIDGE_BYTE_BUDGETS[id], `${id}: cartridge exceeds its own ${CARTRIDGE_BYTE_BUDGETS[id]}-byte budget (tools/scope/lib.mjs CARTRIDGE_BYTE_BUDGETS)`);
}
if (cartridge.slot === 'after-cartridge') {
const at = current.cartridge_order.indexOf(cartridge.after);
invariant(at >= 0 && at < current.cartridge_order.indexOf(id), `${id}: after-cartridge anchor ${cartridge.after} must be composed before it`);
} else {
invariant(cartridge.slot === 'replace-script', `${id}: unsupported slot ${cartridge.slot}`);
}
}
const atlasIndex = fs.readFileSync(atlasIndexPath, 'utf8');
invariant(atlasIndex.includes('crypto.subtle.digest'), 'atlas loader does not verify cartridge SHA-256');
invariant(atlasIndex.includes('document.write'), 'atlas loader does not compose the immutable shell');
invariant(atlasIndex.includes('cartridge_order'), 'atlas loader does not obey cartridge order');
/* The served composer is a registered one and knows every slot the live
composition uses (docs/LIGHTNING-CARTRIDGE.md). */
const loader = registeredLoader(atlasIndexPath);
invariant(loader, 'atlas/index.html is not byte-identical to a registered loader (tools/scope/lib.mjs ATLAS_LOADERS)');
for (const slot of slotsUsed(current)) invariant(loader.slots.includes(slot), `atlas/index.html (loader ${loader.name}) does not support slot ${slot} used by atlas/current.json`);
for (const obsolete of ['successor', 'successor-202608291239', 'successor-202608291430', 'v8-mirror']) {
invariant(!fs.existsSync(path.join(ROOT, 'ui', obsolete)), `obsolete UI copy remains: ui/${obsolete}`);
}
invariant(!fs.existsSync(path.join(ROOT, 'assets')), 'obsolete root assets copy remains');
invariant(!fs.existsSync(path.join(ROOT, 'cartridges')), 'obsolete root cartridges copy remains');
}
}
function lint({ quiet = false } = {}) {
const scopeState = validateScopeLedger();
validateWorkflowBudget(scopeState.master);
validateAtlasLayout(scopeState);
/* Under --stdout the caller is diffing this stream against STATE.md, so
the ledger line goes to stderr, where it is still read by a human and
still fails the run if it throws, but is not in the bytes compared. */
const line = `scope-ledger=PASS active=${scopeState.active?.name || 'none'} master=${scopeState.master.data.status}`;
if (quiet) console.error(line); else console.log(line);
return scopeState;
}
/* `--stdout` renders WITHOUT writing.
------------------------------------------------------------------------
AGENTS.md asks, before every handover: "Prove `node tools/scope/loop.mjs
state --stdout` exactly matches STATE.md". That proof could not fail.
Only `process.argv[2]` was ever read, so `--stdout` was silently ignored,
the command took its normal path, and its normal path WRITES STATE.md -
the very file the operator is about to compare it against.
Demonstrated rather than argued: replace STATE.md with the single line
"DELIBERATELY WRONG", run `state --stdout`, and the file comes back
correct. A drifted STATE.md was repaired by the check that existed to
detect it, and the operator saw a match every time.
So the flag is read now, and with it nothing is written: the rendered
text goes to stdout and the caller diffs it. */
function renderState(scopeState, { toStdout = false } = {}) {
const rootReleaseCount = existingDirectories(ROOT).filter(name => RELEASE_PATTERN.test(name)).length;
const atlasReleaseCount = existingDirectories(path.join(ROOT, 'atlas', 'releases')).filter(name => RELEASE_PATTERN.test(name)).length;
let composition = 'not-created';
const currentPath = path.join(ROOT, 'atlas', 'current.json');
if (fs.existsSync(currentPath)) {
const current = readJson(currentPath);
composition = `${current.generation} · ${current.release_id} · ${(current.cartridge_order || []).join(' → ') || 'shell only'}`;
}
const rows = scopeState.scopes.map(item => `| ${item.data.scope} | ${item.data.generation} | ${item.data.status} | ${item.name} |`).join('\n');
const state = `# GridAtlas durable state\n\n- Master: \`${scopeState.master.data.status}\`\n- Active scope: \`${scopeState.active?.name || 'none'}\`\n- Composition: \`${composition}\`\n- Top-level full release copies: \`${rootReleaseCount}\`\n- Immutable releases under atlas/releases: \`${atlasReleaseCount}\`\n- Active workflows: \`${ACTIVE_WORKFLOWS.length}\`\n- Historical workflows archived: \ … [line shortened here: 622 characters; full line on GitHub]
if (toStdout) {
/* Exactly the bytes that would have been written, and nothing else on
this stream - a caller diffing this against STATE.md must not have to
strip a status line out of it first. */
process.stdout.write(state);
return;
}
writeText(path.join(ROOT, 'STATE.md'), state);
console.log('STATE.md=UPDATED');
}
function next(scopeState) {
const active = scopeState.active;
const output = {
pending: Boolean(active),
scope_file: active?.name || '',
scope_number: active?.data.scope || '',
generation: active?.data.generation || ''
};
githubOutput(output);
console.log(JSON.stringify(output));
}
const command = process.argv[2] || 'lint';
const flags = new Set(process.argv.slice(3));
/* An unrecognised flag is a typo, not a no-op. `--stdout` was ignored for
as long as it has been in AGENTS.md; a silently discarded flag is how a
governance check becomes a formality. */
for (const flag of flags) {
if (flag !== '--stdout') {
console.error(`[scope-loop:${command}] unknown flag ${flag}`);
process.exit(1);
}
}
try {
if (command === 'lint') lint();
else if (command === 'state') {
const toStdout = flags.has('--stdout');
renderState(lint({ quiet: toStdout }), { toStdout });
}
else if (command === 'next') next(lint());
else throw new Error(`unknown command ${command}`);
} catch (error) {
console.error(`[scope-loop:${command}] ${error?.stack || error}`);
process.exitCode = 1;
}