GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / 202608310050-gridatlas-next-version-builders/tools

Streaming Parquet Bridge V9 5 and 2 more files

A JavaScript file in the cartridges folder of GridAtlas that reads grid 400kV, grid 275kV, grid 220kV and grid 132kV, using SHA-256 from the data-GridAtlas repository.

630 lines of JavaScript from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 517 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. Prove Federated Deep Links interaction · gridatlas / 202608310050-gridatlas-next-version-builders/tools/202608310050-prove-federated-deep-links.mjs lines 1–114
  2. Select Build Plan storage · gridatlas / 202608310050-gridatlas-next-version-builders/tools/202608310050-select-build-plan.mjs lines 1–180
  3. Streaming Parquet Bridge V9 5 interaction · gridatlas / atlas/cartridges/202610230100-streaming-parquet-bridge-v9-5.js lines 1–336

Prove Federated Deep Links

A JavaScript module in the tools folder of GridAtlas.

interactiongridatlas / 202608310050-gridatlas-next-version-builders/tools/202608310050-prove-federated-deep-links.mjs · lines 1–114 of 114 · version 2026-08-31 00:50 · Entry point

What it does
Uses libraries node:fs, node:path, playwright. Side effects: changes the web page (DOM); 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: command-line arguments.
Downstream impact
Used directly by 1 file: GridAtlas Next Version Builders Workflow (gridatlas).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Run by GridAtlas Next Version Builders Workflow.
Application
gridatlas · 202608310050-gridatlas-next-version-builders/tools · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL), GridAtlas — Index Page (estate URL), node:fs, node:path, playwright
Used by
run by GridAtlas Next Version Builders 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 202608310050-gridatlas-next-version-builders/tools/202608310050-prove-federated-deep-links.mjs:1-114 · blob 73911156e77a560b2737f0344d963f6e8b422382 · 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
#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import { chromium, request } from 'playwright';

const outputDir = path.resolve(process.argv[2] || '');
const generation = process.argv[3] || 'unknown';
if (!outputDir || !fs.existsSync(outputDir)) throw new Error('output directory is required');

const proofDir = path.join(outputDir, 'browser-proof');
fs.mkdirSync(proofDir, { recursive: true });
const cases = [
  { id: 'stable-beacon-fen-desktop', url: 'https://ventusltd.github.io/gridatlas/atlas/?repd_ref=13599', ref: '13599', viewport: { width: 1280, height: 900 }, dpr: 1 },
  { id: 'stable-beacon-fen-phone', url: 'https://ventusltd.github.io/gridatlas/atlas/?repd_ref=13599', ref: '13599', viewport: { width: 375, height: 667 }, dpr: 2 },
  { id: 'root-redirect-beacon-fen', url: 'https://ventusltd.github.io/gridatlas/?repd_ref=13599', ref: '13599', viewport: { width: 1280, height: 900 }, dpr: 1 },
  { id: 'stable-east-pye-desktop', url: 'https://ventusltd.github.io/gridatlas/atlas/?repd_ref=17494', ref: '17494', viewport: { width: 1280, height: 900 }, dpr: 1 }
];

