GLOBALGRID2050 / EXPLORE CODE

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

Combine and 1 more file

A Python command-line tool in the signals folder of GlobalGrid2050 that reads reviewed signals, top200 solar, aliases and exclusions.

478 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 791 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. Combine render · globalgrid2050 / automation/news/signals/combine.py lines 701–1077
  2. Dates transform · globalgrid2050 / automation/news/signals/dates.py lines 1–101

Combine

A Python command-line tool in the signals folder of GlobalGrid2050 that reads reviewed signals, top200 solar, aliases and exclusions.

renderglobalgrid2050 / automation/news/signals/combine.py · lines 701–1077 of 1077 (continued from section 790) · Entry point · pattern phrase_in (shared by 2 files)

What it does
It loads reviewed signals, top200 solar, aliases and exclusions. Defines 45 functions or classes, including now_utc, read_json, _host_in, _excluded, _norm. Uses libraries __future__, argparse, datetime, json, re. Side effects: changes the web page (DOM); 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.
Inputs & outputs
In: JSON file reviewed_signals.json; JSON file top200_solar.json; JSON file aliases.json; JSON file exclusions.json; JSON file alias_standings.json; JSON file index_ground_truth.json; JSON file project_signals.json; command-line arguments.
Downstream impact
Used directly by 1 file: News — Signals (globalgrid2050).
What it achieves
It reads JSON (`read_json`), parses date (`parse_date`) and cleans planning file (`clean_planning_file`). Part files and the planning files become one file. It accepts `--top200`, `--aliases` and `--exclusions`.
Why it matters
Imported by News — Signals.
Application
globalgrid2050 · automation/news/signals · Python CLI
Uses
Dates (import), Gate (import), Planning File (import), __future__, argparse, datetime, json, re, sys, urllib.parse, pathlib
Used by
imported by News — Signals (import)
Produces
now_utc, read_json, phrase_in, title_key, is_reviewed, parse_date, freshness, tier_of, event_of, order_key, alias_standing, alias_words
Defines here
schema_errors, need, with_any_item, publication_check, load_truth, truth_report, _cell, summary, 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/combine.py:701-1077 · blob 902eccca452dd82e8018c1c106dec7d0b75cff9a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
                part_state[team] = {"status": "failed", "collected_at": None, "items": 0, "note": why}
            continue
        kept = 0
        if good:                                            # this run's items first: on a shared link they win
            stamp = part.get("generated_at") if isinstance(part.get("generated_at"), str) else run_at
            kept = sum(1 for raw in part["items"] if take(dict(raw, collected_at=None, source=team), team, stamp))
        kept_old = sum(1 for raw in old_items[team] if take(raw, team, old_when[team]))
        if good:
            part_state[team] = {"status": "ok", "collected_at": stamp, "items": kept, "note": ""}
        elif kept_old:
            part_state[team] = {"status": "stale", "collected_at": old_when[team], "items": kept_old,
                                "note": why + "; items published before are kept with their own dates"}
        else:
            part_state[team] = {"status": "failed", "collected_at": None, "items": 0,
                                "note": why + "; nothing published before to keep"}

    # one link, one project, unless the title names each or a reviewer tied it to each
    homes = {}
    for ref in refs:
        gathered[ref] = dedupe(gathered[ref])
        for item in gathered[ref]:
            homes.setdefault(link_key(item["link"]), []).append(ref)
    for link, on in homes.items():
        if len(on) < 2:
            continue
        found = {ref: next(i for i in gathered[ref] if link_key(i["link"]) == link) for ref in on}
        named = {ref: names_project(found[ref]["title"], aliases.get(ref) or {}, rows_by_ref[ref]) for ref in on}
        # A reviewed record is a source discovery method, not itself evidence
        # that one URL concerns every REPD row to which it was pasted. The
        # specific identity of *each* project must be supported independently.
        # This also permits a genuinely two-project headline when both names
        # occur; a future reviewed binding may qualify only with a separately
        # audited project-specific receipt.
        keep = [ref for ref in on if named[ref]]
        if not keep:
            keep = [min(on, key=lambda ref: (found[ref]["confidence"] != "confirmed",
                                              standing(ref) != "confirmed",
                                              rows_by_ref[ref].get("rank") or 10 ** 6))]
        for ref in on:
            if ref not in keep:
                gathered[ref] = [i for i in gathered[ref] if link_key(i["link"]) != link]
                dropped["link on several projects"] += 1
            elif len(keep) > 1:
                found[ref]["also_projects"] = sorted((r for r in keep if r != ref), key=lambda r: (len(r), r))
                if not named[ref] and not PLURAL_RE.search(found[ref]["title"]) and found[ref]["confidence"] == "confirmed":
                    found[ref]["confidence"] = "possible"   # tied by hand to several projects, the title names none
                    downgraded["shared link that names no project"] += 1

    # planning files
    plan_origin = {}
    files = {}
    for row in rows:
        ref = str(row["repd_ref"])
        entry = aliases.get(ref) or {}
        file, origin = clean_planning_file(planning.get(ref)), "planning"
        if not file and use_module:
            file, origin = module_planning_file(dict(row, planning_file=entry.get("planning_file"))), "module"
        if not file:
            file, origin = clean_planning_file(entry.get("planning_file")), "aliases"
        if not file:
            file, origin = clean_planning_file(last_resort(row)), "last_resort"
        files[ref], plan_origin[ref] = file, origin
    from_file = sum(1 for o in plan_origin.values() if o == "planning")
    if from_file:
        stamp = plan_data.get("generated_at") if plan_data and isinstance(plan_data.get("generated_at"), str) else run_at
        part_state["planning"] = {"status": "ok", "collected_at": stamp, "items": sum(1 for f in files.values() if f),
                                  "note": "" if from_file == len(refs) else "%d from the planning run, the rest from the alias table" % from_file}
    else:
        part_state["planning"] = {"status": "absent", "collected_at": None, "items": sum(1 for f in files.values() if f),
                                  "note": "no planning run; links built from the alias table and the REPD row"}

    projects = {}
    counts = {"projects": len(refs), "headline": {"label": HEADLINE, "value": 0},
              "by_tier": {t: 0 for t in PROJECT_TIERS}, "possible_only": 0,
              "with_recent_news": 0, "with_official": 0, "with_archive": 0, "with_possible_recent_news": 0,
              "items": {t: 0 for t in TIERS},
              "planning_file": {"verified_direct": 0, "unverified_direct": 0, "register_search": 0, "register_finder": 0}}
    label_count = dict(zip(PLANNING_LABELS, ("verified_direct", "unverified_direct", "register_search", "register_finder")))
    for row in rows:
        ref = str(row["repd_ref"])
        entry = aliases.get(ref) or {}
        lists = {}
        for tier in TIERS:
            shown = cluster(ref, [i for i in gathered[ref] if i["tier"] == tier])[:MAX_PER_TIER]
            lists[tier] = [{k: v for k, v in i.items() if k != "repd_ref"} for i in shown]
            counts["items"][tier] += len(lists[tier])
        confirmed = {t: any(i["confidence"] == "confirmed" for i in lists[t]) for t in TIERS}
        any_item = any(lists[t] for t in TIERS)
        file = files[ref]
        if confirmed["recent_news"]:
            tier = "recent_news"
        elif confirmed["official"]:
            tier = "official"
        elif any_item:
            tier = "archive_only"
            counts["possible_only"] += not confirmed["archive"]
        elif file:
            tier = "planning_file_only"
        else:
            tier = "nothing"
        counts["by_tier"][tier] += 1
        counts["with_recent_news"] += confirmed["recent_news"]
        counts["with_official"] += confirmed["official"]
        counts["with_archive"] += bool(lists["archive"])
        counts["with_possible_recent_news"] += bool(lists["recent_news"]) and not confirmed["recent_news"]
        if file:
            counts["planning_file"][label_count[file["label"]]] += 1
        names = entry.get("aliases") or []
        projects[ref] = {"repd_ref": ref, "rank": row.get("rank"), "site_name": (row.get("site_name") or "").strip(),
                         "alias": names[0] if names and isinstance(names[0], str) else (row.get("site_name") or "").strip(),
                         "alias_standing": standing(ref), "tier": tier,
                         "recent_news": lists["recent_news"], "official": lists["official"], "archive": lists["archive"],
                         "planning_file": file}
    counts["headline"]["value"] = counts["by_tier"]["recent_news"]
    collected = [part_state[t]["collected_at"] for t in LIVE_TEAMS if part_state[t]["status"] == "ok" and part_state[t]["collected_at"]]
    generated = max(collected) if collected else old_generated
    stale = any(part_state[t]["status"] in ("stale", "failed") for t in LIVE_TEAMS)
    return {"schema": SCHEMA, "generated_at": generated, "run_at": run_at, "stale": stale, "scope": SCOPE,
            "recent_days": RECENT_DAYS, "parts": {name: part_state[name] for name in PART_NAMES}, "counts": counts,
            "dropped": dropped, "downgraded": downgraded, "sources": sources, "projects": projects}


