In this section
- Stamp Data Spine Doctrine storage · code-generator / apps/substation-finder/Dt/stamp_data_spine_doctrine.py lines 1–166
- Verify V9 6 2 Equivalence render · code-generator / apps/substation-finder/Ps/202608282348-verify-v9-6-2-equivalence.mjs lines 1–273
- Transit Layer Availability Browser render · code-generator / apps/substation-finder/Ps/202609040219-transit-layer-availability.browser.mjs lines 1–257
Stamp Data Spine Doctrine
A Python command-line tool in the substation finder folder of Code Generator that reads spine stamp and solar.
storagecode-generator / apps/substation-finder/Dt/stamp_data_spine_doctrine.py · lines 1–166 of 166 · Entry point · pattern update_changelog (shared by 2 files)
- What it does
- It loads spine stamp and solar. Defines 9 functions or classes, including utc_now, stamp, read_text, write_text, insert_after_first_block. Uses libraries __future__, argparse, json, datetime, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'substation'): 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: solar.
- Inputs & outputs
- In: JSON file DATA_SPINE_STAMP_LATEST.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It reads text (`read_text`), writes text (`write_text`) and inserts after first block (`insert_after_first_block`). GlobalGrid2050 data spine doctrine stamper. It accepts `--apply`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- code-generator · apps/substation-finder/Dt · Python CLI
- Uses
- __future__, argparse, json, datetime, pathlib
- Used by
- none found
- Produces
- utc_now, stamp, read_text, write_text, insert_after_first_block, update_target, update_changelog, render_report, main
- Defines here
- utc_now, stamp, read_text, write_text, insert_after_first_block, update_target, update_changelog, render_report, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Dt/stamp_data_spine_doctrine.py:1-166 · blob eca7c3a96f63b89e673fa0ad2d6b3d0a4846ae76 · 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: supporting_data
#!/usr/bin/env python3
"""
GlobalGrid2050 data spine doctrine stamper.
Adds a compact data spine backlink block to key architecture logs.
The script is idempotent and writes an audit report.
"""
from __future__ import annotations
import argparse
import json
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
STAMP_HEADING = "## Data spine doctrine stamp"
STAMP_TEXT = """## Data spine doctrine stamp
Data grain discipline applies. Store the right grain for the question, not raw bulk. Settled FUELHH is confirmed where available. Live FUELINST is provisional. Sums roll up. Peaks do not. Solar is provenance stamped. Every fact carries schema, source, completeness and status. Never overwrite good data. Commit facts and regenerate bulk. Full doctrine: data_science_protocol/THE_DATA_SPINE.md
"""
TARGETS = [
"ARCHITECTURE.md",
"PHILOSOPHY.md",
"data_science_protocol/DATA_STORAGE_DISCIPLINE_PROTOCOL.md",
"uk_energy_tracking_v6/V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md",
]
CHANGELOG = "data_science_protocol/DATA_SCIENCE_DISCIPLINE_CHANGELOG.md"
def utc_now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def stamp() -> str:
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def read_text(path: Path) -> str:
if not path.exists():
return ""
return path.read_text(encoding="utf-8", errors="replace")
def write_text(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text.rstrip() + "\n", encoding="utf-8")
def insert_after_first_block(text: str) -> str:
if "data_science_protocol/THE_DATA_SPINE.md" in text:
return text
lines = text.splitlines()
if not lines:
return STAMP_TEXT.rstrip() + "\n"
insert_at = 1
while insert_at < min(len(lines), 12) and lines[insert_at].strip():
insert_at += 1
new_lines = lines[:insert_at] + ["", STAMP_TEXT.rstrip(), ""] + lines[insert_at:]
return "\n".join(new_lines) + "\n"
def update_target(rel: str, apply: bool) -> dict:
path = ROOT / rel
text = read_text(path)
exists = path.exists()
already = "data_science_protocol/THE_DATA_SPINE.md" in text
changed = False
if exists and not already:
new_text = insert_after_first_block(text)
changed = new_text != text
if apply and changed:
write_text(path, new_text)
return {
"path": rel,
"exists": exists,
"alreadyStamped": already,
"wouldChange": bool(exists and not already and changed),
"applied": bool(apply and exists and not already and changed),
}
def update_changelog(apply: bool) -> dict:
path = ROOT / CHANGELOG
text = read_text(path)
exists = path.exists()
marker = "Data spine doctrine adopted"
already = marker in text
block = """
## 2026 06 08 Data spine doctrine adopted
Executive summary: The canonical data spine doctrine was added and stamped across the principal architecture logs. The doctrine defines right grain for the right question, live versus confirmed source discipline, additive and non additive data rules, solar provenance, never overwrite protection and commit facts regenerate bulk storage policy.
Files referenced:
data_science_protocol/THE_DATA_SPINE.md
Known risks:
The doctrine must now be enforced through compiler logic and workflow reports, not merely documented.
Next action:
Run the generation ECG and FUELHH candidate workflows, then ask an external reviewer to check outputs against the data spine acceptance criteria.
"""
changed = exists and not already
if apply and changed:
write_text(path, text.rstrip() + "\n" + block.strip() + "\n")
return {"path": CHANGELOG, "exists": exists, "alreadyLogged": already, "wouldChange": changed, "applied": bool(apply and changed)}
def render_report(payload: dict) -> str:
lines = [
"# GlobalGrid2050 Data Spine Stamp Report",
"",
f"Generated UTC: `{payload['generatedUTC']}`",
f"Mode: `{payload['mode']}`",
"",
"## Results",
"",
]
for result in payload["targets"]:
lines.append(f"{result['path']} exists={result['exists']} already={result.get('alreadyStamped', result.get('alreadyLogged'))} applied={result['applied']}")
return "\n".join(lines) + "\n"
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--apply", action="store_true")
args = parser.parse_args()
targets = [update_target(rel, args.apply) for rel in TARGETS]
targets.append(update_changelog(args.apply))
payload = {
"schemaVersion": "1.0.0",
"generatedUTC": utc_now(),
"mode": "apply" if args.apply else "audit only",
"doctrine": "data_science_protocol/THE_DATA_SPINE.md",
"targets": targets,
}
REPORT_DIR.mkdir(parents=True, exist_ok=True)
REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
s = stamp()
md = REPORT_DIR / f"DATA_SPINE_STAMP_{s}.md"
js = REPORT_JSON_DIR / f"DATA_SPINE_STAMP_{s}.json"
latest_md = REPORT_DIR / "DATA_SPINE_STAMP_LATEST.md"
latest_js = REPORT_JSON_DIR / "DATA_SPINE_STAMP_LATEST.json"
md_text = render_report(payload)
js_text = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
write_text(md, md_text)
write_text(latest_md, md_text)
write_text(js, js_text)
write_text(latest_js, js_text)
print(md_text)
return 0
if __name__ == "__main__":
raise SystemExit(main())Verify V9 6 2 Equivalence
A JavaScript module in the substation finder folder of Code Generator covering solar. It is built from the first number helper (`firstNumber`).
rendercode-generator / apps/substation-finder/Ps/202608282348-verify-v9-6-2-equivalence.mjs · lines 1–273 of 273 · version 2026-08-28 23:48 · Entry point · pattern firstNumber (shared by 3 files)
- What it does
- It draws solar. Defines gate, firstNumber, observe. Uses libraries playwright, node:fs/promises. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'substation'): 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: solar.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- It is itself an entry point (JavaScript module); no other file was found loading it.
- What it achieves
- Its name says it verifies equivalence. Defines `gate`, `firstNumber` and `observe`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- code-generator · apps/substation-finder/Ps · JavaScript module
- Uses
- playwright, node:fs/promises
- Used by
- mentioned in Standalone (comment link)
- Produces
- gate, firstNumber, observe
- Defines here
- gate, firstNumber, observe
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Ps/202608282348-verify-v9-6-2-equivalence.mjs:1-273 · blob fc9f95c33ead9f09b527d86750af403eb14502b1 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env node
import { chromium } from "playwright";
import { writeFile } from "node:fs/promises";
const args = Object.fromEntries(
process.argv.slice(2).reduce(
(pairs, value, index, values) =>
value.startsWith("--") ? [...pairs, [value.slice(2), values[index + 1]]] : pairs,
[],
),
);
const candidate = args.candidate;
const baseline = args.baseline;
const report = args.report;
if (!candidate || !baseline || !report) {
throw new Error("--candidate, --baseline and --report are required");
}
const GENERATION = "202608282348";
const CANDIDATE_GENERATION = "202608282200";
const checks = [];
const sessions = [];
const gate = (id, pass, evidence) => checks.push({ id, pass: Boolean(pass), evidence });
function firstNumber(text) {
const match = String(text).replaceAll(",", "").match(/\d+(?:\.\d+)?/u);
return match ? Number(match[0]) : Number.NaN;
}
async function observe(browser, label, url, viewport) {
const mobile = viewport.width === 390;
const page = await browser.newPage({
viewport,
deviceScaleFactor: mobile ? 3 : 1,
isMobile: mobile,
hasTouch: mobile,
});
const started = Date.now();
const requests = [];
const consoleErrors = [];
const pageErrors = [];
const failed = [];
page.on("request", (request) => requests.push(new URL(request.url()).pathname));
page.on("console", (message) => {
if (message.type() === "error") consoleErrors.push(message.text());
});
page.on("pageerror", (error) => pageErrors.push(error.message));
page.on("requestfailed", (request) =>
failed.push(`${request.url()} :: ${request.failure()?.errorText}`),
);
await page.goto(url, { waitUntil: "domcontentloaded", timeout: 120_000 });
if (label === "candidate") {
await page.waitForFunction(() => document.body.dataset.fastReady === "true", null, {
timeout: 120_000,
});
} else {
await page.waitForFunction(
() => document.querySelector("#resultsMeta")?.dataset.totalCount === "7680",
null,
{ timeout: 120_000 },
);
}
const readyMs = Date.now() - started;
const expectedNews = label === "candidate" ? "136" : "133";
await page.waitForFunction(
(value) => document.querySelector("#newsMeta")?.textContent.includes(value),
expectedNews,
{ timeout: 120_000 },
);
const core = await page.evaluate(() => ({
total: Number(document.querySelector("#resultsMeta")?.dataset.totalCount),
filtered: Number(document.querySelector("#resultsMeta")?.dataset.filteredCount),
capacity: document.querySelector("#v1")?.textContent.trim(),
largest: document.querySelector("#v3")?.textContent.trim(),
columns: document.querySelectorAll(".tablewrap thead th").length,
rows: document.querySelectorAll("#tbody>tr").length,
rootOverflow: document.scrollingElement.scrollWidth - document.documentElement.clientWidth,
tableClient: document.querySelector(".tablewrap")?.clientWidth,
tableScroll: document.querySelector(".tablewrap")?.scrollWidth,
tableOverflow: getComputedStyle(document.querySelector(".tablewrap")).overflowX,
news: document.querySelector("#newsMeta")?.textContent.trim(),
dom: document.querySelectorAll("*").length,
}));
const observedCapacity = firstNumber(core.capacity);
const expectedCapacity = label === "candidate" ? 356_474.09 : 356_474;
gate(
`${label}-${viewport.width}-canonical`,
core.total === 7680 &&
core.filtered === 7680 &&
Math.abs(observedCapacity - expectedCapacity) < 0.001 &&
core.largest.includes("4,100"),
{ ...core, observedCapacity, expectedCapacity },
);
gate(`${label}-${viewport.width}-columns`, core.columns === 11, core.columns);
gate(`${label}-${viewport.width}-news`, core.news.includes(expectedNews), core.news);
if (label === "candidate") {
gate(
`${label}-${viewport.width}-100-rows-per-page`,
core.rows === 100,
{ observed: core.rows, required: 100 },
);
}
if (mobile) {
gate(`${label}-390-contained-root`, core.rootOverflow <= 1, core.rootOverflow);
gate(
`${label}-390-table-horizontal-scroll`,
core.tableScroll > core.tableClient && ["auto", "scroll"].includes(core.tableOverflow),
core,
);
}
if (label === "candidate") {
const startupRelationshipRequests = requests.filter((path) =>
path.includes(`${CANDIDATE_GENERATION}-federated-relationships`) ||
path.includes(`${CANDIDATE_GENERATION}-relationship-governance-status`),
);
gate(
`${label}-${viewport.width}-relationship-zero-startup`,
startupRelationshipRequests.length === 0,
startupRelationshipRequests,
);
gate(
`${label}-${viewport.width}-first-paint`,
readyMs <= 5000,
{ ready_ms: readyMs, maximum_ms: 5000 },
);
}
await page.locator("#search").fill("East Pye");
await page.waitForFunction(
() => document.querySelector("#resultsMeta")?.dataset.filteredCount === "1",
);
gate(
`${label}-${viewport.width}-search-east-pye`,
(await page.locator("#repd-17494").count()) === 1,
await page.locator("#resultsMeta").textContent(),
);
await page.locator("#clearFilters").click();
await page.waitForFunction(
() => document.querySelector("#resultsMeta")?.dataset.filteredCount === "7680",
);
await page.locator('#tech [data-technology="solar"]').click();
await page.waitForFunction(
() => document.querySelector("#resultsMeta")?.dataset.filteredCount === "3563",
);
gate(`${label}-${viewport.width}-solar-filter`, true, 3563);
await page.locator("#clearFilters").click();
await page.locator("#sortProjects").selectOption("updated_desc");
gate(
`${label}-${viewport.width}-sort-desc`,
(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort")) === "descending",
"descending",
);
await page.locator("#sortProjects").selectOption("updated_asc");
gate(
`${label}-${viewport.width}-sort-asc`,
(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort")) === "ascending",
"ascending",
);
await page.locator("#clearFilters").click();
const downloadPromise = page.waitForEvent("download");
await page.locator("#exportInline").click();
const download = await downloadPromise;
gate(
`${label}-${viewport.width}-csv-export`,
download.suggestedFilename().endsWith(".csv"),
download.suggestedFilename(),
);
const atlasLinks = await page.locator("a.atlaslink").count();
gate(`${label}-${viewport.width}-atlas-links`, atlasLinks > 0, atlasLinks);
if (label === "candidate") {
await page.locator("#federatedRelationshipOpen").click();
await page.waitForFunction(
() =>
document.querySelector("#federatedRelationshipHost")?.dataset
.federatedRelationshipState === "ready",
null,
{ timeout: 30_000 },
);
const lazy = {
module: requests.filter((path) =>
path.endsWith(`/${CANDIDATE_GENERATION}-federated-relationships.js`),
).length,
payload: requests.filter((path) =>
path.endsWith(`/${CANDIDATE_GENERATION}-relationship-governance-status.json`),
).length,
rows: await page.locator("#federatedRelationshipHost tbody tr").count(),
abstain: await page
.locator("#federatedRelationshipHost td", { hasText: "ABSTAIN" })
.count(),
};
gate(
`${label}-${viewport.width}-relationship-lazy-once`,
lazy.module === 1 && lazy.payload === 1,
lazy,
);
gate(
`${label}-${viewport.width}-relationship-abstention`,
lazy.rows === 3 && lazy.abstain === 3,
lazy,
);
}
gate(
`${label}-${viewport.width}-console-cors`,
consoleErrors.length === 0 && pageErrors.length === 0 && failed.length === 0,
{ consoleErrors, pageErrors, failed },
);
sessions.push({
label,
viewport,
ready_ms: readyMs,
core,
observed_capacity: observedCapacity,
expected_capacity: expectedCapacity,
requests: requests.length,
console_errors: consoleErrors.length,
page_errors: pageErrors.length,
failed_requests: failed.length,
});
await page.close();
}
const browser = await chromium.launch({ headless: true });
try {
for (const viewport of [
{ width: 1440, height: 1000 },
{ width: 390, height: 844 },
]) {
await observe(browser, "baseline", baseline, viewport);
await observe(browser, "candidate", candidate, viewport);
}
} catch (error) {
gate("browser-completion", false, error.stack || error.message);
} finally {
await browser.close();
}
const failures = checks.filter((check) => !check.pass);
const result = {
schema: "pipelinenews.v9-6-2-equivalence-report.v2",
generation: GENERATION,
candidate_generation: CANDIDATE_GENERATION,
source_commit: process.env.GITHUB_SHA,
workflow_run_id: process.env.GITHUB_RUN_ID,
playwright_version: "1.55.0",
correction: {
rejected_audit_generation: "202608282150",
repaired_candidate_generation: CANDIDATE_GENERATION,
baseline_capacity_display_mw: 356474,
candidate_capacity_precision_mw: 356474.09,
},
sessions,
checks,
summary: {
checks: checks.length,
passed: checks.length - failures.length,
failed: failures.length,
},
promotion_eligible: failures.length === 0,
state: {
candidate: "ARTIFACT_ONLY",
current_pointer_changed: false,
pages_changed: false,
catalogue_changed: false,
},
};
await writeFile(report, `${JSON.stringify(result, null, 2)}\n`);
process.stdout.write(`${JSON.stringify(result.summary)}\n`);
if (failures.length) process.exitCode = 1;
Transit Layer Availability Browser
A JavaScript module in the substation finder folder of Code Generator that draws UK metros trams root. It is built from the proof map class (`ProofMap`).
rendercode-generator / apps/substation-finder/Ps/202609040219-transit-layer-availability.browser.mjs · lines 1–257 of 257 · version 2026-09-04 02:19 · Entry point · pattern ProofMap (shared by 3 files)
- What it does
- It draws UK metros trams root. Defines capture, ProofMap. Uses libraries node:assert/strict, node:http, node:fs/promises, node:path, node:module. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'substation'): 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: Parquet file uk_metros_trams_root.parquet.
- Downstream impact
- Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
- What it achieves
- Defines `capture` and `ProofMap`. It responds to click events.
- Why it matters
- Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/.
- Application
- code-generator · apps/substation-finder/Ps · JavaScript module
- Uses
- node:assert/strict, node:http, node:fs/promises, node:path, node:module, node:url, playwright
- Used by
- linked from Code Generator — Substation Finder Page (link)
- Produces
- capture, ProofMap
- Defines here
- capture, ProofMap
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Ps/202609040219-transit-layer-availability.browser.mjs:1-257 · blob db76dd65a22712eb898a3db88514eadd4deef525 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
#!/usr/bin/env node
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile, stat } from 'node:fs/promises';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const require = createRequire(import.meta.url);
let playwright;
try {
playwright = require('playwright');
} catch {
/* An isolated Git worktree does not duplicate the 200 MB browser install.
CI resolves the package normally; this is the measured laptop checkout. */
playwright = require(path.resolve(ROOT, '..', '..', 'gridatlas-v9104-fullscreen',
'node_modules', 'playwright'));
}
const { chromium } = playwright;
const GENERATION = '202609040219';
const VIEWPORT = { width: 393, height: 852 };
const MIME = new Map([
['.html', 'text/html; charset=utf-8'],
['.js', 'text/javascript; charset=utf-8'],
['.mjs', 'text/javascript; charset=utf-8'],
['.json', 'application/json; charset=utf-8'],
['.css', 'text/css; charset=utf-8'],
['.wasm', 'application/wasm']
]);
const server = createServer(async (request, response) => {
try {
const requestPath = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
const relative = requestPath.replace(/^\/+/, '') || 'index.html';
let target = path.resolve(ROOT, relative);
if (!target.startsWith(`${ROOT}${path.sep}`) && target !== ROOT) {
response.writeHead(403).end('outside repository');
return;
}
if ((await stat(target)).isDirectory()) target = path.join(target, 'index.html');
const bytes = await readFile(target);
response.writeHead(200, {
'content-type': MIME.get(path.extname(target).toLowerCase()) || 'application/octet-stream',
'cache-control': 'no-store',
'access-control-allow-origin': '*'
});
response.end(bytes);
} catch {
response.writeHead(404).end('not found');
}
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const { port } = server.address();
const browser = await chromium.launch({ headless: true });
try {
const context = await browser.newContext({
viewport: VIEWPORT,
isMobile: true,
hasTouch: true,
deviceScaleFactor: 1
});
const page = await context.newPage();
const pageErrors = [];
const consoleErrors = [];
const requestFailures = [];
const metroResponses = [];
page.on('pageerror', (error) => pageErrors.push(String(error?.message || error)));
page.on('console', (message) => {
if (message.type() === 'error') consoleErrors.push(message.text());
});
page.on('requestfailed', (request) => {
requestFailures.push({ url: request.url(), error: request.failure()?.errorText || 'unknown' });
});
page.on('response', (response) => {
if (response.url().includes('uk_metros_trams_root.parquet')) {
metroResponses.push({ url: response.url(), status: response.status() });
}
});
/* Capture the real MapLibre instance without changing production bytes.
The library assigns its UMD export before either cartridge wraps Map. */
await page.addInitScript(() => {
let maplibreValue;
const capture = (value) => {
if (!value || typeof value.Map !== 'function' || value.Map.__gridatlasProofWrapped) return value;
const OriginalMap = value.Map;
function ProofMap(...args) {
const instance = Reflect.construct(OriginalMap, args,
new.target === ProofMap ? OriginalMap : new.target);
window.__GRIDATLAS_PROOF_MAP__ = instance;
return instance;
}
Object.setPrototypeOf(ProofMap, OriginalMap);
ProofMap.prototype = OriginalMap.prototype;
ProofMap.__gridatlasProofWrapped = true;
value.Map = ProofMap;
return value;
};
Object.defineProperty(window, 'maplibregl', {
configurable: true,
enumerable: true,
get: () => maplibreValue,
set: (value) => { maplibreValue = capture(value); }
});
});
const query = new URLSearchParams({
repd_ref: '155',
project: 'Markinch Biomass CHP Plant',
technology: 'biomass',
capacity_mw: '65',
latitude: '56.20118',
longitude: '-3.16226'
});
const url = `http://127.0.0.1:${port}/atlas/?${query}`;
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 120_000 });
await page.waitForFunction((generation) =>
document.documentElement.dataset.gridatlasGeneration === generation,
GENERATION, { timeout: 120_000 });
await page.waitForFunction(() =>
window.__GRIDATLAS_MODULES__?.menuBar?.installed === true
&& document.querySelectorAll('#gridatlas-menu-bar .gm-title').length === 6
&& window.__GRIDATLAS_PROOF_MAP__, null, { timeout: 120_000 });
/* Preserve the product acceptance which brought the user here: the grid
computation remains visible before this unrelated layer is exercised. */
await page.waitForFunction(() => document.body.textContent.includes('28.82 km'),
null, { timeout: 180_000 });
/* Arrival requests fullscreen without a user gesture. Chromium correctly
denies the native request after the shell has entered its CSS state; exit
that denied state, then exercise the same button with a real click. */
await page.evaluate(() => {
if (!document.fullscreenElement && document.body.classList.contains('fs-active')) {
window.exitFullscreen();
}
});
/* v9.104 already proves the shell's fullscreen button. This proof needs a
native user-gesture fullscreen while an arrival may be toggling the
shell's own button visibility, so use a proof-only gesture target. */
await page.evaluate(() => {
const trigger = document.createElement('button');
trigger.id = 'gridatlas-proof-fullscreen';
trigger.textContent = 'Proof fullscreen';
trigger.style.cssText = 'position:fixed;inset:40px auto auto 4px;z-index:2147483647';
trigger.addEventListener('click', () => document.getElementById('map-container').requestFullscreen());
document.body.appendChild(trigger);
});
await page.locator('#gridatlas-proof-fullscreen').focus();
await page.keyboard.press('Enter');
await page.waitForFunction(() => document.fullscreenElement?.id === 'map-container',
null, { timeout: 30_000 });
await page.evaluate(() => document.getElementById('gridatlas-proof-fullscreen')?.remove());
await page.getByRole('button', { name: 'Grid', exact: true }).click();
const tramProxy = page.locator('[data-gridatlas-layer-proxy="engine:tram"]');
await tramProxy.scrollIntoViewIfNeeded();
await tramProxy.click();
await page.waitForFunction(() => {
const original = document.querySelector('#scada-ui-container input[data-layer-id="tram"]');
const proxy = document.querySelector('[data-gridatlas-layer-proxy="engine:tram"]');
return original?.disabled && !original.checked && proxy?.disabled && !proxy.checked
&& proxy.getAttribute('aria-label') === 'Trams & Light Rail [EMPTY]';
}, null, { timeout: 180_000 });
const result = await page.evaluate(() => {
const map = window.__GRIDATLAS_PROOF_MAP__;
const source = map.getSource('src-metros');
const features = Array.isArray(source?._data?.features) ? source._data.features : [];
const propertyPresence = {};
const geometryTypes = {};
for (const feature of features) {
const geometryType = feature?.geometry?.type || '<missing>';
geometryTypes[geometryType] = (geometryTypes[geometryType] || 0) + 1;
for (const key of Object.keys(feature?.properties || {})) {
propertyPresence[key] = (propertyPresence[key] || 0) + 1;
}
}
const layerState = Object.fromEntries(['dlr', 'metro', 'tram'].map((id) => {
const original = document.querySelector(`#scada-ui-container input[data-layer-id="${id}"]`);
const proxy = document.querySelector(`[data-gridatlas-layer-proxy="engine:${id}"]`);
return [id, {
original_checked: original?.checked,
original_disabled: original?.disabled,
proxy_checked: proxy?.checked,
proxy_disabled: proxy?.disabled,
proxy_label: proxy?.getAttribute('aria-label'),
layer_type: map.getLayer(`l-${id}`)?.type,
visibility: map.getLayoutProperty(`l-${id}`, 'visibility'),
rendered_in_view: map.queryRenderedFeatures({ layers: [`l-${id}`] }).length
}];
}));
return {
generation: document.documentElement.dataset.gridatlasGeneration,
viewport: [innerWidth, innerHeight],
fullscreen_element: document.fullscreenElement?.id || '',
fullscreen_contains_menu: document.fullscreenElement
?.contains(document.getElementById('gridatlas-menu-bar')),
menus: [...document.querySelectorAll('#gridatlas-menu-bar .gm-title')]
.map((node) => node.textContent.trim()),
source_features: features.length,
geometry_types: geometryTypes,
property_presence: propertyPresence,
layer_state: layerState,
nearest_visible: document.body.textContent.includes('28.82 km')
};
});
assert.equal(result.generation, GENERATION);
assert.deepEqual(result.viewport, [393, 852]);
assert.equal(result.fullscreen_element, 'map-container');
assert.equal(result.fullscreen_contains_menu, true);
assert.deepEqual(result.menus, ['File', 'Edit', 'View', 'Scope', 'Grid', 'About']);
assert.equal(result.source_features, 7_829, 'the complete deployed partition was reconstructed');
assert.deepEqual(result.geometry_types, { LineString: 7_829 }, 'the runtime payload is entirely LineString');
assert.equal(result.property_presence.railway || 0, 0, 'the runtime projection retains no railway classifier');
for (const id of ['dlr', 'metro', 'tram']) {
assert.deepEqual(result.layer_state[id], {
original_checked: false,
original_disabled: true,
proxy_checked: false,
proxy_disabled: true,
proxy_label: `${id === 'dlr' ? 'DLR' : id === 'metro' ? 'UK Metro' : 'Trams & Light Rail'} [EMPTY]`,
layer_type: 'circle',
visibility: 'none',
rendered_in_view: 0
});
}
assert.equal(result.nearest_visible, true);
assert.ok(metroResponses.some((response) => response.status === 200),
'the production metro/tram Parquet answered successfully');
assert.deepEqual(pageErrors, [], `page errors: ${pageErrors.join(' | ')}`);
assert.deepEqual(consoleErrors, [], `console errors: ${consoleErrors.join(' | ')}`);
const materialFailures = requestFailures.filter(({ url: failedUrl }) =>
!/basemaps\.cartocdn\.com/.test(failedUrl));
assert.deepEqual(materialFailures, [], `material request failures: ${JSON.stringify(materialFailures)}`);
console.log(JSON.stringify({
status: 'PASS',
url,
pageErrors,
consoleErrors,
requestFailures,
metroResponses,
...result
}, null, 2));
await context.close();
} finally {
await browser.close();
await new Promise((resolve) => server.close(resolve));
}