GLOBALGRID2050 / EXPLORE CODE

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

Test Pages Release Classifier and 1 more file

A test in the publication folder of PipelineNews that checks Pages Release Classifier, using SHA-256.

617 lines of Python from pipelinenews, in 2 files. Topic: Electricity markets and data pipelines. Section 1057 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. Test Pages Release Classifier test · pipelinenews / tools/publication/test_pages_release_classifier.py lines 1–329
  2. Test Register Refresh test · pipelinenews / tools/publication/test_register_refresh.py lines 1–288

Test Pages Release Classifier

A test in the publication folder of PipelineNews that checks Pages Release Classifier, using SHA-256.

testpipelinenews / tools/publication/test_pages_release_classifier.py · lines 1–329 of 329 · Entry point · pattern manifest (shared by 9 files)

What it does
It tests its inputs. Defines 31 functions or classes, including ClassifierTests, setUp, tearDown, manifest, test_routes_pages_release. Uses libraries __future__, json, sys, subprocess, tempfile. 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 classification.json; JSON file live-set.json. Out: JSON file release-manifest.json; JSON file live-set.json; JSON file current-v3.json; JSON file current-v4.json.
Downstream impact
Used directly by 2 files: Build 30x Ledger (pipelinenews); Run Pages Candidate Gate (pipelinenews). Reached from 1 other entry point, including PipelineNews Pages Routing Candidate Workflow (pipelinenews).
What it achieves
It sets up (`setUp`) and is built from the classifier tests class (`ClassifierTests`) and the tear down helper (`tearDown`). Defines `ClassifierTests`, `setUp`, `tearDown` and 28 more.
Why it matters
Run by Build 30x Ledger and Run Pages Candidate Gate.
Application
pipelinenews · tools/publication · test
Uses
Pages Release Classifier (import), __future__, json, sys, subprocess, tempfile, unittest, unittest.mock, pathlib
Used by
run by Build 30x Ledger (script call), run by Run Pages Candidate Gate (script call)
Produces
ClassifierTests
Defines here
ClassifierTests, setUp, tearDown, manifest, test_routes_pages_release, test_routes_additive_release_to_source_validation, test_unknown_schema_fails_closed, test_release_id_cannot_escape_release_root, test_manifest_identity_must_match_directory, test_generation_must_match_release_id, test_duplicate_manifest_keys_fail_closed, test_additive_release_cannot_claim_deployment_authority, test_modern_release_must_be_immutable, test_additive_parent_must_be_valid_and_older, test_additive_parent_must_exist, test_oversized_manifest_fails_before_parsing, test_decision_receipts_exact_manifest_bytes, test_github_outputs_are_scalar_and_job_ready, test_receipt_replace_is_complete_json, test_current_committed_additive_release_classifies, test_release_paths_are_deduplicated_and_sorted, test_discovers_release_from_git_commit_range, test_git_range_with_two_releases_is_ambiguous, test_git_range_rejects_immutable_release_edits, test_abbreviated_commit_is_rejected, test_resolves_the_committed_live_pointer, pointer_bytes, test_live_pointer_rejects_a_stale_manifest_digest, test_live_pointer_rejects_two_identical_current_files, test_zero_release_diff_can_resolve_the_live_pointer
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_release_classifier.py:1-329 · blob cb77f87520cc8b9a60620e6353534d5485570fc5 · 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 sys
import subprocess
import tempfile
import unittest
from unittest.mock import patch
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

from pages_release_classifier import (
    ClassificationError,
    classify_release,
    discover_release,
    release_ids_from_paths,
    require_commit,
    resolve_live_pointer,
    write_github_output,
    write_receipt,
)


