GLOBALGRID2050 / EXPLORE CODE

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

All Versions Proof and 2 more files

A JavaScript module in the proofs folder of GridAtlas that reads composition, solar and 750kV, using haversine.

700 lines of JavaScript from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 646 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. Mobile Static Audit interaction · gridatlas / tools/proofs/202609010030-mobile-static.audit.mjs lines 1–189
  2. Parts Integrity Proof ingest · gridatlas / tools/proofs/202609012105-parts-integrity.proof.mjs lines 1–124
  3. All Versions Proof interaction · gridatlas / tools/proofs/202609012150-all-versions.proof.mjs lines 1–387

Mobile Static Audit

A JavaScript module in the proofs folder of GridAtlas that works with CSS block (`cssBlock`) and active rules (`activeRules`).

interactiongridatlas / tools/proofs/202609010030-mobile-static.audit.mjs · lines 1–189 of 189 · version 2026-09-01 00:30 · Entry point · pattern audit (shared by 7 files)

What it does
It draws its content. Defines cssBlock, px, audit, activeRules. Uses libraries node:assert/strict, node:fs, node:path. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: command-line arguments.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
It is built from the CSS block helper (`cssBlock`), the audit step (`audit`) and the active rules helper (`activeRules`). Static mobile gate for the composed GridAtlas shell and single-line diagram (SLD) cartridge. It responds to mousedown and pointerdown events.
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:fs, node:path
Used by
none found
Produces
cssBlock, px, audit, activeRules
Defines here
cssBlock, px, audit, activeRules
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/202609010030-mobile-static.audit.mjs:1-189 · blob 62ca9b37a8dbffebb6121a7ee0a40c3ddd24ca72 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node

/**
 * Static mobile gate for the composed GridAtlas shell and SLD cartridge.
 * It does not pretend to replace Claude's real browser/device pass; it catches
 * interaction and geometry failures that are already decidable from source.
 *
 * Usage:
 *   node tools/proofs/202609010030-mobile-static.audit.mjs \
 *     [--require-clean] <sld-cartridge.js> <ventus.css> <shell-index.html>
 */

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";

const rawArgs = process.argv.slice(2);
const requireClean = rawArgs.includes("--require-clean");
const args = rawArgs.filter(arg => arg !== "--require-clean");
if (args.length !== 3) {
  console.error("usage: node 202609010030-mobile-static.audit.mjs [--require-clean] <cartridge> <base-css> <shell-html>");
  process.exit(2);
}

function cssBlock(source, selector) {
  const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return source.match(new RegExp(`${escaped}\\s*\\{([^}]*)\\}`))?.[1] || "";
}

function px(declarations, property) {
  return Number(declarations.match(new RegExp(`${property}\\s*:\\s*(\\d+(?:\\.\\d+)?)px`))?.[1]);
}

