GLOBALGRID2050 / EXPLORE CODE

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

Trade (part 2)

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

612 lines of Python from globalgrid2050, in 1 file. Topic: Electricity markets and data pipelines. Section 799 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 701–1312

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 701–1312 of 1312 (continued from section 798) · 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
load_projects, load_cache, cache_key, age_days, last_searched, choose, pick_route, read_feed_archive, walk_sitemap, run_site, build_items, add, run, compare_truth, cell, report, parse_args, 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/trade.py:701-1312 · 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
                return ("alias phrase '%s' in the summary with %s '%s'; the headline does not name the project"
                        % (core, agree[0][0], agree[0][1])), "uncertain"
        return None


def load_projects(path):
    table = json.loads(Path(path).read_text(encoding="utf-8"))
    records = table["projects"]
    records = records.values() if isinstance(records, dict) else records
    records = list(records)
    counties = {(r.get("county") or "").strip().lower() for r in records} - {""}
    return sorted((Project(r, counties) for r in records), key=lambda p: (p.rank, p.ref))


# ---------------------------------------------------------------- cache and rotation

def load_cache(path):
    try:
        cache = json.loads(Path(path).read_text(encoding="utf-8"))
        if cache.get("schema") == CACHE_SCHEMA:
            return cache
    except (OSError, ValueError, AttributeError, TypeError):
        pass
    return {"schema": CACHE_SCHEMA, "queries": {}, "feed_hits": {}}


def cache_key(site_id, term):
    return site_id + "|" + " ".join(term.lower().split())


def age_days(stamp, now):
    try:
        then = dt.datetime.fromisoformat(stamp.replace("Z", "+00:00"))
    except (AttributeError, ValueError):
        return 1e9
    return (now - then).total_seconds() / 86400.0


def last_searched(project, cache, now):
    """Age in days of the oldest search of this project across the sites (never searched: very large)."""
    ages = [age_days((cache["queries"].get(cache_key(site["id"], term)) or {}).get("at"), now)
            for site in SITES for term in project.terms()]
    return max(ages) if ages else 0.0


def choose(projects, cache, now, batch, stale_days):
    """The projects to search this run: the `batch` least recently searched, plus every project whose last
    search is older than `stale_days` (never-searched projects wait their turn in the batch)."""
    aged = sorted(((last_searched(p, cache, now), p) for p in projects), key=lambda x: (-x[0], x[1].rank))
    picked = [p for _age, p in aged[:batch]]
    picked += [p for age, p in aged[batch:] if stale_days < age < 1e8]
    return picked


# ---------------------------------------------------------------- one site

def pick_route(site, host, discover, report, main_links=frozenset()):
    """The first route that answers the canary query with results about the canary (a title that says solar),
    so that a home page, a navigation menu or a challenge page is never taken for search results. With
    discover, every route is tried and described in `report`."""
    chosen = None
    for kind, template in site["routes"]:
        url = route_url(site, template, CANARY)
        entry = {"route": kind, "url": url}
        try:
            ctype, body = host.get(url)
            if kind == "sitemap":
                shape, rows = parse_sitemap(body)
                entry.update(status="ok" if rows else "empty", content_type=ctype.split(";")[0], bytes=len(body),
                             results=len(rows), dated="", summaries="", relevant="",
                             sample="%s: %s" % (shape, rows[0] if shape == "index" else rows[0][0]) if rows else "")
                if rows and chosen is None:
                    chosen = (kind, template)
            else:
                rows = parse_results(kind, body, site["base"])
                dated = sum(1 for r in rows if r[2])
                relevant = sum(1 for r in rows if re.search(r"\bsolar\b", r[0], re.I))
                entry.update(status="ok" if relevant else ("no result about the query" if rows else "empty"),
                             content_type=ctype.split(";")[0], bytes=len(body), results=len(rows), dated=dated,
                             summaries=sum(1 for r in rows if r[3]), relevant=relevant,
                             sample=next((r[0] for r in rows if re.search(r"\bsolar\b", r[0], re.I)),
                                         rows[0][0] if rows else ""))
                if discover and kind == "html":
                    print("LINKS %s %s" % (site["id"], url), flush=True)
                    for row in rows[:25]:
                        print("  %s | %s | %s" % (row[2], row[0][:90], row[1][:110]), flush=True)
                usable = relevant >= 1 and (dated or kind != "wp_search")
                if kind == "html" and (relevant < 3 or relevant * 4 < len(rows)):
                    usable = False
                    entry["status"] = "not search results (%d of %d links say solar)" % (relevant, len(rows))
                if kind == "wp_rss" and rows and main_links and {r[1] for r in rows[:10]} <= main_links:
                    usable = False
                    entry["status"] = "ignores the query (same items as the main feed)"
                if usable and chosen is None:
                    chosen = (kind, template)
        except (HttpError, ValueError) as error:
            entry.update(status="refused" if "robots" in str(error) else "failed", error=str(error)[:160])
        report.append(entry)
        if chosen and not discover:
            break
    if discover:
        for path in site.get("probe_urls") or []:
            entry = {"route": "extra", "url": site["base"] + path}
            try:
                ctype, body = host.get(site["base"] + path)
                entry.update(status="ok", content_type=ctype.split(";")[0], bytes=len(body))
                try:
                    rows = parse_results("feed", body, site["base"])
                    dates = sorted(r[2] for r in rows if r[2])
                    entry.update(results=len(rows), dated=len(dates), sample="feed %s to %s; %s" % (
                        dates[0] if dates else "", dates[-1] if dates else "", rows[0][0] if rows else ""))
                except ValueError:
                    shape, rows = parse_sitemap(body)
                    entry.update(results=len(rows), sample="%s: %s" % (shape, " ; ".join(
                        str(r if shape == "index" else r[0]) for r in rows[:3])))
            except HttpError as error:
                entry.update(status="refused" if "robots" in str(error) else "failed", error=str(error)[:160])
            report.append(entry)
    return chosen