class ClassifierTests(unittest.TestCase):
    def setUp(self) -> None:
        self.temp = tempfile.TemporaryDirectory()
        self.repo = Path(self.temp.name)

    def tearDown(self) -> None:
        self.temp.cleanup()

    def manifest(self, folder_id: str, **values: object) -> None:
        root = self.repo / "releases" / folder_id
        root.mkdir(parents=True)
        values.setdefault("release_id", folder_id)
        values.setdefault("generation", folder_id[:12])
        if values.get("schema") == "pipelinenews.additive-cartridge-release.v1":
            values.setdefault("deployment", "not-authorised")
            values.setdefault("parent_release_id", "202608291447-pipelinenews")
            parent_id = str(values["parent_release_id"])
            if parent_id < folder_id:
                parent_root = self.repo / "releases" / parent_id
                parent_root.mkdir(parents=True, exist_ok=True)
                parent_path = parent_root / "release-manifest.json"
                if not parent_path.exists():
                    parent_path.write_text(
                        json.dumps(
                            {
                                "release_id": parent_id,
                                "generation": parent_id[:12],
                                "schema": "pipelinenews.timestamp-folder-successor.v1",
                            }
                        ),
                        encoding="utf-8",
                    )
        if values.get("schema") != "pipelinenews.timestamp-folder-successor.v1":
            values.setdefault("immutable_after_publication", True)
        (root / "release-manifest.json").write_text(json.dumps(values), encoding="utf-8")

    def test_routes_pages_release(self) -> None:
        self.manifest("202608291447-pipelinenews", schema="pipelinenews.timestamp-folder-successor.v1")
        decision = classify_release(self.repo, "202608291447-pipelinenews")
        self.assertEqual(decision.route, "pages")

    def test_routes_additive_release_to_source_validation(self) -> None:
        self.manifest("202609032251-pipelinenews", schema="pipelinenews.additive-cartridge-release.v1")
        decision = classify_release(self.repo, "202609032251-pipelinenews")
        self.assertEqual(decision.route, "source-only")

    def test_unknown_schema_fails_closed(self) -> None:
        self.manifest("202609032252-pipelinenews", schema="invented")
        with self.assertRaises(ClassificationError):
            classify_release(self.repo, "202609032252-pipelinenews")

    def test_release_id_cannot_escape_release_root(self) -> None:
        with self.assertRaises(ClassificationError):
            classify_release(self.repo, "../../outside")

    def test_manifest_identity_must_match_directory(self) -> None:
        release_id = "202609032253-pipelinenews"
        self.manifest(release_id, release_id="202609032254-pipelinenews", schema="pipelinenews.additive-cartridge-release.v1")
        with self.assertRaises(ClassificationError):
            classify_release(self.repo, release_id)

    def test_generation_must_match_release_id(self) -> None:
        release_id = "202609032255-pipelinenews"
        self.manifest(release_id, generation="202609032254", schema="pipelinenews.additive-cartridge-release.v1")
        with self.assertRaises(ClassificationError):
            classify_release(self.repo, release_id)

    def test_duplicate_manifest_keys_fail_closed(self) -> None:
        release_id = "202609032256-pipelinenews"
        root = self.repo / "releases" / release_id
        root.mkdir(parents=True)
        (root / "release-manifest.json").write_text(
            '{"release_id":"%s","generation":"202609032256",'
            '"schema":"pipelinenews.additive-cartridge-release.v1","schema":"invented"}' % release_id,
            encoding="utf-8",
        )
        with self.assertRaises(ClassificationError):
            classify_release(self.repo, release_id)

    def test_additive_release_cannot_claim_deployment_authority(self) -> None:
        release_id = "202609032257-pipelinenews"
        self.manifest(
            release_id,
            schema="pipelinenews.additive-cartridge-release.v1",
            deployment="authorised",
        )
        with self.assertRaises(ClassificationError):
            classify_release(self.repo, release_id)

    def test_modern_release_must_be_immutable(self) -> None:
        release_id = "202609032258-pipelinenews"
        self.manifest(
            release_id,
            schema="pipelinenews.additive-cartridge-release.v1",
            immutable_after_publication=False,
        )
        with self.assertRaises(ClassificationError):
            classify_release(self.repo, release_id)

    def test_additive_parent_must_be_valid_and_older(self) -> None:
        release_id = "202609032259-pipelinenews"
        self.manifest(
            release_id,
            schema="pipelinenews.additive-cartridge-release.v1",
            parent_release_id=release_id,
        )
        with self.assertRaises(ClassificationError):
            classify_release(self.repo, release_id)

    def test_additive_parent_must_exist(self) -> None:
        release_id = "202609032300-pipelinenews"
        self.manifest(release_id, schema="pipelinenews.additive-cartridge-release.v1")
        parent = self.repo / "releases" / "202608291447-pipelinenews"
        (parent / "release-manifest.json").unlink()
        with self.assertRaises(ClassificationError):
            classify_release(self.repo, release_id)

    def test_oversized_manifest_fails_before_parsing(self) -> None:
        release_id = "202609032301-pipelinenews"
        root = self.repo / "releases" / release_id
        root.mkdir(parents=True)
        (root / "release-manifest.json").write_bytes(b" " * (1024 * 1024 + 1))
        with self.assertRaises(ClassificationError):
            classify_release(self.repo, release_id)

    def test_decision_receipts_exact_manifest_bytes(self) -> None:
        release_id = "202609032302-pipelinenews"
        self.manifest(release_id, schema="pipelinenews.additive-cartridge-release.v1")
        decision = classify_release(self.repo, release_id)
        raw = (self.repo / "releases" / release_id / "release-manifest.json").read_bytes()
        import hashlib
        self.assertEqual(decision.manifest_bytes, len(raw))
        self.assertEqual(decision.manifest_sha256, hashlib.sha256(raw).hexdigest())

    def test_github_outputs_are_scalar_and_job_ready(self) -> None:
        release_id = "202609032303-pipelinenews"
        self.manifest(release_id, schema="pipelinenews.additive-cartridge-release.v1")
        output = self.repo / "github-output"
        write_github_output(classify_release(self.repo, release_id), output)
        values = dict(line.split("=", 1) for line in output.read_text().splitlines())
        self.assertEqual(values["route"], "source-only")
        self.assertEqual(values["pages_applicable"], "false")

    def test_receipt_replace_is_complete_json(self) -> None:
        release_id = "202609032304-pipelinenews"
        self.manifest(release_id, schema="pipelinenews.additive-cartridge-release.v1")
        receipt = self.repo / "reports" / "classification.json"
        write_receipt(classify_release(self.repo, release_id), receipt)
        self.assertEqual(json.loads(receipt.read_text())["release_id"], release_id)
        self.assertTrue(receipt.read_bytes().endswith(b"\n"))

    def test_current_committed_additive_release_classifies(self) -> None:
        repo = Path(__file__).resolve().parents[2]
        decision = classify_release(repo, "202609032251-pipelinenews")
        self.assertEqual(decision.route, "source-only")
        self.assertEqual(
            decision.schema, "pipelinenews.additive-cartridge-release.v1"
        )
        self.assertGreater(decision.manifest_bytes, 1000)

    def test_release_paths_are_deduplicated_and_sorted(self) -> None:
        self.assertEqual(
            release_ids_from_paths(
                [
                    "docs/coordination/BOARD.md",
                    "releases/202609032251-pipelinenews/index.html",
                    "releases\\202609032251-pipelinenews\\release-manifest.json",
                    "releases/202608291447-pipelinenews/index.html",
                ]
            ),
            ["202608291447-pipelinenews", "202609032251-pipelinenews"],
        )

    def test_discovers_release_from_git_commit_range(self) -> None:
        subprocess.run(["git", "init", "-q"], cwd=self.repo, check=True)
        subprocess.run(["git", "config", "user.email", "test@example.invalid"], cwd=self.repo, check=True)
        subprocess.run(["git", "config", "user.name", "classifier test"], cwd=self.repo, check=True)
        (self.repo / "README").write_text("base\n", encoding="utf-8")
        self.manifest(
            "202608291447-pipelinenews",
            schema="pipelinenews.timestamp-folder-successor.v1",
        )
        subprocess.run(["git", "add", "README", "releases"], cwd=self.repo, check=True)
        subprocess.run(["git", "commit", "-qm", "base"], cwd=self.repo, check=True)
        base = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=self.repo, text=True).strip()
        release_id = "202609032305-pipelinenews"
        self.manifest(release_id, schema="pipelinenews.additive-cartridge-release.v1")
        subprocess.run(["git", "add", "releases"], cwd=self.repo, check=True)
        subprocess.run(["git", "commit", "-qm", "release"], cwd=self.repo, check=True)
        head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=self.repo, text=True).strip()
        self.assertEqual(discover_release(self.repo, base, head), release_id)

    def test_git_range_with_two_releases_is_ambiguous(self) -> None:
        subprocess.run(["git", "init", "-q"], cwd=self.repo, check=True)
        subprocess.run(["git", "config", "user.email", "test@example.invalid"], cwd=self.repo, check=True)
        subprocess.run(["git", "config", "user.name", "classifier test"], cwd=self.repo, check=True)
        (self.repo / "README").write_text("base\n", encoding="utf-8")
        subprocess.run(["git", "add", "README"], cwd=self.repo, check=True)
        subprocess.run(["git", "commit", "-qm", "base"], cwd=self.repo, check=True)
        base = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=self.repo, text=True).strip()
        for release_id in ("202609032306-pipelinenews", "202609032307-pipelinenews"):
            self.manifest(release_id, schema="pipelinenews.timestamp-folder-successor.v1")
        subprocess.run(["git", "add", "releases"], cwd=self.repo, check=True)
        subprocess.run(["git", "commit", "-qm", "two releases"], cwd=self.repo, check=True)
        head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=self.repo, text=True).strip()
        with self.assertRaises(ClassificationError):
            discover_release(self.repo, base, head)

    def test_git_range_rejects_immutable_release_edits(self) -> None:
        subprocess.run(["git", "init", "-q"], cwd=self.repo, check=True)
        subprocess.run(["git", "config", "user.email", "test@example.invalid"], cwd=self.repo, check=True)
        subprocess.run(["git", "config", "user.name", "classifier test"], cwd=self.repo, check=True)
        release_id = "202609032308-pipelinenews"
        self.manifest(release_id, schema="pipelinenews.timestamp-folder-successor.v1")
        subprocess.run(["git", "add", "releases"], cwd=self.repo, check=True)
        subprocess.run(["git", "commit", "-qm", "release"], cwd=self.repo, check=True)
        base = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=self.repo, text=True).strip()
        manifest = self.repo / "releases" / release_id / "release-manifest.json"
        manifest.write_text(manifest.read_text() + "\n", encoding="utf-8")
        subprocess.run(["git", "add", "releases"], cwd=self.repo, check=True)
        subprocess.run(["git", "commit", "-qm", "mutate"], cwd=self.repo, check=True)
        head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=self.repo, text=True).strip()
        with self.assertRaises(ClassificationError):
            discover_release(self.repo, base, head)

    def test_abbreviated_commit_is_rejected(self) -> None:
        subprocess.run(["git", "init", "-q"], cwd=self.repo, check=True)
        with self.assertRaises(ClassificationError):
            require_commit(self.repo, "937b8c0", "base")

    def test_resolves_the_committed_live_pointer(self) -> None:
        repo = Path(__file__).resolve().parents[2]
        pointer = json.loads((repo / "state/live-set.json").read_text(encoding="utf-8"))
        self.assertEqual(resolve_live_pointer(repo), pointer["release_id"])

    def pointer_bytes(self, release_id: str, *, digest: str | None = None) -> bytes:
        manifest_path = self.repo / "releases" / release_id / "release-manifest.json"
        raw = manifest_path.read_bytes()
        import hashlib
        return (json.dumps(
            {
                "schema": "pipelinenews.live-pointer.v3",
                "generation": release_id[:12],
                "release_id": release_id,
                "entrypoint": f"releases/{release_id}/index.html",
                "release_manifest": {
                    "path": f"releases/{release_id}/release-manifest.json",
                    "bytes": len(raw),
                    "sha256": digest or hashlib.sha256(raw).hexdigest(),
                },
            },
            sort_keys=True,
        ) + "\n").encode()

    def test_live_pointer_rejects_a_stale_manifest_digest(self) -> None:
        release_id = "202609032309-pipelinenews"
        self.manifest(release_id, schema="pipelinenews.timestamp-folder-successor.v1")
        payload = self.pointer_bytes(release_id, digest="0" * 64)
        (self.repo / "state").mkdir()
        (self.repo / "state" / "live-set.json").write_bytes(payload)
        (self.repo / "releases" / "current-v3.json").write_bytes(payload)
        with self.assertRaises(ClassificationError):
            resolve_live_pointer(self.repo)

    def test_live_pointer_rejects_two_identical_current_files(self) -> None:
        release_id = "202609032310-pipelinenews"
        self.manifest(release_id, schema="pipelinenews.timestamp-folder-successor.v1")
        payload = self.pointer_bytes(release_id)
        (self.repo / "state").mkdir()
        (self.repo / "state" / "live-set.json").write_bytes(payload)
        (self.repo / "releases" / "current-v3.json").write_bytes(payload)
        (self.repo / "releases" / "current-v4.json").write_bytes(payload)
        with self.assertRaises(ClassificationError):
            resolve_live_pointer(self.repo)

    def test_zero_release_diff_can_resolve_the_live_pointer(self) -> None:
        repo = Path(__file__).resolve().parents[2]
        pointer = json.loads((repo / "state/live-set.json").read_text(encoding="utf-8"))
        head = subprocess.check_output(
            ["git", "rev-parse", "HEAD"], cwd=repo, text=True
        ).strip()
        self.assertEqual(
            discover_release(repo, head, head, allow_pointer_fallback=True),
            pointer["release_id"],
        )

    def test_receipt_hash_uses_the_same_snapshot_as_classification(self) -> None:
        release_id = "202609032311-pipelinenews"
        self.manifest(release_id, schema="pipelinenews.timestamp-folder-successor.v1")
        manifest = {
            "release_id": release_id,
            "generation": release_id[:12],
            "schema": "pipelinenews.timestamp-folder-successor.v1",
        }
        snapshot = b"the exact bytes classified"
        with patch("pages_release_classifier._read_manifest", return_value=(manifest, snapshot)):
            decision = classify_release(self.repo, release_id)
        import hashlib
        self.assertEqual(decision.manifest_bytes, len(snapshot))
        self.assertEqual(decision.manifest_sha256, hashlib.sha256(snapshot).hexdigest())


