GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / tools/release

Release Generation and 1 more file

A JavaScript module in the tools folder of GridAtlas that checks prep (`checkPrep`), using SHA-256.

514 lines of JavaScript from gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 669 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Release Generation automation · gridatlas / tools/release/release-generation.mjs lines 1–367
  2. Release Status automation · gridatlas / tools/release/release-status.mjs lines 1–147

Release Generation

A JavaScript module in the tools folder of GridAtlas that checks prep (`checkPrep`), using SHA-256.

automationgridatlas / tools/release/release-generation.mjs · lines 1–367 of 367 · Entry point · pattern restore (shared by 8 files)

What it does
It lists and searches its content. Defines 6 functions or classes, including die, step, ok, finish, checkPrep. 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. Out: JSON file current.json.
Downstream impact
Used directly by 3 files: Loader Swap Test (gridatlas); Map Promotion Rehearsal (gridatlas); Release Accepted (gridatlas). Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It checks prep (`checkPrep`) and is built from the die step (`die`) and the step step (`step`). Release a published preview generation G to the live route.
Why it matters
Run by Map Promotion Rehearsal and Release Accepted. Checked by Loader Swap Test.
Application
gridatlas · tools/release · JavaScript module
Uses
GridAtlas — Release (import), GridAtlas — Index Page (estate URL), node:fs, node:path
Used by
run by Loader Swap Test (script call), run by Map Promotion Rehearsal (script call), run by Release Accepted (script call)
Produces
die, step, ok, finish, checkPrep, restore
Defines here
die, step, ok, finish, checkPrep, restore
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/release-generation.mjs:1-367 · blob 79488f292a75a02a19d39739c7294ef7a8a0667a · 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
/**
 * Release a published preview generation G to the live route.
 *
 *   node tools/release/release-generation.mjs --generation G --authorised-by "..." [options]
 *
 * This is the hand procedure of RELEASE-COMMANDS.md (rehearsal E, then the
 * 202610281340 Build L3 release, PR #49) as one checked script. It works in
 * the checkout it lives in, so run it from a fresh worktree of main:
 *
 *   git fetch origin && git worktree add --detach ../gridatlas-release origin/main
 *   cd ../gridatlas-release && node tools/release/release-generation.mjs --generation G ...
 *
 * WHAT IT DOES, IN ORDER
 *   1. Preconditions, all against committed bytes, nothing written:
 *      - the tree is clean and HEAD is exactly --base (default origin/main);
 *      - live (atlas/current.json) is the expected predecessor: --expect-live,
 *        which must also be the manifest's previous_generation;
 *      - G's preview files are present and committed: the composition
 *        manifest, atlas/v/G/{current.json,index.html}, every cartridge the
 *        manifest names (sha256 of the committed blob = the recorded digest),
 *        and a proof tools/proofs/G-<id>.proof.mjs for every cartridge cut at G;
 *      - atlas/v/G/current.json is the derived pointer re-rooted to ../../,
 *        i.e. the preview people tested is the composition that will go live;
 *      - G's proofs pass;
 *      - the loader: atlas/index.html == atlas/v/G/index.html, or G's own
 *        loader is a different REGISTERED loader that supports every slot G
 *        uses (loader v2 for a modular lightning generation); then the release
 *        commit also writes atlas/index.html := atlas/v/G/index.html.
 *   2. On a new branch, optional preparatory commits: --prep-commit <sha>
 *      (cherry-picked, e.g. retiring a workflow) and --prep-gate-kb <N> (raise
 *      the recorded cartridge ceiling in tools/scope/loop.mjs). Each must
 *      leave lint and STATE.md parity green and must not touch the pointer.
 *   3. atlas/current.json from G's manifest exactly as the rehearsal did
 *      (drop the six cut-only keys, JSON.stringify(m, null, 1) + "\n"), then
 *      `node tools/scope/loop.mjs state`. Only those two files may change.
 *   4. Every gate: lint, state parity, verify-compose (generation G),
 *      run-current, G's proofs, data-contract parity (no FAIL row the base
 *      did not already have), rollback.mjs --to <predecessor> --dry-run.
 *   5. The release commit (pointer + STATE.md only), then the hashes.
 *
 * If live is already G, it is a NO-OP release: every precondition and gate
 * still runs, the derived pointer must equal the live one byte for byte, and
 * nothing is committed. That is how the tooling is rehearsed on main.
 *
 * It never pushes, never opens a PR and never edits atlas/releases/**. The
 * owner's authorisation is recorded in the commit, not inferred.
 *
 * Options
 *   --generation G          12-digit preview generation to release (required)
 *   --authorised-by TEXT    who authorised it and where (required to commit)
 *   --expect-live P         the generation that must be live now (default: G's previous_generation)
 *   --base REV              HEAD must equal this (default origin/main)
 *   --branch NAME           default release/G-gridatlas-<composition_version>
 *   --title TEXT            commit subject after "G-gridatlas-vX: "
 *   --prep-commit SHA       cherry-pick as a preparatory commit (repeatable)
 *   --prep-gate-kb N        raise the cartridge ceiling to N kB as a preparatory commit
 *   --prep-gate-reason TEXT required with --prep-gate-kb (who decided, when)
 *   --trailer TEXT          appended to every commit message (repeatable)
 *   --check                 preconditions only; write nothing
 *   --allow-loader-follows  allow the loader to move in the release commit to one the live loader could not
 *                           stand in for (v1 -> v2): opens the HTML cache window; refused by default
 *   --no-commit             leave the release staged-but-uncommitted for inspection
 *   --report FILE           write a JSON report (hashes, gates) to FILE
 *   --log FILE              write the full gate output to FILE
 */

