GLOBALGRID2050 / EXPLORE CODE

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

Verify Live Bytes and 6 more files

A JavaScript module in the scope folder of GridAtlas that resolves atlas reference (`resolveAtlasReference`) and collects targets (`collectTargets`), using SHA-256.

659 lines of JavaScript from gridatlas, in 7 files. Topic: Maps, GIS and field navigation. Section 690 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 Compose render · gridatlas / tools/scope/verify-compose.mjs lines 1–111
  2. Verify Live Bytes storage · gridatlas / tools/scope/verify-live-bytes.mjs lines 1–195
  3. Verify Live render · gridatlas / tools/scope/verify-live.mjs lines 1–195
  4. Build storage · gridatlas / tools/secondary/build.mjs lines 1–7
  5. G203 Swarm 06 Viewport Lifecycle Test test · gridatlas / tools/secondary/g203-swarm-06-viewport-lifecycle.test.mjs lines 1–20
  6. Owner Test Proof test · gridatlas / tools/secondary/owner-test-proof.mjs lines 1–23
  7. Regional Interface render · gridatlas / tools/secondary/regional-interface.mjs lines 1–108

Verify Compose

A JavaScript module in the scope folder of GridAtlas that reads grid 400kV and postcodes, using SHA-256 from postcodes.io. It is built from the release directories helper (`releaseDirectories`).

rendergridatlas / tools/scope/verify-compose.mjs · lines 1–111 of 111 · Entry point

What it does
It loads grid 400kV and postcodes. Defines releaseDirectories. Uses libraries node:fs, node:path. Side effects: changes the web page (DOM); reads or writes files; starts processes.
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, 400kV.
Inputs & outputs
In: data source: postcodes.io; JSON file current.json; GeoJSON file grid_400kv.geojson. Voltage levels named: 400kV.
Downstream impact
Used directly by 8 files: Local CI (gridatlas); CI PR Gate (gridatlas); GridAtlas — Release (gridatlas); Advance (gridatlas); and 4 more. Reached from 24 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Acceptance (gridatlas); Browser Test (gridatlas).
What it achieves
Its name says it verifies compose. Defines `releaseDirectories`. Its code works with 400 kV.
Why it matters
Run by 8 workflows and scripts, including Local CI, CI PR Gate and GridAtlas — Release.
Application
gridatlas · tools/scope · JavaScript module
Uses
GridAtlas — Scope (import), node:fs, node:path
Used by
run by Local CI (script call), run by CI PR Gate (script call), run by GridAtlas — Release (script call), run by Advance (script call), run by GridAtlas Scope Loop Workflow (workflow run), run by GridAtlas Verify Live Workflow (workflow run), run by GridAtlas Cartridge Proof Workflow (workflow run), run by GridAtlas Rollback Composition Workflow (workflow run)
Produces
releaseDirectories
Defines here
releaseDirectories
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/scope/verify-compose.mjs:1-111 · blob e05eee71913e70258d1a49e417e13990c60ded2f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import fs from 'node:fs';
import path from 'node:path';
import {
  ROOT, CURRENT_RELEASE, EXPECTED_RELEASES, SHARED_400KV_CARTRIDGE,
  invariant, readJson, sha256PublishedFile, relativePosix, registeredLoader, slotsUsed
} from './lib.mjs';

function releaseDirectories(directory) {
  if (!fs.existsSync(directory)) return [];
  return fs.readdirSync(directory, { withFileTypes: true })
    .filter(entry => entry.isDirectory() && /^\d{12}-atlas-v9$/.test(entry.name))
    .map(entry => entry.name)
    .sort();
}

