GLOBALGRID2050 / EXPLORE CODE

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

Electrical Distance Proof and 1 more file

A JavaScript module in the proofs folder of GridAtlas that fetches GB transmission network, transformers, 400kV and 132kV.

561 lines of JavaScript from gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 658 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. Sizing Arithmetic Proof render · gridatlas / tools/proofs/modules/202609012205-sizing-arithmetic.proof.mjs lines 1–222
  2. Electrical Distance Proof geodesy · gridatlas / tools/proofs/modules/202609012245-electrical-distance.proof.mjs lines 1–339

Sizing Arithmetic Proof

A JavaScript module in the proofs folder of GridAtlas that works with fresh finance inputs (`freshFinanceInputs`) (units: MW, kVA, MVA).

rendergridatlas / tools/proofs/modules/202609012205-sizing-arithmetic.proof.mjs · lines 1–222 of 222 · version 2026-09-01 22:05 · Not reached from any entry point (candidate for review) · pattern plain (shared by 5 files)

What it does
It fetches data. Defines 8 functions or classes, including plain, same, check, fresh, slice. Uses libraries node:fs/promises, node:path, node:url, node:vm, node:util. Side effects: changes the web page (DOM); 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 upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Downstream impact
Used directly by 1 file: Local CI (gridatlas).
What it achieves
It is built from the plain step (`plain`), the same step (`same`) and the check step (`check`). The module was lifted out of the single-line diagram (SLD)-sandbox body, so the question that matters is PARITY: on the same inputs, does the module return exactly what the inline arithmetic returned?
Why it matters
Run by Local CI.
Application
gridatlas · tools/proofs/modules · JavaScript module
Uses
node:fs/promises, node:path, node:url, node:vm, node:util
Used by
run by Local CI (script call)
Produces
plain, same, check, fresh, slice, freshFinanceInputs, freshFinanceInputs, pick
Defines here
plain, same, check, fresh, slice, freshFinanceInputs, freshFinanceInputs, pick
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/modules/202609012205-sizing-arithmetic.proof.mjs:1-222 · blob 29cc8de1538b22b91909d28c4779acf7b83fcf32 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Proof for the sizing-arithmetic module.
 *
 * The module was lifted out of the sld-sandbox body, so the question that
 * matters is PARITY: on the same inputs, does the module return exactly
 * what the inline arithmetic returned? The inline copy is read from the
 * last cartridge that carried it (v9.68, 202609012141), the block is
 * evaluated in a realm of its own with a state object and the finance
 * defaults handed in the way the body handed them, and the two are run
 * side by side over a battery of inputs, targets and finance cases. A
 * value that differs anywhere fails here, not on a card.
 *
 *   node tools/proofs/modules/202609012205-sizing-arithmetic.proof.mjs
 */

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

const plain = (value) => JSON.parse(JSON.stringify(value === undefined ? null : value));
const same = (a, b) => isDeepStrictEqual(plain(a), plain(b));

const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = resolve(HERE, '..', '..', '..');
const MODULE = join(REPO, 'atlas', 'modules', '202609012205-sizing-arithmetic.js');
const BODY = join(REPO, 'atlas', 'parts', '202609012045-sld-sandbox-body.js');
/* The last served bytes that carried the arithmetic inline. Pinned: this
   is the record the module must reproduce, and it does not move. */
const LAST_INLINE = join(REPO, 'atlas', 'cartridges', '202609012141-sld-sandbox-v9-8.js');

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 fresh() {
  const box = { window: {}, console, Math, JSON, Number, String, Array, Object,
    Map, Set, Boolean, Error, RegExp };
  box.window.window = box.window;
  vm.createContext(box);
  return box;
}

const moduleSource = await readFile(MODULE, 'utf8');
const body = await readFile(BODY, 'utf8');
const shipped = await readFile(LAST_INLINE, 'utf8');

/* ── the module loads on its own ─────────────────────────────────────── */
console.log('\nit loads, alone, frozen\n');
const box = fresh();
vm.runInContext(moduleSource, box);
const mod = box.window.__GRIDATLAS_MODULES__.sizingArithmetic;
check('registers a frozen surface with the generation it was cut at',
  !!mod && Object.isFrozen(mod) && mod.generation === '202609012205');