const browser = await chromium.launch({ headless: true });
const results = [];
let failed = false;
try {
  for (const test of cases) {
    const context = await browser.newContext({ viewport: test.viewport, deviceScaleFactor: test.dpr });
    const page = await context.newPage();
    const consoleErrors = [];
    const requestFailures = [];
    page.on('console', message => {
      if (message.type() === 'error') consoleErrors.push(message.text());
    });
    page.on('pageerror', error => consoleErrors.push(String(error?.stack || error)));
    page.on('requestfailed', request => requestFailures.push({ url: request.url(), failure: request.failure()?.errorText || 'unknown' }));
    const started = Date.now();
    let responseStatus = null;
    let bodyState = null;
    let error = null;
    try {
      const response = await page.goto(test.url, { waitUntil: 'domcontentloaded', timeout: 90_000 });
      responseStatus = response?.status() ?? null;
      await page.waitForFunction(
        ref => document.body?.dataset.gridatlasRepdDeepLink === 'resolved' && document.body?.dataset.gridatlasRepdRef === ref,
        test.ref,
        { timeout: 90_000 }
      );
      bodyState = await page.evaluate(() => ({
        deep_link: document.body?.dataset.gridatlasRepdDeepLink || null,
        repd_ref: document.body?.dataset.gridatlasRepdRef || null,
        router: document.body?.dataset.gridatlasRouter || null,
        generation: document.documentElement?.dataset.gridatlasGeneration || null,
        href: location.href,
        place_search: window.__GRIDATLAS_PLACE_SEARCH__ ? {
          generation: window.__GRIDATLAS_PLACE_SEARCH__.generation,
          deep_link: window.__GRIDATLAS_PLACE_SEARCH__.deep_link,
          failures: window.__GRIDATLAS_PLACE_SEARCH__.failures
        } : null
      }));
      await page.screenshot({ path: path.join(proofDir, `${generation}-${test.id}.png`), fullPage: false });
    } catch (caught) {
      error = String(caught?.stack || caught);
      failed = true;
      try { await page.screenshot({ path: path.join(proofDir, `${generation}-${test.id}-failed.png`), fullPage: false }); } catch {}
    }
    results.push({
      id: test.id,
      url: test.url,
      ref: test.ref,
      viewport: test.viewport,
      dpr: test.dpr,
      response_status: responseStatus,
      elapsed_ms: Date.now() - started,
      body_state: bodyState,
      console_errors: consoleErrors,
      request_failures: requestFailures,
      error,
      passed: !error && bodyState?.deep_link === 'resolved' && bodyState?.repd_ref === test.ref
    });
    if (!results.at(-1).passed) failed = true;
    await context.close();
  }

  const api = await request.newContext({ ignoreHTTPSErrors: false });
  const staleUrl = 'https://ventusltd.github.io/gridatlas/202608300453-atlas-v9/?repd_ref=13599';
  let staleStatus = null;
  let staleError = null;
  try {
    const response = await api.get(staleUrl, { timeout: 30_000, failOnStatusCode: false });
    staleStatus = response.status();
  } catch (error) {
    staleError = String(error?.stack || error);
  } finally {
    await api.dispose();
  }
  const stalePassed = staleStatus === 404;
  if (!stalePassed) failed = true;
  results.push({ id: 'stale-root-release', url: staleUrl, expected_status: 404, response_status: staleStatus, error: staleError, passed: stalePassed });
} finally {
  await browser.close();
}

const proof = {
  schema: 'gridatlas.federated-deep-link-browser-proof.v1',
  generation,
  observed_at: new Date().toISOString(),
  classification: failed ? 'FAILED_PUBLIC_FEDERATED_DEEP_LINK_PROOF' : 'VERIFIED_PUBLIC_FEDERATED_DEEP_LINK_PROOF',
  synthetic_receiver: false,
  route_interceptions: 0,
  stable_route: '/gridatlas/atlas/',
  sentinels: ['13599', '17494'],
  results,
  passed: !failed
};
fs.writeFileSync(path.join(proofDir, `${generation}-federated-deep-link-proof.json`), `${JSON.stringify(proof, null, 2)}\n`, 'utf8');
console.log(JSON.stringify(proof, null, 2));
if (failed) process.exitCode = 1;

Select Build Plan

A JavaScript module in the tools folder of GridAtlas that lists files (`listFiles`), using SHA-256.

storagegridatlas / 202608310050-gridatlas-next-version-builders/tools/202608310050-select-build-plan.mjs · lines 1–180 of 180 · version 2026-08-31 00:50 · Entry point · pattern londonGeneration (shared by 2 files)

