GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Grid network and substations / gridatlas / atlas/cartridges

Substation Intelligence V9 63 (part 21)

A JavaScript file in the cartridges folder of GridAtlas that maps elizabeth line, using haversine and SHA-256 and uses data from the Ventus Grid Engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Grid network and substations. Section 392 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. Substation Intelligence V9 63 geodesy · gridatlas / atlas/cartridges/202611180026-substation-intelligence-v9-63.js lines 6175–6874

Substation Intelligence V9 63

A JavaScript file in the cartridges folder of GridAtlas that maps elizabeth line, using haversine and SHA-256 and uses data from the Ventus Grid Engine, data-federation-map-for-GlobalGrid2050-all-repos and spiders repositories.

Set aside from the main view: A comment at the top of the file says a tool wrote it. (noise-generated, proposed by noise.py). All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line 4 comment: * ASSEMBLED by tools/build-cartridge.mjs from the parts below. Do not edit

geodesygridatlas / atlas/cartridges/202611180026-substation-intelligence-v9-63.js · lines 6175–6874 of 8609 · version 2026-11-18 00:26 (continued from section 383) · pattern switchOn (shared by 4 files)

What it does
It maps elizabeth line, london underground, UK metros trams and hs2. Defines 238 functions or classes, including deepFreeze, escapeHTML, normalizeStatus, fmt, haversine. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): 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: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: spiders data; data source: npm data; GeoJSON file elizabeth_line.geojson; GeoJSON file london_underground.geojson; GeoJSON file uk_metros_trams.geojson; GeoJSON file hs2.geojson. Out: downloaded file gridatlas-; downloaded file globalgrid2050-grid-atlas-; interactive map; canvas drawing; SVG drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 11kV.
Downstream impact
Used directly by 4 files: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/); Map Removal Test (gridatlas); Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Ventus Grid Engine — Genome Page (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/). Reached from 2 other entry points, including GridAtlas PR File Size Guard Workflow (gridatlas); Genome Workflow (ventus-grid-engine).
What it achieves
It normalizes status (`normalizeStatus`), toggles zone draw mode (`toggleZoneDrawMode`) and opens popup (`openPopup`). ASSEMBLED by `tools/build-cartridge.mjs` from the parts below. Its code works with 400 kV, 100 MVA and 132 kV. It responds to fullscreenchange, webkitfullscreenchange and click events.
Why it matters
Loaded by the Substation Finder page in Code Generator at https://ventusltd.github.io/code-generator/apps/substation-finder/ and 1 other page. Also imported by Build Graph, from Ventus Grid Engine. Checked by Map Removal Test.
Application
gridatlas · atlas/cartridges · script
VEDIC
SNAP LINE ENDS TO SUBSTATIONS (GG2050-VEDIC-000106): GridAtlas / Substations · Geospatial data processing. line_features, substation_point_features → Line features whose first and last vertices are moved onto the nearest substation point within tolerance; other geometry unchanged.
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
Uses
Spider Full Po Test (estate URL), Data — Grid Studies Public Page (estate URL)
Used by
linked from Code Generator — Substation Finder Page (link), referenced by Map Removal Test (new URL import.meta.url), named by URL in Build Graph (estate URL), named by URL in Ventus Grid Engine — Genome Page (estate URL), mentioned in Standalone (comment link)
Produces
deepFreeze, escapeHTML, normalizeStatus, fmt, haversine, _zoneDrawGetRadius, _zoneDrawCirclePoints, _zoneDrawCalcArea, _zoneDrawUpdateLayers, _zoneDrawShowPopup, _zoneDrawShowPopupDebounced, _zoneDrawClear
Defines here
tidy, retire, watch, note, readRegisterSource, primeRegister, loadRegister, readSelection, near, collection, setSourceData, ensureLayers, escapeHtml, setVisibility, labelFor, paintLabels, refresh, buildGroup, bind, install
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/cartridges/202611180026-substation-intelligence-v9-63.js:6175-6874 · blob c6f9632fdb6e803baae03a54a542fe508431d153 · 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: production_core

   WHAT THIS DELIBERATELY DOES NOT DO

   - It does not touch a FAILED arrival. When the identity could not be
     resolved the results are the only thing on screen that explains why, and
     hiding them would leave a reader with a map and no account of it.
   - It does not clear a box the reader has touched. Focus or a keystroke
     retires this permanently, so a reader who starts typing while the
     arrival is still resolving never has their text taken away.
   - It does not clear a box holding something other than the ref, which is
     the same rule stated for the case where another lane wrote there first.
   - It hides with `style.display = 'none'`, which is what the shell's own
     Escape key and map click do. This is the product's mechanism, not a new
     one, so nothing has to be taught how to bring it back.

   It runs only where there is a MutationObserver. The cartridge proofs
   execute composed cartridges under node:vm against a window stub that has
   neither observers nor timers, and a module that throws there takes the
   whole cartridge down with it - which is exactly how v9.92 shipped a menu
   bar that broke the sandbox proof. Where there is no observer there is no
   arrival either, so doing nothing is the correct answer rather than a
   degraded one. */
