GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / automation/news/signals

Planning File and 1 more file

A Python command-line tool in the signals folder of GlobalGrid2050 that reads planning registers and the Renewable Energy Planning Database (REPD) register.

585 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 795 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. Official storage · globalgrid2050 / automation/news/signals/official.py lines 469–730
  2. Planning File storage · globalgrid2050 / automation/news/signals/planning_file.py lines 1–323

Official

A Python command-line tool in the signals folder of GlobalGrid2050 that fetches search, top200 solar, aliases and the Renewable Energy Planning Database (REPD) register.

storageglobalgrid2050 / automation/news/signals/official.py · lines 469–730 of 730 (continued from section 794) · Entry point · pattern FetchError (shared by 2 files)

What it does
It fetches search, top200 solar, aliases and the REPD register. Defines 43 functions or classes, including now_utc, FetchError, __init__, _completed_context, _incomplete_chain. Uses libraries __future__, argparse, csv, datetime, io. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file search.json; JSON file top200_solar.json; JSON file aliases.json; command-line arguments.
Downstream impact
Used directly by 4 files: Planning File (globalgrid2050); Test Signals Official (globalgrid2050); Test Signals Planning File (globalgrid2050); GlobalGrid2050 Project Signals Official Workflow (globalgrid2050). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Combine (globalgrid2050).
What it achieves
It fetches error (`FetchError`), closes health (`close_health`) and loads projects (`load_projects`). Official-source signals for the 200 largest solar projects in the REPD (team "official"). It accepts `--out`, `--probe` and `--discover`.
Why it matters
Imported by Planning File. Run by GlobalGrid2050 Project Signals Official Workflow. Checked by 2 tests, including Test Signals Official.
Application
globalgrid2050 · automation/news/signals · Python CLI
Uses
Dates (import), Gate (import), Datacentre Feed (sys.path import), __future__, argparse, csv, datetime, io, json, re, sys
Used by
imported by Planning File (import), imported by Test Signals Official (sys.path import), imported by Test Signals Planning File (sys.path import), run by GlobalGrid2050 Project Signals Official Workflow (workflow run)
Produces
now_utc, FetchError, Fetcher, health, close_health, load_projects, derive_alias, phrase_in, alias_core, match, item, parse_day
Defines here
govuk_results, govuk_queries, source_govuk, html_title, page_mentions, source_ecu, dedupe, run, build_part, by_project, cell, probe_report, discover, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/signals/official.py:469-730 · blob 29495b1d70f6b60f52285246dcee5a4ad2806fa7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core


def govuk_results(body):
    data = json.loads(body.decode("utf-8", "replace") if isinstance(body, bytes) else body)
    out = []
    for r in data.get("results", []):
        link = r.get("link") or ""
        if link.startswith("/"):
            link = "https://www.gov.uk" + link
        orgs = [o.get("title") for o in (r.get("organisations") or []) if isinstance(o, dict) and o.get("title")]
        out.append({"title": r.get("title") or "", "link": link, "summary": r.get("description") or "",
                    "date": DATES.day(r.get("public_timestamp") or ""),
                    "publisher": orgs[0] if orgs else "GOV.UK", "format": r.get("format") or ""})
    return out


def govuk_queries(project):
    queries = ['"%s"' % project["aliases"][0]]
    ref = project.get("planning_ref", "")
    if PINS_REF_RE.fullmatch(ref):
        queries.append(ref)
    return queries


