GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / atman

Verify V9 6 2 Complete Equivalence and 1 more file

A JavaScript module in the atman folder of PipelineNews that projects matrix (`projectMatrix`), covering solar and battery storage (BESS).

490 lines of JavaScript from pipelinenews, in 2 files. Topic: Electricity markets and data pipelines. Section 1006 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 V9 6 2 Complete Equivalence render · pipelinenews / atman/202608290020-verify-v9-6-2-complete-equivalence.mjs lines 1–264
  2. Verify Adaptive Build Controller storage · pipelinenews / atman/202608290202-verify-adaptive-build-controller.mjs lines 1–226

Verify V9 6 2 Complete Equivalence

A JavaScript module in the atman folder of PipelineNews that projects matrix (`projectMatrix`), covering solar and battery storage (BESS).

renderpipelinenews / atman/202608290020-verify-v9-6-2-complete-equivalence.mjs · lines 1–264 of 264 · version 2026-08-29 00:20 · Entry point · pattern clearProjects (shared by 2 files)

What it does
It draws solar and battery storage (BESS). Defines 7 functions or classes, including gate, firstNumber, rangeTotal, clearProjects, projectMatrix. Uses libraries playwright, node:fs/promises. 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 'pipelinenews'): 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: solar, battery storage (BESS).
Inputs & outputs
In: command-line arguments.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
It is built from the first number helper (`firstNumber`), the range total helper (`rangeTotal`) and the clear projects helper (`clearProjects`). Its name says it verifies complete equivalence. Defines `gate`, `firstNumber`, `rangeTotal` and 4 more.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · atman · JavaScript module
Uses
playwright, node:fs/promises
Used by
mentioned in Standalone (comment link)
Produces
gate, firstNumber, rangeTotal, clearProjects, projectMatrix, newsMatrix, observe
Defines here
gate, firstNumber, rangeTotal, clearProjects, projectMatrix, newsMatrix, observe
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 atman/202608290020-verify-v9-6-2-complete-equivalence.mjs:1-264 · blob 18ab9a7df3ac9f420cdd2df51b3bdb5a1eb65530 · 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
#!/usr/bin/env node
import { chromium } from "playwright";
import { writeFile } from "node:fs/promises";

const args = Object.fromEntries(process.argv.slice(2).reduce(
  (pairs, value, index, values) => value.startsWith("--")
    ? [...pairs, [value.slice(2), values[index + 1]]]
    : pairs,
  [],
));
if (!args.candidate || !args.baseline || !args.report) {
  throw new Error("--candidate, --baseline and --report are required");
}

const GENERATION = "202608290020";
const CANDIDATE_GENERATION = "202608282200";
const TECHNOLOGIES = ["all", "solar", "bess", "wind_onshore", "wind_offshore"];
const STATUSES = ["All", "Operational", "Under Construction", "Awaiting Construction", "Application Submitted"];
const NEWS_MODES = ["ALL", "UK", "INTERNATIONAL", "US", "EUROPE", "SOLAR", "BESS", "CONSENT", "CONSTRUCTION", "OPERATIONAL", "FINANCE"];
const checks = [];
const sessions = [];
const gate = (id, pass, evidence) => checks.push({ id, pass: Boolean(pass), evidence });

function firstNumber(text) {
  const match = String(text).replaceAll(",", "").match(/\d+(?:\.\d+)?/u);
  return match ? Number(match[0]) : Number.NaN;
}

function rangeTotal(text) {
  const match = String(text).replaceAll(",", "").match(/\bof\s+(\d+)\b/u);
  return match ? Number(match[1]) : Number.NaN;
}

async function clearProjects(page) {
  await page.locator("#clearFilters").click();
  await page.waitForFunction(() => document.querySelector("#resultsMeta")?.dataset.filteredCount === "7680");
}

