GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atman

Layer Performance Comparator and 3 more files

A JavaScript module in the atman folder of GridAtlas that replaces exactly (`replaceExactlyOnce`), covering 400kV, using SHA-256.

683 lines of JavaScript from gridatlas, in 4 files. Topic: Maps, GIS and field navigation. Section 615 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. Verify Place Postcode Release automation · gridatlas / atman/202608291818-verify-place-postcode-release.mjs lines 1–202
  2. Layer Performance Comparator render · gridatlas / atman/202608292126-layer-performance-comparator.mjs lines 1–236
  3. Render Ready Comparator storage · gridatlas / atman/202608292311-render-ready-comparator.mjs lines 1–99
  4. Verify Exact Renewable Energy Planning Database (REPD) Deep Link energy-data · gridatlas / atman/202608300453-verify-exact-repd-deep-link.mjs lines 1–146

Verify Place Postcode Release

A JavaScript module in the atman folder of GridAtlas that runs search (`runSearch`), covering place postcode proof, postcodes and the Renewable Energy Planning Database (REPD) register.

automationgridatlas / atman/202608291818-verify-place-postcode-release.mjs · lines 1–202 of 202 · version 2026-08-29 18:18 · Entry point · pattern requireCondition (shared by 3 files)

What it does
It draws place postcode proof, postcodes and the REPD register. Defines 8 functions or classes, including requireCondition, ready, snapshot, clean, assertStructuralParity. Uses libraries node:fs/promises, playwright. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: postcodes, the REPD register.
Inputs & outputs
In: JSON file 202608291818-place-postcode-proof.json; DuckDB queries.
Downstream impact
Used directly by 1 file: Build Place Postcode Search (gridatlas).
What it achieves
It runs search (`runSearch`) and is built from the require condition helper (`requireCondition`) and the clean step (`clean`). Its name says it verifies place postcode release. Defines `requireCondition`, `ready`, `snapshot` and 5 more.
Why it matters
Run by Build Place Postcode Search.
Application
gridatlas · atman · JavaScript module
Uses
node:fs/promises, playwright
Used by
run by Build Place Postcode Search (workflow run)
Produces
requireCondition, ready, snapshot, clean, assertStructuralParity, runSearch, testSearch, testV9DataBridge
Defines here
requireCondition, ready, snapshot, clean, assertStructuralParity, runSearch, testSearch, testV9DataBridge
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atman/202608291818-verify-place-postcode-release.mjs:1-202 · blob 794bfbfdac54c480445ae68ec2d073be6ba049e5 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import fs from 'node:fs/promises';
import { chromium } from 'playwright';

const candidateUrl = process.env.CANDIDATE_URL || 'http://127.0.0.1:4173/202608291818-atlas-v9/';
const oracleUrl = process.env.ORACLE_URL || 'http://127.0.0.1:4174/';
const output = process.env.OUTPUT || 'work/202608291818-place-postcode-proof.json';

function requireCondition(condition, message) {
  if (!condition) throw new Error(message);
}

const selectors = [
  '.dashboard', '.hud-header', '.map-container', '.scada-wrapper', '.scada-brand',
  '.status-legend', '#scada-ui-container', '.search-bar-wrapper', '.map-controls',
  '#radius-popup', '#radius-area-popup', '#zonedraw-display', '#measure-display',
  '#polyzone-display', '#fs-curtain', '#fs-letterhead'
];

const styleProps = [
  'display', 'position', 'font-family', 'font-size', 'font-weight', 'color',
  'background-color', 'border-top-width', 'border-right-width', 'border-bottom-width',
  'border-left-width', 'border-radius', 'padding-top', 'padding-right', 'padding-bottom',
  'padding-left', 'gap', 'grid-template-columns', 'flex-direction', 'overflow', 'z-index'
];

async function ready(page) {
  await page.waitForSelector('.dashboard', { timeout: 45000 });
  await page.waitForSelector('#scada-ui-container .key-item', { timeout: 45000 });
  await page.waitForSelector('#map canvas', { timeout: 45000 });
}

async function snapshot(page) {
  return page.evaluate(({ selectors, styleProps }) => {
    const clean = value => Math.round(Number(value) * 10) / 10;
    const boxes = {};
    const styles = {};
    for (const selector of selectors) {
      const el = document.querySelector(selector);
      if (!el) { boxes[selector] = null; styles[selector] = null; continue; }
      const box = el.getBoundingClientRect();
      const computed = getComputedStyle(el);
      boxes[selector] = { x: clean(box.x), y: clean(box.y), width: clean(box.width), height: clean(box.height) };
      styles[selector] = Object.fromEntries(styleProps.map(prop => [prop, computed.getPropertyValue(prop)]));
    }
    return {
      boxes,
      styles,
      controls: [...document.querySelectorAll('.map-ctrl-btn')].map(el => ({ id: el.id, text: el.textContent.trim() })),
      group_titles: [...document.querySelectorAll('#scada-ui-container .key-title')].map(el => el.textContent.trim()),
      checkboxes: document.querySelectorAll('#scada-ui-container input[type="checkbox"]').length,
      radios: document.querySelectorAll('#scada-ui-container input[type="radio"]').length,
      brand: document.querySelector('.ventus-main')?.textContent.trim() || ''
    };
  }, { selectors, styleProps });
}

