GLOBALGRID2050 / EXPLORE CODE

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

Compile Index and 6 more files

A JavaScript module in PipelineNews that reads major project news, using SHA-256 from the GlobalGrid2050 and GridAtlas repositories. It reads pinned (`readPinned`), replaces exactly (`replaceExactly`) and compiles manifest (`compileManifest`).

576 lines of JavaScript and Python from pipelinenews, in 7 files. Topic: Electricity markets and data pipelines. Section 1022 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. Compile Index storage · pipelinenews / index/202609010836-compile-index.mjs lines 1–330
  2. PipelineNews — News other · pipelinenews / news/__init__.py lines 1–1
  3. News — BBC other · pipelinenews / news/bbc/__init__.py lines 1–1
  4. Articles ingest · pipelinenews / news/bbc/articles.py lines 1–75
  5. Collector storage · pipelinenews / news/bbc/collector.py lines 1–75
  6. Sources transform · pipelinenews / news/bbc/sources.py lines 1–17
  7. Test BBC RSS test · pipelinenews / news/tests/test_bbc_rss.py lines 1–77

Compile Index

A JavaScript module in PipelineNews that reads major project news, using SHA-256 from the GlobalGrid2050 and GridAtlas repositories. It reads pinned (`readPinned`), replaces exactly (`replaceExactly`) and compiles manifest (`compileManifest`).

storagepipelinenews / index/202609010836-compile-index.mjs · lines 1–330 of 330 · version 2026-09-01 08:36 · Not reached from any entry point (candidate for review) · pattern writeOutputs (shared by 3 files)

What it does
It loads major project news. Defines 13 functions or classes, including absolute, sha256, readPinned, replaceExactly, rewriteImports. Uses libraries node:assert/strict, node:crypto, node:fs, node:fs/promises, node:path. Side effects: 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.
Inputs & outputs
In: data source: globalgrid2050 data; data source: gridatlas data; JSON file 202608261927-release-v9-1.json; JSON file 202608261737-release-v9-5-1.json; JSON file 202608261721-release-v9-6-2.json; JSON file 202608261927-build-manifest-v9-1.json; JSON file 202608261927-major-project-news-v9-5-1.json; JSON file major_project_news_v5.json.
Downstream impact
Used directly by 1 file: Compare V9 6 2 to Compiled (pipelinenews).
What it achieves
Its name says it compiles index. Defines `absolute`, `sha256`, `readPinned` and 9 more.
Why it matters
Run by Compare V9 6 2 to Compiled.
Application
pipelinenews · index · JavaScript module
Uses
UK Renewables Pipeline — V9 6 1 Page (estate URL), UK Renewables Pipeline — V9 6 Page (estate URL), UK Renewables Pipeline — V9 5 1 Page (estate URL), UK Renewables Pipeline — V9 5 Page (estate URL), UK Renewables Pipeline — V9 4 Page (estate URL), UK Renewables Pipeline — V9 Page (estate URL), UK Renewables Pipeline — V8 Page (estate URL), UK Renewables Pipeline — V7 Page (estate URL), and 5 more, node:assert/strict, node:crypto, node:fs, node:fs/promises, node:path, node:url
Used by
run by Compare V9 6 2 to Compiled (script call)
Produces
absolute, sha256, readPinned, replaceExactly, rewriteImports, rewriteModule, rewriteHtml, compileManifest, validateContractsAndNews, inspect, build, writeOutputs
Defines here
absolute, sha256, readPinned, replaceExactly, rewriteImports, rewriteModule, rewriteHtml, compileManifest, validateContractsAndNews, inspect, build, writeOutputs, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 index/202609010836-compile-index.mjs:1-330 · blob 548b141cf892d7ed55995aff27ee9cc6e3aaf026 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { constants } from "node:fs";
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";

const GENERATION = "202609010836";
// The immutable data cartridges were sealed under the original
// generation and are referenced, never copied; their names do not
// change when the release is recompiled.
const DATA_GENERATION = "202608261927";
const COMPILER_FILE = `${GENERATION}-compile-index.mjs`;
const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const PUBLIC_URL = `https://ventusltd.github.io/pipelinenews/releases/${GENERATION}-index.html`;

const MODULES = Object.freeze([
  ["ui/javascript/202608261557-startplugins.js", "startplugins.js"],
  ["ui/javascript/202608261630-utils.js", "utils.js"],
  ["ui/javascript/202608261632-state.js", "state.js"],
  ["ui/javascript/202608261640-filters.js", "filters.js"],
  ["ui/javascript/202608261723-capacity-presentation.js", "capacity-presentation.js"],
  ["ui/javascript/202608261725-gauges.js", "gauges.js"],
  ["ui/javascript/202608261742-news-regions.js", "news-regions.js"],
  ["ui/javascript/202608261752-canonical-projects-v9-1.js", "canonical-projects-v9-1.js"],
  ["ui/javascript/202608261754-canonical-projects-v9-5-1.js", "canonical-projects-v9-5-1.js"],
  ["ui/javascript/202608261755-newspaper-v9-5-1.js", "newspaper-v9-5-1.js"],
  ["ui/javascript/202608261802-newspaper-v9-6-2.js", "newspaper-v9-6-2.js"],
  ["ui/javascript/202608261804-projects-v9-5-1.js", "projects-v9-5-1.js"],
  ["ui/javascript/202608261806-app-v9-6-2.js", "app-v9-6-2.js"],
]);