def source_govuk(projects, fetcher, per_project=3):
    record = health("govuk-search", GOVUK_SEARCH)
    items = []
    for project in projects:
        kept, seen = [], set()
        for query in govuk_queries(project):
            record["requests"] += 1
            try:
                _, _, body = fetcher.get(govuk_url(query), "application/json")
                results = govuk_results(body)
            except (FetchError, ValueError) as exc:
                record["failures"] += 1
                record["error"] = str(exc)[:200]
                continue
            for r in results:
                hit = match(project, r["title"], r["summary"])
                if not hit or r["link"] in seen:
                    continue
                made = item(project, r["title"], r["link"], r["publisher"], r["date"],
                            "GOV.UK search for %s: %s" % (query, hit[0]), hit[1])
                if made:
                    seen.add(r["link"])
                    made["kind"] = "govuk_page"
                    kept.append(made)
        kept.sort(key=lambda i: i["date"] or "", reverse=True)
        items += kept[:per_project]
    record["items"] = len(items)
    return items, close_health(record)


# ---------------------------------------------------------------- source: Scottish Energy Consents Unit case page

TITLE_RE = re.compile(r"<title[^>]*>(.*?)</title>", re.I | re.S)


def html_title(body):
    m = TITLE_RE.search(body.decode("utf-8", "replace") if isinstance(body, bytes) else body)
    return D.clean_text(m.group(1), 200) if m else ""


def page_mentions(body, *needles):
    text = _norm(D.clean_text(body.decode("utf-8", "replace") if isinstance(body, bytes) else body, MAX_BYTES))
    return any(_norm(n) and _norm(n) in text for n in needles if n)


def source_ecu(projects, fetcher):
    """An ECU case page that answers and names the reference is an official, undated notice of the case."""
    record = health("ecu-case", ECU_CASE.format(ref="<reference>"))
    items = []
    for project in projects:
        ref = project.get("planning_ref", "").upper()
        if not ECU_REF_RE.fullmatch(ref):
            continue
        record["requests"] += 1
        url = ECU_CASE.format(ref=ref)
        try:
            _, _, body = fetcher.get(url, "text/html")
        except FetchError as exc:
            record["failures"] += 1
            record["error"] = str(exc)[:200]
            continue
        if not page_mentions(body, ref):
            record["failures"] += 1
            record["error"] = "case page does not show %s" % ref
            continue
        named = next((a for a in project["aliases"] if page_mentions(body, alias_core(a))), None)
        made = item(project, "%s: Section 36 application %s (Energy Consents Unit case)" % (project["aliases"][0], ref),
                    url, "Scottish Government Energy Consents Unit", None,
                    "Energy Consents Unit case page for %s%s; title composed from the reference" % (
                        ref, ", which names '%s'" % alias_core(named) if named else ""),
                    "confirmed" if named else "uncertain")
        if made:
            made["kind"] = "case_page"
            items.append(made)
    record["items"] = len(items)
    return items, close_health(record)


# ---------------------------------------------------------------- run, report

def dedupe(items):
    seen, out = set(), []
    for it in items:
        key = (it["repd_ref"], it["link"])
        if key not in seen:
            seen.add(key)
            out.append(it)
    return out


def run(projects, fetcher, today, sources=("pins", "govuk", "ecu")):
    items, records, extra = [], [], {}
    if "pins" in sources:
        got, record, found = source_pins(projects, fetcher, today)
        items += got
        records.append(record)
        extra["pins_found"] = {ref: row["ref"] for ref, row in found.items()}
    if "govuk" in sources:
        got, record = source_govuk(projects, fetcher)
        items += got
        records.append(record)
    if "ecu" in sources:
        got, record = source_ecu(projects, fetcher)
        items += got
        records.append(record)
    return dedupe(items), records, extra


def build_part(items, records, now_iso):
    return {"schema": SCHEMA_PART, "team": "official", "generated_at": now_iso, "items": items, "sources": records}


def by_project(items):
    table = {}
    for it in items:
        table.setdefault(it["repd_ref"], []).append(it)
    for group in table.values():
        group.sort(key=lambda i: (i["date"] is not None, i["date"] or ""), reverse=True)
    return table


def cell(text):
    return str(text if text is not None else "").replace("|", "/").replace("\n", " ")


