GLOBALGRID2050 / EXPLORE CODE

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

Verify Wider Fleet Deep Link and 6 more files

A JavaScript module in the intelligence folder of PipelineNews that reads the Renewable Energy Planning Database (REPD) register.

611 lines of JavaScript from pipelinenews, in 7 files. Topic: Electricity markets and data pipelines. Section 1034 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Verify Wider Fleet Deep Link ingest · pipelinenews / tools/intelligence/202609030132-verify-wider-fleet-deep-link.mjs lines 1–245
  2. Sector Ledger Relevance Proof ingest · pipelinenews / tools/intelligence/audits/202609010015-sector-ledger-relevance-proof.mjs lines 1–94
  3. Sector Topic Relevance Audit ingest · pipelinenews / tools/intelligence/audits/sector_topic_relevance_audit.mjs lines 1–74
  4. Build BBC RSS Package render · pipelinenews / tools/intelligence/build-bbc-rss-package.mjs lines 1–39
  5. Build Provisional Package render · pipelinenews / tools/intelligence/build-provisional-package.mjs lines 1–30
  6. BBC RSS Pipeline Model energy-data · pipelinenews / tools/intelligence/cartridges/bbc-rss-intelligence/assets/{GEN}-bbc-rss-pipeline-model.mjs lines 1–73
  7. BBC RSS Pipeline energy-data · pipelinenews / tools/intelligence/cartridges/bbc-rss-intelligence/assets/{GEN}-bbc-rss-pipeline.mjs lines 1–56

Verify Wider Fleet Deep Link

A JavaScript module in the intelligence folder of PipelineNews that reads the Renewable Energy Planning Database (REPD) register.

ingestpipelinenews / tools/intelligence/202609030132-verify-wider-fleet-deep-link.mjs · lines 1–245 of 245 · version 2026-09-03 01:32 · Not reached from any entry point (candidate for review) · pattern identity (shared by 11 files)

What it does
It loads the REPD register. Defines check, exists, identity, report. Uses libraries node:fs/promises, node:fs, node:path, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file 202608291447-registry.json; JSON file current.json; command-line arguments.
What it achieves
It is built from the check step (`check`), the exists step (`exists`) and the identity step (`identity`). The WIDER FLEET deep link, and the payload behind it.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · tools/intelligence · JavaScript module
Uses
node:fs/promises, node:fs, node:path, node:url
Used by
none found
Produces
check, exists, identity, report
Defines here
check, exists, identity, report
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/202609030132-verify-wider-fleet-deep-link.mjs:1-245 · blob 5130687abcf81f9a517384fe03aeec916e5b7cd2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * The WIDER FLEET deep link, and the payload behind it.
 *
 * Generation 202609030132. Written because two questions turned out to have
 * no owner.
 *
 * FIRST: Pipeline News has TWO deep-link emitters, and the contract verifier
 * reads one of them.
 *
 *   tools/.../cartridges/atlas-live-handoff/assets/{GEN}-atlas-pointer-deep-link.mjs
 *       the spine's MAP link, `searchParams.set(...)`
 *       checked by 202609012300-verify-atlas-deep-link-contract.mjs
 *
 *   tools/.../cartridges/wider-fleet/assets/{GEN}-wider-fleet.mjs
 *       the wider fleet's own MAP link, `query.set(...)` inside atlasLink()
 *       checked by nothing until this file
 *
 * SECOND, and this is the one that matters: 202609012300 proves the two sides
 * agree on the NAMES of the seven parameters. It passes 11/11. Nobody had
 * asked what happens to the VALUES.
 *
 * GridAtlas validates the technology parameter against a four-member set,
 * in the live composition:
 *
 *     const allowedTechnologies = new Set(['solar', 'bess', 'wind_onshore', 'wind_offshore']);
 *     if (!allowedTechnologies.has(requestedTechnology))
 *         throw new Error('canonical project technology is invalid');
 *
 * Those four are exactly SPINE_TYPES in the wider fleet's own payload builder
 * -- the four REPD technology types the wider fleet is DEFINED as excluding.
 * So every technology value this payload can carry is outside the set, and
 * every wider-fleet MAP link fails that lane by construction. It is not a data
 * error and it is not fixed by sending the REPD type name instead: there is no
 * value this side can send that the set accepts.
 *
 * This check does not decide who should change. It makes the question
 * answerable from a command line instead of from a screenshot.
 *
 *   node tools/intelligence/202609030132-verify-wider-fleet-deep-link.mjs <release-id>
 *   node ... <release-id> --gridatlas <path>
 *
 * No network. Reads the release directory and the sibling GridAtlas checkout.
 * It does NOT skip when GridAtlas is absent, for the reason 202609012300 gives:
 * a cross-repository check that passes when it cannot see the other repository
 * is green exactly where nobody is watching.
 */

import { readFile, access } from 'node:fs/promises';
import { constants } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = resolve(HERE, '..', '..');
const RELEASES = join(REPO, 'releases');

const releaseId = process.argv[2];
if (!releaseId || releaseId.startsWith('--')) {
  console.error('usage: node 202609030132-verify-wider-fleet-deep-link.mjs <release-id> [--gridatlas <path>]');
  process.exit(2);
}
const argAt = process.argv.indexOf('--gridatlas');
const SIBLING = argAt > 0 ? resolve(process.argv[argAt + 1]) : resolve(REPO, '..', 'gridatlas');

let passed = 0;
const failures = [];
function check(name, condition, detail = '') {
  if (condition) { passed += 1; console.log(`PASS  ${name}`); }
  else {
    failures.push(`${name}${detail ? `: ${detail}` : ''}`);
    console.error(`FAIL  ${name}${detail ? `: ${detail}` : ''}`);
  }
}
const exists = async (path) => {
  try { await access(path, constants.R_OK); return true; } catch { return false; }
};

/* ── the release: cartridge, payload, and what the link carries ─────────── */

const root = join(RELEASES, releaseId);
const generation = releaseId.slice(0, 12);

