GLOBALGRID2050 / EXPLORE CODE

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

Deep Link Technology Buckets Browser and 2 more files

A JavaScript module in the proofs folder of GridAtlas that reads the Renewable Energy Planning Database (REPD) register and battery storage (BESS). It is built from the check step (`check`).

645 lines of JavaScript from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 652 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 Visibility and One Runtime Proof render · gridatlas / tools/proofs/arrival-visibility-and-one-runtime.proof.mjs lines 1–163
  2. Deep Link Technology Buckets Browser render · gridatlas / tools/proofs/deep-link-technology-buckets.browser.mjs lines 1–258
  3. Deep Link Visibility Browser render · gridatlas / tools/proofs/deep-link-visibility.browser.mjs lines 1–224

Arrival Visibility and One Runtime Proof

A JavaScript module in the proofs folder of GridAtlas. It is built from the composed step (`composed`) and the check step (`check`).

rendergridatlas / tools/proofs/arrival-visibility-and-one-runtime.proof.mjs · lines 1–163 of 163 · Not reached from any entry point (candidate for review) · pattern composed (shared by 4 files)

What it does
It loads data. Defines composed, check. Uses libraries node:fs/promises, node:path, node:url. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file current.json; DuckDB queries.
What it achieves
What this generation has to keep true, asserted against the COMPOSED bytes named by `atlas/current.json` - not against the parts they were built from.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/proofs · JavaScript module
Uses
node:fs/promises, node:path, node:url
Used by
none found
Produces
composed, check
Defines here
composed, 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/proofs/arrival-visibility-and-one-runtime.proof.mjs:1-163 · blob 85713edb6ca0aeb977d17ee37c283112a3130a5e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/* What this generation has to keep true, asserted against the COMPOSED bytes
 * named by atlas/current.json - not against the parts they were built from.
 *
 * That distinction is the whole point of this file. The defect it exists to
 * stop already happened once: the iOS Safari visibility fix below was written
 * into atlas/parts/202609041234-sld-sandbox-technology-buckets.js and never
 * reached the composed cartridge, so the repository contained the fix, the
 * part-level reader saw the fix, and the served page did not have it. A proof
 * that reads parts would have passed while the phone stayed broken.
 *
 * Run: node tools/proofs/arrival-visibility-and-one-runtime.proof.mjs
 */

import { readFile } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const REPO = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
const ATLAS = join(REPO, 'atlas');

const current = JSON.parse(await readFile(join(ATLAS, 'current.json'), 'utf8'));
const byId = new Map(current.cartridges.map(c => [c.id, c]));

