GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / releases

PipelineNews Grid Proximity and 1 more file

A JavaScript module that marks tabs, renders radius and sort, calculates great-circle distances and angles and reads inputs for gp centre, gp radius and gp target pick.

700 lines of JavaScript and HTML from pipelinenews, in 2 files. Topic: Electricity markets and data pipelines. Section 1023 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. V8 Candidate render · pipelinenews / releases/202608262141-v8-candidate.html lines 1–164
  2. PipelineNews Grid Proximity geodesy · pipelinenews / releases/202608311557-pipelinenews/assets/202608311557-grid-proximity.mjs lines 1–536

V8 Candidate

A web page in PipelineNews that reads inputs for news, county and sort projects, covering the Renewable Energy Planning Database (REPD) register, solar and battery storage (BESS). Published at https://ventusltd.github.io/pipelinenews/releases/202608262141-v8-candidate.html.

renderpipelinenews / releases/202608262141-v8-candidate.html · lines 1–164 of 164 · version 2026-08-26 21:41 · Entry point

What it does
It draws the REPD register, solar and battery storage (BESS). Uses libraries styles/202608261927-v7-foundation.css, styles/202608262141-v8-foundation.css, vendor/202608261927-chart-umd.min.js. Side effects: changes the web page (DOM).
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: the REPD register, solar, battery storage (BESS).
Inputs & outputs
In: form fields (user input). Out: web page.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/pipelinenews/releases/202608262141-v8-candidate.html.
What it achieves
UK Renewables Pipeline V8 FOUNDATION CANDIDATE. Its code works with 1 MW.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · releases · page
Uses
Mobile (stylesheet), V9 3 (stylesheet), V9 4 (stylesheet), V9 5 1 (stylesheet), V9 6 1 (stylesheet), UK Renewables Pipeline — V9 6 1 Page (link), UK Renewables Pipeline — V9 6 Page (link), UK Renewables Pipeline — V9 5 1 Page (link), and 13 more, styles/202608261927-v7-foundation.css, styles/202608262141-v8-foundation.css, vendor/202608261927-chart-umd.min.js
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/202608262141-v8-candidate.html:1-164 · blob c5f2615f92b3d534656478d1fb0898a237187517 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>GlobalGrid2050 | UK Renewables Pipeline V8 FOUNDATION CANDIDATE</title>
  <link rel="stylesheet" href="styles/202608261927-v7-foundation.css">
  <link rel="stylesheet" href="styles/202608261927-mobile.css">
  <link rel="stylesheet" href="styles/202608261927-v9-3.css">
  <link rel="stylesheet" href="styles/202608261927-v9-4.css">
  <link rel="stylesheet" href="styles/202608261927-v9-5-1.css">
  <link rel="stylesheet" href="styles/202608261927-v9-6-1.css">
  <link rel="stylesheet" href="styles/202608262141-v8-foundation.css">
  <script src="vendor/202608261927-chart-umd.min.js"></script>