import fs from 'node:fs';
import path from 'node:path';
import {
  ROOT, POINTER_FILES, LOADER_FILE, registeredLoaderOf, pointerSlots, die as dieWith, parseArgs, run, git, gitOk, gitBlob, sha256, sha256File,
  readText, exists, deriveCurrent, rerootForPreview, cleanTree, changedPaths, isTracked,
  runGates, printGates, parityFailRows, commitWithMessage, trailerBlock
} from './lib.mjs';

const TOOL = 'release-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), {
    generation: {}, 'authorised-by': {}, 'expect-live': {}, base: { default: 'origin/main' },
    branch: {}, title: {}, 'prep-commit': { multi: true }, 'prep-gate-kb': {}, 'prep-gate-reason': {},
    trailer: { multi: true }, check: { bool: true }, 'no-commit': { bool: true },
    'allow-loader-follows': { bool: true }, report: {}, log: {}
  });
} catch (error) { die(error.message); }

const G = args.generation;
if (!G || !/^\d{12}$/.test(G)) die('--generation must be a 12-digit generation');
if (args['prep-gate-kb'] && !/^\d{3}$/.test(args['prep-gate-kb'])) die('--prep-gate-kb must be a 3-digit kB figure');
if (args['prep-gate-kb'] && !args['prep-gate-reason']) die('--prep-gate-kb needs --prep-gate-reason (the owner decision it records)');

const report = { tool: TOOL, generation: G, 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);
};

/* ------------------------------------------------------- 1. preconditions */
step('preconditions');
if (!cleanTree()) die(`working tree is not clean:\n${changedPaths().join('\n')}`);
ok('working tree clean');

if (!gitOk('rev-parse', '--verify', '--quiet', `${args.base}^{commit}`)) die(`--base ${args.base} does not resolve`);
const baseSha = git('rev-parse', `${args.base}^{commit}`);
const headSha = git('rev-parse', 'HEAD');
if (baseSha !== headSha) die(`HEAD ${headSha} is not ${args.base} ${baseSha} (fetch, and start from a fresh worktree of it)`);
report.base = { ref: args.base, sha: baseSha };
ok(`HEAD = ${args.base} = ${baseSha}`);

const liveText = gitBlob('HEAD', 'atlas/current.json');
if (!liveText) die('atlas/current.json is not committed at HEAD');
const live = JSON.parse(liveText.toString('utf8'));
report.live_before = live.generation;

const manifestRel = `atlas/manifests/${G}-composition.json`;
const previewPointerRel = `atlas/v/${G}/current.json`;
const previewLoaderRel = `atlas/v/${G}/index.html`;
for (const rel of [manifestRel, previewPointerRel, previewLoaderRel]) {
  if (!exists(rel) || !isTracked(rel)) die(`preview file ${rel} is missing or not committed`);
}
ok(`preview files committed: ${manifestRel}, ${previewPointerRel}, ${previewLoaderRel}`);

const manifestText = gitBlob('HEAD', manifestRel).toString('utf8');
const manifest = JSON.parse(manifestText);
if (manifest.generation !== G) die(`${manifestRel} declares generation ${manifest.generation}`);
if (manifest.composition_manifest !== `./manifests/${G}-composition.json`) die(`${manifestRel} composition_manifest is ${manifest.composition_manifest}`);
const rejected = String(manifest.candidate_status || '').startsWith('REJECTED')
  || String(manifest.acceptance?.golden_browser_verification || '').startsWith('REJECTED');
if (rejected) die(`${G} is marked REJECTED in its manifest; it is not a release candidate`);
ok(`manifest identity: generation ${G}, ${manifest.composition_version}`);

