GLOBALGRID2050 / EXPLORE CODE

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

Prove V8 Product Mirror and 2 more files

A JavaScript module in the atman folder of GridAtlas that draws mirror proof, using SHA-256. It normalises pixels (`normalisePixels`) and decodes png (`decodePng`).

591 lines of JavaScript from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 614 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 Live Release automation · gridatlas / atman/202608291430-verify-live-release.mjs lines 1–213
  2. V8 Product Parity render · gridatlas / atman/202608291758-v8-product-parity.mjs lines 1–160
  3. Prove V8 Product Mirror render · gridatlas / atman/202608291818-prove-v8-product-mirror.mjs lines 1–218

Verify Live Release

A JavaScript module in the atman folder of GridAtlas that reads Renewable Energy Planning Database (REPD) browser registry, using SHA-256. It sets hash (`setHash`) and parses args (`parseArgs`).

automationgridatlas / atman/202608291430-verify-live-release.mjs · lines 1–213 of 213 · version 2026-08-29 14:30 · Entry point · pattern setHash (shared by 4 files)

What it does
It loads REPD browser registry. Defines 7 functions or classes, including fail, invariant, digest, setHash, sha256. Uses libraries node:assert/strict, node:crypto, node:fs/promises, node:path, node:url. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
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.
Inputs & outputs
In: JSON file build-manifest.json; JSON file release-manifest.json; JSON file live-set.json; JSON file current-v3.json; JSON file repd_browser_registry_202608290716.json; JSON file release.json; JSON file browser-layer-registry.json; Parquet file layer_membership.parquet.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
Its name says it verifies live release. Defines `fail`, `invariant`, `digest` and 4 more.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · atman · JavaScript module
Uses
node:assert/strict, node:crypto, node:fs/promises, node:path, node:url
Used by
none found
Produces
fail, invariant, digest, setHash, sha256, filesUnder, parseArgs
Defines here
fail, invariant, digest, setHash, sha256, filesUnder, parseArgs
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/202608291430-verify-live-release.mjs:1-213 · blob 40aff29691a6e310ffc4c6ebd842f777d1591ca4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";

const RELEASE_ID = "202608291430-atlas-v9";
const ROOT_INDEX_SHA256 = "4d059a6963ee73378b21bf378a3590292bbced0bba6f3cacf4acd9c6bc695533";
const REPD_REGISTRY_SHA256 = "c8a5c59be878c52014a272eb0e4d09af06a0d301d10a8d6b5d0b116b5d1bb6bc";
const ROUTING_PROJECTS_SHA256 = "c06aedef176d2d38fd135806306a8ef81b4af9994c7be31e8bd760304149f862";
const RELEASE_FILES = [
  "assets/atlas-v9.css",
  "assets/atlas-v9.mjs",
  "assets/data-gridatlas-client.mjs",
  "assets/repd-routing-client.mjs",
  "build-manifest.json",
  "cartridges/202608290716-repd-address-flyto.mjs",
  "index.html",
  "release-manifest.json"
];

function fail(message) { throw new Error(message); }
function invariant(condition, message) { if (!condition) fail(message); }
function digest(bytes) { return createHash("sha256").update(bytes).digest("hex"); }
function setHash(values) { return digest(Buffer.from(JSON.stringify([...values].sort((left, right) => Number(left) - Number(right))) + "\n")); }

async function sha256(file) { return digest(await readFile(file)); }

async function filesUnder(directory, prefix = "") {
  const output = [];
  for (const entry of await readdir(directory, { withFileTypes: true })) {
    const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
    if (entry.isDirectory()) output.push(...await filesUnder(path.join(directory, entry.name), relative));
    else if (entry.isFile()) output.push(relative);
    else fail(`non-regular release entry: ${relative}`);
  }
  return output.sort();
}

function parseArgs(argv) {
  const args = { root: ".", releaseDirectory: null, routingProjects: null, dataRelease: null, allowUnsealed: false };
  for (let index = 2; index < argv.length; index += 1) {
    if (argv[index] === "--root") args.root = argv[++index];
    else if (argv[index] === "--release-directory") args.releaseDirectory = argv[++index];
    else if (argv[index] === "--routing-projects") args.routingProjects = argv[++index];
    else if (argv[index] === "--data-release") args.dataRelease = argv[++index];
    else if (argv[index] === "--allow-unsealed") args.allowUnsealed = true;
    else fail(`unknown argument: ${argv[index]}`);
  }
  invariant(args.routingProjects, "--routing-projects is required");
  return args;
}

