In this section
- Pages Promotion Wrapper Readback render · pipelinenews / atman/pages-promotion-wrapper-readback.mjs lines 1–251
- Repair Pages Historical Source Attestation storage · pipelinenews / automation/202608301152-repair-pages-historical-source-attestation.py lines 1–110
- BBC RSS Pipeline Model energy-data · pipelinenews / cartridges/bbc-rss-pipeline-model.mjs lines 1–73
- BBC RSS Pipeline Model Test test · pipelinenews / cartridges/bbc-rss-pipeline-model.test.mjs lines 1–54
- Coverage Join Audit transform · pipelinenews / cartridges/coverage-join-audit.mjs lines 1–48
- Coverage Join Audit Test test · pipelinenews / cartridges/coverage-join-audit.test.mjs lines 1–28
- Provisional Identity transform · pipelinenews / cartridges/provisional-identity.mjs lines 1–70
- Provisional Identity Test test · pipelinenews / cartridges/provisional-identity.test.mjs lines 1–26
- Reported Project Test test · pipelinenews / cartridges/reported-project.test.mjs lines 1–23
Pages Promotion Wrapper Readback
A JavaScript module in the atman folder of PipelineNews that fetches atlas link, using SHA-256 from the GridAtlas repository.
renderpipelinenews / atman/pages-promotion-wrapper-readback.mjs · lines 1–251 of 251 · Entry point
- What it does
- It fetches atlas link. Defines value, sha256, fetchPublicBytes, throttle. Uses libraries node:fs/promises, node:crypto, playwright. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- 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: gridatlas data; JSON file atlas-link-manifest.json; JSON file current.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: PipelineNews Pages V2 Workflow (pipelinenews). Reached from 1 other entry point, including PipelineNews Pages Workflow (pipelinenews).
- What it achieves
- It fetches public bytes (`fetchPublicBytes`) and is built from the value step (`value`) and the sha256 step (`sha256`). Browser proof for any fail-closed Pages promotion wrapper.
- Why it matters
- Run by PipelineNews Pages V2 Workflow.
- Application
- pipelinenews · atman · JavaScript module
- Uses
- GridAtlas — Atlas Page (estate URL), node:fs/promises, node:crypto, playwright
- Used by
- run by PipelineNews Pages V2 Workflow (workflow run)
- Produces
- value, sha256, fetchPublicBytes, throttle
- Defines here
- value, sha256, fetchPublicBytes, throttle
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 atman/pages-promotion-wrapper-readback.mjs:1-251 · blob 4c332d6b6bd126a0eca341f67c5ca531efcd0c44 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
/** Browser proof for any fail-closed Pages promotion wrapper. */
import fs from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { chromium } from 'playwright';
const args = process.argv.slice(2);
const value = (flag) => {
const index = args.indexOf(flag);
if (index < 0 || index + 1 >= args.length) throw new Error(`${flag} is required`);
return args[index + 1];
};
const candidate = value('--candidate');
const output = value('--output');
const candidateBase = new URL(candidate);
const manifestUrl = new URL('atlas-link-manifest.json', candidateBase);
const manifestResponse = await fetch(manifestUrl);
if (!manifestResponse.ok) throw new Error(`wrapper manifest HTTP ${manifestResponse.status}`);
const manifest = await manifestResponse.json();
if (manifest.schema !== 'pipelinenews.atlas-current-link-manifest.v2') {
throw new Error(`unsupported wrapper manifest: ${manifest.schema}`);
}
const receiver = manifest.receiver;
if (receiver?.base_url !== 'https://ventusltd.github.io/gridatlas/atlas/') {
throw new Error('wrapper receiver is not the stable GridAtlas route');
}
const sha256 = (payload) => createHash('sha256').update(payload).digest('hex');
const fetchPublicBytes = async (url, label) => {
const response = await fetch(url, {
cache: 'no-store',
headers: { 'cache-control': 'no-cache' },
});
if (!response.ok) throw new Error(`${label} HTTP ${response.status}`);
return Buffer.from(await response.arrayBuffer());
};
const publicCurrentUrl = new URL('current.json', receiver.base_url);
publicCurrentUrl.searchParams.set('receiver_commit', receiver.commit);
const publicCurrentBytes = await fetchPublicBytes(publicCurrentUrl, 'Grid current pointer');
const publicCurrent = JSON.parse(publicCurrentBytes.toString('utf8'));
if (publicCurrent.schema !== 'gridatlas.current.v2'
|| publicCurrent.generation !== receiver.generation) {
throw new Error(`public Grid pointer is not receiver generation ${receiver.generation}`);
}
const publicCartridges = new Map(
(publicCurrent.cartridges || []).map((item) => [item.id, item]),
);
const publicReceiverFiles = {};
for (const [id, record] of [
['sld-sandbox', receiver.measurement_cartridge],
['substation-intelligence', receiver.engine_cartridge],
]) {
const current = publicCartridges.get(id);
const expectedCurrentPath = `./${record.path.replace(/^atlas\//u, '')}`;
if (current?.generation !== record.generation
|| current?.version !== record.version
|| current?.path !== expectedCurrentPath
|| current?.sha256 !== record.sha256) {
throw new Error(`public Grid ${id} pointer does not match the wrapper receiver`);
}
const publicUrl = new URL(record.path.replace(/^atlas\//u, ''), receiver.base_url);
publicUrl.searchParams.set('receiver_commit', receiver.commit);
const payload = await fetchPublicBytes(publicUrl, `Grid ${id} cartridge`);
const digest = sha256(payload);
if (payload.length !== record.bytes || digest !== record.sha256) {
throw new Error(`public Grid ${id} bytes do not match ${receiver.commit}`);
}
publicReceiverFiles[id] = {
url: publicUrl.href,
bytes: payload.length,
sha256: digest,
generation: current.generation,
version: current.version,
};
}
const repdRef = '155';
const networkProfile = {
offline: false,
latency: 100,
downloadThroughput: (10 * 1024 * 1024) / 8,
uploadThroughput: (5 * 1024 * 1024) / 8,
connectionType: 'cellular4g',
};
const throttle = async (target) => {
const session = await target.context().newCDPSession(target);
await session.send('Network.enable');
await session.send('Network.emulateNetworkConditions', networkProfile);
};
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
viewport: { width: 393, height: 852 },
serviceWorkers: 'block',
reducedMotion: 'reduce',
});
const page = await context.newPage();
await throttle(page);
const pipelineErrors = [];
const pipelineFailures = [];
page.on('pageerror', (error) => pipelineErrors.push(String(error?.stack || error?.message || error)));
page.on('console', (message) => {
if (message.type() === 'error') pipelineErrors.push(message.text());
});
page.on('requestfailed', (request) => pipelineFailures.push({
url: request.url(), error: request.failure()?.errorText || 'unknown',
}));
const probe = new URL(candidateBase);
probe.searchParams.set('repd_ref', repdRef);
probe.searchParams.set('technology', 'Biomass (dedicated)');
await page.goto(probe.href, { waitUntil: 'domcontentloaded', timeout: 90000 });
await page.waitForFunction(() => document.body?.dataset?.fastReady === 'true', null,
{ timeout: 90000 });
await page.waitForFunction((ref) => [...document.querySelectorAll('a.action-link[href]')]
.some((anchor) => new URL(anchor.href).searchParams.get('repd_ref') === ref),
repdRef, { timeout: 90000 });
const pipeline = await page.evaluate((ref) => {
const matches = [...document.querySelectorAll('a.action-link[href]')]
.filter((candidate) => new URL(candidate.href).searchParams.get('repd_ref') === ref);
const anchor = matches[0];
const row = anchor?.closest('tr');
const rect = anchor?.getBoundingClientRect();
return {
url: location.href,
release_id: document.body.dataset.releaseId || null,
fast_generation: document.body.dataset.fastGeneration || null,
filtered_count: document.querySelector('#resultsMeta')?.dataset?.filteredCount || null,
row_text: row?.textContent?.replace(/\s+/gu, ' ').trim() || null,
atlas_href: anchor?.href || null,
matching_action_count: matches.length,
wider_technology: document.querySelector('#widerTechnology')?.value || null,
action_box: rect ? { width: rect.width, height: rect.height } : null,
horizontal_overflow: document.documentElement.scrollWidth - innerWidth,
};
}, repdRef);
if (!pipeline.atlas_href) throw new Error('Markinch MAP action is absent');
const atlasUrl = new URL(pipeline.atlas_href);
const expectedParameters = [
'repd_ref', 'project', 'technology', 'capacity_mw', 'latitude', 'longitude', 'zoom',
];
if (atlasUrl.origin + atlasUrl.pathname !== receiver.base_url) {
throw new Error(`Atlas receiver changed: ${atlasUrl.origin}${atlasUrl.pathname}`);
}
if ([...atlasUrl.searchParams.keys()].join(',') !== expectedParameters.join(',')) {
throw new Error(`MAP parameter contract changed: ${[...atlasUrl.searchParams.keys()]}`);
}
if (atlasUrl.searchParams.get('repd_ref') !== repdRef
|| atlasUrl.searchParams.get('technology') !== 'biomass'
|| atlasUrl.searchParams.get('project') !== 'Markinch Biomass CHP Plant'
|| Number(atlasUrl.searchParams.get('latitude')) !== 56.20118
|| Number(atlasUrl.searchParams.get('longitude')) !== -3.16226) {
throw new Error(`Markinch transport changed: ${atlasUrl.href}`);
}
if (pipeline.matching_action_count !== 1 || pipeline.wider_technology !== 'Biomass (dedicated)'
|| !pipeline.row_text?.includes('Markinch Biomass CHP Plant')) {
throw new Error('exact Pipeline identity did not render one Markinch MAP action');
}
if (pipeline.horizontal_overflow > 1) throw new Error(`Pipeline mobile overflow ${pipeline.horizontal_overflow}px`);
if (pipelineErrors.length || pipelineFailures.length) {
throw new Error(`Pipeline browser errors: ${JSON.stringify({ pipelineErrors, pipelineFailures })}`);
}
const atlas = await context.newPage();
await throttle(atlas);
const atlasErrors = [];
const atlasFailures = [];
atlas.on('pageerror', (error) => atlasErrors.push(String(error?.stack || error?.message || error)));
atlas.on('console', (message) => {
if (message.type() === 'error') atlasErrors.push(message.text());
});
atlas.on('requestfailed', (request) => atlasFailures.push({
url: request.url(), error: request.failure()?.errorText || 'unknown',
}));
await atlas.goto(atlasUrl.href, { waitUntil: 'domcontentloaded', timeout: 90000 });
await atlas.waitForSelector('#map canvas', { timeout: 90000 });
await atlas.waitForFunction((ref) => {
const state = window.__GRIDATLAS_NEON_LINKS__;
return state?.deep_linked === true
&& Number.isFinite(state.first_coordinate_answer_ms)
&& state.last_selection?.name === 'Markinch Biomass CHP Plant'
&& String(state.identity_verification?.repd_ref || '') === ref
&& ['VERIFIED', 'RECOMPUTED'].includes(state.identity_verification?.status);
}, repdRef, { timeout: 600000 });
const atlasState = await atlas.evaluate((ref) => {
const state = window.__GRIDATLAS_NEON_LINKS__;
const popup = document.querySelector('.maplibregl-popup-content');
return {
url: location.href,
deep_linked: state?.deep_linked,
first_coordinate_answer_ms: state?.first_coordinate_answer_ms,
first_coordinate_origin: state?.first_coordinate_origin,
origin_source: state?.origin_source,
identity_verification: state?.identity_verification || null,
arrival_reconciliation: state?.arrival_reconciliation || null,
last_selection: state?.last_selection || null,
links_drawn: state?.links_drawn,
status_message: state?.status_message,
popup_text: popup?.innerText?.replace(/\s+/gu, ' ').trim() || null,
ref_visible: document.body.innerText.includes(ref),
viewport: { width: innerWidth, height: innerHeight },
};
}, repdRef);
if (!atlasState.ref_visible || !atlasState.popup_text?.includes('Markinch Biomass CHP Plant')) {
throw new Error('Grid receiver did not keep the Markinch identity visible');
}
if (!Number.isFinite(atlasState.links_drawn) || atlasState.links_drawn <= 0
|| atlasState.last_selection?.count !== atlasState.links_drawn
|| !/\bkm straight\b/iu.test(atlasState.popup_text || '')) {
throw new Error('Grid receiver did not publish Markinch measured links');
}
const toleratedFailures = atlasFailures.filter((failure) =>
/tile|basemap|sprite|glyph/iu.test(failure.url));
const unexpectedFailures = atlasFailures.filter((failure) => !toleratedFailures.includes(failure));
const toleratedErrors = atlasErrors.filter((message) =>
/Failed to fetch|MapLibre|tile|sprite|glyph/iu.test(message));
const unexpectedErrors = atlasErrors.filter((message) => !toleratedErrors.includes(message));
if (unexpectedErrors.length || unexpectedFailures.length) {
throw new Error(`Grid browser errors: ${JSON.stringify({ unexpectedErrors, unexpectedFailures })}`);
}
const proof = {
schema: 'pipelinenews.pages-promotion-wrapper-readback.v1',
classification: 'VERIFIED_PIPELINENEWS_MAP_TO_GRID_PRODUCTION_RECEIVER',
wrapper_release_id: manifest.pipeline_release_id,
source_release_id: manifest.source_pipeline_release_id,
receiver_commit: receiver.commit,
receiver_version: receiver.version,
public_receiver: {
current_url: publicCurrentUrl.href,
current_sha256: sha256(publicCurrentBytes),
generation: publicCurrent.generation,
cartridges: publicReceiverFiles,
},
candidate_url: candidateBase.href,
pipeline_probe_url: probe.href,
atlas_url: atlasUrl.href,
viewport: { width: 393, height: 852 },
network_profile: networkProfile,
golden_repd_ref: repdRef,
pipeline,
atlas: atlasState,
tolerated_receiver_errors: toleratedErrors,
tolerated_receiver_failures: toleratedFailures,
unexpected_receiver_errors: unexpectedErrors,
unexpected_receiver_failures: unexpectedFailures,
route_interceptions: 0,
synthetic_receiver: false,
privacy: 'NO_PERSONAL_DATA',
};
await fs.mkdir(output.split('/').slice(0, -1).join('/') || '.', { recursive: true });
await fs.writeFile(output, JSON.stringify(proof, null, 2) + '\n', 'utf8');
console.log(JSON.stringify(proof));
await browser.close();Repair Pages Historical Source Attestation
A Python command-line tool in the automation folder of PipelineNews that verifies record commit (`verify_record_at_commit`), using SHA-256. It replaces once (`replace_once`).
storagepipelinenews / automation/202608301152-repair-pages-historical-source-attestation.py · lines 1–110 of 110 · version 2026-08-30 11:52 · Entry point · pattern verify_record_at_commit (shared by 2 files)
- What it does
- It loads data. Defines replace_once, main, verify_record_at_commit. Uses libraries pathlib. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Downstream impact
- Used directly by 1 file: Repair Pages Historical Source Attestation V2 (pipelinenews).
- What it achieves
- Patch the Pages gate to attest historical compiler inputs for timestamp releases.
- Why it matters
- Run by Repair Pages Historical Source Attestation V2.
- Application
- pipelinenews · automation · Python CLI
- Uses
- Build Pages (script call), pathlib
- Used by
- run by Repair Pages Historical Source Attestation V2 (workflow run)
- Produces
- replace_once, main, verify_record_at_commit
- Defines here
- replace_once, main, verify_record_at_commit
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 automation/202608301152-repair-pages-historical-source-attestation.py:1-110 · blob e7d5f61338c2542dd218b392d2b4aa36d72dd90d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Patch the Pages gate to attest historical compiler inputs for timestamp releases."""
from pathlib import Path
TARGET = Path("atman/202608262014-build-pages.py")
def replace_once(text: str, before: str, after: str, label: str) -> str:
count = text.count(before)
if count != 1:
raise RuntimeError(f"{label}: expected one anchor, found {count}")
return text.replace(before, after)
def main() -> None:
text = TARGET.read_text(encoding="utf-8")
verify_anchor = '''def verify_record(root: Path, record: dict, label: str) -> Path:
relative = record.get("path")
require(isinstance(relative, str) and relative, f"{label} has no path")
target = repository_path(root, relative)
require(target.is_file(), f"missing {label}: {relative}")
require(target.stat().st_size == record.get("bytes"), f"byte mismatch for {relative}")
require(sha256(target) == record.get("sha256"), f"SHA-256 mismatch for {relative}")
return target
'''
helper = verify_anchor + '''
def verify_record_at_commit(root: Path, commit: str, record: dict, label: str) -> None:
relative = record.get("path")
require(isinstance(relative, str) and relative, f"{label} has no path")
completed = subprocess.run(
["git", "show", f"{commit}:{relative}"],
cwd=root,
check=True,
capture_output=True,
)
payload = completed.stdout
expected_bytes = record.get("bytes")
if expected_bytes is not None:
require(len(payload) == expected_bytes, f"historical byte mismatch for {relative}")
require(
hashlib.sha256(payload).hexdigest() == record.get("sha256"),
f"historical SHA-256 mismatch for {relative}",
)
'''
text = replace_once(text, verify_anchor, helper, "verify_record")
text = replace_once(
text,
"def validate_release(root: Path, requested: str) -> dict:\n",
"def validate_release(root: Path, requested: str, *, replay_sources: bool = True) -> dict:\n",
"validate_release signature",
)
old_validation = ''' seen: set[str] = set()
for record in manifest["inputs"]:
require(record["path"] not in seen, f"duplicate manifest path: {record['path']}")
seen.add(record["path"])
verify_record(root, record, "input")
for record in manifest["outputs"]:
require(record["path"] not in seen, f"duplicate manifest path: {record['path']}")
seen.add(record["path"])
verify_record(root, record, "output")
require(manifest_path.is_file(), "release manifest disappeared")
compiler_result = run_compiler(root, manifest, generation)
'''
new_validation = ''' manifest_commit = git_text(root, "log", "-1", "--format=%H", "--", manifest_path.relative_to(root).as_posix())
require(bool(COMMIT_RE.fullmatch(manifest_commit)), "compiled release manifest is not committed")
seen: set[str] = set()
for record in manifest["inputs"]:
require(record["path"] not in seen, f"duplicate manifest path: {record['path']}")
seen.add(record["path"])
if replay_sources or record["path"].startswith("data/"):
verify_record(root, record, "input")
else:
verify_record_at_commit(root, manifest_commit, record, "historical input")
for record in manifest["outputs"]:
require(record["path"] not in seen, f"duplicate manifest path: {record['path']}")
seen.add(record["path"])
verify_record(root, record, "output")
require(manifest_path.is_file(), "release manifest disappeared")
if replay_sources:
compiler_result = run_compiler(root, manifest, generation)
else:
verify_record_at_commit(root, manifest_commit, manifest["compiler"], "historical compiler")
compiler_result = {
"generation": f"{generation}-index",
"status": "HISTORICAL_SOURCE_ATTESTED",
"manifest_commit": manifest_commit,
}
'''
text = replace_once(text, old_validation, new_validation, "compiled validation block")
text = replace_once(
text,
" release = validate_release(root, args.generation)\n",
" release = validate_release(root, args.generation, replay_sources=not bool(args.timestamp_folder_release))\n",
"main validation call",
)
TARGET.write_text(text, encoding="utf-8", newline="\n")
if __name__ == "__main__":
main()BBC RSS Pipeline Model
A JavaScript module in the cartridges folder of PipelineNews that works with the Renewable Energy Planning Database (REPD) register. It builds rss view (`buildRssView`) and refreshes rss (`refreshRss`).
energy-datapipelinenews / cartridges/bbc-rss-pipeline-model.mjs · lines 1–73 of 73 · pattern projectObservation (shared by 3 files)
- What it does
- It calculates the REPD register. Defines articleIdentity, projectObservation, buildRssView, refreshRss.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file bbc-rss.json.
- Downstream impact
- Used directly by 3 files: BBC RSS Pipeline Panel (pipelinenews); BBC RSS Pipeline Model Test (pipelinenews); Build BBC RSS Package (pipelinenews). Reached from 1 other entry point, including PipelineNews Coverage Contract Workflow (pipelinenews).
- What it achieves
- Defines `articleIdentity`, `projectObservation`, `buildRssView` and 1 more.
- Why it matters
- Imported by BBC RSS Pipeline Panel. Run by Build BBC RSS Package. Checked by BBC RSS Pipeline Model Test.
- Application
- pipelinenews · cartridges · JavaScript module
- Uses
- Reported Project (import)
- Used by
- imported by BBC RSS Pipeline Panel (import), imported by BBC RSS Pipeline Model Test (import), run by Build BBC RSS Package (script call)
- Produces
- LIVE_RSS_URL, STALE_AFTER_MS, articleIdentity, projectObservation, buildRssView, refreshRss
- Defines here
- articleIdentity, projectObservation, buildRssView, refreshRss
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 cartridges/bbc-rss-pipeline-model.mjs:1-73 · blob 63a257b51e9bf26edcf8d9eaa02a611895ecf0f1 · 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
import {validateReportedProject} from './reported-project.mjs';
export const LIVE_RSS_URL = 'https://raw.githubusercontent.com/Ventusltd/pipelinenews/main/discovery/products/bbc-rss.json';
export const STALE_AFTER_MS = 3 * 60 * 60 * 1000;
export function articleIdentity(value) {
try {
const url = new URL(value);
const match = url.pathname.match(/^\/news\/articles\/([a-z0-9]+)\/?$/i);
if (url.protocol !== 'https:' || !['www.bbc.co.uk','www.bbc.com'].includes(url.hostname) || !match) return null;
return {id:'bbc:'+match[1].toLowerCase(), url:`https://www.bbc.co.uk/news/articles/${match[1].toLowerCase()}`};
} catch { return null; }
}
// The collector's asserted REPD fields are deliberately not a binding authority.
export function projectObservation(item, projects = [], evidence = [], official = []) {
const identity = articleIdentity(item.url);
const candidates = projects.filter(project=>articleIdentity(project.article_url)?.id === identity?.id);
const project = candidates.length === 1 ? candidates[0] : null;
const reported = evidence.find(report=>articleIdentity(report.article_url)?.id===identity?.id && report.primary_project===project?.name);
const validated = reported ? validateReportedProject(reported) : null;
const ref = String(project?.official_repd_ref || '');
const bound = project?.identity_status==='REPD_BOUND' && /^\d+$/.test(ref) && official.some(row=>String(row.repd_ref)===ref);
return {
name:project?.name || null,
status:bound?'OFFICIAL_IDENTITY_VERIFIED':project?'REPD_PENDING':'UNMATCHED_REQUIRES_REVIEW',
repd_ref:bound?ref:null,
temporary_ref:!bound&&/^[0-9]+-REPD-TBC$/.test(project?.repd_ref || '')?project.repd_ref:null,
gg_project_id:bound?`GG2050-REPD-${ref}`:project?.gg_project_id || null,
claims:validated?.claims || [],
related_projects:validated?.related_projects || [],
unknowns:validated?.unknowns || [],
evidence_basis:validated?.evidence_basis || null,
// A verified project identity never converts a report into official capacity or headroom.
capacity_basis:'reported only; excluded from official REPD totals',
eligible_for_project_signal:false,
};
}
export function buildRssView(payload, {now=Date.now(), projects=[], evidence=[], official=[], refreshError=null}={}) {
if(payload?.schema!=='pipelinenews.bbc-rss.v1' || !Array.isArray(payload.items) || !Array.isArray(payload.feeds)) throw Error('Unsupported BBC RSS product');
if(payload.items.length>500 || payload.feeds.length>100) throw Error('BBC RSS product exceeds bounded collection contract');
const checked=Date.parse(payload.checked_at), successful=Date.parse(payload.last_success_at);
const clockValid=Number.isFinite(now)&&Number.isFinite(checked)&&checked<=now+60000&&Number.isFinite(successful)&&successful<=now+60000;
const age=clockValid?Math.max(0,now-successful):null;
const good=payload.feeds.filter(feed=>feed.status==='ok').length;
const total=payload.feeds.length;
const collection=good===0?'FAILED':good<total||payload.status!=='ok'?'PARTIAL':'OK';
const freshness=!clockValid?'UNKNOWN':age>STALE_AFTER_MS?'STALE':'FRESH';
const unique=new Map();
let rejected=0;
for(const item of payload.items) {
const identity=articleIdentity(item.url);
if(!identity || typeof item.headline!=='string' || !item.headline.trim() || (item.id && item.id!==identity.id)) {rejected++;continue;}
if(unique.has(identity.id)) continue;
unique.set(identity.id,{...identity,headline:item.headline.trim(),published_at:item.source_published_at || null,observation:projectObservation(item,projects,evidence,official)});
}
return {items:[...unique.values()],rejected,collection,freshness,age_ms:age,checked_at:payload.checked_at || null,last_success_at:payload.last_success_at || null,feed_success:good,feed_total:total,feeds:payload.feeds.map(feed=>({url:String(feed.url || ''),status:String(feed.status || 'unknown')})),refresh_error:refreshError?String(refreshError):null};
}
// On any fetch/schema failure retain the previous product and visibly mark refresh failure.
export async function refreshRss(previous, {fetcher=fetch, ...options}={}) {
try {
const response=await fetcher(LIVE_RSS_URL,{cache:'no-store',credentials:'omit',redirect:'error',signal:AbortSignal.timeout(15000)});
if(!response.ok) throw Error('Source HTTP '+response.status);
const text=await response.text();
if(text.length>2*1024*1024) throw Error('Source exceeds 2 MiB limit');
const payload=JSON.parse(text);
return {payload,view:buildRssView(payload,options),live:true};
} catch(error) {
return {payload:previous,view:buildRssView(previous,{...options,refreshError:error.message}),live:false};
}
}BBC RSS Pipeline Model Test
A test in the cartridges folder of PipelineNews that checks BBC RSS Pipeline Model.
testpipelinenews / cartridges/bbc-rss-pipeline-model.test.mjs · lines 1–54 of 54 · Entry point · pattern payload (shared by 6 files)
- What it does
- It tests solar and the REPD register. Defines payload. Uses libraries node:test, node:assert/strict, node:fs. 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, the REPD register.
- Inputs & outputs
- In: JSON file project-register.json; JSON file 202609060208-cearn-project-evidence.json.
- Downstream impact
- Used directly by 1 file: PipelineNews Coverage Contract Workflow (pipelinenews).
- What it achieves
- Defines `payload`. It reads `../data/provisional/project-register.json`.
- Why it matters
- Run by PipelineNews Coverage Contract Workflow.
- Application
- pipelinenews · cartridges · test
- Uses
- BBC RSS Pipeline Model (import), node:test, node:assert/strict, node:fs
- Used by
- run by PipelineNews Coverage Contract Workflow (workflow run)
- Produces
- payload
- Defines here
- payload
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 cartridges/bbc-rss-pipeline-model.test.mjs:1-54 · blob e60e794bd2777fcfb309a0ccc5cef2041f26fb82 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {buildRssView,refreshRss,articleIdentity,LIVE_RSS_URL} from './bbc-rss-pipeline-model.mjs';
const now=Date.parse('2026-09-06T03:00:00Z');
const payload=()=>({schema:'pipelinenews.bbc-rss.v1',status:'ok',checked_at:'2026-09-06T02:00:00Z',last_success_at:'2026-09-06T02:00:00Z',feeds:[{url:'https://feeds.bbci.co.uk/news/england/oxford/rss.xml',status:'ok'}],items:[{id:'bbc:c4gmkezn4nlo',url:'https://www.bbc.co.uk/news/articles/c4gmkezn4nlo',headline:'Solar proposal',repd_ref:'12345',eligible_for_project_signal:true}]});
const projects=JSON.parse(readFileSync(new URL('../data/provisional/project-register.json',import.meta.url))).projects;
const evidence=[JSON.parse(readFileSync(new URL('../discovery/inbox/202609060208-cearn-project-evidence.json',import.meta.url)))];
test('freshness uses last successful collection, not a recent failed attempt',()=>{
const source=payload();assert.equal(buildRssView(source,{now}).freshness,'FRESH');
source.checked_at='2026-09-06T03:00:00Z';source.last_success_at='2026-09-05T23:00:00Z';source.status='failed';source.feeds[0].status='failed';
const failed=buildRssView(source,{now});assert.equal(failed.freshness,'STALE');assert.equal(failed.collection,'FAILED');assert.equal(failed.items.length,1);
source.last_success_at='bad date';assert.equal(buildRssView(source,{now}).freshness,'UNKNOWN');
source.last_success_at='2026-09-07T02:00:00Z';assert.equal(buildRssView(source,{now}).freshness,'UNKNOWN');
});
test('partial feed failure is explicit and does not erase useful headlines',()=>{
const source=payload();source.feeds.push({url:'another feed',status:'failed'});source.status='partial';
const view=buildRssView(source,{now});assert.equal(view.collection,'PARTIAL');assert.equal(view.feed_success,1);assert.equal(view.feed_total,2);assert.equal(view.items.length,1);
});
test('deduplicate BBC host and campaign aliases; reject spoofed identities and publisher URLs',()=>{
const source=payload();source.items.push({...source.items[0],url:'https://www.bbc.com/news/articles/c4gmkezn4nlo?utm_source=feed'}, {...source.items[0],id:'bbc:other'}, {...source.items[0],url:'https://www.bbc.co.uk.evil.test/news/articles/c4gmkezn4nlo'});
const view=buildRssView(source,{now});assert.equal(view.items.length,1);assert.equal(view.rejected,2);
assert.equal(articleIdentity('javascript:alert(1)'),null);
assert.equal(view.items[0].observation.repd_ref,null);assert.equal(view.items[0].observation.eligible_for_project_signal,false);
});
test('Cearn remains pending and Botley West facts cannot become Cearn capacity or cost',()=>{
const original=JSON.stringify(projects);
const item=buildRssView(payload(),{now,projects,evidence}).items[0];
assert.equal(item.observation.name,'Cearn Solar Farm');assert.equal(item.observation.temporary_ref,'9999-REPD-TBC');assert.equal(item.observation.repd_ref,null);
assert.equal(item.observation.claims.find(claim=>claim.metric==='solar_capacity').value,500);
assert.equal(item.observation.claims.some(claim=>claim.metric==='project_cost'),false);
assert.equal(item.observation.related_projects[0].claims.find(claim=>claim.metric==='solar_capacity').value,840);
assert.equal(JSON.stringify(projects),original);
const malformed=structuredClone(evidence);malformed[0].claims[0].subject='Botley West';
assert.throws(()=>buildRssView(payload(),{now,projects,evidence:malformed}),/Cross-project/);
});
test('official identity requires reconciliation and active official source; reported numbers stay reported',()=>{
const bound=structuredClone(projects);bound[0].identity_status='REPD_BOUND';bound[0].official_repd_ref='23456';bound[0].repd_ref='23456';
assert.equal(buildRssView(payload(),{now,projects:bound,evidence}).items[0].observation.repd_ref,null);
const item=buildRssView(payload(),{now,projects:bound,evidence,official:[{repd_ref:'23456'}]}).items[0];
assert.equal(item.observation.repd_ref,'23456');assert.equal(item.observation.temporary_ref,null);assert.equal(item.observation.status,'OFFICIAL_IDENTITY_VERIFIED');
assert.equal(item.observation.capacity_basis,'reported only; excluded from official REPD totals');assert.equal(item.observation.eligible_for_project_signal,false);
});
test('network and schema failures retain previous observations; only collected JSON is fetched',async()=>{
const source=payload();let requested;
const failed=await refreshRss(source,{now,fetcher:async(url)=>{requested=url;throw Error('offline');}});
assert.equal(requested,LIVE_RSS_URL);assert.equal(failed.payload,source);assert.equal(failed.live,false);assert.match(failed.view.refresh_error,/offline/);assert.equal(failed.view.items.length,1);
const invalid=await refreshRss(source,{now,fetcher:async()=>({ok:true,text:async()=>'{"schema":"wrong"}'})});
assert.equal(invalid.payload,source);assert.match(invalid.view.refresh_error,/Unsupported/);
const next=payload();next.checked_at='2026-09-06T02:55:00Z';
const refreshed=await refreshRss(source,{now,fetcher:async()=>({ok:true,text:async()=>JSON.stringify(next)})});
assert.equal(refreshed.live,true);assert.equal(refreshed.view.checked_at,next.checked_at);
});Coverage Join Audit
A JavaScript module in the cartridges folder of PipelineNews that works with substations and the Renewable Energy Planning Database (REPD) register.
transformpipelinenews / cartridges/coverage-join-audit.mjs · lines 1–48 of 48
- What it does
- It calculates substations and the REPD register. Defines key, identities, auditCoverage, difference.
- 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: substations, the REPD register.
- Downstream impact
- Used directly by 2 files: Coverage Join Audit Test (pipelinenews); Build Coverage Candidate (pipelinenews). Reached from 1 other entry point, including PipelineNews Coverage Contract Workflow (pipelinenews).
- What it achieves
- It audits coverage (`auditCoverage`) and is built from the key step (`key`) and the identities step (`identities`). PIPELINE-01: identity coverage only. Presence does not establish network capacity.
- Why it matters
- Run by Build Coverage Candidate. Checked by Coverage Join Audit Test.
- Application
- pipelinenews · cartridges · JavaScript module
- Uses
- none found
- Used by
- imported by Coverage Join Audit Test (import), run by Build Coverage Candidate (script call)
- Produces
- auditCoverage
- Defines here
- key, identities, auditCoverage, difference
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 cartridges/coverage-join-audit.mjs:1-48 · blob 54465b6e719a3d59bc2bc0acfb5fdea455e58377 · 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
// PIPELINE-01: identity coverage only. Presence does not establish network capacity.
function key(value) {
if (!['string', 'number'].includes(typeof value) || !/^\d+$/.test(String(value))) {
throw new TypeError('REPD identity must be a non-empty digit string or integer');
}
return String(value);
}
function identities(rows, label) {
const seen = new Set();
for (const value of rows) {
const id = key(value);
if (seen.has(id)) throw new Error(`${label}: duplicate REPD ${id}`);
seen.add(id);
}
return seen;
}
export function auditCoverage(proximity, grid, substation) {
if (!Array.isArray(proximity?.rows)) throw new TypeError('proximity.rows must be an array');
for (const [label, value] of [['grid', grid?.grid], ['substation', substation?.substation]]) {
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`${label} index missing`);
}
const invalidProximity = [];
const validRows = proximity.rows.filter((row, index) => {
try { key(row.ref); return true; }
catch { invalidProximity.push({index, ref: row.ref ?? null, name: row.name ?? '', reason:'missing-or-invalid-repd-identity'}); return false; }
});
const p = identities(validRows.map(row => row.ref), 'proximity');
const g = identities(Object.keys(grid.grid), 'grid');
const s = identities(Object.keys(substation.substation), 'substation');
const difference = (a, b) => [...a].filter(id => !b.has(id)).sort();
const missingGrid = difference(p, g), missingSubstation = difference(p, s);
const extraGrid = difference(g, p), extraSubstation = difference(s, p);
return {
schema: 'pipelinenews.coverage-join-audit.v1',
counts: { proximity: proximity.rows.length, validProximityIdentities: p.size, grid: g.size, substation: s.size },
invalidProximity,
missingGrid, missingSubstation, extraGrid, extraSubstation,
equalKeySets: ![missingGrid, missingSubstation, extraGrid, extraSubstation, invalidProximity].some(a => a.length),
byTechnology: Object.fromEntries([...new Set(proximity.rows.map(r => r.tech))].sort().map(tech => {
const rows = proximity.rows.filter(r => r.tech === tech);
return [tech, { proximity: rows.length, grid: rows.filter(r => g.has(String(r.ref))).length,
substation: rows.filter(r => s.has(String(r.ref))).length }];
})),
caveat: 'Identity coverage only. Missing records are unavailable, not zero distance or absent infrastructure. Mapped proximity does not establish headroom.'
};
}Coverage Join Audit Test
A test in the cartridges folder of PipelineNews that checks Coverage Join Audit.
testpipelinenews / cartridges/coverage-join-audit.test.mjs · lines 1–28 of 28 · Entry point
- What it does
- It tests substations. Defines load. Uses libraries node:test, node:assert/strict, node:fs. 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: substations, 33kV.
- Inputs & outputs
- In: JSON file 202608311610-grid-proximity.json; JSON file 202608311800-grid-distance.json; JSON file 202608311858-substation-33kv.json. Voltage levels named: 33kV.
- Downstream impact
- Used directly by 1 file: PipelineNews Coverage Contract Workflow (pipelinenews).
- What it achieves
- Defines `load`.
- Why it matters
- Run by PipelineNews Coverage Contract Workflow.
- Application
- pipelinenews · cartridges · test
- Uses
- Coverage Join Audit (import), node:test, node:assert/strict, node:fs
- Used by
- run by PipelineNews Coverage Contract Workflow (workflow run)
- Produces
- load
- Defines here
- load
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 cartridges/coverage-join-audit.test.mjs:1-28 · blob 848b326811d83e89a4bd4792e55ee159a6ac0ac6 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { auditCoverage } from './coverage-join-audit.mjs';
test('equal counts with different identities cannot claim parity', () => {
const result = auditCoverage({rows:[{ref:'1',tech:'solar'}]}, {grid:{2:{k:0}}}, {substation:{1:null}});
assert.equal(result.equalKeySets, false);
assert.deepEqual(result.missingGrid, ['1']);
assert.deepEqual(result.extraGrid, ['2']);
assert.equal(result.counts.substation, 1); // coverage is presence, not usable geometry
});
test('duplicate and invalid identities fail rather than inflate coverage', () => {
assert.throws(() => auditCoverage({rows:[{ref:'1'},{ref:1}]}, {grid:{}}, {substation:{}}), /duplicate/);
assert.equal(auditCoverage({rows:[{ref:null}]}, {grid:{}}, {substation:{}}).invalidProximity.length, 1);
assert.throws(() => auditCoverage({rows:[]}, {grid:[]}, {substation:{}}), /index/);
});
test('pinned 202609050309 release exposes the exact missing project sets', () => {
const base = new URL('../releases/202609050309-pipelinenews/data/', import.meta.url);
const load = name => JSON.parse(readFileSync(new URL(name, base)));
const result = auditCoverage(load('202608311610-grid-proximity.json'), load('202608311800-grid-distance.json'), load('202608311858-substation-33kv.json'));
assert.deepEqual(result.counts, {proximity:4138, validProximityIdentities:4137, grid:3047, substation:3047});
assert.equal(result.missingGrid.length, 1090);
assert.deepEqual(result.missingGrid, result.missingSubstation);
assert.deepEqual(result.extraGrid, []);
assert.deepEqual(result.extraSubstation, []);
assert.equal(result.equalKeySets, false);
});Provisional Identity
A JavaScript module in the cartridges folder of PipelineNews that works with the Renewable Energy Planning Database (REPD) register, using SHA-256. It normalises operator (`normaliseOperator`) and resolves project (`resolveProject`).
transformpipelinenews / cartridges/provisional-identity.mjs · lines 1–70 of 70 · pattern reconcileProvisional (shared by 3 files)
- What it does
- It calculates the REPD register. Defines 8 functions or classes, including globalGridReference, normalise, allocateProvisional, normaliseOperator, reconcileProvisional.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
- Downstream impact
- Used directly by 4 files: Provisional Identity Test (pipelinenews); Build Provisional Package (pipelinenews); Reconcile Provisional (pipelinenews); Register Quarter Test (pipelinenews). Reached from 2 other entry points, including PipelineNews BBC RSS Discovery Workflow (pipelinenews); PipelineNews Coverage Contract Workflow (pipelinenews).
- What it achieves
- Uses the existing Pipeline Global Grid reference convention.
- Why it matters
- Imported by Reconcile Provisional. Run by Build Provisional Package. Checked by 2 tests, including Provisional Identity Test.
- Application
- pipelinenews · cartridges · JavaScript module
- Uses
- none found
- Used by
- imported by Provisional Identity Test (import), run by Build Provisional Package (script call), imported by Reconcile Provisional (import), run by Register Quarter Test (script call)
- Produces
- globalGridReference, allocateProvisional, reconcileProvisional, resolveProject
- Defines here
- globalGridReference, normalise, allocateProvisional, normaliseOperator, reconcileProvisional, operatorOf, place, resolveProject
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 cartridges/provisional-identity.mjs:1-70 · blob f41925809779824bd6b089a8e82141c4e12b23ae · 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
// Uses the existing Pipeline Global Grid reference convention.
export const globalGridReference = ref => `GG2050-REPD-${ref}`;
const normalise = value => String(value ?? '').normalize('NFKC').toLowerCase().replace(/[^a-z0-9]+/g,' ').trim();
export function allocateProvisional(records, project) {
const existing = records.find(row => row.source_key === project.source_key
|| (normalise(row.name)===normalise(project.name)
&& normalise(row.operator)===normalise(project.operator)
&& normalise(row.county)===normalise(project.county)
&& Number(row.capacity_mw)===Number(project.capacity_mw)));
if (existing) return structuredClone(existing);
let number=9999;
const used=new Set(records.flatMap(row=>[row.repd_ref,...(row.aliases ?? [])]));
while(used.has(`${number}-REPD-TBC`)) number++;
const repd_ref=`${number}-REPD-TBC`;
return {...structuredClone(project),repd_ref,official_repd_ref:null,
gg_project_id:globalGridReference(repd_ref),identity_status:'REPD_PENDING',
aliases:[],identity_history:[]};
}
// Operator names compare equal across the separator styles REPD itself switches
// between quarters ("A / B" in Q2 2026 became "A & B" in Q3 2026 on 404 spine refs).
const normaliseOperator = value => normalise(String(value ?? '').replace(/[\/&+]/g,' and ')).replace(/\band\b/g,' ').replace(/\s+/g,' ').trim();
// options.operatorAliases: Map(repd_ref -> [previous operator names]) from the register
// delta. The binding rule is unchanged: name/alias, operator (exact, as before), county
// and capacity must all agree and the match must be unique. A candidate that agrees
// only through last quarter's operator name or a separator respelling ("A / B" vs
// "A & B") is NOT bound: it goes to the review queue (NL-019 decision: name/operator
// matches are reviewed; only exact identity evidence promotes). Near misses likewise.
export function reconcileProvisional(records, official, source, options = {}) {
if (!source?.path || !/^[a-f0-9]{64}$/.test(source.sha256 ?? '')) throw Error('Quarterly source identity required');
const operatorAliases = options.operatorAliases ?? new Map();
const numeric=official.filter(row=>/^\d+$/.test(String(row.repd_ref)));
const occupied=new Set(records.filter(row=>row.official_repd_ref).map(row=>row.official_repd_ref));
return records.map(input=>{
const row=structuredClone(input);
if(row.official_repd_ref) return row;
// A common name or a nearby site is insufficient: require the declared
// name/alias, developer, county and reported capacity to agree uniquely.
const names=[row.name,...(row.name_aliases ?? [])].map(normalise);
const operatorOf=candidate=>[candidate.operator,...(operatorAliases.get(String(candidate.repd_ref)) ?? [])].map(normaliseOperator);
const named=numeric.filter(candidate=>names.includes(normalise(candidate.name)));
const place=candidate=>normalise(candidate.county)===normalise(row.county)
&& Number(candidate.capacity_mw)===Number(row.capacity_mw);
const matches=named.filter(candidate=>normalise(candidate.operator)===normalise(row.operator) && place(candidate));
const aliasOnly=named.filter(candidate=>!matches.includes(candidate) && place(candidate)
&& operatorOf(candidate).includes(normaliseOperator(row.operator)));
if(matches.length!==1 || occupied.has(String(matches[0].repd_ref))) {
row.reconciliation={status:matches.length?'AMBIGUOUS_REQUIRES_REVIEW':aliasOnly.length?'OPERATOR_ALIAS_REQUIRES_REVIEW':'NO_VERIFIED_MATCH',source,candidate_count:matches.length};
const review=named.filter(candidate=>!matches.includes(candidate)).slice(0,10).map(candidate=>({repd_ref:String(candidate.repd_ref),
operator_matches:operatorOf(candidate).includes(normaliseOperator(row.operator)),county_matches:normalise(candidate.county)===normalise(row.county),
capacity_matches:Number(candidate.capacity_mw)===Number(row.capacity_mw)}));
if(review.length) row.reconciliation.review_candidates=review;
return row;
}
const previous=row.repd_ref, next=String(matches[0].repd_ref);
occupied.add(next);
row.aliases=[...new Set([...row.aliases,previous,row.gg_project_id])];
row.repd_ref=next;row.official_repd_ref=next;row.gg_project_id=globalGridReference(next);
row.identity_status='REPD_BOUND';
row.identity_history.push({from:previous,to:next,source,reason:'unique name/developer/county/capacity match'});
row.reconciliation={status:'REPLACED_TEMPORARY_ID',source,candidate_count:1};
return row;
});
}
export function resolveProject(records, identity) {
return records.find(row=>[row.repd_ref,row.gg_project_id,...row.aliases].includes(identity)) ?? null;
}Provisional Identity Test
A test in the cartridges folder of PipelineNews that checks Provisional Identity, using SHA-256.
testpipelinenews / cartridges/provisional-identity.test.mjs · lines 1–26 of 26 · Entry point
- What it does
- It tests the REPD register and solar. Uses libraries node:test.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar.
- Inputs & outputs
- In: JSON file quarterly-repd.json.
- Downstream impact
- Used directly by 2 files: PipelineNews BBC RSS Discovery Workflow (pipelinenews); PipelineNews Coverage Contract Workflow (pipelinenews).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Run by PipelineNews BBC RSS Discovery Workflow and PipelineNews Coverage Contract Workflow.
- Application
- pipelinenews · cartridges · test
- Uses
- Provisional Identity (import), node:test
- Used by
- run by PipelineNews BBC RSS Discovery Workflow (workflow run), run by PipelineNews Coverage Contract Workflow (workflow run)
- 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 cartridges/provisional-identity.test.mjs:1-26 · blob 9308d38aa64e12338b0e6513d46c42ddf5401e94 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import {test} from 'node:test';import assert from 'node:assert/strict';
import {allocateProvisional,reconcileProvisional,resolveProject} from './provisional-identity.mjs';
const project={source_key:'bbc:c4gmkezn4nlo:cearn',name:'Cearn Solar Farm',operator:'Telis Energy UK',county:'Oxfordshire',capacity_mw:500};
const source={path:'quarterly-repd.json',sha256:'a'.repeat(64)};
test('one-time IDs are unique and retries preserve the allocated barcode',()=>{
const a=allocateProvisional([],project);assert.equal(a.repd_ref,'9999-REPD-TBC');
assert.equal(a.gg_project_id,'GG2050-REPD-9999-REPD-TBC');
assert.deepEqual(allocateProvisional([a],project),a);
assert.equal(allocateProvisional([a],{...project,source_key:'another-article-same-project'}).repd_ref,'9999-REPD-TBC');
assert.equal(allocateProvisional([a],{...project,source_key:'another',name:'Another Solar Farm'}).repd_ref,'10000-REPD-TBC');
});
test('quarterly match replaces the number on the same row and keeps old links',()=>{
const a=allocateProvisional([],project),official={...project,repd_ref:'25001'};
const rows=reconcileProvisional([a],[official],source);assert.equal(rows.length,1);
assert.equal(rows[0].repd_ref,'25001');assert.equal(rows[0].gg_project_id,'GG2050-REPD-25001');
assert.equal(resolveProject(rows,'9999-REPD-TBC'),rows[0]);
assert.equal(resolveProject(rows,a.gg_project_id),rows[0]);
assert.deepEqual(reconcileProvisional(rows,[official],source),rows);
});
test('ambiguous, wrong developer and reused official IDs cannot overwrite a provisional row',()=>{
const a=allocateProvisional([],project),official={...project,repd_ref:'25001'};
for(const candidates of [[official,{...official,repd_ref:'25002'}],[{...official,operator:'Another developer'}]])
assert.equal(reconcileProvisional([a],candidates,source)[0].repd_ref,a.repd_ref);
const bound={...a,repd_ref:'25001',official_repd_ref:'25001'};
assert.equal(reconcileProvisional([bound,a],[official],source)[1].repd_ref,a.repd_ref);
});Reported Project Test
A test in the cartridges folder of PipelineNews that checks Reported Project.
testpipelinenews / cartridges/reported-project.test.mjs · lines 1–23 of 23 · Entry point
- What it does
- It tests its inputs. Defines load. Uses libraries node:test, node:assert/strict, node:fs. 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.
- Inputs & outputs
- In: JSON file 202609060208-cearn-project-evidence.json.
- Downstream impact
- Used directly by 1 file: PipelineNews Coverage Contract Workflow (pipelinenews).
- What it achieves
- Defines `load`. It reads `../discovery/inbox/202609060208-cearn-project-evidence.json`.
- Why it matters
- Run by PipelineNews Coverage Contract Workflow.
- Application
- pipelinenews · cartridges · test
- Uses
- Reported Project (import), node:test, node:assert/strict, node:fs
- Used by
- run by PipelineNews Coverage Contract Workflow (workflow run)
- Produces
- load
- Defines here
- load
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 cartridges/reported-project.test.mjs:1-23 · blob d60c1f9364954305f72d916b00ba9edaedf60956 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {validateReportedProject} from './reported-project.mjs';
const load=()=>JSON.parse(readFileSync(new URL('../discovery/inbox/202609060208-cearn-project-evidence.json',import.meta.url)));
test('Cearn stays news-only; Botley West cost cannot leak into its claims',()=>{
const p=validateReportedProject(load());
assert.equal(p.claims.find(x=>x.metric==='solar_capacity').value,500);
assert.equal(p.claims.some(x=>x.metric==='project_cost'),false);
assert.equal(p.related_projects[0].claims.find(x=>x.metric==='solar_capacity').value,840);
assert.equal(p.repd_ref,null);assert.equal(p.geometry,null);assert.equal(p.eligible_for_project_signal,false);
});
test('mixed subjects and invented bindings fail closed',()=>{
const p=load();p.claims.push(p.related_projects[0].claims[1]);assert.throws(()=>validateReportedProject(p),/Cross-project/);
const q=load();q.eligible_for_project_signal=true;assert.throws(()=>validateReportedProject(q),/Unmatched/);
const r=load();r.claims.find(x=>x.metric==='solar_capacity').unit='MWh';assert.throws(()=>validateReportedProject(r),/MW/);
});
test('the declared pinned name search is reproduced against all project rows',()=>{
const p=load();const data=JSON.parse(readFileSync(new URL('../'+p.snapshot_check.path,import.meta.url)));
assert.equal(data.rows.length,p.snapshot_check.rows);
const name=data.fields.indexOf('name');assert.notEqual(name,-1);
assert.equal(data.rows.filter(row=>row[name].toLowerCase().includes('cearn')).length,0);
});