GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / archive/202608261547-pipelinenews/tooling

Poll Official Sources V4 and 6 more files

A JavaScript module in the tooling folder of PipelineNews that fetches official cursor and search.

655 lines of JavaScript from pipelinenews, in 7 files. Topic: Electricity markets and data pipelines. Section 995 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. Check Renewable Energy Planning Database (REPD) Source V2 energy-data · pipelinenews / archive/202608261547-pipelinenews/tooling/check-repd-source-v2.mjs lines 1–94
  2. Check Renewable Energy Planning Database (REPD) Source energy-data · pipelinenews / archive/202608261547-pipelinenews/tooling/check-repd-source.mjs lines 1–87
  3. Finalise Release automation · pipelinenews / archive/202608261547-pipelinenews/tooling/finalise-202608260159-release.mjs lines 1–83
  4. Official Frontier Engine V4 ingest · pipelinenews / archive/202608261547-pipelinenews/tooling/official-frontier-engine-v4.mjs lines 1–29
  5. Poll Official Sources V2 storage · pipelinenews / archive/202608261547-pipelinenews/tooling/poll-official-sources-v2.mjs lines 1–107
  6. Poll Official Sources V3 storage · pipelinenews / archive/202608261547-pipelinenews/tooling/poll-official-sources-v3.mjs lines 1–127
  7. Poll Official Sources V4 storage · pipelinenews / archive/202608261547-pipelinenews/tooling/poll-official-sources-v4.mjs lines 1–128

Check Renewable Energy Planning Database (REPD) Source V2

A JavaScript module in the tooling folder of PipelineNews that fetches the REPD register and wind, using SHA-256. It reads JSON (`readJson`) and parses CSV (`parseCsv`).

energy-datapipelinenews / archive/202608261547-pipelinenews/tooling/check-repd-source-v2.mjs · lines 1–94 of 94 · version 2026-08-26 15:47 · Not reached from any entry point (candidate for review) · pattern optionalJson (shared by 6 files)

What it does
It fetches the REPD register and wind. Defines 6 functions or classes, including sha256, readJson, optionalJson, atomicJson, parseCsv. Uses libraries node:crypto, node:fs/promises. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: the REPD register, wind.
Inputs & outputs
In: JSON file repd-source.json; JSON file candidate.json.
What it achieves
Its name says it checks REPD source. Defines `sha256`, `readJson`, `optionalJson` and 3 more.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · archive/202608261547-pipelinenews/tooling · JavaScript module
Uses
node:crypto, node:fs/promises
Used by
mentioned in Standalone (comment link)
Produces
sha256, readJson, optionalJson, atomicJson, parseCsv, publicProject
Defines here
sha256, readJson, optionalJson, atomicJson, parseCsv, publicProject
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/tooling/check-repd-source-v2.mjs:1-94 · blob c851fbcdb5e2fc7c4ece3b76e8de4a5c97b26c82 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: experimental · users: IPP_developer · canonical: unreached_review
import { createHash } from "node:crypto";
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";

const root = new URL("../", import.meta.url);
const statePath = "state/repd-source.json";
const candidatePath = "data/repd-source/candidate.json";
const contentUrl = "https://www.gov.uk/api/content/government/publications/renewable-energy-planning-database-quarterly-extract";
const admittedTechnologies = new Set(["Solar Photovoltaics", "Battery", "Wind Onshore", "Wind Offshore"]);
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
const readJson = async (path) => JSON.parse(await readFile(new URL(path, root), "utf8"));

async function optionalJson(path, fallback) {
  try { return await readJson(path); } catch (error) { if (error.code === "ENOENT") return fallback; throw error; }
}

async function atomicJson(path, value) {
  const target = new URL(path, root);
  await mkdir(new URL("./", target), { recursive: true });
  const temporary = new URL(`${target.pathname}.tmp-${process.pid}`, target);
  await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { flag: "wx" });
  await rename(temporary, target);
}

function parseCsv(source) {
  const rows = [];
  let row = [];
  let field = "";
  let quoted = false;
  for (let index = 0; index < source.length; index += 1) {
    const char = source[index];
    if (quoted) {
      if (char === '"' && source[index + 1] === '"') { field += '"'; index += 1; }
      else if (char === '"') quoted = false;
      else field += char;
    } else if (char === '"') quoted = true;
    else if (char === ",") { row.push(field); field = ""; }
    else if (char === "\n") { row.push(field.replace(/\r$/, "")); rows.push(row); row = []; field = ""; }
    else field += char;
  }
  if (field || row.length) { row.push(field.replace(/\r$/, "")); rows.push(row); }
  const headers = rows.shift().map((header, index) => (index === 0 ? header.replace(/^\uFEFF/, "") : header).trim());
  return rows.filter((values) => values.some(Boolean)).map((values) => Object.fromEntries(headers.map((header, index) => [header, values[index] ?? ""])));
}

function publicProject(row) {
  const keep = ["Ref ID", "Old Ref ID", "Record Last Updated (dd/mm/yyyy)", "Operator (or Applicant)", "Site Name", "Technology Type", "Storage Type", "Storage Co-location REPD Ref ID", "Installed Capacity (MWelec)", "Development Status", "Development Status (short)", "County", "Region", "Country", "Post Code", "Planning Authority", "Planning Application Reference"];
  return Object.fromEntries(keep.map((key) => [key, row[key] ?? ""]));
}

const metadataResponse = await fetch(contentUrl, { signal: AbortSignal.timeout(10_000) });
if (!metadataResponse.ok) throw new Error(`GOV.UK Content API ${metadataResponse.status}`);
const metadata = await metadataResponse.json();
const attachment = (metadata.details?.attachments || []).find((item) => item.content_type === "text/csv" || /\.csv$/i.test(item.filename || item.url || ""));
if (!attachment?.url) throw new Error("current REPD CSV attachment not found");
const csvResponse = await fetch(attachment.url, { signal: AbortSignal.timeout(25_000) });
if (!csvResponse.ok) throw new Error(`REPD CSV ${csvResponse.status}`);
const csvBytes = Buffer.from(await csvResponse.arrayBuffer());
const sourceRows = parseCsv(csvBytes.toString("utf8"));
if (sourceRows.length < 1000 || !Object.hasOwn(sourceRows[0] || {}, "Ref ID")) throw new Error("REPD source failed schema/row-count validation");
const scopedRows = sourceRows.filter((row) => admittedTechnologies.has(row["Technology Type"]) && Number(row["Installed Capacity (MWelec)"]) >= 1);
const ids = scopedRows.map((row) => String(row["Ref ID"]).trim());
if (ids.some((id) => !id) || new Set(ids).size !== ids.length) throw new Error("scoped REPD source contains blank or duplicate Ref IDs");

