GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Gridbot Feature Installer and 2 more files

A Python command-line tool in the scripts folder that reads yaml (`read_yaml`), applies overlay files (`apply_overlay_files`) and inserts after (`insert_after`).

539 lines of Python from globalgrid2050, in 3 files. Topic: Automation and CI. Section 1764 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 Feature Installer storage · globalgrid2050 / scripts/gridbot_feature_installer.py lines 1–316
  2. GlobalGrid2050 Gridbot Insert DC Subsections storage · globalgrid2050 / scripts/gridbot_insert_dc_subsections.py lines 1–108
  3. GlobalGrid2050 Gridbot Insert Markdown Section storage · globalgrid2050 / scripts/gridbot_insert_markdown_section.py lines 1–115

GlobalGrid2050 Gridbot Feature Installer

A Python command-line tool in the scripts folder that reads yaml (`read_yaml`), applies overlay files (`apply_overlay_files`) and inserts after (`insert_after`).

storageglobalgrid2050 / scripts/gridbot_feature_installer.py · lines 1–316 of 316 · Entry point · pattern apply_overlay_files (shared by 2 files)

What it does
It loads data. Defines 15 functions or classes, including log, fail, safe_rel, read_yaml, copy_version. Uses libraries __future__, argparse, datetime, re, shutil. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Feature Install Workflow (globalgrid2050).
What it achieves
It copies version (`copy_version`) and is built from the regex replace helper (`regex_replace`) and the assert contains helper (`assert_contains`). Defines `log`, `fail`, `safe_rel` and 11 more. It reads `manifest.yml`. It accepts `--source`, `--target` and `--features-root`.
Why it matters
Run by GlobalGrid2050 Gridbot Feature Install Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, re, shutil, subprocess, sys, pathlib
Used by
run by GlobalGrid2050 Gridbot Feature Install Workflow (workflow run)
Produces
log, fail, safe_rel, read_yaml, copy_version, apply_overlay_files, replace_text, regex_replace, insert_after, insert_before, assert_contains, run_command
Defines here
log, fail, safe_rel, read_yaml, copy_version, apply_overlay_files, replace_text, regex_replace, insert_after, insert_before, assert_contains, run_command, install_feature, 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_feature_installer.py:1-316 · blob 06a01779a36307c87c4c3826257387a072502af4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3

from __future__ import annotations

import argparse
import datetime as dt
import re
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Any

import yaml


REPO_ROOT = Path(__file__).resolve().parents[1]
REPORT_DIR = REPO_ROOT / "gridbot_reports"


def log(message: str) -> None:
    print(f"[GridBot] {message}")


def fail(message: str) -> None:
    print(f"[GridBot ERROR] {message}", file=sys.stderr)
    raise SystemExit(1)


def safe_rel(path_text: str) -> Path:
    path = Path(path_text)

    if not path_text or path.is_absolute() or ".." in path.parts:
        fail(f"Unsafe path rejected: {path_text}")

    return path


def read_yaml(path: Path) -> dict[str, Any]:
    if not path.exists():
        fail(f"Missing manifest: {path}")

    data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}

    if not isinstance(data, dict):
        fail(f"Manifest must be a YAML mapping: {path}")

    return data


def copy_version(source: Path, target: Path, overwrite: bool) -> None:
    source = source.resolve()
    target = target.resolve()

    if not source.exists():
        fail(f"Source folder missing: {source}")

    if source == target:
        log("Source and target are the same folder. Copy step skipped.")
        return

    if target.exists():
        if not overwrite:
            log(f"Target already exists, keeping it: {target.relative_to(REPO_ROOT)}")
            return
        shutil.rmtree(target)

    shutil.copytree(source, target)
    log(f"Copied {source.relative_to(REPO_ROOT)} to {target.relative_to(REPO_ROOT)}")


