GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / uk_renewables_pipeline/202609051156/tests

Browser Smoke V9 6 1 and 3 more files

A JavaScript module in the tests folder of GlobalGrid2050 that tests the Renewable Energy Planning Database (REPD) register, using SHA-256.

697 lines of JavaScript and Python from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 923 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. Browser Smoke V9 5 1 test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_5_1.mjs lines 1–253
  2. Browser Smoke V9 6 1 test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_6_1.mjs lines 1–317
  3. Browser Smoke V9 6 2 test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_6_2.mjs lines 1–93
  4. Check Legacy Integrity V9 test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/check_legacy_integrity_v9.py lines 1–34

Browser Smoke V9 5 1

A JavaScript module in the tests folder of GlobalGrid2050 that tests the Renewable Energy Planning Database (REPD) register.

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_5_1.mjs · lines 1–253 of 253 · version 2026-09-05 11:56 · pattern assertContained (shared by 5 files)

What it does
It tests the REPD register. Defines preparePage, layoutSnapshot, assertContained. Uses libraries node:assert/strict, node:fs/promises, node:module, 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 (path word 'renewables'): 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.
Inputs & outputs
In: JSON file build_manifest.json.
Downstream impact
Used directly by 1 file: Run V9 5 1 (globalgrid2050).
What it achieves
It prepares page (`preparePage`) and is built from the layout snapshot helper (`layoutSnapshot`) and the assert contained helper (`assertContained`). Defines `preparePage`, `layoutSnapshot` and `assertContained`. Its code works with 400 MW. It reads `data/v9.1/build_manifest.json`.
Why it matters
Checked by Run V9 5 1.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · JavaScript module
Uses
node:assert/strict, node:fs/promises, node:module, playwright
Used by
run by Run V9 5 1 (script call)
Produces
preparePage, layoutSnapshot, assertContained
Defines here
preparePage, layoutSnapshot, assertContained
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_5_1.mjs:1-253 · blob a5e728439036ca4bdf670086975d647ad5ea81be · 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 assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";

const require = createRequire(new URL("../package.json", import.meta.url));
const { chromium } = require("playwright");
const baseUrl = process.env.V9_BASE_URL || "http://127.0.0.1:8765/uk_renewables_pipeline/v9.5.1/";

async function preparePage(browser, { chartStub = true } = {}) {
  const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
  const page = await context.newPage();
  if (chartStub) {
    await page.addInitScript(() => {
      window.Chart = class ChartStub {
        constructor(_canvas, config) { this.data = config.data; }
        update() {}
      };
    });
  }
  await page.route("https://cdn.jsdelivr.net/**", (route) => (
    chartStub
      ? route.fulfill({ status: 200, contentType: "application/javascript", body: "" })
      : route.abort()
  ));
  return { context, page };
}

async function layoutSnapshot(page) {
  return page.evaluate(() => {
    const selectors = [".main", ".header", ".status", ".newspaper", ".tablewrap"];
    const bounds = Object.fromEntries(selectors.map((selector) => {
      const rect = document.querySelector(selector).getBoundingClientRect();
      return [selector, { left: rect.left, right: rect.right }];
    }));
    return {
      bodyDisplay: getComputedStyle(document.body).display,
      gaugeColumns: getComputedStyle(document.querySelector(".gauges")).gridTemplateColumns.split(" ").length,
      storyColumns: getComputedStyle(document.querySelector(".stories")).gridTemplateColumns.split(" ").length,
      headerDirection: getComputedStyle(document.querySelector(".header")).flexDirection,
      statusWhiteSpace: getComputedStyle(document.querySelector(".status")).whiteSpace,
      searchWidth: Math.round(document.querySelector("#search").getBoundingClientRect().width),
      clientWidth: document.documentElement.clientWidth,
      scrollWidth: document.documentElement.scrollWidth,
      bounds,
    };
  });
}

function assertContained(layout, width, label) {
  assert.ok(layout.scrollWidth <= layout.clientWidth, `${label} document overflow: ${layout.scrollWidth}px > ${layout.clientWidth}px`);
  for (const [selector, bounds] of Object.entries(layout.bounds)) {
    assert.ok(bounds.left >= -0.5, `${label} ${selector} crosses left edge`);
    assert.ok(bounds.right <= width + 0.5, `${label} ${selector} crosses right edge`);
  }
}

