GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / scripts

GlobalGrid2050 Update V6 Transport Energy Sources and 7 more files

A Python command-line tool in the scripts folder that fetches live oil prices, oil price history, live UK fuel prices and EV charging prices.

689 lines of Python and JavaScript from globalgrid2050, in 8 files. Topic: Electricity markets and data pipelines. Section 899 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 Update V6 Transport Energy Sources storage · globalgrid2050 / scripts/update_v6_transport_energy_sources.py lines 1–364
  2. GlobalGrid2050 Validate Renewable Energy Planning Database (REPD) Sources V6 energy-data · globalgrid2050 / scripts/validate_repd_sources_v6.py lines 1–8
  3. GlobalGrid2050 Wire Generation Ecg Candidate energy-data · globalgrid2050 / scripts/wire_generation_ecg_candidate.py lines 1–165
  4. App V9 3 other · globalgrid2050 / testcode/202609051152/pipeline/scripts/app-v9-3.js lines 1–31
  5. App V9 4 other · globalgrid2050 / testcode/202609051152/pipeline/scripts/app-v9-4.js lines 1–31
  6. App V9 5 1 other · globalgrid2050 / testcode/202609051152/pipeline/scripts/app-v9-5-1.js lines 1–31
  7. App V9 5 other · globalgrid2050 / testcode/202609051152/pipeline/scripts/app-v9-5.js lines 1–31
  8. App V9 6 2 other · globalgrid2050 / testcode/202609051152/pipeline/scripts/app-v9-6-2.js lines 1–28

GlobalGrid2050 Update V6 Transport Energy Sources

A Python command-line tool in the scripts folder that fetches live oil prices, oil price history, live UK fuel prices and EV charging prices.

storageglobalgrid2050 / scripts/update_v6_transport_energy_sources.py · lines 1–364 of 364 · Entry point · pattern parse_desnz_csv (shared by 5 files)

What it does
It fetches live oil prices, oil price history, live UK fuel prices and EV charging prices. Defines 16 functions or classes, including now_utc, build_session, fetch_text, yahoo_price, fred_csv. Uses libraries csv, json, re, datetime, io. Side effects: reads or writes files; 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 live_oil_prices.json; GeoJSON file oil_price_history.geojson; JSON file live_uk_fuel_prices.json; JSON file ev_charging_prices.json; CSV file fredgraph.csv.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Update V6 Transport Energy Sources Workflow (globalgrid2050).
What it achieves
It loads existing JSON (`load_existing_json`) and is built from the yahoo price helper (`yahoo_price`) and the fred CSV helper (`fred_csv`). Defines `now_utc`, `build_session`, `fetch_text` and 12 more. It writes `uk_energy_tracking_v6/live_oil_prices.json`.
Why it matters
Run by GlobalGrid2050 Update V6 Transport Energy Sources Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, json, re, datetime, io, pathlib, urllib.parse, requests
Used by
run by GlobalGrid2050 Update V6 Transport Energy Sources Workflow (workflow run)
Produces
now_utc, build_session, fetch_text, yahoo_price, fred_csv, yahoo_history, load_existing_json, write_oil, normalise, parse_number, find_latest_desnz_csv_url, parse_desnz_csv
Defines here
now_utc, build_session, fetch_text, yahoo_price, fred_csv, yahoo_history, load_existing_json, write_oil, normalise, parse_number, find_latest_desnz_csv_url, parse_desnz_csv, find_col, write_fuel, write_ev_reference, 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 scripts/update_v6_transport_energy_sources.py:1-364 · blob ba7aa7ad00e728bc3c80c155281b8b748c105951 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import csv
import json
import re
from datetime import datetime, timezone, timedelta
from io import StringIO
from pathlib import Path
from urllib.parse import urljoin

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

ROOT = Path(__file__).resolve().parents[1]
OUT_DIR = ROOT / "uk_energy_tracking_v6"

OIL_LIVE_FILE = OUT_DIR / "live_oil_prices.json"
OIL_HISTORY_FILE = OUT_DIR / "oil_price_history.geojson"
FUEL_FILE = OUT_DIR / "live_uk_fuel_prices.json"
EV_FILE = OUT_DIR / "ev_charging_prices.json"
REPORT_FILE = OUT_DIR / "V6_TRANSPORT_ENERGY_SOURCES_REPORT.md"

DESNZ_FUEL_PAGE = "https://www.gov.uk/government/statistics/weekly-road-fuel-prices"
HISTORY_YEARS = 25
HISTORY_MAX_AGE_HOURS = 24
HEADERS = {"User-Agent": "GlobalGrid2050/1.0"}


