In this section
- Context render · globalgrid2050 / automation/news/context-ui/context.css lines 1–24
- Render render · globalgrid2050 / automation/news/context-ui/render.mjs lines 1–136
- Test Support test · globalgrid2050 / automation/news/context-ui/test-support.mjs lines 1–25
- Model transform · globalgrid2050 / automation/news/datacentre-ui/model.js lines 1–168
- News — Datacentre UI Style Sheet render · globalgrid2050 / automation/news/datacentre-ui/styles.css lines 1–37
- Browser Smoke test · globalgrid2050 / automation/news/datacentre-ui/tests/browser_smoke.py lines 1–132
- Harness test · globalgrid2050 / automation/news/datacentre-ui/tests/harness.html lines 1–5
- Model Test test · globalgrid2050 / automation/news/datacentre-ui/tests/model.test.cjs lines 1–99
- View Test test · globalgrid2050 / automation/news/datacentre-ui/tests/view.test.cjs lines 1–72
Context
A style sheet in the context ui folder of GlobalGrid2050.
renderglobalgrid2050 / automation/news/context-ui/context.css · lines 1–24 of 24 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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. README: "Load `context.css` and that renderer's `figures.css`."
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents); A4 Legal Model (globalgrid2050).
- What it achieves
- Scoped to the disclosure inside the existing News host.
- Why it matters
- Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/.
- Application
- globalgrid2050 · automation/news/context-ui · style sheet
- Uses
- none found
- Used by
- loaded by GlobalGrid2050 — UK Renewables Pipeline Page (stylesheet)
- 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/context-ui/context.css:1-24 · blob d94856c05e1a0e716a8f6ee4a95d2d5ccb596c28 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/* Scoped to the disclosure inside the existing News host. */
.transition-context { margin-block: .5rem; font: inherit; color: inherit; overflow-wrap: anywhere; }
.transition-context details { margin: .5rem 0 .5rem .75rem; }
.transition-context summary { cursor: pointer; }
.transition-context summary:focus-visible, .transition-context a:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
.transition-context p { margin-block: .35rem; }
.transition-context [data-context-figure] { padding-inline-start: .5rem; }
/* Override only this consumer's injected figures, leaving PR23 unchanged. */
.transition-context [data-filings-figures-root],
.transition-context [data-filings-figures-root] .ff-claim,
.transition-context [data-filings-figures-root] .ff-badge {
background: transparent; color: inherit; border: 0; border-radius: 0; font: inherit;
}
.transition-context [data-filings-figures-root] { line-height: inherit; margin-block: .5rem; }
.transition-context [data-filings-figures-root] .ff-amount,
.transition-context [data-filings-figures-root] .ff-metric,
.transition-context [data-filings-figures-root] .ff-summary { font: inherit; }
.transition-context [data-filings-figures-root] .ff-status,
.transition-context [data-filings-figures-root] .ff-field-label { color: inherit; }
.transition-context [data-filings-figures-root] .ff-summary::marker { color: inherit; }
.transition-context [data-filings-figures-root] .ff-claim { padding: .35rem 0; }
.transition-context [data-filings-figures-root] .ff-summary { padding: .35rem 0; }
.transition-context [data-filings-figures-root] .ff-badge { padding: 0; }
.transition-context a { color: var(--accent, inherit); }Render
A JavaScript module in the context ui folder of GlobalGrid2050 covering solar, using SHA-256.
renderglobalgrid2050 / automation/news/context-ui/render.mjs · lines 1–136 of 136 · pattern disclosure (shared by 3 files)
- What it does
- It draws solar. Defines 11 functions or classes, including known, label, evidenceValue, limitationText, evidence. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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. README: "Import `renderContext` from `render.mjs`, supply exact export bytes as a `Uint8Array`, and inject `buildViewModel` and `renderFigures` from ADDITIONAL's TestCode PR23 `sandbox/filings-ui` at the pin in `pins.json`."
- Downstream impact
- Used directly by 2 files: Adapter Test (globalgrid2050); Preview V928 (globalgrid2050). Reached from 6 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- It renders context (`renderContext`) and is built from the known step (`known`) and the label step (`label`). The README says: Import `renderContext` from `render.mjs`, supply exact export bytes as a `Uint8Array`, and inject `buildViewModel` and `renderFigures` from ADDITIONAL's TestCode PR23 `sandbox/filings-ui` at the pin in `pins.json`.
- Why it matters
- Imported by Preview V928. Checked by Adapter Test.
- Application
- globalgrid2050 · automation/news/context-ui · JavaScript module
- Uses
- Adapter (import)
- Used by
- imported by Adapter Test (import), imported by Preview V928 (dynamic import), mentioned in Standalone (comment link)
- Produces
- evidenceValue, limitationText, isContextHost, renderContext
- Defines here
- known, label, evidenceValue, limitationText, evidence, node, line, disclosure, source, isContextHost, renderContext
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/context-ui/render.mjs:1-136 · blob 40aeab14ce97f752526ea20500d91876cfba8b83 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import {readContext, sourceUrl} from './adapter.mjs';
const generations = new WeakMap();
const rootAttribute = 'data-transition-context-root';
const known = value => value === null || value === undefined ? 'Unknown' : String(value);
const label = value => known(value).replace(/_/g, ' ').toLowerCase().replace(/^./, c => c.toUpperCase());
// Complete values remain in readContext's result; presentation omits transport
// identifiers and renders source/history evidence without JSON or schema jargon.
const transport = new Set(['schema', 'input_schema', 'output_schema', 'input_sha256', 'output_policy']);
const states = new Set(['status', 'state', 'source_state', 'document_state', 'measurement_state',
'baseline_state', 'current_delivery', 'current_project_state', 'legal_compliance', 'canonical_binding', 'binding_basis']);
export function evidenceValue(key, value) {
if (key === 'source_byte_validation' && value === 'RECEIPTS_ONLY') return 'Based on supplied source records; original source files were not checked again.';
return states.has(key) && typeof value === 'string' ? label(value) : value;
}
const limitations = new Map([
['Dated source context; no current project delivery, legal compliance or source truth certified.', 'These are dated source reports. Current delivery, legal compliance and factual accuracy have not been independently confirmed.'],
['No identity crosswalk, site allocation, numerical aggregation, conversion or ranking.', 'Projects have not been matched to other records. Figures are not assigned to sites, added together, converted or ranked.'],
['Receipt hashes are supplied metadata; original source bytes were not reverified.', 'Source fingerprints were supplied with the records. Original source files were not checked again.'],
['Publication, review, retrieval and figure dates remain distinct; composition time is not source freshness.', 'Publication, review, retrieval and figure dates have different meanings. The assessment date does not mean the sources are current.'],
['Historical inventory is separate; no exhaustive treaty history or final COP31 outcome inferred.', 'The separate historical source list is not a complete treaty history. No final COP31 outcome is established here.'],
]);
export const limitationText = value => limitations.get(value) ?? value;
function evidence(document, parent, value) {
if (value.schema === 'globalgrid2050.filing-figure.v1') {
line(document, parent, 'Figure', 'See the figure and source details above');
return;
}
for (const [key, entry] of Object.entries(value)) {
if (transport.has(key)) continue;
const title = ({sha256: 'Source fingerprint', content_sha256: 'Source fingerprint',
native_metadata: 'Source background', source_byte_validation: 'Source check', numeric_claims: 'Figures', canonical_project_id: 'Confirmed project',
canonical_binding: 'Project association', binding_basis: 'Basis for project association',
figure_entity_scope: 'Figure coverage', entity_id: 'Organisation or project reference'})[key] ?? (Array.isArray(value) ? 'Entry' : label(key));
if (entry && typeof entry === 'object') {
const group = disclosure(document, parent, title);
if (!Object.keys(entry).length) line(document, group, 'Details', 'None supplied');
else evidence(document, group, entry);
} else line(document, parent, title, evidenceValue(key, entry));
}
}
function node(document, tag, text) {
const result = document.createElement(tag);
if (text !== undefined) result.textContent = text;
return result;
}
function line(document, parent, label, value) {
parent.append(node(document, 'p', `${label}: ${known(value)}`));
}
function disclosure(document, parent, title) {
const details = node(document, 'details'); details.append(node(document, 'summary', title)); parent.append(details); return details;
}
function source(document, parent, link) {
const details = disclosure(document, parent, `Source: ${link.publisher}`);
const a = node(document, 'a', link.receipt.title || 'Read source'); a.href = sourceUrl(link.url);
a.target = '_blank'; a.rel = 'noopener noreferrer'; details.append(a);
for (const [label, value] of [['Published', link.published_date], ['Reviewed', link.reviewed_at],
['Retrieved', link.retrieved_at], ['Source fingerprint', link.sha256],
['Section', link.locator.section], ['Page', link.locator.page], ['Locator', link.locator.text]]) line(document, details, label, value);
evidence(document, disclosure(document, details, 'Source details'), link.receipt);
}
/** Mount only inside an explicitly opted-in existing News or Pipeline tab. */
export const isContextHost = host => Boolean(host?.hasAttribute?.('data-news-context-host') ||
host?.hasAttribute?.('data-pipeline-context-host'));
export async function renderContext(host, bytes, {expectedSha256, figures}) {
if (!isContextHost(host)) throw new TypeError('An opted-in News or Pipeline host is required');
const generation = (generations.get(host) ?? 0) + 1; generations.set(host, generation);
const document = host.ownerDocument;
const root = node(document, 'details'); root.setAttribute(rootAttribute, ''); root.className = 'transition-context';
let report;
try {
if (typeof figures?.renderFigures !== 'function') throw new TypeError('Missing FIGURES renderer');
report = await readContext(bytes, {expectedSha256, buildViewModel: figures.buildViewModel});
root.contextReport = report; // exact native evidence retained for the host
root.dataset.state = 'available';
root.append(node(document, 'summary', 'Policy, grid and energy context'));
root.append(node(document, 'p', 'Provisional information from dated sources. Project associations, current delivery and legal compliance have not been confirmed.'));
line(document, root, 'Assessment date (sources may be older)', report.as_of);
for (const row of report.records) {
const item = disclosure(document, root, `${row.title} — ${label(row.source_state)}`); item.dataset.contextId = row.id;
line(document, item, 'Coverage', `${label(row.scope.kind)}; source describes: ${label(row.scope.native_scope)}`);
line(document, item, 'Project association', 'Not confirmed');
line(document, item, 'Source status', label(row.source_state)); line(document, item, 'Progress', label(row.evaluation_state));
line(document, item, 'Applicability', label(row.applicability_state));
const n = row.native_record;
if (row.family === 'policy') {
line(document, item, 'Policy scope', n.scope.description);
line(document, item, 'Applicability reason', n.applicability.reason);
line(document, item, 'Measurement', label(n.measurement_state));
line(document, item, 'Evidence limitation', n.metric.limitation);
line(document, item, 'Deadline', n.deadline.value); line(document, item, 'Deadline wording', n.deadline.wording);
line(document, item, 'Reporting obligation', n.reporting_obligation);
for (const condition of n.conditions) line(document, item, 'Condition', condition);
for (const reason of n.reasons) line(document, item, 'Reason', reason);
line(document, item, 'Legal compliance', label(n.legal_compliance));
} else {
line(document, item, 'Current delivery / project status', label(row.family === 'solar' ? n.current_delivery : n.current_project_state));
if (row.family === 'solar') line(document, item, 'Scope limitation', n.scope_note);
line(document, item, 'Research needed', n.research_action);
if (n.figures_omitted_reason !== null) line(document, item, 'Why figures are unavailable', n.figures_omitted_reason);
}
if (!row.numeric_claims.length) item.append(node(document, 'p', 'No supported figures available.'));
for (const figure of row.numeric_claims) {
const box = node(document, 'div'); box.dataset.contextFigure = '';
line(document, box, 'Figure purpose', label(figure.role));
line(document, box, 'Qualifier', figure.qualifier === 'upper_bound' ? 'Upper bound (up to)' : known(figure.qualifier));
figures.renderFigures(box, {entityId: row.scope.entity_id, state: 'available', claims: [figure.claim]});
item.append(box);
}
row.source_links.forEach(link => source(document, item, link));
evidence(document, disclosure(document, item, 'Supporting details and history'), n);
}
const backgroundDetails = disclosure(document, root, 'Coverage and source background');
report.limitations.forEach(value => backgroundDetails.append(node(document, 'p', limitationText(value))));
for (const receipt of report.input_receipts) {
const family = disclosure(document, backgroundDetails, label(receipt.family));
for (const doc of receipt.native_metadata.documents ?? []) {
const background = disclosure(document, family, `${doc.title} — ${label(doc.document_state)}`);
line(document, background, 'Source coverage', doc.read_coverage.note);
source(document, background, {document_id: doc.id, publisher: doc.issuer, url: doc.url,
published_date: doc.published_on, reviewed_at: doc.reviewed_at, retrieved_at: doc.retrieved_at,
sha256: doc.content_sha256, locator: {section: null, page: null, text: doc.read_coverage.locators.join('; ')}, receipt: doc});
}
evidence(document, disclosure(document, family, 'Source background details'), receipt.native_metadata);
}
} catch {
root.replaceChildren();
delete root.contextReport;
root.dataset.state = 'unavailable';
root.append(node(document, 'summary', 'Policy, grid and energy context — unavailable'));
root.append(node(document, 'p', 'This information is temporarily unavailable.'));
}
if (generations.get(host) !== generation) return null;
for (const child of Array.from(host.children)) if (child.hasAttribute(rootAttribute)) child.remove();
host.append(root);
return root;
}Test Support
A JavaScript module in the context ui folder of GlobalGrid2050 that tests pins, ledger, grid fixture and solar context, using SHA-256.
testglobalgrid2050 / automation/news/context-ui/test-support.mjs · lines 1–25 of 25 · pattern encode (shared by 21 files)
- What it does
- It tests pins, ledger, grid fixture and solar context. Defines sha, encode. Uses libraries node:assert/strict, node:crypto, node:fs/promises, node:child_process, node:path. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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 pins.json; JSON file sample_ledger.json; JSON file grid-source-fixture.json; JSON file solar-context.json.
- Downstream impact
- Used directly by 2 files: Adapter Test (globalgrid2050); Browser (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- Defines `sha` and `encode`. It reads `./pins.json`.
- Why it matters
- Imported by Browser. Checked by Adapter Test.
- Application
- globalgrid2050 · automation/news/context-ui · JavaScript module
- Uses
- node:assert/strict, node:crypto, node:fs/promises, node:child_process, node:path, node:url
- Used by
- imported by Adapter Test (import), imported by Browser (import)
- Produces
- directory, pins, sha, encode, figuresDirectory, raw, report
- Defines here
- sha, encode
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/context-ui/test-support.mjs:1-25 · blob ee5653edb8c7b396cd24ebc7c47172ecca29488d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {readFile} from 'node:fs/promises';
import {spawnSync} from 'node:child_process';
import {resolve} from 'node:path';
import {fileURLToPath, pathToFileURL} from 'node:url';
export const directory = fileURLToPath(new URL('./', import.meta.url));
export const pins = JSON.parse(await readFile(new URL('./pins.json', import.meta.url), 'utf8'));
export const sha = bytes => createHash('sha256').update(bytes).digest('hex');
export const encode = value => new TextEncoder().encode(JSON.stringify(value));
assert.ok(process.env.FIGURES_UI_DIR, 'FIGURES_UI_DIR must identify the pinned external renderer directory');
export const figuresDirectory = resolve(process.env.FIGURES_UI_DIR);
for (const [file, hash] of Object.entries(pins.figures_files)) {
assert.equal(sha(await readFile(resolve(figuresDirectory, file))), hash, `Pinned FIGURES ${file}`);
}
export const {buildViewModel} = await import(pathToFileURL(resolve(figuresDirectory, 'model.mjs')));
const result = spawnSync(process.env.PYTHON || 'python', ['-B', '-X', 'utf8', '-m', 'automation.news.build_transition_context',
'--policy', 'automation/news/policy_commitments/sample_ledger.json',
'--grid', 'automation/news/dc_context/grid-source-fixture.json',
'--solar', 'automation/news/dc_context/fixtures/solar-context.json', '--as-of', pins.fixture_as_of],
{cwd: fileURLToPath(new URL('../../../', import.meta.url)), maxBuffer: 17 * 1024 * 1024});
assert.equal(result.status, 0, result.stderr?.toString());
export const raw = new Uint8Array(result.stdout);
assert.equal(sha(raw), pins.fixture_sha256, 'Actual exporter bytes must match accepted receipt');
export const report = JSON.parse(new TextDecoder().decode(raw));Model
A JavaScript module in the datacentre ui folder of GlobalGrid2050 that validates projects (`validateProjects`) and audit (`validateAudit`) and validates official (`validateOfficial`) (units: MW).
transformglobalgrid2050 / automation/news/datacentre-ui/model.js · lines 1–168 of 168 · Entry point · pattern selectRows (shared by 2 files)
- What it does
- It calculates its inputs. Defines 18 functions or classes, including isObject, validText, isUK, safeUrl, requireValid.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentre'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. README: "model.js — strict five-input contract, retained original identifiers, source URL/revision/retrieval evidence, capacity nulls, geographic abstention, quarantine provenance and distinct evidence-grain validation."
- Downstream impact
- Used directly by 3 files: Model Test (globalgrid2050); View (globalgrid2050); GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 6 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents).
- What it achieves
- It validates projects (`validateProjects`), validates audit (`validateAudit`) and validates official (`validateOfficial`). No identity joins.
- Why it matters
- Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/. Also imported by View. Checked by Model Test.
- Application
- globalgrid2050 · automation/news/datacentre-ui · JavaScript module
- Uses
- none found
- Used by
- required by Model Test (require), required by View (require), loaded by GlobalGrid2050 — UK Renewables Pipeline Page (script src)
- Produces
- isObject, validText, isUK, safeUrl, requireValid, distinct, validateProjects, validateAudit, validateOfficial, validateGroups, validateBundle, canonical
- Defines here
- isObject, validText, isUK, safeUrl, requireValid, distinct, validateProjects, validateAudit, validateOfficial, validateGroups, validateBundle, canonical, selectRows, mapUrl, mw, csv, cell, summary
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/datacentre-ui/model.js:1-168 · blob a1a0a3995b47c0cb2fd54f2409935427f5446518 · 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
/* GlobalGrid2050 V9.28: isolated, no-network Data Centre model. No identity joins. */
(function (root, factory) {
const api = factory();
if (typeof module === 'object' && module.exports) module.exports = api;
root.GGDataCentreModel = api;
})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
'use strict';
const PROJECTS = 'globalgrid2050.global-datacentres.projects.v1';
const OFFICIAL = 'globalgrid2050.dc-official-projects.v1';
const GROUPS = 'globalgrid2050.dc-group-links.v1';
const KEYS = ['it_load_mw', 'site_demand_mw', 'grid_connection_mw'];
const isObject = x => x !== null && typeof x === 'object' && !Array.isArray(x);
const validText = x => typeof x === 'string' && x.trim().length > 0;
const isUK = x => x && (x.country?.code === 'GB' || x.country?.code === 'UK' || x.country_code === 'GB');
function safeUrl(x) {
if (typeof x !== 'string') return null;
try {
const u = new URL(x);
return u.protocol === 'https:' && !u.username && !u.password ? u.href : null;
} catch (_) { return null; }
}
function requireValid(ok, why) { if (!ok) throw new Error('Data Centre input rejected: ' + why); }
function distinct(records, field) {
const keys = records.map(x => x[field]);
requireValid(keys.every(validText), 'missing identifier');
requireValid(new Set(keys).size === keys.length, 'duplicate identifier');
}
function validateProjects(data) {
requireValid(isObject(data) && data.schema === PROJECTS && data.scope === 'global', 'projects schema');
requireValid(Array.isArray(data.records) && data.records.length > 0 && data.record_count === data.records.length, 'projects count');
distinct(data.records, 'id');
const countries = new Set();
data.records.forEach(p => {
requireValid(/^DC-WD-Q[1-9]\d*$/.test(p.id) && validText(p.name), 'project identity');
requireValid(p.record_type === 'data_centre' && p.verification_status === 'SOURCE_INDEXED', 'unverified project classification');
requireValid(p.operating_status === 'not_assessed', 'unsupported current operating status');
requireValid(isObject(p.country) && validText(p.country.name) && /^Q[1-9]\d*$/.test(p.country.wikidata_id), 'country');
countries.add(p.country.wikidata_id);
requireValid(p.operator === null || typeof p.operator === 'string', 'operator');
requireValid(isObject(p.source) && safeUrl(p.source.url) && safeUrl(p.source.revision_url) &&
safeUrl(p.source.licence_url) && p.source.licence === 'CC0-1.0' &&
/^\d{4}-\d{2}-\d{2}T/.test(p.source.retrieved_at || ''), 'source / rights / time');
requireValid(isObject(p.capacity) && isObject(p.capacity_sources), 'capacity');
KEYS.forEach(k => {
const value = p.capacity[k], src = p.capacity_sources[k];
requireValid(value === null || (Number.isFinite(value) && value >= 0 && safeUrl(src)), 'unsourced or invalid MW');
});
const pt = p.location;
requireValid(pt === null || (isObject(pt) && Number.isFinite(pt.latitude) && Math.abs(pt.latitude) <= 90 &&
Number.isFinite(pt.longitude) && Math.abs(pt.longitude) <= 180 &&
Number.isFinite(pt.precision_degrees) && pt.precision_degrees > 0), 'location');
});
requireValid(data.country_count === countries.size, 'country count');
return data;
}
function validateAudit(audit, projects) {
requireValid(isObject(audit) && /^globalgrid2050\./.test(audit.schema || ''), 'audit schema');
requireValid(Array.isArray(audit.quarantined) && audit.quarantined_count === audit.quarantined.length, 'quarantine count');
requireValid(audit.selected_count === projects.record_count &&
audit.candidate_count === audit.selected_count + audit.quarantined_count, 'candidate arithmetic');
distinct(audit.quarantined, 'id');
const selected = new Set(projects.records.map(x => x.id));
audit.quarantined.forEach(x => {
requireValid(!selected.has(x.id) && validText(x.name) && validText(x.reason) &&
safeUrl(x.source_revision_url), 'quarantine reason / source');
});
return audit;
}
function validateOfficial(data) {
requireValid(isObject(data) && data.schema === OFFICIAL && Array.isArray(data.projects), 'official schema');
distinct(data.projects, 'project_id');
data.projects.forEach(x => {
requireValid(validText(x.name) && (x.entity_scope === 'planning_case' || x.entity_scope === 'tax_qualification_record') &&
x.current_lifecycle === 'UNKNOWN' && x.review_status === 'PROVISIONAL' &&
isObject(x.source_document) && safeUrl(x.source_document.url) &&
isObject(x.record_event) && validText(x.record_event.kind) && /^\d{4}-\d{2}-\d{2}$/.test(x.record_event.date || '') &&
x.capacity_mw === null, 'official source record is not a verified facility');
});
return data;
}
function validateGroups(data) {
requireValid(isObject(data) && data.schema === GROUPS && Array.isArray(data.records) &&
data.record_count === data.records.length, 'group schema / count');
distinct(data.records, 'project_id');
let provisional = 0, unlinked = 0;
data.records.forEach(x => {
requireValid(x.status === 'PROVISIONAL' || x.status === 'UNLINKED', 'group certainty');
requireValid(x.legal_ownership_verified === false && x.current_operating_status === 'not_assessed' &&
safeUrl(x.source_revision_url) && Array.isArray(x.receipts), 'group rights / status / provenance');
x.receipts.forEach(r => requireValid(safeUrl(r.final_url) && validText(r.publisher) &&
validText(r.retrieved_at), 'group source receipt'));
if (x.status === 'PROVISIONAL') provisional++; else unlinked++;
});
requireValid(data.provisional_count === provisional && data.unlinked_count === unlinked, 'group count');
return data;
}
function validateBundle(bundle) {
requireValid(isObject(bundle), 'missing bundle');
const projects = validateProjects(bundle.projects);
validateOfficial(bundle.official);
validateGroups(bundle.groups);
validateAudit(bundle.audit, projects);
const baseline = validateProjects(bundle.baseline);
const byId = new Map(projects.records.map(x => [x.id, x]));
// Compare semantics, not JSON key order; retrieval times are intentionally newer.
function canonical(x) {
if (Array.isArray(x)) return '[' + x.map(canonical).join(',') + ']';
if (x !== null && typeof x === 'object') return '{' +
Object.keys(x).sort().map(k => JSON.stringify(k) + ':' + canonical(x[k])).join(',') + '}';
return JSON.stringify(x);
}
const sameFields = ['name','record_type','country','operator','operating_status',
'verification_status','location','capacity','capacity_sources','field_sources'];
baseline.records.forEach(x => {
const newer = byId.get(x.id);
requireValid(!!newer, 'original baseline identity lost: ' + x.id);
sameFields.forEach(k => requireValid(canonical(x[k]) === canonical(newer[k]),
'original baseline semantic field changed: ' + x.id + '/' + k));
['publisher','url','revision_url','revision','licence','licence_url'].forEach(k =>
requireValid(x.source[k] === newer.source[k],
'original baseline source changed: ' + x.id + '/' + k));
});
requireValid(baseline.record_count <= projects.record_count, 'baseline larger than expansion');
return bundle;
}
function selectRows(records, {scope = 'uk', query = '', country = ''} = {}) {
const q = String(query).trim().toLocaleLowerCase();
return records.filter(x => (scope !== 'uk' || isUK(x)) &&
(!country || x.country.wikidata_id === country) &&
(!q || [x.name, x.id, x.operator || '', x.country.name].join(' ').toLocaleLowerCase().includes(q)))
.slice().sort((a,b) => Number(isUK(b)) - Number(isUK(a)) ||
a.name.localeCompare(b.name, 'en') || a.id.localeCompare(b.id, 'en'));
}
function mapUrl(x) {
if (!x.location) return null;
const p = x.location, z = p.precision_degrees > 0.01 ? 8 : 14;
return 'https://www.openstreetmap.org/?mlat=' + p.latitude + '&mlon=' + p.longitude +
'#map=' + z + '/' + p.latitude + '/' + p.longitude;
}
const mw = x => x === null || x === undefined ? 'Not reported' : String(x) + ' MW';
function csv(rows) {
const fields = [
['Source entity ID', x => x.id], ['Name', x => x.name],
['Country', x => x.country.name], ['Classification', x => 'Source-indexed lead'],
['Current operation', x => 'Not assessed'], ['IT load MW', x => x.capacity.it_load_mw],
['Site demand MW', x => x.capacity.site_demand_mw], ['Grid connection MW', x => x.capacity.grid_connection_mw],
['Wikidata revision', x => x.source.revision_url], ['Retrieved UTC', x => x.source.retrieved_at],
['IT load source', x => x.capacity_sources.it_load_mw], ['Site demand source', x => x.capacity_sources.site_demand_mw],
['Grid connection source', x => x.capacity_sources.grid_connection_mw]
];
function cell(v) {
let s = v === null || v === undefined ? '' : String(v);
if (/^[=+\-@\t\r\n]/.test(s)) s = "'" + s;
return '"' + s.replace(/"/g, '""') + '"';
}
return [fields.map(x => cell(x[0])).join(',')].concat(rows.map(r => fields.map(x => cell(x[1](r))).join(','))).join('\r\n') + '\r\n';
}
function summary(bundle) {
const records = bundle.projects.records;
return {leads: records.length, uk_leads: records.filter(isUK).length,
countries: bundle.projects.country_count, quarantined: bundle.audit.quarantined_count,
baseline: bundle.baseline.record_count, official_source_records: bundle.official.projects.length,
groups_provisional: bundle.groups.provisional_count, groups_unlinked: bundle.groups.unlinked_count,
verified_facilities: 0};
}
return {validateProjects, validateAudit, validateOfficial, validateGroups, validateBundle,
selectRows, isUK, safeUrl, mapUrl, mw, csv, summary};
});News — Datacentre UI Style Sheet
A style sheet in the automation folder of GlobalGrid2050.
renderglobalgrid2050 / automation/news/datacentre-ui/styles.css · lines 1–37 of 37 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentre'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. README: "styles.css — scoped ggdc-* dark/monospace cyan/yellow, horizontal overflow within table at 375px, without touching global CSS."
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents); A4 Legal Model (globalgrid2050).
- What it achieves
- Local, prefix-scoped V9.24-compatible dark/monospace presentation; no global CSS.
- Why it matters
- Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/.
- Application
- globalgrid2050 · automation/news/datacentre-ui · style sheet
- Uses
- none found
- Used by
- loaded by GlobalGrid2050 — UK Renewables Pipeline Page (stylesheet)
- 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/datacentre-ui/styles.css:1-37 · blob 525fd9d74852d8745d8633135cf55e4ede039fd6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/* Local, prefix-scoped V9.24-compatible dark/monospace presentation; no global CSS. */
.ggdc-component { color: #e3eded; background: #070d10; font: 13px/1.45 ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace; min-width: 0; }
.ggdc-component * { box-sizing: border-box; }
.ggdc-title { margin: 0 0 .4rem; color: #62e7ed; font-size: 1rem; letter-spacing: .04em; }
.ggdc-intro { color: #f4df73; margin: 0 0 .5rem; }
.ggdc-muted, .ggdc-id, .ggdc-stamp { color: #97adb2; font-size: .78rem; }
.ggdc-id, .ggdc-stamp { display: block; margin-top: .2rem; overflow-wrap: anywhere; }
.ggdc-toolbar, .ggdc-filters { display: flex; flex-wrap: wrap; align-items: flex-end; gap: .45rem; margin: .7rem 0; }
.ggdc-component button, .ggdc-component select, .ggdc-component input { font: inherit; color: #e3eded; background: #101c20; border: 1px solid #577279; border-radius: 2px; padding: .42rem .55rem; max-width: 100%; }
.ggdc-component input { width: min(24rem, 100%); }
.ggdc-component button { cursor: pointer; min-height: 37px; }
.ggdc-component button[aria-pressed="true"] { border-color: #62e7ed; color: #62e7ed; text-decoration: underline; text-underline-offset: 3px; }
.ggdc-component button:focus-visible, .ggdc-component input:focus-visible, .ggdc-component select:focus-visible,
.ggdc-component a:focus-visible, .ggdc-scroll:focus-visible { outline: 2px solid #f4df73; outline-offset: 2px; }
.ggdc-filters label { display: flex; flex-direction: column; gap: .25rem; }
.ggdc-component [hidden] { display: none !important; }
.ggdc-status { color: #62e7ed; margin: .5rem 0; }
.ggdc-error { color: #ffc88c; border-left: 2px solid currentColor; padding: .45rem; }
.ggdc-scroll { max-width: 100%; overflow-x: auto; overscroll-behavior-inline: contain; border: 1px solid #28444c; }
.ggdc-table { width: 100%; min-width: 790px; border-collapse: collapse; text-align: left; }
.ggdc-table th { position: sticky; top: 0; background: #142328; color: #f4df73; font-weight: 700; }
.ggdc-table th, .ggdc-table td { border-bottom: 1px solid #294047; padding: .5rem .6rem; vertical-align: top; }
.ggdc-table tbody tr:hover { background: #111e23; }
.ggdc-identity { font-weight: 650; min-width: 9rem; }
.ggdc-evidence { display: flex; flex-direction: column; gap: .3rem; min-width: 8rem; }
.ggdc-source { color: #63e2ed; text-decoration: underline; text-underline-offset: 2px; }
.ggdc-empty { padding: 1rem .4rem; }
@media (max-width: 600px) {
.ggdc-component { font-size: 12px; }
.ggdc-toolbar { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); }
.ggdc-tab { text-align: left; font-size: 11px !important; min-width: 0; }
.ggdc-filters { align-items: stretch; }
.ggdc-filters label { flex: 1 1 100%; }
.ggdc-component input, .ggdc-component select { width: 100%; }
.ggdc-download { width: 100%; }
.ggdc-table { min-width: 720px; }
}Browser Smoke
A Python command-line tool in the tests folder of GlobalGrid2050 that tests official projects, project groups and selection audit, using SHA-256.
testglobalgrid2050 / automation/news/datacentre-ui/tests/browser_smoke.py · lines 1–132 of 132 · Entry point · pattern log_message (shared by 22 files)
- What it does
- It tests official projects, project groups and selection audit. Defines source_path, SilentHandler, log_message, main. Uses libraries __future__, functools, hashlib, http.server, json. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentre'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. README: "tests/harness.html / tests/browser_smoke.py — optional actual Chromium tests at 375, 768 and 1440 width, including search, CSV, official and quarantined categories and fail-closed integrity tampering."
- Inputs & outputs
- In: JSON file projects.json; JSON file official-projects.json; JSON file project-groups.json; JSON file selection-audit.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the source path helper (`source_path`), the silent handler class (`SilentHandler`) and the log message helper (`log_message`). Opt-in real Chromium/Playwright acceptance.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · automation/news/datacentre-ui/tests · Python CLI
- Uses
- __future__, functools, hashlib, http.server, json, pathlib, threading, playwright.sync_api
- Used by
- none found
- Produces
- source_path, SilentHandler, main
- Defines here
- source_path, SilentHandler, log_message, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/datacentre-ui/tests/browser_smoke.py:1-132 · blob 0bdf88405eb4e73ffa2357772b9fc554b4665c02 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Opt-in real Chromium/Playwright acceptance: python automation/news/datacentre-ui/tests/browser_smoke.py
Requires: python -m pip install playwright ; Chromium provisioned with python -m playwright install chromium.
Never publishes/merges or contacts external websites; localhost static server only.
"""
from __future__ import annotations
import functools
import hashlib
import http.server
import json
from pathlib import Path
import threading
from playwright.sync_api import sync_playwright
ROOT = Path(__file__).resolve().parents[4]
DATA = ROOT / "uk_renewables_pipeline" / "202611161757" / "global-datacentres"
BASELINE = ROOT / "uk_renewables_pipeline" / "202611161747" / "global-datacentres" / "projects.json"
PREFIX = "/uk_renewables_pipeline/202611161757/global-datacentres/"
PATHS = {
"projects": PREFIX + "projects.json",
"official": PREFIX + "official-projects.json",
"groups": PREFIX + "project-groups.json",
"audit": PREFIX + "selection-audit.json",
"baseline": "/uk_renewables_pipeline/202611161747/global-datacentres/projects.json",
}
def source_path(url: str) -> Path:
resolved = (ROOT / url.lstrip("/")).resolve()
if not resolved.is_relative_to(ROOT):
raise ValueError("Unsafe fixture")
return resolved
class SilentHandler(http.server.SimpleHTTPRequestHandler):
def log_message(self, *_args):
pass
def main() -> None:
handler = functools.partial(SilentHandler, directory=str(ROOT))
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base = f"http://127.0.0.1:{server.server_port}"
pins = {
"urls": {name: base + url for name, url in PATHS.items()},
"sha256": {name: hashlib.sha256(source_path(url).read_bytes()).hexdigest()
for name, url in PATHS.items()},
}
checks = 0
try:
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=True)
try:
for width in (375, 768, 1440):
page = browser.new_page(viewport={"width": width, "height": 850},
accept_downloads=True)
page.goto(base + "/automation/news/datacentre-ui/tests/harness.html")
page.add_style_tag(url=base + "/automation/news/datacentre-ui/styles.css")
page.add_script_tag(url=base + "/automation/news/datacentre-ui/model.js")
page.add_script_tag(url=base + "/automation/news/datacentre-ui/view.js")
loaded = page.evaluate("""async pins => {
const result = await window.GGDataCentreUI.mount(
document.getElementById('dc'), pins);
return result.error || result.counts;
}""", pins)
assert not isinstance(loaded, str), f"{width}: failed to load: {loaded}"
assert loaded["leads"] == 100 and loaded["uk_leads"] == 54
assert page.locator(".ggdc-table tbody tr").count() == 54
assert page.get_by_role("button", name="UK leads (54)").get_attribute("aria-pressed") == "true"
checks += 3
# Page must not overflow viewport; table remains horizontally scrollable at mobile widths.
widths = page.evaluate("""() => ({
body: document.documentElement.scrollWidth,
viewport: window.innerWidth,
table: document.querySelector('.ggdc-scroll').scrollWidth,
frame: document.querySelector('.ggdc-scroll').clientWidth
})""")
assert widths["body"] <= widths["viewport"] + 2, f"{width}: page overflows: {widths}"
if width < 790:
assert widths["table"] > widths["frame"], f"{width}: table not scrollable"
checks += 2 if width < 790 else 1
page.get_by_role("button", name="Global leads (100)").click()
assert page.locator(".ggdc-table tbody tr").count() == 100
page.get_by_role("button", name="Official source records (3)").click()
assert page.locator(".ggdc-table tbody tr").count() == 3
assert "UNKNOWN" in page.locator(".ggdc-table").inner_text()
page.get_by_role("button", name="Group associations (6)").click()
assert page.locator(".ggdc-table tbody tr").count() == 6
assert "PROVISIONAL" in page.locator(".ggdc-table").inner_text()
page.get_by_role("button", name="Quarantined candidates (38)").click()
assert page.locator(".ggdc-table tbody tr").count() == 38
assert "reason" in page.locator(".ggdc-table").inner_text().lower()
checks += 6
page.get_by_role("button", name="UK leads (54)").click()
page.get_by_role("searchbox", name="Search Data Centre records").fill("CyrusOne")
shown = page.locator(".ggdc-table tbody tr").count()
assert 0 < shown < 54, f"{width}: UK search failed"
checks += 1
page.get_by_role("searchbox", name="Search Data Centre records").fill("")
with page.expect_download() as got:
page.get_by_role("button", name="Export displayed leads (CSV)").click()
data = got.value.path().read_text("utf-8-sig")
assert len(data.strip().splitlines()) == 55
assert "Current operation" in data and "Not assessed" in data
checks += 2
# Mutated hash must clear previously visible records; no stale successes.
bad = json.loads(json.dumps(pins))
bad["sha256"]["projects"] = "0" * 64
failed = page.evaluate("""async pins => {
const result = await window.GGDataCentreUI.mount(
document.getElementById('dc'), pins);
return {error: result.error || null, text: document.getElementById('dc').innerText};
}""", bad)
assert "hash differs" in failed["error"]
assert "unavailable" in failed["text"]
assert page.locator(".ggdc-table tbody tr").count() == 0
checks += 3
page.close()
print(f"PASS: {checks} real Chromium checks across 375 / 768 / 1440; "
"UK-first, four distinct evidence categories, search, CSV, no body overflow, "
"horizontal scroll, hash-negative stale-clearing.")
finally:
browser.close()
finally:
server.shutdown()
server.server_close()
if __name__ == "__main__":
main()Harness
A web page in the tests folder of GlobalGrid2050. Published at https://globalgrid2050.com/automation/news/datacentre-ui/tests/harness.html.
testglobalgrid2050 / automation/news/datacentre-ui/tests/harness.html · lines 1–5 of 5 · Entry point
- What it does
- It tests its inputs. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentre'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. README: "tests/harness.html / tests/browser_smoke.py — optional actual Chromium tests at 375, 768 and 1440 width, including search, CSV, official and quarantined categories and fail-closed integrity tampering."
- Inputs & outputs
- Out: web page.
- Downstream impact
- It is itself an entry point, published at https://globalgrid2050.com/automation/news/datacentre-ui/tests/harness.html.
- What it achieves
- Data Centre isolated browser acceptance fixture.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · automation/news/datacentre-ui/tests · page
- Uses
- none found
- Used by
- none found
- 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/datacentre-ui/tests/harness.html:1-5 · blob 9d7181a85c82693be2297cf17a379bd5ae524897 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Data Centre isolated browser acceptance fixture</title>
<style>html,body{margin:0;max-width:100%;overflow-x:hidden;background:#070d10;color:#e3eded}main{padding:12px;max-width:100%;box-sizing:border-box}</style></head>
<body><main><div id="dc" role="region" aria-label="GlobalGrid2050 Data Centre component"></div></main></body></html>Model Test
A test in the tests folder of GlobalGrid2050 that checks Model. It is built from the read step (`read`), the clone step (`clone`) and the reject step (`reject`).
testglobalgrid2050 / automation/news/datacentre-ui/tests/model.test.cjs · lines 1–99 of 99 · Entry point · pattern reject (shared by 5 files)
- What it does
- It tests its inputs. Defines read, clone, reject. Uses libraries node:test, node:assert/strict, node:fs, node:path. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentre'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. README: "tests/model.test.cjs / tests/view.test.cjs — offline Node tests against the real V9.28 files, baseline and negative evidence/control fixtures."
- Inputs & outputs
- In: JSON file projects.json; JSON file official-projects.json; JSON file project-groups.json; JSON file selection-audit.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- Run from repository root.
- Why it matters
- Run by GlobalGrid2050 V928 Preview Acceptance Workflow.
- Application
- globalgrid2050 · automation/news/datacentre-ui/tests · test
- Uses
- Model (require), node:test, node:assert/strict, node:fs, node:path
- Used by
- run by GlobalGrid2050 V928 Preview Acceptance Workflow (workflow run)
- Produces
- read, clone, reject
- Defines here
- read, clone, reject
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/datacentre-ui/tests/model.test.cjs:1-99 · blob da73f0fa8455c7eef2029f2478f110c3c9d38faa · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/* Run from repository root: node --test automation/news/datacentre-ui/tests/*.test.cjs */
'use strict';
const {test} = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const m = require('../model.js');
const ROOT = path.resolve(__dirname, '../../../..');
const current = path.join(ROOT, 'uk_renewables_pipeline/202611161757/global-datacentres');
const older = path.join(ROOT, 'uk_renewables_pipeline/202611161747/global-datacentres');
const read = f => JSON.parse(fs.readFileSync(f, 'utf8'));
const source = {
projects: read(path.join(current,'projects.json')),
official: read(path.join(current,'official-projects.json')),
groups: read(path.join(current,'project-groups.json')),
audit: read(path.join(current,'selection-audit.json')),
baseline: read(path.join(older,'projects.json'))
};
const clone = () => JSON.parse(JSON.stringify(source));
function reject(name, update) {
test('REJECT: ' + name, () => {
const b = clone();
update(b);
assert.throws(() => m.validateBundle(b), /rejected/);
});
}
test('validated actual source-pinned cohort and sidecars', () => assert.equal(m.validateBundle(source), source));
test('real counts are separate evidence grains, not 103 facilities', () => {
assert.deepEqual(m.summary(source),{
leads:100,uk_leads:54,countries:22,quarantined:38,baseline:12,
official_source_records:3,groups_provisional:3,groups_unlinked:3,verified_facilities:0
});
});
test('UK-first sorting and 54 default UK records', () => {
const uk = m.selectRows(source.projects.records,{scope:'uk'});
assert.equal(uk.length,54);
assert.ok(uk.every(m.isUK));
const all = m.selectRows(source.projects.records,{scope:'global'});
assert.ok(all.slice(0,54).every(m.isUK));
assert.ok(all.slice(54).every(x=>!m.isUK(x)));
});
test('original twelve identities preserved in the successor cohort', () => {
const ids = new Set(source.projects.records.map(x => x.id));
source.baseline.records.forEach(x => assert.ok(ids.has(x.id)));
});
test('no presumed MW, grid connection, or current operation', () => {
for (const x of source.projects.records) {
assert.equal(x.operating_status,'not_assessed');
assert.equal(x.capacity.it_load_mw,null);
assert.equal(x.capacity.site_demand_mw,null);
assert.equal(x.capacity.grid_connection_mw,null);
}
});
test('unknown geometries stay unmappable', () => {
assert.equal(source.projects.records.filter(x=>x.location===null).length,61);
assert.equal(m.mapUrl(source.projects.records.find(x=>x.location===null)),null);
});
test('source filtering and no implicit REPD binding', () => {
assert.equal(m.selectRows(source.projects.records,{scope:'uk',query:'no such source'}).length,0);
assert.ok(m.selectRows(source.projects.records,{scope:'uk',query:'CyrusOne'}).length>0);
assert.equal(Object.keys(source.projects.records[0]).includes('repd_id'),false);
});
test('CSV quotes formula-like values; keeps null MW empty', () => {
const x = structuredClone(source.projects.records[0]);
x.name = '=HYPERLINK("https://evil.example")';
const csv = m.csv([x]);
assert.ok(csv.includes("'=HYPERLINK"));
assert.ok(csv.includes('"IT load MW"'));
assert.ok(csv.includes('""'));
});
test('HTTPS-only original evidence links', () => {
assert.equal(m.safeUrl('javascript:alert(1)'),null);
assert.equal(m.safeUrl('http://example.org'),null);
assert.ok(m.safeUrl(source.projects.records[0].source.revision_url));
});
reject('duplicate source ID', x => x.projects.records[1].id=x.projects.records[0].id);
reject('invented VERIFIED status', x => x.projects.records[0].verification_status='VERIFIED');
reject('invented operational status', x => x.projects.records[0].operating_status='operational');
reject('unsourced MW', x => x.projects.records[0].capacity.it_load_mw=100);
reject('negative MW', x => x.projects.records[0].capacity.it_load_mw=-10);
reject('invented country count', x => x.projects.country_count=999);
reject('unsafe source URL', x => x.projects.records[0].source.revision_url='javascript:alert(1)');
reject('invalid geometry', x => x.projects.records[0].location={latitude:91,longitude:0,precision_degrees:1});
reject('quarantine without reason', x => x.audit.quarantined[0].reason='');
reject('quarantine overlapping selected', x => x.audit.quarantined[0].id=x.projects.records[0].id);
reject('quarantine arithmetic mismatch', x => x.audit.quarantined_count=1);
reject('official record duplicated', x => x.official.projects.push(x.official.projects[0]));
reject('document converted to operating facility', x => x.official.projects[0].current_lifecycle='OPERATIONAL');
reject('provisional legal group mislabelled verified', x => x.groups.records[0].legal_ownership_verified=true);
reject('group link promoted to VERIFIED', x => x.groups.records[0].status='VERIFIED');
reject('group split changed', x => x.groups.provisional_count++);
reject('baseline source identity lost', x => x.baseline.records[0].id='DC-WD-Q999999999');
reject('source rights removed', x => x.projects.records[0].source.licence='UNKNOWN');
reject('timestamp fabricated', x => x.projects.records[0].source.retrieved_at='unknown');
reject('official source mutated to bad URL', x => x.official.projects[0].source_document.url='https://user:pass@example.org/');
reject('baseline original semantic name changed', x => x.baseline.records[0].name='Misidentified site');
reject('baseline original operator changed', x => x.baseline.records[0].operator='Unverified new operator');
reject('baseline original source revision tampered', x => x.baseline.records[0].source.revision=1);View Test
A test in the tests folder of GlobalGrid2050 that checks View, using SHA-256.
testglobalgrid2050 / automation/news/datacentre-ui/tests/view.test.cjs · lines 1–72 of 72 · Entry point · pattern tamper (shared by 2 files)
- What it does
- It tests its inputs. Defines 7 functions or classes, including digest, fetcher, hasMessage, tamper, missing. Uses libraries node:test, node:assert/strict, node:fs, node:path, node:crypto. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentre'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. README: "tests/model.test.cjs / tests/view.test.cjs — offline Node tests against the real V9.28 files, baseline and negative evidence/control fixtures."
- Inputs & outputs
- In: JSON file projects.json; JSON file official-projects.json; JSON file project-groups.json; JSON file selection-audit.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- It is built from the digest step (`digest`), the fetcher step (`fetcher`) and the has message helper (`hasMessage`). Source-integrity loading and failure-mode tests, no external network.
- Why it matters
- Run by GlobalGrid2050 V928 Preview Acceptance Workflow.
- Application
- globalgrid2050 · automation/news/datacentre-ui/tests · test
- Uses
- View (require), node:test, node:assert/strict, node:fs, node:path, node:crypto
- Used by
- run by GlobalGrid2050 V928 Preview Acceptance Workflow (workflow run)
- Produces
- digest, fetcher, hasMessage, tamper, missing, badFetch, badFetch
- Defines here
- digest, fetcher, hasMessage, tamper, missing, badFetch, badFetch
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/datacentre-ui/tests/view.test.cjs:1-72 · blob 4cf242d1577d799d3ea333942cc41649275e4554 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/* Source-integrity loading and failure-mode tests, no external network. */
'use strict';
const {test} = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const view = require('../view.js');
const ROOT = path.resolve(__dirname, '../../../..');
const current = 'uk_renewables_pipeline/202611161757/global-datacentres/';
const baseline = 'uk_renewables_pipeline/202611161747/global-datacentres/projects.json';
const files = {
projects:current+'projects.json',official:current+'official-projects.json',
groups:current+'project-groups.json',audit:current+'selection-audit.json',baseline
};
const contents = Object.fromEntries(Object.entries(files).map(([k,p])=>[k,fs.readFileSync(path.join(ROOT,p),'utf8')]));
const digest = x => crypto.createHash('sha256').update(x).digest('hex');
const inputs = {urls:Object.fromEntries(Object.keys(files).map(k=>[k,'fixture://'+k])),
sha256:Object.fromEntries(Object.keys(files).map(k=>[k,digest(contents[k])]))};
const fetcher = async url => ({ok:true,text:async()=>contents[url.replace('fixture://','')]});
const hasMessage = async (fn,needle) => {
await assert.rejects(fn,e=>String(e.message).includes(needle));
};
test('SHA-256 pinned five-file loader accepts actual cohort',async()=>{
const b=await view.load(inputs,fetcher,digest);
assert.equal(b.projects.records.length,100);
assert.equal(b.official.projects.length,3);
assert.equal(b.groups.records.length,6);
assert.equal(b.audit.quarantined.length,38);
assert.equal(b.baseline.records.length,12);
});
test('reject modified bytes / stale or corrupted source',async()=>{
const tamper=async url=>({ok:true,text:async()=>url==='fixture://projects'?contents.projects+' ':contents[url.replace('fixture://','')]});
await hasMessage(()=>view.load(inputs,tamper,digest),'hash differs');
});
test('reject unavailable source instead of partial rendering',async()=>{
const missing=async url=>url==='fixture://official'?{ok:false}:{ok:true,text:async()=>contents[url.replace('fixture://','')]};
await hasMessage(()=>view.load(inputs,missing,digest),'unavailable');
});
test('reject a missing source hash',async()=>{
const bad=structuredClone(inputs);delete bad.sha256.groups;
await hasMessage(()=>view.load(bad,fetcher,digest),'Unpinned');
});
test('reject URL script scheme even when digest exists',async()=>{
const bad=structuredClone(inputs);bad.urls.projects='javascript:alert(1)';
await hasMessage(()=>view.load(bad,fetcher,digest),'unsafe');
});
test('reject validly hashed but malformed JSON',async()=>{
const badText='{broken';
const bad=structuredClone(inputs);bad.sha256.projects=digest(badText);
const badFetch=async url=>({ok:true,text:async()=>url==='fixture://projects'?badText:contents[url.replace('fixture://','')]});
await assert.rejects(()=>view.load(bad,badFetch,digest),SyntaxError);
});
test('reject validly hashed but fake VERIFIED row',async()=>{
const item=JSON.parse(contents.projects);item.records[0].verification_status='VERIFIED';
const badText=JSON.stringify(item),bad=structuredClone(inputs);bad.sha256.projects=digest(badText);
const badFetch=async url=>({ok:true,text:async()=>url==='fixture://projects'?badText:contents[url.replace('fixture://','')]});
await hasMessage(()=>view.load(bad,badFetch,digest),'unverified');
});
test('on failure, mount removes stale content and visibly fails closed',async()=>{
const previous=global.document;
global.document={createElement(tag){return {tagName:tag,nodeType:1,className:'',textContent:'',setAttribute(){}}}};
try {
const host={nodes:[{textContent:'STALE 100 RECORDS'}],replaceChildren(...nodes){this.nodes=nodes}};
const bad=structuredClone(inputs);bad.sha256.projects='0'.repeat(64);
const r=await view.mount(host,bad,fetcher,digest);
assert.ok(r.error.includes('hash differs'));
assert.equal(host.nodes.length,1);
assert.match(host.nodes[0].textContent,/unavailable/);
assert.doesNotMatch(host.nodes[0].textContent,/STALE/);
} finally {global.document=previous;}
});