GLOBALGRID2050 / EXPLORE CODE

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

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.

423 lines of JavaScript from pipelinenews, in 1 file. Topic: Electricity markets and data pipelines. Section 1014 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 Intelligence Runner storage · pipelinenews / discovery/javascript/202609010719-sector-intelligence-runner.mjs lines 522–944

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 522–944 of 944 · version 2026-09-01 07:19 (continued from section 1013) · 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
mapLimit, worker, fixtureFetch, bindFixtureSources, validateContract, collectNetworkSource, collectFrozenGeneric, collectStaticLinks, collectSectorIntelligence, parseArguments, 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/202609010719-sector-intelligence-runner.mjs:522-944 · 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
      throw error;
    }
    const chunks = [];
    let total = 0;
    if (response.body) {
      const reader = response.body.getReader();
      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          total += value.byteLength;
          if (total > limits.maximum_response_bytes) {
            await reader.cancel("bounded response limit exceeded");
            const error = new Error("RESPONSE_LIMIT");
            error.code = "RESPONSE_LIMIT";
            throw error;
          }
          chunks.push(Buffer.from(value));
        }
      } finally {
        reader.releaseLock();
      }
    }
    const bytes = Buffer.concat(chunks, total);
    return {
      bytes,
      contentType: String(response.headers.get("content-type") || "application/octet-stream").split(";", 1)[0].toLowerCase(),
    };
  } finally {
    clearTimeout(timer);
  }
}

async function mapLimit(values, limit, mapper) {
  const output = new Array(values.length);
  let cursor = 0;
  async function worker() {
    while (cursor < values.length) {
      const index = cursor;
      cursor += 1;
      output[index] = await mapper(values[index], index);
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, values.length) }, () => worker()));
  return output;
}

function fixtureFetch(fixtures) {
  const byUrl = new Map();
  return async (url) => {
    const source = byUrl.get(url);
    assert.ok(source, `fixture request is undeclared: ${url}`);
    const body = typeof source.body === "string" ? source.body : JSON.stringify(source.body);
    return new Response(body, {
      status: source.status,
      headers: { "content-type": source.content_type, "content-length": String(Buffer.byteLength(body)) },
    });
  };
}

function bindFixtureSources(contract, fixture) {
  const responses = fixture.responses;
  const network = contract.sources.filter(({ adapter }) => NETWORK_ADAPTERS.has(adapter));
  assert.deepEqual(Object.keys(responses).sort(), network.map(({ id }) => id).sort());
  const byUrl = new Map(network.map((source) => [source.source_url, responses[source.id]]));
  return async (url) => {
    const response = byUrl.get(url);
    assert.ok(response, `fixture request is undeclared: ${url}`);
    const body = typeof response.body === "string" ? response.body : JSON.stringify(response.body);
    return new Response(body, {
      status: response.status,
      headers: { "content-type": response.content_type, "content-length": String(Buffer.byteLength(body)) },
    });
  };
}