const args = parseArgs(process.argv);
const root = path.resolve(args.root);
const releaseDirectory = args.releaseDirectory ? path.resolve(args.releaseDirectory) : path.join(root, RELEASE_ID);
const routingProjectsPath = path.resolve(args.routingProjects);
const clientPath = path.join(releaseDirectory, "assets/data-gridatlas-client.mjs");
const routingClientPath = path.join(releaseDirectory, "assets/repd-routing-client.mjs");
const cartridgePath = path.join(releaseDirectory, "cartridges/202608290716-repd-address-flyto.mjs");
const { buildLayerQuery, rowsToGeoJSON, validateDataClosure, validateReleaseManifest } = await import(pathToFileURL(clientPath));
const { decodeRoutingProjects, resolveRoutingRecord, REPD_ROUTING_CONTRACT } = await import(pathToFileURL(routingClientPath));
const { ATLAS_V9_REPD_ADDRESS_FLYTO_CONTRACT, parseAtlasQuery, rankRepdProjects } = await import(pathToFileURL(cartridgePath));

const manifest = JSON.parse(await readFile(path.join(releaseDirectory, "release-manifest.json"), "utf8"));
validateReleaseManifest(manifest, { sealed: !args.allowUnsealed });
assert.equal(manifest.source_parent_commit, "936a31f703d31bd975af22d7349708d68a143d56");
assert.equal(manifest.route_contract.identity_rule, "EXACT_REPD_REF_ONLY");
assert.equal(manifest.route_contract.query_coordinates_ignored, true);
assert.deepEqual(manifest.route_contract.browser_sentinels, ["17494", "13599", "12453", "2484", "12780", "2535", "13429"]);

assert.equal(await sha256(path.join(root, "index.html")), ROOT_INDEX_SHA256, "root last-green index changed");
const current = JSON.parse(await readFile(path.join(root, "state/live-set.json"), "utf8"));
const currentMirror = await readFile(path.join(root, "releases/current-v3.json"));
assert.deepEqual(current, JSON.parse(currentMirror), "current pointer mirrors differ");
assert.equal(current.current.release_id, "202608291239-atlas-v9", "verified predecessor pointer drift");
assert.equal(current.current.publication_commit, "1898184ccbf52ca836cf1482362fc5933baf3e8d", "verified predecessor release drift");

const releaseFiles = await filesUnder(releaseDirectory);
assert.deepEqual(releaseFiles, RELEASE_FILES, "timestamped release allowlist mismatch");
const buildManifest = JSON.parse(await readFile(path.join(releaseDirectory, "build-manifest.json"), "utf8"));
assert.equal(buildManifest.schema, "gridatlas.timestamped-live-build.v2");
assert.equal(buildManifest.release_id, RELEASE_ID);
assert.equal(buildManifest.source_commit, manifest.source_commit);
assert.equal(buildManifest.deterministic, true);
const declaredFiles = new Map(buildManifest.files.map(item => [item.path, item]));
assert.equal(declaredFiles.size, buildManifest.files.length, "duplicate build file receipt");
assert.deepEqual([...declaredFiles.keys()].sort(), releaseFiles.filter(item => item !== "build-manifest.json"), "build file closure mismatch");
for (const [relative, receipt] of declaredFiles) {
  const file = path.join(releaseDirectory, relative);
  assert.equal((await stat(file)).size, receipt.bytes, `build byte mismatch: ${relative}`);
  assert.equal(await sha256(file), receipt.sha256, `build hash mismatch: ${relative}`);
}

const html = await readFile(path.join(releaseDirectory, "index.html"), "utf8");
const app = await readFile(path.join(releaseDirectory, "assets/atlas-v9.mjs"), "utf8");
const routingClient = await readFile(routingClientPath, "utf8");
for (const token of ["202608291430 LIVE", "11,033 safe viable search records", "7,652 MAP / 28 NO MAP", "release-manifest.json"]) {
  assert(html.includes(token), `release index missing: ${token}`);
}
for (const token of ["resolveRequestedDeepLink", "loadRoutingDeepLinkFallback", "hasMappableGeometry", "__GRIDATLAS_REPD_ROUTE__", "__GRIDATLAS_RUNTIME__", "normal", "ROUTING_FAILED_CLOSED"]) {
  assert(app.includes(token), `runtime routing token missing: ${token}`);
}
assert(app.includes("records.filter(hasMappableGeometry).map"), "base-map geometry guard missing");
assert(app.includes("registry.records.filter(hasMappableGeometry)"), "normal search/feature registry guard missing");
assert(app.includes("record.latitude === 49.766807 && record.longitude === -7.55716"), "transformed false-origin guard missing");
assert(!app.includes('get("longitude")') && !app.includes('get("latitude")'), "query coordinates are consumed");
for (const token of ["rawLatitude !== null", "rawLongitude !== null", "geometryStatus === \"valid\"", "false zero-origin routing point", "resolveRoutingRecord"]) {
  assert(routingClient.includes(token), `routing decoder guard missing: ${token}`);
}