try {
  const currentPath = path.join(ROOT, 'atlas', 'current.json');
  if (!fs.existsSync(currentPath)) {
    console.log('composition=SKIP atlas/current.json absent before Scope 1');
    process.exit(0);
  }
  const current = readJson(currentPath);
  if (current.schema !== 'gridatlas.current.v2') {
    console.log(`composition=SKIP schema=${current.schema} before Scope 2`);
    process.exit(0);
  }

  invariant(current.architecture === 'IMMUTABLE_SHELL_PLUS_HASHED_CARTRIDGES', 'architecture mismatch');
  invariant(current.release_id === CURRENT_RELEASE, 'release identity mismatch');
  const releases = releaseDirectories(path.join(ROOT, 'atlas', 'releases'));
  invariant(JSON.stringify(releases) === JSON.stringify([...EXPECTED_RELEASES].sort()), `immutable release closure mismatch: ${JSON.stringify(releases)}`);
  invariant(releaseDirectories(ROOT).length === 0, 'top-level release copy found');

  const atlasIndex = fs.readFileSync(path.join(ROOT, 'atlas', 'index.html'), 'utf8');
  for (const marker of ['crypto.subtle.digest', 'cartridge_order', 'replace-script', 'document.write']) {
    invariant(atlasIndex.includes(marker), `atlas composer missing ${marker}`);
  }
  const loader = registeredLoader(path.join(ROOT, 'atlas', 'index.html'));
  invariant(loader, 'atlas/index.html is not a registered loader (tools/scope/lib.mjs ATLAS_LOADERS)');
  for (const slot of slotsUsed(current)) invariant(loader.slots.includes(slot), `atlas composer (loader ${loader.name}) does not support slot ${slot}`);

  const shellIndexPath = path.resolve(path.join(ROOT, 'atlas'), current.shell.index);
  invariant(fs.existsSync(shellIndexPath), `shell index missing: ${relativePosix(shellIndexPath)}`);
  invariant(shellIndexPath === path.join(ROOT, 'atlas', 'releases', CURRENT_RELEASE, 'index.html'), 'shell index escaped fixed release');
  const shell = fs.readFileSync(shellIndexPath, 'utf8');
  const byId = new Map(current.cartridges.map(item => [item.id, item]));
  invariant(byId.size === current.cartridges.length, 'duplicate cartridge id');
  const composed = new Set();
  const usedSlots = new Set();
  for (const id of current.cartridge_order) {
    const cartridge = byId.get(id);
    invariant(cartridge, `missing ordered cartridge ${id}`);
    const filePath = path.resolve(path.join(ROOT, 'atlas'), cartridge.path);
    invariant(filePath.startsWith(`${path.join(ROOT, 'atlas')}${path.sep}`), `${id}: cartridge escaped atlas`);
    invariant(fs.existsSync(filePath), `${id}: cartridge file missing`);
    invariant(sha256PublishedFile(filePath) === cartridge.sha256, `${id}: cartridge hash mismatch`);
    if (cartridge.slot === 'after-cartridge') {
      /* A cartridge of its own, executed straight after a cartridge already
         composed: it claims no shell script, so the shell needs no slot. */
      invariant(typeof cartridge.after === 'string' && composed.has(cartridge.after), `${id}: after-cartridge anchor ${cartridge.after} is not composed before it`);
    } else {
      invariant(cartridge.slot === 'replace-script', `${id}: unsupported slot ${cartridge.slot}`);
      invariant(shell.includes(cartridge.replace_script), `${id}: replacement slot missing from immutable shell`);
      invariant(!usedSlots.has(cartridge.replace_script), `${id}: shell slot ${cartridge.replace_script} already claimed`);
      usedSlots.add(cartridge.replace_script);
    }
    composed.add(id);
  }

  const sharedPath = path.join(ROOT, 'atlas', 'releases', 'cartridges', SHARED_400KV_CARTRIDGE, 'grid_400kv.geojson');
  invariant(fs.existsSync(sharedPath), 'shared 400 kV content-addressed cartridge missing');
  invariant(sha256PublishedFile(sharedPath) === SHARED_400KV_CARTRIDGE, 'shared 400 kV content hash mismatch');

  if (current.cartridge_order.includes('uk-gazetteer-flyto')) {
    const cartridge = byId.get('uk-gazetteer-flyto');
    const source = fs.readFileSync(path.resolve(path.join(ROOT, 'atlas'), cartridge.path), 'utf8');
    for (const marker of [
      "GEOCODER_BASE = 'https://api.postcodes.io'",
      'Promise.all([',
      "kind: 'postcode'",
      "kind: 'postcode_district'",
      "kind: 'place'",
      "url.searchParams.delete('repd_ref')",
      'serial !== activeQuerySerial',
      'geocoder_failures'
    ]) invariant(source.includes(marker), `location cartridge missing ${marker}`);
    const contract = fs.readFileSync(path.join(ROOT, 'ui', 'cartridges', '202608301136-uk-gazetteer-flyto.mjs'), 'utf8');
    invariant(contract.includes("resultClass: 'LOCATION_ONLY'"), 'location contract result class mismatch');
    invariant(contract.includes('setsDeepLink: false'), 'location contract deep-link rule mismatch');
  }

  if (current.composition_manifest) {
    const manifestPath = path.resolve(path.join(ROOT, 'atlas'), current.composition_manifest);
    invariant(fs.existsSync(manifestPath), 'composition manifest missing');
    const manifest = readJson(manifestPath);
    invariant(manifest.generation === current.generation, 'composition manifest generation mismatch');
    invariant(JSON.stringify(manifest.cartridge_order) === JSON.stringify(current.cartridge_order), 'composition order mismatch');
    invariant(manifest.acceptance?.full_application_copies_created === 0, 'composition copied full application');
  }

  console.log(JSON.stringify({
    composition: 'PASS',
    generation: current.generation,
    release_id: current.release_id,
    immutable_releases: releases.length,
    cartridges: current.cartridge_order
  }));
} catch (error) {
  console.error(`[verify-compose] ${error?.stack || error}`);
  process.exitCode = 1;
}

Verify Live Bytes

A JavaScript module in the scope folder of GridAtlas that resolves atlas reference (`resolveAtlasReference`) and collects targets (`collectTargets`), using SHA-256.

storagegridatlas / tools/scope/verify-live-bytes.mjs · lines 1–195 of 195 · Entry point · pattern committedBytes (shared by 2 files)

What it does
It fetches data. Defines 12 functions or classes, including argument, sha256, committedBytes, committedFiles, walk. Uses libraries node:fs, node:path, node:crypto, node:child_process, node:url. Side effects: reads or writes files; makes network requests; starts processes.
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 current.json; command-line arguments.
Downstream impact
Used directly by 2 files: Check Live (gridatlas); GridAtlas Verify Live Workflow (gridatlas).
What it achieves
It resolves atlas reference (`resolveAtlasReference`), collects targets (`collectTargets`) and fetches live (`fetchLive`). Byte-for-byte check that the public GitHub Pages site serves exactly what a commit declares.
Why it matters
Run by Check Live and GridAtlas Verify Live Workflow.
Application
gridatlas · tools/scope · JavaScript module
Uses
GridAtlas — Index Page (estate URL), node:fs, node:path, node:crypto, node:child_process, node:url
Used by
run by Check Live (script call), run by GridAtlas Verify Live Workflow (workflow run)
Produces
argument, sha256, committedBytes, committedFiles, walk, isCommittedFile, resolveAtlasReference, collectTargets, add, walk, fetchLive, main
Defines here
argument, sha256, committedBytes, committedFiles, walk, isCommittedFile, resolveAtlasReference, collectTargets, add, walk, fetchLive, 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 tools/scope/verify-live-bytes.mjs:1-195 · blob 9db4cfeb2a2c5c88853dcf1f1c9c0dddc7749545 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
/* Byte-for-byte check that the public GitHub Pages site serves exactly what a
   commit declares. Dependency-free (Node >= 20 fetch), no browser.

   Compared paths, all relative to the repository root:
     - atlas/current.json and atlas/index.html
     - every path in atlas/current.json that names a committed file: each
       cartridge's `path` (mandatory), plus its contract, module, manifest and
       shell references when those resolve to a committed file
     - every committed file under atlas/v/<generation>/ (preview routes)

   Pages and its CDN lag a push by minutes, so mismatches are retried with
   cache-busting queries until --timeout-s expires. Exit 0 only when every path
   matches; exit 1 with a per-path report otherwise.

   Usage:
     node tools/scope/verify-live-bytes.mjs [--root DIR] [--base URL]
          [--timeout-s 900] [--interval-s 20] [--report FILE]
*/
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

function argument(name, fallback) {
  const index = process.argv.indexOf(`--${name}`);
  return index > 0 && process.argv[index + 1] !== undefined ? process.argv[index + 1] : fallback;
}