check('loading it twice is a no-op', (() => { vm.runInContext(moduleSource, box); return box.window.__GRIDATLAS_MODULES__.sizingArithmetic === mod; })());
for (const name of ['physicalInputs', 'buildStats', 'consistency', 'stringStats', 'centralStats',
  'applyDevelopmentStageDefaults', 'applyMountingBifacial', 'screeningFinance', 'computeStats', 'fitToStatedCapacity', 'financeNumber']) {
  check(`exports ${name}`, typeof mod[name] === 'function');
}
check('the tables are frozen', Object.isFrozen(mod.DEVELOPMENT_STAGES) && Object.isFrozen(mod.DEVELOPMENT_SUCCESS) && Object.isFrozen(mod.BIFACIAL_BY_GCR));
check('no DOM, no fetch, no timers in the module',
  !/\b(document|fetch|setTimeout|setInterval|localStorage|XMLHttpRequest)\b/.test(moduleSource));
/* Comments are stripped first: the note recording the deleted auto-reconciler
   names sld.inputs.z_strings, and that is history, not a read. */
const codeOnly = moduleSource.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
check('the module never reads the body state by name outside the fit it is handed',
  !/\bsld\./.test(codeOnly.replace(/function fitToStatedCapacity[\s\S]*$/, '')) && !/FINANCE_DEFAULTS/.test(codeOnly));

/* ── the inline copy, evaluated as the body evaluated it ─────────────── */
console.log('\nthe last inline copy, evaluated beside the module\n');
function slice(text, from, to, label) {
  const a = text.indexOf(from); if (a < 0) throw new Error(`${label}: start not found`);
  const b = text.indexOf(to, a); if (b < 0) throw new Error(`${label}: end not found`);
  return text.slice(a, b + to.length);
}
const defaultsSrc = slice(shipped, '  const FINANCE_DEFAULTS = Object.freeze({', '  });\n', 'FINANCE_DEFAULTS');
const stateSrc = slice(shipped, '  const sld = {', '  window.__GRIDATLAS_SLD__ = sld;', 'sld').replace('  window.__GRIDATLAS_SLD__ = sld;', '');
const blockSrc = slice(shipped, '  /* ── the sizing arithmetic, carried across unchanged ───', '  sld.fitToStatedCapacity = fitToStatedCapacity;\n', 'block');
check('the shipped cartridge still carries the arithmetic inline (the record this proof reads)', blockSrc.length > 15000 && /function computeCentralStats\(\)/.test(blockSrc));
check('the body no longer carries it inline', !/function computeCentralStats\(\)/.test(body) && /SIZING\.computeStats\(sld\.inputs, sld\.finance, FINANCE_DEFAULTS\)/.test(body));

/* a factory: fresh inline state + functions per call, so runs never share state */
const inlineFactory = vm.runInContext(`(function () {
${defaultsSrc}
  const freshFinanceInputs = () => ({ ...FINANCE_DEFAULTS });
${stateSrc}
${blockSrc}
  return { sld, FINANCE_DEFAULTS, computeSldStats, fitToStatedCapacity, computeScreeningFinance,
    applyDevelopmentStageDefaults, applyMountingBifacial, activePhysicalInputs, consistency,
    DEVELOPMENT_STAGES, DEVELOPMENT_SUCCESS, BIFACIAL_BY_GCR };
})`, fresh());
const inline0 = inlineFactory();
check('the inline copy evaluates and exposes its functions', typeof inline0.computeSldStats === 'function' && typeof inline0.fitToStatedCapacity === 'function');

/* module-side state: the same initial state literal, evaluated in the module's realm */
const stateFactory = vm.runInContext(`(function () {
${defaultsSrc}
  const freshFinanceInputs = () => ({ ...FINANCE_DEFAULTS });
${stateSrc}
  return { sld, FINANCE_DEFAULTS };
})`, box);

check('the three tables are identical', same(mod.DEVELOPMENT_STAGES, inline0.DEVELOPMENT_STAGES) && same(mod.DEVELOPMENT_SUCCESS, inline0.DEVELOPMENT_SUCCESS) && same(mod.BIFACIAL_BY_GCR, inline0.BIFACIAL_BY_GCR));

