GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 V6 Migrate from V5 and 2 more files

A Python command-line tool in the scripts folder that reads cables, solar and battery storage (BESS).

483 lines of Python from globalgrid2050, in 3 files. Topic: Automation and CI. Section 1786 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 V6 Migrate from V5 storage · globalgrid2050 / scripts/v6_migrate_from_v5.py lines 1–238
  2. GlobalGrid2050 V6 Sanity Label Fix storage · globalgrid2050 / scripts/v6_sanity_label_fix.py lines 1–50
  3. GlobalGrid2050 V7 Migrate from V6 storage · globalgrid2050 / scripts/v7_migrate_from_v6.py lines 1–195

GlobalGrid2050 V6 Migrate from V5

A Python command-line tool in the scripts folder that reads cables, solar and battery storage (BESS).

storageglobalgrid2050 / scripts/v6_migrate_from_v5.py · lines 1–238 of 238 · Entry point · pattern copy_file (shared by 2 files)

What it does
It loads cables, solar and battery storage (BESS). Defines 7 functions or classes, including read, write, copy_file, patch_links, launcher_html. Uses libraries pathlib, shutil, datetime. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: cables, solar, battery storage (BESS).
Downstream impact
Used directly by 1 file: GlobalGrid2050 V6 Migrate from V5 Workflow (globalgrid2050).
What it achieves
It patches links (`patch_links`) and is built from the launcher HTML helper (`launcher_html`) and the readme text helper (`readme_text`). Defines `read`, `write`, `copy_file` and 4 more. It writes `index.html`.
Why it matters
Run by GlobalGrid2050 V6 Migrate from V5 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, shutil, datetime
Used by
run by GlobalGrid2050 V6 Migrate from V5 Workflow (workflow run)
Produces
read, write, copy_file, patch_links, launcher_html, readme_text, migrate
Defines here
read, write, copy_file, patch_links, launcher_html, readme_text, migrate
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/v6_migrate_from_v5.py:1-238 · blob c0c7e3d130bbf13844b9e7356ed5265824015403 · 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]
V5 = ROOT / "solar-bess-topology-v5"
V6 = ROOT / "solar-bess-topology-v6"
REPORTS = ROOT / "gridbot_reports"

APP_FOLDERS = {
    "gis-sld-financial-sandbox": {
        "html": "indexforgis-sld-v5.html",
        "copy": [
            "gis-sld-v5.css",
            "gis-sld-v5-config.js",
            "gis-sld-v5-helpers.js",
            "gis-sld-v5-state.js",
            "gis-sld-v5-substations.js",
            "gis-sld-v5-map.js",
            "gis-sld-v5-calculations.js",
            "gis-sld-v5-finance.js",
            "gis-sld-v5-ui-core.js",
            "gis-sld-v5-drawing.js",
            "gis-sld-v5-export.js",
            "gis-sld-v5-ui.js",
        ],
        "title": "GIS SLD Financial Sandbox",
        "description": "Main GIS, SLD, financial and grid screening application."
    },
    "module-layout": {
        "html": "module-layout-v5.html",
        "copy": [
            "gis-sld-v5.css",
            "module-layout-v5.css",
            "gis-sld-v5-config.js",
            "gis-sld-v5-helpers.js",
            "module-layout-v5.js",
        ],
        "title": "Physical Solar Module Layout",
        "description": "Separate module footprint, row, pitch and layout visualiser."
    },
    "dc-ac-lv-topology-review": {
        "html": "dc-ac-lv-topology-review-v5.html",
        "copy": [
            "gis-sld-v5.css",
            "module-layout-v5.css",
            "dc-ac-lv-topology-review-v5.css",
            "dc-ac-lv-topology-review-v5.js",
        ],
        "title": "DC AC LV Topology Review",
        "description": "Separate low voltage and DC topology screening application."
    },
    "cable-geometry-visualiser": {
        "html": "cable-geometry-visualiser-v5.html",
        "copy": [],
        "title": "Cable Geometry Visualiser",
        "description": "Cable formation, trench, bend and geometry visualiser. To be modularised next."
    },
}

SHARED_DOCS = [
    "ARCHITECTURE.md",
    "README_FOR_AI_AND_HUMANS.md",
    "V5_CHANGELOG_AND_ROADMAP.md",
]


