GLOBALGRID2050 / EXPLORE CODE

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

Build Rules and 3 more files

A JavaScript module in the world folder of GlobalGrid2050 that works with overhead lines (OHL), using IEC 62548-1. It checks placement (`checkPlacement`) and builds checks (`buildChecks`).

477 lines of JavaScript from globalgrid2050, in 4 files. Topic: Solar and storage design. Section 177 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. Build Rules transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/build-rules.mjs lines 1–198
  2. Build UI interaction · globalgrid2050 / solar-design-studio/202609271853-site-world/world/build-ui.mjs lines 1–198
  3. Cmd Grammar Plant ingest · globalgrid2050 / solar-design-studio/202609271853-site-world/world/cmd-grammar-plant.mjs lines 1–58
  4. Cmd Grammar Senses ingest · globalgrid2050 / solar-design-studio/202609271853-site-world/world/cmd-grammar-senses.mjs lines 1–23

Build Rules

A JavaScript module in the world folder of GlobalGrid2050 that works with overhead lines (OHL), using IEC 62548-1. It checks placement (`checkPlacement`) and builds checks (`buildChecks`).

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/build-rules.mjs · lines 1–198 of 198 · version 2026-09-27 18:53 · pattern buildChecks (shared by 2 files)

What it does
It calculates overhead lines (OHL). Defines 19 functions or classes, including r1, tableOf, snap, rectOf, overlaps.
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: overhead lines (OHL).
Downstream impact
Used directly by 2 files: Build Geom (globalgrid2050); Build UI (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
Build mode's rules. Real components snap to a grid over the measured ground and click together only where the engineering allows; every refusal is a plain sentence that says what to change. Its code works with 300 kVA.
Why it matters
Imported by Build Geom and Build UI.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Plant Layout (import), String Design (import)
Used by
imported by Build Geom (import), imported by Build UI (import)
Produces
BUILD_NOTE, DEFAULTS, PIECES, tableOf, snap, rectOf, slopeOver, rectToZone, checkPlacement, labelOf, typedOf, wire
Defines here
r1, tableOf, snap, rectOf, overlaps, slopeOver, m, segSeg, o, ptSeg, inPoly, rectToZone, checkPlacement, labelOf, typedOf, wire, route, statusWords, buildChecks
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/202609271853-site-world/world/build-rules.mjs:1-198 · blob 271839b571b04e6ca461daf1f8ec0b8d4241edd0 · 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
// build-rules.mjs: build mode's rules. Real components snap to a grid over the measured ground and click together
// only where the engineering allows; every refusal is a plain sentence that says what to change. Pure: no DOM, no fetch.
//
// Pieces: a TABLE (2P portrait, south-facing, 28 modules a row, the plant layout's own geometry: plant-layout.mjs) and a
// string INVERTER (generic, assumed: 300 kVA as plant-template.mjs, 12 MPPT inputs taking 2 strings each; not a product).
// Rules at placement: measured ground under it; ground no steeper than the slope limit (LAYOUT_DEFAULTS, 15 %, editable);
// outside every overhead line zone (ohl-ui.mjs zonesEN, HSE GS6 reach); no overlap. Strings wire themselves: a table joins
// the nearest inverter with enough free MPPT inputs, or stays unconnected and is said to. The DC trench at each inverter
// must be wide enough for its ducts (station.mjs: 90 mm ducts, 6 strings a duct; the owner's block section is 0.55 m for
// four). Positions are national-grid metres (e, n). Illustrative: early design, estimates only.

import { tableGeometry, LAYOUT_DEFAULTS } from './plant-layout.mjs';
import { stringDesign, stringLine, STRING_ADVICE, ILLUSTRATIVE } from './string-design.mjs';

export const BUILD_NOTE = `Illustrative, assumptions editable. ${ILLUSTRATIVE}`;
export const DEFAULTS = Object.freeze({
  mps: 28, columns: 28, moduleW: 660, moduleLongM: 2.384, moduleShortM: 1.303, // module class A of data/modules.json
  mppt: 12, perMppt: 2, inverterKVA: 300, slopePct: LAYOUT_DEFAULTS.slopeLimitPct, trenchW: 0.55,
  ductOdM: 0.09, ductGapM: 0.03, sideM: 0.05, stringsPerDuct: 6, gapM: LAYOUT_DEFAULTS.tableGapM
});
export const PIECES = Object.freeze({ table: 'Table', inverter: 'Inverter' });
const INV = { w: 1, d: 0.5 };                     // the pole inverter's box in plan (block-build.mjs)
const r1 = v => (Math.round(v * 10) / 10).toFixed(1), r0 = v => Math.round(v).toLocaleString('en-GB');

/** The table for these settings: plan length (east), depth (north), rise, row pitch, modules and strings. */
export function tableOf(P = DEFAULTS) {
  const T = tableGeometry('south', { ...LAYOUT_DEFAULTS, moduleLongM: P.moduleLongM, moduleShortM: P.moduleShortM },
    { counts: { modulesPerString: P.columns }, params: { moduleWp: P.moduleW } });
  const modules = 2 * P.columns, strings = Math.floor(modules / P.mps);
  return { len: T.lenU, depth: T.depth, rise: T.rise, pitch: T.pitch, lowEdge: LAYOUT_DEFAULTS.lowEdgeM, modules, strings,
    spare: modules - strings * P.mps, kWp: modules * P.moduleW / 1000, stepE: T.lenU + P.gapM, stepN: T.pitch };
}

/** Snaps a pointer at (e, n) to the piece's grid (anchored on national-grid multiples, so it never swims). */
export function snap(kind, e, n, P = DEFAULTS) {
  if (kind === 'inverter') return { e: Math.round(e), n: Math.round(n) };
  const T = tableOf(P);
  return { e: Math.round((e - T.len / 2) / T.stepE) * T.stepE, n: Math.round((n - T.depth / 2) / T.stepN) * T.stepN };
}
/** The plan rectangle [e0, n0, e1, n1]: a table from its south-west corner, an inverter round its centre. */
export function rectOf(it, P = DEFAULTS) {
  if (it.kind === 'inverter') return [it.e - INV.w / 2, it.n - INV.d / 2, it.e + INV.w / 2, it.n + INV.d / 2];
  const T = tableOf(P);
  return [it.e, it.n, it.e + T.len, it.n + T.depth];
}
const overlaps = (a, b) => a[0] < b[2] - 1e-6 && b[0] < a[2] - 1e-6 && a[1] < b[3] - 1e-6 && b[1] < a[3] - 1e-6;

// ---- ground: a least-squares plane over a grid of samples; NaN where any sample is not measured ----
export function slopeOver(rect, measured, nx = 5, ny = 3) {
  const pts = [];
  for (let i = 0; i < nx; i++) for (let j = 0; j < ny; j++) {
    const e = rect[0] + (rect[2] - rect[0]) * i / (nx - 1), n = rect[1] + (rect[3] - rect[1]) * j / (ny - 1), h = measured(e, n);
    if (!Number.isFinite(h)) return { measured: false, pct: NaN };
    pts.push([e - rect[0], n - rect[1], h]);
  }
  const m = k => pts.reduce((s, p) => s + p[k], 0) / pts.length, mx = m(0), my = m(1), mz = m(2);
  let sxx = 0, syy = 0, sxy = 0, sxz = 0, syz = 0;
  for (const [x, y, z] of pts) { const a = x - mx, b = y - my, c = z - mz; sxx += a * a; syy += b * b; sxy += a * b; sxz += a * c; syz += b * c; }
  const det = sxx * syy - sxy * sxy, gx = det ? (sxz * syy - syz * sxy) / det : 0, gy = det ? (syz * sxx - sxz * sxy) / det : 0;
  return { measured: true, pct: Math.hypot(gx, gy) * 100, fallsTo: Math.abs(gx) > Math.abs(gy) ? (gx > 0 ? 'west' : 'east') : (gy > 0 ? 'south' : 'north') };
}

// ---- overhead line zones: the distance from a rectangle to a zone's outline (0 when they touch or it lies inside) ----
const segSeg = (a, b, c, d) => {
  const o = (p, q, r) => Math.sign((q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]));
  return o(a, b, c) !== o(a, b, d) && o(c, d, a) !== o(c, d, b);
};
const ptSeg = (p, a, b) => {
  const dx = b[0] - a[0], dy = b[1] - a[1], L = dx * dx + dy * dy, k = L ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / L)) : 0;
  return Math.hypot(p[0] - a[0] - k * dx, p[1] - a[1] - k * dy);
};
const inPoly = (poly, [x, y]) => {
  let c = false;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const [xi, yi] = poly[i], [xj, yj] = poly[j];
    if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) c = !c;
  }
  return c;
};
export function rectToZone(rect, zone) {
  const q = [[rect[0], rect[1]], [rect[2], rect[1]], [rect[2], rect[3]], [rect[0], rect[3]]], pts = zone.pts || [];
  const edges = pts.slice(1).map((p, i) => [pts[i], p]).concat(zone.closed && pts.length > 2 ? [[pts[pts.length - 1], pts[0]]] : []);
  if (!pts.length) return Infinity;
  if (zone.closed && pts.length > 2 && inPoly(pts, [(rect[0] + rect[2]) / 2, (rect[1] + rect[3]) / 2])) return 0;
  if (pts.some(p => p[0] >= rect[0] && p[0] <= rect[2] && p[1] >= rect[1] && p[1] <= rect[3])) return 0;
  let d = Infinity;
  for (const [a, b] of edges.length ? edges : [[pts[0], pts[0]]]) {
    for (let i = 0; i < 4; i++) { const c = q[i], e = q[(i + 1) % 4]; if (segSeg(a, b, c, e)) return 0; d = Math.min(d, ptSeg(c, a, b), ptSeg(a, c, e), ptSeg(b, c, e)); }
  }
  return d;
}

