GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / globalgrid2050 / kuiper-grid/i0085/cartridges

Kuiper Programs (part 116)

A JavaScript file in the cartridges folder of GlobalGrid2050 covering interconnectors, london underground, grid 66kV and motorway services, using IEC 62446-1 and SHA-256, and uses data from the faraday repository.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1382 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. Kuiper Programs electrical · globalgrid2050 / kuiper-grid/i0085/cartridges/008500000000-kuiper-programs.js lines 1401–2100

Kuiper Programs

A JavaScript file in the cartridges folder of GlobalGrid2050 covering interconnectors, london underground, grid 66kV and motorway services, using IEC 62446-1 and SHA-256, and uses data from the faraday repository.

Set aside from the main view: 98% of its lines are the same as kuiper-grid/i0090/cartridges/009000000000-kuiper-programs.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Kuiper Programs; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9755 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0090/cartridges/009000000000-kuiper-programs.js:1-4074 900ccf797d8055b28d45153c3fa3dbb44ccb03a5
  • sha256 7b4328e887c68664f10da37c4c0ca7c43f8b6670aad5e88abcd7c5b8495c1549
  • target sha256 3b3ff8b2b317c0c59e1431b1d9e003c246ec9bb5227219e64e47d313656e2062
  • group of 6 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines
  • re-pointed by apply.py version rule from file 3680 to file 3682; similarity was measured to file 3680

electricalglobalgrid2050 / kuiper-grid/i0085/cartridges/008500000000-kuiper-programs.js · lines 1401–2100 of 4036 (continued from section 1380) · Not reached from any entry point (candidate for review) · pattern checkNetlist (shared by 2 files)