def now_utc():
    return datetime.now(timezone.utc).isoformat()


def build_session():
    retry_strategy = Retry(
        total=3,
        connect=3,
        read=3,
        status=3,
        backoff_factor=2,
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods=["GET"],
        raise_on_status=False,
    )
    session = requests.Session()
    session.headers.update(HEADERS)
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("https://", adapter)
    session.mount("http://", adapter)
    return session


SESSION = build_session()


def fetch_text(url, timeout=30):
    r = SESSION.get(url, timeout=timeout)
    r.raise_for_status()
    return r.text


def yahoo_price(ticker):
    url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}"
    r = SESSION.get(url, timeout=20)
    r.raise_for_status()
    return float(r.json()["chart"]["result"][0]["meta"]["regularMarketPrice"])


def fred_csv(series):
    url = f"https://fred.stlouisfed.org/graph/fredgraph.csv?id={series}"
    rows = []
    cutoff = datetime.now(timezone.utc) - timedelta(days=HISTORY_YEARS * 366)
    for row in csv.DictReader(StringIO(fetch_text(url, timeout=60))):
        date = row.get("observation_date")
        value = row.get(series)
        if not date or not value or value == ".":
            continue
        try:
            dt = datetime.strptime(date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
            if dt >= cutoff:
                rows.append((date, float(value)))
        except ValueError:
            continue
    if not rows:
        raise RuntimeError(f"FRED returned no usable rows for {series}")
    return rows


def yahoo_history(ticker):
    url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?range={HISTORY_YEARS}y&interval=1d"
    r = SESSION.get(url, timeout=60)
    r.raise_for_status()
    result = r.json()["chart"]["result"][0]
    timestamps = result.get("timestamp") or []
    closes = (((result.get("indicators") or {}).get("quote") or [{}])[0].get("close") or [])
    rows = []
    cutoff = datetime.now(timezone.utc) - timedelta(days=HISTORY_YEARS * 366)
    for ts, close in zip(timestamps, closes):
        if close is None:
            continue
        dt = datetime.fromtimestamp(ts, timezone.utc)
        if dt >= cutoff:
            rows.append((dt.strftime("%Y-%m-%d"), float(close)))
    if not rows:
        raise RuntimeError(f"Yahoo returned no usable rows for {ticker}")
    return rows


def load_existing_json(path):
    if not path.exists():
        return None
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return None


def write_oil():
    live = {"updated": now_utc(), "brentUSDperBarrel": None, "wtiUSDperBarrel": None, "health": {}}
    for ticker, key in [("BZ=F", "brentUSDperBarrel"), ("CL=F", "wtiUSDperBarrel")]:
        try:
            live[key] = yahoo_price(ticker)
            live["health"][ticker] = {"ok": True, "source": "Yahoo Finance chart API"}
        except Exception as exc:
            live["health"][ticker] = {"ok": False, "error": str(exc)}
    OIL_LIVE_FILE.write_text(json.dumps(live, indent=2), encoding="utf-8")

    existing = load_existing_json(OIL_HISTORY_FILE)
    if existing and existing.get("features"):
        updated = existing.get("metadata", {}).get("updated")
        try:
            dt = datetime.fromisoformat(str(updated).replace("Z", "+00:00"))
            if datetime.now(timezone.utc) - dt < timedelta(hours=HISTORY_MAX_AGE_HOURS):
                existing.setdefault("metadata", {})["lastSkippedHistoryUpdate"] = now_utc()
                OIL_HISTORY_FILE.write_text(json.dumps(existing, indent=2), encoding="utf-8")
                return {"live": live, "history_features": len(existing.get("features", [])), "fresh_history": False}
        except Exception:
            pass

    merged = {}
    health = []
    for series, field, label in [
        ("DCOILBRENTEU", "brentUSDperBarrel", "FRED Brent Europe daily spot price"),
        ("DCOILWTICO", "wtiUSDperBarrel", "FRED WTI Cushing daily spot price"),
    ]:
        try:
            rows = fred_csv(series)
            for date, value in rows:
                merged.setdefault(date, {})[field] = value
            health.append({"ok": True, "source": label, "rows": len(rows)})
        except Exception as exc:
            health.append({"ok": False, "source": label, "error": str(exc)})

    if not merged:
        for ticker, field, label in [
            ("BZ=F", "brentUSDperBarrel", "Yahoo Brent futures history"),
            ("CL=F", "wtiUSDperBarrel", "Yahoo WTI futures history"),
        ]:
            try:
                rows = yahoo_history(ticker)
                for date, value in rows:
                    merged.setdefault(date, {})[field] = value
                health.append({"ok": True, "source": label, "rows": len(rows), "fallback": True})
            except Exception as exc:
                health.append({"ok": False, "source": label, "error": str(exc), "fallback": True})

    features = [
        {"type": "Feature", "geometry": {"type": "Point", "coordinates": [0, 0]}, "properties": {"date": date, **merged[date]}}
        for date in sorted(merged)
    ]
    history = {
        "type": "FeatureCollection",
        "metadata": {
            "updated": now_utc(),
            "unit": "USD per barrel",
            "period": f"Last {HISTORY_YEARS} years",
            "note": "Placeholder Point geometry. This is a portable time series for charting, not a spatial dataset. FRED is preferred. Yahoo history is fallback.",
            "sources": health,
        },
        "features": features,
    }
    OIL_HISTORY_FILE.write_text(json.dumps(history, indent=2), encoding="utf-8")
    return {"live": live, "history_features": len(features), "fresh_history": True, "health": health}


def normalise(text):
    return re.sub(r"[^a-z0-9]", "", str(text).lower())


def parse_number(value):
    if value is None:
        return None
    text = str(value).replace(",", "").strip()
    if not text or text in {".", "-"}:
        return None
    try:
        return float(text)
    except ValueError:
        return None


def find_latest_desnz_csv_url():
    html = fetch_text(DESNZ_FUEL_PAGE, timeout=30)
    matches = re.findall(r'href="([^"]*weekly_road_fuel_prices_[0-9]{6}\.csv)"', html, flags=re.I)
    current = [m for m in matches if "2003_to_2017" not in m.lower()]
    if not current:
        raise RuntimeError("Could not find current DESNZ weekly road fuel CSV link")
    return urljoin(DESNZ_FUEL_PAGE, current[0])


def parse_desnz_csv(csv_text):
    rows = list(csv.reader(StringIO(csv_text)))
    header_i = None
    for i, row in enumerate(rows[:20]):
        joined = " ".join(row).lower()
        if ("ulsp" in joined or "unleaded" in joined) and ("ulsd" in joined or "diesel" in joined):
            header_i = i
            break
    if header_i is None:
        raise RuntimeError("Could not identify DESNZ CSV header row")
    headers = rows[header_i]
    normalised = [normalise(h) for h in headers]

    def find_col(candidates):
        for needle in candidates:
            for idx, name in enumerate(normalised):
                if needle in name:
                    return idx
        return None

    date_col = find_col(["date", "weekcommencing", "week"])
    petrol_col = find_col(["ulsp", "unleaded", "petrol"])
    diesel_col = find_col(["ulsd", "diesel"])
    if petrol_col is None or diesel_col is None:
        raise RuntimeError(f"Could not identify petrol or diesel columns. Headers: {headers}")

    parsed = []
    for row in rows[header_i + 1:]:
        if len(row) <= max(petrol_col, diesel_col, date_col or 0):
            continue
        petrol = parse_number(row[petrol_col])
        diesel = parse_number(row[diesel_col])
        if petrol is None and diesel is None:
            continue
        parsed.append({
            "week": row[date_col].strip() if date_col is not None else None,
            "petrolPencePerLitre": petrol,
            "dieselPencePerLitre": diesel,
        })
    if not parsed:
        raise RuntimeError("DESNZ CSV parsed but no usable rows were found")
    return parsed


def write_fuel():
    health = {"source": "DESNZ weekly road fuel prices", "page": DESNZ_FUEL_PAGE}
    try:
        csv_url = find_latest_desnz_csv_url()
        rows = parse_desnz_csv(fetch_text(csv_url, timeout=30))
        latest = rows[-1]
        out = {
            "updated": now_utc(),
            "source": "Department for Energy Security and Net Zero weekly road fuel prices",
            "sourcePage": DESNZ_FUEL_PAGE,
            "sourceCsv": csv_url,
            "unit": "pence per litre",
            "latest": latest,
            "history": rows,
            "health": {**health, "ok": True, "csv": csv_url, "rows": len(rows)},
        }
    except Exception as exc:
        existing = load_existing_json(FUEL_FILE)
        if existing and existing.get("history"):
            existing["lastAttemptedUpdate"] = now_utc()
            existing["health"] = {**health, "ok": False, "error": str(exc)}
            out = existing
        else:
            out = {
                "updated": now_utc(),
                "source": "Department for Energy Security and Net Zero weekly road fuel prices",
                "sourcePage": DESNZ_FUEL_PAGE,
                "unit": "pence per litre",
                "latest": {"week": None, "petrolPencePerLitre": None, "dieselPencePerLitre": None},
                "history": [],
                "health": {**health, "ok": False, "error": str(exc)},
            }
    FUEL_FILE.write_text(json.dumps(out, indent=2), encoding="utf-8")
    return {"latest": out.get("latest"), "health": out.get("health")}


def write_ev_reference():
    # Public EV tariffs vary by site, time, membership and vehicle. This file is a transparent reference table,
    # not an automated quote engine. Values are updated only when reviewed.
    out = {
        "updated": now_utc(),
        "unit": "pence per kilowatt hour",
        "sourcePolicy": "Curated public reference values. Public EV charging varies by operator, location, time, app, membership and vehicle.",
        "sources": [
            {"publisher": "The Sunday Times", "note": "Reported UK public charging benchmark: Gridserve 79p/kWh; InstaVolt 85p/kWh, 54p/kWh off peak; Tesla 24p to 47p/kWh for Tesla owners and 32p to 63p/kWh for non Tesla EVs, article citing Zapmap survey context."},
            {"publisher": "Operator websites", "note": "Operator links retained for manual verification before commercial use."},
        ],
        "operators": [
            {
                "operator": "Gridserve",
                "rapidPencePerKWh": 79,
                "ultraRapidPencePerKWh": 79,
                "sourceUrl": "https://www.gridserve.com/electric-highway/",
                "lastChecked": "2026-05-31",
                "status": "public benchmark, site tariffs may vary",
            },
            {
                "operator": "InstaVolt",
                "rapidPencePerKWh": 85,
                "ultraRapidPencePerKWh": 85,
                "offPeakPencePerKWh": 54,
                "sourceUrl": "https://instavolt.co.uk/",
                "lastChecked": "2026-05-31",
                "status": "public benchmark, off peak tariff separately stated",
            },
            {
                "operator": "Tesla Supercharger",
                "rapidPencePerKWh": 36,
                "ultraRapidPencePerKWh": 48,
                "ownerRangePencePerKWh": [24, 47],
                "nonTeslaRangePencePerKWh": [32, 63],
                "sourceUrl": "https://www.tesla.com/en_gb/supercharger",
                "lastChecked": "2026-05-31",
                "status": "midpoint display from reported range; live site pricing varies",
            },
        ],
    }
    EV_FILE.write_text(json.dumps(out, indent=2), encoding="utf-8")
    return {"operators": len(out["operators"]), "updated": out["updated"]}


def main():
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    oil = write_oil()
    fuel = write_fuel()
    ev = write_ev_reference()
    report = {
        "updated": now_utc(),
        "oil": oil,
        "fuel": fuel,
        "ev": ev,
    }
    REPORT_FILE.write_text(
        "# V6 Transport Energy Sources Report\n\n"
        f"Updated UTC: `{report['updated']}`\n\n"
        "## Outputs\n\n"
        "1. `uk_energy_tracking_v6/live_oil_prices.json`\n"
        "2. `uk_energy_tracking_v6/oil_price_history.geojson`\n"
        "3. `uk_energy_tracking_v6/live_uk_fuel_prices.json`\n"
        "4. `uk_energy_tracking_v6/ev_charging_prices.json`\n\n"
        "## Notes\n\n"
        "Oil live prices use Yahoo Finance chart API. Oil history prefers FRED Brent and WTI daily spot price series, with Yahoo futures history as fallback.\n\n"
        "Road fuel uses DESNZ weekly road fuel prices from GOV.UK.\n\n"
        "EV charging values are curated public reference values and must not be treated as live tariff quotes.\n\n"
        "```json\n" + json.dumps(report, indent=2) + "\n```\n",
        encoding="utf-8",
    )
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()

GlobalGrid2050 Validate Renewable Energy Planning Database (REPD) Sources V6

A Python command-line tool in the scripts folder.

energy-dataglobalgrid2050 / scripts/validate_repd_sources_v6.py · lines 1–8 of 8 · Entry point

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.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Major Project News V6 Workflow (globalgrid2050).
What it achieves
Fetch, reconcile and stage the official DESNZ Q2 V6 source snapshot.
Why it matters
Run by GlobalGrid2050 Major Project News V6 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
GlobalGrid2050 Renewable Energy Planning Database (REPD) Sources V6 (import)
Used by
run by GlobalGrid2050 Major Project News V6 Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/validate_repd_sources_v6.py:1-8 · blob 8e959902de99bb3742398f99058433271c51d99f · 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: production_core
#!/usr/bin/env python3
"""Fetch, reconcile and stage the official DESNZ Q2 V6 source snapshot."""

from repd_sources_v6 import main


if __name__ == "__main__":
    main()

GlobalGrid2050 Wire Generation Ecg Candidate

A Python command-line tool in the scripts folder that reads generation ecg technologies 30d 30min candidate, generation recent 30d 30min and ecg candidate wiring.

energy-dataglobalgrid2050 / scripts/wire_generation_ecg_candidate.py · lines 1–165 of 165 · Entry point · pattern patch_config (shared by 2 files)

What it does
It loads generation ecg technologies 30d 30min candidate, generation recent 30d 30min and ecg candidate wiring. Defines 8 functions or classes, including utc_now, stamp, read_text, write_text, patch_config. Uses libraries __future__, argparse, json, datetime, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'generation'): 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 generation_ecg_all_technologies_30d_30min_candidate.json; JSON file generation_recent_30d_30min.json; JSON file ECG_CANDIDATE_WIRING_LATEST.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Wire Generation Ecg Candidate Workflow (globalgrid2050).
What it achieves
It reads text (`read_text`), writes text (`write_text`) and patches config (`patch_config`). GlobalGrid2050 ECG candidate wiring helper. It accepts `--apply`.
Why it matters
Run by GlobalGrid2050 Wire Generation Ecg Candidate Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, json, datetime, pathlib
Used by
run by GlobalGrid2050 Wire Generation Ecg Candidate Workflow (workflow run)
Produces
utc_now, stamp, read_text, write_text, patch_config, patch_loader, render_report, main
Defines here
utc_now, stamp, read_text, write_text, patch_config, patch_loader, render_report, 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 scripts/wire_generation_ecg_candidate.py:1-165 · blob e28ca88f5b4df3f164f9199724f56e52c1a0fd0e · 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: production_core
#!/usr/bin/env python3
"""
GlobalGrid2050 ECG candidate wiring helper.

Adds the browser safe all technology 30 minute ECG candidate path to the generation
history config and routes the recent generation loader to it without touching the
renderer.
"""