export function validateContract(contract) {
  assert.equal(contract.schema, CONTRACT_SCHEMA);
  assert.equal(contract.generation, GENERATION);
  assert.equal(contract.deployment, "not-authorised");
  assert.deepEqual(contract.project_posture, {
    owner: "Ventus Ltd",
    application: USAGE_CONTEXT,
    application_usage_establishes_upstream_rights: false,
    publisher_redistribution_rights: "SOURCE_SPECIFIC_NOT_INFERRED",
  });
  assert.deepEqual(contract.time_provenance, APPROVED_TIME_PROVENANCE,
    "time provenance differs from the approved deterministic closure");
  assert.equal(contract.topics.length, 5);
  const topicRanks = new Map(contract.topics.map(({ code, display_rank }) => [code, display_rank]));
  assert.equal(topicRanks.size, 5);
  assert.deepEqual([...topicRanks.values()], [1, 2, 3, 4, 5]);
  assert.equal(contract.datasets.length, 3);
  assert.deepEqual(contract.datasets.map(({ name, key }) => ({ name, key })), [
    { name: "sector_items", key: ["intelligence_item_id"] },
    { name: "sector_item_topics", key: ["intelligence_item_id", "topic_code"] },
    { name: "sector_project_bindings", key: ["intelligence_item_id", "repd_ref", "binding_role"] },
  ]);
  assert.deepEqual(contract.datasets[0].columns.map(({ name }) => name), ITEM_FIELDS);
  assert.deepEqual(contract.datasets[1].columns.map(({ name }) => name), TOPIC_FIELDS);
  assert.deepEqual(contract.datasets[2].columns.map(({ name }) => name), BINDING_FIELDS);
  assert.deepEqual(contract.limits, APPROVED_LIMITS, "bounded acquisition limits differ from the approved closure");
  assert.equal(contract.physical_layout.compression, "ZSTD");
  assert.equal(contract.physical_layout.path_template,
    `releases/data/intelligence/${GENERATION}/{dataset_directory}/${GENERATION}-part-000.parquet`);
  assert.deepEqual(contract.physical_layout.dataset_directories, {
    sector_items: "sector-items",
    sector_item_topics: "sector-item-topics",
    sector_project_bindings: "sector-project-bindings",
  });
  assert.equal(contract.physical_layout.generation_target_policy,
    "IMMUTABLE_FULL_GENERATION_WRITE_FROM_EMPTY_TARGET");
  assert.equal(contract.federation.data_centres.owner_parquet_copied, false);
  assert.equal(contract.federation.companies_house.acquisition_in_pipelinenews, false);
  assert.equal(contract.identity_policy.query_context_may_establish_project_identity, false);
  assert.deepEqual(contract.identity_policy.forbidden_sector_item_fields, [...FORBIDDEN_ITEM_FIELDS]);
  assert.equal(contract.invariants.generic_news_rows, 136);
  assert.equal(contract.invariants.data_centre_generic_rows_sanitised, 6);
  const ids = contract.sources.map(({ id }) => id);
  assert.equal(ids.length, new Set(ids).size);
  assert.deepEqual(contract.sources.map(({ id, topic_code, adapter, source_url, item_hosts }) => ({
    id, topic_code, adapter, source_url, item_hosts,
  })), APPROVED_SOURCE_CLOSURE, "source URL, adapter or item-host closure changed");
  assert.deepEqual(contract.sources.map(({ source_terms_url }) => source_terms_url), APPROVED_SOURCE_TERMS,
    "source terms URL closure changed");
  assert.equal(contract.sources.filter(({ adapter }) => NETWORK_ADAPTERS.has(adapter)).length, contract.limits.maximum_network_requests);
  assert.equal(contract.sources.filter(({ adapter }) => LOCAL_ADAPTERS.has(adapter)).length, 3);
  for (const source of contract.sources) {
    assert.ok(topicRanks.has(source.topic_code));
    assert.ok(NETWORK_ADAPTERS.has(source.adapter) || LOCAL_ADAPTERS.has(source.adapter));
    httpsUrl(source.source_url, `${source.id} source URL`);
    httpsUrl(source.source_terms_url, `${source.id} terms URL`);
    for (const field of ["evidence_class", "source_licence_id", "redistribution_rights", "attribution"]) {
      assert.ok(String(source[field] || "").trim(), `${source.id} lacks ${field}`);
    }
  }
  const nationalGrid = contract.sources.find(({ id }) => id === "NATIONAL_GRID_GREAT_GRID_UPGRADE");
  assert.equal(nationalGrid.adapter, "STATIC_LINK_V1");
  assert.equal(nationalGrid.source_terms_url, "https://www.nationalgrid.com/terms-and-conditions");
  const fcc = contract.sources.find(({ id }) => id === "FCC_CURRENT_COVERED_LIST");
  assert.equal(fcc.adapter, "STATIC_LINK_V1");
  assert.equal(fcc.source_url, "https://www.fcc.gov/supplychain/coveredlist");
  assert.equal(fcc.current_notice_url, "https://docs.fcc.gov/public/attachments/DA-26-870A1.pdf");
  assert.equal(fcc.current_faq_url, "https://www.fcc.gov/covered-list-faqs-robots-inverters");
  assert.equal(fcc.historical_notice_only, "https://docs.fcc.gov/public/attachments/DA-26-786A1.pdf");
  const fccFeed = contract.sources.find(({ id }) => id === "FCC_EDOCS_NEWS_RSS");
  assert.equal(fccFeed.source_url, "https://api2.fcc.gov/edocs/public/api/v1/rss/docTypes/News_Release");
  assert.equal(fccFeed.redistribution_rights,
    "FCC_AUTHORED_OFFICIAL_METADATA_PUBLIC_DOMAIN_THIRD_PARTY_AND_LOGOS_EXCLUDED");
  const eia = contract.sources.find(({ id }) => id === "EIA_SOLAR_RSS");
  assert.equal(eia.redistribution_rights,
    "EIA_AUTHORED_METADATA_PUBLIC_DOMAIN_WITH_ATTRIBUTION_THIRD_PARTY_LOGOS_PHOTOS_EXCLUDED");
  const owner = contract.federation.data_centres;
  assert.match(owner.owner_commit, /^[a-f0-9]{40}$/u);
  assert.match(owner.export_sha256, /^[a-f0-9]{64}$/u);
  assert.match(owner.owner_parquet_sha256, /^[a-f0-9]{64}$/u);
  const ownerSource = contract.sources.find(({ id }) => id === "DATA_CENTRES_OWNER_EXPORT");
  assert.deepEqual(ownerSource.accepted_content_types, ["application/json", "application/ld+json", "text/plain"]);
  return contract;
}