/**
 * checkPlacement(kind, at, ctx) -> { ok, kind, at, rect, reasons: [sentence], notes: [sentence], slope }
 * ctx: { measured(e, n) (NaN where not measured), zones: { state: 'off' | 'none' | 'on', list: [{ pts, closed, reachM }] },
 *   items: [{ id, kind, e, n }], P }. `at` is already snapped.
 */
export function checkPlacement(kind, at, { measured = () => NaN, zones = { state: 'off', list: [] }, items = [], P = DEFAULTS } = {}) {
  const it = { kind, e: at.e, n: at.n }, rect = rectOf(it, P), reasons = [], notes = [], name = PIECES[kind] || kind;
  const s = slopeOver(rect, measured, kind === 'table' ? 5 : 3, 3);
  if (!s.measured) reasons.push(`The ground here is not measured (no LiDAR under it), so a ${name.toLowerCase()} can't be checked here. Move onto measured ground.`);
  else if (kind === 'table' && s.pct > P.slopePct + 1e-9) {
    reasons.push(`Ground here falls ${r1(s.pct)} % across the table (down to the ${s.fallsTo}); tables stand on ground up to ${r1(P.slopePct)} %. `
      + (s.pct <= 40 ? `Try flatter ground, or change the limit with: build slope ${Math.ceil(s.pct - 1e-6)}.` : 'That is too steep for any table; try flatter ground.'));
  } else if (kind === 'table') notes.push(`ground falls ${r1(s.pct)} %, limit ${r1(P.slopePct)} %`);
  if (zones.state === 'on') {
    for (const z of zones.list) {
      const d = rectToZone(rect, z);
      if (d <= z.reachM) {
        reasons.push(`Inside an overhead line's safety zone: this ${name.toLowerCase()} comes within ${r1(d)} m of the line, and its zone reaches `
          + `${r1(z.reachM)} m (HSE GS6). Nothing is built under or beside a live line here; move it clear.`);
        break;
      }
    }
  } else notes.push(zones.state === 'none' ? 'no overhead line in the loaded grid data here' : 'overhead line zones not checked: switch Grid on in Layers');
  const hit = items.find(o => overlaps(rect, rectOf(o, P)));
  if (hit) reasons.push(`It would overlap ${hit.kind} ${labelOf(hit, items)}. Pick an empty spot on the grid.`);
  return { ok: !reasons.length, kind, at: { e: at.e, n: at.n }, rect, reasons, notes, slope: s };
}
export const labelOf = (it, items) => items.filter(o => o.kind === it.kind).indexOf(it) + 1;
/** The typed line that places this piece. */
export const typedOf = it => `build ${it.kind} at ${Math.round(it.e * 100) / 100} ${Math.round(it.n * 100) / 100}`;

