GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Repin V9 Gates and 4 more files

A Python command-line tool in the scripts folder that works with working tree hashes (`working_tree_hashes`) and rewrite literals (`rewrite_literals`).

699 lines of Python from globalgrid2050, in 5 files. Topic: Automation and CI. Section 1778 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 Repair V6 Mobile Chart Readability render · globalgrid2050 / scripts/repair_v6_mobile_chart_readability.py lines 1–129
  2. GlobalGrid2050 Repair V6 Mobile Chart Stabilise render · globalgrid2050 / scripts/repair_v6_mobile_chart_stabilise.py lines 1–106
  3. GlobalGrid2050 Repair V6 Mobile Inspect Buttons render · globalgrid2050 / scripts/repair_v6_mobile_inspect_buttons.py lines 1–138
  4. GlobalGrid2050 Repair V6 Weekly Axis Padding storage · globalgrid2050 / scripts/repair_v6_weekly_axis_padding.py lines 1–109
  5. GlobalGrid2050 Repin V9 Gates ingest · globalgrid2050 / scripts/repin_v9_gates.py lines 1–217

GlobalGrid2050 Repair V6 Mobile Chart Readability

A Python module in the scripts folder that replaces function (`replace_function`).

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

What it does
It draws its content. Defines replace_function. Uses libraries pathlib. Side effects: changes the web page (DOM); reads or writes files.
Inputs & outputs
Out: canvas drawing.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Repair V6 Mobile Chart Readability Workflow (globalgrid2050).
What it achieves
Defines `replace_function`.
Why it matters
Run by GlobalGrid2050 Repair V6 Mobile Chart Readability Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
pathlib
Used by
run by GlobalGrid2050 Repair V6 Mobile Chart Readability Workflow (workflow run)
Produces
replace_function
Defines here
replace_function
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_mobile_chart_readability.py:1-129 · blob 4444f65cdfef461af12d5f97fcac44a25db6caf9 · 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

ROOT = Path(__file__).resolve().parents[1]
V6 = ROOT / "uk_energy_tracking_v6"

for rel in [
    "AI_START_HERE.md",
    "uk_energy_tracking_v6/V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md",
    "uk_energy_tracking_v6/V5_V6_COMPARISON_REPORT.md",
    "uk_energy_tracking_v6/index.md",
    "uk_energy_tracking_v6/styles/app.css",
    "uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js",
]:
    p = ROOT / rel
    if not p.exists():
        raise FileNotFoundError(f"Required file missing: {rel}")
    p.read_text(encoding="utf-8")

protocol = (V6 / "V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md").read_text(encoding="utf-8")
if "Full screen, period arrows, mobile portrait, mobile landscape and desktop" not in protocol:
    raise RuntimeError("V6 protocol fullscreen contract not recognised")

index_path = V6 / "index.md"
css_path = V6 / "styles/app.css"
render_path = V6 / "price_history_chart/render_price_chart/render_price_chart.js"
report_path = V6 / "V6_REPAIR_MOBILE_CHART_READABILITY_REPORT.md"

index = index_path.read_text(encoding="utf-8")
css = css_path.read_text(encoding="utf-8")
render = render_path.read_text(encoding="utf-8")

refresh_button = '        <button type="button" id="price-history-refresh">Refresh chart</button>\n'
if refresh_button in index:
    index = index.replace(refresh_button, "", 1)
elif 'id="price-history-refresh"' in index:
    raise RuntimeError("Refresh chart button exists in unexpected form")

css_block = """

/* V6 repair: mobile chart readability and cinematic fullscreen layout. */
#price-history-refresh{display:none!important;}
@media(max-width:850px) and (orientation:portrait){
  #electricity-price-history-panel #price-history-canvas{height:92dvh!important;min-height:720px!important;}
}
@media(orientation:landscape){
  #price-history-fullscreen-canvas{height:100dvh!important;width:100vw!important;}
  .price-history-fullscreen-toolbar{background:rgba(0,0,0,.18);}
}
"""
if "mobile chart readability and cinematic fullscreen layout" not in css:
    css = css.rstrip() + css_block


def replace_function(text, start_marker, end_marker, replacement):
    start = text.find(start_marker)
    if start == -1:
        raise RuntimeError(f"Start marker not found: {start_marker}")
    end = text.find(end_marker, start)
    if end == -1:
        raise RuntimeError(f"End marker not found after {start_marker}: {end_marker}")
    return text[:start] + replacement + text[end:]

