GLOBALGRID2050 / EXPLORE CODE

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

Renewable Energy Planning Database (REPD) Diff

A Python command-line tool in the automation folder of GlobalGrid2050 that reads solar and the REPD register, using SHA-256. It cleans ref (`clean_ref`), parses num (`parse_num`) and parses date (`parse_date`).

530 lines of Python from globalgrid2050, in 1 file. Topic: Electricity markets and data pipelines. Section 823 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. Renewable Energy Planning Database (REPD) Diff energy-data · globalgrid2050 / automation/repd/diff.py lines 474–1003

Renewable Energy Planning Database (REPD) Diff

A Python command-line tool in the automation folder of GlobalGrid2050 that reads solar and the REPD register, using SHA-256. It cleans ref (`clean_ref`), parses num (`parse_num`) and parses date (`parse_date`).

energy-dataglobalgrid2050 / automation/repd/diff.py · lines 474–1003 of 1003 (continued from section 822) · Entry point · pattern compare_hashes (shared by 2 files)

What it does
It loads solar and the REPD register. Defines 45 functions or classes, including DiffError, collapse, clean_ref, parse_num, parse_date. Uses libraries __future__, argparse, csv, hashlib, io. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): 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 diff.json; command-line arguments. Out: JSON file diff.json.
Downstream impact
Used directly by 6 files: Binder (globalgrid2050); Build Feed (globalgrid2050); Events (globalgrid2050); Test Binder (globalgrid2050); and 2 more. Reached from 4 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Test Events (globalgrid2050).
What it achieves
REPD release-over-release change report. Its code works with 1 MW and 0.0051 MW. It accepts `--previous`, `--new` and `--out`.
Why it matters
Imported by Binder, Build Feed and Events. Checked by 3 tests, including Test Binder.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
__future__, argparse, csv, hashlib, io, json, math, os
Used by
imported by Binder (import), imported by Build Feed (import), imported by Events (import), imported by Test Binder (import), imported by Test Real Data (import), imported by Test Diff (import)
Produces
DiffError, collapse, clean_ref, parse_num, parse_date, norm_value, values_differ, r3, ref_key, sha256_file, load_csv, load_identity_json
Defines here
pack, side, solar_section, mv, top_live, why_left, _cell, _table, _mw, _signed, render_md, hash_paths, compare_hashes, _inside, run, run_from_descriptor, 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/repd/diff.py:474-1003 · blob 5c42f0ebc8b8c6738261840b43b03b6dd382290d · 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

    # ---- status transitions
    trans = defaultdict(lambda: {"agg": Agg(), "old_mw": 0.0, "refs": []})
    for ref in retained:
        so, sn = text(O[ref], STATUS), text(N[ref], STATUS)
        if so == sn:
            continue
        t = trans[(so, sn)]
        t["agg"].add(cap_of(N[ref]))
        mo = cap_of(O[ref])
        t["old_mw"] += mo or 0.0
        t["refs"].append(ref)
    transitions = []
    for (so, sn), t in trans.items():
        row = {"from": so, "to": sn}
        row.update(t["agg"].out())
        row["old_mw"] = r3(t["old_mw"])
        row["refs"] = t["refs"]
        transitions.append(row)
    transitions.sort(key=lambda t: (-t["n"], -t["mw"], t["from"], t["to"]))
    changed_refs = [r for t in transitions for r in t["refs"]]
    status = {"retained_with_status_change": len(changed_refs),
              "status_changed_new_capacity": total([N[r] for r in changed_refs]),
              "distinct_transitions": len(transitions), "transitions": transitions}

    # ---- milestones by technology
    milestones = {"definitions": MILESTONE_DEFINITIONS, "categories": {}}
    for key, label, pred in MILESTONES:
        items = []
        for ref in retained:
            so, sn = text(O[ref], STATUS), text(N[ref], STATUS)
            if pred(so, sn):
                items.append((N[ref], "transition", so))
        for ref in added:
            if pred("", text(N[ref], STATUS)):
                items.append((N[ref], "new record", "(not in previous)"))
        by_tech = defaultdict(list)
        for it in items:
            by_tech[text(it[0], TECH)].append(it)

        def pack(its, top):
            tr = [i[0] for i in its if i[1] == "transition"]
            nw = [i[0] for i in its if i[1] == "new record"]
            rk = sorted(its, key=lambda i: by_mw_desc(cap_of(i[0]), i[0]["__ref"]))
            return {"all": total([i[0] for i in its]), "transition": total(tr), "new_record": total(nw),
                    "from_status": dict(sorted(Counter(i[2] for i in its if i[1] == "transition").items())),
                    "top": [dict(brief(i[0]), basis=i[1], previous_status=i[2]) for i in rk[:top]],
                    "refs": sorted((i[0]["__ref"] for i in its), key=ref_key)}

        cat = pack(items, 10)
        cat["label"] = label
        cat["by_technology"] = {t: pack(by_tech[t], 5) for t in sorted(by_tech)}
        milestones["categories"][key] = cat

    # ---- technology changes
    tech_changes = [{"ref": r, "site": collapse(N[r].get(SITE)), "from": text(O[r], TECH),
                     "to": text(N[r], TECH), "old_mw": r3(cap_of(O[r])), "new_mw": r3(cap_of(N[r]))}
                    for r in retained if text(O[r], TECH) != text(N[r], TECH)]

    # ---- capacity edits
    edits, u2k, k2u = [], [], []
    for ref in retained:
        mo, mn = cap_of(O[ref]), cap_of(N[ref])
        if mo is None and mn is None:
            continue
        row = dict(brief(N[ref]), old_mw=r3(mo), new_mw=r3(mn))
        row.pop("mw")
        if mo is None:
            u2k.append(row)
        elif mn is None:
            k2u.append(row)
        elif abs(mn - mo) > cap_tol:
            row["delta_mw"] = r3(mn - mo)
            edits.append(row)
    edits.sort(key=lambda c: (-abs(c["delta_mw"]), ref_key(c["ref"])))
    cap_by_tech = defaultdict(lambda: {"n": 0, "up": 0, "down": 0, "net_mw": 0.0})
    for c in edits:
        t = cap_by_tech[c["technology"]]
        t["n"] += 1
        t["up" if c["delta_mw"] > 0 else "down"] += 1
        t["net_mw"] += c["delta_mw"]
    capacity = {
        "tolerance_mw": cap_tol,
        "definition": "retained refs, capacity known in both releases, |new - old| > tolerance",
        "n": len(edits),
        "increases": sum(1 for c in edits if c["delta_mw"] > 0),
        "decreases": sum(1 for c in edits if c["delta_mw"] < 0),
        "gross_up_mw": r3(sum(c["delta_mw"] for c in edits if c["delta_mw"] > 0)),
        "gross_down_mw": r3(sum(c["delta_mw"] for c in edits if c["delta_mw"] < 0)),
        "net_mw": r3(sum(c["delta_mw"] for c in edits)),
        "by_technology": {k: dict(v, net_mw=r3(v["net_mw"])) for k, v in sorted(cap_by_tech.items())},
        "edits_by_abs_delta": edits,
        "unknown_to_known": {"n": len(u2k), "mw": r3(sum(c["new_mw"] for c in u2k)), "records": u2k},
        "known_to_unknown": {"n": len(k2u), "old_mw": r3(sum(c["old_mw"] for c in k2u)), "records": k2u},
    }

    # ---- per-field change counts on shared columns
    cmp_cols = [c for c in shared if c != REF]
    field_counts = Counter()
    for ref in retained:
        o, n = O[ref], N[ref]
        for c in cmp_cols:
            if values_differ(c, o.get(c, ""), n.get(c, ""), cap_tol):
                field_counts[c] += 1
    fields = [{"column": c, "retained_changed": field_counts[c]}
              for c in sorted(cmp_cols, key=lambda c: (-field_counts[c], c))]

    # ---- solar
    solar = solar_section(O, N, added, removed, retained, cap_tol)

    # ---- inputs + conventions
    def side(snap, label):
        info = dict(snap["info"])
        info["label"] = label
        return info

    return {
        "schema": SCHEMA,
        "tool": TOOL,
        "previous": side(old, old_label),
        "new": side(new, new_label),
        "conventions": {
            "basis": "unique Ref IDs; first row kept where a Ref ID repeats",
            "capacity_column": CAP,
            "capacity_rule": "blank or non-numeric capacity is UNKNOWN and excluded from MW sums (never zero)",
            "capacity_tolerance_mw": cap_tol,
            "compared_columns": len(cmp_cols),
            "columns_only_in_previous": [c for c in oh if c not in nh],
            "columns_only_in_new": [c for c in nh if c not in oh],
            "value_normalisation": "whitespace collapsed, dates to ISO (day-first only), numeric columns as numbers equal within the capacity tolerance",
        },
        "summary": {
            "previous_refs": len(O), "new_refs": len(N), "net_refs": len(N) - len(O),
            "added": len(added), "removed": len(removed), "retained": len(retained),
            "added_mw": records["added"]["total"]["mw"], "removed_mw": records["removed"]["total"]["mw"],
            "previous_mw": totals["overall"]["old_mw"], "new_mw": totals["overall"]["new_mw"],
            "delta_mw": totals["overall"]["delta_mw"],
            "status_changes": len(changed_refs),
            "status_changes_new_mw": status["status_changed_new_capacity"]["mw"],
            "capacity_edits": len(edits), "capacity_edits_net_mw": capacity["net_mw"],
            "technology_changes": len(tech_changes),
            "milestones": {k: v["all"] for k, v in milestones["categories"].items()},
        },
        "totals": totals,
        "records": records,
        "status_transitions": status,
        "milestones": milestones,
        "capacity_edits": capacity,
        "technology_changes": tech_changes,
        "field_changes": fields,
        "solar": solar,
    }