async function composed(id) {
    const entry = byId.get(id);
    if (!entry) throw new Error(`no cartridge ${id} in current.json`);
    const rel = entry.path.replace(/^\.\//, '');
    return (await readFile(join(ATLAS, rel), 'utf8')).replace(/\r\n/g, '\n');
}

const failures = [];
let passed = 0;
const check = (name, condition) => {
    if (condition) passed += 1;
    else failures.push(name);
};

const sld = await composed('sld-sandbox');
const bridge = await composed('streaming-parquet-bridge');
const search = await composed('uk-gazetteer-flyto');
const intelligence = await composed('substation-intelligence');

/* ── The iOS Safari arrival, in the SERVED bytes ─────────────────────────
 *
 * Mechanism, reproduced by an independent audit: a deep link loaded with
 * document.hidden === true drew zero layer controls at 40s and the camera
 * never left its default position, recovering 2.5s after being made visible.
 * MapLibre's flyTo() and the engine's paint-driven boot both depend on
 * requestAnimationFrame, which iOS Safari does not tick in a tab that is not
 * composited. flyTo() does not throw there - it is simply never given a frame
 * - so the arrival ran to its own conclusion against a camera that had not
 * moved, and nothing called it again once the tab was finally seen.
 *
 * Pipeline News' MAP control carries target="_blank" on touch devices, which
 * is why this is the ordinary path to the product on a phone and not an edge
 * case. */

check('the layer-control budget is charged in VISIBLE time, not wall clock: '
    + 'time spent in a tab nobody can see buys nothing observable and must not '
    + 'be spent from the budget',
    /visibilityState === 'visible'\) elapsed \+= 200/.test(sld)
    && /while \(elapsed < budgetMs &&/.test(sld));

check('and the wall-clock BUDGET it replaced is genuinely gone, so the two '
    + 'cannot both be present with one shadowing the other',
    !/while \(Date\.now\(\) - started < budgetMs\)/.test(sld));

check('the visible-time budget is nonetheless bounded by an absolute ceiling, '
    + 'because visible time alone never elapses in a tab that is never shown - '
    + 'that would be a poll every 200ms for ever on the device least able to '
    + 'afford the battery',
    /Date\.now\(\) - started < HARD_CEILING_MS/.test(sld)
    && /const HARD_CEILING_MS = 600000;/.test(sld));

check('both clocks are published, because they answer different questions: '
    + 'wall time is what the reader sat through, visible time is what the '
    + 'budget was actually spent from',
    /link\.layer_controls_ready_ms = Date\.now\(\) - started;/.test(sld)
    && /link\.layer_controls_ready_visible_ms = elapsed;/.test(sld));

check('the arrival never STARTS while the document is hidden, because a flyTo '
    + 'issued to an uncomposited tab is silently discarded rather than failing',
    /function attemptArrival\(\)/.test(sld)
    && /if \(document\.visibilityState !== 'visible'\) return;/.test(sld));

check('the arrival is not one-shot: an arrival that produced no visible '
    + 'outcome is run again the first time the tab is actually seen',
    /visibilitychange/.test(sld)
    && /function arrivalHasVisibleOutcome\(\)/.test(sld));

check('a visible outcome is judged on fields the cartridge already publishes '
    + 'and already relies on elsewhere, rather than a new signal invented for '
    + 'the retry to read',
    /link\.links_drawn > 0/.test(sld)
    && /not-in-active-register-no-supplied-point/.test(sld));

check('retrying is BOUNDED, so a genuine non-visibility failure still stops '
    + 'rather than re-running forever every time the reader switches tabs',
    /MAX_AUTO_ARRIVAL_ATTEMPTS = 5/.test(sld)
    && /link\.arrival_attempts = arrivalAttempts/.test(sld));

check('the retry publishes its own state, so a reader can tell an arrival that '
    + 'waited for visibility from one that simply worked',
    /arrival_deferred_for_visibility/.test(sld)
    && /arrival_resumed_on_visibility/.test(sld));

/* ── One DuckDB runtime for the page ─────────────────────────────────────
 *
 * 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 hard. */

check('both cartridges that need DuckDB go through the shared broker, keyed on '
    + 'the window so neither depends on composition order',
    /__GRIDATLAS_DUCKDB_RUNTIME__/.test(bridge)
    && /__GRIDATLAS_DUCKDB_RUNTIME__/.test(search)
    && /sharedDuckDBRuntime\(DUCKDB_MODULE\)/.test(bridge)
    && /sharedDuckDBRuntime\(DUCKDB_MODULE\)/.test(search));

check('neither cartridge still instantiates a runtime outside the broker - if '
    + 'one did, the page would quietly pay for two heaps again',
    bridge.split('database.instantiate(').length - 1 === 1
    && search.split('database.instantiate(').length - 1 === 1);

check('a rejected runtime is dropped rather than cached, so a retry rebuilds '
    + 'instead of inheriting a dead promise',
    /window\[KEY\]\.promise === promise\) delete window\[KEY\]/.test(bridge)
    && /window\[KEY\]\.promise === promise\) delete window\[KEY\]/.test(search));

check('the search lane never terminates a SHARED database: its retry owns its '
    + 'own connection, and tearing down the runtime would take the bridge\'s '
    + 'data plane for every V8 layer down with it',
    /if \(!active\.shared\)/.test(search)
    && /shared: true/.test(search));