def read_feed_archive(site, host, projects, cache, health, feed_hits, main_links, now, args):
    """Page backwards through a feed that takes an offset (Solar Power Portal: 100 items a page, with
    summaries), --feed-pages pages a run, continuing where the last run stopped. Every item is matched against
    all projects with the title rule and the summary rule. When the end is reached the walk starts again
    after --stale-days."""
    state = cache.setdefault("feed_archive", {}).setdefault(site["id"], {"next": 1, "finished_at": ""})
    if state.get("finished_at") and age_days(state["finished_at"], now) < args.stale_days:
        health["feed_archive"] = {"pages_read": 0, "note": "complete; next pass after %d days" % args.stale_days}
        return
    if state.get("finished_at"):
        state.update(next=1, finished_at="")
    step, pages, entries, kept, oldest = site["feed_archive_step"], 0, 0, 0, ""
    while pages < args.feed_pages and not host.spent():
        try:
            _ctype, body = host.get(site["feed_archive"].format(offset=state["next"] * step))
            rows = parse_results("feed", body, site["base"])
        except (HttpError, ValueError) as error:
            health["notes"].append("feed archive page %d: %s" % (state["next"], str(error)[:80]))
            break  # not the end of the archive: the next run tries this page again
        pages += 1
        fresh = [r for r in rows if r[1] not in main_links]
        if not fresh:
            state["finished_at"] = iso(now)
            break
        for title, link, date, summary in fresh:
            main_links.add(link)
            entries += 1
            oldest = min(oldest or "9999", date or "9999")
            refs = {}
            for project in projects:
                verdict = project.match(title, summary)
                if verdict:
                    refs[project.ref] = verdict[0] if "in the summary" in verdict[0] else ""
            if refs:
                feed_hits[link] = {"title": title, "link": link, "date": date, "site": site["id"], "refs": refs,
                                   "how": "feed archive"}
                kept += 1
        state["next"] += 1
    health["feed_archive"] = {"pages_read": pages, "entries": entries, "oldest": oldest, "matched": kept,
                              "next_page": state["next"], "complete": bool(state.get("finished_at"))}