async function projectMatrix(page, label, width, exhaustive) {
  const result = { technologies: {}, statuses: {}, counties: {}, county_options: [] };
  const technologies = exhaustive ? TECHNOLOGIES : ["solar", "bess"];
  for (const value of technologies) {
    await page.locator(`#tech [data-technology="${value}"]`).click();
    const observation = await page.evaluate((selected) => ({
      count: Number(document.querySelector("#resultsMeta")?.dataset.filteredCount),
      pressed: document.querySelector(`#tech [data-technology="${selected}"]`)?.getAttribute("aria-pressed"),
      rows: document.querySelectorAll("#tbody>tr").length,
    }), value);
    result.technologies[value] = observation.count;
    gate(`${label}-${width}-technology-${value}`, observation.count > 0 && observation.pressed === "true" && observation.rows > 0, observation);
  }
  await clearProjects(page);

  const statuses = exhaustive ? STATUSES : ["Operational", "Application Submitted"];
  for (const value of statuses) {
    await page.locator(`#status [data-official-status="${value}"]`).click();
    const observation = await page.evaluate((selected) => ({
      count: Number(document.querySelector("#resultsMeta")?.dataset.filteredCount),
      pressed: document.querySelector(`#status [data-official-status="${selected}"]`)?.getAttribute("aria-pressed"),
      rows: document.querySelectorAll("#tbody>tr").length,
    }), value);
    result.statuses[value] = observation.count;
    gate(`${label}-${width}-status-${value.replaceAll(" ", "-")}`, observation.count > 0 && observation.pressed === "true" && observation.rows > 0, observation);
  }
  await clearProjects(page);

  result.county_options = await page.locator("#county option").evaluateAll((options) => options.map((option) => option.value));
  const counties = exhaustive ? result.county_options.filter((value) => value !== "All") : result.county_options.slice(1, 3);
  for (const value of counties) {
    await page.locator("#county").selectOption(value);
    const observation = await page.evaluate((selected) => ({
      count: Number(document.querySelector("#resultsMeta")?.dataset.filteredCount),
      selected: document.querySelector("#county")?.value,
      rows: document.querySelectorAll("#tbody>tr").length,
    }), value);
    result.counties[value] = observation.count;
    gate(`${label}-${width}-county-${value}`, observation.count > 0 && observation.selected === value && observation.rows > 0, observation);
  }
  await clearProjects(page);
  gate(`${label}-${width}-county-options`, result.county_options.length > 1 && new Set(result.county_options).size === result.county_options.length, result.county_options.length);
  return result;
}

async function newsMatrix(page, label, width, exhaustive) {
  const modes = exhaustive ? NEWS_MODES : ["ALL", "UK", "INTERNATIONAL", "SOLAR", "BESS"];
  const result = {};
  for (const mode of modes) {
    await page.locator(`#newsTools [data-news="${mode}"]`).click();
    const observation = await page.evaluate((selected) => {
      const range = document.querySelector("#newsWindowRange")?.textContent || "";
      const stories = document.querySelectorAll("#stories .story").length;
      const empty = document.querySelectorAll("#stories .news-empty").length;
      return {
        active: document.querySelector(`#newsTools [data-news="${selected}"]`)?.classList.contains("active"),
        range,
        stories,
        empty,
      };
    }, mode);
    const total = observation.range ? rangeTotal(observation.range) : observation.stories;
    result[mode] = total;
    gate(`${label}-${width}-news-filter-${mode}`, observation.active && Number.isFinite(total) && ((total > 0 && observation.stories > 0) || (total === 0 && observation.empty === 1)), { ...observation, total });
  }
  await page.locator('#newsTools [data-news="ALL"]').click();
  return result;
}