const ROOT = path.resolve(argument('root', path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..')));
const BASE = String(argument('base', process.env.GRIDATLAS_BASE_URL || 'https://ventusltd.github.io/gridatlas/')).replace(/\/?$/, '/');
const TIMEOUT_MS = Number(argument('timeout-s', process.env.LIVE_BYTES_TIMEOUT_S || 900)) * 1000;
const INTERVAL_MS = Number(argument('interval-s', process.env.LIVE_BYTES_INTERVAL_S || 20)) * 1000;
const REPORT = argument('report', process.env.LIVE_BYTES_REPORT || '');

const sha256 = bytes => crypto.createHash('sha256').update(bytes).digest('hex');

/* Committed bytes, not the working tree: a CRLF checkout or a stray edit must
   not decide what "committed" means. Falls back to the file when ROOT is not a
   Git checkout (e.g. an exported tree). */
function committedBytes(relative) {
  try {
    return execFileSync('git', ['-C', ROOT, 'show', `HEAD:${relative}`], { maxBuffer: 1 << 30 });
  } catch {
    return fs.readFileSync(path.join(ROOT, relative));
  }
}

function committedFiles(prefix) {
  try {
    return execFileSync('git', ['-C', ROOT, 'ls-tree', '-r', '--name-only', 'HEAD', '--', prefix], { encoding: 'utf8' })
      .split('\n').filter(Boolean).sort();
  } catch {
    const out = [];
    const walk = dir => {
      if (!fs.existsSync(path.join(ROOT, dir))) return;
      for (const entry of fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true })) {
        const child = `${dir}/${entry.name}`;
        if (entry.isDirectory()) walk(child); else if (entry.isFile()) out.push(child);
      }
    };
    walk(prefix.replace(/\/$/, ''));
    return out.sort();
  }
}

function isCommittedFile(relative) {
  try {
    execFileSync('git', ['-C', ROOT, 'cat-file', '-e', `HEAD:${relative}`], { stdio: 'ignore' });
    return execFileSync('git', ['-C', ROOT, 'cat-file', '-t', `HEAD:${relative}`], { encoding: 'utf8' }).trim() === 'blob';
  } catch {
    return fs.existsSync(path.join(ROOT, relative)) && fs.statSync(path.join(ROOT, relative)).isFile();
  }
}

/* Resolve a current.json reference ("./cartridges/x.js", "../ui/y.mjs")
   against atlas/ and keep it only if it stays inside the repository. */
function resolveAtlasReference(value) {
  const joined = path.posix.normalize(path.posix.join('atlas', value));
  return joined.startsWith('../') || joined.startsWith('/') ? null : joined;
}