/* ── The chips a phone actually needs ───────────────────────────────────── */

check('GRID and SUBS stay on the map on a touch screen or a narrow window, '
    + 'because the switches they stand in for live in the SCADA panel below a '
    + 'fold a phone never scrolls to',
    /function chipStaysOnMap/.test(intelligence)
    && /pointer: coarse/.test(intelligence));

check('an UNKNOWN viewport width is not treated as a phone: the width has to '
    + 'be a real positive number before it argues for staying on the map, so a '
    + 'host that publishes no width does not silently get the phone layout',
    /width > 0 && width <= 700/.test(intelligence));

check('everything else still routes into the menus, so this is a targeted '
    + 'exception and not a reversal of the menu consolidation',
    /button\.hidden = true/.test(intelligence)
    && /move\(panels\[route\], button\)/.test(intelligence));

/* ── Report ─────────────────────────────────────────────────────────────── */

if (failures.length) {
    console.error('arrival-visibility-and-one-runtime FAILED ('
        + failures.length + ' of ' + (failures.length + passed) + '):\n- '
        + failures.join('\n- '));
    process.exit(1);
}
console.log('arrival visibility and one runtime: PASS — ' + passed + ' checks '
    + 'against the composed bytes of generation ' + current.generation);

Deep Link Technology Buckets Browser

A JavaScript module in the proofs folder of GridAtlas that reads the Renewable Energy Planning Database (REPD) register and battery storage (BESS). It is built from the check step (`check`).

rendergridatlas / tools/proofs/deep-link-technology-buckets.browser.mjs · lines 1–258 of 258 · Entry point

What it does
It loads the REPD register and battery storage (BESS). Defines check. Uses libraries node:assert/strict, node:http, node:fs/promises, node:path, node:vm. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, battery storage (BESS).
Inputs & outputs
In: JSON file current.json.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
Proof: every technology bucket Pipeline News' MAP link can send arrives with the project's own layer switched on -- or, for the one bucket that genuinely has no layer.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/proofs · JavaScript module
Uses
node:assert/strict, node:http, node:fs/promises, node:path, node:vm, playwright, node:url
Used by
none found
Produces
check
Defines here
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/proofs/deep-link-technology-buckets.browser.mjs:1-258 · blob 2821f2a7954984c70f409701fac47217713843df · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
/**
 * Proof: every technology bucket Pipeline News' MAP link can send arrives
 * with the project's own layer switched on -- or, for the one bucket that
 * genuinely has no layer, arrives saying so plainly -- never with
 * `technology_layer.enabled` reading true while nothing is actually lit.
 *
 * MEASURED BY THE ARCHITECT, LIVE, ON v9.107 -- REPRODUCED HERE
 * ------------------------------------------------------------------------
 *   repd    technology      links  failures                                  project_layer_enabled
 *   7698    wind_offshore   5      ["layer control not found: wind_offshore"] null
 *   2498    wind_offshore   5      ["layer control not found: wind_offshore"] null
 *   3139    wind_onshore    4      ["layer control not found: wind_onshore"]  null
 *   15205   other           5      ["layer control not found: other"]        null
 *   801     biomass         5      []                                        "biomass"
 *   12464   bess            5      []                                        "bess"
 *
 * isProjectTech() tested membership of PROJECT_TECHS, which deliberately
 * contains wind_onshore, wind_offshore and other -- so
 * `link.technology_layer.enabled` read true regardless, and the failure
 * that told the truth sat in `link.failures`, a field no gate read. 2,508
 * of the 7,680-row register -- a third of it -- arrived with the
 * project's own layer dark while the field a reader would check said
 * green.
 *
 * THE BUCKET LIST IS NOT HAND-TYPED HERE
 * ------------------------------------------------------------------------
 * BUCKETS below is read out of the served composition's own
 * technology-coverage module (SPINE + widerFleetBuckets()) at proof run
 * time -- the same module the architect's own root-cause report pointed
 * at. A bucket cannot go missing from THIS list the way wind_onshore,
 * wind_offshore and other went missing from the old PROJECT_TECHS-based
 * `enabled` read, because this list is derived, not retyped.
 *
 * WHAT "a layer id the engine publishes" MEANS HERE
 * ------------------------------------------------------------------------
 * PUBLISHED_LAYER_IDS is read from the LIVE PAGE's own
 * `input[type=checkbox][data-layer-id]` controls after the engine has
 * booted -- not a second hand-typed list either. For twelve of the
 * thirteen buckets, `project_layer_enabled` must be a member of that set.
 * `other` is the documented, permanent exception (see the fix's commit):
 * it has never had a layer, and the proof asserts the arrival says so
 * instead -- `failures: []`, `project_layer_enabled: null`,
 * `technology_layer.enabled: false`, with a stated reason -- rather than
 * asserting a fact that would never be true.
 *
 * WHY NO repd_ref
 * ------------------------------------------------------------------------
 * A supplied longitude/latitude/technology with NO repd_ref never awaits
 * register identity resolution (`receiverPlan.route === 'MEASURE_LINK_FIRST'`
 * and `repdRef` is falsy, so the identity-verification branch is skipped
 * entirely) -- see runDeepLink() in the sld-sandbox cartridge. That makes
 * this proof deterministic and independent of which REPD rows happen to be
 * live in the pinned register product, while still exercising the exact
 * production arrival path a Pipeline News MAP link takes. The coordinates
 * are a fixed, arbitrary point in Great Britain; no real project is
 * claimed to exist there.
 */