from __future__ import annotations

import argparse
import json
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"

CONFIG_PATH = ROOT / "uk_energy_tracking_v6" / "generation_history" / "live-config.js"
LOADER_PATH = ROOT / "uk_energy_tracking_v6" / "generation_history" / "load_generation_history_data.js"
ECG_PATH = "/uk_energy_tracking_v6/generation_history/generation_ecg_all_technologies_30d_30min_candidate.json"
ECG_REPO_PATH = ROOT / "uk_energy_tracking_v6" / "generation_history" / "generation_ecg_all_technologies_30d_30min_candidate.json"


def utc_now() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def stamp() -> str:
    return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")


def read_text(path: Path) -> str:
    return path.read_text(encoding="utf-8", errors="replace") if path.exists() else ""


def write_text(path: Path, text: str) -> None:
    path.write_text(text.rstrip() + "\n", encoding="utf-8")


def patch_config(apply: bool) -> dict:
    text = read_text(CONFIG_PATH)
    exists = CONFIG_PATH.exists()
    already = "recentEcg" in text and ECG_PATH in text
    changed = False
    if exists and not already:
        old = "  recentHalfHourly:'/uk_energy_tracking_v6/generation_history/generation_recent_30d_30min.json',"
        new = old + "\n  recentEcg:'" + ECG_PATH + "',"
        if old in text:
            text = text.replace(old, new)
            changed = True
        elif "recentHalfHourly:" in text:
            lines = text.splitlines()
            out = []
            inserted = False
            for line in lines:
                out.append(line)
                if "recentHalfHourly:" in line and not inserted:
                    out.append("  recentEcg:'" + ECG_PATH + "',")
                    inserted = True
            text = "\n".join(out) + "\n"
            changed = inserted
        if apply and changed:
            write_text(CONFIG_PATH, text)
    return {
        "path": CONFIG_PATH.relative_to(ROOT).as_posix(),
        "exists": exists,
        "recentEcgAlreadyPresent": already,
        "wouldChange": bool(exists and not already and changed),
        "applied": bool(apply and exists and not already and changed),
    }


