GLOBALGRID2050 / EXPLORE CODE

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

PipelineNews Sync Atlas V9 Deep Links and 2 more files

A Python command-line tool in the scripts folder that reads GridAtlas current, atlas deep link audit, solar and battery storage (BESS).

470 lines of JavaScript and Python from pipelinenews, in 3 files. Topic: Maps, GIS and field navigation. Section 712 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. JavaScript Atlas V8 Deep Link Cartridge transform · pipelinenews / releases/javascript/202608271329-atlas-v8-deep-link-cartridge.js lines 1–79
  2. PipelineNews Sync Atlas V9 Deep Links render · pipelinenews / scripts/202608300232-sync-atlas-v9-deep-links.py lines 1–234
  3. Verify Atlas Deep Link Contract ingest · pipelinenews / tools/intelligence/202609012300-verify-atlas-deep-link-contract.mjs lines 1–157

JavaScript Atlas V8 Deep Link Cartridge

A JavaScript module in PipelineNews that works with solar. It builds atlas v8 deep link (`buildAtlasV8DeepLink`).

transformpipelinenews / releases/javascript/202608271329-atlas-v8-deep-link-cartridge.js · lines 1–79 of 79 · version 2026-08-27 13:29 · pattern buildAtlasV8DeepLink (shared by 2 files)

What it does
It calculates solar. Defines buildAtlasV8DeepLink.
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: solar.
Downstream impact
Used directly by 1 file: JavaScript V8 Fast Runtime (pipelinenews). Reached from 126 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage V002 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v002.html).
What it achieves
Defines `buildAtlasV8DeepLink`.
Why it matters
Imported by JavaScript V8 Fast Runtime.
Application
pipelinenews · releases/javascript · JavaScript module
Uses
GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL)
Used by
imported by JavaScript V8 Fast Runtime (import)
Produces
ATLAS_V8_DEEP_LINK_CONTRACT, buildAtlasV8DeepLink
Defines here
buildAtlasV8DeepLink
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/javascript/202608271329-atlas-v8-deep-link-cartridge.js:1-79 · blob d016cc46d993b48c9f8e3423da122a2ae2e295b2 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
export const ATLAS_V8_DEEP_LINK_CONTRACT = Object.freeze({
  schema: "pipelinenews.atlas-v8-deep-link-cartridge.v1",
  generation: "202608271329",
  parent_generation: "202608270844",
  trusted_reference: Object.freeze({
    application: "GlobalGrid2050 UK Renewables Pipeline V9.6.2",
    function: "atlasUrlV9_5_1",
    source_sha256: "f0c63602d85a5726aa38106157e8d3d6924d0ab1a684194ffe2de93df1c6d823",
  }),
  target: Object.freeze({
    protocol: "https:",
    hostname: "globalgrid2050.com",
    pathname: "/repd_grid_atlasv8/",
    base_url: "https://globalgrid2050.com/repd_grid_atlasv8/",
  }),
  eligibility: Object.freeze({
    field: "geometry_status",
    equals: "valid",
    ineligible_result: "",
    presentation: "NO MAP",
  }),
  identity_anchor: "repd_ref",
  query_parameter_order: Object.freeze([
    "repd_ref",
    "project",
    "technology",
    "capacity_mw",
    "latitude",
    "longitude",
    "zoom",
  ]),
  project_field_by_parameter: Object.freeze({
    repd_ref: "repd_ref",
    project: "name",
    technology: "technology",
    capacity_mw: "capacity_mw",
    latitude: "latitude",
    longitude: "longitude",
  }),
  fixed_parameters: Object.freeze({ zoom: "12" }),
  receiver_contract: Object.freeze({
    canonical_identity: Object.freeze(["repd_ref", "technology"]),
    display_context: Object.freeze(["project", "capacity_mw"]),
    coordinate_fallback: Object.freeze(["longitude", "latitude", "zoom"]),
    query_context_never_establishes_identity: true,
  }),
  sentinels: Object.freeze({
    east_pye: Object.freeze({
      repd_ref: "17494",
      expected_url: "https://globalgrid2050.com/repd_grid_atlasv8/?repd_ref=17494&project=East+Pye+Solar+Farm&technology=solar&capacity_mw=500&latitude=52.4733298&longitude=1.2432764&zoom=12",
    }),
    beacon_fen: Object.freeze({
      repd_ref: "13599",
      expected_url: "https://globalgrid2050.com/repd_grid_atlasv8/?repd_ref=13599&project=Beacon+Fen+Energy+Park&technology=solar&capacity_mw=400&latitude=52.9989987&longitude=-0.4092339&zoom=12",
    }),
    invalid_geometry: Object.freeze({
      repd_ref: "12780",
      expected_url: "",
      presentation: "NO MAP",
    }),
  }),
  lifecycle: "write-once; behavioural changes require a later timestamped cartridge",
  deployment: "not-authorised",
});

