GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Repair Public Grid Study Period Selector and 4 more files

A Python command-line tool in the scripts folder that reads procedural docs (`read_procedural_docs`), patches article cache bust (`patch_article_cache_bust`) and writes report (`write_report`).

574 lines of Python from globalgrid2050, in 5 files. Topic: Automation and CI. Section 1774 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 Promote Renewables V6 Homepage storage · globalgrid2050 / scripts/promote_renewables_v6_homepage.py lines 1–36
  2. GlobalGrid2050 Render Site Navigation storage · globalgrid2050 / scripts/render_site_navigation.py lines 1–51
  3. GlobalGrid2050 Repair Public Grid Study Period Selector render · globalgrid2050 / scripts/repair_public_grid_study_period_selector.py lines 1–193
  4. GlobalGrid2050 Repair Public Grid Study Selector Binding render · globalgrid2050 / scripts/repair_public_grid_study_selector_binding.py lines 1–168
  5. GlobalGrid2050 Repair V6 Adaptive Weekly Time Ticks render · globalgrid2050 / scripts/repair_v6_adaptive_weekly_time_ticks.py lines 1–126

GlobalGrid2050 Promote Renewables V6 Homepage

A Python module in the scripts folder that reads solar and battery storage (BESS).

storageglobalgrid2050 / scripts/promote_renewables_v6_homepage.py · lines 1–36 of 36 · Entry point

What it does
It loads solar and battery storage (BESS). Uses libraries pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, battery storage (BESS).
Downstream impact
Used directly by 1 file: GlobalGrid2050 Major Project News V6 Workflow (globalgrid2050).
What it achieves
Its code works with 100 MW and 1 MW.
Why it matters
Run by GlobalGrid2050 Major Project News V6 Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
pathlib
Used by
run by GlobalGrid2050 Major Project News V6 Workflow (workflow run)
Produces
none declared
Defines here
none
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/promote_renewables_v6_homepage.py:1-36 · blob 7621ffe1702d4476a6d3624e23565791212a567e · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
INDEX = ROOT / "index.html"
text = INDEX.read_text(encoding="utf-8")

v6_line = '    { name:"UK Solar + Storage Daily V6", url:"./uk_renewables_pipeline/dashboard_v6_live.html", note:"LIVE · DESNZ Q2 2026 validated snapshot · solar >1MW · BESS >100MW · canonical GlobalGrid/REPD IDs" },\n'
v5_live = '    { name:"UK Solar + Storage Daily V5", url:"./uk_renewables_pipeline/dashboard_v5_live.html", note:"LIVE · daily newspaper · solar >49MWp · BESS >100MW" },'
v5_previous = '    { name:"UK Solar + Storage Daily V5", url:"./uk_renewables_pipeline/dashboard_v5_live.html", note:"previous live · daily newspaper · solar >49MWp · BESS >100MW" },'

if v6_line.strip() in text:
    text = text.replace(v5_live, v5_previous)
else:
    # If an older V6 note exists from a prior partial attempt, replace it rather than duplicate it.
    lines = text.splitlines(keepends=True)
    replaced_existing_v6 = False
    for i, line in enumerate(lines):
        if 'name:"UK Solar + Storage Daily V6"' in line and 'dashboard_v6_live.html' in line:
            lines[i] = v6_line
            replaced_existing_v6 = True
            break
    text = ''.join(lines)
    if not replaced_existing_v6:
        if v5_live in text:
            text = text.replace(v5_live, v6_line + v5_previous, 1)
        elif v5_previous in text:
            text = text.replace(v5_previous, v6_line + v5_previous, 1)
        else:
            raise RuntimeError("Could not locate the V5 homepage entry; refusing to guess where V6 belongs")
    text = text.replace(v5_live, v5_previous)

if text.count('dashboard_v6_live.html') != 1:
    raise RuntimeError("V6 homepage entry must appear exactly once")
INDEX.write_text(text, encoding="utf-8")
print("Homepage V6 promotion PASS")

GlobalGrid2050 Render Site Navigation

A Python command-line tool in the scripts folder.

storageglobalgrid2050 / scripts/render_site_navigation.py · lines 1–51 of 51 · Entry point

What it does
It loads data. Defines render, url. Uses libraries argparse, html, json, re, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'navigation'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: JSON file site-navigation.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Defines `render` and `url`. It accepts `--check`.
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
argparse, html, json, re, pathlib, urllib.parse
Used by
none found
Produces
render
Defines here
render, url
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/render_site_navigation.py:1-51 · blob 3422f25c99840348374c374c7a8b88f3817acf7e · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""Render the stable homepage from its reviewed navigation configuration.

