GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / pipelinenews / tools/intelligence

Release Builder (part 1)

A Python command-line tool in the intelligence folder of PipelineNews that reads cartridge and the Renewable Energy Planning Database (REPD) register, using SHA-256.

700 lines of Python from pipelinenews, in 1 file. Topic: Electricity markets and data pipelines. Section 1050 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. Release Builder automation · pipelinenews / tools/intelligence/release_builder.py lines 1–700

Release Builder

A Python command-line tool in the intelligence folder of PipelineNews that reads cartridge and the Renewable Energy Planning Database (REPD) register, using SHA-256.

automationpipelinenews / tools/intelligence/release_builder.py · lines 1–700 of 1084 · Entry point · pattern refresh_sha256_sidecars (shared by 2 files)

What it does
It loads cartridge and the REPD register. Defines 27 functions or classes, including utc_stamp, sha256_file, sha256_published, published_bytes, published_size. Uses libraries argparse, atexit, contextlib, datetime, hashlib. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file 202608291447-registry.json; JSON file build-manifest.json; JSON file cartridge.json; JSON file release-manifest.json; command-line arguments.
Downstream impact
Used directly by 6 files: Shift (pipelinenews); Build 30x Ledger (pipelinenews); Run Pages Candidate Gate (pipelinenews); PipelineNews Build Intelligence Release Workflow (pipelinenews); and 2 more. Reached from 1 other entry point, including PipelineNews Pages Routing Candidate Workflow (pipelinenews).
What it achieves
It normalises lf (`normalise_to_lf`), refreshes sha256 sidecars (`refresh_sha256_sidecars`) and refreshes build manifest (`refresh_build_manifest`). PipelineNews release builder — one timestamp, one discovery cartridge. It accepts `--list`, `--from` and `--cartridge`.
Why it matters
Run by 6 workflows and scripts, including Shift, Build 30x Ledger and Run Pages Candidate Gate.
Application
pipelinenews · tools/intelligence · Python CLI
Uses
argparse, atexit, contextlib, datetime, hashlib, io, json, os
Used by
run by Shift (script call), run by Build 30x Ledger (script call), run by Run Pages Candidate Gate (script call), run by PipelineNews Build Intelligence Release Workflow (workflow run), run by PipelineNews Map Corpus Contract Workflow (workflow run), run by PipelineNews Pages Workflow (workflow run)
Produces
utc_stamp, sha256_file, sha256_published, published_bytes, published_size, read, write, walk, normalise_to_lf, refresh_sha256_sidecars, refresh_build_manifest, apply_once
Defines here
utc_stamp, sha256_file, sha256_published, published_bytes, published_size, read, write, walk, normalise_to_lf, refresh_sha256_sidecars, refresh_build_manifest, visit, apply_once, releases, cmd_list, cartridge_keys, cmd_applicable, _canonical_sha, _inside, _spine_totals, apply_registry_core, check_registry_core, cmd_build, _discard_partial
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/release_builder.py:1-700 · blob 205733aac1f4b07778836fb2cefa43b4ac3c7226 · 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
"""PipelineNews release builder — one timestamp, one discovery cartridge.

THE ARCHITECTURE THIS IMPLEMENTS
--------------------------------
Take a working app. Stamp a new timestamp. Add ONE discovery cartridge to the
UI. If the result is wrong, do not debug it — build again from an earlier
timestamp. Every timestamp is a complete working app, because the file sizes
are trivial and the UI is the control surface.

Rollback is therefore not a git operation, an undo, or a revert. It is
`--from` an earlier timestamp. Nothing is ever edited in place: releases are
`immutable_after_publication`.

    python release_builder.py --list
    python release_builder.py --from 202608300309-pipelinenews --cartridge project-intelligence
    python release_builder.py --check 202608311304-pipelinenews

`--gen` defaults to the current UTC minute, read from the clock and never
chosen, because cvaa's monotonic-utc-generations vaccine requires a generation
within 15 minutes of its commit time and says generations are read, not picked.

A cartridge package is a directory containing:
    cartridge.json      the manifest: files, the UI section, the loader
    assets/*            files copied into the release's assets/
    data/*              files copied into the release's data/

Pure stdlib. No network. No git operation. Writes only a NEW release directory.
"""

