GLOBALGRID2050 / EXPLORE CODE

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

CI PR Gate and 1 more file

A JavaScript module in the tools folder of GridAtlas that runs async (`runAsync`), using SHA-256.

643 lines of JavaScript from gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 630 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. Overlay Offtakers Test test · gridatlas / tools/ci/offtakers/overlay-offtakers.test.mjs lines 377–530
  2. CI PR Gate automation · gridatlas / tools/ci/pr-gate.mjs lines 1–489

Overlay Offtakers Test

A test in the tools folder of GridAtlas that checks Minidom and GridAtlas — Index Page, using SHA-256 and haversine.

testgridatlas / tools/ci/offtakers/overlay-offtakers.test.mjs · lines 377–530 of 530 (continued from section 629) · Entry point · pattern origNearest (shared by 2 files)

What it does
It tests the REPD register, solar, wind and battery storage (BESS). Defines 41 functions or classes, including sha, hav, GSSRC, GEO, origNearest. Uses libraries node:test, node:assert/strict, node:vm, node:fs, node:zlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
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: the REPD register, solar, wind, battery storage (BESS), 400kV, 275kV.
Inputs & outputs
In: GeoJSON file grid_substations.geojson; GeoJSON file x.geojson. Voltage levels named: 400kV, 275kV, 132kV, 33kV.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It opens tab (`openTab`) and is built from the orig nearest helper (`origNearest`) and the kV of helper (`kvOf`). Defines `sha`, `hav`, `GSSRC` and 33 more. Its code works with 100 MW, 72 MW and 0 MW. It reads `atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson`.
Why it matters
Guards the behaviour of Minidom and GridAtlas — Index Page.
Application
gridatlas · tools/ci/offtakers · test
Uses
Minidom (import), GridAtlas — Index Page (estate URL), node:test, node:assert/strict, node:vm, node:fs, node:zlib, node:crypto, node:url
Used by
none found
Produces
sha, hav, GSSRC, GEO, origNearest, kvOf, tick, drain, boot, src, qrf, tapMap
Defines here
iSubs, iCV, dcBoot, tabOf, panel, openTab, reveal, lines, sloughDC, byRef
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/ci/offtakers/overlay-offtakers.test.mjs:377-530 · blob 950e90e11a662e397353a54a8da4f7cf40320e81 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
const DSKIP = !DCB && 'module has no data-centre file (before DC-B1)';
const SL = [-0.62, 51.523];
const iSubs = o => SUBS.map(s => ({ s, km: hav(o[0], o[1], s.at[0], s.at[1]) })).filter(v => v.km <= 40).sort((a, b) => a.km - b.km).slice(0, 30);
const iCV = o => (CVD ? CVD.features : []).filter(f => f.properties.in_nearest_default !== false).map(f => ({ f, km: hav(o[0], o[1], ...f.geometry.coordinates) })).sort((a, b) => a.km - b.km).slice(0, 30);
const dcBoot = async o => { const x = boot(o); x.O.install(); x.toggle(true); await drain(); return x; };
const tabOf = (x, v) => x.card().querySelector(`[data-offtakers-tab="${v}"]`);
const panel = x => x.card().querySelector('[data-offtakers-panel]'), prow = x => [...panel(x).querySelectorAll('a')].map(text);
const openTab = async (x, v) => { tabOf(x, v).click(); await drain(5); };
const reveal = async x => { x.card().querySelector('[data-offtakers-reveal]').click(); await drain(5); };
const lines = x => x.sources.get('gridatlas-offtakers-neon-dc-l').data.features, bySet = (x, s) => lines(x).filter(f => f.properties.s === s);
const sloughDC = x => x.S.data.dots.filter(d => d.k === 'c').sort((a, b) => hav(...SL, ...a.a) - hav(...SL, ...b.a))[0];