new_summary = """  function compactDateText(t){return String(t||'').replace(/January/g,'Jan').replace(/February/g,'Feb').replace(/March/g,'Mar').replace(/April/g,'Apr').replace(/June/g,'Jun').replace(/July/g,'Jul').replace(/August/g,'Aug').replace(/September/g,'Sep').replace(/October/g,'Oct').replace(/November/g,'Nov').replace(/December/g,'Dec')}
  function drawSummary(g,s,q,w,h,pad,isFull,isLandscape){if(isFull&&isLandscape)return;var cssW=w/q,boxH=(isFull?166:118)*q,x=pad.left,bw=w-pad.left-pad.right,y=isFull?h-boxH-86*q:h-128*q;if(!isFull&&cssW<720)y=h-150*q;g.save();g.fillStyle='rgba(5,7,12,.92)';g.strokeStyle='rgba(0,255,255,.55)';g.lineWidth=1.2*q;g.shadowColor='rgba(0,255,255,.24)';g.shadowBlur=10*q;g.beginPath();g.roundRect(x,y,bw,  … [line shortened here: 1,788 characters; full line on GitHub]
"""

new_render_to = """  function renderTo(canvasId,result){var c=document.getElementById(canvasId);if(!c)return;var isFull=canvasId==='price-history-fullscreen-canvas';var q=window.devicePixelRatio||1,r=c.getBoundingClientRect();c.width=Math.max(320,Math.floor((r.width||1200)*q));c.height=Math.max(360,Math.floor((r.height||720)*q));var g=c.getContext('2d'),w=c.width,h=c.height,cssW=w/q,cssH=h/q,isLan  … [line shortened here: 2,752 characters; full line on GitHub]
"""

render = replace_function(render, "  function drawSummary", "  function decimateRows", new_summary)
render = replace_function(render, "  function renderTo", "  function render(result)", new_render_to)

index_path.write_text(index, encoding="utf-8")
css_path.write_text(css, encoding="utf-8")
render_path.write_text(render, encoding="utf-8")

for path, tokens in {
    index_path: ["price-history-fullscreen-btn", "Download CSV"],
    css_path: ["mobile chart readability and cinematic fullscreen layout", "height:92dvh", "#price-history-refresh{display:none"],
    render_path: ["compactDateText", "isLandscape", "drawSummary(g,s,q,w,h,pad,isFull,isLandscape)", "Metric", "Date / Time", "bottom:300*q", "bottom:52*q"],
}.items():
    txt = path.read_text(encoding="utf-8")
    for token in tokens:
        if token not in txt:
            raise RuntimeError(f"Post repair assertion failed: {path} lacks {token}")

if 'id="price-history-refresh"' in index_path.read_text(encoding="utf-8"):
    raise RuntimeError("Refresh chart button still present in index")

report_path.write_text("""# V6 Repair Report: Mobile Chart Readability

Status: prepared by deterministic repair script.

## Scope

This repair improves the mobile electricity price chart layout after the V6 fullscreen restoration.

## Behaviour changed

1. Removes the redundant `Refresh chart` button from the normal page controls.
2. Makes the normal mobile portrait chart use almost the full mobile viewport height.
3. Makes fullscreen portrait mode use a larger compact table style summary box.
4. Uses bolder red metric rows for High, Average and Low to improve readability for weak eyesight.
5. Removes the summary box in fullscreen landscape mode so the graph has maximum cinematic space.
6. Increases fullscreen landscape graph real estate by reducing chart padding.

## Files changed by workflow execution

1. `uk_energy_tracking_v6/index.md`
2. `uk_energy_tracking_v6/styles/app.css`
3. `uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js`
4. `uk_energy_tracking_v6/V6_REPAIR_MOBILE_CHART_READABILITY_REPORT.md`

## Explicit non scope

No data feeds changed.
No V5 file changed.
No forecast wiring changed.

## Required maintainer test

1. Open `/uk_energy_tracking_v6/` on mobile portrait.
2. Confirm the normal chart fills most of the portrait screen.
3. Open fullscreen portrait and confirm the bottom summary table is readable.
4. Rotate to landscape and confirm the graph is cinematic with no summary box.
5. Confirm arrows and swipe still change period.
""", encoding="utf-8")

