GLOBALGRID2050 / EXPLORE CODE

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

Build Pages (part 3)

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.

560 lines of Python from pipelinenews, in 1 file. Topic: Electricity markets and data pipelines. Section 999 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 1401–1960

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 1401–1960 of 1960 · version 2026-08-26 20:14 (continued from section 997) · 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
copy_release_tree, nondeploying_release_trees, stage_legacy_apps, stage_site, emit_github_outputs, main
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:1401-1960 · 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
            label = f"fast candidate output {index} in {relative_manifest}"
            require(isinstance(record, dict), f"{label} is not an object")
            require(set(record) == {"path", "bytes", "sha256"}, f"unexpected fields in {label}")
            relative = normalise_candidate_output_path(record.get("path"), label)
            require(relative not in manifest_paths, f"duplicate path in {relative_manifest}: {relative}")
            manifest_paths.add(relative)
            output_records[relative] = record
            require(relative not in protected, f"candidate overlaps the governed release: {relative}")
            require(Path(relative).name.startswith(generation), f"candidate output generation mismatch: {relative}")
            require(isinstance(record.get("bytes"), int) and record["bytes"] >= 0, f"invalid byte count for {relative}")
            require(isinstance(record.get("sha256"), str) and bool(SHA256_RE.fullmatch(record["sha256"])), f"invalid SHA-256 for {relative}")
            require_no_symlink_components(root, relative, "fast candidate output path")
            verify_record(root, record, "fast candidate output")
            previous = owners.get(relative)
            require(previous is None, f"candidate output declared by both {previous} and {relative_manifest}: {relative}")
            owners[relative] = relative_manifest
            archived = root / ARCHIVE / relative
            require(not archived.exists() and not archived.is_symlink(), f"candidate overlaps historical public path: {relative}")

        candidate_path = f"releases/{generation}-v8-fast-candidate.html"
        require(candidate_path in output_records, f"candidate HTML is missing: {candidate_path}")
        require(generation not in candidates, f"duplicate fast candidate generation: {generation}")
        candidates[generation] = {
            "manifest": manifest,
            "manifest_path": relative_manifest,
            "manifest_sha256": sha256(manifest_path),
            "outputs": outputs,
            "output_records": output_records,
            "output_paths": manifest_paths,
            "candidate_path": candidate_path,
        }

    owned_paths = sorted(owners)
    for index, relative in enumerate(owned_paths):
        require(
            not any(other.startswith(f"{relative}/") for other in owned_paths[index + 1:]),
            f"candidate path collision: {relative}",
        )

    authorisations_dir = build / "authorisations"
    authorisations: dict[str, tuple[Path, dict]] = {}
    if authorisations_dir.exists():
        require(authorisations_dir.is_dir() and not authorisations_dir.is_symlink(), "invalid fast authorisations directory")
        for authorisation_path in sorted(authorisations_dir.iterdir()):
            relative_authorisation = authorisation_path.relative_to(root).as_posix()
            require_no_symlink_components(root, relative_authorisation, "fast authorisation path")
            require(authorisation_path.is_file(), f"fast authorisation is not a file: {relative_authorisation}")
            match = FAST_AUTHORISATION_RE.fullmatch(authorisation_path.name)
            require(match is not None, f"invalid fast authorisation filename: {relative_authorisation}")
            generation = match.group(1)
            expected_relative = f"build/authorisations/{generation}-v8-fast-pages-authorisation.json"
            require(relative_authorisation == expected_relative, f"misplaced fast authorisation: {relative_authorisation}")
            require(generation not in authorisations, f"duplicate fast authorisation: {generation}")
            authorisation = read_json(authorisation_path)
            require(isinstance(authorisation, dict), f"fast authorisation is not an object: {relative_authorisation}")
            authorisations[generation] = (authorisation_path, authorisation)

    require(set(authorisations).issubset(candidates), "fast authorisation has no matching immutable candidate")
    require(len(authorisations) <= 1, "at most one fast candidate may be authorised")

    # A newer immutable candidate may deliberately reuse outputs from older
    # candidates. Authorising the newest timestamp must therefore carry the
    # complete, hash-bound predecessor chain into Pages; otherwise the newest
    # route would be published with its inherited runtime files quarantined.
    progressive_generations: set[str] = set(authorisations)
    progressive_dependencies: dict[str, set[str]] = {}
    pending_generations = list(progressive_generations)
    while pending_generations:
        generation = pending_generations.pop()
        candidate = candidates[generation]
        inputs = candidate["manifest"].get("inputs")
        require(isinstance(inputs, list), f"fast candidate inputs changed: {candidate['manifest_path']}")
        dependencies: set[str] = set()
        for index, record in enumerate(inputs):
            require(isinstance(record, dict), f"fast candidate input {index} is not an object: {candidate['manifest_path']}")
            relative = record.get("path")
            owner_manifest = owners.get(relative) if isinstance(relative, str) else None
            if owner_manifest is None:
                continue
            owner_match = FAST_CANDIDATE_MANIFEST_RE.fullmatch(Path(owner_manifest).name)
            require(owner_match is not None, f"candidate dependency owner is invalid: {owner_manifest}")
            dependency_generation = owner_match.group(1)
            require(
                dependency_generation < generation,
                f"candidate dependency is not an older timestamp: {generation} -> {dependency_generation}",
            )
            dependency_record = candidates[dependency_generation]["output_records"][relative]
            require(
                record == dependency_record,
                f"candidate dependency binding differs from its immutable output: {relative}",
            )
            dependencies.add(dependency_generation)
            if dependency_generation not in progressive_generations:
                progressive_generations.add(dependency_generation)
                pending_generations.append(dependency_generation)
        progressive_dependencies[generation] = dependencies

    excluded: set[str] = set()
    authorised: set[str] = set()

    for generation, candidate in candidates.items():
        if generation not in progressive_generations:
            excluded.update(candidate["output_paths"])
            continue

        authorised.update(candidate["output_paths"])
        if generation not in authorisations:
            continue

        authorisation_path, authorisation = authorisations[generation]
        relative_authorisation = authorisation_path.relative_to(root).as_posix()
        expected_fields = {
            "schema", "generation", "scope", "deployment", "candidate_manifest", "candidate",
            "outputs", "outputs_sha256", "output_closure_sha256", "candidate_output_commit",
            "authorisation_source_commit", "github_run_id", "authorised_by",
            "authorised_at_source_commit", "evidence", "stable_route_promoted",
            "globalgrid_catalogue_changed",
        }
        require(set(authorisation) == expected_fields, f"fast authorisation fields changed: {relative_authorisation}")
        require(authorisation.get("schema") == FAST_AUTHORISATION_SCHEMA, f"fast authorisation schema changed: {relative_authorisation}")
        require(authorisation.get("generation") == generation, f"fast authorisation generation mismatch: {relative_authorisation}")
        require(authorisation.get("scope") == "github-pages-immutable-candidate", f"fast authorisation scope changed: {relative_authorisation}")
        require(authorisation.get("deployment") == "authorised", f"fast authorisation deployment state changed: {relative_authorisation}")
        require(authorisation.get("stable_route_promoted") is False, "fast authorisation may not promote the stable route")
        require(authorisation.get("globalgrid_catalogue_changed") is False, "fast authorisation may not change GlobalGrid")

        candidate_manifest = authorisation.get("candidate_manifest")
        require(isinstance(candidate_manifest, dict) and set(candidate_manifest) == {"path", "sha256"}, "invalid candidate manifest binding")
        require(candidate_manifest.get("path") == candidate["manifest_path"], "authorisation names the wrong candidate manifest")
        require(candidate_manifest.get("sha256") == candidate["manifest_sha256"], "candidate manifest SHA-256 changed")

        candidate_binding = authorisation.get("candidate")
        require(isinstance(candidate_binding, dict) and set(candidate_binding) == {"source_commit", "build_run", "cache_identity"}, "invalid candidate identity binding")
        manifest = candidate["manifest"]
        require(candidate_binding.get("source_commit") == manifest.get("source_commit"), "candidate source commit binding changed")
        require(candidate_binding.get("build_run") == manifest.get("github_run_id"), "candidate build run binding changed")
        require(candidate_binding.get("cache_identity") == manifest.get("cache_identity"), "candidate cache identity binding changed")
        require(authorisation.get("outputs") == candidate["outputs"], "authorised output closure differs from candidate manifest")
        closure_sha256 = compact_json_sha256(candidate["outputs"])
        require(authorisation.get("outputs_sha256") == closure_sha256, "authorised output closure SHA-256 changed")
        require(authorisation.get("output_closure_sha256") == closure_sha256, "authorised output closure alias changed")

        candidate_output_commit = require_git_commit(root, authorisation.get("candidate_output_commit"), "candidate output commit")
        authorisation_source_commit = require_git_commit(root, authorisation.get("authorisation_source_commit"), "authorisation source commit")
        authorisation_commit = git_text(root, "log", "-1", "--format=%H", "--", relative_authorisation)
        require(bool(COMMIT_RE.fullmatch(authorisation_commit)), "authorisation record is not committed")
        authorisation_parents = git_text(root, "show", "-s", "--format=%P", authorisation_commit).split()
        require(len(authorisation_parents) == 1, "authorisation commit must have exactly one parent")
        require(authorisation_parents[0] == authorisation_source_commit, "authorisation commit parent differs from authorised source")
        changed_paths = {
            line for line in git_text(
                root,
                "diff-tree",
                "--no-commit-id",
                "--name-only",
                "-r",
                authorisation_commit,
            ).splitlines() if line
        }
        require(changed_paths == {relative_authorisation}, "authorisation commit changes paths outside its immutable record")
        require_commit_file(
            root,
            authorisation_commit,
            relative_authorisation,
            sha256(authorisation_path),
            "authorisation record",
        )
        require(
            git_text(root, "log", "-1", "--format=%H", "--", candidate["manifest_path"]) == candidate_output_commit,
            "candidate output commit does not own the immutable manifest",
        )
        require_commit_file(root, candidate_output_commit, candidate["manifest_path"], candidate["manifest_sha256"], "candidate manifest")
        for record in candidate["outputs"]:
            require_commit_file(root, candidate_output_commit, record["path"], record["sha256"], "candidate output")
        timestamp_folder = release.get("timestamp_folder")
        changed_public_paths = {
            line for line in git_text(
                root,
                "diff",
                "--name-only",
                pages_public_change_base(release),
                "HEAD",
                "--",
                "releases",
                "data",
                "archive",
                "state",
            ).splitlines() if line
        }
        allowed_public_changes: set[str] = set()
        if timestamp_folder is not None:
            allowed_public_changes.update(record["path"] for record in timestamp_folder["outputs"])
            allowed_public_changes.add(timestamp_folder["manifest_path"])
        live_pointer = release.get("live_pointer")
        if live_pointer is not None:
            allowed_public_changes.update(live_pointer["paths"])
            pointer_release_id = (live_pointer.get("pointer") or {}).get("release_id")
            if isinstance(pointer_release_id, str) and TIMESTAMP_FOLDER_RE.fullmatch(pointer_release_id):
                pointer_release_root = root / "releases" / pointer_release_id
                require(pointer_release_root.is_dir(), "pointer-bound release folder missing")
                allowed_public_changes.update(
                    path.relative_to(root).as_posix()
                    for path in pointer_release_root.rglob("*")
                    if path.is_file()
                )
        require(
            changed_public_paths.issubset(allowed_public_changes),
            f"legacy public tree changed outside exact Atlas V9 release/pointers: {sorted(changed_public_paths - allowed_public_changes)}",
        )
        subprocess.run(
            ["git", "merge-base", "--is-ancestor", ATLAS_V9_SOURCE_PARENT, "HEAD"],
            cwd=root,
            check=True,
            capture_output=True,
        )
        subprocess.run(
            ["git", "merge-base", "--is-ancestor", manifest["source_commit"], candidate_output_commit],
            cwd=root,
            check=True,
            capture_output=True,
        )
        subprocess.run(
            ["git", "merge-base", "--is-ancestor", authorisation_source_commit, "HEAD"],
            cwd=root,
            check=True,
            capture_output=True,
        )
        expected_timestamp = git_text(root, "show", "-s", "--format=%cI", authorisation_source_commit)
        timestamp = authorisation.get("authorised_at_source_commit")
        require(isinstance(timestamp, str), "invalid authorisation source timestamp")
        require(iso8601_instant(timestamp) == iso8601_instant(expected_timestamp), "authorisation timestamp differs from source commit")
        require(isinstance(authorisation.get("github_run_id"), str) and authorisation["github_run_id"].isdigit(), "invalid authorisation run ID")
        require(isinstance(authorisation.get("authorised_by"), str) and authorisation["authorised_by"].strip(), "missing authorising actor")
        evidence = authorisation.get("evidence")
        expected_evidence = {
            "actor": authorisation["authorised_by"],
            "run_id": authorisation["github_run_id"],
            "source": authorisation_source_commit,
            "authorised_at_utc": timestamp,
        }
        require(evidence == expected_evidence, "authorisation workflow evidence changed")

        candidate_verifier = f"build/javascript/{generation}-verify-v8-fast-browser.mjs"
        require_no_symlink_components(root, candidate_verifier, "fast candidate browser verifier")
        verifier_path = repository_path(root, candidate_verifier)
        require(verifier_path.is_file(), f"missing fast candidate browser verifier: {candidate_verifier}")
        subprocess.run(
            ["node", "--check", str(verifier_path)],
            cwd=root,
            check=True,
            capture_output=True,
        )

        release["candidate_generation"] = generation
        release["candidate_path"] = candidate["candidate_path"]
        release["candidate_sha256"] = candidate["output_records"][candidate["candidate_path"]]["sha256"]
        release["candidate_verifier"] = candidate_verifier
        release["candidate_authorisation"] = relative_authorisation

    if authorisations:
        release["candidate_chain"] = sorted(progressive_generations)
        release["candidate_dependencies"] = {
            generation: sorted(progressive_dependencies.get(generation, set()))
            for generation in sorted(progressive_generations)
        }
        release["candidate_outputs"] = [
            record
            for generation in sorted(progressive_generations)
            for record in candidates[generation]["outputs"]
        ]

    require(excluded.isdisjoint(authorised), "candidate output is both excluded and authorised")
    return excluded, authorised


