GLOBALGRID2050 / EXPLORE CODE

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

Test Release Builder Applicability and 5 more files

A test in the publication folder of PipelineNews. It sets up (`setUp`), adds release (`add_release`) and adds root (`add_root`).

677 lines of Python and JavaScript from pipelinenews, in 6 files. Topic: Electricity markets and data pipelines. Section 1058 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 Release Builder Applicability test · pipelinenews / tools/publication/test_release_builder_applicability.py lines 1–284
  2. Test Verify Pages Workflow test · pipelinenews / tools/publication/test_verify_pages_workflow.py lines 1–21
  3. Verify Testcode ingest · pipelinenews / tools/publication/verify-testcode.mjs lines 1–19
  4. Verify Pages Workflow automation · pipelinenews / tools/publication/verify_pages_workflow.py lines 1–39
  5. Federated Relationships render · pipelinenews / ui/cartridges/202608282044-federated-relationships.mjs lines 1–91
  6. Sector Intelligence render · pipelinenews / ui/cartridges/202609010145-sector-intelligence.mjs lines 1–223

Test Release Builder Applicability

A test in the publication folder of PipelineNews. It sets up (`setUp`), adds release (`add_release`) and adds root (`add_root`).

testpipelinenews / tools/publication/test_release_builder_applicability.py · lines 1–284 of 284 · Entry point · pattern tearDown (shared by 38 files)

What it does
It tests its inputs. Defines 23 functions or classes, including ApplicabilityFixture, setUp, tearDown, add_release, add_root. Uses libraries __future__, contextlib, importlib.util, io, json. 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.
Inputs & outputs
In: JSON file 202608291447-registry.json; JSON file release-manifest.json. Out: JSON file release-manifest.json; JSON file cartridge.json.
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
Regression tests for release-builder cartridge applicability.
Why it matters
Run by Run Pages Candidate Gate.
Application
pipelinenews · tools/publication · test
Uses
__future__, contextlib, importlib.util, io, json, tempfile, unittest, pathlib
Used by
run by Run Pages Candidate Gate (script call)
Produces
ApplicabilityFixture, RepositoryAncestryTests
Defines here
ApplicabilityFixture, setUp, tearDown, add_release, add_root, add_cartridge, test_registered_asset_is_applied, test_repair_only_key_is_inherited_from_ancestor_manifest, test_idempotent_payload_repair_is_not_reapplied, test_unapplied_repair_is_probed, test_missing_parent_fails_closed_before_probe, test_missing_registry_fails_closed, test_malformed_manifest_fails_closed, test_malformed_registry_fails_closed, test_malformed_parent_id_fails_closed, test_cycle_fails_closed, test_only_legacy_root_may_omit_or_null_parent, test_omitted_or_null_intermediate_parent_fails_closed, test_legacy_root_requires_schema_marker, test_forward_or_equal_parent_generation_fails_closed, test_supplemental_entries_must_be_objects, RepositoryAncestryTests, test_0144_recognises_all_seven_repair_only_cartridges
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_release_builder_applicability.py:1-284 · blob 5b5526e99eebe064a67ba9c9d2849d58051306ef · 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
"""Regression tests for release-builder cartridge applicability."""

from __future__ import annotations

import contextlib
import importlib.util
import io
import json
import tempfile
import unittest
from pathlib import Path
from unittest import mock


REPO = Path(__file__).resolve().parents[2]
BUILDER_PATH = REPO / "tools" / "intelligence" / "release_builder.py"
SPEC = importlib.util.spec_from_file_location("release_builder_applicability", BUILDER_PATH)
if SPEC is None or SPEC.loader is None:
    raise RuntimeError(f"cannot import {BUILDER_PATH}")
release_builder = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(release_builder)

REGISTRY = Path("data") / "202608291447-registry.json"
LEGACY_ROOT = "202608291447-pipelinenews"
LEGACY_ROOT_SCHEMA = "pipelinenews.timestamp-folder-successor.v1"
OMIT = object()