def read(path: Path) -> str:
    return path.read_text(encoding="utf-8")


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


def copy_file(src: Path, dst: Path):
    if not src.exists():
        return False
    dst.parent.mkdir(parents=True, exist_ok=True)
    shutil.copy2(src, dst)
    return True


def patch_links(html: str, app_name: str) -> str:
    # Basic V6 navigation rewrite only. File names are otherwise kept unchanged so the migration stays low risk.
    replacements = {
        './indexforgis-sld-v5.html': '../gis-sld-financial-sandbox/index.html',
        './module-layout-v5.html': '../module-layout/index.html',
        './dc-ac-lv-topology-review-v5.html': '../dc-ac-lv-topology-review/index.html',
        './cable-geometry-visualiser-v5.html': '../cable-geometry-visualiser/index.html',
        'Back to GIS SLD V5': 'Back to GIS SLD V6',
        'Module Layout V5': 'Module Layout V6',
        'GlobalGrid2050 V5': 'GlobalGrid2050 V6',
        'DC AC LV Topology Review V5': 'DC AC LV Topology Review V6',
    }
    for old, new in replacements.items():
        html = html.replace(old, new)

    # Keep existing cache busting harmless but mark the V6 migration.
    html = html.replace('dc-ac-lv-topology-review-v5.js?v=stable-live-update-1', 'dc-ac-lv-topology-review-v5.js?v=v6-migration-1')
    return html


def launcher_html() -> str:
    cards = []
    for folder, meta in APP_FOLDERS.items():
        cards.append(f'''
            <a class="card" href="./{folder}/index.html">
                <h2>{meta["title"]}</h2>
                <p>{meta["description"]}</p>
                <span>Open app</span>
            </a>''')
    return f'''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>GlobalGrid2050 V6</title>
    <style>
        :root {{ --bg:#050505; --panel:#0b0e14; --line:#2f343d; --text:#fff; --muted:#a6adbb; --accent:#00ffff; --ok:#00ff88; }}
        * {{ box-sizing:border-box; }}
        body {{ margin:0; padding:28px; background:var(--bg); color:var(--text); font-family:"Courier New", monospace; }}
        header {{ max-width:1180px; margin:0 auto 24px auto; border:1px solid var(--line); background:rgba(10,10,10,.96); padding:22px; border-radius:14px; }}
        .kicker {{ color:var(--accent); text-transform:uppercase; letter-spacing:.14em; font-size:12px; }}
        h1 {{ margin:8px 0 10px 0; font-size:28px; }}
        p {{ color:var(--muted); line-height:1.55; }}
        main {{ max-width:1180px; margin:0 auto; display:grid; grid-template-columns:repeat(auto-fit,minmax(250px,1fr)); gap:18px; }}
        .card {{ display:block; min-height:190px; border:1px solid var(--line); background:var(--panel); border-radius:14px; padding:20px; text-decoration:none; color:var(--text); }}
        .card:hover {{ border-color:var(--accent); }}
        .card h2 {{ margin:0 0 10px 0; color:var(--accent); font-size:18px; }}
        .card span {{ color:var(--ok); font-weight:bold; }}
        footer {{ max-width:1180px; margin:22px auto 0 auto; color:var(--muted); font-size:12px; }}
    </style>
</head>
<body>
    <header>
        <div class="kicker">GlobalGrid2050 V6</div>
        <h1>Separated Application Workspace</h1>
        <p>V6 starts by migrating the working V5 applications into separate folders so each app has its own HTML, CSS and JavaScript context. V5 remains untouched as the stable reference.</p>
    </header>
    <main>{''.join(cards)}
    </main>
    <footer>Generated from V5 on {datetime.now(timezone.utc).isoformat()}.</footer>
</body>
</html>
'''


