GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Gridbot MWh Mobile Bounds Repair and 2 more files

A Python command-line tool in the scripts folder that reads interconnectors. It removes warning (`remove_warning`) and writes report (`write_report`).

408 lines of Python from globalgrid2050, in 3 files. Topic: Automation and CI. Section 1766 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 MWh Mobile Bounds Repair energy-data · globalgrid2050 / scripts/gridbot_mwh_mobile_bounds_repair.py lines 1–182
  2. GlobalGrid2050 Gridbot Replace Modular Note with Summary render · globalgrid2050 / scripts/gridbot_replace_modular_note_with_summary.py lines 1–73
  3. GlobalGrid2050 Gridbot Repo Size Guard storage · globalgrid2050 / scripts/gridbot_repo_size_guard.py lines 1–153

GlobalGrid2050 Gridbot MWh Mobile Bounds Repair

A Python command-line tool in the scripts folder that reads interconnectors. It removes warning (`remove_warning`) and writes report (`write_report`).

energy-dataglobalgrid2050 / scripts/gridbot_mwh_mobile_bounds_repair.py · lines 1–182 of 182 · Entry point · pattern bump_cache (shared by 4 files)

What it does
It loads interconnectors. Defines 11 functions or classes, including now, rel, read, write, remove_warning. Uses libraries __future__, argparse, datetime, json, re. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: interconnectors.
Inputs & outputs
In: JSON file MWH_MOBILE_BOUNDS_REPAIR_LATEST.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot MWh Mobile Bounds Repair Workflow (globalgrid2050).
What it achieves
`/uk_energy_tracking_v6/generation_history/`. It accepts `--apply`.
Why it matters
Run by GlobalGrid2050 Gridbot MWh Mobile Bounds Repair Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, json, re, pathlib
Used by
run by GlobalGrid2050 Gridbot MWh Mobile Bounds Repair Workflow (workflow run)
Produces
now, rel, read, write, remove_warning, inject_css, bump_cache, patch, checks, write_report, main
Defines here
now, rel, read, write, remove_warning, inject_css, bump_cache, patch, checks, 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/gridbot_mwh_mobile_bounds_repair.py:1-182 · blob a1017b9dc4af7a51187f443ed67669ae22059f3d · 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
"""
GridBot MWh Mobile Bounds Repair.

Target:
  /uk_energy_tracking_v6/generation_history/

Purpose:
  Fix phone-width overflow in the MWh cards after the interconnector split. This repair is
  CSS/index-only. It does not change generation aggregate data, interconnector JSON data,
  renderer logic or controller logic.

Fixes:
  - remove the large red interconnector warning box from the MWh panel
  - stop Day/Night split from overflowing when the night segment is tiny
  - stop monthly mini chart and MWh cards from exceeding the viewport
  - override the old interconnector row min-width that pushes bars off-screen
  - add compact metric-grid styling for total electricity check

Audit mode writes reports only. Apply mode writes index.md and reports.
"""
from __future__ import annotations

import argparse
import datetime as dt
import json
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
APP = ROOT / "uk_energy_tracking_v6" / "generation_history"
INDEX = APP / "index.md"
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
REPORT_MD = REPORT_DIR / "MWH_MOBILE_BOUNDS_REPAIR_LATEST.md"
REPORT_JSON = REPORT_JSON_DIR / "MWH_MOBILE_BOUNDS_REPAIR_LATEST.json"
ROUTE = "/uk_energy_tracking_v6/generation_history/"
CACHE = "20260613mwhmobilebounds1"

