GLOBALGRID2050 / EXPLORE CODE

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

Overlay Engine Test (part 3)

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

700 lines of JavaScript from gridatlas, in 1 file. Topic: Maps, GIS and field navigation. Section 627 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 1401–2100

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 1401–2100 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
ctxEval, boot12, wrapFetch, textOf, dumpAll, dumpCard, pl9999, repPoint, pf, installRepd, bruteTop, prows, settle, cf, siteName, bruteSites, siteMW, siteLabel, siteRow, gone, open, flashAt, hangFetch, FCx, rowsOf, chip, press, tapRow, flash0, open
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:1401-2100 · 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
});

test('LRG4: all grid months 404 -> summary fallback, no throw, no cell layer; no error', async () => {
  const x = boot({ index: mkIndex(KROWS), files: {} }); x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.equal(cellsSrc(x), undefined); assert.match(x.cap('flashes'), /cell grid archive not yet published: HTTP 404/); assert.deepEqual(x.log.errors, []);
});


// ================================================================ LR-security (appended to a copy of L-build/test-engine.mjs)
const ctxEval = (x, js) => vm.runInContext(js, x.sandbox);
const ALLOW = /^https:\/\/raw\.githubusercontent\.com\/Ventusltd\/lightning\/main\/data\/history\/(index\.json(\?[\w=&.-]*)?|days\/\d{4}\/\d\d\/\d\d(\/\d\d)?\.json|grid\/\d{4}-\d\d\.json)$/;
const boot12 = async (files, extra = {}) => { const x = boot({ index: mkIndex(KROWS), files, ...extra }); installNeon(x, SUBS); x.toggle(true); x.click(x.chip('12m')); await drain(); return x; };
const wrapFetch = (x, f) => { const real = x.sandbox.fetch; x.sandbox.fetch = (u, o) => f(u, o, real); };

test('LRS1 allow-list: every request (index, days, grid) in every window matches the Ventusltd/lightning history allow-list; grid only YYYY-MM.json', { skip: !process.env.LIGHTNING_DATA }, async () => {
  const dir = process.env.LIGHTNING_DATA, idx = JSON.parse(readFileSync(dir + '/index.json', 'utf8'));
  const files = new Proxy({}, { get: (_, k) => { try { return readFileSync(dir + '/' + String(k)); } catch { return undefined; } } });
  const x = boot({ phone: true, index: idx, files, now: Date.parse(idx.generated_utc) + 60e3 }); installNeon(x, SUBS); x.map.setPaintProperty = () => {}; x.toggle(true);
  for (const p of ['24h', '7d', '30d', '3m', '6m', '12m']) { x.click(x.chip(p)); await drain(); }
  x.click(x.nav('points')); await drain();
  const bad = x.log.fetch.filter(u => !ALLOW.test(u)); assert.deepEqual(bad, []);
  const g = x.log.fetch.filter(u => u.includes('/grid/')); assert.ok(g.length > 0);
  console.log(`# LRS1 ${x.log.fetch.length} fetches (${g.length} grid, ${new Set(g).size} distinct), ${x.log.xhr.length} xhr; all on the allow-list`);
});

test('LRS2 redirect: a grid response with redirected:true is refused (no cells drawn, never FAIL)', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); installNeon(x, SUBS);
  wrapFetch(x, async (u, o, real) => { const r = await real(u, o); if (!u.includes('/grid/')) return r; const b = await r.arrayBuffer(); return { ok: true, status: 200, redirected: true, url: 'https://evil.example/g.json', json: async () => JSON.parse(Buffer.from(b)), arrayBuffer: async () => b }; });
  x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.equal(x.S.res.gd, undefined); assert.equal(cellsSrc(x), undefined); assert.notEqual(x.S.last.state, 'FAIL'); assert.match(x.cap('flashes'), /cell grid archive unavailable: redirected/);
});

