GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / testcode / backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts

GlobalGrid2050 Validate Project Identity V6 and 4 more files

A Python module in the scripts folder of Testcode that reads project identity integrity, major projects, major project news and project news links, using SHA-256.

547 lines of Python and YAML and JavaScript from testcode, in 5 files. Topic: Electricity markets and data pipelines. Section 1067 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. GlobalGrid2050 Build Project Identity V6 automation · testcode / backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts/build_project_identity_v6.py lines 442–588
  2. GlobalGrid2050 Validate Project Identity V6 automation · testcode / backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts/validate_project_identity_v6.py lines 1–236
  3. GlobalGrid2050 Validate V6 Manifest Provenance automation · testcode / backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts/validate_v6_manifest_provenance.py lines 1–76
  4. BBC RSS Discovery automation · testcode / backups/202611140229-pipelinenews-before-repd-2026q3/files/.github/workflows/bbc-rss-discovery.yml lines 1–55
  5. Reconcile Provisional storage · testcode / backups/202611140229-pipelinenews-before-repd-2026q3/files/tools/intelligence/reconcile-provisional.mjs lines 1–33

GlobalGrid2050 Build Project Identity V6

A Python command-line tool in the scripts folder of Testcode that reads major projects, the Renewable Energy Planning Database (REPD) register, solar and battery storage (BESS), using SHA-256.

automationtestcode / backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts/build_project_identity_v6.py · lines 442–588 of 588 · version 2026-11-14 00:31 (continued from section 1066) · Entry point · pattern build_public_snapshot (shared by 2 files)

What it does
It loads major projects, the REPD register, solar and battery storage (BESS). Defines 21 functions or classes, including clean, norm, numeric_sort, technology_category, lifecycle. Uses libraries __future__, csv, hashlib, io, json. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar, battery storage (BESS).
Inputs & outputs
In: JSON file project_identity_v6.json; JSON file major_projects_v6.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It splits refs (`split_refs`), loads manifest (`load_manifest`) and reads official rows (`read_official_rows`). Defines `clean`, `norm`, `numeric_sort` and 16 more.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
testcode · backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts · Python CLI
Uses
__future__, csv, hashlib, io, json, re, collections, pathlib
Used by
none found
Produces
clean, norm, numeric_sort, technology_category, lifecycle, valid_planning_ref, canon_header, split_refs, short_hash, gg_project_id, UnionFind, resolve
Defines here
build_public_snapshot, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts/build_project_identity_v6.py:442-588 · blob 2bc5c360fa47341de71018d3f4744235a722cd68 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
        "identity_rules": {
            "repd_bound": "GG2050-REPD-<official Ref ID>",
            "non_repd": "GG2050-UK-<stable public-anchor hash>; never fabricates an REPD Ref ID",
            "development_grouping": "explicit REPD cross-reference first; planning-reference + authority/NSIP grouping second",
            "capacity_not_identity": True,
        },
        "records": records,
    }
    return registry