print("V6 mobile chart readability repair completed locally by script.")

GlobalGrid2050 Repair V6 Mobile Chart Stabilise

A Python module in the scripts folder.

renderglobalgrid2050 / scripts/repair_v6_mobile_chart_stabilise.py · lines 1–106 of 106 · Entry point

What it does
It loads data. Uses libraries pathlib. Side effects: reads or writes files.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Repair V6 Mobile Chart Stabilise Workflow (globalgrid2050).
What it achieves
It writes `uk_energy_tracking_v6/V6_REPAIR_MOBILE_CHART_STABILISE_REPORT.md`.
Why it matters
Run by GlobalGrid2050 Repair V6 Mobile Chart Stabilise Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
pathlib
Used by
run by GlobalGrid2050 Repair V6 Mobile Chart Stabilise 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/repair_v6_mobile_chart_stabilise.py:1-106 · blob da3cfc02a05752f15785821b62871c4d2463af83 · 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

ROOT = Path(__file__).resolve().parents[1]
V6 = ROOT / "uk_energy_tracking_v6"

for rel in [
    "AI_START_HERE.md",
    "uk_energy_tracking_v6/V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md",
    "uk_energy_tracking_v6/index.md",
    "uk_energy_tracking_v6/styles/app.css",
    "uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js",
]:
    p = ROOT / rel
    if not p.exists():
        raise FileNotFoundError(f"Required file missing: {rel}")
    p.read_text(encoding="utf-8")

css_path = V6 / "styles/app.css"
render_path = V6 / "price_history_chart/render_price_chart/render_price_chart.js"
report_path = V6 / "V6_REPAIR_MOBILE_CHART_STABILISE_REPORT.md"

css = css_path.read_text(encoding="utf-8")
render = render_path.read_text(encoding="utf-8")

# Normal page regression repair: remove the late override that forced the normal page chart to 92dvh.
old_css = """@media(max-width:850px) and (orientation:portrait){
  #electricity-price-history-panel #price-history-canvas{height:92dvh!important;min-height:720px!important;}
}
"""
if old_css in css:
    css = css.replace(old_css, "")

css_add = """

/* V6 repair: stabilise mobile chart after readability experiment. */
@media(max-width:850px) and (orientation:portrait){
  #electricity-price-history-panel #price-history-canvas{height:74dvh!important;min-height:580px!important;}
}
@media(orientation:landscape){
  #price-history-fullscreen-canvas{width:100vw!important;height:100dvh!important;}
}
"""
if "stabilise mobile chart after readability experiment" not in css:
    css = css.rstrip() + css_add

start_marker = "  function compactDateText"
end_marker = "  function decimateRows"
start = render.find(start_marker)
end = render.find(end_marker, start)
if start == -1 or end == -1:
    raise RuntimeError("Could not locate summary function block")

new_summary_block = """  function compactDateText(t){return String(t||'').replace(/January/g,'Jan').replace(/February/g,'Feb').replace(/March/g,'Mar').replace(/April/g,'Apr').replace(/June/g,'Jun').replace(/July/g,'Jul').replace(/August/g,'Aug').replace(/September/g,'Sep').replace(/October/g,'Oct').replace(/November/g,'Nov').replace(/December/g,'Dec')}
  function drawSummary(g,s,q,w,h,pad,isFull,isLandscape){if(isFull&&isLandscape)return;var cssW=w/q,boxH=(isFull?148:118)*q,x=pad.left,bw=w-pad.left-pad.right,y=isFull?h-boxH-92*q:h-128*q;g.save();g.fillStyle='rgba(5,7,12,.92)';g.strokeStyle='rgba(0,255,255,.55)';g.lineWidth=1.2*q;g.shadowColor='rgba(0,255,255,.24)';g.shadowBlur=10*q;g.beginPath();g.roundRect(x,y,bw,boxH,10*q);g.fill();g.stroke();  … [line shortened here: 1,839 characters; full line on GitHub]
"""
render = render[:start] + new_summary_block + render[end:]

