GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609271740-site-world/world

Boq and 3 more files

A JavaScript module in the world folder of GlobalGrid2050 that converts to CSV (`toCsv`) and calculates planar distances, covering cables, overhead lines (OHL) and solar, using IEC 60287.

611 lines of JavaScript from globalgrid2050, in 4 files. Topic: Solar and storage design. Section 163 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. Boq render · globalgrid2050 / solar-design-studio/202609271740-site-world/world/boq.mjs lines 1–391
  2. Buffers UI ingest · globalgrid2050 / solar-design-studio/202609271740-site-world/world/buffers-ui.mjs lines 1–61
  3. Cmd Derive transform · globalgrid2050 / solar-design-studio/202609271740-site-world/world/cmd-derive.mjs lines 1–99
  4. Cmd Grammar Earth ingest · globalgrid2050 / solar-design-studio/202609271740-site-world/world/cmd-grammar-earth.mjs lines 1–60

Boq

A JavaScript module in the world folder of GlobalGrid2050 that converts to CSV (`toCsv`) and calculates planar distances, covering cables, overhead lines (OHL) and solar, using IEC 60287.

renderglobalgrid2050 / solar-design-studio/202609271740-site-world/world/boq.mjs · lines 1–391 of 391 · version 2026-09-27 17:40 · Not reached from any entry point (candidate for review) · pattern armouredOf (shared by 2 files)

What it does
It lists and searches cables, overhead lines (OHL) and solar. Defines 23 functions or classes, including num, fmt, planLength, bendCount, lengthOf. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'boq'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, overhead lines (OHL), solar, 33kV.
Inputs & outputs
Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Design Earthworks (globalgrid2050).
What it achieves
It is built from the num step (`num`), the fmt step (`fmt`) and the plan length helper (`planLength`). A bill of quantities from a design document. Its code works with 33 kV.
Why it matters
Imported by Design Earthworks.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Boq Assumptions (import)
Used by
imported by Design Earthworks (import)
Produces
STATUSES, buildBoq, toCsv
Defines here
num, fmt, planLength, bendCount, lengthOf, weakest, armouredOf, cableRows, trenchRows, roadRows, padRows, fenceRows, hddRows, pileRows, ohlRows, n, trenchPlanRows, rateOf, buildBoq, skip, add, cell, toCsv
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/boq.mjs:1-391 · blob 144f838f33337d17748f71fb4d8e01bf8363092d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
// boq.mjs: a bill of quantities from a design document.
//
// buildBoq(doc, { sections, cables, rates, currency }) -> { rows, skipped, total }
//   doc       { items: [{ id, kind, ...parameters, results }] }, kind one of
//             cable, trench, road, pad, fence, hdd, piles. `results` holds what
//             the design tools computed: routeCable / cableSummary for a cable,
//             trenchSummary for a trench, cutFillForPlatform for a pad, and
//             { length2d, length3d, area } style numbers for the rest.
//   sections  parsed web/world/data/trench-sections.json (needed for trenches)
//   cables    parsed web/world/data/cables.json (optional, resolves cableId)
// A cable is billed on its identity: cableId, or else voltageKv + csaMm2 + conductor + armoured all given.
// A cable with neither is skipped with a reason, never summed into an assumed row. A cable item may carry
// trench: { sectionId, results } for the trench cut for it; that trench is billed as a trench item.
//   rates     optional { [code]: number | { rate, unit } } supplied by the user.
//             With no rates, no money appears anywhere in the output.
//
// Every row: { code, description, unit, quantity, status, basis, sources }.
// status is one of
//   computed   measured from design geometry and values the design supplied
//   estimated  derived from design results by a stated simplification
//   assumed    rests on a default from boq-assumptions.mjs the design did not set
// Rows with the same code are summed; the merged status is the weakest one.
//
// toCsv(boq) -> CSV text: the disclaimer line, then the column header. Pure: no DOM, no fetch.

import { CABLE_DEFAULTS, CABLE_ALLOWANCES, ROAD_BUILD_UPS, FENCE_DEFAULTS, BEDDING_DEFAULTS, BASIS, DISCLAIMER } from './boq-assumptions.mjs';

const GROUND = `ground ${BASIS.ground}, levels in ${BASIS.datum}`;

export const STATUSES = ['computed', 'estimated', 'assumed'];
const RANK = { computed: 0, estimated: 1, assumed: 2 };
const num = (v) => (v != null && v !== '' && Number.isFinite(Number(v)) ? Number(v) : null);
const fmt = (x, dp = 2) => Number(x.toFixed(dp)).toString();