function collectTargets() {
  const current = JSON.parse(committedBytes('atlas/current.json').toString('utf8'));
  const targets = new Map();
  const add = (relative, why) => { if (!targets.has(relative)) targets.set(relative, why); };
  add('atlas/current.json', 'live pointer');
  add('atlas/index.html', 'live router');

  const problems = [];
  const cartridges = Array.isArray(current.cartridges) ? current.cartridges : [];
  if (!cartridges.length) problems.push('atlas/current.json declares no cartridges');
  for (const cartridge of cartridges) {
    const relative = typeof cartridge?.path === 'string' ? resolveAtlasReference(cartridge.path) : null;
    if (!relative || !isCommittedFile(relative)) {
      problems.push(`cartridge ${cartridge?.id}: path ${cartridge?.path} is not a committed file`);
      continue;
    }
    add(relative, `cartridge ${cartridge.id}`);
    if (cartridge.sha256) {
      const actual = sha256(committedBytes(relative));
      if (actual !== cartridge.sha256) problems.push(`cartridge ${cartridge.id}: committed ${relative} sha256 ${actual} != declared ${cartridge.sha256}`);
    }
  }

  // Every other relative reference that names a committed file.
  const walk = (value, where) => {
    if (typeof value === 'string') {
      if (!/^\.\.?\//.test(value)) return;
      const relative = resolveAtlasReference(value);
      if (relative && isCommittedFile(relative)) add(relative, `current.json ${where}`);
    } else if (Array.isArray(value)) value.forEach((item, i) => walk(item, `${where}[${i}]`));
    else if (value && typeof value === 'object') for (const [k, v] of Object.entries(value)) walk(v, where ? `${where}.${k}` : k);
  };
  walk(current, '');

  const previews = committedFiles('atlas/v/').filter(file => /^atlas\/v\/[^/]+\/.+/.test(file));
  if (!previews.length) problems.push('no committed preview files under atlas/v/');
  for (const file of previews) add(file, `preview ${file.split('/')[2]}`);
  return { current, targets, problems };
}

async function fetchLive(relative, attempt) {
  const url = `${BASE}${relative}?live_bytes=${Date.now()}-${attempt}`;
  try {
    const response = await fetch(url, { headers: { 'Cache-Control': 'no-cache', Pragma: 'no-cache' }, redirect: 'follow' });
    const bytes = Buffer.from(await response.arrayBuffer());
    return { status: response.status, bytes, url };
  } catch (error) {
    return { status: 0, bytes: null, url, error: String(error?.message || error) };
  }
}

async function main() {
  const startedAt = new Date().toISOString();
  const { current, targets, problems } = collectTargets();
  const expected = new Map([...targets.keys()].map(relative => {
    const bytes = committedBytes(relative);
    return [relative, { bytes: bytes.length, sha256: sha256(bytes) }];
  }));
  let commit = null;
  try { commit = execFileSync('git', ['-C', ROOT, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(); } catch {}

  const results = new Map();
  const pending = new Set(targets.keys());
  const deadline = Date.now() + TIMEOUT_MS;
  let attempt = 0;
  while (pending.size) {
    attempt += 1;
    for (const relative of [...pending]) {
      const live = await fetchLive(relative, attempt);
      const want = expected.get(relative);
      const got = live.bytes ? { bytes: live.bytes.length, sha256: sha256(live.bytes) } : null;
      const match = live.status === 200 && got?.sha256 === want.sha256;
      results.set(relative, { path: relative, why: targets.get(relative), http: live.status, expected: want, live: got, match, attempts: attempt, error: live.error });
      if (match) pending.delete(relative);
    }
    console.log(`attempt ${attempt}: ${targets.size - pending.size}/${targets.size} paths match`);
    if (!pending.size || Date.now() + INTERVAL_MS > deadline) break;
    await new Promise(resolve => setTimeout(resolve, INTERVAL_MS));
  }

  const mismatches = [...results.values()].filter(row => !row.match);
  const report = {
    schema: 'gridatlas.live-bytes-verification.v1',
    base_url: BASE,
    commit,
    generation: current.generation,
    composition_version: current.composition_version ?? null,
    started_at: startedAt,
    finished_at: new Date().toISOString(),
    attempts: attempt,
    paths_checked: targets.size,
    paths_matched: targets.size - mismatches.length,
    problems,
    status: mismatches.length || problems.length ? 'FAIL' : 'PASS',
    mismatches,
    results: [...results.values()].map(({ path: p, why, http, match, expected: e, attempts }) => ({ path: p, why, http, match, bytes: e.bytes, sha256: e.sha256, attempts }))
  };
  if (REPORT) {
    fs.mkdirSync(path.dirname(path.resolve(REPORT)), { recursive: true });
    fs.writeFileSync(REPORT, `${JSON.stringify(report, null, 2)}\n`);
    console.log(`report=${REPORT}`);
  }
  for (const problem of problems) console.error(`::error title=live-bytes::${problem}`);
  for (const row of mismatches) {
    const live = row.live ? `${row.live.bytes} B sha256 ${row.live.sha256}` : `no body (${row.error || 'fetch failed'})`;
    console.error(`::error title=live-bytes mismatch::${row.path} (${row.why}) HTTP ${row.http}: committed ${row.expected.bytes} B sha256 ${row.expected.sha256}, live ${live}`);
  }
  console.log(`${report.status}: ${report.paths_matched}/${report.paths_checked} live paths byte-identical to ${commit || 'working tree'} (generation ${current.generation}) at ${BASE}`);
  if (report.status !== 'PASS') process.exitCode = 1;
}

await main();

Verify Live

A JavaScript module in the scope folder of GridAtlas covering the Renewable Energy Planning Database (REPD) register and postcodes, and uses data from postcodes.io.

rendergridatlas / tools/scope/verify-live.mjs · lines 1–195 of 195 · Not reached from any entry point (candidate for review) · pattern clone (shared by 15 files)

What it does
It draws the REPD register and postcodes. Defines 7 functions or classes, including invariant, clone, stateSnapshot, waitForDeployedCurrent, record. Uses libraries node:fs, node:path, node:url, 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: the REPD register, postcodes.
Inputs & outputs
In: data source: postcodes.io; JSON file current.json.
What it achieves
It writes report (`writeReport`) and is built from the state snapshot helper (`stateSnapshot`) and the wait for deployed current helper (`waitForDeployedCurrent`). Its name says it verifies live. Defines `invariant`, `clone`, `stateSnapshot` and 4 more.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/scope · JavaScript module
Uses
GridAtlas — Index Page (estate URL), node:fs, node:path, node:url, playwright
Used by
none found
Produces
invariant, clone, stateSnapshot, waitForDeployedCurrent, record, run, writeReport
Defines here
invariant, clone, stateSnapshot, waitForDeployedCurrent, record, run, writeReport
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/scope/verify-live.mjs:1-195 · blob f16bbed46c93d49870f72bedcdfe8797f19b5367 · 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: unreached_review
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium, request } from 'playwright';

const BASE = String(process.env.GRIDATLAS_BASE_URL || 'https://ventusltd.github.io/gridatlas/').replace(/\/?$/, '/');

/* The composition this verifier expects the live surface to reach is READ from
   the composition this repository declares, never written down here.
   ------------------------------------------------------------------------
   It used to be a literal: generation 202608301624, composition_version v9.5.
   That was true on 2026-08-30 and false by the next cut. Measured against the
   live surface on 2026-09-03, thirty-odd generations later:

     live      generation 202609030234  v9.88
     literal   generation 202608301624  v9.5     -> can never match again

   So waitForDeployedCurrent could only ever spend four minutes polling and
   then throw. That is why state/live-set.json still carries
   verified_at 2026-08-30T04:07:46Z while its atlas_composition pointer was
   restamped on every one of those generations: the attestation is not stale
   because nobody ran the verifier, it is stale because the verifier could not
   pass. An expectation that has to be edited by hand on every cut will be
   wrong by the second one.

   fileURLToPath, never new URL().pathname: on Windows the latter yields
   "/C:/Users/..." and join() then produces "C:\C:\Users\...". */
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const DECLARED = JSON.parse(fs.readFileSync(path.join(ROOT, 'atlas', 'current.json'), 'utf8'));
const report = {
  schema: 'gridatlas.live-cartridge-verification.v1',
  base_url: BASE,
  status: 'RUNNING',
  deployed_current: null,
  tests: [],
  browser_console_errors: [],
  failure: null
};
let browser;
let page;

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

function clone(value) {
  return JSON.parse(JSON.stringify(value));
}

async function stateSnapshot() {
  if (!page) return null;
  return page.evaluate(() => JSON.parse(JSON.stringify(window.__GRIDATLAS_PLACE_SEARCH__ || null))).catch(() => null);
}

async function waitForDeployedCurrent() {
  const api = await request.newContext({ extraHTTPHeaders: { 'Cache-Control': 'no-cache' } });
  try {
    for (let attempt = 1; attempt <= 24; attempt += 1) {
      const response = await api.get(`${BASE}atlas/current.json?scope_verify=${Date.now()}`);
      if (response.ok()) {
        const current = await response.json();
        const sameOrder = Array.isArray(current?.cartridge_order)
          && JSON.stringify(current.cartridge_order) === JSON.stringify(DECLARED.cartridge_order);
        if (current?.schema === 'gridatlas.current.v2' && current?.generation === DECLARED.generation && current?.composition_version === DECLARED.composition_version && current?.scope_closure?.status === 'DONE' && sameOrder) {
          return current;
        }
        report.deployed_generation_seen = current?.generation ?? null;
      }
      await new Promise(resolve => setTimeout(resolve, 10_000));
    }
    /* Name both generations. "did not reach the composition" sent a previous
       reader looking for a broken deploy when the expectation was the thing
       that was wrong. */
    throw new Error(`public atlas/current.json did not reach the declared composition: expected ${DECLARED.generation} ${DECLARED.composition_version}, last saw ${report.deployed_generation_seen ?? 'nothing'}`);
  } finally {
    await api.dispose();
  }
}

async function record(name, action) {
  const entry = { name, status: 'RUNNING', state: null, url: null };
  report.tests.push(entry);
  try {
    await action(entry);
    entry.state = await stateSnapshot();
    entry.url = page.url();
    entry.status = 'PASS';
    console.log(JSON.stringify({ test: name, status: entry.status, url: entry.url, state: entry.state }));
  } catch (error) {
    entry.state = await stateSnapshot();
    entry.url = page?.url() || null;
    entry.status = 'FAIL';
    entry.message = String(error?.message || error);
    console.error(JSON.stringify({ test: name, status: entry.status, message: entry.message, url: entry.url, state: entry.state }));
    throw error;
  }
}

async function run() {
  report.deployed_current = await waitForDeployedCurrent();
  browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
  page = await context.newPage();
  page.on('console', message => {
    if (message.type() === 'error') report.browser_console_errors.push(message.text());
  });
  page.on('pageerror', error => report.browser_console_errors.push(String(error?.message || error)));

  await record('exact REPD deep link remains automatic', async () => {
    await page.goto(`${BASE}atlas/?repd_ref=13599`, { waitUntil: 'domcontentloaded', timeout: 120_000 });
    await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.status === 'RESOLVED', null, { timeout: 120_000 });
    const result = await page.evaluate(() => ({
      deep_link: JSON.parse(JSON.stringify(window.__GRIDATLAS_PLACE_SEARCH__.deep_link)),
      selection: JSON.parse(JSON.stringify(window.__GRIDATLAS_PLACE_SEARCH__.last_selection)),
      atlas: JSON.parse(JSON.stringify(window.__GRIDATLAS_ATLAS__))
    }));
    invariant(result.deep_link.repd_ref === '13599' && result.deep_link.mapped === true, 'exact REPD 13599 did not map');
    invariant(result.selection?.repd_ref === '13599', 'exact REPD selection was not retained');
    invariant(new URL(page.url()).searchParams.get('repd_ref') === '13599', 'exact REPD URL identity missing');
  });

  await record('SW1A 1AA flies to a LOCATION_ONLY postcode', async () => {
    const input = page.locator('#search-input');
    await input.fill('SW1A 1AA');
    await page.locator('#search-btn').click();
    const result = page.locator('.search-result-item[data-location-kind="postcode"]').first();
    await result.waitFor({ state: 'visible', timeout: 60_000 });
    await result.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 });
    invariant(!new URL(page.url()).searchParams.has('repd_ref'), 'postcode selection retained repd_ref');
    const selected = await page.evaluate(() => JSON.parse(JSON.stringify(window.__GRIDATLAS_PLACE_SEARCH__.last_location_selection)));
    invariant(String(selected.label).replace(/\s/g, '').toUpperCase() === 'SW1A1AA', `unexpected postcode selection ${selected.label}`);
  });

  await record('Truro town result flies to a LOCATION_ONLY place', async () => {
    const input = page.locator('#search-input');
    await input.fill('Truro');
    await page.locator('#search-btn').click();
    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 });
    invariant(!new URL(page.url()).searchParams.has('repd_ref'), 'town selection set repd_ref');
    const selected = await page.evaluate(() => JSON.parse(JSON.stringify(window.__GRIDATLAS_PLACE_SEARCH__.last_location_selection)));
    invariant(/truro/i.test(selected.label), `unexpected place selection ${selected.label}`);
  });

  await record('known REPD project stays first and sets exact identity', async () => {
    const input = page.locator('#search-input');
    await input.fill('Beacon Fen Energy Park');
    await page.locator('#search-btn').click();
    const exact = page.locator('.search-result-item[data-repd-ref="13599"]').first();
    await exact.waitFor({ state: 'visible', timeout: 60_000 });
    const firstIdentity = await page.locator('.search-result-item').first().getAttribute('data-repd-ref');
    invariant(firstIdentity === '13599', `REPD result was not first; first identity=${firstIdentity}`);
    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', 'REPD project click did not set repd_ref');
  });

  await record('blocked postcodes.io leaves REPD search operational', async () => {
    await page.route('https://api.postcodes.io/**', route => route.abort('failed'));
    await page.evaluate(() => { window.__GRIDATLAS_PLACE_SEARCH__.geocoder_failures.length = 0; });
    const input = page.locator('#search-input');
    await input.fill('Beacon Fen Energy Park');
    await page.locator('#search-btn').click();
    const exact = page.locator('.search-result-item[data-repd-ref="13599"]').first();
    await exact.waitFor({ state: 'visible', timeout: 60_000 });
    await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.geocoder_failures?.length > 0, null, { timeout: 30_000 });
    const state = await page.evaluate(() => JSON.parse(JSON.stringify(window.__GRIDATLAS_PLACE_SEARCH__)));
    invariant(state.geocoder_failures.length > 0, 'blocked geocoder failure was not recorded');
    invariant(await exact.isVisible(), 'REPD result disappeared when geocoder failed');
  });

  report.status = 'PASS';
}

