GLOBALGRID2050 / EXPLORE CODE

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

Publish Preview and 3 more files

A JavaScript module in the tools folder of GridAtlas that works with change set (`changeSet`).

537 lines of JavaScript from gridatlas, in 4 files. Topic: Maps, GIS and field navigation. Section 668 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. Loader Swap Test test · gridatlas / tools/release/loader-swap.test.mjs lines 1–158
  2. Map Promotion Rehearsal automation · gridatlas / tools/release/map-promotion-rehearsal.mjs lines 1–85
  3. Publish Preview automation · gridatlas / tools/release/publish-preview.mjs lines 1–188
  4. Release Accepted automation · gridatlas / tools/release/release-accepted.mjs lines 1–106

Loader Swap Test

A test in the tools folder of GridAtlas that checks GridAtlas — Scope and GridAtlas — Release, using SHA-256.

testgridatlas / tools/release/loader-swap.test.mjs · lines 1–158 of 158 · Not reached from any entry point (candidate for review) · pattern sandbox (shared by 2 files)

What it does
It tests its inputs. Defines sandbox, g, commit, node, cleanup. Uses libraries node:test, node:assert/strict, node:fs, node:os, node:path. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
Out: JSON file current.json.
What it achieves
It is built from the sandbox step (`sandbox`), the commit step (`commit`) and the node step (`node`). Offline tests of the loader-only step (`tools/release/loader-swap.mjs`), the pr-gate rule that calls it, and the guarded loader rollback in `rollback-generation.mjs`.
Why it matters
Guards the behaviour of GridAtlas — Scope, GridAtlas — Release and Loader Swap.
Application
gridatlas · tools/release · test
Uses
GridAtlas — Scope (script call), GridAtlas — Release (script call), Loader Swap (script call), Rollback Generation (script call), Release Generation (script call), node:test, node:assert/strict, node:fs, node:os, node:path, node:child_process
Used by
none found
Produces
sandbox, g, commit, node, cleanup
Defines here
sandbox, g, commit, node, cleanup
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/release/loader-swap.test.mjs:1-158 · blob c92cb4d8d58981c7f594e3117ca26638c1fc459e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Offline tests of the loader-only step (tools/release/loader-swap.mjs), the
 * pr-gate rule that calls it, and the guarded loader rollback in
 * rollback-generation.mjs. Run by tools/ci/pr-gate.mjs (release-tools).
 * No network. The CLI cases run in a throwaway git worktree of HEAD with this
 * tree's tools/ copied in; nothing in the repository is changed.
 *
 *   node --test tools/release/loader-swap.test.mjs
 */

import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { ATLAS_LOADERS } from '../scope/lib.mjs';
import { ROOT, deriveCurrent } from './lib.mjs';
import { proveLoaderSwap } from './loader-swap.mjs';

const V1 = fs.readFileSync(path.join(ROOT, ATLAS_LOADERS.v1.payload));
const V2 = fs.readFileSync(path.join(ROOT, ATLAS_LOADERS.v2.payload));
// The replace-script fixture is pinned to L3 (202610281340), derived exactly as its release wrote atlas/current.json,
// so these tests keep their coverage whatever is live (R-cifix MINOR).
const L3 = '202610281340';
const LIVE = deriveCurrent(fs.readFileSync(path.join(ROOT, `atlas/manifests/${L3}-composition.json`), 'utf8'));
// A modular generation's pointer (after-cartridge slots), derived as release-generation.mjs writes it: the newest one cut
// against L3, so the sandbox's L3 live pointer is its predecessor (a later modular cut against a later live, e.g.
// 202610292014 against 202610291044, would otherwise become the fixture and fail the predecessor check)
const MODULAR = fs.readdirSync(path.join(ROOT, 'atlas/manifests')).filter(f => /^\d{12}-composition\.json$/.test(f)).sort().reverse()
  .map(f => fs.readFileSync(path.join(ROOT, 'atlas/manifests', f), 'utf8')).find(t => /"slot": "after-cartridge"/.test(t) && !/REJECTED/.test(t) && JSON.parse(t).previous_generation === L3);
const MODULAR_POINTER = deriveCurrent(MODULAR);

test('v1 -> v2 is a proven loader-only change for a replace-script live pointer', async () => {
  const r = await proveLoaderSwap({ fromLoader: V1, toLoader: V2, pointerText: LIVE });
  assert.equal(r.ok, true, r.reasons.join('; '));
  assert.equal(r.from.name, 'v1');
  assert.equal(r.to.name, 'v2');
  assert.match(r.detail, /identical/);
});

test('v2 -> v1 (loader rollback) is allowed while a replace-script pointer is live', async () => {
  const r = await proveLoaderSwap({ fromLoader: V2, toLoader: V1, pointerText: LIVE });
  assert.equal(r.ok, true, r.reasons.join('; '));
});

test('v2 -> v1 is refused while a modular generation is live: pointer first, then the loader', async () => {
  assert.ok(MODULAR, 'no modular manifest to test with');
  const r = await proveLoaderSwap({ fromLoader: V2, toLoader: V1, pointerText: MODULAR_POINTER });
  assert.equal(r.ok, false);
  assert.match(r.reasons.join(' '), /cannot compose slot\(s\) after-cartridge .*roll the pointer back first/);
});