function planLength(path) {
  let s = 0;
  for (let k = 1; k < (path || []).length; k++) s += Math.hypot(path[k][0] - path[k - 1][0], path[k][1] - path[k - 1][1]);
  return s;
}

function bendCount(path) {
  let n = 0;
  for (let i = 1; i < (path || []).length - 1; i++) {
    const [a, b, c] = [path[i - 1], path[i], path[i + 1]];
    const cr = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]);
    const dot = (b[0] - a[0]) * (c[0] - b[0]) + (b[1] - a[1]) * (c[1] - b[1]);
    if (Math.abs(Math.atan2(cr, dot)) > 1e-6) n++;
  }
  return n;
}

// Best length an item offers: true 3D first, then plan, then its own path.
function lengthOf(item) {
  const r = item.results || {};
  const l3 = num(r.length3d) ?? num(r.boreLength);
  if (l3 != null) return { value: l3, status: 'computed', basis: 'true 3D length from design results' };
  const l = num(r.length);
  if (l != null) return { value: l, status: 'computed', basis: 'length from design results' };
  const l2 = num(r.length2d);
  if (l2 != null) return { value: l2, status: 'estimated', basis: 'plan length; no ground model, slope not included' };
  if (Array.isArray(item.path) && item.path.length > 1) {
    return { value: planLength(item.path), status: 'estimated', basis: 'plan length of the drawn path; slope not included' };
  }
  return null;
}

const weakest = (...s) => s.reduce((a, b) => (RANK[b] > RANK[a] ? b : a), 'computed');

// ---------------------------------------------------------------- by kind

const armouredOf = (id) => /armour/i.test(id || '') && !/unarmour/i.test(id || '');

function cableRows(item, ctx, add, skip) {
  if (item.trench) trenchRows({ id: `${item.id ?? 'cable'}-trench`, kind: 'trench', ...item.trench }, ctx, add, skip);
  let { voltageKv, csaMm2, conductor, armoured } = item;
  let code, name;
  if (item.cableId) {
    const c = ctx.cables ? (ctx.cables.cables || []).find((k) => k.id === item.cableId) : null;
    if (ctx.cables && !c) return skip(item, `unknown cableId ${item.cableId}`);
    if (c) { voltageKv ??= c.voltage_kv; csaMm2 ??= c.csa_mm2; conductor ??= c.conductor; }
    armoured ??= armouredOf(item.cableId);
    code = `CAB-${item.cableId}`;
    name = item.cableId;
  } else {
    if (voltageKv == null || csaMm2 == null || !conductor || typeof armoured !== 'boolean') {
      return skip(item, 'no cable identity: give cableId, or voltageKv, csaMm2, conductor and armoured');
    }
    code = `CAB-${voltageKv}KV-${conductor}-${csaMm2}-${armoured ? 'ARM' : 'UNARM'}`.toUpperCase();
    name = code.slice(4);
  }
  const r = item.results || {};
  const circuits = num(item.circuits) ?? 1;
  const cores = Array.isArray(r.cores) && r.cores.every((c) => num(c.length3d) != null) ? r.cores : null;
  const perCircuit = num(item.coresPerCircuit) ?? (cores ? cores.length : null);
  const nCores = perCircuit ?? CABLE_DEFAULTS.coresPerCircuit;
  const coreNote = perCircuit != null ? `${nCores} cores per circuit` : `${nCores} cores per circuit (assumed)`;
  let laid, status, basis;
  if (cores && perCircuit === cores.length) {
    laid = cores.reduce((s, c) => s + c.length3d, 0) * circuits;
    status = 'computed';
    basis = `sum of true 3D core axis lengths x ${circuits} circuit(s)`;
  } else {
    const L = lengthOf(item);
    if (!L) return skip(item, 'no route length in results');
    laid = L.value * nCores * circuits;
    status = weakest(L.status, perCircuit != null ? 'computed' : 'assumed');
    basis = `${L.basis} x ${coreNote} x ${circuits} circuit(s)`;
  }
  const kv = voltageKv != null ? `${voltageKv} kV` : 'voltage not given';
  const size = csaMm2 != null ? `${csaMm2} mm²` : 'size not given';
  const kind = `${kv} ${conductor || 'conductor not given'} ${size} ${armoured ? 'armoured' : 'unarmoured'} (${name})`;
  add({ code, description: `Cable ${kind}, laid length`, unit: 'm', quantity: laid, status, basis, rateKey: code }, item);

  const a = item.allowances || {};
  const slackPct = num(a.slackPct) ?? CABLE_DEFAULTS.slackPct;
  const { snakingPct: S, terminationM: T } = CABLE_ALLOWANCES;
  const termM = num(a.terminationM) ?? CABLE_DEFAULTS.terminationM;
  const given = num(a.slackPct) != null && num(a.terminationM) != null;
  const allowance = laid * slackPct / 100 + termM * 2 * nCores * circuits;
  add({
    code: `${code}-ALLOW`, description: `Cable ${kind}, allowances`, unit: 'm', quantity: allowance,
    status: given ? status : 'assumed', rateKey: code,
    basis: `slack ${slackPct} % of laid length${num(a.slackPct) != null ? '' : ` (assumed ${S.unit})`} + ${termM} m tail per core per end`
      + `${num(a.terminationM) != null ? '' : ' (assumed)'}; same allowances as the drum schedule`,
  }, item);
}