const browser = await chromium.launch({ headless: true });
try {
  const { context, page } = await preparePage(browser);
  const errors = [];
  page.on("pageerror", (error) => errors.push(error.message));
  await page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 60000 });
  await page.waitForFunction(() => document.querySelectorAll("#stories .story").length === 133, null, { timeout: 30000 });
  await page.waitForFunction(() => document.querySelector("#v1")?.textContent === "356,474");

  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => page.locator(selector).textContent())), ["356,474", "7,680", "4,100"]);
  assert.equal(await page.locator("#resultsMeta").textContent(), "7,680 of 7,680 records · 356,474 MW · largest 4,100 MW");
  assert.equal(await page.locator("thead th").count(), 11);
  assert.deepEqual(await page.locator("thead th").evaluateAll((headers) => headers.map((header) => header.textContent.trim().replace(/\s+/g, " "))), [
    "SITE NAME", "COUNTY", "OPERATOR", "TECHNOLOGY", "OFFICIAL REPD STATUS", "OFFICIAL CAPACITY",
    "REPD REF", "GLOBALGRID REF", "REPD UPDATED ↕", "NEWS SIGNAL", "ACTIONS",
  ]);
  assert.equal(await page.locator("#resultsMeta").getAttribute("data-filtered-count"), "7680");
  assert.equal(await page.locator("#releaseMeta").textContent(), "V9.5.1 interface · V9.1 canonical data spine · all 7,680 qualifying records loaded");
  assert.match(await page.locator("#newsMeta").textContent(), /45 relevant \/ 133 headlines · 125 V9\.4 baseline retained/);

  const firstIdentity = await page.locator("#tbody tr").first().evaluate((row) => ({
    repd: row.querySelector(".repd-ref")?.textContent,
    globalgrid: row.querySelector(".globalgrid-ref")?.textContent,
    updated: row.querySelector(".repd-updated")?.textContent,
  }));
  assert.ok(/^\d+$/.test(firstIdentity.repd));
  assert.equal(firstIdentity.globalgrid, `GG2050-REPD-${firstIdentity.repd}`);
  assert.match(firstIdentity.updated, /^(?:\d{2}\/\d{2}\/\d{4}|not supplied by REPD)$/);

  assert.equal(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort"), "none");
  assert.equal(await page.locator("#updatedSortIndicator").textContent(), "↕");
  assert.equal(await page.locator("#sortProjects").inputValue(), "capacity_desc");

  await page.locator("#sortUpdated").click();
  assert.equal(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort"), "descending");
  assert.equal(await page.locator("#updatedSortIndicator").textContent(), "▼");
  assert.equal(await page.locator("#sortProjects").inputValue(), "updated_desc");
  const newestDates = await page.locator("#tbody tr").evaluateAll((rows) => rows.slice(0, 50).map((row) => row.dataset.repdUpdated));
  assert.ok(newestDates.every((value, index) => index === 0 || value <= newestDates[index - 1]));
  assert.match(page.url(), /[?&]sort=updated_desc(?:&|$)/);

  await page.locator("#sortUpdated").click();
  assert.equal(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort"), "ascending");
  assert.equal(await page.locator("#updatedSortIndicator").textContent(), "▲");
  assert.equal(await page.locator("#sortProjects").inputValue(), "updated_asc");
  const oldestDates = await page.locator("#tbody tr").evaluateAll((rows) => rows.slice(0, 50).map((row) => row.dataset.repdUpdated));
  assert.ok(oldestDates.every((value, index) => index === 0 || value >= oldestDates[index - 1]));
  assert.match(page.url(), /[?&]sort=updated_asc(?:&|$)/);

  await page.locator("#sortUpdated").click();
  assert.equal(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort"), "descending");
  assert.equal(await page.locator("#sortProjects").inputValue(), "updated_desc");

  await page.locator("#clearFilters").click();
  assert.equal(await page.locator("#sortProjects").inputValue(), "capacity_desc");
  assert.equal(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort"), "none");
  assert.equal(await page.locator("#updatedSortIndicator").textContent(), "↕");

  for (const width of [1440, 1200, 1101]) {
    await page.setViewportSize({ width, height: 1000 });
    const desktop = await layoutSnapshot(page);
    assert.equal(desktop.bodyDisplay, "flex", `${width}px desktop body layout`);
    assert.equal(desktop.gaugeColumns, 3, `${width}px desktop gauge columns`);
    assert.equal(desktop.headerDirection, "row", `${width}px desktop header direction`);
    assert.equal(desktop.statusWhiteSpace, "nowrap", `${width}px desktop status wrapping`);
    assertContained(desktop, width, `${width}px desktop`);
  }

  for (const width of [769, 800, 900, 920, 921, 1000, 1100]) {
    await page.setViewportSize({ width, height: 900 });
    const intermediate = await layoutSnapshot(page);
    assert.equal(intermediate.bodyDisplay, "flex", `${width}px intermediate body layout`);
    assert.equal(intermediate.gaugeColumns, 3, `${width}px intermediate gauge columns`);
    assert.equal(intermediate.headerDirection, "column", `${width}px intermediate header direction`);
    assert.equal(intermediate.statusWhiteSpace, "normal", `${width}px intermediate status wrapping`);
    assertContained(intermediate, width, `${width}px intermediate`);
  }

  for (const width of [390, 430, 440, 768]) {
    await page.setViewportSize({ width, height: 844 });
    const mobile = await layoutSnapshot(page);
    assert.equal(mobile.bodyDisplay, "block", `${width}px mobile body layout`);
    assert.equal(mobile.gaugeColumns, 1, `${width}px mobile gauge columns`);
    assert.equal(mobile.storyColumns, 1, `${width}px mobile story columns`);
    assert.equal(mobile.headerDirection, "column", `${width}px mobile header direction`);
    assert.equal(mobile.statusWhiteSpace, "normal", `${width}px mobile status wrapping`);
    assert.ok(mobile.searchWidth >= width - 50, `${width}px mobile search width`);
    assertContained(mobile, width, `${width}px mobile`);
  }

  await page.setViewportSize({ width: 1440, height: 1000 });
  await page.locator('[data-technology="wind_offshore"]').click();
  await page.waitForFunction(() => document.querySelector("#v1")?.textContent === "80,535");
  assert.equal(await page.locator("#tbody tr").count(), 109);
  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => page.locator(selector).textContent())), ["80,535", "109", "4,100"]);
  assert.equal(await page.locator("#resultsMeta").textContent(), "109 of 7,680 records · 80,535 MW · largest 4,100 MW");

  await page.locator("#clearFilters").click();
  await page.locator("#search").fill("GG2050-REPD-10087 Brecks");
  assert.equal(await page.locator("#tbody tr").count(), 1);
  assert.notEqual(await page.locator("#tbody .signal").textContent(), "—");
  assert.match(await page.locator("#tbody .signal-note").textContent(), /canonical PRIMARY_MATCH/);

  await page.locator("#search").fill("");
  await page.locator("#search").fill("GG2050-REPD-9873 Berwick");
  assert.equal(await page.locator("#tbody tr").count(), 1);
  const atlas = new URL(await page.locator("#tbody .atlaslink").getAttribute("href"));
  assert.equal(atlas.searchParams.get("repd_ref"), "9873");
  assert.equal(atlas.searchParams.get("technology"), "wind_offshore");

  await page.locator("#tbody .project-record summary").click();
  assert.equal(await page.locator("#tbody .project-record").getAttribute("open"), "");
  assert.match(await page.locator("#tbody .record-grid").textContent(), /PLANNING AUTHORITY/);

  await page.locator("#tbody .copy-id").click();
  await page.waitForFunction(() => document.querySelector("#tbody .copy-id")?.textContent === "COPIED");
  assert.equal(await page.locator("#tbody .copy-id").textContent(), "COPIED");

  const missingRef = await page.evaluate(async () => {
    const manifest = await fetch("data/v9.1/build_manifest.json").then((response) => response.json());
    for (const partition of manifest.project_partitions) {
      const payload = await fetch(partition.path).then((response) => response.json());
      const missing = payload.projects.find((project) => project.geometry_status !== "valid");
      if (missing) return missing.repd_ref;
    }
    return "";
  });
  assert.ok(missingRef);
  await page.locator("#search").fill(missingRef);
  assert.equal(await page.locator("#tbody tr").count(), 1);
  assert.equal(await page.locator("#tbody .action-disabled").textContent(), "NO MAP");
  assert.equal(await page.locator("#tbody .atlaslink").count(), 0);

  await page.locator('[data-news="RELEVANT"]').click();
  const relevantCount = await page.locator("#stories .story").count();
  assert.equal(relevantCount, 45);
  await page.locator("#newsSearch").fill("Beacon Fen");
  assert.equal(await page.locator("#stories .story").count(), 1);
  assert.match(await page.locator("#stories .story").textContent(), /Beacon Fen Energy Park development consent decision announced/);
  assert.match(await page.locator("#stories .story").textContent(), /400 MW/);
  assert.match(await page.locator("#stories .story").textContent(), /REPD 13599/);
  await page.locator("#newsSearch").fill("");
  await page.locator('[data-news="ALL"]').click();
  assert.equal(await page.locator("#stories .story").count(), 133);

  await page.locator("#search").fill("GG2050-REPD-13599 Beacon Fen");
  assert.equal(await page.locator("#tbody tr").count(), 1);
  assert.notEqual(await page.locator("#tbody .signal").textContent(), "—");
  assert.match(await page.locator("#tbody .signal-note").textContent(), /canonical PRIMARY_MATCH 91%/);
  await page.locator("#search").fill("GG2050-REPD-13600 Beacon Fen");
  assert.equal(await page.locator("#tbody tr").count(), 1);
  assert.equal(await page.locator("#tbody .signal").textContent(), "—");

  await page.locator("#search").fill("definitely-no-such-repd-project-v9-5-1");
  assert.equal(await page.locator("#tbody tr").count(), 0);
  const downloadPromise = page.waitForEvent("download");
  await page.locator("#exportInline").click();
  const download = await downloadPromise;
  assert.match(download.suggestedFilename(), /^globalgrid2050_uk_renewables_pipeline_v9_5_1_\d{4}-\d{2}-\d{2}\.csv$/);
  const csv = await readFile(await download.path(), "utf8");
  assert.equal(csv.trimEnd().split(/\r?\n/).length, 1);
  assert.match(csv, /Site Name/);

  assert.deepEqual(errors, []);
  await context.close();

  const newsFailure = await preparePage(browser);
  await newsFailure.page.route("**/dist/major_project_news_v9_5_1.json*", (route) => route.abort());
  await newsFailure.page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await newsFailure.page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await newsFailure.page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 60000 });
  await newsFailure.page.waitForFunction(() => document.querySelector("#newsMeta").textContent === "newspaper unavailable");
  await newsFailure.page.waitForFunction(() => document.querySelector("#v1")?.textContent === "356,474");
  await newsFailure.context.close();

  const projectFailure = await preparePage(browser);
  await projectFailure.page.route("**/contracts/release.v9.5.1.json*", (route) => route.abort());
  await projectFailure.page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await projectFailure.page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await projectFailure.page.waitForFunction(() => document.querySelectorAll("#stories .story").length > 0, null, { timeout: 30000 });
  await projectFailure.page.waitForFunction(() => document.querySelector("#tbody").textContent.includes("V9.5.1 has failed closed."));
  await projectFailure.context.close();

  const chartFailure = await preparePage(browser, { chartStub: false });
  await chartFailure.page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await chartFailure.page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await chartFailure.page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 60000 });
  await chartFailure.page.waitForFunction(() => document.querySelector("#v1")?.textContent === "356,474");
  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => chartFailure.page.locator(selector).textContent())), ["356,474", "7,680", "4,100"]);
  await chartFailure.context.close();

  console.log("V9.5.1 browser smoke: PASS (133 ALL, 45 RELEVANT, Beacon Fen REPD 13599, date sort, CSV and Atlas)");
} finally {
  await browser.close();
}