# ---------------------------------------------------------------- the writer's checks (fail closed)

def schema_errors(result, expected_refs=None):
    """Every way the file breaks the version 2 contract (an empty list means it may be published)."""
    errors = []

    def need(ok, message):
        if not ok and len(errors) < 40:
            errors.append(message)

    if not isinstance(result, dict):
        return ["not an object"]
    need(result.get("schema") == SCHEMA, "schema is not %s" % SCHEMA)
    stamp = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$")
    need(result.get("generated_at") is None or (isinstance(result.get("generated_at"), str) and stamp.match(result["generated_at"])),
         "generated_at is not a timestamp or null")
    need(isinstance(result.get("run_at"), str) and stamp.match(result.get("run_at") or ""), "run_at is not a timestamp")
    parts = result.get("parts") if isinstance(result.get("parts"), dict) else {}
    for name in PART_NAMES:
        state = parts.get(name)
        need(isinstance(state, dict) and state.get("status") in ("ok", "stale", "failed", "absent")
             and "collected_at" in state, "parts.%s lacks status or collected_at" % name)
    live_ok = [parts[t]["collected_at"] for t in LIVE_TEAMS
               if isinstance(parts.get(t), dict) and parts[t].get("status") == "ok" and parts[t].get("collected_at")]
    if live_ok:
        need(result.get("generated_at") == max(live_ok), "generated_at is not the newest successful collection")
    projects = result.get("projects") if isinstance(result.get("projects"), dict) else {}
    counts = result.get("counts") if isinstance(result.get("counts"), dict) else {}
    by_tier = counts.get("by_tier") if isinstance(counts.get("by_tier"), dict) else {}
    need(set(by_tier) == set(PROJECT_TIERS), "counts.by_tier keys are wrong")
    need(sum(v for v in by_tier.values() if isinstance(v, int)) == len(projects) == counts.get("projects"),
         "counts.by_tier does not sum to the number of projects")
    need(isinstance(counts.get("headline"), dict) and counts["headline"].get("value") == by_tier.get("recent_news"),
         "headline does not equal the candidate recent-news count")
    if expected_refs is not None:
        need(set(projects) == {str(r) for r in expected_refs}, "the projects are not the expected set")
    need(by_tier.get("nothing") == 0, "%s project(s) have neither an item nor a planning file" % by_tier.get("nothing"))
    today = dt.date.fromisoformat(result["run_at"][:10]) if isinstance(result.get("run_at"), str) and stamp.match(result["run_at"]) else None
    for ref, project in projects.items():
        if not isinstance(project, dict):
            need(False, "%s is not an object" % ref)
            continue
        file = project.get("planning_file")
        need(isinstance(file, dict) and file.get("label") in PLANNING_LABELS and str(file.get("url") or "").startswith("https://"),
             "%s: planning_file missing or mislabelled" % ref)
        need(project.get("tier") in PROJECT_TIERS, "%s: tier" % ref)
        links = []
        for tier in TIERS:
            items = project.get(tier)
            if not isinstance(items, list):
                need(False, "%s: %s is not a list" % (ref, tier))
                continue
            keys = []
            for item in items:
                where = "%s %s" % (ref, tier)
                if not isinstance(item, dict):
                    need(False, where + ": item is not an object")
                    continue
                links.append(item.get("link"))
                need(isinstance(item.get("title"), str) and item["title"] and str(item.get("link") or "").startswith("https://"),
                     where + ": title or link")
                need(item.get("tier") == tier, where + ": item tier differs from its list")
                need(item.get("confidence") in ("confirmed", "possible"), where + ": confidence")
                need(item.get("obtained") in ("fetched", "reviewed"), where + ": obtained")
                need(item.get("event") is None or item.get("event") in EVENTS, where + ": event")
                need(isinstance(item.get("collected_at"), str) and item["collected_at"], where + ": collected_at")
                date = item.get("date")
                if date is None:
                    need(item.get("freshness") == "undated" and tier == "archive"
                         and (item.get("year") is None or isinstance(item.get("year"), int)),
                         where + ": undated item outside the archive or mislabelled")
                elif today is not None:
                    need(parse_date(date, today) == date, where + ": date %r is not a past calendar date" % (date,))
                    if parse_date(date, today) == date:
                        need(item.get("freshness") == freshness(date, today) and item.get("year") == int(date[:4]),
                             where + ": freshness or year does not follow from the date")
                        need(tier != "recent_news" or item.get("freshness") == "recent", where + ": old item in recent_news")
                if isinstance(item.get("link"), str) and item.get("confidence") in ("confirmed", "possible") and item.get("family") in FAMILIES:
                    keys.append(order_key(item))
            need(keys == sorted(keys), "%s %s: not in order (newest dated first)" % (ref, tier))
        need(len(links) == len(set(links)), "%s: a link appears twice" % ref)
    return errors


