GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Verify Published Versions and 2 more files

A Python command-line tool in the scripts folder that fetches homepage catalogue, using SHA-256 from GitHub API and the PipelineNews and GridAtlas repositories.

700 lines of Python from globalgrid2050, in 3 files. Topic: Automation and CI. Section 1788 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 Renewables V6 Scope storage · globalgrid2050 / scripts/validate_renewables_v6_scope.py lines 368–605
  2. GlobalGrid2050 Validate V6 Manifest Provenance ingest · globalgrid2050 / scripts/validate_v6_manifest_provenance.py lines 1–78
  3. GlobalGrid2050 Verify Published Versions storage · globalgrid2050 / scripts/verify_published_versions.py lines 1–384

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 368–605 of 605 (continued from section 1787) · 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
fixture_story
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:368-605 · 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
            "article rejection reason totals exact",
        )
    check(isinstance(pair_reasons, dict), "project-pair rejection reasons recorded")
    if isinstance(pair_reasons, dict) and isinstance(fresh_candidates, int):
        identity_pairs = telemetry.get("identity_candidate_pairs")
        check(
            isinstance(identity_pairs, int)
            and all(isinstance(value, int) and value >= 0 for value in pair_reasons.values())
            and sum(pair_reasons.values()) + identity_pairs == fresh_candidates * EXPECTED_PROJECTS,
            "all fresh project/article pair outcomes accounted",
        )
    check(sample_limit == 50 and isinstance(rejected_samples, list), "bounded rejected-article audit samples configured")
    sample_errors = []
    allowed_sample_keys = {
        "title", "source", "published", "resolution", "identity_candidates",
        "qualified_candidates", "top_score", "pair_reasons",
    }
    if isinstance(rejected_samples, list):
        expected_sample_count = (
            min(sample_limit, fresh_rejected)
            if isinstance(sample_limit, int) and isinstance(fresh_rejected, int) and fresh_rejected >= 0
            else -1
        )
        if len(rejected_samples) != expected_sample_count:
            sample_errors.append("sample count does not equal bounded rejected count")
        for sample_index, sample in enumerate(rejected_samples):
            if not isinstance(sample, dict) or set(sample) != allowed_sample_keys:
                sample_errors.append(f"sample {sample_index} has unsafe/unexpected keys")
                continue
            if sample.get("resolution") not in (rejection_reasons or {}):
                sample_errors.append(f"sample {sample_index} resolution is not aggregated")
            sample_pair_reasons = sample.get("pair_reasons")
            valid_pair_counts = isinstance(sample_pair_reasons, dict) and all(
                isinstance(value, int) and value >= 0 for value in sample_pair_reasons.values()
            )
            if not valid_pair_counts or sum(sample_pair_reasons.values()) != EXPECTED_PROJECTS:
                sample_errors.append(f"sample {sample_index} pair outcomes are incomplete")
    check(not sample_errors, "rejected-article samples are bounded, public and complete", "; ".join(sample_errors[:10]))
    source_telemetry = {clean(row.get("name")): row for row in telemetry.get("queried_sources") or []}
    for source_name in PRIORITY_SOURCES:
        row = source_telemetry.get(source_name) or {}
        check(int(row.get("configured", 0)) > 0, f"priority source queried: {source_name}")
        check(int(row.get("completed", 0)) + int(row.get("failed", 0)) > 0, f"priority source attempt recorded: {source_name}")

    try:
        edition_time = datetime.fromisoformat(clean(news.get("updated")).replace("Z", "+00:00"))
        edition_time = edition_time if edition_time.tzinfo else edition_time.replace(tzinfo=timezone.utc)
    except Exception:
        edition_time = datetime.now(timezone.utc)
        errors.append(f"news updated timestamp invalid: {news.get('updated')!r}")
    cutoff, latest = edition_time.date() - timedelta(days=183), edition_time.date() + timedelta(days=1)
    article_ids, article_errors = set(), []
    for index, item in enumerate(items):
        ref, article_id = clean(item.get("repd_ref")), clean(item.get("gg_article_id"))
        project = by_ref.get(ref)
        if not project:
            article_errors.append(f"article {index} references ineligible REPD {ref}")
            continue
        if not article_id.startswith("GG2050-NEWS-") or article_id in article_ids:
            article_errors.append(f"article {index} invalid/duplicate article ID")
        article_ids.add(article_id)
        if item.get("role") != "PRIMARY_MATCH" or item.get("eligible_for_news_signal") is not True:
            article_errors.append(f"article {index} is not its one eligible PRIMARY_MATCH")
        if item.get("gg_project_id") != project.get("gg_project_id") or item.get("gg_development_id") != project.get("gg_development_id"):
            article_errors.append(f"article {index} canonical identity mismatch")
        if item.get("status") != project.get("status"):
            article_errors.append(f"article {index} overwrites official REPD status")
        if number(item.get("capacity_mw")) != number(project.get("capacity_mw")):
            article_errors.append(f"article {index} overwrites official REPD capacity")
        if item.get("repd_record_updated") != project.get("repd_record_updated"):
            article_errors.append(f"article {index} overwrites official REPD update date")
        if clean(item.get("technology")) != clean(project.get("technology")):
            article_errors.append(f"article {index} technology binding mismatch")
        parsed_url = urlparse(clean(item.get("url")))
        if parsed_url.scheme not in {"http", "https"} or not parsed_url.netloc:
            article_errors.append(f"article {index} URL invalid")
        try:
            published = datetime.fromisoformat(clean(item.get("published"))).date()
            if not cutoff <= published <= latest:
                article_errors.append(f"article {index} outside news horizon")
        except Exception:
            article_errors.append(f"article {index} publication date invalid")
        confidence = number(item.get("confidence"))
        if confidence is None or not MIN_CONFIDENCE <= confidence <= 100:
            article_errors.append(f"article {index} confidence below threshold")
        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:
                article_errors.append(f"article {index} missing passed {gate}")
        if evidence.get("capacity_only") is not False or evidence.get("capacity_is_corroboration_only") is not True:
            article_errors.append(f"article {index} treats capacity as identity")
        anchors = set(evidence.get("anchors") or [])
        if not anchors & {"planning_reference", "exact_project_name_in_headline", "exact_project_name", "distinctive_name_variant", "distinctive_project_name_tokens"}:
            article_errors.append(f"article {index} lacks a public identity anchor")
        literal_technology = evidence.get("technology_context_hit") is True
        inferred_technology = evidence.get("technology_context_inferred") is True
        if not (literal_technology or inferred_technology):
            article_errors.append(f"article {index} has no literal or safely inferred technology context")
        if inferred_technology and "technology_context_inferred_from_source_and_identity" not in anchors:
            article_errors.append(f"article {index} omits its inferred-technology audit anchor")
        if inferred_technology and evidence.get("official_source") is not True:
            article_errors.append(f"article {index} infers technology from a non-authoritative source")
        story_context = norm(" ".join((clean(item.get("headline")), clean(item.get("source")), clean(item.get("source_url")))))
        project_context = norm(" ".join(clean(project.get(key)) for key in ("name", "country", "county", "region", "planning_authority", "planning_application_reference")))
        leaked = [phrase for phrase in FOREIGN_PHRASES if phrase in story_context and phrase not in project_context]
        if leaked:
            article_errors.append(f"article {index} foreign-location leakage: {leaked}")
        bad = [phrase for phrase in KNOWN_BAD if phrase in story_context]
        if bad:
            article_errors.append(f"article {index} known false-positive class: {bad}")
    check(not article_errors, "all accepted news passes identity/technology/foreign/quality gates", "; ".join(article_errors[:10]))

    # Offline matcher fixtures guard the coverage repair while retaining the
    # V6 false-positive controls.  They use only the committed public snapshot.
    fixture_errors = []
    try:
        import major_project_news_v6 as matcher

        _fixture_snapshot, fixture_projects = matcher.load_project_snapshot()
        fixture_now = datetime.now(timezone.utc)

        def fixture_story(title, source, source_url):
            return {
                "title": title, "description": "", "source": source,
                "source_url": source_url, "link": "https://example.test/v6-fixture",
                "published": fixture_now,
            }

        positives = (
            ("DESNZ grants DCO for 150MW Dean Moor solar project in Cumbria", "GOV.UK", "https://www.gov.uk", "14550"),
            ("One Earth development consent decision announced", "GOV.UK", "https://www.gov.uk", "14806"),
            ("Longhedge solar project begins construction in Nottinghamshire", "reNEWS", "https://renews.biz", "11063"),
        )
        for title, source_name, source_url, expected_ref in positives:
            matched, resolution, _detail = matcher._resolve_story(
                fixture_story(title, source_name, source_url), fixture_projects
            )
            if matched is None or matched.get("repd_ref") != expected_ref:
                fixture_errors.append(f"true-positive fixture {expected_ref} resolved as {resolution}/{matched and matched.get('repd_ref')}")

        negatives = (
            ("New Jersey Board of Public Utilities releases 150MW BTM energy storage proposal", "Energy-Storage.News", "https://energy-storage.news"),
            ("Capital Dynamics acquires 170MW/680MWh BESS in County Kerry, Ireland", "Solar Power Portal", "https://solarpowerportal.co.uk"),
            ("The Grange celebrates Forest Healthcare's National Care Award", "BBC", "https://bbc.co.uk"),
            ("150MW battery storage project secures financing", "Energy-Storage.News", "https://energy-storage.news"),
            ("One Earth solar project announces an update", "Example News", "https://example.com"),
            ("Approval for East Yorkshire offshore wind farm substation", "BBC", "https://www.bbc.co.uk"),
            ("Fire crew still at significant Avonmouth recycling centre fire", "BBC", "https://www.bbc.co.uk"),
            ("Construction to start on improvements to Witney High Street", "Oxfordshire County Council", "https://news.oxfordshire.gov.uk"),
        )
        for title, source_name, source_url in negatives:
            matched, resolution, _detail = matcher._resolve_story(
                fixture_story(title, source_name, source_url), fixture_projects
            )
            if matched is not None:
                fixture_errors.append(f"known false-positive fixture matched REPD {matched.get('repd_ref')}: {title}")
    except Exception as exc:
        fixture_errors.append(f"fixture replay raised {type(exc).__name__}: {exc}")
    check(not fixture_errors, "offline news matcher true/false-positive fixtures", "; ".join(fixture_errors))

    links = load(DIST / "project_news_links_v6.json")
    link_rows = links.get("links") or []
    check(links.get("schema") == "globalgrid2050.project-news-links.v6", "project-news relationship schema")
    check(links.get("article_count") == len(items), "relationship article count permits zero")
    check(links.get("link_count") == len(link_rows), "relationship link count exact")
    check(links.get("primary_link_count") == len(items), "relationship metadata has exactly one primary per article")
    check(
        links.get("related_development_link_count")
        == sum(link.get("role") == "RELATED_DEVELOPMENT" for link in link_rows),
        "relationship related-link metadata exact",
    )
    link_rules = links.get("rules") or {}
    check(
        link_rules.get("one_primary_match_per_article") is True
        and link_rules.get("primary_match_drives_news_signal") is True
        and link_rules.get("related_development_drives_news_signal") is False,
        "relationship NEWS SIGNAL policy explicit",
    )
    primary_counts, link_errors = Counter(), []
    for link in link_rows:
        article_id, ref, role = clean(link.get("gg_article_id")), clean(link.get("repd_ref")), clean(link.get("role"))
        project = by_ref.get(ref)
        if article_id not in article_ids or not project:
            link_errors.append(f"link references unknown article/project {article_id}/{ref}")
            continue
        if link.get("gg_project_id") != project.get("gg_project_id") or link.get("gg_development_id") != project.get("gg_development_id"):
            link_errors.append(f"link identity mismatch {article_id}/{ref}")
        if role == "PRIMARY_MATCH":
            primary_counts[article_id] += 1
            if link.get("eligible_for_news_signal") is not True:
                link_errors.append(f"primary link signal false {article_id}")
        elif role == "RELATED_DEVELOPMENT":
            if link.get("eligible_for_news_signal") is not False:
                link_errors.append(f"related link drives signal {article_id}/{ref}")
        else:
            link_errors.append(f"unsupported link role {role}")
    if any(primary_counts[article_id] != 1 for article_id in article_ids):
        link_errors.append("one or more articles does not have exactly one PRIMARY_MATCH")
    check(not link_errors, "all project-news relationships valid", "; ".join(link_errors[:10]))

    combined_public = json.dumps({"projects": projects, "news": news, "links": links}, ensure_ascii=False).lower()
    for forbidden in ("private_relationship", "relationship_score", "visit_priority", "commercial_priority", "personal_email"):
        check(forbidden not in combined_public, f"no private field: {forbidden}")

    report = {
        "schema": "globalgrid2050.renewables-v6-integrity.v6",
        "pass": not errors,
        "validated_at": datetime.now(timezone.utc).isoformat(),
        "metrics": {
            "source_records": EXPECTED_ROWS,
            "source_unique_refs": EXPECTED_ROWS,
            "public_projects": len(rows),
            "solar_projects": solar,
            "bess_projects": bess,
            "record_updates_supplied": updates,
            "record_updates_missing": len(rows) - updates,
            "news_candidates": telemetry.get("deduplicated_article_candidates"),
            "news_accepted": len(items),
            "news_rejected": telemetry.get("articles_rejected"),
            "news_ambiguous": telemetry.get("articles_ambiguous"),
            "news_retained": telemetry.get("previous_articles_carried_forward"),
            "solar_rotation_cursor_next": query_plan.get("solar_rotation_cursor_next"),
            "project_news_links": len(link_rows),
        },
        "checks": checks,
        "errors": errors,
    }
    REPORT.write_text(json.dumps(report, indent=2), encoding="utf-8")
    if errors:
        print("V6 AGREED-SCOPE VALIDATION FAILED")
        for error in errors[:150]:
            print(" -", error)
        raise SystemExit(1)
    print("V6 AGREED-SCOPE VALIDATION PASS", json.dumps(report["metrics"], sort_keys=True))


