In this section
- Check Deeplinks automation · globalgrid2050 / automation/pipeline_release/check_deeplinks.mjs lines 1–74
- Check Template automation · globalgrid2050 / automation/pipeline_release/check_template.mjs lines 1–123
- Code Census automation · globalgrid2050 / automation/pipeline_release/code_census.py lines 1–107
- Code Line Delta automation · globalgrid2050 / automation/pipeline_release/code_line_delta.py lines 1–94
- Automation — Pipeline Release automation · globalgrid2050 / automation/pipeline_release/common.py lines 1–98
- Edition History automation · globalgrid2050 / automation/pipeline_release/edition_history.mjs lines 1–28
Check Deeplinks
A JavaScript module in the pipeline release folder of GlobalGrid2050 that reads grid engine contract and the Renewable Energy Planning Database (REPD) register, using SHA-256.
automationglobalgrid2050 / automation/pipeline_release/check_deeplinks.mjs · lines 1–74 of 74 · Entry point · pattern strip (shared by 31 files)
- What it does
- It loads grid engine contract and the REPD register. Defines strip, contractFaults. Uses libraries node:fs/promises, node:crypto, node:url, 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. Domain terms in the code: the REPD register.
- Inputs & outputs
- In: JSON file grid_engine_contract.json; JSON file build_manifest.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Verify (globalgrid2050). Reached from 5 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Publish Pipeline V923 Ledger Workflow (globalgrid2050); GlobalGrid2050 V923 Six Hour Python Repair Workflow (globalgrid2050).
- What it achieves
- It is built from the strip step (`strip`) and the contract faults helper (`contractFaults`). Every row of one version, against two contracts.
- Why it matters
- Run by Verify.
- Application
- globalgrid2050 · automation/pipeline_release · JavaScript module
- Uses
- node:fs/promises, node:crypto, node:url, node:path
- Used by
- run by Verify (script call)
- Produces
- strip, contractFaults
- Defines here
- strip, contractFaults
- 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/pipeline_release/check_deeplinks.mjs:1-74 · blob 003a34c03ccdf87238a85088bb0e4896900bed03 · 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 node
/* check_deeplinks.mjs - every row of one version, against two contracts.
*
* MAP contract the href the page builds for the MAP button carries the
* row's own REPD reference and technology, the row's own
* coordinates when the geometry is valid and none otherwise.
* Grid Engine contract the same href obeys the Ventus Grid Engine deep-link
* contract (grid_engine_contract.json): canonical receiver,
* no retired receiver, only contract parameters, a numeric
* REPD reference, a technology from the contract's buckets.
* The Grid Engine is the engine behind the MAP link: its
* contract names GridAtlas as the receiver that carries
* it. There is no second link.
*
* Usage: node check_deeplinks.mjs <version folder> [<hrefs.json>]
* Prints one JSON object. With a second argument it also writes every row's MAP
* href keyed by REPD reference, so a version can be compared with its parent row
* by row (verify.py requires the hrefs to be identical).
*/
import { readFile, writeFile } from "node:fs/promises";
import { createHash } from "node:crypto";
import { pathToFileURL, fileURLToPath } from "node:url";
import { dirname, join, resolve } from "node:path";
const release = resolve(process.argv[2]);
const contract = JSON.parse(await readFile(join(dirname(fileURLToPath(import.meta.url)), "grid_engine_contract.json"), "utf8"));
const strip = (u) => String(u).split("?")[0].split("#")[0].replace(/\/+$/, "");
const { buildAtlasDeepLinkV9_7, atlasCentresOnRepdPointV9_7 } = await import(pathToFileURL(join(release, "scripts/core/atlas-receiver-v9-7.js")).href);
const manifest = JSON.parse(await readFile(join(release, "data/v9.1/build_manifest.json"), "utf8"));
const rows = [];
for (const part of manifest.project_partitions) rows.push(...JSON.parse(await readFile(join(release, part.path), "utf8")).projects);
function contractFaults(href, row) {
const faults = [];
let u;
try { u = new URL(href); } catch { return ["href does not parse"]; }
if (strip(u.origin + u.pathname) !== strip(contract.canonical_receiver)) faults.push("not the canonical receiver");
if (contract.retired_receivers.some((r) => strip(r) === strip(u.origin + u.pathname))) faults.push("retired receiver");
for (const key of u.searchParams.keys()) if (!contract.params.includes(key)) faults.push(`parameter outside the contract: ${key}`);
const ref = u.searchParams.get(contract.identity_param);
if (!/^\d+$/.test(ref || "")) faults.push("REPD reference missing or not numeric");
if (ref !== String(row.repd_ref)) faults.push("REPD reference is not the row's");
const tech = u.searchParams.get("technology");
if (!contract.buckets.includes(tech)) faults.push(`technology outside the contract buckets: ${tech}`);
if (tech !== String(row.technology)) faults.push("technology is not the row's");
const located = atlasCentresOnRepdPointV9_7(row);
const hasPoint = u.searchParams.has("latitude") && u.searchParams.has("longitude");
if (located && (u.searchParams.get("latitude") !== String(row.latitude) || u.searchParams.get("longitude") !== String(row.longitude))) faults.push("valid geometry but not the row's coordinates");
if (!located && (u.searchParams.has("latitude") || u.searchParams.has("longitude"))) faults.push("coordinates sent for a row without valid geometry");
if (hasPoint && !u.searchParams.has("zoom")) faults.push("located link without zoom");
return faults;
}
const result = { rows: rows.length, map: { ok: 0, failed: 0 }, grid_engine: { link: "the MAP link (the contract's canonical receiver carries the engine)", ok: 0, failed: 0 }, with_point: 0, without_point: 0, examples: [] };
const hrefs = {};
for (const row of rows) {
if (atlasCentresOnRepdPointV9_7(row)) result.with_point += 1; else result.without_point += 1;
const href = buildAtlasDeepLinkV9_7(row);
hrefs[row.repd_ref] = href || "";
const faults = href ? contractFaults(href, row) : ["no MAP href"];
// MAP contract: identity, technology and coordinates are the row's own.
const mapFaults = faults.filter((f) => /row's|coordinates|zoom|no MAP href|parse/.test(f));
// Grid Engine contract: receiver, parameter names, vocabulary.
const engineFaults = faults.filter((f) => !mapFaults.includes(f) || /no MAP href|parse/.test(f));
if (mapFaults.length) { result.map.failed += 1; if (result.examples.length < 10) result.examples.push(`MAP REPD ${row.repd_ref}: ${mapFaults.join("; ")}`); } else result.map.ok += 1;
if (engineFaults.length) { result.grid_engine.failed += 1; if (result.examples.length < 10) result.examples.push(`GRID ENGINE REPD ${row.repd_ref}: ${engineFaults.join("; ")}`); } else result.grid_engine.ok += 1;
}
result.unique_refs = Object.keys(hrefs).length;
result.hrefs_sha256 = createHash("sha256").update(Object.keys(hrefs).sort((a, b) => a - b).map((k) => `${k} ${hrefs[k]}`).join("\n")).digest("hex");
if (process.argv[3]) await writeFile(process.argv[3], JSON.stringify(hrefs));
result.pass = result.rows === manifest.project_count && result.unique_refs === result.rows && result.map.failed === 0 && result.grid_engine.failed === 0;
console.log(JSON.stringify(result));
process.exit(result.pass ? 0 : 1);Check Template
A JavaScript module in the pipeline release folder of GlobalGrid2050 that reads major project news, interconnectors and the Renewable Energy Planning Database (REPD) register, using SHA-256.
automationglobalgrid2050 / automation/pipeline_release/check_template.mjs · lines 1–123 of 123 · Not reached from any entry point (candidate for review)
- What it does
- It loads major project news, interconnectors and the REPD register. Defines text, json, sha256, fmt. Uses libraries node:assert/strict, node:crypto, node:fs/promises, node:url, node:path. Side effects: reads or writes files.
- 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: interconnectors, the REPD register.
- Inputs & outputs
- In: JSON file release.v9.1.json; JSON file release.v9.5.1.json; JSON file build_manifest.json; JSON file major_project_news_v9_5_1.json; JSON file interconnectors.v9.8.json; JSON file interconnectors.json; JSON file interconnectors_manifest.json.
- What it achieves
- It is built from the text step (`text`), the JSON step (`json`) and the sha256 step (`sha256`). `check_v`@NUM@.mjs - Pipeline News V@VERSION@, proven from the bytes and through the page's OWN loaders (the pattern of `check_v9_13.mjs`).
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · automation/pipeline_release · JavaScript module
- Uses
- node:assert/strict, node:crypto, node:fs/promises, node:url, node:path
- Used by
- none found
- Produces
- text, json, sha256, fmt
- Defines here
- text, json, sha256, fmt
- 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/pipeline_release/check_template.mjs:1-123 · blob 71201eca04fd170a4173050f3d33de16d6b65cf9 · 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: unreached_review
/* check_v@NUM@.mjs - Pipeline News V@VERSION@, proven from the bytes and through the
* page's OWN loaders (the pattern of check_v9_13.mjs).
*
* 1. The contracts bind the fixtures held by @FIXTURE_OWNER@ by path and sha256.
* 2. The page's own loader chain is imported unmodified and executed against the
* files in this folder; every invariant the browser asserts is asserted here.
* 3. The spine partitions are what the manifest says (sha256 and counts).
* 4. The UK newspaper feed is unchanged and Beacon Fen still resolves.
* 5. The interconnector product and contract are the parent's, byte for byte.
* 6. The page states its own identity and version label.
*
* Run: node tests/check_v@NUM@.mjs
*/
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { basename, dirname, join } from "node:path";
const HERE = dirname(fileURLToPath(import.meta.url));
const RELEASE = join(HERE, "..");
const ID = basename(RELEASE);
const ROOT = join(RELEASE, "..", "..");
const VERSION = "@VERSION@";
const STATE = "@STATE@";
const PARENT_ID = "@PARENT_ID@";
const FIXTURE_OWNER = "@FIXTURE_OWNER@";
const PARENT = join(RELEASE, "..", PARENT_ID);
const text = (p) => readFile(p, "utf8");
const json = async (p) => JSON.parse(await text(p));
const sha256 = (b) => createHash("sha256").update(b).digest("hex");
const NEWS_FEED_SHA256 = "cea104c3e9cfc07971680afdf5f64073e1d4825b63bfaf4e969266df8386ebbd";
// 1. contracts bind fixtures
const c91 = await json(join(RELEASE, "contracts", "release.v9.1.json"));
const c951 = await json(join(RELEASE, "contracts", "release.v9.5.1.json"));
assert.equal(c91.source.dataset, "DESNZ Renewable Energy Planning Database Q3 2026");
for (const [pathKey, shaKey] of [["identity_fixture", "identity_fixture_sha256"], ["coordinate_fixture", "coordinate_fixture_sha256"]]) {
const rel = c91.source[pathKey];
assert.ok(rel.startsWith(`uk_renewables_pipeline/${FIXTURE_OWNER}/fixtures/`), `${pathKey} must be the fixture owner's: ${rel}`);
assert.equal(sha256(await readFile(join(ROOT, rel))), c91.source[shaKey], `${pathKey} bytes`);
}
const coords = await json(join(ROOT, c91.source.coordinate_fixture));
assert.equal(coords.source_workbook_sha256, c91.source.workbook_sha256, "coordinate fixture names the contract workbook");
const identity = await json(join(ROOT, c91.source.identity_fixture));
assert.equal(identity.schema, "globalgrid2050.project-identity.v6");
assert.equal(identity.records.length, identity.raw_record_count);
assert.equal(coords.source_records, identity.raw_record_count, "workbook and identity hold the same refs");
// 2. the page's own loader, unmodified, against these bytes
const ORIGIN = "http://release.invalid";
const BASE = `${ORIGIN}/uk_renewables_pipeline/${ID}/`;
globalThis.window = { location: { origin: ORIGIN, href: BASE } };
globalThis.fetch = async (path) => {
const url = new URL(path, BASE);
assert.ok(url.pathname.startsWith(`/uk_renewables_pipeline/${ID}/`), `loader fetched outside the release: ${url}`);
const file = join(RELEASE, decodeURIComponent(url.pathname.slice(`/uk_renewables_pipeline/${ID}/`.length)));
const body = await text(file);
return { ok: true, status: 200, url: url.href, json: async () => JSON.parse(body) };
};
const loader = await import(new URL("../scripts/data/canonical-projects-v9-5-1.js", import.meta.url).href);
const model = await loader.loadCanonicalProjectsV9_5_1();
assert.equal(model.projects.length, c951.expected.project_count);
assert.equal(Math.round(model.metadata.capacity_mw), c951.expected.displayed_capacity_mw);
// 3. partitions are the manifest's bytes
const manifest = await json(join(RELEASE, "data", "v9.1", "build_manifest.json"));
for (const part of [...manifest.project_partitions, ...manifest.atlas_partitions]) {
assert.equal(sha256(await readFile(join(RELEASE, part.path))), part.sha256, `${part.path} hash`);
}
const atlasFeatures = manifest.atlas_partitions.reduce((n, p) => n + p.feature_count, 0);
assert.equal(atlasFeatures, manifest.geometry_count, "atlas features = valid geometries");
for (const key of Object.keys(c91.expected)) assert.equal(manifest[key], c91.expected[key], `manifest ${key}`);
assert.equal(manifest.source_dataset, c91.source.dataset);
assert.equal(manifest.source_record_count, identity.raw_record_count);
// 4. the newspaper: unchanged Q2 feed, every bound ref still resolves
const feedBytes = await readFile(join(ROOT, "dist", "major_project_news_v9_5_1.json"));
assert.equal(sha256(feedBytes), NEWS_FEED_SHA256, "dist/major_project_news_v9_5_1.json must not be rebuilt by this release");
const feed = JSON.parse(feedBytes);
const byRef = new Map(model.projects.map((p) => [p.repd_ref, p]));
const boundRefs = new Set(feed.canonical_items.map((item) => String(item.repd_ref)));
const unresolved = [...boundRefs].filter((ref) => !byRef.has(ref));
const beacon = byRef.get(feed.beacon_fen_contract.repd_ref);
assert.ok(beacon, "Beacon Fen must be in the spine");
assert.equal(beacon.capacity_mw, feed.beacon_fen_contract.official_capacity_mw, "Beacon Fen official capacity");
// 5. interconnectors are the parent's
for (const rel of ["contracts/interconnectors.v9.8.json", "data/v9.8/interconnectors.json", "data/v9.8/interconnectors_manifest.json"]) {
assert.equal(sha256(await readFile(join(RELEASE, rel))), sha256(await readFile(join(PARENT, rel))), `${rel} is the parent's`);
}
// 6. page identity
const fmt = (n) => n.toLocaleString("en-GB");
const html = await text(join(RELEASE, "index.html"));
const compact = html.includes(`data-edition="${ID}"`);
assert.ok(compact || html.includes(`UK RENEWABLES PIPELINE ${ID}`), "visible page identity names this release");
assert.ok(new RegExp(`Canonical DESNZ REPD Q3 2026[^<]*${fmt(manifest.project_count)} solar, BESS and wind records`).test(html), "index.html states the Q3 register count");
assert.ok(!html.includes("REPD Q2 2026: 7,680"), "index.html must not claim the Q2 register");
assert.ok(html.includes("scripts/app-v9-8.js"), "index.html loads the v9.8 app");
const label = html.slice(html.indexOf("<body>"), html.indexOf('<section class="newspaper">'));
assert.ok(!/CANDIDATE/.test(label.replaceAll("RELEASE CANDIDATE", "")), "brand, nav, h1 and meta carry no candidate label other than this version's own state");
if (compact) {
assert.ok(label.includes(`<small>PIPELINE NEWS · V${VERSION}</small>`), "compact brand names the version");
assert.ok(label.includes(`>V${VERSION} · PIPELINE NEWS</a>`), "compact nav names the version");
assert.ok(label.includes(`V${VERSION} · `) && label.includes(' · REPD OCTOBER 2026 · '), "compact stamp names the version and source vintage");
assert.ok(html.includes(`<title>GlobalGrid2050 | Pipeline News V${VERSION} · ${ID}</title>`), "compact title names this release");
assert.equal((html.match(/<section\b/g)||[]).length,2,"exactly two principal blocks");
for (const tab of ['solarTab','bessTab','gridTab','datacentreTab']) assert.ok(html.includes(`id="${tab}" role="tab"`),`category ${tab}`);
assert.ok(!html.includes('<th>NEWS SIGNAL</th>')&&!html.includes('id="solar1000Pilot"'),"withdrawn panels/column do not return");
} else {
assert.ok(label.includes(`<small>UK RENEWABLES PIPELINE · V${VERSION}</small>`), "brand names the version");
assert.ok(label.includes(`<a class="active" href="#">V${VERSION} ${STATE} · REPD Q3 2026</a>`), "nav names the version");
assert.ok(new RegExp(`<strong>V${VERSION.replace(".", "\\.")} · REPD OCTOBER 2026 \\(Q3\\) · [^<]+ · ${STATE} · \\d+ November 2026</strong>`).test(label), "meta line names the version and its date");
assert.ok(html.includes(`<title>GlobalGrid2050 | UK Renewables Pipeline ${ID}</title>`), "title names this release");
}
assert.ok(label.includes(`<a href="../${PARENT_ID}/">`), "nav links back to the parent");
assert.ok(label.includes('<a href="../versions.html">'), "nav links to the list of all versions");
console.log(`check_v@NUM@: ${ID} loader PASS - ${fmt(model.projects.length)} records, ${model.metadata.capacity_mw.toLocaleString("en-GB", { minimumFractionDigits: 2 })} MW, `
+ `${manifest.geometry_count} with geometry / ${manifest.missing_geometry_count} without; news feed unchanged, `
+ `${boundRefs.size - unresolved.length}/${boundRefs.size} bound refs resolve${unresolved.length ? ` (unresolved: ${unresolved.join(", ")})` : ""}`);Code Census
A Python module in the pipeline release folder of GlobalGrid2050 that reads summary and the Renewable Energy Planning Database (REPD) register.
automationglobalgrid2050 / automation/pipeline_release/code_census.py · lines 1–107 of 107 · Entry point · pattern total (shared by 3 files)
- What it does
- It loads summary and the REPD register. Defines git, group, kind, summarise, total. Uses libraries argparse, collections, csv, json, pathlib. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- 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: the REPD register.
- Inputs & outputs
- In: CSV file files.csv; command-line arguments. Out: JSON file summary.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Pipeline Code Census Workflow (globalgrid2050).
- What it achieves
- It is built from the git step (`git`), the group step (`group`) and the kind step (`kind`). Read-only census of committed Pipeline News files; identical blobs counted once. It accepts `--ref`, `--current` and `--output`.
- Why it matters
- Run by GlobalGrid2050 Pipeline Code Census Workflow.
- Application
- globalgrid2050 · automation/pipeline_release · Python module
- Uses
- argparse, collections, csv, json, pathlib, re, subprocess
- Used by
- run by GlobalGrid2050 Pipeline Code Census Workflow (workflow run)
- Produces
- git, group, kind, summarise
- Defines here
- git, group, kind, summarise, total
- 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/pipeline_release/code_census.py:1-107 · blob fe82908c3229ad45097e49a8c746c61671416ca7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Read-only census of committed Pipeline News files; identical blobs counted once."""
import argparse
from collections import defaultdict
import csv
import json
from pathlib import Path, PurePosixPath
import re
import subprocess
CODE={'.py','.js','.mjs','.cjs','.ts','.tsx','.jsx','.html','.css','.scss','.sh','.bash','.ps1','.sql','.rs','.go','.java','.c','.cpp','.h','.hpp','.vue','.svelte'}
DATA={'.json','.jsonl','.ndjson','.csv','.tsv','.geojson','.parquet','.xml','.xlsx','.db','.sqlite','.gpkg','.pbf','.zip','.gz'}
DOC={'.md','.rst','.txt','.pdf','.docx'}
AUTOMATION={'news','pipeline_release','repd','pipeline_public','convergence','dc_location_ui','document_facts_ui','energy_context_ui','grid_notice_ui','journey_entry_ui','journey_return_ui','mobile_map_ui','news_history_return','news_quality_ui','price_daily_ui','primary_note_ui','repd_expand_ui','ticker_crisp_ui','ticker_neon_ui','v923-recovery','v924_public','v928_context','v928_intelligence'}
def git(*args):
return subprocess.check_output(['git',*args])
def group(path):
p=PurePosixPath(path)
if p.parts[0]=='uk_renewables_pipeline':
return 'Current V9.57' if p.parts[1]==current else 'Historical application versions'
if p.parts[0]=='automation' and len(p.parts)>2:
folder=p.parts[1]
if folder=='news': return 'News intelligence engine'
if folder=='pipeline_release': return 'Release engineering'
if folder in AUTOMATION or re.fullmatch(r'v9\d{2}_preview',folder):
return 'Other related automation'
if p.parts[:2]==('.github','workflows') and re.search(r'pipeline|repd|pn-v9|news',p.name,re.I):
return 'CI/CD workflows'
return None
def kind(path):
p=PurePosixPath(path); parts={s.lower() for s in p.parts}; n=p.name.lower(); ext=p.suffix.lower()
if parts & {'vendor','node_modules','third_party','third-party','thirdparty','external'} or n.endswith(('.min.js','.min.css')): return 'Third-party/vendor'
if n in {'package-lock.json','yarn.lock','pnpm-lock.yaml','requirements.txt','package.json','pyproject.toml'}: return 'Dependency manifests'
if ext in CODE:
if parts & {'test','tests','__tests__','spec','specs'} or re.match(r'(test[-_]|check[-_]|validate[-_])',n) or n.endswith(('.test.js','.spec.js','.test.mjs')): return 'Tests'
if parts & {'fixtures','generated','dist'}: return 'Generated/fixture code'
return 'Application/automation source'
if p.parts[:2]==('.github','workflows') and ext in {'.yml','.yaml'}: return 'Workflow configuration'
if ext in DATA or parts & {'fixtures'}: return 'Data/fixtures'
if ext in DOC: return 'Documentation'
if ext in {'.yaml','.yml','.toml','.ini','.cfg'}: return 'Other configuration'
return 'Other assets'
parser=argparse.ArgumentParser()
parser.add_argument('--ref',default='HEAD')
parser.add_argument('--current',default='202611201709')
parser.add_argument('--output',default='pipeline-code-census')
args=parser.parse_args()
current=args.current
commit=git('rev-parse',args.ref).decode().strip()
root=Path(args.output);root.mkdir(parents=True,exist_ok=True)
entries=[]
for record in git('ls-tree','-rlz',commit).split(b'\0'):
if not record: continue
meta,path=record.split(b'\t',1); mode,typ,oid,size=meta.decode().split()
if typ!='blob': continue
path=path.decode('utf-8','surrogateescape'); scope=group(path)
if scope: entries.append(dict(path=path,scope=scope,category=kind(path),blob=oid,bytes=int(size)))
line_kinds={'Application/automation source','Tests','Generated/fixture code','Third-party/vendor','Workflow configuration','Other configuration'}
metrics={}
# Persistent Git process: one blob read per unique content, no working-tree writes.
with subprocess.Popen(['git','cat-file','--batch'],stdin=subprocess.PIPE,stdout=subprocess.PIPE) as proc:
for e in entries:
oid=e['blob']
if e['category'] not in line_kinds or oid in metrics: continue
proc.stdin.write((oid+'\n').encode());proc.stdin.flush()
header=proc.stdout.readline().split()
assert len(header)==3 and header[1]==b'blob',header
content=proc.stdout.read(int(header[2]));assert proc.stdout.read(1)==b'\n'
try: lines=content.decode('utf-8').splitlines()
except UnicodeDecodeError: metrics[oid]=(None,None);continue
if b'\0' in content: metrics[oid]=(None,None);continue
metrics[oid]=(len(lines),sum(bool(l.strip()) for l in lines))
proc.stdin.close()
for e in entries:
e['lines'],e['nonblank_lines']=metrics.get(e['blob'],(None,None)) if e['category'] in line_kinds else (None,None)
def summarise(items):
unique={}
for e in items:
if e['blob'] not in unique or (unique[e['blob']]['lines'] is None and e['lines'] is not None):unique[e['blob']]=e
def total(rows,key):return sum(e[key] or 0 for e in rows)
u=list(unique.values())
return dict(files=len(items),unique_blobs=len(u),bytes=total(items,'bytes'),unique_bytes=total(u,'bytes'),physical_lines=total(items,'lines'),nonblank_lines=total(items,'nonblank_lines'),unique_physical_lines=total(u,'lines'),unique_nonblank_lines=total(u,'nonblank_lines'),line_counted_files=sum(e['lines'] is not None for e in items))
scopes={}
for s in sorted({e['scope'] for e in entries}):
items=[e for e in entries if e['scope']==s]
scopes[s]={k:summarise([e for e in items if e['category']==k]) for k in sorted({e['category'] for e in items})}
categories={k:summarise([e for e in entries if e['category']==k]) for k in sorted({e['category'] for e in entries})}
source=[e for e in entries if e['category']=='Application/automation source']
current_source=[e for e in source if e['scope']=='Current V9.57']
current_ids={e['blob'] for e in current_source}
historical_extra=[e for e in source if e['scope']=='Historical application versions' and e['blob'] not in current_ids]
report={'commit':commit,'release':current,'method':'Physical and nonblank lines of UTF-8 text; exact content deduplication by Git blob. Comments included, near-duplicates not collapsed. Source is a path/extension classification, not reachability or authorship proof. Data and docs counted as files and bytes, not LOC. Scope excludes external repositories and untracked files. Category and scope total … [line shortened here: 645 characters; full line on GitHub]
(root/'summary.json').write_text(json.dumps(report,indent=2)+'\n')
with (root/'files.csv').open('w',newline='',encoding='utf-8') as f:
w=csv.DictWriter(f,fieldnames=['path','scope','category','blob','bytes','lines','nonblank_lines']);w.writeheader();w.writerows(entries)
lines=['# Pipeline News code census','',f'Commit: `{commit}`',f'Current release: `{current}`','',report['method'],'','| Scope | Category | Files | Unique files | Physical lines | Unique physical lines | Unique nonblank lines | Unique bytes |','|---|---|---:|---:|---:|---:|---:|---:|']
for s,cats in scopes.items():
for k,m in cats.items():
values=[m['files'],m['unique_blobs']]+([m['physical_lines'],m['unique_physical_lines'],m['unique_nonblank_lines']] if m['line_counted_files'] else ['—']*3)+[m['unique_bytes']]
lines.append('| '+s+' | '+k+' | '+' | '.join(f'{v:,}' if isinstance(v,int) else v for v in values)+' |')
lines+=['','## Deduplicated estate-wide totals','',f"Application/automation source: {report['all_source']['unique_physical_lines']:,} physical lines; {report['all_source']['unique_nonblank_lines']:,} nonblank lines; {report['all_source']['unique_blobs']:,} unique files.",f"Historical source absent as exact content from current V9.57: {report['historical_source_not_in_current']['unique_physical_lin … [line shortened here: 510 characters; full line on GitHub]
md='\n'.join(lines)+'\n';(root/'summary.md').write_text(md);print(md)Code Line Delta
A Python command-line tool in the pipeline release folder of GlobalGrid2050. It is built from the git step (`git`), the versions step (`versions`) and the entries step (`entries`).
automationglobalgrid2050 / automation/pipeline_release/code_line_delta.py · lines 1–94 of 94 · Entry point · pattern entries (shared by 4 files)
- What it does
- Defines 7 functions or classes, including git, versions, entries, text_lines, compare. Uses libraries argparse, difflib, json, pathlib, re. 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: command-line arguments. Out: JSON file delta.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Pipeline Code Census Workflow (globalgrid2050).
- What it achieves
- Quick immutable Pipeline News release delta; no checkout of copied app trees. It accepts `--ref`, `--current` and `--previous`.
- Why it matters
- Run by GlobalGrid2050 Pipeline Code Census Workflow.
- Application
- globalgrid2050 · automation/pipeline_release · Python CLI
- Uses
- argparse, difflib, json, pathlib, re, subprocess
- Used by
- run by GlobalGrid2050 Pipeline Code Census Workflow (workflow run)
- Produces
- git, versions, entries, text_lines, compare, main
- Defines here
- git, versions, entries, text_lines, compare, totals, 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/pipeline_release/code_line_delta.py:1-94 · blob fa0c4b45d96aef88ee569a2961d339da31b6c185 · 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
"""Quick immutable Pipeline News release delta; no checkout of copied app trees."""
import argparse
import difflib
import json
from pathlib import Path
import re
import subprocess
TEXT_EXT = {".html",".css",".js",".mjs",".cjs",".jsx",".ts",".tsx",".py",".sh",".md",".txt",".yml",".yaml",".json5"}
CODE_EXT = TEXT_EXT - {".md",".txt",".yml",".yaml",".json5"}
PREFIX = "uk_renewables_pipeline/"
def git(*args):
return subprocess.check_output(["git",*args])
def versions(ref):
names=git("ls-tree","--name-only","-d",ref+":"+PREFIX.rstrip("/")).decode().splitlines()
return sorted(name for name in names if re.fullmatch(r"20\d{10}",name))
def entries(ref,version):
raw=git("ls-tree","-r","-z",ref+":"+PREFIX+version)
return {path.decode("utf-8","surrogateescape"):meta.split()[2].decode()
for meta,path in (rec.split(b"\t",1) for rec in raw.split(b"\0") if rec)}
def text_lines(sha):
if sha is None: return []
data=git("cat-file","blob",sha)
if b"\0" in data or len(data)>2000000: return None
try: return data.decode("utf-8").splitlines()
except UnicodeError: return None
def compare(ref,previous,current):
old,new=entries(ref,previous),entries(ref,current)
changes=[]
for path in sorted(set(old)|set(new)):
if old.get(path)==new.get(path): continue
ext=Path(path).suffix.lower()
kind="source" if ext in CODE_EXT else "other-text" if ext in TEXT_EXT else "binary/data"
added=deleted=None
if kind!="binary/data":
a,b=text_lines(old.get(path)),text_lines(new.get(path))
if a is not None and b is not None:
opcodes=difflib.SequenceMatcher(a=a,b=b,autojunk=False).get_opcodes()
added=sum(j2-j1 for tag,i1,i2,j1,j2 in opcodes if tag in ("replace","insert"))
deleted=sum(i2-i1 for tag,i1,i2,j1,j2 in opcodes if tag in ("replace","delete"))
changes.append(dict(path=path,kind=kind,added=added,deleted=deleted,
before=old.get(path),after=new.get(path)))
def totals(rows):
return dict(added=sum(x["added"] or 0 for x in rows),
deleted=sum(x["deleted"] or 0 for x in rows),
changed_files=len(rows))
exact_same=sum(old.get(p)==new.get(p) for p in (set(old)|set(new)))
return dict(previous=previous,current=current,git_ref=ref,
identical_inherited_files=exact_same,
all_text=totals([x for x in changes if x["added"] is not None]),
source=totals([x for x in changes if x["kind"]=="source" and x["added"] is not None]),
nontext_changed_files=sum(x["added"] is None for x in changes),
changed_files=len(changes),files=changes)
def main():
p=argparse.ArgumentParser()
p.add_argument("--ref",default="HEAD")
p.add_argument("--current",default="latest")
p.add_argument("--previous")
p.add_argument("--output",default="/tmp/pipeline-release-delta")
args=p.parse_args()
v=versions(args.ref)
current=v[-1] if args.current=="latest" else args.current
if current not in v: p.error("unknown timestamped release: "+current)
idx=v.index(current)
if idx==0 and args.previous is None: p.error("no predecessor")
previous=args.previous or v[idx-1]
if previous not in v or previous>=current:p.error("invalid predecessor")
report=compare(args.ref,previous,current)
out=Path(args.output);out.mkdir(parents=True,exist_ok=True)
(out/"delta.json").write_text(json.dumps(report,indent=2)+"\n")
total=report["all_text"];code=report["source"]
summary="\n".join((
"## Pipeline News immutable release delta",
"",
f"**{previous} → {current}**",
f"**{total['added']:,} lines added, {total['deleted']:,} removed** across {total['changed_files']} text files.",
f"Application source: +{code['added']:,} / -{code['deleted']:,} lines in {code['changed_files']} files.",
f"Exact inherited unchanged files: {report['identical_inherited_files']:,}.",
f"Nontext/data changes: {report['nontext_changed_files']}.",
"",
"Counts are source-to-source differences, not duplicated lines from full release copies.",
"Full ledger: delta.json",
""
))
(out/"summary.md").write_text(summary)
print(summary)
if __name__=="__main__": main()Automation — Pipeline Release
A Python module in GlobalGrid2050 that validates registry metadata (`validate_registry_metadata`), loads registry (`load_registry`) and saves registry (`save_registry`), using SHA-256.
automationglobalgrid2050 / automation/pipeline_release/common.py · lines 1–98 of 98 · pattern load_registry (shared by 3 files)
- What it does
- It loads data. Defines 8 functions or classes, including walk, sha256, tree_hash, re_runner, data_digest. Uses libraries hashlib, json, os, subprocess, tempfile. 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 registry.json.
- Downstream impact
- Used directly by 7 files: Test Release Audit (globalgrid2050); Test Release Feature Migrations (globalgrid2050); Feature Contracts (globalgrid2050); New Version (globalgrid2050); and 3 more. Reached from 14 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Publish Pipeline V923 Ledger Workflow (globalgrid2050).
- What it achieves
- It is built from the walk step (`walk`), the sha256 step (`sha256`) and the tree hash helper (`tree_hash`). Shared helpers for the Pipeline News release train (standard library only).
- Why it matters
- Imported by 4 files, including Feature Contracts, New Version and Verify. Checked by 3 tests, including Test Release Audit.
- Application
- globalgrid2050 · automation/pipeline_release · Python module
- Uses
- hashlib, json, os, subprocess, tempfile, pathlib, re
- Used by
- imported by Test Release Audit (sys.path import), imported by Test Release Feature Migrations (sys.path import), imported by Feature Contracts (import), imported by New Version (import), imported by Test Registry Metadata (sys.path import), imported by Verify (import), imported by Repair (sys.path import)
- Produces
- walk, sha256, tree_hash, re_runner, data_digest, validate_registry_metadata, load_registry, save_registry
- Defines here
- walk, sha256, tree_hash, re_runner, data_digest, validate_registry_metadata, load_registry, save_registry
- 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/pipeline_release/common.py:1-98 · blob c6a58fb3b7a6457b527cb4f71e8bbee289c913fe · 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
"""Shared helpers for the Pipeline News release train (standard library only)."""
import hashlib
import json
import os
import subprocess
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
PIPELINE = ROOT / "uk_renewables_pipeline"
REGISTRY = HERE / "registry.json"
SKIP_PARTS = {"__pycache__", "node_modules"}
def walk(folder: Path):
"""Relative paths of every release file, sorted, as the runners walk them."""
out = []
for path in folder.rglob("*"):
if not path.is_file() or path.suffix == ".pyc" or SKIP_PARTS & set(path.parts):
continue
out.append(path.relative_to(folder).as_posix())
return sorted(out)
def sha256(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def tree_hash(version_id: str, root: Path = ROOT) -> str:
"""Git tree hash of the bytes ON DISK of one version folder (same method as the runners)."""
rel = f"uk_renewables_pipeline/{version_id}"
files = [f"{rel}/{p}" for p in walk(root / rel)]
with tempfile.TemporaryDirectory() as scratch:
env = dict(os.environ, GIT_DIR=f"{scratch}/objects.git", GIT_WORK_TREE=str(root), GIT_INDEX_FILE=f"{scratch}/index")
subprocess.run(["git", "init", "-q", "--bare", f"{scratch}/objects.git"], check=True, env={k: v for k, v in os.environ.items() if not k.startswith("GIT_")})
subprocess.run(["git", "-C", str(root), "-c", "core.autocrlf=false", "-c", "core.fileMode=true", "update-index", "--add", "-z", "--stdin"],
input=("\0".join(files) + "\0").encode("utf-8"), check=True, env=env)
# Windows cannot recover executable bits from disk. Preserve tracked
# modes; new release runners are executable by the release contract.
if os.name == "nt":
tracked = subprocess.run(["git", "-C", str(root), "ls-files", "-s", "-z", "--", rel],
check=True, capture_output=True).stdout
modes = {entry.split(b"\t", 1)[1].decode(): entry.split(b" ", 1)[0].decode()
for entry in tracked.split(b"\0") if entry}
for mode in ("100644", "100755"):
paths = [p for p in files if modes.get(p, "100755" if re_runner(p) else "100644") == mode]
if paths:
subprocess.run(["git", "update-index", "--chmod=" + ("+x" if mode == "100755" else "-x"), "-z", "--stdin"],
input=("\0".join(paths) + "\0").encode(), check=True, env=env, cwd=root)
return subprocess.run(["git", "write-tree", f"--prefix={rel}/"], check=True, env=env, capture_output=True, text=True).stdout.strip()
def re_runner(path):
import re
return bool(re.search(r"/tests/run_v9_\d+\.sh$", path))
def data_digest(folder: Path) -> str:
"""One hash over every file under data/ (path and sha256), to compare a version with its parent."""
h = hashlib.sha256()
for rel in walk(folder / "data"):
h.update(f"{rel} {sha256(folder / 'data' / rel)}\n".encode())
return h.hexdigest()
def validate_registry_metadata(reg):
"""Reject malformed CI metadata before release checks or registry writes."""
if not isinstance(reg, dict) or not isinstance(reg.get("versions"), list):
raise ValueError("release registry must be an object with a versions array")
for index, version in enumerate(reg["versions"]):
if not isinstance(version, dict):
raise ValueError(f"registry versions[{index}] must be an object")
label = version.get("id", f"versions[{index}]")
ci = version.get("ci")
if ci is None:
continue
if not isinstance(ci, dict):
raise ValueError(f"registry version {label}: ci must be an object or null")
# These are the optional fields used by the ledger renderer. Preserve
# all other historical metadata and impose no URL or result enum policy.
for field in ("url", "conclusion"):
if field in ci and not isinstance(ci[field], str):
raise ValueError(f"registry version {label}: ci.{field} must be a string")
return reg
def load_registry():
return validate_registry_metadata(json.loads(REGISTRY.read_text(encoding="utf-8")))
def save_registry(reg):
validate_registry_metadata(reg)
REGISTRY.write_text(json.dumps(reg, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", newline="\n")Edition History
A JavaScript module in the pipeline release folder of GlobalGrid2050 that works with protected edition changes (`protectedEditionChanges`).
automationglobalgrid2050 / automation/pipeline_release/edition_history.mjs · lines 1–28 of 28
- What it does
- It lists and searches its content. Defines protectedEditionChanges, git. Uses libraries node:child_process. Side effects: 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.
- Downstream impact
- Used directly by 9 files: Edition History Test (globalgrid2050); Invariants (globalgrid2050); Invariants (globalgrid2050); Invariants (globalgrid2050); and 5 more. Reached from 7 other entry points, including GlobalGrid2050 V928 Preview Acceptance Workflow (globalgrid2050); GlobalGrid2050 V929 Preview Acceptance Workflow (globalgrid2050); GlobalGrid2050 V930 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- It is built from the protected edition changes helper (`protectedEditionChanges`) and the git step (`git`). Test-only guard: every numeric edition directory in the pinned base is immutable.
- Why it matters
- Run by Invariants. Checked by 3 tests, including Edition History Test.
- Application
- globalgrid2050 · automation/pipeline_release · JavaScript module
- Uses
- node:child_process
- Used by
- run by Edition History Test (script call), run by Invariants (script call), run by Invariants (script call), run by Invariants (script call), run by Invariants (script call), run by Invariants (script call), run by Invariants (script call), imported by Contracts Test (import), and 1 more
- Produces
- protectedEditionChanges
- Defines here
- protectedEditionChanges, git
- 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/pipeline_release/edition_history.mjs:1-28 · blob a575813dbe15f19445df3007e59dc5c3d9d02352 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Test-only guard: every numeric edition directory in the pinned base is immutable. */
import {execFileSync} from 'node:child_process';
export function protectedEditionChanges({cwd,base}) {
if (typeof cwd!=='string'||!cwd||typeof base!=='string'||!base.trim()) {
throw new TypeError('History guard requires a repository directory and pinned base');
}
const git=args=>execFileSync('git',args,{cwd,encoding:'utf8',maxBuffer:16*1024*1024,stdio:['ignore','pipe','pipe']});
let commit,directories;
try {
commit=git(['rev-parse','--verify','--end-of-options',base+'^{commit}']).trim();
const tree=git(['rev-parse','--verify','--end-of-options',commit+':uk_renewables_pipeline']).trim();
if (git(['cat-file','-t',tree]).trim()!=='tree') throw new Error('Pipeline baseline is not a directory');
directories=git(['ls-tree','-d','--name-only','-z',tree]).split('\0')
.filter(name=>/^\d{12}$/.test(name)).map(name=>'uk_renewables_pipeline/'+name);
if (!directories.length) throw new Error('Pipeline baseline has no numeric edition directories');
} catch (cause) {
throw new Error('Cannot resolve immutable edition history from pinned base '+base,{cause});
}
// Check both the working tree and index: an unstaged restoration must not hide
// a staged mutation. No rename detection means the original deletion is kept.
const changed=new Set([
...git(['diff','--name-only','--no-renames','-z',commit,'--']).split('\0'),
...git(['diff','--cached','--name-only','--no-renames','-z',commit,'--']).split('\0'),
...git(['ls-files','--others','--exclude-standard','-z']).split('\0')
].filter(Boolean));
return [...changed].filter(path=>directories.some(dir=>path===dir||path.startsWith(dir+'/'))).sort();
}