Browser Smoke V9 6 1

A JavaScript module in the tests folder of GlobalGrid2050 that tests the Renewable Energy Planning Database (REPD) register, using SHA-256.

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_6_1.mjs · lines 1–317 of 317 · version 2026-09-05 11:56 · pattern assertContained (shared by 5 files)

What it does
It tests the REPD register. Defines preparePage, layoutSnapshot, renderedHash, assertContained. Uses libraries node:assert/strict, node:fs/promises, node:module, 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 (path word 'renewables'): 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.
Inputs & outputs
In: JSON file build_manifest.json.
Downstream impact
Used directly by 1 file: Run V9 6 1 (globalgrid2050).
What it achieves
It prepares page (`preparePage`) and is built from the layout snapshot helper (`layoutSnapshot`) and the rendered hash helper (`renderedHash`). Defines `preparePage`, `layoutSnapshot`, `renderedHash` and 1 more. Its code works with 400 MW. It reads `data/v9.1/build_manifest.json`.
Why it matters
Checked by Run V9 6 1.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · JavaScript module
Uses
node:assert/strict, node:fs/promises, node:module, playwright
Used by
run by Run V9 6 1 (script call), mentioned in Standalone (comment link)
Produces
preparePage, layoutSnapshot, renderedHash, assertContained
Defines here
preparePage, layoutSnapshot, renderedHash, assertContained
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_6_1.mjs:1-317 · blob 22f271fa341a23bb3fcb443cc30b95fc52552a0c · 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 assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";