/**
 * wire(items, P) -> { tables: [{ id, inverter (index or null), strings, inputs, run: [[e, n]...], runM }], inverters: [{ id, inputs, strings,
 *   kWp, dcAc, ducts, widthNeedM }], strings, connected, unconnected, spareModules }
 * Each table, in the order placed, joins the nearest inverter (by its home run) that still has enough free MPPT inputs;
 * a table's strings stay on one inverter. Home runs leave the table end nearer the inverter, 1 m south in the aisle,
 * run east or west along it, then north or south to the inverter.
 */
export function wire(items, P = DEFAULTS) {
  const T = tableOf(P), invs = items.filter(i => i.kind === 'inverter'), tabs = items.filter(i => i.kind === 'table');
  const need = Math.ceil(T.strings / P.perMppt), free = invs.map(() => P.mppt), load = invs.map(() => ({ inputs: 0, strings: 0, tables: 0 }));
  const route = (t, v) => {
    const end = [Math.abs(t.e - v.e) < Math.abs(t.e + T.len - v.e) ? t.e : t.e + T.len, t.n - 1];
    const run = [end, [v.e, end[1]], [v.e, v.n]];
    return { run, runM: Math.abs(v.e - end[0]) + Math.abs(v.n - end[1]) };
  };
  const tables = tabs.map(t => {
    const opts = invs.map((v, k) => ({ k, ...route(t, v) })).filter(o => free[o.k] >= need && T.strings > 0).sort((a, b) => a.runM - b.runM || a.k - b.k);
    const o = opts[0];
    if (!o) return { id: t.id, inverter: null, strings: T.strings, inputs: need, run: null, runM: NaN };
    free[o.k] -= need; Object.assign(load[o.k], { inputs: load[o.k].inputs + need, strings: load[o.k].strings + T.strings, tables: load[o.k].tables + 1 });
    return { id: t.id, inverter: o.k, strings: T.strings, inputs: need, run: o.run, runM: o.runM };
  });
  const inverters = invs.map((v, k) => {
    const L = load[k], kWp = L.strings * P.mps * P.moduleW / 1000, ducts = Math.ceil(L.strings / P.stringsPerDuct);
    return { id: v.id, inputs: L.inputs, strings: L.strings, tables: L.tables, kWp, dcAc: kWp / P.inverterKVA, ducts,
      widthNeedM: ducts ? ducts * P.ductOdM + (ducts - 1) * P.ductGapM + 2 * P.sideM : 0 };
  });
  const strings = tabs.length * T.strings, connected = tables.filter(t => t.inverter !== null).reduce((s, t) => s + t.strings, 0);
  return { tables, inverters, strings, connected, unconnected: strings - connected, spareModules: tabs.length * T.spare, T };
}