import argparse
import atexit
import contextlib
import datetime
import hashlib
import io
import json
import os
import re
import shutil
import sys
from collections import Counter

HERE = os.path.dirname(os.path.abspath(__file__))
# tools/intelligence/ -> repo root -> releases/
REPO = os.path.dirname(os.path.dirname(HERE))
RELEASES = os.path.join(REPO, "releases")
CARTRIDGES = os.path.join(HERE, "cartridges")

APP = "assets/202608291447-app.mjs"
REGISTRY = "data/202608291447-registry.json"
ANALYTICS_ANCHOR = '    <h2 class="section-title">REPD PIPELINE ANALYTICS</h2>'
# This is the one stable core binding in every current release. Earlier builds
# inserted every new cartridge after bindFederatedRelationships(), which made
# the builder unable to extend a release once that rejected panel was
# deliberately withdrawn. A withdrawn optional surface cannot be the extension
# point for the application.
BOOT_BIND_ANCHOR = "  bindSectorIntelligence();"
RELEASE_ID_RE = re.compile(r"^[0-9]{12}-pipelinenews$")
LEGACY_ROOT_RELEASE_ID = "202608291447-pipelinenews"
LEGACY_ROOT_SCHEMA = "pipelinenews.timestamp-folder-successor.v1"


# --------------------------------------------------------------------- utils

def utc_stamp():
    return datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d%H%M")


def sha256_file(path):
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


# Text assets are hashed as they are PUBLISHED, which is LF: the sums are
# generated from LF content and GitHub Pages serves those bytes. A Windows
# checkout with core.autocrlf=true writes CRLF into the working copy, so
# hashing the file on disk disagrees with every published digest and --check
# fails on a release nobody has touched. Measured on 202608312018: 48 of 55
# files "mismatched", none of them actually wrong.
#
# The browser hashes what the server sends, so this is the comparison that
# means anything. Same defect, same fix, as the GridAtlas release verifier.
def sha256_published(path):
    return hashlib.sha256(published_bytes(path)).hexdigest()


# Six of the thirty-one ledgered releases fail their own `--check` today, and
# every one of the ten mismatched entries is this defect:
#
#   releases/202608311530 .. 202608311610  grid-proximity.mjs + its sidecar
#   releases/202608312018                  atlas-pointer-deep-link.mjs
#
# For all ten, sha256(bytes.replace(LF, CRLF)) equals the recorded digest
# exactly. The bytes GitHub Pages serves are LF and are correct; the LEDGER
# names bytes that were never served. The digests were taken on a Windows
# working copy before `.gitattributes` forced LF, by hashing the file on disk.
#
# normalise_to_lf() and `.gitattributes` between them mean the tree is already
# LF by the time any digest is recorded, so on a current checkout this helper
# returns the same bytes sha256_file() would have hashed. That is the point: it
# is no longer possible for the answer to depend on whose machine ran the build.
def published_bytes(path):
    """The bytes this file ships as: LF for text, untouched for everything else."""
    with open(path, "rb") as fh:
        raw = fh.read()
    if os.path.splitext(path)[1].lower() not in TEXT_EXT:
        return raw
    return raw.replace(b"\r\n", b"\n")


def published_size(path):
    return len(published_bytes(path))


def read(p):
    # Applicability walks every manifest and registry in an ancestry. Closing
    # each handle immediately avoids retaining two descriptors per generation.
    with io.open(p, encoding="utf-8") as stream:
        return stream.read()


def write(p, t):
    io.open(p, "w", encoding="utf-8", newline="").write(t)


def walk(root):
    out = []
    for base, _d, names in os.walk(root):
        for n in names:
            out.append(os.path.relpath(os.path.join(base, n), root).replace("\\", "/"))
    return sorted(out)