test('LRS3 prototype pollution: __proto__/constructor keys in a grid never reach Object.prototype; a schema hidden under __proto__ is refused', async () => {
  const poison = '"__proto__":{"polluted":"yes","schema":"uk-lightning-history-grid.v1"},"constructor":{"prototype":{"polluted2":"yes"}}';
  // a valid grid with extra poison keys at top level and inside every day entry still loads, and nothing is polluted
  const files = mkGrids(KGRID); for (const k in files) { const s = files[k].toString(); files[k] = Buffer.from(s.replace(/^\{/, '{' + poison + ',').replace(/\{"date"/g, '{' + poison + ',"date"')); }
  const x = await boot12(files);
  assert.equal(x.S.res.gd.n, 50000); assert.equal(ctxEval(x, '({}).polluted===undefined&&({}).polluted2===undefined&&[].polluted===undefined'), true);
  // the only schema is under __proto__ (own key after JSON.parse): refused
  const g2 = mkGrids(KGRID, g => { const { schema, ...rest } = g; return '{' + poison + ',' + JSON.stringify(rest).slice(1); });
  const y = await boot12(g2); assert.equal(y.S.res.gd, undefined); assert.equal(ctxEval(y, '({}).schema'), undefined);
  // a cell row that is an object (with numeric keys / length) is refused, not iterated
  const z = await boot12(mkGrids(KGRID, g => ({ ...g, cells: g.cells.map(r => ({ ...r, length: r.length })) }))); assert.equal(z.S.res.gd, undefined);
});

test('LRS4 huge numbers: floats, negatives, 2^32, 1e308, 2^53+1 are refused; -0 is harmless', async () => {
  for (const v of [1.5, -1, 4294967296, 1e308, 9007199254740993, '7', null, true]) {
    const x = await boot12(mkGrids(KGRID, g => ({ ...g, cells: g.cells.map(r => [r[0], r[1], v]) }))); assert.equal(x.S.res.gd, undefined, String(v));
  }
  const y = await boot12(mkGrids(KGRID, g => ({ ...g, cells: g.cells.map((r, i) => i ? r : [-0, ...r.slice(1)]) })));
  assert.ok(y.S.res.gd === undefined || y.S.res.gd.fc.features.every(f => f.properties.cell >= 0));
});

test('LRS5 [FIXED S2] a cell summing to >= 2^32 (two valid uint32 days) is drawn and its tap fires', async () => {
  const M = 4294967295, R = { [KD[0]]: { count: M, bytes: 1000, path: P(KD[0]), sha256: 'x' }, [KD[1]]: { count: M, bytes: 1000, path: P(KD[1]), sha256: 'y' } };
  const g = [{ date: KD[0], row: R[KD[0]], cells: { [LC1]: M } }, { date: KD[1], row: R[KD[1]], cells: { [LC1]: M } }];
  const x = boot({ index: mkIndex(R), files: mkGrids(g) }); installNeon(x, SUBS); x.toggle(true); x.click(x.chip('12m')); await drain();
  const f = cellsSrc(x).data.features[0]; assert.equal(f.properties.n, 2 * M, 'cell drawn with n = 2^33-2');
  cellHit(x, f);
  assert.equal(x.neonCalls.length, 1, 'tap dropped'); assert.ok(card(x));
  console.log('# LRS5 drawn n=' + f.properties.n + ', tap: 0 engine calls, no card');
});

test('LRS6 [FIXED S1] grid/YYYY-MM.json over 2 MB is refused before parsing; 1.9 MB still loads', async () => {
  const pad = 'x'.repeat(2.1e6); { const y = await boot12(mkGrids(KGRID, g => ({ ...g, pad: 'x'.repeat(1.9e6) }))); assert.equal(y.S.res.gd.n, 50000, '1.9 MB refused'); }
  const files = mkGrids(KGRID, g => ({ ...g, pad }));
  const t0 = Date.now(); const x = await boot12(files);
  assert.equal(x.S.res.gd, undefined, 'over-cap grid accepted'); assert.match(x.cap('flashes'), /cell grid archive unavailable: grid size/);
  console.log(`# LRS6 accepted ${Object.values(files).reduce((a, b) => a + b.length, 0)} B of grid JSON in ${Date.now() - t0} ms; day files are capped by index bytes+sha256, grid files by nothing`);
});

test('LRS7 innerHTML/attributes: grid text never becomes markup; the JSON error message reaches the caption as text only', async () => {
  const x = await boot12(mkGrids(KGRID, () => '<img src=x onerror=alert(1)>"‮'));
  const imgs = x.doc.documentElement.querySelectorAll('img').length; assert.equal(imgs, 0);
  const c = x.cap('flashes'); console.log('# LRS7 caption tail: ' + JSON.stringify(c.slice(c.indexOf('cell grid'))));
  assert.match(c, /cell grid archive unavailable: /);
  const b = await boot12(mkGrids(KGRID, () => '\u202e\u200bevil')); const cb2 = b.cap('flashes');
  assert.equal(/[\u202e\u200b]/.test(cb2), false, 'bidi/zero-width text reached the caption (S3)'); console.log('# LRS7 bidi in caption: ' + /[\u202e\u200b]/.test(cb2) + ' ' + JSON.stringify(cb2.slice(cb2.indexOf('cell grid'))));
  // the cell card is built from numbers re-derived and range-checked by cb(); feature properties are never interpolated as HTML
  const y = await boot12(mkGrids(KGRID)); const f = cellsSrc(y).data.features[0];
  cellHit(y, { properties: { ...f.properties, lat: '<b>x</b>' } }); assert.equal(card(y), null, 'string lat accepted');
  cellHit(y, { properties: { ...f.properties, n: '<b>' } }); assert.equal(card(y), null, 'string n accepted');
  cellHit(y, { properties: { ...f.properties, lon: f.properties.lon + 0.2 } }); assert.equal(card(y), null, 'centre outside its cell accepted');
  cellHit(y, { properties: { ...f.properties, s: -1 } }); assert.equal(card(y), null, 'stale serial accepted');
  cellHit(y, f); assert.ok(card(y)); assert.equal(card(y).querySelectorAll('img').length, 0);
});

test('LRS8 mask blob: decodes to exactly 16,800 cells, equals LR-bugs mask-30km.txt (placeholder point dropped), is a module-private constant not reachable from the API', () => {
  const m = SRC.match(/for\(const c of'([0-9A-Za-z]+)'\.match/); assert.ok(m); const s = m[1];
  assert.equal(s, readFileSync(new URL('./fixtures/mask-30km.txt', import.meta.url), 'utf8'));
  let p = 0; const runs = s.match(/[A-Z]?./g).map(c => c[1] ? (c.charCodeAt(0) - 64) * 36 + parseInt(c[1], 36) : parseInt(c, 36)); for (const r of runs) p += r;
  assert.equal(p, 16800, 'run lengths sum'); assert.ok(runs.every(Number.isInteger));
  assert.doesNotMatch(SRC.match(/NS\.ukLightning=Object\.freeze\(\{[^}]*\}/)[0], /LM|gd|gg/);
  assert.equal(SRC.split('LM()[').length, 2, 'mask indexed in one place'); assert.match(SRC, /r\[0\]>>>0!==r\[0\]\|\|r\[0\]>=16800/);
});

test('LRS9 caps: >16,800 cell rows, a row of 65 entries, 32 days are refused', async () => {
  for (const t of [g => ({ ...g, cells: Array(16801).fill(g.cells[0]) }), g => ({ ...g, cells: [[g.cells[0][0], ...Array(32).fill([1, 1]).flat()]] }), g => ({ ...g, days: Array(32).fill(g.days[0]) })]) {
    const x = await boot12(mkGrids(KGRID, t)); assert.equal(x.S.res.gd, undefined);
  }
});

// ================================================================ LR-words (evidence/LR-words/harness.mjs WORDS dump)

const textOf = n => { const o = []; const w = e => { if (e.textContent !== undefined && !e.children?.length) o.push(e.textContent); for (const c of e.children || []) w(c); }; w(n); return o; };
const dumpAll = (x, tag) => { const o = [`=== ${tag}`, `LABEL  ${x.label()}`, `STATUS ${x.status()}`]; for (const k of ['window','days','actual','flashes','refresh','searched','warning','footer']) o.push(`CAP.${k.padEnd(8)} ${x.cap(k)}`); o.push(`STATE ${JSON.stringify(x.S.last)}`); return o.join('\n'); };
const dumpCard = (x, tag) => { const c = card(x); if (!c) return `--- ${tag}: NO CARD`; const o = [`--- CARD ${tag}`, `aria-label=${c.getAttribute('aria-label')} role=${c.getAttribute('role')}`];
  for (const b of c.querySelectorAll('button')) o.push(`button "${b.textContent}" aria-label=${b.getAttribute('aria-label')}`); o.push(...textOf(c).map(s => '  · ' + s)); return o.join('\n'); };
test('WORDS dump (real data)', { skip: !process.env.LIGHTNING_DATA }, async () => {
  const dir = process.env.LIGHTNING_DATA, idx = JSON.parse(readFileSync(dir + '/index.json', 'utf8'));
  const files = new Proxy({}, { get: (_, k) => { try { return readFileSync(dir + '/' + String(k)); } catch { return undefined; } } });
  const fd = readFileSync(dir + '/../uk_lightning.geojson', 'utf8'); const out = [];
  for (const phone of [true, false]) {
    const x = boot({ phone, index: idx, files, feedFn: () => fd, now: Date.parse(idx.generated_utc) + 60e3 }); installNeon(x, SUBS); x.map.setPaintProperty = () => {}; x.toggle(true); await drain();
    out.push(dumpAll(x, `${phone ? 'PHONE' : 'DESKTOP'} 24h (default)`));
    for (const p of ['12h', '48h', '7d', '30d', '3m', '6m', '12m']) {
      x.click(x.chip(p)); await drain(); out.push(dumpAll(x, `${phone ? 'PHONE' : 'DESKTOP'} ${p}`));
      const cs = cellsSrc(x); const fs = cs && cs.data && cs.data.features || [];
      if (fs.length) { const big = fs.reduce((a, f) => f.properties.n > a.properties.n ? f : a), sm = fs.find(f => f.properties.n === 1);
        cellHit(x, big); out.push(dumpCard(x, `${p} big cell n=${big.properties.n}`)); if (sm) { cellHit(x, sm); out.push(dumpCard(x, `${p} n=1 cell`)); }
        if (phone && p === '12m') { x.click(x.nav('points')); await drain(); out.push(dumpAll(x, 'PHONE 12m after LOAD POINTS')); x.click(x.nav('prev')); await drain(); out.push(dumpAll(x, 'PHONE 12m PREV (after LOAD POINTS consent reset?)')); }
      } else if (x.S.res && x.S.res.ev.length) { tapFlash(x, x.S.res.ev.length - 1); out.push(dumpCard(x, `${p} flash`)); }
    }
    x.click(x.chip('7d')); await drain(); installNeon(x, []); tapFlash(x, 0); out.push(dumpCard(x, '7d flash, substations not loaded'));
    if (phone) { x.click(x.chip('30d')); await drain(); x.click(x.nav('prev')); await drain(); out.push(dumpAll(x, 'PHONE 30d PREV')); }
  }
  // grid unavailable
  const nog = new Proxy({}, { get: (_, k) => String(k).startsWith('grid/') ? undefined : (() => { try { return readFileSync(dir + '/' + String(k)); } catch { return undefined; } })() });
  const y = boot({ phone: true, index: idx, files: nog, feedFn: () => fd, now: Date.parse(idx.generated_utc) + 60e3 }); y.map.setPaintProperty = () => {}; y.toggle(true); await drain(); y.click(y.chip('12m')); await drain(); out.push(dumpAll(y, 'PHONE 12m grid 404'));
  // index 404 -> feed
  const z = boot({ phone: true, index: null, files: {}, feedFn: () => fd, now: Date.parse(idx.generated_utc) + 60e3 }); z.map.setPaintProperty = () => {}; z.toggle(true); await drain(); out.push(dumpAll(z, 'PHONE 24h index 404')); z.click(z.chip('12m')); await drain(); out.push(dumpAll(z, 'PHONE 12m index 404'));
  console.log(out.join('\n\n').split('\n').map(l => '#R ' + l).join('\n'));
  const all = out.join('\n'); // L3: LR-words assertions on the rendered words
  assert.doesNotMatch(all, /affected|Not yet ingested|\d+h \d+min|0 archived in window \(unknown, not zero\)|day-level|as tappable points|UK land|sea and abroad/i);
  for (const m of all.matchAll(/CAP\.flashes  (Flashes .*map shows.*)/g)) assert.ok(m[1].length <= 380, 'flashes line ' + m[1].length + ' chars: ' + m[1]);
  for (const m of all.matchAll(/--- CARD .*\n.*\n.*\n.*\n  · (.*)/g)) assert.ok(m[1].length <= 42, 'card title ' + m[1]);
  assert.match(all, /optical flashes in this 0.1° cell/); assert.match(all, /[Nn]ot evidence any asset was struck/); // M5: F2 wording
});


// ================================================================ L3-build: LR-numbers, LR-layout (node), LR-regress m1/m2, LR-words W-checks
test('LRN (real data): whenever cells draw, the caption\'s "N archived" equals the grid total (whole UTC days), at index time and on parts day 2026-08-27', { skip: !process.env.LIGHTNING_DATA }, async () => {
  const dir = process.env.LIGHTNING_DATA, idx = JSON.parse(readFileSync(dir + '/index.json', 'utf8'));
  const files = new Proxy({}, { get: (_, k) => { try { return readFileSync(dir + '/' + String(k)); } catch { return undefined; } } });
  for (const now of [Date.parse(idx.generated_utc) + 60e3, Date.parse('2026-08-27T13:00:00Z'), Date.UTC(2026, 10, 27, 13, 20)]) {
    const x = boot({ phone: true, index: idx, files, now }); x.toggle(true); await drain();
    for (const p of ['30d', '3m', '6m', '12m']) {
      x.click(x.chip(p)); await drain(); const r = x.S.res; if (!r.gd) { console.log(`# LRN ${new Date(now).toISOString()} ${p}: ${r.mode} ${r.ev.length} points`); continue; }
      const g = r.gd, fs = cellsSrc(x).data.features;
      console.log(`# LRN ${new Date(now).toISOString()} ${p}: arch ${r.arch} grid n ${g.n} drawn ${g.k} in ${fs.length} cells (stale ${g.st})`);
      if (!g.st) assert.equal(g.n, r.arch, p + ' two totals in one caption');
      assert.equal(fs.reduce((a, f) => a + f.properties.n, 0), g.k); assert.match(x.cap('flashes'), new RegExp('archived on .* not a national density map: ' + g.k.toLocaleString('en-GB') + ' in .* ' + (g.n - g.k).toLocaleString('en-GB') + ' counted, not drawn'));
    }
  }
});

test('LAY1 (LR-layout MAJOR): fitBounds keeps the origin and endpoints clear: top 150 (search bar + labels), bottom = card bottom offset + height + 24', async () => {
  const od = Object.getOwnPropertyDescriptor(El.prototype, 'offsetHeight');
  Object.defineProperty(El.prototype, 'offsetHeight', { configurable: true, get() { return 143; } });
  try {
    const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installNeon(x, SUBS);
    x.mapEl._rect = { top: 0, left: 0, right: 393, bottom: 659, width: 393, height: 659 }; x.map.getBounds = () => ({ contains: () => false });
    x.toggle(true); await drain(); tapFlash(x); await Promise.resolve(); // M4 (M2R-taps T1): deferred framing
    const c = card(x), fb = x.camera.find(k => k[0] === 'fitBounds'); assert.ok(fb, 'fitBounds'); const pad = fb[1][1].padding;
    assert.equal(pad.top, 150); assert.equal(typeof c.bb, 'number'); assert.equal(pad.bottom, c.bb + 143 + 24); assert.ok(pad.bottom >= 175);
  } finally { if (od) Object.defineProperty(El.prototype, 'offsetHeight', od); else delete El.prototype.offsetHeight; }
});

test('LAY2 (LR-layout MINOR): the card title wraps instead of ellipsising; LR-words W3 title fits 40 characters for n < 10,000', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); installNeon(x, SUBS); x.toggle(true); x.click(x.chip('12m')); await drain();
  cellHit(x, cellsSrc(x).data.features[0]); const t = card(x).children[0].children[0];
  assert.doesNotMatch(t.style.cssText, /nowrap|ellipsis|overflow:hidden/); assert.equal(pl9999(), true);
  function pl9999() { return '9,999 optical flashes in this 0.1° cell'.length <= 41; }
});

test('m1 (LR-regress): a cell layer failure does not turn a good load into FAIL "map layer"; it is noted', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); const a0 = x.map.addLayer;
  x.map.addLayer = (l, b) => { if (/lightning-cell/.test(l.id)) throw new Error('cell layer boom'); return a0(l, b); };
  x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.notEqual(x.S.last.state, 'FAIL'); assert.ok(x.S.errors.some(e => /cells: cell layer boom/.test(e)), JSON.stringify(x.S.errors));
});

test('m1b (LR-regress): if the points draw throws, the previous window\'s cells are still removed', async () => {
  const s = shard(ymd(Date.now() - D), 5, Date.now() - D);
  const x = boot({ index: mkIndex({ ...KROWS, [ymd(Date.now() - D)]: s.row }), files: { ...mkGrids(KGRID), [s.row.path]: s.b } }); x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.ok(cellsSrc(x)); x.sources.get('gridatlas-lightning').setData = () => { throw new Error('setData boom'); };
  x.click(x.chip('7d')); await drain(); assert.equal(cellsSrc(x), undefined, 'stale 12M cells left on the map'); assert.equal(x.S.last.state, 'FAIL');
});

test('m2 (LR-regress): with no hit or cell layer a tap does nothing (no style scan, no card close), as in J', async () => {
  const x = boot(); installNeon(x, SUBS); x.toggle(true); await drain(); tapFlash(x); assert.ok(card(x));
  for (const l of ['gridatlas-lightning-hit', 'gridatlas-lightning-cell']) x.layers.delete(l);
  let scans = 0; x.map.getStyle = () => { scans++; return { layers: [] }; }; x.tapMap([1, 1], {});
  assert.equal(scans, 0); assert.ok(card(x), 'card closed by a tap that hit nothing');
});
test('LRT1 (LR-taps MAJOR): LATEST with a card open clears the card and the neon links', async () => {
  const x = boot({ phone: true, index: mkIndex(KROWS), files: mkGrids(KGRID) }); installNeon(x, SUBS); x.map.setPaintProperty = () => {}; x.toggle(true);
  x.click(x.chip('30d')); await drain(); x.click(x.nav('prev')); await drain(); assert.ok(cellsSrc(x), 'paged 30D has cells');
  cellHit(x, cellsSrc(x).data.features.find(q => q.properties.cell === LC1)); assert.ok(card(x)); assert.ok(x.sources.get('gridatlas-lightning-neon-links'));
  x.click(x.nav('latest')); await drain(); assert.ok(!card(x), 'stale card after LATEST'); assert.equal(x.sources.get('gridatlas-lightning-neon-links'), undefined);
});

