GLOBALGRID2050 / EXPLORE CODE

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

Flow Lib and 4 more files

A JavaScript module in the tools folder of GridAtlas that classifies pr (`classifyPr`), parses verdict (`parseVerdict`) and reads acceptance (`readAcceptance`).

603 lines of JavaScript from gridatlas, in 5 files. Topic: Maps, GIS and field navigation. Section 666 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. Check Served automation · gridatlas / tools/release/check-served.mjs lines 1–107
  2. Cut Grid Explorer automation · gridatlas / tools/release/cut-grid-explorer.mjs lines 1–106
  3. Flow Lib automation · gridatlas / tools/release/flow-lib.mjs lines 1–246
  4. Flow Test test · gridatlas / tools/release/flow.test.mjs lines 1–91
  5. Grid Explorer Proof automation · gridatlas / tools/release/grid-explorer-proof.mjs lines 1–53

Check Served

A JavaScript module in the tools folder of GridAtlas that reads homepage owner, using SHA-256.

automationgridatlas / tools/release/check-served.mjs · lines 1–107 of 107 · Entry point · pattern finish (shared by 32 files)

What it does
It loads homepage owner. Defines sha256, sleep, get, finish. Uses libraries node:fs, node:os, 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-owner.json; JSON file homepage.json; command-line arguments.
Downstream impact
Used directly by 2 files: Release Status (gridatlas); GridAtlas Verify Live Workflow (gridatlas).
What it achieves
It is built from the sha256 step (`sha256`), the sleep step (`sleep`) and the get step (`get`). Step 7 of the delivery flow: a served check of www.globalgrid2050.com.
Why it matters
Run by Release Status and GridAtlas Verify Live Workflow.
Application
gridatlas · tools/release · JavaScript module
Uses
GridAtlas — Release (script call), Flow Lib (script call), node:fs, node:os, node:path, node:child_process, node:crypto
Used by
run by Release Status (script call), run by GridAtlas Verify Live Workflow (workflow run)
Produces
sha256, sleep, get, finish
Defines here
sha256, sleep, get, finish
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/check-served.mjs:1-107 · blob 55d29baf64548fb9ca4666c4c204a3ac469826d2 · 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 7 of the delivery flow: a served check of www.globalgrid2050.com.
 *
 *   node tools/release/check-served.mjs [--generation G] [--timeout-s 900] [--interval-s 30] [--report FILE]
 *
 * PRE-CONDITIONS
 *   - the domain pin PR is merged and deploy-pages.yml ran for globalgrid2050
 *     main (tools/release/homepage-bump.mjs deploy);
 *   - network access to www.globalgrid2050.com. Some sandboxes block it; then
 *     run it in CI instead (exactly the same script):
 *       gh api -X POST repos/Ventusltd/gridatlas/actions/workflows/202608301321-verify-live.yml/dispatches \
 *         -f ref=main -f 'inputs[mode]=served-homepage'
 *
 * WHAT IT CHECKS (expected values all come from GitHub, served values from the domain)
 *   1. globalgrid2050 main's catalogue/homepage-owner.json pins a homepage commit;
 *      the pinned data/homepage.json makes G the operative GridAtlas release
 *      (G defaults to the generation gridatlas main serves: the homepage must
 *      advertise what is live);
 *   2. served homepage-shell/data/homepage.json and homepage-shell/assets/
 *      versioned-homepage.{css,js} are byte-identical to the pin's SHA-256s;
 *   3. the served homepage (/) carries the GridAtlas row with G's label
 *      (e.g. "V9.176 - 29 October 2026") and links the live route.
 * Retries with cache-busting queries until --timeout-s (Pages/CDN lag).
 * Exit 0 PASS, 1 FAIL, 2 cannot reach the domain.
 */

import fs from 'node:fs';
import os from 'node:os';
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_BASE, PAGES_BASE, ghFile, writeJson } from './flow-lib.mjs';

const TOOL = 'check-served';
let args;
try {
  args = parseArgs(process.argv.slice(2), { generation: {}, 'timeout-s': { default: '900' }, 'interval-s': { default: '30' }, report: {}, base: { default: DOMAIN_BASE } });
} catch (error) { console.error(`${TOOL}: ${error.message}`); process.exit(2); }
const BASE = args.base.replace(/\/?$/, '/');
const sha256 = (b) => createHash('sha256').update(b).digest('hex');
const sleep = (s) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, s * 1000);
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'served-'));

/** curl, because it honours HTTPS_PROXY where Node's fetch does not. */
function get(url) {
  const out = path.join(tmp, 'body');
  const r = spawnSync('curl', ['-sS', '-L', '--max-time', '30', '-H', 'Cache-Control: no-cache', '-o', out, '-w', '%{http_code}', url], { encoding: 'utf8' });
  const http = Number(r.stdout) || 0;
  return { http, body: http ? fs.readFileSync(out) : null, error: http ? null : (r.stderr || '').trim() };
}

/* ------------------------------------------------------------- expected */
const live = JSON.parse(ghFile(GRIDATLAS, 'main', 'atlas/current.json'));
const G = args.generation || String(live.generation);
const pin = JSON.parse(ghFile(DOMAIN, 'main', 'catalogue/homepage-owner.json'));
const pinnedHome = JSON.parse(ghFile(HOMEPAGE, pin.commit, 'data/homepage.json'));
const entity = pinnedHome.entities.find(e => e.id === 'gridatlas');
const release = entity.releases.find(r => r.id === entity.operative_release_id);
const report = { tool: TOOL, base: BASE, generation: G, gridatlas_live: String(live.generation), pin: pin.commit,
  operative_release: entity.operative_release_id, label: release?.label, problems: [], attempts: 0, checks: [] };
const finish = (status, code) => {
  report.status = status;
  if (args.report) writeJson(args.report, report);
  console.log(`${status}: ${report.problems.length ? report.problems.join('; ') : `${BASE} serves the pinned homepage with GridAtlas "${report.label}"`}`);
  process.exit(code);
};
if (entity.operative_release_id !== G) { report.problems.push(`the pinned homepage (${pin.commit.slice(0, 12)}) makes ${entity.operative_release_id} operative, not ${G}`); finish('FAIL', 1); }
if (String(live.generation) !== G) report.problems.push(`note: gridatlas main serves ${live.generation}, not ${G}`);
console.log(`pin ${pin.commit.slice(0, 12)}: GridAtlas ${G} "${release.label}"`);

