GLOBALGRID2050 / EXPLORE CODE

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

JavaScript Sector Intelligence Runner and 2 more files

A JavaScript module in the discovery folder of PipelineNews that reads PipelineNews centres and search, using SHA-256 from the data-centres-GB repository.

700 lines of JavaScript from pipelinenews, in 3 files. Topic: Electricity markets and data pipelines. Section 1013 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. JavaScript Sector Ledger Relevance Gate storage · pipelinenews / discovery/javascript/202609010015-sector-ledger-relevance-gate.mjs lines 1–130
  2. JavaScript Sector Topic Evidence transform · pipelinenews / discovery/javascript/202609010015-sector-topic-evidence.mjs lines 1–49
  3. JavaScript Sector Intelligence Runner storage · pipelinenews / discovery/javascript/202609010719-sector-intelligence-runner.mjs lines 1–521

JavaScript Sector Ledger Relevance Gate

A JavaScript module in the discovery folder of PipelineNews that works with sector topic decision (`sectorTopicDecision`) and gate sector ledger (`gateSectorLedger`).

storagepipelinenews / discovery/javascript/202609010015-sector-ledger-relevance-gate.mjs · lines 1–130 of 130 · version 2026-09-01 00:15 · Entry point

What it does
It loads data. Defines sectorTopicDecision, gateSectorLedger, argumentsFrom, main. Uses libraries node:assert/strict, node:fs/promises, node:path, node:url. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'gate'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 3 files: Sector Ledger Relevance Proof (pipelinenews); Sector Topic Relevance Audit (pipelinenews); PipelineNews Sector Intelligence Candidate Workflow (pipelinenews).
What it achieves
It is built from the sector topic decision helper (`sectorTopicDecision`), the gate sector ledger helper (`gateSectorLedger`) and the arguments from helper (`argumentsFrom`). Defines `sectorTopicDecision`, `gateSectorLedger` and `argumentsFrom`.
Why it matters
Imported by Sector Ledger Relevance Proof and Sector Topic Relevance Audit. Run by PipelineNews Sector Intelligence Candidate Workflow.
Application
pipelinenews · discovery/javascript · JavaScript module
Uses
JavaScript Sector Topic Evidence (import), node:assert/strict, node:fs/promises, node:path, node:url
Used by
imported by Sector Ledger Relevance Proof (import), imported by Sector Topic Relevance Audit (import), run by PipelineNews Sector Intelligence Candidate Workflow (workflow run)
Produces
sectorTopicDecision, gateSectorLedger
Defines here
sectorTopicDecision, gateSectorLedger, argumentsFrom, 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 discovery/javascript/202609010015-sector-ledger-relevance-gate.mjs:1-130 · blob b9359124632f9715b36b3ca3fb46c2c1f6ab37c1 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
#!/usr/bin/env node

import assert from "node:assert/strict";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";

import { ACTIVE_SECTOR_TOPICS, classifySectorTopic } from "./202609010015-sector-topic-evidence.mjs";

const LEDGER_SCHEMA = "pipelinenews.sector-intelligence-ledger.v3";
const EXPLICIT_SOURCE_TOPICS = new Map([
  ["DATA_CENTRES_OWNER_EXPORT", { topic: "DATA_CENTRES", rule: "PINNED_OWNER_EXPORT" }],
  ["FROZEN_GENERIC_DATA_CENTRE_NEWS", { topic: "DATA_CENTRES", rule: "FROZEN_DATA_CENTRE_HEADLINE" }],
  ["FCC_CURRENT_COVERED_LIST", { topic: "INVERTER_SECURITY_POLICY", rule: "STATIC_REGULATOR_REFERENCE" }],
  ["NATIONAL_GRID_GREAT_GRID_UPGRADE", { topic: "GREAT_GRID_UPGRADE", rule: "STATIC_NETWORK_OWNER_REFERENCE" }],
]);
const WITHDRAWN_SOURCES = new Set(["GOVUK_HORMUZ_ENERGY", "GOVUK_UKRAINE_ENERGY"]);

export function sectorTopicDecision(item) {
  if (WITHDRAWN_SOURCES.has(item.source_id)) return null;
  return EXPLICIT_SOURCE_TOPICS.get(item.source_id) || classifySectorTopic(item);
}

