In this section
- Export Print and Image Outcomes Browser render · gridatlas / tools/proofs/export-print-and-image-outcomes.browser.mjs lines 701–829
- Grid Subs Chips on Desktop Browser render · gridatlas / tools/proofs/grid-subs-chips-on-desktop.browser.mjs lines 1–79
- Layer Census GPU storage · gridatlas / tools/proofs/layer-census-gpu.py lines 1–35
- Layer Census storage · gridatlas / tools/proofs/layer-census.py lines 1–61
- Lightning Cartridge render · gridatlas / tools/proofs/lightning-cartridge.mjs lines 1–152
- Loader Composition render · gridatlas / tools/proofs/loader-composition.mjs lines 1–86
- Loader Equivalence Proof render · gridatlas / tools/proofs/loader-equivalence.proof.mjs lines 1–121
Export Print and Image Outcomes Browser
A JavaScript module in the proofs folder of GridAtlas that exports control (`exportControl`), opens export menu (`openExportMenu`), calculates planar distances and draws on a canvas, using SHA-256.
rendergridatlas / tools/proofs/export-print-and-image-outcomes.browser.mjs · lines 701–829 of 829 (continued from section 653) · Not reached from any entry point (candidate for review) · pattern shape (shared by 4 files)
- What it does
- It draws its content. Defines 13 functions or classes, including argv, check, pdfFacts, number, streamOf. Uses libraries node:http, node:fs/promises, node:os, node:path, node:zlib. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file current.json; command-line arguments. Out: canvas drawing.
- What it achieves
- It exports control (`exportControl`) and opens export menu (`openExportMenu`). Its name says it exports print and image outcomes browser. Defines `argv`, `check`, `pdfFacts` and 10 more. It responds to click events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- node:http, node:fs/promises, node:os, node:path, node:zlib, node:module, node:url, playwright
- Used by
- none found
- Produces
- argv, check, pdfFacts, number, streamOf, decoded, sample, times, exportControl, shape, openExportMenu, coverageOf
- Defines here
- coverageOf, describe
- 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/proofs/export-print-and-image-outcomes.browser.mjs:701-829 · blob eb8c36e05fa2486af4b3a56668ab3ab793595a98 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* Back to screen media before anything is clicked again: the print
stylesheet hides the menu bar outright, so a control cannot be pressed
while print media is emulated. Page.printToPDF applies print media
itself, so nothing is lost. */
await page.emulateMedia({ media: null });
await page.waitForTimeout(300);
/* B + C. The artefact itself. */
const session = await context.newCDPSession(page);
receipt.pdf = {};
for (const paper of PAPERS) {
/* PRINT IS INVOKED AGAIN FOR EACH SHEET, because that is what a reader
does and because the export overlays are TEMPORARY: printView()
removes them 20 seconds after the click, and generating three PDFs of
a page this heavy takes longer than that. Measuring the second and
third sheets against overlays the app had already cleaned up would be
a driver artefact reported as a product failure -- the same class of
mistake this file was rewritten to remove. */
await openExportMenu(`print for ${paper.name}`);
await printControl.locator.click({ timeout: 10000 });
await page.waitForTimeout(1200);
const overlays = await page.evaluate(() => ({
furniture: document.querySelectorAll('#gridatlas-print-furniture').length,
capturedMap: document.querySelectorAll('#gridatlas-print-map').length
}));
check(`${viewport.name} / ${paper.name}: the print overlays are on the page, exactly once each`,
overlays.furniture === 1 && overlays.capturedMap === 1,
`${overlays.furniture} furniture node(s), ${overlays.capturedMap} captured-map node(s)`);
const options = { printBackground: true, preferCSSPageSize: paper.preferCSSPageSize };
if (paper.paperWidth) { options.paperWidth = paper.paperWidth; options.paperHeight = paper.paperHeight; }
const { data } = await session.send('Page.printToPDF', options);
const facts = pdfFacts(data);
receipt.pdf[paper.name] = facts;
const sheet = facts.pagePt;
const coverageOf = (image) => (image && image.placed && sheet)
? {
width: Number((image.placed.widthPt / sheet.width).toFixed(3)),
height: Number((image.placed.heightPt / sheet.height).toFixed(3))
}
: null;
for (const image of facts.images) image.coverage = coverageOf(image);
/* THE QUESTION IS NOT "IS THE LARGEST IMAGE THE MAP".
The printed page carries more than one large raster -- the live
canvas among them -- and asking about the largest one lets a blank
rectangle answer for the map. So the page is asked whether ANY image
on it is a picture of the map: big enough not to be an icon, laid
out to fill the sheet, carrying more than one colour, and not hidden
behind an alpha mask. If one such image exists, the reader sees a
map. If none does, the sheet is blank however many images are on it. */
const graded = facts.images.map(image => {
const content = image.content || {};
const coverage = image.coverage;
return {
image,
bigEnough: image.width >= 200 && image.height >= 200,
fills: Boolean(coverage)
&& Math.max(coverage.width, coverage.height) >= FILLS_ONE_DIRECTION
&& coverage.width <= NO_OVERFLOW && coverage.height <= NO_OVERFLOW,
varied: (content.distinct || 0) >= MIN_DISTINCT
&& content.dominantShare !== undefined && content.dominantShare < MAX_DOMINANT,
visible: !image.smask
|| (image.smask.nonZeroShare !== undefined && image.smask.nonZeroShare >= MIN_VISIBLE)
};
});
const describe = (row) => {
const content = row.image.content || {};
const coverage = row.image.coverage;
return `#${row.image.id} ${row.image.width}x${row.image.height}px`
+ ` placed ${coverage ? `${coverage.width}x${coverage.height}` : 'nowhere'} of the sheet,`
+ ` ${content.distinct === undefined ? content.unread : `${content.distinct} distinct/${content.sampled} sampled`}`
+ `, dominant ${content.dominantShare}`
+ (row.image.smask ? `, alpha non-zero ${row.image.smask.nonZeroShare}` : ', no mask');
};
const mapLike = graded.filter(row => row.bigEnough && row.fills);
const printed = mapLike.filter(row => row.varied && row.visible);
facts.verdict = {
images: graded.length,
big_and_filling_the_sheet: mapLike.length,
carrying_visible_map_pixels: printed.length
};
check(`${viewport.name} / ${paper.name}: the PDF contains a rasterised map`,
facts.imageCount >= 1, `${facts.imageCount} image XObjects (masks excluded) in ${facts.bytes} bytes`);
check(`${viewport.name} / ${paper.name}: an image the size of the sheet is on the page, not just an icon`,
mapLike.length >= 1,
graded.length
? graded.map(describe).join(' | ')
: 'no image XObject at all');
check(`${viewport.name} / ${paper.name}: that image carries visible map pixels, not one flat colour behind an empty mask`,
printed.length >= 1,
mapLike.length
? mapLike.map(describe).join(' | ')
+ ` [floors: ${MIN_DISTINCT} distinct, dominant < ${MAX_DOMINANT}, alpha >= ${MIN_VISIBLE}]`
: 'no sheet-sized image to inspect');
check(`${viewport.name} / ${paper.name}: the slide is one page`,
facts.pages === 1, `${facts.pages} pages`);
}
await session.detach().catch(() => { /* the context is closing anyway */ });
await page.emulateMedia({ media: null });
await context.close();
}
} finally {
/* Own every child. A browser or a listening socket left behind is a defect
of this harness, not an inconvenience. */
await browser.close().catch(() => { /* already gone */ });
for (const socket of sockets) socket.destroy();
await new Promise(resolve => server.close(resolve));
}
console.log(`route under test: ${ROUTE}`);
console.log(`generation under test: ${GENERATION}`);
console.log(`export cartridge: ${receipts.export_cartridge}`);
console.log(`export cartridge sha256: ${receipts.export_cartridge_sha256}`);
console.log(JSON.stringify(receipts, null, 2));
let failed = 0;
for (const entry of checks) {
if (!entry.ok) failed += 1;
console.log(`${entry.ok ? 'PASS' : 'FAIL'} ${entry.name}${entry.detail ? ` [${entry.detail}]` : ''}`);
}
console.log(`\n${checks.length - failed}/${checks.length} export outcome checks passed`);
if (RECEIPT_OUT) {
await writeFile(path.resolve(RECEIPT_OUT),
`${JSON.stringify({ route: ROUTE, generation: GENERATION, receipts, checks }, null, 2)}\n`, 'utf8');
}
if (failed) console.error(`${failed} export outcome check(s) failed`);
/* Explicit, so a stray handle cannot keep this process alive after the work
is done and the receipts are written. */
process.exit(failed ? 1 : 0);Grid Subs Chips on Desktop Browser
A JavaScript module in the proofs folder of GridAtlas.
rendergridatlas / tools/proofs/grid-subs-chips-on-desktop.browser.mjs · lines 1–79 of 79 · Not reached from any entry point (candidate for review)
- What it does
- It lists and searches its content. Uses libraries playwright. Side effects: changes the web page (DOM); 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
- ARE GRID AND SUBS UNDER THE CURSOR, NOT INSIDE A MENU? --------------------------------------------------------------------------- "in mobile view the Grid and subs buttons are nice show them on desktop TOO" -- the architect, .
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- playwright
- Used by
- none found
- 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/proofs/grid-subs-chips-on-desktop.browser.mjs:1-79 · blob 4a055348c530e2eb9cc7799c10725688d3159154 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
* ARE GRID AND SUBS UNDER THE CURSOR, NOT INSIDE A MENU?
* ---------------------------------------------------------------------------
* "in mobile view the Grid and subs buttons are nice show them on desktop TOO"
* -- the architect, 2026-09-05.
*
* These two chips were deliberately phone-only. The reasoning is on the record
* and it was sound: the grid-line and substation switches live in a panel below
* the map "which a phone never scrolls to; activation looked broken", so on a
* touch screen the chips stay on the map. On desktop they were routed into the
* menu because a menu is always one click away.
*
* That last step is the one being reversed. GRID and SUBS are the two layers a
* reader toggles most often, and a control used that often belongs under the
* cursor. This proof fails while they are reachable only through a menu.
*
* node tools/proofs/grid-subs-chips-on-desktop.browser.mjs <base-url>
*/
import { chromium } from 'playwright';
const BASE = process.argv[2];
if (!BASE) { console.error('usage: <base-url>'); process.exit(2); }
const VIEWPORTS = [
{ name: '1400x900 desktop', width: 1400, height: 900 },
{ name: '2327x1156 ultrawide', width: 2327, height: 1156 },
{ name: '393x852 phone (must not regress)', width: 393, height: 852 }
];
const rows = [];
const browser = await chromium.launch({ headless: true });
try {
for (const viewport of VIEWPORTS) {
const context = await browser.newContext({ viewport });
const page = await context.newPage();
try {
await page.goto(BASE, { waitUntil: 'domcontentloaded', timeout: 90000 });
await page.locator('#gridatlas-menu-bar').waitFor({ timeout: 90000 });
await page.waitForTimeout(1500);
/* Measured by BOX, not by presence in the DOM: a chip that exists inside
a closed menu panel is exactly the state this proof exists to reject. */
const chips = await page.evaluate(() => {
/* The chips are '⚡ Grid' and '◉ Subs' -- a leading symbol,
then the word. Matching on the word with any leading symbol is what
this needs; an earlier version anchored on ⚡ alone and therefore
never saw Subs at all, and reported a red that was its own.
'Grid At Point' is a different control and is excluded by name. */
const wanted = /^[^A-Za-z0-9]*\s*(grid|subs)\s*$/i;
return Array.from(document.querySelectorAll('button,[role=button]'))
.map(node => ({
text: (node.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 24),
rect: node.getBoundingClientRect(),
/* The menu bar's own GRID title is a button reading exactly
"Grid" and it is NOT in a panel, so without this it counts as a
chip on the map and this proof goes green while the chip is
still buried in a menu -- passing for the wrong reason, which
is worse than failing. */
inMenu: !!(node.closest('.gm-panel') || node.closest('.gm-title')
|| node.classList.contains('gm-title')
|| node.closest('#gridatlas-menu-bar'))
}))
.filter(item => wanted.test(item.text))
.map(item => ({
text: item.text,
onMap: item.rect.width > 0 && item.rect.height > 0 && !item.inMenu,
inMenu: item.inMenu
}));
});
const onMap = chips.filter(c => c.onMap).map(c => c.text);
const ok = onMap.some(t => /grid/i.test(t)) && onMap.some(t => /subs/i.test(t));
rows.push({ view: viewport.name, ok, detail: `on the map: [${onMap.join(', ')}]` });
console.log(`${ok ? 'PASS' : 'FAIL'} ${viewport.name} on the map: [${onMap.join(', ')}]`);
} finally { await context.close().catch(() => {}); }
}
} finally { await browser.close().catch(() => {}); }
const failed = rows.filter(r => !r.ok);
console.log(`\n${rows.length - failed.length} passed, ${failed.length} failed, ${rows.length} checks`);
if (failed.length) process.exit(1);Layer Census GPU
A Python module in the proofs folder of GridAtlas that reads GPU receipt, using SHA-256. It is built from the gpu step (`gpu`).
storagegridatlas / tools/proofs/layer-census-gpu.py · lines 1–35 of 35 · Not reached from any entry point (candidate for review)
- What it does
- It loads GPU receipt. Defines gpu. Uses libraries argparse, hashlib, json, pathlib, time. 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.
- Inputs & outputs
- In: command-line arguments. Out: JSON file gpu-receipt.json.
- What it achieves
- Bounded CuPy geometry and filter census, independently checked against scalar CPU masks. It accepts `--input`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/proofs · Python module
- Uses
- argparse, hashlib, json, pathlib, time, cupy, numpy
- Used by
- none found
- Produces
- none declared
- Defines here
- gpu
- 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/proofs/layer-census-gpu.py:1-35 · blob b76e56e732cc6ce3be9514dec53fee23201c3d7c · 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
"""Bounded CuPy geometry and filter census, independently checked against scalar CPU masks."""
import argparse,hashlib,json,pathlib,time
import cupy as cp
import numpy as np
p=argparse.ArgumentParser();p.add_argument('--input',default='work/layer-census');a=p.parse_args();root=pathlib.Path(a.input)
manifest=json.loads((root/'manifest.json').read_text());assert hashlib.sha256((root/'inputs.npz').read_bytes()).hexdigest()==manifest['input_sha256']
data=np.load(root/'inputs.npz');started=time.perf_counter();results=[]
for layer in manifest['layers']:
prefix=layer['id'];vocab=layer['vocabulary']
def gpu(e):
if not isinstance(e,list):return e
op,*args=e
if op in ['all','any']:
masks=[gpu(x) for x in args];answer=masks[0]
for mask in masks[1:]:answer=answer & mask if op=='all' else answer | mask
return answer
if op=='!':return ~gpu(args[0])
if op in ['==','!=']:
key=args[0][1];codes=cp.asarray(data[prefix+'_'+key]);dictionary=vocab[key]
target=args[1] if dictionary is None else dictionary.index(args[1]) if args[1] in dictionary else -1
return codes==target if op=='==' else codes!=target
if op=='in':
needle=args[0];key=args[1][1];dictionary=vocab[key]
allowed=cp.asarray([i for i,v in enumerate(dictionary) if v is not None and needle in v],dtype=cp.int32)
return cp.isin(cp.asarray(data[prefix+'_'+key]),allowed)
raise ValueError('unsupported real layer filter '+op)
mask=cp.asarray(data[prefix+'_geometry'])==layer['expected_geometry']
if layer['filter']:mask &= gpu(layer['filter'])
got=cp.asnumpy(mask);expected=data[prefix+'_cpu'];diff=int(np.count_nonzero(got!=expected));assert diff==0,(prefix,diff)
assert got.any(),(prefix,'no geometry-compatible features satisfy the layer filter')
results.append({'id':prefix,'examined':len(got),'eligible':int(got.sum()),'cpu_gpu_differences':diff})
xy=cp.asarray(data['coordinates']);invalid=int(cp.count_nonzero(~cp.isfinite(xy)).get());outside=int(cp.count_nonzero((cp.abs(xy[:,0])>180)|(cp.abs(xy[:,1])>90)).get());assert invalid==outside==0
cp.cuda.Stream.null.synchronize()
receipt={'status':'passed','gpu':cp.cuda.runtime.getDeviceProperties(0)['name'].decode(),'cupy':cp.__version__,'input_sha256':manifest['input_sha256'],'script_sha256':hashlib.sha256(pathlib.Path(__file__).read_bytes()).hexdigest(),'layers':results,'coordinates':len(xy),'invalid_values':invalid,'out_of_range_coordinates':outside,'elapsed_seconds':time.perf_counter()-started,'scope':'Real published … [line shortened here: 610 characters; full line on GitHub]
(root/'gpu-receipt.json').write_text(json.dumps(receipt,indent=2));print(json.dumps(receipt,indent=2))Layer Census
A Python module in the proofs folder of GridAtlas that prepares the real published layer corpus for CPU/GPU parity; never synthesize cases, using SHA-256.
storagegridatlas / tools/proofs/layer-census.py · lines 1–61 of 61 · Not reached from any entry point (candidate for review) · pattern coordinates (shared by 3 files)
- What it does
- It loads data. Defines value, coordinates, gather. Uses libraries argparse, collections, hashlib, json, pathlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file layer-config.json; command-line arguments.
- What it achieves
- Defines `value`, `coordinates` and `gather`. It accepts `--data-root`, `--config` and `--out`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/proofs · Python module
- Uses
- argparse, collections, hashlib, json, pathlib, numpy, pyarrow.parquet
- Used by
- none found
- Produces
- value, coordinates
- Defines here
- value, coordinates, gather
- 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/proofs/layer-census.py:1-61 · blob 74043f414d480ddc8bbbf2b67ae9ed440a3bbbd8 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
"""Prepare the real published layer corpus for CPU/GPU parity; never synthesize cases."""
import argparse, collections, hashlib, json, pathlib
import numpy as np
import pyarrow.parquet as pq
p=argparse.ArgumentParser();p.add_argument('--data-root',required=True);p.add_argument('--config',default='work/layer-config.json');p.add_argument('--out',default='work/layer-census');a=p.parse_args()
root=pathlib.Path(a.data_root);out=pathlib.Path(a.out);out.mkdir(parents=True,exist_ok=True)
manifest=json.loads((root/'manifest.json').read_text());artifacts={x['path']:x for x in manifest['artifacts']}
layers=[l for g in json.loads(pathlib.Path(a.config).read_text()) for l in g['layers']]
GEOM={'Point':1,'MultiPoint':1,'LineString':2,'MultiLineString':2}
def value(e,props):
if not isinstance(e,list):return e
op,*args=e
if op=='get':return props.get(args[0])
if op=='literal':return args[0]
if op=='coalesce':return next((v for x in args if (v:=value(x,props)) is not None),None)
if op=='all':return all(value(x,props) for x in args)
if op=='any':return any(value(x,props) for x in args)
if op=='!':return not value(args[0],props)
if op=='==':return value(args[0],props)==value(args[1],props)
if op=='!=':return value(args[0],props)!=value(args[1],props)
if op=='in':return value(args[0],props) in (value(args[1],props) or '')
if op=='>=':return (value(args[0],props) or 0)>=value(args[1],props)
raise ValueError(op)
def coordinates(c):
if c and isinstance(c[0],(int,float)):yield c[:2]
else:
for item in c:yield from coordinates(item)
cache={};descriptors=[];arrays={};coord_groups=[]
for layer in layers:
name=layer['url'].rsplit('/',1)[-1].removesuffix('.geojson').removesuffix('.json')
name={'repd_master':'repd_master_v8_oracle','uk_metros_trams':'uk_metros_trams_local_unwired'}.get(name,name)
artifact=artifacts['partitions/'+name+'.parquet'];file=root/artifact['path']
assert hashlib.sha256(file.read_bytes()).hexdigest()==artifact['sha256'],file
if name not in cache:
rows=pq.read_table(file).to_pylist();features=[{'geometry':json.loads(r['geometry_json']),'properties':json.loads(r['properties_json'])} for r in rows]
cache[name]=features
coord_groups.extend([xy for f in features for xy in coordinates(f['geometry']['coordinates'])])
features=cache[name];prefix=layer['id'];expected_geom=2 if layer['type']=='line' else 1
geom=np.array([GEOM.get(f['geometry']['type'],0) for f in features],dtype=np.int8)
expected=np.array([GEOM.get(f['geometry']['type'],0)==expected_geom and (not layer.get('filter') or value(layer['filter'],f['properties'])) for f in features],dtype=np.bool_)
arrays[prefix+'_geometry']=geom;arrays[prefix+'_cpu']=expected
keys=set()
def gather(e):
if isinstance(e,list):
if e[0]=='get':keys.add(e[1])
for v in e[1:]:gather(v)
gather(layer.get('filter'));vocab={}
for key in keys:
values=[f['properties'].get(key) for f in features]
if all(v is None or isinstance(v,(int,float)) for v in values):arrays[prefix+'_'+key]=np.array([np.nan if v is None else v for v in values]);vocab[key]=None
else:
dictionary=list(dict.fromkeys(values));lookup={v:i for i,v in enumerate(dictionary)}
arrays[prefix+'_'+key]=np.array([lookup[v] for v in values],dtype=np.int32);vocab[key]=dictionary
descriptors.append({'id':prefix,'source':name,'sha256':artifact['sha256'],'features':len(features),'expected_geometry':expected_geom,'filter':layer.get('filter'),'vocabulary':vocab,'eligible_cpu':int(expected.sum())})
arrays['coordinates']=np.asarray(coord_groups,dtype=np.float64)
assert np.isfinite(arrays['coordinates']).all()
assert (np.abs(arrays['coordinates'][:,0])<=180).all() and (np.abs(arrays['coordinates'][:,1])<=90).all()
np.savez_compressed(out/'inputs.npz',**arrays)
(out/'manifest.json').write_text(json.dumps({'schema':'gridatlas.layer-census.v1','layers':descriptors,'sources':len(cache),'coordinates':len(coord_groups),'input_sha256':hashlib.sha256((out/'inputs.npz').read_bytes()).hexdigest()},indent=2))
print(json.dumps({'layers':len(descriptors),'sources':len(cache),'feature_layer_pairs':sum(x['features'] for x in descriptors),'coordinates':len(coord_groups),'zero_eligible':[x['id'] for x in descriptors if not x['eligible_cpu']]}))Lightning Cartridge
A JavaScript module in the proofs folder of GridAtlas that uses SHA-256. It reads JSON (`readJson`) and is built from the sha step (`sha`) and the route of helper (`routeOf`).
rendergridatlas / tools/proofs/lightning-cartridge.mjs · lines 1–152 of 152 · Not reached from any entry point (candidate for review) · pattern readJson (shared by 43 files)
- What it does
- It loads data. Defines 6 functions or classes, including sha, readJson, routeOf, proveLightningCartridge, at. Uses libraries node:assert/strict, node:fs, node:path, node:vm, node:crypto. Side effects: changes the web page (DOM); 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.
- Inputs & outputs
- In: JSON file current.json.
- Downstream impact
- Used directly by 1 file: UK Lightning Overlay Proof (gridatlas).
- What it achieves
- The proof of a modular lightning generation: the UK lightning overlay composed as its OWN cartridge ('UK-lightning-overlay', slot after-cartridge, after single-line diagram (SLD)-sandbox), with SLD-sandbox back to the original bytes. It reads `atlas/current.json`.
- Why it matters
- Imported by UK Lightning Overlay Proof.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- Loader Composition (import), GridAtlas — Scope (dynamic import), node:assert/strict, node:fs, node:path, node:vm, node:crypto
- Used by
- imported by UK Lightning Overlay Proof (import)
- Produces
- ORIGINAL_SLD, OVERLAY_ID, OVERLAY_BUDGET, routeOf, proveLightningCartridge
- Defines here
- sha, readJson, routeOf, proveLightningCartridge, at, read
- 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/proofs/lightning-cartridge.mjs:1-152 · blob 673c7d32f25dd9f72a0564b9ac7a44d9e4d641c1 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
* The proof of a modular lightning generation: the UK lightning overlay
* composed as its OWN cartridge ('uk-lightning-overlay', slot after-cartridge,
* after sld-sandbox), with sld-sandbox back to the original 202609241334
* bytes. docs/LIGHTNING-CARTRIDGE.md. Each such generation has a two-line
* tools/proofs/<G>-uk-lightning-overlay.proof.mjs that calls this with G.
*
* It asserts, against the composition that names G (atlas/current.json once
* released, atlas/v/G/current.json until then):
*
* identity G, the order [..., sld-sandbox, uk-lightning-overlay], the
* slot, the anchor, and every hash;
* sld sld-sandbox is the original 202609241334 cartridge, 435,218
* bytes, sha256 7812953671d8...; nothing of the overlay is in it;
* module the overlay cartridge IS atlas/modules/<M>-uk-lightning-overlay.js
* (no copy), within its 64,781-byte budget, names generation M,
* parses, and is one strict IIFE with nothing else at top level,
* so it declares no global binding and its strictness does not
* depend on the script it used to share;
* loader the route's served loader is registered and supports the slots;
* parity against M's monolithic composition (sld-sandbox = original +
* '\n' + the same module), both composed by their own served
* loaders in node:vm: the same scripts run in the same order,
* sld-sandbox(M) == sld-sandbox(G) + '\n' + overlay(G) byte for
* byte, and the composed HTML is identical except for the one
* overlay tag directly after the sld-sandbox tag and the
* published composition state. That is arrival parity: the
* arrival code (sld-sandbox) is byte-identical, at the same place
* in the document, before the same overlay bytes.
*/
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { createHash } from 'node:crypto';
import { compose, ROOT } from './loader-composition.mjs';
export const ORIGINAL_SLD = Object.freeze({
generation: '202609241334',
path: 'atlas/cartridges/202609241334-sld-sandbox-v9-8.js',
sha256: '7812953671d8bb22a566de5e98fd3137da2d23411c5aecd526df5afa111ca4ca',
bytes: 435218
});
export const OVERLAY_ID = 'uk-lightning-overlay';
export const OVERLAY_BUDGET = 64781;
const sha = (b) => createHash('sha256').update(b).digest('hex');
const readJson = (rel) => JSON.parse(fs.readFileSync(path.join(ROOT, rel), 'utf8'));
/** The route ('atlas/' or 'atlas/v/G/') whose current.json composes G. */
export function routeOf(G) {
const live = readJson('atlas/current.json');
if (String(live.generation) === G) return 'atlas/';
return `atlas/v/${G}/`;
}
export async function proveLightningCartridge(G) {
process.chdir(ROOT); // tools/scope/lib.mjs resolves from the working directory
const { registeredLoader, slotsUsed, CARTRIDGE_BYTE_BUDGETS } = await import('../scope/lib.mjs');
const route = routeOf(G);
const current = readJson(`${route}current.json`);
const at = (p) => path.resolve(ROOT, route, p);
/* identity */
assert.equal(String(current.generation), G, `${route}current.json declares ${current.generation}`);
const order = current.cartridge_order;
const byId = new Map(current.cartridges.map(c => [c.id, c]));
assert.equal(order.indexOf(OVERLAY_ID), order.indexOf('sld-sandbox') + 1, 'the overlay is ordered directly after sld-sandbox');
assert.equal(order.filter(id => id === OVERLAY_ID).length, 1);
const sld = byId.get('sld-sandbox');
const overlay = byId.get(OVERLAY_ID);
assert.ok(sld && overlay, 'sld-sandbox and the overlay are both composed');
assert.equal(overlay.type, 'script');
assert.equal(overlay.slot, 'after-cartridge');
assert.equal(overlay.after, 'sld-sandbox');
assert.equal(overlay.generation, G, 'the overlay cartridge is cut at G (run-current finds this proof by it)');
/* sld: the original cartridge, untouched */
assert.equal(sld.slot, 'replace-script');
assert.equal(sld.generation, ORIGINAL_SLD.generation);
assert.equal(at(sld.path), path.join(ROOT, ORIGINAL_SLD.path), 'sld-sandbox is the original file, not a copy');
const sldBytes = fs.readFileSync(at(sld.path));
assert.equal(sha(sldBytes), ORIGINAL_SLD.sha256, 'the original 202609241334 sld-sandbox bytes are unchanged');
assert.equal(sld.sha256, ORIGINAL_SLD.sha256);
assert.equal(sldBytes.length, ORIGINAL_SLD.bytes);
assert.equal(sldBytes.includes('uk-lightning-overlay'), false, 'nothing of the overlay is inside sld-sandbox');
/* module: the overlay cartridge is the module file itself */
const M = String(overlay.module_generation || '');
assert.match(M, /^\d{12}$/, 'module_generation names the module stamp');
const modulePath = path.join(ROOT, 'atlas', 'modules', `${M}-uk-lightning-overlay.js`);
assert.equal(at(overlay.path), modulePath, 'the overlay cartridge path is the module itself (no copy)');
const module = fs.readFileSync(modulePath);
assert.equal(sha(module), overlay.sha256, 'overlay SHA-256');
assert.equal(module.length, overlay.bytes, 'overlay bytes');
assert.ok(module.length <= OVERLAY_BUDGET && module.length <= CARTRIDGE_BYTE_BUDGETS[OVERLAY_ID], `overlay ${module.length} B exceeds the ${OVERLAY_BUDGET}-byte budget`);
const text = module.toString('utf8');
assert.ok(text.includes(`generation ${M}`), 'module header names its generation');
new vm.Script(text, { filename: modulePath });
const body = text.replace(/^(\s*\/\*[\s\S]*?\*\/)*\s*/, '');
assert.ok(body.startsWith("(()=>{'use strict';"), 'top level is one strict arrow IIFE');
assert.ok(/\}\)\(\);\s*$/.test(body), 'and ends with its call');
assert.equal((text.match(/\(\(\)=>\{'use strict'/g) || []).length, 1, 'exactly one IIFE');
// Wrapped in parentheses the top level parses only if it is ONE expression:
// a second statement, or a top-level let/const/function, is a SyntaxError.
new vm.Script(`(${body.trim().replace(/;\s*$/, '')}\n)`, { filename: `${modulePath}#single-expression` });
/* loader */
const loader = registeredLoader(path.join(ROOT, route, 'index.html'));
assert.ok(loader, `${route}index.html is not a registered loader`);
for (const slot of slotsUsed(current)) assert.ok(loader.slots.includes(slot), `${route}index.html (${loader.name}) does not support ${slot}`);
/* parity with the monolithic composition of the same module */
const R = String(overlay.parity_reference || M);
const refRoute = `atlas/v/${R}/`;
const ref = readJson(`${refRoute}current.json`);
const refSld = ref.cartridges.find(c => c.id === 'sld-sandbox');
const refLoader = registeredLoader(path.join(ROOT, refRoute, 'index.html'));
assert.ok(refLoader, `${refRoute}index.html is not a registered loader`);
const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8');
const [g0, r] = await Promise.all([
compose({ loaderHtml: read(path.join(route, 'index.html')), route }),
compose({ loaderHtml: read(path.join(refRoute, 'index.html')), route: refRoute })
]);
// Further after-cartridge overlays chained after this one (e.g. uk-offtakers-overlay, after uk-lightning-overlay) carry
// their own proofs; they are taken out here, tag and script, so this parity is about the lightning overlay alone.
const extra = current.cartridges.filter(c => c.slot === 'after-cartridge' && c.id !== OVERLAY_ID).map(c => c.id);
const g = { ...g0, scripts: g0.scripts.filter(s => !extra.includes(s.id)),
html: extra.reduce((h, id) => h.replace(new RegExp(`\\n<script data-gridatlas-cartridge="${id}" src="blob:gridatlas\\/\\d+"><\\/script>`), ''), g0.html) };
for (const id of extra) assert.equal(g0.scripts.filter(s => s.id === id).length, 1, `${id}: one tag`);
assert.equal(g.failed, false, `${route}: ${g.message} ${g.errors.join(' ')}`);
assert.equal(r.failed, false, `${refRoute}: ${r.message} ${r.errors.join(' ')}`);
const gIds = g.scripts.map(s => s.id), rIds = r.scripts.map(s => s.id);
const k = rIds.indexOf('sld-sandbox');
assert.deepEqual(gIds, [...rIds.slice(0, k + 1), OVERLAY_ID, ...rIds.slice(k + 1)], 'the same scripts in the same order, the overlay straight after sld-sandbox');
for (let i = 0; i < k; i += 1) assert.equal(sha(g.scripts[i].source), sha(r.scripts[i].source), `${rIds[i]} differs from ${R}`);
const joined = Buffer.concat([g.scripts[k].source, Buffer.from('\n'), g.scripts[k + 1].source]);
assert.equal(sha(joined), refSld.sha256, `sld-sandbox(${R}) == sld-sandbox(${G}) + '\\n' + overlay(${G}), byte for byte`);
for (let i = k + 1; i < rIds.length; i += 1) assert.equal(sha(g.scripts[i + 1].source), sha(r.scripts[i].source), `${rIds[i]} differs from ${R}`);
// HTML: drop the one inserted overlay tag and the published state script;
// everything else, every blob URL included, is the same document.
const overlayTag = g.html.match(/\n<script data-gridatlas-cartridge="uk-lightning-overlay" src="blob:gridatlas\/\d+"><\/script>/g);
assert.equal(overlayTag?.length, 1, 'one overlay tag');
const sldTag = g.html.match(/<script data-gridatlas-cartridge="sld-sandbox" src="blob:gridatlas\/\d+"><\/script>/)[0];
assert.ok(g.html.includes(sldTag + overlayTag[0]), 'the overlay tag sits directly after the sld-sandbox tag');
const state = /<script>window\.__GRIDATLAS_ATLAS__=[^\n]*?<\/script>/;
const gHtml = g.html.replace(overlayTag[0], '').replace(state, '<STATE>');
const rHtml = r.html.replace(state, '<STATE>');
assert.equal(gHtml, rHtml, `the composed document equals ${R}'s apart from the overlay tag and the published state`);
console.log(`${G} uk-lightning-overlay: sld-sandbox is the original ${ORIGINAL_SLD.generation} (${ORIGINAL_SLD.bytes} B); overlay = atlas/modules/${M}-uk-lightning-overlay.js (${module.length} B <= ${OVERLAY_BUDGET}); loader ${loader.name}; arrival parity with ${R}: ${gIds.length} scripts, sld+'\\n'+overlay == ${R} sld-sandbox, document identical but for the overlay tag. PASS`);
}Loader Composition
A JavaScript module in the proofs folder of GridAtlas that works with loader script (`loaderScript`) and stub URL (`StubURL`).
rendergridatlas / tools/proofs/loader-composition.mjs · lines 1–86 of 86 · pattern compose (shared by 4 files)
- What it does
- It draws its content. Defines response, loaderScript, compose, StubURL, fetch. Uses libraries node:fs, node:path, node:vm, node:crypto, node:url. Side effects: changes the web page (DOM); 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.
- Inputs & outputs
- In: JSON file current.json.
- Downstream impact
- Used directly by 6 files: Lightning Cartridge (gridatlas); Loader Equivalence Proof (gridatlas); Offtakers Cartridge (gridatlas); Loader Swap (gridatlas); and 2 more. Reached from 5 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); GridAtlas Verify Live Workflow (gridatlas); CI PR Gate (gridatlas).
- What it achieves
- It is built from the response step (`response`), the loader script helper (`loaderScript`) and the compose step (`compose`). Run the GridAtlas composer (`atlas/index.html`) in Node, without a browser, and return exactly what it would hand to document.write: the composed HTML and, in document order, the source of every script tag it points at a verified cartridge blob.
- Why it matters
- Imported by 6 files, including Lightning Cartridge, Loader Equivalence Proof and Offtakers Cartridge.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- node:fs, node:path, node:vm, node:crypto, node:url
- Used by
- imported by Lightning Cartridge (import), imported by Loader Equivalence Proof (import), imported by Offtakers Cartridge (import), imported by Loader Swap (import), imported by Keys (import), imported by Preserve (import)
- Produces
- ROOT, loaderScript, compose
- Defines here
- response, loaderScript, compose, StubURL, fetch
- 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/proofs/loader-composition.mjs:1-86 · blob 42fa325f6f2e0cbc7a7946f8210be8cdad362a38 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
* Run the GridAtlas composer (atlas/index.html) in Node, without a browser,
* and return exactly what it would hand to document.write: the composed HTML
* and, in document order, the source of every script tag it points at a
* verified cartridge blob.
*
* import { compose } from './loader-composition.mjs';
* const out = await compose({ loaderHtml, route: 'atlas/v/<gen>/' });
*
* The loader's own module script is executed verbatim in a vm context. Only
* the platform is stubbed: fetch reads the repository working tree (the bytes
* GitHub Pages serves for this tree), crypto.subtle is Node's WebCrypto, and
* URL.createObjectURL returns deterministic blob:gridatlas/<n> URLs so two
* runs, or two loaders, can be compared byte for byte.
*/
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { webcrypto } from 'node:crypto';
import { fileURLToPath } from 'node:url';
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const ORIGIN = 'https://ventusltd.github.io';
const SITE = '/gridatlas/';
function response(file, virtual) {
if (virtual) file = null;
const bytes = virtual ? Buffer.from(virtual) : null;
if (!bytes && (!file || !fs.existsSync(file) || !fs.statSync(file).isFile())) {
return { ok: false, status: 404, async json() { throw new Error('404'); }, async text() { return ''; }, async arrayBuffer() { return new ArrayBuffer(0); } };
}
const body = bytes || fs.readFileSync(file);
return {
ok: true, status: 200,
async json() { return JSON.parse(body.toString('utf8')); },
async text() { return body.toString('utf8'); },
async arrayBuffer() { return body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength); }
};
}
export function loaderScript(loaderHtml) {
const m = String(loaderHtml).match(/<script type="module">([\s\S]*?)<\/script>/);
if (!m) throw new Error('loader has no module script');
return m[1];
}
/** route: the served directory of the pointer, 'atlas/' (live) or 'atlas/v/<gen>/'.
files: optional virtual files, { 'atlas/v/x/current.json': text }, served in
place of (or in addition to) the working tree; nothing is written to disk. */
export async function compose({ loaderHtml, route = 'atlas/', files = {} }) {
const href = `${ORIGIN}${SITE}${route}`;
const blobs = new Map();
let serial = 0;
class StubURL extends URL {}
StubURL.createObjectURL = (blob) => {
const url = `blob:gridatlas/${++serial}`;
blobs.set(url, blob);
return url;
};
const written = [];
const loader = { innerHTML: '' };
const errors = [];
const document = {
getElementById: (id) => (id === 'gridatlas-loader' ? loader : null),
body: { dataset: {} },
open() {}, write(s) { written.push(s); }, close() {}
};
const fetch = async (input) => {
const u = new URL(String(input), href);
if (u.origin !== ORIGIN || !u.pathname.startsWith(SITE)) return response(null);
const rel = decodeURIComponent(u.pathname.slice(SITE.length));
return response(path.join(ROOT, rel), Object.hasOwn(files, rel) ? files[rel] : null);
};
const context = vm.createContext({
window: { location: { href } }, document, fetch, URL: StubURL, Blob, crypto: webcrypto,
console: { error: (...a) => errors.push(a.map(String).join(' ')), log() {} }
});
await vm.runInContext(`(async () => {${loaderScript(loaderHtml)}\n})()`, context);
const html = written.join('');
const scripts = [];
for (const m of html.matchAll(/<script data-gridatlas-cartridge="([^"]+)" src="(blob:gridatlas\/\d+)"><\/script>/g)) {
scripts.push({ id: m[1], url: m[2], source: Buffer.from(await blobs.get(m[2]).arrayBuffer()) });
}
return { html, scripts, failed: document.body.dataset.gridatlasRouter === 'failed', message: loader.innerHTML, errors };
}Loader Equivalence Proof
A JavaScript module in the proofs folder of GridAtlas that uses SHA-256. It is built from the sha step (`sha`), the read step (`read`) and the extra step (`extra`).
rendergridatlas / tools/proofs/loader-equivalence.proof.mjs · lines 1–121 of 121 · pattern extra (shared by 2 files)
- What it does
- It loads data. Defines sha, read, up, extra, run. Uses libraries node:assert/strict, node:fs, node:path, node:crypto. Side effects: changes the web page (DOM); 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.
- Inputs & outputs
- In: JSON file current.json.
- Downstream impact
- Used directly by 1 file: CI PR Gate (gridatlas). Reached from 2 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Map Promotion Rehearsal (gridatlas).
- What it achieves
- Loader v2 (`tools/scope/payloads/atlas-loader-v2.html`) adds one slot type, 'after-cartridge': a verified cartridge as its own script tag straight after a cartridge composed before it. It reads `atlas/current.json`.
- Why it matters
- Run by CI PR Gate.
- Application
- gridatlas · tools/proofs · JavaScript module
- Uses
- Loader Composition (import), GridAtlas — Scope (dynamic import), node:assert/strict, node:fs, node:path, node:crypto
- Used by
- run by CI PR Gate (script call)
- Produces
- sha, read, up, extra, run
- Defines here
- sha, read, up, extra, run
- 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/proofs/loader-equivalence.proof.mjs:1-121 · blob 5aae9ef10bd41bcc9323f122b84a8f3f31aa78de · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
* Loader v2 (tools/scope/payloads/atlas-loader-v2.html) adds one slot type,
* 'after-cartridge': a verified cartridge as its own script tag straight after
* a cartridge composed before it. docs/LIGHTNING-CARTRIDGE.md. This proves:
*
* 1. Served loaders. atlas/index.html and every atlas/v/<gen>/index.html is
* byte-identical to a registered loader (tools/scope/lib.mjs ATLAS_LOADERS)
* that supports every slot its own current.json uses.
* 2. Equivalence. For atlas/current.json and every pinned composition that
* uses only 'replace-script', v2 writes byte-for-byte the HTML v1 writes,
* pointing at byte-identical cartridge blobs. So moving the live
* atlas/index.html from v1 to v2 changes nothing for any of them, and a
* rollback to any of them is safe under either loader.
* 3. Fail-closed. v1 refuses a composition that uses 'after-cartridge' (its
* failure screen, nothing written). v2 refuses an after-cartridge entry
* whose anchor is missing or composed later, whose bytes do not hash to the
* record, whose file is missing, or whose slot is unknown.
* 4. Order. An after-cartridge entry executes immediately after its anchor;
* two entries on one anchor keep cartridge_order.
*
* The loaders' own module scripts run verbatim in node:vm
* (tools/proofs/loader-composition.mjs); only fetch, WebCrypto and blob URLs
* are platform stubs.
*
* node tools/proofs/loader-equivalence.proof.mjs
*/
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { compose, ROOT } from './loader-composition.mjs';
process.chdir(ROOT); // tools/scope/lib.mjs resolves from the working directory
const { ATLAS_LOADERS, registeredLoader, slotsUsed } = await import('../scope/lib.mjs');
const sha = (b) => createHash('sha256').update(b).digest('hex');
const read = (rel) => fs.readFileSync(path.join(ROOT, rel), 'utf8');
const v1 = read(ATLAS_LOADERS.v1.payload);
const v2 = read(ATLAS_LOADERS.v2.payload);
assert.notEqual(sha(v1), sha(v2), 'v1 and v2 payloads must differ');
for (const marker of ['crypto.subtle.digest', 'cartridge_order', 'replace-script', 'after-cartridge', 'document.write']) {
assert.ok(v2.includes(marker), `loader v2 missing ${marker}`);
}
/* ------------------------------------------------ 1 and 2: every route */
const routes = ['atlas/'];
const vDir = path.join(ROOT, 'atlas', 'v');
for (const d of fs.readdirSync(vDir).filter(d => /^\d{12}$/.test(d)).sort()) {
if (fs.existsSync(path.join(vDir, d, 'current.json'))) routes.push(`atlas/v/${d}/`);
}
const served = { v1: 0, v2: 0 };
let equal = 0, modular = 0;
for (const route of routes) {
const pointer = JSON.parse(read(`${route}current.json`));
const slots = slotsUsed(pointer);
const loader = registeredLoader(path.join(ROOT, route, 'index.html'));
assert.ok(loader, `${route}index.html is not byte-identical to a registered loader`);
for (const slot of slots) assert.ok(loader.slots.includes(slot), `${route}index.html is loader ${loader.name}, which does not support ${slot}`);
served[loader.name] += 1;
const now = await compose({ loaderHtml: v2, route });
assert.equal(now.failed, false, `${route}: loader v2 failed: ${now.message} ${now.errors.join(' ')}`);
const before = await compose({ loaderHtml: v1, route });
if (slots.every(s => s === 'replace-script')) {
assert.equal(before.failed, false, `${route}: loader v1 failed: ${before.message}`);
assert.equal(now.html, before.html, `${route}: v2 composes different HTML from v1`);
assert.deepEqual(now.scripts.map(s => [s.id, sha(s.source)]), before.scripts.map(s => [s.id, sha(s.source)]), `${route}: cartridge blobs differ`);
equal += 1;
} else {
assert.equal(before.failed, true, `${route}: loader v1 must refuse a slot it does not know`);
assert.match(before.message, /unsupported cartridge slot/);
assert.equal(before.html, '', `${route}: v1 must write nothing`);
modular += 1;
}
}
console.log(`served loaders: ${routes.length} route(s), v1 ${served.v1}, v2 ${served.v2}; each supports the slots of its own current.json`);
console.log(`equivalence: ${equal} replace-script-only composition(s) compose byte-identically under v1 and v2; ${modular} modular composition(s) refused by v1, as designed`);
/* --------------------------------------- 3 and 4: synthetic compositions */
// Served from memory beside the pinned routes; nothing is written to disk.
const tmpRoute = 'atlas/v/loader-proof/';
const live = JSON.parse(read('atlas/current.json'));
const extras = { [`${tmpRoute}a.js`]: '/* extra A */\n', [`${tmpRoute}b.js`]: '/* extra B */\n' };
const up = (p) => p.replace(/^\.\//, '../../');
const baseCartridges = live.cartridges.map(c => ({ ...c, path: up(c.path) }));
const anchor = live.cartridge_order[live.cartridge_order.length - 1];
const extra = (id, file, after, digest) => ({ id, type: 'script', slot: 'after-cartridge', after, path: `./${file}`,
sha256: digest ?? sha(Buffer.from(extras[`${tmpRoute}${file}`])) });
const run = (loaderHtml, cartridges, order) => compose({ loaderHtml, route: tmpRoute, files: {
...extras,
[`${tmpRoute}current.json`]: JSON.stringify({ ...live, shell: { ...live.shell, index: up(live.shell.index), base: up(live.shell.base) }, cartridges, cartridge_order: order })
} });
const ok = await run(v2, [...baseCartridges, extra('a', 'a.js', anchor), extra('b', 'b.js', anchor)], [...live.cartridge_order, 'a', 'b']);
assert.equal(ok.failed, false, ok.message);
const ids = ok.scripts.map(s => s.id);
const at = ids.indexOf(anchor);
assert.deepEqual(ids.slice(at, at + 3), [anchor, 'a', 'b'], 'after-cartridge entries follow their anchor in cartridge_order');
assert.match(ok.html, new RegExp(`data-gridatlas-cartridge="${anchor}" src="blob:gridatlas/\\d+"></script>\\n<script data-gridatlas-cartridge="a" src="blob:gridatlas/\\d+"></script>\\n<script data-gridatlas-cartridge="b"`), 'A sits directly after the anchor tag, B directly after A');
assert.equal(ok.scripts.find(s => s.id === 'a').source.toString(), extras[`${tmpRoute}a.js`]);
const refusedByV1 = await run(v1, [...baseCartridges, extra('a', 'a.js', anchor)], [...live.cartridge_order, 'a']);
assert.equal(refusedByV1.failed, true, 'v1 must refuse after-cartridge');
assert.equal(refusedByV1.html, '', 'v1 must write nothing');
const failures = [
['anchor absent', [...baseCartridges, extra('a', 'a.js', 'no-such-cartridge')], [...live.cartridge_order, 'a'], /anchor no-such-cartridge is not composed before it/],
['anchor later in order', [...baseCartridges, extra('a', 'a.js', anchor)], ['a', ...live.cartridge_order], /is not composed before it/],
['digest mismatch', [...baseCartridges, extra('a', 'a.js', anchor, '0'.repeat(64))], [...live.cartridge_order, 'a'], /a: SHA-256 mismatch/],
['file missing', [...baseCartridges, { ...extra('a', 'a.js', anchor), path: './missing.js' }], [...live.cartridge_order, 'a'], /a: HTTP 404/],
['unknown slot', [...baseCartridges, { ...extra('a', 'a.js', anchor), slot: 'append-body' }], [...live.cartridge_order, 'a'], /a: unsupported cartridge slot/]
];
for (const [name, cartridges, order, pattern] of failures) {
const r = await run(v2, cartridges, order);
assert.equal(r.failed, true, `${name}: must fail closed`);
assert.match(r.message, pattern, `${name}: ${r.message}`);
assert.equal(r.html, '', `${name}: nothing may be written`);
}
console.log(`after-cartridge: order kept; v1 refuses it; ${failures.length} malformed compositions fail closed under v2 with nothing written`);
console.log('loader registry, equivalence and fail-closed PASS');