GLOBALGRID2050 / EXPLORE CODE

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

Place Global Search V9 5 and 5 more files

A JavaScript file in the cartridges folder of GridAtlas that maps Renewable Energy Planning Database (REPD) projects and offshore coordinates, using SHA-256, and uses data from postcodes.io and OpenStreetMap Nominatim.

546 lines of JavaScript and HTML and CSS from gridatlas, in 6 files. Topic: Maps, GIS and field navigation. Section 519 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. Place Global Search V9 5 geodesy · gridatlas / atlas/cartridges/202611180026-place-global-search-v9-5.js lines 701–931
  2. Codex Lab render · gridatlas / atlas/codex/202609020010/assets/lab.css lines 1–12
  3. Codex Lab interaction · gridatlas / atlas/codex/202609020010/assets/lab.js lines 1–36
  4. Atlas — Codex Page render · gridatlas / atlas/codex/202609020010/index.html lines 1–31
  5. Codex Proof storage · gridatlas / atlas/codex/202609020010/proof.mjs lines 1–112
  6. GridAtlas — Atlas Page render · gridatlas / atlas/index.html lines 1–124

Place Global Search V9 5

A JavaScript file in the cartridges folder of GridAtlas that maps Renewable Energy Planning Database (REPD) projects and offshore coordinates, using SHA-256, and uses data from postcodes.io and OpenStreetMap Nominatim.

Set aside from the main view: A comment at the top of the file says a tool wrote it. (noise-generated, proposed by noise.py). All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line 4 comment: * ASSEMBLED by tools/build-cartridge.mjs from the parts below. Do not edit

geodesygridatlas / atlas/cartridges/202611180026-place-global-search-v9-5.js · lines 701–931 of 931 · version 2026-11-18 00:26 (continued from section 518) · pattern loadDerivedCoordinates (shared by 4 files)