def readme_text() -> str:
    return '''# GlobalGrid2050 V6

V6 is a separated application workspace copied from the stable V5 folder.

Purpose:

1. Keep V5 stable.
2. Place each application in its own folder.
3. Make it obvious which scripts belong to which app.
4. Prepare the cable geometry visualiser for modularisation without risking the GIS SLD sandbox or DC AC LV topology app.

Folder structure:

```text
solar-bess-topology-v6/
  index.html
  gis-sld-financial-sandbox/
  module-layout/
  dc-ac-lv-topology-review/
  cable-geometry-visualiser/
  docs/
  tools/
```

Rules for future AI or human work:

1. Do not edit V5 when working on V6.
2. Do not mix scripts between apps unless they are deliberately placed in a shared folder later.
3. Keep each app working independently inside its own folder.
4. Use small workflows and small commits.
5. For the cable geometry visualiser, split only after the copied V6 app is confirmed working.

Next planned work:

Modularise `cable-geometry-visualiser/index.html` into separate CSS, data, calculation, rendering, UI and export files.
'''


def migrate():
    if not V5.exists():
        raise SystemExit("V5 folder not found")

    if V6.exists():
        shutil.rmtree(V6)
    V6.mkdir(parents=True, exist_ok=True)

    actions = []

    for folder, meta in APP_FOLDERS.items():
        app_dir = V6 / folder
        app_dir.mkdir(parents=True, exist_ok=True)
        src_html = V5 / meta["html"]
        if src_html.exists():
            html = patch_links(read(src_html), folder)
            write(app_dir / "index.html", html)
            actions.append(f"created {folder}/index.html from {meta['html']}")
        else:
            actions.append(f"missing {meta['html']}")
        for fname in meta["copy"]:
            ok = copy_file(V5 / fname, app_dir / fname)
            actions.append(("copied " if ok else "missing ") + f"{fname} to {folder}")

    write(V6 / "index.html", launcher_html())
    write(V6 / "README.md", readme_text())

    docs_dir = V6 / "docs"
    for doc in SHARED_DOCS:
        if copy_file(V5 / doc, docs_dir / doc):
            actions.append(f"copied doc {doc}")

    tools_dir = V6 / "tools" / "legacy-v5-installers"
    for py in sorted(V5.glob("install_*.py")):
        copy_file(py, tools_dir / py.name)
        actions.append(f"copied legacy installer {py.name}")

    REPORTS.mkdir(parents=True, exist_ok=True)
    report = REPORTS / "v6_migration_from_v5.md"
    write(report, "# V6 Migration From V5\n\n" +
          f"UTC created: {datetime.now(timezone.utc).isoformat()}\n\n" +
          "Created `solar-bess-topology-v6` as a separated application workspace.\n\n" +
          "V5 remains the stable baseline.\n\n" +
          "Actions:\n\n" + "\n".join(f"- {a}" for a in actions) + "\n")

    print("V6 migration complete")


if __name__ == "__main__":
    migrate()

GlobalGrid2050 V6 Sanity Label Fix

A Python command-line tool in the scripts folder that reads solar, battery storage (BESS) and cables.

storageglobalgrid2050 / scripts/v6_sanity_label_fix.py · lines 1–50 of 50 · Entry point

What it does
It loads solar, battery storage (BESS) and cables. Defines main. Uses libraries pathlib, datetime. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: solar, battery storage (BESS), cables.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V6 Sanity Label Fix 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 V6 Sanity Label Fix Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, datetime
Used by
run by GlobalGrid2050 V6 Sanity Label Fix 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/v6_sanity_label_fix.py:1-50 · blob 734a077498521dd307b1d46e0d7d544172e2e76c · 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

ROOT = Path(__file__).resolve().parents[1]
V6 = ROOT / "solar-bess-topology-v6"
REPORTS = ROOT / "gridbot_reports"

REPLACEMENTS = {
    "GlobalGrid2050 V5": "GlobalGrid2050 V6",
    "GIS SLD Financial Sandbox V5": "GIS SLD Financial Sandbox V6",
    "Module Layout V5": "Module Layout V6",
    "DC AC LV Topology Review V5": "DC AC LV Topology Review V6",
    "Cable Geometry Visualiser V5": "Cable Geometry Visualiser V6",
    "Back to GIS SLD V5": "Back to GIS SLD V6",
    "<!-- V5 modular app scripts -->": "<!-- V6 migrated modular app scripts -->",
}

# Keep file names unchanged in this first V6 migration. This preserves dependency behaviour and avoids breaking V5-derived scripts.
TEXT_TYPES = {".html", ".css", ".js", ".md"}


