GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / cosmic / tools/explore/theme

Pilot Renewable Energy Planning Database (REPD) and 1 more file

A JavaScript file in the theme folder of Cosmic that maps the REPD register, solar, wind and postcodes, and uses data from the GridAtlas repository.

482 lines of JavaScript from cosmic, cvaa, in 2 files. Topic: Electricity markets and data pipelines. Section 735 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. Pilot Renewable Energy Planning Database (REPD) energy-data · cosmic / tools/explore/theme/pilot-repd.js lines 1–464
  2. CVAA Generation Correction Test test · cvaa / tools/generation-correction.test.mjs lines 1–18

Pilot Renewable Energy Planning Database (REPD)

A JavaScript file in the theme folder of Cosmic that maps the REPD register, solar, wind and postcodes, and uses data from the GridAtlas repository.

energy-datacosmic / tools/explore/theme/pilot-repd.js · lines 1–464 of 464 · Entry point · pattern brief (shared by 2 files)

What it does
It maps the REPD register, solar, wind and postcodes. Defines 39 functions or classes, including safeSrc, techOf, setState, load, creditFrom. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): 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, wind, postcodes.
Inputs & outputs
In: data source: gridatlas data; browser storage (getItem). Out: browser storage (setItem).
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
It sets state (`setState`), sets filter (`setFilter`) and builds panel (`buildPanel`). Pilot module W06 (TURBINE-46): REPD sites layer, search and jump-to. It responds to change, click and input events.
Why it matters
Loaded by the Pilot page at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
Application
cosmic · tools/explore/theme · script
Uses
GridAtlas — Index Page (estate URL)
Used by
loaded by Pilot (script src)
Produces
safeSrc, techOf, setState, load, creditFrom, okUK, pack, inBox, passes, setFilter, lodMinMW, radius
Defines here
safeSrc, techOf, setState, load, creditFrom, okUK, pack, inBox, passes, setFilter, lodMinMW, radius, draw, labels, pick, fmtMW, cardOf, select, show, flyTo, nextFrom, act, nearest, brief, norm, parseQ, hay, score, has, search
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot-repd.js:1-464 · blob f9a16e309d35407c3e893cc71d2eb811826803a2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
/* Pilot module W06 (TURBINE-46): REPD sites layer, search and jump-to. Contract: /tmp/vk/pilot200/CONTRACT.md v1.
   Data: the GridAtlas browser registry of the Renewable Energy Planning Database (DESNZ), streamed from GridAtlas's published
   URL (PILOT.data.GA + data/repd_browser_registry_<generation>.json) only when the layer is switched on, the REPD search is
   used, or #repd=<ref> is in the address. Nothing is copied into cosmic; nothing loads before first paint.
   Search scoring is ported to plain script from GridAtlas (Ventusltd/gridatlas, Apache-2.0)
   ui/cartridges/202608290716-repd-address-flyto.mjs @ f944f8dcbc09cd09c0895f0126682ec241cd576f
   (normalizeSearchText, parseAtlasQuery, scoreRecord, rankRepdProjects). Every site shown is a REPD record at its published
   coordinates; nothing here invents a location. */