function trenchRows(item, ctx, add, skip) {
  const sec = (ctx.sections?.sections || []).find((s) => s.id === item.sectionId);
  if (!sec) return skip(item, item.sectionId ? `unknown sectionId ${item.sectionId}` : 'no sectionId');
  const r = item.results || {};
  const L = lengthOf(item);
  if (!L) return skip(item, 'no trench length in results');
  const width = num(r.width) ?? sec.trench_width_m;
  const depth = num(r.depth) ?? sec.trench_depth_m;
  const tag = `TR-${sec.id}`;
  add({ code: `${tag}-LEN`, description: `Trench ${sec.id} (${sec.voltage_class}), length`, unit: 'm', quantity: L.value, status: L.status, basis: L.basis }, item);

  const spoil = num(r.spoil) ?? num(r.spoilVolumeM3);
  add(spoil != null
    ? { code: `${tag}-SPOIL`, description: `Trench ${sec.id}, excavated spoil (bank volume)`, unit: 'm³', quantity: spoil,
        status: 'computed',
        basis: `cut volume against the ground model (${GROUND}); ${BASIS.spoil}` }
    : { code: `${tag}-SPOIL`, description: `Trench ${sec.id}, excavated spoil (bank volume)`, unit: 'm³', quantity: L.value * width * depth,
        status: 'estimated',
        basis: `length x ${width} m wide x ${depth} m deep; vertical walls; ${BASIS.spoil}` }, item);

  const t = num(sec.bedding?.thickness_mm);
  if (t != null) {
    const trefoil = /trefoil/i.test(sec.formation || '');
    const unit = num(sec.duct_od_mm) ?? num(sec.phase_spacing_mm);
    const env = unit != null ? (trefoil ? unit * (1 + Math.sqrt(3) / 2) : unit) : BEDDING_DEFAULTS.envelopeMm;
    const envNote = unit != null ? `${fmt(env, 0)} mm ${trefoil ? 'trefoil' : 'single layer'} envelope` : `${env} mm envelope (assumed)`;
    add({
      code: `${tag}-BED`, description: `Trench ${sec.id}, bedding: ${sec.bedding.material}`, unit: 'm³',
      quantity: L.value * width * (2 * t + env) / 1000, status: unit != null ? 'estimated' : 'assumed',
      basis: `length x ${width} m x (${t} mm bed + ${envNote} + ${t} mm above); gross, cable and duct volume not deducted`,
    }, item);
  }
  const m = sec.marker?.type || '';
  if (m) {
    const count = /each/i.test(m) ? (num(sec.circuits) ?? 1) : 1;
    const tape = /tape/i.test(m);
    add({
      code: `${tag}-${tape ? 'TAPE' : 'TILE'}`, description: `Trench ${sec.id}, ${tape ? 'warning tape' : 'protection tile'}`,
      unit: 'm', quantity: L.value * count, status: L.status,
      basis: `trench length x ${count} run(s): ${m}`,
    }, item);
  }
}