CSS_MARKER = "GridBot MWh mobile bounds repair"
CSS = f"""
  /* {CSS_MARKER} */
  #generation-history-panel .mwh-panel,
  #generation-history-panel .mwh-card{{box-sizing:border-box;max-width:100%;overflow:hidden;}}
  #generation-history-panel .mwh-aggregate-head{{min-width:0;max-width:100%;}}
  #generation-history-panel .mwh-aggregate-head span{{min-width:0;max-width:54%;overflow:hidden;text-overflow:ellipsis;}}
  #generation-history-panel .mwh-mini-chart{{box-sizing:border-box;width:100%;max-width:100%;min-width:0;overflow:hidden;}}
  #generation-history-panel .mwh-col{{min-width:0;}}
  #generation-history-panel .mwh-split{{box-sizing:border-box;width:100%;max-width:100%;min-width:0;}}
  #generation-history-panel .mwh-split div{{min-width:0!important;overflow:hidden;white-space:nowrap;}}
  #generation-history-panel .mwh-split div:last-child{{font-size:0;}}
  #generation-history-panel .mwh-check-grid{{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:8px;}}
  #generation-history-panel .mwh-check-metric{{border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px;background:rgba(255,255,255,.03);min-width:0;}}
  #generation-history-panel .mwh-check-metric span{{display:block;color:#9aa3b6;font-size:11px;letter-spacing:.06em;text-transform:uppercase;}}
  #generation-history-panel .mwh-check-metric strong{{display:block;color:#f5f7fb;font-size:13px;margin-top:3px;}}
  @media(max-width:850px){{
    #generation-history-panel .mwh-card{{padding:10px;}}
    #generation-history-panel .mwh-aggregate-head{{display:block;}}
    #generation-history-panel .mwh-aggregate-head span{{display:block;max-width:100%;white-space:normal;text-align:left;margin-top:4px;}}
    #generation-history-panel .mwh-row,
    #generation-history-panel .mwh-row.mwh-interconnector-row{{grid-template-columns:minmax(84px,.78fr) minmax(88px,1fr) minmax(58px,auto)!important;gap:6px;}}
    #generation-history-panel .mwh-row.mwh-interconnector-row .mwh-label{{white-space:normal;line-height:1.25;color:#cfd7e6;}}
    #generation-history-panel .mwh-label{{min-width:0;overflow-wrap:anywhere;}}
    #generation-history-panel .mwh-track{{min-width:0;}}
    #generation-history-panel .mwh-value{{font-size:11px;white-space:nowrap;}}
    #generation-history-panel .mwh-check-grid{{grid-template-columns:1fr;}}
  }}
"""


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


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, text: str):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")


def remove_warning(text: str) -> str:
    return re.sub(r'\n?\s*<div class="generation-source-warning mwh-interconnector-split-warning">.*?</div>', '', text, flags=re.DOTALL)


def inject_css(text: str) -> str:
    if CSS_MARKER in text:
        return text
    return text.replace("</style>", CSS + "</style>", 1)


def bump_cache(text: str) -> str:
    for name in ("render_generation_mwh_aggregates", "control_generation_mwh_aggregates"):
        text = re.sub(rf"(/uk_energy_tracking_v6/generation_history/{name}\.js\?v=)[^\"']+", rf"\g<1>{CACHE}", text)
    return text


def patch(text: str) -> str:
    return bump_cache(inject_css(remove_warning(text)))


def checks(patched: str) -> dict[str, bool]:
    return {
        "index_exists": INDEX.exists(),
        "route_present": f"permalink: {ROUTE}" in patched,
        "warning_box_removed": "mwh-interconnector-split-warning" not in patched,
        "mobile_bounds_css_inserted": CSS_MARKER in patched,
        "day_night_split_bounded": "#generation-history-panel .mwh-split div{min-width:0!important" in patched,
        "mini_chart_bounded": "#generation-history-panel .mwh-mini-chart{box-sizing:border-box;width:100%;max-width:100%;" in patched,
        "interconnector_min_width_overridden": "#generation-history-panel .mwh-row.mwh-interconnector-row{grid-template-columns:minmax(84px,.78fr)" in patched,
        "total_check_metric_grid_styled": "#generation-history-panel .mwh-check-grid" in patched and "#generation-history-panel .mwh-check-metric" in patched,
        "cache_busters_updated": CACHE in patched,
        "data_files_not_touched": True,
    }