if __name__ == "__main__":
    main()

GlobalGrid2050 Validate V6 Manifest Provenance

A Python module in the scripts folder that reads solar and battery storage (BESS). It is built from the need step (`need`) and the load step (`load`).

ingestglobalgrid2050 / scripts/validate_v6_manifest_provenance.py · lines 1–78 of 78 · Entry point

What it does
It loads solar and battery storage (BESS). Defines need, load. Uses libraries __future__, json, pathlib, urllib.parse. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: solar, battery storage (BESS).
Downstream impact
Used directly by 1 file: GlobalGrid2050 Major Project News V6 Workflow (globalgrid2050).
What it achieves
Validate that V6 is bound to the reconciled, immutable Q2 2026 release.
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__, json, pathlib, urllib.parse
Used by
run by GlobalGrid2050 Major Project News V6 Workflow (workflow run)
Produces
need, load
Defines here
need, 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_v6_manifest_provenance.py:1-78 · blob 415af70d2129ac6042c4c9a82143d373035e3fba · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""Validate that V6 is bound to the reconciled, immutable Q2 2026 release."""
from __future__ import annotations

import json
from pathlib import Path
from urllib.parse import urlparse

from repd_sources_v6 import (
    CSV_URL,
    EXPECTED_BESS_GT100,
    EXPECTED_CSV_SHA256,
    EXPECTED_ROWS,
    EXPECTED_SOLAR_GT1,
    EXPECTED_UNIQUE_REFS,
    EXPECTED_XLSX_SHA256,
    MANIFEST,
    PUBLICATION_DATE,
    QUARTER_LABEL,
    REPORT,
    SOURCE_PAGE,
    XLSX_URL,
)

errors = []


def need(condition, message):
    if not condition:
        errors.append(message)


def load(path: Path):
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception as exc:
        raise RuntimeError(f"Cannot read {path}: {exc}") from exc


manifest = load(MANIFEST)
source = load(REPORT)
metrics = source.get("metrics") or {}
hashes = source.get("source_hashes") or {}

need(manifest.get("schema") == "globalgrid2050.repd-manifest.v6", "V6 manifest schema mismatch")
need(manifest.get("status") == "VALIDATED", "V6 manifest is not validated")
need(source.get("pass") is True, "CSV/XLSX reconciliation did not pass")
need(manifest.get("source_owner") == "Department for Energy Security and Net Zero (DESNZ)", "DESNZ owner missing")
need(manifest.get("source_page") == SOURCE_PAGE, "official publication page mismatch")
need(manifest.get("source_page_last_updated") == PUBLICATION_DATE, f"{QUARTER_LABEL} publication date mismatch")
need(manifest.get("source_url") == CSV_URL == source.get("csv_url"), "official CSV URL mismatch")
need(manifest.get("source_excel_url") == XLSX_URL == source.get("xlsx_url"), "official XLSX URL mismatch")
need(urlparse(CSV_URL).netloc == "assets.publishing.service.gov.uk", "official CSV host mismatch")
need(urlparse(XLSX_URL).netloc == "assets.publishing.service.gov.uk", "official XLSX host mismatch")
need(hashes.get("csv_sha256") == EXPECTED_CSV_SHA256, "official CSV hash mismatch")
need(hashes.get("xlsx_sha256") == EXPECTED_XLSX_SHA256, "official XLSX hash mismatch")
need(manifest.get("source_hashes") == hashes, "manifest/source-report hashes differ")
need(metrics.get("csv_rows") == EXPECTED_ROWS, "CSV row count mismatch")
need(metrics.get("xlsx_rows") == EXPECTED_ROWS, "XLSX row count mismatch")
need(metrics.get("csv_unique_refs") == EXPECTED_UNIQUE_REFS, "CSV unique Ref count mismatch")
need(metrics.get("xlsx_unique_refs") == EXPECTED_UNIQUE_REFS, "XLSX unique Ref count mismatch")
need(metrics.get("material_mismatches") == 0, "material CSV/XLSX mismatch present")
need(metrics.get("canonical_solar_gt1") == EXPECTED_SOLAR_GT1, "canonical solar count mismatch")
need(metrics.get("canonical_bess_gt100") == EXPECTED_BESS_GT100, "canonical BESS count mismatch")
need(metrics.get("canonical_combined_projects") == EXPECTED_SOLAR_GT1 + EXPECTED_BESS_GT100, "combined V6 count mismatch")

if errors:
    print("V6 MANIFEST PROVENANCE FAILED")
    for error in errors:
        print(" -", error)
    raise SystemExit(1)

print(
    "V6 MANIFEST PROVENANCE PASS",
    f"source_rows={EXPECTED_ROWS}",
    f"solar={EXPECTED_SOLAR_GT1}",
    f"bess={EXPECTED_BESS_GT100}",
)

GlobalGrid2050 Verify Published Versions

A Python command-line tool in the scripts folder that fetches homepage catalogue, using SHA-256 from GitHub API and the PipelineNews and GridAtlas repositories.

storageglobalgrid2050 / scripts/verify_published_versions.py · lines 1–384 of 802 · Entry point · pattern check_offline (shared by 2 files)

What it does
It fetches homepage catalogue. Defines 13 functions or classes, including Failure, fetch, published_snapshots, named_on_homepage, parse_gridatlas_catalogue. Uses libraries __future__, argparse, hashlib, json, os. Side effects: reads or writes files; makes network requests; starts processes.
Inputs & outputs
In: data source: GitHub API; data source: pipelinenews data; data source: gridatlas data; JSON file homepage-catalogue.json; JSON file current.json; command-line arguments.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Verify Published Versions Workflow (globalgrid2050); GlobalGrid2050 Test Verify Published Versions (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It parses GridAtlas catalogue (`parse_gridatlas_catalogue`), checks GridAtlas catalogue retention (`check_gridatlas_catalogue_retention`) and checks GridAtlas homepage identity (`check_gridatlas_homepage_identity`). Fail when a Pipeline News version is published but not reachable, or named but not published. It accepts `--json` and `--offline`.
Why it matters
Run by GlobalGrid2050 Verify Published Versions Workflow. Checked by GlobalGrid2050 Test Verify Published Versions.
Application
globalgrid2050 · scripts · Python CLI
Uses
GridAtlas — Atlas Page (estate URL), __future__, argparse, hashlib, json, os, re, sys, urllib.error
Used by
run by GlobalGrid2050 Verify Published Versions Workflow (workflow run), imported by GlobalGrid2050 Test Verify Published Versions (import)
Produces
Failure, fetch, published_snapshots, named_on_homepage, parse_gridatlas_catalogue, catalogue_digest, archived_gridatlas_record, check_gridatlas_catalogue_retention, check_gridatlas_homepage_identity, check_offline, check_network, main
Defines here
Failure, fetch, published_snapshots, named_on_homepage, parse_gridatlas_catalogue, catalogue_digest, archived_gridatlas_record, check_gridatlas_catalogue_retention, check_gridatlas_homepage_identity, version_key
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/verify_published_versions.py:1-384 · blob 3e7e471e1959886eca72ea83018ab62922c3978f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""Fail when a Pipeline News version is published but not reachable, or named but not published.

WHY THIS EXISTS
---------------
Publishing a version and naming it are two different acts in this repository,
and until 202609020042 nothing checked that the second one had happened.

  * `pipelinenews_intelligence/<generation>/` is copied in by the Pipeline
    News overnight runner, which deliberately does not touch `index.html` -
    the homepage is governed by a numbered-snapshot ritual and a byte-exact
    sentinel contract.
  * `index.html` is the only route a reader has to those directories.

So the bytes of `202609012326` and `202609020025` sat on globalgrid2050.com,
byte-identical to their releases and served with HTTP 200, while the newest
version any reader could reach was `202608312339`. Published, and invisible.
That is the drift this script makes loud.

It also checks the Grid Atlas row, which had gone stale the same way: the
homepage claimed v9.5 / 202608301624 was the current verified release while
the live composition had moved to v9.77.

Offline checks always run.  The two network checks run only when
raw.githubusercontent.com is reachable, and say so when they are skipped.

    python3 scripts/verify_published_versions.py
    python3 scripts/verify_published_versions.py --json report.json
    python3 scripts/verify_published_versions.py --offline
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import sys
import urllib.error
import urllib.request
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
INDEX = ROOT / "index.html"
SNAPSHOTS = ROOT / "pipelinenews_intelligence"
CATALOGUE = ROOT / "catalogue" / "homepage-catalogue.json"
HOMEPAGE_VERSIONS = ROOT / "homepage_versions"

GENERATION_RE = re.compile(r"^[0-9]{12}$")
SNAPSHOT_URL_RE = re.compile(r'url:"\./pipelinenews_intelligence/([0-9]{12})/"')
SNAPSHOT_PATH_RE = re.compile(r"\./pipelinenews_intelligence/([0-9]{12})/?")
GRIDATLAS_ROW_RE = re.compile(
    r"GRIDATLAS_V9_AUTOMATION_START.*?data_gridatlas_release:\"([0-9]{12})-gridatlas-(v[0-9.]+)\".*?GRIDATLAS_V9_AUTOMATION_END",
    re.S,
)
GRIDATLAS_OS_STRIP_RE = re.compile(
    r'<div class="os-strip"><a href="https://ventusltd\.github\.io/gridatlas/atlas/">'
    r'UK Grid Atlas (V[0-9.]+) — Current Release \(Working Verified\)</a>'
    r'<span class="live-status">([0-9]{12})\b'
)
GRIDATLAS_CATALOGUE_BLOCK_RE = re.compile(
    r"GRIDATLAS_VERSION_CATALOGUE_START(?P<body>.*?)GRIDATLAS_VERSION_CATALOGUE_END",
    re.S,
)
GRIDATLAS_CATALOGUE_ENTRY_RE = re.compile(
    r'\{ name:"(?P<name>[^"]+)",(?: url:"(?P<url>[^"]+)",)? '
    r'note:"(?P<note>[^"]+)", data_gridatlas_catalogue:"'
    r'(?P<version>v[0-9]+(?:\.[0-9]+)?)\|'
    r'(?P<generation>none|[0-9]{12})\|'
    r'(?P<status>LIVE|ARCHIVED|REJECTED_PRE_PROMOTION|MISSING)\|'
    r'(?P<availability>[A-Z_]+)\|'
    r'(?P<commit>none|[0-9a-f]{40})\|'
    r'(?P<checked_at>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z)" \},'
)

GRIDATLAS_FOUNDATION_COUNT = 124
# Filled from the canonical serialisation of the first 124 records (V1 through
# v9.103) after v9.103's stale current link received its one permitted archive
# transition. Those records can never otherwise be rewritten for a successor.
GRIDATLAS_FOUNDATION_SHA256 = "40288c3233faba486848c90b958586b2f925a706285f13daa28696cff888b7f5"
GRIDATLAS_AVAILABILITY = {
    "NONE",
    "SOURCE_ONLY",
    "MANIFEST_EVIDENCE",
    "WORKING_VERIFIED",
    "REACHABLE_UNVERIFIED",
    "BROKEN",
}

PIPELINENEWS_RAW = "https://raw.githubusercontent.com/Ventusltd/pipelinenews/main"
GRIDATLAS_CURRENT = "https://raw.githubusercontent.com/Ventusltd/gridatlas/main/atlas/current.json"
GRIDATLAS_MANIFESTS = "https://raw.githubusercontent.com/Ventusltd/gridatlas/main/atlas/manifests"
GRIDATLAS_MAIN_API = "https://api.github.com/repos/Ventusltd/gridatlas/commits/main"

# A release built and superseded without ever entering the published lineage is
# not a published version.  These are recorded rather than silently ignored so
# the inventory of what exists and what is public stays honest.
UNPUBLISHED_BY_DESIGN = {
    "202608311550": "superseded sibling of 202608311558; never a parent",
    "202608311557": "superseded sibling of 202608311558; never a parent",
    "202608312018": "superseded sibling of 202608312037; never a parent",
    "202608312337": "superseded sibling of 202608312339; never a parent",
    "202609020010": "ISOLATED_CANDIDATE_ONLY_NO_SHARED_POINTER - paired with an isolated Codex atlas lab route",
}


class Failure(Exception):
    pass


def fetch(url: str, timeout: int = 20) -> bytes:
    headers = {"User-Agent": "globalgrid2050-publication-check/1"}
    token = os.environ.get("GITHUB_TOKEN")
    if token and url.startswith(("https://api.github.com/", "https://raw.githubusercontent.com/")):
        headers["Authorization"] = f"Bearer {token}"
    request = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(request, timeout=timeout) as response:
        return response.read()


def published_snapshots() -> list[str]:
    if not SNAPSHOTS.is_dir():
        raise Failure(f"{SNAPSHOTS.relative_to(ROOT)} does not exist")
    found = []
    for child in sorted(SNAPSHOTS.iterdir()):
        if not child.is_dir():
            continue
        if not GENERATION_RE.match(child.name):
            raise Failure(f"snapshot directory is not a 12-digit generation: {child.name}")
        if not (child / "index.html").is_file():
            raise Failure(f"published snapshot has no index.html: {child.name}")
        found.append(child.name)
    return found


def named_on_homepage(text: str) -> list[str]:
    """Which published generations can a reader actually reach from the front door?

    This used to read index.html and match url:"./pipelinenews_intelligence/NNN/".
    On 2026-09-08 the homepage became a VIEW: index.html now ships a nest renderer
    and fetches catalogue/homepage-catalogue.json at runtime, so it contains no
    snapshot URL at all. The regex started returning [], which made "published but
    not reachable" fire on all 34 snapshots at once - a true statement about the
    regex and a false one about the site.

    The catalogue is what the front door reads, is generated from the tree and git
    and is never typed, so it is the honest place to ask this. The `text` argument
    is kept and ignored: the caller still hands over index.html, and a later change
    that puts the URLs back in the page should not have to move this call site.
    """
    del text
    doc = json.loads(CATALOGUE.read_text(encoding="utf-8"))
    found = [
        match.group(1)
        for entry in doc.get("entries", [])
        if (match := SNAPSHOT_PATH_RE.fullmatch(str(entry.get("url") or "")))
    ]
    # The homepage presents newest first; the catalogue is generated in that order
    # and check_offline compares named[0] against the newest on disk.
    return found


def parse_gridatlas_catalogue(text: str, failures: list[str], *, required: bool = True) -> list[dict]:
    """Parse the reader-visible, machine-marked lineage without executing JavaScript."""
    blocks = list(GRIDATLAS_CATALOGUE_BLOCK_RE.finditer(text))
    if not blocks:
        if required:
            failures.append("the homepage has no Grid Atlas version catalogue block")
        return []
    if len(blocks) != 1:
        failures.append(f"the homepage must carry exactly one Grid Atlas catalogue block; found {len(blocks)}")
        return []

    body = blocks[0].group("body")
    matches = list(GRIDATLAS_CATALOGUE_ENTRY_RE.finditer(body))
    marker_count = body.count("data_gridatlas_catalogue:")
    if marker_count != len(matches):
        failures.append(
            "one or more Grid Atlas catalogue rows are malformed: "
            f"found {marker_count} markers but parsed {len(matches)} records"
        )

    records = []
    for match in matches:
        record = match.groupdict()
        record["generation"] = None if record["generation"] == "none" else record["generation"]
        record["commit"] = None if record["commit"] == "none" else record["commit"]
        records.append(record)
    return records


def catalogue_digest(records: list[dict]) -> str:
    payload = json.dumps(
        records,
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


GRIDATLAS_CURRENT_URL = "https://ventusltd.github.io/gridatlas/atlas/"
GRIDATLAS_ARCHIVE_NOTE_SUFFIX = (
    " | archived after successor promotion; immutable composition manifest retained; "
    "no longer the mutable current route"
)


def archived_gridatlas_record(record: dict) -> dict | None:
    """Return the sole permitted rewrite of a stale v9.x current record."""
    if not (
        re.fullmatch(r"v9\.[0-9]+", record["version"])
        and record["generation"]
        and record["status"] == "LIVE"
        and record["availability"] == "WORKING_VERIFIED"
        and record["url"] == GRIDATLAS_CURRENT_URL
        and record["name"].endswith(" -- Live Current (Working Verified)")
        and record["note"].startswith("LIVE | WORKING VERIFIED | ")
    ):
        return None

    archived = dict(record)
    archived["name"] = record["name"].removesuffix(
        " -- Live Current (Working Verified)"
    ) + " -- Archived (Working Verified)"
    archived["url"] = (
        "https://ventusltd.github.io/gridatlas/atlas/manifests/"
        f"{record['generation']}-composition.json"
    )
    archived["note"] = (
        "ARCHIVED | WORKING VERIFIED | "
        + record["note"].removeprefix("LIVE | WORKING VERIFIED | ")
        + GRIDATLAS_ARCHIVE_NOTE_SUFFIX
    )
    archived["status"] = "ARCHIVED"
    return archived


def check_gridatlas_catalogue_retention(records: list[dict]) -> list[str]:
    """A numbered pre-edit snapshot makes already-catalogued identities append-only."""
    failures: list[str] = []
    snapshots = sorted(HOMEPAGE_VERSIONS.glob("homepage_v[0-9][0-9][0-9].html"))
    if not snapshots:
        return ["no numbered homepage snapshot exists before the Grid Atlas catalogue edit"]

    previous_failures: list[str] = []
    previous = parse_gridatlas_catalogue(
        snapshots[-1].read_text(encoding="utf-8"),
        previous_failures,
        required=False,
    )
    if previous_failures:
        failures.extend(f"latest homepage snapshot: {failure}" for failure in previous_failures)
        return failures
    if not previous:
        return failures

    current_by_identity = {
        (record["version"], record["generation"]): record for record in records
    }
    for old in previous:
        identity = (old["version"], old["generation"])
        current = current_by_identity.get(identity)
        if current is None:
            failures.append(
                f"append-only Grid Atlas history lost {old['version']} / {old['generation'] or 'no generation'}"
            )
            continue
        if current == old:
            continue
        permitted_archive = archived_gridatlas_record(old)
        if permitted_archive is not None and current == permitted_archive:
            continue
        if current["commit"] != old["commit"]:
            failures.append(f"append-only Grid Atlas history rewrote the commit for {old['version']}")
        failures.append(f"append-only Grid Atlas history rewrote retained record {old['version']}")
    return failures


def check_gridatlas_homepage_identity(text: str, report: dict) -> list[str]:
    """Require the live identity and the complete append-only catalogue to agree."""
    failures: list[str] = []
    for marker in ("GRIDATLAS_V9_AUTOMATION_START", "GRIDATLAS_V9_AUTOMATION_END"):
        count = text.count(marker)
        if count != 1:
            failures.append(f"the homepage must retain exactly one {marker} marker; found {count}")
    if text.count("const AREAS = [") != 1:
        failures.append("the homepage must retain exactly one AREAS directory")
    if text.count('url:"./repd_grid_atlasv8/"') != 1:
        failures.append("the homepage must retain exactly one local V8 sentinel route")
    if text.count("children:[...GRIDATLAS_VERSION_CATALOGUE].reverse()") != 1:
        failures.append("the complete Grid Atlas catalogue is not wired into AREAS exactly once")

    governed = GRIDATLAS_ROW_RE.findall(text)
    strips = GRIDATLAS_OS_STRIP_RE.findall(text)

    if len(governed) != 1:
        failures.append(
            "the GRIDATLAS_V9_AUTOMATION block must carry exactly one "
            f"data_gridatlas_release; found {len(governed)}"
        )
    if len(strips) != 1:
        failures.append(
            "the homepage must carry exactly one Grid Atlas os-strip identity; "
            f"found {len(strips)}"
        )

    if len(governed) == 1:
        report["gridatlas_named"] = {
            "generation": governed[0][0],
            "version": governed[0][1],
        }
    if len(strips) == 1:
        report["gridatlas_os_strip"] = {
            "generation": strips[0][1],
            "version": strips[0][0].lower(),
        }
    if len(governed) == 1 and len(strips) == 1:
        governed_identity = (governed[0][0], governed[0][1].lower())
        strip_identity = (strips[0][1], strips[0][0].lower())
        if strip_identity != governed_identity:
            failures.append(
                "the Grid Atlas os-strip names "
                f"{strip_identity[1]} / {strip_identity[0]} while the governed row names "
                f"{governed_identity[1]} / {governed_identity[0]}"
            )

    records = parse_gridatlas_catalogue(text, failures)
    report["gridatlas_catalogue_count"] = len(records)
    if not records:
        return failures

    identities = [(record["version"], record["generation"]) for record in records]
    if len(identities) != len(set(identities)):
        failures.append("the Grid Atlas catalogue contains a duplicate version/generation identity")

    def version_key(record: dict) -> tuple[int, int, str]:
        parts = record["version"][1:].split(".")
        return int(parts[0]), int(parts[1]) if len(parts) == 2 else 0, record["generation"] or ""

    if [version_key(record) for record in records] != sorted(version_key(record) for record in records):
        failures.append("the Grid Atlas catalogue is not oldest-first; a successor must be appended, not inserted")

    if len(records) < GRIDATLAS_FOUNDATION_COUNT + 1:
        failures.append(
            f"the Grid Atlas catalogue has {len(records)} records; its protected foundation needs "
            f"at least {GRIDATLAS_FOUNDATION_COUNT + 1}"
        )
    elif catalogue_digest(records[:GRIDATLAS_FOUNDATION_COUNT]) != GRIDATLAS_FOUNDATION_SHA256:
        failures.append("the protected V1-to-v9.103 Grid Atlas catalogue foundation was rewritten")

    for record in records:
        version = record["version"]
        generation = record["generation"]
        status = record["status"]
        availability = record["availability"]
        commit = record["commit"]
        checked_at = record["checked_at"]
        url = record["url"]
        note = record["note"]

        if availability not in GRIDATLAS_AVAILABILITY:
            failures.append(f"{version} uses unknown availability {availability}")
        if version.upper() not in record["name"]:
            failures.append(f"{version} is not named visibly on its catalogue row")
        if not note.startswith(f"{status} | {availability.replace('_', ' ')} | "):
            failures.append(f"{version} does not state its status and evidence class visibly")
        if generation and f"generation {generation}" not in note:
            failures.append(f"{version} does not state generation {generation} visibly")
        if commit and f"source commit {commit}" not in note:
            failures.append(f"{version} does not state its exact source commit visibly")
        if f"checked_at {checked_at}" not in note:
            failures.append(f"{version} does not state checked_at {checked_at} visibly")

        if status == "MISSING":
            if availability != "NONE" or generation or commit or url:
                failures.append(f"missing {version} invents a generation, commit, URL or availability")
        elif not url or not commit:
            failures.append(f"recoverable {version} must carry both a URL and a full source commit")

        if availability == "MANIFEST_EVIDENCE":
            if "not a runnable application" not in note:
                failures.append(f"{version} manifest evidence is not labelled as non-runnable")