GLOBALGRID2050 / EXPLORE CODE

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

Overlay Engine Test and 1 more file

A test in the lightning folder of GridAtlas that checks Minidom and Reference Module F, using SHA-256 and haversine.

553 lines of JavaScript from gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 628 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 Engine Test test · gridatlas / tools/ci/lightning/overlay-engine.test.mjs lines 2101–2505
  2. Overlay Latest Test test · gridatlas / tools/ci/lightning/overlay-latest.test.mjs lines 1–148

Overlay Engine Test

A test in the lightning folder of GridAtlas that checks Minidom and Reference Module F, using SHA-256 and haversine.

testgridatlas / tools/ci/lightning/overlay-engine.test.mjs · lines 2101–2505 of 2505 (continued from section 625) · Entry point · pattern origNearest (shared by 2 files)

What it does
It tests the REPD register and solar. Defines 118 functions or classes, including track, TResponse, iso, ymd, enc. 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, 33kV.
Inputs & outputs
In: GeoJSON file f.geojson; JSON file index.json; JSON file x.json; JSON file 05.json; JSON file 00.json; GeoJSON file uk_lightning.geojson; JSON file g.json; JSON file repd_master.json. Out: interactive map. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid). Voltage levels named: 33kV.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It adds event listener (`addEventListener`), wraps fetch (`wrapFetch`) and dumps card (`dumpCard`). Defines `track`, `TResponse`, `iso` and 109 more. Its code works with 10 MW, 33 kV and 0 MW. It reads `/index.json`.
Why it matters
Guards the behaviour of Minidom and Reference Module F.
Application
gridatlas · tools/ci/lightning · test
Uses
Minidom (import), Reference Module F (new URL import.meta.url), node:test, node:assert/strict, node:vm, node:fs, node:zlib, node:crypto
Used by
none found
Produces
track, TResponse, iso, ymd, enc, flash, feed, dayFile, mkIndex, boot, tapMap, XHR
Defines here
mlCam, emit, stop, backBtn, fly, dots, dotKey, wantDots, installRecords, run, nname, mwOf, recsAt, wantRec, recBlocks, recLines, partsOf, recTap, pts, T, cell
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/lightning/overlay-engine.test.mjs:2101-2505 · blob ae6f8517baf054d0d21ba75a5bb962bfb99bbad2 · 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 x = await flashAt([-1.5, 52], FCx([...bad, pf(-1.5, 52.01, { name: 'Good' })]));
  assert.deepEqual(rowsOf(x).map(r => r.split(' · ').pop()), ['Good']); tapRow(x, 0); await settle(); assert.equal(card(x).getAttribute('aria-label'), 'REPD project');
  const y = await flashAt([-7.5, 49.8], FCx([pf(-7.55716, 49.766807, { name: 'Scilly' }), pf(-1.5, 52)])); assert.match(card(y).textContent, /No REPD site within 40 km/);
});
test('M3R-repd (M2R-repd R1, R3; M2R-data D1, D2): rows within about 10 m are one site; statuses outside the 4 register classes are in no class; repeated records of one scheme count their MW once', async () => {
  const x = await flashAt([-1.5, 52], FCx([pf(-1.5, 52.01, { name: 'Roosecote', capacity: 49 }), pf(-1.500014, 52.01, { name: 'Roosecote 2', capacity: 50, tech: 'bess', raw_tech: 'Battery' }), pf(-1.5, 52.02, { name: 'Next' })]));
  assert.deepEqual(rowsOf(x), ['1.11 km · Battery + Solar 99 MW · 2 projects at this point:', '2.23 km · Solar 10 MW · operational · Next']);
  const y = await flashAt([-1.5, 52], FCx([pf(-1.5, 52.01, { name: 'Refused', status: 'Application Refused' }), pf(-1.5, 52.02, { name: 'Granted', status: 'Planning Permission Granted' })]));
  for (const k of ['st:op', 'st:cc', 'st:pl']) { press(y, k); assert.deepEqual(rowsOf(y), [], k); }
  const fv = { name: 'Feldon Vale Solar Farm', capacity: 49.9 }, z = await flashAt([-1.5, 52], FCx([pf(-1.5, 52.05, { ...fv, status: 'awaiting construction' }), pf(-1.5, 52.05, { ...fv, operator: 'X' })]));
  assert.equal(rowsOf(z)[0], '5.57 km · Solar 49.9 MW · 2 projects at this point:'); assert.match(card(z).textContent, /Within 10 km: 2 projects · 49\.9 MW stated, mixed statuses/);
  assert.equal(z.sources.get('gridatlas-lightning-neon-pnodes').data.features[0].properties.mw, 49.9);
});
test('M3R-diff (M2R-diff MD1): on a short map where L3 could frame clear of a collapsed card, the bottom padding is L3 padding; it is capped only when that fit is impossible', async () => {
  const od = Object.getOwnPropertyDescriptor(El.prototype, 'offsetHeight'); let h = 143; Object.defineProperty(El.prototype, 'offsetHeight', { configurable: true, get() { return h; } });
  try { for (const [H, hh, want] of [[340, 143, null], [659, 521, 389]]) { h = hh; const x = flash0(); installRepd(x, SUBS, FCx([pf(-1.5, 52.3)])); x.mapEl.clientHeight = H; x.map.getBounds = () => ({ contains: () => false }); x.toggle(true); await drain(); tapFlash(x); await settle();
    const fb = x.camera.filter(k => k[0] === 'fitBounds').at(-1); assert.equal(fb[1][1].padding.bottom, want ?? card(x).bb + hh + 24, 'H=' + H); } }
  finally { if (od) Object.defineProperty(El.prototype, 'offsetHeight', od); else delete El.prototype.offsetHeight; }
});
test('M3R-layout (M2R-layout F1-F3): an open card stays below container top + 320 px; a point hidden under the card (though on the map) is reframed; expanding or collapsing the card reframes', async () => {
  const x = flash0(); installRepd(x, SUBS, FCx([pf(-1.5, 52.3)])); x.mapEl._rect = { top: 0, left: 0, right: 393, bottom: 659, width: 393, height: 659 }; x.mapEl.clientHeight = 659; x.mapEl.clientWidth = 393;
  x.map.getBounds = () => ({ contains: () => true }); x.setProj(() => ({ x: 200, y: 600 })); // every end on the map, but under the card
  x.toggle(true); await drain(); tapFlash(x); await settle();
  assert.equal(card(x).style.maxHeight, '296px', 'M6: MX(200, 45 % of 659)');
  assert.ok(x.camera.some(k => k[0] === 'fitBounds'), 'an end under the card is reframed');
  x.setProj(() => ({ x: 200, y: 200 })); x.camera.length = 0; { const dd = card(x).querySelector('details'); dd.open = !dd.open; dispatch(dd, 'toggle', x.log.errors); } /* M6: a real open/close change reframes; the default open does not */
  assert.equal(x.camera.filter(k => k[0] === 'fitBounds').length, 1, 'the details toggle forces a reframe');
});
// ---------------------------------------------------------------- M4-build: no camera move nested inside another (M2R-taps MAJOR M2R-T1)
// MapLibre 3.6.2 camera stand-in: a move stays in flight until finish(); every camera call first stop()s the move in flight,
// and stop() fires `moveend` SYNCHRONOUSLY (Camera._stop -> _onEaseEnd -> _afterEase -> fire), as a natural end does.
// A camera call made while that moveend is being dispatched is NESTED: in the browser it leaves an orphan render frame
// ("this._onEaseFrame is not a function", then "Attempting to run(), but is already running") and the map stops drawing.
// off() removes a once() listener, as MapLibre's Evented.off does for _oneTimeListeners.
const mlCam = x => {
  const once = [], st = { moving: false, inStop: 0, nested: [], moves: 0 };
  const emit = () => { const f = once.splice(0); for (const g of f) g({ type: 'moveend' }); for (const h of x.handlers.filter(h => h.t === 'moveend')) h.f({ type: 'moveend' }); };
  const stop = () => { if (!st.moving) return; st.moving = false; st.inStop++; try { emit(); } finally { st.inStop--; } };
  for (const k of ['fitBounds', 'flyTo', 'easeTo', 'jumpTo']) x.map[k] = (...a) => { if (st.inStop) st.nested.push(k); stop(); x.camera.push([k, a]); st.moves++; if (k === 'jumpTo') emit(); else st.moving = true; };
  x.map.stop = stop; x.map.isMoving = () => st.moving;
  x.map.once = (t, f) => { if (t === 'moveend' && !once.includes(f)) once.push(f); };
  x.map.off = (t, f) => { const i = t === 'moveend' ? once.indexOf(f) : -1; if (i >= 0) once.splice(i, 1); };
  st.pending = () => once.length;
  // a natural end (the last ease frame): moveend fires and no outer move follows, so a framing started there is not nested
  st.finish = async () => { if (st.moving) { st.moving = false; emit(); } await settle(); };
  return st;
};
const backBtn = x => card(x).querySelector('[data-lightning-back]');