export function gateSectorLedger(input) {
  assert.equal(input.schema, LEDGER_SCHEMA);
  const itemDataset = input.datasets?.sector_items;
  const topicDataset = input.datasets?.sector_item_topics;
  const bindingDataset = input.datasets?.sector_project_bindings;
  assert.ok(Array.isArray(itemDataset?.rows));
  assert.ok(Array.isArray(topicDataset?.rows));
  assert.ok(Array.isArray(bindingDataset?.rows));

  const rankByTopic = new Map();
  for (const row of topicDataset.rows) {
    if (!rankByTopic.has(row.topic_code)) rankByTopic.set(row.topic_code, row.display_rank);
  }
  for (const topic of ACTIVE_SECTOR_TOPICS) assert.ok(rankByTopic.has(topic), `ledger lacks rank for ${topic}`);

  const accepted = [];
  const rejected = [];
  const topics = [];
  for (const item of itemDataset.rows) {
    const match = sectorTopicDecision(item);
    if (!match) {
      rejected.push(item);
      continue;
    }
    assert.ok(ACTIVE_SECTOR_TOPICS.includes(match.topic));
    accepted.push(item);
    topics.push({
      intelligence_item_id: item.intelligence_item_id,
      topic_code: match.topic,
      generation: item.generation,
      assignment_basis: `AFFIRMATIVE_ITEM_EVIDENCE:${match.rule}`,
      display_rank: rankByTopic.get(match.topic),
      eligible_for_news_signal: false,
    });
  }

  accepted.sort((left, right) => left.intelligence_item_id.localeCompare(right.intelligence_item_id));
  topics.sort((left, right) => left.intelligence_item_id.localeCompare(right.intelligence_item_id)
    || left.topic_code.localeCompare(right.topic_code));
  const acceptedIds = new Set(accepted.map(({ intelligence_item_id }) => intelligence_item_id));
  assert.equal(accepted.length, acceptedIds.size);
  assert.ok(topics.every(({ intelligence_item_id }) => acceptedIds.has(intelligence_item_id)));
  assert.ok(topics.every(({ topic_code }) => ACTIVE_SECTOR_TOPICS.includes(topic_code)));

  const retainedBySource = Map.groupBy(accepted, ({ source_id }) => source_id);
  const sourceStatuses = input.source_statuses.map((status) => ({
    ...status,
    retained_items: retainedBySource.get(status.source_id)?.length || 0,
  }));

  return {
    ...input,
    datasets: {
      ...input.datasets,
      sector_items: { ...itemDataset, rows: accepted },
      sector_item_topics: { ...topicDataset, rows: topics },
      sector_project_bindings: {
        ...bindingDataset,
        rows: bindingDataset.rows.filter(({ intelligence_item_id }) => acceptedIds.has(intelligence_item_id)),
      },
    },
    source_statuses: sourceStatuses,
    policy_evidence: {
      ...input.policy_evidence,
      topic_relevance_gate: {
        generation: "202609010015",
        basis: "AFFIRMATIVE_ITEM_LOCAL_TITLE_OR_SUMMARY_EVIDENCE",
        active_topics: [...ACTIVE_SECTOR_TOPICS],
        candidates: itemDataset.rows.length,
        retained: accepted.length,
        rejected: rejected.length,
        withdrawn_sources: [...WITHDRAWN_SOURCES].sort(),
      },
    },
  };
}

function argumentsFrom(argv) {
  const result = {};
  for (let index = 0; index < argv.length; index += 2) {
    assert.ok(argv[index]?.startsWith("--") && argv[index + 1], `invalid argument near ${argv[index]}`);
    result[argv[index].slice(2)] = argv[index + 1];
  }
  for (const required of ["input", "output"]) assert.ok(result[required], `--${required} is required`);
  return result;
}

async function main() {
  const options = argumentsFrom(process.argv.slice(2));
  const gated = gateSectorLedger(JSON.parse(await readFile(options.input, "utf8")));
  const output = path.resolve(options.output);
  await mkdir(path.dirname(output), { recursive: true });
  await writeFile(output, `${JSON.stringify(gated, null, 2)}\n`);
  process.stdout.write(`${JSON.stringify({
    status: "PASS",
    candidates: gated.policy_evidence.topic_relevance_gate.candidates,
    retained: gated.policy_evidence.topic_relevance_gate.retained,
    rejected: gated.policy_evidence.topic_relevance_gate.rejected,
    active_topics: gated.policy_evidence.topic_relevance_gate.active_topics,
  })}\n`);
}

const invoked = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (invoked) main().catch((error) => {
  process.stderr.write(`${error.stack || error}\n`);
  process.exitCode = 1;
});

JavaScript Sector Topic Evidence

A JavaScript module in the discovery folder of PipelineNews that works with solar and substations. It normalises sector evidence (`normaliseSectorEvidence`) and classifies sector topic (`classifySectorTopic`).

transformpipelinenews / discovery/javascript/202609010015-sector-topic-evidence.mjs · lines 1–49 of 49 · version 2026-09-01 00:15

What it does
It calculates solar and substations. Defines normaliseSectorEvidence, classifySectorTopic.
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, substations.
Downstream impact
Used directly by 3 files: Datacentre Binder (pipelinenews); JavaScript Sector Ledger Relevance Gate (pipelinenews); Sector Ledger Relevance Proof (pipelinenews). Reached from 4 other entry points, including PipelineNews BBC RSS Discovery Workflow (pipelinenews); PipelineNews Sector Intelligence Candidate Workflow (pipelinenews); Datacentre Binder Test (pipelinenews).
What it achieves
Affirmative, item-local evidence rules for neutral sector intelligence.
Why it matters
Imported by Datacentre Binder, JavaScript Sector Ledger Relevance Gate and Sector Ledger Relevance Proof.
Application
pipelinenews · discovery/javascript · JavaScript module
Uses
none found
Used by
imported by Datacentre Binder (import), imported by JavaScript Sector Ledger Relevance Gate (import), imported by Sector Ledger Relevance Proof (import)
Produces
ACTIVE_SECTOR_TOPICS, normaliseSectorEvidence, classifySectorTopic
Defines here
normaliseSectorEvidence, classifySectorTopic
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 discovery/javascript/202609010015-sector-topic-evidence.mjs:1-49 · blob be4c5c27ae715c586abf59066eb6eec9bd830dfe · 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
/** Affirmative, item-local evidence rules for neutral sector intelligence. */

