GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / globalgrid2050 / testcode/202609060300/atlas/cartridges

Single-Line Diagram (SLD) Sandbox (part 8)

A JavaScript file in the cartridges folder of GlobalGrid2050 that maps grid substations, connection points, GB transmission network and price decade rollup, using haversine.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Grid network and substations. Section 357 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. Single-Line Diagram (SLD) Sandbox geodesy · globalgrid2050 / testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js lines 4901–5600

Single-Line Diagram (SLD) Sandbox

A JavaScript file in the cartridges folder of GlobalGrid2050 that maps grid substations, connection points, GB transmission network and price decade rollup, using haversine.

geodesyglobalgrid2050 / testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js · lines 4901–5600 of 7736 · version 2026-09-06 03:00 (continued from section 350) · Not reached from any entry point (candidate for review) · pattern widerFleetBuckets (shared by 6 files)

What it does
It maps grid substations, connection points, GB transmission network and price decade rollup. Defines 233 functions or classes, including distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV.
Inputs & outputs
In: GeoJSON file grid_substations.geojson; JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json; JSON file price-decade-rollup.json; browser storage (getItem); DuckDB queries; form fields (user input). Out: browser storage (setItem); interactive map. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 750kV, 415kV, 400kV, 275kV, 220kV, 132kV, 110kV, 66kV.
What it achieves
It creates compute observer (`createComputeObserver`), builds stats (`buildStats`) and applies development stage defaults (`applyDevelopmentStageDefaults`). Its `distanceKm` function gives distance km from two coordinate pairs (VEDIC: measure). Its code works with 400 kV, 132 kV and 33 kV. It responds to click, keydown and touchstart events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609060300/atlas/cartridges · script
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
Uses
none found
Used by
mentioned in Standalone (comment link)
Produces
distanceKm, representativePoint, voltagesKv, destinationPoint, initialBearingDeg, copy, finite, located, sameLocation, sameEntity, createComputeObserver, publish
Defines here
ensurePinLayers, setPin, clearPin, togglePin, styleTextFont, glyphsReachable, addLabelLayerWhenDrawable, gbNumber, gbRow, gbProductError, renderGbConditions, ledgerStamp, installVersionLedger, scopeModule, ensureScopeLayers, clearScope, scopeHtml, runGridScope
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060300/atlas/cartridges/202609060300-sld-sandbox.js:4901-5600 · blob b9451a6d240116dae04211c0cc8216a75da78ad1 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: experimental · users: none · canonical: unreached_review
      if (!box.checked) box.click();
      link.project_layer_enabled = layerId;
      // The field a reader (and every prior proof) actually trusted must
      // say what happened, not what the request's bucket merely belonged
      // to. Set here, on the ONE path that turns a control on, rather than
      // synthesised from set membership before this ever ran.
      link.technology_layer = Object.assign({}, link.technology_layer, {
        requested: tech, layer_id: layerId, enabled: true, reason: null
      });
      recoverFailures(new RegExp('^layer control not found: '
        + String(layerId).replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '$'));
      return true;
    } catch (error) {
      link.failures.push('layer: ' + String(error?.message || error));
      return false;
    }
  }

  /* ── the project pin ─────────────────────────────────────────────────
     A marker for the selected project, drawn by this cartridge rather than
     borrowed from a layer.

     The engine's technology layers are hydrated on demand and can be switched
     off by the user, so a project arriving by deep link may have no pixel at
     all. This one does not depend on any of that: it is the thing the card is
     about, and while a card is open its subject should be visible on the map.
     It toggles, because a pin over the site is exactly what you want out of the
     way when you are looking at the site. */

  const SRC_PIN = 'gridatlas-project-pin';
  const L_PIN_HALO = 'l-project-pin-halo';
  const L_PIN = 'l-project-pin';
  let pinVisible = true;

  function ensurePinLayers(map) {
    // addSource throws if the style is not loaded, and a source that failed to
    // add reads back as null. The pin is a convenience: it may not be the
    // reason a card fails to open.
    if (!map || typeof map.addSource !== 'function') return false;
    if (map.getSource(SRC_PIN)) return true;
    try {
    map.addSource(SRC_PIN, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
    /* A ring around the site, not a dot on it.
       ------------------------------------------------------------------
       A filled dot in the technology colour was invisible: it sat under the
       engine's own pixel for the same project, and the neon links converging
       on it are drawn in that same colour, so it disappeared into its own
       arrival point. Seen in Chrome at zoom 12 on Botley West -- position
       exactly right, nothing to look at.

       A ring solves all three. It does not duplicate the engine's pixel,
       because it surrounds it. It reads against the links, because it crosses
       them rather than joining them. And it answers the question the marker
       exists for -- which of these is the one the card is about -- which a
       second dot among dots cannot. */
    map.addLayer({
      id: L_PIN_HALO, type: 'circle', source: SRC_PIN,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 11, 14, 26],
        'circle-color': 'rgba(0,0,0,0)',
        'circle-stroke-color': ['get', 'colour'],
        'circle-stroke-width': 6,
        'circle-stroke-opacity': 0.13,
        'circle-blur': 0.4,
      },
    });
    map.addLayer({
      id: L_PIN, type: 'circle', source: SRC_PIN,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 11, 14, 26],
        // Hollow: whatever the engine draws for this project stays readable
        // inside it.
        'circle-color': 'rgba(0,0,0,0)',
        // Pale, not white. It has to separate from the technology colour it
        // encircles without becoming the loudest thing on a dark map.
        'circle-stroke-color': '#cfe9ed',
        'circle-stroke-width': 1.6,
        'circle-stroke-opacity': 0.85,
      },
    });
    } catch (error) {
      link.failures.push('pin: ' + String(error?.message || error));
      return false;
    }
    return Boolean(map.getSource(SRC_PIN));
  }

  function setPin(map, origin, name, tech) {
    if (!ensurePinLayers(map)) return;
    const source = map.getSource(SRC_PIN);
    if (!source || typeof source.setData !== 'function') return;
    const colour = TECH_COLOUR[tech] || SUBSTATION_COLOUR;
    source.setData({
      type: 'FeatureCollection',
      features: origin && pinVisible ? [{
        type: 'Feature',
        properties: { colour, name: name || '' },
        geometry: { type: 'Point', coordinates: origin },
      }] : [],
    });
    link.project_pin = { shown: Boolean(origin && pinVisible), name: name || null };
  }

  function clearPin(map) {
    const source = map && map.getSource && map.getSource(SRC_PIN);
    if (source && typeof source.setData === 'function') {
      source.setData({ type: 'FeatureCollection', features: [] });
    }
    link.project_pin = { shown: false, name: null };
  }

  function togglePin() {
    pinVisible = !pinVisible;
    if (capturedMap && lastSelection) {
      setPin(capturedMap, lastSelection.origin, lastSelection.name, lastSelection.tech);
    }
    return pinVisible;
  }
  link.togglePin = togglePin;

  /* ── labels need glyphs, and glyphs can be absent ─────────────────────
     A symbol layer cannot draw text without a glyph atlas, and maplibre does
     not degrade when it cannot build one: it throws reading `width` off a null
     atlas, and it does it again on the NEXT frame, and the next. Both of us
     watching this estate tonight found the same storm from different ends --
     Codex counted 50+ in about 20 seconds on mounting the layout, and a cold
     load here produced 4,218. Same exception, and the two symbol layers in
     this cartridge are the only text it draws.

     Two ways to have no atlas: the style carries no `glyphs` endpoint at all,
     or it has one and the named font is not served by it. The font name here
     was assumed -- 'Open Sans Bold' -- rather than taken from the style that
     has to serve it, so a basemap with a different font family produced text
     that could never resolve.

     So: ask the style. No glyphs endpoint means no labels, which is a quiet
     map rather than a broken one. Otherwise use a font the style already uses
     for its own labels, because that one is definitely served.

     This matters most on a phone. An exception per frame is a main thread that
     never idles, and on a phone that is heat, battery and a page that stops
     answering touches. */
  function styleTextFont(map) {
    try {
      const style = map.getStyle?.();
      if (!style || !style.glyphs) return null;
      for (const layer of style.layers || []) {
        const font = layer?.layout?.['text-font'];
        if (Array.isArray(font) && font.length && typeof font[0] === 'string') {
          return font;
        }
      }
      // A glyph endpoint with no symbol layer to learn from. This is the
      // Mapbox/MapLibre default family and the one CARTO serves.
      return ['Open Sans Bold', 'Arial Unicode MS Bold'];
    } catch (error) {
      link.failures.push('glyphs: ' + String(error?.message || error));
      return null;
    }
  }

  /* Having a glyphs endpoint is not the same as being able to reach it.
     ----------------------------------------------------------------------
     Naming a font the style serves fixed one half. The other half was watched
     live and is worse: the style declared

       https://tiles.basemaps.cartocdn.com/fonts/{fontstack}/{range}.pbf

     on the same CDN that had just returned 200 for style.json and then served
     no vector tiles at all. A declared endpoint that cannot be reached gives
     exactly the same null atlas as no endpoint, and 5,362 exceptions in thirty
     seconds. Checking that the property exists proves nothing; the only honest
     test is to ask for a range and see.

     So fetch one - the first 256 codepoints, a few kilobytes, the same request
     the renderer would make. If it does not come back, there are no labels.
     That is a map without text, which is a great deal better than a map that
     throws on every frame it ever draws.

     Deferring the labels costs nothing: they are decoration over links that
     are already on screen, and the distances they annotate are on the card. */
  async function glyphsReachable(map, font) {
    let template;
    try { template = map.getStyle?.()?.glyphs; } catch (error) { template = null; }
    if (!template || !font) return false;
    const url = String(template)
      .replace('{fontstack}', encodeURIComponent(font.join(',')))
      .replace('{range}', '0-255');
    try {
      const response = await fetch(url, { cache: 'force-cache' });
      if (!response.ok) {
        link.failures.push('glyph range ' + response.status + '; labels omitted');
        return false;
      }
      return true;
    } catch (error) {
      link.failures.push('glyph range unreachable; labels omitted');
      return false;
    }
  }

  // Add a symbol layer only once its text can actually be drawn. Callers do
  // not await this: the labels arrive when they arrive, or never, and nothing
  // else waits on them.
  function addLabelLayerWhenDrawable(map, font, spec, what) {
    glyphsReachable(map, font).then((ok) => {
      link.labels_drawn = ok;
      if (!ok) return;
      try {
        if (!map.getLayer(spec.id)) map.addLayer(spec);
      } catch (error) {
        link.failures.push(what + ' labels: ' + String(error?.message || error));
      }
    });
  }

  /* ── GB grid conditions, from the tracker that already measures them ───
     The estate already has an application that tracks GB electricity:
     globalgrid2050.com/uk_energy_tracking_v6, backed by Ventusltd/
     data-gb-electricity. The Atlas had no idea it existed, so a map of where
     the country is building generation could not tell you what the system was
     doing.

     This does not port that application. It is 49 MB, and the Atlas already
     boots a 35.7 MB query engine before it can answer anything -- adding a
     second one would be a way of making both worse. It reads the small
     published feeds the tracker writes, one to four kilobytes each, and links
     to the full application for everything else. The tracker stays the place
     the analysis lives.

     HONESTY ABOUT AGE. Measured when this was written, those feeds were
     stamped 2026-06-18: about ten weeks old. A panel that prints a price with
     no date implies it is current, and a stale number presented as live is
     worse than no number. So the age is always shown, and past a day it is
     labelled as not current rather than merely dated. If the feeds start
     updating again the same panel gets better on its own.

     Mobile first: it opens collapsed, sized against the viewport, and is a
     single column on a narrow screen. */

  /* What a megawatt hour has been worth in the available historic record.
     ----------------------------------------------------------------------
     A map of where the country is building generation should be able to say
     what the system has been doing while it was built.

     IT READS THE DATA REPOSITORY, NOT A COPY. The governing rule in the
     estate's migration scope is "data before charts": a consumer must read a
     data product that already sits clean, and must never own source data or
     become a second source of truth. So this reads
     Ventusltd/data-gb-electricity, which owns the Parquet and publishes a
     browser-sized rollup derived from it. An earlier version of this panel read a
     copy derived inside globalgrid2050; that copy was a second definition of
     the same numbers and has been retired in favour of this one.

     A ROLLUP, NOT A HUNDRED MEGABYTES. Settlement-period history is the right
     size for a chart someone chose to open and the wrong size for a panel
     inside a map on a phone, which is where most readers arrive.

     THE MEASUREMENT STOPS WHERE THE PRODUCT STOPS. A negative system price is
     an observed market value. It does not by itself establish a local network
     constraint, curtailment, connection capacity, a usable charging window or
     the economics of any project on this map.

     SOLAR IS ABSENT, AND SAYS SO. PVLive has not been decided into the data
     repository, so the product declares solar absent rather than carrying a
     series from somewhere else. A panel that quietly filled that gap from a
     second source would be the exact thing the discipline forbids. */

  const GB_PIN_ID = 'price-decade-rollup';
  const GB_ROLLUP = PINS ? PINS.url(GB_PIN_ID) : null;
  const GB_APP = 'https://globalgrid2050.com/uk_energy_tracking_v6/';
  const GB_ID = 'gridatlas-gb-conditions';
  const GB_SCHEMA = 'data-gb-electricity.price-decade-rollup.v2';
  /* Loader state on the window, as the topology loader's is, so the source
     registry can say whether this product answered, was withheld (reached,
     not the schema this consumer answers) or failed - generation 202609012217. */
  const gbLoader = { state: 'idle', product: GB_ROLLUP, schema_required: GB_SCHEMA,
    schema: null, reason: null, error: null, renders: 0 };
  window.__GRIDATLAS_GB_CONDITIONS__ = gbLoader;

  const gbNumber = (value, digits) =>
    Number.isFinite(Number(value)) ? Number(value).toFixed(digits) : '--';

  function gbRow(label, value, unit) {
    return `<div class="gb-row"><span class="gb-k">${label}</span>`
      + `<span class="gb-v">${value}<em>${unit || ''}</em></span></div>`;
  }

  function gbProductError(product) {
    if (!product || product.schema !== GB_SCHEMA) return 'owner product v2 is not available';
    const price = product.price || {};
    const derived = product.derived_from || {};
    const years = Array.isArray(price.by_year) ? price.by_year : [];
    if (!years.length) return 'year rows are absent';
    const included = years.reduce((sum, row) => sum + Number(row.days_included), 0);
    const negative = years.reduce((sum, row) =>
      sum + Number(row.days_with_a_negative_settlement_period), 0);
    if (included !== Number(derived.included_days)) return 'included-date total disagrees';
    if (negative !== Number(price.days_with_a_negative_settlement_period)) {
      return 'negative-date total disagrees';
    }
    const validYears = years.every(row => {
      const days = Number(row.days_included);
      const calendarDays = Number(row.calendar_days);
      const status = days === calendarDays ? 'FULL_DATE_COVERAGE' : 'PARTIAL_DATE_COVERAGE';
      const coverage = 100 * days / calendarDays;
      const share = 100 * Number(row.days_with_a_negative_settlement_period) / days;
      return days === Number(row.days)
        && calendarDays >= days
        && row.calendar_date_coverage === status
        && Math.abs(Number(row.calendar_date_coverage_pct) - coverage) < 0.011
        && Math.abs(Number(row.negative_period_day_share_pct) - share) < 0.011;
    });
    if (!validYears) return 'year coverage or share disagrees';
    if (Math.abs(Number(price.negative_period_day_share_pct)
      - (100 * negative / included)) >= 0.011) return 'record share disagrees';
    for (const extreme of [price.lowest_settlement_period, price.highest_settlement_period]) {
      if (!Number.isInteger(extreme?.settlement_period)
        || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/u.test(extreme?.period_start_utc)) {
        return 'extreme-period identity is incomplete';
      }
    }
    return '';
  }

  async function renderGbConditions(body) {
    let product = null;
    gbLoader.state = 'loading';
    try {
      /* no-cache, not force-cache. Watched live on v9.41's first minutes:
         the owner had published v2, a fresh fetch returned v2, and the panel
         showed its withheld state - because force-cache handed back the v1
         this browser had fetched hours earlier and never revalidated. A
         consumer that gates on a product's version must not pin itself to
         whichever version it saw first. no-cache revalidates every open,
         which costs a 304 when nothing changed and correctness when it did. */
      const response = await fetch(GB_ROLLUP, { cache: 'no-cache' });
      if (response.ok) {
        const text = await response.text();
        gbLoader.pin = await PINS.verify(GB_PIN_ID, text);
        if (gbLoader.pin.state === 'MISMATCH') gbLoader.error = gbLoader.pin.detail;
        else product = JSON.parse(text);
      }
    } catch (error) {
      product = null;
      gbLoader.error = String(error && error.message || error);
    }
    if (!product) {
      gbLoader.state = 'failed';
      body.innerHTML = '<p class="gb-note">The price rollup could not be '
        + 'reached. This says nothing about the grid, only about the network '
        + 'between here and the data repository.</p>';
      link.gb_conditions = { reached: false };
      return;
    }

    const productError = gbProductError(product);
    if (productError) {
      gbLoader.state = 'withheld';
      gbLoader.reason = productError;
      gbLoader.schema = product.schema || null;
      body.innerHTML = '<p class="gb-note">The owner price product did not pass '
        + `the v2 evidence gate (${productError}), so no values are shown.</p>`;
      link.gb_conditions = { reached: true, schema_supported: false,
        source: 'data-gb-electricity', reason: productError, project_bindings: 0 };
      return;
    }

    const price = product.price || {};
    const years = Array.isArray(price.by_year) ? price.by_year : [];
    const latest = years.length ? years[years.length - 1] : null;
    const low = price.lowest_settlement_period || null;
    const includedDays = Number((product.derived_from || {}).included_days);
    const negativeDays = Number(price.days_with_a_negative_settlement_period);
    const partialYears = years.filter(row =>
      row.calendar_date_coverage === 'PARTIAL_DATE_COVERAGE');

    const rows = [];
    rows.push(gbRow('Available-record daily mean',
      gbNumber(price.available_record_daily_mean, 2), ' &pound;/MWh'));
    rows.push(gbRow('Dates with a negative period',
      gbNumber(price.negative_period_day_share_pct, 2) + '%',
      ` ${negativeDays} of ${includedDays}`));
    if (latest) {
      const partial = latest.calendar_date_coverage === 'PARTIAL_DATE_COVERAGE';
      rows.push(gbRow(latest.year + (partial ? ' partial' : ''),
        gbNumber(latest.mean_gbp_per_mwh, 2), ' &pound;/MWh'));
    }

    const lowLine = low && Number.isFinite(Number(low.value))
      ? '<p class="gb-note gb-point">Lowest observed settlement price: '
        + `<b>${gbNumber(low.value, 2)} &pound;/MWh</b>, SP ${low.settlement_period}, `
        + `${low.period_start_utc}. This is a historic GB system-price `
        + 'observation, not evidence about a project on this map.</p>'
      : '';

    // Absent by decision, so it is stated rather than left as a silent gap.
    const solarLine = product.solar && product.solar.present === false
      ? '<p class="gb-note">Solar is not in this product yet: the data '
        + 'repository has not taken PVLive, and filling the gap from somewhere '
        + 'else would make a second source of truth.</p>'
      : '';

    const span = Array.isArray(price.span) ? price.span.join('–') : '';
    body.innerHTML = rows.join('')
      + lowLine
      + solarLine
      + `<p class="gb-note">GB system sell price ${span}, included daily means `
      + `from dates with at least ${product.grain.minimum_periods_per_day} available `
      + 'settlement periods. Included does not mean all 48 are present. '
      + `${partialYears.length} year${partialYears.length === 1 ? '' : 's'} have `
      + 'partial calendar-date coverage. Elexon, via Ventusltd/data-gb-electricity. '
      + 'Historic system conditions only: not a forecast, not a price '
      + 'expectation, and not a statement about any project on this map. The '
      + 'count and share do not measure local network constraint, curtailment, '
      + 'connection capacity, a usable charging window or project revenue.</p>'
      + `<a class="gb-more" href="${GB_APP}" target="_blank" rel="noopener">`
      + 'Open the full GB energy tracker &#8599;</a>';

    gbLoader.state = 'ready';
    gbLoader.schema = product.schema;
    gbLoader.renders += 1;
    link.gb_conditions = {
      reached: true,
      schema_supported: true,
      source: 'data-gb-electricity',
      schema: product.schema,
      span: price.span || null,
      available_record_daily_mean: price.available_record_daily_mean ?? null,
      negative_date_share_pct: price.negative_period_day_share_pct ?? null,
      negative_dates: negativeDays,
      included_dates: includedDays,
      lowest: low ? { value: low.value, settlement_period: low.settlement_period,
        period_start_utc: low.period_start_utc } : null,
      solar_present: product.solar ? product.solar.present : null,
      project_bindings: 0,
    };
  }


  /* ── the version ledger, on the page ──────────────────────────────────
     The estate's whole method is sealed, timestamped compositions - build a
     new one, never edit the last - and in one overnight session that produced
     twenty-four of them, each a correction with a one-line scope. Pipeline
     News ledgers its releases on the homepage; the Atlas's generations were
     visible only in git, which a visitor does not have.

     The ledger below is extracted from git at BUILD time: every composition
     manifest that ever existed, read at its last commit. It is pinned history
     carried by the page, not prose about it, and nothing is fetched at
     runtime. Rollback doctrine, stated where the versions are: a bad
     composition is never repaired in place - an earlier one is composed
     again under a new timestamp.

     Mobile first, like everything since Vikram said the link travels by
     WhatsApp: a collapsed chip, viewport-sized body, newest first. */
  /* The ledger itself is a module now, in the cartridge with room for it -
     see atlas/modules/202609030157-version-ledger.js. The name is kept so
     every reader below is unchanged, and an absent module gives an empty
     ledger the panel reports rather than a throw that costs the session. */
  const VERSION_LEDGER =
    (window.__GRIDATLAS_MODULES__ || {}).versionLedger?.entries || [];
  const PRE_SCOPE_COMPOSITIONS = 16;
  const LEDGER_ID = 'gridatlas-version-ledger';
  const LEDGER_DOCTRINE = 'Each row is immutable audit evidence, not a promise '
    + 'that it was live. REJECTED_PRE_PROMOTION entries were never live and are '
    + 'not rollback targets. A deployed bad composition is never repaired in place; '
    + 'an earlier deployed one is composed again under a new timestamp.';

  function ledgerStamp(generation) {
    return generation.slice(0, 4) + '-' + generation.slice(4, 6) + '-'
      + generation.slice(6, 8) + ' ' + generation.slice(8, 10) + ':'
      + generation.slice(10, 12) + ' UTC';
  }

  function installVersionLedger() {
    if (document.getElementById(LEDGER_ID)) return;
    const stack = document.querySelector('.map-controls');
    if (!stack) { link.failures.push('no map-controls for the ledger'); return; }

    const style = document.createElement('style');
    style.id = LEDGER_ID + '-style';
    style.textContent = SLD_STYLES.versionLedger(LEDGER_ID);
    document.head.appendChild(style);

    const panel = document.createElement('div');
    panel.id = LEDGER_ID;
    panel.dataset.open = '0';
    const button = document.createElement('button');
    button.type = 'button';
    const newest = VERSION_LEDGER[VERSION_LEDGER.length - 1];
    button.textContent = 'Versions \u00b7 ' + newest.v + ' \u25b8';
    button.setAttribute('aria-expanded', 'false');
    const body = document.createElement('div');
    body.className = 'vl-body';

    const rows = [...VERSION_LEDGER].reverse().map(entry =>
      '<div class="vl-row"><div class="vl-head">'
      + '<span class="vl-ver">' + entry.v
      + (entry.status ? '<span class="vl-status">' + entry.status + '</span>' : '')
      + '</span>'
      + '<span class="vl-when">' + ledgerStamp(entry.g) + '</span></div>'
      + '<div class="vl-scope">' + entry.s + '</div>'
      + (entry.reason ? '<div class="vl-reason">' + entry.reason + '</div>' : '')
      + '</div>').join('');
    body.innerHTML = rows
      + '<p class="vl-note">' + LEDGER_DOCTRINE + ' ' + PRE_SCOPE_COMPOSITIONS
      + ' earlier compositions predate '
      + 'the scope line. Extracted from the repository history at build time; '
      + 'nothing here is fetched or editable at runtime.</p>';

    panel.appendChild(button);
    panel.appendChild(body);
    button.addEventListener('click', (event) => {
      event.stopPropagation();
      event.preventDefault();
      const open = panel.dataset.open === '1';
      panel.dataset.open = open ? '0' : '1';
      button.textContent = 'Versions \u00b7 ' + newest.v + (open ? ' \u25b8' : ' \u25be');
      button.setAttribute('aria-expanded', String(!open));
    });
    panel.addEventListener('click', (event) => event.stopPropagation());
    stack.appendChild(panel);
    link.version_ledger = { entries: VERSION_LEDGER.length, newest: newest.v,
      rejected_pre_promotion: VERSION_LEDGER
        .filter(entry => entry.status === 'REJECTED_PRE_PROMOTION').map(entry => entry.v) };
  }



  /* ── the Grid Finding Scope ───────────────────────────────────────────
     Vikram: clicking blank space should show what grid is in the
     vicinity. Until v9.62 a blank click cleared the map, which treated
     everywhere that is not a consented project as empty. It is not empty;
     it is unexamined.

     The computation is the grid-scope module: this half only arms it,
     draws it and writes it down. The neon project path is untouched and
     remains the anchor - a scope never runs where a project or substation
     was hit. */
  const SCOPE_SRC = 'gridatlas-scope-src';
  const SCOPE_RING_LAYER = 'gridatlas-scope-rings';
  const SCOPE_DOT_LAYER = 'gridatlas-scope-dots';
  const SCOPE_COLOUR = '#7fb5d8';        // cool blue: neither project nor declared
  let scopeArmed = false;
  /* Armed explicitly, like the scope. Published on the link object so a
     reviewer can ask the page which modes are live. */
  let pointArmed = false;
  let scopeResult = null;

  function scopeModule() {
    try { return window.__GRIDATLAS_MODULES__?.gridScope || null; }
    catch (_) { return null; }
  }

  function ensureScopeLayers(map) {
    if (map.getSource(SCOPE_SRC)) return true;
    if (!guardedAddSource(map, SCOPE_SRC, { type: 'geojson', data: emptyCollection() })) {
      return false;
    }
    map.addLayer({ id: SCOPE_RING_LAYER, type: 'circle', source: SCOPE_SRC,
      filter: ['==', ['get', 'kind'], 'band'],
      paint: { 'circle-radius': ['get', 'pixels'], 'circle-color': 'transparent',
        'circle-stroke-color': SCOPE_COLOUR, 'circle-stroke-width': 1,
        'circle-stroke-opacity': 0.5 } });
    map.addLayer({ id: SCOPE_DOT_LAYER, type: 'circle', source: SCOPE_SRC,
      filter: ['==', ['get', 'kind'], 'site'],
      paint: { 'circle-radius': 4, 'circle-color': SCOPE_COLOUR,
        'circle-stroke-color': '#04141c', 'circle-stroke-width': 1 } });
    return true;
  }

  function clearScope() {
    scopeResult = null;
    const map = capturedMap;
    if (map && map.getSource(SCOPE_SRC)) setSourceData(map, SCOPE_SRC, emptyCollection());
    document.querySelectorAll('.' + SCOPE_BLOCK).forEach(node => node.remove());
    link.grid_scope = null;
  }

  const SCOPE_BLOCK = 'gridatlas-scope-block';

  function scopeHtml(result) {
    const bands = result.bands.map(band => {
      const classes = Object.keys(band.by_class_kv)
        .map(Number).sort((a, b) => b - a)
        .map(kv => `${band.by_class_kv[kv]} \u00d7 ${kv} kV`).join(', ');
      return `<li><span class="neon-km">${band.within_km} km</span>`
        + `<span class="neon-name">${band.substations
          ? escapeHtml(classes) : 'nothing mapped'}</span></li>`;
    }).join('');
    const nearest = result.nearest_named.slice(0, 3).map(entry =>
      `<li><span class="neon-km">${entry.km.toFixed(2)} km</span>`
      + `<span class="neon-name">${escapeHtml(entry.name)}</span>`
      + `<span class="neon-kv">${entry.kv} kV</span></li>`).join('');
    /* Which cartridges answered, on the card, not in a console.
       ------------------------------------------------------------------
       Vikram: a click anywhere should make the neons "look for cartridges
       and code". The looking is the source-registry module; this prints
       what it found. A reader told that five of six sources answered and
       which one did not can judge the answer in front of them. A reader
       shown a quietly shorter answer cannot, and will reasonably assume
       the map has told them everything it knows. */
    const survey = result.sources || null;
    const sourcesLine = survey
      ? `<p class="neon-caveat"><b>Sources:</b> ${escapeHtml(survey.sentence)}</p>`
      : '';
    return `<div class="${SCOPE_BLOCK} ${BLOCK_CLASS}">`
      + `<div class="neon-hd">Grid finding scope<span class="neon-beta">Beta</span></div>`
      + `<p class="neon-caveat">${escapeHtml(result.what_this_is)}</p>`
      + `<ol>${bands}</ol>`
      + (nearest ? `<div class="neon-hd">Nearest named</div><ol>${nearest}</ol>` : '')
      + topologyBlockHtml(result.nearest_named.slice(0, 3).map(entry => ({ name: entry.name, kv: entry.kv })))
      + `<p class="neon-caveat"><b>${escapeHtml(result.what_this_is_not)}</b></p>`
      + sourcesLine
      + `<p class="neon-caveat">${escapeHtml(result.method)}. `
      + `Substations as mapped in this release's payload; an absence here is `
      + `an absence from the map, not from the ground.</p></div>`;
  }

  async function runGridScope(map, origin) {
    const scope = scopeModule();
    if (!scope) { noteFailure('grid scope: module unavailable'); return; }
    if (!link.substations_qualifying) {
      injectStatusStyle();
      showStatus('Reading the substation data for this area.', 'waiting');
    }
    const subs = await loadSubstations();
    if (!subs.length) {
      injectStatusStyle();
      showStatus('The substation data did not load, so nothing can be counted '
        + 'here. This is usually the network rather than the place.', 'failed');
      return;
    }
    clearStatus();
    const result = scope.scope(origin, subs, { nearestCount: 5 });

    /* Ask what could have answered, before saying what did.
       ------------------------------------------------------------------
       The deep scan of 202609012230 found this path reporting only what
       OpenStreetMap has mapped while the cartridge holding NESO's 886
       published connection points sat loaded in the same page. The scope
       still counts only what it can count - widening the computation is a
       separate, provable change - but it no longer stays silent about the
       sources it did not use. */
    const registry = window.__GRIDATLAS_MODULES__?.sourceRegistry || null;
    if (registry) {
      try { result.sources = registry.survey(window); }
      catch (error) { noteFailure('source registry: ' + String(error?.message || error)); }
    }

    scopeResult = result;
    link.grid_scope = { counted: result.counted, radius_km: result.radius_km,
      nearest_km: result.nearest[0]?.km ?? null,
      sources_ready: result.sources?.ready || null,
      sources_missing: result.sources?.missing || null };

    if (ensureScopeLayers(map)) {
      /* The bands are drawn in metres-per-pixel at the current zoom, so a
         ring means the distance it says at the zoom it was drawn. */
      const metresPerPixel = 156543.03392
        * Math.cos(origin[1] * Math.PI / 180) / Math.pow(2, map.getZoom());
      const features = result.bands.map(band => ({
        type: 'Feature',
        properties: { kind: 'band', pixels: (band.within_km * 1000) / metresPerPixel },
        geometry: { type: 'Point', coordinates: origin }
      })).concat(result.nearest.map(entry => ({
        type: 'Feature', properties: { kind: 'site' },
        geometry: { type: 'Point', coordinates: entry.at }
      })));
      setSourceData(map, SCOPE_SRC, { type: 'FeatureCollection', features });
    }

    const gl = window.maplibregl;
    if (gl?.Popup) {
      try {
        new gl.Popup({ maxWidth: '360px', closeOnClick: false })
          .setLngLat(origin)
          .setHTML(scopeHtml(result))
          .addTo(map);
      } catch (error) {
        noteFailure('grid scope card: ' + String(error?.message || error));
      }
    }
  }

  /* ── the mobile tray ──────────────────────────────────────────────────
     Vikram's phone acceptance, 2026-09-01: the six shell tool buttons at
     44px touch height are the right size to hit and the wrong size to keep
     on screen - a third of a portrait map behind buttons - and the switches
     that turn the grid lines and substations on live below the map, where a
     phone never looks. Both are composition faults, not engine faults: the
     44px rule is this cartridge's own coarse-pointer override, and the
     engine's switches work - toggled live in Chrome, the lines drew at once.

     So on a touch screen or a narrow window the six tool buttons collapse
     behind one chip, and two first-class chips - GRID and SUBS - stand on
     the map itself. They drive the engine's own checkboxes with real
     clicks, the same path enableTechnologyLayer has used all along, so the
     scada panel, the fullscreen curtain and these chips cannot disagree. */