GLOBALGRID2050 / EXPLORE CODE

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

Build Feed and 2 more files

A Python command-line tool in the news folder of GlobalGrid2050 that reads binder evaluation and the Renewable Energy Planning Database (REPD) register, using SHA-256.

580 lines of Python from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 777 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. Build Feed storage · globalgrid2050 / automation/news/build_feed.py lines 1–290
  2. Build News Priority storage · globalgrid2050 / automation/news/build_news_priority.py lines 1–144
  3. Build Prospecting Priority other · globalgrid2050 / automation/news/build_prospecting_priority.py lines 1–146

Build Feed

A Python command-line tool in the news folder of GlobalGrid2050 that reads binder evaluation and the Renewable Energy Planning Database (REPD) register, using SHA-256.

storageglobalgrid2050 / automation/news/build_feed.py · lines 1–290 of 290 · Entry point · pattern _dump (shared by 3 files)

What it does
It loads binder evaluation and the REPD register. Defines 7 functions or classes, including panel_fields, _input, _dump, top50_csv, top50_md. Uses libraries __future__, argparse, csv, io, json. Side effects: reads or writes files; 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 binder_evaluation_v9_5_1.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the panel fields helper (`panel_fields`), the top50 CSV helper (`top50_csv`) and the top50 md helper (`top50_md`). Build the REPD events feed, the article relevance file and the binder evaluation for one release pair. It accepts `--previous`, `--new` and `--previous-label`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · automation/news · Python CLI
Uses
Renewable Energy Planning Database (REPD) Diff (import), Events (import), __future__, argparse, csv, io, json, sys, datetime, pathlib
Used by
none found
Produces
panel_fields, top50_csv, top50_md, build, main
Defines here
panel_fields, _input, _dump, top50_csv, top50_md, build, 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/build_feed.py:1-290 · blob aeca182cbe90bac9147fb42a8292ac66fdbd11c8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""automation/news/build_feed.py - build the REPD events feed, the article relevance file and the
binder evaluation for one release pair. Every output is NEW (never an existing feed name) and
deterministic (no clock, no absolute paths; inputs by name, size and sha256).

    python -m automation.news.build_feed \
        --previous REPD_Q2_2026_cleaned.csv --previous-label "July 2026 (Q2)" \
        --new repd-2026q3.csv --new-label "October 2026 (Q3)" --release 2026q3 \
        --previous-feed dist/major_project_news_v9_5_1.json \
        --convergence dist/convergence/2026q3 \
        --datacentres uk_datacentre_pipeline_202610312133.geojson \
        --labels automation/news/labels/binding_labels_v9_5_1.json \
        --out-dir dist/news --docs-dir docs/news/2026q3

Writes
  <out-dir>/repd_events_<release>.json           schema globalgrid2050.pipeline-news.repd-events-feed.v1
  <out-dir>/repd_events_<release>_top50.csv      the top 50 (co-located siblings folded)
  <out-dir>/article_relevance_v9_5_1_<release>.json   the 133 v9.5.1 articles re-bound and re-scored
  <out-dir>/binder_evaluation_v9_5_1.json        binder metrics on the labelled set
  <docs-dir>/top50.md                            the top 50 as a readable table