test('LRT2 (LR-taps MINOR): a tap while a load is in flight is ignored (no stale card)', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); installNeon(x, SUBS); x.toggle(true); x.click(x.chip('12m')); await drain();
  const f = cellsSrc(x).data.features[0]; x.S.busy = true; cellHit(x, f); assert.ok(!card(x)); assert.equal(x.neonCalls.length, 0);
  x.S.busy = false; cellHit(x, f); assert.ok(card(x)); assert.equal(x.neonCalls.length, 1);
});

test('LRT3 (LR-taps MINOR): the solar glow halo alone does not swallow a cell tap; the solar dot still wins', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); installNeon(x, SUBS); x.toggle(true); x.click(x.chip('12m')); await drain();
  x.map.getStyle = () => ({ layers: [{ id: 'l-solar-glow', source: 'src-repd' }, { id: 'l-solar', source: 'src-repd' }, ...[...x.layers.keys()].map(id => ({ id, source: x.layers.get(id).source }))] });
  x.map.getLayoutProperty = () => 'visible'; const f = cellsSrc(x).data.features[0], at = [f.properties.lon * 10, f.properties.lat * 10];
  x.tapMap(at, { 'l-solar-glow': [{ properties: {} }], [CELL]: [f] }); assert.ok(card(x), 'glow swallowed the cell tap'); assert.equal(x.neonCalls.length, 1);
  x.tapMap(at, { 'l-solar-glow': [{ properties: {} }], 'l-solar': [{ properties: {} }], [CELL]: [f] }); assert.ok(!card(x)); assert.equal(x.neonCalls.length, 1);
  assert.equal(x.layers.get(CLS[0]) && true, true);
});

test('LRT4 (LR-taps MINOR): LOAD POINTS states the real number when the window holds fewer than 40,000', async () => {
  const s1 = shard(KD[0], 6000, Date.parse(KD[0] + 'T10:00:00Z')), s2 = shard(KD[1], 6000, Date.parse(KD[1] + 'T10:00:00Z'));
  const rows = { [KD[0]]: s1.row, [KD[1]]: s2.row }, g = [{ date: KD[0], row: s1.row, cells: { [LC1]: 6000 } }, { date: KD[1], row: s2.row, cells: { [LC1]: 6000 } }];
  const x = boot({ phone: true, index: mkIndex(rows), files: mkGrids(g) }); x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.match(x.cap('flashes'), /LOAD POINTS adds the newest 12,000 flashes$/);
});

// ---------------------------------------------------------------- M-build: the 10 nearest REPD projects on a lightning tap
// The original's public measure (sld-sandbox 202609241334 link.measure): distanceKm = GEODESY haversine (R 6378.137 km,
// reproduced as hav above), representativePoint (cartridge :3356) and isProjectTech (PROJECT_TECHS, cartridge :1683).
const PTECH = new Set(['solar', 'solar_operational', 'solar_roof', 'bess', 'bess_operational', 'wind', 'wind_onshore', 'wind_onshore_operational', 'wind_offshore', 'wind_offshore_operational', 'biomass', 'hydro', 'hydrogen', 'tidal', 'geothermal', 'flywheel', 'caes', 'act', 'other']);
const repPoint = g => { if (!g) return null; if (g.type === 'Point') return [g.coordinates[0], g.coordinates[1]]; const ring = g.type === 'Polygon' ? g.coordinates[0] : g.type === 'MultiPolygon' ? g.coordinates[0]?.[0] : null; if (!Array.isArray(ring) || !ring.length) return null; let a = 0, b = 0; for (const p of ring) { a += p[0]; b += p[1]; } return [a / ring.length, b / ring.length]; };
const REPD_FILE = new URL('./fixtures/repd-master-v8-oracle.json.gz', import.meta.url);
const REPD_RAW = gunzipSync(readFileSync(REPD_FILE)); // required in CI: never skip silently
// the export of the pinned repd_master_v8_oracle.parquet (sha256 a737d00d…) used by M-build, MR and M2-build
assert.equal(createHash('sha256').update(REPD_RAW).digest('hex'), '15cc89a79450711970b0d5be08c3c82542be2103f6e9165c56a92c7fac70f61c', 'REPD fixture bytes changed');
const REPD_REAL = JSON.parse(REPD_RAW.toString('utf8'));
const pf = (lon, lat, p) => ({ type: 'Feature', geometry: { type: 'Point', coordinates: [lon, lat] }, properties: { name: 'P', tech: 'solar', raw_tech: 'Solar Photovoltaics', capacity: 10, status: 'operational', operator: '', mounting: 'nan', ...p } });
// installs the original's measure surface; repd = FeatureCollection; via 'source' (a REPD layer has loaded src-repd) or 'fetch'
const installRepd = (x, subs, repd, via = 'source', fetchImpl = null) => {
  installNeon(x, subs); x.sandbox.URLSearchParams = URLSearchParams; x.sandbox.location = { pathname: '/gridatlas/atlas/' }; const M = x.W.__GRIDATLAS_NEON_LINKS__.measure; x.distCalls = 0;
  Object.assign(M, { distanceKm: (a, b, c, d) => (x.distCalls++, hav(a, b, c, d)), representativePoint: repPoint, isProjectTech: t => PTECH.has(t), MAX_LINK_KM: 40 });
  x.repdFetch = []; const base = x.map.getSource;
  if (via === 'source') x.map.getSource = id => id === 'src-repd' ? { serialize: () => ({ type: 'geojson', data: repd }) } : base(id);
  const of = x.sandbox.fetch;
  x.sandbox.fetch = async (u, o) => { if (String(u).endsWith('/dist/repd_master.json')) { x.repdFetch.push(u); if (fetchImpl) return fetchImpl(u); return new Response(JSON.stringify(repd), { status: 200 }); } return of(u, o); };
};
const bruteTop = (repd, lon, lat) => repd.features.map(f => ({ f, a: repPoint(f.geometry) })).filter(r => r.a && PTECH.has(r.f.properties.tech)).map(r => ({ ...r, km: hav(lon, lat, r.a[0], r.a[1]) })).filter(r => r.km <= 40).sort((a, b) => a.km - b.km).slice(0, 10);
const prows = c => c.querySelectorAll('a');
const settle = async () => { for (let k = 0; k < 20; k++) await new Promise(r => setImmediate(r)); };
const NEWARK = [-0.81, 53.07];

// M2: co-located parts (same point) are one site row; exact duplicate rows count once; ties with the 10th site are kept.
// The independent brute force below reproduces that from the raw register (no module code).
const cf = v => String(v).replace(/\p{Cf}/gu, '').slice(0, 200);
const siteName = p => ({ solar: 'Solar', solar_roof: 'Rooftop solar' })[p.tech] || cf(p.raw_tech);
const bruteSites = (repd, lon, lat, keep = () => true) => {
  const seen = new Set(), m = new Map(), rows = [];
  for (const f of repd.features) {
    const a = repPoint(f.geometry), p = f.properties || {}; if (!a || !PTECH.has(p.tech) || !keep(p)) continue;
    const km = hav(lon, lat, a[0], a[1]); if (km > 40) continue;
    const k = a + JSON.stringify(p); if (seen.has(k)) continue; seen.add(k);
    rows.push({ a, km, p });
  }
  for (const r of rows.sort((x, y) => x.km - y.km)) { let g = [...m.values()].find(g => Math.abs(g.a[0] - r.a[0]) < 2e-4 && Math.abs(g.a[1] - r.a[1]) < 1e-4); if (!g) m.set(r.a.join(), g = { a: r.a, km: r.km, parts: [] }); g.parts.push(r.p); }
  const s = [...m.values()].sort((x, y) => x.km - y.km); return s.filter((g, i) => i < 10 || g.km === s[9].km);
};
const siteMW = g => [...new Set(g.parts.map(p => p.name + '|' + p.raw_tech + '|' + (p.capacity > 0 ? +p.capacity : 0)))].reduce((t, k) => t + +k.split('|').pop(), 0);
const siteLabel = g => `${g.km.toFixed(2)} km · ${[...new Set(g.parts.map(siteName))].sort().join(' + ')}${siteMW(g) > 0 ? ' ' + siteMW(g).toLocaleString('en-GB') + ' MW' : ''}`;
const siteRow = g => `${siteLabel(g)}${siteMW(g) > 0 ? '' : ' · capacity not stated'} · ${g.parts.length > 1 ? g.parts.length + ' projects at this point:' : cf(g.parts[0].status) + ' · ' + cf(g.parts[0].name)}`;

test('REPD1 (real REPD, engine source; M2 grouping): a flash near Newark lists the 10 nearest REPD sites of the full register, ascending, as the brute force over all 10,784 rows', { skip: !REPD_REAL }, async () => {
  const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', NEWARK)]) }); installRepd(x, SUBS.map(q => ({ ...q, at: [q.at[0] + 0.69, q.at[1] + 1.07] })), REPD_REAL);
  x.toggle(true); await drain(); tapFlash(x); await settle();
  const c = card(x), rows = [...prows(c)].map(r => r.textContent), want = bruteSites(REPD_REAL, ...NEWARK);
  assert.equal(REPD_REAL.features.length, 10784); assert.equal(want.length, 10); assert.deepEqual(rows, want.map(siteRow));
  assert.ok(want.some(g => g.parts.length > 1), 'Newark has a co-located site (the M2 grouping case)');
  assert.equal(x.distCalls, 10784, 'every register row measured with the original distanceKm');
  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; not evidence any project was struck\./);
  assert.match(c.children[0].children[0].textContent + c.textContent, / · 5 nearest substations · 10 nearest REPD sites/);
  const ln = x.sources.get('gridatlas-lightning-neon-plinks').data.features, nd = x.sources.get('gridatlas-lightning-neon-pnodes').data.features;
  assert.equal(ln.length, 10); assert.equal(nd.length, 10); for (const f of ln) assert.deepEqual([...f.geometry.coordinates[0]], NEWARK);
  assert.deepEqual(Array.from(nd, f => f.properties.label), want.map(siteLabel)); assert.deepEqual(Array.from(nd, f => f.properties.mw), want.map(siteMW));
  assert.equal(x.sources.get('gridatlas-lightning-neon-links').data.features.length, 5, 'the 5 substation links are kept');
  for (const id of ['p-core', 'p-node', 'p-label']) assert.ok(x.layers.get('gridatlas-lightning-neon-' + id), id);
  assert.notDeepEqual(x.layers.get('gridatlas-lightning-neon-p-core').paint['line-color'], '#d8c96a');
  assert.equal(x.repdFetch.length, 0, 'the engine source was used; no second fetch');
});