# Text extensions git stores with LF. Anything not listed is left untouched,
# because a stray byte change in a parquet or an image is a corruption.
TEXT_EXT = {".html", ".htm", ".css", ".js", ".mjs", ".json", ".txt", ".md",
            ".yml", ".yaml", ".csv", ".svg", ".sha256", ".geojson"}


def normalise_to_lf(root):
    """Rewrite CRLF to LF across a copied release tree.

    THIS IS NOT COSMETIC. A Windows checkout holds CRLF; git holds LF; and the
    release manifests record the LF byte counts and SHA-256 digests. Copying
    the working tree therefore produces a release whose every inherited file is
    a few hundred bytes larger than its own manifest says, and the repository's
    Pages gate rejects it — correctly.

    Measured on a real build: app.mjs +2,823 bytes, index.html +935, and 35
    records mismatched in total. Nothing in the release was wrong except the
    line endings, and no verifier in this suite caught it, because they all
    hashed the same wrong bytes consistently.
    """
    fixed = 0
    for rel in walk(root):
        if os.path.splitext(rel)[1].lower() not in TEXT_EXT:
            continue
        path = os.path.join(root, rel)
        with open(path, "rb") as fh:
            raw = fh.read()
        if b"\r\n" not in raw:
            continue
        with open(path, "wb") as fh:
            fh.write(raw.replace(b"\r\n", b"\n"))
        fixed += 1
    if fixed:
        print("  normalised %d text files to LF (matching what git stores)" % fixed)
    return fixed


def refresh_sha256_sidecars(target):
    """Rewrite every `<file>.sha256` to attest the file as it now stands.

    A cartridge ships its payload as `{GEN}-thing.json` plus a sidecar digest,
    and the build substitutes {GEN} in BOTH -- which changes the payload's
    bytes after the sidecar was written. The sidecar then attests a file that
    no longer exists, and nothing catches it: app.mjs verifies against the
    registry digest, and sha256sums.txt is regenerated from scratch.

    Measured on 202608311610: the shipped grid-proximity sidecar said
    c6ef7879..., the file hashed 49aaf5c3.... A file whose only job is to
    attest its neighbour, getting its neighbour wrong, is worse than no file.
    Published releases are immutable, so that one stays as it is; this repairs
    it going forward, for inherited sidecars as well as new ones.
    """
    fixed = 0
    for rel in walk(target):
        if not rel.endswith(".sha256"):
            continue
        subject = rel[:-len(".sha256")]
        subject_abs = os.path.join(target, subject)
        if not os.path.exists(subject_abs):
            continue
        path = os.path.join(target, rel)
        want = sha256_published(subject_abs)
        line = "%s  %s\n" % (want, os.path.basename(subject))
        if read(path) != line:
            write(path, line)
            fixed += 1
            print("    %s now attests %s" % (rel, want[:12]))
    print("  %d sha256 sidecar(s) rewritten" % fixed)
    return fixed


def refresh_build_manifest(target, release_id):
    """Recompute every byte count and digest the build manifest records.

    The manifest is inherited from the parent, so every file this build changed
    -- index.html, app.mjs, the registry, the atlas link manifest -- still
    carries the parent's numbers until they are rewritten here. Leaving them
    stale is what a hash-verified release is specifically designed to catch.
    """
    path = os.path.join(target, "build-manifest.json")
    if not os.path.exists(path):
        return 0
    doc = json.loads(read(path))

    def visit(node):
        count = 0
        if isinstance(node, dict):
            if "path" in node and isinstance(node.get("path"), str):
                f = os.path.join(target, node["path"])
                if os.path.exists(f):
                    if "bytes" in node:
                        node["bytes"] = published_size(f)
                        count += 1
                    if "sha256" in node:
                        node["sha256"] = sha256_published(f)
            for v in node.values():
                count += visit(v)
        elif isinstance(node, list):
            for v in node:
                count += visit(v)
        return count

    updated = visit(doc)
    write(path, json.dumps(doc, indent=2, ensure_ascii=False) + "\n")
    print("  refreshed %d records in build-manifest.json" % updated)
    return updated