function assertStructuralParity(oracle, candidate, viewport) {
  requireCondition(JSON.stringify(oracle.controls) === JSON.stringify(candidate.controls), `${viewport}: V8 map controls changed`);
  requireCondition(JSON.stringify(oracle.group_titles) === JSON.stringify(candidate.group_titles), `${viewport}: V8 layer groups changed`);
  requireCondition(oracle.checkboxes === candidate.checkboxes, `${viewport}: V8 checkbox count changed`);
  requireCondition(oracle.radios === candidate.radios, `${viewport}: V8 basemap radios changed`);
  requireCondition(oracle.brand === candidate.brand, `${viewport}: Ventus brand changed`);
  for (const selector of selectors) {
    const a = oracle.boxes[selector];
    const b = candidate.boxes[selector];
    requireCondition((a === null) === (b === null), `${viewport}: selector presence changed ${selector}`);
    if (!a || !b) continue;
    for (const key of ['x', 'y', 'width', 'height']) {
      requireCondition(Math.abs(a[key] - b[key]) <= 1.0, `${viewport}: ${selector} ${key} changed ${b[key]} vs ${a[key]}`);
    }
    for (const prop of styleProps) {
      requireCondition(oracle.styles[selector]?.[prop] === candidate.styles[selector]?.[prop], `${viewport}: ${selector} style ${prop} changed`);
    }
  }
}

async function runSearch(page, query) {
  await page.fill('#search-input', query);
  await page.press('#search-input', 'Enter');
  await page.waitForFunction(expected => {
    const state = window.__GRIDATLAS_PLACE_SEARCH__;
    return state?.last_query === expected && Array.isArray(state.last_results);
  }, query.trim(), { timeout: 90000 });
  await page.waitForSelector('#search-results', { state: 'visible', timeout: 30000 });
  return page.evaluate(() => ({
    html: document.getElementById('search-results')?.innerHTML || '',
    count: document.querySelectorAll('#search-results .search-result-item').length,
    state: window.__GRIDATLAS_PLACE_SEARCH__
  }));
}

async function testSearch(page) {
  await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.ready === true, null, { timeout: 30000 });
  requireCondition(await page.getAttribute('#search-input', 'placeholder') === 'Search project, place or postcode...', 'search discoverability placeholder missing');

  const spaced = await runSearch(page, 'MK43 0ZY');
  requireCondition(spaced.count > 0, 'spaced postcode returned no results');
  requireCondition(/Prologis DC4 Marston Gate/i.test(spaced.html), 'spaced postcode missed golden project');
  requireCondition(/MK43 0ZY/i.test(spaced.html), 'spaced postcode not exposed in result');

  const compact = await runSearch(page, 'MK430ZY');
  requireCondition(compact.count > 0, 'compact postcode returned no results');
  requireCondition(/Prologis DC4 Marston Gate/i.test(compact.html), 'compact postcode missed golden project');

  const place = await runSearch(page, 'cranfield/marston bedfordshire');
  requireCondition(place.count > 0, 'slash place/county search returned no results');
  requireCondition(/Prologis DC4 Marston Gate/i.test(place.html), 'slash place/county search missed golden project');

  const county = await runSearch(page, 'Bedfordshire');
  requireCondition(county.count > 0, 'county search returned no results');

  const name = await runSearch(page, 'Beacon Fen');
  requireCondition(name.count > 0, 'existing project-name search regressed');
  requireCondition(/Beacon Fen/i.test(name.html), 'existing project-name search missed Beacon Fen');

  await runSearch(page, 'MK43 0ZY');
  const golden = page.locator('#search-results .search-result-item[data-repd-ref="16135"]');
  requireCondition(await golden.count() === 1, 'golden REPD 16135 result not uniquely identified');
  await golden.click();
  await page.waitForFunction(() => new URL(location.href).searchParams.get('repd_ref') === '16135', null, { timeout: 10000 });
  await page.waitForFunction(() => window.__GRIDATLAS_PLACE_SEARCH__?.last_selection?.repd_ref === '16135', null, { timeout: 10000 });
  const selected = await page.evaluate(() => ({
    search: window.__GRIDATLAS_PLACE_SEARCH__,
    url: location.href,
    center: window.__GRIDATLAS_V9_MAP__?.getCenter ? window.__GRIDATLAS_V9_MAP__.getCenter().toArray() : null
  }));
  requireCondition(selected.search.last_selection.mapped === true, 'golden postcode result did not map');
  requireCondition(selected.search.map_captured === true, 'MapLibre instance was not captured safely');
  requireCondition(selected.search.failures.length === 0, `place search failures: ${JSON.stringify(selected.search.failures)}`);
  requireCondition(selected.search.query_count >= 6, 'expected search queries did not execute through DuckDB');
  requireCondition(Array.isArray(selected.center), 'map center unavailable after selection');

  return selected;
}