</head>
<body>
  <aside class="sidebar">
    <div class="brand">
      <b>GLOBALGRID2050</b>
      <small>UK RENEWABLES PIPELINE · V8 FOUNDATION CANDIDATE</small>
    </div>
    <nav class="nav">
      <a class="active" href="#">V8 FOUNDATION CANDIDATE LIVE VALIDATED</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/v9.6.1/">V9.6.1 FROZEN APP</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/v9.6/">V9.6 DISCONTINUED</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/v9.5.1/">V9.5.1 FROZEN APP</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/v9.5/">V9.5 FROZEN APP</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/v9.4/">V9.4 FROZEN APP</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/v9/">V9.3.1 FROZEN APP</a>
      <a href="https://github.com/Ventusltd/globalgrid2050/tree/eee4cf7d854bf44235c249d337c2aad3916bcdc0/uk_renewables_pipeline/v9" target="_blank" rel="noopener">V9.3 CHECKPOINT</a>
      <a href="https://github.com/Ventusltd/globalgrid2050/tree/77085a5dc8a8ce42cd4de7dad927eaf9aaf785ee/uk_renewables_pipeline/v9" target="_blank" rel="noopener">V9.2 CHECKPOINT</a>
      <a href="https://github.com/Ventusltd/globalgrid2050/tree/59f74e319fbaad62abdb995107dba5759d7f3ca2/uk_renewables_pipeline/v9" target="_blank" rel="noopener">V9.1 CHECKPOINT</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/v8/">V8.1 FALLBACK</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/v7/">V7 FALLBACK</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v6_live.html">V6</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v5_live.html">V5</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v4_live.html">V4</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v3_live_2026-08-22.html">V3</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v2_2026-08-22.html">V2</a>
      <a href="https://globalgrid2050.com/uk_renewables_pipeline/dashboard.html">V1 LEGACY</a>
      <a href="https://globalgrid2050.com/">DIRECTORY</a>
      <a href="https://globalgrid2050.com/repd_grid_atlasv8/">MAP ATLAS</a>
      <a href="#" id="export">EXPORT CSV</a>
    </nav>
  </aside>
  <main class="main">
    <div class="header">
      <h1>UK RENEWABLES PIPELINE V8 FOUNDATION CANDIDATE</h1>
      <div class="status">● 133 HEADLINES · 45 UK · 19 INTERNATIONAL · FULL ≥1 MW</div>
    </div>
    <div class="meta">
      <strong>V8 FOUNDATION CANDIDATE · UK + INTERNATIONAL NEWS · LIVE VALIDATED · 24 August 2026</strong>
      <span>Canonical DESNZ REPD Q2 2026: 7,680 solar, BESS and wind records at ≥1 MW.</span>
      <span id="releaseMeta" class="release-meta">Loading canonical release contract…</span>
      <a href="https://www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract" target="_blank" rel="noopener">Official REPD source</a>
    </div>

    <section class="newspaper">
      <div class="masthead">
        <h2>GLOBALGRID2050 <span>ENERGY DAILY</span></h2>
        <div class="strap">
          <span>UK requires canonical REPD binding · INTERNATIONAL requires explicit non-UK geography plus solar or battery context · international items never drive REPD project signals</span>
          <span id="newsMeta">loading daily edition…</span>
        </div>
      </div>
      <div class="news-tools" id="newsTools">
        <button class="active" data-news="ALL">ALL</button>
        <button data-news="UK">UK</button>
        <button data-news="INTERNATIONAL">INTERNATIONAL</button>
        <button data-news="US">US</button>
        <button data-news="EUROPE">EUROPE</button>
        <button data-news="SOLAR">SOLAR</button>
        <button data-news="BESS">BESS</button>
        <button data-news="CONSENT">CONSENT</button>
        <button data-news="CONSTRUCTION">CONSTRUCTION</button>
        <button data-news="OPERATIONAL">OPERATIONAL</button>
        <button data-news="FINANCE">FINANCE / M&amp;A</button>
        <input id="newsSearch" placeholder="SEARCH HEADLINES / PROJECT / OPERATOR">
      </div>
      <div class="paper">
        <div class="stories" id="stories">
          <div class="news-empty">Loading today’s major-project newspaper…</div>
        </div>
      </div>
    </section>

    <h2 class="section-title">REPD PIPELINE ANALYTICS</h2>
    <div class="gauges">
      <div class="card">
        <h3>FILTERED CAPACITY (MW)</h3>
        <div class="chart"><canvas id="g1"></canvas><div class="value" id="v1">0</div></div>
      </div>
      <div class="card">
        <h3>FILTERED PROJECTS (≥1MW)</h3>
        <div class="chart"><canvas id="g2"></canvas><div class="value" id="v2">0</div></div>
      </div>
      <div class="card">
        <h3>LARGEST SINGLE SITE (MW)</h3>
        <div class="chart"><canvas id="g3"></canvas><div class="value" id="v3">0</div></div>
      </div>
    </div>

    <div class="filters" id="tech">
      <button class="btn active" data-technology="all" aria-pressed="true">ALL TECH</button>
      <button class="btn" data-technology="solar" aria-pressed="false">SOLAR</button>
      <button class="btn" data-technology="bess" aria-pressed="false">BATTERY</button>
      <button class="btn" data-technology="wind_onshore" aria-pressed="false">ONSHORE</button>
      <button class="btn" data-technology="wind_offshore" aria-pressed="false">OFFSHORE</button>
    </div>
    <div class="filters" id="status">
      <button class="btn active" data-official-status="All" aria-pressed="true">ALL STATUS</button>
      <button class="btn" data-official-status="Operational" aria-pressed="false">OPERATIONAL</button>
      <button class="btn" data-official-status="Under Construction" aria-pressed="false">CONSTRUCTING</button>
      <button class="btn" data-official-status="Awaiting Construction" aria-pressed="false">AWAITING</button>
      <button class="btn" data-official-status="Application Submitted" aria-pressed="false">SUBMITTED</button>
    </div>
    <div class="filters">
      <select id="county"><option value="All">🌍 ALL COUNTIES</option></select>
      <select id="sortProjects" aria-label="Sort projects">
        <option value="capacity_desc">SORT: CAPACITY (DEFAULT)</option>
        <option value="updated_desc">SORT: REPD UPDATED — NEWEST</option>
        <option value="updated_asc">SORT: REPD UPDATED — OLDEST</option>
      </select>
      <input id="search" class="asset-search" placeholder="🔍 SEARCH PROJECT / REPD / GLOBALGRID / PLANNING..." autocomplete="off">
      <button class="btn clear-filters" id="clearFilters">CLEAR FILTERS</button>
      <button class="btn export-inline" id="exportInline">EXPORT FILTERED CSV</button>
      <span id="resultsMeta" class="results-meta">Loading all qualifying records…</span>
      <span id="exportMeta" class="export-meta">CSV contains the current filtered rows only</span>
    </div>
    <div class="meta">
      <strong>STATUS DISCIPLINE</strong>
      <span><b>DEFAULT:</b> every qualifying ≥1 MW record is loaded. Filters are user controls; they never redefine or truncate the pipeline.</span>
      <span><b>NEWS:</b> relevance scores are algorithmic screening only and never change an official REPD fact.</span>
      <span><b>ATLAS:</b> valid geometry resolves the exact REPD Ref. Missing geometry remains in search and CSV and is labelled NO MAP.</span>
    </div>
    <div class="tablewrap">
      <table>
        <thead>
          <tr>
            <th>SITE NAME</th>
            <th class="hide-mobile">COUNTY</th>
            <th class="hide-mobile">OPERATOR</th>
            <th>TECHNOLOGY</th>
            <th>OFFICIAL REPD STATUS</th>
            <th>OFFICIAL CAPACITY</th>
            <th class="hide-mobile">REPD REF</th>
            <th class="hide-mobile">GLOBALGRID REF</th>
            <th class="hide-mobile repd-updated-heading" id="repdUpdatedHeader" aria-sort="none">
              <button id="sortUpdated" type="button" aria-label="Sort by REPD updated date, newest first">
                REPD UPDATED <span id="updatedSortIndicator" aria-hidden="true">↕</span>
              </button>
            </th>
            <th>NEWS SIGNAL</th>
            <th>ACTIONS</th>
          </tr>
        </thead>
        <tbody id="tbody"></tbody>
      </table>
    </div>
  </main>
  <script type="module" src="javascript/202608262141-app-v8-foundation.js"></script>
  <script type="module" src="javascript/202608261927-capacity-presentation.js"></script>
