GLOBALGRID2050 / EXPLORE CODE

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

JavaScript Live News Runner (part 2)

A JavaScript module in the discovery folder of PipelineNews that reads live news discovery contract, solar, battery storage (BESS) and the Renewable Energy Planning Database (REPD) register.

611 lines of JavaScript from pipelinenews, in 1 file. Topic: Electricity markets and data pipelines. Section 1012 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 Live News Runner storage · pipelinenews / discovery/javascript/202608270844-live-news-runner.mjs lines 701–1311

JavaScript Live News Runner

A JavaScript module in the discovery folder of PipelineNews that reads live news discovery contract, solar, battery storage (BESS) and the Renewable Energy Planning Database (REPD) register.

storagepipelinenews / discovery/javascript/202608270844-live-news-runner.mjs · lines 701–1311 of 1311 · version 2026-08-27 08:44 (continued from section 1011) · pattern isPlainObject (shared by 2 files)

What it does
It loads live news discovery contract, solar, battery storage (BESS) and the REPD register. Defines 44 functions or classes, including LiveNewsDiscoveryError, fail, isPlainObject, assertPlainObject, assertExactKeys. Uses libraries node:fs/promises, node:path, node:url. 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, battery storage (BESS), the REPD register.
Inputs & outputs
In: JSON file 202608270844-live-news-discovery-contract.json; command-line arguments.
Downstream impact
Used directly by 2 files: Check BBC Enrichment (pipelinenews); Check Live News Candidate (pipelinenews). Reached from 1 other entry point, including PipelineNews Coverage Contract Workflow (pipelinenews).
What it achieves
It gets project (`getProject`), validates canonical contract (`validateCanonicalContract`) and normalises discovery contract (`normaliseDiscoveryContract`). Defines `LiveNewsDiscoveryError`, `fail`, `isPlainObject` and 41 more.
Why it matters
Checked by 2 tests, including Check BBC Enrichment.
Application
pipelinenews · discovery/javascript · JavaScript module
Uses
JavaScript BBC Enrichment (import), node:fs/promises, node:path, node:url
Used by
imported by Check BBC Enrichment (import), imported by Check Live News Candidate (import)
Produces
GENERATION, LIMITS, LiveNewsDiscoveryError, normaliseDiscoveryContract, validateApprovedEvidence, approvedEvidenceToNewsItems, compileApprovedBbcRecords, selectEligibleProjects, buildBoundedQueryPlan, parseBingNewsRss, searchNewsProvider, configuredOptionalProviders
Defines here
validateApprovedEvidence, approvedEvidenceToNewsItems, selectEligibleProjects, quoteQueryTerm, buildBoundedQueryPlan, decodeXml, xmlTag, parseBingNewsRss, readBoundedText, providerRequest, secretValue, compactProviderItem, searchNewsProvider, configuredOptionalProviders, classifySearchResult, collectLiveNews, cliArguments, resolveOutput, loadCollectorInputs, writeCliJson, cliMain
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-live-news-runner.mjs:701-1311 · blob 0b9c4038df948be1ada8d3a010c3cc229a096537 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core

    const related = record.binding?.role === 'RELATED_MENTION';
    const metadataKeys = related
      ? ['country', 'county', 'technology', 'primary_subject', 'primary_operator']
      : ['country', 'county', 'technology'];
    assertExactKeys(record.compact_metadata, metadataKeys, `EVIDENCE_${index}_COMPACT_METADATA_INVALID`);
    for (const key of metadataKeys) assertString(record.compact_metadata[key], `EVIDENCE_${index}_COMPACT_METADATA_INVALID`, { maximum: 120 });
    if (!Array.isArray(record.exact_project_mentions) || !record.exact_project_mentions.length) {
      fail(`EVIDENCE_${index}_MENTIONS_INVALID`);
    }
    for (const mention of record.exact_project_mentions) {
      assertExactKeys(mention, ['text', 'canonical_name', 'paragraph_index'], `EVIDENCE_${index}_MENTION_INVALID`);
      assertString(mention.text, `EVIDENCE_${index}_MENTION_INVALID`, { maximum: 120 });
      assertNullableString(mention.canonical_name, `EVIDENCE_${index}_MENTION_INVALID`, 120);
      if (!Number.isInteger(mention.paragraph_index) || mention.paragraph_index < 0) fail(`EVIDENCE_${index}_MENTION_INVALID`);
    }
    if (!Array.isArray(record.internal_article_urls) || record.internal_article_urls.length > 10) {
      fail(`EVIDENCE_${index}_INTERNAL_URLS_INVALID`);
    }
    for (const url of record.internal_article_urls) validateBbcArticleUrl(url);
    if (!Array.isArray(record.bounded_evidence_snippets) || !record.bounded_evidence_snippets.length) {
      fail(`EVIDENCE_${index}_SNIPPETS_INVALID`);
    }
    for (const snippet of record.bounded_evidence_snippets) {
      assertString(snippet, `EVIDENCE_${index}_SNIPPET_INVALID`, { maximum: LIMITS.snippet_chars });
      if (Array.from(snippet).length > LIMITS.snippet_chars || /<\/?(?:html|body|script)\b/i.test(snippet)) {
        fail(`EVIDENCE_${index}_SNIPPET_UNBOUNDED`);
      }
    }

    const primaryBindingKeys = [
      'role',
      'repd_ref',
      'gg_project_id',
      'project',
      'technology',
      'official_capacity_mw',
      'operator',
      'county',
      'country',
      'planning_reference',
      'event',
      'event_detail',
      'confidence',
      'canonical_relevant',
      'eligible_for_news_signal',
      'related_components',
    ];
    const relatedBindingKeys = [
      'role',
      'relationship',
      'repd_ref',
      'gg_project_id',
      'project',
      'technology',
      'official_capacity_mw',
      'operator',
      'county',
      'country',
      'planning_reference',
      'event',
      'event_detail',
      'confidence',
      'canonical_relevant',
      'eligible_for_news_signal',
      'related_context_repd_ref',
      'related_context_project',
      'binding_label',
      'related_components',
    ];
    assertExactKeys(record.binding, related ? relatedBindingKeys : primaryBindingKeys, `EVIDENCE_${index}_BINDING_KEYS_INVALID`);
    if (!Array.isArray(record.binding.related_components)) fail(`EVIDENCE_${index}_RELATED_COMPONENTS_INVALID`);
    if (record.binding.confidence !== 100) fail(`EVIDENCE_${index}_CONFIDENCE_INVALID`);
    if (record.binding.canonical_relevant !== !related) fail(`EVIDENCE_${index}_CANONICAL_FLAG_INVALID`);
    if (related && record.binding.related_context_project !== 'Beacon Fen Energy Park') {
      fail(`EVIDENCE_${index}_RELATED_CONTEXT_PROJECT_INVALID`);
    }
    for (const component of record.binding.related_components) {
      assertExactKeys(component, [
        'role',
        'repd_ref',
        'gg_project_id',
        'project',
        'technology',
        'official_capacity_mw',
        'eligible_for_news_signal',
      ], `EVIDENCE_${index}_RELATED_COMPONENT_KEYS_INVALID`);
      if (component.project !== record.binding.project) fail(`EVIDENCE_${index}_RELATED_COMPONENT_PROJECT_INVALID`);
    }

    return {
      article_id: record.gg_article_id,
      url: record.url,
      headline: record.headline,
      published_at: record.published_at,
      source: record.source,
      confidence: record.binding.confidence,
      evidence: {
        enrichment_url: record.url,
        exact_project_mentions: record.exact_project_mentions.map((mention) => mention.canonical_name ?? mention.text),
        internal_article_urls: [...record.internal_article_urls],
        snippets: [...record.bounded_evidence_snippets],
      },
      binding: {
        role: record.binding.role,
        relationship: record.binding.relationship ?? null,
        repd_ref: record.binding.repd_ref || null,
        gg_project_id: record.binding.gg_project_id || null,
        project_name: record.binding.project,
        technology: record.binding.technology,
        official_capacity_mw: record.binding.official_capacity_mw,
        operator: record.binding.operator,
        county: record.binding.county,
        country: record.binding.country,
        planning_reference: record.binding.planning_reference || null,
        event: record.binding.event,
        event_detail: record.binding.event_detail || null,
        eligible_for_news_signal: record.binding.eligible_for_news_signal,
        related_context_repd_ref: record.binding.related_context_repd_ref ?? null,
        related_context_label: record.binding.binding_label ?? null,
        related_components: record.binding.related_components.map((component) => ({
          role: component.role,
          repd_ref: component.repd_ref,
          gg_project_id: component.gg_project_id,
          technology: component.technology,
          official_capacity_mw: component.official_capacity_mw,
          eligible_for_news_signal: component.eligible_for_news_signal,
        })),
      },
    };
  });
  return {
    schema: EVIDENCE_SCHEMA,
    generation: evidence.generation,
    created_at: new Date(evidence.decision_recorded_at).toISOString(),
    limits: {
      request_timeout_ms: LIMITS.request_timeout_ms,
      response_bytes: LIMITS.response_bytes,
      snippet_chars: evidence.retention.maximum_snippet_characters,
      bbc_link_depth: LIMITS.bbc_link_depth,
    },
    records: canonicalRecords,
  };
}