(function arrivalTidy() {
  if (typeof document === 'undefined' || typeof window === 'undefined') return;
  if (typeof MutationObserver !== 'function') return;

  var ref = '';
  try {
    ref = String(new URLSearchParams(window.location.search).get('repd_ref') || '').trim();
  } catch (_) { return; }
  if (!ref) return;

  var typed = false;
  var done = false;

  function tidy() {
    if (done) return true;
    var state = document.body && document.body.dataset
      ? document.body.dataset.gridatlasRepdDeepLink : '';
    if (state !== 'resolved') return state === 'failed';   /* failed: stop watching, change nothing */
    var results = document.getElementById('search-results');
    var input = document.getElementById('search-input');
    if (!results || !input) return false;
    if (!typed) {
      results.style.display = 'none';
      if (input.value === ref) input.value = '';
    }
    done = true;
    return true;
  }

  function retire() { typed = true; }

  function watch() {
    var input = document.getElementById('search-input');
    if (input) {
      input.addEventListener('focus', retire, { once: true });
      input.addEventListener('input', retire, { once: true });
    }
    if (tidy()) return;
    var observer = new MutationObserver(function () {
      if (tidy()) observer.disconnect();
    });
    observer.observe(document.body, {
      attributes: true, attributeFilter: ['data-gridatlas-repd-deep-link']
    });
    window.__GRIDATLAS_ARRIVAL_TIDY__ = {
      installed: true,
      repd_ref: ref,
      get dismissed() { return done; },
      get retired_by_reader() { return typed; }
    };
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', watch, { once: true });
  } else {
    watch();
  }
}());

/**
 * Module: pipeline-news-layers
 *
 * A PIPELINE NEWS (REPD) section in the layer dashboard, beside TOPOLOGY,
 * ASSETS and TRANSIT, that summons the rest of the pipeline around whatever
 * project is currently selected.
 *
 * Vikram: "summon other pipeline items within the atlas after clicking the
 * map ... under REPD pipelinenews under its own section like topology, assets
 * etc". Arriving from Pipeline News you land on one project with five links to
 * substations and nothing else of the pipeline in view. These three controls
 * put the neighbours back: what else is being built within reach, of the same
 * technology, of the twenty technologies Pipeline News' own spine does not
 * carry, or of anything at all.
 *
 * WHY IT DOES NOT USE data-layer-id
 * ---------------------------------
 * The engine delegates a `change` listener on #scada-ui-container and on
 * #fs-curtain-keys, and any checkbox carrying `data-layer-id` is routed to its
 * own handleLayerToggle -- which would be handed an id it has no config for.
 * These controls carry `data-pn-layer` instead and are handled here. Same
 * lesson as the wider-fleet tabs in Pipeline News: borrow the styling, never
 * the attribute that another owner dispatches on.
 *
 * WHAT IT IS NOT
 * --------------
 * It draws register points near a selection. It does not measure them, rank
 * them, bind them to the selected project, or imply any relationship between
 * them. Two projects near each other share a map square and nothing else --
 * not a circuit, not a connection, not a queue position. The labels say
 * "within 25 km" and stop there.
 *
 * Depends on: geodesy.
 */