test('an unregistered loader is refused, even one byte off v2', async () => {
  const r = await proveLoaderSwap({ fromLoader: V1, toLoader: Buffer.concat([V2, Buffer.from('\n')]), pointerText: LIVE });
  assert.equal(r.ok, false);
  assert.match(r.reasons.join(' '), /not a registered loader/);
});

test('a pointer neither loader can compose is refused (a cartridge hash off by one digit)', async () => {
  const p = JSON.parse(LIVE);
  const c = p.cartridges.find(x => x.id === p.cartridge_order[0]);
  c.sha256 = (c.sha256[0] === '0' ? '1' : '0') + c.sha256.slice(1);
  const r = await proveLoaderSwap({ fromLoader: V1, toLoader: V2, pointerText: `${JSON.stringify(p, null, 1)}\n` });
  assert.equal(r.ok, false);
  assert.match(r.reasons.join(' '), /does not compose/);
});

/* ---------- the CLI the gate calls, and the rollback guard, in a throwaway worktree ---------- */
function sandbox() {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'loader-swap-'));
  const wt = path.join(dir, 'wt');
  const env = { ...process.env, GIT_AUTHOR_NAME: 'loader-swap test', GIT_AUTHOR_EMAIL: 'test@example.invalid', GIT_COMMITTER_NAME: 'loader-swap test', GIT_COMMITTER_EMAIL: 'test@example.invalid' };
  const g = (args, cwd = wt) => spawnSync('git', args, { cwd, encoding: 'utf8', env });
  const add = g(['worktree', 'add', '-q', '--detach', wt, 'HEAD'], ROOT);
  if (add.status !== 0) throw new Error(add.stderr);
  // this tree's tools (possibly uncommitted) over HEAD's
  fs.cpSync(path.join(ROOT, 'tools'), path.join(wt, 'tools'), { recursive: true });
  const commit = (msg) => { g(['add', '-A']); const r = g(['commit', '-q', '--no-verify', '--allow-empty', '-m', msg]); if (r.status !== 0) throw new Error(r.stderr); return g(['rev-parse', 'HEAD']).stdout.trim(); };
  const node = (args) => spawnSync('node', args, { cwd: wt, encoding: 'utf8' });
  const cleanup = () => { g(['worktree', 'remove', '--force', wt], ROOT); fs.rmSync(dir, { recursive: true, force: true }); };
  return { wt, g, commit, node, cleanup };
}

test('gate CLI: loader-only v1 -> v2 passes; v2 -> v1 under a modular live pointer fails', () => {
  const s = sandbox();
  try {
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), V1); fs.writeFileSync(path.join(s.wt, 'atlas/current.json'), LIVE);
    const base = s.commit('base: v1 live loader, L3 live');
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), V2);
    let r = s.node(['tools/release/loader-swap.mjs', 'check', '--base', base]);
    assert.equal(r.status, 0, r.stdout + r.stderr);
    assert.match(r.stdout, /^PASS loader-only change v1 -> v2/m);
    // an unregistered loader is refused by the same check
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), Buffer.concat([V2, Buffer.from('<!-- x -->\n')]));
    r = s.node(['tools/release/loader-swap.mjs', 'check', '--base', base]);
    assert.equal(r.status, 1);
    assert.match(r.stdout, /^FAIL .*not a registered loader/m);
    // modular pointer live behind v2, loader back to v1 alone
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), V2);
    fs.writeFileSync(path.join(s.wt, 'atlas/current.json'), MODULAR_POINTER);
    const modularBase = s.commit('modular live behind v2');
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), V1);
    r = s.node(['tools/release/loader-swap.mjs', 'check', '--base', modularBase]);
    assert.equal(r.status, 1);
    assert.match(r.stdout, /roll the pointer back first/);
  } finally { s.cleanup(); }
});

test('rollback-generation refuses a loader-only revert while a generation needing the newer loader is live', () => {
  const s = sandbox();
  try {
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), V1); fs.writeFileSync(path.join(s.wt, 'atlas/current.json'), LIVE);
    s.commit('base: v1 live loader, L3 live');
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), V2);
    const step1 = s.commit('step 1: loader v2 alone');
    fs.writeFileSync(path.join(s.wt, 'atlas/current.json'), MODULAR_POINTER);
    const head = s.commit('step 2 (pointer only; STATE.md not regenerated in this fixture)');
    const r = s.node(['tools/release/rollback-generation.mjs', '--release-commit', step1, '--reason', 'test', '--base', head, '--no-commit']);
    assert.equal(r.status, 1, r.stdout + r.stderr);
    assert.match(r.stderr, /refusing the loader rollback v2 -> v1: .*roll the pointer back first, then the loader/);
    assert.equal(s.g(['rev-parse', 'HEAD']).stdout.trim(), head, 'nothing committed, HEAD unchanged');
    assert.equal(s.g(['status', '--porcelain']).stdout, '', 'nothing written');
  } finally { s.cleanup(); }
});

test('rollback-generation refuses a loader-only revert when the loader has moved since', () => {
  const s = sandbox();
  try {
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), V1); fs.writeFileSync(path.join(s.wt, 'atlas/current.json'), LIVE);
    s.commit('base');
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), V2);
    const step1 = s.commit('step 1');
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), V1);
    const head = s.commit('loader moved again');
    const r = s.node(['tools/release/rollback-generation.mjs', '--release-commit', step1, '--reason', 'test', '--base', head, '--no-commit']);
    assert.equal(r.status, 1);
    assert.match(r.stderr, /has moved since/);
  } finally { s.cleanup(); }
});