function writeReport() {
  const generation = report.deployed_current?.scope_closure?.generation || report.deployed_current?.generation || 'unknown';
  const output = path.join(process.cwd(), 'reports', 'scope-loop', `${generation}-live-verification.json`);
  fs.mkdirSync(path.dirname(output), { recursive: true });
  fs.writeFileSync(output, `${JSON.stringify(report, null, 2)}\n`, 'utf8');
  console.log(`report=${path.relative(process.cwd(), output)}`);
}

try {
  await run();
} catch (error) {
  report.status = 'FAIL';
  report.failure = String(error?.stack || error);
  process.exitCode = 1;
} finally {
  if (browser) await browser.close().catch(() => {});
  writeReport();
}

Build

A JavaScript module in the secondary folder of GridAtlas.

storagegridatlas / tools/secondary/build.mjs · lines 1–7 of 7 · Not reached from any entry point (candidate for review)

What it does
It loads data. Uses libraries node:fs, node:vm. Side effects: 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.
Inputs & outputs
In: command-line arguments.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/secondary · JavaScript module
Uses
UKPN Secondary Substations (new URL import.meta.url), node:fs, node:vm
Used by
none found
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 tools/secondary/build.mjs:1-7 · blob 4a36bd2f0a5483bdd7145c904be592096cdd00e2 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import fs from 'node:fs';
import vm from 'node:vm';
const out=process.argv[process.argv.indexOf('--out')+1];
if(!process.argv.includes('--out')||!out)throw Error('usage: build.mjs --out PATH');
const source=fs.readFileSync(new URL('./src/202612010912-native-layer.js',import.meta.url));
new vm.Script(source.toString('utf8'));
fs.writeFileSync(out,source,{flag:'wx'});