def with_any_item(result):
    return sum(1 for p in (result.get("projects") or {}).values() if any(p.get(t) for t in TIERS))


def publication_check(result, previous, expected_refs=None):
    """Reasons not to publish (empty: publish). Schema first, then a sharp drop against the published version 2 file."""
    reasons = ["schema: " + e for e in schema_errors(result, expected_refs)]
    if isinstance(previous, dict) and previous.get("schema") == SCHEMA and not reasons:
        pairs = (("projects with any item", with_any_item(previous), with_any_item(result)),
                 ("items", sum((previous.get("counts") or {}).get("items", {}).values() or [0]), sum(result["counts"]["items"].values())))
        for name, before, after in pairs:
            if before >= 6 and after < before * (1 - DROP_LIMIT):
                reasons.append("sharp drop: %s fell from %d to %d (more than a third)" % (name, before, after))
    return reasons


# ---------------------------------------------------------------- ground truth (the members' findings)

def load_truth(path):
    data, state = read_json(path)
    if state != "ok" or not isinstance(data, dict) or data.get("schema") != TRUTH_SCHEMA:
        return {}
    return data.get("projects") or {}


def truth_report(truth, signals_by_ref, label="all parts"):
    """Markdown: of the projects the members marked "found", how many the automated run finds, by family."""
    found = {ref: t for ref, t in truth.items() if t.get("status") == "found"}
    if not truth:
        return "### Ground truth\n\nNo ground-truth file.\n"
    hit = [ref for ref in found if signals_by_ref.get(ref)]
    lines = ["### Compared with the members' ground truth (%s)\n" % label,
             "Ground truth covers %d projects: %d found, %d uncertain, %d none, %d not searched." % (
                 len(truth), len(found), sum(1 for t in truth.values() if t.get("status") == "uncertain"),
                 sum(1 for t in truth.values() if t.get("status") == "none"),
                 sum(1 for t in truth.values() if t.get("status") not in ("found", "uncertain", "none"))),
             "Of the %d found by a member, the automated run has at least one signal for **%d**.\n" % (len(found), len(hit)),
             "| family in ground truth | projects | automated: any signal | automated: same family | same link |",
             "|---|---|---|---|---|"]
    for family in FAMILIES:
        refs = [ref for ref, t in found.items() if family in (t.get("families") or [])]
        any_signal = sum(1 for ref in refs if signals_by_ref.get(ref))
        same = sum(1 for ref in refs if any(s["family"] == family for s in signals_by_ref.get(ref) or []))
        links = sum(1 for ref in refs
                    if {D.canonical_link(l) for l in found[ref].get("links") or []} & {s["link"] for s in signals_by_ref.get(ref) or []})
        lines.append("| %s | %d | %d | %d | %d |" % (family, len(refs), any_signal, same, links))
    extra = [ref for ref, t in truth.items() if t.get("status") != "found" and signals_by_ref.get(ref)]
    lines.append("\nAutomated signals for projects a member did not mark found: %d%s." % (
        len(extra), (" (REPD " + ", ".join(sorted(extra, key=lambda r: (len(r), r))[:30]) + ")") if extra else ""))
    missed = sorted((ref for ref in found if not signals_by_ref.get(ref)), key=lambda r: (len(r), r))
    if missed:
        lines.append("Found by a member, not by the run: REPD " + ", ".join(missed[:80]) + ".")
    return "\n".join(lines) + "\n"