async function observe(browser, label, url, viewport) {
  const width = viewport.width;
  const mobile = width === 390;
  const exhaustive = width === 1440;
  const page = await browser.newPage({ viewport, deviceScaleFactor: mobile ? 3 : 1, isMobile: mobile, hasTouch: mobile });
  const requests = [];
  const consoleErrors = [];
  const pageErrors = [];
  const failedRequests = [];
  const started = Date.now();
  page.on("request", (request) => requests.push(new URL(request.url()).pathname));
  page.on("console", (message) => { if (message.type() === "error") consoleErrors.push(message.text()); });
  page.on("pageerror", (error) => pageErrors.push(error.message));
  page.on("requestfailed", (request) => failedRequests.push(`${request.url()} :: ${request.failure()?.errorText}`));

  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 120_000 });
  if (label === "candidate") {
    await page.waitForFunction(() => document.body.dataset.fastReady === "true", null, { timeout: 120_000 });
  } else {
    await page.waitForFunction(() => document.querySelector("#resultsMeta")?.dataset.totalCount === "7680", null, { timeout: 120_000 });
  }
  const readyMs = Date.now() - started;
  const expectedNews = label === "candidate" ? "136" : "133";
  await page.waitForFunction((value) => document.querySelector("#newsMeta")?.textContent.includes(value), expectedNews, { timeout: 120_000 });

  const core = await page.evaluate(() => ({
    total: Number(document.querySelector("#resultsMeta")?.dataset.totalCount),
    filtered: Number(document.querySelector("#resultsMeta")?.dataset.filteredCount),
    capacity: document.querySelector("#v1")?.textContent.trim(),
    largest: document.querySelector("#v3")?.textContent.trim(),
    columns: document.querySelectorAll(".tablewrap thead th").length,
    rows: document.querySelectorAll("#tbody>tr").length,
    rootOverflow: document.scrollingElement.scrollWidth - document.documentElement.clientWidth,
    tableClient: document.querySelector(".tablewrap")?.clientWidth,
    tableScroll: document.querySelector(".tablewrap")?.scrollWidth,
    tableOverflow: getComputedStyle(document.querySelector(".tablewrap")).overflowX,
    news: document.querySelector("#newsMeta")?.textContent.trim(),
  }));
  const observedCapacity = firstNumber(core.capacity);
  const expectedCapacity = label === "candidate" ? 356474.09 : 356474;
  gate(`${label}-${width}-canonical`, core.total === 7680 && core.filtered === 7680 && Math.abs(observedCapacity - expectedCapacity) < 0.001 && core.largest.includes("4,100"), { ...core, observedCapacity, expectedCapacity });
  gate(`${label}-${width}-columns`, core.columns === 11, core.columns);
  gate(`${label}-${width}-news-count`, core.news.includes(expectedNews), core.news);
  if (label === "candidate") {
    gate(`${label}-${width}-100-rows`, core.rows === 100, core.rows);
    gate(`${label}-${width}-first-paint`, readyMs <= 5000, { ready_ms: readyMs, maximum_ms: 5000 });
    const startupRelationship = requests.filter((path) => path.includes(`${CANDIDATE_GENERATION}-federated-relationships`) || path.includes(`${CANDIDATE_GENERATION}-relationship-governance-status`));
    gate(`${label}-${width}-relationship-zero-startup`, startupRelationship.length === 0, startupRelationship);
  }
  if (mobile) {
    gate(`${label}-390-contained-root`, core.rootOverflow <= 1, core.rootOverflow);
    gate(`${label}-390-table-scroll`, core.tableScroll > core.tableClient && ["auto", "scroll"].includes(core.tableOverflow), core);
  }

  await page.locator("#search").fill("East Pye");
  await page.waitForFunction(() => document.querySelector("#resultsMeta")?.dataset.filteredCount === "1");
  gate(`${label}-${width}-search-east-pye`, (await page.locator("#repd-17494").count()) === 1, await page.locator("#resultsMeta").textContent());
  await clearProjects(page);

  const projects = await projectMatrix(page, label, width, exhaustive);
  await page.locator("#sortProjects").selectOption("updated_desc");
  gate(`${label}-${width}-sort-desc`, (await page.locator("#repdUpdatedHeader").getAttribute("aria-sort")) === "descending", "descending");
  await page.locator("#sortProjects").selectOption("updated_asc");
  gate(`${label}-${width}-sort-asc`, (await page.locator("#repdUpdatedHeader").getAttribute("aria-sort")) === "ascending", "ascending");
  await clearProjects(page);

  const downloadPromise = page.waitForEvent("download");
  await page.locator("#exportInline").click();
  const download = await downloadPromise;
  gate(`${label}-${width}-csv-export`, download.suggestedFilename().endsWith(".csv"), download.suggestedFilename());
  gate(`${label}-${width}-atlas-links`, (await page.locator("a.atlaslink").count()) > 0, await page.locator("a.atlaslink").count());

  const news = await newsMatrix(page, label, width, exhaustive);
  await page.locator("#newsSearch").fill("Beacon Fen");
  const beaconStories = await page.locator("#stories .story").count();
  gate(`${label}-${width}-news-search-beacon-fen`, beaconStories > 0, beaconStories);
  await page.locator("#newsSearch").fill("");

  if (label === "candidate") {
    const firstProjectId = await page.locator("#tbody>tr").first().getAttribute("id");
    const firstProjectRange = await page.locator("#projectWindowControls [data-window-range]").textContent();
    await page.locator('#projectWindowControls [data-window="next"]').click();
    const nextProjectId = await page.locator("#tbody>tr").first().getAttribute("id");
    const nextProjectRange = await page.locator("#projectWindowControls [data-window-range]").textContent();
    await page.locator('#projectWindowControls [data-window="previous"]').click();
    const restoredProjectId = await page.locator("#tbody>tr").first().getAttribute("id");
    const restoredProjectRange = await page.locator("#projectWindowControls [data-window-range]").textContent();
    gate(`${label}-${width}-project-pagination`, firstProjectRange.includes("1–100") && nextProjectRange.includes("101–200") && restoredProjectRange.includes("1–100") && firstProjectId !== nextProjectId && firstProjectId === restoredProjectId && (await page.locator("#tbody>tr").count()) === 100, { firstProjectRange, nextProjectRange, restoredProjectRange, firstProjectId, nextProjectId, restoredPro  … [line shortened here: 410 characters; full line on GitHub]

    await page.locator('#newsTools [data-news="ALL"]').click();
    const firstArticleId = await page.locator("#stories .story").first().getAttribute("data-article-id");
    const firstNewsRange = await page.locator("#newsWindowRange").textContent();
    await page.locator("#newsMore").click();
    const nextArticleId = await page.locator("#stories .story").first().getAttribute("data-article-id");
    const nextNewsRange = await page.locator("#newsWindowRange").textContent();
    await page.locator("#newsPrevious").click();
    const restoredArticleId = await page.locator("#stories .story").first().getAttribute("data-article-id");
    const restoredNewsRange = await page.locator("#newsWindowRange").textContent();
    gate(`${label}-${width}-news-pagination`, firstNewsRange.includes("1–30") && nextNewsRange.includes("31–60") && restoredNewsRange.includes("1–30") && firstArticleId !== nextArticleId && firstArticleId === restoredArticleId, { firstNewsRange, nextNewsRange, restoredNewsRange, firstArticleId, nextArticleId, restoredArticleId });

    await page.locator("#federatedRelationshipOpen").click();
    await page.waitForFunction(() => document.querySelector("#federatedRelationshipHost")?.dataset.federatedRelationshipState === "ready", null, { timeout: 30000 });
    await page.locator("#federatedRelationshipOpen").click();
    const lazy = {
      module: requests.filter((path) => path.endsWith(`/${CANDIDATE_GENERATION}-federated-relationships.js`)).length,
      payload: requests.filter((path) => path.endsWith(`/${CANDIDATE_GENERATION}-relationship-governance-status.json`)).length,
      rows: await page.locator("#federatedRelationshipHost tbody tr").count(),
      abstain: await page.locator("#federatedRelationshipHost td", { hasText: "ABSTAIN" }).count(),
    };
    gate(`${label}-${width}-relationship-lazy-once`, lazy.module === 1 && lazy.payload === 1, lazy);
    gate(`${label}-${width}-relationship-abstention`, lazy.rows === 3 && lazy.abstain === 3, lazy);
  }

  gate(`${label}-${width}-console-cors`, consoleErrors.length === 0 && pageErrors.length === 0 && failedRequests.length === 0, { consoleErrors, pageErrors, failedRequests });
  const session = { label, viewport, ready_ms: readyMs, core, projects, news, request_count: requests.length, console_errors: consoleErrors.length, page_errors: pageErrors.length, failed_requests: failedRequests.length };
  sessions.push(session);
  await page.close();
  return session;
}

const browser = await chromium.launch({ headless: true });
try {
  for (const viewport of [{ width: 1440, height: 1000 }, { width: 390, height: 844 }]) {
    const baseline = await observe(browser, "baseline", args.baseline, viewport);
    const candidate = await observe(browser, "candidate", args.candidate, viewport);
    gate(`equivalence-${viewport.width}-technology-counts`, JSON.stringify(candidate.projects.technologies) === JSON.stringify(baseline.projects.technologies), { baseline: baseline.projects.technologies, candidate: candidate.projects.technologies });
    gate(`equivalence-${viewport.width}-status-counts`, JSON.stringify(candidate.projects.statuses) === JSON.stringify(baseline.projects.statuses), { baseline: baseline.projects.statuses, candidate: candidate.projects.statuses });
    gate(`equivalence-${viewport.width}-county-options`, JSON.stringify(candidate.projects.county_options) === JSON.stringify(baseline.projects.county_options), { baseline: baseline.projects.county_options.length, candidate: candidate.projects.county_options.length });
    gate(`equivalence-${viewport.width}-county-counts`, JSON.stringify(candidate.projects.counties) === JSON.stringify(baseline.projects.counties), { baseline: baseline.projects.counties, candidate: candidate.projects.counties });
    const newsNoLoss = Object.entries(baseline.news).every(([mode, count]) => candidate.news[mode] >= count);
    gate(`equivalence-${viewport.width}-news-no-loss`, newsNoLoss, { baseline: baseline.news, candidate: candidate.news });
  }
} catch (error) {
  gate("browser-completion", false, error.stack || error.message);
} finally {
  await browser.close();
}

const failures = checks.filter((check) => !check.pass);
const result = {
  schema: "pipelinenews.v9-6-2-complete-equivalence-report.v1",
  generation: GENERATION,
  candidate_generation: CANDIDATE_GENERATION,
  source_commit: process.env.GITHUB_SHA,
  workflow_run_id: process.env.GITHUB_RUN_ID,
  playwright_version: "1.55.0",
  predecessor_audit: { generation: "202608282348", run_id: 33218336294, disposition: "GREEN_INCOMPLETE_NOT_PROMOTION_ELIGIBLE" },
  complete_matrix: { technologies: TECHNOLOGIES, statuses: STATUSES, counties: "EVERY_RENDERED_OPTION_AT_1440_AND_EQUIVALENT_OPTIONS_AT_390", news_modes: NEWS_MODES, project_pagination: true, news_pagination: true },
  sessions,
  checks,
  summary: { checks: checks.length, passed: checks.length - failures.length, failed: failures.length },
  promotion_eligible: failures.length === 0,
  state: { candidate: "ARTIFACT_ONLY", current_pointer_changed: false, pages_changed: false, catalogue_changed: false },
};
await writeFile(args.report, `${JSON.stringify(result, null, 2)}\n`);
process.stdout.write(`${JSON.stringify(result.summary)}\n`);
if (failures.length) process.exitCode = 1;

Verify Adaptive Build Controller

A JavaScript module in the atman folder of PipelineNews that uses SHA-256 using data from GitHub API. It parses args (`parseArgs`), validates milestones (`validateMilestones`) and validates contract (`validateContract`).

storagepipelinenews / atman/202608290202-verify-adaptive-build-controller.mjs · lines 1–226 of 226 · version 2026-08-29 02:02 · Entry point · pattern validateContract (shared by 3 files)

What it does
It fetches data. Defines 9 functions or classes, including parseArgs, sha256, git, isAbsent, api. Uses libraries node:assert/strict, node:crypto, node:child_process, node:fs/promises. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): 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: data source: GitHub API; JSON file live-set.json; JSON file current.json; command-line arguments.
Downstream impact
Used directly by 1 file: PipelineNews Adaptive Controller Contract Gate Workflow (pipelinenews).
What it achieves
Its name says it verifies adaptive build controller. Defines `parseArgs`, `sha256`, `git` and 6 more.
Why it matters
Run by PipelineNews Adaptive Controller Contract Gate Workflow.
Application
pipelinenews · atman · JavaScript module
Uses
node:assert/strict, node:crypto, node:child_process, node:fs/promises
Used by
run by PipelineNews Adaptive Controller Contract Gate Workflow (workflow run)
Produces
parseArgs, sha256, git, isAbsent, api, validateMilestones, validateContract, verifyArtifact, remoteAttestation
Defines here
parseArgs, sha256, git, isAbsent, api, validateMilestones, validateContract, verifyArtifact, remoteAttestation
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 atman/202608290202-verify-adaptive-build-controller.mjs:1-226 · blob fe8c87371cc2d3645540b4a44d35a75fc0f369ed · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network, process · 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 { execFileSync } from "node:child_process";
import { lstat, readFile, writeFile } from "node:fs/promises";

