GLOBALGRID2050 / EXPLORE CODE

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

Trade (part 1)

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

700 lines of Python from globalgrid2050, in 1 file. Topic: Electricity markets and data pipelines. Section 798 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. Trade storage · globalgrid2050 / automation/news/signals/trade.py lines 1–700

Trade

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

storageglobalgrid2050 / automation/news/signals/trade.py · lines 1–700 of 1312 · Entry point · pattern HttpError (shared by 2 files)

What it does
It fetches aliases, cache, solar and the REPD register. Defines 56 functions or classes, including now_utc, iso, Robots, __init__, _parse. Uses libraries __future__, argparse, datetime, json, re. 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: solar, the REPD register.
Inputs & outputs
In: JSON file aliases.json; JSON file .cache.json; command-line arguments.
Downstream impact
Used directly by 2 files: Test Signals Trade (globalgrid2050); GlobalGrid2050 Project Signals Trade Workflow (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It fetches URL (`fetch_url`), parses HTML results (`parse_html_results`) and parses results (`parse_results`). Trade-press signals for the 200 largest REPD solar projects (team "trade" of the project-signals contract). Its code works with 740 MW. It accepts `--out`, `--aliases` and `--cache`.
Why it matters
Run by GlobalGrid2050 Project Signals Trade Workflow. Checked by Test Signals Trade.
Application
globalgrid2050 · automation/news/signals · Python CLI
Uses
Datacentre Feed (sys.path import), Dates (import), Gate (import), Pipeline Headlines (sys.path import), __future__, argparse, datetime, json, re, sys, threading, time
Used by
imported by Test Signals Trade (sys.path import), run by GlobalGrid2050 Project Signals Trade Workflow (workflow run)
Produces
now_utc, iso, Robots, HttpError, fetch_url, Host, day_of, date_near, parse_html_results, parse_results, parse_sitemap, html_unescape
Defines here
now_utc, iso, Robots, __init__, _parse, _regex, allowed, HttpError, fetch_url, Host, __init__, _wait, _robots, spent, get, _valid_date, day_of, _tomorrow, date_near, parse_html_results, parse_results, parse_sitemap, html_unescape, slug_words, parse_article_head, route_url, straight, fold, bounded, core_of
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/trade.py:1-700 · blob 3ce1682e1cb059ebb6a7de3389d9fe7f701ff916 · 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
#!/usr/bin/env python3
"""Trade-press signals for the 200 largest REPD solar projects (team "trade" of the project-signals contract).

For each project and each alias in automation/news/signals/aliases.json this script asks each trade site's own
public search for the alias and keeps the results whose HEADLINE names the project. It also reads each site's
main feed once a run and matches every alias against it, so fresh news is caught for all 200 every day.

  python3 automation/news/signals/trade.py --out dist/project_signals_trade.json --cache dist/trade_cache.json
  python3 automation/news/signals/trade.py --out part.json --probe summary.md --discover --batch 200

Sites, in priority order (owner: Solar Power Portal is the second primary source after BBC News):
Solar Power Portal, PV Tech, pv magazine, Energy-Storage.news, Current, reNEWS, Planning Resource,
Construction Enquirer, Solar Energy UK.

Rules
- Headlines and links only: title, link, publisher, date. Summaries are never stored; no article page is
  requested.
- robots.txt of every host is fetched first and honoured (the group for this User-Agent, else "*"; Allow,
  Disallow with * and $, Crawl-delay). A search route that robots.txt disallows is recorded as
  "refused by robots.txt" and never requested.
- One request a second per host at most (longer when Crawl-delay says so), HTTP 429: wait ten seconds and retry
  once, a request cap per host and per run, a time budget per host. One site failing never stops the run.
- Each site has an ordered list of search routes (WordPress REST posts search, WordPress RSS search, the site's
  HTML results page, WordPress REST search). The first route that answers a canary query with parsable results
  is used for the run; --discover tries every route and reports what each one returns.
- A result counts only when its title contains the alias phrase, whole words, case-insensitive. The phrase is
  the alias without its generic tail ("Botley West Solar Farm" -> "Botley West"). A short or common phrase
  (one word, or only everyday words such as "Low Farm") also needs a second agreeing term in the title: the
  developer, the county, the planning authority, or a solar word. A planning reference (EN010147) in the title
  matches on its own. The basis line of every item says which of these applied.
- Summary rule of the contract, as a fallback: when the headline does not name the project but the search or
  feed summary contains the alias phrase AND the developer, county, planning authority or planning reference
  agrees, the item is kept with confidence "uncertain" and a basis that says so. The summary itself is read in
  memory and never stored.
- A title containing one of the project's "exclude" phrases is dropped. Aliases with alias_status "derived" or
  "uncertain" give items with confidence "uncertain".
- Cache and rotation: the cache file is keyed by site and query and stores only matching headlines. A run
  searches the --batch (default 40) least recently searched projects, plus any project whose last search is
  older than --stale-days (default 30); a query younger than --fresh-days (default 4) is never repeated. At
  one run a day the 200 projects are covered in five runs (five days) and every project is searched again
  every five days; a cold start with an empty cache takes the same five runs. The main feeds are read on
  every run for all 200.
- Feed archive (Solar Power Portal): its RSS feed takes limit and offset, so the script pages backwards
  through the whole archive, --feed-pages (default 30) pages of 100 headlines a run, and applies the title rule
  and the summary rule to every item for all 200 projects; when the end is reached it starts again after
  --stale-days.
- Sitemap route (a site with no usable search, such as Solar Power Portal, whose robots.txt disallows /search):
  the sitemap files named in robots.txt are read, --sitemap-files (default 90) a run, those never read first;
  an article link whose path contains an alias phrase is kept and its headline and date are taken from the
  article page's own metadata, --page-lookups (default 60) a run, the newest link of each project first. Only
  the headline and the date are kept. The whole sitemap is covered in about five runs and re-read in rotation.
- Fetch failure handling, feed parsing, dates, canonical links and text cleaning are imported from
  datacentre_feed.py; nothing is copied.
"""
from __future__ import annotations

import argparse
import datetime as dt
import json
import re
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

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

import datacentre_feed as D  # noqa: E402  parse_feed, parse_date, canonical_link, clean_text, limits
import dates as DATES  # noqa: E402  one date rule shared by the collectors and the combiner
import gate as GATE  # noqa: E402  the title gate shared with official.py, index.py and combine.py
import pipeline_headlines as P  # noqa: E402  FOREIGN and UK_WORDS: a headline naming another country is not UK news

SCHEMA = "project-signals-part.v1"
CACHE_SCHEMA = "project-signals-trade-cache.v1"
TEAM = "trade"
UA_TOKEN = "GlobalGrid2050-ProjectSignals"
USER_AGENT = UA_TOKEN + "/1.0 (+https://globalgrid2050.com)"
MIN_INTERVAL_S = 1.0
RETRY_429_S = 10.0
CANARY = "solar farm"
MAX_TERMS_PER_PROJECT = 2
PER_PUBLISHER = 5
BREAKER = 6  # consecutive failures after which a site is left alone for the rest of the run

WP_POSTS = "/wp-json/wp/v2/posts?search={q}&per_page=20&orderby=relevance&_fields=title,link,date,excerpt"
WP_SEARCH = "/wp-json/wp/v2/search?search={q}&per_page=20"
WP_RSS = "/?s={q}&feed=rss2"
WP_FEED = "/feed/?s={q}"

# id, publisher, base, main feeds, ordered search routes (kind, path template).
SITES = [
    {"id": "solar-power-portal", "publisher": "Solar Power Portal", "base": "https://www.solarpowerportal.co.uk",
     "feeds": ["https://www.solarpowerportal.co.uk/rss.xml?content_types=article&limit=100"],
     "routes": [("html", "/search?q={q}"), ("wp_posts", WP_POSTS), ("sitemap", "/sitemap.xml")],
     "feed_archive": "https://www.solarpowerportal.co.uk/rss.xml?content_types=article&limit=100&offset={offset}",
     "feed_archive_step": 100},
    {"id": "pv-tech", "publisher": "PV Tech", "base": "https://www.pv-tech.org",
     "feeds": ["https://www.pv-tech.org/feed/"],
     "routes": [("wp_posts", WP_POSTS), ("wp_rss", WP_RSS), ("wp_rss", WP_FEED), ("html", "/?s={q}"),
                ("wp_search", WP_SEARCH)]},
    {"id": "pv-magazine", "publisher": "pv magazine", "base": "https://www.pv-magazine.com",
     "feeds": ["https://www.pv-magazine.com/feed/"],
     "routes": [("wp_posts", WP_POSTS), ("wp_rss", WP_RSS), ("wp_rss", WP_FEED), ("html", "/?s={q}"),
                ("wp_search", WP_SEARCH)]},
    {"id": "energy-storage-news", "publisher": "Energy-Storage.news", "base": "https://www.energy-storage.news",
     "feeds": ["https://www.energy-storage.news/feed/"],
     "routes": [("wp_posts", WP_POSTS), ("wp_rss", WP_RSS), ("wp_rss", WP_FEED), ("html", "/?s={q}"),
                ("wp_search", WP_SEARCH)]},
    {"id": "current", "publisher": "Current", "base": "https://www.current-news.co.uk",
     "feeds": ["https://www.current-news.co.uk/feed/"],
     "routes": [("wp_posts", WP_POSTS), ("wp_rss", WP_RSS), ("wp_rss", WP_FEED), ("html", "/?s={q}"),
                ("wp_search", WP_SEARCH)]},
    {"id": "renews", "publisher": "reNEWS", "base": "https://renews.biz",
     "feeds": ["https://feeds.feedburner.com/Renews-RenewableEnergyNews"],
     "routes": [("wp_posts", WP_POSTS)]},
    {"id": "planning-resource", "publisher": "Planning Resource", "base": "https://www.planningresource.co.uk",
     "feeds": ["https://www.planningresource.co.uk/rss/news"],
     "routes": [("html", "/search/articles?KeyWords={q}"), ("html", "/search?q={q}")]},
    {"id": "construction-enquirer", "publisher": "Construction Enquirer",
     "base": "https://www.constructionenquirer.com",
     "feeds": ["https://www.constructionenquirer.com/feed/"],
     "routes": [("wp_posts", WP_POSTS), ("wp_rss", WP_RSS), ("wp_rss", WP_FEED), ("html", "/?s={q}"),
                ("wp_search", WP_SEARCH)]},
    {"id": "solar-energy-uk", "publisher": "Solar Energy UK", "base": "https://solarenergyuk.org",
     "feeds": ["https://solarenergyuk.org/feed/"],
     "routes": [("wp_posts", WP_POSTS), ("wp_rss", WP_RSS), ("wp_rss", WP_FEED), ("html", "/?s={q}"),
                ("wp_search", WP_SEARCH)]},
]


SITE_SUFFIX = re.compile(r"\s*[|\-\u2013\u2014]\s*(?:%s)\s*$" % "|".join(re.escape(x["publisher"]) for x in SITES), re.I)


def now_utc():
    return dt.datetime.now(dt.timezone.utc).replace(microsecond=0)


def iso(moment):
    return moment.isoformat().replace("+00:00", "Z")


# ---------------------------------------------------------------- robots.txt

class Robots:
    """Rules of one robots.txt for this User-Agent. Missing or unreadable file: everything allowed (RFC 9309
    for 4xx); a 5xx or network error on robots.txt: nothing allowed for the run."""

    def __init__(self, text=None, blocked=False):
        self.rules, self.delay, self.sitemaps, self.blocked = [], None, [], blocked
        if text:
            self._parse(text)

    def _parse(self, text):
        groups, agents, rules, fresh = [], [], [], True
        for raw in text.splitlines():
            line = raw.split("#", 1)[0].strip()
            if ":" not in line:
                continue
            key, value = (part.strip() for part in line.split(":", 1))
            key = key.lower()
            if key == "sitemap":
                self.sitemaps.append(value)
            elif key == "user-agent":
                if not fresh:
                    groups.append((agents, rules))
                    agents, rules, fresh = [], [], True
                agents.append(value.lower())
            elif key in ("allow", "disallow", "crawl-delay"):
                fresh = False
                rules.append((key, value))
        groups.append((agents, rules))
        token = UA_TOKEN.lower()
        chosen = [r for a, r in groups if any(x != "*" and x in token for x in a)] or \
                 [r for a, r in groups if "*" in a]
        for rules in chosen:
            for key, value in rules:
                if key == "crawl-delay":
                    try:
                        self.delay = max(self.delay or 0.0, float(value))
                    except ValueError:
                        pass
                elif value:
                    self.rules.append((key == "allow", value, self._regex(value)))

    @staticmethod
    def _regex(pattern):
        end = pattern.endswith("$")
        body = "".join(".*" if ch == "*" else re.escape(ch) for ch in pattern.rstrip("$"))
        return re.compile(body + ("$" if end else ""))

    def allowed(self, url):
        if self.blocked:
            return False
        parts = urllib.parse.urlsplit(url)
        target = (parts.path or "/") + ("?" + parts.query if parts.query else "")
        best = None
        for allow, pattern, regex in self.rules:
            if regex.match(target):
                rank = (len(pattern), allow)
                if best is None or rank > best:
                    best = rank
        return True if best is None else best[1]


# ---------------------------------------------------------------- fetching

class HttpError(Exception):
    pass


def fetch_url(url):
    """(content type, body bytes). Raises HttpError with a short reason."""
    request = urllib.request.Request(url, headers={
        "User-Agent": USER_AGENT,
        "Accept": "application/json, application/rss+xml, application/atom+xml, application/xml, text/html;q=0.8"})
    try:
        with urllib.request.urlopen(request, timeout=D.TIMEOUT_S) as response:  # noqa: S310 (fixed https list)
            return response.headers.get("Content-Type", ""), response.read(D.MAX_BYTES + 1)
    except urllib.error.HTTPError as error:
        raise HttpError("HTTP %d" % error.code) from None
    except Exception as error:  # network, TLS, timeout
        raise HttpError((type(error).__name__ + ": " + str(error))[:160]) from None


class Host:
    """Polite access to one site: robots.txt, spacing, the 429 rule, caps, counters."""

    def __init__(self, site, fetch, cap, seconds, sleep=time.sleep, clock=time.monotonic):
        self.site, self.fetch, self.cap, self.seconds = site, fetch, cap, seconds
        self.sleep, self.clock = sleep, clock
        self.last = {}
        self.started = clock()
        self.requests = self.failures = self.streak = 0
        self.robots = {}
        self.notes = []

    def _wait(self, host, interval):
        due = self.last.get(host, -1e9) + interval
        pause = due - self.clock()
        if pause > 0:
            self.sleep(pause)
        self.last[host] = self.clock()

    def _robots(self, url):
        parts = urllib.parse.urlsplit(url)
        host = parts.netloc
        if host not in self.robots:
            self._wait(host, MIN_INTERVAL_S)
            self.requests += 1
            try:
                _ctype, body = self.fetch("%s://%s/robots.txt" % (parts.scheme, host))
                self.robots[host] = Robots(body.decode("utf-8", "replace"))
            except HttpError as error:
                missing = re.match(r"HTTP 4\d\d", str(error)) is not None
                self.robots[host] = Robots(blocked=not missing)
                self.notes.append("robots.txt %s: %s (%s)" % (host, error,
                                                              "treated as no rules" if missing else "host skipped"))
        return self.robots[host]

    def spent(self):
        if self.requests >= self.cap:
            return "request cap of %d reached" % self.cap
        if self.clock() - self.started > self.seconds:
            return "time budget of %d s reached" % self.seconds
        if self.streak >= BREAKER:
            return "%d failures in a row" % self.streak
        return None

    def get(self, url):
        """(content type, body) or raises HttpError. 'refused by robots.txt' is raised without a request."""
        robots = self._robots(url)
        if not robots.allowed(url):
            raise HttpError("refused by robots.txt")
        reason = self.spent()
        if reason:
            raise HttpError(reason)
        host = urllib.parse.urlsplit(url).netloc
        interval = max(MIN_INTERVAL_S, robots.delay or 0.0)
        for attempt in (1, 2):
            self._wait(host, interval)
            self.requests += 1
            try:
                result = self.fetch(url)
                self.streak = 0
                return result
            except HttpError as error:
                if attempt == 1 and str(error) == "HTTP 429":
                    self.sleep(RETRY_429_S)
                    continue
                self.failures += 1
                self.streak += 1
                raise


# ---------------------------------------------------------------- reading search results

MONTHS = {m: i + 1 for i, m in enumerate(
    ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"))}
A_RE = re.compile(r"<a\b([^>]*)>(.*?)</a>", re.I | re.S)
HREF_RE = re.compile(r"""\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')""", re.I)
DATETIME_RE = re.compile(r"""\bdatetime\s*=\s*["'](\d{4}-\d{2}-\d{2})""", re.I)
DMY_RE = re.compile(r"\b(\d{1,2})(?:st|nd|rd|th)?\s+([A-Za-z]{3})[a-z]*\.?,?\s+(\d{4})\b")
MDY_RE = re.compile(r"\b([A-Za-z]{3})[a-z]*\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(\d{4})\b")
URL_DATE_RE = re.compile(r"/(20\d{2})/(\d{1,2})/(\d{1,2})/")


def _valid_date(year, month, day):
    try:
        return dt.date(int(year), int(month), int(day)).isoformat()
    except (TypeError, ValueError):
        return None


def day_of(value):
    """YYYY-MM-DD from an RSS, Atom or ISO date; None when unreadable. A WordPress REST date has no zone."""
    found = DATES.day(value)        # the publisher's own calendar day, whatever the zone or the lack of one
    if found:
        return found
    stamp = D.parse_date(value)
    if stamp:
        return stamp[:10]
    found = re.match(r"\s*(\d{4})-(\d{2})-(\d{2})", value or "")
    return _valid_date(*found.groups()) if found else None


def _tomorrow():
    return (dt.datetime.now(dt.timezone.utc).date() + dt.timedelta(days=1)).isoformat()


def date_near(text):
    """A date in a fragment of results-page markup: <time datetime>, '10 November 2026' or 'Nov 10, 2026'."""
    found = DATETIME_RE.search(text)
    if found:
        return found.group(1)
    plain = D.clean_text(text, 4000)
    best = None                                             # the date written nearest the headline, whatever its spelling
    for regex, order in ((DMY_RE, (2, 1, 0)), (MDY_RE, (2, 0, 1))):
        for found in regex.finditer(plain):
            parts = found.groups()
            month = MONTHS.get(parts[order[1]].lower()[:3])
            date = month and _valid_date(parts[order[0]], month, parts[order[2]])
            if date and date <= _tomorrow() and (best is None or found.start() < best[0]):
                best = (found.start(), date)                # a date still to come is an event date, not a publication date
                break
    return best[1] if best else None


def parse_html_results(body, base):
    """[(title, link, date, "")] from a results page: every same-site link whose text reads like a headline. The
    date is the first one in the markup that follows the link (before the next headline link), else the date in
    the link itself. The alias rule decides afterwards which of these count."""
    text = body.decode("utf-8", "replace")
    host = urllib.parse.urlsplit(base).netloc.removeprefix("www.")
    found = []
    for match in A_RE.finditer(text):
        href = HREF_RE.search(match.group(1))
        title = D.clean_text(match.group(2), 300)
        if not href or len(title) < 20 or len(title.split()) < 4:
            continue
        link = D.canonical_link(urllib.parse.urljoin(base + "/", href.group(1) or href.group(2) or ""))
        if not link or urllib.parse.urlsplit(link).netloc.removeprefix("www.") != host:
            continue
        found.append((title, link, match.end()))
    out, seen = [], set()
    for index, (title, link, end) in enumerate(found):
        if link in seen:
            continue
        seen.add(link)
        stop = found[index + 1][2] if index + 1 < len(found) else len(text)
        url_date = URL_DATE_RE.search(link)
        date = date_near(text[end:min(stop, end + 1500)]) or (url_date and _valid_date(*url_date.groups()))
        out.append((title, link, date or None, ""))
    return out


def parse_results(kind, body, base):
    """[(title, link, date, summary)] for one search route; the summary is read in memory for the summary rule
    and is never written anywhere. Raises ValueError when the answer is not what the route
    promises (an HTML challenge page where JSON was expected, for example)."""
    if kind in ("wp_posts", "wp_search"):
        try:
            rows = json.loads(body.decode("utf-8", "replace"))
        except ValueError:
            raise ValueError("not JSON") from None
        if not isinstance(rows, list):
            raise ValueError("JSON is not a list")
        out = []
        for row in rows:
            if not isinstance(row, dict):
                continue
            title = row.get("title")
            if isinstance(title, dict):
                title = title.get("rendered")
            link = D.canonical_link(row.get("link") or row.get("url") or "")
            title = D.clean_text(title if isinstance(title, str) else "", 300)
            excerpt = row.get("excerpt")
            if isinstance(excerpt, dict):
                excerpt = excerpt.get("rendered")
            if title and link:
                out.append((title, link, day_of(row.get("date_gmt") or row.get("date") or ""),
                            D.clean_text(excerpt if isinstance(excerpt, str) else "", 1500)))
        return out
    if kind in ("wp_rss", "feed"):
        out = []
        for title, link, date, summary in D.parse_feed(body):
            title, link = D.clean_text(title, 300), D.canonical_link(link)
            if title and link:
                out.append((title, link, day_of(date), D.clean_text(summary, 1500)))
        return out
    if kind == "html":
        return parse_html_results(body, base)
    raise ValueError("unknown route kind %s" % kind)


LOC_RE = re.compile(r"<loc>\s*(?:<!\[CDATA\[)?\s*([^<\]\s]+)", re.I)
URL_RE = re.compile(r"<url>(.*?)</url>", re.I | re.S)
LASTMOD_RE = re.compile(r"<lastmod>\s*(\d{4}-\d{2}-\d{2})", re.I)
NEWS_TITLE_RE = re.compile(r"<news:title>\s*(?:<!\[CDATA\[)?(.*?)(?:\]\]>)?\s*</news:title>", re.I | re.S)
NEWS_DATE_RE = re.compile(r"<news:publication_date>\s*(\d{4}-\d{2}-\d{2})", re.I)
META_RE = re.compile(r"<meta\b[^>]*>", re.I)
ATTR_RE = re.compile(r"""\b(property|name|content)\s*=\s*(?:"([^"]*)"|'([^']*)')""", re.I)
PUBLISHED_RE = re.compile(r""""datePublished"\s*:\s*"(\d{4}-\d{2}-\d{2})""")
H1_RE = re.compile(r"<h1\b[^>]*>(.*?)</h1>", re.I | re.S)
TITLE_TAG_RE = re.compile(r"<title[^>]*>(.*?)</title>", re.I | re.S)


def parse_sitemap(body):
    """('index', [sitemap urls]) or ('urls', [(loc, lastmod, news title, news date)]). Read with regular
    expressions so that a file cut off at the size limit still gives its complete entries."""
    text = body.decode("utf-8", "replace")
    if "<sitemapindex" in text[:3000].lower():
        return "index", [html_unescape(u) for u in LOC_RE.findall(text)]
    out = []
    for block in URL_RE.findall(text):
        loc = LOC_RE.search(block)
        if not loc:
            continue
        lastmod, title, date = LASTMOD_RE.search(block), NEWS_TITLE_RE.search(block), NEWS_DATE_RE.search(block)
        out.append((html_unescape(loc.group(1)), lastmod.group(1) if lastmod else None,
                    D.clean_text(title.group(1), 300) if title else "", date.group(1) if date else None))
    return "urls", out


def html_unescape(value):
    return D.clean_text(value, 2000)


def slug_words(text):
    """Lower-case words of a URL path or a phrase, for matching an alias against a link: 'Bloy's Grove' and
    '/solar-projects/edf-renewables-50mw-bloy-s-grove-solar-farm' both give '... bloy s grove ...'."""
    return " " + " ".join(re.findall(r"[a-z0-9]+", urllib.parse.unquote(text).lower().replace("\u2019", "'"))) + " "


def parse_article_head(body):
    """(headline, YYYY-MM-DD or None) from an article page's own metadata (og:title, article:published_time,
    datePublished). Nothing else of the page is read or kept."""
    text = body.decode("utf-8", "replace")
    meta = {}
    for tag in META_RE.findall(text):
        attrs = {k.lower(): (a or b) for k, a, b in ATTR_RE.findall(tag)}
        key = (attrs.get("property") or attrs.get("name") or "").lower()
        if key and "content" in attrs:
            meta.setdefault(key, attrs["content"])
    title = D.clean_text(meta.get("og:title") or meta.get("twitter:title") or "", 300)
    if not title:
        found = TITLE_TAG_RE.search(text)
        title = re.sub(r"\s+[|\-\u2013]\s+[^|\-\u2013]{3,40}$", "", D.clean_text(found.group(1) if found else "", 300))
    title = SITE_SUFFIX.sub("", title)
    h1 = H1_RE.search(text)
    h1 = D.clean_text(h1.group(1), 300) if h1 else ""
    if title and len(h1) > len(title) and h1.lower().startswith(title.lower().rstrip(". ")):
        title = h1  # the page's own headline when the metadata carries a shortened one
    date = day_of(meta.get("article:published_time") or meta.get("og:article:published_time") or "")
    if not date:
        found = PUBLISHED_RE.search(text)
        date = found.group(1) if found else None
    return title, date


def route_url(site, template, term):
    return site["base"] + template.format(q=urllib.parse.quote_plus(term))


# ---------------------------------------------------------------- aliases and the title rule

KEYWORD = re.compile(r"\s+(?:solar|energy|energyfarm|renewables?|photovoltaics?|pv|battery|bess)(?!\w)", re.I)
TAIL = re.compile(r"(?:\s+(?:farm|park|project|scheme|array|plant|development|ltd|limited|nsip|dco))+\s*$", re.I)
ADJACENT = (r"(?:[\s\-]+[\w&'.]+){0,2}?[\s\-]+(?:solar|photovoltaics?|pv|energyfarm|(?:renewable\s+)?energy\s+(?:park|farm|project|centre|hub)"
            r"|(?:green|clean)\s+energy)(?!\w)")
COMMON = frozenset(
    "farm farms hill hills lane manor house park grange hall wood woods green north south east west great little "
    "new old high low lower upper moor field fields bridge road drove mill church land lands meadow meadows "
    "marsh fen common court lodge cottage barn home top end side long big cross way gate lakes lake valley "
    "airfield quarry airport the of and at on".split())
ELSEWHERE = re.compile(
    r"(?<!\w)(?:New Zealand|Kenya|Chile|Mexico|Portugal|Romania|Bulgaria|Hungary|Turkey|Türkiye|Saudi|UAE|Egypt|"
    r"South Africa|Indonesia|Malaysia|Thailand|Pakistan|Bangladesh|Colombia|Argentina|Peru|Ontario|Alberta|"
    r"Arizona|Nevada|Florida|Ohio|Indiana|Virginia|Illinois|Tasmania|Western Australia|Austria|Switzerland|"
    r"Croatia|Serbia|Ukraine|Lithuania|Latvia|Estonia|Czech|Slovakia|Israel|Oman|Qatar|Nigeria|Ghana|Zambia|"
    r"Uzbekistan|Kazakhstan|Louisiana|Colorado|Utah|Oregon|Michigan|Wisconsin|Kentucky|Tennessee|Oklahoma)(?!\w)")
GENERIC_CORES = frozenset(("solar", "solar farm", "solar park", "land", "farm", "energy", "pv"))
SOLAR_WORD = re.compile(r"(?<!\w)(?:solar|PV|photovoltaics?|energy (?:park|farm)|DCO|NSIP)(?!\w)", re.I)
OPERATOR_STOP = frozenset(
    "ltd limited plc llp uk gb group holdings energy energies renewable renewables solar power partners "
    "development developments company co and the of infrastructure capital investments generation green "
    "services management international europe farm park project".split())
PLAIN_FIRST_WORDS = frozenset("british european low green island national scottish welsh big new good united "
                              "clean one first north south east west renewable solar energy power".split())
OTHER_TECH = re.compile(r"(?<!\w)(?:batter(?:y|ies)|BESS|gas|wind|hydrogen|nuclear|compressor|CCGT|EV|"
                        r"data[\s-]?cent(?:re|er)s?|power station|offshore|onshore|turbines?)(?!\w)", re.I)
AUTHORITY_STOP = frozenset(
    "nsip pins dco the planning inspectorate national infrastructure council district borough county city of and unitary "
    "metropolitan authority government scottish welsh ministers energy consents unit north south east west "
    "mid central vale".split())


def straight(text):
    """Typographic apostrophes as plain ones, so that "Bloy\u2019s Grove" is "Bloy's Grove"."""
    return (text or "").replace("\u2019", "'").replace("\u2018", "'")


def fold(text):
    """Letters the REPD writes plainly: 'Ørsted' is 'Orsted' there."""
    return text.replace("\u00d8", "O").replace("\u00f8", "o")


def bounded(phrase):
    words = [re.escape(w) for w in re.split(r"[\s\-]+", phrase.strip()) if w]
    return re.compile(r"(?<!\w)" + r"[\s\-]+".join(words) + r"(?:['’]s)?(?!\w)", re.I)


def core_of(alias):
    """The alias without its generic tail: 'Botley West Solar Farm' -> 'Botley West', 'East Park Energy' ->
    'East Park', 'Great North Road Solar and Biodiversity Park' -> 'Great North Road'."""
    text = re.sub(r"^\s*the\s+", "", " ".join((alias or "").split()), flags=re.I)
    text = " ".join(re.sub(r"\([^)]*\)", " ", text).split())
    cut = KEYWORD.search(text)
    if cut:
        return text[:cut.start()].strip(" ,-") or text
    core = TAIL.sub("", text).strip(" ,-")
    if not core or all(w.lower() in COMMON for w in core.split()):
        return text  # 'Low Farm' stays 'Low Farm'
    return core


def weakness(core, counties=()):
    """0 = distinctive phrase (two or more words, not all everyday words): the phrase alone is enough.
    1 = one distinctive word: a second agreeing term is needed anywhere in the title.
    2 = only everyday words, or a county name: the developer or county must agree, or a solar or energy word
    must follow the phrase directly ('Green Hill Solar Farm', 'East Yorkshire Solar Farm')."""
    words = re.findall(r"[A-Za-z0-9']+", core)
    if all(w.lower() in COMMON for w in words) or core.lower() in counties:
        return 2
    return 1 if len(words) < 2 or len(core) < 6 else 0


def _tokens(text, stop):
    return [w for w in re.findall(r"[A-Za-z][A-Za-z0-9]{2,}", text or "") if w.lower() not in stop]


class Project:
    def __init__(self, record, counties=()):
        self.ref = str(record["repd_ref"])
        self.record = record
        self.rank = record.get("rank") or 999
        self.site_name = record.get("site_name") or ""
        self.status = record.get("alias_status") or "derived"
        self.planning_ref = (record.get("planning_ref") or "").strip()
        self.aliases, self.full = [], []
        seen = set()
        for alias in record.get("aliases") or []:
            core = core_of(alias)
            if core and core.lower() not in seen and core.lower() not in GENERIC_CORES:
                seen.add(core.lower())
                self.aliases.append((alias, core, bounded(core), weakness(core, counties)))
            full = " ".join(re.sub(r"\([^)]*\)", " ", alias).split())
            if core and len(full) > len(core) + 3 and core.lower() not in GENERIC_CORES:
                self.full.append(bounded(full))
        self.exclude = [bounded(p) for p in record.get("exclude") or [] if p and p.strip()]
        second = []
        for name in re.split(r"\s*(?:&|/|,|\band\b)\s*", record.get("operator") or ""):
            words = _tokens(name, OPERATOR_STOP)
            if words and words[0].lower() in PLAIN_FIRST_WORDS:
                found = re.search(re.escape(words[0]) + r"\s+[A-Za-z0-9]+", name)  # 'Low Carbon', 'British Solar'
                if found:
                    second.append(("developer", found.group(0)))
            elif words:
                second.append(("developer", words[0]))
        if record.get("county"):
            second.append(("county", record["county"]))
        for word in _tokens(record.get("planning_authority"), AUTHORITY_STOP):
            second.append(("planning authority", word))
        self.second = [(label, text, bounded(text)) for label, text in second]
        try:
            mw = float(record.get("mw") or 0)
        except (TypeError, ValueError):
            mw = 0.0
        if mw >= 5:  # the stated capacity is an agreeing fact: '740MW One Earth'
            number = ("%d" % mw) if mw == int(mw) else re.escape(("%.2f" % mw).rstrip("0"))
            self.second.append(("capacity", "%gMW" % mw, re.compile(
                r"(?<![\d.,])" + number + r"(?:\.0+)?\s?MW(?:p|ac|dc)?(?!\w)", re.I)))
        self.ref_rx = bounded(self.planning_ref) if re.match(r"^[A-Z]{2}\d{6}$", self.planning_ref) else None

    def terms(self):
        """Search phrases, most distinctive first. A weak phrase is sent with 'solar' beside it."""
        out = []
        for _alias, core, _rx, weak in self.aliases[:MAX_TERMS_PER_PROJECT]:
            out.append(core + " solar" if weak else core)
        return out

    def match(self, title, summary=""):
        """The module's own rule (_match), then the shared title gate (gate.py): a name in the title without a
        solar term, abroad or in another county is not this project; thin support is kept as uncertain."""
        found = self._match(title, summary)
        if found is None and not any(rx.search(title) for rx in self.exclude):
            # The old weak-name extractor misses headlines such as "Fenwick
            # solar approval" and "Great North Road solar nears decision".
            # Recover only project-core + solar + a real development action.
            # This is NEVER a confirmed identity or publisher-rights claim.
            foreign_only = (P.FOREIGN.search(title) or ELSEWHERE.search(title)) and not P.UK_WORDS.search(title)
            if not foreign_only:
                project = GATE.for_record(self.record)
                if GATE.named_development_candidate(title, project):
                    verdict, reason = GATE.judge(self.ref, title, project=project)
                    if verdict in ("possible", "ok"):
                        found = ("project-core solar development candidate; independent REPD identity pending",
                                 "uncertain")
        return GATE.gated(self.record, straight(title), found)

    def _match(self, title, summary=""):
        """(basis, confidence) when the title names this project, else None. The summary rule of the contract
        is the fallback: the alias phrase in the feed or search summary together with the developer, county,
        planning authority or planning reference (in the title or the summary). Such an item is always
        'uncertain' and its basis says the headline does not name the project."""
        title = straight(title)
        summary = straight(summary)
        if any(rx.search(title) for rx in self.exclude):
            return None
        if (P.FOREIGN.search(title) or ELSEWHERE.search(title)) and not P.UK_WORDS.search(title):
            return None  # 'Meridian Energy ... in New Zealand' is not the Lincolnshire project
        confidence = "confirmed" if self.status == "confirmed" else "uncertain"
        if self.ref_rx and self.ref_rx.search(title):
            return "planning reference %s in title" % self.planning_ref, confidence
        if GATE.inverted_solar_place(title, self.record):
            return "verified place alias in inverted solar-farm title", confidence
        for _alias, core, rx, weak in self.aliases:
            if not rx.search(title):
                continue
            agree = [(label, text) for label, text, srx in self.second
                     if srx.search(fold(title)) and text.lower() not in core.lower()]
            rest = rx.sub(" ", title)
            named = any(full.search(title) for full in self.full)
            near = re.search(rx.pattern + ADJACENT, title, re.I) is not None
            if not named and not near and OTHER_TECH.search(rest) and not SOLAR_WORD.search(rest) \
                    and not any(label == "developer" for label, _text in agree):
                continue  # 'West Burton C battery', 'St Fergus gas compressor': the same place, another scheme
            if weak == 2:
                agree = []  # everyday words or a county name: only the name followed by its solar word counts
            if agree:
                extra = "%s '%s'" % agree[0]
            elif named:
                extra = "the full alias"
            elif near:
                extra = "solar or energy word directly after it"
            else:
                extra = None
            if weak and not extra:
                continue
            basis = "alias phrase '%s' in title" % core
            if extra:
                basis += " with %s" % extra
            return basis, confidence
        if summary:
            return self.match_summary(title, summary)
        return None

    def match_summary(self, title, summary):
        title, summary = straight(title), straight(summary)
        if any(rx.search(summary) for rx in self.exclude):
            return None
        both = title + " . " + summary
        if (P.FOREIGN.search(both) or ELSEWHERE.search(both)) and not P.UK_WORDS.search(both):
            return None
        for _alias, core, rx, weak in self.aliases:
            if not rx.search(summary):
                continue
            if weak == 2 and not (re.search(rx.pattern + ADJACENT, summary, re.I)
                                  or any(full.search(summary) for full in self.full)):
                continue
            agree = [(label, text) for label, text, srx in self.second
                     if srx.search(fold(both)) and text.lower() not in core.lower()]
            if self.ref_rx and self.ref_rx.search(both):
                agree.insert(0, ("planning reference", self.planning_ref))
            if agree: