In this section
- GlobalGrid2050 Generate V6 Architectural Integrity Protocol storage · globalgrid2050 / scripts/generate_v6_architectural_integrity_protocol.py lines 1–200
- GlobalGrid2050 Generate V8 Codebase Blueprint render · globalgrid2050 / scripts/generate_v8_codebase_blueprint.py lines 1–259
GlobalGrid2050 Generate V6 Architectural Integrity Protocol
A Python command-line tool in the scripts folder that extracts compare summary (`extract_compare_summary`). It is built from the exists step (`exists`).
storageglobalgrid2050 / scripts/generate_v6_architectural_integrity_protocol.py · lines 1–200 of 200 · Entry point · pattern exists (shared by 14 files)
- What it does
- It loads data. Defines exists, extract_compare_summary, main. Uses libraries __future__, datetime, pathlib. Side effects: reads or writes files.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Generate V6 Architectural Integrity Protocol Workflow (globalgrid2050).
- What it achieves
- This is a non destructive guardrail generator.
- Why it matters
- Run by GlobalGrid2050 Generate V6 Architectural Integrity Protocol Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, datetime, pathlib
- Used by
- run by GlobalGrid2050 Generate V6 Architectural Integrity Protocol Workflow (workflow run)
- Produces
- exists, extract_compare_summary, main
- Defines here
- exists, extract_compare_summary, 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/generate_v6_architectural_integrity_protocol.py:1-200 · blob 5fe4e6f5bc84025966079b5fa0d342ddd778ac55 · 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
"""
Generate the V6 Architectural Integrity Protocol.
This is a non destructive guardrail generator. It reads the V5 V6 comparison
report if available and writes a standing protocol into the V6 folder.
Output:
uk_energy_tracking_v6/V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md
"""
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
V6 = ROOT / "uk_energy_tracking_v6"
COMPARE_REPORT = V6 / "V5_V6_COMPARISON_REPORT.md"
OUTPUT = V6 / "V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md"
DOCS = [
"AI_START_HERE.md",
"ARCHITECTURE.md",
"PHILOSOPHY.md",
"LAUNCH_FREEZE.md",
"OPERATOR_MANUAL_V1.md",
"WORKFLOW_REGISTRY.md",
"GRIDBOT_FEATURE_INSTALL_INSTRUCTIONS.md",
"uk_energy_tracking_v5/README.md",
"uk_energy_tracking_v5/AI_RELOAD_INSTRUCTIONS.md",
"uk_energy_tracking_v6/V5_V6_COMPARISON_REPORT.md",
"uk_energy_tracking_v6/V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md",
]
def exists(path: str) -> str:
return "yes" if (ROOT / path).exists() else "no"
def extract_compare_summary() -> list[str]:
if not COMPARE_REPORT.exists():
return [
"Comparison report status: not yet present.",
"Required action: run `Compare UK Energy Tracking V5 and V6` before any V6 repair workflow is designed.",
]
text = COMPARE_REPORT.read_text(encoding="utf-8", errors="replace")
wanted = [
"## Critical chart contract checks",
"## DOM id parity",
"## Page load order",
"## Data file comparison",
"## Initial interpretation rules",
]
lines = text.splitlines()
out: list[str] = []
for heading in wanted:
if heading not in text:
out.append(f"Missing section in comparison report: {heading}")
continue
idx = lines.index(heading)
chunk = []
for line in lines[idx:idx + 45]:
if line.startswith("## ") and line != heading and chunk:
break
chunk.append(line)
out.append("\n".join(chunk))
return out
def main() -> None:
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
compare_status = "present" if COMPARE_REPORT.exists() else "missing"
lines: list[str] = []
lines.append("# V6 Architectural Integrity Protocol")
lines.append("")
lines.append(f"Generated UTC: `{now}`")
lines.append("Status: mandatory pre change guardrail for `uk_energy_tracking_v6`")
lines.append("Scope: UK Energy Tracking V6 only")
lines.append("Comparison report: `" + compare_status + "`")
lines.append("")
lines.append("## 1. Purpose")
lines.append("")
lines.append("This file exists to prevent AI or human haste from overwriting working dependencies in V6. It must be read before any new V6 change is proposed, scripted, reviewed or executed.")
lines.append("")
lines.append("V6 is a modular rewrite of a working reference. Modularisation is not proof of correctness. The working behaviour must be compared against V5 before changes are made.")
lines.append("")
lines.append("## 2. Binding operating rule")
lines.append("")
lines.append("All V6 changes, however small or large, must be made through a named GitHub workflow or a reviewed workflow generated by a script. Direct ad hoc editing of V6 application files is not allowed during repair work.")
lines.append("")
lines.append("The sequence is:")
lines.append("")
lines.append("1. Read this protocol.")
lines.append("2. Read `uk_energy_tracking_v6/V5_V6_COMPARISON_REPORT.md`.")
lines.append("3. Identify one defect or one controlled repair only.")
lines.append("4. Create a Python repair script or deterministic patch script.")
lines.append("5. Create a matching GitHub Actions workflow.")
lines.append("6. Workflow runs the script and writes a report into `uk_energy_tracking_v6/`.")
lines.append("7. Workflow commits only the intended files and the repair report.")
lines.append("8. Maintainer tests the live page.")
lines.append("9. No second feature is added until the first is accepted or reverted.")
lines.append("")
lines.append("## 3. Required documents to read")
lines.append("")
lines.append("| Document | Exists | Purpose |")
lines.append("|---|---:|---|")
purposes = {
"AI_START_HERE.md": "AI starting rules and repo orientation",
"ARCHITECTURE.md": "global architecture and doctrine",
"PHILOSOPHY.md": "platform intent and design philosophy",
"LAUNCH_FREEZE.md": "pre launch freeze rule",
"OPERATOR_MANUAL_V1.md": "operating doctrine and licence guidance",
"WORKFLOW_REGISTRY.md": "workflow preservation rule",
"GRIDBOT_FEATURE_INSTALL_INSTRUCTIONS.md": "controlled workflow method",
"uk_energy_tracking_v5/README.md": "V5 purpose and reference twin rules",
"uk_energy_tracking_v5/AI_RELOAD_INSTRUCTIONS.md": "V5 recovery and AI rules",
"uk_energy_tracking_v6/V5_V6_COMPARISON_REPORT.md": "specific V5 versus V6 defect map",
"uk_energy_tracking_v6/V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md": "this guardrail file",
}
for doc in DOCS:
lines.append(f"| `{doc}` | {exists(doc)} | {purposes.get(doc, '')} |")
lines.append("")
lines.append("## 4. Non negotiable V6 chart contract")
lines.append("")
lines.append("The raw chart must show published data only. Experimental forecast layers must not contaminate the raw chart.")
lines.append("")
lines.append("The current raw chart contract is:")
lines.append("")
lines.append("1. 12 hour, 1 day, 7 day, 30 day, 3 month and 6 month views use full half hourly settlement data.")
lines.append("2. 12 month, 5 year and 10 year views use the daily aggregate file and must preserve daily high, average and low.")
lines.append("3. V5 is the behavioural reference unless the comparison report proves a V6 difference is intentional.")
lines.append("4. High, average and low values must not be hidden for visual neatness.")
lines.append("5. Full screen, period arrows, mobile portrait, mobile landscape and desktop must be checked after every chart repair.")
lines.append("6. Elexon source fields and generated daily aggregate values must remain traceable.")
lines.append("")
lines.append("## 5. Forbidden repair behaviour")
lines.append("")
lines.append("Do not:")
lines.append("")
lines.append("1. Rewrite whole V6 files by hand when a smaller deterministic patch is possible.")
lines.append("2. Add a forecast, annotation or new UI feature while the raw V6 chart is still not at V5 parity.")
lines.append("3. Delete V5, V4 or any stable reference app.")
lines.append("4. Move shared datasets or change data paths without a workflow and explicit approval.")
lines.append("5. Hide data truth to make the chart look cleaner.")
lines.append("6. Patch multiple unrelated defects in one workflow.")
lines.append("7. Trust screenshots alone without comparing source files and data outputs.")
lines.append("")
lines.append("## 6. Required repair workflow shape")
lines.append("")
lines.append("Every V6 repair must use this structure:")
lines.append("")
lines.append("```text")
lines.append("scripts/repair_v6_<short_name>.py")
lines.append(".github/workflows/repair_v6_<short_name>.yml")
lines.append("uk_energy_tracking_v6/V6_REPAIR_<SHORT_NAME>_REPORT.md")
lines.append("```")
lines.append("")
lines.append("The Python script must:")
lines.append("")
lines.append("1. Read this protocol.")
lines.append("2. Read the V5 V6 comparison report.")
lines.append("3. Read the target file or files.")
lines.append("4. Assert expected old text or expected structure before editing.")
lines.append("5. Make the smallest necessary change.")
lines.append("6. Assert expected new text or structure after editing.")
lines.append("7. Write a repair report into the V6 folder.")
lines.append("")
lines.append("The workflow must:")
lines.append("")
lines.append("1. Run the Python repair script.")
lines.append("2. Commit only the target files and the repair report.")
lines.append("3. Use a clear commit message.")
lines.append("4. Avoid broad `git add .` unless the script itself generated a manifest of touched files.")
lines.append("")
lines.append("## 7. Comparison report extracts")
lines.append("")
for block in extract_compare_summary():
lines.append("```text")
lines.append(block)
lines.append("```")
lines.append("")
lines.append("## 8. Approval sentence")
lines.append("")
lines.append("No V6 app change should proceed unless the maintainer can say:")
lines.append("")
lines.append("> This repair has been compared against V5, is limited to one defect, is workflow driven, writes a V6 repair report and preserves the raw published data chart.")
lines.append("")
lines.append("## 9. Final rule")
lines.append("")
lines.append("If there is doubt, stop and regenerate the comparison report. Do not improvise inside V6.")
lines.append("")
OUTPUT.write_text("\n".join(lines), encoding="utf-8")
print(f"Wrote {OUTPUT.relative_to(ROOT)}")
if __name__ == "__main__":
main()GlobalGrid2050 Generate V8 Codebase Blueprint
A Python command-line tool in the scripts folder that reads solar and battery storage (BESS). It reads text (`read_text`) and extracts file summary (`extract_file_summary`).
renderglobalgrid2050 / scripts/generate_v8_codebase_blueprint.py · lines 1–259 of 259 · Entry point · pattern iter_files (shared by 4 files)
- What it does
- It loads solar and battery storage (BESS). Defines 7 functions or classes, including iter_files, rel, read_text, directory_tree, unique_sorted. Uses libraries __future__, datetime, os, re, pathlib. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain terms in the code: solar, battery storage (BESS).
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Generate V8 Codebase Blueprint Workflow (globalgrid2050).
- What it achieves
- Generate a compact V8 codebase blueprint for AI review.
- Why it matters
- Run by GlobalGrid2050 Generate V8 Codebase Blueprint Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, datetime, os, re, pathlib
- Used by
- run by GlobalGrid2050 Generate V8 Codebase Blueprint Workflow (workflow run)
- Produces
- iter_files, rel, read_text, directory_tree, unique_sorted, extract_file_summary, main
- Defines here
- iter_files, rel, read_text, directory_tree, unique_sorted, extract_file_summary, 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/generate_v8_codebase_blueprint.py:1-259 · blob b6d572f4a902511a3f0a2f895ccf86699f708038 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""Generate a compact V8 codebase blueprint for AI review.
Purpose:
Create a small structural map of the V8 codebase so AI and GridBot can
understand the app without reading every full source file.
Output:
solar-bess-topology-v8/CODEBASE_BLUEPRINT.md
Scope:
solar-bess-topology-v8 only. V7 is not scanned or modified.
"""
from __future__ import annotations
import datetime as dt
import os
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TARGET = ROOT / "solar-bess-topology-v8"
OUTPUT = TARGET / "CODEBASE_BLUEPRINT.md"
REPORT = ROOT / "gridbot_reports" / "generate_v8_codebase_blueprint.md"
IGNORE_DIRS = {
".git",
".github",
"node_modules",
"__pycache__",
"venv",
"env",
"dist",
"build",
}
ALLOWED_EXTENSIONS = {
".html",
".css",
".js",
".mjs",
".json",
".md",
".py",
".yml",
".yaml",
}
SIGNATURE_PATTERNS = [
re.compile(r"^\s*function\s+[A-Za-z0-9_$]+\s*\("),
re.compile(r"^\s*async\s+function\s+[A-Za-z0-9_$]+\s*\("),
re.compile(r"^\s*(?:const|let|var)\s+[A-Za-z0-9_$]+\s*=\s*(?:async\s*)?\(?.*?\)?\s*=>"),
re.compile(r"^\s*class\s+[A-Za-z0-9_$]+"),
re.compile(r"^\s*def\s+[A-Za-z0-9_]+\s*\("),
re.compile(r"^\s*class\s+[A-Za-z0-9_]+\s*[:(]"),
]
HTML_ID_PATTERN = re.compile(r"id=[\"']([^\"']+)[\"']")
HTML_CLASS_PATTERN = re.compile(r"class=[\"']([^\"']+)[\"']")
SCRIPT_SRC_PATTERN = re.compile(r"<script[^>]+src=[\"']([^\"']+)[\"']", re.IGNORECASE)
CSS_LINK_PATTERN = re.compile(r"<link[^>]+href=[\"']([^\"']+)[\"']", re.IGNORECASE)
EVENT_PATTERN = re.compile(r"addEventListener\s*\(\s*[\"']([^\"']+)[\"']")
DOM_ID_PATTERN = re.compile(r"getElementById\s*\(\s*[\"']([^\"']+)[\"']")
QUERY_PATTERN = re.compile(r"querySelector(?:All)?\s*\(\s*[\"']([^\"']+)[\"']")
CSS_SELECTOR_PATTERN = re.compile(r"^\s*([.#][A-Za-z0-9_-][^{,]*)")
def iter_files() -> list[Path]:
files: list[Path] = []
for root, dirs, filenames in os.walk(TARGET):
dirs[:] = [d for d in dirs if d not in IGNORE_DIRS]
root_path = Path(root)
for filename in filenames:
path = root_path / filename
if path.suffix.lower() in ALLOWED_EXTENSIONS:
files.append(path)
return sorted(files)
def rel(path: Path) -> str:
return path.relative_to(ROOT).as_posix()
def read_text(path: Path) -> str:
try:
return path.read_text(encoding="utf-8")
except UnicodeDecodeError:
return path.read_text(encoding="latin-1")
def directory_tree(files: list[Path]) -> str:
tree: dict[str, set[str]] = {}
for path in files:
parent = path.parent.relative_to(TARGET).as_posix()
tree.setdefault(parent, set()).add(path.name)
lines = [TARGET.name + "/"]
for parent in sorted(tree):
level = 0 if parent == "." else parent.count("/") + 1
indent = " " * level
if parent != ".":
lines.append(f"{indent}{Path(parent).name}/")
file_indent = " " * (level + 1)
for filename in sorted(tree[parent]):
lines.append(f"{file_indent}{filename}")
return "\n".join(lines)
def unique_sorted(values: list[str], limit: int = 80) -> list[str]:
cleaned = sorted({v.strip() for v in values if v and v.strip()})
return cleaned[:limit]
def extract_file_summary(path: Path) -> str:
text = read_text(path)
lines = text.splitlines()
ext = path.suffix.lower()
parts: list[str] = [f"### `{rel(path)}`", ""]
parts.append(f"Size: `{len(text):,}` characters, `{len(lines):,}` lines")
parts.append("")
if ext == ".html":
ids = unique_sorted(HTML_ID_PATTERN.findall(text))
classes_raw = HTML_CLASS_PATTERN.findall(text)
classes = unique_sorted([c for group in classes_raw for c in group.split()])
scripts = unique_sorted(SCRIPT_SRC_PATTERN.findall(text))
links = unique_sorted(CSS_LINK_PATTERN.findall(text))
if links:
parts.append("Linked CSS:")
parts.extend([f"- `{item}`" for item in links])
parts.append("")
if scripts:
parts.append("Linked scripts:")
parts.extend([f"- `{item}`" for item in scripts])
parts.append("")
if ids:
parts.append("HTML IDs:")
parts.extend([f"- `{item}`" for item in ids])
parts.append("")
if classes:
parts.append("HTML classes:")
parts.extend([f"- `{item}`" for item in classes[:80]])
parts.append("")
if ext in {".js", ".mjs", ".py"}:
signatures = []
for line in lines:
if any(pattern.search(line) for pattern in SIGNATURE_PATTERNS):
signatures.append(line.strip())
events = unique_sorted(EVENT_PATTERN.findall(text))
dom_ids = unique_sorted(DOM_ID_PATTERN.findall(text))
queries = unique_sorted(QUERY_PATTERN.findall(text))
if signatures:
parts.append("Signatures:")
parts.append("```text")
parts.extend(signatures[:120])
parts.append("```")
parts.append("")
if events:
parts.append("Events listened for:")
parts.extend([f"- `{item}`" for item in events])
parts.append("")
if dom_ids:
parts.append("DOM IDs referenced:")
parts.extend([f"- `{item}`" for item in dom_ids])
parts.append("")
if queries:
parts.append("Selectors referenced:")
parts.extend([f"- `{item}`" for item in queries])
parts.append("")
if ext == ".css":
selectors = []
for line in lines:
match = CSS_SELECTOR_PATTERN.search(line)
if match:
selectors.append(match.group(1).strip())
selectors = unique_sorted(selectors, limit=120)
if selectors:
parts.append("CSS selectors:")
parts.extend([f"- `{item}`" for item in selectors])
parts.append("")
if ext in {".md", ".yml", ".yaml", ".json"}:
headings = [line.strip() for line in lines if line.strip().startswith("#")]
if headings:
parts.append("Headings:")
parts.extend([f"- {item}" for item in headings[:60]])
parts.append("")
return "\n".join(parts)
def main() -> int:
if not TARGET.exists():
raise SystemExit("V8 folder does not exist. Run the V8 creation workflow first.")
files = iter_files()
now = dt.datetime.now(dt.timezone.utc).isoformat()
content: list[str] = []
content.append("# GlobalGrid2050 V8 Codebase Blueprint")
content.append("")
content.append(f"Generated UTC: `{now}`")
content.append("")
content.append("This is a compact AI review map of the V8 codebase. It records folder structure, file roles, HTML IDs, linked scripts, linked CSS, JavaScript function signatures, DOM references, event listeners and key CSS selectors.")
content.append("")
content.append("It is intentionally not a full source dump. Use this first, then inspect individual files only when needed.")
content.append("")
content.append("## Directory Structure")
content.append("")
content.append("```text")
content.append(directory_tree(files))
content.append("```")
content.append("")
content.append("## File Summaries")
content.append("")
for path in files:
content.append(extract_file_summary(path))
OUTPUT.write_text("\n".join(content), encoding="utf-8")
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text("\n".join([
"# Generate V8 Codebase Blueprint",
"",
f"Generated UTC: `{now}`",
"",
"## Output",
"",
"```text",
rel(OUTPUT),
"```",
"",
"## Scope",
"",
"Scanned only:",
"",
"```text",
rel(TARGET),
"```",
"",
"## File count",
"",
str(len(files)),
"",
"## Purpose",
"",
"Create a compact code skeleton for AI and GridBot review without pasting the full raw codebase into a prompt.",
"",
]), encoding="utf-8")
print(f"Generated {rel(OUTPUT)} from {len(files)} files.")
return 0
if __name__ == "__main__":
raise SystemExit(main())