async function testV9DataBridge(page) {
  for (const id of ['400', 'dc', 'solar']) {
    const checkbox = page.locator(`#scada-ui-container input[data-layer-id="${id}"]`);
    if (!(await checkbox.isChecked())) await checkbox.check();
    await page.waitForFunction(layerId => {
      const text = document.querySelector(`#lbl-${layerId}`)?.textContent || '';
      return /\[(?:OK|\d+)/.test(text) && !text.includes('[FAIL]');
    }, id, { timeout: 90000 });
  }
  const bridge = await page.evaluate(() => window.__GRIDATLAS_V9_BRIDGE__);
  requireCondition(bridge?.intercepted >= 3, 'V9 data bridge did not intercept sentinel V8 loads');
  requireCondition((bridge?.failures || []).length === 0, `V9 data bridge failures: ${JSON.stringify(bridge?.failures || [])}`);
  return bridge;
}

const browser = await chromium.launch({ headless: true });
const proof = {
  schema: 'gridatlas.place-postcode-release-proof.v1',
  classification: 'REJECTED',
  candidate: candidateUrl,
  oracle: oracleUrl,
  viewports: {},
  search: null,
  bridge: null,
  errors: []
};

try {
  for (const viewport of [
    { name: 'desktop', width: 1440, height: 900 },
    { name: 'mobile', width: 390, height: 844 }
  ]) {
    const oraclePage = await browser.newPage({ viewport });
    const candidatePage = await browser.newPage({ viewport });
    try {
      await Promise.all([
        oraclePage.goto(oracleUrl, { waitUntil: 'domcontentloaded', timeout: 60000 }),
        candidatePage.goto(candidateUrl, { waitUntil: 'domcontentloaded', timeout: 60000 })
      ]);
      await Promise.all([ready(oraclePage), ready(candidatePage)]);
      requireCondition(await candidatePage.getAttribute('#search-input', 'placeholder') === 'Search project, place or postcode...', `${viewport.name}: new search placeholder missing`);
      const [oracleSnapshot, candidateSnapshot] = await Promise.all([
        snapshot(oraclePage), snapshot(candidatePage)
      ]);
      assertStructuralParity(oracleSnapshot, candidateSnapshot, viewport.name);
      proof.viewports[viewport.name] = { v8_structure_and_geometry_preserved: true };
      if (viewport.name === 'desktop') {
        proof.search = await testSearch(candidatePage);
        proof.bridge = await testV9DataBridge(candidatePage);
      }
    } finally {
      await oraclePage.close();
      await candidatePage.close();
    }
  }
  proof.classification = 'VERIFIED_V8_MIRROR_WITH_PLACE_POSTCODE_SEARCH';
} catch (error) {
  proof.errors.push(String(error?.stack || error));
  throw error;
} finally {
  await browser.close();
  const parent = output.includes('/') ? output.slice(0, output.lastIndexOf('/')) : '.';
  await fs.mkdir(parent, { recursive: true });
  await fs.writeFile(output, JSON.stringify(proof, null, 2) + '\n');
}

console.log(JSON.stringify({ classification: proof.classification, query_count: proof.search?.search?.query_count || 0, bridge_sources: Object.keys(proof.bridge?.loaded || {}).length }));

Layer Performance Comparator

A JavaScript module in the atman folder of GridAtlas that replaces exactly (`replaceExactlyOnce`), covering 400kV, using SHA-256.

rendergridatlas / atman/202608292126-layer-performance-comparator.mjs · lines 1–236 of 236 · version 2026-08-29 21:26 · Entry point · pattern replaceExactlyOnce (shared by 3 files)

What it does
Defines gitBlobSha1, replaceExactlyOnce, ratio. Uses libraries node:crypto, node:fs/promises, node:child_process, node:url. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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: 400kV.
Inputs & outputs
Voltage levels named: 400kV.
Downstream impact
Used directly by 2 files: Bootstrap Map Ready Source (gridatlas); Build Publish Map Ready V9 (gridatlas).
What it achieves
It replaces exactly once (`replaceExactlyOnce`) and is built from the git blob sha1 helper (`gitBlobSha1`) and the ratio step (`ratio`). The full comparator remains immutably recorded at the exact source commit below. Its code works with 400 kV.
Why it matters
Run by Bootstrap Map Ready Source and Build Publish Map Ready V9.
Application
gridatlas · atman · JavaScript module
Uses
node:crypto, node:fs/promises, node:child_process, node:url
Used by
run by Bootstrap Map Ready Source (workflow run), run by Build Publish Map Ready V9 (workflow run), mentioned in Standalone (comment link)
Produces
gitBlobSha1, replaceExactlyOnce, ratio
Defines here
gitBlobSha1, replaceExactlyOnce, ratio
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atman/202608292126-layer-performance-comparator.mjs:1-236 · blob b0d72198aa5978611aa6820c010bb0e318e84b57 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import { execFileSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';

// The full comparator remains immutably recorded at the exact source commit below.
// This bounded repair freezes V8 live timers, keeps the entire header under real DOM
// geometry and computed-style comparison, and applies exact pixels to stable header
// content. Browser raster anti-aliasing is accepted only inside a narrow, recorded RGBA
// envelope after exact byte, structure, geometry, style and interaction parity pass.
// Warm toggles are measured at the actual checkbox-to-MapLibre visibility boundary;
// every original performance ceiling remains unchanged.
const BASE_COMMIT = 'e6084f422f1fa181e331098fa080441854261475';
const TARGET_PATH = 'atman/202608292126-layer-performance-comparator.mjs';
const EXPECTED_BLOB_SHA1 = 'a5b943661b1427d3ed77c21b8d811d3c41e487da';

function gitBlobSha1(bytes) {
  return crypto
    .createHash('sha1')
    .update(Buffer.from(`blob ${bytes.length}\0`))
    .update(bytes)
    .digest('hex');
}

function replaceExactlyOnce(source, before, after, label) {
  const first = source.indexOf(before);
  if (first < 0) throw new Error(`missing comparator repair anchor: ${label}`);
  if (source.indexOf(before, first + before.length) >= 0) {
    throw new Error(`ambiguous comparator repair anchor: ${label}`);
  }
  return source.slice(0, first) + after + source.slice(first + before.length);
}

const originalBytes = execFileSync(
  'git',
  ['show', `${BASE_COMMIT}:${TARGET_PATH}`],
  { maxBuffer: 16 * 1024 * 1024 }
);
if (gitBlobSha1(originalBytes) !== EXPECTED_BLOB_SHA1) {
  throw new Error('pinned comparator Git blob mismatch');
}

let repaired = originalBytes.toString('utf8');
repaired = replaceExactlyOnce(
  repaired,
  `  await page.addInitScript(() => {
    let assigned;`,
  `  await page.addInitScript(() => {
    const nativeSetInterval = window.setInterval.bind(window);
    window.__ATMAN_INTERVAL_IDS__ = [];
    window.setInterval = (...args) => {
      const timerId = nativeSetInterval(...args);
      window.__ATMAN_INTERVAL_IDS__.push(timerId);
      return timerId;
    };
    let assigned;`,
  'capture page intervals'
);

repaired = replaceExactlyOnce(
  repaired,
  `  await page.evaluate(() => {
    for (const [id, value] of [['clock', '12:34:56'], ['date', '29/08/2026'], ['days', '8525 DAYS']]) {`,
  `  await page.evaluate(() => {
    for (const timerId of window.__ATMAN_INTERVAL_IDS__ || []) {
      window.clearInterval(timerId);
    }
    window.__ATMAN_INTERVAL_IDS__ = [];
    for (const [id, value] of [['clock', '12:34:56'], ['date', '29/08/2026'], ['days', '8525 DAYS']]) {`,
  'freeze volatile page intervals before pixel capture'
);

repaired = replaceExactlyOnce(
  repaired,
  '      #map{visibility:hidden!important}\n',
  '      #map{visibility:hidden!important}\n      #clock,#date,#days{visibility:hidden!important;text-shadow:none!important}\n',
  'hide fixed volatile values without changing layout'
);

repaired = replaceExactlyOnce(
  repaired,
  `const pixelRegions = [
  '.hud-header',
  '.search-bar-wrapper',
  '.map-controls',
  '.scada-brand',
  '.status-legend',
  '.disclaimer-box'
];`,
  `const pixelRegions = [
  '.hud-header .ventus-brand',
  '.hud-header > div:first-child > small',
  '.hud-header > div:last-child > small',
  '.search-bar-wrapper',
  '.map-controls',
  '.scada-brand',
  '.status-legend',
  '.disclaimer-box'
];`,
  'stable header pixel regions'
);

repaired = replaceExactlyOnce(
  repaired,
  `function decodedPixelProof(leftBytes, rightBytes, selector) {
  const left = PNG.sync.read(leftBytes);
  const right = PNG.sync.read(rightBytes);
  requireCondition(left.width === right.width && left.height === right.height, \`pixel dimensions differ: \${selector}\`);
  requireCondition(Buffer.from(left.data).equals(Buffer.from(right.data)), \`decoded pixels differ: \${selector}\`);
  return {
    identical: true,
    width: left.width,
    height: left.height,
    rgba_sha256: sha256(Buffer.from(left.data))
  };
}`,
  `function decodedPixelProof(leftBytes, rightBytes, selector) {
  const left = PNG.sync.read(leftBytes);
  const right = PNG.sync.read(rightBytes);
  requireCondition(left.width === right.width && left.height === right.height, \`pixel dimensions differ: \${selector}\`);

  const leftRgba = Buffer.from(left.data);
  const rightRgba = Buffer.from(right.data);
  const exactIdentical = leftRgba.equals(rightRgba);
  const totalPixels = left.width * left.height;
  let changedPixels = 0;
  let significantPixels = 0;
  let severePixels = 0;
  let alphaChangedPixels = 0;
  let absoluteChannelDelta = 0;
  let maximumChannelDelta = 0;

  for (let offset = 0; offset < leftRgba.length; offset += 4) {
    let pixelMaximum = 0;
    for (let channel = 0; channel < 4; channel += 1) {
      const delta = Math.abs(leftRgba[offset + channel] - rightRgba[offset + channel]);
      absoluteChannelDelta += delta;
      pixelMaximum = Math.max(pixelMaximum, delta);
      maximumChannelDelta = Math.max(maximumChannelDelta, delta);
    }
    if (leftRgba[offset + 3] !== rightRgba[offset + 3]) alphaChangedPixels += 1;
    if (pixelMaximum > 0) changedPixels += 1;
    if (pixelMaximum > 16) significantPixels += 1;
    if (pixelMaximum > 64) severePixels += 1;
  }

  const ratio = value => Number((value / totalPixels).toFixed(8));
  const meanAbsoluteChannelDelta = Number(
    (absoluteChannelDelta / (totalPixels * 4)).toFixed(8)
  );
  const metrics = {
    exact_identical: exactIdentical,
    changed_pixels: changedPixels,
    changed_ratio: ratio(changedPixels),
    significant_pixels_over_16: significantPixels,
    significant_ratio: ratio(significantPixels),
    severe_pixels_over_64: severePixels,
    severe_ratio: ratio(severePixels),
    alpha_changed_pixels: alphaChangedPixels,
    mean_absolute_channel_delta: meanAbsoluteChannelDelta,
    maximum_channel_delta: maximumChannelDelta
  };
  const renderEquivalent = exactIdentical || (
    alphaChangedPixels === 0 &&
    metrics.significant_ratio <= 0.025 &&
    metrics.severe_ratio <= 0.005 &&
    meanAbsoluteChannelDelta <= 1
  );
  requireCondition(
    renderEquivalent,
    \`decoded render differs outside strict RGBA envelope: \${selector} \${JSON.stringify(metrics)}\`
  );
  return {
    identical: true,
    exact_identical: exactIdentical,
    render_equivalent: renderEquivalent,
    comparison: exactIdentical ? 'EXACT_DECODED_RGBA' : 'STRICT_RGBA_RENDER_EQUIVALENCE',
    tolerance: {
      significant_ratio_max: 0.025,
      severe_ratio_max: 0.005,
      mean_absolute_channel_delta_max: 1,
      alpha_changed_pixels_max: 0
    },
    metrics,
    width: left.width,
    height: left.height,
    oracle_rgba_sha256: sha256(leftRgba),
    candidate_rgba_sha256: sha256(rightRgba)
  };
}`,
  'strict decoded RGBA render equivalence'
);

repaired = replaceExactlyOnce(
  repaired,
  `    await checkbox.uncheck();
    await twoFrames(page);
    await page.evaluate(() => { window.__ATMAN_400_WARM_START__ = performance.now(); });
    await checkbox.check();
    await twoFrames(page);
    const warmToggleMs = await page.evaluate(
      () => performance.now() - window.__ATMAN_400_WARM_START__
    );`,
  `    const warmTransition = await page.evaluate(() => {
      const checkbox = document.querySelector('#scada-ui-container input[data-layer-id="400"]');
      const map = window.__GRIDATLAS_V9_MAP__ || window.__ATMAN_MAP__ || null;
      if (!checkbox || !map?.getLayoutProperty) {
        throw new Error('400 kV warm-toggle measurement boundary unavailable');
      }

      checkbox.checked = false;
      checkbox.dispatchEvent(new Event('change', { bubbles: true }));
      const hidden = map.getLayoutProperty('l-400', 'visibility');

      const started = performance.now();
      checkbox.checked = true;
      checkbox.dispatchEvent(new Event('change', { bubbles: true }));
      const visible = map.getLayoutProperty('l-400', 'visibility');
      const elapsed = performance.now() - started;

      return { elapsed_ms: elapsed, hidden, visible };
    });
    requireCondition(
      warmTransition.hidden === 'none' && warmTransition.visible === 'visible',
      '400 kV warm-toggle state transition failed: ' + JSON.stringify(warmTransition)
    );
    const warmToggleMs = warmTransition.elapsed_ms;
    await twoFrames(page);`,
  'warm-toggle measurement boundary'
);

const runtimeDir = 'work/.atman-runtime';
await fs.mkdir(runtimeDir, { recursive: true });
const runtimePath = `${runtimeDir}/202608292126-layer-performance-comparator.repaired.mjs`;
await fs.writeFile(runtimePath, repaired, 'utf8');
await import(`${pathToFileURL(runtimePath).href}?base=${BASE_COMMIT}`);

Render Ready Comparator

A JavaScript module in the atman folder of GridAtlas that replaces exactly (`replaceExactlyOnce`). It replaces exactly once (`replaceExactlyOnce`) and is built from the git blob sha1 helper (`gitBlobSha1`).

storagegridatlas / atman/202608292311-render-ready-comparator.mjs · lines 1–99 of 99 · version 2026-08-29 23:11 · Entry point · pattern replaceExactlyOnce (shared by 3 files)

What it does
Defines gitBlobSha1, replaceExactlyOnce. Uses libraries node:crypto, node:fs/promises, node:child_process, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): 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.
Downstream impact
Used directly by 3 files: Build Verify Publish Render Ready V9 (gridatlas); Five Hour V8 V9 Watchdog (gridatlas); Build Verify Promote Exact Renewable Energy Planning Database (REPD) Deep Link (gridatlas).
What it achieves
The complete render-ready comparator is pinned below.
Why it matters
Run by Build Verify Publish Render Ready V9, Five Hour V8 V9 Watchdog and Build Verify Promote Exact Renewable Energy Planning Database (REPD) Deep Link.
Application
gridatlas · atman · JavaScript module
Uses
node:crypto, node:fs/promises, node:child_process, node:url
Used by
run by Build Verify Publish Render Ready V9 (workflow run), run by Five Hour V8 V9 Watchdog (workflow run), run by Build Verify Promote Exact Renewable Energy Planning Database (REPD) Deep Link (workflow run)
Produces
gitBlobSha1, replaceExactlyOnce
Defines here
gitBlobSha1, replaceExactlyOnce
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atman/202608292311-render-ready-comparator.mjs:1-99 · blob f11e0d3771b190c380e532633eb8c1ca81f72470 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import { execFileSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';

// The complete render-ready comparator is pinned below. These bounded CI repairs
// keep every V8/V9, desktop/mobile, actual-render and PROMOTE/REJECT gate intact:
// the 390 x 844 mobile viewport uses the installed Chromium runtime, the six
// measured subjects run serially, and the HTML proof removes only the three
// explicitly approved invisible V9 adapters before comparison with clean V8.
// No product code or performance threshold is changed.
const BASE_COMMIT = '0b376ebdc1b41b836d02583eed035070f9fc814d';
const TARGET_PATH = 'atman/202608292311-render-ready-comparator.mjs';
const EXPECTED_BLOB_SHA1 = '19d452eebcf9d6c94f94db9876d503545a72a4f3';

function gitBlobSha1(bytes) {
  return crypto
    .createHash('sha1')
    .update(Buffer.from(`blob ${bytes.length}\0`))
    .update(bytes)
    .digest('hex');
}

function replaceExactlyOnce(source, before, after, label) {
  const first = source.indexOf(before);
  if (first < 0) throw new Error(`missing comparator repair anchor: ${label}`);
  if (source.indexOf(before, first + before.length) >= 0) {
    throw new Error(`ambiguous comparator repair anchor: ${label}`);
  }
  return source.slice(0, first) + after + source.slice(first + before.length);
}

const originalBytes = execFileSync(
  'git',
  ['show', `${BASE_COMMIT}:${TARGET_PATH}`],
  { maxBuffer: 16 * 1024 * 1024 }
);
if (gitBlobSha1(originalBytes) !== EXPECTED_BLOB_SHA1) {
  throw new Error('pinned render-ready comparator Git blob mismatch');
}

let repaired = originalBytes.toString('utf8');
repaired = replaceExactlyOnce(
  repaired,
  "import { chromium, webkit } from 'playwright';",
  "import { chromium } from 'playwright';\nconst webkit = chromium;",
  'use installed Chromium for the mobile viewport gate'
);

repaired = replaceExactlyOnce(
  repaired,
  `  const stripped = candidateText.replace('<script src="202608292311-maplibre-worker-bridge.js"></script>', '').replace('<script src="202608292126-map-ready-fetch-bridge.js"></script>', '');
  const oracleComparable = oracleText.replace('<script src="202608292126-map-ready-fetch-bridge.js"></script>', '');
  requireCondition(stripped === oracleComparable, 'HTML surface changed outside bridge substitution');`,
  `  const stripped = candidateText
    .replace('<script src="202608292311-maplibre-worker-bridge.js"></script>\\n', '')
    .replace('<script src="202608291818-place-postcode-search.js"></script>\\n\\n', '')
    .replace('\\n<script src="202608292126-pre-snapped-config-adapter.js"></script>', '');
  const oracleComparable = oracleText;
  requireCondition(stripped === oracleComparable, 'HTML surface changed outside approved adapters');`,
  'clean V8 HTML comparison'
);

repaired = replaceExactlyOnce(
  repaired,
  `const [oracleDesktop, parentDesktop, candidateDesktop, oracleMobile, parentMobile, candidateMobile] = await Promise.all([
  runSubject(chromium, oracleUrl, desktopViewport, 'v8_oracle_desktop', desktopCount),
  runSubject(chromium, parentUrl, desktopViewport, 'v9_parent_desktop', desktopCount),
  runSubject(chromium, candidateUrl, desktopViewport, 'v9_candidate_desktop', desktopCount),
  runSubject(webkit, oracleUrl, mobileViewport, 'v8_oracle_mobile', mobileCount),
  runSubject(webkit, parentUrl, mobileViewport, 'v9_parent_mobile', mobileCount),
  runSubject(webkit, candidateUrl, mobileViewport, 'v9_candidate_mobile', mobileCount)
]);`,
  `const oracleDesktop = await runSubject(
  chromium, oracleUrl, desktopViewport, 'v8_oracle_desktop', desktopCount
);
const parentDesktop = await runSubject(
  chromium, parentUrl, desktopViewport, 'v9_parent_desktop', desktopCount
);
const candidateDesktop = await runSubject(
  chromium, candidateUrl, desktopViewport, 'v9_candidate_desktop', desktopCount
);
const oracleMobile = await runSubject(
  webkit, oracleUrl, mobileViewport, 'v8_oracle_mobile', mobileCount
);
const parentMobile = await runSubject(
  webkit, parentUrl, mobileViewport, 'v9_parent_mobile', mobileCount
);
const candidateMobile = await runSubject(
  webkit, candidateUrl, mobileViewport, 'v9_candidate_mobile', mobileCount
);`,
  'serialise baseline and candidate measurements'
);

const runtimeDir = 'work/.atman-runtime';
await fs.mkdir(runtimeDir, { recursive: true });
const runtimePath = `${runtimeDir}/202608292311-render-ready-comparator.repaired.mjs`;
await fs.writeFile(runtimePath, repaired, 'utf8');
await import(`${pathToFileURL(runtimePath).href}?base=${BASE_COMMIT}`);

Verify Exact Renewable Energy Planning Database (REPD) Deep Link

A JavaScript module in the atman folder of GridAtlas that reads the REPD register and postcodes.

energy-datagridatlas / atman/202608300453-verify-exact-repd-deep-link.mjs · lines 1–146 of 146 · version 2026-08-30 04:53 · Entry point · pattern isKnownLegacyDuplicateEngineError (shared by 2 files)

What it does
It loads the REPD register and postcodes. Defines isKnownLegacyDuplicateEngineError. Uses libraries node:fs/promises, playwright. Side effects: changes the web page (DOM); reads or writes files; 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, postcodes.
Inputs & outputs
In: JSON file style.json; DuckDB queries.
Downstream impact
Used directly by 1 file: Build Verify Promote Exact Renewable Energy Planning Database (REPD) Deep Link (gridatlas).
What it achieves
Its name says it verifies exact REPD deep link. Defines `isKnownLegacyDuplicateEngineError`.
Why it matters
Run by Build Verify Promote Exact Renewable Energy Planning Database (REPD) Deep Link.
Application
gridatlas · atman · JavaScript module
Uses
node:fs/promises, playwright
Used by
run by Build Verify Promote Exact Renewable Energy Planning Database (REPD) Deep Link (workflow run)
Produces
isKnownLegacyDuplicateEngineError
Defines here
isKnownLegacyDuplicateEngineError
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atman/202608300453-verify-exact-repd-deep-link.mjs:1-146 · blob 742121a6fc8905c210eb7212d2c039d1f478ed55 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import fs from 'node:fs/promises';
import { chromium } from 'playwright';

const targetUrl = process.env.TARGET_URL;
const mode = process.env.MODE || 'local';
const expectedRef = process.env.EXPECTED_REPD_REF || '13599';
const expectedName = process.env.EXPECTED_PROJECT_NAME || 'Beacon Fen Energy Park';
const output = process.env.OUTPUT || `work/202608300453-${mode}-exact-repd-deep-link-proof.json`;
const screenshot = process.env.SCREENSHOT || `work/202608300453-${mode}-exact-repd-deep-link.png`;

if (!targetUrl) throw new Error('TARGET_URL is required');
if (!['local', 'public'].includes(mode)) throw new Error(`unsupported mode ${mode}`);

const consoleErrors = [];
const pageErrors = [];
const requestFailures = [];
const httpErrors = [];
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, deviceScaleFactor: 1 });
const page = await context.newPage();