def write_report(report: dict):
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    lines = [
        "# MWh Mobile Bounds Repair",
        "",
        f"Generated UTC: `{report['generatedUTC']}`",
        f"Mode: `{report['mode']}`",
        f"Pass: `{report['pass']}`",
        "",
        report["executiveSummary"],
        "",
        "## Planned changed files",
        "",
    ]
    lines += [f"- `{p}`" for p in report["plannedChangedFiles"]]
    lines += ["", "## Checks", "", "| Check | Result |", "|---|---|"]
    lines += [f"| {k} | {'✅' if v else '❌'} |" for k, v in report["checks"].items()]
    lines += ["", "## Rollback", "", report["rollbackMethod"], ""]
    write(REPORT_MD, "\n".join(lines))
    write(REPORT_JSON, json.dumps(report, indent=2) + "\n")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()
    mode = "apply" if args.apply else "audit"
    original = read(INDEX)
    patched = patch(original)
    ch = checks(patched)
    planned = [rel(INDEX)] if patched != original else []
    passed = all(ch.values())
    if args.apply and passed and patched != original:
        write(INDEX, patched)
    report = {
        "reportTitle": "MWh Mobile Bounds Repair",
        "schemaVersion": "1.0.0",
        "generatedUTC": now(),
        "repository": "Ventusltd/globalgrid2050",
        "workflowName": "GridBot MWh Mobile Bounds Repair",
        "scriptName": "scripts/gridbot_mwh_mobile_bounds_repair.py",
        "route": ROUTE,
        "mode": mode,
        "changedFiles": planned if args.apply else [],
        "plannedChangedFiles": planned,
        "checks": ch,
        "browserRoutingAffected": True,
        "rollbackMethod": "Revert the apply commit. This repair changes only uk_energy_tracking_v6/generation_history/index.md.",
        "executiveSummary": "Fixes phone-width overflow in the Generation Output in MWh cards. It removes the large red interconnector warning box, bounds the Day/Night split and monthly mini-chart to the card width, overrides the old interconnector min-width rule and styles the total electricity check as compact metrics. No data files are changed.",
        "applied": bool(args.apply),
        "pass": passed,
    }
    write_report(report)
    print(json.dumps(report, indent=2))
    return 0 if passed else 1


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

GlobalGrid2050 Gridbot Replace Modular Note with Summary

A Python command-line tool in the scripts folder.

renderglobalgrid2050 / scripts/gridbot_replace_modular_note_with_summary.py · lines 1–73 of 73 · Entry point · pattern safe_rel (shared by 6 files)

What it does
It loads data. Defines safe_rel, main. Uses libraries __future__, argparse, datetime, pathlib. Side effects: changes the web page (DOM); reads or writes files.
Inputs & outputs
In: command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Defines `safe_rel`. It accepts `--target`, `--summary` and `--backup-dir`.
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
__future__, argparse, datetime, pathlib
Used by
none found
Produces
safe_rel, main
Defines here
safe_rel, 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_replace_modular_note_with_summary.py:1-73 · blob 0ce70576763ca09f485c56564d3fc7a2dbe90b2d · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import datetime as dt
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]


