GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / code-generator / apps/substation-finder/Ps

Place Global Search Arrival Identity and 1 more file

A JavaScript file in the substation finder folder of Code Generator that maps Renewable Energy Planning Database (REPD) projects, using SHA-256 and uses data from the GridAtlas repository.

700 lines of JavaScript from code-generator, in 2 files. Topic: Grid network and substations. Section 267 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. Arrival Identity Browser render · code-generator / apps/substation-finder/Ps/202609040229-arrival-identity.browser.mjs lines 1–302
  2. Place Global Search Arrival Identity render · code-generator / apps/substation-finder/Ps/202609040229-place-global-search-arrival-identity.js lines 1–398

Arrival Identity Browser

A JavaScript module in the substation finder folder of Code Generator that reads Renewable Energy Planning Database (REPD) and solar from the GridAtlas repository.

Set aside from the main view: 98% of its lines are the same as tools/proofs/202609040229-arrival-identity.browser.mjs (gridatlas), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Arrival Identity Browser; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9767 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/202609040229-arrival-identity.browser.mjs:1-309 2b59b09048dd5996738ba226e7b08a5d1c33f989
  • sha256 928c87be0755fea4aa3af7b5dda36208512d5a651a77b36f2b9abb2663304b56
  • target sha256 977439fbe96ce019ddbc4eb4ee0b1dd69468ebf82ca0699ef4fa1bc594ab5f85
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

rendercode-generator / apps/substation-finder/Ps/202609040229-arrival-identity.browser.mjs · lines 1–302 of 302 · version 2026-09-04 02:29 · Not reached from any entry point (candidate for review) · pattern ProofMap (shared by 3 files)

What it does
It loads REPD and solar. Defines capture, ProofMap. Uses libraries node:assert/strict, node:http, node:fs/promises, node:path, node:module. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'substation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
Inputs & outputs
In: data source: gridatlas data; JSON file current.json; JSON file repd_v9_manifest_202608290716.json.
What it achieves
It is built from the proof map class (`ProofMap`). Defines `capture` and `ProofMap`.
Why it matters
No other file in the estate was found to import it.
Application
code-generator · apps/substation-finder/Ps · JavaScript module
Uses
node:assert/strict, node:http, node:fs/promises, node:path, node:module, node:url, playwright
Used by
none found
Produces
capture, ProofMap
Defines here
capture, ProofMap
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Ps/202609040229-arrival-identity.browser.mjs:1-302 · blob d30ab61ca575a8e296b3943b61a485ab0aad1ced · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile, stat } from 'node:fs/promises';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const require = createRequire(import.meta.url);
let playwright;
try {
  playwright = require('playwright');
} catch {
  playwright = require(path.resolve(ROOT, '..', '..', 'gridatlas-v9104-fullscreen',
    'node_modules', 'playwright'));
}
const { chromium } = playwright;
const CURRENT = JSON.parse(await readFile(path.join(ROOT, 'atlas', 'current.json'), 'utf8'));
const GENERATION = CURRENT.generation;
const VIEWPORT = { width: 393, height: 852 };
const REPD_MANIFEST_URL =
  'https://ventusltd.github.io/gridatlas/data/repd_v9_manifest_202608290716.json';
const MIME = new Map([
  ['.html', 'text/html; charset=utf-8'], ['.js', 'text/javascript; charset=utf-8'],
  ['.mjs', 'text/javascript; charset=utf-8'], ['.json', 'application/json; charset=utf-8'],
  ['.css', 'text/css; charset=utf-8'], ['.wasm', 'application/wasm'],
  ['.parquet', 'application/octet-stream']
]);

const server = createServer(async (request, response) => {
  try {
    const requestPath = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
    const relative = requestPath.replace(/^\/+/, '') || 'index.html';
    let target = path.resolve(ROOT, relative);
    if (!target.startsWith(`${ROOT}${path.sep}`) && target !== ROOT) {
      response.writeHead(403).end('outside repository');
      return;
    }
    if ((await stat(target)).isDirectory()) target = path.join(target, 'index.html');
    const bytes = await readFile(target);
    response.writeHead(200, {
      'content-type': MIME.get(path.extname(target).toLowerCase())
        || 'application/octet-stream',
      'cache-control': 'no-store', 'access-control-allow-origin': '*'
    });
    response.end(bytes);
  } catch {
    response.writeHead(404).end('not found');
  }
});
await new Promise((resolve, reject) => {
  server.once('error', reject);
  server.listen(0, '127.0.0.1', resolve);
});
const { port } = server.address();