const admittedProjects = [];
for (let part = 1; part <= 16; part += 1) {
  const payload = await readJson(`newsv7/data/v9.1/projects/part-${String(part).padStart(3, "0")}.json`);
  admittedProjects.push(...(Array.isArray(payload) ? payload : payload.projects || payload.items || []));
}
if (admittedProjects.length !== 7680) throw new Error(`admitted spine drift: ${admittedProjects.length}`);
const admittedIds = new Set(admittedProjects.map((project) => String(project.repd_ref ?? project.ref_id ?? project["Ref ID"] ?? "").trim()));
const previous = await optionalJson(statePath, { source_sha256: null, scoped_row_hashes: {} });
const rowHashes = Object.fromEntries(scopedRows.map((row) => [String(row["Ref ID"]).trim(), sha256(JSON.stringify(row))]));
const sourceHash = sha256(csvBytes);
const newRows = scopedRows.filter((row) => !admittedIds.has(String(row["Ref ID"]).trim()));
const sourceIds = new Set(ids);
const missingIds = [...admittedIds].filter((id) => id && !sourceIds.has(id)).sort((a, b) => a.localeCompare(b, "en", { numeric: true }));
const priorHashes = previous.scoped_row_hashes || {};
const changedIds = previous.source_sha256 && previous.source_sha256 !== sourceHash ? ids.filter((id) => priorHashes[id] && priorHashes[id] !== rowHashes[id]) : [];
const checkedAt = new Date().toISOString();

await atomicJson(candidatePath, {
  schema: "pipelinenews.repd-source-candidate.v2",
  checked_at: checkedAt,
  changed_source: previous.source_sha256 !== null && previous.source_sha256 !== sourceHash,
  first_baseline: previous.source_sha256 === null,
  source: { title: attachment.title, url: attachment.url, govuk_updated_at: metadata.public_updated_at, sha256: sourceHash, bytes: csvBytes.length, raw_rows: sourceRows.length },
  scope: { technologies: [...admittedTechnologies], capacity_mw_inclusive_minimum: 1, scoped_rows: scopedRows.length, all_official_statuses: true },
  admitted_spine: { rows: admittedProjects.length },
  delta: { new_ref_ids: newRows.map((row) => String(row["Ref ID"]).trim()), missing_ref_ids: missingIds, changed_ref_ids: changedIds },
  new_projects: newRows.map(publicProject),
  admission: "CANDIDATE_ONLY_REQUIRES_FAIL_CLOSED_QUARTERLY_RELEASE",
});
await atomicJson(statePath, { schema: "pipelinenews.repd-source-state.v2", checked_at: checkedAt, source_url: attachment.url, source_sha256: sourceHash, raw_rows: sourceRows.length, scoped_rows: scopedRows.length, scoped_row_hashes: rowHashes });
console.log(`REPD ${attachment.title}: ${sourceRows.length} raw; ${scopedRows.length} in scope; ${newRows.length} new; ${changedIds.length} changed; ${missingIds.length} missing`);

Check Renewable Energy Planning Database (REPD) Source

A JavaScript module in the tooling folder of PipelineNews that fetches the REPD register, using SHA-256. It reads JSON (`readJson`) and parses CSV (`parseCsv`).

energy-datapipelinenews / archive/202608261547-pipelinenews/tooling/check-repd-source.mjs · lines 1–87 of 87 · version 2026-08-26 15:47 · Not reached from any entry point (candidate for review) · pattern optionalJson (shared by 6 files)

What it does
It fetches the REPD register. Defines sha256, readJson, optionalJson, atomicJson, parseCsv. Uses libraries node:crypto, node:fs/promises. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file repd-source.json; JSON file candidate.json.
What it achieves
Its name says it checks REPD source. Defines `sha256`, `readJson`, `optionalJson` and 2 more.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · archive/202608261547-pipelinenews/tooling · JavaScript module
Uses
node:crypto, node:fs/promises
Used by
none found
Produces
sha256, readJson, optionalJson, atomicJson, parseCsv
Defines here
sha256, readJson, optionalJson, atomicJson, parseCsv
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/tooling/check-repd-source.mjs:1-87 · blob fec8dbbe1f672bf9e486497f763c9210eeda6b79 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: experimental · users: IPP_developer · canonical: unreached_review
import { createHash } from "node:crypto";
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";

const root = new URL("../", import.meta.url);
const statePath = "state/repd-source.json";
const candidatePath = "data/repd-source/candidate.json";
const contentUrl = "https://www.gov.uk/api/content/government/publications/renewable-energy-planning-database-quarterly-extract";
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
const readJson = async (path) => JSON.parse(await readFile(new URL(path, root), "utf8"));

async function optionalJson(path, fallback) {
  try { return await readJson(path); } catch (error) { if (error.code === "ENOENT") return fallback; throw error; }
}

async function atomicJson(path, value) {
  const target = new URL(path, root);
  await mkdir(new URL("./", target), { recursive: true });
  const temporary = new URL(`${target.pathname}.tmp-${process.pid}`, target);
  await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { flag: "wx" });
  await rename(temporary, target);
}

function parseCsv(source) {
  const rows = [];
  let row = [];
  let field = "";
  let quoted = false;
  for (let index = 0; index < source.length; index += 1) {
    const char = source[index];
    if (quoted) {
      if (char === '"' && source[index + 1] === '"') { field += '"'; index += 1; }
      else if (char === '"') quoted = false;
      else field += char;
    } else if (char === '"') quoted = true;
    else if (char === ",") { row.push(field); field = ""; }
    else if (char === "\n") { row.push(field.replace(/\r$/, "")); rows.push(row); row = []; field = ""; }
    else field += char;
  }
  if (field || row.length) { row.push(field.replace(/\r$/, "")); rows.push(row); }
  const headers = rows.shift().map((header, index) => (index === 0 ? header.replace(/^\uFEFF/, "") : header).trim());
  return rows.filter((values) => values.some(Boolean)).map((values) => Object.fromEntries(headers.map((header, index) => [header, values[index] ?? ""])));
}

const metadataResponse = await fetch(contentUrl, { signal: AbortSignal.timeout(10_000) });
if (!metadataResponse.ok) throw new Error(`GOV.UK Content API ${metadataResponse.status}`);
const metadata = await metadataResponse.json();
const attachment = (metadata.details?.attachments || []).find((item) => item.content_type === "text/csv" || /\.csv$/i.test(item.filename || item.url || ""));
if (!attachment?.url) throw new Error("current REPD CSV attachment not found");
const csvResponse = await fetch(attachment.url, { signal: AbortSignal.timeout(25_000) });
if (!csvResponse.ok) throw new Error(`REPD CSV ${csvResponse.status}`);
const csvBytes = Buffer.from(await csvResponse.arrayBuffer());
const rows = parseCsv(csvBytes.toString("utf8"));
if (rows.length < 1000 || !Object.hasOwn(rows[0] || {}, "Ref ID")) throw new Error("REPD source failed schema/row-count validation");
const ids = rows.map((row) => String(row["Ref ID"]).trim());
if (ids.some((id) => !id) || new Set(ids).size !== ids.length) throw new Error("REPD source contains blank or duplicate Ref IDs");

