GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / globalgrid2050 / scripts

GlobalGrid2050 Gridbot Root Homepage Directory Audit and 1 more file

A Python command-line tool in the scripts folder that extracts menu block (`extract_menu_block`) and script (`extract_script`) and renders report (`render_report`), covering solar, battery storage (BESS) and cables, using SHA-256.

700 lines of Python from globalgrid2050, in 2 files. Topic: Automation and CI. Section 1767 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 Gridbot Repo Split Inventory storage · globalgrid2050 / scripts/gridbot_repo_split_inventory.py lines 1–313
  2. GlobalGrid2050 Gridbot Root Homepage Directory Audit render · globalgrid2050 / scripts/gridbot_root_homepage_directory_audit.py lines 1–387

GlobalGrid2050 Gridbot Repo Split Inventory

A Python command-line tool in the scripts folder that classifies file (`classify_file`) and writes reports (`write_reports`).

storageglobalgrid2050 / scripts/gridbot_repo_split_inventory.py · lines 1–313 of 313 · Entry point · pattern classify_file (shared by 2 files)

What it does
It loads data. Defines 11 functions or classes, including utc_now, stamp, rel, git_head, should_skip_dir. Uses libraries __future__, argparse, datetime, json, subprocess. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Repo Split Inventory Workflow (globalgrid2050).
What it achieves
It is built from the utc now helper (`utc_now`), the stamp step (`stamp`) and the rel step (`rel`). Audit-only script. It scans the current working tree, estimates folder/file weight, classifies likely app boundaries, and writes human + machine reports. It accepts `--warn-mb` and `--fail-mb`.
Why it matters
Run by GlobalGrid2050 Gridbot Repo Split Inventory Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, json, subprocess, collections, pathlib, typing
Used by
run by GlobalGrid2050 Gridbot Repo Split Inventory Workflow (workflow run)
Produces
utc_now, stamp, rel, git_head, should_skip_dir, iter_files, mb, classify_file, scan, write_reports, main
Defines here
utc_now, stamp, rel, git_head, should_skip_dir, iter_files, mb, classify_file, scan, write_reports, 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/gridbot_repo_split_inventory.py:1-313 · blob b4b65671737d191253bc46d96aed6bf8eb0a976f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""GridBot repo split inventory.