/* --------------------------------------------------------------- served */
const files = [['homepage-shell/data/homepage.json', 'data/homepage.json'],
  ['homepage-shell/assets/versioned-homepage.css', 'assets/versioned-homepage.css'],
  ['homepage-shell/assets/versioned-homepage.js', 'assets/versioned-homepage.js']];
const deadline = Date.now() + Number(args['timeout-s']) * 1000;
for (;;) {
  report.attempts += 1;
  const q = `?served-check=${Date.now()}`;
  const checks = [];
  let unreachable = null;
  for (const [served, pinned] of files) {
    const r = get(`${BASE}${served}${q}`);
    if (!r.http) unreachable = r.error;
    const got = r.body ? sha256(r.body) : null;
    checks.push({ path: served, http: r.http, ok: r.http === 200 && got === pin.files[pinned], expected: pin.files[pinned], live: got });
  }
  const home = get(`${BASE}${q}`);
  if (!home.http) unreachable = home.error;
  const html = home.body ? home.body.toString('utf8') : '';
  const row = (html.match(/<tr data-entity-id="gridatlas">[\s\S]*?<\/tr>/) || [''])[0];
  checks.push({ path: '/', http: home.http, ok: home.http === 200 && row.includes(release.label) && row.includes(`${PAGES_BASE}atlas/`),
    expected: `GridAtlas row with "${release.label}" linking ${PAGES_BASE}atlas/`, live: row ? row.slice(0, 120) : 'no GridAtlas row' });
  report.checks = checks;
  for (const c of checks) console.log(`  ${c.ok ? 'OK  ' : 'DIFF'}  ${c.path}  HTTP ${c.http}`);
  if (checks.every(c => c.ok)) finish('PASS', 0);
  if (unreachable && report.attempts === 1 && !checks.some(c => c.http)) {
    report.problems.push(`cannot reach ${BASE}: ${unreachable}; run it in CI (see the header)`);
    finish('BLOCKED', 2);
  }
  if (Date.now() > deadline) {
    report.problems.push(...checks.filter(c => !c.ok).map(c => `${c.path}: expected ${c.expected}, served ${c.live} (HTTP ${c.http})`));
    finish('FAIL', 1);
  }
  sleep(Number(args['interval-s']));
}

Cut Grid Explorer

A JavaScript module in the tools folder of GridAtlas that reads composition, generations, mobile arrival card edits and substations, using SHA-256.

automationgridatlas / tools/release/cut-grid-explorer.mjs · lines 1–106 of 106 · Not reached from any entry point (candidate for review)

What it does
It loads composition, generations, mobile arrival card edits and substations. Defines read, hash, json, write, arg. Uses libraries node:fs, node:path, node:assert/strict, 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. Domain terms in the code: substations.
Inputs & outputs
In: JSON file current.json; JSON file -composition.json; JSON file generations.json; JSON file mobile-arrival-card-edits.json; command-line arguments.
What it achieves
It is built from the read step (`read`), the hash step (`hash`) and the JSON step (`json`). Cut additive source-built explorer candidates. Never moves the live pointer.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/release · JavaScript module
Uses
GridAtlas — Release (script call), Single-Line Diagram (SLD) Build (script call), Build (script call), Build (script call), Build (script call), Build (script call), Grid Explorer Proof (script call), node:fs, node:path, node:assert/strict, node:crypto, node:url, node:child_process
Used by
none found
Produces
read, hash, json, write, arg
Defines here
read, hash, json, write, arg
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/cut-grid-explorer.mjs:1-106 · blob 0de3bea0bef075c151e0b07bcb989b3f743df5e9 · 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
/** Cut additive source-built explorer candidates. Never moves the live pointer. */
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {fileURLToPath} from 'node:url';
import {execFileSync} from 'node:child_process';
import {deriveCurrent, rerootForPreview} from './lib.mjs';
import {buildSld} from '../sld/build.mjs';

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const read = p => fs.readFileSync(path.join(root, p), 'utf8').replace(/\r\n/g, '\n');
const hash = b => createHash('sha256').update(b).digest('hex');
const json = p => JSON.parse(read(p));
const write = (p, body) => { const f = path.join(root, p); assert.ok(!fs.existsSync(f), `Refusing historical overwrite ${p}`); fs.mkdirSync(path.dirname(f), {recursive: true}); fs.writeFileSync(f, body); };
const arg = k => { const i = process.argv.indexOf(k); return i < 0 ? undefined : process.argv[i + 1]; };
const G = arg('--generation'), version = arg('--version'), stage = arg('--stage');
assert.ok(/^\d{12}$/.test(G || ''), '--generation YYYYMMDDHHMM required');
assert.ok(/^v9\.\d+$/.test(version || ''), '--version v9.N required');
assert.ok(['native', 'vicinity'].includes(stage), '--stage native|vicinity required');
const cutDate = new Date(`${G.slice(0,4)}-${G.slice(4,6)}-${G.slice(6,8)}T${G.slice(8,10)}:${G.slice(10,12)}:00.000Z`);
assert.ok(Number.isFinite(cutDate.getTime()) && cutDate <= new Date(), 'Generation must be an actual, non-future UTC minute');
const parent = json('atlas/current.json'), P = parent.generation;
assert.ok(G > P, 'Generation must follow live parent');
assert.ok(Number(version.slice(3)) > Math.max(...fs.readdirSync(path.join(root, 'atlas/manifests')).filter(n => n.endsWith('-composition.json')).flatMap(n => {
  const m = json(`atlas/manifests/${n}`); return [m.version, m.composition_version].map(v => /^v9\.(\d+)$/.exec(v || '')?.[1]).filter(Boolean).map(Number);
})), 'Version must exceed every committed candidate');
const composition = structuredClone(parent);
Object.assign(composition, {generation: G, previous_generation: P, superseded_generation: P, candidate_predecessor: P,
  composition_version: version, composition_id: `${G}-gridatlas-${version}`, composition_manifest: `./manifests/${G}-composition.json`,
  composition_note: stage === 'native' ? 'Mobile arrival summary and native Journey/Layers. Synthetic learning journeys labelled; existing real assets retain factual identity.' : 'Vicinity spatial explorer: 1–50 km, voltage context, local user model; source connections are never inferred.'});
