GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / kuiper-belt / .github/workflows

Build and 8 more files (part 2)

A Python command-line tool in the tools folder of Law that reads laws.

697 lines of Python and YAML from kuiper-belt, kuiper-drawing-engine, law and 1 more, in 9 files. Topic: Automation and CI. Section 1817 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. Engine Workflow automation · kuiper-belt / .github/workflows/engine.yml lines 1–53
  2. Array Pages Workflow automation · kuiper-drawing-engine / .github/workflows/array-pages.yml lines 1–52
  3. Build ingest · law / tools/build.py lines 1–158
  4. Verify Derived Workflow automation · layout-tool / .github/workflows/verify-derived.yml lines 1–36
  5. Verify Original Workflow automation · layout-tool / .github/workflows/verify-original.yml lines 1–42
  6. Derive Module storage · layout-tool / tools/derive_module.py lines 1–49
  7. Import Original storage · layout-tool / tools/import_original.py lines 1–79
  8. Test Verify Derived test · layout-tool / tools/test_verify_derived.py lines 1–101
  9. Verify Derived storage · layout-tool / tools/verify_derived.py lines 1–127

Engine Workflow

A GitHub Actions workflow in Kuiper Belt. Runs on a schedule and by hand.

automationkuiper-belt / .github/workflows/engine.yml · lines 1–53 of 53 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: 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).
Inputs & outputs
Out: commits pushed to the repository.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Runs CI Check (`tools/ci_check.py`), Harvest (`tools/harvest.py`) and Wafer Topup (`tools/wafer_topup.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-belt · .github/workflows · workflow
Uses
CI Check (workflow run), Harvest (workflow run), Wafer Topup (workflow run)
Used by
none found
Produces
none declared
Defines here
engine
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 .github/workflows/engine.yml:1-53 · blob 4d9e95ed37aa5331ee0ed9ef0dab59146ea41ea8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unknown
name: engine

# The engine that runs with nobody paying and nobody watching. On a timer, on GitHub's machine, it
# checks the repository, measures every PUBLIC repository of the estate, and commits what it found.
# It uses no assistant and no paid credit. If every other machine is switched off, this still runs.
on:
  schedule:
    - cron: '17 */6 * * *'
  workflow_dispatch:

permissions:
  contents: write

concurrency:
  group: engine
  cancel-in-progress: false

jobs:
  harvest:
    runs-on: ubuntu-latest
    timeout-minutes: 80
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - name: Check first, and fail closed
        run: python tools/ci_check.py
      - name: Measure the public estate
        env:
          GITHUB_TOKEN: ${{ github.token }}
        run: python tools/harvest.py
      - name: Check again with the new data in place
        run: python tools/ci_check.py
      - name: Grow the wafer by every public commit since its rim
        timeout-minutes: 30
        env:
          GITHUB_TOKEN: ${{ github.token }}
        run: python tools/wafer_topup.py
      - name: Check the grown wafer
        run: python tools/ci_check.py
      - name: Commit the measurement
        run: |
          git config user.name "kuiper-engine"
          git config user.email "actions@users.noreply.github.com"
          git add cosmos/standing.tsv cosmos/pulse.tsv cosmos/wafer.tsv cosmos/repos.tsv cosmos/wafer-meta.json
          git diff --cached --quiet && exit 0
          git commit -q -m "engine: lines standing and the wafer grown, measured by GitHub Actions"
          git pull -q --rebase --autostash origin "${GITHUB_REF_NAME}"
          git push -q origin "HEAD:${GITHUB_REF_NAME}"

Array Pages Workflow

A GitHub Actions workflow in Kuiper Drawing Engine that builds and publishes the site. Runs on push and by hand.

automationkuiper-drawing-engine / .github/workflows/array-pages.yml · lines 1–52 of 52 · Entry point

What it does
It builds and publishes its content. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'array'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
Out: GitHub Pages deployment.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Array layout checks and Pages”; runs Test Public Bundle (`tests/test_public_bundle.py`), Check Public Bundle (`tools/check_public_bundle.py`) and `tests/browser.cjs`; publishes to GitHub Pages.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
kuiper-drawing-engine · .github/workflows · workflow
Uses
Geometry Test (workflow run), Site Test (workflow run), Kuiper Drawing Engine — App (workflow run), Test Public Bundle (workflow run), Check Public Bundle (workflow run)
Used by
none found
Produces
none declared
Defines here
Array layout checks and Pages
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-drawing-engine@0d322ce8edb4646f2153cf72eeac247d903301e6 .github/workflows/array-pages.yml:1-52 · blob c40b32c830b36072aa9499e0a51e29b9dd258bca · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
name: Array layout checks and Pages
on:
  push:
    branches: [main, codex/array-studio-coast]
  workflow_dispatch:
permissions:
  contents: read
  pages: write
  id-token: write
concurrency:
  group: array-pages-${{ github.ref }}
  cancel-in-progress: false
jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - name: Geometry and bundle checks
        run: |
          node --test tests/*.test.mjs
          node --check web/app.mjs
          python3 tests/test_public_bundle.py
          python3 tools/check_public_bundle.py
      - name: Hosted browser checks
        run: |
          npm install --prefix "$RUNNER_TEMP/browser" --no-save --ignore-scripts playwright@1.62.1
          "$RUNNER_TEMP/browser/node_modules/.bin/playwright" install --with-deps chromium
          PLAYWRIGHT_MODULE="$RUNNER_TEMP/browser/node_modules/playwright" node tests/browser.cjs
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: array-browser-evidence
          path: browser-evidence
      - uses: actions/configure-pages@v5
        if: github.ref == 'refs/heads/main'
      - uses: actions/upload-pages-artifact@v3
        if: github.ref == 'refs/heads/main'
        with:
          path: web
  deploy:
    if: github.ref == 'refs/heads/main'
    needs: verify
    runs-on: ubuntu-latest
    environment:
      name: github-pages
      url: ${{ steps.deploy.outputs.page_url }}
    steps:
      - uses: actions/deploy-pages@v4
        id: deploy

Build

A Python command-line tool in the tools folder of Law that reads laws.

ingestlaw / tools/build.py · lines 1–158 of 158 · Entry point

What it does
It loads laws. Defines main. Uses libraries io, json, sys. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file laws.json.
Downstream impact
Used directly by 1 file: Law — Index Page (law). Reached from 2 other entry points, including Watch Workflow (time-stone); Watch (time-stone).
What it achieves
Render `index.html` from `laws.json`, and refuse if a law is not whole.
Why it matters
Loaded by the Law page.
Application
law · tools · Python CLI
Uses
io, json, sys
Used by
linked from Law — Index Page (link)
Produces
main
Defines here
main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
law@53c6c3218e7c56bce3fe6ca7727f82f2fb505dc4 tools/build.py:1-158 · blob 932e7028a581a71f16c4eb93b8e93a97b37f6d1d · GitHub at these lines
State
achieves: comment · context: auto · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""tools/build.py - render index.html from laws.json, and refuse if a law is not whole.

A LAW WITHOUT A KEY IS A CANDIDATE, NOT A LAW. This build checks that every law carries all seven
parts and at least one key, and exits non-zero if any does not, so an unfinished law cannot reach
the page by accident. Keys marked `candidate` are allowed through, because saying "quoted from
memory, do not build on it" is honest, but they are counted and shown on the page.

    python tools/build.py          writes index.html, prints the audit
"""
import io
import json
import sys

REQUIRED = ['id', 'title', 'say', 'mean', 'real', 'eq', 'symbols', 'work', 'wrong', 'keys']

CSS = """
  :root { color-scheme: dark; }
  html { background:#000; }
  body { background:#000; color:#fff; font-family:Courier,monospace; padding:40px; max-width:980px; margin:0 auto; font-size:20px; line-height:1.6; }
  h1 { margin:0 0 6px; }
  a { color:#66ccff; text-decoration:none; } a:hover { text-decoration:underline; }
  header p { color:#aaa; font-size:16px; margin:0 0 10px; }
  .rule { color:#aaa; font-size:15px; border-top:1px solid #333; border-bottom:1px solid #333; padding:14px 0; margin:22px 0 10px; }
  .rule b { color:#00ffff; }
  .rule ol { margin:8px 0 0; padding-left:26px; } .rule li { margin:3px 0; }
  .audit { color:#7a7a7a; font-size:14px; margin:0 0 26px; }
  .audit b { color:#ffbe45; }
  details.area { border-bottom:1px solid #333; }
  details.area > summary { list-style:none; cursor:pointer; padding:14px 0; color:#00ffff; font-weight:bold; letter-spacing:.5px; font-size:24px; }
  details.area > summary::-webkit-details-marker { display:none; }
  details.area > summary::before { content:"[+] "; }
  details.area[open] > summary::before { content:"[-] "; }
  details.area > summary:hover { color:#66ffff; }
  details.nest { margin:0 0 14px 18px; border-bottom:0; }
  details.nest > summary { list-style:none; cursor:pointer; font-size:18px; padding:8px 0; color:#66ccff; font-weight:bold; }
  details.nest > summary::-webkit-details-marker { display:none; }
  details.nest > summary::before { content:"[+] "; color:#00ffff; }
  details.nest[open] > summary::before { content:"[-] "; color:#00ffff; }
  details.nest > summary:hover { color:#9fdcff; }
  .body { margin:0 0 22px 22px; border-left:1px solid #1c1c1c; padding-left:18px; }
  .say { color:#fff; font-size:19px; line-height:1.45; margin:6px 0 4px; }
  .lab { display:block; color:#00ffff; font-size:12px; letter-spacing:.09em; text-transform:uppercase; margin:16px 0 5px; }
  p.t { color:#cfcfcf; font-size:15px; margin:4px 0; }
  p.r { color:#d8c9a8; font-size:15px; margin:4px 0; }
  .eq { background:#0b0b0b; border-left:2px solid #00ffff; padding:11px 13px; margin:7px 0; color:#e8e6e1; font-size:16px; overflow-x:auto; }
  ul.sym { margin:6px 0 0; padding-left:20px; color:#9aa3af; font-size:14px; }
  ul.sym li { margin:3px 0; } ul.sym b { color:#e8e6e1; }
  .work { color:#53ff4c; font-size:15px; margin:4px 0; }
  .wrong { color:#ffbe45; font-size:15px; margin:4px 0; }
  table.keys { width:100%; border-collapse:collapse; font-size:13px; margin:6px 0 0; }
  table.keys td { padding:5px 8px 5px 0; border-bottom:1px solid #161616; vertical-align:top; color:#9aa3af; }
  table.keys td.k { color:#e8e6e1; width:34%; }
  .st { font-weight:bold; text-transform:uppercase; font-size:11px; letter-spacing:.06em; white-space:nowrap; }
  .st-exact,.st-derived { color:#53ff4c; } .st-standard,.st-published { color:#66ccff; }
  .st-measured { color:#00ffff; } .st-candidate { color:#ffbe45; }
  .footer { margin-top:50px; font-size:14px; color:#aaa; line-height:1.5; border-top:1px solid #333; padding-top:18px; }
  .footer a { color:#5a5a5a; }
  @media(max-width:600px){ body{padding:22px;font-size:18px} details.area>summary{font-size:22px} .say{font-size:18px} .eq{font-size:14px} table.keys td.k{width:44%} }
"""


def main():
    d = json.load(io.open('laws.json', encoding='utf-8'))

    # ---- refuse before rendering -----------------------------------------------------------
    problems, counts = [], {}
    for area in d['areas']:
        for law in area['laws']:
            for f in REQUIRED:
                if not law.get(f):
                    problems.append('%s is missing %s' % (law.get('id', '?'), f))
            for k in law.get('keys', []):
                if len(k) != 3 or not all(k):
                    problems.append('%s has a malformed key: %r' % (law['id'], k))
                else:
                    counts[k[2]] = counts.get(k[2], 0) + 1
                    if k[2] not in d['status_meanings']:
                        problems.append('%s uses unknown status %r' % (law['id'], k[2]))
    if problems:
        print('REFUSING TO BUILD. A law that is not whole does not get published.')
        for p in problems:
            print('  ' + p)
        return 1

    nlaws = sum(len(a['laws']) for a in d['areas'])
    nkeys = sum(counts.values())
    ncand = counts.get('candidate', 0)

    out = []
    w = out.append
    w('<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="UTF-8">')
    w('<link rel="icon" href="data:,">\n<title>%s</title>' % d['title'])
    w('<meta name="viewport" content="width=device-width, initial-scale=1">')
    w('<style>%s</style>\n</head>\n<body>' % CSS)
    w('<header>\n  <h1>%s</h1>\n  <p>%s</p>\n</header>' % (d['title'], d['lede']))

    w('<div class="rule"><b>How every law is written.</b> In this order, always.<ol>')
    for step in d['format']:
        w('  <li>%s</li>' % step)
    w('</ol>Notation is the last step and never the price of entry.</div>')

    w('<p class="audit">%d laws &middot; %d keys &middot; <b>%d marked candidate</b>, meaning '
      'quoted from memory or illustrative and not yet verified. Do not build on a candidate. '
      'The build refuses to publish a law missing any part or any key.</p>'
      % (nlaws, nkeys, ncand))

    w('<main>')
    for area in d['areas']:
        w('<details class="area"><summary>%s</summary>' % area['name'])
        for law in area['laws']:
            w('  <details class="nest"><summary>%s &middot; %s</summary>' % (law['id'], law['title']))
            w('  <div class="body">')
            w('    <p class="say">%s</p>' % law['say'])
            w('    <span class="lab">What it means</span>')
            w('    <p class="t">%s</p>' % law['mean'])
            w('    <span class="lab">In the real world</span>')
            w('    <p class="r">%s</p>' % law['real'])
            w('    <span class="lab">The maths</span>')
            w('    <div class="eq">%s</div>' % law['eq'])
            w('    <ul class="sym">')
            for s in law['symbols']:
                w('      <li>%s</li>' % s)
            w('    </ul>')
            w('    <span class="lab">A worked number</span>')
            w('    <p class="work">%s</p>' % law['work'])
            w('    <span class="lab">How to show it is wrong</span>')
            w('    <p class="wrong">%s</p>' % law['wrong'])
            w('    <span class="lab">Keys</span>')
            w('    <table class="keys">')
            for what, src, st in law['keys']:
                w('      <tr><td class="k">%s</td><td>%s</td>'
                  '<td class="st st-%s">%s</td></tr>' % (what, src, st, st))
            w('    </table>')
            w('  </div>\n  </details>')
        w('</details>')
    w('</main>')

    w('<div class="footer"><b>Disclaimer:</b> Content provided for general technical documentation '
      'and research purposes only. Laws are stated so that they can be shown to be wrong. Every '
      'number carries a key saying where it came from; a key marked <span class="st st-candidate">'
      'candidate</span> was quoted from memory or is illustrative and must be checked against the '
      'standard before anyone builds anything on it. No warranty is given.<br><br>'
      'Built from <a href="laws.json">laws.json</a> by <a href="tools/build.py">tools/build.py</a>, '
      'which refuses to publish a law that is not whole.<br>'
      'Code under Apache-2.0. Documentation under CC BY 4.0.</div>')
    w('</body>\n</html>')

    io.open('index.html', 'w', encoding='utf-8', newline='\n').write('\n'.join(out) + '\n')

    print('built index.html: %d laws, %d keys' % (nlaws, nkeys))
    for st in sorted(counts, key=lambda s: -counts[s]):
        print('  %-10s %3d   %s' % (st, counts[st], d['status_meanings'][st]))
    return 0


if __name__ == '__main__':
    sys.exit(main())

Verify Derived Workflow

A GitHub Actions workflow in Layout Tool. Runs on push, on pull requests and by hand.

automationlayout-tool / .github/workflows/verify-derived.yml · lines 1–36 of 36 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file derived-latest.json.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Verify derived Module cartridge provenance”; runs Test Verify Derived (`tools/test_verify_derived.py`) and Verify Derived (`tools/verify_derived.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
layout-tool · .github/workflows · workflow
Uses
Test Verify Derived (workflow run), Verify Derived (workflow run)
Used by
none found
Produces
none declared
Defines here
Verify derived Module cartridge provenance
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
layout-tool@a23476c78898ff3023048738986497382b5569c1 .github/workflows/verify-derived.yml:1-36 · blob 8f1b98dd388df816747adb7f52f466dc7221d521 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
name: Verify derived Module cartridge provenance
on:
  push:
    branches: [main]
    paths:
      - 'src/module-layout/**'
      - 'releases/**'
      - 'derived-latest.json'
      - 'tools/verify_derived.py'
      - 'tools/test_verify_derived.py'
      - '.github/workflows/verify-derived.yml'
  pull_request:
  workflow_dispatch:
permissions:
  contents: read
jobs:
  verify:
    runs-on: ubuntu-24.04
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
        with:
          fetch-depth: 0
          persist-credentials: false
      - name: Exercise negative derived controls
        run: python3 -B tools/test_verify_derived.py
      - name: Verify pinned baseline, composition and cartridge
        run: python3 -B tools/verify_derived.py --out artifacts/derived-runtime.json
      - name: Retain compact provenance receipt
        if: always()
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
        with:
          name: derived-layout-${{ github.sha }}-${{ github.run_id }}
          path: artifacts/derived-runtime.json
          if-no-files-found: error
          retention-days: 30

Verify Original Workflow

A GitHub Actions workflow in Layout Tool. Runs on push, on pull requests and by hand.

automationlayout-tool / .github/workflows/verify-original.yml · lines 1–42 of 42 · Entry point

What it does
It runs solar and battery storage (BESS). Side effects: starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar, battery storage (BESS).
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Verify original layout component baselines”; runs `tools/test_verify.py` and `tools/verify.py`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
layout-tool · .github/workflows · workflow
Uses
none found
Used by
none found
Produces
none declared
Defines here
Verify original layout component baselines
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
layout-tool@a23476c78898ff3023048738986497382b5569c1 .github/workflows/verify-original.yml:1-42 · blob de4549e097bbd5a3c357e8f35f9843288a775f67 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
name: Verify original layout component baselines
on:
  push:
    branches: [main]
  pull_request:
  workflow_dispatch:
permissions:
  contents: read
concurrency:
  group: layout-original-${{ github.ref }}
  cancel-in-progress: false
jobs:
  verify:
    runs-on: ubuntu-24.04
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
        with:
          persist-credentials: false
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
        with:
          repository: Ventusltd/globalgrid2050
          ref: 4185020ade7da01869b4ffc0ee1d2656608da716
          path: .origin
          persist-credentials: false
          sparse-checkout: |
            solar-bess-topology-v7/module-layout
            solar-bess-topology-v7/cable-geometry-visualiser
            solar-bess-topology-v7/dc-ac-lv-topology-review
          sparse-checkout-cone-mode: false
      - name: Verify negative controls
        run: python3 -B tools/test_verify.py
      - name: Check exact original bytes and local dependencies
        run: python3 -B tools/verify.py --source .origin --expected-origin 4185020ade7da01869b4ffc0ee1d2656608da716 --out artifacts/original-baseline.json
      - name: Retain compact receipt
        if: always()
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
        with:
          name: original-layout-${{ github.sha }}-${{ github.run_id }}
          path: artifacts/original-baseline.json
          if-no-files-found: error
          retention-days: 30

Derive Module

A Python command-line tool in the tools folder of Layout Tool covering solar, battery storage (BESS) and cables, using SHA-256.

storagelayout-tool / tools/derive_module.py · lines 1–49 of 49 · Entry point

What it does
Defines blob, sha, main. Uses libraries pathlib, argparse, datetime, hashlib, json. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar, battery storage (BESS), cables. README: "`tools/derive_module.py` composes a new timestamp without overwriting old releases."
Inputs & outputs
In: command-line arguments. Out: JSON file derived-latest.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the blob step (`blob`) and the sha step (`sha`). Compose one immutable Module Layout guard release from committed original bytes. It accepts `--generation`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
layout-tool · tools · Python CLI
Uses
pathlib, argparse, datetime, hashlib, json, re, subprocess
Used by
none found
Produces
blob, sha, main
Defines here
blob, sha, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
layout-tool@a23476c78898ff3023048738986497382b5569c1 tools/derive_module.py:1-49 · blob a2457b21dc37ac17887ed7a6030c2ae390ed4109 · 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
"""Compose one immutable Module Layout guard release from committed original bytes."""
from pathlib import Path
import argparse, datetime, hashlib, json, re, subprocess

ROOT=Path(__file__).resolve().parents[1]
BASELINE='e201075e052bfc71e7fef01f1360f319808cb78f'
GENERATION='202609051858'
PREFIX='solar-bess-topology-v7/module-layout/'
def blob(path):
    return subprocess.check_output(['git','-C',str(ROOT),'show',BASELINE+':'+path])
def sha(raw): return hashlib.sha256(raw).hexdigest()

def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--generation',default=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d%H%M'));args=parser.parse_args()
    if not re.fullmatch(r'\d{12}',args.generation): raise SystemExit('Unique UTC timestamp required')
    release=ROOT/'releases'/args.generation
    if release.exists(): raise SystemExit('Immutable release already exists')
    baseline_raw=blob('releases/'+GENERATION+'/manifest.json');baseline=json.loads(baseline_raw)
    entry=PREFIX+'index.html';cartridge=PREFIX+'draw-readiness.js'
    insertion='<script src="./draw-readiness.js"></script>\n'
    files=[];prepared=[]
    for member in baseline['files']:
        if not member['path'].startswith(PREFIX):continue
        raw=blob('releases/'+GENERATION+'/'+member['path'])
        if sha(raw)!=member['sha256']:raise SystemExit('Baseline manifest mismatch')
        role='original'
        if member['path']==entry:
            if raw.count(b'</body>')!=1:raise SystemExit('Ambiguous entry insertion')
            raw=raw.replace(b'</body>',insertion.encode()+b'</body>');role='composed-entry'
        prepared.append((member['path'],raw,role))
    source='src/module-layout/draw-readiness.js';raw=(ROOT/source).read_bytes().replace(b'\r\n',b'\n')
    prepared.append((cartridge,raw,'cartridge'))
    release.mkdir(parents=True)
    for name,raw,role in prepared:
        target=release/name;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(raw)
        files.append(dict(path=name,bytes=len(raw),sha256=sha(raw),role=role))
    siblings=[dict(path='solar-bess-topology-v7/dc-ac-lv-topology-review/index.html',repository='Ventusltd/layout-tool',commit=BASELINE,release=GENERATION,manifestSha256=sha(baseline_raw)),
      dict(path='solar-bess-topology-v7/cable-geometry-visualiser/index.html',repository='Ventusltd/cable-trench-or-drill',commit='76396fd3639dd86cddd21e392f29f43ab6d22f2d',release='202609051921',manifestSha256='a1b96236ba223bbbb8153538961bea677513a9fe3a877b9c61cd70d61128960e')]
    siblings+=baseline.get('crossOwnerNavigation',[])
    manifest=dict(schema='globalgrid.derived-runtime.v1',generation=args.generation,createdAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),
      baseline=dict(commit=BASELINE,generation=GENERATION,manifestSha256=sha(baseline_raw)),
      applications=[dict(id='module-layout',entry=entry)],files=files,
      composition=dict(entry=entry,insertBefore='</body>',insertion=insertion),cartridge=dict(path=cartridge,sourcePath=source),
      crossOwnerNavigation=siblings,rootOriginDependencies=baseline.get('rootOriginDependencies',[]),
      scope='Original formulas and runtime files preserved. Only entry composition and independent draw-readiness guard are new. No engineering acceptance claim.')
    raw=(json.dumps(manifest,indent=2)+'\n').encode();(release/'manifest.json').write_bytes(raw)
    pointer=dict(schema='globalgrid.derived-runtime-pointer.v1',generation=args.generation,manifest='releases/'+args.generation+'/manifest.json',manifestSha256=sha(raw))
    (ROOT/'derived-latest.json').write_text(json.dumps(pointer,indent=2)+'\n',encoding='utf8',newline='\n');print(json.dumps(pointer))