const GENERATION = "202608290202";
const SCHEMA = "pipelinenews.adaptive-build-controller.v1";

function parseArgs(values) {
  const result = {};
  for (let index = 0; index < values.length; index += 1) {
    if (!values[index].startsWith("--")) continue;
    result[values[index].slice(2)] = values[index + 1];
    index += 1;
  }
  return result;
}

function sha256(raw) {
  return createHash("sha256").update(raw).digest("hex");
}

function git(...args) {
  return execFileSync("git", args, { encoding: "utf8" }).trim();
}

async function isAbsent(filename) {
  try {
    await lstat(filename);
    return false;
  } catch (error) {
    if (error?.code === "ENOENT") return true;
    throw error;
  }
}

async function api(endpoint, { authenticated = true } = {}) {
  const token = process.env.GITHUB_TOKEN;
  if (authenticated) assert.ok(token, "GITHUB_TOKEN is required for remote contract attestation");
  const headers = {
    Accept: "application/vnd.github+json",
    "X-GitHub-Api-Version": "2022-11-28",
  };
  if (authenticated) headers.Authorization = `Bearer ${token}`;
  const response = await fetch(`${process.env.GITHUB_API_URL ?? "https://api.github.com"}${endpoint}`, {
    headers,
  });
  assert.ok(response.ok, `GitHub API ${response.status}: ${endpoint}`);
  return response.json();
}