G203 Swarm 06 Viewport Lifecycle Test

A test in the secondary folder of GridAtlas that checks G203 Regional Native Viewport. It is built from the flush step (`flush`) and the check step (`check`).

testgridatlas / tools/secondary/g203-swarm-06-viewport-lifecycle.test.mjs · lines 1–20 of 20 · Entry point · pattern flush (shared by 14 files)

What it does
It tests its inputs. Defines flush, check. Uses libraries node:fs, node:assert/strict. Side effects: 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.
Downstream impact
Used directly by 1 file: GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Execute the actual candidate lifecycle with controlled asynchronous query outcomes.
Why it matters
Run by GridAtlas PR File Size Guard Workflow.
Application
gridatlas · tools/secondary · test
Uses
G203 Regional Native Viewport (new URL import.meta.url), node:fs, node:assert/strict
Used by
run by GridAtlas PR File Size Guard Workflow (workflow run)
Produces
flush, check
Defines here
flush, check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/secondary/g203-swarm-06-viewport-lifecycle.test.mjs:1-20 · blob 2d19c9e4b25b7e94e4a7166e105c18315796f3b2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// Execute the actual candidate lifecycle with controlled asynchronous query outcomes.
import {readFileSync} from 'node:fs';
import assert from 'node:assert/strict';
const source=readFileSync(new URL('../../atlas/modules/g203-regional-native-viewport.js',import.meta.url),'utf8');
const start=source.indexOf('    let ukpnViewportEpoch =');
const end=source.indexOf("    map.on('moveend',requestUKPNViewport);",start);
assert.ok(start>=0&&end>start,'candidate lifecycle missing');
const factory=new Function('map','RUNTIME_STATE','regionalEligible','updateUIState','window','console',source.slice(start,end)+'\nreturn {requestUKPNViewport,read:()=>({epoch:ukpnViewportEpoch,wanted:ukpnViewportWanted,loaded:ukpnViewportLoaded,busy:ukpnViewportBusy})};');
let active=true,west=0,data=[],states=[],pending=[],state={};
const map={getBounds:()=>({getWest:()=>west,getSouth:()=>51,getEast:()=>west+.1,getNorth:()=>52}),getSource:()=>({setData:fc=>data=fc.features})};
const api=factory(map,{ukpn_secondary:state},()=>active,(_,s)=>states.push(s),{__GRIDATLAS_MODULES__:{ukpnSecondary:{viewportFeatures:()=>new Promise((resolve,reject)=>pending.push({resolve,reject}))}}},{error:()=>{}});
const flush=async()=>{for(let i=0;i<10;i++)await Promise.resolve()};
const check=(name,condition)=>{assert.ok(condition,name);console.log('PASS',name)};
api.requestUKPNViewport();pending[0].resolve(['A']);await flush();check('initial A loaded',state.loaded&&data[0]==='A');
west=1;api.requestUKPNViewport();pending[1].reject(Error('simulated'));await flush();check('current failure clears old data',data.length===0);check('current failure invalidates previous key',api.read().loaded===null&&!state.loaded);
west=0;api.requestUKPNViewport();check('return to A requests new query',pending.length===3);pending[2].resolve(['A2']);await flush();check('retry restores data',state.loaded&&data[0]==='A2');
west=2;api.requestUKPNViewport();west=3;api.requestUKPNViewport();check('serialized queries',pending.length===4);pending[3].resolve(['stale']);await flush();check('stale result not committed',data[0]==='A2'&&pending.length===5);pending[4].resolve(['D']);await flush();check('latest result committed',data[0]==='D');
west=4;api.requestUKPNViewport();active=false;api.requestUKPNViewport();check('off evicts immediately',data.length===0&&!state.loaded);pending[5].resolve(['disabled']);await flush();check('off rejects late result',data.length===0&&!state.loaded);
active=true;api.requestUKPNViewport();pending[6].resolve(['E']);await flush();check('re-enable reacquires',state.loaded&&data[0]==='E');
console.log('11 viewport lifecycle checks passed (simulated queries, actual source)');

Owner Test Proof

A JavaScript module in the secondary folder of GridAtlas that tests composition and substations, using SHA-256. It is built from the sha step (`sha`) and the prove step (`prove`).

testgridatlas / tools/secondary/owner-test-proof.mjs · lines 1–23 of 23 · pattern prove (shared by 3 files)

