GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / registry_of_all_content_in_repos_and_dependencies / scripts

Build Registry and 3 more files

A Python command-line tool in the scripts folder of Registry Of All Content In Repos And Dependencies that fetches registry repos, schema, sources and kernel from GitHub API.

623 lines of Python from registry_of_all_content_in_repos_and_dependencies, in 4 files. Topic: Electricity markets and data pipelines. Section 1065 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 Registry storage · registry_of_all_content_in_repos_and_dependencies / scripts/build_registry.py lines 1–458
  2. Build Registry from Config ingest · registry_of_all_content_in_repos_and_dependencies / scripts/build_registry_from_config.py lines 1–30
  3. Reconcile Registry storage · registry_of_all_content_in_repos_and_dependencies / scripts/reconcile_registry.py lines 1–100
  4. Reconcile Registry from Config ingest · registry_of_all_content_in_repos_and_dependencies / scripts/reconcile_registry_from_config.py lines 1–35

Build Registry

A Python command-line tool in the scripts folder of Registry Of All Content In Repos And Dependencies that fetches registry repos, schema, sources and kernel from GitHub API.

storageregistry_of_all_content_in_repos_and_dependencies / scripts/build_registry.py · lines 1–458 of 458 · Entry point · pattern validate_registry (shared by 2 files)

What it does
It fetches registry repos, schema, sources and kernel. Defines 26 functions or classes, including utc_now, read_scope_config, config_repo_entries, apply_config_scope, unresolved_candidate_names. Uses libraries __future__, json, os, re, sys. Side effects: reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
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: data source: GitHub API; JSON file registry_repos.json; JSON file .schema.json; JSON file sources.json; JSON file latest.json; JSON file graph_latest.json; JSON file kernel.json; SQLite database. Out: JSON file latest.json.
Downstream impact
Used directly by 3 files: Build Registry from Config (registry_of_all_content_in_repos_and_dependencies); Reconcile Registry (registry_of_all_content_in_repos_and_dependencies); Reconcile Registry from Config (registry_of_all_content_in_repos_and_dependencies). Reached from 1 other entry point, including Registry Workflow (registry_of_all_content_in_repos_and_dependencies).
What it achieves
It reads scope config (`read_scope_config`), applies config scope (`apply_config_scope`) and validates scope completeness (`validate_scope_completeness`). Build the GlobalGrid2050 kernel registry.
Why it matters
Imported by Build Registry from Config, Reconcile Registry and Reconcile Registry from Config.
Application
registry_of_all_content_in_repos_and_dependencies · scripts · Python CLI
Uses
__future__, json, os, re, sys, time, urllib.error, urllib.request
Used by
imported by Build Registry from Config (import), imported by Reconcile Registry (import), imported by Reconcile Registry from Config (import)
Produces
utc_now, read_scope_config, config_repo_entries, apply_config_scope, unresolved_candidate_names, expected_scope_from_config, validate_scope_completeness, github_headers, api_get_json, repo_api, repo_html, blob_url
Defines here
utc_now, read_scope_config, config_repo_entries, apply_config_scope, unresolved_candidate_names, expected_scope_from_config, validate_scope_completeness, github_headers, api_get_json, repo_api, repo_html, blob_url, raw_url, classify_type, classify_role, classify_state, fetch_repo_tree, boot_sequence, existing_versions, read_latest, next_version, assemble_registry, validate_registry, render_markdown, write_registry, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
registry_of_all_content_in_repos_and_dependencies@2205a7abf98723f320f00aa4a0f6b648cf7109df scripts/build_registry.py:1-458 · blob 4e68ccd9d2f486e3ae63e5eef145d092f4f39482 · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: filesystem, network, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Build the GlobalGrid2050 kernel registry.