export function buildAtlasV8DeepLink(project) {
  if (project?.[ATLAS_V8_DEEP_LINK_CONTRACT.eligibility.field]
      !== ATLAS_V8_DEEP_LINK_CONTRACT.eligibility.equals) {
    return ATLAS_V8_DEEP_LINK_CONTRACT.eligibility.ineligible_result;
  }

  const url = new URL(ATLAS_V8_DEEP_LINK_CONTRACT.target.base_url);
  for (const parameter of ATLAS_V8_DEEP_LINK_CONTRACT.query_parameter_order) {
    const fixed = ATLAS_V8_DEEP_LINK_CONTRACT.fixed_parameters[parameter];
    const field = ATLAS_V8_DEEP_LINK_CONTRACT.project_field_by_parameter[parameter];
    url.searchParams.set(parameter, fixed ?? project[field]);
  }
  return url.href;
}

PipelineNews Sync Atlas V9 Deep Links

A Python command-line tool in the scripts folder that reads GridAtlas current, atlas deep link audit, solar and battery storage (BESS).

renderpipelinenews / scripts/202608300232-sync-atlas-v9-deep-links.py · lines 1–234 of 234 · version 2026-08-30 02:32 · Entry point · pattern normalise_base (shared by 2 files)

What it does
It loads GridAtlas current, atlas deep link audit, solar and battery storage (BESS). Defines 9 functions or classes, including require, load, normalise_base, mutable_files, rewrite_source. Uses libraries __future__, argparse, json, re, sys. Side effects: changes the web page (DOM); 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: solar, battery storage (BESS).
Inputs & outputs
In: JSON file live-set.json; JSON file gridatlas-v9-current.json; JSON file atlas-v9-current.json; JSON file atlas-v9-deep-link-audit.json; command-line arguments.
Downstream impact
Used directly by 2 files: PipelineNews Sync Atlas V9 Deep Links Workflow (pipelinenews); PipelineNews Bootstrap Five Hour Atlas Integration Workflow (pipelinenews).
What it achieves
It normalises base (`normalise_base`), builds URL (`build_url`) and validates URL (`validate_url`). Synchronise PipelineNews mutable sources to the promoted Atlas V9 deep-link contract. It accepts `--gridatlas`, `--globalgrid` and `--repo-root`.
Why it matters
Run by PipelineNews Sync Atlas V9 Deep Links Workflow and PipelineNews Bootstrap Five Hour Atlas Integration Workflow.
Application
pipelinenews · scripts · Python CLI
Uses
GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL), __future__, argparse, json, re, sys, pathlib, typing, urllib.parse
Used by
run by PipelineNews Sync Atlas V9 Deep Links Workflow (workflow run), run by PipelineNews Bootstrap Five Hour Atlas Integration Workflow (workflow run)
Produces
require, load, normalise_base, mutable_files, rewrite_source, build_url, validate_url, javascript_module, main
Defines here
require, load, normalise_base, mutable_files, rewrite_source, build_url, validate_url, javascript_module, 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 scripts/202608300232-sync-atlas-v9-deep-links.py:1-234 · blob 1a03bf7dd5de7f191fb9b27c065e6dc0b50b19fd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Synchronise PipelineNews mutable sources to the promoted Atlas V9 deep-link contract."""

from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any, Iterable
from urllib.parse import parse_qs, urlencode, urlparse

MIN_RENDER_READY_GENERATION = "202608292311"
VALID_TECHNOLOGIES = {"solar", "bess", "wind_onshore", "wind_offshore"}
TEXT_EXTENSIONS = {".html", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".py", ".json"}
SOURCE_ROOTS = {"ui", "src", "javascript", "templates", "index", "compiler", "app", "public"}
EXCLUDED_ROOTS = {
    ".git", ".github", "node_modules", "vendor", "archive", "archives", "releases",
    "dist", "build", "work", "coverage", "machine-learning", "data", "reports", "state"
}
TIMESTAMPED = re.compile(r"^\d{12}(?:-|$)")
OLD_BASES = (
    "https://globalgrid2050.com/repd_grid_atlasv8/",
    "https://globalgrid2050.com/repd_grid_atlasv8",
    "http://globalgrid2050.com/repd_grid_atlasv8/",
    "http://globalgrid2050.com/repd_grid_atlasv8",
)
OLD_V9 = re.compile(r"https://ventusltd\.github\.io/gridatlas/\d{12}-atlas-v9/?")


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 normalise_base(value: str, release_id: str) -> str:
    parsed = urlparse(value)
    require(parsed.scheme == "https", "Atlas base must use HTTPS")
    require(not parsed.query and not parsed.fragment, "Atlas base must not contain query or fragment data")
    if parsed.netloc == "ventusltd.github.io":
        expected_path = f"/gridatlas/{release_id}/"
    elif parsed.netloc in {"globalgrid2050.com", "www.globalgrid2050.com"}:
        expected_path = f"/{release_id}/"
    else:
        raise RuntimeError("Atlas base must use governed GridAtlas or GlobalGrid2050 hosting")
    require(parsed.path == expected_path, "Atlas base is not the exact immutable V9 route")
    return value.rstrip("/") + "/"


def mutable_files(root: Path) -> Iterable[Path]:
    for path in sorted(root.rglob("*")):
        if not path.is_file() or path.suffix.lower() not in TEXT_EXTENSIONS:
            continue
        relative = path.relative_to(root)
        parts = relative.parts
        if not parts:
            continue
        first = parts[0]
        if first in EXCLUDED_ROOTS or TIMESTAMPED.match(first):
            continue
        if len(parts) > 1 and first not in SOURCE_ROOTS and first != "scripts":
            continue
        if relative.as_posix() == "scripts/202608300232-sync-atlas-v9-deep-links.py":
            continue
        yield path


def rewrite_source(text: str, base_url: str) -> tuple[str, int]:
    replacements = 0
    updated = text
    for old in OLD_BASES:
        count = updated.count(old)
        if count:
            updated = updated.replace(old, base_url)
            replacements += count
    updated, count = OLD_V9.subn(base_url, updated)
    replacements += count
    return updated, replacements


def build_url(base_url: str, repd_ref: str, technology: str, **optional: object) -> str:
    ref = str(repd_ref).strip()
    tech = str(technology).strip()
    require(re.fullmatch(r"[A-Za-z0-9-]{1,40}", ref) is not None, "invalid REPD reference")
    require(tech in VALID_TECHNOLOGIES, "invalid Atlas technology")
    query: dict[str, str] = {"repd_ref": ref, "technology": tech}
    for key in ("name", "longitude", "latitude"):
        value = optional.get(key)
        if value is not None and str(value).strip():
            query[key] = str(value).strip()
    return base_url + "?" + urlencode(query)


def validate_url(url: str, expected_ref: str, expected_technology: str) -> None:
    parsed = urlparse(url)
    query = parse_qs(parsed.query)
    require(query.get("repd_ref") == [expected_ref], f"deep-link REPD identity mismatch: {url}")
    require(query.get("technology") == [expected_technology], f"deep-link technology mismatch: {url}")


def javascript_module(release_id: str, base_url: str) -> str:
    return f"""(() => {{
  'use strict';
  const RELEASE_ID = {json.dumps(release_id)};
  const BASE_URL = {json.dumps(base_url)};
  const TECHNOLOGIES = new Set(['solar', 'bess', 'wind_onshore', 'wind_offshore']);
  const REPD_REF = /^[A-Za-z0-9-]{{1,40}}$/;

  function buildAtlasV9Url(project) {{
    const repdRef = String(project?.repd_ref ?? project?.repdRef ?? '').trim();
    const technology = String(project?.technology ?? '').trim();
    if (!REPD_REF.test(repdRef) || !TECHNOLOGIES.has(technology)) return null;
    const query = new URLSearchParams({{ repd_ref: repdRef, technology }});
    for (const key of ['name', 'longitude', 'latitude']) {{
      const value = project?.[key];
      if (value !== undefined && value !== null && String(value).trim()) query.set(key, String(value).trim());
    }}
    return `${{BASE_URL}}?${{query.toString()}}`;
  }}

  window.GridAtlasV9DeepLinks = Object.freeze({{ releaseId: RELEASE_ID, baseUrl: BASE_URL, build: buildAtlasV9Url }});
}})();
"""


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--gridatlas", required=True, type=Path)
    parser.add_argument("--globalgrid", type=Path)
    parser.add_argument("--repo-root", default=".", type=Path)
    args = parser.parse_args()

    atlas_state = load(args.gridatlas / "state/live-set.json")
    generation = str(atlas_state.get("generation") or "")
    if generation < MIN_RENDER_READY_GENERATION:
        print(json.dumps({"classification": "WAITING_FOR_RENDER_READY_PROMOTION", "generation": generation}, sort_keys=True))
        return 0

    verification = atlas_state.get("verification") or {}
    current = atlas_state.get("current") or {}
    require(verification.get("promotion_eligible") is True, "Atlas current release is not promotion eligible")
    require(int(verification.get("failed_gates", -1)) == 0, "Atlas current release has failed gates")
    require(verification.get("commit_lineage_attested") is True, "Atlas current release lineage is not attested")
    release_id = str(current.get("release_id") or "")
    require(re.fullmatch(r"\d{12}-atlas-v9", release_id) is not None, "invalid Atlas release id")
    base_url = normalise_base(str(current.get("live_url") or ""), release_id)

    globalgrid_mirror_verified = False
    if args.globalgrid:
        pointer_path = args.globalgrid / "state/gridatlas-v9-current.json"
        if pointer_path.is_file():
            global_pointer = load(pointer_path)
            if (
                global_pointer.get("classification") == "MIRRORED_PROMOTED_GRIDATLAS_V9"
                and global_pointer.get("release_id") == release_id
            ):
                normalise_base(str(global_pointer.get("globalgrid_live_url") or ""), release_id)
                globalgrid_mirror_verified = True

    root = args.repo_root.resolve()
    changed_files: list[str] = []
    replacement_count = 0
    for path in mutable_files(root):
        try:
            original = path.read_text(encoding="utf-8")
        except UnicodeDecodeError:
            continue
        updated, replacements = rewrite_source(original, base_url)
        if replacements:
            path.write_text(updated, encoding="utf-8", newline="\n")
            changed_files.append(path.relative_to(root).as_posix())
            replacement_count += replacements

    module_path = root / "ui/atlas-v9-deep-links.js"
    module_path.parent.mkdir(parents=True, exist_ok=True)
    module_path.write_text(javascript_module(release_id, base_url), encoding="utf-8", newline="\n")

    sentinels = [
        {"name": "Beacon Fen", "repd_ref": "13599", "technology": "solar"},
        {"name": "East Pye", "repd_ref": "17494", "technology": "solar"},
    ]
    for sentinel in sentinels:
        sentinel["atlas_v9_url"] = build_url(base_url, sentinel["repd_ref"], sentinel["technology"], name=sentinel["name"])
        validate_url(sentinel["atlas_v9_url"], sentinel["repd_ref"], sentinel["technology"])

    pointer = {
        "schema": "pipelinenews.atlas-v9-pointer.v1",
        "classification": "PROMOTED_ATLAS_V9_DEEP_LINK_SOURCE",
        "generation": generation,
        "release_id": release_id,
        "base_url": base_url,
        "identity": ["repd_ref", "technology"],
        "optional_evidence": ["name", "longitude", "latitude"],
        "name_or_coordinate_identity_permitted": False,
        "source_pointer": "Ventusltd/gridatlas:state/live-set.json",
        "globalgrid_pointer": "Ventusltd/globalgrid2050:state/gridatlas-v9-current.json" if args.globalgrid else None,
        "globalgrid_mirror_verified": globalgrid_mirror_verified,
    }
    pointer_path = root / "state/atlas-v9-current.json"
    pointer_path.parent.mkdir(parents=True, exist_ok=True)
    pointer_path.write_text(json.dumps(pointer, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")

    audit = {
        "schema": "pipelinenews.atlas-v9-deep-link-audit.v1",
        "classification": "CANONICAL_DEEP_LINKS_READY",
        "release_id": release_id,
        "base_url": base_url,
        "files_rewritten": sorted(changed_files),
        "replacement_count": replacement_count,
        "sentinels": sentinels,
        "immutable_releases_modified": 0,
        "globalgrid_mirror_verified": globalgrid_mirror_verified,
        "privacy": "NO_PERSONAL_DATA",
    }
    audit_path = root / "reports/atlas-v9-deep-link-audit.json"
    audit_path.parent.mkdir(parents=True, exist_ok=True)
    audit_path.write_text(json.dumps(audit, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
    print(json.dumps(audit, sort_keys=True))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as error:  # noqa: BLE001
        print(f"PIPELINENEWS_ATLAS_V9_SYNC_FAILED: {error}", file=sys.stderr)
        raise

Verify Atlas Deep Link Contract

A JavaScript module in the intelligence folder of PipelineNews that reads cartridge. It is built from the check step (`check`) and the exists step (`exists`).

ingestpipelinenews / tools/intelligence/202609012300-verify-atlas-deep-link-contract.mjs · lines 1–157 of 157 · version 2026-09-01 23:00 · Not reached from any entry point (candidate for review) · pattern exists (shared by 14 files)

What it does
It loads cartridge. Defines check, exists. Uses libraries node:fs/promises, node:fs, node:path, node:url. Side effects: reads or writes files; starts processes.
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.
Inputs & outputs
In: JSON file cartridge.json; JSON file current.json; command-line arguments.
Downstream impact
Used directly by 1 file: Shift (pipelinenews).
What it achieves
The deep link is a contract, and this is the side of it Pipeline News owns.
Why it matters
Run by Shift.
Application
pipelinenews · tools/intelligence · JavaScript module
Uses
node:fs/promises, node:fs, node:path, node:url
Used by
run by Shift (script call)
Produces
check, exists
Defines here
check, exists
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/intelligence/202609012300-verify-atlas-deep-link-contract.mjs:1-157 · blob 1e647de5f324a192f69941cfd9900f98216ec7c6 · 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: unreached_review
/**
 * The deep link is a contract, and this is the side of it Pipeline News owns.
 *
 * Generation 202609012300. Written because a deep scan of both applications
 * on 1 Sep 2026 compared the two sides for the first time and found this:
 *
 *   Pipeline News set seven parameters on every MAP link.
 *   GridAtlas read six.
 *   `zoom` was set on every link ever generated and read by nobody.
 *
 * It did no visible harm, which is precisely why it survived. GridAtlas's
 * immutable shell hard-codes `map.flyTo({ zoom: 12 })`, and Pipeline News
 * happens to send 12, so arrival looked correct. The two agreed by
 * coincidence. The day somebody tuned DEFAULT_ZOOM here, nothing would have
 * moved on the map and nobody would have found out for a week.
 *
 * A parameter that crosses a repository boundary has two owners and no test.
 * This is that test, from this side.
 *
 *   node tools/intelligence/202609012300-verify-atlas-deep-link-contract.mjs
 *
 * It reads the sibling GridAtlas checkout. If that is absent it FAILS and
 * says how to satisfy it. It does not skip: a cross-repository check that
 * quietly passes when it cannot see the other repository is worse than no
 * check, because it reports green on exactly the isolated checkout where
 * nobody is watching. (That lesson is one generation old and was Codex's.)
 */

import { readFile, readdir, access } from 'node:fs/promises';
import { constants } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = resolve(HERE, '..', '..');
/* WHICH GridAtlas. This matters more than it looks.
   ------------------------------------------------------------------------
   The first run of this check reported that `repd_ref` and `zoom` were read
   by nobody. Both were true — of the sibling checkout, which was sitting at
   generation 202609010106 (v9.39) while the work was happening in a
   worktree. A cross-repository check that does not say WHICH checkout it
   read is a check that reports history as if it were the present.

   So the generation and the path are printed, and --gridatlas points it at
   a worktree or any other checkout. */
const argAt = process.argv.indexOf('--gridatlas');
const SIBLING = argAt > 0
  ? resolve(process.argv[argAt + 1])
  : resolve(REPO, '..', 'gridatlas');

let passed = 0;
const failures = [];
function check(name, condition, detail = '') {
  if (condition) { passed += 1; console.log(`PASS  ${name}`); }
  else { failures.push(`${name}${detail ? `: ${detail}` : ''}`);
    console.error(`FAIL  ${name}${detail ? `: ${detail}` : ''}`); }
}

const exists = async (path) => {
  try { await access(path, constants.R_OK); return true; } catch { return false; }
};

/* ── this side: what the builder sets ──────────────────────────────────── */

const BUILDER = join(REPO, 'tools', 'intelligence', 'cartridges',
  'atlas-live-handoff', 'assets', '{GEN}-atlas-pointer-deep-link.mjs');

check('the deep-link builder is where the cartridge says it is',
  await exists(BUILDER), BUILDER);
const builder = await readFile(BUILDER, 'utf8');

const produced = [...builder.matchAll(/searchParams\.set\(\s*["']([\w_]+)["']/g)]
  .map(match => match[1]);
const producedSet = new Set(produced);
console.log(`\n  Pipeline News sets: ${[...producedSet].sort().join(', ')}`);
check('the builder sets at least the identity and the position',
  ['repd_ref', 'latitude', 'longitude'].every(name => producedSet.has(name)));

/* The cartridge also DECLARES its context parameters. A declaration that
   disagrees with the code is its own defect, and cheap to catch here. */
const cartridge = JSON.parse(await readFile(join(REPO, 'tools', 'intelligence',
  'cartridges', 'atlas-live-handoff', 'cartridge.json'), 'utf8'));
const declared = new Set([...(cartridge.registry_entry?.context_parameters || []),
  cartridge.registry_entry?.identity_rule === 'EXACT_PROJECT_REPD_REF' ? 'repd_ref' : null]
  .filter(Boolean));
const undeclared = [...producedSet].filter(name => !declared.has(name));
const unbuilt = [...declared].filter(name => !producedSet.has(name));
check('every parameter the code sets is declared in cartridge.json',
  undeclared.length === 0, undeclared.join(', '));
check('every parameter cartridge.json declares is actually set',
  unbuilt.length === 0, unbuilt.join(', '));

/* ── the other side: what GridAtlas reads ──────────────────────────────── */

const sibling = await exists(join(SIBLING, '.git')) || await exists(SIBLING);
check('the GridAtlas checkout this contract binds to is available', sibling,
  `not found at ${SIBLING} — clone Ventusltd/gridatlas beside this repository. `
  + 'This check does not skip: a cross-repository contract that passes when it '
  + 'cannot see the other repository is green exactly where nobody is watching.');

if (sibling) {
  /* Read the COMPOSED cartridge, not a source file: the composed bytes are
     what a browser is handed, and the composition names which one. */
  const current = JSON.parse(
    await readFile(join(SIBLING, 'atlas', 'current.json'), 'utf8'));
  const cartridges = current.cartridges || [];
  console.log(`\n  GridAtlas composition ${current.generation} `
    + `(${current.composition_version}), ${cartridges.length} cartridges`);
  console.log(`  read from ${SIBLING}`);
  check('the checkout being read is a composition, not an empty tree',
    Boolean(current.generation) && cartridges.length > 0);

  let readNames = new Set();
  const readIn = new Map();
  for (const entry of cartridges) {
    const file = join(SIBLING, 'atlas', entry.path.replace('./', ''));
    if (!await exists(file)) continue;
    const text = await readFile(file, 'utf8');
    /* Resolve the binding, then read only that variable — the same
       discipline the deep scan had to learn after its first regex reported
       twenty-three parameters that were being read all along. */
    const bound = new Set(
      [...text.matchAll(/(?:const|let|var)\s+(\w+)\s*=\s*new\s+URLSearchParams\s*\(/g)]
        .map(match => match[1]));
    if (!bound.size) continue;
    const reads = new RegExp(`\\b(${[...bound].join('|')})\\.get\\(\\s*["']([\\w_]+)["']`, 'g');
    for (const match of text.matchAll(reads)) {
      readNames.add(match[2]);
      if (!readIn.has(match[2])) readIn.set(match[2], new Set());
      readIn.get(match[2]).add(entry.id);
    }
  }
  console.log(`  GridAtlas reads:    ${[...readNames].sort().join(', ')}`);

  const orphaned = [...producedSet].filter(name => !readNames.has(name));
  check('every parameter Pipeline News sets is read by the composed GridAtlas',
    orphaned.length === 0,
    orphaned.length
      ? `${orphaned.join(', ')} — set on every MAP link and read nowhere. `
        + 'Either GridAtlas should read it or this side should stop sending it; '
        + 'a parameter with two owners and no reader is a promise nobody keeps.'
      : '');

  for (const name of ['repd_ref', 'latitude', 'longitude', 'zoom']) {
    if (!producedSet.has(name)) continue;
    check(`  ${name} is read, by ${[...(readIn.get(name) || ['nobody'])].join(', ')}`,
      readNames.has(name));
  }
}

console.log(`\n${passed}/${passed + failures.length} checks passed`);
if (failures.length) {
  console.error('\nFAILURES');
  for (const failure of failures) console.error(`  ${failure}`);
  process.exit(1);
}
console.log('the deep link is a contract both sides keep.');