def build_public_snapshot(registry, manifest):
    projects = []
    for record in registry["records"]:
        category = technology_category(record["technology"])
        capacity = record["capacity_mw"]
        if capacity is None:
            continue
        if category == "solar" and capacity <= 1.0:
            continue
        if category == "bess" and capacity <= 100.0:
            continue
        if category not in {"solar", "bess"}:
            continue
        explicit_types = {
            clean(relation.get("repd_ref")): relation.get("type")
            for relation in record.get("relationships") or []
            if clean(relation.get("repd_ref"))
        }
        development_relationships = [
            {
                "repd_ref": target,
                "type": explicit_types.get(target, "SAME_DEVELOPMENT"),
            }
            for target in record["development_repd_refs"]
            if target != record["repd_ref"]
        ]
        projects.append(
            {
                "gg_project_id": record["gg_project_id"],
                "gg_development_id": record["gg_development_id"],
                "identity_status": record["identity_status"],
                "repd_ref": record["repd_ref"],
                "repd_old_ref": record["repd_old_ref"],
                "repd_record_updated": record["repd_record_updated"],
                "name": record["site_name"],
                "technology": category,
                "repd_technology": record["technology"],
                "capacity_mw": capacity,
                "capacity_known": True,
                "status": record["status"],
                "lifecycle": record["lifecycle"],
                "operator": record["operator"] or None,
                "county": record["county"] or None,
                "region": record["region"] or None,
                "country": record["country"] or None,
                "planning_authority": record["planning_authority"] or None,
                "planning_application_reference": record["planning_application_reference"] or None,
                "planning_application_submitted": record["planning_application_submitted"],
                "planning_application_withdrawn": record["planning_application_withdrawn"],
                "planning_permission_refused": record["planning_permission_refused"],
                "planning_permission_granted": record["planning_permission_granted"],
                "planning_permission_expired": record["planning_permission_expired"],
                "under_construction": record["under_construction"],
                "operational": record["operational"],
                "related_repd_refs": record["development_repd_refs"][1:],
                "relationships": record["relationships"],
                "development_relationships": development_relationships,
                "source_row": record["source_row"],
            }
        )

    projects.sort(key=lambda item: (-item["capacity_mw"], item["name"].casefold(), numeric_sort(item["repd_ref"])))
    solar_count = sum(item["technology"] == "solar" for item in projects)
    bess_count = sum(item["technology"] == "bess" for item in projects)
    if (solar_count, bess_count, len(projects)) != (
        EXPECTED_SOLAR_GT1,
        EXPECTED_BESS_GT100,
        EXPECTED_SOLAR_GT1 + EXPECTED_BESS_GT100,
    ):
        raise RuntimeError(
            "Canonical V6 threshold universe mismatch: "
            f"solar={solar_count} bess={bess_count} total={len(projects)}"
        )

    canonical_projects = json.dumps(projects, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
    update_count = sum(bool(item["repd_record_updated"]) for item in projects)
    snapshot = {
        "schema": "globalgrid2050.major-projects.v6",
        "identity_schema": SCHEMA,
        "version": 6,
        "validated_at": manifest["validated_at"],
        "source_owner": manifest["source_owner"],
        "source_dataset_title": manifest["source_dataset_title"],
        "source_publication_date": manifest["source_page_last_updated"],
        "source_page": manifest["source_page"],
        "source_csv_url": manifest["source_url"],
        "source_xlsx_url": manifest["source_excel_url"],
        "source_hashes": manifest["source_hashes"],
        "source_record_count": EXPECTED_ROWS,
        "source_unique_ref_count": EXPECTED_ROWS,
        "csv_xlsx_reconciled": True,
        "repd_bound": True,
        "globalgrid_id_required": True,
        "canonical_capacity_source": manifest["canonical_capacity_source"],
        "thresholds": manifest["thresholds"],
        "project_count": len(projects),
        "count": len(projects),
        "solar_count": solar_count,
        "bess_count": bess_count,
        "record_update_supplied_count": update_count,
        "record_update_missing_count": len(projects) - update_count,
        "projects_sha256": hashlib.sha256(canonical_projects.encode("utf-8")).hexdigest(),
        "projects": projects,
    }
    return snapshot


def main():
    manifest = load_manifest()
    source_url, canonical_path = ensure_official_csv(manifest)
    rows, headers, relationship_columns = read_official_rows(canonical_path)
    registry = build_registry(rows, manifest, source_url)
    registry["detected_header_count"] = len(headers)
    registry["detected_relationship_columns"] = relationship_columns
    IDENTITY_OUT.write_text(json.dumps(registry, indent=2), encoding="utf-8")
    snapshot = build_public_snapshot(registry, manifest)
    PROJECTS_OUT.write_text(json.dumps(snapshot, separators=(",", ":")), encoding="utf-8")
    manifest["public_snapshot"] = {
        "path": "dist/major_projects_v6.json",
        "project_count": snapshot["project_count"],
        "projects_sha256": snapshot["projects_sha256"],
    }
    MANIFEST.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
    print(
        "identity",
        f"raw={registry['raw_record_count']}",
        f"repd={registry['repd_bound_count']}",
        f"gg_only={registry['globalgrid_only_count']}",
        f"groups={registry['development_group_count']}",
        f"coverage={registry['repd_ref_coverage']:.3%}",
        f"public_projects={snapshot['project_count']}",
    )


if __name__ == "__main__":
    main()

GlobalGrid2050 Validate Project Identity V6

A Python module in the scripts folder of Testcode that reads project identity integrity, major projects, major project news and project news links, using SHA-256.

automationtestcode / backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts/validate_project_identity_v6.py · lines 1–236 of 236 · version 2026-11-14 00:31 · Entry point · pattern number (shared by 21 files)

What it does
It loads project identity integrity, major projects, major project news and project news links. Defines check, load, clean, number. Uses libraries __future__, hashlib, json, math, datetime. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): 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 project_identity_v6.json; JSON file major_projects_v6.json; JSON file major_project_news_v6.json; JSON file project_news_links_v6.json; JSON file project_identity_v6_integrity.json.
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
It is built from the check step (`check`), the load step (`load`) and the clean step (`clean`). Validate V6 project/development identities and news relationships.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
testcode · backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts · Python module
Uses
__future__, hashlib, json, math, datetime, pathlib
Used by
none found
Produces
check, load, clean, number
Defines here
check, load, clean, number
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts/validate_project_identity_v6.py:1-236 · blob a1cb95c751e237a00df6a42cdfdf2f7b440cc2fd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
#!/usr/bin/env python3
"""Validate V6 project/development identities and news relationships."""
from __future__ import annotations