Run normally after changing catalogue/site-navigation.json; --check never writes.
The archive catalogue is independent and cannot add front-page nests.
"""
import argparse
import html
import json
import re
from pathlib import Path
from urllib.parse import urlsplit

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

def render(config):
    if config.get('schema_version') != 1:
        raise ValueError('Unsupported navigation schema')
    nests = config['nests']
    ids = [n['id'] for n in nests]
    if not nests or len(ids) != len(set(ids)):
        raise ValueError('Nest IDs must be nonempty and unique')
    esc = lambda value: html.escape(value, quote=True)
    def url(value):
        parsed = urlsplit(value)
        if parsed.scheme != 'https' or not parsed.netloc or parsed.username or parsed.password:
            raise ValueError('Navigation requires a full HTTPS URL without credentials')
        return esc(value)
    rows = []
    for i, n in enumerate(nests, 1):
        if not re.fullmatch(r'[a-z][a-z0-9-]*', n['id']):
            raise ValueError('Invalid nest ID')
        if not isinstance(n['open'], bool):
            raise ValueError('open must be a boolean')
        opened = ' open' if n['open'] else ''
        rows.append(f'<details id="{esc(n["id"])}"{opened}><summary><span class="number">{i:02}</span><span class="title">{esc(n["title"])}<small>{esc(n["subtitle"])}</small></span></summary><div class="inside"><p>{esc(n["description"])}</p><a class="launch" href="{url(n["url"])}">{esc(n["label"])} &rarr;</a></div></details>')
    template = (ROOT / 'scripts/homepage.template.html').read_text(encoding='utf-8')
    return template.replace('{{NESTS}}', '\n'.join(rows)).replace('{{ARCHIVE_URL}}', url(config['archive']['url'])).replace('{{ARCHIVE_LABEL}}', esc(config['archive']['label']))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--check', action='store_true')
    args = parser.parse_args()
    output = render(json.loads((ROOT / 'catalogue/site-navigation.json').read_text(encoding='utf-8')))
    target = ROOT / 'index.html'
    if args.check:
        if target.read_text(encoding='utf-8') != output:
            raise SystemExit('Homepage differs from configuration: run python scripts/render_site_navigation.py')
        print('Homepage matches navigation configuration')
    else:
        target.write_text(output, encoding='utf-8', newline='\n')
        print('Rendered index.html')

GlobalGrid2050 Repair Public Grid Study Period Selector

A Python command-line tool in the scripts folder that reads procedural docs (`read_procedural_docs`), patches article cache bust (`patch_article_cache_bust`) and writes report (`write_report`).

renderglobalgrid2050 / scripts/repair_public_grid_study_period_selector.py · lines 1–193 of 193 · Entry point · pattern must_not_contain (shared by 2 files)

What it does
It draws its content. Defines 12 functions or classes, including read, write, must_contain, must_not_contain, replace_once. Uses libraries pathlib, datetime. Side effects: changes the web page (DOM); reads or writes files.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Repair Public Grid Study Period Selector Workflow (globalgrid2050).
What it achieves
It replaces once (`replace_once`) and is built from the must not contain helper (`must_not_contain`) and the helper text helper (`helper_text`). Defines `read`, `write`, `must_contain` and 8 more.
Why it matters
Run by GlobalGrid2050 Repair Public Grid Study Period Selector Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, datetime
Used by
run by GlobalGrid2050 Repair Public Grid Study Period Selector Workflow (workflow run)
Produces
read, write, must_contain, must_not_contain, replace_once, read_procedural_docs, helper_text, patch_helper, patch_article_cache_bust, write_report, assert_final_state, main
Defines here
read, write, must_contain, must_not_contain, replace_once, read_procedural_docs, helper_text, patch_helper, patch_article_cache_bust, write_report, assert_final_state, 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/repair_public_grid_study_period_selector.py:1-193 · blob 89fde94626ed0d1e76a130a28fcde0e2fcfdb852 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: production_core
from pathlib import Path
from datetime import datetime, timezone

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

FILES = {
    "ai_start": ROOT / "AI_START_HERE.md",
    "architecture": ROOT / "ARCHITECTURE.md",
    "launch_freeze": ROOT / "LAUNCH_FREEZE.md",
    "workflow_registry": ROOT / "WORKFLOW_REGISTRY.md",
    "operator_manual": ROOT / "OPERATOR_MANUAL_V1.md",
    "article": ROOT / "data" / "grid_studies_public" / "great_britain_electricity_price_grid_constraint_trends_2016_2026.html",
    "helper": ROOT / "data" / "grid_studies_public" / "gb_electricity_year_selector.js",
    "report": ROOT / "data" / "grid_studies_public" / "PUBLIC_GRID_STUDY_PERIOD_SELECTOR_REPAIR_REPORT.md",
}

TOUCHED = []


def read(path):
    if not path.exists():
        raise SystemExit(f"Missing required file: {path.relative_to(ROOT)}")
    return path.read_text(encoding="utf-8")


def write(path, text):
    old = path.read_text(encoding="utf-8") if path.exists() else ""
    if old != text:
        path.write_text(text, encoding="utf-8")
        rel = str(path.relative_to(ROOT))
        if rel not in TOUCHED:
            TOUCHED.append(rel)


def must_contain(text, needle, label):
    if needle not in text:
        raise SystemExit(f"Missing expected marker in {label}: {needle[:160]}")


def must_not_contain(text, needle, label):
    if needle in text:
        raise SystemExit(f"Unexpected marker in {label}: {needle[:160]}")


def replace_once(text, old, new, label):
    count = text.count(old)
    if count != 1:
        raise SystemExit(f"Expected exactly 1 match in {label}, found {count}: {old[:160]}")
    return text.replace(old, new, 1)


def read_procedural_docs():
    checks = {
        "ai_start": "AI proposes.",
        "architecture": "Use Python, YAML and GitHub Actions",
        "launch_freeze": "Freeze structure. Fix function. Document risks. Clean later.",
        "workflow_registry": "No workflow should be removed, renamed or archived",
        "operator_manual": "AI proposes. Python processes. GitHub records. GridBot executes. The maintainer approves.",
    }
    for key, marker in checks.items():
        text = read(FILES[key])
        must_contain(text, marker, key)


def helper_text():
    return """(function(){
  var FIRST_YEAR=2016;
  var YEAR_ROLLOVER_MONTH=0;
  var YEAR_ROLLOVER_DAY=15;
  var PERIODS=[
    {value:'7d',label:'1 week'},
    {value:'30d',label:'1 month'},
    {value:'3m',label:'3 months'},
    {value:'6m',label:'6 months'},
    {value:'12m',label:'12 months Jan to Dec'}
  ];
  function $(id){return document.getElementById(id)}
  function activeDataYear(){var d=new Date();var y=d.getUTCFullYear();if(d.getUTCMonth()===YEAR_ROLLOVER_MONTH&&d.getUTCDate()<YEAR_ROLLOVER_DAY)return y-1;return y}
  function ymd(d){return d.toISOString().slice(0,10)}
  function label(year){return year===activeDataYear()?String(year)+' YTD':String(year)}
  function maxDate(){return window.V6LoadPriceHistoryData&&window.V6LoadPriceHistoryData.maxDate?window.V6LoadPriceHistoryData.maxDate():new Date()}
  function periodDays(period){return window.V6LoadPriceHistoryData&&window.V6LoadPriceHistoryData.periodDays?window.V6LoadPriceHistoryData.periodDays(period):365}
  function periodLabel(period){var found=PERIODS.filter(function(p){return p.value===period})[0];return found?found.label:period}
  function yearStart(year){return new Date(Date.UTC(year,0,1,0,0,0))}
  function yearEnd(year){return year===activeDataYear()?maxDate():new Date(Date.UTC(year,11,31,23,59,59))}
  function selectedYear(){var sel=$('gg2050-electricity-year-select');return sel?Number(sel.value):activeDataYear()}
  function selectedPeriod(){var sel=$('gg2050-electricity-period-select');return sel&&sel.value?sel.value:'12m'}
  function rangeFor(year,period){var start=yearStart(year),end=yearEnd(year);if(period==='12m')return{start:start,end:end};var days=periodDays(period),candidate=new Date(start.getTime()+days*86400000);if(candidate<end)end=candidate;return{start:start,end:end}}
  function addStyles(){if($('gg2050-year-selector-style'))return;var s=document.createElement('style');s.id='gg2050-year-selector-style';s.textContent='.gg2050-year-period-controls{display:grid;grid-template-columns:1fr 1fr;gap:10px;width:100%;margin:0 0 10px 0}.gg2050-year-select-label{display:flex;align-items:center;justify-content:space-between;gap:8px;border:1px solid rgba(0,255,255,.45);borde  … [line shortened here: 917 characters; full line on GitHub]
  function filterRows(result,start,end){result.rows=(result.rows||[]).filter(function(r){var raw=r.date?r.date+'T12:00:00Z':(r.priceTimeUTC||r.time);var t=new Date(raw);return t>=start&&t<=end});return result}
  function renderSelection(){var year=selectedYear(),period=selectedPeriod(),range=rangeFor(year,period);window.V6LoadPriceHistoryData.loadWindow(range.start,period,'all').then(function(result){result.end=range.end;result.period=period;filterRows(result,range.start,range.end);window.V6RenderPriceChart.render(result);var status=$('price-history-range-status');if(status)status.textContent=ymd(range.  … [line shortened here: 679 characters; full line on GitHub]
  function buildSelect(id,items,value){var sel=document.createElement('select');sel.id=id;items.forEach(function(item){var o=document.createElement('option');o.value=item.value;o.textContent=item.label;sel.appendChild(o)});sel.value=value;return sel}
  function init(){var grid=$('preset-grid');if(!grid||$('gg2050-electricity-year-select'))return;if(!window.V6LoadPriceHistoryData||!window.V6RenderPriceChart)return;addStyles();var wrap=document.createElement('div');wrap.className='gg2050-year-period-controls';var yearLab=document.createElement('label');yearLab.className='gg2050-year-select-label';yearLab.appendChild(document.createTextNode('Year  … [line shortened here: 1,203 characters; full line on GitHub]
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();
})();
"""


def patch_helper():
    current = read(FILES["helper"])
    must_contain(current, "function activeDataYear()", "existing helper active year")
    must_contain(current, "function renderYear(year)", "existing helper render year")
    must_not_contain(current, "gg2050-electricity-period-select", "existing helper should not already contain period selector")
    new = helper_text()
    must_contain(new, "gg2050-electricity-period-select", "new helper period selector")
    must_contain(new, "12 months Jan to Dec", "new helper default period label")
    must_contain(new, "periodSel=buildSelect('gg2050-electricity-period-select',PERIODS,'12m')", "new helper default period")
    write(FILES["helper"], new)


def patch_article_cache_bust():
    article = read(FILES["article"])
    must_contain(article, "id=\"preset-grid\"", "public grid study preset grid")
    must_contain(article, "gb_electricity_year_selector.js?v=20260604year2", "public grid study existing helper version")
    updated = replace_once(article, "gb_electricity_year_selector.js?v=20260604year2", "gb_electricity_year_selector.js?v=20260605period1", "helper cache bust")
    must_contain(updated, "gb_electricity_year_selector.js?v=20260605period1", "public grid study new helper version")
    write(FILES["article"], updated)


def write_report():
    report = f"""# Public Grid Study Repair Report: Year and Period Selector

Generated UTC: {datetime.now(timezone.utc).isoformat()}

## Scope

This workflow adds a Period selector beside the existing Year selector on the public Great Britain electricity price and grid constraint study chart.

## Intended behaviour

1. Existing preset buttons remain in place.
2. The Year selector remains in place.
3. A new Period selector is added with 1 week, 1 month, 3 months, 6 months and 12 months Jan to Dec.
4. The default period is 12 months Jan to Dec.
5. Selecting a year defaults to that calendar year unless the current active year is year to date.
6. Selecting a shorter period starts from 1 January of the selected year and ends after the chosen period, or at the available current data limit for the active YTD year.
7. The chart continues to use the existing V6 loader and renderer.
8. The existing preset buttons remain available for COVID, gas squeeze, 2021 spike, Ukraine crisis, negative price regime and latest 24 hour, 48 hour and 1 week views.

## Files touched by script

{chr(10).join('- ' + x for x in TOUCHED) if TOUCHED else '- No file content changes were required'}

## Guardrails checked

- AI_START_HERE.md read.
- ARCHITECTURE.md read.
- LAUNCH_FREEZE.md read.
- WORKFLOW_REGISTRY.md read.
- OPERATOR_MANUAL_V1.md read.
- No workflow was deleted, renamed or archived.
- Existing chart preset buttons were not removed.
- Existing data loader and renderer paths remain unchanged.

## Maintainer test checklist

1. Open /data/grid_studies_public/great_britain_electricity_price_grid_constraint_trends_2016_2026.html.
2. Confirm Year and Period selectors appear above the existing buttons.
3. Confirm Period defaults to 12 months Jan to Dec.
4. Select 2016 and confirm Jan to Dec 2016 loads.
5. Select 2022 and confirm Jan to Dec 2022 loads.
6. Select 2026 YTD and confirm the active year to date range loads.
7. Change Period to 1 month, 3 months and 6 months and confirm the chart updates from 1 January of the selected year.
8. Confirm the existing preset buttons still work.
"""
    write(FILES["report"], report)


def assert_final_state():
    helper = read(FILES["helper"])
    article = read(FILES["article"])
    must_contain(helper, "gg2050-electricity-period-select", "helper final period selector")
    must_contain(helper, "12 months Jan to Dec", "helper final default label")
    must_contain(helper, "window.V6LoadPriceHistoryData.loadWindow", "helper final loader preserved")
    must_contain(article, "gb_electricity_year_selector.js?v=20260605period1", "article final cache bust")
    must_contain(article, "Latest 24 hours", "article buttons preserved")
    must_contain(article, "Latest 48 hours", "article buttons preserved")
    must_contain(article, "Latest 1 week", "article buttons preserved")


def main():
    read_procedural_docs()
    patch_helper()
    patch_article_cache_bust()
    assert_final_state()
    write_report()
    print("Public grid study period selector repair prepared.")
    for item in TOUCHED:
        print("touched:", item)


if __name__ == "__main__":
    main()

GlobalGrid2050 Repair Public Grid Study Selector Binding

A Python command-line tool in the scripts folder that reads docs (`read_docs`), patches article cache (`patch_article_cache`) and writes report (`write_report`).

renderglobalgrid2050 / scripts/repair_public_grid_study_selector_binding.py · lines 1–168 of 168 · Entry point · pattern patch_helper (shared by 2 files)

What it does
It draws its content. Defines 11 functions or classes, including read, write, must_contain, replace_once, read_docs. Uses libraries pathlib, datetime. Side effects: changes the web page (DOM); reads or writes files.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Repair Public Grid Study Selector Binding Workflow (globalgrid2050).
What it achieves
It replaces once (`replace_once`) and is built from the helper text helper (`helper_text`) and the patch helper helper (`patch_helper`). Defines `read`, `write`, `must_contain` and 7 more.
Why it matters
Run by GlobalGrid2050 Repair Public Grid Study Selector Binding Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, datetime
Used by
run by GlobalGrid2050 Repair Public Grid Study Selector Binding Workflow (workflow run)
Produces
read, write, must_contain, replace_once, read_docs, helper_text, patch_helper, patch_article_cache, assert_final, write_report, main
Defines here
read, write, must_contain, replace_once, read_docs, helper_text, patch_helper, patch_article_cache, assert_final, 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/repair_public_grid_study_selector_binding.py:1-168 · blob dd90d7f0b088aab7610408a2a5e956efdf5d10dc · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: production_core
from pathlib import Path
from datetime import datetime, timezone

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

FILES = {
    "ai_start": ROOT / "AI_START_HERE.md",
    "architecture": ROOT / "ARCHITECTURE.md",
    "operator_manual": ROOT / "OPERATOR_MANUAL_V1.md",
    "workflow_registry": ROOT / "WORKFLOW_REGISTRY.md",
    "helper": ROOT / "data" / "grid_studies_public" / "gb_electricity_year_selector.js",
    "article": ROOT / "data" / "grid_studies_public" / "great_britain_electricity_price_grid_constraint_trends_2016_2026.html",
    "report": ROOT / "data" / "grid_studies_public" / "PUBLIC_GRID_STUDY_SELECTOR_BINDING_REPAIR_REPORT.md",
}

TOUCHED = []


def read(path):
    if not path.exists():
        raise SystemExit(f"Missing required file: {path.relative_to(ROOT)}")
    return path.read_text(encoding="utf-8")


def write(path, text):
    old = path.read_text(encoding="utf-8") if path.exists() else ""
    if old != text:
        path.write_text(text, encoding="utf-8")
        rel = str(path.relative_to(ROOT))
        if rel not in TOUCHED:
            TOUCHED.append(rel)


def must_contain(text, needle, label):
    if needle not in text:
        raise SystemExit(f"Missing expected marker in {label}: {needle[:160]}")


def replace_once(text, old, new, label):
    count = text.count(old)
    if count != 1:
        raise SystemExit(f"Expected exactly 1 match in {label}, found {count}: {old[:160]}")
    return text.replace(old, new, 1)


def read_docs():
    checks = {
        "ai_start": "AI proposes.",
        "architecture": "Use Python, YAML and GitHub Actions",
        "operator_manual": "AI proposes. Python processes. GitHub records. GridBot executes. The maintainer approves.",
        "workflow_registry": "No workflow should be removed, renamed or archived",
    }
    for key, marker in checks.items():
        must_contain(read(FILES[key]), marker, key)


def helper_text():
    return """(function(){
  var FIRST_YEAR=2016;
  var YEAR_ROLLOVER_MONTH=0;
  var YEAR_ROLLOVER_DAY=15;
  var PERIODS=[
    {value:'7d',label:'1 week'},
    {value:'30d',label:'1 month'},
    {value:'3m',label:'3 months'},
    {value:'6m',label:'6 months'},
    {value:'12m',label:'12 months Jan to Dec'}
  ];
  function $(id){return document.getElementById(id)}
  function activeDataYear(){var d=new Date();var y=d.getUTCFullYear();if(d.getUTCMonth()===YEAR_ROLLOVER_MONTH&&d.getUTCDate()<YEAR_ROLLOVER_DAY)return y-1;return y}
  function ymd(d){return d.toISOString().slice(0,10)}
  function label(year){return year===activeDataYear()?String(year)+' YTD':String(year)}
  function maxDate(){return window.V6LoadPriceHistoryData&&window.V6LoadPriceHistoryData.maxDate?window.V6LoadPriceHistoryData.maxDate():new Date()}
  function periodDays(period){return window.V6LoadPriceHistoryData&&window.V6LoadPriceHistoryData.periodDays?window.V6LoadPriceHistoryData.periodDays(period):365}
  function periodLabel(period){var found=PERIODS.filter(function(p){return p.value===period})[0];return found?found.label:period}
  function yearStart(year){return new Date(Date.UTC(year,0,1,0,0,0))}
  function yearEnd(year){return year===activeDataYear()?maxDate():new Date(Date.UTC(year,11,31,23,59,59))}
  function selectedYear(){var sel=$('gg2050-electricity-year-select');return sel?Number(sel.value):activeDataYear()}
  function selectedPeriod(){var sel=$('gg2050-electricity-period-select');return sel&&sel.value?sel.value:'12m'}
  function rangeFor(year,period){var start=yearStart(year),end=yearEnd(year);if(period==='12m')return{start:start,end:end};var days=periodDays(period),candidate=new Date(start.getTime()+days*86400000-1000);if(candidate<end)end=candidate;return{start:start,end:end}}
  function addStyles(){if($('gg2050-year-selector-style'))return;var s=document.createElement('style');s.id='gg2050-year-selector-style';s.textContent='.gg2050-year-period-controls{display:grid;grid-template-columns:1fr 1fr;gap:10px;width:100%;margin:0 0 10px 0}.gg2050-year-select-label{display:flex;align-items:center;justify-content:space-between;gap:8px;border:1px solid rgba(0,255,255,.45);borde  … [line shortened here: 1,246 characters; full line on GitHub]
  function filterRows(result,start,end){result.rows=(result.rows||[]).filter(function(r){var raw=r.date?r.date+'T12:00:00Z':(r.priceTimeUTC||r.time);var t=new Date(raw);return t>=start&&t<=end});return result}
  function clearPresetButtons(){var grid=$('preset-grid');if(!grid)return;grid.querySelectorAll('button').forEach(function(b){b.classList.remove('active')});var apply=$('gg2050-apply-selection');if(apply)apply.classList.add('active')}
  function renderSelection(){var year=selectedYear(),period=selectedPeriod(),range=rangeFor(year,period);clearPresetButtons();window.V6LoadPriceHistoryData.loadWindow(range.start,period,'all').then(function(result){result.end=range.end;result.period=period;filterRows(result,range.start,range.end);window.V6RenderPriceChart.render(result);var status=$('price-history-range-status');if(status)status.t  … [line shortened here: 700 characters; full line on GitHub]
  function buildSelect(id,items,value){var sel=document.createElement('select');sel.id=id;items.forEach(function(item){var o=document.createElement('option');o.value=item.value;o.textContent=item.label;sel.appendChild(o)});sel.value=value;return sel}
  function init(){var grid=$('preset-grid');if(!grid||$('gg2050-electricity-year-select'))return;if(!window.V6LoadPriceHistoryData||!window.V6RenderPriceChart)return;addStyles();var wrap=document.createElement('div');wrap.className='gg2050-year-period-controls';var yearLab=document.createElement('label');yearLab.className='gg2050-year-select-label';yearLab.appendChild(document.createTextNode('Year  … [line shortened here: 1,506 characters; full line on GitHub]
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();
})();
"""


def patch_helper():
    old = read(FILES["helper"])
    must_contain(old, "gg2050-electricity-period-select", "existing period selector helper")
    must_contain(old, "grid.querySelectorAll('button').forEach", "existing active button clearing logic")
    new = helper_text()
    must_contain(new, "Apply selected year and period", "new apply button")
    must_contain(new, "setTimeout(renderSelection,120)", "new initial selection render")
    must_contain(new, "periodSel=buildSelect('gg2050-electricity-period-select',PERIODS,'12m')", "new default 12m")
    write(FILES["helper"], new)


def patch_article_cache():
    article = read(FILES["article"])
    must_contain(article, "gb_electricity_year_selector.js?v=20260605period1", "existing helper cache bust")
    article = replace_once(article, "gb_electricity_year_selector.js?v=20260605period1", "gb_electricity_year_selector.js?v=20260605period2", "helper cache bust")
    write(FILES["article"], article)


def assert_final():
    helper = read(FILES["helper"])
    article = read(FILES["article"])
    must_contain(helper, "gg2050-apply-selection", "helper final apply button")
    must_contain(helper, "clearPresetButtons()", "helper final active clearing")
    must_contain(helper, "setTimeout(renderSelection,120)", "helper final initial render")
    must_contain(helper, "12 months Jan to Dec", "helper final default label")
    must_contain(article, "gb_electricity_year_selector.js?v=20260605period2", "article final cache bust")


def write_report():
    report = f"""# Public Grid Study Selector Binding Repair Report

Generated UTC: {datetime.now(timezone.utc).isoformat()}

## Problem found

The Year and Period selectors were visible, but the existing preset button state could remain visually and functionally dominant. On mobile this made the chart appear to remain locked to the 10 year preset even after changing the Period selector.

## Repair

1. Added an explicit Apply selected year and period button.
2. Added both input and change listeners for mobile selector behaviour.
3. Clears preset button active state before rendering the selected year and period.
4. Marks the selector apply button active after selector rendering.
5. Defaults the selector based chart to 12 months Jan to Dec.
6. Triggers a selector render after page load so the selector state and chart state are aligned.
7. Preserves all existing preset buttons.

## Files touched by script

{chr(10).join('- ' + x for x in TOUCHED) if TOUCHED else '- No file content changes were required'}

## Maintainer test checklist

1. Open the public grid study page.
2. Confirm Year and Period selectors appear.
3. Confirm an Apply selected year and period button appears.
4. Confirm default selector chart is 12 months Jan to Dec or current YTD for the active year.
5. Select 2016 and 6 months, then apply if needed.
6. Confirm the chart no longer remains on 10 year view.
7. Confirm all existing preset buttons still work.
"""
    write(FILES["report"], report)


def main():
    read_docs()
    patch_helper()
    patch_article_cache()
    assert_final()
    write_report()
    print("Public grid study selector binding repair prepared.")
    for item in TOUCHED:
        print("touched:", item)


if __name__ == "__main__":
    main()

GlobalGrid2050 Repair V6 Adaptive Weekly Time Ticks

A Python command-line tool in the scripts folder that replaces function (`replace_function`), patches renderer (`patch_renderer`) and writes report (`write_report`).

renderglobalgrid2050 / scripts/repair_v6_adaptive_weekly_time_ticks.py · lines 1–126 of 126 · Entry point · pattern replace_function (shared by 4 files)

What it does
It loads data. Defines 7 functions or classes, including read, write, must_contain, replace_function, patch_renderer. Uses libraries pathlib, datetime. Side effects: reads or writes files.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Repair V6 Adaptive Weekly Time Ticks Workflow (globalgrid2050).
What it achieves
Defines `read`, `write`, `must_contain` and 3 more.
Why it matters
Run by GlobalGrid2050 Repair V6 Adaptive Weekly Time Ticks Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, datetime
Used by
run by GlobalGrid2050 Repair V6 Adaptive Weekly Time Ticks Workflow (workflow run)
Produces
read, write, must_contain, replace_function, patch_renderer, write_report, main
Defines here
read, write, must_contain, replace_function, patch_renderer, 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/repair_v6_adaptive_weekly_time_ticks.py:1-126 · blob 2bcf946c4b4d11c2e44bed0a7cc12bfb82e6a6c9 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
from pathlib import Path
from datetime import datetime, timezone

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

FILES = {
    "ai_start": ROOT / "AI_START_HERE.md",
    "protocol": ROOT / "uk_energy_tracking_v6" / "V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md",
    "renderer": ROOT / "uk_energy_tracking_v6" / "price_history_chart" / "render_price_chart" / "render_price_chart.js",
    "report": ROOT / "uk_energy_tracking_v6" / "V6_REPAIR_ADAPTIVE_WEEKLY_TIME_TICKS_REPORT.md",
}

TOUCHED = []


def read(path):
    if not path.exists():
        raise SystemExit(f"Missing required file: {path}")
    return path.read_text(encoding="utf-8")


def write(path, text):
    old = read(path)
    if old != text:
        path.write_text(text, encoding="utf-8")
        TOUCHED.append(str(path.relative_to(ROOT)))


def must_contain(text, needle, label):
    if needle not in text:
        raise SystemExit(f"Missing expected marker in {label}: {needle}")


def replace_function(text, name, replacement):
    start = text.find("function " + name + "(")
    if start < 0:
        raise SystemExit(f"Function not found: {name}")
    next_marker = text.find("\n  function ", start + 1)
    if next_marker < 0:
        raise SystemExit(f"Could not find end of function: {name}")
    return text[:start] + replacement + text[next_marker:]


def patch_renderer():
    path = FILES["renderer"]
    text = read(path)

    must_contain(text, "function drawShortWindowTicks", "renderer current weekly tick helper")
    must_contain(text, "span>7.1*86400000", "renderer one week guard")
    must_contain(text, "function drawAxes", "renderer axes helper")

    new_ticks = """function drawShortWindowTicks(g,w,h,q,pad,t0,t1,span){if(span>7.1*86400000)return;g.save();g.textAlign='center';var plotW=w-pad.left-pad.right;if(span>2.1*86400000){var day=86400000,days=Math.max(1,span/day),pxPerDay=plotW/days,firstDay=Math.ceil(t0/day)*day;var hours=pxPerDay>=360?[6,13,16]:pxPerDay>=230?[6,16]:pxPerDay>=145?[13]:[];var dayY=h-pad.bottom+34*q,timeY=h-pad.bottom  … [line shortened here: 1,538 characters; full line on GitHub]

    text = replace_function(text, "drawShortWindowTicks", new_ticks)

    # Make sure the weekly label area has enough bottom room once the adaptive time row is active.
    if "pad.bottom=Math.max(pad.bottom,104*q)" not in text:
        text = text.replace("pad.bottom=Math.max(pad.bottom,82*q)", "pad.bottom=Math.max(pad.bottom,104*q)")

    must_contain(text, "pxPerDay>=360?[6,13,16]", "renderer adaptive dense rule")
    must_contain(text, "pxPerDay>=230?[6,16]", "renderer adaptive medium rule")
    must_contain(text, "pxPerDay>=145?[13]", "renderer adaptive tight rule")
    must_contain(text, "if(x-lastTimeX<minGap)return", "renderer overlap guard")
    must_contain(text, "pad.bottom=Math.max(pad.bottom,104*q)", "renderer expanded weekly padding")
    write(path, text)


def write_report():
    report = f"""# V6 Repair Report: Adaptive Weekly Time Ticks

Generated UTC: {datetime.now(timezone.utc).isoformat()}

## Reason

The weekly chart was drawing too many time labels per day. On narrower chart widths the labels overlapped and looked like one merged timestamp string.

## Change

The weekly time row now adapts to available pixels per day:

1. Wide chart: 06:00, 13:00 and 16:00.
2. Medium chart: 06:00 and 16:00.
3. Tight chart: 13:00 only.
4. Very tight chart: day labels only.

The day label itself marks the 00:00 boundary, so the chart still gives a daily time reference without clutter.

## Guardrails

- Raw half hourly data is unchanged.
- Loader files are unchanged.
- CSV paths are unchanged.
- The rule is guarded to windows not greater than 1 week.
- Both the live V6 page and the embedded article chart use this shared renderer.

## Files touched by script

{chr(10).join('- ' + x for x in TOUCHED) if TOUCHED else '- No file content changes were required'}

## Manual checks

1. Open /uk_energy_tracking_v6/ and select 1 week.
2. Confirm the day labels are clear.
3. Confirm the time labels no longer collide.
4. Open /data/grid_studies_public/great_britain_electricity_price_grid_constraint_trends_2016_2026.html and select Latest 1 week.
5. Confirm the same behaviour.
"""
    FILES["report"].write_text(report, encoding="utf-8")
    if str(FILES["report"].relative_to(ROOT)) not in TOUCHED:
        TOUCHED.append(str(FILES["report"].relative_to(ROOT)))


def main():
    ai = read(FILES["ai_start"])
    protocol = read(FILES["protocol"])
    must_contain(ai, "Do not directly rewrite large HTML, CSS or JavaScript files", "AI_START_HERE")
    must_contain(protocol, "All V6 changes", "V6 protocol")
    patch_renderer()
    write_report()
    print("V6 adaptive weekly time tick repair completed.")
    for item in TOUCHED:
        print("touched:", item)


if __name__ == "__main__":
    main()