What it does
It loads data. Defines 11 functions or classes, including invariant, londonGeneration, pick, output, listFiles. Uses libraries node:crypto, node:fs, node:os, node:path, node:child_process. Side effects: reads or writes files; starts processes.
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 status.json. Out: JSON file source-lock.json.
Downstream impact
Used directly by 1 file: GridAtlas Next Version Builders Workflow (gridatlas).
What it achieves
It lists files (`listFiles`) and is built from the london generation helper (`londonGeneration`) and the output step (`output`). Defines `invariant`, `londonGeneration`, `pick` and 7 more.
Why it matters
Run by GridAtlas Next Version Builders Workflow.
Application
gridatlas · 202608310050-gridatlas-next-version-builders/tools · JavaScript module
Uses
node:crypto, node:fs, node:os, node:path, node:child_process
Used by
run by GridAtlas Next Version Builders Workflow (workflow run), mentioned in Standalone (comment link)
Produces
invariant, londonGeneration, pick, output, listFiles, wordCount, inspectBuildPlan, refs, materialise, completedStages, main
Defines here
invariant, londonGeneration, pick, output, listFiles, wordCount, inspectBuildPlan, refs, materialise, completedStages, 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 202608310050-gridatlas-next-version-builders/tools/202608310050-select-build-plan.mjs:1-180 · blob 121d187affe19f97418df125f43410be3a983950 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync, spawnSync } from 'node:child_process';

const ROOT = process.cwd();
const CAMPAIGN = '202608310050-gridatlas-next-version-builders';
const OUTPUT_ROOT = path.join(ROOT, CAMPAIGN, 'outputs');
const MATERIALISED = path.join(ROOT, 'work', '202608310050-build-plan');
const REQUIRED_WORDS = 43_000;
const NOT_BEFORE = Date.parse('2026-08-31T00:15:00Z');
const CAMPAIGN_END = Date.parse('2026-08-31T09:00:00Z');
const REQUIRED = [
  'NEXT-VERSION.md',
  'summary.md',
  'window-intelligence.md',
  'questions.md',
  'DRAFT-CARTRIDGES/exact-ref-index.spec.md',
  'DRAFT-CARTRIDGES/exact-ref-index.js.txt',
  'DRAFT-CARTRIDGES/window-intelligence.spec.md',
  'DRAFT-CARTRIDGES/window-intelligence.js.txt'
];
const STAGES = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n11', 'handover'];
const TEXT_EXTENSIONS = new Set(['.md', '.txt', '.json', '.js', '.mjs', '.cjs', '.py', '.yml', '.yaml', '.csv', '.html', '.css']);

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

function londonGeneration(date = new Date()) {
  const parts = new Intl.DateTimeFormat('en-GB', {
    timeZone: 'Europe/London', year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', hourCycle: 'h23'
  }).formatToParts(date);
  const pick = type => parts.find(part => part.type === type)?.value;
  return `${pick('year')}${pick('month')}${pick('day')}${pick('hour')}${pick('minute')}`;
}

function output(values) {
  const file = process.env.GITHUB_OUTPUT;
  if (!file) return;
  fs.appendFileSync(file, `${Object.entries(values).map(([key, value]) => `${key}=${String(value).replaceAll('\n', '%0A')}`).join('\n')}\n`);
}

function listFiles(directory) {
  const result = [];
  if (!fs.existsSync(directory)) return result;
  for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
    const target = path.join(directory, entry.name);
    if (entry.isDirectory()) result.push(...listFiles(target));
    else if (entry.isFile()) result.push(target);
  }
  return result.sort();
}