function roadRows(item, ctx, add, skip) {
  const r = item.results || {};
  const custom = Array.isArray(item.buildUp) && item.buildUp.length ? item.buildUp : null;
  const surface = item.surface || 'unbound';
  const std = ROAD_BUILD_UPS[surface];
  if (!custom && !std) return skip(item, `unknown surface ${surface}; supply buildUp`);
  let area = num(r.area), aStatus = 'computed', aBasis = 'plan area from design results';
  if (area == null) {
    const L = lengthOf(item), w = num(item.widthM) ?? num(r.width);
    if (!L || w == null) return skip(item, 'no road area, or length and widthM');
    area = L.value * w; aStatus = L.status; aBasis = `${L.basis} x ${w} m wide`;
  }
  const tag = `RD-${surface.toUpperCase()}`;
  add({ code: `${tag}-AREA`, description: `Road, ${custom ? surface : std.label}, area`, unit: 'm²', quantity: area, status: aStatus, basis: aBasis }, item);
  const layers = custom || std.layers;
  layers.forEach((ly, i) => {
    const key = ly.key || `L${i + 1}`;
    const assumed = !custom || ly.assumed === true;
    add({
      code: `${tag}-${key}`, description: `Road, ${ly.material}`, unit: 'm³', quantity: area * ly.thicknessMm / 1000,
      status: assumed ? 'assumed' : aStatus,
      basis: `area x ${ly.thicknessMm} mm${assumed ? ' (assumed build-up, as road.mjs draws it)' : ' (design build-up)'}; compacted volume`,
    }, item);
  });
  const lvl = `formation under the finished road; ${GROUND}`;
  if (num(r.cutM3) != null) add({ code: `${tag}-CUT`, description: 'Road, cut to formation', unit: 'm³', quantity: num(r.cutM3),
    status: 'computed', basis: `cut against the ground model to the ${lvl}; ${BASIS.spoil}; batters at assumed slopes` }, item);
  if (num(r.fillM3) != null) add({ code: `${tag}-FILL`, description: 'Road, fill to formation', unit: 'm³', quantity: num(r.fillM3),
    status: 'computed', basis: `fill against the ground model to the ${lvl}; compacted, no shrinkage factor; batters at assumed slopes` }, item);
  if (!custom && std.geotextile) {
    add({ code: `${tag}-GEOTEX`, description: 'Road, separation geotextile', unit: 'm²', quantity: area, status: 'assumed', basis: 'area, no laps (assumed build-up)' }, item);
  }
}

function padRows(item, ctx, add, skip) {
  const r = item.results || {};
  const area = num(r.polygonArea) ?? num(r.area);
  if (area == null && num(r.cut) == null) return skip(item, 'no pad results');
  const tag = `PAD-${item.id}`;
  if (area != null) add({ code: `${tag}-AREA`, description: `Pad ${item.id}, plan area`, unit: 'm²', quantity: area, status: 'computed', basis: 'polygon area' }, item);
  const lvl = num(r.level) != null ? ` to level ${fmt(r.level, 3)} m above Ordnance Datum Newlyn` : '';
  if (num(r.cut) != null) add({ code: `${tag}-CUT`, description: `Pad ${item.id}, cut`, unit: 'm³', quantity: r.cut,
      status: 'computed',
      basis: `cut against the ground model${lvl} (${GROUND}); ${BASIS.spoil}` }, item);
  if (num(r.fill) != null) add({ code: `${tag}-FILL`, description: `Pad ${item.id}, fill`, unit: 'm³', quantity: r.fill,
      status: 'computed',
      basis: `fill against the ground model${lvl} (${GROUND}); compacted, no shrinkage factor` }, item);
  const th = num(item.thicknessM);
  if (th != null && area != null) {
    const mat = item.material || 'pad construction';
    // The thickness is a design choice the tools assume (pad.mjs stone depth); billed as assumed unless the
    // item says thicknessAssumed: false.
    const given = item.thicknessAssumed === false;
    add({ code: `${tag}-SLAB`, description: `Pad ${item.id}, ${mat}`, unit: 'm³', quantity: area * th, status: given ? 'computed' : 'assumed',
      basis: `area x ${th} m thick${given ? ' (design thickness)' : ' (assumed thickness)'}` }, item);
  }
}