test('M4-1 (M2R-taps MAJOR): 8 fast row -> "◀ back" cycles (each before the previous flight ends) never start a camera move inside moveend', async () => {
  const x = await flashAt([-1.5, 52]), cam = mlCam(x); assert.ok(prows(card(x)).length > 1, 'rows');
  // the tap's own flight is in flight again (the stand-in replaced the camera after the tap)
  x.map.flyTo({ center: [-1.5, 52], zoom: 12 }); x.map.once('moveend', () => {});
  for (let i = 0; i < 8; i++) {
    tapRow(x, i % 3); await settle(); assert.ok(backBtn(x), 'project view ' + i);
    dispatch(backBtn(x), 'click', x.log.errors); await settle(); assert.ok(prows(card(x)).length > 1, 'lightning card ' + i);
  }
  assert.deepEqual(cam.nested, [], 'no camera call inside a moveend dispatched by stop()');
  assert.ok(cam.pending() <= 1, 'at most one framing pending, got ' + cam.pending());
  // the last flight ends: the pending framing runs once, outside the stop
  const n0 = x.camera.length; await cam.finish(); await cam.finish();
  assert.deepEqual(cam.nested, []); assert.ok(x.camera.length >= n0, 'framing ran'); assert.deepEqual(x.log.errors.map(String), []);
});

test('M4-2: the suggested regression: a stub stop() that fires moveend synchronously sees no fitBounds inside it (row tap, back, re-tap, details toggle, fit, cluster)', async () => {
  const x = await flashAt([-1.5, 52]), cam = mlCam(x);
  const fly = () => { x.map.flyTo({ center: [-1.5, 52], zoom: 12 }); };
  // a framing is pending on every path below while a flight is in flight; then each path starts a new camera move
  const paths = {
    row: () => tapRow(x, 0),
    back: () => dispatch(backBtn(x), 'click', x.log.errors),
    retap: () => tapFlash(x),
    toggle: () => { const d = card(x).querySelector('details'); d.open = !d.open; dispatch(d, 'toggle', x.log.errors); },
    fit: () => x.click(x.nav('fit')),
    cluster: () => { x.sources.get('gridatlas-lightning').getClusterExpansionZoom = (id, cb) => cb(null, 9);
      x.tapMap([10, 10], { 'gridatlas-lightning-hit': [{ properties: { cluster: true, cluster_id: 7, point_count: 50 }, geometry: { coordinates: [-1.5, 52] } }] }); }
  };
  for (const [k, f] of Object.entries(paths)) {
    if (k === 'back' && !backBtn(x)) { tapRow(x, 0); await settle(); }
    if (k === 'fit' || k === 'cluster') { tapFlash(x); await settle(); assert.equal(cam.pending(), 1, k + ': the tap armed its framing'); } else { fly(); x.map.once('moveend', () => {}); await settle(); }
    // re-arm the module's own framing: a register/back render while moving queues it (RpR) and nz queues one per flight
    const before = cam.nested.length, m0 = cam.moves; f(); await settle();
    assert.equal(cam.nested.length, before, k + ': nested ' + cam.nested.slice(before).join());
    if (k !== 'toggle') assert.ok(cam.moves > m0 || cam.pending() >= 1, k + ': a camera move was made or a framing queued');
  }
  assert.deepEqual(cam.nested, []); assert.deepEqual(x.log.errors.map(String), []);
});

test('M4-3: a framing pending when someone else moves the camera (engine popup, search, a gesture stop) runs after that stop, never inside it, and not while the map moves', async () => {
  const x = await flashAt([-1.5, 52]), cam = mlCam(x);
  tapRow(x, 0); await settle(); assert.ok(cam.moving && cam.pending() >= 1, 'flight in flight, framing pending');
  // a foreign flyTo (not the module): its stop() fires the module's pending moveend synchronously
  const n0 = x.camera.length; x.map.flyTo({ center: [0, 51], zoom: 9 }); await settle();
  assert.deepEqual(cam.nested, [], 'no module camera call inside the foreign stop');
  assert.equal(x.camera.length, n0 + 1, 'the foreign move is not overridden while it runs');
  await cam.finish(); assert.deepEqual(cam.nested, []); assert.deepEqual(x.log.errors.map(String), []);
});
// ---------------------------------------------------------------- M4-build: M2R-camera fix C (landscape / short map dock)
test('M4R-camera (M2R-camera MAJOR-2, fix C): an 852x393 map docks the card right and frames the area to its left; portrait and desktop keep the centred card', async () => {
  const od = Object.getOwnPropertyDescriptor(El.prototype, 'offsetWidth');
  Object.defineProperty(El.prototype, 'offsetWidth', { configurable: true, get() { return 480; } });
  try {
    for (const [w, h, dock] of [[852, 393, true], [393, 659, false], [1280, 800, false]]) {
      let at = { x: 5, y: 5 }; const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installNeon(x, SUBS);
      x.mapEl._rect = { top: 0, left: 0, right: w, bottom: h, width: w, height: h }; x.mapEl.clientWidth = w; x.mapEl.clientHeight = h; x.setProj(() => at);
      x.toggle(true); await drain(); tapFlash(x); await Promise.resolve();
      const c = card(x); assert.equal(!!c.sd, dock, w + 'x' + h); assert.equal(c.style.marginRight, dock ? '0' : 'auto');
      const fb = x.camera.filter(k => k[0] === 'fitBounds').at(-1); assert.ok(fb, 'an end outside the free area is framed'); const p = fb[1][1].padding;
      if (dock) assert.deepEqual([p.top, p.right, p.bottom, p.left], [60, 512, 100, 40]); else assert.deepEqual([p.top, p.right, p.left], [150, 40, 40]);
      if (dock) {
        // an end in the free area left of the docked card needs no fit; an end under the docked card (x > W - 512 + 20) does
        at = { x: 200, y: 200 }; x.camera.length = 0; tapFlash(x); await Promise.resolve(); assert.equal(x.camera.filter(k => k[0] === 'fitBounds').length, 0, 'free area');
        at = { x: w - 300, y: 200 }; x.camera.length = 0; tapFlash(x); await Promise.resolve(); assert.equal(x.camera.filter(k => k[0] === 'fitBounds').length, 1, 'under the docked card');
      }
      assert.deepEqual(x.log.errors.map(String), []);
    }
  } finally { if (od) Object.defineProperty(El.prototype, 'offsetWidth', od); else delete El.prototype.offsetWidth; }
});
// ---------------------------------------------------------------- M4b (owner option): only the listed sites, as REPD-styled dots
// M4b draws the card's listed sites with the engine's glow + core paint (ventus-corev8engine.js:1305-1337) in its own
// gridatlas-lightning-neon-p-glow / -p-dot layers (source -pdots) and never touches a Layers control. These run on M4b
// modules only (the M3 layer tests above run on M3/M4 modules only).
const dots = x => [...(x.sources.get('gridatlas-lightning-neon-pdots') || { data: { features: [] } }).data.features];
const dotKey = f => f.geometry.coordinates.join() + '|' + f.properties.t + '|' + f.properties.c;
const wantDots = sites => sites.flatMap(g => g.parts.map(p => g.a.join() + '|' + p.tech + '|' + (+p.capacity > 0 ? +p.capacity : 0))).sort();
const B4 = M4B ? test : test.skip;