export function validateApprovedEvidence({ evidence, contract, projectByRef }) {
  const canonicalContract = validateContract(contract);
  const canonicalEvidence = normaliseProductionEvidence(evidence);
  assertExactKeys(canonicalEvidence, ['schema', 'generation', 'created_at', 'limits', 'records'], 'EVIDENCE_ROOT_KEYS_INVALID');
  if (canonicalEvidence.schema !== EVIDENCE_SCHEMA) fail('EVIDENCE_SCHEMA_INVALID');
  if (canonicalEvidence.generation !== GENERATION) fail('EVIDENCE_GENERATION_INVALID');
  assertIsoDate(canonicalEvidence.created_at, 'EVIDENCE_CREATED_AT_INVALID');
  assertExactKeys(canonicalEvidence.limits, ['request_timeout_ms', 'response_bytes', 'snippet_chars', 'bbc_link_depth'], 'EVIDENCE_LIMIT_KEYS_INVALID');
  for (const key of Object.keys(canonicalEvidence.limits)) {
    if (canonicalEvidence.limits[key] !== LIMITS[key]) fail(`EVIDENCE_LIMIT_${key.toUpperCase()}_INVALID`);
  }
  if (!Array.isArray(canonicalEvidence.records) || canonicalEvidence.records.length !== 3) fail('EVIDENCE_RECORD_COUNT_INVALID');
  const expectedById = new Map(canonicalContract.articles.map((article) => [article.article_id, article]));
  const seen = new Set();
  canonicalEvidence.records.forEach((record, index) => {
    const expected = expectedById.get(record?.article_id);
    if (!expected || seen.has(record.article_id)) fail(`EVIDENCE_${index}_ARTICLE_SET_INVALID`);
    seen.add(record.article_id);
    validateEvidenceRecord(record, expected, canonicalContract, projectByRef, index);
  });
  if (seen.size !== expectedById.size) fail('EVIDENCE_ARTICLE_SET_INVALID');
  const primaryMatches = canonicalEvidence.records.filter((record) => record.binding.role === 'PRIMARY_MATCH').length;
  const relatedMentions = canonicalEvidence.records.filter((record) => record.binding.role === 'RELATED_MENTION').length;
  if (primaryMatches !== 2 || relatedMentions !== 1) fail('EVIDENCE_DECISION_COUNTS_INVALID');
  return Object.freeze({
    valid: true,
    generation: GENERATION,
    records: 3,
    primary_matches: primaryMatches,
    related_mentions: relatedMentions,
    eligible_for_news_signal: 2,
    deployment_status: canonicalContract.deployment_status,
  });
}

