GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Cables and conductors / cable-trench-or-drill / tools

Route Constraints Test and 4 more files

A test in the tools folder of Cable Trench or Drill that checks Route Constraints, using SHA-256.

597 lines of Python and JavaScript from cable-trench-or-drill, in 5 files. Topic: Cables and conductors. Section 6 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. Route Constraints Test test · cable-trench-or-drill / tools/route-constraints.test.mjs lines 1–180
  2. Test Verify test · cable-trench-or-drill / tools/test_verify.py lines 1–62
  3. Test Verify Derived test · cable-trench-or-drill / tools/test_verify_derived.py lines 1–101
  4. Verify storage · cable-trench-or-drill / tools/verify.py lines 1–127
  5. Verify Derived storage · cable-trench-or-drill / tools/verify_derived.py lines 1–127

Route Constraints Test

A test in the tools folder of Cable Trench or Drill that checks Route Constraints, using SHA-256.

testcable-trench-or-drill / tools/route-constraints.test.mjs · lines 1–180 of 180 · Entry point

What it does
It tests its inputs. Defines check, stubEngine, fetchFor. Uses libraries node:fs, node:url, node:path, node:crypto. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: JSON file engine-pin.json.
Downstream impact
Used directly by 1 file: Verify Route Constraints Workflow (cable-trench-or-drill).
What it achieves
It is built from the check step (`check`), the stub engine helper (`stubEngine`) and the fetch for helper (`fetchFor`). The second result must never become the first.
Why it matters
Run by Verify Route Constraints Workflow.
Application
cable-trench-or-drill · tools · test
Uses
Route Constraints (import), node:fs, node:url, node:path, node:crypto
Used by
run by Verify Route Constraints Workflow (workflow run)
Produces
check, stubEngine, fetchFor
Defines here
check, stubEngine, fetchFor
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a tools/route-constraints.test.mjs:1-180 · blob 57e66583e5b457ad4ee127dd03ddc91b4c9cef3c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
/* route-constraints.test.mjs — the second result must never become the first.
 *
 * The checks that matter here are the refusals: a moved engine, an unreachable
 * one, a wrong schema, and a route the engine will not estimate. In every one
 * of those the direct first pass must still be returned intact, because it is a
 * measurement and it does not stop being one because the constrained result
 * failed.
 *
 * The engine is stubbed. This test proves the CARTRIDGE's contract — pinning,
 * verification, refusal and the preserved first pass. The mathematics itself is
 * proven in ventus-grid-engine by proofs/route-obstacles.proof.mjs, and
 * duplicating those assertions here would create exactly the second copy this
 * cartridge exists to avoid.
 *
 * Run: node tools/route-constraints.test.mjs
 */

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { createHash } from 'node:crypto';
import * as rc from '../src/route-constraints/route-constraints.js';

const here = dirname(fileURLToPath(import.meta.url));
const pinPath = join(here, '..', 'src', 'route-constraints', 'engine-pin.json');
const pin = JSON.parse(readFileSync(pinPath, 'utf8'));

const failures = [];
let passed = 0;
const check = (n, c) => { c ? passed += 1 : failures.push(n); };

/* A stand-in for the engine module, with the shape the cartridge relies on. */
const STUB_SOURCE = 'export const schema = "ventus-grid-engine.route-obstacles.v1";\n';
const STUB_SHA = createHash('sha256').update(STUB_SOURCE).digest('hex');

function stubEngine({ blocked = false } = {}) {
    return {
        schema: 'ventus-grid-engine.route-obstacles.v1',
        routeEstimate({ straightLineKm, crossings, corridorFactor }) {
            const undeclared = crossings.filter(c => c.widthM === undefined).map(c => c.type);
            if (blocked) {
                return { value: null, straightLineKm, schedule: { undeclaredLengths: undeclared, blockedBy: ['Open water / sea'] },
                    basis: 'blocked by open water' };
            }
            return { value: straightLineKm * corridorFactor, straightLineKm,
                schedule: { undeclaredLengths: undeclared, blockedBy: [] }, basis: 'ok' };
        }
    };
}

/* A fetch that serves our pin and our stub, with the pin's hash rewritten so
   the happy path verifies. */
function fetchFor({ source = STUB_SOURCE, sha = STUB_SHA, status = 200 } = {}) {
    const patched = { ...pin, engine: { ...pin.engine, contentSha256: sha } };
    return async (url) => {
        const s = String(url);
        if (s.endsWith('engine-pin.json')) return { ok: true, json: async () => patched };
        return { ok: status === 200, status, text: async () => source };
    };
}

/* ── The pin itself. ────────────────────────────────────────────────────── */

check('the pin names an exact engine commit, blob and content hash',
    /^[0-9a-f]{40}$/.test(pin.engine.commit)
    && /^[0-9a-f]{40}$/.test(pin.engine.gitBlob)
    && /^[0-9a-f]{64}$/.test(pin.engine.contentSha256));

check('the pin states that the direct first pass remains unchanged',
    /never a replacement/i.test(pin.firstPass.statement)
    && /stage 3/i.test(pin.firstPass.statement));

