GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / pipelinenews / orchestration

Build Current Atlas Link Successor and 1 more file

A Python command-line tool in the orchestration folder of PipelineNews that reads the Renewable Energy Planning Database (REPD) register, using SHA-256 from the GridAtlas repository.

526 lines of Python from pipelinenews, in 2 files. Topic: Maps, GIS and field navigation. Section 710 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 Current Atlas Link Successor electrical · pipelinenews / orchestration/202608300309-build-current-atlas-link-successor.py lines 1–303
  2. Promote Current Atlas Link electrical · pipelinenews / orchestration/202608300309-promote-current-atlas-link.py lines 1–223

Build Current Atlas Link Successor

A Python command-line tool in the orchestration folder of PipelineNews that reads the Renewable Energy Planning Database (REPD) register, using SHA-256 from the GridAtlas repository.

electricalpipelinenews / orchestration/202608300309-build-current-atlas-link-successor.py · lines 1–303 of 303 · version 2026-08-30 03:09 · Entry point · pattern validate_atlas (shared by 2 files)

What it does
It loads the REPD register. Defines 8 functions or classes, including require, sha256, load_json, validate_atlas, pointer_module. Uses libraries __future__, argparse, hashlib, json, re. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): 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: data source: gridatlas data; JSON file atlas-link-manifest.json; JSON file build-manifest.json; JSON file release-manifest.json; command-line arguments. Out: JSON file atlas-link-manifest.json; JSON file build-manifest.json; JSON file release-manifest.json.
Downstream impact
Used directly by 1 file: PipelineNews Current GridAtlas V9 Deep Link Successor Workflow (pipelinenews).
What it achieves
It loads JSON (`load_json`), validates atlas (`validate_atlas`) and verifies unchanged (`verify_unchanged`). Build a timestamped PipelineNews successor changing only the verified Atlas receiver. It accepts `--source`, `--output` and `--release-id`.
Why it matters
Run by PipelineNews Current GridAtlas V9 Deep Link Successor Workflow.
Application
pipelinenews · orchestration · Python CLI
Uses
__future__, argparse, hashlib, json, re, shutil, pathlib, typing
Used by
run by PipelineNews Current GridAtlas V9 Deep Link Successor Workflow (workflow run)
Produces
require, sha256, load_json, validate_atlas, pointer_module, verify_unchanged, write_manifests, main
Defines here
require, sha256, load_json, validate_atlas, pointer_module, verify_unchanged, write_manifests, 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 orchestration/202608300309-build-current-atlas-link-successor.py:1-303 · blob 3fc06005971c8fc82e213b7924c8dace0e0756ff · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Build a timestamped PipelineNews successor changing only the verified Atlas receiver."""

from __future__ import annotations

import argparse
import hashlib
import json
import re
import shutil
from pathlib import Path
from typing import Any


POINTER_PATH = Path("assets/202608291447-atlas-pointer-deep-link.mjs")
ALLOWED_CHANGED = {
    "index.html",
    POINTER_PATH.as_posix(),
    "atlas-link-manifest.json",
    "build-manifest.json",
    "release-manifest.json",
    "sha256sums.txt",
}


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


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


def load_json(path: Path) -> dict[str, Any]:
    value = json.loads(path.read_text(encoding="utf-8"))
    require(isinstance(value, dict), f"JSON root is not an object: {path}")
    return value


def validate_atlas(state: dict[str, Any], minimum_generation: str) -> dict[str, str]:
    generation = str(state.get("generation") or "")
    require(re.fullmatch(r"\d{12}", generation) is not None, "Atlas generation is invalid")
    require(int(generation) >= int(minimum_generation), "Atlas generation is below the minimum")
    current = state.get("current") or {}
    verification = state.get("verification") or {}
    release_id = str(current.get("release_id") or "")
    live_url = str(current.get("live_url") or "")
    source_commit = str(current.get("source_commit") or "")
    publication_commit = str(current.get("publication_commit") or "")
    require(re.fullmatch(r"\d{12}-atlas-v9", release_id) is not None, "Atlas release ID is invalid")
    require(live_url == f"https://ventusltd.github.io/gridatlas/{release_id}/", "Atlas live URL mismatch")
    require(re.fullmatch(r"[a-f0-9]{40}", source_commit) is not None, "Atlas source commit is invalid")
    require(re.fullmatch(r"[a-f0-9]{40}", publication_commit) is not None, "Atlas publication commit is invalid")
    require(verification.get("promotion_eligible") is True, "Atlas is not promotion eligible")
    require(int(verification.get("failed_gates", 999)) == 0, "Atlas has failed gates")
    return {
        "generation": generation,
        "release_id": release_id,
        "live_url": live_url,
        "source_commit": source_commit,
        "publication_commit": publication_commit,
    }


def pointer_module(
    generation: str,
    atlas: dict[str, str],
    golden_repd_ref: str,
    state_url: str,
) -> str:
    receiver = {
        "schema": "pipelinenews.gridatlas-live-pointer-receipt.v3",
        "classification": "VERIFIED_PROMOTION_ELIGIBLE_GRIDATLAS_V9",
        "generation": atlas["generation"],
        "release_id": atlas["release_id"],
        "base_url": atlas["live_url"],
        "source_commit": atlas["source_commit"],
        "publication_commit": atlas["publication_commit"],
        "query_parameter": "repd_ref",
        "identity_rule": "EXACT_REPD_REF_ONLY",
        "golden_repd_ref": golden_repd_ref,
        "state_url": state_url,
    }
    return f'''const GRIDATLAS_RECEIVER = Object.freeze({json.dumps(receiver, separators=(",", ":"))});

function invariant(condition, message) {{
  if (!condition) throw new Error(`Atlas receiver contract: ${{message}}`);
}}

const receiverUrl = new URL(GRIDATLAS_RECEIVER.base_url);
invariant(GRIDATLAS_RECEIVER.classification === "VERIFIED_PROMOTION_ELIGIBLE_GRIDATLAS_V9", "receiver not verified");
invariant(receiverUrl.protocol === "https:", "receiver is not HTTPS");
invariant(receiverUrl.hostname === "ventusltd.github.io", "receiver hostname changed");
invariant(receiverUrl.pathname === `/gridatlas/${{GRIDATLAS_RECEIVER.release_id}}/`, "receiver route mismatch");
invariant(GRIDATLAS_RECEIVER.identity_rule === "EXACT_REPD_REF_ONLY", "identity rule changed");

export const ATLAS_V9_DEEP_LINK_CONTRACT = Object.freeze({{
  schema: "pipelinenews.atlas-current-deep-link-cartridge.v1",
  generation: {json.dumps(generation)},
  receiver: GRIDATLAS_RECEIVER,
  eligibility: Object.freeze({{
    field: "geometry_status",
    equals: "valid",
    ineligible_result: "",
    presentation: "NO MAP"
  }}),
  identity_anchor: "repd_ref",
  query_parameter_order: Object.freeze(["repd_ref"]),
  inbound_match_semantics: "EXACT_PROJECT_REPD_REF",
  lifecycle: "timestamped PipelineNews release; receiver authenticated at build and public readback"
}});

export function buildAtlasV9DeepLink(project) {{
  if (project?.[ATLAS_V9_DEEP_LINK_CONTRACT.eligibility.field]
      !== ATLAS_V9_DEEP_LINK_CONTRACT.eligibility.equals) return "";
  const repdRef = String(project?.repd_ref ?? "").trim();
  if (!/^\\d+$/u.test(repdRef)) return "";
  const url = new URL(GRIDATLAS_RECEIVER.base_url);
  url.searchParams.set("repd_ref", repdRef);
  return url.href;
}}
'''


def verify_unchanged(source: Path, target: Path) -> None:
    for path in sorted(item for item in source.rglob("*") if item.is_file()):
        relative = path.relative_to(source).as_posix()
        if relative in ALLOWED_CHANGED or relative in {"build-manifest.json", "release-manifest.json"}:
            continue
        peer = target / relative
        require(peer.is_file(), f"source file disappeared: {relative}")
        require(peer.read_bytes() == path.read_bytes(), f"unapproved source-release byte change: {relative}")


def write_manifests(
    target: Path,
    source_release_id: str,
    release_id: str,
    generation: str,
    source_commit: str,
    atlas: dict[str, str],
    golden_repd_ref: str,
    state_url: str,
) -> None:
    atlas_manifest = {
        "schema": "pipelinenews.atlas-current-link-manifest.v1",
        "classification": "VERIFIED_GRIDATLAS_V9_RECEIVER_BOUND",
        "generation": generation,
        "pipeline_release_id": release_id,
        "source_pipeline_release_id": source_release_id,
        "atlas": {**atlas, "state_url": state_url},
        "identity": {
            "parameter": "repd_ref",
            "rule": "EXACT_REPD_REF_ONLY",
            "golden_repd_ref": golden_repd_ref,
            "golden_url": f'{atlas["live_url"]}?repd_ref={golden_repd_ref}',
        },
        "data_changes": 0,
        "news_changes": 0,
        "project_changes": 0,
    }
    (target / "atlas-link-manifest.json").write_text(
        json.dumps(atlas_manifest, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
        newline="\n",
    )

    files = []
    for path in sorted(
        item
        for item in target.rglob("*")
        if item.is_file() and item.name not in {"sha256sums.txt", "build-manifest.json", "release-manifest.json"}
    ):
        files.append(
            {
                "path": path.relative_to(target).as_posix(),
                "bytes": path.stat().st_size,
                "sha256": sha256(path),
            }
        )
    build = {
        "schema": "pipelinenews.current-atlas-link-build-manifest.v1",
        "classification": "DETERMINISTIC_RECEIVER_ONLY_BUILD",
        "generation": generation,
        "release_id": release_id,
        "source_release_id": source_release_id,
        "source_commit": source_commit,
        "atlas_release_id": atlas["release_id"],
        "allowed_changed_paths": sorted(ALLOWED_CHANGED),
        "files": files,
    }
    (target / "build-manifest.json").write_text(
        json.dumps(build, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
        newline="\n",
    )
    release = {
        "schema": "pipelinenews.current-atlas-link-release.v1",
        "classification": "CURRENT_ATLAS_LINK_CANDIDATE",
        "generation": generation,
        "release_id": release_id,
        "parent_release_id": source_release_id,
        "immutable_after_publication": True,
        "atlas_release_id": atlas["release_id"],
        "atlas_live_url": atlas["live_url"],
        "golden_repd_ref": golden_repd_ref,
        "promotion_policy": "LOCAL_AND_PUBLIC_BROWSER_DEEP_LINK_PROOF",
    }
    (target / "release-manifest.json").write_text(
        json.dumps(release, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
        newline="\n",
    )
    sums = []
    for path in sorted(item for item in target.rglob("*") if item.is_file() and item.name != "sha256sums.txt"):
        sums.append(f"{sha256(path)}  {path.relative_to(target).as_posix()}\n")
    (target / "sha256sums.txt").write_text("".join(sums), encoding="utf-8", newline="\n")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--source", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--release-id", required=True)
    parser.add_argument("--generation", required=True)
    parser.add_argument("--source-commit", required=True)
    parser.add_argument("--atlas-state", required=True)
    parser.add_argument("--atlas-state-url", required=True)
    parser.add_argument("--minimum-atlas-generation", required=True)
    parser.add_argument("--golden-repd-ref", default="16135")
    args = parser.parse_args()

    source = Path(args.source)
    target = Path(args.output)
    require(source.is_dir(), f"source release missing: {source}")
    require(not target.exists(), f"immutable output already exists: {target}")
    require(re.fullmatch(r"\d{12}-pipelinenews", args.release_id) is not None, "release ID invalid")
    require(re.fullmatch(r"\d{12}", args.generation) is not None, "generation invalid")
    require(args.release_id == f"{args.generation}-pipelinenews", "release ID and generation differ")
    require(re.fullmatch(r"\d+", args.golden_repd_ref) is not None, "golden REPD Ref invalid")

    atlas = validate_atlas(load_json(Path(args.atlas_state)), args.minimum_atlas_generation)
    shutil.copytree(source, target)
    for stale in ["build-manifest.json", "release-manifest.json", "sha256sums.txt"]:
        (target / stale).unlink(missing_ok=True)

    pointer = target / POINTER_PATH
    pointer.write_text(
        pointer_module(args.generation, atlas, args.golden_repd_ref, args.atlas_state_url),
        encoding="utf-8",
        newline="\n",
    )

    index_path = target / "index.html"
    index = index_path.read_text(encoding="utf-8")
    index, count = re.subn(
        r"https://ventusltd\.github\.io/gridatlas/[0-9]{12}-atlas-v9/",
        atlas["live_url"],
        index,
    )
    require(count >= 2, f"expected at least two direct Atlas links, found {count}")
    index = index.replace(
        'data-fast-generation="202608291447" data-release-id="202608291447-pipelinenews"',
        f'data-fast-generation="{args.generation}" data-release-id="{args.release_id}"',
    )
    index = index.replace(
        "<title>PipelineNews | Atlas V9 deep-link successor 202608291447</title>",
        f"<title>PipelineNews | Current verified Atlas V9 deep-link successor {args.generation}</title>",
    )
    index_path.write_text(index, encoding="utf-8", newline="\n")

    verify_unchanged(source, target)
    write_manifests(
        target,
        source.name,
        args.release_id,
        args.generation,
        args.source_commit,
        atlas,
        args.golden_repd_ref,
        args.atlas_state_url,
    )
    print(
        json.dumps(
            {
                "classification": "DETERMINISTIC_RECEIVER_ONLY_BUILD",
                "release_id": args.release_id,
                "source_release_id": source.name,
                "atlas_release_id": atlas["release_id"],
                "golden_url": f'{atlas["live_url"]}?repd_ref={args.golden_repd_ref}',
            },
            sort_keys=True,
        )
    )


if __name__ == "__main__":
    main()

Promote Current Atlas Link

A Python command-line tool in the orchestration folder of PipelineNews that reads the Renewable Energy Planning Database (REPD) register, using SHA-256 from the GridAtlas repository.

electricalpipelinenews / orchestration/202608300309-promote-current-atlas-link.py · lines 1–223 of 223 · version 2026-08-30 03:09 · Entry point · pattern validate_atlas (shared by 2 files)

What it does
It loads the REPD register. Defines 6 functions or classes, including require, load, sha256, file_record, validate_atlas. Uses libraries __future__, argparse, hashlib, json, re. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): 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: data source: gridatlas data; JSON file release-manifest.json; JSON file build-manifest.json; JSON file atlas-link-manifest.json; command-line arguments.
Downstream impact
Used directly by 2 files: PipelineNews Current GridAtlas V9 Deep Link Successor Workflow (pipelinenews); PipelineNews Resume Exact Atlas Pages Promotion Workflow (pipelinenews).
What it achieves
It validates atlas (`validate_atlas`) and is built from the require step (`require`) and the load step (`load`). Promote a publicly proven PipelineNews release bound to a verified Atlas V9 receiver. It accepts `--release-dir`, `--release-id` and `--generation`.
Why it matters
Run by PipelineNews Current GridAtlas V9 Deep Link Successor Workflow and PipelineNews Resume Exact Atlas Pages Promotion Workflow.
Application
pipelinenews · orchestration · Python CLI
Uses
__future__, argparse, hashlib, json, re, datetime, pathlib, typing
Used by
run by PipelineNews Current GridAtlas V9 Deep Link Successor Workflow (workflow run), run by PipelineNews Resume Exact Atlas Pages Promotion Workflow (workflow run)
Produces
require, load, sha256, file_record, validate_atlas, main
Defines here
require, load, sha256, file_record, validate_atlas, 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 orchestration/202608300309-promote-current-atlas-link.py:1-223 · blob 962bd9813fcd4678dceeb82bb9634cbd124d89ca · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Promote a publicly proven PipelineNews release bound to a verified Atlas V9 receiver."""