def copy_release_tree(
    source: Path,
    target: Path,
    excluded: set[str],
    excluded_trees: set[str] | None = None,
) -> None:
    """Overlay committed releases without copying non-deploying candidates."""
    require(source.is_dir(), f"release publication tree missing: {source}")
    excluded_trees = excluded_trees or set()
    target.mkdir(parents=True, exist_ok=True)
    for candidate in sorted(source.rglob("*")):
        relative = candidate.relative_to(source).as_posix()
        public_relative = f"releases/{relative}"
        require(not candidate.is_symlink(), f"symlink in release publication tree: {public_relative}")
        if any(public_relative == prefix or public_relative.startswith(f"{prefix}/")
               for prefix in excluded_trees):
            continue
        if public_relative in excluded:
            require(candidate.is_file(), f"excluded candidate output is not a file: {public_relative}")
            continue
        destination = target / relative
        if candidate.is_dir():
            destination.mkdir(parents=True, exist_ok=True)
        elif candidate.is_file():
            destination.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(candidate, destination)
        else:
            raise AssertionError(f"unsupported release publication entry: {public_relative}")


def nondeploying_release_trees(root: Path) -> set[str]:
    """Return additive source releases that Pages must never serve directly."""
    releases = root / "releases"
    require(releases.is_dir(), "release publication tree missing")
    excluded: set[str] = set()
    for folder in sorted(releases.iterdir()):
        if not folder.is_dir() or not TIMESTAMP_FOLDER_RE.fullmatch(folder.name):
            continue
        require(not folder.is_symlink(), f"symlink release folder: {folder.name}")
        manifest_path = folder / "release-manifest.json"
        if not manifest_path.is_file():
            continue
        manifest = read_json(manifest_path)
        if manifest.get("schema") != "pipelinenews.additive-cartridge-release.v1":
            continue
        require(manifest.get("release_id") == folder.name,
                f"additive release identity changed: {folder.name}")
        require(manifest.get("deployment") == "not-authorised",
                f"additive release gained direct Pages authority: {folder.name}")
        excluded.add(f"releases/{folder.name}")
    return excluded