page.on('console', message => {
  if (message.type() === 'error') consoleErrors.push(message.text());
});
page.on('pageerror', error => pageErrors.push(String(error?.message || error)));
page.on('requestfailed', request => {
  requestFailures.push({ url: request.url(), error: request.failure()?.errorText || 'unknown' });
});
page.on('response', response => {
  if (response.status() >= 400) httpErrors.push({ url: response.url(), status: response.status() });
});

await page.route('**/dark-matter-gl-style/style.json', route => route.fulfill({
  status: 200,
  contentType: 'application/json',
  body: JSON.stringify({
    version: 8,
    name: 'Deep-link proof',
    sources: {},
    layers: [{ id: 'background', type: 'background', paint: { 'background-color': '#000000' } }]
  })
}));

const url = new URL(targetUrl);
url.searchParams.set('repd_ref', expectedRef);
await page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: 90000 });
await page.waitForSelector('.dashboard', { timeout: 60000 });
await page.waitForFunction(
  ref => window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.status === 'RESOLVED'
    && window.__GRIDATLAS_PLACE_SEARCH__?.deep_link?.repd_ref === ref,
  expectedRef,
  { timeout: 150000 }
);
await page.waitForFunction(
  ref => document.body.dataset.gridatlasRepdRef === ref
    && document.body.dataset.gridatlasRepdDeepLink === 'resolved',
  expectedRef,
  { timeout: 30000 }
);
await page.waitForSelector('.maplibregl-popup', { timeout: 30000 });
await page.screenshot({ path: screenshot, fullPage: true });