function wordCount(text) {
  return (String(text).match(/[A-Za-z0-9][A-Za-z0-9_’'\-]*/g) || []).length;
}

function inspectBuildPlan(directory) {
  const plan = path.join(directory, '_build-plan');
  const files = listFiles(plan).filter(file => TEXT_EXTENSIONS.has(path.extname(file).toLowerCase()));
  let words = 0;
  let bytes = 0;
  const digest = crypto.createHash('sha256');
  for (const file of files) {
    const relative = path.relative(plan, file).split(path.sep).join('/');
    const content = fs.readFileSync(file);
    digest.update(relative);
    digest.update('\0');
    digest.update(crypto.createHash('sha256').update(content).digest());
    bytes += content.length;
    words += wordCount(content.toString('utf8'));
  }
  const missing = REQUIRED.filter(relative => !fs.existsSync(path.join(plan, relative)));
  return { plan, files: files.length, words, bytes, missing, fingerprint: digest.digest('hex') };
}

function refs() {
  const raw = execFileSync('git', ['for-each-ref', '--format=%(refname:short)|%(objectname)|%(committerdate:unix)', 'refs/remotes/origin'], { encoding: 'utf8' });
  const seen = new Set();
  const rows = [];
  for (const line of raw.trim().split(/\r?\n/).filter(Boolean)) {
    const [ref, sha, unix] = line.split('|');
    if (!ref || ref.endsWith('/HEAD') || seen.has(sha)) continue;
    seen.add(sha);
    rows.push({ ref, sha, unix: Number(unix || 0) });
  }
  const head = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
  if (!seen.has(head)) rows.push({ ref: 'HEAD', sha: head, unix: Math.floor(Date.now() / 1000) });
  return rows;
}

function materialise(ref, destination) {
  fs.rmSync(destination, { recursive: true, force: true });
  fs.mkdirSync(destination, { recursive: true });
  const archive = spawnSync('git', ['archive', '--format=tar', ref, '_build-plan'], { encoding: null, maxBuffer: 128 * 1024 * 1024 });
  if (archive.status !== 0) return false;
  const untar = spawnSync('tar', ['-xf', '-', '-C', destination], { input: archive.stdout, encoding: null, maxBuffer: 128 * 1024 * 1024 });
  return untar.status === 0;
}

function completedStages() {
  const complete = new Set();
  if (!fs.existsSync(OUTPUT_ROOT)) return complete;
  for (const directory of fs.readdirSync(OUTPUT_ROOT, { withFileTypes: true })) {
    if (!directory.isDirectory()) continue;
    const statusPath = path.join(OUTPUT_ROOT, directory.name, 'status.json');
    if (!fs.existsSync(statusPath)) continue;
    try {
      const status = JSON.parse(fs.readFileSync(statusPath, 'utf8'));
      if (status.completed === true && STAGES.includes(status.stage)) complete.add(status.stage);
    } catch {}
  }
  return complete;
}

function main() {
  const now = Date.now();
  const active = now < CAMPAIGN_END;
  const mature = now >= NOT_BEFORE;
  execFileSync('git', ['fetch', '--all', '--prune', '--tags', '--force'], { stdio: 'inherit' });
  const candidates = [];
  for (const row of refs()) {
    const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'gridatlas-plan-'));
    try {
      if (!materialise(row.ref, temporary)) continue;
      const inspected = inspectBuildPlan(temporary);
      candidates.push({ ...row, ...inspected, temporary });
    } catch {
      fs.rmSync(temporary, { recursive: true, force: true });
    }
  }
  candidates.sort((a, b) => {
    const aComplete = a.missing.length === 0 ? 1 : 0;
    const bComplete = b.missing.length === 0 ? 1 : 0;
    return bComplete - aComplete || b.words - a.words || b.unix - a.unix;
  });
  const selected = candidates[0] || null;
  const ready = Boolean(selected && selected.words >= REQUIRED_WORDS && selected.missing.length === 0);
  let stage = '';
  let generation = '';
  let outputDir = '';
  if (active && mature && ready) {
    materialise(selected.ref, MATERIALISED);
    invariant(fs.existsSync(path.join(MATERIALISED, '_build-plan', 'NEXT-VERSION.md')), 'materialised build plan is incomplete');
    const complete = completedStages();
    stage = STAGES.find(item => !complete.has(item)) || '';
    if (stage) {
      generation = londonGeneration();
      const runId = process.env.GITHUB_RUN_ID || `manual-${process.pid}`;
      outputDir = path.join(CAMPAIGN, 'outputs', `${generation}-${stage}-gridatlas-run-${runId}`).split(path.sep).join('/');
      fs.mkdirSync(path.join(ROOT, outputDir), { recursive: true });
      fs.writeFileSync(path.join(ROOT, outputDir, 'source-lock.json'), `${JSON.stringify({
        schema: 'gridatlas.next-version-build-plan-lock.v1', generation, stage,
        selected_ref: selected.ref, selected_sha: selected.sha,
        files: selected.files, words: selected.words, bytes: selected.bytes,
        fingerprint: selected.fingerprint, required_words: REQUIRED_WORDS,
        required_files: REQUIRED, missing: selected.missing,
        materialised_path: 'work/202608310050-build-plan/_build-plan',
        live_pointer_mutation: false, immutable_shell_mutation: false
      }, null, 2)}\n`);
    }
  }
  for (const candidate of candidates) {
    if (candidate.temporary) fs.rmSync(candidate.temporary, { recursive: true, force: true });
  }
  const result = {
    active, mature, ready, stage, generation, output_dir: outputDir,
    source_ref: selected?.ref || '', source_sha: selected?.sha || '',
    source_words: selected?.words || 0, source_files: selected?.files || 0,
    missing: selected?.missing.join(',') || '', campaign_complete: ready && !stage
  };
  output(result);
  console.log(JSON.stringify(result, null, 2));
}

main();

Streaming Parquet Bridge V9 5

A JavaScript file in the cartridges folder of GridAtlas that reads grid 400kV, grid 275kV, grid 220kV and grid 132kV, using SHA-256 from the data-GridAtlas repository.

interactiongridatlas / atlas/cartridges/202610230100-streaming-parquet-bridge-v9-5.js · lines 1–336 of 336 · version 2026-10-23 01:00 · Not reached from any entry point (candidate for review) · pattern scheduleRuntimePrewarm (shared by 3 files)

What it does
It loads grid 400kV, grid 275kV, grid 220kV and grid 132kV. Defines 16 functions or classes, including invariant, requestPath, mapReadyKey, legacyStem, sha256Hex. Side effects: changes the web page (DOM); 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.
Inputs & outputs
In: data source: data-gridatlas data; GeoJSON file grid_400kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_220kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file grid_substations.geojson; GeoJSON file power_plants.geojson.
What it achieves
It maps ready key (`mapReadyKey`), gets manifest (`getManifest`) and gets runtime (`getRuntime`). Defines `invariant`, `requestPath`, `mapReadyKey` and 13 more. It responds to abort events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/cartridges · script
Uses
Data GridAtlas — Data GridAtlas Page (estate URL)
Used by
none found
Produces
invariant, requestPath, mapReadyKey, legacyStem, sha256Hex, getManifest, sharedDuckDBRuntime, promise, getRuntime, scheduleRuntimePrewarm, start, resolvePartition
Defines here
invariant, requestPath, mapReadyKey, legacyStem, sha256Hex, getManifest, sharedDuckDBRuntime, promise, getRuntime, scheduleRuntimePrewarm, start, resolvePartition, rowObject, queryOnDemand, task, abort
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202610230100-streaming-parquet-bridge-v9-5.js:1-336 · blob 480000111fe12306a4d250fa9b246ab5de22f865 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
(() => {
  'use strict';

  const GENERATION = '202609241251';
  const DATA_BASE = 'https://ventusltd.github.io/data-gridatlas/202608291237-data-gridatlas/';
  const MANIFEST_URL = `${DATA_BASE}data/manifest.json`;
  const MANIFEST_SHA256 = '3246dbdaa042ae8352ec9b7128cb6c2fe65e4f1aba0534302510661828df2526';
  const DUCKDB_MODULE = 'https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/+esm';
  const CRITICAL_RELEASE_PATH = 'data/grid_400kv.geojson';
  const CRITICAL_RUNTIME_URL = '../cartridges/5f5fbec83f9ce307b47ddc6e7277743f0bba1a2445b0f3ca50a9a1806146e993/grid_400kv.geojson';
  const MAP_READY_PATHS = new Set([
    'data/grid_400kv.geojson',
    'data/grid_275kv.geojson',
    'data/grid_220kv.geojson',
    'data/grid_132kv.geojson',
    'data/grid_66kv.geojson',
    'data/grid_substations.geojson',
    'data/power_plants.geojson',
    'data/industrial_offtakers.geojson',
    'data/datacentres.geojson',
    'data/airports.geojson',
    'data/railways.geojson'
  ]);

  const nativeFetch = window.fetch.bind(window);
  const sourceCache = new Map();
  let manifestPromise = null;
  let runtimePromise = null;

  const state = {
    schema: 'gridatlas.maplibre-worker-fetch-bridge.v1',
    generation: GENERATION,
    data_release: '202608291237-data-gridatlas',
    architecture: {
      map_ready_same_origin_geojson: true,
      critical_400kv_maplibre_worker_source: true,
      critical_400kv_window_prefetch: false,
      critical_400kv_main_thread_json_parse: false,
      preload_browser_duckdb: 'AFTER_CRITICAL_SOURCE',
      serialized_preload_queue: false,
      topology_pre_snapped: true,
      analytical_search_duckdb_retained: true
    },
    critical_source: {
      release_copy_path: CRITICAL_RELEASE_PATH,
      runtime_url: CRITICAL_RUNTIME_URL,
      cache_identity: 'CONTENT_ADDRESSED_STABLE_URL',
      delivery: 'MAPLIBRE_WORKER_DIRECT_URL',
      eager_window_prefetch: false,
      window_fetch_hits: 0
    },
    map_ready_requests: 0,
    map_ready_paths: [...MAP_READY_PATHS],
    parquet_requests: 0,
    duckdb_runtime_started: false,
    duckdb_runtime_started_at_ms: null,
    duckdb_runtime_shared: false,
    intercepted_on_demand: 0,
    loaded_on_demand: {},
    failures: [],
    streamed_responses: 0,
    released_payloads: 0,
    stream_failures: [],
    runtime_prewarm: { requested: false, started: false, completed: false, failed: null }
  };
  window.__GRIDATLAS_MAP_READY__ = state;

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

  function requestPath(input) {
    try {
      const raw = typeof input === 'string' ? input : input?.url;
      const url = new URL(raw, window.location.href);
      // The GridAtlas internal Parquet resolver owns only same-origin paths.
      // External GeoJSON (e.g. public lightning observations) must go to native
      // browser fetch, not be interpreted as an internal DuckDB partition.
      if (url.origin !== window.location.origin) return '';
      return url.pathname;
    } catch {
      return '';
    }
  }

  function mapReadyKey(pathname) {
    const marker = '/data/';
    const index = pathname.toLowerCase().lastIndexOf(marker);
    if (index < 0) return '';
    return `data/${decodeURIComponent(pathname.slice(index + marker.length)).toLowerCase()}`;
  }

  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 '';
  }

  async function sha256Hex(bytes) {
    const digest = await crypto.subtle.digest('SHA-256', bytes);
    return [...new Uint8Array(digest)]
      .map(value => value.toString(16).padStart(2, '0'))
      .join('');
  }

  async function getManifest() {
    manifestPromise ||= (async () => {
      const response = await nativeFetch(MANIFEST_URL, { cache: 'no-store' });
      invariant(response.ok, `manifest HTTP ${response.status}`);
      const bytes = await response.arrayBuffer();
      invariant(await sha256Hex(bytes) === MANIFEST_SHA256, 'data manifest SHA-256 mismatch');
      const manifest = JSON.parse(new TextDecoder().decode(bytes));
      invariant(manifest?.schema === 'data-gridatlas.v8-transplant-manifest.v1', 'data manifest schema mismatch');
      invariant(manifest?.closure?.sources === 56, 'V8 source closure mismatch');
      invariant(manifest?.closure?.layers === 60, 'V8 layer closure mismatch');
      invariant(manifest?.closure?.features === 541282, 'V8 feature closure mismatch');
      return manifest;
    })();
    return manifestPromise;
  }

  /* ONE DuckDB runtime for the whole page.
     ----------------------------------------------------------------------
     This cartridge and the uk-gazetteer-flyto search lane each built their
     own. Both were correctly memoised internally, so neither was a fault by
     itself; nothing coordinated between them because they are separate
     cartridges by design. Measured on the live page at an iPhone 13 profile,
     202609041500: duckdb-eh.wasm fetched TWICE, 5.92 MB each, 11.84 MB of a
     12.81 MB arrival - and, which matters more on a phone, two WebAssembly
     heaps and two workers alive at once. iOS Safari caps per-tab memory hard
     where a desktop does not.

     The broker below is deliberately duplicated verbatim into the search
     lane rather than imported. Cartridges are composed as independent
     scripts with no shared module loader between them, so there is nothing
     to import from; the CONTRACT is the window key and the shape it holds,
     not this function. Whichever cartridge asks first builds the runtime and
     the other awaits the same promise, so it is order-independent - which
     matters because composition order is a manifest decision, not a
     guarantee this code should rely on.

     A rejected runtime is dropped rather than cached, so a retry rebuilds
     instead of inheriting a dead promise. And note what is NOT here: nobody
     terminates a shared database. The search lane's retry closes only its
     own connection - see the note there. */
  function sharedDuckDBRuntime(moduleUrl) {
    const KEY = '__GRIDATLAS_DUCKDB_RUNTIME__';
    const held = window[KEY];
    if (held && held.module_url === moduleUrl) return held.promise;
    const promise = (async () => {
      const duckdb = await import(moduleUrl);
      const bundle = await duckdb.selectBundle(duckdb.getJsDelivrBundles());
      invariant(bundle?.mainModule && bundle?.mainWorker, 'DuckDB-WASM bundle unavailable');
      const workerUrl = URL.createObjectURL(new Blob([
        `importScripts(${JSON.stringify(bundle.mainWorker)});`
      ], { type: 'text/javascript' }));
      const worker = new Worker(workerUrl);
      const logger = new duckdb.ConsoleLogger(duckdb.LogLevel.WARNING);
      const database = new duckdb.AsyncDuckDB(logger, worker);
      try {
        await database.instantiate(bundle.mainModule, bundle.pthreadWorker);
      } finally {
        URL.revokeObjectURL(workerUrl);
      }
      return { duckdb, database, worker };
    })();
    /* Assigned synchronously, before the first await inside the IIFE can
       yield, so two callers in the same task cannot both build one. */
    window[KEY] = { module_url: moduleUrl, promise, claimed_at_ms: performance.now() };
    promise.catch(() => {
      if (window[KEY] && window[KEY].promise === promise) delete window[KEY];
    });
    return promise;
  }

  async function getRuntime() {
    runtimePromise ||= (async () => {
      state.duckdb_runtime_started = true;
      state.duckdb_runtime_started_at_ms = performance.now();
      const shared = await sharedDuckDBRuntime(DUCKDB_MODULE);
      state.duckdb_runtime_shared = true;
      return { database: shared.database, worker: shared.worker };
    })();
    return runtimePromise;
  }

  function scheduleRuntimePrewarm() {
    state.runtime_prewarm.requested = true;
    let checks = 0;
    const poll = setInterval(() => {
      checks += 1;
      let criticalReady = false;
      try {
        const map = window.__GRIDATLAS_V9_MAP__;
        criticalReady = Boolean(map && map.getSource('src-400') && map.isSourceLoaded('src-400'));
      } catch {}
      if (!criticalReady && checks < 240) return;
      clearInterval(poll);
      const start = () => {
        state.runtime_prewarm.started = true;
        getRuntime().then(() => {
          state.runtime_prewarm.completed = true;
        }).catch(error => {
          state.runtime_prewarm.failed = String(error?.message || error);
          state.failures.push({ pathname: 'duckdb-runtime-prewarm', message: state.runtime_prewarm.failed });
        });
      };
      if (typeof requestIdleCallback === 'function') requestIdleCallback(start, { timeout: 2000 });
      else setTimeout(start, 0);
    }, 250);
  }

  queueMicrotask(scheduleRuntimePrewarm);

  async function resolvePartition(pathname) {
    const stem = legacyStem(pathname);
    invariant(stem, `unsupported V8 data path: ${pathname}`);
    // These three controls draw stations. The root partition contains track lines.
    // The station partition is selected explicitly after geometry/filter/browser validation;
    // provenance and the former quarantine are recorded in the composition manifest.
    const alias = stem === 'uk_metros_trams' ? 'uk_metros_trams_local_unwired' : stem;
    const expected = `partitions/${alias}.parquet`.toLowerCase();
    const manifest = await getManifest();
    const artifact = (manifest.artifacts || []).find(
      item => String(item.path || '').toLowerCase() === expected
    );
    invariant(artifact, `no V9 Parquet partition for V8 source ${pathname}`);
    invariant(/^[a-f0-9]{64}$/.test(artifact.sha256 || ''), `bad partition digest for ${artifact.path}`);
    return artifact;
  }

  function rowObject(row) {
    return row && typeof row.toJSON === 'function' ? row.toJSON() : row;
  }

  async function queryOnDemand(pathname) {
    if (sourceCache.has(pathname)) return sourceCache.get(pathname);
    const task = (async () => {
      const artifact = await resolvePartition(pathname);
      const parquetUrl = `${DATA_BASE}data/${artifact.path}`;
      const { database } = await getRuntime();
      const connection = await database.connect();
      state.parquet_requests += 1;
      try {
        const escaped = parquetUrl.replaceAll("'", "''");
        const table = await connection.query(`
          SELECT source_id, feature_index, feature_id, geometry_json, properties_json
          FROM read_parquet('${escaped}')
          ORDER BY feature_index
        `);
        const features = table.toArray().map(raw => {
          const row = rowObject(raw);
          return {
            type: 'Feature',
            id: row.feature_id || `${row.source_id}:${row.feature_index}`,
            geometry: JSON.parse(String(row.geometry_json)),
            properties: JSON.parse(String(row.properties_json || '{}'))
          };
        });
        state.loaded_on_demand[pathname] = {
          parquet: artifact.path,
          rows: features.length,
          sha256: artifact.sha256
        };
        return { type: 'FeatureCollection', features };
      } finally {
        await connection.close();
      }
    })();
    sourceCache.set(pathname, task);
    try {
      return await task;
    } catch (error) {
      sourceCache.delete(pathname);
      state.failures.push({ pathname, message: String(error?.message || error) });
      throw error;
    }
  }

  window.fetch = async function gridAtlasMaplibreWorkerFetch(input, init = undefined) {
    const pathname = requestPath(input);
    const readyKey = mapReadyKey(pathname);

    if (MAP_READY_PATHS.has(readyKey)) {
      state.map_ready_requests += 1;
      if (readyKey === CRITICAL_RELEASE_PATH) state.critical_source.window_fetch_hits += 1;
      return nativeFetch(input, { ...(init || {}), cache: 'force-cache' });
    }

    if (!legacyStem(pathname)) return nativeFetch(input, init);

    state.intercepted_on_demand += 1;
    if (init?.signal?.aborted) throw new DOMException('Aborted', 'AbortError');

    // Return response headers before DuckDB imports, downloads, queries and serialises the body.
    // This preserves the native fetch contract expected by the V8 engine: its 15 s timer protects
    // response establishment, while response.json() may continue consuming a streamed body.
    state.streamed_responses += 1;
    const encoder = new TextEncoder();
    let bodyController = null;
    let aborted = false;
    const abort = () => {
      aborted = true;
      try { bodyController?.error(new DOMException('Aborted', 'AbortError')); } catch {}
    };
    init?.signal?.addEventListener('abort', abort, { once: true });
    const body = new ReadableStream({
      start(controller) {
        bodyController = controller;
        queryOnDemand(pathname).then(payload => {
          if (aborted || init?.signal?.aborted) return abort();
          const serialised = JSON.stringify(payload);
          sourceCache.delete(pathname);
          state.released_payloads += 1;
          controller.enqueue(encoder.encode(serialised));
          controller.close();
        }).catch(error => {
          sourceCache.delete(pathname);
          state.stream_failures.push({ pathname, message: String(error?.message || error) });
          try { controller.error(error); } catch {}
        });
      },
      cancel() { aborted = true; }
    });
    return new Response(body, {
      status: 200,
      headers: {
        'Content-Type': 'application/geo+json; charset=utf-8',
        'Cache-Control': 'private, max-age=3600',
        'X-GridAtlas-Data-Plane': 'V9-PARQUET-DUCKDB-STREAMED-RESPONSE'
      }
    });
  };
})();