def walk_sitemap(site, host, start, projects, cache, health, now, args, known):
    """Read the site's sitemap files (robots.txt 'Sitemap:' lines, else `start`), keep the article links whose
    path contains a project's alias phrase, and get each kept link's headline and date: from the sitemap when it
    carries news:title, else from the article page's own metadata (one request per new link, remembered in the
    cache; the newest link of every project first). At most --sitemap-files files a run, those never read
    first and then the ones read longest ago, so the whole sitemap is covered in a few runs and then re-read
    in rotation. Returns feed-hit records; the alias rule is applied to the real headline afterwards."""
    robots = host._robots(site["base"] + "/")
    skip = re.compile(r"image|video|event|webinar|contributor|author", re.I)
    roots = [u for u in robots.sitemaps if re.search(r"sitemap|\.xml", u, re.I) and not skip.search(u)] \
        or [site["base"] + start]
    wanted = []
    for project in projects:
        for _alias, core, _rx, _weak in project.aliases:
            wanted.append((slug_words(core), project))
    state = cache.setdefault("sitemaps", {}).setdefault(site["id"], {"files": {}, "links": {}})
    files, links = state["files"], state["links"]
    age = lambda u: files.get(u, "")  # noqa: E731  never read sorts first
    work, seen, indexes, read, urls, position = sorted(dict.fromkeys(roots), key=age), set(roots), set(), 0, 0, 0
    while position < len(work) and read < args.sitemap_files and not host.spent():
        url = work[position]
        position += 1
        try:
            _ctype, body = host.get(url)
        except HttpError as error:
            health["notes"].append("sitemap %s: %s" % (url, error))
            files[url] = iso(now)
            continue
        shape, rows = parse_sitemap(body)
        if shape == "index":
            indexes.add(url)
            fresh = sorted((c for c in dict.fromkeys(rows) if c not in seen and not skip.search(c)), key=age)
            seen.update(fresh)
            work[position:position] = fresh
            continue
        read += 1
        for loc, lastmod, news_title, news_date in rows:
            urls += 1
            link = D.canonical_link(loc)
            if not link:
                continue
            words = slug_words(urllib.parse.urlsplit(link).path)
            for phrase, project in wanted:
                if phrase in words:
                    found = links.setdefault(link, {"refs": []})
                    found.update(lastmod=lastmod, title=news_title or found.get("title") or "",
                                 date=news_date or found.get("date"))
                    if project.ref not in found["refs"]:
                        found["refs"].append(project.ref)
        files[url] = iso(now)
    known = [u for u in work if u not in indexes]
    print("SITEMAPS %s roots=%d files=%d sample=%s" % (site["id"], len(roots), len(known),
                                                      json.dumps(work[:6] + work[-6:])), flush=True)
    pages, hits, looked = cache.setdefault("pages", {}), {}, 0
    per_project = {}
    for link in sorted(links, key=lambda l: links[l].get("lastmod") or "", reverse=True):
        for ref in links[link]["refs"]:
            per_project.setdefault(ref, []).append(link)
    order = sorted({(position, link) for chain in per_project.values() for position, link in enumerate(chain)},
                   key=lambda x: (x[0], -int((links[x[1]].get("lastmod") or "0000-00-00").replace("-", ""))))
    done = set()
    for _position, link in order:
        if link in done:
            continue
        done.add(link)
        found = links[link]
        title, date = found.get("title"), found.get("date")
        if not title and link in known:
            continue  # the feed already gave this headline
        if not title and link in pages:
            title, date = pages[link]
        elif not title and looked < args.page_lookups and not host.spent():
            looked += 1
            try:
                _ctype, body = host.get(link)
                title, date = parse_article_head(body)
                if title:
                    pages[link] = [title, date]
            except HttpError:
                continue
        if title:
            hits[link] = {"title": title, "link": link, "date": date, "site": site["id"],
                          "refs": {ref: "" for ref in found["refs"]}, "how": "sitemap"}
    health["sitemap"] = {"files_known": len(known), "files_read_this_run": read,
                         "files_never_read": sum(1 for u in known if u not in files), "urls_read": urls,
                         "links_matching_an_alias": len(links), "pages_opened": looked,
                         "headlines_known": len(hits)}
    return hits


