GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Repair V6 Chart Context Labels and 3 more files

A Python command-line tool in the scripts folder that patches article (`patch_article`) and renderer (`patch_renderer`) and writes report (`write_report`).

562 lines of Python from globalgrid2050, in 4 files. Topic: Automation and CI. Section 1775 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 Chart Boxes No Summary render · globalgrid2050 / scripts/repair_v6_chart_boxes_no_summary.py lines 1–135
  2. GlobalGrid2050 Repair V6 Chart Context Labels render · globalgrid2050 / scripts/repair_v6_chart_context_labels.py lines 1–170
  3. GlobalGrid2050 Repair V6 Chart Inspect Arrows render · globalgrid2050 / scripts/repair_v6_chart_inspect_arrows.py lines 1–145
  4. GlobalGrid2050 Repair V6 Connect Inspect Overlay render · globalgrid2050 / scripts/repair_v6_connect_inspect_overlay.py lines 1–112

GlobalGrid2050 Repair V6 Chart Boxes No Summary

A Python module in the scripts folder.

renderglobalgrid2050 / scripts/repair_v6_chart_boxes_no_summary.py · lines 1–135 of 135 · 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 Chart Boxes No Summary Workflow (globalgrid2050).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by GlobalGrid2050 Repair V6 Chart Boxes No Summary Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
pathlib
Used by
run by GlobalGrid2050 Repair V6 Chart Boxes No Summary 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_chart_boxes_no_summary.py:1-135 · blob 5163c28605a6be3c6a7059c83bd9d0ae00f1e005 · 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"
RENDER = V6 / "price_history_chart/render_price_chart/render_price_chart.js"
INDEX = V6 / "index.md"
CSS = V6 / "styles/app.css"
REPORT = V6 / "V6_REPAIR_CHART_BOXES_NO_SUMMARY_REPORT.md"

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

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

old_pointer = "  function drawTrackerPointer(g,point,q,x,y){g.save();g.strokeStyle='#ff3333';g.shadowColor='rgba(0,255,255,.55)';g.shadowBlur=7*q;g.lineWidth=1.4*q;g.beginPath();g.moveTo(point.x,point.y);g.lineTo(x,y-22*q);g.stroke();g.restore()}\n"
new_pointer = "  function drawTrackerPointer(g,point,q,x,y){return}\n"
if old_pointer not in text:
    raise RuntimeError("Expected pointer function not found")
text = text.replace(old_pointer, new_pointer, 1)

old_box = "  function drawTrackerBox(g,lines,q,x,y,align){var pad=7*q,lh=15*q,wid=0;g.save();g.font='900 '+(align==='center'?10:9.5)*q+'px Courier New';lines.forEach(function(t){wid=Math.max(wid,g.measureText(t).width)});var bh=lines.length*lh+pad*2,bw=wid+pad*2,xx=align==='right'?x-bw:(align==='center'?x-bw/2:x);if(xx<8*q)xx=8*q;if(xx+bw>g.canvas.width-8*q)xx=g.canvas.width-bw-8*q;var yy=y-bh+4*q  … [line shortened here: 847 characters; full line on GitHub]
new_box = "  function drawTrackerBox(g,lines,q,x,y,align){var pad=7*q,lh=14*q,wid=0;g.save();g.font='900 '+9*q+'px Courier New';lines.forEach(function(t){wid=Math.max(wid,g.measureText(t).width)});var bh=lines.length*lh+pad*2,bw=wid+pad*2;var xx=x-bw/2,yy=y-bh/2;if(xx<8*q)xx=8*q;if(xx+bw>g.canvas.width-8*q)xx=g.canvas.width-bw-8*q;if(yy<8*q)yy=8*q;if(yy+bh>g.canvas.height-8*q)yy=g.canvas.height-bh  … [line shortened here: 779 characters; full line on GitHub]
if old_box not in text:
    raise RuntimeError("Expected tracker box function not found")
text = text.replace(old_box, new_box, 1)