import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile, stat } from 'node:fs/promises';
import path from 'node:path';
import vm from 'node:vm';
import { chromium } from 'playwright';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const CURRENT = JSON.parse(await readFile(path.join(ROOT, 'atlas', 'current.json'), 'utf8'));
const GENERATION = CURRENT.generation;

// The bucket list, derived from the served module, not retyped.
const coverageContext = { window: {} };
coverageContext.window.window = coverageContext.window;
vm.createContext(coverageContext);
vm.runInContext(
  await readFile(path.join(ROOT, 'atlas', 'modules', '202609031310-technology-coverage.js'), 'utf8'),
  coverageContext, { filename: 'technology-coverage.js' });
const coverage = coverageContext.window.__GRIDATLAS_MODULES__?.technologyCoverage;
assert.ok(coverage, 'the technology-coverage module did not register');
const BUCKETS = [...coverage.spine, ...coverage.widerFleetBuckets()];
assert.equal(BUCKETS.length, 13, `expected 13 Pipeline buckets, the module named ${BUCKETS.length}`);

const NO_LAYER_BUCKETS = new Set(['other']);

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();

// A fixed, arbitrary GB point (near Leicester). No real project is claimed
// to exist here -- see the header note on why no repd_ref is supplied.
const LATITUDE = 52.6369;
const LONGITUDE = -1.1398;

const WIDTHS = [
  { width: 393, height: 852, touch: true },
  { width: 456, height: 906, touch: true },
  { width: 1280, height: 800, touch: false }
];

const widthFilter = String(process.env.GRIDATLAS_BROWSER_WIDTH || '').trim();
const bucketFilter = String(process.env.GRIDATLAS_BROWSER_BUCKET || '').trim();
const selectedWidths = widthFilter
  ? WIDTHS.filter((w) => String(w.width) === widthFilter) : WIDTHS;
const selectedBuckets = bucketFilter
  ? BUCKETS.filter((b) => b === bucketFilter) : BUCKETS;
assert.ok(selectedWidths.length, `no width matched GRIDATLAS_BROWSER_WIDTH=${widthFilter}`);
assert.ok(selectedBuckets.length, `no bucket matched GRIDATLAS_BROWSER_BUCKET=${bucketFilter}`);