old_pad = "var pad=isFull?(isLandscape?{left:62*q,right:30*q,top:58*q,bottom:52*q}:{left:58*q,right:18*q,top:104*q,bottom:300*q}):{left:74*q,right:24*q,top:96*q,bottom:284*q};"
new_pad = "var pad=isFull?(isLandscape?{left:50*q,right:22*q,top:74*q,bottom:44*q}:{left:58*q,right:18*q,top:104*q,bottom:270*q}):{left:74*q,right:24*q,top:96*q,bottom:284*q};"
if old_pad not in render:
    raise RuntimeError("Expected current pad expression not found")
render = render.replace(old_pad, new_pad, 1)

css_path.write_text(css, encoding="utf-8")
render_path.write_text(render, encoding="utf-8")

checks = {
    css_path: ["stabilise mobile chart", "height:74dvh", "min-height:580px"],
    render_path: ["if(isFull&&isLandscape)return", "bottom:270*q", "bottom:44*q", "Date", "dateText.slice(0,17)"],
}
for path, tokens in checks.items():
    text = path.read_text(encoding="utf-8")
    for token in tokens:
        if token not in text:
            raise RuntimeError(f"Post repair assertion failed: {path} lacks {token}")

report_path.write_text("""# V6 Repair Report: Mobile Chart Stabilise

Status: prepared by deterministic repair script.

## Problem observed

The previous mobile readability workflow changed the normal mobile chart height too aggressively and the fullscreen portrait table overflowed horizontally. Landscape fullscreen improved but the title/key area remained cramped.

## Behaviour changed

1. Reverts the normal mobile page chart height to the earlier stable mobile size.
2. Keeps fullscreen landscape summary hidden.
3. Reduces landscape chart padding so graph space improves without clipping the title/key area.
4. Makes the portrait fullscreen summary table more compact.
5. Shortens long date strings inside the portrait summary table so they stay inside the box.

## Files changed by workflow execution

1. `uk_energy_tracking_v6/styles/app.css`
2. `uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js`
3. `uk_energy_tracking_v6/V6_REPAIR_MOBILE_CHART_STABILISE_REPORT.md`

## Required maintainer test

1. Normal mobile page should look like the earlier stable view again.
2. Fullscreen portrait summary should stay inside the box.
3. Fullscreen landscape should show graph only, with no summary box.
""", encoding="utf-8")

print("V6 mobile chart stabilise repair completed locally by script.")

GlobalGrid2050 Repair V6 Mobile Inspect Buttons

A Python command-line tool in the scripts folder that patches renderer (`patch_renderer`) and writes report (`write_report`). It replaces once (`replace_once`) and is built from the bump cache helper (`bump_cache`).

renderglobalgrid2050 / scripts/repair_v6_mobile_inspect_buttons.py · lines 1–138 of 138 · Entry point · pattern bump_cache (shared by 4 files)

What it does
It draws its content. Defines 8 functions or classes, including read, write, must_contain, replace_once, patch_renderer. Uses libraries pathlib, datetime, re. Side effects: changes the web page (DOM); reads or writes files.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Repair V6 Mobile Inspect Buttons Workflow (globalgrid2050).
What it achieves
Defines `read`, `write`, `must_contain` and 4 more.
Why it matters
Run by GlobalGrid2050 Repair V6 Mobile Inspect Buttons Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, datetime, re
Used by
run by GlobalGrid2050 Repair V6 Mobile Inspect Buttons Workflow (workflow run)
Produces
read, write, must_contain, replace_once, patch_renderer, bump_cache, write_report, main
Defines here
read, write, must_contain, replace_once, patch_renderer, bump_cache, 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_mobile_inspect_buttons.py:1-138 · blob dfdd9f59fdb9d0807f1bd94df5900d57b196b07f · 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",
    "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",
    "index": ROOT / "uk_energy_tracking_v6" / "index.md",
    "article": ROOT / "data" / "grid_studies_public" / "great_britain_electricity_price_grid_constraint_trends_2016_2026.html",
    "report": ROOT / "uk_energy_tracking_v6" / "V6_REPAIR_MOBILE_INSPECT_BUTTONS_REPORT.md",
}