function validateMilestones(milestones) {
  assert.equal(milestones.length, 10);
  const ids = milestones.map(({ id }) => id);
  assert.deepEqual(ids, Array.from({ length: 10 }, (_, index) => `M${String(index + 1).padStart(2, "0")}`));
  for (const [index, milestone] of milestones.entries()) {
    assert.ok(milestone.title && milestone.acceptance.length > 0);
    for (const dependency of milestone.depends_on) {
      const dependencyIndex = ids.indexOf(dependency);
      assert.ok(dependencyIndex >= 0 && dependencyIndex < index, `${milestone.id} has a non-causal dependency: ${dependency}`);
    }
  }
}

async function validateContract(manifest, manifestPath) {
  assert.equal(manifest.schema, SCHEMA);
  assert.equal(manifest.generation, GENERATION);
  assert.equal(manifest.lifecycle, "write-once");
  assert.match(manifest.source_parent_commit, /^[0-9a-f]{40}$/u);
  assert.equal(manifest.controller.authoritative_task_id, "6a921120ec248191a3551a6e618ea000");
  assert.equal(manifest.controller.superseded_watchdog_id, "6a92242b34b88191ac51b68ccf595bf9");
  assert.equal(manifest.controller.failed_predecessor_id, "6a919a1495f08191949507e6b817cbeb");
  assert.equal(manifest.controller.github_workflow_role, "IMMUTABLE_CONTRACT_GATE_NOT_A_SECOND_TIMER");
  assert.equal(manifest.current_state.verified_through, "M00");
  assert.equal(manifest.current_state.earliest_unmet_milestone, "M01");
  assert.ok(manifest.mission.paris_agreement_article_2_1_a.includes("well below 2°C"));
  assert.ok(manifest.mission.paris_agreement_article_2_1_a.includes("1.5°C"));
  assert.equal(manifest.product_contract.projects, 7680);
  assert.equal(manifest.product_contract.capacity_mw, 356474.09);
  assert.equal(manifest.product_contract.headlines, 136);
  assert.equal(manifest.product_contract.rows_per_page, 100);
  assert.equal(manifest.product_contract.table_columns, 11);
  assert.equal(manifest.relationship_law.authoritative_writer, false);
  assert.equal(manifest.relationship_law.project_bindings, 0);
  assert.equal(manifest.relationship_law.decision, "ABSTAIN");
  validateMilestones(manifest.milestones);

  const expectedBoundary = [
    `.github/workflows/${GENERATION}-adaptive-controller-contract-gate.yml`,
    `atman/${GENERATION}-verify-adaptive-build-controller.mjs`,
    `manifests/${GENERATION}-adaptive-build-controller-prompt.md`,
    `manifests/${GENERATION}-adaptive-build-controller.json`,
  ].sort();
  assert.deepEqual(manifest.source_boundary.slice().sort(), expectedBoundary);
  assert.equal(manifestPath, `manifests/${GENERATION}-adaptive-build-controller.json`);
  assert.equal(manifest.source_files.length, 3);
  for (const pin of manifest.source_files) {
    const stat = await lstat(pin.path);
    assert.ok(stat.isFile() && !stat.isSymbolicLink(), `not a regular controller source: ${pin.path}`);
    const raw = await readFile(pin.path);
    assert.equal(raw.length, pin.bytes, `controller byte drift: ${pin.path}`);
    assert.equal(sha256(raw), pin.sha256, `controller hash drift: ${pin.path}`);
  }

  const promptPin = manifest.source_files.find(({ path }) => path.endsWith("-prompt.md"));
  assert.ok(promptPin);
  const prompt = await readFile(promptPin.path, "utf8");
  for (const required of manifest.prompt_required_literals) {
    assert.ok(prompt.includes(required), `merged prompt lost required scope: ${required}`);
  }
  assert.ok(prompt.length > 24000, "merged prompt is unexpectedly truncated");
}