/* ── the battery ─────────────────────────────────────────────────────── */
console.log('\nvalue for value, over a battery of inputs\n');
const variations = [
  {},
  { mode: 'central' },
  { z_strings: 23 }, { z_strings: 12, y_invs: 20 }, { string_inv_kva: 600 }, { string_inv_kva: 250, string_skid_mva: 4.4 },
  { b_cols: 1, s_subs: 1 }, { b_cols: 12, s_subs: 3 }, { mod_wp: 720, mod_l: 2.4, mod_w: 1.13 }, { gcr: 0.35 }, { gcr: 0.75, gross_factor: 1.5 },
  { dc_ac_ratio: 1.0 }, { dc_ac_ratio: 1.45 }, { mod_wp: 0 }, { x_mods: 0 },
  { mode: 'central', inv_per_mv_c: 2 }, { mode: 'central', inv_per_mv_c: 3, central_skid_mva_c: 8.8 }, { mode: 'central', inv_ac_mw_c: 12, inv_dc_mw_c: 14.4 },
  { mode: 'central', rings_c: 1, mv_per_ring_c: 1 }, { mode: 'central', rings_c: 9, mv_per_ring_c: 12 }, { mode: 'central', mod_wp_c: 0 }, { mode: 'central', x_mods_c: 0 },
  { mode: 'central', gcr_c: 0.35 }, { mode: 'central', inv_ac_mw_c: 0 },
];
const financeCases = [
  {}, { price: 80, other: 5 }, { yield: 1100, bifacial: 8, losses: 3, deg: 0.5 }, { opex: 30000, epc_ex: 0.35, modules: 0.12 },
  { flood: true, flood_rate: 0.05 }, { bess_mw: 20, bess_mwh: 40, bess_capex: 300000, bess_cycles: 365, bess_spread: 60, bess_eff: 85 },
  { dev_stage: '0.035', dev_cost_mw: 0.035, dev_success: 30 }, { loss_dc_string: 1, loss_lv_dc: 1, loss_lv_ac: 1, loss_tx: 1, loss_other: 1 },
  { fixed_capex: 0, cont: 0 }, { yield: 'abc', price: null },
];
let compared = 0; let diffs = 0;
for (const v of variations) {
  const a = inlineFactory();
  const b = stateFactory();
  Object.assign(a.sld.inputs, v); Object.assign(b.sld.inputs, v);
  for (const fc of financeCases) {
    const mode = a.sld.inputs.mode;
    Object.assign(a.sld.finance[mode], fc); Object.assign(b.sld.finance[mode], fc);
    const sa = a.computeSldStats();
    const sb = mod.computeStats(b.sld.inputs, b.sld.finance, b.FINANCE_DEFAULTS);
    compared += 1;
    if (!same(sa, sb)) { diffs += 1; if (diffs < 4) console.log('    differs on', JSON.stringify(v), JSON.stringify(fc), '\n     inline', JSON.stringify(plain(sa)).slice(0, 300), '\n     module', JSON.stringify(plain(sb)).slice(0, 300)); }
  }
}
check(`computeStats agrees with the inline copy on ${compared} input/finance combinations`, diffs === 0, `${diffs} differ`);

/* consistency and physical inputs directly */
{
  let d = 0;
  for (const v of variations) {
    const a = inlineFactory(); const b = stateFactory();
    Object.assign(a.sld.inputs, v); Object.assign(b.sld.inputs, v);
    if (!same(a.activePhysicalInputs(), mod.physicalInputs(b.sld.inputs))) d += 1;
    const s = a.computeSldStats();
    if (!same(a.consistency(a.sld.inputs, s), mod.consistency(b.sld.inputs, s))) d += 1;
  }
  check('physicalInputs and consistency agree on every variation', d === 0, `${d} differ`);
}

/* finance with a null inputs object falls back to the defaults, as the body's did */
{
  const a = inlineFactory(); const b = stateFactory();
  const s = a.computeSldStats();
  check('screeningFinance with no inputs uses the defaults, as the inline copy did',
    same(a.computeScreeningFinance(null, s), mod.screeningFinance(null, s, { fallbackMode: b.sld.inputs.mode, defaults: b.FINANCE_DEFAULTS })));
  const bare = { dc_mwp: 50, ac_mw: 40 };
  a.sld.inputs.mode = 'central';
  check('screeningFinance with stats lacking a mode falls back to the state mode',
    same(a.computeScreeningFinance(a.sld.finance.central, bare), mod.screeningFinance(b.sld.finance.central, bare, { fallbackMode: 'central', defaults: b.FINANCE_DEFAULTS })));
}

/* the fit: targets across the register's range, both bases, both modes */
{
  let d = 0; let runs = 0;
  for (const mode of ['string', 'central']) {
    for (const basis of ['ac', 'dc', 'unstated']) {
      for (const target of [1, 2.5, 5, 9.9, 30, 49.9, 50, 100, 249, 600, 0, -1, NaN]) {
        const a = inlineFactory(); const b = stateFactory();
        a.sld.inputs.mode = mode; b.sld.inputs.mode = mode;
        a.sld.targetMw = target; b.sld.targetMw = target;
        a.sld.targetBasis = basis; b.sld.targetBasis = basis;
        a.fitToStatedCapacity();
        mod.fitToStatedCapacity(b.sld, () => mod.computeStats(b.sld.inputs, b.sld.finance, b.FINANCE_DEFAULTS));
        runs += 1;
        const pick = (s) => ({ inputs: s.inputs, residual: s.fitResidualPct, quantum: s.fitQuantumMw });
        if (!same(pick(a.sld), pick(b.sld))) { d += 1; if (d < 4) console.log('    fit differs', mode, basis, target, JSON.stringify(plain(pick(a.sld))).slice(0, 200), JSON.stringify(plain(pick(b.sld))).slice(0, 200)); }
      }
    }
  }
  check(`fitToStatedCapacity lands on the same layout, residual and quantum in ${runs} fits`, d === 0, `${d} differ`);
}