def probe_report(projects, items, records, now_iso):
    table = by_project(items)
    with_any = [p for p in projects if p["repd_ref"] in table]
    with_page = [p for p in projects if any(i.get("kind") == "govuk_page" for i in table.get(p["repd_ref"], []))]
    with_milestone = [p for p in projects
                      if any(i.get("kind") == "register_milestone" for i in table.get(p["repd_ref"], []))]
    without = [p for p in projects if p["repd_ref"] not in table]
    lines = ["## Official sources: %d of %d projects with at least one official signal" % (
        len(with_any), len(projects)), "",
        "Generated %s. GOV.UK page: %d projects; Planning Inspectorate register milestone: %d; "
        "Energy Consents Unit case page: %d; items: %d." % (
            now_iso, len(with_page), len(with_milestone),
            len({i["repd_ref"] for i in items if i.get("kind") == "case_page"}), len(items)), "",
        "| source | status | requests | failures | items | error |", "|---|---|---|---|---|---|"]
    for r in records:
        lines.append("| %s | %s | %s | %s | %s | %s |" % (r["id"], r["status"], r["requests"], r["failures"],
                                                           r["items"], cell(r["error"])))
    failed = [r["id"] for r in records if r["status"] != "ok"]
    lines += ["", "Sources that failed or were partial: %s" % (", ".join(failed) or "none"), "",
              "### Newest official signal per project", "",
              "| rank | REPD | alias | date | publisher | title | basis |", "|---|---|---|---|---|---|---|"]
    for p in with_any:
        top = table[p["repd_ref"]][0]
        lines.append("| %s | %s | %s | %s | %s | [%s](%s) | %s |" % (
            p["rank"], p["repd_ref"], cell(p["aliases"][0]), top["date"] or "", cell(top["publisher"]),
            cell(top["title"])[:110], top["link"], cell(top["basis"])[:110]))
    lines += ["", "### Projects with no official signal (%d)" % len(without), "",
              ", ".join("%s %s" % (p["repd_ref"], cell(p["aliases"][0])) for p in without) or "none", ""]
    return "\n".join(lines)


DISCOVER = [
    (PINS_CSV, "text/csv, */*"),
    (PINS_PROJECT.format(ref="EN010147"), "text/html"),
    (PINS_HOST + "/projects/EN010147/project-updates", "text/html"),
    (PINS_HOST + "/projects/EN010147/documents", "text/html"),
    (PINS_HOST + "/projects/EN0110020", "text/html"),
    (PINS_HOST + "/project-search?searchTerm=Botley", "text/html"),
    (govuk_url('"Botley West Solar Farm"', 5), "application/json"),
    (govuk_url("EN010147", 5), "application/json"),
    (govuk_url('"Cottam Solar Project"', 5), "application/json"),
    (ECU_CASE.format(ref="ECU00005085"), "text/html"),
    ("https://www.energyconsents.scot/ApplicationSearch.aspx", "text/html"),
    ("https://planningcasework.service.gov.wales/", "text/html"),
    ("https://planningcasework.service.gov.wales/en/case/CAS-01772-Z5P5D2", "text/html"),
    ("https://planningcasework.service.gov.wales/case/CAS-01772-Z5P5D2", "text/html"),
    ("https://planningcasework.service.gov.wales/en/case/DNS-3274702", "text/html"),
    ("https://planningcasework.service.gov.wales/en/case-search?q=CAS-01772-Z5P5D2", "text/html"),
    ("https://planningcasework.service.gov.wales/en/case-search?searchTerm=3274702", "text/html"),
]
HREF_RE = re.compile(r'href="([^"#]{2,200})"', re.I)