def apply_once(text, old, new, label, expect=1):
    n = text.count(old)
    if n != expect:
        raise SystemExit("PATCH FAILED [%s]: expected %d, found %d" % (label, expect, n))
    print("    %-52s %d" % (label, n))
    return text.replace(old, new)


def releases():
    if not os.path.isdir(RELEASES):
        return []
    out = []
    for name in sorted(os.listdir(RELEASES)):
        d = os.path.join(RELEASES, name)
        if os.path.isdir(d) and os.path.exists(os.path.join(d, "index.html")):
            out.append(name)
    return out


# ---------------------------------------------------------------------- list

def cmd_list():
    rel = releases()
    if not rel:
        print("no releases found in %s" % RELEASES)
        return 1
    print("Rollback points — every one is a complete working app.\n")
    print("  %-34s %-8s %-9s %s" % ("RELEASE", "FILES", "CARTRIDGES", "ADDED PANELS"))
    for name in rel:
        d = os.path.join(RELEASES, name)
        files = walk(d)
        reg_path = os.path.join(d, REGISTRY)
        panels = []
        if os.path.exists(reg_path):
            try:
                sup = json.loads(read(reg_path)).get("supplemental_assets") or {}
                panels = sorted(sup.keys())
            except ValueError:
                panels = ["<unreadable registry>"]
        print("  %-34s %-8d %-9d %s"
              % (name, len(files), len(panels), ", ".join(panels) or "—"))
    print("\nBuild from any of them:")
    print("  python release_builder.py --from %s --cartridge <name>" % rel[-1])

    # "Available" used to mean "there is a directory here", and that is not the
    # same question as "can this be built". Measured against 202609030009 on
    # 2026-09-03: of the nineteen listed, fifteen were already in the release
    # and the other four could not apply at all -- their patch anchors had been
    # rewritten by later cartridges. Nothing was buildable, and the listing said
    # nothing about it. The key check below is exact and free; the anchor check
    # costs a build each, so it lives behind --applicable.
    print("\nCartridges, against %s:" % rel[-1])
    if os.path.isdir(CARTRIDGES):
        applied = set(cartridge_keys(rel[-1]))
        for c in sorted(os.listdir(CARTRIDGES)):
            man = os.path.join(CARTRIDGES, c, "cartridge.json")
            if not os.path.exists(man):
                continue
            m = json.loads(read(man))
            mark = "applied" if m.get("key") in applied else "new    "
            print("  [%s] %-26s %s" % (mark, c, m.get("summary", "")))
        print("\n  [applied] is exact. [  new  ] means only that the key is absent;")
        print("  whether its patches still anchor is a different question:")
        print("    python release_builder.py --applicable %s" % rel[-1])
    else:
        print("  (none — create %s/<name>/cartridge.json)" % CARTRIDGES)
    return 0


