GLOBALGRID2050 / EXPLORE CODE

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

JavaScript BBC Enrichment and 2 more files

A JavaScript module in the discovery folder of PipelineNews that decodes entities (`decodeHtmlEntities`), finds phrase (`findPhrase`) and parses tag attributes (`parseTagAttributes`).

613 lines of JavaScript and Python from pipelinenews, in 3 files. Topic: Electricity markets and data pipelines. Section 1010 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. BBC RSS other · pipelinenews / discovery/bbc_rss.py lines 1–20
  2. Datacentre Binder energy-data · pipelinenews / discovery/datacentre-binder.mjs lines 1–138
  3. JavaScript BBC Enrichment ingest · pipelinenews / discovery/javascript/202608270844-bbc-enrichment.mjs lines 1–455

BBC RSS

A Python command-line tool in the discovery folder of PipelineNews.

otherpipelinenews / discovery/bbc_rss.py · lines 1–20 of 20 · Entry point

What it does
Uses libraries sys, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Downstream impact
Used directly by 1 file: Build RSS Candidate (pipelinenews). Reached from 1 other entry point, including PipelineNews Coverage Contract Workflow (pipelinenews).
What it achieves
Compatibility entry point for the BBC RSS collector in news.bbc.
Why it matters
Run by Build RSS Candidate.
Application
pipelinenews · discovery · Python CLI
Uses
Articles (import), Collector (import), Sources (import), sys, pathlib
Used by
run by Build RSS Candidate (script call)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 discovery/bbc_rss.py:1-20 · blob a5f4276ea814eacd70bfe0974fee74b0f3ae8883 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Compatibility entry point for the BBC RSS collector in news.bbc."""

import sys
from pathlib import Path

if not __package__:
    sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from news.bbc.articles import TOPIC, canonical_article, merge_items, parse_feed
from news.bbc.collector import NoRedirect, collect, main
from news.bbc.sources import MAX_BYTES, MAX_ITEMS, SECTIONS

__all__ = [
    "TOPIC", "canonical_article", "merge_items", "parse_feed",
    "NoRedirect", "collect", "main", "MAX_BYTES", "MAX_ITEMS", "SECTIONS",
]


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

Datacentre Binder

A JavaScript module in the discovery folder of PipelineNews that works with UK datacentre pipeline and the Renewable Energy Planning Database (REPD) register, using SHA-256.

energy-datapipelinenews / discovery/datacentre-binder.mjs · lines 1–138 of 138 · pattern distinctive (shared by 2 files)

What it does
It calculates UK datacentre pipeline and the REPD register. Defines 10 functions or classes, including normalise, distinctive, mentions, verifyRegisterBytes, noteValue. Uses libraries node:crypto.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'datacentre'): 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.
Downstream impact
Used directly by 1 file: Datacentre Binder Test (pipelinenews). Reached from 1 other entry point, including PipelineNews BBC RSS Discovery Workflow (pipelinenews).
What it achieves
It verifies register bytes (`verifyRegisterBytes`), builds sites (`buildSites`) and binds centre (`bindDataCentreItem`). Data-centre topic binder: news items -> released GridAtlas data-centre register site ids.
Why it matters
Checked by Datacentre Binder Test.
Application
pipelinenews · discovery · JavaScript module
Uses
JavaScript Sector Topic Evidence (import), node:crypto
Used by
imported by Datacentre Binder Test (import)
Produces
DC_SCHEMA, DC_REGISTER_PIN, normalise, verifyRegisterBytes, buildSites, bindDataCentreItem, bindDataCentres
Defines here
normalise, distinctive, mentions, verifyRegisterBytes, noteValue, operatorList, buildSites, chain, bindDataCentreItem, bindDataCentres
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/datacentre-binder.mjs:1-138 · blob 22b64270da1179f8761b412d7d5a0f5e120a3021 · 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
// Data-centre topic binder: news items -> released GridAtlas data-centre register site ids.
//
// Source of truth (NL-019, until Agent A or the owner says otherwise): GridAtlas
// data/uk_datacentre_pipeline_202610312133.geojson, 226 sites, sha256 pinned below
// and in the GridAtlas offtakers overlay (atlas/modules/202610312138-uk-offtakers-overlay.js:12).
//
// Rules
// - Topic gate: the existing sector rule (discovery/javascript/202609010015-sector-topic-evidence.mjs)
//   must say DATA_CENTRES. Nothing else is bound here.
// - A data centre is its own category. It never receives a REPD ref or a GG2050-REPD id.
// - Bind to a dc_site_id only when exactly one site name is named in the headline, or named
//   in the text and corroborated by its place or operator. An operator alone (Equinix runs
//   11 listed sites) or a place alone ("west London") is never a site identity.
// - Publication (NL-019 decision, Agent A 2026-11-14): a site named in an article is a
//   review item, not a published binding. Every result has publish:false and dc_site_id:null;
//   a unique named site is returned as review_candidate.dc_site_id for the review queue.
// - Map status comes from the register: EXACT_SITE, APPROXIMATE (settlement/region centroid,
//   not from the source) or NO_MAP when geometry is missing. Nothing is invented.
import {createHash} from 'node:crypto';
import {classifySectorTopic} from './javascript/202609010015-sector-topic-evidence.mjs';

export const DC_SCHEMA = 'pipelinenews.datacentre-binding.v1';
export const DC_REGISTER_PIN = Object.freeze({
  repository: 'Ventusltd/gridatlas',
  path: 'data/uk_datacentre_pipeline_202610312133.geojson',
  sha256: '87337db5d3bf7959f7f605d3abd029dd4196ab24a79107ceb95210c5b7751654',
  sites: 226,
});

const DC_DESCRIPTORS = new Set(['data', 'centre', 'centres', 'center', 'centers', 'datacentre', 'datacentres', 'campus', 'dc',
  'hyperscale', 'facility', 'site', 'park', 'building', 'hall', 'phase', 'ai', 'growth', 'zone', 'supercomputer', 'computing',
  'colocation', 'colo', 'the', 'of', 'and', 'at', 'land', 'unnamed', 'new', 'next', 'national', 'uk', 'ltd', 'limited', 'plc',
  'north', 'south', 'east', 'west', 'road', 'lane', 'former', 'landfill', 'services', 'it', 'technology', 'group']);

export const normalise = value => String(value ?? '').normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase()
  .replace(/&/g, ' and ').replace(/\([^)]*\)/g, ' ').replace(/[^a-z0-9]+/g, ' ').replace(/\s+/g, ' ').trim();
const distinctive = alias => alias.split(' ').filter(token => token.length > 1 && !DC_DESCRIPTORS.has(token) && !/^\d+$/.test(token));
const mentions = (text, phrase) => Boolean(phrase) && new RegExp(`(^|[^a-z0-9])${phrase.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}($|[^a-z0-9])`).test(text);

export function verifyRegisterBytes(bytes, pin = DC_REGISTER_PIN) {
  const digest = createHash('sha256').update(bytes).digest('hex');
  if (digest !== pin.sha256) throw Error(`Data-centre register digest ${digest} does not match pin ${pin.sha256}`);
  const register = JSON.parse(bytes);
  if (register?.type !== 'FeatureCollection' || !Array.isArray(register.features)) throw Error('Not a GeoJSON FeatureCollection');
  if (register.features.length !== pin.sites) throw Error(`Register has ${register.features.length} sites, pin says ${pin.sites}`);
  return register;
}

const noteValue = (notes, key) => (notes ?? []).find(note => note.startsWith(`${key}:`))?.slice(key.length + 1).trim() ?? null;

const operatorList = p => String(p.operator ?? '').split(/;|\//).map(part => normalise(part.replace(/\(.*$/, ''))).filter(Boolean);

export function buildSites(register) {
  // Operators that run several listed sites: their name never identifies one site.
  const operatorSites = new Map();
  for (const feature of register.features) for (const operator of new Set(operatorList(feature.properties ?? {}))) operatorSites.set(operator, (operatorSites.get(operator) ?? 0) + 1);
  const chain = name => [...operatorSites].some(([operator, count]) => count > 1 && (name === operator || name === `${operator} data centre` || name === `${operator} data centres`));
  const sites = register.features.map(feature => {
    const p = feature.properties ?? {};
    const precision = p.location?.precision ?? 'unknown';
    const geometry = feature.geometry?.type === 'Point' && Array.isArray(feature.geometry.coordinates) ? feature.geometry.coordinates : null;
    const operators = operatorList(p);
    const place = noteValue(p.notes, 'place');
    const places = [p.location?.local_authority, ...(place ? place.split(',') : [])].map(normalise).filter(value => value && value.length >= 4);
    const nameAliases = [p.name, ...(p.aliases ?? [])].map(normalise).filter(Boolean);
    // A name that is only a multi-site operator's name or "unnamed data centre" identifies no site.
    const identities = new Set();
    for (const alias of nameAliases) {
      if (!distinctive(alias).length) continue;
      if (chain(alias)) continue;
      identities.add(alias);
      const core = alias.split(' ').filter(token => !['data', 'centre', 'centres', 'center', 'campus', 'datacentre'].includes(token)).join(' ').trim();
      if (core && core !== alias && distinctive(core).length) identities.add(core);
    }
    return {
      dc_site_id: p.id ?? feature.id, name: p.name ?? null, status: p.status ?? 'unknown', operator: p.operator ?? null,
      operators, places, identities: [...identities],
      it_load_mw: p.it_load_mw?.value ?? null, grid_connection_mw: p.grid_connection_mw?.value ?? null, unclassified_mw: p.unclassified_mw?.value ?? null,
      precision, longitude: geometry?.[0] ?? null, latitude: geometry?.[1] ?? null,
      map_status: !geometry ? 'NO_MAP' : precision === 'exact_site' ? 'EXACT_SITE' : 'APPROXIMATE',
      evidence_urls: p.evidence_urls ?? [],
    };
  });
  const index = new Map();
  for (const site of sites) for (const alias of site.identities) {
    const list = index.get(alias) ?? []; list.push(site); index.set(alias, list);
  }
  return {sites, index, aliases: [...index.keys()].sort((a, b) => b.length - a.length)};
}

export function bindDataCentreItem(item, register) {
  const headline = String(item.headline ?? item.title ?? '');
  const body = [item.summary, item.snippet, item.evidence_snippet].filter(Boolean).join(' ');
  const topic = classifySectorTopic({title: headline, summary: body || null});
  const base = {schema: DC_SCHEMA, category: 'DATA_CENTRE', repd_ref: null, topic: topic?.topic ?? null, topic_rule: topic?.rule ?? null,
    outcome: 'NOT_DATA_CENTRE_TOPIC', reason: null, publish: false, dc_site_id: null, review_candidate: null, map_status: null, candidates: []};
  if (topic?.topic !== 'DATA_CENTRES') return base;
  const h = normalise(headline), all = normalise(`${headline} ${body}`);
  const hits = [];
  for (const alias of register.aliases) {
    if (!mentions(all, alias)) continue;
    if (hits.some(hit => hit.alias.includes(alias))) continue; // a longer accepted name covers it
    for (const site of register.index.get(alias)) hits.push({alias, site, headline: mentions(h, alias)});
  }
  const bySite = new Map();
  for (const hit of hits) {
    const row = bySite.get(hit.site.dc_site_id) ?? {site: hit.site, aliases: new Set(), headline: false};
    row.aliases.add(hit.alias); row.headline ||= hit.headline; bySite.set(hit.site.dc_site_id, row);
  }
  for (const row of bySite.values()) {
    row.place = row.site.places.some(place => mentions(all, place));
    row.operator = row.site.operators.some(operator => operator.length >= 3 && mentions(all, operator));
    row.strong = [...row.aliases].some(alias => distinctive(alias).length >= 2 || alias.split(' ').length >= 3);
  }
  const usable = [...bySite.values()].filter(row => (row.headline && (row.strong || row.place || row.operator)) || (row.place && row.operator));
  const candidates = [...bySite.values()].map(row => ({dc_site_id: row.site.dc_site_id, name: row.site.name, status: row.site.status,
    aliases: [...row.aliases], in_headline: row.headline, place: row.place, operator: row.operator}));
  if (!bySite.size) {
    const operatorSites = register.sites.filter(site => site.operators.some(operator => operator.length >= 3 && mentions(all, operator)));
    return {...base, outcome: operatorSites.length ? 'OPERATOR_ONLY' : 'TOPIC_ONLY',
      reason: operatorSites.length ? `OPERATOR_NAMED_${operatorSites.length}_SITES` : 'NO_REGISTER_SITE_NAMED',
      candidates: operatorSites.slice(0, 20).map(site => ({dc_site_id: site.dc_site_id, name: site.name, status: site.status}))};
  }
  if (usable.length !== 1) return {...base, outcome: usable.length ? 'AMBIGUOUS' : 'CONTEXT_ONLY', reason: usable.length ? 'SEVERAL_SITES_NAMED' : 'SITE_NAME_WITHOUT_CORROBORATION', candidates};
  const site = usable[0].site;
  return {...base, outcome: 'SITE_NAME_MATCH_REVIEW', reason: usable[0].headline ? 'HEADLINE' : 'TEXT_WITH_PLACE_AND_OPERATOR',
    review_candidate: {queue: 'REVIEW', dc_site_id: site.dc_site_id},
    site_name: site.name, site_status: site.status, map_status: site.map_status,
    latitude: site.map_status === 'NO_MAP' ? null : site.latitude, longitude: site.map_status === 'NO_MAP' ? null : site.longitude,
    it_load_mw: site.it_load_mw, grid_connection_mw: site.grid_connection_mw, candidates};
}

export function bindDataCentres(items, register) {
  const results = items.map(item => ({item_id: item.id ?? item.url, ...bindDataCentreItem(item, register)}));
  const counts = {};
  for (const row of results) counts[row.outcome] = (counts[row.outcome] ?? 0) + 1;
  return {schema: DC_SCHEMA, register: DC_REGISTER_PIN, counts, results};
}

JavaScript BBC Enrichment

A JavaScript module in the discovery folder of PipelineNews that decodes entities (`decodeHtmlEntities`), finds phrase (`findPhrase`) and parses tag attributes (`parseTagAttributes`).

ingestpipelinenews / discovery/javascript/202608270844-bbc-enrichment.mjs · lines 1–455 of 455 · version 2026-08-27 08:44 · pattern isPlainObject (shared by 2 files)

What it does
It lists and searches its content. Defines 25 functions or classes, including BbcEnrichmentError, fail, isPlainObject, compactText, decodeHtmlEntities.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Downstream impact
Used directly by 2 files: JavaScript Live News Runner (pipelinenews); Check BBC Enrichment (pipelinenews). Reached from 2 other entry points, including PipelineNews Coverage Contract Workflow (pipelinenews); Check Live News Candidate (pipelinenews).
What it achieves
It decodes HTML entities (`decodeHtmlEntities`), finds phrase (`findPhrase`) and parses tag attributes (`parseTagAttributes`). Defines `BbcEnrichmentError`, `fail`, `isPlainObject` and 22 more.
Why it matters
Imported by JavaScript Live News Runner. Checked by Check BBC Enrichment.
Application
pipelinenews · discovery/javascript · JavaScript module
Uses
none found
Used by
imported by JavaScript Live News Runner (import), imported by Check BBC Enrichment (import), mentioned in Standalone (comment link)
Produces
BBC_ENRICHMENT_LIMITS, BbcEnrichmentError, validateBbcArticleUrl, extractBbcArticleMetadata, fetchBbcArticleMetadata, enrichBbcArticle, classifyEnrichedBbcArticle
Defines here
BbcEnrichmentError, fail, isPlainObject, compactText, decodeHtmlEntities, escapeRegExp, exactPhraseRegExp, findPhrase, boundedSnippet, parseTagAttributes, metaContent, findNewsArticleJsonLd, visit, jsonLdAboutNames, articlePlainText, validateBbcArticleUrl, internalArticleUrls, normaliseGazetteer, extractBbcArticleMetadata, readBoundedHtml, fetchBbcArticleMetadata, abort, enrichBbcArticle, evidenceText, classifyEnrichedBbcArticle
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/202608270844-bbc-enrichment.mjs:1-455 · blob 3e550f7e9ee2844d5957520e1f9b86282a168ebf · 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: production_core
const BBC_ORIGIN = 'https://www.bbc.co.uk';
const BBC_ARTICLE_PATH = /^\/news\/articles\/[a-z0-9]+$/;
const MAX_INTERNAL_ARTICLE_LINKS = 10;

export const BBC_ENRICHMENT_LIMITS = Object.freeze({
  request_timeout_ms: 5_000,
  response_bytes: 1_048_576,
  snippet_chars: 300,
  max_link_depth: 1,
  max_internal_article_links: MAX_INTERNAL_ARTICLE_LINKS,
});

export class BbcEnrichmentError extends Error {
  constructor(code) {
    super(code);
    this.name = 'BbcEnrichmentError';
    this.code = code;
  }
}

function fail(code) {
  throw new BbcEnrichmentError(code);
}

function isPlainObject(value) {
  if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
  const prototype = Object.getPrototypeOf(value);
  return prototype === Object.prototype || prototype === null;
}

function compactText(value) {
  return String(value ?? '').replace(/\s+/g, ' ').trim();
}

function decodeHtmlEntities(value) {
  const named = new Map([
    ['amp', '&'],
    ['apos', "'"],
    ['gt', '>'],
    ['hellip', '…'],
    ['ldquo', '“'],
    ['lsquo', '‘'],
    ['lt', '<'],
    ['nbsp', ' '],
    ['pound', '£'],
    ['quot', '"'],
    ['rdquo', '”'],
    ['rsquo', '’'],
    ['ndash', '–'],
    ['mdash', '—'],
  ]);

  return String(value ?? '').replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (match, token) => {
    if (token[0] === '#') {
      const radix = token[1]?.toLowerCase() === 'x' ? 16 : 10;
      const digits = radix === 16 ? token.slice(2) : token.slice(1);
      const codePoint = Number.parseInt(digits, radix);
      if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) return match;
      try {
        return String.fromCodePoint(codePoint);
      } catch {
        return match;
      }
    }
    return named.get(token.toLowerCase()) ?? match;
  });
}

function escapeRegExp(value) {
  return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function exactPhraseRegExp(phrase) {
  return new RegExp(`(^|[^\\p{L}\\p{N}])(${escapeRegExp(phrase)})(?=$|[^\\p{L}\\p{N}])`, 'iu');
}

function findPhrase(text, phrase) {
  const match = exactPhraseRegExp(phrase).exec(text);
  return match ? match.index + match[1].length : -1;
}

function boundedSnippet(text, phrase, maximum = BBC_ENRICHMENT_LIMITS.snippet_chars) {
  const clean = compactText(text);
  const index = findPhrase(clean, phrase);
  if (index < 0) return '';
  const before = Math.max(0, index - Math.floor((maximum - phrase.length) / 2));
  const after = Math.min(clean.length, before + maximum);
  let snippet = clean.slice(before, after).trim();
  if (before > 0) snippet = `…${snippet.slice(1)}`;
  if (after < clean.length) snippet = `${snippet.slice(0, -1)}…`;
  return snippet.slice(0, maximum);
}

function parseTagAttributes(tag) {
  const attributes = Object.create(null);
  const pattern = /([:\w-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
  let match;
  while ((match = pattern.exec(tag))) {
    const key = match[1].toLowerCase();
    if (key === 'meta' || key === 'a' || key === 'link') continue;
    attributes[key] = decodeHtmlEntities(match[2] ?? match[3] ?? match[4] ?? '');
  }
  return attributes;
}

function metaContent(html, key, expected) {
  const tags = String(html).match(/<meta\b[^>]*>/gi) ?? [];
  for (const tag of tags) {
    const attributes = parseTagAttributes(tag);
    if (String(attributes[key] ?? '').toLowerCase() === expected.toLowerCase()) {
      return compactText(attributes.content);
    }
  }
  return '';
}

function findNewsArticleJsonLd(html) {
  const scripts = String(html).match(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>[\s\S]*?<\/script>/gi) ?? [];
  const candidates = [];

  const visit = (node) => {
    if (Array.isArray(node)) {
      for (const child of node) visit(child);
      return;
    }
    if (!isPlainObject(node)) return;
    const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']];
    if (types.some((type) => ['NewsArticle', 'Article', 'ReportageNewsArticle'].includes(type))) {
      candidates.push(node);
    }
    if (Array.isArray(node['@graph'])) visit(node['@graph']);
  };

  for (const script of scripts) {
    const body = script.replace(/^<script\b[^>]*>/i, '').replace(/<\/script>$/i, '').trim();
    try {
      visit(JSON.parse(body));
    } catch {
      // Invalid JSON-LD is ignored; BBC metadata tags remain authoritative input.
    }
  }
  return candidates[0] ?? null;
}

function jsonLdAboutNames(article) {
  const values = Array.isArray(article?.about) ? article.about : article?.about ? [article.about] : [];
  return values
    .map((entry) => (typeof entry === 'string' ? entry : entry?.name))
    .map(compactText)
    .filter(Boolean);
}

function articlePlainText(html) {
  return compactText(decodeHtmlEntities(
    String(html)
      .replace(/<!--[\s\S]*?-->/g, ' ')
      .replace(/<(script|style|noscript|svg|template)\b[^>]*>[\s\S]*?<\/\1>/gi, ' ')
      .replace(/<[^>]+>/g, ' '),
  ));
}

export function validateBbcArticleUrl(value) {
  if (typeof value !== 'string' || value.length > 200) fail('BBC_URL_INVALID');
  let url;
  try {
    url = new URL(value);
  } catch {
    fail('BBC_URL_INVALID');
  }
  if (
    url.origin !== BBC_ORIGIN
    || url.protocol !== 'https:'
    || url.hostname !== 'www.bbc.co.uk'
    || url.port
    || url.username
    || url.password
    || url.search
    || url.hash
    || !BBC_ARTICLE_PATH.test(url.pathname)
  ) {
    fail('BBC_URL_NOT_APPROVED');
  }
  const canonical = `${BBC_ORIGIN}${url.pathname}`;
  if (value !== canonical) fail('BBC_URL_NOT_CANONICAL');
  return canonical;
}

function internalArticleUrls(html, articleUrl) {
  const urls = [];
  const seen = new Set([articleUrl]);
  const tags = String(html).match(/<a\b[^>]*>/gi) ?? [];
  for (const tag of tags) {
    const href = parseTagAttributes(tag).href;
    if (!href) continue;
    let candidate;
    try {
      candidate = new URL(href, articleUrl).toString();
      candidate = validateBbcArticleUrl(candidate);
    } catch {
      continue;
    }
    if (seen.has(candidate)) continue;
    seen.add(candidate);
    urls.push(candidate);
    if (urls.length === MAX_INTERNAL_ARTICLE_LINKS) break;
  }
  return urls;
}

function normaliseGazetteer(gazetteer) {
  if (!Array.isArray(gazetteer)) fail('BBC_GAZETTEER_INVALID');
  return gazetteer.map((entry) => {
    if (!isPlainObject(entry) || typeof entry.repd_ref !== 'string' || !Array.isArray(entry.aliases)) {
      fail('BBC_GAZETTEER_INVALID');
    }
    const aliases = [...new Set([entry.name, ...entry.aliases].map(compactText).filter(Boolean))];
    if (!aliases.length) fail('BBC_GAZETTEER_INVALID');
    return { repd_ref: entry.repd_ref, name: compactText(entry.name), aliases };
  });
}

export function extractBbcArticleMetadata(html, articleUrl, options = {}) {
  const url = validateBbcArticleUrl(articleUrl);
  if (typeof html !== 'string' || Buffer.byteLength(html, 'utf8') > BBC_ENRICHMENT_LIMITS.response_bytes) {
    fail('BBC_HTML_INVALID');
  }
  const gazetteer = normaliseGazetteer(options.gazetteer ?? []);
  const subjectNames = [...new Set((options.subject_names ?? []).map(compactText).filter(Boolean))];
  const jsonLd = findNewsArticleJsonLd(html);
  const headline = compactText(
    metaContent(html, 'property', 'og:title')
      || metaContent(html, 'name', 'twitter:title')
      || jsonLd?.headline,
  );
  const publishedAt = compactText(
    metaContent(html, 'property', 'article:published_time')
      || jsonLd?.datePublished,
  );
  const description = compactText(
    metaContent(html, 'property', 'og:description')
      || metaContent(html, 'name', 'description')
      || jsonLd?.description,
  ).slice(0, BBC_ENRICHMENT_LIMITS.snippet_chars);
  if (!headline || headline.length > 300) fail('BBC_HEADLINE_INVALID');
  if (publishedAt && Number.isNaN(Date.parse(publishedAt))) fail('BBC_PUBLICATION_DATE_INVALID');

  const text = articlePlainText(html);
  const aboutNames = [...new Set(jsonLdAboutNames(jsonLd))].slice(0, 10);
  const searchSpaces = [
    ['headline', headline],
    ['description', description],
    ['about', aboutNames.join(' | ')],
    ['article', text],
  ];
  const phrases = [];
  for (const entry of gazetteer) {
    for (const alias of entry.aliases) phrases.push({ alias, repd_ref: entry.repd_ref, canonical_name: entry.name });
  }
  for (const name of subjectNames) phrases.push({ alias: name, repd_ref: null, canonical_name: name });

  const mentions = [];
  const seen = new Set();
  const evidenceSnippets = [];
  for (const phrase of phrases) {
    const locations = searchSpaces.filter(([, space]) => findPhrase(space, phrase.alias) >= 0).map(([location]) => location);
    if (!locations.length) continue;
    const key = `${phrase.repd_ref ?? ''}\u0000${phrase.alias.toLowerCase()}`;
    if (seen.has(key)) continue;
    seen.add(key);
    const snippet = boundedSnippet(text, phrase.alias);
    if (snippet && !evidenceSnippets.includes(snippet)) evidenceSnippets.push(snippet);
    mentions.push({
      mention: phrase.alias,
      canonical_name: phrase.canonical_name,
      repd_ref: phrase.repd_ref,
      locations,
      evidence_snippet: snippet,
    });
  }

  return Object.freeze({
    schema: 'pipelinenews.bbc-article-compact.v1',
    url,
    headline,
    published_at: publishedAt || null,
    description,
    about_names: aboutNames,
    exact_project_mentions: mentions,
    internal_article_urls: internalArticleUrls(html, url),
    evidence_snippets: evidenceSnippets.slice(0, 20),
  });
}

async function readBoundedHtml(response) {
  const declaredLength = Number(response.headers?.get?.('content-length'));
  if (Number.isFinite(declaredLength) && declaredLength > BBC_ENRICHMENT_LIMITS.response_bytes) {
    fail('BBC_RESPONSE_TOO_LARGE');
  }
  const chunks = [];
  let total = 0;
  if (response.body?.getReader) {
    const reader = response.body.getReader();
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      total += value.byteLength;
      if (total > BBC_ENRICHMENT_LIMITS.response_bytes) {
        await reader.cancel().catch(() => {});
        fail('BBC_RESPONSE_TOO_LARGE');
      }
      chunks.push(value);
    }
  } else if (typeof response.arrayBuffer === 'function') {
    const bytes = new Uint8Array(await response.arrayBuffer());
    total = bytes.byteLength;
    if (total > BBC_ENRICHMENT_LIMITS.response_bytes) fail('BBC_RESPONSE_TOO_LARGE');
    chunks.push(bytes);
  } else {
    fail('BBC_RESPONSE_BODY_INVALID');
  }
  const joined = new Uint8Array(total);
  let offset = 0;
  for (const chunk of chunks) {
    joined.set(chunk, offset);
    offset += chunk.byteLength;
  }
  return new TextDecoder('utf-8', { fatal: false }).decode(joined);
}

export async function fetchBbcArticleMetadata(articleUrl, options = {}) {
  const url = validateBbcArticleUrl(articleUrl);
  const fetchImpl = options.fetch_impl ?? globalThis.fetch;
  if (typeof fetchImpl !== 'function') fail('BBC_FETCH_UNAVAILABLE');
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), BBC_ENRICHMENT_LIMITS.request_timeout_ms);
  const externalSignal = options.signal;
  const abort = () => controller.abort();
  externalSignal?.addEventListener?.('abort', abort, { once: true });
  try {
    const response = await fetchImpl(url, {
      method: 'GET',
      redirect: 'error',
      signal: controller.signal,
      headers: {
        accept: 'text/html,application/xhtml+xml;q=0.9',
        'user-agent': 'PipelineNews-Live-News-Discovery/202608270844',
      },
    });
    if (!response || response.status !== 200) fail('BBC_RESPONSE_NOT_OK');
    if (response.redirected) fail('BBC_REDIRECT_REJECTED');
    if (response.url && response.url !== url) fail('BBC_REDIRECT_REJECTED');
    const contentType = String(response.headers?.get?.('content-type') ?? 'text/html').toLowerCase();
    if (!contentType.includes('text/html') && !contentType.includes('application/xhtml+xml')) {
      fail('BBC_RESPONSE_TYPE_REJECTED');
    }
    const html = await readBoundedHtml(response);
    return extractBbcArticleMetadata(html, url, options);
  } catch (error) {
    if (error instanceof BbcEnrichmentError) throw error;
    fail(controller.signal.aborted ? 'BBC_REQUEST_TIMEOUT' : 'BBC_REQUEST_FAILED');
  } finally {
    clearTimeout(timeout);
    externalSignal?.removeEventListener?.('abort', abort);
  }
}

export async function enrichBbcArticle(articleUrl, options = {}) {
  const requestedDepth = options.max_link_depth ?? BBC_ENRICHMENT_LIMITS.max_link_depth;
  if (!Number.isInteger(requestedDepth) || requestedDepth < 0 || requestedDepth > BBC_ENRICHMENT_LIMITS.max_link_depth) {
    fail('BBC_LINK_DEPTH_INVALID');
  }
  const root = await fetchBbcArticleMetadata(articleUrl, options);
  const linkedArticles = [];
  if (requestedDepth === 1) {
    for (const url of root.internal_article_urls.slice(0, MAX_INTERNAL_ARTICLE_LINKS)) {
      linkedArticles.push(await fetchBbcArticleMetadata(url, options));
    }
  }
  return Object.freeze({
    schema: 'pipelinenews.bbc-enrichment.v1',
    root,
    linked_articles: linkedArticles,
    health: Object.freeze({
      fetched_articles: 1 + linkedArticles.length,
      maximum_link_depth: requestedDepth,
      retained_raw_html: false,
      retained_article_bodies: false,
      request_timeout_ms: BBC_ENRICHMENT_LIMITS.request_timeout_ms,
      response_bytes: BBC_ENRICHMENT_LIMITS.response_bytes,
      snippet_chars: BBC_ENRICHMENT_LIMITS.snippet_chars,
    }),
  });
}

function evidenceText(article) {
  return compactText([
    article.headline,
    article.description,
    ...(article.about_names ?? []),
    ...(article.evidence_snippets ?? []),
  ].join(' '));
}

export function classifyEnrichedBbcArticle(article, contract) {
  if (!isPlainObject(article) || article.schema !== 'pipelinenews.bbc-article-compact.v1') {
    fail('BBC_COMPACT_ARTICLE_INVALID');
  }
  validateBbcArticleUrl(article.url);
  const gazetteer = normaliseGazetteer(contract?.gazetteer ?? []);
  const returnedEvidence = evidenceText(article);
  if (/\bwind\s*(?:farm|turbine|energy|power)?\b/i.test(returnedEvidence)) {
    return Object.freeze({ outcome: 'REJECT', reason: 'WIND_EXCLUDED', repd_ref: null });
  }
  const foreignTerms = Array.isArray(contract?.foreign_conflict_terms) ? contract.foreign_conflict_terms : [];
  if (foreignTerms.some((term) => findPhrase(returnedEvidence, term) >= 0)) {
    return Object.freeze({ outcome: 'REJECT', reason: 'FOREIGN_CONFLICT', repd_ref: null });
  }

  const subjectEvidence = compactText([article.headline, ...(article.about_names ?? [])].join(' '));
  const excludedSubject = (contract?.excluded_primary_subjects ?? []).find(
    (subject) => findPhrase(subjectEvidence, subject.name) >= 0,
  );
  const matches = [];
  for (const entry of gazetteer) {
    const aliases = entry.aliases.filter((alias) => findPhrase(returnedEvidence, alias) >= 0);
    if (!aliases.length) continue;
    const headlineAliases = aliases.filter((alias) => findPhrase(article.headline, alias) >= 0);
    const aboutAliases = aliases.filter((alias) => (article.about_names ?? []).some((name) => findPhrase(name, alias) >= 0));
    const original = contract.gazetteer.find((item) => item.repd_ref === entry.repd_ref);
    const corroborated = Boolean(
      original?.planning_reference && findPhrase(returnedEvidence, original.planning_reference) >= 0,
    );
    matches.push({ repd_ref: entry.repd_ref, aliases, headlineAliases, aboutAliases, corroborated });
  }
  if (excludedSubject) {
    if (matches.length === 1) {
      return Object.freeze({
        outcome: 'RELATED_MENTION',
        reason: 'NON_REPD_PRIMARY_WITH_EDITORIAL_CONTEXT',
        repd_ref: null,
        related_context_repd_ref: matches[0].repd_ref,
        primary_subject: excludedSubject.name,
      });
    }
    return Object.freeze({ outcome: 'ABSTAIN', reason: 'NON_REPD_PRIMARY_AMBIGUOUS', repd_ref: null });
  }
  const direct = matches.filter((match) => match.headlineAliases.length || match.aboutAliases.length || match.corroborated);
  if (direct.length === 1) {
    return Object.freeze({ outcome: 'PRIMARY_MATCH', reason: 'RETURNED_PUBLISHER_EVIDENCE', repd_ref: direct[0].repd_ref });
  }
  if (!direct.length && matches.length === 1) {
    return Object.freeze({ outcome: 'ABSTAIN', reason: 'BODY_MENTION_ONLY', repd_ref: null });
  }
  return Object.freeze({ outcome: 'ABSTAIN', reason: matches.length ? 'AMBIGUOUS_IDENTITY' : 'NO_CLOSED_GAZETTEER_MATCH', repd_ref: null });
}