const own = [];
if(process.argv.includes('--train-gazetteer')){
  const {buildGazetteer}=await import('../train/gazetteer/build.mjs');
  const bytes=buildGazetteer(G),c=composition.cartridges.find(c=>c.id==='uk-gazetteer-flyto');
  assert.ok(c,'Gazetteer predecessor required');delete c.assembled_from;
  Object.assign(c,{generation:G,version,path:`./cartridges/${G}-place-global-search-v9-5.js`,sha256:hash(bytes),bytes:bytes.length,source_recipe:'tools/train/gazetteer/generations.json'});
  c.capabilities=[...c.capabilities,'lookup-only-place-resolver-without-selection-side-effects'];
  write('atlas/'+c.path,bytes);own.push(c.id);
}
if (process.argv.includes('--pipeline-lifecycle')) {
  const {buildSubstation} = await import('../pipeline-lifecycle/build.mjs');
  const bytes = buildSubstation(G), c = composition.cartridges.find(c => c.id === 'substation-intelligence');
  assert.ok(c, 'Substation predecessor required');
  delete c.assembled_from;
  Object.assign(c, {generation: G, version, path: `./cartridges/${G}-substation-intelligence-v9-63.js`, sha256: hash(bytes), bytes: bytes.length,
    source_recipe: 'tools/pipeline-lifecycle/generations.json'});
  c.capabilities = [...c.capabilities, 'pipeline-selection-poll-map-removal-cleanup'];
  write('atlas/' + c.path, bytes); own.push(c.id);
}
const extraSldEdits = stage === 'native' ? 'tools/sld/src/mobile-arrival-card-edits.json' : arg('--sld-edits');
if (extraSldEdits) {
  const registryPath = 'tools/sld/generations.json', registry = json(registryPath), base = registry.generations[P];
  assert.ok(base, 'Native release requires source-built SLD parent');
  const editsPath = `tools/sld/src/${G}-mobile-arrival-edits.json`;
  assert.ok(extraSldEdits.startsWith('tools/sld/src/') && extraSldEdits.endsWith('.json'), 'SLD edits must be a declared local source recipe');
  const edits = [...json(base.edits), ...json(extraSldEdits)];
  write(editsPath, JSON.stringify(edits, null, 2) + '\n');
  let source = read(base.base.path);
  for (const [i, edit] of edits.entries()) {
    assert.equal(source.split(edit.before).length - 1, 1, `Edit ${i} must match exactly once`);
    source = source.replace(edit.before, edit.after);
  }
  const bytes = Buffer.from(base.header + read(base.owner.path) + '\n' + source);
  registry.generations[G] = {...base, edits: editsPath, output_sha256: hash(bytes)};
  fs.writeFileSync(path.join(root, registryPath), JSON.stringify(registry, null, 2) + '\n');
  assert.deepEqual(buildSld(G), bytes);
  const c = composition.cartridges.find(c => c.id === 'sld-sandbox');
  Object.assign(c, {generation: G, version, path: `./cartridges/${G}-sld-sandbox-v9-8.js`, sha256: hash(bytes), bytes: bytes.length});
  c.capabilities = [...c.capabilities, ...(stage === 'native' ? ['mobile-nearest-summary-before-details', '44px-labelled-details-map-controls'] : ['map-removal-observer-cleanup'])];
  write('atlas/' + c.path, bytes); own.push(c.id);
}
if (stage === 'native') {
  const {assembleModule} = await import('../journey/build.mjs');
  const result = assembleModule({generation: G});
  const body = result.body;
  assert.ok(Buffer.byteLength(body) <= 72000, 'Journey module budget');
  const journey = {id: 'grid-journey-preview', generation: G, version, type: 'script', slot: 'after-cartridge', after: 'uk-offtakers-overlay',
    path: `./modules/${G}-grid-journey-preview.js`, sha256: hash(body), bytes: Buffer.byteLength(body), byte_budget: 72000,
    immutable_shell_modified: false, real_routes_accepted: 0,
    capabilities: ['native-maplibre', 'native-layers-launcher', 'explicit-synthetic-learning-cursor', 'manual-reduced-motion', 'removable-lifecycle']};
  composition.cartridge_order.push(journey.id); composition.cartridges.push(journey); own.push(journey.id);
  write('atlas/' + journey.path, body);
} else {
  const {assemble, BUDGET: vicinityBudget} = await import('../vicinity/build.mjs');
  const result = assemble({generation: G});
  const vicinity = {id: 'grid-vicinity', generation: G, version, type: 'script', slot: 'after-cartridge', after: 'grid-journey-preview',
    path: `./modules/${G}-grid-vicinity.js`, sha256: result.sha256, bytes: result.bytes, byte_budget: vicinityBudget,
    immutable_shell_modified: false, capabilities: ['spatial-radius-1-50km', 'source-voltage-context', 'native-layers-launcher', 'validated-origin-intent', 'local-user-model']};
  assert.ok(composition.cartridge_order.includes(vicinity.after), 'Native Journey predecessor required');
  composition.cartridge_order.push(vicinity.id); composition.cartridges.push(vicinity); own.push(vicinity.id);
  write('atlas/' + vicinity.path, result.body);
}
const manifest = {...composition, parent_generation: P, version, cut_at_utc: cutDate.toISOString(),
  candidate_status: 'REVIEW_AND_PUBLIC_ACCEPTANCE_PENDING', note: composition.composition_note,
  acceptance: {full_application_copies_created: 0, immutable_shell_modified: false,
    owner_authorization: 'https://github.com/Ventusltd/neural-link-between-agents/issues/42#issuecomment-6964495738',
    owner_release_acceptance: 'Session owner authorised overnight release execution; no agent ACCEPT comment manufactured',
    immutable_releases_tree: execFileSync('git', ['rev-parse', 'HEAD:atlas/releases'], {cwd: root, encoding: 'utf8'}).trim(),
    stage, real_connections_inferred: 0}};