Aggregate open-data facts only; headlines are generated from REPD fields; no commentary on
companies. Proximity to data centres is straight-line screening, never a connection.
"""
from __future__ import annotations

import argparse
import csv
import io
import json
import sys
from datetime import date
from pathlib import Path

from automation.repd import diff as repd
from automation.news import events as E
from automation.news import relevance as R
from automation.news import binder as B

FEED_SCHEMA = "globalgrid2050.pipeline-news.repd-events-feed.v1"
ARTICLES_SCHEMA = "globalgrid2050.pipeline-news.article-relevance.v1"
TOP_N = 50
CAVEATS = [
    "Events are derived from two official DESNZ REPD releases; a REPD status change records when the "
    "register was updated, which can lag the real-world decision.",
    "Blank REPD capacity is unknown (null), never zero.",
    "Headlines are generated from REPD fields only; they carry no commentary on any company.",
    "Data-centre proximity is straight-line screening from the convergence join; it is not a grid "
    "connection, capacity, offtake or planning link. Data centres are a separate category and never "
    "carry a REPD Ref ID.",
    "Relevance is an additive, rule-based score for a solar, storage and grid business; every component "
    "is shown and the profile is versioned.",
]


LANE = "REPD_EVENTS"


def panel_fields(ev: dict) -> dict:
    """Flat fields shared with the data-centre capex/politics panel (N4): title, date, link or ref, lane,
    score. link is null (REPD has no article URL); ref and gg_project_id identify the project."""
    return {"title": ev["headline"], "date": ev["event_date"] or ev["record_last_updated"],
            "date_kind": "milestone" if ev["event_date"] else "record_last_updated",
            "link": None, "lane": LANE, "score": ev["relevance"]["score"]}


def _input(role, path, label=None, extra=None):
    p = Path(path)
    out = {"role": role, "file": label or p.name, "bytes": p.stat().st_size, "sha256": R.sha256_file(p)}
    out.update(extra or {})
    return out


def _dump(path: Path, doc) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(doc, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")


def top50_csv(top: list) -> str:
    buf = io.StringIO()
    w = csv.writer(buf, lineterminator="\n")
    w.writerow(["rank", "score", "event_type", "ref", "grouped_refs", "site_name", "technology", "capacity_mw",
                "previous_status", "status", "county", "region", "country", "event_date", "headline",
                "nearest_datacentre_km", "event_id"])
    for ev in top:
        near = ((ev.get("datacentre_context") or {}).get("nearest") or {})
        w.writerow([ev["top_rank"], ev["relevance"]["score"], ev["event_type"], ev["ref"], " ".join(ev["grouped_refs"]),
                    ev["site_name"], ev["technology"] or "", "" if ev["capacity_mw"] is None else ev["capacity_mw"],
                    ev["previous_status"] or "", ev["status"] or "", ev["county"] or "", ev["region"] or "",
                    ev["country"] or "", ev["event_date"] or "", ev["headline"],
                    "" if near.get("km") is None else near["km"], ev["event_id"]])
    return buf.getvalue()


def top50_md(feed: dict) -> str:
    lines = [f"# Pipeline News: top {len(feed['top'])} REPD project events, {feed['previous']['label']} to {feed['new']['label']}",
             "",
             f"Generated by `{feed['tool']}` from `{feed['previous']['file']}` (sha256 `{feed['previous']['sha256'][:16]}…`) and "
             f"`{feed['new']['file']}` (sha256 `{feed['new']['sha256'][:16]}…`). Relevance profile `{feed['profile']['id']}` "
             f"(sha256 `{feed['profile_sha256'][:16]}…`), reference date {feed['reference_date']}. Score out of "
             f"{feed['max_score']:g}; components: capacity, stage, technology, recency, national route, data-centre "
             "proximity, novelty, evidence tier, co-located storage. Full components per event in "
             f"`dist/news/repd_events_{feed['release']}.json`.",
             "",
             "Open data only (DESNZ REPD; data-centre proximity from the convergence join is screening, not a connection).",
             "",
             "| # | Score | Event | REPD | MW | Technology | Place | Headline |",
             "|---|---|---|---|---|---|---|---|"]
    for ev in feed["top"]:
        refs = ev["ref"] + (f" (+{', '.join(ev['grouped_refs'])})" if ev["grouped_refs"] else "")
        mw = "unknown" if ev["capacity_mw"] is None else f"{ev['capacity_mw']:g}"
        place = ev["county"] or ev["region"] or ""
        lines.append(f"| {ev['top_rank']} | {ev['relevance']['score']:g} | {ev['event_type']} | {refs} | {mw} | "
                     f"{ev['technology'] or ''} | {place} | {ev['headline'].replace('|', '/')} |")
    lines += ["", "Counts by event type (all events, before ranking):", ""]
    lines += [f"- {k}: {v}" for k, v in feed["counts"].items() if v]
    return "\n".join(lines) + "\n"


def build(a) -> dict:
    old, new = E.load_pair(a.previous, a.new)
    ev_doc = E.build_events(old, new, a.previous_label, a.new_label, a.large_application_mw)
    reference = date.fromisoformat(new["info"]["max_record_last_updated"])
    dc_index = R.load_datacentre_index(a.convergence) if a.convergence else None
    previous = R.load_previous_feed(a.previous_feed) if a.previous_feed else None
    ranked = R.rank_events(ev_doc["events"], reference, dc_index, previous)
    for ev in ranked:
        ev.update(panel_fields(ev))
    top_ids = R.top_events(ranked, TOP_N)
    by_id = {e["event_id"]: e for e in ranked}
    top = []
    for t in top_ids:
        ev = dict(by_id[t["event_id"]])
        ev["top_rank"] = t["rank"]
        ev["grouped_refs"] = t["grouped_refs"]
        top.append(ev)

    inputs = [
        {"role": "repd_previous", **{k: ev_doc["previous"][k] for k in ("file", "bytes", "sha256", "unique_refs")}},
        {"role": "repd_new", **{k: ev_doc["new"][k] for k in ("file", "bytes", "sha256", "unique_refs")}},
    ]
    if previous:
        inputs.append(_input("previous_feed", a.previous_feed, f"dist/{Path(a.previous_feed).name}"))
    inputs += [{"role": "convergence", **x} for x in R.convergence_inputs(a.convergence)]

    feed = {
        "schema": FEED_SCHEMA,
        "tool": "automation/news/build_feed.py",
        "release": a.release,
        "category": "REPD_ENERGY_PROJECTS",
        "lane": LANE,
        "panel_fields": ["title", "date", "link", "ref", "lane", "score"],
        "previous": ev_doc["previous"],
        "new": ev_doc["new"],
        "reference_date": reference.isoformat(),
        "reference_date_rule": "newest Record Last Updated in the new release (no wall clock)",
        "inputs": inputs,
        "profile": R.DEFAULT_PROFILE,
        "profile_sha256": R.profile_sha256(),
        "max_score": R.max_possible(),
        "rules": ev_doc["rules"],
        "datacentre_join": "supplied" if dc_index is not None else "not supplied",
        "caveats": CAVEATS,
        "counts": ev_doc["counts"],
        "operator_cosmetic_changes_not_emitted": ev_doc["operator_cosmetic_changes_not_emitted"],
        "event_count": len(ranked),
        "top_n": TOP_N,
        "top": top,
        "events": ranked,
    }

    # ---- articles: re-bind and re-score the v9.5.1 newspaper against the new register
    index = B.ProjectIndex(new)
    dci = B.DatacentreIndex(a.datacentres) if a.datacentres else None
    release_events_by_ref = {}
    for ev in ranked:
        release_events_by_ref.setdefault(ev["ref"], set()).add(ev["event_type"])
    articles_out = None
    if a.previous_feed:
        legacy = json.loads(Path(a.previous_feed).read_text(encoding="utf-8"))
        art_ref = date.fromisoformat(str(legacy.get("updated", reference.isoformat()))[:10])
        rows = []
        for i, it in enumerate(legacy.get("all_items", [])):
            art = {"headline": it.get("headline"), "source": it.get("source", ""), "source_url": it.get("source_url", ""),
                   "url": it.get("url"), "published": it.get("published")}
            b = B.bind(art, index)
            project = index.records.get(b["ref"]) if b["ref"] and b["class"] in B.SIGNAL_CLASSES else None
            rel = R.score_article(art, b, project, art_ref, dc_index, None, release_events_by_ref)
            row = {"id": f"v951-{i:03d}", "gg_article_id": it.get("gg_article_id"), **art,
                   "category": "DATA_CENTRES" if dci and dci.bind(art)["topic_datacentres"] else "ENERGY",
                   "binding": {k: b[k] for k in ("class", "ref", "gg_project_id", "related_refs", "evidence", "trace")},
                   "drives_project_signal": b["class"] in B.SIGNAL_CLASSES,
                   "legacy_v9_5_1": {"role": it.get("role"), "repd_ref": it.get("repd_ref"), "event": it.get("event"),
                                     "confidence": it.get("confidence")},
                   "relevance": rel}
            if dci:
                row["datacentre_binding"] = dci.bind(art)
            rows.append(row)
        # dedupe: one lead story per (bound development, article event); official first, then earliest
        clusters = {}
        for row in rows:
            if not row["drives_project_signal"]:
                continue
            grp = index.records[row["binding"]["ref"]]["group"]
            clusters.setdefault((grp, row["relevance"]["article_event"]), []).append(row)
        tier_rank = {"official_record": 0, "attributed_reporting": 1, "unverified_lead": 2}
        for members in clusters.values():
            members.sort(key=lambda r: (tier_rank[r["relevance"]["evidence_tier"]], r["published"] or "", r["id"]))
            for m in members[1:]:
                m["duplicate_of"] = members[0]["id"]
        rows.sort(key=lambda r: (-r["relevance"]["score"], r["id"]))
        for k, row in enumerate(rows, 1):
            row["rank"] = k
        articles_out = {
            "schema": ARTICLES_SCHEMA,
            "tool": "automation/news/build_feed.py",
            "release": a.release,
            "reference_date": art_ref.isoformat(),
            "reference_date_rule": "the legacy feed's own 'updated' date (scores do not drift with the clock)",
            "inputs": inputs[:2] + [x for x in inputs if x["role"] == "previous_feed"] +
                      ([_input("datacentre_register", a.datacentres)] if a.datacentres else []),
            "profile_sha256": R.profile_sha256(),
            "max_score": R.max_possible(article=True),
            "note": "The v9.5.1 articles (Aug 2026 crawl) re-bound to October 2026 REPD Ref IDs and re-scored; "
                    "novelty is not assessed against the feed the articles came from.",
            "counts": {
                "articles": len(rows),
                "by_binding_class": {c: sum(1 for r in rows if r["binding"]["class"] == c) for c in B.CLASS_ORDER},
                "drives_project_signal": sum(1 for r in rows if r["drives_project_signal"]),
                "duplicates_folded": sum(1 for r in rows if r.get("duplicate_of")),
                "by_evidence_tier": {t: sum(1 for r in rows if r["relevance"]["evidence_tier"] == t) for t in tier_rank},
                "category_datacentres": sum(1 for r in rows if r["category"] == "DATA_CENTRES"),
                "datacentre_site_bindings": sum(len(r.get("datacentre_binding", {}).get("bindings", [])) for r in rows),
                "contradictions": sum(1 for r in rows if r["relevance"]["contradiction"]),
                "officially_corroborated_in_release": sum(1 for r in rows if any(
                    c["name"] == "official_corroboration" and c["points"] == R.DEFAULT_PROFILE["official_corroboration"]["same_event_in_release"]
                    for c in r["relevance"]["components"])),
            },
            "articles": rows,
        }

    evaluation = None
    if a.labels:
        labels_doc = json.loads(Path(a.labels).read_text(encoding="utf-8"))
        evaluation = B.evaluate(labels_doc["labels"], index)
        evaluation["inputs"] = [inputs[1], _input("labels", a.labels, "automation/news/labels/" + Path(a.labels).name)]
        evaluation["labels_method"] = labels_doc.get("method")
    return {"feed": feed, "articles": articles_out, "evaluation": evaluation}


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--previous", required=True)
    ap.add_argument("--new", required=True)
    ap.add_argument("--previous-label", default="previous")
    ap.add_argument("--new-label", default="new")
    ap.add_argument("--release", required=True)
    ap.add_argument("--previous-feed")
    ap.add_argument("--convergence")
    ap.add_argument("--datacentres")
    ap.add_argument("--labels")
    ap.add_argument("--large-application-mw", type=float, default=E.DEFAULT_LARGE_APPLICATION_MW)
    ap.add_argument("--out-dir", required=True)
    ap.add_argument("--docs-dir")
    a = ap.parse_args(argv)
    out = build(a)
    od = Path(a.out_dir)
    feed_path = od / f"repd_events_{a.release}.json"
    for p in (feed_path,):
        if p.exists() and p.read_text(encoding="utf-8") != json.dumps(out["feed"], indent=1, ensure_ascii=False) + "\n":
            print(f"note: {p} exists and will be replaced by this build's bytes", file=sys.stderr)
    _dump(feed_path, out["feed"])
    (od / f"repd_events_{a.release}_top50.csv").write_text(top50_csv(out["feed"]["top"]), encoding="utf-8")
    if out["articles"]:
        _dump(od / f"article_relevance_v9_5_1_{a.release}.json", out["articles"])
    if out["evaluation"]:
        _dump(od / "binder_evaluation_v9_5_1.json", out["evaluation"])
    if a.docs_dir:
        dd = Path(a.docs_dir)
        dd.mkdir(parents=True, exist_ok=True)
        (dd / "top50.md").write_text(top50_md(out["feed"]), encoding="utf-8")
    summary = {"events": out["feed"]["event_count"], "counts": out["feed"]["counts"]}
    if out["evaluation"]:
        summary["binder_signal"] = out["evaluation"]["signal_metrics"]
    print(json.dumps(summary))
    return 0


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

Build News Priority

A Python command-line tool in the automation folder of GlobalGrid2050 that reads pipeline headlines schema, using SHA-256. It is built from the build step (`build`) and the dumps step (`dumps`).

storageglobalgrid2050 / automation/news/build_news_priority.py · lines 1–144 of 144 · Entry point · pattern dumps (shared by 4 files)

What it does
It loads pipeline headlines schema. Defines _unique, _validate, build, dumps, main. Uses libraries __future__, argparse, hashlib, json, pathlib. Side effects: reads or writes files.
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.
Inputs & outputs
In: JSON file pipeline-headlines.v1.schema.json; command-line arguments.
Downstream impact
Used directly by 2 files: Test News Priority Export (globalgrid2050); GlobalGrid2050 Pipeline Headlines 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
Build a deterministic rank sidecar without changing the existing headline file. It accepts `--input` and `--output`.
Why it matters
Run by GlobalGrid2050 Pipeline Headlines Workflow. Checked by Test News Priority Export.
Application
globalgrid2050 · automation/news · Python CLI
Uses
News Algorithm (import), __future__, argparse, hashlib, json, pathlib, re
Used by
imported by Test News Priority Export (import), run by GlobalGrid2050 Pipeline Headlines Workflow (workflow run)
Produces
build, dumps, main
Defines here
_unique, _validate, build, dumps, 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/build_news_priority.py:1-144 · blob 4671d94ca467bfbe264e248df8b789480eb51506 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Build a deterministic rank sidecar without changing the existing headline file.

Run: python -m automation.news.build_news_priority --input dist/pipeline_headlines.json
     --output dist/pipeline_headlines.rank.json
Publish both files in one data-branch commit. A sidecar is display guidance, never
source permission, project binding or evidence verification.
"""
from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
import re