old_trackers = "  function drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape){if(isFull&&isLandscape)return;var avgX=(pad.left+w-pad.right)/2,avgY=Y(s.avg),top=pad.top,bottom=h-pad.bottom;var highX=X(s.hi),highY=Y(s.hiValue),lowX=X(s.lo),lowY=Y(s.loValue);var items=[{label:'HIGH',val:s.hiValue,date:s.hiDate,clock:s.hiClock,x:highX,y:highY,tx:Math.min(w-pad.right-150*q,highX+22*q),ty:  … [line shortened here: 968 characters; full line on GitHub]
new_trackers = "  function drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape){var avgX=(pad.left+w-pad.right)/2,avgY=Y(s.avg),top=pad.top,bottom=h-pad.bottom;var highX=X(s.hi),highY=Y(s.hiValue),lowX=X(s.lo),lowY=Y(s.loValue);var items=[{label:'HIGH',val:s.hiValue,date:s.hiDate,clock:s.hiClock,x:highX,y:Math.max(top+42*q,Math.min(bottom-42*q,highY))},{label:'AVERAGE',val:s.avg,date:'  … [line shortened here: 713 characters; full line on GitHub]
if old_trackers not in text:
    raise RuntimeError("Expected visible tracker function not found")
text = text.replace(old_trackers, new_trackers, 1)

old_render = "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:285*q}):{left:74*q,right:24*q,top:96*q,bottom:284*q};"
new_render = "var pad=isFull?(isLandscape?{left:50*q,right:22*q,top:78*q,bottom:48*q}:{left:58*q,right:18*q,top:132*q,bottom:86*q}):{left:74*q,right:24*q,top:96*q,bottom:96*q};"
if old_render not in text:
    raise RuntimeError("Expected pad definition not found")
text = text.replace(old_render, new_render, 1)

old_call = "if(isFull){drawSummary(g,s,q,w,h,pad,isFull,isLandscape);drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape)}else{drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape)}"
new_call = "drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape)"
if old_call not in text:
    raise RuntimeError("Expected summary plus tracker call not found")
text = text.replace(old_call, new_call, 1)

RENDER.write_text(text, encoding="utf-8")
updated = RENDER.read_text(encoding="utf-8")
for forbidden in ["drawSummary(g,s,q,w,h,pad,isFull,isLandscape);drawHighAverageLowTrackers", "lineTo(x,y-22*q)"]:
    if forbidden in updated:
        raise RuntimeError(f"Forbidden old behaviour remains: {forbidden}")
for token in ["function drawTrackerPointer(g,point,q,x,y){return}", "bottom:96*q", "top:132*q", "drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape)"]:
    if token not in updated:
        raise RuntimeError(f"Post repair assertion failed: {token}")

idx = INDEX.read_text(encoding="utf-8")
old_src = "/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js?v=20260602boxes2"
new_src = "/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js?v=20260602boxes3"
if old_src in idx:
    idx = idx.replace(old_src, new_src, 1)
elif new_src not in idx:
    raise RuntimeError("Expected render script cache version not found")
INDEX.write_text(idx, encoding="utf-8")