class ApplicabilityFixture(unittest.TestCase):
    def setUp(self) -> None:
        self.temporary = tempfile.TemporaryDirectory()
        self.root = Path(self.temporary.name)
        self.releases = self.root / "releases"
        self.cartridges = self.root / "cartridges"
        self.releases.mkdir()
        self.cartridges.mkdir()
        self.original_releases = release_builder.RELEASES
        self.original_cartridges = release_builder.CARTRIDGES
        release_builder.RELEASES = str(self.releases)
        release_builder.CARTRIDGES = str(self.cartridges)

    def tearDown(self) -> None:
        release_builder.RELEASES = self.original_releases
        release_builder.CARTRIDGES = self.original_cartridges
        self.temporary.cleanup()

    def add_release(
        self,
        release_id: str,
        *,
        parent: object = OMIT,
        schema: str = "pipelinenews.additive-cartridge-release.v1",
        cartridge_added: str | None = None,
        assets: tuple[str, ...] = (),
    ) -> Path:
        target = self.releases / release_id
        (target / REGISTRY.parent).mkdir(parents=True)
        manifest: dict[str, object] = {
            "release_id": release_id,
            "schema": schema,
        }
        if parent is not OMIT:
            manifest["parent_release_id"] = parent
        if cartridge_added is not None:
            manifest["cartridge_added"] = cartridge_added
        (target / "release-manifest.json").write_text(
            json.dumps(manifest), encoding="utf-8"
        )
        (target / REGISTRY).write_text(
            json.dumps({"supplemental_assets": {key: {} for key in assets}}),
            encoding="utf-8",
        )
        return target

    def add_root(self, *, parent: object = OMIT) -> Path:
        return self.add_release(
            LEGACY_ROOT,
            parent=parent,
            schema=LEGACY_ROOT_SCHEMA,
        )

    def add_cartridge(self, directory: str, key: str) -> None:
        target = self.cartridges / directory
        target.mkdir()
        (target / "cartridge.json").write_text(
            json.dumps({"key": key, "summary": "test cartridge"}),
            encoding="utf-8",
        )

    def test_registered_asset_is_applied(self) -> None:
        release_id = LEGACY_ROOT
        self.add_release(
            release_id, schema=LEGACY_ROOT_SCHEMA, assets=("registered_asset",)
        )
        self.assertEqual(
            release_builder.cartridge_keys(release_id), {"registered_asset"}
        )

    def test_repair_only_key_is_inherited_from_ancestor_manifest(self) -> None:
        base = "202609040001-pipelinenews"
        tip = "202609040002-pipelinenews"
        self.add_root()
        self.add_release(
            base,
            parent=LEGACY_ROOT,
            cartridge_added="repair_only",
            assets=("ancestor_asset",),
        )
        self.add_release(tip, parent=base, assets=("registered_asset",))
        self.assertEqual(
            release_builder.cartridge_keys(tip),
            {"registered_asset", "ancestor_asset", "repair_only"},
        )

    def test_idempotent_payload_repair_is_not_reapplied(self) -> None:
        base = "202609040001-pipelinenews"
        tip = "202609040002-pipelinenews"
        self.add_root()
        self.add_release(
            base, parent=LEGACY_ROOT, cartridge_added="wider_fleet_proximity"
        )
        self.add_release(tip, parent=base, assets=("grid_proximity",))
        self.add_cartridge("wider-fleet-proximity", "wider_fleet_proximity")

        output = io.StringIO()
        with mock.patch.object(release_builder, "cmd_build") as build:
            with contextlib.redirect_stdout(output):
                result = release_builder.cmd_applicable(tip)

        self.assertEqual(result, 0)
        build.assert_not_called()
        self.assertRegex(output.getvalue(), r"wider-fleet-proximity\s+ALREADY APPLIED")

    def test_unapplied_repair_is_probed(self) -> None:
        tip = "202609040001-pipelinenews"
        self.add_root()
        self.add_release(tip, parent=LEGACY_ROOT)
        self.add_cartridge("new-repair", "new_repair")

        output = io.StringIO()
        with mock.patch.object(release_builder, "utc_stamp", return_value="202609040002"):
            with mock.patch.object(release_builder, "cmd_build") as build:
                with contextlib.redirect_stdout(output):
                    result = release_builder.cmd_applicable(tip)

        self.assertEqual(result, 0)
        build.assert_called_once_with(tip, "new-repair", "202609040002", None)
        self.assertIn("new-repair                   APPLIES", output.getvalue())

    def test_missing_parent_fails_closed_before_probe(self) -> None:
        tip = "202609040002-pipelinenews"
        self.add_release(tip, parent="202609040001-pipelinenews")
        self.add_cartridge("new-repair", "new_repair")

        with mock.patch.object(release_builder, "cmd_build") as build:
            with self.assertRaisesRegex(SystemExit, "missing release.*202609040001"):
                release_builder.cmd_applicable(tip)
        build.assert_not_called()

    def test_missing_registry_fails_closed(self) -> None:
        tip = LEGACY_ROOT
        target = self.add_root()
        (target / REGISTRY).unlink()
        with self.assertRaisesRegex(SystemExit, "missing registry"):
            release_builder.cartridge_keys(tip)

    def test_malformed_manifest_fails_closed(self) -> None:
        tip = LEGACY_ROOT
        target = self.add_root()
        (target / "release-manifest.json").write_text("{", encoding="utf-8")
        with self.assertRaisesRegex(SystemExit, "malformed release manifest"):
            release_builder.cartridge_keys(tip)

    def test_malformed_registry_fails_closed(self) -> None:
        tip = LEGACY_ROOT
        target = self.add_root()
        (target / REGISTRY).write_text(
            json.dumps({"supplemental_assets": []}), encoding="utf-8"
        )
        with self.assertRaisesRegex(SystemExit, "malformed supplemental_assets"):
            release_builder.cartridge_keys(tip)

    def test_malformed_parent_id_fails_closed(self) -> None:
        tip = "202609040001-pipelinenews"
        self.add_release(tip, parent="../outside")
        with self.assertRaisesRegex(SystemExit, "malformed parent_release_id"):
            release_builder.cartridge_keys(tip)

    def test_cycle_fails_closed(self) -> None:
        first = "202609040002-pipelinenews"
        second = "202609040001-pipelinenews"
        self.add_release(first, parent=second)
        self.add_release(second, parent=first)
        with self.assertRaisesRegex(SystemExit, "cycle.*202609040001"):
            release_builder.cartridge_keys(first)

    def test_only_legacy_root_may_omit_or_null_parent(self) -> None:
        root = self.add_root(parent=None)
        self.assertEqual(release_builder.cartridge_keys(LEGACY_ROOT), set())

        manifest_path = root / "release-manifest.json"
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
        del manifest["parent_release_id"]
        manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
        self.assertEqual(release_builder.cartridge_keys(LEGACY_ROOT), set())

    def test_omitted_or_null_intermediate_parent_fails_closed(self) -> None:
        tip = "202609040002-pipelinenews"
        intermediate = "202609040001-pipelinenews"
        self.add_root()
        intermediate_dir = self.add_release(intermediate, parent=None)
        self.add_release(tip, parent=intermediate)

        with self.assertRaisesRegex(SystemExit, "null parent_release_id"):
            release_builder.cartridge_keys(tip)

        manifest_path = intermediate_dir / "release-manifest.json"
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
        del manifest["parent_release_id"]
        manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
        with self.assertRaisesRegex(SystemExit, "missing parent_release_id"):
            release_builder.cartridge_keys(tip)

    def test_legacy_root_requires_schema_marker(self) -> None:
        self.add_release(LEGACY_ROOT, parent=None, schema="wrong.root.schema")
        with self.assertRaisesRegex(SystemExit, "only legacy root.*successor"):
            release_builder.cartridge_keys(LEGACY_ROOT)

    def test_forward_or_equal_parent_generation_fails_closed(self) -> None:
        current = "202609040002-pipelinenews"
        forward = "202609040003-pipelinenews"
        self.add_release(current, parent=forward)
        self.add_release(forward, parent=LEGACY_ROOT)
        with self.assertRaisesRegex(SystemExit, "not strictly older"):
            release_builder.cartridge_keys(current)

        current_manifest = self.releases / current / "release-manifest.json"
        manifest = json.loads(current_manifest.read_text(encoding="utf-8"))
        manifest["parent_release_id"] = current
        current_manifest.write_text(json.dumps(manifest), encoding="utf-8")
        with self.assertRaisesRegex(SystemExit, "not strictly older"):
            release_builder.cartridge_keys(current)

    def test_supplemental_entries_must_be_objects(self) -> None:
        root = self.add_root()
        registry_path = root / REGISTRY
        for malformed in (None, [], "asset"):
            with self.subTest(value=malformed):
                registry_path.write_text(
                    json.dumps({"supplemental_assets": {"bad": malformed}}),
                    encoding="utf-8",
                )
                with self.assertRaisesRegex(
                    SystemExit, "malformed supplemental asset entry.*expected object"
                ):
                    release_builder.cartridge_keys(LEGACY_ROOT)