/* the stage and mounting handlers */
{
  let d = 0;
  for (const stage of ['0.003', '0.015', '0.035', '0.055', '0.070', '0.080', '0.100', '0.5', 'x', 0.07]) {
    const fa = { dev_stage: 'old', dev_cost_mw: 9, dev_success: 9 }; const fb = { ...fa };
    const ra = inline0.applyDevelopmentStageDefaults(fa, stage); const rb = mod.applyDevelopmentStageDefaults(fb, stage);
    if (ra !== rb || !same(fa, fb)) d += 1;
  }
  check('applyDevelopmentStageDefaults agrees, including on stages that do not exist', d === 0, `${d} differ`);
  let e = 0;
  for (const [mode, gcr] of [['string', 0.35], ['string', '0.45'], ['central', 0.75], ['central', 0.5], ['nowhere', 0.35], ['string', 'abc']]) {
    const a = inlineFactory(); const b = stateFactory();
    const ra = a.applyMountingBifacial(mode, gcr); const rb = mod.applyMountingBifacial(b.sld.finance, mode, gcr);
    if (ra !== rb || !same(a.sld.finance, b.sld.finance)) e += 1;
  }
  check('applyMountingBifacial agrees, including on a mode that does not exist and a GCR with no preset', e === 0, `${e} differ`);
}

/* ── the body delegates, and fails by name without the module ────────── */
console.log('\nthe body delegates\n');
check('the body binds the module and throws by name if it is absent',
  /const SIZING = \(window\.__GRIDATLAS_MODULES__ \|\| \{\}\)\.sizingArithmetic;/.test(body)
  && /throw new Error\('sld-sandbox: the sizing-arithmetic module is not composed'\)/.test(body));
for (const name of ['activePhysicalInputs', 'applyDevelopmentStageDefaults', 'applyMountingBifacial', 'computeScreeningFinance', 'fitToStatedCapacity']) {
  check(`the body keeps ${name} as a delegation`, new RegExp(`function ${name}\\([^)]*\\) \\{[^}]*SIZING\\.`).test(body));
}
check('the body still publishes computeFinance, applyDevelopmentStage, applyMountingBifacial and fitToStatedCapacity on the state',
  ['sld.computeFinance = computeScreeningFinance;', 'sld.applyDevelopmentStage = applyDevelopmentStageDefaults;', 'sld.applyMountingBifacial = applyMountingBifacial;', 'sld.fitToStatedCapacity = fitToStatedCapacity;'].every(s => body.includes(s)));
check('the body no longer defines the tables', !/const DEVELOPMENT_STAGES = Object\.freeze/.test(body) && !/const BIFACIAL_BY_GCR/.test(body));

console.log(`\n${passed}/${passed + failures.length} passed`);
if (failures.length) { console.log('\nFAILED:'); for (const f of failures) console.log('  - ' + f); process.exit(1); }

Electrical Distance Proof

A JavaScript module in the proofs folder of GridAtlas that fetches GB transmission network, transformers, 400kV and 132kV.

geodesygridatlas / tools/proofs/modules/202609012245-electrical-distance.proof.mjs · lines 1–339 of 339 · version 2026-09-01 22:45 · Not reached from any entry point (candidate for review) · pattern fakeIndex (shared by 2 files)