if __name__ == "__main__":
    unittest.main()

Test Register Refresh

A test in the publication folder of PipelineNews covering solar, using SHA-256. It validates projects tests (`ValidateProjectsTests`), sets up (`setUp`) and hashes tree (`hash_tree`).

testpipelinenews / tools/publication/test_register_refresh.py · lines 1–288 of 288 · Entry point · pattern assert_refused (shared by 2 files)

What it does
It tests solar. Defines 35 functions or classes, including load, project, JsOutputTests, test_numbers_print_like_json_stringify, test_stringify_keeps_non_ascii_and_null. Uses libraries __future__, contextlib, copy, hashlib, importlib.util. 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. Domain terms in the code: solar.
Inputs & outputs
In: JSON file 202608291447-registry.json; JSON file old-01.json; JSON file old-p.json; JSON file old-s.json; JSON file news.json; JSON file release-manifest.json; JSON file x.json. Out: JSON file release-manifest.json; JSON file cartridge.json.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for the quarterly register refresh: `register_refresh.py` and the release builder's `registry_core` door.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
pipelinenews · tools/publication · test
Uses
__future__, contextlib, copy, hashlib, importlib.util, io, json, os
Used by
none found
Produces
load, project, JsOutputTests, ValidateProjectsTests, RegistryCoreBuildTests, HashGuardTests, Q2PortProofTest
Defines here
load, project, JsOutputTests, test_numbers_print_like_json_stringify, test_stringify_keeps_non_ascii_and_null, test_normalise_matches_the_compiler_rules, test_dictionary_codes_and_search_alignment, ValidateProjectsTests, test_totals, test_rejects_duplicate_unsorted_and_sub_megawatt, test_rejects_blank_capacity_rather_than_reading_it_as_zero, RegistryCoreBuildTests, setUp, tearDown, hash_tree, make_cartridge, build, test_refresh_derives_digests_and_leaves_parent_untouched, assert_refused, test_refuses_declared_totals_that_disagree, test_refuses_partial_core, test_refuses_keys_outside_the_core, test_refuses_index_out_of_partition_order, test_refuses_short_partition_before_the_last, short, test_refuses_path_escaping_release, HashGuardTests, setUp, tearDown, verify
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_register_refresh.py:1-288 · blob 9a11bfea02c2e5662f18f909645d12a098f3d044 · 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
"""Tests for the quarterly register refresh: register_refresh.py and the
release builder's registry_core door. Synthetic fixtures; no network."""