def cartridge_keys(release_id):
    """Every cartridge key applied anywhere in a release's ancestry.

    Registered cartridges are visible in ``supplemental_assets``. Repair-only
    cartridges intentionally register no asset, so their only durable identity
    is the ``cartridge_added`` field in the release manifest that applied them.
    Looking at the tip registry alone therefore made ``--applicable`` probe an
    already-applied repair forever. A replacement edit can be idempotent, so the
    probe may even appear to succeed while changing nothing.

    An incomplete ancestry is not evidence that a cartridge is new. Missing or
    malformed records and cycles consequently stop the command before it can
    perform a throwaway build.
    """
    keys = set()
    seen = set()
    current = release_id

    while current is not None:
        if not isinstance(current, str) or not RELEASE_ID_RE.fullmatch(current):
            raise SystemExit("malformed release id in applicability ancestry: %r"
                             % current)
        if current in seen:
            raise SystemExit("cycle in applicability ancestry at %s" % current)
        seen.add(current)

        release_dir = os.path.join(RELEASES, current)
        if not os.path.isdir(release_dir):
            raise SystemExit("missing release in applicability ancestry: %s" % current)

        manifest_path = os.path.join(release_dir, "release-manifest.json")
        if not os.path.isfile(manifest_path):
            raise SystemExit("missing release manifest in applicability ancestry: %s"
                             % current)
        try:
            manifest = json.loads(read(manifest_path))
        except (OSError, ValueError) as error:
            raise SystemExit("malformed release manifest in applicability ancestry "
                             "%s: %s" % (current, error))
        if not isinstance(manifest, dict):
            raise SystemExit("malformed release manifest in applicability ancestry "
                             "%s: expected object" % current)
        if manifest.get("release_id") != current:
            raise SystemExit("malformed release manifest in applicability ancestry "
                             "%s: release_id is %r" %
                             (current, manifest.get("release_id")))

        added = manifest.get("cartridge_added")
        if added is not None:
            if (not isinstance(added, str) or not added.strip()
                    or added != added.strip()):
                raise SystemExit("malformed cartridge_added in applicability ancestry "
                                 "%s: %r" % (current, added))
            keys.add(added)

        registry_path = os.path.join(release_dir, REGISTRY)
        if not os.path.isfile(registry_path):
            raise SystemExit("missing registry in applicability ancestry: %s" % current)
        try:
            registry = json.loads(read(registry_path))
        except (OSError, ValueError) as error:
            raise SystemExit("malformed registry in applicability ancestry %s: %s"
                             % (current, error))
        if not isinstance(registry, dict):
            raise SystemExit("malformed registry in applicability ancestry %s: "
                             "expected object" % current)
        supplemental = registry.get("supplemental_assets")
        if not isinstance(supplemental, dict):
            raise SystemExit("malformed supplemental_assets in applicability ancestry "
                             "%s: expected object" % current)
        malformed_keys = [key for key in supplemental
                          if (not isinstance(key, str) or not key.strip()
                              or key != key.strip())]
        if malformed_keys:
            raise SystemExit("malformed supplemental asset key in applicability ancestry "
                             "%s: %r" % (current, malformed_keys[0]))
        malformed_entries = [key for key, entry in supplemental.items()
                             if not isinstance(entry, dict)]
        if malformed_entries:
            key = malformed_entries[0]
            raise SystemExit("malformed supplemental asset entry in applicability "
                             "ancestry %s: %s is %s, expected object"
                             % (current, key, type(supplemental[key]).__name__))
        keys.update(supplemental)

        parent = manifest.get("parent_release_id")
        if parent is None:
            is_legacy_root = (current == LEGACY_ROOT_RELEASE_ID
                              and manifest.get("schema") == LEGACY_ROOT_SCHEMA)
            if not is_legacy_root:
                state = "null" if "parent_release_id" in manifest else "missing"
                raise SystemExit("%s parent_release_id in applicability ancestry %s; "
                                 "only legacy root %s (%s) may terminate the chain"
                                 % (state, current, LEGACY_ROOT_RELEASE_ID,
                                    LEGACY_ROOT_SCHEMA))
            break
        if not isinstance(parent, str) or not RELEASE_ID_RE.fullmatch(parent):
            raise SystemExit("malformed parent_release_id in applicability ancestry "
                             "%s: %r" % (current, parent))
        if current == LEGACY_ROOT_RELEASE_ID:
            raise SystemExit("legacy applicability root %s must not declare a parent"
                             % current)
        if parent == current:
            raise SystemExit("parent release generation is not strictly older in "
                             "applicability ancestry: %s -> %s" % (current, parent))
        if parent in seen:
            raise SystemExit("cycle in applicability ancestry: %s -> %s"
                             % (current, parent))
        if parent[:12] >= current[:12]:
            raise SystemExit("parent release generation is not strictly older in "
                             "applicability ancestry: %s -> %s" % (current, parent))
        current = parent

    return keys


# --------------------------------------------------------------- applicable