export function approvedEvidenceToNewsItems({ evidence, contract, projectByRef }) {
  validateApprovedEvidence({ evidence, contract, projectByRef });
  const canonicalEvidence = normaliseProductionEvidence(evidence);
  return canonicalEvidence.records.map((record) => {
    const binding = record.binding;
    return Object.freeze({
      gg_article_id: record.article_id,
      repd_ref: binding.repd_ref,
      gg_project_id: binding.gg_project_id,
      project_name: binding.project_name,
      technology: binding.technology,
      capacity_mw: binding.official_capacity_mw,
      operator: binding.operator,
      county: binding.county,
      country: binding.country,
      event: binding.event,
      event_detail: binding.event_detail,
      headline: record.headline,
      published_at: record.published_at,
      source: record.source,
      url: record.url,
      confidence: record.confidence,
      canonical_relevant: binding.role === 'PRIMARY_MATCH' && binding.eligible_for_news_signal,
      role: binding.role,
      relationship: binding.relationship,
      related_context_repd_ref: binding.related_context_repd_ref,
      related_context_label: binding.related_context_label,
      eligible_for_news_signal: binding.eligible_for_news_signal,
      related_components: binding.related_components.map((component) => Object.freeze({ ...component })),
      exact_project_mentions: [...record.evidence.exact_project_mentions],
      internal_article_urls: [...record.evidence.internal_article_urls],
      evidence_snippets: [...record.evidence.snippets],
    });
  });
}

