In this section
- Homepage Bump automation · gridatlas / tools/release/homepage-bump.mjs lines 1–247
- GridAtlas — Release automation · gridatlas / tools/release/lib.mjs lines 1–213
- Loader Swap automation · gridatlas / tools/release/loader-swap.mjs lines 1–153
Homepage Bump
A JavaScript module in the tools folder of GridAtlas that reads homepage owner, using SHA-256.
automationgridatlas / tools/release/homepage-bump.mjs · lines 1–247 of 247 · Entry point
- What it does
- It loads homepage owner. Defines 9 functions or classes, including die, ok, sh, gitIn, sha256. Uses libraries node:fs, node:path, node:child_process, 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 current.json; JSON file homepage.json; JSON file homepage-owner.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 cleans origin main (`cleanAtOriginMain`) and is built from the die step (`die`) and the git in helper (`gitIn`). Step 6 of the delivery flow: put the released GridAtlas on www.globalgrid2050.com.
- 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 (script call), Flow Lib (script call), node:fs, node:path, node:child_process, node:crypto
- Used by
- none found
- Produces
- die, ok, sh, gitIn, sha256, cleanAtOriginMain, pointerCommit, liveBytesPassed, homepageGridatlas
- Defines here
- die, ok, sh, gitIn, sha256, cleanAtOriginMain, pointerCommit, liveBytesPassed, homepageGridatlas
- 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/homepage-bump.mjs:1-247 · blob 193062b7427edd9f539f7bc7f0dd2c3c9b7f948c · 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
/**
* Step 6 of the delivery flow: put the released GridAtlas on
* www.globalgrid2050.com. Two repositories, two PRs, in this order:
*
* 6a. label: Ventusltd/globalgrid2050-homepage, its one-command tool
* node tools/release/homepage-bump.mjs label --homepage DIR [--generation G]
* [--description TEXT] [--published-at ISO] [--push] (--rehearsal: not-yet-live G, --offline, no push)
* 6b. pin: Ventusltd/globalgrid2050 (SPARSE clone; never check it out in full)
* node tools/release/homepage-bump.mjs pin --homepage DIR --domain DIR [--push]
* 6c. deploy: after the pin PR merges, deploy-pages.yml imports the pinned bundle
* node tools/release/homepage-bump.mjs deploy [--dispatch]
*
* PRE-CONDITIONS
* label:
* - gridatlas main's atlas/current.json names G (default: whatever is live);
* - the live-bytes job passed for the commit that moved the pointer
* (tools/release/check-live.mjs), so the homepage never advertises bytes
* Pages is not yet serving;
* - the owner accepted G (tools/release/acceptance.mjs), as the homepage
* tool itself requires ("Do it only after the owner has accepted");
* - DIR is a clean clone of the homepage repo at its origin/main, which does
* not yet record release G.
* pin:
* - the homepage repo's origin/main has G as gridatlas' operative release
* (the label PR is merged);
* - every one of the seven bundle files at that commit hashes to the pin
* (re-read through the GitHub API, the same check import_homepage_owner.py makes);
* - DOMAIN is a clean sparse clone of globalgrid2050 whose sparse set
* includes catalogue/, at its origin/main.
*
* WHAT IT DOES
* label: branch gridatlas-<version>; `python scripts/release_gridatlas.py release
* G <version> --published-at <time the pointer moved>`; the homepage CI
* checks (validate, fallback rebuild idempotent, unittest, node --check,
* fetch_active_pages --check); one commit; --push: push and a DRAFT PR.
* pin: branch homepage-gridatlas-<version>; writes catalogue/homepage-owner.json
* from `python scripts/release_gridatlas.py pin origin/main`; one commit;
* --push: push and a DRAFT PR. The restore point (homepage_vNNN.html and its
* metrics, homepage_versions/README.md) is the domain's own rule: dispatch
* homepage-restore-point-check.yml and add the snapshot to the same branch
* before the PR leaves draft. The script prints the commands.
* deploy: reports deploy-pages.yml for globalgrid2050 main's head
* (merging the pin pushes catalogue/** to main, which triggers it);
* --dispatch starts it when it did not run.
*
* Rollback of the label: in the homepage repo,
* python scripts/releases.py promote gridatlas <previous release id> --reason "..."
* then pin again (6b) and deploy (6c). Earlier releases are never deleted.
*/
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { parseArgs } from './lib.mjs';
import {
GRIDATLAS, HOMEPAGE, DOMAIN, DOMAIN_DEPLOY_WORKFLOW, LIVE_BYTES_WORKFLOW, gh, ghFile, ghHeadSha,
workflowRuns, dispatchWorkflow, readAcceptance, cutAtUtc, openDraftPr
} from './flow-lib.mjs';
const TOOL = 'homepage-bump';
const die = (m) => { console.error(`${TOOL}: STOP: ${m}`); process.exit(1); };
const ok = (m) => console.log(` OK ${m}`);
const sub = process.argv[2];
if (!['label', 'pin', 'deploy'].includes(sub)) die('usage: homepage-bump.mjs label|pin|deploy [options] (see the header)');
let args;
try {
args = parseArgs(process.argv.slice(3), {
homepage: {}, domain: {}, generation: {}, description: {}, 'published-at': {}, push: { bool: true },
dispatch: { bool: true }, 'skip-acceptance': { bool: true }, rehearsal: { bool: true }
});
} catch (error) { die(error.message); }
const sh = (cmd, argv, cwd, opts = {}) => {
const r = spawnSync(cmd, argv, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, ...opts });
if (r.error) die(`${cmd}: ${r.error.message}`);
if (r.status !== 0 && !opts.allowFail) die(`${cmd} ${argv.join(' ')} (in ${cwd}) exit ${r.status}\n${r.stdout}${r.stderr}`);
return r;
};
const gitIn = (dir, ...a) => sh('git', a, dir).stdout.trim();
const sha256 = (b) => createHash('sha256').update(b).digest('hex');
function cleanAtOriginMain(dir, name) {
if (!dir || !fs.existsSync(path.join(dir, '.git'))) die(`--${name} must be a clone of the ${name} repository`);
sh('git', ['fetch', '-q', 'origin', 'main'], dir);
if (gitIn(dir, 'status', '--porcelain=v1')) die(`${dir} is not clean`);
const head = gitIn(dir, 'rev-parse', 'HEAD'), main = gitIn(dir, 'rev-parse', 'origin/main');
if (head !== main) die(`${dir} HEAD ${head.slice(0, 12)} is not origin/main ${main.slice(0, 12)} (git switch --detach origin/main)`);
return main;
}
/** The gridatlas commit that last moved atlas/current.json, and when. */
function pointerCommit() {
const [c] = gh(`repos/${GRIDATLAS}/commits?path=atlas/current.json&sha=main&per_page=1`);
return { sha: c.sha, at: c.commit.committer.date };
}
function liveBytesPassed(sha) {
for (const run of workflowRuns(GRIDATLAS, LIVE_BYTES_WORKFLOW, { headSha: sha, perPage: 10 })) {
const job = (gh(`repos/${GRIDATLAS}/actions/runs/${run.id}/jobs?per_page=50`).jobs || []).find(j => j.name === 'live-bytes');
if (job?.status === 'completed') return { ok: job.conclusion === 'success', url: job.html_url, conclusion: job.conclusion };
}
return { ok: false, url: null, conclusion: 'not run' };
}
function homepageGridatlas(text) {
return JSON.parse(text).entities.find(e => e.id === 'gridatlas');
}
/* ------------------------------------------------------------------ label */
if (sub === 'label') {
let G, version, pc, headLb = { url: 'rehearsal' };
if (args.rehearsal) {
/* Everything below the gridatlas checks, for a generation that is not live yet: the homepage tool runs with
--offline, nothing is pushed. */
if (args.push) die('--rehearsal never pushes');
G = args.generation || die('--rehearsal needs --generation');
const m = JSON.parse(ghFile(GRIDATLAS, 'main', `atlas/manifests/${G}-composition.json`) || die(`${G} has no manifest on main`));
version = m.composition_version;
pc = { sha: ghHeadSha(GRIDATLAS, 'main'), at: new Date().toISOString() };
console.log(`\n== REHEARSAL for ${G} (${version}): gridatlas live, live-bytes and acceptance NOT checked`);
} else {
const live = JSON.parse(ghFile(GRIDATLAS, 'main', 'atlas/current.json'));
G = args.generation || String(live.generation);
version = live.composition_version;
console.log(`\n== gridatlas: ${G}`);
if (String(live.generation) !== G) die(`gridatlas main serves ${live.generation}, not ${G}`);
ok(`main serves ${G} (${version})`);
pc = pointerCommit();
const lb = liveBytesPassed(pc.sha);
// The live-bytes run of a later push also proves these bytes (the pointer has not moved since).
headLb = lb.ok ? lb : liveBytesPassed(ghHeadSha(GRIDATLAS, 'main'));
if (!headLb.ok) die(`live-bytes has not passed for ${pc.sha.slice(0, 12)} or main's head (${lb.conclusion}): node tools/release/check-live.mjs --wait`);
ok(`live-bytes PASS ${headLb.url}`);
if (!args['skip-acceptance']) {
const a = readAcceptance(G, { since: cutAtUtc(G) || undefined });
if (a.state !== 'accepted') die(`${G} has no owner acceptance on GitHub (${a.state}); pass --skip-acceptance only for a generation released before acceptance was recorded there`);
ok(`accepted by ${a.by} ${a.url}`);
}
}
console.log(`\n== ${HOMEPAGE}`);
const dir = path.resolve(args.homepage || die('--homepage DIR is required'));
cleanAtOriginMain(dir, 'homepage');
const entity = homepageGridatlas(fs.readFileSync(path.join(dir, 'data/homepage.json'), 'utf8'));
if (entity.releases.some(r => r.id === G)) die(`the homepage already records ${G} (operative: ${entity.operative_release_id})`);
ok(`homepage operative release ${entity.operative_release_id}; ${G} not yet recorded`);
const publishedAt = args['published-at'] || pc.at.replace(/:\d\d(\.\d+)?Z$/, ':00Z');
const branch = args.rehearsal ? `rehearsal/gridatlas-${version}` : `gridatlas-${version}`;
sh('git', ['switch', '-q', '-c', branch], dir);
const rel = ['scripts/release_gridatlas.py', 'release', G, version, '--published-at', publishedAt, '--source-ref', `https://github.com/${GRIDATLAS}/commit/${pc.sha}`];
if (args.description) rel.push('--description', args.description);
if (args.rehearsal) rel.push('--offline', '--archive-url', `https://ventusltd.github.io/gridatlas/atlas/v/${G}/`);
console.log(sh('python3', rel, dir).stdout.trim());
const indexOnce = sha256(fs.readFileSync(path.join(dir, 'index.html')));
for (const [cmd, a] of [['python3', ['scripts/releases.py', 'validate']], ['python3', ['scripts/build_homepage_fallback.py']],
['python3', ['-m', 'unittest', 'discover', '-s', 'tests']],
['node', ['--check', 'assets/versioned-homepage.js']], ['python3', ['scripts/fetch_active_pages.py', '--check']]]) {
sh(cmd, a, dir); ok(`${cmd} ${a.join(' ')}`);
}
if (sha256(fs.readFileSync(path.join(dir, 'index.html'))) !== indexOnce) die('build_homepage_fallback.py is not idempotent on the new data');
ok('fallback index.html rebuild is idempotent');
const after = homepageGridatlas(fs.readFileSync(path.join(dir, 'data/homepage.json'), 'utf8'));
if (after.operative_release_id !== G) die(`after the tool, the operative release is ${after.operative_release_id}`);
const label = after.releases.find(r => r.id === G).label;
sh('git', ['add', '-A'], dir);
sh('git', ['commit', '-q', '-m', `homepage: GridAtlas ${version} (${G}) is live: "${label}"`], dir);
ok(`committed ${gitIn(dir, 'rev-parse', '--short', 'HEAD')} on ${branch}: ${gitIn(dir, 'diff', '--stat', 'origin/main', 'HEAD').split('\n').pop().trim()}`);
if (args.push) {
sh('git', ['push', '-u', 'origin', branch], dir);
const pr = openDraftPr({ repo: HOMEPAGE, head: branch, title: `homepage: GridAtlas ${version} on the homepage (${label})`,
body: `GridAtlas ${G} (${version}) is live on gridatlas main (${pc.sha}) and live-bytes passed (${headLb.url}).\n\nGenerated by tools/release/homepage-bump.mjs label in ${GRIDATLAS}. Merge once "Homepage PR checks" passes, then run \`homepage-bump.mjs pin\`.\n` });
ok(`draft PR ${pr.html_url}`);
} else console.log(`\nnot pushed: git -C ${dir} push -u origin ${branch}, then open a draft PR in ${HOMEPAGE}`);
process.exit(0);
}
/* -------------------------------------------------------------------- pin */
if (sub === 'pin') {
const home = path.resolve(args.homepage || die('--homepage DIR is required'));
const dom = path.resolve(args.domain || die('--domain DIR is required'));
let pin, version;
if (args.rehearsal) {
/* Pin the local label commit (HEAD of --homepage) instead of origin/main; it is not on GitHub, so the seven
hashes are taken from the local blobs. Nothing is pushed. */
if (args.push) die('--rehearsal never pushes');
if (gitIn(home, 'status', '--porcelain=v1')) die(`${home} is not clean`);
const entity = homepageGridatlas(gitIn(home, 'show', 'HEAD:data/homepage.json'));
const G = entity.operative_release_id;
version = JSON.parse(ghFile(GRIDATLAS, 'main', `atlas/manifests/${G}-composition.json`)).composition_version;
pin = JSON.parse(sh('python3', ['scripts/release_gridatlas.py', 'pin', 'HEAD'], home).stdout);
console.log(`\n== REHEARSAL: pinning local ${pin.commit.slice(0, 12)} (operative ${G}); gridatlas live and GitHub re-read NOT checked`);
} else {
const homeMain = cleanAtOriginMain(home, 'homepage');
const live = JSON.parse(ghFile(GRIDATLAS, 'main', 'atlas/current.json'));
version = live.composition_version;
const entity = homepageGridatlas(gitIn(home, 'show', 'origin/main:data/homepage.json'));
if (entity.operative_release_id !== String(live.generation))
die(`homepage origin/main makes ${entity.operative_release_id} operative, but gridatlas serves ${live.generation}: merge the label PR first`);
ok(`homepage ${homeMain.slice(0, 12)} makes ${live.generation} operative`);
pin = JSON.parse(sh('python3', ['scripts/release_gridatlas.py', 'pin', 'origin/main'], home).stdout);
for (const [name, digest] of Object.entries(pin.files)) {
const served = ghFile(HOMEPAGE, pin.commit, name);
if (served === null || sha256(Buffer.from(served, 'utf8')) !== digest) die(`${name} at ${pin.commit} does not hash to the pin`);
}
ok(`pin ${pin.commit.slice(0, 12)}: 7 files re-read from GitHub and hash-identical`);
}
const sparse = sh('git', ['sparse-checkout', 'list'], dom, { allowFail: true });
if (sparse.status !== 0 || !/^\/?catalogue\/?$/m.test(sparse.stdout)) die(`${dom} must be a sparse clone of ${DOMAIN} whose sparse set includes catalogue/`);
cleanAtOriginMain(dom, 'domain');
const pinPath = path.join(dom, 'catalogue/homepage-owner.json');
const old = JSON.parse(fs.readFileSync(pinPath, 'utf8'));
if (old.commit === pin.commit) die(`the domain already pins ${pin.commit}`);
const branch = `${args.rehearsal ? 'rehearsal/' : ''}homepage-gridatlas-${version}`;
sh('git', ['switch', '-q', '-c', branch], dom);
fs.writeFileSync(pinPath, `${JSON.stringify(pin, null, 2)}\n`);
sh('git', ['add', 'catalogue/homepage-owner.json'], dom);
sh('git', ['commit', '-q', '-m', `homepage: promote owner bundle with GridAtlas ${version}`], dom);
ok(`committed the pin on ${branch} (${old.commit.slice(0, 12)} -> ${pin.commit.slice(0, 12)})`);
console.log(`\nrestore point (homepage_versions/README.md), before the PR leaves draft:\n` +
` gh api -X POST repos/${DOMAIN}/actions/workflows/homepage-restore-point-check.yml/dispatches -f ref=main\n` +
` then add the next homepage_versions/homepage_vNNN.html + -metrics.json + README entry to ${branch}`);
if (args.push) {
sh('git', ['push', '-u', 'origin', branch], dom);
const pr = openDraftPr({ repo: DOMAIN, head: branch, title: `homepage: promote owner bundle with GridAtlas ${version}`,
body: `Pins ${HOMEPAGE}@${pin.commit} (GridAtlas ${version} operative). The seven SHA-256s were re-read from GitHub.\n\nBefore merge: the restore-point snapshot. Merging pushes catalogue/** to main and triggers deploy-pages.yml.\n` });
ok(`draft PR ${pr.html_url}`);
}
process.exit(0);
}
/* ----------------------------------------------------------------- deploy */
const head = ghHeadSha(DOMAIN, 'main');
const pinText = ghFile(DOMAIN, 'main', 'catalogue/homepage-owner.json');
console.log(`globalgrid2050 main ${head.slice(0, 12)} pins ${JSON.parse(pinText).commit.slice(0, 12)}`);
const runs = workflowRuns(DOMAIN, DOMAIN_DEPLOY_WORKFLOW, { branch: 'main', perPage: 5 });
const forHead = runs.find(r => r.head_sha === head);
if (forHead) {
console.log(`${DOMAIN_DEPLOY_WORKFLOW}: ${forHead.status} ${forHead.conclusion || ''} ${forHead.html_url}`);
process.exit(forHead.conclusion === 'success' ? 0 : forHead.status === 'completed' ? 1 : 3);
}
console.log(`${DOMAIN_DEPLOY_WORKFLOW} has no run for main's head (latest: ${runs[0]?.head_sha?.slice(0, 12) || 'none'} ${runs[0]?.conclusion || ''})`);
if (args.dispatch) { dispatchWorkflow(DOMAIN, DOMAIN_DEPLOY_WORKFLOW, 'main'); console.log('dispatched'); }
process.exit(3);GridAtlas — Release
A JavaScript module in the tools folder that derives current (`deriveCurrent`), cleans tree (`cleanTree`) and runs gates (`runGates`), using SHA-256.
automationgridatlas / tools/release/lib.mjs · lines 1–213 of 213 · pattern sha256File (shared by 4 files)
- What it does
- It loads data. Defines 23 functions or classes, including registeredLoaderOf, pointerSlots, die, parseArgs, run. 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.
- Downstream impact
- Used directly by 18 files: Build (gridatlas); Acceptance (gridatlas); Check Live (gridatlas); Check Served (gridatlas); and 14 more. Reached from 15 other entry points, including GridAtlas Cartridge Proof Workflow (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas); GridAtlas Verify Live Workflow (gridatlas).
- What it achieves
- It parses args (`parseArgs`), reads text (`readText`) and derives current (`deriveCurrent`). Shared helpers for `tools/release/release-generation.mjs` and `tools/release/rollback-generation.mjs`.
- Why it matters
- Imported by 8 files, including Build, Acceptance and Loader Swap. Run by 8 workflows and scripts, including Check Live, Check Served and Cut Grid Explorer. Checked by 2 tests, including Flow Test.
- Application
- gridatlas · tools/release · JavaScript module
- Uses
- GridAtlas — Scope (script call), Data Contract Parity Proof (script call), Loop (script call), Verify Compose (script call), Run Current (script call), GridAtlas Rollback (script call), node:fs, node:path, node:child_process, node:crypto, node:url
- Used by
- imported by Build (import), imported by Acceptance (import), run by Check Live (script call), run by Check Served (script call), run by Cut Grid Explorer (script call), run by Flow Lib (script call), imported by Flow Test (import), run by Grid Explorer Proof (script call), and 10 more
- Produces
- ROOT, MANIFEST_ONLY_KEYS, POINTER_FILES, LOADER_FILE, registeredLoaderOf, pointerSlots, PARITY_PROOF, die, parseArgs, run, git, gitOk
- Defines here
- registeredLoaderOf, pointerSlots, die, parseArgs, run, git, gitOk, gitBlob, sha256, sha256File, readText, exists, deriveCurrent, rerootForPreview, cleanTree, changedPaths, isTracked, parityFailRows, runGates, record, printGates, commitWithMessage, trailerBlock
- 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/lib.mjs:1-213 · blob ea77ddffe77046731f57fd8c1e904a47cc3ac561 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
* Shared helpers for tools/release/release-generation.mjs and
* tools/release/rollback-generation.mjs.
*
* Both scripts automate what was done by hand for the 202610270024 rehearsal
* and the 202610281340 (Build L3) release, recorded in
* docs/lightning/hardening-20261026/evidence/release-rehearsal-E/RELEASE-COMMANDS.md.
* They never push, never open a PR and never touch atlas/releases/**. They
* work in whatever checkout they live in, so run them from a worktree.
*/
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';
import { ATLAS_LOADERS } from '../scope/lib.mjs';
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
/* The manifest keys that describe the CUT rather than the composition. The
rehearsal deleted exactly these six and wrote the rest with a one-space
indent and a trailing newline; L3's live atlas/current.json is byte-identical
to that derivation of its manifest. */
export const MANIFEST_ONLY_KEYS = Object.freeze([
'parent_generation', 'version', 'cut_at_utc', 'note', 'acceptance', 'candidate_status'
]);
/* The only two files a release (or its revert) may change... */
export const POINTER_FILES = Object.freeze(['atlas/current.json', 'STATE.md']);
/* ...plus the live loader, when and only when the generation going live is
served by a different registered loader than the live one (loader v2 for
the modular lightning generations, docs/LIGHTNING-CARTRIDGE.md). The
loader then moves in the release commit itself, so reverting that one
commit restores all three files byte for byte. */
export const LOADER_FILE = 'atlas/index.html';
/** The name of the registered loader (tools/scope/lib.mjs ATLAS_LOADERS)
whose payload is byte-identical to buffer, and the slots it supports. */
export function registeredLoaderOf(buffer) {
if (!buffer) return null;
const digest = sha256(Buffer.from(buffer.toString('binary').replace(/\r\n/g, '\n'), 'binary'));
for (const [name, loader] of Object.entries(ATLAS_LOADERS)) {
const payload = fs.readFileSync(path.join(ROOT, loader.payload));
if (sha256(Buffer.from(payload.toString('binary').replace(/\r\n/g, '\n'), 'binary')) === digest) return { name, slots: loader.slots };
}
return null;
}
/** The slot types the ordered cartridges of a pointer use. */
export function pointerSlots(pointer) {
const byId = new Map((pointer.cartridges || []).map(c => [c.id, c]));
return [...new Set((pointer.cartridge_order || []).map(id => byId.get(id)?.slot))].filter(Boolean).sort();
}
/* The rows of 202609012214-data-contract-parity that fail on every commit
since before Lightning. They are reported, never hidden: the gate is that a
release adds no FAIL row that the pre-release tree did not already have. */
export const PARITY_PROOF = 'tools/proofs/202609012214-data-contract-parity.proof.mjs';
export function die(tool, message) {
console.error(`${tool}: STOP: ${message}`);
process.exit(1);
}
export function parseArgs(argv, spec) {
const out = {};
for (const [name, def] of Object.entries(spec)) out[name] = def.multi ? [] : (def.default ?? null);
for (let i = 0; i < argv.length; i += 1) {
const raw = argv[i];
if (!raw.startsWith('--')) throw new Error(`unexpected argument ${raw}`);
const name = raw.slice(2);
const def = spec[name];
if (!def) throw new Error(`unknown flag ${raw}`);
if (def.bool) { out[name] = true; continue; }
const value = argv[i + 1];
if (value === undefined || value.startsWith('--')) throw new Error(`${raw} needs a value`);
i += 1;
if (def.multi) out[name].push(value); else out[name] = value;
}
return out;
}
export function run(cmd, args, { cwd = ROOT, allowFail = false, input } = {}) {
const r = spawnSync(cmd, args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, input });
if (r.error) throw r.error;
if (r.status !== 0 && !allowFail) {
throw new Error(`${cmd} ${args.join(' ')} exited ${r.status}\n${r.stdout}${r.stderr}`);
}
return { status: r.status, stdout: r.stdout, stderr: r.stderr, out: `${r.stdout}${r.stderr}` };
}
export const git = (...args) => run('git', args).stdout.trim();
export const gitOk = (...args) => run('git', args, { allowFail: true }).status === 0;
export function gitBlob(rev, relative) {
const r = spawnSync('git', ['show', `${rev}:${relative}`], { cwd: ROOT, encoding: 'buffer', maxBuffer: 256 * 1024 * 1024 });
return r.status === 0 ? r.stdout : null;
}
export const sha256 = (buffer) => createHash('sha256').update(buffer).digest('hex');
export const sha256File = (relative) => sha256(fs.readFileSync(path.join(ROOT, relative)));
export const readText = (relative) => fs.readFileSync(path.join(ROOT, relative), 'utf8');
export const exists = (relative) => fs.existsSync(path.join(ROOT, relative));
/** atlas/current.json exactly as the rehearsal wrote it from G's manifest. */
export function deriveCurrent(manifestText) {
const manifest = JSON.parse(manifestText);
for (const key of MANIFEST_ONLY_KEYS) delete manifest[key];
return `${JSON.stringify(manifest, null, 1)}\n`;
}
/** The pinned preview route atlas/v/G/current.json is the same composition
with every "./" or "../" relative reference re-rooted two levels up. */
export function rerootForPreview(currentText) {
return currentText.replace(/": "(\.\/|\.\.\/)/g, '": "../../');
}
export function cleanTree() {
return run('git', ['status', '--porcelain=v1', '--untracked-files=all']).stdout.trim() === '';
}
export function changedPaths() {
return run('git', ['status', '--porcelain=v1', '--untracked-files=all']).stdout
.split('\n').filter(Boolean).map(line => line.slice(3)).sort();
}
export function isTracked(relative) {
return gitOk('ls-files', '--error-unmatch', '--', relative);
}
/* ---------------------------------------------------------------- gates */
/** FAIL rows of the data-contract parity proof, parsed from its FAILURES
block. A non-zero exit with no FAILURES block is itself a FAIL row, so a
proof that crashes cannot read as "no new failures". */
export function parityFailRows() {
const r = run('node', [PARITY_PROOF], { allowFail: true });
const lines = r.out.split('\n');
const start = lines.findIndex(l => l.trim() === 'FAILURES');
let rows = start === -1 ? [] : lines.slice(start + 1).map(l => l.trim()).filter(Boolean);
if (r.status !== 0 && rows.length === 0) rows = [`parity proof exited ${r.status} without a FAILURES block`];
return { status: r.status, rows, out: r.out };
}
/**
* Every gate the hand release ran, in the same order. Returns rows of
* { gate, ok, detail } and the full log text; never throws on a red gate.
*
* expectGeneration verify-compose must report this generation
* proofs generation-matched proofs to run directly
* parityBaseline FAIL rows the pre-release tree already had
* rollbackTo generation for `tools/rollback.mjs --dry-run` (null skips)
*/
export function runGates({ expectGeneration, proofs = [], parityBaseline = [], rollbackTo = null }) {
const rows = [];
let log = '';
const record = (gate, ok, detail, out) => {
rows.push({ gate, ok, detail });
log += `\n### ${gate} -> ${ok ? 'PASS' : 'FAIL'} ${detail}\n${out ?? ''}`;
};
const lint = run('node', ['tools/scope/loop.mjs', 'lint'], { allowFail: true });
record('loop.mjs lint', lint.status === 0, lint.out.trim().split('\n').pop(), lint.out);
const state = run('node', ['tools/scope/loop.mjs', 'state', '--stdout'], { allowFail: true });
const stateOk = state.status === 0 && exists('STATE.md') && state.stdout === readText('STATE.md');
record('loop.mjs state --stdout == STATE.md', stateOk, stateOk ? 'STATE_PARITY_OK' : 'STATE.md differs from the generator', state.stderr);
const compose = run('node', ['tools/scope/verify-compose.mjs'], { allowFail: true });
let composeOk = compose.status === 0;
let composeDetail = `exit ${compose.status}`;
try {
const parsed = JSON.parse(compose.stdout.trim().split('\n').pop());
composeOk = composeOk && parsed.composition === 'PASS' && parsed.generation === expectGeneration;
composeDetail = `composition=${parsed.composition} generation=${parsed.generation}`;
} catch { composeOk = false; }
record('verify-compose', composeOk, composeDetail, compose.out);
const current = run('node', ['tools/proofs/run-current.mjs'], { allowFail: true });
record('run-current', current.status === 0, current.out.trim().split('\n').pop(), current.out);
for (const proof of proofs) {
const r = run('node', [proof], { allowFail: true });
record(proof, r.status === 0, `exit ${r.status}`, r.out);
}
const parity = parityFailRows();
const added = parity.rows.filter(row => !parityBaseline.includes(row));
record('data-contract parity (no new FAIL rows)', added.length === 0,
`${parity.rows.length} FAIL row(s), ${added.length} new${added.length ? `: ${added.join(' | ')}` : ''}`, parity.out);
if (rollbackTo) {
const rb = run('node', ['tools/rollback.mjs', '--to', rollbackTo, '--reason', 'release readiness', '--dry-run'], { allowFail: true });
record(`rollback.mjs --to ${rollbackTo} --dry-run`, rb.status === 0, `exit ${rb.status}`, rb.out);
}
return { rows, log, parityRows: parity.rows };
}
export function printGates(rows) {
const width = Math.max(...rows.map(r => r.gate.length));
for (const r of rows) console.log(` ${r.ok ? 'PASS' : 'FAIL'} ${r.gate.padEnd(width)} ${r.detail}`);
}
export function commitWithMessage(message) {
run('git', ['commit', '-q', '-F', '-'], { input: message });
return git('rev-parse', 'HEAD');
}
export function trailerBlock(trailers) {
return trailers.length ? `\n\n${trailers.join('\n')}` : '';
}Loader Swap
A JavaScript module in the tools folder of GridAtlas that works with cli check (`cliCheck`) and cli release (`cliRelease`), using SHA-256.
automationgridatlas / tools/release/loader-swap.mjs · lines 1–153 of 153 · Entry point · pattern abort (shared by 9 files)
- What it does
- It loads data. Defines 7 functions or classes, including proveLoaderSwap, die, ok, cliCheck, cliRelease. Uses libraries node:fs, node:path, node:url. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file current.json; command-line arguments.
- Downstream impact
- Used directly by 3 files: CI PR Gate (gridatlas); Loader Swap Test (gridatlas); Rollback Generation (gridatlas). Reached from 2 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Map Promotion Rehearsal (gridatlas).
- What it achieves
- It is built from the die step (`die`), the cli check helper (`cliCheck`) and the cli release helper (`cliRelease`). The live loader on its own: step 1 (and its rollback) of a two-step release of a generation whose own loader differs from the live one (`docs/RELEASE.md` "Loader first, then the pointer"; `docs/LIGHTNING-CARTRIDGE.md` "Cache window").
- Why it matters
- Imported by Rollback Generation. Run by CI PR Gate. Checked by Loader Swap Test.
- Application
- gridatlas · tools/release · JavaScript module
- Uses
- GridAtlas — Scope (import), Loader Composition (import), GridAtlas — Release (import), node:fs, node:path, node:url
- Used by
- run by CI PR Gate (script call), run by Loader Swap Test (script call), imported by Rollback Generation (import)
- Produces
- proveLoaderSwap
- Defines here
- proveLoaderSwap, die, ok, cliCheck, cliRelease, finish, 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/loader-swap.mjs:1-153 · blob 9aadce80f3ea03610aa64b57cb1304ca5060a1b5 · 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
/**
* The live loader on its own: step 1 (and its rollback) of a two-step release
* of a generation whose own loader differs from the live one (docs/RELEASE.md
* "Loader first, then the pointer"; docs/LIGHTNING-CARTRIDGE.md "Cache window").
*
* atlas/index.html may change WITHOUT atlas/current.json only when every one
* of these holds against the pointer that stays live:
* - the new loader is a REGISTERED loader (tools/scope/lib.mjs ATLAS_LOADERS);
* - it supports every slot the live pointer uses (so a loader rollback is
* refused while a generation that needs the newer loader is live: roll the
* pointer back first, then the loader);
* - run verbatim in node:vm (tools/proofs/loader-composition.mjs), it writes
* byte-for-byte the HTML, and byte-identical cartridge blobs, that the
* loader it replaces writes for the live pointer, and neither fails.
*
* node tools/release/loader-swap.mjs check [--base REV]
* HEAD's working-tree atlas/index.html against REV's (default origin/main),
* for the working-tree atlas/current.json. Used by tools/ci/pr-gate.mjs
* (loader-registry) when a PR changes atlas/index.html alone.
*
* node tools/release/loader-swap.mjs release --to v2 --authorised-by TEXT
* [--base origin/main] [--branch release/loader-<to>-<live gen>]
* [--trailer TEXT ...] [--report FILE] [--log FILE]
* Step 1: clean tree at --base; prove the swap; write
* atlas/index.html := the registered payload; every release gate
* (lint, state parity, verify-compose of the unchanged live generation,
* run-current, data-contract parity, loader-equivalence); one commit that
* changes atlas/index.html only, on a new local branch. Never pushes.
*
* Its revert is tools/release/rollback-generation.mjs --release-commit <sha>,
* which accepts a loader-only commit under the same proof.
*/
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { ATLAS_LOADERS } from '../scope/lib.mjs';
import { compose } from '../proofs/loader-composition.mjs';
import {
ROOT, LOADER_FILE, registeredLoaderOf, pointerSlots, parseArgs, run, git, gitOk, gitBlob, sha256,
cleanTree, changedPaths, runGates, printGates, parityFailRows, commitWithMessage, trailerBlock
} from './lib.mjs';
/** Prove that `toLoader` may replace `fromLoader` while `pointerText` stays
live. Pure apart from reading the working tree through compose(). */
export async function proveLoaderSwap({ fromLoader, toLoader, pointerText }) {
const reasons = [];
const from = registeredLoaderOf(fromLoader);
const to = registeredLoaderOf(toLoader);
let pointer;
try { pointer = JSON.parse(String(pointerText)); } catch (e) { return { ok: false, from, to, reasons: [`atlas/current.json unreadable: ${e.message}`] }; }
if (!to) reasons.push(`the new ${LOADER_FILE} is not a registered loader (tools/scope/lib.mjs ATLAS_LOADERS)`);
const slots = pointerSlots(pointer);
const missing = to ? slots.filter(s => !to.slots.includes(s)) : [];
if (missing.length) reasons.push(`loader ${to.name} cannot compose slot(s) ${missing.join(', ')} of the live ${pointer.generation}; roll the pointer back first, then the loader`);
let detail = '';
if (!reasons.length) {
const files = { 'atlas/current.json': String(pointerText) };
const a = await compose({ loaderHtml: String(fromLoader), route: 'atlas/', files });
const b = await compose({ loaderHtml: String(toLoader), route: 'atlas/', files });
if (a.failed) reasons.push(`the replaced loader${from ? ` (${from.name})` : ''} does not compose the live ${pointer.generation}: ${a.message.replace(/<[^>]+>/g, ' ').trim().slice(0, 200)}`);
if (b.failed) reasons.push(`loader ${to.name} does not compose the live ${pointer.generation}: ${b.message.replace(/<[^>]+>/g, ' ').trim().slice(0, 200)}`);
if (!a.failed && !b.failed) {
if (a.html !== b.html) reasons.push(`loader ${to.name} writes different HTML from ${from ? from.name : 'the replaced loader'} for the live ${pointer.generation}`);
const same = a.scripts.length === b.scripts.length && a.scripts.every((s, i) => s.id === b.scripts[i].id && s.url === b.scripts[i].url && s.source.equals(b.scripts[i].source));
if (!same) reasons.push(`loader ${to.name} hands different cartridge blobs from ${from ? from.name : 'the replaced loader'} for the live ${pointer.generation}`);
detail = `${a.scripts.length} cartridge blob(s), HTML ${a.html.length} B, identical`;
}
}
return { ok: reasons.length === 0, from, to, generation: pointer.generation, slots, reasons, detail };
}
const TOOL = 'loader-swap';
const die = (m) => { console.error(`${TOOL}: STOP: ${m}`); process.exit(1); };
const ok = (m) => console.log(` OK ${m}`);
async function cliCheck(argv) {
const args = parseArgs(argv, { base: { default: 'origin/main' } });
if (!gitOk('rev-parse', '--verify', '--quiet', `${args.base}^{commit}`)) die(`--base ${args.base} does not resolve`);
const fromLoader = gitBlob(args.base, LOADER_FILE);
const toLoader = fs.readFileSync(path.join(ROOT, LOADER_FILE));
const pointerText = fs.readFileSync(path.join(ROOT, 'atlas/current.json'), 'utf8');
const r = await proveLoaderSwap({ fromLoader, toLoader, pointerText });
const name = `${r.from?.name || 'unregistered'} -> ${r.to?.name || 'unregistered'}`;
if (!r.ok) { console.log(`FAIL loader-only change ${name}: ${r.reasons.join('; ')}`); process.exit(1); }
console.log(`PASS loader-only change ${name} for the live ${r.generation} (slots ${r.slots.join(', ')}): ${r.detail}`);
}
async function cliRelease(argv) {
const args = parseArgs(argv, {
to: {}, 'authorised-by': {}, base: { default: 'origin/main' }, branch: {}, trailer: { multi: true }, report: {}, log: {}
});
if (!args.to || !Object.hasOwn(ATLAS_LOADERS, args.to)) die(`--to must name a registered loader (${Object.keys(ATLAS_LOADERS).join(', ')})`);
if (!args['authorised-by']) die('--authorised-by is required');
const report = { tool: TOOL, mode: 'release', to: args.to, started_utc: new Date().toISOString() };
const finish = (code) => { report.exit = code; if (args.report) fs.writeFileSync(path.resolve(args.report), `${JSON.stringify(report, null, 1)}\n`); process.exit(code); };
console.log('\n== 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}`);
const fromLoader = gitBlob('HEAD', LOADER_FILE);
const toLoader = fs.readFileSync(path.join(ROOT, ATLAS_LOADERS[args.to].payload));
if (Buffer.compare(fromLoader, toLoader) === 0) die(`${LOADER_FILE} is already loader ${args.to}`);
const pointerText = gitBlob('HEAD', 'atlas/current.json').toString('utf8');
const proof = await proveLoaderSwap({ fromLoader, toLoader, pointerText });
Object.assign(report, { base: baseSha, live: proof.generation, from: proof.from?.name || null, proof });
if (!proof.ok) die(proof.reasons.join('; '));
ok(`${proof.from?.name} -> ${proof.to.name} composes the live ${proof.generation} byte for byte (${proof.detail})`);
const parityBaseline = parityFailRows().rows;
const branch = args.branch || `release/loader-${args.to}-${proof.generation}`;
if (gitOk('rev-parse', '--verify', '--quiet', `refs/heads/${branch}`)) die(`branch ${branch} already exists`);
run('git', ['switch', '-q', '-c', branch]);
const abort = () => { run('git', ['checkout', '-q', '--', LOADER_FILE], { allowFail: true }); run('git', ['switch', '-q', '--detach', baseSha]); run('git', ['branch', '-D', branch], { allowFail: true }); };
fs.writeFileSync(path.join(ROOT, LOADER_FILE), toLoader);
const changed = changedPaths();
if (JSON.stringify(changed) !== JSON.stringify([LOADER_FILE])) { abort(); die(`expected only ${LOADER_FILE} to change, got ${changed.join(', ')}`); }
console.log('\n== 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); }
run('git', ['add', '--', LOADER_FILE]);
const msg = `live loader ${proof.from.name} -> ${proof.to.name} (atlas/index.html only; the pointer stays ${proof.generation})\n\n` +
`Step 1 of a two-step release (docs/RELEASE.md "Loader first, then the pointer"): atlas/index.html := ${ATLAS_LOADERS[args.to].payload}.\n` +
`For the live ${proof.generation} it writes byte-for-byte the HTML and cartridge blobs ${proof.from.name} writes (tools/release/loader-swap.mjs, ${proof.detail}).\n` +
`Nothing else changes. Release the pointer only after check-served passes and at least 10 minutes have passed (the HTML cache window).\n` +
`Rollback: git revert this commit (tools/release/rollback-generation.mjs --release-commit <sha>), only while the live pointer composes under ${proof.from.name}.\n\n` +
`Authorised by: ${args['authorised-by']}${trailerBlock(args.trailer)}\n`;
report.commit = commitWithMessage(msg);
report.tree = git('rev-parse', 'HEAD^{tree}');
report.hashes = { before: sha256(fromLoader), after: sha256(toLoader) };
console.log(`\n ${LOADER_FILE} ${report.hashes.before} -> ${report.hashes.after}\n commit ${report.commit}\n\nLOADER RELEASE READY on branch ${branch} (not pushed).`);
finish(0);
}
if (import.meta.url === pathToFileURL(process.argv[1] || '').href) {
const [mode, ...rest] = process.argv.slice(2);
try {
if (mode === 'check') await cliCheck(rest);
else if (mode === 'release') await cliRelease(rest);
else die('usage: loader-swap.mjs check [--base REV] | release --to v2 --authorised-by TEXT [--base REV] [--branch NAME]');
} catch (e) { die(e.message); }
}