const STYLES = Object.freeze([
  ["ui/styles/202608261740-v7-foundation.css", "v7-foundation.css"],
  ["ui/styles/202608261614-mobile.css", "mobile.css"],
  ["ui/styles/202608261927-v9-3.css", "v9-3.css"],
  ["ui/styles/202608261927-v9-4.css", "v9-4.css"],
  ["ui/styles/202608261927-v9-5-1.css", "v9-5-1.css"],
  ["ui/styles/202608261927-v9-6-1.css", "v9-6-1.css"],
]);

const INPUTS = Object.freeze({
  template: "ui/templates/202608261927-shell-v9-6-2.html",
  vendor: "ui/vendor/202608261927-chart-umd.min.js",
  releaseV9_1: "data/contracts/202608261927-release-v9-1.json",
  releaseV9_5_1: "data/contracts/202608261737-release-v9-5-1.json",
  releaseV9_6_2: "data/contracts/202608261721-release-v9-6-2.json",
  sourceManifest: "data/manifests/202608261927-build-manifest-v9-1.json",
  news: "data/news/202608261927-major-project-news-v9-5-1.json",
});

const PINNED_SHA256 = Object.freeze({
  "ui/javascript/202608261557-startplugins.js": "e5aaa19b5bee93683fae461f7ead55d019e8c2edc8ce377680c0da634606e378",
  "ui/javascript/202608261630-utils.js": "bec300e2720e0793bc08434e91c0ea0dd8c3d8e36e79b97172e4d5270f01eda0",
  "ui/javascript/202608261632-state.js": "7280acd43f72e166e7b7b3dac1d6e75439b1e1bf46b9e137c1b8aa891b52aad7",
  "ui/javascript/202608261640-filters.js": "007126279582d5dbbe6bb5ebf30a79fd998b4839e8498c5a9a76ab2e4033c842",
  "ui/javascript/202608261723-capacity-presentation.js": "650e2d1ca9fea55d0cb96db58c752e03ac03645499f033d11d4f76d29c917cef",
  "ui/javascript/202608261725-gauges.js": "30803e3ecc787175bc31b6913541d52cc6065e9be2b50dc4d3ed900797348682",
  "ui/javascript/202608261742-news-regions.js": "673126663b69f67c73dfed4f6393e56e7779514e612559f0b6aad88a4354037f",
  "ui/javascript/202608261752-canonical-projects-v9-1.js": "26dd3f1da795717b7e82b317a795658ef0c51338525f65a9c6b43ba2a88c0ebb",
  "ui/javascript/202608261754-canonical-projects-v9-5-1.js": "4e6f3351576c898e0c1c3d5018ae40dd28b0e28a86cb9c513ea8b5e099118060",
  "ui/javascript/202608261755-newspaper-v9-5-1.js": "9a3436bae58d3a982285c2caf77830b11f0a157a99255b623cd822c89bf81549",
  "ui/javascript/202608261802-newspaper-v9-6-2.js": "1a883ff28bb7e5b98e1daba50510d3807e2ed794c93447a851042ac40e9945c8",
  "ui/javascript/202608261804-projects-v9-5-1.js": "af631896921c418943014362b21a967310adb4e85c2cc8e6e99582358ca6194e",
  "ui/javascript/202608261806-app-v9-6-2.js": "371ad15c570df5408e5060dd9e298309a39b183ee7c00dd387c12a3ee57bfc1a",
  "ui/styles/202608261740-v7-foundation.css": "036dbfe43ef1ffb2c55ba277d49dec57ab7c7be976289226a5d568e1f1be319d",
  "ui/styles/202608261614-mobile.css": "9855b9c11255a85f477873d07cca45b057aedcdc8a6cc4aab2d29a0ffaac9b85",
  "ui/styles/202608261927-v9-3.css": "219782d5f3fba11b8418a5b46075a8b1b918eed272f6bc2360f6b1060c1f2e9b",
  "ui/styles/202608261927-v9-4.css": "39f7d0fd3ff42e82407c1f5129444e6cc308ef5c0ec551d43c7396ac53310d17",
  "ui/styles/202608261927-v9-5-1.css": "79ff5b1db85ae82a381fbad061c0122e7151bb9c9c7ba80c549051761f0bfae3",
  "ui/styles/202608261927-v9-6-1.css": "851b0827ca2aa0950438c98ae3cf6cc7dce33667d37458122ea38bb2c6da2f81",
  "ui/templates/202608261927-shell-v9-6-2.html": "06382e57a58e460defcdd3c460ad01b93aa4c4578065348afa846b446e6d34ae",
  "ui/vendor/202608261927-chart-umd.min.js": "48444a82d4edcb5bec0f1965faacdde18d9c17db3063d042abada2f705c9f54a",
  "data/contracts/202608261927-release-v9-1.json": "bc21070f44aae1d32da333e4954816acd907aa8c9fa9cb639c64d651f7fd4259",
  "data/contracts/202608261737-release-v9-5-1.json": "4137a31477be33a04b6ad5406d7cd13cefec1be8d84a94e23997c129c82076f1",
  "data/contracts/202608261721-release-v9-6-2.json": "661bb4f226ac3c75811f9e1d36546602f401491a5c21e1ddebccda170da92ece",
  "data/manifests/202608261927-build-manifest-v9-1.json": "67976a1bbcaf383ed7121b13060db3b864db9ce33dfc721a88b59c8ca8b8e06c",
  "data/news/202608261927-major-project-news-v9-5-1.json": "cea104c3e9cfc07971680afdf5f64073e1d4825b63bfaf4e969266df8386ebbd",
});

const outputModuleName = new Map(MODULES.map(([source, purpose]) => [
  path.posix.basename(source),
  `${GENERATION}-${purpose}`,
]));