async function collectNetworkSource(source, contract, fetchImpl, collectionAnchorAt, fixtureMode, topicRanks) {
  try {
    const { bytes, contentType } = await fetchBounded(source, fetchImpl, contract.limits);
    if (source.adapter === "PINNED_OWNER_EXPORT_V1") {
      assert.ok(source.accepted_content_types.includes(contentType), `${source.id} returned an undeclared media type`);
    }
    if (source.adapter === "GOVUK_SEARCH_V1") {
      assert.ok(["application/json", "application/ld+json"].includes(contentType), `${source.id} returned a non-JSON media type`);
    }
    if (source.adapter === "OFFICIAL_RSS_V1") {
      assert.ok(["application/rss+xml", "application/xml", "application/atom+xml", "text/xml"].includes(contentType),
        `${source.id} returned a non-feed media type`);
    }
    if (source.adapter === "PINNED_OWNER_EXPORT_V1" && !fixtureMode) {
      assert.equal(sha256(bytes), contract.federation.data_centres.export_sha256, "pinned owner export digest changed");
    }
    let values;
    if (source.adapter === "PINNED_OWNER_EXPORT_V1") values = ownerExportItems(source, bytes.toString("utf8"), contract, fixtureMode);
    else if (source.adapter === "GOVUK_SEARCH_V1") values = govukItems(source, bytes.toString("utf8"), collectionAnchorAt, contract.limits);
    else if (source.adapter === "OFFICIAL_RSS_V1") values = rssItems(source, bytes.toString("utf8"), collectionAnchorAt, contract.limits);
    else values = [{
      source_item_id: source.source_url,
      title: source.ventus_authored_label,
      canonical_url: source.source_url,
      source_published_at: null,
      observed_at: collectionAnchorAt,
      summary: null,
      status: "OFFICIAL_ENDPOINT_AVAILABLE",
    }];
    const items = values.map((value) => itemRow(source, value, collectionAnchorAt, contract.limits));
    const topics = items.map((item) => topicRow(item, source, topicRanks,
      source.adapter === "PINNED_OWNER_EXPORT_V1" ? "PINNED_OWNER_TOPIC" : "SOURCE_DEFINITION_TOPIC"));
    return {
      source_status: {
        source_id: source.id,
        result: "OK",
        requested: true,
        response_bytes: bytes.length,
        response_sha256: sha256(bytes),
        content_type: contentType,
        retained_items: items.length,
        error_code: null,
      },
      items,
      topics,
    };
  } catch (error) {
    return {
      source_status: {
        source_id: source.id,
        result: "FAILED_SOFT",
        requested: true,
        response_bytes: 0,
        response_sha256: null,
        content_type: null,
        retained_items: 0,
        error_code: failureCode(error),
      },
      items: [],
      topics: [],
    };
  }
}