function fenceRows(item, ctx, add, skip) {
  const L = lengthOf(item);
  if (!L) return skip(item, 'no fence length');
  const spacing = num(item.postSpacingM) ?? FENCE_DEFAULTS.postSpacingM;
  const runs = num(item.runs) ?? 1;
  const bends = num(item.results?.bends?.length) ?? bendCount(item.path);
  const tag = `FEN-${item.fenceType || 'STD'}`.toUpperCase();
  add({ code: `${tag}-LEN`, description: `Fence${item.fenceType ? ` ${item.fenceType}` : ''}, length`, unit: 'm', quantity: L.value, status: L.status, basis: L.basis }, item);
  // The fence tool's own counts win: they are what the readout shows (code review 4).
  const c = item.results?.counts;
  if (c && num(c.posts) != null) {
    add({ code: `${tag}-POST`, description: 'Fence, posts (all)', unit: 'nr', quantity: c.posts, status: 'computed',
      basis: `counted by the fence tool: ${num(c.cornerPosts) ?? 0} corner, ${num(c.gatePosts) ?? 0} gate` }, item);
    if (num(c.strainers)) add({ code: `${tag}-STRAIN`, description: 'Fence, straining posts', unit: 'nr', quantity: c.strainers, status: 'computed', basis: 'counted by the fence tool' }, item);
    if (num(c.struts)) add({ code: `${tag}-STRUT`, description: 'Fence, struts', unit: 'nr', quantity: c.struts, status: 'computed', basis: 'counted by the fence tool' }, item);
    const g = num(item.gates);
    if (g) add({ code: `${tag}-GATE`, description: 'Fence, gates', unit: 'nr', quantity: g, status: 'computed', basis: 'count from design' }, item);
    return;
  }
  const perRun = Math.ceil(L.value / runs / spacing - 1e-9) + 1;
  add({
    code: `${tag}-POST`, description: 'Fence, line posts', unit: 'nr', quantity: perRun * runs,
    status: num(item.postSpacingM) != null ? L.status : 'assumed',
    basis: `ceil(length / ${spacing} m) + 1 per run, ${runs} run(s)${num(item.postSpacingM) != null ? '' : ' (assumed spacing)'}`,
  }, item);
  add({
    code: `${tag}-STRAIN`, description: 'Fence, straining posts', unit: 'nr', quantity: 2 * runs + bends,
    status: 'assumed', basis: `one at each run end and each of ${bends} bend(s); counted among the line posts (assumed practice)`,
  }, item);
  const gates = num(item.gates);
  if (gates) add({ code: `${tag}-GATE`, description: 'Fence, gates', unit: 'nr', quantity: gates, status: 'computed', basis: 'count from design' }, item);
}

function hddRows(item, ctx, add, skip) {
  const L = lengthOf(item);
  if (!L) return skip(item, 'no bore length');
  add({ code: 'HDD-BORE', description: 'Horizontal directional drill, bore length', unit: 'm', quantity: L.value, status: L.status, basis: L.basis }, item);
  const ducts = num(item.ducts);
  if (ducts) {
    const od = num(item.ductOdMm);
    add({ code: `HDD-DUCT${od ? `-${od}` : ''}`, description: `HDD duct${od ? ` ${od} mm OD` : ''}`, unit: 'm', quantity: L.value * ducts,
        status: L.status,
        basis: `bore length x ${ducts} duct(s)` }, item);
  }
}

function pileRows(item, ctx, add, skip) {
  const r = item.results || {};
  const count = num(r.count) ?? num(item.count) ?? (Array.isArray(item.points) ? item.points.length : null);
  if (count == null) return skip(item, 'no pile count');
  const type = item.pileType || 'STD';
  add({ code: `PIL-${type}`.toUpperCase(), description: `Piles${item.pileType ? ` ${item.pileType}` : ''}, count`, unit: 'nr', quantity: count,
    status: 'computed', basis: 'count from design' }, item);
  const emb = num(r.totalEmbedmentM) ?? (num(item.embedmentM) != null ? count * item.embedmentM : null);
  // Embedment is provisional until pile load tests set it, so the embedded and total lengths are 'assumed'.
  if (emb != null) add({ code: `PIL-${type}-EMB`.toUpperCase(), description: 'Piles, total embedded length (embedment provisional)', unit: 'm',
      quantity: emb, status: 'assumed',
      basis: num(r.totalEmbedmentM) != null ? 'sum from design results; embedment assumed' : `count x ${item.embedmentM} m` }, item);
  const len = num(r.totalPileLengthM);
  if (len != null) add({ code: `PIL-${type}-M`.toUpperCase(), description: 'Piles, total length (reveal + embedment, provisional)', unit: 'm',
      quantity: len, status: 'assumed', basis: 'sum from design results; embedment assumed' }, item);
}