def discover(fetcher, urls=DISCOVER):
    """What each candidate source returns: status, type, size, title, first bytes and telling links. A CI aid."""
    lines = ["## Source discovery", ""]
    for url, accept in urls:
        lines.append("### `%s`" % url)
        try:
            final, ctype, body = fetcher.get(url, accept)
        except FetchError as exc:
            lines += ["FAILED: %s" % exc, ""]
            continue
        text = body.decode("utf-8", "replace")
        lines.append("ok; final `%s`; type `%s`; %d bytes; title: %s" % (final, ctype, len(body),
                                                                       cell(html_title(body))))
        if "html" in ctype:
            hrefs = [h for h in dict.fromkeys(HREF_RE.findall(text))
                     if re.search(r"project|case|EN0|ECU|update|document|download|api|search", h, re.I)]
            lines += ["links: " + " ; ".join("`%s`" % h for h in hrefs[:40]), "",
                      "text: " + cell(D.clean_text(re.sub(r"(?is)<(script|style).*?</\1>", " ", text), 1500))]
        else:
            lines += ["```", text[:1500].replace("```", "'''"), "```"]
        lines.append("")
    return "\n".join(lines)


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--out", default=None, help="write the part file (project-signals-part.v1) here")
    ap.add_argument("--probe", default=None, help="write a Markdown coverage report here")
    ap.add_argument("--discover", default=None, help="write a Markdown report of what each source returns and stop")
    ap.add_argument("--top", default=None)
    ap.add_argument("--aliases", default=None)
    ap.add_argument("--limit", type=int, default=0, help="only the first N projects by rank")
    ap.add_argument("--sources", default="pins,govuk,ecu")
    ap.add_argument("--now", default=None)
    args = ap.parse_args(argv)

    fetcher = Fetcher()
    if args.discover:
        report = discover(fetcher)
        Path(args.discover).write_text(report, encoding="utf-8")
        return 0
    now_iso = args.now or now_utc()
    projects = load_projects(args.top, args.aliases)
    if args.limit:
        projects = projects[:args.limit]
    items, records, _ = run(projects, fetcher, now_iso[:10], tuple(args.sources.split(",")))
    part = build_part(items, records, now_iso)
    if args.out:
        out = Path(args.out)
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(json.dumps(part, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    if args.probe:
        Path(args.probe).write_text(probe_report(projects, items, records, now_iso), encoding="utf-8")
    print(json.dumps({"projects": len(projects), "with_official_signal": len({i["repd_ref"] for i in items}),
                      "items": len(items), "sources": {r["id"]: r["status"] for r in records}}))
    return 1 if records and all(r["status"] == "failed" for r in records) else 0


if __name__ == "__main__":
    sys.exit(main())

Planning File

A Python command-line tool in the signals folder of GlobalGrid2050 that reads planning registers and the Renewable Energy Planning Database (REPD) register.

storageglobalgrid2050 / automation/news/signals/planning_file.py · lines 1–323 of 323 · Entry point · pattern probe_report (shared by 4 files)

What it does
It loads planning registers and the REPD register. Defines 13 functions or classes, including load_registers, _specific, _reference_forms, search_page, planning_file_for. Uses libraries __future__, argparse, json, re, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage site_feasibility (path word 'planning'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file planning_registers.json; command-line arguments.
Downstream impact
Used directly by 3 files: Combine (globalgrid2050); Test Signals Planning File (globalgrid2050); GlobalGrid2050 Project Signals Official Workflow (globalgrid2050). Reached from 3 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); News — Signals (globalgrid2050).
What it achieves
It loads registers (`load_registers`), searches page (`search_page`) and registers check (`register_check`). The planning-file fallback for the 200 largest solar projects in the REPD. It accepts `--out`, `--probe` and `--verify`.
Why it matters
Imported by Combine. Run by GlobalGrid2050 Project Signals Official Workflow. Checked by Test Signals Planning File.
Application
globalgrid2050 · automation/news/signals · Python CLI
Uses
Official (import), __future__, argparse, json, re, sys, urllib.parse, pathlib
Used by
imported by Combine (import), imported by Test Signals Planning File (sys.path import), run by GlobalGrid2050 Project Signals Official Workflow (workflow run)
Produces
load_registers, search_page, planning_file_for, verify, counts_of, build, probe_report, main
Defines here
load_registers, _specific, _reference_forms, search_page, planning_file_for, made, _check, verify, register_check, counts_of, build, probe_report, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/signals/planning_file.py:1-323 · blob 6aebc9505b483caa7ec383dc1bdc4166db36a2cd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: production_core
#!/usr/bin/env python3
"""The planning-file fallback for the 200 largest solar projects in the REPD.

Owner, 14 November 2026: "Default to its local authority planning application file if nothing significant
discovered." So every project gets one link to its planning file, of the best kind available:

  pins_project   the Planning Inspectorate project page for a national infrastructure reference (EN01xxxx)
  ecu_case       the Scottish Energy Consents Unit case for a Section 36 reference (ECU0000xxxx)
  pedw_case      the Planning and Environment Decisions Wales case, where a case address is known
  application    the local planning authority's own page for the application, where a direct address can be built
                 from the reference (or was recorded with the alias table)
  search_page    the authority's planning register search page, with the reference for the reader to paste

A planning file is labelled "planning file", carries the authority and the reference, and is never a news signal.
The table of authority to register is planning_registers.json (every authority among the 200; a test enforces it).

  planning_file_for(project) -> dict            offline, used by the combiner
  python automation/news/signals/planning_file.py --out planning-files.json [--verify] [--probe summary.md]
                                                [--official part-official.json]

--verify fetches each register home once and each direct link once (one request a second per host) and sets
"verified" from what answered: a direct link is verified when the page answers and shows the reference or the
project's name; a link that is gone (404, 410, no such host) falls back to the search page.
"""
from __future__ import annotations

import argparse
import json
import re
import sys
import urllib.parse
from pathlib import Path

HERE = Path(__file__).resolve().parent
if str(HERE) not in sys.path:
    sys.path.insert(0, str(HERE))

import official as O  # noqa: E402  Fetcher, load_projects, matching helpers

SCHEMA = "project-planning-files.v1"
LABEL = "planning file"
KINDS = ("pins_project", "ecu_case", "pedw_case", "application", "search_page")
DIRECT = ("pins_project", "ecu_case", "pedw_case", "application")
GENERIC_SEARCH = "https://www.gov.uk/search-register-planning-decisions"
GONE = (404, 410)
REGISTER_TIMEOUT_S = 10

_registers = None


def load_registers(path=None):
    global _registers
    if path is None and _registers is not None:
        return _registers
    table = json.loads(Path(path or HERE / "planning_registers.json").read_text(encoding="utf-8"))["authorities"]
    if path is None:
        _registers = table
    return table


def _specific(url, register):
    """A member-recorded address that points at a case, not at a register's front page."""
    u = urllib.parse.urlsplit(url)
    if u.scheme != "https" or not u.hostname:
        return False
    fronts = {(register or {}).get(k, "").rstrip("/") for k in ("home", "search", "council")}
    return url.rstrip("/") not in fronts and (len(u.path.strip("/")) > 0 or bool(u.query)) and \
        not re.search(r"search\.do\?action=(simple|advanced)", url)


def _reference_forms(ref):
    return {"ref": urllib.parse.quote(ref, safe="/"), "ref_lower_dashed": ref.lower().replace("/", "-"),
            "ref_digits": re.sub(r"\D", "", ref)}


def search_page(register, authority, reference, why=""):
    register = register or {}
    dead = register.get("check", {}).get("status") == "gone"
    url = (register.get("council") if dead else register.get("search") or register.get("home")) \
        or register.get("council") or GENERIC_SEARCH
    note = "Search the register for %s." % reference if reference else "Search the register for the site name."
    if register.get("notes"):
        note += " " + register["notes"]
    if why:
        note += " " + why
    return {"label": LABEL, "authority": register.get("label") or authority, "reference": reference, "url": url,
            "kind": "search_page", "verified": False, "note": note.strip()}


def planning_file_for(project, registers=None):
    """The best planning-file link for one project, without the network. `project` is a dict with planning_authority,
    planning_ref and, optionally, the alias table's planning_file (a member's finding)."""
    registers = load_registers() if registers is None else registers
    authority = (project.get("planning_authority") or "").strip()
    reference = (project.get("planning_ref") or "").strip()
    register = registers.get(authority)
    member = project.get("planning_file") if isinstance(project.get("planning_file"), dict) else None

    def made(kind, url, auth, ref, note="", verified=False):
        return {"label": LABEL, "authority": auth, "reference": ref, "url": url, "kind": kind,
                "verified": bool(verified), "note": note}

    pins = registers.get("The Planning Inspectorate - National Infrastructure", {})
    ecu = registers.get("Scottish Government (S36)", {})
    en_ref = reference.upper() if O.PINS_REF_RE.fullmatch(reference) else None
    if not en_ref and member and member.get("kind") == "pins_project":
        found = O.PINS_REF_RE.search("%s %s" % (member.get("url", ""), member.get("reference", "")))
        en_ref = found.group(0).upper() if found else None
    if en_ref:
        note = "" if en_ref == reference.upper() else \
            "REPD records the reference %s; the national infrastructure reference is %s." % (reference, en_ref)
        return made("pins_project", O.PINS_PROJECT.format(ref=en_ref),
                    pins.get("label", "Planning Inspectorate (national infrastructure)"), en_ref, note)
    if O.ECU_REF_RE.fullmatch(reference):
        return made("ecu_case", O.ECU_CASE.format(ref=reference.upper()),
                    ecu.get("label", "Scottish Government Energy Consents Unit"), reference.upper())
    if member and member.get("kind") in DIRECT and _specific(member.get("url", ""), register):
        return made(member["kind"], member["url"], (register or {}).get("label") or member.get("authority") or authority,
                    member.get("reference") or reference, "", member.get("verified") is True)
    if register and register.get("application") and reference and \
            re.fullmatch(register.get("ref_re", r".+"), reference):
        return made(register.get("kind", "application"), register["application"].format(**_reference_forms(reference)),
                    register.get("label") or authority, reference)
    if not register and member and str(member.get("url", "")).startswith("https://"):
        return made("search_page", member["url"], member.get("authority") or authority,
                    member.get("reference") or reference, "Search the register for %s." % reference)
    return search_page(register, authority, reference)


# ---------------------------------------------------------------- verification (network)

def _check(fetcher, url, cache):
    """('ok', body) | ('gone', reason) | ('blocked', reason): gone is a 404/410 or a host that does not resolve."""
    if url in cache:
        return cache[url]
    try:
        _, _, body = fetcher.get(url, "text/html, */*")
        result = ("ok", body)
    except O.FetchError as exc:
        text = str(exc)
        gone = exc.status in GONE or "Name or service not known" in text or "No address associated" in text \
            or "getaddrinfo" in text or "nodename nor servname" in text
        result = ("gone" if gone else "blocked", text[:120])
    cache[url] = result
    return result


def verify(projects, fetcher, registers=None):
    """Planning files with "verified" set from the network, and one health record per register."""
    registers = load_registers() if registers is None else registers
    cache, files, checks = {}, {}, {}

    def register_check(authority):
        register = registers.get(authority)
        if register is None:
            return None
        if authority not in checks:
            record = {"authority": authority, "url": register.get("search") or register.get("home"),
                      "status": "", "error": "", "used": ""}
            status, detail = _check(fetcher, record["url"], cache)
            if status != "ok" and register.get("search") and register.get("home"):
                status2, detail2 = _check(fetcher, register["home"], cache)
                if status2 == "ok":
                    status, detail, record["url"] = status2, detail2, register["home"]
            record["status"] = status
            if status == "ok":
                record["used"] = record["url"]
            else:
                record["error"] = detail
                if register.get("council"):
                    status3, _ = _check(fetcher, register["council"], cache)
                    if status3 == "ok":
                        record["used"] = register["council"]
                        record["status"] = "council_page_only" if status == "gone" else "blocked"
            checks[authority] = record
        return checks[authority]

    for project in projects:
        made = dict(planning_file_for(project, registers))
        made["verified"] = False
        made["check"] = ""
        authority = project.get("planning_authority", "")
        if made["kind"] in DIRECT:
            status, detail = _check(fetcher, made["url"], cache)
            if status == "ok":
                names = [O.alias_core(a) for a in project.get("aliases", [])]
                if O.page_mentions(detail, made["reference"], *names):
                    made["verified"], made["check"] = True, "page answers and shows the reference or the name"
                elif made["url"].lower().endswith(".pdf"):
                    made["verified"], made["check"] = True, "document answers"
                else:
                    made["check"] = "page answers but does not show the reference"
            elif status == "blocked":
                made["check"] = "not fetched (%s); link kept, unverified" % detail
            else:
                made = search_page(registers.get(authority), authority, project.get("planning_ref", ""),
                                   "The direct link did not answer (%s)." % detail)
                made["check"] = "direct link gone"
        if made["kind"] == "search_page":
            record = register_check(authority)
            if record is None:
                made["check"] = made.get("check") or "authority not in the register table"
            elif record["status"] == "ok":
                made["url"] = record["url"]
                made["check"] = (made.get("check") + "; " if made.get("check") else "") + "register page answers"
            elif record["used"]:
                if record["status"] == "council_page_only":
                    made["url"] = record["used"]
                made["check"] = "register page: %s (%s)" % (record["status"], record["error"])
            else:
                made["check"] = "register page: %s (%s)" % (record["status"], record["error"])
            made["register_status"] = record["status"] if record else "unknown"
        files[project["repd_ref"]] = made
    return files, [checks[a] for a in sorted(checks)]


# ---------------------------------------------------------------- output

def counts_of(files, total):
    direct_ok = [r for r, f in files.items() if f["kind"] in DIRECT and f["verified"]]
    direct_unverified = [r for r, f in files.items() if f["kind"] in DIRECT and not f["verified"]]
    search = [r for r, f in files.items() if f["kind"] == "search_page"]
    return {"projects": total, "with_planning_file": len(files), "verified_direct": len(direct_ok),
            "direct_unverified": len(direct_unverified), "search_page": len(search),
            "search_page_register_answers": sum(1 for r in search if files[r].get("register_status") == "ok"),
            "nothing": total - len(files),
            "by_kind": {k: sum(1 for f in files.values() if f["kind"] == k) for k in KINDS}}


def build(projects, files, register_records, now_iso, verified_run):
    return {"schema": SCHEMA, "generated_at": now_iso, "verified_run": verified_run,
            "counts": counts_of(files, len(projects)),
            "projects": {p["repd_ref"]: {"repd_ref": p["repd_ref"], "planning_file": files[p["repd_ref"]]}
                         for p in projects if p["repd_ref"] in files},
            "registers": register_records}


def probe_report(projects, files, register_records, now_iso, official=None):
    c = counts_of(files, len(projects))
    signalled = {i["repd_ref"] for i in (official or {}).get("items", [])}
    verified = {r for r, f in files.items() if f["kind"] in DIRECT and f["verified"]}
    search_only = [p for p in projects if p["repd_ref"] not in signalled and p["repd_ref"] not in verified
                   and files.get(p["repd_ref"], {}).get("kind") == "search_page"]
    unverified_only = [p for p in projects if p["repd_ref"] not in signalled and p["repd_ref"] not in verified
                       and files.get(p["repd_ref"], {}).get("kind") in DIRECT]
    nothing = [p for p in projects if p["repd_ref"] not in signalled and p["repd_ref"] not in files]
    failed = ["%s (%s)" % (s["id"], s["status"]) for s in (official or {}).get("sources", []) if s["status"] != "ok"]
    bad_registers = [r for r in register_records if r["status"] != "ok"]
    lines = ["## Project signals, official sources and planning files: %d projects" % len(projects), "",
             "Generated %s." % now_iso, "",
             "| measure | projects |", "|---|---|"]
    if official is not None:
        lines.append("| at least one official signal | %d |" % len(signalled))
    lines += ["| a verified planning file (direct link that answered and shows the reference or name) | %d |" % len(verified),
              "| a direct planning-file link that could not be verified from here | %d |" % c["direct_unverified"],
              "| a search-page planning file | %d (register page answered for %d) |" % (
                  c["search_page"], c["search_page_register_answers"])]
    if official is not None:
        lines += ["| no official signal and no verified file: only a search-page fallback | %d |" % len(search_only),
                  "| no official signal and only an unverified direct link | %d |" % len(unverified_only),
                  "| an official signal or a planning file (the guarantee) | %d |" % (len(projects) - len(nothing))]
    lines += ["| nothing at all | %d |" % len(nothing), "",
              "Planning files by kind: " + ", ".join("%s %d" % (k, v) for k, v in c["by_kind"].items()), "",
              "Sources that failed or were partial: %s" % (", ".join(failed) or "none"), "",
              "Registers that did not answer: %d of %d checked" % (len(bad_registers), len(register_records)), ""]
    if bad_registers:
        lines += ["| authority | status | address tried | error | page used |", "|---|---|---|---|---|"]
        lines += ["| %s | %s | %s | %s | %s |" % (O.cell(r["authority"]), r["status"], r["url"], O.cell(r["error"]),
                                                 r["used"]) for r in bad_registers]
        lines.append("")
    lines += ["Projects with nothing: %s" % (", ".join("%s %s" % (p["repd_ref"], O.cell(p["site_name"]))
                                                       for p in nothing) or "none"), "",
              "### Planning file per project", "",
              "| rank | REPD | project | authority | reference | kind | verified | check |",
              "|---|---|---|---|---|---|---|---|"]
    for p in projects:
        f = files.get(p["repd_ref"])
        if f:
            lines.append("| %s | %s | %s | %s | [%s](%s) | %s | %s | %s |" % (
                p["rank"], p["repd_ref"], O.cell(p["aliases"][0]), O.cell(f["authority"]),
                O.cell(f["reference"]) or "(none)", f["url"].replace(" ", "%20"), f["kind"],
                "yes" if f["verified"] else "no", O.cell(f.get("check", ""))[:90]))
    lines.append("")
    return "\n".join(lines)


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--out", default=None, help="write the planning files (project-planning-files.v1) here")
    ap.add_argument("--probe", default=None, help="write a Markdown report here")
    ap.add_argument("--verify", action="store_true", help="fetch register pages and direct links to set 'verified'")
    ap.add_argument("--official", default=None, help="the official part file, to report combined coverage")
    ap.add_argument("--top", default=None)
    ap.add_argument("--aliases", default=None)
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--now", default=None)
    args = ap.parse_args(argv)

    now_iso = args.now or O.now_utc()
    projects = O.load_projects(args.top, args.aliases)
    if args.limit:
        projects = projects[:args.limit]
    if args.verify:
        O.TIMEOUT_S = REGISTER_TIMEOUT_S        # many council hosts do not answer a datacentre address: do not wait long
        files, records = verify(projects, O.Fetcher())
    else:
        files, records = {p["repd_ref"]: planning_file_for(p) for p in projects}, []
    result = build(projects, files, records, now_iso, args.verify)
    if args.out:
        out = Path(args.out)
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(json.dumps(result, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    if args.probe:
        official = None
        if args.official and Path(args.official).exists():
            official = json.loads(Path(args.official).read_text(encoding="utf-8"))
        Path(args.probe).write_text(probe_report(projects, files, records, now_iso, official), encoding="utf-8")
    print(json.dumps(result["counts"]))
    return 1 if result["counts"]["nothing"] else 0


if __name__ == "__main__":
    sys.exit(main())