def patch_loader(apply: bool) -> dict:
    text = read_text(LOADER_PATH)
    exists = LOADER_PATH.exists()
    old = "function loadRecent(){return loadJsonOnce('recent',cfg().recentHalfHourly)}"
    new = "function loadRecent(){return loadJsonOnce('recent',cfg().recentEcg||cfg().recentHalfHourly)}"
    already = new in text
    changed = False
    if exists and not already and old in text:
        text = text.replace(old, new)
        changed = True
        if apply:
            write_text(LOADER_PATH, text)
    return {
        "path": LOADER_PATH.relative_to(ROOT).as_posix(),
        "exists": exists,
        "rendererTouched": False,
        "usesRecentEcgFallback": already or changed,
        "wouldChange": bool(exists and not already and changed),
        "applied": bool(apply and exists and not already and changed),
    }


def render_report(payload: dict) -> str:
    lines = [
        "# GlobalGrid2050 ECG Candidate Wiring Report",
        "",
        f"Generated UTC: `{payload['generatedUTC']}`",
        f"Mode: `{payload['mode']}`",
        "",
        "## Results",
        "",
        f"ECG file exists: `{payload['ecgFileExists']}`",
        f"ECG file size bytes: `{payload['ecgFileSizeBytes']}`",
        f"Renderer touched: `False`",
        "",
        "## Config",
        "",
        json.dumps(payload["config"], indent=2),
        "",
        "## Loader",
        "",
        json.dumps(payload["loader"], indent=2),
        "",
        "## Rule",
        "",
        payload["rule"],
    ]
    return "\n".join(lines) + "\n"


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()

    config_result = patch_config(args.apply)
    loader_result = patch_loader(args.apply)
    size = ECG_REPO_PATH.stat().st_size if ECG_REPO_PATH.exists() else 0
    payload = {
        "schemaVersion": "1.0.0",
        "generatedUTC": utc_now(),
        "mode": "apply" if args.apply else "audit only",
        "ecgPath": ECG_PATH,
        "ecgRepoPath": ECG_REPO_PATH.relative_to(ROOT).as_posix(),
        "ecgFileExists": ECG_REPO_PATH.exists(),
        "ecgFileSizeBytes": size,
        "config": config_result,
        "loader": loader_result,
        "rule": "Renderer untouched. Loader uses recentEcg when present and falls back to recentHalfHourly. Dropdown filtering remains unchanged.",
    }

    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    s = stamp()
    md = REPORT_DIR / f"ECG_CANDIDATE_WIRING_{s}.md"
    js = REPORT_JSON_DIR / f"ECG_CANDIDATE_WIRING_{s}.json"
    latest_md = REPORT_DIR / "ECG_CANDIDATE_WIRING_LATEST.md"
    latest_js = REPORT_JSON_DIR / "ECG_CANDIDATE_WIRING_LATEST.json"
    md_text = render_report(payload)
    js_text = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
    write_text(md, md_text)
    write_text(js, js_text)
    write_text(latest_md, md_text)
    write_text(latest_js, js_text)
    print(md_text)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