/** The one-line status under the tools. */
export function statusWords(items, W, P = DEFAULTS) {
  const nt = items.filter(i => i.kind === 'table').length, ni = W.inverters.length;
  if (!items.length) return 'Nothing built yet. Choose Table, then click the ground.';
  const kWp = nt * W.T.kWp, runs = W.tables.map(t => t.runM).filter(Number.isFinite), inputs = W.inverters.map(v => `${v.inputs} of ${P.mppt}`).join(', ');
  return `${r0(nt)} table${nt === 1 ? '' : 's'} · ${r0(W.strings)} strings of ${P.mps} · ${r1(kWp)} kWp DC · ${ni} inverter${ni === 1 ? '' : 's'}`
    + (ni ? ` (inputs used ${inputs})` : ' (place an inverter to wire the strings)')
    + (W.unconnected ? ` · ${W.unconnected} strings unconnected` : '') + (runs.length ? ` · longest home run ${r0(Math.max(...runs))} m` : '');
}

/**
 * HUD checks for what was built, in hud-checks.mjs form: { id, failed, line, working: { inputs, standard, note }, always?, advice? }.
 * cat / cls: the module catalogue and class (data/modules.json); the string voltage is skipped until they load.
 */
export function buildChecks(items, W, P = DEFAULTS, { cat = null, cls = null } = {}) {
  const out = [], add = (id, failed, line, inputs, standard) => out.push({ id, failed: !!failed, line, working: { inputs, standard, note: BUILD_NOTE } });
  if (!items.some(i => i.kind === 'table')) return out;
  const sd = cls && cat ? stringDesign({ cls, cat, mps: P.mps, tempMinC: cat.coldest_cell_C }) : null;
  if (sd) {
    add('build-voc', !sd.ok, `BUILT ${stringLine(sd)}`, [['Modules in series', P.mps], ['Coldest cell', `${sd.tempMinC} °C`],
      ['String Voc', `${sd.stringV.toFixed(1)} V`], ['System voltage', `${sd.systemV} V`], ['Most in series here', sd.most], ['Change', 'build string N']],
      'IEC 62548-1 (array maximum voltage at the lowest expected cell temperature)');
    Object.assign(out.at(-1), { always: true, advice: STRING_ADVICE });
  }
  if (W.unconnected) {
    add('build-mppt', true, `${W.unconnected} BUILT STRINGS UNCONNECTED · NO FREE MPPT INPUT`, [['Strings built', W.strings], ['Connected', W.connected],
      ['Inverters', W.inverters.length], ['MPPT inputs each (assumed)', `${P.mppt} × ${P.perMppt} strings`],
      ['Inputs used', W.inverters.map(v => v.inputs).join(', ') || 'no inverter placed'], ['Fix', 'place another inverter nearer the red tables']],
      'IEC 62548-1 (strings connected only to inputs rated for them)');
  }
  const narrow = W.inverters.filter(v => v.ducts && P.trenchW < v.widthNeedM - 1e-9);
  if (narrow.length) {
    const v = narrow[0];
    add('build-trench', true, `DC TRENCH ${P.trenchW.toFixed(2)} M < ${v.widthNeedM.toFixed(2)} M FOR ${v.ducts} DUCTS AT INVERTER ${W.inverters.indexOf(v) + 1}`,
      [['Trench as set', `${P.trenchW} m (build trench W)`], ['Strings into this inverter', v.strings], ['Ducts', `${v.ducts} × ${P.ductOdM * 1000} mm, ${P.stringsPerDuct} strings a duct`],
        ['Width the ducts need', `${v.widthNeedM.toFixed(2)} m (ducts, ${P.ductGapM * 1000} mm between, ${P.sideM * 1000} mm each side)`]],
      'Rule of thumb from the owner\'s block DC section (0.55 m for four 90 mm ducts); not a standard');
  }
  if (W.spareModules) {
    add('build-spare', true, `${W.spareModules} BUILT MODULES IN NO STRING (${2 * P.columns} A TABLE, ${P.mps} IN SERIES)`,
      [['Modules a table', 2 * P.columns], ['Modules in series', P.mps], ['Left over a table', W.T.spare]], 'IEC 62548-1 (string design)');
  }
  return out;
}