export const compileApprovedBbcRecords = approvedEvidenceToNewsItems;

export function selectEligibleProjects(projects) {
  if (!Array.isArray(projects)) fail('COLLECTOR_PROJECTS_INVALID');
  return projects
    .filter((project) => {
      const technology = String(project?.technology ?? '').toLowerCase();
      const capacity = Number(project?.capacity_mw);
      if (!Number.isFinite(capacity)) return false;
      if (technology === 'solar') return capacity >= LIMITS.solar_minimum_mw;
      if (technology === 'bess') return capacity >= LIMITS.bess_minimum_mw;
      return false;
    })
    .sort((left, right) => (
      Number(right.capacity_mw) - Number(left.capacity_mw)
      || String(left.repd_ref).localeCompare(String(right.repd_ref), 'en', { numeric: true })
    ))
    .slice(0, LIMITS.selected_projects);
}

function quoteQueryTerm(value) {
  return `"${compactText(value).replace(/["\r\n]/g, ' ')}"`;
}

export function buildBoundedQueryPlan(projects) {
  const selected = selectEligibleProjects(projects);
  const queries = [];
  for (const project of selected) {
    const technologyTerms = project.technology === 'bess' ? 'battery storage' : 'solar';
    queries.push({
      repd_ref: String(project.repd_ref),
      query_index: 0,
      query: `${quoteQueryTerm(project.name)} ${quoteQueryTerm(project.county)} ${technologyTerms}`,
    });
    queries.push({
      repd_ref: String(project.repd_ref),
      query_index: 1,
      query: `${quoteQueryTerm(project.name)} ${quoteQueryTerm(project.operator)} planning`,
    });
  }
  if (queries.length > LIMITS.queries_per_run) fail('COLLECTOR_QUERY_LIMIT_EXCEEDED');
  return Object.freeze({ selected_projects: selected, queries });
}