def run_site(site, projects, todo, cache, fetch, now, args, out):
    """Feeds, route choice and the searches of one site. Everything it learns goes into `out` (one dict per
    site, written by this thread only)."""
    host = Host(site, fetch, args.per_host_cap, args.host_seconds)
    health = {"id": site["id"], "url": site["base"], "status": "ok", "requests": 0, "failures": 0, "items": 0,
              "error": "", "route": "", "routes": [], "feeds": [], "searched": 0, "cached": 0, "skipped": 0}
    hits, main_links = [], set()
    new_queries, feed_hits = {}, {}
    try:
        for url in site["feeds"]:
            entry = {"url": url}
            try:
                _ctype, body = host.get(url)
                rows = parse_results("feed", body, site["base"])
                main_links.update(r[1] for r in rows)
                kept = 0
                for title, link, date, summary in rows:
                    refs = {}
                    for project in projects:
                        verdict = project.match(title, summary)
                        if verdict:
                            refs[project.ref] = verdict[0] if "in the summary" in verdict[0] else ""
                    if refs:
                        feed_hits[link] = {"title": title, "link": link, "date": date, "site": site["id"],
                                           "refs": refs}
                        kept += 1
                entry.update(status="ok", entries=len(rows), matched=kept,
                             newest=max((r[2] for r in rows if r[2]), default=""))
            except (HttpError, ValueError) as error:
                entry.update(status="failed", error=str(error)[:160])
            health["feeds"].append(entry)

        if site.get("feed_archive"):
            read_feed_archive(site, host, projects, cache, health, feed_hits, main_links, now, args)
        route = pick_route(site, host, args.discover, health["routes"], frozenset(main_links))
        host.failures = host.streak = 0  # routes that do not exist are findings, not failures of the run
        health["notes"] = host.notes
        if route and route[0] == "sitemap":
            health["route"] = "sitemap (links by alias in the path, headline from the article's metadata)"
            known = set(feed_hits) | set(cache.get("feed_hits") or {})
            for link, hit in walk_sitemap(site, host, route[1], projects, cache, health, now, args, known).items():
                feed_hits.setdefault(link, hit)  # a headline from the feed is kept as the feed gave it
            health["searched"] = len(projects)
        elif route:
            kind, template = route
            health["route"] = kind + " " + template
            for project in todo:
                for term in project.terms():
                    key = cache_key(site["id"], term)
                    old = cache["queries"].get(key)
                    if old and old.get("status") == "ok" and age_days(old.get("at"), now) < args.fresh_days:
                        health["cached"] += 1
                        continue
                    if host.spent():
                        health["skipped"] += 1
                        continue
                    try:
                        _ctype, body = host.get(route_url(site, template, term))
                        rows = parse_results(kind, body, site["base"])
                        core_rx = bounded(term[:-6] if term.endswith(" solar") else term)
                        keep = []
                        for title, link, date, summary in rows:
                            if core_rx.search(straight(title)) or (project.ref_rx and project.ref_rx.search(title)):
                                keep.append([title, link, date])
                            else:
                                verdict = project.match_summary(title, summary) if summary else None
                                if verdict:
                                    keep.append([title, link, date, verdict[0]])
                        new_queries[key] = {"at": iso(now), "status": "ok", "route": kind, "returned": len(rows),
                                            "results": keep[:12]}
                        health["searched"] += 1
                    except (HttpError, ValueError) as error:
                        if isinstance(error, ValueError):
                            host.failures += 1
                            host.streak += 1
                        print("FAILED %s %r: %s" % (site["id"], term, str(error)[:100]), flush=True)
                        new_queries.setdefault(key, {"at": iso(now), "status": "failed",
                                                     "error": str(error)[:120], "results": (old or {}).get("results", [])})
                        health["skipped"] += 1
        else:
            health["error"] = "no search route usable: " + "; ".join(
                "%s %s" % (r["route"], r.get("error") or r["status"]) for r in health["routes"])
    except Exception as error:  # a bug in one site must not stop the others
        health["error"] = (type(error).__name__ + ": " + str(error))[:200]
    reason = host.spent()
    if reason and not health["error"]:
        health["error"] = reason
    feeds_ok = any(f["status"] == "ok" for f in health["feeds"])
    if not health["route"] and not feeds_ok:
        health["status"] = "failed"
    elif not health["route"] or health["error"] or host.failures > 3 or health["skipped"] > 3:
        health["status"] = "partial"
    health["requests"], health["failures"] = host.requests, host.failures
    print("SITE " + json.dumps({k: v for k, v in health.items() if k not in ("routes", "feeds")}), flush=True)
    out[site["id"]] = {"health": health, "queries": new_queries, "feed_hits": feed_hits, "hits": hits}


# ---------------------------------------------------------------- build