const require = createRequire(new URL("../package.json", import.meta.url));
const { chromium } = require("playwright");
const baseUrl = process.env.V9_BASE_URL || "http://127.0.0.1:8765/uk_renewables_pipeline/v9.6.1/";
const parentUrl = new URL("../v9.5.1/", baseUrl).href;

async function preparePage(browser, { chartStub = true } = {}) {
  const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
  const page = await context.newPage();
  if (chartStub) {
    await page.addInitScript(() => {
      window.Chart = class ChartStub {
        constructor(_canvas, config) { this.data = config.data; }
        update() {}
      };
    });
  }
  await page.route("https://cdn.jsdelivr.net/**", (route) => (
    chartStub
      ? route.fulfill({ status: 200, contentType: "application/javascript", body: "" })
      : route.abort()
  ));
  return { context, page };
}

async function layoutSnapshot(page) {
  return page.evaluate(() => {
    const selectors = [".main", ".header", ".status", ".newspaper", ".tablewrap"];
    const wrap = document.querySelector(".tablewrap");
    const table = wrap.querySelector("table");
    const firstRow = document.querySelector("#tbody tr");
    const bounds = Object.fromEntries(selectors.map((selector) => {
      const rect = document.querySelector(selector).getBoundingClientRect();
      return [selector, { left: rect.left, right: rect.right }];
    }));
    return {
      bodyDisplay: getComputedStyle(document.body).display,
      gaugeColumns: getComputedStyle(document.querySelector(".gauges")).gridTemplateColumns.split(" ").length,
      storyColumns: getComputedStyle(document.querySelector(".stories")).gridTemplateColumns.split(" ").length,
      headerDirection: getComputedStyle(document.querySelector(".header")).flexDirection,
      statusWhiteSpace: getComputedStyle(document.querySelector(".status")).whiteSpace,
      searchWidth: Math.round(document.querySelector("#search").getBoundingClientRect().width),
      clientWidth: document.documentElement.clientWidth,
      scrollWidth: document.documentElement.scrollWidth,
      tableDisplay: getComputedStyle(table).display,
      headDisplay: getComputedStyle(table.tHead).display,
      rowDisplay: getComputedStyle(firstRow).display,
      tableMinWidth: getComputedStyle(table).minWidth,
      tableScrollWidth: table.scrollWidth,
      wrapClientWidth: wrap.clientWidth,
      wrapOverflowX: getComputedStyle(wrap).overflowX,
      headerCellDisplays: [...table.tHead.rows[0].cells].map((cell) => getComputedStyle(cell).display),
      firstRowCellDisplays: [...firstRow.cells].map((cell) => getComputedStyle(cell).display),
      bounds,
    };
  });
}

async function renderedHash(page, selector) {
  return page.locator(selector).evaluate(async (element) => {
    const bytes = new TextEncoder().encode(element.innerHTML);
    const digest = await crypto.subtle.digest("SHA-256", bytes);
    return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
  });
}

function assertContained(layout, width, label) {
  assert.ok(layout.scrollWidth <= layout.clientWidth, `${label} document overflow: ${layout.scrollWidth}px > ${layout.clientWidth}px`);
  for (const [selector, bounds] of Object.entries(layout.bounds)) {
    assert.ok(bounds.left >= -0.5, `${label} ${selector} crosses left edge`);
    assert.ok(bounds.right <= width + 0.5, `${label} ${selector} crosses right edge`);
  }
}