What it does
It maps REPD projects, offshore coordinates, postcodes and the REPD register. Defines 41 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 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: postcodes, the REPD register.
Inputs & outputs
In: data source: postcodes.io; data source: OpenStreetMap Nominatim; Parquet file repd_projects_202611132345.parquet; JSON file repd_v9_manifest_202611132345.json; JSON file offshore-coordinates.json; DuckDB queries. Out: interactive map. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
What it achieves
It marks deep link cancelled (`markDeepLinkCancelled`), normalises compact (`normaliseCompact`) and parses groups (`parseGroups`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. It responds to gridatlas, click and input events.
Why it matters
Loaded by the Substation Finder page in Code Generator at https://ventusltd.github.io/code-generator/apps/substation-finder/.
Application
gridatlas · atlas/cartridges · 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)
Produces
invariant, arrivalCoordinator, markDeepLinkCancelled, invalidatePendingDeepLink, escapeHtml, sqlString, normaliseCompact, parseGroups, sha256Hex, verifyManifest, sharedDuckDBRuntime, promise
Defines here
receiveExactRepdDeepLink, stillOwned, retryExactRepdDeepLink, bindSearch
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-place-global-search-v9-5.js:701-931 · blob c3ef9b6b82b3e983feb93015b168fed3d11322b9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
  }

  async function receiveExactRepdDeepLink(input, resultsEl,
    expectedOwnerEpoch = null) {
    const params = new URLSearchParams(window.location.search);
    const repdRef = String(params.get('repd_ref') || '').trim();
    if (!repdRef) {
      state.deep_link = { status: 'ABSENT', repd_ref: null, resolved: false, mapped: false };
      return;
    }

    const arrival = suppliedArrivalFields(params, repdRef);
    let coordinator = null;
    let ownerEpoch = null;
    try {
      invariant(/^[A-Za-z0-9-]{1,40}$/.test(repdRef), 'invalid exact REPD deep-link identity');
      coordinator = arrivalCoordinator();
      invariant(coordinator, 'shared arrival coordinator unavailable');
      if (Number.isInteger(expectedOwnerEpoch)) {
        if (!coordinator.arrivalGate.isCurrent(expectedOwnerEpoch)) return;
        ownerEpoch = expectedOwnerEpoch;
      } else {
        ownerEpoch = coordinator.claimPendingArrival(window.location.search);
      }
      state.deep_link = {
        ...arrival, owner_epoch: ownerEpoch, status: 'RECEIVING',
        resolved: false, mapped: false,
        identity_source: 'ACTIVE_REGISTER_PENDING'
      };
      const stillOwned = () => coordinator.arrivalGate.isCurrent(ownerEpoch);
      const querySerial = ++activeQuerySerial;
      input.value = repdRef;
      const results = await queryOfficialRepd(repdRef, querySerial, stillOwned);
      if (!stillOwned() || querySerial !== activeQuerySerial) return;
      const exact = results.find(result => String(result.repd_ref) === repdRef);
      if (!exact) {
        // A successful query with no exact row is evidence about this active
        // snapshot, not a network failure and not evidence that the supplied
        // project never existed. Keep the link's point and identity separate.
        renderResults(results, resultsEl);
        document.body.dataset.gridatlasRepdRef = repdRef;
        document.body.dataset.gridatlasRepdDeepLink = 'not-in-active-register';
        state.deep_link = {
          ...arrival,
          owner_epoch: ownerEpoch,
          status: 'NOT_IN_ACTIVE_REGISTER',
          resolved: false,
          mapped: false,
          supplied_point_usable: hasSafeMapPoint(arrival),
          identity_source: 'ARRIVAL_LINK',
          official_active_register_match: false,
          statement: 'No exact identity in the active-register snapshot; supplied arrival fields retained.'
        };
        return;
      }
      renderResults(results, resultsEl);
      await waitForCapturedMap();
      if (!stillOwned()) return;

      /* A ref the register does not locate used to be treated worse than a ref
         the register does not contain. The not-in-register branch above keeps
         the supplied arrival point and degrades gracefully; this branch found
         its row, could not map it, and threw - so a project present in the
         register but without a coordinate showed the user a failure card.
         Measured on the live page: between 3 and 8 of 20 MAP links carry no
         coordinate at all, so there was nothing to fall back to either.

         Offshore is where this bites. 8 of 101 offshore rows carry no easting
         or northing, and the Crown Estate leases the seabed under them, so a
         derived point exists for 6 of the 8 in atlas/data/offshore-coordinates.json.
         Using it is honest as long as the card says the coordinate is derived
         and the identity is not: the register named the project, the lease
         located it. */
      const derived = !hasSafeMapPoint(exact) ? await derivedCoordinateFor(repdRef) : null;
      if (derived) {
        exact.longitude = derived.longitude;
        exact.latitude = derived.latitude;
      }
      /* No register point and no lease point. Measured offline on v9.144:
         13432 is in the register, has no coordinate, is in no lease, and
         still reached the invariant below and showed a failure card. A name
         the register confirmed is worth more than a card that says try again,
         so the identity stands and the map does not move. If the link itself
         carried a usable point it is used and labelled as the link's, never
         as the register's. */
      const linkPoint = !hasSafeMapPoint(exact) && hasSafeMapPoint(arrival)
        ? { longitude: arrival.longitude, latitude: arrival.latitude } : null;
      if (linkPoint) {
        exact.longitude = linkPoint.longitude;
        exact.latitude = linkPoint.latitude;
      }
      if (!hasSafeMapPoint(exact)) {
        document.body.dataset.gridatlasRepdRef = repdRef;
        document.body.dataset.gridatlasRepdDeepLink = 'resolved-unmapped';
        state.deep_link = {
          ...arrival,
          owner_epoch: ownerEpoch,
          repd_ref: repdRef,
          status: 'RESOLVED_UNMAPPED',
          resolved: true,
          mapped: false,
          name: exact.name,
          technology: exact.technology,
          capacity_mw: exact.capacity_mw,
          status_value: exact.status,
          identity_source: 'OFFICIAL_ACTIVE_REGISTER',
          official_active_register_match: true,
          coordinate_source: 'NONE',
          coordinate_derived: false,
          coordinate_lease: null,
          coordinate_tenant: null,
          coordinate_statement: 'The register names this project but holds no coordinate for it, and no Crown Estate lease covers it. Identity confirmed; position unknown; the map was not moved.',
          statement: 'Exact identity in the active-register snapshot; no coordinate from any source held.'
        };
        return;
      }
      if (!selectResult(exact, { deepLinkEpoch: ownerEpoch })) return;
      if (!stillOwned()) return;
      invariant(state.last_selection?.repd_ref === repdRef, 'exact REPD selection was not retained');
      invariant(state.last_selection?.mapped === true, 'exact REPD identity did not fly to a safe map point');
      document.body.dataset.gridatlasRepdRef = repdRef;
      document.body.dataset.gridatlasRepdDeepLink = 'resolved';
      state.deep_link = {
        status: 'RESOLVED',
        owner_epoch: ownerEpoch,
        repd_ref: repdRef,
        resolved: true,
        mapped: true,
        /* Identity and coordinate have different provenance and are reported
           separately. The register named this project; where it did not locate
           it, a Crown Estate lease did, and the card must not present the two
           as one fact. */
        coordinate_source: derived ? derived.source : linkPoint ? 'ARRIVAL_LINK' : 'OFFICIAL_ACTIVE_REGISTER',
        coordinate_derived: Boolean(derived),
        coordinate_lease: derived ? derived.lease : null,
        coordinate_tenant: derived ? derived.tenant : null,
        coordinate_statement: derived
          ? 'Position derived from Crown Estate lease geometry because the register carries no coordinate for this project. The identity is the register’s; the position is not.'
          : linkPoint
            ? 'Position taken from the arrival link because the register carries no coordinate for this project and no lease covers it. The identity is the register’s; the position is the link’s.'
            : 'Position as published in the active register.',
        name: exact.name,
        postcode: exact.postcode,
        longitude: exact.longitude,
        latitude: exact.latitude,
        technology: exact.technology,
        capacity_mw: exact.capacity_mw,
        status_value: exact.status,
        identity_source: 'OFFICIAL_ACTIVE_REGISTER',
        official_active_register_match: true
      };
    } catch (error) {
      if (coordinator && Number.isInteger(ownerEpoch)
          && !coordinator.arrivalGate.isCurrent(ownerEpoch)) return;
      const message = String(error?.message || error);
      state.failures.push({ phase: 'exact_repd_deep_link', repd_ref: repdRef, message });
      state.deep_link = {
        ...arrival, owner_epoch: ownerEpoch, status: 'FAILED',
        resolved: false, mapped: false, message,
        identity_source: 'ACTIVE_REGISTER_CHECK_FAILED'
      };
      document.body.dataset.gridatlasRepdDeepLink = 'failed';
      console.error('[V9 EXACT REPD DEEP LINK]', error);
    }
  }

  async function retryExactRepdDeepLink(input, resultsEl, ownerEpoch) {
    const coordinator = arrivalCoordinator();
    invariant(coordinator, 'shared arrival coordinator unavailable for retry');
    invariant(Number.isInteger(ownerEpoch), 'identity retry requires one shared owner epoch');
    if (!coordinator.arrivalGate.isCurrent(ownerEpoch)) return state.deep_link;
    state.identity_retry_count += 1;
    await resetOfficialRuntime();
    if (!coordinator.arrivalGate.isCurrent(ownerEpoch)) return state.deep_link;
    return receiveExactRepdDeepLink(input, resultsEl, ownerEpoch);
  }

  function bindSearch() {
    const input = document.getElementById('search-input');
    const button = document.getElementById('search-btn');
    const resultsEl = document.getElementById('search-results');
    invariant(input && button && resultsEl, 'V8 search controls missing');
    input.setAttribute('placeholder', 'Search project, address, postcode or place...');
    input.setAttribute('aria-label', 'Search project, address, postcode or place');

    input.addEventListener('input', event => {
      event.stopImmediatePropagation();
      invalidatePendingDeepLink('user-search-input');
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => executeSearch(input, resultsEl, false), 180);
    }, true);

    input.addEventListener('keydown', event => {
      if (event.key === 'Enter') {
        event.preventDefault();
        event.stopImmediatePropagation();
        invalidatePendingDeepLink('user-search-submit');
        clearTimeout(debounceTimer);
        executeSearch(input, resultsEl, true);
      } else if (event.key === 'Escape') {
        event.stopImmediatePropagation();
        invalidatePendingDeepLink('user-search-dismiss');
        resultsEl.style.display = 'none';
      }
    }, true);

    button.addEventListener('click', event => {
      event.preventDefault();
      event.stopImmediatePropagation();
      invalidatePendingDeepLink('user-search-submit');
      clearTimeout(debounceTimer);
      executeSearch(input, resultsEl, true);
    }, true);

    state.retry_exact_deep_link = (ownerEpoch) =>
      retryExactRepdDeepLink(input, resultsEl, ownerEpoch);
    state.ready = true;
  }

  window.addEventListener('DOMContentLoaded', () => {
    try {
      bindSearch();
      const input = document.getElementById('search-input');
      const resultsEl = document.getElementById('search-results');
      void receiveExactRepdDeepLink(input, resultsEl);
    } catch (error) {
      state.failures.push({ phase: 'bind', message: String(error?.message || error) });
      console.error('[V9 PLACE SEARCH INIT]', error);
    }
  }, { once: true });
})();

