GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Check Public Language and 4 more files

A Python command-line tool in the scripts folder that reads solar. It is built from the visible step (`visible`), the surface step (`surface`) and the approved spans helper (`approved_spans`).

697 lines of Python from globalgrid2050, in 5 files. Topic: Automation and CI. Section 1758 of 2044.

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

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

In this section

  1. GlobalGrid2050 Build Status ingest · globalgrid2050 / scripts/build_status.py lines 1–134
  2. GlobalGrid2050 Check Homepage Catalogue ingest · globalgrid2050 / scripts/check_homepage_catalogue.py lines 1–129
  3. GlobalGrid2050 Check Public Language ingest · globalgrid2050 / scripts/check_public_language.py lines 1–165
  4. GlobalGrid2050 Clone V3 to V4 storage · globalgrid2050 / scripts/clone_v3_to_v4.py lines 1–150
  5. GlobalGrid2050 Clone V3 Tracker to V4 storage · globalgrid2050 / scripts/clone_v3_tracker_to_v4.py lines 1–119

GlobalGrid2050 Build Status

A Python command-line tool in the scripts folder that works with both clocks (`both_clocks`).

ingestglobalgrid2050 / scripts/build_status.py · lines 1–134 of 134 · Entry point

What it does
It loads data. Defines read_status, both_clocks, row, build. Uses libraries html, io, json, os, datetime. Side effects: reads or writes files.
Inputs & outputs
In: JSON file status.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It reads status (`read_status`) and is built from the row step (`row`) and the build step (`build`). Publish `status.json` as `status.html`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · scripts · Python CLI
Uses
html, io, json, os, datetime
Used by
none found
Produces
read_status, both_clocks, row, build
Defines here
read_status, both_clocks, row, build
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/build_status.py:1-134 · blob 4cc08fa5bbb8b4e778be4b9f704ffddbdb4635c8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
"""Publish status.json as status.html.

The context window of a long session dies, and when it does the only thing that
survives is what was written down somewhere a person can open. This publishes
the session log to the live site at intervals, so the next session - human or
model - can recover where the work had got to without reading a transcript.

Build facts only. No correspondence, no client material, nothing private: this
page is public the moment it is pushed.

Times are UTC. The architect's clock is BST, +1, so each row shows both - the
mismatch has caused typed-stamp errors in this estate before.

    python scripts/build_status.py
"""
import html
import io
import json
import os
from datetime import datetime, timedelta, timezone

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def read_status():
    with io.open(os.path.join(ROOT, "status.json"), encoding="utf-8") as handle:
        return json.load(handle)


def both_clocks(stamp):
    """202609050227 -> ('2026-09-05 02:27 UTC', '03:27 BST')."""
    try:
        moment = datetime.strptime(stamp, "%Y%m%d%H%M").replace(tzinfo=timezone.utc)
    except ValueError:
        return html.escape(stamp), ""
    return (moment.strftime("%Y-%m-%d %H:%M UTC"),
            (moment + timedelta(hours=1)).strftime("%H:%M BST"))


def row(entry):
    utc, bst = both_clocks(str(entry.get("utc", "")))
    commit = html.escape(str(entry.get("commit", "")))
    repo = html.escape(str(entry.get("repo", "")))
    lane = html.escape(str(entry.get("lane", "")))
    what = html.escape(str(entry.get("what", "")))
    verified = html.escape(str(entry.get("verified", "")))
    return (
        '<article class="entry">'
        f'<p class="when">{utc}<span class="bst"> · {bst}</span>'
        f'<span class="lane">lane {lane}</span></p>'
        f'<p class="where"><span class="repo">{repo}</span> '
        f'<span class="commit">{commit}</span></p>'
        f'<p class="what">{what}</p>'
        f'<p class="verified">{verified}</p>'
        "</article>"
    )