</body>
</html>

PipelineNews Grid Proximity

A JavaScript module that marks tabs, renders radius and sort, calculates great-circle distances and angles and reads inputs for gp centre, gp radius and gp target pick.

Set aside from the main view: 91% of its lines are the same as pipelinenews_intelligence/202609020611/assets/202608311610-grid-proximity.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 91% of lines shared with Grid Proximity; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9109 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 pipelinenews_intelligence/202609020611/assets/202608311610-grid-proximity.mjs:1-702 00dafd47a1693591572cf0c05ec350151da8b181
  • sha256 ad49d51d38869085401d23a01152df256b1c31a6413a4b6e19dfe1669cccdbbe
  • target sha256 be8e57089d3075334085d91c77b68ac32b01171b24d8203d40a94d356bfd0cf5
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesypipelinenews / releases/202608311557-pipelinenews/assets/202608311557-grid-proximity.mjs · lines 1–536 of 684 · version 2026-08-31 15:57 · Not reached from any entry point (candidate for review) · pattern mountGridProximity (shared by 3 files)

What it does
It draws substations, the REPD register, 66kV and cables. Defines 27 functions or classes, including atlasHaversineKm, boundingBox, esc, km, mw. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path 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, the REPD register, 66kV, cables, 132kV.
Inputs & outputs
In: form fields (user input). Out: canvas drawing. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 132kV, 66kV.
What it achieves
It marks tabs (`markTabs`), renders radius (`renderRadius`) and renders sort (`renderSort`). Deployment: not-authorised. Its code works with 66 kV and 132 kV. It responds to click and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · releases/202608311557-pipelinenews/assets · JavaScript module
Uses
none found
Used by
none found
Produces
GRID_PROXIMITY_CARTRIDGE_CONTRACT, mountGridProximity
Defines here
atlasHaversineKm, boundingBox, esc, km, mw, mountGridProximity, markTabs, ensurePayload, select, renderRadius, run, renderSort, value, draw, renderConnect, lineFeature, renderMethod, injectScopeStyle, paintScope, toXY
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/202608311557-pipelinenews/assets/202608311557-grid-proximity.mjs:1-536 · blob 1ec3b3b8034470dedcb617010c0930f79a4cce28 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
/**
 * PipelineNews grid-proximity cartridge.
 * Generation 202608311557. DRAFT - deployment: not-authorised.
 *
 * ADDITIVE ONLY. Adds a tabbed panel inside its own host div. It does not
 * modify, re-render, restyle or re-order any existing part of the application.
 * If it fails to load, the core product is unchanged.
 *
 * What it adds, all of it ported from work that already exists in the estate:
 *
 *   RADIUS      Geodesic radius search around any centre, using the same
 *               haversine and the same Earth radius as the GridAtlas radius
 *               tool (ventus-corev8engine.js) and the GIS SLD sandbox
 *               (atlasHaversineKm). A distance read here equals the distance
 *               read there.
 *
 *   SORT        The project table sorted by capacity, town, county, postcode
 *               region, circuit distance or substation distance. Click a
 *               heading; click again to reverse.
 *
 *   CONNECT     For every project, the line to the nearest point on the
 *               nearest circuit and the line to the nearest substation, the
 *               same nearestPointOnLine idea the sandbox uses for cable
 *               routes. Exports as GeoJSON that the Atlas and the sandbox
 *               both already read.
 *
 *   TARGET      A scope that locks onto a site and draws straight to the
 *               nearest substation, with every voltage in reach shown in the
 *               colour the REPD atlas grid model has always used for it.
 *               Range rings are geodesic. It is a picture of the same
 *               arithmetic the other tabs print as numbers.
 *
 *   METHOD      What the numbers are, and what they are not.
 *
 * PUBLIC WORDING: caveats are read from the payload's `caveat` block. Nothing
 * about accuracy is hardcoded here. To change wording, edit build_payload.py
 * and regenerate.
 *
 * It uses classes already in the frozen stylesheet (.card, .btn, .filters,
 * .gauges, .meta, .section-title) so it inherits the design freeze. The scope
 * adds its own styles, every selector scoped under #gridProximityHost, so
 * nothing outside the cartridge's own host is restyled.
 */