test('REPD2: labels read "2.14 km · Solar 49.9 MW"; unknown capacity shows no MW; every status and technology is eligible; rows deep-link the original way, never with a repd_ref', async () => {
  const repd = { type: 'FeatureCollection', features: [
    pf(-1.5, 52.0192, { name: 'Sun A', capacity: 49.9 }), pf(-1.5, 52.03, { name: 'Bat B', tech: 'bess', raw_tech: 'Battery', capacity: 0, status: 'application submitted' }),
    pf(-1.5, 52.04, { name: 'Wind C', tech: 'wind', raw_tech: 'Wind Onshore', capacity: 1200, status: 'awaiting construction' }), pf(-1.5, 52.05, { name: 'Roof D', tech: 'solar_roof', status: 'under construction' }),
    pf(-1.5, 52.06, { name: 'AD E', tech: 'biomass', raw_tech: 'Anaerobic Digestion', capacity: 2.5 }), pf(-1.5, 52.5, { name: 'Far F' }), pf(-1.5, 52.01, { name: 'Bad G', tech: 'nonsense' })] };
  const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installRepd(x, SUBS, repd, 'fetch');
  x.toggle(true); await drain(); tapFlash(x); await settle();
  const rows = [...prows(card(x))].map(r => r.textContent);
  assert.deepEqual(rows, ['2.14 km · Solar 49.9 MW · operational · Sun A', '3.34 km · Battery · capacity not stated · application submitted · Bat B', '4.45 km · Wind Onshore 1,200 MW · awaiting construction · Wind C', '5.57 km · Rooftop solar 10 MW · under construction · Roof D', '6.68 km · Anaerobic Digestion 2.5 MW · operational · AD E']);
  assert.match(card(x).textContent, /5 nearest REPD sites within 40 km/);
  const a = prows(card(x))[0], q = new URLSearchParams(a.href.split('?')[1]); assert.ok(a.href.startsWith('/gridatlas/atlas/?'), 'the row opens the page route, not the shell base: ' + a.href);
  assert.deepEqual(Object.fromEntries(q), { longitude: '-1.5', latitude: '52.0192', technology: 'solar', project: 'Sun A', capacity_mw: '49.9', status: 'operational' });
  for (const r of prows(card(x))) assert.doesNotMatch(r.href, /repd_ref/);
  assert.equal(x.repdFetch.length, 1); assert.equal(x.repdFetch[0], '/dist/repd_master.json');
});

test('REPD3: the register is fetched once per page (engine URL through the bridge) and reused; a failed fetch says so, keeps the substations, and the next tap retries', async () => {
  let fail = true; const repd = { type: 'FeatureCollection', features: [pf(-1.5, 52.01, { name: 'Near' })] };
  const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) });
  installRepd(x, SUBS, repd, 'fetch', async () => fail ? Promise.reject(new Error('network error')) : new Response(JSON.stringify(repd), { status: 200 }));
  x.toggle(true); await drain(); tapFlash(x); await settle();
  assert.match(card(x).textContent, /REPD projects unavailable: network error/); assert.equal(x.sources.get('gridatlas-lightning-neon-links').data.features.length, 5);
  assert.equal(x.sources.get('gridatlas-lightning-neon-plinks'), undefined);
  fail = false; tapFlash(x); await settle(); assert.equal(prows(card(x)).length, 1); tapFlash(x); await settle(); assert.equal(prows(card(x)).length, 1);
  assert.equal(x.repdFetch.length, 2, 'one failed + one good fetch; the third tap reuses the register');
  const y = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installRepd(y, SUBS, null, 'fetch', async () => new Response('x', { status: 503 }));
  y.toggle(true); await drain(); tapFlash(y); await settle(); assert.match(card(y).textContent, /REPD projects unavailable: HTTP 503/);
  const z = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installRepd(z, SUBS, { type: 'FeatureCollection', features: [] }, 'fetch');
  z.toggle(true); await drain(); tapFlash(z); await settle(); assert.match(card(z).textContent, /REPD projects unavailable: register empty/); assert.doesNotMatch(card(z).textContent, /No REPD site/);
});

test('REPD4: none within 40 km is stated; no project lines; the substation answer is unchanged', async () => {
  const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installRepd(x, SUBS, { type: 'FeatureCollection', features: [pf(-1.5, 53, { name: 'Far' })] });
  x.toggle(true); await drain(); tapFlash(x); await settle();
  assert.match(card(x).textContent, /Screening · No REPD site within 40 km of this optical flash, straight line\. Proximity only, not impact; not evidence any project was struck\./); assert.equal(prows(card(x)).length, 0);
  assert.match(card(x).textContent, / · no REPD site within 40 km/); assert.doesNotMatch(card(x).textContent, /Within 10 km/); assert.equal(x.sources.get('gridatlas-lightning-neon-plinks').data.features.length, 0);
});

test('REPD5: close, period switch, LATEST and OFF remove the project lines, nodes and labels; a register arriving after close draws nothing', async () => {
  const repd = { type: 'FeatureCollection', features: [pf(-1.5, 52.01, { name: 'Near' })] }, ids = ['p-core', 'p-node', 'p-label'].map(s => 'gridatlas-lightning-neon-' + s);
  const gone = x => { for (const id of ids) assert.equal(x.layers.get(id), undefined, id); assert.equal(x.sources.get('gridatlas-lightning-neon-plinks'), undefined); assert.equal(x.sources.get('gridatlas-lightning-neon-pnodes'), undefined); };
  const x = boot({ phone: true, index: mkIndex(KROWS), files: mkGrids(KGRID) }); x.map.setPaintProperty = () => {}; x.toggle(true);
  x.click(x.chip('30d')); await drain(); x.click(x.nav('prev')); await drain();
  const f0 = cellsSrc(x).data.features.find(q => q.properties.cell === LC1); installRepd(x, SUBS, { type: 'FeatureCollection', features: [pf(f0.properties.lon + 0.05, f0.properties.lat, { name: 'Near' })] });
  const open = async () => { cellHit(x, cellsSrc(x).data.features.find(q => q.properties.cell === LC1)); await settle(); assert.equal(x.sources.get('gridatlas-lightning-neon-plinks').data.features.length, 1, 'drawn'); };
  await open(); dispatch(card(x).querySelectorAll('button')[1], 'click', x.log.errors); gone(x);
  await open(); x.click(x.nav('latest')); gone(x); await drain();
  x.click(x.chip('12m')); await drain(); await open(); x.click(x.chip('6m')); gone(x); await drain();
  await open(); x.toggle(false); gone(x);
  let release; const y = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) });
  installRepd(y, SUBS, repd, 'fetch', () => new Promise(r => { release = () => r(new Response(JSON.stringify(repd), { status: 200 })); }));
  y.toggle(true); await drain(); tapFlash(y); await settle(); dispatch(card(y).querySelectorAll('button')[1], 'click', y.log.errors); release(); await settle(); gone(y);
  assert.deepEqual(y.log.errors.map(String), []);
});

test('REPD6: a cell tap measures projects from the cell centre; the camera frames origin, substations and projects (L3 padding)', async () => {
  const od = Object.getOwnPropertyDescriptor(El.prototype, 'offsetHeight');
  Object.defineProperty(El.prototype, 'offsetHeight', { configurable: true, get() { return 143; } });
  try {
    const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); x.toggle(true); x.click(x.chip('12m')); await drain();
    const f = cellsSrc(x).data.features[0], [lon, lat] = f.geometry.coordinates;
    const repd = { type: 'FeatureCollection', features: [pf(lon + 0.3, lat, { name: 'East' }), pf(lon, lat - 0.2, { name: 'South' })] };
    installRepd(x, SUBS, repd); x.mapEl._rect = { top: 0, left: 0, right: 393, bottom: 659, width: 393, height: 659 }; x.map.getBounds = () => ({ contains: () => false });
    cellHit(x, f); await settle();
    assert.deepEqual(x.neonCalls.at(-1).slice(0, 2), [lon, lat]); assert.equal(prows(card(x)).length, 2);
    assert.match(card(x).textContent, /2 nearest REPD sites within 40 km of this cell centre/);
    const fb = x.camera.filter(k => k[0] === 'fitBounds').at(-1); assert.ok(fb); const [[w, s], [e, n]] = fb[1][0], pad = fb[1][1].padding;
    for (const [a, b] of [[lon, lat], [lon + 0.3, lat], [lon, lat - 0.2]]) assert.ok(a >= w && a <= e && b >= s && b <= n, 'bbox misses ' + a + ',' + b);
    assert.equal(pad.top, 150); assert.equal(pad.bottom, card(x).bb + 143 + 24); assert.equal(fb[1][1].maxZoom, 12);
  } finally { if (od) Object.defineProperty(El.prototype, 'offsetHeight', od); else delete El.prototype.offsetHeight; }
});

test('REPD7: honest wording: never "affected" as a claim, never a strike on a site; the module never writes the URL', async () => {
  const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) }); installRepd(x, SUBS, { type: 'FeatureCollection', features: [pf(-1.5, 52.01)] });
  x.toggle(true); await drain(); tapFlash(x); await settle(); const t = card(x).textContent;
  assert.match(t, /[Nn]ot evidence any project was struck\./); assert.doesNotMatch(t, /(were|was|are|is) affected|strike on|struck the|hit the/i);
  assert.doesNotMatch(SRC.replace(/\bo\.repd_ref\b/g, ''), /repd_ref|location\.(href|search|hash|assign|replace)|history\.(push|replace)State|pushState/); // M5: a shown record's own ref only
});

// ---------------------------------------------------------------- M2-build: MR1-MR4 + the comprehensive REPD feature; each fails on Build M
const REPD_IND = structuredClone(REPD_REAL); // MR's independent DuckDB export of the pinned parquet: the same 10,784 rows, in the same order
const flashAt = async (ll, repd = REPD_IND, via = 'source', fi = null) => { const x = boot({ feedFn: () => feed([flash(Date.now() - H, 'z', ll)]) }); installRepd(x, SUBS.map(q => ({ ...q, at: [q.at[0] + 0.69, q.at[1] + 1.07] })), repd, via, fi); x.toggle(true); await drain(); tapFlash(x); await settle(); return x; };
const hangFetch = x => { const of = x.sandbox.fetch; x.sandbox.fetch = async (u, o) => { if (!String(u).endsWith('/dist/repd_master.json')) return of(u, o); x.repdFetch.push(u);
  return new Response(new ReadableStream({ start(c) { o && o.signal && o.signal.addEventListener('abort', () => c.error(new DOMException('Aborted', 'AbortError'))); } }), { status: 200 }); }; };
const FCx = f => ({ type: 'FeatureCollection', features: f });
const rowsOf = x => [...prows(card(x))].map(a => a.textContent);
const chip = (x, k) => card(x).querySelector(`[data-lightning-repd-filter="${k}"]`);
const press = (x, k) => dispatch(chip(x, k), 'click', x.log.errors);
const tapRow = (x, i = 0) => { const a = prows(card(x))[i]; let prevented = false; for (const f of a.listeners.click || []) f({ type: 'click', target: a, preventDefault: () => { prevented = true; }, stopPropagation() {} }); return prevented; };
const flash0 = () => boot({ feedFn: () => feed([flash(Date.now() - H, 'z', [-1.5, 52])]) });