from __future__ import annotations

import argparse
import hashlib
import json
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Any


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


def load(path: Path) -> dict[str, Any]:
    value = json.loads(path.read_text(encoding="utf-8"))
    require(isinstance(value, dict), f"JSON root is not an object: {path}")
    return value


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


def file_record(path: Path, repository_path: str) -> dict[str, Any]:
    return {
        "path": repository_path,
        "bytes": path.stat().st_size,
        "sha256": sha256(path),
    }


def validate_atlas(state: dict[str, Any], minimum_generation: str) -> dict[str, Any]:
    generation = str(state.get("generation") or "")
    current = state.get("current") or {}
    verification = state.get("verification") or {}
    release_id = str(current.get("release_id") or "")
    base_url = str(current.get("live_url") or "")
    require(re.fullmatch(r"\d{12}", generation) is not None, "Atlas generation invalid")
    require(int(generation) >= int(minimum_generation), "Atlas generation below minimum")
    require(re.fullmatch(r"\d{12}-atlas-v9", release_id) is not None, "Atlas release invalid")
    require(base_url == f"https://ventusltd.github.io/gridatlas/{release_id}/", "Atlas base URL mismatch")
    require(verification.get("promotion_eligible") is True, "Atlas not promotion eligible")
    require(int(verification.get("failed_gates", 999)) == 0, "Atlas has failed gates")
    return {
        "generation": generation,
        "release_id": release_id,
        "base_url": base_url,
        "source_commit": current.get("source_commit"),
        "publication_commit": current.get("publication_commit"),
        "identity_rule": "EXACT_REPD_REF_ONLY",
        "query_parameter": "repd_ref",
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--release-dir", required=True)
    parser.add_argument("--release-id", required=True)
    parser.add_argument("--generation", required=True)
    parser.add_argument("--source-release-id", required=True)
    parser.add_argument("--release-source-commit", required=True)
    parser.add_argument("--publication-commit", required=True)
    parser.add_argument("--public-url", required=True)
    parser.add_argument("--public-proof", required=True)
    parser.add_argument("--atlas-state", required=True)
    parser.add_argument("--atlas-state-url", required=True)
    parser.add_argument("--minimum-atlas-generation", required=True)
    parser.add_argument("--golden-repd-ref", default="16135")
    parser.add_argument("--previous-state", required=True)
    parser.add_argument("--output-state", required=True)
    parser.add_argument("--output-current", required=True)
    parser.add_argument("--output-link-contract", required=True)
    args = parser.parse_args()

    require(re.fullmatch(r"\d{12}", args.generation) is not None, "generation invalid")
    require(args.release_id == f"{args.generation}-pipelinenews", "release ID mismatch")
    require(re.fullmatch(r"[a-f0-9]{40}", args.release_source_commit) is not None, "source commit invalid")
    require(re.fullmatch(r"[a-f0-9]{40}", args.publication_commit) is not None, "publication commit invalid")
    require(re.fullmatch(r"\d+", args.golden_repd_ref) is not None, "golden REPD Ref invalid")
    require(
        args.public_url == f"https://ventusltd.github.io/pipelinenews/releases/{args.release_id}/",
        "PipelineNews public URL mismatch",
    )

    release_dir = Path(args.release_dir)
    require(release_dir.is_dir(), f"release directory missing: {release_dir}")
    release_manifest_path = release_dir / "release-manifest.json"
    build_manifest_path = release_dir / "build-manifest.json"
    atlas_link_manifest_path = release_dir / "atlas-link-manifest.json"
    for path in (release_manifest_path, build_manifest_path, atlas_link_manifest_path):
        require(path.is_file(), f"release evidence missing: {path}")

    release_manifest = load(release_manifest_path)
    build_manifest = load(build_manifest_path)
    atlas_link_manifest = load(atlas_link_manifest_path)
    require(release_manifest.get("release_id") == args.release_id, "release manifest identity mismatch")
    require(build_manifest.get("release_id") == args.release_id, "build manifest identity mismatch")
    require(build_manifest.get("classification") == "DETERMINISTIC_RECEIVER_ONLY_BUILD", "build not deterministic")
    require(atlas_link_manifest.get("data_changes") == 0, "data changed")
    require(atlas_link_manifest.get("news_changes") == 0, "news changed")
    require(atlas_link_manifest.get("project_changes") == 0, "projects changed")

    atlas = validate_atlas(load(Path(args.atlas_state)), args.minimum_atlas_generation)
    require(atlas_link_manifest.get("atlas", {}).get("release_id") == atlas["release_id"], "Atlas release drift")
    require(atlas_link_manifest.get("atlas", {}).get("live_url") == atlas["base_url"], "Atlas URL drift")

    proof_path = Path(args.public_proof)
    proof = load(proof_path)
    require(proof.get("classification") == "VERIFIED_PUBLIC_PIPELINENEWS_ATLAS_V9_DEEP_LINK", "public proof classification mismatch")
    require(proof.get("mode") == "public", "public proof mode mismatch")
    require(proof.get("pipeline_url") == args.public_url, "public proof PipelineNews URL mismatch")
    expected_receiver = f'{atlas["base_url"]}?repd_ref={args.golden_repd_ref}'
    require(proof.get("expected_url") == expected_receiver, "public proof receiver mismatch")
    require(proof.get("synthetic_receiver") is False, "synthetic receiver evidence forbidden")
    require(int(proof.get("route_interceptions", 999)) == 0, "route interception detected")
    require(proof.get("errors") == [], "public proof contains errors")

    previous = load(Path(args.previous_state))
    require(previous.get("release_id") == args.source_release_id, "predecessor pointer moved")
    require(previous.get("classification") == "VERIFIED_LIVE_TIMESTAMPED_RELEASE", "predecessor is not green")

    verified_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
    atlas_receiver = {
        **atlas,
        "state_url": args.atlas_state_url,
        "golden_repd_ref": args.golden_repd_ref,
        "golden_url": expected_receiver,
    }
    state = {
        "schema": "pipelinenews.live-pointer.v4",
        "generation": args.generation,
        "release_id": args.release_id,
        "classification": "VERIFIED_LIVE_TIMESTAMPED_RELEASE",
        "route": f"/pipelinenews/releases/{args.release_id}/",
        "entrypoint": f"releases/{args.release_id}/index.html",
        "release_manifest": file_record(
            release_manifest_path,
            f"releases/{args.release_id}/release-manifest.json",
        ),
        "build_manifest": file_record(
            build_manifest_path,
            f"releases/{args.release_id}/build-manifest.json",
        ),
        "atlas_link_manifest": file_record(
            atlas_link_manifest_path,
            f"releases/{args.release_id}/atlas-link-manifest.json",
        ),
        "release_source_commit": args.release_source_commit,
        "deployed_commit": args.publication_commit,
        "verified_at_utc": verified_at,
        "atlas_v9_receiver": atlas_receiver,
        "predecessor": {
            "release_id": args.source_release_id,
            "classification": previous.get("classification"),
            "public_url": f"https://ventusltd.github.io/pipelinenews/releases/{args.source_release_id}/",
            "deployed_commit": previous.get("deployed_commit"),
        },
        "rollback": previous.get("rollback"),
        "public_proof": {
            "classification": proof["classification"],
            "path": proof_path.as_posix(),
            "sha256": sha256(proof_path),
            "pipeline_url": args.public_url,
            "receiver_url": expected_receiver,
            "synthetic_receiver": False,
            "route_interceptions": 0,
        },
    }

    link_contract = {
        "schema": "pipelinenews.atlas-v9-link-contract.v1",
        "classification": "VERIFIED_CURRENT_ATLAS_V9_RECEIVER",
        "generation": args.generation,
        "pipeline_release_id": args.release_id,
        "receiver": atlas_receiver,
        "join": {
            "identity_key": "repd_ref",
            "query_parameter": "repd_ref",
            "identity_rule": "EXACT_REPD_REF_ONLY",
            "url_template": f'{atlas["base_url"]}?repd_ref={{repd_ref}}',
        },
        "proof": state["public_proof"],
        "rollback": state["predecessor"],
    }

    state_payload = json.dumps(state, indent=2, sort_keys=True) + "\n"
    current_path = Path(args.output_current)
    state_path = Path(args.output_state)
    contract_path = Path(args.output_link_contract)
    for path in (state_path, current_path, contract_path):
        path.parent.mkdir(parents=True, exist_ok=True)
    state_path.write_text(state_payload, encoding="utf-8", newline="\n")
    current_path.write_text(state_payload, encoding="utf-8", newline="\n")
    contract_path.write_text(
        json.dumps(link_contract, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
        newline="\n",
    )
    print(
        json.dumps(
            {
                "classification": "VERIFIED_PIPELINENEWS_ATLAS_LINK_POINTER_BUILT",
                "release_id": args.release_id,
                "atlas_release_id": atlas["release_id"],
                "receiver_url": expected_receiver,
            },
            sort_keys=True,
        )
    )


if __name__ == "__main__":
    main()