def solar_section(O, N, added, removed, retained, cap_tol, n=50) -> dict:
    """Solar movements (any status, any size) and the top-50 live solar >1 MW list."""
    moves = []

    def mv(ref, kind, o, n_):
        ob, nb = (brief(o) if o else None), (brief(n_) if n_ else None)
        mo, mn = (ob["mw"] if ob else None), (nb["mw"] if nb else None)
        rank_mw = max([m for m in (mo, mn) if m is not None], default=None)
        b = nb or ob
        moves.append({"ref": ref, "movement": kind, "site": b["site"], "operator": b["operator"],
                      "previous_status": ob["status"] if ob else None,
                      "new_status": nb["status"] if nb else None,
                      "previous_mw": mo, "new_mw": mn, "rank_mw": rank_mw, "country": b["country"]})

    for ref in added:
        if text(N[ref], TECH) == SOLAR:
            mv(ref, "added", None, N[ref])
    for ref in removed:
        if text(O[ref], TECH) == SOLAR:
            mv(ref, "removed", O[ref], None)
    for ref in retained:
        o, n_ = O[ref], N[ref]
        to, tn = text(o, TECH), text(n_, TECH)
        if SOLAR not in (to, tn):
            continue
        kinds = []
        if to != tn:
            kinds.append("technology " + ("into" if tn == SOLAR else "out of") + " solar")
        if text(o, STATUS) != text(n_, STATUS):
            kinds.append("status")
        mo, mn = cap_of(o), cap_of(n_)
        if (mo is None) != (mn is None) or (mo is not None and abs(mn - mo) > cap_tol):
            kinds.append("capacity")
        if kinds:
            mv(ref, " + ".join(kinds), o, n_)
    moves.sort(key=lambda m: by_mw_desc(m["rank_mw"], m["ref"]))

    def top_live(by_ref):
        pop = [r for r in by_ref.values()
               if text(r, TECH) == SOLAR and cap_of(r) is not None and cap_of(r) > 1.0
               and text(r, STATUS) in LIVE]
        pop.sort(key=lambda r: by_mw_desc(cap_of(r), r["__ref"]))
        return [dict(brief(r), rank=i) for i, r in enumerate(pop[:n], 1)]

    t_old, t_new = top_live(O), top_live(N)
    oi, ni = {d["ref"]: d for d in t_old}, {d["ref"]: d for d in t_new}

    def why_left(ref):
        if ref not in N:
            return "ref removed"
        r = N[ref]
        if text(r, TECH) != SOLAR:
            return "technology now " + text(r, TECH)
        if text(r, STATUS) not in LIVE:
            return "status now " + text(r, STATUS)
        return "displaced by larger schemes"

    return {
        "movement_counts": dict(sorted(Counter(m["movement"] for m in moves).items())),
        "movements_total": len(moves),
        "movements_by_mw": moves,
        "top50_live_definition": "Solar Photovoltaics, capacity > 1 MW, status in " + ", ".join(sorted(LIVE)),
        "top50_live_previous": t_old,
        "top50_live_new": t_new,
        "top50_entered": [dict(d, previous_rank=None) for d in t_new if d["ref"] not in oi],
        "top50_left": [dict(d, reason=why_left(d["ref"])) for d in t_old if d["ref"] not in ni],
        "top50_sum_mw_previous": r3(sum(d["mw"] for d in t_old)),
        "top50_sum_mw_new": r3(sum(d["mw"] for d in t_new)),
    }