export const ACTIVE_SECTOR_TOPICS = Object.freeze([
  "DATA_CENTRES",
  "INVERTER_SECURITY_POLICY",
  "GREAT_GRID_UPGRADE",
  "WORLDWIDE_PV",
  "MV_HV_COMPONENTS",
]);

export function normaliseSectorEvidence(value) {
  return String(value || "")
    .normalize("NFKD")
    .replace(/[^a-z0-9+/. -]+/giu, " ")
    .replace(/\s+/gu, " ")
    .trim()
    .toLocaleLowerCase("en-GB");
}

export function classifySectorTopic({ title, summary = null }) {
  const text = normaliseSectorEvidence(`${title || ""} ${summary || ""}`);

  if (/\bdata cent(?:re|er)s?\b/u.test(text)) {
    return { topic: "DATA_CENTRES", rule: "DATA_CENTRE_EXPLICIT" };
  }

  if (/\b(solar|photovoltaic|pv|inverter|pcs|power conversion)\b/u.test(text)
      && /\b(cyber\w*|security|vulnerab\w*|covered list|ban\w*|regulat\w*)\b/u.test(text)) {
    return { topic: "INVERTER_SECURITY_POLICY", rule: "POWER_ELECTRONICS_AND_SECURITY" };
  }

  if (/\bgreat grid upgrade\b/u.test(text)
      || (/\b(grid|electricity transmission|transmission network|substation|interconnector)\b/u.test(text)
          && /\b(upgrade|network|investment|connection\w*|reinforcement|programme|program)\b/u.test(text))) {
    return { topic: "GREAT_GRID_UPGRADE", rule: "GRID_ASSET_AND_PROGRAMME" };
  }

  if (/\b(solar|photovoltaic|pv|module|inverter)\b/u.test(text)
      && /\b(deployment|capacity|installation\w*|market|manufactur\w*|supply chain|surge|growth|record high\w*|auction|tender)\b/u.test(text)) {
    return { topic: "WORLDWIDE_PV", rule: "PV_AND_DEPLOYMENT" };
  }

  if (/\b(transformer|switchgear|circuit breaker|cable|conductor|substation|busbar|insulator|gis|hvdc)\b/u.test(text)
      && /\b(grid|voltage|procurement|manufactur\w*|outage|supply chain|rating|kv)\b/u.test(text)) {
    return { topic: "MV_HV_COMPONENTS", rule: "COMPONENT_AND_ENGINEERING" };
  }

  return null;
}

JavaScript Sector Intelligence Runner

A JavaScript module in the discovery folder of PipelineNews that reads PipelineNews centres and search, using SHA-256 from the data-centres-GB repository.

storagepipelinenews / discovery/javascript/202609010719-sector-intelligence-runner.mjs · lines 1–521 of 944 · version 2026-09-01 07:19 · Entry point · pattern fixtureFetch (shared by 2 files)

What it does
It loads PipelineNews centres and search. Defines 33 functions or classes, including sha256, canonicalJson, decodeEntity, linearCleanText, cleanText. Uses libraries node:assert/strict, node:crypto, node:fs/promises, node:path, node:url. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
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: data-centres-gb data; JSON file 202608271727-pipelinenews-data-centres.json; JSON file search.json; command-line arguments.
Downstream impact
Used directly by 1 file: Sector Ledger Relevance Proof (pipelinenews).
What it achieves
It decodes entity (`decodeEntity`), cleans text (`cleanText`) and scans feed entries (`scanFeedEntries`). Defines `sha256`, `canonicalJson`, `decodeEntity` and 29 more.
Why it matters
Imported by Sector Ledger Relevance Proof.
Application
pipelinenews · discovery/javascript · JavaScript module
Uses
node:assert/strict, node:crypto, node:fs/promises, node:path, node:url
Used by
imported by Sector Ledger Relevance Proof (import)
Produces
GENERATION, cleanText, scanFeedEntries, failureCode, fetchBounded, validateContract, collectSectorIntelligence
Defines here
sha256, canonicalJson, decodeEntity, linearCleanText, cleanText, iso, httpsUrl, stableItemId, staleness, itemRow, topicRow, tagBoundary, boundedRaw, scanFeedEntries, nextOpening, rawTagValue, rawLinkHref, rssItems, govukItems, ownerExportItems, failureCode, fetchBounded
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 discovery/javascript/202609010719-sector-intelligence-runner.mjs:1-521 · blob f8bcac9cd84065e352f884767e05a0421a4a8fa0 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node

import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";