def stage_legacy_apps(archive: Path, site: Path) -> None:
    v1_files = [
        "newsv1/index.html", "newsv1/MIGRATION_MANIFEST.json",
        "newsv1/scripts/app-newsv1.js", "newsv1/scripts/core/plugin-host.js",
        "newsv1/scripts/core/project-filter-v9-2.js", "newsv1/scripts/core/state.js",
        "newsv1/scripts/core/utils.js", "newsv1/scripts/data/canonical-projects-newsv1-release.js",
        "newsv1/scripts/data/canonical-projects-newsv1.js",
        "newsv1/scripts/plugins/capacity-presentation-v9-3.js", "newsv1/scripts/plugins/gauges-v9-2.js",
        "newsv1/scripts/plugins/newspaper-newsv1-base.js", "newsv1/scripts/plugins/newspaper-newsv1.js",
        "newsv1/scripts/plugins/projects-newsv1.js", "newsv1/styles/v7.css",
        "newsv1/styles/mobile.css", "newsv1/styles/v9-3.css", "newsv1/styles/v9-4.css",
        "newsv1/styles/v9-5-1.css", "newsv1/styles/v9-6-1.css",
        "newsv1/styles/performance-newsv1.css", "newsv1/contracts/release.newsv1.json",
        "newsv1/contracts/release.v9.1.json", "newsv1/data/v9.1/build_manifest.json",
        "newsv1/data/v9.7/regional_manifest.json", "newsv1/data/v9.7/regional_news.json",
        "newsv1/dist/major_project_news_v9_5_1.json",
    ]
    v7_files = [
        "newsv7/index.html", "newsv7/MIGRATION_MANIFEST.json",
        "newsv7/scripts/app-newsv7.js", "newsv7/scripts/core/plugin-host.js",
        "newsv7/scripts/core/project-filter-v9-2.js", "newsv7/scripts/core/state.js",
        "newsv7/scripts/core/utils.js", "newsv7/scripts/data/canonical-projects-newsv7-release.js",
        "newsv7/scripts/data/canonical-projects-newsv7.js",
        "newsv7/scripts/plugins/capacity-presentation-v9-3.js", "newsv7/scripts/plugins/gauges-v9-2.js",
        "newsv7/scripts/plugins/intelligence-newsv7.js", "newsv7/scripts/plugins/newspaper-newsv7-base.js",
        "newsv7/scripts/plugins/newspaper-newsv7.js", "newsv7/scripts/plugins/projects-newsv7.js",
        "newsv7/styles/v7.css", "newsv7/styles/mobile.css", "newsv7/styles/v9-3.css",
        "newsv7/styles/v9-4.css", "newsv7/styles/v9-5-1.css", "newsv7/styles/v9-6-1.css",
        "newsv7/styles/performance-newsv7.css", "newsv7/styles/intelligence-newsv7.css",
        "newsv7/contracts/release.newsv7.json", "newsv7/contracts/release.v9.1.json",
        "newsv7/data/v9.1/build_manifest.json", "newsv7/data/v9.7/regional_manifest.json",
        "newsv7/data/v9.7/regional_news.json", "newsv7/data/newsv7/cumulative_intelligence.json",
        "newsv7/data/newsv7/build_manifest.json", "newsv7/dist/major_project_news_v9_5_1.json",
    ]
    for relative in v1_files + v7_files:
        copy_file(archive, site, relative)
    copy_tree(archive / "newsv1/data/v9.1/projects", site / "newsv1/data/v9.1/projects")
    copy_tree(archive / "newsv7/data/v9.1/projects", site / "newsv7/data/v9.1/projects")


