GLOBALGRID2050 / EXPLORE CODE

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

Build Pages (part 1)

A Python command-line tool in the atman folder of PipelineNews that reads atlas link and atlas current, using SHA-256 from the GridAtlas repository.

700 lines of Python from pipelinenews, in 1 file. Topic: Electricity markets and data pipelines. Section 997 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 Pages ingest · pipelinenews / atman/202608262014-build-pages.py lines 1–700

Build Pages

A Python command-line tool in the atman folder of PipelineNews that reads atlas link and atlas current, using SHA-256 from the GridAtlas repository.

ingestpipelinenews / atman/202608262014-build-pages.py · lines 1–700 of 1960 · version 2026-08-26 20:14 · Entry point · pattern validate_current_or_predecessor_pointer (shared by 2 files)

What it does
It loads atlas link and atlas current. Defines 42 functions or classes, including RuntimeAssets, __init__, handle_starttag, require, sha256. Uses libraries __future__, argparse, datetime, hashlib, html.parser. 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.
Inputs & outputs
In: data source: gridatlas data; JSON file -release-manifest.json; JSON file 202608261737-release-v9-5-1.json; JSON file atlas-link-manifest.json; JSON file build-manifest.json; JSON file release-manifest.json; JSON file live-set.json; JSON file current-v4.json.
Downstream impact
Used directly by 7 files: Audit Atlas V8 Deep Link Quarantine (pipelinenews); Extend Pages Atlas Link V2 (pipelinenews); Repair Pages Historical Source Attestation (pipelinenews); Test Pages Promotion Tooling (pipelinenews); and 3 more. Reached from 1 other entry point, including PipelineNews Pages Workflow (pipelinenews).
What it achieves
It reads JSON (`read_json`), verifies record (`verify_record`) and verifies record commit (`verify_record_at_commit`). Validate and stage the immutable modular PipelineNews Pages release. It accepts `--root`, `--generation` and `--stage`.
Why it matters
Run by 5 workflows and scripts, including Audit Atlas V8 Deep Link Quarantine, Extend Pages Atlas Link V2 and Repair Pages Historical Source Attestation. Checked by Test Pages Promotion Tooling.
Application
pipelinenews · atman · Python CLI
Uses
GridAtlas — Atlas Page (estate URL), __future__, argparse, datetime, hashlib, html.parser, json, os, pathlib
Used by
run by Audit Atlas V8 Deep Link Quarantine (script call), run by Extend Pages Atlas Link V2 (script call), run by Repair Pages Historical Source Attestation (script call), run by Test Pages Promotion Tooling (script call), run by Repair Pages Historical Source Attestation (workflow run), run by Repair Pages Historical Source Attestation V2 (workflow run), run by PipelineNews Pages V2 Workflow (workflow run)
Produces
RuntimeAssets, require, sha256, read_json, repository_path, web_path, verify_record, verify_record_at_commit, select_release, run_compiler, data_generation, validate_html_and_modules
Defines here
RuntimeAssets, __init__, handle_starttag, require, sha256, read_json, repository_path, web_path, verify_record, verify_record_at_commit, select_release, run_compiler, data_generation, validate_html_and_modules, validate_data, validate_release, _atlas_link_v2_outputs, _promotion_receiver_record, validate_pages_promotion_wrapper_v1, validate_current_atlas_link_v2
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 atman/202608262014-build-pages.py:1-700 · blob 5d7354d645b9de568c75c9000ad3aa4d47facf2c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Validate and stage the immutable modular PipelineNews Pages release.