test('MR-A (M2 grouping): with the independent register, the rows equal the independent brute force (sites, co-located parts grouped) at 7 dense and sparse points', async () => {
  for (const ll of [[-0.81, 53.07], [-0.85, 52.75], [-0.35, 53.25], [0.15, 53.05], [-4.95, 57.95], [-5.15, 57.65], [-3.85, 58.45]]) {
    const x = await flashAt(ll); assert.deepEqual(rowsOf(x), bruteSites(REPD_IND, ...ll).map(siteRow), ll.join());
  }
});
test('M2-MR1: a register body that never completes (stalled bridge) is reported after the 15 s timeout, the substations stay, and the next tap retries', async () => {
  const x = flash0(); installRepd(x, SUBS, null, 'fetch'); hangFetch(x);
  x.toggle(true); await drain(); tapFlash(x); await settle(); assert.match(card(x).textContent, /REPD projects: loading…/);
  await new Promise(r => setTimeout(r, 15500)); await settle();
  assert.match(card(x).textContent, /REPD projects unavailable: timeout after 15 s/); assert.doesNotMatch(card(x).textContent, /loading…/);
  assert.equal(x.sources.get('gridatlas-lightning-neon-links').data.features.length, 5, 'substation links kept');
  tapFlash(x); await settle(); assert.equal(x.repdFetch.length, 2, 'the next tap retries');
});
test('M2-MR1b: a redirected register response is refused like every other module fetch', async () => {
  const x = flash0();
  installRepd(x, SUBS, null, 'fetch', async () => { const r = new Response(JSON.stringify(FCx([pf(-1.5, 52.01)])), { status: 200 }); Object.defineProperty(r, 'redirected', { value: true }); return r; });
  x.toggle(true); await drain(); tapFlash(x); await settle(); assert.match(card(x).textContent, /REPD projects unavailable: redirected/); assert.equal(prows(card(x)).length, 0);
});
test('M2-MR1c (bridge keeps a failed start): the first failure says "tap again"; a repeated failure adds the switch-on-a-REPD-layer / reload advice', async () => {
  const x = flash0(); installRepd(x, SUBS, null, 'fetch', async () => Promise.reject(new Error('DuckDB start failed')));
  x.toggle(true); await drain(); tapFlash(x); await settle();
  assert.match(card(x).textContent, /REPD projects unavailable: DuckDB start failed\. Tap the flash again to retry\./); assert.doesNotMatch(card(x).textContent, /reload/);
  assert.match(card(x).querySelector('summary').textContent, / · REPD unavailable$/, 'M2R-a11y: the collapsed card says so');
  tapFlash(x); await settle(); assert.match(card(x).textContent, /REPD projects unavailable: DuckDB start failed\. Switch on a REPD layer or reload the page, then tap again\./);
  assert.equal(x.repdFetch.length, 2);
});
test('M2-MR2: exact duplicate register rows are listed once (Kelvin Energy Recovery Facility, real register); same point with other properties is one grouped site', async () => {
  const x = await flashAt([-1.99, 52.51]), t = card(x).textContent; assert.equal(t.split('Kelvin Energy Recovery Facility').length - 1, 1, 'listed once');
  const d = pf(-1.5, 52.01, { name: 'Dup' }), y = await flashAt([-1.5, 52], FCx([d, structuredClone(d)]));
  assert.equal(rowsOf(y).length, 1); assert.doesNotMatch(rowsOf(y)[0], /co-located/); assert.match(card(y).textContent, /1 nearest REPD site within/);
  const z = await flashAt([-1.5, 52], FCx([d, structuredClone(d), pf(-1.5, 52.01, { name: 'Dup', tech: 'bess', raw_tech: 'Battery' })]));
  assert.equal(rowsOf(z).length, 1); assert.match(rowsOf(z)[0], / · Battery \+ Solar 20 MW · 2 projects at this point:$/);
});
test('M2-MR3: Steeple Renewables solar and its co-located BESS are one site; a different site tied with the 10th is kept; an 11th farther site is not', async () => {
  const x = await flashAt([-0.75, 53.35]), r = rowsOf(x).filter(s => /^4\.92 km · /.test(s));
  assert.equal(r.length, 1); assert.match(r[0], /Battery \+ Solar 1,100 MW · 3 projects at this point:$/); assert.equal(card(x).textContent.split('Steeple Renewables Project').length - 1, 2, 'its two listed parts (solar and BESS), named beneath the row');
  const f = [...Array(9)].map((_, i) => pf(-1.5, 52 + 0.01 * (i + 1), { name: 'R' + i })); f.push(pf(-1.34, 52, { name: 'TieE' }), pf(-1.66, 52, { name: 'TieW' }), pf(-1.5, 52.2, { name: 'Far' }));
  const y = await flashAt([-1.5, 52], FCx(f)), yr = rowsOf(y);
  assert.equal(yr.length, 11); assert.ok(yr.some(s => /TieE$/.test(s)) && yr.some(s => /TieW$/.test(s))); assert.ok(!yr.some(s => /Far$/.test(s)));
  assert.match(card(y).textContent, /11 nearest REPD sites within 40 km/); assert.equal(y.sources.get('gridatlas-lightning-neon-pnodes').data.features.length, 11);
});
test('M2-MR4: a register landing while the map is still moving is framed when that move ends', async () => {
  let release; const repd = FCx([pf(-1.5, 52.3, { name: 'FarNorth' })]), x = flash0();
  installRepd(x, SUBS, repd, 'fetch', () => new Promise(r => { release = () => r(new Response(JSON.stringify(repd), { status: 200 })); }));
  x.map.getBounds = () => ({ contains: ([a, b]) => b < 52.2 }); x.toggle(true); await drain(); tapFlash(x); await settle();
  const q = []; x.map.once = (t, f) => q.push([t, f]); x.map.isMoving = () => true; release(); await settle();
  assert.equal(prows(card(x)).length, 1); const n0 = x.camera.filter(k => k[0] === 'fitBounds').length;
  x.map.isMoving = () => false; for (const [t, f] of q.splice(0)) if (t === 'moveend') f(); await settle();
  const fb = x.camera.filter(k => k[0] === 'fitBounds'); assert.equal(fb.length, n0 + 1, 'reframed at moveend');
  const [[w, s], [e, n]] = fb.at(-1)[1][0]; assert.ok(n >= 52.3 && s <= 52 && w <= -1.5 && e >= -1.5, 'FarNorth and the origin are framed');
});
test('M2-MR4b: the moveend wait is harmless after close (no reframe, no throw)', async () => {
  let release; const repd = FCx([pf(-1.5, 52.3, { name: 'FarNorth' })]), x = flash0();
  installRepd(x, SUBS, repd, 'fetch', () => new Promise(r => { release = () => r(new Response(JSON.stringify(repd), { status: 200 })); }));
  x.map.getBounds = () => ({ contains: ([a, b]) => b < 52.2 }); x.toggle(true); await drain(); tapFlash(x); await settle();
  const q = []; x.map.once = (t, f) => q.push([t, f]); x.map.isMoving = () => true; release(); await settle();
  dispatch(card(x).querySelectorAll('button')[1], 'click', x.log.errors); await settle(); assert.equal(x.sources.get('gridatlas-lightning-neon-plinks'), undefined, 'closed');
  const n0 = x.camera.filter(k => k[0] === 'fitBounds').length; for (const [t, f] of q.splice(0)) if (t === 'moveend') f(); await settle();
  assert.equal(x.camera.filter(k => k[0] === 'fitBounds').length, n0); assert.deepEqual(x.log.errors.map(String), []);
});