async function collectFrozenGeneric(contract, genericNewsPath, collectionAnchorAt, topicRanks) {
  const source = contract.sources.find(({ adapter }) => adapter === "FROZEN_GENERIC_NEWS_V1");
  const bytes = await readFile(genericNewsPath);
  assert.equal(sha256(bytes), contract.frozen_generic_news.sha256);
  const payload = JSON.parse(bytes);
  assert.equal(payload.rows.length, contract.frozen_generic_news.expected_rows);
  const fields = payload.fields;
  const records = payload.rows.map((row) => Object.fromEntries(fields.map((field, index) => [field, row[index]])));
  const selected = records.filter((record) => record.role === "DISCOVERY_ONLY" && /data\s*cent(?:re|er)/iu.test(record.headline));
  assert.equal(selected.length, contract.frozen_generic_news.expected_data_centre_discovery_rows);
  assert.ok(selected.every((record) => record.repd_ref === "" && record.gg_project_id === "" && record.eligible_for_news_signal === false));
  assert.ok(selected.some((record) => record.project && record.capacity_mw), "fixture did not expose the query-context contamination being stripped");
  const items = selected.map((record) => itemRow(source, {
    source_item_id: record.gg_article_id,
    title: record.headline,
    summary: null,
    canonical_url: record.url,
    source_published_at: record.published,
    observed_at: record.published,
    status: "DISCOVERY_ONLY_QUERY_CONTEXT_STRIPPED",
    evidence_class: "DISCOVERY_ONLY",
    attribution: `${record.source}; Google News link-through`,
    generic_article_id: record.gg_article_id,
  }, collectionAnchorAt, contract.limits));
  const topics = items.map((item) => topicRow(item, source, topicRanks, "FROZEN_HEADLINE_TOPIC_QUERY_IDENTITY_STRIPPED"));
  return {
    source_status: {
      source_id: source.id,
      result: "OK",
      requested: false,
      response_bytes: bytes.length,
      response_sha256: sha256(bytes),
      content_type: "application/json",
      retained_items: items.length,
      error_code: null,
    },
    items,
    topics,
  };
}

function collectStaticLinks(contract, collectionAnchorAt, topicRanks) {
  return contract.sources.filter(({ adapter }) => adapter === "STATIC_LINK_V1").map((source) => {
    const item = itemRow(source, {
      source_item_id: source.source_url,
      title: source.ventus_authored_label,
      summary: null,
      canonical_url: source.source_url,
      source_published_at: null,
      observed_at: collectionAnchorAt,
      status: "STATIC_LINK_REFERENCE",
    }, collectionAnchorAt, contract.limits);
    return {
      source_status: {
        source_id: source.id,
        result: "STATIC_LINK",
        requested: false,
        response_bytes: 0,
        response_sha256: null,
        content_type: null,
        retained_items: 1,
        error_code: null,
      },
      items: [item],
      topics: [topicRow(item, source, topicRanks, "STATIC_LINK_TOPIC")],
    };
  });
}