TOUCHED = []
NEW_VERSION = "20260604inspect2"


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_once(text, old, new, label):
    count = text.count(old)
    if count != 1:
        raise SystemExit(f"Expected exactly 1 match in {label}, found {count}: {old[:180]}")
    return text.replace(old, new, 1)


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

    must_contain(text, "function ensureInspectControls", "renderer inspect controls")
    must_contain(text, "previous point", "renderer previous button")
    must_contain(text, "next point", "renderer next button")

    helper_marker = "function ensureInspectControls(canvasId,result){"
    style_helper = "function ensureInspectControlStyles(){if(document.getElementById('v6-inspect-control-style'))return;var s=document.createElement('style');s.id='v6-inspect-control-style';s.textContent='.v6-inspect-controls{display:none;align-items:center;gap:10px;flex-wrap:wrap;margin:10px 0 0 0;font-family:Courier New,Courier,monospace}.v6-inspect-button{border:1px solid #00ffff;border-radius:  … [line shortened here: 1,135 characters; full line on GitHub]
    if "function ensureInspectControlStyles" not in text:
        text = replace_once(text, helper_marker, style_helper, "insert inspect control style helper")

    old_bar_style = "var wrap=c.parentElement;var bar=document.createElement('div');bar.id=canvasId+'-inspect-controls';bar.style.cssText='display:none;align-items:center;gap:10px;flex-wrap:wrap;margin:10px 0 0 0;font-family:Courier New,Courier,monospace';"
    new_bar_style = "ensureInspectControlStyles();var wrap=c.parentElement;var bar=document.createElement('div');bar.id=canvasId+'-inspect-controls';bar.className='v6-inspect-controls';"
    if old_bar_style in text:
        text = replace_once(text, old_bar_style, new_bar_style, "inspect bar class")

    old_out_style = "out.style.cssText='flex:1;min-width:260px;color:#00ff88;border:1px solid rgba(0,255,255,.25);border-radius:10px;padding:9px 11px;background:#080b10;line-height:1.35';"
    new_out_style = "out.className='v6-inspect-readout';"
    if old_out_style in text:
        text = replace_once(text, old_out_style, new_out_style, "inspect readout class")

    old_button_style = "[prev,next].forEach(function(b){b.style.cssText='border:1px solid #00ffff;border-radius:10px;padding:9px 12px;color:#00ffff;background:#051014;font-family:Courier New,Courier,monospace;font-weight:bold;cursor:pointer'});"
    new_button_style = "prev.className='v6-inspect-button v6-inspect-prev';next.className='v6-inspect-button v6-inspect-next';"
    if old_button_style in text:
        text = replace_once(text, old_button_style, new_button_style, "inspect button classes")

    # Keep DOM order as previous, readout, next. CSS order controls mobile portrait layout.
    must_contain(text, "function ensureInspectControlStyles", "renderer style helper")
    must_contain(text, "v6-inspect-controls[style]", "renderer mobile portrait grid rule")
    must_contain(text, "v6-inspect-prev", "renderer previous class")
    must_contain(text, "v6-inspect-next", "renderer next class")
    must_contain(text, "v6-inspect-readout", "renderer readout class")

    write(path, text)


def bump_cache(path):
    text = read(path)
    must_contain(text, "render_price_chart.js?v=", str(path))
    import re
    text2 = re.sub(r"render_price_chart\.js\?v=[A-Za-z0-9_.-]+", f"render_price_chart.js?v={NEW_VERSION}", text)
    must_contain(text2, f"render_price_chart.js?v={NEW_VERSION}", str(path))
    write(path, text2)


def write_report():
    report = f"""# V6 Repair Report: Mobile Inspect Buttons

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

## Scope

This repair changes only the inspection control layout and cache version references.

## Behaviour

1. Desktop and wider layouts keep the previous point button, readout and next point button in a normal row.
2. Mobile portrait places the previous point and next point buttons beside each other.
3. The selected point readout moves below the 2 buttons in mobile portrait.
4. The shared renderer is cache busted to `{NEW_VERSION}` on both public pages.

## Files touched by script

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

## Guardrails

- No data files changed.
- No loader files changed.
- No source data paths changed.
- No chart calculations changed.
"""
    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()
    bump_cache(FILES["index"])
    bump_cache(FILES["article"])
    write_report()
    print("V6 mobile inspect button layout repair completed.")
    for item in TOUCHED:
        print("touched:", item)


if __name__ == "__main__":
    main()

GlobalGrid2050 Repair V6 Weekly Axis Padding

A Python command-line tool in the scripts folder that patches renderer (`patch_renderer`) and writes report (`write_report`). It replaces once (`replace_once`).

storageglobalgrid2050 / scripts/repair_v6_weekly_axis_padding.py · lines 1–109 of 109 · Entry point · pattern patch_renderer (shared by 8 files)