const failures = [];
const receipts = [];
const browser = await chromium.launch({ headless: true });
try {
  for (const spec of selectedWidths) {
    const context = await browser.newContext({
      viewport: { width: spec.width, height: spec.height },
      ...(spec.touch ? { isMobile: true, hasTouch: true } : {})
    });
    const page = await context.newPage();
    let publishedLayerIds = null;

    for (const bucket of selectedBuckets) {
      const pageErrors = [];
      page.removeAllListeners('pageerror');
      page.on('pageerror', (error) => pageErrors.push(String(error?.message || error)));

      const query = new URLSearchParams({
        technology: bucket, latitude: String(LATITUDE), longitude: String(LONGITUDE),
        zoom: '12', project: 'GRIDATLAS_PROOF_' + bucket, capacity_mw: '10'
      });
      const url = `http://127.0.0.1:${port}/atlas/?${query}`;
      await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 120_000 });
      await page.waitForFunction((generation) =>
        document.documentElement.dataset.gridatlasGeneration === generation,
      GENERATION, { timeout: 120_000 });
      await page.waitForFunction(() =>
        window.__GRIDATLAS_MODULES__?.menuBar?.installed === true
          && document.querySelectorAll('#gridatlas-menu-bar .gm-title').length === 6,
      null, { timeout: 120_000 });

      if (!publishedLayerIds) {
        publishedLayerIds = await page.evaluate(() =>
          [...document.querySelectorAll('input[type=checkbox][data-layer-id]')]
            .map((input) => input.dataset.layerId));
      }

      try {
        await page.waitForFunction(() => {
          const link = window.__GRIDATLAS_NEON_LINKS__;
          const layer = link?.technology_layer;
          return !!layer && (layer.enabled === true || layer.layer_id === null);
        }, null, { timeout: 60_000 });
      } catch (error) {
        const diagnostic = await page.evaluate(() => ({
          link: window.__GRIDATLAS_NEON_LINKS__ ? {
            technology_layer: window.__GRIDATLAS_NEON_LINKS__.technology_layer,
            project_layer_enabled: window.__GRIDATLAS_NEON_LINKS__.project_layer_enabled,
            failures: window.__GRIDATLAS_NEON_LINKS__.failures
          } : null
        }));
        throw new Error(`${spec.width}px ${bucket} did not reach a terminal layer state: `
          + `${JSON.stringify(diagnostic)}`, { cause: error });
      }

      const result = await page.evaluate(() => {
        const link = window.__GRIDATLAS_NEON_LINKS__;
        return {
          runtime_generation: document.documentElement.dataset.gridatlasGeneration,
          failures: link.failures || [],
          project_layer_enabled: link.project_layer_enabled ?? null,
          technology_layer: link.technology_layer || null
        };
      });

      const check = (label, condition, detail) => {
        const full = `${spec.width}px ${bucket}: ${label}`;
        if (condition) { console.log(`  [PASS] ${full}`); }
        else { console.log(`  [FAIL] ${full}${detail ? ' -- ' + detail : ''}`); failures.push(full); }
      };

      check('runtime generation matches the composed generation',
        result.runtime_generation === GENERATION);
      check('no page errors', pageErrors.length === 0, pageErrors.join(' | '));

      if (NO_LAYER_BUCKETS.has(bucket)) {
        check('failures stays empty -- the missing layer is said plainly, not searched for',
          Array.isArray(result.failures) && result.failures.length === 0,
          JSON.stringify(result.failures));
        check('project_layer_enabled stays null -- there was never a layer to enable',
          result.project_layer_enabled === null, String(result.project_layer_enabled));
        check('technology_layer.enabled is false',
          result.technology_layer?.enabled === false);
        check('technology_layer.layer_id is null',
          result.technology_layer?.layer_id === null);
        check('technology_layer.reason states plainly that no layer exists',
          /no map layer/i.test(result.technology_layer?.reason || ''),
          result.technology_layer?.reason);
      } else {
        check('failures: [] -- the exact assertion the old code could not make',
          Array.isArray(result.failures) && result.failures.length === 0,
          JSON.stringify(result.failures));
        check('project_layer_enabled is a layer id the engine actually publishes',
          publishedLayerIds.includes(result.project_layer_enabled),
          `got ${JSON.stringify(result.project_layer_enabled)}, `
            + `published: ${JSON.stringify(publishedLayerIds)}`);
        check('technology_layer.enabled is true',
          result.technology_layer?.enabled === true);
        check('technology_layer.layer_id matches project_layer_enabled',
          result.technology_layer?.layer_id === result.project_layer_enabled);
      }

      receipts.push({ width: spec.width, bucket, ...result, page_errors: pageErrors });
    }
    await context.close();
  }

  console.log(`\n${receipts.length} bucket/width cases run, ${failures.length} failure(s)`);
  if (failures.length) {
    console.error('\nFAILURES');
    for (const failure of failures) console.error('  ' + failure);
    process.exitCode = 1;
  } else {
    console.log(JSON.stringify({ status: 'PASS', generation: GENERATION,
      widths: selectedWidths.map((w) => w.width), buckets: selectedBuckets,
      cases: receipts.length }, null, 2));
  }
} finally {
  await browser.close();
  await new Promise((resolve) => server.close(resolve));
}