// Overhead line zone conflicts (ohl-zones.mjs), one item per design item flagged: { id, kind: 'ohlZone', zone, height,
// goalposts } counts. Listed so the bill carries them; illustrative, on assumed tower heights and sag.
function ohlRows(item, ctx, add) {
  const basis = 'illustrative: tower heights and sag assumed; HSE GS6 paragraphs 11, 19 and 25';
  const n = k => num(item[k]) ?? 0;
  if (n('zone')) add({ code: 'OHL-ZONE', description: 'Overhead line zone conflicts: plan the work under GS6 with the network operator',
    unit: 'nr', quantity: n('zone'), status: 'estimated', basis }, item);
  if (n('height')) add({ code: 'OHL-HEIGHT', description: 'Working height reaches an overhead line exclusion distance (height user-set)',
    unit: 'nr', quantity: n('height'), status: 'estimated', basis }, item);
  if (n('goalposts')) add({ code: 'OHL-GOAL', description: 'Goalpost crossing points under overhead lines, suggested (HSE GS6 paragraphs 21 and 22)',
    unit: 'nr', quantity: n('goalposts'), status: 'estimated', basis }, item);
}

// Trenches sized by rating (trench-plan.mjs, the solar block): { stages: { dc|ac|mv: { trenchM, dugM3, beddingM3, pits, joints } } }.
function trenchPlanRows(item, ctx, add) {
  const basis = 'sized by rating, IEC 60287 method (own code); indicative', name = { dc: 'DC', ac: 'LV AC', mv: '33 kV' };
  for (const [k, s] of Object.entries(item.stages || {})) {
    const up = k.toUpperCase(), what = `${name[k] || k} trench`;
    if (num(s.trenchM)) add({ code: `TP-${up}-LEN`, description: `${what}, sized by rating (each trench of a split run counted)`, unit: 'm', quantity: s.trenchM, status: 'estimated', basis }, item);
    if (num(s.dugM3)) add({ code: `TP-${up}-DIG`, description: `${what}: excavation, bank volume`, unit: 'm³', quantity: s.dugM3, status: 'estimated', basis }, item);
    if (num(s.beddingM3)) add({ code: `TP-${up}-BED`, description: `${what}: bedding and surround`, unit: 'm³', quantity: s.beddingM3, status: 'estimated', basis }, item);
    if (num(s.pits)) add({ code: 'TP-PIT', description: 'Draw pits where ducts turn or the pull reaches its limit', unit: 'nr', quantity: s.pits, status: 'estimated', basis }, item);
    if (num(s.joints)) add({ code: 'TP-JOINT', description: 'Joint bays at drum lengths', unit: 'nr', quantity: s.joints, status: 'estimated', basis }, item);
  }
}

const KINDS = { cable: cableRows, trench: trenchRows, road: roadRows, pad: padRows, fence: fenceRows, hdd: hddRows, piles: pileRows,
  ohlZone: ohlRows, trenchPlan: trenchPlanRows };

// ---------------------------------------------------------------- build

function rateOf(rates, code, unit) {
  if (!rates || !(code in rates)) return null;
  const v = rates[code];
  const rate = typeof v === 'object' && v !== null ? num(v.rate) : num(v);
  if (rate == null) throw new Error(`boq: rate for ${code} is not a number`);
  if (typeof v === 'object' && v.unit && v.unit !== unit) throw new Error(`boq: rate for ${code} is per ${v.unit}, row is in ${unit}`);
  return rate;
}

export function buildBoq(doc, { sections = null, cables = null, rates = null, currency = null } = {}) {
  if (!doc || !Array.isArray(doc.items)) throw new Error('buildBoq: doc.items must be an array');
  const byCode = new Map(), skipped = [];
  const skip = (item, reason) => skipped.push({ id: item.id ?? null, kind: item.kind ?? null, reason });
  const add = (row, item) => {
    const prev = byCode.get(row.code);
    const id = item.id ?? `(${item.kind})`;
    if (!prev) { byCode.set(row.code, { ...row, rateKey: row.rateKey || row.code, sources: [id], bases: [row.basis] }); return; }
    if (prev.unit !== row.unit) throw new Error(`boq: ${row.code} mixes ${prev.unit} and ${row.unit}`);
    prev.quantity += row.quantity;
    prev.status = weakest(prev.status, row.status);
    if (!prev.sources.includes(id)) prev.sources.push(id);
    if (!prev.bases.includes(row.basis)) prev.bases.push(row.basis);
  };
  const ctx = { sections, cables };
  for (const item of doc.items) {
    const fn = KINDS[item?.kind];
    if (!fn) { skip(item || {}, `unknown kind ${item?.kind}`); continue; }
    fn(item, ctx, add, skip);
  }
  const rows = [...byCode.values()].map(({ bases, rateKey, ...r }) => {
    const row = { ...r, basis: bases.join('; ') };
    if (rates) {
      const rate = rateOf(rates, r.code, r.unit) ?? rateOf(rates, rateKey, r.unit);
      row.rate = rate;
      row.amount = rate == null ? null : rate * r.quantity;
    }
    return row;
  });
  const out = { rows, skipped };
  if (rates) {
    out.currency = currency;
    out.total = rows.reduce((s, r) => s + (r.amount ?? 0), 0);
    out.unrated = rows.filter((r) => r.rate == null).map((r) => r.code);
  }
  return out;
}