const admittedProjects = [];
for (let part = 1; part <= 16; part += 1) {
  const payload = await readJson(`newsv7/data/v9.1/projects/part-${String(part).padStart(3, "0")}.json`);
  admittedProjects.push(...(Array.isArray(payload) ? payload : payload.projects || payload.items || []));
}
if (admittedProjects.length !== 7680) throw new Error(`admitted spine drift: ${admittedProjects.length}`);
const admittedIds = new Set(admittedProjects.map((project) => String(project.repd_ref ?? project.ref_id ?? project["Ref ID"] ?? "").trim()));
const previous = await optionalJson(statePath, { source_sha256: null, row_hashes: {} });
const rowHashes = Object.fromEntries(rows.map((row) => [String(row["Ref ID"]).trim(), sha256(JSON.stringify(row))]));
const sourceHash = sha256(csvBytes);
const newRows = rows.filter((row) => !admittedIds.has(String(row["Ref ID"]).trim()));
const sourceIds = new Set(ids);
const missingIds = [...admittedIds].filter((id) => id && !sourceIds.has(id)).sort((a, b) => a.localeCompare(b, "en", { numeric: true }));
const changedIds = previous.source_sha256 && previous.source_sha256 !== sourceHash
  ? ids.filter((id) => previous.row_hashes[id] && previous.row_hashes[id] !== rowHashes[id])
  : [];
const checkedAt = new Date().toISOString();

await atomicJson(candidatePath, {
  schema: "pipelinenews.repd-source-candidate.v1",
  checked_at: checkedAt,
  changed_source: previous.source_sha256 !== null && previous.source_sha256 !== sourceHash,
  first_baseline: previous.source_sha256 === null,
  source: { title: attachment.title, url: attachment.url, govuk_updated_at: metadata.public_updated_at, sha256: sourceHash, bytes: csvBytes.length, rows: rows.length },
  admitted_spine: { rows: admittedProjects.length },
  delta: { new_ref_ids: newRows.map((row) => String(row["Ref ID"]).trim()), missing_ref_ids: missingIds, changed_ref_ids: changedIds },
  new_projects: newRows,
  admission: "CANDIDATE_ONLY_REQUIRES_FAIL_CLOSED_QUARTERLY_RELEASE",
});
await atomicJson(statePath, { schema: "pipelinenews.repd-source-state.v1", checked_at: checkedAt, source_url: attachment.url, source_sha256: sourceHash, source_rows: rows.length, row_hashes: rowHashes });
console.log(`REPD source ${attachment.title}: ${rows.length} rows; ${newRows.length} new; ${changedIds.length} changed; ${missingIds.length} missing`);

Finalise Release

A JavaScript module in the tooling folder of PipelineNews that reads major project news, solar and battery storage (BESS), using SHA-256.

automationpipelinenews / archive/202608261547-pipelinenews/tooling/finalise-202608260159-release.mjs · lines 1–83 of 83 · version 2026-08-26 01:59 · Not reached from any entry point (candidate for review) · pattern entry (shared by 5 files)

What it does
It loads major project news, solar and battery storage (BESS). Defines 7 functions or classes, including canonical, sha256, abs, put, entry. Uses libraries node:crypto, node:fs/promises, node:path, node:url. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: solar, battery storage (BESS).
Inputs & outputs
In: JSON file release.json; JSON file candidate.json; JSON file major_project_news_v9_5_1.json.
What it achieves
It is built from the put step (`put`), the entry step (`entry`) and the walk step (`walk`). Defines `canonical`, `sha256`, `abs` and 4 more.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · archive/202608261547-pipelinenews/tooling · JavaScript module
Uses
node:crypto, node:fs/promises, node:path, node:url
Used by
none found
Produces
canonical, sha256, abs, put, entry, walk, sum
Defines here
canonical, sha256, abs, put, entry, walk, sum
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/tooling/finalise-202608260159-release.mjs:1-83 · blob 6a322668738e8173c74116fa575dcdb2320838eb · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
import { createHash } from "node:crypto";
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
import { dirname, join, relative } from "node:path";
import { fileURLToPath } from "node:url";

const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const id = "202608260159-pipelinenews";
const inception = "2026-08-26T01:59:35+01:00";
const created = "2026-08-26T02:59:16+01:00";
const canonical = (value) => `${JSON.stringify(value, null, 2)}\n`;
const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
const abs = (path) => join(root, path);
const put = async (path, value) => { await mkdir(dirname(abs(path)), { recursive: true }); await writeFile(abs(path), Buffer.isBuffer(value) || typeof value === "string" ? value : canonical(value)); };
const entry = async (path) => { const bytes = await readFile(abs(path)); return { path, bytes: bytes.length, sha256: sha256(bytes) }; };
const walk = async (path) => (await Promise.all((await readdir(abs(path))).map(async (name) => {
  const child = join(path, name); return (await stat(abs(child))).isDirectory() ? walk(child) : [child];
}))).flat();
const sum = (rows) => rows.reduce((total, row) => total + row.bytes, 0);

const snapshotPath = `${id}/CHANGELOG_SNAPSHOT.md`;
const changelog = await readFile(abs("CHANGELOG.md"));
await put(snapshotPath, changelog);
await put(`${id}/readme.md`, `# ${id}\n\nImmutable copy-first recovery candidate using the complete V9.6.2 interface and asset closure. Only audited release labels, same-origin dependency paths and privacy-safe typed news output differ. Publication, PipelineNews Pages and GlobalGrid2050 catalogue status remain UNVERIFIED until later attestations.\n`);
await put(`${id}/release.json`, {
  schema: "pipelinenews.v962-copy-release.v1", release_id: id, status: "CANDIDATE_PREPUBLICATION", immutable: true,
  source: { repository: "Ventusltd/globalgrid2050", commit: "204aae6462a9851a8341af59760c3e7cb6ad08a5", path: "uk_renewables_pipeline/v9.6.2", closure_decision: "../plans/20260826-v962-source-closure-decision.md" },
  manifest: `../releases/${id}.json`, changelog_snapshot: "CHANGELOG_SNAPSHOT.md",
  interface: { exact_v962_copy: true, table_columns: 11, full_project_rows: 7680, headline_rows: 133, mobile_horizontal_scroll: true, individual_person_names_published: false },
});
await put("releases/candidate.json", { schema: "pipelinenews.release-pointer.v2", channel: "candidate", release_id: id, manifest: `releases/${id}.json`, updated_at: created, public_app_switched: false, rejected_predecessors: ["202608251701-pipelinenews", "202608251750-pipelinenews", "202608251929-pipelinenews"] });