(function () {
  'use strict';
  var W = window, P = W.PILOT;
  if (!P) return;
  var D = W.document;
  P.module('repd', { version: '1', owner: 'W06' });

  // ---- S02 source
  var GEN = '202611132345', SCHEMA = 'gridatlas.browser-registry.v1', EXPECT = 11329;
  var GA = (P.data && P.data.GA) || 'https://ventusltd.github.io/gridatlas/';
  function safeSrc(search, href) {
    var m = /[?&]repdsrc=([^&#]+)/.exec(search || '');
    if (!m) return null;
    try {
      var u = new URL(decodeURIComponent(m[1]), href);
      var here = new URL(href);
      if (u.origin === here.origin || /^(localhost|127\.0\.0\.1)$/.test(u.hostname)) return u.href;
    } catch (e) { /* ignored */ }
    return null;
  }
  var SRC = safeSrc(W.location && W.location.search, W.location && W.location.href) ||
            GA + 'data/repd_browser_registry_' + GEN + '.json';
  var LABEL_OP = 'REPD operator or applicant (as published)';
  var TRUTH = '“Operator or applicant” is the REPD role label, not proof of current ownership. A location or nearby project never establishes involvement.';
  var CREDIT0 = 'REPD sites: Renewable Energy Planning Database (DESNZ), via GridAtlas. Contains public sector information licensed under the Open Government Licence v3.0';

  // ---- S05 palette (registry `technology` and `status` values)
  var TECH = {
    solar: ['Solar (ground)', '#ffc21a', 'solar'], solar_roof: ['Solar (roof)', '#ffe27a', 'solar'],
    bess: ['Battery storage', '#b06cff', 'bess'], wind_onshore: ['Wind onshore', '#33d0ff', 'wind'],
    wind_offshore: ['Wind offshore', '#2f7dff', 'wind'], biomass: ['Biomass / EfW', '#7ac943', 'other'],
    hydro: ['Hydro', '#2ec4b6', 'other'], hydrogen: ['Hydrogen', '#ff7ad9', 'other'], act: ['Advanced conversion', '#c08a4f', 'other'],
    tidal: ['Tidal', '#00b3b3', 'other'], geothermal: ['Geothermal', '#ff6b3d', 'other'], caes: ['Compressed air storage', '#9aa5b1', 'other'],
    other: ['Other', '#d0d0d0', 'other']
  };
  var TKEYS = Object.keys(TECH);
  var STATUS = {
    'operational': ['Operational', 'operational'], 'under construction': ['Under construction', 'building'],
    'awaiting construction': ['Awaiting construction (consented)', 'consented'], 'application submitted': ['Application submitted', 'planning']
  };
  var SKEYS = Object.keys(STATUS);
  var TECH_CHIPS = [['all', 'All'], ['solar', 'Solar'], ['wind', 'Wind'], ['bess', 'BESS'], ['other', 'Other']];
  var STATUS_CHIPS = [['all', 'All'], ['operational', 'Operational'], ['building', 'Building'], ['consented', 'Consented'], ['planning', 'Planning']];
  function techOf(code) { return TECH[TKEYS[code]] || TECH.other; }

  // ---- state
  var state = 'idle', err = '', REG = null, recs = [], N = 0, skipped = 0;
  var LAT, LON, MW, TC, SC, byRef = {}, cells = {}, CELL = 0.25;
  var filt = { tech: 'all', status: 'all' };
  try { var sv = JSON.parse(W.localStorage.getItem('p-repd-filter') || 'null'); if (sv && sv.tech && sv.status) filt = sv; } catch (e) { /* none */ }
  var loadP = null, selRef = null, tour = [], drawn = [];

  // ---- S03 loader (fails closed like GridAtlas: schema + generation + records array)
  function setState(s, msg) { state = s; err = msg || ''; ui.state(); }
  function load() {
    if (loadP) return loadP;
    if (P.offline) { setState('failed', 'REPD sites need the network (offline mode).'); return Promise.reject(new Error('offline')); }
    setState('loading');
    var t0 = Date.now();
    loadP = P.data.fetchJSON(SRC, { cache: true, timeout: 90000 }).then(function (reg) {
      if (!reg || reg.schema !== SCHEMA || !Array.isArray(reg.records) || (!safeSrc(W.location && W.location.search, W.location && W.location.href) && reg.generation !== GEN))
        throw new Error('REPD registry contract mismatch; no site has been drawn');
      pack(reg);
      layer.credit = creditFrom(reg);
      setState('ready');
      P.emit('repd:ready', { count: N, skipped: skipped, ms: Date.now() - t0 });
      if (TEST) console.log('[repd] ready', N, 'sites,', skipped, 'skipped,', Date.now() - t0, 'ms');
      return N;
    }).catch(function (e) {
      loadP = null; REG = null; N = 0;
      setState('failed', 'Could not load the REPD register (' + (e && e.message || e) + ').');
      throw e;
    });
    return loadP;
  }
  function creditFrom(reg) {
    var s = reg.source || {};
    return 'REPD sites: ' + [s.dataset, s.publisher].filter(Boolean).join(' · ') +
      ', via GridAtlas. Contains public sector information licensed under the Open Government Licence v3.0';
  }

  // ---- S04 pack into typed arrays + cell index
  function okUK(la, lo) { return isFinite(la) && isFinite(lo) && la > 49.0 && la < 61.5 && lo > -9.0 && lo < 2.5; }
  function pack(reg) {
    REG = reg; var R = reg.records; recs = []; byRef = {}; cells = {}; skipped = 0;
    var n = R.length; LAT = new Float64Array(n); LON = new Float64Array(n); MW = new Float32Array(n); TC = new Uint8Array(n); SC = new Uint8Array(n);
    for (var k = 0; k < n; k++) {
      var r = R[k], la = +r.latitude, lo = +r.longitude;
      if (r.latitude == null || r.longitude == null || !okUK(la, lo)) { skipped++; continue; }
      var i = recs.length; recs.push(r);
      LAT[i] = la; LON[i] = lo;
      MW[i] = (r.capacity_mw == null || r.capacity_mw === '' || !isFinite(+r.capacity_mw)) ? NaN : +r.capacity_mw;
      var t = TKEYS.indexOf(r.technology); TC[i] = t < 0 ? TKEYS.indexOf('other') : t;
      var s = SKEYS.indexOf(r.status); SC[i] = s < 0 ? 255 : s;
      byRef[String(r.repd_ref)] = i;
      var key = Math.floor(la / CELL) + ':' + Math.floor(lo / CELL);
      (cells[key] || (cells[key] = [])).push(i);
    }
    N = recs.length;
  }
  function inBox(s, w, n, e) {
    var out = [];
    for (var a = Math.floor(s / CELL); a <= Math.floor(n / CELL); a++)
      for (var b = Math.floor(w / CELL); b <= Math.floor(e / CELL); b++) {
        var c = cells[a + ':' + b]; if (!c) continue;
        for (var j = 0; j < c.length; j++) { var i = c[j]; if (LAT[i] >= s && LAT[i] <= n && LON[i] >= w && LON[i] <= e) out.push(i); }
      }
    return out;
  }

  // ---- S14 filters
  function passes(i) {
    if (filt.tech !== 'all' && techOf(TC[i])[2] !== filt.tech) return false;
    if (filt.status !== 'all' && (SC[i] === 255 || STATUS[SKEYS[SC[i]]][1] !== filt.status)) return false;
    return true;
  }
  function setFilter(kind, val) {
    filt[kind] = val;
    try { W.localStorage.setItem('p-repd-filter', JSON.stringify(filt)); } catch (e) { /* none */ }
    ui.chips(); ui.results(); ui.nearest(true);
  }

  // ---- S07 LOD
  function lodMinMW(lod) { return lod >= 3 ? 20 : lod >= 2 ? 5 : 0; }
  var CAP = 1500;

  // ---- S06 draw
  function radius(i) { var m = MW[i]; return Math.max(3.5, Math.min(13, 3 + (m === m ? Math.sqrt(m) * 0.9 : 0))); }
  function draw(g, v) {
    drawn = [];
    if (state !== 'ready' || !v.bbox) return;
    var b = v.bbox, cand = inBox(b.s, b.w, b.n, b.e), minMW = lodMinMW(v.lod || 0), list = [];
    for (var k = 0; k < cand.length; k++) { var i = cand[k]; if (!passes(i)) continue; if (minMW && !(MW[i] >= minMW)) continue; list.push(i); }
    if (list.length > CAP) { list.sort(function (a, c) { return (MW[c] || 0) - (MW[a] || 0); }); list.length = CAP; }
    g.save();
    g.lineWidth = 1.5;
    for (k = 0; k < list.length; k++) {
      i = list[k];
      var p = v.project(LAT[i], LON[i], null); if (!p || p.x < -20 || p.y < -20 || p.x > v.w + 20 || p.y > v.h + 20) continue;
      var r = radius(i), col = techOf(TC[i])[1], st = SC[i] === 255 ? 'planning' : STATUS[SKEYS[SC[i]]][1];
      g.beginPath(); g.arc(p.x, p.y, r, 0, 6.2832);
      if (st === 'operational') { g.fillStyle = col; g.fill(); g.strokeStyle = 'rgba(0,0,0,.75)'; g.setLineDash([]); g.stroke(); }
      else {
        g.fillStyle = 'rgba(0,0,0,.35)'; g.fill();
        g.strokeStyle = col; g.lineWidth = st === 'planning' ? 1.5 : 2.5;
        g.setLineDash(st === 'building' ? [3, 2] : []); g.stroke(); g.lineWidth = 1.5;
      }
      if (recs[i].repd_ref == selRef) { g.setLineDash([]); g.strokeStyle = '#00ffff'; g.lineWidth = 2.5; g.beginPath(); g.arc(p.x, p.y, r + 5, 0, 6.2832); g.stroke(); g.lineWidth = 1.5; }
      drawn.push({ i: i, x: p.x, y: p.y, r: r, d: p.d });
    }
    g.setLineDash([]);
    if ((v.lod || 0) === 0) labels(g, v);
    g.restore();
    layer._drawn = drawn.length;
  }
  function labels(g, v) {
    var near = drawn.filter(function (o) { return o.d < 4000; }).sort(function (a, b) { return a.d - b.d; }).slice(0, 12), boxes = [];
    g.font = '12px system-ui, sans-serif'; g.textBaseline = 'middle';
    near.forEach(function (o) {
      var r = recs[o.i], txt = String(r.name || 'REPD ' + r.repd_ref).slice(0, 40) + (MW[o.i] === MW[o.i] ? ' · ' + fmtMW(MW[o.i]) : '');
      var w = g.measureText(txt).width + 8, bx = [o.x + o.r + 4, o.y - 9, w, 18];
      if (bx[0] + w > v.w) return;
      for (var k = 0; k < boxes.length; k++) { var q = boxes[k]; if (bx[0] < q[0] + q[2] && q[0] < bx[0] + bx[2] && bx[1] < q[1] + q[3] && q[1] < bx[1] + bx[3]) return; }
      boxes.push(bx);
      g.fillStyle = 'rgba(0,0,0,.6)'; g.fillRect(bx[0], bx[1], bx[2], bx[3]);
      g.fillStyle = '#fff'; g.fillText(txt, bx[0] + 4, o.y);
    });
  }

  // ---- S08 pick
  function pick(sx, sy) {
    var best = null, bd = 1e9;
    for (var k = 0; k < drawn.length; k++) {
      var o = drawn[k], d = Math.hypot(o.x - sx, o.y - sy);
      if (d <= Math.max(22, o.r + 6) && d < bd) { bd = d; best = o; }
    }
    if (!best) return null;
    var c = cardOf(best.i);
    select(best.i, false);
    return c;
  }

  // ---- S09 card
  function fmtMW(m) { return m >= 100 ? Math.round(m) + ' MW' : m >= 10 ? m.toFixed(1).replace(/\.0$/, '') + ' MW' : (+m.toFixed(2)) + ' MW'; }
  function cardOf(i) {
    var r = recs[i], E = P.esc, t = techOf(TC[i]), st = SC[i] === 255 ? (r.status || 'status not stated') : STATUS[SKEYS[SC[i]]][0];
    var rows = [
      ['Technology', r.repd_technology || t[0]], ['Status', st],
      ['Capacity', MW[i] === MW[i] ? fmtMW(MW[i]) : 'not stated'],
      ['Place', [r.county, r.region, r.country].filter(Boolean).join(', ')],
      ['Address', [r.repd_address_display, r.repd_postcode || r.repd_postcode_raw].filter(Boolean).join(', ')],
      ['Planning', [r.planning_authority, r.planning_application_reference].filter(Boolean).join(' · ')],
      [LABEL_OP, r.repd_operator_or_applicant], ['REPD ref', r.repd_ref], ['Record updated', r.source_record_updated],
      ['Lat, lon', LAT[i].toFixed(5) + ', ' + LON[i].toFixed(5)]
    ];
    var ref = E(String(r.repd_ref));
    var html = '<dl class="p-repd-dl">' + rows.filter(function (x) { return x[1] != null && x[1] !== ''; }).map(function (x) {
      return '<div><dt>' + E(x[0]) + '</dt><dd>' + E(String(x[1])) + '</dd></div>'; }).join('') + '</dl>' +
      '<div class="p-repd-acts">' +
      '<button type="button" class="p-repd-btn" data-p-repd-act="fly" data-p-repd-ref="' + ref + '">Fly here</button>' +
      '<button type="button" class="p-repd-btn" data-p-repd-act="prev" data-p-repd-ref="' + ref + '" aria-label="Previous REPD site">‹ Prev</button>' +
      '<button type="button" class="p-repd-btn" data-p-repd-act="next" data-p-repd-ref="' + ref + '" aria-label="Next nearest REPD site">Next ›</button>' +
      '<a class="p-repd-btn" target="_blank" rel="noopener" href="' + E(GA + 'atlas/?repd_ref=' + encodeURIComponent(r.repd_ref)) + '">GridAtlas ↗</a></div>' +
      '<p class="p-repd-small">' + E(TRUTH) + '</p><p class="p-repd-small">' + E(layer.credit || CREDIT0) + '</p>';
    return { title: String(r.name || 'REPD site ' + r.repd_ref), html: html, lat: LAT[i], lon: LON[i], id: 'repd:' + r.repd_ref, cap: 'REPD SITE · ' + t[0].toUpperCase() };
  }

  // ---- S10 / S16 / S17 select, fly, tour
  function select(i, fly, instant) {
    var r = recs[i]; selRef = r.repd_ref;
    try { P.hash('repd', String(r.repd_ref)); } catch (e) { /* hash optional */ }
    P.emit('repd:select', { ref: String(r.repd_ref), name: r.name, tech: r.technology, mw: MW[i] === MW[i] ? MW[i] : null, lat: LAT[i], lon: LON[i] });
    if (fly) flyTo(i, instant);
  }
  function show(i, instant) {
    if (!layer.visible) setVisible(true);
    var c = cardOf(i); select(i, true, instant);
    P.card({ title: c.title, html: c.html, lat: c.lat, lon: c.lon, cap: c.cap });
  }
  function flyTo(i, instant) {
    var r = recs[i];
    var pr = P.flyTo(LAT[i], LON[i], { alt: 300, dist: 700, label: String(r.name || 'REPD ' + r.repd_ref).slice(0, 48), source: 'repd', id: String(r.repd_ref), instant: !!instant });
    if (pr && pr.catch) pr.catch(function () { /* cancelled by the pilot */ });
    return pr;
  }
  function nextFrom(i) {
    var seen = {}; tour.forEach(function (k) { seen[k] = 1; }); seen[i] = 1;
    var best = -1, bd = 1e18;
    for (var k = 0; k < N; k++) { if (seen[k] || !passes(k)) continue; var d = P.dist(LAT[i], LON[i], LAT[k], LON[k]); if (d < bd && d > 1) { bd = d; best = k; } }
    return best;
  }
  function act(kind, ref) {
    var i = byRef[ref]; if (i == null) return;
    if (kind === 'fly') { select(i, true); return; }
    if (kind === 'next') { var j = nextFrom(i); if (j < 0) { P.note('No further REPD site within the filters.', 2500); return; } tour.push(i); show(j); return; }
    if (kind === 'prev') { if (!tour.length) { P.note('This is the first site of the tour.', 2000); return; } show(tour.pop()); }
  }

  // ---- S15 nearest
  function nearest(lat, lon, n, radiusM, all) {
    var out = [];
    for (var k = 0; k < N; k++) {
      if (!all && !passes(k)) continue;
      var d = P.dist(lat, lon, LAT[k], LON[k]); if (radiusM && d > radiusM) continue;
      if (out.length < n || d < out[out.length - 1].d) {
        out.push({ i: k, d: d }); out.sort(function (a, b) { return a.d - b.d; }); if (out.length > n) out.pop();
      }
    }
    return out;
  }
  function brief(o) {
    var r = recs[o.i];
    return { ref: String(r.repd_ref), name: r.name, tech: r.technology, status: r.status, mw: MW[o.i] === MW[o.i] ? MW[o.i] : null, lat: LAT[o.i], lon: LON[o.i], d: o.d };
  }

  // ---- S12 search (ported from GridAtlas repd-address-flyto.mjs, plain script)
  var STOP = {}; ['a', 'an', 'and', 'anybody', 'anyone', 'are', 'at', 'being', 'built', 'by', 'can', 'farm', 'for', 'in', 'involved', 'is', 'of', 'on', 'project', 'site', 'someone', 'the', 'there', 'who'].forEach(function (w) { STOP[w] = 1; });
  function norm(value) {
    return String(value || '').normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/&/g, ' and ').replace(/[^a-z0-9/]+/g, ' ').trim();
  }
  function parseQ(raw) {
    var n = norm(raw);
    return {
      normalized: n, compact: n.replace(/\s/g, ''), constructionIntent: /\b(?:build|building|built|construction|constructing)\b/.test(n),
      groups: n.split(/\s+/).filter(Boolean).filter(function (t) { return !STOP[t]; }).map(function (t) { return t.split('/').filter(Boolean); }).filter(function (g) { return g.length; })
    };
  }
  var HAY = null;
  function hay(i) {
    if (!HAY) HAY = new Array(N);
    if (HAY[i] == null) {
      var r = recs[i];
      var h = norm([r.name, r.repd_address_display, r.repd_postcode_raw, r.repd_postcode, r.county, r.region, r.planning_authority, r.planning_application_reference, r.repd_ref, r.technology, r.repd_technology].filter(Boolean).join(' '));
      HAY[i] = [h, h.replace(/\s/g, ''), norm(r.name), norm(r.repd_address_display), norm(r.repd_postcode).replace(/\s/g, ''), norm(r.county), norm(r.planning_authority), norm(r.technology + ' ' + r.repd_technology)];
    }
    return HAY[i];
  }
  function score(i, q) {
    var H = hay(i), h = H[0], ch = H[1];
    var has = function (t) { return ch.indexOf(t.replace(/\s/g, '')) >= 0 || h.indexOf(t) >= 0; };
    if (!q.groups.length || !q.groups.every(function (g) { return g.some(has); })) return null;
    var r = recs[i], s = 0, why = {};
    q.groups.forEach(function (g) {
      var term = g.filter(has)[0] || g[0], compact = term.replace(/\s/g, '');
      if (String(r.repd_ref) === term) { s += 1000; why['REPD ID'] = 1; }
      if (H[4] && H[4] === compact) { s += 800; why.postcode = 1; }
      if (H[2] === term) { s += 700; why['project name'] = 1; }
      else if (H[2].indexOf(term) >= 0) { s += 260; why['project name'] = 1; }
      if (H[3].indexOf(term) >= 0) { s += 180; why['official address'] = 1; }
      if (H[5].indexOf(term) >= 0) { s += 130; why.county = 1; }
      if (H[6].indexOf(term) >= 0) { s += 90; why['planning authority'] = 1; }
      if (H[7].indexOf(term) >= 0) { s += 70; why.technology = 1; }
    });
    // Pilot addition: a whole-query postcode ("MK43 0ZY" is two tokens to the original scorer).
    if (H[4] && q.compact.length >= 5 && H[4] === q.compact && !why.postcode) { s += 800; why.postcode = 1; }
    if (q.constructionIntent && (r.status === 'under construction' || r.status === 'awaiting construction' || r.status === 'application submitted')) {
      s += r.status === 'under construction' ? 160 : r.status === 'awaiting construction' ? 120 : 40; why[r.status] = 1;
    }
    return { i: i, score: s, reasons: Object.keys(why) };
  }
  function search(raw, limit, all) {
    var q = parseQ(raw), out = [];
    if (!q.groups.length) return out;
    for (var i = 0; i < N; i++) { if (!all && !passes(i)) continue; var m = score(i, q); if (m) out.push(m); }
    // order exactly as GridAtlas rankRepdProjects (gridatlas@f944f8dcbc09cd09c0895f0126682ec241cd576f
    // ui/cartridges/202608290716-repd-address-flyto.mjs:59-62, family 70345): score, then name, then repd_ref; limit 20
    out.sort(function (a, b) { return b.score - a.score || String(recs[a.i].name).localeCompare(String(recs[b.i].name)) || Number(recs[a.i].repd_ref) - Number(recs[b.i].repd_ref); });
    return out.slice(0, limit || 20);
  }

  // ---- S11 / S13 panel UI (DOM built with textContent; no record text through innerHTML)
  var ui = { state: function () {}, chips: function () {}, results: function () {}, nearest: function () {} };
  var body = null, els = {}, tab = 'results', qTimer = 0, lastNear = 0;
  function el(tag, cls, text, attrs) {
    var e = D.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text;
    if (attrs) Object.keys(attrs).forEach(function (k) { e.setAttribute(k, attrs[k]); }); return e;
  }
  function chipRow(kind, list, label) {
    var row = el('div', 'p-repd-chips', null, { role: 'group', 'aria-label': label });
    list.forEach(function (c) { var b = el('button', 'p-repd-chip', c[1], { type: 'button', 'data-p-repd-chip': kind + ':' + c[0] }); row.appendChild(b); });
    return row;
  }
  function buildPanel() {
    if (!D || !P.panel) return;
    body = P.panel('repd', '', { title: 'REPD sites', icon: 'RE' });
    if (!body) return;
    var w = el('div', 'p-repd-wrap');
    var tog = el('label', 'p-repd-tog'); els.on = el('input', null, null, { type: 'checkbox' }); tog.appendChild(els.on); tog.appendChild(D.createTextNode(' Show REPD sites on the map'));
    els.state = el('p', 'p-repd-state', null, { role: 'status', 'aria-live': 'polite' });
    els.retry = el('button', 'p-repd-btn', 'Retry', { type: 'button' }); els.retry.hidden = true;
    els.q = el('input', 'p-repd-q', null, { type: 'search', placeholder: 'Name, postcode, county or REPD ref', 'aria-label': 'Search REPD sites', autocomplete: 'off', enterkeyhint: 'go' });
    els.tchips = chipRow('tech', TECH_CHIPS, 'Technology filter'); els.schips = chipRow('status', STATUS_CHIPS, 'Status filter');
    var tabs = el('div', 'p-repd-tabs', null, { role: 'group', 'aria-label': 'List' });
    els.tRes = el('button', 'p-repd-chip', 'Search results', { type: 'button' }); els.tNear = el('button', 'p-repd-chip', 'Nearest to me', { type: 'button' });
    tabs.appendChild(els.tRes); tabs.appendChild(els.tNear);
    els.list = el('ol', 'p-repd-list', null, { 'aria-label': 'REPD sites' });
    var legend = el('p', 'p-repd-small', 'Filled dot: operational. Dashed ring: under construction. Ring: consented. Thin ring: application submitted. Colour: technology; size: capacity.');
    els.credit = el('p', 'p-repd-small');
    [tog, els.state, els.retry, els.q, els.tchips, els.schips, tabs, els.list, legend, el('p', 'p-repd-small', TRUTH), els.credit].forEach(function (x) { w.appendChild(x); });
    body.appendChild(w);

    els.on.addEventListener('change', function () { setVisible(els.on.checked); });
    els.retry.addEventListener('click', function () { load().then(function () { ui.results(); ui.nearest(true); }, function () {}); });
    els.q.addEventListener('input', function () { tab = 'results'; clearTimeout(qTimer); qTimer = setTimeout(runSearch, 200); });
    els.q.addEventListener('keydown', function (e) {
      if (e.key !== 'Enter') return; e.preventDefault();
      runSearch(true);
    });
    w.addEventListener('click', function (e) {
      var c = e.target.closest && e.target.closest('[data-p-repd-chip]'); if (!c) return;
      var kv = c.getAttribute('data-p-repd-chip').split(':'); setFilter(kv[0], kv[1]);
    });
    els.tRes.addEventListener('click', function () { tab = 'results'; ui.results(); });
    els.tNear.addEventListener('click', function () { tab = 'nearest'; ensure().then(function () { ui.nearest(true); }, function () {}); ui.tabs(); });

    ui.state = function () {
      var t = state === 'idle' ? 'Not loaded yet. The register (about 1.7 MB) loads when you switch the layer on or search.'
        : state === 'loading' ? 'Loading the REPD register from GridAtlas…'
        : state === 'ready' ? N.toLocaleString() + ' REPD sites ready' + (skipped ? ' (' + skipped + ' without usable coordinates left out)' : '') + '.'
        : err;
      els.state.textContent = t; els.retry.hidden = state !== 'failed' || !!P.offline;
      els.credit.textContent = layer.credit || CREDIT0;
    };
    ui.chips = function () {
      [].forEach.call(w.querySelectorAll('[data-p-repd-chip]'), function (b) {
        var kv = b.getAttribute('data-p-repd-chip').split(':'); b.setAttribute('aria-pressed', String(filt[kv[0]] === kv[1]));
      });
    };
    ui.tabs = function () { els.tRes.setAttribute('aria-pressed', String(tab === 'results')); els.tNear.setAttribute('aria-pressed', String(tab === 'nearest')); };
    ui.results = function () {
      if (tab !== 'results') return; ui.tabs();
      var q = els.q.value.trim(); els.list.textContent = '';
      if (!q) { els.list.appendChild(el('li', 'p-repd-small', 'Type a project name, postcode, county, planning reference or REPD ref.')); return; }
      if (state !== 'ready') return;
      var res = search(q, 20);
      if (!res.length) { els.list.appendChild(el('li', 'p-repd-small', 'No REPD site matches “' + q + '” within the filters.')); return; }
      res.forEach(function (m) { els.list.appendChild(row(m.i, m.reasons.join(', '))); });
    };
    ui.nearest = function (force) {
      if (tab !== 'nearest' || state !== 'ready') return; ui.tabs();
      var now = Date.now(); if (!force && now - lastNear < 500) return; lastNear = now;
      var c = P.camLL ? P.camLL() : null; if (!c) return;
      els.list.textContent = '';
      nearest(c.lat, c.lon, 10).forEach(function (o) {
        els.list.appendChild(row(o.i, fmtD(o.d) + ' ' + compass(P.bearing(c.lat, c.lon, LAT[o.i], LON[o.i]))));
      });
    };
    ui.state(); ui.chips(); ui.tabs(); ui.results();
  }
  function row(i, extra) {
    var r = recs[i], li = el('li');
    var b = el('button', 'p-repd-row', null, { type: 'button' });
    var dot = el('span', 'p-repd-dot', null, { 'aria-hidden': 'true' }); dot.style.background = techOf(TC[i])[1];
    b.appendChild(dot);
    b.appendChild(el('span', 'p-repd-name', r.name || 'REPD ' + r.repd_ref));
    b.appendChild(el('span', 'p-repd-meta', [techOf(TC[i])[0], MW[i] === MW[i] ? fmtMW(MW[i]) : 'MW not stated', r.status, r.county, extra].filter(Boolean).join(' · ')));
    b.addEventListener('click', function () { tour = []; show(i); });
    li.appendChild(b); return li;
  }
  function fmtD(m) { return m < 1000 ? Math.round(m) + ' m' : (m / 1000).toFixed(m < 10000 ? 1 : 0) + ' km'; }
  function compass(deg) { return ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.round(((deg % 360) + 360) % 360 / 45) % 8]; }
  function ensure() { return state === 'ready' ? Promise.resolve(N) : load(); }
  function runSearch(go) {
    ensure().then(function () {
      ui.results();
      if (go) { var res = search(els.q.value.trim(), 1); if (res.length) { tour = []; show(res[0].i); } }
    }, function () {});
  }
  function setVisible(on) {
    layer.visible = !!on;
    if (P.setLayerVisible) P.setLayerVisible('repd', !!on);
    if (els.on) els.on.checked = !!on;
    if (on) ensure().catch(function () {});
  }

  // ---- S01 layer
  var layer = { id: 'repd', title: 'REPD sites', order: 50, visible: false, credit: CREDIT0, draw: draw, pick: pick };
  layer = P.addLayer(layer) || layer;
  layer._api = { src: function () { return SRC; }, safeSrc: safeSrc, load: load, pack: pack, inBox: inBox, search: search, nearest: nearest, brief: brief,
    cardOf: cardOf, byRef: function (r) { return byRef[String(r)]; }, rec: function (i) { return recs[i]; }, count: function () { return N; }, skipped: function () { return skipped; },
    state: function () { return state; }, setFilter: setFilter, passes: passes, lodMinMW: lodMinMW, TECH: TECH, STATUS: STATUS, show: show, nextFrom: nextFrom };

  // ---- S10 card actions (delegated: the card html is inserted by core)
  if (D && D.addEventListener) D.addEventListener('click', function (e) {
    var b = e.target && e.target.closest && e.target.closest('[data-p-repd-act]'); if (!b) return;
    e.preventDefault(); act(b.getAttribute('data-p-repd-act'), b.getAttribute('data-p-repd-ref'));
  });

  // ---- S18 events for other modules (never forces the register to load)
  P.on('repd:query', function (q) {
    if (!q || typeof q.reply !== 'function') return;
    // query contract v2: radius in metres as q.radiusM (q.maxM accepted); never a bare 'radius' of unknown unit
    if (state === 'failed') { q.reply([], { loaded: false, state: 'error', error: err || 'REPD register failed to load' }); return; }
    if (state !== 'ready') { q.reply([], { loaded: false, state: 'notloaded' }); return; }
    var rM = +q.radiusM || +q.maxM || 0, n = Math.min(+q.n || 10, 100);
    var got = nearest(+q.lat, +q.lon, n, rM, !!q.all);
    q.reply(got.map(brief), { loaded: true, state: 'ok', count: N, capped: got.length >= n, radiusM: rM, credit: layer.credit });
  });
  P.on('repd:show', function (q) {
    var ref = q && String(q.ref); if (!ref) return;
    ensure().then(function () { var i = byRef[ref]; if (i == null) P.note('REPD ref ' + ref + ' is not in the register.', 3500); else show(i, !!q.instant); }, function () {});
  });
  P.onFrame(function () { if (tab === 'nearest' && body && state === 'ready') ui.nearest(false); });

  // ---- S17 deep link #repd=<ref>
  var TEST = /[?&]repdtest=1/.test((W.location && W.location.search) || '');
  P.ready(function () {
    buildPanel();
    var ref = null; try { ref = P.hash('repd'); } catch (e) { /* none */ }
    if (ref) ensure().then(function () {
      var i = byRef[String(ref)];
      if (i == null) P.note('REPD ref ' + ref + ' is not in the register.', 4000); else show(i, true);
    }, function () {});
    if (TEST) console.log('[repd] module ready; src', SRC);
  });
})();