const browser = await chromium.launch({ headless: true });
try {
  const { context, page } = await preparePage(browser);
  const errors = [];
  page.on("pageerror", (error) => errors.push(error.message));
  await page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 60000 });
  await page.waitForFunction(() => document.querySelectorAll("#stories .story").length === 133, null, { timeout: 30000 });
  await page.waitForFunction(() => document.querySelector("#v1")?.textContent === "356,474");

  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => page.locator(selector).textContent())), ["356,474", "7,680", "4,100"]);
  assert.equal(await page.locator("#resultsMeta").textContent(), "7,680 of 7,680 records · 356,474 MW · largest 4,100 MW");
  assert.equal(await page.locator("thead th").count(), 11);
  assert.deepEqual(await page.locator("thead th").evaluateAll((headers) => headers.map((header) => header.textContent.trim().replace(/\s+/g, " "))), [
    "SITE NAME", "COUNTY", "OPERATOR", "TECHNOLOGY", "OFFICIAL REPD STATUS", "OFFICIAL CAPACITY",
    "REPD REF", "GLOBALGRID REF", "REPD UPDATED ↕", "NEWS SIGNAL", "ACTIONS",
  ]);
  assert.equal(await page.locator("#resultsMeta").getAttribute("data-filtered-count"), "7680");
  assert.equal(await page.locator("#minCapacity").count(), 0);
  assert.equal(await page.locator("#maxCapacity").count(), 0);
  assert.equal(await page.locator("#releaseMeta").textContent(), "V9.5.1 interface · V9.1 canonical data spine · all 7,680 qualifying records loaded");
  assert.match(await page.locator("#newsMeta").textContent(), /45 relevant \/ 133 headlines · 125 V9\.4 baseline retained/);

  const firstIdentity = await page.locator("#tbody tr").first().evaluate((row) => ({
    repd: row.querySelector(".repd-ref")?.textContent,
    globalgrid: row.querySelector(".globalgrid-ref")?.textContent,
    updated: row.querySelector(".repd-updated")?.textContent,
  }));
  assert.ok(/^\d+$/.test(firstIdentity.repd));
  assert.equal(firstIdentity.globalgrid, `GG2050-REPD-${firstIdentity.repd}`);
  assert.match(firstIdentity.updated, /^(?:\d{2}\/\d{2}\/\d{4}|not supplied by REPD)$/);

  assert.equal(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort"), "none");
  assert.equal(await page.locator("#updatedSortIndicator").textContent(), "↕");
  assert.equal(await page.locator("#sortProjects").inputValue(), "capacity_desc");

  await page.locator("#sortUpdated").click();
  assert.equal(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort"), "descending");
  assert.equal(await page.locator("#updatedSortIndicator").textContent(), "▼");
  assert.equal(await page.locator("#sortProjects").inputValue(), "updated_desc");
  const newestDates = await page.locator("#tbody tr").evaluateAll((rows) => rows.slice(0, 50).map((row) => row.dataset.repdUpdated));
  assert.ok(newestDates.every((value, index) => index === 0 || value <= newestDates[index - 1]));
  assert.match(page.url(), /[?&]sort=updated_desc(?:&|$)/);

  await page.locator("#sortUpdated").click();
  assert.equal(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort"), "ascending");
  assert.equal(await page.locator("#updatedSortIndicator").textContent(), "▲");
  assert.equal(await page.locator("#sortProjects").inputValue(), "updated_asc");
  const oldestDates = await page.locator("#tbody tr").evaluateAll((rows) => rows.slice(0, 50).map((row) => row.dataset.repdUpdated));
  assert.ok(oldestDates.every((value, index) => index === 0 || value >= oldestDates[index - 1]));
  assert.match(page.url(), /[?&]sort=updated_asc(?:&|$)/);

  await page.locator("#sortUpdated").click();
  assert.equal(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort"), "descending");
  assert.equal(await page.locator("#sortProjects").inputValue(), "updated_desc");

  await page.locator("#clearFilters").click();
  assert.equal(await page.locator("#sortProjects").inputValue(), "capacity_desc");
  assert.equal(await page.locator("#repdUpdatedHeader").getAttribute("aria-sort"), "none");
  assert.equal(await page.locator("#updatedSortIndicator").textContent(), "↕");

  for (const width of [1440, 1200, 1101]) {
    await page.setViewportSize({ width, height: 1000 });
    const desktop = await layoutSnapshot(page);
    assert.equal(desktop.bodyDisplay, "flex", `${width}px desktop body layout`);
    assert.equal(desktop.gaugeColumns, 3, `${width}px desktop gauge columns`);
    assert.equal(desktop.headerDirection, "row", `${width}px desktop header direction`);
    assert.equal(desktop.statusWhiteSpace, "nowrap", `${width}px desktop status wrapping`);
    assertContained(desktop, width, `${width}px desktop`);
  }

  for (const width of [769, 800, 900, 920, 921, 1000, 1100]) {
    await page.setViewportSize({ width, height: 900 });
    const intermediate = await layoutSnapshot(page);
    assert.equal(intermediate.bodyDisplay, "flex", `${width}px intermediate body layout`);
    assert.equal(intermediate.gaugeColumns, 3, `${width}px intermediate gauge columns`);
    assert.equal(intermediate.headerDirection, "column", `${width}px intermediate header direction`);
    assert.equal(intermediate.statusWhiteSpace, "normal", `${width}px intermediate status wrapping`);
    assertContained(intermediate, width, `${width}px intermediate`);
  }

  for (const width of [390, 430, 440, 768]) {
    await page.setViewportSize({ width, height: 844 });
    const mobile = await layoutSnapshot(page);
    assert.equal(mobile.bodyDisplay, "block", `${width}px mobile body layout`);
    assert.equal(mobile.gaugeColumns, 1, `${width}px mobile gauge columns`);
    assert.equal(mobile.storyColumns, 1, `${width}px mobile story columns`);
    assert.equal(mobile.headerDirection, "column", `${width}px mobile header direction`);
    assert.equal(mobile.statusWhiteSpace, "normal", `${width}px mobile status wrapping`);
    assert.ok(mobile.searchWidth >= width - 50, `${width}px mobile search width`);
    assert.equal(mobile.tableDisplay, "table", `${width}px native table`);
    assert.equal(mobile.headDisplay, "table-header-group", `${width}px native table head`);
    assert.equal(mobile.rowDisplay, "table-row", `${width}px native project row`);
    assert.equal(mobile.tableMinWidth, "1280px", `${width}px inherited V9.5.1 table minimum`);
    assert.equal(mobile.wrapOverflowX, "auto", `${width}px project wrapper overflow`);
    assert.equal(mobile.headerCellDisplays.length, 11, `${width}px complete project headers`);
    assert.equal(mobile.firstRowCellDisplays.length, 11, `${width}px complete project row`);
    assert.ok(mobile.headerCellDisplays.every((display) => display === "table-cell"), `${width}px visible project headers`);
    assert.ok(mobile.firstRowCellDisplays.every((display) => display === "table-cell"), `${width}px visible project cells`);
    assert.ok(mobile.tableScrollWidth > mobile.wrapClientWidth, `${width}px projects are horizontally scrollable`);
    assertContained(mobile, width, `${width}px mobile`);
    const scrolled = await page.locator(".tablewrap").evaluate((wrap) => {
      wrap.scrollLeft = wrap.scrollWidth;
      return wrap.scrollLeft;
    });
    assert.ok(scrolled > 0, `${width}px project table accepts a horizontal swipe`);
  }

  const parentPage = await context.newPage();
  await parentPage.addInitScript(() => {
    window.Chart = class ChartStub {
      constructor(_canvas, config) { this.data = config.data; }
      update() {}
    };
  });
  await parentPage.route("https://cdn.jsdelivr.net/**", (route) =>
    route.fulfill({ status: 200, contentType: "application/javascript", body: "" }));
  await parentPage.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await parentPage.goto(parentUrl, { waitUntil: "domcontentloaded" });
  await parentPage.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 60000 });
  await parentPage.waitForFunction(() => document.querySelectorAll("#stories .story").length === 133, null, { timeout: 30000 });
  assert.equal(await renderedHash(page, "#tbody"), await renderedHash(parentPage, "#tbody"), "project rendering differs from V9.5.1");
  assert.equal(await renderedHash(page, "#stories"), await renderedHash(parentPage, "#stories"), "newspaper rendering differs from V9.5.1");
  for (const width of [769, 800, 900, 920, 921, 1000, 1100, 1101, 1200, 1440]) {
    await page.setViewportSize({ width, height: 900 });
    await parentPage.setViewportSize({ width, height: 900 });
    const targetLayout = await layoutSnapshot(page);
    const parentLayout = await layoutSnapshot(parentPage);
    for (const key of ["bodyDisplay", "gaugeColumns", "storyColumns", "headerDirection", "statusWhiteSpace", "searchWidth", "clientWidth", "scrollWidth", "tableDisplay", "headDisplay", "rowDisplay", "tableMinWidth", "tableScrollWidth", "wrapClientWidth", "wrapOverflowX"]) {
      assert.deepEqual(targetLayout[key], parentLayout[key], `${width}px desktop parity: ${key}`);
    }
  }
  await parentPage.close();

  await page.setViewportSize({ width: 1440, height: 1000 });
  await page.locator('[data-technology="wind_offshore"]').click();
  await page.waitForFunction(() => document.querySelector("#v1")?.textContent === "80,535");
  assert.equal(await page.locator("#tbody tr").count(), 109);
  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => page.locator(selector).textContent())), ["80,535", "109", "4,100"]);
  assert.equal(await page.locator("#resultsMeta").textContent(), "109 of 7,680 records · 80,535 MW · largest 4,100 MW");

  await page.locator("#clearFilters").click();
  await page.locator("#search").fill("GG2050-REPD-10087 Brecks");
  assert.equal(await page.locator("#tbody tr").count(), 1);
  assert.notEqual(await page.locator("#tbody .signal").textContent(), "—");
  assert.match(await page.locator("#tbody .signal-note").textContent(), /canonical PRIMARY_MATCH/);

  await page.locator("#search").fill("");
  await page.locator("#search").fill("GG2050-REPD-9873 Berwick");
  assert.equal(await page.locator("#tbody tr").count(), 1);
  const atlas = new URL(await page.locator("#tbody .atlaslink").getAttribute("href"));
  assert.equal(atlas.searchParams.get("repd_ref"), "9873");
  assert.equal(atlas.searchParams.get("technology"), "wind_offshore");

  await page.locator("#tbody .project-record summary").click();
  assert.equal(await page.locator("#tbody .project-record").getAttribute("open"), "");
  assert.match(await page.locator("#tbody .record-grid").textContent(), /PLANNING AUTHORITY/);

  await page.locator("#tbody .copy-id").click();
  await page.waitForFunction(() => document.querySelector("#tbody .copy-id")?.textContent === "COPIED");
  assert.equal(await page.locator("#tbody .copy-id").textContent(), "COPIED");

  const missingRef = await page.evaluate(async () => {
    const manifest = await fetch("data/v9.1/build_manifest.json").then((response) => response.json());
    for (const partition of manifest.project_partitions) {
      const payload = await fetch(partition.path).then((response) => response.json());
      const missing = payload.projects.find((project) => project.geometry_status !== "valid");
      if (missing) return missing.repd_ref;
    }
    return "";
  });
  assert.ok(missingRef);
  await page.locator("#search").fill(missingRef);
  assert.equal(await page.locator("#tbody tr").count(), 1);
  assert.equal(await page.locator("#tbody .action-disabled").textContent(), "NO MAP");
  assert.equal(await page.locator("#tbody .atlaslink").count(), 0);

  await page.locator('[data-news="RELEVANT"]').click();
  const relevantCount = await page.locator("#stories .story").count();
  assert.equal(relevantCount, 45);
  await page.locator("#newsSearch").fill("Beacon Fen");
  assert.equal(await page.locator("#stories .story").count(), 1);
  assert.match(await page.locator("#stories .story").textContent(), /Beacon Fen Energy Park development consent decision announced/);
  assert.match(await page.locator("#stories .story").textContent(), /400 MW/);
  assert.match(await page.locator("#stories .story").textContent(), /REPD 13599/);
  await page.locator("#newsSearch").fill("");
  await page.locator('[data-news="ALL"]').click();
  assert.equal(await page.locator("#stories .story").count(), 133);

  await page.locator("#search").fill("GG2050-REPD-13599 Beacon Fen");
  assert.equal(await page.locator("#tbody tr").count(), 1);
  assert.notEqual(await page.locator("#tbody .signal").textContent(), "—");
  assert.match(await page.locator("#tbody .signal-note").textContent(), /canonical PRIMARY_MATCH 91%/);
  await page.locator("#search").fill("GG2050-REPD-13600 Beacon Fen");
  assert.equal(await page.locator("#tbody tr").count(), 1);
  assert.equal(await page.locator("#tbody .signal").textContent(), "—");

  await page.locator("#search").fill("definitely-no-such-repd-project-v9-5-1");
  assert.equal(await page.locator("#tbody tr").count(), 0);
  const downloadPromise = page.waitForEvent("download");
  await page.locator("#exportInline").click();
  const download = await downloadPromise;
  assert.match(download.suggestedFilename(), /^globalgrid2050_uk_renewables_pipeline_v9_5_1_\d{4}-\d{2}-\d{2}\.csv$/);
  const csv = await readFile(await download.path(), "utf8");
  assert.equal(csv.trimEnd().split(/\r?\n/).length, 1);
  assert.match(csv, /Site Name/);

  assert.deepEqual(errors, []);
  await context.close();

  const newsFailure = await preparePage(browser);
  await newsFailure.page.route("**/dist/major_project_news_v9_5_1.json*", (route) => route.abort());
  await newsFailure.page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await newsFailure.page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await newsFailure.page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 60000 });
  await newsFailure.page.waitForFunction(() => document.querySelector("#newsMeta").textContent === "newspaper unavailable");
  await newsFailure.page.waitForFunction(() => document.querySelector("#v1")?.textContent === "356,474");
  await newsFailure.context.close();

  const projectFailure = await preparePage(browser);
  await projectFailure.page.route("**/contracts/release.v9.5.1.json*", (route) => route.abort());
  await projectFailure.page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await projectFailure.page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await projectFailure.page.waitForFunction(() => document.querySelectorAll("#stories .story").length > 0, null, { timeout: 30000 });
  await projectFailure.page.waitForFunction(() => document.querySelector("#tbody").textContent.includes("V9.5.1 has failed closed."));
  await projectFailure.context.close();

  const chartFailure = await preparePage(browser, { chartStub: false });
  await chartFailure.page.route("https://raw.githubusercontent.com/**", (route) => route.abort());
  await chartFailure.page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await chartFailure.page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680, null, { timeout: 60000 });
  await chartFailure.page.waitForFunction(() => document.querySelector("#v1")?.textContent === "356,474");
  assert.deepEqual(await Promise.all(["#v1", "#v2", "#v3"].map((selector) => chartFailure.page.locator(selector).textContent())), ["356,474", "7,680", "4,100"]);
  await chartFailure.context.close();

  console.log("V9.6.1 browser smoke: PASS (V9.5.1 parity plus mobile project-table scroll)");
} finally {
  await browser.close();
}