The registry is a complete versioned snapshot, not a diff. This script never edits
an existing registry_vNNNN.json. It writes the next number, regenerates
registry.md from the JSON, and then updates latest.json only after validation.
"""
from __future__ import annotations

import json
import os
import re
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

OWNER = "Ventusltd"
REPOS = [
    "data_uk_dno_and_tso",
    "data-federation-map-for-globalgrid2050-all-repos",
    "globalgrid2050",
    "spiders",
    "data-gb-electricity",
    "registry_of_all_content_in_repos_and_dependencies",
]

ROOT = Path(__file__).resolve().parents[1]
REGISTRY_DIR = ROOT / "registry"
RECEIPTS_DIR = REGISTRY_DIR / "receipts"
CONFIG_PATH = ROOT / "config" / "registry_repos.json"
SCHEMA_VERSION = "globalgrid2050.kernel_registry.v1"
API_ROOT = "https://api.github.com"

BINARY_EXTENSIONS = {
    ".7z", ".avif", ".bmp", ".doc", ".docx", ".eot", ".gif", ".gz", ".ico",
    ".jpeg", ".jpg", ".otf", ".parquet", ".pdf", ".png", ".ppt", ".pptx",
    ".sqlite", ".sqlite3", ".tar", ".tif", ".tiff", ".ttf", ".webp", ".woff",
    ".woff2", ".xls", ".xlsm", ".xlsx", ".zip",
}

TEXT_EXTENSIONS = {
    "", ".csv", ".css", ".geojson", ".gitignore", ".html", ".js", ".json",
    ".md", ".py", ".txt", ".ts", ".tsx", ".yml", ".yaml", ".xml",
}

ROLE_BY_REPO = {
    "data_uk_dno_and_tso": "UK and Ireland DNO/TSO declared data spine",
    "data-federation-map-for-globalgrid2050-all-repos": "federation node and edge control ledger",
    "globalgrid2050": "retiring monolith, atlas and application source",
    "spiders": "spider species lab and topology viewers",
    "data-gb-electricity": "GB electricity time-series Parquet data layer",
    "registry_of_all_content_in_repos_and_dependencies": "authoritative kernel registry of repo contents and dependencies",
}


def utc_now() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def read_scope_config() -> dict[str, Any] | None:
    if not CONFIG_PATH.exists():
        return None
    cfg = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
    if not isinstance(cfg, dict):
        raise RuntimeError("config/registry_repos.json must contain a JSON object")
    return cfg


def config_repo_entries(cfg: dict[str, Any]) -> list[dict[str, Any]]:
    repos = cfg.get("repos", [])
    if not isinstance(repos, list):
        raise RuntimeError("config/registry_repos.json repos must be an array")
    entries = []
    for item in repos:
        if not isinstance(item, dict):
            raise RuntimeError("config/registry_repos.json repos entries must be objects")
        name = item.get("name")
        if not isinstance(name, str) or not name.strip():
            raise RuntimeError("config/registry_repos.json repo entry missing name")
        entries.append(item)
    return entries


def apply_config_scope() -> str:
    """Load the configured repository scope inside the builder process.

    The legacy six-repo REPOS list remains a documented fallback only. Loading the
    config here makes subprocess rebuilds safe, because callers no longer have to
    inject global module state before invoking this file.
    """
    global REPOS

    cfg = read_scope_config()
    if cfg is None:
        message = f"scope: built-in fallback ({len(REPOS)} repos)"
        print(message)
        return message

    entries = config_repo_entries(cfg)
    if not entries:
        message = f"scope: built-in fallback ({len(REPOS)} repos)"
        print(message)
        return message

    REPOS = [item["name"] for item in entries]
    for item in entries:
        ROLE_BY_REPO[item["name"]] = item.get("role", "GlobalGrid2050 federation repository")

    message = f"scope: config/registry_repos.json ({len(REPOS)} repos)"
    print(message)
    return message


def unresolved_candidate_names(cfg: dict[str, Any]) -> set[str]:
    names: set[str] = set()
    candidates = cfg.get("unresolved_candidates", [])
    if not isinstance(candidates, list):
        return names
    for item in candidates:
        if isinstance(item, str) and item:
            names.add(item)
        elif isinstance(item, dict) and isinstance(item.get("name"), str):
            names.add(item["name"])
    return names


def expected_scope_from_config() -> set[str] | None:
    cfg = read_scope_config()
    if cfg is None:
        return None
    entries = config_repo_entries(cfg)
    if not entries:
        return None
    expected = {item["name"] for item in entries}
    return expected - unresolved_candidate_names(cfg)


def validate_scope_completeness(registry: dict[str, Any]) -> None:
    expected = expected_scope_from_config()
    if expected is None:
        return
    actual = {repo.get("name") for repo in registry.get("repos", []) if repo.get("name")}
    missing = sorted(expected - actual)
    if missing:
        raise RuntimeError(
            "Refusing to write or repoint partial registry: "
            f"missing configured repos {missing}; expected {len(expected)} repos, got {len(actual)}"
        )


def github_headers() -> dict[str, str]:
    token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
    headers = {
        "Accept": "application/vnd.github+json",
        "X-GitHub-Api-Version": "2022-11-28",
        "User-Agent": "globalgrid2050-kernel-registry",
    }
    if token:
        headers["Authorization"] = f"Bearer {token}"
    return headers


def api_get_json(url: str) -> dict[str, Any]:
    req = urllib.request.Request(url, headers=github_headers())
    try:
        with urllib.request.urlopen(req, timeout=60) as response:
            raw = response.read().decode("utf-8")
            return json.loads(raw)
    except urllib.error.HTTPError as exc:
        body = exc.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"GitHub API error {exc.code} for {url}: {body[:500]}") from exc


def repo_api(repo: str) -> str:
    return f"{API_ROOT}/repos/{OWNER}/{repo}"


def repo_html(repo: str) -> str:
    return f"https://github.com/{OWNER}/{repo}"


def blob_url(repo: str, branch: str, path: str) -> str:
    return f"https://github.com/{OWNER}/{repo}/blob/{branch}/{path}"


def raw_url(repo: str, branch: str, path: str) -> str:
    return f"https://raw.githubusercontent.com/{OWNER}/{repo}/{branch}/{path}"


def classify_type(path: str) -> str:
    lower = path.lower()
    suffix = Path(lower).suffix
    if suffix in BINARY_EXTENSIONS:
        return "binary"
    if lower.endswith(".schema.json"):
        return "schema"
    if "/workflows/" in lower or lower.startswith(".github/workflows/"):
        return "workflow"
    if lower.endswith(".geojson"):
        return "geojson"
    if suffix == ".json":
        return "json"
    if suffix in {".md", ".txt"}:
        return "document"
    if suffix in {".py", ".js", ".ts", ".tsx"}:
        return "code"
    if suffix in {".csv"}:
        return "tabular"
    if suffix in {".html", ".css"}:
        return "web"
    return "file"


def classify_role(path: str) -> str:
    lower = path.lower()
    name = Path(lower).name
    if name == "readme.md":
        return "human entry point"
    if name in {"anchor_ai_must_read.md", "federation.yaml"}:
        return "AI boot and federation manifest"
    if "data_contract" in lower or lower.endswith(".schema.json"):
        return "data contract or schema"
    if "data_sources" in lower or "sources.json" in lower:
        return "source registry"
    if lower.startswith(".github/workflows/"):
        return "automation workflow"
    if lower.startswith("registry/"):
        return "kernel registry artifact"
    if lower.startswith("scripts/") or "/scripts/" in lower:
        return "builder or automation script"
    if lower.startswith("data/") or "/data/" in lower:
        return "data artifact"
    if lower.startswith("docs/") or "/docs/" in lower:
        return "documentation"
    if lower.endswith("index.html"):
        return "web entry point"
    if lower.endswith(".geojson"):
        return "geospatial layer"
    if lower.endswith(".parquet"):
        return "Parquet data product"
    return "repository content"


def classify_state(path: str, tree_item: dict[str, Any]) -> str:
    if Path(path.lower()).suffix in BINARY_EXTENSIONS:
        return "binary"
    if tree_item.get("type") != "blob":
        return "unreachable"
    return "verified"


def fetch_repo_tree(repo: str) -> dict[str, Any]:
    meta = api_get_json(repo_api(repo))
    default_branch = meta.get("default_branch")
    if not default_branch:
        raise RuntimeError(f"No default branch detected for {repo}")
    tree = api_get_json(f"{repo_api(repo)}/git/trees/{default_branch}?recursive=1")
    if "tree" not in tree or not isinstance(tree["tree"], list):
        raise RuntimeError(f"Tree response missing tree array for {repo}")
    files = []
    for item in tree["tree"]:
        if item.get("type") != "blob":
            continue
        path = item.get("path")
        if not isinstance(path, str) or not path:
            continue
        files.append(
            {
                "path": path,
                "github_url": blob_url(repo, default_branch, path),
                "raw_url": raw_url(repo, default_branch, path),
                "type": classify_type(path),
                "role": classify_role(path),
                "state": classify_state(path, item),
            }
        )
    files.sort(key=lambda f: f["path"].lower())
    return {
        "name": repo,
        "html_url": meta.get("html_url") or repo_html(repo),
        "api_url": meta.get("url") or repo_api(repo),
        "default_branch": default_branch,
        "role": ROLE_BY_REPO.get(repo, "GlobalGrid2050 federation repository"),
        "file_count": len(files),
        "files": files,
    }


def boot_sequence() -> list[dict[str, str]]:
    return [
        {"repo": "data-federation-map-for-globalgrid2050-all-repos", "path": "anchor_AI_MUST_READ.md", "reason": "AI boot doctrine"},
        {"repo": "data-federation-map-for-globalgrid2050-all-repos", "path": "federation.yaml", "reason": "machine federation manifest"},
        {"repo": "data-federation-map-for-globalgrid2050-all-repos", "path": "DATA_CONTRACT.md", "reason": "node and edge contract"},
        {"repo": "data-federation-map-for-globalgrid2050-all-repos", "path": "IMPLEMENTATION.md", "reason": "scanner implementation description"},
        {"repo": "data-federation-map-for-globalgrid2050-all-repos", "path": "scripts/build_federation_map.py", "reason": "scanner source of truth"},
        {"repo": "registry_of_all_content_in_repos_and_dependencies", "path": "registry/latest.json", "reason": "authoritative registry pointer"},
        {"repo": "data_uk_dno_and_tso", "path": "README.md", "reason": "DNO/TSO spine discipline"},
        {"repo": "data_uk_dno_and_tso", "path": "config/sources.json", "reason": "DNO/TSO source registry"},
        {"repo": "data-gb-electricity", "path": "README.md", "reason": "GB electricity data law"},
        {"repo": "globalgrid2050", "path": "ARCHITECTURE.md", "reason": "monolith and platform architecture"},
        {"repo": "spiders", "path": "README.md", "reason": "spider species operating law"},
    ]


def existing_versions() -> list[int]:
    REGISTRY_DIR.mkdir(parents=True, exist_ok=True)
    versions = []
    for path in REGISTRY_DIR.glob("registry_v*.json"):
        match = re.fullmatch(r"registry_v(\d{4})\.json", path.name)
        if match:
            versions.append(int(match.group(1)))
    return sorted(versions)


def read_latest() -> dict[str, Any] | None:
    latest = REGISTRY_DIR / "latest.json"
    if not latest.exists():
        return None
    return json.loads(latest.read_text(encoding="utf-8"))


def next_version() -> int:
    versions = existing_versions()
    return (versions[-1] + 1) if versions else 1


def assemble_registry(version: int) -> dict[str, Any]:
    repos = []
    for repo in sorted(REPOS, key=str.lower):
        repos.append(fetch_repo_tree(repo))
        time.sleep(0.1)
    file_count = sum(repo["file_count"] for repo in repos)
    reachable_count = sum(1 for repo in repos for file in repo["files"] if file["state"] in {"verified", "declared", "binary"})
    unreachable_count = sum(1 for repo in repos for file in repo["files"] if file["state"] == "unreachable")
    return {
        "schema_version": SCHEMA_VERSION,
        "generated_at": utc_now(),
        "registry_version": version,
        "boot_sequence": boot_sequence(),
        "totals": {
            "repo_count": len(repos),
            "file_count": file_count,
            "reachable_count": reachable_count,
            "unreachable_count": unreachable_count,
        },
        "repos": repos,
    }


def validate_registry(registry: dict[str, Any], expected_version: int) -> None:
    if registry.get("registry_version") != expected_version:
        raise RuntimeError("registry_version does not match filename version")
    repos = registry.get("repos")
    if not isinstance(repos, list) or not repos:
        raise RuntimeError("registry contains no repos")
    if any(not repo.get("files") for repo in repos):
        empty = [repo.get("name", "<unknown>") for repo in repos if not repo.get("files")]
        raise RuntimeError(f"repo block empty: {empty}")
    actual_file_count = sum(len(repo.get("files", [])) for repo in repos)
    if registry.get("totals", {}).get("file_count") != actual_file_count:
        raise RuntimeError("file_count does not equal actual file entries")
    if registry.get("totals", {}).get("repo_count") != len(repos):
        raise RuntimeError("repo_count does not equal actual repo entries")
    validate_scope_completeness(registry)
    encoded = json.dumps(registry, indent=2, sort_keys=True)
    json.loads(encoded)


def render_markdown(registry: dict[str, Any]) -> str:
    totals = registry["totals"]
    version = int(registry["registry_version"])
    lines = [
        "# GlobalGrid2050 Kernel Registry",
        "",
        "This file is generated from the authoritative JSON snapshot. Do not edit it by hand.",
        "",
        f"Authoritative version: `{version:04d}`",
        f"Generated at: `{registry['generated_at']}`",
        "",
        "## Totals",
        "",
        f"- Repositories: {totals['repo_count']}",
        f"- Files: {totals['file_count']}",
        f"- Reachable: {totals['reachable_count']}",
        f"- Unreachable: {totals['unreachable_count']}",
        "",
        "## Boot sequence",
        "",
    ]
    for item in registry["boot_sequence"]:
        repo = item["repo"]
        path = item["path"]
        url = f"https://github.com/{OWNER}/{repo}/blob/HEAD/{path}"
        lines.append(f"- [{repo}/{path}]({url}) — {item['reason']}")
    lines.extend(["", "## Repositories", ""])
    for repo in registry["repos"]:
        lines.extend([
            f"### [{repo['name']}]({repo['html_url']})",
            "",
            f"Role: {repo['role']}",
            "",
            f"Default branch: `{repo['default_branch']}`",
            "",
            f"File count: {repo['file_count']}",
            "",
            "| State | Type | Path | Role |",
            "|---|---|---|---|",
        ])
        for file in repo["files"]:
            state = file["state"]
            ftype = file["type"]
            path = file["path"]
            role = file["role"]
            lines.append(f"| {state} | {ftype} | [{path}]({file['github_url']}) | {role} |")
        lines.append("")
    return "\n".join(lines).rstrip() + "\n"


def write_registry(registry: dict[str, Any], version: int) -> None:
    REGISTRY_DIR.mkdir(parents=True, exist_ok=True)
    json_path = REGISTRY_DIR / f"registry_v{version:04d}.json"
    if json_path.exists():
        raise RuntimeError(f"Refusing to overwrite existing {json_path}")
    validate_registry(registry, version)
    json_text = json.dumps(registry, indent=2, sort_keys=True) + "\n"
    md_text = render_markdown(registry)
    tmp_json = REGISTRY_DIR / f"registry_v{version:04d}.json.tmp"
    tmp_json.write_text(json_text, encoding="utf-8")
    json.loads(tmp_json.read_text(encoding="utf-8"))
    tmp_json.replace(json_path)
    md_path = REGISTRY_DIR / "registry.md"
    md_path.write_text(md_text, encoding="utf-8")
    latest = {
        "authoritative_version": version,
        "json_path": f"registry/registry_v{version:04d}.json",
        "md_path": "registry/registry.md",
        "graph_path": "registry/graph_latest.json",
        "kernel_path": "registry/kernel.json",
        "updated_at": registry["generated_at"],
    }
    (REGISTRY_DIR / "latest.json").write_text(json.dumps(latest, indent=2, sort_keys=True) + "\n", encoding="utf-8")


def main() -> int:
    apply_config_scope()
    version = next_version()
    registry = assemble_registry(version)
    write_registry(registry, version)
    print(f"Wrote registry_v{version:04d}.json with {registry['totals']['file_count']} files")
    return 0


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

Build Registry from Config

A Python command-line tool in the scripts folder of Registry Of All Content In Repos And Dependencies that reads registry repos. It loads scope (`load_scope`).

ingestregistry_of_all_content_in_repos_and_dependencies / scripts/build_registry_from_config.py · lines 1–30 of 30 · Entry point · pattern load_scope (shared by 2 files)

What it does
It loads registry repos. Defines load_scope, main. Uses libraries __future__, 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 registry_repos.json.
Downstream impact
Used directly by 1 file: Registry Workflow (registry_of_all_content_in_repos_and_dependencies).
What it achieves
Build the registry using `config/registry_repos.json` instead of the legacy hardcoded scope.
Why it matters
Run by Registry Workflow.
Application
registry_of_all_content_in_repos_and_dependencies · scripts · Python CLI
Uses
Build Registry (import), __future__, json, pathlib
Used by
run by Registry Workflow (workflow run)
Produces
load_scope, main
Defines here
load_scope, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
registry_of_all_content_in_repos_and_dependencies@2205a7abf98723f320f00aa4a0f6b648cf7109df scripts/build_registry_from_config.py:1-30 · blob 87aec37b1a7d00a751f7eb50d500d3d92a769c16 · GitHub at these lines
State
achieves: comment · context: auto · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
#!/usr/bin/env python3
"""Build the registry using config/registry_repos.json instead of the legacy hardcoded scope."""
from __future__ import annotations

import json
from pathlib import Path

import build_registry

ROOT = Path(__file__).resolve().parents[1]
CONFIG = ROOT / "config" / "registry_repos.json"


def load_scope() -> None:
    cfg = json.loads(CONFIG.read_text(encoding="utf-8"))
    repos = cfg.get("repos", [])
    if not repos:
        raise RuntimeError("config/registry_repos.json has no repos")
    build_registry.REPOS = [item["name"] for item in repos]
    for item in repos:
        build_registry.ROLE_BY_REPO[item["name"]] = item.get("role", "GlobalGrid2050 federation repository")


def main() -> int:
    load_scope()
    return build_registry.main()


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

Reconcile Registry

A Python command-line tool in the scripts folder of Registry Of All Content In Repos And Dependencies that writes receipt (`write_receipt`), counts live (`count_live`) and runs builder (`run_builder`).

storageregistry_of_all_content_in_repos_and_dependencies / scripts/reconcile_registry.py · lines 1–100 of 100 · Entry point · pattern run_builder (shared by 2 files)

What it does
It loads data. Defines 7 functions or classes, including utc_now, write_receipt, latest_pointer, authoritative_registry, count_live. Uses libraries __future__, json, subprocess, sys, datetime. 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.
Inputs & outputs
In: JSON file latest.json.
Downstream impact
Used directly by 1 file: Reconcile Registry from Config (registry_of_all_content_in_repos_and_dependencies). Reached from 1 other entry point, including Registry Workflow (registry_of_all_content_in_repos_and_dependencies).
What it achieves
It is built from the utc now helper (`utc_now`), the latest pointer helper (`latest_pointer`) and the authoritative registry helper (`authoritative_registry`). Reconcile the authoritative registry against live GitHub repo trees.
Why it matters
Imported by Reconcile Registry from Config.
Application
registry_of_all_content_in_repos_and_dependencies · scripts · Python CLI
Uses
Build Registry (import), __future__, json, subprocess, sys, datetime, pathlib
Used by
imported by Reconcile Registry from Config (import)
Produces
utc_now, write_receipt, latest_pointer, authoritative_registry, count_live, run_builder, main
Defines here
utc_now, write_receipt, latest_pointer, authoritative_registry, count_live, run_builder, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
registry_of_all_content_in_repos_and_dependencies@2205a7abf98723f320f00aa4a0f6b648cf7109df scripts/reconcile_registry.py:1-100 · blob e302cfdf39a77216dcba99020b34f83ad2198898 · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Reconcile the authoritative registry against live GitHub repo trees."""
from __future__ import annotations