check('the pin explains why bytes are pinned rather than a URL trusted',
    /pins bytes, not URLs/i.test(pin.why));

/* ── The first pass, always. ────────────────────────────────────────────── */

check('the direct first pass returns the distance it was given, unmodified',
    rc.directFirstPass({ straightLineKm: 142.21 }).value === 142.21);

check('the first pass says in words that it is not a route',
    /is not a route/i.test(rc.directFirstPass({ straightLineKm: 10 }).basis));

/* ── Happy path. ────────────────────────────────────────────────────────── */
{
    rc.reset();
    const loaded = await rc.load({ fetchImpl: fetchFor(), importImpl: async () => stubEngine() });
    check('a module whose bytes match the pin loads', loaded.state === 'ready');

    const a = await rc.assess({ straightLineKm: 10, crossings: [{ type: 'motorway', widthM: 30, setbackM: 15 }], corridorFactor: 1.245, loaded });
    check('an assessed route returns both the first pass and the constrained result',
        a.state === 'assessed' && a.firstPass.value === 10
        && Math.abs(a.constrained.value - 12.45) < 1e-9);
    check('the engine commit travels with the answer', a.engineCommit === pin.engine.commit);
    check('a fully declared route reports declared coverage', a.coverage.state === 'declared');
    check('the note keeps the screening caveat and says it never replaces the first pass',
        /never in place of it/i.test(a.note));
}

/* ── Unknown coverage is a state, not a zero. ───────────────────────────── */
{
    rc.reset();
    const loaded = await rc.load({ fetchImpl: fetchFor(), importImpl: async () => stubEngine() });
    const a = await rc.assess({ straightLineKm: 10, crossings: [{ type: 'railway' }], corridorFactor: 1.245, loaded });
    check('a crossing with no width declared reports UNKNOWN coverage and names it',
        a.coverage.state === 'unknown' && a.coverage.undeclared.includes('railway'));
    check('the coverage note says unknown coverage is a state and not a zero',
        /state, not a zero/i.test(a.coverage.note));
}

/* ── The engine refusing is not the cartridge failing. ──────────────────── */
{
    rc.reset();
    const loaded = await rc.load({ fetchImpl: fetchFor(), importImpl: async () => stubEngine({ blocked: true }) });
    const a = await rc.assess({ straightLineKm: 142.21, crossings: [{ type: 'open_water' }], corridorFactor: 1.245, loaded });
    check('a route the engine will not estimate returns no-result, not an error',
        a.state === 'no-result' && a.constrained.value === null);
    check('and the direct first pass is STILL returned intact, because it is a measurement',
        a.firstPass.value === 142.21);
    check('the note says the first pass stands and is unchanged',
        /first pass above stands and is unchanged/i.test(a.note));
}

/* ── Integrity failures. Each must refuse, and each must keep the first pass. ── */
{
    rc.reset();
    const moved = await rc.load({
        fetchImpl: fetchFor({ source: 'export const schema = "something-else";\n' }),
        importImpl: async () => stubEngine()
    });
    check('a module whose bytes differ from the pin is REFUSED', moved.state === 'refused');
    check('the refusal says the engine has moved and names the pinned commit',
        /does not match the pinned bytes/i.test(moved.reason) && moved.reason.includes(pin.engine.commit.slice(0, 7)));
    check('the refusal says a route assessment must not change because a dependency changed',
        /must not change because a\s+dependency changed/i.test(moved.reason.replace(/\s+/g, ' '))
        || /must not change because a dependency changed/i.test(moved.reason.replace(/\s+/g, ' ')));

    const a = await rc.assess({ straightLineKm: 55, crossings: [], corridorFactor: 1.245, loaded: moved });
    check('after a pin mismatch the assessment refuses but STILL returns the first pass',
        a.state === 'refused' && a.firstPass.value === 55 && a.constrained === null);
    check('the refusal note says only the second result is unavailable',
        /Only the constraint-aware\s+second result is unavailable/i.test(a.note.replace(/\s+/g, ' '))
        || /only the constraint-aware second result is unavailable/i.test(a.note.replace(/\s+/g, ' ')));
}

{
    rc.reset();
    const down = await rc.load({ fetchImpl: fetchFor({ status: 503 }), importImpl: async () => stubEngine() });
    check('an unreachable engine is refused with its HTTP status',
        down.state === 'refused' && /HTTP 503/.test(down.reason));
}

{
    rc.reset();
    const wrongSchema = await rc.load({
        fetchImpl: fetchFor(),
        importImpl: async () => ({ schema: 'ventus-grid-engine.route-obstacles.v2', routeEstimate: () => ({}) })
    });
    check('a module with an unexpected schema is refused even when its bytes hash correctly',
        wrongSchema.state === 'refused' && /declares schema/i.test(wrongSchema.reason));
}