from __future__ import annotations

import contextlib
import copy
import hashlib
import importlib.util
import io
import json
import os
import tempfile
import unittest
from pathlib import Path


REPO = Path(__file__).resolve().parents[2]


def load(name: str, path: Path):
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


release_builder = load("release_builder_core", REPO / "tools" / "intelligence" / "release_builder.py")
refresh = load("register_refresh_core", REPO / "tools" / "intelligence" / "register_refresh.py")

REGISTRY = "data/202608291447-registry.json"
APP = "assets/202608291447-app.mjs"
PARENT = "202601010000-pipelinenews"


def project(ref: str, cap: float, tech: str = "solar", geometry: str = "valid") -> dict:
    return {
        "repd_ref": ref, "gg_project_id": "GG2050-REPD-%s" % ref,
        "gg_development_id": "GG2050-DEV-REPD-%s" % ref,
        "identity_status": "REPD_BOUND", "identity_confidence": "authoritative",
        "name": "Site %s" % ref, "technology": tech, "repd_technology": "Solar Photovoltaics",
        "capacity_mw": cap, "status": "Operational", "lifecycle": "OPERATIONAL",
        "operator": "Op", "county": "Kent", "region": "South East", "country": "England",
        "repd_record_updated": "2026-10-01", "geometry_status": geometry,
        "latitude": 51.0 if geometry == "valid" else None,
        "longitude": 0.5 if geometry == "valid" else None,
        "direct_related_repd_refs": [], "planning_sibling_repd_refs": [],
        "development_repd_refs": [ref],
    }