What it does
It loads data. Defines 7 functions or classes, including read, write, must_contain, replace_once, patch_renderer. Uses libraries pathlib, datetime. Side effects: reads or writes files.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Repair V6 Weekly Axis Padding Workflow (globalgrid2050).
What it achieves
Defines `read`, `write`, `must_contain` and 3 more.
Why it matters
Run by GlobalGrid2050 Repair V6 Weekly Axis Padding Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, datetime
Used by
run by GlobalGrid2050 Repair V6 Weekly Axis Padding Workflow (workflow run)
Produces
read, write, must_contain, replace_once, patch_renderer, write_report, main
Defines here
read, write, must_contain, replace_once, 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_weekly_axis_padding.py:1-109 · blob 438c1acfbf54f15fc10f83425cf5529a38059033 · 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_WEEKLY_AXIS_PADDING_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_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 patch_renderer():
    path = FILES["renderer"]
    text = read(path)

    must_contain(text, "function drawShortWindowTicks", "renderer short window tick helper")
    must_contain(text, "[0,6,13,16].forEach", "renderer weekly time markers")
    must_contain(text, "span>7.1*86400000", "renderer one week guard")

    old = "var mm=minMax(vals),t0=result.start.getTime(),t1=result.end.getTime();drawAxes(g,w,h,q,mm,pad,t0,t1);"
    new = "var mm=minMax(vals),t0=result.start.getTime(),t1=result.end.getTime();var visibleSpan=t1-t0;if(result.mode!=='daily'&&visibleSpan>2.1*86400000&&visibleSpan<=7.1*86400000){pad.bottom=Math.max(pad.bottom,82*q)}drawAxes(g,w,h,q,mm,pad,t0,t1);"

    if "visibleSpan=t1-t0" not in text:
        text = replace_once(text, old, new, "renderer weekly bottom padding")

    must_contain(text, "pad.bottom=Math.max(pad.bottom,82*q)", "renderer weekly padding rule")
    write(path, text)


def write_report():
    report = f"""# V6 Repair Report: Weekly Axis Padding

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

## Scope

This repair only changes chart canvas bottom padding for raw half hourly weekly windows.

## Reason

Weekly day labels and 00:00, 06:00, 13:00 and 16:00 time guide labels were being drawn below the available canvas plot area. They were visible but cut off at the bottom edge.

## Behaviour

1. If the visible window is greater than 2.1 days and not greater than 7.1 days, the renderer increases bottom padding to at least 82 device scaled pixels.
2. 24 hour and 48 hour views are not changed by this rule.
3. Daily aggregate and longer range behaviour is not changed.
4. No data files, loaders, CSV files or source paths are changed.

## 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 day labels and time guide labels are visible and not cut off.
3. Open /data/grid_studies_public/great_britain_electricity_price_grid_constraint_trends_2016_2026.html and select Latest 1 week.
4. Confirm the same behaviour.
5. Confirm 24 hours, 48 hours, 1 month, 6 months and 10 years still behave as before.
"""
    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 weekly axis padding repair completed.")
    for item in TOUCHED:
        print("touched:", item)


if __name__ == "__main__":
    main()

GlobalGrid2050 Repin V9 Gates

A Python command-line tool in the scripts folder that works with working tree hashes (`working_tree_hashes`) and rewrite literals (`rewrite_literals`).

ingestglobalgrid2050 / scripts/repin_v9_gates.py · lines 1–217 of 217 · Entry point · pattern rewrite (shared by 2 files)