const normalRegistryPath = path.join(root, "data/repd_browser_registry_202608290716.json");
assert.equal(await sha256(normalRegistryPath), REPD_REGISTRY_SHA256, "normal registry identity drift");
const normalRegistry = JSON.parse(await readFile(normalRegistryPath, "utf8"));
assert.equal(normalRegistry.records.length, 11069, "normal registry row closure drift");
const normalByRef = new Map();
const safeNormalByRef = new Map();
const excludedFalseOrigin = new Set();
for (const record of normalRegistry.records) {
  const repdRef = String(record.repd_ref);
  assert(!normalByRef.has(repdRef), `duplicate normal repd_ref: ${repdRef}`);
  assert.equal(typeof record.latitude, "number", `normal latitude type drift: ${repdRef}`);
  assert.equal(typeof record.longitude, "number", `normal longitude type drift: ${repdRef}`);
  assert(Number.isFinite(record.latitude) && Number.isFinite(record.longitude), `normal non-finite point: ${repdRef}`);
  assert(!(record.latitude === 0 && record.longitude === 0), `normal false zero-origin point: ${repdRef}`);
  normalByRef.set(repdRef, record);
  if (record.latitude === 49.766807 && record.longitude === -7.55716) excludedFalseOrigin.add(repdRef);
  else safeNormalByRef.set(repdRef, record);
}
assert.equal(excludedFalseOrigin.size, 36);
assert.equal(setHash(excludedFalseOrigin), "acdee510ef7f29855ea07b376cdc1519835d498184c5d14ea2a8a06d756365d9");
assert.equal(safeNormalByRef.size, 11033);
assert.equal(setHash(safeNormalByRef.keys()), "fc8b3bedf4f39c2eaa534d45a30806053cc931fdf7ced4a703f7275e43d27b21");

const routingRaw = await readFile(routingProjectsPath);
assert.equal(routingRaw.length, 979338, "routing projects byte closure drift");
assert.equal(digest(routingRaw), ROUTING_PROJECTS_SHA256, "routing projects identity drift");
const decoded = decodeRoutingProjects(JSON.parse(routingRaw));
assert.equal(decoded.records.length, REPD_ROUTING_CONTRACT.projects);
assert.equal(decoded.mapIdentities, 7652);
assert.equal(decoded.noMapIdentities, 28);
const routingMapRefs = new Set(decoded.records.filter(record => record.selectable).map(record => record.repd_ref));
const routingNoMapRefs = new Set(decoded.records.filter(record => !record.selectable).map(record => record.repd_ref));
const fallbackRefs = new Set([...routingMapRefs].filter(repdRef => !safeNormalByRef.has(repdRef)));
const finalSelectable = new Set([...safeNormalByRef.keys(), ...fallbackRefs]);
assert.equal(fallbackRefs.size, 2419);
assert.equal(setHash(fallbackRefs), "5cbd8e6fc2f24f9fab897e9fb558c01e5886d0868db405f73260713ae3542a3b");
assert.equal(finalSelectable.size, 13452);
assert.equal(setHash(finalSelectable), "1ed30d2eef18b75d4b4064f971d2b1ea3fd41ef618fc585b3a3ff0723462ac5f");
assert.equal([...routingMapRefs].filter(repdRef => !finalSelectable.has(repdRef)).length, 0);
assert.equal([...routingNoMapRefs].filter(repdRef => finalSelectable.has(repdRef)).length, 0);
for (const repdRef of ["17494", "13599"]) {
  assert(safeNormalByRef.has(repdRef), `normal sentinel missing: ${repdRef}`);
  assert.equal(resolveRoutingRecord(decoded, repdRef).selectable, true, `routing overlap sentinel invalid: ${repdRef}`);
}
for (const repdRef of ["12453", "2484", "2535"]) {
  assert(!safeNormalByRef.has(repdRef), `fallback sentinel unexpectedly normal: ${repdRef}`);
  const result = resolveRoutingRecord(decoded, repdRef);
  assert.equal(result.selectable, true, `fallback sentinel is not selectable: ${repdRef}`);
  assert(!(result.record.longitude === 0 && result.record.latitude === 0));
}
const noMap = resolveRoutingRecord(decoded, "12780");
assert(!safeNormalByRef.has("12780"));
assert.equal(noMap.found, true);
assert.equal(noMap.selectable, false);
assert.equal(noMap.record.geometry_status, "invalid");
assert.equal(noMap.record.latitude, null);
assert.equal(noMap.record.longitude, null);
const transformedNoMap = resolveRoutingRecord(decoded, "13429");
assert(normalByRef.has("13429") && !safeNormalByRef.has("13429"));
assert.equal(transformedNoMap.found, true);
assert.equal(transformedNoMap.selectable, false);
assert.equal(transformedNoMap.record.geometry_status, "missing");
assert.equal(resolveRoutingRecord(decoded, "012780").found, false, "routing identity is not exact repd_ref");

const parsed = parseAtlasQuery("Anybody involved in the solar farm being built by Cranfield/Marston? Bedfordshire?");
const ranked = rankRepdProjects([...safeNormalByRef.values()], "MK430ZY", 5);
assert(parsed.constructionIntent && parsed.groups.length === 3, "normal search grammar drift");
assert.equal(ranked[0]?.record?.repd_ref, "16135", "normal search regression");
assert.equal(ATLAS_V9_REPD_ADDRESS_FLYTO_CONTRACT.payloadRequests, 0, "normal search performs hidden requests");