# --------------------------------------------------------------------------- markdown

def _cell(x):
    if x is None:
        return ""
    if isinstance(x, bool):
        return "yes" if x else "no"
    if isinstance(x, float):
        return f"{x:,.1f}"
    if isinstance(x, int):
        return f"{x:,}"
    return str(x).replace("|", "\\|").replace("\n", " ")


def _table(headers, rows) -> list:
    out = ["| " + " | ".join(headers) + " |", "|" + "|".join("---" for _ in headers) + "|"]
    out += ["| " + " | ".join(_cell(v) for v in row) + " |" for row in rows]
    return out + [""]


def _mw(x):
    return "unknown" if x is None else f"{x:,.1f}"


def _signed(x, mw=False):
    if x is None:
        return ""
    return f"{x:+,.1f}" if mw else f"{x:+,}"


def render_md(d: dict, top_added: int = 15, top_edits: int = 15, top_solar: int = 50) -> str:
    p, n, s, c = d["previous"], d["new"], d["summary"], d["conventions"]
    L = []
    A = L.extend
    L.append(f"# REPD change report: {p['label']} -> {n['label']}")
    L.append("")
    L.append(f"Generated by `{TOOL}` ({SCHEMA}). Full lists in `diff.json`. "
             "Blank capacity is unknown, never zero: MW figures sum known capacities only.")
    L.append("")
    L.append("## Inputs")
    L.append("")
    A(_table(["", "Previous", "New"], [
        ["Label", p["label"], n["label"]],
        ["File", p["file"], n["file"]],
        ["SHA-256", p["sha256"], n["sha256"]],
        ["Kind", p["kind"], n["kind"]],
        ["Rows / unique refs", f"{p['source_rows']:,} / {p['unique_refs']:,}",
         f"{n['source_rows']:,} / {n['unique_refs']:,}"],
        ["Max Record Last Updated", p["max_record_last_updated"], n["max_record_last_updated"]],
        ["Fidelity", p["fidelity"], n["fidelity"]],
    ]))
    for side, info in (("previous", p), ("new", n)):
        for dup in info["duplicate_refs"]:
            L.append(f"- Duplicate Ref ID in {side}: {dup['ref']} ({dup['site']}) x{dup['rows']}, "
                     f"{dup['kind']}; first row kept.")
    L.append(f"- Columns compared: {c['compared_columns']}; capacity edit tolerance {c['capacity_tolerance_mw']} MW.")
    if c["columns_only_in_new"] and p["kind"].startswith("derived"):
        L.append(f"- {len(c['columns_only_in_new'])} official columns are not in the derived previous file and are not compared.")
    elif c["columns_only_in_previous"] or c["columns_only_in_new"]:
        L.append(f"- Columns only in previous: {c['columns_only_in_previous'] or 'none'}; "
                 f"only in new: {c['columns_only_in_new'] or 'none'}.")
    L.append("")

    o = d["totals"]["overall"]
    L.append("## Headline")
    L.append("")
    L.append(f"- Records: {s['previous_refs']:,} -> {s['new_refs']:,} ({_signed(s['net_refs'])}): "
             f"{s['added']:,} added ({_mw(s['added_mw'])} MW), {s['removed']:,} removed "
             f"({_mw(s['removed_mw'])} MW), {s['retained']:,} retained.")
    L.append(f"- Capacity, all statuses: {_mw(s['previous_mw'])} -> {_mw(s['new_mw'])} MW "
             f"({_signed(s['delta_mw'], True)} MW); unknown-capacity records "
             f"{o['old_n_unknown_mw']:,} -> {o['new_n_unknown_mw']:,}.")
    L.append(f"- Status changes on retained records: {s['status_changes']:,} "
             f"({_mw(s['status_changes_new_mw'])} MW at new capacity).")
    for key, m in s["milestones"].items():
        cat = d["milestones"]["categories"][key]
        L.append(f"- {cat['label']}: {m['n']:,} ({_mw(m['mw'])} MW; {m['n_unknown_mw']} unknown capacity), "
                 f"{cat['transition']['n']:,} transitions + {cat['new_record']['n']:,} new records.")
    ce = d["capacity_edits"]
    L.append(f"- Capacity edits: {ce['n']:,} ({ce['increases']} up, {ce['decreases']} down, net "
             f"{_signed(ce['net_mw'], True)} MW); unknown->known {ce['unknown_to_known']['n']} "
             f"({_mw(ce['unknown_to_known']['mw'])} MW), known->unknown {ce['known_to_unknown']['n']}.")
    L.append(f"- Technology type changes: {s['technology_changes']}.")
    L.append("")

    L.append("## Totals by technology")
    L.append("")
    A(_table(["Technology", "Prev n", "New n", "Delta n", "Prev MW", "New MW", "Delta MW", "Unknown cap. (new)"],
             [[r["key"], r["old_n"], r["new_n"], _signed(r["delta_n"]), r["old_mw"], r["new_mw"],
               _signed(r["delta_mw"], True), r["new_n_unknown_mw"]] for r in d["totals"]["by_technology"]]))
    L.append("## Totals by status")
    L.append("")
    A(_table(["Status", "Prev n", "New n", "Delta n", "Prev MW", "New MW", "Delta MW"],
             [[r["key"], r["old_n"], r["new_n"], _signed(r["delta_n"]), r["old_mw"], r["new_mw"],
               _signed(r["delta_mw"], True)] for r in d["totals"]["by_status"]]))

    ad, rm = d["records"]["added"], d["records"]["removed"]
    L.append(f"## Records added: {ad['total']['n']:,} ({_mw(ad['total']['mw'])} MW)")
    L.append("")
    A(_table(["Technology", "n", "MW", "Unknown MW"],
             [[k, v["n"], v["mw"], v["n_unknown_mw"]]
              for k, v in sorted(ad["by_technology"].items(), key=lambda kv: (-kv[1]["n"], kv[0]))]))
    L.append(f"Largest {top_added} added:")
    L.append("")
    A(_table(["Ref", "Site", "Technology", "Status", "MW", "Operator"],
             [[x["ref"], x["site"], x["technology"], x["status"], x["mw"], x["operator"]]
              for x in ad["records_by_mw"][:top_added]]))
    L.append(f"## Records removed: {rm['total']['n']:,} ({_mw(rm['total']['mw'])} MW)")
    L.append("")
    A(_table(["Ref", "Site", "Technology", "Status (previous)", "MW"],
             [[x["ref"], x["site"], x["technology"], x["status"], x["mw"]]
              for x in rm["records_by_mw"][:top_added]]))
    if rm["total"]["n"] > top_added:
        L.append(f"({rm['total']['n'] - top_added} more in diff.json)")
        L.append("")

    st = d["status_transitions"]
    L.append(f"## Status transitions: {st['retained_with_status_change']:,} records, "
             f"{st['distinct_transitions']} distinct")
    L.append("")
    A(_table(["From", "To", "n", "MW (new)", "Unknown MW"],
             [[t["from"], t["to"], t["n"], t["mw"], t["n_unknown_mw"]] for t in st["transitions"]]))

    L.append("## Milestones by technology")
    L.append("")
    for key, defn in MILESTONE_DEFINITIONS.items():
        if key != "basis":
            L.append(f"- {key}: {defn}.")
    L.append(f"- {MILESTONE_DEFINITIONS['basis']}")
    L.append("")
    for key, cat in d["milestones"]["categories"].items():
        a = cat["all"]
        L.append(f"### {cat['label']}: {a['n']:,} ({_mw(a['mw'])} MW)")
        L.append("")
        if not a["n"]:
            L.append("None.")
            L.append("")
            continue
        A(_table(["Technology", "n", "MW", "Transitions", "New records", "Unknown MW", "Largest scheme"],
                 [[t, v["all"]["n"], v["all"]["mw"], v["transition"]["n"], v["new_record"]["n"],
                   v["all"]["n_unknown_mw"],
                   (f"{v['top'][0]['ref']} {v['top'][0]['site']} ({_mw(v['top'][0]['mw'])} MW)" if v["top"] else "")]
                  for t, v in sorted(cat["by_technology"].items(),
                                     key=lambda kv: (-kv[1]["all"]["mw"], kv[0]))]))
        L.append("Top schemes:")
        L.append("")
        A(_table(["Ref", "Site", "Technology", "MW", "Basis", "Previous status", "Operator"],
                 [[x["ref"], x["site"], x["technology"], x["mw"], x["basis"], x["previous_status"], x["operator"]]
                  for x in cat["top"]]))

    L.append(f"## Capacity edits (|delta| > {ce['tolerance_mw']} MW): {ce['n']}")
    L.append("")
    if ce["by_technology"]:
        A(_table(["Technology", "n", "Up", "Down", "Net MW"],
                 [[k, v["n"], v["up"], v["down"], _signed(v["net_mw"], True)] for k, v in ce["by_technology"].items()]))
        A(_table(["Ref", "Site", "Technology", "Status", "Prev MW", "New MW", "Delta MW"],
                 [[x["ref"], x["site"], x["technology"], x["status"], x["old_mw"], x["new_mw"],
                   _signed(x["delta_mw"], True)] for x in ce["edits_by_abs_delta"][:top_edits]]))
    L.append(f"Unknown -> known: {ce['unknown_to_known']['n']} ({_mw(ce['unknown_to_known']['mw'])} MW). "
             f"Known -> unknown: {ce['known_to_unknown']['n']} ({_mw(ce['known_to_unknown']['old_mw'])} MW previously). "
             "Neither is in the net edit figure.")
    L.append("")
    if d["technology_changes"]:
        L.append(f"## Technology type changes: {len(d['technology_changes'])}")
        L.append("")
        A(_table(["Ref", "Site", "From", "To", "New MW"],
                 [[t["ref"], t["site"], t["from"], t["to"], t["new_mw"]] for t in d["technology_changes"]]))

    so = d["solar"]
    L.append(f"## Solar: top {top_solar} movements by MW ({so['movements_total']:,} solar records moved)")
    L.append("")
    L.append("Movement = added, removed, status change, capacity edit or technology change on a "
             "Solar Photovoltaics record (any size). Ranked by the larger of previous/new MW. Counts: "
             + "; ".join(f"{k} {v}" for k, v in so["movement_counts"].items()) + ".")
    L.append("")
    A(_table(["#", "Ref", "Site", "Movement", "Prev status", "New status", "Prev MW", "New MW", "Operator"],
             [[i, m["ref"], m["site"], m["movement"], m["previous_status"], m["new_status"],
               m["previous_mw"], m["new_mw"], m["operator"]]
              for i, m in enumerate(so["movements_by_mw"][:top_solar], 1)]))
    L.append(f"Top-50 live solar list ({so['top50_live_definition']}): sum "
             f"{_mw(so['top50_sum_mw_previous'])} -> {_mw(so['top50_sum_mw_new'])} MW; "
             f"{len(so['top50_entered'])} entered, {len(so['top50_left'])} left.")
    L.append("")
    if so["top50_entered"]:
        A(_table(["New rank", "Ref", "Site", "MW", "Status"],
                 [[x["rank"], x["ref"], x["site"], x["mw"], x["status"]] for x in so["top50_entered"]]))
    if so["top50_left"]:
        A(_table(["Old rank", "Ref", "Site", "MW", "Reason"],
                 [[x["rank"], x["ref"], x["site"], x["mw"], x["reason"]] for x in so["top50_left"]]))

    L.append("## Field changes on retained records")
    L.append("")
    A(_table(["Column", "Records changed"],
             [[f["column"], f["retained_changed"]] for f in d["field_changes"] if f["retained_changed"]]))
    return "\n".join(L).rstrip("\n") + "\n"