class RepositoryAncestryTests(unittest.TestCase):
    def test_0144_recognises_all_seven_repair_only_cartridges(self) -> None:
        release_id = "202609040144-pipelinenews"
        registry = json.loads(
            (REPO / "releases" / release_id / REGISTRY).read_text(encoding="utf-8")
        )
        registered = set(registry["supplemental_assets"])
        repair_only = {
            "wider_fleet_proximity",
            "summary_seam",
            "wider_fleet_dropdown",
            "withdraw_nonanswers",
            "sector_open_neutral_sort",
            "phone_first_heights",
            "no_grading",
        }
        self.assertTrue(repair_only.isdisjoint(registered))

        applied = release_builder.cartridge_keys(release_id)
        self.assertEqual(applied, registered | repair_only)
        self.assertEqual(len(applied), 26)


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

Test Verify Pages Workflow

A test in the publication folder of PipelineNews that checks Verify Pages Workflow. It is built from the workflow contract tests class (`WorkflowContractTests`).

testpipelinenews / tools/publication/test_verify_pages_workflow.py · lines 1–21 of 21 · Entry point

What it does
It tests its inputs. Defines WorkflowContractTests, test_repository_workflow_keeps_both_routes. Uses libraries __future__, sys, 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 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
Defines `WorkflowContractTests` and `test_repository_workflow_keeps_both_routes`.
Why it matters
Run by Build 30x Ledger and Run Pages Candidate Gate.
Application
pipelinenews · tools/publication · test
Uses
Verify Pages Workflow (import), __future__, sys, unittest, pathlib
Used by
run by Build 30x Ledger (script call), run by Run Pages Candidate Gate (script call)
Produces
WorkflowContractTests
Defines here
WorkflowContractTests, test_repository_workflow_keeps_both_routes
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_verify_pages_workflow.py:1-21 · blob f699cd15bd85b833b02e245adcc931d7fad55a05 · 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 sys
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from verify_pages_workflow import verify


class WorkflowContractTests(unittest.TestCase):
    def test_repository_workflow_keeps_both_routes(self) -> None:
        workflow = Path(__file__).resolve().parents[2] / ".github" / "workflows" / "pages.yml"
        receipt = verify(workflow)
        self.assertTrue(receipt["passed"])
        self.assertGreaterEqual(sum(receipt["checks"].values()), 15)


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

Verify Testcode

A JavaScript module in the publication folder of PipelineNews that uses SHA-256.

ingestpipelinenews / tools/publication/verify-testcode.mjs · lines 1–19 of 19 · Entry point