test('release-generation refuses a one-step v1 -> v2 release of a modular generation unless --allow-loader-follows (R-cifix MAJOR)', () => {
  const G = JSON.parse(MODULAR).generation, s = sandbox();
  try {
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), V1); fs.writeFileSync(path.join(s.wt, 'atlas/current.json'), LIVE);
    const head = s.commit('base: v1 live loader, L3 live');
    let r = s.node(['tools/release/release-generation.mjs', '--generation', G, '--base', head, '--expect-live', L3, '--check']);
    assert.equal(r.status, 1, r.stdout + r.stderr);
    assert.match(r.stderr, /the live loader \(v1\) cannot compose slot\(s\) after-cartridge .*release the loader first/);
    r = s.node(['tools/release/release-generation.mjs', '--generation', G, '--base', head, '--expect-live', L3, '--check', '--allow-loader-follows']);
    assert.doesNotMatch(r.stderr, /cannot compose slot/, 'the explicit override passes this precondition');
    assert.match(r.stdout, /LOADER_FOLLOWS/);
    // loader first: with v2 live, the same release is LOADER_IDENTICAL and needs no override
    fs.writeFileSync(path.join(s.wt, 'atlas/index.html'), V2); const head2 = s.commit('step 1: loader v2');
    r = s.node(['tools/release/release-generation.mjs', '--generation', G, '--base', head2, '--expect-live', L3, '--check']);
    assert.match(r.stdout, /LOADER_IDENTICAL/, r.stdout + r.stderr); assert.doesNotMatch(r.stderr, /cannot compose slot/);
  } finally { s.cleanup(); }
});

Map Promotion Rehearsal

A JavaScript module in the tools folder of GridAtlas that reads before, after and rollback.

automationgridatlas / tools/release/map-promotion-rehearsal.mjs · lines 1–85 of 85 · Entry point · pattern invoke (shared by 5 files)

What it does
It loads before, after and rollback. Defines run, git, json, invoke. Uses libraries node:fs, node:path, node:assert/strict, node:url, 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 before.json; JSON file after.json; JSON file rollback.json. Out: JSON file map-promotion-rehearsal.json.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It is built from the run step (`run`), the git step (`git`) and the JSON step (`json`). Full local-only release and route-C rollback; never push or read acceptance.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/release · JavaScript module
Uses
Release Generation (script call), CI PR Gate (script call), Rollback Generation (script call), node:fs, node:path, node:assert/strict, node:url, node:child_process
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
run, git, json, invoke
Defines here
run, git, json, invoke
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/map-promotion-rehearsal.mjs:1-85 · blob 1ce0adcb24b2344c89faafe4b0cd8a903bf8f818 · 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
/** Full local-only release and route-C rollback; never push or read acceptance. */
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {fileURLToPath} from 'node:url';
import {spawnSync} from 'node:child_process';