const manifestText = JSON.stringify(manifest, null, 1) + '\n';
write(`atlas/manifests/${G}-composition.json`, manifestText);
write(`atlas/v/${G}/current.json`, rerootForPreview(deriveCurrent(manifestText)));
write(`atlas/v/${G}/index.html`, read('atlas/index.html'));
for (const id of own) write(`tools/proofs/${G}-${id}.proof.mjs`, `import {proveExplorerGeneration} from '../release/grid-explorer-proof.mjs';\nawait proveExplorerGeneration('${G}', '${id}');\n`);
console.log(JSON.stringify({generation: G, version, stage, parent: P, own, livePointerChanged: false}));

Flow Lib

A JavaScript module in the tools folder of GridAtlas that classifies pr (`classifyPr`), parses verdict (`parseVerdict`) and reads acceptance (`readAcceptance`).

automationgridatlas / tools/release/flow-lib.mjs · lines 1–246 of 246 · pattern writeJson (shared by 8 files)

What it does
It loads data. Defines 24 functions or classes, including generationFiles, PROGRESS_DOC, runningAsAgent, GhError, gh. 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.
Downstream impact
Used directly by 8 files: Acceptance (gridatlas); Check Live (gridatlas); Check Served (gridatlas); Flow Test (gridatlas); and 4 more. Reached from 1 other entry point, including GridAtlas Verify Live Workflow (gridatlas).
What it achieves
It classifies pr (`classifyPr`), parses verdict (`parseVerdict`) and reads acceptance (`readAcceptance`). Shared helpers for the delivery-flow scripts in `tools/release/` (cut, preview, acceptance, release, live bytes, homepage label, served check, status).
Why it matters
Imported by Acceptance and Publish Preview. Run by 5 workflows and scripts, including Check Live, Check Served and Homepage Bump. Checked by Flow Test.
Application
gridatlas · tools/release · JavaScript module
Uses
GridAtlas — Release (script call), GridAtlas — Index Page (estate URL), node:fs, node:path, node:child_process
Used by
imported by Acceptance (import), run by Check Live (script call), run by Check Served (script call), imported by Flow Test (import), run by Homepage Bump (script call), imported by Publish Preview (import), run by Release Accepted (script call), run by Release Status (script call)
Produces
GRIDATLAS, HOMEPAGE, DOMAIN, PAGES_BASE, DOMAIN_BASE, LIVE_BYTES_WORKFLOW, PR_GATE_WORKFLOW, DOMAIN_DEPLOY_WORKFLOW, OWNER_LOGINS, STAMP, generationFiles, PROGRESS_DOC
Defines here
generationFiles, PROGRESS_DOC, runningAsAgent, GhError, gh, ghAll, ghFile, ghHeadSha, prsNaming, prFiles, classifyPr, acceptLabel, parseVerdict, trustedActor, decideAcceptance, readAcceptance, cutAtUtc, workflowRuns, checkRunsFor, dispatchWorkflow, openDraftPr, writeJson, readCommittedJson, pad
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/flow-lib.mjs:1-246 · blob 53e50fd477a2d9943ee06ef5068215ec71b8c38e · 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
/**
 * Shared helpers for the delivery-flow scripts in tools/release/ (cut,
 * preview, acceptance, release, live bytes, homepage label, served check,
 * status). See docs/RELEASE.md, "The delivery flow".
 *
 * GitHub is read and written only through `gh api` on repository-scoped REST
 * endpoints. GraphQL (and so `gh pr create`, `gh pr list`) and the search API
 * are not available from every environment the flow runs in, so nothing here
 * depends on them.
 */

import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { ROOT, run } from './lib.mjs';

export const GRIDATLAS = process.env.GRIDATLAS_REPO || 'Ventusltd/gridatlas';
export const HOMEPAGE = process.env.GRIDATLAS_HOMEPAGE_REPO || 'Ventusltd/globalgrid2050-homepage';
export const DOMAIN = process.env.GRIDATLAS_DOMAIN_REPO || 'Ventusltd/globalgrid2050';
export const PAGES_BASE = 'https://ventusltd.github.io/gridatlas/';
export const DOMAIN_BASE = 'https://www.globalgrid2050.com/';
export const LIVE_BYTES_WORKFLOW = '202608301321-verify-live.yml';
export const PR_GATE_WORKFLOW = 'pr-file-size-guard.yml';
export const DOMAIN_DEPLOY_WORKFLOW = 'deploy-pages.yml';

/* Who may accept a generation. The owner's GitHub login; override with a
   comma-separated GRIDATLAS_OWNER_LOGINS. */
export const OWNER_LOGINS = (process.env.GRIDATLAS_OWNER_LOGINS || 'Ventusltd')
  .split(',').map(s => s.trim()).filter(Boolean);

export const STAMP = /^\d{12}$/;

/** The six files tools/lightning/make-generation.mjs writes for generation G. */
export function generationFiles(G) {
  return {
    module: `atlas/modules/${G}-uk-lightning-overlay.js`,
    cartridge: `atlas/cartridges/${G}-sld-sandbox-v9-8.js`,
    proof: `tools/proofs/${G}-sld-sandbox.proof.mjs`,
    manifest: `atlas/manifests/${G}-composition.json`,
    routeIndex: `atlas/v/${G}/index.html`,
    routeCurrent: `atlas/v/${G}/current.json`
  };
}
/** The optional seventh: the candidate's progress note. */
export const PROGRESS_DOC = (G, name) => `docs/lightning/CANDIDATE-${G}-${name}-progress.md`;
export const PROGRESS_DOC_RE = /^docs\/lightning\/CANDIDATE-(\d{12})-[A-Za-z0-9._-]+-progress\.md$/;