SPINE = [project("10", 50.0), project("11", 20.0, "bess"), project("12", 12.5),
         project("13", 3.0, "wind_onshore", "missing"), project("14", 1.0)]


class JsOutputTests(unittest.TestCase):
    def test_numbers_print_like_json_stringify(self):
        self.assertEqual(refresh.js_number(4100.0), "4100")
        self.assertEqual(refresh.js_number(12.5), "12.5")
        self.assertEqual(refresh.js_number(56.4431397), "56.4431397")
        self.assertEqual(refresh.js_number(-1.4664021), "-1.4664021")
        self.assertEqual(refresh.js_number(1e-7), "1e-7")
        self.assertEqual(refresh.js_number(0.000001), "0.000001")
        self.assertEqual(refresh.js_number(3), "3")

    def test_stringify_keeps_non_ascii_and_null(self):
        self.assertEqual(refresh.js_stringify({"a": "Ynys Môn", "b": None, "c": [1.0, True]}),
                         '{"a":"Ynys Môn","b":null,"c":[1,true]}')

    def test_normalise_matches_the_compiler_rules(self):
        self.assertEqual(refresh.normalise("Café & Bar / Ltd."), "cafe and bar ltd.")
        self.assertEqual(refresh.normalise(None), "")
        self.assertEqual(refresh.normalise(12.0), "12")

    def test_dictionary_codes_and_search_alignment(self):
        payload = refresh.compile_projects(SPINE, "G", "C")
        self.assertEqual(payload["dictionaries"]["technology"], ["bess", "solar", "wind_onshore"])
        self.assertEqual([r[0] for r in payload["rows"]], ["10", "11", "12", "13", "14"])
        self.assertEqual(payload["rows"][1][3], 0)
        search = refresh.compile_search(SPINE, "G", "C")
        self.assertEqual(len(search["rows"]), len(SPINE))
        self.assertIn("gg2050-repd-12", search["rows"][2])