import json
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path

import build_registry

ROOT = Path(__file__).resolve().parents[1]
REGISTRY_DIR = ROOT / "registry"
RECEIPTS_DIR = REGISTRY_DIR / "receipts"


def utc_now() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def write_receipt(kind: str, payload: dict) -> Path:
    RECEIPTS_DIR.mkdir(parents=True, exist_ok=True)
    stamp = utc_now().replace(":", "").replace("-", "")
    path = RECEIPTS_DIR / f"{stamp}_{kind}.json"
    path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    return path


def latest_pointer() -> dict:
    path = REGISTRY_DIR / "latest.json"
    if not path.exists():
        raise RuntimeError("registry/latest.json missing")
    return json.loads(path.read_text(encoding="utf-8"))


def authoritative_registry() -> dict:
    latest = latest_pointer()
    json_path = ROOT / latest["json_path"]
    return json.loads(json_path.read_text(encoding="utf-8"))


def count_live() -> dict:
    repos = []
    for repo_name in sorted(build_registry.REPOS, key=str.lower):
        repo = build_registry.fetch_repo_tree(repo_name)
        repos.append({"name": repo_name, "file_count": repo["file_count"]})
    return {
        "repo_count": len(repos),
        "file_count": sum(repo["file_count"] for repo in repos),
        "repos": repos,
    }