let dataClosure = null;
if (args.dataRelease) {
  const dataRoot = path.resolve(args.dataRelease);
  const dataRelease = JSON.parse(await readFile(path.join(dataRoot, "release.json"), "utf8"));
  const registry = JSON.parse(await readFile(path.join(dataRoot, "browser-layer-registry.json"), "utf8"));
  const layers = validateDataClosure(manifest, dataRelease, registry);
  const first = layers.find(layer => layer.id === "400");
  const query = buildLayerQuery(manifest, first, { west: -8, south: 49, east: 2, north: 61 });
  assert(query.includes("layer_membership.parquet") && query.includes("m.layer_id = '400'"));
  const geojson = rowsToGeoJSON([{ source_id: "grid_400kv", feature_index: 0, geometry_json: '{"type":"LineString","coordinates":[[0,0],[1,1]]}', properties_json: "{}", original_feature_sha256: "a".repeat(64), projected_feature_sha256: "b".repeat(64) }], first);
  assert.equal(geojson.features.length, 1);
  dataClosure = { layers: layers.length, features: dataRelease.candidate_closure.features, memberships: dataRelease.candidate_closure.layer_membership_rows };
}

const fileProofs = {};
for (const relative of releaseFiles) {
  const file = path.join(releaseDirectory, relative);
  fileProofs[relative] = { bytes: (await stat(file)).size, sha256: await sha256(file) };
}
console.log(JSON.stringify({
  schema: "gridatlas.atman.timestamped-routing-live-release.v1",
  classification: args.allowUnsealed ? "VERIFIED_UNSEALED_ROUTING_BUILD_INPUT" : "VERIFIED_LIVE_ROUTING_RELEASE_SOURCE",
  release_id: RELEASE_ID,
  release_files: fileProofs,
  normal_registry: { source_rows: 11069, selectable_rows: 11033, excluded_false_origin_rows: 36, role: "NORMAL_SEARCH_AND_BASE_MAP" },
  routing: { projects: 7680, map_identities: 7652, no_map_identities: 28 },
  sentinels: { normal: ["17494", "13599"], fallback_map: ["12453", "2484", "2535"], no_map: ["12780", "13429"] },
  data: dataClosure,
  startup_parquet_requests: 0,
  failures: []
}, null, 2));

V8 Product Parity

A JavaScript module in the atman folder of GridAtlas that compares snapshots (`compareSnapshots`).

rendergridatlas / atman/202608291758-v8-product-parity.mjs · lines 1–160 of 160 · version 2026-08-29 17:58 · Entry point · pattern requireCondition (shared by 3 files)

What it does
It draws its content. Defines 8 functions or classes, including requireCondition, ready, snapshot, clean, compareSnapshots. 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.
Inputs & outputs
In: JSON file 202608291758-v8-product-parity.json.
Downstream impact
Used directly by 1 file: Build V8 Product Mirror (gridatlas).
What it achieves
It compares snapshots (`compareSnapshots`) and is built from the require condition helper (`requireCondition`) and the clean step (`clean`). Defines `requireCondition`, `ready`, `snapshot` and 5 more.
Why it matters
Run by Build V8 Product Mirror.
Application
gridatlas · atman · JavaScript module
Uses
GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL), node:fs/promises, playwright
Used by
run by Build V8 Product Mirror (workflow run), mentioned in Standalone (comment link)
Produces
requireCondition, ready, snapshot, clean, compareSnapshots, sameJson, testBridge, toggle
Defines here
requireCondition, ready, snapshot, clean, compareSnapshots, sameJson, testBridge, toggle
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/202608291758-v8-product-parity.mjs:1-160 · blob 7219da8d8d83e1f492f4dffb308f94184cd92fe6 · 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/202608291758-atlas-v9/';
const oracleUrl = process.env.ORACLE_URL || 'https://globalgrid2050.com/repd_grid_atlasv8/';
const output = process.env.OUTPUT || 'work/202608291758-v8-product-parity.json';

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

const structuralSelectors = [
  '.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: 30000 });
  await page.waitForSelector('#scada-ui-container .key-item', { timeout: 30000 });
  await page.waitForSelector('#map canvas', { timeout: 30000 });
}