def stage_site(root: Path, site: Path, release: dict) -> None:
    require(not site.exists(), f"staging destination already exists: {site}")
    site.mkdir(parents=True)
    archive = root / ARCHIVE
    require(archive.is_dir(), f"missing archived public closure: {archive}")
    stage_legacy_apps(archive, site)

    timestamp_releases = sorted(
        path for path in archive.iterdir()
        if path.is_dir() and re.fullmatch(r"\d{12}-(?:PipelineNews|pipelinenews)", path.name)
    )
    require(len(timestamp_releases) == 9, f"historical timestamp release count: {len(timestamp_releases)}")
    for source in timestamp_releases:
        copy_tree(source, site / source.name)
    copy_tree(archive / "objects", site / "objects")
    copy_tree(archive / "releases", site / "releases")
    if (archive / "attestations").is_dir():
        copy_tree(archive / "attestations", site / "attestations")

    pointer_name = "current.json" if (archive / "attestations/202608260159-pipelinenews-closure.json").is_file() else "candidate.json"
    pointer = read_json(archive / "releases" / pointer_name)
    governed_manifest = read_json(repository_path(archive, pointer["manifest"]))
    for proof in governed_manifest.get("proof", []):
        relative = proof.get("path", "")
        if relative.startswith("reports/"):
            copy_file(archive, site, relative)

    excluded_candidates, authorised_candidates = candidate_publication_boundary(root, release)
    timestamp_folder = release.get("timestamp_folder")
    excluded_release_trees = nondeploying_release_trees(root)
    if timestamp_folder is not None and timestamp_folder.get("kind") == "pages-promotion-wrapper-v1":
        require(f"releases/{timestamp_folder['source_release_id']}" in excluded_release_trees,
                "promotion source is not classified as non-deploying")
    copy_release_tree(
        root / "releases", site / "releases", excluded_candidates, excluded_release_trees,
    )
    copy_tree(root / "data", site / "data")
    live_pointer = release.get("live_pointer")
    if live_pointer is not None:
        for relative in live_pointer["paths"]:
            copy_file(root, site, relative)
    (site / ".nojekyll").touch()

    for relative in excluded_candidates:
        require(not (site / relative).exists(), f"non-deploying candidate entered Pages artifact: {relative}")
    for relative in excluded_release_trees:
        require(not (site / relative).exists(),
                f"non-deploying promotion source entered Pages artifact: {relative}")
    authorised_records = {
        record["path"]: record for record in release.get("candidate_outputs", [])
    }
    require(set(authorised_records) == authorised_candidates, "authorised candidate record set changed")
    for relative in authorised_candidates:
        verify_record(site, authorised_records[relative], "staged authorised candidate output")
    if timestamp_folder is not None:
        for record in timestamp_folder["outputs"]:
            verify_record(site, record, "staged timestamp-folder output")
        timestamp_manifest = timestamp_folder["manifest_path"]
        require((site / timestamp_manifest).is_file(), "staged timestamp release manifest is missing")
        require(
            sha256(site / timestamp_manifest) == timestamp_folder["manifest_sha256"],
            "staged timestamp release manifest changed",
        )

    required = [
        "newsv1/index.html", "newsv7/index.html", "202608260159-pipelinenews/index.html",
        "objects/data/sha256/3d2cd9cba8581bbc8c4e7434deb0c584d3969639a00926393cf011e2c3f8a00b.json",
        "releases/current.json", release["release_path"],
    ]
    if timestamp_folder is not None:
        required.extend([timestamp_folder["index_path"], timestamp_folder["manifest_path"]])
    if live_pointer is not None:
        required.extend(live_pointer["paths"])
    for relative in required:
        require((site / relative).is_file(), f"staged public path missing: {relative}")
    forbidden_roots = ["ui", "index", "atman", "archive"]
    for relative in forbidden_roots:
        require(not (site / relative).exists(), f"source tree was published: {relative}")
    require(not any(path.name == "tests" for path in site.rglob("tests")), "test tree was published")
    require(not any(path.is_symlink() for path in site.rglob("*")), "symlink in Pages artifact")

    manifest = release["manifest"]
    for record in manifest["outputs"]:
        verify_record(site, record, "staged output")
    for record in manifest["inputs"]:
        if record["path"].startswith("data/"):
            verify_record(site, record, "staged shared data")
    validate_html_and_modules(site, manifest, release["generation"])
    validate_data(site, manifest, release["generation"])