from automation.news import news_algorithm as N
from automation.news import pipeline_headlines as P

SCHEMA = "globalgrid2050.news.headline-priority.v1"
MAX_BYTES = 2_000_000
HEADLINE_SCHEMA = json.loads((Path(__file__).parent / "schema/pipeline-headlines.v1.schema.json").read_text(encoding="utf-8"))


def _unique(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate JSON property")
        result[key] = value
    return result


def _validate(value, rule, root=HEADLINE_SCHEMA):
    """Existing headline schema's small, dependency-free keyword subset."""
    supported = {"$schema", "$id", "$defs", "title", "description", "$ref", "anyOf", "const", "enum", "type",
                 "minLength", "maxLength", "pattern", "minimum", "maxItems", "items", "required",
                 "properties", "additionalProperties", "propertyNames"}
    if set(rule) - supported:
        raise ValueError("unsupported headline schema keyword")
    if "$ref" in rule:
        rule = root["$defs"][rule["$ref"].split("/")[-1]]
    if "anyOf" in rule:
        for option in rule["anyOf"]:
            try:
                _validate(value, option, root)
                return
            except ValueError:
                pass
        raise ValueError("headline schema: no valid variant")
    kind = rule.get("type")
    types = {"object": dict, "array": list, "string": str, "integer": int, "null": type(None)}
    if kind and type(value) is not types[kind]:
        raise ValueError("headline schema: wrong type")
    if "const" in rule and value != rule["const"] or "enum" in rule and value not in rule["enum"]:
        raise ValueError("headline schema: invalid value")
    if isinstance(value, str):
        if not rule.get("minLength", 0) <= len(value) <= rule.get("maxLength", MAX_BYTES):
            raise ValueError("headline schema: text length")
        if "pattern" in rule and not re.search(rule["pattern"], value):
            raise ValueError("headline schema: text pattern")
    if type(value) is int and value < rule.get("minimum", value):
        raise ValueError("headline schema: below minimum")
    if isinstance(value, list):
        if len(value) > rule.get("maxItems", 200):
            raise ValueError("headline schema: too many items")
        for child in value:
            _validate(child, rule.get("items", {}), root)
    if isinstance(value, dict):
        if not set(rule.get("required", ())).issubset(value):
            raise ValueError("headline schema: missing property")
        props, extra = rule.get("properties", {}), rule.get("additionalProperties", True)
        for key, child in value.items():
            if "propertyNames" in rule:
                _validate(key, rule["propertyNames"], root)
            if key in props:
                _validate(child, props[key], root)
            elif extra is False:
                raise ValueError("headline schema: unexpected property")
            elif isinstance(extra, dict):
                _validate(child, extra, root)


def build(raw: bytes) -> dict:
    if not isinstance(raw, bytes) or not 0 < len(raw) <= MAX_BYTES:
        raise ValueError("bounded nonempty headline bytes required")
    doc = json.loads(raw.decode("utf-8-sig"), object_pairs_hook=_unique,
                     parse_constant=lambda value: (_ for _ in ()).throw(ValueError("nonfinite JSON")))
    _validate(doc, HEADLINE_SCHEMA)
    if doc["counts"]["items"] != len(doc["items"]):
        raise ValueError("headline item count mismatch")
    as_of = N._clock(doc["generated_at"])
    by_link = {}
    for item in doc["items"]:
        if N._clock(item["first_seen"]) > as_of:
            raise ValueError("first collection occurs after document generation")
        if item["date"] is not None:
            N._clock(item["date"])
        link = N.public_url(item["link"])
        if link in by_link:
            raise ValueError("duplicate canonical headline URL")
        by_link[link] = item
    ranking = N.rank_headlines(doc["items"], as_of=as_of.isoformat())
    entries = []
    for ranked in ranking["items"]:
        original, editorial = by_link[ranked["link"]], ranked["editorial"]
        entries.append({
            "link": original["link"], "source": original["source"], "title": original["title"],
            "rank": editorial["rank"], "source_kind": editorial["source"]["kind"],
            "role": editorial["role"], "topics": editorial["topics"],
            "freshness_state": editorial["freshness"]["state"],
            "uk_context": editorial["components"]["uk_headline_context"] > 0,
            "score": editorial["selection_score"],
            "requires_primary_followup": editorial["requires_primary_followup"],
            "subscription_notice": editorial["source"]["access_notice"] is not None,
        })
    return {"schema": SCHEMA, "input_sha256": hashlib.sha256(raw).hexdigest(),
            "input_bytes": len(raw), "input_generated_at": doc["generated_at"],
            "input_count": len(doc["items"]), "as_of": ranking["as_of"],
            "profile_id": N.PROFILE["id"], "profile_sha256": N.PROFILE_SHA256,
            "entries": entries}


def dumps(document):
    return json.dumps(document, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False) + "\n"


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    if args.input.resolve() == args.output.resolve():
        parser.error("sidecar must not overwrite the headline input")
    with args.input.open("rb") as source:
        raw = source.read(MAX_BYTES + 1)
    document = build(raw)
    result = dumps(document).encode("utf-8")
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_bytes(result)
    print(f"priority sidecar: {len(document['entries'])} credited headlines; input bytes unchanged")


if __name__ == "__main__":
    main()

Build Prospecting Priority

A Python command-line tool in the news folder of GlobalGrid2050 that builds artifacts (`build_artifacts`) and writes artifacts (`write_artifacts`), covering solar and the Renewable Energy Planning Database (REPD) register, using SHA-256.

otherglobalgrid2050 / automation/news/build_prospecting_priority.py · lines 1–146 of 146 · Entry point · pattern encoded (shared by 4 files)

What it does
Defines 7 functions or classes, including encoded, sha, remark, csv_text, build_artifacts. Uses libraries __future__, argparse, csv, hashlib, io. Side effects: reads or writes files.
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 priority.json; CSV file priority.csv; command-line arguments.
Downstream impact
Used directly by 1 file: Test Prospecting Export (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 is built from the encoded step (`encoded`), the sha step (`sha`) and the remark step (`remark`). Export the existing bounded research ranking without changing official rows. It accepts `--as-of`, `--out-dir` and `--limit`.
Why it matters
Checked by Test Prospecting Export.
Application
globalgrid2050 · automation/news · Python CLI
Uses
Prospecting (import), __future__, argparse, csv, hashlib, io, json, pathlib
Used by
imported by Test Prospecting Export (import)
Produces
encoded, sha, remark, csv_text, build_artifacts, write_artifacts, main
Defines here
encoded, sha, remark, csv_text, build_artifacts, write_artifacts, 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/build_prospecting_priority.py:1-146 · blob bc769854bbdb3fa5093e087bc40f1248c01fdc58 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Export the existing bounded research ranking without changing official rows.

Offline only. Writes a new immutable review directory containing priority.json,
priority.csv and manifest.json. Integration must pin the manifest before use.
"""
from __future__ import annotations

import argparse
import csv
import hashlib
import io
import json
from pathlib import Path

from automation.news import prospecting

SCHEMA = "globalgrid2050.prospecting.export.v1"


def encoded(value):
    return (json.dumps(value, sort_keys=True, ensure_ascii=False, indent=2,
                       allow_nan=False) + "\n").encode("utf-8")


def sha(raw):
    return hashlib.sha256(raw).hexdigest()


def remark(row):
    """Summarise supplied record fields, never create an event or delivery claim."""
    if row["record_type"] == "data_centre":
        return ("Research note: Wikidata source-indexed data-centre lead; "
                "operation, demand, connection and funding remain unassessed. "
                "Inspect the linked entity revision.")
    capacity = row["capacities"]["repd_installed_mw"]
    quantity = "capacity unknown" if capacity is None else f"{capacity:g} MW installed capacity"
    status = row["official_status"] or "status unknown"
    date = row["record_freshness"]["timestamp"] or "unknown update date"
    return (f"Research note: {row['id']} records {quantity}; {status}; record date {date}. "
            "Review the linked REPD record. This is not a new event or evidence of grid access.")


def csv_text(value):
    value = "" if value is None else str(value)
    # Spreadsheet interpretation must not execute source-provided formulas.
    return "'" + value if value.lstrip().startswith(("=", "+", "-", "@")) or value.startswith(("\t", "\r", "\n")) else value


def build_artifacts(*, as_of, limit=1000, evidence=None, datacentres=None, repo_root=None):
    triage = prospecting.build(as_of=as_of, limit=limit, evidence=evidence,
                               datacentres=datacentres, repo_root=repo_root)
    rows, pilot, official = prospecting.official(repo_root)
    ids = ["REPD-" + row["repd_ref"] for row, _ in rows]
    solar_count = sum(row["technology"] == "solar" for row, _ in rows)
    prospecting.require(len(ids) == len(set(ids)) == 7775 and solar_count == 3604,
                        "Official population invariant failed")
    prospecting.require(len(pilot) == len(set(pilot)) == 1000,
                        "Solar-1000 invariant failed")
    dc_rows, _ = prospecting.dc_input(datacentres, prospecting._moment(as_of))
    dc_ids = sorted(row["id"] for row in dc_rows)
    all_ids = set(ids + dc_ids)
    prospecting.require(all(row["id"] in all_ids for row in triage["records"]),
                        "Ranked record is absent from source inventory")
    for row in triage["records"]:
        row["research_note"] = remark(row)
    priority = encoded(triage)
    prospecting.require(len(priority) <= prospecting.MAX_BYTES,
                        "Priority output exceeds consumer size limit")
    stream = io.StringIO(newline="")
    fields = ["rank", "project_id", "record_type", "name", "research_priority_points",
              "official_status", "repd_installed_mw", "research_state", "momentum_state",
              "as_of", "source_record_date", "source_url", "source_sha256", "research_note"]
    writer = csv.writer(stream, lineterminator="\n")
    writer.writerow(fields)
    for row in triage["records"]:
        writer.writerow([csv_text(value) for value in (
            row["rank"], row["id"], row["record_type"], row["name"], row["score"],
            row["official_status"], row["capacities"].get("repd_installed_mw"),
            row["research_state"], row["heat"]["state"], triage["as_of"],
            row["record_freshness"]["timestamp"], row["source"].get("revision_url", row["source"]["url"]),
            row["source"]["sha256"], row["research_note"])])
    csv_bytes = stream.getvalue().encode("utf-8")
    inventory = {"official_ids": ids, "solar1000_ids": pilot, "data_centre_ids": dc_ids}
    manifest = {
        "schema": SCHEMA, "as_of": as_of, "purpose": triage["purpose"],
        "publication_state": "REVIEW_ARTIFACT", "source_release": official["release"],
        "official_count": 7775, "solar_count": 3604, "solar1000_count": 1000,
        "ranked_count": triage["returned_count"], "input_count": triage["input_count"],
        "rank_scope": "Bounded research subset; not the numeric Solar-1000 selection",
        "unranked_state": "OUTSIDE_RANKED_SUBSET", "inventory": inventory,
        "inventory_sha256": sha(encoded(inventory)),
        "input_receipts": triage["input_receipts"],
        "profile_sha256": triage["profile_sha256"],
        "files": {name: {"sha256": sha(raw), "bytes": len(raw)} for name, raw in
                  (("priority.json", priority), ("priority.csv", csv_bytes))},
    }
    manifest_bytes = encoded(manifest)
    prospecting.require(len(csv_bytes) <= prospecting.MAX_BYTES and len(manifest_bytes) <= 1024 * 1024,
                        "Export output exceeds consumer size limit")
    return {"priority.json": priority, "priority.csv": csv_bytes, "manifest.json": manifest_bytes}


def write_artifacts(directory, artifacts):
    """Validate/build first, then create a new directory; never replace a pointer."""
    destination = Path(directory).resolve()
    prospecting.require(not destination.is_relative_to(prospecting.queue.ROOT / "uk_renewables_pipeline"),
                        "Do not write into immutable release trees")
    prospecting.require(set(artifacts) == {"priority.json", "priority.csv", "manifest.json"},
                        "Unexpected export files")
    manifest = json.loads(artifacts["manifest.json"])
    for name in ("priority.json", "priority.csv"):
        prospecting.require(manifest["files"][name] == {"sha256": sha(artifacts[name]),
                            "bytes": len(artifacts[name])}, "Export digest mismatch")
    destination.mkdir(parents=True, exist_ok=False)
    # Manifest is the completion receipt. An interrupted write has no valid receipt.
    for name in ("priority.json", "priority.csv", "manifest.json"):
        with (destination / name).open("xb") as stream:
            stream.write(artifacts[name])


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--as-of", required=True)
    parser.add_argument("--out-dir", required=True, type=Path)
    parser.add_argument("--limit", type=int, default=1000)
    for name in ("evidence", "datacentres"):
        parser.add_argument("--" + name, type=Path)
        parser.add_argument("--" + name + "-sha256")
    args = parser.parse_args(argv)
    inputs = {}
    for name in ("evidence", "datacentres"):
        path, digest = getattr(args, name), getattr(args, name + "_sha256")
        if bool(path) != bool(digest):
            parser.error("Optional inputs require both a file and exact SHA256")
        inputs[name] = (path, digest) if path else None
    try:
        artifacts = build_artifacts(as_of=args.as_of, limit=args.limit, **inputs)
        write_artifacts(args.out_dir, artifacts)
    except (ValueError, OSError) as exc:
        parser.exit(2, f"Priority export failed: {exc}\n")
    print(f"Priority review export complete: {json.loads(artifacts['manifest.json'])['ranked_count']} ranked; 7775 official IDs retained")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())