def cmd_applicable(parent_id):
    """Report which cartridges can actually be built onto a parent.

    A cartridge fails to apply when a later cartridge rewrote the text its
    patches anchor on. Nothing in the repository detected that: `--list` showed
    every directory under cartridges/ as available, and the operator found out
    by running a build and watching it discard itself.

    Applied identity comes from the complete release ancestry. For every key
    absent from that ancestry, this answers the remaining anchor question the
    only way it can be answered honestly -- by building it. Every probe writes
    a throwaway release and removes it again; a failed probe is already removed
    by the builder's own discard handler before this function sees it. The
    parent is never modified, and cmd_build asserts that itself.
    """
    if not os.path.isdir(os.path.join(RELEASES, parent_id)):
        raise SystemExit("no such parent release: %s" % parent_id)
    if not os.path.isdir(CARTRIDGES):
        raise SystemExit("no cartridges directory: %s" % CARTRIDGES)

    applied = cartridge_keys(parent_id)
    names = sorted(n for n in os.listdir(CARTRIDGES)
                   if os.path.exists(os.path.join(CARTRIDGES, n, "cartridge.json")))
    print("Cartridges against %s\n" % parent_id)
    print("  each unapplied candidate is built into a throwaway generation and removed again\n")

    rows = []
    for name in names:
        man = json.loads(read(os.path.join(CARTRIDGES, name, "cartridge.json")))
        if man.get("key") in applied:
            rows.append((name, "ALREADY APPLIED", ""))
            continue
        gen = utc_stamp()
        target = os.path.join(RELEASES, "%s-pipelinenews" % gen)
        if os.path.exists(target):
            rows.append((name, "NOT PROBED", "a release already occupies %s" % gen))
            continue
        buffer = io.StringIO()
        try:
            with contextlib.redirect_stdout(buffer):
                cmd_build(parent_id, name, gen, None)
            rows.append((name, "APPLIES", ""))
        except SystemExit as error:
            rows.append((name, "CANNOT APPLY", str(error).splitlines()[0][:120]))
        finally:
            if os.path.isdir(target):
                shutil.rmtree(target, ignore_errors=True)

    for name, verdict, detail in rows:
        print("  %-28s %-16s %s" % (name, verdict, detail))
    tally = Counter(verdict for _n, verdict, _d in rows)
    print()
    for verdict, count in tally.most_common():
        print("  %-16s %d" % (verdict, count))
    if not tally.get("APPLIES"):
        print("\n  Nothing here can be built onto %s. A new generation needs a new"
              % parent_id)
        print("  cartridge, not a rebuild of an existing one.")
    return 0


# ------------------------------------------------------------ registry core

# A quarterly REPD refresh replaces the register itself: the project spine
# (detail partitions), the compact project and search indexes compiled from
# it, and the totals and source pins that describe them. Those live in the
# registry's core, outside supplemental_assets, and no cartridge could reach
# them, so a new register could only arrive by recompiling the 202608291447
# root -- discarding every cartridge since. This is the narrow door instead.
#
# The cartridge DECLARES paths, schemas and the totals it expects. Everything
# that is a statement about bytes -- sha256, bytes, record_count -- is DERIVED
# here from the files in the new release, and the totals are recomputed from
# the partitions and must equal the declaration. Nothing else in the core can
# be replaced: cache_contract and cache_identity stay, because app.mjs pins
# them, and news, chart and style keep their entries.
REGISTRY_CORE_KEYS = ("totals", "source", "assets.projects", "assets.search",
                      "detail_partitions")
DETAIL_SCHEMA = "globalgrid2050.v9.project-partition.v9.1"


def _canonical_sha(value):
    raw = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(raw.encode("utf-8")).hexdigest()


def _inside(target, rel):
    full = os.path.normpath(os.path.join(target, rel))
    if not full.startswith(os.path.normpath(target) + os.sep):
        raise SystemExit("registry_core path escapes the release: %s" % rel)
    if not os.path.isfile(full):
        raise SystemExit("registry_core path missing from the release: %s" % rel)
    return full