What it does
It loads data. Defines hash. Uses libraries node:fs, node:child_process, node:crypto, node:path. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: PipelineNews Coverage Contract Workflow (pipelinenews).
What it achieves
Its name says it verifies testcode. Defines `hash`.
Why it matters
Run by PipelineNews Coverage Contract Workflow.
Application
pipelinenews · tools/publication · JavaScript module
Uses
node:fs, node:child_process, node:crypto, node:path
Used by
run by PipelineNews Coverage Contract Workflow (workflow run)
Produces
hash
Defines here
hash
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/verify-testcode.mjs:1-19 · blob 4374e2831acf1b48e28651269591c5510b6230b3 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: experimental · users: none · canonical: production_core
import { readFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { resolve, relative, isAbsolute } from 'node:path';
const root=resolve(process.argv[2] ?? '');
const manifest=JSON.parse(readFileSync(resolve(root,'manifest.json')));
const hash=b=>createHash('sha256').update(b).digest('hex');
if (!/^[a-f0-9]{40}$/.test(manifest.sourceCommit)) throw Error('Full source SHA required');
for (const entry of manifest.files) {
  const path=resolve(root,entry.path), rel=relative(root,path);
  if (isAbsolute(rel)||rel.startsWith('..')) throw Error('File outside candidate');
  const b=readFileSync(path);
  if (b.length!==entry.bytes || hash(b)!==entry.sha256) throw Error(`Candidate bytes mismatch: ${entry.path}`);
}
for (const entry of [...manifest.sources ?? [], ...manifest.module ? [manifest.module] : []]) {
  const b=execFileSync('git',['show',`${manifest.sourceCommit}:${entry.path}`],{maxBuffer:20*1024*1024});
  if (hash(b)!==entry.sha256) throw Error(`Committed source mismatch: ${entry.path}`);
}
console.log(`PASS ${manifest.generation}: candidate files and committed source identities`);

Verify Pages Workflow

A Python command-line tool in the publication folder of PipelineNews that reads pages release classification. It is built from the verify step (`verify`).

automationpipelinenews / tools/publication/verify_pages_workflow.py · lines 1–39 of 39 · Entry point · pattern verify (shared by 34 files)

What it does
It loads pages release classification. Defines verify. Uses libraries __future__, json, 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.
Inputs & outputs
In: JSON file pages-release-classification.json.
Downstream impact
Used directly by 1 file: Test Verify Pages Workflow (pipelinenews). Reached from 3 other entry points, including PipelineNews Pages Routing Candidate Workflow (pipelinenews); Build 30x Ledger (pipelinenews); Run Pages Candidate Gate (pipelinenews).
What it achieves
Fail when the Pages caller loses its release-routing boundaries.
Why it matters
Checked by Test Verify Pages Workflow.
Application
pipelinenews · tools/publication · Python CLI
Uses
__future__, json, pathlib
Used by
imported by Test Verify Pages Workflow (import)
Produces
verify
Defines here
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/verify_pages_workflow.py:1-39 · blob c9221e9d221108f10d240ec54f929ba6cd6392d6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Fail when the Pages caller loses its release-routing boundaries."""

from __future__ import annotations

import json
from pathlib import Path


def verify(path: Path) -> dict[str, object]:
    text = path.read_text(encoding="utf-8")
    pre_jobs, jobs = text.split("\njobs:\n", 1)
    checks = {
        "classifier_precedes_routes": jobs.index("  classify:\n") < jobs.index("  deploy:\n"),
        "classification_is_bound_to_full_oid": '[[ "$EXPECTED_SHA" =~ ^[0-9a-f]{40}$ ]]' in jobs,
        "classification_checkout_matches_oid": 'test "$(git rev-parse HEAD)" = "$EXPECTED_SHA"' in jobs,
        "classification_oid_is_current_main": 'test "$(git rev-parse FETCH_HEAD)" = "$EXPECTED_SHA"' in jobs,
        "main_binding_precedes_classification": jobs.index("Require exact current main before classification") < jobs.index("Classify release from immutable manifest"),
        "classifier_emits_receipt": "--receipt reports/pages-release-classification.json" in jobs,
        "source_only_has_own_gate": "if: needs.classify.outputs.route == 'source-only'" in jobs,
        "source_only_runs_release_check": "release_builder.py --check \"$RELEASE_ID\"" in jobs,
        "pages_needs_classifier": "  deploy:\n    needs: classify\n" in jobs,
        "pages_has_job_level_if": "if: needs.classify.outputs.route == 'pages'" in jobs,
        "pages_receives_classified_release": "timestamp_folder_release: ${{ needs.classify.outputs.release_id }}" in jobs,
        "push_preserves_pointer_fallback": "--allow-pointer-fallback" in jobs,
        "manual_preserves_pointer_fallback": "args+=(--live-pointer)" in jobs,
        "global_token_is_read_only": "pages: write" not in pre_jobs and "id-token: write" not in pre_jobs,
        "pages_route_has_write_token": "pages: write\n      id-token: write\n    uses:" in jobs,
    }
    failed = [name for name, passed in checks.items() if not passed]
    receipt = {"schema": "pipelinenews.pages-workflow-proof.v1", "checks": checks, "passed": not failed}
    print(json.dumps(receipt, sort_keys=True))
    if failed:
        raise SystemExit("workflow contract failed: " + ", ".join(failed))
    return receipt


if __name__ == "__main__":
    verify(Path(__file__).resolve().parents[2] / ".github" / "workflows" / "pages.yml")

Federated Relationships

A JavaScript module in the cartridges folder of PipelineNews that fetches verified projection (`fetchVerifiedProjection`), using SHA-256.

Set aside from the main view: 97% of its lines are the same as pipelinenews_intelligence/202608311343/assets/202608282200-federated-relationships.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Federated Relationships; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9733 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 pipelinenews_intelligence/202608311343/assets/202608282200-federated-relationships.mjs:1-91 b6d6db56bf61afb519cdb7f62a582277d9e4d9ac
  • sha256 750bd9eaa145bb3ec05ec7c39ee595d4e7e6af50710e9e261c4381aa62c9e854
  • target sha256 8d6d46c0b1ca86ad4d4dc54d6ffdce483991dcdfd8c7dad3cbd206165cbcecc2
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderpipelinenews / ui/cartridges/202608282044-federated-relationships.mjs · lines 1–91 of 91 · version 2026-08-28 20:44 · Not reached from any entry point (candidate for review) · pattern mountFederatedRelationships (shared by 2 files)

What it does
It draws its content. Defines invariant, bytesToHex, fetchVerifiedProjection, render, mountFederatedRelationships. Side effects: changes the web page (DOM); makes network requests.
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.
What it achieves
It fetches verified projection (`fetchVerifiedProjection`) and is built from the bytes to hex helper (`bytesToHex`) and the render step (`render`). Defines `invariant`, `bytesToHex`, `fetchVerifiedProjection` and 2 more.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · ui/cartridges · JavaScript module
Uses
none found
Used by
none found
Produces
FEDERATED_RELATIONSHIP_CARTRIDGE_CONTRACT, mountFederatedRelationships
Defines here
invariant, bytesToHex, fetchVerifiedProjection, render, mountFederatedRelationships
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 ui/cartridges/202608282044-federated-relationships.mjs:1-91 · blob 5f4b60641b427e1825343b9496011fc53b8530ae · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
const GENERATION = "202608282044";

export const FEDERATED_RELATIONSHIP_CARTRIDGE_CONTRACT = Object.freeze({
  schema: "pipelinenews.federated-relationship-cartridge.v1",
  generation: GENERATION,
  activation: "dynamic-import-on-user-open; projection-fetch-after-explicit-open",
  maximumPayloadRequests: 1,
  expectedRows: 3,
  projectBindings: 0,
});

function invariant(condition, message) {
  if (!condition) throw new Error(message);
}

function bytesToHex(bytes) {
  return [...bytes].map((value) => value.toString(16).padStart(2, "0")).join("");
}

async function fetchVerifiedProjection(asset) {
  invariant(asset && typeof asset.url === "string", "relationship payload URL missing");
  invariant(Number.isInteger(asset.bytes) && asset.bytes > 0, "relationship payload byte pin missing");
  invariant(/^[a-f0-9]{64}$/u.test(asset.sha256), "relationship payload digest pin missing");
  const target = new URL(asset.url, document.baseURI);
  invariant(target.origin === location.origin, "cross-origin relationship payload rejected");
  const response = await fetch(target, { cache: "force-cache" });
  invariant(response.ok, `relationship payload returned HTTP ${response.status}`);
  const raw = new Uint8Array(await response.arrayBuffer());
  invariant(raw.byteLength === asset.bytes, "relationship payload byte drift");
  invariant(globalThis.crypto?.subtle, "Web Crypto unavailable");
  const digest = bytesToHex(new Uint8Array(await crypto.subtle.digest("SHA-256", raw)));
  invariant(digest === asset.sha256, "relationship payload digest drift");
  return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw));
}

function render(host, projection) {
  invariant(projection.schema === "pipelinenews.federated-relationship-status-browser.v1", "relationship schema changed");
  invariant(projection.generation === GENERATION, "relationship generation changed");
  invariant(projection.heading === "RELATIONSHIP EVIDENCE — CANDIDATES AND ABSTENTIONS", "safe heading changed");
  invariant(projection.project_bindings === 0, "project binding entered projection");
  invariant(projection.confirmed_ownership_rows === 0 && projection.confirmed_operator_rows === 0, "confirmed role entered projection");
  invariant(Array.isArray(projection.rows) && projection.rows.length === 3, "relationship row count changed");
  invariant(projection.rows.every((row) => row.decision === "ABSTAIN" && row.eligible_for_join === false), "abstention law changed");

  const heading = document.createElement("h3");
  heading.textContent = projection.heading;
  const notice = document.createElement("p");
  notice.textContent = "Governance status only. Candidate counts are not ownership, operator, developer or project-identity facts.";
  const table = document.createElement("table");
  table.className = "projects-table";
  const thead = document.createElement("thead");
  const header = document.createElement("tr");
  for (const label of ["FAMILY", "SEGMENT", "CANDIDATE ROWS", "REQUESTED ROLE", "DECISION", "JOIN", "CAVEAT"]) {
    const cell = document.createElement("th");
    cell.scope = "col";
    cell.textContent = label;
    header.append(cell);
  }
  thead.append(header);
  const tbody = document.createElement("tbody");
  for (const row of projection.rows) {
    const tr = document.createElement("tr");
    const values = [
      row.relationship_family,
      row.segment,
      Number(row.candidate_rows).toLocaleString("en-GB"),
      row.requested_role,
      row.decision,
      row.eligible_for_join ? "ELIGIBLE" : "NO",
      row.caveat,
    ];
    for (const value of values) {
      const td = document.createElement("td");
      td.textContent = String(value);
      tr.append(td);
    }
    tbody.append(tr);
  }
  table.append(thead, tbody);
  host.replaceChildren(heading, notice, table);
  host.dataset.federatedRelationshipState = "ready";
}

export async function mountFederatedRelationships({ host, payloadAsset }) {
  invariant(host instanceof HTMLElement, "relationship host missing");
  invariant(!host.dataset.federatedRelationshipMounted, "relationship cartridge mounted twice");
  host.dataset.federatedRelationshipMounted = "true";
  const projection = await fetchVerifiedProjection(payloadAsset);
  render(host, projection);
  return Object.freeze({ payloadRequests: 1, rows: projection.rows.length, projectBindings: 0 });
}

Sector Intelligence

A JavaScript module in the cartridges folder of PipelineNews that validates asset (`validateAsset`), decodes payload (`decodePayload`) and loads payload (`loadPayload`), using SHA-256.

Set aside from the main view: 98% of its lines are the same as releases/javascript/202609010719-sector-intelligence.js (pipelinenews), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with JavaScript Sector Intelligence; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9781 to pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 releases/javascript/202609010719-sector-intelligence.js:1-223 e850939eec58f56ac22a1a0b378423b2f7e368a9
  • sha256 650bd84b2f4d675d56c12ba9c8e4dac6f8b27011378e95fb38a76bc41d3f9c66
  • target sha256 1e8e0252a3768c12f45d07e3b11e4a8ff47d097b2acd551c484b6d35a11f309a
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderpipelinenews / ui/cartridges/202609010145-sector-intelligence.mjs · lines 1–223 of 223 · version 2026-09-01 01:45 · Not reached from any entry point (candidate for review) · pattern mountSectorIntelligence (shared by 4 files)

What it does
It draws its content. Defines 9 functions or classes, including element, installStyles, sha256Hex, validateAsset, decodePayload. Side effects: changes the web page (DOM); makes network requests.
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: DuckDB queries.
What it achieves
It validates asset (`validateAsset`), decodes payload (`decodePayload`) and loads payload (`loadPayload`). Defines `element`, `installStyles`, `sha256Hex` and 6 more. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
pipelinenews · ui/cartridges · JavaScript module
Uses
none found
Used by
none found
Produces
SECTOR_INTELLIGENCE_CARTRIDGE_CONTRACT, mountSectorIntelligence
Defines here
element, installStyles, sha256Hex, validateAsset, decodePayload, loadPayload, renderRows, mountSectorIntelligence, select
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 ui/cartridges/202609010145-sector-intelligence.mjs:1-223 · blob 62818e605ea0c969f39a601d8d42e45fa9fb6504 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: duplicate_candidate
const GENERATION = "202609010145";
const PAYLOAD_SCHEMA = "pipelinenews.sector-intelligence-browser.v3";
const USAGE_CONTEXT = "NON_COMMERCIAL_OPEN_SOURCE";
const TOPICS = Object.freeze([
  Object.freeze({ code: "DATA_CENTRES", label: "DATA CENTRES", rank: 1 }),
  Object.freeze({ code: "INVERTER_SECURITY_POLICY", label: "INVERTERS · SECURITY", rank: 2 }),
  Object.freeze({ code: "GREAT_GRID_UPGRADE", label: "GREAT GRID UPGRADE", rank: 3 }),
  Object.freeze({ code: "WORLDWIDE_PV", label: "WORLDWIDE PV", rank: 4 }),
  Object.freeze({ code: "MV_HV_COMPONENTS", label: "MV/HV COMPONENTS", rank: 5 }),
]);
const EXPECTED_FIELDS = Object.freeze([
  "topic_code", "topic_display_rank", "intelligence_item_id", "item_kind", "title", "summary", "canonical_url",
  "source_published_at", "observed_at", "staleness_state", "status", "evidence_class", "source_id",
  "source_licence_id", "source_terms_url", "redistribution_rights", "attribution", "owner_repository",
  "owner_generation", "owner_record_id", "generic_article_id", "value_min", "value_max", "unit", "binding_label",
  "project_binding_count", "eligible_for_news_signal",
]);
const FORBIDDEN_FIELDS = Object.freeze([
  "repd_ref", "gg_project_id", "project", "technology", "capacity_mw", "operator", "county", "related_context_repd_ref",
]);

export const SECTOR_INTELLIGENCE_CARTRIDGE_CONTRACT = Object.freeze({
  schema: "pipelinenews.sector-intelligence-cartridge.v3",
  generation: GENERATION,
  usage_context: USAGE_CONTEXT,
  usage_context_establishes_upstream_rights: false,
  activation: "dynamic-import-on-user-open; payload-fetch-on-first-topic-selection",
  topics: TOPICS,
  payload_schema: PAYLOAD_SCHEMA,
  startup_module_requests: 0,
  startup_payload_requests: 0,
  maximum_payload_requests: 1,
  maximum_rows_per_topic: 24,
  generic_news_rows_mutated: false,
  project_bindings: 0,
  eligible_for_news_signal: false,
  atman_runtime_dependency: false,
  deployment: "not-authorised",
});

const mounted = new WeakMap();

function element(tag, attributes = {}, text = null) {
  const node = document.createElement(tag);
  for (const [name, value] of Object.entries(attributes)) {
    if (name === "class") node.className = value;
    else node.setAttribute(name, String(value));
  }
  if (text !== null) node.textContent = String(text);
  return node;
}

function installStyles() {
  if (document.querySelector(`style[data-sector-generation="${GENERATION}"]`)) return;
  const style = document.createElement("style");
  style.dataset.sectorGeneration = GENERATION;
  style.textContent = `
    .sector-shell{border:1px solid #3e4650;background:#0d1117;color:#f0f4f8;margin:12px 0;padding:12px;min-width:0}
    .sector-head{display:flex;flex-wrap:wrap;gap:10px;justify-content:space-between;align-items:flex-start}
    .sector-head h2{color:#00ffff;font:700 17px/1.2 monospace;margin:0}
    .sector-head p{color:#b9c2cb;font:11px/1.45 monospace;margin:5px 0 0;max-width:900px}
    .sector-tabs{display:flex;gap:6px;overflow-x:auto;overscroll-behavior:contain;padding:12px 0}
    .sector-tabs button{background:#171d24;border:1px solid #65717c;color:#fff;cursor:pointer;flex:none;font:700 10px/1.2 monospace;min-height:44px;padding:8px 12px}
    .sector-tabs button[aria-selected="true"]{background:#00343b;border-color:#00ffff;color:#00ffff}
    .sector-list{display:grid;gap:8px;grid-template-columns:repeat(auto-fit,minmax(270px,1fr));min-width:0}
    .sector-card{background:#141a20;border:1px solid #343f49;min-width:0;padding:10px}
    .sector-card>a{align-items:center;color:#ffeb3b;display:inline-flex;font:700 12px/1.4 monospace;min-height:44px;overflow-wrap:anywhere;text-decoration:none}
    .sector-card>a:focus-visible,.sector-card>a:hover{text-decoration:underline}
    .sector-card p{color:#b8c0c8;font:10px/1.45 monospace;margin:6px 0;overflow-wrap:anywhere}
    .sector-card .sector-binding{border:1px solid #56616d;color:#00ff88;display:inline-block;font-weight:700;padding:4px 7px}
    .sector-message{border:1px dashed #52606d;color:#adb7c2;font:11px/1.45 monospace;padding:18px}
    @media (max-width:768px),((orientation:landscape) and (max-height:500px)){
      .sector-shell{padding:8px}.sector-list{grid-template-columns:1fr}.sector-card>a{min-height:44px}
    }
  `;
  document.head.appendChild(style);
}

async function sha256Hex(bytes) {
  const digest = await crypto.subtle.digest("SHA-256", bytes);
  return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");
}

function validateAsset(asset) {
  if (!asset || typeof asset !== "object") throw new Error("sector payload asset is missing");
  if (!/^data\/202609010145-sector-intelligence\.json$/u.test(asset.url)) throw new Error("sector payload URL changed");
  if (!Number.isSafeInteger(asset.bytes) || asset.bytes <= 0) throw new Error("sector payload byte count is invalid");
  if (!/^[a-f0-9]{64}$/u.test(asset.sha256)) throw new Error("sector payload digest is invalid");
}

function decodePayload(payload) {
  if (payload.schema !== PAYLOAD_SCHEMA || payload.generation !== GENERATION) throw new Error("sector payload identity mismatch");
  if (payload.usage_context !== USAGE_CONTEXT || payload.usage_context_establishes_upstream_rights !== false) {
    throw new Error("sector usage/right separation mismatch");
  }
  if (payload.derived_only_from_landed_parquet_duckdb_readback !== true) throw new Error("sector payload lacks landed-Parquet lineage");
  if (payload.project_bindings !== 0 || payload.eligible_for_news_signal !== false || payload.generic_news_rows_mutated !== false) {
    throw new Error("sector payload crossed the generic-news or project-binding boundary");
  }
  if (JSON.stringify(payload.fields) !== JSON.stringify(EXPECTED_FIELDS)) throw new Error("sector payload field contract changed");
  for (const field of FORBIDDEN_FIELDS) if (payload.fields.includes(field)) throw new Error(`query identity field entered sector payload: ${field}`);
  if (!Array.isArray(payload.rows)) throw new Error("sector payload rows are missing");
  const rows = payload.rows.map((values) => {
    if (!Array.isArray(values) || values.length !== EXPECTED_FIELDS.length) throw new Error("sector payload row width changed");
    const row = Object.fromEntries(EXPECTED_FIELDS.map((field, index) => [field, values[index]]));
    if (!/^GG2050-SECTOR-ITEM-[A-F0-9]{20}$/u.test(row.intelligence_item_id)) throw new Error("sector item identity changed");
    if (row.project_binding_count !== 0 || row.eligible_for_news_signal !== false) throw new Error("sector item attempted a project signal");
    if (!TOPICS.some(({ code, rank }) => code === row.topic_code && rank === row.topic_display_rank)) throw new Error("sector topic changed");
    for (const field of ["source_licence_id", "source_terms_url", "redistribution_rights", "attribution"]) {
      if (!row[field]) throw new Error(`source-specific rights field is empty: ${field}`);
    }
    const expectedLabel = row.generic_article_id
      ? "SECTOR CONTEXT ONLY — QUERY PROJECT IDENTITY REMOVED"
      : "SECTOR CONTEXT ONLY — NOT A PROJECT BINDING";
    if (row.binding_label !== expectedLabel) throw new Error("sector context label changed");
    return Object.freeze(row);
  });
  if (new Set(rows.map(({ intelligence_item_id, topic_code }) => `${intelligence_item_id}\u001f${topic_code}`)).size !== rows.length) {
    throw new Error("sector browser key collision");
  }
  for (const topic of TOPICS) {
    if (rows.filter(({ topic_code }) => topic_code === topic.code).length > payload.maximum_rows_per_topic) {
      throw new Error("sector browser topic row limit exceeded");
    }
  }
  return Object.freeze(rows);
}

async function loadPayload(asset) {
  validateAsset(asset);
  const response = await fetch(asset.url, { cache: "force-cache", credentials: "same-origin" });
  if (!response.ok) throw new Error(`sector payload request failed: ${response.status}`);
  const bytes = await response.arrayBuffer();
  if (bytes.byteLength !== asset.bytes) throw new Error("sector payload byte count mismatch");
  if (await sha256Hex(bytes) !== asset.sha256) throw new Error("sector payload digest mismatch");
  return decodePayload(JSON.parse(new TextDecoder().decode(bytes)));
}

function renderRows(container, rows) {
  container.replaceChildren();
  if (!rows.length) {
    container.appendChild(element("div", { class: "sector-message" }, "No retained source metadata is available for this topic."));
    return;
  }
  for (const row of rows) {
    const card = element("article", { class: "sector-card", "data-sector-item-id": row.intelligence_item_id });
    const title = element("a", { href: row.canonical_url, target: "_blank", rel: "noopener noreferrer" }, row.title);
    const rights = element("p");
    const terms = element("a", { href: row.source_terms_url, target: "_blank", rel: "noopener noreferrer" }, row.source_licence_id);
    rights.append(document.createTextNode(`${row.attribution} · ${row.redistribution_rights} · `), terms);
    card.append(title);
    if (row.summary) card.appendChild(element("p", {}, row.summary));
    if (row.item_kind === "CONTEXT_METRIC") {
      const range = row.value_min === row.value_max ? `${row.value_min}` : `${row.value_min}–${row.value_max}`;
      card.appendChild(element("p", {}, `PINNED OWNER CONTEXT METRIC · ${range} ${row.unit}`));
    }
    card.append(
      rights,
      element("p", {}, `${row.evidence_class} · ${String(row.source_published_at || row.observed_at).slice(0, 10)} · ${row.staleness_state}`),
      element("p", { class: "sector-binding" }, row.binding_label),
    );
    container.appendChild(card);
  }
}

export function mountSectorIntelligence({ host, payloadAsset }) {
  if (!(host instanceof HTMLElement)) throw new Error("sector intelligence host is missing");
  if (mounted.has(host)) return mounted.get(host);
  validateAsset(payloadAsset);
  installStyles();
  const shell = element("section", { class: "sector-shell", "aria-label": "Sector intelligence" });
  const header = element("div", { class: "sector-head" });
  const heading = element("div");
  heading.append(
    element("h2", {}, "SOURCE-AND-EVIDENCE SECTOR INTELLIGENCE"),
    element("p", {}, "Ventus Ltd application context: non-commercial open source. Upstream rights remain source-specific and are shown on every item."),
    element("p", {}, "Sector context is separate from the 136-headline newspaper and cannot create or alter REPD project identity."),
  );
  const status = element("p", { "data-sector-status": "WAIT" }, "WAIT · choose one topic; no payload has been requested.");
  header.append(heading, status);
  const tabs = element("div", { class: "sector-tabs", role: "tablist", "aria-label": "Sector topics" });
  const list = element("div", { class: "sector-list", role: "tabpanel" });
  list.appendChild(element("div", { class: "sector-message" }, "Choose a topic to load one compact DuckDB/Parquet-derived cartridge."));
  const buttons = new Map();
  let payloadPromise = null;
  let payloadRequests = 0;
  async function select(topic) {
    for (const [code, button] of buttons) button.setAttribute("aria-selected", String(code === topic));
    status.dataset.sectorStatus = "LOAD";
    status.textContent = `LOAD · ${topic}`;
    list.replaceChildren(element("div", { class: "sector-message" }, "Loading bounded sector metadata…"));
    try {
      if (!payloadPromise) {
        payloadRequests += 1;
        if (payloadRequests > 1) throw new Error("sector payload request budget exceeded");
        payloadPromise = loadPayload(payloadAsset);
      }
      const allRows = await payloadPromise;
      const rows = allRows.filter(({ topic_code }) => topic_code === topic);
      renderRows(list, rows);
      status.dataset.sectorStatus = rows.length ? "OK" : "EMPTY";
      status.textContent = `${rows.length ? "OK" : "EMPTY"} · ${rows.length} rows · landed ZSTD Parquet readback`;
    } catch (error) {
      status.dataset.sectorStatus = "FAIL";
      status.textContent = "FAIL · sector topic unavailable; core newspaper and project register are unchanged.";
      list.replaceChildren(element("div", { class: "sector-message" }, "Sector intelligence failed closed."));
      throw error;
    }
  }
  for (const topic of TOPICS) {
    const button = element("button", { type: "button", role: "tab", "aria-selected": "false", "data-sector-topic": topic.code }, topic.label);
    button.addEventListener("click", () => select(topic.code).catch((error) => console.error("sector intelligence", error)));
    buttons.set(topic.code, button);
    tabs.appendChild(button);
  }
  shell.append(header, tabs, list);
  host.replaceChildren(shell);
  host.hidden = false;
  host.dataset.sectorIntelligenceState = "ready";
  const result = Object.freeze({ shell, tabs, list, status, buttons, select, get payloadRequests() { return payloadRequests; } });
  mounted.set(host, result);
  return result;
}