Deep Link Visibility Browser

A JavaScript module in the proofs folder of GridAtlas that reads solar. It is built from the check step (`check`).

rendergridatlas / tools/proofs/deep-link-visibility.browser.mjs · lines 1–224 of 224 · Entry point

What it does
It loads solar. Defines check. Uses libraries node:assert/strict, node:http, node:fs/promises, node:path, playwright. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar.
Inputs & outputs
In: JSON file current.json.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
Proof: a deep-link arrival opened in a HIDDEN tab does not run while hidden, does not burn its layer-control budget while hidden, and completes -- camera, card and links -- once the tab is actually shown.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/proofs · JavaScript module
Uses
node:assert/strict, node:http, node:fs/promises, node:path, playwright, node:url
Used by
none found
Produces
check
Defines here
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/proofs/deep-link-visibility.browser.mjs:1-224 · blob 367e4ec1db446a4f7f0358b90bde0e5d9453dc8a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
/**
 * Proof: a deep-link arrival opened in a HIDDEN tab does not run while
 * hidden, does not burn its layer-control budget while hidden, and
 * completes -- camera, card and links -- once the tab is actually shown.
 *
 * MEASURED LIVE, TWICE, ON A REAL IPHONE
 * ------------------------------------------------------------------------
 * The architect opened Pipeline News' MAP control (`target="_blank"` on
 * touch devices) for two different solar projects. Both times: menu bar
 * rendered, attribution rendered unoccluded, the basemap painted fully --
 * and the camera sat at the default UK-wide view (-3.5, 54 @ z4.2), no
 * project card, no neon links. An independent audit reproduced the
 * mechanism exactly: a deep link loaded with `document.hidden === true`
 * drew zero layer controls at 40s and the camera never left its default
 * position -- because `requestAnimationFrame` does not tick in a tab that
 * is not composited on iOS Safari, so `map.flyTo()`'s interpolation and the
 * engine's own paint-gated boot both stall for as long as the tab stays
 * hidden. It recovered 2.5s after being made visible, which is the
 * behaviour this proof pins: NOT that the arrival never fails, but that it
 * is never left stranded once the reader actually looks.
 *
 * WHAT THIS PROOF CAN AND CANNOT SIMULATE
 * ------------------------------------------------------------------------
 * A CI runner cannot reproduce iOS's own suspension of requestAnimationFrame
 * in a background tab -- headless Chromium and WebKit keep ticking regardless
 * of visibility. What this proof CAN and DOES exercise faithfully is the
 * exact signal the fix is built on: `document.visibilityState` and the
 * `visibilitychange` event, overridden here via an init script installed
 * BEFORE any page script runs, so the arrival's own gating logic sees a
 * genuinely hidden document exactly as it would on a real device, then a
 * genuine transition to visible. That the fix does the right thing on that
 * signal is the whole content of the fix; MapLibre's internal animation
 * driver is not this repository's code to prove.
 *
 * Before the fix this test fails two ways: the arrival starts anyway while
 * "hidden" (arrival_attempts > 0 before visibility), and/or it never
 * recovers afterwards. Run on both `chromium` and `webkit`, at 393 px --
 * the width and touch class the architect's phone actually is.
 */