What it does
It fetches GB transmission network, transformers, 400kV and 132kV. Defines check, fakeIndex, N. Uses libraries node:fs, node:path, node:url. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: transformers, 400kV, 132kV.
Inputs & outputs
In: JSON file gb-transmission-network.v1.json. Voltage levels named: 400kV, 132kV.
Downstream impact
Used directly by 1 file: Local CI (gridatlas).
What it achieves
It is built from the check step (`check`) and the fake index helper (`fakeIndex`). Run against the REAL published payload, not a fixture. Its code works with 400 kV and 132 kV.
Why it matters
Run by Local CI.
Application
gridatlas · tools/proofs/modules · JavaScript module
Uses
node:fs, node:path, node:url
Used by
run by Local CI (script call)
Produces
check, fakeIndex, N
Defines here
check, fakeIndex, N
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/modules/202609012245-electrical-distance.proof.mjs:1-339 · blob c4ea12943c0f80ed9bd61089a7b86aad0cc238f1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Proof for the electrical-distance module.
 *
 * Run against the REAL published payload, not a fixture. A fixture proves
 * the code agrees with a shape I wrote, and the defect class this estate
 * keeps finding is code agreeing with itself. The counts below were read
 * off the product by survey before this file was written:
 *
 *   921 sites, 2,679 nodes, 1,392 circuits, 1,472 transformers,
 *   2,230 planned changes; 649 nodes publish a null voltage_kv and
 *   voltage_consistent_with_site is false on roughly a quarter of them;
 *   voltage_ratio_kv is published on 140 of 1,472 transformers; and
 *   NO field anywhere in either product expresses headroom, spare
 *   capacity or availability.
 *
 * A skip is not a pass: if the sibling data-grid-gb checkout is absent
 * this proof FAILS. It does not quietly report success on the half of
 * itself it could still run.
 *
 *   node tools/proofs/modules/202609012245-electrical-distance.proof.mjs
 */
import { readFileSync, existsSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '..', '..', '..');
const PRODUCT = resolve(ROOT, '..', 'data-grid-gb', 'derived', 'gb-transmission-network.v1.json');

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

/* ── load the two modules into a window, as the page does ───────────── */
const TOPOLOGY = process.env.GRIDATLAS_TOPOLOGY_MODULE
  || 'atlas/modules/202609012245-network-topology.js';
const DISTANCE = 'atlas/modules/202609012245-electrical-distance.js';

const window = { __GRIDATLAS_MODULES__: {} };
for (const rel of [TOPOLOGY, DISTANCE]) {
  const path = join(ROOT, rel);
  if (!existsSync(path)) { console.error(`missing module: ${rel}`); process.exit(1); }
  new Function('window', readFileSync(path, 'utf8'))(window);
}
const NS = window.__GRIDATLAS_MODULES__;
const topology = NS.networkTopology;
const distance = NS.electricalDistance;

console.log('\nthe module is what it says it is\n');

check('both modules registered', !!topology && !!distance);
check('the distance module declares the graph contract it requires',
  distance.requires === 'gridatlas.module.network-topology.graph.v1');
check('it says a hop is not a distance', /not a distance/i.test(distance.not_a_distance));
check('it says a path is not a capacity', /says nothing about whether/i.test(distance.not_a_capacity));

/* The structural discipline: no arithmetic over the impedance fields.
   Carrying a published parameter is publishing; adding them is the first
   line of a load flow, and a load flow needs a declared model, base
   values, taps, generation and load assumptions, contingencies and
   validation against a trusted solver - none of which are in this file. */
const source = readFileSync(join(ROOT, DISTANCE), 'utf8');
const codeOnly = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
check('the module contains no impedance arithmetic',
  !/(r_pct|x_pct|b_pct)\w*\s*[+\-*/]/.test(codeOnly)
  && !/[+\-*/]\s*\w*(r_pct|x_pct|b_pct)/.test(codeOnly));