function absolute(relativePath) {
  const resolved = path.resolve(REPOSITORY_ROOT, relativePath);
  assert.ok(resolved.startsWith(`${REPOSITORY_ROOT}${path.sep}`), `path escapes repository: ${relativePath}`);
  return resolved;
}

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

async function readPinned(relativePath, encoding = null) {
  const bytes = await readFile(absolute(relativePath));
  assert.equal(sha256(bytes), PINNED_SHA256[relativePath], `input hash changed: ${relativePath}`);
  return encoding ? bytes.toString(encoding) : bytes;
}

function replaceExactly(source, from, to, expectedCount = 1) {
  const actualCount = source.split(from).length - 1;
  assert.equal(actualCount, expectedCount, `replacement count for ${JSON.stringify(from)}`);
  return source.split(from).join(to);
}

function rewriteImports(source) {
  let count = 0;
  const rewritten = source.replace(/(from\s+["'])\.\/([^"']+)(["'])/g, (match, before, basename, after) => {
    const output = outputModuleName.get(basename);
    assert.ok(output, `undeclared module import: ${basename}`);
    count += 1;
    return `${before}./${output}${after}`;
  });
  return { source: rewritten, count };
}

function rewriteModule(sourcePath, source) {
  if (sourcePath.endsWith("202608261632-state.js")) {
    source = replaceExactly(source, "../../dist/major_project_news_v5.json", `../data/news/${DATA_GENERATION}-major-project-news-v9-5-1.json`);
    source = replaceExactly(source, "https://raw.githubusercontent.com/Ventusltd/globalgrid2050/main/dist/major_project_news_v5.json", `../data/news/${DATA_GENERATION}-major-project-news-v9-5-1.json`);
  }
  if (sourcePath.endsWith("202608261752-canonical-projects-v9-1.js")) {
    source = replaceExactly(source, "contracts/release.v9.1.json", `../data/contracts/${DATA_GENERATION}-release-v9-1.json`);
    source = replaceExactly(source, "data/v9.1/build_manifest.json", `manifests/${GENERATION}-build-manifest-v9-1.json`);
  }
  if (sourcePath.endsWith("202608261754-canonical-projects-v9-5-1.js")) {
    source = replaceExactly(source, "contracts/release.v9.5.1.json", "../data/contracts/202608261737-release-v9-5-1.json");
  }
  if (sourcePath.endsWith("202608261755-newspaper-v9-5-1.js")) {
    const original = `const NEWS_SOURCES = Object.freeze([\n  ["Pages", "../../dist/major_project_news_v9_5_1.json"],\n  ["GitHub main", "https://raw.githubusercontent.com/Ventusltd/globalgrid2050/main/dist/major_project_news_v9_5_1.json"],\n]);`;
    const replacement = `const NEWS_SOURCES = Object.freeze([\n  ["PipelineNews", "../data/news/${DATA_GENERATION}-major-project-news-v9-5-1.json"],\n]);`;
    source = replaceExactly(source, original, replacement);
  }
  return rewriteImports(source);
}

function rewriteHtml(source) {
  const replacements = [
    ["styles/v7.css?v=9.6.2", `styles/${GENERATION}-v7-foundation.css`],
    ["styles/mobile.css?v=9.6.2", `styles/${GENERATION}-mobile.css`],
    ["styles/v9-3.css?v=9.6.2", `styles/${GENERATION}-v9-3.css`],
    ["styles/v9-4.css?v=9.6.2", `styles/${GENERATION}-v9-4.css`],
    ["styles/v9-5-1.css?v=9.6.2", `styles/${GENERATION}-v9-5-1.css`],
    ["styles/v9-6-1.css?v=9.6.2", `styles/${GENERATION}-v9-6-1.css`],
    ["https://cdn.jsdelivr.net/npm/chart.js", `vendor/${GENERATION}-chart-umd.min.js`],
    ["scripts/app-v9-6-2.js?v=9.6.2", `javascript/${GENERATION}-app-v9-6-2.js`],
    ["scripts/plugins/capacity-presentation-v9-3.js?v=9.6.2", `javascript/${GENERATION}-capacity-presentation.js`],
    ["../v9.6.1/", "https://globalgrid2050.com/uk_renewables_pipeline/v9.6.1/"],
    ["../v9.6/", "https://globalgrid2050.com/uk_renewables_pipeline/v9.6/"],
    ["../v9.5.1/", "https://globalgrid2050.com/uk_renewables_pipeline/v9.5.1/"],
    ["../v9.5/", "https://globalgrid2050.com/uk_renewables_pipeline/v9.5/"],
    ["../v9.4/", "https://globalgrid2050.com/uk_renewables_pipeline/v9.4/"],
    ["../v9/", "https://globalgrid2050.com/uk_renewables_pipeline/v9/"],
    ["../v8/", "https://globalgrid2050.com/uk_renewables_pipeline/v8/"],
    ["../v7/", "https://globalgrid2050.com/uk_renewables_pipeline/v7/"],
    ["../dashboard_v6_live.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v6_live.html"],
    ["../dashboard_v5_live.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v5_live.html"],
    ["../dashboard_v4_live.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v4_live.html"],
    ["../dashboard_v3_live_2026-08-22.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v3_live_2026-08-22.html"],
    ["../dashboard_v2_2026-08-22.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard_v2_2026-08-22.html"],
    ["../dashboard.html", "https://globalgrid2050.com/uk_renewables_pipeline/dashboard.html"],
    ["../../index.html", "https://globalgrid2050.com/"],
    ["../../repd_grid_atlasv8/", "https://ventusltd.github.io/gridatlas/202608300453-atlas-v9/"],
  ];
  for (const [from, to] of replacements) source = replaceExactly(source, from, to);
  return { source, replacements: replacements.length };
}