class ValidateProjectsTests(unittest.TestCase):
    def test_totals(self):
        totals = refresh.validate_projects(SPINE)
        self.assertEqual(totals["project_count"], 5)
        self.assertEqual(totals["capacity_mw"], 86.5)
        self.assertEqual(totals["missing_geometry_count"], 1)

    def test_rejects_duplicate_unsorted_and_sub_megawatt(self):
        for bad in (SPINE + [project("10", 0.5 + 0.5)],
                    [project("1", 2.0), project("2", 3.0)],
                    [project("1", 0.9)]):
            with self.assertRaises(SystemExit):
                refresh.validate_projects(bad)

    def test_rejects_blank_capacity_rather_than_reading_it_as_zero(self):
        p = project("1", 2.0)
        p["capacity_mw"] = None
        with self.assertRaises(SystemExit):
            refresh.validate_projects([p])


class RegistryCoreBuildTests(unittest.TestCase):
    """A synthetic parent release refreshed through cmd_build."""

    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        root = Path(self.tmp.name)
        self.releases, self.cartridges = root / "releases", root / "cartridges"
        self.releases.mkdir()
        self.cartridges.mkdir()
        self.saved = (release_builder.RELEASES, release_builder.CARTRIDGES)
        release_builder.RELEASES, release_builder.CARTRIDGES = str(self.releases), str(self.cartridges)
        self.parent = self.releases / PARENT
        (self.parent / "data" / "projects").mkdir(parents=True)
        (self.parent / "assets").mkdir()
        (self.parent / "index.html").write_text("<title>t</title><span>Q2 cut</span>\n", encoding="utf-8")
        (self.parent / APP).write_text('const X = "Q2";\nasync function boot() {}\n', encoding="utf-8")
        old = [project("1", 5.0)]
        old_part = self.parent / "data" / "projects" / "old-01.json"
        old_part.write_text(json.dumps({"schema": refresh.DETAIL_SCHEMA, "record_count": 1, "projects": old}),
                            encoding="utf-8")
        registry = {
            "detail_schema": refresh.DETAIL_SCHEMA, "detail_partition_size": 2,
            "totals": {"project_count": 1}, "source": {"dataset": "Q2"},
            "cache_identity": "keep", "cache_contract": {"keep": True},
            "assets": {"projects": {"path": "data/old-p.json", "sha256": "x"},
                       "search": {"path": "data/old-s.json", "sha256": "y"},
                       "news": {"path": "data/news.json", "sha256": "z"}},
            "detail_partitions": [{"path": "data/projects/old-01.json"}],
            "supplemental_assets": {},
        }
        (self.parent / REGISTRY).write_text(json.dumps(registry), encoding="utf-8")
        (self.parent / "release-manifest.json").write_text(
            json.dumps({"release_id": PARENT, "parent_release_id": None}), encoding="utf-8")
        self.parent_hashes = self.hash_tree(self.parent)

    def tearDown(self):
        release_builder.RELEASES, release_builder.CARTRIDGES = self.saved
        self.tmp.cleanup()

    @staticmethod
    def hash_tree(root: Path) -> dict:
        return {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest()
                for p in sorted(root.rglob("*")) if p.is_file()}

    def make_cartridge(self, name="refresh", spine=SPINE, mutate=None):
        pkg = self.cartridges / name
        (pkg / "data").mkdir(parents=True)
        parts = [spine[i:i + 2] for i in range(0, len(spine), 2)]
        detail = []
        for i, rows in enumerate(parts, 1):
            fname = "{GEN}-part-%02d.json" % i
            (pkg / "data" / fname).write_text(json.dumps(
                {"schema": refresh.DETAIL_SCHEMA, "record_count": len(rows), "projects": rows}), encoding="utf-8")
            detail.append({"path": "data/" + fname})
        (pkg / "data" / "{GEN}-projects.json").write_bytes(refresh.json_bytes(
            refresh.compile_projects(spine, "{GEN}", "cid")))
        (pkg / "data" / "{GEN}-search.json").write_bytes(refresh.json_bytes(
            refresh.compile_search(spine, "{GEN}", "cid")))
        totals = refresh.validate_projects(spine)
        man = {
            "key": "repd_test_register", "modifies_existing_dashboard": True,
            "repairs": {"index.html": [{"label": "cut", "from": "Q2 cut", "to": "Q3 cut"}]},
            "registry_core": {
                "totals": totals,
                "source": {"dataset": "Q3", "admitted_project_count": totals["project_count"]},
                "assets.projects": {"path": "data/{GEN}-projects.json", "schema": refresh.PROJECT_SCHEMA,
                                    "generation": "{GEN}", "cache_identity": "cid"},
                "assets.search": {"path": "data/{GEN}-search.json", "schema": refresh.SEARCH_SCHEMA,
                                  "generation": "{GEN}", "cache_identity": "cid"},
                "detail_partitions": detail,
            },
        }
        if mutate:
            mutate(man)
        (pkg / "cartridge.json").write_text(json.dumps(man), encoding="utf-8")
        return name

    def build(self, name, gen="202602020000"):
        with contextlib.redirect_stdout(io.StringIO()):
            return release_builder.cmd_build(PARENT, name, gen, None)

    def test_refresh_derives_digests_and_leaves_parent_untouched(self):
        self.assertEqual(self.build(self.make_cartridge()), 0)
        target = self.releases / "202602020000-pipelinenews"
        reg = json.loads((target / REGISTRY).read_text(encoding="utf-8"))
        self.assertEqual(reg["totals"]["project_count"], 5)
        self.assertEqual(reg["source"]["dataset"], "Q3")
        self.assertEqual([d["record_count"] for d in reg["detail_partitions"]], [2, 2, 1])
        p = target / reg["assets"]["projects"]["path"]
        self.assertEqual(reg["assets"]["projects"]["sha256"], hashlib.sha256(p.read_bytes()).hexdigest())
        self.assertEqual(reg["assets"]["projects"]["generation"], "202602020000")
        self.assertEqual(reg["assets"]["news"], {"path": "data/news.json", "sha256": "z"})
        self.assertEqual(reg["cache_identity"], "keep")
        rel = json.loads((target / "release-manifest.json").read_text(encoding="utf-8"))
        self.assertEqual(sorted(rel["registry_core_replaced"]), sorted(release_builder.REGISTRY_CORE_KEYS))
        self.assertIn("Q3 cut", (target / "index.html").read_text(encoding="utf-8"))
        # inherited Q2 bytes stay, byte-identical
        self.assertTrue((target / "data/projects/old-01.json").exists())
        self.assertEqual(self.hash_tree(self.parent), self.parent_hashes)
        with contextlib.redirect_stdout(io.StringIO()):
            self.assertEqual(release_builder.cmd_check("202602020000-pipelinenews"), 0)

    def assert_refused(self, mutate=None, spine=SPINE, index_spine=None):
        name = self.make_cartridge(mutate=mutate, spine=spine)
        if index_spine is not None:
            (self.cartridges / name / "data" / "{GEN}-projects.json").write_bytes(
                refresh.json_bytes(refresh.compile_projects(index_spine, "{GEN}", "cid")))
        with self.assertRaises(SystemExit):
            self.build(name)
        self.assertEqual(self.hash_tree(self.parent), self.parent_hashes)

    def test_refuses_declared_totals_that_disagree(self):
        self.assert_refused(lambda m: m["registry_core"]["totals"].update(project_count=6))

    def test_refuses_partial_core(self):
        self.assert_refused(lambda m: m["registry_core"].pop("assets.search"))

    def test_refuses_keys_outside_the_core(self):
        self.assert_refused(lambda m: m["registry_core"].update(cache_identity="new"))

    def test_refuses_index_out_of_partition_order(self):
        swapped = copy.deepcopy(SPINE)
        swapped[0], swapped[1] = swapped[1], swapped[0]
        self.assert_refused(index_spine=swapped)

    def test_refuses_short_partition_before_the_last(self):
        def short(m):
            m["registry_core"]["detail_partitions"].insert(0, m["registry_core"]["detail_partitions"].pop())
        self.assert_refused(short)

    def test_refuses_path_escaping_release(self):
        self.assert_refused(lambda m: m["registry_core"]["assets.search"].update(path="../x.json"))


