GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Validate Renewables V6 Scope and 3 more files

A Python command-line tool in the scripts folder that reads renewables integrity, major projects, major project news and Renewable Energy Planning Database (REPD) master, using SHA-256.

700 lines of Python from globalgrid2050, in 4 files. Topic: Automation and CI. Section 1787 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 Validate Project Identity V6 storage · globalgrid2050 / scripts/validate_project_identity_v6.py lines 1–247
  2. GlobalGrid2050 Validate Renewables V5 Integrity ingest · globalgrid2050 / scripts/validate_renewables_v5_integrity.py lines 1–79
  3. GlobalGrid2050 Validate Renewables V6 Integrity other · globalgrid2050 / scripts/validate_renewables_v6_integrity.py lines 1–7
  4. GlobalGrid2050 Validate Renewables V6 Scope storage · globalgrid2050 / scripts/validate_renewables_v6_scope.py lines 1–367

GlobalGrid2050 Validate Project Identity V6

A Python module in the scripts folder that reads major project news, project news links, the Renewable Energy Planning Database (REPD) register and solar, using SHA-256.

storageglobalgrid2050 / scripts/validate_project_identity_v6.py · lines 1–247 of 247 · Entry point · pattern number (shared by 21 files)

What it does
It loads major project news, project news links, the REPD register and solar. Defines check, load, clean, number. Uses libraries __future__, hashlib, json, math, os. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: the REPD register, solar.
Inputs & outputs
In: JSON file major_project_news_v6.json; JSON file project_news_links_v6.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Major Project News V6 Workflow (globalgrid2050).
What it achieves
It is built from the check step (`check`), the load step (`load`) and the clean step (`clean`). Validate V6 project/development identities and news relationships.
Why it matters
Run by GlobalGrid2050 Major Project News V6 Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
GlobalGrid2050 Renewable Energy Planning Database (REPD) Sources V6 (import), __future__, hashlib, json, math, os, datetime, pathlib
Used by
run by GlobalGrid2050 Major Project News V6 Workflow (workflow run)
Produces
check, load, clean, number
Defines here
check, load, clean, number
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/validate_project_identity_v6.py:1-247 · blob dfe185d916c83e33b2a53c69c0c64240cf30e83a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""Validate V6 project/development identities and news relationships."""
from __future__ import annotations

import hashlib
import json
import math
import os
from datetime import datetime, timezone
from pathlib import Path

from repd_sources_v6 import (
    DIST,
    EXPECTED_BESS_GT100 as EXPECTED_BESS,
    EXPECTED_SOLAR_GT1 as EXPECTED_SOLAR,
    EXPECTED_UNIQUE_REFS as EXPECTED_ROWS,
    EXPECTED_ROWS as EXPECTED_SOURCE_ROWS,
    OUTPUT_SUFFIX,
    RELEASE_DESCRIPTOR,
    utc_now,
)

ROOT = Path(__file__).resolve().parents[1]
IDENTITY = DIST / f"project_identity_{OUTPUT_SUFFIX}.json"
PROJECTS = DIST / f"major_projects_{OUTPUT_SUFFIX}.json"
# News is not regenerated by a descriptor run: the frozen V6 news/link files are
# read (never written) to prove the existing bindings still resolve in the new release.
_INPUT_ROOT = Path(os.environ.get("REPD_INPUT_ROOT", "").strip() or ROOT)
NEWS = _INPUT_ROOT / RELEASE_DESCRIPTOR.get("news_input", "dist/major_project_news_v6.json")
LINKS = _INPUT_ROOT / RELEASE_DESCRIPTOR.get("links_input", "dist/project_news_links_v6.json")
REPORT = DIST / f"project_identity_{OUTPUT_SUFFIX}_integrity.json"

EXPECTED_PROJECTS = EXPECTED_SOLAR + EXPECTED_BESS

errors = []
checks = []


def check(condition, gate, detail=""):
    ok = bool(condition)
    checks.append({"gate": gate, "pass": ok, "detail": detail})
    if not ok:
        errors.append(f"{gate}: {detail}" if detail else gate)


def load(path):
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception as exc:
        errors.append(f"cannot load {path}: {exc}")
        return {}


def clean(value):
    return str(value or "").strip()


def number(value):
    try:
        result = float(value)
        return result if math.isfinite(result) else None
    except Exception:
        return None


identity = load(IDENTITY)
projects = load(PROJECTS)
news = load(NEWS)
links = load(LINKS)

records = identity.get("records") or []
check(identity.get("schema") == "globalgrid2050.project-identity.v6", "identity schema")
check(identity.get("raw_record_count") == EXPECTED_ROWS, "identity raw row count", str(identity.get("raw_record_count")))
check(identity.get("repd_bound_count") == EXPECTED_ROWS, "identity REPD-bound count", str(identity.get("repd_bound_count")))
check(identity.get("globalgrid_only_count") == 0, "no fabricated REPD identities", str(identity.get("globalgrid_only_count")))
check(len(records) == EXPECTED_ROWS, "identity record array exact", f"records={len(records)}")
check(identity.get("identity_rules", {}).get("capacity_not_identity") is True, "capacity excluded from identity")

by_ref = {}
by_gg = {}
identity_error_start = len(errors)
for index, record in enumerate(records):
    ref = clean(record.get("repd_ref"))
    gg = clean(record.get("gg_project_id"))
    development = clean(record.get("gg_development_id"))
    if not ref:
        errors.append(f"identity row {index} lacks official REPD Ref")
    if gg != f"GG2050-REPD-{ref}":
        errors.append(f"identity row {index} has non-deterministic project ID: {gg}")
    if record.get("identity_status") != "REPD_BOUND":
        errors.append(f"identity row {index} is not REPD_BOUND")
    if not development.startswith("GG2050-DEV-"):
        errors.append(f"identity row {index} lacks development ID")
    if record.get("capacity_known") != (number(record.get("capacity_mw")) is not None):
        errors.append(f"identity row {index} violates capacity-null discipline")
    if ref in by_ref:
        errors.append(f"duplicate identity REPD Ref: {ref}")
    if gg in by_gg:
        errors.append(f"duplicate GlobalGrid project ID: {gg}")
    by_ref[ref] = record
    by_gg[gg] = record
check(len(errors) == identity_error_start, "all identity rows valid and unique", f"new_errors={len(errors)-identity_error_start}")

relationship_error_start = len(errors)
for ref, record in by_ref.items():
    development = clean(record.get("gg_development_id"))
    for relation in record.get("relationships") or []:
        target = clean(relation.get("repd_ref"))
        if relation.get("type") not in {"CURRENT_VERSION", "PREVIOUS_REPD_REF", "RELATED_APPLICATION", "COLOCATED_COMPONENT"}:
            errors.append(f"untyped relation {ref}->{target}: {relation.get('type')}")
        if target in by_ref:
            if clean(by_ref[target].get("gg_development_id")) != development:
                errors.append(f"resolvable relation not grouped {ref}->{target}")
    for target in record.get("development_repd_refs") or []:
        target = clean(target)
        if target not in by_ref:
            errors.append(f"development member absent {ref}->{target}")
        elif clean(by_ref[target].get("gg_development_id")) != development:
            errors.append(f"development group inconsistent {ref}->{target}")
check(len(errors) == relationship_error_start, "all identity relationships resolve consistently", f"new_errors={len(errors)-relationship_error_start}")

project_rows = projects.get("projects") or []
check(projects.get("schema") == "globalgrid2050.major-projects.v6", "public project schema")
check(projects.get("repd_bound") is True, "public projects REPD-bound")
check(projects.get("globalgrid_id_required") is True, "public projects GlobalGrid-bound")
check(projects.get("csv_xlsx_reconciled") is True, "public projects reconciled")
check(projects.get("source_record_count") == EXPECTED_SOURCE_ROWS, "public source row metadata")
check(projects.get("project_count") == EXPECTED_PROJECTS == len(project_rows), "public project count", f"metadata={projects.get('project_count')} rows={len(project_rows)}")
check(projects.get("solar_count") == EXPECTED_SOLAR, "public solar count")
check(projects.get("bess_count") == EXPECTED_BESS, "public BESS count")
canonical_projects = json.dumps(project_rows, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
check(projects.get("projects_sha256") == hashlib.sha256(canonical_projects.encode("utf-8")).hexdigest(), "public project-array hash")

project_refs = set()
solar = bess = 0
project_error_start = len(errors)
for index, project in enumerate(project_rows):
    ref = clean(project.get("repd_ref"))
    identity_row = by_ref.get(ref)
    if not identity_row:
        errors.append(f"public project {index} absent from identity registry: {ref}")
        continue
    if ref in project_refs:
        errors.append(f"duplicate public project REPD Ref: {ref}")
    project_refs.add(ref)
    for field, project_key, identity_key in (
        ("project ID", "gg_project_id", "gg_project_id"),
        ("development ID", "gg_development_id", "gg_development_id"),
        ("name", "name", "site_name"),
        ("status", "status", "status"),
        ("update date", "repd_record_updated", "repd_record_updated"),
    ):
        if project.get(project_key) != identity_row.get(identity_key):
            errors.append(f"public {field} differs from identity registry: {ref}")
    if number(project.get("capacity_mw")) != number(identity_row.get("capacity_mw")):
        errors.append(f"public capacity differs from identity registry: {ref}")
    tech, capacity = project.get("technology"), number(project.get("capacity_mw"))
    if tech == "solar" and capacity is not None and capacity > 1.0:
        solar += 1
    elif tech == "bess" and capacity is not None and capacity > 100.0:
        bess += 1
    else:
        errors.append(f"public project outside exclusive thresholds: {ref}")
check(len(errors) == project_error_start, "all public projects bind exactly to identity registry", f"new_errors={len(errors)-project_error_start}")
check(solar == EXPECTED_SOLAR and bess == EXPECTED_BESS, "derived public thresholds", f"solar={solar} bess={bess}")

items = news.get("items") or []
link_rows = links.get("links") or []
check(news.get("repd_bound") is True, "news REPD-bound")
check(news.get("globalgrid_id_required") is True, "news GlobalGrid-bound")
check(news.get("headline_count") == len(items), "news headline count permits zero", f"metadata={news.get('headline_count')} rows={len(items)}")
check(links.get("schema") == "globalgrid2050.project-news-links.v6", "project-news link schema")
check(links.get("article_count") == len(items), "link article count permits zero")

primary = {}
link_error_start = len(errors)
for link in link_rows:
    article = clean(link.get("gg_article_id"))
    ref = clean(link.get("repd_ref"))
    if ref not in project_refs:
        errors.append(f"news link references ineligible project {article}/{ref}")
    if link.get("role") == "PRIMARY_MATCH":
        if article in primary:
            errors.append(f"multiple PRIMARY_MATCH links: {article}")
        primary[article] = link
        if link.get("eligible_for_news_signal") is not True:
            errors.append(f"primary link cannot drive signal: {article}")
    elif link.get("role") == "RELATED_DEVELOPMENT":
        if link.get("eligible_for_news_signal") is not False:
            errors.append(f"related link drives signal: {article}/{ref}")
    else:
        errors.append(f"invalid project-news role: {link.get('role')}")
check(len(errors) == link_error_start, "all project-news links valid", f"new_errors={len(errors)-link_error_start}")

article_ids = set()
article_error_start = len(errors)
for index, item in enumerate(items):
    article = clean(item.get("gg_article_id"))
    ref = clean(item.get("repd_ref"))
    if not article.startswith("GG2050-NEWS-"):
        errors.append(f"news article {index} has invalid ID: {article}")
    if article in article_ids:
        errors.append(f"duplicate news article ID: {article}")
    article_ids.add(article)
    if ref not in project_refs:
        errors.append(f"news article {index} PRIMARY_MATCH is ineligible: {ref}")
    if ref in by_ref:
        if item.get("gg_project_id") != by_ref[ref].get("gg_project_id"):
            errors.append(f"news article {index} project ID mismatch")
        if item.get("gg_development_id") != by_ref[ref].get("gg_development_id"):
            errors.append(f"news article {index} development ID mismatch")
    if article not in primary or clean(primary[article].get("repd_ref")) != ref:
        errors.append(f"news article {index} lacks exactly one matching primary link")
    evidence = item.get("match_evidence") or {}
    for gate in ("identity_gate_passed", "technology_gate_passed", "foreign_veto_passed", "duplicate_name_gate_passed"):
        if evidence.get(gate) is not True:
            errors.append(f"news article {index} failed persisted {gate}")
    if evidence.get("capacity_only") is not False:
        errors.append(f"news article {index} is capacity-only")
check(len(errors) == article_error_start, "all news articles preserve public match evidence", f"new_errors={len(errors)-article_error_start}")
check(len(primary) == len(items), "one PRIMARY_MATCH per article", f"primary={len(primary)} items={len(items)}")

report = {
    "schema": "globalgrid2050.project-identity-integrity.v6",
    "pass": not errors,
    "validated_at": utc_now(),
    "metrics": {
        "identity_records": len(records),
        "development_groups": len({clean(row.get('gg_development_id')) for row in records}),
        "public_projects": len(project_rows),
        "solar_projects": solar,
        "bess_projects": bess,
        "news_articles": len(items),
        "project_news_links": len(link_rows),
    },
    "checks": checks,
    "errors": errors,
}
REPORT.write_text(json.dumps(report, indent=2), encoding="utf-8")

if errors:
    print(f"PROJECT IDENTITY {OUTPUT_SUFFIX.upper()} FAILED")
    for error in errors[:100]:
        print(" -", error)
    raise SystemExit(1)

print(f"PROJECT IDENTITY {OUTPUT_SUFFIX.upper()} PASS", json.dumps(report["metrics"], sort_keys=True))

GlobalGrid2050 Validate Renewables V5 Integrity

A Python module in the scripts folder that reads Renewable Energy Planning Database (REPD) master, major project news and the REPD register.

ingestglobalgrid2050 / scripts/validate_renewables_v5_integrity.py · lines 1–79 of 79 · Entry point

What it does
It loads REPD master, major project news and the REPD register. Uses libraries pathlib, json, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file repd_master.json; JSON file major_project_news_v5.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Major Project News V5 Workflow (globalgrid2050); 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 Major Project News V5 Workflow and GlobalGrid2050 Repair V5 News Loader Workflow.
Application
globalgrid2050 · scripts · Python module
Uses
pathlib, json, sys
Used by
run by GlobalGrid2050 Major Project News V5 Workflow (workflow run), 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/validate_renewables_v5_integrity.py:1-79 · blob 57a28253062b8ec5f77fa5518067c9afc4a2417f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from pathlib import Path
import json
import sys

ROOT = Path(__file__).resolve().parents[1]
P = ROOT / "uk_renewables_pipeline"
FILES = {
    "v1": P / "dashboard.html",
    "v2": P / "dashboard_v2_2026-08-22.html",
    "v3": P / "dashboard_v3_live_2026-08-22.html",
    "v4": P / "dashboard_v4_live.html",
    "v5": P / "dashboard_v5_live.html",
}

errors = []
texts = {}
sizes = {}
for name, path in FILES.items():
    if not path.exists():
        errors.append(f"missing {name}: {path}")
        continue
    text = path.read_text(encoding="utf-8")
    texts[name] = text
    sizes[name] = len(text.encode("utf-8"))
    if "</html>" not in text.lower():
        errors.append(f"{name} missing closing </html>")

v5 = texts.get("v5", "")
required_v5 = {
    "Chart.js": "cdn.jsdelivr.net/npm/chart.js",
    "REPD master loader": "../dist/repd_master.json",
    "major-news loader": "../dist/major_project_news_v5.json",
    "three gauges": "id=\"g3\"",
    "technology filters": "data-tech=\"Solar\"",
    "status filters": "data-status=\"Operational\"",
    "county filter": "id=\"county\"",
    "site/operator search": "SEARCH OPERATOR OR SITE",
    "REPD table": "id=\"tbody\"",
    "CSV export": "EXPORT CSV",
    "news newspaper": "GLOBALGRID2050 <span>ENERGY DAILY</span>",
    "news signal column": "NEWS SIGNAL",
    "official status label": "REPD STATUS",
    "news/REPD disclaimer": "not REPD-confirmed",
    "mobile layout": "@media(max-width:768px)",
}
for label, token in required_v5.items():
    if token not in v5:
        errors.append(f"V5 missing required feature: {label}")

if "<iframe" in v5.lower():
    errors.append("V5 must be standalone; iframe detected")

# V2 is intentionally a historical iframe wrapper. V3/V4 are the relevant
# standalone predecessors for truncation comparison; V1 is the original full app.
if all(k in sizes for k in ("v1", "v2", "v3", "v4", "v5")):
    standalone_floor = int(min(sizes["v3"], sizes["v4"]) * 0.75)
    if sizes["v5"] < standalone_floor:
        errors.append(
            f"V5 suspiciously small: {sizes['v5']} bytes; "
            f"minimum 75% of smaller standalone V3/V4 = {standalone_floor}"
        )
    if sizes["v5"] <= sizes["v2"]:
        errors.append(
            f"V5 ({sizes['v5']} bytes) is not larger than historical V2 wrapper "
            f"({sizes['v2']} bytes)"
        )

report = {
    "files_bytes": sizes,
    "v2_role": "historical iframe wrapper around V1",
    "standalone_baseline": ["v1", "v3", "v4"],
    "v5_required_features": list(required_v5),
    "errors": errors,
}
print(json.dumps(report, indent=2))
if errors:
    sys.exit(1)
print("V5 integrity PASS: full standalone REPD + newspaper application retained.")

GlobalGrid2050 Validate Renewables V6 Integrity

A Python command-line tool in the scripts folder.

otherglobalgrid2050 / scripts/validate_renewables_v6_integrity.py · lines 1–7 of 7 · Entry point

Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Compatibility entry point for the authoritative V6 scope validator.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · scripts · Python CLI
Uses
GlobalGrid2050 Validate Renewables V6 Scope (import)
Used by
none found
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/validate_renewables_v6_integrity.py:1-7 · blob f04796a2252297c7b9e7fb274e761b5fc0a5febc · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Compatibility entry point for the authoritative V6 scope validator."""
from validate_renewables_v6_scope import main