def run_builder(reason: str, before: dict | None, live: dict | None) -> None:
    payload = {
        "status": "builder_invoked",
        "reason": reason,
        "before": before,
        "live": live,
        "generated_at": utc_now(),
    }
    receipt = write_receipt("reconcile_trigger", payload)
    print(f"Registry reconciliation invoking builder: {reason}; receipt={receipt}")
    subprocess.check_call([sys.executable, str(ROOT / "scripts" / "build_registry.py")])


def main() -> int:
    build_registry.apply_config_scope()
    try:
        current = authoritative_registry()
    except Exception as exc:
        run_builder(f"authoritative registry unreadable: {exc}", None, None)
        return 0

    before = current.get("totals", {})
    if before.get("repo_count", 0) < 1 or before.get("file_count", 0) < 1:
        run_builder("authoritative registry count collapsed toward zero", before, None)
        return 0

    live = count_live()
    if before.get("repo_count") == live.get("repo_count") and before.get("file_count") == live.get("file_count"):
        receipt = write_receipt(
            "heartbeat",
            {
                "status": "ok_no_change",
                "generated_at": utc_now(),
                "authoritative_totals": before,
                "live_totals": live,
            },
        )
        print(f"Registry heartbeat OK: {receipt}")
        return 0

    run_builder("live counts differ from authoritative registry", before, live)
    return 0


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