const noop = live.generation === G;
const predecessor = noop ? live.previous_generation : live.generation;
if (noop) {
  if (args['expect-live'] && args['expect-live'] !== G) die(`live is ${G}, not --expect-live ${args['expect-live']}`);
  ok(`live is already ${G}: NO-OP release (verify everything, commit nothing)`);
} else {
  const expected = args['expect-live'] || manifest.previous_generation;
  if (live.generation !== expected) die(`live is ${live.generation}, expected predecessor ${expected}`);
  if (manifest.previous_generation !== live.generation) die(`${G}'s previous_generation is ${manifest.previous_generation} but live is ${live.generation}; the manifest was cut against a different predecessor`);
  ok(`live = expected predecessor = ${live.generation} = ${G}.previous_generation`);
  if (!args.check && !args['no-commit'] && !args['authorised-by']) die('--authorised-by is required to commit a release');
}
report.predecessor = predecessor;

const derived = deriveCurrent(manifestText);
const previewPointer = gitBlob('HEAD', previewPointerRel).toString('utf8');
if (rerootForPreview(derived) !== previewPointer) die(`${previewPointerRel} is not the derived pointer re-rooted to ../../; the preview that was tested is not what would go live`);
ok(`${previewPointerRel} == derived pointer re-rooted (the tested preview is the release)`);
if (noop && derived !== liveText.toString('utf8')) die('live is G but the pointer derived from its manifest is not byte-identical to atlas/current.json');
if (noop) ok('derived pointer is byte-identical to the live atlas/current.json');

const cutHere = [];
for (const cartridge of manifest.cartridges || []) {
  const rel = path.posix.join('atlas', cartridge.path);
  const blob = gitBlob('HEAD', rel);
  if (!blob) die(`${cartridge.id}: ${rel} is not committed`);
  if (sha256(blob) !== cartridge.sha256) die(`${cartridge.id}: committed ${rel} does not hash to ${cartridge.sha256}`);
  if (cartridge.generation === G) cutHere.push(cartridge.id);
}
ok(`${(manifest.cartridges || []).length} cartridges: committed blobs hash to the recorded sha256`);
if (!cutHere.length) die(`no cartridge in ${manifestRel} was cut at ${G}`);

const proofs = cutHere.map(id => `tools/proofs/${G}-${id}.proof.mjs`);
for (const proof of proofs) {
  if (!exists(proof) || !isTracked(proof)) die(`${proof} is missing or not committed`);
  const r = run('node', [proof], { allowFail: true });
  if (r.status !== 0) die(`${proof} fails on the preview route:\n${r.out}`);
  ok(`${proof} passes (preview route)`);
}

const loader = gitBlob('HEAD', LOADER_FILE);
const previewLoader = gitBlob('HEAD', previewLoaderRel);
if (!loader || !previewLoader) die(`${LOADER_FILE} or ${previewLoaderRel} is not committed`);
const previewRegistered = registeredLoaderOf(previewLoader);
if (!previewRegistered) die(`${previewLoaderRel} is not a registered loader (tools/scope/lib.mjs ATLAS_LOADERS)`);
const missingSlots = pointerSlots(manifest).filter(slot => !previewRegistered.slots.includes(slot));
if (missingSlots.length) die(`${previewLoaderRel} (loader ${previewRegistered.name}) cannot compose slot(s) ${missingSlots.join(', ')} that ${G} uses`);
const loaderMoves = Buffer.compare(loader, previewLoader) !== 0;
const RELEASE_FILES = loaderMoves ? [...POINTER_FILES, LOADER_FILE] : [...POINTER_FILES];
report.loader = { live: registeredLoaderOf(loader)?.name || null, preview: previewRegistered.name, moves: loaderMoves };
if (loaderMoves && noop) die(`live is ${G} but ${LOADER_FILE} is not ${previewLoaderRel}`);
// A loader that moves WITH the pointer to one the live loader could not compose (v1 -> v2 for a modular G) opens the HTML
// cache window (docs/RELEASE.md "Loader first, then the pointer"): a browser holding the cached old loader reads the new
// pointer and fails closed for up to ~10 minutes. Ship the loader first (tools/release/loader-swap.mjs release), wait,
// then release the pointer; a one-step release needs --allow-loader-follows (an explicit owner decision).
const liveRegistered = registeredLoaderOf(loader);
const liveMissing = liveRegistered ? pointerSlots(manifest).filter(slot => !liveRegistered.slots.includes(slot)) : pointerSlots(manifest);
report.loader.live_missing_slots = liveMissing;
if (loaderMoves && liveMissing.length && !args['allow-loader-follows']) {
  die(`the live loader (${report.loader.live || 'unregistered'}) cannot compose slot(s) ${liveMissing.join(', ')} that ${G} uses: release the loader first ` +
    `(node tools/release/loader-swap.mjs release --to ${previewRegistered.name} …), wait for check-served plus 10 minutes, then release ${G}; ` +
    'or pass --allow-loader-follows to accept the cache window (docs/RELEASE.md)');
}
if (loaderMoves) ok(`LOADER_FOLLOWS ${LOADER_FILE} (${report.loader.live}) -> ${previewLoaderRel} (${previewRegistered.name}, sha256 ${sha256(previewLoader).slice(0, 16)}…) in the release commit`);
else ok(`LOADER_IDENTICAL ${LOADER_FILE} == ${previewLoaderRel} (${previewRegistered.name}, sha256 ${sha256(loader).slice(0, 16)}…)`);