async function snapshot(page) {
  return page.evaluate(({ structuralSelectors, styleProps }) => {
    const clean = value => Math.round(Number(value) * 10) / 10;
    const boxes = {};
    const styles = {};
    for (const selector of structuralSelectors) {
      const el = document.querySelector(selector);
      if (!el) {
        boxes[selector] = null;
        styles[selector] = null;
        continue;
      }
      const box = el.getBoundingClientRect();
      boxes[selector] = { x: clean(box.x), y: clean(box.y), width: clean(box.width), height: clean(box.height) };
      const computed = getComputedStyle(el);
      styles[selector] = Object.fromEntries(styleProps.map(prop => [prop, computed.getPropertyValue(prop)]));
    }
    return {
      title: document.title,
      boxes,
      styles,
      buttons: [...document.querySelectorAll('.map-ctrl-btn')].map(el => ({ id: el.id, text: el.textContent.trim() })),
      groups: [...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,
      searchPlaceholder: document.querySelector('#search-input')?.getAttribute('placeholder') || '',
      brand: document.querySelector('.ventus-main')?.textContent.trim() || '',
      bodyClass: document.body.className
    };
  }, { structuralSelectors, styleProps });
}

function compareSnapshots(oracle, candidate, viewport) {
  const errors = [];
  const sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
  if (!sameJson(oracle.buttons, candidate.buttons)) errors.push(`${viewport}: map control contract differs`);
  if (!sameJson(oracle.groups, candidate.groups)) errors.push(`${viewport}: layer group contract differs`);
  if (oracle.checkboxes !== candidate.checkboxes) errors.push(`${viewport}: checkbox count ${candidate.checkboxes} != ${oracle.checkboxes}`);
  if (oracle.radios !== candidate.radios) errors.push(`${viewport}: basemap radio count ${candidate.radios} != ${oracle.radios}`);
  if (oracle.searchPlaceholder !== candidate.searchPlaceholder) errors.push(`${viewport}: search placeholder differs`);
  if (oracle.brand !== candidate.brand) errors.push(`${viewport}: brand differs`);
  for (const selector of structuralSelectors) {
    const a = oracle.boxes[selector];
    const b = candidate.boxes[selector];
    if ((a === null) !== (b === null)) {
      errors.push(`${viewport}: selector presence differs: ${selector}`);
      continue;
    }
    if (!a || !b) continue;
    for (const key of ['x', 'y', 'width', 'height']) {
      if (Math.abs(a[key] - b[key]) > 1.5) errors.push(`${viewport}: ${selector} ${key} ${b[key]} != ${a[key]}`);
    }
    for (const prop of styleProps) {
      if (oracle.styles[selector]?.[prop] !== candidate.styles[selector]?.[prop]) {
        errors.push(`${viewport}: ${selector} style ${prop} differs`);
      }
    }
  }
  return errors;
}

async function testBridge(page) {
  requireCondition(await page.evaluate(() => Boolean(window.__GRIDATLAS_V9_BRIDGE__)), 'V9 Parquet bridge missing');
  const toggle = async id => {
    const selector = `#scada-ui-container input[data-layer-id="${id}"]`;
    await page.locator(selector).check();
    await page.waitForFunction(layerId => {
      const text = document.querySelector(`#lbl-${layerId}`)?.textContent || '';
      return /\[(?:OK|\d+)/.test(text) && !text.includes('[FAIL]');
    }, id, { timeout: 60000 });
  };
  await toggle('400');
  await toggle('dc');
  await toggle('solar');
  const bridge = await page.evaluate(() => window.__GRIDATLAS_V9_BRIDGE__);
  requireCondition(bridge.intercepted >= 3, 'bridge did not intercept V8 data loads');
  requireCondition(Object.keys(bridge.loaded || {}).length >= 3, 'bridge did not hydrate sentinel sources');
  requireCondition((bridge.failures || []).length === 0, `bridge failures: ${JSON.stringify(bridge.failures)}`);

  await page.fill('#search-input', 'Beacon');
  await page.click('#search-btn');
  await page.waitForTimeout(250);
  requireCondition(await page.locator('#search-results').isVisible(), 'V8 project search results did not open');
  requireCondition(await page.locator('#search-results .search-result-item').count() > 0, 'V8 project search returned no Beacon result');

  for (const id of ['btn-export', 'btn-radius', 'btn-radius-area', 'btn-zonedraw', 'btn-status', 'btn-measure', 'btn-fullscreen']) {
    requireCondition(await page.locator(`#${id}`).count() === 1, `missing V8 control ${id}`);
  }
  return bridge;
}

const browser = await chromium.launch({ headless: true });
const proof = {
  schema: 'gridatlas.v8-product-parity-proof.v1',
  classification: 'REJECTED',
  oracle: oracleUrl,
  candidate: candidateUrl,
  viewports: {},
  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 });
    await Promise.all([
      oraclePage.goto(oracleUrl, { waitUntil: 'domcontentloaded', timeout: 60000 }),
      candidatePage.goto(candidateUrl, { waitUntil: 'domcontentloaded', timeout: 60000 })
    ]);
    await Promise.all([ready(oraclePage), ready(candidatePage)]);
    const [oracle, candidate] = await Promise.all([snapshot(oraclePage), snapshot(candidatePage)]);
    const errors = compareSnapshots(oracle, candidate, viewport.name);
    proof.viewports[viewport.name] = { oracle, candidate, errors };
    proof.errors.push(...errors);
    await oraclePage.close();
    if (viewport.name === 'desktop') proof.bridge = await testBridge(candidatePage);
    await candidatePage.close();
  }
  requireCondition(proof.errors.length === 0, proof.errors.join('\n'));
  proof.classification = 'VERIFIED_V8_PRODUCT_MIRROR_ON_V9_DATA_PLANE';
} finally {
  await browser.close();
  await fs.mkdir(new URL('.', `file://${process.cwd()}/${output}`).pathname, { recursive: true }).catch(() => {});
  await fs.writeFile(output, JSON.stringify(proof, null, 2) + '\n');
}