function decodeXml(value) {
  return compactText(String(value ?? '')
    .replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1')
    .replace(/<[^>]+>/g, ' ')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(/&#39;|&apos;/g, "'")
    .replace(/&amp;/g, '&'));
}

function xmlTag(item, name) {
  const match = new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${name}>`, 'i').exec(item);
  return match ? decodeXml(match[1]) : '';
}

export function parseBingNewsRss(xml) {
  if (typeof xml !== 'string' || Buffer.byteLength(xml, 'utf8') > LIMITS.response_bytes) fail('BING_RSS_INVALID');
  const items = xml.match(/<item(?:\s[^>]*)?>[\s\S]*?<\/item>/gi) ?? [];
  return items.slice(0, LIMITS.results_per_query).map((item) => ({
    title: xmlTag(item, 'title'),
    url: xmlTag(item, 'link'),
    snippet: truncateSnippet(xmlTag(item, 'description')),
    published_at: xmlTag(item, 'pubDate') || null,
    source: xmlTag(item, 'News:Source') || xmlTag(item, 'source') || null,
  })).filter((item) => item.title && item.url);
}

async function readBoundedText(response) {
  const declared = Number(response.headers?.get?.('content-length'));
  if (Number.isFinite(declared) && declared > LIMITS.response_bytes) fail('PROVIDER_RESPONSE_TOO_LARGE');
  const bytes = new Uint8Array(await response.arrayBuffer());
  if (bytes.byteLength > LIMITS.response_bytes) fail('PROVIDER_RESPONSE_TOO_LARGE');
  return new TextDecoder().decode(bytes);
}

async function providerRequest(url, init, fetchImpl) {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), LIMITS.request_timeout_ms);
  try {
    const response = await fetchImpl(url, { ...init, redirect: 'error', signal: controller.signal });
    if (!response || response.status !== 200 || response.redirected) fail('PROVIDER_RESPONSE_NOT_OK');
    return await readBoundedText(response);
  } catch (error) {
    if (error instanceof LiveNewsDiscoveryError) throw error;
    fail(controller.signal.aborted ? 'PROVIDER_REQUEST_TIMEOUT' : 'PROVIDER_REQUEST_FAILED');
  } finally {
    clearTimeout(timeout);
  }
}

function secretValue(secretEnv, key) {
  const value = secretEnv?.[key];
  return typeof value === 'string' && value ? value : null;
}

function compactProviderItem(item) {
  return {
    title: compactText(item.title),
    url: compactText(item.url ?? item.link),
    snippet: truncateSnippet(item.snippet ?? item.description),
    published_at: compactText(item.published_at ?? item.age ?? item.date) || null,
    source: compactText(item.source ?? item.profile?.long_name) || null,
  };
}

export async function searchNewsProvider(query, options = {}) {
  assertString(query, 'PROVIDER_QUERY_INVALID', { maximum: 500 });
  const provider = options.provider ?? 'bing';
  const fetchImpl = options.fetch_impl ?? globalThis.fetch;
  const secretEnv = options.secret_env ?? process.env;
  if (typeof fetchImpl !== 'function') fail('PROVIDER_FETCH_UNAVAILABLE');
  let payload;
  let parsed;
  if (provider === 'bing') {
    const url = new URL('https://www.bing.com/news/search');
    url.searchParams.set('q', query);
    url.searchParams.set('format', 'rss');
    payload = await providerRequest(url, { headers: { accept: 'application/rss+xml,application/xml;q=0.9' } }, fetchImpl);
    return parseBingNewsRss(payload);
  }
  if (provider === 'brave') {
    const key = secretValue(secretEnv, 'BRAVE_SEARCH_API_KEY');
    if (!key) fail('BRAVE_SECRET_NOT_CONFIGURED');
    const url = new URL('https://api.search.brave.com/res/v1/news/search');
    url.searchParams.set('q', query);
    url.searchParams.set('count', String(LIMITS.results_per_query));
    payload = await providerRequest(url, { headers: { accept: 'application/json', 'x-subscription-token': key } }, fetchImpl);
    try { parsed = JSON.parse(payload); } catch { fail('BRAVE_RESPONSE_INVALID'); }
    return (parsed.results ?? []).slice(0, LIMITS.results_per_query).map(compactProviderItem).filter((item) => item.title && item.url);
  }
  if (provider === 'google_cse') {
    const key = secretValue(secretEnv, 'GOOGLE_CSE_API_KEY');
    const cx = secretValue(secretEnv, 'GOOGLE_CSE_ID');
    if (!key || !cx) fail('GOOGLE_CSE_SECRET_NOT_CONFIGURED');
    const url = new URL('https://www.googleapis.com/customsearch/v1');
    url.searchParams.set('key', key);
    url.searchParams.set('cx', cx);
    url.searchParams.set('q', query);
    url.searchParams.set('num', String(LIMITS.results_per_query));
    payload = await providerRequest(url, { headers: { accept: 'application/json' } }, fetchImpl);
    try { parsed = JSON.parse(payload); } catch { fail('GOOGLE_CSE_RESPONSE_INVALID'); }
    return (parsed.items ?? []).slice(0, LIMITS.results_per_query).map((item) => compactProviderItem({
      title: item.title,
      url: item.link,
      snippet: item.snippet,
      source: item.displayLink,
    })).filter((item) => item.title && item.url);
  }
  if (provider === 'serper') {
    const key = secretValue(secretEnv, 'SERPER_API_KEY');
    if (!key) fail('SERPER_SECRET_NOT_CONFIGURED');
    payload = await providerRequest('https://google.serper.dev/news', {
      method: 'POST',
      headers: { accept: 'application/json', 'content-type': 'application/json', 'x-api-key': key },
      body: JSON.stringify({ q: query, num: LIMITS.results_per_query }),
    }, fetchImpl);
    try { parsed = JSON.parse(payload); } catch { fail('SERPER_RESPONSE_INVALID'); }
    return (parsed.news ?? []).slice(0, LIMITS.results_per_query).map(compactProviderItem).filter((item) => item.title && item.url);
  }
  fail('PROVIDER_NOT_APPROVED');
}

export function configuredOptionalProviders(secretEnv = process.env) {
  const providers = [];
  if (secretValue(secretEnv, 'BRAVE_SEARCH_API_KEY')) providers.push('brave');
  if (secretValue(secretEnv, 'GOOGLE_CSE_API_KEY') && secretValue(secretEnv, 'GOOGLE_CSE_ID')) providers.push('google_cse');
  if (secretValue(secretEnv, 'SERPER_API_KEY')) providers.push('serper');
  return providers;
}

export function classifySearchResult(result, contract) {
  const canonicalContract = validateContract(contract);
  assertExactKeys(result, ['title', 'url', 'snippet', 'published_at', 'source'], 'SEARCH_RESULT_KEYS_INVALID');
  const returnedEvidence = compactText([result.title, result.snippet, result.source].join(' '));
  if (/\bwind\s*(?:farm|turbine|energy|power)?\b/i.test(returnedEvidence)) {
    return Object.freeze({ outcome: 'REJECT', reason: 'WIND_EXCLUDED', repd_ref: null });
  }
  if (canonicalContract.foreign_conflict_terms.some((term) => containsPhrase(returnedEvidence, term))) {
    return Object.freeze({ outcome: 'REJECT', reason: 'FOREIGN_CONFLICT', repd_ref: null });
  }
  const matches = canonicalContract.gazetteer.filter((entry) => entry.aliases.some((alias) => containsPhrase(returnedEvidence, alias)));
  const titleMatches = matches.filter((entry) => entry.aliases.some((alias) => containsPhrase(result.title, alias)));
  if (titleMatches.length === 1 && matches.length === 1) {
    return Object.freeze({ outcome: 'PRIMARY_MATCH', reason: 'RETURNED_SEARCH_EVIDENCE', repd_ref: titleMatches[0].repd_ref });
  }
  return Object.freeze({
    outcome: 'ABSTAIN',
    reason: matches.length > 1 ? 'AMBIGUOUS_IDENTITY' : matches.length === 1 ? 'SNIPPET_CONTEXT_ONLY' : 'NO_CLOSED_GAZETTEER_MATCH',
    repd_ref: null,
  });
}

export async function collectLiveNews({
  projects,
  contract,
  provider = 'bing',
  fetch_impl = globalThis.fetch,
  secret_env = process.env,
} = {}) {
  const canonicalContract = validateContract(contract);
  const plan = buildBoundedQueryPlan(projects);
  const candidates = [];
  const outcomes = { PRIMARY_MATCH: 0, RELATED_MENTION: 0, ABSTAIN: 0, REJECT: 0 };
  let completedQueries = 0;
  let failedQueries = 0;
  let bbcRoots = 0;
  let bbcArticles = 0;
  const enrichedUrls = new Set();

  for (const query of plan.queries) {
    let results;
    try {
      results = await searchNewsProvider(query.query, { provider, fetch_impl, secret_env });
      completedQueries += 1;
    } catch {
      failedQueries += 1;
      continue;
    }
    for (const result of results.slice(0, LIMITS.results_per_query)) {
      const searchDecision = classifySearchResult(result, canonicalContract);
      outcomes[searchDecision.outcome] += 1;
      candidates.push(Object.freeze({
        source_stage: 'SEARCH_RESULT',
        provider,
        query_context: { repd_ref: query.repd_ref, query_index: query.query_index },
        returned_evidence: result,
        decision: searchDecision,
      }));

      let exactBbcUrl;
      try { exactBbcUrl = validateBbcArticleUrl(result.url); } catch { continue; }
      if (enrichedUrls.has(exactBbcUrl) || bbcRoots >= LIMITS.bbc_enrichment_roots_per_run) continue;
      enrichedUrls.add(exactBbcUrl);
      bbcRoots += 1;
      try {
        const enriched = await enrichBbcArticle(exactBbcUrl, {
          fetch_impl,
          max_link_depth: LIMITS.bbc_link_depth,
          gazetteer: canonicalContract.gazetteer,
          subject_names: canonicalContract.excluded_primary_subjects.map((subject) => subject.name),
        });
        for (const article of [enriched.root, ...enriched.linked_articles]) {
          bbcArticles += 1;
          const decision = classifyEnrichedBbcArticle(article, canonicalContract);
          outcomes[decision.outcome] += 1;
          candidates.push(Object.freeze({
            source_stage: 'BBC_ENRICHMENT',
            provider,
            query_context: { repd_ref: query.repd_ref, query_index: query.query_index },
            returned_evidence: article,
            decision,
          }));
        }
      } catch {
        // Fail closed. Search evidence remains in the ledger with its own decision.
      }
    }
  }

  return Object.freeze({
    schema: 'pipelinenews.live-news-discovery-run.v1',
    generation: GENERATION,
    deployment_status: 'not-authorised',
    candidates,
    health: Object.freeze({
      provider,
      selected_projects: plan.selected_projects.length,
      queries_planned: plan.queries.length,
      queries_completed: completedQueries,
      queries_failed: failedQueries,
      search_results_retained: candidates.filter((candidate) => candidate.source_stage === 'SEARCH_RESULT').length,
      bbc_enrichment_roots: bbcRoots,
      bbc_articles_enriched: bbcArticles,
      decisions: outcomes,
      secrets_retained: false,
      raw_html_retained: false,
      article_bodies_retained: false,
      limits: {
        ...LIMITS,
        max_internal_article_links: BBC_ENRICHMENT_LIMITS.max_internal_article_links,
      },
    }),
  });
}

function cliArguments(argv) {
  const allowed = new Set(['--collect', '--provider', '--health-out', '--ledger-out']);
  const values = new Map();
  for (let index = 0; index < argv.length; index += 1) {
    const name = argv[index];
    if (!allowed.has(name) || values.has(name)) fail('CLI_ARGUMENT_INVALID');
    if (name === '--collect') {
      values.set(name, true);
      continue;
    }
    const value = argv[index + 1];
    if (!value || value.startsWith('--')) fail('CLI_ARGUMENT_INVALID');
    values.set(name, value);
    index += 1;
  }
  for (const name of allowed) {
    if (!values.has(name)) fail('CLI_ARGUMENT_MISSING');
  }
  const providerAliases = { bing: 'bing', brave: 'brave', google: 'google_cse', google_cse: 'google_cse', serper: 'serper' };
  const provider = providerAliases[values.get('--provider')];
  if (!provider) fail('PROVIDER_NOT_APPROVED');
  return Object.freeze({
    provider,
    health_out: values.get('--health-out'),
    ledger_out: values.get('--ledger-out'),
  });
}

function resolveOutput(root, requested) {
  if (typeof requested !== 'string' || !requested || requested.includes('\\')) fail('CLI_OUTPUT_PATH_INVALID');
  const resolved = path.resolve(root, requested);
  if (!resolved.startsWith(`${root}${path.sep}`)) fail('CLI_OUTPUT_PATH_INVALID');
  return resolved;
}

async function loadCollectorInputs(root) {
  const contract = JSON.parse(await readFile(path.join(
    root,
    'data/news-discovery/202608270844-live-news-discovery-contract.json',
  ), 'utf8'));
  const projectDirectory = path.join(root, 'data/projects');
  const filenames = (await readdir(projectDirectory))
    .filter((name) => /^202608261927-project-partition-v9-1-\d+\.json$/u.test(name))
    .sort();
  if (filenames.length !== 16) fail('COLLECTOR_PROJECT_PARTITIONS_INVALID');
  const projects = [];
  for (const filename of filenames) {
    const partition = JSON.parse(await readFile(path.join(projectDirectory, filename), 'utf8'));
    if (!Array.isArray(partition.projects)) fail('COLLECTOR_PROJECT_PARTITIONS_INVALID');
    projects.push(...partition.projects);
  }
  if (projects.length !== 7_680) fail('COLLECTOR_PROJECT_COUNT_INVALID');
  return { contract, projects };
}

async function writeCliJson(filename, value) {
  await mkdir(path.dirname(filename), { recursive: true });
  await writeFile(filename, `${JSON.stringify(value, null, 2)}\n`, { flag: 'wx' });
}

async function cliMain() {
  const arguments_ = cliArguments(process.argv.slice(2));
  const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
  const { contract, projects } = await loadCollectorInputs(repositoryRoot);
  const run = await collectLiveNews({
    projects,
    contract,
    provider: arguments_.provider,
  });
  const health = {
    schema: 'pipelinenews.live-news-discovery-health.v1',
    generation: run.generation,
    deployment_status: run.deployment_status,
    ...run.health,
  };
  const ledger = {
    schema: run.schema,
    generation: run.generation,
    deployment_status: run.deployment_status,
    candidates: run.candidates,
    secrets_retained: false,
    raw_html_retained: false,
    article_bodies_retained: false,
  };
  await writeCliJson(resolveOutput(repositoryRoot, arguments_.health_out), health);
  await writeCliJson(resolveOutput(repositoryRoot, arguments_.ledger_out), ledger);
  process.stdout.write(`${JSON.stringify({
    generation: run.generation,
    provider: run.health.provider,
    selected_projects: run.health.selected_projects,
    queries_planned: run.health.queries_planned,
    queries_completed: run.health.queries_completed,
    queries_failed: run.health.queries_failed,
    candidates: run.candidates.length,
    deployment_status: run.deployment_status,
  })}\n`);
}

if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
  cliMain().catch((error) => {
    const code = error instanceof LiveNewsDiscoveryError ? error.code : 'COLLECTOR_FAILED';
    process.stderr.write(`${code}\n`);
    process.exitCode = 1;
  });
}