Browser Smoke V9 6 2

A JavaScript module in the tests folder of GlobalGrid2050 that works with click count (`clickCount`). It is built from the page at helper (`pageAt`) and the click count helper (`clickCount`).

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_6_2.mjs · lines 1–93 of 93 · version 2026-09-05 11:56 · pattern clickCount (shared by 4 files)

What it does
It tests its inputs. Defines pageAt, clickCount. Uses libraries node:assert/strict, node:module, playwright. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): 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 1 file: Run V9 6 2 (globalgrid2050).
What it achieves
Defines `pageAt` and `clickCount`.
Why it matters
Checked by Run V9 6 2.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · JavaScript module
Uses
node:assert/strict, node:module, playwright
Used by
run by Run V9 6 2 (script call)
Produces
pageAt, clickCount
Defines here
pageAt, clickCount
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/browser_smoke_v9_6_2.mjs:1-93 · blob 8a69372089f306b4fcdceb0ce3d64231f90063ba · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import assert from "node:assert/strict";
import { createRequire } from "node:module";

const require = createRequire(new URL("../package.json", import.meta.url));
const { chromium } = require("playwright");
const baseUrl = process.env.V9_BASE_URL || "http://127.0.0.1:8765/uk_renewables_pipeline/v9.6.2/";