def apply_overlay_files(feature_dir: Path) -> list[str]:
    installed: list[str] = []
    files_dir = feature_dir / "files"

    if not files_dir.exists():
        return installed

    for source in sorted(files_dir.rglob("*")):
        if source.is_dir():
            continue

        rel = source.relative_to(files_dir)
        target = REPO_ROOT / rel
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(source, target)
        installed.append(str(rel))

    return installed


def replace_text(op: dict[str, Any]) -> str:
    file_path = REPO_ROOT / safe_rel(str(op["file"]))
    find = str(op["find"])
    replace = str(op["replace"])

    if not file_path.exists():
        fail(f"File missing: {file_path.relative_to(REPO_ROOT)}")

    text = file_path.read_text(encoding="utf-8")
    count = text.count(find)

    if count == 0:
        fail(f"Text not found in {file_path.relative_to(REPO_ROOT)}: {find[:120]}")

    limit = int(op.get("count", 0) or 0)
    new_text = text.replace(find, replace, limit if limit > 0 else -1)
    file_path.write_text(new_text, encoding="utf-8")

    return f"replace: {file_path.relative_to(REPO_ROOT)} | {count} match"


def regex_replace(op: dict[str, Any]) -> str:
    file_path = REPO_ROOT / safe_rel(str(op["file"]))
    pattern = str(op["pattern"])
    replace = str(op["replace"])
    flags_text = str(op.get("flags", ""))

    if not file_path.exists():
        fail(f"File missing: {file_path.relative_to(REPO_ROOT)}")

    flags = 0
    if "i" in flags_text:
        flags |= re.IGNORECASE
    if "m" in flags_text:
        flags |= re.MULTILINE
    if "s" in flags_text:
        flags |= re.DOTALL

    text = file_path.read_text(encoding="utf-8")
    new_text, count = re.subn(pattern, replace, text, flags=flags)

    if count == 0:
        fail(f"Regex did not match in {file_path.relative_to(REPO_ROOT)}: {pattern[:120]}")

    file_path.write_text(new_text, encoding="utf-8")
    return f"regex_replace: {file_path.relative_to(REPO_ROOT)} | {count} match"


def insert_after(op: dict[str, Any]) -> str:
    file_path = REPO_ROOT / safe_rel(str(op["file"]))
    marker = str(op["marker"])
    insert = str(op["insert"])

    if not file_path.exists():
        fail(f"File missing: {file_path.relative_to(REPO_ROOT)}")

    text = file_path.read_text(encoding="utf-8")
    index = text.find(marker)

    if index < 0:
        fail(f"Marker not found in {file_path.relative_to(REPO_ROOT)}: {marker[:120]}")

    position = index + len(marker)
    new_text = text[:position] + insert + text[position:]
    file_path.write_text(new_text, encoding="utf-8")

    return f"insert_after: {file_path.relative_to(REPO_ROOT)}"


def insert_before(op: dict[str, Any]) -> str:
    file_path = REPO_ROOT / safe_rel(str(op["file"]))
    marker = str(op["marker"])
    insert = str(op["insert"])

    if not file_path.exists():
        fail(f"File missing: {file_path.relative_to(REPO_ROOT)}")

    text = file_path.read_text(encoding="utf-8")
    index = text.find(marker)

    if index < 0:
        fail(f"Marker not found in {file_path.relative_to(REPO_ROOT)}: {marker[:120]}")

    new_text = text[:index] + insert + text[index:]
    file_path.write_text(new_text, encoding="utf-8")

    return f"insert_before: {file_path.relative_to(REPO_ROOT)}"


def assert_contains(op: dict[str, Any]) -> str:
    file_path = REPO_ROOT / safe_rel(str(op["file"]))
    required = str(op["text"])

    if not file_path.exists():
        fail(f"File missing: {file_path.relative_to(REPO_ROOT)}")

    text = file_path.read_text(encoding="utf-8")

    if required not in text:
        fail(f"Assertion failed. Missing text in {file_path.relative_to(REPO_ROOT)}: {required[:120]}")

    return f"assert_contains: {file_path.relative_to(REPO_ROOT)}"