App V9 3

A JavaScript module in the scripts folder of GlobalGrid2050.

otherglobalgrid2050 / testcode/202609051152/pipeline/scripts/app-v9-3.js · lines 1–31 of 31 · version 2026-09-05 11:52 · Entry point

Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 1 file: UK Renewables Pipeline — V9 Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/v9/). Reached from 184 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — PipelineNews Intelligence Page (globalgrid2050, https://globalgrid2050.com/pipelinenews_intelligence/202609050309/).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Loaded by the V9 page at https://globalgrid2050.com/uk_renewables_pipeline/v9/.
Application
globalgrid2050 · testcode/202609051152/pipeline/scripts · JavaScript module
Uses
Gauges V9 2 (import), Newspaper V9 2 (import), Projects V9 3 (import), Plugin Host (import)
Used by
loaded by UK Renewables Pipeline — V9 Page (script src)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/pipeline/scripts/app-v9-3.js:1-31 · blob 177338febb78efe86566fc5cd9b7e1847eef9ea7 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: production_core
import { initialiseGaugesV9_2 } from "./plugins/gauges-v9-2.js";
import { bindNewspaperV9_2, loadNewsV9_2 } from "./plugins/newspaper-v9-2.js";
import {
  bindProjectControlsV9_3,
  loadProjectsV9_3,
  refreshProjectsV9_3,
} from "./plugins/projects-v9-3.js";
import { startPlugins } from "./core/plugin-host.js";

startPlugins([
  {
    id: "gauges",
    start: initialiseGaugesV9_2,
  },
  {
    id: "newspaper",
    dependsOn: ["gauges"],
    start() {
      bindNewspaperV9_2(refreshProjectsV9_3);
      loadNewsV9_2();
    },
  },
  {
    id: "projects",
    dependsOn: ["gauges", "newspaper"],
    start() {
      bindProjectControlsV9_3();
      loadProjectsV9_3();
    },
  },
]);

App V9 4

A JavaScript module in the scripts folder of GlobalGrid2050.

otherglobalgrid2050 / testcode/202609051152/pipeline/scripts/app-v9-4.js · lines 1–31 of 31 · version 2026-09-05 11:52 · Entry point

Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 1 file: UK Renewables Pipeline — V9 4 Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/v9.4/). Reached from 183 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — PipelineNews Intelligence Page (globalgrid2050, https://globalgrid2050.com/pipelinenews_intelligence/202609050309/).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Loaded by the V9 4 page at https://globalgrid2050.com/uk_renewables_pipeline/v9.4/.
Application
globalgrid2050 · testcode/202609051152/pipeline/scripts · JavaScript module
Uses
Gauges V9 2 (import), Newspaper V9 2 (import), Projects V9 4 (import), Plugin Host (import)
Used by
loaded by UK Renewables Pipeline — V9 4 Page (script src)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/pipeline/scripts/app-v9-4.js:1-31 · blob 0596783fc7967029c0cefa644c304a03e45b0311 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: production_core
import { initialiseGaugesV9_2 } from "./plugins/gauges-v9-2.js";
import { bindNewspaperV9_2, loadNewsV9_2 } from "./plugins/newspaper-v9-2.js";
import {
  bindProjectControlsV9_4,
  loadProjectsV9_4,
  refreshProjectsV9_4,
} from "./plugins/projects-v9-4.js";
import { startPlugins } from "./core/plugin-host.js";

startPlugins([
  {
    id: "gauges",
    start: initialiseGaugesV9_2,
  },
  {
    id: "newspaper",
    dependsOn: ["gauges"],
    start() {
      bindNewspaperV9_2(refreshProjectsV9_4);
      loadNewsV9_2();
    },
  },
  {
    id: "projects",
    dependsOn: ["gauges", "newspaper"],
    start() {
      bindProjectControlsV9_4();
      loadProjectsV9_4();
    },
  },
]);

App V9 5 1

A JavaScript module in the scripts folder of GlobalGrid2050.

otherglobalgrid2050 / testcode/202609051152/pipeline/scripts/app-v9-5-1.js · lines 1–31 of 31 · version 2026-09-05 11:52 · Entry point

Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 2 files: UK Renewables Pipeline — V9 5 1 Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/v9.5.1/); UK Renewables Pipeline — V9 6 1 Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/v9.6.1/). Reached from 178 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — PipelineNews Intelligence Page (globalgrid2050, https://globalgrid2050.com/pipelinenews_intelligence/202609050309/).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Loaded by the V9 5 1 page at https://globalgrid2050.com/uk_renewables_pipeline/v9.5.1/ and 1 other page.
Application
globalgrid2050 · testcode/202609051152/pipeline/scripts · JavaScript module
Uses
Gauges V9 2 (import), Newspaper V9 5 1 (import), Projects V9 5 1 (import), Plugin Host (import)
Used by
loaded by UK Renewables Pipeline — V9 5 1 Page (script src), loaded by UK Renewables Pipeline — V9 6 1 Page (script src)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/pipeline/scripts/app-v9-5-1.js:1-31 · blob 36a5c48a017158e3e13b5566261f34b905b79007 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: production_core
import { initialiseGaugesV9_2 } from "./plugins/gauges-v9-2.js";
import { bindNewspaperV9_5_1, loadNewsV9_5_1 } from "./plugins/newspaper-v9-5-1.js";
import {
  bindProjectControlsV9_5_1,
  loadProjectsV9_5_1,
  refreshProjectsV9_5_1,
} from "./plugins/projects-v9-5-1.js";
import { startPlugins } from "./core/plugin-host.js";

startPlugins([
  {
    id: "gauges",
    start: initialiseGaugesV9_2,
  },
  {
    id: "newspaper",
    dependsOn: ["gauges"],
    start() {
      bindNewspaperV9_5_1(refreshProjectsV9_5_1);
      loadNewsV9_5_1();
    },
  },
  {
    id: "projects",
    dependsOn: ["gauges", "newspaper"],
    start() {
      bindProjectControlsV9_5_1();
      loadProjectsV9_5_1();
    },
  },
]);

App V9 5

A JavaScript module in the scripts folder of GlobalGrid2050.

otherglobalgrid2050 / testcode/202609051152/pipeline/scripts/app-v9-5.js · lines 1–31 of 31 · version 2026-09-05 11:52 · Entry point

Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 1 file: UK Renewables Pipeline — V9 5 Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/v9.5/). Reached from 180 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — PipelineNews Intelligence Page (globalgrid2050, https://globalgrid2050.com/pipelinenews_intelligence/202609050309/).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Loaded by the V9 5 page at https://globalgrid2050.com/uk_renewables_pipeline/v9.5/.
Application
globalgrid2050 · testcode/202609051152/pipeline/scripts · JavaScript module
Uses
Gauges V9 2 (import), Newspaper V9 5 (import), Projects V9 5 (import), Plugin Host (import)
Used by
loaded by UK Renewables Pipeline — V9 5 Page (script src)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/pipeline/scripts/app-v9-5.js:1-31 · blob 9146bfb97803a6d5680f861d66b89f81027b0711 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: production_core
import { initialiseGaugesV9_2 } from "./plugins/gauges-v9-2.js";
import { bindNewspaperV9_5, loadNewsV9_5 } from "./plugins/newspaper-v9-5.js";
import {
  bindProjectControlsV9_5,
  loadProjectsV9_5,
  refreshProjectsV9_5,
} from "./plugins/projects-v9-5.js";
import { startPlugins } from "./core/plugin-host.js";

startPlugins([
  {
    id: "gauges",
    start: initialiseGaugesV9_2,
  },
  {
    id: "newspaper",
    dependsOn: ["gauges"],
    start() {
      bindNewspaperV9_5(refreshProjectsV9_5);
      loadNewsV9_5();
    },
  },
  {
    id: "projects",
    dependsOn: ["gauges", "newspaper"],
    start() {
      bindProjectControlsV9_5();
      loadProjectsV9_5();
    },
  },
]);

App V9 6 2

A JavaScript module in the scripts folder of GlobalGrid2050.

otherglobalgrid2050 / testcode/202609051152/pipeline/scripts/app-v9-6-2.js · lines 1–28 of 28 · version 2026-09-05 11:52 · Entry point

Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 2 files: UK Renewables Pipeline — V9 6 2 Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/v9.6.2/); PipelineNews — PipelineNews Page (pipelinenews, https://ventusltd.github.io/pipelinenews/archive/202608261547-pipelinenews/202608260159-pipelinenews/). Reached from 89 other entry points, including Grid Engine — Compute Against Charging Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060324-compute-against-charging/); Grid Engine — Connection Cap Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060212-connection-cap/); Grid Engine — Corridor Estimate Page (globalgrid2050, https://globalgrid2050.com/grid_engine/202609060237-corridor-estimate/).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Loaded by the V9 6 2 page at https://globalgrid2050.com/uk_renewables_pipeline/v9.6.2/ and 1 other page.
Application
globalgrid2050 · testcode/202609051152/pipeline/scripts · JavaScript module
Uses
Gauges V9 2 (import), Newspaper V9 6 2 (import), Projects V9 5 1 (import), Plugin Host (import)
Used by
loaded by UK Renewables Pipeline — V9 6 2 Page (script src), loaded by PipelineNews — PipelineNews Page (script src)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609051152/pipeline/scripts/app-v9-6-2.js:1-28 · blob f37e16cf9f1f0160ecc4da8f4ce7bb509330cde2 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: experimental · users: none · canonical: production_core
import { initialiseGaugesV9_2 } from "./plugins/gauges-v9-2.js";
import { bindNewspaperV9_6_2, loadNewsV9_6_2 } from "./plugins/newspaper-v9-6-2.js";
import {
  bindProjectControlsV9_5_1,
  loadProjectsV9_5_1,
  refreshProjectsV9_5_1,
} from "./plugins/projects-v9-5-1.js";
import { startPlugins } from "./core/plugin-host.js";

startPlugins([
  { id: "gauges", start: initialiseGaugesV9_2 },
  {
    id: "newspaper",
    dependsOn: ["gauges"],
    start() {
      bindNewspaperV9_6_2(refreshProjectsV9_5_1);
      loadNewsV9_6_2();
    },
  },
  {
    id: "projects",
    dependsOn: ["gauges", "newspaper"],
    start() {
      bindProjectControlsV9_5_1();
      loadProjectsV9_5_1();
    },
  },
]);