GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / energy-transition-simulator/202609280014/mod/engine

Cmd Grammar and 4 more files

A JavaScript module in the engine folder of GlobalGrid2050 covering solar, overhead lines (OHL), cables and the Renewable Energy Planning Database (REPD) register.

648 lines of JavaScript from globalgrid2050, in 5 files. Topic: Electricity markets and data pipelines. Section 844 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. Cmd Derive transform · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-derive.mjs lines 1–101
  2. Cmd Grammar Earth ingest · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-grammar-earth.mjs lines 1–62
  3. Cmd Grammar Plant ingest · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-grammar-plant.mjs lines 1–60
  4. Cmd Grammar Senses ingest · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-grammar-senses.mjs lines 1–25
  5. Cmd Grammar ingest · globalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-grammar.mjs lines 1–400

Cmd Derive

A JavaScript module in the engine folder of GlobalGrid2050 that works with cables and 33kV.

Set aside from the main view: 97% of its lines are the same as solar-design-studio/202609271740-site-world/world/cmd-derive.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Cmd Derive; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.974 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/cmd-derive.mjs:1-99 8b3cb3dbf647d2f4b7fcf7f94d857d723e21e37b
  • sha256 e7dd3329efcff8ad1992668aa38ae511c605c0fcf82e4eeeed5d058985190995
  • target sha256 c727fc45681064162e5a034c5897f23d2a9deb02a8b89702f2ea62f1bba6b49c
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

transformglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-derive.mjs · lines 1–101 of 101 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern stringLoops (shared by 3 files)