What it does
It draws interconnectors, london underground, grid 66kV and motorway services. Defines 220 functions or classes, including reFire, closestPair, blackSky, nameInLines, makeBody. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: interconnectors, 400kV, 275kV, 132kV, 66kV, 33kV.
Inputs & outputs
In: data source: faraday data; JSON file interconnectors.config.json; GeoJSON file london_underground.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file motorway_services.geojson; GeoJSON file railways.geojson; JSON file current.json. Out: canvas drawing. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV, 1500V.
What it achieves
It makes body (`makeBody`), sets tag (`setTag`) and merges menu (`mergeMenu`). Defines `reFire`, `closestPair`, `blackSky` and 202 more. Its code works with 11 kV, 33 kV and 352 kVA. It responds to click and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · kuiper-grid/i0085/cartridges · script
Uses
Faraday — Index Page (estate URL), Wafer Development Environment — Proof S0004 Page (estate URL), ./fire.js
Used by
none found
Produces
reFire, closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet
Defines here
provisional, push, blockDrawing, put, poly, box, see, U, key, run, loadFireConfig, say, searchCommands, fireKey, dedupeCommands, plainName, curateCommands, chipWords, makeFireBar
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0085/cartridges/008500000000-kuiper-programs.js:1401-2100 · blob 632f3f06fa83d30d68e45b0285fb525873faeed8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: duplicate_candidate
    const fmt = I.table_format;
    const stringsPerTable = fmt === '2-string-2-tier' ? 2 : 1;
    const tiers = fmt === '1-string-1-tier' ? 1 : 2;
    const colsPerString = fmt === '1-string-2-tier' ? Math.ceil(M / 2) : M;
    const tiersPerString = fmt === '1-string-2-tier' ? 2 : 1;
    const comp = stringComponent({ modules_per_string: M, tiers: tiersPerString, cols: colsPerString,
      mod, module_gap_m: I.module_gap_m, tier_gap_m: I.tier_gap_m });
    const pitchY = mod.length_m + I.tier_gap_m;
    const tableWidth = comp.width_m;
    const tableDepth = (tiers - 1) * pitchY + mod.length_m;
    const nTables = Math.ceil(N / stringsPerTable);
    const tablesPerRow = Math.min(I.tables_per_row, nTables);
    const nRows = Math.ceil(nTables / tablesPerRow);
    const rowPitch = Math.max(I.row_pitch_m, tableDepth + 0.5);
    const strings = [];
    for (let i = 0; i < N; i++) {
      const t = Math.floor(i / stringsPerTable);
      const slotInTable = i % stringsPerTable;
      const row = Math.floor(t / tablesPerRow);
      const col = t % tablesPerRow;
      const ox = col * (tableWidth + I.table_gap_m);
      const oy = row * rowPitch + (stringsPerTable === 2 ? slotInTable * pitchY : 0);
      strings.push({ i, table: t, row, col, ox, oy, tierBase: stringsPerTable === 2 ? slotInTable : 0 });
    }
    const blockX0 = 0;
    const blockX1 = tablesPerRow * tableWidth + (tablesPerRow - 1) * I.table_gap_m;
    const blockY0 = 0;
    const blockY1 = (nRows - 1) * rowPitch + tableDepth;
    const midX = (blockX0 + blockX1) / 2;
    const midY = (blockY0 + blockY1) / 2;
    const so = I.inverter_standoff_m;
    let inv;
    switch (I.inverter_position) {
      case 'east-centre': inv = [blockX1 + so, midY]; break;
      case 'south-centre': inv = [midX, blockY0 - so]; break;
      case 'north-centre': inv = [midX, blockY1 + so]; break;
      case 'west-quarter': inv = [blockX0 - so, blockY0 + (blockY1 - blockY0) * 0.25]; break;
      case 'typed': inv = I.inverter_xy ? [I.inverter_xy[0], I.inverter_xy[1]] : [blockX0 - so, midY]; break;
      default: inv = [blockX0 - so, midY];
    }
    const [invX, invY] = inv;
    const corridorX = invX <= midX ? blockX0 - I.corridor_offset_m : blockX1 + I.corridor_offset_m;
    const invW = INVERTER_CLASS.width_m;
    const invD = INVERTER_CLASS.depth_m;
    const faceY = invY - invD / 2;
    const nInputs = arr.inputs;
    const trackers = [];
    const inputsById = new Map();
    for (let t = 0; t < arr.trackers; t++) {
      const tr = { id: `${B}.INV.T${p2(t + 1)}`, t, inputs: [] };
      for (let a = 0; a < arr.inputs_per_tracker; a++) {
        const idx = a * arr.trackers + t;
        const x = invX - invW / 2 + ((idx + 1) * invW) / (nInputs + 1);
        const id = `${tr.id}.in${a + 1}`;
        const input = { id, tracker: t, a, order: idx,
          terminals: { plus: { id: `${id}+`, xy: [r(x + 0.012), r(faceY)] },
                       minus: { id: `${id}-`, xy: [r(x - 0.012), r(faceY)] } },
          used_by: null, lod: 'box' };
        tr.inputs.push(input);
        inputsById.set(id, input);
      }
      trackers.push(tr);
    }
    const slots = [];
    for (let a = 0; a < arr.inputs_per_tracker; a++) for (let t = 0; t < arr.trackers; t++) slots.push(trackers[t].inputs[a]);
    const provisional = (s) => { const bx = s.ox + comp.start[0], by = s.oy + comp.start[1];
      return Math.abs(corridorX - bx) + Math.abs(invY - by) + Math.abs(invX - corridorX); };
    for (const s of strings) s.prov = provisional(s);
    const order = [...strings];
    if (I.pairing === 'long-short') order.sort((a, b) => b.prov - a.prov || a.i - b.i);
    let lo = 0, hi = order.length - 1;
    const taken = [];
    for (let k = 0; k < slots.length && lo <= hi; k++) {
      const a = slots[k].a;
      const s = I.pairing === 'long-short' && a % 2 === 1 ? order[hi--] : order[lo++];
      taken.push([slots[k], s]);
    }
    for (const [slot, s] of taken) { slot.used_by = `${B}.S${p2(s.i + 1)}`; s.input = slot; }
    const modules = [];
    const conductors = [];
    const outStrings = [];
    for (const s of strings) {
      const sid = `${B}.S${p2(s.i + 1)}`;
      const sMods = comp.modules.map((m) => {
        const mid = `${sid}.M${p2(m.j + 1)}`;
        const rec = { id: mid, string: s.i, j: m.j, tier: m.tier + s.tierBase, col: m.col,
          rect: [r(s.ox + m.rect[0]), r(s.oy + m.rect[1]), m.rect[2], m.rect[3]],
          box: { id: `${mid}.box`,
            plus: { id: `${mid}.box+`, xy: [r(s.ox + m.box.plus[0]), r(s.oy + m.box.plus[1])] },
            minus: { id: `${mid}.box-`, xy: [r(s.ox + m.box.minus[0]), r(s.oy + m.box.minus[1])] } },
          alias: `block.string[${s.i}].module[${m.j}]`, lod: 'module' };
        modules.push(rec); return rec; });
      for (const l of comp.links) {
        const from = sMods[l.j].box.plus, to = sMods[l.j + 1].box.minus;
        const pts = dedupe([from.xy, to.xy]);
        conductors.push({ id: `${sid}.L${p2(l.j + 1)}`, kind: 'link', string: s.i, from: from.id, to: to.id,
          polyline: pts, length_m: r(polyLength(pts)), reach: r(dist(from.xy, to.xy)),
          alias: `block.string[${s.i}].link[${l.j}]`, lod: 'string' });
      }
      const laneSign = corridorX <= midX ? -1 : +1;
      const laneX = corridorX + laneSign * s.input.order * I.corridor_lane_pitch_m;
      const sep = I.home_separation_m / 2;
      const ends = [
        { pole: 'plus', sign: '+', box: sMods[M - 1].box.plus, term: s.input.terminals.plus, off: +sep },
        { pole: 'minus', sign: '-', box: sMods[0].box.minus, term: s.input.terminals.minus, off: -sep },
      ];
      const homeRuns = [];
      for (const e of ends) {
        const [bx, by] = e.box.xy, [tx, ty] = e.term.xy, gx = laneX + e.off;
        /* Leg 1 goes north out of the table to the middle of the inter-row gap, so the run
           travels ALONG the row end and never through the faces of the tables to its west. */
        const rowEndY = s.row * rowPitch + tableDepth + (rowPitch - tableDepth) / 2 + e.off;
        const pts = dedupe([[bx, by], [bx, r(rowEndY)], [r(gx), r(rowEndY)], [r(gx), r(ty)], [tx, ty]]);
        const hr = { id: `${sid}.HR${e.sign}`, kind: 'home_run', pole: e.pole, string: s.i,
          from: e.box.id, to: e.term.id, input: s.input.id, tracker: s.input.tracker,
          polyline: pts, length_m: r(polyLength(pts)), reach: r(dist([bx, by], [tx, ty])),
          alias: `block.string[${s.i}].home.${e.pole}`, lod: 'block' };
        conductors.push(hr); homeRuns.push(hr);
      }
      outStrings.push({ id: sid, index: s.i, alias: `block.string[${s.i}]`,
        placement: { table: s.table, row: s.row, col: s.col, tier_base: s.tierBase, tiers: tiersPerString,
          cols: colsPerString, origin: [r(s.ox), r(s.oy)],
          outline: [r(s.ox), r(s.oy), comp.width_m, r(comp.depth_m)] },
        tracker: s.input.tracker, input: s.input.id, modules: sMods.map((m) => m.id),
        home_runs: homeRuns.map((h) => h.id),
        home_run_length_m: r(homeRuns[0].length_m + homeRuns[1].length_m), lod: 'string' });
    }
    const T_cold = I.ambient_min_C + I.cold_allowance_K;
    const T_hot = I.hot_cell_C;
    const bVoc = mod.beta_Voc_pct_per_K / 100;
    const gVmp = mod.gamma_Vmp_pct_per_K / 100;
    const Voc_stc = M * mod.Voc_V;
    const Voc_cold = M * mod.Voc_V * (1 + bVoc * (T_cold - 25));
    const Vmp_stc = M * mod.Vmp_V;
    const Vmp_hot = M * mod.Vmp_V * (1 + gVmp * (T_hot - 25));
    const Imp = mod.Imp_A, Isc = mod.Isc_A;
    const I_design = I.design_current_factor * I.bifacial_factor * Isc;
    const P_string = M * mod.Vmp_V * mod.Imp_A;
    const P_block = N * P_string;
    const perTracker = new Map();
    for (let t = 0; t < arr.trackers; t++) perTracker.set(t, 0);
    for (const s of outStrings) perTracker.set(s.tracker, perTracker.get(s.tracker) + 1);
    const maxStringsOnATracker = Math.max(...perTracker.values());
    const minStringsOnATracker = Math.min(...perTracker.values());
    const I_tracker = maxStringsOnATracker * I_design;
    const Isc_tracker = maxStringsOnATracker * I.bifacial_factor * Isc;
    /* Fuses rest on the strings ACTUALLY paralleled on the fullest tracker, never on the
       nominal strings-in-parallel of the arrangement. */
    const Np = maxStringsOnATracker;
    const Np_nominal = arr.strings_in_parallel_per_tracker;
    const fuseRating = I.module_max_series_fuse_A;
    const faultNoBackfeed = (Np - 1) * I.design_current_factor * I.bifacial_factor * Isc;
    const countRuleFires = Np >= 3;
    const currentRuleFires = faultNoBackfeed > fuseRating;
    const fusesRequired = countRuleFires || currentRuleFires;
    const fuseRuleFired = countRuleFires ? (currentRuleFires ? 'count and current' : 'count') : (currentRuleFires ? 'current' : 'none');
    const backfeedUnconfirmed = I.inputs_block_reverse_current !== 'yes';
    const faultTerm = `(${Np} - 1) x ${I.design_current_factor} x ${I.bifacial_factor} x Isc = ${r(faultNoBackfeed, 2)} A`;
    const askMaker = backfeedUnconfirmed
      ? ' The inverter inputs are NOT confirmed to block reverse current, so the backfeed contribution to a faulted string is unknown and no maker publishes it: ASK THE INVERTER MAKER. That term is separate from the parallel-string term above and can only make the case for fuses stronger, never weaker.'
      : ' The inverter inputs are declared to block reverse current, so the parallel-string term above is the whole of the fault current.';
    const fuseWords = (countRuleFires
      ? `STRING FUSES ARE REQUIRED. ${Np} strings sit in parallel on the fullest tracker and the COUNT rule fires at three or more: the healthy strings can drive ${faultTerm} into a faulted one, against a ${fuseRating} A module maximum series fuse rating. Every string needs its own fuse, or a fused combiner, ahead of the tracker.` + (currentRuleFires ? ' The CURRENT rule fires on the same block.'   … [line shortened here: 405 characters; full line on GitHub]
      : currentRuleFires
        ? `STRING FUSES ARE NOT REQUIRED by the count rule - only ${Np} strings are paralleled on the fullest tracker - but the CURRENT rule fires: ${faultTerm} is above the ${fuseRating} A module maximum series fuse rating, so fuses are needed on that term.`
        : `STRING FUSES ARE NOT REQUIRED on the parallel-string term. ${Np} strings are paralleled on the fullest tracker, so the count rule (three or more) does not fire, and ${faultTerm} stays at or below the ${fuseRating} A module maximum series fuse rating, so the current rule does not fire either.`)
      + (Np === Np_nominal ? '' : ` The ${arr.label} arrangement would nominally hold ${Np_nominal} strings on a tracker; this block only fills ${Np}, and the verdict follows the actual count.`)
      + askMaker;
    const otherKey = arrKey === '12x2' ? '6x5' : '12x2';
    const otherArr = ARRANGEMENTS[otherKey];
    const faultOther = (otherArr.strings_in_parallel_per_tracker - 1) * I.design_current_factor * I.bifacial_factor * Isc;
    const kWp = P_block / 1000;
    const insulation = { clause: 'IEC 62446-1:2016, 6.7.2 and Table 3', value_Mohm: 1, test_V: 500 };
    const V = [];
    const push = (label, value, unit, limit, verdict, status, note) =>
      V.push({ label, value: typeof value === 'number' ? r(value, 2) : value, unit, limit, verdict, status, note });
    push('string Voc at STC', Voc_stc, 'V', INVERTER_CLASS.max_pv_input_voltage_V,
      Voc_stc <= 1500 ? 'pass' : 'fail', st('modules_per_string', 'module_class'), `${M} x ${mod.Voc_V} V`);
    push(`string Voc at the cold design temperature (${r(T_cold, 1)} C)`, Voc_cold, 'V',
      INVERTER_CLASS.max_pv_input_voltage_V, Voc_cold <= 1500 ? 'pass' : 'fail',
      st('ambient_min_C', 'cold_allowance_K', 'modules_per_string'),
      `lowest ambient ${I.ambient_min_C} C plus a ${I.cold_allowance_K} K allowance; beta_Voc ${mod.beta_Voc_pct_per_K} %/K`);
    push('margin to the 1500 V limit at the cold design temperature', 1500 - Voc_cold, 'V', 0,
      1500 - Voc_cold >= 0 ? 'pass' : 'fail', st('ambient_min_C', 'cold_allowance_K'), null);
    push('string Vmp at STC', Vmp_stc, 'V', `${INVERTER_CLASS.mppt_min_V}-${INVERTER_CLASS.mppt_max_V}`,
      Vmp_stc >= 500 && Vmp_stc <= 1500 ? 'pass' : 'fail', st('modules_per_string', 'module_class'), null);
    push(`string Vmp at the hot design cell temperature (${T_hot} C)`, Vmp_hot, 'V',
      INVERTER_CLASS.mppt_min_V, Vmp_hot >= INVERTER_CLASS.mppt_min_V ? 'pass' : 'fail',
      st('hot_cell_C', 'modules_per_string'), 'against the MPPT minimum');
    push('string Imp at STC', Imp, 'A', null, null, st('module_class'), null);
    push('string Isc at STC', Isc, 'A', null, null, st('module_class'), null);
    push('string design current, factor x bifacial factor x Isc', I_design, 'A', null, null,
      st('design_current_factor', 'bifacial_factor', 'module_class'),
      `${I.design_current_factor} x ${I.bifacial_factor} x ${Isc} A`);
    push('current into each inverter input', I_design, 'A', arr.A_per_input,
      I_design <= arr.A_per_input ? 'pass' : 'fail', st('design_current_factor', 'bifacial_factor'), 'one string per input');
    push('current into each tracker', I_tracker, 'A', arr.A_per_tracker,
      I_tracker <= arr.A_per_tracker ? 'pass' : 'fail', st('design_current_factor', 'bifacial_factor'),
      `${maxStringsOnATracker} strings on the fullest tracker`);
    push('Isc into each tracker', Isc_tracker, 'A', arr.Isc_per_tracker_A,
      Isc_tracker <= arr.Isc_per_tracker_A ? 'pass' : 'fail', st('bifacial_factor'), null);
    push('DC power per string at STC', P_string / 1000, 'kW', null, null, st('module_class', 'modules_per_string'), null);
    push('DC power of the block at STC', kWp, 'kW', null, null,
      st('module_class', 'modules_per_string', 'strings_per_inverter'),
      `${N} strings x ${M} modules x ${r(mod.Vmp_V * mod.Imp_A, 3)} W`);
    push('DC/AC ratio against 352 kVA at 30 C', kWp / INVERTER_CLASS.S_kVA_at_30C, 'ratio', null, null,
      st('module_class', 'strings_per_inverter'), null);
    push('DC/AC ratio against 320 kVA at 40 C', kWp / INVERTER_CLASS.S_kVA_at_40C, 'ratio', null, null,
      st('module_class', 'strings_per_inverter'), null);
    push('DC/AC ratio against 295 kVA at 50 C', kWp / INVERTER_CLASS.S_kVA_at_50C, 'ratio', null, null,
      st('module_class', 'strings_per_inverter'), null);
    push('strings in parallel on the fullest tracker', Np, 'strings', Np_nominal, null,
      st('strings_per_inverter', 'arrangement'),
      `actual count on this block; the ${arr.label} arrangement would nominally hold ${Np_nominal}`);
    push('fault current into one string, inputs DO block reverse current', faultNoBackfeed, 'A', fuseRating,
      faultNoBackfeed <= fuseRating ? 'pass' : 'fail', st('module_max_series_fuse_A', 'design_current_factor', 'bifacial_factor'),
      `(${Np} - 1) x ${I.design_current_factor} x ${I.bifacial_factor} x Isc against the ${fuseRating} A module maximum series fuse rating; rule fired: ${fuseRuleFired}`);
    push('fault current into one string, inputs do NOT block reverse current', faultNoBackfeed, 'A', fuseRating,
      backfeedUnconfirmed ? null : (faultNoBackfeed <= fuseRating ? 'pass' : 'fail'),
      st('inputs_block_reverse_current'),
      backfeedUnconfirmed
        ? 'the inverter backfeed contribution must be added and no maker publishes it, so the verdict is null by rule rather than invented: ASK THE INVERTER MAKER.'
        : 'the inputs are declared to block reverse current, so this equals the term above.');
    push(`the same check in the ${otherArr.label} world`, faultOther, 'A', mod.Ir_A,
      faultOther <= mod.Ir_A ? 'pass' : 'fail', 'ASSUMED', otherArr.fuse_words);
    push('insulation resistance threshold for this block', insulation.value_Mohm, 'Mohm', insulation.value_Mohm,
      null, 'ASSUMED',
      `${insulation.clause}: system voltage above 500 V, test at ${insulation.test_V} V d.c. ` +
      `Block is ${r(kWp, 2)} kWp; the clause is measured per string or sub-array, not across the block.`);
    const hrs = conductors.filter((c) => c.kind === 'home_run');
    const hrLen = hrs.map((h) => h.length_m);
    push('total home-run conductor', hrLen.reduce((a, b) => a + b, 0), 'm', null, null, st('inverter_position'), null);
    push('longest home run', Math.max(...hrLen), 'm', null, null, st('inverter_position'), null);
    push('shortest home run', Math.min(...hrLen), 'm', null, null, st('inverter_position'), null);
    return {
      schema: 'solar-block/v1', version: 'solar-block/1.0.0', id: B, inputs: I, typed: [...typedKeys],
      module_class: mod, inverter_class: INVERTER_CLASS,
      arrangement: { ...arr, strings_fitted: N, inputs_free: arr.inputs - N,
        strings_on_fullest_tracker: maxStringsOnATracker, strings_on_emptiest_tracker: minStringsOnATracker,
        strings_in_parallel_per_tracker: Np,
        strings_in_parallel_nominal: Np_nominal,
        module_max_series_fuse_A: fuseRating,
        fuses_required: fusesRequired,
        fuse_rule_fired: fuseRuleFired,
        ask_the_inverter_maker: backfeedUnconfirmed,
        fuse_words: fuseWords },
      geometry: { bbox: [r(blockX0), r(blockY0), r(blockX1), r(blockY1)], rows: nRows, tables: nTables,
        tables_per_row: tablesPerRow, table_format: fmt, table_width_m: tableWidth, table_depth_m: r(tableDepth),
        row_pitch_m: r(rowPitch), corridor_x: r(corridorX), corridor_lane_pitch_m: I.corridor_lane_pitch_m,
        corridor_far_x: r(corridorX + (corridorX <= midX ? -1 : 1) * (N - 1) * I.corridor_lane_pitch_m) },
      inverter: { id: `${B}.INV`, xy: [r(invX), r(invY)],
        rect: [r(invX - invW / 2), r(invY - invD / 2), r(invW), r(invD)],
        trackers, inputs: [...inputsById.values()], lod: 'block' },
      strings: outStrings, modules, conductors,
      counts: { strings: outStrings.length, modules: modules.length,
        links: conductors.filter((c) => c.kind === 'link').length, home_runs: hrs.length,
        inputs: nInputs, inputs_used: [...inputsById.values()].filter((i2) => i2.used_by).length },
      values: V,
      notes: [ fuseWords,
        'Metres throughout. The ground plan is a plan projection; tilt is not modelled.',
        'Every home run is a four-leg orthogonal route: out of the table to the inter-row gap, ' +
        'along the row end, up the gathering corridor, then onto its own named inverter input terminal.',
        'DEVELOPMENT ENVIRONMENT. Not a warranted design.' ],
    };
  }
  /* ---- end of the copy from block.mjs ---- */

  // ===== THE BLOCK AS THIS ENGINE'S SHAPE DATA ===================================================
  // FINE PENCIL, NO FILLS. Module outlines are the thinnest line on the page; each string carries its
  // own outline so twenty-four of them can be told apart at macro; the two home runs are red for + and
  // light for −, and each one ends ON ITS OWN NAMED INVERTER INPUT TERMINAL, which is drawn and named.
  // MACRO BY DEFAULT: the whole block is laid out at once and the view opens on all of it; the module
  // rectangles, the module labels and the input names only come up as the reader zooms in.
  // THE VALUES LIST IS NOT WRITTEN ON THE DRAWING. It is the answer, and it belongs in the window.
  function blockDrawing(BK) {
    const shapes = [], marks = [], words = [], conns = [], terminals = [];
    const put = o => { if (o.pot === undefined) o.pot = 0; if (o.node === undefined) o.node = null; shapes.push(o); return o; };
    const poly = (role, o, pts, extra) => put(Object.assign({ role, order:o, pot:0, pts, weight:1 }, extra || {}));
    const box = (role, o, x0, y0, x1, y1, extra) => poly(role, o, [[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]], extra);
    const nS = Math.max(1, BK.strings.length);
    const byId = {};
    for (const s of BK.strings) byId[s.index] = s;

    // ---- the inverter, with its twenty-four named input pairs
    const ir = BK.inverter.rect;
    box('inverter', 0, ir[0], ir[1], ir[0] + ir[2], ir[1] + ir[3], { fill:SHAPE_FILL, node:'inv' });
    marks.push({ x:ir[0] + ir[2] / 2, y:ir[1] - 1.1, text:BK.inverter.id + '  ' + BK.inverter_class.label,
      size:11, colour:SHAPE_INK, minPx:0, mid:true, rank:0 });
    for (const inp of BK.inverter.inputs) {
      const P = inp.terminals.plus.xy, Mn = inp.terminals.minus.xy;
      poly('terminal', 0, [[P[0], P[1]], [P[0], P[1] - 0.22]], { node:inp.id, pot:1 });
      put({ role:'terminal', order:0, pot:1, node:inp.id, pts:[[P[0], P[1]]], dot:0.05 });
      poly('terminal', 0, [[Mn[0], Mn[1]], [Mn[0], Mn[1] - 0.22]], { node:inp.id, pot:0 });
      put({ role:'terminal', order:0, pot:0, node:inp.id, pts:[[Mn[0], Mn[1]]], dot:0.05 });
      terminals.push({ id:inp.terminals.plus.id, x:P[0], y:P[1], kind:'inv+', module:0 });
      terminals.push({ id:inp.terminals.minus.id, x:Mn[0], y:Mn[1], kind:'inv-', module:0 });
      marks.push({ x:(P[0] + Mn[0]) / 2, y:P[1] - 0.40,
        text:inp.id.replace(BK.id + '.INV.', '') + (inp.used_by ? ' \u2190 ' + inp.used_by.replace(BK.id + '.', '') : ' free'),
        size:9, colour:SHAPE_EDGE, minPx:34, mid:true, rank:2, dodge:true });
    }

    // ---- every string: its own outline, its modules, its links, its two home runs
    for (const s of BK.strings) {
      const ol = s.placement.outline, o = (s.index + 1) / nS;
      box('module', o, ol[0] - 0.12, ol[1] - 0.12, ol[0] + ol[2] + 0.12, ol[1] + ol[3] + 0.12,
        { node:s.id, weight:0.9, says:s.id + ', ' + s.modules.length + ' modules in series onto ' + s.input });
      marks.push({ x:ol[0] + ol[2] / 2, y:ol[1] + ol[3] + 0.42, text:s.id.replace(BK.id + '.', ''),
        size:10, colour:SHAPE_INK, minPx:16, mid:true, rank:1, dodge:true });
    }
    for (const m of BK.modules) {
      const o = (m.string + 1) / nS;
      box('module', o, m.rect[0], m.rect[1], m.rect[0] + m.rect[2], m.rect[1] + m.rect[3],
        { node:m.id, weight:0.7, lod:m.lod });
    }
    for (const cd of BK.conductors) {
      const o = (cd.string + 1) / nS;
      if (cd.kind === 'link') {
        poly('lead', o, cd.polyline, { node:cd.id, pot:o, plus:false, weight:0.7, hit:true,
          from:cd.from, to:cd.to, metres:cd.length_m,
          says:cd.from + ' to ' + cd.to + ', ' + cd.length_m.toFixed(2) + ' m' });
      } else {
        const plus = cd.pole === 'plus';
        poly('cable', o, cd.polyline, { node:cd.id, pot:plus ? 1 : 0, plus, weight:plus ? 1.2 : 0.9, hit:true,
          from:cd.from, to:cd.to, metres:cd.length_m,
          says:cd.id + ': ' + cd.length_m.toFixed(1) + ' m onto ' + cd.to });
        conns.push({ node:cd.id, from:cd.from, to:cd.to, needed:cd.length_m, pair:null, reaches:true, home:true });
      }
    }

    // ---- the words. The key and the owner's own sentence, pinned to the screen, never in the picture.
    words.push({ pinned:3, note:true, off:true,
      text:BK.counts.strings + ' strings of ' + BK.strings[0].modules.length + ' modules in series \u00b7 '
        + BK.counts.modules + ' modules \u00b7 ' + BK.counts.home_runs + ' home runs onto '
        + BK.counts.inputs_used + ' of ' + BK.counts.inputs + ' named inverter inputs',
      small:BK.counts.strings + ' strings \u00b7 ' + BK.counts.modules + ' modules \u00b7 '
        + BK.counts.home_runs + ' home runs \u00b7 ' + BK.counts.inputs_used + '/' + BK.counts.inputs + ' inputs' });
    words.push({ pinned:4, danger:true, text:DEV_WARNING, small:DEV_WARNING_SHORT });
    words.push({ pinned:1, note:true, narrow:true,
      text:'red +, light \u2212 \u00b7 every string shows, and every home run lands on its own named input' });
    words.push({ pinned:0, note:true, wide:true,
      text:'all ' + BK.counts.strings + ' strings per inverter are drawn, each with its own two home runs onto its own named input; '
        + 'the numbers are in the window, not on the drawing',
      small:'all ' + BK.counts.strings + ' strings show, each onto its own named input' });

    // ---- measured, then laid out the way the row is: as tall as the disc, as wide as it needs to be
    let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9;
    const see = (x, y) => { if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; };
    for (const s of shapes) { if (s.pts) for (const p of s.pts) see(p[0], p[1]); }
    for (const m of marks) see(m.x, m.y);
    for (const t2 of terminals) see(t2.x, t2.y);
    const S = Math.min(1.85 / Math.max(0.5, y1 - y0), 1.90 / Math.max(0.5, x1 - x0));
    const my = (y0 + y1) / 2, mx = (x0 + x1) / 2;
    const U = (x, y) => [(x - mx) * S, (y - my) * S];
    for (const s of shapes) { if (s.pts) s.pts = s.pts.map(p => U(p[0], p[1])); if (s.mid) s.mid = U(s.mid[0], s.mid[1]); }
    for (const m of marks) { const u = U(m.x, m.y); m.x = u[0]; m.y = u[1]; }
    for (const t2 of terminals) { const u = U(t2.x, t2.y); t2.x = u[0]; t2.y = u[1]; }
    for (const w of words) { if (w.pinned !== undefined) continue; const u = U(w.x, w.y); w.x = u[0]; w.y = u[1]; }
    for (const s of shapes) s.breaks = [];
    const volts = BK.strings[0].modules.length * BK.module_class.Vmp_V;
    return { kind:'string', shapes, marks, words, conns, terminals, wiring:true, crossings:[], perM:S,
      open:false, g:null, firstModuleX:U(0, 0)[0], volts, volts_open:BK.strings[0].modules.length * BK.module_class.Voc_V,
      earth_node:'earth', bounds:{ x0:U(x0, y0)[0], y0:U(x0, y0)[1], x1:U(x1, y1)[0], y1:U(x1, y1)[1] },
      near:{ x:U(BK.inverter.xy[0], BK.inverter.xy[1])[0], y:U(BK.inverter.xy[0], BK.inverter.xy[1])[1] },
      mPerUnit:1 / S, amps:BK.module_class.Imp_A, front:-1, head:-1, walk:null, t0:0 };
  }

  const key = s => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
  function run(inp) {
    const BK = buildBlock(inp || {});
    const D = blockDrawing(BK);
    // the pseudo string the engine's dot layout and renderer read: the drawing is already made, so
    // nothing here is ever asked to build it a second time.
    const g = { c:{ sheet:(inp && inp.sheet) ? 1 : 0, view:'wiring' }, N:BK.counts.modules, short:[], links:[],
      rows:BK.geometry.rows, cols:BK.geometry.tables_per_row, rowY:[0], order:[], bothNear:true, ret:0,
      row:BK.geometry.bbox[2], lead_m:0, field_m:0, ohm:0, __draw:D };
    D.g = g;
    const V = BK.values;
    const numbers = { strings_per_inverter:BK.counts.strings, modules_per_string:BK.strings[0].modules.length,
      modules_in_the_block:BK.counts.modules, links_between_modules:BK.counts.links,
      home_run_cables:BK.counts.home_runs, inverter_inputs:BK.counts.inputs, inverter_inputs_used:BK.counts.inputs_used,
      inverter_dc_arrangement:BK.arrangement.label, string_fuses_required:BK.arrangement.fuses_required ? 'YES' : 'no, on the parallel-string term only',
      module_class:BK.module_class.label, block_width_m:BK.geometry.bbox[2], block_depth_m:BK.geometry.bbox[3],
      rows_of_tables:BK.geometry.rows, tables:BK.geometry.tables };
    // THE VALUES LIST GOES IN THE ANSWER, not on the picture: label, value, unit, limit and verdict.
    for (const v of V) numbers[key(v.label)] = v.value + (v.unit ? ' ' + v.unit : '')
      + (v.limit !== null && v.limit !== undefined ? ' (limit ' + v.limit + ')' : '')
      + (v.verdict ? ' ' + v.verdict.toUpperCase() : v.limit !== null && v.limit !== undefined ? ' verdict withheld' : '')
      + ' [' + v.status + ']';
    const said = 'ONE COMPLETE INVERTER BLOCK: ' + BK.counts.strings + ' strings of '
      + BK.strings[0].modules.length + ' modules in series, ' + BK.counts.modules + ' modules, '
      + BK.counts.strings + ' strings on one inverter and every one of them drawn - '
      + BK.counts.home_runs + ' home runs, each landing on its own named inverter input ('
      + BK.counts.inputs_used + ' of ' + BK.counts.inputs + ' inputs used, ' + BK.arrangement.label + '). '
      + 'Block ' + BK.geometry.bbox[2].toFixed(1) + ' m by ' + BK.geometry.bbox[3].toFixed(1) + ' m over '
      + BK.geometry.rows + ' rows of ' + BK.geometry.tables_per_row + ' tables. '
      + V[12].value + ' kW at STC against the ' + BK.inverter_class.S_kVA_at_30C + ' kVA class. '
      + BK.notes[0];
    return { connections:null, numbers, said,
      electrical_order:BK.strings.map(s => s.id.replace(BK.id + '.', '') + '\u2192' + s.input.replace(BK.id + '.INV.', '')).join('  '),
      how:'Every number and every point here comes from the tested library solar-block/1.0.0 '
        + '(block.mjs, 68 of 68 assertions), copied into this cartridge unchanged; only the conversion '
        + 'to this engine\u2019s shape data is new. Metres, volts, amps, watts. The ground plan is a plan '
        + 'projection and tilt is not modelled. ' + BK.notes[2] + ' '
        + 'Everything is ASSUMED unless every input feeding it was typed, and each line of the values '
        + 'list says which it is. The module class, the cold and hot design temperatures, the bifacial '
        + 'and design-current factors and the geometry are all inputs: change any of them and the checks '
        + 'move. The one number the model cannot close is the inverter backfeed contribution to a string '
        + 'fault, which no maker publishes, so that verdict is returned null rather than invented. '
        + BK.notes[3], block:g, values:V, inputs_used:Object.assign({}, BK.inputs) };
  }
  // WHAT A READER MAY TURN: every input the library declares, made into a box.
  const BOXES = INPUTS.filter(i => i.kind !== 'pair' && i.kind !== 'text').map(i => {
    const b = { key:i.key, label:i.label };
    if (i.unit) b.unit = i.unit;
    if (i.kind === 'choice') { b.kind = 'choice'; b.choices = i.choices.map(c => [c, c]); }
    else { b.kind = 'number'; if (i.min !== undefined) b.min = i.min; if (i.max !== undefined) b.max = i.max;
      b.step = i.step === undefined ? 1 : i.step; }
    return b; });
  F.register('block', 'STRINGS', run, BOXES);
  // THE COPY DECLARES WHAT IT IS A COPY OF. The 380 lines above are a verbatim carry of
  // LIB/solar-block/block.mjs; nothing here runs that library's own tests, so the one thing that can be
  // checked cheaply is that the copy and the library still name the same version. COPIED_FROM is that
  // declaration, and the CI proof compares it with VERSION in block.mjs, so silent drift is caught.
  const COPIED_FROM = 'solar-block/1.0.0';
  F.block = { buildBlock, blockDrawing, INPUTS, DEFAULTS, MODULE_CLASSES, ARRANGEMENTS, INVERTER_CLASS, COPIED_FROM };
})(typeof window !== 'undefined' ? window : globalThis);
// ===== THE COMMAND LIST, READ THE WAY GRIDATLAS READS A COMPOSITION ===============================
// The sentences in the bar are not written into this page: the page fetches them. This is the reader, and it is built the way
// the Atlas reads atlas/current.json - a POINTER fetched with no cache at all, a schema that must be the one we know, a file
// named by the pointer, and the bytes that arrive RE-HASHED here and compared with the hash the pointer declared before one
// sentence is shown. Nothing is trusted because it arrived; it is trusted because it hashes to what was promised.
//
// ON ANY FAULT THE BAR SAYS THE EXACT REASON. A list that quietly falls back to a few built-in sentences teaches a reader
// nothing; "the list hashes to 9c1f6a and the pointer says 4749ae" tells them, and tells us, what actually happened.
//
// WHERE IT READS FROM: the faraday repository's Pages site. That is a DIFFERENT ORIGIN from the one this page is served from,
// for as long as the list is produced there: the fetch depends on that site's Access-Control-Allow-Origin header, which is not
// ours to promise, and a refusal is one of the faults the bar will name. The day the list is copied under this origin, pass
// that base in instead; the pointer, the hash and the checks are the same either way.
async function loadFireConfig(base) {
  const say = reason => ({ ok: false, reason: reason });
  const at = String(base || '');
  if (!at || at.slice(-1) !== '/') return say('the base address must end in a slash; it was "' + at + '"');
  if (typeof fetch !== 'function') return say('this browser has no fetch, so the list cannot be read');
  const subtle = (typeof crypto !== 'undefined' && crypto && crypto.subtle) ? crypto.subtle : null;
  if (!subtle) return say('this page cannot hash what it fetched (crypto.subtle is missing, which is what a page served over plain http gets), so nothing is trusted');
  let res;
  try { res = await fetch(at + 'current.json', { cache: 'no-store' }); }
  catch (e) { return say('the pointer ' + at + 'current.json could not be fetched: ' + (e && e.message ? e.message : e)); }
  if (!res.ok) return say('the pointer ' + at + 'current.json answered ' + res.status);
  let cur;
  try { cur = JSON.parse(await res.text()); }
  catch (e) { return say('the pointer is not valid JSON: ' + (e && e.message ? e.message : e)); }
  if (!cur || typeof cur !== 'object') return say('the pointer is not an object');
  if (cur.schema !== 'faraday.commands.current.v1') return say('the pointer says schema "' + cur.schema + '" and this page reads faraday.commands.current.v1');
  if (typeof cur.file !== 'string' || !cur.file) return say('the pointer names no file');
  if (typeof cur.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(cur.sha256)) return say('the pointer carries no sha256 for ' + cur.file);
  if (typeof cur.generation !== 'string' || !cur.generation) return say('the pointer carries no generation');
  let fres;
  try { fres = await fetch(at + cur.file, { cache: 'no-store' }); }
  catch (e) { return say('the list ' + cur.file + ' could not be fetched: ' + (e && e.message ? e.message : e)); }
  if (!fres.ok) return say('the list ' + cur.file + ' answered ' + fres.status);
  const buf = await fres.arrayBuffer();
  if (typeof cur.bytes === 'number' && buf.byteLength !== cur.bytes) return say('the list is ' + buf.byteLength + ' bytes and the pointer says ' + cur.bytes);
  const digest = await subtle.digest('SHA-256', buf);
  let hex = ''; const view = new Uint8Array(digest);
  for (let i = 0; i < view.length; i++) hex += view[i].toString(16).padStart(2, '0');
  if (hex !== cur.sha256) return say('the list hashes to ' + hex.slice(0, 12) + ' and the pointer says ' + cur.sha256.slice(0, 12) + ': these are not the bytes that were published');
  let list;
  try { list = JSON.parse(new TextDecoder('utf-8').decode(buf)); }
  catch (e) { return say('the list is not valid JSON: ' + (e && e.message ? e.message : e)); }
  if (!list || typeof list !== 'object') return say('the list is not an object');
  if (list.schema !== 'faraday.commands.v2') return say('the list says schema "' + list.schema + '" and this page reads faraday.commands.v2');
  if (list.generation !== cur.generation) return say('the list is generation ' + list.generation + ' and the pointer says ' + cur.generation);
  if (!Array.isArray(list.commands)) return say('the list carries no commands');
  if (typeof cur.count === 'number' && list.commands.length !== cur.count) return say('the pointer counts ' + cur.count + ' commands and the list holds ' + list.commands.length);
  if (!list.commands.length) return say('the list is empty');
  for (let i = 0; i < list.commands.length; i++) {
    const c = list.commands[i];
    if (!c || typeof c !== 'object') return say('command ' + i + ' is not an object');
    for (const k of ['family', 'kind', 'sentence', 'command']) if (typeof c[k] !== 'string' || !c[k]) return say('command ' + i + ' has no ' + k);
    if (c.seed !== null && c.seed !== undefined && typeof c.seed !== 'number') return say('command ' + i + ' has a seed that is not a number');
    if (c.case !== null && c.case !== undefined && typeof c.case !== 'number') return say('command ' + i + ' has a case that is not a number');
  }
  return { ok: true, generation: list.generation, commands: list.commands };
}
// A THOUSAND SENTENCES NEED A SEARCH BOX. Every word typed must appear somewhere in the family, the kind or the sentence, so
// "chain export 500" narrows to chains that export near a 500 kW limit. Case blind, and never more than fifty at once,
// because a list longer than a screen is a list nobody reads.
function searchCommands(commands, text) {
  const words = String(text === undefined || text === null ? '' : text).toLowerCase().split(/\s+/).filter(Boolean);
  const out = [];
  if (!Array.isArray(commands)) return out;
  for (let i = 0; i < commands.length && out.length < 200; i++) {
    const c = commands[i];
    if (!c) continue;
    const hay = ((c.family || '') + ' ' + (c.kind || '') + ' ' + (c.name || '') + ' ' + (c.sentence || '')).toLowerCase();
    let all = true;
    for (let w = 0; w < words.length; w++) if (hay.indexOf(words[w]) < 0) { all = false; break; }
    if (all) out.push(c);
  }
  return out;
}
// ===== THE WAFER'S OWN BAR AND WINDOW, LIFTED ONTO THE KUIPER ====================================
// Vikram, on seeing the pop-up this replaced: "You've killed the preset wafer lifted popup bar". His
// standing rule is that the wafer development environment page IS the look and every feature evolves
// that renderer; a list pop-up of my own invention is a new look, and it went. What is here is the
// wafer's own component, taken from
// globalgrid2050.com/testcode/wafer-development-environment/202609192215-proof-s0004/ (pilot.mjs), with
// its own ids, its own classes and its own proportions kept, so the two bars are one component:
//
//   #pilot   one full width typed bar across the very bottom, with #pin in it
//   #eg      the examples picker just above it on the right: "EXAMPLES: PICK ONE, IT LANDS IN THE BOX,
//            PRESS ENTER" over "- choose an example sentence -"
//   #presets the preset chips along the top left, the way the wafer carries home, the grid, 400 kV
//   #say     the window: #saybar with the title and minimise, maximise and close, #saybody under it,
//            dragged by its bar, resized from its corner
//
// What the owner asked for on top of the wafer, and what is his and not the wafer's:
//   - choosing a preset FIRES it. The bar then shows its plain NAME, never the JSON.
//   - the command text is shown only when it is asked for, inside the window, where it can be edited
//     and fired again.
//   - typing in the bar searches the published thousand by their plain words; the picker becomes the
//     list of what matched, and Enter fires the first of them.
//   - nothing is offered twice (see fireKey above), and the face carries nothing else at all.
const FIRE_CONFIG = 'https://ventusltd.github.io/faraday/bench/results/commands/';
const FIRE_SLD_KIND = (typeof window !== 'undefined' ? window : globalThis).FIRE_SLD_KIND ||
  ((typeof window !== 'undefined' ? window : globalThis).FIRE_SLD_KIND = { 'string':'string', 'block':'string' });