console.log(JSON.stringify({ classification: proof.classification, errors: proof.errors.length, bridgeSources: Object.keys(proof.bridge?.loaded || {}).length }));

Prove V8 Product Mirror

A JavaScript module in the atman folder of GridAtlas that draws mirror proof, using SHA-256. It normalises pixels (`normalisePixels`) and decodes png (`decodePng`).

rendergridatlas / atman/202608291818-prove-v8-product-mirror.mjs · lines 1–218 of 218 · version 2026-08-29 18:18 · Entry point · pattern requireCondition (shared by 3 files)

What it does
It draws mirror proof. Defines 17 functions or classes, including requireCondition, blob, sha256, bytes, byteProof. Uses libraries node:crypto, node:fs/promises, pngjs, playwright. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
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.
Inputs & outputs
In: JSON file 202608291818-v8-mirror-proof.json.
Downstream impact
Used directly by 1 file: Prove V8 Product Mirror (gridatlas).
What it achieves
Defines `requireCondition`, `blob`, `sha256` and 14 more.
Why it matters
Run by Prove V8 Product Mirror.
Application
gridatlas · atman · JavaScript module
Uses
node:crypto, node:fs/promises, pngjs, playwright
Used by
run by Prove V8 Product Mirror (workflow run), mentioned in Standalone (comment link)
Produces
requireCondition, blob, sha256, bytes, byteProof, ready, snapshot, round, compare, normalisePixels, shot, decodePng
Defines here
requireCondition, blob, sha256, bytes, byteProof, ready, snapshot, round, compare, normalisePixels, shot, decodePng, pixelProof, controlState, display, interactionProof, bridgeProof
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-prove-v8-product-mirror.mjs:1-218 · blob 4f5e2aabd6f3877bec7bb2b954a338b376a9ed70 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · 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 { PNG } from 'pngjs';
import { chromium } from 'playwright';

const oracleUrl = process.env.ORACLE_URL || 'http://127.0.0.1:4174/';
const mirrorUrl = process.env.MIRROR_URL || 'https://ventusltd.github.io/gridatlas/202608291758-atlas-v9/';
const output = process.env.OUTPUT || 'work/202608291818-v8-mirror-proof.json';
const expected = Object.freeze({
  index: '278c3f55d3b61af9d13417c99bfb558374131143',
  css: '29a2edb490407f489c29433d84e329b1038e0657',
  engine: '0a647c32c346770851704727bbf86fb7167e2596',
  bridge: '<script src="v9-parquet-fetch-bridge.js"></script>\n\n'
});
const selectors = [
  '.dashboard','.hud-header','.map-container','.scada-wrapper','.scada-brand','.status-legend','.disclaimer-box',
  '#scada-ui-container','.search-bar-wrapper','.map-controls','#radius-popup','#radius-area-popup',
  '#zonedraw-display','#measure-display','#polyzone-display','#fs-curtain','#fs-letterhead',
  '#btn-fullscreen','#btn-fullscreen-exit'
];
const styles = [
  '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'
];
const pixelRegions = [
  { selector: '.hud-header', masks: ['#clock','#date','#days'] },
  { selector: '.search-bar-wrapper', masks: [] },
  { selector: '.map-controls', masks: [] },
  { selector: '.scada-brand', masks: [] },
  { selector: '.status-legend', masks: [] },
  { selector: '.disclaimer-box', masks: [] }
];

const requireCondition = (ok, message) => { if (!ok) throw new Error(message); };
const blob = bytes => crypto.createHash('sha1').update(Buffer.from(`blob ${bytes.length}\0`)).update(bytes).digest('hex');
const sha256 = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
async function bytes(url) {
  const r = await fetch(url, { cache: 'no-store' });
  requireCondition(r.ok, `${url} HTTP ${r.status}`);
  return Buffer.from(await r.arrayBuffer());
}