def build_items(projects, cache):
    """Items of the contract from everything the cache holds (search results and feed hits)."""
    publisher = {s["id"]: s["publisher"] for s in SITES}
    by_term = {}
    for project in projects:
        for term in project.terms():
            by_term.setdefault(" ".join(term.lower().split()), []).append(project)
    items, seen = [], set()

    def add(project, title, link, date, site_id, how, summary_basis=""):
        if summary_basis:
            if any(rx.search(title) for rx in project.exclude):
                return
            verdict = (summary_basis, "uncertain")
        else:
            verdict = project.match(title)
        if not verdict or (project.ref, link) in seen:
            return
        seen.add((project.ref, link))
        items.append({"repd_ref": project.ref, "title": title[:300], "link": link, "publisher": publisher[site_id],
                      "date": date, "family": "trade", "basis": "%s %s: %s" % (publisher[site_id], how, verdict[0]),
                      "confidence": verdict[1]})

    by_ref = {p.ref: p for p in projects}
    for key in sorted(cache["queries"]):
        site_id, _, term = key.partition("|")
        if site_id not in publisher:
            continue
        for row in cache["queries"][key].get("results") or []:
            for project in by_term.get(term, []):
                add(project, row[0], row[1], row[2], site_id, "search", row[3] if len(row) > 3 else "")
    for link in sorted(cache.get("feed_hits") or {}):
        hit = cache["feed_hits"][link]
        if hit.get("site") not in publisher:
            continue
        for ref, summary_basis in sorted((hit.get("refs") or {}).items()):
            if ref in by_ref:
                add(by_ref[ref], hit["title"], hit["link"], hit.get("date"), hit["site"], hit.get("how") or "feed",
                    summary_basis)
    strong = re.compile(r" with (?:developer|county|capacity|planning authority) |planning reference ")
    by_link = {}
    for item in items:
        by_link.setdefault(item["link"], []).append(item)
    for group in by_link.values():  # one headline, several projects of the same name: the agreeing fact decides
        if len(group) > 1 and any(strong.search(i["basis"]) for i in group):
            cores = {}
            for item in group:
                found = re.search(r"alias phrase '([^']*)'", item["basis"])
                cores.setdefault(found.group(1).lower() if found else item["repd_ref"], []).append(item)
            for same in cores.values():
                if len(same) > 1 and any(strong.search(i["basis"]) for i in same):
                    for item in same:
                        if not strong.search(item["basis"]):
                            items.remove(item)
    rank = {p.ref: p.rank for p in projects}
    items.sort(key=lambda i: (rank[i["repd_ref"]], i["date"] is None, "" if i["date"] is None else
                              "%08d" % (99999999 - int(i["date"].replace("-", ""))), i["link"]))
    kept, count = [], {}
    for item in items:  # newest first within a project: at most PER_PUBLISHER items per project and site
        key = (item["repd_ref"], item["publisher"])
        count[key] = count.get(key, 0) + 1
        if count[key] <= PER_PUBLISHER:
            kept.append(item)
    return kept