css = CSS.read_text(encoding="utf-8")
css_old = """.price-history-fullscreen-toolbar{position:sticky;z-index:6;top:0;height:42px;display:flex;align-items:center;gap:8px;padding:0 max(8px,env(safe-area-inset-right)) 0 max(8px,env(safe-area-inset-left));background:rgba(0,0,0,.58);backdrop-filter:blur(4px);color:#f5f7fb;font-family:\"Courier New\",monospace;}
.price-history-fullscreen-toolbar strong{color:#00ffff;text-transform:uppercase;letter-spacing:.08em;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.price-history-fullscreen-toolbar span{display:none!important;}
.price-history-fullscreen-toolbar button{margin-left:auto;border:1px solid rgba(0,255,255,.22);border-radius:50%;width:34px;height:34px;color:#00ffff;background:rgba(0,255,255,.05);font:24px/1 \"Courier New\",monospace;cursor:pointer;flex:0 0 auto;}
"""
css_new = """.price-history-fullscreen-toolbar{position:fixed;z-index:6;top:0;left:0;right:0;min-height:94px;display:grid;grid-template-columns:1fr auto;grid-template-rows:auto auto;gap:8px 12px;align-items:center;padding:calc(10px + env(safe-area-inset-top)) max(12px,env(safe-area-inset-right)) 10px max(12px,env(safe-area-inset-left));background:linear-gradient(180deg,rgba(0,0,0,.88),rgba(0,0,0,.  … [line shortened here: 506 characters; full line on GitHub]
.price-history-fullscreen-toolbar strong{grid-column:1/2;color:#00ffff;text-transform:uppercase;letter-spacing:.08em;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.price-history-fullscreen-period-label{grid-column:1/3;display:flex;align-items:center;gap:10px;color:#9aa3b6;font-size:11px;text-transform:uppercase;letter-spacing:.10em;}
.price-history-fullscreen-period-label select{background:#05070c!important;color:#00ffff!important;border:1px solid rgba(0,255,255,.42)!important;border-radius:6px!important;padding:8px 12px!important;font-family:\"Courier New\",monospace!important;box-shadow:0 0 12px rgba(0,255,255,.10)!important;min-width:180px;}
.price-history-fullscreen-toolbar span{display:none!important;}
.price-history-fullscreen-toolbar button{grid-column:2/3;grid-row:1/2;margin-left:auto;border:1px solid rgba(0,255,255,.35);border-radius:50%;width:34px;height:34px;color:#00ffff;background:rgba(0,255,255,.06);font:24px/1 \"Courier New\",monospace;cursor:pointer;flex:0 0 auto;}
"""
if css_old not in css:
    raise RuntimeError("Expected fullscreen toolbar CSS block not found")
css = css.replace(css_old, css_new, 1)
css = css.replace("#price-history-fullscreen-canvas{width:100vw;height:calc(100dvh - 42px);min-height:620px;display:block;background:#05070c;touch-action:pan-y;transform:translateZ(0);will-change:transform;}", "#price-history-fullscreen-canvas{width:100vw;height:100dvh;min-height:620px;display:block;background:#05070c;touch-action:pan-y;transform:translateZ(0);will-change:transform;}" , 1)
css = css.replace("#price-history-fullscreen-canvas{height:calc(100dvh - 36px);min-height:0;}", "#price-history-fullscreen-canvas{height:100dvh;min-height:0;}" , 1)
CSS.write_text(css, encoding="utf-8")
css_updated = CSS.read_text(encoding="utf-8")
for token in ["position:fixed;z-index:6;top:0;left:0;right:0;min-height:94px", "background:#05070c!important;color:#00ffff!important", "height:100dvh"]:
    if token not in css_updated:
        raise RuntimeError(f"CSS assertion failed: {token}")

REPORT.write_text("""# V6 Repair Report: Chart Boxes, No Summary

Status: prepared by deterministic repair script.

## Problem observed

The previous repair made HIGH, AVERAGE and LOW boxes visible, but it kept pointer lines and left the bottom summary box in place. In fullscreen mode the summary box consumed too much vertical space. The period dropdown also used default browser styling and sat too high in the toolbar.

## Behaviour changed

1. Removes tracker pointer lines.
2. Places HIGH, AVERAGE and LOW tracker boxes directly over their chart positions.
3. Removes the bottom summary box in both normal page mode and fullscreen mode.
4. Reduces chart bottom padding so the chart occupies more of the available space.
5. Lets the fullscreen canvas occupy the full viewport height.
6. Lowers and colour matches the fullscreen period dropdown to the site style.
7. Bumps the V6 render script query string so the live page loads the corrected renderer.

## Files changed by workflow execution

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

## Explicit non scope

No V5 file changed.
No data feed changed.
No forecast wiring changed.
No period calculation changed.

## Required maintainer test

Open `/uk_energy_tracking_v6/`. Confirm that normal in-page mode has no bottom summary box and no pointer lines, and that HIGH, AVERAGE and LOW boxes appear over the chart. Then enter fullscreen portrait and confirm the dropdown is site-coloured, the chart uses the full available viewport and the old bottom summary box is gone.
""", encoding="utf-8")

