GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050-ip-and-mac-addresses / tests

Apps Registry and 4 more files

A Python command-line tool in the tools folder of Kuiper Belt that reads overview graph, periodic table, elements and overhead lines (OHL), using SHA-256 from the stars repository.

585 lines of Python and JavaScript from globalgrid2050-ip-and-mac-addresses, kuiper-belt, legislation, in 5 files. Topic: Electricity markets and data pipelines. Section 976 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 Registry test · globalgrid2050-ip-and-mac-addresses / tests/test_registry.py lines 1–174
  2. Apps Registry storage · kuiper-belt / tools/apps_registry.py lines 1–321
  3. PipelineNews Replay ingest · legislation / apps/pipelinenews/replay.py lines 1–33
  4. Test Renewable Energy Planning Database (REPD) Ownership test · legislation / apps/test_repd_ownership.py lines 1–24
  5. Verify Registry render · legislation / protections/verify-registry.mjs lines 1–33

Test Registry

A test in the tests folder of GlobalGrid2050 IP and MAC Addresses that checks Registry.

testglobalgrid2050-ip-and-mac-addresses / tests/test_registry.py · lines 1–174 of 174 · Entry point

What it does
It tests its inputs. Defines 21 functions or classes, including RegistryTests, setUp, cli, test_update_and_retirement_preserve_identity_and_history, test_retired_identity_cannot_change_or_be_reissued. Uses libraries copy, pathlib, subprocess, sys, tempfile. 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 registry.json; JSON file previous.json.
Downstream impact
Used directly by 1 file: Publish Workflow (globalgrid2050-ip-and-mac-addresses).
What it achieves
It sets up (`setUp`) and is built from the registry tests class (`RegistryTests`) and the cli step (`cli`). Registry integrity tests using copies and temporary files, never live writes.
Why it matters
Run by Publish Workflow.
Application
globalgrid2050-ip-and-mac-addresses · tests · test
Uses
Registry (import), copy, pathlib, subprocess, sys, tempfile, unittest, unittest.mock, uuid
Used by
run by Publish Workflow (workflow run)
Produces
RegistryTests
Defines here
RegistryTests, setUp, cli, test_update_and_retirement_preserve_identity_and_history, test_retired_identity_cannot_change_or_be_reissued, test_decimal_roundtrip_and_leading_zeroes, test_numeric_precision_and_encoding_drift_rejected, test_duplicate_asset_registration_rejected, test_duplicate_record_rejected, test_duplicate_event_id_rejected, test_immutable_fields_cannot_be_updated, test_consistent_history_rewrite_requires_previous_to_detect, test_valid_but_truncated_history_rejected_by_extends, test_record_only_mutation_rejected, test_malicious_addresses_rejected, test_valid_https_record_url, test_duplicate_json_properties_rejected, test_cli_refuses_invalid_mutation_without_writing, test_cli_requires_public_acknowledgment_before_creating_file, test_refused_atomic_replace_preserves_file_and_cleans_temporary, test_cli_previous_detects_history_rewrite
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050-ip-and-mac-addresses@2ba77a48351e70648ab8d122c187a87c47d0f6fc tests/test_registry.py:1-174 · blob 80e2fee6bf3513402df4e6f54323dd7d079d9806 · 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: unknown
"""Registry integrity tests using copies and temporary files, never live writes."""
import copy
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
import uuid

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
import registry