def _spine_totals(projects):
    counts = Counter(p.get("technology") for p in projects)
    capacity = sum(float(p["capacity_mw"]) for p in projects)
    geometry = sum(1 for p in projects if p.get("geometry_status") == "valid")
    return {
        "project_count": len(projects),
        "capacity_mw": round(capacity + sys.float_info.epsilon, 2),
        "largest_mw": max(float(p["capacity_mw"]) for p in projects) if projects else 0.0,
        "solar_count": counts["solar"],
        "bess_count": counts["bess"],
        "wind_onshore_count": counts["wind_onshore"],
        "wind_offshore_count": counts["wind_offshore"],
        "geometry_count": geometry,
        "missing_geometry_count": len(projects) - geometry,
    }


def apply_registry_core(target, reg, core, sub):
    core = json.loads(sub(json.dumps(core)))
    unknown = sorted(set(core) - set(REGISTRY_CORE_KEYS))
    if unknown:
        raise SystemExit("registry_core keys not replaceable: %s" % unknown)
    missing = sorted(set(REGISTRY_CORE_KEYS) - set(core))
    if missing:
        # A partial refresh would leave the indexes describing one register and
        # the detail partitions another. All five move together or none does.
        raise SystemExit("registry_core must replace all of %s; missing %s"
                         % (list(REGISTRY_CORE_KEYS), missing))
    print("    registry core refresh")
    before = {
        "totals": reg.get("totals"), "source": reg.get("source"),
        "assets.projects": (reg.get("assets") or {}).get("projects"),
        "assets.search": (reg.get("assets") or {}).get("search"),
        "detail_partitions": reg.get("detail_partitions"),
    }

    detail, projects, refs = [], [], []
    for entry in core["detail_partitions"]:
        path = _inside(target, entry["path"])
        doc = json.loads(read(path))
        if doc.get("schema") != reg.get("detail_schema", DETAIL_SCHEMA):
            raise SystemExit("%s is not a %s partition" % (entry["path"], reg.get("detail_schema")))
        rows = doc.get("projects") or []
        if doc.get("record_count") != len(rows):
            raise SystemExit("%s record_count disagrees with its rows" % entry["path"])
        if len(rows) > int(reg.get("detail_partition_size", 500)):
            raise SystemExit("%s exceeds detail_partition_size" % entry["path"])
        projects.extend(rows)
        refs.extend(str(r.get("repd_ref")) for r in rows)
        detail.append({"path": entry["path"], "sha256": sha256_published(path),
                       "bytes": published_size(path), "record_count": len(rows),
                       "activation": entry.get("activation", "project-detail-or-export")})
    # Every partition but the last must be full, or floor(index/500) lands in
    # the wrong file and app.mjs reports a missing record.
    size = int(reg.get("detail_partition_size", 500))
    if any(d["record_count"] != size for d in detail[:-1]):
        raise SystemExit("detail partitions are not full %d-row pages" % size)
    if len(set(refs)) != len(refs):
        raise SystemExit("detail partitions repeat a REPD Ref")

    derived = _spine_totals(projects)
    declared = core["totals"]
    if {k: declared.get(k) for k in derived} != derived:
        raise SystemExit("registry_core totals disagree with the partitions:\n  declared %s\n  derived  %s"
                         % (declared, derived))
    if core["source"].get("admitted_project_count", derived["project_count"]) != derived["project_count"]:
        raise SystemExit("registry_core source.admitted_project_count disagrees with the partitions")

    assets = {}
    for key in ("assets.projects", "assets.search"):
        entry = dict(core[key])
        path = _inside(target, entry["path"])
        doc = json.loads(read(path))
        for field in ("schema", "generation", "cache_identity"):
            if field in entry and doc.get(field) != entry[field]:
                raise SystemExit("%s %s is %r, registry_core says %r"
                                 % (entry["path"], field, doc.get(field), entry[field]))
        if len(doc.get("rows") or []) != derived["project_count"]:
            raise SystemExit("%s has %d rows, partitions hold %d"
                             % (entry["path"], len(doc.get("rows") or []), derived["project_count"]))
        if key == "assets.projects":
            index_refs = [str(row[0]) for row in doc["rows"]]
            if index_refs != refs:
                # floor(global_row_index/500) is the detail locator: the index
                # and the partitions must hold the same refs in the same order.
                raise SystemExit("project index row order differs from the detail partitions")
        entry["sha256"] = sha256_published(path)
        entry["bytes"] = published_size(path)
        assets[key.split(".", 1)[1]] = entry

    reg["totals"] = declared
    reg["source"] = core["source"]
    reg.setdefault("assets", {}).update(assets)
    reg["detail_partitions"] = detail
    after = {"totals": reg["totals"], "source": reg["source"],
             "assets.projects": assets["projects"], "assets.search": assets["search"],
             "detail_partitions": detail}
    replaced = {}
    for key in REGISTRY_CORE_KEYS:
        replaced[key] = {"from_sha256": _canonical_sha(before[key]),
                         "to_sha256": _canonical_sha(after[key])}
        print("      %-18s %s -> %s" % (key, replaced[key]["from_sha256"][:12],
                                       replaced[key]["to_sha256"][:12]))
    print("      %d projects in %d partitions" % (derived["project_count"], len(detail)))
    return replaced