B4('M4b-1 (real register, Doncaster 53.45, -1.05): exactly the parts of the independent brute-force 10 nearest sites are drawn, in the engine REPD style; no Layers control changes', async () => {
  const { x, E } = await boot3(DONC, null, REPD_IND, { userOn: ['wind'] }); E.toggles.length = 0; tapFlash(x, 0); await settle();
  assert.deepEqual(dots(x).map(dotKey).sort(), wantDots(bruteSites(REPD_IND, ...DONC)));
  assert.deepEqual(E.toggles, [], 'no layer switched'); assert.deepEqual(onIds(E), ['wind'], 'the reader layer untouched'); inSync(E);
  const g = x.layers.get('gridatlas-lightning-neon-p-glow'), d = x.layers.get('gridatlas-lightning-neon-p-dot');
  assert.ok(g && d, 'glow + core'); assert.ok(!/^l-/.test(g.id) && !/^l-/.test(d.id), 'not engine-interactive ids');
  // engine paint: solar core ramp, solar glow ramp, blur 1, black 1.5 px stroke, the engine REPD order as sort key
  assert.ok(JSON.stringify(d.paint['circle-color']).includes('"solar",["interpolate",["linear"],["get","c"],0,"#ffff00",20,"#ffcc00",50,"#ffaa00",200,"#ff6600",500,"#ff2200"]'));
  assert.ok(JSON.stringify(g.paint['circle-radius']).includes('4,22,20,32,50,44,200,60,500,80')); assert.equal(g.paint['circle-blur'], 1);
  assert.equal(d.paint['circle-stroke-color'], '#000'); assert.equal(JSON.stringify(d.layout['circle-sort-key']), '["get","o"]');
  // the Tech filter redraws the dots for the filtered list
  press(x, 'te:solar'); assert.deepEqual(dots(x).map(dotKey).sort(), wantDots(bruteSites(REPD_IND, ...DONC, p => /^solar/.test(p.tech))));
  assert.match(card(x).textContent, /only these sites are drawn, in the REPD layer style/); assert.doesNotMatch(card(x).textContent, /REPD map layers on/);
  assert.deepEqual(E.toggles, []); assert.equal(x.log.errors.length, 0);
});

B4('M4b-2: a row tap draws only that site in the project view; back restores the list dots; close, OFF and a period change remove every dot layer and source', async () => {
  for (const end of ['close', 'off', 'period']) {
    const { x, E } = await boot3([-1.5, 52], null, SYN); tapFlash(x, 0); await settle(); const n = dots(x).length; assert.ok(n >= 3, 'list dots ' + n);
    tapRow(x, 1); await settle(); assert.equal(card(x).getAttribute('aria-label'), 'REPD project');
    assert.equal(dots(x).length, 1, 'the project view draws its own site'); assert.equal(dots(x)[0].properties.t, 'bess');
    dispatch(card(x).querySelector('[data-lightning-back]'), 'click', x.log.errors); await settle(); assert.equal(dots(x).length, n, 'back');
    if (end === 'close') closeCard(x); else if (end === 'off') x.toggle(false); else x.click(x.chip('7d')); await drain();
    for (const id of ['p-glow', 'p-dot']) assert.equal(x.layers.get('gridatlas-lightning-neon-' + id), undefined, end + ' ' + id);
    assert.equal(x.sources.get('gridatlas-lightning-neon-pdots'), undefined, end); assert.deepEqual(E.toggles, []); assert.deepEqual(x.log.errors.map(String), []);
  }
});

B4('M4b-3: a tap on a drawn site dot opens that site\'s project view (as its row); a tap elsewhere is the lightning tap as before', async () => {
  const { x } = await boot3([-1.5, 52], null, SYN); tapFlash(x, 0); await settle();
  const f = dots(x).find(q => q.properties.t === 'wind'); assert.ok(f);
  x.tapMap([5, 5], { 'gridatlas-lightning-neon-p-dot': [{ properties: { ...f.properties } }] }); await settle();
  assert.equal(card(x).getAttribute('aria-label'), 'REPD project'); assert.match(card(x).textContent, /W1/); assert.ok(card(x).querySelector('[data-lightning-back]'));
  dispatch(card(x).querySelector('[data-lightning-back]'), 'click', x.log.errors); await settle();
  tapFlash(x, 0); await settle(); assert.equal(card(x).getAttribute('aria-label'), 'Lightning flash'); assert.deepEqual(x.log.errors.map(String), []);
});

B4('M4b-4: the module names no Layers control (the proof\'s original static negative holds) and nothing is drawn before a tap', async () => {
  assert.equal(/data-layer-id|lbl-/.test(SRC), false);
  const x = boot({ feedFn: () => feed([]) }); installRepd(x, S3, SYN); const E = installLayers(x); x.toggle(true); await drain(); x.toggle(false); await drain();
  assert.deepEqual(E.toggles, []); assert.equal(dots(x).length, 0);
});