def run_command(command: list[str]) -> None:
    log("Running: " + " ".join(command))
    result = subprocess.run(command, cwd=REPO_ROOT, text=True)
    if result.returncode != 0:
        fail(f"Command failed: {' '.join(command)}")


def install_feature(feature_dir: Path) -> list[str]:
    manifest = read_yaml(feature_dir / "manifest.yml")
    changes: list[str] = []

    log(f"Installing feature: {manifest.get('name', feature_dir.name)}")

    for installed in apply_overlay_files(feature_dir):
        changes.append(f"overlay: {installed}")

    operations = manifest.get("operations", [])

    if not isinstance(operations, list):
        fail(f"operations must be a list in {feature_dir / 'manifest.yml'}")

    for op in operations:
        if not isinstance(op, dict):
            fail("Each operation must be a YAML mapping")

        op_type = str(op.get("type", ""))

        if op_type == "replace":
            changes.append(replace_text(op))
        elif op_type == "regex_replace":
            changes.append(regex_replace(op))
        elif op_type == "insert_after":
            changes.append(insert_after(op))
        elif op_type == "insert_before":
            changes.append(insert_before(op))
        elif op_type == "assert_contains":
            changes.append(assert_contains(op))
        else:
            fail(f"Unsupported operation type: {op_type}")

    return changes


def write_report(target: str, features: list[str], changes: list[str]) -> None:
    REPORT_DIR.mkdir(parents=True, exist_ok=True)

    timestamp = dt.datetime.utcnow().strftime("%Y%m%d_%H%M%S")
    report = REPORT_DIR / f"gridbot_install_{timestamp}.md"

    body = [
        "# GridBot Install Report",
        "",
        f"UTC: {dt.datetime.utcnow().isoformat(timespec='seconds')}Z",
        f"Target: `{target}`",
        "",
        "## Features",
        "",
    ]

    for feature in features:
        body.append(f"- `{feature}`")

    body.extend(["", "## Changes", ""])

    for change in changes:
        body.append(f"- {change}")

    body.append("")
    report.write_text("\n".join(body), encoding="utf-8")
    log(f"Report written: {report.relative_to(REPO_ROOT)}")


def main() -> int:
    parser = argparse.ArgumentParser(description="GridBot feature installer")
    parser.add_argument("--source", required=True)
    parser.add_argument("--target", required=True)
    parser.add_argument("--features-root", default="feature_requests")
    parser.add_argument("--feature", action="append")
    parser.add_argument("--overwrite", action="store_true")
    parser.add_argument("--run-tests", action="store_true")

    args = parser.parse_args()

    source = REPO_ROOT / safe_rel(args.source)
    target = REPO_ROOT / safe_rel(args.target)
    features_root = REPO_ROOT / safe_rel(args.features_root)

    copy_version(source, target, args.overwrite)

    if not features_root.exists():
        fail(f"Feature request folder missing: {features_root}")

    if args.feature:
        feature_dirs = [features_root / name for name in args.feature]
    else:
        feature_dirs = sorted([p for p in features_root.iterdir() if p.is_dir()])

    if not feature_dirs:
        fail("No feature folders found")

    changes: list[str] = []
    installed_names: list[str] = []

    for feature_dir in feature_dirs:
        if not feature_dir.exists():
            fail(f"Feature folder missing: {feature_dir}")

        installed_names.append(feature_dir.name)
        changes.extend(install_feature(feature_dir))

    if args.run_tests:
        run_command(["python", "-m", "compileall", "scripts"])

    write_report(args.target, installed_names, changes)

    log("GridBot install complete")
    return 0


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

GlobalGrid2050 Gridbot Insert DC Subsections

A Python command-line tool in the scripts folder that works with renumber dc subsections (`renumber_dc_subsections`). It inserts once (`insert_once`).

storageglobalgrid2050 / scripts/gridbot_insert_dc_subsections.py · lines 1–108 of 108 · Entry point · pattern safe_rel (shared by 6 files)

