In this section
- GlobalGrid2050 Clone V4 to V5 storage · globalgrid2050 / scripts/clone_v4_to_v5.py lines 1–131
- GlobalGrid2050 Dependencies V4 render · globalgrid2050 / scripts/dependencies_v4.py lines 1–281
- GlobalGrid2050 Enrich Renewables V6 Identity storage · globalgrid2050 / scripts/enrich_renewables_v6_identity.py lines 1–146
- GlobalGrid2050 Fix V5 JS Filenames storage · globalgrid2050 / scripts/fix_v5_js_filenames.py lines 1–54
GlobalGrid2050 Clone V4 to V5
A Python command-line tool in the scripts folder that reads battery storage (BESS), solar, cables and substations.
storageglobalgrid2050 / scripts/clone_v4_to_v5.py · lines 1–131 of 131 · Entry point
- What it does
- It loads battery storage (BESS), solar, cables and substations. Defines main. Uses libraries pathlib, shutil, datetime. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain terms in the code: battery storage (BESS), solar, cables, substations.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Clone V4 to V5 Workflow (globalgrid2050).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Run by GlobalGrid2050 Clone V4 to V5 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- GlobalGrid2050 — Solar Battery Energy Storage System (BESS) Topology V5 Page (estate URL), Indexforgis Single-Line Diagram (SLD) V5 (estate URL), Module Layout V5 (estate URL), pathlib, shutil, datetime
- Used by
- run by GlobalGrid2050 Clone V4 to V5 Workflow (workflow run)
- Produces
- main
- Defines here
- 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/clone_v4_to_v5.py:1-131 · blob 57bbc3ed57e89c3f87cd0ae310be4ac590b4fc4b · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
from pathlib import Path
import shutil
from datetime import datetime, timezone
ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "solar-bess-topology-v4"
DST = ROOT / "solar-bess-topology-v5"
REPORT = ROOT / "gridbot_reports" / "v5_clone_from_v4_report.md"
CHANGELOG = DST / "V5_CHANGELOG_AND_ROADMAP.md"
TEXT_SUFFIXES = {".html", ".css", ".js", ".json", ".md", ".txt", ".yml", ".yaml"}
FILES = [
"indexforgis-sld", "gis-sld-config", "gis-sld-helpers", "gis-sld-state",
"gis-sld-substations", "gis-sld", "gis-sld-map", "gis-sld-calculations",
"gis-sld-finance", "gis-sld-ui-core", "gis-sld-drawing", "gis-sld-export",
"gis-sld-ui", "module-layout"
]
RENAME_PAIRS = []
for name in FILES:
if name == "gis-sld":
RENAME_PAIRS.append(("gis-sld-v4.css", "gis-sld-v5.css"))
elif name == "module-layout":
RENAME_PAIRS.extend([
("module-layout-v4.html", "module-layout-v5.html"),
("module-layout-v4.css", "module-layout-v5.css"),
("module-layout-v4.js", "module-layout-v5.js"),
])
else:
ext = ".html" if name == "indexforgis-sld" else ".js"
RENAME_PAIRS.append((f"{name}-v4{ext}", f"{name}-v5{ext}"))
TEXT_REPLACE_PAIRS = [("solar-bess-topology-v4", "solar-bess-topology-v5"), ("V4", "V5"), ("v4", "v5")]
CHANGELOG_TEXT = """# GlobalGrid2050 V5 Change Record and Roadmap
UTC created: {created_at}
## Purpose
V5 is cloned from the stabilised V4 application so V4 can remain available for users while future development continues in a separate working version.
V4 is now the public user baseline. V5 is the development track.
## V3 baseline
V3 was the first serious modular version of the GIS SLD Financial Sandbox. It separated the application into HTML, CSS and multiple JavaScript files. It established map display, substation reference data, string inverter topology, central inverter topology, technical quantity outputs, logistics estimates, baseline project economics, GeoJSON export and the separate physical module layout page.
## What changed in V4
V4 was created by cloning V3 into a new folder and renaming the main files and references from V3 to V4. V4 then became a separate deployable version. It retained the modular structure but added stronger project qualification language, expanded Financial Model Logic, a detailed screening disclaimer, a stronger GeoJSON export note and a CSS fix so the cyan explainer box could display the long discl … [line shortened here: 415 characters; full line on GitHub]
## Why V4 changed
The sandbox had moved beyond a visual prototype. It now combines land, grid proximity, topology, cable assumptions, BESS assumptions, CAPEX, revenue and exportable GIS context. That means users need clear boundaries. V4 explains that the tool is for early stage screening and learning, not construction design, grid approval, EPC pricing, financial advice or bankable technical due diligence.
## Possible V5 projects
1. Add a V5 development badge and a link back to stable V4.
2. Make long explainer and disclaimer sections collapsible.
3. Add scenario save and load using JSON.
4. Improve cashflow, profit and risk adjusted financial terminology.
5. Add project comparison mode.
6. Improve BESS modelling.
7. Add clearer cable loss and cable route cost assumptions.
8. Improve GeoJSON export structure.
9. Add CSV export.
10. Add report export.
11. Add public data source provenance notes.
12. Add validation warnings for unusual engineering or financial assumptions.
13. Use GridBot feature manifests for all future V5 changes.
## Governance principle
V4 remains stable for users. V5 is where new ideas are tested, documented and only later promoted when useful, stable and approved.
"""
def main():
if not SRC.exists():
raise SystemExit(f"Source folder missing: {SRC}")
if DST.exists():
shutil.rmtree(DST)
shutil.copytree(SRC, DST)
renamed = []
for old, new in RENAME_PAIRS:
old_path = DST / old
new_path = DST / new
if old_path.exists():
old_path.rename(new_path)
renamed.append((old, new))
changed_files = []
for path in DST.rglob("*"):
if path.is_file() and path.suffix.lower() in TEXT_SUFFIXES:
text = path.read_text(encoding="utf-8")
original = text
for old, new in TEXT_REPLACE_PAIRS:
text = text.replace(old, new)
if text != original:
path.write_text(text, encoding="utf-8")
changed_files.append(str(path.relative_to(ROOT)))
created_at = datetime.now(timezone.utc).isoformat()
CHANGELOG.write_text(CHANGELOG_TEXT.format(created_at=created_at), encoding="utf-8")
files = sorted(str(p.relative_to(ROOT)) for p in DST.rglob("*") if p.is_file())
REPORT.parent.mkdir(parents=True, exist_ok=True)
report = [
"# V5 Clone from V4 Report", "", f"UTC created: {created_at}", "",
"Source: solar-bess-topology-v4/", "Destination: solar-bess-topology-v5/", "",
"Main V5 URLs after GitHub Pages deploy:", "",
"https://globalgrid2050.com/solar-bess-topology-v5/",
"https://globalgrid2050.com/solar-bess-topology-v5/indexforgis-sld-v5.html",
"https://globalgrid2050.com/solar-bess-topology-v5/module-layout-v5.html", "",
"Change record: solar-bess-topology-v5/V5_CHANGELOG_AND_ROADMAP.md", "",
"Renamed files:", "",
]
report.extend(f"- {old} -> {new}" for old, new in renamed)
report.extend(["", "Files with V4 to V5 text references updated:", ""])
report.extend(f"- {f}" for f in changed_files)
report.extend(["", "Files cloned:", ""])
report.extend(f"- {f}" for f in files)
report.extend(["", "Rollback: delete solar-bess-topology-v5/ and this report. V4 remains untouched."])
REPORT.write_text("\n".join(report) + "\n", encoding="utf-8")
if __name__ == "__main__":
main()GlobalGrid2050 Dependencies V4
A Python command-line tool in the scripts folder that reads live grid energy, live grid price, electricity price history and live oil prices.
renderglobalgrid2050 / scripts/dependencies_v4.py · lines 1–281 of 281 · Entry point · pattern exists (shared by 14 files)
- What it does
- It loads live grid energy, live grid price, electricity price history and live oil prices. Defines 13 functions or classes, including read_text, exists, count_csv_rows, csv_years, json_row_count. Uses libraries __future__, csv, json, re, pathlib. Side effects: changes the web page (DOM); reads or writes files.
- Inputs & outputs
- In: JSON file dependencies_v4.json; JSON file live_grid_energy.json; JSON file live_grid_price.json; JSON file electricity_price_history.json; CSV file electricity_price_history.csv; JSON file live_oil_prices.json; GeoJSON file oil_price_history.geojson; JSON file live_uk_fuel_prices.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Dependencies V4 Workflow (globalgrid2050).
- What it achieves
- It extracts script refs (`extract_script_refs`) and is built from the CSV years helper (`csv_years`) and the JSON row count helper (`json_row_count`). Defines `read_text`, `exists`, `count_csv_rows` and 9 more.
- Why it matters
- Run by GlobalGrid2050 Dependencies V4 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, csv, json, re, pathlib, typing
- Used by
- run by GlobalGrid2050 Dependencies V4 Workflow (workflow run)
- Produces
- read_text, exists, count_csv_rows, csv_years, json_row_count, annual_files, extract_script_refs, extract_css_refs, has_id, status, warn, line
- Defines here
- read_text, exists, count_csv_rows, csv_years, json_row_count, annual_files, extract_script_refs, extract_css_refs, has_id, status, warn, line, 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/dependencies_v4.py:1-281 · blob f51f64799f658747cd923dec6bcd83c62afb0489 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: production_core
from __future__ import annotations
import csv
import json
import re
from pathlib import Path
from typing import Iterable
ROOT = Path('.')
V3 = ROOT / 'uk_energy_tracking_v3'
V4 = ROOT / 'uk_energy_tracking_v4'
REPORT = ROOT / 'gridbot_reports' / 'dependencies_v4.md'
JSON_REPORT = ROOT / 'gridbot_reports' / 'dependencies_v4.json'
V4_FILES = {
'page': V4 / 'index.md',
'css': V4 / 'price-history-ui.css',
'price_ui_js': V4 / 'price-history-ui.js',
'fullscreen_js': V4 / 'price-history-fullscreen.js',
'live_energy': V4 / 'live_grid_energy.json',
'live_price': V4 / 'live_grid_price.json',
'price_history_json': V4 / 'electricity_price_history.json',
'price_history_csv': V4 / 'electricity_price_history.csv',
'oil_json': V4 / 'live_oil_prices.json',
'oil_history': V4 / 'oil_price_history.geojson',
'fuel_json': V4 / 'live_uk_fuel_prices.json',
'ev_json': V4 / 'ev_charging_prices.json',
}
SCRIPT_FILES = {
'energy_updater': ROOT / 'scripts' / 'update_uk_energy_v4.py',
'price_updater': ROOT / 'scripts' / 'update_uk_price_v4.py',
'oil_updater': ROOT / 'scripts' / 'update_oil_prices_v4.py',
'fuel_updater': ROOT / 'scripts' / 'update_uk_fuel_prices_v4.py',
'elexon_master_downloader': ROOT / 'scripts' / 'download_elexon_system_prices.py',
'elexon_annual_splitter': ROOT / 'scripts' / 'split_elexon_system_prices_by_year.py',
}
DATA_FILES = {
'elexon_master_csv': ROOT / 'data' / 'electricity' / 'elexon_system_prices_half_hourly.csv',
}
EXPECTED_DOM_IDS = [
'price-history-range',
'price-history-from',
'price-history-to',
'price-history-clear-dates',
'price-history-canvas',
'price-history-table-body',
'price-history-fullscreen-btn',
'price-history-fullscreen-overlay',
'price-history-fullscreen-canvas',
]
HAZARD_SELECT_VALUES = ['10y', 'all']
MAX_SAFE_VISIBLE_ROWS = 20000
def read_text(path: Path) -> str:
if not path.exists():
return ''
try:
return path.read_text(encoding='utf-8')
except UnicodeDecodeError:
return ''
def exists(path: Path) -> bool:
return path.exists() and path.is_file()
def count_csv_rows(path: Path) -> int:
if not exists(path):
return 0
try:
with path.open('r', encoding='utf-8', newline='') as handle:
return max(0, sum(1 for _ in handle) - 1)
except Exception:
return 0
def csv_years(path: Path) -> list[str]:
years: set[str] = set()
if not exists(path):
return []
try:
with path.open('r', encoding='utf-8', newline='') as handle:
reader = csv.DictReader(handle)
for row in reader:
value = (row.get('settlementDate') or row.get('periodStartUTC') or '').strip()
if len(value) >= 4 and value[:4].isdigit():
years.add(value[:4])
except Exception:
pass
return sorted(years)
def json_row_count(path: Path) -> int:
if not exists(path):
return 0
try:
data = json.loads(path.read_text(encoding='utf-8'))
if isinstance(data, dict) and isinstance(data.get('rows'), list):
return len(data['rows'])
if isinstance(data, list):
return len(data)
except Exception:
pass
return 0
def annual_files() -> list[Path]:
folder = ROOT / 'data' / 'electricity'
if not folder.exists():
return []
return sorted(folder.glob('elexon_system_prices_20*.csv'))
def extract_script_refs(page_text: str) -> list[str]:
return re.findall(r'<script[^>]+src=[\"\']([^\"\']+)[\"\']', page_text)
def extract_css_refs(page_text: str) -> list[str]:
return re.findall(r'<link[^>]+href=[\"\']([^\"\']+)[\"\']', page_text)
def has_id(page_text: str, dom_id: str) -> bool:
return f'id="{dom_id}"' in page_text or f"id='{dom_id}'" in page_text
def status(ok: bool) -> str:
return 'PASS' if ok else 'FAIL'
def warn(ok: bool) -> str:
return 'OK' if ok else 'WARN'
def line(items: Iterable[str]) -> str:
return '\n'.join(items)
def main() -> None:
page = read_text(V4_FILES['page'])
price_js = read_text(V4_FILES['price_ui_js'])
fullscreen_js = read_text(V4_FILES['fullscreen_js'])
checks: list[dict[str, object]] = []
warnings: list[str] = []
for name, path in V4_FILES.items():
checks.append({'group': 'v4_files', 'name': name, 'path': str(path), 'status': status(exists(path))})
for name, path in SCRIPT_FILES.items():
checks.append({'group': 'scripts', 'name': name, 'path': str(path), 'status': status(exists(path))})
script_refs = extract_script_refs(page)
css_refs = extract_css_refs(page)
for ref in script_refs:
local = ROOT / ref.split('?')[0].lstrip('/')
checks.append({'group': 'page_script_refs', 'name': ref, 'path': str(local), 'status': status(local.exists())})
for ref in css_refs:
local = ROOT / ref.split('?')[0].lstrip('/')
checks.append({'group': 'page_css_refs', 'name': ref, 'path': str(local), 'status': status(local.exists())})
for dom_id in EXPECTED_DOM_IDS:
checks.append({'group': 'dom_ids', 'name': dom_id, 'path': 'uk_energy_tracking_v4/index.md', 'status': status(has_id(page, dom_id))})
v3_leaks = []
for name, path in V4_FILES.items():
text = read_text(path)
if 'uk_energy_tracking_v3' in text or '/uk_energy_tracking_v3/' in text:
v3_leaks.append(str(path))
checks.append({'group': 'path_isolation', 'name': 'no V3 path leaks inside V4 files', 'path': 'uk_energy_tracking_v4', 'status': status(not v3_leaks), 'details': v3_leaks})
master_rows = count_csv_rows(DATA_FILES['elexon_master_csv'])
captured_rows = json_row_count(V4_FILES['price_history_json'])
annual = annual_files()
annual_counts = {p.name: count_csv_rows(p) for p in annual}
load_master = 'elexon_system_prices_half_hourly.csv' in price_js
has_annual_loader = 'elexon_system_prices_' in price_js and '<year>' not in price_js
has_10y = 'value="10y"' in page or '"10y"' in price_js
has_all = 'value="all"' in page or "range==='all'" in price_js
checks.append({'group': 'price_history_loading', 'name': 'main chart does not fetch full master CSV', 'path': 'uk_energy_tracking_v4/price-history-ui.js', 'status': warn(not load_master), 'details': 'Current script fetches master CSV' if load_master else 'No master CSV fetch found'})
checks.append({'group': 'price_history_loading', 'name': 'annual files exist for lazy loading', 'path': 'data/electricity/elexon_system_prices_*.csv', 'status': status(bool(annual)), 'details': annual_counts})
checks.append({'group': 'price_history_loading', 'name': '10 year selector removed before annual lazy loading', 'path': 'uk_energy_tracking_v4/index.md', 'status': warn(not has_10y), 'details': '10y option still present' if has_10y else 'No 10y option found'})
checks.append({'group': 'price_history_loading', 'name': 'all data selector removed before annual lazy loading', 'path': 'uk_energy_tracking_v4/index.md', 'status': warn(not has_all), 'details': 'all option still present' if has_all else 'No all option found'})
if load_master and (has_10y or has_all) and master_rows > MAX_SAFE_VISIBLE_ROWS:
warnings.append('Collapse risk: V4 price-history-ui.js can load the full Elexon master CSV and the UI still exposes 10y or all data ranges. This can crash mobile Safari and make the chart unreadable.')
if 'window.__v4PriceHistoryState' in price_js and '__v4PriceHistoryState' not in fullscreen_js:
warnings.append('Fullscreen and inline state may be out of sync. The full screen script should use the same loaded snapshot as the inline chart.')
report = []
report.append('# V4 Dependency Diagnostics')
report.append('')
report.append('Purpose: map all V4 page, script, data and workflow dependencies that must remain in sync before any modularisation or lazy loading patch is applied.')
report.append('')
report.append('## Executive diagnosis')
report.append('')
if warnings:
for item in warnings:
report.append(f'- WARNING: {item}')
else:
report.append('- No immediate collapse warning detected by static diagnostics.')
report.append('')
report.append('## Data scale')
report.append('')
report.append(f'- Elexon master CSV rows: {master_rows}')
report.append(f'- V4 captured price JSON rows: {captured_rows}')
report.append(f'- Elexon master CSV years: {", ".join(csv_years(DATA_FILES["elexon_master_csv"])) or "not detected"}')
report.append(f'- Annual Elexon files found: {len(annual)}')
for name, rows in annual_counts.items():
report.append(f' - {name}: {rows} rows')
report.append('')
report.append('## Dependency graph')
report.append('')
report.append('```text')
report.append('uk_energy_tracking_v4/index.md')
report.append(' -> /uk_energy_tracking_v4/price-history-ui.css')
report.append(' -> /uk_energy_tracking_v4/price-history-ui.js')
report.append(' -> /uk_energy_tracking_v4/electricity_price_history.json')
report.append(' -> /data/electricity/elexon_system_prices_half_hourly.csv OR annual CSVs')
report.append(' -> DOM ids: price-history-range, price-history-from, price-history-to, price-history-canvas, price-history-table-body')
report.append(' -> /uk_energy_tracking_v4/price-history-fullscreen.js')
report.append(' -> window.__v4PriceHistoryState from price-history-ui.js')
report.append(' -> /uk_energy_tracking_v4/live_grid_energy.json')
report.append(' -> /uk_energy_tracking_v4/live_grid_price.json')
report.append(' -> /uk_energy_tracking_v4/live_oil_prices.json')
report.append(' -> /uk_energy_tracking_v4/live_uk_fuel_prices.json')
report.append(' -> /uk_energy_tracking_v4/ev_charging_prices.json')
report.append('scripts/update_uk_energy_v4.py -> live_grid_energy.json')
report.append('scripts/update_uk_price_v4.py -> live_grid_price.json and captured electricity history')
report.append('scripts/update_oil_prices_v4.py -> oil price files')
report.append('scripts/update_uk_fuel_prices_v4.py -> fuel price file')
report.append('scripts/download_elexon_system_prices.py -> data/electricity/elexon_system_prices_half_hourly.csv')
report.append('scripts/split_elexon_system_prices_by_year.py -> data/electricity/elexon_system_prices_YEAR.csv')
report.append('```')
report.append('')
report.append('## Checks')
report.append('')
report.append('| Group | Item | Status | Path |')
report.append('|---|---:|---:|---|')
for c in checks:
report.append(f"| {c['group']} | {c['name']} | {c['status']} | `{c['path']}` |")
report.append('')
report.append('## Why the lazy loading patch failed')
report.append('')
report.append('The failed V3 lazy loading patch changed too many coupled layers at once: the visible controls, the chart data source, the range logic, full screen behaviour and attribution text. The inline chart and full screen chart had separate JavaScript logic, so one could be corrected while the other stayed stale. The page also still had a path where the master 2016 to present Elexon CSV … [line shortened here: 699 characters; full line on GitHub]
report.append('')
report.append('## Modularisation sequence for V4')
report.append('')
report.append('1. Run this dependency diagnostic and compare V4 against V3 before every patch.')
report.append('2. Extract only CSS from inline style into a V4 stylesheet, with no behaviour change.')
report.append('3. Extract price history JavaScript into modules: data loading, range selection, chart drawing, table rendering and full screen rendering.')
report.append('4. Make full screen consume the same state object as the inline chart. No separate fetch path.')
report.append('5. Add annual lazy loading after the module boundary exists.')
report.append('6. Only then add year, season and explanatory text controls.')
report.append('')
report.append('## Rule')
report.append('')
report.append('Patch V4 only. V3 remains the benchmark.')
report.append('')
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text('\n'.join(report), encoding='utf-8')
JSON_REPORT.write_text(json.dumps({'checks': checks, 'warnings': warnings, 'data': {'master_rows': master_rows, 'captured_rows': captured_rows, 'annual_files': annual_counts}}, indent=2), encoding='utf-8')
failed = [c for c in checks if c['status'] == 'FAIL']
print(f'Wrote {REPORT}')
print(f'Warnings: {len(warnings)}')
print(f'Failures: {len(failed)}')
if warnings:
for item in warnings:
print('WARNING:', item)
if __name__ == '__main__':
main()GlobalGrid2050 Enrich Renewables V6 Identity
A Python command-line tool in the scripts folder that reads project identity, major projects, major project news and project news links, using SHA-256.
storageglobalgrid2050 / scripts/enrich_renewables_v6_identity.py · lines 1–146 of 146 · Entry point · pattern clean (shared by 37 files)
- What it does
- It loads project identity, major projects, major project news and project news links. Defines clean, norm, article_id, load, main. Uses libraries __future__, hashlib, json, re, datetime. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'renewables'): 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.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Major Project News V6 Workflow (globalgrid2050).
- What it achieves
- It is built from the load step (`load`). Defines `clean`, `norm`, `article_id` and 1 more.
- Why it matters
- Run by GlobalGrid2050 Major Project News V6 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, hashlib, json, re, datetime, pathlib
- Used by
- run by GlobalGrid2050 Major Project News V6 Workflow (workflow run)
- Produces
- clean, norm, article_id, load, main
- Defines here
- clean, norm, article_id, load, 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/enrich_renewables_v6_identity.py:1-146 · blob b8ef4c00c9c3fe17a661dcaa256b0e73a44dc235 · 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: production_core
#!/usr/bin/env python3
from __future__ import annotations
import hashlib
import json
import re
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"
def clean(v):
return str(v or "").strip()
def norm(v):
return re.sub(r"\s+", " ", re.sub(r"[^a-z0-9]+", " ", clean(v).lower())).strip()
def article_id(item):
# Stable across Google News redirect URL churn: headline/source/publication date are the anchor.
key = "|".join((norm(item.get("headline")), norm(item.get("source")), clean(item.get("published"))))
return "GG2050-NEWS-" + hashlib.sha256(key.encode("utf-8")).hexdigest()[:16].upper()
def load(path):
if not path.exists():
raise RuntimeError(f"Missing required V6 artifact: {path.relative_to(ROOT)}")
return json.loads(path.read_text(encoding="utf-8"))
def main():
identity = load(IDENTITY)
projects = load(PROJECTS)
news = load(NEWS)
records = identity.get("records") or []
by_ref = {clean(r.get("repd_ref")): r for r in records if clean(r.get("repd_ref"))}
eligible_refs = {clean(p.get("repd_ref")) for p in (projects.get("projects") or []) if clean(p.get("repd_ref"))}
if not by_ref:
raise RuntimeError("Identity registry has no REPD-bound records")
for project in projects.get("projects") or []:
ref = clean(project.get("repd_ref"))
record = by_ref.get(ref)
if not record:
raise RuntimeError(f"Eligible V6 project has no canonical identity: REPD {ref} {project.get('name')}")
if project.get("gg_project_id") != record.get("gg_project_id"):
raise RuntimeError(f"Eligible V6 project ID differs from registry: REPD {ref}")
if project.get("gg_development_id") != record.get("gg_development_id"):
raise RuntimeError(f"Eligible V6 development ID differs from registry: REPD {ref}")
links = []
seen_article_ids = set()
for item in news.get("items") or []:
ref = clean(item.get("repd_ref"))
record = by_ref.get(ref)
if not record:
raise RuntimeError(f"Headline has no canonical REPD/GlobalGrid identity: {ref} {item.get('headline')}")
if ref not in eligible_refs:
raise RuntimeError(f"Headline primary match is outside the V6 threshold universe: REPD {ref}")
aid = article_id(item)
if aid in seen_article_ids:
# The newspaper should already dedupe exact headlines. Treat a collision as a data defect.
raise RuntimeError(f"Duplicate canonical article ID: {aid} {item.get('headline')}")
seen_article_ids.add(aid)
item["gg_article_id"] = aid
item["gg_project_id"] = record["gg_project_id"]
item["gg_development_id"] = record["gg_development_id"]
item["identity_status"] = record["identity_status"]
item["primary_repd_ref"] = ref
item["development_related_repd_refs"] = [
r for r in (record.get("development_repd_refs") or []) if r != ref and r in eligible_refs
]
item["direct_related_repd_refs"] = [
r for r in (record.get("direct_related_repd_refs") or []) if r != ref
]
item["news_binding_rule"] = "PRIMARY_MATCH_ONLY; related development records are context, not REPD/news-status confirmation"
links.append(
{
"gg_article_id": aid,
"gg_project_id": record["gg_project_id"],
"gg_development_id": record["gg_development_id"],
"repd_ref": ref,
"role": "PRIMARY_MATCH",
"eligible_for_news_signal": True,
"confidence": item.get("confidence"),
}
)
for related_ref in item["development_related_repd_refs"]:
related = by_ref[related_ref]
links.append(
{
"gg_article_id": aid,
"gg_project_id": related["gg_project_id"],
"gg_development_id": related["gg_development_id"],
"repd_ref": related_ref,
"role": "RELATED_DEVELOPMENT",
"eligible_for_news_signal": False,
"confidence": None,
}
)
news["identity_schema"] = identity.get("schema")
news["globalgrid_id_required"] = True
news["news_signal_scope"] = "Only PRIMARY_MATCH links may drive NEWS SIGNAL; RELATED_DEVELOPMENT is context only"
NEWS.write_text(json.dumps(news, indent=2), encoding="utf-8")
LINKS.write_text(
json.dumps(
{
"schema": "globalgrid2050.project-news-links.v6",
"generated_at": datetime.now(timezone.utc).isoformat(),
"identity_schema": identity.get("schema"),
"article_count": len(seen_article_ids),
"link_count": len(links),
"primary_link_count": sum(1 for x in links if x["role"] == "PRIMARY_MATCH"),
"related_development_link_count": sum(1 for x in links if x["role"] == "RELATED_DEVELOPMENT"),
"rules": {
"one_primary_match_per_article": True,
"primary_match_drives_news_signal": True,
"related_development_drives_news_signal": False,
"related_development_never_confirms_repd_status": True,
"article_display_is_deduplicated": True,
},
"links": links,
},
indent=2,
),
encoding="utf-8",
)
print("identity enrichment", f"projects={len(projects.get('projects') or [])}", f"articles={len(seen_article_ids)}", f"links={len(links)}")
if __name__ == "__main__":
main()GlobalGrid2050 Fix V5 JS Filenames
A Python command-line tool in the scripts folder.
storageglobalgrid2050 / scripts/fix_v5_js_filenames.py · lines 1–54 of 54 · Entry point
- What it does
- Defines main. Uses libraries pathlib, datetime, shutil. Side effects: reads or writes files.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Fix V5 JS Filenames Workflow (globalgrid2050).
- 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
- Run by GlobalGrid2050 Fix V5 JS Filenames Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- pathlib, datetime, shutil
- Used by
- run by GlobalGrid2050 Fix V5 JS Filenames Workflow (workflow run)
- Produces
- main
- Defines here
- 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/fix_v5_js_filenames.py:1-54 · blob 420f1a227bd6df28fcf1edaaad1d03d1005cf41d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
from pathlib import Path
from datetime import datetime, timezone
import shutil
ROOT = Path(__file__).resolve().parents[1]
V5 = ROOT / "solar-bess-topology-v5"
REPORT = ROOT / "gridbot_reports" / "v5_js_filename_repair.md"
SUFFIXES = [
"config",
"helpers",
"state",
"substations",
"map",
"calculations",
"finance",
"ui-core",
"drawing",
"export",
"ui",
]
def main():
if not V5.exists():
raise SystemExit(f"Missing V5 folder: {V5}")
actions = []
for suffix in SUFFIXES:
src = V5 / f"gis-sld-v4-{suffix}.js"
dst = V5 / f"gis-sld-v5-{suffix}.js"
if src.exists():
shutil.copyfile(src, dst)
actions.append(f"copied {src.name} to {dst.name}")
elif dst.exists():
actions.append(f"already present {dst.name}")
else:
actions.append(f"missing both source and target for {suffix}")
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text(
"# V5 JavaScript Filename Repair\n\n"
f"UTC created: {datetime.now(timezone.utc).isoformat()}\n\n"
"Purpose:\n"
"Repair V5 clone filename mismatch where the V5 HTML referenced gis-sld-v5 JavaScript files but the clone retained several gis-sld-v4 JavaScript filenames inside the V5 folder.\n\n"
"Actions:\n\n"
+ "\n".join(f"- {a}" for a in actions)
+ "\n\nResult:\nThe V5 HTML dependency chain should now resolve against V5 named JavaScript files. V4 remains untouched.\n",
encoding="utf-8"
)
if __name__ == "__main__":
main()