GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atman

Build Highway Transport Repair and 3 more files

A Python command-line tool in the highway forensics folder of GridAtlas that reads UK motorways, UK trunk roads and UK primary roads, using SHA-256 from the GlobalGrid2050 repository.

640 lines of Python and JavaScript from gridatlas, in 4 files. Topic: Maps, GIS and field navigation. Section 616 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Verify V9 5 Search render · gridatlas / atman/202608301624-verify-v9-5-search.mjs lines 1–192
  2. Verify Atlas V9 storage · gridatlas / atman/202611132345-verify-atlas-v9.py lines 1–79
  3. Verify Streaming Roads render · gridatlas / atman/verify_streaming_roads.mjs lines 1–126
  4. Build Highway Transport Repair render · gridatlas / bootstrap/highway-forensics/build_highway_transport_repair.py lines 1–243

Verify V9 5 Search

A JavaScript module in the atman folder of GridAtlas that draws search proof, postcodes and the Renewable Energy Planning Database (REPD) register.

rendergridatlas / atman/202608301624-verify-v9-5-search.mjs · lines 1–192 of 192 · version 2026-08-30 16:24 · Entry point · pattern waitReady (shared by 3 files)

What it does
It draws search proof, postcodes and the REPD register. Defines invariant, waitReady, record, cleanPage, query. Uses libraries node:fs/promises, playwright. 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: postcodes, the REPD register.
Inputs & outputs
In: JSON file 202608301624-v9-5-search-proof.json.
Downstream impact
Used directly by 1 file: GridAtlas Verify Live Workflow (gridatlas).
What it achieves
It cleans page (`cleanPage`) and is built from the wait ready helper (`waitReady`) and the query step (`query`). Its name says it verifies search. Defines `invariant`, `waitReady`, `record` and 2 more.
Why it matters
Run by GridAtlas Verify Live Workflow.
Application
gridatlas · atman · JavaScript module
Uses
node:fs/promises, playwright
Used by
run by GridAtlas Verify Live Workflow (workflow run)
Produces
invariant, waitReady, record, cleanPage, query
Defines here
invariant, waitReady, record, cleanPage, query
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atman/202608301624-verify-v9-5-search.mjs:1-192 · blob ef8307dd67b785648ccac87422ef962ac601fc0b · 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: production_core
import fs from 'node:fs/promises';
import { chromium } from 'playwright';

const base = String(process.env.GRIDATLAS_URL || 'http://127.0.0.1:4173/gridatlas/atlas/');
const output = process.env.OUTPUT || 'work/202608301624-v9-5-search-proof.json';
const expectedCompositionGeneration = process.env.EXPECTED_GENERATION || '202608301624';
const expectedSearchGeneration = process.env.EXPECTED_SEARCH_GENERATION || '202608301624';

const proof = {
  schema: 'gridatlas.v9-5-global-search-proof.v2',
  composition_generation: expectedCompositionGeneration,
  search_cartridge_generation: expectedSearchGeneration,
  url: base,
  status: 'RUNNING',
  tests: [],
  console_errors: [],
  failure: null
};

function invariant(condition, message) {
  if (!condition) throw new Error(message);
}

async function waitReady(page) {
  await page.waitForFunction(expected => {
    const search = window.__GRIDATLAS_PLACE_SEARCH__;
    const atlas = window.__GRIDATLAS_ATLAS__;
    return search?.ready === true &&
      search?.generation === expected.search &&
      atlas?.generation === expected.composition &&
      atlas?.loaded_cartridges?.some(item => item.id === 'uk-gazetteer-flyto') &&
      window.__GRIDATLAS_V9_MAP__;
  }, { composition: expectedCompositionGeneration, search: expectedSearchGeneration }, { timeout: 120_000 });
}

async function record(name, action) {
  const row = { name, status: 'RUNNING' };
  proof.tests.push(row);
  try {
    row.evidence = await action();
    row.status = 'PASS';
    console.log(JSON.stringify({ test: name, status: 'PASS', evidence: row.evidence }));
  } catch (error) {
    row.status = 'FAIL';
    row.message = String(error?.message || error);
    throw error;
  }
}

async function cleanPage(page) {
  await page.goto(`${base}?proof=${Date.now()}`, { waitUntil: 'domcontentloaded', timeout: 120_000 });
  await waitReady(page);
}

async function query(page, text, { sequential = false } = {}) {
  const input = page.locator('#search-input');
  await input.fill('');
  if (sequential) await input.pressSequentially(text, { delay: 220 });
  else await input.fill(text);
  await input.press('Enter');
  await page.waitForFunction(expected => window.__GRIDATLAS_PLACE_SEARCH__?.last_query === expected, text, { timeout: 120_000 });
  await page.locator('#search-results').waitFor({ state: 'visible', timeout: 120_000 });
}

const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ viewport: { width: 390, height: 844 } });
const page = await context.newPage();
page.on('console', message => {
  if (message.type() === 'error') proof.console_errors.push(message.text());
});
page.on('pageerror', error => proof.console_errors.push(String(error?.message || error)));