/** True when an agent (Claude Code, CI) is running this process. */
export function runningAsAgent() {
  return Boolean(process.env.CLAUDECODE || process.env.CLAUDE_CODE_SESSION_ID || process.env.CODEX_SANDBOX
    || process.env.GITHUB_ACTIONS || process.env.CI);
}

/* ------------------------------------------------------------------ gh api */

export class GhError extends Error {}

/** `gh api` returning parsed JSON (or text with raw: true). */
export function gh(endpoint, { method = 'GET', fields = {}, raw = false, input } = {}) {
  const argv = ['api', '-X', method, endpoint];
  if (raw) argv.push('-H', 'Accept: application/vnd.github.raw');
  for (const [k, v] of Object.entries(fields)) argv.push(typeof v === 'string' ? '-f' : '-F', `${k}=${v}`);
  if (input !== undefined) argv.push('--input', '-');
  const r = spawnSync('gh', argv, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, input });
  if (r.error) throw new GhError(`gh not runnable: ${r.error.message}`);
  if (r.status !== 0) throw new GhError(`gh api ${method} ${endpoint}: ${(r.stderr || r.stdout).trim().split('\n').pop()}`);
  if (raw) return r.stdout;
  const text = r.stdout.trim();
  if (!text) return null;
  return JSON.parse(text);
}

/** Every page of a list endpoint. `gh --paginate` follows Link headers that
    use numeric repositories/{id} paths, which some proxies refuse, so pages
    are requested explicitly. */
export function ghAll(endpoint, { perPage = 100, maxPages = 30 } = {}) {
  const out = [];
  const sep = endpoint.includes('?') ? (endpoint.endsWith('?') ? '' : '&') : '?';
  for (let page = 1; page <= maxPages; page += 1) {
    const rows = gh(`${endpoint}${sep}per_page=${perPage}&page=${page}`);
    const list = Array.isArray(rows) ? rows : [];
    out.push(...list);
    if (list.length < perPage) break;
  }
  return out;
}

/** A file at a ref of a repository, or null when it does not exist. */
export function ghFile(repo, ref, relative) {
  try { return gh(`repos/${repo}/contents/${relative}?ref=${encodeURIComponent(ref)}`, { raw: true }); }
  catch (error) { if (/Not Found|404/.test(error.message)) return null; throw error; }
}

export function ghHeadSha(repo, branch = 'main') {
  return gh(`repos/${repo}/commits/${branch}`).sha;
}

/* --------------------------------------------------------- PRs and comments */

/** Pull requests whose title, body or head branch names G (newest first). */
export function prsNaming(G, { pulls } = {}) {
  const all = pulls || gh(`repos/${GRIDATLAS}/pulls?state=all&per_page=100&sort=created&direction=desc`);
  return all.filter(p => [p.title, p.body || '', p.head?.ref || ''].some(t => t.includes(G)));
}

export function prFiles(number) {
  return ghAll(`repos/${GRIDATLAS}/pulls/${number}/files`);
}

/** Classify a PR for G: a preview adds atlas/v/G/current.json; a release is
    a release/G-* branch that changes atlas/current.json; a rollback likewise
    on rollback/G-*. */
export function classifyPr(pr, files, G) {
  const names = files.map(f => f.filename);
  if (files.some(f => f.filename === `atlas/v/${G}/current.json` && f.status === 'added')) return 'preview';
  const ref = pr.head?.ref || '';
  /* A release PR may carry preparatory commits (L3's retired a workflow) before the pointer commit. */
  if (ref.startsWith(`release/${G}`) && names.includes('atlas/current.json')) return 'release';
  if (ref.startsWith('rollback/') && ref.includes(G) && names.includes('atlas/current.json')) return 'rollback';
  return 'other';
}

/* ------------------------------------------------------------- acceptance */

/*
 * An acceptance is ONE of:
 *   - a comment, anywhere in the gridatlas repository (issue or PR), whose
 *     first non-blank line is `ACCEPT <G>` (or `/accept <G>`), optionally
 *     followed by free text on later lines;
 *   - the label `accepted:<G>` on the preview PR.
 * It counts only when it was made by an OWNER_LOGINS account, not through a
 * GitHub App (Codex and other connectors post as the owner with an app
 * marker), and carries no agent signature. A later `REJECT <G>` comment, or
 * the removal of the label, withdraws it.
 *
 * No script in tools/release/ writes either form. Agents running with the
 * owner's token must not post them; acceptance.mjs --record refuses to run
 * under an agent and only prints the owner's command.
 */
export const AGENT_SIGNATURES = [/Claude-Session:/i, /Generated (?:with|by) \[Claude Code\]/i, /noreply@anthropic\.com/i, /chatgpt-codex/i];
export const acceptLabel = (G) => `accepted:${G}`;

export function parseVerdict(body, G) {
  const first = String(body || '').split(/\r?\n/).map(s => s.trim()).find(Boolean) || '';
  const m = first.match(/^\/?(ACCEPT|ACCEPTED|REJECT|REJECTED)\s+(\d{12})\b/i);
  if (!m || m[2] !== G) return null;
  return /^REJECT/i.test(m[1]) ? 'reject' : 'accept';
}

export function trustedActor(user, app, body = '') {
  if (!user || !OWNER_LOGINS.includes(user.login)) return { ok: false, why: `by ${user?.login ?? 'unknown'}, not an owner login (${OWNER_LOGINS.join(', ')})` };
  if (app) return { ok: false, why: `posted through the GitHub App ${app.slug || app.name}` };
  const sig = AGENT_SIGNATURES.find(re => re.test(body));
  if (sig) return { ok: false, why: `carries an agent signature (${sig})` };
  return { ok: true };
}

/**
 * Decide acceptance of G from repository comments and label events.
 *   comments: GET repos/R/issues/comments (any order)
 *   events:   GET repos/R/issues/events  (labeled / unlabeled)
 * Returns { state: 'accepted'|'rejected'|'none', by, at, url, ignored: [...] }.
 */