export const GENERATION = "202609010719";
const CONTRACT_SCHEMA = "pipelinenews.sector-intelligence-contract.v3";
const FIXTURE_SCHEMA = "pipelinenews.sector-intelligence-fixture.v3";
const LEDGER_SCHEMA = "pipelinenews.sector-intelligence-ledger.v3";
const USAGE_CONTEXT = "NON_COMMERCIAL_OPEN_SOURCE";
const NETWORK_ADAPTERS = new Set(["PINNED_OWNER_EXPORT_V1", "GOVUK_SEARCH_V1", "OFFICIAL_RSS_V1"]);
const LOCAL_ADAPTERS = new Set(["FROZEN_GENERIC_NEWS_V1", "STATIC_LINK_V1"]);
const FORBIDDEN_ITEM_FIELDS = new Set([
  "repd_ref", "gg_project_id", "project", "technology", "capacity_mw", "operator", "county", "related_context_repd_ref",
]);
const ITEM_FIELDS = Object.freeze([
  "intelligence_item_id", "generation", "item_kind", "source_id", "source_item_id", "title", "summary",
  "canonical_url", "source_published_at", "observed_at", "collection_anchor_at", "staleness_state", "status",
  "evidence_class", "usage_context", "source_licence_id", "source_terms_url", "redistribution_rights",
  "attribution", "owner_repository", "owner_generation", "owner_record_id", "generic_article_id", "value_min",
  "value_max", "unit", "eligible_for_news_signal",
]);
const TOPIC_FIELDS = Object.freeze([
  "intelligence_item_id", "topic_code", "generation", "assignment_basis", "display_rank", "eligible_for_news_signal",
]);
const BINDING_FIELDS = Object.freeze([
  "intelligence_item_id", "repd_ref", "binding_role", "generation", "decision", "evidence", "eligible_for_news_signal",
]);
const APPROVED_LIMITS = Object.freeze({
  maximum_network_requests: 9,
  maximum_concurrency: 3,
  maximum_results_per_source: 6,
  maximum_total_items: 96,
  maximum_rows_per_browser_topic: 24,
  request_timeout_ms: 5000,
  maximum_response_bytes: 1048576,
  maximum_feed_entries_scanned: 48,
  maximum_feed_scan_operations: 512,
  maximum_raw_feed_entry_characters: 65536,
  maximum_raw_feed_field_characters: 8192,
  maximum_raw_feed_tag_characters: 2048,
  maximum_raw_text_characters: 8192,
  maximum_title_characters: 180,
  maximum_summary_characters: 300,
  maximum_url_characters: 700,
  redirects: 0,
  retained_raw_html_bytes: 0,
  retained_article_body_bytes: 0,
  retained_search_snippet_characters: 0,
});
const APPROVED_TIME_PROVENANCE = Object.freeze({
  generation_label_timezone: "Europe/London",
  generation_label_utc_anchor: "2026-08-27T20:30:00Z",
  live_collection_anchor_field: "collection_anchor_at",
  live_collection_anchor_basis: "ACTIONS_LIVE_COLLECTION_STARTED_AT",
  github_run_id_is_execution_provenance: true,
  collection_anchor_claims_wall_clock_fetch_time: true,
});
const APPROVED_SOURCE_CLOSURE = Object.freeze([
  { id: "DATA_CENTRES_OWNER_EXPORT", topic_code: "DATA_CENTRES", adapter: "PINNED_OWNER_EXPORT_V1", source_url: "https://raw.githubusercontent.com/Ventusltd/data-centres-gb/432864748d3af7b5fffcc51b65804aa6903672dd/exports/202608271727-pipelinenews-data-centres.json", item_hosts: ["www.bbc.co.uk"] },
  { id: "FROZEN_GENERIC_DATA_CENTRE_NEWS", topic_code: "DATA_CENTRES", adapter: "FROZEN_GENERIC_NEWS_V1", source_url: "https://github.com/Ventusltd/pipelinenews", item_hosts: ["news.google.com"] },
  { id: "GOVUK_INVERTER_SECURITY", topic_code: "INVERTER_SECURITY_POLICY", adapter: "GOVUK_SEARCH_V1", source_url: "https://www.gov.uk/api/search.json?count=6&order=-public_timestamp&q=solar%20inverter%20cyber%20security", item_hosts: ["www.gov.uk"] },
  { id: "FCC_CURRENT_COVERED_LIST", topic_code: "INVERTER_SECURITY_POLICY", adapter: "STATIC_LINK_V1", source_url: "https://www.fcc.gov/supplychain/coveredlist", item_hosts: ["www.fcc.gov"] },
  { id: "FCC_EDOCS_NEWS_RSS", topic_code: "INVERTER_SECURITY_POLICY", adapter: "OFFICIAL_RSS_V1", source_url: "https://api2.fcc.gov/edocs/public/api/v1/rss/docTypes/News_Release", item_hosts: ["www.fcc.gov", "docs.fcc.gov", "api2.fcc.gov"] },
  { id: "EC_ENERGY_RSS", topic_code: "INVERTER_SECURITY_POLICY", adapter: "OFFICIAL_RSS_V1", source_url: "https://energy.ec.europa.eu/node/2/rss_en", item_hosts: ["energy.ec.europa.eu"] },
  { id: "GOVUK_GRID_UPGRADE", topic_code: "GREAT_GRID_UPGRADE", adapter: "GOVUK_SEARCH_V1", source_url: "https://www.gov.uk/api/search.json?count=6&order=-public_timestamp&q=Great%20Grid%20Upgrade%20electricity%20transmission", item_hosts: ["www.gov.uk"] },
  { id: "NATIONAL_GRID_GREAT_GRID_UPGRADE", topic_code: "GREAT_GRID_UPGRADE", adapter: "STATIC_LINK_V1", source_url: "https://www.nationalgrid.com/the-great-grid-upgrade", item_hosts: ["www.nationalgrid.com"] },
  { id: "OFGEM_GRID_RSS", topic_code: "GREAT_GRID_UPGRADE", adapter: "OFFICIAL_RSS_V1", source_url: "https://www.ofgem.gov.uk/rss.xml", item_hosts: ["www.ofgem.gov.uk"] },
  { id: "GOVUK_WORLDWIDE_PV", topic_code: "WORLDWIDE_PV", adapter: "GOVUK_SEARCH_V1", source_url: "https://www.gov.uk/api/search.json?count=6&order=-public_timestamp&q=global%20solar%20photovoltaic%20deployment", item_hosts: ["www.gov.uk"] },
  { id: "EIA_SOLAR_RSS", topic_code: "WORLDWIDE_PV", adapter: "OFFICIAL_RSS_V1", source_url: "https://www.eia.gov/rss/todayinenergy.xml", item_hosts: ["www.eia.gov", "eia.gov"] },
  { id: "GOVUK_MV_HV_COMPONENTS", topic_code: "MV_HV_COMPONENTS", adapter: "GOVUK_SEARCH_V1", source_url: "https://www.gov.uk/api/search.json?count=6&order=-public_timestamp&q=power%20transformer%20high%20voltage%20cable%20grid", item_hosts: ["www.gov.uk"] },
]);
const APPROVED_SOURCE_TERMS = Object.freeze([
  "https://github.com/Ventusltd/data-centres-gb",
  "https://policies.google.com/terms",
  "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
  "https://www.usa.gov/government-copyright",
  "https://www.usa.gov/government-copyright",
  "https://commission.europa.eu/legal-notice_en",
  "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
  "https://www.nationalgrid.com/terms-and-conditions",
  "https://www.ofgem.gov.uk/c-ofgem-2026",
  "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
  "https://www.eia.gov/about/copyrights_reuse.php",
  "https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/",
]);

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