import hashlib
import json
import math
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
DIST = ROOT / "dist"
IDENTITY = DIST / "project_identity_v6.json"
PROJECTS = DIST / "major_projects_v6.json"
NEWS = DIST / "major_project_news_v6.json"
LINKS = DIST / "project_news_links_v6.json"
REPORT = DIST / "project_identity_v6_integrity.json"

EXPECTED_ROWS = 14657
EXPECTED_SOLAR = 3445
EXPECTED_BESS = 269
EXPECTED_PROJECTS = EXPECTED_SOLAR + EXPECTED_BESS

errors = []
checks = []


def check(condition, gate, detail=""):
    ok = bool(condition)
    checks.append({"gate": gate, "pass": ok, "detail": detail})
    if not ok:
        errors.append(f"{gate}: {detail}" if detail else gate)


def load(path):
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception as exc:
        errors.append(f"cannot load {path.relative_to(ROOT)}: {exc}")
        return {}


def clean(value):
    return str(value or "").strip()


def number(value):
    try:
        result = float(value)
        return result if math.isfinite(result) else None
    except Exception:
        return None


identity = load(IDENTITY)
projects = load(PROJECTS)
news = load(NEWS)
links = load(LINKS)

records = identity.get("records") or []
check(identity.get("schema") == "globalgrid2050.project-identity.v6", "identity schema")
check(identity.get("raw_record_count") == EXPECTED_ROWS, "identity raw row count", str(identity.get("raw_record_count")))
check(identity.get("repd_bound_count") == EXPECTED_ROWS, "identity REPD-bound count", str(identity.get("repd_bound_count")))
check(identity.get("globalgrid_only_count") == 0, "no fabricated REPD identities", str(identity.get("globalgrid_only_count")))
check(len(records) == EXPECTED_ROWS, "identity record array exact", f"records={len(records)}")
check(identity.get("identity_rules", {}).get("capacity_not_identity") is True, "capacity excluded from identity")

by_ref = {}
by_gg = {}
identity_error_start = len(errors)
for index, record in enumerate(records):
    ref = clean(record.get("repd_ref"))
    gg = clean(record.get("gg_project_id"))
    development = clean(record.get("gg_development_id"))
    if not ref:
        errors.append(f"identity row {index} lacks official REPD Ref")
    if gg != f"GG2050-REPD-{ref}":
        errors.append(f"identity row {index} has non-deterministic project ID: {gg}")
    if record.get("identity_status") != "REPD_BOUND":
        errors.append(f"identity row {index} is not REPD_BOUND")
    if not development.startswith("GG2050-DEV-"):
        errors.append(f"identity row {index} lacks development ID")
    if record.get("capacity_known") != (number(record.get("capacity_mw")) is not None):
        errors.append(f"identity row {index} violates capacity-null discipline")
    if ref in by_ref:
        errors.append(f"duplicate identity REPD Ref: {ref}")
    if gg in by_gg:
        errors.append(f"duplicate GlobalGrid project ID: {gg}")
    by_ref[ref] = record
    by_gg[gg] = record
check(len(errors) == identity_error_start, "all identity rows valid and unique", f"new_errors={len(errors)-identity_error_start}")