def main():
    actions = []
    if not V6.exists():
        raise SystemExit("solar-bess-topology-v6 not found")

    for path in sorted(V6.rglob("*")):
        if not path.is_file() or path.suffix.lower() not in TEXT_TYPES:
            continue
        text = path.read_text(encoding="utf-8")
        old = text
        for a, b in REPLACEMENTS.items():
            text = text.replace(a, b)
        if text != old:
            path.write_text(text, encoding="utf-8")
            actions.append(str(path.relative_to(ROOT)))

    REPORTS.mkdir(parents=True, exist_ok=True)
    report = REPORTS / "v6_sanity_label_fix.md"
    report.write_text(
        "# V6 Sanity Label Fix\n\n"
        f"UTC created: {datetime.now(timezone.utc).isoformat()}\n\n"
        "Updated V6 visible labels while deliberately keeping migrated V5 file names unchanged so dependencies remain stable.\n\n"
        "Files changed:\n\n" + ("\n".join(f"- {a}" for a in actions) if actions else "- none") + "\n",
        encoding="utf-8"
    )
    print("V6 sanity label fix complete")

if __name__ == "__main__":
    main()

GlobalGrid2050 V7 Migrate from V6

A Python command-line tool in the scripts folder that reads solar and battery storage (BESS). It reads text (`read_text`), writes text (`write_text`) and patches text (`patch_text`).

storageglobalgrid2050 / scripts/v7_migrate_from_v6.py · lines 1–195 of 195 · Entry point · pattern migrate (shared by 2 files)

What it does
It loads solar and battery storage (BESS). Defines 8 functions or classes, including rel, read_text, write_text, patch_text, patch_v7_files. Uses libraries __future__, argparse, datetime, shutil, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: solar, battery storage (BESS).
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 V7 Migrate from V6 Workflow (globalgrid2050).
What it achieves
Creates a brand new V7 folder from the current V6 workspace. It accepts `--overwrite`.
Why it matters
Run by GlobalGrid2050 V7 Migrate from V6 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, shutil, pathlib
Used by
run by GlobalGrid2050 V7 Migrate from V6 Workflow (workflow run)
Produces
rel, read_text, write_text, patch_text, patch_v7_files, write_report, migrate, main
Defines here
rel, read_text, write_text, patch_text, patch_v7_files, write_report, migrate, 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/v7_migrate_from_v6.py:1-195 · blob 2924f4c22fbc687cf9256742a480302d19e0d16b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""
V7 Migrate From V6

Creates a brand new V7 folder from the current V6 workspace.

Purpose:
- Preserve V6 as the working version history baseline.
- Create solar-bess-topology-v7 as the next development workspace.
- Copy the full V6 folder, including apps, docs, training, learning objectives and upgrade manifests.
- Relabel safe user-facing V6 references to V7.
- Keep internal legacy file names where changing them would create break risk.
- Write a GridBot migration report.

This script does not edit V6.
"""

from __future__ import annotations

import argparse
import datetime as dt
import shutil
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
V6 = ROOT / "solar-bess-topology-v6"
V7 = ROOT / "solar-bess-topology-v7"
REPORTS = ROOT / "gridbot_reports"

SAFE_TEXT_EXTENSIONS = {
    ".html",
    ".md",
    ".yml",
    ".yaml",
    ".txt",
    ".css",
    ".js",
}

# Conservative replacements only. Do not rename legacy v5 file names.
REPLACEMENTS = {
    "GlobalGrid2050 V6": "GlobalGrid2050 V7",
    "GIS SLD Financial Sandbox V6": "GIS SLD Financial Sandbox V7",
    "V6 Training Index": "V7 Training Index",
    "V6 Learning Objectives": "V7 Learning Objectives",
    "V6 progress": "V7 progress",
    "V6 Progress": "V7 Progress",
    "V6 workspace": "V7 workspace",
    "V6 Workspace": "V7 Workspace",
    "V6 folder": "V7 folder",
    "V6 Folder": "V7 Folder",
    "V6 is": "V7 is",
    "V6 remains": "V7 remains",
    "V6 should": "V7 should",
    "V6 must": "V7 must",
    "V6 gives": "V7 gives",
    "Future V6": "Future V7",
    "future V6": "future V7",
    "Current V6": "Current V7",
    "current V6": "current V7",
    "solar-bess-topology-v6": "solar-bess-topology-v7",
    "V6": "V7",
}

PRESERVE_NOTE = """