test('M2-C1 co-located: solar + battery at one point are one link, one node and one label ("2.64 km · Battery + Solar 69.9 MW"), with every part listed in the card', async () => {
  const lat = 52 + 2.64 / 111.32, x = await flashAt([-1.5, 52], FCx([pf(-1.5, lat, { name: 'Sun Farm', capacity: 49.9 }), pf(-1.5, lat, { name: 'Sun Farm BESS', tech: 'bess', raw_tech: 'Battery', capacity: 20, status: 'awaiting construction' }), pf(-1.5, 52.1, { name: 'Other' })]));
  const km = hav(-1.5, 52, -1.5, lat).toFixed(2); assert.equal(km, '2.64');
  assert.deepEqual(rowsOf(x), ['2.64 km · Battery + Solar 69.9 MW · 2 projects at this point:', rowsOf(x)[1]]);
  const t = card(x).textContent; assert.match(t, /Solar 49\.9 MW · operational · Sun Farm/); assert.match(t, /Battery 20 MW · awaiting construction · Sun Farm BESS/);
  assert.match(t, /2 nearest REPD sites \(3 projects; those at one point grouped\) within 40 km/);
  const nd = x.sources.get('gridatlas-lightning-neon-pnodes').data.features, ln = x.sources.get('gridatlas-lightning-neon-plinks').data.features;
  assert.equal(nd.length, 2); assert.equal(ln.length, 2); assert.equal(nd[0].properties.label, '2.64 km · Battery + Solar 69.9 MW'); assert.equal(nd[0].properties.mw, 69.9);
});
test('M2-C2 filters: All / Operational / Consented & construction / Planning and All / Solar / Wind / BESS / Other; default All; the nearest 10 are re-ranked within the filter; lines follow', async () => {
  const f = [...Array(12)].map((_, i) => pf(-1.5, 52 + 0.01 * (i + 1), { name: 'Await' + i, status: 'awaiting construction' }));
  f.push(pf(-1.5, 52.3, { name: 'OpSolar' }), pf(-1.5, 52.31, { name: 'OpBess', tech: 'bess', raw_tech: 'Battery' }), pf(-1.5, 52.32, { name: 'UC Wind', tech: 'wind_onshore', raw_tech: 'Wind Onshore', status: 'under construction' }),
    pf(-1.5, 52.33, { name: 'Plan Hydro', tech: 'hydro', raw_tech: 'Small Hydro', status: 'application submitted' }));
  const x = await flashAt([-1.5, 52], FCx(f)), lines = () => x.sources.get('gridatlas-lightning-neon-plinks').data.features.length;
  for (const k of ['st:all', 'st:op', 'st:cc', 'st:pl', 'te:all', 'te:solar', 'te:wind', 'te:bess', 'te:other']) assert.ok(chip(x, k), k);
  assert.deepEqual(['Operational', 'Consented', 'Planning', 'Solar', 'Wind', 'BESS', 'Other'].map(t => card(x).querySelectorAll('button').some(b => b.textContent === t)), Array(7).fill(true));
  assert.equal(chip(x, 'st:all').getAttribute('aria-pressed'), 'true'); assert.equal(chip(x, 'te:all').getAttribute('aria-pressed'), 'true');
  assert.equal(rowsOf(x).length, 10); assert.ok(rowsOf(x).every(r => /Await/.test(r)));
  press(x, 'st:op'); assert.deepEqual(rowsOf(x).map(r => r.split(' · ').pop()), ['OpSolar', 'OpBess']); assert.equal(lines(), 2);
  assert.equal(chip(x, 'st:op').getAttribute('aria-pressed'), 'true'); assert.equal(chip(x, 'st:all').getAttribute('aria-pressed'), 'false');
  assert.match(card(x).textContent, /2 nearest REPD sites within 40 km of this optical flash, straight line \(Operational\)\. Proximity only, not impact; not evidence any project was struck\./);
  press(x, 'te:bess'); assert.deepEqual(rowsOf(x).map(r => r.split(' · ').pop()), ['OpBess']); assert.match(card(x).textContent, /straight line \(Operational · BESS\)/); assert.match(card(x).querySelector('summary').textContent, / · 1 nearest REPD site \(Operational · BESS\)$/);
  press(x, 'st:cc'); press(x, 'te:all'); assert.equal(rowsOf(x).length, 10); assert.ok(rowsOf(x).every(r => /Await/.test(r)));
  press(x, 'te:wind'); assert.deepEqual(rowsOf(x).map(r => r.split(' · ').pop()), ['UC Wind']);
  press(x, 'st:pl'); press(x, 'te:other'); assert.deepEqual(rowsOf(x).map(r => r.split(' · ').pop()), ['Plan Hydro']);
  press(x, 'te:solar'); assert.match(card(x).textContent, /No REPD site within 40 km of this optical flash, straight line \(Planning · Solar\)/); assert.equal(lines(), 0);
  press(x, 'st:all'); press(x, 'te:all'); assert.equal(rowsOf(x).length, 10); assert.equal(lines(), 10);
  press(x, 'st:op'); tapFlash(x); await settle(); assert.equal(chip(x, 'st:op').getAttribute('aria-pressed'), 'true', 'the filter is kept for the next tap'); assert.equal(rowsOf(x).length, 2);
  assert.deepEqual(x.log.errors.map(String), []);
});
test('M2-C3 summary: "N REPD projects within 10 km · M within 40 km · total X MW within 10 km", follows the filter, and states uncounted capacity honestly', async () => {
  const x = await flashAt([-1.5, 52], FCx([pf(-1.5, 52.018, { capacity: 10, name: 'A' }), pf(-1.5, 52.045, { capacity: 0, name: 'B', status: 'application submitted' }), pf(-1.5, 52.18, { capacity: 100, name: 'C' }), pf(-1.5, 52.5, { name: 'Out' })]));
  assert.match(card(x).textContent, /Within 10 km: 2 projects · 10 MW stated, mixed statuses, 1 not stated · within 40 km: 3 projects/);
  press(x, 'st:op'); assert.match(card(x).textContent, /Within 10 km: 1 project · 10 MW stated, Operational · within 40 km: 2 projects/);
  const y = await flashAt([-1.5, 52], FCx([pf(-1.5, 52.5)])); assert.doesNotMatch(card(y).textContent, /Within 10 km|0 MW/);
  const z = await flashAt([-1.5, 52], FCx([pf(-1.5, 52.01, { capacity: 0 }), pf(-1.5, 52.3, { capacity: 5 })])); assert.match(card(z).textContent, /Within 10 km: 1 project · capacity not stated · within 40 km: 2 projects/); assert.doesNotMatch(card(z).textContent, / 0 MW/);
});
test('M2-C4 fewer than 10: stated, with the radius kept at 40 km; not stated when 10 exist', async () => {
  const x = await flashAt([-1.5, 52], FCx([pf(-1.5, 52.01), pf(-1.5, 52.02), pf(-1.5, 52.03), pf(-1.5, 52.6)]));
  assert.match(card(x).textContent, /Only 3 sites within the 40 km search radius\./);
  const y = await flashAt([-1.5, 52], FCx([...Array(12)].map((_, i) => pf(-1.5, 52 + 0.01 * (i + 1))))); assert.doesNotMatch(card(y).textContent, /Only \d+ site/);
  press(y, 'st:op'); assert.doesNotMatch(card(y).textContent, /Only \d+ site/);
});
test('M2-C5 row tap stays in the page: no navigation; flies to the project and draws its nearest-substation links; "◀ back to lightning flash" restores the card, links and list', async () => {
  const x = flash0(); installRepd(x, SUBS, FCx([pf(-1.45, 52.02, { name: 'Sun A', capacity: 49.9 }), pf(-1.45, 52.02, { name: 'Bat A', tech: 'bess', raw_tech: 'Battery', capacity: 20 }), pf(-1.5, 52.1, { name: 'B' })]), 'fetch');
  x.toggle(true); await drain(); tapFlash(x); await settle();
  const href = prows(card(x))[0].href; assert.ok(href.startsWith('/gridatlas/atlas/?'), 'the deep link stays as the href (open in new tab)');
  x.camera.length = 0; const n0 = x.neonCalls.length; assert.equal(tapRow(x, 0), true, 'default navigation prevented'); await settle();
  const c = card(x); assert.equal(c.getAttribute('aria-label'), 'REPD project'); assert.equal(x.S.pp, c);
  assert.deepEqual(x.neonCalls.at(-1).slice(0, 2), [-1.45, 52.02]); assert.equal(x.neonCalls.length, n0 + 1);
  const fly = x.camera.find(k => k[0] === 'flyTo'); assert.deepEqual([...fly[1][0].center], [-1.45, 52.02]); assert.equal(fly[1][0].zoom, 12);
  assert.equal(x.sources.get('gridatlas-lightning-neon-links').data.features.length, 5, 'the 5 substation links from the project');
  assert.equal(x.sources.get('gridatlas-lightning-neon-plinks'), undefined, 'no project list in the project view');
  assert.match(c.textContent, /REPD · Battery \+ Solar 69\.9 MW/); assert.match(c.textContent, /2 projects at this point · Sun A \/ Bat A/);
  assert.match(c.textContent, /Solar 49\.9 MW · operational · Sun A; Battery 20 MW · operational · Bat A/);
  assert.match(c.textContent, /Screening · nearest substations, straight line\. Not its declared connection or capacity\./);
  assert.match(c.textContent, /4\.09 km from the optical flash \(straight-line\)/); assert.match(c.textContent, /Record · REPD \(DESNZ, Apr 2026, OGL v3\.0\)\. Status as registered, not as built\. Lightning: optical flashes, not ground strikes; not evidence the project was struck\./); assert.doesNotMatch(c.textContent, /(were|was|are|is) affected|strike on|struck the|hit the/i);
  const back = c.querySelector('[data-lightning-back]'); assert.equal(back.textContent, '◀ back to lightning flash'); assert.equal(c.querySelectorAll('button')[1].getAttribute('aria-label'), 'Close');
  dispatch(back, 'click', x.log.errors); await settle();
  const d = card(x); assert.equal(d.getAttribute('aria-label'), 'Lightning flash'); assert.deepEqual(x.neonCalls.at(-1).slice(0, 2), [-1.5, 52]);
  assert.equal(rowsOf(x).length, 2); assert.equal(x.sources.get('gridatlas-lightning-neon-plinks').data.features.length, 2); assert.equal(d.querySelector('details').open, true, 'M6: restored as at the tap (open by default; the card is at most 45 % of the map, so the camera frames the links above it)');
  assert.equal(x.repdFetch.length, 1, 'the register is reused'); assert.deepEqual(x.log.errors.map(String), []);
});
test('M2-C6 row tap from a cell: "◀ back to lightning cell"; close, period switch and OFF clean the project view', async () => {
  const x = boot({ phone: true, index: mkIndex(KROWS), files: mkGrids(KGRID) }); x.map.setPaintProperty = () => {}; x.toggle(true); x.click(x.chip('12m')); await drain();
  const f0 = cellsSrc(x).data.features.find(q => q.properties.cell === LC1), lon = f0.properties.lon, lat = f0.properties.lat; installRepd(x, SUBS, FCx([pf(lon + 0.05, lat, { name: 'Near' })]));
  const open = async () => { cellHit(x, cellsSrc(x).data.features.find(q => q.properties.cell === LC1)); await settle(); tapRow(x, 0); await settle(); assert.equal(card(x).getAttribute('aria-label'), 'REPD project'); };
  await open(); const back = card(x).querySelector('[data-lightning-back]'); assert.equal(back.textContent, '◀ back to lightning cell');
  dispatch(back, 'click', x.log.errors); await settle(); assert.equal(card(x).getAttribute('aria-label'), 'Lightning cell'); assert.match(card(x).textContent, /1 nearest REPD site within 40 km of this cell centre/);
  const gone = () => { assert.equal(x.S.pp, null); for (const s of ['links', 'nodes', 'pin', 'plinks', 'pnodes']) assert.equal(x.sources.get('gridatlas-lightning-neon-' + s), undefined, s); };
  await open(); dispatch(card(x).querySelectorAll('button')[1], 'click', x.log.errors); gone();
  await open(); x.click(x.chip('6m')); gone(); await drain();
  await open(); x.toggle(false); gone(); assert.deepEqual(x.log.errors.map(String), []);
});
test('M2-C7 a project with no substation within 40 km is still flown to (zoom 12), states it, and keeps "◀ back"', async () => {
  const x = flash0(); installRepd(x, SUBS, FCx([pf(-1.5, 52.3, { name: 'North' })]), 'fetch'); x.toggle(true); await drain(); tapFlash(x); await settle();
  x.W.__GRIDATLAS_NEON_LINKS__.substations = SUBS.map(q => ({ ...q, at: [q.at[0] - 3, q.at[1] - 3] })); x.camera.length = 0; tapRow(x, 0); await settle();
  assert.match(card(x).textContent, /No substation within 40 km/); const fly = x.camera.find(k => k[0] === 'flyTo'); assert.ok(fly, 'flown'); assert.deepEqual([...fly[1][0].center], [-1.5, 52.3]);
  assert.ok(card(x).querySelector('[data-lightning-back]'));
});
test('M2-C8 framing: a card taller than the room left by the 150 px top padding no longer blocks fitBounds (bottom padding clamped to height − 270)', async () => {
  const od = Object.getOwnPropertyDescriptor(El.prototype, 'offsetHeight'); Object.defineProperty(El.prototype, 'offsetHeight', { configurable: true, get() { return 521; } });
  try { const x = flash0(); installRepd(x, SUBS, FCx([pf(-1.5, 52.3)])); x.mapEl.clientHeight = 659; 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, 659 - 270); assert.equal(fb[1][1].padding.top, 150);
  } finally { if (od) Object.defineProperty(El.prototype, 'offsetHeight', od); else delete El.prototype.offsetHeight; }
});
test('M2-MR1d: a stalled register body whose stream errors with a non-Abort error after the 15 s abort is still reported as the timeout', async () => {
  const x = flash0(); installRepd(x, SUBS, null, 'fetch'); const of = x.sandbox.fetch;
  x.sandbox.fetch = async (u, o) => { if (!String(u).endsWith('/dist/repd_master.json')) return of(u, o); x.repdFetch.push(u);
    return new Response(new ReadableStream({ start(c) { o.signal.addEventListener('abort', () => c.error(new TypeError('Failed to fetch'))); } }), { status: 200 }); };
  x.toggle(true); await drain(); tapFlash(x); await settle(); await new Promise(r => setTimeout(r, 15500)); await settle();
  assert.match(card(x).textContent, /REPD projects unavailable: timeout after 15 s\. Tap the flash again to retry\./);
});