Codex Lab

A style sheet in the assets folder of GridAtlas.

rendergridatlas / atlas/codex/202609020010/assets/lab.css · lines 1–12 of 12 · version 2026-09-02 00:10 · Entry point

What it does
Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
Used directly by 1 file: Atlas — Codex Page (gridatlas, https://gridatlas.globalgrid2050.com/atlas/codex/202609020010/).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Loaded by the Codex page at https://gridatlas.globalgrid2050.com/atlas/codex/202609020010/.
Application
gridatlas · atlas/codex/202609020010/assets · style sheet
Uses
none found
Used by
loaded by Atlas — Codex Page (stylesheet)
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 atlas/codex/202609020010/assets/lab.css:1-12 · blob bed75cf1976fffa6fccb818d70c5f2a4cca2c128 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: production_core
:root { color-scheme: dark; font-family: system-ui, sans-serif; background:#071011; color:#e9ffff; }
body { margin:0; min-height:100vh; background:radial-gradient(circle at 20% 0,#123a3d,#071011 55%); }
main { width:min(760px,calc(100% - 32px)); margin:auto; padding:42px 0; }
.stamp { color:#79f8ef; letter-spacing:.13em; font-size:.78rem; font-weight:800; }
h1 { margin:.25rem 0 1rem; font-size:clamp(2rem,7vw,4.5rem); line-height:.95; }
.limit { border-left:4px solid #ff8acb; padding:12px 16px; background:#1b1520; }
form { display:grid; grid-template-columns:repeat(auto-fit,minmax(210px,1fr)); gap:14px; margin:26px 0; }
label { display:grid; gap:6px; color:#b9d3d4; }
input,button { box-sizing:border-box; width:100%; padding:12px; border:1px solid #41666a; border-radius:5px; background:#0a181a; color:#fff; }
button { background:#79f8ef; color:#051011; font-weight:800; cursor:pointer; align-self:end; }
pre { min-height:110px; overflow:auto; padding:16px; background:#030909; border:1px solid #23474a; }
.ownership { color:#93aeb0; font-size:.9rem; }

Codex Lab

A JavaScript file in the assets folder of GridAtlas.

interactiongridatlas / atlas/codex/202609020010/assets/lab.js · lines 1–36 of 36 · version 2026-09-02 00:10 · Entry point · pattern envelope (shared by 2 files)

What it does
Defines envelope. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
Used directly by 1 file: Atlas — Codex Page (gridatlas, https://gridatlas.globalgrid2050.com/atlas/codex/202609020010/).
What it achieves
Defines `envelope`. It responds to submit events.
Why it matters
Loaded by the Codex page at https://gridatlas.globalgrid2050.com/atlas/codex/202609020010/.
Application
gridatlas · atlas/codex/202609020010/assets · script
Uses
none found
Used by
loaded by Atlas — Codex Page (script src)
Produces
envelope
Defines here
envelope
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/codex/202609020010/assets/lab.js:1-36 · blob 1fb55952f544f485c9909c2c7f71466f1b011425 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: production_core
(() => {
  'use strict';
  const SCHEMA = 'gridatlas.codex-computation-lab.v1';
  const LIMIT = 'Screening only: not solved power flow, available headroom, queue position, a connection offer or a connection assessment.';
  const form = document.getElementById('click-form');
  const answer = document.getElementById('answer');

  function envelope(values) {
    const lon = Number(values.get('lon'));
    const lat = Number(values.get('lat'));
    if (!Number.isFinite(lon) || !Number.isFinite(lat)
      || lon < -180 || lon > 180 || lat < -90 || lat > 90) return null;
    const kv = Number(values.get('connection_kv'));
    return {
      schema: SCHEMA,
      generation: '202609020010',
      origin: { lon, lat },
      repd_ref: values.get('repd_ref') || null,
      site_code: (values.get('site_code') || '').toUpperCase() || null,
      connection_voltage_kv: Number.isFinite(kv) ? kv : null,
      computation_state: 'inputs-only',
      missing: ['declared-connection-product', 'mapped-substation-product',
        'voltage-scoped-network-product'],
      limits: LIMIT
    };
  }

  form.addEventListener('submit', event => {
    event.preventDefault();
    const result = envelope(new FormData(form));
    answer.textContent = result ? JSON.stringify(result, null, 2)
      : 'Invalid coordinate: no screening envelope was produced.';
  });

  window.__CODEX_GRID_LAB__ = Object.freeze({ schema: SCHEMA, envelope });
})();

Atlas — Codex Page

A web page in GridAtlas that reads inputs for lon, lat and Renewable Energy Planning Database (REPD) ref. Published at https://gridatlas.globalgrid2050.com/atlas/codex/202609020010/.

rendergridatlas / atlas/codex/202609020010/index.html · lines 1–31 of 31 · version 2026-09-02 00:10 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "`atlas/index.html` is the stable composer."
Inputs & outputs
In: form fields (user input). Out: web page.
Downstream impact
It is itself an entry point, published at https://gridatlas.globalgrid2050.com/atlas/codex/202609020010/.
What it achieves
Codex computation lab.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · atlas/codex/202609020010 · page
Uses
Codex Lab (stylesheet), Codex Lab (script src)
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 atlas/codex/202609020010/index.html:1-31 · blob e98be8c6c908c277ac5c39d43d8f0d51655a6679 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: production_core
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Codex computation lab · 202609020010</title>
  <link rel="stylesheet" href="./assets/lab.css">
</head>
<body>
  <main>
    <p class="stamp">CODEX COMPUTATION LAB · 202609020010</p>
    <h1>Grid-click computation envelope</h1>
    <p class="limit"><strong>Screening only.</strong> Published facts and
      straight-line measurements are not solved power flow, available
      headroom, queue position, a connection offer or a connection assessment.</p>
    <form id="click-form">
      <label>Longitude <input name="lon" inputmode="decimal" value="-0.6774547"></label>
      <label>Latitude <input name="lat" inputmode="decimal" value="53.2926216"></label>
      <label>REPD reference <input name="repd_ref" value="10916"></label>
      <label>ETYS site code <input name="site_code" value="WBUR"></label>
      <label>Connection voltage (kV) <input name="connection_kv" inputmode="numeric" value="400"></label>
      <button type="submit">Build screening envelope</button>
    </form>
    <pre id="answer" aria-live="polite"></pre>
    <p class="ownership">This immutable Codex route neither composes nor
      promotes the shared GridAtlas application. Its assets are pinned by
      <code>route-manifest.json</code>.</p>
  </main>
  <script src="./assets/lab.js"></script>
</body>
</html>

Codex Proof

A JavaScript module in the atlas folder of GridAtlas that fetches route, using SHA-256. Served with the page at https://gridatlas.globalgrid2050.com/atlas/codex/202609020010/.

storagegridatlas / atlas/codex/202609020010/proof.mjs · lines 1–112 of 112 · version 2026-09-02 00:10 · Not reached from any entry point (candidate for review)

What it does
It fetches route. Defines git, check, walk. Uses libraries node:crypto, node:child_process, node:fs/promises, node:path, node:url. Side effects: reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file route-manifest.json; browser IndexedDB.
What it achieves
Defines `git`, `check` and `walk`.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/codex/202609020010 · JavaScript module
Uses
node:crypto, node:child_process, node:fs/promises, node:path, node:url
Used by
none found
Produces
git, check, walk
Defines here
git, check, walk
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/codex/202609020010/proof.mjs:1-112 · blob 9df7b69e8065bd13d67d7eba81da16a6181efe1d · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, network, process, storage · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { readFile, readdir } from 'node:fs/promises';
import { dirname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
const generation = '202609020010';
const route = join(ROOT, 'atlas', 'codex', generation);
const manifest = JSON.parse(await readFile(join(route, 'route-manifest.json'), 'utf8'));
const git = (...args) => execFileSync('git', args, { cwd: ROOT, encoding: 'utf8' }).trim();
const base = process.env.CODEX_ROUTE_BASE || 'origin/main';
let passed = 0; const failures = [];
function check(label, condition) {
  if (condition) { passed++; console.log(`  [PASS] ${label}`); }
  else { failures.push(label); console.log(`  [FAIL] ${label}`); }
}
async function walk(dir) {
  const out = [];
  for (const item of await readdir(dir, { withFileTypes: true })) {
    const path = join(dir, item.name);
    if (item.isDirectory()) out.push(...await walk(path)); else out.push(path);
  }
  return out;
}

const files = await walk(route);
const texts = await Promise.all(files.map(async path => [path, await readFile(path, 'utf8')]));
const joined = texts.map(([, text]) => text).join('\n');
const served = texts.filter(([path]) => /(?:index\.html|assets[\\/].*\.(?:js|css))$/.test(path))
  .map(([, text]) => text).join('\n');
const html = await readFile(join(route, 'index.html'), 'utf8');
check('route generation is immutable and exactly twelve digits',
  /^\d{12}$/.test(generation) && manifest.generation === generation && manifest.immutable === true);
check('the page visibly declares CODEX COMPUTATION LAB', /CODEX COMPUTATION LAB/.test(html));
check('screening and connection-assessment limits are visible',
  /Screening only/.test(html) && /not solved power flow/.test(joined)
  && /available headroom/.test(joined) && /not.*connection assessment/i.test(joined));
check('the route never names or loads the shared composition pointer',
  !joined.includes('current' + '.json'));
check('the route has no root-relative, parent-relative or remote asset load',
  !/(?:src|href)=["'](?:\/|\.\.\/|https?:|\/\/)/i.test(html));
check('the lab performs no network request or storage mutation',
  !/\bfetch\s*\(|XMLHttpRequest|sendBeacon|localStorage|sessionStorage|indexedDB/.test(served));
check('every pinned asset is inside this route', manifest.assets.every(asset =>
  !asset.path.includes('..') && !asset.path.startsWith('/') && !/^https?:/i.test(asset.path)));
let hashesMatch = manifest.assets.length > 0;
for (const asset of manifest.assets) {
  const bytes = await readFile(join(route, asset.path));
  const hash = createHash('sha256').update(bytes).digest('hex');
  if (hash !== asset.sha256) hashesMatch = false;
}
check('every declared local artifact matches its pinned SHA-256', hashesMatch);
const declared = new Set(manifest.assets.map(asset => asset.path));
const actual = files.map(path => relative(route, path).replace(/\\/g, '/'))
  .filter(path => path !== 'route-manifest.json');
check('every served artifact is pinned, with no undeclared extra file',
  actual.length === declared.size && actual.every(path => declared.has(path)));
check('the lab exposes only an inputs-only envelope until owner products are pinned',
  /computation_state:\s*'inputs-only'/.test(joined)
  && /declared-connection-product/.test(joined)
  && /voltage-scoped-network-product/.test(joined));

/* Publication collision boundary. A clean route is insufficient if its
   branch also carries older changes outside the route. Validate the complete
   base-to-candidate transaction, using Git blobs rather than the working copy. */
const head = git('rev-parse', 'HEAD');
const parent = git('rev-parse', 'HEAD^');
const baseSha = git('rev-parse', base);
check('the candidate is a single transaction on the exact publication base',
  parent === baseSha);

const changed = git('diff', '--name-status', '--find-renames', `${baseSha}..${head}`)
  .split(/\r?\n/).filter(Boolean).map(line => {
    const [status, ...parts] = line.split('\t');
    return { status, paths: parts };
  });
const prefix = `atlas/codex/${generation}/`;
check('the complete transaction only adds files inside its exact route',
  changed.length > 0 && changed.every(change => change.status === 'A'
    && change.paths.length === 1 && change.paths[0].startsWith(prefix)
    && !change.paths[0].includes('..') && !change.paths[0].includes('\\')
    && !/[\u0000-\u001f\u007f]/.test(change.paths[0])));

let routeAlreadyExisted = true;
try {
  execFileSync('git', ['cat-file', '-e', `${baseSha}:atlas/codex/${generation}`],
    { cwd: ROOT, stdio: 'ignore' });
}
catch { routeAlreadyExisted = false; }
check('the publication base does not already contain this generation', !routeAlreadyExisted);

const tree = git('ls-tree', '-r', head, '--', `atlas/codex/${generation}`)
  .split(/\r?\n/).filter(Boolean).map(line => {
    const match = /^(\d+)\s+(\w+)\s+[a-f0-9]+\t(.+)$/.exec(line);
    return match && { mode: match[1], type: match[2], path: match[3] };
  });
check('the route contains ordinary blobs only, never symlinks or submodules',
  tree.length > 0 && tree.every(item => item && item.mode === '100644' && item.type === 'blob'));
const folded = tree.map(item => item.path.toLowerCase());
check('the route has no case-fold path collision', new Set(folded).size === folded.length);

let blobHashesMatch = true;
for (const asset of manifest.assets) {
  const blob = execFileSync('git', ['show', `${head}:${prefix}${asset.path}`], { cwd: ROOT });
  if (createHash('sha256').update(blob).digest('hex') !== asset.sha256) blobHashesMatch = false;
}
check('manifest hashes describe committed Git blobs, not translated working files', blobHashesMatch);

console.log(`\n${passed}/${passed + failures.length} checks passed`);
if (failures.length) process.exit(1);
console.log('the immutable Codex route is locally pinned and cannot share-load or mutate the live composition.');

GridAtlas — Atlas Page

A web page that works with escape attribute (`escapeAttribute`) and sha256 hex (`sha256Hex`), using SHA-256. Published at https://gridatlas.globalgrid2050.com/atlas/.

rendergridatlas / atlas/index.html · lines 1–124 of 124 · Entry point · pattern escapeAttribute (shared by 6 files)

What it does
It draws its content. Defines invariant, escapeAttribute, sha256Hex, fail. Uses libraries ${escapeAttribute(blobUrl)}. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. README: "`atlas/index.html` is the stable composer."
Inputs & outputs
In: JSON file current.json. Out: web page.
Downstream impact
Used directly by 242 files: Pilot (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609190330-cable-cross-sections/); Links (globalgrid2050); Build N1 Deep Link Candidates (code-generator); Single-Line Diagram (SLD) Mobile Arrival Card Browser (gridatlas); and 238 more. Reached from 317 other entry points, including Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html); Iterations — 32 Spider and Galaxy Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/). It is itself an entry point, published at https://gridatlas.globalgrid2050.com/atlas/.
What it achieves
It is built from the invariant step (`invariant`), the escape attribute helper (`escapeAttribute`) and the sha256 hex helper (`sha256Hex`). The README says: `atlas/index.html` is the stable composer. It reads `./current.json`.
Why it matters
Loaded by the Lightning Grid page at https://gridatlas.globalgrid2050.com/atlas/labs/lightning-grid/ and 134 other pages. Also imported by 81 files, including Pilot, Links and Build N1 Deep Link Candidates, from Claude, Code Generator, Cosmic and others. Checked by 26 tests, including Test Build Topology.
Application
gridatlas · atlas · page
Uses
${escapeAttribute(blobUrl)}
Used by
named by URL in Pilot (estate URL), named by URL in Links (estate URL), named by URL in Build N1 Deep Link Candidates (estate URL), named by URL in Single-Line Diagram (SLD) Mobile Arrival Card Browser (estate URL), named by URL in Test Build Topology (estate URL), named by URL in Atlas Pointer Deep Link (estate URL), named by URL in GlobalGrid2050 Catalogue GridAtlas V9 (estate URL), named by URL in GlobalGrid2050 Test Catalogue GridAtlas V9 (estate URL), and 234 more, mentioned in Index Composer (comment link)
Produces
invariant, escapeAttribute, sha256Hex, fail
Defines here
invariant, escapeAttribute, sha256Hex, fail
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/index.html:1-124 · blob aeb2936aae54c82d1a7f216924d58eaa771bae4d · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Grid Atlas</title>
  <style>
    html,body{height:100%;margin:0;background:#000;color:#00ffff;font:13px monospace}
    #gridatlas-loader{display:grid;place-items:center;height:100%;padding:24px;text-align:center}
    #gridatlas-loader strong{color:#ffae00}
  </style>
</head>
<body data-gridatlas-router="loading">
  <main id="gridatlas-loader"><div><strong>GRIDATLAS</strong><br>verifying immutable shell and cartridges…</div></main>
  <script type="module">
    const SCRIPT_CLOSE = '</scr' + 'ipt>';
    const loader = document.getElementById('gridatlas-loader');

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

    function escapeAttribute(value) {
      return String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
    }

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

    function fail(error) {
      console.error('[GRIDATLAS COMPOSER]', error);
      document.body.dataset.gridatlasRouter = 'failed';
      loader.innerHTML = `<div><strong>GRIDATLAS COMPOSITION FAILED</strong><br>${String(error?.message || error).replace(/[<>&]/g, '')}<br><small>The immutable shell was not changed.</small></div>`;
    }

    try {
      const currentResponse = await fetch('./current.json', { cache: 'no-store' });
      invariant(currentResponse.ok, `current.json HTTP ${currentResponse.status}`);
      const current = await currentResponse.json();
      invariant(current?.schema === 'gridatlas.current.v2', 'unsupported current.json schema');
      invariant(current?.architecture === 'IMMUTABLE_SHELL_PLUS_HASHED_CARTRIDGES', 'architecture contract mismatch');
      invariant(Array.isArray(current.cartridge_order) && Array.isArray(current.cartridges), 'cartridge registry malformed');

      const shellUrl = new URL(current.shell.index, window.location.href);
      const shellBase = new URL(current.shell.base, window.location.href).href;
      const shellResponse = await fetch(shellUrl, { cache: 'no-store' });
      invariant(shellResponse.ok, `immutable shell HTTP ${shellResponse.status}`);
      let html = await shellResponse.text();
      invariant(/<head\b/i.test(html) && /<body\b/i.test(html), 'immutable shell is not HTML');
      html = html.replace(/<head([^>]*)>/i, match => `${match}\n<base href="${escapeAttribute(shellBase)}">`);

      const byId = new Map(current.cartridges.map(item => [item.id, item]));
      const loaded = [];
      const scriptTagPattern = new RegExp('<script\\b[^>]*\\bsrc=(["\\\'])([^"\\\']+)\\1[^>]*>\\s*<\\/script>', 'gi');
      // Two slot types. 'replace-script' swaps one of the immutable shell's
      // script tags for a verified cartridge. 'after-cartridge' adds a verified
      // cartridge as its own script tag immediately after a cartridge composed
      // earlier in cartridge_order (after the last one already chained to it),
      // so it executes at exactly the point an appended module used to.
      const SLOTS = ['replace-script', 'after-cartridge'];
      const tailTag = new Map();

      for (const id of current.cartridge_order) {
        const cartridge = byId.get(id);
        invariant(cartridge, `missing cartridge ${id}`);
        invariant(cartridge.type === 'script', `${id}: unsupported cartridge type`);
        invariant(SLOTS.includes(cartridge.slot), `${id}: unsupported cartridge slot`);
        if (cartridge.slot === 'replace-script') {
          invariant(typeof cartridge.replace_script === 'string' && cartridge.replace_script, `${id}: replace_script missing`);
        } else {
          invariant(typeof cartridge.after === 'string' && tailTag.has(cartridge.after), `${id}: after-cartridge anchor ${cartridge.after} is not composed before it`);
        }
        invariant(/^[a-f0-9]{64}$/.test(cartridge.sha256 || ''), `${id}: invalid SHA-256`);

        const cartridgeUrl = new URL(cartridge.path, window.location.href);
        const response = await fetch(cartridgeUrl, { cache: 'no-store' });
        invariant(response.ok, `${id}: HTTP ${response.status}`);
        const bytes = await response.arrayBuffer();
        invariant(await sha256Hex(bytes) === cartridge.sha256, `${id}: SHA-256 mismatch`);
        const blobUrl = URL.createObjectURL(new Blob([bytes], { type: 'text/javascript' }));
        const tag = `<script data-gridatlas-cartridge="${escapeAttribute(id)}" src="${escapeAttribute(blobUrl)}">${SCRIPT_CLOSE}`;

        if (cartridge.slot === 'replace-script') {
          let replaced = false;
          html = html.replace(scriptTagPattern, (full, quote, src) => {
            if (replaced || String(src).split('/').pop() !== cartridge.replace_script) return full;
            replaced = true;
            return tag;
          });
          invariant(replaced, `${id}: shell slot ${cartridge.replace_script} not found`);
        } else {
          const anchor = tailTag.get(cartridge.after);
          const at = html.indexOf(anchor);
          invariant(at >= 0 && html.indexOf(anchor, at + 1) < 0, `${id}: anchor tag of ${cartridge.after} not found exactly once`);
          html = html.slice(0, at + anchor.length) + '\n' + tag + html.slice(at + anchor.length);
          tailTag.set(cartridge.after, tag);
        }
        tailTag.set(id, tag);
        loaded.push({ id, sha256: cartridge.sha256, blob_url: blobUrl });
      }

      const publicState = JSON.stringify({
        schema: current.schema,
        generation: current.generation,
        release_id: current.release_id,
        architecture: current.architecture,
        shell: current.shell,
        cartridge_order: current.cartridge_order,
        loaded_cartridges: loaded.map(item => ({ id: item.id, sha256: item.sha256 }))
      }).replace(/</g, '\\u003c');
      const stateScript = `<script>window.__GRIDATLAS_ATLAS__=${publicState};document.documentElement.dataset.gridatlasGeneration=${JSON.stringify(current.generation)};${SCRIPT_CLOSE}`;
      html = html.replace(/<body([^>]*)>/i, match => `${match}\n${stateScript}`);

      document.open();
      document.write(html);
      document.close();
    } catch (error) {
      fail(error);
    }
  </script>
</body>
</html>