Audit-only script. It scans the current working tree, estimates folder/file weight,
classifies likely app boundaries, and writes human + machine reports. It does not
move, delete, rewrite history or create repositories.
"""
from __future__ import annotations

import argparse
import datetime as dt
import json
import subprocess
from collections import defaultdict
from pathlib import Path
from typing import Any

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

EXCLUDE_DIRS = {
    ".git",
    ".github/.cache",
    ".jekyll-cache",
    ".bundle",
    "_site",
    "node_modules",
    "__pycache__",
    ".venv",
    "venv",
    "env",
}

APP_TARGETS = [
    {
        "app": "Generation History",
        "sourcePath": "uk_energy_tracking_v6/generation_history",
        "targetRepo": "globalgrid2050-generation-history",
        "priority": 1,
        "rule": "move app code and compact confirmed JSON only; exclude raw FUELHH shards",
    },
    {
        "app": "UK Energy Tracking shell",
        "sourcePath": "uk_energy_tracking_v6",
        "targetRepo": "globalgrid2050-uk-energy-tracking",
        "priority": 2,
        "rule": "move app shell after Generation History is isolated",
    },
    {
        "app": "UK Renewables Pipeline",
        "sourcePath": "uk_renewables_pipeline",
        "targetRepo": "globalgrid2050-uk-renewables-pipeline",
        "priority": 3,
        "rule": "move clean project facts; keep heavy GIS/raw basemaps outside normal app repo",
    },
    {
        "app": "Estimators",
        "sourcePath": "estimators",
        "targetRepo": "globalgrid2050-estimators",
        "priority": 4,
        "rule": "move calculator apps and small reference tables only",
    },
]

RAW_OR_COLD_PREFIXES = (
    "data/raw/",
    "data/transient/",
    "data/tmp/",
    "data/temp/",
    "data/generation/fuelhh_halfhourly/",
    "cold_storage/",
    "external_archives/",
)

LIKELY_BULK_EXTENSIONS = {".csv", ".geojson", ".json", ".parquet", ".zip", ".7z", ".gz"}


def utc_now() -> str:
    return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")


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


def rel(path: Path) -> str:
    return path.relative_to(ROOT).as_posix()


def git_head() -> str:
    try:
        return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
    except Exception:
        return ""


def should_skip_dir(path: Path) -> bool:
    r = rel(path) if path != ROOT else ""
    if path.name in EXCLUDE_DIRS:
        return True
    return r in EXCLUDE_DIRS


def iter_files() -> list[Path]:
    out: list[Path] = []
    for path in ROOT.rglob("*"):
        if path.is_dir():
            continue
        parts = set(path.relative_to(ROOT).parts)
        if parts & EXCLUDE_DIRS:
            continue
        out.append(path)
    return out


def mb(size: int) -> float:
    return round(size / 1024 / 1024, 3)


def classify_file(r: str) -> dict[str, Any]:
    destination = "KEEP_IN_MAIN_UNTIL_APP_SPLIT"
    reason = "default repository content"
    target_repo = "globalgrid2050"

    if r.startswith(RAW_OR_COLD_PREFIXES):
        destination = "MOVE_TO_COLD_ARCHIVE_OR_REGENERATE"
        reason = "raw/transient/cold data path"
        target_repo = "external-cold-archive"
    elif r.startswith("data/confirmed/"):
        destination = "COPY_COMPACT_FACT_TO_RELEVANT_APP"
        reason = "confirmed fact layer can be copied selectively"
        target_repo = "app-specific"
    elif r.startswith("data/generation/"):
        destination = "REVIEW_FOR_ARCHIVE_OR_COMPACT_FACT"
        reason = "generation data path; only compact confirmed facts belong in app repos"
        target_repo = "app-specific-or-cold-archive"
    elif r.startswith("data_science_protocol/"):
        destination = "KEEP_IN_MAIN_AND_COPY_RELEVANT_DOCS"
        reason = "doctrine and audit reports"
        target_repo = "globalgrid2050"
    elif r.startswith(".github/workflows/") or r.startswith("scripts/"):
        destination = "REWRITE_AS_APP_LOCAL_PIPELINE_IF_NEEDED"
        reason = "automation must be copied only when owned by the target app"
        target_repo = "app-specific"
    else:
        for app in APP_TARGETS:
            source = app["sourcePath"].rstrip("/") + "/"
            if r == app["sourcePath"] or r.startswith(source):
                destination = "MOVE_TO_APP_REPO"
                reason = app["rule"]
                target_repo = app["targetRepo"]
                break

    return {"destination": destination, "targetRepo": target_repo, "reason": reason}


def scan(warn_mb: float, fail_mb: float) -> dict[str, Any]:
    files = iter_files()
    top_files = []
    dir_sizes: dict[str, int] = defaultdict(int)
    classifications: dict[str, Any] = defaultdict(lambda: {"files": 0, "bytes": 0})
    red_flags = []

    for path in files:
        try:
            size = path.stat().st_size
        except FileNotFoundError:
            continue
        r = rel(path)
        top_files.append({"path": r, "sizeBytes": size, "sizeMB": mb(size), **classify_file(r)})
        parts = r.split("/")
        for depth in (1, 2, 3):
            if len(parts) >= depth:
                dir_sizes["/".join(parts[:depth])] += size
        c = classify_file(r)
        key = c["destination"]
        classifications[key]["files"] += 1
        classifications[key]["bytes"] += size
        if size >= fail_mb * 1024 * 1024:
            red_flags.append({"severity": "fail_threshold", "path": r, "sizeMB": mb(size), "detail": f"file is >= {fail_mb} MB"})
        elif size >= warn_mb * 1024 * 1024:
            red_flags.append({"severity": "warn_threshold", "path": r, "sizeMB": mb(size), "detail": f"file is >= {warn_mb} MB"})
        if r.startswith(RAW_OR_COLD_PREFIXES):
            red_flags.append({"severity": "raw_or_cold_path", "path": r, "sizeMB": mb(size), "detail": "raw/cold path should not remain in normal app repos"})
        if path.suffix.lower() in LIKELY_BULK_EXTENSIONS and size >= warn_mb * 1024 * 1024:
            red_flags.append({"severity": "bulk_file_review", "path": r, "sizeMB": mb(size), "detail": "large data-like artifact needs owner and tier"})

    top_files = sorted(top_files, key=lambda x: x["sizeBytes"], reverse=True)[:80]
    top_dirs = sorted(
        [{"path": k, "sizeBytes": v, "sizeMB": mb(v)} for k, v in dir_sizes.items()],
        key=lambda x: x["sizeBytes"],
        reverse=True,
    )[:80]

    app_summaries = []
    for app in APP_TARGETS:
        p = ROOT / app["sourcePath"]
        size = 0
        count = 0
        if p.exists():
            for f in p.rglob("*"):
                if f.is_file():
                    try:
                        size += f.stat().st_size
                        count += 1
                    except FileNotFoundError:
                        pass
        app_summaries.append({**app, "exists": p.exists(), "fileCount": count, "sizeBytes": size, "sizeMB": mb(size)})

    summary = {
        "fileCount": len(files),
        "workingTreeBytes": sum(x["sizeBytes"] for x in top_files) if False else sum((p.stat().st_size for p in files if p.exists()), 0),
        "workingTreeMB": mb(sum((p.stat().st_size for p in files if p.exists()), 0)),
        "classificationSummary": {
            k: {"files": v["files"], "sizeBytes": v["bytes"], "sizeMB": mb(v["bytes"])} for k, v in classifications.items()
        },
    }

    return {
        "reportTitle": "Repo Split Inventory",
        "schemaVersion": "1.0.0",
        "generatedUTC": utc_now(),
        "repository": "Ventusltd/globalgrid2050",
        "branch": "main",
        "gitHead": git_head(),
        "mode": "audit",
        "applied": False,
        "pass": True,
        "warnMB": warn_mb,
        "failMB": fail_mb,
        "summary": summary,
        "appTargets": app_summaries,
        "topDirectories": top_dirs,
        "topFiles": top_files,
        "redFlags": red_flags[:300],
        "nextActions": [
            "Review topDirectories and appTargets.",
            "Bootstrap app repositories with GridBot App Repo Bootstrap in audit mode first.",
            "Migrate Generation History first using clean-copy migration, not history-preserving clone.",
            "Move raw/cold data outside normal app repos or regenerate through GitHub Actions.",
            "Only after app routes are verified, remove moved app folders from the main repo at HEAD.",
        ],
    }


def write_reports(payload: dict[str, Any]) -> None:
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    s = stamp()
    lines = [
        "# Repo Split Inventory",
        "",
        f"Generated UTC: `{payload['generatedUTC']}`",
        f"Repository: `{payload['repository']}`",
        f"Git head: `{payload['gitHead']}`",
        f"Mode: `{payload['mode']}`",
        f"Applied: `{payload['applied']}`",
        f"Pass: `{payload['pass']}`",
        "",
        "## Working tree summary",
        "",
        f"Files scanned: `{payload['summary']['fileCount']}`",
        f"Working tree MB excluding .git/cache dirs: `{payload['summary']['workingTreeMB']}`",
        "",
        "## App targets",
        "",
        "| Priority | App | Source path | Target repo | Exists | Files | MB | Rule |",
        "|---:|---|---|---|---|---:|---:|---|",
    ]
    for app in payload["appTargets"]:
        lines.append(
            f"| {app['priority']} | {app['app']} | `{app['sourcePath']}` | `{app['targetRepo']}` | {app['exists']} | {app['fileCount']} | {app['sizeMB']} | {app['rule']} |"
        )
    lines.extend(["", "## Largest directories", "", "| Path | MB |", "|---|---:|"])
    for d in payload["topDirectories"][:30]:
        lines.append(f"| `{d['path']}` | {d['sizeMB']} |")
    lines.extend(["", "## Largest files", "", "| Path | MB | Proposed destination | Target repo |", "|---|---:|---|---|"])
    for f in payload["topFiles"][:40]:
        lines.append(f"| `{f['path']}` | {f['sizeMB']} | {f['destination']} | `{f['targetRepo']}` |")
    lines.extend(["", "## Red flags", ""])
    if payload["redFlags"]:
        for flag in payload["redFlags"][:80]:
            lines.append(f"- `{flag['severity']}` `{flag['path']}` {flag['sizeMB']} MB — {flag['detail']}")
    else:
        lines.append("No red flags above configured thresholds.")
    lines.extend(["", "## Next actions", ""])
    for action in payload["nextActions"]:
        lines.append(f"- {action}")
    lines.append("")

    md = "\n".join(lines)
    for p in (REPORT_DIR / f"{STEM}_{s}.md", REPORT_DIR / f"{STEM}_LATEST.md"):
        p.write_text(md, encoding="utf-8")
    js = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
    for p in (REPORT_JSON_DIR / f"{STEM}_{s}.json", REPORT_JSON_DIR / f"{STEM}_LATEST.json"):
        p.write_text(js, encoding="utf-8")


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--warn-mb", type=float, default=5.0)
    ap.add_argument("--fail-mb", type=float, default=25.0)
    args = ap.parse_args()
    payload = scan(args.warn_mb, args.fail_mb)
    write_reports(payload)
    print(json.dumps({"pass": payload["pass"], "workingTreeMB": payload["summary"]["workingTreeMB"], "redFlags": len(payload["redFlags"])}, indent=2))
    return 0


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

GlobalGrid2050 Gridbot Root Homepage Directory Audit

A Python command-line tool in the scripts folder that extracts menu block (`extract_menu_block`) and script (`extract_script`) and renders report (`render_report`), covering solar, battery storage (BESS) and cables, using SHA-256.

renderglobalgrid2050 / scripts/gridbot_root_homepage_directory_audit.py · lines 1–387 of 605 · Entry point · pattern changed_paths_for (shared by 2 files)

What it does
It draws solar, battery storage (BESS) and cables. Defines 20 functions or classes, including now, rel, read, write, sha256_text. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (voltage levels 33kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar, battery storage (BESS), cables, 33kV.
Inputs & outputs
In: JSON file ROOT_HOMEPAGE_DIRECTORY_AUDIT_LATEST.json; form fields (user input); command-line arguments. Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Root Homepage Directory Audit Workflow (globalgrid2050).
What it achieves
It collects state (`collect_state`) and is built from the now step (`now`) and the rel step (`rel`). Replace the current flat homepage table with the controlled grouped drawer menu supplied by Vikram, without changing data feeds, dashboards or child routes. Its code works with 33 kV. It accepts `--apply`.
Why it matters
Run by GlobalGrid2050 Gridbot Root Homepage Directory Audit Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, hashlib, json, re, subprocess, tempfile
Used by
run by GlobalGrid2050 Gridbot Root Homepage Directory Audit Workflow (workflow run)
Produces
now, rel, read, write, sha256_text, sha256_file, git_head, extract_menu_block, menu_links, table_links, extract_script, node_check
Defines here
now, rel, read, write, sha256_text, sha256_file, git_head, extract_menu_block, menu_links, table_links, extract_script, node_check, target_status, planned_files, changed_paths_for, collect_state
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/gridbot_root_homepage_directory_audit.py:1-387 · blob 757e3d5521acc0c701108eb4dd636cbfe77a3dbc · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
GridBot Root Homepage Directory Audit.

Target:
  /index.html

Purpose:
  Replace the current flat homepage table with the controlled grouped drawer menu
  supplied by Vikram, without changing data feeds, dashboards or child routes.

Audit mode:
  Reads the current root homepage, builds the proposed replacement in memory and
  writes Markdown and JSON reports only.

Apply mode:
  Writes only index.html after checks pass, then writes Markdown and JSON reports.
"""
from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import json
import re
import subprocess
import tempfile
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parent.parent
TARGET = ROOT / "index.html"
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
REPORT_MD = REPORT_DIR / "ROOT_HOMEPAGE_DIRECTORY_AUDIT_LATEST.md"
REPORT_JSON = REPORT_JSON_DIR / "ROOT_HOMEPAGE_DIRECTORY_AUDIT_LATEST.json"

