GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / tools/intelligence/cartridges/grid-actions-inline

Make Cartridge and 1 more file (part 2)

A Python command-line tool in the grid actions inline folder of PipelineNews covering substations, 33kV, cables and 11kV, using SHA-256.

529 lines of Python and JavaScript from pipelinenews, in 2 files. Topic: Electricity markets and data pipelines. Section 1037 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. Make Cartridge ingest · pipelinenews / tools/intelligence/cartridges/grid-actions-inline/make_cartridge.py lines 1–340
  2. Proof render · pipelinenews / tools/intelligence/cartridges/grid-actions-inline/proof.mjs lines 1–189

Make Cartridge

A Python command-line tool in the grid actions inline folder of PipelineNews covering substations, 33kV, cables and 11kV, using SHA-256.

ingestpipelinenews / tools/intelligence/cartridges/grid-actions-inline/make_cartridge.py · lines 1–340 of 340 · Entry point · pattern anchor (shared by 16 files)

What it does
It lists and searches substations, 33kV, cables and 11kV. Defines read, anchor, main. Uses libraries argparse, io, json, os, sys. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: substations, 33kV, cables, 11kV.
Inputs & outputs
In: JSON file cartridge.json; command-line arguments. Voltage levels named: 33kV, 11kV.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the read step (`read`) and the anchor step (`anchor`). Generate `cartridge.json`: move GRID out of the table and into ACTIONS, alongside a new nearest 33kV+ substation distance. Its code works with 33 kV, 11 kV and 40 MW. It accepts `--parent`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · tools/intelligence/cartridges/grid-actions-inline · Python CLI
Uses
argparse, io, json, os, sys
Used by
none found
Produces
read, anchor, main
Defines here
read, anchor, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/grid-actions-inline/make_cartridge.py:1-340 · blob 5589710a49cf45fa9d5fd88b675bdde4b9dfc1bf · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Generate cartridge.json: move GRID out of the table and into ACTIONS,
alongside a new nearest 33 kV+ substation distance.

WHY THE COLUMN GOES AWAY
------------------------
The GRID column worked and nobody could see it. Measured from the published
bytes, desktop-visible text only, its right edge sat at ~1,430px while a 1366px
laptop shows ~1,056px of table. It only cleared the fold at about 1920px.

Beside the MAP link it is reachable at any width, and the pairing is the right
one: MAP opens the Atlas, and the distances are measured against the Atlas
layers. Both are per-project facts about where this site sits on the network.

WHAT IS LOST, AND WHAT IS KEPT
------------------------------
A sortable heading needs a column, so click-to-sort on distance goes with it.
Sorting itself does NOT: `grid_asc` and `grid_desc` stay in the SORT control,
so the register can still be ordered nearest-first from the dropdown. Only the
heading disappears.

    python make_cartridge.py --parent 202608311816-pipelinenews