check('the module never reduces or sums a parameter list',
  !/parameters[\s\S]{0,80}\.reduce\(/.test(codeOnly));
check('it never fetches and never renders',
  !/\b(fetch|document|innerHTML|XMLHttpRequest)\b/.test(codeOnly));
check('it never decodes a voltage from a node code',
  !/voltage_digit|charAt|\.slice\(4/.test(codeOnly));
/* Not "the word never appears" - the whole point of the disclaimers is to
   use those words in order to deny them, and a check that bans the word
   outright is a check that gets the denial deleted rather than the claim.
   What must never exist is an ASSERTION: a field, variable or key naming
   headroom. The words are permitted only inside the NOT_A_* constants. */
const denials = (codeOnly.match(/const NOT_A_[A-Z_]+\s*=[\s\S]*?;/g) || []).join('\n');
const outsideDenials = codeOnly.split(/const NOT_A_[A-Z_]+\s*=[\s\S]*?;/).join(' ');
check('the denials do deny headroom rather than staying silent about it',
  /spare/i.test(denials) && /says nothing about whether/i.test(denials));
check('nothing outside the denials speaks of headroom, spare or availability',
  !/headroom|spare|available/i.test(outsideDenials));
check('no key or identifier in the module names headroom',
  !/\b\w*(headroom|spare_|available_)\w*\b/i.test(codeOnly));

/* ── behaviour, on a graph built by hand for the edge cases ─────────── */
console.log('\nthe rule that only a transformer may change voltage\n');

function fakeIndex(nodes, edges, sites) {
  const byNode = new Map();
  for (const e of edges) {
    for (const [near, far] of [['node_1', 'node_2'], ['node_2', 'node_1']]) {
      const n = e.row[near];
      if (!byNode.has(n)) byNode.set(n, []);
      byNode.get(n).push({ kind: e.kind, row: e.row, near, far });
    }
  }
  return {
    site: (key) => sites.find(s => s.code === String(key).toUpperCase()) || null,
    graph: () => ({
      schema: 'gridatlas.module.network-topology.graph.v1',
      has: (n) => nodes.some(x => x.node === n),
      nodeVoltageKv: (n) => {
        const node = nodes.find(x => x.node === n);
        if (!node || node.voltage_consistent_with_site !== true) return null;
        return Number.isFinite(node.voltage_kv) ? node.voltage_kv : null;
      },
      nodeSiteCode: (n) => (nodes.find(x => x.node === n) || {}).site_code || null,
      edgesAt: (n) => (byNode.get(n) || []).filter(e => e.kind !== 'planned_change'),
      nodesOfSite: (c) => nodes.filter(x => x.site_code === c).map(x => x.node).sort(),
      siteByCode: (c) => sites.find(s => s.code === c) || null,
      ratingsOf: (row) => (Number.isFinite(row.winter_mva) ? { winter: row.winter_mva } : null),
      parametersOf: (row) => (Number.isFinite(row.x_pct_100mva) ? { x_pct: row.x_pct_100mva } : null)
    })
  };
}

const N = (node, site_code, voltage_kv, ok = true) =>
  ({ node, site_code, voltage_kv, voltage_consistent_with_site: ok });

/* A: two 400 kV nodes joined by a circuit - one legal hop. */
{
  const idx = fakeIndex(
    [N('AAA4-', 'AAA', 400), N('BBB4-', 'BBB', 400)],
    [{ kind: 'circuit', row: { node_1: 'AAA4-', node_2: 'BBB4-', winter_mva: 3000, x_pct_100mva: 1.2 } }],
    [{ code: 'AAA', name: 'ALPHA' }, { code: 'BBB', name: 'BETA' }]);
  const r = distance.between(idx, 'AAA', 'BBB');
  check('a circuit between two 400 kV nodes is one hop', r.reached === true && r.hops === 1);
  check('the hop names both nodes and both sites',
    r.path[0].from_node === 'AAA4-' && r.path[0].to_site_code === 'BBB');
  check('the hop carries the published rating and parameter, unaltered',
    r.path[0].ratings_mva.winter === 3000 && r.path[0].parameters_pct_100mva.x_pct === 1.2);
  check('no voltage changed and no transformer was crossed',
    r.voltage_changes === 0 && r.transformers_crossed === 0);
}

/* B: a CIRCUIT whose two ends declare different voltages - refused. */
{
  const idx = fakeIndex(
    [N('AAA4-', 'AAA', 400), N('BBB1-', 'BBB', 132)],
    [{ kind: 'circuit', row: { node_1: 'AAA4-', node_2: 'BBB1-', winter_mva: 100 } }],
    [{ code: 'AAA', name: 'ALPHA' }, { code: 'BBB', name: 'BETA' }]);
  const r = distance.between(idx, 'AAA', 'BBB');
  check('a circuit that appears to change voltage is NOT walked', r.reached === false);
  check('the refusal is recorded, not swallowed',
    r.refusals.length === 1 && /only a transformer may change voltage/.test(r.refusals[0].reason));
  check('the refusal names both voltages it saw',
    /400 kV and 132 kV/.test(r.refusals[0].reason));
}

/* C: the SAME voltage change, across a transformer - legal and named. */
{
  const idx = fakeIndex(
    [N('AAA4-', 'AAA', 400), N('AAA1-', 'AAA', 132), N('BBB1-', 'BBB', 132)],
    [{ kind: 'transformer', row: { node_1: 'AAA4-', node_2: 'AAA1-', rating_mva: 240, voltage_ratio_kv: '400/132', x_pct_100mva: 24.7 } },
     { kind: 'circuit', row: { node_1: 'AAA1-', node_2: 'BBB1-', winter_mva: 200 } }],
    [{ code: 'AAA', name: 'ALPHA' }, { code: 'BBB', name: 'BETA' }]);
  const r = distance.between(idx, 'AAA', 'BBB', { voltageKv: 400 });
  check('from a 400 kV node the path reaches a 132 kV site through the transformer',
    r.reached === true && r.hops === 2);
  check('the transformer is named as the thing that changed the voltage',
    r.path[0].kind === 'transformer' && r.path[0].voltage_changed === true
    && r.transformers_crossed === 1 && r.voltage_changes === 1);
  check('the transformer carries its PUBLISHED ratio, not a reconstructed one',
    r.path[0].voltage_ratio_kv === '400/132');
  check('the transformer carries its own rating field',
    r.path[0].transformer_rating_mva === 240);
}

/* D: a transformer with no published ratio reports null, never a guess. */
{
  const idx = fakeIndex(
    [N('AAA4-', 'AAA', 400), N('BBB1-', 'BBB', 132)],
    [{ kind: 'transformer', row: { node_1: 'AAA4-', node_2: 'BBB1-', rating_mva: 120 } }],
    [{ code: 'AAA', name: 'ALPHA' }, { code: 'BBB', name: 'BETA' }]);
  const r = distance.between(idx, 'AAA', 'BBB');
  check('an unpublished voltage ratio is null, not reconstructed from the nodes',
    r.reached === true && r.path[0].voltage_ratio_kv === null
    && r.path[0].from_voltage_kv === 400 && r.path[0].to_voltage_kv === 132);
}

/* E: an UNDECLARED voltage is not a voltage change. */
{
  const idx = fakeIndex(
    [N('AAA4-', 'AAA', 400), N('BBB2-', 'BBB', 275, false)],
    [{ kind: 'circuit', row: { node_1: 'AAA4-', node_2: 'BBB2-', winter_mva: 500 } }],
    [{ code: 'AAA', name: 'ALPHA' }, { code: 'BBB', name: 'BETA' }]);
  const r = distance.between(idx, 'AAA', 'BBB');
  check('a node whose site does not vouch for its voltage is undeclared, not 275',
    r.reached === true && r.path[0].to_voltage_kv === null);
  check('an undeclared end is not treated as a voltage change',
    r.path[0].voltage_changed === false && r.refusals.length === 0);
}

/* F: planned changes are not paths. */
{
  const idx = fakeIndex(
    [N('AAA4-', 'AAA', 400), N('BBB4-', 'BBB', 400)],
    [{ kind: 'planned_change', row: { node_1: 'AAA4-', node_2: 'BBB4-', year: '2030', status: 'Addition' } }],
    [{ code: 'AAA', name: 'ALPHA' }, { code: 'BBB', name: 'BETA' }]);
  const r = distance.between(idx, 'AAA', 'BBB');
  check('a circuit published for 2030 is not a path a current can take today',
    r.reached === false);
}

/* G: hop limits and unknown sites fail closed. */
{
  const idx = fakeIndex([N('AAA4-', 'AAA', 400)], [], [{ code: 'AAA', name: 'ALPHA' }]);
  check('an unknown site is null, not an empty answer', distance.between(idx, 'AAA', 'ZZZ') === null);
  check('an index without a graph is refused', distance.between({ site: () => ({}) }, 'AAA', 'AAA') === null);
  const same = distance.between(idx, 'AAA', 'AAA');
  check('the same site is zero hops and says so', same.reached === true && same.hops === 0);
}

/* ── the real payload ────────────────────────────────────────────────── */
console.log('\nthe published network, 921 sites and 2,679 nodes\n');

if (!existsSync(PRODUCT)) {
  console.error(`\nFAILED: the published product is not at ${PRODUCT}.`);
  console.error('A skip is not a pass. Check out Ventusltd/data-grid-gb beside this');
  console.error('repository; this proof does not report success on half of itself.');
  process.exit(1);
}

const product = JSON.parse(readFileSync(PRODUCT, 'utf8'));
const index = topology.index(product);
check('the topology module accepts the published schema', !!index);
check('the index hands out a graph', typeof index.graph === 'function'
  && index.graph().schema === 'gridatlas.module.network-topology.graph.v1');

const graph = index.graph();
check('the graph reports the published node count', index.counts.nodes === 2679);
check('the graph reports the published site count', index.counts.sites === 921);

/* The one-hop view and the traversal must agree about the first hop. A
   disagreement here is the two-implementations bug this estate has paid
   for once already, so it is asserted rather than assumed. */
const WB = index.at('WBUR', { voltageKv: 400 });
check('West Burton resolves at 400 kV', !!WB && WB.counts.nodes > 0);
const oneHopSites = new Set((WB.neighbours || []).map(n => n.code).filter(Boolean));
const walked = distance.within(index, 'WBUR', { hops: 1, voltageKv: 400 });
check('the traversal finds neighbours at one hop', walked && walked.sites.length > 0);
check('every site the traversal reaches in one hop is a site the one-hop view already named',
  walked.sites.every(s => oneHopSites.size === 0 || oneHopSites.has(s.code)),
  `walked=${walked.sites.map(s => s.code).join(',')} view=${[...oneHopSites].join(',')}`);
check('every one-hop site is reported at exactly one hop',
  walked.sites.every(s => s.hops === 1));

const two = distance.within(index, 'WBUR', { hops: 2, voltageKv: 400 });
check('two hops reaches at least as many sites as one', two.sites.length >= walked.sites.length);
check('the hop at which each site was first reached is recorded',
  two.sites.every(s => s.hops === 1 || s.hops === 2));
/* Same distinction in the answer: no KEY may name headroom, and the words
   may appear only inside the two denial fields the answer carries. */
check('no key in the neighbourhood answer names headroom or spare capacity',
  !Object.keys(two).some(k => /headroom|spare|available/i.test(k))
  && !two.sites.some(s => Object.keys(s).some(k => /headroom|spare|available/i.test(k))));
check('the only mention of spare capacity in the answer is the denial of it', (() => {
  const stripped = JSON.stringify(Object.assign({}, two,
    { not_a_capacity: '', not_a_distance: '' }));
  return !/headroom|spare|available/i.test(stripped);
})());
check('the neighbourhood carries its own refusal to imply capacity',
  /says nothing about whether/i.test(two.not_a_capacity));

/* A real path between two real sites, every hop citable. */
const target = two.sites.find(s => s.hops === 2) || two.sites[0];
if (target) {
  const path = distance.between(index, 'WBUR', target.code, { voltageKv: 400, maxHops: 4 });
  check(`a path from WBUR to ${target.code} is found and is citable`,
    path.reached === true && path.path.length > 0);
  check('every hop names two real nodes',
    path.path.every(h => graph.has(h.from_node) && graph.has(h.to_node)));
  check('every hop is a circuit or a transformer, never a planned change',
    path.path.every(h => h.kind === 'circuit' || h.kind === 'transformer'));
  check('every voltage change on the path is across a transformer',
    path.path.every(h => !h.voltage_changed || h.kind === 'transformer'));
  check('the path carries no summed impedance anywhere in its answer',
    !('total_impedance' in path) && !('x_total' in path)
    && !JSON.stringify(path).includes('"impedance_sum"'));
} else {
  check('a real path was available to test', false, 'no neighbour found');
}

/* ── the successor answers exactly as the incumbent ──────────────────
   202609012245-network-topology.js was produced FROM the bytes of
   202609012145 by insertion only, and this is the assertion that says so
   behaviourally rather than by inspection. Both are loaded, both index
   the same 10 MB payload, and at() is compared value for value across
   every site the product publishes. A successor that answered even one
   site differently would be a silent change to a shipped computation. */
console.log('\nthe successor is the incumbent, plus a handle\n');

const INCUMBENT = 'atlas/modules/202609012145-network-topology.js';
if (!existsSync(join(ROOT, INCUMBENT))) {
  check('the incumbent module is present to compare against', false, INCUMBENT);
} else {
  const w2 = { __GRIDATLAS_MODULES__: {} };
  new Function('window', readFileSync(join(ROOT, INCUMBENT), 'utf8'))(w2);
  const old = w2.__GRIDATLAS_MODULES__.networkTopology;
  const oldIndex = old.index(product);

  check('the incumbent has no graph handle, and the successor does',
    typeof oldIndex.graph !== 'function' && typeof index.graph === 'function');
  check('both index the same counts', JSON.stringify(oldIndex.counts) === JSON.stringify(index.counts));

  let compared = 0;
  const differed = [];
  for (const site of product.sites) {
    const a = JSON.stringify(oldIndex.at(site.code));
    const b = JSON.stringify(index.at(site.code));
    compared += 1;
    if (a !== b) differed.push(site.code);
    if (differed.length > 3) break;
  }
  check(`at() is identical on all ${compared} published sites`,
    differed.length === 0, differed.join(','));
  check('every published site was actually compared, not a sample',
    compared === product.sites.length);
}

/* The whole point: electrical distance and geographic distance are
   different questions, and the module must not be quietly reproducing
   the geographic one. */
check('the answer never carries a kilometre figure',
  !/_km\b/.test(JSON.stringify(distance.within(index, 'WBUR', { hops: 1 }))));

console.log(`\n${passed}/${passed + failures.length} checks passed`);
if (failures.length) {
  console.log('FAILURES');
  for (const f of failures) console.log(`  ${f}`);
  process.exit(1);
}
console.log('a hop is a published circuit, a voltage changes only across a named');
console.log('transformer, and nothing here is a distance or a capacity.');