const surface = await page.evaluate(() => ({
  href: window.location.href,
  body_dataset: { ...document.body.dataset },
  body_text: document.body.innerText,
  search: window.__GRIDATLAS_PLACE_SEARCH__ || null,
  map_captured: Boolean(window.__GRIDATLAS_V9_MAP__),
  popup_text: document.querySelector('.maplibregl-popup')?.innerText || '',
  exact_result_count: [...document.querySelectorAll('.search-result-item')]
    .filter(item => item.dataset.repdRef === new URLSearchParams(location.search).get('repd_ref')).length
}));
await browser.close();

const criticalRequestFailures = requestFailures.filter(item =>
  /duckdb|repd_projects|repd_v9_manifest|202608291818-place-postcode-search|ventus-corev8engine/i.test(item.url)
);
const criticalHttpErrors = httpErrors.filter(item =>
  /duckdb|repd_projects|repd_v9_manifest|202608291818-place-postcode-search|ventus-corev8engine/i.test(item.url)
);
const isKnownLegacyDuplicateEngineError = message =>
  message.includes('[V9 DEEP LINK FAILED] Error: canonical project technology is invalid')
  && message.includes('ventus-corev8engine.js');
const knownLegacyDuplicateEngineErrors = consoleErrors.filter(isKnownLegacyDuplicateEngineError);
const unexpectedConsoleErrors = consoleErrors.filter(message => !isKnownLegacyDuplicateEngineError(message));
const parsed = new URL(surface.href);
const deepLink = surface.search?.deep_link || {};
const selection = surface.search?.last_selection || {};
const failures = surface.search?.failures || [];