async function compileManifest(inputRecords) {
  const raw = await readPinned(INPUTS.sourceManifest, "utf8");
  const manifest = JSON.parse(raw);
  assert.equal(manifest.project_partitions.length, 16);
  assert.equal(manifest.atlas_partitions.length, 18);
  let projectCount = 0;
  for (let index = 0; index < manifest.project_partitions.length; index += 1) {
    const entry = manifest.project_partitions[index];
    const cartridge = `data/projects/${DATA_GENERATION}-project-partition-v9-1-${String(index + 1).padStart(2, "0")}.json`;
    const bytes = await readFile(absolute(cartridge));
    assert.equal(sha256(bytes), entry.sha256, `project partition hash ${index + 1}`);
    const payload = JSON.parse(bytes);
    assert.equal(payload.record_count, entry.record_count);
    assert.equal(payload.projects.length, entry.record_count);
    projectCount += payload.projects.length;
    inputRecords.push({ path: cartridge, bytes: bytes.length, sha256: sha256(bytes) });
    entry.path = `../${cartridge}`;
  }
  assert.equal(projectCount, 7680);

  for (const entry of manifest.atlas_partitions) {
    const match = entry.path.match(/atlas\/(.+)-part-(\d+)\.geojson$/);
    assert.ok(match, `invalid atlas path ${entry.path}`);
    const technology = match[1].replaceAll("_", "-");
    const cartridge = `data/atlas/${DATA_GENERATION}-atlas-${technology}-partition-v9-1-${match[2]}.geojson`;
    const bytes = await readFile(absolute(cartridge));
    assert.equal(sha256(bytes), entry.sha256, `atlas partition hash ${entry.path}`);
    const payload = JSON.parse(bytes);
    assert.equal(payload.features.length, entry.feature_count);
    inputRecords.push({ path: cartridge, bytes: bytes.length, sha256: sha256(bytes) });
    entry.path = `../${cartridge}`;
  }
  return `${JSON.stringify(manifest, null, 2)}\n`;
}

async function validateContractsAndNews(inputRecords) {
  for (const contractPath of [INPUTS.releaseV9_1, INPUTS.releaseV9_5_1, INPUTS.releaseV9_6_2]) {
    const bytes = await readPinned(contractPath);
    JSON.parse(bytes);
    inputRecords.push({ path: contractPath, bytes: bytes.length, sha256: sha256(bytes) });
  }
  const newsBytes = await readPinned(INPUTS.news);
  const news = JSON.parse(newsBytes);
  assert.equal(news.all_items.length, 133);
  assert.equal(news.canonical_items.length, 45);
  const prohibited = new Set(["author", "author_name", "reporter", "first_name", "last_name", "editor_name", "person_name", "contact_name"]);
  const inspect = (value) => {
    if (Array.isArray(value)) value.forEach(inspect);
    else if (value && typeof value === "object") {
      for (const [key, child] of Object.entries(value)) {
        assert.equal(prohibited.has(key.toLowerCase()), false, `prohibited person field: ${key}`);
        inspect(child);
      }
    }
  };
  inspect(news);
  inputRecords.push({ path: INPUTS.news, bytes: newsBytes.length, sha256: sha256(newsBytes) });
}

async function build() {
  assert.equal(path.basename(fileURLToPath(import.meta.url)), COMPILER_FILE);
  const outputs = new Map();
  const inputRecords = [];
  let importRewrites = 0;

  for (const [sourcePath, purpose] of MODULES) {
    const source = await readPinned(sourcePath, "utf8");
    inputRecords.push({ path: sourcePath, bytes: Buffer.byteLength(source), sha256: sha256(source) });
    const rewritten = rewriteModule(sourcePath, source);
    importRewrites += rewritten.count;
    outputs.set(`releases/javascript/${GENERATION}-${purpose}`, rewritten.source);
  }
  assert.equal(importRewrites, 18);

  for (const [sourcePath, purpose] of STYLES) {
    const bytes = await readPinned(sourcePath);
    inputRecords.push({ path: sourcePath, bytes: bytes.length, sha256: sha256(bytes) });
    outputs.set(`releases/styles/${GENERATION}-${purpose}`, bytes);
  }

  const template = await readPinned(INPUTS.template, "utf8");
  inputRecords.push({ path: INPUTS.template, bytes: Buffer.byteLength(template), sha256: sha256(template) });
  const html = rewriteHtml(template);
  outputs.set(`releases/${GENERATION}-index.html`, html.source);

  const vendor = await readPinned(INPUTS.vendor);
  inputRecords.push({ path: INPUTS.vendor, bytes: vendor.length, sha256: sha256(vendor) });
  outputs.set(`releases/vendor/${GENERATION}-chart-umd.min.js`, vendor);

  await validateContractsAndNews(inputRecords);
  const compiledManifest = await compileManifest(inputRecords);
  inputRecords.push({ path: INPUTS.sourceManifest, bytes: Buffer.byteLength(await readPinned(INPUTS.sourceManifest, "utf8")), sha256: PINNED_SHA256[INPUTS.sourceManifest] });
  outputs.set(`releases/manifests/${GENERATION}-build-manifest-v9-1.json`, compiledManifest);

  const outputRecords = [...outputs.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([outputPath, content]) => {
    const bytes = Buffer.isBuffer(content) ? content : Buffer.from(content);
    return { path: outputPath, bytes: bytes.length, sha256: sha256(bytes) };
  });
  const compilerBytes = await readFile(fileURLToPath(import.meta.url));
  const releaseManifest = {
    schema: "pipelinenews.compiled-release.v1",
    generation: `${GENERATION}-index`,
    trusted_parent: "GlobalGrid2050 V9.6.2",
    public_url: PUBLIC_URL,
    status: "COMPILED_AWAITING_BROWSER_ATTESTATION",
    compiler: { path: `index/${COMPILER_FILE}`, sha256: sha256(compilerBytes) },
    discipline: {
      stable_folders: true,
      timestamped_files: true,
      source_mutation: false,
      data_cartridges_copied: false,
      release_references_immutable_data_cartridges: true,
    },
    substitutions: {
      javascript_imports: importRewrites,
      html_asset_and_navigation_urls: html.replacements,
      mutable_news_sources_removed: true,
      project_manifest_paths: 16,
      atlas_manifest_paths: 18,
      chart_js_pinned_locally: "4.5.1",
    },
    inputs: inputRecords.sort((left, right) => left.path.localeCompare(right.path)),
    outputs: outputRecords,
  };
  outputs.set(`releases/manifests/${GENERATION}-release-manifest.json`, `${JSON.stringify(releaseManifest, null, 2)}\n`);
  return { outputs, releaseManifest };
}

