In this section
- Feature Contracts automation · globalgrid2050 / automation/pipeline_release/feature_contracts.py lines 1–349
- New Version automation · globalgrid2050 / automation/pipeline_release/new_version.py lines 1–177
- Runner Template automation · globalgrid2050 / automation/pipeline_release/runner_template.sh lines 1–88
Feature Contracts
A Python module in the pipeline release folder of GlobalGrid2050 that fetches ticker, official projects, project groups and selection audit, using SHA-256.
automationglobalgrid2050 / automation/pipeline_release/feature_contracts.py · lines 1–349 of 349 · pattern handle_starttag (shared by 13 files)
- What it does
- It fetches ticker, official projects, project groups and selection audit. Defines 10 functions or classes, including _ticker_neon, _global_dc_ui, semantic, _Scripts, __init__. Uses libraries json, hashlib, re, html.parser. Side effects: changes the web page (DOM); makes network requests.
- 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 ticker.v940.json; JSON file projects.json; JSON file official-projects.json; JSON file project-groups.json; JSON file selection-audit.json; JSON file pipeline_headlines.snapshot.json; JSON file priority.json; CSV file priority.csv.
- Downstream impact
- Used directly by 5 files: Test Release Feature Migrations (globalgrid2050); New Version (globalgrid2050); Verify (globalgrid2050); Test Migration (globalgrid2050); and 1 more. Reached from 15 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 checks features (`check_features`) and is built from the semantic step (`semantic`) and the handle starttag helper (`handle_starttag`). Inherited features, including explicit, executable presentation migrations. It reads `../202611161630/global-datacentres/projects.json`.
- Why it matters
- Imported by New Version and Verify. Checked by 3 tests, including Test Release Feature Migrations.
- Application
- globalgrid2050 · automation/pipeline_release · Python module
- Uses
- Automation — Pipeline Release (import), json, hashlib, re, html.parser
- Used by
- imported by Test Release Feature Migrations (sys.path import), imported by New Version (import), imported by Verify (import), imported by Test Migration (sys.path import), imported by Test Migration Origins (sys.path import)
- Produces
- check_features
- Defines here
- _ticker_neon, _global_dc_ui, semantic, _Scripts, __init__, handle_starttag, _news_internal, _research_internal, _solar_inline, check_features
- 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/feature_contracts.py:1-349 · blob a05027fd77c99cbefcea5b15fecf12023738ac16 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Inherited features, including explicit, executable presentation migrations.
Migration contracts are code-reviewed validators, not aliases for missing strings.
An unknown contract fails. The original release's marker remains independently
checked; only descendants declaring this migration use its stronger contract.
"""
import json
import hashlib
import re
from html.parser import HTMLParser
from common import data_digest
SOLAR_MIGRATION = {"id": "solar1000-pilot", "from": "202611161244", "contract": "solar1000-inline-v1"}
NEWS_MIGRATION = {"id": "news-editorial-priority", "from": "202611161734", "contract": "news-priority-internal-v1"}
GLOBAL_DC_MIGRATION = {"id": "global-dc-tab", "from": "202611161630", "contract": "global-dc-ui-v928-v1"}
RESEARCH_MIGRATIONS = [
{"id": feature, "from": "202611161747", "contract": "research-priority-internal-v1"}
for feature in ("inline-research-priority", "source-bound-priority")
]
NEON_MIGRATIONS = [{"id": feature, "from": "202611171507", "contract": "ticker-neon-v940-v1"}
for feature in ("v936-ticker-contract", "v936-ticker-bounded-static")]
KNOWN_MIGRATIONS = [SOLAR_MIGRATION, NEWS_MIGRATION, *RESEARCH_MIGRATIONS, GLOBAL_DC_MIGRATION, *NEON_MIGRATIONS]
MIGRATION_FLAGS = {
"solar1000-inline-v1": [SOLAR_MIGRATION],
"news-priority-internal-v1": [NEWS_MIGRATION],
"research-priority-internal-v1": RESEARCH_MIGRATIONS,
"global-dc-ui-v928-v1": [GLOBAL_DC_MIGRATION],
"ticker-neon-v940-v1": NEON_MIGRATIONS,
}
def _ticker_neon(folder, source):
"""Explicit owner presentation replacement; historical static feature stays intact."""
failures = []
contract = json.loads((folder / "contracts/ticker.v940.json").read_text(encoding="utf-8"))
if contract.get("schema") != "globalgrid2050.neon-headline-ticker.v940" or contract.get("limit") != 100:
failures.append("invalid moving ticker contract")
shared = folder.parents[1] / "automation/ticker_neon_ui/20261117-v940"
hashes = contract.get("shared_sha256", {})
if set(hashes) != {"ticker.mjs", "header.mjs", "styles.css"}:
failures.append("incomplete shared successor pins")
for name, digest in hashes.items():
if name not in {"ticker.mjs", "header.mjs", "styles.css"} or hashlib.sha256((shared / name).read_bytes()).hexdigest() != digest:
failures.append("changed shared ticker/header bytes")
if data_digest(folder) != data_digest(source) or (folder / "scripts/layers/model.mjs").read_bytes() != (source / "scripts/layers/model.mjs").read_bytes():
failures.append("changed inherited source data or headline selection policy")
binding = "import {latestHeadlines} from './model.mjs';\nimport {createTickerRenderer} from '../../../../automation/ticker_neon_ui/20261117-v940/ticker.mjs';\nexport const renderTicker=createTickerRenderer(latestHeadlines);\n"
if (folder / "scripts/layers/ticker.mjs").read_text(encoding="utf-8") != binding:
failures.append("missing shared ticker binding")
probe = "(()=>{const t=document.querySelector('#headlineTicker'),q=document.querySelector('.pn-news-header-search input'),c=t?.querySelector('.pn-ticker-copy');return !!q&&q.closest('.masthead')&&t.querySelectorAll('input,button').length===0&&t.querySelectorAll('ul').length===1&&!!c&&c.hasAttribute('inert')&&c.getAttribute('aria-hidden')==='true'&&c.querySelectorAll('a,[tabindex]').length===0; … [line shortened here: 405 characters; full line on GitHub]
return failures, [{"name": "V9.40 singular main header query and one semantic ticker list", "selector": "#headlineTicker", "js": probe}]
INTERNAL_PRIORITY_IDS = {NEWS_MIGRATION["id"], *(m["id"] for m in RESEARCH_MIGRATIONS)}
DC_PINS = {
"projects.json": "faf617d9979151b7d309554cb1cd59d343f70b9d60616f90db45e5c2a227d449",
"official-projects.json": "bcf6473bebe78e7a7dab566b1998ea51237d653c5a8584420690c2cea9a5180f",
"project-groups.json": "b77afd5846a3c27697e49664fabb4c0020a81a88ccaa680fb5130f6d6d1b8970",
"selection-audit.json": "faa79b4651d62baee822b8e6f748e447d0b8aebbe1c8c13beafd81d973b1c592",
}
def _global_dc_ui(folder, source):
failures = []
for name, digest in DC_PINS.items():
if hashlib.sha256((folder / "global-datacentres" / name).read_bytes()).hexdigest() != digest:
failures.append(f"changed accepted 100-lead recovery input: {name}")
projects = json.loads((folder / "global-datacentres/projects.json").read_text(encoding="utf-8"))
original = json.loads((source / "global-datacentres/projects.json").read_text(encoding="utf-8"))
rows, baseline = projects["records"], original["records"]
by_id = {row["id"]: row for row in rows}
if len(rows) != 100 or len(by_id) != 100 or len(baseline) != 12:
failures.append("invalid recovered/original Data Centre populations")
def semantic(row):
value = json.loads(json.dumps(row))
value["source"].pop("retrieved_at", None)
return value
if any(row["id"] not in by_id or semantic(by_id[row["id"]]) != semantic(row) for row in baseline):
failures.append("lost original 12 Data Centre semantic identities")
if (sum(row["country"]["code"] == "GB" for row in rows) != 54
or any(row["operating_status"] != "not_assessed" or row["verification_status"] != "SOURCE_INDEXED"
or any(value is not None for value in row["capacity"].values()) for row in rows)):
failures.append("unsupported Data Centre operation/capacity or changed UK population")
if data_digest(folder) != data_digest(source):
failures.append("official REPD data changed by Data Centre presentation migration")
html = _Scripts((folder / "index.html").read_text(encoding="utf-8"))
if not {"datacentreTab", "datacentrePanel", "datacentreHost"} <= html.ids:
failures.append("missing consolidated Data Centre tab/host")
for script in ("../../automation/news/datacentre-ui/model.js", "../../automation/news/datacentre-ui/view.js",
"scripts/plugins/preview-v928.js"):
if script not in html.sources:
failures.append(f"missing Data Centre dependency wiring: {script}")
host = (folder / "scripts/plugins/preview-v928.js").read_text(encoding="utf-8")
if any(marker not in host for marker in ("!dcStarted", "GGDataCentreUI.mount", "dcInputs", "datacentreHost")):
failures.append("missing lazy integrity-pinned host implementation")
if "scripts/plugins/global-datacentres-v925.js" in html.sources:
failures.append("old competing Data Centre renderer still wired")
probe = {"name": "Data Centre migration: actual lazy tab, original source states and no extra principal panel",
"selector": "body", "js": """(async () => {
const host=document.querySelector('#datacentreHost'),tab=document.querySelector('#datacentreTab');
if(!host||!tab||!window.GGDataCentreModel?.validateBundle)return false;
const previous=document.querySelector('#officialRegister [role=tab][aria-selected=true]');
try{
tab.click();const stop=performance.now()+6000;
while(host.querySelectorAll('.ggdc-table tbody tr').length!==54&&performance.now()<stop)await new Promise(r=>setTimeout(r,25));
if(host.querySelectorAll('.ggdc-table tbody tr').length!==54||document.querySelectorAll('main>section').length!==2)return false;
const global=[...host.querySelectorAll('button')].find(n=>n.textContent==='Global leads (100)');
if(!global)return false;global.click();
if(host.querySelectorAll('.ggdc-table tbody tr').length!==100||!host.innerText.includes('not assessed'))return false;
const paths=['projects.json','official-projects.json','project-groups.json','selection-audit.json'];
const docs=await Promise.all(paths.map(async path=>{const r=await fetch('global-datacentres/'+path);if(!r.ok)throw Error('Data Centre input absent');return r.json();}));
const baseline=await fetch('../202611161630/global-datacentres/projects.json').then(r=>r.json());
const bundle={projects:docs[0],official:docs[1],groups:docs[2],audit:docs[3],baseline};
GGDataCentreModel.validateBundle(bundle);
const forged=structuredClone(bundle);forged.projects.records[0].capacity.it_load_mw=100;
let rejected=false;try{GGDataCentreModel.validateBundle(forged);}catch{rejected=true;}
return rejected&&docs[0].records.length===100&&baseline.records.length===12&&docs[3].quarantined.length===38
&&docs[0].records.every(r=>r.operating_status==='not_assessed'&&Object.values(r.capacity).every(v=>v===null));
}finally{const uk=[...host.querySelectorAll('button')].find(n=>n.textContent==='UK leads (54)');uk?.click();previous?.click();}
})()"""}
return failures, [probe]
class _Scripts(HTMLParser):
def __init__(self, html):
super().__init__()
self.sources, self.ids = [], set()
self.feed(html)
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if "id" in attrs:
self.ids.add(attrs["id"])
if tag == "script" and isinstance(attrs.get("src"), str):
self.sources.append(attrs["src"].split("?", 1)[0])
def _news_internal(folder, source):
failures = []
if data_digest(folder) != data_digest(source):
failures.append("official data changed from internal-news migration source")
html = _Scripts((folder / "index.html").read_text(encoding="utf-8"))
plugin = (folder / "scripts/plugins/live-news.js").read_text(encoding="utf-8")
original = (source / "scripts/plugins/live-news.js").read_text(encoding="utf-8")
if "scripts/plugins/live-news.js" not in html.sources:
failures.append("source-attributed headline renderer is not wired")
# Retain the exact cryptographic envelope validator while presentation may
# change. A schema string alone cannot stand in for the accepted algorithm.
pattern = r"async function validatePriority\(.*?(?=\n function when\()"
before, after = re.search(pattern, original, re.S), re.search(pattern, plugin, re.S)
if before is None or after is None or before.group() != after.group():
failures.append("exact-input priority validation was changed or removed")
for marker in ("globalgrid2050.news.headline-priority.v1", "priorities.get(doc)",
"validatePriority(doc, bytes", "item.source", "safeLink(item.link)"):
if marker not in plugin:
failures.append(f"missing internal headline implementation: {marker}")
snapshot = json.loads((folder / "news/pipeline_headlines.snapshot.json").read_text(encoding="utf-8"))
if (not isinstance(snapshot, dict) or snapshot.get("schema") != "globalgrid2050.news.pipeline-headlines.v1"
or not isinstance(snapshot.get("items"), list)
or any(not isinstance(item, dict) or not all(isinstance(item.get(k), str) and item[k] for k in ("title", "source", "link"))
for item in snapshot.get("items", []))):
failures.append("headline snapshot lost original source/title/link provenance")
# This is an explicitly synthetic renderer/sidecar test, not source evidence.
probe = {"name": "Internal headline priority: reject forged receipts, retain ranked attribution without visible scores",
"selector": "body", "js": """(async () => {
const p=window.pipelineHeadlines, original=window.pipelineHeadlineDocument;
if(!p?.validatePriority||!p?.render)return false;
const now=Date.now(),stamp=new Date(now).toISOString();
const items=[{title:'Synthetic older ranked headline',source:'Synthetic source A',link:'https://example.org/v928-a',date:new Date(now-86400000).toISOString(),first_seen:stamp},
{title:'Synthetic newer headline',source:'Synthetic source B',link:'https://example.org/v928-b',date:stamp,first_seen:stamp}];
const doc={schema:p.schema,generated_at:stamp,status:'ok',items,counts:{feeds_ok:2,feeds_failed:0}};
const bytes=new TextEncoder().encode(JSON.stringify(doc));
const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),v=>v.toString(16).padStart(2,'0')).join('');
const side={schema:p.prioritySchema,input_sha256:hash,input_bytes:bytes.byteLength,input_generated_at:stamp,input_count:2,as_of:stamp,
profile_id:'uk-transition-global-context.v1',profile_sha256:'06250f2435088a522d8d25676f31f813165a430df1e19f602bd8baae03961c05',
entries:items.map((v,i)=>({...v,rank:i+1,source_kind:'government',role:'primary_context',topics:['solar'],freshness_state:'current',uk_context:true,score:99-i,requires_primary_followup:false,subscription_notice:false}))};
side.entries=side.entries.map(({date,first_seen,...entry})=>entry);
try{
const bad=structuredClone(side);bad.input_sha256='0'.repeat(64);
if(await p.validatePriority(doc,bytes,bad))return false;
const forged=structuredClone(side);forged.entries[0].source='Forged attribution';
if(await p.validatePriority(doc,bytes,forged))return false;
if(!await p.validatePriority(doc,bytes,side))return false;
p.render(doc,'live',now);
const rows=[...document.querySelectorAll('#liveNews .ln-item')];
const visible=n=>getComputedStyle(n).display!=='none'&&getComputedStyle(n).visibility!=='hidden'&&n.getBoundingClientRect().width>0;
return rows.length===2&&rows.every((r,i)=>r.querySelector('.ln-title')?.href===items[i].link&&r.querySelector('.ln-title')?.textContent===items[i].title&&r.querySelector('.ln-meta')?.textContent.includes(items[i].source))
&&document.querySelector('#newsStatus')?.dataset.order==='priority'&&![...document.querySelectorAll('#liveNews .ln-priority')].some(visible)
&&!/\\bPriority\\s+\\d/.test(document.querySelector('#liveNews')?.innerText||'');
}finally{p.render(original,'snapshot');}
})()"""}
return failures, [probe]
def _research_internal(folder, source):
failures = []
if data_digest(folder) != data_digest(source):
failures.append("official data changed from internal-research migration source")
preserved = ("prospecting/manifest.json", "prospecting/priority.json", "prospecting/priority.csv",
"scripts/plugins/research-priority-v927.js", "scripts/plugins/prospecting/adapter.mjs",
"scripts/plugins/prospecting/bundle.mjs", "scripts/plugins/prospecting/view.mjs")
for relative in preserved:
if (folder / relative).read_bytes() != (source / relative).read_bytes():
failures.append(f"changed retained internal research artifact: {relative}")
manifest_bytes = (folder / "prospecting/manifest.json").read_bytes()
manifest = json.loads(manifest_bytes)
if not isinstance(manifest, dict):
return failures + ["invalid retained research manifest"], []
if (manifest.get("schema") != "globalgrid2050.prospecting.export.v1"
or manifest.get("publication_state") != "REVIEW_ARTIFACT"
or [manifest.get(k) for k in ("official_count", "solar_count", "solar1000_count")] != [7775, 3604, 1000]):
failures.append("retained research provenance/population state changed")
for name in ("priority.json", "priority.csv"):
raw = (folder / "prospecting" / name).read_bytes()
pin = manifest["files"][name]
if pin["bytes"] != len(raw) or pin["sha256"] != hashlib.sha256(raw).hexdigest():
failures.append(f"retained research receipt differs: {name}")
html = _Scripts((folder / "index.html").read_text(encoding="utf-8"))
if "researchPriorityStatus" in html.ids or "scripts/plugins/research-priority-v927.js" in html.sources:
failures.append("withdrawn research-score presentation is still wired")
digest = hashlib.sha256(manifest_bytes).hexdigest()
probe = {"name": "Internal research priority: execute retained pinned parser without public score presentation",
"selector": "body", "js": """(async () => {
const visible=n=>getComputedStyle(n).display!=='none'&&getComputedStyle(n).visibility!=='hidden'&&n.getBoundingClientRect().width>0;
if([...document.querySelectorAll('.v927-priority-hint,[data-priority-id],#researchPriorityStatus')].some(visible))return false;
const [m,p]=await Promise.all(['prospecting/manifest.json','prospecting/priority.json'].map(async path=>{const r=await fetch(path);if(!r.ok)throw Error('retained research unavailable');return new Uint8Array(await r.arrayBuffer());}));
const parser=await import(new URL('scripts/plugins/prospecting/bundle.mjs',location.href).href);
const bundle=await parser.parsePriorityBundle(p,m,""" + json.dumps(digest) + """);
return bundle.members.size===7775&&bundle.byId.size===1000&&bundle.manifest.solar1000_count===1000
&&bundle.manifest.publication_state==='REVIEW_ARTIFACT'&&document.querySelector('#tbody')?.dataset.complete==='true'
&&![...document.querySelectorAll('.v927-priority-hint,[data-priority-id],#researchPriorityStatus')].some(visible);
})()"""}
return failures, [probe]
def _solar_inline(folder, source):
failures, probes = [], []
for relative in ("solar1000/manifest.json", "solar1000/candidates.json"):
if (folder / relative).read_bytes() != (source / relative).read_bytes():
failures.append(f"changed frozen {relative}")
manifest = json.loads((folder / "solar1000/manifest.json").read_text(encoding="utf-8"))
ids = manifest.get("ids", [])
if (len(ids) != 1000 or any(not isinstance(i, str) or not i.isascii() or not i.isdecimal() for i in ids)
or len(set(ids)) != 1000 or sorted(ids, key=int) != ids
or manifest.get("selection") != "numeric-repd-ref-ascending"
or manifest.get("selection_count") != 1000 or manifest.get("record_count") != 7775
or manifest.get("independently_verified") != 0):
failures.append("invalid frozen Solar-1000 membership/order/counts")
candidates = json.loads((folder / "solar1000/candidates.json").read_text(encoding="utf-8"))
if len(candidates) != 2 or any(c.get("repd_ref") not in ids for c in candidates):
failures.append("invalid inherited source candidates")
if data_digest(folder) != data_digest(source):
failures.append("official data changed from migration source")
html = (folder / "index.html").read_text(encoding="utf-8")
plugin = (folder / "scripts/plugins/solar1000-v924.js").read_text(encoding="utf-8")
for marker in ('id="evidenceCoverage"', 'data-evidence-selection', 'data-evidence-status',
'src="scripts/plugins/solar1000-v924.js'):
if marker not in html:
failures.append(f"missing inline wiring: {marker}")
for marker in ("solar1000/manifest.json", "solar1000/candidates.json", "pipeline-projects-rendered",
".project-record", "integratedEvidence", "renderEvidence"):
if marker not in plugin:
failures.append(f"missing inline implementation: {marker}")
# Runtime probes prove the retained sources are reachable inside the existing
# project records; static marker checks alone cannot establish this migration.
probes.append({"name": "Solar-1000 migration: unchanged selection in consolidated register", "selector": "body",
"js": "document.querySelector('#evidenceCoverage')?.dataset.selectionCount==='1000' && !document.querySelector('#solar1000Pilot') && document.querySelector('#tbody')?.dataset.complete==='true'"})
for candidate in candidates:
ref, url = candidate["repd_ref"], candidate["source_url"]
probes.append({"name": f"Solar-1000 migration: inherited source inside project {ref}", "search": ref,
"row": f"repd-{ref}", "selector": ".project-record",
"js": "(() => {const d=document.querySelector(" + json.dumps(f"#repd-{ref} .project-record") + ");"
"if(!d)return false;d.open=true;const h=d.querySelector('[data-integrated-evidence]');"
"const e=h?.querySelector('[data-evidence-project]');const a=h?.querySelector('.v925-inherited-source a');"
"return !!h&&!!e&&h.dataset.integratedEvidence===" + json.dumps(ref) +
"&&e.dataset.evidenceProject===" + json.dumps(ref) + "&&a?.href===" + json.dumps(url) +
"&&a.getBoundingClientRect().width>0&&h.textContent.includes('unverified')&&d.open;})()"})
return failures, probes
def check_features(version, by_id, pipeline):
"""Return the offline verdict and mandatory browser probes for migrations."""
inherited, dropped, migrations, errors = [], set(), {}, []
node, visited = version, set()
while node:
if node["id"] in visited:
errors.append("cyclic feature ancestry")
break
visited.add(node["id"])
dropped |= set(node.get("removed_features", []))
inherited = [(f, node["id"]) for f in node["features"] if f["id"] not in dropped] + inherited
local_migration_ids = set()
for migration in node.get("feature_migrations", []):
if not isinstance(migration, dict) or migration not in KNOWN_MIGRATIONS:
errors.append("unknown feature migration contract")
continue
if migration["id"] in local_migration_ids:
errors.append("duplicate feature migration")
local_migration_ids.add(migration["id"])
# A descendant may explicitly restate the same audited contract;
# duplicates within one declaration remain invalid.
if migration["id"] in migrations and migrations[migration["id"]] != migration:
errors.append("conflicting inherited feature migration")
migrations.setdefault(migration["id"], migration)
node = by_id.get(node["parent"])
if dropped & INTERNAL_PRIORITY_IDS:
errors.append("internal priority features require an audited migration, not removal")
folder = pipeline / version["id"]
missing, receipts, probes = [], [], []
for feature_id, migration in migrations.items():
declarations = [(feature, origin) for feature, origin in inherited if feature["id"] == feature_id]
origins = [origin for _, origin in declarations]
origin_valid = origins == [migration["from"]]
if migration in NEON_MIGRATIONS:
# V9.37-39 repeat the original V9.36 feature records verbatim.
# Admit only those identical restatements, with one original source
# and no duplicate identity inside any edition. Other migrations
# retain their original exact single-source requirement.
origin_valid = (bool(origins) and origins[0] == migration["from"]
and len(set(origins)) == len(origins)
and all(feature == declarations[0][0] for feature, _ in declarations))
faults = []
if not origin_valid or feature_id in dropped or version["id"] == migration["from"]:
faults.append("migration must preserve its exact inherited feature and source")
else:
try:
validator = {"solar1000-inline-v1": _solar_inline,
"news-priority-internal-v1": _news_internal,
"research-priority-internal-v1": _research_internal,
"global-dc-ui-v928-v1": _global_dc_ui,
"ticker-neon-v940-v1": _ticker_neon}[migration["contract"]]
faults, runtime = validator(folder, pipeline / migration["from"])
probes.extend(runtime)
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
# Paths may be private locally; public verdicts contain no exception path.
faults = [f"invalid or unavailable migration input ({type(exc).__name__})"]
receipts.append(dict(migration, **{"pass": not faults, "failures": faults}))
if faults:
missing.append(feature_id)
for feature, _ in inherited:
if feature["id"] in migrations:
continue
path = folder / feature["file"]
if not path.is_file() or feature["contains"] not in path.read_text(encoding="utf-8", errors="replace"):
missing.append(feature["id"])
probes = list({probe["name"]: probe for probe in probes}.values())
return {"pass": not missing and not errors, "features": [f["id"] for f, _ in inherited],
"missing": missing, "withdrawn_on_purpose": sorted(dropped),
"migrations": receipts, "errors": errors}, probesNew Version
A Python command-line tool in the pipeline release folder of GlobalGrid2050 that reads the Renewable Energy Planning Database (REPD) register from the GridAtlas repository.
automationglobalgrid2050 / automation/pipeline_release/new_version.py · lines 1–177 of 177 · Entry point · pattern finalize (shared by 4 files)
- What it does
- It loads the REPD register. Defines write_text, num, migration_records, create, finalize. Uses libraries re, shutil, sys, datetime. 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: data source: gridatlas data; command-line arguments.
- Downstream impact
- Used directly by 4 files: Test Release Audit (globalgrid2050); Test Release Feature Migrations (globalgrid2050); Test Compact Successor (globalgrid2050); Repair (globalgrid2050). Reached from 8 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V923 Six Hour Python Repair Workflow (globalgrid2050).
- What it achieves
- It writes text (`write_text`) and is built from the num step (`num`) and the migration records helper (`migration_records`). Start and finish a Pipeline News version by the existing pattern. Its code works with 1 MW. It writes `index.html`.
- Why it matters
- Run by Repair. Checked by 3 tests, including Test Release Audit.
- Application
- globalgrid2050 · automation/pipeline_release · Python CLI
- Uses
- Automation — Pipeline Release (import), Feature Contracts (import), GridAtlas — Atlas Page (estate URL), re, shutil, sys, datetime
- Used by
- imported by Test Release Audit (sys.path import), imported by Test Release Feature Migrations (sys.path import), imported by Test Compact Successor (sys.path import), run by Repair (script call)
- Produces
- write_text, num, migration_records, create, finalize
- Defines here
- write_text, num, migration_records, create, finalize
- 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/new_version.py:1-177 · blob 97e3983b6034651fce61825aaae7c0bd57cd42f3 · 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
"""Start and finish a Pipeline News version by the existing pattern.
new_version.py create <new id> <V9.NN> "<short title>" ["RELEASE CANDIDATE"] [--dry-run]
copies the newest registered version to uk_renewables_pipeline/<new id>/, relabels
index.html, README.md and the check script, and writes tests/run_v9_NN.sh pinned
to the parent's tree hash. Then edit the new folder.
new_version.py finalize <new id> "<what it added>" [--fault "<known fault>"]... [--feature id:file:marker]... [--migrate-feature <audited-contract>]... [--state release_candidate_publication_blocked]
lists every changed, new and removed file in the runner, and records the version
(tree hash, features, faults) in registry.json. Only an unpublished candidate
at the registry tail may be re-finalized; published records are immutable.
Audited contracts: solar1000-inline-v1, news-priority-internal-v1,
research-priority-internal-v1 and global-dc-ui-v928-v1. Each flag occurs
once; research expands to both exact inherited V9.27 feature identities.
Published folders are never edited: create only ever writes a new folder.
"""
import re
import shutil
import sys
from datetime import datetime, timezone
from common import PIPELINE, HERE, load_registry, save_registry, tree_hash, walk
from feature_contracts import SOLAR_MIGRATION, KNOWN_MIGRATIONS, MIGRATION_FLAGS
RUNNER_TEMPLATE = (HERE / "runner_template.sh").read_text(encoding="utf-8")
def write_text(path, text):
path.write_text(text, encoding="utf-8", newline="\n")
def num(version): # "V9.14" -> "9_14"
return version.lstrip("V").replace(".", "_")
def migration_records(flags):
"""Expand explicit audited flags; reject unknown/repeated features."""
records = []
for flag in flags:
if flag not in MIGRATION_FLAGS:
raise ValueError("Unknown or duplicate feature migration")
incoming = MIGRATION_FLAGS[flag]
if any(m["id"] in {old["id"] for old in records} for m in incoming):
raise ValueError("Unknown or duplicate feature migration")
records.extend(dict(m) for m in incoming)
return records
def create(new_id, version, title, state="BUILD", dry_run=False):
reg = load_registry()
parent = reg["versions"][-1]
src, dst = PIPELINE / parent["id"], PIPELINE / new_id
assert re.fullmatch(r"\d{12}", new_id) and not dst.exists(), "new id must be an unused 12-digit UTC stamp"
print(f"parent: {parent['id']} ({parent['version']})")
if dry_run:
print(f"dry-run: would create {dst} as {version}; no files written")
return
shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__", "node_modules", "*.pyc"))
pv, nv = parent["version"], version
(dst / parent["runner"]).unlink()
old_check = dst / f"tests/check_v{num(pv)}.mjs"
check_template = HERE / "check_template.mjs"
old_check.unlink()
check = check_template.read_text(encoding="utf-8").replace("@VERSION@", nv.lstrip("V")).replace("@PARENT_ID@", parent["id"]).replace("@FIXTURE_OWNER@", reg["fixture_owner"]).replace("@NUM@", num(nv)).replace("@STATE@", state)
write_text(dst / f"tests/check_v{num(nv)}.mjs", check)
runner = (RUNNER_TEMPLATE.replace("@NUM@", num(nv)).replace("@VERSION@", nv).replace("@PARENT_ID@", parent["id"])
.replace("@PARENT_TREE@", tree_hash(parent["id"])).replace("@FIXTURE_OWNER@", reg["fixture_owner"]))
path = dst / f"tests/run_v{num(nv)}.sh"
write_text(path, runner)
path.chmod(0o755)
day = datetime.now(timezone.utc).strftime("%d %B %Y").lstrip("0")
html = (dst / "index.html").read_text(encoding="utf-8")
compact = f'data-edition="{parent["id"]}"' in html
html = html.replace(f"UK Renewables Pipeline {parent['id']}</title>", f"UK Renewables Pipeline {new_id}</title>")
html = html.replace(f"<small>UK RENEWABLES PIPELINE · {pv}</small>", f"<small>UK RENEWABLES PIPELINE · {nv}</small>")
if compact:
html = html.replace(f"Pipeline News {pv} · {parent['id']}</title>", f"Pipeline News {nv} · {new_id}</title>")
html = html.replace(f"<small>PIPELINE NEWS · {pv}</small>", f"<small>PIPELINE NEWS · {nv}</small>")
html = html.replace(f'data-edition="{parent["id"]}"', f'data-edition="{new_id}"')
html, stamp_count = re.subn(r'(<p class="preview-status"[^>]*>)[^<]*(</p>)',
lambda m: f'{m[1]}{nv} · {day.upper()} · REPD OCTOBER 2026 · Source dates and provisional research states retained{m[2]}', html, count=1)
assert stamp_count == 1, "compact edition stamp not found"
active_label = f"{nv} · PIPELINE NEWS" if compact else f"{nv} {state} · REPD Q3 2026"
if compact and '<nav class="release-links"' in html:
# Keep the owner's replacement header bounded as further editions arrive.
links = [f'<a class="active" href="#" aria-current="page">{active_label}</a>',
'<a href="../versions.html">ALL VERSIONS · CI VERDICTS</a>',
f'<a href="../{parent["id"]}/">{pv} · PREVIOUS EDITION</a>',
'<a href="https://ventusltd.github.io/gridatlas/atlas/" id="mapAtlasNav">MAP ATLAS</a>',
'<a href="#" id="export">EXPORT CSV</a>', '<a href="../../index.html">DIRECTORY</a>']
html, n = re.subn(r'(<nav class="release-links"[^>]*>).*?(</nav>)',
lambda m: m[1] + "\n " + "\n ".join(links) + "\n " + m[2], html, count=1, flags=re.S)
else:
html, n = re.subn(r'<a class="active" href="#"(?: aria-current="page")?>[^<]*</a>\n(\s*)(<a href="\.\./versions\.html">[^<]*</a>\n\s*)?',
lambda m: f'<a class="active" href="#">{active_label}</a>\n{m.group(1)}<a href="../versions.html">ALL VERSIONS · CI VERDICTS</a>\n{m.group(1)}<a href="../{parent["id"]}/">{pv} {parent["id"]} · REPD Q3 2026</a>\n{m.group(1)}', html, count=1)
assert n == 1, "nav active link not found"
html = html.replace(f"<h1>UK RENEWABLES PIPELINE {parent['id']}</h1>", f"<h1>UK RENEWABLES PIPELINE {new_id}</h1>")
html, n = re.subn(r"<strong>V9\.\d+ · [^<]*</strong>", f"<strong>{nv} · REPD OCTOBER 2026 (Q3) · {title.upper()} · {state} · {day}</strong>", html, count=1)
assert compact or n == 1, "meta line not found"
write_text(dst / "index.html", html)
write_text(dst / "README.md",
f"# GlobalGrid2050 UK Renewables Pipeline {new_id} ({nv})\n\n"
f"{state.capitalize()} dated {day}. Parent: `{parent['id']}` ({pv}). The register is the REPD October 2026 (Q3 2026) release, unchanged: "
f"7,775 solar, battery and wind records at 1 MW and above, keyed by REPD Ref ID.\n\n"
f"This build: {title}. See `CHANGES.md` for what changed and any known fault.\n\n"
f"Validate offline from a checkout of the repository:\n\n bash tests/run_v{num(nv)}.sh\n\n"
f"All versions, with their automated verdicts: `../versions.html`.\n")
write_text(dst / "CHANGES.md", f"# {new_id} ({nv})\n\nParent: `{parent['id']}` ({pv}), tree `{tree_hash(parent['id'])}`.\n\nCandidate initialized; see final change report before publication.\n")
print(f"created {dst} from {parent['id']}")
def finalize(new_id, added, faults, features, state="published", feature_migrations=None):
reg = load_registry()
parent = reg["versions"][-1]
registered = [entry for entry in reg["versions"] if entry["id"] == new_id]
assert not registered or (len(registered) == 1 and parent["id"] == new_id), "already registered; historical records cannot be rewritten"
if feature_migrations is None:
feature_migrations = parent.get("feature_migrations", []) if parent["id"] == new_id else []
assert isinstance(feature_migrations, list) and all(
migration in KNOWN_MIGRATIONS for migration in feature_migrations), "unknown feature migration"
assert len({migration["id"] for migration in feature_migrations}) == len(feature_migrations), "duplicate feature migration"
if parent["id"] == new_id:
assert parent.get("state", "").startswith("release_candidate_") and state.startswith("release_candidate_"), "already registered; published records cannot be rewritten"
reg["versions"].pop()
parent = reg["versions"][-1]
src, dst = PIPELINE / parent["id"], PIPELINE / new_id
old, new = set(walk(src)), set(walk(dst))
changed = sorted(p for p in new if p not in old or (src / p).read_bytes() != (dst / p).read_bytes())
removed = sorted(old - new)
runner = next(p for p in changed if re.fullmatch(r"tests/run_v9_\d+\.sh", p))
text = (dst / runner).read_text(encoding="utf-8")
block = lambda name, items: f"{name}=(\n" + "".join(f" {i}\n" for i in items) + ")"
text = re.sub(r"CHANGED_FROM_PARENT=\(\n.*?\n?\)", block("CHANGED_FROM_PARENT", changed), text, count=1, flags=re.S)
text = re.sub(r"REMOVED_FROM_PARENT=\(\n.*?\n?\)", block("REMOVED_FROM_PARENT", removed), text, count=1, flags=re.S)
write_text(dst / runner, text)
version = "V" + re.search(r"run_v(9_\d+)\.sh", runner).group(1).replace("_", ".")
reg["versions"].append({
"id": new_id, "version": version, "parent": parent["id"],
"date": datetime.strptime(new_id, "%Y%m%d%H%M").replace(tzinfo=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"added": added, "data_changed": False, "runner": runner, "trees": [tree_hash(new_id)],
"features": [dict(zip(("id", "file", "contains"), f.split(":", 2))) for f in features],
"known_faults": faults, "ci": None, "merge_commit": None, "state": state,
**({"feature_migrations": feature_migrations} if feature_migrations else {}),
})
save_registry(reg)
print(f"finalized {new_id}: {len(changed)} changed or new, {len(removed)} removed, tree {reg['versions'][-1]['trees'][0]}")
if __name__ == "__main__":
args = sys.argv[1:]
dry_run = "--dry-run" in args
if dry_run:
args.remove("--dry-run")
if args[:1] == ["create"] and len(args) in (4, 5):
create(*args[1:], dry_run=dry_run)
elif args[:1] == ["finalize"] and len(args) >= 3 and not dry_run:
rest, faults, features = args[3:], [], []
state, migrations, migration_flags = "published", None, []
while rest:
if len(rest) < 2 or rest[0] not in {"--fault", "--feature", "--state", "--migrate-feature"}:
sys.exit("Expected --fault, --feature, --state or --migrate-feature and value")
flag, value, rest = rest[0], rest[1], rest[2:]
if flag == "--state":
state = value
elif flag == "--migrate-feature":
migration_flags.append(value)
try:
migrations = migration_records(migration_flags)
except ValueError as exc:
sys.exit(str(exc))
else:
(faults if flag == "--fault" else features).append(value)
finalize(args[1], args[2], faults, features, state=state, feature_migrations=migrations)
else:
sys.exit(__doc__)Runner Template
A shell script in the pipeline release folder of GlobalGrid2050 covering interconnectors.
Set aside from the main view: A comment at the top of the file says a tool wrote it. (noise-generated, proposed by noise.py). All set-aside files, with reasons. Nothing was deleted.
Evidence
- line 4 comment: # Written by automation/pipeline_release/new_version.py by the pattern of run_v9_13.sh.
automationglobalgrid2050 / automation/pipeline_release/runner_template.sh · lines 1–88 of 88 · Entry point · pattern is_listed (shared by 38 files)
- What it does
- Defines is_listed, walk. 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. Domain terms in the code: interconnectors.
- Inputs & outputs
- In: JSON file release.v9.1.json; command-line arguments.
- Downstream impact
- It is itself an entry point (shell script); no other file was found loading it.
- What it achieves
- Defines `is_listed` and `walk`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · automation/pipeline_release · shell script
- Uses
- none found
- Used by
- none found
- Produces
- is_listed, walk
- Defines here
- is_listed, walk
- 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/runner_template.sh:1-88 · blob 366743eca56672d42f35247c54cc4fea91a4d8c8 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env bash
# run_v@NUM@.sh - Pipeline News @VERSION@: one visible step on its parent, same REPD
# October 2026 (Q3 2026) register. Offline, in a git checkout or a plain copy.
# Written by automation/pipeline_release/new_version.py by the pattern of run_v9_13.sh.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RELEASE="$(cd "$HERE/.." && pwd)"
ID="$(basename "$RELEASE")"
PARENT_ID="@PARENT_ID@"
FIXTURE_OWNER="@FIXTURE_OWNER@"
PARENT="$(cd "$RELEASE/../$PARENT_ID" && pwd)"
ROOT="$(cd "$RELEASE/../.." && pwd)"
# The parent by git tree of the bytes ON DISK.
PARENT_TREE="@PARENT_TREE@"
SCRATCH="$(mktemp -d)"
trap 'rm -rf "$SCRATCH"' EXIT
actual_tree="$(python - "$ROOT" "$PARENT_ID" <<'PYTREE'
import sys
sys.path.insert(0, sys.argv[1] + "/automation/pipeline_release")
from common import tree_hash
print(tree_hash(sys.argv[2]))
PYTREE
)"
test "$actual_tree" = "$PARENT_TREE" || { echo "parent $PARENT_ID tree is $actual_tree, expected $PARENT_TREE" >&2; exit 1; }
# WHAT THIS VERSION CHANGES FROM ITS PARENT, NAMED ONE FILE AT A TIME.
CHANGED_FROM_PARENT=(
)
REMOVED_FROM_PARENT=(
)
is_listed() {
local needle="$1"; shift
for entry in "$@"; do [[ "$entry" == "$needle" ]] && return 0; done
return 1
}
walk() { find "$1" -type f -not -path '*/__pycache__/*' -not -name '*.pyc' -not -path '*/node_modules/*' | sort; }
while IFS= read -r file; do
relative="${file#$PARENT/}"
is_listed "$relative" "${CHANGED_FROM_PARENT[@]}" && continue
if is_listed "$relative" "${REMOVED_FROM_PARENT[@]}"; then
test ! -e "$RELEASE/$relative" || { echo "should not be copied: $relative" >&2; exit 1; }
continue
fi
cmp -s "$file" "$RELEASE/$relative" || { echo "inherited file differs from parent: $relative" >&2; exit 1; }
done < <(walk "$PARENT")
while IFS= read -r file; do
relative="${file#$RELEASE/}"
is_listed "$relative" "${CHANGED_FROM_PARENT[@]}" && continue
test -e "$PARENT/$relative" || { echo "unlisted new file: $relative" >&2; exit 1; }
done < <(walk "$RELEASE")
for relative in "${CHANGED_FROM_PARENT[@]}"; do
test -f "$RELEASE/$relative" || { echo "listed but missing: $relative" >&2; exit 1; }
if [[ -f "$PARENT/$relative" ]] && cmp -s "$PARENT/$relative" "$RELEASE/$relative"; then
echo "listed as changed but identical to parent: $relative" >&2; exit 1
fi
done
# The register is the parent's: contract, spine and interconnector product byte for byte.
cmp -s "$PARENT/contracts/release.v9.1.json" "$RELEASE/contracts/release.v9.1.json"
grep -q "\"identity_fixture\": \"uk_renewables_pipeline/$FIXTURE_OWNER/fixtures/2026q3/project_identity_2026q3.json\"" "$RELEASE/contracts/release.v9.1.json"
diff -r "$PARENT/data/v9.1" "$RELEASE/data/v9.1"
diff -r "$PARENT/data/v9.8" "$RELEASE/data/v9.8"
# Spine and interconnector product rebuilt in a scratch root that holds this version
# and, at the fixture owner's path, only the two fixtures the contract binds. They
# must reproduce the committed bytes.
SROOT="$SCRATCH/root"
COPY="$SROOT/uk_renewables_pipeline/$ID"
mkdir -p "$SROOT/uk_renewables_pipeline/$FIXTURE_OWNER/fixtures"
cp -a "$ROOT/uk_renewables_pipeline/$FIXTURE_OWNER/fixtures/2026q3" "$SROOT/uk_renewables_pipeline/$FIXTURE_OWNER/fixtures/"
cp -a "$RELEASE" "$COPY"
rm -rf "$COPY/data/v9.1"
PYTHONDONTWRITEBYTECODE=1 python "$COPY/scripts/data/build_v9_1_spine.py"
diff -r "$RELEASE/data/v9.1" "$COPY/data/v9.1"
node "$COPY/scripts/build/interconnectors-v9-8.mjs" >/dev/null
diff -r "$RELEASE/data/v9.8" "$COPY/data/v9.8"
node "$HERE/check_v@NUM@.mjs"
node "$HERE/check_map_contract_all_rows.mjs"
while IFS= read -r source; do
node --check "$source"
done < <(find "$RELEASE/scripts" -type f \( -name '*.js' -o -name '*.mjs' \) -print | sort)
echo "@VERSION@ ($ID) validation suite: PASS ($ROOT)"