def run(projects, cache, fetch, now, args):
    todo = choose(projects, cache, now, args.batch, args.stale_days)
    results, threads = {}, []
    for site in SITES:
        thread = threading.Thread(target=run_site, args=(site, projects, todo, cache, fetch, now, args, results),
                                  daemon=True)
        threads.append(thread)
        thread.start()
    for thread in threads:
        thread.join()
    sources = []
    for site in SITES:
        result = results.get(site["id"])
        if not result:
            sources.append({"id": site["id"], "url": site["base"], "status": "failed", "requests": 0,
                            "failures": 0, "items": 0, "error": "no result"})
            continue
        cache["queries"].update(result["queries"])
        store = cache.setdefault("feed_hits", {})
        for link, hit in result["feed_hits"].items():
            if hit.get("how") == "sitemap" and link in store and store[link].get("how") != "sitemap":
                store[link].setdefault("refs", {}).update({r: b for r, b in hit["refs"].items()
                                                           if r not in store[link].get("refs", {})})
            else:
                store[link] = hit
        sources.append(result["health"])
    cache["updated_at"] = iso(now)
    items = build_items(projects, cache)
    publisher = {s["publisher"]: s["id"] for s in SITES}
    for source in sources:
        source["items"] = sum(1 for i in items if publisher[i["publisher"]] == source["id"])
    return {"schema": SCHEMA, "team": TEAM, "generated_at": iso(now), "items": items, "sources": sources,
            "rotation": {"projects": len(projects), "searched_this_run": len(todo), "batch": args.batch,
                         "stale_days": args.stale_days, "fresh_days": args.fresh_days,
                         "full_cycle_runs": -(-len(projects) // max(1, args.batch))}}


# ---------------------------------------------------------------- report

def compare_truth(items, truth, projects):
    """How many of the members' trade-press signals the script found (by canonical link), and for how many
    projects with a trade signal in the ground truth the script has at least one item."""
    hosts = {urllib.parse.urlsplit(s["base"]).netloc.removeprefix("www.") for s in SITES}
    known = {p.ref for p in projects}
    found_links = {(i["repd_ref"], i["link"]) for i in items}
    have = {i["repd_ref"] for i in items}
    rows = []
    for signal in truth:
        link = D.canonical_link(signal.get("link") or "")
        if not link or str(signal.get("repd_ref")) not in known:
            continue
        host = urllib.parse.urlsplit(link).netloc.removeprefix("www.")
        if host not in hosts:
            continue
        ref = str(signal["repd_ref"])
        rows.append({"repd_ref": ref, "title": signal.get("title") or "", "link": link, "host": host,
                     "link_found": (ref, link) in found_links, "project_found": ref in have})
    refs = {r["repd_ref"] for r in rows}
    return {"signals": len(rows), "signals_found": sum(r["link_found"] for r in rows),
            "projects": len(refs), "projects_found": len({r["repd_ref"] for r in rows if r["project_found"]}),
            "rows": rows}


def cell(text):
    return str(text).replace("|", "/").replace("\n", " ")


def report(part, projects, truth, discover):
    items, lines = part["items"], []
    with_signal = {i["repd_ref"] for i in items}
    confirmed = {i["repd_ref"] for i in items if i["confidence"] == "confirmed"}
    by_title = {i["repd_ref"] for i in items if "in the summary" not in i["basis"]}
    rot = part["rotation"]
    lines.append("## Trade-press signals for the top 200 solar projects\n")
    lines.append("**Projects with at least one trade signal: %d of %d** (%d by the title rule, %d more by the "
                 "summary rule only; %d with a confirmed item; %d items).  Searched this run: %d projects; a full "
                 "cycle is %d runs of %d.\n"
                 % (len(with_signal), len(projects), len(by_title), len(with_signal - by_title), len(confirmed),
                    len(items), rot["searched_this_run"],
                    rot["full_cycle_runs"], rot["batch"]))
    lines.append("### Per site\n")
    lines.append("| site | status | search route used | searched | cached | skipped | requests | failures | "
                 "projects | items | note |\n|---|---|---|---|---|---|---|---|---|---|---|")
    by_pub = {}
    for item in items:
        by_pub.setdefault(item["publisher"], set()).add(item["repd_ref"])
    for site, source in zip(SITES, part["sources"]):
        lines.append("| %s | %s | %s | %s | %s | %s | %s | %s | %d | %s | %s |" % (
            site["publisher"], source["status"], cell(source.get("route") or "none"), source.get("searched", ""),
            source.get("cached", ""), source.get("skipped", ""), source["requests"], source["failures"],
            len(by_pub.get(site["publisher"], ())), source["items"],
            cell("; ".join([source.get("error") or ""] + (source.get("notes") or [])
                           + ["%s %s" % (k, json.dumps(source[k])) for k in ("feed_archive", "sitemap")
                              if source.get(k)]).strip("; "))))
    lines.append("\n### Routes tried (canary query '%s')%s\n" % (CANARY, "" if discover else
                                                                   " - stops at the first that works"))
    lines.append("| site | route | result | type | results | about solar | dated | with summary | sample or error |\n"
                 "|---|---|---|---|---|---|---|---|---|")
    for site, source in zip(SITES, part["sources"]):
        for route in source.get("routes") or []:
            lines.append("| %s | %s | %s | %s | %s | %s | %s | %s | %s |" % (
                site["publisher"], cell(route["url"].replace(site["base"], "")), route["status"],
                route.get("content_type", ""), route.get("results", ""), route.get("relevant", ""),
                route.get("dated", ""),
                route.get("summaries", ""),
                cell((route.get("sample") or route.get("error") or "")[:160])))
    lines.append("\n### Main feeds\n")
    lines.append("| site | feed | result | entries | newest | matched a project |\n|---|---|---|---|---|---|")
    for site, source in zip(SITES, part["sources"]):
        for feed in source.get("feeds") or []:
            lines.append("| %s | %s | %s | %s | %s | %s |" % (
                site["publisher"], feed["url"], feed["status"] + (" " + feed.get("error", "") if feed.get("error") else ""),
                feed.get("entries", ""), feed.get("newest", ""), feed.get("matched", "")))
    if truth is not None:
        result = compare_truth(items, truth, projects)
        lines.append("\n### Against the members' ground truth (trade-press signals on these nine sites)\n")
        lines.append("Truth signals found by link: **%d of %d**. Projects with a truth trade signal for which the "
                     "script has at least one item: **%d of %d**.\n"
                     % (result["signals_found"], result["signals"], result["projects_found"], result["projects"]))
        missed = [r for r in result["rows"] if not r["link_found"]]
        if missed:
            lines.append("| REPD | host | project has an item | truth title not found by link |\n|---|---|---|---|")
            for row in missed[:60]:
                lines.append("| %s | %s | %s | %s |" % (row["repd_ref"], row["host"],
                                                       "yes" if row["project_found"] else "no", cell(row["title"][:110])))
    lines.append("\n### Newest item per project (first 60 by rank)\n")
    lines.append("| rank | REPD | date | publisher | confidence | title | basis |\n|---|---|---|---|---|---|---|")
    rank = {p.ref: p.rank for p in projects}
    shown = set()
    for item in items:
        if item["repd_ref"] in shown or len(shown) >= 60:
            continue
        shown.add(item["repd_ref"])
        lines.append("| %s | %s | %s | %s | %s | [%s](%s) | %s |" % (
            rank[item["repd_ref"]], item["repd_ref"], item["date"] or "", item["publisher"], item["confidence"],
            cell(item["title"][:120]), item["link"], cell(item["basis"])))
    without = [p for p in projects if p.ref not in with_signal]
    lines.append("\n### Projects without a trade signal (%d)\n" % len(without))
    lines.append(", ".join("%s (%s)" % (p.ref, cell(p.aliases[0][1] if p.aliases else p.site_name))
                           for p in without))
    return "\n".join(lines) + "\n"


# ---------------------------------------------------------------- main

def parse_args(argv=None):
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--out", required=True)
    parser.add_argument("--aliases", default=str(HERE / "aliases.json"))
    parser.add_argument("--cache", default="", help="query cache, read and rewritten (default: next to --out)")
    parser.add_argument("--probe", default="", help="write a markdown report here")
    parser.add_argument("--truth", default="", help="ground-truth signals (JSON list) to compare with")
    parser.add_argument("--discover", action="store_true", help="try every search route of every site")
    parser.add_argument("--limit", type=int, default=0, help="only the first N projects by rank")
    parser.add_argument("--batch", type=int, default=40, help="projects searched per run")
    parser.add_argument("--stale-days", type=float, default=30.0)
    parser.add_argument("--fresh-days", type=float, default=4.0)
    parser.add_argument("--per-host-cap", type=int, default=200, help="requests per site per run")
    parser.add_argument("--host-seconds", type=int, default=900, help="time budget per site per run")
    parser.add_argument("--feed-pages", type=int, default=30, help="pages of an offset feed read per run")
    parser.add_argument("--sitemap-files", type=int, default=90, help="sitemap files read per run (sitemap route)")
    parser.add_argument("--page-lookups", type=int, default=60,
                        help="article pages opened per run for their headline and date (sitemap route)")
    return parser.parse_args(argv)


def main(argv=None, fetch=fetch_url):
    args = parse_args(argv)
    now = now_utc()
    projects = load_projects(args.aliases)
    if args.limit:
        projects = projects[:args.limit]
    out = Path(args.out)
    cache_path = Path(args.cache) if args.cache else out.with_name(out.stem + ".cache.json")
    cache = load_cache(cache_path)
    part = run(projects, cache, fetch, now, args)
    for path, payload in ((out, part), (cache_path, cache)):
        path.parent.mkdir(parents=True, exist_ok=True)
        tmp = path.with_suffix(path.suffix + ".tmp")
        tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
        tmp.replace(path)
    truth = None
    if args.truth and Path(args.truth).exists():
        truth = json.loads(Path(args.truth).read_text(encoding="utf-8"))
    if args.probe:
        Path(args.probe).write_text(report(part, projects, truth, args.discover), encoding="utf-8")
    with_signal = len({i["repd_ref"] for i in part["items"]})
    print(json.dumps({"projects": len(projects), "with_trade_signal": with_signal, "items": len(part["items"]),
                      "sources": {s["id"]: s["status"] for s in part["sources"]}}))
    return 1 if all(s["status"] == "failed" for s in part["sources"]) else 0


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