const ROOT=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
const G='202611161720', BEFORE='202611161645', PARENT='202611132345';
function run(cwd,command,args,{allowFailure=false}={}) {
  const r=spawnSync(command,args,{cwd,encoding:'utf8',maxBuffer:128*1024*1024});
  const output=(r.stdout||'')+(r.stderr||'');
  if(!allowFailure)assert.equal(r.status,0,`${command} ${args.join(' ')}\n${output}`);
  return {status:r.status,output};
}
const git=(cwd,...args)=>run(cwd,'git',args).output.trim();
assert.equal(git(ROOT,'status','--porcelain'),'','rehearsal requires a clean committed candidate');
const originalHead=git(ROOT,'rev-parse','HEAD');
assert.equal(JSON.parse(fs.readFileSync(path.join(ROOT,'atlas/current.json'))).generation,PARENT);
fs.mkdirSync(path.join(ROOT,'work'),{recursive:true});
const checkout=fs.mkdtempSync(path.join(ROOT,'work','map-release-rehearsal-'));
assert.ok(path.resolve(checkout).startsWith(path.join(ROOT,'work')+path.sep));
run(ROOT,'git',['worktree','add','--detach',checkout,originalHead]);
fs.mkdirSync(path.join(checkout,'work'),{recursive:true});
const suffix=path.basename(checkout), branch=name=>`rehearsal/${suffix}/${name}`;
const json=name=>JSON.parse(fs.readFileSync(path.join(checkout,'work',name)));
const invoke=(script,args)=>run(checkout,'node',[script,...args],{allowFailure:true});
const summary={candidate_commit:originalHead,generation:G,parent:PARENT};
try {
  // Exercise the exact rejected release, not a synthetic validator fixture.
  const before=invoke('tools/release/release-generation.mjs',[
    '--generation',BEFORE,'--base',originalHead,'--expect-live',PARENT,
    '--branch',branch('before'),'--authorised-by','Local regression rehearsal only; never publish',
    '--report','work/before.json','--log','work/before.log']);
  assert.equal(before.status,1,'old preview must fail real promotion');
  const failed=json('before.json');
  assert.deepEqual(failed.gates.filter(g=>!g.ok).map(g=>g.gate).sort(),[
    'verify-compose',`rollback.mjs --to ${PARENT} --dry-run`].sort());
  const beforeLog=fs.readFileSync(path.join(checkout,'work/before.log'),'utf8');
  assert.match(beforeLog,/composition copied full application/);
  assert.match(beforeLog,/not an ancestor/);
  assert.equal(git(checkout,'status','--porcelain'),'');
  assert.equal(git(checkout,'rev-parse','HEAD'),originalHead);
  summary.before={expected_failure:true,gates:failed.gates};
  console.log('BEFORE PASS: real release rejects missing copy attestation and parent lineage, restoring pointer/STATE.');

  const after=invoke('tools/release/release-generation.mjs',[
    '--generation',G,'--base',originalHead,'--expect-live',PARENT,
    '--branch',branch('release'),'--authorised-by','Local regression rehearsal only; never publish',
    '--report','work/after.json','--log','work/after.log']);
  assert.equal(after.status,0,after.output);
  const released=json('after.json');
  assert.ok(released.gates.length>=7 && released.gates.every(g=>g.ok));
  assert.equal(JSON.parse(fs.readFileSync(path.join(checkout,'atlas/current.json'))).generation,G);
  assert.deepEqual(git(checkout,'diff','--name-only',`${released.release_commit}^`,released.release_commit).split('\n').sort(),['STATE.md','atlas/current.json']);
  summary.after={gates:released.gates,release_commit:released.release_commit,before:released.before,after:released.after};
  console.log('AFTER PASS: actual release committed only pointer/STATE; every promotion gate passed.');

  // The preview gate sees the predecessor; exercise the full PR gate with the actual promoted composition.
  const promotedGate=invoke('tools/ci/pr-gate.mjs',['--base',originalHead]);
  fs.writeFileSync(path.join(checkout,'work/promoted-pr-gate.log'),promotedGate.output);
  assert.equal(promotedGate.status,0,promotedGate.output);
  summary.promoted_pr_gate={passed:true,summary:promotedGate.output.match(/\d+\/\d+ checks passed/)?.[0]};
  console.log('PROMOTED PR GATE PASS: '+summary.promoted_pr_gate.summary);

  const reverted=invoke('tools/release/rollback-generation.mjs',[
    '--release-commit',released.release_commit,'--base',released.release_commit,
    '--branch',branch('rollback'),'--reason','Local route-C regression rehearsal only; never publish',
    '--report','work/rollback.json','--log','work/rollback.log']);
  assert.equal(reverted.status,0,reverted.output);
  const rollback=json('rollback.json');
  assert.ok(rollback.gates.every(g=>g.ok));
  assert.deepEqual(rollback.byte_exact,{'atlas/current.json':true,'STATE.md':true});
  assert.equal(JSON.parse(fs.readFileSync(path.join(checkout,'atlas/current.json'))).generation,PARENT);
  assert.equal(git(checkout,'diff',originalHead,'HEAD','--','atlas/current.json','STATE.md'),'');
  assert.equal(git(checkout,'status','--porcelain'),'');
  summary.rollback={gates:rollback.gates,byte_exact:rollback.byte_exact,from:rollback.from,to:rollback.to};
  console.log('ROLLBACK PASS: route C restored predecessor pointer and STATE byte-for-byte; every rollback gate passed.');
  summary.result='PASS';
} finally {
  assert.equal(git(ROOT,'rev-parse','HEAD'),originalHead);
  assert.equal(git(ROOT,'status','--porcelain'),'');
  // Only this path-free summary is uploaded. Full local reports remain in the isolated checkout.
  fs.writeFileSync(path.join(ROOT,'work','map-promotion-rehearsal.json'),JSON.stringify(summary,null,2)+'\n');
}

Publish Preview

A JavaScript module in the tools folder of GridAtlas that works with change set (`changeSet`).

automationgridatlas / tools/release/publish-preview.mjs · lines 1–188 of 188 · Entry point

What it does
It loads data. Defines 6 functions or classes, including die, ok, show, check, changeSet. 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 (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
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
It is built from the die step (`die`), the show step (`show`) and the check step (`check`). Step 2 of the delivery flow: publish one or more generations cut by `tools/lightning/make-generation.mjs` (step 1) as a preview PR.
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), Flow Lib (import), node:fs, node:path
Used by
none found
Produces
die, ok, show, check, changeSet, version
Defines here
die, ok, show, check, changeSet, version
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/publish-preview.mjs:1-188 · blob 41bf4557a6331ac71f77016b2a9be1007981655b · 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
/**
 * Step 2 of the delivery flow: publish one or more generations cut by
 * tools/lightning/make-generation.mjs (step 1) as a preview PR. A preview is
 * ADDITIVE: it adds each generation's six files (and optionally its progress
 * note), carries the lightning source it was built from
 * (tools/lightning/src/*.js, tools/lightning/generations.json), and changes
 * nothing that is live.
 *
 *   node tools/release/publish-preview.mjs --generation G [--generation G2 ...]
 *        [--base origin/main] [--branch NAME] [--allow PATH ...] [--subject G=TEXT ...]
 *        [--title TEXT] [--body-file FILE] [--trailer TEXT ...] [--push] [--report FILE]
 *
 * PRE-CONDITIONS (all checked; nothing is committed if one fails)
 *   - HEAD is --base (cut files still uncommitted) or a branch descending from it;
 *   - against --base, the change set is exactly, per G, the six generation files
 *     ADDED, plus at most one docs/lightning/CANDIDATE-G-*-progress.md ADDED,
 *     plus the lightning source edit (tools/lightning/src/*.js, generations.json);
 *     any other path must be named with --allow (e.g. the vendored suite) and
 *     may never be atlas/current.json, STATE.md, atlas/index.html or atlas/releases/**;
 *   - none of G's files exist on --base;
 *   - per G: the manifest names G, its previous_generation is live on --base,
 *     atlas/v/G/current.json is the derived pointer re-rooted to ../../ (what
 *     release-generation.mjs will require), and its loader is a registered
 *     loader that supports the slots it uses (it need not equal the live one);
 *   - the PR gate passes locally: node tools/ci/pr-gate.mjs --base <base sha>
 *     (the same script CI runs on the PR).
 *
 * WHAT IT DOES
 *   1. If the cut files are uncommitted, creates --branch (default
 *      preview/<G>-<version>) and makes one commit per generation, subject
 *      "<G> candidate (<version>): <--subject or the manifest's scope tail>";
 *      the source edit goes into the newest generation's commit (the commit
 *      that cut it is its source, docs/LIGHTNING-SOURCE.md).
 *   2. Runs the pre-conditions and the PR gate on the branch.
 *   3. --push: pushes the branch and opens a DRAFT PR through the REST API.
 *      Without --push it prints the exact commands instead.
 *
 * After the PR is open, CI (pr-file-size-guard.yml: size-guard + cartridge-gate)
 * runs on it; `node tools/release/release-status.mjs --generation G` shows the
 * checks. The PR is merged with "Rebase and merge" once the owner wants the
 * preview on Pages; merging a preview never moves the live pointer.
 */