def _cell(text):
    return str(text if text is not None else "").replace("|", "/").replace("[", "(").replace("]", ")")


def summary(result, truth=None, reasons=None, published=True):
    c = result["counts"]
    t = c["by_tier"]
    lines = ["## Project signals: combined file (version 2)\n",
             "### Publication\n",
             ("**Published.**" if published else "**Not published: the file on the data branch stays as it was.**")
             + " Last successful live collection (generated_at): %s. This run: %s.%s\n" % (
                 result["generated_at"] or "never", result["run_at"],
                 " **Stale: at least one live part did not collect in this run.**" if result["stale"] else "")]
    for reason in reasons or []:
        lines.append("- refused because: %s" % reason)
    lines += ["\n### Counts by tier (%s; each of the %d projects is counted once)\n" % (result["scope"], c["projects"]),
              "**%s: %d of %d** (a publisher's item dated within %d days of this run, confirmed match).\n" % (
                  HEADLINE.capitalize(), c["headline"]["value"], c["projects"], result["recent_days"]),
              "| tier | projects |\n|---|---|",
              "| with recent news | %d |" % t["recent_news"],
              "| with an official item (and no recent news) | %d |" % t["official"],
              "| with archive only (older or undated items, shown with their year) | %d |" % t["archive_only"],
              "| with planning file only | %d |" % t["planning_file_only"],
              "| with nothing (zero) | %d |" % t["nothing"],
              "\nNot exclusive: %d projects have a confirmed official item, %d have an archive item, %d have only a possible "
              "match in recent news. Of the archive-only projects %d have possible matches only (shown as possible, never "
              "as fact)." % (c["with_official"], c["with_archive"], c["with_possible_recent_news"], c["possible_only"]),
              "Items listed: recent news %d, official %d, archive %d." % (c["items"]["recent_news"], c["items"]["official"], c["items"]["archive"]),
              "Planning files: %d verified direct links, %d unverified direct links, %d register searches, %d register "
              "finders." % tuple(c["planning_file"][k] for k in ("verified_direct", "unverified_direct", "register_search", "register_finder")),
              "\n### Parts\n", "| part | status | collected_at | items | note |\n|---|---|---|---|---|"]
    for name, state in result["parts"].items():
        lines.append("| %s | %s | %s | %d | %s |" % (name, state["status"], state["collected_at"] or "", state["items"], _cell(state["note"])))
    lines.append("\nDropped: %s. Downgraded to possible: %s.\n" % (
        ", ".join("%s %d" % kv for kv in result["dropped"].items() if kv[1]) or "none",
        ", ".join("%s %d" % kv for kv in result["downgraded"].items() if kv[1]) or "none"))
    lines.append("| team | source | status | requests | failures | items | error |\n|---|---|---|---|---|---|---|")
    for s in result["sources"]:
        lines.append("| %s | %s | %s | %s | %s | %s | %s |" % (s["team"], s["id"], s["status"], s["requests"], s["failures"],
                                                                s["items"], _cell(s["error"])))
    if truth is not None:
        lines.append("\n" + truth_report(truth, {ref: [i for tier in TIERS for i in p[tier]] for ref, p in result["projects"].items()}))
    lines.append("\n### The %d\n\n| rank | REPD | alias | tier | shown | date | publisher | title or reference |\n|---|---|---|---|---|---|---|---|" % c["projects"])
    for p in sorted(result["projects"].values(), key=lambda p: p["rank"] or 0):
        shown = next((p[tier][0] for tier in TIERS if p[tier] and p[tier][0]["confidence"] == "confirmed"), None) or \
            next((p[tier][0] for tier in TIERS if p[tier]), None)
        if shown:
            lines.append("| %s | %s | %s | %s | %s, %s%s%s | %s | %s | [%s](%s) |" % (
                p["rank"], p["repd_ref"], _cell(p["alias"]), p["tier"], shown["tier"], shown["obtained"],
                "" if shown["confidence"] == "confirmed" else ", possible match",
                (", " + shown["event"]) if shown["event"] else "", shown["date"] or "undated", _cell(shown["publisher"]),
                _cell(shown["title"]), shown["link"]))
        else:
            f = p["planning_file"] or {}
            lines.append("| %s | %s | %s | %s | %s | | %s | [%s](%s) |" % (
                p["rank"], p["repd_ref"], _cell(p["alias"]), p["tier"], f.get("label") or "none", _cell(f.get("authority")),
                _cell(f.get("reference") or f.get("kind") or "none"), f.get("url") or ""))
    return "\n".join(lines) + "\n"


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    for team in TEAMS:
        ap.add_argument("--" + team, default=None, help="part file of team %s (optional)" % team)
    ap.set_defaults(reviewed=str(HERE / "reviewed_signals.json"))
    ap.add_argument("--top200", default=str(HERE / "top200_solar.json"))
    ap.add_argument("--aliases", default=str(HERE / "aliases.json"))
    ap.add_argument("--exclusions", default=str(HERE / "exclusions.json"))
    ap.add_argument("--standings", default=str(HERE / "alias_standings.json"))
    ap.add_argument("--planning", default=None, help="optional {repd_ref: planning_file} file")
    ap.add_argument("--previous", default=None, help="the file published last time; its items are kept")
    ap.add_argument("--truth", default=str(HERE / "index_ground_truth.json"))
    ap.add_argument("--out", default="dist/project_signals.json")
    ap.add_argument("--summary", default=None, help="write a Markdown summary here")
    ap.add_argument("--now", default=None)
    ap.add_argument("--force", action="store_true", help="write even after a sharp drop (never after a schema failure)")
    args = ap.parse_args(argv)

    rows = json.loads(Path(args.top200).read_text(encoding="utf-8"))
    aliases, _ = read_json(args.aliases)
    exclusions, _ = read_json(args.exclusions)
    parts = {}
    for team in TEAMS:
        data, state = read_json(getattr(args, team))
        parts[team] = data if state == "ok" else state
    planning, _ = read_json(args.planning)
    previous, _ = read_json(args.previous)
    standings, _ = read_json(args.standings)
    result = combine(rows, aliases, parts, planning, previous, args.now, exclusions=exclusions, standings=standings)
    reasons = publication_check(result, previous, [r["repd_ref"] for r in rows])
    refuse = [r for r in reasons if r.startswith("schema") or not args.force]
    out = Path(args.out)
    same = lambda d: {k: v for k, v in d.items() if k != "run_at"}  # noqa: E731
    unchanged = not refuse and isinstance(previous, dict) and previous.get("schema") == SCHEMA and same(previous) == same(result)
    if unchanged and out.exists():
        reasons = ["nothing changed since the published file (only the run time differs): not rewritten"]
    elif not refuse:
        out.parent.mkdir(parents=True, exist_ok=True)
        tmp = out.with_suffix(".tmp")
        tmp.write_text(json.dumps(result, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
        tmp.replace(out)
    if args.summary:
        truth = load_truth(args.truth) if args.truth and Path(args.truth).exists() else None
        Path(args.summary).write_text(summary(result, truth, reasons, published=not refuse), encoding="utf-8")
    print(json.dumps({"out": str(out) if not refuse else None, "generated_at": result["generated_at"], "stale": result["stale"],
                      "by_tier": result["counts"]["by_tier"], "headline": result["counts"]["headline"],
                      "parts": {t: s["status"] for t, s in result["parts"].items()}}))
    if refuse:
        for reason in refuse:
            print("NOT PUBLISHED: %s" % reason, file=sys.stderr)
        return 3
    return 0


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

Dates

A Python module in the signals folder of GlobalGrid2050 that works with URL day (`url_day`) and URL year (`url_year`). It is built from the day step (`day`).

transformglobalgrid2050 / automation/news/signals/dates.py · lines 1–101 of 101 · Entry point · pattern _make (shared by 2 files)

What it does
It calculates its inputs. Defines _make, day, url_day, url_year. Uses libraries __future__, datetime, re.
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.
Downstream impact
Used directly by 5 files: Datacentre Feed (globalgrid2050); Combine (globalgrid2050); News — Signals (globalgrid2050); Official (globalgrid2050); and 1 more. Reached from 22 other entry points, including GlobalGrid2050 Agent7 V922 CI Workflow (globalgrid2050); GlobalGrid2050 Datacentre News Workflow (globalgrid2050); GlobalGrid2050 Pipeline Headlines Workflow (globalgrid2050).
What it achieves
Project signals: one date rule shared by the three collectors and the combiner.
Why it matters
Imported by 5 files, including Datacentre Feed, Combine and News — Signals.
Application
globalgrid2050 · automation/news/signals · Python module
Uses
__future__, datetime, re
Used by
imported by Datacentre Feed (import), imported by Combine (import), imported by News — Signals (import), imported by Official (import), imported by Trade (import)
Produces
day, url_day, url_year
Defines here
_make, day, url_day, url_year
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/dates.py:1-101 · blob 1cdc313d880d7b508612171ddb7d049ef0f8abc9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Project signals: one date rule shared by the three collectors and the combiner.

  day(value, today=None) -> "YYYY-MM-DD" or None

The day is the publisher's own calendar day: the date as written, not shifted to UTC (a story stamped
00:30 +01:00 on the 15th is dated the 15th by every collector). A missing or unknown time zone costs the time,
never the date. Impossible dates (30 February), placeholder dates (1970, year 26), dates before 2005 and, when
`today` is given, dates later than the day after it are None: an undated item, never a recent one.

  url_day(link) -> "YYYY-MM-DD" or None       a full date written in the link's path (/2026/11/10/, /10112026/)
  url_year(link) -> int or None               a year written in the link's path (/2026/, /uploads/2023/12/)
"""
from __future__ import annotations

import datetime as dt
import re

MONTHS = {m: n for n, names in enumerate((
    ("jan", "january"), ("feb", "february"), ("mar", "march"), ("apr", "april"), ("may",), ("jun", "june"),
    ("jul", "july"), ("aug", "august"), ("sep", "sept", "september"), ("oct", "october"), ("nov", "november"),
    ("dec", "december")), 1) for m in names}
FIRST_YEAR = 2005                 # before any utility-scale solar news in Great Britain

ISO_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})(?:$|[T ])")
BASIC_RE = re.compile(r"^(\d{4})(\d{2})(\d{2})(?:$|T\d{6}Z?$)")
WORDS_RE = re.compile(r"(?<!\d)(\d{1,2})(?:st|nd|rd|th)?[ \-]([A-Za-z]{3,9})\.?,?[ \-](\d{4}|\d{2})(?!\d)")
US_WORDS_RE = re.compile(r"\b([A-Za-z]{3,9})\.? (\d{1,2})(?:st|nd|rd|th)?,? (\d{4})(?!\d)")
NUMERIC_RE = re.compile(r"^(\d{1,2})[/.\-](\d{1,2})[/.\-](\d{4}|\d{2})(?:$|[ T])")


def _make(year, month, day_, today=None):
    try:
        short = len(str(year)) <= 2
        year, month, day_ = int(year), int(month), int(day_)
        if short:
            year += 2000
        made = dt.date(year, month, day_)
    except (TypeError, ValueError):
        return None
    if made.year < FIRST_YEAR:
        return None
    if today is not None and made > today + dt.timedelta(days=1):
        return None
    return made.isoformat()


def day(value, today=None, month_first=False):
    """The calendar day a source wrote, or None. Accepts ISO dates and timestamps (with or without a zone), RFC 822
    dates with any or no zone name, "14 November 2026", "Nov 14, 2026", 14/11/2026, 14.11.2026, 20261114."""
    if not isinstance(value, str):
        return None
    text = value.strip()
    if not text:
        return None
    found = ISO_RE.match(text) or BASIC_RE.match(text)
    if found:
        return _make(found.group(1), found.group(2), found.group(3), today)
    found = WORDS_RE.search(text)
    if found and found.group(2).lower() in MONTHS:
        return _make(found.group(3), MONTHS[found.group(2).lower()], found.group(1), today)
    found = US_WORDS_RE.search(text)
    if found and found.group(1).lower() in MONTHS:
        return _make(found.group(3), MONTHS[found.group(1).lower()], found.group(2), today)
    found = NUMERIC_RE.match(text)
    if found:
        first, second = found.group(1), found.group(2)
        if month_first or int(second) > 12 >= int(first):
            first, second = second, first
        return _make(found.group(3), second, first, today)
    return None


URL_DAY_RES = (re.compile(r"/(20\d{2})[/-](\d{1,2})[/-](\d{1,2})(?:/|-|$)"),
               re.compile(r"/(\d{2})(\d{2})(20\d{2})/"))
URL_YEAR_RE = re.compile(r"/(20\d{2})(?:/|$)")


def url_day(link, today=None):
    if not isinstance(link, str):
        return None
    path = link.split("?")[0]
    found = URL_DAY_RES[0].search(path)
    if found:
        return _make(found.group(1), found.group(2), found.group(3), today)
    found = URL_DAY_RES[1].search(path)
    if found:
        return _make(found.group(3), found.group(2), found.group(1), today)
    return None


def url_year(link, today=None):
    if not isinstance(link, str):
        return None
    found = URL_YEAR_RE.search(link.split("?")[0])
    if not found:
        return None
    year = int(found.group(1))
    if year < FIRST_YEAR or (today is not None and year > today.year):
        return None
    return year