// ---------------------------------------------------------------- CSV

const DP = { m: 1, 'm²': 1, 'm³': 2, nr: 0 };
const cell = (v) => {
  const s = v == null ? '' : String(v);
  return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};

export function toCsv(boq) {
  const priced = 'total' in boq;
  const head = ['code', 'description', 'unit', 'quantity', 'status', 'basis', 'sources'];
  if (priced) head.push(`rate${boq.currency ? ` (${boq.currency})` : ''}`, `amount${boq.currency ? ` (${boq.currency})` : ''}`);
  const lines = [cell(DISCLAIMER), head.map(cell).join(',')];
  for (const r of boq.rows) {
    const line = [r.code, r.description, r.unit, (r.quantity).toFixed(DP[r.unit] ?? 2), r.status, r.basis, r.sources.join(' ')];
    if (priced) line.push(r.rate == null ? 'no rate' : r.rate, r.amount == null ? '' : r.amount.toFixed(2));
    lines.push(line.map(cell).join(','));
  }
  if (priced) lines.push(['TOTAL', 'Total of rated rows only', '', '', '', '', '', '', boq.total.toFixed(2)].map(cell).join(','));
  return lines.join('\r\n') + '\r\n';
}

Buffers UI

A JavaScript module in the world folder of GlobalGrid2050 that fetches cables, using SHA-256.

ingestglobalgrid2050 / solar-design-studio/202609271740-site-world/world/buffers-ui.mjs · lines 1–61 of 61 · version 2026-09-27 17:40 · Not reached from any entry point (candidate for review) · pattern loadWorldFiles (shared by 2 files)

What it does
It fetches cables. Defines 8 functions or classes, including worldFrom, drawnItems, local, loadWorldFiles, cfg. Side effects: makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): 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.
What it achieves
It loads world files (`loadWorldFiles`) and is built from the world from helper (`worldFrom`) and the drawn items helper (`drawnItems`). Page wiring for the Buffers layer.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Buffers (import), Layers (import)
Used by
none found
Produces
worldFrom, drawnItems, loadWorldFiles, mountBuffers
Defines here
worldFrom, drawnItems, local, loadWorldFiles, cfg, get, mountBuffers, refresh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/buffers-ui.mjs:1-61 · blob 667e8fbdf6595a1fdf1f3a00ac02868419e122aa · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Page wiring for the Buffers layer. While it is switched on, the zones are worked out (buffers.mjs) from the site's
// own data files, fetched through the same hash check as the layers that draw them (the manifest's configs for grid,
// water, ways and canopy hedges), and the drawn design is checked against them (clash.mjs). Zones are local metres,
// so they are rebuilt when the origin moves; clashes are rebuilt when a trench or cable is finished.
import { buildZones, checkClashes } from './buffers.mjs';
import { makeApi } from './layers.mjs';

// The world lists buildZones takes, from the files as the layers read them. Missing files give empty lists.
export function worldFrom({ grid, rivers, roads, hedges } = {}) {
  return {
    overhead: (grid?.lines || []).filter(l => Array.isArray(l.points)),
    water: (rivers?.lines || []).filter(l => Array.isArray(l.points)),
    roads: (roads?.lines || []).filter(l => Array.isArray(l.pts)),
    hedges: (hedges?.lines || []).filter(l => Array.isArray(l.pts)),
  };
}

