GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / automation/pipeline_release/tests

Verify and 6 more files

A Python command-line tool in the pipeline release folder of GlobalGrid2050 that reads browser, probes, GridAtlas state and versions.

667 lines of Python and JavaScript and CSS from globalgrid2050, in 7 files. Topic: Electricity markets and data pipelines. Section 817 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. Edition History Test test · globalgrid2050 / automation/pipeline_release/tests/edition_history.test.mjs lines 1–96
  2. Test Compact Successor test · globalgrid2050 / automation/pipeline_release/tests/test_compact_successor.py lines 1–45
  3. Test Registry Metadata test · globalgrid2050 / automation/pipeline_release/tests/test_registry_metadata.py lines 1–125
  4. Verify automation · globalgrid2050 / automation/pipeline_release/verify.py lines 1–232
  5. Canvas render · globalgrid2050 / automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/canvas.mjs lines 1–53
  6. Model storage · globalgrid2050 / automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/model.mjs lines 1–105
  7. Automation — Price Daily UI Style Sheet render · globalgrid2050 / automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/styles.css lines 1–11

Edition History Test

A test in the tests folder of GlobalGrid2050 that checks Edition History. It is built from the write step (`write`).

testglobalgrid2050 / automation/pipeline_release/tests/edition_history.test.mjs · lines 1–96 of 96 · Entry point · pattern fixture (shared by 30 files)

What it does
It tests its inputs. Defines frozen, fixture, git, write. Uses libraries node:assert/strict, node:child_process, node:fs, node:os, node:path. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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: GlobalGrid2050 V932 Preview Acceptance Workflow (globalgrid2050); GlobalGrid2050 V933 Preview Acceptance Workflow (globalgrid2050).
What it achieves
Defines `frozen`, `fixture`, `git` and 1 more. It writes `uk_renewables_pipeline/v7/index.html`.
Why it matters
Run by GlobalGrid2050 V932 Preview Acceptance Workflow and GlobalGrid2050 V933 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/pipeline_release/tests · test
Uses
Edition History (script call), node:assert/strict, node:child_process, node:fs, node:os, node:path, node:test
Used by
run by GlobalGrid2050 V932 Preview Acceptance Workflow (workflow run), run by GlobalGrid2050 V933 Preview Acceptance Workflow (workflow run)
Produces
frozen, fixture, git, write
Defines here
frozen, fixture, git, write
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_release/tests/edition_history.test.mjs:1-96 · blob d00937b173b75797cf5076374b6c19b463925b74 · 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
import assert from 'node:assert/strict';
import {execFileSync} from 'node:child_process';
import {mkdtempSync,mkdirSync,writeFileSync,unlinkSync,renameSync,rmSync,realpathSync} from 'node:fs';
import {tmpdir} from 'node:os';
import {basename,dirname,join,resolve} from 'node:path';
import test from 'node:test';
import {protectedEditionChanges} from '../edition_history.mjs';

const PREFIX='globalgrid2050-edition-history-';
const editions=['202601010000','202611170512','999999999999'];
const frozen=id=>'uk_renewables_pipeline/'+id+'/index.html';
function fixture(run,{numeric=true}={}) {
  const parent=realpathSync(tmpdir()),repo=mkdtempSync(join(parent,PREFIX));
  const git=args=>execFileSync('git',args,{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim();
  const write=(path,text='original\n')=>{const target=resolve(repo,path);mkdirSync(dirname(target),{recursive:true});writeFileSync(target,text);};
  try {
    git(['init','--quiet']);git(['config','user.email','history-test@example.invalid']);git(['config','user.name','Edition history tests']);
    git(['config','core.autocrlf','false']);git(['config','core.quotepath','true']);
    write('.gitignore','*.ignored\n');write('uk_renewables_pipeline/v7/index.html');
    if(numeric)for(const id of editions)write(frozen(id));
    git(['add','--all']);git(['commit','--quiet','-m','Frozen baseline']);
    const base=git(['rev-parse','HEAD']),changes=()=>protectedEditionChanges({cwd:repo,base});
    return run({repo,git,write,base,changes});
  } finally {
    // Resolve and verify the exact generated directory before recursive cleanup,
    // including on Windows. Never delete a caller-supplied repository path.
    const target=realpathSync(repo);
    assert.equal(dirname(target),parent,'Temporary repository must remain inside its verified parent');
    assert.ok(basename(target).startsWith(PREFIX),'Temporary repository prefix must match');
    rmSync(target,{recursive:true,force:true});
  }
}

test('unchanged baseline has no protected changes',()=>fixture(({changes})=>assert.deepEqual(changes(),[])));

test('new committed, staged and untracked edition files are append-only additions',()=>fixture(({git,write,changes})=>{
  write('uk_renewables_pipeline/202611170513/index.html');git(['add','--all']);git(['commit','--quiet','-m','Append edition']);
  write('uk_renewables_pipeline/202611170514/index.html');git(['add','--all']);
  write('uk_renewables_pipeline/202611170515/source note.txt');
  assert.deepEqual(changes(),[]);
}));

for(const id of editions)test('baseline edition '+id+' is protected regardless of age or current/future label',()=>fixture(({write,changes})=>{
  write(frozen(id),'modified\n');assert.deepEqual(changes(),[frozen(id)]);
}));

test('deleting an existing file is rejected',()=>fixture(({repo,changes})=>{
  unlinkSync(resolve(repo,frozen(editions[0])));assert.deepEqual(changes(),[frozen(editions[0])]);
}));

test('untracked insertion inside any frozen edition is rejected',()=>fixture(({write,changes})=>{
  const path='uk_renewables_pipeline/'+editions[1]+'/extra/new source.json';write(path,'{}\n');assert.deepEqual(changes(),[path]);
}));

test('moving an old file into a new edition still reports the original deletion',()=>fixture(({repo,write,git,changes})=>{
  const destination='uk_renewables_pipeline/202611170513/index.html';write(destination);
  unlinkSync(resolve(repo,destination));renameSync(resolve(repo,frozen(editions[0])),resolve(repo,destination));git(['add','--all']);
  assert.deepEqual(changes(),[frozen(editions[0])]);
}));

test('NUL paths preserve Unicode and spaces without Git quote escaping',()=>fixture(({write,git,changes})=>{
  const original='uk_renewables_pipeline/'+editions[0]+'/source receipts/énergie 电力.txt';
  const inserted='uk_renewables_pipeline/'+editions[0]+'/source receipts/未確認 note.txt';
  write(original);git(['add','--all']);git(['commit','--quiet','-m','Add protected Unicode baseline']);
  const base=git(['rev-parse','HEAD']);write(original,'changed\n');write(inserted);
  assert.deepEqual(protectedEditionChanges({cwd:git(['rev-parse','--show-toplevel']),base}),[original,inserted].sort());
}));

test('a restored working file cannot conceal a staged mutation',()=>fixture(({write,git,changes})=>{
  write(frozen(editions[0]),'staged mutation\n');git(['add','--all']);write(frozen(editions[0]));
  assert.deepEqual(changes(),[frozen(editions[0])]);
}));

test('ignored insertions are excluded but tracked changes remain protected',()=>fixture(({write,changes})=>{
  write('uk_renewables_pipeline/'+editions[0]+'/cache.ignored');assert.deepEqual(changes(),[]);
  write(frozen(editions[0]),'changed\n');assert.deepEqual(changes(),[frozen(editions[0])]);
}));

test('non-numeric directories and unrelated source files are outside edition history',()=>fixture(({write,changes})=>{
  write('uk_renewables_pipeline/v7/index.html','changed\n');write('automation/new-test.mjs');assert.deepEqual(changes(),[]);
}));

test('missing or invalid pinned bases fail closed',()=>fixture(({repo,base})=>{
  for(const invalid of [undefined,null,'','missing-history-ref','-invalid',base+':missing'])
    assert.throws(()=>protectedEditionChanges({cwd:repo,base:invalid}),/pinned base/);
}));

test('a valid commit without numeric baseline editions fails closed',()=>fixture(({changes})=>{
  assert.throws(changes,/Cannot resolve immutable edition history/);
},{numeric:false}));

test('a missing baseline pipeline tree fails closed',()=>fixture(({repo,git,write})=>{
  git(['checkout','--orphan','empty-baseline']);git(['rm','-r','--quiet','--cached','.']);write('unrelated.txt');
  git(['add','--','unrelated.txt']);git(['commit','--quiet','-m','No pipeline baseline']);
  assert.throws(()=>protectedEditionChanges({cwd:repo,base:git(['rev-parse','HEAD'])}),/Cannot resolve immutable edition history/);
}));

Test Compact Successor

A test in the tests folder of GlobalGrid2050 that checks New Version.

testglobalgrid2050 / automation/pipeline_release/tests/test_compact_successor.py · lines 1–45 of 45 · Entry point

What it does
It tests its inputs. Defines test_create_successor_from_real_compact_or_legacy_shell. Uses libraries sys, pathlib, pytest. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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 6 files: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 V929 Preview Acceptance Workflow (globalgrid2050); GlobalGrid2050 V930 Preview Acceptance Workflow (globalgrid2050); GlobalGrid2050 V931 Preview Acceptance Workflow (globalgrid2050); and 2 more.
What it achieves
Successor editions must preserve the approved compact shell and frozen parent.
Why it matters
Run by 6 workflows and scripts, including GlobalGrid2050 Project Signals Acid Workflow, GlobalGrid2050 V929 Preview Acceptance Workflow and GlobalGrid2050 V930 Preview Acceptance Workflow.
Application
globalgrid2050 · automation/pipeline_release/tests · test
Uses
New Version (sys.path import), sys, pathlib, pytest
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run), run by GlobalGrid2050 V929 Preview Acceptance Workflow (workflow run), run by GlobalGrid2050 V930 Preview Acceptance Workflow (workflow run), run by GlobalGrid2050 V931 Preview Acceptance Workflow (workflow run), run by GlobalGrid2050 V932 Preview Acceptance Workflow (workflow run), run by GlobalGrid2050 V933 Preview Acceptance Workflow (workflow run)
Produces
test_create_successor_from_real_compact_or_legacy_shell
Defines here
test_create_successor_from_real_compact_or_legacy_shell
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_release/tests/test_compact_successor.py:1-45 · blob a287351c1880b8b69a35ae2e2f8137ea4f052159 · 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
"""Successor editions must preserve the approved compact shell and frozen parent."""
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0,str(ROOT / "automation/pipeline_release"))
import new_version