try {
  await record('composition retains the independently versioned search cartridge', async () => {
    await cleanPage(page);
    const state = await page.evaluate(() => ({
      atlas: window.__GRIDATLAS_ATLAS__,
      search_generation: window.__GRIDATLAS_PLACE_SEARCH__?.generation,
      search_ready: window.__GRIDATLAS_PLACE_SEARCH__?.ready
    }));
    invariant(state.atlas.generation === expectedCompositionGeneration, 'composition generation mismatch');
    invariant(state.search_generation === expectedSearchGeneration, 'search cartridge generation mismatch');
    invariant(state.search_ready === true, 'search cartridge is not ready');
    invariant(state.atlas.loaded_cartridges.some(item => item.id === 'uk-gazetteer-flyto'), 'search cartridge is not loaded');
    return state;
  });

  await record('direct REPD 13599 deep link flies to Beacon Fen', async () => {
    await page.goto(`${base}?repd_ref=13599`, { waitUntil: 'domcontentloaded', timeout: 120_000 });
    await waitReady(page);
    await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.status === 'RESOLVED', null, { timeout: 120_000 });
    await page.locator('.maplibregl-popup-content').filter({ hasText: 'Beacon Fen Energy Park' }).waitFor({ state: 'visible', timeout: 30_000 });
    const state = await page.evaluate(() => ({
      deep_link: window.__GRIDATLAS_PLACE_SEARCH__.deep_link,
      selection: window.__GRIDATLAS_PLACE_SEARCH__.last_selection,
      url: location.href
    }));
    invariant(state.deep_link.repd_ref === '13599' && state.deep_link.mapped === true, 'direct 13599 did not map');
    invariant(new URL(state.url).searchParams.get('repd_ref') === '13599', 'direct deep link lost identity');
    return state;
  });

  await record('SW1A 1AA typed character-by-character keeps final postcode result', async () => {
    await cleanPage(page);
    await query(page, 'SW1A 1AA', { sequential: true });
    const postcode = page.locator('.search-result-item[data-location-kind="postcode"]').first();
    await postcode.waitFor({ state: 'visible', timeout: 60_000 });
    await page.waitForTimeout(3000);
    invariant(await postcode.isVisible(), 'final postcode was overwritten by a stale response');
    const kinds = await page.locator('.search-result-item[data-location-kind]').evaluateAll(items => items.map(item => item.dataset.locationKind));
    invariant(kinds[0] === 'postcode', `final location was ${kinds[0] || 'missing'}, not postcode`);
    invariant((await postcode.textContent() || '').includes('SW1A 1AA'), 'final visible postcode label is wrong');
    await postcode.click();
    await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection?.kind === 'postcode' && window.__GRIDATLAS_PLACE_SEARCH__.last_location_selection.mapped === true, null, { timeout: 30_000 });
    const selected = await page.evaluate(() => ({
      location: window.__GRIDATLAS_PLACE_SEARCH__.last_location_selection,
      popup: document.querySelector('.maplibregl-popup-content')?.textContent || '',
      url: location.href
    }));
    invariant(!new URL(selected.url).searchParams.has('repd_ref'), 'postcode selection claimed REPD identity');
    invariant(selected.popup.includes('Location only · postcodes.io · no project identity claimed'), 'postcode popup provenance is wrong');
    return { kinds, selected };
  });

  await record('Truro flies to a UK location', async () => {
    await query(page, 'Truro');
    const result = page.locator('.search-result-item[data-location-kind="place"]').filter({ hasText: 'Truro' }).first();
    await result.waitFor({ state: 'visible', timeout: 60_000 });
    await result.click();
    await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection?.kind === 'place' && window.__GRIDATLAS_PLACE_SEARCH__.last_location_selection.mapped === true, null, { timeout: 30_000 });
    const selected = await page.evaluate(() => window.__GRIDATLAS_PLACE_SEARCH__.last_location_selection);
    invariant(/truro/i.test(selected.label), `unexpected Truro label ${selected.label}`);
    invariant(!new URL(page.url()).searchParams.has('repd_ref'), 'Truro selection claimed REPD identity');
    return selected;
  });

  await record('Beacon Fen REPD 13599 is first and sets identity', async () => {
    await query(page, 'Beacon Fen');
    const exact = page.locator('.search-result-item[data-repd-ref="13599"]').first();
    await exact.waitFor({ state: 'visible', timeout: 60_000 });
    const firstRef = await page.locator('.search-result-item').first().getAttribute('data-repd-ref');
    invariant(firstRef === '13599', `first result is ${firstRef}, expected 13599`);
    await exact.click();
    await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.last_selection?.repd_ref === '13599', null, { timeout: 30_000 });
    invariant(new URL(page.url()).searchParams.get('repd_ref') === '13599', 'Beacon Fen did not set repd_ref=13599');
    return await page.evaluate(() => window.__GRIDATLAS_PLACE_SEARCH__.last_selection);
  });

  await record('Oxford, England, UK flies without project identity', async () => {
    await query(page, 'Oxford, England, UK');
    const result = page.locator('.search-result-item[data-location-kind]').filter({ hasText: 'Oxford' }).first();
    await result.waitFor({ state: 'visible', timeout: 60_000 });
    await result.click();
    await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection?.mapped === true, null, { timeout: 30_000 });
    const selected = await page.evaluate(() => window.__GRIDATLAS_PLACE_SEARCH__.last_location_selection);
    invariant(selected.latitude > 51.5 && selected.latitude < 52.0, `Oxford latitude out of range ${selected.latitude}`);
    invariant(selected.longitude > -1.6 && selected.longitude < -0.8, `Oxford longitude out of range ${selected.longitude}`);
    invariant(!new URL(page.url()).searchParams.has('repd_ref'), 'Oxford selection claimed REPD identity');
    return selected;
  });

  await record('Delhi flies through the global gazetteer', async () => {
    await query(page, 'Delhi');
    const result = page.locator('.search-result-item[data-location-kind="global_place"]').filter({ hasText: 'Delhi' }).first();
    await result.waitFor({ state: 'visible', timeout: 90_000 });
    await result.click();
    await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.last_location_selection?.kind === 'global_place' && window.__GRIDATLAS_PLACE_SEARCH__.last_location_selection.mapped === true, null, { timeout: 30_000 });
    const selected = await page.evaluate(() => window.__GRIDATLAS_PLACE_SEARCH__.last_location_selection);
    invariant(selected.latitude > 27.5 && selected.latitude < 29.8, `Delhi latitude out of range ${selected.latitude}`);
    invariant(selected.longitude > 76.0 && selected.longitude < 78.5, `Delhi longitude out of range ${selected.longitude}`);
    invariant(selected.provider === 'Nominatim / OpenStreetMap', `unexpected global provider ${selected.provider}`);
    invariant(!new URL(page.url()).searchParams.has('repd_ref'), 'Delhi selection claimed REPD identity');
    return selected;
  });

  proof.status = 'PASS';
} catch (error) {
  proof.status = 'FAIL';
  proof.failure = String(error?.stack || error);
  proof.runtime_state = await page.evaluate(() => ({
    atlas: window.__GRIDATLAS_ATLAS__ || null,
    search: window.__GRIDATLAS_PLACE_SEARCH__ || null,
    transport: window.__GRIDATLAS_MAP_READY__ || null,
    ready_state: document.readyState
  })).catch(() => null);
  process.exitCode = 1;
} finally {
  await browser.close();
  await fs.mkdir(output.includes('/') ? output.slice(0, output.lastIndexOf('/')) : '.', { recursive: true });
  await fs.writeFile(output, JSON.stringify(proof, null, 2) + '\n');
  console.log(JSON.stringify({ status: proof.status, tests: proof.tests.map(test => ({ name: test.name, status: test.status })), output }));
}