ROUTE = "/"
SCRIPT_NAME = "scripts/gridbot_root_homepage_directory_audit.py"
WORKFLOW_NAME = "GridBot Root Homepage Directory Audit"
FEATURE_NAME = "ROOT_HOMEPAGE_DIRECTORY_AUDIT"
EXPECTED_LINK_COUNT = 41

EXPECTED_INDEX_HTML = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GlobalGrid2050</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  :root { color-scheme: dark; }
  html { background: #000; }
  body {
    background: #000;
    color: white;
    font-family: Courier, monospace;
    padding: 40px;
    max-width: 900px;
    margin: 0 auto;
    font-size: 20px;
    line-height: 1.6;
  }
  h1 { margin-top: 0; }

  a { color: #66ccff; text-decoration: none; }
  a:hover { text-decoration: underline; }

  .dev-status { color: #ff3333; font-weight: bold; font-size: 16px; }

  #gridSearch {
    width: 100%;
    padding: 12px;
    background: #111;
    color: white;
    border: 1px solid #444;
    font-family: Courier, monospace;
    font-size: 18px;
    margin-top: 20px;
    margin-bottom: 18px;
    box-sizing: border-box;
  }
  #gridSearch:focus { outline: none; border-color: #66ccff; }

  /* areas (top tier) */
  details.area { border-bottom: 1px solid #333; }
  details.area > summary {
    list-style: none;
    cursor: pointer;
    padding: 14px 0;
    color: #00ffff;
    font-weight: bold;
    letter-spacing: 0.5px;
  }
  details.area > summary::-webkit-details-marker { display: none; }
  details.area > summary::before { content: "[+] "; color: #00ffff; }
  details.area[open] > summary::before { content: "[\2212] "; }
  details.area > summary:hover { text-decoration: none; color: #66ffff; }

  /* drawer rows (infinite) */
  ul.drawer { list-style: none; margin: 0 0 10px; padding: 0; }
  ul.drawer li { padding: 10px 0 10px 28px; border-top: 1px solid #1c1c1c; }

  /* direct top-level links (areas with no children) */
  .toplink { display: block; padding: 14px 0; border-bottom: 1px solid #333; }

  .noresult { color: #888; padding: 20px 0; }

  .footer {
    margin-top: 60px;
    font-size: 16px;
    color: #aaaaaa;
    line-height: 1.5;
  }

  @media (max-width: 600px) {
    body { padding: 25px; font-size: 18px; }
    .footer { font-size: 14px; }
    ul.drawer li { padding-left: 20px; }
  }
</style>
</head>
<body>
<h1>GlobalGrid2050</h1>

<p>An open grid development, engineering, procurement, construction and operations platform dedicated to documenting, analysing and improving the world's electrical energy systems as they undergo rapid electrification.</p>

<input type="text" id="gridSearch" placeholder="Search everything..." autocomplete="off">

<div id="menu"></div>

<div class="footer">
  <p><strong>Disclaimer:</strong> Content provided for general technical documentation and research purposes only.</p>
</div>

<script>
/* ====================================================================== *
 *  MENU DATA  —  the only thing you edit.
 *
 *  A top-level entry is either:
 *    • an AREA with a drawer:   { name: "Pricing", children: [ ...rows ] }
 *    • a direct link:           { name: "Blog", url: "./blog/" }
 *
 *  A drawer row:   { name: "Title", url: "./path/", note: "in development" }
 *  ( note is optional; shown in red. )
 *
 *  Add a row  -> add one line to a children array.
 *  Re-group   -> move a line from one area to another.
 *  Re-order   -> areas and rows display in the order written here.
 * ====================================================================== */
const AREAS = [
  { name: "Solar & BESS Topology", children: [
    { name: "GIS SLD Topology Engine And Financial Sandbox", url: "./solar-bess-topology/indexforgis-sld.html" },
    { name: "GIS SLD Financial Sandbox V2", url: "./solar-bess-topology-v2/indexforgis-sld-v2.html" },
    { name: "GIS SLD Financial Sandbox V4", url: "./solar-bess-topology-v4/indexforgis-sld-v4.html" },
    { name: "GIS SLD Financial Sandbox V5", url: "./solar-bess-topology-v5/indexforgis-sld-v5.html" },
    { name: "Cable Geometry Visualiser V5", url: "./solar-bess-topology-v5/cable-geometry-visualiser-v5.html" },
    { name: "DC AC LV Solar PV Cable Topology Review V5", url: "./solar-bess-topology-v5/dc-ac-lv-topology-review-v5.html" },
    { name: "Physical Solar Module Layout V5", url: "./solar-bess-topology-v5/module-layout-v5.html" },
    { name: "Solar BESS Topology V6 Testing Phase", url: "./solar-bess-topology-v6/" },
    { name: "Solar BESS Topology V7 Workspace", url: "./solar-bess-topology-v7/" },
    { name: "BESS GIS SLD Financial Sandbox V8", url: "./solar-bess-topology-v8/bess-gis-sld-financial-sandbox/index.html", note: "in development" },
  ]},
  { name: "UK Grid Tracking", children: [
    { name: "UK Live Grid Tracker, Electricity, Carbon, Oil and Metals", url: "./uk_energy_tracking/" },
    { name: "UK Live Grid Tracker V2, Transport Energy Test Clone", url: "./uk_energy_tracking_v2/" },
    { name: "UK Live Grid Tracker V3, Experimental Intelligence Lab", url: "./uk_energy_tracking_v3/" },
    { name: "UK Live Grid Tracker V5, Electricity Market Intelligence Machine", url: "./uk_energy_tracking_v5/", note: "in development" },
    { name: "UK Live Grid Tracker V6, Modular Electricity Market Intelligence Machine", url: "./uk_energy_tracking_v6/", note: "modular development" },
    { name: "UK Generation History V6 Module", url: "./uk_energy_tracking_v6/generation_history/", note: "in development" },
    { name: "UK Generation History V6 2 Backup Mirror", url: "./uk_energy_tracking_v6_2/generation_history/", note: "BACKUP" },
    { name: "UK Energy Atlas Grid Overlay V8", url: "./repd_grid_atlasv8/" },
    { name: "UK Macro Energy Consumption Trends ONS", url: "./uk_macro_energy_trends/" },
    { name: "UK Renewables Pipeline Analytics Dashboard", url: "./uk_renewables_pipeline/dashboard.html" },
    { name: "Solar Deployment Statistics", url: "./solar_deployment_statistics/" },
  ]},
  { name: "Cables & Conductors", children: [
    { name: "AC Cables Knowledge", url: "./ac_cables_knowledge/" },
    { name: "DC Cables Knowledge", url: "./dc_cables_knowledge/" },
    { name: "Conductor Resistances", url: "./conductor_resistances/" },
  ]},
  { name: "Pricing & Materials", children: [
    { name: "33 kV UK DAP Price Estimator", url: "./33kv_uk_dap_price_estimator/" },
    { name: "LV AC and DC Distribution Cables Price Estimator", url: "./lv_ac_dc_price_estimator/" },
    { name: "Copper and Aluminium Historic Prices & Trends", url: "./copper_and_aluminium_prices_historic_trends/" },
  ]},
  { name: "Components", children: [
    { name: "MV and HV Components", url: "./mv_and_hv_components/" },
    { name: "Solar Components", url: "./solar_components/" },
  ]},
  { name: "Planning & Requirements", children: [
    { name: "NSIP Solar Farms", url: "./nsip_solar_farms/" },
    { name: "Grid Studies Public", url: "./data/grid_studies_public/" },
    { name: "Employer Requirements BESS Notes", url: "./employers_requirements_BESS/" },
    { name: "Employers Requirements Large Scale Solar", url: "./employers_requirments_large_scale_solar/" },
  ]},
  { name: "Reference & Knowledge", children: [
    { name: "Definitions", url: "./definitions/" },
    { name: "Power Systems Studies", url: "./power_systems_studies/" },
    { name: "Single Line Diagrams And Grids", url: "./sld_single_diagrams_diagrams_and_grids/" },
  ]},
  { name: "About & Media", children: [
    { name: "Why VENTUS Ltd Is Building GlobalGrid2050", url: "./why_ventusltd_building_globalgrid2050/" },
    { name: "Blog", url: "./blog/" },
    { name: "Podcast Transcripts", url: "./podcast_transcripts/" },
    { name: "Earth", url: "./marketing/earth.html" },
    { name: "Time Left Today, Hourglass to 2050", url: "./time_to_2050/" },
  ]},
];

const esc = (s) => String(s).replace(/[&<>"']/g, c => ({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[c]));
const menu = document.getElementById("menu");

function rowHtml(r) {
  const note = r.note ? ` <span class="dev-status">(${esc(r.note)})</span>` : "";
  const key = (r.name + " " + (r.note || "")).toLowerCase();
  return `<li data-name="${esc(key)}"><a href="${encodeURI(r.url)}">${esc(r.name)}</a>${note}</li>`;
}

function build() {
  let html = "";
  for (const a of AREAS) {
    if (a.children && a.children.length) {
      const rows = a.children.map(rowHtml).join("");
      html += `<details class="area" data-name="${esc(a.name.toLowerCase())}">` +
              `<summary>${esc(a.name)}</summary>` +
              `<ul class="drawer">${rows}</ul></details>`;
    } else if (a.url) {
      html += `<a class="toplink" data-name="${esc(a.name.toLowerCase())}" href="${encodeURI(a.url)}">${esc(a.name)}</a>`;
    }
  }
  html += `<p class="noresult" id="noresult" style="display:none">No match.</p>`;
  menu.innerHTML = html;
}

function applySearch(raw) {
  const q = raw.trim().toLowerCase();
  let anyVisible = false;

  document.querySelectorAll(".toplink").forEach(el => {
    const show = !q || el.dataset.name.includes(q);
    el.style.display = show ? "" : "none";
    if (show) anyVisible = true;
  });

  document.querySelectorAll("details.area").forEach(d => {
    const areaMatch = !!q && d.dataset.name.includes(q);
    let childMatch = false;
    d.querySelectorAll("li").forEach(li => {
      const liMatch = li.dataset.name.includes(q);
      const show = !q || areaMatch || liMatch;
      li.style.display = show ? "" : "none";
      if (q && liMatch) childMatch = true;
    });
    const visible = !q || areaMatch || childMatch;
    d.style.display = visible ? "" : "none";
    d.open = q ? visible : false;          // search opens matches; empty collapses all
    if (visible) anyVisible = true;
  });

  document.getElementById("noresult").style.display = anyVisible ? "none" : "";
}

build();
document.getElementById("gridSearch").addEventListener("input", e => applySearch(e.target.value));
</script>
</body>
</html>"""


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


def rel(path: Path) -> str:
    return path.relative_to(ROOT).as_posix()


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


def write(path: Path, content: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content, encoding="utf-8")


def sha256_text(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else ""


def git_head() -> str:
    try:
        result = subprocess.run(
            ["git", "rev-parse", "HEAD"],
            cwd=ROOT,
            text=True,
            capture_output=True,
            timeout=10,
        )
        return result.stdout.strip() if result.returncode == 0 else ""
    except Exception:
        return ""


def extract_menu_block(html: str) -> str:
    marker = "const AREAS = ["
    if marker not in html:
        return ""
    return html.split(marker, 1)[1].split("];", 1)[0]


def menu_links(html: str) -> list[str]:
    block = extract_menu_block(html)
    return re.findall(r'url:\s*"([^"]+)"', block)


def table_links(html: str) -> list[str]:
    return re.findall(r'<a\s+href="([^"]+)"', html)


def extract_script(html: str) -> str:
    match = re.search(r"<script>(.*?)</script>", html, re.DOTALL | re.IGNORECASE)
    return match.group(1) if match else ""


def node_check(source: str) -> dict[str, Any]:
    if not source.strip():
        return {"ok": False, "detail": "No inline script found."}
    try:
        with tempfile.NamedTemporaryFile("w", suffix="_root_homepage_menu.js", delete=False, encoding="utf-8") as handle:
            handle.write(source)
            temp_path = Path(handle.name)
        result = subprocess.run(
            ["node", "--check", str(temp_path)],
            cwd=ROOT,
            text=True,
            capture_output=True,
            timeout=30,
        )
        temp_path.unlink(missing_ok=True)
        return {"ok": result.returncode == 0, "detail": (result.stderr or result.stdout).strip()}
    except FileNotFoundError:
        return {"ok": True, "detail": "node unavailable in this runner; skipped"}
    except Exception as exc:
        return {"ok": False, "detail": str(exc)}


def target_status(link: str) -> dict[str, Any]:
    if not link.startswith("./"):
        return {"link": link, "exists": False, "reason": "not relative"}
    path = ROOT / link[2:]
    if link.endswith("/"):
        return {"link": link, "exists": path.is_dir(), "reason": "directory"}
    return {"link": link, "exists": path.is_file(), "reason": "file"}


def planned_files() -> dict[Path, str]:
    content = EXPECTED_INDEX_HTML.rstrip() + "\n"
    return {TARGET: content}


def changed_paths_for(planned: dict[Path, str]) -> list[str]:
    return [rel(path) for path, content in planned.items() if read(path) != content]


def collect_state(mode: str, planned: dict[Path, str], before_hash: str, baseline_html: str) -> dict[str, Any]:
    current_html = baseline_html
    proposed_html = planned[TARGET]
    current_links = table_links(current_html)
    proposed_links = menu_links(proposed_html)
    added_links = sorted(set(proposed_links) - set(current_links))
    removed_links = sorted(set(current_links) - set(proposed_links))
    link_status = [target_status(link) for link in proposed_links]
    missing_targets = [row for row in link_status if not row["exists"]]
    js_check = node_check(extract_script(proposed_html))
    checks = {
        "targetFileExists": TARGET.exists(),
        "targetIsRootIndexHtml": rel(TARGET) == "index.html",
        "currentHomepageRead": bool(current_html.strip()),
        "currentFlatDirectoryTableDetected": '<table id="directoryTable">' in current_html,
        "currentHourglassIframeDetectedForRemoval": 'class="hourglass-embed"' in current_html,
        "proposedHtmlHasDoctype": proposed_html.lstrip().startswith("<!DOCTYPE html>"),