async function writeOutputs(outputs) {
  for (const outputPath of outputs.keys()) {
    try {
      await access(absolute(outputPath), constants.F_OK);
      assert.fail(`immutable output already exists: ${outputPath}`);
    } catch (error) {
      if (error.code !== "ENOENT") throw error;
    }
  }
  for (const [outputPath, content] of outputs) {
    await mkdir(path.dirname(absolute(outputPath)), { recursive: true });
    await writeFile(absolute(outputPath), content, { flag: "wx" });
  }
}

async function main() {
  const { outputs, releaseManifest } = await build();
  if (!process.argv.includes("--check")) await writeOutputs(outputs);
  process.stdout.write(`${JSON.stringify({
    generation: releaseManifest.generation,
    public_url: PUBLIC_URL,
    output_files: outputs.size,
    input_files: releaseManifest.inputs.length,
    project_count: 7680,
    status: process.argv.includes("--check") ? "CHECKED" : "COMPILED",
  }, null, 2)}\n`);
}

main().catch((error) => {
  process.stderr.write(`${error.stack || error.message}\n`);
  process.exitCode = 1;
});

PipelineNews — News

A Python module.

otherpipelinenews / news/__init__.py · lines 1–1 of 1

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.
Downstream impact
Used directly by 1 file: Build RSS Candidate (pipelinenews). Reached from 1 other entry point, including PipelineNews Coverage Contract Workflow (pipelinenews).
What it achieves
PipelineNews news collection algorithms.
Why it matters
Run by Build RSS Candidate.
Application
pipelinenews · news · Python module
Uses
none found
Used by
run by Build RSS Candidate (script call)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 news/__init__.py:1-1 · blob 85b6987905610db9d36fc5a9dfe4b9bfe2587dc3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""PipelineNews news collection algorithms."""

News — BBC

A Python module in PipelineNews.

otherpipelinenews / news/bbc/__init__.py · lines 1–1 of 1

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.
Downstream impact
Used directly by 1 file: Build RSS Candidate (pipelinenews). Reached from 1 other entry point, including PipelineNews Coverage Contract Workflow (pipelinenews).
What it achieves
BBC RSS collection and article metadata rules.
Why it matters
Run by Build RSS Candidate.
Application
pipelinenews · news/bbc · Python module
Uses
none found
Used by
run by Build RSS Candidate (script call)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 news/bbc/__init__.py:1-1 · blob ca91f8fa50bfb0d7ab42ba56308798c54b79cc0d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""BBC RSS collection and article metadata rules."""

Articles

A Python module in the bbc folder of PipelineNews that parses feed (`parse_feed`).

ingestpipelinenews / news/bbc/articles.py · lines 1–75 of 75 · pattern canonical_article (shared by 2 files)