function canonicalJson(value) {
  return Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
}

function decodeEntity(token) {
  const named = { amp: "&", quot: "\"", apos: "'", lt: "<", gt: ">", nbsp: " " };
  const lower = token.toLocaleLowerCase("en-GB");
  if (Object.hasOwn(named, lower)) return named[lower];
  let codePoint = null;
  if (lower.startsWith("#x") && /^[a-f0-9]+$/u.test(lower.slice(2))) codePoint = Number.parseInt(lower.slice(2), 16);
  else if (lower.startsWith("#") && /^[0-9]+$/u.test(lower.slice(1))) codePoint = Number.parseInt(lower.slice(1), 10);
  if (Number.isSafeInteger(codePoint) && codePoint >= 0 && codePoint <= 0x10ffff && !(codePoint >= 0xd800 && codePoint <= 0xdfff)) {
    return String.fromCodePoint(codePoint);
  }
  return null;
}

function linearCleanText(raw) {
  const source = raw.startsWith("<![CDATA[") && raw.endsWith("]]>") ? raw.slice(9, -3) : raw;
  const output = [];
  let inTag = false;
  let pendingSpace = false;
  for (let index = 0; index < source.length; index += 1) {
    const character = source[index];
    if (inTag) {
      if (character === ">") {
        inTag = false;
        pendingSpace = output.length > 0;
      }
      continue;
    }
    if (character === "<") {
      inTag = true;
      continue;
    }
    let retained = character;
    if (character === "&") {
      let semicolon = -1;
      const entityWindowEnd = Math.min(source.length, index + 19);
      for (let probe = index + 1; probe < entityWindowEnd; probe += 1) {
        if (source[probe] === ";") {
          semicolon = probe;
          break;
        }
      }
      if (semicolon > index) {
        const decoded = decodeEntity(source.slice(index + 1, semicolon));
        if (decoded !== null) {
          retained = decoded;
          index = semicolon;
        }
      }
    }
    const whitespace = retained === " " || retained === "\t" || retained === "\r" || retained === "\n" || retained === "\f";
    if (whitespace) {
      pendingSpace = output.length > 0;
      continue;
    }
    if (pendingSpace) output.push(" ");
    output.push(retained);
    pendingSpace = false;
  }
  return output.join("");
}

export function cleanText(value, maximum, { nullable = false, rawMaximum = APPROVED_LIMITS.maximum_raw_text_characters } = {}) {
  const raw = String(value ?? "");
  assert.ok(raw.length <= rawMaximum, "retained text exceeds its raw pre-parse bound");
  const text = linearCleanText(raw);
  if (!text && nullable) return null;
  assert.ok(text, "required retained text is empty");
  assert.ok([...text].length <= maximum, "retained text exceeds its declared bound");
  return text;
}

function iso(value, label, { nullable = false, dateOnly = false } = {}) {
  if ((value === null || value === undefined || value === "") && nullable) return null;
  const input = dateOnly && /^\d{4}-\d{2}-\d{2}$/u.test(String(value)) ? `${value}T00:00:00Z` : String(value);
  const timestamp = Date.parse(input);
  assert.ok(Number.isFinite(timestamp), `${label} is not an ISO-compatible timestamp`);
  return new Date(timestamp).toISOString().replace(".000Z", "Z");
}