What it does
It loads data. Defines safe_rel, renumber_dc_subsections, repl, insert_once, main. Uses libraries __future__, argparse, datetime, re, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'dc'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Install Solar DC Er Subsections Workflow (globalgrid2050).
What it achieves
Defines `safe_rel`, `renumber_dc_subsections`, `repl` and 1 more. It accepts `--target`, `--material-fragment` and `--duct-fragment`.
Why it matters
Run by GlobalGrid2050 Install Solar DC Er Subsections Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, re, pathlib
Used by
run by GlobalGrid2050 Install Solar DC Er Subsections Workflow (workflow run)
Produces
safe_rel, renumber_dc_subsections, insert_once, main
Defines here
safe_rel, renumber_dc_subsections, repl, insert_once, 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_insert_dc_subsections.py:1-108 · blob 2920c8548802c0973d7af4b3c653413805214615 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import datetime as dt
import re
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 renumber_dc_subsections(text: str) -> str:
    start = text.find("# 5. DC String and DC Cable System Requirements")
    end = text.find("# 6. Behaviour of Direct Current Systems")
    if start < 0 or end < 0 or end <= start:
        raise SystemExit("Expected DC section boundaries not found. Run first workflow successfully before this workflow.")

    before = text[:start]
    section = text[start:end]
    after = text[end:]

    counter = {"n": 0}

    def repl(match: re.Match[str]) -> str:
        counter["n"] += 1
        return f"## 5.{counter['n']}. {match.group(1).strip()}"

    section = re.sub(r"(?m)^## 5\.\d+\.\s+(.*)$", repl, section)
    return before + section + after