@pytest.mark.parametrize("parent_id,version,next_version", [("202611161757", "V9.28", "V9.29"), ("202611161747", "V9.27", "V9.29"), ("202611162354", "V9.29", "V9.30")])
def test_create_successor_from_real_compact_or_legacy_shell(tmp_path, monkeypatch, parent_id, version, next_version):
    """The approved compact shell has no former giant h1/strong metadata line."""
    source = ROOT / "uk_renewables_pipeline" / parent_id
    parent = tmp_path / parent_id
    (parent / "tests").mkdir(parents=True)
    original = (source / "index.html").read_bytes()
    (parent / "index.html").write_bytes(original)
    suffix = version.removeprefix("V").replace(".", "_")
    for name in (f"run_v{suffix}.sh", f"check_v{suffix}.mjs"):
        (parent / "tests" / name).write_bytes((source / "tests" / name).read_bytes())
    monkeypatch.setattr(new_version, "PIPELINE", tmp_path)
    monkeypatch.setattr(new_version, "load_registry", lambda: {"fixture_owner": "202611132345", "versions": [
        {"id": parent_id, "version": version, "runner": f"tests/run_v{suffix}.sh"}]})
    monkeypatch.setattr(new_version, "tree_hash", lambda _: "f" * 40)
    new_version.create("202611170001", next_version, "Existing source layers", "RELEASE CANDIDATE")
    result = (tmp_path / "202611170001/index.html").read_text(encoding="utf8")
    assert (parent / "index.html").read_bytes() == original
    assert '<a href="../' + parent_id + '/">' in result
    next_suffix = next_version.removeprefix("V").replace(".", "_")
    assert (tmp_path / f"202611170001/tests/run_v{next_suffix}.sh").exists()
    assert (tmp_path / f"202611170001/tests/check_v{next_suffix}.mjs").exists()
    if version in ("V9.28", "V9.29"):
        assert 'data-edition="202611170001"' in result
        assert f'<title>GlobalGrid2050 | Pipeline News {next_version} · 202611170001</title>' in result
        assert f'<small>PIPELINE NEWS · {next_version}</small>' in result
        assert result.count('<section') == 2
        if version == "V9.29":
            assert '<aside' not in result
            navigation = result.split('<nav class="release-links"', 1)[1].split('</nav>', 1)[0]
            assert navigation.count('<a ') == 6
            assert navigation.count('../versions.html') == 1
            assert navigation.count('PREVIOUS EDITION') == 1
    else:
        assert '<h1>UK RENEWABLES PIPELINE 202611170001</h1>' in result
        assert 'V9.29 RELEASE CANDIDATE · REPD Q3 2026' in result

Test Registry Metadata

A test in the tests folder of GlobalGrid2050 that checks Automation — Pipeline Release and Verify.

testglobalgrid2050 / automation/pipeline_release/tests/test_registry_metadata.py · lines 1–125 of 125 · Entry point

What it does
It tests its inputs. Defines 13 functions or classes, including RegistryMetadataTests, setUp, cleanup_temp, write, bad_string_record. Uses libraries copy, html, json, pathlib, sys. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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 registry.json.
Downstream impact
Used directly by 3 files: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Publish Pipeline V923 Ledger Workflow (globalgrid2050); GlobalGrid2050 Verify Pipeline Versions Workflow (globalgrid2050).
What it achieves
It sets up (`setUp`) and is built from the registry metadata tests class (`RegistryMetadataTests`) and the cleanup temp helper (`cleanup_temp`). Malformed CI records must fail before the full release/browser verification.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow, GlobalGrid2050 Publish Pipeline V923 Ledger Workflow and GlobalGrid2050 Verify Pipeline Versions Workflow.
Application
globalgrid2050 · automation/pipeline_release/tests · test
Uses
Automation — Pipeline Release (sys.path import), Verify (sys.path import), copy, html, json, pathlib, sys, tempfile, unittest
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run), run by GlobalGrid2050 Publish Pipeline V923 Ledger Workflow (workflow run), run by GlobalGrid2050 Verify Pipeline Versions Workflow (workflow run)
Produces
RegistryMetadataTests
Defines here
RegistryMetadataTests, setUp, cleanup_temp, write, bad_string_record, test_missing_null_empty_and_extended_metadata_round_trip_unchanged, test_reported_url_string_is_rejected_with_release_and_field, test_verify_rejects_string_before_scratch_tree_or_runner_work, test_save_rejects_bad_metadata_before_existing_bytes_change, test_other_non_object_ci_values_are_rejected, test_optional_renderer_fields_require_strings, test_string_content_and_extra_metadata_are_not_rewritten_or_enum_limited, test_actual_corrected_registry_metadata_renders_all_versions
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_release/tests/test_registry_metadata.py:1-125 · blob 682881c97e0d8f1f0a9b1438a31dee7150232b73 · 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
"""Malformed CI records must fail before the full release/browser verification."""
import copy
import html
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest import mock