def emit_github_outputs(release: dict, site: Path | None) -> None:
    output_path = os.environ.get("GITHUB_OUTPUT")
    if not output_path:
        return
    values = {
        "generation": release["generation"],
        "release_path": release["release_path"],
        "release_sha256": release["release_sha256"],
        "public_url": release["public_url"],
        "project_count": EXPECTED_PROJECTS,
        "headline_count": EXPECTED_HEADLINES,
    }
    for key in ("candidate_generation", "candidate_path", "candidate_sha256", "candidate_verifier"):
        if key in release:
            values[key] = release[key]
    timestamp_folder = release.get("timestamp_folder")
    if timestamp_folder is not None:
        values.update({
            "timestamp_folder_release": timestamp_folder["release_id"],
            "timestamp_folder_generation": timestamp_folder["generation"],
            "timestamp_folder_path": timestamp_folder["folder_path"],
            "timestamp_folder_index_path": timestamp_folder["index_path"],
            "timestamp_folder_index_sha256": timestamp_folder["index_sha256"],
            "timestamp_folder_manifest_path": timestamp_folder["manifest_path"],
            "timestamp_folder_manifest_sha256": timestamp_folder["manifest_sha256"],
        })
    live_pointer = release.get("live_pointer")
    if live_pointer is not None:
        values.update({
            "live_pointer": "true",
            "live_pointer_sha256": live_pointer["sha256"],
            "live_pointer_bytes": live_pointer["bytes"],
        })
    if site is not None:
        files = [path for path in site.rglob("*") if path.is_file()]
        values["staged_files"] = len(files)
        values["staged_bytes"] = sum(path.stat().st_size for path in files)
    with Path(output_path).open("a", encoding="utf-8") as handle:
        for key, value in values.items():
            handle.write(f"{key}={value}\n")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", default=".", help="repository root")
    parser.add_argument("--generation", default="latest", help="latest or YYYYMMDDHHMM")
    parser.add_argument("--stage", help="fresh Pages staging directory")
    parser.add_argument("--timestamp-folder-release", help="optional immutable YYYYMMDDHHMM-pipelinenews folder")
    args = parser.parse_args()

    root = Path(args.root).resolve()
    release = validate_release(root, args.generation, replay_sources=not bool(args.timestamp_folder_release))
    if args.timestamp_folder_release:
        release["timestamp_folder"] = validate_timestamp_folder_release(root, args.timestamp_folder_release)
    timestamp_folder = release.get("timestamp_folder")
    if (timestamp_folder is not None
            and timestamp_folder.get("kind") in {
                "current-atlas-link-v2", "pages-promotion-wrapper-v1",
            }):
        live_pointer = validate_current_or_predecessor_pointer(root, timestamp_folder)
    else:
        live_pointer = validate_live_pointer(root, timestamp_folder)
    if live_pointer is not None:
        release["live_pointer"] = live_pointer
    site = Path(args.stage).resolve() if args.stage else None
    if site is not None:
        stage_site(root, site, release)
    emit_github_outputs(release, site)
    summary = {
        "status": "CHECKED_AND_STAGED" if site else "CHECKED",
        "generation": release["generation"],
        "release_path": release["release_path"],
        "release_sha256": release["release_sha256"],
        "project_count": EXPECTED_PROJECTS,
        "headline_count": EXPECTED_HEADLINES,
        "site": str(site) if site else None,
    }
    for key in ("candidate_generation", "candidate_path", "candidate_sha256", "candidate_verifier"):
        if key in release:
            summary[key] = release[key]
    if "timestamp_folder" in release:
        summary["timestamp_folder"] = {
            key: value for key, value in release["timestamp_folder"].items()
            if key != "manifest"
        }
    if "live_pointer" in release:
        summary["live_pointer"] = {
            "paths": release["live_pointer"]["paths"],
            "bytes": release["live_pointer"]["bytes"],
            "sha256": release["live_pointer"]["sha256"],
        }
    print(json.dumps(summary, indent=2))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as error:
        print(f"PAGES BUILD GATE FAILED: {error}", file=sys.stderr)
        raise