print("V6 chart boxes no summary repair prepared.")

GlobalGrid2050 Repair V6 Chart Context Labels

A Python command-line tool in the scripts folder that patches article (`patch_article`) and renderer (`patch_renderer`) and writes report (`write_report`).

renderglobalgrid2050 / scripts/repair_v6_chart_context_labels.py · lines 1–170 of 170 · Entry point · pattern patch_article (shared by 3 files)

What it does
It loads data. Defines 9 functions or classes, including read, write, must_contain, replace_once, patch_article. Uses libraries pathlib, datetime. Side effects: reads or writes files.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Repair V6 Chart Context Labels Workflow (globalgrid2050).
What it achieves
It replaces once (`replace_once`) and is built from the assert final state helper (`assert_final_state`). Defines `read`, `write`, `must_contain` and 5 more.
Why it matters
Run by GlobalGrid2050 Repair V6 Chart Context Labels Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, datetime
Used by
run by GlobalGrid2050 Repair V6 Chart Context Labels Workflow (workflow run)
Produces
read, write, must_contain, replace_once, patch_article, patch_renderer, assert_final_state, write_report, main
Defines here
read, write, must_contain, replace_once, patch_article, patch_renderer, assert_final_state, 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_chart_context_labels.py:1-170 · blob 635c2b9d3d0718649b102af88efd845160de68d0 · 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",
    "article": ROOT / "data" / "grid_studies_public" / "great_britain_electricity_price_grid_constraint_trends_2016_2026.html",
    "report": ROOT / "uk_energy_tracking_v6" / "V6_REPAIR_CHART_CONTEXT_LABELS_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[:140]}")
    return text.replace(old, new, 1)