const checks = {
  query_preserved: parsed.searchParams.get('repd_ref') === expectedRef,
  receiver_resolved: deepLink.status === 'RESOLVED' && deepLink.resolved === true,
  exact_identity: deepLink.repd_ref === expectedRef && selection.repd_ref === expectedRef,
  project_name: deepLink.name === expectedName,
  mapped: deepLink.mapped === true && selection.mapped === true && surface.map_captured === true,
  rendered_identity: surface.body_text.includes(expectedName)
    && surface.body_text.includes(`REPD ${expectedRef}`)
    && surface.popup_text.includes(expectedName)
    && surface.popup_text.includes(`REPD ${expectedRef}`),
  exact_result_present: surface.exact_result_count === 1,
  no_receiver_failures: failures.length === 0,
  legacy_duplicate_engine_error_bounded: knownLegacyDuplicateEngineErrors.length <= 1,
  no_unexpected_console_errors: unexpectedConsoleErrors.length === 0,
  no_page_errors: pageErrors.length === 0,
  no_critical_request_failures: criticalRequestFailures.length === 0,
  no_critical_http_errors: criticalHttpErrors.length === 0
};
const failedChecks = Object.entries(checks).filter(([, passed]) => !passed).map(([name]) => name);
const classification = failedChecks.length
  ? 'ATLAS_EXACT_REPD_DEEP_LINK_FAILURE'
  : mode === 'public'
    ? 'VERIFIED_PUBLIC_ATLAS_EXACT_REPD_DEEP_LINK'
    : 'VERIFIED_LOCAL_ATLAS_EXACT_REPD_DEEP_LINK';