// ---------------------------------------------------------------- M5 / M5b: the full REPD record of each listed project
// Owner, 29 Oct 2026 02:21 UTC: list all 10 sites with names, distances and full REPD addresses, in the grid engine's card
// pattern (place-global-search 202609071213 :413-416: name, technology, MW, "address · postcode · county", "REPD <ref> · <status>").
// The records come from the SAME pinned file the engine's project search reads (repd_projects_202608290716.parquet, via
// the page's shared DuckDB runtime). Here a DuckDB stand-in answers the module's SQL from the repository's JSON twin of
// that parquet (data/repd_browser_registry_202608290716.json: same generation and manifest, 11,069 rows; checked
// row-for-row equal to the parquet with DuckDB in the M5-build lane). The register the list is built from carries no ref,
// so a record is shown only on an exact single match; otherwise "address not in register". A ref is never inferred.
const REC_RAW = readFileSync(new URL('../../../data/repd_browser_registry_202608290716.json', import.meta.url));
assert.equal(createHash('sha256').update(REC_RAW).digest('hex'), 'c8a5c59be878c52014a272eb0e4d09af06a0d301d10a8d6b5d0b116b5d1bb6bc', 'the manifest-pinned browser registry');
const RECS = JSON.parse(REC_RAW.toString('utf8')).records;
const MAN_RAW = readFileSync(new URL('../../../data/repd_v9_manifest_202608290716.json', import.meta.url));
const PQ_URL = 'https://ventusltd.github.io/gridatlas/data/repd_projects_202608290716.parquet', MAN_URL = 'https://ventusltd.github.io/gridatlas/data/repd_v9_manifest_202608290716.json';
const installRecords = (x, recs = RECS, o = {}) => {
  x.sql = []; x.manFetch = 0;
  const run = sql => {
    x.sql.push(sql); assert.ok(sql.startsWith(`SELECT * FROM read_parquet('${PQ_URL}') WHERE (abs(longitude-(`), 'the pinned parquet only, filtered by point');
    const pts = [...sql.matchAll(/\(abs\(longitude-\((-?[\d.]+)\)\)<=([\d.]+) AND abs\(latitude-\((-?[\d.]+)\)\)<=([\d.]+)\)/g)].map(m => [+m[1], +m[3], +m[2]]);
    assert.equal(sql.replace(/\(abs\(longitude-\((-?[\d.]+)\)\)<=([\d.]+) AND abs\(latitude-\((-?[\d.]+)\)\)<=([\d.]+)\)( OR )?/g, '').length, `SELECT * FROM read_parquet('${PQ_URL}') WHERE `.length, 'nothing but point clauses');
    return recs.filter(r => pts.some(([a, b, t]) => Math.abs(r.longitude - a) <= t && Math.abs(r.latitude - b) <= t)).map(r => ({ toJSON: () => ({ ...r }) }));
  };
  if (!o.noRuntime) x.W.__GRIDATLAS_DUCKDB_RUNTIME__ = { module_url: 'stand-in', promise: Promise.resolve({ database: { connect: () => o.hangConnect ? new Promise(() => {}) : Promise.resolve({ query: async sql => { if (o.hang) return new Promise(() => {}); const r = run(sql); return { toArray: () => r }; }, close: async () => {} }) } }) };
  const of = x.sandbox.fetch;
  x.sandbox.fetch = async (u, op) => { if (String(u) === MAN_URL) { x.manFetch++; return new Response(o.badManifest ? Buffer.concat([MAN_RAW, Buffer.from(' ')]) : MAN_RAW, { status: 200 }); } return of(u, op); };
};
// the test's own exact-join rule (written independently of the module): same point within 1e-6°, same name after cp1252
// C1 repair + NFC + whitespace collapse, same MW (0/absent = not stated), same REPD technology; exactly one record
const w1252 = new TextDecoder('windows-1252');
const nname = s => [...String(s ?? '')].map(c => { const k = c.codePointAt(0); return k >= 0x80 && k <= 0x9f ? w1252.decode(Buffer.from([k])) : c; }).join('').normalize('NFC').trim().split(/\s+/).filter(Boolean).join(' ');
const mwOf = v => (v > 0 ? Number(v) : 0);
const RGRID = new Map(); for (const r of RECS) if (r.longitude != null) { const k = Math.round(r.longitude * 1e3) + ':' + Math.round(r.latitude * 1e3); (RGRID.get(k) || RGRID.set(k, []).get(k)).push(r); }
const recsAt = (lon, lat) => { const out = []; for (let i = -1; i <= 1; i++) for (let j = -1; j <= 1; j++) for (const r of RGRID.get((Math.round(lon * 1e3) + i) + ':' + (Math.round(lat * 1e3) + j)) || []) if (Math.abs(r.longitude - lon) <= 1.000001e-6 && Math.abs(r.latitude - lat) <= 1.000001e-6) out.push(r); return out; };
const wantRec = (p, a) => { const c = recsAt(a[0], a[1]).filter(r => nname(r.name) === nname(p.name) && Math.abs(mwOf(r.capacity_mw) - mwOf(p.capacity)) < 1e-6 && r.repd_technology === p.raw_tech); return c.length === 1 ? c[0] : null; };
const recBlocks = x => card(x).querySelectorAll('[data-tier="record"]').filter(b => b.style.cssText.includes('padding:2px 0 10px 12px'));
const recLines = r => [[r.repd_address_display || 'address not stated', r.repd_postcode || 'no postcode', r.county, r.region].filter(Boolean).join(' · '), `Record · REPD ${r.repd_ref} · ${r.status}`];
// the parts in card order with their own points, from the independent brute force
const partsOf = (repd, ll, keep) => { const pt = new Map(); for (const f of repd.features) pt.set(f.properties, repPoint(f.geometry)); return bruteSites(repd, ...ll, keep).flatMap(g => g.parts.map(p => [p, pt.get(p)])); };
const recTap = async (ll, subs, o = {}) => { const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', ll)]) }); installRepd(x, subs, REPD_IND); installRecords(x, RECS, o); x.toggle(true); await drain(); tapFlash(x); await settle(); await drain(); return x; };
const NEWARK_SUBS = SUBS.map(q => ({ ...q, at: [q.at[0] + 0.69, q.at[1] + 1.07] }));

test('M5-1 (real register + real records, Doncaster and Newark): every listed project carries its exact REPD record, or "address not in register"; refs only from an exact single match', async () => {
  for (const [ll, subs] of [[DONC, S3], [NEWARK, NEWARK_SUBS]]) {
    const x = await recTap(ll, subs), parts = partsOf(REPD_IND, ll), bl = recBlocks(x);
    assert.equal(x.manFetch, 1, 'the pinned manifest is checked once'); assert.equal(x.sql.length, 1, 'one query for the listed points');
    assert.equal(bl.length, parts.length, 'one record block per listed project (grouped sites expanded)');
    let joined = 0;
    parts.forEach(([p, a], i) => {
      const r = wantRec(p, a), t = bl[i].children.map(c => c.textContent);
      if (r) { joined++; assert.deepEqual(t.slice(0, 2).map((s, k) => k ? s.replace(/ \(map register: .*\)$/, '') : s), recLines(r), p.name); if (r.status !== p.status) assert.match(t[1], /\(map register: /); }
      else assert.deepEqual(t, ['Record · address not in register (no exact REPD match; no ref shown)'], p.name);
    });
    assert.ok(joined >= parts.length - 2, 'nearly all listed projects join exactly (' + joined + '/' + parts.length + ')');
    const refs = [...card(x).textContent.matchAll(/REPD (\d+) · /g)].map(m => m[1]);
    assert.deepEqual(refs.sort(), parts.map(([p, a]) => wantRec(p, a)).filter(Boolean).map(r => r.repd_ref).sort(), 'no ref beyond the exact matches');
    for (const a of prows(card(x))) assert.doesNotMatch(a.href, /repd_ref/);
    assert.equal(x.log.errors.length, 0);
  }
});

test('M5-2 (the owner\'s example): a flash at REPD 15149 shows the engine card\'s address line and "REPD 15149 · application submitted"', async () => {
  const x = await recTap([-0.813464, 53.138419], NEWARK_SUBS), t = card(x).textContent;
  assert.ok(t.includes('north west of Newark on Trent, west of A1 and north of A617, Newark · NG23 6HT · Nottinghamshire · East Midlands'));
  assert.ok(t.includes('Record · REPD 15149 · application submitted'));
  assert.ok(t.includes('The Planning Inspectorate - National Infrastructure · EN010162 · record updated 13/10/2025'));
  assert.ok(t.includes('Operator: not shown (may name a person) or not stated'), 'a withheld operator stays withheld');
});

test('M5-3 (whole register): the module\'s exported join pairs 10,503 of the 10,784 register rows with exactly one record and never one record with two rows', () => {
  const x = boot({ feedFn: () => feed([]) }), api = x.W.__GRIDATLAS_MODULES__.repdRecords;
  assert.equal(api.source, PQ_URL); assert.equal(api.manifest, MAN_URL); assert.equal(Object.isFrozen(api), true);
  const C = new Map(), hits = new Map(); let joined = 0;
  for (const f of REPD_IND.features) { const a = repPoint(f.geometry); C.set(a + '', recsAt(...a)); }
  for (const f of REPD_IND.features) {
    const a = repPoint(f.geometry), r = api.join(f.properties, a, C), w = wantRec(f.properties, a);
    assert.equal(r ? r.repd_ref : null, w ? w.repd_ref : null, f.id);
    if (r) { joined++; hits.set(r.repd_ref, (hits.get(r.repd_ref) || 0) + 1); }
  }
  assert.equal(joined, 10503); assert.equal([...hits.values()].filter(v => v > 1).length, 0);
  assert.equal(api.join({ name: 'x' }, [0, 0], new Map()), undefined, 'not loaded is not "no match"');
});

test('M5-4: no invented refs: no record at the point, a changed MW, a different name, two identical records: each says "address not in register" and shows no ref', async () => {
  const P = (n, extra) => ({ repd_ref: String(n), name: 'Test Farm', repd_address_display: 'Somewhere', repd_postcode: 'AB1 2CD', county: 'Shire', region: 'East', planning_authority: 'Council', planning_application_reference: 'P/1', repd_operator_or_applicant: 'Op Ltd', applicant_publication_state: 'REPD_AS_PUBLISHED', repd_technology: 'Solar Photovoltaics', status: 'operational', capacity_mw: 10,  … [line shortened here: 484 characters; full line on GitHub]
  const repd = FCx([pf(-1.5, 52.01, { name: 'Test Farm' }), pf(-1.5, 52.02, { name: 'MW Farm' }), pf(-1.5, 52.03, { name: 'Name Farm' }), pf(-1.5, 52.04, { name: 'Twin Farm' }), pf(-1.5, 52.05, { name: 'Lonely Farm' })]);
  const recs = [P(1), P(2, { name: 'MW Farm', latitude: 52.02, capacity_mw: 12 }), P(3, { name: 'Name Farm Extension', latitude: 52.03 }), P(4, { name: 'Twin Farm', latitude: 52.04 }), P(5, { name: 'Twin Farm', latitude: 52.04 })];
  const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installRepd(x, SUBS, repd); installRecords(x, recs); x.toggle(true); await drain(); tapFlash(x); await settle(); await drain();
  const t = recBlocks(x).map(b => b.textContent);
  assert.equal(t.length, 5); assert.match(t[0], /Record · REPD 1 · operational/);
  for (const s of t.slice(1)) assert.equal(s, 'Record · address not in register (no exact REPD match; no ref shown)');
  assert.deepEqual([...card(x).textContent.matchAll(/REPD (\d+)/g)].map(m => m[1]), ['1']);
});

test('M5-5: missing fields are said, never filled: no address, no postcode, no planning fields, no update date; a withheld operator is not shown; a newer record status is shown beside the register status', async () => {
  const repd = FCx([pf(-1.5, 52.01, { name: 'Bare', status: 'application submitted' }), pf(-1.5, 52.02, { name: 'Full' })]);
  const recs = [{ repd_ref: '7', name: 'Bare', repd_address_display: null, repd_postcode: null, county: null, region: 'Wales', planning_authority: null, planning_application_reference: null, repd_operator_or_applicant: 'WITHHELD — POSSIBLE INDIVIDUAL', applicant_publication_state: 'WITHHELD_POSSIBLE_INDIVIDUAL', repd_technology: 'Solar Photovoltaics', status: 'awaiting construction', capacity_mw:   … [line shortened here: 468 characters; full line on GitHub]
    { repd_ref: '8', name: 'Full', repd_address_display: 'Lane <b>&', repd_postcode: 'ZZ9 9ZZ', county: 'C', region: 'R', planning_authority: 'PA', planning_application_reference: 'X/1', repd_operator_or_applicant: 'Op Ltd', applicant_publication_state: 'REPD_AS_PUBLISHED', repd_technology: 'Solar Photovoltaics', status: 'operational', capacity_mw: 10, longitude: -1.5, latitude: 52.02, source_reco  … [line shortened here: 428 characters; full line on GitHub]
  const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installRepd(x, SUBS, repd); installRecords(x, recs); x.toggle(true); await drain(); tapFlash(x); await settle(); await drain();
  const [a, b] = recBlocks(x).map(q => q.children.map(c => c.textContent));
  assert.deepEqual(a, ['address not stated · no postcode · Wales', 'Record · REPD 7 · awaiting construction (map register: application submitted)', 'Operator: not shown (may name a person) or not stated', 'planning authority not stated']);
  assert.deepEqual(b, ['Lane <b>& · ZZ9 9ZZ · C · R', 'Record · REPD 8 · operational', 'Operator: Op Ltd', 'PA · X/1 · record updated 02/02/2026']);
  assert.equal(recBlocks(x)[1].children[0].children.length, 1, 'text, never markup');
});

test('M5-6: rows per point are cached for the page: no point is ever queried twice (filter presses query only sites new to the list); a second tap at the same place sends no query', async () => {
  const x = await recTap(DONC, S3); assert.equal(x.sql.length, 1);
  const pts = () => x.sql.flatMap(q => [...q.matchAll(/longitude-\((-?[\d.]+)\)\)<=[\d.]+ AND abs\(latitude-\((-?[\d.]+)\)/g)].map(m => m[1] + ',' + m[2]));
  for (const k of ['te:solar', 'st:op', 'te:all', 'st:all']) { press(x, k); await settle(); await drain(); }
  const n = x.sql.length; tapFlash(x); await settle(); await drain(); assert.equal(x.sql.length, n, 'same tap: cached'); assert.equal(x.manFetch, 1);
  assert.equal(new Set(pts()).size, pts().length, 'no point queried twice');
  // R-cifix MINOR: under load the record join (WebCrypto digest of the manifest, then the query) can outlast drain(); wait for it,
  // up to 3 s, instead of a fixed tick count. The expectation is unchanged: every block ends loaded.
  assert.ok(recBlocks(x).length >= 10); const t0 = Date.now(); while (card(x).textContent.includes('loading…') && Date.now() - t0 < 3000) await new Promise(r => setTimeout(r, 5));
  assert.ok(!card(x).textContent.includes('loading…'));
});

test('M5-7: failures are said and retried: no search runtime, a manifest that is not the pinned one, a query that never answers (timeout)', async () => {
  let x = await recTap(DONC, S3, { noRuntime: true });
  assert.match(recBlocks(x)[0].textContent, /^REPD record unavailable — tap to retry \(the map search runtime has not started; reload the page\)$/);
  assert.ok(prows(card(x)).length >= 10, 'the list itself stands');
  x = await recTap(DONC, S3, { badManifest: true }); assert.match(recBlocks(x)[0].textContent, /REPD record unavailable — tap to retry \(REPD manifest is not the pinned one\)/); assert.equal(x.sql.length, 0, 'no query without the pinned manifest');
  globalThis.__SRC_OVERRIDE = SRC.replace('TMO=15000', 'TMO=40');
  try { x = await recTap(DONC, S3, { hang: true }); await new Promise(r => setTimeout(r, 120)); await drain(); assert.match(recBlocks(x)[0].textContent, /REPD record unavailable — tap to retry \(timeout after 15 s\)/); }
  finally { delete globalThis.__SRC_OVERRIDE; }
  assert.ok(SRC.includes('TMO=15000'), 'the shipped timeout is 15 s');
});

test('M5-8 Area summary (Screening): counts and stated MW by technology and by status within 10 and 40 km equal the brute force; the nearest substation per voltage comes from the card\'s own 5', async () => {
  const x = await recTap(DONC, S3), c = card(x), g = c.querySelectorAll('[data-tier="screening"]').find(e => e.style.cssText.includes('grid'));
  assert.ok(g, 'summary grid'); const cells = g.children.map(e => e.textContent), rows = [];
  for (let i = 3; i < cells.length; i += 3) rows.push(cells.slice(i, i + 3));
  const seen = new Set(), all = [];
  for (const f of REPD_IND.features) { const a = repPoint(f.geometry), p = f.properties; if (!a || !PTECH.has(p.tech)) continue; const km = hav(...DONC, ...a); const k = a + JSON.stringify(p); if (km <= 40 && !seen.has(k)) { seen.add(k); all.push({ p, km }); } }
  const T = t => /^solar/.test(t) ? 'Solar' : /^wind/.test(t) ? 'Wind' : /^bess/.test(t) ? 'BESS' : 'Other', St = s => ({ operational: 'Operational', 'under construction': 'Consented', 'awaiting construction': 'Consented', 'application submitted': 'Planning' })[s];
  const cell = (lab, d) => { const r = all.filter(q => q.km <= d && (T(q.p.tech) === lab || St(q.p.status) === lab)), w = [...new Set(r.map(q => q.p.name + '|' + q.p.raw_tech + '|' + mwOf(q.p.capacity)))].reduce((s, k) => s + +k.split('|').pop(), 0); return r.length + (w > 0 ? ' · ' + w.toLocaleString('en-GB') + ' MW' : '') + (r.some(q => !(q.p.capacity > 0)) ? '*' : ''); };
  const want = ['Solar', 'Wind', 'BESS', 'Other', 'Operational', 'Consented', 'Planning'].filter(l => cell(l, 40) !== '0').map(l => [l, cell(l, 10), cell(l, 40)]);
  assert.deepEqual(rows, want);
  const k = origNearest(...DONC, S3), V = new Map(); for (const s of k) if (!V.has(s.kv[0])) V.set(s.kv[0], s);
  assert.ok(c.textContent.includes('Nearest per voltage, of the substations above: ' + [...V].sort((a, b) => b[0] - a[0]).map(([v, s]) => `${v} kV ${(+s.km).toFixed(2)} km`).join(' · ')));
  assert.ok(c.textContent.includes('Counts and distances only: not capacity, connection feasibility or exposure.'));
});

test('M5-9 tiers: record blocks are data-tier="record", the summary "screening"; no distance, count or sum is marked record; the banned words appear only negated', async () => {
  const x = await recTap(DONC, S3), c = card(x);
  for (const b of c.querySelectorAll('[data-tier="record"]')) assert.doesNotMatch(b.textContent, /\d km\b|within \d+ km/, 'a record block carries no distance');
  const scr = c.querySelectorAll('[data-tier="screening"]').map(e => e.textContent).join(' ') + ' ' + c.textContent.split('Record ·')[0];
  const bad = scr.replace(/not capacity, connection feasibility or exposure|Proximity, not exposure or a current path|Proximity only, not impact|not evidence any (asset|project) was struck|capacity not stated|some capacities not stated|MW not stated|Not its declared connection or capacity/g, '');
  assert.doesNotMatch(bad, /\brisk|exposure|exposed|struck|\bhit\b|impact|damage|\bsafe\b|capacity available|headroom|feasib|can connect|\broute\b/i);
  assert.match(c.textContent, /Screening · 10 nearest REPD sites \(\d+ projects; those at one point grouped\) within 40 km of this optical flash, straight line\. Proximity only, not impact/);
  assert.match(c.textContent, /Record · REPD \(DESNZ, OGL v3\.0\): the map register is the Apr 2026 extract; address, ref, operator and planning fields are from the Jul 2026 extract/);
});

test('M5-10 project view (row tap): the site\'s records are shown in the engine pattern; back restores the list with its records from the cache', async () => {
  const x = await recTap(NEWARK, NEWARK_SUBS), sites = bruteSites(REPD_IND, ...NEWARK), pt = new Map(REPD_IND.features.map(f => [f.properties, repPoint(f.geometry)]));
  const i = sites.findIndex(g => g.parts.length > 1); assert.ok(i >= 0); tapRow(x, i); await settle(); await drain();
  const c = card(x); assert.equal(c.getAttribute('aria-label'), 'REPD project');
  const bl = c.querySelectorAll('[data-tier="record"]'); assert.equal(bl.length, sites[i].parts.length);
  sites[i].parts.forEach((p, k) => { const r = wantRec(p, pt.get(p)); assert.ok(bl[k].textContent.includes(r ? `Record · REPD ${r.repd_ref}` : 'address not in register')); });
  assert.match(c.textContent, /Record · REPD \(DESNZ, Apr 2026, OGL v3\.0\)\. Status as registered, not as built\./);
  assert.equal(x.sql.length, 1, 'the project view reads the cache');
  dispatch(c.querySelector('[data-lightning-back]'), 'click', x.log.errors); await settle(); await drain();
  assert.equal(recBlocks(x).length, partsOf(REPD_IND, NEWARK).length); assert.equal(x.sql.length, 1); assert.equal(x.log.errors.length, 0);
});

test('M5-11 phone (393 px): record and summary blocks wrap (no fixed width, no nowrap); every line is short enough for two lines at 11 px monospace except addresses, which wrap anywhere', async () => {
  const x = await recTap(DONC, S3), c = card(x);
  for (const b of [...recBlocks(x), ...c.querySelectorAll('[data-tier="screening"]')]) {
    assert.doesNotMatch(b.style.cssText, /(^|;)\s*(min-)?width:|nowrap|position:absolute/); }
  for (const b of recBlocks(x)) { assert.match(b.style.cssText, /overflow-wrap:anywhere/); assert.match(b.style.cssText, /font-size:11px/); }
  const g = c.querySelectorAll('[data-tier="screening"]').find(e => e.style.cssText.includes('grid'));
  assert.match(g.style.cssText, /grid-template-columns:auto auto auto/); for (const e of g.children) assert.ok(e.textContent.length <= 22, e.textContent);
  assert.ok(c.querySelector('details').open, 'M6: the card opens by default (the list is visible)');
});

// ---------------------------------------------------------------- M6-build: the 10-site list is visible by default (owner, iPhone 03:05 UTC)
test('M6-1: the card opens by default as a half-height panel: the sites come first (above the substations), the Area summary after them; "▾ Hide list" / "▸ Show 10 sites" reflects the real state; × closes', async () => {
  const x = await recTap(DONC, S3); x.mapEl._rect = { top: 0, left: 0, right: 393, bottom: 852, width: 393, height: 852 }; const c = card(x), d = c.querySelector('details');
  assert.equal(d.open, true, 'open by default');
  const [tg, close] = c.querySelectorAll('button'); assert.equal(tg.textContent, '▾ Hide list'); assert.equal(tg.getAttribute('aria-label'), 'Hide list'); assert.equal(tg.getAttribute('aria-expanded'), 'true'); assert.equal(close.getAttribute('aria-label'), 'Close');
  assert.equal(prows(c).length, 10); assert.ok(prows(c).every(a => d.contains(a)));
  const t = c.textContent, r = rowsOf(x); assert.ok(t.indexOf(r[0]) < t.indexOf('Screening · nearest substations'), 'sites first'); assert.ok(t.indexOf('Area summary') > t.indexOf(r[9]), 'Area summary after the sites');
  assert.ok(t.indexOf(r[9]) < t.indexOf('Cell lat') || !t.includes('Cell lat'));
  dispatch(tg, 'click', x.log.errors); assert.equal(d.open, false); assert.equal(tg.textContent, '▸ Show 10 sites'); assert.equal(tg.getAttribute('aria-label'), 'Show 10 sites'); assert.equal(tg.getAttribute('aria-expanded'), 'false');
  d.open = true; dispatch(d, 'toggle', x.log.errors); assert.equal(tg.textContent, '▾ Hide list', 'the summary tap updates the toggle too');
  dispatch(close, 'click', x.log.errors); assert.equal(card(x), null); assert.equal(x.log.errors.length, 0);
});
test('M6-2: the panel is at most 45 % of the map (393x852: 383 px) and scrolls inside', async () => {
  const x = flash0(); installRepd(x, SUBS, FCx([pf(-1.5, 52.3)])); x.mapEl._rect = { top: 0, left: 0, right: 393, bottom: 852, width: 393, height: 852 }; x.mapEl.clientHeight = 852; x.mapEl.clientWidth = 393;
  x.toggle(true); await drain(); tapFlash(x); await settle();
  assert.equal(card(x).style.maxHeight, '383px'); assert.match(card(x).style.cssText, /overflow-y:auto/); assert.equal(card(x).querySelector('details').open, true);
});
test('M6-3: rows render from the map register even when the REPD record fetch fails or hangs: "loading REPD record…" at once, then "REPD record unavailable — tap to retry" within the 15 s budget; a tap on it retries; never an empty list', async () => {
  globalThis.__SRC_OVERRIDE = SRC.replace('TMO=15000', 'TMO=40');
  try {
    const x = await recTap(DONC, S3, { hang: true }); const c = card(x);
    assert.equal(prows(c).length, 10, 'the 10 rows stand'); for (const a of prows(c)) assert.match(a.textContent, /^\d+\.\d\d km · .+ · .+/);
    assert.ok(recBlocks(x).length >= 10); const api = x.W.__GRIDATLAS_MODULES__.repdRecords; assert.equal(api.block({ name: 'A' }, [1, 2], new Map).textContent, 'loading REPD record…', 'not loaded yet: loading'); assert.match(api.block({ name: 'A' }, [1, 2], new Map, new Error('x')).textContent, /^REPD record unavailable — tap to retry \(x\)$/);
    await new Promise(r => setTimeout(r, 120)); await drain();
    assert.ok(recBlocks(x).every(b => /^REPD record unavailable — tap to retry \(timeout after 15 s\)$/.test(b.textContent)));
    assert.equal(prows(c).length, 10, 'still 10 rows'); assert.equal(recBlocks(x)[0].getAttribute('role'), 'button');
  } finally { delete globalThis.__SRC_OVERRIDE; }
  const y = await recTap(DONC, S3, { noRuntime: true }); assert.equal(prows(card(y)).length, 10); assert.ok(recBlocks(y).every(b => b.textContent.startsWith('REPD record unavailable — tap to retry')));
  installRecords(y, RECS); dispatch(recBlocks(y)[0], 'click', y.log.errors); await settle(); await drain();
  assert.ok(!card(y).textContent.includes('unavailable'), 'the retry fills every slot'); assert.ok(recBlocks(y).some(b => /Record · REPD \d+/.test(b.textContent))); assert.equal(y.sql.length, 1);
  assert.equal(y.log.errors.length, 0);
});

// R-otsec ORS8 (from 202610290935, M6 + this fix): RpQ's R() keeps its own timer. With one shared timer,
// R(R(runtime).then(connect)) cleared the outer timer when the runtime resolved, so the exported records() never
// settled on a hung connect() (the card was saved only by its own outer deadline). Older modules skip this test.
const MODULE_GEN = (SRC.match(/GEN='(\d{12})'/) || [])[1] || '0';
test('ORS8: repdRecords.records() rejects with the timeout when connect() hangs (the card says so too)', { skip: MODULE_GEN < '202610290935' && `module ${MODULE_GEN} predates the fix` }, async () => {
  globalThis.__SRC_OVERRIDE = SRC.replace('TMO=15000', 'TMO=40');
  try {
    const x = await recTap(DONC, S3, { hangConnect: true }); await new Promise(r => setTimeout(r, 150)); await drain();
    assert.match(recBlocks(x)[0].textContent, /REPD record unavailable — tap to retry \(timeout after 15 s\)/);
    const api = x.W.__GRIDATLAS_MODULES__.repdRecords;
    const out = await Promise.race([api.records([[-1.25, 53.5]]).then(() => 'resolved', e => 'rejected: ' + e.message), new Promise(r => setTimeout(() => r('still pending'), 400))]);
    assert.equal(out, 'rejected: timeout after 15 s', 'a hung connect() must time out inside records() itself');
  } finally { delete globalThis.__SRC_OVERRIDE; }
});

// R-taps MAJOR (from 202610291043 on): a tap that lands on a potential-offtakers dot, or that another overlay has claimed
// (e.gridatlasClaim), is not lightning's: the card stays, no cell or REPD-dot path runs, and no layer this module switched
// on is handed to the reader, so closing the card still releases it (Drax with both overlays on left bess ticked).
(M4B ? test.skip : test)('TAPS1: an offtakers dot or a claimed tap is not lightning\'s: no hand-over, no close, the layers are still released on close', { skip: MODULE_GEN < '202610291043' && `module ${MODULE_GEN} predates the fix` }, async () => {
  for (const how of ['offtakers dot', 'claimed']) {
    const { x, E } = await boot3([-1.5, 52], null, SYN, { userOn: ['wind'] }); tapFlash(x, 0); await settle(); assert.deepEqual([...x.S.ly].sort(), ['bess', 'solar'], how);
    const c0 = card(x); assert.ok(c0, 'card open');
    if (how === 'offtakers dot') { x.layers.set('gridatlas-offtakers-hit', { id: 'gridatlas-offtakers-hit' }); x.tapMap([50, 50], { 'gridatlas-offtakers-hit': [{ properties: { i: 0 } }], 'l-bess': [{ properties: { name: 'B1', tech: 'bess' } }], 'gridatlas-lightning-cell': [{ properties: {} }] }); }
    else { const e = { point: [50, 50], lngLat: { lng: 0, lat: 0 }, gridatlasClaim: 'offtakers' }; for (const h of x.handlers.filter(h => h.t === 'click' && !h.layer)) h.f(e); }
    await drain();
    assert.deepEqual([...x.S.ly].sort(), ['bess', 'solar'], `${how}: nothing handed to the reader`); assert.equal(card(x), c0, `${how}: lightning's card untouched by a tap it does not own`);
    closeCard(x); assert.deepEqual(onIds(E), ['wind'], `${how}: closing releases every layer the module switched on`); assert.equal(x.S.ly.size, 0); inSync(E);
  }
});

Overlay Latest Test

A test in the lightning folder of GridAtlas that uses SHA-256. It is built from the hours ago helper (`hoursAgo`), the feed step (`feed`) and the boot step (`boot`).

testgridatlas / tools/ci/lightning/overlay-latest.test.mjs · lines 1–148 of 148 · Entry point · pattern drain (shared by 3 files)

What it does
It tests its inputs. Defines 7 functions or classes, including hoursAgo, stamp, flash, feed, boot. Uses libraries node:test, node:assert/strict, node:vm, node:fs. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
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 26.json.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Defines `hoursAgo`, `stamp`, `flash` and 4 more.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/ci/lightning · test
Uses
node:test, node:assert/strict, node:vm, node:fs
Used by
none found
Produces
hoursAgo, stamp, flash, feed, boot, XHR, drain
Defines here
hoursAgo, stamp, flash, feed, boot, XHR, drain
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/lightning/overlay-latest.test.mjs:1-148 · blob 7b8d1d14987c0cf13e88982a06633b38100ac2d3 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
// Independent fail-first runtime regressions for GridAtlas lightning. Node built-ins only.
// Vendored unchanged (apart from this header) from the hardening lane's
// chatgpt-latest.test.mjs, the superset of chatgpt-lightning-regression.test.mjs,
// so the PR gate (tools/ci/pr-gate.mjs, docs/CI.md) can run it against the overlay
// module of every touched and live generation. It passes on 202610281340 and
// 202610281950; it was written RED against the original 202610261949 candidate.
// Do not adjust expectations to pass.
//   LIGHTNING_MODULE=atlas/modules/<gen>-uk-lightning-overlay.js node --test tools/ci/lightning/overlay-latest.test.mjs
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import {readFileSync} from 'node:fs';

const gen=process.env.LIGHTNING_TEST_GEN||'202610261949';
const path=process.env.LIGHTNING_MODULE||('atlas/modules/'+gen+'-uk-lightning-overlay.js');
const src=readFileSync(path,'utf8');
const seam='NS.ukLightning=Object.freeze(';
assert.equal(src.split(seam).length,2,'Test probe cannot locate the original module seam');
const observed=src.replace(seam,'window.__PROBE__={ok,cf,sh,cp,ff,state:S};'+seam);
const hoursAgo=h=>Date.now()-h*3600000;
const stamp=h=>new Date(hoursAgo(h)).toISOString();
const flash=(h,id,coords=[-1.5,52])=>({type:'Feature',id,
  geometry:{type:'Point',coordinates:coords},
  properties:{time_utc:stamp(h),observation_kind:'optical_lightning_flash'}});
const feed=(features,age=1)=>({type:'FeatureCollection',features,
  metadata:{query_start_utc:stamp(age+1),query_end_utc:stamp(age),
    scan_end_utc:stamp(age),published_at_utc:stamp(age)}});

function boot({getFeed=()=>feed([flash(2,'one')]),getJson=()=>({ok:false,status:404})}={}){
  const xhr=[],requests=[],sources=new Map(),layers=new Map();
  const map={
    getLayer:id=>layers.get(id),getSource:id=>sources.get(id),
    addSource:(id,opt)=>sources.set(id,{...opt,setData(x){this.data=x;}}),
    addLayer:x=>layers.set(x.id,{...x}),
    removeLayer:id=>layers.delete(id),removeSource:id=>sources.delete(id),
    setLayoutProperty(id,key,value){let x=layers.get(id);if(x){x.layout=x.layout||{};x.layout[key]=value;}}
  };
  class XHR {
    open(method,url){this.url=url;}
    send(){xhr.push(this.url);const data=getFeed();
      if(data?.error){this.onerror?.();return;}
      this.status=data?.status||200;
      this.responseText=JSON.stringify(data?.json??data);this.onload?.();
    }
  }
  const sandbox={
    window:{__GRIDATLAS_V9_MAP__:map,innerWidth:1440},document:{},
    Date,AbortController,Map,XMLHttpRequest:XHR,
    fetch:async(url,opts)=>{requests.push(url);return getJson(url,opts);},
    matchMedia:()=>({matches:false}),setTimeout,clearTimeout,
    setInterval:()=>17,clearInterval:()=>{}
  };
  vm.runInNewContext(observed,sandbox,{filename:path,timeout:2000});
  return {api:sandbox.window.__GRIDATLAS_MODULES__.ukLightning,
    probe:sandbox.window.__PROBE__,xhr,requests,sources,layers};
}
const drain=async()=>{for(let k=0;k<15;k++)await new Promise(resolve=>setImmediate(resolve));};

test('Sanity: lightning starts OFF with zero network and map work',async()=>{
  const x=boot();await drain();
  assert.equal(x.api.state.on,false);
  assert.equal(x.requests.length,0);
  assert.equal(x.xhr.length,0);
  assert.equal(x.sources.size,0);
});

test('H01: reactivating feed fetches newer observations, not a cached promise',async()=>{
  let response=feed([flash(2,'old')]);
  const x=boot({getFeed:()=>response});
  x.api.setOn(true);await drain();
  assert.equal(x.xhr.length,1);
  assert.equal(x.api.state.res?.ev?.[0]?.id,'old');
  x.api.setOn(false);
  response=feed([flash(0.5,'new')]);
  x.api.setOn(true);await drain();
  assert.equal(x.xhr.length,2,'refresh / OFF→ON must revalidate the live feed');
  assert.equal(x.api.state.res?.ev?.[0]?.id,'new');
});

test('H02: fallback feed older than 24h carries visible STALE state',()=>{
  const x=boot(),now=Date.now(),w={s:now-7*864e5,e:now,period:'7d'};
  const r={mode:'feed',idx:null,fl:[],ev:[flash(72,'stale')],w,
    meta:feed([flash(72,'stale')],72).metadata,
    cov:{f:0.1,ny:3*864e5,bf:0,u:[],r:1}};
  assert.equal(x.probe.cf(r,now).stale,true);
});

test('H03: geodesy rejects out-of-bounds and malformed coordinates',()=>{
  const x=boot();
  assert.equal(x.probe.ok(flash(1,'valid',[-1.5,52])),true);
  for(const bad of [[150,10],[null,52],['bad',52],[NaN,52],[-1.5,95],[],[0]]){
    assert.equal(x.probe.ok(flash(1,'invalid',bad)),false,'bad coordinate: '+JSON.stringify(bad));
  }
});

test('H04: reject a dated shard whose index count, bytes and hash are wrong',async()=>{
  const x=boot({getJson:async()=>({ok:true,status:200,json:async()=>({
    schema:'uk-lightning-history-day.v1',type:'FeatureCollection',
    metadata:{date_utc:'2026-10-26'},features:[flash(2,'valid')]
  })})});
  await assert.rejects(
    x.probe.sh({path:'days/2026/10/26.json',sealed:true,
      count:999,bytes:123456,sha256:'0'.repeat(64)},'2026-10-26'),
    /integrity|mismatch|count|sha|bytes/i);
});

test('H05: do not call overlapping whole-day index counts exact in-window totals',()=>{
  const x=boot(),now=Date.now(),w={s:now-12*36e5,e:now,period:'12h',
    label:'12 hours',atLatest:true,custom:false,clamped:false};
  const r={w,mode:'detail',idx:{gen:now,iv:1,nextDue:now+36e5},
    ev:[flash(2,'valid')],arch:50000,ld:['2026-10-26'],sk:['2026-10-25'],
    fl:[],rq:2,cs:'index',ic:40000,cl:true,
    cov:{f:1,r:6,a:w.s,b:w.e,ny:0,bf:0,u:[],d:2}};
  const captions=x.probe.cp(r,now);
  assert.doesNotMatch(captions.flashes,/50,000 archived in window/i);
});


test('H07: 12-month selection remains usable with no archive, retaining only genuine feed events',async()=>{
  const x=boot({getFeed:()=>feed([flash(2,'genuine')])});
  const now=Date.now();
  const oneYear={s:now-365*864e5,e:now,label:'1 year',period:'12m',
    atLatest:true,custom:false,clamped:false,span:365*864e5};
  const r=await x.probe.ff(oneYear,now,'archive index HTTP 404');
  assert.equal(r.mode,'feed');
  assert.equal(r.ev.length,1,'No fake historical observations: only one genuine feed fixture point');
  assert.equal(r.ev[0].id,'genuine');
  const captions=x.probe.cp(r,now);
  assert.match(captions.window,/1 year|12m|2025/i);
  assert.match(captions.flashes+' '+captions.warning+' '+captions.refresh,
    /unknown|unavailable|not published/i,
    'Historical periods remain selectable but missing older coverage must be called UNKNOWN');
});

test('H08: live-feed last query window is NOT an evidence-backed 2% searched coverage claim',()=>{
  const x=boot(),now=Date.now(),w={s:now-7*864e5,e:now,
    period:'7d',label:'7 days',atLatest:true,custom:false,clamped:false};
  const f=feed([flash(2,'real')],1);
  const r={mode:'feed',idx:null,ie:'archive HTTP 404',meta:f.metadata,w,
    ev:f.features,fl:[],rq:1,cs:'live feed',ic:1,cl:false,ld:[],sk:[],
    cov:{f:0.02,ny:now-w.s,bf:0,u:[],d:7,r:1,a:now-3*36e5,b:now}};
  const lines=x.probe.cp(r,now);
  assert.doesNotMatch(lines.searched,/Searched EUMETSAT\s+\d+(?:\.\d+)?%\s+of window/i,
    'The most recent collection query does not prove seven-day cumulative search coverage');
  assert.match(lines.searched+' '+lines.warning,/unknown|unverified|not available/i,
    'Feed mode must explicitly state that full-window searched coverage is unknown');
});