CVAA Generation Correction Test

A test in the tools folder.

testcvaa / tools/generation-correction.test.mjs · lines 1–18 of 18 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Defines run. Uses libraries node:assert/strict, node:fs. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'generation'): 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.
What it achieves
Defines `run`.
Why it matters
No other file in the estate was found to import it.
Application
cvaa · tools · test
Uses
node:assert/strict, node:fs
Used by
none found
Produces
run
Defines here
run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cvaa@dc04524c4df79e90642b8b7c00729e67cdf52855 tools/generation-correction.test.mjs:1-18 · blob 1468ea21ca551e4c98b88ddefadfc1753407f793 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';

const source = readFileSync(new URL('../vaccines/202608301701-monotonic-utc-generations.md', import.meta.url), 'utf8');
const code = source.split('```js\n')[1].split('\n```')[0];
const { default: check } = await import('data:text/javascript,' + encodeURIComponent(code));
const first = {sha: '1'.repeat(40), date: '2026-08-30T16:20:22Z', generation: '202608301940'};
const next = {sha: '2'.repeat(40), date: '2026-08-30T16:31:22Z', generation: '202608301631'};
const correction = {sha: first.sha, recorded: first.generation, corrected: '202608301620', reason: 'Compare exact UTC author timestamp'};
const run = (entries, commits = [next, first]) => check({commits, config: {historical_generation_corrections: entries}});
assert.equal(run([]).length, 2);
assert.deepEqual(run([correction]), []);
assert.ok(run([{...correction, corrected: '202608301619'}]).length);
assert.ok(run([{...correction, recorded: '202608301945'}]).length);
assert.ok(run([{...correction, sha: '3'.repeat(40)}]).length);
assert.ok(run([correction, correction]).length);
assert.ok(run([correction], [{...next, generation: '202608301615'}, first]).length);
console.log('Historical corrections require exact revision, original stamp and Git UTC minute. New regressions still fail.');