What it does
It tests composition and substations. Defines sha, prove. Uses libraries node:fs, node:assert/strict, node:crypto. Side effects: 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: substations.
Inputs & outputs
In: JSON file -composition.json; JSON file current.json.
Downstream impact
Used directly by 7 files: Substation Intelligence Proof (gridatlas); UKPN Secondary Card Proof (gridatlas); UKPN Secondary Substations Proof (gridatlas); SatNav Start Walk Proof (gridatlas); and 3 more. Reached from 1 other entry point, including GridAtlas PR File Size Guard Workflow (gridatlas).
What it achieves
Rebuild and verify each cut cartridge and its preview manifest. It reads `-composition.json`.
Why it matters
Imported by 7 files, including Substation Intelligence Proof, UKPN Secondary Card Proof and UKPN Secondary Substations Proof.
Application
gridatlas · tools/secondary · JavaScript module
Uses
Regional Interface (import), Secondary Vicinity (import), node:fs, node:assert/strict, node:crypto
Used by
imported by Substation Intelligence Proof (import), imported by UKPN Secondary Card Proof (import), imported by UKPN Secondary Substations Proof (import), imported by SatNav Start Walk Proof (import), imported by SatNav Waypoint Map Proof (import), imported by UK Offtakers Overlay Proof (import), imported by Vicinity Focus Proof (import)
Produces
prove
Defines here
sha, prove
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/secondary/owner-test-proof.mjs:1-23 · blob 0a83196fdda76e877704fc7eea6529a9d2cbd747 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// Rebuild and verify each cut cartridge and its preview manifest.
import fs from 'node:fs';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {buildRegional} from './regional-interface.mjs';
import {buildSecondaryVicinity} from '../satnav/guidance/secondary-vicinity.mjs';
const sha=b=>createHash('sha256').update(b).digest('hex');
export function prove(g,id) {
  const m=JSON.parse(fs.readFileSync('atlas/manifests/'+g+'-composition.json','utf8'));
  const p=JSON.parse(fs.readFileSync('atlas/v/'+g+'/current.json','utf8'));
  const copy={...m};for(const k of ['parent_generation','version','cut_at_utc','note','acceptance','candidate_status'])delete copy[k];
  assert.deepEqual(p,JSON.parse(JSON.stringify(copy,null,1).replace(/": "(\.\/|\.\.\/)/g,'": "../../')));
  assert.equal(m.previous_generation,'202611222343');
  assert.equal(new Set(m.cartridge_order).size,m.cartridges.length);
  for(const c of m.cartridges){const b=fs.readFileSync('atlas/'+c.path.slice(2));assert.equal(sha(b),c.sha256,c.id);assert.equal(b.length,c.bytes,c.id);}
  for(const d of m.runtime_dependency_pins||[]){const b=fs.readFileSync(d.path);assert.equal(sha(b),d.sha256,d.path);assert.equal(b.length,d.bytes);}
  const entry=m.cartridges.find(c=>c.id===id);assert.equal(entry.generation,g);
  let expected;
  if(['substation-intelligence','ukpn-secondary-substations','ukpn-secondary-card'].includes(id)){const b=buildRegional();expected=b[{'substation-intelligence':'engine','ukpn-secondary-substations':'data','ukpn-secondary-card':'card'}[id]];}
  if(['uk-offtakers-overlay','vicinity-focus'].includes(id)){const b=buildSecondaryVicinity();expected=b[id==='uk-offtakers-overlay'?'engine':'focus'];}
  if(expected!==undefined)assert.equal(fs.readFileSync('atlas/'+entry.path.slice(2),'utf8'),expected);
  console.log('PASS '+g+' '+id+' exact source, manifest and cartridge hashes');
}

Regional Interface

A JavaScript module in the secondary folder of GridAtlas that reads composition, substations and 11kV, using SHA-256. It replaces once (`replaceOnce`), patches native engine (`patchNativeEngine`) and splits secondary adapter (`splitSecondaryAdapter`).

rendergridatlas / tools/secondary/regional-interface.mjs · lines 1–108 of 108 · pattern replaceOnce (shared by 2 files)

