In this section
- GridAtlas Local Arrival Grid render · gridatlas / local-arrival-grid.mjs lines 1–202
- Evaluate Cross Repo Atlas V9 storage · gridatlas / orchestration/202608300232-evaluate-cross-repo-atlas-v9.py lines 1–187
- Assemble Study Build Controller storage · gridatlas / orchestration/202608310015-gridatlas-overnight-next-versions/202608310015-assemble-study-build-controller.mjs lines 1–32
- Finalise Overnight Candidate storage · gridatlas / orchestration/202608310015-gridatlas-overnight-next-versions/202608310015-finalise-overnight-candidate.mjs lines 1–155
GridAtlas Local Arrival Grid
A JavaScript module that reads harvest cache, the Renewable Energy Planning Database (REPD) register and solar. Served with the page at https://gridatlas.globalgrid2050.com/.
rendergridatlas / local-arrival-grid.mjs · lines 1–202 of 202 · Not reached from any entry point (candidate for review) · pattern worker (shared by 9 files)
- What it does
- It loads harvest cache, the REPD register and solar. Defines 6 functions or classes, including arg, harvest, grab, probe, url. Uses libraries playwright, node:fs, node:os. 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. Domain terms in the code: the REPD register, solar.
- Inputs & outputs
- In: JSON file harvest-cache.json; command-line arguments.
- What it achieves
- It is built from the arg step (`arg`), the harvest step (`harvest`) and the grab step (`grab`). The gap that let every defect found on ship: no CI job has ever loaded a deep link in a real browser at any viewport.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · / · JavaScript module
- Uses
- GridAtlas — Atlas Page (estate URL), playwright, node:fs, node:os
- Used by
- none found
- Produces
- arg, harvest, grab, probe, url, worker
- Defines here
- arg, harvest, grab, probe, url, worker
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 local-arrival-grid.mjs:1-202 · blob da6286796bd8ae3097e5f5a56967c657e1dba1aa · 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
/**
* Local arrival regression grid.
*
* The gap that let every defect found on 2026-09-04 ship: no CI job has ever
* loaded a deep link in a real browser at any viewport. Every vm proof stubs
* innerWidth:1280 and matchMedia->false, so the narrow branch is never taken,
* and the one mobile audit is orphaned because run-current cannot pick up a
* .audit.mjs file.
*
* This runs the real thing, locally, across every core: workers x {chromium,
* webkit} x {393, 1280} px, cycling REPD deep links harvested from the live
* Pipeline News release, asserting what a reader actually gets.
*
* Usage: node local-arrival-grid.mjs [--workers N] [--limit N] [--hidden]
*
* --hidden forces document.visibilityState to 'hidden' for the whole load,
* which is the iOS new-tab case: MAP carries target=_blank, iOS defers the
* tab, rAF never ticks, and the arrival expires against its 12s budget.
*/
import { chromium, webkit } from 'playwright';
import { appendFileSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
import os from 'node:os';
const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };
const WORKERS = Number(arg('--workers', Math.max(4, Math.floor(os.cpus().length / 2))));
const LIMIT = Number(arg('--limit', 400));
const HIDDEN = process.argv.includes('--hidden');
const OUT = arg('--out', 'C:/Users/vikra/OneDrive/Documents/GitHub/claude-governor-codex-20260904/sessions/202609040915-chrome-map-cycle/arrival-grid.jsonl');
const ATLAS = 'https://ventusltd.github.io/gridatlas/atlas/';
const PIPELINE = 'https://globalgrid2050.com/pipelinenews_intelligence/202609040144/';
const VIEWPORTS = [
{ w: 393, h: 852, name: 'iphone', mobile: true },
{ w: 1280, h: 800, name: 'desktop', mobile: false },
];
/** Harvest the real deep links from the live Pipeline News release. */
async function harvest() {
const cache = 'harvest-cache.json';
if (existsSync(cache)) {
const rows = JSON.parse(readFileSync(cache, 'utf8'));
if (rows.length) { console.log('harvest: ' + rows.length + ' rows from cache'); return rows; }
}
const b = await chromium.launch();
const p = await b.newPage({ viewport: { width: 1400, height: 900 } });
await p.goto(PIPELINE, { waitUntil: 'load', timeout: 90000 });
await p.waitForSelector('table tbody tr', { timeout: 60000 });
const rows = await p.evaluate(async () => {
const grab = () => [...document.querySelectorAll('table tbody tr')].map(r => {
const tds = [...r.querySelectorAll('td')].map(t => t.textContent.trim());
const a = [...r.querySelectorAll('a,button')].find(e => /^MAP/.test(e.textContent.trim()));
if (!a || !a.href) return { repd: tds[8], noMap: true, techLabel: tds[5], actions: tds[12] };
const u = new URL(a.href); const q = {}; u.searchParams.forEach((v, k) => q[k] = v);
return Object.assign({ repd: tds[8], name: tds[0].split('REPD')[0].trim(),
techLabel: tds[5], actions: tds[12], noMap: false }, q);
});
const out = [];
const spine = [...document.querySelectorAll('button')]
.filter(b => ['ALL TECH', 'SOLAR', 'BATTERY', 'ONSHORE', 'OFFSHORE'].includes(b.textContent.trim()));
for (const b of spine) {
b.click(); await new Promise(r => setTimeout(r, 900)); out.push(...grab());
}
const sel = document.querySelector('#widerTechnology') || document.querySelector('#tech');
if (sel) {
const opts = [...sel.querySelectorAll('option')].map(o => o.value).filter(v => v && !/^all/i.test(v));
for (const o of opts) {
sel.value = o; sel.dispatchEvent(new Event('change', { bubbles: true }));
await new Promise(r => setTimeout(r, 900)); out.push(...grab());
}
}
const seen = new Set();
return out.filter(r => r.repd && !seen.has(r.repd) && seen.add(r.repd));
});
await b.close();
writeFileSync(cache, JSON.stringify(rows, null, 1));
console.log('harvest: ' + rows.length + ' distinct REPD rows (' + rows.filter(r => r.noMap).length + ' NO MAP)');
return rows;
}
const probe = () => {
const L = window.__GRIDATLAS_NEON_LINKS__;
const m = window.__GRIDATLAS_V9_MAP__;
const q = new URLSearchParams(location.search);
const ans = [...document.querySelectorAll('body *')]
.find(e => e.children.length < 6 && /Nearest .* substation/.test(e.innerText || ''));
const attr = document.querySelector('.custom-map-attrib');
const ar = attr && attr.getBoundingClientRect();
// Sample the credit across its whole width. A centre-only check passed this
// build while "(c) CARTO" was already buried under an open menu panel.
const cover = ar ? [0.1, 0.3, 0.5, 0.7, 0.9].map(f => {
const e = document.elementFromPoint(ar.x + ar.width * f, ar.y + ar.height / 2);
return !!(e && (attr === e || attr.contains(e)));
}) : [];
const scada = document.querySelector('#scada-ui-container');
return {
repd: q.get('repd_ref'),
tech: q.get('technology'),
visibility: document.visibilityState,
card: !!ans,
answerY: ans ? Math.round(ans.getBoundingClientRect().y) : null,
answerOnFirstScreen: !!(ans && ans.getBoundingClientRect().y >= 0 && ans.getBoundingClientRect().y < innerHeight),
links_drawn: L ? L.links_drawn : null,
failures: L ? L.failures : null,
project_layer_enabled: L ? L.project_layer_enabled : null,
cameraFlew: m ? Math.abs(m.getCenter().lng - Number(q.get('longitude'))) < 0.05 : null,
attribCovered: cover.filter(x => !x).length,
attribSamples: cover.length,
menuBar: !!document.querySelector('#gridatlas-menu-bar'),
masthead: /SYSTEM TIME/.test(document.body.innerText),
scadaHeight: scada ? Math.round(scada.getBoundingClientRect().height) : null,
undersized: [...document.querySelectorAll('button,a,input,label')].filter(e => {
const r = e.getBoundingClientRect();
return r.width > 0 && r.height > 0 && Math.min(r.width, r.height) < 44;
}).length,
};
};
function url(r) {
const p = new URLSearchParams({
repd_ref: r.repd,
project: r.name || ('REPD-' + r.repd),
technology: r.technology || 'solar',
capacity_mw: r.capacity_mw || '1',
latitude: r.latitude,
longitude: r.longitude,
zoom: r.zoom || '12',
});
return ATLAS + '?' + p.toString();
}
async function worker(engine, engineName, vp, queue, stats) {
const browser = await engine.launch();
while (queue.length) {
const r = queue.pop();
if (!r) break;
const ctx = await browser.newContext({
viewport: { width: vp.w, height: vp.h },
deviceScaleFactor: vp.mobile ? 3 : 1,
isMobile: vp.mobile && engineName === 'webkit',
hasTouch: vp.mobile,
});
const page = await ctx.newPage();
const errors = [];
page.on('pageerror', e => errors.push(String(e).slice(0, 180)));
const t0 = Date.now();
try {
if (HIDDEN) {
await page.addInitScript(() => {
Object.defineProperty(document, 'visibilityState', { get: () => 'hidden' });
Object.defineProperty(document, 'hidden', { get: () => true });
});
}
await page.goto(url(r), { waitUntil: 'load', timeout: 60000 });
await page.waitForTimeout(9000);
const s = await page.evaluate(probe);
s.engine = engineName;
s.viewport = vp.name;
s.ms = Date.now() - t0;
s.pageErrors = errors.slice(0, 3);
s.techLabel = r.techLabel;
s.hiddenRun = HIDDEN;
s.t = new Date().toISOString();
s.observer = 'grid';
appendFileSync(OUT, JSON.stringify(s) + '\n');
stats.done++;
if ((s.failures && s.failures.length) || !s.card || s.attribCovered > 0) stats.bad++;
if (stats.done % 10 === 0) {
console.log('[' + engineName + '/' + vp.name + '] ' + stats.done + ' done, '
+ stats.bad + ' with findings, queue ' + queue.length);
}
} catch (e) {
appendFileSync(OUT, JSON.stringify({
repd: r.repd, engine: engineName, viewport: vp.name,
error: String(e.message).slice(0, 200), observer: 'grid', t: new Date().toISOString(),
}) + '\n');
stats.errors++;
}
await ctx.close();
}
await browser.close();
}
const all = await harvest();
const rows = all.filter(r => !r.noMap && r.latitude && r.longitude).slice(0, LIMIT);
console.log('grid: ' + rows.length + ' projects x ' + VIEWPORTS.length
+ ' viewports x 2 engines, ' + WORKERS + ' workers, hidden=' + HIDDEN);
const stats = { done: 0, bad: 0, errors: 0 };
const jobs = [];
for (const vp of VIEWPORTS) {
for (const pair of [[chromium, 'chromium'], [webkit, 'webkit']]) {
jobs.push({ eng: pair[0], name: pair[1], vp, queue: rows.slice() });
}
}
const perJob = Math.max(1, Math.floor(WORKERS / jobs.length));
const lanes = [];
for (const j of jobs) {
for (let i = 0; i < perJob; i++) lanes.push(worker(j.eng, j.name, j.vp, j.queue, stats));
}
await Promise.all(lanes);
console.log('GRID COMPLETE: ' + stats.done + ' arrivals, ' + stats.bad
+ ' with findings, ' + stats.errors + ' errors -> ' + OUT);Evaluate Cross Repo Atlas V9
A Python command-line tool in the orchestration folder of GridAtlas that reads GridAtlas current, atlas deep link audit and atlas company Renewable Energy Planning Database (REPD) links, using SHA-256.
storagegridatlas / orchestration/202608300232-evaluate-cross-repo-atlas-v9.py · lines 1–187 of 187 · version 2026-08-30 02:32 · Entry point · pattern milestone (shared by 2 files)
- What it does
- It loads GridAtlas current, atlas deep link audit, atlas company REPD links and atlas deep link contract. Defines load_optional, sha, milestone, main. Uses libraries __future__, argparse, hashlib, json, datetime. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'atlas'): 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 live-set.json; JSON file gridatlas-v9-current.json; JSON file atlas-v9-current.json; JSON file atlas-v9-deep-link-audit.json; JSON file atlas-v9-company-repd-links-manifest.json; JSON file atlas-v9-deep-link-contract.v1.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Evaluate Cross Repo Atlas V9 (gridatlas).
- What it achieves
- It loads optional (`load_optional`) and is built from the sha step (`sha`) and the milestone step (`milestone`). Evaluate the governed Atlas V9 publication/deep-link chain across four repositories. It accepts `--gridatlas`, `--globalgrid` and `--pipelinenews`.
- Why it matters
- Run by Evaluate Cross Repo Atlas V9.
- Application
- gridatlas · orchestration · Python CLI
- Uses
- __future__, argparse, hashlib, json, datetime, pathlib, typing
- Used by
- run by Evaluate Cross Repo Atlas V9 (workflow run)
- Produces
- load_optional, sha, milestone, main
- Defines here
- load_optional, sha, milestone, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 orchestration/202608300232-evaluate-cross-repo-atlas-v9.py:1-187 · blob 7bddf20b3ece082d891f8aecc13d6a7892ef50ad · 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: production_core
#!/usr/bin/env python3
"""Evaluate the governed Atlas V9 publication/deep-link chain across four repositories."""
from __future__ import annotations
import argparse
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
MIN_GENERATION = "202608292311"
def load_optional(path: Path) -> dict[str, Any] | None:
if not path.is_file():
return None
value = json.loads(path.read_text(encoding="utf-8"))
return value if isinstance(value, dict) else None
def sha(path: Path) -> str | None:
return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None
def milestone(identifier: str, passed: bool, observed: Any, gate: Any) -> dict[str, Any]:
return {
"id": identifier,
"passed": bool(passed),
"observed": observed,
"gate": gate,
}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--gridatlas", required=True, type=Path)
parser.add_argument("--globalgrid", required=True, type=Path)
parser.add_argument("--pipelinenews", required=True, type=Path)
parser.add_argument("--companies", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
atlas_path = args.gridatlas / "state/live-set.json"
global_path = args.globalgrid / "state/gridatlas-v9-current.json"
pipeline_pointer_path = args.pipelinenews / "state/atlas-v9-current.json"
pipeline_audit_path = args.pipelinenews / "reports/atlas-v9-deep-link-audit.json"
companies_pointer_path = args.companies / "state/atlas-v9-current.json"
companies_manifest_path = args.companies / "reports/atlas-v9-company-repd-links-manifest.json"
contract_path = args.gridatlas / "contracts/atlas-v9-deep-link-contract.v1.json"
atlas = load_optional(atlas_path) or {}
global_pointer = load_optional(global_path) or {}
pipeline_pointer = load_optional(pipeline_pointer_path) or {}
pipeline_audit = load_optional(pipeline_audit_path) or {}
companies_pointer = load_optional(companies_pointer_path) or {}
companies_manifest = load_optional(companies_manifest_path) or {}
contract = load_optional(contract_path) or {}
generation = str(atlas.get("generation") or "")
current = atlas.get("current") or {}
verification = atlas.get("verification") or {}
release_id = str(current.get("release_id") or "")
m0 = milestone(
"M0_FROZEN_BASELINE",
bool((current.get("product_oracle") or {}).get("commit") and (atlas.get("rollback") or {}).get("release_id")),
{
"oracle_commit": (current.get("product_oracle") or {}).get("commit"),
"rollback_release_id": (atlas.get("rollback") or {}).get("release_id"),
},
{"oracle_pinned": True, "rollback_recorded": True},
)
m1 = milestone(
"M1_RENDER_COMPARATOR_PROMOTED",
generation >= MIN_GENERATION
and verification.get("promotion_eligible") is True
and int(verification.get("failed_gates", -1)) == 0,
{
"generation": generation,
"release_id": release_id,
"classification": atlas.get("classification"),
"promotion_eligible": verification.get("promotion_eligible"),
"failed_gates": verification.get("failed_gates"),
"public_400kv_click_p95_ms": verification.get("public_400kv_click_p95_ms"),
"public_400kv_render_p95_ms": verification.get("public_400kv_render_p95_ms"),
},
{"generation_min": MIN_GENERATION, "promotion_eligible": True, "failed_gates": 0},
)
m2 = milestone(
"M2_GLOBALGRID_MIRROR_AND_ORDER",
global_pointer.get("classification") == "MIRRORED_PROMOTED_GRIDATLAS_V9"
and global_pointer.get("release_id") == release_id,
{
"release_id": global_pointer.get("release_id"),
"live_url": global_pointer.get("globalgrid_live_url"),
"files": global_pointer.get("files"),
},
{"release_id": release_id, "classification": "MIRRORED_PROMOTED_GRIDATLAS_V9"},
)
m3 = milestone(
"M3_CANONICAL_DEEP_LINK_CONTRACT",
contract.get("schema") == "gridatlas.deep-link-contract.v1"
and (contract.get("identity") or {}).get("required") == ["repd_ref", "technology"],
{
"schema": contract.get("schema"),
"required_identity": (contract.get("identity") or {}).get("required"),
"sha256": sha(contract_path),
},
{"schema": "gridatlas.deep-link-contract.v1", "required_identity": ["repd_ref", "technology"]},
)
sentinel_refs = {
str(item.get("repd_ref"))
for item in pipeline_audit.get("sentinels", [])
if isinstance(item, dict)
}
m4 = milestone(
"M4_PIPELINENEWS_CANONICAL_LINKS",
pipeline_pointer.get("release_id") == release_id
and pipeline_audit.get("classification") == "CANONICAL_DEEP_LINKS_READY"
and {"13599", "17494"}.issubset(sentinel_refs)
and int(pipeline_audit.get("immutable_releases_modified", -1)) == 0,
{
"release_id": pipeline_pointer.get("release_id"),
"base_url": pipeline_pointer.get("base_url"),
"sentinel_refs": sorted(sentinel_refs),
"replacements": pipeline_audit.get("replacement_count"),
"immutable_releases_modified": pipeline_audit.get("immutable_releases_modified"),
},
{"release_id": release_id, "sentinels": ["13599", "17494"], "immutable_releases_modified": 0},
)
m5 = milestone(
"M5_COMPANIES_COMPACT_RELATION",
companies_pointer.get("release_id") == release_id
and companies_manifest.get("classification") == "DETERMINISTIC_COMPACT_RELATION_BUILT"
and companies_manifest.get("raw_companies_house_data_stored") is False
and companies_manifest.get("personal_data") is False,
{
"release_id": companies_pointer.get("release_id"),
"output_rows": companies_manifest.get("output_rows"),
"output_bytes": companies_manifest.get("output_bytes"),
"output_sha256": companies_manifest.get("output_sha256"),
"abstentions": companies_manifest.get("source_rows_abstained"),
"raw_companies_house_data_stored": companies_manifest.get("raw_companies_house_data_stored"),
"personal_data": companies_manifest.get("personal_data"),
},
{"release_id": release_id, "raw_companies_house_data_stored": False, "personal_data": False},
)
milestones = [m0, m1, m2, m3, m4, m5]
all_green = all(item["passed"] for item in milestones)
m6 = milestone(
"M6_END_TO_END_GREEN",
all_green,
{"passed": sum(1 for item in milestones if item["passed"]), "total": len(milestones)},
{"passed": len(milestones), "total": len(milestones)},
)
milestones.append(m6)
payload = {
"schema": "gridatlas.cross-repo-atlas-v9-milestones.v1",
"classification": "CROSS_REPO_ATLAS_V9_GREEN" if m6["passed"] else "CROSS_REPO_ATLAS_V9_IN_PROGRESS",
"evaluated_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
"generation": generation or None,
"release_id": release_id or None,
"milestones": milestones,
"passed": sum(1 for item in milestones if item["passed"]),
"total": len(milestones),
"next_milestone": next((item["id"] for item in milestones if not item["passed"]), None),
"sources": {
"gridatlas_live_set_sha256": sha(atlas_path),
"globalgrid_pointer_sha256": sha(global_path),
"pipelinenews_pointer_sha256": sha(pipeline_pointer_path),
"pipelinenews_audit_sha256": sha(pipeline_audit_path),
"companies_pointer_sha256": sha(companies_pointer_path),
"companies_manifest_sha256": sha(companies_manifest_path),
"deep_link_contract_sha256": sha(contract_path),
},
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
print(json.dumps(payload, sort_keys=True))
if __name__ == "__main__":
main()Assemble Study Build Controller
A JavaScript module in the orchestration folder of GridAtlas that uses SHA-256.
storagegridatlas / orchestration/202608310015-gridatlas-overnight-next-versions/202608310015-assemble-study-build-controller.mjs · lines 1–32 of 32 · version 2026-08-31 00:15 · Entry point
- What it does
- It loads data. Defines sha256. Uses libraries node:crypto, node:fs/promises, node:path. 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.
- Downstream impact
- Used directly by 1 file: GridAtlas Overnight Next Versions Workflow (gridatlas).
- What it achieves
- Defines `sha256`.
- Why it matters
- Run by GridAtlas Overnight Next Versions Workflow.
- Application
- gridatlas · orchestration/202608310015-gridatlas-overnight-next-versions · JavaScript module
- Uses
- node:crypto, node:fs/promises, node:path
- Used by
- run by GridAtlas Overnight Next Versions Workflow (workflow run)
- Produces
- sha256
- Defines here
- sha256
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 orchestration/202608310015-gridatlas-overnight-next-versions/202608310015-assemble-study-build-controller.mjs:1-32 · blob be64a62d9d731bc2083e1eff5af97d46a21d7120 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
const root = path.resolve(process.env.SOURCE_ROOT || process.cwd());
const source = path.join(root, 'orchestration/202608310015-gridatlas-overnight-next-versions');
const output = path.resolve(process.env.CONTROLLER_OUTPUT || path.join(root, 'work/202608310015-study-build-controller.mjs'));
const expected = new Map([
['202608310015-study-build-controller.part-00', 'b70db8723cbe7020adbeaa296ec5e94d93961eb2fcc6d776bad8ec74e71f8500'],
['202608310015-study-build-controller.part-01', 'e18f782eded3c464f84f09d0106bd948b30cad8267f4b56f04de7be5aa5298ef'],
['202608310015-study-build-controller.part-02', '401bd93dc0e097da92874cd6ea77f2faafc92dc7f1c30b01a52686dcac8e38c7'],
['202608310015-study-build-controller.part-03', '6cb8526e8a7885764955a996b4828760c5422f2f7f64b30c9876b4f6b01ee70f'],
['202608310015-study-build-controller.part-04', '4b194b34edeba7a14b3da84f08227ad2a29623bd59023ae7442f830d732d46ca'],
['202608310015-study-build-controller.part-05', 'b82908bd6acac006941f9ac03ce64db8a6fce7010ac054a0f869fa35833e3d5f'],
['202608310015-study-build-controller.part-06', 'ee42d39225c1e9f6631b0664f7b554c04df73a4a07c3d7aff5538269bcb97d62'],
['202608310015-study-build-controller.part-07', '13bfa16018843b927dd97df78b8b9ea681b768b57b816022e4d321e06c460058']
]);
const expectedController = '40d45d31f1e3c926b2261067f8870bc77f7df69399b119ef581ef4054ab0a901';
const sha256 = value => crypto.createHash('sha256').update(value).digest('hex');
const chunks = [];
for (const [name, digest] of expected) {
const bytes = await fs.readFile(path.join(source, name));
const actual = sha256(bytes);
if (actual !== digest) throw new Error(`${name}: SHA-256 ${actual} != ${digest}`);
chunks.push(bytes);
}
const controller = Buffer.concat(chunks);
const actualController = sha256(controller);
if (actualController !== expectedController) throw new Error(`controller SHA-256 ${actualController} != ${expectedController}`);
await fs.mkdir(path.dirname(output), { recursive: true });
await fs.writeFile(output, controller);
console.log(JSON.stringify({ output, parts: expected.size, bytes: controller.length, sha256: actualController }));Finalise Overnight Candidate
A JavaScript module in the orchestration folder of GridAtlas that reads GridAtlas programme ledger, using SHA-256. It appends output (`appendOutput`), reads JSON (`readJson`) and writes JSON (`writeJson`).
storagegridatlas / orchestration/202608310015-gridatlas-overnight-next-versions/202608310015-finalise-overnight-candidate.mjs · lines 1–155 of 155 · version 2026-08-31 00:15 · Entry point · pattern writeJson (shared by 8 files)
- What it does
- It loads GridAtlas programme ledger. Defines 6 functions or classes, including appendOutput, sha256, htmlEscape, readJson, writeJson. Uses libraries node:crypto, node:fs/promises, node:path, node:fs. 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 202608310015-gridatlas-programme-ledger.json.
- Downstream impact
- Used directly by 1 file: GridAtlas Overnight Next Versions Workflow (gridatlas).
- What it achieves
- Defines `appendOutput`, `sha256`, `htmlEscape` and 3 more.
- Why it matters
- Run by GridAtlas Overnight Next Versions Workflow.
- Application
- gridatlas · orchestration/202608310015-gridatlas-overnight-next-versions · JavaScript module
- Uses
- node:crypto, node:fs/promises, node:path, node:fs
- Used by
- run by GridAtlas Overnight Next Versions Workflow (workflow run)
- Produces
- appendOutput, sha256, htmlEscape, readJson, writeJson, listFilesRecursive
- Defines here
- appendOutput, sha256, htmlEscape, readJson, writeJson, listFilesRecursive
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 orchestration/202608310015-gridatlas-overnight-next-versions/202608310015-finalise-overnight-candidate.mjs:1-155 · blob 2b028366a6612edb89ca192f0f44626796a3d7fe · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import fsSync from 'node:fs';
const root = path.resolve(process.env.SOURCE_ROOT || process.cwd());
const candidateDir = String(process.env.CANDIDATE_DIR || '');
const candidateManifestPath = String(process.env.CANDIDATE_MANIFEST || '');
const candidateCurrentPath = String(process.env.CANDIDATE_CURRENT || '');
const proofPath = String(process.env.PROOF || '');
const programmeRoot = String(process.env.PROGRAMME_ROOT || 'nightly/202608310015-gridatlas-overnight-next-versions');
const runStamp = String(process.env.RUN_STAMP || '202608310015');
const candidateId = String(process.env.CANDIDATE_ID || path.posix.basename(candidateDir));
const browserExit = Number(process.env.BROWSER_EXIT || 0);
if (!candidateDir || !candidateManifestPath || !candidateCurrentPath || !proofPath) {
throw new Error('CANDIDATE_DIR, CANDIDATE_MANIFEST, CANDIDATE_CURRENT and PROOF are required');
}
function appendOutput(key, value) {
if (!process.env.GITHUB_OUTPUT) return;
fsSync.appendFileSync(process.env.GITHUB_OUTPUT, `${key}=${String(value).replaceAll('\n', ' ')}\n`);
}
function sha256(buffer) {
return crypto.createHash('sha256').update(buffer).digest('hex');
}
function htmlEscape(value) {
return String(value)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}
async function readJson(filePath) {
return JSON.parse(await fs.readFile(path.join(root, filePath), 'utf8'));
}
async function writeJson(filePath, value) {
const absolute = path.join(root, filePath);
await fs.mkdir(path.dirname(absolute), { recursive: true });
await fs.writeFile(absolute, `${JSON.stringify(value, null, 2)}\n`);
}
async function listFilesRecursive(folder, relative = '') {
const absolute = path.join(folder, relative);
const entries = await fs.readdir(absolute, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const child = relative ? path.posix.join(relative, entry.name) : entry.name;
if (entry.isDirectory()) files.push(...await listFilesRecursive(folder, child));
else if (entry.isFile()) files.push(child);
}
return files.sort();
}
let proof;
try {
proof = await readJson(proofPath);
} catch (error) {
proof = {
schema: 'gridatlas.overnight-candidate-browser-proof.v1',
status: 'FAIL',
hard_failures: 1,
soft_failures: 0,
failure: `browser proof missing or unreadable: ${String(error?.message || error)}`
};
}
const allowedStatuses = new Set(['PASS', 'CORE_PASS_EXTERNAL_UNAVAILABLE', 'FAIL']);
const testStatus = allowedStatuses.has(proof.status) ? proof.status : 'FAIL';
const testedAt = new Date().toISOString();
const manifest = await readJson(candidateManifestPath);
manifest.test_status = testStatus;
manifest.tested_at = testedAt;
manifest.quarantined = testStatus === 'FAIL';
manifest.proof = {
path: proofPath,
screenshot: proofPath.replace(/\.json$/, '.png'),
browser_exit: browserExit,
hard_failures: Number(proof.hard_failures || 0),
soft_failures: Number(proof.soft_failures || 0),
status: testStatus
};
await writeJson(candidateManifestPath, manifest);
const current = await readJson(candidateCurrentPath);
current.candidate ||= {};
current.candidate.test_status = testStatus;
current.candidate.tested_at = testedAt;
current.candidate.quarantined = testStatus === 'FAIL';
await writeJson(candidateCurrentPath, current);
const ledgerPath = path.posix.join(programmeRoot, '202608310015-gridatlas-programme-ledger.json');
const ledger = await readJson(ledgerPath);
const ledgerCandidate = (ledger.candidates || []).find(item => item.candidate_id === candidateId);
if (!ledgerCandidate) throw new Error(`candidate ${candidateId} missing from programme ledger`);
ledgerCandidate.test_status = testStatus;
ledgerCandidate.tested_at = testedAt;
ledgerCandidate.proof_path = proofPath;
ledgerCandidate.browser_exit = browserExit;
await writeJson(ledgerPath, ledger);
const statusJsonName = `${runStamp}-gridatlas-candidate-test-status.json`;
const statusHtmlName = `${runStamp}-gridatlas-candidate-test-status.html`;
const statusJsonPath = path.posix.join(candidateDir, statusJsonName);
const statusHtmlPath = path.posix.join(candidateDir, statusHtmlName);
const status = {
schema: 'gridatlas.overnight-candidate-test-status.v1',
generation: runStamp,
candidate_id: candidateId,
candidate_route: `/gridatlas/${candidateDir}/`,
tested_at: testedAt,
status: testStatus,
quarantined: testStatus === 'FAIL',
browser_exit: browserExit,
hard_failures: Number(proof.hard_failures || 0),
soft_failures: Number(proof.soft_failures || 0),
proof_path: proofPath,
tests: proof.tests || [],
console_errors: proof.console_errors || [],
page_errors: proof.page_errors || []
};
await writeJson(statusJsonPath, status);
const rows = (proof.tests || []).map(test => `<tr><td>${htmlEscape(test.severity || '')}</td><td>${htmlEscape(test.name || '')}</td><td>${htmlEscape(test.status || '')}</td><td><pre>${htmlEscape(test.error || JSON.stringify(test.evidence || {}, null, 2))}</pre></td></tr>`).join('\n');
const statusHtml = `<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>${htmlEscape(candidateId)} test status</title>
<style>body{font:14px/1.4 system-ui;margin:24px;max-width:1500px}code,pre{font:12px/1.35 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere}table{border-collapse:collapse;width:100%}th,td{border:1px solid #bbb;padding:6px;text-align:left;vertical-align:top}.PASS{color:#075}.FAIL{color:#b00}.CORE_PASS_EXTERNAL_UNAVAILABLE{color:#a50}</style></head><body>
<h1>${htmlEscape(candidateId)}</h1>
<p>Status: <strong class="${htmlEscape(testStatus)}">${htmlEscape(testStatus)}</strong></p>
<p><a href="./">Open candidate app</a> · <a href="./${htmlEscape(path.posix.basename(proofPath))}">Browser proof JSON</a></p>
<p>Hard failures: ${status.hard_failures}; soft failures: ${status.soft_failures}; browser exit: ${browserExit}.</p>
<table><thead><tr><th>Severity</th><th>Test</th><th>Status</th><th>Evidence / error</th></tr></thead><tbody>${rows}</tbody></table>
</body></html>\n`;
await fs.writeFile(path.join(root, statusHtmlPath), statusHtml);
const candidateAbsolute = path.join(root, candidateDir);
const sumsName = `${runStamp}-gridatlas-sha256sums.txt`;
const files = (await listFilesRecursive(candidateAbsolute)).filter(name => name !== sumsName);
const sums = [];
for (const name of files) {
const buffer = await fs.readFile(path.join(candidateAbsolute, name));
sums.push(`${sha256(buffer)} ${name}`);
}
await fs.writeFile(path.join(candidateAbsolute, sumsName), `${sums.join('\n')}\n`);
appendOutput('candidate_status', testStatus);
appendOutput('candidate_quarantined', testStatus === 'FAIL' ? 'true' : 'false');
appendOutput('status_json', statusJsonPath);
appendOutput('status_html', statusHtmlPath);
console.log(JSON.stringify({ candidate_id: candidateId, status: testStatus, hard_failures: status.hard_failures, soft_failures: status.soft_failures, status_json: statusJsonPath }, null, 2));