In this section
- GlobalGrid2050 Patch V3 Price Range Fullscreen Fix energy-data · globalgrid2050 / scripts/patch_v3_price_range_fullscreen_fix.py lines 1–142
- GlobalGrid2050 Patch V5 News Backend Loader render · globalgrid2050 / scripts/patch_v5_news_backend_loader.py lines 1–36
- GlobalGrid2050 Repair V6 Price Annotation Layout energy-data · globalgrid2050 / scripts/repair_v6_price_annotation_layout.py lines 1–230
- GlobalGrid2050 Repair V6 Price Annotations V5 Style energy-data · globalgrid2050 / scripts/repair_v6_price_annotations_v5_style.py lines 1–152
GlobalGrid2050 Patch V3 Price Range Fullscreen Fix
A Python command-line tool in the scripts folder that patches page (`patch_page`) and CSS (`patch_css`) and patches js (`patch_js`), covering electricity price history and Elexon system prices half hourly.
energy-dataglobalgrid2050 / scripts/patch_v3_price_range_fullscreen_fix.py · lines 1–142 of 142 · Entry point · pattern patch_diary (shared by 6 files)
- What it does
- It draws electricity price history and Elexon system prices half hourly. Defines patch_page, patch_css, patch_js, patch_diary, main. Uses libraries pathlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: JSON file electricity_price_history.json; CSV file elexon_system_prices_half_hourly.csv; CSV file electricity_price_history.csv; form fields (user input). Out: canvas drawing.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Patch V3 Price Range Fullscreen Fix Workflow (globalgrid2050).
- What it achieves
- Defines `patch_page`, `patch_css`, `patch_js` and 1 more.
- Why it matters
- Run by GlobalGrid2050 Patch V3 Price Range Fullscreen Fix Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- pathlib
- Used by
- run by GlobalGrid2050 Patch V3 Price Range Fullscreen Fix Workflow (workflow run)
- Produces
- patch_page, patch_css, patch_js, patch_diary, main
- Defines here
- patch_page, patch_css, patch_js, patch_diary, 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/patch_v3_price_range_fullscreen_fix.py:1-142 · blob 795f5821a7ba9f91f1047f107905c1275f48469f · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
from pathlib import Path
PAGE = Path('uk_energy_tracking_v3/index.md')
CSS = Path('uk_energy_tracking_v3/price-history-ui.css')
JS = Path('uk_energy_tracking_v3/price-history-ui.js')
FS = Path('uk_energy_tracking_v3/price-history-fullscreen.js')
DIARY = Path('uk_energy_tracking_v3/WORK_DIARY.md')
DATE_HTML = '''
<label class="price-history-date-label">From <input type="date" id="price-history-from"></label>
<label class="price-history-date-label">To <input type="date" id="price-history-to"></label>
<button type="button" id="price-history-clear-dates" class="price-history-date-apply">Clear dates</button>'''
CSS_ADD = '''
/* V3 price history calendar range controls */
#electricity-price-history-panel .price-history-date-label{display:flex;align-items:center;gap:6px;color:#9aa3b6;text-transform:uppercase;letter-spacing:.08em;font-size:11px}
#electricity-price-history-panel .price-history-date-label input{background:#050505!important;color:#00ffff!important;border:1px solid #252b36!important;border-radius:4px;padding:7px 9px;font-family:"Courier New",monospace}
#electricity-price-history-panel .price-history-date-apply{border:1px solid #252b36!important;border-radius:4px;padding:7px 9px;color:#00ffff!important;background:rgba(0,255,255,.05)!important;font-family:"Courier New",monospace;cursor:pointer}
#electricity-price-history-panel table.price-history-table tr.price-warning td{background:#20160b!important;color:#ffd28a!important}
#electricity-price-history-panel table.price-history-table tr.price-warning td:nth-child(2){color:#ffcc66!important}
'''
FS_JS = r'''(function(){
var JSON_URL='/uk_energy_tracking_v3/electricity_price_history.json';
var CSV_URL='/data/electricity/elexon_system_prices_half_hourly.csv';
var S={rows:[],a:0,b:1,drag:false,x:0};
function E(id){return document.getElementById(id)}
function csvLine(line){var out=[],v='',q=false;for(var i=0;i<line.length;i++){var c=line[i];if(c==='"'){if(q&&line[i+1]==='"'){v+='"';i++}else q=!q}else if(c===','&&!q){out.push(v);v=''}else v+=c}out.push(v);return out}
function fmtDate(t){return new Date(t).toLocaleString('en-GB',{day:'2-digit',month:'short',hour:'2-digit',minute:'2-digit'})}
function parseCsv(text){text=(text||'').trim();if(!text)return[];var lines=text.split(/\r?\n/),heads=csvLine(lines[0]).map(function(h){return h.trim()});return lines.slice(1).map(function(line){var cols=csvLine(line),r={};heads.forEach(function(h,i){r[h]=(cols[i]||'').trim()});var price=r.systemBuyPriceGBPperMWh||r.systemSellPriceGBPperMWh||r.priceGBPperMWh||'';return{t:new Date(r.periodStartUTC … [line shortened here: 574 characters; full line on GitHub]
function parseJson(data){return(data.rows||[]).map(function(r){return{t:new Date(r.priceTimeUTC).getTime(),v:Number(r.priceGBPperMWh),health:r.priceHealth||''}}).filter(function(r){return r.t&&r.v===r.v})}
function cutoff(range){if(range==='all')return null;var end=Date.now(),ms=0;if(range==='24h')ms=86400000;else if(range==='7d')ms=7*86400000;else if(range==='30d')ms=30*86400000;else if(range==='3m')ms=92*86400000;else if(range==='6m')ms=183*86400000;else if(range==='12m')ms=366*86400000;else ms=3650*86400000;return end-ms}
function customWindow(){var f=E('price-history-from'),t=E('price-history-to');if(!f||!t||!f.value||!t.value)return null;var a=new Date(f.value+'T00:00:00Z').getTime(),b=new Date(t.value+'T23:59:59Z').getTime();if(!a||!b||b<a)return null;var max=60*86400000;if(b-a>max)b=a+max;return{a:a,b:b}}
function loadRows(){var rangeEl=E('price-history-range'),range=rangeEl?rangeEl.value:'7d',cw=customWindow(),cut=cutoff(range);return Promise.all([fetch(JSON_URL+'?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.json():{rows:[]}}).then(parseJson).catch(function(){return[]}),fetch(CSV_URL+'?t='+Date.now(),{cache:'no-store'}).then(function(r){return r.ok?r.text():''}).then(parseCs … [line shortened here: 753 characters; full line on GitHub]
function setView(){if(S.rows.length){S.a=S.rows[0].t;S.b=S.rows[S.rows.length-1].t;if(S.b<=S.a)S.b=S.a+1}}
function minMax(rows){var lo=rows[0].v,hi=lo;rows.forEach(function(r){if(r.v<lo)lo=r.v;if(r.v>hi)hi=r.v});if(lo===hi)hi=lo+1;var m=(hi-lo)*.1;return{lo:lo-m,hi:hi+m}}
function draw(){var c=E('price-history-fullscreen-canvas');if(!c)return;var q=devicePixelRatio||1,rc=c.getBoundingClientRect();c.width=Math.max(400,Math.floor(rc.width*q));c.height=Math.max(260,Math.floor(rc.height*q));var g=c.getContext('2d'),w=c.width,h=c.height,p=74*q,rp=28*q;g.fillStyle='#05070c';g.fillRect(0,0,w,h);g.font=12*q+'px Courier New';var rows=S.rows.filter(function(r){return r.t>= … [line shortened here: 1,316 characters; full line on GitHub]
function zoom(f,cr){var sp=S.b-S.a,cen=S.a+sp*(cr==null?.5:cr),ns=Math.max(1800000,sp*f),k=cr==null?.5:cr;S.a=cen-ns*k;S.b=S.a+ns;draw()}
function open(){var o=E('price-history-fullscreen-overlay');if(!o)return;o.classList.add('open');loadRows().then(function(rows){S.rows=rows;setView();draw()})}
function close(){var o=E('price-history-fullscreen-overlay');if(o)o.classList.remove('open')}
document.addEventListener('DOMContentLoaded',function(){var b=E('price-history-fullscreen-btn');if(b)b.onclick=open;var c=E('price-history-fullscreen-close');if(c)c.onclick=close;var z=E('price-history-zoom-reset');if(z)z.onclick=function(){setView();draw()};var zi=E('price-history-zoom-in');if(zi)zi.onclick=function(){zoom(.7)};var zo=E('price-history-zoom-out');if(zo)zo.onclick=function(){zoom … [line shortened here: 1,191 characters; full line on GitHub]
})();'''
def patch_page():
text=PAGE.read_text(encoding='utf-8')
if 'price-history-from' not in text:
text=text.replace('<a href="/uk_energy_tracking_v3/electricity_price_history.csv" download>Download CSV</a>',DATE_HTML+'\n <a href="/uk_energy_tracking_v3/electricity_price_history.csv" download>Download CSV</a>',1)
text=text.replace('Captured Market Index Price','Electricity Price History')
text=text.replace('Independently captured from Elexon BMRS Market Index values.','Historical Elexon System Prices are shown for context. New live Market Index records build forward. Warnings are shown in the table health column.')
PAGE.write_text(text,encoding='utf-8')
def patch_css():
text=CSS.read_text(encoding='utf-8')
if 'price-history-date-label' not in text:
text=text.rstrip()+CSS_ADD
elif 'tr.price-warning' not in text:
text=text.rstrip()+"\n#electricity-price-history-panel table.price-history-table tr.price-warning td{background:#20160b!important;color:#ffd28a!important}\n#electricity-price-history-panel table.price-history-table tr.price-warning td:nth-child(2){color:#ffcc66!important}\n"
CSS.write_text(text,encoding='utf-8')
def patch_js():
text=JS.read_text(encoding='utf-8')
old_cut=""" function cutoff(range){
if(range === "all") return null;
var d = new Date();
if(range === "24h") d.setDate(d.getDate() - 1);
else if(range === "7d") d.setDate(d.getDate() - 7);
else if(range === "30d") d.setDate(d.getDate() - 30);
else if(range === "3m") d.setMonth(d.getMonth() - 3);
else if(range === "6m") d.setMonth(d.getMonth() - 6);
else if(range === "12m") d.setFullYear(d.getFullYear() - 1);
else d.setFullYear(d.getFullYear() - 10);
return d;
}
"""
new_cut=""" function customDateWindow(){
var f = document.getElementById("price-history-from"), t = document.getElementById("price-history-to");
if(!f || !t || !f.value || !t.value) return null;
var start = new Date(f.value + "T00:00:00Z");
var end = new Date(t.value + "T23:59:59Z");
if(isNaN(start) || isNaN(end) || end < start) return null;
var max = 60 * 24 * 60 * 60 * 1000;
if(end - start > max) end = new Date(start.getTime() + max);
return {start:start, end:end, label:f.value + " to " + end.toISOString().slice(0,10)};
}
function cutoff(range){
if(range === "all") return null;
var now = Date.now(), days = 3650;
if(range === "24h") days = 1;
else if(range === "7d") days = 7;
else if(range === "30d") days = 30;
else if(range === "3m") days = 92;
else if(range === "6m") days = 183;
else if(range === "12m") days = 366;
return new Date(now - days * 24 * 60 * 60 * 1000);
}
"""
if old_cut in text:
text=text.replace(old_cut,new_cut,1)
elif 'function customDateWindow' not in text:
text=text.replace(' function cutoff(range){\n',new_cut+'\n function cutoff(range){\n',1)
old_health=""" function carbonHealthCell(r){
if(r.carbonGperKWh !== "" && r.carbonGperKWh != null) return r.carbonGperKWh + " g/kWh";
if(r.carbonIndex) return String(r.carbonIndex);
if(r.priceHealth && r.priceHealth !== "ok") return "price: " + r.priceHealth;
if(r.carbonHealth && r.carbonHealth !== "ok") return "carbon: " + r.carbonHealth;
return "—";
}
"""
new_health=""" function carbonHealthCell(r){
if(r.priceHealth && r.priceHealth !== "ok") return "price: " + r.priceHealth;
if(r.carbonHealth && r.carbonHealth !== "ok") return "carbon: " + r.carbonHealth;
if(r.carbonGperKWh !== "" && r.carbonGperKWh != null) return r.carbonGperKWh + " g/kWh";
if(r.carbonIndex) return String(r.carbonIndex);
return "—";
}
"""
if old_health in text:
text=text.replace(old_health,new_health,1)
text=text.replace(' var cut = cutoff(range);\n var rows = cut ? allRows.filter(function(r){ return new Date(r.priceTimeUTC) >= cut; }) : allRows;',' var custom = customDateWindow();\n var cut = cutoff(range);\n var rows = custom ? allRows.filter(function(r){ var t = new Date(r.priceTimeUTC); return t >= custom.start && t <= custom.end; }) : (cut ? allRows.filter(functi … [line shortened here: 524 characters; full line on GitHub]
text=text.replace(' renderTable(rows, range);\n draw(rows, range);',' renderTable(rows, activeRangeLabel);\n draw(rows, activeRangeLabel);')
text=text.replace("return '<tr><td>' + dateLabel(r.priceTimeUTC)", "return '<tr class=\"' + ((r.priceHealth && r.priceHealth !== 'ok') ? 'price-warning' : '') + '\"><td>' + dateLabel(r.priceTimeUTC)")
if 'price-history-clear-dates' not in text:
text=text.replace(' if(rangeEl) rangeEl.addEventListener("change", load);\n load();',' if(rangeEl) rangeEl.addEventListener("change", load);\n var f=document.getElementById("price-history-from"),to=document.getElementById("price-history-to"),cl=document.getElementById("price-history-clear-dates");\n if(f)f.addEventListener("change",load);\n if(to)to.addEventListener("chan … [line shortened here: 520 characters; full line on GitHub]
JS.write_text(text,encoding='utf-8')
def patch_diary():
text=DIARY.read_text(encoding='utf-8')
marker='## Diary entry: 2026-05-26 V3 range and full screen correction amended before run'
if marker not in text:
text+='\n\n'+marker+'\n\nAmended before execution after code review. The patch now aligns full screen with the inline chart by loading both the historical Elexon system price CSV and the V3 captured JSON. It adds From and To date controls capped to 60 days, changes rolling cutoffs to millisecond based UTC comparisons, surfaces priceHealth warnings before carbon values in the table health c … [line shortened here: 563 characters; full line on GitHub]
DIARY.write_text(text,encoding='utf-8')
def main():
patch_page(); patch_css(); patch_js(); FS.write_text(FS_JS,encoding='utf-8'); patch_diary(); print('amended V3 price range and fullscreen fix ready')
if __name__=='__main__': main()GlobalGrid2050 Patch V5 News Backend Loader
A Python module in the scripts folder that draws major project news, Renewable Energy Planning Database (REPD) master and the REPD register.
renderglobalgrid2050 / scripts/patch_v5_news_backend_loader.py · lines 1–36 of 36 · Entry point
- What it does
- It draws major project news, REPD master and the REPD register. Uses libraries pathlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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: the REPD register.
- Inputs & outputs
- In: JSON file major_project_news_v5.json; JSON file repd_master.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Repair V5 News Loader 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 V5 News Loader Workflow.
- Application
- globalgrid2050 · scripts · Python module
- Uses
- pathlib
- Used by
- run by GlobalGrid2050 Repair V5 News Loader 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/patch_v5_news_backend_loader.py:1-36 · blob c3776fc8ae332938ba47ea6f272d625b366d4dd2 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from pathlib import Path
path = Path('uk_renewables_pipeline/dashboard_v5_live.html')
text = path.read_text(encoding='utf-8')
old = "async function loadNews(){try{const r=await fetch('../dist/major_project_news_v5.json?v='+Date.now());if(!r.ok)throw new Error('news '+r.status);renderNews(await r.json())}catch(e){document.getElementById('stories').innerHTML='<div class=\"news-empty\">Daily newspaper feed unavailable. REPD analytics below remain live.</div>';document.getElementById('newsMeta').textContent='feed unavailable … [line shortened here: 404 characters; full line on GitHub]
new = """function validNewsPayload(p){return p&&Array.isArray(p.items)&&Number.isFinite(Number(p.headline_count??p.items.length))}\nfunction newsPayloadTime(p){const t=Date.parse(String(p&&p.updated||''));return Number.isFinite(t)?t:0}\nasync function fetchNewsPayload(label,url){const r=await fetch(url,{cache:'no-store'});if(!r.ok)throw new Error(label+' '+r.status);const data=await r.json();if(!v … [line shortened here: 1,441 characters; full line on GitHub]
if new in text:
print('V5 loader already patched')
elif old in text:
text = text.replace(old, new, 1)
path.write_text(text, encoding='utf-8')
print('Patched V5 news loader: Pages + raw GitHub main, newest payload wins')
else:
raise SystemExit('Expected V5 loadNews function not found; refusing unsafe edit')
check = path.read_text(encoding='utf-8')
required = [
"major_project_news_v5.json",
"raw.githubusercontent.com/Ventusltd/globalgrid2050/main/dist/major_project_news_v5.json",
"repd_master.json",
"EXPORT CSV",
"NEWS SIGNAL",
"function drawNews()",
"function table(d)",
"</html>"
]
missing = [x for x in required if x not in check]
if missing:
raise SystemExit('Integrity failure after patch: '+', '.join(missing))
if '<iframe' in check.lower():
raise SystemExit('Integrity failure: iframe introduced')
print('V5 loader integrity PASS; bytes', len(check.encode('utf-8')))GlobalGrid2050 Repair V6 Price Annotation Layout
A Python module in the scripts folder.
energy-dataglobalgrid2050 / scripts/repair_v6_price_annotation_layout.py · lines 1–230 of 230 · Entry point
- What it does
- It loads data. Uses libraries pathlib, re. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Repair V6 Price Annotation Layout 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 Price Annotation Layout Workflow.
- Application
- globalgrid2050 · scripts · Python module
- Uses
- pathlib, re
- Used by
- run by GlobalGrid2050 Repair V6 Price Annotation Layout 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_price_annotation_layout.py:1-230 · blob 1b5695d8c4d5ad8289e8cf7f31a4bf89921d1610 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
from pathlib import Path
import re
ROOT = Path(__file__).resolve().parents[1]
V6 = ROOT / "uk_energy_tracking_v6"
V5 = ROOT / "uk_energy_tracking_v5"
RENDER = V6 / "price_history_chart/render_price_chart/render_price_chart.js"
INDEX = V6 / "index.md"
REPORT = V6 / "V6_REPAIR_PRICE_ANNOTATION_LAYOUT_REPORT.md"
REQUIRED = [
ROOT / "AI_START_HERE.md",
V6 / "V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md",
V6 / "V5_V6_COMPARISON_REPORT.md",
V5 / "price-history-ui.js",
RENDER,
INDEX,
]
for path in REQUIRED:
if not path.exists():
raise FileNotFoundError(f"Required file missing: {path.relative_to(ROOT)}")
path.read_text(encoding="utf-8")
v5_before = (V5 / "price-history-ui.js").read_text(encoding="utf-8")
for token in ["function eventBox", "function drawPointer", "function drawEvents", "function drawDailyEvents"]:
if token not in v5_before:
raise RuntimeError(f"V5 reference behaviour missing: {token}")
js = RENDER.read_text(encoding="utf-8")
index = INDEX.read_text(encoding="utf-8")
issues = []
if "function drawTrackerPointer" in js and "lineTo" in js[js.find("function drawTrackerPointer"):js.find("function drawTrackerPointer") + 350]:
issues.append("Visible pointer lines are still drawn by drawTrackerPointer, causing diagonal clutter.")
if "function drawHighAverageLowTrackers" not in js:
raise RuntimeError("V6 tracker function missing; refusing to patch a different renderer shape.")
if "drawSummary(g,s,q,w,h,pad,isFull,isLandscape)" in js:
issues.append("Bottom summary box is still being called, creating a competing annotation layer.")
if "render_price_chart_box_overlay.js" in index:
issues.append("Overlay workaround is loaded in index.md, causing duplicate annotation passes.")
if "render_price_chart_v6_clean_boxes.js" in index:
issues.append("Broken replacement renderer is still referenced in index.md.")
if "(mm.hi-v)/(mm.hi-mm.lo)" not in js:
issues.append("Could not confirm normal y-axis mapping formula statically.")
else:
issues.append("Y-axis formula is statically normal: higher prices map upward, lower prices map downward.")
# Turn the old pointer helper into a safe no-op so any old calls cannot draw stray diagonals.
js = re.sub(
r" function drawTrackerPointer\(g,point,q,x,y\)\{.*?\}\n function drawTrackerBox",
" function drawTrackerPointer(g,point,q,x,y){return}\n function drawTrackerBox",
js,
count=1,
flags=re.S,
)
if "function drawTrackerPointer(g,point,q,x,y){return}" not in js:
raise RuntimeError("Failed to make drawTrackerPointer a no-op")
# Replace only the V6 tracker layout. Keep the rest of the renderer intact.
new_tracker = """ function drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape){
var plotLeft=pad.left,plotRight=w-pad.right,plotTop=pad.top,plotBottom=h-pad.bottom;
var chartWidth=plotRight-plotLeft,chartHeight=plotBottom-plotTop;
var highPoint={x:X(s.hi),y:Y(s.hiValue)};
var lowPoint={x:X(s.lo),y:Y(s.loValue)};
var avgPoint={x:plotLeft+chartWidth*.50,y:Y(s.avg)};
function dot(p){g.save();g.fillStyle='#ff3333';g.shadowColor='rgba(0,255,255,.85)';g.shadowBlur=8*q;g.beginPath();g.arc(p.x,p.y,5*q,0,Math.PI*2);g.fill();g.restore()}
function connector(from,to){g.save();g.strokeStyle='rgba(255,51,51,.78)';g.shadowColor='rgba(0,255,255,.42)';g.shadowBlur=6*q;g.lineWidth=1.15*q;g.beginPath();g.moveTo(from.x,from.y);g.lineTo(to.x,to.y-25*q);g.stroke();g.restore()}
dot(highPoint);dot(lowPoint);
var maxW=chartWidth*.92,highBox,avgBox,lowBox;
if(isFull&&isLandscape){
var boxX=plotRight-chartWidth*.18;
highBox={x:boxX,y:plotTop+chartHeight*.18};
avgBox={x:boxX,y:plotTop+chartHeight*.50};
lowBox={x:boxX,y:plotTop+chartHeight*.82};
maxW=chartWidth*.36
}else{
var blankTop=plotBottom+46*q;
var blankBottom=h-(isFull?18*q:22*q);
if(blankBottom-blankTop<150*q){blankTop=plotBottom+22*q;blankBottom=h-10*q}
var zoneH=Math.max(150*q,blankBottom-blankTop);
var boxX=plotLeft+chartWidth*.50;
highBox={x:boxX,y:blankTop+zoneH*.18};
avgBox={x:boxX,y:blankTop+zoneH*.50};
lowBox={x:boxX,y:blankTop+zoneH*.82}
}
connector(highPoint,highBox);connector(avgPoint,avgBox);connector(lowPoint,lowBox);
drawTrackerBox(g,trackerLines('HIGH',s.hiValue,s.hiDate,s.hiClock),q,highBox.x,highBox.y,'center');
drawTrackerBox(g,trackerLines('AVERAGE',s.avg,'Visible period',''),q,avgBox.x,avgBox.y,'center');
drawTrackerBox(g,trackerLines('LOW',s.loValue,s.loDate,s.loClock),q,lowBox.x,lowBox.y,'center')
}
"""
js, tracker_count = re.subn(
r" function drawHighAverageLowTrackers\(g,s,q,w,h,pad,X,Y,isFull,isLandscape\)\{.*?\n \}\n function drawSummary",
new_tracker + " function drawSummary",
js,
count=1,
flags=re.S,
)
if tracker_count != 1:
raise RuntimeError("Failed to replace exactly one drawHighAverageLowTrackers function")
# Remove all known forms of drawSummary usage from the render path. Keep drawSummary definition untouched for rollback traceability.
known_calls = [
"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)}",
"g.restore();drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape);drawSummary(g,s,q,w,h,pad,isFull,isLandscape);set('ph-latest-price'",
"g.restore();drawSummary(g,s,q,w,h,pad,isFull,isLandscape);drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape);set('ph-latest-price'",
]
for call in known_calls:
if call in js:
if call.startswith("g.restore();"):
js = js.replace(call, "g.restore();drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape);set('ph-latest-price'", 1)
else:
js = js.replace(call, "drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape)", 1)
if "drawSummary(g,s,q,w,h,pad,isFull,isLandscape);" in js:
raise RuntimeError("drawSummary call still remains in renderer path")
if "function drawTrackerPointer(g,point,q,x,y){return}" not in js:
raise RuntimeError("Pointer no-op assertion failed")
for token in ["isFull&&isLandscape", "boxX=plotRight-chartWidth*.18", "blankTop=plotBottom+46*q", "connector(highPoint,highBox)"]:
if token not in js:
raise RuntimeError(f"Annotation layout assertion failed: {token}")
# Clean index.md so only the working renderer is loaded.
index = re.sub(r'\n<script src="/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart_box_overlay\.js\?v=[^"]+"></script>', "", index)
index = re.sub(r'/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart_v6_clean_boxes\.js\?v=[^"]+',
'/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js?v=20260602anno2', index)
index = re.sub(r'/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart\.js\?v=[^"]+',
'/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js?v=20260602anno2', index)
if "render_price_chart_box_overlay.js" in index:
raise RuntimeError("Overlay workaround still referenced in index.md")
if "render_price_chart_v6_clean_boxes.js" in index:
raise RuntimeError("Broken clean renderer still referenced in index.md")
if "render_price_chart.js?v=20260602anno2" not in index:
raise RuntimeError("Cache-busted working renderer not referenced")
RENDER.write_text(js, encoding="utf-8")
INDEX.write_text(index, encoding="utf-8")
# Confirm V5 has not changed.
v5_after = (V5 / "price-history-ui.js").read_text(encoding="utf-8")
if v5_after != v5_before:
raise RuntimeError("V5 changed unexpectedly. Aborting.")
REPORT.write_text(f"""# V6 Repair Report: Price Annotation Layout
Status: generated by deterministic diagnostic and repair script.
## Diagnosis before repair
{chr(10).join('- ' + item for item in issues)}
## Why the earlier attempts failed
1. Pointer lines were still active and crossed the chart.
2. The old bottom summary box was still being drawn.
3. The temporary overlay workaround created duplicate annotation passes.
4. The boxes were being placed inside the plot area rather than being assigned to deliberate zones.
5. Landscape mode had no specific design contract, so it inherited portrait logic and looked poor.
## V5 comparison
The script verified that V5 still contains the original event annotation concepts:
1. `eventBox`
2. `drawPointer`
3. `drawEvents`
4. `drawDailyEvents`
V5 was not modified.
## V6 repair behaviour
1. Keeps the existing working V6 renderer file.
2. Turns `drawTrackerPointer` into a no-op so old diagonal lines cannot appear.
3. Replaces only the `drawHighAverageLowTrackers` layout function.
4. Keeps the high and low red dots at the true data points.
5. Uses a mid-plot average reference point.
6. Removes the bottom summary box call.
7. Removes the prior overlay workaround from `index.md`.
8. Removes any broken replacement renderer reference from `index.md`.
9. Cache-busts the working renderer to `20260602anno2`.
## Portrait behaviour
HIGH, AVERAGE and LOW boxes are placed in the blank space below the plot:
1. HIGH in the upper blank zone.
2. AVERAGE in the middle blank zone.
3. LOW in the lower blank zone.
Connector lines run from the actual chart points to those boxes.
## Fullscreen landscape behaviour
Fullscreen landscape is treated separately:
1. The chart remains large.
2. Boxes are compact and placed on the right-hand side in top, middle and lower zones.
3. Connector lines run from the actual high, average and low points to the boxes.
4. The old bottom summary box is not drawn.
## Files modified by workflow
1. `uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js`
2. `uk_energy_tracking_v6/index.md`
3. `uk_energy_tracking_v6/V6_REPAIR_PRICE_ANNOTATION_LAYOUT_REPORT.md`
## Files deliberately not modified
1. `uk_energy_tracking_v5/price-history-ui.js`
2. V5 data files
3. V6 data pipeline files
4. V6 control logic
5. V6 CSS
## Test instruction
Open `/uk_energy_tracking_v6/`, hard refresh, then test:
1. Normal in-page mobile portrait.
2. Fullscreen mobile portrait.
3. Fullscreen mobile landscape.
Expected result: no duplicate bottom summary box, no overlay boxes, red dots remain at true high and low points, portrait boxes sit below the chart in the blank space, and landscape shows a large chart with compact right-side pointer boxes.
""", encoding="utf-8")
print("V6 price annotation layout diagnosis and repair prepared.")GlobalGrid2050 Repair V6 Price Annotations V5 Style
A Python module in the scripts folder.
energy-dataglobalgrid2050 / scripts/repair_v6_price_annotations_v5_style.py · lines 1–152 of 152 · Entry point
- What it does
- It loads data. Uses libraries pathlib, re. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Repair V6 Price Annotations V5 Style 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 Price Annotations V5 Style Workflow.
- Application
- globalgrid2050 · scripts · Python module
- Uses
- pathlib, re
- Used by
- run by GlobalGrid2050 Repair V6 Price Annotations V5 Style 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_price_annotations_v5_style.py:1-152 · blob 8686e3477303e4b47217a469428c5067d88cac34 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
from pathlib import Path
import re
ROOT = Path(__file__).resolve().parents[1]
V6 = ROOT / "uk_energy_tracking_v6"
V5 = ROOT / "uk_energy_tracking_v5"
RENDER = V6 / "price_history_chart/render_price_chart/render_price_chart.js"
INDEX = V6 / "index.md"
REPORT = V6 / "V6_REPAIR_PRICE_ANNOTATIONS_V5_STYLE_REPORT.md"
required = [
ROOT / "AI_START_HERE.md",
V6 / "V6_ARCHITECTURAL_INTEGRITY_PROTOCOL.md",
V6 / "V5_V6_COMPARISON_REPORT.md",
V5 / "price-history-ui.js",
RENDER,
INDEX,
]
for path in required:
if not path.exists():
raise FileNotFoundError(f"Required file missing: {path.relative_to(ROOT)}")
path.read_text(encoding="utf-8")
v5_before = (V5 / "price-history-ui.js").read_text(encoding="utf-8")
for token in ["function eventBox", "function drawPointer", "function drawEvents", "function drawDailyEvents"]:
if token not in v5_before:
raise RuntimeError(f"V5 reference token missing: {token}")
js = RENDER.read_text(encoding="utf-8")
index = INDEX.read_text(encoding="utf-8")
issues = []
if "render_price_chart_box_overlay.js" in index:
issues.append("Overlay workaround loaded after renderer")
if "render_price_chart_v6_clean_boxes.js" in index:
issues.append("Broken replacement renderer reference present")
if "drawSummary(g,s,q,w,h,pad,isFull,isLandscape)" in js:
issues.append("Bottom summary box still being drawn")
if "function drawHighAverageLowTrackers" in js:
issues.append("Current V6 has custom tracker layout instead of V5 event annotation logic")
# V5 UI method, adapted only at the data boundary for V6 field names.
# No data loading, filtering, period selection, forecast or control logic is touched.
replacement = """ 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 eventBox(g,lines,q,x,y,align){var pad=8*q,lh=18*q,wid=0;g.save();g.font='900 '+14*q+'px Courier New';lines.forEach(function(t){wid=Math.max(wid,g.measureText(t).width)});var bh=lines.length*lh+pad*2,xx=align==='right'?x-wid-pad*2:x;g.fillStyle='rgba(5,7,12,.78)';g.strokeStyle='rgba(0,255,255,.35)';g.lineWidth=1*q;g.shadowColor='rgba(0,255,255,.24)';g.shadowBlur=8*q;g.beginPath();g.round … [line shortened here: 592 characters; full line on GitHub]
function drawPointer(g,point,q,x,y){g.save();g.strokeStyle='#ff3333';g.shadowColor='rgba(0,255,255,.55)';g.shadowBlur=7*q;g.lineWidth=1.5*q;g.beginPath();g.moveTo(point.x,point.y);g.lineTo(x,y-24*q);g.stroke();g.restore()}
function drawV5StyleEvents(g,s,X,Y,q,w,h,pad){if(!s)return;var hx=X(s.hi),hy=Y(s.hiValue),lx=X(s.lo),ly=Y(s.loValue);g.save();g.fillStyle='#ff3333';g.shadowColor='rgba(0,255,255,.85)';g.shadowBlur=8*q;g.beginPath();g.arc(hx,hy,5*q,0,Math.PI*2);g.fill();g.beginPath();g.arc(lx,ly,5*q,0,Math.PI*2);g.fill();g.restore();var hr=hx<w/2,lr=lx<w/2;var hxText=hr?Math.min(w-pad.right-150*q,hx+18*q):Math.ma … [line shortened here: 959 characters; full line on GitHub]
function drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape){drawV5StyleEvents(g,s,X,Y,q,w,h,pad)}
"""
js, count = re.subn(
r" function compactDateText\(t\)\{.*?\n function drawSummary",
replacement + " function drawSummary",
js,
count=1,
flags=re.S,
)
if count != 1:
raise RuntimeError("Could not replace V6 annotation helper block safely")
# Remove bottom summary draw calls, keeping the function definition untouched for rollback traceability.
patterns = [
"drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape);drawSummary(g,s,q,w,h,pad,isFull,isLandscape);",
"drawSummary(g,s,q,w,h,pad,isFull,isLandscape);drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape);",
"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)}",
]
for p in patterns:
js = js.replace(p, "drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape);")
if "drawSummary(g,s,q,w,h,pad,isFull,isLandscape);" in js:
raise RuntimeError("Bottom summary call remains after repair")
for token in ["function eventBox", "function drawPointer", "function drawV5StyleEvents", "drawHighAverageLowTrackers(g,s,q,w,h,pad,X,Y,isFull,isLandscape)"]:
if token not in js:
raise RuntimeError(f"V5 style assertion failed: {token}")
tracker_slice = js[js.find("function drawHighAverageLowTrackers"):js.find("function drawHighAverageLowTrackers")+500]
if "AVERAGE" in tracker_slice:
raise RuntimeError("Average label still present in event annotation block")
# Clean index.md so only the working V6 renderer is loaded and cache-busted.
index = re.sub(r'\n<script src="/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart_box_overlay\.js\?v=[^"]+"></script>', "", index)
index = re.sub(r'/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart_v6_clean_boxes\.js\?v=[^"]+',
'/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js?v=20260602v5exact1', index)
index = re.sub(r'/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart\.js\?v=[^"]+',
'/uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js?v=20260602v5exact1', index)
if "render_price_chart_box_overlay.js" in index or "render_price_chart_v6_clean_boxes.js" in index:
raise RuntimeError("Old overlay or replacement renderer still referenced in index.md")
if "render_price_chart.js?v=20260602v5exact1" not in index:
raise RuntimeError("Working renderer cache bust missing")
RENDER.write_text(js, encoding="utf-8")
INDEX.write_text(index, encoding="utf-8")
v5_after = (V5 / "price-history-ui.js").read_text(encoding="utf-8")
if v5_after != v5_before:
raise RuntimeError("V5 changed unexpectedly")
REPORT.write_text(f"""# V6 Repair Report: V5 Style Price Annotations
Status: generated by deterministic diagnostic repair script.
## User instruction
Copy the V5 in-page price annotation UI method into V6, on and off fullscreen, while keeping V6 data logic.
## Diagnosis before repair
{chr(10).join('- ' + i for i in issues) if issues else '- No duplicate overlay issue detected before repair.'}
## V5 reference confirmed
The script verified V5 contains:
1. `eventBox`
2. `drawPointer`
3. `drawEvents`
4. `drawDailyEvents`
V5 was read as the UI reference and was not modified.
## Behaviour applied to V6
1. Uses V5-style `eventBox` and `drawPointer` functions inside the V6 renderer.
2. Uses V6 rows, V6 stats, V6 X/Y scaling and V6 period controls.
3. Draws HIGH and LOW labels only, matching V5.
4. Red dots remain at the exact high and low data points.
5. Removes the AVERAGE event label.
6. Removes the bottom summary box draw call.
7. Removes the overlay workaround from `index.md`.
8. Removes the broken replacement renderer reference if present.
9. Cache-busts the working renderer to `20260602v5exact1`.
## Files modified by workflow
1. `uk_energy_tracking_v6/price_history_chart/render_price_chart/render_price_chart.js`
2. `uk_energy_tracking_v6/index.md`
3. `uk_energy_tracking_v6/V6_REPAIR_PRICE_ANNOTATIONS_V5_STYLE_REPORT.md`
## Files deliberately not modified
1. `uk_energy_tracking_v5/price-history-ui.js`
2. V5 data files
3. V6 data feeds
4. V6 control logic
5. V6 CSS
## Required test
Open `/uk_energy_tracking_v6/` and hard refresh.
Expected result: V6 keeps its data and controls but the chart annotations behave like V5: HIGH and LOW only, red dots at the exact points and V5-style labels in page and fullscreen modes. No bottom summary box and no average box.
""", encoding="utf-8")
print("V6 V5 exact UI annotation repair prepared.")