What it does
It loads data. Defines 8 functions or classes, including git, working_tree_hashes, tree_hashes_at, rewrite_literals, rewrite. Uses libraries __future__, json, os, re, subprocess. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage field_execution (path word 'gates'): 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: command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the git step (`git`), the tree hashes at helper (`tree_hashes_at`) and the rewrite step (`rewrite`). Recompute every pinned V9 subtree hash from the working tree.
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__, json, os, re, subprocess, sys, tempfile, pathlib
Used by
none found
Produces
git, working_tree_hashes, tree_hashes_at, rewrite_literals, rewrite, rewrite_contract, main
Defines here
git, working_tree_hashes, tree_hashes_at, rewrite_literals, rewrite, sub, rewrite_contract, 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/repin_v9_gates.py:1-217 · blob b180cf6c529b3fe6f868a5ba0a9689799ffe3166 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
#!/usr/bin/env python3
"""Recompute every pinned V9 subtree hash from the working tree.

WHY THIS EXISTS
The V9 gates prove byte-exactness by pinning a parent's git subtree hash:

    test "$(git -C "$ROOT" rev-parse 'HEAD:uk_renewables_pipeline/v9.5')" = "763c5b40..."
    assert.equal(gitTree("HEAD:uk_renewables_pipeline/v9.6.1"), "243d1217...")
    "frozen_parent": { "path": "uk_renewables_pipeline/v9.6.2", "subtree": "d978c215..." }

That is a good gate and it is not being weakened here. Its cost is that the
pinned hash covers the version's tests as well as its runtime, so repairing a
test - even a test that has been red for a week - changes the hash the NEXT
version pins, which changes that version's hash, and so on up the chain. The
hashes live in three shapes across shell, JavaScript and JSON, so the edit was
being done by hand and getting done wrong.

There is a fourth shape, found the first time this ran: a bare literal that a
test compares against a contract field, or a manifest field under another name
(`assert.equal(contract.frozen_parent.subtree, "d9a50884...")`,
`"frozen_v9_3_1_subtree": "d9a50884..."`). Those carry no path, so they are
rewritten by value: every 40-hex literal in scope that equals what a v9 subtree
hashed to at --base (default HEAD), or at any earlier pass of this run, becomes
that subtree's current hash. Blob and commit hashes never collide with a tree
hash, so nothing else is touched.

This rewrites all four shapes from git, iterating until nothing moves, so a
repair to any V9 test is a two-step operation instead of a hash rodeo:

    git add -A && git commit -m '...'
    python3 scripts/repin_v9_gates.py --base HEAD~1 && git commit -am 'chore: repin the V9 gate chain'

(--base is the last commit whose pins were all consistent; HEAD when the repair
is still uncommitted in the working tree.)

SCOPE - deliberately narrow
Only uk_renewables_pipeline/v9* is rewritten. The timestamped releases
(uk_renewables_pipeline/<12-digit stamp>/) carry their own frozen copies of
these runners; they are published artefacts whose git tree hash is the barcode
printed in catalogue/homepage-catalogue.json, and rewriting them would silently
rebarcode a published version. If one of those ever needs repinning it is a
republication, not a chore.

NOT TOUCHED: frozen_parent.tree_listing_sha256. Nothing in this repository
derives it and nothing compares it to anything computed - check_v9_4.mjs asserts
the contract's literal equals another literal in the test. It is a decorative
hash. Leave it alone until someone documents what it hashes, or delete it.
"""
from __future__ import annotations

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

ROOT = Path(__file__).resolve().parent.parent
SCOPE = re.compile(r"^uk_renewables_pipeline/v9[^/]*/")
MAX_PASSES = 12

SHELL_PIN = re.compile(
    r"""(rev-parse\s+'HEAD:(uk_renewables_pipeline/v9[^']*)'\)"\s*=\s*")([0-9a-f]{40})(")"""
)
JS_PIN = re.compile(
    r"""(gitTree\("HEAD:(uk_renewables_pipeline/v9[^"]*)"\),\s*\n\s*")([0-9a-f]{40})(")"""
)


def git(*args: str, index: str | None = None) -> str:
    env = dict(os.environ)
    if index:
        env["GIT_INDEX_FILE"] = index
    out = subprocess.run(["git", "-C", str(ROOT), *args], capture_output=True, text=True, env=env)
    if out.returncode:
        raise SystemExit(f"git {' '.join(args)} failed: {out.stderr.strip()}")
    return out.stdout.strip()


def working_tree_hashes() -> dict[str, str]:
    """Subtree hash of every uk_renewables_pipeline/v9* directory AS IT IS NOW.

    Read from a throwaway index so the caller's staged state is untouched: the
    point is to pin what is about to be committed, not what was committed last."""
    with tempfile.TemporaryDirectory() as tmp:
        index = str(Path(tmp) / "repin.index")
        git("read-tree", "HEAD", index=index)
        git("add", "-A", "--", "uk_renewables_pipeline", index=index)
        tree = git("write-tree", index=index)
        found = {}
        for line in git("ls-tree", tree, "uk_renewables_pipeline/").splitlines():
            meta, name = line.split("\t", 1)
            mode, kind, sha = meta.split()
            if kind == "tree" and name.rsplit("/", 1)[-1].startswith("v9"):
                found[name.rstrip("/")] = sha
        return found