async function byteProof() {
  const [oi,oc,oe,mi,mc,me] = await Promise.all([
    bytes(new URL('index.html', oracleUrl)), bytes(new URL('ventusv8.css', oracleUrl)),
    bytes(new URL('ventus-corev8engine.js', oracleUrl)), bytes(new URL('index.html', mirrorUrl)),
    bytes(new URL('ventusv8.css', mirrorUrl)), bytes(new URL('ventus-corev8engine.js', mirrorUrl))
  ]);
  requireCondition(blob(oi) === expected.index, 'V8 index blob mismatch');
  requireCondition(blob(oc) === expected.css, 'V8 CSS blob mismatch');
  requireCondition(blob(oe) === expected.engine, 'V8 engine blob mismatch');
  requireCondition(blob(mc) === expected.css, 'mirror CSS is not V8 byte-identical');
  requireCondition(blob(me) === expected.engine, 'mirror engine is not V8 byte-identical');
  const text = mi.toString('utf8');
  requireCondition(text.includes(expected.bridge), 'mirror bridge tag missing');
  const normalised = Buffer.from(text.replace(expected.bridge, ''), 'utf8');
  requireCondition(normalised.equals(oi) && blob(normalised) === expected.index, 'mirror HTML has an unapproved V8 delta');
  return { index_blob:expected.index, css_blob:expected.css, engine_blob:expected.engine,
    html_delta:'ONE_BRIDGE_SCRIPT_INSERTION_ONLY', css_byte_identical:true, engine_byte_identical:true };
}

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, styles }) => {
    const round = n => Math.round(Number(n)*10)/10;
    const boxes = {}, computed = {};
    for (const selector of selectors) {
      const el = document.querySelector(selector);
      if (!el) { boxes[selector]=null; computed[selector]=null; continue; }
      const b = el.getBoundingClientRect(), c = getComputedStyle(el);
      boxes[selector] = { x:round(b.x), y:round(b.y), width:round(b.width), height:round(b.height) };
      computed[selector] = Object.fromEntries(styles.map(p => [p,c.getPropertyValue(p)]));
    }
    return {
      boxes, computed,
      controls:[...document.querySelectorAll('.map-ctrl-btn')].map(el=>({id:el.id,text:el.textContent.trim()})),
      groups:[...document.querySelectorAll('#scada-ui-container .key-title')].map(el=>el.textContent.trim()),
      labels:[...document.querySelectorAll('#scada-ui-container span[data-base-label]')].map(el=>({id:el.id,base:el.getAttribute('data-base-label'),color:getComputedStyle(el).color})),
      checkboxes:document.querySelectorAll('#scada-ui-container input[type="checkbox"]').length,
      radios:document.querySelectorAll('#scada-ui-container input[type="radio"]').length,
      placeholder:document.querySelector('#search-input')?.getAttribute('placeholder')||'',
      brand:document.querySelector('.ventus-main')?.textContent.trim()||'',
      disclaimer:document.querySelector('.disclaimer-box')?.textContent.trim()||''
    };
  }, { selectors, styles });
}

function compare(a,b,viewport) {
  const errors=[], same=(x,y)=>JSON.stringify(x)===JSON.stringify(y);
  for (const [name,x,y] of [
    ['controls',a.controls,b.controls],['groups',a.groups,b.groups],['labels/order/colours',a.labels,b.labels]
  ]) if (!same(x,y)) errors.push(`${viewport}: ${name} differ`);
  if (a.checkboxes!==b.checkboxes) errors.push(`${viewport}: checkbox count differs`);
  if (a.radios!==b.radios) errors.push(`${viewport}: radio count differs`);
  if (a.placeholder!==b.placeholder) errors.push(`${viewport}: search placeholder differs`);
  if (a.brand!==b.brand) errors.push(`${viewport}: brand differs`);
  if (a.disclaimer!==b.disclaimer) errors.push(`${viewport}: disclaimer differs`);
  for (const selector of selectors) {
    const x=a.boxes[selector], y=b.boxes[selector];
    if ((x===null)!==(y===null)) { errors.push(`${viewport}: presence differs ${selector}`); continue; }
    if (!x||!y) continue;
    for (const k of ['x','y','width','height']) if (Math.abs(x[k]-y[k])>1) errors.push(`${viewport}: ${selector} ${k} differs`);
    for (const p of styles) if (a.computed[selector]?.[p]!==b.computed[selector]?.[p]) errors.push(`${viewport}: ${selector} ${p} differs`);
  }
  return errors;
}

async function normalisePixels(page) {
  await page.addStyleTag({ content:`
    *,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}
    #map{visibility:hidden!important}
  `});
  await page.evaluate(() => {
    document.querySelectorAll('input[type="checkbox"]').forEach(el=>el.checked=false);
    document.querySelectorAll('input[type="radio"][value="dark"]').forEach(el=>el.checked=true);
    const input=document.getElementById('search-input'); if(input){input.value='';input.blur();}
    const results=document.getElementById('search-results'); if(results){results.innerHTML='';results.style.display='none';}
    document.querySelectorAll('.map-ctrl-btn').forEach(el=>el.classList.remove('active'));
    for(const id of ['radius-popup','radius-area-popup','zonedraw-display','measure-display','polyzone-display']){
      const el=document.getElementById(id); if(el)el.style.display='none';
    }
  });
  await page.waitForTimeout(80);
}