Reconcile Registry from Config

A Python command-line tool in the scripts folder of Registry Of All Content In Repos And Dependencies that reads registry repos. It loads scope (`load_scope`).

ingestregistry_of_all_content_in_repos_and_dependencies / scripts/reconcile_registry_from_config.py · lines 1–35 of 35 · Entry point · pattern load_scope (shared by 2 files)

What it does
It loads registry repos. Defines load_scope, main. Uses libraries __future__, 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 registry_repos.json.
Downstream impact
Used directly by 1 file: Registry Workflow (registry_of_all_content_in_repos_and_dependencies).
What it achieves
Reconcile the registry using `config/registry_repos.json`.
Why it matters
Run by Registry Workflow.
Application
registry_of_all_content_in_repos_and_dependencies · scripts · Python CLI
Uses
Build Registry (import), Reconcile Registry (import), __future__, json, pathlib
Used by
run by Registry Workflow (workflow run)
Produces
load_scope, main
Defines here
load_scope, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
registry_of_all_content_in_repos_and_dependencies@2205a7abf98723f320f00aa4a0f6b648cf7109df scripts/reconcile_registry_from_config.py:1-35 · blob b94971b05edcd3e83908c64c815eb67f50b63540 · GitHub at these lines
State
achieves: comment · context: auto · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""Reconcile the registry using config/registry_repos.json."""
from __future__ import annotations

import json
from pathlib import Path

import build_registry
import reconcile_registry

ROOT = Path(__file__).resolve().parents[1]
CONFIG = ROOT / "config" / "registry_repos.json"


def load_scope() -> None:
    cfg = json.loads(CONFIG.read_text(encoding="utf-8"))
    repos = cfg.get("repos", [])
    if not repos:
        raise RuntimeError("config/registry_repos.json has no repos")
    names = [item["name"] for item in repos]
    build_registry.REPOS = names
    reconcile_registry.build_registry.REPOS = names
    for item in repos:
        role = item.get("role", "GlobalGrid2050 federation repository")
        build_registry.ROLE_BY_REPO[item["name"]] = role
        reconcile_registry.build_registry.ROLE_BY_REPO[item["name"]] = role


def main() -> int:
    load_scope()
    return reconcile_registry.main()


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