async function verifyArtifact(repository, expected) {
  const [run, artifact] = await Promise.all([
    api(`/repos/${repository}/actions/runs/${expected.run_id}`),
    api(`/repos/${repository}/actions/artifacts/${expected.artifact_id}`),
  ]);
  assert.equal(run.status, "completed");
  assert.equal(run.conclusion, "success");
  assert.equal(run.head_sha, expected.source_commit);
  assert.equal(artifact.workflow_run.id, expected.run_id);
  assert.equal(artifact.size_in_bytes, expected.artifact_bytes);
  assert.equal(artifact.digest, `sha256:${expected.artifact_sha256}`);
  assert.equal(artifact.expired, false);
  return { run_id: run.id, artifact_id: artifact.id, verdict: "MATCH" };
}

async function remoteAttestation(manifest) {
  const repository = manifest.controller.repository;
  const localHead = git("rev-parse", "HEAD");
  const [branch, workflow, candidate, equivalence, companies, dataCentres, globalGrid] = await Promise.all([
    api(`/repos/${repository}/branches/main`),
    api(`/repos/${repository}/actions/workflows/${GENERATION}-adaptive-controller-contract-gate.yml`),
    verifyArtifact(repository, manifest.verified_baton.candidate),
    verifyArtifact(repository, manifest.verified_baton.equivalence),
    api(`/repos/Ventusltd/companies/branches/main`, { authenticated: false }),
    api(`/repos/Ventusltd/data-centres-gb/branches/main`, { authenticated: false }),
    api(`/repos/Ventusltd/globalgrid2050/branches/main`, { authenticated: false }),
  ]);
  assert.equal(branch.commit.sha, localHead, "remote main moved beyond checked-out controller source");
  assert.equal(workflow.path, `.github/workflows/${GENERATION}-adaptive-controller-contract-gate.yml`);
  assert.equal(workflow.state, "active");
  assert.equal(companies.commit.sha, manifest.pinned_dependencies.companies_commit);
  assert.equal(dataCentres.commit.sha, manifest.pinned_dependencies.data_centres_commit);
  assert.equal(globalGrid.commit.sha, manifest.pinned_dependencies.globalgrid_commit);
  return {
    local_head: localHead,
    remote_main_head: branch.commit.sha,
    workflow: { id: workflow.id, path: workflow.path, state: workflow.state },
    baton: { candidate, equivalence },
    dependency_heads: {
      companies: companies.commit.sha,
      data_centres: dataCentres.commit.sha,
      globalgrid: globalGrid.commit.sha,
    },
  };
}