def safe_rel(path_text: str) -> Path:
    path = Path(path_text)
    if not path_text or path.is_absolute() or ".." in path.parts:
        raise SystemExit(f"Unsafe path: {path_text}")
    return path


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--target", required=True)
    parser.add_argument("--summary", required=True)
    parser.add_argument("--backup-dir", default="backups")
    parser.add_argument("--report-dir", default="gridbot_reports")
    args = parser.parse_args()

    target = REPO_ROOT / safe_rel(args.target)
    summary_file = REPO_ROOT / safe_rel(args.summary)

    if not target.exists():
        raise SystemExit(f"Target missing: {target}")
    if not summary_file.exists():
        raise SystemExit(f"Summary missing: {summary_file}")

    original = target.read_text(encoding="utf-8")
    summary = summary_file.read_text(encoding="utf-8").strip()

    old_block = "# Modular Section Index\n\nThis page is intentionally shallow. Each technical topic opens into its own subpage so readers can navigate the guidance without being overwhelmed by the full depth of the document.\n\n"
    if old_block not in original:
        if "# Executive Summary" in original:
            print("Executive summary already installed")
            return
        raise SystemExit("Expected modular note block not found")

    updated = original.replace(old_block, summary + "\n\n", 1)

    timestamp = dt.datetime.utcnow().strftime("%Y%m%d_%H%M%S")
    backup_dir = REPO_ROOT / safe_rel(args.backup_dir)
    backup_dir.mkdir(parents=True, exist_ok=True)
    backup_path = backup_dir / f"{target.stem}_before_executive_summary_{timestamp}{target.suffix}"
    backup_path.write_text(original, encoding="utf-8")

    target.write_text(updated, encoding="utf-8")

    report_dir = REPO_ROOT / safe_rel(args.report_dir)
    report_dir.mkdir(parents=True, exist_ok=True)
    report_path = report_dir / f"solar_er_executive_summary_install_{timestamp}.md"
    report_path.write_text(
        "# Solar ER Executive Summary Install Report\n\n"
        f"UTC: {dt.datetime.utcnow().isoformat(timespec='seconds')}Z\n\n"
        f"Target: `{args.target}`\n\n"
        f"Summary fragment: `{args.summary}`\n\n"
        f"Backup: `{backup_path.relative_to(REPO_ROOT)}`\n\n"
        "Change: replaced the modular note with an executive summary while preserving the section links, print page and disclaimer.\n",
        encoding="utf-8",
    )

    print(f"Updated {target.relative_to(REPO_ROOT)}")
    print(f"Backup {backup_path.relative_to(REPO_ROOT)}")
    print(f"Report {report_path.relative_to(REPO_ROOT)}")


if __name__ == "__main__":
    main()

GlobalGrid2050 Gridbot Repo Size Guard

A Python command-line tool in the scripts folder that works with changed files (`changed_files`).

storageglobalgrid2050 / scripts/gridbot_repo_size_guard.py · lines 1–153 of 153 · Entry point · pattern changed_files (shared by 4 files)

What it does
Defines 7 functions or classes, including mb, run, changed_files, all_files, is_blocked_path. Uses libraries __future__, argparse, json, os, subprocess. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file REPO_SIZE_GUARD_LATEST.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Repo Size Guard Workflow (globalgrid2050).
What it achieves
It is built from the run step (`run`), the all files helper (`all_files`) and the is blocked path helper (`is_blocked_path`). Fails when changed files exceed size budgets or when future commits try to add raw/transient bulk data into normal Git history. It accepts `--scope`, `--warn-mb` and `--fail-mb`.
Why it matters
Run by GlobalGrid2050 Repo Size Guard Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, json, os, subprocess, sys, pathlib, typing
Used by
run by GlobalGrid2050 Repo Size Guard Workflow (workflow run)
Produces
mb, run, changed_files, all_files, is_blocked_path, inspect, main
Defines here
mb, run, changed_files, all_files, is_blocked_path, inspect, 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_size_guard.py:1-153 · blob e39269db28054dca977d2673e08f9455b71ea965 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""GlobalGrid2050 repository size guard.