// ---------------------------------------------------------------- CI additions (tools/ci/pr-gate.mjs): mutants that the M2 suite let through
// Mutation run of 28 Oct 2026 (hardening lane M2R-ci): 18 single-point bugs in 202610282100; the M2 suite let two
// through. CI1 and CI2 catch "OFF leaves the dots layer behind". The other, "the tap-time cell index guard (< 16,800)
// is gone", is left: the grid parser already refuses such cells, and a test that taps a forged out-of-grid cell sends
// that mutant into a runaway allocation that kills the whole suite process rather than failing one test.
// MapLibre refuses to remove a source while a layer still uses it; the stub map in boot() did not, so a cleanup that
// forgot a layer still looked clean.
const strictRemoval = x => { x.map.removeSource = id => { for (const l of x.layers.values()) if (l.source === id) throw new Error(`Source "${id}" cannot be removed while layer "${l.id}" is using it.`); x.sources.delete(id); }; };
const lightningLeft = x => [...x.layers.keys(), ...x.sources.keys()].filter(id => /lightning/.test(id));

test('CI1: OFF after flashes, a flash card with REPD rows and a project view leaves no lightning layer or source (MapLibre removal rules)', async () => {
  const x = await flashAt([-0.81, 53.07]); strictRemoval(x);
  assert.ok(x.layers.has('l-gridatlas-lightning'), 'flash dots drawn'); assert.ok(prows(card(x)).length > 0, 'REPD rows listed');
  tapRow(x, 0); await settle(); assert.match(card(x).textContent, /◀ back to lightning flash/);
  x.toggle(false); await drain();
  assert.deepEqual(lightningLeft(x), [], 'left behind after OFF'); assert.equal(card(x), null, 'card closed'); assert.deepEqual(x.log.errors.map(String), []);
});

test('CI2: OFF after 12M cells and a cell card leaves no lightning layer or source (MapLibre removal rules)', async () => {
  const x = boot({ index: mkIndex(KROWS), files: mkGrids(KGRID) }); installNeon(x, SUBS); strictRemoval(x);
  x.toggle(true); x.click(x.chip('12m')); await drain();
  assert.ok(cellsSrc(x) && cellsSrc(x).data.features.length > 0, 'cells drawn');
  cellHit(x, cellsSrc(x).data.features[0]); await settle(); assert.ok(card(x), 'cell card');
  x.toggle(false); await drain();
  assert.deepEqual(lightningLeft(x), [], 'left behind after OFF'); assert.deepEqual(x.log.errors.map(String), []);
});