/* WHERE THE CARTRIDGE ACTUALLY IS.
 *
 * This used to be `assets/${releaseId.slice(0,12)}-wider-fleet.mjs`, which
 * assumes the asset is named after the release reading it. That holds for
 * exactly one release -- the one that ADDED the cartridge. Every release built
 * on top of it inherits the file under the older generation's name, so the
 * check reported "the release carries a wider-fleet cartridge: FAIL" for a
 * release that carries it perfectly well, and stopped before it read anything.
 * Measured on 202609031307, the first generation to inherit it.
 *
 * The registry is the authority for where a supplemental asset lives -- it is
 * the file app.mjs itself resolves the import from -- so ask it, and fall back
 * to the old guess only when there is no registry entry to ask.
 */
const registryPath = join(root, 'data', '202608291447-registry.json');
let cartridgeRelative = `assets/${generation}-wider-fleet.mjs`;
let payloadRelative = `data/${generation}-wider-fleet.json`;
if (await exists(registryPath)) {
  const entry = JSON.parse(await readFile(registryPath, 'utf8'))
    .supplemental_assets?.wider_fleet;
  if (entry?.cartridge?.path) cartridgeRelative = entry.cartridge.path;
  if (entry?.payload?.path) payloadRelative = entry.payload.path;
  console.log(`  registry names ${cartridgeRelative} and ${payloadRelative}\n`);
}
const cartridgePath = join(root, cartridgeRelative);
const payloadPath = join(root, payloadRelative);

check('the release carries a wider-fleet cartridge', await exists(cartridgePath), cartridgePath);
check('the release carries a wider-fleet payload', await exists(payloadPath), payloadPath);
if (failures.length) { report(); }

const cartridge = await readFile(cartridgePath, 'utf8');
const rows = JSON.parse(await readFile(payloadPath, 'utf8'));
check('the payload carries rows', Array.isArray(rows) && rows.length > 0);

/* Which payload field reaches the URL. This is the whole point of the file:
   `rt` is the REPD type and `t` is an engine layer id, and reading the code
   is the only way to know which one a reader's browser sends. */