What it does
It calculates cables and 33kV. Defines 12 functions or classes, including noonSun, rowShade, formationOf, cableFor, bendOf.
Why it exists in the grid workflow
Domain stage sub33kv_design (voltage levels 33kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, 33kV.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Cmd Model (globalgrid2050).
What it achieves
It is built from the noon sun helper (`noonSun`), the row shade helper (`rowShade`) and the formation of helper (`formationOf`). The quantities a typed command changes, worked out from its inputs. Its code works with 33 kV.
Why it matters
Imported by Cmd Model.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
Module Catalogue (import)
Used by
imported by Cmd Model (import)
Produces
noonSun, rowShade, formationOf, cableFor, bendOf, BED_M, trenchOf, shoelace, LOOP_ASSUMED, stringLoops, coldVoc, soilEffect
Defines here
noonSun, rowShade, formationOf, cableFor, bendOf, m, trenchOf, shoelace, stringLoops, coldVoc, cap, soilEffect
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/cmd-derive.mjs:1-101 · blob 1ab06169118326a0b49d9c1e4a0218dd98b36e80 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 cmd-derive.mjs at v12 commit 3adcee9 (file last changed 8903e78). Modular star family: public #147688 noonSun.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// cmd-derive.mjs: the quantities a typed command changes, worked out from its inputs. Pure: no DOM.
//   sun and shade    noon sun height at the solstices for the site latitude; the shadow a row casts on level ground
//   cable            outside diameter and bend radius from data/cables.json (installation and final multiples of OD)
//   trench           the cable formation's span and height, the cover left over it, and whether it fits the width
//   string loops     the area enclosed between the + and - conductors of one string, standard and leapfrog wiring,
//                    by the closed-path winding area (shoelace), the text engine's method (closed-path-winding-area.v1)
// Illustrative: conductor routes on the table are ASSUMED (named below); nothing here is a design for any site.

import { coldVocOf } from './module-catalogue.mjs';

const DEG = Math.PI / 180, TILT_AXIS = 23.44;

/** Noon sun elevation (degrees) on the winter and summer solstices and the equinox, at latitude latDeg. */
export function noonSun(latDeg) {
  return { winter: 90 - latDeg - TILT_AXIS, equinox: 90 - latDeg, summer: Math.min(90, 90 - latDeg + TILT_AXIS) };
}

/** Shadow of a south row on level ground at noon: { shadowM, gapM, shaded } for a table of rise and plan depth. */
export function rowShade({ rise, depth, pitch, elevDeg }) {
  const shadowM = elevDeg > 0 ? rise / Math.tan(elevDeg * DEG) : Infinity, gapM = pitch - depth;
  return { shadowM, gapM, shaded: shadowM > gapM + 1e-9 };
}

// The formation of three single-core cables of outside diameter od (m): trefoil touching, or flat spaced one OD apart.
export function formationOf(formation, od) {
  return formation === 'flat' ? { span: 5 * od, height: od, centres: [[-2 * od, od / 2], [0, od / 2], [2 * od, od / 2]] }
    : { span: 2 * od, height: od * (1 + Math.sqrt(3) / 2), centres: [[-od / 2, od / 2], [od / 2, od / 2], [0, od / 2 + od * Math.sqrt(3) / 2]] };
}

/** The cable from the catalogue (data/cables.json) for a size and conductor, 33 kV single core. */
export function cableFor(catalogue, size, metal = 'al') {
  const list = catalogue?.cables || [];
  const want = metal === 'cu' ? new RegExp(`^33kv-1c-cu-xlpe-${size}(-|$)`) : new RegExp(`^33kv-1c-al-xlpe-${size}$`);
  const c = list.find(x => want.test(x.id));
  return c ? { id: c.id, od: c.od_mm / 1000, odMm: c.od_mm, armoured: /armoured/.test(c.id), status: c.status || 'catalogue' } : null;
}

/** Bend radius at the cable's inner edge: installation and final multiples of OD from the catalogue's rules. */
export function bendOf(catalogue, cable) {
  if (!cable) return null;
  const rules = (catalogue?.rules || []).filter(x => x.voltage_kv === 33 && x.construction === (cable.armoured ? 'single_core_armoured' : 'single_core_unarmoured'));
  const m = when => rules.find(x => x.when === when)?.multiple_of_od ?? null;
  const inst = m('installation'), fin = m('final');
  return { installM: inst ? inst * cable.od : null, finalM: fin ? fin * cable.od : null, installX: inst, finalX: fin,
    source: rules.find(x => x.when === 'installation')?.source || 'no rule in the catalogue' };
}

export const BED_M = 0.075, SIDE_M = 0.1, AGRI_COVER_M = 0.91; // bedding under the cables; side clearance each side (assumed)

/** Trench with its cables: the cover left to the top cable, and whether the formation fits the width. */
export function trenchOf({ depth, width, formation, od }) {
  const f = formationOf(formation, od), cover = depth - BED_M - f.height;
  return { ...f, cover, fits: width >= f.span + 2 * SIDE_M - 1e-9, needWidth: f.span + 2 * SIDE_M, agriShort: AGRI_COVER_M - cover };
}

/** Signed area of a closed polyline (shoelace). */
export function shoelace(pts) {
  let a = 0;
  for (let i = 0; i < pts.length; i++) { const [x0, y0] = pts[i], [x1, y1] = pts[(i + 1) % pts.length]; a += x0 * y1 - x1 * y0; }
  return a / 2;
}

// ASSUMED routes on one tier of a portrait table (u along the row, w up the module from its lower edge):
//   junction boxes 0.15 of the module length below the top edge; module leads either side of the box 0.06 m apart;
//   the standard string's return lead clipped to the lower purlin, 0.25 of the module length up.
export const LOOP_ASSUMED = Object.freeze({ jboxFromTop: 0.15, leadHalfGapM: 0.06, purlinAt: 0.25 });

/** The loop between + and - of one string: { standard, leapfrog } each { poly, area } in m and m². */
export function stringLoops({ mps, moduleShortM = 1.134, moduleLongM = 2.384, moduleGapM = 0.02 }, a = LOOP_ASSUMED) {
  const pitch = moduleShortM + moduleGapM, x = i => (i + 0.5) * pitch, L = mps * pitch - moduleGapM;
  const yj = moduleLongM * (1 - a.jboxFromTop), yr = moduleLongM * a.purlinAt, d = a.leadHalfGapM;
  // Standard: out along the boxes from the first module to the last, home along the purlin.
  const standard = [[0, yj], ...Array.from({ length: mps }, (_, i) => [x(i), yj]), [L, yj], [L, yr], [0, yr]];
  // Leapfrog: out on every other module, back on the ones skipped; both ends at the start of the row.
  const odd = Array.from({ length: mps }, (_, i) => i).filter(i => i % 2 === 0), even = Array.from({ length: mps }, (_, i) => i).filter(i => i % 2);
  const leapfrog = [[0, yj + d], ...odd.map(i => [x(i), yj + d]), [L, yj + d], [L, yj - d], ...even.reverse().map(i => [x(i), yj - d]), [0, yj - d]];
  return { standard: { poly: standard, area: Math.abs(shoelace(standard)) }, leapfrog: { poly: leapfrog, area: Math.abs(shoelace(leapfrog)) }, lengthM: L };
}

/** Sizing cold open-circuit voltage of one module (the stricter of the coldest cell and Voc x 1.15) and of a string of n (V). */
export function coldVoc({ voc, coeff = -0.0025, minC = -10 }, n) {
  const v = coldVocOf({ voc, coeffPctPerK: coeff * 100, tC: minC }).v;
  return { module: v, string: v * n, most: Math.floor(1500 / v) };
}

const cap = s => String(s || '').toLowerCase().replace(/\b\w/g, c => c.toUpperCase());
/** The ground at a point (layers/ground.mjs at()) in words, and what it means for the trench. */
export function soilEffect(here) {
  const head = 'Soil type from BGS 1:625k';
  if (!here || (here.superficial === null && here.bedrock === null)) return `${head}: not in this site's ground file; trench in normal ground assumed.`;
  const sup = here.superficial || [], rock = (here.bedrock || [])[0];
  const soft = sup.find(s => /alluvi|peat|tidal|lacustrine|marine|clay|silt/i.test(`${s.name} ${s.lithology || ''}`));
  const rockWords = rock ? `bedrock ${cap(rock.name)} (${String(rock.lithology || 'lithology not given').toLowerCase()})` : 'no bedrock mapped here';
  if (soft) return `${head}: ${cap(soft.name)} over ${rockWords} → trench option alluvium / soft wet ground (support or batter, dewatering).`;
  if (sup.length) return `${head}: ${cap(sup[0].name)} over ${rockWords} → trench in normal ground.`;
  const hard = rock && /limestone|sandstone|granite|basalt|dolerite|chalk/i.test(rock.lithology || '');
  return `${head}: no superficial deposit mapped (${here.superficial === null ? 'not imported' : 'queried, none'}); ${rockWords} → trench in normal ground`
    + `${hard ? '; rock may lie near the surface, allow for breaking out' : ''}.`;
}

Cmd Grammar Earth

A JavaScript module in the engine folder of GlobalGrid2050 covering cables.

Set aside from the main view: 96% of its lines are the same as solar-design-studio/202609271740-site-world/world/cmd-grammar-earth.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Cmd Grammar Earth; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.96 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/cmd-grammar-earth.mjs:1-60 0c8ba71512223c7f446770a792604fcd85e0f082
  • sha256 240f36c9d7f0b6d746cbb15d3805b98fbc988c05428134cfb8d4c9f9925c18c2
  • target sha256 d941ab42143e7c08bbffd88d8e66dda288d836bc1dbbf29e07ab60258953ee76
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

ingestglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-grammar-earth.mjs · lines 1–62 of 62 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern isThermalSoil (shared by 3 files)

What it does
It lists and searches cables. Defines isNum, isThermalSoil, parseEarth, has, chk.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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: cables.
Downstream impact
Used directly by 1 file: Cmd Grammar (globalgrid2050).
What it achieves
It parses earth (`parseEarth`) and is built from the is num helper (`isNum`) and the is thermal soil helper (`isThermalSoil`). The earthing words of the command line (earthing, earth, soil rho, bonding), split out of `cmd-grammar.mjs` to keep each cartridge under 400 lines.
Why it matters
Imported by Cmd Grammar.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
none found
Used by
imported by Cmd Grammar (import)
Produces
EARTH_KEYS, EARTH_COMMANDS, EARTH_ALIASES, isThermalSoil, parseEarth
Defines here
isNum, isThermalSoil, parseEarth, has, chk
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/cmd-grammar-earth.mjs:1-62 · blob 4ec2fff5976d6ca232f4201263ba4695f8174f00 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 cmd-grammar-earth.mjs at v12 commit 3adcee9 (file last changed 8903e78). Modular star family: public #148228 parseEarth.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// cmd-grammar-earth.mjs: the earthing words of the command line (earthing, earth, soil rho, bonding), split out of
// cmd-grammar.mjs to keep each cartridge under 400 lines. Pure: parse() hands each verb here with its words.

// Earthing settings (typed, checked like KEYS; held by the earthing cartridge, earth-mount.mjs).
export const EARTH_KEYS = Object.freeze({ mesh: { label: 'earth grid mesh spacing', unit: 'm', min: 2, max: 20 },
  ring: { label: 'earth ring depth', unit: 'm', min: 0.3, max: 2 }, rods: { label: 'rods per station', unit: 'rods', min: 0, max: 40, int: true },
  rodLength: { label: 'rod length', unit: 'm', min: 1.2, max: 12 }, target: { label: 'earth resistance target', unit: 'Ω', min: 0.1, max: 50 },
  split: { label: 'split factor', unit: '', min: 0.05, max: 1 }, rho: { label: 'soil resistivity', unit: 'Ω·m', min: 1, max: 10000 } });

// The earthing verbs for help and search, and their plain words (longest first; the grammar applies them to whole words).
export const EARTH_COMMANDS = Object.freeze([
  { verb: 'earthing', usage: 'earthing show  ·  earthing hide  ·  earthing dc floating  ·  earthing dc earthed',
    words: 'earth electrode rod ring grid mesh bonding touch step epr resistance layer' },
  { verb: 'earth', usage: 'earth grid 5m  ·  earth ring 0.6m  ·  earth rods 4 2.4m  ·  earth target 2  ·  earth split 0.5',
    words: 'earthing electrode rod ring grid mesh spacing depth target resistance split factor substation station' },
  { verb: 'bonding', usage: 'bonding single-point  ·  bonding both-ends  ·  bonding cross  ·  bonding auto', words: 'cable screen sheath svl link box ecc earthing' },
]);
export const EARTH_ALIASES = Object.freeze([
  ['soil thermal resistivity', 'soil'], ['thermal resistivity', 'soil'], ['soil resistivity', 'soil rho'],
  ['earth grid', 'earth mesh'], ['earthing grid', 'earth mesh'], ['cross bonded', 'cross'], ['cross-bonded', 'cross'],
  ['cross bonding', 'cross'], ['single point', 'single-point'], ['both ends', 'both-ends'], ['ohm m', 'ohmm'], ['ohm-m', 'ohmm'], ['ohm.m', 'ohmm'],
  ['ohms', 'ohm'], ['resistivity', 'rho'], ['solid', 'both-ends'], ['bond', 'bonding']
]);

const isNum = t => t && typeof t === 'object' && Number.isFinite(t.n);

/** soil N alone (or in K.m/W) is the cable rating's thermal resistivity, not an earthing word. */
export const isThermalSoil = rest => !rest.includes('rho') && !rest.includes('survey') && !rest.some(x => isNum(x) && /^ohm/.test(x.unit || ''));

/**
 * parseEarth(v, rest, bad, eg) -> { act, arg } or null (refused; the reason pushed on bad).
 * v: earthing | earth | soil | bonding; rest: the words and numbers after it; eg(what): an example for the verb.
 */
export function parseEarth(v, rest, bad, eg) {
  const has = w => rest.includes(w);
  if (v === 'earthing' && has('dc')) {   // the DC array's earthing: floating (the default) or one pole earthed
    const d = ['floating', 'earthed'].find(has);
    if (!d) { bad.push('earthing dc takes floating or earthed'); return null; }
    return { act: 'earthing', arg: { what: 'dc', value: d } };
  }
  if (v === 'earthing') return { act: 'earthing', arg: { what: has('hide') ? 'hide' : 'show' } };
  if (v === 'bonding') {
    const b = ['single-point', 'both-ends', 'cross', 'auto'].find(has);
    if (!b) { bad.push('bonding takes single-point, both-ends, cross or auto'); return null; }
    return { act: 'earthing', arg: { what: 'bonding', value: b } };
  }
  const what = v === 'soil' ? (has('survey') ? 'survey' : 'rho') : ['mesh', 'ring', 'rods', 'target', 'split'].find(has);
  if (!what) { bad.push('earth takes grid, ring, rods, target or split, e.g. earth grid 5m'); return null; }
  const ns = rest.filter(isNum);
  const chk = (k, x) => { const K = EARTH_KEYS[k], n = x.unit === 'cm' ? x.n / 100 : x.unit === 'mm' ? x.n / 1000 : x.n;
    const ok = n >= K.min && n <= K.max && (!K.int || Math.round(n) === n);
    if (!ok) bad.push(`${K.label} must be ${K.int ? 'a whole number' : 'a number'} from ${K.min} to ${K.max}${K.unit ? ' ' + K.unit : ''}; you typed ${x.n}${x.unit}`);
    return n; };
  const out = { act: 'earthing', arg: { what: what === 'mesh' ? 'grid' : what, value: null, value2: null } };
  if (what === 'survey') return out;
  if (!ns.length && what !== 'mesh') { bad.push(`${v} ${what} needs a number, e.g. ${eg(what)}`); return null; }
  if (ns[0]) out.arg.value = chk(what, ns[0]);
  if (what === 'rods' && ns[1]) out.arg.value2 = chk('rodLength', ns[1]);
  return out;
}

Cmd Grammar Plant

A JavaScript module in the engine folder of GlobalGrid2050. It parses plant (`parsePlant`) and is built from the has step (`has`).

Set aside from the main view: 96% of its lines are the same as solar-design-studio/202609271853-site-world/world/cmd-grammar-plant.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with Cmd Grammar Plant; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9623 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/cmd-grammar-plant.mjs:1-58 c2cdf8ecb478fd310c5f418bf1a7515328b9ff30
  • sha256 dbb37776e9b7c35668944681a7a63a8d834c7afc534812916d8ab67ee0441725
  • target sha256 236f3f02a7feb5a1599e60a769f3cdadd2ee7adcb264f46be7f44db69ceeef3f
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

ingestglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-grammar-plant.mjs · lines 1–60 of 60 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern parsePlant (shared by 3 files)

What it does
It lists and searches its content. Defines parsePlant, has, at.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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: Cmd Grammar (globalgrid2050).
What it achieves
The typed words for the plant's inverter class, its packing and the study presets. Its code works with 2500 kVA, 300 kVA and 400 kVA.
Why it matters
Imported by Cmd Grammar.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
Structure Presets (import)
Used by
imported by Cmd Grammar (import)
Produces
PLANT_KEYS, PLANT_COMMANDS, PLANT_VOCAB, parsePlant
Defines here
parsePlant, has, at
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/cmd-grammar-plant.mjs:1-60 · blob 965845b36ac0f957788efb29dbd03326fe26a860 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 cmd-grammar-plant.mjs at v12 commit 3adcee9 (file last changed a83209f). Modular star family: not known to star-find.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// cmd-grammar-plant.mjs: the typed words for the plant's inverter class, its packing and the study presets.
//   inverter central 2500kva 2   central inverters of 2500 kVA, two to a station (MV skid or container)
//   inverter string 300kva 20    string inverters of 300 kVA, twenty to a station (the v09 plant)
//   packing fields | packing bands | packing band 400 run 280   how the tables fill the land (plant-packing.mjs)
//   preset central-6l-20          a generic preset from the UK study (structure-presets.mjs)
// Pure: imports only the presets' names.

import { PRESET_IDS } from './structure-presets.mjs';

export const PLANT_KEYS = Object.freeze({
  inverterClass: { label: 'inverter class', choices: ['string', 'central'] },
  inverterKVA: { label: 'inverter rating', unit: 'kVA', min: 100, max: 5000 },
  invertersPerStation: { label: 'inverters per station', unit: '', min: 1, max: 30, int: true },
  packing: { label: 'packing', choices: ['fields', 'bands'] },
  bandM: { label: 'distance between east-west tracks', unit: 'm', min: 100, max: 2000 },
  runM: { label: 'table run between cross lanes', unit: 'm', min: 30, max: 500 },
  hedge: { label: 'hedge setback between fields', unit: 'm', min: 2, max: 10 },
  moduleLong: { label: 'module length', unit: 'm', min: 1, max: 2.6 },
  moduleShort: { label: 'module width', unit: 'm', min: 0.6, max: 1.4 }
});
export const PLANT_COMMANDS = Object.freeze([
  { verb: 'inverter', usage: 'inverter central 2500kva 2  ·  inverter string 300kva 20',
    words: 'central string inverter skid container combiner box station kva class' },
  { verb: 'packing', usage: 'packing fields  ·  packing bands  ·  packing band 400 run 280',
    words: 'fill fields hedges parcels tracks bands runs cross lanes half tables land use' },
  { verb: 'preset', usage: 'preset  ·  preset central-6l-20  ·  preset uk-dense', words: 'study uk practice operational plant class landscape central' }
]);
export const PLANT_VOCAB = { inverter: ['central', 'string'], packing: ['fields', 'bands', 'band', 'run'] };
// A class switched without a rating takes the class's typical one: central 2500 kVA alone, string 300 kVA twenty.
const CLASS_DEFAULT = { central: [2500, 1], string: [300, 20] };

/** Parses inverter, packing and preset into out (set, act, arg); refusals go to bad. */
export function parsePlant(v, rest, out, { put, bad, isNum }) {
  const has = w => rest.includes(w);
  if (v === 'inverter') {
    const cls = has('central') ? 'central' : has('string') ? 'string' : null, ns = rest.filter(isNum);
    const kva = ns.find(x => x.unit === 'kva') || ns.find(x => !x.unit && x.n >= 100), per = ns.find(x => x !== kva && !x.unit);
    if (!cls && !kva && !per) { bad.push('inverter takes central or string, a rating in kVA and inverters per station, such as inverter central 2500kva 2'); return; }
    if (ns.some(x => x.unit && x.unit !== 'kva')) { bad.push('the inverter rating is in kVA, such as inverter central 2500kva'); return; }
    if (cls) put('inverterClass', cls);
    const c = cls || null, k = kva ? kva.n : c ? CLASS_DEFAULT[c][0] : null, n = per ? per.n : c ? CLASS_DEFAULT[c][1] : null;
    if (k != null) put('inverterKVA', k);
    if (n != null) put('invertersPerStation', n);
    if (c === 'central' && ((k != null && (k < 500 || k > 5000)) || (n != null && n > 4))) bad.push('a central inverter is 500 to 5000 kVA, 1 to 4 to a station');
    if (c === 'string' && ((k != null && (k < 100 || k > 400)) || (n != null && n < 8))) bad.push('a string inverter is 100 to 400 kVA, 8 to 30 to a station');
  } else if (v === 'packing') {
    if (has('fields')) put('packing', 'fields');
    if (has('bands')) put('packing', 'bands');
    const at = w => { const i = rest.indexOf(w); return i >= 0 && isNum(rest[i + 1]) ? rest[i + 1].n : null; };
    if (at('band') != null) put('bandM', at('band'));
    if (at('run') != null) put('runM', at('run'));
    if (!Object.keys(out.set).length && !bad.length) bad.push('packing is fields or bands, with band N and run N in metres, such as packing band 400 run 280');
  } else if (v === 'preset') {
    const w = rest.filter(x => typeof x === 'string').join('').replace(/-/g, ''), id = PRESET_IDS.find(k => k.replace(/-/g, '') === w);
    if (w && !id) bad.push(`no preset "${w}"; the presets are ${PRESET_IDS.join(', ')} (type preset for the list)`);
    out.act = 'structure'; out.arg = { id: id || null, preset: true };
  }
}

Cmd Grammar Senses

A JavaScript module in the engine folder of GlobalGrid2050. It parses senses (`parseSenses`) and is built from the is num helper (`isNum`).

Set aside from the main view: 90% of its lines are the same as solar-design-studio/202609271853-site-world/world/cmd-grammar-senses.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 90% of lines shared with Cmd Grammar Senses; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9048 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/cmd-grammar-senses.mjs:1-23 e25c7ed1117084e1d79f371885783b12da7178e5
  • sha256 ebb6a5dfe54fd76be317d811ab7ef772881e46c2abf8a7fa820f323ed72edb35
  • target sha256 7e8af98f85ccda1e84755897507e8284ab27d10ede17d4342439ad1898717eb7
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

ingestglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-grammar-senses.mjs · lines 1–25 of 25 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern parseSenses (shared by 3 files)

What it does
Defines isNum, parseSenses.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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: Cmd Grammar (globalgrid2050).
What it achieves
The binoculars words of the command line (binoculars, zoom, range), split out of `cmd-grammar.mjs` to keep each cartridge under 400 lines.
Why it matters
Imported by Cmd Grammar.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
none found
Used by
imported by Cmd Grammar (import)
Produces
SENSES_COMMANDS, SENSES_VOCAB, SENSES_ALIASES, parseSenses
Defines here
isNum, parseSenses
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/cmd-grammar-senses.mjs:1-25 · blob 990111a8ed37b6e7e721b3841a719816e16fe580 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 cmd-grammar-senses.mjs at v12 commit 3adcee9 (file last changed b6ebfdb). Modular star family: not known to star-find.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// cmd-grammar-senses.mjs: the binoculars words of the command line (binoculars, zoom, range), split out of cmd-grammar.mjs
// to keep each cartridge under 400 lines. Pure: parse() hands each verb here with its words. They change no design value
// and stay out of the typed script; the engine (cmd-run.mjs) hands them to senses-mount.mjs.

export const SENSES_COMMANDS = Object.freeze([
  { verb: 'binoculars', usage: 'binoculars on  ·  binoculars off', words: 'binocular lens zoom magnify far horizon look distance rangefinder' },
  { verb: 'zoom', usage: 'zoom 7  ·  zoom 10', words: 'binoculars magnification lens times' },
  { verb: 'range', usage: 'range', words: 'rangefinder distance bearing height what is under the reticle horizon binoculars' }
]);
export const SENSES_VOCAB = Object.freeze({ binoculars: ['on', 'off'], zoom: ['7x', '10x', 'x'], range: [] });
export const SENSES_ALIASES = Object.freeze([['binocular', 'binoculars'], ['rangefinder', 'range']]);
const STEPS = [7, 10];
const isNum = t => t && typeof t === 'object' && Number.isFinite(t.n);

/** parseSenses(v, rest, bad) -> { act: 'binoculars', arg: { on?, zoom?, range? } } or null (refused; the reason pushed on bad). */
export function parseSenses(v, rest, bad) {
  if (v === 'binoculars') return { act: 'binoculars', arg: { on: !rest.includes('off') } };
  if (v === 'range') return { act: 'binoculars', arg: { range: true } };
  const n = rest.find(isNum), w = rest.find(x => typeof x === 'string' && /^\d+x$/.test(x));
  const m = n ? n.n : w ? Number(w.slice(0, -1)) : NaN;
  if (!STEPS.includes(m)) { bad.push(`zoom is ${STEPS.join(' or ')} (the binoculars' steps)${Number.isFinite(m) ? `; you typed ${m}` : ''}`); return null; }
  return { act: 'binoculars', arg: { zoom: m } };
}

Cmd Grammar

A JavaScript module in the engine folder of GlobalGrid2050 covering solar, overhead lines (OHL), cables and the Renewable Energy Planning Database (REPD) register.

Set aside from the main view: 97% of its lines are the same as solar-design-studio/202609271853-site-world/world/cmd-grammar.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Cmd Grammar; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9737 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271853-site-world/world/cmd-grammar.mjs:1-398 c3f13dc29a8c3305178363d4464954ffa2242e8d
  • sha256 4dab6879e48be6dd2cfabb0ed4b0ca85982a7535dcf52afdc11556782670663a
  • target sha256 502e40c6c4eb7eef3a2b0b5f25005b5161e48640694705c31e159e2b859d8050
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

ingestglobalgrid2050 / energy-transition-simulator/202609280014/mod/engine/cmd-grammar.mjs · lines 1–400 of 400 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern example (shared by 3 files)

What it does
It lists and searches solar, overhead lines (OHL), cables and the REPD register. Defines 15 functions or classes, including r, said, guard, words, search.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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, overhead lines (OHL), cables, the REPD register.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: Cmd Model (globalgrid2050).
What it achieves
It is built from the said step (`said`), the guard step (`guard`) and the words step (`words`). The typed design language of the site world. Its code works with 10 MVA, 100 MVA and 50 MW.
Why it matters
Imported by Cmd Model.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod/engine · JavaScript module
Uses
Structures (import), Cmd Grammar Plant (import), Structure Presets (import), Cmd Grammar Trench (import), Cmd Grammar Earth (import), Cmd Grammar Senses (import), Sub Grammar (import), Renewable Energy Planning Database (REPD) Grammar (import)
Used by
imported by Cmd Model (import)
Produces
KEYS, COMMANDS, ALIASES, guard, words, search, example, parse, help
Defines here
r, said, guard, words, search, hay, example, refuse, isNum, parse, put, num, after, has, help
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/cmd-grammar.mjs:1-400 · blob 34eeb1af3487710646582215ef80098b5070deb8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
// COPIED UNCHANGED from world/v12 cmd-grammar.mjs at v12 commit 3adcee9 (file last changed 0562d4f). Modular star family: public #20973 guard.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// cmd-grammar.mjs: the typed design language of the site world. One line is one command; parse(line) turns it into
// { verb, set: { key: value }, act, arg } or refuses it in words. Pure: no DOM; imports only its earthing words.
//
// Patterns taken from the Kuiper shell's typed bar (globalgrid2050 kuiper-grid i0097 programs): one input table
// (KEYS: label, unit, min, max) drives the guard and the echo; an alias table maps plain words onto keys; a value
// outside its range is refused, never clamped ("gcr must be a number from 0.2 to 0.8; you typed 4"), and a value
// that fits once divided by 1000 or 100 is named as a likely unit slip; plain-word search needs every word to match.
// Imports pure word tables: table formats and structure names, the plant's inverter, packing and preset words.
import { parseFormat, formatRefusal, STRUCTURE_IDS } from './structures.mjs';
import { PLANT_KEYS, PLANT_COMMANDS, PLANT_VOCAB, parsePlant } from './cmd-grammar-plant.mjs';
import { PRESET_IDS } from './structure-presets.mjs';
import { TRENCH_KEYS_TYPED, TRENCH_COMMANDS, TRENCH_VOCAB, SPLIT_KINDS, COVER_KINDS, parseTrench } from './cmd-grammar-trench.mjs';
import { EARTH_KEYS, EARTH_COMMANDS, EARTH_ALIASES, parseEarth, isThermalSoil } from './cmd-grammar-earth.mjs';
import { SENSES_COMMANDS, SENSES_VOCAB, SENSES_ALIASES, parseSenses } from './cmd-grammar-senses.mjs';
import { SUB_COMMANDS, parseSubCommand } from './sub-grammar.mjs'; import { parseConnect } from './connect-here.mjs'; // go substation 132 · connect here
import { REPD_COMMANDS, parseRepd } from './repd-grammar.mjs'; export { EARTH_KEYS, SPLIT_KINDS, COVER_KINDS }; // REPD: go solar, next bess
export const KEYS = Object.freeze({
  mw: { label: 'plant export', unit: 'MW', min: 1, max: 5000 },
  layout: { label: 'layout', choices: ['south', 'east-west', 'tracker'] },
  tilt: { label: 'tilt', unit: '°', min: 5, max: 40 },
  tiltEw: { label: 'east-west tilt', unit: '°', min: 3, max: 20 },
  pitch: { label: 'row pitch', unit: 'm', min: 3, max: 40 },
  gcr: { label: 'ground cover ratio', unit: '', min: 0.2, max: 0.8 },
  edge: { label: 'lowest module edge', unit: 'm', min: 0.3, max: 2.5 },
  mps: { label: 'modules per string', unit: 'modules', min: 10, max: 40, int: true },
  wp: { label: 'module power', unit: 'W', min: 200, max: 800 },
  voc: { label: 'module open-circuit voltage', unit: 'V', min: 20, max: 80 },
  tempMin: { label: 'coldest cell temperature', unit: '°C', min: -40, max: 15 },
  fence: { label: 'fence setback', unit: 'm', min: 5, max: 10 },
  water: { label: 'watercourse setback', unit: 'm', min: 0, max: 100 },
  slope: { label: 'slope limit', unit: '%', min: 1, max: 40 },
  depth: { label: 'trench depth', unit: 'm', min: 0.45, max: 3 },
  width: { label: 'trench width', unit: 'm', min: 0.25, max: 3 },
  formation: { label: 'cable formation', choices: ['trefoil', 'flat'] },
  size: { label: 'cable size', unit: 'mm²', choices: [35, 50, 70, 95, 120, 150, 185, 240, 300, 400, 500, 630, 800, 1000] },
  metal: { label: 'conductor', choices: ['al', 'cu'] },
  wiring: { label: 'string wiring', choices: ['standard', 'leapfrog'] },
  avoidOhl: { label: 'overhead line zones kept clear', choices: [true, false] },
  stations: { label: 'block size', unit: 'MVA', min: 10, max: 100 },
  pocKv: { label: 'grid connection', unit: 'kV', choices: [132, 275, 400] },
  ...TRENCH_KEYS_TYPED,
  // Structures (structures.mjs): table format, post lines, tracker strings a row, the row gap rule, the MPPT cap, post height.
  tiers: { label: 'modules up the table', unit: '', min: 1, max: 6, int: true },
  orient: { label: 'module orientation', choices: ['portrait', 'landscape'] },
  tableCols: { label: 'modules along each tier', unit: 'modules', min: 4, max: 40, int: true },
  posts: { label: 'post lines per table', choices: [1, 2] },
  trackerStrings: { label: 'strings per tracker row', unit: 'strings', min: 1, max: 4, int: true },
  rowGap: { label: 'row gap rule', choices: ['flat', 'slope'] },
  mppts: { label: 'MPPT inputs per inverter', unit: '', min: 1, max: 24, int: true },
  stringsPerMppt: { label: 'strings per MPPT input', unit: '', min: 1, max: 6, int: true },
  postMax: { label: 'post height limit', unit: 'm', min: 1.5, max: 6 },
  gcrTracker: { label: 'tracker ground cover ratio', unit: '', min: 0.2, max: 0.6 },
  ...PLANT_KEYS // inverter class, packing, hedge setback, module size (cmd-grammar-plant.mjs)
});

// Every verb, with a usage line and plain words for the search and for help.
export const COMMANDS = Object.freeze([
  { verb: 'plant', usage: 'plant 100mw south', words: 'lay out solar farm capacity export east-west tracker open land' },
  { verb: 'fill', usage: 'fill boundary', words: 'lay out inside the drawn boundary' },
  { verb: 'boundary', usage: 'boundary 399000 208500, 399800 208500, 399800 209200', words: 'site outline national grid corners' },
  { verb: 'table', usage: 'table 2P27 portrait tilt 25  ·  table 3P12 tilt 15  ·  table 4L12 single  ·  table 2P tracker',
    words: 'rows of modules string length portrait landscape tiers format 3P 4P 3L 4L 6L half' },
  { verb: 'module', usage: 'module 600w voc 50', words: 'panel power open circuit voltage' },
  { verb: 'string', usage: 'string 28  ·  modules per string 28  ·  series 28', words: 'modules in series string length voltage headroom' },
  { verb: 'temp', usage: 'temp min -10', words: 'coldest cell temperature minimum site cold open circuit voltage' },
  { verb: 'tilt', usage: 'tilt 20', words: 'panel angle sun' },
  { verb: 'pitch', usage: 'pitch 7  ·  row width 7', words: 'row spacing shade coverage' },
  { verb: 'gcr', usage: 'gcr 0.4', words: 'ground cover ratio coverage spacing' },
  { verb: 'edge', usage: 'edge 0.8', words: 'lowest module edge clearance grazing' },
  ...TRENCH_COMMANDS,
  { verb: 'soil', usage: 'soil 1.2  ·  soil rho 100  ·  soil rho survey',
    words: 'soil thermal resistivity ground rating dry sand clay ohm metre earthing wenner survey' },
  { verb: 'bend', usage: 'bend radius', words: 'cable minimum bend radius corner' },
  { verb: 'wiring', usage: 'wiring leapfrog', words: 'string dc loop leapfrog standard inductive' },
  { verb: 'loop', usage: 'loop area', words: 'inductive loop string area lightning' },
  { verb: 'piles', usage: 'piles auto', words: 'piling foundations posts automatic' },
  { verb: 'block', usage: 'block 10mva', words: 'station block 10 mva rings' },
  { verb: 'follow', usage: 'follow  ·  follow next  ·  follow play  ·  follow close', words: 'power path module to the grid landing trace' },
  { verb: 'sld', usage: 'sld  ·  sld hide', words: 'single line diagram schematic stations feeders' },
  { verb: 'go', usage: 'go block  ·  go block 3 table 5  ·  go compound  ·  go <place>', words: 'fly to station table compound solar block place town postcode find' },
  { verb: 'show', usage: 'show pylons  ·  show water  ·  show slope 10%  ·  show soil', words: 'layer overhead lines rivers gradient geology' },
  { verb: 'hide', usage: 'hide slope', words: 'layer off' },
  { verb: 'avoid', usage: 'avoid slope 15%  ·  avoid pylons on', words: 'constraint gradient overhead lines keep clear' },
  { verb: 'setback', usage: 'setback water 10  ·  setback fence 8', words: 'watercourse stand-off fence' },
  ...EARTH_COMMANDS, ...SENSES_COMMANDS, ...REPD_COMMANDS, ...SUB_COMMANDS,
  { verb: 'hud', usage: 'hud on  ·  hud off  ·  hud rules', words: 'checks failed red overlay private rules file' },
  { verb: 'structure', usage: 'structure  ·  structure tracker-2p  ·  structure fixed-2p', words: 'mounting class catalogue frame tracker fixed agrivoltaic' },
  ...PLANT_COMMANDS,
  { verb: 'posts', usage: 'posts single  ·  posts twin  ·  posts max 3', words: 'single post line mono twin front rear pile height limit' },
  { verb: 'tracker', usage: 'tracker 3 strings  ·  tracker 2p', words: 'single axis rows strings per row torque tube' },
  { verb: 'rowgap', usage: 'rowgap slope  ·  rowgap flat', words: 'row gap slope aware north facing shade winter pitch' },
  { verb: 'mppt', usage: 'mppt 12 inputs 2', words: 'inverter mppt inputs strings per inverter cap dc ac ratio' },
  { verb: 'undo', usage: 'undo', words: 'take back the last command' },
  { verb: 'script', usage: 'script', words: 'list typed commands design' },
  { verb: 'help', usage: 'help pitch', words: 'commands how' }
]);
const VERBS = COMMANDS.map(c => c.verb);

// Plain words to the language's own, longest first. Applied to whole words only.
export const ALIASES = Object.freeze([
  ['strings per mppt', 'inputs'], ['strings per input', 'inputs'], ['row gap', 'rowgap'], ['slope-aware', 'slope'], ['slope aware', 'slope'],
  ['single post line', 'posts single'], ['single post', 'posts single'], ['mono post', 'posts single'], ['twin posts', 'posts twin'],
  ['modules per string', 'string'], ['modules in series', 'string'], ['modules in a string', 'string'], ['string length', 'string'],
  ['coldest cell temperature', 'temp'], ['coldest cell', 'temp'], ['minimum temperature', 'temp'], ['min temp', 'temp'], ['temp min', 'temp'],
  ['temperature', 'temp'], ['coldest', 'temp'], ['series', 'string'], ['mps', 'string'],
  ...EARTH_ALIASES, ...SENSES_ALIASES,
  ['single line diagram', 'sld'], ['single-line diagram', 'sld'],
  ['lowest module edge', 'edge'], ['ground cover ratio', 'gcr'], ['overhead lines', 'pylons'], ['overhead line', 'pylons'],
  ['power lines', 'pylons'], ['inductive loops', 'loop'], ['inductive loop', 'loop'], ['row width', 'pitch'], ['row pitch', 'pitch'],
  ['row spacing', 'pitch'], ['lowest edge', 'edge'], ['low edge', 'edge'], ['panel angle', 'tilt'], ['bend radius', 'bend'],
  ['loop area', 'loop'], ['string wiring', 'wiring'], ['ground cover', 'gcr'], ['go to', 'go'], ['fly to', 'go'], ['lay out', 'plant'],
  ['east west', 'eastwest'], ['east-west', 'eastwest'], ['fence setback', 'setback fence'], ['water setback', 'setback water'],
  ['spacing', 'pitch'], ['angle', 'tilt'], ['clearance', 'edge'], ['goto', 'go'], ['fly', 'go'], ['capacity', 'plant'],
  ['pile', 'piles'], ['piling', 'piles'], ['ohl', 'pylons'], ['towers', 'pylons'], ['pylon', 'pylons'], ['grid', 'pylons'],
  ['rivers', 'water'], ['river', 'water'], ['watercourses', 'water'], ['watercourse', 'water'], ['streams', 'water'],
  ['gradients', 'slope'], ['gradient', 'slope'], ['slopes', 'slope'], ['geology', 'soil'], ['soils', 'soil'], ['ew', 'eastwest'],
  ['solar day', 'solar-day'], ['as built', 'xray'], ['as-built', 'xray'], ['x-ray', 'xray'],
  ['aluminium', 'al'], ['aluminum', 'al'], ['copper', 'cu'], ['sequential', 'standard'], ['station', 'block'], ['commands', 'help'], ['diagram', 'sld'], ['trace', 'follow'], ['trackers', 'tracker']
]);

const r = (v, d = 2) => Math.round(v * 10 ** d) / 10 ** d;
const said = v => (typeof v === 'string' ? `"${v}"` : String(v));
const UNIT_WORDS = ['mw', 'mva', 'kva', 'mm2', 'mm²', 'mm', 'cm', 'm', '%', 'w', 'v', 'kv', 'deg', '°', '°c', 'c', 'ohmm', 'ohm'];
const NUM = /^([-−]?(?:\d+(?:\.\d+)?|\.\d+))(mw|mva|kva|mm2|mm²|mm|cm|m|%|w|v|kv|deg|°c|°|c|ohmm|ohm)?$/;
/** Checks one typed value against KEYS; returns null or the refusal in words. */
export function guard(key, v) {
  const k = KEYS[key];
  if (!k) return `unknown setting ${key}`;
  if (k.choices) {
    if (k.choices.includes(v)) return null;
    return `${k.label} must be one of ${k.choices.map(String).join(', ')}${k.unit ? ' ' + k.unit : ''}; you typed ${said(v)}`;
  }
  if (typeof v !== 'number' || !Number.isFinite(v)) return `${k.label} must be a number; you typed ${said(v)}`;
  if (k.int && Math.round(v) !== v) return `${k.label} must be a whole number from ${k.min} to ${k.max}; you typed ${v}`;
  if (v >= k.min && v <= k.max) return null;
  if (k.int) return `${k.label} must be a whole number from ${k.min} to ${k.max}; you typed ${v}`;   // a count: no unit to have mistyped
  let hint = '';
  for (const [f, why] of key === 'tempMin' ? [] : [[1000, 'you may have typed millimetres'], [100, key === 'gcr' ? 'a percentage' : 'you may have typed centimetres']]) {
    const g = v / f;
    if (g >= k.min && g <= k.max) { hint = ` Did you mean ${r(g, 3)}${k.unit ? ' ' + k.unit : ''}? (${why})`; break; }
  }
  return `${k.label} must be a number from ${k.min} to ${k.max}${k.unit ? ' ' + k.unit : ''}; you typed ${v}${hint ? '.' + hint : ''}`;
}

/** Lower-case words with the aliases applied; numbers keep their unit as { n, unit }. */
export function words(line) {
  let s = ` ${String(line || '').toLowerCase().replace(/#.*$/, '').replace(/[,;]/g, ' , ').replace(/\s+/g, ' ').trim()} `;
  s = s.replace(/ω·m|ωm|ω\.m/g, 'ohmm').replace(/ω/g, 'ohm'); // Ω typed (lower-cased to ω): 2Ω, 100 Ω·m
  for (const [a, b] of ALIASES) s = s.split(` ${a} `).join(` ${b} `);
  const t = s.trim().split(' ').filter(Boolean);
  // "50 MW", "7 m", "15 %": a unit written apart joins its number.
  for (let i = t.length - 1; i > 0; i--) if (UNIT_WORDS.includes(t[i]) && /^-?(\d+(\.\d+)?|\.\d+)$/.test(t[i - 1])) t.splice(i - 1, 2, t[i - 1] + t[i]);
  return t.map(w => { const m = w.match(NUM); return m ? { n: Number(m[1].replace('−', '-')), unit: m[2] || '' } : w; });
}
/** Plain-word search over the commands: every word typed must appear in the usage or the words; usage matches first. At most 8. */
export function search(text, limit = 8) {
  const ws = String(text || '').toLowerCase().split(/\s+/).filter(Boolean);
  if (!ws.length) return COMMANDS.slice(0, limit);
  const hay = c => `${c.verb} ${c.usage} ${c.words}`.toLowerCase();
  const exact = COMMANDS.filter(c => c.verb === ws[0] || c.verb.startsWith(ws[0]));
  const rest = COMMANDS.filter(c => !exact.includes(c) && ws.every(w => hay(c).includes(w)))
    .map((c, i) => [c, ws.filter(w => c.usage.includes(w)).length, i]).sort((a, b) => b[1] - a[1] || a[2] - b[2]).map(x => x[0]);
  return [...exact, ...rest].slice(0, limit);
}
/** The usage of a command that best shows the words typed ("slope" -> "avoid slope 15%"). */
export const example = (c, text = '') => { const vs = c.usage.split('  ·  '), w = String(text).toLowerCase().split(/\s+/)[0]; return vs.find(v => w && v.includes(w)) || vs[0]; };
const refuse = (why, line) => ({ ok: false, why, line });
// The words each verb reads besides numbers; any other word is refused, never dropped ("plant 50mw north").
const VOCAB = { plant: ['south', 'eastwest', 'tracker'], fill: ['boundary', 'south', 'eastwest', 'tracker'],
  boundary: ['open', ','], table: ['portrait', 'landscape', 'tilt', 'eastwest', 'tracker', 'single', 'twin', 'south'],
  posts: ['single', 'twin', 'max'], tracker: ['strings', 'string'], rowgap: ['slope', 'flat'], mppt: ['inputs', 'x'],
  module: ['voc', 'size'], string: ['modules'], temp: ['min', 'cell'], ...PLANT_VOCAB,
  ...TRENCH_VOCAB, ...SENSES_VOCAB, wiring: ['leapfrog', 'standard'], piles: ['auto'],
  follow: ['next', 'back', 'play', 'pause', 'close'], sld: ['hide', 'show'], hud: ['on', 'off', 'rules'],
  block: ['poc', 'at'], go: ['block', 'table', 'compound'], show: ['pylons', 'water', 'slope', 'soil', 'earthing'], hide: ['pylons', 'water', 'slope', 'soil', 'earthing'],
  earthing: ['show', 'hide', 'dc', 'floating', 'earthed'], earth: ['mesh', 'ring', 'rods', 'target', 'split'], soil: ['rho', 'survey'], bonding: ['single-point', 'both-ends', 'cross', 'auto'],
  avoid: ['slope', 'pylons', 'water', 'on', 'off'], setback: ['water', 'fence', 'hedge'] };
const isNum = t => t && typeof t === 'object' && Number.isFinite(t.n);

/**
 * parse(line) -> { ok: true, verb, set, act, arg, line } | { ok: false, why, line }
 *   set: typed values by KEYS key (already guarded); act: 'layout' | 'fill' | 'boundary' | 'block' | 'piles' | 'go' | 'show' | 'follow' | 'sld'
 *   | 'explain' | 'undo' | 'help' | 'script' | null; arg: what the act needs.
 */
export function parse(line) {
  const t = words(line), hop = parseSubCommand(line) || parseRepd(line) || parseConnect(line); if (hop) return hop; // journey, then REPD, then connect here
  if (!t.length) return refuse('nothing typed', line);
  if (t[0] === 'set' && t.length > 1) t.shift(); // "set pitch 7" is "pitch 7"
  let [v, ...rest] = t;
  if (typeof v !== 'string') return refuse(`a command starts with a word, such as ${VERBS.slice(0, 4).join(', ')}; type help for all`, line);
  if (!VERBS.includes(v)) {
    const c = VERBS.filter(x => x.startsWith(v));
    if (c.length === 1) v = c[0];
    else if (c.length > 1) return refuse(`"${v}" could be ${c.join(', ')}; type more letters`, line);
    else {
      const s = search(v, 3).map(x => example(x, v));
      return refuse(`"${v}" is not a command.${s.length ? ` Try ${s.join(', ')}.` : ''} Type help for all.`, line);
    }
  }
  const out = { ok: true, verb: v, set: {}, act: null, arg: {}, line: String(line).trim() };
  // go <place>: words go looks up in Find (a town, a postcode, a grid reference), not a block or a table.
  if (v === 'go' && rest.some(w => typeof w === 'string' && !(VOCAB.go || []).includes(w)) && !rest.includes('block')) {
    const place = String(line).trim().replace(/^\s*(go\s+to|goto|fly\s+to|fly|go)\s+/i, '').trim();
    return { ok: true, verb: 'go', set: {}, act: 'find', arg: { place }, line: String(line).trim() };
  }
  const bad = [], stray = ['help', 'structure', 'preset'].includes(v) ? [] : rest.filter(w => typeof w === 'string' && !(VOCAB[v] || []).includes(w) && !/^\d[pl]\d*$/.test(w));
  if (stray.length) {
    const takes = (VOCAB[v] || []).filter(w => w !== ',');
    return refuse(`${v} does not read "${stray[0]}"; ${takes.length ? `it takes ${takes.join(', ')} and numbers` : 'it takes a number'}`
      + ` (e.g. ${example(COMMANDS.find(c => c.verb === v))}). Nothing was changed.`, line);
  }
  const put = (key, val) => { const g = guard(key, val); if (g) bad.push(g); else out.set[key] = val; };
  const num = (i, key, units = []) => {
    let x = rest[i];
    if (isNum(x) && KEYS[key].unit === 'm' && (x.unit === 'cm' || x.unit === 'mm')) x = { n: x.n / (x.unit === 'cm' ? 100 : 1000), unit: 'm' };
    if (!isNum(x)) {
      const said = `${v} ${rest.slice(0, i).filter(w => typeof w === 'string').join(' ')}`.trim(), c = COMMANDS.find(k => k.verb === v);
      const eg = c.usage.split('  ·  ').find(u => u.startsWith(said + ' ')) || example(c);
      bad.push(`${said} needs a number, e.g. ${eg}`); return;
    }
    if (x.unit && units.length && !units.includes(x.unit)) { bad.push(`${KEYS[key].label} is in ${units[0] || KEYS[key].unit}; you typed ${x.n}${x.unit}`); return; }
    put(key, x.n);
  };
  const after = w => { const i = rest.indexOf(w); return i < 0 ? -1 : i + 1; };
  const has = w => rest.includes(w);
  switch (v) {
    case 'plant': case 'fill': {
      const n = rest.find(isNum);
      if (n) { if (n.unit && n.unit !== 'mw') bad.push(`plant capacity is in MW; you typed ${n.n}${n.unit}`); else put('mw', n.n); }
      if (has('south')) put('layout', 'south');
      if (has('eastwest')) put('layout', 'east-west');
      if (has('tracker')) put('layout', 'tracker');
      out.act = v === 'fill' ? 'fill' : 'layout';
      break;
    }
    case 'boundary': {
      if (has('open')) { out.act = 'boundary'; out.arg = { open: true }; break; }
      const pts = [];
      let cur = [];
      for (const x of [...rest, ',']) {
        if (x === ',') { if (cur.length) { pts.push(cur); cur = []; } continue; }
        if (isNum(x)) cur.push(x.n); else { bad.push(`boundary points are "easting northing" pairs in metres; "${x}" is not a number`); break; }
      }
      if (pts.some(p => p.length !== 2)) bad.push('each boundary corner is two numbers, easting then northing, separated by commas');
      else if (pts.length < 3) bad.push('a boundary needs at least three corners');
      else if (pts.some(([e, n]) => !(e > 0 && e < 700000 && n > 0 && n < 1300000))) bad.push('boundary corners are national-grid metres (easting 0 to 700000)');
      out.act = 'boundary'; out.arg = { points: pts };
      break;
    }
    case 'table': {
      // kPn / kLn (structures.mjs): n is the string length for 2P south, 1P east-west and trackers; for 3P, 3L and 4L it
      // is the modules along each tier (strings then run on across tables).
      const f = rest.find(w => typeof w === 'string' && /^\d[pl]\d*$/.test(w)), F = parseFormat(f);
      if (F) {
        const lay = has('tracker') ? 'tracker' : has('eastwest') ? 'east-west' : has('south') || F.tiers > 1 ? 'south' : 'east-west';
        const no = formatRefusal(lay, F.tiers, F.orient);
        if (no) bad.push(no);
        else {
          put('layout', lay); put('tiers', F.tiers); put('orient', F.orient);
          const own = lay === 'south' && !(F.tiers === 2 && F.orient === 'portrait'); // 3P, 3L, 4L: n along each tier
          if (F.cols !== null) put(own ? 'tableCols' : 'mps', F.cols);
          if (!own) out.set.tableCols = null;
        }
        if (has('landscape') && F.orient === 'portrait') bad.push(`${f.toUpperCase()} is portrait; landscape tables are 3L to 6L, such as table 4L12`);
      } else if (has('landscape')) bad.push('landscape takes a format: table 3L12, table 4L26 or table 6L12');
      else if (has('eastwest')) put('layout', 'east-west');
      if (has('single')) put('posts', 1);
      if (has('twin')) put('posts', 2);
      if (after('tilt') > 0) num(after('tilt'), (out.set.layout || '') === 'east-west' ? 'tiltEw' : 'tilt', ['°', 'deg']);
      if (!f && after('tilt') < 0 && !has('eastwest') && !has('single') && !has('twin')) bad.push('table needs a format, such as table 2P27 portrait tilt 25');
      break;
    }
    case 'structure': {
      const w = rest.filter(x => typeof x === 'string').join('').replace(/-/g, ''), id = [...STRUCTURE_IDS, ...PRESET_IDS].find(k => k.replace(/-/g, '') === w);
      if (w && !id) bad.push(`no structure "${w}"; the catalogue has ${STRUCTURE_IDS.join(', ')}; presets: type preset for the list`);
      out.act = 'structure'; out.arg = { id: id || null };
      break;
    }
    case 'posts': {
      if (has('max')) { const i = rest.findIndex(isNum); if (i >= 0) num(i, 'postMax', ['m']); else bad.push('posts max needs metres, such as posts max 3'); }
      else if (has('single') || rest.some(x => isNum(x) && x.n === 1)) put('posts', 1);
      else if (has('twin') || rest.some(x => isNum(x) && x.n === 2)) put('posts', 2);
      else bad.push('posts takes single, twin (or 1, 2) or max N');
      break;
    }
    case 'tracker': {
      put('layout', 'tracker');
      const F = parseFormat(rest.find(w => typeof w === 'string' && /^\d[pl]\d*$/.test(w)));
      if (F) { const no = formatRefusal('tracker', F.tiers, F.orient); if (no) bad.push(no); else { put('tiers', F.tiers); put('orient', 'portrait'); } }
      const n = rest.find(isNum);
      if (n) put('trackerStrings', n.n);
      if (!F && !n) bad.push('tracker takes strings per row (tracker 3 strings) or a format (tracker 2p)');
      break;
    }
    case 'inverter': case 'packing': case 'preset': parsePlant(v, rest, out, { put, bad, isNum }); break;
    case 'rowgap': if (has('slope')) put('rowGap', 'slope'); else if (has('flat')) put('rowGap', 'flat'); else bad.push('rowgap is slope or flat'); break;
    case 'mppt': {
      const ns = rest.filter(isNum);
      if (!ns.length) { bad.push('mppt needs the MPPT inputs and strings per input, such as mppt 12 inputs 2'); break; }
      put('mppts', ns[0].n);
      if (ns[1]) put('stringsPerMppt', ns[1].n);
      break;
    }
    case 'module': {
      const w = rest.find(x => isNum(x) && x.unit === 'w');
      if (w) put('wp', w.n);
      if (after('voc') > 0) num(after('voc'), 'voc', ['v']);
      if (after('size') > 0) { num(after('size'), 'moduleLong', ['m']); num(after('size') + 1, 'moduleShort', ['m']); } // module 260w size 1.65 0.99
      if (!w && after('voc') < 0 && after('size') < 0) bad.push('module needs a power, a Voc or a size, such as module 600w voc 50');
      break;
    }
    case 'string': { const n = rest.find(isNum); if (n) put('mps', n.n); else bad.push('string needs a number of modules in series, such as string 28'); break; }
    case 'temp': { const n = rest.find(isNum); if (!n) bad.push('temp needs the coldest cell temperature in °C, such as temp min -10');
      else if (n.unit && !['c', '°c', '°', 'deg'].includes(n.unit)) bad.push(`the coldest cell is in °C; you typed ${n.n}${n.unit}`); else put('tempMin', n.n); break; }
    case 'tilt': num(0, 'tilt', ['°', 'deg']); out.arg.maybeEw = true; break;
    case 'pitch': num(0, 'pitch', ['m']); break;
    case 'gcr': num(0, 'gcr'); break;
    case 'edge': num(0, 'edge', ['m']); break;
    case 'trench': case 'cable': case 'load': case 'xray': parseTrench(v, rest, out, { has, after, num, put, bad, guard }); break;
    case 'bend': out.act = 'explain'; out.arg = { what: 'bend' }; break;
    case 'loop': out.act = 'explain'; out.arg = { what: 'loop' }; break;
    case 'wiring': {
      const w = rest.find(x => x === 'leapfrog' || x === 'standard');
      if (w) put('wiring', w); else bad.push('wiring is leapfrog or standard');
      break;
    }
    case 'piles': if (!has('auto')) bad.push('piles are placed from the tables: type piles auto'); out.act = 'piles'; break;
    case 'block': {
      const n = rest.find(isNum);
      const mva = n ? n.n : 10;
      if (n && n.unit && n.unit !== 'mva') bad.push(`block size is in MVA; you typed ${n.n}${n.unit}`);
      else if (mva % 10) bad.push(`the block is built of 10 MVA stations: type 10 to 100 MVA in steps of 10; you typed ${mva}`);
      else put('stations', mva);
      if (after('poc') > 0 && isNum(rest[after('poc')])) put('pocKv', rest[after('poc')].n);
      const ia = after('at');
      if (ia > 0) { if (isNum(rest[ia]) && isNum(rest[ia + 1])) out.arg.at = { e: rest[ia].n, n: rest[ia + 1].n }; else bad.push('block at takes an easting and a northing'); }
      out.act = 'block';
      break;
    }
    case 'follow': out.act = 'follow'; out.arg = { step: ['next', 'back', 'play', 'pause', 'close'].find(has) || null }; break;
    case 'sld': out.act = 'sld'; out.arg = { on: !has('hide') }; break;
    case 'hud': out.act = 'hud'; out.arg = { rules: has('rules'), on: !has('off') }; break;
    case 'go': {
      const ib = after('block'), it = after('table');
      if (has('compound')) out.arg = { compound: true };
      else if (ib > 0 && isNum(rest[ib])) out.arg = { block: rest[ib].n, table: it > 0 && isNum(rest[it]) ? rest[it].n : null };
      else if (has('block') && it < 0) out.arg = { block: null, table: null };           // go block: the placed solar block
      else if (isNum(rest[0]) && isNum(rest[1])) out.arg = { e: rest[0].n, n: rest[1].n };
      else bad.push('go takes block N [table M], compound, or an easting and northing');
      out.act = 'go';
      break;
    }
    case 'earthing': case 'earth': case 'soil': case 'bonding': {
      if (v === 'soil' && isThermalSoil(rest)) { num(0, 'soil'); break; }     // soil N: thermal resistivity (cable rating)
      const e = parseEarth(v, rest, bad, w => example(COMMANDS.find(c => c.verb === v), w));
      if (e) { out.act = e.act; out.arg = e.arg; }
      break;
    }
    case 'show': case 'hide': {
      if (has('earthing')) { out.act = 'earthing'; out.arg = { what: v }; break; }
      const what = rest.find(x => ['pylons', 'water', 'slope', 'soil'].includes(x));
      if (!what) { bad.push(`${v} takes pylons, water, slope, soil or earthing`); break; }
      const pct = rest.find(isNum);
      if (pct && what === 'slope') { const g = guard('slope', pct.n); if (g) bad.push(g.replace('slope limit', 'slope shown from')); else out.arg.limit = pct.n; }
      out.act = 'show'; Object.assign(out.arg, { layer: what, on: v === 'show' });
      break;
    }
    case 'avoid': {
      if (has('slope')) { const n = rest.find(isNum); if (n) put('slope', n.n); else bad.push('avoid slope needs a percentage, such as avoid slope 15%'); }
      else if (has('pylons')) put('avoidOhl', !has('off'));
      else if (has('water')) { const n = rest.find(isNum); if (n) put('water', n.n); else bad.push('avoid water needs a setback in metres'); }
      else bad.push('avoid takes slope N%, pylons on|off or water N');
      break;
    }
    case 'setback': {
      const n = rest.find(isNum);
      if (!n) bad.push('setback needs metres, such as setback water 10');
      else if (has('water')) put('water', n.n);
      else if (has('fence')) put('fence', n.n);
      else if (has('hedge')) put('hedge', n.n);
      else bad.push('setback takes water or fence');
      break;
    }
    case 'binoculars': case 'zoom': case 'range': { const s = parseSenses(v, rest, bad); if (s) { out.act = s.act; out.arg = s.arg; } break; }
    case 'undo': out.act = 'undo'; break;
    case 'script': out.act = 'script'; break;
    case 'help': out.act = 'help'; out.arg = { topic: rest.filter(x => typeof x === 'string').join(' ') }; break;
  }
  if (bad.length) return refuse(bad.slice(0, 3).join('; ') + '. Nothing was changed.', line);
  return out;
}

/** Help text: every usage, or the commands matching a topic. */
export function help(topic = '') {
  const list = topic ? search(topic, 24) : COMMANDS;
  if (!list.length) return `No command matches "${topic}". Type help for all.`;
  return list.map(c => c.usage).join('\n');
}