if __name__ == "__main__":
    main()

GlobalGrid2050 Validate Renewables V6 Scope

A Python command-line tool in the scripts folder that reads renewables integrity, major projects, major project news and Renewable Energy Planning Database (REPD) master, using SHA-256.

storageglobalgrid2050 / scripts/validate_renewables_v6_scope.py · lines 1–367 of 605 · Entry point · pattern git_blob_sha (shared by 3 files)

What it does
It loads renewables integrity, major projects, major project news and REPD master. Defines 9 functions or classes, including clean, norm, number, git_blob_sha, json_sha. Uses libraries __future__, hashlib, json, math, re. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'renewables'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file renewables_v6_integrity.json; JSON file major_projects_v6.json; JSON file major_project_news_v6.json; JSON file repd_master.json; JSON file major_project_news_v5.json; JSON file manifest_v6.json; JSON file repd_source_reconciliation_v6.json; JSON file project_identity_v6_integrity.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Major Project News V6 Workflow (globalgrid2050); GlobalGrid2050 Validate Renewables V6 Integrity (globalgrid2050).
What it achieves
It is built from the clean step (`clean`), the norm step (`norm`) and the number step (`number`). End-to-end V6 release gate, including immutable V1–V5 regression controls. Its code works with 150 MW, 1 MW and 100 MW.
Why it matters
Imported by GlobalGrid2050 Validate Renewables V6 Integrity. Run by GlobalGrid2050 Major Project News V6 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
GlobalGrid2050 Major Project News V6 (import), __future__, hashlib, json, math, re, collections, datetime, pathlib
Used by
run by GlobalGrid2050 Major Project News V6 Workflow (workflow run), imported by GlobalGrid2050 Validate Renewables V6 Integrity (import)
Produces
clean, norm, number, git_blob_sha, json_sha, main
Defines here
clean, norm, number, git_blob_sha, json_sha, main, check, load
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/validate_renewables_v6_scope.py:1-367 · blob 87e8b6cb2e52cb821ce1efbb94da309ba52cb238 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""End-to-end V6 release gate, including immutable V1–V5 regression controls."""
from __future__ import annotations

import hashlib
import json
import math
import re
from collections import Counter
from datetime import datetime, timedelta, timezone
from pathlib import Path
from urllib.parse import urlparse

ROOT = Path(__file__).resolve().parents[1]
PIPE = ROOT / "uk_renewables_pipeline"
DIST = ROOT / "dist"
REPORT = DIST / "renewables_v6_integrity.json"

FILES = {
    "v1": PIPE / "dashboard.html",
    "v2": PIPE / "dashboard_v2_2026-08-22.html",
    "v3": PIPE / "dashboard_v3_live_2026-08-22.html",
    "v4": PIPE / "dashboard_v4_live.html",
    "v5": PIPE / "dashboard_v5_live.html",
    "v6": PIPE / "dashboard_v6_live.html",
}
BASELINE_BLOBS = {
    "v1": "e2d99e37d6388d3f498a79696773238ad689574b",
    "v2": "cb953a67332d3d29355945fb58a513e30c681013",
    "v3": "911921e7aa254f0bfdecc122d975cc0e3af130c7",
    "v4": "f356b37b1c6202150f3a5bb404a57ee329212f70",
    "v5": "ac33daf67dba8951527b06761ab587003a19f60e",
}

EXPECTED_ROWS = 14657
EXPECTED_SOLAR = 3445
EXPECTED_BESS = 269
EXPECTED_PROJECTS = EXPECTED_SOLAR + EXPECTED_BESS
EXPECTED_CSV_SHA = "84c1b5f958a934d8b4b86ec88f50bdcf43830ded7ff2efc27bffca0c98695035"
EXPECTED_XLSX_SHA = "624a0a9712c58a7a93716e51f2bf054eec8b1af7170f6f9516cc10cd248e2657"
MIN_CONFIDENCE = 68
PRIORITY_SOURCES = {
    "DESNZ / GOV.UK",
    "Planning Inspectorate",
    "BBC",
    "Solar Power Portal",
    "Energy-Storage.News",
    "PV Magazine",
}
FOREIGN_PHRASES = {
    "new jersey", "california", "texas", "australia", "new south wales", "queensland",
    "canada", "alberta", "ontario canada", "germany", "italy", "spain", "india", "china",
    "south africa", "new zealand", "republic of ireland", "irish republic", "united states",
    "u s roundup", "new york", "arizona", "nevada", "florida", "ohio", "virginia",
    "massachusetts", "pennsylvania", "colorado",
}
KNOWN_BAD = {
    "forest healthcare", "evolution mining", "new jersey board of public utilities",
}


def clean(value):
    return str(value or "").strip()


def norm(value):
    return re.sub(r"\s+", " ", re.sub(r"[^a-z0-9]+", " ", clean(value).lower())).strip()


def number(value):
    try:
        result = float(value)
        return result if math.isfinite(result) else None
    except Exception:
        return None


def git_blob_sha(path):
    data = path.read_bytes()
    return hashlib.sha1(b"blob " + str(len(data)).encode("ascii") + b"\0" + data).hexdigest()


def json_sha(value):
    encoded = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()


def main():
    errors, checks = [], []

    def check(condition, gate, detail=""):
        passed = bool(condition)
        checks.append({"gate": gate, "pass": passed, "detail": detail})
        if not passed:
            errors.append(f"{gate}: {detail}" if detail else gate)

    def load(path):
        try:
            return json.loads(path.read_text(encoding="utf-8"))
        except Exception as exc:
            errors.append(f"cannot load {path.relative_to(ROOT)}: {exc}")
            return {}

    # Immutable lineage and semantic frontend structure.
    texts = {}
    for version, path in FILES.items():
        check(path.exists(), f"{version} exists", str(path.relative_to(ROOT)))
        if not path.exists():
            continue
        text = path.read_text(encoding="utf-8")
        texts[version] = text
        check("</html>" in text.lower(), f"{version} closes HTML")
        if version in BASELINE_BLOBS:
            actual = git_blob_sha(path)
            check(actual == BASELINE_BLOBS[version], f"{version} immutable blob", actual)

    v6 = texts.get("v6", "")
    required_frontend = {
        "same-origin project snapshot": "../dist/major_projects_v6.json",
        "same-origin news snapshot": "../dist/major_project_news_v6.json",
        "Chart.js": "cdn.jsdelivr.net/npm/chart.js",
        "newspaper": "ENERGY DAILY",
        "news filters": 'data-mode="FINANCE"',
        "news search": 'id="newsSearch"',
        "three gauges": 'id="g3"',
        "asset filters": 'id="tech"',
        "status filter": 'id="state"',
        "geography filter": 'id="county"',
        "asset search": 'id="assetSearch"',
        "project table": 'id="tbody"',
        "CSV export": 'id="export"',
        "mobile CSV export": 'id="exportMobile"',
        "GlobalGrid project ID": "GLOBALGRID PROJECT ID",
        "GlobalGrid development ID": "GLOBALGRID DEVELOPMENT ID",
        "REPD Ref": "REPD REF",
        "REPD record update": "REPD UPDATED",
        "official status": "REPD STATUS",
        "separate news signal": "NEWS SIGNAL",
        "official missing date": "not supplied by REPD",
        "mobile layout": "@media(max-width:768px)",
        "official portal": "https://www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract",
    }
    for label, token in required_frontend.items():
        check(token in v6, f"V6 frontend: {label}", token)
    for version_path in (
        "dashboard.html", "dashboard_v2_2026-08-22.html", "dashboard_v3_live_2026-08-22.html",
        "dashboard_v4_live.html", "dashboard_v5_live.html",
    ):
        check(version_path in v6, "V6 version lineage", version_path)
    lower_v6 = v6.lower()
    check("<iframe" not in lower_v6, "V6 is standalone")
    check("papaparse" not in lower_v6 and "papa.parse" not in lower_v6, "no browser CSV parser")
    check("assets.publishing.service.gov.uk" not in lower_v6, "no government asset runtime dependency")
    check("../dist/repd_master.json" not in v6, "no shared V1–V5 master loader")
    check("../dist/major_project_news_v5.json" not in v6, "no V5 news fallback")

    homepage = (ROOT / "index.html").read_text(encoding="utf-8")
    check(
        "LIVE · DESNZ Q2 2026 validated snapshot · solar >1MW · BESS >100MW · canonical GlobalGrid/REPD IDs" in homepage,
        "homepage V6 snapshot wording",
    )

    manifest = load(DIST / "manifest_v6.json")
    source = load(DIST / "repd_source_reconciliation_v6.json")
    identity_integrity = load(DIST / "project_identity_v6_integrity.json")
    source_metrics = source.get("metrics") or {}
    source_hashes = source.get("source_hashes") or {}
    check(manifest.get("schema") == "globalgrid2050.repd-manifest.v6" and manifest.get("status") == "VALIDATED", "validated V6 manifest")
    check(source.get("pass") is True and source_metrics.get("material_mismatches") == 0, "CSV/XLSX reconciliation passed")
    check(source_metrics.get("csv_rows") == EXPECTED_ROWS == source_metrics.get("xlsx_rows"), "official source row counts exact")
    check(source_metrics.get("csv_unique_refs") == EXPECTED_ROWS == source_metrics.get("xlsx_unique_refs"), "official unique Ref counts exact")
    check(source_metrics.get("canonical_solar_gt1") == EXPECTED_SOLAR, "canonical solar count exact")
    check(source_metrics.get("canonical_bess_gt100") == EXPECTED_BESS, "canonical BESS count exact")
    check(source_hashes.get("csv_sha256") == EXPECTED_CSV_SHA, "official Q2 CSV hash exact")
    check(source_hashes.get("xlsx_sha256") == EXPECTED_XLSX_SHA, "official Q2 XLSX hash exact")
    check(manifest.get("source_hashes") == source_hashes, "manifest/source hashes agree")
    check(identity_integrity.get("pass") is True, "identity integrity report passed", str(identity_integrity.get("errors") or []))

    projects = load(DIST / "major_projects_v6.json")
    rows = projects.get("projects") or []
    check(projects.get("schema") == "globalgrid2050.major-projects.v6", "V6 public project schema")
    check(projects.get("repd_bound") is True and projects.get("globalgrid_id_required") is True, "V6 canonical identity policy")
    check(projects.get("csv_xlsx_reconciled") is True, "V6 snapshot declares source reconciliation")
    check(projects.get("source_record_count") == EXPECTED_ROWS == projects.get("source_unique_ref_count"), "V6 source metadata exact")
    check(projects.get("project_count") == EXPECTED_PROJECTS == projects.get("count") == len(rows), "V6 project quantity exact", f"metadata={projects.get('project_count')} rows={len(rows)}")
    check(projects.get("solar_count") == EXPECTED_SOLAR, "V6 solar metadata exact")
    check(projects.get("bess_count") == EXPECTED_BESS, "V6 BESS metadata exact")
    check((projects.get("thresholds") or {}).get("solar_mw_exclusive") == 1.0, "V6 solar threshold exclusive")
    check((projects.get("thresholds") or {}).get("bess_mw_exclusive") == 100.0, "V6 BESS threshold exclusive")
    check(projects.get("source_hashes") == source_hashes, "V6 snapshot/source hashes agree")
    check(projects.get("projects_sha256") == json_sha(rows), "V6 project array SHA-256 exact")
    snapshot_meta = manifest.get("public_snapshot") or {}
    check(snapshot_meta.get("project_count") == EXPECTED_PROJECTS, "manifest public project count exact")
    check(snapshot_meta.get("projects_sha256") == projects.get("projects_sha256"), "manifest/public project hash exact")

    by_ref, gg_ids = {}, set()
    project_errors = []
    solar = bess = updates = 0
    for index, row in enumerate(rows):
        ref, gg, development = clean(row.get("repd_ref")), clean(row.get("gg_project_id")), clean(row.get("gg_development_id"))
        capacity, technology = number(row.get("capacity_mw")), clean(row.get("technology"))
        if not ref or ref in by_ref:
            project_errors.append(f"row {index} missing/duplicate REPD Ref {ref!r}")
        if gg != f"GG2050-REPD-{ref}" or gg in gg_ids:
            project_errors.append(f"row {index} invalid/duplicate GlobalGrid ID {gg!r}")
        if not development.startswith("GG2050-DEV-"):
            project_errors.append(f"row {index} missing development ID")
        if row.get("identity_status") != "REPD_BOUND":
            project_errors.append(f"row {index} is not REPD_BOUND")
        if row.get("capacity_known") is not True or capacity is None:
            project_errors.append(f"row {index} has unknown capacity in threshold universe")
        elif technology == "solar" and capacity > 1.0:
            solar += 1
        elif technology == "bess" and capacity > 100.0:
            bess += 1
        else:
            project_errors.append(f"row {index} fails its exclusive technology threshold")
        if not clean(row.get("name")) or not clean(row.get("status")):
            project_errors.append(f"row {index} lacks required official name/status")
        updated = row.get("repd_record_updated")
        if updated:
            if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", clean(updated)):
                project_errors.append(f"row {index} invalid REPD update date")
            else:
                updates += 1
        for date_field in (
            "planning_application_submitted", "planning_application_withdrawn", "planning_permission_refused",
            "planning_permission_granted", "planning_permission_expired", "under_construction", "operational",
        ):
            value = row.get(date_field)
            if value and not re.fullmatch(r"\d{4}-\d{2}-\d{2}", clean(value)):
                project_errors.append(f"row {index} invalid official date {date_field}")
        by_ref[ref], _ = row, gg_ids.add(gg)
    check(not project_errors, "every V6 project is canonical and threshold-qualified", "; ".join(project_errors[:10]))
    check(solar == EXPECTED_SOLAR and bess == EXPECTED_BESS, "V6 derived threshold counts", f"solar={solar} bess={bess}")
    check(projects.get("record_update_supplied_count") == updates, "REPD supplied-update metadata exact")
    check(projects.get("record_update_missing_count") == len(rows) - updates, "REPD missing-update metadata exact")

    news = load(DIST / "major_project_news_v6.json")
    items = news.get("items") or []
    telemetry = news.get("telemetry") or {}
    check(news.get("schema") == "globalgrid2050.major-project-news.v6", "V6 news schema")
    check(news.get("repd_bound") is True and news.get("globalgrid_id_required") is True, "V6 news canonical identity policy")
    check(news.get("eligible_projects") == EXPECTED_PROJECTS, "news eligible project count exact")
    check(news.get("eligible_solar") == EXPECTED_SOLAR and news.get("eligible_bess") == EXPECTED_BESS, "news eligible technology counts exact")
    check(news.get("headline_count") == len(items), "news headline count permits a valid zero", f"metadata={news.get('headline_count')} items={len(items)}")
    check(news.get("news_horizon_days") == 183 and news.get("lookback_days") == 183, "news horizon exact")
    check(PRIORITY_SOURCES.issubset(set(news.get("priority_sources") or [])), "priority public sources configured")
    check(telemetry.get("source_first") is True, "source-first crawl executed")
    configured = telemetry.get("queries_configured")
    check(isinstance(configured, int) and configured > 0, "news queries configured/executed", str(configured))
    for metric in (
        "queries_completed", "queries_failed_or_cancelled", "rss_candidates_returned",
        "deduplicated_article_candidates", "articles_accepted_before_limit", "articles_published",
        "articles_rejected", "articles_ambiguous", "articles_dropped_by_headline_limit",
    ):
        value = telemetry.get(metric)
        check(isinstance(value, int) and value >= 0, f"news telemetry {metric} recorded", str(value))
    check(telemetry.get("articles_published") == len(items), "telemetry accepted count exact")
    check(news.get("raw_story_count") == telemetry.get("deduplicated_article_candidates"), "candidate count exposed")
    check(news.get("rejected_candidates") == telemetry.get("articles_rejected"), "rejected count exposed")
    check(news.get("ambiguous_candidates") == telemetry.get("articles_ambiguous"), "ambiguous count exposed")
    check(telemetry.get("zero_accepted_is_valid") is True, "quiet-period policy explicit")

    # Discovery coverage must advance from persisted state, not wall-clock
    # timing.  The explicit indexes make every rotation independently auditable.
    query_plan = telemetry.get("query_plan") or {}
    selected = query_plan.get("solar_targeted_batches_selected")
    total_batches = query_plan.get("solar_targeted_batches_total")
    cursor_start = query_plan.get("solar_rotation_cursor_start")
    cursor_next = query_plan.get("solar_rotation_cursor_next")
    cursor_source = query_plan.get("solar_rotation_cursor_source")
    full_sweep_runs = query_plan.get("solar_rotation_full_sweep_runs")
    batch_indexes = query_plan.get("solar_targeted_batch_indexes")
    cursor_planned_next = query_plan.get("solar_rotation_cursor_planned_next")
    cursor_advanced = query_plan.get("solar_rotation_advance_applied")
    cursor_advance_reason = query_plan.get("solar_rotation_advance_reason")
    cursor_values_valid = all(
        isinstance(value, int) and not isinstance(value, bool)
        for value in (selected, total_batches, cursor_start, cursor_next, full_sweep_runs)
    )
    check(cursor_values_valid, "persisted solar rotation metadata typed")
    if cursor_values_valid and total_batches > 0 and selected > 0:
        expected_indexes = [(cursor_start + offset) % total_batches for offset in range(selected)]
        check(0 < selected <= total_batches, "solar rotation selects a bounded non-empty window")
        check(batch_indexes == expected_indexes, "solar rotation indexes are consecutive and auditable")
        expected_next = (cursor_start + selected) % total_batches
        check(cursor_planned_next == expected_next, "solar rotation planned cursor is deterministic")
        solar_execution = (telemetry.get("query_execution") or {}).get("solar_targeted_backstop") or {}
        all_queries_completed = (
            solar_execution.get("configured") == selected
            and solar_execution.get("completed") == selected
            and solar_execution.get("failed") == 0
        )
        check(cursor_advanced is all_queries_completed, "solar rotation advances only after a complete crawl")
        check(
            cursor_next == (expected_next if all_queries_completed else cursor_start),
            "solar rotation persists the next complete or retry window",
        )
        check(
            cursor_advance_reason
            == (
                "all_selected_solar_queries_completed"
                if all_queries_completed
                else "incomplete_solar_query_execution_retry_window"
            ),
            "solar rotation advance reason explicit",
        )
        check(full_sweep_runs == math.ceil(total_batches / selected), "solar rotation full-sweep bound exact")
    else:
        check(False, "solar rotation has a non-empty Q2 solar universe")
    check(
        cursor_source in {
            "initial_zero", "previous_v6_news_telemetry", "query_universe_changed_reset_zero"
        },
        "solar rotation cursor source explicit",
        clean(cursor_source),
    )
    check(
        query_plan.get("targeted_name_strategy")
        == "distinctive public name stem with official REPD-name fallback",
        "targeted discovery uses press-compatible distinctive project names",
    )

    # Fresh-crawl decisions and retained-story decisions are separate.  These
    # equations prevent a rotating batch from silently replacing the newspaper.
    fresh_candidates = telemetry.get("deduplicated_article_candidates")
    fresh_accepted = telemetry.get("articles_accepted_before_limit")
    fresh_rejected = telemetry.get("articles_rejected")
    if all(isinstance(value, int) and value >= 0 for value in (fresh_candidates, fresh_accepted, fresh_rejected)):
        check(fresh_candidates == fresh_accepted + fresh_rejected, "fresh candidate accounting exact")
    previous_considered = telemetry.get("previous_articles_considered")
    previous_revalidated = telemetry.get("previous_articles_revalidated")
    previous_carried = telemetry.get("previous_articles_carried_forward")
    previous_dropped = telemetry.get("previous_articles_dropped")
    fresh_published = telemetry.get("fresh_articles_published")
    retention_counts = (previous_considered, previous_revalidated, previous_carried, previous_dropped, fresh_published)
    check(all(isinstance(value, int) and value >= 0 for value in retention_counts), "retained-story telemetry typed")
    if all(isinstance(value, int) and value >= 0 for value in retention_counts):
        check(previous_considered == previous_revalidated + previous_dropped, "previous-story revalidation accounting exact")
        check(previous_carried <= previous_revalidated, "only revalidated stories are carried forward")
        check(telemetry.get("articles_published") == fresh_published + previous_carried, "final newspaper union accounting exact")
    drop_reasons = telemetry.get("previous_article_drop_reasons")
    check(isinstance(drop_reasons, dict), "previous-story drop reasons recorded")
    if isinstance(drop_reasons, dict) and isinstance(previous_dropped, int):
        check(
            all(isinstance(value, int) and value >= 0 for value in drop_reasons.values())
            and sum(drop_reasons.values()) == previous_dropped,
            "previous-story drop reason totals exact",
        )
    retention_detail = telemetry.get("story_retention") or {}
    check(
        retention_detail.get("previous_artifact_status")
        in {"accepted_same_project_snapshot", "not_available_or_invalid", "project_snapshot_mismatch"},
        "previous news artifact is project-snapshot bound",
    )

    # Rejections remain inspectable without retaining article bodies or URLs.
    rejection_reasons = telemetry.get("rejection_reasons")
    pair_reasons = telemetry.get("pair_rejection_reasons")
    rejected_samples = telemetry.get("rejected_article_samples")
    sample_limit = telemetry.get("rejected_article_sample_limit")
    check(isinstance(rejection_reasons, dict), "article rejection reasons recorded")
    if isinstance(rejection_reasons, dict) and isinstance(fresh_rejected, int):
        check(
            all(isinstance(value, int) and value >= 0 for value in rejection_reasons.values())
            and sum(rejection_reasons.values()) == fresh_rejected,