const setCalls = [...cartridge.matchAll(/query\.set\(\s*["']([\w_]+)["']\s*,\s*([^)]+)\)/g)]
  .map(m => [m[1], m[2].trim()]);
const emitted = new Map(setCalls);
console.log(`\n  wider fleet sets: ${[...emitted.keys()].sort().join(', ')}`);
check('the wider-fleet link sets a technology parameter', emitted.has('technology'));
const technologyExpression = emitted.get('technology') || '';
console.log(`  technology comes from: ${technologyExpression}`);

const field = /row\.rt\b/.test(technologyExpression) ? 'rt'
  : /row\.t\b/.test(technologyExpression) ? 't' : null;
check('the technology parameter is traceable to one payload field', field !== null,
  `could not resolve ${technologyExpression} to row.t or row.rt`);

/* ── payload integrity ─────────────────────────────────────────────────── */

const repdTypes = new Set(rows.map(r => r.rt));
const emittedValues = [...new Set(rows.map(r => r[field]).filter(v => v != null))].sort();
console.log(`\n  REPD technology types in the cut : ${repdTypes.size}`);
console.log(`  distinct technology values emitted: ${emittedValues.length} `
  + `— ${emittedValues.join(', ')}`);

const withRef = rows.filter(r => r.ref);
const unresolved = rows.filter(r => !r.ref);
console.log(`  rows ${rows.length}, with a REPD reference ${withRef.length} `
  + `(${(100 * withRef.length / rows.length).toFixed(2)}%), without ${unresolved.length}`);

const refCounts = new Map();
for (const row of withRef) refCounts.set(row.ref, (refCounts.get(row.ref) || 0) + 1);
const repeatedRefs = [...refCounts].filter(([, n]) => n > 1).map(([ref]) => ref);
check('no REPD reference is claimed by two rows', repeatedRefs.length === 0,
  repeatedRefs.join(', '));

/* A duplicate row is not cosmetic. It double-counts capacity in the tab
   totals, and it is also why some rows can never resolve: the join looks a
   site up by name and technology, finds two, tries operator and then
   development status, and returns "ambiguous" when it still cannot get to
   one. A register that carries a project twice hands the resolver exactly
   that situation. */
const identity = (r) => JSON.stringify([r.n, r.rt, r.c, r.ll]);
const seen = new Map();
for (const row of rows) seen.set(identity(row), (seen.get(identity(row)) || 0) + 1);
const duplicated = [...seen].filter(([, n]) => n > 1);
const extraRows = duplicated.reduce((sum, [, n]) => sum + n - 1, 0);
const doubleCounted = duplicated.reduce(
  (sum, [key, n]) => sum + (JSON.parse(key)[2] || 0) * (n - 1), 0);
if (duplicated.length) {
  console.log('');
  for (const [key, n] of duplicated) {
    const [name, type, capacity] = JSON.parse(key);
    console.log(`  x${n}  ${name} — ${type}, ${capacity} MW`);
  }
}
check('no project appears twice with the same name, type, capacity and position',
  duplicated.length === 0,
  `${duplicated.length} duplicated identities, ${extraRows} extra rows, `
  + `${doubleCounted.toFixed(2)} MW double-counted in every tab total that includes them`);

if (unresolved.length) {
  console.log(`\n  the ${unresolved.length} rows the Atlas cannot resolve:`);
  for (const row of unresolved) {
    console.log(`    ${String(row.c).padStart(7)} MW  ${row.rt.padEnd(20)} ${row.n}`);
  }
}

/* ── the other side: the values GridAtlas will accept ──────────────────── */

const sibling = await exists(join(SIBLING, '.git')) || await exists(SIBLING);
check('the GridAtlas checkout this contract binds to is available', sibling,
  `not found at ${SIBLING} — clone Ventusltd/gridatlas beside this repository, `
  + 'or pass --gridatlas <path>. This check does not skip.');

if (sibling) {
  const current = JSON.parse(await readFile(join(SIBLING, 'atlas', 'current.json'), 'utf8'));
  const cartridges = current.cartridges || [];
  console.log(`\n  GridAtlas composition ${current.generation} `
    + `(${current.composition_version}), ${cartridges.length} cartridges`);
  console.log(`  read from ${SIBLING}`);
  check('the checkout being read is a composition, not an empty tree',
    Boolean(current.generation) && cartridges.length > 0);

  /* Read the allow-set out of the COMPOSED bytes, never out of a source file:
     the composed bytes are what a browser is handed. */
  let allowed = null;
  let allowedIn = null;
  for (const entry of cartridges) {
    const file = join(SIBLING, 'atlas', entry.path.replace('./', ''));
    if (!await exists(file)) continue;
    const text = await readFile(file, 'utf8');
    const match = text.match(
      /allowedTechnologies\s*=\s*new\s+Set\(\s*\[([^\]]*)\]\s*\)/);
    if (!match) continue;
    allowed = new Set([...match[1].matchAll(/["']([\w_]+)["']/g)].map(m => m[1]));
    allowedIn = entry.id;
    break;
  }
  check('the composed GridAtlas declares a technology allow-set', allowed !== null,
    'no allowedTechnologies Set found in any composed cartridge — if the check '
    + 'has moved, this harness is reading the wrong thing and must be updated');

  if (allowed) {
    console.log(`\n  ${allowedIn} accepts: ${[...allowed].sort().join(', ')}`);
    const rejected = emittedValues.filter(value => !allowed.has(value));
    const rowsRejected = rows.filter(r => !allowed.has(r[field])).length;
    check('every technology value the wider fleet emits is one GridAtlas accepts',
      rejected.length === 0,
      `${rejected.join(', ')} — ${rowsRejected} of ${rows.length} MAP links throw `
      + "'canonical project technology is invalid' on arrival. The allow-set is the "
      + 'four spine technologies, which are exactly the four the wider fleet is '
      + 'defined as excluding, so no value this side can send will pass it. '
      + 'Sending the REPD type name instead does not help.');
  }
}

report();

function report() {
  console.log(`\n${passed}/${passed + failures.length} checks passed`);
  if (failures.length) {
    console.error('\nFAILURES');
    for (const failure of failures) console.error(`  ${failure}`);
    process.exit(1);
  }
  console.log('the wider fleet links to an Atlas that can answer it.');
  process.exit(0);
}

Sector Ledger Relevance Proof

A JavaScript module in the audits folder of PipelineNews that reads sector intelligence contract, sector intelligence rss and solar.

ingestpipelinenews / tools/intelligence/audits/202609010015-sector-ledger-relevance-proof.mjs · lines 1–94 of 94 · version 2026-09-01 00:15 · Entry point

What it does
It loads sector intelligence contract, sector intelligence rss and solar. Uses libraries node:assert/strict, node:fs/promises. 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. Domain terms in the code: solar.
Inputs & outputs
In: JSON file 202608272130-sector-intelligence-contract.json; JSON file 202608272130-sector-intelligence-rss.json; JSON file 202608271524-fd2212a8c76d-v8-fast-news.json; JSON file 202608272130-sector-intelligence.json.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
It reads `data/news-discovery/202608272130-sector-intelligence-contract.json`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · tools/intelligence/audits · JavaScript module
Uses
JavaScript Sector Intelligence Runner (import), JavaScript Sector Topic Evidence (import), JavaScript Sector Ledger Relevance Gate (import), node:assert/strict, node:fs/promises
Used by
none found
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 tools/intelligence/audits/202609010015-sector-ledger-relevance-proof.mjs:1-94 · blob e4b869d056f9c0a247aeffee4c53ab0f70423039 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node

import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";

import { collectSectorIntelligence } from "../../../discovery/javascript/202608272130-sector-intelligence-runner.mjs";
import {
  ACTIVE_SECTOR_TOPICS,
  classifySectorTopic,
} from "../../../discovery/javascript/202609010015-sector-topic-evidence.mjs";
import {
  gateSectorLedger,
  sectorTopicDecision,
} from "../../../discovery/javascript/202609010015-sector-ledger-relevance-gate.mjs";

const contract = JSON.parse(await readFile("data/news-discovery/202608272130-sector-intelligence-contract.json", "utf8"));
const fixture = JSON.parse(await readFile("discovery/fixtures/202608272130-sector-intelligence-rss.json", "utf8"));
fixture.responses.GOVUK_INVERTER_SECURITY.body.results[0].title = "Connected solar inverter security policy update";

const ledger = await collectSectorIntelligence({
  contract,
  genericNewsPath: "releases/data/202608271524-fd2212a8c76d-v8-fast-news.json",
  fixture,
  collectionAnchorAt: fixture.collection_anchor_at,
  collectionAnchorBasis: fixture.collection_anchor_basis,
});
assert.equal(ledger.datasets.sector_items.rows.length, 19);
const rawLedger = JSON.stringify(ledger);
const gated = gateSectorLedger(ledger);
assert.equal(JSON.stringify(ledger), rawLedger, "gate mutated the collector receipt in place");
assert.deepEqual(gateSectorLedger(ledger), gated, "gate is not deterministic");
const retainedIds = new Set(gated.datasets.sector_items.rows.map(({ intelligence_item_id }) => intelligence_item_id));
const rejectedFixture = ledger.datasets.sector_items.rows
  .filter(({ intelligence_item_id }) => !retainedIds.has(intelligence_item_id))
  .map(({ source_id, title }) => ({ source_id, title }));
assert.equal(gated.datasets.sector_items.rows.length, 17, JSON.stringify(rejectedFixture));
assert.equal(gated.datasets.sector_item_topics.rows.length, 17);
assert.deepEqual(gated.datasets.sector_project_bindings.rows, []);
assert.ok(gated.datasets.sector_item_topics.rows.every(({ topic_code }) => ACTIVE_SECTOR_TOPICS.includes(topic_code)));
assert.ok(gated.datasets.sector_item_topics.rows.every(({ assignment_basis }) => assignment_basis.startsWith("AFFIRMATIVE_ITEM_EVIDENCE:")));
assert.ok(gated.source_statuses.every((row) => Object.keys(row).sort().join("|")
  === "content_type|error_code|requested|response_bytes|response_sha256|result|retained_items|source_id"));
for (const sourceId of ["GOVUK_HORMUZ_ENERGY", "GOVUK_UKRAINE_ENERGY"]) {
  assert.equal(gated.datasets.sector_items.rows.some(({ source_id }) => source_id === sourceId), false);
  assert.equal(gated.source_statuses.find(({ source_id }) => source_id === sourceId).retained_items, 0);
}

const cases = [
  ["More data centres approved for west London", "DATA_CENTRES"],
  ["Solar inverter cybersecurity regulation enters consultation", "INVERTER_SECURITY_POLICY"],
  ["Electricity transmission network upgrade programme", "GREAT_GRID_UPGRADE"],
  ["Worldwide solar capacity growth reaches record high", "WORLDWIDE_PV"],
  ["Power transformer high-voltage cable supply chain", "MV_HV_COMPONENTS"],
  ["Notorious Kidlington dump fully cleared", null],
  ["Biometrics and Surveillance Camera Commissioner FOI responses", null],
  ["Retail sales forecast for 2027", null],
  ["The economic benefits of touring and impact of EU exit", null],
  ["Schools funding announcement", null],
  ["Electricity update", null],
  ["Security policy update", null],
];
for (const [title, expected] of cases) {
  assert.equal(classifySectorTopic({ title })?.topic || null, expected, title);
}

const browser = JSON.parse(await readFile(
  "releases/202608312114-pipelinenews/data/202608272130-sector-intelligence.json",
  "utf8",
));
const rows = browser.rows.map((row) => Object.fromEntries(browser.fields.map((field, index) => [field, row[index]])));
const decisions = rows.map((row) => ({ row, match: sectorTopicDecision(row) }));
const accepted = decisions.filter(({ match }) => match);
const rejected = decisions.filter(({ match }) => !match);
const reassigned = accepted.filter(({ row, match }) => row.topic_code !== match.topic);
assert.equal(rows.length, 51);
assert.equal(accepted.length, 12);
assert.equal(rejected.length, 39);
assert.equal(reassigned.length, 1);
assert.ok(rejected.some(({ row }) => /Kidlington dump/iu.test(row.title)));
assert.ok(rejected.some(({ row }) => /Biometrics and Surveillance/iu.test(row.title)));
assert.ok(reassigned.some(({ row, match }) => /surge in solar energy/iu.test(row.title)
  && match.topic === "WORLDWIDE_PV"));

process.stdout.write(`${JSON.stringify({
  status: "PASS",
  synthetic_collector_candidates: ledger.datasets.sector_items.rows.length,
  synthetic_pre_parquet_retained: gated.datasets.sector_items.rows.length,
  active_topics: ACTIVE_SECTOR_TOPICS,
  inspected_real_rows: rows.length,
  real_rows_retained: accepted.length,
  real_rows_rejected: rejected.length,
  real_rows_reassigned: reassigned.length,
  diseased_examples_rejected: cases.filter(([, expected]) => expected === null).length,
}, null, 2)}\n`);

Sector Topic Relevance Audit

A JavaScript module in the audits folder of PipelineNews that reads sector intelligence and solar.

ingestpipelinenews / tools/intelligence/audits/sector_topic_relevance_audit.mjs · lines 1–74 of 74 · Entry point

What it does
It loads sector intelligence and solar. Uses libraries node:assert/strict, node:fs/promises, node:path, node:process. 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. Domain terms in the code: solar.
Inputs & outputs
In: JSON file 202608272130-sector-intelligence.json; command-line arguments.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · tools/intelligence/audits · JavaScript module
Uses
JavaScript Sector Ledger Relevance Gate (import), node:assert/strict, node:fs/promises, node:path, node:process
Used by
none found
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 tools/intelligence/audits/sector_topic_relevance_audit.mjs:1-74 · blob e25ede15dbfe7af70f2089ce128bb8ea10b02eac · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node

import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
import process from "node:process";

import { sectorTopicDecision } from "../../../discovery/javascript/202609010015-sector-ledger-relevance-gate.mjs";

const release = process.argv[2] || "releases/202608312114-pipelinenews";
const file = path.join(release, "data", "202608272130-sector-intelligence.json");
const payload = JSON.parse(await readFile(file, "utf8"));
assert.equal(payload.schema, "pipelinenews.sector-intelligence-browser.v3");

const rows = payload.rows.map((row) => Object.fromEntries(
  payload.fields.map((field, index) => [field, row[index]]),
));

const decisions = rows.map((row) => ({ row, match: sectorTopicDecision(row) }));
const accepted = decisions.filter(({ match }) => match);
const rejected = decisions.filter(({ match }) => !match);
const misfiled = accepted.filter(({ row, match }) => row.topic_code !== match.topic);
const exact = accepted.filter(({ row, match }) => row.topic_code === match.topic);

const duplicateUrls = Object.entries(Object.groupBy(
  rows.filter(({ item_kind }) => item_kind === "SOURCE_METADATA"),
  ({ canonical_url }) => canonical_url,
)).filter(([, values]) => values.length > 1);

const report = {
  schema: "pipelinenews.sector-topic-relevance-audit.v1",
  release,
  payload_generation: payload.generation,
  rows: rows.length,
  exact_topic_rows: exact.length,
  reassignable_rows: misfiled.length,
  rejected_rows: rejected.length,
  displayable_after_reassignment: accepted.length,
  source_metadata_duplicate_url_groups: duplicateUrls.length,
  rejected: rejected.map(({ row }) => ({
    topic: row.topic_code,
    source: row.source_id,
    title: row.title,
  })),
  reassign: misfiled.map(({ row, match }) => ({
    from: row.topic_code,
    to: match.topic,
    rule: match.rule,
    title: row.title,
  })),
};

process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);

const requireClean = process.argv.includes("--require-clean");
if (requireClean) {
  assert.equal(rejected.length, 0, "sector payload still contains rows without affirmative topic evidence");
  assert.equal(misfiled.length, 0, "sector payload still contains rows assigned to the wrong topic");
} else {
  // Current measured acceptance envelope: 11 correctly filed rows plus one EC
  // solar story that belongs under WORLDWIDE_PV. Baseline mode attests exactly
  // what was inspected in the 51-row release; clean mode above is reusable for
  // a future collector whose row count must not be frozen to today's payload.
  assert.equal(rows.length, 51);
  assert.equal(exact.length, 11);
  assert.equal(misfiled.length, 1);
  assert.equal(accepted.length, 12);
  assert.equal(rejected.length, 39);
  assert.equal(rejected.filter(({ row }) => row.source_id.startsWith("GOVUK_")).length, 35);
  assert.ok(rejected.some(({ row }) => /Kidlington dump/iu.test(row.title)));
  assert.ok(rejected.some(({ row }) => /Biometrics and Surveillance/iu.test(row.title)));
  assert.ok(misfiled.some(({ row, match }) => /surge in solar energy/iu.test(row.title)
    && match.topic === "WORLDWIDE_PV"));
}

Build BBC RSS Package

A JavaScript module in the intelligence folder of PipelineNews that reads cearn project evidence, project register and cartridge, using SHA-256.

renderpipelinenews / tools/intelligence/build-bbc-rss-package.mjs · lines 1–39 of 39 · Not reached from any entry point (candidate for review) · pattern source (shared by 13 files)

What it does
It loads cearn project evidence, project register and cartridge. Defines source. Uses libraries node:fs, node:child_process, node:crypto. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file bbc-rss.json; JSON file 202609060208-cearn-project-evidence.json; JSON file project-register.json; command-line arguments. Out: JSON file cartridge.json.
What it achieves
Its name says it builds BBC RSS package. Defines `source`. It writes `/cartridge.json`.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · tools/intelligence · JavaScript module
Uses
BBC RSS Pipeline Model (script call), BBC RSS Pipeline Panel (script call), node:fs, node:child_process, node:crypto
Used by
none found
Produces
source
Defines here
source
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/build-bbc-rss-package.mjs:1-39 · blob 90cc68ed47edfd9fce06758b7819629f81ec68e8 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import {mkdirSync,readFileSync,writeFileSync} from 'node:fs';
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
const root='tools/intelligence/cartridges/bbc-rss-intelligence';
const sha=execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8'}).trim();
const draft=process.argv.includes('--draft');
const sources=[];
function source(path) {
  const bytes=draft&&path.startsWith('cartridges/bbc-rss-pipeline-')?Buffer.from(readFileSync(path,'utf8').replace(/\r\n/g,'\n')):execFileSync('git',['show',`${sha}:${path}`]);
  sources.push({path,sha256:createHash('sha256').update(bytes).digest('hex'),basis:draft&&path.startsWith('cartridges/bbc-rss-pipeline-')?'uncommitted draft':'committed Git blob'});
  return bytes;
}
mkdirSync(root+'/assets',{recursive:true});mkdirSync(root+'/data',{recursive:true});
const model=source('cartridges/bbc-rss-pipeline-model.mjs').toString().replace("'./reported-project.mjs'","'./{GEN}-bbc-reported-project.mjs'");
const panel=source('cartridges/bbc-rss-pipeline-panel.mjs').toString().replace("'./bbc-rss-pipeline-model.mjs'","'./{GEN}-bbc-rss-pipeline-model.mjs'");
writeFileSync(root+'/assets/{GEN}-bbc-rss-pipeline-model.mjs',model);
writeFileSync(root+'/assets/{GEN}-bbc-rss-pipeline.mjs',panel);
writeFileSync(root+'/assets/{GEN}-bbc-reported-project.mjs',source('cartridges/reported-project.mjs'));
const payload={schema:'pipelinenews.bbc-rss-pipeline-payload.v1',rss:JSON.parse(source('discovery/products/bbc-rss.json')),evidence:[JSON.parse(source('discovery/inbox/202609060208-cearn-project-evidence.json'))],projects:JSON.parse(source('data/provisional/project-register.json')).projects};
writeFileSync(root+'/data/{GEN}-bbc-rss-pipeline.json',JSON.stringify(payload,null,2)+'\n');
const manifest={key:'bbc_rss_intelligence',summary:'Automated BBC RSS discovery with freshness, source health and separate reported project evidence inside the full Pipeline app.',modifies_existing_dashboard:true,modification_note:'Adds a BBC RSS panel. Headlines and reported capacity do not change official REPD rows, geometry or totals.',
 section:'    <section class="panel" id="bbc-rss-intelligence"><h2 class="section-title">PIPELINE INTELLIGENCE - BBC RSS DISCOVERY</h2><div id="bbcRssIntelligenceHost" role="status">Loading collected BBC headlines...</div></section>\n',
 loader:`async function bindBbcRssIntelligence() {
  const host=document.getElementById('bbcRssIntelligenceHost');
  try {
    const entry=registry.supplemental_assets.bbc_rss_intelligence;
    const payload=await fetchImmutable(entry.payload.path);
    invariant(payload.schema==='pipelinenews.bbc-rss-pipeline-payload.v1','RSS panel payload schema mismatch');
    const module=await import('../'+entry.cartridge.path);
    invariant(module.CONTRACT.generation===entry.generation,'RSS panel module generation mismatch');
    window.__bbcRssIntelligence=module.mount({host,payload:payload.rss,evidence:payload.evidence,projects:()=>window.__provisionalProjects?.projects || payload.projects,official:rows.map((_,index)=>project(index))});
  }catch(error){host.textContent='BBC RSS discovery unavailable: '+error.message;}
}\n`,
 bind_call:'await bindBbcRssIntelligence();',
 hash_fields:[{at:['cartridge','sha256'],path:'assets/{GEN}-bbc-rss-pipeline.mjs'},{at:['model','sha256'],path:'assets/{GEN}-bbc-rss-pipeline-model.mjs'},{at:['evidence_validator','sha256'],path:'assets/{GEN}-bbc-reported-project.mjs'},{at:['payload','sha256'],path:'data/{GEN}-bbc-rss-pipeline.json'}],
 registry_entry:{schema:'pipelinenews.bbc-rss-pipeline-supplement.v1',generation:'{GEN}',source_commit:sha,source_mode:draft?'UNCOMMITTED_DRAFT_DO_NOT_PUBLISH':'committed',sources,
  cartridge:{path:'assets/{GEN}-bbc-rss-pipeline.mjs',schema:'pipelinenews.bbc-rss-pipeline.v1'},model:{path:'assets/{GEN}-bbc-rss-pipeline-model.mjs'},evidence_validator:{path:'assets/{GEN}-bbc-reported-project.mjs'},payload:{path:'data/{GEN}-bbc-rss-pipeline.json',schema:payload.schema},official_source_totals_unchanged:true,live_source:'https://raw.githubusercontent.com/Ventusltd/pipelinenews/ma  … [line shortened here: 647 characters; full line on GitHub]
writeFileSync(root+'/cartridge.json',JSON.stringify(manifest,null,2)+'\n');
console.log(root+(draft?' (DRAFT - rerun without --draft after committing owner source)':''));

Build Provisional Package

A JavaScript module in the intelligence folder of PipelineNews covering project register, cartridge and the Renewable Energy Planning Database (REPD) register, using SHA-256.

renderpipelinenews / tools/intelligence/build-provisional-package.mjs · lines 1–30 of 30 · Not reached from any entry point (candidate for review)

What it does
Defines blob. Uses libraries node:fs, node:child_process. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
Out: JSON file project-register.json; JSON file cartridge.json.
What it achieves
Its name says it builds provisional package. Defines `blob`. It writes `/cartridge.json`.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · tools/intelligence · JavaScript module
Uses
Provisional Identity (script call), Provisional Pipeline Panel (script call), node:fs, node:child_process
Used by
none found
Produces
blob
Defines here
blob
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/build-provisional-package.mjs:1-30 · blob e11e9fea0e4bdd619c8783285a1ded90c2059874 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import {mkdirSync,writeFileSync} from 'node:fs';
import {execFileSync} from 'node:child_process';
const root='tools/intelligence/cartridges/provisional-projects';
const sha=execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8'}).trim();
const blob=path=>execFileSync('git',['show',`${sha}:${path}`]);
mkdirSync(root+'/assets',{recursive:true});mkdirSync(root+'/data',{recursive:true});
writeFileSync(root+'/assets/{GEN}-provisional-identity.mjs',blob('cartridges/provisional-identity.mjs'));
writeFileSync(root+'/assets/{GEN}-provisional-projects.mjs',blob('cartridges/provisional-pipeline-panel.mjs'));
writeFileSync(root+'/data/{GEN}-provisional-projects.json',blob('data/provisional/project-register.json'));
const manifest={key:'provisional_projects',summary:'News-reported projects enter the Pipeline under one-time REPD-pending identities.',
 modifies_existing_dashboard:true,modification_note:'Adds a labelled pending-register table; official REPD totals and geometry stay source-bound.',
 section:'    <section class="panel" id="provisional-projects"><h2 class="section-title">REPD PIPELINE - AWAITING REGISTER PUBLICATION</h2><div id="provisionalProjectsHost" role="status">Loading pending project records...</div></section>\n',
 loader:`async function bindProvisionalProjects() {
  const host=document.getElementById('provisionalProjectsHost');
  try {
    const entry=registry.supplemental_assets.provisional_projects;
    const payload=await fetchImmutable(entry.payload.path);
    const module=await import('../'+entry.cartridge.path);
    invariant(module.CONTRACT.generation===entry.generation,'provisional module generation mismatch');
    const result=module.mount({host,payload,official:rows.map((_,index)=>project(index)),source:{path:registry.assets.projects.path,sha256:registry.assets.projects.sha256}});
    window.__provisionalProjects=result;
  }catch(error){host.textContent='Pending project records unavailable: '+error.message;}
}\n`,
 bind_call:'await bindProvisionalProjects();',
 hash_fields:[{at:['cartridge','sha256'],path:'assets/{GEN}-provisional-projects.mjs'},{at:['identity','sha256'],path:'assets/{GEN}-provisional-identity.mjs'},{at:['payload','sha256'],path:'data/{GEN}-provisional-projects.json'}],
 registry_entry:{schema:'pipelinenews.provisional-pipeline-supplement.v1',generation:'{GEN}',source_commit:sha,
   cartridge:{path:'assets/{GEN}-provisional-projects.mjs',schema:'pipelinenews.provisional-pipeline.v1'},identity:{path:'assets/{GEN}-provisional-identity.mjs'},payload:{path:'data/{GEN}-provisional-projects.json',schema:'pipelinenews.provisional-register.v1'},
   identity_status:'REPD_PENDING',official_source_totals_unchanged:true,quarterly_rule:'Unique name/developer/county/capacity match replaces the temporary ref; previous ref and Global Grid reference remain aliases.'}};
writeFileSync(root+'/cartridge.json',JSON.stringify(manifest,null,2)+'\n');
console.log(root);

BBC RSS Pipeline Model

A JavaScript module in the assets folder of PipelineNews that works with the Renewable Energy Planning Database (REPD) register. It builds rss view (`buildRssView`) and refreshes rss (`refreshRss`).

Set aside from the main view: 97% of its lines are the same as cartridges/bbc-rss-pipeline-model.mjs (pipelinenews), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with BBC RSS Pipeline Model; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9672 to pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 cartridges/bbc-rss-pipeline-model.mjs:1-73 63a257b51e9bf26edcf8d9eaa02a611895ecf0f1
  • sha256 2d7121bebab68d2cfe162b946977eef57d508365b50735eea9cb4e32398e2eb3
  • target sha256 42e4bbba938e6efb5701e0a6ab68e9c2a736e69d817dd506137cc8a376896f35
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

energy-datapipelinenews / tools/intelligence/cartridges/bbc-rss-intelligence/assets/{GEN}-bbc-rss-pipeline-model.mjs · lines 1–73 of 73 · Not reached from any entry point (candidate for review) · pattern projectObservation (shared by 3 files)

What it does
It calculates the REPD register. Defines articleIdentity, projectObservation, buildRssView, refreshRss.
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.
Inputs & outputs
In: JSON file bbc-rss.json.
Downstream impact
Used directly by 1 file: BBC RSS Pipeline (pipelinenews).
What it achieves
Defines `articleIdentity`, `projectObservation`, `buildRssView` and 1 more.
Why it matters
Imported by BBC RSS Pipeline.
Application
pipelinenews · tools/intelligence/cartridges/bbc-rss-intelligence/assets · JavaScript module
Uses
Reported Project (import)
Used by
imported by BBC RSS Pipeline (import)
Produces
LIVE_RSS_URL, STALE_AFTER_MS, articleIdentity, projectObservation, buildRssView, refreshRss
Defines here
articleIdentity, projectObservation, buildRssView, refreshRss
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/bbc-rss-intelligence/assets/{GEN}-bbc-rss-pipeline-model.mjs:1-73 · blob 90eaf130339dc17eab35bf0b34bf5dc10d4d67d9 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
import {validateReportedProject} from './{GEN}-bbc-reported-project.mjs';

export const LIVE_RSS_URL = 'https://raw.githubusercontent.com/Ventusltd/pipelinenews/main/discovery/products/bbc-rss.json';
export const STALE_AFTER_MS = 3 * 60 * 60 * 1000;

export function articleIdentity(value) {
  try {
    const url = new URL(value);
    const match = url.pathname.match(/^\/news\/articles\/([a-z0-9]+)\/?$/i);
    if (url.protocol !== 'https:' || !['www.bbc.co.uk','www.bbc.com'].includes(url.hostname) || !match) return null;
    return {id:'bbc:'+match[1].toLowerCase(), url:`https://www.bbc.co.uk/news/articles/${match[1].toLowerCase()}`};
  } catch { return null; }
}

// The collector's asserted REPD fields are deliberately not a binding authority.
export function projectObservation(item, projects = [], evidence = [], official = []) {
  const identity = articleIdentity(item.url);
  const candidates = projects.filter(project=>articleIdentity(project.article_url)?.id === identity?.id);
  const project = candidates.length === 1 ? candidates[0] : null;
  const reported = evidence.find(report=>articleIdentity(report.article_url)?.id===identity?.id && report.primary_project===project?.name);
  const validated = reported ? validateReportedProject(reported) : null;
  const ref = String(project?.official_repd_ref || '');
  const bound = project?.identity_status==='REPD_BOUND' && /^\d+$/.test(ref) && official.some(row=>String(row.repd_ref)===ref);
  return {
    name:project?.name || null,
    status:bound?'OFFICIAL_IDENTITY_VERIFIED':project?'REPD_PENDING':'UNMATCHED_REQUIRES_REVIEW',
    repd_ref:bound?ref:null,
    temporary_ref:!bound&&/^[0-9]+-REPD-TBC$/.test(project?.repd_ref || '')?project.repd_ref:null,
    gg_project_id:bound?`GG2050-REPD-${ref}`:project?.gg_project_id || null,
    claims:validated?.claims || [],
    related_projects:validated?.related_projects || [],
    unknowns:validated?.unknowns || [],
    evidence_basis:validated?.evidence_basis || null,
    // A verified project identity never converts a report into official capacity or headroom.
    capacity_basis:'reported only; excluded from official REPD totals',
    eligible_for_project_signal:false,
  };
}

export function buildRssView(payload, {now=Date.now(), projects=[], evidence=[], official=[], refreshError=null}={}) {
  if(payload?.schema!=='pipelinenews.bbc-rss.v1' || !Array.isArray(payload.items) || !Array.isArray(payload.feeds)) throw Error('Unsupported BBC RSS product');
  if(payload.items.length>500 || payload.feeds.length>100) throw Error('BBC RSS product exceeds bounded collection contract');
  const checked=Date.parse(payload.checked_at), successful=Date.parse(payload.last_success_at);
  const clockValid=Number.isFinite(now)&&Number.isFinite(checked)&&checked<=now+60000&&Number.isFinite(successful)&&successful<=now+60000;
  const age=clockValid?Math.max(0,now-successful):null;
  const good=payload.feeds.filter(feed=>feed.status==='ok').length;
  const total=payload.feeds.length;
  const collection=good===0?'FAILED':good<total||payload.status!=='ok'?'PARTIAL':'OK';
  const freshness=!clockValid?'UNKNOWN':age>STALE_AFTER_MS?'STALE':'FRESH';
  const unique=new Map();
  let rejected=0;
  for(const item of payload.items) {
    const identity=articleIdentity(item.url);
    if(!identity || typeof item.headline!=='string' || !item.headline.trim() || (item.id && item.id!==identity.id)) {rejected++;continue;}
    if(unique.has(identity.id)) continue;
    unique.set(identity.id,{...identity,headline:item.headline.trim(),published_at:item.source_published_at || null,observation:projectObservation(item,projects,evidence,official)});
  }
  return {items:[...unique.values()],rejected,collection,freshness,age_ms:age,checked_at:payload.checked_at || null,last_success_at:payload.last_success_at || null,feed_success:good,feed_total:total,feeds:payload.feeds.map(feed=>({url:String(feed.url || ''),status:String(feed.status || 'unknown')})),refresh_error:refreshError?String(refreshError):null};
}

// On any fetch/schema failure retain the previous product and visibly mark refresh failure.
export async function refreshRss(previous, {fetcher=fetch, ...options}={}) {
  try {
    const response=await fetcher(LIVE_RSS_URL,{cache:'no-store',credentials:'omit',redirect:'error',signal:AbortSignal.timeout(15000)});
    if(!response.ok) throw Error('Source HTTP '+response.status);
    const text=await response.text();
    if(text.length>2*1024*1024) throw Error('Source exceeds 2 MiB limit');
    const payload=JSON.parse(text);
    return {payload,view:buildRssView(payload,options),live:true};
  } catch(error) {
    return {payload:previous,view:buildRssView(previous,{...options,refreshError:error.message}),live:false};
  }
}

BBC RSS Pipeline

A JavaScript module in the assets folder of PipelineNews that works with UK time (`ukTime`), covering the Renewable Energy Planning Database (REPD) register.

Set aside from the main view: 92% of its lines are the same as testcode/202609060232/pipeline/assets/202609060232-bbc-rss-pipeline.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 92% of lines shared with BBC RSS Pipeline; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9245 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609060232/pipeline/assets/202609060232-bbc-rss-pipeline.mjs:1-56 e4739a739d33a37be3c01e44c4e861fea0aa2830
  • sha256 b9d39ad8b98ad57e6c7e4261a6b3c538087153c65594e0d0797ba29198e54b44
  • target sha256 73ae7f04c4fc7d4d05fb69a301350c8969a2b39308656d3b0b3d8582303a06f5
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

energy-datapipelinenews / tools/intelligence/cartridges/bbc-rss-intelligence/assets/{GEN}-bbc-rss-pipeline.mjs · lines 1–56 of 56 · Not reached from any entry point (candidate for review) · pattern ukTime (shared by 3 files)

What it does
It draws the REPD register. Defines 6 functions or classes, including mount, ukTime, create, options, render. Side effects: changes the web page (DOM).
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.
What it achieves
It is built from the UK time helper (`ukTime`), the options step (`options`) and the render step (`render`). Defines `mount`, `ukTime`, `create` and 3 more. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · tools/intelligence/cartridges/bbc-rss-intelligence/assets · JavaScript module
Uses
BBC RSS Pipeline Model (import)
Used by
none found
Produces
CONTRACT, mount
Defines here
mount, ukTime, create, options, render, update
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/cartridges/bbc-rss-intelligence/assets/{GEN}-bbc-rss-pipeline.mjs:1-56 · blob 155efbbd78593452433b5c1c353ead570ec67258 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
import {buildRssView,refreshRss} from './{GEN}-bbc-rss-pipeline-model.mjs';
export const CONTRACT={schema:'pipelinenews.bbc-rss-pipeline.v1',generation:'{GEN}'};

export function mount({host,payload,evidence=[],projects=[],official=[],fetcher=fetch}) {
  const doc=host.ownerDocument;
  const ukTime=value=>{const date=new Date(value);return Number.isFinite(date.getTime())?new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit',timeZoneName:'short'}).format(date):'unknown';};
  const create=(tag,text)=>{const el=doc.createElement(tag);if(text!==undefined)el.textContent=text;return el;};
  const description=create('p','BBC RSS discovery runs every two hours. This panel checks the latest collected headlines on opening; article pages are not fetched. News reports do not establish consent, firm capacity or connection headroom.');
  const controls=create('div');controls.style.cssText='display:flex;gap:8px;flex-wrap:wrap;margin:12px 0';
  const refresh=create('button','Refresh collected RSS'),snapshot=create('button','Publication snapshot');
  for(const button of [refresh,snapshot]){button.type='button';button.style.cssText='min-height:44px;padding:8px 12px;cursor:pointer';}
  controls.append(refresh,snapshot);
  const status=create('p');status.setAttribute('role','status');status.setAttribute('aria-live','polite');
  const list=create('div');list.style.overflowWrap='anywhere';
  const details=create('details'),summary=create('summary','Source feed health'),feeds=create('ul');details.append(summary,feeds);
  host.replaceChildren(description,controls,status,list,details);
  let current=payload,mode='Publication snapshot',request=0,disposed=false;
  const options=()=>({projects:typeof projects==='function'?projects():projects,evidence,official});
  function render(view) {
    host.dataset.rssReady='true';host.dataset.rssFreshness=view.freshness;host.dataset.rssCollection=view.collection;host.dataset.rssItems=String(view.items.length);
    status.textContent=`${mode} | ${view.collection}: ${view.feed_success}/${view.feed_total} feeds | ${view.freshness} | checked ${view.checked_at?ukTime(view.checked_at):'unknown'} | last successful collection ${view.last_success_at?ukTime(view.last_success_at):'none'}.`+(view.refresh_error?' Refresh unavailable: '+view.refresh_error+'. Previous observations retained.':'');
    list.replaceChildren();
    if(!view.items.length)list.append(create('p','No matching headlines in this collection. An empty feed is not proof that a project does not exist.'));
    for(const item of view.items) {
      const article=create('article');article.style.cssText='border-top:1px solid currentColor;padding:12px 0';
      const link=create('a',item.headline);link.href=item.url;link.rel='noopener noreferrer';
      article.append(link,create('p','BBC News | '+(item.published_at?ukTime(item.published_at):'Publication date unavailable')));
      const observation=item.observation;
      if(observation.name) {
        const identity=observation.repd_ref?'Verified official REPD identity '+observation.repd_ref:'Awaiting verified REPD match'+(observation.temporary_ref?' | '+observation.temporary_ref:'');
        article.append(create('p',observation.name+' | '+identity+(observation.gg_project_id?' | '+observation.gg_project_id:'')));
        const claims=create('ul');
        for(const claim of observation.claims)claims.append(create('li',claim.metric.replaceAll('_',' ')+': '+(claim.value===true?'reported included':String(claim.value))+(claim.unit?' '+claim.unit:'')+(claim.qualifier?' — '+claim.qualifier:'')));
        article.append(claims,create('p','These statements remain reported evidence, even after an official identity match. '+observation.capacity_basis+'.'));
        if(observation.related_projects.length)article.append(create('p','Separate related project: '+observation.related_projects.map(project=>project.name).join(', ')+'. Its capacity and cost are not attributed to '+observation.name+'.'));
        if(observation.unknowns.length)article.append(create('p','Not established by this report: '+observation.unknowns.join('; ')+'.'));
        if(observation.evidence_basis)article.append(create('small',observation.evidence_basis));
      } else article.append(create('p','REPD match unverified. Headline metadata only; no project capacity inferred.'));
      list.append(article);
    }
    feeds.replaceChildren();for(const feed of view.feeds)feeds.append(create('li',feed.status+' | '+feed.url));
    summary.textContent=`Source feed health (${view.feed_success}/${view.feed_total} successful)`;
  }
  async function update() {
    const token=++request;refresh.disabled=true;status.textContent='Refreshing collected BBC RSS metadata…';
    const result=await refreshRss(current,{...options(),fetcher});
    if(disposed||token!==request)return;
    current=result.payload;if(result.live)mode='Latest collected RSS';
    refresh.disabled=false;render(result.view);
  }
  refresh.addEventListener('click',update);
  snapshot.addEventListener('click',()=>{request++;refresh.disabled=false;current=payload;mode='Publication snapshot';render(buildRssView(current,options()));});
  render(buildRssView(current,options()));
  const ready=update();
  return {ready,refresh:update,dispose(){disposed=true;request++;}};
}