async function pageAt(browser, width) {
  const context = await browser.newContext({ viewport: { width, height: 1000 } });
  const page = await context.newPage();
  await page.addInitScript(() => {
    window.Chart = class ChartStub {
      constructor(_canvas, config) { this.data = config.data; }
      update() {}
    };
  });
  await page.route("https://cdn.jsdelivr.net/**", (route) => route.fulfill({
    status: 200, contentType: "application/javascript", body: "",
  }));
  await page.goto(baseUrl, { waitUntil: "domcontentloaded" });
  await page.waitForFunction(() => document.querySelectorAll("#tbody tr").length === 7680);
  return { context, page };
}

async function clickCount(page, mode) {
  await page.locator(`button[data-news="${mode}"]`).click();
  await page.waitForFunction(() => !document.querySelector("#stories .news-empty"));
  return page.locator("#stories .story").count();
}

const browser = await chromium.launch({ headless: true });
try {
  const { context, page } = await pageAt(browser, 1440);
  assert.equal(await page.locator("#tbody tr").count(), 7680);
  assert.equal(await page.locator("#v1").innerText(), "356,474");
  assert.equal(await page.locator("#v2").innerText(), "7,680");
  assert.equal(await page.locator("#v3").innerText(), "4,100");
  assert.equal(await page.locator("#stories .story").count(), 133);

  assert.equal(await clickCount(page, "UK"), 45);
  assert.ok(await page.locator("#stories").innerText().then((text) => text.includes("Beacon Fen Energy Park development consent decision announced")));
  assert.ok(await page.locator("#stories").innerText().then((text) => !text.includes("New Jersey")));

  assert.equal(await clickCount(page, "INTERNATIONAL"), 19);
  const international = await page.locator("#stories").innerText();
  assert.match(international, /New Jersey/);
  assert.match(international, /County Kerry, Ireland/);
  assert.match(international, /Australia/);
  assert.doesNotMatch(international, /Kintore/);
  assert.doesNotMatch(international, /Canadian Solar says patent dispute/);

  assert.equal(await clickCount(page, "US"), 4);
  const us = await page.locator("#stories").innerText();
  assert.match(us, /New Jersey/);
  assert.doesNotMatch(us, /County Kerry/);

  assert.equal(await clickCount(page, "EUROPE"), 9);
  const europe = await page.locator("#stories").innerText();
  assert.match(europe, /County Kerry, Ireland/);
  assert.match(europe, /Germany BESS/);
  assert.doesNotMatch(europe, /New Jersey/);
  await context.close();

  for (const width of [390, 430, 440, 768]) {
    const mobile = await pageAt(browser, width);
    const layout = await mobile.page.evaluate(() => {
      const wrap = document.querySelector(".tablewrap");
      const table = wrap.querySelector("table");
      return {
        clientWidth: document.documentElement.clientWidth,
        scrollWidth: document.documentElement.scrollWidth,
        wrapClientWidth: wrap.clientWidth,
        wrapScrollWidth: wrap.scrollWidth,
        overflowX: getComputedStyle(wrap).overflowX,
        tableDisplay: getComputedStyle(table).display,
        columns: table.tHead.rows[0].cells.length,
        displays: [...table.tHead.rows[0].cells].map((cell) => getComputedStyle(cell).display),
      };
    });
    assert.ok(layout.scrollWidth <= layout.clientWidth, `${width}px document overflow`);
    assert.equal(layout.overflowX, "auto");
    assert.ok(layout.wrapScrollWidth > layout.wrapClientWidth, `${width}px table is not horizontally scrollable`);
    assert.equal(layout.tableDisplay, "table");
    assert.equal(layout.columns, 11);
    assert.ok(layout.displays.every((display) => display === "table-cell"));
    assert.equal(await clickCount(mobile.page, "INTERNATIONAL"), 19);
    await mobile.context.close();
  }
} finally {
  await browser.close();
}