# --------------------------------------------------------------------------- hash guard

def hash_paths(paths) -> dict:
    """{path: sha256} for every file under each path (files or directories), sorted."""
    out = {}
    for p in paths:
        p = Path(p)
        if p.is_dir():
            for root, dirs, files in os.walk(p):
                dirs[:] = sorted(x for x in dirs if x != ".git")
                for f in sorted(files):
                    fp = Path(root) / f
                    out[str(fp)] = sha256_file(fp)
        elif p.is_file():
            out[str(p)] = sha256_file(p)
        else:
            raise DiffError(f"protected path does not exist: {p}")
    return dict(sorted(out.items()))


def compare_hashes(before: dict, after: dict) -> list:
    problems = []
    for k in sorted(set(before) | set(after)):
        if k not in after:
            problems.append(f"deleted: {k}")
        elif k not in before:
            problems.append(f"created: {k}")
        elif before[k] != after[k]:
            problems.append(f"modified: {k}")
    return problems


def _inside(child: Path, parent: Path) -> bool:
    try:
        child.resolve().relative_to(parent.resolve())
        return True
    except ValueError:
        return False


# --------------------------------------------------------------------------- run

def run(previous, new, out_dir, previous_label="previous", new_label="new",
        cap_tol=DEFAULT_CAP_TOL, protect=()) -> dict:
    out = Path(out_dir)
    protected = [Path(previous), Path(new)] + [Path(p) for p in protect]
    for p in protected:
        if p.is_dir() and _inside(out, p):
            raise DiffError(f"--out {out} is inside protected path {p}; choose another directory")
        for name in ("diff.json", "changelog.md"):
            if p.is_file() and (out / name).resolve() == p.resolve():
                raise DiffError(f"--out would overwrite protected file {p}")
    before = hash_paths(protected)
    new_snap = load_csv(new)
    old_snap = load_previous(previous, header_reference=new_snap["header"])
    d = build_diff(old_snap, new_snap, previous_label, new_label, cap_tol)
    md = render_md(d)
    out.mkdir(parents=True, exist_ok=True)
    (out / "diff.json").write_text(json.dumps(d, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
    (out / "changelog.md").write_text(md, encoding="utf-8")
    problems = compare_hashes(before, hash_paths(protected))
    if problems:
        raise DiffError("hash guard: protected files changed during the run: " + "; ".join(problems))
    d["_hash_guard"] = {"protected_files": len(before), "unchanged": True}
    return d


def run_from_descriptor(desc: dict) -> dict:
    """Release-descriptor entry point. Keys: previous, new, out, previous_label, label,
    capacity_tolerance (optional), protect (optional list)."""
    for k in ("previous", "new", "out"):
        if not desc.get(k):
            raise DiffError(f"release descriptor lacks '{k}'")
    return run(desc["previous"], desc["new"], desc["out"], desc.get("previous_label", "previous"),
               desc.get("label", "new"), float(desc.get("capacity_tolerance", DEFAULT_CAP_TOL)),
               desc.get("protect", ()))


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description="REPD release-over-release change report.")
    ap.add_argument("--previous", required=True, help="official-layout CSV or project_identity_v6.json")
    ap.add_argument("--new", required=True, help="cleaned canonical CSV")
    ap.add_argument("--out", required=True, help="output directory (changelog.md, diff.json)")
    ap.add_argument("--previous-label", default="previous")
    ap.add_argument("--new-label", default="new")
    ap.add_argument("--capacity-tolerance", type=float, default=DEFAULT_CAP_TOL)
    ap.add_argument("--protect", action="append", default=[],
                    help="file or directory that must be byte-identical after the run (repeatable)")
    args = ap.parse_args(argv)
    try:
        d = run(args.previous, args.new, args.out, args.previous_label, args.new_label,
                args.capacity_tolerance, args.protect)
    except DiffError as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 3 if str(exc).startswith("hash guard") else 2
    s = d["summary"]
    print(f"{d['previous']['label']}: {s['previous_refs']} refs; {d['new']['label']}: {s['new_refs']} refs")
    print(f"added {s['added']} ({s['added_mw']} MW), removed {s['removed']} ({s['removed_mw']} MW), "
          f"retained {s['retained']}; status changes {s['status_changes']}; "
          f"capacity edits {s['capacity_edits']} (net {s['capacity_edits_net_mw']} MW)")
    print("milestones: " + ", ".join(f"{k} {v['n']} / {v['mw']} MW" for k, v in s["milestones"].items()))
    print(f"hash guard: {d['_hash_guard']['protected_files']} protected files unchanged")
    print(f"wrote {Path(args.out) / 'changelog.md'} and {Path(args.out) / 'diff.json'}")
    return 0


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