## V7 migration note

V7 was created as a full workspace copy from V6.

V6 remains preserved as the previous working baseline.

Internal legacy file names may still contain older version labels where renaming them would create unnecessary break risk. This is intentional. User facing documentation, launcher labels and development notes are relabelled to V7 where safe.
""".strip()


def rel(path: Path) -> str:
    try:
        return str(path.resolve(strict=False).relative_to(ROOT.resolve(strict=False)))
    except ValueError:
        return str(path)


def read_text(path: Path) -> str:
    return path.read_text(encoding="utf-8")


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


def patch_text(text: str) -> tuple[str, int]:
    count = 0
    for old, new in REPLACEMENTS.items():
        occurrences = text.count(old)
        if occurrences:
            text = text.replace(old, new)
            count += occurrences
    return text, count


def patch_v7_files() -> list[str]:
    actions: list[str] = []
    for path in sorted(V7.rglob("*")):
        if not path.is_file():
            continue
        if path.suffix.lower() not in SAFE_TEXT_EXTENSIONS:
            continue
        try:
            original = read_text(path)
        except UnicodeDecodeError:
            actions.append(f"skipped binary or non utf8 file: {rel(path)}")
            continue
        patched, count = patch_text(original)
        if patched != original:
            write_text(path, patched)
            actions.append(f"patched {count} label references in {rel(path)}")

    readme = V7 / "README.md"
    if readme.exists():
        text = read_text(readme)
        if "## V7 migration note" not in text:
            write_text(readme, text.rstrip() + "\n\n" + PRESERVE_NOTE + "\n")
            actions.append("added V7 migration note to README.md")
    return actions


def write_report(actions: list[str], overwrite: bool) -> Path:
    REPORTS.mkdir(parents=True, exist_ok=True)
    timestamp = dt.datetime.now(dt.timezone.utc).isoformat()
    report = REPORTS / "v7_migration_from_v6.md"
    lines = [
        "# V7 Migration From V6",
        "",
        f"UTC created: {timestamp}",
        f"Source: `{rel(V6)}`",
        f"Target: `{rel(V7)}`",
        f"Overwrite used: {overwrite}",
        "",
        "## Purpose",
        "",
        "Create a full V7 workspace from the current V6 workspace while preserving V6 as the prior working baseline.",
        "",
        "## Migration stance",
        "",
        "- V6 is not edited.",
        "- V7 is a new version folder.",
        "- Internal legacy file names are not renamed unless deliberately handled later.",
        "- Safe user facing labels and documentation references are relabelled from V6 to V7.",
        "- A separate workflow should be used for future V7 upgrades.",
        "",
        "## Actions",
        "",
    ]
    lines.extend([f"- {action}" for action in actions] or ["- no file label changes required"])
    lines.extend([
        "",
        "## Next steps",
        "",
        "1. Test `solar-bess-topology-v7/index.html` locally through GitHub Pages.",
        "2. Test each V7 app route.",
        "3. Do not add V7 to the public homepage until manual checks pass.",
        "4. Use V7 for the next phase of controlled upgrades.",
        "",
    ])
    write_text(report, "\n".join(lines))
    return report


def migrate(overwrite: bool) -> None:
    if not V6.exists():
        raise SystemExit(f"Source folder missing: {rel(V6)}")

    if V7.exists():
        if not overwrite:
            raise SystemExit(f"Target folder already exists: {rel(V7)}. Re-run with --overwrite if intentional.")
        shutil.rmtree(V7)

    shutil.copytree(V6, V7)
    actions = [f"copied full folder {rel(V6)} to {rel(V7)}"]
    actions.extend(patch_v7_files())
    report = write_report(actions, overwrite)
    print(f"V7 migration complete. Report: {rel(report)}")


def main() -> int:
    parser = argparse.ArgumentParser(description="Create solar-bess-topology-v7 from solar-bess-topology-v6.")
    parser.add_argument("--overwrite", action="store_true", help="Delete and recreate existing V7 folder if it already exists.")
    args = parser.parse_args()
    migrate(overwrite=args.overwrite)
    return 0


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