def insert_once(text: str, marker: str, fragment: str) -> str:
    first_line = fragment.strip().splitlines()[0].strip()
    if first_line in text:
        print(f"Already present: {first_line}")
        return text
    if marker not in text:
        raise SystemExit(f"Marker not found: {marker}")
    before, after = text.split(marker, 1)
    return before + fragment.strip() + "\n\n" + marker + after


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--target", required=True)
    parser.add_argument("--material-fragment", required=True)
    parser.add_argument("--duct-fragment", 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)
    material = REPO_ROOT / safe_rel(args.material_fragment)
    duct = REPO_ROOT / safe_rel(args.duct_fragment)

    if not target.exists():
        raise SystemExit(f"Target missing: {target}")
    if not material.exists():
        raise SystemExit(f"Material fragment missing: {material}")
    if not duct.exists():
        raise SystemExit(f"Duct fragment missing: {duct}")

    original = target.read_text(encoding="utf-8")
    updated = original

    material_text = material.read_text(encoding="utf-8")
    duct_text = duct.read_text(encoding="utf-8")

    updated = insert_once(updated, "## 5.5. Connector Compatibility and Termination Quality", material_text)
    updated = insert_once(updated, "## 5.20. Required DC Deliverables", duct_text)
    updated = renumber_dc_subsections(updated)

    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_dc_subsections_{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_dc_subsections_install_{timestamp}.md"
    report_path.write_text(
        "# Solar DC Subsections Install Report\n\n"
        f"UTC: {dt.datetime.utcnow().isoformat(timespec='seconds')}Z\n\n"
        f"Target: `{args.target}`\n\n"
        f"Material fragment: `{args.material_fragment}`\n\n"
        f"Duct fragment: `{args.duct_fragment}`\n\n"
        f"Backup: `{backup_path.relative_to(REPO_ROOT)}`\n\n"
        "Change: inserted material life and duct congestion subsections, then renumbered Section 5 subsections.\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 Insert Markdown Section

A Python command-line tool in the scripts folder that replaces contents (`replace_contents`). It is built from the sub step (`sub`).

storageglobalgrid2050 / scripts/gridbot_insert_markdown_section.py · lines 1–115 of 115 · Entry point · pattern safe_rel (shared by 6 files)

What it does
It loads data. Defines 6 functions or classes, including safe_rel, increment_numbered_headings, top, sub, replace_contents. Uses libraries __future__, argparse, datetime, re, pathlib. Side effects: reads or writes files.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Install Solar DC Er Section Workflow (globalgrid2050).
What it achieves
Defines `safe_rel`, `increment_numbered_headings`, `top` and 2 more. It accepts `--target`, `--fragment` and `--marker`.
Why it matters
Run by GlobalGrid2050 Install Solar DC Er Section Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, re, pathlib
Used by
run by GlobalGrid2050 Install Solar DC Er Section Workflow (workflow run)
Produces
safe_rel, increment_numbered_headings, replace_contents, main
Defines here
safe_rel, increment_numbered_headings, top, sub, replace_contents, 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_insert_markdown_section.py:1-115 · blob f76ed12abb7076c130984b4b76404219e043a900 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import datetime as dt
import re
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 increment_numbered_headings(text: str, start_at: int, offset: int) -> str:
    def top(match: re.Match[str]) -> str:
        num = int(match.group(2))
        if num >= start_at:
            return f"{match.group(1)}{num + offset}{match.group(3)}"
        return match.group(0)

    def sub(match: re.Match[str]) -> str:
        num = int(match.group(2))
        if num >= start_at:
            return f"{match.group(1)}{num + offset}.{match.group(3)}"
        return match.group(0)

    text = re.sub(r"(?m)^(# )(\d+)(\. .*)$", top, text)
    text = re.sub(r"(?m)^(## )(\d+)\.(\d+\. .*)$", sub, text)
    return text


def replace_contents(text: str, contents: str) -> str:
    start = "# Contents\n\n"
    end = "# 3. System Level Electrical Behaviour"
    if start not in text or end not in text:
        raise SystemExit("Contents markers not found")
    before, rest = text.split(start, 1)
    _old, after = rest.split(end, 1)
    return before + start + contents.strip() + "\n\n" + end + after


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--target", required=True)
    parser.add_argument("--fragment", required=True)
    parser.add_argument("--marker", required=True)
    parser.add_argument("--new-contents", required=True)
    parser.add_argument("--backup-dir", default="backups")
    parser.add_argument("--report-dir", default="gridbot_reports")
    parser.add_argument("--start-renumber", type=int, default=5)
    args = parser.parse_args()

    target = REPO_ROOT / safe_rel(args.target)
    fragment = REPO_ROOT / safe_rel(args.fragment)
    contents_file = REPO_ROOT / safe_rel(args.new_contents)

    if not target.exists():
        raise SystemExit(f"Target missing: {target}")
    if not fragment.exists():
        raise SystemExit(f"Fragment missing: {fragment}")
    if not contents_file.exists():
        raise SystemExit(f"Contents file missing: {contents_file}")

    original = target.read_text(encoding="utf-8")
    section = fragment.read_text(encoding="utf-8").strip() + "\n\n"
    new_contents = contents_file.read_text(encoding="utf-8")

    first_line = section.splitlines()[0].strip()
    if first_line in original:
        print(f"Section already present: {first_line}")
        return

    if args.marker not in original:
        raise SystemExit(f"Marker not found: {args.marker}")

    before, tail = original.split(args.marker, 1)
    tail = args.marker + tail
    tail = increment_numbered_headings(tail, args.start_renumber, 1)
    updated = before + section + tail
    updated = replace_contents(updated, new_contents)
    updated = updated.replace("Normative References", "Referenced Standards and Guidance")

    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_dc_section_{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_dc_section_install_{timestamp}.md"
    report_path.write_text(
        "# Solar DC Section Install Report\n\n"
        f"UTC: {dt.datetime.utcnow().isoformat(timespec='seconds')}Z\n\n"
        f"Target: `{args.target}`\n\n"
        f"Fragment: `{args.fragment}`\n\n"
        f"Backup: `{backup_path.relative_to(REPO_ROOT)}`\n\n"
        "Change: inserted staged DC String and DC Cable System Requirements section and renumbered following headings.\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()