def tree_hashes_at(rev: str) -> dict[str, str]:
    """Subtree hash of every uk_renewables_pipeline/v9* directory at a committed revision."""
    found = {}
    for line in git("ls-tree", rev, "uk_renewables_pipeline/").splitlines():
        meta, name = line.split("\t", 1)
        mode, kind, sha = meta.split()
        if kind == "tree" and name.rsplit("/", 1)[-1].startswith("v9"):
            found[name.rstrip("/")] = sha
    return found


def rewrite_literals(text: str, literal_map: dict[str, str]) -> tuple[str, int]:
    changes = 0
    for old, new in literal_map.items():
        n = text.count(old)
        if n:
            text = text.replace(old, new)
            changes += n
    return text, changes


def rewrite(text: str, hashes: dict[str, str]) -> tuple[str, int]:
    changes = 0

    def sub(match: re.Match) -> str:
        nonlocal changes
        head, path, old, tail = match.group(1), match.group(2), match.group(3), match.group(4)
        new = hashes.get(path.rstrip("/"))
        if new is None or new == old:
            return match.group(0)
        changes += 1
        return f"{head}{new}{tail}"

    text = SHELL_PIN.sub(sub, text)
    text = JS_PIN.sub(sub, text)
    return text, changes


def rewrite_contract(path: Path, hashes: dict[str, str]) -> int:
    # Rewrite each moved "subtree" value in place, as text, so the contract keeps
    # its own formatting: a re-dump would restyle every list in the file.
    raw = path.read_text(encoding="utf-8")
    try:
        doc = json.loads(raw)
    except json.JSONDecodeError:
        return 0
    changes = 0
    for key, block in doc.items():
        if not isinstance(block, dict):
            continue
        target, subtree = block.get("path"), block.get("subtree")
        if not isinstance(target, str) or not isinstance(subtree, str):
            continue
        new = hashes.get(target.rstrip("/"))
        if new and new != subtree:
            pattern = re.compile(r'("subtree"\s*:\s*")' + re.escape(subtree) + '"')
            raw, n = pattern.subn(lambda m: m.group(1) + new + '"', raw, count=1)
            changes += n
    if changes:
        with path.open("w", encoding="utf-8", newline="") as fh:
            fh.write(raw)
    return changes


def main() -> int:
    argv = sys.argv[1:]
    base = argv[argv.index("--base") + 1] if "--base" in argv else "HEAD"
    files = [
        ROOT / p for p in git("ls-files", "uk_renewables_pipeline").splitlines()
        if SCOPE.match(p) and p.endswith((".sh", ".mjs", ".js", ".json"))
    ]
    former: dict[str, set[str]] = {p: {h} for p, h in tree_hashes_at(base).items()}
    total = 0
    for attempt in range(1, MAX_PASSES + 1):
        hashes = working_tree_hashes()
        literal_map = {
            old: hashes[path]
            for path, olds in former.items() if path in hashes
            for old in olds if old != hashes[path]
        }
        moved = 0
        for path in files:
            if not path.is_file():
                continue
            with path.open(encoding="utf-8", newline="") as fh:
                before = fh.read()
            after, n = rewrite(before, hashes)
            if path.suffix != ".json":
                after, m = rewrite_literals(after, literal_map)
                n += m
            if after != before:
                with path.open("w", encoding="utf-8", newline="") as fh:
                    fh.write(after)
                moved += n
            if path.suffix == ".json":
                moved += rewrite_contract(path, hashes)
                with path.open(encoding="utf-8", newline="") as fh:
                    before = fh.read()
                after, m = rewrite_literals(before, literal_map)
                if m:
                    with path.open("w", encoding="utf-8", newline="") as fh:
                        fh.write(after)
                    moved += m
        for path, sha in hashes.items():
            former.setdefault(path, set()).add(sha)
        print(f"pass {attempt}: {moved} pin(s) rewritten")
        total += moved
        if not moved:
            break
    else:
        print(f"still moving after {MAX_PASSES} passes - the pin graph has a cycle", file=sys.stderr)
        return 1
    print(f"{total} pin(s) rewritten in total; nothing else was touched")
    return 0


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