def patch_article():
    path = FILES["article"]
    text = read(path)

    old_controls = '''<div class="chart-controls" id="preset-grid">
                    <button type="button" data-start="2016-01-01" data-period="10y">10 year daily view</button>
                    <button type="button" data-start="2019-11-01" data-period="6m">2019 to 2020</button>
                    <button type="button" data-start="2020-11-01" data-period="6m">2020 to 2021</button>
                    <button type="button" data-start="2021-05-01" data-period="6m">2021 shock</button>
                    <button type="button" data-start="2022-06-01" data-period="6m">2022 crisis</button>
                    <button type="button" data-start="2022-12-01" data-period="6m">2023 negative prices</button>
                    <button type="button" data-dynamic="latest" data-period="24h">Latest 24 hours</button>
                    <button type="button" data-dynamic="latest" data-period="48h">Latest 48 hours</button>
                    <button type="button" data-dynamic="latest" data-period="7d" class="active">Latest 1 week</button>
                </div>'''

    new_controls = '''<div class="chart-controls" id="preset-grid">
                    <button type="button" data-start="2016-01-01" data-period="10y">10 year daily view</button>
                    <button type="button" data-start="2019-11-01" data-period="6m">COVID demand shock</button>
                    <button type="button" data-start="2020-11-01" data-period="6m">Post COVID gas squeeze</button>
                    <button type="button" data-start="2021-05-01" data-period="6m">2021 price spike</button>
                    <button type="button" data-start="2022-06-01" data-period="6m">Ukraine energy crisis</button>
                    <button type="button" data-start="2022-12-01" data-period="6m">Negative price regime</button>
                    <button type="button" data-dynamic="latest" data-period="24h">Latest 24 hours</button>
                    <button type="button" data-dynamic="latest" data-period="48h">Latest 48 hours</button>
                    <button type="button" data-dynamic="latest" data-period="7d" class="active">Latest 1 week</button>
                </div>
                <p class="chart-context-note">Longer windows show the market arc: COVID demand shock, post COVID gas tightening, the 2021 scarcity spike, the Ukraine energy crisis and the later negative price regime. Short windows show half hourly behaviour: 24 hours equals 48 settlement periods, 48 hours equals 96 and 1 week equals 336. Future gas and LNG stress, including Middle East shipping an  … [line shortened here: 471 characters; full line on GitHub]

    if "chart-context-note" not in text:
        text = replace_once(text, old_controls, new_controls, "article chart controls")

    old_css = ".chart-controls button.active { background:#06282c; color:#fff; box-shadow:0 0 14px rgba(0,255,255,.25); }"
    new_css = old_css + "\n        .chart-context-note { margin:8px 0 14px 0; color:var(--muted); font-size:calc(var(--reader-font-size) * .88); line-height:1.55; }"
    if ".chart-context-note" not in text.split("</style>", 1)[0]:
        text = replace_once(text, old_css, new_css, "article chart context CSS")

    must_contain(text, "COVID demand shock", "article updated button")
    must_contain(text, "Ukraine energy crisis", "article updated button")
    must_contain(text, "Middle East shipping and Iran related risk", "article energy risk note")
    write(path, text)


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

    old_label = "function shortTickLabel(t,span){var d=new Date(t);if(span<=2.1*86400000)return d.toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit',hour12:false});return d.toLocaleDateString('en-GB',{weekday:'short',day:'numeric',month:'short'})}"
    new_label = "function shortTickLabel(t,span){var d=new Date(t);if(span<=2.1*86400000)return d.toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit',hour12:false});return d.toLocaleDateString('en-GB',{weekday:'short',day:'numeric',month:'short'})}\n  function shortTimeLabel(t){return new Date(t).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit',hour12:false})}"
    if "function shortTimeLabel" not in text:
        text = replace_once(text, old_label, new_label, "renderer short time helper")

    old_ticks = "function drawShortWindowTicks(g,w,h,q,pad,t0,t1,span){if(span>7.1*86400000)return;var interval=span<=1.1*86400000?3*3600000:span<=2.1*86400000?6*3600000:86400000;var first=Math.ceil(t0/interval)*interval;g.save();g.font=10*q+'px Courier New';g.textAlign='center';for(var t=first;t<t1;t+=interval){var x=pad.left+((t-t0)/(t1-t0))*(w-pad.left-pad.right);g.strokeStyle='rgba(255,255,255  … [line shortened here: 567 characters; full line on GitHub]
    new_ticks = "function drawShortWindowTicks(g,w,h,q,pad,t0,t1,span){if(span>7.1*86400000)return;g.save();g.textAlign='center';if(span>2.1*86400000){var day=86400000,firstDay=Math.ceil(t0/day)*day;for(var d=firstDay;d<t1;d+=day){var dx=pad.left+((d-t0)/(t1-t0))*(w-pad.left-pad.right);g.strokeStyle='rgba(255,255,255,.12)';g.beginPath();g.moveTo(dx,pad.top);g.lineTo(dx,h-pad.bottom);g.stroke();g.f  … [line shortened here: 1,293 characters; full line on GitHub]
    if "[0,6,13,16].forEach" not in text:
        text = replace_once(text, old_ticks, new_ticks, "renderer weekly day and time ticks")

    must_contain(text, "span>7.1*86400000", "renderer one week guard")
    must_contain(text, "[0,6,13,16].forEach", "renderer weekly time markers")
    write(path, text)


def assert_final_state():
    article = read(FILES["article"])
    renderer = read(FILES["renderer"])
    for needle in ["COVID demand shock", "Post COVID gas squeeze", "2021 price spike", "Ukraine energy crisis", "Negative price regime", "Latest 24 hours", "Latest 48 hours", "Latest 1 week"]:
        must_contain(article, needle, "article final labels")
    must_contain(article, "24 hours equals 48 settlement periods", "article 24h explanation")
    must_contain(article, "1 week equals 336", "article weekly explanation")
    must_contain(article, "Middle East shipping and Iran related risk", "article energy risk wording")
    must_contain(renderer, "function shortTimeLabel", "renderer time helper")
    must_contain(renderer, "[0,6,13,16].forEach", "renderer weekly time markers")
    must_contain(renderer, "span>7.1*86400000", "renderer one week guard")


def write_report():
    report = f"""# V6 Repair Report: Chart Context Labels

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

## Scope

This repair updates presentation only.

## Changes

1. Main article chart buttons now describe the chosen historical windows more clearly.
2. A short explanatory line below the buttons explains long windows, short half hourly windows and forward gas or LNG stress monitoring.
3. Weekly view now adds light time guide labels at 00:00, 06:00, 13:00 and 16:00 for each day where space permits.

## 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 paths changed.
- Weekly time labels remain guarded to windows not greater than 1 week.

## Manual checks

1. Open the main article and confirm button labels read correctly.
2. Confirm the explanatory sentence appears under the buttons.
3. Select Latest 1 week and check day labels plus small time guide labels.
4. Confirm 24 hour and 48 hour views are not cluttered.
"""
    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_article()
    patch_renderer()
    assert_final_state()
    write_report()
    print("V6 chart context label repair completed.")
    for item in TOUCHED:
        print("touched:", item)


if __name__ == "__main__":
    main()

GlobalGrid2050 Repair V6 Chart Inspect Arrows

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

renderglobalgrid2050 / scripts/repair_v6_chart_inspect_arrows.py · lines 1–145 of 145 · Entry point · pattern patch_renderer (shared by 8 files)

What it does
It draws its content. Defines 7 functions or classes, including read, write, must_contain, replace_once, patch_renderer. Uses libraries pathlib, datetime. 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 Chart Inspect Arrows Workflow (globalgrid2050).
What it achieves
Defines `read`, `write`, `must_contain` and 3 more.
Why it matters
Run by GlobalGrid2050 Repair V6 Chart Inspect Arrows Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, datetime
Used by
run by GlobalGrid2050 Repair V6 Chart Inspect Arrows 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_chart_inspect_arrows.py:1-145 · blob 1f0f221c4e2d8b6d2c26125dc40fc2643c4cfd81 · 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",
    "report": ROOT / "uk_energy_tracking_v6" / "V6_REPAIR_CHART_INSPECT_ARROWS_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)


INSPECT_HELPERS = r'''  var inspectState={};
  function inspectKey(result){return [result.mode,result.start&&result.start.toISOString?result.start.toISOString():String(result.start),result.end&&result.end.toISOString?result.end.toISOString():String(result.end),(result.rows||[]).length].join('|')}
  function inspectAllowed(result){return result&&result.mode!=='daily'&&result.rows&&result.rows.length&&((result.end.getTime()-result.start.getTime())<=186*86400000)}
  function inspectRows(result){return (result.rows||[]).filter(function(r){var v=price(r),t=new Date(time(r)).getTime();return !isNaN(v)&&!isNaN(t)})}
  function highestInspectIndex(rows){var n=0;for(var i=1;i<rows.length;i++){if(price(rows[i])>price(rows[n]))n=i}return n}
  function nearestInspectIndex(rows,target){if(!rows.length)return 0;var best=0,bestD=Infinity;for(var i=0;i<rows.length;i++){var d=Math.abs(new Date(time(rows[i])).getTime()-target);if(d<bestD){bestD=d;best=i}}return best}
  function ensureInspectState(canvasId,result){var key=inspectKey(result),rows=inspectRows(result),st=inspectState[canvasId]||{};if(st.key!==key){st={key:key,index:highestInspectIndex(rows),moved:false};inspectState[canvasId]=st}return st}
  function inspectLineLabel(r,idx,total){return compactDateText(niceDate(time(r)))+' '+niceClock(time(r))+' | £'+fmt(price(r),2)+'/MWh | point '+(idx+1)+' of '+total.toLocaleString('en-GB')}
  function ensureInspectControls(canvasId,result){var c=document.getElementById(canvasId);if(!c||c.dataset.v6InspectControls==='1')return;c.dataset.v6InspectControls='1';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,monosp  … [line shortened here: 1,578 characters; full line on GitHub]
  function updateInspectControls(canvasId,result,row,idx,total){var bar=document.getElementById(canvasId+'-inspect-controls'),out=document.getElementById(canvasId+'-inspect-readout');if(!bar)return;if(!inspectAllowed(result)){bar.style.display='none';return}bar.style.display='flex';if(out&&row)out.textContent=inspectLineLabel(row,idx,total)}
  function attachInspectEvents(canvasId){var c=document.getElementById(canvasId);if(!c||c.dataset.v6InspectEvents==='1')return;c.dataset.v6InspectEvents='1';function move(ev){if(!lastResult||!inspectAllowed(lastResult))return;var st=inspectState[canvasId];if(!st||!st.geom)return;var rect=c.getBoundingClientRect(),q=window.devicePixelRatio||1,x=(ev.clientX-rect.left)*q,geo=st.geom;if(x<geo.pad.left  … [line shortened here: 881 characters; full line on GitHub]
  function drawInspectOverlay(g,result,q,w,h,pad,X,Y,canvasId){if(!inspectAllowed(result)){updateInspectControls(canvasId,result,null,0,0);return}var rows=inspectRows(result),st=ensureInspectState(canvasId,result);st.geom={pad:pad,w:w,h:h,t0:result.start.getTime(),t1:result.end.getTime()};var idx=Math.max(0,Math.min(rows.length-1,st.index)),r=rows[idx],x=X(r),y=Y(price(r));g.save();g.strokeStyle='  … [line shortened here: 1,113 characters; full line on GitHub]
'''


def patch_renderer():
    path = FILES["renderer"]
    text = read(path)
    must_contain(text, "function drawDailyLines", "renderer daily lines")
    must_contain(text, "function renderTo", "renderer render function")
    must_contain(text, "function drawV5StyleEvents", "renderer event boxes")

    if "function inspectAllowed" not in text:
        text = text.replace("  function renderTo(canvasId,result)", INSPECT_HELPERS + "  function renderTo(canvasId,result)", 1)

    old = "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,isLandscape=isF  … [line shortened here: 3,003 characters; full line on GitHub]

    new = "function renderTo(canvasId,result){var c=document.getElementById(canvasId);if(!c)return;ensureInspectControls(canvasId,result);attachInspectEvents(canvasId);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.ge  … [line shortened here: 3,124 characters; full line on GitHub]

    if "drawInspectOverlay(g,result,q,w,h,pad,X,Y,canvasId)" not in text:
        text = replace_once(text, old, new, "renderer renderTo inspect overlay")

    for marker in [
        "function inspectAllowed",
        "function nearestInspectIndex",
        "function ensureInspectControls",
        "function attachInspectEvents",
        "function drawInspectOverlay",
        "drawInspectOverlay(g,result,q,w,h,pad,X,Y,canvasId)",
        "<=186*86400000",
    ]:
        must_contain(text, marker, "renderer inspect repair")

    write(path, text)


def write_report():
    report = f"""# V6 Repair Report: Chart Inspect Arrows

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

## Scope

This repair adds chart inspection behaviour to the shared V6 price chart renderer.

## Behaviour

1. Inspection is available only for raw half hourly chart windows up to 6 months.
2. The initial inspection line appears at the highest visible half hourly price point.
3. The selected data box appears only after the user moves the pointer or uses the previous or next point arrows.
4. Mouse movement, touch movement, previous point and next point all snap to exact loaded half hourly points.
5. Long daily aggregate views remain unchanged.

## Files touched by script

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

## Guardrails

- No CSV files changed.
- No data loader files changed.
- No source paths changed.
- No annual calculations changed.
- Both the live V6 page and the main article chart use the same shared renderer.

## Manual checks

1. Open /uk_energy_tracking_v6/.
2. Select Latest 1 week.
3. Confirm a thin inspection line starts at the high point.
4. Press previous point and next point.
5. Confirm the selected data box appears with exact date, time and £/MWh.
6. Touch or move mouse across the chart and confirm snapping to points.
7. Open /data/grid_studies_public/great_britain_electricity_price_grid_constraint_trends_2016_2026.html and repeat.
8. Confirm 10 year daily view is not 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()
    write_report()
    print("V6 chart inspect arrow repair completed.")
    for item in TOUCHED:
        print("touched:", item)


if __name__ == "__main__":
    main()

GlobalGrid2050 Repair V6 Connect Inspect Overlay

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

renderglobalgrid2050 / scripts/repair_v6_connect_inspect_overlay.py · lines 1–112 of 112 · 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: changes the web page (DOM); reads or writes files.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Repair V6 Connect Inspect Overlay Workflow (globalgrid2050).
What it achieves
Defines `read`, `write`, `must_contain` and 3 more.
Why it matters
Run by GlobalGrid2050 Repair V6 Connect Inspect Overlay Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, datetime
Used by
run by GlobalGrid2050 Repair V6 Connect Inspect Overlay 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_connect_inspect_overlay.py:1-112 · blob 6d177536aaf496b287693efe3ad504495f07ff99 · 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",
    "report": ROOT / "uk_energy_tracking_v6" / "V6_REPAIR_CONNECT_INSPECT_OVERLAY_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)

    for marker in [
        "function ensureInspectControls",
        "function attachInspectEvents",
        "function drawInspectOverlay",
        "function renderTo",
    ]:
        must_contain(text, marker, "renderer inspect helpers")

    old_start = "function renderTo(canvasId,result){var c=document.getElementById(canvasId);if(!c)return;var isFull="
    new_start = "function renderTo(canvasId,result){var c=document.getElementById(canvasId);if(!c)return;ensureInspectControls(canvasId,result);attachInspectEvents(canvasId);var isFull="
    if "ensureInspectControls(canvasId,result);attachInspectEvents(canvasId);var isFull=" not in text:
        text = replace_once(text, old_start, new_start, "renderTo inspect setup call")

    old_draw = "set('ph-source','Seasonal baseline')}if(!isFull&&result.forecastRows&&result.forecastRows.length)drawHealthBar"
    new_draw = "set('ph-source','Seasonal baseline')}drawInspectOverlay(g,result,q,w,h,pad,X,Y,canvasId);if(!isFull&&result.forecastRows&&result.forecastRows.length)drawHealthBar"
    if "drawInspectOverlay(g,result,q,w,h,pad,X,Y,canvasId);if(!isFull" not in text:
        text = replace_once(text, old_draw, new_draw, "renderTo inspect overlay call")

    must_contain(text, "ensureInspectControls(canvasId,result);attachInspectEvents(canvasId);var isFull=", "renderer connected controls")
    must_contain(text, "drawInspectOverlay(g,result,q,w,h,pad,X,Y,canvasId);if(!isFull", "renderer connected overlay")
    write(path, text)


def write_report():
    report = f"""# V6 Repair Report: Connect Inspect Overlay

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

## Reason

The previous inspection workflow inserted the helper functions but did not connect them into the renderTo execution path. The function definition existed, but the renderer did not call it.

## Change

1. renderTo now creates and attaches the previous point and next point inspection controls.
2. renderTo now calls drawInspectOverlay after the high and low marker stage.
3. Inspection remains limited to raw half hourly windows up to 6 months.

## 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 paths changed.
- No annual 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()
    write_report()
    print("V6 inspect overlay connector repair completed.")
    for item in TOUCHED:
        print("touched:", item)


if __name__ == "__main__":
    main()