test('DC1: data centres: the pinned pipeline file once, every site that passes the schema checks, one operator per origin; Slough ≥16 origins within 3 km', { skip: DSKIP }, async () => {
  const x = await dcBoot(); const dc = x.S.data.dots.filter(d => d.k === 'c');
  assert.equal(x.log.xhr.filter(u => u === DCURL).length, 1); assert.ok(SRC.includes(`DCFSHA='${sha(fs.readFileSync(REPO + DCREL))}'`), 'DC file pin');
  assert.equal(dc.length, DCD_MAPPABLE.length);
  // NL-007 P7b: the unplaced records (null geometry) are counted in the file whose sha256 equals the module's DCFSHA, not written as
  // a literal, so the test holds for every pin (the live 202610292044 pins a file with two, 202610312138 one); Ebbsfleet is one of them
  const PINNED = SRC.match(/DCFSHA='([0-9a-f]{64})'/)[1], PFILE = fs.readdirSync(REPO + 'data').filter(n => /\.geojson$/.test(n)).find(n => sha(fs.readFileSync(REPO + 'data/' + n)) === PINNED);
  assert.ok(PFILE, 'a file under data/ matches DCFSHA ' + PINNED); const UNPLACED = JSON.parse(fs.readFileSync(REPO + 'data/' + PFILE, 'utf8')).features.filter(f => f.geometry == null);
  assert.ok(UNPLACED.length > 0, 'the pinned file keeps its unplaced planning records'); assert.equal(x.S.data.pl.bad, UNPLACED.length, 'the module skips exactly the unplaced records of ' + PFILE);
  assert.equal(DCD.features.length - DCD_MAPPABLE.length, UNPLACED.length, 'every unplaced record remains in the source, never drawn');
  assert.ok(UNPLACED.some(f => /Ebbsfleet/.test(f.properties.name)), 'Ebbsfleet is among the unplaced'); assert.ok(!dc.some(d => UNPLACED.some(f => f.properties.id === d.p.id)), 'no unplaced record is drawn');
  assert.ok(dc.length >= 178, 'at least the operational OSM sites');
  assert.ok(dc.every(d => d.dc && d.p.site_kind !== 'cable_landing_station'));
  // one operator per origin: a single operator string (or none); a source naming another operator must be flagged by the file
  // (operator_alternatives, or an operator_disagreement conflict). The pipeline's members trace to DC-A4, where one origin merges two
  // operators (Digital Realty LHR26 / Global Technical Realty; evidence/DC-B1/out/cross-operator.txt), reported to the lead
  for (const d of dc) { assert.ok(d.p.operator == null || typeof d.p.operator === 'string', d.p.id);
    const ops = new Set((d.p.sources || []).map(s => (s.operator || '').toLowerCase()).filter(Boolean)); if (ops.size > 1) assert.ok((d.p.operator_alternatives || []).length || (d.p.conflicts || []).some(c => c.kind === 'operator_disagreement'), 'cross-operator merge not flagged: ' + d.p.id); }
  // #73: source refs for different Slough operators must never share one map origin.
  const byRef = id => dc.find(d => (d.p.sources || []).some(s => s.record_ref === 'gg2050-dc-' + id));
  for (const [a,b] of [[133,237],[193,231],[56,196],[56,57]]) {
    const x=byRef(a),y=byRef(b);
    assert.ok(x&&y,'Slough records '+a+'/'+b+' present');
    assert.notEqual(x.p.id,y.p.id,'cross-operator source merge '+a+'/'+b);
  }
  const sl = dc.filter(d => hav(...SL, ...d.a) <= 3); assert.ok(sl.length >= 16, 'Slough origins ' + sl.length); assert.ok(new Set(sl.map(d => d.a + '')).size >= 16, 'distinct points');
  assert.match(text(x.host.querySelector('[data-offtakers-status]')), new RegExp(`data centres: ${dc.length} from the open pipeline \\(operational ${dc.filter(d => d.t === 'op').length}`));
  assert.ok(x.host.querySelector('[data-offtakers-dc]').querySelector('[data-offtakers-class="c"]'), 'own chip row'); assert.match(text(x.host.querySelector('[data-offtakers-foot]')), /Data centres \(violet\)/);
  assert.match(JSON.stringify(x.layers.get('l-gridatlas-offtakers').paint['circle-stroke-color']), /#39d98a/, 'status ring');
});

test('DC2: a Slough tap: 30 substations = gridScope = independent haversine, first 5 = nearestSubstations; 30 REPD; 30 conventional; nearest 10 drawn, Show all, Draw all; labels ≤ 6', { skip: DSKIP }, async () => {
  const x = await dcBoot(); const r = sloughDC(x); await x.tapDot(r); await drain(); const c = x.card();
  assert.equal(c.getAttribute('aria-label'), 'Data centre'); assert.equal(tabOf(x, 'a').getAttribute('aria-selected'), 'true', 'Area by default');
  assert.equal(c.querySelectorAll('[role="tab"]').length, 4); deq(x.W.__NS__.at(-1), r.a, 'the original nearestSubstations is called at the site');
  assert.equal(x.S.errors.filter(e => /differs/.test(e)).length, 0, 'scope head = nearestSubstations');
  const is = iSubs(r.a), ns = origNearest(r.a[0], r.a[1], SUBS); assert.equal(is.length, 30);
  await openTab(x, 's'); let rows = prow(x); assert.equal(rows.length, 10);
  await reveal(x); rows = prow(x); assert.equal(rows.length, 30);
  is.forEach((v, i) => assert.ok(rows[i].startsWith(`${i + 1}. ${v.km.toFixed(2)} km · ${Math.max(...v.s.kv)} kV`), `sub ${i + 1}: ${rows[i]} vs ${v.km.toFixed(2)}`));
  ns.forEach((v, i) => assert.ok(rows[i].startsWith(`${i + 1}. ${v.km.toFixed(2)} km`), 'head = original ' + i));
  assert.equal(bySet(x, 's').length, 30); deq(bySet(x, 's').map(f => f.geometry.coordinates[1]), is.map(v => v.s.at));
  // a voltage chip re-ranks within its band from the whole 40 km scope (not from the 30): 275 kV here
  panel(x).querySelector('[data-offtakers-volt="275"]').click(); await drain(5); const i275 = SUBS.map(q => ({ q, km: hav(r.a[0], r.a[1], q.at[0], q.at[1]) })).filter(v => v.km <= 40 && Math.max(...v.q.kv) >= 274.5 && Math.max(...v.q.kv) < 399.5).sort((a, b) => a.km - b.km);
  rows = prow(x); assert.ok(i275.length > 0); assert.equal(rows.length, Math.min(30, i275.length)); i275.slice(0, 30).forEach((v, i) => assert.ok(rows[i].startsWith(`${i + 1}. ${v.km.toFixed(2)} km · ${Math.max(...v.q.kv)} kV`), `275 ${i + 1}: ${rows[i]}`));
  assert.ok(i275[0].km > is[29].km || !is.some(v => Math.max(...v.s.kv) >= 274.5 && Math.max(...v.s.kv) < 399.5), 'the band reaches past the 30 of All');
  panel(x).querySelector('[data-offtakers-volt="all"]').click(); await drain(5);
  await openTab(x, 'r'); const ir = indep(r, { st: 'all', te: 'all' }, 30); rows = prow(x); assert.equal(rows.length, 10); await reveal(x); rows = prow(x);
  assert.equal(rows.length, ir.length); assert.ok(ir.length >= 30); ir.forEach((g, i) => assert.ok(rows[i].startsWith(`${i + 1}. ${g.km.toFixed(2)} km`), `repd ${i + 1}: ${rows[i]}`));
  await openTab(x, 'v'); const ic = iCV(r.a); rows = prow(x); assert.equal(rows.length, 10); await reveal(x); rows = prow(x); assert.equal(rows.length, 30);
  ic.forEach((v, i) => assert.ok(rows[i].startsWith(`${i + 1}. ${v.km.toFixed(2)} km`), `conv ${i + 1}: ${rows[i]} vs ${v.km.toFixed(2)}`));
  const d = ic.filter(v => v.km <= 100).length; assert.match(text(c), new RegExp(`Lines drawn for ${d} of 30 \\(≤100 km\\)`)); assert.equal(bySet(x, 'v').length, d);
  for (const v of ['a', 's', 'r', 'v']) { await openTab(x, v); const f = x.layers.get('gridatlas-offtakers-neon-dc-label').filter; assert.ok(f[2][1].length <= 6, 'labels ≤ 6 on ' + v); }
  assert.ok(x.S.perf.links >= 60 && x.S.perf.links <= 90 && x.S.perf.ms >= 0, JSON.stringify(x.S.perf));
  await openTab(x, 'a'); assert.match(text(x.card()), /Nearest 400 kV /); assert.match(text(x.card()), /Within \(straight line\)/); assert.match(text(x.card()), /IT load and grid connection not stated/);
  const eases = x.camera.filter(q => q[0] === 'easeTo'); assert.ok(eases.length >= 1); for (const [, [o]] of eases) { assert.equal(o.padding, undefined, 'no persistent padding'); assert.ok(o.offset[1] < 0, 'the site sits in the band above the card'); assert.ok(o.zoom >= 7.5 && o.zoom <= 13); }
  const k = x.layers.get('gridatlas-offtakers-neon-dc-core-r').paint['line-dasharray']; deq(k, [2, 2]); assert.equal(x.layers.get('gridatlas-offtakers-neon-dc-core-s').paint['line-color'], '#ffccee');
});

test('DC3: default: nearest 10 of each set drawn; "Draw all" draws every listed link within reach; tab keys move the selection', { skip: DSKIP }, async () => {
  const x = await dcBoot(); const r = sloughDC(x); await x.tapDot(r); await drain();
  assert.equal(bySet(x, 's').length, 10); assert.equal(bySet(x, 'r').length, 10); assert.equal(bySet(x, 'v').length, iCV(r.a).slice(0, 10).filter(v => v.km <= 100).length);
  x.card().querySelector('[data-offtakers-draw-all]').click(); await drain(5);
  assert.equal(bySet(x, 's').length, 30); assert.equal(bySet(x, 'r').length, indep(r, { st: 'all', te: 'all' }, 30).length); assert.equal(bySet(x, 'v').length, iCV(r.a).filter(v => v.km <= 100).length);
  const tl = x.card().querySelector('[role="tablist"]'); tl.listeners.keydown[0]({ key: 'End' }); assert.equal(tabOf(x, 'v').getAttribute('aria-selected'), 'true');
  x.card().querySelector('[role="tablist"]').listeners.keydown[0]({ key: 'ArrowRight' }); assert.equal(tabOf(x, 'a').getAttribute('aria-selected'), 'true');
});

test('DC4: a remote site: conventional always lists 30 (any distance) and draws only ≤100 km; short substation and REPD sets say so', { skip: DSKIP }, async () => {
  const x = await dcBoot(); const r = x.S.data.dots.find(d => d.k === 'c'); r.a = [-1.2, 60.3]; await x.tapDot(r); await drain();
  await openTab(x, 'v'); await reveal(x); const ic = iCV(r.a), rows = prow(x); assert.equal(rows.length, 30); assert.ok(ic[29].km > 100);
  assert.equal(bySet(x, 'v').length, ic.filter(v => v.km <= 100).length); assert.ok(rows.some(t => / · not drawn/.test(t)));
  await openTab(x, 's'); const t = text(x.card()); assert.ok(/Only \d+ substations ≥33 kV within 40 km/.test(t) || /None within 40 km\. Nearest: /.test(t), t.slice(0, 200));
});

test('DC5: CSV: four comment lines and the header; the site, every listed substation, REPD project and conventional site; licences; drawn flag; no formula cells', { skip: DSKIP }, async () => {
  const x = await dcBoot(); const r = sloughDC(x); await x.tapDot(r); await drain();
  x.card().querySelector('[data-offtakers-csv]').click(); await drain(); const csv = x.blobs.at(-1).text, L = csv.trim().split('\n');
  assert.match(L[0], new RegExp(`^# GridAtlas data-centre vicinity sheet · generation ${x.O.generation} · site ${r.p.id}`)); assert.match(L[1], /Not cable routes, capacity, headroom, connection offers or feasibility/);
  assert.match(L[2], /IT load not stated · grid connection not stated\. Never added together/); assert.equal(L[4], 'set,rank,name,ref,type_or_voltage,status,kv_max,kv_all,mw_stated,mw_basis,km_straight_line,lon,lat,drawn_on_map,source,licence,data_date');
  const rows = L.slice(5).map(l => l.match(/("([^"]|"")*"|[^,]*)(,|$)/g).map(v => v.replace(/,$/, ''))), n = s => rows.filter(c => c[0] === s).length;
  const parts = indep(r, { st: 'all', te: 'all' }, 30).reduce((s, g) => s + g.parts.length, 0);
  assert.equal(n('data centre'), 1); assert.equal(n('substation'), 30); assert.equal(n('REPD project'), parts); assert.equal(n('conventional'), 30);
  for (const c of rows) { assert.ok(c[15], 'licence ' + c); assert.ok(!/^[=+\-@]/.test(c[2]), 'no formula'); }
  assert.equal(rows.filter(c => c[0] === 'substation' && c[13] === 'yes').length, 10, 'drawn flag follows the map');
  assert.equal(rows.find(c => c[0] === 'data centre')[8], 'not stated', 'IT load not stated, never 0');
});

test('DC6: cleanup: OFF removes every data-centre source, layer, ring and card; cycles leave nothing; no error noted', { skip: DSKIP }, async () => {
  const x = boot(); x.O.install(); const h0 = x.handlers.length;
  for (let k = 0; k < 3; k++) { x.toggle(true); await drain(); await x.tapDot(sloughDC(x)); await drain(); assert.ok(x.sources.get('gridatlas-offtakers-neon-dc-rings'));
    x.toggle(false); assert.equal(x.card(), null); assert.equal([...x.sources.keys()].filter(OTIDS).length, 0); assert.equal([...x.layers.keys()].filter(OTIDS).length, 0); assert.equal(x.handlers.length, h0); assert.equal(x.rafs.size, 0); }
  assert.equal(x.errs.length, 0); assert.equal(x.S.errors.length, 0, x.S.errors.join('; '));
});

test('DC7: a failed data-centre file keeps the offtakers data centres and says why; a failed conventional file falls back to the power-station class and says so', { skip: DSKIP }, async () => {
  const x = await dcBoot({ tamper: DCREL.split('/').pop() }); assert.equal(x.S.data.dots.filter(d => d.k === 'c').length, 164);
  assert.match(text(x.host.querySelector('[data-offtakers-status]')), /data-centre file not loaded: data check failed/);
  const r = x.S.data.dots.find(d => d.k === 'c'); await x.tapDot(r); await drain(); assert.match(text(x.card()), /Status: not tracked/);
  const y = await dcBoot({ tamper: CVREL.split('/').pop() }); await y.tapDot(sloughDC(y)); await drain(); await openTab(y, 'v');
  assert.match(text(y.card()), /From the offtakers power-station class \(the conventional dataset is not loaded: data check failed/); assert.equal(prow(y).length, 10);
});

test('DC8: isolation: no gridScope → "not loaded yet" (no throw); lightning stays installed and working; non-data-centre taps keep 15 REPD + 5 substations', { skip: DSKIP }, async () => {
  const x = await dcBoot({ gridScope: false, lightning: true }); await x.tapDot(sloughDC(x)); await drain(); await openTab(x, 's');
  assert.match(text(x.card()), /Substation data not loaded yet; trying again\./); x.ltoggle(true); await drain(); assert.equal(x.W.__LP__.S.on, true);
  const y = await dcBoot(); const rf = bigSites(y).refinery; await y.tapDot(rf); await drain();
  assert.equal(y.sources.get('gridatlas-offtakers-neon-subs').data.features.length, 5); assert.equal(rowsOf(y.card()).length, indep(rf).length); assert.equal(y.sources.get('gridatlas-offtakers-neon-dc-l'), undefined);
});

test('DC9: rows open their own card; ◀ back to data centre restores the tab', { skip: DSKIP }, async () => {
  const x = await dcBoot(); await x.tapDot(sloughDC(x)); await drain(); await openTab(x, 'r');
  panel(x).querySelector('a').click(); await drain(); assert.equal(x.card().getAttribute('aria-label'), 'REPD project'); assert.match(text(x.card()), /◀ back to data centre/);
  x.card().querySelector('[data-offtakers-back]').click(); await drain(); assert.equal(x.card().getAttribute('aria-label'), 'Data centre'); assert.equal(tabOf(x, 'r').getAttribute('aria-selected'), 'true');
  await openTab(x, 's'); panel(x).querySelector('a').click(); await drain(); assert.equal(x.card().getAttribute('aria-label'), 'Substation');
  assert.match(text(x.card()), /5 nearest REPD sites to this substation/); x.card().querySelector('[data-offtakers-back]').click(); await drain(); assert.equal(tabOf(x, 's').getAttribute('aria-selected'), 'true');
  await openTab(x, 'v'); panel(x).querySelector('a').click(); await drain(); assert.equal(x.card().getAttribute('aria-label'), 'Conventional power site'); assert.match(text(x.card()), /nearest substations to this site/);
});

test('DC10: schema checks and the URL allow-list: bad records are skipped and counted, never repaired; Marchwood is gas', { skip: DSKIP }, async () => {
  const x = await dcBoot(); const P = x.P, ok = { id: 'DC-X-1', name: 'A', status: 'operational', sources: [{ licence: 'ODbL 1.0' }] }, pt = (p, c = [-0.6, 51.5]) => ({ type: 'Feature', geometry: { type: 'Point', coordinates: c }, properties: p });
  const r = P.dn([pt(ok), pt({ ...ok, sources: [{ licence: 'CC BY-NC 4.0' }] }), pt({ ...ok, sources: [{ licence: 'CC BY-ND 4.0' }] }), pt(ok, [5, 40]), pt({ ...ok, id: 'x y' }), pt({ ...ok, sources: 'x' }), pt({ ...ok, site_kind: 'cable_landing_station' }), null]);
  assert.equal(r.o.length, 1); assert.equal(r.bad, 6); assert.equal(r.cl, 1);
  const q = P.cn([pt({ ...ok, mw: -3, fuel: 'unstated', status: 'odd' }), pt({ ...ok, in_nearest_default: false }), pt({ ...ok, mw: 1e9 })]);
  assert.equal(q.o.length, 2); assert.equal(q.o[0].mw, null); assert.equal(q.o[0].f, 'fuel not stated'); assert.equal(q.o[0].st, 'status unknown'); assert.equal(q.o[1].mw, null);
  assert.throws(() => P.AL('https://example.com/x.geojson'), /not allow-listed/); assert.throws(() => P.AL('https://ventusltd.github.io/gridatlas/data/../x.js'), /not allow-listed/);
  const m = x.S.data.dots.find(d => d.p.id === 'OT-B-0823'); assert.equal(m.p.subclass, 'gas_ccgt_large'); await x.tapDot(m); await drain(); assert.match(text(x.card()), /Marchwood .*gas CCGT large/); assert.equal(/biomass/.test(text(x.card()).split('Within 5 km')[0]), false);
  assert.ok(!/https:\/\/(?!ventusltd\.github\.io\/gridatlas\/data\/)/.test(SRC.replace(/\/\*[\s\S]*?\*\//g, '')), 'no other host in the bytes');
});

test('DC11: MW wording: IT load and grid connection apart, never derived or added; an unlabelled MW is quoted with its own label and never sizes the dot', { skip: DSKIP }, async () => {
  const x = await dcBoot(), D = n => x.S.data.dots.find(d => d.k === 'c' && new RegExp(n).test([d.p.name,...(d.p.aliases||[])].join(' ')));
  const q = D('QuestPit'), c = D('Court Lane'), mf = D('Manor Farm');
  assert.ok(q && c && mf, 'the pinned pipeline has the DC-A3 sites QuestPit, Court Lane (Iver) and Manor Farm (Slough)');
  await x.tapDot(q); await drain(); assert.match(text(x.card()), /IT load 720 MW · grid connection 200 MW/); assert.equal(q.z, 2);
  await x.tapDot(c); await drain(); assert.match(text(x.card()), /Grid connection 140 MW · IT load not stated/);
  await x.tapDot(mf); await drain(); const t = text(x.card()); assert.match(t, /IT load 72 MW · grid connection not stated/); assert.match(t, /Also stated: 100 MW, not said to be IT load or grid connection \(battery energy storage capacity \(BESS\); not data-centre load\); not added to either\./);
  assert.equal(mf.z, 1.6, 'sized by the 72 MW IT load, not the 100 MW battery');
  const un = x.S.data.dots.filter(d => d.k === 'c' && d.p.unclassified_mw && d.p.unclassified_mw.value > 0 && !(d.p.it_load_mw && d.p.it_load_mw.value) && !(d.p.grid_connection_mw && d.p.grid_connection_mw.value));
  assert.ok(un.length >= 1, 'a site with only an unlabelled MW'); for (const d of un) assert.equal(d.z, 1, 'an unlabelled MW never sizes the dot: ' + d.n); assert.match(t, /A pipeline entry is not a commitment/);
  assert.equal(/\b(172|212|243) MW\b/.test(t), false, 'never summed');
});

CI PR Gate

A JavaScript module in the tools folder of GridAtlas that runs async (`runAsync`), using SHA-256.

automationgridatlas / tools/ci/pr-gate.mjs · lines 1–489 of 489 · Entry point · pattern group (shared by 18 files)

What it does
It loads data. Defines 13 functions or classes, including record, run, tail, group, step. Uses libraries node:fs, node:os, node:path, node:child_process, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage field_execution (path word 'gate'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: JSON file current.json; command-line arguments.
Downstream impact
Used directly by 2 files: Map Promotion Rehearsal (gridatlas); GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
It is built from the record step (`record`), the run step (`run`) and the tail step (`tail`). The pull-request gate: every check that was run by hand before a cut, run by the runner on every PR to main.
Why it matters
Run by Map Promotion Rehearsal and GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/ci · JavaScript module
Uses
GridAtlas — Scope (script call), Loop (script call), Regional Interface Test (script call), Convergence 2km Test (script call), Convergence Preview (script call), Run Current (script call), Verify Compose (script call), Loader Swap (script call), and 7 more, node:fs, node:os, node:path, node:child_process, node:url
Used by
run by Map Promotion Rehearsal (script call), run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
record, run, tail, group, step, baseHas, check, runAsync, overlayFile, overlayGenerationOf, offFile, modOf
Defines here
record, run, tail, group, step, baseHas, check, runAsync, overlayFile, overlayGenerationOf, offFile, modOf, add
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/ci/pr-gate.mjs:1-489 · blob b93a4c5c716797c0822e66d1d21bed342af086a4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
/**
 * The pull-request gate: every check that was run by hand before a cut,
 * run by the runner on every PR to main. Node built-ins only, no browser,
 * no network, no secrets. See docs/CI.md.
 *
 *   node tools/ci/pr-gate.mjs                    # diff against origin/main
 *   node tools/ci/pr-gate.mjs --base <sha>       # diff against a given commit
 *
 * Checks, in order; every check runs even after an earlier one fails, so one
 * run reports everything that is wrong:
 *
 *   lint              node tools/scope/loop.mjs lint
 *   state-parity      node tools/scope/loop.mjs state --stdout == STATE.md
 *   generations       for every generation the PR touches, and the one
 *                     atlas/current.json points to: its pinned composition
 *                     (atlas/v/<gen>/current.json) hashes, and every
 *                     tools/proofs/<gen>-*.proof.mjs
 *   run-current       node tools/proofs/run-current.mjs
 *   verify-compose    node tools/scope/verify-compose.mjs
 *   loader-registry   atlas/index.html and every atlas/v/<gen>/index.html is
 *                     byte-identical to a registered loader
 *                     (tools/scope/lib.mjs ATLAS_LOADERS) that supports every
 *                     slot its own current.json uses; a loader that exists at
 *                     the base is never rewritten, and atlas/index.html
 *                     changes with atlas/current.json, to the loader of
 *                     the generation going live (docs/LIGHTNING-CARTRIDGE.md),
 *                     or alone, to a registered loader proven to compose the
 *                     unchanged live pointer byte for byte as the base's
 *                     loader does (tools/release/loader-swap.mjs check)
 *   loader-equivalence  tools/proofs/loader-equivalence.proof.mjs
 *   lightning-source  node tools/lightning/build.mjs --check: the newest
 *                     lightning overlay generation is listed in
 *                     tools/lightning/generations.json, and every listed
 *                     generation rebuilds from tools/lightning/src byte for
 *                     byte (docs/LIGHTNING-SOURCE.md)
 *   offtakers-source  node tools/offtakers/build.mjs --check (the same, for the
 *                     potential-offtakers overlay; docs/OFFTAKERS-SOURCE.md)
 *   lightning-suites  tools/ci/lightning/*.test.mjs against the live overlay
 *                     module, every overlay module the PR adds or edits, the
 *                     overlay of every pinned generation the PR adds, and,
 *                     when the PR changes a suite or this gate, the newest
 *                     pinned overlay; a suite marked
 *                     `@gate-min-generation <stamp>` skips older modules
 *   offtakers-suites  tools/ci/offtakers/*.test.mjs once per (offtakers module,
 *                     lightning module) pair composed by the live pointer, by a
 *                     pinned composition the PR adds or edits, or by one that
 *                     composes an overlay module the PR adds or edits (and the
 *                     newest such composition when the PR changes a suite, the
 *                     source or this gate), each with that composition's OWN
 *                     lightning module; an uncomposed module runs against
 *                     the suite's default lightning module
 *   release-tools     node --check of every tools/release/*.mjs and
 *                     node --test tools/release/*.test.mjs (offline)
 *   twin              when the PR touches atlas/, data/, compiler/ or tools/
 *                     (docs/CI.md, "Twin, preservation and keys"), offline:
 *                     preservation  tools/twin/preserve.mjs --base: every
 *                                   published generation, shell and data file
 *                                   keeps its recorded sha256, the previous
 *                                   live generation still composes, nothing
 *                                   published at the base is edited or removed
 *                     twin-offline  tools/twin/replicate-generation.mjs
 *                                   --offline: the live generation's pins agree
 *                                   and the cartridges it cut rebuild byte for
 *                                   byte (the data rebuild needs the source and
 *                                   Python: the workflow's twin job, after this)
 *                     keys          tools/twin/keys.mjs --check: every claim in
 *                                   the newest register of keys still holds
 *
 * A generation is "touched" when a changed path under atlas/ or tools/proofs/
 * carries its twelve-digit stamp as a path segment or a filename prefix.
 * A NEW pinned generation (atlas/v/<gen>/current.json added by the PR) with no
 * proof is a failure, as run-current already treats a composed cartridge with
 * no proof. Historical generations that never had a proof are reported, not
 * failed: nothing can be run for them.
 */

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn, spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
// The same served-bytes digest every other verifier in this repository uses.
import { sha256PublishedFile as sha256Published, registeredLoader, slotsUsed } from '../scope/lib.mjs';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const STAMP = /^\d{12}$/;
const PROOF_TIMEOUT_MS = 180_000;

const args = process.argv.slice(2);
const baseFlag = args.indexOf('--base');
const BASE = baseFlag >= 0 ? args[baseFlag + 1] : 'origin/main';

const results = [];
function record(name, ok, detail = '') {
  results.push({ name, ok, detail });
  console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? `  ${detail}` : ''}`);
  // An annotation shows on the PR itself, without opening the log.
  if (!ok && process.env.GITHUB_ACTIONS) console.log(`::error title=PR gate: ${name}::${String(detail).replace(/\r?\n/g, ' ')}`);
}

function run(argv, opts = {}) {
  const r = spawnSync(argv[0], argv.slice(1), {
    cwd: ROOT, encoding: 'utf8', timeout: PROOF_TIMEOUT_MS,
    maxBuffer: 64 * 1024 * 1024, ...opts
  });
  return { code: r.status ?? (r.signal ? 124 : 1), stdout: r.stdout || '', stderr: r.stderr || '', error: r.error };
}

// The line that says what went wrong: the first Error/FAIL line if there is
// one (an assertion's stack ends in '}', which says nothing), else the last.
function tail(text, lines = 6) {
  const all = text.trim().split(/\r?\n/);
  const hit = all.find(l => /(Error|FAIL|mismatch|missing)\b/.test(l));
  return (hit ? [hit.trim()] : all.slice(-lines)).join(' ').slice(0, 400);
}

function group(title, fn) {
  if (process.env.GITHUB_ACTIONS) console.log(`::group::${title}`);
  try { return fn(); } finally { if (process.env.GITHUB_ACTIONS) console.log('::endgroup::'); }
}

function step(name, argv) {
  return group(name, () => {
    const r = run(argv);
    process.stdout.write(r.stdout);
    process.stderr.write(r.stderr);
    record(name, r.code === 0, r.code === 0 ? '' : `exit ${r.code}: ${tail(r.stderr || r.stdout, 3)}`);
    return r;
  });
}

// ---------------------------------------------------------------- the diff
const diff = run(['git', 'diff', '--name-only', '--no-renames', BASE]);
if (diff.code !== 0) {
  console.error(`cannot diff against ${BASE}: ${diff.stderr.trim()}`);
  console.error('fetch the base first (git fetch origin main) or pass --base <sha>');
  process.exit(2);
}
const changed = diff.stdout.split('\n').map(s => s.trim()).filter(Boolean);
const baseHas = file => run(['git', 'cat-file', '-e', `${BASE}:${file}`]).code === 0;
console.log(`base ${BASE}; ${changed.length} changed path(s)`);

const current = JSON.parse(fs.readFileSync(path.join(ROOT, 'atlas', 'current.json'), 'utf8'));
const touched = new Set();
for (const file of changed) {
  if (!file.startsWith('atlas/') && !file.startsWith('tools/proofs/')) continue;
  if (file.startsWith('atlas/releases/')) continue; // immutable shells, not generations
  for (const segment of file.split('/')) {
    const stamp = segment.slice(0, 12);
    if (STAMP.test(stamp) && (segment.length === 12 || segment[12] === '-')) touched.add(stamp);
  }
}
const generations = new Set([...touched, String(current.generation)]);
console.log(`generations under test: ${[...generations].sort().join(', ')}` +
  ` (touched: ${[...touched].sort().join(', ') || 'none'}; live: ${current.generation})`);

// ---------------------------------------------------------------- 1, 2
step('lint', ['node', 'tools/scope/loop.mjs', 'lint']);

group('state-parity', () => {
  const r = run(['node', 'tools/scope/loop.mjs', 'state', '--stdout']);
  const committed = fs.readFileSync(path.join(ROOT, 'STATE.md'), 'utf8');
  const ok = r.code === 0 && r.stdout === committed;
  record('state-parity', ok, ok ? '' : r.code !== 0
    ? `state --stdout exit ${r.code}: ${tail(r.stderr, 3)}`
    : 'STATE.md differs from `node tools/scope/loop.mjs state --stdout`; regenerate it in the same commit');
});

step('regional-interface-contract', ['node', '--test', 'tools/secondary/regional-interface.test.mjs']);

// Candidate SatNav proof is part of the existing mandatory gate, not a
// tenth active workflow. Once present it runs on every PR.
if (fs.existsSync(path.join(ROOT, 'tools/satnav/guidance/convergence-2km.test.mjs'))) {
  step('satnav-convergence-geometry', ['node','--test','tools/satnav/guidance/convergence-2km.test.mjs']);
  step('satnav-convergence-preview-syntax', ['node','--check','tools/satnav/guidance/convergence-preview.mjs']);
  for (const file of ['waypoint-map','gate-walk']) {
    step('satnav-convergence-' + file + '-syntax', ['node','--check','atlas/modules/satnav-convergence-2km-' + file + '.js']);
  }
}

// ---------------------------------------------------------------- 3
const proofsDir = path.join(ROOT, 'tools', 'proofs');
const proofFiles = fs.readdirSync(proofsDir).filter(f => /^\d{12}-.+\.proof\.mjs$/.test(f));
for (const gen of [...generations].sort()) {
  group(`generation ${gen}`, () => {
    const pinned = path.join(ROOT, 'atlas', 'v', gen, 'current.json');
    const isLive = gen === String(current.generation);
    if (fs.existsSync(pinned)) {
      const failures = [];
      let composition;
      try { composition = JSON.parse(fs.readFileSync(pinned, 'utf8')); }
      catch (e) { failures.push(`unreadable: ${e.message}`); }
      if (composition) {
        if (String(composition.generation) !== gen) failures.push(`declares generation ${composition.generation}`);
        const byId = new Map((composition.cartridges || []).map(c => [c.id, c]));
        for (const id of composition.cartridge_order || []) {
          const c = byId.get(id);
          if (!c) { failures.push(`${id}: in cartridge_order but not in cartridges`); continue; }
          const file = path.resolve(path.dirname(pinned), c.path);
          if (!file.startsWith(path.join(ROOT, 'atlas') + path.sep)) { failures.push(`${id}: path escapes atlas/`); continue; }
          if (!fs.existsSync(file)) { failures.push(`${id}: ${path.relative(ROOT, file)} missing`); continue; }
          if (sha256Published(file) !== c.sha256) failures.push(`${id}: SHA-256 mismatch for ${path.relative(ROOT, file)}`);
        }
      }
      record(`composition ${gen}`, failures.length === 0, failures.join('; '));
    }
    const proofs = proofFiles.filter(f => f.startsWith(`${gen}-`)).sort();
    if (!proofs.length) {
      const isNew = fs.existsSync(pinned) && !baseHas(`atlas/v/${gen}/current.json`);
      if (isNew || isLive) record(`proof ${gen}`, false, `no tools/proofs/${gen}-*.proof.mjs for a ${isLive ? 'live' : 'new pinned'} generation`);
      else console.log(`note  ${gen}: historical generation with no proof; nothing to run`);
      return;
    }
    for (const proof of proofs) {
      const r = run(['node', path.join('tools', 'proofs', proof)]);
      process.stdout.write(r.stdout);
      process.stderr.write(r.stderr);
      record(`proof ${proof}`, r.code === 0, r.code === 0 ? '' : `exit ${r.code}: ${tail(r.stderr || r.stdout, 3)}`);
    }
  });
}

// ---------------------------------------------------------------- 4, 5
step('run-current', ['node', 'tools/proofs/run-current.mjs']);
step('verify-compose', ['node', 'tools/scope/verify-compose.mjs']);

// ---------------------------------------------------------------- 6
group('loader-registry', () => {
  const vDir = path.join(ROOT, 'atlas', 'v');
  const dirs = fs.existsSync(vDir) ? fs.readdirSync(vDir).filter(d => STAMP.test(d)).sort() : [];
  const bad = [];
  const count = {};
  const check = (indexRel, currentRel) => {
    const loader = registeredLoader(path.join(ROOT, indexRel));
    if (!loader) { bad.push(`${indexRel} is not a registered loader`); return; }
    count[loader.name] = (count[loader.name] || 0) + 1;
    let pointer;
    try { pointer = JSON.parse(fs.readFileSync(path.join(ROOT, currentRel), 'utf8')); } catch { return; }
    for (const slot of slotsUsed(pointer)) if (!loader.slots.includes(slot)) bad.push(`${indexRel} (loader ${loader.name}) cannot compose slot ${slot} of ${currentRel}`);
  };
  check('atlas/index.html', 'atlas/current.json');
  for (const d of dirs) {
    const rel = `atlas/v/${d}/index.html`;
    if (!fs.existsSync(path.join(ROOT, rel))) {
      if (fs.existsSync(path.join(vDir, d, 'current.json'))) bad.push(`${rel} missing beside its current.json`);
      continue;
    }
    check(rel, `atlas/v/${d}/current.json`);
  }
  // Existing generations keep the loader bytes they were cut with.
  for (const file of changed) {
    if (/^atlas\/v\/\d{12}\/index\.html$/.test(file) && baseHas(file)) bad.push(`${file} existed at the base and was changed or removed`);
  }
  // The live loader moves either with the pointer, to the loader of the generation going live, or ON ITS OWN
  // (step 1 of a two-step release, docs/RELEASE.md): then it must be a registered loader that composes the
  // unchanged live pointer byte for byte as the base's loader does (tools/release/loader-swap.mjs check).
  if (changed.includes('atlas/index.html')) {
    const liveIndex = path.join(ROOT, 'atlas', 'v', String(current.generation), 'index.html');
    if (!changed.includes('atlas/current.json')) {
      const swap = run(['node', 'tools/release/loader-swap.mjs', 'check', '--base', BASE]);
      process.stdout.write(swap.stdout);
      process.stderr.write(swap.stderr);
      if (swap.code !== 0) bad.push(`atlas/index.html changed without atlas/current.json and is not a proven loader-only change: ${tail(swap.stdout || swap.stderr, 2)}`);
    } else if (!fs.existsSync(liveIndex) || !fs.readFileSync(liveIndex).equals(fs.readFileSync(path.join(ROOT, 'atlas', 'index.html')))) {
      bad.push(`atlas/index.html changed but is not atlas/v/${current.generation}/index.html`);
    }
  }
  record('loader-registry', bad.length === 0, bad.length ? bad.join('; ')
    : `${1 + dirs.length} served loader(s) registered (${Object.entries(count).map(([k, v]) => `${k} ${v}`).join(', ')}); each supports its own composition`);
});
step('loader-equivalence', ['node', 'tools/proofs/loader-equivalence.proof.mjs']);

// ---------------------------------------------------------------- 6b
// The overlay modules are built from tools/lightning/src, not edited in
// atlas/modules/: the newest generation must rebuild from the committed
// source byte for byte, so the source in the repository is the source of
// the bytes that ship.
step('lightning-source', ['node', 'tools/lightning/build.mjs', '--check']);
// The same for the potential-offtakers overlay (tools/offtakers/src, docs/OFFTAKERS-SOURCE.md).
step('offtakers-source', ['node', 'tools/offtakers/build.mjs', '--check']);

// ---------------------------------------------------------------- 7
// Each suite may declare, in its first lines, `// @gate-min-generation <stamp>`:
// the first overlay generation it describes. It is run only against modules of
// that generation or later, because a suite that tests a newer feature (the
// REPD card of 202610282100) is RED by design on the modules before it.
const SUITE_TIMEOUT_MS = 240_000;
function runAsync(argv, opts = {}) {
  return new Promise(resolve => {
    const child = spawn(argv[0], argv.slice(1), { cwd: ROOT, ...opts });
    let stdout = '', stderr = '', timedOut = false;
    child.stdout.on('data', d => { stdout += d; });
    child.stderr.on('data', d => { stderr += d; });
    const t = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, SUITE_TIMEOUT_MS);
    child.on('close', (code, signal) => { clearTimeout(t); resolve({ code: timedOut ? 124 : code ?? (signal ? 1 : 0), stdout, stderr, timedOut }); });
  });
}

const suiteDir = path.join(ROOT, 'tools', 'ci', 'lightning');
const suites = (fs.existsSync(suiteDir) ? fs.readdirSync(suiteDir).filter(f => f.endsWith('.test.mjs')).sort() : [])
  .map(name => {
    const head = fs.readFileSync(path.join(suiteDir, name), 'utf8').slice(0, 2048);
    const min = (head.match(/@gate-min-generation\s+(\d{12})\b/) || [])[1] || null;
    return { name, min };
  });
const overlayFile = g => path.join('atlas', 'modules', `${g}-uk-lightning-overlay.js`);
/* The overlay module a composition serves: its own 'uk-lightning-overlay'
   cartridge (the module file itself, docs/LIGHTNING-CARTRIDGE.md), else the
   module appended to its sld-sandbox, named by the sld-sandbox generation. */
function overlayGenerationOf(pointer) {
  const own = (pointer.cartridges || []).find(c => c.id === 'uk-lightning-overlay');
  const m = own && String(own.path).match(/(\d{12})-uk-lightning-overlay\.js$/);
  if (m) return m[1];
  const sldEntry = (pointer.cartridges || []).find(c => c.id === 'sld-sandbox');
  return sldEntry ? String(sldEntry.generation) : null;
}
// The live overlay, every overlay module the PR adds or edits, and the
// overlay of any pinned generation the PR adds. Not every touched
// generation: the suites were written RED against earlier candidates, so a
// PR that only edits an old proof must not be failed for a module it did
// not change. A PR that changes a suite, this gate or its workflow is also
// run against the newest pinned overlay (the candidate), so a suite edit is
// proven on the module it guards.
const gens = new Set();
const liveOverlay = overlayGenerationOf(current);
if (liveOverlay) gens.add(liveOverlay);
for (const file of changed) {
  const m = file.match(/^atlas\/modules\/(\d{12})-uk-lightning-overlay\.js$/);
  if (m) { gens.add(m[1]); continue; }
  const v = file.match(/^atlas\/v\/(\d{12})\/current\.json$/);
  if (v && !baseHas(file)) {
    gens.add(v[1]);
    try {
      const g = overlayGenerationOf(JSON.parse(fs.readFileSync(path.join(ROOT, file), 'utf8')));
      if (g) gens.add(g);
    } catch { /* the composition check above reports an unreadable pointer */ }
  }
}
const gateChanged = changed.some(f => f.startsWith('tools/ci/lightning/') || f === 'tools/ci/pr-gate.mjs'
  || f === '.github/workflows/pr-file-size-guard.yml');
if (gateChanged) {
  const vDir = path.join(ROOT, 'atlas', 'v');
  const pinned = (fs.existsSync(vDir) ? fs.readdirSync(vDir) : [])
    .filter(d => STAMP.test(d) && fs.existsSync(path.join(vDir, d, 'current.json')) && fs.existsSync(path.join(ROOT, overlayFile(d))))
    .sort();
  if (pinned.length) gens.add(pinned[pinned.length - 1]);
}
const modules = [...gens].sort().map(g => ({ g, file: overlayFile(g) })).filter(m => fs.existsSync(path.join(ROOT, m.file)));

if (!modules.length) console.log('note  no lightning overlay module in the live or touched generations');
else if (!suites.length) record('lightning-suites', false, 'tools/ci/lightning/*.test.mjs missing');
else {
  const jobs = [];
  for (const { g, file } of modules) {
    for (const suite of suites) {
      if (suite.min && g < suite.min) { console.log(`note  ${suite.name} starts at ${suite.min}; not run on ${g}`); continue; }
      jobs.push({ g, file, suite: suite.name });
    }
  }
  if (!jobs.length) record('lightning-suites', false, `no suite applies to ${modules.map(m => m.g).join(', ')}`);
  // The suites spend most of their time waiting on real timers (the 15 s
  // register timeout), not on the CPU, so they run side by side.
  const width = Math.max(2, Math.min(4, os.availableParallelism ? os.availableParallelism() : 2));
  const out = new Array(jobs.length);
  let next = 0;
  await Promise.all(Array.from({ length: Math.min(width, jobs.length) }, async () => {
    while (next < jobs.length) {
      const i = next++, { g, file, suite } = jobs[i], t0 = Date.now();
      const r = await runAsync(['node', '--test', '--test-reporter=tap', path.join('tools', 'ci', 'lightning', suite)], {
        env: { ...process.env, LIGHTNING_MODULE: file, LIGHTNING_TEST_GEN: g }
      });
      out[i] = { ...r, seconds: ((Date.now() - t0) / 1000).toFixed(1) };
    }
  }));
  jobs.forEach(({ g, suite }, i) => group(`lightning ${g} ${suite}`, () => {
    const r = out[i];
    const counts = (r.stdout.match(/^# (pass|fail|skipped) \d+$/gm) || []).join(' ').replace(/# /g, '');
    if (r.code !== 0) { process.stdout.write(r.stdout); process.stderr.write(r.stderr); }
    else console.log(`${suite} on ${g}: ${counts} in ${r.seconds} s`);
    record(`lightning ${g} ${suite}`, r.code === 0,
      `${counts} ${r.seconds} s` + (r.code === 0 ? '' : r.timedOut ? `  timed out after ${SUITE_TIMEOUT_MS / 1000} s` : `  exit ${r.code}`));
  }));
}

// ---------------------------------------------------------------- 8
// tools/ci/offtakers/*.test.mjs, run once per (offtakers module, lightning module) PAIR that a composition actually ships:
// the suite boots both overlays side by side (T1, T11, T13), so it must boot the lightning module the composition pairs
// with the offtakers module, not a fixed reference. The compositions under test: the live one; every pinned composition
// (atlas/v/<gen>/current.json) the PR adds or edits; every pinned composition that composes an offtakers or lightning
// module the PR adds or edits; and, when the PR changes a suite, the offtakers source or this gate, the newest pinned
// composition that composes an offtakers module (older ones, e.g. 202610290400, are historical: the suite has moved on
// with the data and the class defaults, as the lightning suites skip modules below @gate-min-generation). An offtakers module the PR adds that no composition composes yet (and,
// on a suite/source/gate change, the newest module if it is uncomposed) runs against the suite's default lightning module
// (LIGHTNING_MODULE unset), and the check name says so. A composition with an offtakers cartridge but no
// uk-lightning-overlay cartridge also runs against the default, named as such.
{
  const dir = path.join(ROOT, 'tools', 'ci', 'offtakers'), vDir = path.join(ROOT, 'atlas', 'v');
  const OFF = /(\d{12})-uk-offtakers-overlay\.js$/, LIG = /(\d{12})-uk-lightning-overlay\.js$/;
  const offFile = g => path.join('atlas', 'modules', `${g}-uk-offtakers-overlay.js`), ligFile = g => path.join('atlas', 'modules', `${g}-uk-lightning-overlay.js`);
  const modOf = (p, id, re) => { const e = (p.cartridges || []).find(c => c.id === id); const m = e && String(e.path).match(re); return m ? m[1] : null; };
  // every composition on disk that ships an offtakers cartridge, with the lightning module it pairs it with
  const comps = [{ name: 'atlas/current.json', p: current }];
  for (const d of (fs.existsSync(vDir) ? fs.readdirSync(vDir) : []).filter(d => STAMP.test(d)).sort()) {
    const f = path.join('atlas', 'v', d, 'current.json');
    if (fs.existsSync(path.join(ROOT, f))) try { comps.push({ name: f, p: JSON.parse(fs.readFileSync(path.join(ROOT, f), 'utf8')) }); } catch { /* reported above */ }
  }
  const composed = comps.map(c => ({ name: c.name, o: modOf(c.p, 'uk-offtakers-overlay', OFF), l: modOf(c.p, 'uk-lightning-overlay', LIG) })).filter(c => c.o);
  const newest = composed.filter(c => c.name !== 'atlas/current.json').map(c => c.name).sort().at(-1);
  const offChanged = new Set(), ligChanged = new Set(), compChanged = new Set();
  for (const f of changed) {
    let m = f.match(/^atlas\/modules\/(\d{12})-uk-offtakers-overlay\.js$/); if (m) offChanged.add(m[1]);
    m = f.match(/^atlas\/modules\/(\d{12})-uk-lightning-overlay\.js$/); if (m) ligChanged.add(m[1]);
    if (/^atlas\/v\/\d{12}\/current\.json$/.test(f)) compChanged.add(f);
  }
  const wide = changed.some(f => f.startsWith('tools/ci/offtakers/') || f.startsWith('tools/offtakers/') || f === 'tools/ci/pr-gate.mjs');
  const pairs = new Map(); // "o|l" -> { o, l, why: [composition names] }
  const add = (o, l, why) => { const k = `${o}|${l || ''}`; if (!pairs.has(k)) pairs.set(k, { o, l, why: [] }); if (!pairs.get(k).why.includes(why)) pairs.get(k).why.push(why); };
  for (const c of composed) {
    if (c.name === 'atlas/current.json' || compChanged.has(c.name) || offChanged.has(c.o) || (c.l && ligChanged.has(c.l)) || (wide && c.name === newest)) add(c.o, c.l, c.name);
  }
  const uncomposed = new Set([...offChanged].filter(o => !composed.some(c => c.o === o)));
  if (wide) {
    const all = fs.readdirSync(path.join(ROOT, 'atlas', 'modules')).map(n => (n.match(/^(\d{12})-uk-offtakers-overlay\.js$/) || [])[1]).filter(Boolean).sort();
    if (all.length && !composed.some(c => c.o === all.at(-1))) uncomposed.add(all.at(-1));
  }
  for (const o of uncomposed) add(o, null, 'no composition yet');
  const osuites = fs.existsSync(dir) ? fs.readdirSync(dir).filter(f => f.endsWith('.test.mjs')).sort() : [];
  if (!pairs.size) console.log('note  no offtakers overlay module in the live or touched compositions');
  else if (!osuites.length) record('offtakers-suites', false, 'tools/ci/offtakers/*.test.mjs missing');
  else for (const { o, l, why } of [...pairs.values()].sort((a, b) => (a.o + (a.l || '')).localeCompare(b.o + (b.l || '')))) for (const suite of osuites) {
    const name = `offtakers ${o} + ${l ? `lightning ${l}` : 'default lightning'} ${suite}`;
    group(name, () => {
      if (!fs.existsSync(path.join(ROOT, offFile(o)))) return record(name, false, `${offFile(o)} missing (${why.join(', ')})`);
      if (l && !fs.existsSync(path.join(ROOT, ligFile(l)))) return record(name, false, `${ligFile(l)} missing (${why.join(', ')})`);
      const env = { ...process.env, OFFTAKERS_MODULE: offFile(o) };
      if (l) env.LIGHTNING_MODULE = path.join(ROOT, ligFile(l)); else delete env.LIGHTNING_MODULE;
      const t0 = Date.now(), r = run(['node', '--test', '--test-reporter=tap', path.join('tools', 'ci', 'offtakers', suite)], { env, timeout: SUITE_TIMEOUT_MS });
      const counts = (r.stdout.match(/^# (pass|fail|skipped) \d+$/gm) || []).join(' ').replace(/# /g, ''), sec = ((Date.now() - t0) / 1000).toFixed(1);
      if (r.code !== 0) { process.stdout.write(r.stdout); process.stderr.write(r.stderr); } else console.log(`${suite} on ${o} + ${l || 'default lightning'}: ${counts} in ${sec} s`);
      record(name, r.code === 0, `${counts} ${sec} s; ${why.join(', ')}` + (r.code === 0 ? '' : `  exit ${r.code}`));
    });
  }
}
// The delivery-flow tooling (docs/RELEASE.md): its offline unit tests, and a
// syntax check of every script, so a broken release script fails the PR that
// broke it rather than the release that needs it.
group('release-tools', () => {
  const dir = path.join(ROOT, 'tools', 'release');
  if (!fs.existsSync(dir)) return;
  const scripts = fs.readdirSync(dir).filter(f => f.endsWith('.mjs')).sort();
  const bad = scripts.filter(f => run(['node', '--check', path.join('tools', 'release', f)]).code !== 0);
  const tests = scripts.filter(f => f.endsWith('.test.mjs')).map(f => path.join('tools', 'release', f));
  const t = tests.length ? run(['node', '--test', '--test-reporter=tap', ...tests]) : { code: 0, stdout: '' };
  const counts = (t.stdout.match(/^# (pass|fail) \d+$/gm) || []).join(' ').replace(/# /g, '');
  if (t.code !== 0) { process.stdout.write(t.stdout); process.stderr.write(t.stderr || ''); }
  record('release-tools', bad.length === 0 && t.code === 0,
    `${scripts.length} script(s) parse${bad.length ? `; SYNTAX ERROR in ${bad.join(', ')}` : ''}; ${tests.length} test file(s): ${counts || 'none'}`);
});

step('sld-source', ['node', '--test', 'tools/sld/build.test.mjs']);

// ---------------------------------------------------------------- 9
// The twin, preservation and the register of keys (tools/twin/, docs/CI.md). Offline here; the data rebuild from the
// pinned source runs in the workflow's twin job, which needs this gate first (offline first, then network).
if (changed.some(f => /^(atlas|data|compiler|tools)\//.test(f))) {
  step('preservation', ['node', 'tools/twin/preserve.mjs', '--base', BASE]);
  step('twin-offline', ['node', 'tools/twin/replicate-generation.mjs', '--offline']);
  step('keys', ['node', 'tools/twin/keys.mjs', '--check']);
} else console.log('note  twin, preservation, keys: the PR touches none of atlas/, data/, compiler/, tools/; not run');

// ---------------------------------------------------------------- summary
const failed = results.filter(r => !r.ok);
const lines = [
  '## PR gate', '',
  `Base \`${BASE}\`, ${changed.length} changed path(s). Generations under test: ${[...generations].sort().map(g => `\`${g}\``).join(', ')}.`, '',
  '| check | result | detail |', '|---|---|---|',
  ...results.map(r => `| ${r.name} | ${r.ok ? 'PASS' : '**FAIL**'} | ${String(r.detail).replace(/\|/g, '\\|').replace(/\r?\n/g, ' ')} |`), '',
  `${results.length - failed.length}/${results.length} passed.`
];
if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, lines.join('\n') + '\n');
console.log(`\n${results.length - failed.length}/${results.length} checks passed`);
if (process.env.GITHUB_ACTIONS) {
  console.log(`::notice title=PR gate::${results.length - failed.length}/${results.length} passed; generations ${[...generations].sort().join(', ')}; ` +
    results.map(r => `${r.ok ? 'PASS' : 'FAIL'} ${r.name}`).join('; '));
}
if (failed.length) {
  for (const f of failed) console.error(`  FAIL ${f.name}`);
  process.exitCode = 1;
}