export async function collectSectorIntelligence({
  contract,
  genericNewsPath,
  fetchImpl = fetch,
  fixture = null,
  collectionAnchorAt,
  collectionAnchorBasis,
}) {
  validateContract(contract);
  const normalisedCollectionAnchorAt = iso(
    collectionAnchorAt || fixture?.collection_anchor_at,
    "collection_anchor_at",
  );
  const normalisedCollectionAnchorBasis = collectionAnchorBasis || fixture?.collection_anchor_basis;
  assert.equal(normalisedCollectionAnchorBasis, fixture
    ? "SYNTHETIC_FIXTURE_GENERATION_ANCHOR"
    : contract.time_provenance.live_collection_anchor_basis,
  "collection anchor basis does not match its execution mode");
  const topicRanks = new Map(contract.topics.map(({ code, display_rank }) => [code, display_rank]));
  if (fixture) {
    assert.equal(fixture.schema, FIXTURE_SCHEMA);
    assert.equal(fixture.generation, GENERATION);
    assert.equal(fixture.usage_context, USAGE_CONTEXT);
    assert.ok(Object.values(fixture.forbidden_retained_content).every((value) => value === false));
    fetchImpl = bindFixtureSources(contract, fixture);
  }
  const networkSources = contract.sources.filter(({ adapter }) => NETWORK_ADAPTERS.has(adapter));
  const results = await mapLimit(networkSources, contract.limits.maximum_concurrency,
    (source) => collectNetworkSource(source, contract, fetchImpl, normalisedCollectionAnchorAt, Boolean(fixture), topicRanks));
  results.push(...collectStaticLinks(contract, normalisedCollectionAnchorAt, topicRanks));
  results.push(await collectFrozenGeneric(contract, genericNewsPath, normalisedCollectionAnchorAt, topicRanks));
  const items = results.flatMap(({ items: values }) => values);
  const topics = results.flatMap(({ topics: values }) => values);
  const bindings = [];
  items.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));
  assert.ok(items.length <= contract.limits.maximum_total_items);
  assert.equal(items.length, new Set(items.map(({ intelligence_item_id }) => intelligence_item_id)).size);
  assert.equal(topics.length, new Set(topics.map((row) => `${row.intelligence_item_id}\u001f${row.topic_code}`)).size);
  assert.ok(topics.every(({ intelligence_item_id }) => items.some((item) => item.intelligence_item_id === intelligence_item_id)));
  assert.ok(items.every(({ eligible_for_news_signal }) => eligible_for_news_signal === false));
  assert.ok(topics.every(({ eligible_for_news_signal }) => eligible_for_news_signal === false));
  assert.deepEqual(bindings, []);
  const serialisedItems = JSON.stringify(items);
  for (const field of FORBIDDEN_ITEM_FIELDS) assert.equal(new RegExp(`\"${field}\"`, "u").test(serialisedItems), false);
  assert.equal(/DESCRIPTION MUST NOT BE RETAINED|QUERY CONTEXT MUST NOT SURVIVE/iu.test(serialisedItems), false);
  const genericItems = items.filter(({ generic_article_id }) => generic_article_id !== null);
  assert.equal(genericItems.length, contract.invariants.data_centre_generic_rows_sanitised);
  const ownerItems = items.filter(({ owner_repository }) => owner_repository !== null);
  if (!fixture) assert.equal(ownerItems.length, contract.invariants.owner_metric_rows_expected);
  const ledger = {
    schema: LEDGER_SCHEMA,
    generation: GENERATION,
    collection_anchor_at: normalisedCollectionAnchorAt,
    collection_anchor_basis: normalisedCollectionAnchorBasis,
    usage_context: USAGE_CONTEXT,
    usage_context_establishes_upstream_rights: false,
    datasets: {
      sector_items: { fields: ITEM_FIELDS, rows: items },
      sector_item_topics: { fields: TOPIC_FIELDS, rows: topics },
      sector_project_bindings: { fields: BINDING_FIELDS, rows: bindings },
    },
    source_statuses: results.map(({ source_status }) => source_status).sort((a, b) => a.source_id.localeCompare(b.source_id)),
    policy_evidence: {
      network_requests: networkSources.length,
      upstream_data_centre_requests: 0,
      pinned_data_centre_owner_export_requests: 1,
      companies_house_requests: 0,
      generic_news_rows_preserved: contract.invariants.generic_news_rows,
      generic_data_centre_rows_sanitised: genericItems.length,
      query_context_used_for_project_identity: false,
      stripped_project_identity_fields: [...FORBIDDEN_ITEM_FIELDS],
      retained_raw_html_bytes: 0,
      retained_article_body_bytes: 0,
      retained_search_snippet_characters: 0,
      owner_parquet_copied: false,
      sector_project_bindings: 0,
      all_items_eligible_for_news_signal: false,
    },
    deployment: "not-authorised",
  };
  return ledger;
}

function parseArguments(argv) {
  const output = {};
  for (let index = 0; index < argv.length; index += 2) {
    const key = argv[index];
    assert.ok(key?.startsWith("--") && argv[index + 1] !== undefined, `invalid argument near ${key}`);
    output[key.slice(2)] = argv[index + 1];
  }
  for (const required of ["contract", "generic-news", "ledger"]) assert.ok(output[required], `--${required} is required`);
  return output;
}

async function main() {
  const arguments_ = parseArguments(process.argv.slice(2));
  const contract = JSON.parse(await readFile(arguments_.contract));
  const fixture = arguments_.fixture ? JSON.parse(await readFile(arguments_.fixture)) : null;
  if (!fixture) {
    assert.ok(arguments_["collection-anchor-at"], "--collection-anchor-at is required for live collection");
    assert.ok(arguments_["collection-anchor-basis"], "--collection-anchor-basis is required for live collection");
  }
  const ledger = await collectSectorIntelligence({
    contract,
    genericNewsPath: arguments_["generic-news"],
    fixture,
    collectionAnchorAt: arguments_["collection-anchor-at"],
    collectionAnchorBasis: arguments_["collection-anchor-basis"],
  });
  const destination = path.resolve(arguments_.ledger);
  await mkdir(path.dirname(destination), { recursive: true });
  await writeFile(destination, canonicalJson(ledger));
  process.stdout.write(`${JSON.stringify({
    status: "PASS",
    generation: GENERATION,
    items: ledger.datasets.sector_items.rows.length,
    topics: ledger.datasets.sector_item_topics.rows.length,
    bindings: ledger.datasets.sector_project_bindings.rows.length,
    generic_data_centre_rows_sanitised: ledger.policy_evidence.generic_data_centre_rows_sanitised,
    deployment: "not-authorised",
  })}\n`);
}

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