// Drawn trenches and cables (national-grid paths [{ e, n }]) as clash items in local metres.
export function drawnItems(design, origin) {
  const local = path => (path || []).map(p => [p.e - origin.e, p.n - origin.n]);
  return [
    ...(design?.trenches || []).map((t, i) => ({ id: `trench-${i + 1}`, kind: 'trench', points: local(t.path) })),
    ...(design?.cables || []).map((c, i) => ({ id: `cable-${i + 1}`, kind: 'trench', points: local(c.path) })),
  ].filter(it => it.points.length >= 2);
}

// Fetches the site files named in the manifest; each one is checked against its SHA-256 before it is used.
export async function loadWorldFiles(manifestUrl, api = null) {
  const base = new URL(manifestUrl, location.href);
  const manifest = await (await fetch(base, { cache: 'no-cache' })).json();
  const a = api || makeApi(new URL('./', base).href);
  const cfg = id => (manifest.layers || []).find(l => l.id === id)?.config || null;
  const get = c => (c && (c.path || c.index) && c.sha256 ? a.fetchJSON(c.path || c.index, c.sha256).catch(() => null) : null);
  const canopy = cfg('canopy');
  const [grid, rivers, roads, canopyIndex] = await Promise.all([get(cfg('grid')), get(cfg('water')), get(cfg('ways')?.roads), get(canopy)]);
  let hedges = null;
  if (canopyIndex?.hedges?.file && canopyIndex.hedges.sha256) {
    const dir = canopy.index.slice(0, canopy.index.lastIndexOf('/') + 1);
    hedges = await a.fetchJSON(dir + canopyIndex.hedges.file, canopyIndex.hedges.sha256).catch(() => null);
  }
  return { grid, rivers, roads, hedges };
}

// layer: the buffers layer object. origin(): { e, n, id }. design(): the design in memory. load(): the world files.
// Returns { refresh(on) }: call it after the layer is switched and on a steady tick.
export function mountBuffers({ layer, origin, design, designVersion = null, load = () => loadWorldFiles('./world/manifest.json') } = {}) {
  if (!layer || typeof layer.setZones !== 'function') return null;
  let files = null, loading = null, zonesKey = '', clashKey = '', zones = [], seen = null;
  const refresh = on => {
    if (!on) return;
    if (!files) { loading ||= Promise.resolve().then(load).then(f => { files = f; refresh(true); }, e => console.warn('buffers: ' + e.message)); return; }
    const o = origin(), zk = `${o.e},${o.n}`, dv = designVersion?.();
    if (dv != null && zk === zonesKey && `${zk}@${dv}` === seen) return;  // nothing changed: no copy of the design (PERF.md 2)
    seen = dv == null ? null : `${zk}@${dv}`;
    const d = design();
    if (zk !== zonesKey) { zones = buildZones(worldFrom(files), { origin: o }); layer.setZones(zones); zonesKey = zk; clashKey = ''; }
    const ck = `${zk}@${d.trenches.length}@${d.cables.length}`;
    if (ck !== clashKey) { layer.setClashes(checkClashes(drawnItems(d, o), zones)); clashKey = ck; }
  };
  return { refresh };
}

Cmd Derive

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

transformglobalgrid2050 / solar-design-studio/202609271740-site-world/world/cmd-derive.mjs · lines 1–99 of 99 · version 2026-09-27 17:40 · 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 (path word 'design'): 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 2 files: Cmd Model (globalgrid2050); Cmd Run (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (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 and Cmd Run.
Application
globalgrid2050 · solar-design-studio/202609271740-site-world/world · JavaScript module
Uses
Module Catalogue (import)
Used by
imported by Cmd Model (import), imported by Cmd Run (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 solar-design-studio/202609271740-site-world/world/cmd-derive.mjs:1-99 · blob 8b3cb3dbf647d2f4b7fcf7f94d857d723e21e37b · 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: production_core
// 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 world folder of GlobalGrid2050 covering cables.

ingestglobalgrid2050 / solar-design-studio/202609271740-site-world/world/cmd-grammar-earth.mjs · lines 1–60 of 60 · version 2026-09-27 17:40 · 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 sub33kv_design (path word 'design'): 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.
Downstream impact
Used directly by 1 file: Cmd Grammar (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (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 · solar-design-studio/202609271740-site-world/world · 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 solar-design-studio/202609271740-site-world/world/cmd-grammar-earth.mjs:1-60 · blob 0c8ba71512223c7f446770a792604fcd85e0f082 · 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: production_core
// 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;
}