import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile, stat } from 'node:fs/promises';
import path from 'node:path';
import { chromium, webkit } from 'playwright';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const CURRENT = JSON.parse(await readFile(path.join(ROOT, 'atlas', 'current.json'), 'utf8'));
const GENERATION = CURRENT.generation;

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();

// A fixed GB point, matching the pattern of the technology-bucket proof --
// no repd_ref, so no dependency on the live register.
const query = new URLSearchParams({
  technology: 'solar', latitude: '52.6369', longitude: '-1.1398',
  zoom: '12', project: 'GRIDATLAS_PROOF_visibility', capacity_mw: '10'
});
const url = `http://127.0.0.1:${port}/atlas/?${query}`;

const ENGINES = [
  { name: 'chromium', launcher: chromium, mobile: true },
  { name: 'webkit', launcher: webkit, mobile: false }   // Playwright's isMobile emulation is Chromium-only
];
const engineFilter = String(process.env.GRIDATLAS_BROWSER_ENGINE || '').trim();
const selectedEngines = engineFilter ? ENGINES.filter((e) => e.name === engineFilter) : ENGINES;
assert.ok(selectedEngines.length, `no engine matched GRIDATLAS_BROWSER_ENGINE=${engineFilter}`);

const failures = [];
function check(label, condition, detail) {
  if (condition) { console.log(`  [PASS] ${label}`); }
  else { console.log(`  [FAIL] ${label}${detail ? ' -- ' + detail : ''}`); failures.push(label); }
}