export const GRID_PROXIMITY_CARTRIDGE_CONTRACT = Object.freeze({
  schema: "pipelinenews.grid-proximity-cartridge.v1",
  generation: "202608311557",
  deployment: "not-authorised",
  activation: "dynamic-import-on-user-open; payload-fetch-on-first-tab-selection",
  additive_only: true,
  mutates_existing_dom: false,
  project_bindings: 0,
  eligible_for_news_signal: false,
  asserts_no_personal_data: true,
  derived_values_are_inferred: true,
  corroboration_adapters_built: false,
  one_signal_policy: "WITHHOLD",
  tabs: Object.freeze(["RADIUS", "SORT", "CONNECT", "TARGET", "METHOD"]),
});

/* ---- geodesy -------------------------------------------------------------
   Byte-for-byte the same formula and constant as ventus-corev8engine.js
   haversine() and gis-sld-v5-drawing.js atlasHaversineKm(). Do not "improve"
   this to 6371.0088 - that is what made the old circuit_km read 0.112% short
   and disagree with every other Ventus tool.                               */
const R_ATLAS = 6378.137;
const DEG = Math.PI / 180;

function atlasHaversineKm(lon1, lat1, lon2, lat2) {
  const dLat = (lat2 - lat1) * DEG;
  const dLon = (lon2 - lon1) * DEG;
  const x = Math.sin(dLat / 2) ** 2
    + Math.cos(lat1 * DEG) * Math.cos(lat2 * DEG) * Math.sin(dLon / 2) ** 2;
  return R_ATLAS * 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1 - x));
}

/* A cheap bounding box in degrees, so a radius query does not measure every
   project. Latitude is the tighter bound; longitude widens with latitude. */
function boundingBox(lon, lat, km) {
  const dLat = km / (R_ATLAS * DEG);
  const cos = Math.max(Math.cos(lat * DEG), 1e-6);
  return { dLat, dLon: dLat / cos };
}

const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g,
  (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));

const km = (v) => (!Number.isFinite(v) ? "n/a" : v < 1 ? `${Math.round(v * 1000)} m` : `${v.toFixed(2)} km`);
/* Grid probable is deliberately quiet: a plain word and a rank, no traffic
   lights and no banner. The working is one click away for whoever wants it. */
const BAND_RANK = { STRONG: 0, MODERATE: 1, DISTANT: 2, REMOTE: 3, UNKNOWN: 4 };
const mw = (v) => (!Number.isFinite(v) ? "n/a" : v >= 100 ? v.toFixed(0) : v.toFixed(1));