import fs from 'node:fs';
import path from 'node:path';
import { ROOT, parseArgs, run, git, gitOk, cleanTree, deriveCurrent, rerootForPreview, registeredLoaderOf, pointerSlots } from './lib.mjs';
import { generationFiles, PROGRESS_DOC_RE, GRIDATLAS, openDraftPr, writeJson } from './flow-lib.mjs';

const TOOL = 'publish-preview';
const die = (m) => { console.error(`${TOOL}: STOP: ${m}`); process.exit(1); };
const ok = (m) => console.log(`  OK    ${m}`);

let args;
try {
  args = parseArgs(process.argv.slice(2), {
    generation: { multi: true }, base: { default: 'origin/main' }, branch: {}, allow: { multi: true },
    subject: { multi: true }, title: {}, 'body-file': {}, trailer: { multi: true }, push: { bool: true }, report: {}
  });
} catch (error) { die(error.message); }
const GENS = [...new Set(args.generation)].sort();
if (!GENS.length || GENS.some(g => !/^\d{12}$/.test(g))) die('--generation G (12 digits) is required, repeatable');
const subjects = Object.fromEntries(args.subject.map(s => { const i = s.indexOf('='); return [s.slice(0, i), s.slice(i + 1)]; }));
const FORBIDDEN = /^(atlas\/current\.json|STATE\.md|atlas\/index\.html|atlas\/releases\/)/;
const SOURCE = /^tools\/lightning\/(src\/[^/]+\.js|generations\.json)$/;
for (const a of args.allow) if (FORBIDDEN.test(a)) die(`--allow ${a}: a preview may never change ${a}`);

if (!gitOk('rev-parse', '--verify', '--quiet', `${args.base}^{commit}`)) die(`--base ${args.base} does not resolve (git fetch origin)`);
const baseSha = git('rev-parse', `${args.base}^{commit}`);
if (!gitOk('merge-base', '--is-ancestor', baseSha, 'HEAD')) die(`HEAD does not descend from ${args.base} ${baseSha}`);
const show = (rev, rel) => { const r = run('git', ['show', `${rev}:${rel}`], { allowFail: true }); return r.status === 0 ? r.stdout : null; };
const baseLive = JSON.parse(show(baseSha, 'atlas/current.json')).generation;
const report = { tool: TOOL, generations: GENS, base: baseSha, live_on_base: baseLive, checks: [] };
const check = (name, pass, detail = '') => { report.checks.push({ name, pass, detail }); if (!pass) die(`${name}: ${detail}`); ok(`${name}${detail ? `  ${detail}` : ''}`); };

/* ---------------------------------------------- the change set vs base */
function changeSet() {
  const committed = run('git', ['diff', '--name-status', '--no-renames', baseSha, 'HEAD']).stdout.split('\n').filter(Boolean)
    .map(l => { const [s, ...p] = l.split('\t'); return { status: s[0], path: p.join('\t') }; });
  const pending = run('git', ['status', '--porcelain=v1', '--untracked-files=all']).stdout.split('\n').filter(Boolean)
    .map(l => ({ status: l.startsWith('??') ? 'A' : l[1] === 'D' || l[0] === 'D' ? 'D' : (l[0] === 'A' ? 'A' : 'M'), path: l.slice(3) }));
  const byPath = new Map(committed.map(c => [c.path, c]));
  for (const p of pending) byPath.set(p.path, { status: byPath.get(p.path)?.status === 'A' ? 'A' : p.status, path: p.path });
  return { all: [...byPath.values()].sort((a, b) => a.path.localeCompare(b.path)), pending };
}