function httpsUrl(value, label, allowedHosts = null) {
  assert.ok(String(value || "").length <= 700, `${label} exceeds the URL bound`);
  const parsed = new URL(String(value));
  assert.equal(parsed.protocol, "https:", `${label} must be HTTPS`);
  assert.equal(parsed.username, "", `${label} contains credentials`);
  assert.equal(parsed.password, "", `${label} contains credentials`);
  assert.equal(parsed.port, "", `${label} must use the default HTTPS port`);
  assert.equal(parsed.hash, "", `${label} must not contain a fragment`);
  for (const key of parsed.searchParams.keys()) {
    assert.doesNotMatch(key, /(?:api[_-]?key|token|secret|password|credential)/iu, `${label} has a secret-shaped parameter`);
  }
  if (allowedHosts) assert.ok(allowedHosts.includes(parsed.hostname), `${label} host is outside the closed allowlist`);
  return parsed.href;
}

function stableItemId(sourceId, sourceItemId, canonicalUrl) {
  const digest = sha256(Buffer.from([sourceId, sourceItemId, canonicalUrl].join("\u001f")));
  return `GG2050-SECTOR-ITEM-${digest.slice(0, 20).toUpperCase()}`;
}

function staleness(sourceAt, collectionAnchorAt, staleAfterHours) {
  const reference = Date.parse(sourceAt || collectionAnchorAt);
  const age = Math.max(0, (Date.parse(collectionAnchorAt) - reference) / 3_600_000);
  return age > staleAfterHours ? "STALE" : "CURRENT";
}

function itemRow(source, values, collectionAnchorAt, limits) {
  const url = httpsUrl(values.canonical_url, `${source.id} item URL`, source.item_hosts);
  const sourceItemId = cleanText(values.source_item_id || url, 500);
  const published = iso(values.source_published_at, `${source.id} source_published_at`, { nullable: true, dateOnly: true });
  const observed = iso(values.observed_at || published || collectionAnchorAt, `${source.id} observed_at`, { dateOnly: true });
  const row = {
    intelligence_item_id: stableItemId(source.id, sourceItemId, url),
    generation: GENERATION,
    item_kind: values.item_kind || "SOURCE_METADATA",
    source_id: source.id,
    source_item_id: sourceItemId,
    title: cleanText(values.title, limits.maximum_title_characters),
    summary: cleanText(values.summary, limits.maximum_summary_characters, { nullable: true }),
    canonical_url: url,
    source_published_at: published,
    observed_at: observed,
    collection_anchor_at: collectionAnchorAt,
    staleness_state: staleness(published || observed, collectionAnchorAt, source.stale_after_hours),
    status: values.status || "RETAINED_METADATA",
    evidence_class: values.evidence_class || source.evidence_class,
    usage_context: USAGE_CONTEXT,
    source_licence_id: cleanText(values.source_licence_id || source.source_licence_id, 180),
    source_terms_url: httpsUrl(values.source_terms_url || source.source_terms_url, `${source.id} terms URL`),
    redistribution_rights: cleanText(values.redistribution_rights || source.redistribution_rights, 240),
    attribution: cleanText(values.attribution || source.attribution, 300),
    owner_repository: values.owner_repository || null,
    owner_generation: values.owner_generation || null,
    owner_record_id: values.owner_record_id || null,
    generic_article_id: values.generic_article_id || null,
    value_min: values.value_min ?? null,
    value_max: values.value_max ?? null,
    unit: values.unit || null,
    eligible_for_news_signal: false,
  };
  assert.deepEqual(Object.keys(row), ITEM_FIELDS);
  for (const field of FORBIDDEN_ITEM_FIELDS) assert.equal(Object.hasOwn(row, field), false);
  return row;
}

function topicRow(item, source, topicRanks, assignmentBasis) {
  const row = {
    intelligence_item_id: item.intelligence_item_id,
    topic_code: source.topic_code,
    generation: GENERATION,
    assignment_basis: assignmentBasis,
    display_rank: topicRanks.get(source.topic_code),
    eligible_for_news_signal: false,
  };
  assert.deepEqual(Object.keys(row), TOPIC_FIELDS);
  return row;
}

function tagBoundary(character) {
  return character === ">" || character === "/" || " \t\r\n".includes(character);
}

function boundedRaw(value, maximum, label) {
  assert.equal(typeof value, "string", `${label} is not text`);
  assert.ok(value.length <= maximum, `${label} exceeds its raw pre-parse bound`);
  return value;
}