(() => {
  'use strict';

  const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  if (NS.pipelineNewsLayers) return;

  const geodesy = NS.geodesy;
  if (!geodesy) {
    throw new Error('pipeline-news-layers requires the geodesy module');
  }

  const GENERATION = '202609030048';
  const RADIUS_KM = 25;
  const GROUP_TITLE = 'PIPELINE NEWS (REPD)';

  /* The register comes from the engine, not from a URL.
     ----------------------------------------------------------------------
     dist/repd_master.json is NOT a served file. Fetching it 404s on the live
     host and in a local checkout alike -- measured both ways -- because the
     streaming bridge reconstructs the register from parquet and hands it
     straight to MapLibre. Every REPD layer the engine draws (l-solar, l-wind,
     l-bess, l-biomass and the rest) is a filter over ONE shared source, and
     that source holds all 10,784 rows once any one of those layers has been
     switched on.
     So this reads src-repd. It is the engine's register, hydrated by the
     engine, and there is no second copy and no second fetch. If nothing has
     hydrated it yet, ticking the engine's own control is what fills it --
     the same move enableTechnologyLayer makes, for the same reason. */
  const REGISTER_SOURCE = 'src-repd';
  const REGISTER_PRIMER = 'biomass';   // any REPD control hydrates the shared source

  /* Pipeline News' spine carries four REPD technology types. Everything else
     in the register is the wider fleet -- the 1,104 projects its own product
     could not admit without changing what it is. Named by the register's own
     `tech` classification, not by a nickname. */
  const SPINE_TECHS = new Set(['solar', 'solar_roof', 'bess', 'wind']);

  /* The engine's own technology colours, so a point reads the same here as it
     does on the layer it belongs to. */
  const TECH_COLOUR = {
    solar: '#ffff00', solar_roof: '#ffcc00', bess: '#ffae00', wind: '#00ffff',
    biomass: '#39ff14', hydro: '#00aaff', hydrogen: '#ffffff', tidal: '#00bfff',
    act: '#ff6600', geothermal: '#ff3300', flywheel: '#ff69b4', caes: '#88aaff',
    other: '#888888'
  };

  const CONTROLS = [
    {
      id: 'same',
      label: 'Same technology',
      colour: '#5fbdc2',
      keep: (row, selection) => row.tech === selection.tech
    },
    {
      id: 'wider',
      label: 'Wider fleet',
      colour: '#39ff14',
      keep: (row) => !SPINE_TECHS.has(row.tech)
    },
    {
      id: 'all',
      label: 'All pipeline',
      colour: '#d8b64a',
      keep: () => true
    }
  ];

  const state = {
    schema: 'gridatlas.pipeline-news-layers.v1',
    generation: GENERATION,
    installed: false,
    register_rows: 0,
    register_url: null,
    radius_km: RADIUS_KM,
    selection: null,
    counts: {},
    active: [],
    failures: []
  };
  window.__GRIDATLAS_PIPELINE_LAYERS__ = state;

  function note(message) {
    const text = String(message && message.message ? message.message : message);
    if (!state.failures.includes(text)) state.failures.push(text);
  }

  const removedMaps = new WeakSet();
  let installedMap = null;
  let register = null;         // the engine's rows, read once and kept

  function readRegisterSource(map) {
    try {
      const source = map.getSource(REGISTER_SOURCE);
      const features = source && source._data && source._data.features;
      if (!Array.isArray(features) || !features.length) return null;
      return features.map((feature) => {
        const properties = feature.properties || {};
        const coordinates = (feature.geometry || {}).coordinates || [];
        return {
          name: properties.name || '',
          operator: properties.operator || '',
          tech: properties.tech || 'other',
          raw: properties.raw_tech || '',
          status: properties.status || '',
          mw: Number(properties.capacity) || 0,
          lon: Number(coordinates[0]),
          lat: Number(coordinates[1])
        };
      }).filter((row) => Number.isFinite(row.lon) && Number.isFinite(row.lat));
    } catch (error) {
      note('register: ' + String(error && error.message || error));
      return null;
    }
  }

  /* Ask the engine to hydrate its own register, by ticking the control it
     owns rather than reaching past it into the map. The panel then tells the
     truth about what is on, which it would not if this added a source itself. */
  function primeRegister() {
    const box = document.querySelector(
      '#scada-ui-container input[type=checkbox][data-layer-id="' + REGISTER_PRIMER + '"]');
    if (!box) { note('register: no ' + REGISTER_PRIMER + ' control to prime with'); return false; }
    if (!box.checked) box.click();
    state.primed_with = REGISTER_PRIMER;
    return true;
  }

  async function loadRegister(map) {
    if (removedMaps.has(map)) return [];
    if (register) return register;
    register = readRegisterSource(map);
    if (register) { state.register_rows = register.length; return register; }

    if (!primeRegister()) throw new Error('register unavailable');
    for (let attempt = 0; attempt < 40; attempt += 1) {
      await new Promise((resolve) => setTimeout(resolve, 250));
      if (removedMaps.has(map)) return [];
      register = readRegisterSource(map);
      if (register) { state.register_rows = register.length; return register; }
    }
    note('register: ' + REGISTER_SOURCE + ' did not hydrate within 10 s');
    throw new Error('register unavailable');
  }

  /* The selected project, read from the pin the sld-sandbox cartridge draws.
     There is no public selection surface carrying coordinates -- last_selection
     has the name, the technology and the nearest distance, but not the origin
     -- so this reads the pin source and corroborates it against the public
     project_pin.name before trusting it. If the cartridge ever publishes the
     origin properly, delete this and read that. */
  function readSelection(map) {
    try {
      const source = map.getSource('gridatlas-project-pin');
      const features = source && source._data && source._data.features;
      if (!features || !features.length) return null;
      const [lon, lat] = features[0].geometry.coordinates || [];
      if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null;
      const links = window.__GRIDATLAS_NEON_LINKS__ || {};
      const name = (features[0].properties || {}).name
        || (links.project_pin || {}).name || '';
      return { lon, lat, name, tech: (links.last_selection || {}).tech || '' };
    } catch (error) {
      note('selection: ' + String(error && error.message || error));
      return null;
    }
  }

  function near(rows, selection) {
    const found = [];
    for (const row of rows) {
      const km = geodesy.distanceKm(selection.lon, selection.lat, row.lon, row.lat);
      if (km > RADIUS_KM) continue;
      // The selected project is not one of its own neighbours.
      if (km < 0.0005 && row.name === selection.name) continue;
      found.push({ ...row, km });
    }
    found.sort((a, b) => a.km - b.km);
    return found;
  }

  function collection(rows) {
    return {
      type: 'FeatureCollection',
      features: rows.map((row) => ({
        type: 'Feature',
        geometry: { type: 'Point', coordinates: [row.lon, row.lat] },
        properties: {
          name: row.name, operator: row.operator, tech: row.tech,
          raw_tech: row.raw, status: row.status, mw: row.mw,
          km: Number(row.km.toFixed(3)),
          colour: TECH_COLOUR[row.tech] || TECH_COLOUR.other
        }
      }))
    };
  }

  /* addSource throws if the style is not loaded, and a source that failed to
     add reads back as null. The sld-sandbox body learned this the night the
     basemap CDN served style.json and then no tiles at all, and its proof now
     refuses any unguarded setData call site anywhere in the served
     cartridge -- including, as it turns out, one written inside a comment.
     This section is drawing, not plumbing: a missing source costs the drawing,
     not the session. */
  function setSourceData(map, id, data) {
    try {
      const source = map.getSource(id);
      if (!source || typeof source.setData !== 'function') {
        note('source missing, nothing drawn: ' + id);
        return false;
      }
      source.setData(data);
      return true;
    } catch (error) {
      note('source ' + id + ': ' + String(error && error.message || error));
      return false;
    }
  }

  function ensureLayers(map, control) {
    const sourceId = 'pn-src-' + control.id;
    const ringId = 'l-pn-' + control.id + '-ring';
    const dotId = 'l-pn-' + control.id;
    if (map.getSource(sourceId)) return { sourceId, ringId, dotId };
    try {
      map.addSource(sourceId, { type: 'geojson', data: collection([]) });
    } catch (error) {
      note('addSource ' + sourceId + ': ' + String(error && error.message || error));
      return { sourceId, ringId, dotId };
    }
    // A ring in the control's colour, a dot in the technology's own. The ring
    // says which control summoned it; the dot says what it is.
    map.addLayer({
      id: ringId, type: 'circle', source: sourceId,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 4, 12, 8, 16, 13],
        'circle-color': 'rgba(0,0,0,0)',
        'circle-stroke-color': control.colour,
        'circle-stroke-width': 1.4,
        'circle-stroke-opacity': 0.9
      }
    });
    map.addLayer({
      id: dotId, type: 'circle', source: sourceId,
      paint: {
        'circle-radius': ['interpolate', ['linear'], ['zoom'], 6, 1.8, 12, 3.4, 16, 5.5],
        'circle-color': ['coalesce', ['get', 'colour'], '#888888'],
        'circle-opacity': 0.95
      }
    });
    map.on('click', dotId, (event) => {
      const properties = (event.features && event.features[0] || {}).properties || {};
      try {
        new window.maplibregl.Popup({ closeButton: true })
          .setLngLat(event.lngLat)
          .setHTML(
            '<div style="font-family:monospace;background:#000;padding:6px;max-width:260px">'
            + '<b style="color:#5fbdc2;font-size:12px">' + escapeHtml(properties.name || 'Project') + '</b><br>'
            + '<span style="color:#888">' + escapeHtml(properties.raw_tech || properties.tech || '') + '</span><br>'
            + '<span style="color:#ffae00">' + escapeHtml(String(properties.mw || 0)) + ' MW</span> · '
            + '<span style="color:#aaa">' + escapeHtml(properties.status || '') + '</span><br>'
            + '<span style="color:#555;font-size:10px">' + escapeHtml(String(properties.km)) + ' km from the selected project. '
            + 'Proximity only — not a connection, a circuit or a queue position.</span></div>')
          .addTo(map);
      } catch (error) {
        note('popup: ' + String(error && error.message || error));
      }
    });
    map.on('mouseenter', dotId, () => { map.getCanvas().style.cursor = 'pointer'; });
    map.on('mouseleave', dotId, () => { map.getCanvas().style.cursor = ''; });
    return { sourceId, ringId, dotId };
  }

  function escapeHtml(value) {
    return String(value == null ? '' : value)
      .replace(/[&<>"]/g, (character) => ({
        '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'
      }[character]));
  }

  function setVisibility(map, control, visible) {
    for (const id of ['l-pn-' + control.id + '-ring', 'l-pn-' + control.id]) {
      if (map.getLayer(id)) map.setLayoutProperty(id, 'visibility', visible ? 'visible' : 'none');
    }
  }

  function labelFor(control, count, selection) {
    if (!selection) return control.label + ' [SELECT A PROJECT]';
    if (count === null || count === undefined) return control.label + ' [WAIT]';
    return control.label + ' [' + count.toLocaleString('en-GB') + ' within ' + RADIUS_KM + ' km]';
  }

  function paintLabels(selection) {
    for (const control of CONTROLS) {
      const text = labelFor(control, state.counts[control.id], selection);
      for (const span of document.querySelectorAll('[data-pn-label="' + control.id + '"]')) {
        span.textContent = text;
      }
    }
  }

  async function refresh(map, control) {
    if (removedMaps.has(map)) return;
    const selection = state.selection;
    if (!selection) return;
    const rows = await loadRegister(map);
    if (removedMaps.has(map)) return;
    const found = near(rows.filter((row) => control.keep(row, selection)), selection);
    state.counts[control.id] = found.length;
    const { sourceId } = ensureLayers(map, control);
    setSourceData(map, sourceId, collection(found));
    paintLabels(selection);
  }

  function buildGroup(container, isFullscreen) {
    if (container.querySelector('[data-pn-group]')) return;
    const group = document.createElement('div');
    group.className = 'key-group';
    group.setAttribute('data-pn-group', '1');
    const title = document.createElement('div');
    title.className = 'key-title';
    title.textContent = GROUP_TITLE;
    group.appendChild(title);

    for (const control of CONTROLS) {
      const label = document.createElement('label');
      label.className = 'key-item';
      const input = document.createElement('input');
      input.type = 'checkbox';
      // NOT data-layer-id: the engine dispatches on that attribute.
      input.setAttribute('data-pn-layer', control.id);
      input.dataset.pnLayer = control.id;
      const span = document.createElement('span');
      span.setAttribute('data-pn-label', control.id);
      span.style.color = control.colour;
      span.textContent = labelFor(control, state.counts[control.id], state.selection);
      label.appendChild(input);
      label.appendChild(document.createTextNode(' '));
      label.appendChild(span);
      group.appendChild(label);
    }
    container.appendChild(group);
    state[isFullscreen ? 'installed_fullscreen' : 'installed_main'] = true;
  }

  function bind(map, container) {
    container.addEventListener('change', (event) => {
      if (removedMaps.has(map)) return;
      const target = event.target;
      if (!target || target.type !== 'checkbox' || !target.dataset.pnLayer) return;
      const control = CONTROLS.find((candidate) => candidate.id === target.dataset.pnLayer);
      if (!control) return;

      // Keep the two dashboards agreeing, as the engine does for its own.
      for (const twin of document.querySelectorAll(
        'input[data-pn-layer="' + control.id + '"]')) {
        twin.checked = target.checked;
      }

      state.active = CONTROLS
        .filter((candidate) => document.querySelector(
          'input[data-pn-layer="' + candidate.id + '"]:checked'))
        .map((candidate) => candidate.id);

      if (!target.checked) {
        setVisibility(map, control, false);
        return;
      }
      if (!state.selection) {
        // Nothing is selected, so there is no "near" to be near to. Say so on
        // the label rather than switching on an empty layer and looking broken.
        paintLabels(null);
        target.checked = false;
        return;
      }
      ensureLayers(map, control);
      setVisibility(map, control, true);
      refresh(map, control).catch((error) => {
        note('refresh: ' + String(error && error.message || error));
        paintLabels(state.selection);
      });
    });
  }

  function install() {
    const map = window.__GRIDATLAS_V9_MAP__;
    const container = document.getElementById('scada-ui-container');
    if (!map || typeof map.addSource !== 'function' || removedMaps.has(map)) return false;
    if (!container || !container.querySelector('.key-group')) return false;

    installedMap = map;
    buildGroup(container, false);
    bind(map, container);

    const curtain = document.getElementById('fs-curtain-keys');
    if (curtain) { buildGroup(curtain, true); bind(map, curtain); }

    /* Watch the pin rather than the cartridge. There is no selection event to
       subscribe to, and wrapping the cartridge's selectAt would make this a
       second owner of its behaviour. A one-second poll of a source it already
       maintains is the smaller coupling, and costs nothing measurable. */
    let lastKey = '';
    if (typeof setInterval !== 'function') return true;
    const selectionPoll = setInterval(() => {
      if (removedMaps.has(map)) return;
      const selection = readSelection(map);
      const key = selection ? [selection.lon, selection.lat, selection.tech].join('|') : '';
      if (key === lastKey) return;
      lastKey = key;
      state.selection = selection;
      state.counts = {};
      if (!selection) {
        for (const control of CONTROLS) setVisibility(map, control, false);
        paintLabels(null);
        return;
      }
      paintLabels(selection);
      for (const control of CONTROLS) {
        if (!document.querySelector('input[data-pn-layer="' + control.id + '"]:checked')) continue;
        refresh(map, control).catch((error) => note('refresh: '
          + String(error && error.message || error)));
      }
    }, 1000);
    map.on('remove', () => {
      removedMaps.add(map);
      clearInterval(selectionPoll);
      if (installedMap !== map) return;
      installedMap = null;
      state.installed = false;
      state.selection = null;
      state.counts = {};
      state.active = [];
    });

    state.installed = true;
    return true;
  }

  /* The engine builds its dashboard inside map.on('load'), so nothing here can
     assume a panel at module time. Poll until it exists, then stop.

     Guarded on the timer existing at all. The cartridge proof runs this file
     in a bare vm context with no DOM and no timers, to check the served bytes
     without a browser; an unguarded setInterval threw there and took the whole
     proof down. A context with no timers also has no map and no dashboard, so
     there is nothing for this to install and returning is the correct answer
     rather than a concession to the harness. */
  if (typeof setInterval === 'function') {
    const started = Date.now();
    const boot = setInterval(() => {
      let done = false;
      try { done = install(); } catch (error) { note('install: ' + String(error && error.message || error)); }
      if (done || Date.now() - started > 120000) clearInterval(boot);
    }, 400);
  }

  NS.pipelineNewsLayers = Object.freeze({
    schema: 'gridatlas.module.pipeline-news-layers.v1',
    generation: GENERATION,
    RADIUS_KM,
    CONTROLS: CONTROLS.map((control) => control.id),
    install,
    state
  });
})();

