In this section
- Prove Pages Promotion Wrapper ingest · pipelinenews / tools/publication/prove_pages_promotion_wrapper.mjs lines 1–172
- Run Pages Candidate Gate storage · pipelinenews / tools/publication/run_pages_candidate_gate.py lines 1–94
- Test Pages Candidate Workflow test · pipelinenews / tools/publication/test_pages_candidate_workflow.py lines 1–30
- Test Pages Promotion Tooling test · pipelinenews / tools/publication/test_pages_promotion_tooling.py lines 1–254
Prove Pages Promotion Wrapper
A JavaScript module in the publication folder of PipelineNews that reads atlas link, using SHA-256.
ingestpipelinenews / tools/publication/prove_pages_promotion_wrapper.mjs · lines 1–172 of 172 · Entry point · pattern identity (shared by 11 files)
- What it does
- It loads atlas link. Defines 6 functions or classes, including sha256, read, json, check, decode. Uses libraries node:child_process, node:crypto, node:fs/promises, node:path, node:url. 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: JSON file release-manifest.json; JSON file build-manifest.json; JSON file atlas-link-manifest.json; JSON file 202608291447-registry.json; JSON file 202608270055-8ab1807551bc-v8-fast-projects.json; JSON file 202609030009-wider-fleet.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: PipelineNews Pages V2 Workflow (pipelinenews). Reached from 1 other entry point, including PipelineNews Pages Workflow (pipelinenews).
- What it achieves
- It is built from the sha256 step (`sha256`), the read step (`read`) and the JSON step (`json`). Prove a Pages promotion wrapper against its exact Grid production receiver.
- Why it matters
- Run by PipelineNews Pages V2 Workflow.
- Application
- pipelinenews · tools/publication · JavaScript module
- Uses
- node:child_process, node:crypto, node:fs/promises, node:path, node:url
- Used by
- run by PipelineNews Pages V2 Workflow (workflow run)
- Produces
- sha256, read, json, check, decode, identity
- Defines here
- sha256, read, json, check, decode, identity
- 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/publication/prove_pages_promotion_wrapper.mjs:1-172 · blob d97360886103f10d23015795c6605a42fa6ac759 · 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 node
/** Prove a Pages promotion wrapper against its exact Grid production receiver. */
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
const repo = resolve(here, "../..");
const releaseId = process.argv[2];
const gridFlag = process.argv.indexOf("--gridatlas");
if (!/^\d{12}-pipelinenews$/u.test(releaseId || "") || gridFlag < 0) {
throw new Error("usage: node prove_pages_promotion_wrapper.mjs <release-id> --gridatlas <checkout>");
}
const grid = resolve(process.argv[gridFlag + 1]);
const release = join(repo, "releases", releaseId);
const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
const read = (relative) => readFile(join(release, relative));
const json = async (relative) => JSON.parse((await read(relative)).toString("utf8"));
let passed = 0;
const failures = [];
const check = (name, ok, detail = "") => {
if (ok) { passed += 1; console.log(`PASS ${name}`); }
else { failures.push(`${name}${detail ? `: ${detail}` : ""}`); }
};
const releaseManifest = await json("release-manifest.json");
const buildManifest = await json("build-manifest.json");
const atlas = await json("atlas-link-manifest.json");
check("release is an explicit Pages promotion wrapper",
releaseManifest.promotion_wrapper?.schema === "pipelinenews.pages-promotion-wrapper.v1"
&& releaseManifest.schema === "pipelinenews.current-atlas-link-release.v2");
check("build and release bind the same promotion source",
JSON.stringify(buildManifest.promotion_wrapper) === JSON.stringify(releaseManifest.promotion_wrapper));
const receiver = atlas.receiver;
check("wrapper carries a production receiver contract",
receiver?.schema === "pipelinenews.gridatlas-production-receiver.v1"
&& receiver.repository === "Ventusltd/gridatlas");
check("all manifests bind the same receiver",
JSON.stringify(buildManifest.receiver) === JSON.stringify(receiver)
&& releaseManifest.atlas_receiver_commit === receiver.commit
&& releaseManifest.atlas_receiver_version === receiver.version);
for (const [label, record] of Object.entries({
"measurement cartridge": receiver.measurement_cartridge,
"engine cartridge": receiver.engine_cartridge,
"composition manifest": receiver.composition_manifest,
"production proof": receiver.production_proof,
})) {
const payload = await readFile(join(grid, record.path));
check(`pinned Grid ${label} bytes match`,
payload.length === record.bytes && sha256(payload) === record.sha256,
`${payload.length} ${sha256(payload)}`);
}
const gridHead = execFileSync("git", ["-C", grid, "rev-parse", "HEAD"], { encoding: "utf8" }).trim();
check("Grid checkout is the exact wrapper-bound commit", gridHead === receiver.commit, gridHead);
const registry = await json("data/202608291447-registry.json");
const entry = registry.supplemental_assets?.map_corpus_contract;
check("wrapper retains the source MAP corpus registry entry", Boolean(entry));
const app = (await read("assets/202608291447-app.mjs")).toString("utf8");
const senderName = app.match(
/^import \{ buildAtlasV9DeepLink \} from "\.\/(\d{12}-atlas-pointer-deep-link\.mjs)";/mu
)?.[1];
check("wrapper runtime imports one canonical sender", Boolean(senderName));
if (!entry || !senderName) throw new Error("wrapper MAP wiring is incomplete");
const sender = await import(pathToFileURL(join(release, "assets", senderName)).href);
const wider = await import(pathToFileURL(join(release, entry.cartridge.path)).href);
check("sender self-test passes", sender.selfTest().ok);
const compact = await json("data/202608270055-8ab1807551bc-v8-fast-projects.json");
const decode = (row) => Object.fromEntries(compact.fields.map((field, index) => {
const value = row[index];
return [field, compact.dictionaries[field] ? (compact.dictionaries[field][value] ?? "") : value];
}));
const spine = compact.rows.map(decode).filter((row) => row.geometry_status === "valid");
const sourceWider = await json("data/202609030009-wider-fleet.json");
const outputWider = await json(entry.payload.path);
const corpus = [
...spine.map((project) => ({ lane: "spine", project })),
...sourceWider.map((row) => ({ lane: "wider", project: {
repd_ref: row.ref || "", name: row.n, technology: row.t, capacity_mw: row.c,
longitude: row.ll?.[0], latitude: row.ll?.[1], geometry_status: "valid",
} })),
];
check("complete source population is derived", spine.length === 7652
&& sourceWider.length === 1104 && corpus.length === 8756);
const parameterOrder = [
"repd_ref", "project", "technology", "capacity_mw", "latitude", "longitude", "zoom",
];
const canonical = new Set(sender.CANONICAL_PROJECT_TECHNOLOGIES);
let clickable = 0;
let unresolved = 0;
let malformed = 0;
const refs = [];
for (const { project } of corpus) {
const ref = String(project.repd_ref ?? "").trim();
const href = sender.buildAtlasV9DeepLink(project);
if (!ref) {
unresolved += 1;
if (href) malformed += 1;
continue;
}
clickable += 1;
try {
const url = new URL(href);
const ok = url.origin === "https://ventusltd.github.io"
&& url.pathname === "/gridatlas/atlas/"
&& [...url.searchParams.keys()].join(",") === parameterOrder.join(",")
&& parameterOrder.every((name) => url.searchParams.getAll(name).length === 1)
&& url.searchParams.get("repd_ref") === ref
&& canonical.has(url.searchParams.get("technology"))
&& Number.isFinite(Number(url.searchParams.get("latitude")))
&& Number.isFinite(Number(url.searchParams.get("longitude")));
if (!ok) malformed += 1;
refs.push(ref);
} catch { malformed += 1; }
}
check("all exact identities emit canonical seven-parameter MAP URLs",
clickable === 8743 && malformed === 0, `${clickable} clickable, ${malformed} malformed`);
check("unresolved source rows fail closed", unresolved === 13, String(unresolved));
check("clickable identities remain unique", new Set(refs).size === refs.length,
`${refs.length - new Set(refs).size} duplicates`);
const identity = (row) => JSON.stringify([row.n, row.rt, row.c, row.ll]);
const sourceRefs = sourceWider.flatMap((row) => row.ref ? [String(row.ref)] : []).sort();
const outputRefs = outputWider.flatMap((row) => Array.isArray(row.repd_records)
? row.repd_records.map(({ ref }) => String(ref)) : (row.ref ? [String(row.ref)] : [])).sort();
check("three wider display duplicates collapse without reference loss",
outputWider.length === 1101
&& new Set(outputWider.map(identity)).size === 1101
&& JSON.stringify(sourceRefs) === JSON.stringify(outputRefs));
check("the active wider runtime exposes all retained MAP actions",
outputWider.flatMap((row) => wider.mapLinksForRow(row)).length === 1091);
const measurementSource = (await readFile(join(grid, receiver.measurement_cartridge.path))).toString("utf8");
const engineSource = (await readFile(join(grid, receiver.engine_cartridge.path))).toString("utf8");
check("production receiver reads every canonical URL input",
["longitude", "latitude", "repd_ref", "technology", "project", "capacity_mw", "zoom"]
.every((name) => measurementSource.includes(`q.get('${name}')`)
|| engineSource.includes(`params.get('${name}')`)));
const allowed = engineSource.match(/const allowedTechnologies = new Set\(\[([\s\S]*?)\]\);/u)?.[1] || "";
const accepted = new Set([...allowed.matchAll(/'([^']+)'/gu)].map((match) => match[1]));
const rejected = [...canonical].filter((technology) => !accepted.has(technology));
check("production engine accepts every sender technology", rejected.length === 0, rejected.join(", "));
try {
const output = execFileSync(process.execPath, [join(grid, receiver.production_proof.path)], {
cwd: grid,
env: { ...process.env, PIPELINENEWS_REPO: repo },
encoding: "utf8",
maxBuffer: 8 * 1024 * 1024,
});
check("exact Grid production proof is wholly green", /(\d+)\/\1 checks passed/u.test(output));
check("Grid production dispatches all 8,756 points measure-first",
/every published point takes the product receiver's measure-first route[^\n]*8756\/8756/u.test(output));
check("Grid production closes the Markinch acceptance fixture",
/Markinch ref 155[^\n]*\[PASS\]|\[PASS\][^\n]*Markinch ref 155/u.test(output));
} catch (error) {
failures.push(`exact Grid production proof failed: ${error.stdout || error.stderr || error}`);
}
console.log(`\n${passed}/${passed + failures.length} checks passed`);
console.log(JSON.stringify({ source_rows: corpus.length, clickable_rows: clickable,
unresolved_rows: unresolved, receiver_commit: receiver.commit, receiver_version: receiver.version }));
if (failures.length) {
console.error("\nFAILURES");
failures.forEach((failure) => console.error(` ${failure}`));
process.exit(1);
}Run Pages Candidate Gate
A Python command-line tool in the publication folder of PipelineNews that runs the complete Pages routing gate serially and write a durable receipt, using SHA-256.
storagepipelinenews / tools/publication/run_pages_candidate_gate.py · lines 1–94 of 94 · Entry point · pattern atomic_json (shared by 2 files)
- What it does
- Defines execute, atomic_json, main. Uses libraries __future__, argparse, hashlib, json, re. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'gate'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- In: command-line arguments. Out: JSON file.
- Downstream impact
- Used directly by 2 files: Build 30x Ledger (pipelinenews); PipelineNews Pages Routing Candidate Workflow (pipelinenews).
- What it achieves
- Defines `execute` and `atomic_json`. It accepts `--repo` and `--receipt`.
- Why it matters
- Run by Build 30x Ledger and PipelineNews Pages Routing Candidate Workflow.
- Application
- pipelinenews · tools/publication · Python CLI
- Uses
- Pages Release Classifier (import), Test Pages Release Classifier (script call), Test Release Builder Applicability (script call), Test Verify Pages Workflow (script call), Test Pages Candidate Workflow (script call), Release Builder (script call), __future__, argparse, hashlib, json, re, subprocess, sys, tempfile
- Used by
- run by Build 30x Ledger (script call), run by PipelineNews Pages Routing Candidate Workflow (workflow run)
- Produces
- execute, atomic_json, main
- Defines here
- execute, atomic_json, 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 tools/publication/run_pages_candidate_gate.py:1-94 · blob 921d20a655cc8c68c513c74194617d61873cd9b3 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
#!/usr/bin/env python3
"""Run the complete Pages routing gate serially and write a durable receipt."""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import subprocess
import sys
import tempfile
from dataclasses import asdict
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from pages_release_classifier import classify_release
RELEASE_RE = re.compile(r"^[0-9]{12}-pipelinenews$")
def execute(repo: Path, command: list[str]) -> dict[str, object]:
process = subprocess.run(command, cwd=repo, check=False, capture_output=True)
sys.stdout.buffer.write(process.stdout)
sys.stderr.buffer.write(process.stderr)
combined = process.stdout + process.stderr
return {
"command": command,
"returncode": process.returncode,
"output_bytes": len(combined),
"output_sha256": hashlib.sha256(combined).hexdigest(),
}
def atomic_json(path: Path, payload: dict[str, object]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
"w", encoding="utf-8", newline="\n", dir=path.parent, delete=False
) as stream:
json.dump(payload, stream, indent=2, sort_keys=True)
stream.write("\n")
temporary = Path(stream.name)
temporary.replace(path)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parents[2])
parser.add_argument("--receipt", type=Path, required=True)
args = parser.parse_args(argv)
repo = args.repo.resolve()
releases = sorted(
path.name for path in (repo / "releases").iterdir()
if path.is_dir() and RELEASE_RE.fullmatch(path.name)
)
if not releases:
raise SystemExit("no timestamp release exists")
latest = releases[-1]
decision = classify_release(repo, latest)
python = sys.executable
commands = [
[python, "tools/publication/test_pages_release_classifier.py"],
[python, "tools/publication/test_release_builder_applicability.py"],
[python, "tools/publication/test_verify_pages_workflow.py"],
[python, "tools/publication/test_pages_candidate_workflow.py"],
[python, "tools/publication/pages_release_classifier.py", "--repo", ".", "--release", latest],
[python, "tools/publication/pages_release_classifier.py", "--repo", ".", "--live-pointer"],
]
if decision.route == "source-only":
commands.append([python, "tools/intelligence/release_builder.py", "--check", latest])
results = []
for command in commands:
result = execute(repo, command)
results.append(result)
if result["returncode"] != 0:
break
head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
passed = len(results) == len(commands) and all(item["returncode"] == 0 for item in results)
receipt = {
"schema": "pipelinenews.pages-candidate-gate.v1",
"head": head,
"latest_release": latest,
"classification": asdict(decision),
"commands": results,
"passed": passed,
}
atomic_json(args.receipt, receipt)
print(json.dumps({"passed": passed, "receipt": str(args.receipt), "head": head}, sort_keys=True))
return 0 if passed else 1
if __name__ == "__main__":
raise SystemExit(main())Test Pages Candidate Workflow
A test in the publication folder of PipelineNews. It is built from the candidate workflow tests class (`CandidateWorkflowTests`).
testpipelinenews / tools/publication/test_pages_candidate_workflow.py · lines 1–30 of 30 · Entry point
- What it does
- It tests its inputs. Defines CandidateWorkflowTests, test_candidate_has_compute_without_publish_authority. Uses libraries __future__, unittest, pathlib. Side effects: reads or writes files.
- 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.
- Downstream impact
- Used directly by 1 file: Run Pages Candidate Gate (pipelinenews). Reached from 2 other entry points, including PipelineNews Pages Routing Candidate Workflow (pipelinenews); Build 30x Ledger (pipelinenews).
- What it achieves
- Defines `CandidateWorkflowTests` and `test_candidate_has_compute_without_publish_authority`.
- Why it matters
- Run by Run Pages Candidate Gate.
- Application
- pipelinenews · tools/publication · test
- Uses
- __future__, unittest, pathlib
- Used by
- run by Run Pages Candidate Gate (script call)
- Produces
- CandidateWorkflowTests
- Defines here
- CandidateWorkflowTests, test_candidate_has_compute_without_publish_authority
- 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/publication/test_pages_candidate_workflow.py:1-30 · blob 91cacdaa462144c9c6ae9a8a9b2b51014d999a0d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import unittest
from pathlib import Path
class CandidateWorkflowTests(unittest.TestCase):
def test_candidate_has_compute_without_publish_authority(self) -> None:
path = Path(__file__).resolve().parents[2] / ".github" / "workflows" / "202609040100-pages-routing-candidate.yml"
source = path.read_text(encoding="utf-8")
trigger = source.split("\npermissions:\n", 1)[0]
permissions = source.split("\npermissions:\n", 1)[1].split("\nconcurrency:\n", 1)[0]
self.assertIn("workflow_dispatch:", trigger)
self.assertIn("pull_request:", trigger)
self.assertIn("push:", trigger)
push = trigger.split(" push:\n", 1)[1].split(" pull_request:\n", 1)[0]
self.assertIn("branches:\n - main", push)
self.assertIn(".github/workflows/202609040100-pages-routing-candidate.yml", push)
self.assertIn("tools/publication/**", push)
self.assertNotIn("schedule:", trigger)
self.assertEqual(permissions.strip(), "contents: read")
self.assertIn("cancel-in-progress: true", source)
self.assertIn("run_pages_candidate_gate.py", source)
self.assertIn("actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02", source)
self.assertNotIn("actions/deploy-pages", source)
if __name__ == "__main__":
unittest.main()Test Pages Promotion Tooling
A test in the publication folder of PipelineNews that checks Build Pages Promotion Wrapper and Build Pages, using SHA-256. It is built from the promotion tooling tests class (`PromotionToolingTests`).
testpipelinenews / tools/publication/test_pages_promotion_tooling.py · lines 1–254 of 254 · Entry point
- What it does
- It tests its inputs. Defines 16 functions or classes, including PromotionToolingTests, test_exact_source_closure_is_available_without_mutation, test_receiver_builder_fails_closed_on_wrong_digest, test_wrapper_builder_requires_clean_pipeline_checkout, test_receiver_builder_fails_closed_on_wrong_head. Uses libraries __future__, json, importlib.util, pathlib, subprocess. 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: JSON file release-manifest.json; JSON file current.json. Out: JSON file 202601010000-composition.json; JSON file current.json; JSON file release-manifest.json.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Defines `PromotionToolingTests`, `test_exact_source_closure_is_available_without_mutation`, `test_receiver_builder_fails_closed_on_wrong_digest` and 13 more.
- Why it matters
- Guards the behaviour of Build Pages Promotion Wrapper and Build Pages.
- Application
- pipelinenews · tools/publication · test
- Uses
- Build Pages Promotion Wrapper (import), Build Pages (script call), __future__, json, importlib.util, pathlib, subprocess, tempfile, unittest
- Used by
- none found
- Produces
- PromotionToolingTests
- Defines here
- PromotionToolingTests, test_exact_source_closure_is_available_without_mutation, test_receiver_builder_fails_closed_on_wrong_digest, test_wrapper_builder_requires_clean_pipeline_checkout, test_receiver_builder_fails_closed_on_wrong_head, test_source_builder_fails_closed_on_wrong_commit, test_workflow_uses_read_only_exact_receiver_checkout, test_workflow_checks_out_pinned_geodesy_beside_grid_before_proof, test_javascript_proofs_parse, test_browser_readback_binds_public_receiver_bytes_and_identity, test_modular_browser_proof_intercepts_immutable_news_payload, test_pointer_source_manifest_receipt_fails_closed, test_main_dispatch_reaches_promotion_pointer_validator, test_pages_stage_excludes_non_deploying_promotion_source_tree, test_non_deploying_source_exclusion_is_independent_of_selected_release, test_promotion_public_diff_starts_after_immutable_source
- 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/publication/test_pages_promotion_tooling.py:1-254 · blob 99b98017a4da624c44366fa771373bfc893e67e8 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import json
import importlib.util
from pathlib import Path
import subprocess
import tempfile
import unittest
import build_pages_promotion_wrapper as wrapper
ROOT = Path(__file__).resolve().parents[2]
SOURCE_RELEASE = "202609040044-pipelinenews"
SOURCE_COMMIT = "20514b74172eef5748df6adf2b21bde942ce82ed"
ATMAN_SPEC = importlib.util.spec_from_file_location(
"pages_build_gate", ROOT / "atman/202608262014-build-pages.py"
)
assert ATMAN_SPEC is not None and ATMAN_SPEC.loader is not None
pages_gate = importlib.util.module_from_spec(ATMAN_SPEC)
ATMAN_SPEC.loader.exec_module(pages_gate)
class PromotionToolingTests(unittest.TestCase):
def test_exact_source_closure_is_available_without_mutation(self) -> None:
files = wrapper.verify_source_release(ROOT, SOURCE_RELEASE, SOURCE_COMMIT)
self.assertGreater(len(files), 60)
self.assertIn("release-manifest.json", files)
self.assertIn("assets/202609040044-atlas-pointer-deep-link.mjs", files)
def test_receiver_builder_fails_closed_on_wrong_digest(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
repo = Path(temporary)
(repo / "atlas/cartridges").mkdir(parents=True)
(repo / "atlas/manifests").mkdir(parents=True)
(repo / "tools/proofs").mkdir(parents=True)
(repo / "atlas/cartridges/202601010000-sld.js").write_text("sld\n")
(repo / "atlas/cartridges/202601010000-engine.js").write_text("engine\n")
(repo / "atlas/manifests/202601010000-composition.json").write_text("{}\n")
(repo / "tools/proofs/202601010000-sld-sandbox.proof.mjs").write_text("// proof\n")
current = {
"schema": "gridatlas.current.v2",
"generation": "202601010000",
"cartridges": [
{"id": "sld-sandbox", "generation": "202601010000", "version": "v9.1",
"path": "./cartridges/202601010000-sld.js", "sha256": "0" * 64},
{"id": "substation-intelligence", "generation": "202601010000", "version": "v9.1",
"path": "./cartridges/202601010000-engine.js", "sha256": "0" * 64},
],
}
(repo / "atlas/current.json").write_text(json.dumps(current) + "\n")
subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
subprocess.run(["git", "config", "user.email", "test@example.invalid"], cwd=repo, check=True)
subprocess.run(["git", "config", "user.name", "test"], cwd=repo, check=True)
subprocess.run(["git", "add", "."], cwd=repo, check=True)
subprocess.run(["git", "commit", "-qm", "fixture"], cwd=repo, check=True)
head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
with self.assertRaisesRegex(AssertionError, "current digest changed"):
wrapper.receiver_contract(repo, head)
def test_wrapper_builder_requires_clean_pipeline_checkout(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
repo = Path(temporary)
subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
subprocess.run(["git", "config", "user.email", "test@example.invalid"], cwd=repo, check=True)
subprocess.run(["git", "config", "user.name", "test"], cwd=repo, check=True)
fixture = repo / "fixture.txt"
fixture.write_text("clean\n")
subprocess.run(["git", "add", "."], cwd=repo, check=True)
subprocess.run(["git", "commit", "-qm", "fixture"], cwd=repo, check=True)
wrapper.require_clean_checkout(repo, "Pipeline validator")
fixture.write_text("dirty\n")
with self.assertRaisesRegex(AssertionError, "Pipeline validator checkout is dirty"):
wrapper.require_clean_checkout(repo, "Pipeline validator")
def test_receiver_builder_fails_closed_on_wrong_head(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
repo = Path(temporary)
subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
subprocess.run(["git", "config", "user.email", "test@example.invalid"], cwd=repo, check=True)
subprocess.run(["git", "config", "user.name", "test"], cwd=repo, check=True)
(repo / "fixture.txt").write_text("fixture\n")
subprocess.run(["git", "add", "."], cwd=repo, check=True)
subprocess.run(["git", "commit", "-qm", "fixture"], cwd=repo, check=True)
with self.assertRaisesRegex(AssertionError, "not exact commit"):
wrapper.receiver_contract(repo, "0" * 40)
def test_source_builder_fails_closed_on_wrong_commit(self) -> None:
with self.assertRaises(subprocess.CalledProcessError):
wrapper.verify_source_release(ROOT, SOURCE_RELEASE, "0" * 40)
def test_workflow_uses_read_only_exact_receiver_checkout(self) -> None:
source = (ROOT / ".github/workflows/202608301214-pages-v2.yml").read_text()
self.assertIn("steps.promotion.outputs.receiver_commit", source)
self.assertIn("repository: Ventusltd/gridatlas", source)
self.assertIn("prove_pages_promotion_wrapper.mjs", source)
self.assertIn(".promotion_wrapper.schema // empty", source)
self.assertIn("if test -z \"$promotion_schema\"; then exit 0; fi", source)
self.assertLess(
source.index("Validate committed products and stage public closure"),
source.index("Prove the complete MAP corpus against production receiver bytes"),
)
receiver_step = source.split("Checkout the exact Grid production receiver read-only", 1)[1]
receiver_step = receiver_step.split("Prove the complete MAP corpus", 1)[0]
self.assertIn("persist-credentials: false", receiver_step)
def test_workflow_checks_out_pinned_geodesy_beside_grid_before_proof(self) -> None:
source = (ROOT / ".github/workflows/202608301214-pages-v2.yml").read_text()
grid_step = "Checkout the exact Grid production receiver read-only"
geodesy_step = "Checkout the exact canonical geodesy read-only"
proof_step = "Prove the complete MAP corpus against production receiver bytes"
self.assertLess(source.index(grid_step), source.index(geodesy_step))
self.assertLess(source.index(geodesy_step), source.index(proof_step))
checkout = source.split(geodesy_step, 1)[1].split(
"Validate committed products and stage public closure", 1
)[0]
self.assertIn(
"uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09",
checkout,
)
self.assertIn("repository: Ventusltd/grid-distance-maths", checkout)
self.assertIn("ref: 30d2f817a4b007b7c3be334f3aff308331a848b8", checkout)
self.assertIn("path: _receiver/grid-distance-maths", checkout)
self.assertIn("persist-credentials: false", checkout)
def test_javascript_proofs_parse(self) -> None:
for relative in (
"tools/publication/prove_pages_promotion_wrapper.mjs",
"atman/pages-promotion-wrapper-readback.mjs",
):
subprocess.run(["node", "--check", relative], cwd=ROOT, check=True)
def test_browser_readback_binds_public_receiver_bytes_and_identity(self) -> None:
source = (ROOT / "atman/pages-promotion-wrapper-readback.mjs").read_text()
self.assertIn("new URL('current.json', receiver.base_url)", source)
self.assertIn("digest !== record.sha256", source)
self.assertIn("['VERIFIED', 'RECOMPUTED'].includes", source)
self.assertIn("identity_verification?.repd_ref || ''", source)
self.assertIn("atlasState.links_drawn <= 0", source)
self.assertIn("atlasState.last_selection?.count !== atlasState.links_drawn", source)
self.assertIn("km straight", source)
self.assertIn("Network.emulateNetworkConditions", source)
self.assertIn("connectionType: 'cellular4g'", source)
self.assertIn("timeout: 600000", source)
self.assertIn("probe.searchParams.set('technology', 'Biomass (dedicated)')", source)
self.assertIn("pipeline.matching_action_count !== 1", source)
self.assertIn("pipeline.wider_technology !== 'Biomass (dedicated)'", source)
self.assertIn("error?.stack || error?.message", source)
def test_modular_browser_proof_intercepts_immutable_news_payload(self) -> None:
source = (ROOT / "atman/202608262014-browser-proof.mjs").read_text()
route = '"**/data/news/*-major-project-news-v9-5-1.json*"'
interception = (
'assert.equal(failedNewsRequests, 1, '
'"expected to intercept exactly one immutable news payload request")'
)
unavailable = (
'assert.match(await failClosed.locator("#stories").innerText(), '
'/unavailable|No location-verified|No headlines match/i)'
)
self.assertIn(route, source)
self.assertNotIn("${generation}-major-project-news-v9-5-1.json", source)
self.assertIn("failedNewsRequests += 1", source)
self.assertLess(source.index(route), source.index(interception))
self.assertLess(source.index(interception), source.index(unavailable))
def test_pointer_source_manifest_receipt_fails_closed(self) -> None:
manifest_receipt = {
"path": f"releases/{SOURCE_RELEASE}/release-manifest.json",
"bytes": 123,
"sha256": "a" * 64,
}
timestamp_folder = {
"source_release_id": SOURCE_RELEASE,
"source_commit": SOURCE_COMMIT,
"manifest": {"promotion_wrapper": {
"source_release_manifest": manifest_receipt,
}},
}
pointer = {"promotion_source": {
"release_id": SOURCE_RELEASE,
"commit": SOURCE_COMMIT,
"manifest": manifest_receipt,
}}
pages_gate.validate_pages_promotion_source_pointer(pointer, timestamp_folder)
pointer["promotion_source"]["manifest"] = {
**manifest_receipt, "sha256": "b" * 64,
}
with self.assertRaisesRegex(AssertionError, "source receipt changed"):
pages_gate.validate_pages_promotion_source_pointer(pointer, timestamp_folder)
def test_main_dispatch_reaches_promotion_pointer_validator(self) -> None:
source = (ROOT / "atman/202608262014-build-pages.py").read_text()
self.assertIn(
'"current-atlas-link-v2", "pages-promotion-wrapper-v1",',
source,
)
def test_pages_stage_excludes_non_deploying_promotion_source_tree(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
source = root / "source"
target = root / "target"
(source / "kept").mkdir(parents=True)
(source / "not-authorised/nested").mkdir(parents=True)
(source / "kept/index.html").write_text("kept\n")
(source / "not-authorised/nested/index.html").write_text("excluded\n")
pages_gate.copy_release_tree(
source,
target,
set(),
{"releases/not-authorised"},
)
self.assertTrue((target / "kept/index.html").is_file())
self.assertFalse((target / "not-authorised").exists())
def test_non_deploying_source_exclusion_is_independent_of_selected_release(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
release_id = "202601010000-pipelinenews"
source = root / "releases" / release_id
source.mkdir(parents=True)
(source / "release-manifest.json").write_text(json.dumps({
"schema": "pipelinenews.additive-cartridge-release.v1",
"release_id": release_id,
"deployment": "not-authorised",
}))
self.assertEqual(
pages_gate.nondeploying_release_trees(root),
{f"releases/{release_id}"},
)
manifest = json.loads((source / "release-manifest.json").read_text())
manifest["deployment"] = "candidate"
(source / "release-manifest.json").write_text(json.dumps(manifest))
with self.assertRaisesRegex(AssertionError, "gained direct Pages authority"):
pages_gate.nondeploying_release_trees(root)
def test_promotion_public_diff_starts_after_immutable_source(self) -> None:
release = {"timestamp_folder": {
"kind": "pages-promotion-wrapper-v1",
"source_commit": SOURCE_COMMIT,
}}
self.assertEqual(pages_gate.pages_public_change_base(release), SOURCE_COMMIT)
self.assertEqual(pages_gate.pages_public_change_base({}), pages_gate.ATLAS_V9_SOURCE_PARENT)
release["timestamp_folder"]["source_commit"] = "not-a-commit"
with self.assertRaisesRegex(AssertionError, "public-diff source changed"):
pages_gate.pages_public_change_base(release)
if __name__ == "__main__":
unittest.main()