What it does
It lists and searches its content. Defines canonical_article, parse_feed, merge_items, recent. Uses libraries datetime, email.utils, re, urllib.parse, xml.etree.ElementTree.
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. README: "`bbc/articles.py` validates and filters RSS items, canonicalises BBC links, and merges observations with 30-day retention."
Downstream impact
Used directly by 4 files: BBC RSS (pipelinenews); Collector (pipelinenews); Test BBC RSS (pipelinenews); Build RSS Candidate (pipelinenews). Reached from 2 other entry points, including PipelineNews BBC RSS Discovery Workflow (pipelinenews); PipelineNews Coverage Contract Workflow (pipelinenews).
What it achieves
It is built from the canonical article helper (`canonical_article`), the merge items helper (`merge_items`) and the recent step (`recent`). Parse, identify and retain BBC article metadata.
Why it matters
Imported by BBC RSS and Collector. Run by Build RSS Candidate. Checked by Test BBC RSS.
Application
pipelinenews · news/bbc · Python module
Uses
Sources (relative import), datetime, email.utils, re, urllib.parse, xml.etree.ElementTree
Used by
imported by BBC RSS (import), imported by Collector (relative import), imported by Test BBC RSS (import), run by Build RSS Candidate (script call)
Produces
canonical_article, parse_feed, merge_items
Defines here
canonical_article, parse_feed, merge_items, recent
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 news/bbc/articles.py:1-75 · blob 8c6bbc6ac1e260d73b54479f5bb6dd16aa70e488 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Parse, identify and retain BBC article metadata."""

import datetime as dt
import email.utils
import re
import urllib.parse
import xml.etree.ElementTree as ET

from .sources import MAX_BYTES, MAX_ITEMS

TOPIC = re.compile(r'\b(solar|photovoltaic|wind farm|battery storage|energy storage|electricity grid|substation)\b', re.I)


def canonical_article(value):
    u = urllib.parse.urlsplit(value)
    if u.scheme != 'https' or u.hostname not in ('www.bbc.co.uk', 'www.bbc.com') or u.username or u.password or u.port:
        raise ValueError('not a BBC article URL')
    if not re.fullmatch(r'/news/articles/[a-z0-9]+', u.path):
        raise ValueError('not a BBC article path')
    # RSS campaign parameters are attribution, not a second news identity.
    return 'https://www.bbc.co.uk' + u.path


def parse_feed(body, feed_url, observed_at):
    if len(body) > MAX_BYTES or b'<!DOCTYPE' in body.upper() or b'<!ENTITY' in body.upper():
        raise ValueError('RSS exceeds bound or contains a DTD/entity declaration')
    root = ET.fromstring(body)
    if root.tag != 'rss' or root.find('channel') is None:
        raise ValueError('not an RSS channel')
    result = []
    for item in root.findall('./channel/item')[:MAX_ITEMS]:
        try:
            url = canonical_article(item.findtext('link', '').strip())
        except ValueError:
            continue
        headline = ' '.join(item.findtext('title', '').split())[:300]
        # Description is used only to find relevant links; no article body is retained.
        description = item.findtext('description', '')[:2000]
        if not headline or not TOPIC.search(headline + ' ' + description):
            continue
        published = None
        try:
            parsed = email.utils.parsedate_to_datetime(item.findtext('pubDate', ''))
            if parsed.tzinfo is not None:
                published = parsed.astimezone(dt.timezone.utc).isoformat()
        except (ValueError, TypeError, OverflowError):
            pass
        result.append({'id': 'bbc:' + url.rsplit('/', 1)[1], 'url': url,
                       'headline': headline, 'publisher': 'BBC News',
                       'source_published_at': published, 'first_observed_at': observed_at,
                       'last_seen_at': observed_at, 'feed_urls': [feed_url],
                       'repd_ref': None, 'binding_status': 'UNMATCHED_REQUIRES_REVIEW',
                       'eligible_for_project_signal': False})
    return result


def merge_items(previous, incoming, now):
    cutoff = now - dt.timedelta(days=30)
    kept = {}
    for item in previous + incoming:
        identity = item['id']
        if identity in kept:
            old = kept[identity]
            item = dict(item, first_observed_at=old['first_observed_at'],
                        feed_urls=sorted(set(old['feed_urls'] + item['feed_urls'])))
        kept[identity] = item
    def recent(item):
        # Missing dates stay missing; observation is used only for retention.
        try:
            value = dt.datetime.fromisoformat(item['source_published_at'] or item['last_seen_at'])
            return value.tzinfo is not None and value >= cutoff
        except (ValueError, TypeError):
            return False
    return sorted((x for x in kept.values() if recent(x)),
                  key=lambda x: (x['source_published_at'] or '', x['id']), reverse=True)[:MAX_ITEMS]

Collector

A Python command-line tool in the bbc folder of PipelineNews that fetches bbc rss and the Renewable Energy Planning Database (REPD) register, using SHA-256.

storagepipelinenews / news/bbc/collector.py · lines 1–75 of 75 · Entry point · pattern NoRedirect (shared by 2 files)

What it does
It fetches bbc rss and the REPD register. Defines NoRedirect, redirect_request, collect, main. Uses libraries argparse, datetime, hashlib, json, pathlib. Side effects: reads or writes files; makes network requests.
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: the REPD register. README: "`bbc/collector.py` fetches feeds, records health and checks the manual inbox."
Inputs & outputs
In: JSON file bbc-rss.json; command-line arguments.
Downstream impact
Used directly by 3 files: BBC RSS (pipelinenews); Test BBC RSS (pipelinenews); Build RSS Candidate (pipelinenews). Reached from 2 other entry points, including PipelineNews BBC RSS Discovery Workflow (pipelinenews); PipelineNews Coverage Contract Workflow (pipelinenews).
What it achieves
It is built from the no redirect class (`NoRedirect`), the redirect request helper (`redirect_request`) and the collect step (`collect`). Collect bounded BBC RSS metadata and write a single collection receipt. It accepts `--output` and `--previous`.
Why it matters
Imported by BBC RSS. Run by Build RSS Candidate. Checked by Test BBC RSS.
Application
pipelinenews · news/bbc · Python CLI
Uses
Articles (relative import), Sources (relative import), argparse, datetime, hashlib, json, pathlib, urllib.request
Used by
imported by BBC RSS (import), imported by Test BBC RSS (import), run by Build RSS Candidate (script call)
Produces
NoRedirect, collect, main
Defines here
NoRedirect, redirect_request, collect, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 news/bbc/collector.py:1-75 · blob 8880d3a31dbd805b744156984667db58272caa35 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Collect bounded BBC RSS metadata and write a single collection receipt."""

import argparse
import datetime as dt
import hashlib
import json
import pathlib
import urllib.request

from .articles import canonical_article, merge_items, parse_feed
from .sources import MAX_BYTES, MAX_ITEMS, SECTIONS, feed_urls


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        raise ValueError('feed redirect rejected')