/**
 * SLD runtime styles, mechanically lifted from the v9.106 sandbox body.
 *
 * This module owns only the seven template-literal CSS values. The sandbox
 * still owns when each surface is installed and the DOM element receiving it.
 * Keeping those lifecycles in place makes this a byte-for-byte style move,
 * not a UI redesign. The sibling substation cartridge carries this module
 * because it executes before sld-sandbox and has the required headroom.
 */
(() => {
  'use strict';

  const NS = (window.__GRIDATLAS_MODULES__ = window.__GRIDATLAS_MODULES__ || {});
  if (NS.sldStyles) throw new Error('sld-styles module registered twice');

  NS.sldStyles = Object.freeze({
    schema: 'gridatlas.module.sld-styles.v1',
  neonBlock(BLOCK_CLASS) {
    return `
.${BLOCK_CLASS}{margin-top:7px;padding-top:6px;border-top:1px solid #123;font-family:monospace}
.${BLOCK_CLASS} .neon-hd{display:flex;align-items:center;gap:6px;font-size:10px;letter-spacing:.06em;
  color:#5fbdc2;font-weight:bold;text-transform:uppercase}
.${BLOCK_CLASS} .neon-beta{font-size:8px;letter-spacing:.06em;padding:1px 4px;border-radius:2px;
  background:#3a2f12;color:#e0b050;border:1px solid #6a5320;text-transform:uppercase}
.${BLOCK_CLASS} ol{list-style:none;margin:5px 0 0;padding:0}
.${BLOCK_CLASS} li{display:flex;align-items:baseline;gap:6px;padding:2px 0}
.${BLOCK_CLASS} .neon-km{color:#5fbdc2;font-weight:bold;font-variant-numeric:tabular-nums;
  min-width:54px;text-shadow:0 0 6px rgba(95,189,194,.35)}
.${BLOCK_CLASS} .neon-name{color:#9fb3ba;overflow:hidden;text-overflow:ellipsis;
  white-space:nowrap;flex:1;max-width:150px}
.${BLOCK_CLASS} .neon-kv{color:#ffae00;font-size:9px;white-space:nowrap;cursor:help}
.${BLOCK_CLASS} .neon-kvnote{margin-top:6px;font-size:10px;line-height:1.45}
.${BLOCK_CLASS} .neon-kvnote b{color:#ffae00;font-weight:normal}
.${BLOCK_CLASS} .neon-pin{display:block;width:100%;margin-top:7px;padding:5px 6px;
  background:#0a1a1d;border:1px solid #2f6f75;border-radius:3px;color:#8b9aa1;
  font:inherit;font-size:10px;letter-spacing:.05em;cursor:pointer;text-transform:uppercase}
.${BLOCK_CLASS} .neon-pin:hover{border-color:#5fbdc2;color:#bfe9ee}
.${BLOCK_CLASS} .neon-pin[aria-pressed="false"]{color:#5f7a80;border-color:#1d3238}
.${BLOCK_CLASS} .neon-layout{display:block;width:100%;margin-top:7px;padding:5px 6px;
  background:#0a1a1d;border:1px solid #2f6f75;border-radius:3px;color:#5fbdc2;
  font:inherit;font-size:10px;letter-spacing:.05em;cursor:pointer;text-transform:uppercase}
.${BLOCK_CLASS} .neon-layout:hover{border-color:#5fbdc2;color:#bfe9ee;background:#0d2429}
/* The measurement and its qualifiers, as one element. A hairline rule and
   six pixels of padding: nothing here colours or grades the number. */
.${BLOCK_CLASS} .neon-answer{margin:0 0 8px;padding:6px 0 8px;
  border-bottom:1px solid #123}
.${BLOCK_CLASS} .neon-answer > .neon-caveat:first-child{margin-top:0}
/* The card sits over the map and used to be immovable, with only MapLibre's
   own hairline close cross. It gets a bar: grab it to move the card out of the
   way, and two controls big enough to hit without aiming. */
/* Measured on the live map: the card was 563px tall inside a 319px map and
   hung 403px below it, so the caveat and the layout button could not be
   reached at all. The content is now bounded to the map and scrolls, and the
   bar stays put at the top of that scroll so the controls never leave. */
.maplibregl-popup-content{max-height:var(--gridatlas-card-max, 60vh) !important;
  overflow-y:auto !important;overflow-x:hidden;overscroll-behavior:contain}
.gridatlas-card-bar{position:sticky;top:-6px;z-index:2;flex:0 0 auto;
  display:flex;align-items:center;gap:6px;margin:-6px -6px 6px;
  padding:5px 6px;background:#0a1a1d;border-bottom:1px solid #1d3238;
  border-radius:3px 3px 0 0;cursor:grab;user-select:none;touch-action:none;font-family:monospace}
.gridatlas-card-bar:active{cursor:grabbing}
.gridatlas-card-bar .grip{color:#3f6f75;letter-spacing:2px;font-size:11px}
.gridatlas-card-bar .label{color:#8b9aa1;font-size:10px;max-width:190px;overflow:hidden;
  text-overflow:ellipsis;white-space:nowrap}
.maplibregl-popup.gridatlas-min .gridatlas-card-bar .label{color:#5fbdc2;font-weight:bold;max-width:230px}
.gridatlas-card-bar .spacer{flex:1}
.gridatlas-card-bar button{background:#050a0d;border:1px solid #2f6f75;color:#5fbdc2;
  font:inherit;font-size:14px;line-height:1;min-width:44px;height:44px;border-radius:3px;
  cursor:pointer;padding:0 6px}
.gridatlas-card-bar button:hover{color:#bfe9ee;border-color:#5fbdc2;background:#0d2429}
.gridatlas-card-bar button.close:hover{color:#ff8f8f;border-color:#ff5d5d}
.maplibregl-popup.gridatlas-free{position:fixed !important;transform:none !important;
  left:var(--gx) !important;top:var(--gy) !important;z-index:12}
.maplibregl-popup.gridatlas-free .maplibregl-popup-tip{display:none !important}
.maplibregl-popup.gridatlas-min .maplibregl-popup-content > *:not(.gridatlas-card-bar){display:none !important}
.maplibregl-popup.gridatlas-min .maplibregl-popup-content{padding:6px !important;
  border:1px solid #2f6f75;border-radius:4px;box-shadow:0 0 14px rgba(95,189,194,.25)}
.maplibregl-popup.gridatlas-min .gridatlas-card-bar{margin:0;border-bottom:0;
  border-radius:3px;background:#08171a}
.maplibregl-popup.gridatlas-min .gridatlas-card-bar button.min{border-color:#5fbdc2;color:#bfe9ee}
.${BLOCK_CLASS} .neon-caveat{margin-top:6px;color:#68797f;font-size:9px;line-height:1.5}
.${BLOCK_CLASS} .neon-caveat b{color:#8b9aa1;font-weight:bold}
/* The immutable shell predates phone-landscape use. These are composition
   overrides, not a mutation of the attested shell: the left control stack can
   scroll inside a short map, and search results cannot extend below it. */
@media (max-height:600px){
  .map-controls{max-height:min(70%,calc(100dvh - 100px));overflow-y:auto;
    overscroll-behavior:contain;scrollbar-width:thin}
  .search-results{max-height:calc(100dvh - 140px) !important}
}
@media (pointer:coarse){
  .map-ctrl-btn,.search-btn{min-height:44px}
  .search-input{min-height:44px;box-sizing:border-box}
  .${BLOCK_CLASS} .neon-pin,.${BLOCK_CLASS} .neon-layout{min-height:44px}
}
/* ── THE CARD IS A DOCKED SHEET ON A PHONE ───────────────────────────────
   Measured on a verified iPhone-class device (393x852 at dpr 3,
   pointer:coarse, hover:none, 5 touch points, document.hidden false): the
   anchored card opened at y=426, 819px tall, so its bottom edge was 393px
   BELOW the screen and the end of it was unreachable at every scroll
   position. Its left edge sat at x=-89 at 390px wide. Anchoring is the wrong
   idea on a phone - a 340px box hung off a marker in a 393px viewport has
   nowhere to go - so on a coarse pointer or a narrow window the card docks
   to the bottom edge, full width, and nothing has to be dragged.
   No rule below reads technology: three buckets light no layer at all. */
html.gridatlas-sheet-open .maplibregl-popup.gridatlas-sheet{
  position:fixed !important;left:0 !important;right:0 !important;
  top:auto !important;bottom:0 !important;transform:none !important;
  width:100vw !important;max-width:100vw !important;
  margin:0 !important;padding:0 !important;z-index:400 !important}
.maplibregl-popup.gridatlas-sheet .maplibregl-popup-tip{display:none !important}
.maplibregl-popup.gridatlas-sheet .maplibregl-popup-content{
  max-height:var(--gridatlas-sheet-h,56dvh) !important;
  width:100% !important;max-width:100% !important;
  border-radius:12px 12px 0 0;box-sizing:border-box;
  border-top:1px solid #2f6f75;box-shadow:0 -8px 24px rgba(0,0,0,.55);
  padding-bottom:calc(8px + env(safe-area-inset-bottom,0px)) !important}
.maplibregl-popup.gridatlas-sheet.gridatlas-min .maplibregl-popup-content{
  max-height:none !important}
/* MapLibre's own hairline cross is 20x18 and now sits inside a full-width