In this section
- Build M render · gridatlas / tools/lightning/lineage/build-M.mjs lines 1–86
- Build M2 storage · gridatlas / tools/lightning/lineage/build-M2.mjs lines 1–39
- Build M3 storage · gridatlas / tools/lightning/lineage/build-M3.mjs lines 1–53
- Build M4 storage · gridatlas / tools/lightning/lineage/build-M4.mjs lines 1–35
- Build M4b render · gridatlas / tools/lightning/lineage/build-M4b.mjs lines 1–60
- Const2let transform · gridatlas / tools/lightning/lineage/const2let.mjs lines 1–42
- Fixes M4 transform · gridatlas / tools/lightning/lineage/fixes-m4.mjs lines 1–17
- Layers M3 Part render · gridatlas / tools/lightning/lineage/layers-m3.part.js lines 1–14
- Make Generation M4 energy-data · gridatlas / tools/lightning/lineage/make-generation-M4.mjs lines 1–281
Build M
A JavaScript module in the lineage folder of GridAtlas that maps Renewable Energy Planning Database (REPD) master, the REPD register, substations and solar.
rendergridatlas / tools/lightning/lineage/build-M.mjs · lines 1–86 of 86 · Entry point
- What it does
- It maps REPD master, the REPD register, substations and solar. Defines KEEP, fin, once, all, b. Uses libraries node:fs. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, substations, solar.
- Inputs & outputs
- In: JSON file repd_master.json; command-line arguments.
- Downstream impact
- It is itself an entry point (JavaScript module); no other file was found loading it.
- What it achieves
- It is built from the all step (`all`). Defines `KEEP`, `fin`, `once` and 1 more. It reads `/dist/repd_master.json`.
- 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
- Const2let (import), node:fs
- Used by
- none found
- Produces
- KEEP, fin, once, all, b
- Defines here
- KEEP, fin, once, all, b
- 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/build-M.mjs:1-86 · blob 6331e7b54344d3d3c2653aa5dda42492dea7bd0f · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
// build-M.mjs: L3 live module (202610281340) -> M0 (byte savings only, zero behaviour change) -> M (adds REPD projects).
// Every replacement must match exactly once (or the stated count). Usage: node build-M.mjs <L3 module> <outdir> [GEN]
import fs from 'node:fs';
import { const2let } from './const2let.mjs';
// A5 (applied last to each output): const -> let where scope analysis proves no reassignment; two declarations whose
// exact text the suites assert (test-engine 1271 grid path, 1457 mask loop) stay const.
const KEEP = t => t.startsWith("const u=AR+'grid/'") || t === "const c of'";
const fin = t => { const r = const2let(t, KEEP); if (r.kept !== 2) throw new Error('const2let kept ' + r.kept); return r.out; };
const [,, SRC, OUT, GEN] = process.argv;
let s = fs.readFileSync(SRC, 'utf8');
const L3GEN = '202610281340';
const once = (from, to, n = 1) => { const k = s.split(from).length - 1; if (k !== n) throw new Error(`expected ${n} x ${JSON.stringify(from.slice(0, 80))}, found ${k}`); s = s.split(from).join(to); };
const all = (from, to) => once(from, to, s.split(from).length - 1);
/* ---------- stage A: savings ---------- */
// A1 header: 4 lines -> 1 shorter line, same facts (generation, OFF by default, never persisted, not ground strikes, unknown not zero, cells)
const hEnd = s.indexOf('*/') + 3;
if (!s.startsWith('/* uk-lightning-overlay, generation ' + L3GEN)) throw new Error('header');
s = `/* uk-lightning-overlay, generation ${L3GEN} (UTC). EUMETSAT MTG LI L2-LFL optical flashes, OFF by default, never persisted; NOT confirmed ground strikes; unsearched is unknown, never zero. Long periods: ≈10 km cells within 30 km of a REPD site. */\n` + s.slice(hEnd);
// A2 whole-line // comments
const before = s.length; s = s.replace(/^\/\/.*\n/gm, ''); if (before - s.length < 1000) throw new Error('comments');
// A3 aliases: Math.max/min, Array.isArray, Date.parse (all static, no `this`), appendChild and getBoundingClientRect helpers,
// and the phrase 'unknown, not zero'
once("const NS=(window", "const MX=Math.max,MN=Math.min,AI=Array.isArray,DP=Date.parse,ap=(p,c)=>p.appendChild(c),gr=e=>e.getBoundingClientRect(),U='unknown, not zero',NS=(window");
all('Math.max(', 'MX('); all('Math.min(', 'MN('); all('Array.isArray(', 'AI('); all('Date.parse(', 'DP(');
{ const n = s.split('.appendChild(').length - 1;
s = s.replace(/([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*(?:\(\))?)\.appendChild\(/g, (m0, r) => r === 'p' ? m0 : `ap(${r},`);
if (n < 10 || s.split('.appendChild(').length - 1 !== 1) throw new Error('ap'); }
{ s = s.replace(/([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*(?:\(\))?)\.getBoundingClientRect\(\)/g, (m0, r) => r === 'e' ? m0 : `gr(${r})`);
if (s.split('.getBoundingClientRect()').length - 1 !== 1) throw new Error('gr'); }
once("FOOTER='Times UTC · Optical flashes seen by MTG Lightning Imager (EUMETSAT L2-LFL), not confirmed ground strikes · Missing days are unknown, not zero · UK box −11.0,49.5 → 3.0,61.5'",
"FOOTER=`Times UTC · Optical flashes seen by MTG Lightning Imager (EUMETSAT L2-LFL), not confirmed ground strikes · Missing days are ${U} · UK box −11.0,49.5 → 3.0,61.5`");
once("nz=' (unknown, not zero)'", "nz=` (${U})`");
once("r.old?'earlier days unknown, not zero':", "r.old?'earlier days '+U:");
once("nothing shown (unknown, not zero)`", "nothing shown (${U})`");
once("${x.cutoffDate}) — unknown, not zero`", "${x.cutoffDate}) — ${U}`");
once("earlier hours unknown, not zero)`", "earlier hours ${U})`");
once("': earlier coverage unknown, not zero'", "': earlier coverage '+U");
once("'Actual none seen in the 7-day feed (unknown, not zero)'", "`Actual none seen in the 7-day feed (${U})`");
once("'Searched EUMETSAT: shard lost (integrity alert), unknown, not zero'", "'Searched EUMETSAT: shard lost (integrity alert), '+U");
once("of window (unknown, not zero)`", "of window (${U})`");
once("(integrity alert), unknown, not zero`", "(integrity alert), ${U}`");
once("(malformed timestamp; unknown, not zero)`", "(malformed timestamp; ${U})`");
once("unsearched days unknown, not zero`", "unsearched days ${U}`");
if (s.split('unknown, not zero').length !== 2) throw new Error('phrase left');
const M0 = fin(s);
fs.writeFileSync(`${OUT}/module-M0.js`, M0);
/* ---------- stage B: REPD projects ---------- */
if (GEN) {
// B1 project layer and source ids join the L3 neon set, so nc() (close, period, LATEST, OFF) removes them too
once("'pin-halo','pin']", "'pin-halo','pin','p-core','p-node','p-label']");
once("NSR=[NP+'-links',NP+'-nodes',NP+'-pin']", "NSR=[NP+'-links',NP+'-nodes',NP+'-pin',NP+'-plinks',NP+'-pnodes']");
// B2 nr: the drawing helpers move above the "no substation" return; the frame list is S.fk; the 10 nearest REPD projects
once("const k=M.nearestSubstations(x,y,subs);say(", "const k=M.nearestSubstations(x,y,subs),o=[x,y],TC='#d8c96a',TL='#5fbdc2',FL='#bfe9ee',Z=(a,b,h=12)=>['interpolate',['linear'],['zoom'],6,a,h,b],RJ={'line-cap':'round','line-join':'round'},\nA=(i,type,source,paint,layout)=>m.addLayer(Object.assign({id:NI[i],type,source,paint},layout?{layout}:{}));S.fk=[o,...k.map(a=>a.at)];say(");
once(":''));return k}\nfor(const a of k)say(`${(+a.km).toFixed(2)} km · ${a.kv[0]} kV · ${cs(a.name||'unnamed substation')}`);\n",
":''))}\nfor(const a of k)say(`${(+a.km).toFixed(2)} km · ${a.kv[0]} kV · ${cs(a.name||'unnamed substation')}`);\n"
+ "const pd=say('REPD projects: loading…');RG(m,M).then(G=>{if(S.pp!==c)return;"
+ "const P=G.map(([a,p])=>({a,p,km:M.distanceKm(x,y,...a)})).filter(r=>r.km<=40).sort((a,b)=>a.km-b.km).slice(0,10),"
+ "L=r=>`${r.km.toFixed(2)} km · ${({solar:'Solar',solar_roof:'Rooftop solar'})[r.p.tech]||cs(r.p.raw_tech)}${r.p.capacity>0?` ${N(r.p.capacity)} MW`:''}`,"
+ "F=g=>({type:'geojson',data:FC(P.map(r=>({type:'Feature',properties:{mw:+r.p.capacity||0,label:L(r)},geometry:g(r)})))}),C=['interpolate',['linear'],['get','mw'],0,'#ffaa00',50,'#ff4400',200,'#f00'];\n"
+ "pd.textContent=`${P.length?pl(P.length,'nearest REPD project'):'No REPD project'} within 40 km of this ${c.wh} (straight-line; all technologies and statuses). Not evidence any project was struck or affected.`;P.length&&(c.sm.textContent+=` · ${P.length} nearest projects`);\n"
+ "for(const r of P){const p=r.p,b=el('a','display:block;padding:14px 0 13px;border-top:1px solid #1d3238;color:#ffb27a',`${L(r)} · ${cs(p.status)} · ${cs(p.name)}`);b.href=location.pathname+'?'+new URLSearchParams({longitude:r.a[0],latitude:r.a[1],technology:p.tech,project:p.name,capacity_mw:p.capacity,status:p.status});ap(c.out,b)}\n"
+ "m.addSource(NSR[3],F(r=>({type:'LineString',coordinates:[o,r.a]})));m.addSource(NSR[4],F(r=>({type:'Point',coordinates:r.a})));\n"
+ "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});\n"
+ "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))}\n"
+ "cpos();S.fk.push(...P.map(r=>r.a));m.isMoving&&m.isMoving()||ck()}).catch(e=>{if(S.pp===c)pd.textContent='REPD projects unavailable: '+msg(e)});if(!k.length)return k;\n");
once("\nconst o=[x,y],TC='#d8c96a',TL='#5fbdc2',FL='#bfe9ee',Z=(a,b,h=12)=>['interpolate',['linear'],['zoom'],6,a,h,b],RJ={'line-cap':'round','line-join':'round'},\nA=(i,type,source,paint,layout)=>m.addLayer(Object.assign({id:NI[i],type,source,paint},layout?{layout}:{}));\n", "\n");
// B3 camera: one frame list S.fk (origin, substations, then projects), checked at moveend or when projects arrive
once("if(k.length)nz(m,x,y,k);return}", "if(k.length)nz(m,x,y);return}");
once("nz=(m,x,y,k)=>{try{m.flyTo({center:[x,y],zoom:12,duration:1200,essential:true});const ck=()=>{const v=m.getBounds&&m.getBounds();if(!v||S.pp===null||k.every(a=>v.contains(a.at)))return;let w=x,s=y,e=x,n=y;for(const[a,o]of k.map(a=>a.at)){w=MN(w,a);e=MX(e,a);s=MN(s,o);n=MX(n,o)}\n"
+ "m.fitBounds([[w,s],[e,n]],{padding:{top:150,left:40,right:40,bottom:(S.pp.bb+S.pp.offsetHeight||196)+24},maxZoom:12,duration:900})};typeof m.once=='function'?m.once('moveend',ck):ck()}catch(e){note('camera: '+msg(e))}},",
"nz=(m,x,y)=>{try{m.flyTo({center:[x,y],zoom:12,duration:1200,essential:true});typeof m.once=='function'?m.once('moveend',ck):ck()}catch(e){note('camera: '+msg(e))}},\n"
+ "ck=()=>{try{const m=mh(),v=m&&m.getBounds&&m.getBounds(),k=S.fk;if(!v||!S.pp||k.every(a=>v.contains(a)))return;let[w,s]=k[0],[e,n]=k[0];for(const[a,o]of k){w=MN(w,a);e=MX(e,a);s=MN(s,o);n=MX(n,o)}\n"
+ "m.fitBounds([[w,s],[e,n]],{padding:{top:150,left:40,right:40,bottom:(S.pp.bb+S.pp.offsetHeight||196)+24},maxZoom:12,duration:900})}catch(e){note('camera: '+msg(e))}},\n"
// B4 the register: the engine's src-repd data once a REPD layer has loaded it, else the engine's own URL through the bridge
+ "RG=(m,M)=>S.rg||(S.rg=(async()=>{let f;try{f=m.getSource('src-repd').serialize().data.features}catch(_){}if(!(f&&f.length)){let r=await fetch('/dist/repd_master.json');r.ok||E('HTTP '+r.status);f=(await r.json()).features}"
+ "const 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})),");
s = s.replace(`generation ${L3GEN}`, `generation ${GEN}`).replace(`GEN='${L3GEN}'`, `GEN='${GEN}'`);
if (!s.includes(`GEN='${GEN}'`) || !s.includes(`generation ${GEN}`)) throw new Error('stamp');
s = fin(s);
fs.writeFileSync(`${OUT}/module-M.js`, s);
}
const b = x => Buffer.byteLength(x);
console.log(JSON.stringify({ L3: b(fs.readFileSync(SRC, 'utf8')), M0: b(M0), M: GEN ? b(s) : null, cap: 44781, cartridge_M: GEN ? 435218 + 1 + b(s) : null }));Build M2
A JavaScript module in the lineage folder of GridAtlas that reads the Renewable Energy Planning Database (REPD) register and substations.
storagegridatlas / tools/lightning/lineage/build-M2.mjs · lines 1–39 of 39 · Not reached from any entry point (candidate for review)
- What it does
- It loads the REPD register and substations. Defines once, cut. Uses libraries node:fs. Side effects: reads or writes files.
- 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, substations.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- It is built from the once step (`once`) and the cut step (`cut`). Cartridge gate 500,000 B, module cap 64,781 B). It responds to click events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/lightning/lineage · JavaScript module
- Uses
- Renewable Energy Planning Database (REPD) M2 Part (new URL import.meta.url), node:fs
- Used by
- none found
- Produces
- once, cut
- Defines here
- once, cut
- 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/build-M2.mjs:1-39 · blob ec7c0799c93f7dd617a55044ea50085417baac3c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// build-M2.mjs: Build M (202610281950) module -> M2 module (owner, 28 Oct 2026 20:51 UTC: "make the feature comprehensive";
// cartridge gate 500,000 B, module cap 64,781 B). Every replacement is exact-once against the M bytes.
// MR1-MR4 (reports/MR.md) + the bridge failed-start note, and the comprehensive REPD block (tools/repd-m2.part.js):
// in-page row tap with "◀ back", co-located sites grouped, status/technology filter chips with re-ranking,
// a 10 km / 40 km summary line, and an explicit "fewer than 10" statement.
// usage: node build-M2.mjs <module-M.js> <out.js>
import fs from 'node:fs';
const [, , IN, OUT] = process.argv;
let s = fs.readFileSync(IN, 'utf8'); const b0 = Buffer.byteLength(s), log = [];
const once = (id, a, b) => { const k = s.split(a).length - 1; if (k !== 1) throw new Error(id + ' found ' + k); const n0 = Buffer.byteLength(s); s = s.replace(a, () => b); log.push([id, Buffer.byteLength(s) - n0]); };
const cut = (id, from, to, b) => { const i = s.indexOf(from), j = s.indexOf(to, i); if (i < 0 || j < 0 || s.indexOf(from, i + 1) >= 0) throw new Error(id); const n0 = Buffer.byteLength(s); s = s.slice(0, i) + b + s.slice(j); log.push([id, Buffer.byteLength(s) - n0]); };
// header: one more readable line for M2
once('header', 'Long periods: ≈10 km cells within 30 km of a REPD site. */',
'Long periods: ≈10 km cells within 30 km of a REPD site. */\n/* M2: a tap lists the nearest REPD project sites (straight-line, 40 km; co-located parts grouped; status and technology filters; 10 km / 40 km summary); a row flies to the project and draws its nearest-substation links, with "◀ back" to the lightning card. Distance only: never "affected". */');
// card: options (np = no REPD list, open, foot, back) and a re-open closure for "◀ back"
once('cd-sig', 'cd=(m,x,y,lb,ti,su,de,wh)=>{', 'cd=(m,x,y,lb,ti,su,de,wh,o={})=>{');
once('cd-re', 'c.wh=wh;', 'c.wh=wh;c.o=o;c.re=open=>cd(m,x,y,lb,ti,su,de,wh,{...o,open});');
once('cd-back', 'ap(d,c.out);ap(bd,d);',
"ap(d,c.out);if(o.back){let k=ap(bd,el('button','display:block;width:100%;min-height:44px;margin:8px 0 2px;background:#050a0d;border:1px solid #2f6f75;border-radius:3px;color:#5fbdc2;font:12px/1 monospace;text-align:left;padding:0 10px;cursor:pointer',o.back[0]));k.type='button';k.dataset.lightningBack='';k.addEventListener('click',o.back[1])}ap(bd,d);if(o.open)d.open=true;");
once('cd-foot', "ap(bd,el('div','color:#8b9aa1;font-size:10px','EUMETSAT MTG Lightning Imager · optical flash, not necessarily a ground strike.'));",
"ap(bd,el('div','color:#8b9aa1;font-size:10px',o.foot||'EUMETSAT MTG Lightning Imager · optical flash, not necessarily a ground strike.'));");
// nr: the project view states that nearest is not the declared connection; the REPD list runs only for lightning cards
once('nr-say', 'say(`Nearest substations to this ${c.wh} (straight-line km). Not evidence any asset was struck; faults can have other causes.`);',
"say(c.o.np?'Nearest substations to this project (straight-line km; not its declared grid connection).':`Nearest substations to this ${c.wh} (straight-line km). Not evidence any asset was struck; faults can have other causes.`);");
// nf: the project view always flies to the project, even with no substation within 40 km
once('nf-fly', 'if(k.length)nz(m,x,y);return}', 'if(k.length||c.o.np)nz(m,x,y);return}');
cut('nr-repd', "let pd=say('REPD projects: loading…');", "if(!k.length)return k;", 'if(!c.o.np)Rp(m,c,x,y,M);');
// gj: once its own 15 s timer has aborted, any rejection (e.g. a body stream that errors on abort, as the bridge's may)
// is reported as the timeout, not as "Failed to fetch" (browser repro: evidence/M2-build/browser, repd-stall-7D)
once('gj-abort', ".catch(e=>{throw e&&e.name==='AbortError'?new Error(TOE):e})", ".catch(e=>{throw c.signal.aborted||e&&e.name==='AbortError'?new Error(TOE):e})");
// ck: a tall (expanded) card left no room for fitBounds, which then did nothing; keep at least 120 px of map between the
// 150 px top padding and the card. Unchanged whenever the card leaves that room (every L3 tap, which arrives collapsed).
once('ck-pad', 'bottom:(S.pp.bb+S.pp.offsetHeight||196)+24}', 'bottom:MN((S.pp.bb+S.pp.offsetHeight||196)+24,MX(0,(m.getContainer().clientHeight||1e4)-270))}');
// RG and the new REPD functions (readable block) replace M's RG
cut('rg+repd', 'RG=(m,M)=>', 'BTN=(a,t,x)=>', fs.readFileSync(new URL('repd-m2.part.js', import.meta.url), 'utf8'));
fs.writeFileSync(OUT, s);
const n = Buffer.byteLength(s);
console.log(JSON.stringify({ from: b0, to: n, deltas: log, cap: 64781, spare: 64781 - n, cartridge: 435219 + n, cartridgeSpare: 500000 - 435219 - n }));Build M3
A JavaScript module in the lineage folder of GridAtlas that reads the Renewable Energy Planning Database (REPD) register.
storagegridatlas / tools/lightning/lineage/build-M3.mjs · lines 1–53 of 53 · Not reached from any entry point (candidate for review)
- What it does
- It loads the REPD register. Defines once, cut. Uses libraries node:fs. Side effects: reads or writes files.
- 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.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- It is built from the once step (`once`) and the cut step (`cut`). Build M2 module (, as published on main) -> M3 module. It responds to toggle and change events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/lightning/lineage · JavaScript module
- Uses
- Layers M3 Part (new URL import.meta.url), Renewable Energy Planning Database (REPD) M3 Part (new URL import.meta.url), node:fs
- Used by
- none found
- Produces
- once, cut
- Defines here
- once, cut
- 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/build-M3.mjs:1-53 · blob 015892aef2135577240a2fc78cfe0c2ebd79c709 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// build-M3.mjs: Build M2 module (202610282100, as published on main) -> M3 module.
// Owner, 28 Oct 2026 21:39 UTC: "Can we auto activate the REPD layers of the targeted 10 nearest projects?"
// Every replacement is exact-once against the M2 bytes. The layer bookkeeping lives in tools/layers-m3.part.js.
// Review fixes from reports/M2R-*.md are applied by tools/fixes-m3.mjs (exported `fixes(once, cut)`), if present.
// usage: node build-M3.mjs <module-M2.js> <out.js>
import fs from 'node:fs';
const [, , IN, OUT] = process.argv;
let s = fs.readFileSync(IN, 'utf8'); const b0 = Buffer.byteLength(s), log = [];
const once = (id, a, b) => { const k = s.split(a).length - 1; if (k !== 1) throw new Error(id + ' found ' + k); const n0 = Buffer.byteLength(s); s = s.replace(a, () => b); log.push([id, Buffer.byteLength(s) - n0]); };
const cut = (id, from, to, b) => { const i = s.indexOf(from), j = s.indexOf(to, i); if (i < 0 || j < 0 || s.indexOf(from, i + 1) >= 0) throw new Error(id); const n0 = Buffer.byteLength(s); s = s.slice(0, i) + b + s.slice(j); log.push([id, Buffer.byteLength(s) - n0]); };
once('header', 'with "◀ back" to the lightning card. Distance only: never "affected". */',
'with "◀ back" to the lightning card. Distance only: never "affected". */\n/* M3: the original REPD map layers of the listed technologies are switched on through their own Layers checkboxes, and only those M3 switched on are switched off again on close, lightning OFF, a period change, LATEST or a new list. */');
// the REPD block (M2's RG … RpV) is replaced by the M3 block: the layer bookkeeping (tools/layers-m3.part.js) and the REPD
// card with the M2 review fixes folded in (tools/repd-m3.part.js; see reports/M3-build.md for each finding)
cut('repd', '/* ---- REPD projects near a tap (M2)', 'BTN=(a,t,x)=>', fs.readFileSync(new URL('layers-m3.part.js', import.meta.url), 'utf8') + fs.readFileSync(new URL('repd-m3.part.js', import.meta.url), 'utf8'));
// M2R-repd R2: the header says what the grouping does
once('hdr-group', '40 km; co-located parts grouped;', '40 km; projects at one point grouped;');
// M2R-a11y MAJOR-1: one visually hidden polite status region per card, outside the closed <details>
once('a11y-live', 'ap(c,bar);ap(c,bd);S.pp=c;', "ap(c,bar);ap(c,bd);c.lv=ap(c,el('div','position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)'));c.lv.setAttribute('role','status');S.pp=c;");
// M2R-a11y MINOR-1: the back control's name without the ◀ glyph
once('a11y-back', "k.dataset.lightningBack='';", "k.dataset.lightningBack='';k.setAttribute('aria-label',o.back[0].slice(2));");
// M2R-words W10: next to the REPD summary, say what is not within 40 km
once('w10', '` · none within ${k.radiusKm||40} km`', '` · no substation within ${k.radiusKm||40} km`');
// M2R-layout F1 (MAJOR-1): an open card never rises above the container top + 320 px (at least 240 px tall), so the origin
// band stays visible
once('layout-f1', "c.style.maxHeight=MX(44,k.height-t-b)+'px'", "c.style.maxHeight=MX(44,MN(k.height-t-b,MX(240,k.height-b-320)))+'px'");
// M2R-layout F2 (MAJOR-2, MINOR-3): refit when any point is outside the visible band (x 20..W-20, y 130..card top-24), not only
// outside the map, or when forced; M2R-diff MD1: the bottom padding is capped at H-270 only when L3's fit is impossible
once('layout-f2', 'ck=()=>{try{let m=mh(),v=m&&m.getBounds&&m.getBounds(),k=S.fk;if(!v||!S.pp||k.every(a=>v.contains(a)))return;',
'ck=f=>{try{let m=mh(),c=S.pp,k=S.fk,C=m&&m.getContainer(),H=C&&C.clientHeight||1e4,B=c&&(c.bb+c.offsetHeight||196)+24;if(!c||!k||f!==1&&k.every(a=>{let p=m.project(a);return p.x>=20&&p.x<=(C.clientWidth||1e4)-20&&p.y>=130&&p.y<=H-B}))return;');
once('layout-f2b', 'bottom:MN((S.pp.bb+S.pp.offsetHeight||196)+24,MX(0,(m.getContainer().clientHeight||1e4)-270))}', 'bottom:H-150>B?B:MX(0,H-270)}');
// M2R-layout F3: re-frame when the card is expanded, collapsed or minimised
once('layout-f3', "bd=el('div','padding:0 8px 6px'),d=el('details'),", "bd=el('div','padding:0 8px 6px'),d=el('details'),rf=()=>{cpos();if(S.pp===c)ck(1)},");
once('layout-f3b', "mn.setAttribute('aria-expanded',o);cpos()});", "mn.setAttribute('aria-expanded',o);rf()});d.addEventListener('toggle',rf);");
// M2R-layout MINOR-4: 11 px, not 10 px (detail line, footer; the REPD block's chip labels and part lines in repd-m3.part.js)
once('layout-11a', "ap(d,el('div','color:#8b9aa1;font-size:10px;overflow-wrap:anywhere',de));", "ap(d,el('div','color:#8b9aa1;font-size:11px;overflow-wrap:anywhere',de));");
once('layout-11b', "ap(bd,el('div','color:#8b9aa1;font-size:10px',o.foot||", "ap(bd,el('div','color:#8b9aa1;font-size:11px',o.foot||");
// close (×), a tap on empty map, period / page / custom / LOAD POINTS (ld without refresh), LATEST, lightning OFF
once('close', "B('×','Close',pc)", "B('×','Close',()=>{pc();Ry()})");
once('tap-empty', 'return f&&cc(m,f)}', 'return f?cc(m,f):Ry()}');
once('ld', 'ld=refresh=>{if(!refresh)pc();', 'ld=refresh=>{if(!refresh)pc(),Ry();');
once('latest', 'S.end=null;S.h=[];pc();return ld(true)', 'S.end=null;S.h=[];pc();Ry();return ld(true)');
once('off', 'else{S.serial++;S.res=null;cx();', 'else{S.serial++;S.res=null;cx();Ry();');
// a user tick/untick of a layer M3 holds hands it to the user (M3's own dispatch runs with S.lyx set)
once('bt', "bt=c=>c.addEventListener('change',ev=>{let t=ev.target;if(t&&t.dataset&&t.dataset.lightningControl==='toggle')so(!!t.checked)})",
"bt=c=>c.addEventListener('change',ev=>{let t=ev.target,d=t&&t.dataset;if(!d)return;if(d.lightningControl==='toggle')so(!!t.checked);else if(!S.lyx&&S.ly)S.ly.delete(d.layerId)})");
let fixesUrl = new URL('fixes-m3.mjs', import.meta.url);
if (fs.existsSync(fixesUrl)) { const { fixes } = await import(fixesUrl); fixes(once, cut); }
fs.writeFileSync(OUT, s);
const n = Buffer.byteLength(s);
console.log(JSON.stringify({ from: b0, to: n, deltas: log, cap: 64781, spare: 64781 - n, cartridge: 435219 + n, cartridgeSpare: 500000 - 435219 - n }));Build M4
A JavaScript module in the lineage folder of GridAtlas that reads the Renewable Energy Planning Database (REPD) register. It is built from the once step (`once`).
storagegridatlas / tools/lightning/lineage/build-M4.mjs · lines 1–35 of 35 · Not reached from any entry point (candidate for review)
- What it does
- It loads the REPD register. Defines once. Uses libraries node:fs. Side effects: reads or writes files.
- 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.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- Build M3 module (, as on main) -> M4 module.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/lightning/lineage · JavaScript module
- Uses
- Fixes M4 (new URL import.meta.url), node:fs
- Used by
- none found
- Produces
- once
- Defines here
- once
- 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/build-M4.mjs:1-35 · blob 62e606371f181424603c9bc73e9928ab772dd370 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// build-M4.mjs: Build M3 module (202610282215, as on main) -> M4 module. Every replacement is exact-once against the M3 bytes.
// M2R-taps MAJOR M2R-T1: a camera move started while the previous one was still running made MapLibre's stop() fire the
// pending once('moveend',ck) synchronously, so ck's fitBounds ran NESTED inside the new move; the outer move then left an
// orphan render frame and the map stopped drawing after a few fast row -> back cycles (latent in L3 for quick re-taps).
// Fix: (1) every module camera move first drops the module's pending framing (cm: m.off('moveend',cw)): nz (tap, row,
// back), ck's own fitBounds (details toggle, minimise), RpR's register-lands-mid-move framing, the cluster easeTo, and the
// fit button; (2) the pending framing itself (cw) runs after the stop that fired it has returned (a microtask), and only
// when the map is then not moving, so a camera move by anyone else (engine popup, search, a gesture) is never nested or
// overridden either.
// Review fixes from reports/M2R-camera.md and reports/M2R-l3regress.md are applied by tools/fixes-m4.mjs if present.
// usage: node build-M4.mjs <module-M3.js> <out.js>
import fs from 'node:fs';
const [, , IN, OUT] = process.argv;
let s = fs.readFileSync(IN, 'utf8'); const b0 = Buffer.byteLength(s), log = [];
const once = (id, a, b) => { const k = s.split(a).length - 1; if (k !== 1) throw new Error(id + ' found ' + k); const n0 = Buffer.byteLength(s); s = s.replace(a, () => b); log.push([id, Buffer.byteLength(s) - n0]); };
once('header', '/* M3: the original REPD map layers',
'/* M4: a module camera move never starts inside another (MapLibre fires moveend synchronously from stop()): the pending framing is dropped before each own move and otherwise runs after the stop that fired it, only when the map is not moving. */\n/* M3: the original REPD map layers');
// (1) nz: drop the pending framing, fly, queue the deferred framing
once('nz', "nz=(m,x,y)=>{try{m.flyTo({center:[x,y],zoom:12,duration:1200,essential:true});typeof m.once=='function'?m.once('moveend',ck):ck()}",
"cw=()=>Promise.resolve().then(()=>{let m=mh();m&&!(m.isMoving&&m.isMoving())&&ck()}),cm=m=>m.off&&m.off('moveend',cw),\nnz=(m,x,y)=>{try{cm(m);m.flyTo({center:[x,y],zoom:12,duration:1200,essential:true});typeof m.once=='function'?m.once('moveend',cw):ck()}");
// ck's own fitBounds (forced by the details toggle / minimise while a flight runs)
once('ck', 'm.fitBounds([[w,s],[e,n]],{padding:{top:150', 'cm(m);m.fitBounds([[w,s],[e,n]],{padding:{top:150');
// RpR: a register that lands mid-move is framed when that move ends (deferred, one pending at most)
once('rpr', "m.isMoving&&m.isMoving()?m.once('moveend',ck):ck()}", "m.isMoving&&m.isMoving()?(cm(m),m.once('moveend',cw)):ck()}");
// the cluster zoom and the fit button are camera moves too
once('cluster', 'let go=z=>m.easeTo({center:f.geometry.coordinates,zoom:z})', 'let go=z=>(cm(m),m.easeTo({center:f.geometry.coordinates,zoom:z}))');
once('fit', 'm.fitBounds([[a,b],[c,d]],{padding:40,maxZoom:9})}', 'cm(m);m.fitBounds([[a,b],[c,d]],{padding:40,maxZoom:9})}');
let fixesUrl = new URL('fixes-m4.mjs', import.meta.url);
if (fs.existsSync(fixesUrl)) { const { fixes } = await import(fixesUrl); fixes(once); }
if (/\bm\.once\('moveend',ck\)/.test(s)) throw new Error('an undeferred moveend framing remains');
fs.writeFileSync(OUT, s);
const n = Buffer.byteLength(s);
console.log(JSON.stringify({ from: b0, to: n, deltas: log, cap: 64781, spare: 64781 - n, cartridge: 435219 + n, cartridgeSpare: 500000 - 435219 - n }));Build M4b
A JavaScript module in the lineage folder of GridAtlas that maps the Renewable Energy Planning Database (REPD) register, solar, wind and battery storage (BESS).
rendergridatlas / tools/lightning/lineage/build-M4b.mjs · lines 1–60 of 60 · Not reached from any entry point (candidate for review)
- What it does
- It maps the REPD register, solar, wind and battery storage (BESS). Defines once, cut. Uses libraries node:fs. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar, wind, battery storage (BESS).
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- It is built from the once step (`once`) and the cut step (`cut`). M4 module -> M4b module (owner option). It responds to change events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/lightning/lineage · JavaScript module
- Uses
- node:fs
- Used by
- none found
- Produces
- once, cut
- Defines here
- once, cut
- 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/build-M4b.mjs:1-60 · blob 3f66efea98a1b32d86a86f4349ec70aa7ba40e18 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// build-M4b.mjs: M4 module -> M4b module (owner option). Same as M4, but instead of switching on whole REPD layers (M3/M4
// lit 148 dots in view at Doncaster, burying the 10 listed sites) it draws ONLY the listed sites, as REPD-styled dots with
// the engine's own glow + core paint (atlas/releases/202608300453-atlas-v9/ventus-corev8engine.js:1305-1337; colours of
// the other techs from that shell's "REPD (GeoJSON)" config, index.html:243-259), and never touches the Layers controls.
// Every replacement is exact-once against the M4 bytes. usage: node build-M4b.mjs <module-M4.js> <out.js>
import fs from 'node:fs';
const [, , IN, OUT] = process.argv;
let s = fs.readFileSync(IN, 'utf8'); const b0 = Buffer.byteLength(s), log = [];
const once = (id, a, b) => { const k = s.split(a).length - 1; if (k !== 1) throw new Error(id + ' found ' + k); const n0 = Buffer.byteLength(s); s = s.replace(a, () => b); log.push([id, Buffer.byteLength(s) - n0]); };
const cut = (id, from, to, b) => { const i = s.indexOf(from), j = s.indexOf(to, i); if (i < 0 || j < 0 || s.indexOf(from, i + 1) >= 0) throw new Error(id); const n0 = Buffer.byteLength(s); s = s.slice(0, i) + b + s.slice(j); log.push([id, Buffer.byteLength(s) - n0]); };
cut('header', '/* M3: the original REPD map layers', '\n',
'/* M4b: the listed REPD sites only are drawn as REPD-styled dots (the engine\'s glow + core paint); the Layers controls are never touched. */');
// the M3 layer bookkeeping (RL, Ly, Ry) is replaced by the dot layer of the listed sites
cut('layers', '/* ---- M3: the REPD map layers', '/* ---- REPD projects near a tap', `/* ---- M4b: the listed REPD sites, drawn in the original REPD style ----------------------------------------------------
One dot per listed project at its site, with the engine's own paint (ventus-corev8engine.js:1305-1337): the solar and
rooftop-solar glow by capacity, the capacity-graded core, and each other technology's own layer colour; stacked in the
engine's REPD layer order. Only the sites on the card are drawn; the reader's Layers are never changed. A dot tap opens
that site's project view, as its row does. */
RpO='solar solar_operational solar_roof wind wind_onshore_operational wind_offshore_operational bess bess_operational biomass tidal hydrogen hydro flywheel act geothermal caes'.split(' '),
RpD=(m,P)=>{let d=FC(P.flatMap((g,k)=>g.parts.map(p=>({type:'Feature',properties:{t:p.tech,c:+p.capacity>0?+p.capacity:0,k,o:RpO.indexOf(p.tech)},geometry:{type:'Point',coordinates:g.a}})))),
T=['get','t'],I=(...a)=>['interpolate',['linear'],['get','c'],...a],R=(r,o)=>['match',T,'solar_roof',r,o];
if(m.getSource(NSR[5]))return m.getSource(NSR[5]).setData(d);m.addSource(NSR[5],{type:'geojson',data:d});
m.addLayer({id:NI[12],type:'circle',source:NSR[5],filter:['any',['all',['==',T,'solar'],['>=',['get','c'],4]],['all',['==',T,'solar_roof'],['>=',['get','c'],1]]],
paint:{'circle-color':R(I(1,'#ff8c00',5,'#ff6600',10,'#ff4400'),I(4,'#ffff00',20,'#ffaa00',50,'#ff4400',200,'#ff0000')),'circle-radius':R(I(1,26,2,30,5,36,10,44),I(4,22,20,32,50,44,200,60,500,80)),
'circle-opacity':R(.15,I(4,.12,20,.18,50,.25,200,.35)),'circle-blur':1,'circle-stroke-width':0}});
m.addLayer({id:NI[13],type:'circle',source:NSR[5],layout:{'circle-sort-key':['get','o']},
paint:{'circle-color':['match',T,'solar_roof',I(0,'#ffcc00',.99,'#ffcc00',1,'#ff8c00',5,'#ff6600',10,'#ff4400'),'solar',I(0,'#ffff00',20,'#ffcc00',50,'#ffaa00',200,'#ff6600',500,'#ff2200'),
'wind','#00ffff','bess','#ffae00','biomass','#39ff14','tidal','#00bfff','hydrogen','#ffffff','hydro','#00aaff','flywheel','#ff69b4','act','#ff6600','geothermal','#ff3300','caes','#88aaff','#888888'],
'circle-radius':R(I(0,7,.5,7,.99,8,1,16,2,18,5,22,10,28),I(0,8,10,10,50,13,200,17,500,22,1000,28)),'circle-stroke-width':R(I(0,1,.99,1,1,2),1.5),'circle-stroke-color':'#000','circle-opacity':R(.9,.85)}})},
`);
once('ni', "'p-label'].map(s=>NP+'-'+s)", "'p-label','p-glow','p-dot'].map(s=>NP+'-'+s)");
once('nsr', "NP+'-pnodes']", "NP+'-pnodes',NP+'-pdots']");
// no layer is switched, so nothing is released (M3's Ry calls go) and the container listener is M2's again
once('close', "B('×','Close',()=>{pc();Ry()})", "B('×','Close',pc)");
once('tap-empty', 'return f?cc(m,f):Ry()}', 'return f&&cc(m,f)}');
once('ld', 'if(!refresh)pc(),Ry();', 'if(!refresh)pc();');
once('latest', 'pc();Ry();return ld(true)', 'pc();return ld(true)');
once('off', 'cx();Ry();', 'cx();');
// M4b holds no layer: a tap on a drawn REPD dot (the reader's own layers) just closes the card, as in L3 (pc removes the dots)
once('l3r-dot', 'if(h&&h.length){for(let q of h)S.ly&&S.ly.delete(q.properties&&q.properties.tech);return Ry()}', 'if(h&&h.length)return;');
once('rg-fail', 'if(S.pp!==c)return;Ry();', 'if(S.pp!==c)return;');
once('bt', "bt=c=>c.addEventListener('change',ev=>{let t=ev.target,d=t&&t.dataset;if(!d)return;if(d.lightningControl==='toggle')so(!!t.checked);else if(!S.lyx&&S.ly)S.ly.delete(d.layerId)})",
"bt=c=>c.addEventListener('change',ev=>{let t=ev.target;if(t&&t.dataset&&t.dataset.lightningControl==='toggle')so(!!t.checked)})");
// RpR: the card says what the map shows instead of naming switched layers; the drawn list is kept for dot taps
cut('rpr-layers', ' // M3: the original REPD layers of the listed technologies', " let C=['interpolate'",
" c.ps=P;if(P.length)ap(box,el('div','margin-top:6px;color:#8b9aa1;font-size:11px','Map: only these sites are drawn, in the REPD layer style; tap a dot for its project view. Your Layers are unchanged.'));\n");
once('rpr-set', 'm.getSource(NSR[3]).setData(ln);m.getSource(NSR[4]).setData(nd)}', 'm.getSource(NSR[3]).setData(ln);m.getSource(NSR[4]).setData(nd);RpD(m,P)}');
once('rpr-add', "A(9,'line',NSR[3],{'line-color':C,'line-width':Z(1,2),'line-opacity':.8,'line-dasharray':[2,2]});", "A(9,'line',NSR[3],{'line-color':C,'line-width':Z(1,2),'line-opacity':.8,'line-dasharray':[2,2]});RpD(m,P);");
// a tap on a drawn site opens its project view (as its row); the project view draws its own site's dots
once('tap-dot', 'tap=e=>{let m=mh();if(!S.on||S.busy||!m||!(m.getLayer(HIT)||m.getLayer(CEL)))return;',
'tap=e=>{let m=mh();if(!S.on||S.busy||!m||!(m.getLayer(HIT)||m.getLayer(CEL)))return;let rq=S.pp&&S.pp.ps&&m.getLayer(NI[13])&&m.queryRenderedFeatures(e.point,{layers:[NI[13]]})[0],rg=rq&&S.pp.ps[rq.properties.k];if(rg)return RpV(m,S.pp,rg);');
once('nr-dot', 'if(!c.o.np)Rp(m,c,x,y,M);', 'if(!c.o.np)Rp(m,c,x,y,M);else if(c.o.g)RpD(m,[c.o.g]);');
once('rpv-g', "'project',{np:1,foot:", "'project',{np:1,g,foot:");
once('rpv-cmt', 'The REPD layers M3 switched on stay on.', 'The project view draws its own site in the REPD style.');
for (const bad of [/data-layer-id/, /lbl-/, /\bRy\(/, /S\.ly\b/, /\bRL\b/, /\bLy\(/]) if (bad.test(s)) throw new Error('M4b still contains ' + bad);
fs.writeFileSync(OUT, s);
const n = Buffer.byteLength(s);
console.log(JSON.stringify({ from: b0, to: n, deltas: log, cap: 64781, spare: 64781 - n, cartridge: 435219 + n, cartridgeSpare: 500000 - 435219 - n }));Const2let
A JavaScript module in the lineage folder of GridAtlas. It is built from the const2let step (`const2let`).
transformgridatlas / tools/lightning/lineage/const2let.mjs · lines 1–42 of 42
- What it does
- It calculates its inputs. Defines const2let.
- 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.
- Downstream impact
- Used directly by 1 file: Build M (gridatlas).
- What it achieves
- Rewrite `const` declarations as `let` (2 bytes each) after proving, with scope resolution, that no binding a declaration creates is ever the target of an assignment, update or for-in/of head.
- Why it matters
- Imported by Build M.
- Application
- gridatlas · tools/lightning/lineage · JavaScript module
- Uses
- ./deps/node_modules/acorn/dist/acorn.mjs, ./deps/node_modules/acorn-walk/dist/walk.mjs
- Used by
- imported by Build M (import)
- Produces
- const2let
- Defines here
- const2let
- 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/const2let.mjs:1-42 · blob 21dc12220c39b50902e30a8aac03d6092b5b5baa · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// const2let: rewrite `const` declarations as `let` (2 bytes each) after proving, with scope resolution, that no binding a
// declaration creates is ever the target of an assignment, update or for-in/of head. For a binding that is never
// reassigned, const and let are identical at run time (same block scope, same TDZ, same per-iteration for-of binding).
import * as acorn from './deps/node_modules/acorn/dist/acorn.mjs';
import * as walk from './deps/node_modules/acorn-walk/dist/walk.mjs';
const FN = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
const names = (p, out) => { if (!p) return out; if (p.type === 'Identifier') out.push(p); else if (p.type === 'ObjectPattern') p.properties.forEach(q => names(q.type === 'RestElement' ? q.argument : q.value, out)); else if (p.type === 'ArrayPattern') p.elements.forEach(e => names(e, out)); else if (p.type === 'RestElement') names(p.argument, out); else if (p.type === 'AssignmentPattern') names(p.l … [line shortened here: 425 characters; full line on GitHub]
export function const2let(src, keep = () => false) {
const ast = acorn.parse(src, { ecmaVersion: 2022, sourceType: 'script' });
const scopes = new Map(), bind = (scope, id, decl) => { if (!scopes.has(scope)) scopes.set(scope, new Map()); scopes.get(scope).set(id.name, decl); };
const decls = [];
// 1. declarations -> scope node
walk.fullAncestor(ast, (n, _s, anc) => {
const parent = anc[anc.length - 2];
if (n.type === 'VariableDeclaration') {
let scope;
if (n.kind === 'var') scope = [...anc].reverse().find(a => FN.has(a.type) || a.type === 'Program');
else scope = /^(For|ForIn|ForOf)Statement$/.test(parent.type) ? parent : parent.type === 'SwitchCase' ? anc[anc.length - 3] : parent;
for (const d of n.declarations) for (const id of names(d.id, [])) bind(scope, id, n);
if (n.kind === 'const') decls.push(n);
}
if (FN.has(n.type)) { for (const p of n.params) for (const id of names(p, [])) bind(n, id, null); if (n.id && n.type === 'FunctionExpression') bind(n, n.id, null); }
if (n.type === 'FunctionDeclaration' && n.id) bind(parent.type === 'SwitchCase' ? anc[anc.length - 3] : parent, n.id, null);
if (n.type === 'CatchClause' && n.param) for (const id of names(n.param, [])) bind(n, id, null);
});
// 2. assignment targets -> the declaration they resolve to
const hit = new Set(), resolve = (id, anc) => { for (let i = anc.length - 1; i >= 0; i--) { const m = scopes.get(anc[i]); if (m && m.has(id.name)) return m.get(id.name); } return undefined; };
walk.fullAncestor(ast, (n, _s, anc) => {
let targets = [];
if (n.type === 'AssignmentExpression') targets = names(n.left, []);
else if (n.type === 'UpdateExpression') targets = names(n.argument, []);
else if ((n.type === 'ForOfStatement' || n.type === 'ForInStatement') && n.left.type !== 'VariableDeclaration') targets = names(n.left, []);
for (const id of targets) { const d = resolve(id, anc); if (d) hit.add(d); }
});
const safe = decls.filter(d => !hit.has(d) && !keep(src.slice(d.start, d.end + 4)));
let out = src;
for (const d of safe.sort((a, b) => b.start - a.start)) {
if (out.slice(d.start, d.start + 5) !== 'const') throw new Error('const2let: offset');
out = out.slice(0, d.start) + 'let' + out.slice(d.start + 5);
}
return { out, count: safe.length, kept: decls.length - safe.length };
}Fixes M4
A JavaScript module in the lineage folder of GridAtlas. It is built from the fixes step (`fixes`).
transformgridatlas / tools/lightning/lineage/fixes-m4.mjs · lines 1–17 of 17 · Not reached from any entry point (candidate for review)
- What it does
- It calculates its inputs. Defines fixes.
- 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.
- Downstream impact
- Used directly by 1 file: Build M4 (gridatlas).
- What it achieves
- Review fixes folded into M4 (called by `build-M4.mjs` with its exact-once `once`).
- Why it matters
- Imported by Build M4.
- Application
- gridatlas · tools/lightning/lineage · JavaScript module
- Uses
- none found
- Used by
- referenced by Build M4 (new URL import.meta.url)
- Produces
- fixes
- Defines here
- fixes
- 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/fixes-m4.mjs:1-17 · blob f72d42465d0b367a2079b95f7b132abfbb6d3607 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// fixes-m4.mjs: review fixes folded into M4 (called by build-M4.mjs with its exact-once `once`).
export function fixes(once) {
// M2R-camera MAJOR-2 (fix C, landscape / short map): with a map under 500 px tall and at least 300 px beside the card,
// the card docks to the right edge (c.sd) and the camera frames the free area to its left (right padding = card width
// + 32, top 60, bottom 100). Portrait and desktop are unchanged (M3 already carries L = M2R-layout F1-F3, i.e. MAJOR-1's
// screen-pixel visibility test and the forced re-frame on toggle).
once('cam-c-cpos', 'w=MN(480,k.width-16),L=k.left+(k.width-w)/2,h=c.offsetHeight||0;let b=8;',
"w=MN(480,k.width-16),sd=c.sd=k.height<500&&k.width-w>=300,L=sd?k.right-8-w:k.left+(k.width-w)/2,h=c.offsetHeight||0;c.style.marginRight=sd?'0':'auto';let b=8;");
once('cam-c-ck', 'H=C&&C.clientHeight||1e4,B=c&&(c.bb+c.offsetHeight||196)+24;if(!c||!k||f!==1&&k.every(a=>{let p=m.project(a);return p.x>=20&&p.x<=(C.clientWidth||1e4)-20&&p.y>=130&&p.y<=H-B}))return;',
'H=C&&C.clientHeight||1e4,d=c&&c.sd,B=d?100:c&&(c.bb+c.offsetHeight||196)+24,R=d?c.offsetWidth+32:40,T=d?60:150;if(!c||!k||f!==1&&k.every(a=>{let p=m.project(a);return p.x>=20&&p.x<=(C.clientWidth||1e4)-R+20&&p.y>=T-20&&p.y<=H-B}))return;');
once('cam-c-pad', 'padding:{top:150,left:40,right:40,bottom:H-150>B?B:MX(0,H-270)}', 'padding:{top:T,left:40,right:R,bottom:d?B:H-150>B?B:MX(0,H-270)}');
// M2R-l3regress MINOR M3-L1: a tap on a drawn REPD dot belongs to the engine and closes the card (as L3), but M3 kept its
// auto-switched layers on with no card. Now the tapped dot's technology is handed to the reader (it stays on, as the dot
// the reader just engaged with) and every other layer M4 switched on is released.
once('l3r-dot', 'if(!f){let rp=RP(m);if(rp.length&&m.queryRenderedFeatures(e.point,{layers:rp}).length)return;',
'if(!f){let rp=RP(m),h=rp.length&&m.queryRenderedFeatures(e.point,{layers:rp});if(h&&h.length){for(let q of h)S.ly&&S.ly.delete(q.properties&&q.properties.tech);return Ry()}');
}Layers M3 Part
A JavaScript file in the lineage folder of GridAtlas covering the Renewable Energy Planning Database (REPD) register, solar, wind and battery storage (BESS).
rendergridatlas / tools/lightning/lineage/layers-m3.part.js · lines 1–14 of 14 · Not reached from any entry point (candidate for review)
- What it does
- Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar, wind, battery storage (BESS).
- Downstream impact
- Used directly by 1 file: Build M3 (gridatlas).
- What it achieves
- M3: the REPD map layers of the listed projects --------------------------------------------------------------- The owner (28 Oct 2026, 21:39 UTC): "auto activate the REPD layers of the targeted 10 nearest projects".
- 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/layers-m3.part.js:1-14 · blob 4ac250c1b6edd7c28f7d8396c3884cce330f34f4 · 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
/* ---- M3: the REPD map layers of the listed projects ---------------------------------------------------------------
The owner (28 Oct 2026, 21:39 UTC): "auto activate the REPD layers of the targeted 10 nearest projects". Each register
tech is the id of the original's own REPD layer (solar, solar_roof, wind, bess, biomass, …; engine config "REPD (GeoJSON)").
A layer is switched exactly as a tap on its Layers checkbox would: the original #scada-ui-container input is ticked and
a bubbling "change" is dispatched, so the engine's own delegated listener syncs the fullscreen-curtain copy and runs
its handleLayerToggle (visibility + hydration), and the menu bar's document listener syncs its proxy. S.ly holds only
the layers M3 itself switched on; a layer the user already had on is never touched, and a layer the user ticks or
unticks while M3 holds it becomes the user's (bt below). */
RL='solar solar_roof wind bess biomass tidal hydrogen hydro flywheel act geothermal caes'.split(' '),
Ly=(id,on)=>{let h=Q('scada-ui-container'),b=h&&h.querySelector(`input[data-layer-id="${id}"]`);if(!b||b.disabled||!!b.checked===on)return 0;
S.lyx=1;try{b.checked=on;b.dispatchEvent(new Event('change',{bubbles:true}))}catch(e){note('REPD layer '+id+': '+msg(e))}finally{S.lyx=0}return 1},
// switch on the layers `need` names that are off, and off every layer M3 switched on that `need` no longer names
Ry=(need=[])=>{let o=S.ly||(S.ly=new Set);for(let id of[...o])if(!need.includes(id)){o.delete(id);Ly(id,false)}
for(let id of need)if(RL.includes(id)&&!o.has(id)&&Ly(id,true))o.add(id)},Make Generation M4
A JavaScript module in the lineage folder of GridAtlas that reads composition, Renewable Energy Planning Database (REPD) publication q1 and the REPD register, using SHA-256.
energy-datagridatlas / tools/lightning/lineage/make-generation-M4.mjs · lines 1–281 of 281 · Entry point · pattern countOf (shared by 2 files)
- What it does
- It loads composition, REPD publication q1 and the REPD register. Defines 12 functions or classes, including die, need, R, readBuf, readText. Uses libraries node:fs, node:path, node:crypto. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- 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. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file current.json; JSON file -composition.json; JSON file current-v5.json; JSON file live-set.json; CSV file REPD_publication_Q1_2026.csv; command-line arguments.
- Downstream impact
- It is itself an entry point (JavaScript module); no other file was found loading it.
- What it achieves
- It reads buf (`readBuf`), reads text (`readText`) and derives composition (`deriveComposition`). `make-generation.mjs` -- cut a NEW immutable candidate generation of the UK lightning implant (issue #32 §8 Step F, §12 E). Its code works with 0 MW. 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/lineage · JavaScript module
- Uses
- node:fs, node:path, node:crypto
- Used by
- none found
- Produces
- die, need, R, readBuf, readText, sha, shaLF, json, countOf, versionNum, deriveComposition, write
- Defines here
- die, need, R, readBuf, readText, sha, shaLF, json, countOf, versionNum, deriveComposition, 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/lineage/make-generation-M4.mjs:1-281 · blob 890f62acd923a12cbf83df52fc0826e88b35f2c2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · 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 implant (issue #32 §8 Step F, §12 E).
* Author: opus-generation-scaffold (Claude lane); reused by L-build/L3-build; M-build adaptation: live is now L3
* M4-build adaptation: the predecessor candidate is Build M3 (202610282215, merged on main 77fca87), live is still L3; --variant m4
* (M3 + the camera fixes; layers as M3) or m4b (owner option: only the listed sites drawn as REPD-styled dots, no Layers
* control touched, so the proof's original static negative for data-layer-id / lbl- is restored).
* M3-build adaptation: the predecessor candidate is Build M2 (202610282100, published on main fa992a6), live is still L3;
* the M2 proof already carries the 64,781 B / 500 kB lines, so only GEN changes in the proof.
* M2-build adaptation (500 kB gate, module cap 64,781 B): the predecessor candidate is Build M (202610281950) while the live pointer stays L3 (202610281340);
* both lineages are proven (L3 cartridge = BASE + "\n" + L3 module, M cartridge = BASE + "\n" + M module).
* (atlas/current.json = 202610281340), so CAND = LIVE_PTR = 202610281340 while the cartridge BASE bytes stay the original
* 202609241334 sld-sandbox (the L3 cartridge is proven to be BASE + "\n" + L3 module before anything is written).
*
* node make-generation.mjs --repo <worktree> --module <fixed-module.js> --gen <YYYYMMDDHHMM> --version v9.159
* [--proof-budget <24001..24781>]
*
* --proof-budget is OPT-IN. The predecessor proof asserts module <= 24,000 bytes (proof line 23) while the real ceiling is
* 24,781 (460,000 - 435,218 live sld-sandbox - 1 newline). The unmodified module is 23,973 bytes: 27 bytes of headroom
* under the proof. Without the flag a module over 24,000 bytes is refused; with it, exactly that one proof line changes.
*
* Writes SIX new files inside <worktree> and nothing else (every write uses flag 'wx', so an existing file is never
* overwritten):
* atlas/modules/<GEN>-uk-lightning-overlay.js the module (restamped 202610261949 -> GEN in its two identity tokens)
* atlas/cartridges/<GEN>-sld-sandbox-v9-8.js LIVE 202609241334 sld-sandbox bytes + "\n" + module
* tools/proofs/<GEN>-sld-sandbox.proof.mjs 202610261949 proof with only `const GEN=` changed (module path follows GEN)
* atlas/manifests/<GEN>-composition.json 202610261949 manifest re-identified (see deriveComposition)
* atlas/v/<GEN>/index.html byte copy of atlas/index.html
* atlas/v/<GEN>/current.json 202610261949 route current.json re-identified, ../../ paths
*
* Deterministic: output depends only on the inputs (cut_at_utc is derived from GEN, not the clock).
* Protected files (issue §2) and every 202610261949 file are hashed before and after; any change aborts with exit 1.
*/
import fs from 'node:fs';
import path from 'node:path';
import {createHash} from 'node:crypto';
const CAND = '202610282215'; // M4-build: predecessor is the candidate Build M3 (not live)
const PREV_CAND = '202610282100'; // M3's own candidate_predecessor (Build M2)
const LIVE_PTR = '202610281340'; // atlas/current.json generation (live since 28 Oct 18:53 UTC)
const LIVE = '202609241334'; // the ORIGINAL sld-sandbox generation; its bytes stay the base
const LIVE_SLD = `atlas/cartridges/${LIVE}-sld-sandbox-v9-8.js`;
const LIVE_SLD_SHA = '7812953671d8bb22a566de5e98fd3137da2d23411c5aecd526df5afa111ca4ca';
const PROOF_BUDGET = 24000; // asserted by tools/proofs/202610261949-sld-sandbox.proof.mjs:23
const HARD_CEILING = 64781; // 500,000 - 435,218 - 1 (owner raised the cartridge gate to 500 kB, 28 Oct 2026 20:51 UTC)
const CARTRIDGE_CEILING = 500000; // tools/scope/loop.mjs:194 (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); };
/* ---------- arguments ---------- */
const args = {};
for (let i = 2; i < process.argv.length; i += 2) {
const k = process.argv[i], v = process.argv[i + 1];
need(/^--(repo|module|gen|version|proof-budget|variant)$/.test(k) && v !== undefined, `bad argument ${k}`);
args[k.slice(2)] = v;
}
for (const k of ['repo', 'module', 'gen', 'version']) need(args[k], `--${k} is required`);
const REPO = path.resolve(args.repo), GEN = args.gen, VERSION = args.version, VARIANT = args.variant || 'm4';
need(VARIANT === 'm4' || VARIANT === 'm4b', '--variant must be m4 or m4b');
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(GEN > CAND, `--gen ${GEN} must advance beyond the predecessor candidate ${CAND}`);
need(/^v9\.\d+$/.test(VERSION), `--version must look like v9.N, got ${VERSION}`);
const MODULE_BUDGET = args['proof-budget'] === undefined ? PROOF_BUDGET : Number(args['proof-budget']);
need(Number.isInteger(MODULE_BUDGET) && MODULE_BUDGET >= PROOF_BUDGET && MODULE_BUDGET <= HARD_CEILING,
`--proof-budget must be an integer in ${PROOF_BUDGET}..${HARD_CEILING}`);
const R = (p) => path.join(REPO, 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');
/* The loader and lint hash the PUBLISHED (LF) bytes: tools/scope/lib.mjs:195-203 sha256PublishedFile. */
const shaLF = (buf) => sha(Buffer.from(buf.toString('binary').replace(/\r\n/g, '\n'), 'binary'));
const json = (obj) => JSON.stringify(obj, null, 1) + '\n'; // the format of every 202610261949 JSON file (verified)
const countOf = (hay, needle) => hay.split(needle).length - 1;
need(fs.existsSync(R('atlas/current.json')) && fs.existsSync(R('tools/scope/loop.mjs')), `${REPO} is not a gridatlas worktree`);
/* ---------- version: must be unused anywhere in the composition record ---------- */
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)))
];
const versionNum = (v) => Number(v.split('.')[1]);
let maxUsed = 0;
for (const p of versionFiles) {
const text = readText(p);
need(!new RegExp(`"${VERSION.replace('.', '\\.')}"`).test(text) && !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]));
}
/* v9.157 was burned by the rolled-back V1 (atlas/manifests/202610221600-composition.json); it is caught by the scan. */
need(versionNum(VERSION) > maxUsed, `${VERSION} does not advance beyond the highest recorded version v9.${maxUsed}`);
/* ---------- outputs must not exist (immutability) ---------- */
const OUT = {
module: `atlas/modules/${GEN}-uk-lightning-overlay.js`,
cartridge: `atlas/cartridges/${GEN}-sld-sandbox-v9-8.js`,
proof: `tools/proofs/${GEN}-sld-sandbox.proof.mjs`,
manifest: `atlas/manifests/${GEN}-composition.json`,
routeIndex: `atlas/v/${GEN}/index.html`,
routeCurrent: `atlas/v/${GEN}/current.json`
};
for (const p of Object.values(OUT)) need(!fs.existsSync(R(p)), `${p} already exists; generations are immutable, pick a new --gen`);
/* ---------- protected set: hashed before, re-hashed after ---------- */
const live = JSON.parse(readText('atlas/current.json'));
need(live.generation === LIVE_PTR, `atlas/current.json generation is ${live.generation}, expected the live ${LIVE_PTR}`);
const liveSldEntry = live.cartridges.find(c => c.id === 'sld-sandbox');
need(liveSldEntry && liveSldEntry.path === `./cartridges/${LIVE_PTR}-sld-sandbox-v9-8.js` && liveSldEntry.generation === LIVE_PTR, `live sld-sandbox entry does not name the ${LIVE_PTR} cartridge`);
const PROTECTED = [
'atlas/current.json', 'STATE.md', 'atlas/index.html', `atlas/manifests/${LIVE}-composition.json`, LIVE_SLD,
'releases/current-v5.json', 'state/live-set.json',
...live.cartridge_order.map(id => 'atlas/' + live.cartridges.find(c => c.id === id).path.replace(/^\.\//, '')),
`atlas/modules/${CAND}-uk-lightning-overlay.js`, `atlas/cartridges/${CAND}-sld-sandbox-v9-8.js`,
`tools/proofs/${CAND}-sld-sandbox.proof.mjs`, `atlas/manifests/${CAND}-composition.json`,
`atlas/v/${CAND}/index.html`, `atlas/v/${CAND}/current.json`,
`atlas/modules/${LIVE_PTR}-uk-lightning-overlay.js`, `atlas/cartridges/${LIVE_PTR}-sld-sandbox-v9-8.js`,
`tools/proofs/${LIVE_PTR}-sld-sandbox.proof.mjs`, `atlas/manifests/${LIVE_PTR}-composition.json`,
`atlas/v/${LIVE_PTR}/index.html`, `atlas/v/${LIVE_PTR}/current.json`
];
const before = Object.fromEntries(PROTECTED.map(p => [p, sha(readBuf(p))]));
/* ---------- 1. module ---------- */
let moduleText = fs.readFileSync(path.resolve(args.module), 'utf8');
need(Buffer.from(moduleText, 'utf8').equals(fs.readFileSync(path.resolve(args.module))), 'module is not valid UTF-8');
need(!moduleText.includes('\r'), 'module contains CR; supply LF-only bytes (the proof hashes raw bytes, the loader hashes LF)');
const restamped = [];
for (const [from, to] of [[`generation ${CAND}`, `generation ${GEN}`], [`GEN='${CAND}'`, `GEN='${GEN}'`]]) {
if (moduleText.includes(to)) continue; // already stamped by the caller
need(countOf(moduleText, from) === 1, `module must carry exactly one ${JSON.stringify(from)} or ${JSON.stringify(to)}`);
moduleText = moduleText.replace(from, to);
restamped.push(`${from} -> ${to}`);
}
const moduleBuf = Buffer.from(moduleText, 'utf8');
need(moduleBuf.length <= MODULE_BUDGET, `module is ${moduleBuf.length} bytes; the proof budget is ${MODULE_BUDGET}`
+ (MODULE_BUDGET === PROOF_BUDGET ? ` (pass --proof-budget <=${HARD_CEILING} to raise it in the new proof only)` : ''));
/* ---------- 2. cartridge = LIVE bytes + "\n" + module ---------- */
const baseBuf = readBuf(LIVE_SLD);
need(sha(baseBuf) === LIVE_SLD_SHA, `${LIVE_SLD} is not the pinned live bytes`);
/* lineage: the live L3 cartridge (sha in atlas/current.json) is exactly BASE + "\n" + the L3 module */
need(shaLF(readBuf(`atlas/cartridges/${LIVE_PTR}-sld-sandbox-v9-8.js`)) === liveSldEntry.sha256, 'live L3 cartridge does not match atlas/current.json');
for (const g of [LIVE_PTR, CAND]) need(readBuf(`atlas/cartridges/${g}-sld-sandbox-v9-8.js`).equals(Buffer.concat([baseBuf, Buffer.from('\n'), readBuf(`atlas/modules/${g}-uk-lightning-overlay.js`)])), `${g} cartridge is not BASE + \\n + its module`);
need(JSON.parse(readText(`atlas/v/${CAND}/current.json`)).cartridges.find(c => c.id === 'sld-sandbox').sha256 === shaLF(readBuf(`atlas/cartridges/${CAND}-sld-sandbox-v9-8.js`)), 'M route current.json does not pin the M cartridge');
need(!baseBuf.includes(13), `${LIVE_SLD} contains CR`);
const cartridgeBuf = Buffer.concat([baseBuf, Buffer.from('\n'), moduleBuf]);
need(cartridgeBuf.length <= CARTRIDGE_CEILING, `cartridge is ${cartridgeBuf.length} bytes; ceiling ${CARTRIDGE_CEILING}`);
const cartridgeSha = shaLF(cartridgeBuf);
need(cartridgeSha === sha(cartridgeBuf), 'raw and LF hashes differ (CR present)');
/* ---------- 3. proof: only `const GEN=` changes; the module path is 'atlas/modules/'+GEN+... ---------- */
const candProof = readText(`tools/proofs/${CAND}-sld-sandbox.proof.mjs`);
need(countOf(candProof, CAND) === 1 && countOf(candProof, `const GEN='${CAND}';`) === 1,
'predecessor proof no longer has exactly one generation literal; re-derive by hand');
need(candProof.includes("'atlas/modules/'+GEN+'-uk-lightning-overlay.js'"), 'predecessor proof module path is not GEN-derived');
let proofText = candProof.replace(`const GEN='${CAND}';`, `const GEN='${GEN}';`);
const BUDGET_64 = "assert.ok(Buffer.byteLength(module,'utf8')<=64781,'module exceeds the 64,781-byte budget');";
const CART_500 = "assert.ok(Buffer.byteLength(source,'utf8')<=500000,'cartridge exceeds the 500 kB ceiling (raised from 480 kB by the owner, 28 Oct 2026)');";
need(countOf(proofText, BUDGET_64) === 1 && countOf(proofText, CART_500) === 1 && MODULE_BUDGET === HARD_CEILING, 'predecessor proof 64,781 B / 500 kB lines changed; re-derive by hand');
/* M4 keeps M3's proof as it is (the module still ticks the REPD layer checkboxes: the narrowed negative and the three
read-site assertions). M4b names no such control, so its proof restores the original negative (data-layer-id and lbl-
banned outright) and drops the M3 read-site comment and assertions. */
const NEG_OLD = "const negatives=/ukConfig|initVentusMap|window\\.fetch|data-layer-id|data-pn-layer|data-gridatlas-layer-proxy|data-gridatlas-layer-key|prepend\\(|lbl-|name=[\"']bm|<style|createElement\\(['\"]style|localStorage|sessionStorage|document\\.cookie/;";
const NEG_M3 = "const negatives=/ukConfig|initVentusMap|window\\.fetch|data-pn-layer|data-gridatlas-layer-proxy|data-gridatlas-layer-key|prepend\\(|name=[\"']bm|<style|createElement\\(['\"]style|localStorage|sessionStorage|document\\.cookie/;";
const M3_SITES = ["/* M3: the REPD layer checkboxes", "assert.deepEqual(module.match(/data-layer-id|lbl-/g)", "assert.equal((module.match(/input", "assert.equal(/setAttribute"];
need(countOf(proofText, NEG_M3) === 1 && M3_SITES.every(a => proofText.split('\n').filter(l => l.startsWith(a)).length === 1), 'predecessor (M3) proof negatives changed; re-derive by hand');
if (VARIANT === 'm4b') {
proofText = proofText.split('\n').filter(l => !M3_SITES.some(a => l.startsWith(a))).join('\n').replace(NEG_M3, NEG_OLD);
need(countOf(proofText, NEG_OLD) === 1 && !proofText.includes('M3: the REPD layer'), 'm4b proof: original negative not restored');
need(!/data-layer-id|lbl-/.test(moduleText), 'm4b module names data-layer-id or lbl-');
}
/* ---------- 4/5. composition manifest and route current.json ---------- */
function deriveComposition(src, prefix, kind) {
const c = structuredClone(src);
const oldVersion = c.composition_version;
need(c.generation === CAND && c.previous_generation === LIVE_PTR && c.candidate_predecessor === PREV_CAND, `${kind}: predecessor identity changed`);
c.generation = GEN;
c.previous_generation = LIVE_PTR; // the live pointer this candidate would replace (L3)
c.composition_manifest = `${prefix}manifests/${GEN}-composition.json`;
c.composition_version = VERSION;
c.composition_id = `${GEN}-gridatlas-${VERSION}`;
need(c.superseded_generation === LIVE_PTR, `${kind}: superseded_generation is not ${LIVE_PTR}`);
c.superseded_generation = LIVE_PTR;
c.candidate_predecessor = CAND; // honest lineage: built on candidate M2; it would replace the live L3
if (typeof c.composition_note === 'string' && c.composition_note.startsWith(`${oldVersion}:`))
c.composition_note = VERSION + c.composition_note.slice(oldVersion.length);
for (const [a, b] of (VARIANT === 'm4b' ? NOTE : [])) { need(countOf(c.composition_note, a) === 1, `${kind}: note anchor ${a}`); c.composition_note = c.composition_note.replace(a, b); }
const sld = c.cartridges.find(x => x.id === 'sld-sandbox');
need(sld && sld.generation === CAND && sld.derived_from === `${prefix}cartridges/${LIVE}-sld-sandbox-v9-8.js`,
`${kind}: sld-sandbox entry is not derived from the live ${LIVE} cartridge`);
sld.generation = GEN;
sld.version = VERSION;
sld.path = `${prefix}cartridges/${GEN}-sld-sandbox-v9-8.js`;
sld.sha256 = cartridgeSha;
sld.bytes = cartridgeBuf.length;
sld.uk_lightning.module = `${prefix}modules/${GEN}-uk-lightning-overlay.js`;
sld.uk_lightning.module_bytes = moduleBuf.length;
need(sld.uk_lightning.repd_projects === REPD_NOTE, 'repd_projects note changed (M3)');
need(typeof sld.uk_lightning.transport === 'string' && sld.uk_lightning.transport.includes('same 15 s timeout'), 'transport');
need(sld.uk_lightning.contract === M3_CONTRACT && sld.uk_lightning.repd_layers === REPD_LAYERS && typeof sld.uk_lightning.repd_source === 'object', 'M3 contract / repd_layers / repd_source changed');
need(!('camera' in sld.uk_lightning) && !('repd_dots' in sld.uk_lightning), 'camera/repd_dots already present');
sld.uk_lightning.camera = CAMERA;
if (VARIANT === 'm4b') { sld.uk_lightning.contract = M2_CONTRACT; delete sld.uk_lightning.repd_layers; sld.uk_lightning.repd_dots = REPD_DOTS; }
if (kind === 'manifest') {
need(c.parent_generation === LIVE_PTR, 'manifest parent_generation changed');
c.parent_generation = LIVE_PTR; // verify-candidate: parent is the live generation
need(c.acceptance.scope.includes('M3 (' + CAND + '):'), 'M3 scope note missing'); c.acceptance.scope += ' ' + SCOPE_NOTE;
c.version = VERSION;
c.cut_at_utc = cutAt;
c.acceptance.proof = `tools/proofs/${GEN}-sld-sandbox.proof.mjs`;
/* Repository vocabulary for "pending": tools/recompose.mjs:417, tools/rollback.mjs:222. */
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 may survive: the only 202610261949 left is candidate_predecessor, no old version anywhere. */
const want = kind === 'manifest' ? 3 : 2; // LIVE_PTR: previous_generation, superseded_generation (+ parent_generation)
need(countOf(text, `"${LIVE_PTR}"`) === want && countOf(text, `"${CAND}"`) === 1 && countOf(text, CAND) === (kind === 'manifest' ? 2 : 1) && text.includes(`"candidate_predecessor": "${CAND}"`), `${kind}: stale ${CAND} remains (${countOf(text, CAND)})`);
need(!text.includes(`"${oldVersion}"`) && !text.includes(`${oldVersion}:`) && !text.includes(`-${oldVersion}"`), `${kind}: stale ${oldVersion} remains`);
return text;
}
const REPD_NOTE = 'on a flash or cell tap, besides the 5 nearest substations: the 10 nearest REPD project sites within 40 km by straight-line distance (the original link.measure.distanceKm), a site being the projects at one registered point (rows within about 10 m of a nearer row join its site; e.g. solar + battery share one link, one label "<km> km · Battery + Solar <MW> MW" and one card row "<n> … [line shortened here: 2,091 characters; full line on GitHub]
const REPD_LAYERS = 'while a REPD list is shown, the original REPD layer of each technology in that list (within the card filter; the register tech is the layer id: solar, solar_roof, wind, bess, biomass, tidal, hydrogen, hydro, flywheel, act, geothermal, caes) is switched on exactly as a reader tap would: the #scada-ui-container checkbox is ticked and a bubbling change is dispatched, so the engin … [line shortened here: 909 characters; full line on GitHub]
const REPD_SOURCE = {
register: 'Renewable Energy Planning Database (REPD), April 2026 (Q1 2026) quarterly extract',
publisher: 'Department for Energy Security and Net Zero (DESNZ), compiled by Barbour ABI',
published: '2026-05-06 (gov.uk update history: January 2026 files replaced with April 2026, Q1)',
upstream_file: 'REPD_publication_Q1_2026.csv',
licence: 'Open Government Licence v3.0; contains public sector information licensed under the Open Government Licence v3.0',
served_as: 'partitions/repd_master_v8_oracle.parquet (sha256 a737d00d54dbee0ccb46be07f18277cb1c5c111acefbfda43f3d34ce3d53416c, 10,784 rows) in data-gridatlas manifest 3246dbda, from globalgrid2050 dist/repd_master.json (synced 2026-06-01; operational, under construction, awaiting construction, application submitted only)',
currency: 'a snapshot: DESNZ has since published July 2026 (Q2, 3 Aug 2026); rows are not refreshed by this module'
};
const M2_CONTRACT = 'no data-layer-id, data-pn-layer, data-gridatlas-layer-proxy, data-gridatlas-layer-key, lbl-* id or name=bm; menuBar.inspect() stays {60,3,63,63,true}';
const M3_CONTRACT = 'creates no data-layer-id, data-pn-layer, data-gridatlas-layer-proxy or data-gridatlas-layer-key control, lbl-* id or name=bm; reads and ticks the original REPD layer checkboxes (input[data-layer-id]) through the engine\'s own change path only while a REPD list is shown (repd_layers); menuBar.inspect() stays {60,3,63,63,true}';
const NOTE = [["the original REPD map layers of the listed technologies are switched on through their own Layers checkboxes while the list is shown, and only those the overlay switched on are switched off again),",
"only the listed sites are drawn on the map as REPD-styled dots (the engine's own glow and core paint), and the Layers controls are never touched),"]];
const CAMERA = 'a module camera move (tap, row, back, card toggle, cluster zoom, fit) first drops the module\'s pending framing, and the framing queued for the end of a flight runs after the stop that fired moveend and only when the map is not moving, so no camera move ever starts inside another (MapLibre 3.6.2 fires moveend synchronously from stop(); a nested fitBounds left an orphan render frame … [line shortened here: 729 characters; full line on GitHub]
const REPD_DOTS = 'while a REPD list is shown, each listed project (and, in the project view, that site\'s projects) is drawn at its site as a dot in the original engine REPD style (ventus-corev8engine.js:1305-1337: the solar and rooftop-solar glow by capacity, the capacity-graded core, every other technology in its own layer colour, stacked in the engine REPD layer order), in the overlay\'s own g … [line shortened here: 642 characters; full line on GitHub]
const SCOPE_NOTE = (VARIANT === 'm4b' ? 'M4b (' : 'M4 (') + GEN + '): Build M3 with the camera race fixed (M2R-taps MAJOR T1: no camera move starts inside another; fast row/back cycles no longer freeze map redraws) and M2R-camera fix C (screen-pixel framing; the card docks right on short or landscape maps)'
+ (VARIANT === 'm4b' ? '; owner option M4b: instead of switching on whole REPD layers, only the listed sites are drawn as REPD-styled dots and the Layers controls are never touched' : '; the REPD layers of the listed technologies are switched on as in M3') + '; module cap 64,781 B under the 500 kB cartridge gate.';
const manifestText = deriveComposition(JSON.parse(readText(`atlas/manifests/${CAND}-composition.json`)), './', 'manifest');
const routeText = deriveComposition(JSON.parse(readText(`atlas/v/${CAND}/current.json`)), '../../', 'route');
const indexBuf = readBuf('atlas/index.html');
/* ---------- 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);
/* ---------- post-checks ---------- */
for (const p of PROTECTED) need(sha(readBuf(p)) === before[p], `protected file changed: ${p}`);
need(readBuf(OUT.routeIndex).equals(readBuf('atlas/index.html')), 'route index.html differs from atlas/index.html');
need(readBuf(OUT.cartridge).equals(Buffer.concat([readBuf(LIVE_SLD), Buffer.from('\n'), readBuf(OUT.module)])), 'cartridge is not live + \\n + module');
const m = JSON.parse(readText(OUT.manifest)), rc = JSON.parse(readText(OUT.routeCurrent));
for (const [label, c, base] of [['manifest', m, R('atlas')], ['route', rc, R(`atlas/v/${GEN}`)]]) {
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}`);
}
}
need(JSON.stringify(m.cartridge_order) === JSON.stringify(rc.cartridge_order), 'manifest and route cartridge_order differ');
console.log(JSON.stringify({
result: 'WRITTEN', generation: GEN, version: VERSION, candidate_predecessor: CAND, parent_generation: LIVE_PTR,
module: {path: OUT.module, bytes: moduleBuf.length, sha256: sha(moduleBuf), restamped,
proof_budget: MODULE_BUDGET, headroom_to_proof_budget: MODULE_BUDGET - moduleBuf.length, headroom_to_24781: HARD_CEILING - moduleBuf.length},
cartridge: {path: OUT.cartridge, bytes: cartridgeBuf.length, sha256_lf: cartridgeSha, base: LIVE_SLD},
proof: OUT.proof, manifest: OUT.manifest, route: [OUT.routeIndex, OUT.routeCurrent],
protected_unchanged: PROTECTED.length
}, null, 1));