console.log(`\n== change set against ${args.base} ${baseSha.slice(0, 12)} (live ${baseLive})`);
const { all, pending } = changeSet();
const expected = new Map();
for (const G of GENS) for (const p of Object.values(generationFiles(G))) expected.set(p, G);
const problems = [];
const progressFor = {};
const sources = [];
for (const c of all) {
  if (expected.has(c.path)) { if (c.status !== 'A') problems.push(`${c.path} is ${c.status}, must be added`); continue; }
  const pm = PROGRESS_DOC_RE.exec(c.path);
  if (pm && GENS.includes(pm[1]) && c.status === 'A' && !progressFor[pm[1]]) { progressFor[pm[1]] = c.path; continue; }
  if (SOURCE.test(c.path) && (c.status !== 'D' || c.path.includes('/src/'))) { sources.push(c.path); continue; }
  if (args.allow.includes(c.path) && !FORBIDDEN.test(c.path) && c.status !== 'D') continue;
  problems.push(`${c.status} ${c.path} is not part of a preview of ${GENS.join(', ')} (name it with --allow if intended)`);
}
for (const p of expected.keys()) if (!all.some(c => c.path === p)) problems.push(`${p} is missing`);
check('additive change set', problems.length === 0, problems.length ? problems.join('; ') : `${all.length} path(s): ${GENS.length}×6 generation files` +
  `${Object.keys(progressFor).length ? ` + ${Object.keys(progressFor).length} progress note(s)` : ''}${sources.length ? ` + lightning source (${sources.join(', ')})` : ''}${args.allow.length ? ` + allowed ${args.allow.join(', ')}` : ''}`);
for (const p of expected.keys()) if (show(baseSha, p) !== null) die(`${p} already exists on ${args.base}`);

/* ------------------------------------------------------- per generation */
const meta = {};
for (const G of GENS) {
  const F = generationFiles(G);
  const manifestText = fs.readFileSync(path.join(ROOT, F.manifest), 'utf8');
  const m = JSON.parse(manifestText);
  meta[G] = m;
  check(`${G} manifest names ${G}`, m.generation === G && m.composition_manifest === `./manifests/${G}-composition.json`, m.composition_id);
  check(`${G} was cut against live ${baseLive}`, String(m.previous_generation) === String(baseLive),
    `previous_generation ${m.previous_generation}${String(m.previous_generation) !== String(baseLive) ? ' (re-cut against the current live)' : ''}`);
  check(`${G} preview route = derived pointer`, fs.readFileSync(path.join(ROOT, F.routeCurrent), 'utf8') === rerootForPreview(deriveCurrent(manifestText)));
  // Any REGISTERED loader that supports the preview's slots: after a loader-only step 1 (loader-swap.mjs) the live
  // loader is v2 while monolithic previews keep v1; release-generation.mjs moves the loader with the pointer if it differs.
  const routeLoader = registeredLoaderOf(fs.readFileSync(path.join(ROOT, F.routeIndex)));
  const missing = routeLoader ? pointerSlots(JSON.parse(fs.readFileSync(path.join(ROOT, F.routeCurrent), 'utf8'))).filter(s => !routeLoader.slots.includes(s)) : [];
  check(`${G} loader registered`, !!routeLoader && !missing.length, !routeLoader ? `${F.routeIndex} is not a registered loader (tools/scope/lib.mjs ATLAS_LOADERS)`
    : missing.length ? `${F.routeIndex} (loader ${routeLoader.name}) cannot compose slot(s) ${missing.join(', ')}`
    : `${routeLoader.name}${fs.readFileSync(path.join(ROOT, F.routeIndex)).equals(fs.readFileSync(path.join(ROOT, 'atlas/index.html'))) ? ' (= live loader)' : ' (differs from the live loader; it moves with the pointer at release)'}`);
}