"""

import argparse
import io
import json
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(HERE))))
RELEASES = os.path.join(REPO, "releases")
APP = "assets/202608291447-app.mjs"


def read(path):
    return io.open(path, encoding="utf-8", newline="").read()


def anchor(text, needle, label):
    n = text.count(needle)
    if n != 1:
        raise SystemExit("anchor %r occurs %d times, expected 1:\n%s"
                         % (label, n, needle[:220]))
    return needle


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--parent", default="202608311816-pipelinenews")
    a = ap.parse_args()

    parent = os.path.join(RELEASES, a.parent)
    if not os.path.isdir(parent):
        raise SystemExit("no such parent release: %s" % parent)
    idx = read(os.path.join(parent, "index.html"))
    app = read(os.path.join(parent, APP))

    ri, ra = [], []

    # ---- index.html: drop the GRID heading ------------------------------
    th_from = anchor(idx,
                     '            <th class="hide-mobile sortable-heading" id="gridHeader" aria-sort="none">\n'
                     '              <button id="sortGrid" type="button" aria-label="Sort by straight-line distance to the nearest mapped grid circuit">\n'
                     '                GRID <span class="beta-chip">BETA</span> <span id="gridSortIndicator" aria-hidden="true">↕</span>\n'
                     '              </button>\n'
                     '            </th>\n'
                     '            <th class="hide-mobile">OPERATOR</th>',
                     "grid heading")
    ri.append({"label": "GRID heading removed; the metrics move into ACTIONS",
               "from": th_from,
               "to": '            <th class="hide-mobile">OPERATOR</th>'})

    # ---- index.html: styles for the inline metrics ----------------------
    css_from = anchor(idx, "    .grid-note { color: #8d98a5; font-size: 9px; }",
                      "grid-note css")
    css_to = css_from + """

    /* GRID and SUB inside ACTIONS. Chips rather than links: they are facts
       about the row, not things to click, so they must not read as buttons. */
    .action-metric {
      display: inline-block; white-space: nowrap; font-size: 9px;
      font-variant-numeric: tabular-nums; padding: 3px 6px; border-radius: 3px;
      border: 1px solid #2b3138; background: #0a0d12; color: #8d98a5;
      cursor: help;
    }
    .action-metric b { font-weight: bold; color: #d8dee6; margin-left: 3px; }
    .action-metric .unit { color: #6c7681; margin-left: 2px; }
    /* Band tints the number only. A band says how close the mapped network is;
       it never implies a connection is obtainable there. */
    .action-metric[data-band="STRONG"] b { color: #6fd18a; }
    .action-metric[data-band="MODERATE"] b { color: #d8c96a; }
    .action-metric[data-band="DISTANT"] b { color: #d89a6a; }
    .action-metric[data-band="REMOTE"] b { color: #b06a6a; }
    .action-metric.pending { color: #4d555e; }
    .project-actions { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }"""
    ri.append({"label": "inline metric chip styles", "from": css_from, "to": css_to})

    # ---- app.mjs: renderers ---------------------------------------------
    # Replace the table-cell renderer with two chip renderers.
    cell_from = anchor(app,
                       'function gridCellHtml(item) {\n'
                       '  if (!gridDistance) return "\\u2026";\n'
                       '  const hit = gridFor(item);\n'
                       '  if (!hit || typeof hit.k !== "number") return "-";\n'
                       '  const parts = [`Nearest mapped circuit ${hit.k.toFixed(2)} km${hit.v ? ` at ${hit.v} kV` : ""}`];\n'
                       '  if (typeof hit.t === "number") parts.push(`transmission ${hit.t.toFixed(2)} km${hit.tv ? ` (${hit.tv} kV)` : ""}`);\n'
                       '  if (typeof hit.d === "number") parts.push(`distribution ${hit.d.toFixed(2)} km${hit.dv ? ` (${hit.dv} kV)` : ""}`);\n'
                       '  parts.push("Straight-line to mapped geometry, not a cable route or a connection length.");\n'
                       '  parts.push("Fault level and thermal headroom are not shown and cannot be inferred from distance: they need DNO network data such as source impedance and are established by a connection study.");\n'
                       '  const band = hit.b ? ` data-band="${escapeHtml(hit.b)}"` : "";\n'
                       '  return `<span${band} title="${escapeHtml(parts.join(" \\u00b7 "))}"><span class="km">${hit.k.toFixed(2)}</span><span class="kv">km${hit.v ? ` \\u00b7 ${hit.v}kV` : ""}</span></span>`;\n'
                       '}',
                       "gridCellHtml")

    cell_to = '''// The nearest 33 kV+ substation, keyed by REPD ref. Scope is 33 kV and above:
// 11 kV is rare for utility-scale export and where it occurs is often a private
// network behind the meter, so it is not a screening signal. Every one of the
// 5,800 substations in the Atlas layer qualifies, so nothing is filtered out at
// runtime -- the scope is a property of the layer, recorded in the payload.
let substation = null;

function substationFor(item) {
  return (substation && substation[String(item.repd_ref)]) || null;
}

// The sentence a distance can never answer. Held in one place so the two chips
// and the strip cannot drift apart.
const HEADROOM_CAVEAT = "Fault level and thermal headroom cannot be inferred from "
  + "distance: they depend on DNO network data such as source impedance, fault "
  + "infeed and existing committed connections, and are established by a "
  + "connection study.";

function metricChip({ ready, hit, label, unitSuffix, lines }) {
  if (!ready) return `<span class="action-metric pending">${label} \\u2026</span>`;
  if (!hit || typeof hit.k !== "number") {
    // Absence from a mapped layer is not absence on the ground, so this is a
    // dash and never a large number standing in for "not found".
    return `<span class="action-metric" title="No mapped feature found for this project. Absence from a mapped layer is not absence on the ground.">${label} -</span>`;
  }
  const band = hit.b ? ` data-band="${escapeHtml(hit.b)}"` : "";
  const title = escapeHtml(lines.filter(Boolean).join(" \\u00b7 "));
  return `<span class="action-metric"${band} title="${title}">${label}`
    + `<b>${hit.k.toFixed(2)}</b><span class="unit">km${unitSuffix}</span></span>`;
}

// Distance to the nearest mapped circuit, at 33 kV and above.
function gridActionHtml(item) {
  const hit = gridFor(item);
  const lines = [];
  if (hit && typeof hit.k === "number") {
    lines.push(`Nearest mapped circuit ${hit.k.toFixed(2)} km${hit.v ? ` at ${hit.v} kV` : ""}`);
    if (typeof hit.t === "number") lines.push(`transmission ${hit.t.toFixed(2)} km${hit.tv ? ` (${hit.tv} kV)` : ""}`);
    if (typeof hit.d === "number") lines.push(`distribution ${hit.d.toFixed(2)} km${hit.dv ? ` (${hit.dv} kV)` : ""}`);
    lines.push("Straight-line to mapped geometry, not a cable route or a connection length.");
    lines.push(HEADROOM_CAVEAT);
  }
  return metricChip({
    ready: Boolean(gridDistance), hit, label: "GRID",
    unitSuffix: hit && hit.v ? ` \\u00b7 ${hit.v}kV` : "", lines,
  });
}

// Distance to the nearest 33 kV+ substation -- for a scheme of a few tens of MW
// this is closer to where it would actually connect than the circuit is.
function substationActionHtml(item) {
  const hit = substationFor(item);
  const lines = [];
  if (hit && typeof hit.k === "number") {
    lines.push(`Nearest substation at 33 kV or above, ${hit.k.toFixed(2)} km`
      + (hit.n ? ` \\u2014 ${hit.n}` : "")
      + (hit.v && hit.v.length ? ` (${hit.v.join("/")} kV)` : ""));
    lines.push("A mapped substation point does not confirm capacity, voltage suitability, connection rights, queue position or acceptance by any network party.");
    lines.push(HEADROOM_CAVEAT);
  }
  return metricChip({
    ready: Boolean(substation), hit, label: "SUB", unitSuffix: "", lines,
  });
}'''
    ra.append({"label": "chip renderers for GRID and SUB", "from": cell_from, "to": cell_to})

    # ---- app.mjs: drop the cell, add the chips to ACTIONS ----------------
    td_from = anchor(app, '<td class="hide-mobile grid-cell">${gridCellHtml(item)}</td>',
                     "grid td")
    ra.append({"label": "GRID table cell removed", "from": td_from, "to": ""})

    act_from = anchor(app,
                      '<div class="project-actions">${mapAction}<a class="action-link newslink"',
                      "actions div")
    act_to = ('<div class="project-actions">${mapAction}${gridActionHtml(item)}'
              '${substationActionHtml(item)}<a class="action-link newslink"')
    ra.append({"label": "GRID and SUB placed after MAP inside ACTIONS",
               "from": act_from, "to": act_to})

    span_from = anchor(app, '<tr><td colspan="14" class="fast-fail">', "colspan")
    ra.append({"label": "fail-closed row back to 13 columns",
               "from": span_from, "to": '<tr><td colspan="13" class="fast-fail">'})

    # ---- app.mjs: the heading is gone, the sort is not ------------------
    head_from = anchor(app,
                       '  // Nearest first: the screening question is "what is close", so the\n'
                       '  // first click answers it rather than showing the most remote sites.\n'
                       '  grid: { header: "gridHeader", indicator: "gridSortIndicator", asc: "grid_asc", desc: "grid_desc", first: "grid_asc" },\n',
                       "grid SORT_HEADINGS")
    ra.append({"label": "grid heading wiring removed; grid_asc/grid_desc stay in SORTS",
               "from": head_from, "to": ""})

    # ---- app.mjs: load the substation payload ---------------------------
    loader_from = anchor(app, "async function loadGridDistance() {", "loadGridDistance")
    loader_to = '''async function loadSubstation33kv() {
  const entry = registry.supplemental_assets?.grid_actions_inline;
  if (!entry) return;
  try {
    runtimeEvidence.substationRequests += 1;
    const payload = await fetchImmutable(entry.payload.path);
    invariant(payload.schema === entry.payload.schema, "substation schema mismatch");
    invariant(payload.generation === entry.generation, "substation generation mismatch");
    invariant(payload.substation && typeof payload.substation === "object", "substation index missing");
    substation = payload.substation;
    runtimeEvidence.substationReady = true;
  } catch (error) {
    // A substation payload that will not load must not take the table with it.
    substation = null;
  }
}

''' + loader_from
    ra.append({"label": "substation loader", "from": loader_from, "to": loader_to})

    boot_from = anchor(app, "  await loadGridDistance();", "loadGridDistance call")
    ra.append({"label": "load the substation payload during boot",
               "from": boot_from, "to": boot_from + "\n  await loadSubstation33kv();"})

    ev_from = anchor(app, "  gridDistanceRequests: 0,\n  gridDistanceReady: false,",
                     "grid evidence counters")
    ra.append({"label": "runtime evidence counters",
               "from": ev_from,
               "to": ev_from + "\n  substationRequests: 0,\n  substationReady: false,"})

    # ---- app.mjs: the strip now describes both --------------------------
    note_from = anchor(app,
                       '      note.textContent = `GRID \\u00b7 BETA \\u00b7 straight-line km to the nearest mapped circuit \\u00b7 `\n'
                       '        + `${(payload.projects || 0).toLocaleString("en-GB")} measured, ${strong} within 2 km \\u00b7 `\n'
                       '        + `not a cable route, and not headroom`;',
                       "note text")
    note_to = ('      note.textContent = `GRID + SUB \\u00b7 BETA \\u00b7 in the ACTIONS column, beside MAP \\u00b7 `\n'
               '        + `straight-line km to the nearest mapped circuit and to the nearest substation at 33 kV or above \\u00b7 `\n'
               '        + `${(payload.projects || 0).toLocaleString("en-GB")} projects measured, ${strong} within 2 km of a circuit \\u00b7 `\n'
               '        + `not a cable route, and not headroom \\u2014 fault level and thermal headroom need DNO network data such as source impedance and a connection study`;')
    ra.append({"label": "strip describes both metrics and where they now live",
               "from": note_from, "to": note_to})

    man = {
        "key": "grid_actions_inline",
        "summary": ("GRID and a new nearest 33 kV+ substation distance move into "
                    "the ACTIONS column beside MAP, where they are reachable at "
                    "any window width. The GRID column and its sortable heading "
                    "are removed; grid_asc and grid_desc remain in the sort "
                    "control."),
        "modifies_existing_dashboard": True,
        "modification_note": ("This cartridge is NOT panel-only. It removes a "
                              "column, adds two metric chips to the ACTIONS cell, "
                              "narrows the fail-closed row back to 13, and adds a "
                              "second payload fetched during boot."),
        "repairs": {"index.html": ri, "app": ra},
        "hash_fields": [{"at": ["payload", "sha256"],
                         "path": "data/{GEN}-substation-33kv.json"}],
        "registry_entry": {
            "schema": "pipelinenews.grid-actions-supplemental-asset.v1",
            "generation": "{GEN}",
            "usage_context": "NON_COMMERCIAL_OPEN_SOURCE",
            "usage_context_establishes_upstream_rights": False,
            "activation": "fetched once during boot, before the first table paint; fails soft",
            "additive_only": False,
            "mutates_existing_dashboard": ("removes the GRID column and places "
                                           "GRID and SUB inside ACTIONS"),
            "network_at_runtime": False,
            "payload": {"schema": "pipelinenews.substation-33kv.v1",
                        "path": "data/{GEN}-substation-33kv.json",
                        "sha256": "", "bytes": 0},
            "placement": {
                "was": "a sortable GRID column between POSTCODE and OPERATOR",
                "now": "GRID and SUB chips in the ACTIONS cell, after MAP",
                "why": ("Measured from the published bytes, the GRID column's "
                        "right edge sat at ~1,430px while a 1366px laptop shows "
                        "~1,056px of table; it only cleared the fold at about "
                        "1920px. Beside MAP it is reachable at any width, and "
                        "MAP opens the Atlas the distances are measured against."),
                "cost": ("A sortable heading needs a column, so click-to-sort on "
                         "distance is gone. Sorting is not: grid_asc and "
                         "grid_desc remain in the SORT control."),
            },
            "substation_scope": {
                "minimum_kv": 33,
                "why": ("33 kV and above. 11 kV is rare for utility-scale export "
                        "and where it occurs is often a private network behind "
                        "the meter, so it is not a screening signal."),
                "layer": ("All 5,800 substations in the Atlas layer carry at "
                          "least 33 kV; 4,342 carry 33 kV itself. Nothing is "
                          "excluded, so the published substation distance is "
                          "already the nearest 33 kV+ substation."),
                "why_it_matters": ("A scheme of a few tens of MW connects at a "
                                   "substation, not to a conductor it sits "
                                   "under. Median distance to a 33 kV+ "
                                   "substation is 1.52 km against 6.44 km to a "
                                   "33 kV circuit, and for the 30-40 MW band the "
                                   "substation is the closer of the two for 68% "
                                   "of projects."),
            },
            "cannot_be_inferred": (
                "Fault level and thermal headroom. These are properties of the "
                "network, not of the geometry: they depend on DNO data such as "
                "source impedance, fault infeed and existing committed "
                "connections, and are established by a connection study. No "
                "distance, at any precision, implies them. Proximity to a mapped "
                "substation is not capacity at it."),
            "provenance": {
                "geometry": ("OpenStreetMap-derived overhead line and substation "
                             "layers, ODbL-1.0, (c) OpenStreetMap contributors."),
                "mathematics": ("Ventusltd/grid-distance-maths src/geodesy.py. "
                                "All 3,047 published substation distances were "
                                "re-measured against it at build time and "
                                "reproduced within the source payload's own "
                                "rounding."),
            },
        },
    }

    out = os.path.join(HERE, "cartridge.json")
    io.open(out, "w", encoding="utf-8", newline="").write(
        json.dumps(man, ensure_ascii=False, indent=2) + "\n")
    print("wrote cartridge.json")
    print("  index.html repairs  %d" % len(ri))
    print("  app.mjs repairs     %d" % len(ra))
    print("  every anchor verified unique in %s" % a.parent)
    return 0


if __name__ == "__main__":
    sys.exit(main())

Proof

A JavaScript module in the grid actions inline folder of PipelineNews that fetches substations, 33kV, the Renewable Energy Planning Database (REPD) register and cables.

renderpipelinenews / tools/intelligence/cartridges/grid-actions-inline/proof.mjs · lines 1–189 of 189 · Not reached from any entry point (candidate for review) · pattern expected (shared by 5 files)

What it does
It fetches substations, 33kV, the REPD register and cables. Defines 6 functions or classes, including check, $, rowsOf, refOf, kmOf. Uses libraries node:fs/promises, node:path, node:url, node:crypto, jsdom. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: substations, 33kV, the REPD register, cables, 11kV.
Inputs & outputs
In: JSON file 202608270055-8ab1807551bc-v8-fast-projects.json; command-line arguments. Voltage levels named: 33kV, 11kV.
What it achieves
It is built from the check step (`check`), the rows of helper (`rowsOf`) and the ref of helper (`refOf`). Grid-actions-inline render proof. Its code works with 33 kV and 11 kV.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · tools/intelligence/cartridges/grid-actions-inline · JavaScript module
Uses
node:fs/promises, node:path, node:url, node:crypto, jsdom
Used by
none found
Produces
check, $, rowsOf, refOf, kmOf, expected
Defines here
check, $, rowsOf, refOf, kmOf, expected
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/grid-actions-inline/proof.mjs:1-189 · blob 6b819012a2db2ce63dd93d619d5006efde306b76 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * grid-actions-inline render proof.
 *
 * The GRID column is gone and the two distances now live inside ACTIONS. That
 * is a placement change, so the things worth proving are: the numbers survived
 * the move unchanged, the substation distance is real, the caveats travelled
 * with them, and the sort that used to hang off the heading still works from
 * the dropdown.
 *
 * Every count and value is re-derived from the payloads, never read back out of
 * the element it came from.
 *
 *   node proof.mjs <release-dir> <generation> <grid-distance-generation>
 */

import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { webcrypto } from "node:crypto";
import { JSDOM } from "jsdom";

const root = process.argv[2];
const gen = process.argv[3];
const gridGen = process.argv[4] ?? gen;
if (!root || !gen) {
  console.error("usage: node proof.mjs <release-dir> <generation> [grid-gen]");
  process.exit(2);
}

let passed = 0;
const failures = [];
const check = (label, ok, detail = "") => {
  if (ok) passed += 1; else failures.push(`${label}${detail ? ` -- ${detail}` : ""}`);
};

const html = await readFile(join(root, "index.html"), "utf8");
const dom = new JSDOM(html, { url: "http://localhost/", pretendToBeVisual: true, runScripts: "outside-only" });
const { window } = dom;
window.fetch = async (i) => {
  const u = new URL(String(i?.url ?? i), "http://localhost/");
  try {
    const b = await readFile(join(root, decodeURIComponent(u.pathname).replace(/^\//, "")), "utf8");
    return { ok: true, status: 200, json: async () => JSON.parse(b), text: async () => b };
  } catch { return { ok: false, status: 404, json: async () => ({}), text: async () => "" }; }
};
const K = ["document","location","history","navigator","screen","matchMedia","getComputedStyle","requestAnimationFrame","cancelAnimationFrame","Event","CustomEvent","EventTarget","AbortController","AbortSignal","Node","Element","HTMLElement","HTMLInputElement","HTMLSelectElement","HTMLOptionElement","Option","Image","DocumentFragment","NodeList","DOMParser","XMLHttpRequest","FormData","Blob","URL"  … [line shortened here: 538 characters; full line on GitHub]
for (const k of K) { let v; try { v = window[k]; } catch { continue; } if (v === undefined) continue;
  try { Object.defineProperty(globalThis, k, { value: v, writable: true, configurable: true }); } catch {} }
for (const [k, v] of [["window", window], ["fetch", window.fetch], ["crypto", webcrypto],
  ["addEventListener", window.addEventListener.bind(window)], ["dispatchEvent", window.dispatchEvent.bind(window)]])
  Object.defineProperty(globalThis, k, { value: v, writable: true, configurable: true });

await import(pathToFileURL(join(root, "assets", "202608291447-app.mjs")).href);
const ready = await new Promise((r) => { const t = Date.now(); const p = setInterval(() => {
  if (window.document.body.dataset.fastReady === "true") { clearInterval(p); r(true); }
  else if (window.document.body.dataset.fastFailed === "true") { clearInterval(p); r(false); }
  else if (Date.now() - t > 60000) { clearInterval(p); r(false); } }, 40); });
check("app boots", ready);
if (!ready) { console.error("did not boot"); console.error(failures.join("\n")); process.exit(1); }

const doc = window.document;
const $ = (s) => doc.querySelector(s);
const rowsOf = () => [...doc.querySelectorAll("#tbody tr")];

// ------------------------------------------------------- the payloads -----
const subs = JSON.parse(await readFile(join(root, "data", `${gen}-substation-33kv.json`), "utf8"));
const grid = JSON.parse(await readFile(join(root, "data", `${gridGen}-grid-distance.json`), "utf8"));

check("substation payload schema", subs.schema === "pipelinenews.substation-33kv.v1", subs.schema);
check("substation payload generation matches the release", subs.generation === gen, subs.generation);
check("substation scope is 33 kV and above", subs.scope?.minimum_kv === 33, String(subs.scope?.minimum_kv));
check("the scope records why 11 kV is excluded",
  /behind the meter/i.test(subs.scope?.why ?? ""), subs.scope?.why);
check("every substation in the layer qualifies, so nothing is silently dropped",
  subs.scope?.qualifying === subs.scope?.layer_features && subs.scope?.excluded_below_33kv === 0,
  `${subs.scope?.qualifying} of ${subs.scope?.layer_features}, ${subs.scope?.excluded_below_33kv} excluded`);
check("the substation payload makes no runtime network claim", subs.network_at_runtime === false);
check("the substation caveat names DNO impedance and a study",
  /impedance/i.test(subs.caveat?.headroom ?? "") && /connection study/i.test(subs.caveat?.headroom ?? ""),
  subs.caveat?.headroom?.slice(0, 120));

// ------------------------------------------------- the column is gone -----
const headings = [...doc.querySelectorAll("thead th")].map((th) => th.textContent.replace(/\s+/g, " ").trim());
check("the table is back to 13 columns", headings.length === 13, `${headings.length}: ${headings.join(" | ")}`);
check("no GRID heading remains", !headings.some((h) => h.startsWith("GRID")), headings.join(" | "));
check("no GRID header element remains", doc.getElementById("gridHeader") === null);
const app = await readFile(join(root, "assets", "202608291447-app.mjs"), "utf8");
const colspan = app.match(/colspan="(\d+)" class="fast-fail"/);
check("fail-closed row spans 13", colspan && colspan[1] === "13", colspan?.[1]);
const rows = rowsOf();
check("every row has 13 cells", rows.every((tr) => tr.querySelectorAll("td").length === 13),
  [...new Set(rows.map((tr) => tr.querySelectorAll("td").length))].join(","));

// ------------------------------------------- the metrics live in ACTIONS --
const actionsIndex = headings.findIndex((h) => h.startsWith("ACTIONS"));
check("ACTIONS is still the last column", actionsIndex === headings.length - 1, String(actionsIndex));

const projects = JSON.parse(await readFile(
  join(root, "data", "202608270055-8ab1807551bc-v8-fast-projects.json"), "utf8"));
const F = Object.fromEntries(projects.fields.map((n, i) => [n, i]));
const refOf = (r) => String(r[F.repd_ref]);
const byRef = new Map(projects.rows.map((r) => [refOf(r), r]));

let gridOk = 0; let subOk = 0; let gridDash = 0; let subDash = 0; let orderOk = 0;
for (const tr of rows) {
  const ref = tr.id.replace(/^repd-/, "");
  const cell = [...tr.querySelectorAll("td")][actionsIndex];
  const chips = [...cell.querySelectorAll(".action-metric")];
  const kids = [...cell.querySelector(".project-actions").children];
  const mapAt = kids.findIndex((e) => /MAP/.test(e.textContent));
  const gridAt = kids.findIndex((e) => e.classList.contains("action-metric") && /GRID/.test(e.textContent));
  const subAt = kids.findIndex((e) => e.classList.contains("action-metric") && /SUB/.test(e.textContent));
  if (mapAt !== -1 && gridAt === mapAt + 1 && subAt === gridAt + 1) orderOk += 1;

  const g = grid.grid[ref];
  const s = subs.substation[ref];
  const gText = chips.find((c) => /GRID/.test(c.textContent))?.textContent.replace(/\s+/g, "") ?? "";
  const sText = chips.find((c) => /SUB/.test(c.textContent))?.textContent.replace(/\s+/g, "") ?? "";
  if (g) { if (gText.includes(g.k.toFixed(2))) gridOk += 1; } else { if (gText.includes("-")) gridDash += 1; }
  if (s) { if (sText.includes(s.k.toFixed(2))) subOk += 1; } else { if (sText.includes("-")) subDash += 1; }
}
check("MAP, then GRID, then SUB, in that order on every row",
  orderOk === rows.length, `${orderOk} of ${rows.length}`);
check("every GRID chip matches the payload or is a dash",
  gridOk + gridDash === rows.length, `${gridOk} matched, ${gridDash} dashed, of ${rows.length}`);
check("every SUB chip matches the payload or is a dash",
  subOk + subDash === rows.length, `${subOk} matched, ${subDash} dashed, of ${rows.length}`);
check("the substation distance is present on real rows, not universally blank",
  subOk > 0, `${subOk} populated`);

const measuredChip = [...doc.querySelectorAll(".action-metric")].find((c) => /SUB/.test(c.textContent) && /\d/.test(c.textContent));
const subTitle = measuredChip?.getAttribute("title") ?? "";
check("a SUB chip says 33 kV or above", /33 kV or above/i.test(subTitle), subTitle.slice(0, 120));
check("a SUB chip carries the capacity caveat",
  /does not confirm capacity/i.test(subTitle), subTitle.slice(0, 160));
check("a SUB chip carries the headroom caveat",
  /impedance/i.test(subTitle) && /connection study/i.test(subTitle), subTitle.slice(0, 200));

const gridChip = [...doc.querySelectorAll(".action-metric")].find((c) => /GRID/.test(c.textContent) && /\d/.test(c.textContent));
const gridTitle = gridChip?.getAttribute("title") ?? "";
check("a GRID chip still says it is not a cable route",
  /not a cable route/i.test(gridTitle), gridTitle.slice(0, 160));
check("a GRID chip still carries the headroom caveat",
  /impedance/i.test(gridTitle) && /connection study/i.test(gridTitle), gridTitle.slice(0, 200));

// ------------------------------------------------- the sort survived ------
const options = [...doc.querySelectorAll("#sortProjects option")].map((o) => o.value);
check("grid_asc is still offered in the sort control", options.includes("grid_asc"), options.join(","));
check("grid_desc is still offered", options.includes("grid_desc"));

const kmOf = (row) => { const h = grid.grid[refOf(row)]; return h && typeof h.k === "number" ? h.k : null; };
const WINDOW = 100;
const expected = (direction) => {
  const order = projects.rows.map((_r, i) => i);
  order.sort((l, r) => {
    const a = kmOf(projects.rows[l]); const b = kmOf(projects.rows[r]);
    if (a === null && b === null) return l - r;
    if (a === null) return 1;
    if (b === null) return -1;
    return direction * (a - b) || l - r;
  });
  return order.slice(0, WINDOW).map((i) => refOf(projects.rows[i]));
};
for (const [mode, dir] of [["grid_asc", 1], ["grid_desc", -1]]) {
  $("#sortProjects").value = mode;
  $("#sortProjects").dispatchEvent(new window.Event("change", { bubbles: true }));
  const got = rowsOf().map((tr) => tr.id.replace(/^repd-/, ""));
  const want = expected(dir);
  check(`${mode} still orders the register correctly from the dropdown`,
    got.join(",") === want.join(","),
    `first 5 got ${got.slice(0, 5).join(",")} want ${want.slice(0, 5).join(",")}`);
}

// ------------------------------------------------------- the strip --------
const note = doc.getElementById("gridDistanceNote");
const noteText = note?.textContent ?? "";
check("the strip names both metrics", /GRID/.test(noteText) && /SUB/.test(noteText), noteText.slice(0, 160));
check("the strip says where they now are", /ACTIONS/i.test(noteText), noteText.slice(0, 160));
check("the strip still marks the work BETA", /BETA/.test(noteText));
check("the strip states headroom needs DNO data and a study",
  /impedance/i.test(noteText) && /connection study/i.test(noteText), noteText.slice(0, 260));

console.log(`\ngrid-actions-inline proof: ${passed} passed, ${failures.length} failed`);
if (failures.length) {
  console.error("\nFAILURES");
  for (const f of failures) console.error("  " + f);
  process.exit(1);
}
console.log("GRID and SUB sit beside MAP, carry their caveats, and the sort survived the column.");