In this section
- GridAtlas Screen Frame render · teleprinter / drivers/gridatlas/screen-frame.js lines 1–290
- GridAtlas Smoke Test test · teleprinter / drivers/gridatlas/smoke.test.mjs lines 1–130
- GridAtlas Lightning Immutable Test test · testcode / drivers/gridatlas-lightning-immutable.test.mjs lines 1–100
GridAtlas Screen Frame
A JavaScript module in the drivers folder of Teleprinter that stops tracks (`stopTracks`) and draws on a canvas.
renderteleprinter / drivers/gridatlas/screen-frame.js · lines 1–290 of 290 · Not reached from any entry point (candidate for review) · pattern pixelsFromSource (shared by 6 files)
- What it does
- It draws its content. Defines stopTracks, pixelsFromSource, fromDisplay, screenFrame. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path 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
- Out: canvas drawing; SVG drawing.
- Downstream impact
- Used directly by 1 file: GridAtlas Print PDF (teleprinter).
- What it achieves
- It stops tracks (`stopTracks`) and is built from the pixels from source helper (`pixelsFromSource`) and the from display helper (`fromDisplay`). One job, and one refusal.
- Why it matters
- Imported by GridAtlas Print PDF.
- Application
- teleprinter · drivers/gridatlas · JavaScript module
- Uses
- none found
- Used by
- imported by GridAtlas Print PDF (import)
- Produces
- screenFrame
- Defines here
- stopTracks, pixelsFromSource, fromDisplay, screenFrame
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/gridatlas/screen-frame.js:1-290 · blob 0ff959ac94be00a79a6254024de85b30fed33c25 · 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
/**
* GET THE FRAME THE READER IS LOOKING AT.
* ---------------------------------------------------------------------------
* One job, and one refusal.
*
* The job: return the pixels currently on the reader's screen, with their real
* dimensions and a note saying HOW they were obtained.
*
* The refusal: this never reconstructs the page. There is a tempting shortcut
* -- serialise the DOM into an <svg><foreignObject>, draw that to a canvas, and
* call the result a screenshot. It is not one. It drops cross-origin images,
* loses most pseudo-elements, cannot see into shadow roots, and silently
* substitutes fallback fonts. A reader handed that would be looking at a
* drawing of their screen while being told it was a record of it, which is the
* one thing a teleprinter must never do. If no honest frame can be had, this
* throws and the caller says so.
*
* TWO SOURCES, IN ORDER, AND THE RECORD ALWAYS NAMES THE ONE USED
*
* 'host' a capture function supplied by the embedder. This exists so a
* test harness can hand in the browser's own screenshot and
* exercise every downstream byte without a permission chooser --
* and so a future native shell can supply a real device grab.
*
* 'display' navigator.mediaDevices.getDisplayMedia({preferCurrentTab:true}).
* The compositor's own output: every layer, WebGL and DOM
* together, at the resolution the reader is actually looking at.
* Costs one permission click. That click is the price of an
* honest record and it is worth paying.
*
* WHY NOT canvas.toDataURL ALONE. GridAtlas draws its map into a WebGL canvas
* created without preserveDrawingBuffer, so the drawing buffer is gone by the
* time anything outside the frame that drew it goes looking. Reading it gives
* a fully transparent image that encodes to a perfectly valid, perfectly blank
* PNG. That is the failure that produced white sheets, and it is why a canvas
* read is a MAP source, never a SCREEN source.
*/
/** Milliseconds to wait for the capture track to actually produce a frame. */
const FRAME_TIMEOUT_MS = 10000;
/* A display track that never paints must not hang the reader's browser
forever. Chrome will happily keep an unstarted <video> pending, so the wait
is bounded and the tracks are stopped whatever happens -- an abandoned
capture leaves the tab's sharing indicator lit, which reads to the reader as
"this page is still watching my screen". */
function stopTracks(stream) {
if (!stream || typeof stream.getTracks !== 'function') return;
for (const track of stream.getTracks()) {
try { track.stop(); } catch (_) { /* already stopped */ }
}
}
function pixelsFromSource(source, width, height) {
if (!width || !height) throw new Error('The captured frame has no size.');
/* 40 megapixels is about a 8K screen at dpr 2. Past that the RGBA buffer
alone is 160 MB and the tab is more likely to die than to print. */
if (width * height > 40000000) {
throw new Error('The screen is too large to print in one page.');
}
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d', { willReadFrequently: true });
if (!context) throw new Error('This browser refused a 2D context.');
context.drawImage(source, 0, 0, width, height);
return { width, height, rgba: context.getImageData(0, 0, width, height).data };
}
async function fromDisplay() {
const media = navigator.mediaDevices;
if (!media || typeof media.getDisplayMedia !== 'function') {
/* This used to say: take a screenshot and use "Print a screenshot"
instead. THERE IS NO SUCH CONTROL IN THIS LANE. Telling a reader on the
one platform where this path fails to go and press a button that does
not exist is worse than telling them nothing, and it went unnoticed
because no test reads error strings. Say only what is true. */
throw new Error('This browser will not let a page capture the screen — '
+ 'iOS Safari does not offer it. Print source code still works here, and '
+ 'it records the screen state.');
}
/* preferCurrentTab is Chromium-only and is a HINT: it puts this tab at the
top of the chooser. Elsewhere the reader picks, which is correct -- their
screen, their choice. */
/* ASK FOR THE SCREEN'S REAL RESOLUTION.
------------------------------------------------------------------------
getDisplayMedia hands back whatever size the browser feels like unless it
is asked, and what it feels like is frequently NOT the reader's pixels. On
a 393x852 phone viewport at devicePixelRatio 3 -- 1179x2556 real pixels --
an unconstrained capture came back 786x1704: an effective scale of 2.0
against a dpr of 3, holding 1.34 of the screen's 3.01 megapixels. FORTY-
FOUR PERCENT of the record, and the receipt said "1:1" because the PDF
page equalled the captured image, which it did. The page was 1:1 with the
capture; the capture was not 1:1 with the screen.
So the real pixel count is asked for explicitly, and whatever arrives is
MEASURED against it rather than assumed. */
const wantWidth = Math.round(window.innerWidth * (window.devicePixelRatio || 1));
const wantHeight = Math.round(window.innerHeight * (window.devicePixelRatio || 1));
const stream = await media.getDisplayMedia({
video: {
frameRate: 1,
width: { ideal: wantWidth },
height: { ideal: wantHeight }
},
audio: false,
preferCurrentTab: true,
selfBrowserSurface: 'include'
});
try {
/* ImageCapture FIRST, because a <video> is the wrong instrument here.
---------------------------------------------------------------------
Piping the track into a detached <video> and reading videoWidth gave
786x1704 from a track that declares -- and caps at -- 1179x2556. Waiting
for the resolution to ramp did not fix it: a video element with no
layout is handed a reduced frame and keeps being handed one.
ImageCapture.grabFrame() asks the track for a frame directly and returns
it at the track's own size, with no element and no layout in the path.
The <video> route is kept only as a fallback for engines that have no
ImageCapture. */
const directTrack = stream.getVideoTracks()[0];
if (typeof ImageCapture === 'function' && directTrack) {
try {
/* RETRY WHILE THE TRACK RAMPS.
WAIT FOR THE FRAME TO STOP CHANGING, NOT FOR A SIZE IT WILL NEVER
REACH. The first version of this loop waited until the frame matched
track.getSettings().width, and the comment it carried -- that the
track "climbs to its own declared size" -- IS CONTRADICTED BY
MEASUREMENT. On a display track Chrome reports
`resizeMode: "crop-and-scale", width: 1179, height: 2556`: those are
the values that were ASKED FOR, echoed back, not the frames being
produced. It delivered 786x1704 throughout. So the exit condition was
unsatisfiable, the loop burned its whole timeout on every print, and
accepted the first frame anyway. There is no ramp on this track.
Waiting for stability is the honest version: grab until two
consecutive frames are the same size, which exits immediately when
the first frame is already final and still catches a source that
genuinely does climb. It also removes a five-second stall paid on
every print whose width is odd -- 2326 never reaches 2327. */
const capture = new ImageCapture(directTrack);
let grabbed = await capture.grabFrame();
const rampEnd = Date.now() + 5000;
let previousWidth = -1;
let previousHeight = -1;
while ((grabbed.width !== previousWidth || grabbed.height !== previousHeight)
&& (grabbed.width < wantWidth || grabbed.height < wantHeight)
&& Date.now() < rampEnd) {
previousWidth = grabbed.width;
previousHeight = grabbed.height;
if (typeof grabbed.close === 'function') grabbed.close();
await new Promise(resolve => setTimeout(resolve, 200));
grabbed = await capture.grabFrame();
}
try {
const settings = typeof directTrack.getSettings === 'function'
? directTrack.getSettings() : {};
return {
...pixelsFromSource(grabbed, grabbed.width, grabbed.height),
method: 'display',
screenWidth: wantWidth,
screenHeight: wantHeight,
trackWidth: Number(settings.width) || null,
trackHeight: Number(settings.height) || null,
/* BOTH AXES. captureScale was width-only, so a frame that was
full width and short in height reported as complete. The receipt
now carries the exact pixel counts and a flag that is an INTEGER
EQUALITY, not a threshold. */
captureScale: wantWidth ? grabbed.width / wantWidth : null,
captureScaleHeight: wantHeight ? grabbed.height / wantHeight : null,
everyScreenPixel: grabbed.width >= wantWidth && grabbed.height >= wantHeight
};
} finally {
if (typeof grabbed.close === 'function') grabbed.close();
}
} catch (_) { /* fall through to the video element */ }
}
const video = document.createElement('video');
video.muted = true;
video.playsInline = true;
video.srcObject = stream;
await video.play();
await new Promise((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error('No screen frame arrived within 10 seconds.')),
FRAME_TIMEOUT_MS
);
/* requestVideoFrameCallback fires on a frame that has actually been
composited. readyState alone can be satisfied by a track that has
produced metadata and no picture. */
if (typeof video.requestVideoFrameCallback === 'function') {
video.requestVideoFrameCallback(() => { clearTimeout(timer); resolve(); });
} else {
const poll = setInterval(() => {
if (video.videoWidth > 0 && video.readyState >= 2) {
clearInterval(poll);
clearTimeout(timer);
resolve();
}
}, 60);
}
});
/* WAIT FOR THE CAPTURE TO REACH ITS OWN FULL SIZE.
---------------------------------------------------------------------
This is where the "44% of the screen" defect actually lived, and it was
not a browser limit. Probed on 2026-09-05 at a 393x852 viewport, dpr 3:
the TRACK reports width 1179, height 2556, and getCapabilities gives a
max of exactly 1179x2556 -- the whole screen, available. But the first
composited frame arrives smaller and Chrome ramps up over the following
frames, so a capture taken on the first frame yielded 786x1704 and the
receipt called it the screen.
(min and exact constraints cannot be used to force it: Chrome rejects
both outright on getDisplayMedia -- "min constraints are not supported",
"exact constraints are not supported". Asking politely and then WAITING
is the whole technique.)
So the track's own declared size is the target, and this waits for the
decoded frame to reach it. If it never does, whatever arrived is used
and the shortfall is reported rather than hidden. */
const track = stream.getVideoTracks()[0];
const declared = track && typeof track.getSettings === 'function'
? track.getSettings() : {};
const targetWidth = Math.max(Number(declared.width) || 0, 0) || wantWidth;
const targetHeight = Math.max(Number(declared.height) || 0, 0) || wantHeight;
const rampDeadline = Date.now() + 4000;
while (video.videoWidth < targetWidth && Date.now() < rampDeadline) {
await new Promise(resolve => {
if (typeof video.requestVideoFrameCallback === 'function') {
video.requestVideoFrameCallback(() => resolve());
setTimeout(resolve, 200);
} else {
setTimeout(resolve, 100);
}
});
}
const frame = pixelsFromSource(video, video.videoWidth, video.videoHeight);
video.pause();
video.srcObject = null;
return {
...frame,
method: 'display',
screenWidth: wantWidth,
screenHeight: wantHeight,
trackWidth: targetWidth,
trackHeight: targetHeight,
/* 1 means the file holds every pixel that was on the screen. Anything
less is a reduction and must be printed on the receipt as one. */
captureScale: wantWidth ? frame.width / wantWidth : null,
captureScaleHeight: wantHeight ? frame.height / wantHeight : null,
everyScreenPixel: frame.width >= wantWidth && frame.height >= wantHeight
};
} finally {
stopTracks(stream);
}
}
/**
* @param {object} [options]
* @param {function} [options.capture] host-supplied capture returning a Blob,
* an ImageBitmap, or {width,height,rgba}. Used by the proof harness.
* @returns {Promise<{width:number,height:number,rgba:Uint8ClampedArray,method:string}>}
*/
export async function screenFrame({ capture } = {}) {
if (typeof capture === 'function') {
const supplied = await capture();
if (supplied && supplied.rgba && supplied.width && supplied.height) {
return { ...supplied, method: supplied.method || 'host' };
}
if (supplied && typeof createImageBitmap === 'function') {
/* colorSpaceConversion:'none' matters: the browser's image decoder will
otherwise shift sample values by a level or two on a tagged image, and
a print engine that claims to preserve pixels must not quietly alter
them. Codex measured exactly this in WebKit on 2026-09-05. */
const bitmap = await createImageBitmap(supplied, {
colorSpaceConversion: 'none',
premultiplyAlpha: 'none'
});
try {
return { ...pixelsFromSource(bitmap, bitmap.width, bitmap.height), method: 'host' };
} finally {
bitmap.close();
}
}
throw new Error('The supplied capture produced nothing usable.');
}
return fromDisplay();
}GridAtlas Smoke Test
A test in the drivers folder of Teleprinter that checks GridAtlas Print Source Code and GridAtlas Print PDF.
testteleprinter / drivers/gridatlas/smoke.test.mjs · lines 1–130 of 130 · Not reached from any entry point (candidate for review)
- What it does
- It tests its inputs. Defines installBrowser, node. Uses libraries node:test, node:assert/strict. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path 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.
- What it achieves
- It is built from the install browser helper (`installBrowser`) and the node step (`node`). On `print-source-code.js` referenced three identifiers that were never defined -- `headerLines`, `fileBlocks` and `splitIntoVolumes`, each appearing exactly ONCE in the file.
- Why it matters
- Guards the behaviour of GridAtlas Print Source Code and GridAtlas Print PDF.
- Application
- teleprinter · drivers/gridatlas · test
- Uses
- GridAtlas Print Source Code (dynamic import), GridAtlas Print PDF (dynamic import), node:test, node:assert/strict
- Used by
- none found
- Produces
- installBrowser, node
- Defines here
- installBrowser, node
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/gridatlas/smoke.test.mjs:1-130 · blob d04ad853b1699bbb5c640a01af6825cdf563dc72 · 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
/**
* THE TEST THIS LANE DID NOT HAVE.
* ---------------------------------------------------------------------------
* On 2026-09-05 `print-source-code.js` referenced three identifiers that were
* never defined -- `headerLines`, `fileBlocks` and `splitIntoVolumes`, each
* appearing exactly ONCE in the file. Every call threw a ReferenceError, so the
* Print source code button was dead on the live site.
*
* Nothing caught it. `node --check` passes on an undefined identifier: a syntax
* check parses, it does not resolve names. The lane's offline CI ran that check
* and went green. An independent comparison of the two driver lanes found it by
* reading the source.
*
* The lesson is narrow and cheap to act on: CALL THE FUNCTIONS. A test that
* merely imports a module proves almost nothing, because the bodies are never
* entered. These stub the few browser objects the drivers touch and then
* actually invoke every exported entry point, so an unresolved name, a bad
* property access or a broken return shape fails here instead of on a phone.
*
* node --test drivers/gridatlas/smoke.test.mjs
*/
import test from 'node:test';
import assert from 'node:assert/strict';
/* A deliberately small stub. It is not a DOM and does not pretend to be one:
it answers exactly what these drivers ask for and nothing else, so a driver
that starts depending on something new fails loudly rather than silently
getting a convincing fake. */
function installBrowser({ resources = [] } = {}) {
const removed = [];
const node = (tag) => ({
tagName: String(tag).toUpperCase(),
id: '', className: '', style: { cssText: '' }, dataset: {},
children: [], value: '', readOnly: false, textContent: '', href: '', download: '',
rel: '', type: '', parentNode: null,
setAttribute() {}, removeAttribute() {}, addEventListener() {},
appendChild(child) { this.children.push(child); child.parentNode = this; return child; },
removeChild(child) { removed.push(child); return child; },
focus() {}, setSelectionRange() {}, click() {}, closest() { return null; },
getBoundingClientRect() { return { width: 0, height: 0, top: 0, left: 0 }; },
classList: { add() {}, remove() {}, contains() { return false; } }
});
const body = node('body');
const documentElement = node('html');
documentElement.outerHTML = '<html><body>stub</body></html>';
const stubs = {
document: {
documentElement, body,
title: 'GridAtlas stub',
createElement: node,
getElementById: () => null,
querySelector: () => null,
querySelectorAll: () => []
},
window: { innerWidth: 800, innerHeight: 600, devicePixelRatio: 2 },
location: { href: 'https://example.invalid/atlas/' },
navigator: { userAgent: 'stub', clipboard: { writeText: async () => {} } },
performance: { getEntriesByType: () => resources },
fetch: async () => ({ ok: true, type: 'basic', status: 200, text: async () => 'stub body' }),
ImageCapture: undefined
};
const previous = {};
for (const [name, value] of Object.entries(stubs)) {
previous[name] = Object.getOwnPropertyDescriptor(globalThis, name);
Object.defineProperty(globalThis, name, { configurable: true, writable: true, value });
}
return () => {
for (const [name, descriptor] of Object.entries(previous)) {
if (descriptor) Object.defineProperty(globalThis, name, descriptor);
else delete globalThis[name];
}
};
}
test('collectSourceCode runs to completion and returns a usable record', async (t) => {
const restore = installBrowser({
resources: [{ name: 'https://example.invalid/atlas/app.js', initiatorType: 'script' }]
});
t.after(restore);
const { collectSourceCode } = await import('./print-source-code.js');
const collected = await collectSourceCode({ appName: 'GridAtlas' });
assert.equal(typeof collected.text, 'string');
assert.ok(collected.text.includes('TELEPRINT OF THE SOURCE CODE'));
assert.ok(collected.text.includes('END OF TELEPRINT'));
assert.match(collected.filename, /GridAtlas-source-code-.*\.txt$/);
assert.ok(collected.included > 0, 'nothing was collected at all');
assert.ok(Array.isArray(collected.missing));
/* The screen state is the reason this file is worth attaching to a chat. */
assert.equal(collected.state.url, 'https://example.invalid/atlas/');
assert.equal(collected.state.viewport.width, 800);
});
test('deliverSourceCode returns a record naming how the file was delivered', async (t) => {
const restore = installBrowser();
t.after(restore);
const previousUrl = globalThis.URL.createObjectURL;
globalThis.URL.createObjectURL = () => 'blob:stub';
globalThis.URL.revokeObjectURL = () => {};
t.after(() => { globalThis.URL.createObjectURL = previousUrl; });
const { collectSourceCode, deliverSourceCode } = await import('./print-source-code.js');
const collected = await collectSourceCode({ appName: 'GridAtlas' });
const record = await deliverSourceCode(collected, { panel: true });
assert.ok(record.via.includes('panel'), 'our own panel must always be offered');
assert.ok(record.bytes > 0);
assert.equal(typeof record.filename, 'string');
});
test('screenPdf writes a real one-page PDF with the strip outside the image', async () => {
const { screenPdf } = await import('./print-pdf.js');
const width = 4, height = 3;
const rgba = new Uint8ClampedArray(width * height * 4).fill(200);
const built = await screenPdf({ width, height, rgba },
{ title: 'stub', url: 'https://example.invalid/', stamp: '2026-01-01 00:00 UTC' });
const text = Buffer.from(built.bytes).toString('latin1');
assert.ok(text.startsWith('%PDF-'), 'not a PDF');
assert.ok(text.trimEnd().endsWith('%%EOF'), 'truncated PDF');
assert.ok(text.includes('/FlateDecode'));
assert.equal(built.pageWidth, width, 'the page must be the capture width, not paper');
/* The record must never be written on: the page is TALLER than the image and
the provenance lives in the space that adds. */
assert.ok(built.pageHeight > height, 'the strip is not outside the image');
assert.equal(built.pageHeight - built.strip, height);
});
test('screenPdf refuses a frame whose samples do not match its dimensions', async () => {
const { screenPdf } = await import('./print-pdf.js');
await assert.rejects(
() => screenPdf({ width: 4, height: 3, rgba: new Uint8ClampedArray(8) }),
/wrong number of samples/);
});GridAtlas Lightning Immutable Test
A test in the drivers folder of Testcode that uses SHA-256. It is built from the file step (`file`), the JSON step (`json`) and the hash step (`hash`).
testtestcode / drivers/gridatlas-lightning-immutable.test.mjs · lines 1–100 of 100 · Entry point
- What it does
- It tests its inputs. Defines file, json, hash, get. Uses libraries node:test, node:assert/strict, node:fs, node:path, node:crypto. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path 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; JSON file -composition.json.
- Downstream impact
- Used directly by 1 file: GridAtlas Lightning Independent Workflow (testcode).
- What it achieves
- Independent GridAtlas Lightning candidate preservation audit.
- Why it matters
- Run by GridAtlas Lightning Independent Workflow.
- Application
- testcode · drivers · test
- Uses
- node:test, node:assert/strict, node:fs, node:path, node:crypto, node:vm, node:url
- Used by
- run by GridAtlas Lightning Independent Workflow (workflow run)
- Produces
- file, json, hash, get
- Defines here
- file, json, hash, get
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 drivers/gridatlas-lightning-immutable.test.mjs:1-100 · blob d7e077bfc0a88ed5fc3d189045d9c046a97e8f77 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
/**
* Independent GridAtlas Lightning candidate preservation audit.
* This lives in TESTCODE, never in the product repository.
* Execute with a checkout of the exact candidate beside testcode:
* GRIDATLAS_ROOT=../gridatlas LIGHTNING_GEN=202610270024 \
* node --test drivers/gridatlas-lightning-immutable.test.mjs
*
* No network; no CSS, shell, app or archive writes; no synthetic data substitution.
* This proves STATIC invariants ONLY. Live WebKit/network and owner veto are separate.
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { resolve, join } from 'node:path';
import { createHash } from 'node:crypto';
import { Script } from 'node:vm';
import { fileURLToPath } from 'node:url';
const GEN = process.env.LIGHTNING_GEN || '202610270024';
const HERE = fileURLToPath(new URL('.', import.meta.url));
const ROOT = resolve(process.env.GRIDATLAS_ROOT || join(HERE, '../../gridatlas'));
const file = p => readFileSync(join(ROOT, p));
const json = p => JSON.parse(file(p).toString('utf8'));
const hash = b => createHash('sha256').update(b).digest('hex');
const get = (j,id) => {
const x=j.cartridges.filter(c=>c.id===id);
assert.equal(x.length,1, 'Missing/duplicated cartridge ' + id);
return x[0];
};
const ids = ['streaming-parquet-bridge','uk-gazetteer-flyto','substation-intelligence','sld-sandbox'];
const current = json('atlas/current.json');
const candidate = json('atlas/v/'+GEN+'/current.json');
const manifest = json('atlas/manifests/'+GEN+'-composition.json');
const overlay = file('atlas/modules/'+GEN+'-uk-lightning-overlay.js');
const orig = file('atlas/cartridges/202609241334-sld-sandbox-v9-8.js');
const composed = file('atlas/cartridges/'+GEN+'-sld-sandbox-v9-8.js');
const loader = file('atlas/v/'+GEN+'/index.html');
test('LIVE-01: still selects accepted generation 202609241334',()=>{
assert.equal(current.generation,'202609241334');
assert.equal(current.architecture,'IMMUTABLE_SHELL_PLUS_HASHED_CARTRIDGES');
assert.deepEqual(current.cartridge_order,ids);
});
test('LIVE-02: accepted original cartridge is byte-verifiable',()=>{
assert.equal(hash(orig),get(current,'sld-sandbox').sha256);
assert.equal(orig.length,435218);
});
test('CAND-01: versioned standalone page uses byte-identical composer',()=>{
assert.deepEqual(loader,file('atlas/index.html'));
assert.equal(candidate.generation,GEN);
assert.equal(manifest.generation,GEN);
assert.deepEqual(candidate.cartridge_order,ids);
assert.deepEqual(manifest.cartridge_order,ids);
assert.equal(candidate.shell.index,'../../releases/202608300453-atlas-v9/index.html');
assert.equal(candidate.shell.base,'../../releases/202608300453-atlas-v9/');
});
test('CAND-02: all other three original slot hashes are unmodified',()=>{
for(const id of ids.slice(0,3)){
assert.equal(get(candidate,id).sha256,get(current,id).sha256,'Hash changed for '+id);
assert.equal(get(manifest,id).sha256,get(current,id).sha256,'Manifest hash changed for '+id);
}
});
test('CAND-03: original composed cartridge is EXACT prefix, then one new module',()=>{
const expected = Buffer.concat([orig,Buffer.from('\n'),overlay]);
assert.deepEqual(composed,expected);
assert.equal(hash(composed),get(candidate,'sld-sandbox').sha256);
assert.equal(hash(composed),get(manifest,'sld-sandbox').sha256);
assert.equal(composed.length,get(candidate,'sld-sandbox').bytes);
});
test('CAND-04: overlay stays within documented byte limits',()=>{
assert.ok(overlay.length<=24781,'Original 460 kB budget leaves at most 24,781 overlay bytes: '+overlay.length);
assert.ok(overlay.length<=24781,'Hard bound 24,781 exceeded');
assert.ok(composed.length<=460000,'Derived cartridge exceeds 460,000 bytes');
});
test('CAND-05: module parses without execution or fetching anything',()=>{
assert.doesNotThrow(()=>new Script(overlay.toString('utf8'),{filename:GEN+'-uk-lightning-overlay.js'}));
});
test('CAND-06: optical flashes explicitly distinguish ground strikes',()=>{
const s=overlay.toString('utf8');
assert.match(s,/optical/i);
assert.match(s,/ground strike/i);
assert.match(s,/12m/);
assert.match(s,/7d/);
});
test('CAND-07: provenance record states exact candidate SHA and source',()=>{
const p=get(candidate,'sld-sandbox');
assert.equal(p.generation,GEN);
assert.match(p.path,new RegExp(GEN));
assert.match(candidate.composition_manifest,new RegExp(GEN));
});
console.log('Testcode independent audit reads:',ROOT,'generation',GEN);