const fixtures = [{
  label: 'supplied-point active-register absence', identity: 'NOT_IN_ACTIVE_REGISTER',
  verification: 'NOT_IN_ACTIVE_REGISTER', measures: true,
  query: { repd_ref: '12453', project: 'Thorpe Marsh Power Station - Battery Energy Storage',
    technology: 'bess', capacity_mw: '1450', latitude: '53.5802575',
    longitude: '-1.0850616', zoom: '12' }
}, {
  label: 'ref-only active-register absence', identity: 'NOT_IN_ACTIVE_REGISTER',
  verification: 'NOT_IN_ACTIVE_REGISTER', measures: false,
  query: { repd_ref: '12453' }
}, {
  label: 'failed owner retries to official match', identity: 'RESOLVED',
  verification: null, measures: true, retry: true,
  query: { repd_ref: '12588' }
}, {
  label: 'failed owner retries to active-register absence',
  identity: 'NOT_IN_ACTIVE_REGISTER', verification: 'NOT_IN_ACTIVE_REGISTER',
  measures: false, retry: true, query: { repd_ref: '12453' }
}, {
  label: 'official active-register match', identity: 'RESOLVED',
  verification: 'VERIFIED', measures: true,
  query: { repd_ref: '12588', project: 'Botley West, Botley - Botley West Solar Project',
    technology: 'solar', capacity_mw: '840', latitude: '51.8132088',
    longitude: '-1.3489728', zoom: '12' }
}];
const filter = String(process.env.GRIDATLAS_BROWSER_FIXTURE || '').trim();
const selected = filter ? fixtures.filter(({ label }) => label.includes(filter)) : fixtures;
assert.ok(selected.length, `no fixture matched GRIDATLAS_BROWSER_FIXTURE=${filter}`);

