GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / star-solar-star / scripts

Star Contract and 2 more files

A Python command-line tool in the scripts folder of Star Solar Star that reads solar, using ISO 3166-1 and SHA-256.

413 lines of Python from star-solar-star, in 3 files. Topic: Solar and storage design. Section 258 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. Star Contract ingest · star-solar-star / scripts/star_contract.py lines 1–182
  2. Validate Sun ingest · star-solar-star / scripts/validate_sun.py lines 1–117
  3. Verify Pages storage · star-solar-star / scripts/verify_pages.py lines 1–114

Star Contract

A Python command-line tool in the scripts folder of Star Solar Star that reads solar, using ISO 3166-1 and SHA-256.

ingeststar-solar-star / scripts/star_contract.py · lines 1–182 of 182 · Entry point · pattern _public_https_url (shared by 2 files)

What it does
It loads solar. Defines 9 functions or classes, including canonical_bytes, _jcs_domain, observation_bytes, seed_for, _require. Uses libraries __future__, argparse, datetime, hashlib, ipaddress. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 3 files: Issue to Star (star-solar-star); Publish Main (star-solar-star); Country Star CI Workflow (star-solar-star). Reached from 4 other entry points, including Build Sun Daily Workflow (star-solar-star); Publication CI Workflow (star-solar-star); Publish Approved Star Workflow (star-solar-star).
What it achieves
It writes JSON (`write_json`) and is built from the canonical bytes helper (`canonical_bytes`) and the observation bytes helper (`observation_bytes`). Dependency-free validator and seed compiler for public solar star definitions.
Why it matters
Imported by Issue to Star. Run by Publish Main and Country Star CI Workflow.
Application
star-solar-star · scripts · Python CLI
Uses
__future__, argparse, datetime, hashlib, ipaddress, json, math, re
Used by
imported by Issue to Star (import), run by Publish Main (script call), run by Country Star CI Workflow (workflow run)
Produces
canonical_bytes, observation_bytes, seed_for, validate, write_json
Defines here
canonical_bytes, _jcs_domain, observation_bytes, seed_for, _require, _date_like, _public_https_url, validate, write_json
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-solar-star@4ac16c0c2297c4b6022afc4d6f921faf091bb74e scripts/star_contract.py:1-182 · blob 88e6f6c9805f54f95ae5189db067b0664bb843a5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""Dependency-free validator and seed compiler for public solar star definitions."""
from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import ipaddress
import json
import math
import re
import urllib.parse
from pathlib import Path
from typing import Any

from vendor.rfc8785 import dumps as jcs_bytes


SCHEMA = "star-solar-star.definition.v1"
CANONICALIZATION = "UTF-8 JSON, recursively sorted object keys, observations sorted by key, no insignificant whitespace"
JCS_CANONICALIZATION = "RFC8785-JCS; observations sorted by UTF-16 key; safe integers; v2"
SHA256 = re.compile(r"^[0-9a-f]{64}$")
SLUG = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
PERIOD = re.compile(r"^[0-9]{4}(?:-[0-9]{2}(?:-[0-9]{2})?)?$")
RELATIONS = {"exact", "approximately", "greater_than", "less_than"}
PUBLIC_LANGUAGE_EXCLUSIONS = (
    "companies house",
    "prospect company",
    "sales target",
    "karma",
    "vedic",
    "enemy",
    "verdict",
)


def canonical_bytes(value: Any) -> bytes:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")


def _jcs_domain(value: Any) -> None:
    """Use the same safe numeric domain before browser and Python serialization."""
    if isinstance(value, (int, float)) and not isinstance(value, bool):
        _require(math.isfinite(value), "JCS numbers must be finite")
        _require(not float(value).is_integer() or abs(value) <= 2**53 - 1,
                 "JCS integer values must be within the safe integer domain")
    elif isinstance(value, list):
        for child in value:
            _jcs_domain(child)
    elif isinstance(value, dict):
        for child in value.values():
            _jcs_domain(child)


def observation_bytes(observations: list[dict[str, Any]], canonicalization: str = CANONICALIZATION) -> bytes:
    if canonicalization == CANONICALIZATION:
        return canonical_bytes(sorted(observations, key=lambda item: item["key"]))
    _require(canonicalization == JCS_CANONICALIZATION, "unexpected seed canonicalization")
    _jcs_domain(observations)
    ordered = sorted(observations, key=lambda item: item["key"].encode("utf-16be"))
    return jcs_bytes(ordered)


def seed_for(observations: list[dict[str, Any]], canonicalization: str = CANONICALIZATION) -> str:
    return hashlib.sha256(observation_bytes(observations, canonicalization)).hexdigest()


def _require(condition: bool, message: str) -> None:
    if not condition:
        raise ValueError(message)


def _date_like(value: Any, label: str) -> None:
    _require(isinstance(value, str) and PERIOD.fullmatch(value) is not None, f"{label} must be YYYY, YYYY-MM or YYYY-MM-DD")


def _public_https_url(value: Any, label: str) -> None:
    _require(isinstance(value, str), f"{label} must be a string")
    parsed = urllib.parse.urlsplit(value)
    _require(parsed.scheme == "https" and parsed.hostname is not None, f"{label} must use HTTPS with a host")
    _require(parsed.username is None and parsed.password is None, f"{label} must not contain credentials")
    _require(not parsed.fragment, f"{label} must not contain a fragment")
    host = parsed.hostname.lower().rstrip(".")
    try:
        address = ipaddress.ip_address(host)
    except ValueError:
        _require("." in host and host != "localhost" and not host.endswith(".local"), f"{label} host must be public")
    else:
        _require(address.is_global, f"{label} IP host must be globally routable")


def validate(star: dict[str, Any]) -> dict[str, Any]:
    _require(isinstance(star, dict), "star must be a JSON object")
    required = {"schema", "id", "type", "name", "description", "region", "sources", "observations", "seed"}
    _require(required <= set(star), f"missing top-level keys: {sorted(required - set(star))}")
    _require(star["schema"] == SCHEMA, f"schema must be {SCHEMA}")
    _require(isinstance(star["id"], str) and SLUG.fullmatch(star["id"]) is not None, "id must be a lowercase hyphenated slug")
    _require(star["type"] in {"country-solar", "global-solar"}, "unsupported star type")
    _require(isinstance(star["name"], str) and 1 <= len(star["name"].strip()) <= 120, "name must contain 1 to 120 characters")
    _require(isinstance(star["description"], str) and 1 <= len(star["description"].strip()) <= 500, "description must contain 1 to 500 characters")

    public_text = " ".join([star["name"], star["description"]]).lower()
    for term in PUBLIC_LANGUAGE_EXCLUSIONS:
        _require(term not in public_text, f"public-facing name/description contains excluded term: {term}")

    region = star["region"]
    _require(isinstance(region, dict), "region must be an object")
    _require(set(region) == {"scheme", "code", "name"}, "region must contain scheme, code and name only")
    if star["type"] == "country-solar":
        _require(region["scheme"] == "ISO_3166-1_alpha-2", "country stars require ISO 3166-1 alpha-2")
        _require(re.fullmatch(r"[A-Z]{2}", str(region["code"])) is not None, "country code must be two uppercase letters")
    else:
        _require(region["scheme"] == "UN_M49" and region["code"] == "001", "global star requires UN M49 code 001")

    sources = star["sources"]
    _require(isinstance(sources, list) and sources, "sources must be a non-empty array")
    source_ids = set()
    for pos, source in enumerate(sources):
        label = f"sources[{pos}]"
        needed = {"id", "publisher", "title", "url", "published", "accessed_utc", "bytes", "sha256"}
        _require(isinstance(source, dict) and needed <= set(source), f"{label} lacks required provenance")
        _require(source["id"] not in source_ids, f"duplicate source id {source['id']}")
        source_ids.add(source["id"])
        _public_https_url(source["url"], f"{label}.url")
        _date_like(source["published"], f"{label}.published")
        _require(isinstance(source["accessed_utc"], str) and source["accessed_utc"].endswith("Z"), f"{label}.accessed_utc must end in Z")
        try:
            dt.datetime.fromisoformat(source["accessed_utc"].replace("Z", "+00:00"))
        except ValueError as exc:
            raise ValueError(f"{label}.accessed_utc is invalid") from exc
        _require(isinstance(source["bytes"], int) and not isinstance(source["bytes"], bool) and source["bytes"] > 0, f"{label}.bytes must be positive")
        _require(isinstance(source["sha256"], str) and SHA256.fullmatch(source["sha256"]) is not None, f"{label}.sha256 is invalid")

    observations = star["observations"]
    _require(isinstance(observations, list) and observations, "observations must be a non-empty array")
    keys = set()
    for pos, observation in enumerate(observations):
        label = f"observations[{pos}]"
        needed = {"key", "metric", "period", "value", "unit", "relation", "source_id", "locator"}
        _require(isinstance(observation, dict) and needed <= set(observation), f"{label} lacks required fields")
        _require(isinstance(observation["key"], str) and observation["key"], f"{label}.key is required")
        _require(observation["key"] not in keys, f"duplicate observation key {observation['key']}")
        keys.add(observation["key"])
        _date_like(observation["period"], f"{label}.period")
        value = observation["value"]
        _require(isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value), f"{label}.value must be finite")
        _require(isinstance(observation["unit"], str) and observation["unit"], f"{label}.unit is required")
        _require(observation["relation"] in RELATIONS, f"{label}.relation is unsupported")
        _require(observation["source_id"] in source_ids, f"{label} refers to unknown source")
        _require(isinstance(observation["locator"], str) and observation["locator"], f"{label}.locator is required")

    seed = star["seed"]
    _require(isinstance(seed, dict), "seed must be an object")
    _require(seed.get("algorithm") == "sha256", "seed algorithm must be sha256")
    version = seed.get("canonicalization")
    _require(version in {CANONICALIZATION, JCS_CANONICALIZATION}, "unexpected seed canonicalization")
    _require(seed.get("url_parameter") == "seed", "seed URL parameter must be seed")
    expected_inputs = sorted(keys, key=(lambda key: key.encode("utf-16be")) if version == JCS_CANONICALIZATION else None)
    _require(seed.get("inputs") == expected_inputs, "seed inputs must be all observation keys in sorted order")
    expected_seed = seed_for(observations, version)
    _require(seed.get("value") == expected_seed, "seed does not match canonical observations")
    return {
        "id": star["id"],
        "type": star["type"],
        "region": region["code"],
        "sources": len(sources),
        "observations": len(observations),
        "seed": expected_seed,
    }


def write_json(path: Path, value: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8", newline="\n") as handle:
        handle.write(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("star", type=Path)
    args = parser.parse_args()
    print(json.dumps(validate(json.loads(args.star.read_text(encoding="utf-8"))), sort_keys=True))

Validate Sun

A Python command-line tool in the scripts folder of Star Solar Star that reads today, history, UK solar and voices, using SHA-256.

ingeststar-solar-star / scripts/validate_sun.py · lines 1–117 of 117 · Entry point

What it does
It loads today, history, UK solar and voices. Defines load, validate. Uses libraries __future__, argparse, datetime, json, re. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file today.json; JSON file history.json; JSON file uk-solar.json; JSON file voices.json; JSON file press.json; JSON file provenance.json; command-line arguments.
Downstream impact
Used directly by 4 files: Publish Main (star-solar-star); Test Integrity (star-solar-star); Build Sun Daily Workflow (star-solar-star); Solar Integrity Workflow (star-solar-star). Reached from 3 other entry points, including Publication CI Workflow (star-solar-star); Publish Approved Star Workflow (star-solar-star); Test Publication (star-solar-star).
What it achieves
It is built from the load step (`load`) and the validate step (`validate`). Fail-closed validation for the six committed Sun Star payloads.
Why it matters
Run by Publish Main, Build Sun Daily Workflow and Solar Integrity Workflow. Checked by Test Integrity.
Application
star-solar-star · scripts · Python CLI
Uses
Build Sun (import), __future__, argparse, datetime, json, re, pathlib
Used by
run by Publish Main (script call), imported by Test Integrity (sys.path import), run by Build Sun Daily Workflow (workflow run), run by Solar Integrity Workflow (workflow run)
Produces
load, validate
Defines here
load, validate
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-solar-star@4ac16c0c2297c4b6022afc4d6f921faf091bb74e scripts/validate_sun.py:1-117 · blob 145fffcb362b887ec044d49945ebde147e644283 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""Fail-closed validation for the six committed Sun Star payloads."""
from __future__ import annotations

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