def build():
    status = read_status()
    entries = sorted(status.get("entries", []),
                     key=lambda e: str(e.get("utc", "")), reverse=True)
    written = datetime.now(timezone.utc)
    written_utc = written.strftime("%Y-%m-%d %H:%M UTC")
    written_bst = (written + timedelta(hours=1)).strftime("%H:%M BST")

    open_items = "".join(f"<li>{html.escape(str(item))}</li>"
                         for item in status.get("open", []))

    page = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GlobalGrid2050 — build status</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body {{ background:#000; color:#fff; font-family:Courier,monospace; padding:40px;
         max-width:900px; margin:0 auto; font-size:18px; line-height:1.6; }}
  h1 {{ margin-top:0; font-size:40px; line-height:1.1; }}
  h2 {{ font-size:18px; font-weight:normal; letter-spacing:.14em; text-transform:uppercase;
        color:#888; margin:46px 0 6px; }}
  a {{ color:#66ccff; text-decoration:none; }}
  a:hover {{ text-decoration:underline; }}
  .lede {{ color:#cccccc; font-size:16px; }}
  .written {{ color:#888; font-size:15px; }}
  .entry {{ border-top:1px solid #222; padding-top:12px; margin-top:22px; }}
  .when {{ color:#66ccff; font-size:15px; margin:0; }}
  .bst {{ color:#6f8f9c; }}
  .lane {{ float:right; color:#888; }}
  .where {{ margin:2px 0 0; font-size:15px; color:#aaa; }}
  .repo {{ color:#fff; }}
  .commit {{ color:#8fb6c0; }}
  .what {{ margin:6px 0 0; font-size:16px; }}
  .verified {{ margin:2px 0 0; font-size:14px; color:#7f9f88; }}
  ul {{ padding-left:20px; }}
  li {{ margin-top:10px; font-size:16px; color:#ccc; }}
  @media (max-width:600px) {{
    body {{ padding:25px; font-size:16px; }}
    h1 {{ font-size:32px; }}
    .lane {{ float:none; display:block; }}
  }}
</style>
</head>
<body>
<header>
  <h1>Build status</h1>
  <p class="lede">What is being built, as it is built. Published at intervals so the
  work can be picked up again when a session ends — by a person or by the next model.
  Times are UTC first, because stamps in this estate are read from the clock in UTC;
  the second time is the same moment in British Summer Time.</p>
  <p class="written">Written {written_utc} · {written_bst}</p>
  <p><a href="./">← GlobalGrid2050</a></p>
</header>

<h2>Open</h2>
<ul>{open_items}</ul>

<h2>Log</h2>
{''.join(row(entry) for entry in entries)}

<footer>
  <p class="written">Build facts only. This page is public.</p>
</footer>
</body>
</html>
"""
    out = os.path.join(ROOT, "status.html")
    with io.open(out, "w", encoding="utf-8", newline="\n") as handle:
        handle.write(page)
    print("status.html written: %d entries, %d bytes" % (len(entries), len(page)))


if __name__ == "__main__":
    build()

GlobalGrid2050 Check Homepage Catalogue

A Python module in the scripts folder that works with rev parse (`rev_parse`) and servable row (`servable_row`). It is built from the has page helper (`has_page`).

ingestglobalgrid2050 / scripts/check_homepage_catalogue.py · lines 1–129 of 129 · Entry point · pattern has_page (shared by 2 files)

What it does
It loads data. Defines rev_parse, has_page, servable_row. Uses libraries __future__, json, re, subprocess, sys. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file homepage-catalogue.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Homepage Catalogue Workflow (globalgrid2050).
What it achieves
Reconcile the committed homepage catalogue against git, on whatever platform this runs - and it is meant to run on Linux.
Why it matters
Run by GlobalGrid2050 Homepage Catalogue Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
__future__, json, re, subprocess, sys, pathlib
Used by
run by GlobalGrid2050 Homepage Catalogue Workflow (workflow run)
Produces
rev_parse, has_page, servable_row
Defines here
rev_parse, has_page, servable_row
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/check_homepage_catalogue.py:1-129 · blob 3596d21d40a4876ee600d882157582bf2215ede4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""Reconcile the committed homepage catalogue against git, on whatever platform
this runs - and it is meant to run on Linux.

WHY
The catalogue carries two references per version: the GlobalGrid2050
reference (the UTC stamp-name) and the independent git reference (the tree
hash, `git rev-parse HEAD:<path>`). The second exists so that the first can be
checked by something that does not depend on anyone's memory or anyone's
machine. On 2026-09-06 a Windows checkout held 3,555 files whose bytes differed
from the blobs git would serve; a catalogue generated there could have carried
barcodes for bytes that never shipped. Git tree hashes are computed from the
blobs, not the working copy, so they are the same on every platform - and this
check proves that for every row, every run, by re-deriving each one.

WHAT FAILS
  - a row whose recorded tree hash differs from `git rev-parse HEAD:<path>` now
  - a row whose relative URL no longer resolves to a page
  - a row whose id is not <12-digit UTC stamp>-<slug>
  - two rows sharing a URL
  - a current release that is not the newest of its family

Run:  python3 scripts/check_homepage_catalogue.py
"""
from __future__ import annotations

import json
import re
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
CAT = ROOT / "catalogue" / "homepage-catalogue.json"


def rev_parse(path: str) -> str | None:
    r = subprocess.run(["git", "rev-parse", f"HEAD:{path}"], cwd=ROOT, capture_output=True, text=True)
    return r.stdout.strip() if r.returncode == 0 else None


def has_page(rel: str) -> bool:
    p = ROOT / rel
    return p.is_file() or (p / "index.html").is_file() or (p / "index.md").is_file()


doc = json.loads(CAT.read_text(encoding="utf-8"))
rows = doc["entries"]
failures: list[str] = []
reconciled = 0
seen_urls: set[str] = set()

for e in rows:
    if not re.fullmatch(r"\d{12}-[a-z0-9-]+", e["id"]):
        failures.append(f"{e['id']}: id is not <UTC stamp>-<slug>")
    if e["url"] in seen_urls:
        failures.append(f"{e['id']}: duplicate url {e['url']}")
    seen_urls.add(e["url"])
    if e["url"].startswith("./"):
        rel = e["url"][2:].rstrip("/")
        if not has_page(rel):
            failures.append(f"{e['id']}: {e['url']} no longer resolves to a page")
        if e.get("tree"):
            now = rev_parse(rel)
            if now != e["tree"]:
                failures.append(f"{e['id']}: barcode {e['tree'][:12]} recorded, git now says {(now or 'nothing')[:12]} for {rel}")
            else:
                reconciled += 1

def servable_row(entry):
    """Does this row's page decode as text and open like a document?

    Only local rows can be checked; an external URL is taken as given."""
    url = str(entry.get("url") or "")
    if not url.startswith("./"):
        return True
    target = ROOT / url[2:]
    if target.is_dir():
        target = target / "index.html"
    if not target.is_file():
        return True          # a missing page is already caught by the link check
    try:
        head = target.read_bytes()[:2048].decode("utf-8").lstrip().lower()
    except (OSError, UnicodeDecodeError):
        return False
    # Looked-for, not led-with. repd_grid_atlasv4/index.html carries a stray
    # line of build chatter ("supermarkets layer added") above its doctype and is
    # otherwise a perfectly good page; requiring the doctype at byte zero called
    # it corrupt. The defect being caught is bytes that are not text at all, so
    # the test is that it decodes and that a document tag appears near the top.
    return "<html" in head or "<!doctype" in head


for family in doc["families"]:
    fam = [e for e in rows if e["family"] == family]
    current = [e for e in fam if e.get("status") == "current"]
    if len(current) > 1:
        failures.append(f"{family}: {len(current)} rows marked current; there can be one")
    if current and fam:
        """A newer release only outranks the current one if it can be served.

        This rule used to say, flatly, that the newest release of a kind must be
        the current one. On 2026-09-08 that turned into an instruction to publish
        a broken page: 202609080146 was committed with an index.html of binary
        noise rather than HTML, and the rule demanded it be promoted over the
        working 202609071221. With the homepage now reduced to Pipeline News,
        obeying would have taken the site down.

        So an unservable release is not a candidate for current, and it gets its
        own finding instead - the corruption is the problem to report, not the
        pointer that correctly declined to follow it."""
        servable = [e for e in fam if servable_row(e)]
        unservable = [e for e in fam if e not in servable]
        for e in unservable:
            failures.append(
                f"{e['id']}: published page is not readable as text, so it cannot be served "
                f"or made current; the corruption is in the commit, not just the working tree")
        pool = servable or fam
        newest = max(pool, key=lambda e: e["stamp"])
        if current[0]["stamp"] < newest["stamp"] and newest.get("kind") == current[0].get("kind"):
            failures.append(f"{family}: current is {current[0]['id']} but {newest['id']} is newer of the same kind")

if failures:
    print(f"HOMEPAGE CATALOGUE FAILED - {len(failures)} finding(s) of {len(rows)} rows:")
    for f in failures[:30]:
        print("  - " + f)
    sys.exit(1)
print(f"homepage catalogue: PASS - {len(rows)} rows, {reconciled} barcodes re-derived from git and identical, "
      f"every relative link resolves, one current per family")

GlobalGrid2050 Check Public Language

A Python command-line tool in the scripts folder that reads solar. It is built from the visible step (`visible`), the surface step (`surface`) and the approved spans helper (`approved_spans`).

ingestglobalgrid2050 / scripts/check_public_language.py · lines 1–165 of 165 · Entry point · pattern visible (shared by 17 files)

What it does
It loads solar. Defines visible, surface, approved_spans, main. Uses libraries argparse, glob, html, os, re. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain terms in the code: solar.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Public Language Gate Workflow (globalgrid2050).
What it achieves
Register entry 24: "the rule that certain words must not appear in public text is currently checked by reading. It accepts `--list`.
Why it matters
Run by GlobalGrid2050 Public Language Gate Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
argparse, glob, html, os, re, sys
Used by
run by GlobalGrid2050 Public Language Gate Workflow (workflow run)
Produces
visible, surface, approved_spans, main
Defines here
visible, surface, approved_spans, 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/check_public_language.py:1-165 · blob 55256da4c181988f2d9dc662927329c005ba63fb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: production_core
"""The public-language gate.

Register entry 24: "the rule that certain words must not appear in public text
is currently checked by reading. It needs to be a check that runs before
anything is published."

This is that check. It reads the VISIBLE text of the published surface - script
and style stripped, tags removed - and fails the build if it finds language
that must not reach a customer. Intent is not the test. On 20 September 2026
the published manual carried twenty reserved words, every one of them inside a
disclaimer written to protect the reader, and it still breached the rule.

    python scripts/check_public_language.py            # check
    python scripts/check_public_language.py --list     # show the surface

Exit code 1 means do not publish.
"""
import argparse
import glob
import html
import os
import re
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# ---- the published surface. A folder that is published must be listed here,
#      the same rule the deploy workflow learned four times.
SURFACE = [
    "index.html",
    "status.html",
    "historical_builds.html",
    "compute/*.html",
    "kuiper-grid/*.html",
    "kuiper-grid/*.md",
    # A NEW PUBLISHED FOLDER MUST BE ADDED HERE OR IT IS NEVER READ. This
    # list has the same defect the deploy workflow has learned five times:
    # it is an allow-list, and a page nobody adds to it is published
    # unchecked while the gate still prints PASS. plant/ is added with the
    # page, not after it.
    "plant/*.html",
    # SIXTH TIME THE ALLOW-LIST DEFECT ABOVE BIT. On 21 September 2026 the
    # composer shell at kuiper/ and all sixteen build shells under
    # kuiper-grid/i0*/ were given visible prose - navigation, a scope note
    # and the unsourced-limit warning - and NONE of them were on this list,
    # so the gate read eight files, printed PASS, and had not looked at any
    # of the seventeen pages the text had just been added to.
    "kuiper/*.html",
    "kuiper-grid/i0*/*.html",
    "ventus/*.html",
    "ventus/wiring/*.html",
]

# ---- what must never appear in public text
RULES = [
    ("reserved",
     r"\b(capacity|headroom|outage|risk|measured)\b",
     "the reserved word list: these make a claim about a network or a "
     "measurement that this work does not support"),
    ("maker-or-site",
     r"\b(sungrow|huawei|sma solar|fimer|fronius|trina|jinko|longi|"
     r"ja solar|canadian solar|risen|astronergy|cleve hill|"
     r"little cheyne|larks green)\b",
     "a manufacturer or a named site: this work is nameless by rule"),
    ("dev-diary",
     r"\b(TODO|FIXME|XXX|HACK|KLUDGE|Archived Broken|DO NOT SHIP|"
     r"quick and dirty|placeholder|lorem ipsum)\b",
     "working notes left in customer-facing text"),
    ("local-path",
     r"[A-Za-z]:\\Users\\|[A-Za-z]:/Users/|E:\\swarm|E:/swarm",
     "an absolute path from the author's machine"),
    ("assistant",
     r"\b(Claude|Codex|ChatGPT|GPT-4|GPT-5|OpenAI|Anthropic|Gemini|Copilot|"
     r"subagent|prompt engineering)\b",
     "an AI assistant named outside the approved statement"),
]

# ---- the one approved place an assistant may be named. Anything matching this
#      is the deliberate positioning statement, not leakage.
APPROVED = [
    r"explores current technology with Claude and\s+Codex AI",
    r"explores current technology with Claude and Codex AI",
]


def visible(path):
    s = open(path, encoding="utf-8", errors="replace").read()
    if path.lower().endswith((".html", ".htm")):
        s = re.sub(r"(?is)<script.*?</script>", " ", s)
        s = re.sub(r"(?is)<style.*?</style>", " ", s)
        s = re.sub(r"(?s)<!--.*?-->", " ", s)
        s = re.sub(r"<[^>]+>", " ", s)
    return html.unescape(re.sub(r"[ \t]+", " ", s))


def surface():
    out = []
    for pat in SURFACE:
        out.extend(sorted(glob.glob(os.path.join(ROOT, pat))))
    return [p for p in out if os.path.isfile(p)]


def approved_spans(text):
    spans = []
    for pat in APPROVED:
        for m in re.finditer(pat, text, re.I):
            spans.append((max(0, m.start() - 200), m.end() + 200))
    return spans


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--list", action="store_true")
    a = ap.parse_args()

    files = surface()
    if a.list:
        for f in files:
            print(" ", os.path.relpath(f, ROOT).replace("\\", "/"))
        return 0

    # a check that reached nothing FAILS
    if not files:
        print("FAIL: the published surface matched no files. A check that "
              "reached nothing is not a pass.")
        return 1

    findings = []
    for f in files:
        text = visible(f)
        ok = approved_spans(text)
        for name, pat, why in RULES:
            for m in re.finditer(pat, text, re.I):
                if name == "assistant" and any(
                        lo <= m.start() <= hi for lo, hi in ok):
                    continue
                a0 = max(0, m.start() - 55)
                findings.append((
                    os.path.relpath(f, ROOT).replace("\\", "/"), name,
                    m.group(0),
                    re.sub(r"\s+", " ", text[a0:m.end() + 55]).strip(), why))

    print("public-language gate: %d files on the published surface" % len(files))
    if not findings:
        print("PASS: no reserved word, maker name, working note, local path or "
              "unapproved assistant reference in visible text.")
        return 0

    by_rule = {}
    for f in findings:
        by_rule.setdefault(f[1], []).append(f)
    print("\nFAIL: %d finding(s). Do not publish.\n" % len(findings))
    for name, items in by_rule.items():
        print("  [%s] %s" % (name, items[0][4]))
        for path, _n, word, ctx, _w in items[:8]:
            print("    %s  '%s'" % (path, word))
            print("        ...%s..." % ctx[:110])
        if len(items) > 8:
            print("    (and %d more)" % (len(items) - 8))
        print()
    return 1


if __name__ == "__main__":
    sys.exit(main())

GlobalGrid2050 Clone V3 to V4

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

storageglobalgrid2050 / scripts/clone_v3_to_v4.py · lines 1–150 of 150 · Entry point

What it does
It loads solar, battery storage (BESS) 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: solar, battery storage (BESS), substations.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Clone V3 to V4 Once 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 V3 to V4 Once Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
GlobalGrid2050 — Solar Battery Energy Storage System (BESS) Topology V4 Page (estate URL), Indexforgis Single-Line Diagram (SLD) V4 (estate URL), Module Layout V4 (estate URL), pathlib, shutil, datetime
Used by
run by GlobalGrid2050 Clone V3 to V4 Once 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_v3_to_v4.py:1-150 · blob 81d9f8b92c67e3ec5cbeffce20660d6e162be7af · 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-v3"
DST = ROOT / "solar-bess-topology-v4"
REPORT = ROOT / "gridbot_reports" / "v4_clone_from_v3_report.md"

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

RENAME_PAIRS = [
    ("indexforgis-sld-v3.html", "indexforgis-sld-v4.html"),
    ("gis-sld-v3-config.js", "gis-sld-v4-config.js"),
    ("gis-sld-v3-helpers.js", "gis-sld-v4-helpers.js"),
    ("gis-sld-v3-state.js", "gis-sld-v4-state.js"),
    ("gis-sld-v3-substations.js", "gis-sld-v4-substations.js"),
    ("gis-sld-v3.css", "gis-sld-v4.css"),
    ("gis-sld-v3-map.js", "gis-sld-v4-map.js"),
    ("gis-sld-v3-calculations.js", "gis-sld-v4-calculations.js"),
    ("gis-sld-v3-finance.js", "gis-sld-v4-finance.js"),
    ("gis-sld-v3-ui-core.js", "gis-sld-v4-ui-core.js"),
    ("gis-sld-v3-drawing.js", "gis-sld-v4-drawing.js"),
    ("gis-sld-v3-export.js", "gis-sld-v4-export.js"),
    ("gis-sld-v3-ui.js", "gis-sld-v4-ui.js"),
    ("module-layout-v3.html", "module-layout-v4.html"),
    ("module-layout-v3.css", "module-layout-v4.css"),
    ("module-layout-v3.js", "module-layout-v4.js"),
]

TEXT_REPLACE_PAIRS = [
    ("solar-bess-topology-v3", "solar-bess-topology-v4"),
    ("GIS SLD Financial Sandbox V3", "GIS SLD Financial Sandbox V4"),
    ("GlobalGrid2050 V3", "GlobalGrid2050 V4"),
    ("Module Layout V3", "Module Layout V4"),
    ("Physical Solar Module Layout", "Physical Solar Module Layout"),
    ("indexforgis-sld-v3.html", "indexforgis-sld-v4.html"),
    ("gis-sld-v3-config.js", "gis-sld-v4-config.js"),
    ("gis-sld-v3-helpers.js", "gis-sld-v4-helpers.js"),
    ("gis-sld-v3-state.js", "gis-sld-v4-state.js"),
    ("gis-sld-v3-substations.js", "gis-sld-v4-substations.js"),
    ("gis-sld-v3.css", "gis-sld-v4.css"),
    ("gis-sld-v3-map.js", "gis-sld-v4-map.js"),
    ("gis-sld-v3-calculations.js", "gis-sld-v4-calculations.js"),
    ("gis-sld-v3-finance.js", "gis-sld-v4-finance.js"),
    ("gis-sld-v3-ui-core.js", "gis-sld-v4-ui-core.js"),
    ("gis-sld-v3-drawing.js", "gis-sld-v4-drawing.js"),
    ("gis-sld-v3-export.js", "gis-sld-v4-export.js"),
    ("gis-sld-v3-ui.js", "gis-sld-v4-ui.js"),
    ("module-layout-v3.html", "module-layout-v4.html"),
    ("module-layout-v3.css", "module-layout-v4.css"),
    ("module-layout-v3.js", "module-layout-v4.js"),
    ("V3", "V4"),
    ("v3", "v4"),
]


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 not path.is_file():
            continue
        if path.suffix.lower() not in TEXT_SUFFIXES:
            continue
        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)))

    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 = [
        "# V4 Clone from V3 Report",
        "",
        f"UTC created: {datetime.now(timezone.utc).isoformat()}",
        "",
        "Purpose:",
        "Clone the current V3 application into a separate V4 folder so V3 becomes the safety baseline and future development can continue in V4.",
        "",
        "Source:",
        "solar-bess-topology-v3/",
        "",
        "Destination:",
        "solar-bess-topology-v4/",
        "",
        "Main V4 test URLs after GitHub Pages deploy:",
        "",
        "https://globalgrid2050.com/solar-bess-topology-v4/",
        "https://globalgrid2050.com/solar-bess-topology-v4/indexforgis-sld-v4.html",
        "https://globalgrid2050.com/solar-bess-topology-v4/module-layout-v4.html",
        "",
        "Files cloned:",
        "",
    ]
    report.extend(f"- {f}" for f in files)
    report.extend([
        "",
        "Renamed files:",
        "",
    ])
    report.extend(f"- {old} -> {new}" for old, new in renamed)
    report.extend([
        "",
        "Files with V3 to V4 text references updated:",
        "",
    ])
    report.extend(f"- {f}" for f in changed_files)
    report.extend([
        "",
        "Rollback method:",
        "",
        "Delete solar-bess-topology-v4/ and this report if the clone is not wanted. V3 is not changed by this clone operation.",
        "",
        "Validation checklist:",
        "",
        "1. Open the V4 main app URL.",
        "2. Confirm the map loads.",
        "3. Confirm String and Central tabs work.",
        "4. Draw a grid.",
        "5. Test export cable length, pick up array, rotation and waypoint routing.",
        "6. Open module-layout-v4.html and test physical module layout.",
        "7. Confirm V3 remains unchanged.",
    ])
    REPORT.write_text("\n".join(report) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()

GlobalGrid2050 Clone V3 Tracker to V4

A Python command-line tool in the scripts folder that appends v4 diary (`append_v4_diary`) and writes report (`write_report`). It copies scripts (`copy_scripts`).

storageglobalgrid2050 / scripts/clone_v3_tracker_to_v4.py · lines 1–119 of 119 · Entry point · pattern write_report (shared by 52 files)

What it does
It loads data. Defines 7 functions or classes, including v4_text, rewrite_file, copy_folder, copy_scripts, append_v4_diary. Uses libraries pathlib, shutil. Side effects: reads or writes files.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Create UK Energy Tracking V4 Workflow (globalgrid2050).
What it achieves
Defines `v4_text`, `rewrite_file`, `copy_folder` and 3 more.
Why it matters
Run by GlobalGrid2050 Create UK Energy Tracking V4 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, shutil
Used by
run by GlobalGrid2050 Create UK Energy Tracking V4 Workflow (workflow run)
Produces
v4_text, rewrite_file, copy_folder, copy_scripts, append_v4_diary, write_report, main
Defines here
v4_text, rewrite_file, copy_folder, copy_scripts, append_v4_diary, write_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/clone_v3_tracker_to_v4.py:1-119 · blob ee16676ad3c0fd7bed9e197544f3e3df9ededfbb · 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

root = Path('.')
source = root / 'uk_energy_tracking_v3'
target = root / 'uk_energy_tracking_v4'
report = root / 'gridbot_reports' / 'clone_uk_energy_tracking_v3_to_v4.md'

text_suffixes = {'.md', '.html', '.css', '.js', '.json', '.csv', '.txt', '.py'}

script_pairs = [
    ('scripts/update_uk_energy_v3.py', 'scripts/update_uk_energy_v4.py'),
    ('scripts/update_uk_price_v3.py', 'scripts/update_uk_price_v4.py'),
    ('scripts/update_oil_prices_v3.py', 'scripts/update_oil_prices_v4.py'),
    ('scripts/update_uk_fuel_prices_v3.py', 'scripts/update_uk_fuel_prices_v4.py'),
]


def v4_text(text):
    for old, new in [
        ('uk_energy_tracking_v3', 'uk_energy_tracking_v4'),
        ('/uk_energy_tracking_v3/', '/uk_energy_tracking_v4/'),
        ('UK Live Grid Tracker V3', 'UK Live Grid Tracker V4'),
        ('UK LIVE GRID TRACKER V3', 'UK LIVE GRID TRACKER V4'),
        ('V3 experimental clone', 'V4 experimental clone'),
        ('isolated V3 feeds', 'isolated V4 feeds'),
        ('V3 captured', 'V4 captured'),
        ('V3', 'V4'),
        ('_v3.py', '_v4.py'),
        ('v3', 'v4'),
    ]:
        text = text.replace(old, new)
    return text


def rewrite_file(path):
    if path.suffix.lower() not in text_suffixes:
        return
    try:
        text = path.read_text(encoding='utf-8')
    except UnicodeDecodeError:
        return
    path.write_text(v4_text(text), encoding='utf-8')


def copy_folder():
    if not source.exists():
        raise SystemExit('Missing uk_energy_tracking_v3')
    if target.exists():
        raise SystemExit('uk_energy_tracking_v4 already exists. Stop to avoid overwriting.')
    shutil.copytree(source, target)
    for item in target.rglob('*'):
        if item.is_file():
            rewrite_file(item)


def copy_scripts():
    made = []
    for src_name, dst_name in script_pairs:
        src = root / src_name
        dst = root / dst_name
        if not src.exists():
            continue
        dst.write_text(v4_text(src.read_text(encoding='utf-8')), encoding='utf-8')
        made.append(dst_name)
    return made


def append_v4_diary():
    diary = target / 'WORK_DIARY.md'
    if diary.exists():
        with diary.open('a', encoding='utf-8') as f:
            f.write('\n\n## Diary entry: V4 clone from V3 benchmark\n\n')
            f.write('V4 was cloned from the preserved V3 tracker. V3 is now the benchmark and should not be modified for the next UI experiments. Annual lazy loading, year selection, seasonal filters and further price explanation should be developed in V4 only. V4 workflows should be added separately with correct workflow permissions.\n')


def write_report(scripts):
    report.parent.mkdir(parents=True, exist_ok=True)
    report.write_text('\n'.join([
        '# Clone UK Energy Tracking V3 to V4',
        '',
        'Created V4 from the preserved V3 benchmark.',
        '',
        'New app:',
        '',
        '```text',
        'uk_energy_tracking_v4/',
        'https://globalgrid2050.com/uk_energy_tracking_v4/',
        '```',
        '',
        'Benchmark preserved:',
        '',
        '```text',
        'uk_energy_tracking_v3/',
        '```',
        '',
        'Copied scripts:',
        '',
        '```text',
        '\n'.join(scripts) if scripts else 'none',
        '```',
        '',
        'Workflow files are not created by this clone workflow because GitHub Actions cannot create or update workflow files unless the token has workflow permission. Create V4 workflows separately.',
        '',
        'Rule: patch V4 only. Leave V3 as benchmark.',
        ''
    ]), encoding='utf-8')


def main():
    copy_folder()
    scripts = copy_scripts()
    append_v4_diary()
    write_report(scripts)
    print('V4 clone created')


if __name__ == '__main__':
    main()