if __name__=='__main__':main()

Import Original

A Python command-line tool in the tools folder of Layout Tool covering grid substations, Renewable Energy Planning Database (REPD) master, solar and battery storage (BESS), using SHA-256.

storagelayout-tool / tools/import_original.py · lines 1–79 of 79 · Entry point

What it does
Defines git, main. Uses libraries argparse, datetime, hashlib, json, re. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar, battery storage (BESS).
Inputs & outputs
In: GeoJSON file grid_substations.geojson; JSON file repd_master.json; command-line arguments. Out: JSON file latest.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the git step (`git`). Import an immutable original runtime from an explicit GlobalGrid Git revision. It accepts `--source`, `--commit` and `--generation`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
layout-tool · tools · Python CLI
Uses
argparse, datetime, hashlib, json, re, subprocess, pathlib
Used by
none found
Produces
git, main
Defines here
git, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
layout-tool@a23476c78898ff3023048738986497382b5569c1 tools/import_original.py:1-79 · blob de1ed18e64c971e02e5cf74b91473ab9d77161d4 · 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
"""Import an immutable original runtime from an explicit GlobalGrid Git revision."""
import argparse
import datetime
import hashlib
import json
import re
import subprocess
from pathlib import Path


def git(repo, *args):
    return subprocess.check_output(['git', '-C', str(repo), *args])


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--source', type=Path, required=True)
    parser.add_argument('--commit', required=True)
    parser.add_argument('--generation', required=True)
    parser.add_argument('--apps', nargs='+', default=['module-layout', 'cable-geometry-visualiser', 'dc-ac-lv-topology-review'])
    parser.add_argument('--gis-producer-commit', required=True)
    args = parser.parse_args()
    if not re.fullmatch(r'[0-9a-f]{40}', args.commit) or not re.fullmatch(r'\d{12}', args.generation):
        parser.error('full source SHA and 12-digit generation required')
    base = Path(__file__).resolve().parents[1]
    target = base / 'releases' / args.generation
    if target.exists():
        parser.error('immutable generation already exists')
    prefixes = ['solar-bess-topology-v7/' + app for app in args.apps]
    paths = git(args.source, 'ls-tree', '-r', '--name-only', args.commit, '--', *prefixes).decode().splitlines()
    paths = [p for p in paths if Path(p).suffix in {'.html', '.js', '.css'}]
    if not paths:
        parser.error('no original runtime files')
    contents = {p: git(args.source, 'show', args.commit + ':' + p) for p in paths}
    required = set()
    external = set()
    for raw in contents.values():
        text = raw.decode('utf8')
        required.update(re.findall(r'\.\./\.\./(repd_grid_atlasv8/data/[\w.-]+)', text))
        external.update(re.findall(r'https?://[^\s\"\'<>`]+', text))
    for relative in sorted(required):
        contents[relative] = git(args.source, 'show', args.commit + ':' + relative)
    manifest = {
        'schema': 'globalgrid.original-runtime.v1', 'generation': args.generation,
        'createdAt': datetime.datetime.now(datetime.timezone.utc).isoformat(),
        'origin': {'repository': 'Ventusltd/globalgrid2050', 'commit': args.commit},
        'applications': [{'id': app, 'entry': 'solar-bess-topology-v7/' + app + '/index.html'} for app in args.apps],
        'policy': 'Original runtime and required relative data bytes copied unchanged; no generated full-code reports.',
        'rootOriginDependencies': ['/grid_substations.geojson', '/dist/repd_master.json'],
        'externalLiteralUrls': sorted(external),
        'externalScope': 'Literal URL inventory, not exhaustive dynamic dependency closure. External libraries, styles, tiles and geocoding remain external. Root-absolute data requires the GlobalGrid origin or an explicit hosting adapter.',
        'files': []}
    if not re.fullmatch(r'[0-9a-f]{40}', args.gis_producer_commit):
        parser.error('full GIS producer commit required for cross-owner navigation')
    manifest['crossOwnerNavigation'] = [{
        'path': 'solar-bess-topology-v7/gis-sld-financial-sandbox/index.html',
        'repository': 'Ventusltd/unnamed-01', 'commit': args.gis_producer_commit,
        'entry': 'releases/202609051855/solar-bess-topology-v7/gis-sld-financial-sandbox/index.html',
        'manifestSha256': '90190a0846717b5203305a8c08301fb26ed58e015b992272e0999272091a0916',
        'rule': 'Consumer composes this separately owned sibling route; no GIS implementation copied into layout-tool.'}]
    for relative, raw in sorted(contents.items()):
        path = target / relative
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(raw)
        manifest['files'].append({'path': relative, 'bytes': len(raw),
                                  'sha256': hashlib.sha256(raw).hexdigest(),
                                  'gitBlob': hashlib.sha1(b'blob ' + str(len(raw)).encode() + b'\0' + raw).hexdigest(),
                                  'role': 'relative-data' if relative in required else 'runtime'})
    raw_manifest = (json.dumps(manifest, indent=2) + '\n').encode()
    (target / 'manifest.json').write_bytes(raw_manifest)
    latest = {'schema': 'globalgrid.original-runtime-pointer.v1', 'generation': args.generation,
              'manifest': 'releases/' + args.generation + '/manifest.json',
              'manifestSha256': hashlib.sha256(raw_manifest).hexdigest()}
    (base / 'latest.json').write_text(json.dumps(latest, indent=2) + '\n', encoding='utf8')
    print(json.dumps({'generation': args.generation, 'files': len(contents), 'bytes': sum(map(len, contents.values())), 'manifestSha256': latest['manifestSha256']}))