RELEASE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(RELEASE))
import common
import verify

ACTUAL_REGISTRY = common.REGISTRY


class RegistryMetadataTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory(prefix="pn-registry-metadata-")
        self.parent = Path(tempfile.gettempdir()).resolve()
        self.folder = Path(self.temp.name).resolve()
        self.assertEqual(self.folder.parent, self.parent)
        self.assertTrue(self.folder.name.startswith("pn-registry-metadata-"))
        self.addCleanup(self.cleanup_temp)
        self.registry = self.folder / "registry.json"
        patcher = mock.patch.object(common, "REGISTRY", self.registry)
        patcher.start()
        self.addCleanup(patcher.stop)

    def cleanup_temp(self):
        # Confirm the exact generated path before the standard-library recursive
        # cleanup on Windows; these tests never clean a caller-supplied path.
        target = Path(self.temp.name).resolve()
        self.assertEqual(target.parent, self.parent)
        self.assertTrue(target.name.startswith("pn-registry-metadata-"))
        self.temp.cleanup()

    def write(self, data):
        self.registry.write_text(json.dumps(data), encoding="utf-8")

    def bad_string_record(self):
        return {"versions": [{"id": "202611170324", "ci":
            "https://github.com/Ventusltd/globalgrid2050/actions/runs/44016860896"}]}

    def test_missing_null_empty_and_extended_metadata_round_trip_unchanged(self):
        data = {"versions": [
            {"id": "missing"}, {"id": "null", "ci": None},
            {"id": "empty", "ci": {}},
            {"id": "legacy", "ci": {"workflow": "Original workflow", "pull_request": 68,
                "conclusion": "success", "note": "Original provenance retained"}},
        ]}
        common.save_registry(data)
        self.assertEqual(common.load_registry(), data)

    def test_reported_url_string_is_rejected_with_release_and_field(self):
        self.write(self.bad_string_record())
        with self.assertRaisesRegex(ValueError, "202611170324: ci must be an object or null"):
            common.load_registry()

    def test_verify_rejects_string_before_scratch_tree_or_runner_work(self):
        self.write(self.bad_string_record())
        with mock.patch.object(verify.tempfile, "mkdtemp") as scratch, \
                mock.patch.object(verify, "tree_hash") as tree, \
                mock.patch.object(verify, "run") as runner:
            with self.assertRaisesRegex(ValueError, "202611170324: ci must be an object or null"):
                verify.main()
            scratch.assert_not_called()
            tree.assert_not_called()
            runner.assert_not_called()

    def test_save_rejects_bad_metadata_before_existing_bytes_change(self):
        original = b"existing registry bytes\n"
        self.registry.write_bytes(original)
        with self.assertRaisesRegex(ValueError, "ci must be an object or null"):
            common.save_registry(self.bad_string_record())
        self.assertEqual(self.registry.read_bytes(), original)

    def test_other_non_object_ci_values_are_rejected(self):
        for value in ([], 1, True, False):
            with self.subTest(value=value):
                with self.assertRaisesRegex(ValueError, "ci must be an object or null"):
                    common.validate_registry_metadata({"versions": [{"id": "release", "ci": value}]})

    def test_optional_renderer_fields_require_strings(self):
        for field in ("url", "conclusion"):
            for value in (None, True, 1, [], {}):
                with self.subTest(field=field, value=value):
                    with self.assertRaisesRegex(ValueError, rf"ci\.{field} must be a string"):
                        common.validate_registry_metadata({"versions": [{"id": "release", "ci": {field: value}}]})

    def test_string_content_and_extra_metadata_are_not_rewritten_or_enum_limited(self):
        data = {"versions": [{"id": "release", "ci": {"url": "../legacy-receipt.html#run",
            "conclusion": "provider_specific_result", "source_commit": "original", "extra": {"keep": True}}}]}
        before = copy.deepcopy(data)
        self.assertIs(common.validate_registry_metadata(data), data)
        common.save_registry(data)
        self.assertEqual(common.load_registry(), before)

    def test_actual_corrected_registry_metadata_renders_all_versions(self):
        original = json.loads(ACTUAL_REGISTRY.read_text(encoding="utf-8"))
        self.write(original)
        reg = common.load_registry()
        self.assertEqual(reg, original)
        v932 = next(v for v in reg["versions"] if v["id"] == "202611170324")
        self.assertIsInstance(v932["ci"], dict)
        self.assertEqual(v932["ci"]["url"], "https://github.com/Ventusltd/globalgrid2050/actions/runs/44016860896")
        # Use actual release/CI metadata with explicitly unexecuted verdicts.
        # This exercises the real renderer, not the expensive release runners.
        doc = {"generated_at": "metadata-only regression fixture", "versions": []}
        for version in reversed(reg["versions"]):
            doc["versions"].append({**version, "ci": version.get("ci"),
                "state": version.get("state", "published"), "url": version["id"] + "/",
                "verdict": "NOT_RUN", "browser_checked": False,
                "known_faults": version.get("known_faults", []),
                "checks": {"map_contract": {"rows": reg["expected_record_count"], "pass": False}}})
        rendered = verify.render(doc)
        self.assertEqual(rendered.count('<tr class="not_run">'), len(reg["versions"]))
        self.assertIn(html.escape(v932["ci"]["url"]), rendered)
        self.assertIn("SUCCESS</a>", rendered)


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

Verify

A Python command-line tool in the pipeline release folder of GlobalGrid2050 that reads browser, probes, GridAtlas state and versions.

automationglobalgrid2050 / automation/pipeline_release/verify.py · lines 1–232 of 232 · Entry point