// ---------------------------------------------------------------- M3-build: auto-activate the REPD layers of the listed projects
// Engine stand-in (original substation-intelligence cartridge, buildDOM/handleLayerToggle :1060-1190 and menuBar :4386-6080):
// the REPD group of #scada-ui-container (input[data-layer-id] + span#lbl-<id>[data-base-label]), its fullscreen-curtain copy,
// the container's delegated change listener (syncs the curtain copy, then handleLayerToggle -> layer visibility), and the
// menu bar's document-level change listener that syncs its proxy. Nothing here calls module code.
El.prototype.dispatchEvent = function (ev) { dispatch(this, ev.type, this.__errs || []); return true; };
const REPD_LAYERS = [['solar', 'Solar PV'], ['solar_operational', 'Solar PV (Operational Only)'], ['solar_roof', 'Solar Roof'], ['wind', 'Wind'], ['wind_onshore_operational', 'Onshore Wind (Operational Only)'], ['bess', 'Battery Storage'], ['biomass', 'Biomass & EfW'], ['tidal', 'Tidal & Wave'], ['hydrogen', 'Hydrogen'], ['hydro', 'Hydro & Pumped Storage'], ['flywheel', 'Flywheel'], ['act', 'Advan  … [line shortened here: 484 characters; full line on GitHub]
const installLayers = (x, { userOn = [], disabled = [] } = {}) => {
  x.sandbox.Event = class { constructor(t, o) { this.type = t; this.bubbles = !!(o && o.bubbles); } };
  const doc = x.doc, curtain = doc.getElementById('fs-curtain-keys'), E = { toggles: [], main: {}, fs: {}, proxy: {} };
  const group = (host, pre) => { const g = doc.createElement('div'); g.className = 'key-group'; const t = doc.createElement('div'); t.className = 'key-title'; t.textContent = 'REPD (GeoJSON)'; g.appendChild(t);
    for (const [id, lab] of REPD_LAYERS) { const l = doc.createElement('label'); l.className = 'key-item'; const i = doc.createElement('input'); i.type = 'checkbox'; i.setAttribute('data-layer-id', id);
      const s = doc.createElement('span'); s.id = pre + id; s.setAttribute('data-base-label', lab); s.textContent = lab + ' [WAIT]'; l.appendChild(i); l.appendChild(s); g.appendChild(l); (pre === 'lbl-' ? E.main : E.fs)[id] = i; }
    host.insertBefore(g, host.children[1] || null); };
  group(x.host, 'lbl-'); group(curtain, 'fs-lbl-');
  for (const [id] of REPD_LAYERS) { x.layers.set('l-' + id, { id: 'l-' + id, source: 'src-repd', layout: { visibility: 'none' } }); E.proxy[id] = { checked: false }; }
  const handleLayerToggle = (id, on) => { E.toggles.push([id, on]); x.map.setLayoutProperty('l-' + id, 'visibility', on ? 'visible' : 'none'); };
  x.host.addEventListener('change', e => { const id = e.target.getAttribute && e.target.getAttribute('data-layer-id'); if (!id) return; E.fs[id].checked = e.target.checked; handleLayerToggle(id, e.target.checked); });
  curtain.addEventListener('change', e => { const id = e.target.getAttribute && e.target.getAttribute('data-layer-id'); if (!id) return; E.main[id].checked = e.target.checked; handleLayerToggle(id, e.target.checked); });
  doc.documentElement.addEventListener('change', e => { const id = e.target.getAttribute && e.target.getAttribute('data-layer-id'); if (id) E.proxy[id].checked = !!E.main[id].checked; });
  x.map.getStyle = () => ({ layers: [...x.layers.values()].map(l => ({ id: l.id, type: l.type, source: l.source })) }); x.map.getLayoutProperty = (id, k) => ((x.layers.get(id) || {}).layout || {})[k];
  for (const id of disabled) E.main[id].disabled = true;
  for (const id of userOn) userTick(x, E, id, true);
  E.toggles.length = 0; x.E = E; return E;
};
// a reader's tap on the original checkbox (main panel or curtain): the browser flips `checked`, then "change" bubbles
const userTick = (x, E, id, on, where = 'main') => { const i = E[where][id]; i.checked = on; dispatch(i, 'change', x.log.errors); };
const onIds = E => REPD_LAYERS.map(r => r[0]).filter(id => E.main[id].checked);
const inSync = E => { for (const [id] of REPD_LAYERS) { const v = !!E.main[id].checked; assert.equal(!!E.fs[id].checked, v, 'curtain ' + id); assert.equal(E.proxy[id].checked, v, 'menu proxy ' + id); } };
const visible = x => REPD_LAYERS.map(r => r[0]).filter(id => x.layers.get('l-' + id).layout.visibility === 'visible');
const inspect = x => { const n = x.host.querySelectorAll('input[data-layer-id]').length; return n; };
const closeCard = x => dispatch(card(x).querySelectorAll('button')[1], 'click', x.log.errors);
const techsOf = sites => [...new Set(sites.flatMap(g => g.parts.map(p => p.tech)))].filter(t => REPD_LAYERS.some(r => r[0] === t)).sort();
const S3 = SUBS.map(q => ({ ...q, at: [q.at[0] + 0.45, q.at[1] + 1.45] })); // substations moved near Doncaster
const DONC = [-1.05, 53.45];
// two flashes (index 0 older, index 1 newer) so a second tap can land elsewhere on the same result
const boot3 = async (ll0, ll1, repd, opts = {}) => { const x = boot({ feedFn: () => feed([flash(Date.now() - 2 * H, 'a', ll0), flash(Date.now() - H, 'b', ll1 || ll0)]) });
  installRepd(x, S3, repd, opts.via || 'source', opts.fetchImpl || null); const E = installLayers(x, opts); x.toggle(true); await drain(); return { x, E }; };
const SYN = FCx([pf(-1.5, 52.01, { name: 'S1' }), pf(-1.5, 52.02, { name: 'B1', tech: 'bess', raw_tech: 'Battery' }), pf(-1.5, 52.03, { name: 'W1', tech: 'wind', raw_tech: 'Wind Onshore' }),
  pf(-3.0, 55.01, { name: 'H1', tech: 'hydro', raw_tech: 'Small Hydro' }), pf(-3.0, 55.02, { name: 'R1', tech: 'solar_roof' }), pf(-3.0, 55.03, { name: 'O1', tech: 'other', raw_tech: 'Unknown' })]);

(M4B ? test.skip : test)('M3-1: a tap switches on exactly the REPD layers of the listed technologies, through the original checkbox path; close switches them off again', async () => {
  const { x, E } = await boot3([-1.5, 52], null, SYN), n0 = inspect(x);
  assert.equal(E.toggles.length, 0, 'nothing switched before a tap'); assert.equal(x.S.ly, undefined);
  tapFlash(x, 0); await settle();
  assert.deepEqual(onIds(E), ['bess', 'solar', 'wind'].sort((a, b) => REPD_LAYERS.findIndex(r => r[0] === a) - REPD_LAYERS.findIndex(r => r[0] === b)));
  assert.deepEqual([...x.S.ly].sort(), ['bess', 'solar', 'wind']); assert.deepEqual(E.toggles.map(t => t.join()).sort(), ['bess,true', 'solar,true', 'wind,true']);
  assert.deepEqual(visible(x).sort(), ['bess', 'solar', 'wind']); inSync(E); assert.equal(inspect(x), n0, 'no control added or removed');
  assert.match(card(x).textContent, /REPD map layers on for this list: Solar PV, Battery Storage, Wind \(those switched on here go off when this card closes\)/);
  E.toggles.length = 0; closeCard(x);
  assert.equal(card(x), null); assert.deepEqual(onIds(E), []); assert.deepEqual(visible(x), []); assert.equal(x.S.ly.size, 0); inSync(E);
  assert.deepEqual(E.toggles.map(t => t.join()).sort(), ['bess,false', 'solar,false', 'wind,false']); assert.equal(x.log.errors.length, 0);
});
(M4B ? test.skip : test)('M3-2: a layer the user had on already is never switched (on or off) by M3 and survives close; the rest of the user state is restored exactly', async () => {
  const { x, E } = await boot3([-1.5, 52], null, SYN, { userOn: ['solar', 'hydro', 'solar_operational'] });
  const before = onIds(E); tapFlash(x, 0); await settle();
  assert.deepEqual([...x.S.ly].sort(), ['bess', 'wind']); assert.ok(!E.toggles.some(t => t[0] === 'solar'), 'solar untouched');
  assert.match(card(x).textContent, /REPD map layers on for this list: Solar PV, Battery Storage, Wind \(those/);
  closeCard(x); assert.deepEqual(onIds(E), before); inSync(E); assert.deepEqual(visible(x).sort(), ['hydro', 'solar', 'solar_operational']);
});
(M4B ? test.skip : test)('M3-3: a new tap whose list needs other technologies switches off only what M3 switched on and is no longer needed; the same list toggles nothing', async () => {
  const { x, E } = await boot3([-1.5, 52], [-3.0, 55], SYN, { userOn: ['hydro'] });
  tapFlash(x, 0); await settle(); assert.deepEqual([...x.S.ly].sort(), ['bess', 'solar', 'wind']);
  E.toggles.length = 0; tapFlash(x, 1); await settle();
  assert.deepEqual([...x.S.ly].sort(), ['solar_roof'], 'hydro was the user\'s; other has no layer');
  assert.deepEqual(E.toggles.map(t => t.join()).sort(), ['bess,false', 'solar,false', 'solar_roof,true', 'wind,false']);
  assert.deepEqual(onIds(E).sort(), ['hydro', 'solar_roof']); inSync(E);
  E.toggles.length = 0; tapFlash(x, 1); await settle(); assert.deepEqual(E.toggles, [], 'same list: no toggles');
  closeCard(x); assert.deepEqual(onIds(E), ['hydro']);
});
(M4B ? test.skip : test)('M3-4: the layers follow the card filter (Tech: Solar drops Battery and Wind; All brings them back)', async () => {
  const { x, E } = await boot3([-1.5, 52], null, SYN); tapFlash(x, 0); await settle();
  press(x, 'te:solar'); assert.deepEqual([...x.S.ly], ['solar']); assert.deepEqual(onIds(E), ['solar']); inSync(E);
  press(x, 'te:all'); assert.deepEqual([...x.S.ly].sort(), ['bess', 'solar', 'wind']);
  press(x, 'st:pl'); assert.deepEqual(onIds(E), [], 'no planning project: no layer'); assert.doesNotMatch(card(x).textContent, /REPD map layers on/);
  press(x, 'st:all'); closeCard(x); assert.deepEqual(onIds(E), []);
});
(M4B ? test.skip : test)('M3-5: a row tap keeps the layers (the project\'s own dot stays drawn), back keeps them, close from the project view switches them off', async () => {
  const { x, E } = await boot3([-1.5, 52], null, SYN); tapFlash(x, 0); await settle(); E.toggles.length = 0;
  assert.equal(tapRow(x, 1), true); await settle(); assert.equal(card(x).getAttribute('aria-label'), 'REPD project');
  assert.deepEqual(E.toggles, []); assert.ok(visible(x).includes('bess'), 'Battery row: its own layer is drawn');
  dispatch(card(x).querySelector('[data-lightning-back]'), 'click', x.log.errors); await settle();
  assert.equal(card(x).getAttribute('aria-label'), 'Lightning flash'); assert.deepEqual(E.toggles, []); assert.deepEqual([...x.S.ly].sort(), ['bess', 'solar', 'wind']);
  tapRow(x, 0); await settle(); closeCard(x); assert.deepEqual(onIds(E), []); assert.equal(x.S.ly.size, 0); inSync(E);
});
(M4B ? test.skip : test)('M3-6: lightning OFF, a period change, LATEST, prev and a tap on empty map each restore the user state; a tap on a drawn REPD dot keeps it', async () => {
  const run = async act => { 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']); await act(x); await drain(); return { x, E }; };
  for (const [nm, act] of [['off', x => x.toggle(false)], ['period', x => x.click(x.chip('7d'))], ['empty map', x => x.tapMap([50, 50], {})], ['prev', x => x.click(x.nav('prev'))], ['latest', x => x.click(x.nav('latest'))], ['custom apply', x => { x.click(x.chip('custom')); }]]) {
    const { x, E } = await run(act); assert.deepEqual(onIds(E), ['wind'], nm); assert.equal(x.S.ly.size, 0, nm); inSync(E); }
  { const { x, E } = await run(x => x.tapMap([50, 50], { 'l-solar': [{ properties: { name: 'S1', tech: 'solar' } }] })); assert.deepEqual([...x.S.ly], [], 'the engine owns this tap; M4 holds nothing after it (M2R-l3regress M3-L1)'); assert.equal(card(x), null);
    assert.deepEqual(onIds(E), ['solar', 'wind'], 'the tapped dot stays: Solar is now the reader\'s; Battery released'); inSync(E); x.toggle(false); assert.deepEqual(onIds(E), ['solar', 'wind']); }
});
(M4B ? test.skip : test)('M3-7: a layer M3 holds becomes the user\'s once the user unticks or re-ticks it (main panel or fullscreen curtain), and then survives close', async () => {
  const { x, E } = await boot3([-1.5, 52], null, SYN); tapFlash(x, 0); await settle();
  userTick(x, E, 'bess', false); userTick(x, E, 'bess', true); userTick(x, E, 'wind', false, 'fs');
  assert.deepEqual([...x.S.ly], ['solar']); closeCard(x); assert.deepEqual(onIds(E), ['bess']); inSync(E);
  tapFlash(x, 0); await settle(); assert.deepEqual([...x.S.ly].sort(), ['solar', 'wind']); closeCard(x); assert.deepEqual(onIds(E), ['bess']);
});
(M4B ? test.skip : test)('M3-8: nothing is switched with lightning OFF or before a tap; a disabled control and a technology with no layer are skipped; a register failure on a new tap releases the held layers', async () => {
  { const x = boot({ feedFn: () => feed([]) }); installRepd(x, S3, SYN); const E = installLayers(x); await drain(); assert.deepEqual(E.toggles, []); x.toggle(true); await drain(); x.toggle(false); await drain();
    assert.deepEqual(E.toggles, []); assert.ok(!(x.S.ly && x.S.ly.size), 'OFF before any tap switches nothing'); }
  { const { x, E } = await boot3([-1.5, 52], null, SYN, { disabled: ['bess'] }); tapFlash(x, 0); await settle(); assert.deepEqual([...x.S.ly].sort(), ['solar', 'wind']); assert.equal(E.main.bess.checked, false); }
  { let fail = false; const { x, E } = await boot3([-1.5, 52], null, null, { via: 'fetch', fetchImpl: async () => fail ? Promise.reject(new Error('network error')) : new Response(JSON.stringify(SYN), { status: 200 }) });
    tapFlash(x, 0); await settle(); assert.equal(x.S.ly.size, 3); x.S.rg = null; fail = true; tapFlash(x, 0); await settle();
    assert.match(card(x).textContent, /REPD projects unavailable: network error/); assert.equal(x.S.ly.size, 0); assert.deepEqual(onIds(E), []); }
});
(M4B ? test.skip : test)('M3-9 (real register, the owner\'s Doncaster-area cell 53.45, -1.05): the layers switched on equal the technologies of the independent brute-force 10 nearest sites, and close restores all off', async () => {
  const { x, E } = await boot3(DONC, null, REPD_IND); tapFlash(x, 0); await settle();
  const want = techsOf(bruteSites(REPD_IND, ...DONC)); assert.ok(want.length >= 2, want.join());
  assert.deepEqual(onIds(E).sort(), want); assert.deepEqual([...x.S.ly].sort(), want); inSync(E);
  for (const [k, keep] of [['te:solar', p => /^solar/.test(p.tech)], ['st:op', p => p.status === 'operational']]) {
    press(x, k); assert.deepEqual(onIds(E).sort(), techsOf(bruteSites(REPD_IND, ...DONC, k === 'te:solar' ? keep : (p => /^solar/.test(p.tech) && keep(p)))), k); }
  closeCard(x); assert.deepEqual(onIds(E), []); inSync(E); assert.equal(x.log.errors.length, 0);
});

// ---------------------------------------------------------------- M3-build: the M2 review fixes folded into M3 (each fails on M2)
El.prototype.focus = function () { this.ownerDocument.activeElement = this; };
const live = x => card(x).children.find(e => e.getAttribute && e.getAttribute('role') === 'status');
const later = () => new Promise(r => setTimeout(r, 150));
test('M3R-a11y (M2R-a11y MAJOR-1..3, MINOR-1): a polite status outside the <details> announces loading, the list and a failure; focus follows chip, row and back; back is named without the glyph', async () => {
  const x = await flashAt([-1.5, 52], FCx([pf(-1.5, 52.01, { name: 'A' }), pf(-1.5, 52.02, { name: 'B', tech: 'bess', raw_tech: 'Battery' })]));
  const lv = live(x); assert.ok(lv, 'status region'); assert.ok(!card(x).querySelector('details').contains(lv), 'outside the closed details'); await later();
  assert.match(lv.textContent, /^Screening · 2 nearest REPD sites within 40 km of this optical flash, straight line\. Proximity only, not impact; not evidence any project was struck\. Only 2 sites within the 40 km search radius\.$/);
  press(x, 'te:bess'); assert.equal(x.doc.activeElement, chip(x, 'te:bess'), 'focus stays on the pressed chip'); await later(); assert.match(lv.textContent, /^Screening · 1 nearest REPD site .*\(BESS\)/);
  press(x, 'te:all'); tapRow(x, 0); await settle(); const back = card(x).querySelector('[data-lightning-back]');
  assert.equal(x.doc.activeElement, back); assert.equal(back.getAttribute('aria-label'), 'back to lightning flash');
  dispatch(back, 'click', x.log.errors); await settle(); assert.equal(x.doc.activeElement, card(x).querySelector('summary'));
  const y = flash0(); installRepd(y, SUBS, null, 'fetch', async () => Promise.reject(new Error('network error'))); y.toggle(true); await drain(); tapFlash(y); await settle(); await later();
  assert.match(live(y).textContent, /^REPD projects unavailable: network error\. Tap the flash again to retry\.$/); assert.match(card(y).querySelector('summary').textContent, / · REPD unavailable$/);
});
test('M3R-bugs (M2R-bugs M2RB1, M2RB2): a Ctrl/Cmd/Shift click keeps the browser default (new tab); a map error while drawing the project lines is noted, not shown as a register failure, and the next render rebuilds them', async () => {
  const x = await flashAt([-1.5, 52], FCx([pf(-1.5, 52.01, { name: 'A' })]));
  for (const k of ['ctrlKey', 'metaKey', 'shiftKey']) { const a = prows(card(x))[0]; let prevented = false; for (const f of a.listeners.click) f({ type: 'click', [k]: true, button: 0, target: a, preventDefault: () => { prevented = true; } }); assert.equal(prevented, false, k); assert.equal(card(x).getAttribute('aria-label'), 'Lightning flash', k); }
  const y = flash0(); installRepd(y, SUBS, FCx([pf(-1.5, 52.01, { name: 'A' }), pf(-1.5, 52.02, { name: 'B', tech: 'bess', raw_tech: 'Battery' })]), 'fetch'); y.toggle(true); await drain();
  const add = y.map.addLayer; let boom = true; y.map.addLayer = l => { if (boom && /neon-p-node$/.test(l.id)) throw new Error('Style is not done loading'); return add(l); };
  tapFlash(y); await settle(); assert.doesNotMatch(card(y).textContent, /REPD projects unavailable|REPD unavailable/); // M5: a record block without a search runtime says so on its own assert.equal(prows(card(y)).length, 2); assert.ok(y.S.errors.some(e => /project lines: Style is not done loading/.test(e)));
  boom = false; press(y, 'te:bess'); assert.ok(y.layers.get('gridatlas-lightning-neon-p-node'), 'rebuilt'); assert.equal(y.sources.get('gridatlas-lightning-neon-pnodes').data.features.length, 1);
});
test('M3R-security (M2R-security SEC-M2-1/2, M2R-data D5): a malformed or string-coordinate row is skipped, never the whole register; the Scilly placeholder is dropped', async () => {
  const bad = [null, { type: 'Feature', geometry: { type: 'Point', coordinates: null }, properties: { tech: 'solar' } }, pf('-1.5', '52.02', { name: 'Str' }), pf(-7.55716, 49.766807, { name: 'Scilly' })];