export function decideAcceptance(G, { comments = [], events = [] }) {
  const verdicts = [];
  const ignored = [];
  for (const c of comments) {
    const v = parseVerdict(c.body, G);
    if (!v) continue;
    const t = trustedActor(c.user, c.performed_via_github_app, c.body);
    if (!t.ok) { ignored.push({ url: c.html_url, why: t.why }); continue; }
    verdicts.push({ verdict: v, by: c.user.login, at: c.created_at, url: c.html_url, via: 'comment' });
  }
  for (const e of events) {
    if (!['labeled', 'unlabeled'].includes(e.event) || e.label?.name !== acceptLabel(G)) continue;
    const t = trustedActor(e.actor, e.performed_via_github_app);
    if (!t.ok) { ignored.push({ url: e.issue?.html_url, why: `label ${e.event} ${t.why}` }); continue; }
    verdicts.push({ verdict: e.event === 'labeled' ? 'accept' : 'withdraw', by: e.actor.login, at: e.created_at,
      url: e.issue?.html_url, via: `label ${acceptLabel(G)}` });
  }
  verdicts.sort((a, b) => a.at.localeCompare(b.at));
  const last = verdicts[verdicts.length - 1];
  if (!last) return { state: 'none', ignored, history: verdicts };
  const state = last.verdict === 'accept' ? 'accepted' : last.verdict === 'reject' ? 'rejected' : 'none';
  return { state, ...last, ignored, history: verdicts };
}

/** Acceptance of G read from GitHub: every repository comment since `since`,
    and the label events of the PRs that name G. */
export function readAcceptance(G, { since, pulls } = {}) {
  const q = since ? `&since=${encodeURIComponent(since)}` : '';
  const comments = ghAll(`repos/${GRIDATLAS}/issues/comments?sort=created${q}`);
  const events = prsNaming(G, { pulls })
    .flatMap(p => ghAll(`repos/${GRIDATLAS}/issues/${p.number}/events?`).map(e => ({ ...e, issue: { html_url: p.html_url } })))
    .filter(e => !since || e.created_at >= since);
  return decideAcceptance(G, { comments, events });
}

/** G's cut_at_utc, from the local checkout or gridatlas main. */
export function cutAtUtc(G) {
  const rel = generationFiles(G).manifest;
  const local = path.join(ROOT, rel);
  const text = fs.existsSync(local) ? fs.readFileSync(local, 'utf8') : ghFile(GRIDATLAS, 'main', rel);
  return text ? (JSON.parse(text).cut_at_utc || null) : null;
}

/* --------------------------------------------------------------- workflows */

export function workflowRuns(repo, workflow, { branch, headSha, event, perPage = 20 } = {}) {
  const q = [`per_page=${perPage}`];
  if (branch) q.push(`branch=${branch}`);
  if (headSha) q.push(`head_sha=${headSha}`);
  if (event) q.push(`event=${event}`);
  return gh(`repos/${repo}/actions/workflows/${workflow}/runs?${q.join('&')}`).workflow_runs || [];
}

export function checkRunsFor(repo, sha) {
  return gh(`repos/${repo}/commits/${sha}/check-runs?per_page=100`).check_runs || [];
}

export function dispatchWorkflow(repo, workflow, ref, inputs = {}) {
  const body = JSON.stringify({ ref, inputs });
  gh(`repos/${repo}/actions/workflows/${workflow}/dispatches`, { method: 'POST', input: body });
}

/** Open a DRAFT pull request through REST (gh pr create needs GraphQL). */
export function openDraftPr({ repo = GRIDATLAS, head, base = 'main', title, body }) {
  return gh(`repos/${repo}/pulls`, { method: 'POST', input: JSON.stringify({ head, base, title, body, draft: true }) });
}

/* ------------------------------------------------------------------ misc */

export function writeJson(file, data) {
  fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true });
  fs.writeFileSync(path.resolve(file), `${JSON.stringify(data, null, 1)}\n`);
}

export function readCommittedJson(rev, relative, cwd = ROOT) {
  const r = run('git', ['show', `${rev}:${relative}`], { cwd, allowFail: true });
  return r.status === 0 ? JSON.parse(r.stdout) : null;
}

export function pad(rows) {
  const widths = rows[0].map((_, i) => Math.max(...rows.map(r => String(r[i]).length)));
  return rows.map(r => r.map((c, i) => String(c).padEnd(widths[i])).join('  ').trimEnd()).join('\n');
}

Flow Test

A test in the tools folder of GridAtlas that checks Flow Lib and GridAtlas — Release. It is built from the comment step (`comment`).

testgridatlas / tools/release/flow.test.mjs · lines 1–91 of 91 · Not reached from any entry point (candidate for review) · pattern comment (shared by 3 files)

What it does
It tests its inputs. Defines comment, ev, pr, f. Uses libraries node:test, node:assert/strict.
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.
What it achieves
Offline tests of the delivery-flow rules in `flow-lib.mjs` (run by `tools/ci/pr-gate.mjs`, check release-tools).
Why it matters
Guards the behaviour of Flow Lib and GridAtlas — Release.
Application
gridatlas · tools/release · test
Uses
Flow Lib (import), GridAtlas — Release (import), node:test, node:assert/strict
Used by
none found
Produces
comment, ev, pr, f
Defines here
comment, ev, pr, f
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/flow.test.mjs:1-91 · blob 895d86ac7fc003e4adc4c5cdf049b01a0488f4cc · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Offline tests of the delivery-flow rules in flow-lib.mjs (run by
 * tools/ci/pr-gate.mjs, check release-tools). No network, no gh.
 *
 *   node --test tools/release/flow.test.mjs
 */

import test from 'node:test';
import assert from 'node:assert/strict';
import {
  parseVerdict, trustedActor, decideAcceptance, classifyPr, generationFiles, PROGRESS_DOC_RE, acceptLabel, OWNER_LOGINS
} from './flow-lib.mjs';
import { deriveCurrent, rerootForPreview } from './lib.mjs';

const G = '202610290045';
const owner = { login: OWNER_LOGINS[0] };
const comment = (body, at, extra = {}) => ({ body, created_at: at, user: owner, performed_via_github_app: null, html_url: `https://x/c/${at}`, ...extra });