def check_registry_core(target, reg):
    """Core assets are attested like supplemental ones: path exists, digest holds."""
    ok = True
    entries = [("assets.%s" % k, (reg.get("assets") or {}).get(k)) for k in ("projects", "search")]
    entries += [("detail_partitions[%d]" % i, d) for i, d in enumerate(reg.get("detail_partitions") or [])]
    bad = []
    for label, node in entries:
        if not isinstance(node, dict) or "path" not in node or "sha256" not in node:
            continue
        p = os.path.join(target, node["path"])
        if not os.path.exists(p) or sha256_published(p) != node["sha256"]:
            bad.append(label)
    print("  [%s] %-20s %s" % ("PASS" if not bad else "FAIL", "core asset digests",
                               "%d checked" % len(entries) if not bad else bad[:4]))
    ok &= not bad
    return ok


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

def cmd_build(parent_id, cartridge_name, gen, atlas_target):
    parent = os.path.join(RELEASES, parent_id)
    if not os.path.isdir(parent):
        raise SystemExit("no such parent release: %s" % parent)

    pkg = os.path.join(CARTRIDGES, cartridge_name)
    man_path = os.path.join(pkg, "cartridge.json")
    if not os.path.exists(man_path):
        raise SystemExit("no cartridge manifest: %s" % man_path)
    man = json.loads(read(man_path))

    release_id = "%s-pipelinenews" % gen
    target = os.path.join(RELEASES, release_id)
    if os.path.exists(target):
        raise SystemExit("release already exists (immutable): %s\n"
                         "Bump the generation or delete it deliberately." % target)

    # A new timestamp must sort after its parent, or the ordering the whole
    # system relies on runs backwards.
    if gen <= parent_id[:12]:
        raise SystemExit("generation %s is not after parent %s; generations are "
                         "monotonic" % (gen, parent_id[:12]))

    print("Building %s\n  from    %s\n  adding  %s\n" % (release_id, parent_id, cartridge_name))

    before = {p: sha256_file(os.path.join(parent, p)) for p in walk(parent)}
    shutil.copytree(parent, target)
    normalise_to_lf(target)

    # A build that fails part-way must leave NOTHING behind. A half-written
    # release directory looks like a real release to every later command — it
    # has an index.html, so --list shows it and --from will build on it — and
    # the whole rollback model depends on every timestamp being complete.
    # This is not hypothetical: it happened, and the corrupt release carried
    # its parent's registry entry and import while looking fine from outside.
    build_ok = {"done": False}

    def _discard_partial():
        if not build_ok["done"] and os.path.isdir(target):
            shutil.rmtree(target, ignore_errors=True)
            sys.stderr.write("\nbuild failed; discarded partial release %s\n" % release_id)

    atexit.register(_discard_partial)
    print("  %d files carried forward\n" % len(before))

    key = man["key"]
    stamped = {}      # placeholder -> value used across the manifest