Verify Atlas V9

A Python command-line tool in the atman folder of GridAtlas that reads the Renewable Energy Planning Database (REPD) register, using SHA-256.

storagegridatlas / atman/202611132345-verify-atlas-v9.py · lines 1–79 of 79 · version 2026-11-13 23:45 · Entry point

What it does
It loads the REPD register. Defines sha, main. Uses libraries argparse, hashlib, importlib.util, json, pathlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (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. Domain terms in the code: the REPD register.
Inputs & outputs
In: DuckDB queries; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Its name says it verifies atlas. Defines `sha`. It accepts `--site`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · atman · Python CLI
Uses
argparse, hashlib, importlib.util, json, pathlib, duckdb
Used by
none found
Produces
sha, main
Defines here
sha, 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 atman/202611132345-verify-atlas-v9.py:1-79 · blob fe183c27e75d150da327dc93325197cf2277343f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path

import duckdb

GENERATION = "202611132345"
# The address/fly-to UI cartridge is unchanged by a data-only release; only the data generation moves.
CARTRIDGE_GENERATION = "202608290716"
EXPECTED_COLUMNS = [
    ("repd_ref", "VARCHAR"), ("name", "VARCHAR"), ("repd_address_raw", "VARCHAR"),
    ("repd_address_display", "VARCHAR"), ("repd_postcode_raw", "VARCHAR"),
    ("repd_postcode", "VARCHAR"), ("postcode_valid", "BOOLEAN"), ("county", "VARCHAR"),
    ("region", "VARCHAR"), ("country", "VARCHAR"), ("planning_authority", "VARCHAR"),
    ("planning_application_reference", "VARCHAR"), ("repd_operator_or_applicant", "VARCHAR"),
    ("applicant_publication_state", "VARCHAR"), ("technology", "VARCHAR"),
    ("repd_technology", "VARCHAR"), ("status", "VARCHAR"), ("capacity_mw", "DOUBLE"),
    ("longitude", "DOUBLE"), ("latitude", "DOUBLE"), ("source_record_updated", "VARCHAR"),
    ("source_row", "INTEGER"), ("source_row_sha256", "VARCHAR")
]

def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--site", required=True)
    args = parser.parse_args()
    site = Path(args.site)
    data = site / "data"
    manifest_path = data / f"repd_v9_manifest_{GENERATION}.json"
    registry_path = data / f"repd_browser_registry_{GENERATION}.json"
    parquet_path = data / f"repd_projects_{GENERATION}.parquet"
    required = [site / "index.html", site / "assets" / "atlas-v9.mjs", site / "assets" / "atlas-v9.css", site / "cartridges" / f"{CARTRIDGE_GENERATION}-repd-address-flyto.mjs", manifest_path, registry_path, parquet_path]
    missing = [str(path.relative_to(site)) for path in required if not path.is_file()]
    if missing:
        raise SystemExit(f"missing closure: {missing}")
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    registry = json.loads(registry_path.read_text(encoding="utf-8"))
    if manifest["runtime"]["duckdb"] != "1.3.2" or manifest["runtime"]["parquet_compression"] != "ZSTD":
        raise SystemExit("DuckDB/ZSTD pin failed")
    if sha(parquet_path) != manifest["parquet"]["sha256"] or parquet_path.stat().st_size != manifest["parquet"]["bytes"]:
        raise SystemExit("Parquet identity failed")
    if sha(registry_path) != manifest["browser_registry"]["sha256"] or registry_path.stat().st_size != manifest["browser_registry"]["bytes"]:
        raise SystemExit("registry identity failed")
    con = duckdb.connect()
    schema = [(row[0], row[1]) for row in con.execute(f"DESCRIBE SELECT * FROM read_parquet('{parquet_path}')").fetchall()]
    if schema != EXPECTED_COLUMNS:
        raise SystemExit(f"typed schema drift: {schema}")
    stats = con.execute(f"SELECT count(*), count(DISTINCT repd_ref), count(repd_address_display), count(repd_postcode_raw), count(*) FILTER (WHERE postcode_valid), count(*) FILTER (WHERE applicant_publication_state='WITHHELD_POSSIBLE_INDIVIDUAL') FROM read_parquet('{parquet_path}')").fetchone()
    case = con.execute(f"SELECT name, repd_address_display, repd_postcode, county, status, repd_operator_or_applicant FROM read_parquet('{parquet_path}') WHERE repd_ref='16135'").fetchone()
    con.close()
    if stats[0] != stats[1] or stats[0] != len(registry["records"]) or stats[0] != manifest["closure"]["rows"]:
        raise SystemExit(f"row closure failed: {stats}")
    if stats[2] < 10000 or stats[3] < 8500 or stats[4] < 8000:
        raise SystemExit(f"location completeness floor failed: {stats}")
    if case != ("Prologis DC4 Marston Gate, Brockley Way - Solar Panels", "Prologis Marston Gate DC4, Unit 1 Brockley Way, Brogborough", "MK43 0ZY", "Bedfordshire", "awaiting construction", "Prologis UK Limited"):
        raise SystemExit(f"golden case failed: {case}")
    if manifest["v8_oracle"]["oracle_features"] != 10784 or manifest["v8_oracle"]["match_ratio"] < 0.95 or not manifest["v8_untouched"]:
        raise SystemExit("V8 oracle proof failed")
    html = (site / "index.html").read_text(encoding="utf-8")
    app = (site / "assets" / "atlas-v9.mjs").read_text(encoding="utf-8")
    cartridge = (site / "cartridges" / f"{CARTRIDGE_GENERATION}-repd-address-flyto.mjs").read_text(encoding="utf-8")
    required_text = ["GRID ATLAS V9", "Official REPD address", "ATLAS_V9_REPD_ADDRESS_FLYTO_CONTRACT", "mountRepdAddressFlyTo", "DIRECT_PROJECT_MATCH"]
    joined = html + app + cartridge
    absent = [item for item in required_text if item not in joined]
    if absent:
        raise SystemExit(f"UI contract text missing: {absent}")
    forbidden = ["nominatim", "reverse-geocode", "verified owner", "confirmed owner"]
    found = [item for item in forbidden if item in joined.lower()]
    if found:
        raise SystemExit(f"forbidden inference/provider found: {found}")
    print(json.dumps({"classification": "VERIFIED", "rows": stats[0], "addresses": stats[2], "postcodes": stats[3], "valid_postcodes": stats[4], "withheld_possible_individuals": stats[5], "v8_match_ratio": manifest["v8_oracle"]["match_ratio"], "golden_repd_ref": "16135"}, sort_keys=True))

if __name__ == "__main__":
    main()

Verify Streaming Roads

A JavaScript module in the atman folder of GridAtlas that reads streaming road proof, UK motorways, UK trunk roads and UK primary roads.

rendergridatlas / atman/verify_streaming_roads.mjs · lines 1–126 of 126 · Entry point

What it does
It loads streaming road proof, UK motorways, UK trunk roads and UK primary roads. Uses libraries node:fs/promises, playwright. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file streaming-road-proof.json; GeoJSON file uk_motorways.geojson; GeoJSON file uk_trunk_roads.geojson; GeoJSON file uk_primary_roads.geojson; DuckDB queries.
Downstream impact
Used directly by 1 file: GridAtlas Verify Live Workflow (gridatlas).
What it achieves
Its name says it verifies streaming roads.
Why it matters
Run by GridAtlas Verify Live Workflow.
Application
gridatlas · atman · JavaScript module
Uses
node:fs/promises, playwright
Used by
run by GridAtlas Verify Live Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atman/verify_streaming_roads.mjs:1-126 · blob 9c4cfdece8409aa423755c53680e14ad60e22682 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import fs from 'node:fs/promises';
import { chromium } from 'playwright';

const url = process.env.GRIDATLAS_URL;
const expectedGeneration = process.env.EXPECTED_GENERATION;
const output = process.env.OUTPUT || 'work/streaming-road-proof.json';
if (!url || !expectedGeneration) throw new Error('GRIDATLAS_URL and EXPECTED_GENERATION are required');

const expected = new Map([
  ['motorways', { rows: 17713, path: '/uk_motorways.geojson' }],
  ['trunk_roads', { rows: 130228, path: '/uk_trunk_roads.geojson' }],
  ['primary_roads', { rows: 163790, path: '/uk_primary_roads.geojson' }],
]);
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
const page = await context.newPage();
const cdp = await context.newCDPSession(page);
const consoleErrors = [];
page.on('console', message => { if (message.type() === 'error') consoleErrors.push(message.text()); });
page.on('pageerror', error => consoleErrors.push(String(error?.message || error)));

await page.goto(`${url}${url.includes('?') ? '&' : '?'}streaming-roads=${Date.now()}`, { waitUntil: 'domcontentloaded', timeout: 120000 });
await page.waitForFunction(generation => (
  window.__GRIDATLAS_ATLAS__?.generation === generation &&
  window.__GRIDATLAS_V9_MAP__ &&
  document.querySelectorAll('#scada-ui-container input[data-layer-id]').length > 0
), expectedGeneration, { timeout: 120000 });

const composition = await page.evaluate(() => window.__GRIDATLAS_ATLAS__);
if (JSON.stringify(composition.cartridge_order) !== JSON.stringify(['streaming-parquet-bridge', 'uk-gazetteer-flyto'])) {
  throw new Error(`unexpected cartridge order: ${JSON.stringify(composition.cartridge_order)}`);
}
await page.waitForFunction(() => {
  const state = window.__GRIDATLAS_MAP_READY__;
  return state?.runtime_prewarm?.completed === true || state?.runtime_prewarm?.failed;
}, null, { timeout: 120000 });
const prewarm = await page.evaluate(() => window.__GRIDATLAS_MAP_READY__?.runtime_prewarm);
if (!prewarm?.completed) throw new Error(`DuckDB runtime prewarm failed: ${JSON.stringify(prewarm)}`);

const results = [];
let failures = 0;
for (const [id, target] of expected) {
  const selector = `#scada-ui-container input[data-layer-id="${id}"]`;
  const exists = await page.locator(selector).count();
  if (exists !== 1) throw new Error(`${id}: expected one layer control, found ${exists}`);
  const started = performance.now();
  await page.locator(selector).check({ force: true });
  await page.waitForFunction(layerId => {
    const label = document.querySelector(`#lbl-${CSS.escape(layerId)}`)?.textContent || '';
    return /\[(OK|EMPTY|FAIL)\]/.test(label);
  }, id, { timeout: 60000 });
  const terminal = await page.evaluate(layerId => {
    const map = window.__GRIDATLAS_V9_MAP__;
    const mapLayer = map?.getLayer(`l-${layerId}`);
    const sourceId = mapLayer?.source || null;
    const label = document.querySelector(`#lbl-${CSS.escape(layerId)}`)?.textContent || '';
    return { sourceId, label };
  }, id);
  if (terminal.sourceId && terminal.label.includes('[OK]')) {
    await page.waitForFunction(sourceId => {
      try { return window.__GRIDATLAS_V9_MAP__?.isSourceLoaded(sourceId) === true; } catch { return false; }
    }, terminal.sourceId, { timeout: 60000 });
  }
  const seconds = (performance.now() - started) / 1000;
  await page.waitForTimeout(250);
  await cdp.send('HeapProfiler.collectGarbage');
  const heapMb = (await cdp.send('Runtime.getHeapUsage')).usedSize / 1e6;
  const state = await page.evaluate(({ layerId, pathname }) => {
    const map = window.__GRIDATLAS_V9_MAP__;
    const mapLayer = map?.getLayer(`l-${layerId}`);
    const sourceId = mapLayer?.source || null;
    let loaded = false;
    let rendered = 0;
    try {
      loaded = Boolean(sourceId && map.isSourceLoaded(sourceId));
      rendered = map.queryRenderedFeatures({ layers: [`l-${layerId}`] }).length;
    } catch {}
    const transport = window.__GRIDATLAS_MAP_READY__;
    const entry = Object.entries(transport?.loaded_on_demand || {}).find(([key]) => key.endsWith(pathname));
    return {
      sourceId,
      loaded,
      rendered,
      rows: entry?.[1]?.rows ?? -1,
      parquet: entry?.[1]?.parquet ?? null,
      streamedResponses: transport?.streamed_responses ?? -1,
      releasedPayloads: transport?.released_payloads ?? -1,
      streamFailures: transport?.stream_failures || [],
      label: document.querySelector(`#lbl-${CSS.escape(layerId)}`)?.textContent || '',
    };
  }, { layerId: id, pathname: target.path });
  const bad = (
    !state.label.includes('[OK]') ||
    !state.loaded ||
    state.rows !== target.rows ||
    state.streamedResponses < 1 ||
    state.releasedPayloads < state.streamedResponses ||
    state.streamFailures.length > 0 ||
    seconds > 15 ||
    heapMb > 400
  );
  if (bad) failures += 1;
  results.push({ id, expected_rows: target.rows, seconds, heap_mb: heapMb, ...state, verdict: bad ? 'FAIL' : 'PASS' });
  await page.locator(selector).uncheck({ force: true }).catch(() => {});
  await page.waitForTimeout(500);
  await cdp.send('HeapProfiler.collectGarbage');
}

const report = {
  schema: 'gridatlas.streaming-road-proof.v1',
  url,
  expected_generation: expectedGeneration,
  composition,
  runtime_prewarm: prewarm,
  results,
  console_errors: consoleErrors,
  failures,
  status: failures ? 'FAIL' : 'PASS',
};
await fs.mkdir(output.split('/').slice(0, -1).join('/') || '.', { recursive: true });
await fs.writeFile(output, JSON.stringify(report, null, 2) + '\n');
console.log('| layer | rows | loaded | seconds | heap MB | cache released | label | verdict |');
console.log('|---|---:|---:|---:|---:|---:|---|---|');
for (const row of results) console.log(`| ${row.id} | ${row.rows} | ${row.loaded} | ${row.seconds.toFixed(1)} | ${row.heap_mb.toFixed(0)} | ${row.releasedPayloads}/${row.streamedResponses} | ${row.label.replaceAll('|', '/')} | ${row.verdict} |`);
await browser.close();
process.exit(failures ? 1 : 0);

Build Highway Transport Repair

A Python command-line tool in the highway forensics folder of GridAtlas that reads UK motorways, UK trunk roads and UK primary roads, using SHA-256 from the GlobalGrid2050 repository.

rendergridatlas / bootstrap/highway-forensics/build_highway_transport_repair.py · lines 1–243 of 243 · Entry point · pattern write_atomic (shared by 2 files)

What it does
It loads UK motorways, UK trunk roads, UK primary roads and REPD master. Defines 9 functions or classes, including BuildError, require, read_json, canonical_json, sha256_bytes. Uses libraries __future__, argparse, hashlib, json, os. 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 (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: data source: globalgrid2050 data; GeoJSON file uk_motorways.geojson; GeoJSON file uk_trunk_roads.geojson; GeoJSON file uk_primary_roads.geojson; JSON file repd_master.json; JSON file heavy_emitters_uk.json; JSON file current.json; DuckDB queries.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It builds error (`BuildError`), reads JSON (`read_json`) and writes atomic (`write_atomic`). Build the GridAtlas v9.5 highway transport repair as one hashed cartridge. It accepts `--generation`, `--current` and `--shell-bridge`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · bootstrap/highway-forensics · Python CLI
Uses
__future__, argparse, hashlib, json, os, re, pathlib, typing
Used by
none found
Produces
BuildError, require, read_json, canonical_json, sha256_bytes, write_atomic, patch_bridge, make_contract, main
Defines here
BuildError, require, read_json, canonical_json, sha256_bytes, write_atomic, patch_bridge, make_contract, 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 bootstrap/highway-forensics/build_highway_transport_repair.py:1-243 · blob 9e8326233fdd61588d6017deff4997f9aa6c023f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Build the GridAtlas v9.5 highway transport repair as one hashed cartridge.

The immutable shell is never edited. The existing map bridge is copied from the
frozen shell, patched deterministically, and installed through atlas/current.json.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
from pathlib import Path
from typing import Any

CVAA_SHA = "d2ebc01f6eab41f2a84b0c53c4cfae0d2625ec5e"
GLOBALGRID_SHA = "6afd5dea721648e3ef14d5705d9f2dc3589af100"
CARTRIDGE_ID = "highway-static-transport"
REPLACE_SCRIPT = "202608292311-maplibre-worker-bridge.js"
GEN_RE = re.compile(r"^[0-9]{12}$")
STATIC_NAMES = (
    "uk_motorways.geojson",
    "uk_trunk_roads.geojson",
    "uk_primary_roads.geojson",
)

class BuildError(RuntimeError):
    pass

def require(condition: bool, message: str) -> None:
    if not condition:
        raise BuildError(message)

def read_json(path: Path) -> dict[str, Any]:
    require(path.is_file(), f"missing JSON: {path}")
    value = json.loads(path.read_text(encoding="utf-8"))
    require(isinstance(value, dict), f"JSON root must be object: {path}")
    return value

def canonical_json(value: dict[str, Any]) -> str:
    return json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n"

def sha256_bytes(value: bytes) -> str:
    return hashlib.sha256(value).hexdigest()

def write_atomic(path: Path, content: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(f".{path.name}.tmp-{os.getpid()}")
    tmp.write_text(content, encoding="utf-8", newline="\n")
    tmp.replace(path)

def patch_bridge(source: str, generation: str) -> str:
    original = source
    source, n = re.subn(r"const GENERATION = '[0-9]{12}';", f"const GENERATION = '{generation}';", source, count=1)
    require(n == 1, "immutable bridge generation marker missing")
    duckdb_line = "  const DUCKDB_MODULE = 'https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/+esm';\n"
    require(source.count(duckdb_line) == 1, "immutable bridge DuckDB marker missing")
    static_block = f"""  const HIGHWAY_SOURCE_COMMIT = '{GLOBALGRID_SHA}';
  const HIGHWAY_STATIC = new Map([
    ['uk_motorways.geojson', 'https://raw.githubusercontent.com/Ventusltd/globalgrid2050/{GLOBALGRID_SHA}/uk_motorways.geojson'],
    ['uk_trunk_roads.geojson', 'https://raw.githubusercontent.com/Ventusltd/globalgrid2050/{GLOBALGRID_SHA}/uk_trunk_roads.geojson'],
    ['uk_primary_roads.geojson', 'https://raw.githubusercontent.com/Ventusltd/globalgrid2050/{GLOBALGRID_SHA}/uk_primary_roads.geojson']
  ]);
"""
    source = source.replace(duckdb_line, duckdb_line + static_block, 1)
    architecture_marker = "      analytical_search_duckdb_retained: true\n"
    require(source.count(architecture_marker) == 1, "bridge architecture marker missing")
    source = source.replace(architecture_marker, architecture_marker + "      visual_highways_static_geojson: true,\n" + "      primary_roads_duckdb_rehydration: false\n", 1)
    source = source.replace("      analytical_search_duckdb_retained: true\n      visual_highways_static_geojson:", "      analytical_search_duckdb_retained: true,\n      visual_highways_static_geojson:", 1)
    state_marker = "    loaded_on_demand: {},\n"
    require(source.count(state_marker) == 1, "bridge state marker missing")
    source = source.replace(state_marker, state_marker + "    highway_static_requests: 0,\n" + "    highway_static_sources: {},\n", 1)
    legacy_function_end = """  function legacyStem(pathname) {
    const name = decodeURIComponent(pathname.split('/').pop() || '').toLowerCase();
    if (name === 'repd_master.json') return 'repd_master_v8_oracle';
    if (name === 'heavy_emitters_uk.json') return 'heavy_emitters_uk';
    if (name.endsWith('.geojson')) return name.slice(0, -8);
    return '';
  }
"""
    require(source.count(legacy_function_end) == 1, "legacyStem block changed unexpectedly")
    helper = """
  function highwayStatic(pathname) {
    const name = decodeURIComponent(pathname.split('/').pop() || '').toLowerCase();
    const url = HIGHWAY_STATIC.get(name);
    return url ? { name, url } : null;
  }
"""
    source = source.replace(legacy_function_end, legacy_function_end + helper, 1)
    fetch_marker = """  window.fetch = async function gridAtlasMaplibreWorkerFetch(input, init = undefined) {
    const pathname = requestPath(input);
    const readyKey = mapReadyKey(pathname);

"""
    require(source.count(fetch_marker) == 1, "window.fetch bridge marker missing")
    static_fetch = """  window.fetch = async function gridAtlasMaplibreWorkerFetch(input, init = undefined) {
    const pathname = requestPath(input);
    const readyKey = mapReadyKey(pathname);
    const highway = highwayStatic(pathname);

    if (highway) {
      state.highway_static_requests += 1;
      state.highway_static_sources[highway.name] = {
        source_commit: HIGHWAY_SOURCE_COMMIT,
        url: highway.url,
        delivery: 'PINNED_V8_STATIC_GEOJSON',
        duckdb: false
      };
      if (init?.signal?.aborted) throw new DOMException('Aborted', 'AbortError');
      const response = await nativeFetch(highway.url, { ...(init || {}), cache: 'force-cache', mode: 'cors' });
      invariant(response.ok, `${highway.name} static HTTP ${response.status}`);
      return response;
    }

"""
    source = source.replace(fetch_marker, static_fetch, 1)
    require(source != original, "bridge patch made no changes")
    for name in STATIC_NAMES:
        require(name in source, f"missing static source {name}")
    require("table.toArray().map" in source, "analytical DuckDB fallback was lost")
    require("primary_roads_duckdb_rehydration: false" in source, "repair contract missing")
    return source

def make_contract(generation: str, cartridge_sha: str) -> str:
    urls = {name: f"https://raw.githubusercontent.com/Ventusltd/globalgrid2050/{GLOBALGRID_SHA}/{name}" for name in STATIC_NAMES}
    payload = {
        "schema": "gridatlas.highway-static-transport-contract.v1",
        "generation": generation,
        "version": "v9.5",
        "cartridge_id": CARTRIDGE_ID,
        "cartridge_sha256": cartridge_sha,
        "replace_script": REPLACE_SCRIPT,
        "source_repository": "Ventusltd/globalgrid2050",
        "source_commit": GLOBALGRID_SHA,
        "sources": urls,
        "transport": "PINNED_V8_STATIC_GEOJSON",
        "duckdb_for_visual_highways": False,
        "analytical_duckdb_fallback_retained": True,
        "immutable_shell_mutated": False,
        "full_application_copies_created": 0,
    }
    return "export default " + json.dumps(payload, indent=2, sort_keys=True) + ";\n"

def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--generation", required=True)
    parser.add_argument("--current", default="atlas/current.json")
    parser.add_argument("--shell-bridge", default="atlas/releases/202608300453-atlas-v9/202608292311-maplibre-worker-bridge.js")
    parser.add_argument("--report", required=True)
    args = parser.parse_args()
    generation = args.generation
    require(bool(GEN_RE.fullmatch(generation)), "generation must be UTC YYYYMMDDHHMM")
    current_path = Path(args.current)
    current = read_json(current_path)
    require(current.get("schema") == "gridatlas.current.v2", "unexpected current schema")
    require(current.get("architecture") == "IMMUTABLE_SHELL_PLUS_HASHED_CARTRIDGES", "composition architecture changed")
    require(current.get("composition_version") == "v9.5", "not a v9.5 composition")
    require(current.get("release_id") == "202608300453-atlas-v9", "unexpected shell")
    require(current.get("contracts", {}).get("shell_mutation_forbidden") is True, "shell not frozen")
    existing = next((item for item in current.get("cartridges", []) if item.get("id") == CARTRIDGE_ID), None)
    if existing:
        existing_path = Path("atlas") / str(existing["path"]).removeprefix("./")
        require(existing_path.is_file(), f"installed cartridge missing: {existing_path}")
        require(sha256_bytes(existing_path.read_bytes()) == existing.get("sha256"), "installed cartridge hash mismatch")
        report = {"schema": "gridatlas.highway-transport-build.v1", "status": "ALREADY_INSTALLED", "changed": False, "generation": current["generation"], "composition_id": current["composition_id"], "cartridge": existing, "full_application_copies_created": 0, "shell_mutated": False}
        write_atomic(Path(args.report), canonical_json(report))
        print(json.dumps(report, sort_keys=True))
        return 0
    shell_bridge_path = Path(args.shell_bridge)
    require(shell_bridge_path.is_file(), f"immutable bridge missing: {shell_bridge_path}")
    shell_bridge = shell_bridge_path.read_text(encoding="utf-8")
    shell_bridge_sha = sha256_bytes(shell_bridge.encode("utf-8"))
    cartridge_text = patch_bridge(shell_bridge, generation)
    cartridge_sha = sha256_bytes(cartridge_text.encode("utf-8"))
    cartridge_rel = f"cartridges/{generation}-highway-static-transport-v9-5.js"
    cartridge_path = Path("atlas") / cartridge_rel
    contract_rel = f"../ui/cartridges/{generation}-highway-static-transport-v9-5.mjs"
    contract_path = Path("ui/cartridges") / f"{generation}-highway-static-transport-v9-5.mjs"
    manifest_rel = f"./manifests/{generation}-composition.json"
    manifest_path = Path("atlas/manifests") / f"{generation}-composition.json"
    write_atomic(cartridge_path, cartridge_text)
    write_atomic(contract_path, make_contract(generation, cartridge_sha))
    source_shell_path = Path("atlas") / str(current["shell"]["index"]).removeprefix("./")
    require(source_shell_path.is_file(), f"shell index missing: {source_shell_path}")
    shell_bytes = source_shell_path.read_bytes()
    new_cartridge = {
        "id": CARTRIDGE_ID, "generation": generation, "version": "v9.5", "type": "script", "slot": "replace-script", "replace_script": REPLACE_SCRIPT,
        "path": f"./{cartridge_rel}", "sha256": cartridge_sha, "contract": contract_rel,
        "capabilities": ["v8-static-highway-parity", "primary-a-roads", "trunk-a-roads", "motorways", "duckdb-analytical-fallback", "main-thread-memory-reduction"],
        "source_commit": GLOBALGRID_SHA, "transport": "PINNED_V8_STATIC_GEOJSON"
    }
    old_generation = str(current["generation"])
    old_manifest = str(current["composition_manifest"])
    old_cartridges = [item for item in current.get("cartridges", []) if item.get("id") != CARTRIDGE_ID]
    current["previous_generation"] = old_generation
    current["generation"] = generation
    current["cartridge_order"] = [CARTRIDGE_ID] + [item for item in current.get("cartridge_order", []) if item != CARTRIDGE_ID]
    current["cartridges"] = [new_cartridge] + old_cartridges
    current["composition_manifest"] = manifest_rel
    current["composition_id"] = f"{generation}-gridatlas-v9.5-highway-repair"
    current["provenance"]["cvaa_commit"] = CVAA_SHA
    current["provenance"]["highway_source_repository"] = "https://github.com/Ventusltd/globalgrid2050"
    current["provenance"]["highway_source_commit"] = GLOBALGRID_SHA
    current["scope_closure"] = {"generation": generation, "status": "DONE", "scope": "V8/V9.5 A-roads browser forensics and modular transport repair", "schedule_retired": True}
    current["forensics"] = {
        "cause": "The generic on-demand bridge materialised 163790 primary-road rows from a 29292883-byte Parquet partition, expanded Arrow rows into JavaScript objects, stringified a full FeatureCollection, reparsed it in the V8 core, then handed another copy to MapLibre.",
        "classification": "BROWSER_MEMORY_AMPLIFICATION_NOT_SOURCE_CORRUPTION", "v8_transport": "STATIC_GEOJSON", "v9_before_transport": "PARQUET_DUCKDB_FULL_REHYDRATION", "v9_after_transport": "PINNED_V8_STATIC_GEOJSON",
        "primary_roads_rows": 163790, "primary_roads_parquet_bytes": 29292883, "shell_mutated": False, "full_application_copies_created": 0
    }
    manifest_cartridges = []
    for item in current["cartridges"]:
        source_path = Path("atlas") / str(item["path"]).removeprefix("./")
        require(source_path.is_file(), f"composition cartridge missing: {source_path}")
        payload = dict(item)
        payload["source_size_bytes"] = source_path.stat().st_size
        manifest_cartridges.append(payload)
    manifest = {
        "schema": "gridatlas.composition.v1", "generation": generation, "composition_id": current["composition_id"], "architecture": current["architecture"], "composition_version": "v9.5", "release_id": current["release_id"], "release_route": current["release_route"],
        "source_release_index": str(current["shell"]["index"]).removeprefix("./"), "source_shell_sha256": sha256_bytes(shell_bytes), "source_shell_bytes": len(shell_bytes), "previous_composition": old_manifest, "cartridge_order": current["cartridge_order"], "cartridges": manifest_cartridges,
        "invariants": {"immutable_shell_mutated": False, "full_application_copies_created": 0, "shell_release_preserved": True, "search_cartridge_preserved": any(item.get("id") == "uk-gazetteer-flyto" for item in current["cartridges"]), "transport_repair_is_one_cartridge": True, "cvaa_full_history_pin": CVAA_SHA},
        "forensics": current["forensics"],
        "source_evidence": {"immutable_bridge_path": args.shell_bridge, "immutable_bridge_sha256": shell_bridge_sha, "globalgrid_source_commit": GLOBALGRID_SHA, "primary_roads_partition_sha256": "9df875a7791ed5af1c77a40b9872ff32315711eec73b4b9eaa31e7a0882e8a99"}
    }
    write_atomic(current_path, canonical_json(current))
    write_atomic(manifest_path, canonical_json(manifest))
    report = {
        "schema": "gridatlas.highway-transport-build.v1", "status": "BUILT", "changed": True, "generation": generation, "composition_id": current["composition_id"], "previous_generation": old_generation,
        "source_bridge": args.shell_bridge, "source_bridge_sha256": shell_bridge_sha, "cartridge": str(cartridge_path), "cartridge_sha256": cartridge_sha, "contract": str(contract_path), "manifest": str(manifest_path), "cvaa_commit": CVAA_SHA, "globalgrid_source_commit": GLOBALGRID_SHA,
        "primary_roads": {"rows": 163790, "parquet_bytes": 29292883, "parquet_sha256": "9df875a7791ed5af1c77a40b9872ff32315711eec73b4b9eaa31e7a0882e8a99", "before": "PARQUET_DUCKDB_FULL_REHYDRATION", "after": "PINNED_V8_STATIC_GEOJSON"},
        "full_application_copies_created": 0, "shell_mutated": False, "existing_cartridges_preserved": [item.get("id") for item in old_cartridges]
    }
    write_atomic(Path(args.report), canonical_json(report))
    print(json.dumps(report, sort_keys=True))
    return 0

if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except (BuildError, KeyError, ValueError, json.JSONDecodeError) as error:
        print(f"BUILD FAILED: {error}", file=os.sys.stderr)
        raise SystemExit(1)