try {
  for (const engine of selectedEngines) {
    console.log(`\n=== ${engine.name} ===`);
    const browser = await engine.launcher.launch({ headless: true });
    const context = await browser.newContext({
      viewport: { width: 393, height: 852 }, hasTouch: true,
      ...(engine.mobile ? { isMobile: true } : {})
    });
    const page = await context.newPage();
    const pageErrors = [];
    page.on('pageerror', (error) => pageErrors.push(String(error?.message || error)));

    // Installed BEFORE any page script runs, so the arrival's own gating
    // sees a genuinely hidden document from the very first line of JS --
    // the same as a real tab opened in the background.
    await page.addInitScript(() => {
      let state = 'hidden';
      Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state });
      Object.defineProperty(document, 'hidden', { configurable: true, get: () => state === 'hidden' });
      window.__gridatlasProofSetVisibility = (next) => {
        state = next;
        document.dispatchEvent(new Event('visibilitychange'));
      };
    });

    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,
    null, { timeout: 120_000 });

    // The arrival must recognise the hidden document and defer itself.
    await page.waitForFunction(() =>
      window.__GRIDATLAS_NEON_LINKS__?.arrival_deferred_for_visibility === true,
    null, { timeout: 30_000 });

    // Wait past the OLD 12s budget while still hidden. Nothing should have
    // been attempted, let alone completed.
    await page.waitForTimeout(14_000);
    const whileHidden = await page.evaluate(() => ({
      visibilityState: document.visibilityState,
      links_drawn: window.__GRIDATLAS_NEON_LINKS__?.links_drawn ?? null,
      camera: window.__GRIDATLAS_NEON_LINKS__?.camera_from_link ?? null,
      attempts: window.__GRIDATLAS_NEON_LINKS__?.arrival_attempts ?? null,
      failures: window.__GRIDATLAS_NEON_LINKS__?.failures ?? null
    }));
    check(`${engine.name}: document really reads hidden`,
      whileHidden.visibilityState === 'hidden');
    check(`${engine.name}: the arrival was never attempted while hidden `
      + '(the old code would have started, burned the 12s budget, and failed)',
      whileHidden.attempts === 0, JSON.stringify(whileHidden));
    check(`${engine.name}: the camera never flew while hidden`,
      whileHidden.camera === null, JSON.stringify(whileHidden.camera));
    check(`${engine.name}: nothing drawn while hidden`,
      whileHidden.links_drawn === 0, String(whileHidden.links_drawn));
    check(`${engine.name}: no spurious "layer controls" failure was recorded `
      + 'for time nobody could see spent',
      Array.isArray(whileHidden.failures) && whileHidden.failures.length === 0,
      JSON.stringify(whileHidden.failures));

    // Now the tab is actually shown.
    await page.evaluate(() => window.__gridatlasProofSetVisibility('visible'));

    try {
      await page.waitForFunction(() =>
        (window.__GRIDATLAS_NEON_LINKS__?.links_drawn ?? 0) > 0,
      null, { timeout: 60_000 });
    } catch (error) {
      const diagnostic = await page.evaluate(() => ({
        link: window.__GRIDATLAS_NEON_LINKS__ ? {
          links_drawn: window.__GRIDATLAS_NEON_LINKS__.links_drawn,
          camera_from_link: window.__GRIDATLAS_NEON_LINKS__.camera_from_link,
          arrival_attempts: window.__GRIDATLAS_NEON_LINKS__.arrival_attempts,
          arrival_resumed_on_visibility: window.__GRIDATLAS_NEON_LINKS__.arrival_resumed_on_visibility,
          failures: window.__GRIDATLAS_NEON_LINKS__.failures
        } : null
      }));
      throw new Error(`${engine.name}: arrival never recovered after becoming visible: `
        + `${JSON.stringify(diagnostic)}`, { cause: error });
    }

    const afterVisible = await page.evaluate(() => ({
      links_drawn: window.__GRIDATLAS_NEON_LINKS__.links_drawn,
      camera: window.__GRIDATLAS_NEON_LINKS__.camera_from_link,
      failures: window.__GRIDATLAS_NEON_LINKS__.failures,
      resumed: window.__GRIDATLAS_NEON_LINKS__.arrival_resumed_on_visibility,
      popupText: document.querySelector('.maplibregl-popup-content')
        ?.innerText.replace(/\s+/g, ' ').trim() || ''
    }));
    check(`${engine.name}: the camera flew to the requested coordinates once visible`,
      afterVisible.camera?.longitude === -1.1398 && afterVisible.camera?.latitude === 52.6369,
      JSON.stringify(afterVisible.camera));
    check(`${engine.name}: links were drawn once visible`,
      afterVisible.links_drawn > 0, String(afterVisible.links_drawn));
    check(`${engine.name}: the project card is on screen`,
      /GRIDATLAS_PROOF_visibility/.test(afterVisible.popupText), afterVisible.popupText);
    check(`${engine.name}: the resumed-on-visibility counter recorded the recovery`,
      afterVisible.resumed >= 1, String(afterVisible.resumed));
    check(`${engine.name}: no page errors across the whole run`,
      pageErrors.length === 0, pageErrors.join(' | '));

    await context.close();
    await browser.close();
  }

  console.log(`\n${failures.length === 0 ? 'ALL' : 'SOME'} checks passed (${failures.length} failure(s))`);
  if (failures.length) {
    console.error('\nFAILURES');
    for (const failure of failures) console.error('  ' + failure);
    process.exitCode = 1;
  } else {
    console.log('the arrival never runs hidden, and never stays stranded once seen.');
  }
} finally {
  await new Promise((resolve) => server.close(resolve));
}