Build UI

A JavaScript module in the world folder of GlobalGrid2050 that sets tool (`setTool`), shows ghost (`showGhost`) and calculates planar distances, covering overhead lines (OHL).

interactionglobalgrid2050 / solar-design-studio/202609271853-site-world/world/build-ui.mjs · lines 1–198 of 198 · version 2026-09-27 18:53 · pattern pilesAuto (shared by 2 files)

What it does
It draws overhead lines (OHL). Defines 23 functions or classes, including createBuild, o, measured, ground, zones. Side effects: changes the web page (DOM); 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: overhead lines (OHL).
Inputs & outputs
In: JSON file modules.json.
Downstream impact
Used directly by 1 file: Build Mount (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 creates build (`createBuild`), sets tool (`setTool`) and shows ghost (`showGhost`). Build mode on the page. Choose Table or Inverter; a ghost follows the pointer, snapped to the grid on the ground, outlined in green where it may go and red where it may not. It responds to click, pointermove and pointerdown events.
Why it matters
Imported by Build Mount.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Pick (import), Build Rules (import), Build Geom (import), Build Cmd (import), Cmd Run (dynamic import)
Used by
imported by Build Mount (dynamic import)
Produces
createBuild
Defines here
createBuild, o, measured, ground, zones, ctx, o3, batch, batches, changed, snapshot, remember, tell, setTool, place, showGhost, pointAt, local, exec, pilesAuto, script, replay, probe
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/202609271853-site-world/world/build-ui.mjs:1-198 · blob fc5c64f3e387a555a2ea889241c1a2183c186ac9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// build-ui.mjs: build mode on the page. Choose Table or Inverter; a ghost follows the pointer, snapped to the grid on the
// ground, outlined in green where it may go and red where it may not, and the bar under the view says why in plain words.
// A click (or tap) on a green ghost places it and writes its typed line; a tap on a red one only explains. Strings wire
// themselves (build-rules.mjs wire), "piles auto" piles what was built, and the check HUD shows the failed checks.
// Loaded the first time Place or a build line is used (build-mount.mjs). It draws nothing of its own: a frame is asked for
// only when the ghost's snapped cell or its verdict changes, or something is placed (0 fps when still).

import { rayFromScreen, pickGround } from './pick.mjs';
import { DEFAULTS, PIECES, snap, checkPlacement, wire, statusWords, buildChecks, typedOf, labelOf } from './build-rules.mjs';
import { sceneGroups, ghostGroup, builtPiles } from './build-geom.mjs';
import { parseBuild, settingLines } from './build-cmd.mjs';

const C = { tables: [0.62, 0.72, 0.86, 0.85], strings: [0.4, 0.62, 0.95, 0.8], loose: [1, 0.23, 0.19, 0.95], runs: [0.95, 0.8, 0.35, 0.8],
  inverters: [0.95, 0.97, 1, 1], ok: [0.35, 0.9, 0.5, 0.95], no: [1, 0.23, 0.19, 0.95], piles: [0.8, 0.8, 0.8, 0.9], flagged: [1, 0.55, 0.2, 1] };
const CSS = `#build-bar { position: fixed; left: 50%; transform: translateX(-50%); bottom: calc(var(--foot, 28px) + 8px); width: min(620px, calc(100vw - 16px));
  box-sizing: border-box; background: var(--panel, #111); border: 1px solid var(--edge, #333); border-radius: 6px; padding: 6px 8px; z-index: 3;
  display: flex; gap: 8px; align-items: flex-start; font: 12px/1.45 system-ui, sans-serif; color: var(--text, #ddd); }
#build-bar[hidden], body[data-cmd] #build-bar { display: none; }
#build-bar p { margin: 0; flex: 1; } #build-bar .no { color: #ff8a7a; } #build-bar .ok { color: #8fe0a3; }
#build-bar button { flex: none; background: none; color: var(--dim, #aaa); border: 1px solid var(--edge, #333); border-radius: 4px; min-height: 28px; padding: 0 10px; cursor: pointer; }`;
const CLICK_PX = 6;

// deps: { api (substrate extension api), world (window.world), ohl ({ layer } from ohl-ui.mjs), doc, row (the Place row, or null) }
export function createBuild({ api, world, ohl = null, doc = document, row = null }) {
  const S = { tool: null, items: [], undo: [], P: { ...DEFAULTS }, ghost: null, ghostKey: '', v: 0, piles: null, cat: null, cls: null, next: 1,
    wired: null, say: '', sayOk: true };
  const canvas = api.canvas;
  if (!doc.getElementById('build-style')) { const s = doc.createElement('style'); s.id = 'build-style'; s.textContent = CSS; doc.head.append(s); }
  const bar = doc.createElement('section'); bar.id = 'build-bar'; bar.hidden = true; bar.setAttribute('aria-label', 'Place');
  bar.innerHTML = '<p id="build-say" role="status" aria-live="polite"></p><button type="button" id="build-undo">Undo</button><button type="button" id="build-done">Done</button>';
  doc.body.append(bar);
  const say = bar.querySelector('#build-say');
  bar.querySelector('#build-undo').addEventListener('click', () => exec('build undo'));
  bar.querySelector('#build-done').addEventListener('click', () => exec('build done'));

  // The module catalogue for the string voltage check (the HUD's own inputs), once.
  const catalogue = fetch(new URL('./world/data/modules.json', location.href), { cache: 'no-cache' }).then(r => (r.ok ? r.json() : null)).catch(() => null)
    .then(c => { S.cat = c; S.cls = c?.classes?.find(k => k.id === (world.module?.debug?.()?.class || 'A')) || c?.classes?.[0] || null; changed(false); });

  // ---- the world, in national-grid metres ----
  const o = () => world.origin();
  const measured = (e, n) => world.measuredAt(e - o().e, n - o().n);
  const ground = (e, n) => api.heightAt(e - o().e, n - o().n);
  function zones() {
    if (!(world.layersOn?.() || []).includes('grid') || !ohl?.layer?.zonesEN) return { state: 'off', list: [] };
    const list = ohl.layer.zonesEN() || [];
    return { state: list.length ? 'on' : 'none', list };
  }
  const ctx = () => ({ measured, zones: zones(), items: S.items, P: S.P });

  // ---- what is drawn ----
  let cache = { v: -1, org: '', groups: null };
  const o3 = base => [base[0] - o().e, base[1] - o().n, base[2]];
  const batch = (key, G, color, version) => (G && G.count ? { key: 'build-' + key, version, positions: G.v, color, origin: o3(G.base) } : null);
  function batches() {
    const org = `${o().e},${o().n}`;
    if (cache.v !== S.v || cache.org !== org) cache = { v: S.v, org, groups: S.items.length ? sceneGroups(S.items, S.wired, S.P, ground) : null };
    const out = [];
    if (cache.groups) for (const k of ['tables', 'strings', 'loose', 'runs', 'inverters']) out.push(batch(k, cache.groups[k], C[k], `${S.v}`));
    if (S.piles) { out.push(batch('piles', S.piles.groups.ok, C.piles, `${S.v}p`), batch('piles-flagged', S.piles.groups.flagged, C.flagged, `${S.v}p`)); }
    if (S.tool && S.ghost) out.push(batch('ghost', S.ghost.G, S.ghost.check.ok ? C.ok : C.no, S.ghostKey));
    return out.filter(Boolean);
  }
  api.hooks.batches.add(batches);

  // ---- state changes ----
  function changed(redraw = true) {
    S.wired = wire(S.items, S.P); S.v++;
    S.checks = buildChecks(S.items, S.wired, S.P, { cat: S.cat, cls: S.cls });
    if (redraw) { api.hooks.design.forEach(f => f()); api.gate.invalidate(); }
    else window.worldHud?.refresh?.();
  }
  const snapshot = () => ({ items: S.items.map(i => ({ ...i })), P: { ...S.P }, next: S.next });
  const remember = () => { S.undo.push(snapshot()); if (S.undo.length > 200) S.undo.shift(); };
  function tell(text, ok = true) {
    S.say = text; S.sayOk = ok; say.textContent = text; say.className = ok ? 'ok' : 'no';
    bar.hidden = !S.tool && !text;
  }
  function setTool(kind) {
    S.tool = kind; S.ghost = null; S.ghostKey = '';
    for (const b of row?.querySelectorAll('[data-place]') || []) b.setAttribute('aria-pressed', String(b.dataset.place === kind));
    if (kind) { // one tool at a time: a Design drawing tool is put down
      for (const b of doc.querySelectorAll('#design [data-tool][aria-pressed="true"]')) b.click();
      tell(`${PIECES[kind]}: move over the ground to see where it may go, then click to place. Typed: build ${kind} at E N.`);
    } else { bar.hidden = true; }
    api.gate.invalidate();
  }

  // Place a piece at national-grid (e, n), snapped; refused in words where a rule says no.
  function place(kind, e, n) {
    const at = snap(kind, e, n, S.P), c = checkPlacement(kind, at, ctx());
    if (!c.ok) { showGhost(c); return { ok: false, text: `${PIECES[kind]} not placed. ${c.reasons.join(' ')}` }; }
    remember();
    const it = { id: `${kind}-${S.next++}`, kind, e: at.e, n: at.n };
    S.items.push(it); S.piles = null; changed();
    const w = S.wired.tables.find(t => t.id === it.id), label = labelOf(it, S.items);
    const wired = kind === 'table' ? (w?.inverter !== null && w
      ? ` Its ${w.strings} strings joined inverter ${w.inverter + 1} (${w.inputs} MPPT input${w.inputs === 1 ? '' : 's'}, home run ${Math.round(w.runM)} m).`
      : ` Its ${S.wired.T.strings} strings are not connected: ${S.wired.inverters.length ? 'no inverter has a free MPPT input. Place another inverter.' : 'place an inverter.'}`)
      : ` ${S.wired.inverters[S.wired.inverters.length - 1].strings} strings wired to it.`;
    return { ok: true, text: `${PIECES[kind]} ${label} placed${c.notes.length ? `: ${c.notes.join('; ')}` : ''}.${wired} Typed: ${typedOf(it)}. ${statusWords(S.items, S.wired, S.P)}` };
  }
  function showGhost(c) {
    const key = `${c.kind}:${c.at.e}:${c.at.n}:${c.ok}:${S.v}`;
    if (key === S.ghostKey) return;
    S.ghostKey = key; S.ghost = { check: c, G: ghostGroup(c, S.P, ground) };
    tell(c.ok ? `${PIECES[c.kind]} can go here${c.notes.length ? `: ${c.notes.join('; ')}` : ''}. Click to place.` : c.reasons.join(' '), c.ok);
    api.gate.invalidate();
  }
  function pointAt(x, y) {
    const s = world.state(), r = rayFromScreen(x, y, canvas.clientWidth, canvas.clientHeight, s.pos, s.yaw, s.pitch, api.FOV);
    const p = pickGround(r, api.heightAt, { maxDistance: 3000 });
    return p ? { e: p[0] + o().e, n: p[1] + o().n } : null;
  }

  // ---- pointer: hover shows the ghost (mouse), a click or tap places ----
  let press = null;
  const local = e => { const r = canvas.getBoundingClientRect(); return [e.clientX - r.left, e.clientY - r.top]; };
  canvas.addEventListener('pointermove', e => {
    if (!S.tool || press || e.pointerType !== 'mouse') return;
    const p = pointAt(...local(e));
    if (p) showGhost(checkPlacement(S.tool, snap(S.tool, p.e, p.n, S.P), ctx()));
  });
  canvas.addEventListener('pointerdown', e => { if (S.tool) press = { x: e.clientX, y: e.clientY }; });
  canvas.addEventListener('pointerup', e => {
    const p0 = press; press = null;
    if (!S.tool || !p0 || Math.hypot(e.clientX - p0.x, e.clientY - p0.y) > CLICK_PX) return;
    const p = pointAt(...local(e));
    if (!p) { tell('No ground under that point. Look down at the ground and try again.', false); return; }
    const at = snap(S.tool, p.e, p.n, S.P), c = checkPlacement(S.tool, at, ctx());
    // A tap on a phone first shows the ghost and why; a second tap on the same green ghost places it. A mouse places at once.
    const same = S.ghost && S.ghost.check.kind === S.tool && S.ghost.check.at.e === at.e && S.ghost.check.at.n === at.n;
    if (e.pointerType !== 'mouse' && !same) { showGhost(c); return; }
    const r = place(S.tool, p.e, p.n);
    tell(r.text, r.ok);
  });

  // ---- typed lines: every click has one ----
  function exec(line) {
    const q = parseBuild(line);
    if (!q) return null;
    if (!q.ok) { tell(q.why, false); return { ok: false, text: q.why, line }; }
    let r;
    if (q.act === 'status') r = { ok: true, text: statusWords(S.items, S.wired || wire(S.items, S.P), S.P), quiet: true };
    else if (q.act === 'done') { setTool(null); r = { ok: true, text: 'Place put down. ' + statusWords(S.items, S.wired || wire(S.items, S.P), S.P), quiet: true }; }
    else if (q.act === 'undo') {
      const u = S.undo.pop();
      if (!u) r = { ok: false, text: 'Nothing to undo in build.' };
      else { Object.assign(S, { items: u.items, P: u.P, next: u.next, piles: null }); S.ghostKey = ''; changed(); r = { ok: true, text: 'Undone. ' + statusWords(S.items, S.wired, S.P) }; }
    } else if (q.act === 'clear') {
      if (S.items.length) remember();
      S.items = []; S.piles = null; changed(); r = { ok: true, text: 'Build cleared (build undo brings it back).' };
    } else if (q.act === 'set') {
      remember(); const was = S.P[q.key]; S.P = { ...S.P, [q.key]: q.value }; S.piles = null; S.ghostKey = ''; changed();
      r = { ok: true, text: `${line.trim()}: ${was} → ${q.value}. ${statusWords(S.items, S.wired, S.P)}` };
    } else if (q.act === 'place') {
      if (!q.at) {
        const c = canvas, p = pointAt(c.clientWidth / 2, c.clientHeight / 2);
        if (!p) r = { ok: false, text: 'No ground at the centre of the view: look at the ground, or type build table at E N.' };
        else { if (S.tool !== q.kind) setTool(q.kind); r = place(q.kind, p.e, p.n); }
      } else r = place(q.kind, q.at.e, q.at.n);
    }
    tell(r.text, r.ok);
    return { ...r, line };
  }
  // "piles auto" piles what was built (the plant's engine and rules), then the plant and block as before.
  async function pilesAuto() {
    S.piles = builtPiles(S.items, S.P, measured); S.v++; api.gate.invalidate();
    const s = S.piles?.summary;
    if (!s) return null;
    const flags = s.revealHigh + s.revealLow, bits = [flags && `${flags} outside the reveal band`, s.gradingTables && `${s.gradingTables} tables need grading`,
      s.twistTables && `${s.twistTables} twisted over tolerance`, s.unmeasured && `${s.unmeasured} on ground not fully measured`].filter(Boolean);
    let text = `Built tables piled automatically: ${s.piles} piles, front and rear posts, ${Math.round(s.totalPileLengthM)} m of pile `
      + `(embedment provisional); ${s.proofTests} proof tests. ${bits.length ? 'Flagged (orange): ' + bits.join(' · ') + '.' : 'No piles flagged.'}`;
    if (world.plant?.result?.() || world.block?.built?.()) {
      try { const { pilesText } = await import('./cmd-run.mjs'); text += ' ' + pilesText(await world.piles.auto(), world.plant?.result?.()); } catch { /* the plant's piles stay as they were */ }
    }
    tell(text, true);
    return { ok: true, text, line: 'piles auto' };
  }

  // ---- the check HUD and the design file ----
  (api.hooks.checks ||= new Set()).add(() => ({ key: `build:${S.v}`, list: S.checks || [] }));
  const script = () => [...settingLines(S.P, DEFAULTS), ...S.items.map(typedOf)];
  function replay(lines) {
    Object.assign(S, { items: [], undo: [], P: { ...DEFAULTS }, piles: null, next: 1 });
    const out = lines.map(l => exec(l)).filter(Boolean);
    S.undo = []; changed();
    return out;
  }
  changed(false);
  // probe: the verdict a placement would get at national-grid (e, n), without placing (tests and the console).
  const probe = (kind, e, n) => { const c = checkPlacement(kind, snap(kind, e, n, S.P), ctx()); return { ok: c.ok, at: c.at, reasons: c.reasons, notes: c.notes }; };
  return { exec, pilesAuto, setTool, script, replay, catalogue, probe,
    debug: () => ({ tool: S.tool, items: S.items.map(i => ({ ...i })), P: { ...S.P }, say: S.say, ok: S.sayOk, ghost: S.ghost ? { ...S.ghost.check.at, ok: S.ghost.check.ok } : null,
      wired: S.wired && { strings: S.wired.strings, connected: S.wired.connected, unconnected: S.wired.unconnected, inverters: S.wired.inverters.map(v => ({ ...v })) },
      piles: S.piles?.summary ? { piles: S.piles.summary.piles, flagged: S.piles.groups.flagged.count / 2 } : null, checks: (S.checks || []).map(c => c.id), version: S.v, script: script() }) };
}

Cmd Grammar Plant

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

ingestglobalgrid2050 / solar-design-studio/202609271853-site-world/world/cmd-grammar-plant.mjs · lines 1–58 of 58 · version 2026-09-27 18:53 · 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 sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
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
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 · solar-design-studio/202609271853-site-world/world · 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 solar-design-studio/202609271853-site-world/world/cmd-grammar-plant.mjs:1-58 · blob c2cdf8ecb478fd310c5f418bf1a7515328b9ff30 · 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-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 world folder of GlobalGrid2050. It parses senses (`parseSenses`) and is built from the is num helper (`isNum`).

ingestglobalgrid2050 / solar-design-studio/202609271853-site-world/world/cmd-grammar-senses.mjs · lines 1–23 of 23 · version 2026-09-27 18:53 · pattern parseSenses (shared by 3 files)

What it does
Defines isNum, parseSenses.
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.
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
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 · solar-design-studio/202609271853-site-world/world · 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 solar-design-studio/202609271853-site-world/world/cmd-grammar-senses.mjs:1-23 · blob e25c7ed1117084e1d79f371885783b12da7178e5 · 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-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 } };
}