const sourcePlan = await readFile(abs("plans/20260826-v962-source-closure-decision.md"), "utf8");
const pins = new Map();
for (const match of sourcePlan.matchAll(/^\| (?:direct-runtime|manifest-reference) \| `([^`]+)` \| (\d+) \| `([a-f0-9]{40})` \| `([a-f0-9]{64})` \|$/gmu)) {
  let sourcePath = match[1];
  const releasePath = sourcePath.replace(/^uk_renewables_pipeline\/v9\.6\.2\//u, "");
  pins.set(releasePath, { source_path: sourcePath, source_bytes: Number(match[2]), source_blob_sha1: match[3], source_sha256: match[4] });
}
if (pins.size !== 58) throw new Error(`SOURCE_PIN_COUNT_${pins.size}`);
const substitutedPaths = new Set(["index.html", "dist/major_project_news_v9_5_1.json", "scripts/core/news-regions-v9-6-2.js", "scripts/plugins/newspaper-v9-5-1.js", "scripts/plugins/projects-v9-5-1.js"]);
const substitutions = [];
const reused = [];
for (const [path, pin] of [...pins].sort()) {
  const actual = await entry(`${id}/${path}`);
  if (substitutedPaths.has(path)) substitutions.push({ path: `${id}/${path}`, ...pin, candidate_bytes: actual.bytes, candidate_sha256: actual.sha256, reason: path === "index.html" ? "release labels, absolute legacy links and local chart dependency" : path.includes("major_project_news") ? "privacy-safe typed same-origin evidence payload" : "same-origin, privacy or fail-closed path substitution" });
  else {
    if (actual.bytes !== pin.source_bytes || actual.sha256 !== pin.source_sha256) throw new Error(`FROZEN_COPY_MISMATCH_${path}`);
    reused.push({ ...actual, source_path: pin.source_path, source_blob_sha1: pin.source_blob_sha1, source_commit: "204aae6462a9851a8341af59760c3e7cb6ad08a5" });
  }
}
await put(`reports/${id}-substitutions.json`, { schema: "pipelinenews.v962-copy-substitutions.v1", release_id: id, source_inventory_files: 58, source_inventory_bytes: 12831093, exact_reused_files: reused.length, substitutions, additions: [await entry(`${id}/vendor/chart.umd.min.js`)], out_of_scope: ["engine", "discovery", "attribution", "crawler", "search improvements"] });

const screenshotPaths = ["desktop.png", "mobile-390.png", "mobile-390-fail-closed.png"].map((name) => `reports/browser-${id}/${name}`);
await put(`attestations/${id}-preview.json`, {
  schema: "pipelinenews.local-preview-attestation.v1", release_id: id, reviewed_at: created,
  repository_head_before_build: "4e2906b76732db19bb72f255608b45764b8612a5", deployment_started: false,
  browser: { desktop: "PASS", mobile_390: "PASS", interactions: "PASS", optional_news_failure_core_boot: "PASS", visual_review: "PASS", screenshots: await Promise.all(screenshotPaths.map(entry)) },
  data: { projects: 7680, capacity_mw: 356474.09, solar: { projects: 3563, capacity_mw: 67013.29 }, bess: { projects: 1609, capacity_mw: 147681.94 }, headlines: 133, governed_uk: 45, sentinels: { "13599": "PASS", "17494": "PASS" } },
});

const shellPaths = [`${id}/index.html`, `${id}/readme.md`, `${id}/release.json`];
const newPaths = [`${id}/vendor/chart.umd.min.js`];
const evidencePaths = [...substitutions.map((row) => row.path).filter((path) => path !== `${id}/index.html`), snapshotPath, `reports/${id}-substitutions.json`, `attestations/${id}-preview.json`, ...screenshotPaths, "tests/check-202608260159-pipelinenews.mjs", "tests/browser-202608260159-pipelinenews.mjs", "tooling/sanitise-202608260159-news.mjs", "tooling/finalise-202608260159-release.mjs"];
const supportPaths = ["releases/candidate.json", "tests/check-current-timestamp-release.mjs", "tests/run-current-timestamp-release.sh", ".github/workflows/pages.yml"];
const categories = { lightweight_release_shell: await Promise.all(shellPaths.map(entry)), new_content_addressed: await Promise.all(newPaths.map(entry)), reused_or_pinned: reused, proof_and_evidence: await Promise.all(evidencePaths.map(entry)), publication_support: await Promise.all(supportPaths.map(entry)) };
let reportBytes = 0; let manifestBytes = 0; let report; let manifest;
for (let pass = 0; pass < 12; pass += 1) {
  const accounting = Object.fromEntries(Object.entries(categories).map(([key, rows]) => [key, { files: rows.length, bytes: sum(rows) }]));
  accounting.report = { files: 1, bytes: reportBytes }; accounting.manifest = { files: 1, bytes: manifestBytes };
  const releaseFiles = await walk(id);
  accounting.minimum_pages_deployment_impact = { files: releaseFiles.length + 8, bytes: sum(await Promise.all(releaseFiles.map(entry))) + reportBytes + manifestBytes + (await entry("releases/candidate.json")).bytes + (await entry(`reports/${id}-substitutions.json`)).bytes + (await entry(`attestations/${id}-preview.json`)).bytes + sum(await Promise.all(screenshotPaths.map(entry))) };
  accounting.total_closure = { files: Object.values(accounting).slice(0, 7).reduce((total, row) => total + row.files, 0), bytes: Object.values(accounting).slice(0, 7).reduce((total, row) => total + row.bytes, 0) };
  report = { schema: "pipelinenews.v962-copy-proof.v1", release_id: id, status: "LOCAL_PREPUBLICATION_PASS_LIVE_UNVERIFIED", checks: { source_closure: "PASS", source_manifest_hashes: "34_OF_34_PASS", project_count: 7680, capacity_mw: 356474.09, solar: { projects: 3563, capacity_mw: 67013.29 }, bess: { projects: 1609, capacity_mw: 147681.94 }, headlines: 133, table_columns: 11, sentinel_13599: "PAS  … [line shortened here: 705 characters; full line on GitHub]
  const reportBuffer = Buffer.from(canonical(report));
  const reportEntry = { path: `reports/${id}-proof.json`, bytes: reportBuffer.length, sha256: sha256(reportBuffer) };
  manifest = { schema: "pipelinenews.timestamp-release-manifest.v3", release_id: id, status: "CANDIDATE_PREPUBLICATION", immutable: true, timeline: { incepted_at: inception, created_at: created, committed_at: { value: null, status: "UNVERIFIED" }, pipeline_pages_verified_at: { value: null, status: "UNVERIFIED" }, catalogued_at: { value: null, status: "UNVERIFIED" }, globalgrid_live_verified_at: {   … [line shortened here: 1,507 characters; full line on GitHub]
  const nextReportBytes = reportBuffer.length; const nextManifestBytes = Buffer.byteLength(canonical(manifest));
  if (nextReportBytes === reportBytes && nextManifestBytes === manifestBytes) break;
  reportBytes = nextReportBytes; manifestBytes = nextManifestBytes;
}
await put(`reports/${id}-proof.json`, report);
await put(`releases/${id}.json`, manifest);
console.log(`FINALISE ${id}: PASS · ${manifest.byte_accounting.total_closure.files} files · ${manifest.byte_accounting.total_closure.bytes} bytes`);

Official Frontier Engine V4

A JavaScript module in the tooling folder of PipelineNews that uses SHA-256. It resolves official frontier engine (`resolveOfficialFrontierEngine`) and loads official frontier engine (`loadOfficialFrontierEngine`).

ingestpipelinenews / archive/202608261547-pipelinenews/tooling/official-frontier-engine-v4.mjs · lines 1–29 of 29 · version 2026-08-26 15:47 · Not reached from any entry point (candidate for review)

What it does
It loads data. Defines resolveOfficialFrontierEngine, loadOfficialFrontierEngine. Uses libraries node:crypto, node:fs/promises. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 2 files: Check Official Source V4 (pipelinenews); Poll Official Sources V4 (pipelinenews).
What it achieves
Defines `resolveOfficialFrontierEngine` and `loadOfficialFrontierEngine`.
Why it matters
Imported by Poll Official Sources V4. Checked by Check Official Source V4.
Application
pipelinenews · archive/202608261547-pipelinenews/tooling · JavaScript module
Uses
node:crypto, node:fs/promises
Used by
imported by Check Official Source V4 (import), imported by Poll Official Sources V4 (import)
Produces
PINNED_AUTHORITY_SAFE_ENGINE, resolveOfficialFrontierEngine, loadOfficialFrontierEngine
Defines here
resolveOfficialFrontierEngine, loadOfficialFrontierEngine
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/tooling/official-frontier-engine-v4.mjs:1-29 · blob 1547123ed90718fa5c3fd1c9ed4beeed089bcef3 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";

export const PINNED_AUTHORITY_SAFE_ENGINE = Object.freeze({
  role: "authority_safe_frontier_engine",
  path: "objects/js/sha256/60ebe5b31cdb881e61c7275fd3f696b33a4f134c5c0a6e6cd8f1474545156acc.mjs",
  sha256: "60ebe5b31cdb881e61c7275fd3f696b33a4f134c5c0a6e6cd8f1474545156acc",
});

export function resolveOfficialFrontierEngine(manifest) {
  const moduleDescriptors = Array.isArray(manifest.objects?.modules) ? manifest.objects.modules : [];
  return moduleDescriptors.find((item) =>
    item.role === "official_frontier_engine" || item.role === "authority_safe_frontier_engine"
  ) ?? PINNED_AUTHORITY_SAFE_ENGINE;
}

export async function loadOfficialFrontierEngine(manifest, repositoryRoot) {
  const descriptor = resolveOfficialFrontierEngine(manifest);
  const bytes = await readFile(new URL(descriptor.path, repositoryRoot));
  const actualSha256 = createHash("sha256").update(bytes).digest("hex");
  if (actualSha256 !== descriptor.sha256) {
    throw new Error("official_frontier_engine content hash mismatch");
  }
  return {
    descriptor,
    module: await import(new URL(descriptor.path, repositoryRoot)),
  };
}

Poll Official Sources V2

A JavaScript module in the tooling folder of PipelineNews that fetches official cursor and search.

storagepipelinenews / archive/202608261547-pipelinenews/tooling/poll-official-sources-v2.mjs · lines 1–107 of 107 · version 2026-08-26 15:47 · Not reached from any entry point (candidate for review) · pattern optionalJson (shared by 6 files)

What it does
It fetches official cursor and search. Defines readJson, sleep, optionalJson, atomicJson. Uses libraries node:fs/promises. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): 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 current.json; JSON file official-source-cursor.json; JSON file latest.json; JSON file search.json.
What it achieves
It reads JSON (`readJson`) and is built from the optional JSON helper (`optionalJson`) and the atomic JSON helper (`atomicJson`). Defines `readJson`, `sleep`, `optionalJson` and 1 more. It reads `releases/current.json`.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · archive/202608261547-pipelinenews/tooling · JavaScript module
Uses
node:fs/promises
Used by
none found
Produces
readJson, sleep, optionalJson, atomicJson
Defines here
readJson, sleep, optionalJson, atomicJson
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/tooling/poll-official-sources-v2.mjs:1-107 · blob c04f8b54e8d222c5c177d58ed6ec2d03fabdd360 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: experimental · users: none · canonical: duplicate_candidate
import { readFile, mkdir, rename, writeFile } from "node:fs/promises";

const root = new URL("../", import.meta.url);
const readJson = async (path) => JSON.parse(await readFile(new URL(path, root), "utf8"));
const pointer = await readJson("releases/current.json");
const manifest = await readJson(pointer.manifest);
const engineObject = manifest.objects.modules.find((item) => item.role === "official_frontier_engine");
if (!engineObject) throw new Error("current release does not expose official_frontier_engine");
const { buildReferenceGroups, normalisePlanningReference, resolvePlanningBinding, selectFrontier, sourceHealth } = await import(new URL(engineObject.path, root));

const statePath = "state/official-source-cursor.json";
const snapshotPath = "data/official-source/latest.json";
const now = new Date().toISOString();
const deadline = Date.now() + 165_000;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const optionalJson = async (path, fallback) => { try { return await readJson(path); } catch (error) { if (error.code === "ENOENT") return fallback; throw error; } };
async function atomicJson(path, value) {
  const target = new URL(path, root);
  await mkdir(new URL("./", target), { recursive: true });
  const temporary = new URL(`${target.pathname}.tmp-${process.pid}`, target);
  await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { flag: "wx" });
  await rename(temporary, target);
}

const projects = [];
for (let part = 1; part <= 16; part += 1) {
  const payload = await readJson(`newsv7/data/v9.1/projects/part-${String(part).padStart(3, "0")}.json`);
  projects.push(...(Array.isArray(payload) ? payload : payload.projects || payload.items || []));
}
if (projects.length !== 7680) throw new Error(`REPD spine must contain 7680 projects, got ${projects.length}`);
const groups = buildReferenceGroups(projects);
const state = await optionalJson(statePath, { schema: "pipelinenews.official-source-cursor.v1", next_index: 0, last_good_at: null });
const previous = await optionalJson(snapshotPath, { planit_by_reference: {}, govuk_items: [] });
const frontier = selectFrontier(groups, state, Number(process.env.PLANIT_BUDGET || 48));

const planitByReference = { ...previous.planit_by_reference };
let attempted = 0;
let completed = 0;
let lastStatus = null;
let healthMessage = null;
for (const group of frontier.selected) {
  if (Date.now() >= deadline) { healthMessage = "run deadline reached; unfinished work retained"; break; }
  attempted += 1;
  const url = new URL("https://www.planit.org.uk/api/applics/json");
  url.searchParams.set("id_match", group.query_reference);
  url.searchParams.set("pg_sz", "10");
  url.searchParams.set("compress", "on");
  try {
    const response = await fetch(url, { headers: { "User-Agent": "PipelineNews/1.0 (+https://github.com/Ventusltd/pipelinenews)" }, signal: AbortSignal.timeout(10_000) });
    lastStatus = response.status;
    if (response.status === 429) {
      const retrySeconds = Math.min(15, Math.max(0, Number(response.headers.get("retry-after") || 0)));
      healthMessage = `rate limited; unfinished work retained${retrySeconds ? `; retry-after ${retrySeconds}s observed` : ""}`;
      if (retrySeconds && Date.now() + retrySeconds * 1000 < deadline) await sleep(retrySeconds * 1000);
      break;
    }
    if (!response.ok) { healthMessage = `PlanIt HTTP ${response.status}; unfinished work retained`; break; }
    const payload = await response.json();
    const records = Array.isArray(payload.records) ? payload.records : [];
    planitByReference[group.normalised_reference] = {
      checked_at: now,
      query_reference: group.query_reference,
      records: records.map((record) => ({
        uid: record.uid ?? null, reference: record.reference ?? null, name: record.name ?? null,
        area_name: record.area_name ?? null, description: record.description ?? null,
        app_state: record.app_state ?? null, start_date: record.start_date ?? null,
        decided_date: record.decided_date ?? null, last_changed: record.last_changed ?? null,
        url: record.url ?? record.link ?? null, binding: resolvePlanningBinding(record, group),
      })),
    };
    completed += 1;
  } catch (error) { healthMessage = `${error.name || "fetch error"}; unfinished work retained`; break; }
  await sleep(2_000);
}

let govukAttempted = 0;
let govukSucceeded = 0;
let lastGovukStatus = null;
let govukItems = previous.govuk_items || [];
try {
  govukAttempted = 1;
  const url = new URL("https://www.gov.uk/api/search.json");
  url.searchParams.set("q", "renewable energy planning");
  url.searchParams.set("filter_organisations", "department-for-energy-security-and-net-zero");
  url.searchParams.set("count", "100");
  url.searchParams.set("order", "-public_timestamp");
  url.searchParams.set("fields", "title,description,link,public_timestamp");
  const response = await fetch(url, { signal: AbortSignal.timeout(10_000) });
  lastGovukStatus = response.status;
  if (response.ok) {
    const payload = await response.json();
    govukSucceeded = 1;
    govukItems = (payload.results || []).map((item) => {
      const haystack = normalisePlanningReference(`${item.title || ""} ${item.description || ""}`);
      const matches = groups.filter((group) => group.normalised_reference.length >= 6 && haystack.includes(group.normalised_reference));
      return { title: item.title, description: item.description, url: new URL(item.link, "https://www.gov.uk").toString(), public_timestamp: item.public_timestamp, bindings: matches.map((group) => resolvePlanningBinding({ reference: group.query_reference, name: item.title, description: item.description }, group)) };
    });
  }
} catch { /* health below records failure and preserves prior good items */ }

const planitHealth = sourceHealth({ attempted, succeeded: completed, statusCode: lastStatus, priorGoodAt: state.last_good_at, message: healthMessage });
const govukHealth = sourceHealth({ attempted: govukAttempted, succeeded: govukSucceeded, statusCode: lastGovukStatus, priorGoodAt: state.last_good_at });
if (completed === 0 && govukSucceeded === 0) throw new Error("all official adapters unavailable; refusing an empty-success snapshot");
const nextIndex = groups.length ? (Number(state.next_index || 0) + completed) % groups.length : 0;
await atomicJson(snapshotPath, { schema: "pipelinenews.official-source-snapshot.v2", generated_at: now, spine: { projects: projects.length, reference_groups: groups.length }, source_health: { planit: planitHealth, govuk: govukHealth }, planit_by_reference: planitByReference, govuk_items: govukItems, google_news: { enabled: true, credibility_score: 30, role: "noisy discovery only" } });
await atomicJson(statePath, { schema: "pipelinenews.official-source-cursor.v2", next_index: nextIndex, total_groups: groups.length, last_run_at: now, last_good_at: now });
console.log(`official-source poll: ${projects.length} projects; PlanIt ${completed}/${attempted}; GOV.UK ${govukSucceeded}/${govukAttempted}; next=${nextIndex}`);

Poll Official Sources V3

A JavaScript module in the tooling folder of PipelineNews that fetches official cursor and search.

Set aside from the main view: 95% of its lines are the same as archive/202608261547-pipelinenews/tooling/poll-official-sources-v4.mjs (pipelinenews), which stays. (near-copy-of, proposed by families.py). 94% of lines shared with Poll Official Sources V4; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9469 to pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/tooling/poll-official-sources-v4.mjs:1-128 ce680f9986579e5a3d543afa5d75a9bf4930591a
  • sha256 7869adbdf32b87a31a02fc52ee497e8263f9e4d5288d56d711ac303b2e4a5b49
  • target sha256 a1c451483726d5c14bb22c1c326c2ab36842bacc34bf1ee6ca0f6d4d39b73515
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

storagepipelinenews / archive/202608261547-pipelinenews/tooling/poll-official-sources-v3.mjs · lines 1–127 of 127 · version 2026-08-26 15:47 · Not reached from any entry point (candidate for review) · pattern optionalJson (shared by 6 files)

What it does
It fetches official cursor and search. Defines readJson, sleep, optionalJson, atomicJson. Uses libraries node:fs/promises. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): 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 current.json; JSON file official-source-cursor.json; JSON file latest.json; JSON file search.json.
What it achieves
It reads JSON (`readJson`) and is built from the optional JSON helper (`optionalJson`) and the atomic JSON helper (`atomicJson`). Defines `readJson`, `sleep`, `optionalJson` and 1 more. It reads `releases/current.json`.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · archive/202608261547-pipelinenews/tooling · JavaScript module
Uses
node:fs/promises
Used by
none found
Produces
readJson, sleep, optionalJson, atomicJson
Defines here
readJson, sleep, optionalJson, atomicJson
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/tooling/poll-official-sources-v3.mjs:1-127 · blob 84aaaddce179c1016f8e7124f054f8c8763c7bb4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: experimental · users: none · canonical: duplicate_candidate
import { readFile, mkdir, rename, writeFile } from "node:fs/promises";

const root = new URL("../", import.meta.url);
const readJson = async (path) => JSON.parse(await readFile(new URL(path, root), "utf8"));
const pointer = await readJson("releases/current.json");
const manifest = await readJson(pointer.manifest);
const engineObject = manifest.objects.modules.find((item) => item.role === "official_frontier_engine" || item.role === "authority_safe_frontier_engine");
if (!engineObject) throw new Error("current release does not expose official_frontier_engine");
const { buildReferenceGroups, normalisePlanningReference, resolvePlanningBinding, selectFrontier, sourceHealth } = await import(new URL(engineObject.path, root));

const statePath = "state/official-source-cursor.json";
const snapshotPath = "data/official-source/latest.json";
const now = new Date().toISOString();
const deadline = Date.now() + 165_000;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const optionalJson = async (path, fallback) => { try { return await readJson(path); } catch (error) { if (error.code === "ENOENT") return fallback; throw error; } };
async function atomicJson(path, value) {
  const target = new URL(path, root);
  await mkdir(new URL("./", target), { recursive: true });
  const temporary = new URL(`${target.pathname}.tmp-${process.pid}`, target);
  await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { flag: "wx" });
  await rename(temporary, target);
}

const projects = [];
for (let part = 1; part <= 16; part += 1) {
  const payload = await readJson(`newsv7/data/v9.1/projects/part-${String(part).padStart(3, "0")}.json`);
  projects.push(...(Array.isArray(payload) ? payload : payload.projects || payload.items || []));
}
if (projects.length !== 7680) throw new Error(`REPD spine must contain 7680 projects, got ${projects.length}`);
const groups = buildReferenceGroups(projects);
const state = await optionalJson(statePath, { schema: "pipelinenews.official-source-cursor.v1", next_index: 0, last_good_at: null });
const previous = await optionalJson(snapshotPath, { planit_by_reference: {}, govuk_items: [] });
const frontier = selectFrontier(groups, state, Number(process.env.PLANIT_BUDGET || 48));

const groupByReference = new Map(groups.map((group) => [group.normalised_reference, group]));
const planitByReference = Object.fromEntries(Object.entries(previous.planit_by_reference || {}).map(([reference, entry]) => {
  const group = groupByReference.get(reference);
  const records = (entry.records || []).map((record) => {
    const binding = group
      ? resolvePlanningBinding(record, group)
      : { role: "ABSTAIN", reason: "NO_REPD_REFERENCE_GROUP" };
    if (JSON.stringify(binding) === JSON.stringify(record.binding)) return record;
    return { ...record, previous_binding: record.previous_binding || record.binding, binding };
  });
  return [reference, { ...entry, records }];
}));
let attempted = 0;
let completed = 0;
let lastStatus = null;
let healthMessage = null;
for (const group of frontier.selected) {
  if (Date.now() >= deadline) { healthMessage = "run deadline reached; unfinished work retained"; break; }
  attempted += 1;
  const url = new URL("https://www.planit.org.uk/api/applics/json");
  url.searchParams.set("id_match", group.query_reference);
  url.searchParams.set("pg_sz", "10");
  url.searchParams.set("compress", "on");
  try {
    const response = await fetch(url, { headers: { "User-Agent": "PipelineNews/1.0 (+https://github.com/Ventusltd/pipelinenews)" }, signal: AbortSignal.timeout(10_000) });
    lastStatus = response.status;
    if (response.status === 429) {
      const retrySeconds = Math.min(15, Math.max(0, Number(response.headers.get("retry-after") || 0)));
      healthMessage = `rate limited; unfinished work retained${retrySeconds ? `; retry-after ${retrySeconds}s observed` : ""}`;
      if (retrySeconds && Date.now() + retrySeconds * 1000 < deadline) await sleep(retrySeconds * 1000);
      break;
    }
    if (!response.ok) { healthMessage = `PlanIt HTTP ${response.status}; unfinished work retained`; break; }
    const payload = await response.json();
    const records = Array.isArray(payload.records) ? payload.records : [];
    planitByReference[group.normalised_reference] = {
      checked_at: now,
      query_reference: group.query_reference,
      records: records.map((record) => ({
        uid: record.uid ?? null, reference: record.reference ?? null, altid: record.altid ?? null, name: record.name ?? null,
        area_name: record.area_name ?? null, description: record.description ?? null,
        app_state: record.app_state ?? null, start_date: record.start_date ?? null,
        decided_date: record.decided_date ?? null, last_changed: record.last_changed ?? null,
        url: record.url ?? record.link ?? null, binding: resolvePlanningBinding(record, group),
      })),
    };
    completed += 1;
  } catch (error) { healthMessage = `${error.name || "fetch error"}; unfinished work retained`; break; }
  await sleep(2_000);
}

let govukAttempted = 0;
let govukSucceeded = 0;
let lastGovukStatus = null;
let govukItems = previous.govuk_items || [];
try {
  govukAttempted = 1;
  const url = new URL("https://www.gov.uk/api/search.json");
  url.searchParams.set("q", "renewable energy planning");
  url.searchParams.set("filter_organisations", "department-for-energy-security-and-net-zero");
  url.searchParams.set("count", "100");
  url.searchParams.set("order", "-public_timestamp");
  url.searchParams.set("fields", "title,description,link,public_timestamp");
  const response = await fetch(url, { signal: AbortSignal.timeout(10_000) });
  lastGovukStatus = response.status;
  if (response.ok) {
    const payload = await response.json();
    govukSucceeded = 1;
    govukItems = (payload.results || []).map((item) => {
      const haystack = normalisePlanningReference(`${item.title || ""} ${item.description || ""}`);
      const matches = groups.filter((group) => group.normalised_reference.length >= 6 && haystack.includes(group.normalised_reference));
      return { title: item.title, description: item.description, url: new URL(item.link, "https://www.gov.uk").toString(), public_timestamp: item.public_timestamp, bindings: matches.map((group) => resolvePlanningBinding({ reference: group.query_reference, name: item.title, description: item.description }, group)) };
    });
  }
} catch { /* health below records failure and preserves prior good items */ }

const priorPlanitGoodAt = state.planit_last_good_at || state.last_good_at || null;
const priorGovukGoodAt = state.govuk_last_good_at || state.last_good_at || null;
const planitHealth = sourceHealth({ attempted, succeeded: completed, statusCode: lastStatus, priorGoodAt: priorPlanitGoodAt, message: healthMessage });
const govukHealth = sourceHealth({ attempted: govukAttempted, succeeded: govukSucceeded, statusCode: lastGovukStatus, priorGoodAt: priorGovukGoodAt });
if (completed === 0 && govukSucceeded === 0) throw new Error("all official adapters unavailable; refusing an empty-success snapshot");
const nextIndex = groups.length ? (Number(state.next_index || 0) + completed) % groups.length : 0;
await atomicJson(snapshotPath, { schema: "pipelinenews.official-source-snapshot.v3", generated_at: now, spine: { projects: projects.length, reference_groups: groups.length }, source_health: { planit: planitHealth, govuk: govukHealth }, planit_by_reference: planitByReference, govuk_items: govukItems, google_news: { enabled: true, credibility_score: 30, role: "noisy discovery only" } });
await atomicJson(statePath, {
  schema: "pipelinenews.official-source-cursor.v3",
  next_index: nextIndex,
  total_groups: groups.length,
  last_run_at: now,
  planit_last_good_at: completed > 0 ? now : priorPlanitGoodAt,
  govuk_last_good_at: govukSucceeded > 0 ? now : priorGovukGoodAt,
});
console.log(`official-source v3 poll: ${projects.length} projects; PlanIt ${completed}/${attempted}; GOV.UK ${govukSucceeded}/${govukAttempted}; next=${nextIndex}`);

Poll Official Sources V4

A JavaScript module in the tooling folder of PipelineNews that fetches official cursor and search.

storagepipelinenews / archive/202608261547-pipelinenews/tooling/poll-official-sources-v4.mjs · lines 1–128 of 128 · version 2026-08-26 15:47 · Not reached from any entry point (candidate for review) · pattern optionalJson (shared by 6 files)

What it does
It fetches official cursor and search. Defines readJson, sleep, optionalJson, atomicJson. Uses libraries node:fs/promises. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): 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 current.json; JSON file official-source-cursor.json; JSON file latest.json; JSON file search.json.
What it achieves
It reads JSON (`readJson`) and is built from the optional JSON helper (`optionalJson`) and the atomic JSON helper (`atomicJson`). Defines `readJson`, `sleep`, `optionalJson` and 1 more. It reads `releases/current.json`.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · archive/202608261547-pipelinenews/tooling · JavaScript module
Uses
Official Frontier Engine V4 (import), node:fs/promises
Used by
none found
Produces
readJson, sleep, optionalJson, atomicJson
Defines here
readJson, sleep, optionalJson, atomicJson
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 archive/202608261547-pipelinenews/tooling/poll-official-sources-v4.mjs:1-128 · blob ce680f9986579e5a3d543afa5d75a9bf4930591a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: experimental · users: none · canonical: unreached_review
import { readFile, mkdir, rename, writeFile } from "node:fs/promises";
import { loadOfficialFrontierEngine } from "./official-frontier-engine-v4.mjs";

const root = new URL("../", import.meta.url);
const readJson = async (path) => JSON.parse(await readFile(new URL(path, root), "utf8"));
const pointer = await readJson("releases/current.json");
const manifest = await readJson(pointer.manifest);
const { module: frontierEngine } = await loadOfficialFrontierEngine(manifest, root);
const { buildReferenceGroups, normalisePlanningReference, resolvePlanningBinding, selectFrontier, sourceHealth } = frontierEngine;

const statePath = "state/official-source-cursor.json";
const snapshotPath = "data/official-source/latest.json";
const now = new Date().toISOString();
const deadline = Date.now() + 165_000;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const optionalJson = async (path, fallback) => { try { return await readJson(path); } catch (error) { if (error.code === "ENOENT") return fallback; throw error; } };
async function atomicJson(path, value) {
  const target = new URL(path, root);
  await mkdir(new URL("./", target), { recursive: true });
  const temporary = new URL(`${target.pathname}.tmp-${process.pid}`, target);
  await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { flag: "wx" });
  await rename(temporary, target);
}

const projects = [];
for (let part = 1; part <= 16; part += 1) {
  const payload = await readJson(`newsv7/data/v9.1/projects/part-${String(part).padStart(3, "0")}.json`);
  projects.push(...(Array.isArray(payload) ? payload : payload.projects || payload.items || []));
}
if (projects.length !== 7680) throw new Error(`REPD spine must contain 7680 projects, got ${projects.length}`);
const groups = buildReferenceGroups(projects);
const state = await optionalJson(statePath, { schema: "pipelinenews.official-source-cursor.v1", next_index: 0, last_good_at: null });
const previous = await optionalJson(snapshotPath, { planit_by_reference: {}, govuk_items: [] });
const frontier = selectFrontier(groups, state, Number(process.env.PLANIT_BUDGET || 48));

const groupByReference = new Map(groups.map((group) => [group.normalised_reference, group]));
const planitByReference = Object.fromEntries(Object.entries(previous.planit_by_reference || {}).map(([reference, entry]) => {
  const group = groupByReference.get(reference);
  const records = (entry.records || []).map((record) => {
    const binding = group
      ? resolvePlanningBinding(record, group)
      : { role: "ABSTAIN", reason: "NO_REPD_REFERENCE_GROUP" };
    if (JSON.stringify(binding) === JSON.stringify(record.binding)) return record;
    return { ...record, previous_binding: record.previous_binding || record.binding, binding };
  });
  return [reference, { ...entry, records }];
}));
let attempted = 0;
let completed = 0;
let lastStatus = null;
let healthMessage = null;
for (const group of frontier.selected) {
  if (Date.now() >= deadline) { healthMessage = "run deadline reached; unfinished work retained"; break; }
  attempted += 1;
  const url = new URL("https://www.planit.org.uk/api/applics/json");
  url.searchParams.set("id_match", group.query_reference);
  url.searchParams.set("pg_sz", "10");
  url.searchParams.set("compress", "on");
  try {
    const response = await fetch(url, { headers: { "User-Agent": "PipelineNews/1.0 (+https://github.com/Ventusltd/pipelinenews)" }, signal: AbortSignal.timeout(10_000) });
    lastStatus = response.status;
    if (response.status === 429) {
      const retrySeconds = Math.min(15, Math.max(0, Number(response.headers.get("retry-after") || 0)));
      healthMessage = `rate limited; unfinished work retained${retrySeconds ? `; retry-after ${retrySeconds}s observed` : ""}`;
      if (retrySeconds && Date.now() + retrySeconds * 1000 < deadline) await sleep(retrySeconds * 1000);
      break;
    }
    if (!response.ok) { healthMessage = `PlanIt HTTP ${response.status}; unfinished work retained`; break; }
    const payload = await response.json();
    const records = Array.isArray(payload.records) ? payload.records : [];
    planitByReference[group.normalised_reference] = {
      checked_at: now,
      query_reference: group.query_reference,
      records: records.map((record) => ({
        uid: record.uid ?? null, reference: record.reference ?? null, altid: record.altid ?? null, name: record.name ?? null,
        area_name: record.area_name ?? null, description: record.description ?? null,
        app_state: record.app_state ?? null, start_date: record.start_date ?? null,
        decided_date: record.decided_date ?? null, last_changed: record.last_changed ?? null,
        url: record.url ?? record.link ?? null, binding: resolvePlanningBinding(record, group),
      })),
    };
    completed += 1;
  } catch (error) { healthMessage = `${error.name || "fetch error"}; unfinished work retained`; break; }
  await sleep(2_000);
}

let govukAttempted = 0;
let govukSucceeded = 0;
let lastGovukStatus = null;
let govukItems = previous.govuk_items || [];
try {
  govukAttempted = 1;
  const url = new URL("https://www.gov.uk/api/search.json");
  url.searchParams.set("q", "renewable energy planning");
  url.searchParams.set("filter_organisations", "department-for-energy-security-and-net-zero");
  url.searchParams.set("count", "100");
  url.searchParams.set("order", "-public_timestamp");
  url.searchParams.set("fields", "title,description,link,public_timestamp");
  const response = await fetch(url, { signal: AbortSignal.timeout(10_000) });
  lastGovukStatus = response.status;
  if (response.ok) {
    const payload = await response.json();
    govukSucceeded = 1;
    govukItems = (payload.results || []).map((item) => {
      const haystack = normalisePlanningReference(`${item.title || ""} ${item.description || ""}`);
      const matches = groups.filter((group) => group.normalised_reference.length >= 6 && haystack.includes(group.normalised_reference));
      return { title: item.title, description: item.description, url: new URL(item.link, "https://www.gov.uk").toString(), public_timestamp: item.public_timestamp, bindings: matches.map((group) => resolvePlanningBinding({ reference: group.query_reference, name: item.title, description: item.description }, group)) };
    });
  }
} catch { /* health below records failure and preserves prior good items */ }

const priorPlanitGoodAt = state.planit_last_good_at || state.last_good_at || null;
const priorGovukGoodAt = state.govuk_last_good_at || state.last_good_at || null;
const planitHealth = sourceHealth({ attempted, succeeded: completed, statusCode: lastStatus, priorGoodAt: priorPlanitGoodAt, message: healthMessage });
const govukHealth = sourceHealth({ attempted: govukAttempted, succeeded: govukSucceeded, statusCode: lastGovukStatus, priorGoodAt: priorGovukGoodAt });
if (completed === 0 && govukSucceeded === 0) throw new Error("all official adapters unavailable; refusing an empty-success snapshot");
const nextIndex = groups.length ? (Number(state.next_index || 0) + completed) % groups.length : 0;
await atomicJson(snapshotPath, { schema: "pipelinenews.official-source-snapshot.v3", generated_at: now, spine: { projects: projects.length, reference_groups: groups.length }, source_health: { planit: planitHealth, govuk: govukHealth }, planit_by_reference: planitByReference, govuk_items: govukItems, google_news: { enabled: true, credibility_score: 30, role: "noisy discovery only" } });
await atomicJson(statePath, {
  schema: "pipelinenews.official-source-cursor.v3",
  next_index: nextIndex,
  total_groups: groups.length,
  last_run_at: now,
  planit_last_good_at: completed > 0 ? now : priorPlanitGoodAt,
  govuk_last_good_at: govukSucceeded > 0 ? now : priorGovukGoodAt,
});
console.log(`official-source v3 poll: ${projects.length} projects; PlanIt ${completed}/${attempted}; GOV.UK ${govukSucceeded}/${govukAttempted}; next=${nextIndex}`);