const before = Object.fromEntries(RELEASE_FILES.map(f => [f, sha256File(f)]));
report.before = before;

/* --prep-gate-kb is validated with the preconditions (so --check runs it too) and before any branch exists:
   a redundant or malformed ceiling must not leave a stray branch with HEAD on it. */
if (args['prep-gate-kb']) {
  const text = readText('tools/scope/loop.mjs');
  const sizes = [...text.matchAll(/fs\.statSync\(cartridgePath\)\.size <= (\d{3})_000/g)];
  if (sizes.length !== 1) die(`tools/scope/loop.mjs: expected exactly one cartridge ceiling, found ${sizes.length}`);
  if (Number(args['prep-gate-kb']) <= Number(sizes[0][1])) die(`--prep-gate-kb ${args['prep-gate-kb']} does not raise the current ${sizes[0][1]} kB ceiling`);
  if ([...text.matchAll(/exceeds the \d{3} kB recorded ceiling \([^)`]*\)/g)].length !== 1) die('tools/scope/loop.mjs: ceiling message not found exactly once');
  ok(`--prep-gate-kb ${args['prep-gate-kb']} raises the current ${sizes[0][1]} kB ceiling`);
}

if (args.check) {
  console.log(`\nCHECK PASS: ${G} is releasable on ${baseSha.slice(0, 7)} (live ${live.generation}). Nothing written.`);
  finish(0);
}

/* Parity FAIL rows on the untouched tree: the release must not add any. */
const parityBaseline = parityFailRows().rows;
report.parity_baseline = parityBaseline;

/* ------------------------------------------------------------- no-op path */
if (noop) {
  step('gates (no-op: live tree as is)');
  const gates = runGates({ expectGeneration: G, proofs, parityBaseline, rollbackTo: predecessor });
  printGates(gates.rows);
  if (args.log) fs.writeFileSync(path.resolve(args.log), gates.log);
  report.gates = gates.rows;
  report.after = Object.fromEntries(POINTER_FILES.map(f => [f, sha256File(f)]));
  step('hashes');
  for (const f of POINTER_FILES) console.log(`  ${f.padEnd(20)} ${before[f]}  (unchanged)`);
  console.log(`  derived pointer      ${sha256(derived)}`);
  if (!cleanTree()) die('a gate wrote to the tree');
  const green = gates.rows.every(r => r.ok);
  console.log(green ? `\nNOOP PASS: ${G} is live and re-derives byte-exact; nothing committed.` : '\nNOOP FAIL: see gates above.');
  finish(green ? 0 : 1);
}

/* ---------------------------------------------------- 2. branch and prep */
const branch = args.branch || `release/${G}-gridatlas-${manifest.composition_version}`;
if (gitOk('rev-parse', '--verify', '--quiet', `refs/heads/${branch}`)) die(`branch ${branch} already exists`);
run('git', ['switch', '-q', '-c', branch]);
report.branch = branch;
step(`branch ${branch} at ${baseSha.slice(0, 7)}`);

const trailers = trailerBlock(args.trailer);
const prepCommits = [];
const checkPrep = (label) => {
  const touched = git('diff', '--name-only', 'HEAD^', 'HEAD').split('\n').filter(Boolean);
  const bad = touched.filter(f => POINTER_FILES.includes(f) || f.startsWith('atlas/releases/') || f === 'atlas/index.html');
  if (bad.length) die(`${label} touches ${bad.join(', ')}; a preparatory commit must leave the pointer, STATE.md, the loader and releases alone`);
  const lint = run('node', ['tools/scope/loop.mjs', 'lint'], { allowFail: true });
  if (lint.status !== 0) die(`${label}: loop.mjs lint fails after it:\n${lint.out}`);
  const state = run('node', ['tools/scope/loop.mjs', 'state', '--stdout'], { allowFail: true });
  if (state.status !== 0 || state.stdout !== readText('STATE.md')) die(`${label}: STATE.md no longer matches the generator after it`);
  const sha = git('rev-parse', 'HEAD');
  prepCommits.push({ label, sha, files: touched });
  ok(`${label} -> ${sha.slice(0, 7)} (${touched.join(', ')}); lint PASS, STATE.md unchanged`);
};

for (const sha of args['prep-commit']) {
  const r = run('git', ['cherry-pick', '-x', sha], { allowFail: true });
  if (r.status !== 0) {
    run('git', ['cherry-pick', '--abort'], { allowFail: true });
    /* nothing is released on a failed preparation: leave no stray branch and put HEAD back where it was */
    run('git', ['switch', '-q', '--detach', baseSha], { allowFail: true }); run('git', ['branch', '-D', branch], { allowFail: true });
    die(`cherry-pick ${sha} failed (branch ${branch} removed; HEAD back at ${baseSha.slice(0, 7)}):\n${r.out}`);
  }
  checkPrep(`prep cherry-pick ${sha.slice(0, 7)}`);
}

if (args['prep-gate-kb']) {
  const rel = 'tools/scope/loop.mjs';
  const text = readText(rel);
  const sizeRe = /fs\.statSync\(cartridgePath\)\.size <= (\d{3})_000/g;
  const sizes = [...text.matchAll(sizeRe)];
  if (sizes.length !== 1) die(`${rel}: expected exactly one cartridge ceiling, found ${sizes.length}`);
  const oldKb = sizes[0][1];
  const N = args['prep-gate-kb'];
  if (Number(N) <= Number(oldKb)) die(`--prep-gate-kb ${N} does not raise the current ${oldKb} kB ceiling`);
  const msgRe = /exceeds the \d{3} kB recorded ceiling \([^)`]*\)/g;
  if ([...text.matchAll(msgRe)].length !== 1) die(`${rel}: ceiling message not found exactly once`);
  const reason = args['prep-gate-reason'].replace(/[`$\\]/g, '');
  const next = text.replace(sizeRe, `fs.statSync(cartridgePath).size <= ${N}_000`)
    .replace(msgRe, `exceeds the ${N} kB recorded ceiling (400 kB target; raised from ${oldKb} kB: ${reason})`);
  fs.writeFileSync(path.join(ROOT, rel), next);
  run('git', ['add', '--', rel]);
  commitWithMessage(`gate: raise the recorded cartridge ceiling from ${oldKb} kB to ${N} kB (${reason})\n\nPreparatory commit for the ${G} release. Lint and STATE.md parity pass; live composition unchanged.${trailers}\n`);
  checkPrep(`prep gate ${oldKb} -> ${N} kB`);
}
report.prep_commits = prepCommits;
const releaseParent = git('rev-parse', 'HEAD');

/* ------------------------------------------- 3. pointer and STATE.md only */
step(`write atlas/current.json from ${manifestRel}${loaderMoves ? `, ${LOADER_FILE} from ${previewLoaderRel}` : ''} and regenerate STATE.md`);
fs.writeFileSync(path.join(ROOT, 'atlas/current.json'), derived);
if (loaderMoves) fs.writeFileSync(path.join(ROOT, LOADER_FILE), previewLoader);
const state = run('node', ['tools/scope/loop.mjs', 'state'], { allowFail: true });
/* On any failure from here on: put the pointer back, and if no preparatory
   commit was made, leave HEAD where it started and drop the empty branch. */
const restore = () => {
  run('git', ['checkout', '--', ...RELEASE_FILES], { allowFail: true });
  if (!prepCommits.length) {
    run('git', ['switch', '-q', '--detach', baseSha], { allowFail: true });
    run('git', ['branch', '-D', branch], { allowFail: true });
  }
};
const HINT = 'If lint fails on the cartridge ceiling or the workflow budget, add the owner-approved preparatory commit (--prep-gate-kb N --prep-gate-reason "..." or --prep-commit <sha>) and run again.';
if (state.status !== 0) { restore(); die(`loop.mjs state failed with ${G}'s pointer in place; the pointer was restored.\n${HINT}\n${state.out}`); }
ok(state.out.trim().replace(/\n/g, '; '));
const changed = changedPaths();
if (JSON.stringify(changed) !== JSON.stringify([...RELEASE_FILES].sort())) {
  restore(); die(`the release must change exactly ${RELEASE_FILES.join(', ')}; it changed: ${changed.join(', ')}`);
}
ok(`changed: ${changed.join(', ')}`);

/* ----------------------------------------------------------------- 4. gates */
step('gates');
const gates = runGates({ expectGeneration: G, proofs, parityBaseline, rollbackTo: predecessor });
printGates(gates.rows);
if (args.log) fs.writeFileSync(path.resolve(args.log), gates.log);
report.gates = gates.rows;
report.parity_after = gates.parityRows;
if (JSON.stringify(changedPaths()) !== JSON.stringify([...RELEASE_FILES].sort())) { restore(); die('a gate wrote outside the release files'); }
if (!gates.rows.every(r => r.ok)) {
  restore();
  console.error(`\n${TOOL}: gates FAILED; the pointer was restored. ${prepCommits.length ? `Branch ${branch} holds ${prepCommits.length} prep commit(s) only.` : 'No branch kept.'}\n${HINT}`);
  finish(1);
}

const after = Object.fromEntries(RELEASE_FILES.map(f => [f, sha256File(f)]));
report.after = after;

/* ---------------------------------------------------------- 5. the commit */
if (!args['no-commit']) {
  run('git', ['add', '--', ...RELEASE_FILES]);
  const subject = `${G}-gridatlas-${manifest.composition_version}: ${args.title || `release composition ${G} to the live route`}`;
  const body = `Moves atlas/current.json and STATE.md${loaderMoves ? ` and the loader (${LOADER_FILE} := ${previewLoaderRel}, ${report.loader.live} -> ${previewRegistered.name})` : ''} from ${live.generation} to ${G}, written from ${manifestRel} by tools/release/release-generation.mjs. Nothing else changes.\nRollback: git revert this commit (tools/release/rollback-generation.mjs).\n\nAuthorised by  … [line shortened here: 428 characters; full line on GitHub]
  const sha = commitWithMessage(`${subject}\n\n${body}${trailers}\n`);
  const touched = git('diff', '--name-only', 'HEAD^', 'HEAD').split('\n').filter(Boolean).sort();
  if (JSON.stringify(touched) !== JSON.stringify([...RELEASE_FILES].sort())) die(`release commit touched ${touched.join(', ')}`);
  report.release_commit = sha;
  report.release_tree = git('rev-parse', 'HEAD^{tree}');
}

step('hashes');
for (const f of RELEASE_FILES) console.log(`  ${f.padEnd(20)} before ${before[f]}\n  ${''.padEnd(20)} after  ${after[f]}`);
for (const p of prepCommits) console.log(`  prep commit          ${p.sha}  ${p.label}`);
if (report.release_commit) {
  console.log(`  release commit       ${report.release_commit}`);
  console.log(`  release tree         ${report.release_tree}`);
  console.log(`  parent of release    ${releaseParent}`);
  console.log(`\n${run('git', ['diff', '--stat', `${baseSha}..HEAD`]).stdout.trimEnd()}`);
  console.log(`\nRELEASE READY on branch ${branch} (not pushed). Next, by a person:
  git push -u origin ${branch}
  gh pr create --draft --base main --head ${branch}   # Rebase and merge, never squash: the release commit must stay separately revertable
  # after merge + Pages deploy: GRIDATLAS_BASE_URL=https://ventusltd.github.io/gridatlas/ node tools/scope/verify-live.mjs
  # rollback: node tools/release/rollback-generation.mjs --release-commit <merged sha of the release commit>`);
} else {
  console.log(`\nRELEASE STAGED (--no-commit) on branch ${branch}; inspect with git diff.`);
}
finish(0);

Release Status

A JavaScript module in the tools folder of GridAtlas that reads homepage owner.

automationgridatlas / tools/release/release-status.mjs · lines 1–147 of 147 · Entry point

What it does
It loads homepage owner. Defines isLine, liveBytes, ci, prState. Uses libraries node:fs, node:path, node:child_process. 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 is built from the is line helper (`isLine`), the live bytes helper (`liveBytes`) and the pr state helper (`prState`). Where every candidate is in the delivery flow (`docs/RELEASE.md`).
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), Check Served (script call), node:fs, node:path, node:child_process
Used by
none found
Produces
isLine, liveBytes, ci, prState
Defines here
isLine, liveBytes, ci, prState
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/release-status.mjs:1-147 · blob 9e25fdcaad0b7d12adb6e0b003f6488a9af4c4de · 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
#!/usr/bin/env node
/**
 * Where every candidate is in the delivery flow (docs/RELEASE.md).
 *
 *   node tools/release/release-status.mjs [--generation G ...] [--all] [--json] [--served]
 *
 * Default candidates: the live generation and every generation newer than it
 * that is pinned on gridatlas main (atlas/v/G/current.json) or cut in this
 * checkout. --all lists every pinned lightning-line generation.
 *
 * For each, read-only, from `gh api` (repository-scoped REST) and this checkout:
 *   cut        the six files exist here (local) / on main
 *   preview    the PR that adds atlas/v/G/current.json: number, state, CI
 *   accepted   owner acceptance (tools/release/acceptance.mjs rules)
 *   release    the release/G-* PR: number, state, CI
 *   live       gridatlas main's atlas/current.json names G; live-bytes job for main's head
 *   homepage   globalgrid2050-homepage main: G recorded / operative, with its label
 *   domain     globalgrid2050 main's catalogue/homepage-owner.json pins a homepage
 *              commit that makes G operative; deploy-pages.yml for main's head
 *   served     only with --served: tools/release/check-served.mjs once (needs network)
 * and the next step of the flow.
 */

import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { ROOT, parseArgs } from './lib.mjs';
import {
  GRIDATLAS, HOMEPAGE, DOMAIN, LIVE_BYTES_WORKFLOW, DOMAIN_DEPLOY_WORKFLOW, STAMP, gh, ghAll, ghFile, ghHeadSha,
  generationFiles, prsNaming, prFiles, classifyPr, checkRunsFor, decideAcceptance, workflowRuns, pad
} from './flow-lib.mjs';

let args;
try { args = parseArgs(process.argv.slice(2), { generation: { multi: true }, all: { bool: true }, json: { bool: true }, served: { bool: true } }); }
catch (error) { console.error(`release-status: ${error.message}`); process.exit(2); }

/* ------------------------------------------------------- shared reads */
const mainSha = ghHeadSha(GRIDATLAS, 'main');
const live = JSON.parse(ghFile(GRIDATLAS, mainSha, 'atlas/current.json'));
const LIVE = String(live.generation);
const pinnedOnMain = (gh(`repos/${GRIDATLAS}/contents/atlas/v?ref=${mainSha}`) || []).map(e => e.name).filter(n => STAMP.test(n)).sort();
const localCut = fs.existsSync(path.join(ROOT, 'atlas/v'))
  ? fs.readdirSync(path.join(ROOT, 'atlas/v')).filter(n => STAMP.test(n) && fs.existsSync(path.join(ROOT, generationFiles(n).manifest))) : [];
const isLine = (g) => g >= '202610261949';
let gens = args.generation.length ? args.generation
  : [...new Set([...pinnedOnMain, ...localCut])].filter(g => (args.all ? isLine(g) : g >= LIVE)).sort();

const pulls = gh(`repos/${GRIDATLAS}/pulls?state=all&per_page=100&sort=created&direction=desc`);
const oldestCut = gens.map(g => `${g.slice(0, 4)}-${g.slice(4, 6)}-${g.slice(6, 8)}T${g.slice(8, 10)}:${g.slice(10, 12)}:00Z`).sort()[0];
const comments = oldestCut ? ghAll(`repos/${GRIDATLAS}/issues/comments?sort=created&since=${oldestCut}`) : [];

const liveBytes = (() => {
  for (const run of workflowRuns(GRIDATLAS, LIVE_BYTES_WORKFLOW, { headSha: mainSha, perPage: 5 })) {
    const job = (gh(`repos/${GRIDATLAS}/actions/runs/${run.id}/jobs?per_page=50`).jobs || []).find(j => j.name === 'live-bytes');
    if (job) return job.status === 'completed' ? job.conclusion : job.status;
  }
  return 'no run';
})();

const homepageMain = JSON.parse(ghFile(HOMEPAGE, 'main', 'data/homepage.json')).entities.find(e => e.id === 'gridatlas');
const pin = JSON.parse(ghFile(DOMAIN, 'main', 'catalogue/homepage-owner.json'));
const pinnedHome = JSON.parse(ghFile(HOMEPAGE, pin.commit, 'data/homepage.json')).entities.find(e => e.id === 'gridatlas');
const domainSha = ghHeadSha(DOMAIN, 'main');
const deploy = workflowRuns(DOMAIN, DOMAIN_DEPLOY_WORKFLOW, { branch: 'main', perPage: 5 }).find(r => r.head_sha === domainSha);

/* G is superseded when a later pinned candidate names it as candidate_predecessor. */
const successors = {};
for (const g of pinnedOnMain.filter(x => gens.some(y => x > y))) {
  try {
    const m = JSON.parse(ghFile(GRIDATLAS, mainSha, generationFiles(g).manifest));
    if (m.candidate_predecessor && !successors[m.candidate_predecessor]) successors[m.candidate_predecessor] = g;
  } catch { /* not a lightning-line manifest */ }
}

const ci = (sha) => {
  const runs = checkRunsFor(GRIDATLAS, sha);
  if (!runs.length) return 'no CI';
  if (runs.some(r => r.status !== 'completed')) return 'CI running';
  const bad = runs.filter(r => !['success', 'skipped', 'neutral'].includes(r.conclusion));
  return bad.length ? `CI RED (${bad.map(r => r.name).join(',')})` : 'CI green';
};
const prState = (p) => (p.merged_at ? 'merged' : p.state === 'open' ? (p.draft ? 'draft' : 'open') : 'closed');

/* ------------------------------------------------------- per candidate */
const rows = [];
for (const G of gens) {
  const F = generationFiles(G);
  const onMain = pinnedOnMain.includes(G);
  const local = localCut.includes(G);
  let manifest = null;
  try { manifest = JSON.parse(onMain ? ghFile(GRIDATLAS, mainSha, F.manifest) : fs.readFileSync(path.join(ROOT, F.manifest), 'utf8')); } catch { /* none */ }
  const version = manifest?.composition_version || '?';
  const named = prsNaming(G, { pulls });
  const typed = named.map(p => ({ p, kind: classifyPr(p, prFiles(p.number), G) }));
  const preview = typed.filter(t => t.kind === 'preview').map(t => t.p)[0];
  const release = typed.filter(t => t.kind === 'release').map(t => t.p)[0];
  const rollback = typed.filter(t => t.kind === 'rollback').map(t => t.p)[0];
  const events = preview ? ghAll(`repos/${GRIDATLAS}/issues/${preview.number}/events?`).map(e => ({ ...e, issue: { html_url: preview.html_url } })) : [];
  const since = manifest?.cut_at_utc;
  const acc = decideAcceptance(G, { comments: comments.filter(c => !since || c.created_at >= since), events: events.filter(e => !since || e.created_at >= since) });
  const isLive = G === LIVE;
  const supersededBy = successors[G];
  const hpRel = homepageMain.releases.find(r => r.id === G);
  const row = {
    generation: G, version,
    cut: onMain ? 'on main' : local ? 'local only' : 'no',
    preview: preview ? `#${preview.number} ${prState(preview)}, ${ci(preview.head.sha)}` : (onMain ? 'on main (no PR found)' : 'none'),
    accepted: acc.state === 'accepted' ? `yes (${acc.by}, ${acc.via})` : acc.state === 'rejected' ? `REJECTED (${acc.by})` : (isLive ? 'n/a (released before GitHub acceptance)' : 'no'),
    acceptance_url: acc.url || null,
    release: release ? `#${release.number} ${prState(release)}, ${ci(release.head.sha)}` : 'none',
    live: isLive ? `LIVE, live-bytes ${liveBytes}` : (release?.merged_at ? `was live; now ${LIVE}` : 'no'),
    rollback: rollback ? `#${rollback.number} ${prState(rollback)}` : '-',
    homepage: hpRel ? `${homepageMain.operative_release_id === G ? 'OPERATIVE' : 'recorded'} "${hpRel.label}"` : 'no',
    domain: pinnedHome.operative_release_id === G ? `pinned ${pin.commit.slice(0, 7)}, deploy ${deploy ? (deploy.conclusion || deploy.status) : 'not run for head'}` : 'no'
  };
  row.next = !onMain && local ? `publish-preview.mjs --generation ${G}`
    : !onMain ? `tools/lightning/make-generation.mjs --gen ${G} ...`
    : preview && !preview.merged_at ? `CI green, then rebase-merge preview #${preview.number}`
    : supersededBy && !isLive && !release && acc.state !== 'accepted' ? `superseded by ${supersededBy} (nothing to do)`
    : acc.state !== 'accepted' && !isLive && !release?.merged_at ? `owner: ACCEPT ${G} (acceptance.mjs --how --pr ${preview?.number ?? 'N'})`
    : !isLive && !release ? `release-accepted.mjs --generation ${G} --push`
    : !isLive && release && !release.merged_at ? `CI green, owner rebase-merges release #${release.number}`
    : !isLive ? '-'
    : liveBytes !== 'success' ? 'check-live.mjs --wait'
    : homepageMain.operative_release_id !== G ? 'homepage-bump.mjs label --homepage DIR --push'
    : pinnedHome.operative_release_id !== G ? 'homepage-bump.mjs pin --homepage DIR --domain DIR --push'
    : !deploy || deploy.conclusion !== 'success' ? 'homepage-bump.mjs deploy [--dispatch]'
    : 'check-served.mjs (done when it passes)';
  rows.push(row);
}

let served = null;
if (args.served) {
  const r = spawnSync('node', [path.join(ROOT, 'tools/release/check-served.mjs'), '--timeout-s', '1'], { encoding: 'utf8' });
  served = { exit: r.status, line: (r.stdout || '').trim().split('\n').pop() };
}

const out = { gridatlas_main: mainSha, live: LIVE, live_bytes: liveBytes, homepage_operative: homepageMain.operative_release_id,
  domain_pin: pin.commit, domain_operative: pinnedHome.operative_release_id, domain_deploy: deploy ? (deploy.conclusion || deploy.status) : 'not run for head',
  served, candidates: rows };
if (args.json) { console.log(JSON.stringify(out, null, 1)); process.exit(0); }
console.log(`gridatlas main ${mainSha.slice(0, 12)}: live ${LIVE} (${live.composition_version}), live-bytes ${liveBytes}`);
console.log(`homepage: operative ${homepageMain.operative_release_id}; domain pin ${pin.commit.slice(0, 12)} makes ${pinnedHome.operative_release_id} operative; deploy ${out.domain_deploy}`);
if (served) console.log(`served: ${served.line}`);
console.log('');
const cols = ['generation', 'version', 'cut', 'preview', 'accepted', 'release', 'live', 'homepage', 'domain', 'next'];
console.log(pad([cols, ...rows.map(r => cols.map(c => r[c]))]));