export function mountGridProximity({ host, payloadAsset }) {
  let payloadRequests = 0;
  let data = null;
  let active = "RADIUS";
  let pendingTarget = null;

  const root = document.createElement("div");
  root.className = "card";
  host.appendChild(root);

  const tabs = document.createElement("div");
  tabs.className = "filters";
  tabs.setAttribute("role", "tablist");
  const body = document.createElement("div");
  const note = document.createElement("p");
  note.className = "meta";

  root.append(tabs, note, body);

  GRID_PROXIMITY_CARTRIDGE_CONTRACT.tabs.forEach((code) => {
    const b = document.createElement("button");
    b.className = "btn";
    b.type = "button";
    b.textContent = code;
    b.setAttribute("role", "tab");
    b.addEventListener("click", () => select(code));
    tabs.appendChild(b);
  });

  function markTabs() {
    Array.from(tabs.children).forEach((b) => {
      const on = b.textContent === active;
      b.setAttribute("aria-selected", String(on));
      b.style.fontWeight = on ? "bold" : "";
    });
  }

  async function ensurePayload() {
    if (data) return data;
    note.textContent = "LOAD · requesting the derived proximity index";
    payloadRequests += 1;
    const response = await fetch(payloadAsset.url);
    if (!response.ok) throw new Error(`payload ${response.status}`);
    data = await response.json();
    if (data.schema !== "pipelinenews.v9.grid-proximity.v1") {
      throw new Error("unexpected payload schema");
    }
    note.textContent = `${data.record_count} projects · ${data.network.segments.toLocaleString()} circuit segments · `
      + `${data.network.substations.toLocaleString()} substations · ${data.network.voltages_kv.join("/")} kV`;
    return data;
  }

  async function select(code) {
    active = code;
    markTabs();
    body.textContent = "";
    try {
      const d = await ensurePayload();
      if (code === "RADIUS") renderRadius(d);
      else if (code === "SORT") renderSort(d);
      else if (code === "CONNECT") renderConnect(d);
      else if (code === "TARGET") renderTarget(d, pendingTarget);
      else renderMethod(d);
      pendingTarget = null;
    } catch (error) {
      console.error("grid proximity", error);
      note.textContent = "FAIL · grid proximity unavailable; core product unchanged";
    }
  }

  /* ---- RADIUS ---------------------------------------------------------- */
  function renderRadius(d) {
    const wrap = document.createElement("div");
    wrap.innerHTML = `
      <p class="section-title">PROJECTS WITHIN A RADIUS</p>
      <p class="meta">Centre on any project by name or REPD reference, or type a coordinate as
        <code>lat, lon</code>. Distances are ${esc(d.earth_model.formula)} on
        R = ${d.earth_model.radius_km} km, the same figure the Atlas radius tool uses.</p>
      <div class="filters">
        <input id="gpCentre" type="text" placeholder="Project name, REPD ref, or lat, lon" style="min-width:18rem">
        <input id="gpRadius" type="number" value="10" min="0.1" max="500" step="0.5" style="width:6rem">
        <span class="meta">km</span>
        <button class="btn" id="gpGo" type="button">SEARCH</button>
      </div>
      <div id="gpOut"></div>`;
    body.appendChild(wrap);

    const run = () => {
      const out = wrap.querySelector("#gpOut");
      const raw = wrap.querySelector("#gpCentre").value.trim();
      const radius = Math.max(0.1, Math.min(500, Number(wrap.querySelector("#gpRadius").value) || 10));
      if (!raw) { out.innerHTML = `<p class="meta">Enter a centre to search from.</p>`; return; }

      let centre = null;
      let label = "";
      const coord = raw.match(/^\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*$/);
      if (coord) {
        centre = [Number(coord[2]), Number(coord[1])];
        label = `${centre[1].toFixed(5)}, ${centre[0].toFixed(5)}`;
      } else {
        const needle = raw.toLowerCase();
        const hit = d.rows.find((r) => r.ref === raw)
          || d.rows.find((r) => (r.name || "").toLowerCase().includes(needle));
        if (!hit) { out.innerHTML = `<p class="meta">No project matches that. Try a REPD reference, or <code>lat, lon</code>.</p>`; return; }
        centre = hit.at;
        label = `${hit.name} (REPD ${hit.ref})`;
      }

      const box = boundingBox(centre[0], centre[1], radius);
      const found = [];
      for (const r of d.rows) {
        if (Math.abs(r.at[1] - centre[1]) > box.dLat) continue;
        if (Math.abs(r.at[0] - centre[0]) > box.dLon) continue;
        const dist = atlasHaversineKm(centre[0], centre[1], r.at[0], r.at[1]);
        if (dist <= radius) found.push({ r, dist });
      }
      found.sort((a, b) => a.dist - b.dist);

      const totalMw = found.reduce((s, f) => s + (f.r.mw || 0), 0);
      out.innerHTML = `
        <div class="gauges">
          <div><strong>${found.length}</strong><span>projects within ${radius} km</span></div>
          <div><strong>${mw(totalMw)}</strong><span>MW in the circle</span></div>
          <div><strong>${esc(label)}</strong><span>centre</span></div>
        </div>
        ${table(found.map((f) => ({ ...f.r, _d: f.dist })), [
          ["_d", "DISTANCE", (r) => km(r._d)],
          ["name", "PROJECT", (r) => esc(r.name)],
          ["mw", "MW", (r) => mw(r.mw)],
          ["tech", "TECH", (r) => esc(r.tech)],
          ["town", "TOWN", (r) => esc(r.town)],
          ["circuit", "CIRCUIT", (r) => (r.circuit ? `${km(r.circuit.km)} · ${r.circuit.kv} kV` : "n/a")],
        ])}`;
    };

    wrap.querySelector("#gpGo").addEventListener("click", run);
    wrap.querySelector("#gpCentre").addEventListener("keydown", (e) => { if (e.key === "Enter") run(); });
  }

  /* ---- SORT ------------------------------------------------------------ */
  function renderSort(d) {
    let key = "mw";
    let dir = -1;
    const wrap = document.createElement("div");
    body.appendChild(wrap);

    const columns = [
      ["name", "PROJECT", (r) => esc(r.name)],
      ["mw", "MW", (r) => mw(r.mw)],
      ["tech", "TECH", (r) => esc(r.tech)],
      ["town", "TOWN", (r) => esc(r.town)],
      ["county", "COUNTY", (r) => esc(r.county)],
      ["region", "REGION", (r) => esc(r.region)],
      ["_ckm", "CIRCUIT", (r) => (r.circuit ? km(r.circuit.km) : "n/a")],
      ["_ckv", "kV", (r) => (r.circuit ? r.circuit.kv : "n/a")],
      ["_skm", "SUBSTATION", (r) => (r.substation ? km(r.substation.km) : "n/a")],
      ["_gp", "GRID", (r) => `<button class="gp-lock" type="button" data-why="${esc(r.ref)}"
        title="show the working">${esc(r.grid_probable.band.toLowerCase())}</button>`],
    ];

    const value = (r, k) => (
      k === "_gp" ? BAND_RANK[r.grid_probable.band]
        : k === "_ckm" ? (r.circuit ? r.circuit.km : Infinity)
        : k === "_ckv" ? (r.circuit ? r.circuit.kv : -1)
          : k === "_skm" ? (r.substation ? r.substation.km : Infinity)
            : r[k]);

    function draw() {
      const rows = d.rows.slice().sort((a, b) => {
        const x = value(a, key);
        const y = value(b, key);
        if (typeof x === "string" || typeof y === "string") {
          return String(x || "").localeCompare(String(y || "")) * dir;
        }
        return ((x ?? Infinity) - (y ?? Infinity)) * dir;
      });
      wrap.innerHTML = `
        <p class="section-title">EVERY PROJECT, SORTED</p>
        <p class="meta">Click a heading to sort. Click it again to reverse. Sorting by town or county
          clusters a region together; sorting by circuit distance puts the best-connected first.</p>
        <div id="gpWhy"></div>
        ${table(rows.slice(0, 400), columns, key, dir)}
        <p class="meta">Showing the first 400 of ${d.record_count}. Narrow with the RADIUS tab.</p>`;
      injectScopeStyle();
      wrap.querySelectorAll("button[data-why]").forEach((btn) => {
        btn.addEventListener("click", () => {
          const r = d.rows.find((x) => x.ref === btn.dataset.why);
          const rule = d.grid_probable_rule;
          const box = wrap.querySelector("#gpWhy");
          box.innerHTML = `<div class="gp-readout"><h4>${esc(r.grid_probable.band)} · ${esc(r.name)}</h4>
            <dl><dt>NEAREST CIRCUIT</dt><dd>${km(r.circuit.km)} · ${r.circuit.kv} kV</dd>
            <dt>NEAREST SUBSTATION</dt><dd>${km(r.substation.km)}</dd>
            <dt>CAPACITY</dt><dd>${mw(r.mw)} MW</dd></dl>
            <p class="meta" style="margin:10px 0 0;font-size:11px;color:#4d7a5f">${esc(rule.purpose)}</p>
            <p class="meta" style="margin:6px 0 0;font-size:11px;color:#4d7a5f"><strong>Not modelled:</strong>
              ${rule.not_modelled.map(esc).join("; ")}.</p></div>`;
        });
      });
      wrap.querySelectorAll("th[data-k]").forEach((th) => {
        th.style.cursor = "pointer";
        th.addEventListener("click", () => {
          const k = th.dataset.k;
          if (k === key) dir = -dir; else { key = k; dir = (k === "name" || k === "town" || k === "county" || k === "region" || k === "tech") ? 1 : -1; }
          draw();
        });
      });
    }
    draw();
  }

  /* ---- CONNECT --------------------------------------------------------- */
  function renderConnect(d) {
    const wrap = document.createElement("div");
    const closest = d.rows
      .filter((r) => r.substation && r.circuit)
      .slice()
      .sort((a, b) => a.substation.km - b.substation.km)
      .slice(0, 60);
    wrap.innerHTML = `
      <p class="section-title">AUTO-DRAWN CONNECTIONS</p>
      <p class="meta">For every project the panel holds two indicative lines: the site to the
        nearest point on the nearest circuit, and the site to the nearest mapped substation.
        The circuit point is a true perpendicular onto the line, not the nearest drawn vertex.
        ${esc(d.caveat.substation)}</p>
      <div class="filters">
        <button class="btn" id="gpGeo" type="button">EXPORT ALL AS GEOJSON</button>
        <span class="meta">Opens in the Atlas and the GIS SLD sandbox</span>
      </div>
      ${table(closest, [
        ["name", "PROJECT", (r) => esc(r.name)],
        ["mw", "MW", (r) => mw(r.mw)],
        ["_sub", "NEAREST SUBSTATION", (r) => esc(r.substation.name || "unnamed")],
        ["_skv", "kV", (r) => (r.substation.kv.length ? r.substation.kv.join("/") : "n/a")],
        ["_skm", "TO SUBSTATION", (r) => km(r.substation.km)],
        ["_ckm", "TO CIRCUIT", (r) => `${km(r.circuit.km)} · ${r.circuit.kv} kV`],
        ["_lock", "", (r) => `<button class="gp-lock" type="button" data-ref="${esc(r.ref)}">LOCK</button>`],
      ])}
      <p class="meta">The 60 projects closest to a mapped substation. Every one of the
        ${d.record_count} rows carries the same two lines in the export.</p>`;
    body.appendChild(wrap);

    injectScopeStyle();
    wrap.querySelectorAll("button.gp-lock").forEach((btn) => {
      btn.addEventListener("click", () => {
        pendingTarget = d.rows.find((r) => r.ref === btn.dataset.ref) || null;
        select("TARGET");
      });
    });

    wrap.querySelector("#gpGeo").addEventListener("click", () => {
      const features = [];
      for (const r of d.rows) {
        if (r.circuit) {
          features.push(lineFeature(r.at, r.circuit.foot, {
            type: "indicative_circuit_connection",
            repd_ref: r.ref, project: r.name, mw: r.mw,
            circuit_kv: r.circuit.kv, circuit_name: r.circuit.line || null,
            length_km: r.circuit.km,
            measurement_method: "atlas_haversine_6378_137_km",
            basis: "perpendicular to the nearest mapped circuit segment",
          }));
        }
        if (r.substation) {
          features.push(lineFeature(r.at, r.substation.at, {
            type: "indicative_substation_connection",
            repd_ref: r.ref, project: r.name, mw: r.mw,
            substation: r.substation.name || null,
            substation_kv: r.substation.kv,
            length_km: r.substation.km,
            measurement_method: "atlas_haversine_6378_137_km",
            basis: "straight line to the nearest mapped substation point",
          }));
        }
      }
      const blob = new Blob([JSON.stringify({
        type: "FeatureCollection",
        properties: {
          generation: d.generation,
          note: "Indicative screening geometry. Not a cable route, wayleave or connection offer.",
          caveat: d.caveat,
          provenance: d.provenance,
        },
        features,
      })], { type: "application/geo+json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${d.generation}-indicative-connections.geojson`;
      a.click();
      setTimeout(() => URL.revokeObjectURL(url), 4000);
    });
  }

  function lineFeature(from, to, properties) {
    return {
      type: "Feature",
      geometry: { type: "LineString", coordinates: [from, to] },
      properties,
    };
  }

  /* ---- METHOD ---------------------------------------------------------- */
  function renderMethod(d) {
    const e = d.earth_model;
    const wrap = document.createElement("div");
    wrap.innerHTML = `
      <p class="section-title">HOW THESE DISTANCES ARE MEASURED</p>
      <p class="meta"><strong>Formula.</strong> ${esc(e.formula)} on a sphere of
        R = ${e.radius_km} km. ${esc(e.radius_source)}. The same constant is used by
        ${e.matches.map((m) => `<code>${esc(m)}</code>`).join(" and ")}, so a distance measured
        here equals the same distance measured there.</p>
      <p class="meta"><strong>To a circuit.</strong> ${esc(d.network.measure)}, across
        ${d.network.segments.toLocaleString()} segments of
        ${esc(d.network.voltages_kv.join("/"))} kV line. The site is projected onto the segment on a
        local tangent plane built from the WGS84 radii of curvature at its own latitude
        (${esc(e.segment_projection)}), so the foot of the perpendicular is correct rather than
        snapped to the nearest drawn vertex.</p>
      <p class="meta"><strong>To a substation.</strong> Straight line to the nearest of
        ${d.network.substations.toLocaleString()} mapped substation points.</p>
      <p class="meta"><strong>Straight line.</strong> ${esc(d.caveat.straight_line)}</p>
      <p class="meta"><strong>Substations.</strong> ${esc(d.caveat.substation)}</p>
      <p class="meta"><strong>Coverage.</strong> ${esc(d.caveat.coverage)}</p>
      <p class="meta"><strong>Precision.</strong> ${esc(d.caveat.precision)}</p>
      <p class="meta"><strong>What changed.</strong> The earlier
        <code>circuit_km</code> measured to the nearest point of a decimated sample of
        400/275/132 kV vertices on a ${e.differs_from.project_intelligence_circuit_km} km sphere,
        which reads ${e.differs_from.reads_short_by_pct}% short and could only overstate the
        distance to the conductor. This figure measures to the line itself, includes 220 and
        66 kV, and uses the Atlas radius.</p>
      <p class="meta"><strong>Provenance.</strong> ${esc(d.provenance.spine)}. ${esc(d.provenance.network)}.</p>`;
    body.appendChild(wrap);
  }


  /* ---- TARGET ----------------------------------------------------------
     A targeting scope. The point is that the maths is legible as a picture:
     range rings you can count, a bearing you can see, and every voltage in
     reach drawn in the colour the estate has always used for it.

     Voltage colours are the ones already established in the REPD atlas grid
     model, so a 66 kV line is the same purple here as it is on the map.      */
  const KV_COLOUR = { 400: "#0054ff", 275: "#ff0000", 220: "#ff9900", 132: "#00cc00", 66: "#b200ff" };
  const SCOPE_STYLE_ID = "gp-scope-style";

  function injectScopeStyle() {
    if (document.getElementById(SCOPE_STYLE_ID)) return;
    const s = document.createElement("style");
    s.id = SCOPE_STYLE_ID;
    /* Every selector is scoped under the cartridge host, so nothing outside
       it is restyled and the additive-only boundary holds. */
    s.textContent = `
      #gridProximityHost .gp-scope-wrap { display:grid; grid-template-columns:minmax(280px,1fr) minmax(220px,320px);
        gap:18px; align-items:start; margin-top:10px; }
      @media (max-width:720px){ #gridProximityHost .gp-scope-wrap { grid-template-columns:1fr; } }
      #gridProximityHost .gp-scope { position:relative; background:#04070a; border:1px solid #1d2c22;
        border-radius:2px; overflow:hidden; }
      #gridProximityHost .gp-scope canvas { display:block; width:100%; height:auto; }
      #gridProximityHost .gp-readout { font-family:ui-monospace,Menlo,Consolas,monospace; font-size:12px;
        line-height:1.5; color:#8fe3b0; background:#04070a; border:1px solid #1d2c22; padding:12px 14px; }
      #gridProximityHost .gp-readout h4 { margin:0 0 8px; font-size:11px; letter-spacing:.18em;
        color:#39ff88; font-weight:600; text-transform:uppercase; }
      #gridProximityHost .gp-readout dl { display:grid; grid-template-columns:auto 1fr; gap:3px 12px; margin:0; }
      #gridProximityHost .gp-readout dt { color:#4d7a5f; letter-spacing:.06em; }
      #gridProximityHost .gp-readout dd { margin:0; color:#d6ffe6; font-variant-numeric:tabular-nums; text-align:right; }
      #gridProximityHost .gp-kv { display:flex; flex-wrap:wrap; gap:5px; margin-top:10px; }
      #gridProximityHost .gp-kv span { font-family:ui-monospace,monospace; font-size:10.5px; padding:2px 6px;
        border:1px solid currentColor; border-radius:2px; }
      #gridProximityHost .gp-lock { font-family:ui-monospace,monospace; font-size:10.5px; padding:3px 8px;
        border:1px solid #39ff88; background:transparent; color:#39ff88; cursor:pointer; border-radius:2px; }
      #gridProximityHost .gp-lock:hover { background:#0d2a19; }
      #gridProximityHost .gp-lock:focus-visible { outline:2px solid #39ff88; outline-offset:2px; }
      @media (prefers-reduced-motion:reduce){ #gridProximityHost .gp-scope canvas { opacity:1; } }`;
    document.head.appendChild(s);
  }

  let scopeFrame = null;

  /** Draw one frame of the scope. `t` runs 0 to 1 during acquisition. */
  function paintScope(canvas, row, t) {
    const ctx = canvas.getContext("2d");
    const W = canvas.width; const H = canvas.height;
    const cx = W / 2; const cy = H / 2;
    const pad = 26;
    const R = Math.min(W, H) / 2 - pad;

    // Range the scope covers: the furthest thing worth showing, rounded up.
    const far = Math.max(
      row.substation ? row.substation.km : 0,
      ...(row.substations_nearby || []).map((s) => s.km),
      row.circuit ? row.circuit.km : 0,
    );
    const nice = [0.5, 1, 2, 5, 10, 20, 50, 100, 200];
    const span = nice.find((n) => n >= far * 1.15) || Math.ceil(far * 1.15);
    const toXY = (lon, lat) => {
      const { kx, ky } = { kx: Math.cos(row.at[1] * Math.PI / 180) * 111.32, ky: 110.574 };
      const dx = (lon - row.at[0]) * kx;
      const dy = (lat - row.at[1]) * ky;
      return [cx + (dx / span) * R, cy - (dy / span) * R];
    };

    ctx.clearRect(0, 0, W, H);
    ctx.fillStyle = "#04070a";
    ctx.fillRect(0, 0, W, H);

    // range rings
    ctx.strokeStyle = "#12331f";
    ctx.fillStyle = "#2f6a45";
    ctx.font = "10px ui-monospace,monospace";
    ctx.lineWidth = 1;
    for (let i = 1; i <= 4; i += 1) {
      const rr = (R * i) / 4;
      ctx.beginPath(); ctx.arc(cx, cy, rr, 0, Math.PI * 2); ctx.stroke();
      const label = (span * i) / 4;
      ctx.fillText(`${label < 1 ? `${Math.round(label * 1000)}m` : `${label}km`}`, cx + 3, cy - rr - 3);
    }
    ctx.beginPath();
    ctx.moveTo(cx - R, cy); ctx.lineTo(cx + R, cy);
    ctx.moveTo(cx, cy - R); ctx.lineTo(cx, cy + R);
    ctx.stroke();
    ctx.fillStyle = "#2f6a45";
    ctx.fillText("N", cx - 4, cy - R - 8);

    // sweep, once, during acquisition
    if (t < 1) {
      const a = -Math.PI / 2 + t * Math.PI * 2;
      const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, R);
      g.addColorStop(0, "rgba(57,255,136,0.22)");
      g.addColorStop(1, "rgba(57,255,136,0)");
      ctx.fillStyle = g;
      ctx.beginPath(); ctx.moveTo(cx, cy);
      ctx.arc(cx, cy, R, a - 0.5, a); ctx.closePath(); ctx.fill();
    }

    // one vector per voltage in reach, in the estate's own colours
    const entries = Object.entries(row.circuit_by_kv || {})
      .map(([kv, v]) => ({ kv: Number(kv), ...v }))
      .filter((v) => v.km <= span)
      .sort((a, b) => b.kv - a.kv);
    for (const v of entries) {
      const [x, y] = toXY(v.foot[0], v.foot[1]);
      ctx.strokeStyle = KV_COLOUR[v.kv] || "#666";
      ctx.globalAlpha = 0.35 + 0.65 * Math.min(1, t * 1.6);
      ctx.lineWidth = v.kv >= 275 ? 2 : 1.4;