console.log("V9.6.2 browser smoke: PASS (UK, INTERNATIONAL, US, EUROPE and mobile table)");

Check Legacy Integrity V9

A Python module in the tests folder of GlobalGrid2050 that works with git object (`git_object`), using SHA-256.

testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/check_legacy_integrity_v9.py · lines 1–34 of 34 · version 2026-09-05 11:56 · Entry point

What it does
It tests its inputs. Defines git_object. Uses libraries hashlib, json, subprocess, pathlib. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'legacy'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file legacy-integrity.v9.json.
Downstream impact
Used directly by 5 files: Run V9 1 (globalgrid2050); Run V9 3 (globalgrid2050); Run V9 4 (globalgrid2050); Run V9 5 (globalgrid2050); and 1 more.
What it achieves
Its name says it checks legacy integrity. Defines `git_object`.
Why it matters
Checked by 5 tests, including Run V9 1.
Application
globalgrid2050 · uk_renewables_pipeline/202609051156/tests · Python module
Uses
hashlib, json, subprocess, pathlib
Used by
run by Run V9 1 (script call), run by Run V9 3 (script call), run by Run V9 4 (script call), run by Run V9 5 (script call), run by Run V9 5 1 (script call)
Produces
git_object
Defines here
git_object
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/check_legacy_integrity_v9.py:1-34 · blob 667a4027f30bdcd132613d2861c340edaf39ecdf · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: experimental · users: IPP_developer · canonical: production_core
#!/usr/bin/env python3
import hashlib
import json
import subprocess
from pathlib import Path


V9_DIR = Path(__file__).resolve().parents[1]
REPO = V9_DIR.parents[1]
CONTRACT = json.loads((V9_DIR / "contracts/legacy-integrity.v9.json").read_text())


def git_object(path: str) -> str:
    return subprocess.check_output(
        ["git", "-C", str(REPO), "rev-parse", f"HEAD:{path}"],
        text=True,
    ).strip()


checks = 0
for version, marker in CONTRACT["versions"].items():
    path = marker["path"]
    actual_object = git_object(path)
    expected_object = marker.get("git_blob") or marker.get("git_tree")
    assert actual_object == expected_object, f"{version} Git object changed: {actual_object}"
    checks += 1
    if "sha256" in marker:
        actual_sha = hashlib.sha256((REPO / path).read_bytes()).hexdigest()
        assert actual_sha == marker["sha256"], f"{version} SHA-256 changed: {actual_sha}"
        checks += 1

assert CONTRACT["policy"]["prior_versions_are_read_only"] is True
assert CONTRACT["policy"]["history_is_evidence_not_ai_memory"] is True
print(f"V9 legacy integrity: PASS ({checks} immutable V1–V8 markers)")