export function scanFeedEntries(text, limits) {
  assert.equal(typeof text, "string", "feed body is not text");
  assert.ok(text.length <= limits.maximum_response_bytes, "decoded feed exceeds its response-character bound");
  for (const field of [
    "maximum_feed_entries_scanned", "maximum_feed_scan_operations", "maximum_raw_feed_entry_characters",
    "maximum_raw_feed_field_characters", "maximum_raw_feed_tag_characters",
  ]) assert.ok(Number.isSafeInteger(limits[field]) && limits[field] > 0, `invalid RSS bound: ${field}`);
  const lower = text.toLocaleLowerCase("en-GB");
  const entries = [];
  let cursor = 0;
  let entriesScanned = 0;
  let operations = 0;
  let terminalReason = "END_OF_FEED";
  function nextOpening() {
    while (cursor < lower.length) {
      if (operations >= limits.maximum_feed_scan_operations) {
        return { operation_limit: true };
      }
      operations += 1;
      const start = lower.indexOf("<", cursor);
      if (start < 0) {
        cursor = lower.length;
        return null;
      }
      cursor = start + 1;
      for (const kind of ["item", "entry"]) {
        const after = start + kind.length + 1;
        if (lower.startsWith(`<${kind}`, start) && tagBoundary(lower[after] || "")) {
          return { kind, start };
        }
      }
    }
    return null;
  }
  while (entriesScanned < limits.maximum_feed_entries_scanned) {
    const opening = nextOpening();
    if (opening?.operation_limit) {
      terminalReason = "OPERATION_LIMIT";
      break;
    }
    if (!opening) break;
    entriesScanned += 1;
    if (operations >= limits.maximum_feed_scan_operations) {
      terminalReason = "OPERATION_LIMIT";
      break;
    }
    operations += 1;
    const openEnd = lower.indexOf(">", opening.start + opening.kind.length + 1);
    if (openEnd < 0) {
      terminalReason = "MALFORMED_OPEN_TAG";
      break;
    }
    if (openEnd - opening.start + 1 > limits.maximum_raw_feed_tag_characters) {
      terminalReason = "ENTRY_RAW_LIMIT";
      break;
    }
    if (operations >= limits.maximum_feed_scan_operations) {
      terminalReason = "OPERATION_LIMIT";
      break;
    }
    operations += 1;
    const closeToken = `</${opening.kind}>`;
    const closeStart = lower.indexOf(closeToken, openEnd + 1);
    if (closeStart < 0) {
      terminalReason = "MALFORMED_UNCLOSED_ENTRY";
      break;
    }
    const contentStart = openEnd + 1;
    const contentLength = closeStart - contentStart;
    if (contentLength > limits.maximum_raw_feed_entry_characters) {
      terminalReason = "ENTRY_RAW_LIMIT";
      break;
    }
    entries.push({ kind: opening.kind, content_start: contentStart, content_end: closeStart });
    cursor = closeStart + closeToken.length;
  }
  if (terminalReason === "END_OF_FEED" && entriesScanned >= limits.maximum_feed_entries_scanned) {
    const extra = nextOpening();
    if (extra?.operation_limit) terminalReason = "OPERATION_LIMIT";
    else if (extra) terminalReason = "ENTRY_LIMIT";
  }
  return {
    entries,
    entries_scanned: entriesScanned,
    scan_operations: operations,
    terminal_reason: terminalReason,
  };
}

function rawTagValue(block, tag, limits) {
  boundedRaw(block, limits.maximum_raw_feed_entry_characters, `${tag} entry`);
  const lower = block.toLocaleLowerCase("en-GB");
  let cursor = 0;
  for (let probe = 0; probe < 32; probe += 1) {
    const start = lower.indexOf(`<${tag}`, cursor);
    if (start < 0) return "";
    const after = start + tag.length + 1;
    if (!tagBoundary(lower[after] || "")) {
      cursor = start + 1;
      continue;
    }
    const openEnd = lower.indexOf(">", after);
    if (openEnd < 0) return "";
    assert.ok(openEnd - start + 1 <= limits.maximum_raw_feed_tag_characters, `${tag} opening tag exceeds its raw pre-parse bound`);
    const closeStart = lower.indexOf(`</${tag}>`, openEnd + 1);
    if (closeStart < 0) return "";
    assert.ok(closeStart - openEnd - 1 <= limits.maximum_raw_feed_field_characters, `${tag} value exceeds its raw pre-parse bound`);
    return block.slice(openEnd + 1, closeStart);
  }
  throw new Error(`${tag} tag probe limit exceeded`);
}

function rawLinkHref(block, limits) {
  const lower = block.toLocaleLowerCase("en-GB");
  let cursor = 0;
  for (let probe = 0; probe < 32; probe += 1) {
    const start = lower.indexOf("<link", cursor);
    if (start < 0) return "";
    const after = start + 5;
    if (!tagBoundary(lower[after] || "")) {
      cursor = start + 1;
      continue;
    }
    const openEnd = lower.indexOf(">", after);
    if (openEnd < 0) return "";
    assert.ok(openEnd - start + 1 <= limits.maximum_raw_feed_tag_characters,
      "link opening tag exceeds its raw pre-parse bound");
    const opening = block.slice(start, openEnd + 1);
    const href = opening.match(/\bhref\s*=\s*["']([^"']+)["']/iu)?.[1] || "";
    return boundedRaw(href, limits.maximum_raw_feed_field_characters, "link href");
  }
  throw new Error("link tag probe limit exceeded");
}