from build_sun import summarize_pv_day


NAMES = {"today.json", "history.json", "uk-solar.json", "voices.json", "press.json", "provenance.json"}
SHA256 = re.compile(r"^[0-9a-f]{64}$")


def load(root: Path, name: str):
    path = root / name
    if not path.is_file():
        raise ValueError(f"missing {name}")
    return json.loads(path.read_text(encoding="utf-8"))


def validate(root: Path) -> dict:
    present = {path.name for path in root.glob("*.json")}
    if present != NAMES:
        raise ValueError(f"expected exactly {sorted(NAMES)}, found {sorted(present)}")
    today = load(root, "today.json")
    history = load(root, "history.json")
    uk = load(root, "uk-solar.json")
    voices = load(root, "voices.json")
    press = load(root, "press.json")
    provenance = load(root, "provenance.json")

    if today.get("schema") != "star-solar-star.today.v2":
        raise ValueError("unexpected today schema")
    if history.get("schema") != "star-solar-star.history.v2":
        raise ValueError("unexpected history schema")
    if not SHA256.fullmatch(str(today.get("seed", ""))):
        raise ValueError("today seed is not a full SHA-256")
    if today["seed"] != today["pv_live"].get("seed_sha256"):
        raise ValueError("top-level and PV Live seeds differ")
    if not history.get("days"):
        raise ValueError("history is empty")
    dates = [dt.date.fromisoformat(day["date"]) for day in history["days"]]
    if dates != [dates[0] + dt.timedelta(days=n) for n in range(len(dates))]:
        raise ValueError("history dates must be unique, ordered and consecutive")
    for day in history["days"]:
        if day.get("complete") is not True:
            raise ValueError("PV Live day must be explicitly complete")
        expected = summarize_pv_day(day["date"], day["series"])
        if day != expected:
            raise ValueError("history PV Live summaries do not match recomputed series")
    selected = today["pv_live"]
    requested = dt.date.fromisoformat(selected["requested_date"])
    data_date = dt.date.fromisoformat(selected["data_date"])
    if data_date > requested or selected.get("date") != selected["data_date"]:
        raise ValueError("selected/source/requested PV Live dates disagree")
    if selected.get("used_latest_available") is not (data_date != requested):
        raise ValueError("PV Live fallback flag disagrees with requested/source dates")
    if today["london_solar_geometry"].get("date") != requested.isoformat():
        raise ValueError("geometry must identify the requested date")
    if history["days"][-1]["date"] != selected["data_date"]:
        raise ValueError("history does not end on the selected day")
    expected_selected = {**history["days"][-1], "requested_date": requested.isoformat(),
                         "data_date": data_date.isoformat(), "used_latest_available": data_date != requested}
    if selected != expected_selected:
        raise ValueError("selected PV Live day does not match verified history")

    projects = uk.get("projects", [])
    missing = [p["repd_ref"] for p in projects if p.get("latitude") is None or p.get("longitude") is None]
    if uk.get("solar_projects") != len(projects):
        raise ValueError("solar project count disagrees with project rows")
    if uk.get("with_coordinates") + uk.get("without_coordinates") != len(projects):
        raise ValueError("coordinate counts do not sum to project count")
    if uk.get("missing_coordinate_repd_refs") != missing:
        raise ValueError("missing coordinate list disagrees with project rows")
    if len({p["repd_ref"] for p in projects}) != len(projects):
        raise ValueError("repd_ref is not unique")

    if not voices.get("episodes"):
        raise ValueError("voices has no episodes")
    allowed_press = {"title", "link", "published", "attribution"}
    if not press.get("entries"):
        raise ValueError("press has no entries")
    for entry in press["entries"]:
        if set(entry) != allowed_press:
            raise ValueError(f"press entry includes fields outside RSS metadata policy: {set(entry)}")

    sources = provenance.get("sources", [])
    if not sources:
        raise ValueError("provenance has no sources")
    for source in sources:
        if not source.get("url") or not source.get("fetched_utc"):
            raise ValueError("provenance source lacks URL or fetched time")
        if not isinstance(source.get("bytes"), int) or source["bytes"] < 1:
            raise ValueError("provenance source lacks positive byte count")
        if not SHA256.fullmatch(str(source.get("sha256", ""))):
            raise ValueError("provenance source lacks SHA-256")
    if set(provenance.get("scans", {})) != {"solar_components", "solar_deployment_statistics"}:
        raise ValueError("the two required estate scans are not present")
    return {
        "date": today["pv_live"]["data_date"],
        "seed": today["seed"],
        "solar_projects": len(projects),
        "with_coordinates": uk["with_coordinates"],
        "press_entries": len(press["entries"]),
        "provenance_sources": len(sources),
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("root", type=Path, nargs="?", default=Path("sun"))
    result = validate(parser.parse_args().root)
    print(json.dumps(result, sort_keys=True))

Verify Pages

A Python command-line tool in the scripts folder of Star Solar Star that verifies build (`verify_build`) and served (`verify_served`), using SHA-256.

storagestar-solar-star / scripts/verify_pages.py · lines 1–114 of 114 · Entry point

What it does
It fetches data. Defines 6 functions or classes, including api, git, committed_payloads, verify_build, verify_served. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 3 files: Test Publication (star-solar-star); Build Sun Daily Workflow (star-solar-star); Publish Approved Star Workflow (star-solar-star). Reached from 1 other entry point, including Publication CI Workflow (star-solar-star).
What it achieves
It is built from the API step (`api`), the git step (`git`) and the committed payloads helper (`committed_payloads`). Request a Pages build and prove its committed publication is served byte-for-byte. It accepts `--publication`, `--result` and `--timeout`.
Why it matters
Run by Build Sun Daily Workflow and Publish Approved Star Workflow. Checked by Test Publication.
Application
star-solar-star · scripts · Python CLI
Uses
__future__, argparse, datetime, hashlib, json, os, pathlib, subprocess
Used by
imported by Test Publication (sys.path import), run by Build Sun Daily Workflow (workflow run), run by Publish Approved Star Workflow (workflow run)
Produces
api, git, committed_payloads, verify_build, verify_served, main
Defines here
api, git, committed_payloads, verify_build, verify_served, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-solar-star@4ac16c0c2297c4b6022afc4d6f921faf091bb74e scripts/verify_pages.py:1-114 · blob 48e521f6cd2ba704f999272c5277c522607d708b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Request a Pages build and prove its committed publication is served byte-for-byte."""
from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import subprocess
import time
import urllib.request
from urllib.parse import quote


def api(endpoint: str, method: str = "GET") -> dict:
    return json.loads(subprocess.check_output(
        ["gh", "api", "--method", method, endpoint], text=True))


def git(*args: str) -> bytes:
    return subprocess.check_output(["git", *args])


def committed_payloads(commit: str, paths: list[str]) -> dict[str, bytes]:
    return {path: git("show", f"{commit}:{path}") for path in paths}


def verify_build(build: dict, published: str, expected: dict[str, bytes]) -> bool:
    if build["status"] != "built":
        return False
    built_commit = build["commit"]
    if subprocess.run(["git", "merge-base", "--is-ancestor", published, built_commit],
                      capture_output=True).returncode:
        return False
    # A descendant may change unrelated files, but must retain every payload.
    return committed_payloads(built_commit, list(expected)) == expected


def verify_served(base_url: str, expected: dict[str, bytes], commit: str) -> dict:
    hashes = {}
    for path, contents in expected.items():
        url = base_url.rstrip("/") + "/" + quote(path, safe="/")
        request = urllib.request.Request(url + "?commit=" + commit,
                                         headers={"Cache-Control": "no-cache"})
        with urllib.request.urlopen(request, timeout=30) as response:
            served = response.read()
        if served != contents:
            raise ValueError(f"served bytes do not match {commit}:{path}")
        hashes[path] = {"url": url, "bytes": len(contents),
                        "sha256": hashlib.sha256(served).hexdigest()}
    return hashes


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--publication", type=Path, required=True)
    parser.add_argument("--result", type=Path, required=True)
    parser.add_argument("--timeout", type=int, default=720)
    args = parser.parse_args()
    publication = json.loads(args.publication.read_text(encoding="utf-8"))
    repo = os.environ["GITHUB_REPOSITORY"]
    endpoint = f"repos/{repo}/pages"
    site = api(endpoint)
    if site["source"] != {"branch": "main", "path": "/"} or site["build_type"] != "legacy":
        raise RuntimeError("expected existing legacy Pages source main /")
    expected = committed_payloads(publication["published_commit"], publication["paths"])
    result = {**publication, "pass": False, "pages_request": None}
    try:
        previous_url = api(endpoint + "/builds/latest")["url"]
        requested = api(endpoint + "/builds", "POST")
        result["pages_request"] = requested
        # The API normally returns /latest. Resolve it to a new numeric build
        # before following it; a previous unrelated success is insufficient.
        build_url = requested["url"]
        deadline = time.monotonic() + args.timeout
        last_error = "Pages build pending"
        while time.monotonic() < deadline:
            build = api(build_url)
            if build_url.endswith("/latest"):
                if build["url"] == previous_url:
                    time.sleep(15)
                    continue
                build_url = build["url"]
            result["pages_build"] = {key: build.get(key) for key in
                                     ("url", "commit", "status", "created_at", "updated_at", "error")}
            if build["status"] == "errored":
                raise RuntimeError(f"Pages build failed: {build.get('error')}")
            if build["status"] == "built":
                git("fetch", "origin", "+refs/heads/main:refs/remotes/origin/main")
                if not verify_build(build, publication["published_commit"], expected):
                    raise RuntimeError("Pages built commit does not retain the publication")
                try:
                    result["served"] = verify_served(site["html_url"], expected,
                                                     publication["published_commit"])
                    result["pass"] = True
                    break
                except (OSError, ValueError) as error:
                    last_error = str(error)
            time.sleep(15)
        if not result["pass"]:
            raise TimeoutError(last_error)
    except Exception as error:
        result["error"] = str(error)
        raise
    finally:
        result["verified_at_utc"] = dt.datetime.now(dt.timezone.utc).isoformat()
        args.result.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
        print(json.dumps(result))


if __name__ == "__main__":
    main()