async function shot(page, region) {
  return page.locator(region.selector).screenshot({
    animations:'disabled', mask:region.masks.map(s=>page.locator(s)), maskColor:'#000000'
  });
}

function decodePng(buffer) {
  const image = PNG.sync.read(buffer);
  return { width:image.width, height:image.height, rgba:Buffer.from(image.data) };
}

async function pixelProof(aPage,bPage,viewport) {
  await Promise.all([normalisePixels(aPage),normalisePixels(bPage)]);
  const regions={};
  for(const region of pixelRegions){
    const [aPng,bPng]=await Promise.all([shot(aPage,region),shot(bPage,region)]);
    const a=decodePng(aPng), b=decodePng(bPng);
    requireCondition(a.width===b.width && a.height===b.height,`${viewport}: decoded dimensions differ for ${region.selector}`);
    requireCondition(a.rgba.equals(b.rgba),`${viewport}: decoded RGBA differs for ${region.selector}`);
    regions[region.selector]={
      identical:true,
      width:a.width,
      height:a.height,
      rgba_sha256:sha256(a.rgba),
      mirror_rgba_sha256:sha256(b.rgba),
      png_encoding_sha256:sha256(aPng),
      mirror_png_encoding_sha256:sha256(bPng),
      masks:region.masks
    };
  }
  return { identical:true, comparison:'EXACT_DECODED_RGBA', volatile_map_pixels_excluded:true,
    live_clock_text_masked:true, async_scada_grid_excluded_from_bitmap_but_exact_dom_gated:true, regions };
}

async function controlState(page,id){
  return page.evaluate(controlId=>{
    const display=s=>{const el=document.querySelector(s);return el?getComputedStyle(el).display:null;};
    return {active:document.getElementById(controlId)?.classList.contains('active')||false,
      radius:display('#radius-popup'),radius_area:display('#radius-area-popup'),zone:display('#zonedraw-display'),measure:display('#measure-display'),
      map_container_class:document.getElementById('map-container')?.className||'',body_class:document.body.className};
  },id);
}
async function interactionProof(a,b){
  const states={};
  for(const id of ['btn-radius','btn-radius-area','btn-zonedraw','btn-status','btn-measure']){
    await Promise.all([a.click(`#${id}`),b.click(`#${id}`)]);
    const [x,y]=await Promise.all([controlState(a,id),controlState(b,id)]);
    requireCondition(JSON.stringify(x)===JSON.stringify(y),`interaction differs after ${id}`); states[id]=y;
    await Promise.all([a.click(`#${id}`),b.click(`#${id}`)]);
  }
  return states;
}
async function bridgeProof(page){
  for(const id of ['400','dc','solar']){
    await page.locator(`#scada-ui-container input[data-layer-id="${id}"]`).check();
    await page.waitForFunction(layerId=>{const t=document.querySelector(`#lbl-${layerId}`)?.textContent||'';return /\[(?:OK|\d+)/.test(t)&&!t.includes('[FAIL]');},id,{timeout:90000});
  }
  const b=await page.evaluate(()=>window.__GRIDATLAS_V9_BRIDGE__);
  requireCondition(b?.intercepted>=3,'V9 bridge did not intercept sentinel loads');
  requireCondition(Object.keys(b?.loaded||{}).length>=3,'V9 bridge did not hydrate sentinel sources');
  requireCondition((b?.failures||[]).length===0,`V9 bridge failures: ${JSON.stringify(b?.failures||[])}`);
  return b;
}

const proof={schema:'gridatlas.v8-public-product-mirror-proof.v7',classification:'REJECTED',oracle:oracleUrl,mirror:mirrorUrl,bytes:null,viewports:{},interactions:null,bridge:null,errors:[]};
const browser=await chromium.launch({headless:true});
try{
  proof.bytes=await byteProof();
  for(const viewport of [{name:'desktop',width:1440,height:900},{name:'mobile',width:390,height:844}]){
    const a=await browser.newPage({viewport}),b=await browser.newPage({viewport});
    try{
      await Promise.all([a.goto(oracleUrl,{waitUntil:'domcontentloaded',timeout:60000}),b.goto(mirrorUrl,{waitUntil:'domcontentloaded',timeout:60000})]);
      await Promise.all([ready(a),ready(b)]);
      const [as,bs]=await Promise.all([snapshot(a),snapshot(b)]),errors=compare(as,bs,viewport.name);
      requireCondition(errors.length===0,errors.join('\n'));
      proof.viewports[viewport.name]={structure_identical:true,pixels:await pixelProof(a,b,viewport.name)};
      if(viewport.name==='desktop'){proof.interactions=await interactionProof(a,b);proof.bridge=await bridgeProof(b);}
    }finally{await a.close();await b.close();}
  }
  proof.classification='VERIFIED_PUBLIC_V8_PRODUCT_MIRROR';
}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,bridge_sources:Object.keys(proof.bridge?.loaded||{}).length}));