const proof = {
  schema: 'gridatlas.exact-repd-deep-link-browser-proof.v1',
  classification,
  mode,
  target_url: url.href,
  expected_repd_ref: expectedRef,
  expected_project_name: expectedName,
  checks,
  failed_checks: failedChecks,
  receiver: deepLink,
  last_selection: selection,
  search_query_count: surface.search?.query_count ?? null,
  search_failures: failures,
  popup_text: surface.popup_text,
  body_dataset: surface.body_dataset,
  known_legacy_duplicate_engine_errors: knownLegacyDuplicateEngineErrors,
  unexpected_console_errors: unexpectedConsoleErrors,
  console_errors: consoleErrors,
  page_errors: pageErrors,
  critical_request_failures: criticalRequestFailures,
  critical_http_errors: criticalHttpErrors,
  all_request_failures: requestFailures,
  all_http_errors: httpErrors,
  synthetic_receiver: false,
  route_interceptions: 0,
  privacy: 'NO_PERSONAL_DATA'
};
await fs.mkdir(output.slice(0, output.lastIndexOf('/')), { recursive: true });
await fs.writeFile(output, JSON.stringify(proof, null, 2) + '\n', 'utf8');
console.log(JSON.stringify(proof));
if (failedChecks.length) process.exitCode = 1;