GLOBALGRID2050 / EXPLORE CODE

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

Reconstruct and 4 more files

A JavaScript module in the lineage folder of GridAtlas that works with line diff (`lineDiff`) and line start (`lineStart`).

678 lines of JavaScript from gridatlas, in 5 files. Topic: Maps, GIS and field navigation. Section 634 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. Reconstruct storage · gridatlas / tools/lightning/lineage/reconstruct.mjs lines 1–257
  2. Renewable Energy Planning Database (REPD) M2 Part energy-data · gridatlas / tools/lightning/lineage/repd-m2.part.js lines 1–82
  3. Renewable Energy Planning Database (REPD) M3 Part energy-data · gridatlas / tools/lightning/lineage/repd-m3.part.js lines 1–100
  4. Verify Lineage ingest · gridatlas / tools/lightning/lineage/verify-lineage.mjs lines 1–37
  5. Make Generation energy-data · gridatlas / tools/lightning/make-generation.mjs lines 1–202

Reconstruct

A JavaScript module in the lineage folder of GridAtlas that works with line diff (`lineDiff`) and line start (`lineStart`).

storagegridatlas / tools/lightning/lineage/reconstruct.mjs · lines 1–257 of 257 · Not reached from any entry point (candidate for review) · pattern depth (shared by 2 files)