relationship_error_start = len(errors)
for ref, record in by_ref.items():
    development = clean(record.get("gg_development_id"))
    for relation in record.get("relationships") or []:
        target = clean(relation.get("repd_ref"))
        if relation.get("type") not in {"CURRENT_VERSION", "PREVIOUS_REPD_REF", "RELATED_APPLICATION", "COLOCATED_COMPONENT"}:
            errors.append(f"untyped relation {ref}->{target}: {relation.get('type')}")
        if target in by_ref:
            if clean(by_ref[target].get("gg_development_id")) != development:
                errors.append(f"resolvable relation not grouped {ref}->{target}")
    for target in record.get("development_repd_refs") or []:
        target = clean(target)
        if target not in by_ref:
            errors.append(f"development member absent {ref}->{target}")
        elif clean(by_ref[target].get("gg_development_id")) != development:
            errors.append(f"development group inconsistent {ref}->{target}")
check(len(errors) == relationship_error_start, "all identity relationships resolve consistently", f"new_errors={len(errors)-relationship_error_start}")

project_rows = projects.get("projects") or []
check(projects.get("schema") == "globalgrid2050.major-projects.v6", "public project schema")
check(projects.get("repd_bound") is True, "public projects REPD-bound")
check(projects.get("globalgrid_id_required") is True, "public projects GlobalGrid-bound")
check(projects.get("csv_xlsx_reconciled") is True, "public projects reconciled")
check(projects.get("source_record_count") == EXPECTED_ROWS, "public source row metadata")
check(projects.get("project_count") == EXPECTED_PROJECTS == len(project_rows), "public project count", f"metadata={projects.get('project_count')} rows={len(project_rows)}")
check(projects.get("solar_count") == EXPECTED_SOLAR, "public solar count")
check(projects.get("bess_count") == EXPECTED_BESS, "public BESS count")
canonical_projects = json.dumps(project_rows, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
check(projects.get("projects_sha256") == hashlib.sha256(canonical_projects.encode("utf-8")).hexdigest(), "public project-array hash")

project_refs = set()
solar = bess = 0
project_error_start = len(errors)
for index, project in enumerate(project_rows):
    ref = clean(project.get("repd_ref"))
    identity_row = by_ref.get(ref)
    if not identity_row:
        errors.append(f"public project {index} absent from identity registry: {ref}")
        continue
    if ref in project_refs:
        errors.append(f"duplicate public project REPD Ref: {ref}")
    project_refs.add(ref)
    for field, project_key, identity_key in (
        ("project ID", "gg_project_id", "gg_project_id"),
        ("development ID", "gg_development_id", "gg_development_id"),
        ("name", "name", "site_name"),
        ("status", "status", "status"),
        ("update date", "repd_record_updated", "repd_record_updated"),
    ):
        if project.get(project_key) != identity_row.get(identity_key):
            errors.append(f"public {field} differs from identity registry: {ref}")
    if number(project.get("capacity_mw")) != number(identity_row.get("capacity_mw")):
        errors.append(f"public capacity differs from identity registry: {ref}")
    tech, capacity = project.get("technology"), number(project.get("capacity_mw"))
    if tech == "solar" and capacity is not None and capacity > 1.0:
        solar += 1
    elif tech == "bess" and capacity is not None and capacity > 100.0:
        bess += 1
    else:
        errors.append(f"public project outside exclusive thresholds: {ref}")
check(len(errors) == project_error_start, "all public projects bind exactly to identity registry", f"new_errors={len(errors)-project_error_start}")
check(solar == EXPECTED_SOLAR and bess == EXPECTED_BESS, "derived public thresholds", f"solar={solar} bess={bess}")

items = news.get("items") or []
link_rows = links.get("links") or []
check(news.get("repd_bound") is True, "news REPD-bound")
check(news.get("globalgrid_id_required") is True, "news GlobalGrid-bound")
check(news.get("headline_count") == len(items), "news headline count permits zero", f"metadata={news.get('headline_count')} rows={len(items)}")
check(links.get("schema") == "globalgrid2050.project-news-links.v6", "project-news link schema")
check(links.get("article_count") == len(items), "link article count permits zero")

primary = {}
link_error_start = len(errors)
for link in link_rows:
    article = clean(link.get("gg_article_id"))
    ref = clean(link.get("repd_ref"))
    if ref not in project_refs:
        errors.append(f"news link references ineligible project {article}/{ref}")
    if link.get("role") == "PRIMARY_MATCH":
        if article in primary:
            errors.append(f"multiple PRIMARY_MATCH links: {article}")
        primary[article] = link
        if link.get("eligible_for_news_signal") is not True:
            errors.append(f"primary link cannot drive signal: {article}")
    elif link.get("role") == "RELATED_DEVELOPMENT":
        if link.get("eligible_for_news_signal") is not False:
            errors.append(f"related link drives signal: {article}/{ref}")
    else:
        errors.append(f"invalid project-news role: {link.get('role')}")
check(len(errors) == link_error_start, "all project-news links valid", f"new_errors={len(errors)-link_error_start}")

article_ids = set()
article_error_start = len(errors)
for index, item in enumerate(items):
    article = clean(item.get("gg_article_id"))
    ref = clean(item.get("repd_ref"))
    if not article.startswith("GG2050-NEWS-"):
        errors.append(f"news article {index} has invalid ID: {article}")
    if article in article_ids:
        errors.append(f"duplicate news article ID: {article}")
    article_ids.add(article)
    if ref not in project_refs:
        errors.append(f"news article {index} PRIMARY_MATCH is ineligible: {ref}")
    if ref in by_ref:
        if item.get("gg_project_id") != by_ref[ref].get("gg_project_id"):
            errors.append(f"news article {index} project ID mismatch")
        if item.get("gg_development_id") != by_ref[ref].get("gg_development_id"):
            errors.append(f"news article {index} development ID mismatch")
    if article not in primary or clean(primary[article].get("repd_ref")) != ref:
        errors.append(f"news article {index} lacks exactly one matching primary link")
    evidence = item.get("match_evidence") or {}
    for gate in ("identity_gate_passed", "technology_gate_passed", "foreign_veto_passed", "duplicate_name_gate_passed"):
        if evidence.get(gate) is not True:
            errors.append(f"news article {index} failed persisted {gate}")
    if evidence.get("capacity_only") is not False:
        errors.append(f"news article {index} is capacity-only")
check(len(errors) == article_error_start, "all news articles preserve public match evidence", f"new_errors={len(errors)-article_error_start}")
check(len(primary) == len(items), "one PRIMARY_MATCH per article", f"primary={len(primary)} items={len(items)}")

report = {
    "schema": "globalgrid2050.project-identity-integrity.v6",
    "pass": not errors,
    "validated_at": datetime.now(timezone.utc).isoformat(),
    "metrics": {
        "identity_records": len(records),
        "development_groups": len({clean(row.get('gg_development_id')) for row in records}),
        "public_projects": len(project_rows),
        "solar_projects": solar,
        "bess_projects": bess,
        "news_articles": len(items),
        "project_news_links": len(link_rows),
    },
    "checks": checks,
    "errors": errors,
}
REPORT.write_text(json.dumps(report, indent=2), encoding="utf-8")

if errors:
    print("PROJECT IDENTITY V6 FAILED")
    for error in errors[:100]:
        print(" -", error)
    raise SystemExit(1)

print("PROJECT IDENTITY V6 PASS", json.dumps(report["metrics"], sort_keys=True))

GlobalGrid2050 Validate V6 Manifest Provenance

A Python module in the scripts folder of Testcode that reads the Renewable Energy Planning Database (REPD) register, solar and battery storage (BESS).

automationtestcode / backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts/validate_v6_manifest_provenance.py · lines 1–76 of 76 · version 2026-11-14 00:31 · Entry point

What it does
It loads the REPD register, solar and battery storage (BESS). Defines need, load. Uses libraries __future__, json, pathlib, urllib.parse, repd_sources_v6. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar, battery storage (BESS).
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
It is built from the need step (`need`) and the load step (`load`). Validate that V6 is bound to the reconciled, immutable Q2 2026 release.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
testcode · backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts · Python module
Uses
__future__, json, pathlib, urllib.parse, repd_sources_v6
Used by
none found
Produces
need, load
Defines here
need, load
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 backups/202611140031-repd-2026q3-pre-release/globalgrid2050/scripts/validate_v6_manifest_provenance.py:1-76 · blob eda9b1b789b860ef3cdd443792a9091937ee818a · 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: unknown
#!/usr/bin/env python3
"""Validate that V6 is bound to the reconciled, immutable Q2 2026 release."""
from __future__ import annotations

import json
from pathlib import Path
from urllib.parse import urlparse

from repd_sources_v6 import (
    CSV_URL,
    EXPECTED_BESS_GT100,
    EXPECTED_CSV_SHA256,
    EXPECTED_ROWS,
    EXPECTED_SOLAR_GT1,
    EXPECTED_XLSX_SHA256,
    MANIFEST,
    PUBLICATION_DATE,
    REPORT,
    SOURCE_PAGE,
    XLSX_URL,
)

errors = []


def need(condition, message):
    if not condition:
        errors.append(message)


def load(path: Path):
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception as exc:
        raise RuntimeError(f"Cannot read {path}: {exc}") from exc


manifest = load(MANIFEST)
source = load(REPORT)
metrics = source.get("metrics") or {}
hashes = source.get("source_hashes") or {}

need(manifest.get("schema") == "globalgrid2050.repd-manifest.v6", "V6 manifest schema mismatch")
need(manifest.get("status") == "VALIDATED", "V6 manifest is not validated")
need(source.get("pass") is True, "CSV/XLSX reconciliation did not pass")
need(manifest.get("source_owner") == "Department for Energy Security and Net Zero (DESNZ)", "DESNZ owner missing")
need(manifest.get("source_page") == SOURCE_PAGE, "official publication page mismatch")
need(manifest.get("source_page_last_updated") == PUBLICATION_DATE, "Q2 publication date mismatch")
need(manifest.get("source_url") == CSV_URL == source.get("csv_url"), "official CSV URL mismatch")
need(manifest.get("source_excel_url") == XLSX_URL == source.get("xlsx_url"), "official XLSX URL mismatch")
need(urlparse(CSV_URL).netloc == "assets.publishing.service.gov.uk", "official CSV host mismatch")
need(urlparse(XLSX_URL).netloc == "assets.publishing.service.gov.uk", "official XLSX host mismatch")
need(hashes.get("csv_sha256") == EXPECTED_CSV_SHA256, "official CSV hash mismatch")
need(hashes.get("xlsx_sha256") == EXPECTED_XLSX_SHA256, "official XLSX hash mismatch")
need(manifest.get("source_hashes") == hashes, "manifest/source-report hashes differ")
need(metrics.get("csv_rows") == EXPECTED_ROWS, "CSV row count mismatch")
need(metrics.get("xlsx_rows") == EXPECTED_ROWS, "XLSX row count mismatch")
need(metrics.get("csv_unique_refs") == EXPECTED_ROWS, "CSV unique Ref count mismatch")
need(metrics.get("xlsx_unique_refs") == EXPECTED_ROWS, "XLSX unique Ref count mismatch")
need(metrics.get("material_mismatches") == 0, "material CSV/XLSX mismatch present")
need(metrics.get("canonical_solar_gt1") == EXPECTED_SOLAR_GT1, "canonical solar count mismatch")
need(metrics.get("canonical_bess_gt100") == EXPECTED_BESS_GT100, "canonical BESS count mismatch")
need(metrics.get("canonical_combined_projects") == EXPECTED_SOLAR_GT1 + EXPECTED_BESS_GT100, "combined V6 count mismatch")

if errors:
    print("V6 MANIFEST PROVENANCE FAILED")
    for error in errors:
        print(" -", error)
    raise SystemExit(1)

print(
    "V6 MANIFEST PROVENANCE PASS",
    f"source_rows={EXPECTED_ROWS}",
    f"solar={EXPECTED_SOLAR_GT1}",
    f"bess={EXPECTED_BESS_GT100}",
)

BBC RSS Discovery

A configuration file in the backups folder of Testcode. Runs on a schedule and by hand.

automationtestcode / backups/202611140229-pipelinenews-before-repd-2026q3/files/.github/workflows/bbc-rss-discovery.yml · lines 1–55 of 55 · version 2026-11-14 02:29 · Not reached from any entry point (candidate for review)

Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
What it achieves
Runs `discovery/bbc_rss.py` and `tools/intelligence/reconcile-provisional.mjs`.
Why it matters
No other file in the estate was found to import it.
Application
testcode · backups/202611140229-pipelinenews-before-repd-2026q3/files/.github/workflows · configuration
Uses
none found
Used by
none found
Produces
none declared
Defines here
Refresh BBC RSS discovery
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 backups/202611140229-pipelinenews-before-repd-2026q3/files/.github/workflows/bbc-rss-discovery.yml:1-55 · blob 6450fa6315b3e3cb4c7729d79907acedd9bfd0d2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
name: Refresh BBC RSS discovery
on:
  schedule:
    - cron: '17 */2 * * *'
  workflow_dispatch:
permissions:
  contents: write
concurrency:
  group: bbc-rss-discovery
  cancel-in-progress: false
jobs:
  refresh:
    runs-on: ubuntu-24.04
    timeout-minutes: 12
    steps:
      - uses: actions/checkout@v4
        with:
          ref: main
          fetch-depth: 1
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - name: Prove RSS boundaries before any collection
        run: python -B -m unittest discover -s discovery -p test_bbc_rss.py
      - name: Collect BBC RSS only
        id: collect
        continue-on-error: true
        run: python -B discovery/bbc_rss.py
      - name: Reconcile provisional IDs against newly imported quarterly projects
        run: |
          node --test cartridges/provisional-identity.test.mjs
          node tools/intelligence/reconcile-provisional.mjs
      - name: Commit bounded product and observed health
        run: |
          git config user.name 'github-actions[bot]'
          git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
          git add -- discovery/products/bbc-rss.json data/provisional/project-register.json
          if ! git diff --cached --quiet; then
            git commit -m 'Refresh BBC RSS metadata and source health [skip ci]'
            git pull --rebase origin main
            git push origin HEAD:main
          fi
      - name: Retain exact collection receipt
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: bbc-rss-health
          path: discovery/products/bbc-rss.json
          retention-days: 7
      - name: Fail when every feed failed
        if: steps.collect.outcome == 'failure'
        run: exit 1

Reconcile Provisional

A JavaScript module in the intelligence folder of Testcode that reads project register, using SHA-256.

storagetestcode / backups/202611140229-pipelinenews-before-repd-2026q3/files/tools/intelligence/reconcile-provisional.mjs · lines 1–33 of 33 · version 2026-11-14 02:29 · Not reached from any entry point (candidate for review)

What it does
It loads project register. Uses libraries node:fs, node:crypto. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file project-register.json; command-line arguments.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
testcode · backups/202611140229-pipelinenews-before-repd-2026q3/files/tools/intelligence · JavaScript module
Uses
Provisional Identity (import), node:fs, node:crypto
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
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 backups/202611140229-pipelinenews-before-repd-2026q3/files/tools/intelligence/reconcile-provisional.mjs:1-33 · blob a5402dbb9943c7cd754bfab3d27280cdf89f0672 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import {readFileSync,writeFileSync,readdirSync,existsSync,renameSync} from 'node:fs';
import {createHash} from 'node:crypto';
import {reconcileProvisional} from '../../cartridges/provisional-identity.mjs';
const registerPath='data/provisional/project-register.json';
if(!existsSync(registerPath)){console.log('No provisional register');process.exit(0);}
let path=process.argv[2];
if(!path){
 // Every imported quarterly source must reach an immutable Pipeline build.
 // Choose the newest compatible project payload; never modify that source.
 const releases=readdirSync('releases').filter(x=>/^\d{12}-pipelinenews$/.test(x)).sort().reverse();
 for(const release of releases){
  const dir=`releases/${release}/data`;if(!existsSync(dir))continue;
  const file=readdirSync(dir).find(x=>/-v8-fast-projects\.json$/.test(x));
  if(file){path=`${dir}/${file}`;break;}
 }
}
if(!path)throw Error('No compatible quarterly project payload');
const bytes=readFileSync(path),data=JSON.parse(bytes);
if(data.schema!=='pipelinenews.v8.fast-project-index.v1'||!Array.isArray(data.fields)||!Array.isArray(data.rows))throw Error('Unsupported quarterly source');
const required=['repd_ref','name','operator','county','capacity_mw'];
for(const field of required)if(!data.fields.includes(field))throw Error('Quarterly identity field missing: '+field);
const official=data.rows.map(values=>Object.fromEntries(required.map(field=>{
 const value=values[data.fields.indexOf(field)];
 return [field,data.dictionaries?.[field] ? data.dictionaries[field][value] : value];
})));
const register=JSON.parse(readFileSync(registerPath));
const source={path,sha256:createHash('sha256').update(bytes).digest('hex')};
const result={...register,projects:reconcileProvisional(register.projects,official,source)};
const body=JSON.stringify(result,null,2)+'\n';
if(body!==readFileSync(registerPath,'utf8').replaceAll('\r\n','\n')){
 const temporary=registerPath+'.tmp';writeFileSync(temporary,body);renameSync(temporary,registerPath);
}
console.log(JSON.stringify({source,pending:result.projects.filter(p=>!p.official_repd_ref).length,matched:result.projects.filter(p=>p.official_repd_ref).length}));