test('parseVerdict reads only the first non-blank line, for exactly this generation', () => {
  assert.equal(parseVerdict(`ACCEPT ${G}`, G), 'accept');
  assert.equal(parseVerdict(`\n  /accept ${G}\nlooks good on the phone`, G), 'accept');
  assert.equal(parseVerdict(`accepted ${G}.`, G), 'accept');
  assert.equal(parseVerdict(`REJECT ${G}: the card overlaps`, G), 'reject');
  assert.equal(parseVerdict(`ACCEPT 202610290050`, G), null);
  assert.equal(parseVerdict(`ACCEPT ${G}0`, G), null);
  assert.equal(parseVerdict(`I would ACCEPT ${G}`, G), null);
  assert.equal(parseVerdict(`Looks fine\nACCEPT ${G}`, G), null);
  assert.equal(parseVerdict('', G), null);
});

test('trustedActor: owner login, no GitHub App, no agent signature', () => {
  assert.equal(trustedActor(owner, null, `ACCEPT ${G}`).ok, true);
  assert.equal(trustedActor({ login: 'someone-else' }, null).ok, false);
  assert.equal(trustedActor(owner, { slug: 'chatgpt-codex-connector' }).ok, false);
  assert.equal(trustedActor(owner, null, `ACCEPT ${G}\n\nClaude-Session: https://claude.ai/code/x`).ok, false);
  assert.equal(trustedActor(owner, null, `ACCEPT ${G}\n🤖 Generated with [Claude Code](https://claude.com/claude-code)`).ok, false);
  assert.equal(trustedActor(null, null).ok, false);
});

test('decideAcceptance: latest trusted verdict wins; untrusted ones are reported, not counted', () => {
  assert.equal(decideAcceptance(G, {}).state, 'none');
  const a = decideAcceptance(G, { comments: [comment(`ACCEPT ${G}`, '2026-10-29T03:00:00Z')] });
  assert.equal(a.state, 'accepted');
  assert.equal(a.by, owner.login);
  assert.equal(a.via, 'comment');
  const r = decideAcceptance(G, { comments: [comment(`ACCEPT ${G}`, '2026-10-29T03:00:00Z'), comment(`REJECT ${G}`, '2026-10-29T04:00:00Z')] });
  assert.equal(r.state, 'rejected');
  const back = decideAcceptance(G, { comments: [comment(`REJECT ${G}`, '2026-10-29T03:00:00Z'), comment(`ACCEPT ${G}`, '2026-10-29T04:00:00Z')] });
  assert.equal(back.state, 'accepted');
  const codex = decideAcceptance(G, { comments: [comment(`ACCEPT ${G}`, '2026-10-29T03:00:00Z', { performed_via_github_app: { slug: 'chatgpt-codex-connector' } })] });
  assert.equal(codex.state, 'none');
  assert.equal(codex.ignored.length, 1);
  const other = decideAcceptance(G, { comments: [comment(`ACCEPT ${G}`, '2026-10-29T03:00:00Z', { user: { login: 'mallory' } })] });
  assert.equal(other.state, 'none');
});

test('decideAcceptance: the accepted:<G> label, and its removal', () => {
  const ev = (event, at, actor = owner, app = null) => ({ event, created_at: at, actor, performed_via_github_app: app, label: { name: acceptLabel(G) }, issue: { html_url: 'https://x/pull/59' } });
  assert.equal(decideAcceptance(G, { events: [ev('labeled', '2026-10-29T03:00:00Z')] }).state, 'accepted');
  assert.equal(decideAcceptance(G, { events: [ev('labeled', '2026-10-29T03:00:00Z'), ev('unlabeled', '2026-10-29T03:05:00Z')] }).state, 'none');
  assert.equal(decideAcceptance(G, { events: [ev('labeled', '2026-10-29T03:00:00Z', owner, { slug: 'bot' })] }).state, 'none');
  assert.equal(decideAcceptance(G, { events: [{ ...ev('labeled', '2026-10-29T03:00:00Z'), label: { name: 'accepted:202610290050' } }] }).state, 'none');
});

test('classifyPr: preview, release (with prep commits), rollback, other', () => {
  const pr = (ref) => ({ head: { ref } });
  const f = (...names) => names.map(n => ({ filename: n, status: n.startsWith('atlas/v/') ? 'added' : 'modified' }));
  assert.equal(classifyPr(pr('claude/x'), f(`atlas/v/${G}/current.json`, `atlas/v/${G}/index.html`), G), 'preview');
  assert.equal(classifyPr(pr(`release/${G}-gridatlas-v9.176`), f('atlas/current.json', 'STATE.md'), G), 'release');
  assert.equal(classifyPr(pr(`release/${G}-gridatlas-v9.176`), f('.github/workflows/x.yml', 'tools/scope/lib.mjs', 'atlas/current.json', 'STATE.md'), G), 'release');
  assert.equal(classifyPr(pr(`rollback/${G}-to-202610281340`), f('atlas/current.json', 'STATE.md'), G), 'rollback');
  assert.equal(classifyPr(pr('docs/x'), f('docs/RELEASE.md'), G), 'other');
  assert.equal(classifyPr(pr(`release/${G}-x`), f('docs/RELEASE.md'), G), 'other');
});

test('the seven preview files', () => {
  assert.deepEqual(Object.values(generationFiles(G)).sort(), [
    `atlas/cartridges/${G}-sld-sandbox-v9-8.js`, `atlas/manifests/${G}-composition.json`, `atlas/modules/${G}-uk-lightning-overlay.js`,
    `atlas/v/${G}/current.json`, `atlas/v/${G}/index.html`, `tools/proofs/${G}-sld-sandbox.proof.mjs`]);
  assert.ok(PROGRESS_DOC_RE.test(`docs/lightning/CANDIDATE-${G}-M4-progress.md`));
  assert.ok(!PROGRESS_DOC_RE.test(`docs/lightning/CANDIDATE-${G}.md`));
});