What it does
It loads browser, probes, GridAtlas state and versions. Defines run, main, state_line, render. Uses libraries html, json, os, subprocess, sys. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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 browser.json; JSON file probes.json; JSON file gridatlas_state.json; JSON file versions.json; command-line arguments. Out: JSON file probes.json; JSON file versions.json.
Downstream impact
Used directly by 4 files: Test Registry Metadata (globalgrid2050); GlobalGrid2050 Publish Pipeline V923 Ledger Workflow (globalgrid2050); GlobalGrid2050 V923 Six Hour Python Repair Workflow (globalgrid2050); GlobalGrid2050 Verify Pipeline Versions Workflow (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It is built from the run step (`run`), the state line helper (`state_line`) and the render step (`render`). Verify every Pipeline News version from onward and compare each with its parent.
Why it matters
Run by GlobalGrid2050 Publish Pipeline V923 Ledger Workflow, GlobalGrid2050 V923 Six Hour Python Repair Workflow and GlobalGrid2050 Verify Pipeline Versions Workflow. Checked by Test Registry Metadata.
Application
globalgrid2050 · automation/pipeline_release · Python CLI
Uses
Automation — Pipeline Release (import), Feature Contracts (import), Check Deeplinks (script call), GridAtlas Resolve (script call), Browser Check (script call), html, json, os, subprocess, sys, tempfile, datetime, pathlib
Used by
imported by Test Registry Metadata (sys.path import), run by GlobalGrid2050 Publish Pipeline V923 Ledger Workflow (workflow run), run by GlobalGrid2050 V923 Six Hour Python Repair Workflow (workflow run), run by GlobalGrid2050 Verify Pipeline Versions Workflow (workflow run)
Produces
run, main, state_line, render
Defines here
run, main, state_line, render
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/pipeline_release/verify.py:1-232 · blob 5f6a004c76bd9a386c501c28af761d69d301d7e8 · GitHub at these lines
State
achieves: comment · 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
"""Verify every Pipeline News version from 202611132345 onward and compare each with its parent.

  verify.py                 offline checks, print the verdicts
  verify.py --browser       also load every page in headless Chrome (desktop and phone)
  verify.py --write         write uk_renewables_pipeline/versions.json and versions.html
  verify.py --check         exit 1 if any version fails
  verify.py --gridatlas-refs <file>   also resolve every MAP link's REPD reference against a
                            GridAtlas register file (see gridatlas_resolve.py)

Per version: (1) the folder's git tree hash is one pinned in registry.json (a published folder
is never edited); (2) its own runner passes; (3) MAP contract and Grid Engine deep-link contract
for every row; (4) against its parent: every row's MAP href identical, data hashes identical
unless the version declares a data change, every feature of every ancestor still present;
(5) in the browser: the page completes with the expected record count, no uncaught errors, no
failed same-origin requests, no sideways overflow on a phone.
"""
import html
import json
import os
import subprocess
import sys
import tempfile
from datetime import datetime, timezone
from pathlib import Path

from common import HERE, PIPELINE, ROOT, data_digest, load_registry, tree_hash
from feature_contracts import check_features

ARGS = sys.argv[1:]
BROWSER, WRITE, CHECK = "--browser" in ARGS, "--write" in ARGS, "--check" in ARGS
GRIDATLAS = ARGS[ARGS.index("--gridatlas-refs") + 1] if "--gridatlas-refs" in ARGS else None


def run(cmd, **kw):
    p = subprocess.run(cmd, capture_output=True, text=True, **kw)
    tail = (p.stdout.strip().splitlines() or [""])[-1] if p.returncode == 0 else (p.stderr.strip().splitlines() or p.stdout.strip().splitlines() or [""])[-1]
    return p.returncode == 0, tail[:400], p.stdout


def main():
    reg = load_registry()
    versions = reg["versions"]
    by_id = {v["id"]: v for v in versions}
    scratch = Path(tempfile.mkdtemp(prefix="pn-verify-"))
    hrefs, digests, results, migration_probes = {}, {}, {}, {}

    for v in versions:
        vid, folder = v["id"], PIPELINE / v["id"]
        checks = {}
        actual = tree_hash(vid)
        checks["tree_unchanged"] = {"pass": actual in v["trees"], "tree": actual}
        ok, tail, _ = run(["bash", str(folder / v["runner"])])
        checks["runner"] = {"pass": ok, "runner": v["runner"], "last_line": tail.replace(str(ROOT), "<repository>")}
        href_file = scratch / f"{vid}.hrefs.json"
        ok, tail, out = run(["node", str(HERE / "check_deeplinks.mjs"), str(folder), str(href_file)])
        try:
            link = json.loads(out.strip().splitlines()[-1])
        except Exception:
            link = {"pass": False, "error": tail}
        checks["map_contract"] = {"pass": link.get("map", {}).get("failed") == 0 and link.get("rows") == reg["expected_record_count"],
                                  "rows": link.get("rows"), "ok": link.get("map", {}).get("ok"), "with_point": link.get("with_point"), "without_point": link.get("without_point")}
        checks["grid_engine_contract"] = {"pass": link.get("grid_engine", {}).get("failed") == 0 and link.get("rows") == reg["expected_record_count"],
                                          "ok": link.get("grid_engine", {}).get("ok"), "examples": link.get("examples", [])}
        hrefs[vid] = json.loads(href_file.read_text()) if href_file.exists() else {}
        digests[vid] = data_digest(folder)

        parent = by_id.get(v["parent"])
        if parent:
            same = sum(1 for ref, href in hrefs[vid].items() if hrefs[parent["id"]].get(ref) == href)
            checks["map_links_identical_to_parent"] = {"pass": same == len(hrefs[vid]) == len(hrefs[parent["id"]]) == reg["expected_record_count"],
                                                       "identical": same, "rows": len(hrefs[vid]), "parent": parent["id"]}
            checks["data_unchanged_from_parent"] = {"pass": bool(v.get("data_changed")) or digests[vid] == digests[parent["id"]],
                                                    "data_digest": digests[vid], "declared_change": bool(v.get("data_changed"))}
        else:
            checks["data_unchanged_from_parent"] = {"pass": True, "data_digest": digests[vid], "declared_change": True, "note": "parent is outside the checked range"}
        checks["features_kept"], migration_probes[vid] = check_features(v, by_id, PIPELINE)
        if reg.get("size_budget_mb") and vid >= reg.get("size_budget_from", ""):
            size = sum((folder / rel).stat().st_size for rel in __import__("common").walk(folder))
            checks["size_budget"] = {"pass": size <= reg["size_budget_mb"] * 1024 * 1024, "bytes": size, "budget_mb": reg["size_budget_mb"]}
        results[vid] = checks

    if GRIDATLAS:
        for v in versions:
            ok, tail, out = run([sys.executable, str(HERE / "gridatlas_resolve.py"), str(PIPELINE / v["id"]), GRIDATLAS, "--summary"])
            try:
                results[v["id"]]["gridatlas_resolves"] = json.loads(out)
            except Exception:
                results[v["id"]]["gridatlas_resolves"] = {"pass": False, "error": tail}

    if BROWSER:
        port = os.environ.get("VERIFY_PORT", "8765")
        server = subprocess.Popen([sys.executable, "-m", "http.server", port, "--bind", "127.0.0.1"], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        try:
            out_file = scratch / "browser.json"
            probes = {}
            for v in versions:
                chain, node, gone = [], v, set()
                while node:
                    gone |= set(node.get("removed_probes", []))
                    chain = [p for p in node.get("browser_probes", []) if p["name"] not in gone] + chain
                    node = by_id.get(node["parent"])
                # Migrations add mandatory executable checks, not removable aliases.
                probes[v["id"]] = chain + migration_probes[v["id"]]
            (scratch / "probes.json").write_text(json.dumps(probes))
            os.environ["PROBES_FILE"] = str(scratch / "probes.json")
            p = subprocess.run(["node", str(HERE / "browser_check.mjs"), f"http://127.0.0.1:{port}/uk_renewables_pipeline/", str(out_file)] + [v["id"] for v in versions], text=True)
            pages = json.loads(out_file.read_text()) if out_file.exists() else {}
        finally:
            server.terminate()
        csv_seen = {}
        for v in versions:
            views = pages.get(v["id"], [])
            summary, good = [], len(views) == 2
            for r in views:
                same_origin = [f for f in r.get("failed_same_origin", []) if not f.endswith("/favicon.ico")]
                okv = bool(r.get("complete")) and r.get("record_count") == reg["expected_record_count"] and not r.get("page_errors") and not same_origin and not (r.get("viewport") == "phone" and r.get("overflow"))
                drawn = r.get("drawn_map_links") or []
                drawn_ok = bool(drawn) and all(hrefs[v["id"]].get(ref) == href for ref, href in drawn)
                okv = okv and drawn_ok
                good = good and okv
                summary.append({"viewport": r.get("viewport"), "pass": okv, "record_count": r.get("record_count"), "rows_drawn": r.get("rows_drawn"),
                                "page_errors": r.get("page_errors", [r.get("error")]), "console_errors": r.get("console_errors", []),
                                "failed_same_origin": same_origin, "failed_external": r.get("failed_external", []), "overflow": r.get("overflow"),
                                "map_links_drawn": len(drawn), "map_links_drawn_equal_contract_href": drawn_ok, "first_map_link": r.get("first_map_link"), "features_seen": r.get("features")})
            results[v["id"]]["browser"] = {"pass": good, "views": summary}
            if probes.get(v["id"]):
                seen = [dict(p, viewport=r.get("viewport")) for r in views for p in (r.get("probes") or [])]
                for p in seen:
                    if p.get("ref") and p.get("map_href") is not None and p.get("pass") and hrefs[v["id"]].get(p["ref"]) != p["map_href"]:
                        p["pass"], p["detail"] = False, "the row's MAP link is not the contract href"
                external = bool(os.environ.get("GITHUB_ACTIONS")) or os.environ.get("PROBE_EXTERNAL") == "1"
                active = [p for p in probes[v["id"]] if external or not p.get("needs_external")]
                expected = sum(1 for p in active if not p.get("block")) * 2 + sum(1 for p in active if p.get("block"))
                results[v["id"]]["feature_probes"] = {"pass": len(seen) == expected and all(p.get("pass") for p in seen), "probes": len(seen), "expected": expected, "skipped_need_internet": len(probes[v["id"]]) - len(active),
                                                      "results": [{k: p.get(k) for k in ("name", "viewport", "pass", "detail", "link")} for p in seen]}
            csv = next((r.get("csv") for r in views if r.get("csv")), None) or {"error": "not exported"}
            parent_csv = csv_seen.get(v["parent"])
            csv_ok = csv.get("rows") == reg["expected_record_count"] and (parent_csv is None or parent_csv.get("header_sha256") == csv.get("header_sha256"))
            results[v["id"]]["csv_export"] = {"pass": csv_ok, "rows": csv.get("rows"), "header_sha256": csv.get("header_sha256"), "body_sha256": csv.get("body_sha256"),
                                              "columns_same_as_parent": None if parent_csv is None else parent_csv.get("header_sha256") == csv.get("header_sha256"),
                                              "body_same_as_parent": None if parent_csv is None else parent_csv.get("body_sha256") == csv.get("body_sha256"), "error": csv.get("error")}
            csv_seen[v["id"]] = csv

    state_file = HERE / "gridatlas_state.json"
    now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    doc = {"schema": "globalgrid2050.pipeline-news.versions.v1", "generated_at": now,
           "generated_by": "automation/pipeline_release/verify.py" + (" --browser" if BROWSER else ""),
           "where_run": "GitHub Actions" if os.environ.get("GITHUB_ACTIONS") else "release train workspace before publication",
           "note": "Every Pipeline News version from 202611132345 onward, newest first. Old versions stay published. "
                   "'verdict' is this tool's result when the file was written; 'ci' is the result of the Verify Pipeline News versions workflow on the pull request that published the version, recorded in the following version.",
           "release_candidate": reg.get("release_candidate"),
           "map_link_state": json.loads(state_file.read_text()) if state_file.exists() else None, "versions": []}
    failed = []
    for v in reversed(versions):
        checks = results[v["id"]]
        verdict = "PASS" if all(c.get("pass") for c in checks.values()) else "FAIL"
        if verdict == "FAIL":
            failed.append(v["id"])
        doc["versions"].append({"id": v["id"], "version": v["version"], "parent": v["parent"], "date": v["date"], "state": v.get("state", "published"),
                                "added": v["added"], "data_changed": v["data_changed"], "url": f"{v['id']}/", "tree": v["trees"],
                                "verdict": verdict, "browser_checked": BROWSER, "checks": checks, "ci": v.get("ci"),
                                "merge_commit": v.get("merge_commit"), "known_faults": v.get("known_faults", []),
                                "datacentre_features": v.get("datacentre_features")})
        print(f"{v['id']} {v['version']}: {verdict} " + " ".join(f"{k}={'ok' if c.get('pass') else 'FAIL'}" for k, c in checks.items()))
        for k, c in checks.items():
            if not c.get("pass"):
                print(f"  {k}: {json.dumps(c, ensure_ascii=False)[:1500]}")
    if WRITE:
        (PIPELINE / "versions.json").write_text(json.dumps(doc, indent=1, ensure_ascii=False) + "\n")
        (PIPELINE / "versions.html").write_text(render(doc))
    else:
        (scratch / "versions.json").write_text(json.dumps(doc, indent=1, ensure_ascii=False) + "\n")
        print(f"verdicts written to {scratch / 'versions.json'}")
    if os.environ.get("VERIFY_OUT"):
        Path(os.environ["VERIFY_OUT"]).write_text(json.dumps(doc, indent=1, ensure_ascii=False) + "\n")
    if CHECK and failed:
        sys.exit(f"FAILED: {', '.join(failed)}")


def state_line(s):
    if not s:
        return ""
    return (f"MAP links and GridAtlas data: every row's MAP link opens GridAtlas on the project by REPD Ref ID. Measured {s['measured_at'][:10]} against GridAtlas register "
            f"generation {s['gridatlas_register']['generation']} ({s['gridatlas_register']['dataset']}): of {s['rows']:,} rows, {s['active_rows']:,} have an active REPD status; "
            f"{s['active_resolved']:,} of those are in that register and {s['active_not_resolved']} are not "
            f"({s.get('active_not_resolved_outside_gridatlas_area', 0)} outside the area GridAtlas compiles, {s.get('active_not_resolved_unexplained', s['active_not_resolved'])} unexplained; listed in versions.json under map_link_state). "
            f"The other {s['not_active_not_expected']:,} rows have a status GridAtlas does not keep; {s.get('rows_without_map_point', 0)} rows have no map point and open by reference only. "
            f"Measured from GridAtlas's published files, not on the live map.")

def render(doc):
    e = html.escape
    rows = []
    for v in doc["versions"]:
        ci = v.get("ci") or {}
        ci_cell = f'<a href="{e(ci["url"])}">{e(ci.get("conclusion", "").upper())}</a>' if ci.get("url") else "not yet recorded"
        checks = " · ".join(f'{e(k.replace("_", " "))}: {"ok" if c.get("pass") else "FAIL"}' for k, c in v["checks"].items())
        faults = "".join(f"<li>{e(f)}</li>" for f in v["known_faults"]) or "<li>None recorded.</li>"
        state = v["state"].upper()
        rows.append(f'<tr class="{e(v["verdict"].lower())}"><td><a href="{e(v["url"])}"><b>{e(v["id"])}</b></a><br>{e(v["version"])}<br><span class="state">{e(state)}</span></td>'
                    f'<td>{e(v["date"].replace("T", " ").replace("Z", " UTC"))}</td><td>{e(v["added"])}{"<br><i>Data-centre features: " + e(v["datacentre_features"]) + ".</i>" if v.get("datacentre_features") else ""}<ul>{faults}</ul></td>'
                    f'<td><b class="verdict">{e(v["verdict"])}</b>{"" if v["browser_checked"] else " (offline checks only)"}<br><small>{checks}</small></td>'
                    f'<td>{ci_cell}</td><td>parent {e(v["parent"])}<br><a href="{e(v["url"])}CHANGES.md">changes</a></td></tr>')
    return f"""<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>GlobalGrid2050 | Pipeline News versions</title>
<style>
body{{font-family:system-ui,Arial,sans-serif;margin:0;padding:20px;background:#07090c;color:#e6e9ee;line-height:1.45}}
a{{color:#6cf}}h1{{font-size:20px;margin:0 0 6px}}p{{max-width:900px;color:#a6adbb;font-size:14px}}
table{{border-collapse:collapse;width:100%;font-size:13px}}th,td{{border:1px solid #252a31;padding:8px;vertical-align:top;text-align:left}}
th{{background:#10141a;font-size:11px;letter-spacing:1px}}tr.pass .verdict{{color:#3d9}}tr.fail .verdict{{color:#f66}}
.state{{font-size:10px;letter-spacing:1px;color:#fc6}}ul{{margin:6px 0 0 16px;padding:0;color:#a6adbb}}small{{color:#7f8996}}
@media(max-width:700px){{table,tbody,tr,td{{display:block}}thead{{display:none}}tr{{margin-bottom:14px}}td{{border-bottom:0}}tr td:last-child{{border-bottom:1px solid #252a31}}}}
</style></head><body>
<h1>Pipeline News versions</h1>
<p>Every published version of the UK renewables pipeline page since the REPD October 2026 register, newest first. Each version is a
separate folder that is never edited after publication; earlier versions stay available. The verdict is the result of the automated
checks (the version's own test suite, the MAP link of every one of {doc['versions'][0]['checks']['map_contract'].get('rows') or '7,775'} rows, comparison with the parent version and a headless
browser load at desktop and phone widths). A verdict is a test result, not an engineering acceptance. Machine-readable copy:
<a href="versions.json">versions.json</a>. Generated {e(doc['generated_at'])}.</p>
<p>{e((doc.get('release_candidate') or {}).get('note', 'No release candidate has been named yet.'))}</p>
<p>{e(state_line(doc.get('map_link_state')))}</p>
<table><thead><tr><th>VERSION</th><th>DATE</th><th>WHAT IT ADDED · KNOWN FAULTS</th><th>AUTOMATED VERDICT</th><th>CI ON PUBLICATION</th><th>LINKS</th></tr></thead>
<tbody>
{chr(10).join(rows)}
</tbody></table>
</body></html>
"""


if __name__ == "__main__":
    main()

Canvas

A JavaScript module in the price daily ui folder of GlobalGrid2050 that draws daily (`drawDaily`) (units: MWh).

renderglobalgrid2050 / automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/canvas.mjs · lines 1–53 of 53 · Not reached from any entry point (candidate for review) · pattern money (shared by 12 files)

What it does
It draws its content. Defines money, tickStep, drawDaily, X. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
Out: canvas drawing.
Downstream impact
Used directly by 1 file: View (globalgrid2050).
What it achieves
It draws daily (`drawDaily`) and is built from the money step (`money`) and the tick step helper (`tickStep`). V6 canvas design: Courier, dark field, cyan mean/gold high/red low, GBP axes.
Why it matters
Imported by View.
Application
globalgrid2050 · automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9 · JavaScript module
Uses
Model (import)
Used by
imported by View (import)
Produces
drawDaily
Defines here
money, tickStep, drawDaily, X
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/canvas.mjs:1-53 · blob a4f4fd1d2fe7d2b16ba1cc0f756eece3710100ca · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
/* V6 canvas design: Courier, dark field, cyan mean/gold high/red low, GBP axes. */
import {segments,dateMs,summarise} from './model.mjs';
const SERIES=[['maximum_observed_gbp_per_mwh','High','#ffcc00'],['mean_available_gbp_per_mwh','Available mean','#00ffff'],['minimum_observed_gbp_per_mwh','Low','#ff3333']];
const money=n=>n===null?'—':'£'+n.toLocaleString('en-GB',{minimumFractionDigits:2,maximumFractionDigits:2});
function tickStep(span){const raw=span/6,p=10**Math.floor(Math.log10(Math.max(raw,1))),n=raw/p;return(n<=1?1:n<=2?2:n<=5?5:10)*p;}
export function drawDaily(canvas,result){
  const ratio=globalThis.devicePixelRatio||1,bounds=canvas.getBoundingClientRect();
  const width=Math.max(240,bounds.width||800),height=Math.max(300,bounds.height||440);
  canvas.width=Math.round(width*ratio);canvas.height=Math.round(height*ratio);
  const g=canvas.getContext('2d');if(!g)throw Error('Canvas unavailable');g.setTransform(ratio,0,0,ratio,0,0);
  const pad={left:55,right:16,top:65,bottom:54},w=width-pad.left-pad.right,h=height-pad.top-pad.bottom;
  const all=result.rows.flatMap(r=>SERIES.map(([field])=>r[field])).filter(Number.isFinite);
  const lo=Math.min(0,...all),hi=Math.max(0,...all),margin=Math.max((hi-lo)*.08,10),bottom=lo-margin,top=hi+margin;
  const start=dateMs(result.start),end=dateMs(result.end)+86400000;
  const X=date=>pad.left+((dateMs(date)+43200000-start)/(end-start))*w,Y=value=>pad.top+(top-value)/(top-bottom)*h;
  g.clearRect(0,0,width,height);g.fillStyle='#05070c';g.fillRect(0,0,width,height);
  g.font='10px Courier New';g.textBaseline='middle';
  const step=tickStep(top-bottom);
  for(let value=Math.ceil(bottom/step)*step;value<=top;value+=step){
    const y=Y(value);g.strokeStyle=value===0?'rgba(0,255,255,.35)':'rgba(255,255,255,.07)';g.lineWidth=1;
    g.beginPath();g.moveTo(pad.left,y);g.lineTo(width-pad.right,y);g.stroke();
    g.fillStyle='#f5f7fb';g.textAlign='left';g.fillText('£'+(Math.round(value)||0).toLocaleString('en-GB'),4,y);
  }
  g.fillStyle='#9aa3b6';g.font='10px Courier New';g.textAlign='left';g.fillText('GBP/MWh · system sell',pad.left,14);
  let legendX=pad.left;
  for(const [,label,color] of SERIES){g.fillStyle=color;g.shadowColor=color;g.shadowBlur=4;g.fillRect(legendX,30,7,7);g.shadowBlur=0;g.fillStyle='#9aa3b6';g.font='9px Courier New';g.fillText(label,legendX+10,34);legendX+=label==='Available mean'?105:55;}
  g.fillStyle='#9aa3b6';g.textAlign='left';g.fillText(result.start,pad.left,height-30);g.textAlign='right';g.fillText(result.end,width-pad.right,height-30);
  g.textAlign='left';g.font='9px Courier New';g.fillText('Gaps retained · hollow markers = partial source days',pad.left,height-12,Math.max(1,w));
  const receipt=[];
  for(const [field,,color] of SERIES){
    const groups=segments(result.rows,field);g.save();g.lineWidth=field==='mean_available_gbp_per_mwh'?2.4:2.1;g.lineCap='round';g.lineJoin='round';
    g.strokeStyle=color;g.shadowColor=color;g.shadowBlur=5;
    for(const group of groups){
      g.beginPath();group.forEach((point,i)=>{if(i)g.lineTo(X(point.date),Y(point.value));else g.moveTo(X(point.date),Y(point.value));});g.stroke();
      for(const point of group)if(group.length===1||point.partial){
        g.beginPath();g.arc(X(point.date),Y(point.value),point.partial?3:2,0,Math.PI*2);g.fillStyle=point.partial?'#05070c':color;g.fill();g.stroke();
      }
    }g.restore();receipt.push({field,segments:groups.map(group=>group.map(point=>point.date))});
  }
  const summary=summarise(result.rows);
  if(!all.length){g.fillStyle='#00ffff';g.textAlign='center';g.font='bold 12px Courier New';g.fillText('No reported prices in this window',pad.left+w/2,pad.top+h/2,Math.max(1,w));}
  else{
    // The dates label source-declared daily observations; no intraday clock is invented.
    const high=result.rows.find(r=>r.maximum_observed_gbp_per_mwh===summary.high),low=result.rows.find(r=>r.minimum_observed_gbp_per_mwh===summary.low);
    for(const [label,row,value,align] of [['HIGH',high,summary.high,'left'],['LOW',low,summary.low,'right']]){
      const x=X(row.date),y=Y(value);g.fillStyle='#ff3333';g.shadowColor='rgba(0,255,255,.8)';g.shadowBlur=6;
      g.beginPath();g.arc(x,y,3,0,Math.PI*2);g.fill();g.shadowBlur=0;
      const text=label+' '+money(value)+' · '+row.date;g.font='bold 9px Courier New';g.textAlign=align;
      g.fillStyle='#ff5555';g.fillText(text,align==='left'?pad.left:width-pad.right,52,Math.max(1,w/2-6));
    }
  }
  return receipt;
}

Model

A JavaScript module in the price daily ui folder of GlobalGrid2050 that reads sources and daily, using SHA-256 from the data-GB-electricity repository.

storageglobalgrid2050 / automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/model.mjs · lines 1–105 of 105 · pattern integer (shared by 5 files)

What it does
It loads sources and daily. Defines 17 functions or classes, including fail, integer, hash, immutable, dateMs. Side effects: uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: data source: data-gb-electricity data; JSON file index.json; JSON file sources.json; Parquet file daily.parquet.
Downstream impact
Used directly by 3 files: Canvas (globalgrid2050); View (globalgrid2050); Contracts Test (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 V931 Preview Acceptance Workflow (globalgrid2050).
What it achieves
It validates index (`validateIndex`), validates year (`validateYear`) and reads pinned (`readPinned`). Daily historical system-sell data only. The data owner defines its grain. It reads `index.json`.
Why it matters
Imported by Canvas and View. Checked by Contracts Test.
Application
globalgrid2050 · automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9 · JavaScript module
Uses
none found
Used by
imported by Canvas (import), imported by View (import), imported by Contracts Test (import)
Produces
SOURCE, dateMs, dateAt, expectedPeriods, validateIndex, validateYear, readPinned, createStore, summarise, segments, trailingWindow
Defines here
fail, integer, hash, immutable, dateMs, dateAt, lastSunday, expectedPeriods, pin, validateIndex, validateYear, readPinned, createStore, year, summarise, segments, trailingWindow
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/model.mjs:1-105 · blob 0a0209d76d3fa8e90e13d44adcf7e99d64694da5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: storage · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
/* Daily historical system-sell data only. The data owner defines its grain. */
export const SOURCE = Object.freeze({
  repository: 'Ventusltd/data-gb-electricity',
  commit: 'cf48c8d6fdd9ab686c4af7261149d81a0129f7fc',
  base: 'https://raw.githubusercontent.com/Ventusltd/data-gb-electricity/cf48c8d6fdd9ab686c4af7261149d81a0129f7fc/derived/price-daily-browser/',
  index: Object.freeze({path:'index.json',bytes:3616,sha256:'3c3ad8e0d8169b4bc253dabbad2a7d35b64984f40accce1abd016e1ca15a1e8e'})
});
const SCHEMA='data-gb-electricity.system-sell-daily.v1',BASIS='ELEXON_SYSTEM_SELL_PRICE',DAY=86400000;
const fail=(ok,message)=>{if(!ok)throw Error('Daily prices rejected: '+message);};
const integer=(n,max=2000000)=>Number.isSafeInteger(n)&&n>=0&&n<=max;
const hash=s=>typeof s==='string'&&/^[a-f0-9]{64}$/.test(s);
function immutable(value){
  if(value&&typeof value==='object'&&!Object.isFrozen(value)){for(const item of Object.values(value))immutable(item);Object.freeze(value);}return value;
}
export function dateMs(date){
  fail(typeof date==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(date),'date');
  const n=Date.parse(date+'T00:00:00Z');fail(Number.isFinite(n)&&new Date(n).toISOString().slice(0,10)===date,'calendar date');return n;
}
export const dateAt=n=>new Date(n).toISOString().slice(0,10);
function lastSunday(year,month){const d=new Date(Date.UTC(year,month+1,0));return dateAt(d.getTime()-d.getUTCDay()*DAY);}
export function expectedPeriods(date){const year=Number(date.slice(0,4));dateMs(date);fail(year>=1996&&year<=2100,'GB calendar range');return date===lastSunday(year,2)?46:date===lastSunday(year,9)?50:48;}
function pin(value,path,max){fail(value?.path===path&&integer(value.bytes,max)&&value.bytes>0&&hash(value.sha256),'part identity');}
export function validateIndex(index){
  fail(index?.schema===SCHEMA+'.index'&&index.unit==='GBP/MWh'&&index.price_basis===BASIS,'index schema/basis');
  const first=dateMs(index.first_date),last=dateMs(index.last_date);
  fail(last>=first&&index.rows===(last-first)/DAY+1&&integer(index.rows,40000),'date span');
  fail(integer(index.source_periods)&&index.source_periods>0&&index.source_periods===index.observed_periods&&
    integer(index.priced_periods)&&index.priced_periods<=index.observed_periods&&
    integer(index.utc_alignment_mismatches)&&index.utc_alignment_mismatches<=index.observed_periods,'input counters');
  fail(hash(index.producer_sha256)&&typeof index.calendar_quality==='string'&&index.calendar_quality.includes('Source-declared'),'producer/quality');
  pin(index.sources,'sources.json',100000);pin(index.parquet,'daily.parquet',2000000);
  fail(Array.isArray(index.parts)&&index.parts.length>0&&index.parts.length<=100,'annual parts');
  let previous=Number(index.first_date.slice(0,4))-1,total=0;
  for(const p of index.parts){
    fail(integer(p.year,2100)&&p.year===previous+1,'ordered years');previous=p.year;pin(p,p.year+'.json',150000);
    const a=Math.max(first,Date.UTC(p.year,0,1)),b=Math.min(last,Date.UTC(p.year+1,0,1)-DAY);
    fail(b>=a&&p.calendar_days===(b-a)/DAY+1&&['observed_days','complete_days','partial_days','missing_days'].every(k=>integer(p[k],366))&&
      p.complete_days+p.partial_days===p.observed_days&&p.observed_days+p.missing_days===p.calendar_days,'year coverage');total+=p.calendar_days;
  }
  fail(total===index.rows&&previous===Number(index.last_date.slice(0,4)),'calendar population');return index;
}
export function validateYear(data,part,index){
  fail(data?.schema===SCHEMA&&data.year===part.year&&data.unit==='GBP/MWh'&&data.price_basis===BASIS&&Array.isArray(data.rows),'year schema/basis');
  const start=Math.max(dateMs(index.first_date),Date.UTC(part.year,0,1));let complete=0,partial=0,missing=0;
  fail(data.rows.length===part.calendar_days,'year row count');
  for(let i=0;i<data.rows.length;i++){
    const r=data.rows[i];fail(r?.date===dateAt(start+i*DAY)&&r.expected_periods===expectedPeriods(r.date),'daily calendar');
    fail(integer(r.observed_periods,50)&&integer(r.priced_periods,50)&&r.priced_periods<=r.observed_periods&&r.observed_periods<=r.expected_periods&&
      integer(r.utc_alignment_mismatches,50)&&r.utc_alignment_mismatches<=r.observed_periods,'daily grain');
    const status=!r.observed_periods?'NO_OBSERVATIONS':r.priced_periods===r.observed_periods&&r.observed_periods===r.expected_periods?'COMPLETE_SOURCE_DAY':'PARTIAL_SOURCE_DAY';
    fail(r.coverage_status===status&&Number.isFinite(r.price_coverage_pct)&&Math.abs(r.price_coverage_pct-100*r.priced_periods/r.expected_periods)<0.000001,'daily coverage');
    const values=[r.minimum_observed_gbp_per_mwh,r.mean_available_gbp_per_mwh,r.maximum_observed_gbp_per_mwh];
    fail(r.priced_periods?values.every(Number.isFinite)&&values[0]<=values[1]&&values[1]<=values[2]:values.every(v=>v===null),'daily prices/nulls');
    if(status==='COMPLETE_SOURCE_DAY')complete++;else if(status==='PARTIAL_SOURCE_DAY')partial++;else missing++;
  }
  fail(complete===part.complete_days&&partial===part.partial_days&&missing===part.missing_days,'observed year coverage');return data.rows;
}
export async function readPinned(url,pin,transport=fetch){
  fail(url.startsWith(SOURCE.base)&&/^\d{4}\.json$|^index\.json$/.test(url.slice(SOURCE.base.length)),'immutable source URL');
  fail(integer(pin?.bytes,150000)&&pin.bytes>0&&hash(pin.sha256),'byte/hash bound');
  const response=await transport(url,{credentials:'omit',referrerPolicy:'no-referrer',redirect:'error',signal:AbortSignal.timeout(15000)});
  fail(response.ok&&!response.redirected,'HTTP response');const reader=response.body?.getReader();fail(reader,'bounded response stream');
  const chunks=[];let size=0;
  for(;;){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>pin.bytes){await reader.cancel();throw Error('Daily prices rejected: byte limit');}chunks.push(value);}
  fail(size===pin.bytes,'exact bytes');const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.byteLength;}
  const actual=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),n=>n.toString(16).padStart(2,'0')).join('');
  fail(actual===pin.sha256,'SHA-256');return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes));
}
export async function createStore(transport=fetch){
  const index=immutable(validateIndex(await readPinned(SOURCE.base+'index.json',SOURCE.index,transport))),cache=new Map();
  async function year(n){
    const part=index.parts.find(p=>p.year===n);fail(part,'available year');
    if(cache.has(n)){const promise=cache.get(n);cache.delete(n);cache.set(n,promise);return promise;}
    const promise=readPinned(SOURCE.base+part.path,part,transport).then(data=>immutable(validateYear(data,part,index))).catch(e=>{if(cache.get(n)===promise)cache.delete(n);throw e;});
    cache.set(n,promise);if(cache.size>3)cache.delete(cache.keys().next().value);return promise;
  }
  return Object.freeze({index,async window(start,end){
    const a=Math.max(dateMs(start),dateMs(index.first_date)),b=Math.min(dateMs(end),dateMs(index.last_date));
    fail(b>=a&&(b-a)/DAY<366,'bounded historical window');
    const years=[];for(let y=new Date(a).getUTCFullYear();y<=new Date(b).getUTCFullYear();y++)years.push(y);
    const rows=(await Promise.all(years.map(year))).flat().filter(r=>dateMs(r.date)>=a&&dateMs(r.date)<=b);
    fail(rows.length===(b-a)/DAY+1,'window calendar continuity');return immutable({start:dateAt(a),end:dateAt(b),rows});
  }});
}
export function summarise(rows){
  const values=rows.filter(r=>r.priced_periods>0);return {
    calendarDays:rows.length,completeDays:rows.filter(r=>r.coverage_status==='COMPLETE_SOURCE_DAY').length,
    partialDays:rows.filter(r=>r.coverage_status==='PARTIAL_SOURCE_DAY').length,missingDays:rows.filter(r=>r.coverage_status==='NO_OBSERVATIONS').length,
    expected:rows.reduce((n,r)=>n+r.expected_periods,0),observed:rows.reduce((n,r)=>n+r.observed_periods,0),priced:rows.reduce((n,r)=>n+r.priced_periods,0),
    clockMismatches:rows.reduce((n,r)=>n+r.utc_alignment_mismatches,0),
    dailyMean:values.length?values.reduce((n,r)=>n+r.mean_available_gbp_per_mwh,0)/values.length:null,
    high:values.length?Math.max(...values.map(r=>r.maximum_observed_gbp_per_mwh)):null,
    low:values.length?Math.min(...values.map(r=>r.minimum_observed_gbp_per_mwh)):null};
}
export function segments(rows,field){
  const output=[];let current=[],previous=null;
  for(const row of rows){
    const value=row[field],t=dateMs(row.date);
    if(!Number.isFinite(value)||!row.priced_periods||previous!==null&&t-previous!==DAY){if(current.length)output.push(current);current=[];}
    if(Number.isFinite(value)&&row.priced_periods)current.push({date:row.date,value,partial:row.coverage_status!=='COMPLETE_SOURCE_DAY'});
    previous=t;
  }
  if(current.length)output.push(current);return output;
}
export function trailingWindow(end,days,first){const b=dateMs(end);fail(integer(days,366)&&days>0,'window length');return {start:dateAt(Math.max(dateMs(first),b-(days-1)*DAY)),end};}