const browser = await chromium.launch({ headless: true });
const receipts = [];
try {
  for (const fixture of selected) {
    const context = await browser.newContext({ viewport: VIEWPORT, isMobile: true,
      hasTouch: true, deviceScaleFactor: 1 });
    const page = await context.newPage();
    const pageErrors = [];
    const consoleErrors = [];
    const requestFailures = [];
    const requests = [];
    let manifestAttempts = 0;
    let beforeRetry = null;
    let inducedFailure = null;
    if (fixture.retry) {
      await page.route(REPD_MANIFEST_URL, async (route) => {
        manifestAttempts += 1;
        if (manifestAttempts === 1) await route.abort('failed');
        else await route.continue();
      });
    }
    page.on('pageerror', (error) => pageErrors.push(String(error?.message || error)));
    page.on('console', (message) => {
      if (message.type() === 'error') consoleErrors.push(message.text());
    });
    page.on('request', (request) => requests.push(request.url()));
    page.on('requestfailed', (request) => requestFailures.push({
      url: request.url(), error: request.failure()?.errorText || 'unknown'
    }));
    await page.addInitScript(() => {
      let value;
      const capture = (candidate) => {
        if (!candidate || typeof candidate.Map !== 'function'
            || candidate.Map.__gridatlasProofWrapped) return candidate;
        const OriginalMap = candidate.Map;
        function ProofMap(...args) {
          const instance = Reflect.construct(OriginalMap, args,
            new.target === ProofMap ? OriginalMap : new.target);
          window.__GRIDATLAS_PROOF_MAP__ = instance;
          return instance;
        }
        Object.setPrototypeOf(ProofMap, OriginalMap);
        ProofMap.prototype = OriginalMap.prototype;
        ProofMap.__gridatlasProofWrapped = true;
        candidate.Map = ProofMap;
        return candidate;
      };
      Object.defineProperty(window, 'maplibregl', { configurable: true, enumerable: true,
        get: () => value, set: (candidate) => { value = capture(candidate); } });
    });

    const url = `http://127.0.0.1:${port}/atlas/?${new URLSearchParams(fixture.query)}`;
    await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 120_000 });
    await page.waitForFunction((generation) =>
      document.documentElement.dataset.gridatlasGeneration === generation,
    GENERATION, { timeout: 120_000 });
    await page.waitForFunction(() =>
      window.__GRIDATLAS_MODULES__?.menuBar?.installed === true
        && document.querySelectorAll('#gridatlas-menu-bar .gm-title').length === 6
        && window.__GRIDATLAS_PROOF_MAP__, null, { timeout: 120_000 });

    if (fixture.retry) {
      await page.waitForFunction(() =>
        window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.status === 'FAILED'
          && document.querySelector('#gridatlas-boot-status button')?.textContent.trim()
            === 'Try again', null, { timeout: 120_000 });
      beforeRetry = await page.evaluate(() => ({
        status: window.__GRIDATLAS_PLACE_SEARCH__.deep_link.status,
        epoch: window.__GRIDATLAS_PLACE_SEARCH__.deep_link.owner_epoch,
        queries: window.__GRIDATLAS_PLACE_SEARCH__.query_count,
        retries: window.__GRIDATLAS_PLACE_SEARCH__.identity_retry_count
      }));
      inducedFailure = { pageErrors: [...pageErrors], consoleErrors: [...consoleErrors],
        requestFailures: [...requestFailures] };
      await page.click('#gridatlas-boot-status button');
      pageErrors.length = 0;
      consoleErrors.length = 0;
      requestFailures.length = 0;
    }

    try {
      await page.waitForFunction(({ identity, verification, measures }) => {
        const owner = window.__GRIDATLAS_PLACE_SEARCH__?.deep_link;
        const link = window.__GRIDATLAS_NEON_LINKS__;
        return owner?.status === identity
          && (!verification || link?.identity_verification?.status === verification)
          && (measures ? link?.links_drawn > 0 && link?.last_selection?.nearest_km > 0
            : link?.links_drawn === 0
              && /not in the active-register snapshot/u.test(link?.status_message || ''));
      }, { identity: fixture.identity, verification: fixture.verification,
        measures: fixture.measures }, { timeout: 180_000 });
    } catch (error) {
      const diagnostic = await page.evaluate(() => ({
        owner: window.__GRIDATLAS_PLACE_SEARCH__?.deep_link || null,
        query_count: window.__GRIDATLAS_PLACE_SEARCH__?.query_count ?? null,
        retry_count: window.__GRIDATLAS_PLACE_SEARCH__?.identity_retry_count ?? null,
        link: window.__GRIDATLAS_NEON_LINKS__ ? {
          origin: window.__GRIDATLAS_NEON_LINKS__.origin_source || null,
          identity: window.__GRIDATLAS_NEON_LINKS__.identity_verification || null,
          links: window.__GRIDATLAS_NEON_LINKS__.links_drawn,
          selection: window.__GRIDATLAS_NEON_LINKS__.last_selection || null,
          retry: window.__GRIDATLAS_NEON_LINKS__.arrival_retry || null,
          reconciliation: window.__GRIDATLAS_NEON_LINKS__.arrival_reconciliation || null,
          gate: window.__GRIDATLAS_NEON_LINKS__.measure?.arrivalGate?.snapshot?.() || null,
          failures: window.__GRIDATLAS_NEON_LINKS__.failures || []
        } : null,
        status: document.getElementById('gridatlas-boot-status')?.innerText || null
      }));
      throw new Error(`${fixture.label} did not finish: ${JSON.stringify({
        manifestAttempts, diagnostic, pageErrors, consoleErrors, requestFailures
      })}`, { cause: error });
    }

    const result = await page.evaluate(() => {
      const state = window.__GRIDATLAS_PLACE_SEARCH__;
      const owner = state.deep_link;
      const link = window.__GRIDATLAS_NEON_LINKS__;
      const popup = document.querySelector('.maplibregl-popup-content');
      const popupText = popup?.innerText.replace(/\s+/g, ' ').trim() || '';
      return {
        runtime_generation: document.documentElement.dataset.gridatlasGeneration,
        owner_generation: state.generation, source_generation: state.source_generation,
        owner, query_count: state.query_count, retry_count: state.identity_retry_count,
        menus: [...document.querySelectorAll('#gridatlas-menu-bar .gm-title')]
          .map((node) => node.textContent.trim()),
        links_drawn: link.links_drawn,
        nearest_km: link.last_selection?.nearest_km ?? null,
        origin_source: link.origin_source || null,
        verification: link.identity_verification || null,
        status_message: link.status_message || null,
        failures: link.failures || [],
        arrival_retry: link.arrival_retry || null,
        reconciliation: link.arrival_reconciliation || null,
        gate: link.measure?.arrivalGate?.snapshot?.() || null,
        popup_text: popupText,
        visible_measurement: /\d+(?:\.\d+)? km straight/u.test(popupText)
      };
    });

    assert.equal(result.runtime_generation, GENERATION);
    assert.equal(result.owner_generation, GENERATION);
    assert.equal(result.source_generation, '202609040229');
    assert.deepEqual(result.menus, ['File', 'Edit', 'View', 'Scope', 'Grid', 'About']);
    assert.equal(result.owner.status, fixture.identity);
    assert.equal(result.owner.repd_ref, fixture.query.repd_ref);
    assert.equal(requests.some((request) => request.includes('/uk_renewables_pipeline/')),
      false, 'legacy wrong-domain Pipeline request was issued');
    if (fixture.retry) {
      assert.equal(beforeRetry.status, 'FAILED');
      assert.equal(beforeRetry.queries, 0);
      assert.equal(beforeRetry.retries, 0);
      assert.equal(result.query_count, 1);
      assert.equal(result.retry_count, 1);
      assert.ok(result.owner.owner_epoch > beforeRetry.epoch);
      assert.equal(result.arrival_retry.owner_epoch, result.owner.owner_epoch);
      assert.equal(result.arrival_retry.measurement_epoch, result.owner.owner_epoch);
      assert.equal(result.reconciliation.epoch, result.owner.owner_epoch);
      assert.equal(result.reconciliation.owner_epoch, result.owner.owner_epoch);
      assert.equal(result.gate.epoch, result.owner.owner_epoch);
      assert.equal(result.arrival_retry.status,
        fixture.identity === 'NOT_IN_ACTIVE_REGISTER'
          ? 'NOT_IN_ACTIVE_REGISTER' : 'RESOLVED');
      assert.ok(manifestAttempts >= 2);
      assert.ok(inducedFailure.consoleErrors.some((message) =>
        /V9 EXACT REPD DEEP LINK/u.test(message)));
    }
    if (fixture.measures) {
      assert.ok(result.links_drawn > 0);
      assert.ok(result.nearest_km > 0);
      assert.equal(result.visible_measurement, true);
    } else {
      assert.equal(result.links_drawn, 0);
      assert.equal(result.nearest_km, null);
      assert.match(result.status_message, /not in the active-register snapshot/u);
      assert.match(result.status_message, /supplies no coordinates/u);
      assert.match(result.status_message, /No official status or location is inferred/u);
    }
    if (fixture.identity === 'NOT_IN_ACTIVE_REGISTER') {
      assert.equal(result.owner.identity_source, 'ARRIVAL_LINK');
      assert.equal(result.owner.official_active_register_match, false);
      assert.equal(result.owner.status_value ?? null, null);
      assert.equal(result.verification.status, 'NOT_IN_ACTIVE_REGISTER');
      if (fixture.measures) {
        assert.equal(result.owner.name, fixture.query.project);
        assert.equal(result.origin_source, 'link-supplied-not-in-active-register');
        assert.match(result.popup_text, /Thorpe Marsh Power Station/u);
        assert.doesNotMatch(result.popup_text, /Revised/u);
      } else {
        assert.equal(result.owner.name, null);
        assert.equal(result.origin_source, 'not-in-active-register-no-supplied-point');
      }
    } else {
      assert.equal(result.owner.identity_source, 'OFFICIAL_ACTIVE_REGISTER');
      assert.equal(result.owner.official_active_register_match, true);
      assert.equal(result.owner.status_value, 'application submitted');
      assert.match(result.popup_text, /Botley West/u);
    }
    assert.deepEqual(result.failures, []);
    assert.deepEqual(pageErrors, []);
    assert.deepEqual(consoleErrors, []);
    const materialFailures = requestFailures.filter(({ url: failedUrl }) =>
      !/basemaps\.cartocdn\.com/u.test(failedUrl));
    assert.deepEqual(materialFailures, []);

    receipts.push({ label: fixture.label, url, manifest_attempts: manifestAttempts,
      induced_failure: inducedFailure, page_errors: pageErrors,
      console_errors: consoleErrors, material_request_failures: materialFailures,
      obsolete_pipeline_requests: requests.filter((request) =>
        request.includes('/uk_renewables_pipeline/')), ...result });
    await context.close();
  }
  console.log(JSON.stringify({ status: 'PASS', generation: GENERATION,
    viewport: VIEWPORT, cases: receipts }, null, 2));
} finally {
  await browser.close();
  await new Promise((resolve) => server.close(resolve));
}