// A PROGRAM REGISTERS ITS OWN KIND. Adding a command that draws a single-line diagram means one entry in
// FIRE_SLD_KIND written by the program itself, not a widened chain here, so two bands never edit one line.
const FIRE_DRAWN_ALWAYS = ['site-pulse', 'network'];     // the two the dots draw that carry no sld kind
const FIRE_DRAWS = { includes: n => FIRE_DRAWN_ALWAYS.includes(n) || Object.prototype.hasOwnProperty.call(FIRE_SLD_KIND, n) };
const CHIPS_SHOWN = 8;                                   // the best few as chips, the way the wafer pins its best few
const PICKER_SHOWN = 100;                                // the pinned hundred in the picker; the rest by typing
// THE STRING TESTS live in this file: they are geometry, they need no bench run, and they are shown first.
const STRING_TESTS = [
  { family:'STRINGS', pin:-12, name:'A tracker, two in portrait, along and back', chip:'2P along-and-back', sentence:'Single axis tracker, two modules in portrait, out along the lower row and back along the upper: both ends at the near end and no return cable', command:'fire string {"mounting":"tracker","modules_high":2,"routing":"serpentine","turn_alternate_rows":1,"jumpers":1,"lead_plus_m":0.35,  … [line shortened here: 424 characters; full line on GitHub]
  { family:'STRINGS', pin:-11, name:'A tracker, two in portrait, leapfrog in each row', chip:'2P leapfrog', sentence:'Single axis tracker, two in portrait, every other module on the way out and the rest on the way back inside each row', command:'fire string {"mounting":"tracker","modules_high":2,"routing":"leapfrog","turn_every_second":1,"lead_plus_m":0.84,"lead_minus_m":1.166,"jumpers":1}' },
  { family:'STRINGS', pin:-10, name:'A tracker, two in portrait, one after another', chip:'2P sequential', sentence:'Single axis tracker, two in portrait, each module to the next with a cable to bring the far end home', command:'fire string {"mounting":"tracker","modules_high":2,"routing":"one-after-another","jumpers":1,"lead_plus_m":0.35,"lead_minus_m":0.28}' },
  { family:'STRINGS', pin:-9, name:'Fixed tilt, one in portrait, leapfrog', chip:'1P leapfrog', sentence:'A single row of thirty modules, every other one joined on the way out, the rest on the way back', command:'fire string {"mounting":"fixed","modules_high":1,"routing":"leapfrog"}' },
  { family:'STRINGS', pin:-8, name:'Fixed tilt, one in portrait, one after another', chip:'1P sequential', sentence:'A single row, each module to the next, and one cable the length of the row to bring the far end home', command:'fire string {"mounting":"fixed","modules_high":1,"routing":"one-after-another"}' },
  { family:'STRINGS', pin:-7, name:'Fixed tilt, two in portrait, along and back', chip:'2P fixed U', sentence:'A table two modules high, out along the lower tier and back along the upper: no return cable is laid', command:'fire string {"mounting":"fixed","modules_high":2,"routing":"serpentine","turn_alternate_rows":1,"jumpers":1,"lead_plus_m":0.35,"lead_minus_m":0.28}' },
  { family:'STRINGS', pin:-6, name:'Fixed tilt, three in portrait, along and back', chip:'3P fixed', sentence:'A table three modules high, wired row by row, turning at the end of each', command:'fire string {"mounting":"fixed","modules_high":3,"routing":"serpentine","turn_alternate_rows":1,"jumpers":1,"lead_plus_m":0.35,"lead_minus_m":0.28}' },
  { family:'STRINGS', pin:-5, name:'Fixed tilt, four in portrait, along and back', chip:'4P fixed', sentence:'A table four modules high, wired row by row', command:'fire string {"mounting":"fixed","modules_high":4,"routing":"serpentine","turn_alternate_rows":1,"jumpers":1,"lead_plus_m":0.35,"lead_minus_m":0.28}' },
  { family:'STRINGS', pin:-4, name:'East and west facing, five in portrait each face', chip:'5P east-west', sentence:'Two faces back to back with a ridge between them, five modules in portrait on each, wired row by row', command:'fire string {"mounting":"east-west","modules_high":5,"routing":"serpentine","turn_alternate_rows":1,"jumpers":1,"lead_plus_m":0.35,"lead_minus_m":0.28}' },
  { family:'STRINGS', pin:-3, name:'Fixed tilt landscape, three high', chip:'3L landscape', sentence:'Modules laid on their side, three high: the two junction boxes now sit one above the other', command:'fire string {"mounting":"fixed","orientation":"landscape","modules_high":3,"routing":"serpentine","turn_alternate_rows":1,"jumpers":1,"lead_plus_m":0.35,"lead_minus_m":0.28}' },
  { family:'STRINGS', pin:-2, name:'Fixed tilt landscape, six high', chip:'6L landscape', sentence:'Modules on their side, six high, wired row by row', command:'fire string {"mounting":"fixed","orientation":"landscape","modules_high":6,"routing":"serpentine","turn_alternate_rows":1,"jumpers":1,"lead_plus_m":0.35,"lead_minus_m":0.28}' },
  { family:'STRINGS', pin:-1, name:'Leapfrog turned, every second module end for end', chip:'1P leapfrog turned', sentence:'Turning every second module end for end makes every link the short kind', command:'fire string {"wiring":"leapfrog","turn_every_second":1,"lead_plus_m":0.84,"lead_minus_m":1.166}' },
  { family:'THE GRID', pin:-30, name:'One substation and every way out of it', chip:'Barking', sentence:'Barking as a station on a map: one coloured line for every circuit route out of it, the voltage the colour, the number of circuits the weight', command:'fire substation {"site":"Barking"}' },
  { family:'THE GRID', pin:-29, name:'The same map with the distances to scale', chip:'neighbours', sentence:'The far stations pushed out to their real distance, so the shape of the map is the shape of the network', command:'fire substation {"site":"Barking","neighbours":1}' },
  { family:'THE GRID', pin:-28, name:'The pulse out from the station', chip:'pulse', sentence:'The front runs out from the station along every line in order of electrical distance, shortest first: this shows CONNECTIVITY, not power', command:'fire substation {"site":"Barking","pulse":1}' },
  { family:'THE GRID', pin:-27, name:'One way out taken off', chip:'outage', sentence:'One circuit route open: it carries nothing and its far station goes dark, and every other way out still lights', command:'fire substation {"site":"Barking","outage":"West Ham"}' },
  { family:'STRINGS', pin:1, name:'One whole inverter block, every string on it', chip:'inverter block', sentence:'Twenty-four strings of thirty modules in series on one inverter: all twenty-four drawn, each with its own two home runs landing on its own named inverter input', command:'fire block {}' },
  { family:'STRINGS', pin:0, name:'A tracker, two in portrait, zigzag between the rows', chip:'2P zigzag', sentence:'Single axis tracker, two in portrait, up one column and along, down the next and along', command:'fire string {"mounting":"tracker","modules_high":2,"routing":"zigzag","jumpers":1,"lead_plus_m":0.84,"lead_minus_m":1.166}' },
];
const FIRE_FALLBACK = [
  { family:'NETWORKS', name:'A chain of substations on full solar', sentence:'A chain of substations, full solar, light load', command:'fire network {"seed":5,"solar":1,"generator":0,"load":0.3}' },
  { family:'NETWORKS', name:'A tree of substations with its generator running', sentence:'A tree of substations, full solar, generator running', command:'fire network {"seed":11,"solar":1,"generator":1,"load":0.3}' },
  { family:'NETWORKS', name:'A factory of seven substations at full load, no solar', sentence:'Sub-boards, seven substations, full load, no solar', command:'fire network {"seed":2026,"solar":0,"generator":0,"load":1}' },
  { family:'NETWORKS', name:'The same factory at the end of a weak grid', sentence:'The same sub-boards on a weak grid', command:'fire network {"seed":2026,"variant":2,"solar":1,"generator":0,"load":0.3}' },
  { family:'NETWORKS', name:'The same factory with every cable three times as long', sentence:'The same sub-boards with every cable three times as long', command:'fire network {"seed":2026,"variant":3,"solar":1,"generator":0,"load":1}' },
  { family:'SITE PULSE', name:'A works with its own solar at full output', sentence:'Site pulse: solar at full output, no generator, load 30%', command:'fire site-pulse {"scenario":3,"load_share":0.3}' },
  { family:'SITE PULSE', name:'The same works with one substation disconnected', sentence:'Site pulse: solar at full output, the tenant substation disconnected', command:'fire site-pulse {"scenario":7,"load_share":0.3}' } ];

// TWO TESTS ARE THE SAME TEST when they draw the same picture and end on the same numbers. The picture is
// the seed and the variant; the numbers are the row the bench recorded when it solved the case. Of the
// 1,000 networks published at 04:06 on 20 September, 102 were another entry word for word in everything a
// reader can see - the same seed at the same solar and the same load, with the generator called on and
// then off, which on those networks moves no dot and no figure - and a list like that reads as nonsense.
// Nothing is offered twice. Where the bench recorded no row, the command itself is the key.
function fireKey(c){
  const r = c && c.row, cmd = String((c && c.command) || '');
  if (!r || typeof r !== 'object') return cmd;
  const seed = /"seed"\s*:\s*(-?\d+)/.exec(cmd), variant = /"variant"\s*:\s*(\d+)/.exec(cmd);
  return [seed ? seed[1] : '?', variant ? variant[1] : '0', r.p_kw, r.vmax_pu, r.vmin_pu, r.worst_tx_pct, r.flags].join('|');
}
function dedupeCommands(list){
  const seen = new Set(), out = [];
  for (const c of (Array.isArray(list) ? list : [])) { const k = fireKey(c); if (seen.has(k)) continue; seen.add(k); out.push(c); }
  return out;
}
// A NAME A BANKER CAN READ. The published list carries one; an older list does not, and then the first
// half of the sentence, up to the colon, is the plain name and the whole sentence is the detail under it.
function plainName(c){
  if (c && c.name) return String(c.name);
  const s = String((c && c.sentence) || (c && c.command) || '');
  const at = s.indexOf(':');
  return at > 8 ? s.slice(0, at) : s;
}
// WHAT TO PIN WHEN NOTHING IS PINNED. The published list says which hundred are worth showing; if the list
// that arrives is older than that, a set is chosen here that is visibly different: no two the same shape,
// the same size of network and the same thing being tested.
function curateCommands(list, want){
  const out = [], taken = new Set();
  for (const c of list) {
    const m = /^A ([a-z-]+(?: network)?) of (\d+)/.exec(String(c.sentence || ''));
    const shape = m ? m[1] : (c.family || 'other'), n = m ? +m[2] : 0;
    const band = n <= 3 ? 'small' : (n <= 8 ? 'middling' : 'large');
    const key = shape + '|' + band + '|' + (c.kind || c.family || '');
    if (taken.has(key)) continue;
    taken.add(key); out.push(c);
    if (out.length >= want) break;
  }
  return out;
}
// a chip is a short word, so a chip takes the head of the name and nothing else
function chipWords(c){
  if (c && c.chip) return String(c.chip);                 // a name short enough to tell eight presets apart
  const n = plainName(c), at = n.indexOf(',');
  const head = at > 4 ? n.slice(0, at) : n;
  return head.length > 30 ? head.slice(0, 29) + '…' : head;
}

let fireBarMade = false;
let closeFireMenu = null;                                // set when the bar is built: an answer always shuts the picker's list
let sayOpen = null;                                      // set when the bar is built: open the window on some words
function makeFireBar(){
  if (fireBarMade) return; fireBarMade = true;
  if (!document.body) return;
  const st = document.createElement('style');
  // The wafer's own rules, kept: the bottom of the screen is a stack, not a pile.
  st.textContent = ':root{--cmd:56px;--footh:34px;--stack:calc(var(--cmd) + var(--footh) + 8px);--egh:0px;--above:calc(var(--stack) + 8px)}'
    // THE BAR IS INSIDE THE SHELL'S OWN FOOT, not fixed on top of it. The wafer's bar is the last thing at
    // the bottom of its page, under the one line that says what the page is not, and the Kuiper's shell
    // measures its foot to decide how big the disc is and where the work card sits. A bar fixed over the
    // foot was a bar the shell could not see: the card checks read the card as off the screen at 390. So
    // the same component is built as the last child of #foot, and the picker as its first, and everything
    // the shell does about height goes on working.
    + '#pilot{display:flex;gap:8px;margin-top:7px;padding-top:7px;border-top:1px solid #1b2030}'
    + '#pilot input{flex:1;min-width:0;font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#11151f;color:#cfe3f2;'
    + 'border:1px solid #1b2030;border-radius:6px;padding:.6rem .9rem}'
    + '#pilot input:focus{outline:1px solid #5ec8f2}'
    + '#pilot input::placeholder{color:#5b6377}'
    // THE BAND IS FILLED, NOT SHORTENED. The examples box sat against the right edge and left a wide strip
    // of empty dark beside it, between the rule at the top of the foot and the bar. Making the box one line
    // shorter closed the strip and ALSO made the foot shorter, and the page's own checks refused that at
    // once: the shell measures its foot to decide how big the disc is, where the work card sits and where
    // every gathered dot lands, and three checks that had passed all night failed. So the box keeps its
    // height to the pixel and is widened to the whole line instead: the strip is the box now.
    + '#eg{margin:0 0 6px;width:auto;max-width:none;background:#0e121b;border:1px solid #1b2030;'
    + 'border-radius:8px;padding:.45rem .7rem;display:flex;flex-direction:column;gap:4px}'
    + '#eg select{align-self:flex-end;width:min(30rem,70vw)}'
    + '#eg label{font:11px ui-monospace,Menlo,Consolas,monospace;letter-spacing:.08em;text-transform:uppercase;color:#8b93a7}'
    + '#eg select{font:12px ui-monospace,Menlo,Consolas,monospace;background:#11151f;color:#cfe3f2;border:1px solid #1b2030;border-radius:6px;padding:.45rem .7rem;max-width:44vw}'
    + '#presets{position:fixed;left:12px;top:12px;z-index:19;display:flex;gap:6px;flex-wrap:wrap;max-width:min(62vw,calc(100% - 24px))}'
    + '#presets button{font:11px/1.6 ui-monospace,Menlo,Consolas,monospace;color:#8b93a7;background:#0b0e14;border:1px solid #232a3a;'
    + 'border-radius:4px;padding:2px 9px;cursor:pointer}'
    + '#presets button:hover,#presets button:focus-visible{color:#e6e9f0;border-color:#4a5573;outline:none}'
    + '#say{position:fixed;left:50%;top:20px;transform:translateX(-50%);width:min(72ch,84vw);'
    + 'max-height:calc(100vh - var(--footh) - 56px);min-width:280px;min-height:64px;background:#0e121bf2;'
    + 'border:1px solid #1b2030;border-radius:8px;padding:0;font:14px/1.5 ui-monospace,Menlo,Consolas,monospace;color:#cfe3f2;'
    + 'z-index:21;resize:both;overflow:hidden;display:none;flex-direction:column}'
    + '#say.open{display:flex}'
    + '#say.max{left:12px;top:12px;right:12px;bottom:calc(var(--footh) + 12px);transform:none;width:auto;max-height:none;height:auto}'
    + '#say.min{height:auto!important;max-height:none;min-height:0;resize:none;width:min(48ch,84vw)} #say.min #saybody{display:none}'
    + '#saybar{display:flex;align-items:center;gap:6px;padding:4px 8px;border-bottom:1px solid #1b2030;background:#11151f;'
    + 'cursor:move;user-select:none;font-size:11px;color:#8b93a7;letter-spacing:.06em;text-transform:uppercase}'
    + '#saybar span{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}'
    + '#saybar button{font:12px ui-monospace,Menlo,Consolas,monospace;background:#0e121b;color:#cfe3f2;border:1px solid #1b2030;'
    + 'border-radius:4px;width:24px;height:22px;cursor:pointer;padding:0}'
    + '#saybar button:hover,#saybar button:focus-visible{border-color:#5ec8f2;outline:none}'
    + '#saybody{padding:.8rem 1.1rem;overflow:auto;flex:1}'
    + '#saybody b{color:#5ec8f2;font-weight:600}#saybody i{color:#f2b05e;font-style:normal}'
    + '#saybody p{margin:.45rem 0}#saybody .dimtext{color:#8b93a7;font-size:12px;line-height:1.45}'
    + '#saybody table{border-collapse:collapse;width:100%;margin:.5rem 0}'
    + '#saybody td{padding:2px 0;border-bottom:1px solid #1b2030;font-size:12.5px}#saybody td+td{text-align:right;color:#fff}'
    + '#saybody code{display:block;background:#11151f;border:1px solid #1b2030;border-radius:4px;padding:4px 7px;color:#cfe3f2;'
    + 'margin:6px 0;font-size:11.5px;word-break:break-all}'
    + '#saybody .more,#saybody .edit{background:none;border:0;color:#8b93a7;font:inherit;font-size:11.5px;text-decoration:underline;cursor:pointer;padding:4px 0}'
    + '#saybody .more:hover,#saybody .edit:hover{color:#5ec8f2}'
    + '#saybody #apps{display:flex;flex-wrap:wrap;gap:6px;margin:.4rem 0 .2rem}'
    + '#saybody .viewrow{display:flex;flex-wrap:wrap;gap:6px;margin:.4rem 0 .2rem}'
    + '#saybody .viewrow button{font:11px/1.6 ui-monospace,Menlo,Consolas,monospace;color:#8b93a7;background:#0b0e14;'
    + 'border:1px solid #232a3a;border-radius:4px;padding:3px 9px;cursor:pointer}'
    + '#saybody .boxes{display:grid;grid-template-columns:1fr 1fr;gap:3px 12px;margin:.5rem 0 .2rem;'
    + 'border-top:1px solid #1b2030;padding-top:.5rem}'
    + '#saybody .boxrow{display:flex;align-items:center;gap:6px;min-width:0}'
    + '#saybody .boxlab{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;'
    + 'font:11px ui-monospace,Menlo,Consolas,monospace;color:#8b93a7}'
    + '#saybody .boxrow input,#saybody .boxrow select{width:5.4rem;flex:none;font:11.5px ui-monospace,Menlo,Consolas,monospace;'
    + 'background:#11151f;color:#cfe3f2;border:1px solid #1b2030;border-radius:4px;padding:2px 5px}'
    + '#saybody .boxrow input:focus,#saybody .boxrow select:focus{outline:1px solid #5ec8f2;border-color:#5ec8f2}'
    + '#saybody .boxrow input.bad{border-color:#ffb454;color:#ffb454}'
    + '#saybody .boxes button.edit{grid-column:1/-1;text-align:left}'
    + '#saybody .conns{max-height:11rem;overflow:auto;border:1px solid #1b2030;border-radius:4px;margin:.2rem 0 .5rem}'
    + '#saybody .conns button{display:block;width:100%;text-align:left;background:none;border:0;border-bottom:1px solid #141a26;'
    + 'color:#a8b6c8;font:11px ui-monospace,Menlo,Consolas,monospace;padding:3px 7px;cursor:pointer}'
    + '#saybody .conns button:hover,#saybody .conns button:focus-visible{background:#131a26;color:#eaf6ff;outline:none}'
    + '#saybody .conns button.bad{color:#ffb454}'
    + '#saybody .values td{text-align:left;vertical-align:top}'
    + '#saybody .values tr.bad td{color:#ffb454;font-weight:600}'
    + '#saybody p.danger{color:#ff5a4f;font-weight:600;font-size:12px;letter-spacing:.04em;margin:.1rem 0 .5rem;'
    + 'border:1px solid #5a2620;border-radius:4px;padding:5px 8px;background:#1a0d0b}'
    // THE BOTTOM OF THE SCREEN IS A STACK, NOT A PILE - the wafer's own rule, and the Kuiper's card has to
    // obey it too. On a phone the shell puts its work card at the very bottom, where the bar and the
    // examples picker now are, and the page's own card checks caught it: four of them read the card as
    // off the screen. The card is lifted to the top of the measured stack instead.
    + '@media (max-width:700px){#pilot input{font-size:16px;min-height:44px}'

    + '#eg{padding:.35rem .6rem}#eg label{font-size:10px}#eg select{align-self:stretch;width:auto;max-width:none;min-height:40px}'