/* ------------------------------------------------------------- commits */
const version = (G) => meta[G].composition_version;
const branch = args.branch || `preview/${GENS[0]}-gridatlas-${version(GENS[0])}`;
const trailers = args.trailer.length ? `\n\n${args.trailer.join('\n')}` : '';
if (pending.length) {
  const current = run('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], { allowFail: true }).stdout.trim();
  if (!current || git('rev-parse', 'HEAD') === baseSha) {
    if (gitOk('rev-parse', '--verify', '--quiet', `refs/heads/${branch}`)) die(`branch ${branch} already exists`);
    run('git', ['switch', '-q', '-c', branch]);
  }
  for (const G of GENS) {
    const own = [...Object.values(generationFiles(G)), ...(progressFor[G] ? [progressFor[G]] : []), ...(G === GENS[GENS.length - 1] ? sources : [])];
    const paths = own.filter(p => pending.some(x => x.path === p || p.startsWith(x.path)));
    if (!paths.length) continue;
    run('git', ['add', '--', ...paths]);
    const scopeTail = (meta[G].acceptance?.scope || '').split(` ${G}): `).pop().split(';')[0].slice(0, 120);
    const subject = `${G} candidate (${version(G)}): ${subjects[G] || scopeTail || 'preview'}`;
    run('git', ['commit', '-q', '-F', '-'], { input: `${subject}\n\nPreview only: atlas/current.json and STATE.md are unchanged; live stays ${baseLive}.${trailers}\n` });
    ok(`committed ${G}: ${git('rev-parse', '--short', 'HEAD')} ${subject.slice(0, 90)}`);
  }
  const rest = run('git', ['status', '--porcelain=v1', '--untracked-files=all']).stdout.split('\n').filter(Boolean).map(l => l.slice(3));
  const allowedLeft = rest.filter(p => args.allow.includes(p));
  if (allowedLeft.length) {
    run('git', ['add', '--', ...allowedLeft]);
    run('git', ['commit', '-q', '-F', '-'], { input: `preview ${GENS.join(', ')}: supporting changes (${allowedLeft.join(', ')})${trailers}\n` });
    ok(`committed supporting paths: ${allowedLeft.join(', ')}`);
  }
}
if (!cleanTree()) die('working tree still has changes outside the preview; commit or remove them');
report.branch = run('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], { allowFail: true }).stdout.trim() || null;
report.head = git('rev-parse', 'HEAD');
report.commits = run('git', ['log', '--format=%H %s', `${baseSha}..HEAD`]).stdout.trim().split('\n').filter(Boolean);
if (!report.branch) die('HEAD is detached; pass --branch or switch to a branch');

/* ---------------------------------------------------------- the PR gate */
console.log(`\n== node tools/ci/pr-gate.mjs --base ${baseSha.slice(0, 12)} (what CI runs on the PR)`);
const gate = run('node', ['tools/ci/pr-gate.mjs', '--base', baseSha], { allowFail: true });
const gateLines = gate.out.split('\n').filter(l => /^(PASS|FAIL) /.test(l));
report.pr_gate = { exit: gate.status, rows: gateLines };
for (const l of gateLines) console.log(`  ${l.slice(0, 160)}`);
if (gate.status !== 0) die(`pr-gate exit ${gate.status}; fix before publishing`);
ok(`pr-gate ${gateLines.filter(l => l.startsWith('PASS')).length}/${gateLines.length} PASS`);

/* ------------------------------------------------------------- publish */
const title = args.title || `Publish preview ${GENS.map(g => `${g} (${version(g)})`).join(' and ')} (no live pointer switch)`;
const body = args['body-file'] ? fs.readFileSync(path.resolve(args['body-file']), 'utf8')
  : `Preview of ${GENS.join(', ')}; live stays ${baseLive}.\n\n${report.commits.map(c => `- ${c.slice(0, 12)} ${c.slice(41)}`).join('\n')}\n\n` +
    `Routes after merge: ${GENS.map(g => `https://ventusltd.github.io/gridatlas/atlas/v/${g}/`).join(' ')}\n\n` +
    `Local pr-gate: ${gateLines.filter(l => l.startsWith('PASS')).length}/${gateLines.length} PASS. Merge with **Rebase and merge**.\n` +
    `Owner acceptance: comment \`ACCEPT <generation>\` (first line) here, or add the label \`accepted:<generation>\`.\n`;
report.title = title;
if (args.push) {
  run('git', ['push', '-u', 'origin', report.branch]);
  const pr = openDraftPr({ head: report.branch, title, body });
  report.pr = { number: pr.number, url: pr.html_url };
  ok(`draft PR #${pr.number} ${pr.html_url}`);
} else {
  console.log(`\n== not pushed (pass --push). To publish:\n  git push -u origin ${report.branch}\n` +
    `  gh api -X POST repos/${GRIDATLAS}/pulls -f head=${report.branch} -f base=main -F draft=true -f title=${JSON.stringify(title)} -F body=@<body.md>`);
}
console.log(`\nnext: CI runs on the PR; then the owner checks ${GENS.map(g => `atlas/v/${g}/`).join(', ')} and records acceptance (tools/release/acceptance.mjs)`);
if (args.report) writeJson(args.report, report);

Release Accepted

A JavaScript module in the tools folder of GridAtlas. It is built from the die step (`die`).

automationgridatlas / tools/release/release-accepted.mjs · lines 1–106 of 106 · Entry point

What it does
It loads data. Defines die, ok. 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; command-line arguments.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
Step 4 of the delivery flow: release an ACCEPTED preview generation.
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), Release Generation (script call), node:fs, node:path, node:child_process
Used by
none found
Produces
die, ok
Defines here
die, ok
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-accepted.mjs:1-106 · blob f0c2f5856134e1d041c40234331bee0ae0482bb6 · 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
/**
 * Step 4 of the delivery flow: release an ACCEPTED preview generation.
 *
 *   node tools/release/release-accepted.mjs --generation G [--title TEXT] [--trailer TEXT ...]
 *        [--report FILE] [--log FILE] [--push] [--body-file FILE] [--base REV] [--branch NAME]
 *   node tools/release/release-accepted.mjs --generation G --rehearsal [...]   (no acceptance needed; never pushes)
 *
 * PRE-CONDITIONS
 *   - the owner's acceptance of G is on GitHub (tools/release/acceptance.mjs: exit 0);
 *   - G's preview is merged: its files are on origin/main (release-generation.mjs
 *     re-checks every byte), and the preview PR's CI (pr-file-size-guard.yml) is green;
 *   - this checkout is a clean worktree whose HEAD is origin/main.
 *
 * WHAT IT DOES
 *   1. Reads the acceptance and the preview PR's checks.
 *   2. Runs tools/release/release-generation.mjs with
 *      --authorised-by "owner (<login>) <comment or label URL>, <UTC time>"
 *      so the commit carries the acceptance record. All of that script's
 *      preconditions and gates apply unchanged (see docs/RELEASE.md).
 *   3. --push: pushes release/G-gridatlas-<version> and opens a DRAFT PR.
 *      CI (the PR gate) runs on it. The owner merges with REBASE AND MERGE:
 *        gh api -X PUT repos/Ventusltd/gridatlas/pulls/<N>/merge -f merge_method=rebase
 *      never squash (a squash folds preparatory commits into the release commit).
 *
 * --rehearsal skips the acceptance read, writes the branch as
 * rehearsal/release-G and refuses --push: the whole release short of
 * publishing, on a local branch.
 */

import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { ROOT, parseArgs, run, git } from './lib.mjs';
import { GRIDATLAS, readAcceptance, cutAtUtc, prsNaming, prFiles, classifyPr, checkRunsFor, openDraftPr, gh } from './flow-lib.mjs';

const TOOL = 'release-accepted';
const die = (m) => { console.error(`${TOOL}: STOP: ${m}`); process.exit(1); };
const ok = (m) => console.log(`  OK    ${m}`);

let args;
try {
  args = parseArgs(process.argv.slice(2), {
    generation: {}, title: {}, trailer: { multi: true }, report: {}, log: {}, push: { bool: true },
    'body-file': {}, rehearsal: { bool: true }, branch: {}, base: {}
  });
} catch (error) { die(error.message); }
const G = args.generation;
if (!G || !/^\d{12}$/.test(G)) die('--generation G (12 digits) is required');
if (args.rehearsal && args.push) die('--rehearsal never pushes');

console.log(`\n== acceptance and preview of ${G}`);
let authorisedBy;
const pulls = gh(`repos/${GRIDATLAS}/pulls?state=all&per_page=100&sort=created&direction=desc`);
const previews = prsNaming(G, { pulls }).filter(p => classifyPr(p, prFiles(p.number), G) === 'preview');
if (!previews.length) die(`no preview PR adds atlas/v/${G}/current.json`);
const preview = previews.find(p => p.merged_at) || previews[0];
if (!preview.merged_at) die(`preview PR #${preview.number} is not merged; merge it (rebase) first`);
ok(`preview PR #${preview.number} merged ${preview.merged_at}`);
const checks = checkRunsFor(GRIDATLAS, preview.head.sha);
const red = checks.filter(c => c.status === 'completed' && !['success', 'skipped', 'neutral'].includes(c.conclusion));
if (!checks.length) die(`preview PR #${preview.number} has no CI check runs on ${preview.head.sha}`);
if (red.length) die(`preview PR #${preview.number} CI is red: ${red.map(c => `${c.name}=${c.conclusion}`).join(', ')}`);
ok(`preview CI: ${checks.map(c => `${c.name}=${c.conclusion}`).join(', ')}`);

if (args.rehearsal) {
  authorisedBy = `REHEARSAL ONLY (no owner acceptance read; tools/release/release-accepted.mjs --rehearsal, ${new Date().toISOString()})`;
  console.log('  --     rehearsal: acceptance not required');
} else {
  const a = readAcceptance(G, { since: cutAtUtc(G) || undefined, pulls });
  for (const i of a.ignored) console.log(`  ignored: ${i.url}  ${i.why}`);
  if (a.state !== 'accepted') die(`${G} is not accepted (${a.state}). The owner records it: node tools/release/acceptance.mjs --generation ${G} --how --pr ${preview.number}`);
  authorisedBy = `owner (${a.by}), ${a.url}, ${a.at}`;
  ok(`accepted: ${authorisedBy}`);
}

const startSha = git('rev-parse', 'HEAD');
console.log('\n== tools/release/release-generation.mjs');
const branch = args.branch || (args.rehearsal ? `rehearsal/release-${G}` : undefined);
const argv = ['tools/release/release-generation.mjs', '--generation', G, '--authorised-by', authorisedBy];
if (branch) argv.push('--branch', branch);
if (args.base) argv.push('--base', args.base);
if (args.title) argv.push('--title', args.title);
for (const t of args.trailer) argv.push('--trailer', t);
if (args.report) argv.push('--report', path.resolve(args.report));
if (args.log) argv.push('--log', path.resolve(args.log));
const r = spawnSync('node', argv, { cwd: ROOT, stdio: 'inherit' });
if (r.status !== 0) die(`release-generation.mjs exit ${r.status}`);

const head = git('rev-parse', 'HEAD');
const current = run('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], { allowFail: true }).stdout.trim();
if (!current || startSha === head) { console.log('nothing committed (no-op release)'); process.exit(0); }
if (!args.push) {
  console.log(`\n== not pushed. To publish:\n  git push -u origin ${current}\n` +
    `  gh api -X POST repos/${GRIDATLAS}/pulls -f head=${current} -f base=main -F draft=true -f title='...' -F body=@<body.md>\n` +
    `then, once CI is green and the owner merges with rebase: node tools/release/check-live.mjs --generation ${G} --wait`);
  process.exit(0);
}
run('git', ['push', '-u', 'origin', current]);
const subject = git('log', '-1', '--format=%s');
const body = args['body-file'] ? fs.readFileSync(path.resolve(args['body-file']), 'utf8')
  : `Release of ${G}, accepted by ${authorisedBy}.\n\nPreview: #${preview.number}. Only atlas/current.json and STATE.md change.\n\n` +
    `Merge with **Rebase and merge** (never squash). Rollback: \`node tools/release/rollback-generation.mjs --release-commit <sha on main>\`.\n`;
const pr = openDraftPr({ head: current, title: subject, body });
ok(`draft release PR #${pr.number} ${pr.html_url}`);
console.log(`next: CI on #${pr.number}; owner merges with rebase; then node tools/release/check-live.mjs --generation ${G} --wait`);