test('the preview route is the release pointer re-rooted (checked by publish-preview)', () => {
  const manifest = JSON.stringify({ generation: G, composition_manifest: `./manifests/${G}-composition.json`, version: 'v9.176', cut_at_utc: 'x',
    cartridges: [{ id: 'a', path: './cartridges/a.js', contract: '../ui/a.mjs' }] }, null, 1) + '\n';
  const route = rerootForPreview(deriveCurrent(manifest));
  assert.match(route, /"path": "\.\.\/\.\.\/cartridges\/a\.js"/);
  assert.match(route, /"contract": "\.\.\/\.\.\/ui\/a\.mjs"/);
  assert.doesNotMatch(route, /cut_at_utc|"version"/);
});

Grid Explorer Proof

A JavaScript module in the tools folder of GridAtlas that reads station, using SHA-256. It proves explorer generation (`proveExplorerGeneration`).

automationgridatlas / tools/release/grid-explorer-proof.mjs · lines 1–53 of 53 · Not reached from any entry point (candidate for review)

What it does
It loads station. Defines read, hash, proveExplorerGeneration. Uses libraries node:fs, node:path, node:assert/strict, node:url, 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 station-source.json.
Downstream impact
Used directly by 4 files: Grid Journey Preview Proof (gridatlas); Grid Vicinity Proof (gridatlas); UK Gazetteer Flyto Proof (gridatlas); Cut Grid Explorer (gridatlas).
What it achieves
Defines `read`, `hash` and `proveExplorerGeneration`. It reads `tools/train/station-source.json`.
Why it matters
Imported by Grid Journey Preview Proof, Grid Vicinity Proof and UK Gazetteer Flyto Proof. Run by Cut Grid Explorer.
Application
gridatlas · tools/release · JavaScript module
Uses
GridAtlas — Release (script call), Single-Line Diagram (SLD) Build (script call), Build (script call), Build (script call), Build (script call), Build (script call), node:fs, node:path, node:assert/strict, node:url, node:crypto, node:child_process, node:vm
Used by
imported by Grid Journey Preview Proof (import), imported by Grid Vicinity Proof (import), imported by UK Gazetteer Flyto Proof (import), run by Cut Grid Explorer (script call)
Produces
proveExplorerGeneration
Defines here
read, hash, proveExplorerGeneration
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/grid-explorer-proof.mjs:1-53 · blob 4701460e547246ba23c5a88f68b2b745e7c9311b · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {fileURLToPath} from 'node:url';
import {createHash} from 'node:crypto';
import {execFileSync} from 'node:child_process';
import vm from 'node:vm';
import {deriveCurrent, rerootForPreview} from './lib.mjs';
import {buildSld} from '../sld/build.mjs';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const read = p => fs.readFileSync(path.join(root, p), 'utf8').replace(/\r\n/g, '\n');
const hash = b => createHash('sha256').update(b).digest('hex');
export async function proveExplorerGeneration(G, id) {
  const manifestText = read(`atlas/manifests/${G}-composition.json`), m = JSON.parse(manifestText);
  const parent = JSON.parse(read(`atlas/manifests/${m.parent_generation}-composition.json`));
  assert.equal(m.generation, G); assert.equal(m.version, m.composition_version);
  for (const field of ['previous_generation', 'superseded_generation', 'candidate_predecessor']) assert.equal(m[field], parent.generation);
  assert.equal(read(`atlas/v/${G}/current.json`), rerootForPreview(deriveCurrent(manifestText)));
  assert.equal(read(`atlas/v/${G}/index.html`), read('atlas/index.html'));
  assert.equal(m.acceptance.full_application_copies_created, 0); assert.equal(m.acceptance.immutable_shell_modified, false);
  assert.equal(m.acceptance.real_connections_inferred, 0);
  assert.equal(execFileSync('git', ['rev-parse', 'HEAD:atlas/releases'], {cwd: root, encoding: 'utf8'}).trim(), m.acceptance.immutable_releases_tree);
  assert.deepEqual(fs.readdirSync(path.join(root, `atlas/v/${G}`)).sort(), ['current.json', 'index.html']);
  for (const c of m.cartridges) {
    const source = read('atlas/' + c.path); assert.equal(hash(source), c.sha256, c.id);
    if (String(c.generation) !== G) assert.deepEqual(c, parent.cartridges.find(p => p.id === c.id), `Parent cartridge ${c.id}`);
    if (c.bytes != null) assert.equal(Buffer.byteLength(source), c.bytes, c.id);
  }
  const cartridge = m.cartridges.find(c => c.id === id); assert.ok(cartridge); assert.equal(cartridge.generation, G);
  const source = read('atlas/' + cartridge.path); new vm.Script(source);
  if (id === 'sld-sandbox') {
    assert.equal(buildSld(G).toString('utf8'), source);
    assert.ok(source.includes("'Nearest mapped ' + kind")); assert.ok(source.includes('Details'));
  } else if (id === 'grid-journey-preview') {
    const {assembleModule} = await import('../journey/build.mjs');
    assert.equal(assembleModule({generation: G}).body, source); assert.ok(Buffer.byteLength(source) <= cartridge.byte_budget);
  } else if (id === 'grid-vicinity') {
    const {assemble} = await import('../vicinity/build.mjs');
    assert.equal(assemble({generation: G}).body, source); assert.ok(Buffer.byteLength(source) <= cartridge.byte_budget);
    if(fs.existsSync(path.join(root,'tools/train/station-source.json'))){
      const pin=JSON.parse(read('tools/train/station-source.json')),raw=fs.readFileSync(path.join(root,pin.path));
      assert.equal(hash(raw),pin.sha256,'Expected station loader input pin');assert.equal(raw.length,pin.bytes);
      assert.equal(JSON.parse(raw).features.length,pin.features);
    }
  } else if (id === 'substation-intelligence') {
    const {buildSubstation} = await import('../pipeline-lifecycle/build.mjs');
    assert.equal(buildSubstation(G).toString('utf8'), source);
  } else if (id === 'uk-gazetteer-flyto') {
    const {buildGazetteer} = await import('../train/gazetteer/build.mjs');
    assert.equal(buildGazetteer(G).toString('utf8'),source);
  } else throw new Error('Unknown explorer source builder ' + id);
  console.log(`Explorer ${G} ${id}: source rebuild, parent lineage, preview derivation, immutable releases and budget PASS`);
}