/* ── The boundary. ──────────────────────────────────────────────────────── */
{
    const callable = Object.keys(rc).filter(k => typeof rc[k] === 'function');
    check('the cartridge exposes no router, optimiser or pricing function',
        callable.every(n => !/route(r|Find)|optimi[sz]e|cost|price|permit/i.test(n)));
    check('what is not implemented is stated, not left as an empty space',
        ['automatedRouting', 'cost', 'permission'].every(k => k in rc.NOT_IMPLEMENTED));
    check('the cartridge holds no copy of the crossing mathematics',
        !readFileSync(join(here, '..', 'src', 'route-constraints', 'route-constraints.js'), 'utf8')
            .match(/OBSTACLES\s*=|trenchless:\s*true/));
}

if (failures.length) {
    console.error('route-constraints test FAILED (' + failures.length + ' of '
        + (failures.length + passed) + '):\n- ' + failures.join('\n- '));
    process.exit(1);
}
console.log('route-constraints test PASS — ' + passed + ' checks');

Test Verify

A test in the tools folder of Cable Trench or Drill that uses SHA-256. It sets up (`setUp`) and is built from the original runtime class (`OriginalRuntime`).

testcable-trench-or-drill / tools/test_verify.py · lines 1–62 of 62 · Entry point

What it does
It tests its inputs. Defines 7 functions or classes, including OriginalRuntime, setUp, test_original_and_query_resource_pass, test_changed_formula_bytes_fail, test_missing_dependency_fails. Uses libraries hashlib, importlib.util, tempfile, unittest, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'cable'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 1 file: Verify Original Workflow (cable-trench-or-drill).
What it achieves
Defines `OriginalRuntime`, `setUp`, `test_original_and_query_resource_pass` and 4 more.
Why it matters
Run by Verify Original Workflow.
Application
cable-trench-or-drill · tools · test
Uses
hashlib, importlib.util, tempfile, unittest, pathlib
Used by
run by Verify Original Workflow (workflow run)
Produces
OriginalRuntime
Defines here
OriginalRuntime, setUp, test_original_and_query_resource_pass, test_changed_formula_bytes_fail, test_missing_dependency_fails, test_invalid_javascript_is_not_excused_by_matching_digest, test_cross_owner_navigation_requires_explicit_pin
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a tools/test_verify.py:1-62 · blob 915d0d9cd403907e2ea350df45e66d4d442bec40 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
import hashlib
import importlib.util
import tempfile
import unittest
from pathlib import Path

spec = importlib.util.spec_from_file_location('original_verify', Path(__file__).with_name('verify.py'))
verify = importlib.util.module_from_spec(spec)
spec.loader.exec_module(verify)