What it does
It loads composition, substations and 11kV. Defines 11 functions or classes, including replaceOnce, patchNativeEngine, regionalEligible, handleLayerToggle, splitSecondaryAdapter. Uses libraries node:fs, node:crypto, node:vm, node:path, node:url. 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: substations, 11kV.
Inputs & outputs
In: JSON file 202612010912-composition.json; command-line arguments. Voltage levels named: 11kV.
Downstream impact
Used directly by 3 files: Owner Test Proof (gridatlas); Regional Interface Test (gridatlas); Regional Preview (gridatlas). Reached from 4 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); CI PR Gate (gridatlas); Map Promotion Rehearsal (gridatlas).
What it achieves
Generate replacement native engine plus separate data/card modules. Its code works with 11 kV. It reads `manifests/202612010912-composition.json`.
Why it matters
Imported by Regional Preview. Checked by 2 tests, including Owner Test Proof.
Application
gridatlas · tools/secondary · JavaScript module
Uses
GridAtlas — Atlas Page (new URL import.meta.url), node:fs, node:crypto, node:vm, node:path, node:url
Used by
imported by Owner Test Proof (import), imported by Regional Interface Test (import), imported by Regional Preview (import)
Produces
patchNativeEngine, splitSecondaryAdapter, assertDataBoundary, readPinnedEngine, buildRegional
Defines here
replaceOnce, patchNativeEngine, regionalEligible, handleLayerToggle, splitSecondaryAdapter, visible, attach, assertDataBoundary, readPinnedEngine, buildRegional, read
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/secondary/regional-interface.mjs:1-108 · blob 6ddd339e38a04a0d8b22b3661b40dbde00e2233d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// Source-only candidate; immutable V9.198 inputs remain unchanged.
// Generate replacement native engine plus separate data/card modules.
import fs from 'node:fs';
import {createHash} from 'node:crypto';
import vm from 'node:vm';
import path from 'node:path';
import {pathToFileURL} from 'node:url';
function replaceOnce(s, a, b) {
  if (!s.includes(a) || s.indexOf(a) !== s.lastIndexOf(a)) throw Error("Expected one source anchor: " + a.slice(0,100));
  return s.replace(a,b);
}
export function patchNativeEngine(s) {
  s=replaceOnce(s,"    function handleLayerToggle(layerId, isVisible) {",`    // Interface-owned acquisition policy. Native controls remain the sole selection owner.
    const regionalSelected = new Set();
    function regionalEligible(layerId) {
        const threshold = getLayerConfig(layerId)?.acquireMinZoom;
        return threshold === undefined || (regionalSelected.has(layerId) && map.getZoom() >= threshold);
    }
    function handleLayerToggle(layerId, isVisible) {
        if (getLayerConfig(layerId)?.acquireMinZoom !== undefined) {
            if (isVisible) regionalSelected.add(layerId); else regionalSelected.delete(layerId);
        }`);
  s=replaceOnce(s,"if (isVisible && layerId !== '400') hydrateLayer(layerId);","if (isVisible && layerId !== '400' && regionalEligible(layerId)) hydrateLayer(layerId);");
  s=replaceOnce(s,"if (!state || state.loaded || state.loading) return;","if (!state || state.loaded || state.loading || !regionalEligible(layerId)) return;");
  s=replaceOnce(s,"                let features = await fetchAndParseGeoJSON(layerConfig.url);",`                // Selection and zoom can change while waiting for a shared queue slot.
                if (!regionalEligible(layerId)) { state.loading = false; updateUIState(layerId, 'WAIT'); return; }
                let features = await fetchAndParseGeoJSON(layerConfig.url);`);
  s=replaceOnce(s,"    map.on('load', () => {\n        buildDOM();",`    map.on('zoomend', () => {
        for (const layerId of regionalSelected) {
            if (regionalEligible(layerId)) hydrateLayer(layerId);
        }
    });
    map.on('load', () => {
        buildDOM();`);
  // The historical menu inventory deliberately fails closed. Register precisely
  // the one authorised additional layer; preserve all six menus and uniqueness.
  s=replaceOnce(s,"var EXPECTED_ENGINE_LAYERS = 60;","var EXPECTED_ENGINE_LAYERS = 61;");
  s=replaceOnce(s,"var EXPECTED_LAYER_CONTROLS = 63;","var EXPECTED_LAYER_CONTROLS = 64;");
  s=replaceOnce(s,"        && unique.size === EXPECTED_LAYER_CONTROLS","        && unique.has('engine:ukpn_secondary')\n        && unique.size === EXPECTED_LAYER_CONTROLS");
  s=replaceOnce(s,"menu not installed: expected 60 engine + 3 Pipeline News layer controls; found ","menu not installed: expected 61 engine + 3 Pipeline News layer controls; found ");
  return s;
}
export function splitSecondaryAdapter(s) {
  s=replaceOnce(s,"radius:['interpolate',['linear'],['zoom'],14,3,18,8],url:ROUTE,minzoom:14,preload:false","radius:['interpolate',['linear'],['zoom'],7,1,9,1.5,12,2.5,14,4,16,6,18,8],url:ROUTE,minzoom:7,acquireMinZoom:7,preload:false");
  s=replaceOnce(s,"{...l,minzoom:13,preload:false,label:'11 kV (OSM - quarantined)'}","{...l,minzoom:7,acquireMinZoom:7,preload:false,label:'11 kV (OSM)',radius:['interpolate',['linear'],['zoom'],7,1,9,1.5,12,2.5,14,4,16,6,18,8]}");
  const start=s.indexOf("  // Gate native checkbox activation"), end=s.indexOf("  const previousFetch = W.fetch.bind(W);");
  const cardStart=s.indexOf("    function augmentPopup() {"), cardEnd=s.indexOf("    function bindMap() {",cardStart);
  if (!(start>=0 && start<cardStart && cardStart<cardEnd && cardEnd<end)) throw Error("Unexpected predecessor card boundaries");
  let popup=s.slice(cardStart,cardEnd);
  popup=replaceOnce(popup,"map.getZoom()<14 || !main()?.checked","map.getZoom()<7 || !visible()");
  popup=replaceOnce(popup,"map.getZoom()>=16 && main()?.checked","map.getZoom()>=16 && visible()");
  popup=replaceOnce(popup,"detailsFor(feature.id)","data.detailsFor(feature.id)");
  s=s.slice(0,start)+`  const originalInit = W.initVentusMap;
  if (typeof originalInit !== 'function') throw Error('GridAtlas native init unavailable');
  W.initVentusMap = function(options) {return originalInit.call(this,extend(options));};
`+s.slice(end);
  s=replaceOnce(s,"    // Recheck at native queue acquisition, in case zoom or visibility changed while queued.\n    if (zoomGate && !zoomGate.canAcquire()) {zoomGate.defer();throw new DOMException('UKPN acquisition deferred until zoom 14','AbortError');}\n","");
  s=replaceOnce(s,"{normalize,unpack,extend,archive:ARCHIVE,sha256:SHA,source:SOURCE}","{normalize,unpack,extend,detailsFor,archive:ARCHIVE,sha256:SHA,source:SOURCE}");
  const card=`/* Interface-owned selected asset card. No menu mutation. */
(() => {
  'use strict';
  const W=window, doc=W.document, ID='ukpn_secondary';
  const data=W.__GRIDATLAS_MODULES__?.ukpnSecondary;
  if(!data)throw Error('UKPN data adapter must load before card');
  let map=null;
  const visible=()=>map?.getLayer('l-'+ID) && map.getLayoutProperty('l-'+ID,'visibility')==='visible';
${popup}
  let frames=0;
  function attach(){
    map=W.__GRIDATLAS_V9_MAP__ || null;
    if(!map){if(++frames<1200)W.requestAnimationFrame(attach);return;}
    map.on('zoomend',augmentPopup);
    map.on('click',()=>W.setTimeout(augmentPopup,0));
  }
  attach();
})();
`;
  assertDataBoundary(s);
  return {data:s,card};
}
export function assertDataBoundary(source) {
  // Narrow diagnostic: not a sandbox or a substitute for browser tests.
  if (/\b(?:document|querySelector(?:All)?|stopImmediatePropagation|stopPropagation|addEventListener|dispatchEvent)\b|\.\s*(?:checked|disabled|style|innerHTML|appendChild|replaceChildren)\b/.test(source)) throw Error("Data adapter contains protected DOM/control operations");
}
// Derive from the exact assembled engine selected by V9.197 and V9.198,
// not the older immutable shell script. Otherwise the regional replacement
// silently removes the substation intelligence and all carried modules.
export function readPinnedEngine(){
  const atlas=new URL('../../atlas/',import.meta.url);
  const manifest=JSON.parse(fs.readFileSync(new URL('manifests/202612010912-composition.json',atlas),'utf8'));
  const entry=manifest.cartridges.find(c=>c.id==='substation-intelligence');
  if(entry?.path!=='./cartridges/202609062358-substation-intelligence-v9-63.js' || entry.sha256!=='d94b0de50deddac77643325b10fbe490ce44b8c406dbc6c67e6e7cadbdaa8ec6' || entry.replace_script!=='ventus-corev8engine.js') throw Error('Unexpected V9.198 engine pin');
  const bytes=fs.readFileSync(new URL(entry.path,atlas));
  if(createHash('sha256').update(bytes).digest('hex')!==entry.sha256) throw Error('Predecessor engine integrity mismatch');
  return bytes.toString('utf8');
}
export function buildRegional(){
  const read=p=>fs.readFileSync(new URL(p,import.meta.url),'utf8');
  const engine=patchNativeEngine(readPinnedEngine());
  const {data,card}=splitSecondaryAdapter(read('./src/202612010912-native-layer.js'));
  for(const source of [engine,data,card])new vm.Script(source);
  return {engine,data,card};
}
if(process.argv[1] && import.meta.url===pathToFileURL(path.resolve(process.argv[1])).href){
  const dir=process.argv[2];if(!dir)throw Error('usage: node tools/secondary/regional-interface.mjs OUTPUT_DIRECTORY');
  const built=buildRegional();fs.mkdirSync(dir,{recursive:true});
  for(const [name,source] of Object.entries(built))fs.writeFileSync(path.join(dir,name+'.js'),source,{flag:'wx'});
}