def collect(previous, now, fetch=None):
    observed = now.isoformat()
    incoming, health = [], []
    opener = urllib.request.build_opener(NoRedirect)
    for url in feed_urls():
        try:
            if fetch:
                body = fetch(url)
            else:
                req = urllib.request.Request(url, headers={'User-Agent':'PipelineNews-RSS/1.0', 'Accept':'application/rss+xml, application/xml'})
                with opener.open(req, timeout=10) as response:
                    body = response.read(MAX_BYTES + 1)
            items = parse_feed(body, url, observed)
            incoming.extend(items)
            health.append({'url':url, 'status':'ok', 'items':len(items), 'sha256':hashlib.sha256(body).hexdigest()})
        except Exception as error:
            health.append({'url':url, 'status':'failed', 'error':type(error).__name__ + ': ' + str(error)[:180]})
    ok = sum(x['status'] == 'ok' for x in health)
    return {'schema':'pipelinenews.bbc-rss.v1', 'checked_at':observed,
            'last_success_at':observed if ok else previous.get('last_success_at'),
            'status':'ok' if ok == len(SECTIONS) else 'partial' if ok else 'failed',
            'items':merge_items(previous.get('items', []), incoming, now), 'feeds':health,
            'limits':{'feeds':len(SECTIONS), 'bytes_per_feed':MAX_BYTES, 'retained_items':MAX_ITEMS, 'retention_days':30},
            'attribution':'BBC News', 'source':'https://www.bbc.co.uk/news',
            'scope':'RSS headlines and links; no article-page requests; no inferred REPD match.'}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--output', default='discovery/products/bbc-rss.json')
    parser.add_argument('--previous', type=pathlib.Path, help='Previous receipt (defaults to the output path)')
    args = parser.parse_args()
    path = pathlib.Path(args.output)
    previous_path = args.previous or path
    previous = json.loads(previous_path.read_text(encoding='utf-8')) if previous_path.exists() else {}
    result = collect(previous, dt.datetime.now(dt.timezone.utc))
    result['submitted_articles'] = []
    for receipt in sorted(pathlib.Path('discovery/inbox').glob('*.json')):
        intake = json.loads(receipt.read_text(encoding='utf-8'))
        if intake.get('schema') != 'pipelinenews.manual-url-intake.v1':
            continue
        url = canonical_article(intake['submitted_url'])
        found = next((item for item in result['items'] if item['url'] == url), None)
        result['submitted_articles'].append({'url':url, 'intake_id':intake['intake_id'],
            'status':'FOUND_IN_RSS' if found else 'NOT_SEEN_IN_FETCHED_RSS',
            'headline':found['headline'] if found else None,
            'note':'Not seen does not mean absent from BBC or REPD; RSS is a rolling feed.'})
    path.parent.mkdir(parents=True, exist_ok=True)
    temp = path.with_suffix('.tmp')
    temp.write_text(json.dumps(result, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
    temp.replace(path)
    print(json.dumps({'status':result['status'], 'items':len(result['items']), 'feeds':len(result['feeds']), 'output':str(path)}))
    return 1 if result['status'] == 'failed' else 0


if __name__ == '__main__':
    raise SystemExit(main())

Sources

A Python module in the bbc folder of PipelineNews that works with feed urls (`feed_urls`).

transformpipelinenews / news/bbc/sources.py · lines 1–17 of 17

What it does
It calculates its inputs. Defines feed_urls.
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. README: "`bbc/sources.py` defines the feed sections and input limits."
Downstream impact
Used directly by 5 files: BBC RSS (pipelinenews); Articles (pipelinenews); Collector (pipelinenews); Test BBC RSS (pipelinenews); and 1 more. Reached from 2 other entry points, including PipelineNews BBC RSS Discovery Workflow (pipelinenews); PipelineNews Coverage Contract Workflow (pipelinenews).
What it achieves
BBC feed inventory and request limits.
Why it matters
Imported by BBC RSS, Articles and Collector. Run by Build RSS Candidate. Checked by Test BBC RSS.
Application
pipelinenews · news/bbc · Python module
Uses
none found
Used by
imported by BBC RSS (import), imported by Articles (relative import), imported by Collector (relative import), imported by Test BBC RSS (import), run by Build RSS Candidate (script call)
Produces
feed_urls
Defines here
feed_urls
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 news/bbc/sources.py:1-17 · blob 21f98b4f2d06067b92c104811c7ebe7dd4b3e8f7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""BBC feed inventory and request limits."""

SECTIONS = ('science_and_environment', 'business', 'england', 'scotland', 'wales',
            'northern_ireland', 'uk', 'england/lincolnshire', 'england/cambridgeshire',
            'england/norfolk', 'england/suffolk', 'england/nottingham',
            'england/essex', 'england/kent', 'england/oxford', 'england/wiltshire',
            'england/somerset', 'england/devon', 'england/cornwall', 'england/lancashire',
            'england/cumbria', 'england/tees', 'england/north_yorkshire',
            'england/south_yorkshire', 'england/leicester', 'england/derbyshire',
            'england/northamptonshire', 'england/hampshire', 'england/shropshire',
            'england/stoke_and_staffordshire', 'england/hereford_and_worcester')
MAX_BYTES = 1_048_576
MAX_ITEMS = 500


def feed_urls():
    return (f"https://feeds.bbci.co.uk/news/{section}/rss.xml" for section in SECTIONS)

Test BBC RSS

A test in the tests folder of PipelineNews that checks Articles and Collector.

testpipelinenews / news/tests/test_bbc_rss.py · lines 1–77 of 77 · Entry point · pattern test_feed_failure_retains_last_good_without_freshness_claim (shared by 2 files)

What it does
It tests its inputs. Defines 9 functions or classes, including RssTests, test_feed_item_stays_unmatched, test_retry_and_cross_feed_deduplication, test_missing_date_never_becomes_collection_date, test_unsafe_urls_and_xml_are_rejected. Uses libraries datetime, json, tempfile, unittest, pathlib. Side effects: 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. README: "`tests/test_bbc_rss.py` covers collection and article boundaries using offline fixtures."
Inputs & outputs
In: JSON file previous.json; JSON file probe.json; command-line arguments.
Downstream impact
Used directly by 2 files: PipelineNews BBC RSS Discovery Workflow (pipelinenews); PipelineNews Coverage Contract Workflow (pipelinenews).
What it achieves
It is built from the rss tests class (`RssTests`), the fail step (`fail`) and the offline collection helper (`offline_collection`). The README says: `tests/test_bbc_rss.py` covers collection and article boundaries using offline fixtures.
Why it matters
Run by PipelineNews BBC RSS Discovery Workflow and PipelineNews Coverage Contract Workflow.
Application
pipelinenews · news/tests · test
Uses
Articles (import), Collector (import), Sources (import), datetime, json, tempfile, unittest, pathlib, unittest.mock
Used by
run by PipelineNews BBC RSS Discovery Workflow (workflow run), run by PipelineNews Coverage Contract Workflow (workflow run)
Produces
RssTests
Defines here
RssTests, test_feed_item_stays_unmatched, test_retry_and_cross_feed_deduplication, test_missing_date_never_becomes_collection_date, test_unsafe_urls_and_xml_are_rejected, test_feed_failure_retains_last_good_without_freshness_claim, fail, test_probe_writes_failed_receipt_without_overwriting_previous, offline_collection
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 news/tests/test_bbc_rss.py:1-77 · blob 34ee8c54830c2c475e8446976fc564e8066e0752 · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import datetime as dt
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from news.bbc.articles import canonical_article, merge_items, parse_feed
from news.bbc.collector import collect, main
from news.bbc.sources import SECTIONS

NOW = dt.datetime(2026, 9, 6, tzinfo=dt.timezone.utc)
RSS = b'''<rss><channel><item><title>New solar farm proposed</title><link>https://www.bbc.co.uk/news/articles/c4gmkezn4nlo?at_campaign=rss</link><pubDate>Sat, 05 Sep 2026 10:00:00 GMT</pubDate></item></channel></rss>'''


class RssTests(unittest.TestCase):
    def test_feed_item_stays_unmatched(self):
        item = parse_feed(RSS, 'feed', NOW.isoformat())[0]
        self.assertEqual(item['url'], 'https://www.bbc.co.uk/news/articles/c4gmkezn4nlo')
        self.assertIsNone(item['repd_ref'])
        self.assertFalse(item['eligible_for_project_signal'])
        self.assertEqual(item['source_published_at'], '2026-09-05T10:00:00+00:00')

    def test_retry_and_cross_feed_deduplication(self):
        a = parse_feed(RSS, 'feed-a', NOW.isoformat())
        b = parse_feed(RSS, 'feed-b', NOW.isoformat())
        result = merge_items(a, b+b, NOW)
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0]['feed_urls'], ['feed-a','feed-b'])

    def test_missing_date_never_becomes_collection_date(self):
        item = parse_feed(RSS.replace(b'<pubDate>Sat, 05 Sep 2026 10:00:00 GMT</pubDate>', b''), 'feed', NOW.isoformat())[0]
        self.assertIsNone(item['source_published_at'])

    def test_unsafe_urls_and_xml_are_rejected(self):
        for value in ['http://www.bbc.co.uk/news/articles/a', 'https://evil.test/news/articles/a', 'https://www.bbc.co.uk@evil.test/news/articles/a']:
            with self.assertRaises(ValueError): canonical_article(value)
        for body in [b'<!DOCTYPE rss><rss><channel/></rss>', b'<html/>', b'x'*1048577]:
            with self.assertRaises(ValueError): parse_feed(body, 'feed', NOW.isoformat())

    def test_feed_failure_retains_last_good_without_freshness_claim(self):
        previous = {'items':parse_feed(RSS,'feed',NOW.isoformat()),'last_success_at':'2026-09-05T10:00:00+00:00'}
        calls=[]
        def fail(url):
            calls.append(url)
            raise OSError('offline')
        result=collect(previous,NOW,fail)
        self.assertEqual(result['status'],'failed')
        self.assertEqual(result['last_success_at'],previous['last_success_at'])
        self.assertEqual(len(result['items']),1)
        self.assertEqual(len(calls),len(SECTIONS))
        self.assertTrue(all(url.startswith('https://feeds.bbci.co.uk/') for url in calls))


    def test_probe_writes_failed_receipt_without_overwriting_previous(self):
        observed = NOW.isoformat()
        previous = {'items': parse_feed(RSS, 'feed', observed), 'last_success_at': observed}

        def offline_collection(prior, _now):
            self.assertEqual(prior, previous)
            return collect(prior, NOW, fetch=lambda url: b'<html/>')

        with tempfile.TemporaryDirectory() as directory:
            previous_path = Path(directory) / 'previous.json'
            output = Path(directory) / 'probe.json'
            previous_path.write_text(json.dumps(previous), encoding='utf-8')
            args = ['collector', '--previous', str(previous_path), '--output', str(output)]
            with patch('sys.argv', args), patch('news.bbc.collector.collect', offline_collection), patch('builtins.print'):
                self.assertEqual(main(), 1)
            self.assertEqual(json.loads(previous_path.read_text(encoding='utf-8')), previous)
            receipt = json.loads(output.read_text(encoding='utf-8'))
            self.assertEqual(receipt['status'], 'failed')
            self.assertEqual(receipt['last_success_at'], observed)
            self.assertEqual(receipt['items'], previous['items'])


if __name__ == '__main__':
    unittest.main()