const args = parseArgs(process.argv.slice(2));
assert.ok(args.manifest && args.report, "--manifest and --report are required");
const manifest = JSON.parse(await readFile(args.manifest, "utf8"));
await validateContract(manifest, args.manifest);

if (args["contract-only"] === "true") {
  await writeFile(args.report, `${JSON.stringify({
    schema: "pipelinenews.adaptive-build-controller-contract-check.v1",
    generation: GENERATION,
    contract_valid: true,
    prompt_path: manifest.controller.prompt,
    milestones: manifest.milestones.map(({ id, title, depends_on: dependencies }) => ({ id, title, dependencies })),
    checked_at: new Date().toISOString(),
  }, null, 2)}\n`);
  process.stdout.write("STATIC_CONTROLLER_CONTRACT_PASS\n");
  process.exit(0);
}

git("merge-base", "--is-ancestor", manifest.source_parent_commit, "HEAD");
const remote = await remoteAttestation(manifest);
const legacyPointer = await readFile(manifest.publication_hazard.legacy_current_path);
assert.equal(legacyPointer.length, manifest.publication_hazard.legacy_current_bytes);
assert.equal(sha256(legacyPointer), manifest.publication_hazard.legacy_current_sha256);
assert.equal(await isAbsent("state/live-set.json"), true);
assert.equal(await isAbsent("releases/current.json"), true);