function audit(cartridge, baseCss, shellHtml) {
  const findings = [];
  // The live page is the immutable shell plus the cartridge's injected CSS.
  // A phone repair is allowed to override the attested shell; auditing the
  // shell alone would keep reporting a defect the composed page no longer has.
  const composedCss = `${baseCss}\n${cartridge}`;

  const mouseOnlySurfaces = [
    ["project card", /bar\.addEventListener\(['"]mousedown['"]/, /bar\.addEventListener\(['"](?:pointerdown|touchstart)['"]/],
    ["layout panel", /heading\.addEventListener\(['"]mousedown['"]/, /heading\.addEventListener\(['"](?:pointerdown|touchstart)['"]/],
    ["array, rotation handle and route pins", /map\.on\(['"]mousedown['"]/, /map\.on\(['"](?:touchstart|pointerdown)['"]/],
  ].filter(([, mouse, touch]) => mouse.test(cartridge) && !touch.test(cartridge)).map(([name]) => name);
  if (mouseOnlySurfaces.length) {
    findings.push({
      code: "MOUSE_ONLY_DRAG_INTERACTIONS",
      detail: `${mouseOnlySurfaces.join("; ")} start only from mousedown; a touch screen cannot begin the claimed drag`,
      surfaces: mouseOnlySurfaces,
    });
  }

  const panel = cssBlock(cartridge, "#${PANEL_ID}");
  const panelTop = px(panel, "top");
  const panelInset = Number(panel.match(/max-height\s*:\s*calc\(100%\s*-\s*(\d+)px\)/)?.[1]);
  const mobilePanel = cartridge.match(/@media\s*\(max-width\s*:\s*700px\)\s*\{#\$\{PANEL_ID\}\s*\{([^}]*)\}/)?.[1] || "";
  const mobileTop = px(mobilePanel, "top");
  if (Number.isFinite(panelTop) && Number.isFinite(panelInset) && panelTop > panelInset) {
    findings.push({
      code: "SLD_PANEL_HEIGHT_OVERRUN",
      detail: "top plus max-height exceeds the map container before content or borders are counted",
      base_overrun_px: panelTop - panelInset,
      mobile_overrun_px: Number.isFinite(mobileTop) ? mobileTop - panelInset : null,
    });
  }

  const cardButton = cssBlock(cartridge, ".gridatlas-card-bar button");
  const panelButtons = cssBlock(cartridge, "#${PANEL_ID} .sld-min,#${PANEL_ID} .sld-close");
  const smallTargets = [];
  for (const [name, block] of [["card minimise/close", cardButton], ["layout minimise/close", panelButtons]]) {
    const width = px(block, "min-width");
    const height = px(block, "height");
    if ((Number.isFinite(width) && width < 44) || (Number.isFinite(height) && height < 44)) {
      smallTargets.push({ name, min_width_px: width, height_px: height });
    }
  }
  if (smallTargets.length) {
    findings.push({
      code: "TOUCH_TARGET_BELOW_44PX",
      detail: "primary panel controls are smaller than the 44 CSS px phone target",
      targets: smallTargets,
    });
  }

  const controls = cssBlock(composedCss, ".map-controls");
  const controlCount = (shellHtml.match(/class="map-ctrl-btn"/g) || []).length;
  const shortQueryAt = composedCss.search(/@media\s*\(max-height\s*:\s*600px\)/);
  const shortRules = shortQueryAt >= 0 ? composedCss.slice(shortQueryAt) : "";
  if (controlCount >= 6 && !/max-height|overflow-y|flex-wrap/.test(controls)
      && !/\.map-controls\s*\{[^}]*?(?:max-height|overflow-y|flex-wrap)/s.test(shortRules)) {
    findings.push({
      code: "LANDSCAPE_CONTROL_STACK_UNBOUNDED",
      detail: `${controlCount} shell buttons plus the injected GB control remain a bottom stack with no short-height bound, scroll or collapse rule`,
      shell_button_count: controlCount,
    });
  }

  const wrapper = cssBlock(composedCss, ".search-bar-wrapper");
  const results = cssBlock(composedCss, ".search-results");
  const searchBottom = px(wrapper, "top") + px(results, "top") + px(results, "max-height");
  if (Number.isFinite(searchBottom)
      && !/@media\s*\(max-height\s*:\s*600px\)[\s\S]*?\.search-results\s*\{/.test(composedCss)) {
    findings.push({
      code: "LANDSCAPE_SEARCH_RESULTS_UNBOUNDED",
      detail: `the fixed search dropdown can extend ${searchBottom}px from the map top and has no short-height override; the map container clips overflow`,
      extent_from_map_top_px: searchBottom,
    });
  }

  if (/Math\.min\(window\.innerWidth\s*-\s*60/.test(cartridge)) {
    findings.push({
      code: "CARD_DRAG_CLAMP_IGNORES_CARD_WIDTH",
      detail: "the free-card x clamp reserves 60px rather than measuring the card, so a dragged card can finish mostly beyond a phone edge",
    });
  }

  return findings;
}

function activeRules(width, height) {
  return [
    width <= 480 ? "shell:max-width-480" : null,
    width <= 700 ? "cartridge:max-width-700" : null,
    height <= 600 ? "shell:max-height-600" : null,
  ].filter(Boolean);
}

// The audit must prove that its principal disease fires and a repaired shape
// is silent before it is trusted against the real candidate.
const disease = `
bar.addEventListener('mousedown', begin);
heading.addEventListener('mousedown', begin);
map.on('mousedown', begin);
#\${PANEL_ID}{top:112px;max-height:calc(100% - 28px)}
@media (max-width:700px){#\${PANEL_ID}{top:96px}}
.gridatlas-card-bar button{min-width:26px;height:22px}
#\${PANEL_ID} .sld-min,#\${PANEL_ID} .sld-close{min-width:24px;height:20px}
Math.min(window.innerWidth - 60, x);
`;
const diseaseCss = `.map-controls{position:absolute}.search-bar-wrapper{top:72px}.search-results{top:36px;max-height:220px}@media (max-height:600px){.hud-header{padding:3px}}`;
const diseaseHtml = new Array(6).fill('<button class="map-ctrl-btn"></button>').join("");
const diseaseCodes = new Set(audit(disease, diseaseCss, diseaseHtml).map(item => item.code));
assert.ok(diseaseCodes.has("MOUSE_ONLY_DRAG_INTERACTIONS"));
assert.ok(diseaseCodes.has("SLD_PANEL_HEIGHT_OVERRUN"));
assert.ok(diseaseCodes.has("LANDSCAPE_CONTROL_STACK_UNBOUNDED"));

const healthy = `
bar.addEventListener('pointerdown', begin);
heading.addEventListener('pointerdown', begin);
map.on('touchstart', begin);
#\${PANEL_ID}{top:112px;bottom:14px;max-height:none}
.gridatlas-card-bar button{min-width:44px;height:44px}
#\${PANEL_ID} .sld-min,#\${PANEL_ID} .sld-close{min-width:44px;height:44px}
Math.min(window.innerWidth - card.getBoundingClientRect().width - 4, x);
`;
const healthyCss = `.map-controls{max-height:70%;overflow-y:auto}.search-bar-wrapper{top:72px}.search-results{top:36px;max-height:220px}@media (max-height:600px){.search-results{max-height:calc(100dvh - 140px)}}`;
assert.deepEqual(audit(healthy, healthyCss, diseaseHtml), []);

const [cartridgePath, cssPath, htmlPath] = args.map(item => path.resolve(item));
const findings = audit(
  fs.readFileSync(cartridgePath, "utf8"),
  fs.readFileSync(cssPath, "utf8"),
  fs.readFileSync(htmlPath, "utf8"),
);

const output = {
  schema: "gridatlas.mobile-static-audit.v1",
  target: {
    cartridge: cartridgePath,
    shell_css: cssPath,
    shell_html: htmlPath,
  },
  viewports: [
    { name: "phone_portrait_390", width: 390, height: 844, active_rules: activeRules(390, 844) },
    { name: "phone_portrait_414", width: 414, height: 896, active_rules: activeRules(414, 896) },
    { name: "phone_landscape_844", width: 844, height: 390, active_rules: activeRules(844, 390) },
  ],
  findings,
  disease_fixture: "FIRES",
  healthy_fixture: "SILENT",
  status: findings.length ? "MOBILE_STATIC_FAILURE" : "CLEAN",
};

console.log(JSON.stringify(output, null, 2));
if (requireClean && findings.length) {
  console.error(`FAIL: ${findings.length} mobile-static findings remain`);
  process.exit(1);
}

Parts Integrity Proof

A JavaScript module in the proofs folder of GridAtlas that uses SHA-256. It is built from the check step (`check`) and the sha256 step (`sha256`).

ingestgridatlas / tools/proofs/202609012105-parts-integrity.proof.mjs · lines 1–124 of 124 · version 2026-09-01 21:05 · Not reached from any entry point (candidate for review)

What it does
It loads data. Defines check, sha256. Uses libraries node:fs/promises, node:fs, node:crypto, node:path, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file -parts.json; JSON file current.json.
Downstream impact
Used directly by 2 files: Local CI (gridatlas); Shift (gridatlas).
What it achieves
Proof: an assembled cartridge still matches the parts it was built from.
Why it matters
Run by Local CI and Shift.
Application
gridatlas · tools/proofs · JavaScript module
Uses
node:fs/promises, node:fs, node:crypto, node:path, node:url
Used by
run by Local CI (script call), run by Shift (script call)
Produces
check, sha256
Defines here
check, sha256
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/202609012105-parts-integrity.proof.mjs:1-124 · blob c7c550cab1a66d778d11af391611c9df28015eab · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Proof: an assembled cartridge still matches the parts it was built from.
 *
 * The hole this closes was opened by my own hand. tools/build-cartridge.mjs
 * writes a parts manifest recording the SHA-256 of every part that went
 * into a cartridge — and then nothing ever looked at it again. I edited
 * atlas/modules/202609012040-grid-scope.js after the 202609012045
 * composition had already assembled it, and every gate in the estate
 * still passed 526/526, because they all test the CARTRIDGE bytes, which
 * had not moved. The manifest was a receipt no one was checking.
 *
 * Two rules, and they are deliberately different:
 *
 *   1. Every cartridge that has a parts manifest must still hash to the
 *      digest that manifest records. Cartridges are immutable here; a
 *      drift is an edited artefact and is always a failure.
 *
 *   2. For the cartridges in the CURRENT composition, every part must
 *      still hash to its record too — otherwise the thing being served
 *      cannot be rebuilt from the tree that claims to produce it. A
 *      superseded generation is exempt: its parts are allowed to have
 *      moved on, which is the whole point of a new generation.
 *
 * Rule 2 is what fails on a tree where a part was edited without
 * reassembling. The correct response is a new generation, never an edit
 * to the shipped cartridge.
 *
 *   node tools/proofs/202609012105-parts-integrity.proof.mjs
 */

import { readFile, readdir, access } from 'node:fs/promises';
import { constants } from 'node:fs';
import { createHash } from 'node:crypto';
import { dirname, join, resolve, basename } from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = resolve(HERE, '..', '..');
const MANIFESTS = join(REPO, 'atlas', 'manifests');

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

// Every digest in this estate is over LF bytes.
const sha256 = (text) => createHash('sha256')
  .update(text.replace(/\r\n/g, '\n'), 'utf8').digest('hex');

const entries = (await readdir(MANIFESTS)).filter(f => f.endsWith('-parts.json'));

/* Which generation is being served: the one atlas/current.json POINTS AT.
   This used to take the last manifest in name order, which is the same
   thing only while every stamp was read from the clock. On 1 Sep 2026 they
   were typed ahead of it - v9.67 is named 202609012250 and was cut at
   18:51 UTC - so the generation that succeeded it, read from the clock,
   sorts before it. Name order called the served composition superseded and
   the superseded one served, and then failed the wrong one. The pointer
   is the chain; sort order is a coincidence of honest clocks. */
const current = JSON.parse(
  await readFile(join(REPO, 'atlas', 'current.json'), 'utf8'));
const currentGeneration = current.generation;
const servedCartridges = new Set(
  (current.cartridges || []).map(c => basename(c.path || c.file || '')));

console.log(`\n${entries.length} parts manifest(s); serving generation ${currentGeneration}\n`);
check('there is at least one parts manifest to check', entries.length > 0);

for (const entry of entries) {
  const manifest = JSON.parse(await readFile(join(MANIFESTS, entry), 'utf8'));
  /* A manifest with no cartridge named is a broken record, and it used to
     take the whole proof down with an ERR_INVALID_ARG_TYPE from basename()
     rather than reporting itself. A gate that crashes tells you less than
     a gate that fails. */
  if (typeof manifest.cartridge !== 'string' || !manifest.cartridge) {
    check(`${entry}: names the cartridge it was built for`, false, 'no cartridge field');
    continue;
  }
  const cartridgeName = basename(manifest.cartridge);
  const cartridgePath = join(REPO, 'atlas', 'cartridges', cartridgeName);

  let present = true;
  try { await access(cartridgePath, constants.R_OK); } catch { present = false; }
  check(`${cartridgeName}: the cartridge its manifest names exists`, present);
  if (!present) continue;

  const cartridge = await readFile(cartridgePath, 'utf8');
  check(`${cartridgeName}: still hashes to its recorded digest`,
    sha256(cartridge) === manifest.sha256,
    `${sha256(cartridge).slice(0, 12)} vs ${String(manifest.sha256).slice(0, 12)}`);

  const isServed = servedCartridges.has(cartridgeName)
    || manifest.generation === currentGeneration;
  if (!isServed) {
    console.log(`  [skip] ${cartridgeName}: superseded, its parts may move on`);
    continue;
  }

  for (const part of manifest.assembled_from || []) {
    let source = null;
    try { source = await readFile(join(REPO, part.path), 'utf8'); } catch { /* gone */ }
    check(`${cartridgeName}: served part is present — ${part.path}`, source !== null);
    if (source === null) continue;
    check(`${cartridgeName}: served part is unchanged — ${part.path}`,
      sha256(source) === part.sha256,
      `${sha256(source).slice(0, 12)} vs ${String(part.sha256).slice(0, 12)}`);
  }
}

console.log(`\n${passed}/${passed + failures.length} checks passed`);
if (failures.length) {
  console.error('\nFAILURES');
  for (const failure of failures) console.error('  ' + failure);
  console.error('\nA served cartridge no longer matches the parts it was assembled\n'
    + 'from. Assemble a NEW generation from the edited parts. Do not edit the\n'
    + 'cartridge, and do not rewrite the manifest to agree with the drift.');
  process.exit(1);
}
console.log('every assembled cartridge still matches the parts it was built from.');

All Versions Proof

A JavaScript module in the proofs folder of GridAtlas that reads composition, solar and 750kV, using haversine.

interactiongridatlas / tools/proofs/202609012150-all-versions.proof.mjs · lines 1–387 of 462 · version 2026-09-01 21:50 · Not reached from any entry point (candidate for review) · pattern sandbox (shared by 2 files)

What it does
It loads composition, solar and 750kV. Defines 8 functions or classes, including check, sandbox, makeElement, MutationObserverStub, cartridgeContext. Uses libraries node:fs/promises, node:path, node:url, node:vm. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, 750kV, 415kV, 415V.
Inputs & outputs
In: JSON file current.json; JSON file -composition.json. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 415V.
Downstream impact
Used directly by 2 files: Local CI (gridatlas); Shift (gridatlas).
What it achieves
It makes element (`makeElement`) and is built from the check step (`check`) and the sandbox step (`sandbox`). Built vs all previous versions. Its code works with 750 kV and 415 kV.
Why it matters
Run by Local CI and Shift.
Application
gridatlas · tools/proofs · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL), node:fs/promises, node:path, node:url, node:vm
Used by
run by Local CI (script call), run by Shift (script call)
Produces
check, sandbox, makeElement, MutationObserverStub, cartridgeContext, walk, withoutComments, currentSandboxFile
Defines here
check, sandbox, makeElement, MutationObserverStub, cartridgeContext, walk, withoutComments, currentSandboxFile
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/202609012150-all-versions.proof.mjs:1-387 · blob a265d35d514411da535cdc862803bca25028cc72 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Built vs all previous versions.
 *
 * Vikram, 2026-09-01: *"deepen grid computation — built vs all previous
 * versions."*
 *
 * The existing parity proof compares the modules against ONE incumbent:
 * the cartridge currently composed. That is the version most likely to
 * agree with them, because it is the one they were extracted from. This
 * asks the harder question — does every version this estate has ever
 * shipped still agree?
 *
 * It matters because the estate's numbers are cumulative. A distance
 * published on a card in v9.51 and the same distance published in v9.65
 * have to be the same distance, or one of them was wrong and nobody said
 * which. The hostile reviewer raised exactly this about the Earth radius:
 * 6378.137 km is the WGS-84 equatorial semi-major axis where a spherical
 * haversine would conventionally use the mean 6371.0088, which is +0.11%
 * on every figure. That is a decision for the whole estate to take at once
 * — grid-distance-maths owns the constant — and this proof is what makes
 * taking it safely possible, because it can name every artefact that would
 * have to move together.
 *
 * Three passes:
 *
 *   1. THE CONSTANT. Every JavaScript artefact under atlas/ that carries an
 *      Earth radius carries the SAME one, and no artefact anywhere carries
 *      a second, different radius. This is exhaustive over the tree, so a
 *      new file cannot quietly introduce a second geodesy.
 *
 *   2. THE ANSWER. Every shipped cartridge that exposes a measuring surface
 *      is loaded and run against the same battery as the geodesy module,
 *      including the versions long superseded. Identical to the last digit,
 *      or it is a finding.
 *
 *      WITH ONE HONEST LIMIT, measured rather than assumed. "Identical to
 *      the last digit" holds IN THIS ENGINE. Verified on the deployed page:
 *      for West Burton Solar to Cottam, Node's V8 (13.6) returns
 *      7.050150827184836 from the atan2 form and ...837 from the asin form,
 *      while Chrome's V8 returns ...837 from BOTH. The same source, two
 *      engines, a different last bit - Math.asin and Math.atan2 are not
 *      required to be correctly rounded and their implementations differ
 *      between builds.
 *
 *      So this proves the estate's versions agree with each other under one
 *      engine, which is what catches a form or constant that has actually
 *      diverged. It does NOT prove bit-identical output in every browser,
 *      and no proof run here could. The bound that does hold is the useful
 *      one: the forms are algebraically the same, so any difference is at
 *      the scale of floating-point epsilon - 1e-15 km here - and no figure
 *      this estate displays is quoted to anywhere near that precision.
 *
 *   3. THE HISTORY. The version ledger on the page is checked against the
 *      compositions actually on disk, so the list a reader sees is the list
 *      that was really shipped.
 *
 *   node tools/proofs/202609012150-all-versions.proof.mjs
 */

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

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

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

function sandbox() {
  const box = { window: {}, console, Math, JSON, Number, String, Array, Object,
    Map, Set, Boolean, Error, RegExp, isNaN, parseFloat, parseInt };
  box.window.window = box.window;
  box.globalThis = box;
  vm.createContext(box);
  return box;
}

/* The same stubs the parity proof uses, because the same cartridges need
   them: a document that answers nothing, a MapLibre that constructs and
   does nothing, and an initVentusMap for the shell slot. */
function makeElement(tag) {
  return { tagName: tag, style: {}, dataset: {}, children: [],
    classList: { add() {}, remove() {}, contains: () => false },
    appendChild() {}, insertBefore() {}, addEventListener() {},
    removeEventListener() {}, setAttribute() {}, getAttribute: () => null,
    querySelector: () => null, querySelectorAll: () => [], remove() {},
    closest: () => null, getBoundingClientRect: () => ({ x: 0, y: 0, width: 0,
      height: 0, top: 0, left: 0, right: 0, bottom: 0 }) };
}
class MutationObserverStub { observe() {} disconnect() {} }

function cartridgeContext() {
  const documentStub = {
    baseURI: 'https://ventusltd.github.io/gridatlas/atlas/',
    head: makeElement('head'), body: makeElement('body'),
    getElementById: () => null, createElement: makeElement,
    querySelector: () => null, querySelectorAll: () => [], addEventListener() {}
  };
  const box = {
    window: { initVentusMap: (options) => options, matchMedia: () => ({ matches: false }),
      requestAnimationFrame: () => 0, cancelAnimationFrame: () => {},
      MutationObserver: MutationObserverStub, location: { search: '' },
      addEventListener() {}, innerWidth: 1280 },
    document: documentStub, console,
    fetch: async () => ({ ok: false, status: 404, json: async () => ({}) }),
    URL, Math, JSON, Number, String, Array, Object, Set, Map, Boolean, Error, RegExp,
    setTimeout, clearTimeout, setInterval, clearInterval, performance,
    requestAnimationFrame: () => 0, cancelAnimationFrame: () => {},
    MutationObserver: MutationObserverStub
  };
  box.window.maplibregl = { Map: class { constructor() {} on() {} once() {}
    getStyle() { return { layers: [] }; } isStyleLoaded() { return false; }
    getContainer() { return makeElement('div'); } }, Popup: class {} };
  box.maplibregl = box.window.maplibregl;
  box.window.window = box.window;
  box.globalThis = box;
  vm.createContext(box);
  return box;
}

async function walk(directory) {
  const found = [];
  let entries = [];
  try { entries = await readdir(directory, { withFileTypes: true }); } catch { return found; }
  for (const entry of entries) {
    const full = join(directory, entry.name);
    if (entry.isDirectory()) found.push(...await walk(full));
    else if (entry.isFile() && entry.name.endsWith('.js')) found.push(full);
  }
  return found;
}

/* ─────────────────────────────────────────────────────────────────────────
   1. ONE RADIUS, EVERYWHERE, EVER
   ───────────────────────────────────────────────────────────────────────── */

console.log('\none radius, across every artefact in the tree\n');

/* Radii a spherical Earth model plausibly uses. If any of these appears
   anywhere in the tree it is a second geodesy, whatever it is called. */
const OTHER_RADII = [
  ['6371.0088', 'IUGG mean radius'],
  ['6371.008', 'mean radius, truncated'],
  ['6371.0', 'mean radius'],
  ['6371,', 'mean radius, bare'],
  ['6356.752', 'WGS-84 polar semi-minor axis'],
  ['6372.8', 'a common approximation'],
  ['3958.8', 'mean radius in miles'],
  ['3963.19', 'equatorial radius in miles']
];

/* Comments are stripped before the scan. The first run of this flagged the
   sandbox body for 6371.0088, which turned out to be a sentence explaining
   that turf.destination defaults to it and this estate does not - exactly
   the documentation that should be there. A check that punishes writing
   down WHY is a check that gets the comment deleted rather than the code
   fixed. Code position only. */
const BLOCK_COMMENT = /\/\*[\s\S]*?\*\//g;
const LINE_COMMENT = /(^|[^:])\/\/.*$/;   // the [^:] keeps https:// intact
const withoutComments = (text) => text
  .replace(BLOCK_COMMENT, ' ')
  .split('\n')
  .map(line => line.replace(LINE_COMMENT, '$1'))
  .join('\n');

const files = await walk(ATLAS);
const carriers = [];
const strangers = [];
for (const file of files) {
  const text = withoutComments(await readFile(file, 'utf8'));
  const relativePath = relative(REPO, file).replace(/\\/g, '/');
  if (text.includes(String(ESTATE_RADIUS_KM))) carriers.push(relativePath);
  for (const [radius, why] of OTHER_RADII) {
    if (text.includes(radius)) strangers.push(`${relativePath}: ${radius} (${why})`);
  }
}

console.log(`         ${files.length} JavaScript artefacts under atlas/, `
  + `${carriers.length} of them measure`);
for (const carrier of carriers) console.log(`           ${carrier}`);

check('the tree was actually walked, not silently empty', files.length > 20);
check('more than one version measures, so this comparison means something',
  carriers.length >= 4, `${carriers.length} carriers`);
check('no artefact anywhere carries a different Earth radius',
  strangers.length === 0, strangers.join('; '));

/* The FORM, not only the constant.
   ------------------------------------------------------------------------
   The local CI found this gap by reading every blob ever committed: this
   scan checked that every artefact used the same radius, and said nothing
   about how it used it. Two forms of the same identity - R*2*atan2(...) and
   2*R*asin(...) - are one unit in the last place apart, which is how the
   geodesy module diverged from every version around it while passing a
   radius check. */
const ATAN2_FORM = /Math\.atan2\(\s*Math\.sqrt\(\s*\w+\s*\)\s*,\s*Math\.sqrt\(\s*1\s*-\s*\w+\s*\)/;
const ASIN_FORM = /Math\.asin\(\s*Math\.sqrt\(/;
const wrongForm = [];
for (const file of files) {
  const code = withoutComments(await readFile(file, 'utf8'));
  if (!code.includes(String(ESTATE_RADIUS_KM))) continue;
  if (ASIN_FORM.test(code) && !ATAN2_FORM.test(code)) {
    wrongForm.push(relative(REPO, file).replace(/\\/g, '/'));
  }
}
check('every measuring artefact uses the estate haversine form, not only its radius',
  wrongForm.length === 0, wrongForm.join('; '));


/* ─────────────────────────────────────────────────────────────────────────
   2. EVERY SHIPPED VERSION STILL ANSWERS THE SAME
   ───────────────────────────────────────────────────────────────────────── */

console.log('\nthe geodesy module against every version that measures\n');

const geodesySource = await readFile(
  join(ATLAS, 'modules', '202609011950-geodesy.js'), 'utf8');
const geodesyBox = sandbox();
vm.runInContext(geodesySource, geodesyBox, { filename: 'geodesy.js' });

/* The cartridge currently served, and the modules its siblings give it. */
const CURRENT_COMPOSITION = JSON.parse(
  await readFile(join(REPO, 'atlas', 'current.json'), 'utf8'));
const currentSandboxFile = (() => {
  const entry = (CURRENT_COMPOSITION.cartridges || []).find(c => c.id === 'sld-sandbox');
  return entry ? String(entry.path).split('/').pop() : null;
})();
const siblingModules = await (async () => {
  const out = [];
  for (const entry of (CURRENT_COMPOSITION.cartridges || [])) {
    if (entry.id === 'sld-sandbox' || !entry.assembled_from) continue;
    let manifest;
    try {
      manifest = JSON.parse(await readFile(
        join(REPO, 'atlas', String(entry.assembled_from).replace(/^\.\//, '')), 'utf8'));
    } catch { continue; }
    for (const part of (manifest.assembled_from || [])) {
      if (part.role !== 'module') continue;
      out.push(await readFile(join(REPO, part.path), 'utf8'));
    }
  }
  return out.join('\n');
})();
const geodesy = geodesyBox.window.__GRIDATLAS_MODULES__.geodesy;

check('the geodesy module is on the estate radius',
  geodesy.EARTH_RADIUS_KM === ESTATE_RADIUS_KM);

/* A battery chosen to break things, not to pass: a zero distance, a short
   hop, a long diagonal, the prime meridian crossed in both directions, and
   two real GB pairs whose figures have been published on cards. */
const BATTERY = [
  ['identical points', -0.6774547, 53.2926216, -0.6774547, 53.2926216],
  ['West Burton Solar to West Burton', -0.6774547, 53.2926216, -0.8092, 53.3616],
  ['West Burton Solar to Cottam', -0.6774547, 53.2926216, -0.7817, 53.3040],
  ['across the prime meridian, east to west', 0.15, 51.5, -0.15, 51.5],
  ['across the prime meridian, west to east', -0.15, 51.5, 0.15, 51.5],
  ['Lincolnshire to Blackhillock', -0.6774547, 53.2926216, -3.0, 57.5],
  ['one degree of latitude', 0, 50, 0, 51],
  ['one degree of longitude at 55N', 0, 55, 1, 55]
];

/* Each shipped cartridge exposes its measuring surface differently. This
   names them explicitly rather than guessing, because a cartridge whose
   surface is not found must be a FAILURE and not a silent skip - that is
   how a version quietly stops being compared. */
/* DISCOVERED from disk, never listed by hand.
   ------------------------------------------------------------------------
   A hand-written list is a list that stops including the newest version the
   moment someone forgets to add it - and a version that is not compared is
   a version that can drift without anyone hearing about it. Every cartridge
   that registers the neon-links measuring surface is found and compared,
   so cutting a new generation automatically widens this test rather than
   quietly narrowing it. */
const MEASURING = /(sld-sandbox|neon-substation-links)/;
const SURFACES = (await readdir(join(ATLAS, 'cartridges')))
  .filter(name => name.endsWith('.js') && MEASURING.test(name))
  .sort()
  .map(name => ({ file: name, version: name.slice(0, 12) }));

console.log(`         ${SURFACES.length} shipped cartridges expose a measuring surface`);
const composedNow = JSON.parse(
  await readFile(join(ATLAS, 'current.json'), 'utf8')).generation;
check('more than one generation is being compared, and the newest is included',
  SURFACES.length >= 4
  && SURFACES.some(entry => entry.file.startsWith(composedNow)),
  SURFACES.map(entry => entry.file).join(', '));

let compared = 0;
for (const surface of SURFACES) {
  const path = join(ATLAS, 'cartridges', surface.file);
  let source = null;
  try { source = await readFile(path, 'utf8'); } catch { /* reported below */ }
  if (source === null) {
    check(`${surface.file}: the shipped cartridge is still on disk`, false,
      'an immutable artefact is missing');
    continue;
  }

  const box = cartridgeContext();
  /* The load THROWS, and that is expected: these cartridges are carried
     engine slots and the V8 engine will not boot under a stub. They
     register their measuring surface on window before they reach the
     engine, which is exactly the "a missing source costs a drawing, never
     the session" discipline the estate already holds. What is NOT
     tolerated is the surface being absent afterwards - that is a version
     silently dropping out of this comparison, so it is a failure below. */
  try { vm.runInContext(source, box, { filename: surface.file }); }
  catch (_) { /* the carried engine will not boot under a stub */ }

  /* Bare first, then with the modules a sibling cartridge supplies.
     ----------------------------------------------------------------------
     Every artefact up to 202609012345 was self-contained and must keep
     being loaded exactly as it shipped, or the comparison stops comparing
     what actually ran. From the generation that moved the computation out
     of the sandbox, a cartridge cannot register its surface without the
     modules the FIRST-loading cartridge now provides.

     Hardcoding that boundary generation would rot. Retrying instead is
     self-adjusting and states the fact plainly: an artefact that needs
     siblings is reported as needing them, and one that does not is never
     given them. */
  let measure = box.window.__GRIDATLAS_NEON_LINKS__?.measure;
  let neededSiblings = false;
  if (typeof measure?.distanceKm !== 'function' && siblingModules) {
    const retry = cartridgeContext();
    vm.createContext(retry);
    try { vm.runInContext(siblingModules, retry, { filename: 'siblings.js' }); }
    catch (_) { /* the surface check below reports the consequence */ }
    try { vm.runInContext(source, retry, { filename: surface.file }); }
    catch (_) { /* the carried engine will not boot under a stub */ }
    const retried = retry.window.__GRIDATLAS_NEON_LINKS__?.measure;
    if (typeof retried?.distanceKm === 'function') {
      measure = retried;
      neededSiblings = true;
      console.log(`  [composed] ${surface.file}: needs modules from a sibling cartridge`);
    }
  }
  void neededSiblings;
  check(`${surface.file} (${surface.version}): exposes its measuring surface`,
    typeof measure?.distanceKm === 'function',
    'a version whose surface cannot be found is not being compared');
  if (typeof measure?.distanceKm !== 'function') continue;

  let agrees = true;
  const disagreements = [];
  for (const [label, aLon, aLat, bLon, bLat] of BATTERY) {
    const mine = geodesy.distanceKm(aLon, aLat, bLon, bLat);
    const theirs = measure.distanceKm(aLon, aLat, bLon, bLat);
    if (mine !== theirs) {
      agrees = false;
      disagreements.push(`${label}: ${theirs} vs ${mine}`);
    }
  }
  check(`${surface.file} (${surface.version}): agrees on all ${BATTERY.length} cases, exactly`,
    agrees, disagreements.join('; '));

  /* Voltage parsing travels with the measurement in these cartridges, and
     it has its own history of being wrong - a 750 V traction supply once
     read as 750 kV. Compared here too, across every version. */
  if (typeof measure.voltagesKv === 'function') {
    const AGREED = [{ voltage: '400000' }, { voltage: '400000;275000' },
      { kv: '132' }, {}, { voltage: 'not a number' }];
    check(`${surface.file} (${surface.version}): reads ordinary voltages identically`,
      AGREED.every(properties =>
        JSON.stringify(measure.voltagesKv(properties))
        === JSON.stringify(geodesy.voltagesKv(properties))));

    /* The low-voltage supplies are where versions are ALLOWED to differ,
       and where the difference must be in one direction only.
       ------------------------------------------------------------------
       Before v9.32 the parser took the number at face value, so a 750 V
       traction supply read as 750 kV and a 415 V works supply as 415 kV -
       voltages that do not exist on this network. v9.32 fixed it. So an
       older version disagreeing here is the fixed bug, not a regression,
       and the test asserts the SHAPE of the disagreement rather than