if __name__ == '__main__':
    main()

Test Verify Derived

A test in the tools folder of Layout Tool that checks Verify Derived, using SHA-256.

Set aside from the main view: 95% of its lines are the same as tools/test_verify_derived.py (cable-trench-or-drill), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with Test Verify Derived; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.954 to cable-trench-or-drill@bf00f9503ff7a662933775a022557c4ca9d9880a tools/test_verify_derived.py:1-101 d607b9d4d68645475b09986b5ed0044678ef0c89
  • sha256 32d6e187de1d015e7201f7aa1444a3106baf798bf55e1327dc107f29d3beca1a
  • target sha256 04e3fa0517673269a623b312e3b444079ba7adf3e2fdb3e040d939a3f68ab22a
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

testlayout-tool / 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 'layout'): 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 (layout-tool).
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
layout-tool · 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
layout-tool@a23476c78898ff3023048738986497382b5569c1 tools/test_verify_derived.py:1-101 · blob cdfbe80b45612ccad687b01b153ed85fd4b99c38 · 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: duplicate_candidate
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 = '202609051858'; 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': 'module-layout', '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 Derived

A Python command-line tool in the tools folder of Layout Tool that works with git bytes (`git_bytes`), using SHA-256.

storagelayout-tool / 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 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. README: "`tools/verify_derived.py` proves the original-file closure, exact entry insertion, maintained guard bytes and explicit sibling pins."
Inputs & outputs
In: JSON file derived-latest.json; JSON file latest.json; command-line arguments.
Downstream impact
Used directly by 2 files: Verify Derived Workflow (layout-tool); Test Verify Derived (layout-tool).
What it achieves
It is built from the digest step (`digest`), the safe step (`safe`) and the verify step (`verify`). Verify an explicit Module 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
layout-tool · tools · Python CLI
Uses
argparse, hashlib, json, re, subprocess, tempfile, pathlib, urllib.parse
Used by
run by Verify Derived Workflow (workflow run), imported by Test Verify Derived (import)
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
layout-tool@a23476c78898ff3023048738986497382b5569c1 tools/verify_derived.py:1-127 · blob c1c7a34b945ea8bc8ed4c06bbba38fbf28f21b10 · 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: duplicate_candidate
"""Verify an explicit Module 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/module-layout/'
ENTRY = PREFIX + 'index.html'
CARTRIDGE = PREFIX + 'draw-readiness.js'
SOURCE = 'src/module-layout/draw-readiness.js'
INSERTION = '<script src="./draw-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': 'module-layout', 'entry': ENTRY}], 'derived release must own Module 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 Module 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'])