In this section
- Rollback Generation automation · gridatlas / tools/release/rollback-generation.mjs lines 1–204
- Split Lightning Cartridge automation · gridatlas / tools/release/split-lightning-cartridge.mjs lines 1–136
- GridAtlas Rollback storage · gridatlas / tools/rollback.mjs lines 1–251
Rollback Generation
A JavaScript module in the tools folder of GridAtlas that works with rollback loader only (`rollbackLoaderOnly`), using SHA-256.
automationgridatlas / tools/release/rollback-generation.mjs · lines 1–204 of 204 · Entry point · pattern abort (shared by 9 files)
- What it does
- It lists and searches its content. Defines 7 functions or classes, including die, step, ok, finish, abort. Uses libraries node:fs, node:path. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'generation'): 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 current.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: Loader Swap Test (gridatlas); Map Promotion Rehearsal (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
- What it achieves
- It is built from the die step (`die`), the step step (`step`) and the finish step (`finish`). Roll a release back by reverting its release commit (route C of `RELEASE-COMMANDS.md`) and prove the pointer is restored byte for byte.
- Why it matters
- Run by Map Promotion Rehearsal. Checked by Loader Swap Test.
- Application
- gridatlas · tools/release · JavaScript module
- Uses
- GridAtlas — Release (import), Loader Swap (import), node:fs, node:path
- Used by
- run by Loader Swap Test (script call), run by Map Promotion Rehearsal (script call)
- Produces
- die, step, ok, finish, abort, rollbackLoaderOnly, abort
- Defines here
- die, step, ok, finish, abort, rollbackLoaderOnly, abort
- 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/release/rollback-generation.mjs:1-204 · blob 9a0fd7228751df4658c744d1b50a90a4ccff4792 · 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: production_core
#!/usr/bin/env node
/**
* Roll a release back by reverting its release commit (route C of
* RELEASE-COMMANDS.md) and prove the pointer is restored byte for byte.
*
* node tools/release/rollback-generation.mjs --release-commit SHA --reason "..." [options]
*
* Route C versus tools/rollback.mjs (route B): rollback.mjs cuts a NEW
* generation carrying an older composition, so its bytes differ from what was
* live before by design. Reverting the release commit instead restores the
* exact pre-release atlas/current.json and STATE.md, which is only possible
* because release-generation.mjs keeps the release commit to those two files.
*
* Preconditions, nothing written:
* - clean tree, HEAD exactly --base (default origin/main);
* - SHA is a single-parent ancestor of HEAD that changed exactly
* atlas/current.json and STATE.md, or those and atlas/index.html (a
* release that moved the loader with the pointer, docs/LIGHTNING-CARTRIDGE.md),
* or atlas/index.html alone (step 1 of a two-step release,
* tools/release/loader-swap.mjs): that revert is refused unless the live
* pointer composes under the restored loader byte for byte as under the
* current one, so while a generation needing the newer loader is live the
* pointer must be rolled back first, then the loader;
* - the pointer has not moved since: HEAD:atlas/current.json is SHA's bytes
* (and HEAD:atlas/index.html too, when SHA moved it).
* Then, on a new branch: `git revert --no-commit SHA`, and
* - atlas/current.json sha256 == SHA^:atlas/current.json (byte-exact);
* - STATE.md sha256 == SHA^:STATE.md when nothing touched STATE.md since the
* release (otherwise it must still equal the generator; reported);
* - lint, state parity, verify-compose (the predecessor), run-current,
* data-contract parity (no new FAIL rows).
* Then the revert commit. It never pushes.
*
* Options
* --release-commit SHA the release commit to revert (required)
* --reason TEXT why (required; recorded in the commit)
* --base REV HEAD must equal this (default origin/main)
* --branch NAME default rollback/<G>-to-<P>
* --trailer TEXT appended to the commit message (repeatable)
* --no-commit leave the revert uncommitted for inspection
* --report FILE / --log FILE
*/
import fs from 'node:fs';
import path from 'node:path';
import {
ROOT, POINTER_FILES, LOADER_FILE, die as dieWith, parseArgs, run, git, gitOk, gitBlob, sha256, sha256File,
cleanTree, changedPaths, runGates, printGates, parityFailRows, commitWithMessage, trailerBlock
} from './lib.mjs';
import { proveLoaderSwap } from './loader-swap.mjs';
const TOOL = 'rollback-generation';
const die = (m) => dieWith(TOOL, m);
const step = (m) => console.log(`\n== ${m}`);
const ok = (m) => console.log(` OK ${m}`);
let args;
try {
args = parseArgs(process.argv.slice(2), {
'release-commit': {}, reason: {}, base: { default: 'origin/main' }, branch: {},
trailer: { multi: true }, 'no-commit': { bool: true }, report: {}, log: {}
});
} catch (error) { die(error.message); }
if (!args['release-commit']) die('--release-commit is required');
if (!args.reason) die('--reason is required; an unexplained pointer move is not a rollback');
const report = { tool: TOOL, root: ROOT, started_utc: new Date().toISOString() };
const finish = (code) => {
report.finished_utc = new Date().toISOString();
report.exit = code;
if (args.report) fs.writeFileSync(path.resolve(args.report), `${JSON.stringify(report, null, 1)}\n`);
process.exit(code);
};
step('preconditions');
if (!cleanTree()) die(`working tree is not clean:\n${changedPaths().join('\n')}`);
if (!gitOk('rev-parse', '--verify', '--quiet', `${args.base}^{commit}`)) die(`--base ${args.base} does not resolve`);
const baseSha = git('rev-parse', `${args.base}^{commit}`);
if (git('rev-parse', 'HEAD') !== baseSha) die(`HEAD is not ${args.base} ${baseSha}`);
ok(`clean tree, HEAD = ${args.base} = ${baseSha}`);
if (!gitOk('rev-parse', '--verify', '--quiet', `${args['release-commit']}^{commit}`)) die(`${args['release-commit']} is not a commit`);
const R = git('rev-parse', `${args['release-commit']}^{commit}`);
if (!gitOk('merge-base', '--is-ancestor', R, 'HEAD')) die(`${R} is not an ancestor of HEAD`);
const parents = git('rev-list', '--parents', '-n', '1', R).split(' ').slice(1);
if (parents.length !== 1) die(`${R} has ${parents.length} parents; revert a single release commit, not a merge`);
const touched = git('diff', '--name-only', `${R}^`, R).split('\n').filter(Boolean).sort();
if (touched.length === 1 && touched[0] === LOADER_FILE) await rollbackLoaderOnly(R);
const loaderMoved = touched.includes(LOADER_FILE);
const RELEASE_FILES = loaderMoved ? [...POINTER_FILES, LOADER_FILE] : [...POINTER_FILES];
if (JSON.stringify(touched) !== JSON.stringify([...RELEASE_FILES].sort())) die(`${R} changed ${touched.join(', ')}; a release commit changes exactly ${POINTER_FILES.join(' and ')} (and ${LOADER_FILE} when the loader moved)`);
ok(`${R.slice(0, 7)} is a single-parent release commit touching ${touched.join(', ')}`);
const releasedPointer = gitBlob(R, 'atlas/current.json');
const restoredPointer = gitBlob(`${R}^`, 'atlas/current.json');
const restoredState = gitBlob(`${R}^`, 'STATE.md');
const G = JSON.parse(releasedPointer.toString('utf8')).generation;
const P = JSON.parse(restoredPointer.toString('utf8')).generation;
const livePointer = gitBlob('HEAD', 'atlas/current.json');
if (Buffer.compare(livePointer, releasedPointer) !== 0) die(`atlas/current.json has moved since ${R.slice(0, 7)} (live is ${JSON.parse(livePointer).generation}); reverting would not restore a known state`);
if (loaderMoved && Buffer.compare(gitBlob('HEAD', LOADER_FILE), gitBlob(R, LOADER_FILE)) !== 0) die(`${LOADER_FILE} has moved since ${R.slice(0, 7)}; reverting would not restore a known state`);
const stateUntouchedSince = Buffer.compare(gitBlob('HEAD', 'STATE.md'), gitBlob(R, 'STATE.md')) === 0;
ok(`live is ${G} exactly as ${R.slice(0, 7)} wrote it; rollback restores ${P}`);
Object.assign(report, { release_commit: R, from: G, to: P, base: baseSha,
expected: { 'atlas/current.json': sha256(restoredPointer), 'STATE.md': sha256(restoredState),
...(loaderMoved ? { [LOADER_FILE]: sha256(gitBlob(`${R}^`, LOADER_FILE)) } : {}) },
before: Object.fromEntries(RELEASE_FILES.map(f => [f, sha256File(f)])) });
const parityBaseline = parityFailRows().rows;
const branch = args.branch || `rollback/${G}-to-${P}`;
if (gitOk('rev-parse', '--verify', '--quiet', `refs/heads/${branch}`)) die(`branch ${branch} already exists`);
run('git', ['switch', '-q', '-c', branch]);
step(`branch ${branch}: git revert --no-commit ${R.slice(0, 7)}`);
const revert = run('git', ['revert', '--no-commit', R], { allowFail: true });
const abort = () => { run('git', ['revert', '--abort'], { allowFail: true }); run('git', ['switch', '-q', '--detach', baseSha]); run('git', ['branch', '-D', branch], { allowFail: true }); };
if (revert.status !== 0) { abort(); die(`git revert did not apply cleanly:\n${revert.out}`); }
const after = Object.fromEntries(RELEASE_FILES.map(f => [f, sha256File(f)]));
report.after = after;
if (after['atlas/current.json'] !== report.expected['atlas/current.json']) { abort(); die('atlas/current.json is NOT byte-exact to the pre-release pointer'); }
ok(`atlas/current.json byte-exact to ${R.slice(0, 7)}^ (${after['atlas/current.json']})`);
if (loaderMoved) {
if (after[LOADER_FILE] !== report.expected[LOADER_FILE]) { abort(); die(`${LOADER_FILE} is NOT byte-exact to the pre-release loader`); }
ok(`${LOADER_FILE} byte-exact to ${R.slice(0, 7)}^ (${after[LOADER_FILE]})`);
}
const stateExact = after['STATE.md'] === report.expected['STATE.md'];
if (stateUntouchedSince && !stateExact) { abort(); die('STATE.md is NOT byte-exact to the pre-release STATE.md'); }
ok(stateExact ? `STATE.md byte-exact to ${R.slice(0, 7)}^ (${after['STATE.md']})` : 'STATE.md changed after the release for another reason; checked against the generator instead');
report.byte_exact = { 'atlas/current.json': true, 'STATE.md': stateExact, ...(loaderMoved ? { [LOADER_FILE]: true } : {}) };
step('gates');
const gates = runGates({ expectGeneration: P, parityBaseline });
printGates(gates.rows);
if (args.log) fs.writeFileSync(path.resolve(args.log), gates.log);
report.gates = gates.rows;
if (!gates.rows.every(r => r.ok)) { abort(); console.error(`\n${TOOL}: gates FAILED; nothing kept.`); finish(1); }
if (!args['no-commit']) {
const subject = git('log', '-1', '--format=%s', R);
const msg = `Revert "${subject}"\n\nThis reverts commit ${R}.\n\nRolls the live route back from ${G} to ${P} by reverting the release commit\n(route C): atlas/current.json${loaderMoved ? `, ${LOADER_FILE}` : ''} and STATE.md are byte-identical to ${R.slice(0, 7)}^.\nReason: ${args.reason}${trailerBlock(args.trailer)}\n`;
report.revert_commit = commitWithMessage(msg);
report.revert_tree = git('rev-parse', 'HEAD^{tree}');
}
step('hashes');
for (const f of RELEASE_FILES) console.log(` ${f.padEnd(20)} released ${report.before[f]}\n ${''.padEnd(20)} restored ${after[f]}${report.byte_exact[f] ? ' (byte-exact)' : ''}`);
if (report.revert_commit) console.log(` revert commit ${report.revert_commit}\n revert tree ${report.revert_tree}`);
console.log(`\nROLLBACK READY on branch ${branch} (not pushed): live would return to ${P}.`);
finish(0);
/* A loader-only commit: step 1 of a two-step release (tools/release/loader-swap.mjs release). It is
reverted only while the live pointer composes under the loader being restored, byte for byte as under
the current one; while a generation that needs the newer loader (an after-cartridge slot under v2) is
live, it is refused: roll the pointer back first, then the loader. */
async function rollbackLoaderOnly(R) {
ok(`${R.slice(0, 7)} is a single-parent loader-only commit (${LOADER_FILE})`);
const released = gitBlob(R, LOADER_FILE);
const restored = gitBlob(`${R}^`, LOADER_FILE);
if (Buffer.compare(gitBlob('HEAD', LOADER_FILE), released) !== 0) die(`${LOADER_FILE} has moved since ${R.slice(0, 7)}; reverting would not restore a known state`);
const pointerText = gitBlob('HEAD', 'atlas/current.json').toString('utf8');
const proof = await proveLoaderSwap({ fromLoader: released, toLoader: restored, pointerText });
const from = proof.from?.name || 'unregistered', to = proof.to?.name || 'unregistered';
if (!proof.ok) die(`refusing the loader rollback ${from} -> ${to}: ${proof.reasons.join('; ')}`);
ok(`${from} -> ${to} composes the live ${proof.generation} byte for byte (${proof.detail})`);
Object.assign(report, { release_commit: R, mode: 'loader-only', from, to, live: proof.generation, base: baseSha,
expected: { [LOADER_FILE]: sha256(restored) }, before: { [LOADER_FILE]: sha256File(LOADER_FILE) },
pointer_unchanged: { 'atlas/current.json': sha256File('atlas/current.json'), 'STATE.md': sha256File('STATE.md') } });
const parityBaseline = parityFailRows().rows;
const branch = args.branch || `rollback/loader-${from}-to-${to}`;
if (gitOk('rev-parse', '--verify', '--quiet', `refs/heads/${branch}`)) die(`branch ${branch} already exists`);
run('git', ['switch', '-q', '-c', branch]);
step(`branch ${branch}: git revert --no-commit ${R.slice(0, 7)}`);
const revert = run('git', ['revert', '--no-commit', R], { allowFail: true });
const abort = () => { run('git', ['revert', '--abort'], { allowFail: true }); run('git', ['switch', '-q', '--detach', baseSha]); run('git', ['branch', '-D', branch], { allowFail: true }); };
if (revert.status !== 0) { abort(); die(`git revert did not apply cleanly:\n${revert.out}`); }
report.after = { [LOADER_FILE]: sha256File(LOADER_FILE) };
if (report.after[LOADER_FILE] !== report.expected[LOADER_FILE]) { abort(); die(`${LOADER_FILE} is NOT byte-exact to ${R.slice(0, 7)}^`); }
for (const f of POINTER_FILES) if (sha256File(f) !== report.pointer_unchanged[f]) { abort(); die(`${f} changed in a loader-only revert`); }
ok(`${LOADER_FILE} byte-exact to ${R.slice(0, 7)}^ (${report.after[LOADER_FILE]}); atlas/current.json and STATE.md unchanged`);
report.byte_exact = { [LOADER_FILE]: true };
step('gates');
const gates = runGates({ expectGeneration: String(proof.generation), parityBaseline });
const eq = run('node', ['tools/proofs/loader-equivalence.proof.mjs'], { allowFail: true });
gates.rows.push({ gate: 'loader-equivalence', ok: eq.status === 0, detail: eq.out.trim().split('\n').pop() });
printGates(gates.rows);
if (args.log) fs.writeFileSync(path.resolve(args.log), `${gates.log}\n### loader-equivalence\n${eq.out}`);
report.gates = gates.rows;
if (!gates.rows.every(r => r.ok)) { abort(); console.error(`\n${TOOL}: gates FAILED; nothing kept.`); finish(1); }
if (!args['no-commit']) {
const subject = git('log', '-1', '--format=%s', R);
const msg = `Revert "${subject}"\n\nThis reverts commit ${R}.\n\nRestores the live loader ${from} -> ${to} (${LOADER_FILE} byte-identical to ${R.slice(0, 7)}^); the pointer stays ${proof.generation}.\nReason: ${args.reason}${trailerBlock(args.trailer)}\n`;
report.revert_commit = commitWithMessage(msg);
report.revert_tree = git('rev-parse', 'HEAD^{tree}');
}
step('hashes');
console.log(` ${LOADER_FILE.padEnd(20)} released ${report.before[LOADER_FILE]}\n ${''.padEnd(20)} restored ${report.after[LOADER_FILE]} (byte-exact)`);
if (report.revert_commit) console.log(` revert commit ${report.revert_commit}\n revert tree ${report.revert_tree}`);
console.log(`\nLOADER ROLLBACK READY on branch ${branch} (not pushed): the live loader would return to ${to}; live stays ${proof.generation}.`);
finish(0);
}Split Lightning Cartridge
A JavaScript module in the tools folder of GridAtlas that reads substations, using SHA-256.
automationgridatlas / tools/release/split-lightning-cartridge.mjs · lines 1–136 of 136 · Entry point · pattern readJson (shared by 43 files)
- What it does
- It loads substations. Defines die, rel, abs, readJson. 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.
- Inputs & outputs
- In: 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
- It reads JSON (`readJson`) and is built from the die step (`die`) and the rel step (`rel`). Cut a MODULAR lightning generation G from a monolithic one R: the same composition, with the UK lightning overlay as its own cartridge ('UK-lightning-overlay', slot after-cartridge, after single-line diagram (SLD)-sandbox) and SLD-sandbox back to the original cartridge (435,218 bytes). It reads `atlas/current.json`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gridatlas · tools/release · JavaScript module
- Uses
- GridAtlas — Release (import), node:fs, node:path
- Used by
- none found
- Produces
- die, rel, abs, readJson
- Defines here
- die, rel, abs, readJson
- 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/release/split-lightning-cartridge.mjs:1-136 · blob 90d0268eadcf797c0e36c642bf54bc613342a75b · 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: production_core
#!/usr/bin/env node
/**
* Cut a MODULAR lightning generation G from a monolithic one R: the same
* composition, with the UK lightning overlay as its own cartridge
* ('uk-lightning-overlay', slot after-cartridge, after sld-sandbox) and
* sld-sandbox back to the original 202609241334 cartridge (435,218 bytes).
* docs/LIGHTNING-CARTRIDGE.md.
*
* node tools/release/split-lightning-cartridge.mjs --from R --generation G --version vX [--check]
*
* R must be a pinned preview whose sld-sandbox is exactly
* original 202609241334 bytes + '\n' + atlas/modules/R-uk-lightning-overlay.js
* (the shape every lightning generation since 202610261949 has). Nothing is
* rebuilt: the overlay cartridge IS that module file, referenced by path and
* hash, so no bytes are copied.
*
* It writes only G's preview files:
* atlas/manifests/G-composition.json
* atlas/v/G/current.json the derived pointer re-rooted to ../../ (tools/release/lib.mjs)
* atlas/v/G/index.html loader v2 (tools/scope/payloads/atlas-loader-v2.html)
* tools/proofs/G-uk-lightning-overlay.proof.mjs
* It never writes atlas/current.json, STATE.md, atlas/index.html or
* atlas/releases/**, and never commits. previous_generation is the live
* generation, so tools/release/release-generation.mjs can release G later.
*/
import fs from 'node:fs';
import path from 'node:path';
import { ROOT, parseArgs, die as dieWith, sha256, deriveCurrent, rerootForPreview } from './lib.mjs';
const TOOL = 'split-lightning-cartridge';
const die = (m) => dieWith(TOOL, m);
const ORIGINAL = '202609241334';
const ORIGINAL_SHA = '7812953671d8bb22a566de5e98fd3137da2d23411c5aecd526df5afa111ca4ca';
const OVERLAY = 'uk-lightning-overlay';
const BUDGET = 64781;
const LOADER_V2 = 'tools/scope/payloads/atlas-loader-v2.html';
let args;
try {
args = parseArgs(process.argv.slice(2), { from: {}, generation: {}, version: {}, check: { bool: true } });
} catch (error) { die(error.message); }
const R = args.from, G = args.generation, VERSION = args.version;
if (!/^\d{12}$/.test(R || '')) die('--from must be the 12-digit monolithic generation');
if (!/^\d{12}$/.test(G || '') || G <= R) die('--generation must be a 12-digit generation later than --from');
if (!/^v\d+\.\d+[a-z]*$/.test(VERSION || '')) die('--version must look like v9.178');
const rel = (...p) => path.posix.join(...p);
const abs = (p) => path.join(ROOT, p);
const readJson = (p) => JSON.parse(fs.readFileSync(abs(p), 'utf8'));
const outputs = [rel('atlas/manifests', `${G}-composition.json`), rel('atlas/v', G, 'current.json'), rel('atlas/v', G, 'index.html'), rel('tools/proofs', `${G}-${OVERLAY}.proof.mjs`)];
for (const o of outputs) if (fs.existsSync(abs(o))) die(`${o} already exists; a generation is cut once`);
const live = readJson('atlas/current.json');
const ref = readJson(`atlas/manifests/${R}-composition.json`);
const original = readJson(`atlas/manifests/${ORIGINAL}-composition.json`).cartridges.find(c => c.id === 'sld-sandbox');
const refSld = ref.cartridges.find(c => c.id === 'sld-sandbox');
if (!refSld || !original) die('sld-sandbox missing from a manifest');
if (ref.cartridge_order.includes(OVERLAY)) die(`${R} is already modular`);
if (original.sha256 !== ORIGINAL_SHA) die(`the ${ORIGINAL} manifest no longer records the original sld-sandbox`);
const moduleRel = `atlas/modules/${R}-uk-lightning-overlay.js`;
const moduleBytes = fs.readFileSync(abs(moduleRel));
const originalBytes = fs.readFileSync(abs(rel('atlas', original.path)));
const refBytes = fs.readFileSync(abs(rel('atlas', refSld.path)));
if (sha256(originalBytes) !== ORIGINAL_SHA) die(`${original.path} is not the original bytes`);
if (sha256(refBytes) !== refSld.sha256) die(`${refSld.path} does not hash to ${R}'s record`);
if (Buffer.compare(refBytes, Buffer.concat([originalBytes, Buffer.from('\n'), moduleBytes])) !== 0) {
die(`${R}'s sld-sandbox is not original + '\\n' + ${moduleRel}; this tool splits only that shape`);
}
if (moduleBytes.length > BUDGET) die(`${moduleRel} is ${moduleBytes.length} B, over the ${BUDGET}-byte overlay budget`);
console.log(`OK ${R} sld-sandbox (${refBytes.length} B) = original ${ORIGINAL} (${originalBytes.length} B) + '\\n' + ${moduleRel} (${moduleBytes.length} B)`);
const lightningCaps = refSld.capabilities.filter(x => !original.capabilities.includes(x));
const lightningSources = (refSld.data_sources || []).filter(x => !(original.data_sources || []).some(o => JSON.stringify(o) === JSON.stringify(x)));
const overlay = {
id: OVERLAY,
generation: G,
version: VERSION,
type: 'script',
slot: 'after-cartridge',
after: 'sld-sandbox',
path: `./modules/${R}-uk-lightning-overlay.js`,
sha256: sha256(moduleBytes),
bytes: moduleBytes.length,
byte_budget: BUDGET,
module_generation: R,
parity_reference: R,
immutable_shell_modified: false,
capabilities: lightningCaps,
reads_at_runtime: {
'window.__GRIDATLAS_MODULES__.menuBar': 'substation-intelligence; polled (MutationObserver + 250 ms) until installed',
'window.__GRIDATLAS_PIPELINE_LAYERS__': 'substation-intelligence; polled until installed',
'the MapLibre map': 'polled until present',
'#scada-ui-container .key-group, #fs-curtain-keys': 'the immutable shell and engine; polled until present',
'input[data-layer-id] (REPD layers)': 'the engine; read and ticked through its own change path on a tap'
},
writes: ['window.__GRIDATLAS_MODULES__.ukLightning'],
isolation: 'its own script element: a parse or top-level error in the overlay no longer stops sld-sandbox, and an sld-sandbox top-level throw no longer stops the overlay',
data_sources: lightningSources,
uk_lightning: { ...refSld.uk_lightning, module: `./modules/${R}-uk-lightning-overlay.js`,
delta: `its own cartridge (after-cartridge, after sld-sandbox), the module file itself; sld-sandbox is the original ${ORIGINAL} bytes` }
};
const manifest = {
...ref,
generation: G,
previous_generation: String(live.generation),
superseded_generation: String(live.generation),
candidate_predecessor: R,
composition_manifest: `./manifests/${G}-composition.json`,
composition_version: VERSION,
composition_id: `${G}-gridatlas-${VERSION}`,
cartridge_order: [...ref.cartridge_order, OVERLAY],
cartridges: [...ref.cartridges.map(c => (c.id === 'sld-sandbox' ? original : c)), overlay],
composition_note: `${VERSION}: ${R} recomposed, behaviour unchanged. The lightning overlay is its own cartridge (slot after-cartridge, its own script tag directly after sld-sandbox, where the appended module ran), and sld-sandbox is the original ${ORIGINAL} cartridge again (${originalBytes.length} bytes). Served by loader v2.`,
loader: 'v2',
parent_generation: String(live.generation),
version: VERSION,
cut_at_utc: new Date().toISOString(),
candidate_status: 'PROTOTYPE_NOT_PUBLISHED',
note: `Modular split of ${R} by tools/release/split-lightning-cartridge.mjs. atlas/current.json is untouched.`,
acceptance: { ...ref.acceptance, scope: `Recompose ${R} with the lightning overlay as its own after-cartridge cartridge; sld-sandbox returns to ${ORIGINAL}.`, full_application_copies_created: 0 }
};
const manifestText = `${JSON.stringify(manifest, null, 1)}\n`;
const pointerText = rerootForPreview(deriveCurrent(manifestText));
const proofText = `/** ${G}: the UK lightning overlay as its own cartridge (module ${R}); sld-sandbox is the original ${ORIGINAL}. tools/proofs/lightning-cartridge.mjs */\nimport { proveLightningCartridge } from './lightning-cartridge.mjs';\nawait proveLightningCartridge('${G}');\n`;
if (args.check) { console.log(`CHECK PASS: ${G} can be split from ${R}; nothing written.`); process.exit(0); }
fs.mkdirSync(abs(rel('atlas/v', G)), { recursive: true });
fs.writeFileSync(abs(outputs[0]), manifestText);
fs.writeFileSync(abs(outputs[1]), pointerText);
fs.copyFileSync(abs(LOADER_V2), abs(outputs[2]));
fs.writeFileSync(abs(outputs[3]), proofText);
for (const o of outputs) console.log(`WROTE ${o} sha256 ${sha256(fs.readFileSync(abs(o))).slice(0, 16)}…`);
console.log(JSON.stringify({ G, from: R, overlay: { path: overlay.path, bytes: overlay.bytes, sha256: overlay.sha256 }, sld: { path: original.path, bytes: originalBytes.length, sha256: original.sha256 } }));GridAtlas Rollback
A JavaScript module in the tools folder that works with committed bytes (`committedBytes`), using SHA-256. It reads JSON (`readJson`) and writes JSON (`writeJson`).
storagegridatlas / tools/rollback.mjs · lines 1–251 of 251 · Entry point · pattern committedBytes (shared by 2 files)
- What it does
- It loads data. Defines argv, die, readJson, writeJson, committedBytes. Uses libraries node:fs, node:path, node:child_process, node:crypto, 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 current.json; JSON file live-set.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: GridAtlas — Release (gridatlas); GridAtlas Rollback Composition Workflow (gridatlas). Reached from 27 other entry points, including GridAtlas Cartridge Proof Workflow (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas); GridAtlas Verify Live Workflow (gridatlas).
- What it achieves
- Roll the live composition back to a generation that has already shipped.
- Why it matters
- Run by GridAtlas — Release and GridAtlas Rollback Composition Workflow.
- Application
- gridatlas · tools · JavaScript module
- Uses
- GridAtlas Recompose (script call), node:fs, node:path, node:child_process, node:crypto, node:url
- Used by
- run by GridAtlas — Release (script call), run by GridAtlas Rollback Composition Workflow (workflow run)
- Produces
- argv, die, readJson, writeJson, committedBytes
- Defines here
- argv, die, readJson, writeJson, committedBytes
- 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/rollback.mjs:1-251 · blob 7d0946a703fafc3baefae2af43f01878f03550cc · 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: production_core
/**
* Roll the live composition back to a generation that has already shipped.
*
* WHY THIS EXISTS
* ---------------
* `tools/recompose.mjs` moves atlas/current.json forward. Nothing moved it
* back. Ten generations were cut in three hours on 2026-09-03, every one of
* them repointing the live route, and the only way to undo a bad one was to
* hand-edit the pointer at whatever hour it was noticed - which is the
* hand-editing habit that recompose was written to end.
*
* v9.83 pinned the runtime products by commit and digest so that a bad
* PRODUCT cannot reach a shipped release. This is the other half: so that a
* bad RELEASE cannot stay on the pointer.
*
* node tools/rollback.mjs --to 202609030233 --reason "why"
* node tools/rollback.mjs --to 202609030233 --reason "why" --dry-run
*
* WHAT IT IS NOT
* --------------
* It is not an amend. A shipped generation is never rewritten: rolling back
* cuts a NEW generation whose composition is a previously shipped one, and
* `previous_generation` still names the generation it replaced, so the
* lineage reads forwards and the history stays append-only. The manifest
* records `restored_from`, so a rollback is visible as a rollback rather than
* looking like an ordinary cut that happens to repeat itself.
*
* WHAT IT REFUSES
* ---------------
* A rollback that cannot be trusted is worse than no rollback, because it is
* reached for in the one moment nobody has time to check it. So before it
* writes anything:
*
* - the target must be an ANCESTOR of the current generation, walked
* through parent_generation. "Roll back" to something that never shipped
* on this line is a typo, and a typo at 3am must not be servable.
* - every cartridge the target names must still exist, and its bytes must
* still hash to the digest the target recorded. A pointer to bytes that
* are gone is the failure this whole mechanism exists to prevent.
*
* Digests are taken from the COMMITTED bytes (`git show HEAD:<path>`), never
* from the working copy. A git-clean tree is not a byte-clean tree: git
* compares through .gitattributes normalisation and reports clean while the
* disk holds CRLF and the blob holds LF. Four separate measurements in this
* estate were wrong for exactly that reason in one night. atlas/ is pinned to
* LF today and both readings agree, which is precisely why reading the wrong
* one now would go unnoticed until the day it stops agreeing.
*/
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
/* fileURLToPath, never new URL().pathname: on Windows the latter yields
"/C:/Users/..." and join() then produces "C:\C:\Users\...". */
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const ATLAS = path.join(ROOT, 'atlas');
function argv(flag) {
const index = process.argv.indexOf(flag);
return index === -1 ? null : process.argv[index + 1] ?? null;
}
function die(message) {
console.error(`rollback: ${message}`);
process.exit(1);
}
function readJson(file) {
return JSON.parse(fs.readFileSync(file, 'utf8'));
}
function writeJson(file, value) {
fs.writeFileSync(file, `${JSON.stringify(value, null, 1)}\n`, 'utf8');
}
/* The committed bytes, which are the bytes GitHub Pages serves. */
function committedBytes(relative) {
const shown = spawnSync('git', ['-C', ROOT, 'show', `HEAD:${relative}`], {
encoding: 'buffer',
maxBuffer: 256 * 1024 * 1024
});
if (shown.status !== 0) return null;
return shown.stdout;
}
const target = argv('--to');
const reason = argv('--reason');
const dryRun = process.argv.includes('--dry-run');
if (!target) die('--to <generation> is required');
if (!/^\d{12}$/.test(target)) die(`--to must be a 12-digit generation, got ${target}`);
if (!reason) die('--reason "..." is required; a rollback with no recorded reason is an unexplained pointer move');
const currentPath = path.join(ATLAS, 'current.json');
const current = readJson(currentPath);
const fromGeneration = current.generation;
if (target === fromGeneration) die(`${target} is already the live generation`);
const targetManifestPath = path.join(ATLAS, 'manifests', `${target}-composition.json`);
if (!fs.existsSync(targetManifestPath)) die(`no composition manifest for ${target}`);
const targetComposition = readJson(targetManifestPath);
/* A cut can exist as immutable audit evidence without ever having been live.
Such a generation must be retained, but it is not a rollback destination.
Check this before ancestry so a quarantined candidate fails for the real
reason even after the live lineage deliberately skips it. */
const targetStatus = String(targetComposition.candidate_status || '');
const targetBrowserStatus = String(
targetComposition.acceptance?.golden_browser_verification || '');
if (targetStatus === 'REJECTED_PRE_PROMOTION'
|| targetBrowserStatus.startsWith('REJECTED_PRE_PROMOTION')) {
die(`${target} is REJECTED_PRE_PROMOTION and was never live; `
+ 'rollback targets must be deployed generations');
}
/* ---- the target must be an ancestor, walked rather than assumed ---- */
const lineage = [];
let walk = fromGeneration;
const seen = new Set();
while (walk && !seen.has(walk)) {
seen.add(walk);
lineage.push(walk);
const manifestPath = path.join(ATLAS, 'manifests', `${walk}-composition.json`);
if (!fs.existsSync(manifestPath)) break;
walk = readJson(manifestPath).parent_generation || null;
}
if (!lineage.includes(target)) {
die(`${target} is not an ancestor of ${fromGeneration}; the lineage from here is ${lineage.join(' <- ')}`);
}
const distance = lineage.indexOf(target);
/* ---- every cartridge the target names must still be servable ---- */
const order = targetComposition.cartridge_order;
const cartridges = targetComposition.cartridges;
if (!Array.isArray(order) || !Array.isArray(cartridges) || cartridges.length === 0) {
die(`${target} composition manifest carries no cartridges`);
}
const byId = new Map(cartridges.map(entry => [entry.id, entry]));
for (const id of order) {
if (!byId.has(id)) die(`${target} names ${id} in cartridge_order and does not define it`);
}
const checks = [];
for (const cartridge of cartridges) {
const relative = path.posix.join('atlas', String(cartridge.path).replace(/^\.\//, ''));
const bytes = committedBytes(relative);
if (bytes === null) {
checks.push({ id: cartridge.id, relative, state: 'ABSENT' });
continue;
}
const digest = createHash('sha256').update(bytes).digest('hex');
checks.push({
id: cartridge.id,
relative,
bytes: bytes.length,
state: digest === cartridge.sha256 ? 'MATCH' : 'DIGEST_MISMATCH',
recorded: cartridge.sha256,
measured: digest
});
}
const shellIndex = path.posix.join('atlas', String(targetComposition.shell.index).replace(/^\.\//, ''));
const shellBytes = committedBytes(shellIndex);
checks.push({ id: 'shell:index.html', relative: shellIndex, state: shellBytes === null ? 'ABSENT' : 'PRESENT' });
for (const check of checks) {
console.log(` ${check.state.padEnd(15)} ${check.id.padEnd(28)} ${check.relative}`);
}
const broken = checks.filter(check => check.state !== 'MATCH' && check.state !== 'PRESENT');
if (broken.length) {
die(`${broken.length} of ${checks.length} target artefacts are absent or no longer hash to what ${target} recorded; refusing to point the live route at them`);
}
/* ---- the new generation ---- */
const now = new Date();
const stamp = argv('--generation') || [
now.getUTCFullYear(),
String(now.getUTCMonth() + 1).padStart(2, '0'),
String(now.getUTCDate()).padStart(2, '0'),
String(now.getUTCHours()).padStart(2, '0'),
String(now.getUTCMinutes()).padStart(2, '0')
].join('');
if (!/^\d{12}$/.test(stamp)) die(`malformed generation stamp ${stamp}`);
if (fs.existsSync(path.join(ATLAS, 'manifests', `${stamp}-composition.json`))) {
die(`${stamp} already exists; a rollback never rewrites a shipped generation`);
}
const version = targetComposition.composition_version || targetComposition.version;
if (!version) die(`${target} composition manifest records no composition_version`);
const restored = {
...current,
previous_generation: fromGeneration,
generation: stamp,
shell: targetComposition.shell.hashes
? { release_id: targetComposition.shell.release_id, index: targetComposition.shell.index, base: targetComposition.shell.base }
: targetComposition.shell,
cartridge_order: order,
cartridges,
composition_version: version,
composition_id: `${stamp}-gridatlas-${version}`,
composition_manifest: `./manifests/${stamp}-composition.json`,
composition_note: reason
};
const composition = {
...targetComposition,
generation: stamp,
parent_generation: fromGeneration,
restored_from: target,
restored_over: fromGeneration,
restored_generations_back: distance,
composition_id: restored.composition_id,
cut_at_utc: now.toISOString(),
acceptance: {
...(targetComposition.acceptance || {}),
scope: reason,
golden_browser_verification: 'PENDING_THIS_GENERATION'
},
note: reason
};
console.log('');
console.log(` from ${fromGeneration} ${current.composition_version}`);
console.log(` restoring ${target} ${version} (${distance} generation${distance === 1 ? '' : 's'} back)`);
console.log(` as ${stamp} ${restored.composition_id}`);
console.log(` cartridges ${cartridges.length} verified against committed bytes`);
if (dryRun) {
console.log('\n--dry-run: nothing written');
process.exit(0);
}
writeJson(path.join(ATLAS, 'manifests', `${stamp}-composition.json`), composition);
writeJson(currentPath, restored);
const liveSetPath = path.join(ATLAS, 'state', 'live-set.json');
if (fs.existsSync(liveSetPath)) {
const liveSet = readJson(liveSetPath);
liveSet.generation = stamp;
liveSet.composition_manifest = restored.composition_manifest;
liveSet.cartridge_order = restored.cartridge_order;
writeJson(liveSetPath, liveSet);
}
console.log(`\nrolled back to ${target} as ${restored.composition_id}`);
console.log('run `node tools/scope/loop.mjs state` and `node tools/proofs/run-current.mjs` before committing');