Automation — Price Daily UI Style Sheet

A style sheet in GlobalGrid2050.

renderglobalgrid2050 / automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/styles.css · lines 1–11 of 11 · Entry point

What it does
Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 1 file: GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents); A4 Legal Model (globalgrid2050).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/.
Application
globalgrid2050 · automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9 · style sheet
Uses
none found
Used by
loaded by GlobalGrid2050 — UK Renewables Pipeline Page (stylesheet)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/price_daily_ui/78d5360239e1a5fcffa83fcb30d5937c5521acb9/styles.css:1-11 · blob ab974c96548474b66406f4221fb432b4303c20e7 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
.pn-daily-prices{font-family:"Courier New",Courier,monospace;background:#05070c;color:#f5f7fb;border:1px solid rgba(0,255,255,.35);border-radius:10px;padding:12px;min-width:0;box-sizing:border-box}
.pn-daily-prices *{box-sizing:border-box}.pn-daily-prices [hidden]{display:none!important}
.pn-daily-prices h3{color:#00ffff;font-size:16px;margin:0 0 10px}.pn-daily-prices p{font-size:11px;line-height:1.6;overflow-wrap:anywhere}
.pn-daily-prices .pnd-source{color:#00ff88}.pnd-tools{display:flex;flex-wrap:wrap;gap:10px;margin:12px 0}.pnd-tools label{display:flex;flex-direction:column;gap:5px;font-size:11px;flex:1;min-width:100px}
.pnd-tools select,.pnd-tools input{font:inherit;min-height:44px;max-width:100%;min-width:0;padding:6px;background:#080b10;color:#00ffff;border:1px solid #00ffff;border-radius:6px;color-scheme:dark}
.pn-daily-prices canvas{display:block;width:100%;height:440px;max-width:100%;min-width:0;border:1px solid rgba(0,255,255,.2);border-radius:8px}
.pnd-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;border:1px solid rgba(0,255,255,.55);border-radius:10px;padding:12px;margin:10px 0;background:rgba(5,7,12,.92);box-shadow:0 0 10px rgba(0,255,255,.15)}
.pnd-stats div{min-width:0}.pnd-stats dt{font-size:10px;color:#ff5555;line-height:1.5}.pnd-stats dd{margin:4px 0 0;font-size:13px;font-weight:bold;overflow-wrap:anywhere}
.pnd-coverage,.pnd-quality,.pnd-note{color:#a6adbb}.pn-daily-prices details{font-size:11px;line-height:1.5}.pn-daily-prices summary{min-height:44px;padding:10px 0;cursor:pointer;color:#00ffff}.pn-daily-prices a{color:#00ffff;overflow-wrap:anywhere}
.pn-daily-prices :focus-visible{outline:2px solid #ffff00;outline-offset:2px}.pnd-table{max-width:100%;overflow:auto;overscroll-behavior:contain}.pnd-table table{border-collapse:collapse;min-width:660px;width:100%;font-size:10px}.pnd-table th,.pnd-table td{padding:7px;text-align:left;border-bottom:1px solid #253040}
@media(max-width:480px){.pnd-stats{grid-template-columns:1fr}.pn-daily-prices{padding:9px}.pn-daily-prices canvas{height:390px}.pnd-tools{gap:7px}}