What it does
It loads data. Defines 20 functions or classes, including rd, norm, analyse, depth, inTpl. Uses libraries node:fs, node:os, node:path, acorn. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: command-line arguments.
What it achieves
It is built from the norm step (`norm`), the analyse step (`analyse`) and the depth step (`depth`). `reconstruct.mjs` (CD-source lane, 29 Oct 2026, one-off; kept as the provenance of `tools/lightning/src`): the committed M4 and M4b module bytes -> `tools/lightning/src/*.js` (readable layout, the comments of `annotations.mjs`, ///#if variant blocks from a token-level diff of the two modules).
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/lightning/lineage · JavaScript module
Uses
Annotations (import), node:fs, node:os, node:path, acorn
Used by
none found
Produces
rd, norm, analyse, depth, inTpl, lineDiff, off, segments, P, posA, ws, lineStart
Defines here
rd, norm, analyse, depth, inTpl, lineDiff, off, segments, P, posA, ws, lineStart, lineEnd, pieces, ind, render, place, at, find, firstDiff
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/lightning/lineage/reconstruct.mjs:1-257 · blob a1142e2e0a349d9980b85c186fe3e3be6fd7e540 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// reconstruct.mjs (CD-source lane, 29 Oct 2026, one-off; kept as the provenance of tools/lightning/src): the committed M4
// and M4b module bytes -> tools/lightning/src/*.js (readable layout, the comments of annotations.mjs, ///#if variant
// blocks from a token-level diff of the two modules), then proves build.mjs reproduces both modules byte for byte.
// It needs acorn 8.11.3 (npm i --no-save acorn@8.11.3 in a scratch directory; the repository installs nothing). It is
// NOT how the source is maintained now: edit tools/lightning/src directly (docs/LIGHTNING-SOURCE.md).
// usage: node reconstruct.mjs <repo-worktree> [--dry]
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as acorn from 'acorn';
import { FILES, NOTES } from './annotations.mjs';

const REPO = path.resolve(process.argv[2]);
const DRY = process.argv.includes('--dry');
const GA = '202610290045', GB = '202610290050', VA = 'layers', VB = 'dots';
const MAXW = 110;
const rd = g => fs.readFileSync(path.join(REPO, 'atlas/modules', `${g}-uk-lightning-overlay.js`), 'utf8');
const norm = (t, g) => { if (t.split(g).length !== 3) throw new Error('GEN count ' + g); return t.split(g).join('@@GEN@@'); };
const A = norm(rd(GA), GA), B = norm(rd(GB), GB);

/* ---------- token info per text: break candidates and depth ---------- */
function analyse(T) {
  const toks = [], comments = [];
  for (const t of acorn.tokenizer(T, { ecmaVersion: 2022, onComment: (b, x, s, e) => comments.push([s, e]) })) toks.push(t);
  const inTok = new Uint8Array(T.length + 1); // 1 = position strictly inside a token or comment
  for (const t of toks) for (let i = t.start + 1; i < t.end; i++) inTok[i] = 1;
  for (const [s, e] of comments) for (let i = s + 1; i < e; i++) inTok[i] = 1;
  const depthAt = new Int16Array(T.length + 1); // bracket depth (excluding templates) before position
  const brk = new Map(); // position -> {kind, depth}
  const stack = [];
  const match = new Map();
  { const st = []; toks.forEach((t, i) => { const l = t.type.label;
      if (l === '{' || l === '${') st.push(i); else if (l === '}') { const j = st.pop(); if (j !== undefined) match.set(j, i); } }); }
  let pos = 0;
  const depth = () => stack.filter(x => x !== '`' && x !== '${').length;
  const inTpl = () => stack.includes('`');
  toks.forEach((t, i) => {
    for (; pos <= t.start; pos++) depthAt[pos] = depth();
    const l = t.type.label;
    const next = toks[i + 1];
    if (l === '`') { if (stack[stack.length - 1] === '`') stack.pop(); else stack.push('`'); }
    else if (l === '${') stack.push('${');
    else if (l === '{' || l === '(' || l === '[') stack.push(l);
    else if (l === '}' || l === ')' || l === ']') stack.pop();
    for (; pos <= t.end; pos++) depthAt[pos] = depth();
    if (!next || next.start !== t.end || inTpl()) return;
    if (l === ';') brk.set(t.end, { kind: 'semi' });
    else if (l === ',') brk.set(t.end, { kind: 'comma' });
    else if (l === '{' && match.has(i) && toks[match.get(i)].start - t.end > 50) {
      brk.set(t.end, { kind: 'open' });
      const c = toks[match.get(i)];
      if (toks[match.get(i) - 1].end === c.start) brk.set(c.start, { kind: 'close' });
    }
  });
  for (; pos <= T.length; pos++) depthAt[pos] = depth();
  const bnd = new Uint8Array(T.length + 1); bnd[0] = bnd[T.length] = 1;
  for (const t of toks) bnd[t.start] = bnd[t.end] = 1;
  for (const [a, b] of comments) bnd[a] = bnd[b] = 1;
  for (let i = 0; i < T.length; i++) if (T[i] === '\n') bnd[i] = bnd[i + 1] = 1;
  return { T, inTok, depthAt, brk, bnd };
}
const IA = analyse(A), IB = analyse(B);

/* ---------- diff A/B into common and alternative segments ---------- */
function lineDiff(a, b) {
  const al = a.split('\n'), bl = b.split('\n'), n = al.length, m = bl.length;
  const L = Array.from({ length: n + 1 }, () => new Int32Array(m + 1));
  for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = al[i] === bl[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
  const ops = []; let i = 0, j = 0;
  while (i < n || j < m) {
    if (i < n && j < m && al[i] === bl[j]) { ops.push(['=', i, j]); i++; j++; }
    else if (j < m && (i === n || L[i][j + 1] >= L[i + 1][j])) { ops.push(['+', i, j]); j++; }
    else { ops.push(['-', i, j]); i++; }
  }
  return { al, bl, ops };
}
const off = ls => { const o = [0]; for (const l of ls) o.push(o[o.length - 1] + l.length + 1); return o; };
function segments() {
  const { al, bl, ops } = lineDiff(A, B), oa = off(al), ob = off(bl);
  const hunks = []; // [aStart, aEnd, bStart, bEnd] char ranges
  let k = 0;
  while (k < ops.length) {
    if (ops[k][0] === '=') { k++; continue; }
    const i0 = ops[k][1], j0 = ops[k][2]; let i1 = i0, j1 = j0;
    while (k < ops.length && ops[k][0] !== '=') { if (ops[k][0] === '-') i1 = ops[k][1] + 1; else j1 = ops[k][2] + 1; k++; }
    let as = oa[i0], ae = oa[i1], bs = ob[j0], be = ob[j1];
    // char-level trim
    while (as < ae && bs < be && A[as] === B[bs]) { as++; bs++; }
    while (ae > as && be > bs && A[ae - 1] === B[be - 1]) { ae--; be--; }
    // snap outwards to positions outside tokens/comments in both texts
    while (!(IA.bnd[as] && IB.bnd[bs])) { as--; bs--; }
    while (!(IA.bnd[ae] && IB.bnd[be])) { ae++; be++; }
    // token-level LCS inside the block
    const P = (I, s, e) => { const o = []; let q = s; for (let i = s + 1; i <= e; i++) if (I.bnd[i]) { o.push([q, i]); q = i; } return o; };
    const pa = P(IA, as, ae), pb = P(IB, bs, be), ta = pa.map(([x, y]) => A.slice(x, y)), tb = pb.map(([x, y]) => B.slice(x, y));
    const n = ta.length, m = tb.length, L = Array.from({ length: n + 1 }, () => new Int32Array(m + 1));
    for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = ta[i] === tb[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
    const runs = []; let i = 0, j = 0, cur = null, same = 0;
    const posA = i => i < n ? pa[i][0] : ae, posB = j => j < m ? pb[j][0] : be;
    while (i < n || j < m) {
      if (i < n && j < m && ta[i] === tb[j]) { if (cur) { same++; if (same > 8 || /\n/.test(ta[i])) { runs.push(cur); cur = null; } } i++; j++; continue; }
      if (!cur) cur = { as: posA(i), bs: posB(j) };
      else if (same) { /* short common gap: absorb */ }
      same = 0;
      if (j < m && (i === n || L[i][j + 1] >= L[i + 1][j])) j++; else i++;
      cur.ae = posA(i); cur.be = posB(j);
    }
    if (cur) runs.push(cur);
    // an unrelated rewrite (few shared tokens) stays one block
    if (L[0][0] < 0.5 * Math.min(n, m) && Math.min(n, m) > 20) runs.splice(0, runs.length, { as, ae, bs, be });
    for (const r of runs) {
      let { as, ae, bs, be } = r;
      // trim the absorbed common tail back off
      while (ae > as && be > bs && A[ae - 1] === B[be - 1]) { ae--; be--; }
      while (!(IA.bnd[ae] && IB.bnd[be])) { ae++; be++; }
      const ws = c => c === ' ';
      while (as > 0 && A[as - 1] !== '\n' && (ws(A[as]) || ws(B[bs]))) { as--; bs--; while (!(IA.bnd[as] && IB.bnd[bs])) { as--; bs--; } }
      while (ae < A.length && ws(A[ae])) { ae++; be++; }
      // widen to whole statements or list items when they are near (inside common text, so A and B move together)
      { const ls = lineStart(A, as); let k = as; const pun = q => /[;,{}(]/.test(A[q - 1]) && IA.bnd[q] && IA.bnd[q - 1] && !IA.inTok[q - 1];
        while (k > ls && as - k <= 40 && !pun(k)) k--;
        if (k === ls || pun(k)) { if (as - k <= 40) { bs -= as - k; as = k; } } }
      { const le = lineEnd(A, ae); let k = ae; const pe = q => /[;,]/.test(A[q]) && IA.bnd[q] && IA.bnd[q + 1] && !IA.inTok[q];
        while (k < le && k - ae <= 40 && !pe(k)) k++;
        if (k < le && k - ae <= 40) { be += k + 1 - ae; ae = k + 1; } else if (k === le && k - ae <= 40) { be += k - ae; ae = k; } }
      if (/^ *$/.test(A.slice(lineStart(A, as), as)) && /^ *$/.test(B.slice(lineStart(B, bs), bs))) { const d = as - lineStart(A, as); if (bs - lineStart(B, bs) === d) { as -= d; bs -= d; } }
      hunks.push([as, ae, bs, be]);
    }
  }
  // merge overlapping / touching hunks
  const H = [];
  for (const h of hunks) { const p = H[H.length - 1]; if (p && h[0] <= p[1]) { p[1] = Math.max(p[1], h[1]); p[3] = Math.max(p[3], h[3]); } else H.push([...h]); }
  const segs = []; let pa = 0, pb = 0;
  for (const [as, ae, bs, be] of H) {
    if (A.slice(pa, as) !== B.slice(pb, bs)) throw new Error('common mismatch');
    if (as > pa) segs.push({ t: 'c', a: pa, b: pb, len: as - pa });
    segs.push({ t: 'x', as, ae, bs, be });
    pa = ae; pb = be;
  }
  if (A.slice(pa) !== B.slice(pb)) throw new Error('tail mismatch');
  segs.push({ t: 'c', a: pa, b: pb, len: A.length - pa });
  return segs;
}

/* ---------- render ---------- */
const lineStart = (T, p) => T.lastIndexOf('\n', p - 1) + 1;
const lineEnd = (T, p) => { const e = T.indexOf('\n', p); return e < 0 ? T.length : e; };
// physical units: {text, cont, s, e, o ('A'|'B'), s2 (B pos for common)}
function pieces(I, s, e, extra) {
  const T = I.T, out = [];
  let p = s;
  while (p < e) {
    const le = Math.min(lineEnd(T, p), e), ls = lineStart(T, p), full = lineEnd(T, p) - ls;
    const atStart = p === ls;
    const lead = (T.slice(ls).match(/^ */) || [''])[0].length;
    const ind = q => ' '.repeat(Math.max(lead + 2, 2 + 2 * Math.max(0, I.depthAt[q] - 2)));
    const cuts = [];
    if (full > MAXW) {
      for (let q = p + 1; q < le; q++) {
        const b = I.brk.get(q); if (!b) continue;
        if (b.kind === 'comma' && I.depthAt[q] !== 2) continue;
        cuts.push(q);
      }
    }
    // second pass: still-long chunks get commas one level deeper
    const bounds = [p, ...cuts, le];
    const fin = [];
    for (let k = 0; k + 1 < bounds.length; k++) {
      const a = bounds[k], b = bounds[k + 1];
      fin.push(a);
      if (b - a > MAXW + 40) {
        const d0 = I.depthAt[a];
        for (let q = a + 1; q < b - 30; q++) { const x = I.brk.get(q); if (x && x.kind === 'comma' && I.depthAt[q] === d0 + 1 && q - fin[fin.length - 1] > 60) fin.push(q); }
      }
    }
    fin.push(le);
    for (let k = 0; k + 1 < fin.length; k++) {
      const a = fin[k], b = fin[k + 1];
      if (a === b) continue;
      const first = a === p;
      const close = I.brk.get(a) && I.brk.get(a).kind === 'close';
      let text = T.slice(a, b);
      if (!(first && atStart)) text = (close ? ind(a).slice(2) : ind(a)) + text;
      const last = k + 2 === fin.length;
      out.push({ text, cont: !(last && le < e) && !(last && le === e && (T[e] === '\n')), s: a, e: b, o: I === IA ? 'A' : 'B', ...extra(a) });
    }
    if (le < e) p = le + 1; else p = e;
  }
  // a piece that ends exactly at a newline inside [s,e) was handled by cont=false; one ending at e mid-line continues
  return out;
}
function render() {
  const segs = segments(), units = [];
  for (const g of segs) {
    if (g.t === 'c') units.push(...pieces(IA, g.a, g.a + g.len, a => ({ sb: a - g.a + g.b })));
    else {
      units.push({ dir: `///#if ${VB}` });
      units.push(...pieces(IB, g.bs, g.be, () => ({})));
      units.push({ dir: '///#else' });
      units.push(...pieces(IA, g.as, g.ae, () => ({})));
      units.push({ dir: '///#endif' });
    }
  }
  // fix cont: a unit continues when its text does not end at a real newline of its origin
  for (const u of units) if (!u.dir) { const T = u.o === 'A' ? A : B; u.cont = T[u.e] !== '\n';
    if (u.cont && !u.text.trim()) throw new Error('blank continued unit at ' + u.o + u.s);
    if (/^\s*\/\/\//.test(u.text)) throw new Error('unit starts with /// at ' + u.o + u.s); }
  return units;
}

/* ---------- annotations and files ---------- */
function place(units) {
  const at = (u, o, p) => !u.dir && (u.o === o ? p >= u.s && p < u.e : (o === 'B' && u.sb !== undefined && p >= u.sb && p < u.sb + (u.e - u.s)));
  const find = (needle, where) => {
    const o = where || (A.split(needle).length === 2 ? 'A' : 'B'), T = o === 'A' ? A : B;
    if (T.split(needle).length !== 2) throw new Error(`anchor not unique in ${o}: ${needle.slice(0, 60)} (${T.split(needle).length - 1})`);
    const p = T.indexOf(needle);
    const i = units.findIndex(u => at(u, o, p));
    if (i < 0) throw new Error('anchor unit not found ' + needle.slice(0, 50));
    return i;
  };
  const pre = new Map(); // unit index -> comment lines
  for (const n of NOTES) {
    const i = find(n.at, n.in);
    const lead = units[i].text.match(/^ */)[0];
    const lines = n.text.trim().split('\n').map(l => lead + '/// ' + l.trim()).map(l => l.trimEnd());
    pre.set(i, [...(pre.get(i) || []), ...lines]);
  }
  const fileAt = new Map();
  for (const f of FILES) {
    let i = f.at === null ? 0 : find(f.at, f.in || 'A');
    if (i && units[i - 1].dir && units[i - 1].dir.startsWith('///#if')) i--;
    if (i && units[i - 1].cont) throw new Error('file split inside a continued line: ' + f.name);
    fileAt.set(i, f);
  }
  const files = []; let cur = null;
  units.forEach((u, i) => {
    if (fileAt.has(i)) { const f = fileAt.get(i); cur = { name: f.name, lines: f.head.trim().split('\n').map(l => ('/// ' + l.trim()).trimEnd()) }; cur.lines.push('///'); files.push(cur); }
    for (const l of pre.get(i) || []) cur.lines.push(l);
    cur.lines.push(u.dir || (u.text + (u.cont ? '///' : '')));
  });
  return files;
}

const units = render();
const files = place(units);
const outDir = DRY ? fs.mkdtempSync(path.join(os.tmpdir(), 'lightning-src-')) : path.join(REPO, 'tools/lightning/src');
for (const n of fs.readdirSync(outDir)) if (n.endsWith('.js')) fs.unlinkSync(path.join(outDir, n));
for (const f of files) fs.writeFileSync(path.join(outDir, f.name), f.lines.join('\n') + '\n');
const { assemble } = await import(path.join(REPO, 'tools/lightning/build.mjs'));
const ga = assemble({ variant: VA, gen: GA, variants: [VA, VB], srcDir: outDir }), gb = assemble({ variant: VB, gen: GB, variants: [VA, VB], srcDir: outDir });
const okA = ga === rd(GA), okB = gb === rd(GB);
const firstDiff = (x, y) => { let i = 0; while (i < x.length && x[i] === y[i]) i++; return i; };
console.log(JSON.stringify({ outDir, files: files.map(f => [f.name, f.lines.length]), okA, okB,
  diffA: okA ? null : [firstDiff(ga, rd(GA)), JSON.stringify(ga.slice(firstDiff(ga, rd(GA)) - 40, firstDiff(ga, rd(GA)) + 40)), JSON.stringify(rd(GA).slice(firstDiff(ga, rd(GA)) - 40, firstDiff(ga, rd(GA)) + 40))],
  diffB: okB ? null : [firstDiff(gb, rd(GB)), JSON.stringify(gb.slice(firstDiff(gb, rd(GB)) - 40, firstDiff(gb, rd(GB)) + 40)), JSON.stringify(rd(GB).slice(firstDiff(gb, rd(GB)) - 40, firstDiff(gb, rd(GB)) + 40))] }));
if (!okA || !okB) process.exit(1);

Renewable Energy Planning Database (REPD) M2 Part

A JavaScript file in the lineage folder of GridAtlas that maps REPD master, the REPD register, solar and wind.

energy-datagridatlas / tools/lightning/lineage/repd-m2.part.js · lines 1–82 of 82 · Not reached from any entry point (candidate for review)

What it does
It maps REPD master, the REPD register, solar and wind.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar, wind.
Inputs & outputs
In: JSON file repd_master.json; DuckDB queries.
Downstream impact
Used directly by 1 file: Build M2 (gridatlas).
What it achieves
REPD projects near a tap (M2) ---------------------------------------------------------------------------------- The register the map already holds (the engine's src-REPD data when a REPD layer has loaded it, else the engine URL `/dist/repd_master.json` through the untouched bridge). Its code works with 0 MW. It responds to click events.
Why it matters
Imported by Build M2.
Application
gridatlas · tools/lightning/lineage · script
Uses
none found
Used by
referenced by Build M2 (new URL import.meta.url)
Produces
none declared
Defines here
none
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/lightning/lineage/repd-m2.part.js:1-82 · blob 8935c5e191b218620e185b6b4d0a30f4cb92f363 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* ---- REPD projects near a tap (M2) ----------------------------------------------------------------------------------
   The register the map already holds (the engine's src-repd data when a REPD layer has loaded it, else the engine URL
   /dist/repd_master.json through the untouched bridge), measured by straight-line distance from the flash or the cell
   centre with the original link.measure.distanceKm. Nearest by distance only: never a claim that a project was struck
   or affected. */
RG=(m,M)=>S.rg||(S.rg=(async()=>{
  let f;try{f=m.getSource('src-repd').serialize().data.features}catch(_){}
  // gj: the module's fetch helper (15 s timeout that also covers the body, redirect refusal, "HTTP n")
  if(!(f&&f.length))f=(await gj('/dist/repd_master.json')).features;
  let o=f.map(x=>[M.representativePoint(x.geometry),x.properties||{}]).filter(([a,p])=>a&&M.isProjectTech(p.tech));
  return o.length?o:E('register empty')})().catch(e=>{S.rg=null;throw e})),
// filter chips: status classes (operational | under or awaiting construction | application submitted) and technology
RpF={st:[['all','All'],['op','Operational'],['cc','Consented & construction'],['pl','Planning']],
  te:[['all','All'],['solar','Solar'],['wind','Wind'],['bess','BESS'],['other','Other']]},
RpS=s=>{s=String(s||'').toLowerCase();return s==='operational'?'op':/construction/.test(s)?'cc':/application|submitted|planning/.test(s)?'pl':'?'},
RpT=t=>/^solar/.test(t)?'solar':/^wind/.test(t)?'wind':/^bess/.test(t)?'bess':'other',
RpN=p=>({solar:'Solar',solar_roof:'Rooftop solar'})[p.tech]||cs(p.raw_tech),
RpW=ps=>ps.reduce((s,p)=>s+(p.capacity>0?+p.capacity:0),0),
RpMW=v=>v>0?` ${N(v)} MW`:'',
RpU=(ps,f)=>[...new Set(ps.map(f))],
// one label per site: co-located parts (e.g. solar + battery at one point) share one link, one node and one label
RpG=g=>`${g.km.toFixed(2)} km · ${RpU(g.parts,RpN).sort().join(' + ')}${RpMW(RpW(g.parts))}`,
Rp=(m,c,x,y,M)=>{
  let pd=ap(c.out,el('div','','REPD projects: loading…')),box=ap(c.out,el('div'));
  RG(m,M).then(G=>{
    if(S.pp!==c||!c.out.contains(pd))return;
    // every register row is measured once; exact duplicate rows (same point, same properties) count once
    let all=[],seen=new Set;
    for(let[a,p]of G){let km=M.distanceKm(x,y,...a);if(km<=40){let k=a+JSON.stringify(p);if(!seen.has(k)){seen.add(k);all.push({a,p,km})}}}
    c.rpAll=all;c.fk0=S.fk.slice();c.smb=c.sm.textContent;RpR(m,c,pd,box)
  }).catch(e=>{
    if(S.pp!==c)return;S.rgf=(S.rgf||0)+1;
    // the bridge keeps a failed DuckDB/manifest start for the page lifetime, so a retry can fail at once: say so
    pd.textContent=`REPD projects unavailable: ${msg(e)}. Tap again to retry`+(S.rgf>1?"; if it keeps failing, switch on a REPD layer or reload the page (the map's REPD loader keeps a failed start until the page is reloaded).":'.')})},
RpR=(m,c,pd,box)=>{
  let f=S.rf||(S.rf={st:'all',te:'all'}),o=c.fk0[0],
    sel=c.rpAll.filter(r=>(f.st==='all'||RpS(r.p.status)===f.st)&&(f.te==='all'||RpT(r.p.tech)===f.te)),groups=new Map;
  for(let r of sel){let k=r.a.join(),g=groups.get(k);if(!g)groups.set(k,g={a:r.a,km:r.km,parts:[]});g.parts.push(r.p)}
  // the nearest 10 sites within the filter, plus any site at exactly the 10th site's distance
  let P=[...groups.values()].sort((a,b)=>a.km-b.km).filter((g,i,a)=>i<10||g.km==a[9].km),parts=P.reduce((s,g)=>s+g.parts.length,0),
    nm=v=>(RpF.st.find(q=>q[0]===v)||RpF.te.find(q=>q[0]===v))[1],all=f.st==='all'&&f.te==='all',
    ft=all?'all technologies and statuses':'filter: '+[f.st,f.te].filter(v=>v!=='all').map(nm).join(' · '),
    n10=sel.filter(r=>r.km<=10),nc10=n10.filter(r=>!(r.p.capacity>0)).length;
  pd.textContent=`${P.length?(parts>P.length?`${pl(P.length,'nearest REPD site')} (${N(parts)} projects; co-located parts grouped)`:pl(P.length,'nearest REPD project')):'No REPD project'} within 40 km of this ${c.wh} (straight-line; ${ft}). Not evidence any project was struck or affected.`;
  box.textContent='';
  ap(box,el('div','margin-top:4px;color:#ffc48a',`${pl(n10.length,'REPD project')} within 10 km · ${N(sel.length)} within 40 km · total${RpMW(RpW(n10.map(r=>r.p)))||' 0 MW'} within 10 km`
    +`${nc10?` (${N(nc10)} without a stated capacity not counted)`:''}; registered capacity, straight-line distance only, not a measure of impact`));
  if(P.length&&P.length<10)ap(box,el('div','',`Only ${pl(P.length,'site')} within 40 km${all?'':' for this filter'}; the radius stays 40 km, so fewer than 10 are listed.`));
  for(let[k,defs,lb]of[['st',RpF.st,'Status'],['te',RpF.te,'Tech']]){
    let row=ap(box,el('div','display:flex;flex-wrap:wrap;align-items:center;gap:4px;margin:6px 0 2px'));row.setAttribute('role','group');row.setAttribute('aria-label','REPD '+lb.toLowerCase()+' filter');
    ap(row,el('span','color:#8b9aa1;font-size:10px;min-width:40px',lb));
    for(let[v,t]of defs){let on=f[k]===v,b=ap(row,el('button',`min-height:44px;padding:0 10px;background:${on?'#2f6f75':'#050a0d'};border:1px solid #2f6f75;border-radius:3px;color:${on?'#e8f4f5':'#5fbdc2'};font:11px/1 monospace;cursor:pointer`,t));
      b.type='button';b.dataset.lightningRepdFilter=k+':'+v;b.setAttribute('aria-pressed',on);b.addEventListener('click',()=>{if(f[k]!==v&&S.pp===c){f[k]=v;RpR(m,c,pd,box)}})}}
  for(let g of P){
    let p=g.parts[0],one=g.parts.length===1,st=RpU(g.parts,q=>cs(q.status)).join(' / '),nm2=RpU(g.parts,q=>cs(q.name)).join(' / '),
      b=ap(box,el('a','display:block;padding:14px 0 13px;border-top:1px solid #1d3238;color:#ffb27a',`${RpG(g)} · ${one?'':g.parts.length+' co-located · '}${st} · ${nm2}`));
    // the href keeps the original coordinate deep link (open in a new tab); a plain tap stays in this page
    b.href=location.pathname+'?'+new URLSearchParams({longitude:g.a[0],latitude:g.a[1],technology:p.tech,project:p.name,capacity_mw:p.capacity,status:p.status});
    b.addEventListener('click',e=>{if(e.preventDefault)e.preventDefault();RpV(m,c,g)});
    if(!one)for(let q of g.parts)ap(box,el('div','padding:0 0 8px 12px;color:#c9a27e;font-size:10px',`${RpN(q)}${RpMW(+q.capacity)} · ${cs(q.status)} · ${cs(q.name)}`))}
  c.sm.textContent=c.smb+(P.length?` · ${P.length} nearest projects`:'');
  let C=['interpolate',['linear'],['get','mw'],0,'#ffaa00',50,'#ff4400',200,'#f00'],Z=(a,b)=>['interpolate',['linear'],['zoom'],6,a,12,b],
    F=geo=>FC(P.map(g=>({type:'Feature',properties:{mw:RpW(g.parts),label:RpG(g)},geometry:geo(g)}))),
    A=(i,type,source,paint,layout)=>m.addLayer(Object.assign({id:NI[i],type,source,paint},layout?{layout}:{})),
    ln=F(g=>({type:'LineString',coordinates:[o,g.a]})),nd=F(g=>({type:'Point',coordinates:g.a}));
  if(m.getSource(NSR[3])&&m.getSource(NSR[4])){m.getSource(NSR[3]).setData(ln);m.getSource(NSR[4]).setData(nd)}
  else{m.addSource(NSR[3],{type:'geojson',data:ln});m.addSource(NSR[4],{type:'geojson',data:nd});
    A(9,'line',NSR[3],{'line-color':C,'line-width':Z(1,2),'line-opacity':.8,'line-dasharray':[2,2]});A(10,'circle',NSR[4],{'circle-radius':Z(3,5),'circle-color':C,'circle-stroke-width':1});
    try{A(11,'symbol',NSR[4],{'text-color':'#ffc48a','text-halo-color':'#000c10','text-halo-width':1.5},{'text-field':['get','label'],'text-size':10,'text-offset':[0,1],'text-anchor':'top','text-font':sf(m)})}catch(e){note('neon labels: '+msg(e))}}
  // frame origin, substations and the listed sites; a register that lands mid-move is framed when that move ends
  cpos();S.fk=[...c.fk0,...P.map(g=>g.a)];m.isMoving&&m.isMoving()?m.once('moveend',ck):ck()},
// a row tap stays in this page: fly to the site and draw the original engine's nearest-substation links from it
// (link.measure.nearestSubstations, as for a flash); "◀ back" restores the lightning card as at its tap (collapsed, so the
// camera can frame it), its links and the filter. Both cards arrive collapsed so the neon links stay visible.
RpV=(m,c,g)=>{
  let back=c.re,src=c.wh==='cell centre'?'cell':'flash',[x,y]=g.a,ps=g.parts;
  pc();
  cd(m,x,y,'REPD project',`REPD · ${RpU(ps,RpN).sort().join(' + ')}${RpMW(RpW(ps))}`,
    ps.length>1?`${ps.length} co-located projects · ${RpU(ps,q=>cs(q.name)).join(' / ')}`:`${cs(ps[0].name)} · ${cs(ps[0].status)}`,
    ps.map(q=>`${RpN(q)}${RpMW(+q.capacity)} · ${cs(q.status)} · ${cs(q.name)}`).join('; ')+` · lat ${y.toFixed(3)}, lon ${x.toFixed(3)} · ${g.km.toFixed(2)} km from the lightning ${src} (straight-line)`,
    'project',{np:1,foot:'REPD register as the map holds it · nearest substations by straight-line distance, not the declared grid connection · not evidence the project was struck or affected.',
      back:['◀ back to lightning '+src,()=>{pc();back()}]})},

Renewable Energy Planning Database (REPD) M3 Part

A JavaScript file in the lineage folder of GridAtlas that maps REPD master, the REPD register, solar and wind.

energy-datagridatlas / tools/lightning/lineage/repd-m3.part.js · lines 1–100 of 100 · Not reached from any entry point (candidate for review)

What it does
It maps REPD master, the REPD register, solar and wind. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar, wind.
Inputs & outputs
In: JSON file repd_master.json; DuckDB queries.
Downstream impact
Used directly by 1 file: Build M3 (gridatlas).
What it achieves
REPD projects near a tap (M2, M3) -------------------------------------------------------------------------------- The register the map already holds (the engine's src-REPD data when a REPD layer has loaded it, else the engine URL `/dist/repd_master.json` through the untouched bridge). Its code works with 0 MW. It responds to click events.
Why it matters
Imported by Build M3.
Application
gridatlas · tools/lightning/lineage · script
Uses
none found
Used by
referenced by Build M3 (new URL import.meta.url)
Produces
none declared
Defines here
none
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/lightning/lineage/repd-m3.part.js:1-100 · blob 198269875dcf5ee294ea56e02bf89532df251dbe · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* ---- REPD projects near a tap (M2, M3) --------------------------------------------------------------------------------
   The register the map already holds (the engine's src-repd data when a REPD layer has loaded it, else the engine URL
   /dist/repd_master.json through the untouched bridge): REPD, DESNZ, April 2026 (Q1) extract, OGL v3.0. Measured by
   straight-line distance from the flash or the cell centre with the original link.measure.distanceKm. Nearest by distance
   only: never a claim that a project was struck or affected. */
RG=(m,M)=>S.rg||(S.rg=(async()=>{
  let f;try{f=m.getSource('src-repd').serialize().data.features}catch(_){}
  // gj: the module's fetch helper (15 s timeout that also covers the body, redirect refusal, "HTTP n")
  if(!(f&&f.length))f=(await gj('/dist/repd_master.json')).features;
  // a malformed row is skipped, never the whole register; numeric coordinates only; the search registry's Scilly
  // placeholder point is dropped should a register ever carry it (0 rows today)
  let o=f.map(x=>{try{let a=M.representativePoint(x.geometry);if(a[0]===+a[0]&&a[1]===+a[1]&&!(a[0]==-7.55716&&a[1]==49.766807))return[a,x.properties||{}]}catch(_){}return[]}).filter(([a,p])=>a&&M.isProjectTech(p.tech));
  return o.length?o:E('register empty')})().catch(e=>{S.rg=null;throw e})),
// filter chips: status classes (operational | under or awaiting construction | application submitted) and technology
RpF={st:[['all','All'],['op','Operational'],['cc','Consented'],['pl','Planning']],
  te:[['all','All'],['solar','Solar'],['wind','Wind'],['bess','BESS'],['other','Other']]},
// an explicit table: a status the pinned register does not carry (refused, withdrawn, decommissioned…) is in no class
RpS=s=>({operational:'op','under construction':'cc','awaiting construction':'cc','application submitted':'pl'})[String(s||'').toLowerCase()]||'?',
RpT=t=>/^solar/.test(t)?'solar':/^wind/.test(t)?'wind':/^bess/.test(t)?'bess':'other',
RpN=p=>({solar:'Solar',solar_roof:'Rooftop solar'})[p.tech]||cs(p.raw_tech),
// stated capacity of the parts at one point; repeated records of one scheme (same name, technology and capacity; only
// status or operator differ) count once. A capacity of 0 means "not stated".
RpW=ps=>RpU(ps,p=>p.name+'|'+p.raw_tech+'|'+(p.capacity>0?+p.capacity:0)).reduce((s,k)=>s+ +k.split('|').pop(),0),
RpMW=v=>v>0?` ${N(v)} MW`:'',
RpC=ps=>RpW(ps)>0?'':' · capacity not stated',
RpU=(ps,f)=>[...new Set(ps.map(f))],
// one label per site: projects at one point (e.g. solar + battery) share one link, one node and one label
RpG=g=>`${g.km.toFixed(2)} km · ${RpU(g.parts,RpN).sort().join(' + ')}${RpMW(RpW(g.parts))}`,
// the card's polite status region (outside the closed <details>): one 99 ms delay keeps the messages in order
Ra=(c,s)=>setTimeout(()=>{if(c.lv)c.lv.textContent=s},99),
Rp=(m,c,x,y,M)=>{
  let pd=ap(c.out,el('div','','REPD projects: loading…')),box=ap(c.out,el('div'));Ra(c,pd.textContent);
  RG(m,M).then(G=>{
    if(S.pp!==c||!c.out.contains(pd))return;
    // every register row is measured once; exact duplicate rows (same point, same properties) count once
    let all=[],seen=new Set;
    for(let[a,p]of G){let km=M.distanceKm(x,y,...a);if(km<=40){let k=a+JSON.stringify(p);if(!seen.has(k)){seen.add(k);all.push({a,p,km})}}}
    c.rpAll=all;c.fk0=S.fk.slice();c.smb=c.sm.textContent;RpR(m,c,pd,box)
  }).catch(e=>{
    if(S.pp!==c)return;Ry();S.rgf=(S.rgf||0)+1;
    // the bridge keeps a failed DuckDB/manifest start for the page lifetime, so a retry can fail at once: say so
    pd.textContent=`REPD projects unavailable: ${msg(e)}. `+(S.rgf>1?'Switch on a REPD layer or reload the page, then tap again.':`Tap the ${c.wh=='cell centre'?'cell':'flash'} again to retry.`);
    c.sm.textContent+=' · REPD unavailable';Ra(c,pd.textContent)})},
RpR=(m,c,pd,box)=>{
  let f=S.rf||(S.rf={st:'all',te:'all'}),o=c.fk0[0],
    sel=c.rpAll.filter(r=>(f.st==='all'||RpS(r.p.status)===f.st)&&(f.te==='all'||RpT(r.p.tech)===f.te)),groups=new Map;
  // one site per registered point: a row within about 10 m (2e-4° lon, 1e-4° lat) of a nearer row joins its site
  for(let r of[...sel].sort((a,b)=>a.km-b.km)){let g=[...groups.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)groups.set(r.a.join(),g={a:r.a,km:r.km,parts:[]});g.parts.push(r.p)}
  // the nearest 10 sites within the filter, plus any site at exactly the 10th site's distance
  let P=[...groups.values()].sort((a,b)=>a.km-b.km).filter((g,i,a)=>i<10||g.km==a[9].km),parts=P.reduce((s,g)=>s+g.parts.length,0),
    nm=v=>(RpF.st.find(q=>q[0]===v)||RpF.te.find(q=>q[0]===v))[1],all=f.st==='all'&&f.te==='all',
    fa=all?'all statuses':[f.st,f.te].filter(v=>v!=='all').map(nm).join(' · '),
    n10=sel.filter(r=>r.km<=10),nc10=n10.filter(r=>!(r.p.capacity>0)).length,W=[...groups.values()].reduce((s,g)=>s+(g.km<=10?RpW(g.parts):0),0);
  pd.textContent=`${P.length?pl(P.length,'nearest REPD site')+(parts>P.length?` (${N(parts)} projects; those at one point grouped)`:''):'No REPD site'} within 40 km of this ${c.wh}, straight-line${all?'':` (${fa})`}. Not evidence any project was struck.`;
  box.textContent='';
  // unknown is not zero: a project without a stated capacity is never summed as 0 MW
  if(sel.length)ap(box,el('div','margin-top:4px;color:#ffc48a',`Within 10 km: ${pl(n10.length,'project')}${n10.length?' · '+(W>0?`${N(W)} MW stated (${fa})`+(nc10?`, ${N(nc10)} not stated`:''):'capacity not stated'):''} · within 40 km: ${pl(sel.length,'project')} · straight-line distance only, not impact · REPD: DESNZ, April 2026, OGL v3.0`));
  let ol=P.length&&P.length<10?ap(box,el('div','',`Only ${pl(P.length,'site')} within the 40 km search radius${all?'':' for this filter'}.`)).textContent:'';
  for(let[k,defs,lb]of[['st',RpF.st,'Status'],['te',RpF.te,'Tech']]){
    let row=ap(box,el('div','display:flex;flex-wrap:wrap;align-items:center;gap:4px;margin:6px 0 2px'));row.setAttribute('role','group');row.setAttribute('aria-label','REPD '+lb.toLowerCase()+' filter');
    ap(row,el('span','color:#8b9aa1;font-size:11px;min-width:40px',lb));
    for(let[v,t]of defs){let on=f[k]===v,b=ap(row,el('button',`min-height:44px;padding:0 10px;background:${on?'#2f6f75':'#050a0d'};border:1px solid #2f6f75;border-radius:3px;color:${on?'#e8f4f5':'#5fbdc2'};font:11px/1 monospace;cursor:pointer`,t));
      // a press re-renders the chips: focus returns to the chip just pressed
      b.type='button';b.dataset.lightningRepdFilter=k+':'+v;b.setAttribute('aria-pressed',on);b.addEventListener('click',()=>{if(f[k]!==v&&S.pp===c){f[k]=v;RpR(m,c,pd,box);box.querySelector(`[data-lightning-repd-filter="${k}:${v}"]`)?.focus?.()}})}}
  for(let g of P){
    let p=g.parts[0],one=g.parts.length===1,
      b=ap(box,el('a','display:block;padding:14px 0 13px;border-top:1px solid #1d3238;color:#ffb27a',`${RpG(g)}${RpC(g.parts)} · ${one?cs(p.status)+' · '+cs(p.name):g.parts.length+' projects at this point:'}`));
    // the href keeps the original coordinate deep link (open in a new tab); a plain tap stays in this page
    b.href=location.pathname+'?'+new URLSearchParams({longitude:g.a[0],latitude:g.a[1],technology:p.tech,project:p.name,capacity_mw:p.capacity,status:p.status});
    b.addEventListener('click',e=>{if(e.ctrlKey||e.metaKey||e.shiftKey||e.button)return;if(e.preventDefault)e.preventDefault();RpV(m,c,g)});
    if(!one)for(let q of g.parts)ap(box,el('div','padding:0 0 8px 12px;color:#c9a27e;font-size:11px',`${RpN(q)}${RpMW(+q.capacity)}${RpC([q])} · ${cs(q.status)} · ${cs(q.name)}`))}
  c.sm.textContent=c.smb+' · '+(P.length?pl(P.length,'nearest REPD site'):'no REPD site within 40 km')+(all?'':` (${fa})`);Ra(c,pd.textContent+' '+ol);
  // M3: the original REPD layers of the listed technologies (within the filter) are on while this list is shown
  let lt=RpU(P.flatMap(g=>g.parts),q=>q.tech).filter(t=>RL.includes(t)),h=Q('scada-ui-container');Ry(lt);lt=lt.filter(t=>{let b=h&&h.querySelector(`input[data-layer-id="${t}"]`);return b&&b.checked});
  if(lt.length)ap(box,el('div','margin-top:6px;color:#8b9aa1;font-size:11px',`REPD map layers on for this list: ${lt.map(t=>{let q=Q('lbl-'+t);return q&&q.getAttribute('data-base-label')||t}).join(', ')}${S.ly.size?' (those switched on here go off when this card closes)':''}`));
  let C=['interpolate',['linear'],['get','mw'],0,'#ffaa00',50,'#ff4400',200,'#f00'],Z=(a,b)=>['interpolate',['linear'],['zoom'],6,a,12,b],
    F=geo=>FC(P.map(g=>({type:'Feature',properties:{mw:RpW(g.parts),label:RpG(g)},geometry:geo(g)}))),
    A=(i,type,source,paint,layout)=>m.addLayer(Object.assign({id:NI[i],type,source,paint},layout?{layout}:{})),
    ln=F(g=>({type:'LineString',coordinates:[o,g.a]})),nd=F(g=>({type:'Point',coordinates:g.a}));
  // a map error while drawing is noted (not shown as a register failure); a half-built set is rebuilt on the next render
  try{if(m.getLayer(NI[10])){m.getSource(NSR[3]).setData(ln);m.getSource(NSR[4]).setData(nd)}
  else{for(let l of NI.slice(9))m.getLayer(l)&&m.removeLayer(l);for(let q of NSR.slice(3))m.getSource(q)&&m.removeSource(q);
    m.addSource(NSR[3],{type:'geojson',data:ln});m.addSource(NSR[4],{type:'geojson',data:nd});
    A(9,'line',NSR[3],{'line-color':C,'line-width':Z(1,2),'line-opacity':.8,'line-dasharray':[2,2]});A(10,'circle',NSR[4],{'circle-radius':Z(3,5),'circle-color':C,'circle-stroke-width':1});
    try{A(11,'symbol',NSR[4],{'text-color':'#ffc48a','text-halo-color':'#000c10','text-halo-width':1.5},{'text-field':['get','label'],'text-size':10,'text-offset':[0,1],'text-anchor':'top','text-font':sf(m)})}catch(e){note('neon labels: '+msg(e))}}}catch(e){note('project lines: '+msg(e))}
  // frame origin, substations and the listed sites; a register that lands mid-move is framed when that move ends
  cpos();S.fk=[...c.fk0,...P.map(g=>g.a)];m.isMoving&&m.isMoving()?m.once('moveend',ck):ck()},
// a row tap stays in this page: fly to the site and draw the original engine's nearest-substation links from it
// (link.measure.nearestSubstations, as for a flash); "◀ back" restores the lightning card as at its tap (collapsed, so the
// camera can frame it), its links and the filter. Both cards arrive collapsed so the neon links stay visible. Focus moves to
// "◀ back" on the project card, and to the restored card's summary after back. The REPD layers M3 switched on stay on.
RpV=(m,c,g)=>{
  let back=c.re,src=c.wh==='cell centre'?'cell':'flash',[x,y]=g.a,ps=g.parts;
  pc();
  cd(m,x,y,'REPD project',`REPD · ${RpU(ps,RpN).sort().join(' + ')}${RpMW(RpW(ps))}`,
    ps.length>1?`${ps.length} projects at this point · ${RpU(ps,q=>cs(q.name)).join(' / ')}`:`${cs(ps[0].name)} · ${cs(ps[0].status)}`,
    ps.map(q=>`${RpN(q)}${RpMW(+q.capacity)}${RpC([q])} · ${cs(q.status)} · ${cs(q.name)}`).join('; ')+` · lat ${y.toFixed(3)}, lon ${x.toFixed(3)} · ${g.km.toFixed(2)} km from the ${c.wh} (straight-line)`,
    'project',{np:1,foot:'REPD register (DESNZ, April 2026 · OGL v3.0) as loaded by the map · lightning = optical flashes, not necessarily ground strikes; not evidence the project was struck.',
      back:['◀ back to lightning '+src,()=>{pc();back();S.pp&&S.pp.sm.focus?.()}]});
  S.pp.querySelector('[data-lightning-back]')?.focus?.()},

Verify Lineage

A JavaScript module in the lightning folder of GridAtlas that reads the Renewable Energy Planning Database (REPD) register.

ingestgridatlas / tools/lightning/lineage/verify-lineage.mjs · lines 1–37 of 37 · Entry point

What it does
It loads the REPD register. Defines mod. Uses libraries node:fs, node:os, node:path, node:child_process, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage 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.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
Its name says it verifies lineage. Defines `mod`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/lightning/lineage · JavaScript module
Uses
node:fs, node:os, node:path, node:child_process, node:url
Used by
none found
Produces
mod
Defines here
mod
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/lightning/lineage/verify-lineage.mjs:1-37 · blob 4c201237b1a98dcd221a3f41ea5d0aab385257a6 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
// verify-lineage.mjs: replay the M-series build scripts on the committed modules and show that each committed
// generation is exactly its predecessor plus that build step (after the generation restamp the scaffolder made).
// Node built-ins only, except build-M (L3 -> M), which needs acorn for const2let and is skipped without it.
// Not part of CI: the gate checks tools/lightning/src instead (build.mjs --check). docs/LIGHTNING-SOURCE.md.
//   node tools/lightning/lineage/verify-lineage.mjs
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url)), ROOT = path.resolve(HERE, '..', '..', '..');
const mod = g => path.join(ROOT, 'atlas', 'modules', `${g}-uk-lightning-overlay.js`);
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lightning-lineage-'));
const steps = [
  // [label, script, from, to, extra args]
  ['L3 -> M  (build-M.mjs, const2let)', 'build-M.mjs', '202610281340', '202610281950'],
  ['M  -> M2 (build-M2.mjs + repd-m2.part.js)', 'build-M2.mjs', '202610281950', '202610282100'],
  ['M2 -> M3 (build-M3.mjs + layers-m3/repd-m3.part.js)', 'build-M3.mjs', '202610282100', '202610282215'],
  ['M3 -> M4 (build-M4.mjs + fixes-m4.mjs)', 'build-M4.mjs', '202610282215', '202610290045'],
  ['M4 -> M4b (build-M4b.mjs)', 'build-M4b.mjs', '202610290045', '202610290050'],
];
let bad = 0;
for (const [label, script, from, to] of steps) {
  let out = path.join(tmp, `${to}.js`), argv;
  if (script === 'build-M.mjs') {
    if (!fs.existsSync(path.join(HERE, 'deps', 'node_modules', 'acorn'))) { console.log(`skip ${label}: needs tools/lightning/lineage/deps/node_modules/acorn (npm i --prefix deps acorn@8.11.3 acorn-walk)`); continue; }
    argv = [path.join(HERE, script), mod(from), tmp, to]; out = path.join(tmp, 'module-M.js');
  } else argv = [path.join(HERE, script), mod(from), out];
  const r = spawnSync(process.execPath, argv, { encoding: 'utf8' });
  if (r.status !== 0) { console.log(`FAIL ${label}: ${(r.stderr || r.stdout).trim().split('\n').pop()}`); bad++; continue; }
  const got = fs.readFileSync(out, 'utf8').split(from).join(to), want = fs.readFileSync(mod(to), 'utf8');
  if (got === want) console.log(`ok   ${label}: ${to} reproduced (${Buffer.byteLength(want)} B)`);
  else { console.log(`FAIL ${label}: output differs from ${path.relative(ROOT, mod(to))}`); bad++; }
}
fs.rmSync(tmp, { recursive: true, force: true });
process.exit(bad ? 1 : 0);

Make Generation

A JavaScript module in the lightning folder of GridAtlas that reads composition, using SHA-256. It reads buf (`readBuf`) and reads text (`readText`).

energy-datagridatlas / tools/lightning/make-generation.mjs · lines 1–202 of 202 · Entry point · pattern countOf (shared by 2 files)

What it does
It loads composition. Defines 12 functions or classes, including die, need, R, readBuf, readText. Uses libraries node:fs, node:path, node:crypto, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'generation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file current.json; JSON file -composition.json; command-line arguments.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
Cut a NEW immutable candidate generation of the UK lightning overlay from `tools/lightning/src`. It reads `atlas/current.json`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/lightning · JavaScript module
Uses
Build (import), node:fs, node:path, node:crypto, node:url
Used by
none found
Produces
die, need, R, readBuf, readText, sha, shaLF, json, countOf, files, derive, write
Defines here
die, need, R, readBuf, readText, sha, shaLF, json, countOf, files, derive, write
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/lightning/make-generation.mjs:1-202 · blob 2bd6965cfabc9ca699ae1b60dae855964d4bd86c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
/**
 * make-generation.mjs: cut a NEW immutable candidate generation of the UK lightning overlay from tools/lightning/src.
 * It is the scaffolder the M-series builds used (make-generation-M4.mjs, kept in tools/lightning/lineage/), made
 * generic: the module is built from the source instead of being passed in, and the generation-specific prose is copied
 * from a template generation of the same variant instead of being written into the script. Node built-ins only.
 *
 *   node tools/lightning/make-generation.mjs --gen 202610300900 --version v9.178 --variant dots \
 *        --scope "M5b (202610300900): <what changed, one sentence>" [--label M5b] [--predecessor <gen>] [--template <gen>] [--dry-run]
 *
 *   --predecessor  the candidate this one is built on (manifest candidate_predecessor); default: the newest lightning
 *                  generation in atlas/modules/.
 *   --template     the generation whose proof, manifest and route current.json are re-identified; default: the newest
 *                  generation of the same variant in tools/lightning/generations.json. Its prose (composition_note,
 *                  uk_lightning.*) is copied as is: when the behaviour it describes changes, edit those strings in the
 *                  new manifest AND the new route current.json in the same commit (the proof and the gate check them).
 *   --scope        appended to acceptance.scope of the manifest: what this generation changes.
 *
 * Writes the six generation files with flag 'wx' (an existing file is never overwritten) and adds the generation to
 * tools/lightning/generations.json, dropping from it every listed generation the edited source no longer rebuilds:
 *   atlas/modules/<GEN>-uk-lightning-overlay.js   node tools/lightning/build.mjs output for --variant, stamped <GEN>
 *   atlas/cartridges/<GEN>-sld-sandbox-v9-8.js    the template's base sld-sandbox bytes + "\n" + module
 *   tools/proofs/<GEN>-sld-sandbox.proof.mjs      the template proof with only `const GEN=` changed
 *   atlas/manifests/<GEN>-composition.json        the template manifest re-identified
 *   atlas/v/<GEN>/index.html                      byte copy of atlas/index.html
 *   atlas/v/<GEN>/current.json                    the template route current.json re-identified
 * Deterministic: cut_at_utc is derived from --gen, not the clock. atlas/current.json, STATE.md, atlas/index.html and
 * every file of the live, template and predecessor generations are hashed before and after; any change aborts.
 * It never moves the live pointer: that is tools/release/release-generation.mjs (docs/RELEASE.md).
 */
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { assemble, readGenerations, newestModule, GENERATIONS } from './build.mjs';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const MODULE_CEILING = 64781;     // 500,000 - 435,218 base sld-sandbox bytes - 1 newline (owner, 28 Oct 2026)
const CARTRIDGE_CEILING = 500000; // tools/scope/loop.mjs (raised from 480 kB by the owner, 28 Oct 2026)

const die = msg => { console.error(`make-generation: FAIL ${msg}`); process.exit(1); };
const need = (ok, msg) => { if (!ok) die(msg); };
const args = { 'dry-run': false };
for (let i = 2; i < process.argv.length; i++) {
  const k = process.argv[i];
  if (k === '--dry-run') { args['dry-run'] = true; continue; }
  need(/^--(gen|version|variant|scope|predecessor|template|label)$/.test(k) && process.argv[i + 1] !== undefined, `bad argument ${k}`);
  args[k.slice(2)] = process.argv[++i];
}
for (const k of ['gen', 'version', 'variant', 'scope']) need(args[k], `--${k} is required`);
const { gen: GEN, version: VERSION, variant: VARIANT } = args, DRY = args['dry-run'];

const R = p => path.join(ROOT, p);
const readBuf = p => fs.readFileSync(R(p));
const readText = p => fs.readFileSync(R(p), 'utf8');
const sha = buf => createHash('sha256').update(buf).digest('hex');
const shaLF = buf => sha(Buffer.from(buf.toString('binary').replace(/\r\n/g, '\n'), 'binary')); // tools/scope/lib.mjs sha256PublishedFile
const json = obj => JSON.stringify(obj, null, 1) + '\n';
const countOf = (hay, needle) => hay.split(needle).length - 1;
const files = g => ({
  module: `atlas/modules/${g}-uk-lightning-overlay.js`, cartridge: `atlas/cartridges/${g}-sld-sandbox-v9-8.js`,
  proof: `tools/proofs/${g}-sld-sandbox.proof.mjs`, manifest: `atlas/manifests/${g}-composition.json`,
  routeIndex: `atlas/v/${g}/index.html`, routeCurrent: `atlas/v/${g}/current.json`
});

/* ---------- arguments ---------- */
const reg = readGenerations();
need(reg.variants.includes(VARIANT), `--variant must be one of ${reg.variants.join(', ')}`);
need(/^\d{12}$/.test(GEN), `--gen must be YYYYMMDDHHMM, got ${GEN}`);
const cutAt = `${GEN.slice(0, 4)}-${GEN.slice(4, 6)}-${GEN.slice(6, 8)}T${GEN.slice(8, 10)}:${GEN.slice(10, 12)}:00.000Z`;
need(!Number.isNaN(Date.parse(cutAt)) && new Date(cutAt).toISOString() === cutAt, `--gen ${GEN} is not a real UTC minute`);
need(/^v9\.\d+$/.test(VERSION), `--version must look like v9.N, got ${VERSION}`);
const PRED = args.predecessor || newestModule();
const sameVariant = Object.keys(reg.generations).filter(g => reg.generations[g].variant === VARIANT).sort();
const TPL = args.template || sameVariant[sameVariant.length - 1];
need(TPL, `no generation of variant ${VARIANT} in generations.json to use as the template; pass --template <gen>`);
need(GEN > PRED && GEN > TPL && GEN > newestModule(), `--gen ${GEN} must advance beyond ${[PRED, TPL, newestModule()].sort().pop()}`);
for (const g of new Set([PRED, TPL])) for (const p of Object.values(files(g))) need(fs.existsSync(R(p)), `${p} missing (generation ${g})`);

/* ---------- version: unused anywhere in the composition record, and advancing ---------- */
const versionFiles = ['atlas/current.json',
  ...fs.readdirSync(R('atlas/manifests')).filter(n => n.endsWith('-composition.json')).map(n => `atlas/manifests/${n}`),
  ...fs.readdirSync(R('atlas/v')).map(n => `atlas/v/${n}/current.json`).filter(p => fs.existsSync(R(p)))];
let maxUsed = 0;
for (const p of versionFiles) {
  const text = readText(p);
  need(!text.includes(`"${VERSION}"`) && !text.includes(`-gridatlas-${VERSION}"`), `${VERSION} is already used in ${p}`);
  for (const m of text.matchAll(/"(?:composition_version|version)": "v9\.(\d+)"/g)) maxUsed = Math.max(maxUsed, Number(m[1]));
}
need(Number(VERSION.split('.')[1]) > maxUsed, `${VERSION} does not advance beyond the highest recorded version v9.${maxUsed}`);

/* ---------- outputs must not exist ---------- */
const OUT = files(GEN);
for (const p of Object.values(OUT)) need(!fs.existsSync(R(p)), `${p} already exists; generations are immutable, pick a new --gen`);
need(!reg.generations[GEN], `${GEN} is already in generations.json`);

/* ---------- protected set ---------- */
const live = JSON.parse(readText('atlas/current.json'));
const LIVE_PTR = String(live.generation);
const PROTECTED = [...new Set(['atlas/current.json', 'STATE.md', 'atlas/index.html',
  ...live.cartridge_order.map(id => 'atlas/' + live.cartridges.find(c => c.id === id).path.replace(/^\.\//, '')),
  ...[PRED, TPL].flatMap(g => Object.values(files(g))),
  ...(fs.existsSync(R(files(LIVE_PTR).module)) ? Object.values(files(LIVE_PTR)).filter(p => fs.existsSync(R(p))) : [])])];
const before = Object.fromEntries(PROTECTED.map(p => [p, sha(readBuf(p))]));

/* ---------- 1. module, from the source ---------- */
const moduleBuf = Buffer.from(assemble({ variant: VARIANT, gen: GEN, variants: reg.variants }), 'utf8');
need(moduleBuf.length <= MODULE_CEILING, `module is ${moduleBuf.length} B; the ceiling is ${MODULE_CEILING} B`);
need(countOf(moduleBuf.toString('utf8'), GEN) === 2, 'the module must carry the generation exactly twice (header and GEN)');

/* ---------- 2. cartridge = base + "\n" + module, the lineage proven on the template and the predecessor ---------- */
const tplManifest = JSON.parse(readText(files(TPL).manifest));
const tplSld = tplManifest.cartridges.find(c => c.id === 'sld-sandbox');
need(tplSld && /^\.\/cartridges\/\d{12}-sld-sandbox-v9-8\.js$/.test(tplSld.derived_from || ''), 'template sld-sandbox entry has no derived_from base');
const BASE = 'atlas/' + tplSld.derived_from.slice(2), baseBuf = readBuf(BASE);
need(!baseBuf.includes(13), `${BASE} contains CR`);
for (const g of new Set([PRED, TPL])) need(readBuf(files(g).cartridge).equals(Buffer.concat([baseBuf, Buffer.from('\n'), readBuf(files(g).module)])),
  `${g} cartridge is not ${BASE} + \\n + its module`);
const cartridgeBuf = Buffer.concat([baseBuf, Buffer.from('\n'), moduleBuf]);
need(cartridgeBuf.length <= CARTRIDGE_CEILING, `cartridge is ${cartridgeBuf.length} B; the ceiling is ${CARTRIDGE_CEILING} B`);
const cartridgeSha = shaLF(cartridgeBuf);
need(cartridgeSha === sha(cartridgeBuf), 'raw and LF hashes differ (CR present)');

/* ---------- 3. proof: only `const GEN=` changes ---------- */
const tplProof = readText(files(TPL).proof);
need(countOf(tplProof, TPL) === 1 && countOf(tplProof, `const GEN='${TPL}';`) === 1, `template proof ${files(TPL).proof} must carry its generation exactly once, as const GEN='${TPL}';`);
const proofText = tplProof.replace(`const GEN='${TPL}';`, `const GEN='${GEN}';`);

/* ---------- 4/5. manifest and route current.json ---------- */
function derive(src, prefix, kind) {
  const c = structuredClone(src), oldVersion = c.composition_version;
  need(c.generation === TPL, `${kind}: template generation is ${c.generation}`);
  c.generation = GEN;
  c.previous_generation = LIVE_PTR;
  c.superseded_generation = LIVE_PTR;
  c.candidate_predecessor = PRED;
  c.composition_manifest = `${prefix}manifests/${GEN}-composition.json`;
  c.composition_version = VERSION;
  c.composition_id = `${GEN}-gridatlas-${VERSION}`;
  if (typeof c.composition_note === 'string' && c.composition_note.startsWith(`${oldVersion}:`)) c.composition_note = VERSION + c.composition_note.slice(oldVersion.length);
  const sld = c.cartridges.find(x => x.id === 'sld-sandbox');
  need(sld && sld.generation === TPL && sld.derived_from === `${prefix}cartridges/${path.basename(BASE)}`, `${kind}: sld-sandbox entry is not the template's`);
  Object.assign(sld, { generation: GEN, version: VERSION, path: `${prefix}cartridges/${GEN}-sld-sandbox-v9-8.js`, sha256: cartridgeSha, bytes: cartridgeBuf.length });
  need(sld.uk_lightning && sld.uk_lightning.module === `${prefix}modules/${TPL}-uk-lightning-overlay.js`, `${kind}: uk_lightning.module is not the template's`);
  sld.uk_lightning.module = `${prefix}modules/${GEN}-uk-lightning-overlay.js`;
  sld.uk_lightning.module_bytes = moduleBuf.length;
  if (kind === 'manifest') {
    c.parent_generation = LIVE_PTR;
    c.version = VERSION;
    c.cut_at_utc = cutAt;
    c.acceptance.scope += ' ' + args.scope;
    c.acceptance.proof = `tools/proofs/${GEN}-sld-sandbox.proof.mjs`;
    c.acceptance.golden_browser_verification = 'PENDING_THIS_GENERATION';
    need(c.acceptance.full_application_copies_created === 0, 'manifest full_application_copies_created must be 0');
  }
  const text = json(c);
  // no stale identity: the template generation survives only as a predecessor or in history prose, its paths and version never
  for (const bad of [`${TPL}-sld-sandbox`, `${TPL}-uk-lightning-overlay`, `${TPL}-composition`, `${TPL}-gridatlas`, `"${oldVersion}"`, `-${oldVersion}"`])
    need(!text.includes(bad), `${kind}: stale ${bad} remains`);
  need(countOf(text, `"${TPL}"`) === (PRED === TPL ? 1 : 0), `${kind}: the template generation remains as an identity value`);
  return text;
}
const manifestText = derive(tplManifest, './', 'manifest');
const routeText = derive(JSON.parse(readText(files(TPL).routeCurrent)), '../../', 'route');
const indexBuf = readBuf('atlas/index.html');

const summary = { result: DRY ? 'DRY-RUN (nothing written)' : 'WRITTEN', generation: GEN, version: VERSION, variant: VARIANT,
  candidate_predecessor: PRED, template: TPL, live: LIVE_PTR, cut_at_utc: cutAt,
  module: { path: OUT.module, bytes: moduleBuf.length, sha256: sha(moduleBuf), spare: MODULE_CEILING - moduleBuf.length },
  cartridge: { path: OUT.cartridge, bytes: cartridgeBuf.length, sha256_lf: cartridgeSha, base: BASE },
  proof: OUT.proof, manifest: OUT.manifest, route: [OUT.routeIndex, OUT.routeCurrent] };
if (DRY) { console.log(JSON.stringify(summary, null, 1)); process.exit(0); }

/* ---------- write (never overwrite) ---------- */
fs.mkdirSync(R(`atlas/v/${GEN}`));
const write = (p, data) => fs.writeFileSync(R(p), data, { flag: 'wx' });
write(OUT.module, moduleBuf);
write(OUT.cartridge, cartridgeBuf);
write(OUT.proof, proofText);
write(OUT.manifest, manifestText);
write(OUT.routeIndex, indexBuf);
write(OUT.routeCurrent, routeText);
// register the new generation; a listed generation the edited source no longer rebuilds is dropped (its source is the
// commit that cut it), so build.mjs --check keeps passing
const regText = JSON.parse(fs.readFileSync(GENERATIONS, 'utf8'));
regText.generations[GEN] = { variant: VARIANT, label: args.label || args.scope.split(/[ :(]/)[0] };
const dropped = Object.keys(regText.generations).filter(g => g !== GEN && !readBuf(files(g).module)
  .equals(Buffer.from(assemble({ variant: regText.generations[g].variant, gen: g, variants: reg.variants }), 'utf8')));
for (const g of dropped) delete regText.generations[g];
fs.writeFileSync(GENERATIONS, json(regText));

/* ---------- post-checks ---------- */
for (const p of PROTECTED) need(sha(readBuf(p)) === before[p], `protected file changed: ${p}`);
need(readBuf(OUT.cartridge).equals(Buffer.concat([baseBuf, Buffer.from('\n'), readBuf(OUT.module)])), 'cartridge is not base + \\n + module');
for (const [label, p, base] of [['manifest', OUT.manifest, R('atlas')], ['route', OUT.routeCurrent, R(`atlas/v/${GEN}`)]]) {
  const c = JSON.parse(readText(p));
  for (const id of c.cartridge_order) {
    const e = c.cartridges.find(x => x.id === id);
    need(shaLF(fs.readFileSync(path.resolve(base, e.path))) === e.sha256, `${label}: ${id} sha256 does not match ${e.path}`);
  }
}
console.log(JSON.stringify({ ...summary, protected_unchanged: PROTECTED.length, generations_json_dropped: dropped }, null, 1));