const report = {
  schema: "pipelinenews.adaptive-build-controller-contract-source-attestation.v1",
  generation: GENERATION,
  contract_valid: true,
  github_contract_source_deployed: remote.workflow.state === "active",
  chatgpt_controller_adoption_attested: false,
  trigger: process.env.GITHUB_EVENT_NAME ?? "local",
  controller_run_id: Number(process.env.GITHUB_RUN_ID ?? 0) || null,
  source_parent_commit: manifest.source_parent_commit,
  source_head: remote.local_head,
  remote,
  legacy_pointer: {
    path: manifest.publication_hazard.legacy_current_path,
    bytes: legacyPointer.length,
    sha256: sha256(legacyPointer),
    verdict: "UNCHANGED",
  },
  publication_state: {
    candidate: "ACTIONS_ARTIFACT_ONLY",
    state_live_set_present: false,
    root_legacy_current_present: false,
    pages_changed_by_this_read_only_workflow: false,
    globalgrid_catalogue_changed_by_this_read_only_workflow: false,
  },
  verified_through: manifest.current_state.verified_through,
  earliest_unmet_milestone: manifest.current_state.earliest_unmet_milestone,
  next_required_action: manifest.milestones[0].title,
  github_workflow_role: manifest.controller.github_workflow_role,
  scheduler_boundary: manifest.controller.scheduler_boundary,
  generated_at: new Date().toISOString(),
};

await writeFile(args.report, `${JSON.stringify(report, null, 2)}\n`);
process.stdout.write(`${JSON.stringify({
  generation: report.generation,
  source_head: report.source_head,
  github_contract_source_deployed: report.github_contract_source_deployed,
  earliest_unmet_milestone: report.earliest_unmet_milestone,
})}\n`);