GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Gridbot Deprecated Tracker Stale Data Audit and 2 more files

A Python command-line tool in the scripts folder that reads deprecated tracker stale audit, deprecated tracker stale retirement, live grid energy and live grid price.

475 lines of Python from globalgrid2050, in 3 files. Topic: Automation and CI. Section 1762 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 Gridbot Daily MWh Seasonal Colouring energy-data · globalgrid2050 / scripts/gridbot_daily_mwh_seasonal_colouring.py lines 1–56
  2. GlobalGrid2050 Gridbot Daily MWh Titles Labels energy-data · globalgrid2050 / scripts/gridbot_daily_mwh_titles_labels.py lines 1–135
  3. GlobalGrid2050 Gridbot Deprecated Tracker Stale Data Audit storage · globalgrid2050 / scripts/gridbot_deprecated_tracker_stale_data_audit.py lines 1–284

GlobalGrid2050 Gridbot Daily MWh Seasonal Colouring

A Python command-line tool in the scripts folder that patches render (`patch_render`) and index (`patch_index`) and writes report (`write_report`) (units: MWh).

energy-dataglobalgrid2050 / scripts/gridbot_daily_mwh_seasonal_colouring.py · lines 1–56 of 56 · Entry point · pattern patch_render (shared by 2 files)

What it does
It loads data. Defines 7 functions or classes, including now, stamp, rel, patch_render, patch_index. Uses libraries __future__, argparse, datetime, json, pathlib. Side effects: reads or writes files.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Daily MWh Seasonal Colouring Workflow (globalgrid2050).
What it achieves
Defines `now`, `stamp`, `rel` and 3 more. It accepts `--apply`.
Why it matters
Run by GlobalGrid2050 Gridbot Daily MWh Seasonal Colouring Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, json, pathlib
Used by
run by GlobalGrid2050 Gridbot Daily MWh Seasonal Colouring Workflow (workflow run)
Produces
now, stamp, rel, patch_render, patch_index, write_report, main
Defines here
now, stamp, rel, patch_render, patch_index, 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/gridbot_daily_mwh_seasonal_colouring.py:1-56 · blob bf4474668a5f2064eca20f138cdd2801e023fb40 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import argparse, datetime as dt, json
from pathlib import Path
ROOT=Path(__file__).resolve().parent.parent
R=ROOT/'uk_energy_tracking_v6'/'generation_history'/'render_solar_daily_mwh_chart.js'
I=ROOT/'uk_energy_tracking_v6'/'generation_history'/'index.md'
RD=ROOT/'data_science_protocol'/'audit_reports'; RJD=RD/'json'; STEM='DAILY_MWH_SEASONAL_COLOURING'
ADD="""function seasonName(t){var m=new Date(t).getUTCMonth()+1;if(m===12||m<=2)return'Winter';if(m>=3&&m<=5)return'Spring';if(m>=6&&m<=8)return'Summer';return'Autumn'}
  function seasonColor(t){var s=seasonName(t);if(s==='Winter')return'#00ffff';if(s==='Spring')return'#00ff88';if(s==='Summer')return'#ffcc00';return'#c79245'}
  function drawSeasonKey(g,q,pad){var items=[['Winter','#00ffff'],['Spring','#00ff88'],['Summer','#ffcc00'],['Autumn','#c79245']],x=pad.left,y=pad.top-28*q;g.save();g.font=9*q+'px Courier New';items.forEach(function(it){g.fillStyle=it[1];g.shadowColor=it[1];g.shadowBlur=4*q;g.fillRect(x,y-7*q,8*q,8*q);g.shadowBlur=0;g.fillStyle='#9aa3b6';g.fillText(it[0],x+12*q,y);x+=58*q});g.restore()}
  function drawSeasonLine(g,rows,p,q){g.save();g.lineWidth=2.15*q;g.lineCap='round';g.lineJoin='round';for(var i=1;i<rows.length;i++){var a=rows[i-1],b=rows[i],col=seasonColor(tm(b));g.strokeStyle=col;g.shadowColor=col;g.shadowBlur=8*q;g.beginPath();g.moveTo(p.X(a),p.Y(val(a)));g.lineTo(p.X(b),p.Y(val(b)));g.stroke()}g.restore()}"""