class OriginalRuntime(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
        self.root = Path(self.temp.name)
        (self.root / 'index.html').write_bytes(b'<script src="app.js?v=1"></script>')
        (self.root / 'app.js').write_bytes(b'const original = 1;')
        self.manifest = {'schema': 'globalgrid.original-runtime.v1', 'generation': '202609051855',
                         'origin': {'repository': 'fixture', 'commit': 'a' * 40},
                         'applications': [{'id': 'fixture', 'entry': 'index.html'}], 'files': []}
        for name in ('index.html', 'app.js'):
            raw = (self.root / name).read_bytes()
            self.manifest['files'].append({'path': name, 'bytes': len(raw), 'sha256': hashlib.sha256(raw).hexdigest(),
                'gitBlob': hashlib.sha1(b'blob ' + str(len(raw)).encode() + b'\0' + raw).hexdigest()})

    def test_original_and_query_resource_pass(self):
        result = verify.verify(self.root, self.manifest)
        self.assertTrue(result['ok'], result)
        self.assertEqual(result['relativeHtmlResources'], 1)

    def test_changed_formula_bytes_fail(self):
        (self.root / 'app.js').write_bytes(b'const original = 2;')
        result = verify.verify(self.root, self.manifest)
        self.assertTrue(any('baseline bytes changed' in e for e in result['errors']))
        self.assertTrue(any('Git blob mismatch' in e for e in result['errors']))

    def test_missing_dependency_fails(self):
        (self.root / 'app.js').unlink()
        result = verify.verify(self.root, self.manifest)
        self.assertTrue(any('missing relative HTML resource' in e for e in result['errors']))

    def test_invalid_javascript_is_not_excused_by_matching_digest(self):
        raw = b'const broken = ;'
        (self.root / 'app.js').write_bytes(raw)
        self.manifest['files'][1].update(bytes=len(raw), sha256=hashlib.sha256(raw).hexdigest(),
            gitBlob=hashlib.sha1(b'blob ' + str(len(raw)).encode() + b'\0' + raw).hexdigest())
        result = verify.verify(self.root, self.manifest)
        self.assertTrue(any('JavaScript parse failure' in e for e in result['errors']))

    def test_cross_owner_navigation_requires_explicit_pin(self):
        raw = b'<a href="gis/index.html">GIS</a>'
        (self.root / 'index.html').write_bytes(raw)
        self.manifest['files'][0].update(bytes=len(raw), sha256=hashlib.sha256(raw).hexdigest(),
            gitBlob=hashlib.sha1(b'blob ' + str(len(raw)).encode() + b'\0' + raw).hexdigest())
        self.assertFalse(verify.verify(self.root, self.manifest)['ok'])
        self.manifest['crossOwnerNavigation'] = [{'path': 'gis/index.html', 'commit': 'b' * 40, 'manifestSha256': 'c' * 64}]
        result = verify.verify(self.root, self.manifest)
        self.assertTrue(result['ok'], result)
        self.assertEqual(result['declaredCrossOwnerLinks'], 1)


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

Test Verify Derived

A test in the tools folder of Cable Trench or Drill that checks Verify Derived, using SHA-256.

testcable-trench-or-drill / tools/test_verify_derived.py · lines 1–101 of 101 · Entry point · pattern test_valid_release_passes_despite_dirty_unrelated_baseline_worktree (shared by 2 files)

What it does
It tests its inputs. Defines 19 functions or classes, including DerivedRelease, setUp, git, encode, sha. Uses libraries copy, hashlib, json, subprocess, tempfile. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'cable'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file latest.json; JSON file derived-latest.json.
Downstream impact
Used directly by 1 file: Verify Derived Workflow (cable-trench-or-drill).
What it achieves
It sets up (`setUp`) and is built from the derived release class (`DerivedRelease`) and the encode step (`encode`). Defines `DerivedRelease`, `setUp`, `git` and 16 more. It writes `latest.json`.
Why it matters
Run by Verify Derived Workflow.
Application
cable-trench-or-drill · tools · test
Uses
Verify Derived (import), copy, hashlib, json, subprocess, tempfile, unittest, pathlib
Used by
run by Verify Derived Workflow (workflow run)
Produces
DerivedRelease
Defines here
DerivedRelease, setUp, git, encode, sha, write, record, pin, replace, refused, test_valid_release_passes_despite_dirty_unrelated_baseline_worktree, test_formula_change_fails_even_with_rehashed_manifest, test_extra_entry_change_fails_even_with_rehashed_manifest, test_cartridge_must_match_maintained_source, test_unknown_role_traversal_duplicate_and_missing_member_fail, test_missing_or_unpinned_sibling_fails, test_github_repository_url_is_supported_but_other_host_is_not, test_baseline_and_pointer_hashes_are_checked, test_syntax_is_checked_even_when_cartridge_matches_source
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a tools/test_verify_derived.py:1-101 · blob d607b9d4d68645475b09986b5ed0044678ef0c89 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
import copy
import hashlib
import json
import subprocess
import tempfile
import unittest
from pathlib import Path
from verify_derived import verify, ENTRY, CARTRIDGE, SOURCE, INSERTION


class DerivedRelease(unittest.TestCase):
    def setUp(self):
        temp = tempfile.TemporaryDirectory(); self.addCleanup(temp.cleanup); self.root = Path(temp.name)
        def git(*args):
            return subprocess.check_output(['git', '-C', str(self.root), *args], stderr=subprocess.PIPE).decode().strip()
        self.git = git; git('init', '-q'); git('config', 'user.name', 'Fixture'); git('config', 'user.email', 'fixture@example.invalid'); git('config', 'core.autocrlf', 'false')
        self.basegen = '202609051921'; self.gen = '202609051959'
        self.original = {ENTRY: b'<html><body><script src="app.js"></script><a href="../sibling/index.html">Sibling</a></body></html>',
                         ENTRY.replace('index.html', 'app.js'): b'const calculation = 120;'}
        files = []
        for path, raw in self.original.items():
            self.write(f'releases/{self.basegen}/' + path, raw); files.append(self.record(path, raw))
        manifest = {'schema': 'globalgrid.original-runtime.v1', 'generation': self.basegen, 'files': files}
        raw = self.encode(manifest); self.write(f'releases/{self.basegen}/manifest.json', raw)
        self.write('latest.json', self.encode({'generation': self.basegen, 'manifest': f'releases/{self.basegen}/manifest.json', 'manifestSha256': self.sha(raw)}))
        git('add', '.'); git('commit', '-qm', 'baseline'); self.commit = git('rev-parse', 'HEAD')
        self.release = self.root / 'releases' / self.gen
        cartridge = b'(() => { const guarded = true; })();'; self.write(SOURCE, cartridge)
        derived = {**self.original, CARTRIDGE: cartridge}; derived[ENTRY] = derived[ENTRY].replace(b'</body>', INSERTION.encode() + b'</body>')
        self.manifest = {'schema': 'globalgrid.derived-runtime.v1', 'generation': self.gen,
            'baseline': {'commit': self.commit, 'generation': self.basegen, 'manifestSha256': self.sha(raw)},
            'applications': [{'id': 'cable-geometry-visualiser', 'entry': ENTRY}],
            'composition': {'entry': ENTRY, 'insertBefore': '</body>', 'insertion': INSERTION},
            'cartridge': {'path': CARTRIDGE, 'sourcePath': SOURCE},
            'crossOwnerNavigation': [{'path': 'solar-bess-topology-v7/sibling/index.html', 'repository': 'Ventusltd/sibling', 'commit': 'b' * 40, 'manifestSha256': 'c' * 64}],
            'files': []}
        for path, contents in derived.items():
            self.write(f'releases/{self.gen}/' + path, contents)
            role = 'composed-entry' if path == ENTRY else 'cartridge' if path == CARTRIDGE else 'original'
            self.manifest['files'].append({**self.record(path, contents), 'role': role})
        self.pin()

    @staticmethod
    def encode(value): return (json.dumps(value, indent=2) + '\n').encode()
    @staticmethod
    def sha(raw): return hashlib.sha256(raw).hexdigest()
    def write(self, path, raw):
        p = self.root / path; p.parent.mkdir(parents=True, exist_ok=True); p.write_bytes(raw)
    def record(self, path, raw): return {'path': path, 'bytes': len(raw), 'sha256': self.sha(raw)}
    def pin(self):
        raw = self.encode(self.manifest); self.write(f'releases/{self.gen}/manifest.json', raw)
        self.write('derived-latest.json', self.encode({'generation': self.gen, 'manifest': f'releases/{self.gen}/manifest.json', 'manifestSha256': self.sha(raw)}))
    def replace(self, path, raw):
        self.write(f'releases/{self.gen}/' + path, raw)
        next(x for x in self.manifest['files'] if x['path'] == path).update(self.record(path, raw)); self.pin()
    def refused(self, text):
        result = verify(self.root); self.assertFalse(result['ok'], result); self.assertIn(text, ' '.join(result['errors']))

    def test_valid_release_passes_despite_dirty_unrelated_baseline_worktree(self):
        self.write(f'releases/{self.basegen}/' + ENTRY, b'dirty working copy')
        result = verify(self.root); self.assertTrue(result['ok'], result); self.assertEqual(result['files'], 3)

    def test_formula_change_fails_even_with_rehashed_manifest(self):
        self.replace(ENTRY.replace('index.html', 'app.js'), b'const calculation = 121;'); self.refused('original runtime changed')

    def test_extra_entry_change_fails_even_with_rehashed_manifest(self):
        self.replace(ENTRY, (self.release / ENTRY).read_bytes().replace(b'Sibling', b'Changed')); self.refused('single insertion')

    def test_cartridge_must_match_maintained_source(self):
        self.replace(CARTRIDGE, b'const other = 1;'); self.refused('maintained cartridge differs')

    def test_unknown_role_traversal_duplicate_and_missing_member_fail(self):
        original = copy.deepcopy(self.manifest)
        for mutate, message in [
            (lambda m: m['files'][0].update(role='unverified'), 'unknown file role'),
            (lambda m: m['files'][0].update(path='../outside'), 'path traversal'),
            (lambda m: m['files'].append(copy.deepcopy(m['files'][0])), 'duplicate'),
            (lambda m: m['files'].pop(), 'closure')]:
            self.manifest = copy.deepcopy(original); mutate(self.manifest); self.pin(); self.refused(message)

    def test_missing_or_unpinned_sibling_fails(self):
        original = copy.deepcopy(self.manifest)
        self.manifest['crossOwnerNavigation'] = []; self.pin(); self.refused('missing or unmanifested')
        self.manifest = original; self.manifest['crossOwnerNavigation'][0]['commit'] = 'main'; self.pin(); self.refused('unbound cross-owner')

    def test_github_repository_url_is_supported_but_other_host_is_not(self):
        pin = self.manifest['crossOwnerNavigation'][0]
        pin['repository'] = 'https://github.com/Ventusltd/sibling'; self.pin()
        self.assertTrue(verify(self.root)['ok'])
        pin['repository'] = 'https://wrong.example/Ventusltd/sibling'; self.pin(); self.refused('unbound cross-owner')

    def test_baseline_and_pointer_hashes_are_checked(self):
        self.manifest['baseline']['manifestSha256'] = '0' * 64; self.pin(); self.refused('baseline manifest hash')
        (self.release / 'manifest.json').write_bytes(b'{}'); self.refused('derived manifest pointer hash')

    def test_syntax_is_checked_even_when_cartridge_matches_source(self):
        raw = b'function broken('; self.write(SOURCE, raw); self.replace(CARTRIDGE, raw); self.refused('JavaScript parse failure')


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

Verify

A Python command-line tool in the tools folder of Cable Trench or Drill that verifies original bytes, JavaScript syntax and local HTML dependency paths, using SHA-256.

storagecable-trench-or-drill / tools/verify.py · lines 1–127 of 127 · Entry point · pattern handle_endtag (shared by 10 files)

What it does
Defines 7 functions or classes, including Resources, __init__, handle_starttag, handle_data, handle_endtag. Uses libraries argparse, hashlib, json, subprocess, tempfile. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'cable'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file latest.json; command-line arguments.
Downstream impact
Used directly by 2 files: Verify Derived (cable-trench-or-drill); Verify Original Workflow (cable-trench-or-drill). Reached from 2 other entry points, including Verify Derived Workflow (cable-trench-or-drill); Test Verify Derived (cable-trench-or-drill).
What it achieves
It is built from the resources class (`Resources`), the handle endtag helper (`handle_endtag`) and the verify step (`verify`). Defines `Resources`, `handle_starttag`, `handle_data` and 2 more. It accepts `--root`, `--source` and `--expected-origin`.
Why it matters
Imported by Verify Derived. Run by Verify Original Workflow.
Application
cable-trench-or-drill · tools · Python CLI
Uses
argparse, hashlib, json, subprocess, tempfile, html.parser, pathlib, urllib.parse
Used by
imported by Verify Derived (import), run by Verify Original Workflow (workflow run)
Produces
Resources, verify, main
Defines here
Resources, __init__, handle_starttag, handle_data, handle_endtag, verify, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a tools/verify.py:1-127 · blob 43f9ec67dbe53bb4544f023f8d64fb8ebb3b590e · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
"""Verify original bytes, JavaScript syntax and local HTML dependency paths."""
import argparse
import hashlib
import json
import subprocess
import tempfile
from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import unquote, urlsplit


class Resources(HTMLParser):
    def __init__(self):
        super().__init__()
        self.urls = []
        self.inline = []
        self.script = None

    def handle_starttag(self, tag, attrs):
        values = dict(attrs)
        for key in ('src', 'href'):
            if values.get(key):
                self.urls.append((tag, values[key]))
        if tag == 'script' and not values.get('src') and values.get('type', '') in ('', 'text/javascript', 'module'):
            self.script = []

    def handle_data(self, data):
        if self.script is not None:
            self.script.append(data)

    def handle_endtag(self, tag):
        if tag == 'script' and self.script is not None:
            self.inline.append(''.join(self.script))
            self.script = None


def verify(root, manifest, source=None):
    errors, scripts, resources, cross_owner_links = [], 0, 0, 0
    if manifest.get('schema') != 'globalgrid.original-runtime.v1':
        errors.append('unsupported baseline schema')
    if source:
        # A publication worktree can have advanced; git show still reads exactly the pinned revision.
        exists = subprocess.run(['git', '-C', str(source), 'cat-file', '-e', manifest['origin']['commit'] + '^{commit}'], capture_output=True)
        if exists.returncode:
            errors.append('pinned origin commit missing from source checkout')
    listed = {item['path'] for item in manifest['files']}
    cross_owner = {item['path']: item for item in manifest.get('crossOwnerNavigation', [])}
    for item in manifest['files']:
        path = (root / item['path']).resolve()
        if not path.is_relative_to(root.resolve()):
            errors.append('file escapes immutable release'); continue
        try:
            raw = path.read_bytes()
        except OSError:
            errors.append('missing file: ' + item['path']); continue
        if len(raw) != item['bytes'] or hashlib.sha256(raw).hexdigest() != item['sha256']:
            errors.append('baseline bytes changed: ' + item['path'])
        blob = hashlib.sha1(b'blob ' + str(len(raw)).encode() + b'\0' + raw).hexdigest()
        if blob != item['gitBlob']:
            errors.append('original Git blob mismatch: ' + item['path'])
        if source:
            result = subprocess.run(['git', '-C', str(source), 'show', manifest['origin']['commit'] + ':' + item['path']], capture_output=True)
            if result.returncode or result.stdout != raw:
                errors.append('origin revision differs: ' + item['path'])
        chunks = []
        if path.suffix == '.js':
            chunks.append(raw.decode('utf8'))
        if path.suffix == '.html':
            parser = Resources(); parser.feed(raw.decode('utf8')); chunks.extend(parser.inline)
            for tag, url in parser.urls:
                parsed = urlsplit(url)
                if parsed.scheme or parsed.netloc or not parsed.path or parsed.path.startswith('/'):
                    continue
                resources += 1
                resolved = (path.parent / unquote(parsed.path)).resolve()
                relative = resolved.relative_to(root.resolve()).as_posix() if resolved.is_relative_to(root.resolve()) else None
                if tag == 'a' and relative in cross_owner:
                    import re
                    dependency = cross_owner[relative]
                    if not re.fullmatch('[0-9a-f]{40}', dependency.get('commit', '')) or not re.fullmatch('[0-9a-f]{64}', dependency.get('manifestSha256', '')):
                        errors.append('unbound cross-owner navigation: ' + relative)
                    cross_owner_links += 1
                    continue
                if not resolved.is_relative_to(root.resolve()) or not resolved.is_file():
                    errors.append('missing relative HTML resource: ' + item['path'] + ' -> ' + url)
                elif resolved.relative_to(root.resolve()).as_posix() not in listed:
                    errors.append('unmanifested relative HTML resource: ' + url)
        for chunk in chunks:
            if not chunk.strip(): continue
            with tempfile.TemporaryDirectory() as temp:
                script = Path(temp) / 'parse.js'; script.write_text(chunk, encoding='utf8')
                result = subprocess.run(['node', '--check', str(script)], capture_output=True, text=True)
                scripts += 1
                if result.returncode: errors.append('JavaScript parse failure: ' + item['path'] + ': ' + result.stderr[-500:])
    for app in manifest['applications']:
        if app['entry'] not in listed: errors.append('application entry is not manifested: ' + app['id'])
    return {'ok': not errors, 'generation': manifest['generation'], 'origin': manifest['origin'],
            'files': len(listed), 'javascriptParses': scripts, 'relativeHtmlResources': resources, 'declaredCrossOwnerLinks': cross_owner_links,
            'errors': errors, 'scope': 'Byte preservation, syntax and declared local dependencies; no browser behavior or engineering acceptance claim.'}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument('--source', type=Path)
    parser.add_argument('--expected-origin')
    parser.add_argument('--out', type=Path)
    args = parser.parse_args()
    latest = json.loads((args.root / 'latest.json').read_bytes())
    manifest_path = args.root / latest['manifest']; raw = manifest_path.read_bytes()
    if hashlib.sha256(raw).hexdigest() != latest['manifestSha256']:
        raise SystemExit('latest pointer manifest digest mismatch')
    manifest = json.loads(raw)
    if args.expected_origin and manifest['origin']['commit'] != args.expected_origin:
        raise SystemExit('baseline origin differs from required source revision')
    if manifest['generation'] != latest['generation']:
        raise SystemExit('latest pointer generation mismatch')
    result = verify(manifest_path.parent, manifest, args.source)
    if args.out:
        args.out.parent.mkdir(parents=True, exist_ok=True)
        args.out.write_text(json.dumps(result, indent=2) + '\n', encoding='utf8')
    print(json.dumps(result))
    raise SystemExit(0 if result['ok'] else 1)


if __name__ == '__main__':
    main()

Verify Derived

A Python command-line tool in the tools folder of Cable Trench or Drill that works with git bytes (`git_bytes`), covering cables, using SHA-256.

storagecable-trench-or-drill / tools/verify_derived.py · lines 1–127 of 127 · Entry point · pattern git_bytes (shared by 4 files)

What it does
Defines digest, safe, git_bytes, verify, require. Uses libraries argparse, hashlib, json, re, subprocess. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'cable'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables.
Inputs & outputs
In: JSON file derived-latest.json; JSON file latest.json; command-line arguments.
Downstream impact
Used directly by 2 files: Test Verify Derived (cable-trench-or-drill); Verify Derived Workflow (cable-trench-or-drill).
What it achieves
It is built from the digest step (`digest`), the safe step (`safe`) and the verify step (`verify`). Verify an explicit Cable derived release without weakening the original baseline gate. It accepts `--root` and `--out`.
Why it matters
Run by Verify Derived Workflow. Checked by Test Verify Derived.
Application
cable-trench-or-drill · tools · Python CLI
Uses
Verify (import), argparse, hashlib, json, re, subprocess, tempfile, pathlib, urllib.parse
Used by
imported by Test Verify Derived (import), run by Verify Derived Workflow (workflow run)
Produces
digest, safe, git_bytes, verify
Defines here
digest, safe, git_bytes, verify, require
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a tools/verify_derived.py:1-127 · blob 907710fc4ca8f0a0a8bd88ab107c2a0de09abb4d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
"""Verify an explicit Cable derived release without weakening the original baseline gate."""
import argparse
import hashlib
import json
import re
import subprocess
import tempfile
from pathlib import Path, PurePosixPath
from urllib.parse import unquote, urlsplit
from verify import Resources

PREFIX = 'solar-bess-topology-v7/cable-geometry-visualiser/'
ENTRY = PREFIX + 'index.html'
CARTRIDGE = PREFIX + 'render-readiness.js'
SOURCE = 'src/cable-geometry/render-readiness.js'
INSERTION = '<script src="./render-readiness.js"></script>\n'


def digest(raw):
    return hashlib.sha256(raw).hexdigest()


def safe(root, name):
    if not isinstance(name, str) or '\\' in name or ':' in name:
        raise ValueError('invalid relative path')
    relative = PurePosixPath(name)
    if relative.is_absolute() or '..' in relative.parts or not relative.parts:
        raise ValueError('path traversal refused: ' + name)
    path = (root / name).resolve()
    if not path.is_relative_to(root.resolve()):
        raise ValueError('path escapes release: ' + name)
    return path


def git_bytes(repo, commit, path):
    return subprocess.check_output(['git', '-C', str(repo), 'show', commit + ':' + path], stderr=subprocess.PIPE)


def verify(repo):
    errors = []
    def require(ok, text):
        if not ok:
            raise ValueError(text)
    try:
        pointer = json.loads((repo / 'derived-latest.json').read_bytes())
        generation = pointer['generation']
        require(bool(re.fullmatch(r'\d{12}', generation)), 'invalid generation')
        require(pointer['manifest'] == f'releases/{generation}/manifest.json', 'pointer path/generation mismatch')
        manifest_path = safe(repo, pointer['manifest'])
        raw_manifest = manifest_path.read_bytes()
        require(digest(raw_manifest) == pointer['manifestSha256'], 'derived manifest pointer hash mismatch')
        m = json.loads(raw_manifest)
        require(m['schema'] == 'globalgrid.derived-runtime.v1' and m['generation'] == generation, 'derived schema/generation mismatch')
        baseline = m['baseline']; commit = baseline['commit']; basegen = baseline['generation']
        require(bool(re.fullmatch('[0-9a-f]{40}', commit)), 'full baseline commit required')
        require(bool(re.fullmatch(r'\d{12}', basegen)), 'baseline generation invalid')
        basepath = f'releases/{basegen}/manifest.json'
        original_raw = git_bytes(repo, commit, basepath)
        require(digest(original_raw) == baseline['manifestSha256'], 'pinned baseline manifest hash mismatch')
        original = json.loads(original_raw)
        require(original['schema'] == 'globalgrid.original-runtime.v1' and original['generation'] == basegen, 'baseline schema/generation mismatch')
        pinned_pointer = json.loads(git_bytes(repo, commit, 'latest.json'))
        require(pinned_pointer['manifest'] == basepath and pinned_pointer['manifestSha256'] == baseline['manifestSha256'] and pinned_pointer['generation'] == basegen, 'baseline pointer mismatch')
        require(m['applications'] == [{'id': 'cable-geometry-visualiser', 'entry': ENTRY}], 'derived release must own Cable only')
        require(m['composition'] == {'entry': ENTRY, 'insertBefore': '</body>', 'insertion': INSERTION}, 'unexpected entry composition')
        require(m['cartridge'] == {'path': CARTRIDGE, 'sourcePath': SOURCE}, 'unexpected cartridge identity')
        originals = {x['path']: x for x in original['files'] if x['path'].startswith(PREFIX)}
        listed = [x['path'] for x in m['files']]
        require(len(listed) == len(set(listed)), 'duplicate manifested path')
        for name in listed:
            safe(manifest_path.parent, name)
        require(set(listed) == set(originals) | {CARTRIDGE}, 'derived closure differs from baseline Cable plus cartridge')
        cross_owner = {x['path']: x for x in m.get('crossOwnerNavigation', [])}
        scripts = resources = 0
        for item in m['files']:
            name = item['path']; role = item['role']; path = safe(manifest_path.parent, name); raw = path.read_bytes()
            require(len(raw) == item['bytes'] and digest(raw) == item['sha256'], 'derived file hash mismatch: ' + name)
            require(role in {'original', 'composed-entry', 'cartridge'}, 'unknown file role: ' + name)
            if name == CARTRIDGE:
                require(role == 'cartridge', 'cartridge role mismatch')
                require(raw == safe(repo, SOURCE).read_bytes(), 'maintained cartridge differs from release')
            else:
                before = git_bytes(repo, commit, f'releases/{basegen}/' + name)
                require(digest(before) == originals[name]['sha256'] and len(before) == originals[name]['bytes'], 'baseline file does not match baseline manifest: ' + name)
                if name == ENTRY:
                    require(role == 'composed-entry', 'entry role mismatch')
                    require(before.count(b'</body>') == 1, 'baseline entry must have one insertion anchor')
                    require(raw == before.replace(b'</body>', INSERTION.encode() + b'</body>', 1), 'entry differs beyond declared single insertion')
                else:
                    require(role == 'original' and raw == before, 'original runtime changed: ' + name)
            chunks = [raw.decode('utf8')] if name.endswith('.js') else []
            if name.endswith('.html'):
                parser = Resources(); parser.feed(raw.decode('utf8')); chunks += parser.inline
                for tag, url in parser.urls:
                    parts = urlsplit(url)
                    if parts.scheme or parts.netloc or not parts.path or parts.path.startswith('/'):
                        continue
                    resolved = (path.parent / unquote(parts.path)).resolve()
                    require(resolved.is_relative_to(manifest_path.parent.resolve()), 'HTML dependency escapes release')
                    relative = resolved.relative_to(manifest_path.parent.resolve()).as_posix(); resources += 1
                    if tag == 'a' and relative in cross_owner:
                        pin = cross_owner[relative]
                        require(bool(re.fullmatch('[0-9a-f]{40}', pin.get('commit', ''))) and bool(re.fullmatch('[0-9a-f]{64}', pin.get('manifestSha256', ''))) and bool(re.fullmatch(r'(?:https://github\.com/)?Ventusltd/[A-Za-z0-9_.-]+', pin.get('repository', ''))), 'unbound cross-owner navigation')
                    else:
                        require(relative in listed and resolved.is_file(), 'missing or unmanifested relative HTML resource: ' + url)
            for chunk in chunks:
                if not chunk.strip():
                    continue
                with tempfile.TemporaryDirectory() as temp:
                    script = Path(temp) / 'parse.js'; script.write_text(chunk, encoding='utf8')
                    result = subprocess.run(['node', '--check', str(script)], capture_output=True)
                    require(result.returncode == 0, 'JavaScript parse failure: ' + name); scripts += 1
        return {'ok': True, 'generation': generation, 'manifestSha256': digest(raw_manifest), 'cartridgeSha256': digest(safe(repo, SOURCE).read_bytes()), 'baseline': baseline, 'files': len(listed), 'javascriptParses': scripts, 'relativeHtmlResources': resources, 'scope': 'Derived byte provenance, declared composition and syntax only; no browser or engineering acceptance.'}
    except (ValueError, KeyError, OSError, subprocess.CalledProcessError, TypeError) as error:
        errors.append(str(error))
        return {'ok': False, 'errors': errors}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument('--out', type=Path)
    args = parser.parse_args(); result = verify(args.root)
    if args.out:
        args.out.parent.mkdir(parents=True, exist_ok=True)
        args.out.write_text(json.dumps(result, indent=2) + '\n', encoding='utf8')
    print(json.dumps(result)); raise SystemExit(not result['ok'])