Place Global Search Arrival Identity

A JavaScript file in the substation finder folder of Code Generator that maps Renewable Energy Planning Database (REPD) projects, using SHA-256 and uses data from the GridAtlas repository.

Set aside from the main view: 96% of its lines are the same as apps/substation-finder/Ug/202609051623-uk-gazetteer-flyto.js (code-generator), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with UK Gazetteer Flyto; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9552 to code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Ug/202609051623-uk-gazetteer-flyto.js:1-817 f5ba42357785598131bb4f19d0c6027f6bc88dc7
  • sha256 a40137cbae040a9e72329ce38fa8f3c6b9adc88689fb43e7a18a95222bca2401
  • target sha256 ea193b7347ed222bca92c393256001047d198fae617483bacdb4d4a0540b7068
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

rendercode-generator / apps/substation-finder/Ps/202609040229-place-global-search-arrival-identity.js · lines 1–398 of 787 · version 2026-09-04 02:29 · pattern invalidatePendingDeepLink (shared by 7 files)

What it does
It maps REPD projects, postcodes and the REPD register. Defines 39 functions or classes, including invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'substation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: postcodes, the REPD register.
Inputs & outputs
In: data source: gridatlas data; data source: postcodes.io; data source: OpenStreetMap Nominatim; Parquet file repd_projects_202608290716.parquet; JSON file repd_v9_manifest_202608290716.json; DuckDB queries. Out: interactive map.
Downstream impact
Used directly by 3 files: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 1 other entry point, including Genome Workflow (ventus-grid-engine).
What it achieves
It marks deep link cancelled (`markDeepLinkCancelled`), normalises compact (`normaliseCompact`) and parses groups (`parseGroups`). Its `buildWhere` function gives SQL predicate from query text (VEDIC: query). It responds to gridatlas, click and input events.
Why it matters
Loaded by the Substation Finder page at https://ventusltd.github.io/code-generator/apps/substation-finder/ and 1 other page. Also imported by Build Graph, from Ventus Grid Engine.
Application
code-generator · apps/substation-finder/Ps · script
VEDIC
QUERY (GG2050-VEDIC-000046): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → sql_predicate
VEDIC
SCORE (GG2050-VEDIC-000047): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → sql_sort_expression
VEDIC
UK GEOCODE (GG2050-VEDIC-000048): GridAtlas / Search and Vicinity · Geographic information / Infrastructure screening. query_text → uk_location_candidates
Uses
none found
Used by
linked from Code Generator — Substation Finder Page (link), named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL)
Produces
invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, sharedDuckDBRuntime, promise
Defines here
invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, sharedDuckDBRuntime, promise, runtime, resetOfficialRuntime, installMapCapture, buildWhere, buildScore, rowObject, queryOfficialRepd, hasSafeMapPoint, setDeepLink, selectResult, geocoderGet, joinParts, queryUkGazetteer
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e apps/substation-finder/Ps/202609040229-place-global-search-arrival-identity.js:1-398 · blob fb987aa326171609fd112e36d7a2676461e92e4a · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
(() => {
  'use strict';

  const PARQUET_URL = 'https://ventusltd.github.io/gridatlas/data/repd_projects_202608290716.parquet';
  const PARQUET_SHA256 = '174040c37f3d63742d6fdd7af722a8cfdf3fb53de3ff85ff1142d22fdac4866b';
  const MANIFEST_URL = 'https://ventusltd.github.io/gridatlas/data/repd_v9_manifest_202608290716.json';
  const MANIFEST_SHA256 = '8850567ff9f1d2b6996b4e0d9707320030f3466a0b821cdcfc5325322b8be8c8';
  const GEOCODER_BASE = 'https://api.postcodes.io';
  const GLOBAL_GEOCODER_URL = 'https://nominatim.openstreetmap.org/search';
  const DUCKDB_MODULE = 'https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/+esm';
  const FALSE_ORIGIN = Object.freeze({ latitude: 49.766807, longitude: -7.55716 });
  const SOURCE_GENERATION = '202609040229';
  const RUNTIME_GENERATION = String(
    document.documentElement?.dataset?.gridatlasGeneration || SOURCE_GENERATION
  );

  const state = {
    schema: 'gridatlas.v9-place-global-search.v5',
    generation: RUNTIME_GENERATION,
    source_generation: SOURCE_GENERATION,
    version: 'v9.106',
    geocoder: GEOCODER_BASE,
    global_geocoder: GLOBAL_GEOCODER_URL,
    geocoder_providers: ['postcodes.io', 'Nominatim / OpenStreetMap'],
    geocoder_requests: 0,
    global_geocoder_requests: 0,
    geocoder_failures: [],
    last_location_selection: null,
    parquet_url: PARQUET_URL,
    parquet_sha256: PARQUET_SHA256,
    ready: false,
    map_captured: false,
    query_count: 0,
    identity_retry_count: 0,
    last_query: '',
    last_results: [],
    last_selection: null,
    failures: [],
    deep_link: { status: 'IDLE', repd_ref: null, resolved: false, mapped: false }
  };
  window.__GRIDATLAS_PLACE_SEARCH__ = state;

  let runtimePromise = null;
  let manifestPromise = null;
  let debounceTimer = null;
  let activeQuerySerial = 0;

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

  function arrivalCoordinator() {
    const measure = window.__GRIDATLAS_NEON_LINKS__?.measure;
    if (!measure?.arrivalGate || typeof measure.claimPendingArrival !== 'function'
        || typeof measure.invalidatePendingArrival !== 'function') return null;
    return measure;
  }

  function markDeepLinkCancelled(reason, epoch = null) {
    const prior = state.deep_link;
    if (!prior?.repd_ref || prior.status === 'ABSENT'
        || prior.status === 'IDLE' || prior.status === 'CANCELLED') return;
    state.deep_link = {
      ...prior,
      status: 'CANCELLED',
      resolved: false,
      mapped: false,
      cancelled_by: String(reason || 'user-navigation'),
      cancelled_epoch: Number.isInteger(epoch) ? epoch : null
    };
    document.body.dataset.gridatlasRepdDeepLink = 'cancelled';
  }

  function invalidatePendingDeepLink(reason) {
    const coordinator = arrivalCoordinator();
    if (!coordinator) {
      markDeepLinkCancelled(reason);
      return null;
    }
    const epoch = coordinator.invalidatePendingArrival(reason);
    /* The shared owner dispatches this synchronously. Keep the direct call as
       a fail-soft fallback for a DOM shim without CustomEvent. */
    markDeepLinkCancelled(reason, epoch);
    return epoch;
  }

  window.addEventListener('gridatlas:arrival-invalidated', (event) => {
    markDeepLinkCancelled(event?.detail?.reason, event?.detail?.epoch);
  });

  function escapeHtml(value) {
    return String(value ?? '')
      .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
  }

  function sqlString(value) {
    return `'${String(value).replaceAll("'", "''")}'`;
  }

  function normaliseCompact(value) {
    return String(value ?? '').toUpperCase().replace(/[^A-Z0-9]/g, '');
  }

  function parseGroups(query) {
    return String(query ?? '')
      .trim()
      .toLowerCase()
      .split(/\s+/)
      .map(group => group.split('/').map(term => term.replace(/[^a-z0-9]/g, '')).filter(Boolean))
      .filter(group => group.length);
  }

  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 verifyManifest() {
    manifestPromise ||= (async () => {
      const response = await fetch(MANIFEST_URL, { cache: 'no-store' });
      invariant(response.ok, `REPD manifest HTTP ${response.status}`);
      const bytes = await response.arrayBuffer();
      invariant(await sha256Hex(bytes) === MANIFEST_SHA256, 'REPD manifest SHA-256 mismatch');
      const manifest = JSON.parse(new TextDecoder().decode(bytes));
      invariant(manifest?.schema === 'gridatlas.build-manifest.v1', 'REPD manifest schema mismatch');
      invariant(manifest?.generation === '202608290716', 'REPD generation mismatch');
      invariant(manifest?.closure?.rows === 11069, 'REPD row closure mismatch');
      invariant(manifest?.closure?.postcodes === 9505, 'REPD postcode closure mismatch');
      invariant(manifest?.closure?.addresses === 11059, 'REPD address closure mismatch');
      invariant(manifest?.parquet?.sha256 === PARQUET_SHA256, 'REPD Parquet identity mismatch');
      return manifest;
    })();
    return manifestPromise;
  }

  /* ONE DuckDB runtime for the whole page. Duplicated verbatim from
     202608301825-streaming-parquet-bridge-v9-5.js, deliberately: cartridges
     are composed as independent scripts with no shared module loader, so
     there is nothing to import from. The CONTRACT is the window key and the
     shape it holds, not this function, and whichever cartridge asks first
     builds it - so neither depends on composition order.

     Why it exists: this lane and the bridge each built their own runtime.
     Measured live at an iPhone 13 profile, 202609041500: duckdb-eh.wasm
     fetched twice at 5.92 MB, 11.84 MB of a 12.81 MB arrival, and two
     WebAssembly heaps alive at once on a device that caps per-tab memory. */
  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 };
    })();
    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 runtime() {
    runtimePromise ||= (async () => {
      await verifyManifest();
      const shared = await sharedDuckDBRuntime(DUCKDB_MODULE);
      /* A connection each. DuckDB supports many connections on one database,
         which is what makes the sharing safe: the lanes stay independent at
         the level they actually need to be. */
      const connection = await shared.database.connect();
      return { connection, database: shared.database, worker: shared.worker, shared: true };
    })();
    return runtimePromise;
  }

  async function resetOfficialRuntime() {
    const previous = runtimePromise;
    runtimePromise = null;
    manifestPromise = null;
    if (!previous) return;
    try {
      const active = await previous;
      try { await active.connection?.close?.(); } catch (_) { /* best effort */ }
      /* A SHARED database is never terminated here. Retry owns this lane's
         connection, not the page's runtime: the streaming-parquet bridge is
         serving every V8 data layer from the same database, and tearing it
         down to retry a search would take the map's data plane with it.
         Closing the connection is the whole of what this lane owns.
         The `shared` flag is set by runtime() above; the terminate path is
         kept for a runtime this lane built alone, so behaviour is unchanged
         if the broker is ever absent. */
      if (!active.shared) {
        try { await active.database?.terminate?.(); } catch (_) { /* best effort */ }
        try { active.worker?.terminate?.(); } catch (_) { /* best effort */ }
      }
    } catch (_) {
      // A rejected cached promise is exactly what retry is replacing.
    }
  }

  function installMapCapture() {
    if (!window.maplibregl?.Map || window.__GRIDATLAS_V9_MAP_CAPTURE_INSTALLED__) return;
    const NativeMap = window.maplibregl.Map;
    const ProxyMap = new Proxy(NativeMap, {
      construct(target, args, newTarget) {
        const instance = Reflect.construct(target, args, newTarget);
        window.__GRIDATLAS_V9_MAP__ = instance;
        state.map_captured = true;
        return instance;
      }
    });
    window.maplibregl.Map = ProxyMap;
    window.__GRIDATLAS_V9_MAP_CAPTURE_INSTALLED__ = true;
  }

  installMapCapture();

  function buildWhere(query) {
    const groups = parseGroups(query);
    invariant(groups.length > 0, 'empty search query');
    const searchable = `lower(concat_ws(' ', coalesce(name,''), coalesce(repd_address_display,''), coalesce(repd_postcode,''), coalesce(county,''), coalesce(planning_authority,''), coalesce(repd_ref,'')))`;
    const compactPostcode = `regexp_replace(upper(coalesce(repd_postcode,'')), '[^A-Z0-9]', '', 'g')`;
    const compactRef = `regexp_replace(upper(coalesce(repd_ref,'')), '[^A-Z0-9]', '', 'g')`;
    return groups.map(group => {
      const alternatives = [];
      for (const term of group) {
        const compact = normaliseCompact(term);
        alternatives.push(`${searchable} LIKE ${sqlString(`%${term}%`)}`);
        if (compact) {
          alternatives.push(`${compactPostcode} LIKE ${sqlString(`%${compact}%`)}`);
          alternatives.push(`${compactRef} = ${sqlString(compact)}`);
        }
      }
      return `(${alternatives.join(' OR ')})`;
    }).join(' AND ');
  }

  function buildScore(query) {
    const compact = normaliseCompact(query);
    const firstTerm = parseGroups(query).flat()[0] || '';
    const clauses = [];
    if (compact) {
      clauses.push(`CASE WHEN regexp_replace(upper(coalesce(repd_postcode,'')), '[^A-Z0-9]', '', 'g') = ${sqlString(compact)} THEN 10000 ELSE 0 END`);
      clauses.push(`CASE WHEN upper(coalesce(repd_ref,'')) = ${sqlString(compact)} THEN 9000 ELSE 0 END`);
    }
    if (firstTerm) {
      clauses.push(`CASE WHEN lower(coalesce(name,'')) = ${sqlString(firstTerm)} THEN 2000 ELSE 0 END`);
      clauses.push(`CASE WHEN lower(coalesce(name,'')) LIKE ${sqlString(`${firstTerm}%`)} THEN 500 ELSE 0 END`);
      clauses.push(`CASE WHEN lower(coalesce(repd_address_display,'')) LIKE ${sqlString(`%${firstTerm}%`)} THEN 200 ELSE 0 END`);
    }
    return clauses.length ? clauses.join(' + ') : '0';
  }

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

  async function queryOfficialRepd(query, serial = null, stillOwned = null) {
    const trimmed = String(query ?? '').trim();
    if (trimmed.length < 2) return [];
    const { connection } = await runtime();
    const sql = `
      SELECT
        repd_ref, name, repd_address_display, repd_postcode, county,
        planning_authority, technology, status, capacity_mw, longitude, latitude,
        (${buildScore(trimmed)}) AS search_score
      FROM read_parquet(${sqlString(PARQUET_URL)})
      WHERE ${buildWhere(trimmed)}
      ORDER BY search_score DESC, TRY_CAST(repd_ref AS BIGINT) ASC NULLS LAST, capacity_mw DESC NULLS LAST, name ASC
      LIMIT 25
    `;
    const table = await connection.query(sql);
    if (serial !== null && serial !== activeQuerySerial) return [];
    if (stillOwned && !stillOwned()) return [];
    const results = table.toArray().map(rowObject).map(row => ({
      repd_ref: String(row.repd_ref ?? ''),
      name: String(row.name ?? ''),
      address: String(row.repd_address_display ?? ''),
      postcode: String(row.repd_postcode ?? ''),
      county: String(row.county ?? ''),
      planning_authority: String(row.planning_authority ?? ''),
      technology: String(row.technology ?? ''),
      status: String(row.status ?? ''),
      capacity_mw: row.capacity_mw == null ? null : Number(row.capacity_mw),
      longitude: row.longitude == null ? null : Number(row.longitude),
      latitude: row.latitude == null ? null : Number(row.latitude),
      score: Number(row.search_score || 0)
    }));
    state.query_count += 1;
    state.last_query = trimmed;
    state.last_results = results.slice(0, 25);
    return results;
  }

  function hasSafeMapPoint(result) {
    if (!Number.isFinite(result.longitude) || !Number.isFinite(result.latitude)) return false;
    if (Math.abs(result.longitude) < 1e-12 && Math.abs(result.latitude) < 1e-12) return false;
    if (Math.abs(result.latitude - FALSE_ORIGIN.latitude) < 1e-9 && Math.abs(result.longitude - FALSE_ORIGIN.longitude) < 1e-9) return false;
    return result.longitude >= -180 && result.longitude <= 180 && result.latitude >= -90 && result.latitude <= 90;
  }

  function setDeepLink(result) {
    const url = new URL(window.location.href);
    url.searchParams.set('repd_ref', result.repd_ref);
    history.replaceState(history.state, '', url);
  }

  function selectResult(result, options = {}) {
    const deepLinkEpoch = Number.isInteger(options.deepLinkEpoch)
      ? options.deepLinkEpoch : null;
    if (deepLinkEpoch === null) {
      invalidatePendingDeepLink('project-search-selection');
    } else if (!arrivalCoordinator()?.arrivalGate.isCurrent(deepLinkEpoch)) {
      return false;
    }
    setDeepLink(result);
    const map = window.__GRIDATLAS_V9_MAP__;
    const canMap = hasSafeMapPoint(result) && map && typeof map.flyTo === 'function';
    state.last_selection = {
      repd_ref: result.repd_ref,
      name: result.name,
      postcode: result.postcode,
      mapped: Boolean(canMap),
      longitude: result.longitude,
      latitude: result.latitude,
      // Published since 202609011141: the measurement cartridge consumes a
      // resolved identity rather than requiring the URL to restate what the
      // register already knows. This lane resolved them; it publishes them.
      technology: result.technology,
      capacity_mw: result.capacity_mw
    };
    if (!canMap) return true;
    map.flyTo({ center: [result.longitude, result.latitude], zoom: 12, duration: 1200, essential: true });
    const cap = Number.isFinite(result.capacity_mw) ? `${result.capacity_mw.toLocaleString('en-GB')} MW` : '';
    const location = [result.address, result.postcode, result.county].filter(Boolean).join(' · ');
    new window.maplibregl.Popup({ maxWidth: '340px' })
      .setLngLat([result.longitude, result.latitude])
      .setHTML(`<div style="font-family:monospace;background:#000;padding:6px"><b style="color:#00ffff;font-size:13px">${escapeHtml(result.name)}</b><br><span style="color:#888">${escapeHtml(result.technology)}</span>${cap ? `<br><span style="color:#ffae00">${escapeHtml(cap)}</span>` : ''}<br><span style="color:#aaa;font-size:10px">${escapeHtml(location)}</span><br><span style="color:#555;font-siz  … [line shortened here: 488 characters; full line on GitHub]
      .addTo(map);
    return true;
  }

  // ---- 202608301136 UK gazetteer lane (LOCATION_ONLY, never claims REPD identity) ----
  const FULL_POSTCODE = /^[A-Z]{1,2}[0-9][A-Z0-9]?[0-9][A-Z]{2}$/;
  const OUTCODE = /^[A-Z]{1,2}[0-9][A-Z0-9]?$/;
  let locationPopup = null;

  async function geocoderGet(path, query) {
    state.geocoder_requests += 1;
    try {
      const response = await fetch(`${GEOCODER_BASE}${path}`, { cache: 'default' });
      if (response.status === 404) return null;
      if (!response.ok) throw new Error(`postcodes.io ${response.status} for ${path}`);
      const body = await response.json();
      return body?.result ?? null;
    } catch (error) {
      state.geocoder_failures.push({
        query: String(query ?? ''),
        path,
        message: String(error?.message || error)
      });
      throw error;
    }
  }

  function joinParts(...parts) {
    return parts.filter(Boolean).join(' · ');
  }

  async function queryUkGazetteer(query) {
    const raw = String(query ?? '').trim();
    if (raw.length < 2) return [];
    const compact = normaliseCompact(raw);
    const out = [];
    try {
      if (FULL_POSTCODE.test(compact)) {
        const result = await geocoderGet(`/postcodes/${encodeURIComponent(compact)}`, raw);
        if (result && Number.isFinite(result.longitude) && Number.isFinite(result.latitude)) {
          out.push({
            kind: 'postcode',
            provider: 'postcodes.io',
            label: result.postcode,
            sublabel: joinParts(result.admin_district, result.admin_county, result.region),
            longitude: result.longitude,
            latitude: result.latitude