guard = load("release_hash_guard_core", REPO / "tools" / "intelligence" / "release_hash_guard.py")


class HashGuardTests(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.root = Path(self.tmp.name)
        (self.root / "releases" / "a-pipelinenews").mkdir(parents=True)
        (self.root / "releases" / "a-pipelinenews" / "index.html").write_text("a", encoding="utf-8")
        self.snap = str(self.root / "snap.sha256")
        with contextlib.redirect_stdout(io.StringIO()):
            guard.main(["--repo", str(self.root), "--snapshot", self.snap])

    def tearDown(self):
        self.tmp.cleanup()

    def verify(self, *allow):
        args = ["--repo", str(self.root), "--verify", self.snap]
        for name in allow:
            args += ["--allow-new", name]
        with contextlib.redirect_stdout(io.StringIO()):
            return guard.main(args)

    def test_new_release_folder_is_allowed_only_when_named(self):
        new = self.root / "releases" / "b-pipelinenews"
        new.mkdir()
        (new / "index.html").write_text("b", encoding="utf-8")
        self.assertEqual(self.verify("b-pipelinenews"), 0)
        self.assertEqual(self.verify(), 1)

    def test_any_change_to_an_existing_byte_fails(self):
        (self.root / "releases" / "a-pipelinenews" / "index.html").write_text("A", encoding="utf-8")
        self.assertEqual(self.verify(), 1)

    def test_a_deleted_file_fails(self):
        (self.root / "releases" / "a-pipelinenews" / "index.html").unlink()
        self.assertEqual(self.verify(), 1)


@unittest.skipUnless((REPO / "releases" / "202609060232-pipelinenews").is_dir(), "Q2 release not present")
class Q2PortProofTest(unittest.TestCase):
    def test_port_reproduces_shipped_q2_indexes_byte_for_byte(self):
        with contextlib.redirect_stdout(io.StringIO()):
            self.assertEqual(refresh.prove_q2("202609060232-pipelinenews"), 0)


if __name__ == "__main__":
    unittest.main()