function rssItems(source, text, collectionAnchorAt, limits) {
  const scan = scanFeedEntries(text, limits);
  if (scan.terminal_reason !== "END_OF_FEED") {
    const error = new Error(scan.terminal_reason);
    error.code = ["ENTRY_LIMIT", "OPERATION_LIMIT"].includes(scan.terminal_reason) ? "SCAN_LIMIT" : "FEED_FORMAT";
    throw error;
  }
  const keywords = source.retained_if_any_keywords.map((word) => word.toLocaleLowerCase("en-GB"));
  const retained = [];
  for (const descriptor of scan.entries) {
    const block = text.slice(descriptor.content_start, descriptor.content_end);
    try {
      const title = cleanText(rawTagValue(block, "title", limits), limits.maximum_title_characters);
      if (!keywords.some((keyword) => title.toLocaleLowerCase("en-GB").includes(keyword))) continue;
      const link = cleanText(rawLinkHref(block, limits) || rawTagValue(block, "link", limits), limits.maximum_url_characters);
      const guid = cleanText(rawTagValue(block, "guid", limits) || rawTagValue(block, "id", limits) || link, 500);
      const published = rawTagValue(block, "pubDate", limits) || rawTagValue(block, "published", limits)
        || rawTagValue(block, "updated", limits) || null;
      retained.push({
        source_item_id: guid,
        title,
        canonical_url: link,
        source_published_at: iso(published, `${source.id} RSS date`, { nullable: true }),
        observed_at: iso(published || collectionAnchorAt, `${source.id} RSS observation`),
        summary: null,
        status: "RETAINED_METADATA",
      });
    } catch {
      // A malformed item is rejected without weakening the bounded source result.
    }
    if (retained.length >= limits.maximum_results_per_source) break;
  }
  return retained;
}

function govukItems(source, text, collectionAnchorAt, limits) {
  const payload = JSON.parse(text);
  assert.ok(Array.isArray(payload.results), `${source.id} GOV.UK results are missing`);
  return payload.results.slice(0, limits.maximum_results_per_source).flatMap((result) => {
    try {
      const canonical = new URL(String(result.link || result.url), "https://www.gov.uk").href;
      const published = result.public_timestamp || result.first_published_at || result.updated_at || null;
      return [{
        source_item_id: cleanText(result.content_id || canonical, 500),
        title: cleanText(result.title, limits.maximum_title_characters),
        canonical_url: canonical,
        source_published_at: iso(published, `${source.id} GOV.UK date`, { nullable: true }),
        observed_at: iso(published || collectionAnchorAt, `${source.id} GOV.UK observation`),
        summary: null,
        status: "RETAINED_METADATA",
      }];
    } catch {
      return [];
    }
  });
}

function ownerExportItems(source, text, contract, fixtureMode) {
  const payload = JSON.parse(text);
  const owner = contract.federation.data_centres;
  assert.equal(payload.schema, "pipelinenews-data-centres-intelligence-v1");
  assert.equal(payload.generation, owner.owner_generation);
  assert.equal(payload.usage_context, USAGE_CONTEXT);
  assert.ok(Array.isArray(payload.records));
  if (!fixtureMode) assert.equal(payload.records.length, contract.invariants.owner_metric_rows_expected);
  return payload.records.map((record) => {
    assert.equal(record.record_kind, "CONTEXT_METRIC");
    assert.equal(record.section, "DATA_CENTRES");
    assert.equal(record.usage_context, USAGE_CONTEXT);
    assert.equal(record.eligible_for_project_signal, false);
    return {
      source_item_id: record.record_id,
      item_kind: "CONTEXT_METRIC",
      title: record.title,
      summary: record.summary,
      canonical_url: record.source_url,
      source_published_at: record.source_date,
      observed_at: record.source_date,
      status: "FEDERATED_OWNER_CONTEXT",
      evidence_class: "FEDERATED_OWNER_CONTEXT",
      source_licence_id: record.source_licence,
      source_terms_url: source.source_terms_url,
      redistribution_rights: record.source_rights_status,
      attribution: record.source_attribution,
      owner_repository: owner.owner_repository,
      owner_generation: owner.owner_generation,
      owner_record_id: record.record_id,
      value_min: record.value_min,
      value_max: record.value_max,
      unit: record.unit,
    };
  });
}

export function failureCode(error) {
  const value = String(error?.code || error?.name || "BOUNDED_FAILURE").toUpperCase();
  if (value.includes("ABORT")) return "TIMEOUT";
  if (value.includes("RESPONSE_LIMIT")) return "RESPONSE_LIMIT";
  if (value.includes("HTTP")) return "HTTP_STATUS";
  if (value.includes("SCAN_LIMIT")) return "SCAN_LIMIT";
  if (value.includes("FEED_FORMAT")) return "FEED_FORMAT";
  return "NETWORK_OR_FORMAT_FAILURE";
}

export async function fetchBounded(source, fetchImpl, limits) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), limits.request_timeout_ms);
  try {
    const response = await fetchImpl(httpsUrl(source.source_url, `${source.id} source URL`), {
      headers: { Accept: "application/json, application/rss+xml, application/xml, text/xml, text/html;q=0.1, */*;q=0.01" },
      redirect: "error",
      signal: controller.signal,
    });
    if (!response.ok) {
      const error = new Error("HTTP_STATUS");
      error.code = "HTTP_STATUS";
      throw error;
    }
    const declared = Number(response.headers.get("content-length") || 0);
    if (declared > limits.maximum_response_bytes) {
      const error = new Error("RESPONSE_LIMIT");
      error.code = "RESPONSE_LIMIT";