Fails when changed files exceed size budgets or when future commits try to add
raw/transient bulk data into normal Git history. Existing tracked bloat is handled
by migration/history-cleanup workflows, not by this guard.
"""
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parent.parent

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

BLOCKED_NAME_FRAGMENTS = (
    "raw_api",
    "raw_elexon",
    "raw_pvlive",
    "fuelinst_raw",
    "fuelhh_raw",
    "backfill_tmp",
    "archive_full",
    "master_halfhourly",
)

REPORT_JSON = ROOT / "data_science_protocol" / "audit_reports" / "json" / "REPO_SIZE_GUARD_LATEST.json"


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


def run(cmd: list[str]) -> str:
    return subprocess.check_output(cmd, cwd=ROOT, text=True, stderr=subprocess.DEVNULL).strip()


def changed_files() -> list[str]:
    candidates: list[str] = []
    base_ref = os.getenv("GITHUB_BASE_REF")
    event = os.getenv("GITHUB_EVENT_NAME", "")
    commands = []
    if event == "pull_request" and base_ref:
        commands.append(["git", "diff", "--name-only", f"origin/{base_ref}...HEAD"])
    commands.extend([
        ["git", "diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD"],
        ["git", "diff", "--name-only", "HEAD~1", "HEAD"],
    ])
    for cmd in commands:
        try:
            text = run(cmd)
            if text:
                candidates = [line.strip() for line in text.splitlines() if line.strip()]
                break
        except Exception:
            continue
    if not candidates:
        candidates = [p.relative_to(ROOT).as_posix() for p in ROOT.rglob("*") if p.is_file() and ".git/" not in p.as_posix()]
    return sorted(set(candidates))


def all_files() -> list[str]:
    out = []
    for p in ROOT.rglob("*"):
        if not p.is_file():
            continue
        r = p.relative_to(ROOT).as_posix()
        if r.startswith(".git/") or "/.git/" in r:
            continue
        out.append(r)
    return sorted(out)


def is_blocked_path(path: str) -> bool:
    lower = path.lower()
    if any(lower.startswith(prefix) for prefix in BLOCKED_PREFIXES):
        return True
    return any(fragment in lower for fragment in BLOCKED_NAME_FRAGMENTS)


def inspect(paths: list[str], warn_mb: float, fail_mb: float, allow_bulk: bool) -> dict[str, Any]:
    warnings = []
    failures = []
    inspected = []
    for r in paths:
        p = ROOT / r
        if not p.exists() or not p.is_file():
            continue
        try:
            size = p.stat().st_size
        except FileNotFoundError:
            continue
        row = {"path": r, "sizeBytes": size, "sizeMB": mb(size)}
        inspected.append(row)
        if size >= fail_mb * 1024 * 1024:
            failures.append({**row, "reason": f"file exceeds hard budget of {fail_mb} MB"})
        elif size >= warn_mb * 1024 * 1024:
            warnings.append({**row, "reason": f"file exceeds warning budget of {warn_mb} MB"})
        if is_blocked_path(r) and not allow_bulk:
            failures.append({**row, "reason": "raw/transient/cold path is blocked for normal app repos"})
    return {
        "schemaVersion": "1.0.0",
        "tool": "gridbot_repo_size_guard.py",
        "scopeFileCount": len(paths),
        "inspectedFileCount": len(inspected),
        "warnMB": warn_mb,
        "failMB": fail_mb,
        "allowBulk": allow_bulk,
        "warnings": warnings,
        "failures": failures,
        "pass": len(failures) == 0,
    }


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--scope", choices=["changed", "all"], default=os.getenv("REPO_GUARD_SCOPE", "changed"))
    ap.add_argument("--warn-mb", type=float, default=float(os.getenv("REPO_GUARD_WARN_MB", "5")))
    ap.add_argument("--fail-mb", type=float, default=float(os.getenv("REPO_GUARD_FAIL_MB", "25")))
    ap.add_argument("--write-report", action="store_true")
    args = ap.parse_args()

    allow_bulk = os.getenv("ALLOW_BULK_DATA_COMMIT", "false").lower() in {"1", "true", "yes"}
    paths = changed_files() if args.scope == "changed" else all_files()
    report = inspect(paths, args.warn_mb, args.fail_mb, allow_bulk)
    print(json.dumps(report, indent=2, ensure_ascii=False))

    if args.write_report:
        REPORT_JSON.parent.mkdir(parents=True, exist_ok=True)
        REPORT_JSON.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

    if not report["pass"]:
        print("Repo size guard failed. Move raw/bulk data outside app repos or explicitly run an approved archive workflow.", file=sys.stderr)
        return 1
    return 0


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