class RegistryTests(unittest.TestCase):
    def setUp(self):
        self.data = registry.load(ROOT / 'data' / 'registry.json')
        self.asset = self.data['records'][0]['id']

    def cli(self, path, *args):
        return subprocess.run([sys.executable, str(ROOT / 'registry.py'), '--file', str(path), *args],
                              capture_output=True, text=True)

    def test_update_and_retirement_preserve_identity_and_history(self):
        original = copy.deepcopy(self.data)
        changed = registry.append(self.data, self.asset, 'updated', {'title': 'Updated public demo'})
        retired = registry.append(changed, self.asset, 'retired', {'reason': 'Demonstration complete'})
        for field in ('id', 'barcode_number', 'created_at'):
            self.assertEqual(original['records'][0][field], retired['records'][0][field])
        self.assertEqual(retired['records'][0]['status'], 'retired')
        self.assertEqual(retired['records'][0]['title'], 'Updated public demo')
        self.assertEqual(len(retired['records']), len(original['records']))
        self.assertEqual(retired['events'][:len(original['events'])], original['events'])
        registry.extends(original, changed)
        registry.extends(changed, retired)
        self.assertEqual(self.data, original)

    def test_retired_identity_cannot_change_or_be_reissued(self):
        retired = registry.append(self.data, self.asset, 'retired', {'reason': 'End of demo'})
        for action, changes in [('updated', {'title': 'Reused'}),
                                ('retired', {'reason': 'Again'}),
                                ('registered', self.data['events'][0]['changes'])]:
            with self.subTest(action=action), self.assertRaises(ValueError):
                registry.append(retired, self.asset, action, changes)

    def test_decimal_roundtrip_and_leading_zeroes(self):
        for record in self.data['records']:
            value = record['barcode_number']
            self.assertIsInstance(value, str)
            self.assertRegex(value, r'^[0-9]{39}$')
            self.assertEqual(str(uuid.UUID(int=int(value))), record['id'])
            self.assertEqual(registry.number(record['id']), value)
        # Fixed UUID4 fixture forces padding independently of the saved examples.
        low = '00000000-0000-4000-8000-000000000001'
        self.assertTrue(registry.number(low).startswith('0'))
        self.assertEqual(str(uuid.UUID(int=int(registry.number(low)))), low)

    def test_numeric_precision_and_encoding_drift_rejected(self):
        value = self.data['records'][0]['barcode_number']
        for replacement in (int(value), float(value), str(int(float(value))).zfill(39), value[:-1], '0' * 39):
            candidate = copy.deepcopy(self.data)
            candidate['records'][0]['barcode_number'] = replacement
            with self.subTest(replacement=replacement), self.assertRaises(ValueError):
                registry.validate(candidate)

    def test_duplicate_asset_registration_rejected(self):
        with self.assertRaisesRegex(ValueError, 'already issued'):
            registry.append(self.data, self.asset, 'registered', self.data['events'][0]['changes'])

    def test_duplicate_record_rejected(self):
        self.data['records'].append(copy.deepcopy(self.data['records'][0]))
        with self.assertRaises(ValueError):
            registry.validate(self.data)

    def test_duplicate_event_id_rejected(self):
        with patch.object(registry.uuid, 'uuid4', return_value=uuid.UUID(self.data['events'][0]['id'])):
            with self.assertRaisesRegex(ValueError, 'Duplicate event ID'):
                registry.append(self.data, self.asset, 'updated', {'title': 'Change'})

    def test_immutable_fields_cannot_be_updated(self):
        for field in ('id', 'barcode_number', 'created_at', 'kind', 'demonstration'):
            with self.subTest(field=field), self.assertRaises(ValueError):
                registry.append(self.data, self.asset, 'updated', {field: 'replacement'})

    def test_consistent_history_rewrite_requires_previous_to_detect(self):
        rewritten = copy.deepcopy(self.data)
        rewritten['events'][0]['changes']['title'] = 'Rewritten origin'
        rewritten['records'][0]['title'] = 'Rewritten origin'
        registry.validate(rewritten)
        with self.assertRaisesRegex(ValueError, 'history'):
            registry.extends(self.data, rewritten)

    def test_valid_but_truncated_history_rejected_by_extends(self):
        truncated = copy.deepcopy(self.data)
        truncated['events'].pop()
        truncated['records'].pop()
        registry.validate(truncated)
        with self.assertRaisesRegex(ValueError, 'history'):
            registry.extends(self.data, truncated)

    def test_record_only_mutation_rejected(self):
        self.data['records'][0]['title'] = 'Not in history'
        with self.assertRaises(ValueError):
            registry.validate(self.data)

    def test_malicious_addresses_rejected(self):
        for value in ('javascript:alert(1)', 'http://example.com', '//example.com',
                      'https://user:secret@example.com', 'https://@example.com',
                      'https://:@example.com', 'https://example.com\\@evil.example',
                      'https://example.com\n.evil.example', 'https://exa%0ample.com',
                      'https://example.com:0', 'https://example.com:65536', 'https:///missing-host'):
            with self.subTest(value=value), self.assertRaises(ValueError):
                registry.https(value)

    def test_valid_https_record_url(self):
        registry.https('https://example.com:443/assets/demo?view=public#details')

    def test_duplicate_json_properties_rejected(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / 'registry.json'
            path.write_text('{"schema":"globalgrid.identity.v1","schema":"globalgrid.identity.v1","records":[],"events":[]}')
            with self.assertRaisesRegex(ValueError, 'Duplicate JSON property'):
                registry.load(path)

    def test_cli_refuses_invalid_mutation_without_writing(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / 'registry.json'
            registry.save(path, self.data)
            original = path.read_bytes()
            for args in [('update', self.asset, '--url', 'javascript:alert(1)'),
                         ('update', self.asset),
                         ('retire', str(uuid.uuid4()), '--reason', 'Unknown')]:
                result = self.cli(path, *args)
                self.assertNotEqual(result.returncode, 0, result.stdout)
                self.assertEqual(path.read_bytes(), original)
                self.assertEqual(sorted(p.name for p in Path(tmp).iterdir()), ['registry.json'])

    def test_cli_requires_public_acknowledgment_before_creating_file(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / 'registry.json'
            result = self.cli(path, 'register', '--title', 'Private by default',
                              '--kind', 'cable', '--url', 'https://example.com')
            self.assertNotEqual(result.returncode, 0)
            self.assertFalse(path.exists())

    def test_refused_atomic_replace_preserves_file_and_cleans_temporary(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / 'registry.json'
            registry.save(path, self.data)
            original = path.read_bytes()
            changed = registry.append(self.data, self.asset, 'updated', {'title': 'Pending'})
            with patch.object(registry.os, 'replace', side_effect=PermissionError('write refused')):
                with self.assertRaises(PermissionError):
                    registry.save(path, changed)
            self.assertEqual(path.read_bytes(), original)
            self.assertEqual(sorted(p.name for p in Path(tmp).iterdir()), ['registry.json'])

    def test_cli_previous_detects_history_rewrite(self):
        with tempfile.TemporaryDirectory() as tmp:
            previous, current = Path(tmp) / 'previous.json', Path(tmp) / 'registry.json'
            registry.save(previous, self.data)
            altered = copy.deepcopy(self.data)
            altered['events'][0]['changes']['title'] = 'Altered'
            altered['records'][0]['title'] = 'Altered'
            registry.save(current, altered)
            original = current.read_bytes()
            result = self.cli(current, 'validate', '--previous', str(previous))
            self.assertNotEqual(result.returncode, 0)
            self.assertEqual(current.read_bytes(), original)


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

Apps Registry

A Python command-line tool in the tools folder of Kuiper Belt that reads overview graph, periodic table, elements and overhead lines (OHL), using SHA-256 from the stars repository.

storagekuiper-belt / tools/apps_registry.py · lines 1–321 of 321 · Entry point · pattern repo_of (shared by 2 files)

What it does
It loads overview graph, periodic table, elements and overhead lines (OHL). Defines 10 functions or classes, including git, find_clone, show, sha256, repo_of. Uses libraries argparse, hashlib, html, io, json. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: overhead lines (OHL).
Inputs & outputs
In: data source: stars data; JSON file overview.json; JSON file overview-graph.json; JSON file periodic-table.json; JSON file graph.json; JSON file apps.json; JSON file elements.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It finds clone (`find_clone`) and is built from the git step (`git`) and the show step (`show`). Write `editions/` `/data/apps.json`, the app registry of the estate (NL-010 step 7.1). It accepts `--edition`, `--roots` and `--check`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · tools · Python CLI
Uses
Element Keys (import), Kuiper Belt — See Through Page (estate URL), Kuiper Belt — Learn the Kuiper Page (estate URL), Kuiper Belt — Index Page (estate URL), argparse, hashlib, html, io, json, os, re, subprocess
Used by
none found
Produces
git, find_clone, show, sha256, repo_of, licence_of, build, check, main
Defines here
git, find_clone, show, sha256, repo_of, licence_of, build, check, ok, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 tools/apps_registry.py:1-321 · blob 8646837b93e5f03a73a77f13a0f2bf52bde5cadd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""tools/apps_registry.py - write editions/<stamp>/data/apps.json, the app registry of the estate (NL-010 step 7.1).

    python3 tools/apps_registry.py --edition editions/202611012135 [--roots /home/user/estate,/home/user]
    python3 tools/apps_registry.py --edition editions/202611012135 --check      # acceptance A1, by script

Two keyed sources and nothing else, plus two rows issued here:
  elements@f7a92fb APPS.md:7-13            7 rows, key block:<Sym>   (Q1: the key is copied, never the title or text)
  globalgrid2050@c66759f homepage_versions/homepage_v134.html:32-56   25 rows, id = data-entity-id
  testcode@d09c185 spider/INDEX.md:13      the spider sandbox, v5          (id spider-sandbox, issued here)
  elements@f7a92fb CATALOGUE.md:1          the periodic table itself       (id periodic-table, issued here)
Every licence is read from a file in a clone and quoted by key (repo@sha12 path:line); `not stated` when the clone
holds no LICENSE/NOTICE/licence sentence; `NOT EVALUATED: no clone of <repo>` when no clone is on this machine.
Nothing is fetched from the network. Apache-2.0 (kuiper-belt code); the output is data, CC BY 4.0.
"""
import argparse, hashlib, html, io, json, os, re, subprocess, sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from element_keys import redact   # noqa: E402  K1 (tools/ci_check.py): a non-public repository name is never written

SRC = {
    'elements': {'repo': 'elements', 'commit': 'f7a92fb085c38dcbbd5cb469a66cd5ca61fb95bf'},
    'homepage': {'repo': 'globalgrid2050', 'commit': 'c66759f0d7ac3489df9158da6eaa1330a37c069f',
                 'path': 'homepage_versions/homepage_v134.html', 'lines': (32, 56)},
    'spider': {'repo': 'testcode', 'commit': 'd09c185c8dacbc5c73afb2b0d0d8dad40745a544', 'path': 'spider/INDEX.md', 'line': 13},
}
APPS_LINES = (7, 13)
V5 = '20260914T143049Z-v5-linkify-frontdoor-brandfaithful'
GRAPHS = [  # the only two spider graphs copied into the edition (ROADMAP Q5: DISCLOSED); byte copies
    {'file': 'data/graphs/overview.json', 'repo': 'testcode', 'commit': 'd09c185c8dacbc5c73afb2b0d0d8dad40745a544',
     'path': 'spider/%s/spider/overview-graph.json' % V5},
    {'file': 'data/graphs/periodic-table.json', 'repo': 'stars', 'commit': 'cbca125bb5eeb7d0ffb02f4546d60eb5d47dadc9',
     'path': 'blocks/graph.json'},
]
# a link to a dated folder whose repository keeps a pointer above it: the pointer is the stable link (team-4 7.1)
POINTERS = {'https://ventusltd.github.io/kuiper-belt/see-through/202610050609/': 'https://ventusltd.github.io/kuiper-belt/see-through/',
            'https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/': 'https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/'}
KB_HOST = 'https://ventusltd.github.io/kuiper-belt/'
SAME_AS = {'block:Pn': 'pipeline-news'}   # team-4/STEPS.md 7.1 names this pair; nothing is merged
KEY_RE = re.compile(r'^(block:[A-Za-z0-9]+|surface:https://)')
LICENCE_FILES = ('LICENSE', 'LICENSE.md', 'LICENSE.txt', 'LICENCE', 'LICENCE.md', 'NOTICE', 'NOTICE.md')
LICENCE_NAMES = [(re.compile(r'CERN[- ]O(pen )?H(ardware )?L(icence)?[- ]?(Version 2|v2)?[^\n]*Strongly Reciprocal|CERN[- ]OHL-S', re.I), 'CERN-OHL-S-2.0'),
                 (re.compile(r'Apache License|Apache-2\.0|Apache License, Version 2\.0', re.I), 'Apache-2.0'),
                 (re.compile(r'\bMIT License\b', re.I), 'MIT'),
                 (re.compile(r'CC BY 4\.0|Creative Commons Attribution 4\.0', re.I), 'CC-BY-4.0')]


def git(d, *a):
    r = subprocess.run(['git'] + list(a), cwd=d, capture_output=True)
    if r.returncode:
        raise RuntimeError('git %s in %s: %s' % (' '.join(a), d, r.stderr.decode('utf-8', 'replace').strip()))
    return r.stdout


def find_clone(roots, name):
    for root in roots:
        d = os.path.join(root, name)
        if os.path.isdir(os.path.join(d, '.git')):
            return d
    return None


def show(d, commit, path):
    return git(d, 'show', '%s:%s' % (commit, path))


def sha256(b):
    return hashlib.sha256(b).hexdigest()


def repo_of(url):
    """the repository a served link lands in, by the estate's hosting rules"""
    m = re.match(r'^https://globalgrid2050\.com/(.*)$', url)
    if m:
        return 'globalgrid2050', m.group(1)
    m = re.match(r'^https://ventusltd\.github\.io/([^/]+)/?(.*)$', url)
    if m:
        return m.group(1), m.group(2)
    m = re.match(r'^https://github\.com/Ventusltd/([^/]+)/tree/[0-9a-f]+/(.*)$', url)
    if m:
        return m.group(1), m.group(2)
    return None, None


def licence_of(roots, url):
    """quote the licence of the folder the link lands in, nearest file first, then the repository root"""
    repo, sub = repo_of(url)
    if not repo:
        return {'licence': 'NOT EVALUATED: no repository rule for %s' % url, 'licence_key': None}
    d = find_clone(roots, repo)
    if not d:
        return {'licence': 'NOT EVALUATED: no clone of %s on this machine' % repo, 'licence_key': None}
    head = git(d, 'rev-parse', 'HEAD').decode().strip()
    tracked = set(git(d, 'ls-files').decode('utf-8', 'replace').split('\n'))
    parts = [p for p in sub.split('#')[0].split('?')[0].split('/') if p]
    if parts and '.' in parts[-1]:
        parts = parts[:-1]
    dirs = ['/'.join(parts[:i]) for i in range(len(parts), -1, -1)]
    for folder in dirs:
        for f in LICENCE_FILES:
            p = (folder + '/' + f) if folder else f
            if p not in tracked:
                continue
            text = show(d, head, p).decode('utf-8', 'replace').split('\n')
            for i, line in enumerate(text[:40], 1):
                for rx, name in LICENCE_NAMES:
                    if rx.search(line):
                        return {'licence': name, 'licence_key': '%s@%s %s:%d' % (repo, head[:7], p, i),
                                'licence_line': line.strip()}
    return {'licence': 'not stated', 'licence_key': '%s@%s (no LICENSE, NOTICE or licence sentence tracked)' % (repo, head[:7])}


def build(roots, edition):
    el = find_clone(roots, 'elements')
    hp = find_clone(roots, 'globalgrid2050')
    tc = find_clone(roots, 'testcode')
    if not (el and hp and tc):
        sys.exit('REFUSED: a source clone is missing (elements, globalgrid2050, testcode)')
    E = SRC['elements']['commit']
    apps_md = show(el, E, 'APPS.md')
    cat_apps = json.loads(show(el, E, 'catalogue/apps.json'))
    by_key = {a['key']: a for a in cat_apps}
    homepage = show(hp, SRC['homepage']['commit'], SRC['homepage']['path'])
    index_md = show(tc, SRC['spider']['commit'], SRC['spider']['path'])
    catalogue_md = show(el, E, 'CATALOGUE.md')
    wafer = set()
    for l in io.open(os.path.join(edition, '..', '..', 'cosmos', 'wafer.tsv'), encoding='utf-8'):
        if l.strip() and not l.startswith('#'):
            wafer.add(l.split('\t')[3])
    rows = []
    # ---- 7 register rows (keys only: Q1)
    lines = apps_md.decode('utf-8').split('\n')
    for n in range(APPS_LINES[0], APPS_LINES[1] + 1):
        m = re.match(r'^\| `(block:[A-Za-z0-9]+)` \|', lines[n - 1])
        if not m:
            sys.exit('REFUSED: APPS.md:%d is not a block row' % n)
        k = m.group(1)
        a = by_key[k]
        link = a['live'][0]
        w = None
        for f in a.get('files', []):
            if f['commit'][:12] in wafer:
                w = {'repo': f['repo'].split('/')[-1], 'commit': f['commit'], 'path': f['path']}
                break
        cat = 'https://github.com/Ventusltd/elements/blob/%s/APPS.md#L%d' % (E, n)
        r = {'key': k, 'id': k, 'key_source': 'register', 'name': k, 'kind': 'app',
             'purpose': 'not copied: elements@f7a92fb states no licence (owner question Q1); read it at the catalogue link',
             'catalogue': cat, 'link': link}
        r.update(licence_of(roots, link))
        r.update({'source': 'elements@f7a92fb APPS.md:%d' % n,
                  'wafer': w, 'wafer_why': None if w else 'no register file of this app has its commit on cosmos/wafer.tsv',
                  'same_as': [SAME_AS[k]] if k in SAME_AS else [], 'copied': 'linked (key only, Q1)'})
        rows.append(r)
    # ---- 25 homepage rows
    hl = homepage.decode('utf-8').split('\n')
    rx = re.compile(r'^<tr data-entity-id="([^"]+)"><th scope="row"><a href="([^"]+)">(.*?)</a><small class="entity-key">([^<]+)</small>'
                    r'</th><td><details class="entity-type"><summary>([^<]+)</summary><p>Intended purpose: (.*?)</p>')
    for n in range(SRC['homepage']['lines'][0], SRC['homepage']['lines'][1] + 1):
        m = rx.match(hl[n - 1])
        if not m:
            sys.exit('REFUSED: homepage_v134.html:%d is not an entity row' % n)
        eid, href, name, ekey, kind, purpose = [html.unescape(x) for x in m.groups()]
        if eid != ekey:
            sys.exit('REFUSED: homepage_v134.html:%d data-entity-id %s != entity-key %s' % (n, eid, ekey))
        link = POINTERS.get(href, href)
        r = {'key': 'surface:' + link, 'id': eid, 'key_source': 'homepage', 'name': name, 'kind': kind,
             'purpose': purpose, 'link': link}
        if link != href:
            r['source_href'] = href
        if link.startswith(KB_HOST):
            r['local'] = '../../' + link[len(KB_HOST):]      # the same repository: open it on the served host
        r.update(licence_of(roots, href))
        r.update({'source': 'globalgrid2050@c66759f homepage_versions/homepage_v134.html:%d' % n, 'wafer': None,
                  'wafer_why': 'a homepage entity is a served page with a version; no register file names it',
                  'same_as': [k for k, v in SAME_AS.items() if v == eid], 'copied': 'linked'})
        rows.append(r)
    # ---- the spider sandbox (issued here)
    il = index_md.decode('utf-8').split('\n')
    if V5 not in il[SRC['spider']['line'] - 1]:
        sys.exit('REFUSED: spider/INDEX.md:13 does not name v5')
    link = 'https://github.com/Ventusltd/testcode/tree/%s/spider/%s/' % (SRC['spider']['commit'], V5)
    graphs = []
    for g in GRAPHS:
        d = find_clone(roots, g['repo'])
        raw = show(d, g['commit'], g['path'])
        text, nred = redact(raw.decode('utf-8'))
        b = text.encode('utf-8')
        j = json.loads(b)
        dst = os.path.join(edition, g['file'])
        here = open(dst, 'rb').read() if os.path.exists(dst) else None
        graphs.append({'file': g['file'], 'source': '%s@%s %s' % (g['repo'], g['commit'][:7], g['path']),
                       'source_sha256': sha256(raw), 'source_bytes': len(raw), 'k1_redacted_tokens': nred,
                       'sha256': sha256(b), 'bytes': len(b), 'nodes': len(j.get('nodes', [])), 'edges': len(j.get('edges', [])),
                       'copy_matches_source': (here == b) if here is not None else 'not copied yet',
                       'licence': licence_of(roots, 'https://ventusltd.github.io/%s/' % g['repo'])['licence'],
                       'status': 'DISCLOSED (owner question Q5): copied with its sha256 and source address, byte for byte'
                                 + ('' if not nred else ' except %d token(s) naming a non-public repository, replaced by not-public (K1)' % nred)})
    r = {'key': 'surface:' + link, 'id': 'spider-sandbox', 'key_source': 'issued-here', 'issued_by': 'data/apps.json',
         'name': il[0].lstrip('# ').strip(), 'kind': 'application',
         'purpose': re.split(r'\s*\|\s*', il[SRC['spider']['line'] - 1].strip('| '))[2],
         'link': link, 'link_note': 'GitHub tree at the recorded commit: no served address of the spider is keyed (elements SURFACES.md records none; UNVERIFIED)'}
    r.update(licence_of(roots, link))
    r.update({'source': 'testcode@d09c185 spider/INDEX.md:13', 'wafer': None,
              'wafer_why': 'the spider is a folder of testcode, not a register block',
              'same_as': [], 'copied': 'linked; 2 graphs copied (DISCLOSED, Q5)', 'graphs': graphs})
    rows.append(r)
    # ---- the periodic table itself (issued here)
    if not catalogue_md.decode('utf-8').startswith('# Catalogue of elements'):
        sys.exit('REFUSED: CATALOGUE.md:1 is not the catalogue heading')
    link = 'https://ventusltd.github.io/stars/blocks/'
    r = {'key': 'surface:' + link, 'id': 'periodic-table', 'key_source': 'issued-here', 'issued_by': 'data/apps.json',
         'name': 'Periodic table', 'kind': 'catalogue',
         'purpose': "the owner's words: \"bring in periodic table\" (neural-link FIXES/NL-010/BRIEF.md:9); the catalogue's own text is not copied (Q1)",
         'catalogue': 'https://github.com/Ventusltd/elements/blob/%s/CATALOGUE.md' % E, 'link': link}
    r.update(licence_of(roots, link))
    r.update({'source': 'elements@f7a92fb CATALOGUE.md:1', 'wafer': None,
              'wafer_why': 'the catalogue is a register of blocks; its 244 elements are the layer, data/elements.json',
              'same_as': [], 'copied': 'linked; keys only copied (data/elements.json, Q1)'})
    rows.append(r)
    # K1: a link whose folder name equals a repository that is not public cannot be written; the row stays, its
    # link reads not-public and says so (the homepage line in `source` still carries it)
    for r in rows:
        if redact(r['link'])[1]:
            r['link_withheld'] = 'K1 (tools/ci_check.py): the folder name equals a repository that is not public; written as not-public, see the source line'
    # rows whose stable link is the same address cross-reference each other (7.1: same_as, never merged)
    by_link = {}
    for r in rows:
        by_link.setdefault(r['link'], []).append(r['id'])
    for r in rows:
        for other in by_link[r['link']]:
            if other != r['id'] and other not in r['same_as']:
                r['same_as'].append(other)
    out = {'schema': 'kuiper.apps.v1', 'edition': os.path.basename(os.path.normpath(edition)),
           'built_by': 'tools/apps_registry.py', 'licence': 'CC BY 4.0 (kuiper-belt data); each row carries its target\'s own licence',
           'provenance': {'sources': [
               {'repo': 'elements', 'commit': E, 'path': 'APPS.md', 'lines': '7-13', 'sha256': sha256(apps_md)},
               {'repo': 'elements', 'commit': E, 'path': 'catalogue/apps.json', 'use': 'live[0], files[] only', 'sha256': sha256(show(el, E, 'catalogue/apps.json'))},
               {'repo': 'globalgrid2050', 'commit': SRC['homepage']['commit'], 'path': SRC['homepage']['path'], 'lines': '32-56', 'sha256': sha256(homepage)},
               {'repo': 'testcode', 'commit': SRC['spider']['commit'], 'path': SRC['spider']['path'], 'lines': '13', 'sha256': sha256(index_md)},
               {'repo': 'elements', 'commit': E, 'path': 'CATALOGUE.md', 'lines': '1', 'sha256': sha256(catalogue_md)}]},
           'counts': {'register': 7, 'homepage': 25, 'issued': 2, 'total': len(rows)},
           'apps': rows}
    return out, apps_md, homepage


def check(edition, roots):
    """acceptance A1: compare data/apps.json with its two sources, by script"""
    j = json.load(open(os.path.join(edition, 'data', 'apps.json')))
    A = j['apps']
    fails = []
    def ok(c, m):
        print(('PASS ' if c else 'FAIL ') + m)
        if not c:
            fails.append(m)
    ok(len(A) == 34, 'A1 34 records (%d)' % len(A))
    for f in ('key', 'id', 'name', 'purpose', 'link', 'licence', 'source', 'key_source', 'copied'):
        ok(all(isinstance(a.get(f), str) and a[f] for a in A), 'A1 every record has a non-empty %s' % f)
    ok(all(KEY_RE.match(a['key']) for a in A), 'A1 every key matches ^(block:[A-Za-z0-9]+|surface:https://)')
    dup = {}
    for a in A:
        dup.setdefault(a['key'], []).append(a)
    ok(all(all(set(x['id'] for x in g) - {y['id']} <= set(y['same_as']) for y in g) for g in dup.values()),
       'A1 %d unique keys; rows that share a key name each other in same_as' % len(dup))
    ok(len(set(a['id'] for a in A)) == 34, 'A1 34 unique ids')
    el = find_clone(roots, 'elements'); hp = find_clone(roots, 'globalgrid2050')
    md = show(el, SRC['elements']['commit'], 'APPS.md').decode('utf-8').split('\n')
    want_b = [re.match(r'^\| `(block:[A-Za-z0-9]+)`', md[n - 1]).group(1) for n in range(7, 14)]
    got_b = [a['key'] for a in A if a['key_source'] == 'register']
    ok(got_b == want_b, 'A1 the 7 register keys equal elements@f7a92fb APPS.md:7-13 %s' % want_b)
    hl = show(hp, SRC['homepage']['commit'], SRC['homepage']['path']).decode('utf-8').split('\n')
    want_h = set(re.findall(r'<tr data-entity-id="([^"]+)"', '\n'.join(hl[31:56])))
    allh = set(re.findall(r'<tr data-entity-id="([^"]+)"', '\n'.join(hl)))
    got_h = set(a['id'] for a in A if a['key_source'] == 'homepage')
    ok(len(want_h) == 25 and got_h == want_h and allh == want_h, 'A1 the 25 homepage ids equal the data-entity-id set of homepage_v134.html (%d)' % len(got_h))
    ok(sorted(a['id'] for a in A if a['key_source'] == 'issued-here') == ['periodic-table', 'spider-sandbox'], 'A1 issued-here ids are spider-sandbox and periodic-table only')
    cat = json.loads(show(el, SRC['elements']['commit'], 'catalogue/apps.json'))
    leaked = [a['key'] for a in A if a['key_source'] == 'register' for c in cat if c['key'] == a['key']
              and (c['title'] in json.dumps(a) or c['description'] in json.dumps(a))]
    ok(not leaked, 'Q1 no register title or description copied %s' % leaked)
    ok(all(a['licence'] == 'not stated' for a in A if a['id'] == 'periodic-table'), 'Q1 the periodic table licence reads not stated')
    sp = [a for a in A if a['id'] == 'spider-sandbox'][0]
    for g in sp['graphs']:
        p = os.path.join(edition, g['file'])
        b = open(p, 'rb').read() if os.path.exists(p) else b''
        ok(sha256(b) == g['sha256'] and len(b) == g['bytes'] and g['copy_matches_source'] is True,
           'Q5 %s is the copy of %s (sha256 %s; source %s; K1 tokens replaced %d)' % (g['file'], g['source'], g['sha256'][:12], g['source_sha256'][:12], g['k1_redacted_tokens']))
    gfiles = sorted(os.listdir(os.path.join(edition, 'data', 'graphs')))
    ok(gfiles == ['overview.json', 'periodic-table.json'], 'Q5 data/graphs holds only the two DISCLOSED graphs %s' % gfiles)
    txt = open(os.path.join(edition, 'data', 'apps.json'), encoding='utf-8').read()
    ok(redact(txt)[1] == 0, 'K1 data/apps.json names no non-public repository')
    print('RESULT: %s' % ('PASS' if not fails else 'FAIL (%d)' % len(fails)))
    return 0 if not fails else 1


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--edition', required=True)
    ap.add_argument('--roots', default='/home/user/estate,/home/user')
    ap.add_argument('--check', action='store_true')
    ap.add_argument('--copy-graphs', action='store_true', help='write the two DISCLOSED graphs, byte for byte')
    a = ap.parse_args()
    roots = a.roots.split(',')
    if a.check:
        sys.exit(check(a.edition, roots))
    if a.copy_graphs:
        os.makedirs(os.path.join(a.edition, 'data', 'graphs'), exist_ok=True)
        for g in GRAPHS:
            b = redact(show(find_clone(roots, g['repo']), g['commit'], g['path']).decode('utf-8'))[0].encode('utf-8')
            open(os.path.join(a.edition, g['file']), 'wb').write(b)
            print('copied %s <- %s@%s %s (%d bytes, sha256 %s)' % (g['file'], g['repo'], g['commit'][:7], g['path'], len(b), sha256(b)))
    out, _, _ = build(roots, a.edition)
    p = os.path.join(a.edition, 'data', 'apps.json')
    s, nred = redact(json.dumps(out, indent=1, ensure_ascii=False) + '\n')
    if nred:
        print('K1: %d token(s) in the registry named a non-public repository; replaced by not-public' % nred)
    open(p, 'w', encoding='utf-8').write(s)
    print('wrote %s: %d records, %d bytes, sha256 %s' % (p, len(out['apps']), len(s.encode()), sha256(s.encode())))


if __name__ == '__main__':
    main()

PipelineNews Replay

A Python command-line tool in Legislation that fetches contract, using SHA-256. It is built from the verified JSON helper (`verified_json`) and the replay step (`replay`).

ingestlegislation / apps/pipelinenews/replay.py · lines 1–33 of 33 · Entry point · pattern replay (shared by 12 files)

What it does
It fetches contract. Defines verified_json, replay. Uses libraries hashlib, json, pathlib, urllib.parse, urllib.request. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path 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 contract.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Replay one canonical partition, select one project identity and discard its fields.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
legislation · apps/pipelinenews · Python CLI
Uses
hashlib, json, pathlib, urllib.parse, urllib.request
Used by
none found
Produces
verified_json, replay
Defines here
verified_json, replay
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 apps/pipelinenews/replay.py:1-33 · blob 9ae9bbf7738f28e56f541ec393d8a3d64813ced0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
"""Replay one canonical partition, select one project identity and discard its fields."""
from hashlib import sha256
import json
from pathlib import Path
from urllib.parse import urlencode, urljoin
from urllib.request import urlopen


def verified_json(url, digest):
    with urlopen(url, timeout=30) as response:
        body = response.read(4_000_001)
    if len(body) > 4_000_000 or sha256(body).hexdigest() != digest:
        raise ValueError(f"Canonical source size or digest changed: {url}")
    return json.loads(body)


def replay():
    spec = json.loads(Path(__file__).with_name("contract.json").read_text())
    manifest = verified_json(spec["manifest"], spec["manifest_sha256"])
    partition, = [p for p in manifest["project_partitions"] if p["path"] == spec["reference_partition"]]
    if partition["sha256"] != spec["partition_sha256"]:
        raise ValueError("Unexpected partition digest")
    data = verified_json(urljoin(spec["edition_url"], partition["path"]), partition["sha256"])
    row, = [p for p in data["projects"] if p["repd_ref"] == spec["reference"]]
    if data["schema"] != spec["partition_schema"] or row["gg_project_id"] != "GG2050-REPD-" + row["repd_ref"]:
        raise ValueError("Unexpected source schema or record identity")
    if not set(spec["date_fields"]).issubset(row):
        raise ValueError("Project date fields changed")
    return spec["edition_url"] + "?" + urlencode({"technology": "all", "q": row["repd_ref"]})


if __name__ == "__main__":
    print(replay())

Test Renewable Energy Planning Database (REPD) Ownership

A test in Legislation covering the REPD register. It is built from the ownership tests class (`OwnershipTests`).

testlegislation / apps/test_repd_ownership.py · lines 1–24 of 24 · Not reached from any entry point (candidate for review)

What it does
It tests the REPD register. Defines OwnershipTests, test_tracker_sources_are_legal_publishers, test_app_reference_contract_has_no_project_partition. Uses libraries json, pathlib, unittest, urllib.parse. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file sources.json; JSON file contract.json.
What it achieves
Protect the separation between project lookup, legal collection and app-owned REPD data.
Why it matters
No other file in the estate was found to import it.
Application
legislation · apps · test
Uses
json, pathlib, unittest, urllib.parse
Used by
none found
Produces
OwnershipTests
Defines here
OwnershipTests, test_tracker_sources_are_legal_publishers, test_app_reference_contract_has_no_project_partition
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 apps/test_repd_ownership.py:1-24 · blob af726aebe024d5c8bf0abd90423d683f627fa594 · 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: unreached_review
"""Protect the separation between project lookup, legal collection and app-owned REPD data."""
import json
from pathlib import Path
import unittest
from urllib.parse import urlparse

ROOT = Path(__file__).resolve().parents[1]


class OwnershipTests(unittest.TestCase):
    def test_tracker_sources_are_legal_publishers(self):
        sources = json.loads((ROOT / "tracking/sources.json").read_bytes())
        for row in sources:
            url = urlparse(row["url"])
            self.assertNotIn("repd", url.geturl().lower())
            self.assertNotIn("renewable-energy-planning-database", url.geturl().lower())
            self.assertNotIn(url.hostname, {"globalgrid2050.com", "ventusltd.github.io"})

    def test_app_reference_contract_has_no_project_partition(self):
        contract = json.loads((ROOT / "apps/pipelinenews/contract.json").read_bytes())
        self.assertRegex(contract["reference"], r"^[1-9][0-9]*$")
        self.assertNotIn("projects", contract)
        self.assertEqual(urlparse(contract["manifest"]).hostname, "globalgrid2050.com")
        self.assertFalse(list((ROOT / "apps").rglob("part-*.json")))

Verify Registry

A JavaScript module in the protections folder of Legislation that reads legal evidence, using SHA-256.

renderlegislation / protections/verify-registry.mjs · lines 1–33 of 33 · Entry point

What it does
It loads legal evidence. Defines read, sha256, check. Uses libraries node:assert/strict, node:crypto, node:fs, node:path, node:child_process. Side effects: changes the web page (DOM); 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 legal-evidence.json; command-line arguments.
Downstream impact
Used directly by 1 file: Verify Workflow (legislation).
What it achieves
It is built from the read step (`read`), the sha256 step (`sha256`) and the check step (`check`). Replay the admitted legal vaccine in CVAA's own data-only worker.
Why it matters
Run by Verify Workflow.
Application
legislation · protections · JavaScript module
Uses
node:assert/strict, node:crypto, node:fs, node:path, node:child_process
Used by
run by Verify Workflow (workflow run)
Produces
read, sha256, check
Defines here
read, sha256, check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
legislation@960afbd0f5393e818b400a7f1a523acd6814e217 protections/verify-registry.mjs:1-33 · blob 9cd4f993ac751087706fab1fa95cbe0d976fe4db · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
// Replay the admitted legal vaccine in CVAA's own data-only worker.
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';

const [registry, contractPath] = process.argv.slice(2);
const vaccine = '202611280012-legal-evidence-screening.md';
const read = path => readFileSync(path, 'utf8');
const lock = JSON.parse(read(join(registry, 'vaccines.lock')));
const document = read(join(registry, 'vaccines', vaccine)).replaceAll('\r\n', '\n');
const sha256 = text => createHash('sha256').update(text).digest('hex');
assert.equal(sha256(document), lock[vaccine], 'admitted antibody digest');
const code = document.match(/```js\n([\s\S]*?)\n```/)?.[1];
assert.ok(code, 'admitted antibody has an executable body');
const receipt = read(contractPath);
const check = document => {
  const contract = { file: 'legal-evidence.json', document, error: null };
  const child = spawnSync(process.execPath, [join(registry, 'tools', 'antibody-runner.mjs')], {
    env: {}, timeout: 5000, encoding: 'utf8',
    input: JSON.stringify({code, ctx: {controlContracts: [contract]}})
  });
  assert.equal(child.status, 0, child.error?.message || child.stderr);
  const result = JSON.parse(child.stdout);
  assert.equal(result.ok, true, result.e);
  assert.ok(!result.skip, 'actual contract evaluated');
  return result.r;
};
assert.deepEqual(check(JSON.parse(receipt)), [], 'live consumer receipt');
assert.deepEqual(check({schema: 'invalid'}), ['invalid-receipt'], 'adverse control');
console.log(JSON.stringify({vaccine, vaccine_sha256: lock[vaccine], contract: contractPath,
  receipt_sha256: sha256(receipt), findings: [], adverse_control: 'invalid-receipt'}));