This is the PipelineNews equivalent of GlobalGrid2050's trusted Pages build gate:
validate the exact committed release, reconstruct the already-public historical
closure, overlay the modular release and its shared data cartridges, then hand the
closed site tree to GitHub Pages.
"""

from __future__ import annotations

import argparse
from datetime import datetime
import hashlib
from html.parser import HTMLParser
import json
import os
from pathlib import Path
import posixpath
import re
import shutil
import subprocess
import sys
from urllib.parse import urljoin, urlsplit


ARCHIVE = Path("archive/202608261547-pipelinenews")
EXPECTED_SCHEMA = "pipelinenews.compiled-release.v1"
EXPECTED_PROJECTS = 7_680
EXPECTED_HEADLINES = 133
EXPECTED_UK_HEADLINES = 45
EXPECTED_OUTPUTS = 22
EXPECTED_INPUTS = 60
EXPECTED_GENERATED_FILES = 23
EXPECTED_IMPORTS = 18
EXPECTED_PROJECT_PARTITIONS = 16
EXPECTED_ATLAS_PARTITIONS = 18
GENERATION_RE = re.compile(r"^\d{12}$")
FAST_CANDIDATE_SCHEMA = "pipelinenews.v8.fast-site-candidate.v1"
FAST_CANDIDATE_MANIFEST_RE = re.compile(r"^(\d{12})-v8-fast-site-manifest\.json$")
FAST_AUTHORISATION_SCHEMA = "pipelinenews.v8.fast-pages-authorisation.v1"
FAST_AUTHORISATION_RE = re.compile(r"^(\d{12})-v8-fast-pages-authorisation\.json$")
SAFE_RELEASE_OUTPUT_RE = re.compile(r"^releases/[A-Za-z0-9._/-]+$")
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
ISO_8601_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$")
IMPORT_RE = re.compile(r"\bfrom\s+[\"']([^\"']+)[\"']|\bimport\s+[\"']([^\"']+)[\"']")
RUNTIME_JSON_RE = re.compile(
    r"[\"']((?:\.{1,2}/)*(?:data|manifests)/[^\"']+\.(?:json|geojson))[\"']"
)
TIMESTAMP_FOLDER_RE = re.compile(r"^(\d{12})-pipelinenews$")
TIMESTAMP_FOLDER_RELEASE_SCHEMA = "pipelinenews.timestamp-folder-successor.v1"
TIMESTAMP_FOLDER_BUILD_SCHEMA = "pipelinenews.timestamp-folder-build-manifest.v1"
TIMESTAMP_FOLDER_REGISTRY_SCHEMA = "pipelinenews.v9.timestamp-folder-registry.v1"
TIMESTAMP_FOLDER_FUNCTIONAL_FILES = 37
TIMESTAMP_FOLDER_TOTAL_FILES = 40
TIMESTAMP_FOLDER_INHERITED_FILES = 33
TIMESTAMP_FOLDER_SHARED_FILES = 29
TIMESTAMP_FOLDER_PARENT_FILES = 4
TIMESTAMP_FOLDER_PROVENANCE_FILES = 1
FORBIDDEN_ATLAS_V8_RECEIVER = "globalgrid2050.com/repd_grid_atlasv8"
ATLAS_V9_SOURCE_PARENT = "693ccda8e6288d449763ce2b3a4ba16ed7b93fee"


class RuntimeAssets(HTMLParser):
    def __init__(self) -> None:
        super().__init__()
        self.styles: list[str] = []
        self.scripts: list[str] = []

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        values = dict(attrs)
        if tag == "link" and "stylesheet" in (values.get("rel") or "").split():
            if values.get("href"):
                self.styles.append(values["href"])
        if tag == "script" and values.get("src"):
            self.scripts.append(values["src"])


def require(condition: bool, message: str) -> None:
    if not condition:
        raise AssertionError(message)


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def read_json(path: Path) -> dict:
    return json.loads(path.read_text(encoding="utf-8"))


def repository_path(root: Path, relative: str) -> Path:
    require(not Path(relative).is_absolute(), f"absolute repository path: {relative}")
    resolved = (root / relative).resolve()
    require(resolved == root or root in resolved.parents, f"path escapes repository: {relative}")
    return resolved


def web_path(document: str, reference: str) -> str | None:
    """Resolve browser fetch/asset references against the Window document base."""
    parsed = urlsplit(reference)
    if parsed.scheme or parsed.netloc:
        return None
    if reference.startswith("#"):
        return None
    resolved = urlsplit(urljoin(f"/{document}", reference)).path
    normalised = posixpath.normpath(resolved).lstrip("/")
    require(not normalised.startswith("../"), f"web path escapes publication root: {reference}")
    return normalised


def verify_record(root: Path, record: dict, label: str) -> Path:
    relative = record.get("path")
    require(isinstance(relative, str) and relative, f"{label} has no path")
    target = repository_path(root, relative)
    require(target.is_file(), f"missing {label}: {relative}")
    require(target.stat().st_size == record.get("bytes"), f"byte mismatch for {relative}")
    require(sha256(target) == record.get("sha256"), f"SHA-256 mismatch for {relative}")
    return target


def verify_record_at_commit(root: Path, commit: str, record: dict, label: str) -> None:
    relative = record.get("path")
    require(isinstance(relative, str) and relative, f"{label} has no path")
    completed = subprocess.run(
        ["git", "show", f"{commit}:{relative}"],
        cwd=root,
        check=True,
        capture_output=True,
    )
    payload = completed.stdout
    expected_bytes = record.get("bytes")
    if expected_bytes is not None:
        require(len(payload) == expected_bytes, f"historical byte mismatch for {relative}")
    require(
        hashlib.sha256(payload).hexdigest() == record.get("sha256"),
        f"historical SHA-256 mismatch for {relative}",
    )


def select_release(root: Path, requested: str) -> tuple[str, Path, dict]:
    manifests = sorted((root / "releases/manifests").glob("*-release-manifest.json"))
    require(manifests, "no compiled release manifests")
    if requested == "latest":
        manifest_path = manifests[-1]
        generation = manifest_path.name.removesuffix("-release-manifest.json")
    else:
        require(bool(GENERATION_RE.fullmatch(requested)), "generation must be latest or YYYYMMDDHHMM")
        generation = requested
        manifest_path = root / f"releases/manifests/{generation}-release-manifest.json"
    require(manifest_path.is_file(), f"missing release manifest for {generation}")
    return generation, manifest_path, read_json(manifest_path)


def run_compiler(root: Path, manifest: dict, generation: str) -> dict:
    compiler = manifest.get("compiler", {})
    compiler_path = repository_path(root, compiler.get("path", ""))
    require(compiler_path.is_file(), f"missing compiler: {compiler_path}")
    require(sha256(compiler_path) == compiler.get("sha256"), "compiler SHA-256 mismatch")
    require(compiler_path.name == f"{generation}-compile-index.mjs", "compiler generation mismatch")
    completed = subprocess.run(
        ["node", str(compiler_path), "--check"],
        cwd=root,
        check=True,
        text=True,
        capture_output=True,
    )
    result = json.loads(completed.stdout)
    expected = {
        "generation": f"{generation}-index",
        "output_files": EXPECTED_GENERATED_FILES,
        "input_files": EXPECTED_INPUTS,
        "project_count": EXPECTED_PROJECTS,
        "status": "CHECKED",
    }
    for key, value in expected.items():
        require(result.get(key) == value, f"compiler {key}: expected {value!r}, got {result.get(key)!r}")
    return result


def data_generation(manifest: dict) -> str:
    """The generation the immutable data cartridges were sealed under.

    Until 202609010836 this was assumed equal to the release generation, and
    the assumption broke the first time a release was recompiled without the
    data changing: the Aug-30 edit of a ui module forced a recompile, but the
    cartridges are referenced, never copied, so their names kept the stamp
    they were sealed under. The data generation is therefore derived from the
    manifest's own digest-verified inputs rather than assumed, and must be
    single-valued across every cartridge family.
    """
    stamps = {
        record["path"].rsplit("/", 1)[-1][:12]
        for record in manifest.get("inputs", [])
        if record["path"].startswith(("data/news/", "data/projects/", "data/atlas/"))
    }
    require(len(stamps) == 1, f"data cartridges span generations: {sorted(stamps)}")
    return next(iter(stamps))


def validate_html_and_modules(root: Path, manifest: dict, generation: str) -> None:
    document = f"releases/{generation}-index.html"
    html_path = repository_path(root, document)
    parser = RuntimeAssets()
    parser.feed(html_path.read_text(encoding="utf-8"))
    require(len(parser.styles) == 6, f"expected 6 stylesheets, found {len(parser.styles)}")
    require(len(parser.scripts) == 3, f"expected 3 scripts, found {len(parser.scripts)}")
    for reference in parser.styles + parser.scripts:
        target = web_path(document, reference)
        require(target is not None, f"external runtime asset is forbidden: {reference}")
        require(repository_path(root, target).is_file(), f"missing HTML runtime asset: {reference} -> {target}")

    modules = sorted(
        record["path"] for record in manifest["outputs"]
        if record["path"].startswith("releases/javascript/") and record["path"].endswith(".js")
    )
    require(len(modules) == 13, f"expected 13 emitted modules, found {len(modules)}")
    import_count = 0
    runtime_references: set[str] = set()
    for relative in modules:
        module_path = repository_path(root, relative)
        subprocess.run(["node", "--check", str(module_path)], cwd=root, check=True, capture_output=True)
        source = module_path.read_text(encoding="utf-8")
        for match in IMPORT_RE.finditer(source):
            specifier = match.group(1) or match.group(2)
            require(specifier.startswith(("./", "../")), f"non-local module import in {relative}: {specifier}")
            resolved = posixpath.normpath(posixpath.join(posixpath.dirname(relative), specifier))
            require(repository_path(root, resolved).is_file(), f"missing module import: {relative} -> {specifier}")
            import_count += 1
        runtime_references.update(RUNTIME_JSON_RE.findall(source))
    require(import_count == EXPECTED_IMPORTS, f"expected {EXPECTED_IMPORTS} imports, found {import_count}")
    require(manifest["substitutions"]["javascript_imports"] == import_count, "import count disagrees with manifest")

    cartridge_generation = data_generation(manifest)
    expected_runtime = {
        f"../data/contracts/{cartridge_generation}-release-v9-1.json",
        "../data/contracts/202608261737-release-v9-5-1.json",
        f"../data/news/{cartridge_generation}-major-project-news-v9-5-1.json",
        f"manifests/{generation}-build-manifest-v9-1.json",
    }
    require(runtime_references == expected_runtime, f"runtime data-reference set changed: {sorted(runtime_references)}")
    for reference in runtime_references:
        target = web_path(document, reference)
        require(target is not None and repository_path(root, target).is_file(), f"unreachable runtime data: {reference}")


def validate_data(root: Path, manifest: dict, generation: str) -> tuple[dict, dict]:
    build_path = root / f"releases/manifests/{generation}-build-manifest-v9-1.json"
    build = read_json(build_path)
    projects = build.get("project_partitions", [])
    atlas = build.get("atlas_partitions", [])
    require(len(projects) == EXPECTED_PROJECT_PARTITIONS, "project partition count changed")
    require(len(atlas) == EXPECTED_ATLAS_PARTITIONS, "atlas partition count changed")
    require(build.get("project_count") == EXPECTED_PROJECTS, "project total changed")
    require(build.get("capacity_mw") == 356474.09, "capacity total changed")
    require(build.get("largest_mw") == 4100, "largest project changed")
    require(build.get("solar_count") == 3563, "solar count changed")
    require(build.get("bess_count") == 1609, "BESS count changed")
    require(build.get("wind_onshore_count") == 2399, "onshore wind count changed")
    require(build.get("wind_offshore_count") == 109, "offshore wind count changed")

    document = f"releases/{generation}-index.html"
    counted_projects = 0
    for entry in projects:
        target = web_path(document, entry["path"])
        require(target is not None, f"invalid project path: {entry['path']}")
        path = repository_path(root, target)
        require(path.is_file(), f"missing project partition: {target}")
        require(sha256(path) == entry["sha256"], f"project partition hash mismatch: {target}")
        payload = read_json(path)
        require(payload["record_count"] == entry["record_count"], f"project record count mismatch: {target}")
        require(len(payload["projects"]) == entry["record_count"], f"project payload mismatch: {target}")
        counted_projects += len(payload["projects"])
    require(counted_projects == EXPECTED_PROJECTS, f"partition project total: {counted_projects}")

    counted_features = 0
    for entry in atlas:
        target = web_path(document, entry["path"])
        require(target is not None, f"invalid atlas path: {entry['path']}")
        path = repository_path(root, target)
        require(path.is_file(), f"missing atlas partition: {target}")
        require(sha256(path) == entry["sha256"], f"atlas partition hash mismatch: {target}")
        features = read_json(path)["features"]
        require(len(features) == entry["feature_count"], f"atlas feature count mismatch: {target}")
        counted_features += len(features)
    require(counted_features == build["geometry_count"], "atlas geometry total changed")

    news_path = root / f"data/news/{data_generation(manifest)}-major-project-news-v9-5-1.json"
    news = read_json(news_path)
    require(len(news.get("all_items", [])) == EXPECTED_HEADLINES, "headline total changed")
    require(len(news.get("canonical_items", [])) == EXPECTED_UK_HEADLINES, "UK headline total changed")
    return build, news


def validate_release(root: Path, requested: str, *, replay_sources: bool = True) -> dict:
    generation, manifest_path, manifest = select_release(root, requested)
    require(manifest.get("schema") == EXPECTED_SCHEMA, "release manifest schema changed")
    require(manifest.get("generation") == f"{generation}-index", "release generation mismatch")
    require(manifest.get("trusted_parent") == "GlobalGrid2050 V9.6.2", "trusted parent changed")
    require(manifest.get("status") == "COMPILED_AWAITING_BROWSER_ATTESTATION", "unexpected release state")
    require(
        manifest.get("public_url") == f"https://ventusltd.github.io/pipelinenews/releases/{generation}-index.html",
        "public release URL changed",
    )
    discipline = manifest.get("discipline", {})
    require(discipline.get("data_cartridges_copied") is False, "release must not duplicate data cartridges")
    require(discipline.get("release_references_immutable_data_cartridges") is True, "shared cartridge discipline changed")
    require(len(manifest.get("inputs", [])) == EXPECTED_INPUTS, "input record count changed")
    require(len(manifest.get("outputs", [])) == EXPECTED_OUTPUTS, "output record count changed")
    substitutions = manifest.get("substitutions", {})
    require(substitutions.get("html_asset_and_navigation_urls") == 25, "HTML substitution count changed")
    require(substitutions.get("project_manifest_paths") == EXPECTED_PROJECT_PARTITIONS, "project path rewrite count changed")
    require(substitutions.get("atlas_manifest_paths") == EXPECTED_ATLAS_PARTITIONS, "atlas path rewrite count changed")
    require(substitutions.get("chart_js_pinned_locally") == "4.5.1", "Chart.js pin changed")
    require(substitutions.get("mutable_news_sources_removed") is True, "mutable news source returned")

    manifest_commit = git_text(root, "log", "-1", "--format=%H", "--", manifest_path.relative_to(root).as_posix())
    require(bool(COMMIT_RE.fullmatch(manifest_commit)), "compiled release manifest is not committed")

    seen: set[str] = set()
    for record in manifest["inputs"]:
        require(record["path"] not in seen, f"duplicate manifest path: {record['path']}")
        seen.add(record["path"])
        if replay_sources or record["path"].startswith("data/"):
            verify_record(root, record, "input")
        else:
            verify_record_at_commit(root, manifest_commit, record, "historical input")
    for record in manifest["outputs"]:
        require(record["path"] not in seen, f"duplicate manifest path: {record['path']}")
        seen.add(record["path"])
        verify_record(root, record, "output")
    require(manifest_path.is_file(), "release manifest disappeared")

    if replay_sources:
        compiler_result = run_compiler(root, manifest, generation)
    else:
        verify_record_at_commit(root, manifest_commit, manifest["compiler"], "historical compiler")
        compiler_result = {
            "generation": f"{generation}-index",
            "status": "HISTORICAL_SOURCE_ATTESTED",
            "manifest_commit": manifest_commit,
        }
    validate_html_and_modules(root, manifest, generation)
    build, news = validate_data(root, manifest, generation)
    html_record = next(record for record in manifest["outputs"] if record["path"] == f"releases/{generation}-index.html")
    return {
        "generation": generation,
        "manifest": manifest,
        "compiler": compiler_result,
        "build": build,
        "news": news,
        "release_path": f"releases/{generation}-index.html",
        "release_sha256": html_record["sha256"],
        "public_url": manifest["public_url"],
    }


def _atlas_link_v2_outputs(root: Path, folder_relative: str) -> tuple[list[dict], set[str]]:
    ledger_relative = f"{folder_relative}/sha256sums.txt"
    ledger = repository_path(root, ledger_relative)
    require(ledger.is_file(), "Atlas-link SHA ledger missing")
    records: list[dict] = []
    declared: set[str] = set()
    for number, raw in enumerate(ledger.read_text(encoding="utf-8").splitlines(), 1):
        if not raw.strip():
            continue
        digest, separator, local = raw.partition("  ")
        require(separator == "  " and bool(SHA256_RE.fullmatch(digest)), f"bad Atlas-link ledger line {number}")
        require(
            local and "\\" not in local and "\x00" not in local
            and not Path(local).is_absolute()
            and posixpath.normpath(local) == local
            and all(part not in ("", ".", "..") for part in local.split("/")),
            f"unsafe Atlas-link ledger path {number}",
        )
        relative = f"{folder_relative}/{local}"
        require(relative not in declared, f"duplicate Atlas-link ledger path: {relative}")
        require_no_symlink_components(root, relative, "Atlas-link release")
        target = repository_path(root, relative)
        require(target.is_file(), f"Atlas-link file missing: {relative}")
        record = {"path": relative, "bytes": target.stat().st_size, "sha256": digest}
        verify_record(root, record, "Atlas-link ledger output")
        records.append(record)
        declared.add(relative)
    require(records, "Atlas-link SHA ledger is empty")
    ledger_record = {
        "path": ledger_relative,
        "bytes": ledger.stat().st_size,
        "sha256": sha256(ledger),
    }
    return records + [ledger_record], declared


def _promotion_receiver_record(receiver: dict, key: str, prefix: str) -> dict:
    value = receiver.get(key)
    require(isinstance(value, dict), f"promotion receiver {key} missing")
    require(set(value) >= {"path", "bytes", "sha256"}, f"promotion receiver {key} fields changed")
    path = value.get("path")
    require(
        isinstance(path, str)
        and path.startswith(prefix)
        and "\\" not in path
        and posixpath.normpath(path) == path,
        f"promotion receiver {key} path changed",
    )
    require(isinstance(value.get("bytes"), int) and value["bytes"] > 0, f"promotion receiver {key} bytes changed")
    require(bool(SHA256_RE.fullmatch(str(value.get("sha256", "")))), f"promotion receiver {key} digest changed")
    return value


def validate_pages_promotion_wrapper_v1(
    root: Path,
    release_id: str,
    generation: str,
    folder_relative: str,
    folder: Path,
    release_manifest_relative: str,
    release_manifest_path: Path,
    release_manifest: dict,
    build_manifest_relative: str,
    build_manifest: dict,
) -> dict:
    """Validate a Pages-class wrapper without reinterpreting its source bytes."""
    promotion = release_manifest.get("promotion_wrapper")
    expected_promotion_fields = {
        "schema", "source_release_id", "source_commit", "validator_commit",
        "copied_file_count", "copied_files_sha256", "source_release_manifest",
        "receiver_contract_sha256",
    }
    require(isinstance(promotion, dict) and set(promotion) == expected_promotion_fields,
            "promotion wrapper fields changed")
    require(promotion.get("schema") == "pipelinenews.pages-promotion-wrapper.v1",
            "promotion wrapper schema changed")
    require(build_manifest.get("promotion_wrapper") == promotion,
            "release and build promotion bindings differ")
    require(build_manifest.get("schema") == "pipelinenews.current-atlas-link-build-manifest.v2",
            "promotion build schema changed")
    for manifest in (release_manifest, build_manifest):
        require(manifest.get("generation") == generation and manifest.get("release_id") == release_id,
                "promotion wrapper identity changed")
    require(release_manifest.get("classification") == "CURRENT_ATLAS_LINK_CANDIDATE",
            "promotion wrapper classification changed")
    require(release_manifest.get("immutable_after_publication") is True,
            "promotion wrapper is not immutable")
    require(release_manifest.get("deployment") == "candidate",
            "promotion wrapper deployment state changed")
    require(release_manifest.get("product_surface")
            == "BYTE_IDENTICAL_ADDITIVE_RELEASE_PLUS_FINAL_GRID_RECEIVER",
            "promotion product boundary changed")
    require(all(release_manifest.get(key) == 0 for key in
                ("application_changes", "data_changes", "news_changes", "project_changes")),
            "promotion wrapper claims product changes")
    require(build_manifest.get("classification") == "DETERMINISTIC_SOURCE_RELEASE_PROMOTION",
            "promotion build classification changed")

    source_release_id = promotion.get("source_release_id")
    source_match = TIMESTAMP_FOLDER_RE.fullmatch(str(source_release_id or ""))
    require(source_match is not None and source_match.group(1) < generation,
            "promotion source identity changed")
    require(release_manifest.get("parent_release_id") == source_release_id
            and build_manifest.get("source_release_id") == source_release_id,
            "promotion source release bindings differ")
    source_commit = require_git_commit(root, promotion.get("source_commit"), "promotion source commit")
    validator_commit = require_git_commit(root, promotion.get("validator_commit"), "promotion validator commit")
    require(build_manifest.get("source_commit") == source_commit
            and build_manifest.get("validator_commit") == validator_commit,
            "promotion build commits differ")
    subprocess.run(["git", "merge-base", "--is-ancestor", source_commit, validator_commit],
                   cwd=root, check=True, capture_output=True)

    outputs, declared = _atlas_link_v2_outputs(root, folder_relative)
    record_by_path = {record["path"]: record for record in outputs}
    atlas_relative = f"{folder_relative}/atlas-link-manifest.json"
    required = {
        f"{folder_relative}/index.html", release_manifest_relative,
        build_manifest_relative, atlas_relative,
    }
    require(required.issubset(declared), "promotion ledger omits required files")

    build_declared: set[str] = set()
    files = build_manifest.get("files")
    require(isinstance(files, list) and files, "promotion build file list missing")
    for index, item in enumerate(files):
        require(isinstance(item, dict) and set(item) == {"path", "bytes", "sha256"},
                f"promotion build record {index} changed")
        local = item["path"]
        require(not Path(local).is_absolute() and posixpath.normpath(local) == local,
                f"unsafe promotion build path: {local}")
        relative = f"{folder_relative}/{local}"
        require(relative in declared, f"promotion build path absent from ledger: {relative}")
        expected = record_by_path[relative]
        require(item["bytes"] == expected["bytes"] and item["sha256"] == expected["sha256"],
                f"promotion build record differs: {relative}")
        require(relative not in build_declared, f"duplicate promotion build record: {relative}")
        build_declared.add(relative)
    require(declared - build_declared == {release_manifest_relative, build_manifest_relative},
            "promotion build and SHA ledgers differ")

    actual = {
        path.relative_to(root).as_posix()
        for path in folder.rglob("*") if path.is_file()
    }
    require(not any(path.is_symlink() for path in folder.rglob("*")),
            "symlink in promotion wrapper")
    require(actual == {record["path"] for record in outputs},
            "promotion wrapper closure differs from ledger")
    release_commit = git_text(root, "log", "--diff-filter=A", "-1", "--format=%H", "--",
                              release_manifest_relative)
    require(bool(COMMIT_RE.fullmatch(release_commit)), "promotion wrapper is not committed")
    require(git_text(root, "show", "-s", "--format=%P", release_commit).split()
            == [validator_commit], "promotion wrapper parent changed")
    changes = {
        line for line in git_text(root, "diff-tree", "--no-commit-id", "--name-only", "-r",
                                  release_commit).splitlines() if line
    }
    require(changes == actual, "promotion commit changes paths outside its wrapper folder")
    for item in outputs:
        require_commit_file(root, release_commit, item["path"], item["sha256"],
                            "promotion committed output")

    control_names = {
        "atlas-link-manifest.json", "build-manifest.json",
        "release-manifest.json", "sha256sums.txt",
    }
    source_prefix = f"releases/{source_release_id}/"
    source_files = {
        line.removeprefix(source_prefix)
        for line in git_text(root, "ls-tree", "-r", "--name-only", source_commit, "--",
                             source_prefix).splitlines()
        if line.startswith(source_prefix)
    }
    source_copies = source_files - control_names
    wrapper_copies = {
        path.removeprefix(f"{folder_relative}/") for path in actual
    } - control_names
    require(wrapper_copies == source_copies,
            "promotion wrapper does not copy the exact source file set")
    copied_records = []
    for local in sorted(wrapper_copies):
        wrapper_path = repository_path(root, f"{folder_relative}/{local}")
        source_path = f"{source_prefix}{local}"
        source_payload = subprocess.check_output(["git", "show", f"{source_commit}:{source_path}"],
                                                 cwd=root)
        wrapper_payload = wrapper_path.read_bytes()
        require(wrapper_payload == source_payload, f"promotion changed source bytes: {local}")
        copied_records.append({
            "path": local, "bytes": len(wrapper_payload),
            "sha256": hashlib.sha256(wrapper_payload).hexdigest(),
        })
    require(promotion.get("copied_file_count") == len(copied_records),
            "promotion copied-file count changed")
    copied_digest = hashlib.sha256(json.dumps(
        copied_records, ensure_ascii=False, sort_keys=True, separators=(",", ":")
    ).encode("utf-8")).hexdigest()
    require(promotion.get("copied_files_sha256") == copied_digest,
            "promotion copied-file closure digest changed")

    source_manifest_record = promotion.get("source_release_manifest")
    require(isinstance(source_manifest_record, dict)
            and set(source_manifest_record) == {"path", "bytes", "sha256"}
            and source_manifest_record.get("path")
            == f"releases/{source_release_id}/release-manifest.json",
            "promotion source manifest receipt changed")
    verify_record_at_commit(root, source_commit, source_manifest_record,
                            "promotion source manifest")
    source_manifest = json.loads(subprocess.check_output(
        ["git", "show", f"{source_commit}:{source_manifest_record['path']}"], cwd=root
    ).decode("utf-8"))
    require(source_manifest.get("schema") == "pipelinenews.additive-cartridge-release.v1"
            and source_manifest.get("deployment") == "not-authorised"
            and source_manifest.get("release_id") == source_release_id,
            "promotion source is not the immutable additive release")

    atlas = read_json(repository_path(root, atlas_relative))
    require(atlas.get("schema") == "pipelinenews.atlas-current-link-manifest.v2"
            and atlas.get("classification")
            == "VERIFIED_GRIDATLAS_PRODUCTION_RECEIVER_BOUND",
            "promotion Atlas binding changed")
    require(atlas.get("generation") == generation
            and atlas.get("pipeline_release_id") == release_id
            and atlas.get("source_pipeline_release_id") == source_release_id
            and atlas.get("source_commit") == source_commit,
            "promotion Atlas identity changed")
    transport = atlas.get("transport") or {}
    require(transport.get("identity_rule") == "EXACT_REPD_REF"
            and transport.get("query_parameter_order")
            == ["repd_ref", "project", "technology", "capacity_mw", "latitude", "longitude", "zoom"]
            and transport.get("source_rows") == 8756
            and transport.get("clickable_rows") == 8743
            and transport.get("unresolved_rows") == 13,
            "promotion transport contract changed")
    receiver = atlas.get("receiver")
    require(isinstance(receiver, dict)
            and receiver.get("schema") == "pipelinenews.gridatlas-production-receiver.v1"
            and receiver.get("repository") == "Ventusltd/gridatlas"
            and bool(COMMIT_RE.fullmatch(str(receiver.get("commit", ""))))
            and bool(GENERATION_RE.fullmatch(str(receiver.get("generation", ""))))
            and bool(re.fullmatch(r"v9\.\d+", str(receiver.get("version", ""))))
            and receiver.get("base_url") == "https://ventusltd.github.io/gridatlas/atlas/"
            and receiver.get("required_result") == "MEASURE_LINK_FIRST"
            and receiver.get("identity_reconciliation")
            == "VERIFY_CONCURRENTLY_AND_REMEASURE_AT_RESOLVED_POINT",
            "promotion receiver identity changed")
    _promotion_receiver_record(receiver, "measurement_cartridge", "atlas/cartridges/")
    _promotion_receiver_record(receiver, "engine_cartridge", "atlas/cartridges/")
    _promotion_receiver_record(receiver, "composition_manifest", "atlas/manifests/")
    _promotion_receiver_record(receiver, "production_proof", "tools/proofs/")
    receiver_digest = hashlib.sha256(json.dumps(
        receiver, ensure_ascii=False, sort_keys=True, separators=(",", ":")
    ).encode("utf-8")).hexdigest()
    require(atlas.get("receiver_contract_sha256") == receiver_digest
            and promotion.get("receiver_contract_sha256") == receiver_digest
            and build_manifest.get("receiver") == receiver,
            "promotion receiver contract digest changed")
    require(release_manifest.get("atlas_live_url") == receiver["base_url"]
            and release_manifest.get("atlas_receiver_commit") == receiver["commit"]
            and release_manifest.get("atlas_receiver_version") == receiver["version"],
            "promotion release receiver binding changed")

    return {
        "release_id": release_id,
        "generation": generation,
        "kind": "pages-promotion-wrapper-v1",
        "folder_path": f"{folder_relative}/",
        "index_path": f"{folder_relative}/index.html",
        "index_sha256": record_by_path[f"{folder_relative}/index.html"]["sha256"],
        "manifest_path": release_manifest_relative,
        "manifest_sha256": sha256(release_manifest_path),
        "manifest": release_manifest,
        "outputs": outputs,
        "release_commit": release_commit,
        "receiver": receiver,
        "source_release_id": source_release_id,
        "source_commit": source_commit,
    }


def validate_current_atlas_link_v2(
    root: Path,
    release_id: str,
    generation: str,
    folder_relative: str,
    folder: Path,
    release_manifest_relative: str,
    release_manifest_path: Path,
    release_manifest: dict,
    build_manifest_relative: str,
    build_manifest: dict,
) -> dict:
    require(release_manifest.get("schema") == "pipelinenews.current-atlas-link-release.v2", "Atlas-link release schema changed")
    if isinstance(release_manifest.get("promotion_wrapper"), dict):
        return validate_pages_promotion_wrapper_v1(
            root, release_id, generation, folder_relative, folder,
            release_manifest_relative, release_manifest_path, release_manifest,
            build_manifest_relative, build_manifest,
        )
    require(build_manifest.get("schema") == "pipelinenews.current-atlas-link-build-manifest.v2", "Atlas-link build schema changed")
    for manifest in (release_manifest, build_manifest):
        require(manifest.get("generation") == generation and manifest.get("release_id") == release_id, "Atlas-link identity changed")
    require(release_manifest.get("classification") == "CURRENT_ATLAS_LINK_CANDIDATE", "Atlas-link release classification changed")
    require(release_manifest.get("immutable_after_publication") is True, "Atlas-link release is not immutable")
    require(release_manifest.get("parent_release_id") == "202608291447-pipelinenews", "Atlas-link parent changed")
    require(release_manifest.get("atlas_release_id") == "202608300453-atlas-v9", "Atlas-link receiver changed")
    require(
        release_manifest.get("atlas_live_url")
        == "https://ventusltd.github.io/gridatlas/202608300453-atlas-v9/",
        "Atlas-link receiver URL changed",
    )
    require(
        all(release_manifest.get(key) == 0 for key in ("data_changes", "news_changes", "project_changes"))
        and release_manifest.get("application_changes") == 1,
        "Atlas-link product boundary changed",
    )
    route = release_manifest.get("exact_identity_route") or {}
    require(
        route.get("parameter") == "repd_ref"
        and route.get("golden_repd_ref") == "13599"
        and route.get("broad_search_supplement_requests_expected") == 0,
        "Atlas-link exact identity route changed",
    )
    require(build_manifest.get("classification") == "DETERMINISTIC_RECEIVER_ONLY_BUILD", "Atlas-link build classification changed")
    require(build_manifest.get("source_release_id") == "202608291447-pipelinenews", "Atlas-link source release changed")
    source_commit = require_git_commit(root, build_manifest.get("source_commit"), "Atlas-link source commit")
    require(
        all(build_manifest.get(key) == 0 for key in ("data_changes", "news_changes", "project_changes"))
        and build_manifest.get("application_changes") == 1
        and build_manifest.get("deep_link_logic_changes") == 2
        and len(build_manifest.get("deep_link_repairs") or []) == 2,
        "Atlas-link build boundary changed",
    )

    atlas_relative = f"{folder_relative}/atlas-link-manifest.json"
    atlas = read_json(repository_path(root, atlas_relative))
    require(atlas.get("schema") == "pipelinenews.atlas-current-link-manifest.v1", "Atlas-link binding schema changed")
    require(atlas.get("classification") == "VERIFIED_GRIDATLAS_V9_RECEIVER_BOUND", "Atlas-link binding classification changed")