def now(): return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00','Z')
def stamp(): return dt.datetime.now(dt.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
def rel(p): return p.relative_to(ROOT).as_posix()
def patch_render(t):
    miss=[]
    if 'function seasonName(' not in t:
        marker="function drawTicks(g,w,h,q,scale,pad,t0,t1){"
        if marker in t: t=t.replace(marker,ADD+'\n  '+marker,1)
        else: miss.append('drawTicks marker')
    old="var pad=isFull?(cssW>cssH?{left:72*q,right:44*q,top:72*q,bottom:58*q}:{left:78*q,right:38*q,top:96*q,bottom:170*q}):{left:(cssW<520?86:96)*q,right:(cssW<520?48:72)*q,top:76*q,bottom:(cssW<620?150:116)*q},t0=result.start.getTime(),t1=result.end.getTime(),scale=mm(rows),p=points(w,h,pad,scale,t0,t1),c='#f5c518';drawTicks(ctx,w,h,q,scale,pad,t0,t1);ctx.save();ctx.strokeStyle=c;ctx.lineWidth=  … [line shortened here: 608 characters; full line on GitHub]
    new="var pad=isFull?(cssW>cssH?{left:72*q,right:44*q,top:72*q,bottom:58*q}:{left:78*q,right:38*q,top:96*q,bottom:170*q}):{left:(cssW<520?86:96)*q,right:(cssW<520?48:72)*q,top:76*q,bottom:(cssW<620?150:116)*q},t0=result.start.getTime(),t1=result.end.getTime(),scale=mm(rows),p=points(w,h,pad,scale,t0,t1);drawTicks(ctx,w,h,q,scale,pad,t0,t1);drawSeasonKey(ctx,q,pad);drawSeasonLine(ctx,rows,p,q);v  … [line shortened here: 418 characters; full line on GitHub]
    if old in t: t=t.replace(old,new,1)
    elif 'drawSeasonLine(ctx,rows,p,q)' in t: pass
    else: miss.append('fixed yellow line marker')
    return t,miss
def patch_index(t):
    done=False
    for v in ['20260611mwhmulti1','20260611mwhlabels1','20260610solarmwh4']:
        old='render_solar_daily_mwh_chart.js?v='+v
        if old in t:
            t=t.replace(old,'render_solar_daily_mwh_chart.js?v=20260611mwhseason1',1); done=True
    return t,([] if done or '20260611mwhseason1' in t else ['index render cache marker'])
def write_report(r):
    RD.mkdir(parents=True,exist_ok=True); RJD.mkdir(parents=True,exist_ok=True); s=stamp()
    md='\n'.join(['# Daily MWh Seasonal Colouring','',f"Generated UTC: `{r['generatedUTC']}`",f"Mode: `{r['mode']}`",f"Changed files: `{', '.join(r['changedFiles'])}`",f"Pass: `{r['pass']}`",'','Adds V5 style season colours to the V6 daily generation energy chart. No data files are changed.'])+'\n'
    for p in (RD/f'{STEM}_{s}.md',RD/f'{STEM}_LATEST.md'): p.write_text(md,encoding='utf-8')
    js=json.dumps(r,indent=2,ensure_ascii=False)+'\n'
    for p in (RJD/f'{STEM}_{s}.json',RJD/f'{STEM}_LATEST.json'): p.write_text(js,encoding='utf-8')
def main():
    ap=argparse.ArgumentParser(); ap.add_argument('--apply',action='store_true'); args=ap.parse_args()
    rt=R.read_text(encoding='utf-8'); it=I.read_text(encoding='utf-8')
    nr,m1=patch_render(rt); ni,m2=patch_index(it); missing=m1+m2
    checks={'season_name_function_present':'function seasonName(' in nr,'season_colour_function_present':'function seasonColor(' in nr,'season_key_present':'drawSeasonKey' in nr,'season_line_present':'drawSeasonLine' in nr,'fixed_single_yellow_line_removed':"c='#f5c518'" not in nr,'high_low_markers_preserved':'HIGH DAY' in nr and 'LOW DAY' in nr,'selected_inspection_preserved':'SELECTED' in nr,'mw  … [line shortened here: 590 characters; full line on GitHub]
    changed=[]
    if nr!=rt: changed.append(rel(R))
    if ni!=it: changed.append(rel(I))
    passed=all(checks.values()) and len(changed)>=1
    if args.apply and passed:
        R.write_text(nr,encoding='utf-8'); I.write_text(ni,encoding='utf-8')
    r={'reportTitle':'Daily MWh Seasonal Colouring','schemaVersion':'1.0.0','generatedUTC':now(),'mode':'apply' if args.apply else 'audit','changedFiles':changed,'missingMarkers':missing,'checks':checks,'pass':passed,'applied':bool(args.apply and passed),'nextAction':'Run apply after audit review.' if not args.apply else 'Open Daily Generation Energy Output and confirm seasonal colours and legend.  … [line shortened here: 402 characters; full line on GitHub]
    write_report(r)
    if not passed: raise SystemExit('seasonal colouring checks failed')
    return 0
if __name__=='__main__': raise SystemExit(main())

GlobalGrid2050 Gridbot Daily MWh Titles Labels

A Python command-line tool in the scripts folder that reads solar. It applies replacements (`apply_replacements`) and writes reports (`write_reports`).

energy-dataglobalgrid2050 / scripts/gridbot_daily_mwh_titles_labels.py · lines 1–135 of 135 · Entry point · pattern write_reports (shared by 12 files)

What it does
It loads solar. Defines 6 functions or classes, including now, stamp, rel, apply_replacements, write_reports. Uses libraries __future__, argparse, datetime, json, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: solar.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Daily MWh Titles Labels Workflow (globalgrid2050).
What it achieves
Defines `now`, `stamp`, `rel` and 2 more. It accepts `--apply`.
Why it matters
Run by GlobalGrid2050 Gridbot Daily MWh Titles Labels Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, json, pathlib
Used by
run by GlobalGrid2050 Gridbot Daily MWh Titles Labels Workflow (workflow run)
Produces
now, stamp, rel, apply_replacements, write_reports, main
Defines here
now, stamp, rel, apply_replacements, write_reports, 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/gridbot_daily_mwh_titles_labels.py:1-135 · blob 9267ae364f464303efd3890d05e050e60c1a8f66 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import argparse, datetime as dt, json
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
TARGET = ROOT / 'uk_energy_tracking_v6' / 'generation_history' / 'index.md'
REPORT_DIR = ROOT / 'data_science_protocol' / 'audit_reports'
REPORT_JSON_DIR = REPORT_DIR / 'json'
STEM = 'DAILY_MWH_TITLES_LABELS'

REPLACEMENTS = [
    (
        '<div class="generation-study-summary"><strong>Solar daily energy output</strong> Standalone daily energy chart using stored Sheffield Solar PVLive MWh. This shows energy generated across each full day, not peak MW. Other technologies will be added only after their daily MWh data is separately fetched or audited.</div>',
        '<div class="generation-study-summary"><strong>Daily generation energy output</strong> Standalone daily MWh chart. Solar uses stored Sheffield Solar PVLive daily MWh. Elexon technologies use audited FUELHH derived daily MWh calculated from half hourly MW values multiplied by 0.5 hours. This chart presents total energy across each full day, not peak MW or average MW.</div>'
    ),
    (
        '<strong>Daily MWh chart</strong>',
        '<strong>Daily energy chart</strong>'
    ),
    (
        '<div id="solar-daily-mwh-status" class="price-history-range-status">Solar daily MWh chart awaiting PVLive data.</div>',
        '<div id="solar-daily-mwh-status" class="price-history-range-status">Daily MWh chart awaiting selected technology data.</div>'
    ),
    (
        '<strong>Solar Daily MWh · PVLive stored energy</strong>',
        '<strong>Daily MWh by technology</strong>'
    ),
    (
        '<strong>Source:</strong> Sheffield Solar PVLive stored daily MWh. This chart shows daily energy, not MW peak power. Other technologies remain disabled until separate MWh data audits are complete.',
        '<strong>Source:</strong> Solar uses Sheffield Solar PVLive stored daily MWh. Other technologies use Elexon FUELHH derived daily MWh after chart wiring. This chart shows daily energy, not MW peak power or average MW.'
    ),
    (
        'render_solar_daily_mwh_chart.js?v=20260610solarmwh4',
        'render_solar_daily_mwh_chart.js?v=20260611mwhlabels1'
    ),
    (
        'control_solar_daily_mwh_chart.js?v=20260610solarmwh2',
        'control_solar_daily_mwh_chart.js?v=20260611mwhlabels1'
    ),
]


def now() -> str:
    return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00','Z')

def stamp() -> str:
    return dt.datetime.now(dt.timezone.utc).strftime('%Y%m%dT%H%M%SZ')

def rel(path: Path) -> str:
    return path.relative_to(ROOT).as_posix()

def apply_replacements(text: str):
    changed = text
    missing = []
    applied = []
    for old, new in REPLACEMENTS:
        if old not in changed:
            missing.append(old[:120])
        else:
            changed = changed.replace(old, new, 1)
            applied.append(new[:120])
    return changed, missing, applied

def write_reports(report: dict):
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    s = stamp()
    md = '\n'.join([
        '# Daily MWh Titles And Labels',
        '',
        f"Generated UTC: `{report['generatedUTC']}`",
        f"Mode: `{report['mode']}`",
        f"Target file: `{report['targetFile']}`",
        f"Changed: `{report['wouldChange']}`",
        f"Replacement count: `{report['replacementCount']}`",
        f"Missing markers: `{report['missingCount']}`",
        f"Pass: `{report['pass']}`",
        '',
        '## Purpose',
        '',
        'This changes visible titles and source labels for the daily MWh chart so the page describes daily energy output by technology, while preserving Solar PVLive as the currently enabled chart data source and leaving Elexon data wiring for the next audited step.',
        '',
        '## Safety',
        '',
        'This workflow does not modify data files. It does not wire new chart data. It does not change calculations. It only changes title, label and cache bust text in the generation history page.'
    ]) + '\n'
    for p in (REPORT_DIR / f'{STEM}_{s}.md', REPORT_DIR / f'{STEM}_LATEST.md'):
        p.write_text(md, encoding='utf-8')
    js = json.dumps(report, indent=2, ensure_ascii=False) + '\n'
    for p in (REPORT_JSON_DIR / f'{STEM}_{s}.json', REPORT_JSON_DIR / f'{STEM}_LATEST.json'):
        p.write_text(js, encoding='utf-8')

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--apply', action='store_true')
    args = ap.parse_args()
    original = TARGET.read_text(encoding='utf-8')
    changed, missing, applied = apply_replacements(original)
    would_change = changed != original
    checks = {
        'target_exists': TARGET.exists(),
        'all_markers_found': len(missing) == 0,
        'would_change_index_only': would_change,
        'no_data_files_changed_by_script': True,
        'solar_source_label_preserved': 'Solar uses stored Sheffield Solar PVLive daily MWh' in changed,
        'elexon_source_label_prepared': 'Elexon technologies use audited FUELHH derived daily MWh' in changed,
        'daily_energy_not_peak_or_average_label': 'not peak MW or average MW' in changed,
        'cache_busters_updated': '20260611mwhlabels1' in changed,
    }
    if args.apply and all(checks.values()):
        TARGET.write_text(changed, encoding='utf-8')
    report = {
        'reportTitle': 'Daily MWh Titles And Labels',
        'schemaVersion': '1.0.0',
        'generatedUTC': now(),
        'mode': 'apply' if args.apply else 'audit',
        'targetFile': rel(TARGET),
        'changedFiles': [rel(TARGET)] if would_change else [],
        'replacementCount': len(applied),
        'missingCount': len(missing),
        'missingMarkers': missing,
        'wouldChange': would_change,
        'applied': bool(args.apply and all(checks.values())),
        'checks': checks,
        'pass': all(checks.values()),
        'nextAction': 'Run apply only after human review confirms wording.' if not args.apply else 'Open live page and confirm titles and labels only changed.'
    }
    write_reports(report)
    if not report['pass']:
        raise SystemExit('Daily MWh title label checks failed')
    return 0

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

GlobalGrid2050 Gridbot Deprecated Tracker Stale Data Audit

A Python command-line tool in the scripts folder that reads deprecated tracker stale audit, deprecated tracker stale retirement, live grid energy and live grid price.

storageglobalgrid2050 / scripts/gridbot_deprecated_tracker_stale_data_audit.py · lines 1–284 of 284 · Entry point · pattern build_manifest (shared by 2 files)

What it does
It loads deprecated tracker stale audit, deprecated tracker stale retirement, live grid energy and live grid price. Defines 14 functions or classes, including now_utc, now_text, read_text, read_json, parse_time. Uses libraries __future__, argparse, datetime, json, os. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'deprecated'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file DEPRECATED_TRACKER_STALE_DATA_AUDIT_LATEST.json; JSON file DEPRECATED_TRACKER_STALE_DATA_RETIREMENT_MANIFEST.json; JSON file live_grid_energy.json; JSON file live_grid_price.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Gridbot Deprecated Tracker Stale Data Audit Workflow (globalgrid2050).
What it achieves
It reads JSON (`read_json`) and parses time (`parse_time`). Defines `now_utc`, `now_text`, `read_text` and 10 more. It reads `live_grid_energy.json`. It accepts `--mode`.
Why it matters
Run by GlobalGrid2050 Gridbot Deprecated Tracker Stale Data Audit Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
__future__, argparse, datetime, json, os, pathlib
Used by
run by GlobalGrid2050 Gridbot Deprecated Tracker Stale Data Audit Workflow (workflow run)
Produces
now_utc, now_text, read_text, read_json, parse_time, age_hours, workflow_status, folder_for, app_file, audit_version, audit_v6, build_manifest
Defines here
now_utc, now_text, read_text, read_json, parse_time, age_hours, workflow_status, folder_for, app_file, audit_version, audit_v6, build_manifest, 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/gridbot_deprecated_tracker_stale_data_audit.py:1-284 · blob 19b1d0e12dfe02746c0cc8918bc37a859f01b510 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import datetime as dt
import json
import os
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
REPORT_DIR = ROOT / "data_science_protocol" / "audit_reports"
REPORT_JSON_DIR = REPORT_DIR / "json"
REPORT_MD = REPORT_DIR / "DEPRECATED_TRACKER_STALE_DATA_AUDIT_LATEST.md"
REPORT_JSON = REPORT_JSON_DIR / "DEPRECATED_TRACKER_STALE_DATA_AUDIT_LATEST.json"
MANIFEST = ROOT / "gridbot_manifests" / "DEPRECATED_TRACKER_STALE_DATA_RETIREMENT_MANIFEST.json"
SCRIPT = "scripts/gridbot_deprecated_tracker_stale_data_audit.py"
VERSIONS = [2, 3, 4, 5]
STALE_MINUTES = 30


def now_utc() -> dt.datetime:
    return dt.datetime.now(dt.timezone.utc)


def now_text() -> str:
    return now_utc().isoformat().replace("+00:00", "Z")


def read_text(path: Path) -> str:
    return path.read_text(encoding="utf-8") if path.exists() else ""


def read_json(path: Path) -> dict:
    if not path.exists():
        return {}
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception as exc:
        return {"readError": str(exc)}


def parse_time(value) -> dt.datetime | None:
    if not value:
        return None
    text = str(value).strip()
    if text.endswith("Z"):
        text = text[:-1] + "+00:00"
    try:
        parsed = dt.datetime.fromisoformat(text)
        if parsed.tzinfo is None:
            parsed = parsed.replace(tzinfo=dt.timezone.utc)
        return parsed.astimezone(dt.timezone.utc)
    except Exception:
        return None


def age_hours(value, now: dt.datetime) -> float | None:
    parsed = parse_time(value)
    if parsed is None:
        return None
    return round((now - parsed).total_seconds() / 3600.0, 3)


def workflow_status(version: int) -> dict:
    path = ROOT / ".github" / "workflows" / f"fetch_uk_energy_and_prices_v{version}.yml"
    text = read_text(path)
    has_dispatch = "workflow_dispatch" in text
    has_cron = "schedule:" in text and "cron:" in text
    return {
        "path": str(path.relative_to(ROOT)),
        "exists": path.exists(),
        "hasWorkflowDispatch": has_dispatch,
        "hasCronSchedule": has_cron,
        "manualOnly": bool(has_dispatch and not has_cron),
    }


def folder_for(version: int) -> Path:
    return ROOT / f"uk_energy_tracking_v{version}"


def app_file(version: int) -> tuple[str | None, str]:
    folder = folder_for(version)
    for name in ["live-app.js", "index.md"]:
        path = folder / name
        if path.exists():
            return str(path.relative_to(ROOT)), read_text(path)
    return None, ""


def audit_version(version: int, now: dt.datetime) -> dict:
    folder = folder_for(version)
    energy_path = folder / "live_grid_energy.json"
    price_path = folder / "live_grid_price.json"
    index_path = folder / "index.md"
    energy = read_json(energy_path)
    price = read_json(price_path)
    app_path, app = app_file(version)
    energy_time = energy.get("updated")
    price_time = price.get("updated")
    energy_age = age_hours(energy_time, now)
    price_age = age_hours(price_time, now)
    ages = [x for x in [energy_age, price_age] if x is not None]
    max_age = max(ages) if ages else None
    mix = energy.get("mix") if isinstance(energy.get("mix"), list) else []
    collapsed = any(str(row.get("label")) == "Imports & Exports" for row in mix) or "Imports & Exports" in app
    masks = "latestIso" in app and "dateLabel" in app
    index_text = read_text(index_path)
    already_retired = "retired" in index_text.lower() or "archived" in index_text.lower() or "retained for reference" in app.lower()
    wf = workflow_status(version)
    if already_retired:
        verdict = "abandoned"
    elif wf["hasCronSchedule"] and max_age is not None and max_age <= (STALE_MINUTES / 60.0):
        verdict = "live"
    elif max_age is None:
        verdict = "abandoned"
    else:
        verdict = "stale"
    return {
        "version": f"v{version}",
        "route": f"/uk_energy_tracking_v{version}/",
        "folderExists": folder.exists(),
        "indexPath": str(index_path.relative_to(ROOT)) if index_path.exists() else None,
        "appPath": app_path,
        "energyPath": str(energy_path.relative_to(ROOT)),
        "pricePath": str(price_path.relative_to(ROOT)),
        "energyUpdated": energy_time,
        "priceUpdated": price_time,
        "energyAgeHours": energy_age,
        "priceAgeHours": price_age,
        "workflow": wf,
        "usesLatestIsoDateLabelPattern": masks,
        "containsCollapsedImportsExports": collapsed,
        "alreadyRetiredOrArchived": already_retired,
        "verdict": verdict,
    }


def audit_v6(now: dt.datetime) -> dict:
    folder = ROOT / "uk_energy_tracking_v6"
    energy = read_json(folder / "live_grid_energy.json")
    price = read_json(folder / "live_grid_price.json")
    wf = workflow_status(6)
    return {
        "version": "v6",
        "route": "/uk_energy_tracking_v6/",
        "energyUpdated": energy.get("updated"),
        "priceUpdated": price.get("updated"),
        "energyAgeHours": age_hours(energy.get("updated"), now),
        "priceAgeHours": age_hours(price.get("updated"), now),
        "workflow": wf,
        "confirmedScheduledLiveVersion": bool(wf.get("hasCronSchedule")),
    }


def build_manifest(audits: list[dict]) -> dict:
    target_files = [f"uk_energy_tracking_v{v}/index.md" for v in VERSIONS]
    source_files = []
    forbidden = []
    for v in VERSIONS:
        source_files += [f"uk_energy_tracking_v{v}/live_grid_energy.json", f"uk_energy_tracking_v{v}/live_grid_price.json", f".github/workflows/fetch_uk_energy_and_prices_v{v}.yml"]
        forbidden += [f"uk_energy_tracking_v{v}/live_grid_energy.json", f"uk_energy_tracking_v{v}/live_grid_price.json"]
    source_files.append(".github/workflows/fetch_uk_energy_and_prices_v6.yml")
    manifest = {
        "feature_id": "deprecated_tracker_stale_data_retirement",
        "feature_name": "Deprecated tracker stale data audit and retirement",
        "owner": "VENTUS Ltd",
        "created_utc": now_text(),
        "target_files": target_files,
        "source_files": source_files,
        "forbidden_files": forbidden,
        "audit_report_md": str(REPORT_MD.relative_to(ROOT)),
        "audit_report_json": str(REPORT_JSON.relative_to(ROOT)),
        "rollback_method": "Revert the apply commit. Apply must touch only deprecated tracker UI or routing files, never data files.",
        "human_approval_required": True,
        "data_source_domain": "UK live electricity tracker UI and routing only. No data refresh source is changed.",
        "public_safety_or_ndA_risk": "Public trust defect caused by stale live data. No NDA content expected.",
        "planned_apply": "Retire deprecated tracker routes v2 through v5 in favour of /uk_energy_tracking_v6/. Do not add cron schedules to old versions.",
        "version_verdicts": {a["version"]: a["verdict"] for a in audits},
    }
    MANIFEST.parent.mkdir(parents=True, exist_ok=True)
    MANIFEST.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    return manifest


def write_report(report: dict) -> None:
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT_JSON_DIR.mkdir(parents=True, exist_ok=True)
    lines = [
        "# Deprecated Tracker Stale Data Audit",
        "",
        f"Generated UTC: `{report['generatedUTC']}`",
        f"Mode: `{report['mode']}`",
        f"Pass: `{report['pass']}`",
        "",
        report["executiveSummary"],
        "",
        "## Version verdicts",
        "",
        "| Version | Route | Energy updated | Energy age h | Price updated | Price age h | Workflow | Timestamp mask | Imports and Exports bucket | Verdict |",
        "|---|---|---:|---:|---:|---:|---|---|---|---|",
    ]
    for a in report["versionAudits"]:
        wf = "cron" if a["workflow"]["hasCronSchedule"] else ("manual only" if a["workflow"]["manualOnly"] else "missing")
        lines.append(f"| {a['version']} | `{a['route']}` | {a['energyUpdated']} | {a['energyAgeHours']} | {a['priceUpdated']} | {a['priceAgeHours']} | {wf} | {a['usesLatestIsoDateLabelPattern']} | {a['containsCollapsedImportsExports']} | **{a['verdict']}** |")
    lines += [
        "",
        "## V6 scheduled live check",
        "",
        json.dumps(report["liveVersionCheck"], indent=2),
        "",
        "## Apply guardrail",
        "",
        "Apply mode is deliberately not run here. The intended fix is to retire deprecated tracker routes v2 through v5 in favour of `/uk_energy_tracking_v6/`, without adding old cron schedules and without touching data files.",
        "",
        "## Changed files",
        "",
    ]
    for p in report["changedFiles"]:
        lines.append(f"- `{p}`")
    lines += ["", "## Checks", "", "| Check | Result |", "|---|---|"]
    for k, v in report["checks"].items():
        lines.append(f"| {k} | {'✅' if v else '❌'} |")
    lines += ["", "## Rollback", "", report["rollbackMethod"], ""]
    REPORT_MD.write_text("\n".join(lines), encoding="utf-8")
    REPORT_JSON.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--mode", choices=["audit"], default="audit")
    args = parser.parse_args()
    now = now_utc()
    audits = [audit_version(v, now) for v in VERSIONS]
    live = audit_v6(now)
    manifest = build_manifest(audits)
    checks = {
        "audit_covers_v2_to_v5": len(audits) == 4,
        "v6_is_confirmed_scheduled_live_version": bool(live["workflow"].get("hasCronSchedule")),
        "deprecated_versions_do_not_have_cron": all(not a["workflow"].get("hasCronSchedule") for a in audits),
        "timestamp_mask_checked_for_each_version": all("usesLatestIsoDateLabelPattern" in a for a in audits),
        "imports_exports_bucket_checked_for_each_version": all("containsCollapsedImportsExports" in a for a in audits),
        "audit_does_not_modify_data_files": True,
        "manifest_written": MANIFEST.exists(),
    }
    passed = all(checks.values())
    report = {
        "reportTitle": "Deprecated Tracker Stale Data Audit",
        "schemaVersion": "1.0.0",
        "generatedUTC": now_text(),
        "repository": "Ventusltd/globalgrid2050",
        "branch": "main",
        "gitHeadBefore": os.environ.get("GITHUB_SHA", "local"),
        "gitHeadAfter": os.environ.get("GITHUB_SHA", "local"),
        "workflowName": "GridBot Deprecated Tracker Stale Data Audit",
        "scriptName": SCRIPT,
        "upgradeType": "correctness and public trust fix under launch freeze",
        "mode": args.mode,
        "sourceApis": [],
        "sourceWindows": {"staleThresholdMinutes": STALE_MINUTES, "auditVersions": [f"v{v}" for v in VERSIONS], "liveVersion": "v6"},
        "inputFiles": manifest["source_files"],
        "outputFiles": [str(REPORT_MD.relative_to(ROOT)), str(REPORT_JSON.relative_to(ROOT)), str(MANIFEST.relative_to(ROOT))],
        "changedFiles": [],
        "addedFiles": [str(MANIFEST.relative_to(ROOT))],
        "deletedFiles": [],
        "checks": checks,
        "rawTemporaryFilesFound": [],
        "browserRoutingAffected": False,
        "rollbackMethod": manifest["rollback_method"],
        "executiveSummary": "Audits deprecated UK energy tracker versions v2 to v5 for stale live data, missing cron schedules, timestamp masking, and collapsed Imports and Exports generation mix. No data files are modified by audit mode.",
        "humanReviewStatus": "required before apply",
        "nextAction": "Review this audit report. If accepted, build or trigger the apply retirement workflow to route deprecated versions to v6. Do not add cron schedules to deprecated versions.",
        "applied": False,
        "pass": passed,
        "versionAudits": audits,
        "liveVersionCheck": live,
    }
    write_report(report)
    print(json.dumps(report, indent=2, ensure_ascii=False))
    return 0 if passed else 1


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