GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / testcode / sandbox/tools

Watch and 6 more files

A Python command-line tool in the tools folder of Time Stone using data from GitHub API and the law and faraday repositories.

551 lines of Python and YAML and JavaScript from testcode, time-stone, v11, in 7 files. Topic: Automation and CI. Section 1868 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. Verify Poly Candidate other · testcode / sandbox/tools/verify-poly-candidate.mjs lines 1–35
  2. Verify Tool Host Candidate other · testcode / sandbox/tools/verify-tool-host-candidate.mjs lines 1–46
  3. Build Pair render · testcode / tools/build-pair.py lines 1–131
  4. Pair Gates render · testcode / tools/pair-gates.cjs lines 1–28
  5. Watch Workflow automation · time-stone / .github/workflows/watch.yml lines 1–40
  6. Watch ingest · time-stone / tools/watch.py lines 1–137
  7. V11 Control Plane Validation Workflow automation · v11 / .github/workflows/v11-control-plane-validation.yml lines 1–134

Verify Poly Candidate

A JavaScript module in the tools folder of Testcode covering publication, provenance and tool layers, using SHA-256.

othertestcode / sandbox/tools/verify-poly-candidate.mjs · lines 1–35 of 35 · Entry point

What it does
Defines blob, hash. Uses libraries node:path, node:assert/strict, node:child_process, node:crypto, node:url. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file publication.json; JSON file source-provenance.json; JSON file tool-layers.json; JSON file current.json; command-line arguments.
Downstream impact
Used directly by 7 files: Map PDF Workflow (testcode); Measurement Clearance Workflow (testcode); Measurement Readouts Workflow (testcode); Poly Zone Workflow (testcode); and 3 more.
What it achieves
Its name says it verifies poly candidate. Defines `blob` and `hash`.
Why it matters
Run by 7 workflows and scripts, including Map PDF Workflow, Measurement Clearance Workflow and Measurement Readouts Workflow.
Application
testcode · sandbox/tools · JavaScript module
Uses
Token Compaction (script call), node:path, node:assert/strict, node:child_process, node:crypto, node:url
Used by
run by Map PDF Workflow (workflow run), run by Measurement Clearance Workflow (workflow run), run by Measurement Readouts Workflow (workflow run), run by Poly Zone Workflow (workflow run), run by Polygon Distance Workflow (workflow run), run by Vertex Limit Workflow (workflow run), run by Vertex Removal Workflow (workflow run)
Produces
blob, hash
Defines here
blob, hash
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/tools/verify-poly-candidate.mjs:1-35 · blob 524c11a87ce4e33d318ca1eb5f7cdbdc74c61e4c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: experimental · users: none · canonical: unknown
import path from 'node:path';
import assert from 'node:assert/strict';
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import {fileURLToPath} from 'node:url';
import {compact,proveEquivalent,replaceMapEngine,replaceOptionalModule} from './token-compaction.mjs';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
const generation=process.argv[2];assert(/^\d{12}$/.test(generation||''));
const owner=process.env.GRIDATLAS_REPO||'C:/Users/vikra/atlas-labels-20260906';
const blob=(repo,p,sha='HEAD')=>execFileSync('git',['show',`${sha}:${p}`],{cwd:repo,maxBuffer:64*1024*1024});
const hash=b=>createHash('sha256').update(b).digest('hex');
const prefix=`sandbox/${generation}/`;
const manifest=JSON.parse(blob(root,prefix+'publication.json'));
for(const item of manifest.files){const b=blob(root,prefix+item.path);assert.equal(b.length,item.bytes,item.path);assert.equal(hash(b),item.sha256,item.path);}
const p=JSON.parse(blob(root,prefix+'atlas/source-provenance.json'));
assert.equal(p.generation,generation);assert(/^[a-f0-9]{40}$/.test(p.ownerCommit));
const parentRef=p.parentSourceCommit||'HEAD';if(p.parentSourceCommit)assert(/^[a-f0-9]{40}$/.test(p.parentSourceCommit));
for(const name of ['map-controls-layout.js','teleprinter-bootstrap.js'])assert.deepEqual(blob(root,prefix+'atlas/'+name),blob(root,`sandbox/${p.parent}/atlas/${name}`,parentRef),'Carried '+name);
assert.equal(blob(root,prefix+'atlas/index.html').toString(),blob(root,`sandbox/${p.parent}/atlas/index.html`,parentRef).toString().replace('Test Code Atlas '+p.parent,'Test Code Atlas '+generation),'Carried complete router and its validation');
const inheritedPins=execFileSync('git',['ls-tree','--name-only',parentRef,`sandbox/${p.parent}/atlas/tool-layers.json`],{cwd:root,encoding:'utf8'}).trim();
if(inheritedPins)assert.deepEqual(blob(root,prefix+'atlas/tool-layers.json'),blob(root,inheritedPins,parentRef),'Carried original tool identities');
const engine=blob(owner,p.engine.path,p.ownerCommit),module=blob(owner,p.module.path,p.ownerCommit),parent=blob(root,p.parentCartridge.path,parentRef);
assert.equal(hash(engine),p.engine.sha256);assert.equal(hash(module),p.module.sha256);assert.equal(hash(parent),p.parentCartridge.sha256);
let assembled=replaceMapEngine(parent.toString(),engine.toString(),module.toString());
for(const extra of p.optionalModules||[]){const bytes=blob(owner,extra.path,p.ownerCommit);assert.equal(hash(bytes),extra.sha256);assembled=replaceOptionalModule(assembled,bytes.toString(),extra.schema);}
assert.equal(hash(assembled),p.assembledSha256);
const expected='/* '+generation+'; source and token/AST compaction receipts in source-provenance.json. */\n'+compact(assembled);
const current=JSON.parse(blob(root,prefix+'atlas/current.json'));
const cartridge=current.cartridges.find(c=>c.id==='substation-intelligence');
const actual=blob(root,prefix+'atlas/'+cartridge.path.slice(2)).toString();
assert.equal(actual,expected);proveEquivalent(assembled,actual);
assert.equal(hash(actual),p.payloadSha256);assert.equal(hash(actual),cartridge.sha256);assert(actual.length<=368640);
assert.equal((actual.match(/gridatlas\.measurement-dock\.v1/g)||[]).length,1,'One measurement module, never accumulated duplicates');
for(const c of current.cartridges){const q=c.path.startsWith('/testcode/')?'sandbox/'+c.path.slice(10):prefix+'atlas/'+c.path.replace(/^\.\//,'');assert.equal(hash(blob(root,q)),c.sha256,c.id);}
console.log(`PASS ${generation}: ${manifest.files.length} published-file identities, complete cartridge dependencies, owner reconstruction and executable token/AST parity (${actual.length}/368640 characters)`);

Verify Tool Host Candidate

A JavaScript module in the tools folder of Testcode covering publication, provenance and tool layers, using SHA-256.

othertestcode / sandbox/tools/verify-tool-host-candidate.mjs · lines 1–46 of 46 · Entry point · pattern source (shared by 13 files)

What it does
It lists and searches publication, provenance and tool layers. Defines blob, hash, source. Uses libraries node:path, node:assert/strict, node:child_process, node:crypto, node:url. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file publication.json; JSON file source-provenance.json; JSON file current.json; JSON file tool-layers.json; command-line arguments.
Downstream impact
Used directly by 1 file: Tool Recovery Workflow (testcode).
What it achieves
Its name says it verifies tool host candidate. Defines `blob`, `hash` and `source`.
Why it matters
Run by Tool Recovery Workflow.
Application
testcode · sandbox/tools · JavaScript module
Uses
node:path, node:assert/strict, node:child_process, node:crypto, node:url
Used by
run by Tool Recovery Workflow (workflow run)
Produces
blob, hash, source
Defines here
blob, hash, source
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/tools/verify-tool-host-candidate.mjs:1-46 · blob 4a2b29ed9c07b226eb1bb057ec519bfa5464adb0 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: experimental · users: none · canonical: unknown
import path from 'node:path';
import assert from 'node:assert/strict';
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import {fileURLToPath} from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
const generation=process.argv[2];assert(/^\d{12}$/.test(generation||''));
const blob=(p,ref='HEAD')=>execFileSync('git',['show',`${ref}:${p}`],{cwd:root,maxBuffer:64*1024*1024});
const hash=b=>createHash('sha256').update(b).digest('hex');
const prefix=`sandbox/${generation}/`,manifest=JSON.parse(blob(prefix+'publication.json'));
assert.equal(manifest.generation,generation);
assert.equal(new Set(manifest.files.map(f=>f.path)).size,manifest.files.length);
for(const f of manifest.files){assert(!f.path.includes('..'));const b=blob(prefix+f.path);assert.equal(b.length,f.bytes,f.path);assert.equal(hash(b),f.sha256,f.path);}
const p=JSON.parse(blob(prefix+'atlas/source-provenance.json'));assert.equal(p.schema,'gridatlas.tool-host-candidate.v1');assert.equal(p.generation,generation);assert.equal(manifest.source_commit,p.sourceCommit);
assert(/^[a-f0-9]{40}$/.test(p.sourceCommit));
const source=q=>blob(q,p.sourceCommit);
const current=JSON.parse(blob(prefix+'atlas/current.json')),parent=JSON.parse(source(`sandbox/${p.parent}/atlas/current.json`));
assert.equal(current.previous_generation,p.parent);assert.equal(current.generation,generation);
assert.deepEqual(current.cartridge_order,parent.cartridge_order);
const carried=parent.cartridges.map(c=>({...c,path:c.path.startsWith('./')?`/testcode/${p.parent}/atlas/${c.path.slice(2)}`:c.path}));
assert.deepEqual(current.cartridges,carried,'No cartridge code or capabilities may change with a host-only release');
for(const c of current.cartridges){assert(c.path.startsWith('/testcode/'));const q='sandbox/'+c.path.slice(10);assert.equal(hash(blob(q)),c.sha256);assert.equal(hash(source(q)),c.sha256);}
for(const f of manifest.files.filter(f=>f.path==='atlas/map-controls-layout.js'||f.path.startsWith('atlas/data/'))){assert.deepEqual(blob(prefix+f.path),source(`sandbox/${p.parent}/${f.path}`),f.path);}
const original=source(`sandbox/${p.appGeneration}/atlas/teleprinter-bootstrap.js`);assert.equal(hash(original),p.originalBootstrapSha256);
const pins=JSON.parse(source(`sandbox/${p.appGeneration}/atlas/tool-layers.json`)),actualPins=JSON.parse(blob(prefix+'atlas/tool-layers.json'));
assert.deepEqual(actualPins.owners,pins.owners,'Original iframe owner identities must survive');
const tools=pins.tools.map(t=>{const o=pins.owners.find(o=>o.applications.some(a=>a.id===t.id));assert(o);return{...t,owner:{repository:o.repository,commit:o.commit,release:o.release,manifestSha256:o.manifestSha256}};});
const registry=[...tools];for(const o of pins.owners)for(const a of o.applications)if(!registry.some(t=>t.id===a.id))registry.push({id:a.id,title:'DC/AC LV Topology Review',entry:'../layer-apps/'+a.entry,owner:{repository:o.repository,commit:o.commit,release:o.release,manifestSha256:o.manifestSha256}});
assert.deepEqual(actualPins.tools,tools);assert.deepEqual(actualPins.registry,registry);assert.equal(actualPins.hostGeneration,p.hostGeneration);
let expected=original.toString().replaceAll("from '../teleprinter/",`from '/testcode/${p.appGeneration}/teleprinter/`)
 .replace("from '../tool-layers/host.js'",`from '/testcode/${p.hostGeneration}/tool-layers/host.js'`)
 .replace(/^mountToolLayers\([^\n]+$/m,`mountToolLayers(${JSON.stringify(tools)},new URL('/testcode/${p.appGeneration}/atlas/teleprinter-bootstrap.js',location.origin).href,${JSON.stringify(registry)});`)
 .replace("new URL('../teleprinter/', import.meta.url)",`new URL('/testcode/${p.appGeneration}/teleprinter/', location.origin)`);
if(p.layout){
 const initializer="import {mountMapControlsLayout} from './map-controls-layout.js';\nmountMapControlsLayout();\n";
 const parentBootstrap=source(`sandbox/${p.parent}/atlas/teleprinter-bootstrap.js`);
 assert.equal(hash(parentBootstrap),p.layout.parentBootstrapSha256);assert.equal(p.layout.initializer,initializer);
 assert.equal(parentBootstrap.toString(),`import '/testcode/${p.appGeneration}/atlas/teleprinter-bootstrap.js';\n`+initializer);
 assert.equal(hash(blob(prefix+'atlas/map-controls-layout.js')),p.layout.sha256);assert.equal(current.layout_cartridge.sha256,p.layout.sha256);
 expected+='\n'+initializer;
}else assert.equal(generation,'202609060447','New hosts must preserve and attest the existing layout initializer');
assert.equal(blob(prefix+'atlas/teleprinter-bootstrap.js').toString(),expected);assert.equal(hash(expected),p.bootstrapSha256);
const seen=new Set(),queue=[`sandbox/${p.hostGeneration}/tool-layers/host.js`];
while(queue.length){const q=queue.shift();if(seen.has(q))continue;seen.add(q);const bytes=source(q),receipt=p.dependencies.find(d=>d.path===q);assert(receipt,q);assert.equal(receipt.bytes,bytes.length);assert.equal(receipt.sha256,hash(bytes));assert.deepEqual(blob(q),bytes,'Immutable host dependency');for(const m of bytes.toString().matchAll(/from ['"]([^'"]+)['"]/g)){assert(m[1].startsWith('./'))  … [line shortened here: 481 characters; full line on GitHub]
assert.equal(p.dependencies.length,seen.size);assert.equal(seen.size,8);
console.log(`PASS ${generation}: ${manifest.files.length} published files, four unchanged cartridges, ${seen.size} pinned host modules, original app owners and bootstrap reconstruction`);

Build Pair

A Python module in the tools folder of Testcode that reads pair inputs, major project news, receivers and interconnectors, using SHA-256 from the ventus-grid-engine and GridAtlas repositories.

rendertestcode / tools/build-pair.py · lines 1–131 of 131 · Entry point

What it does
It loads pair inputs, major project news, receivers and interconnectors. Defines 6 functions or classes, including git, read, write, copy, tree. Uses libraries datetime, hashlib, json, posixpath, pathlib. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (repository name word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: interconnectors.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: gridatlas data; JSON file pair-inputs.json; JSON file major_project_news_v5.json; JSON file major_project_news_v6.json; JSON file major_project_news_v9_5_1.json; JSON file current.json; JSON file receivers.json. Out: JSON file interconnectors_manifest.json; JSON file interconnectors.json.
Downstream impact
Used directly by 1 file: Gridmachine Pair Workflow (testcode).
What it achieves
It is built from the git step (`git`), the read step (`read`) and the write step (`write`). Construct a new test-only app pair from exact Git blobs, with explicit adaptations. It writes `atlas/current.json`.
Why it matters
Run by Gridmachine Pair Workflow.
Application
testcode · tools · Python module
Uses
GridAtlas — Atlas Page (estate URL), datetime, hashlib, json, posixpath, pathlib, re, subprocess, sys
Used by
run by Gridmachine Pair Workflow (workflow run)
Produces
git, read, write, copy, tree, edit
Defines here
git, read, write, copy, tree, edit
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 tools/build-pair.py:1-131 · blob 389e1ca6a47306fa361f86365309a23222ab9b25 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: experimental · users: none · canonical: unknown
#!/usr/bin/env python3
"""Construct a new test-only app pair from exact Git blobs, with explicit adaptations."""
import datetime as dt
import hashlib
import json
import posixpath
from pathlib import Path
import re
import subprocess
import sys
import os

ROOT=Path(__file__).resolve().parents[1]
SOURCES=Path(os.environ.get('GRIDMACHINE_SOURCES','/home/vikram/GitHub'))
STAMP=sys.argv[1] if len(sys.argv)>1 else dt.datetime.now(dt.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
assert re.fullmatch(r'\d{8}T\d{6}Z',STAMP)
PAIR='GGPAIR-GM02-'+STAMP
DEST=ROOT/'sandbox/gm02'/STAMP
if DEST.exists(): raise SystemExit('Candidate already exists; allocate a new timestamp')
DEST.mkdir(parents=True)
def git(repo,*args): return subprocess.check_output(['git','-C',str(SOURCES/repo),*args])
PINS=json.loads((ROOT/'tools/pair-inputs.json').read_text())
PROVENANCE=[]
def read(repo,path): return git(repo,'show',PINS[repo]+':'+path)
def write(path,b):
    p=DEST/path;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(b.encode() if isinstance(b,str) else b)
def copy(repo,source,target):
    b=read(repo,source);write(target,b)
    PROVENANCE.append({'repository':'Ventusltd/'+repo,'commit':PINS[repo],'source':source,'target':target,'source_sha256':hashlib.sha256(b).hexdigest()})
    return b
def tree(repo,path):return git(repo,'ls-tree','-r','--name-only',PINS[repo],'--',path).decode().splitlines()
def edit(path,old,new):
    p=DEST/path;s=p.read_text();assert old in s,(path,old[:70]);p.write_text(s.replace(old,new),encoding='utf-8')

PIPE='uk_renewables_pipeline/202609071221'
for p in tree('globalgrid2050',PIPE):
    rel=p[len(PIPE)+1:]
    if rel=='index.html' or rel.startswith(('scripts/','styles/','contracts/','data/')):copy('globalgrid2050',p,'pipeline/'+rel)
for name in ['major_project_news_v5.json','major_project_news_v6.json','major_project_news_v9_5_1.json']:
    copy('globalgrid2050','dist/'+name,'pipeline/data/shared/'+name)
for p in (DEST/'pipeline/scripts').rglob('*.js'):
    p.write_text(p.read_text().replace('../../dist/','data/shared/'))
for p in tree('gridatlas','atlas/releases/202608300453-atlas-v9'):
    copy('gridatlas',p,'atlas/runtime/'+p.removeprefix('atlas/'))
for p in tree('gridatlas','atlas/data'):copy('gridatlas',p,'atlas/runtime/'+p.removeprefix('atlas/'))
lane='atlas/v/202609071232'
copy('gridatlas',lane+'/index.html','atlas/index.html')
current=json.loads(read('gridatlas',lane+'/current.json'))
for c in current['cartridges']:
    path=posixpath.normpath(posixpath.join(lane,c['path']))
    b=copy('gridatlas',path,'atlas/runtime/'+path.removeprefix('atlas/'))
    assert hashlib.sha256(b).hexdigest()==c['sha256'],path
    c['source_sha256']=c['sha256'];c['path']='./runtime/'+path.removeprefix('atlas/')
    if c['id']=='sld-sandbox':
        target='atlas/'+c['path'].removeprefix('./')
        old='  const EARTH_KM = 6371.0088;'
        edit(target,old,'  const EARTH_KM = window.__GGPAIR_ENGINE__.EARTH_RADIUS_KM;')
        start=(DEST/target).read_text().index('  function haversineKm(lon1, lat1, lon2, lat2) {', (DEST/target).read_text().index('const EARTH_KM'))
        s=(DEST/target).read_text();end=s.index('\n  }',start)+4
        s=s[:start]+'''  function haversineKm(lon1, lat1, lon2, lat2) {
    window.__GGPAIR__.engine_calls++;
    return window.__GGPAIR_ENGINE__.distanceKm(lon1, lat1, lon2, lat2);
  }'''+s[end:]
        (DEST/target).write_text(s)
    c['sha256']=hashlib.sha256((DEST/'atlas'/c['path']).read_bytes()).hexdigest()
    c['bytes']=(DEST/'atlas'/c['path']).stat().st_size
current.update(generation=STAMP,composition_id=PAIR,live_route='./',pair_id=PAIR)
current['shell']={'release_id':current['shell']['release_id'],'index':'./runtime/releases/202608300453-atlas-v9/index.html','base':'./runtime/releases/202608300453-atlas-v9/'}
write('atlas/current.json',json.dumps(current,indent=2)+'\n')
copy('ventus-grid-engine','engine/v9-geodesy.js','engine/v9-geodesy.js')
copy('ventus-grid-engine','LICENSE','engine/LICENSE')
copy('ventus-grid-engine','NOTICE','engine/NOTICE')
write('package.json','{"type":"module","private":true}\n')
for repo in ['globalgrid2050','gridatlas']:
    for name in ['LICENSE','NOTICE']:
        try:copy(repo,name,'attribution/'+repo+'/'+name)
        except subprocess.CalledProcessError:pass

# Explicit test receiver: retain production identity construction/withdrawal logic,
# but bind both compiled and verified receiver paths to this paired Atlas.
receiver='pipeline/scripts/core/atlas-receiver-v9-7.js'
edit(receiver,'const RECEIVERS_URL = "https://ventusltd.github.io/ventus-grid-engine/deeplink/receivers.json";',
'''const PAIR_ATLAS = new URL("../../../atlas/", import.meta.url).href;
const RECEIVERS_URL = new URL("../../../receivers.json", import.meta.url).href;'''.replace('../../../','../../../../'))
# core is pipeline/scripts/core: three parent segments reach the pair root.
edit(receiver,'../../../../atlas/','../../../atlas/')
edit(receiver,'../../../../receivers.json','../../../receivers.json')
edit(receiver,'route: "https://ventusltd.github.io/gridatlas/atlas/",','route: PAIR_ATLAS,')
# The JSON contract route is resolved against its fetch URL before validation.
edit(receiver,'const live = await response.json();','const live = await response.json();\n      live.canonical.route = new URL(live.canonical.route, RECEIVERS_URL).href;')
write('receivers.json',json.dumps({'schema':'ventus.grid-engine.deeplink-receivers.v1','canonical':{'id':PAIR,'route':'./atlas/','carries_engine':True},'retired':[],'pair_id':PAIR},indent=2)+'\n')
write('pair-runtime.js',f'''import * as engine from './engine/v9-geodesy.js';
window.__GGPAIR_ENGINE__=engine;
window.__GGPAIR__={{pair_id:{json.dumps(PAIR)},engine_commit:{json.dumps(PINS['ventus-grid-engine'])},engine_calls:0}};
document.documentElement.dataset.ggpair={json.dumps(PAIR)};
''')
edit('atlas/index.html','    try {','    try {\n      await import("../pair-runtime.js");')
# document.open replaces the DOM; publish the pair sentinel into the composed document too.
edit('atlas/index.html','window.__GRIDATLAS_ATLAS__=${publicState};','window.__GRIDATLAS_ATLAS__=${publicState};document.documentElement.dataset.ggpair='+json.dumps(PAIR)+';')
edit('pipeline/index.html','</head>','<script type="module" src="../pair-runtime.js"></script>\n</head>')
edit('pipeline/index.html','href="https://ventusltd.github.io/gridatlas/atlas/"','href="../atlas/"')
# Pipeline's displayed interconnector span consumes the same engine module.
link='pipeline/scripts/core/atlas-interconnector-link-v9-8.js'
edit(link,'import { atlasReceiverV9_7,', 'import { distanceKm } from "../../../engine/v9-geodesy.js";\nimport { atlasReceiverV9_7,')
# Preserve missing-coordinate semantics; calculate only from the actual converter inputs.
edit(link,'${record.span.straight_line_km}', '${distanceKm(record.gb_end.longitude,record.gb_end.latitude,record.far_end.longitude,record.far_end.latitude).toFixed(3)}')
# Rebuild span measurements with the pinned JS primitive and re-sign the partition.
subprocess.run(['node','--input-type=module','-e',r'''
import fs from 'node:fs';
const root=process.argv[1];const {distanceKm,EARTH_RADIUS_KM}=await import('file://'+root+'/engine/v9-geodesy.js');
const file=root+'/pipeline/data/v9.8/interconnectors.json';const d=JSON.parse(fs.readFileSync(file));
for(const r of d.records){if(r.gb_end&&r.far_end&&r.span){
 const a=r.gb_end,b=r.far_end;const km=distanceKm(a.longitude,a.latitude,b.longitude,b.latitude);
 r.span.straight_line_km=Number(km.toFixed(3));r.span.earth_radius_km=EARTH_RADIUS_KM;
 if(r.span.known_submarine_cable_km)r.span.route_factor=Number((r.span.known_submarine_cable_km/km).toFixed(6));
 const g=r.span.great_circle_midpoint;if(g)r.span.midpoints_differ_km=Number(distanceKm(r.longitude,r.latitude,g.longitude,g.latitude).toFixed(3));
}}
fs.writeFileSync(file,JSON.stringify(d,null,2)+'\n');
''',str(DEST)],check=True)
mp=DEST/'pipeline/data/v9.8/interconnectors_manifest.json';m=json.loads(mp.read_text());m['partition']['sha256']=hashlib.sha256((DEST/'pipeline/data/v9.8/interconnectors.json').read_bytes()).hexdigest();m['test_pair_id']=PAIR;mp.write_text(json.dumps(m,indent=2)+'\n')

manifest={'schema':'testcode.pair.v1','pair_id':PAIR,'timestamp':STAMP,'implementation_lane':'gm02','parent_pair_id':None,
 'source_commits':PINS,'engine_binding':{'repository':'Ventusltd/ventus-grid-engine','commit':PINS['ventus-grid-engine'],'module':'engine/v9-geodesy.js','consumption':'Atlas interconnector haversineKm and Pipeline span display/build call pinned distanceKm; other pre-existing engine functions retain their baseline implementation'},
 'pipeline':'pipeline/','gridatlas':'atlas/','product_verdict':'NOT_RUN','production_approval':'NOT_RECORDED',
 'limitations':['External map/data dependencies remain to be measured and pinned by runtime receipts.','This candidate does not claim all historical MAP buttons or every direction has passed.'],
 'source_files':PROVENANCE,'files':[]}
write('index.html',f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>{PAIR}</title><style>body{{background:#0b1622;color:#e3f1fa;font:18px/1.6 system-ui;max-width:1000px;margin:50px auto;padding:24px}}a{{color:#6edccb}}.pair{{display:grid;grid-template-columns:1fr 1fr;gap:24px}}article{{padding:24px;border:1px solid #345365;border-ra  … [line shortened here: 875 characters; full line on GitHub]
for p in sorted(DEST.rglob('*')):
    if p.is_file():manifest['files'].append({'path':p.relative_to(DEST).as_posix(),'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'bytes':p.stat().st_size})
write('pair.json',json.dumps(manifest,indent=2)+'\n')
print(json.dumps({'pair_id':PAIR,'directory':str(DEST),'files':len(manifest['files']),'bytes':sum(f['bytes'] for f in manifest['files'])}))

Pair Gates

A JavaScript module in the tools folder of Testcode that draws vnd apache and interconnectors, using SHA-256.

rendertestcode / tools/pair-gates.cjs · lines 1–28 of 28 · Entry point

What it does
It draws vnd apache and interconnectors. Uses libraries node:fs, node:path, node:http, node:crypto. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage field_execution (path word 'gates'): 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. Domain terms in the code: interconnectors.
Inputs & outputs
In: Parquet file vnd.apache.parquet; command-line arguments.
Downstream impact
Used directly by 1 file: Gridmachine Pair Workflow (testcode).
What it achieves
Grid Machine: active-click acceptance, with record then network-blocked replay.
Why it matters
Run by Gridmachine Pair Workflow.
Application
testcode · tools · JavaScript module
Uses
node:fs, node:path, node:http, node:crypto
Used by
run by Gridmachine Pair Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 tools/pair-gates.cjs:1-28 · blob 1a9b7572415b57b4d4757beaf2160f1ca63166bd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
// Grid Machine: active-click acceptance, with record then network-blocked replay.
const fs=require('node:fs'),path=require('node:path'),http=require('node:http'),crypto=require('node:crypto');
const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'/home/vikram/.local/share/globalgrid-worker/browser/node_modules/playwright');
const root=path.resolve(__dirname,'..'),stamp=process.argv[2],mode=process.argv[3];
if(!/^\d{8}T\d{6}Z$/.test(stamp)||!['record','offline'].includes(mode))throw Error('timestamp and record/offline required');
const out=path.resolve(process.env.GRIDMACHINE_EVIDENCE||('/home/vikram/.local/share/globalgrid-worker/pair-evidence/'+stamp));fs.mkdirSync(out,{recursive:true});
const cache=path.join(out,'mirror');fs.mkdirSync(cache,{recursive:true});
const report={pair_id:'GGPAIR-GM02-'+stamp,mode,started:new Date().toISOString(),cases:[],misses:[],errors:[],network_fetches:0,product_verdict:'NOT_EVALUATED',coverage:'Five actual PipelineNews MAP clicks; not the full estate or a reverse-direction acceptance test.'};
const types={'.js':'text/javascript','.mjs':'text/javascript','.html':'text/html','.css':'text/css','.json':'application/json','.geojson':'application/json','.wasm':'application/wasm','.parquet':'application/vnd.apache.parquet'};
const server=http.createServer((req,res)=>{try{let f=path.resolve(root,'.'+decodeURIComponent(new URL(req.url,'http://localhost').pathname));if(!f.startsWith(root+path.sep))return res.writeHead(403).end();if(fs.statSync(f).isDirectory())f=path.join(f,'index.html');const bytes=fs.readFileSync(f);res.writeHead(200,{'content-type':types[path.extname(f)]||'application/octet-stream'}).end(bytes);}catch  … [line shortened here: 430 characters; full line on GitHub]
let browser;
const checks=[{ref:'11386',tech:'all',status:'RESOLVED',mapped:true,source:'OFFICIAL_ACTIVE_REGISTER',control:true},{ref:'13429',tech:'all',status:'RESOLVED',mapped:true,source:'CROWN_ESTATE_LEASE_POINT_ON_SURFACE'},{ref:'13432',tech:'all',status:'RESOLVED_UNMAPPED',mapped:false,source:'NONE'},{ref:'IC-INTNED',tech:'interconnector',status:'RESOLVED'},{ref:'IC-INTVKL',tech:'interconnector',status:'  … [line shortened here: 416 characters; full line on GitHub]
(async()=>{await new Promise(r=>server.listen(0,'127.0.0.1',r));const origin=`http://127.0.0.1:${server.address().port}`,base=origin+`/sandbox/gm02/${stamp}/`;browser=await chromium.launch({channel:process.env.BROWSER_CHANNEL||'chrome',chromiumSandbox:true});report.browser=browser.version();
for(const c of checks){const ctx=await browser.newContext({viewport:{width:1440,height:1000},serviceWorkers:'block'});
await ctx.route('**/*',async route=>{const req=route.request(),url=req.url();if(url.startsWith(origin+'/'))return route.continue();if(!/^https?:/.test(url))return route.continue();const key=crypto.createHash('sha256').update(JSON.stringify([req.method(),url,req.headers().range||''])).digest('hex'),meta=path.join(cache,key+'.json'),body=path.join(cache,key+'.bin');try{
if(fs.existsSync(meta)&&fs.existsSync(body)){const m=JSON.parse(fs.readFileSync(meta));return route.fulfill({status:m.status,headers:m.headers,body:fs.readFileSync(body)});}
if(mode==='offline'){report.misses.push({url,range:req.headers().range||null});return route.abort('internetdisconnected');}
report.network_fetches++;const response=await route.fetch({timeout:45000}),bytes=await response.body(),headers=response.headers();delete headers['content-encoding'];delete headers['transfer-encoding'];headers['content-length']=String(bytes.length);fs.writeFileSync(body,bytes);fs.writeFileSync(meta,JSON.stringify({url,method:req.method(),range:req.headers().range||null,status:response.status(),head  … [line shortened here: 538 characters; full line on GitHub]
}catch(e){report.errors.push({url,error:String(e).slice(0,200)});try{await route.abort();}catch{}}});
const p=await ctx.newPage();let result={ref:c.ref,control:!!c.control,pass:false};try{await p.goto(base+'pipeline/',{waitUntil:'domcontentloaded'});await p.locator('#tbody .atlaslink').first().waitFor({timeout:45000});await p.locator(`[data-technology="${c.tech}"]`).click();await p.locator('#search').fill(c.ref.replace('IC-',''));const link=p.locator(`#repd-${c.ref} .atlaslink`);await link.waitFor  … [line shortened here: 850 characters; full line on GitHub]
Object.assign(result,await a.evaluate(()=>({url:location.href,pair:window.__GGPAIR__,identity:window.__GRIDATLAS_PLACE_SEARCH__?.deep_link,interconnector:window.__GRIDATLAS_INTERCONNECTORS__?.arrival?((a)=>({status:a.status,framed:a.framed,ends:(a.ends||[]).map(e=>e?({nearest_km:e.nearest_km,nearest_name:e.nearest_name,coverage:e.coverage}):null),search_km:a.search_km}))(window.__GRIDATLAS_INTERCO  … [line shortened here: 812 characters; full line on GitHub]
const pairOK=result.url.startsWith(base+'atlas/')&&result.pair?.pair_id===report.pair_id&&!result.failure_card;
result.pass=c.tech==='interconnector'?Boolean(pairOK&&result.interconnector?.status===c.status&&result.pair.engine_calls>0&&result.interconnector?.ends?.[0]?.nearest_km!=null):Boolean(pairOK&&result.identity?.status===c.status&&result.identity?.mapped===c.mapped&&result.identity?.coordinate_source===c.source&&(!c.control||result.engine?.links_drawn>0));
await a.screenshot({path:path.join(out,mode+'-'+c.ref+'.png')});await a.close();
}catch(e){result.error=String(e);}
report.cases.push(result);await ctx.close();fs.writeFileSync(path.join(out,mode+'.json'),JSON.stringify(report,null,2));if(c.control&&!result.pass){report.product_verdict='HARNESS_INVALID';break;}}
if(report.product_verdict!=='HARNESS_INVALID')report.product_verdict=report.cases.length===checks.length&&report.cases.every(c=>c.pass)&&!report.misses.length?'PASS':report.cases.some(c=>c.error)?'BLOCKED_HARNESS':'FAIL';
})().catch(e=>{report.errors.push(String(e.stack));report.product_verdict='BLOCKED_HARNESS';}).finally(async()=>{if(browser)await browser.close();server.close();report.finished=new Date().toISOString();fs.writeFileSync(path.join(out,mode+'.json'),JSON.stringify(report,null,2));console.log(JSON.stringify({mode,verdict:report.product_verdict,cases:report.cases.map(c=>({ref:c.ref,pass:c.pass,error:c.  … [line shortened here: 509 characters; full line on GitHub]

Watch Workflow

A GitHub Actions workflow in Time Stone. Runs on a schedule and by hand.

automationtime-stone / .github/workflows/watch.yml · lines 1–40 of 40 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
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 Watch (`tools/watch.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
time-stone · .github/workflows · workflow
Uses
Watch (workflow run)
Used by
none found
Produces
none declared
Defines here
watch
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
time-stone@50b6b1506d19812caf1f1ec64c5f4f966cb16833 .github/workflows/watch.yml:1-40 · blob bf2b510076844cb6f849545ccdf6067393ed2e3a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
name: watch

# The time stone. Once an hour, on GitHub's machine, in a few seconds: ask what changed, write down
# only what changed. No assistant, no paid credit, no clone. It commits only when something changed.
on:
  schedule:
    - cron: '23 * * * *'
  workflow_dispatch:

permissions:
  contents: write

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

jobs:
  watch:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v4
      - uses: actions/checkout@v4
        with:
          repository: Ventusltd/kuiper-belt
          path: kb
          sparse-checkout: tools
      - name: Watch, and fail closed
        env:
          GITHUB_TOKEN: ${{ github.token }}
        run: python3 tools/watch.py
      - name: Commit only what changed
        run: |
          git config user.name "time-stone"
          git config user.email "actions@users.noreply.github.com"
          git add ledger.tsv site.tsv NOW.md
          git diff --cached --quiet && exit 0
          git commit -q -m "watch: what changed"
          git pull -q --rebase --autostash origin "${GITHUB_REF_NAME}"
          git push -q origin "HEAD:${GITHUB_REF_NAME}"

Watch

A Python command-line tool in the tools folder of Time Stone using data from GitHub API and the law and faraday repositories.

ingesttime-stone / tools/watch.py · lines 1–137 of 137 · Entry point · pattern public_repos (shared by 3 files)

What it does
It fetches data. Defines kind, public_repos, status, last, main. Uses libraries io, json, os, sys, time. Side effects: reads or writes files; makes network requests; starts processes.
Inputs & outputs
In: data source: law data; data source: faraday data; data source: GitHub API; command-line arguments.
Downstream impact
Used directly by 1 file: Watch Workflow (time-stone).
What it achieves
It is built from the kind step (`kind`), the public repos helper (`public_repos`) and the status step (`status`). The time stone: what changed, and when, across everything public.
Why it matters
Run by Watch Workflow.
Application
time-stone · tools · Python CLI
Uses
Cable Geometry Visualiser V5 (estate URL), Law — Index Page (estate URL), Faraday — Index Page (estate URL), io, json, os, sys, time, urllib.error, urllib.request, check_proof
Used by
run by Watch Workflow (workflow run)
Produces
kind, public_repos, status, last, main
Defines here
kind, public_repos, status, last, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
time-stone@50b6b1506d19812caf1f1ec64c5f4f966cb16833 tools/watch.py:1-137 · blob 84728ca0746fe1e744fdca7f240eb295d0947efc · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
r"""tools/watch.py - the time stone: what changed, and when, across everything public.

    python tools/watch.py [--dry]

One question to GitHub per run: which repositories of this account are public, and when was each
last pushed to. No clones, no assistant, no paid credit; a run takes seconds. It writes:

    ledger.tsv   APPEND ONLY. One row each time a repository is seen to have changed:
                 seen_unix, repository, pushed_at. Old rows are never rewritten, so this is a record
                 of the future arriving, in the order it arrived.
    site.tsv     APPEND ONLY. One row each time a watched page changes its answer: seen_unix, status, url.
    NOW.md       rebuilt from the two ledgers: everything watched, newest change first, by kind.

THE MIRROR. This repository does not watch itself. Its own commits would change its own push time,
which it would then record, which would be a commit: a watcher that watches itself never rests.

SAFEGUARDS. Public repositories only, and anything marked private is skipped anyway. Everything
about to be written goes through the digest guard first; one match and nothing is written, exit 2.
If GitHub cannot be reached nothing is written, exit 1: no answer is not the same as no change.
"""
import io
import json
import os
import sys
import time
import urllib.error
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.join(HERE, '..')
OWNER, SELF = 'Ventusltd', 'time-stone'
sys.path.insert(0, os.environ.get('KB_TOOLS', os.path.join(ROOT, 'kb', 'tools')))
from check_proof import leaks                       # the guard lives in kuiper-belt; one copy, not two

PAGES = ['https://globalgrid2050.com/',
         'https://globalgrid2050.com/solar-bess-topology-v5/cable-geometry-visualiser-v5.html',
         'https://ventusltd.github.io/law/',
         'https://ventusltd.github.io/faraday/']

KINDS = [('stone', ('stone', 'tokens', 'law', 'faraday', 'grid', 'sld')), ('kuiper', ('kuiper', 'cosmic')),
         ('wafer', ('wafer', 'cpu')), ('gridatlas', ('gridatlas', 'atlas')), ('pipelinenews', ('pipeline',))]


def kind(name):
    n = name.lower()
    for k, words in KINDS:
        if any(n == w or w in n for w in words if w != 'grid') or (k == 'stone' and n == 'grid'):
            return k
    return 'estate'


def public_repos():
    out, page = [], 1
    while True:
        req = urllib.request.Request('https://api.github.com/users/%s/repos?type=owner&per_page=100&page=%d' % (OWNER, page),
                                     headers={'Accept': 'application/vnd.github+json', 'User-Agent': 'time-stone'})
        if os.environ.get('GITHUB_TOKEN'):
            req.add_header('Authorization', 'Bearer ' + os.environ['GITHUB_TOKEN'])
        rows = json.load(urllib.request.urlopen(req, timeout=60))
        if not rows:
            return out
        out += [(r['name'], r['pushed_at']) for r in rows
                if not r.get('private') and r.get('visibility', 'public') == 'public' and r['name'] != SELF]
        page += 1


def status(url):
    try:
        req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'time-stone'})
        return str(urllib.request.urlopen(req, timeout=30).status)
    except urllib.error.HTTPError as e:
        return str(e.code)
    except Exception:
        return 'unreachable'


def last(path):
    """The newest value recorded for each name in an append only ledger: {name: value}."""
    seen = {}
    if os.path.exists(path):
        for l in io.open(path, encoding='utf-8'):
            if l.strip() and l[0] != '#':
                c = l.rstrip('\n').split('\t')
                seen[c[-1] if path.endswith('site.tsv') else c[1]] = c[1] if path.endswith('site.tsv') else c[2]
    return seen


def main():
    dry = '--dry' in sys.argv
    now = int(time.time())
    try:
        repos = public_repos()
    except Exception as e:
        print('FAIL: GitHub did not answer (%s); nothing written' % type(e).__name__)
        return 1
    lp, sp = os.path.join(ROOT, 'ledger.tsv'), os.path.join(ROOT, 'site.tsv')
    known, answered = last(lp), last(sp)
    changed = [(n, p) for n, p in sorted(repos, key=lambda r: r[1]) if known.get(n) != p]
    pages = [(u, status(u)) for u in PAGES]
    turned = [(u, s) for u, s in pages if answered.get(u) != s]

    add_l = ''.join('%d\t%s\t%s\n' % (now, n, p) for n, p in changed)
    add_s = ''.join('%d\t%s\t%s\n' % (now, s, u) for u, s in turned)
    current = dict(known)
    current.update(dict(changed))
    rows = sorted(current.items(), key=lambda r: r[1], reverse=True)
    md = ['# NOW', '', 'Rebuilt by `tools/watch.py` from `ledger.tsv` and `site.tsv`. Newest change first.', '',
          '| page | answer |', '|---|---|'] + ['| %s | %s |' % (u, s) for u, s in pages] + ['']
    for k in [k for k, _ in KINDS] + ['estate']:
        mine = [(n, p) for n, p in rows if kind(n) == k]
        if mine:
            md += ['## %s' % k, '', '| repository | last pushed (UTC) |', '|---|---|'] + \
                  ['| [%s](https://github.com/%s/%s) | %s |' % (n, OWNER, n, p.replace('T', ' ').replace('Z', '')) for n, p in mine] + ['']
    md = '\n'.join(md)

    if leaks(add_l + md):
        print('REFUSED (L6): a name that is not public is in the result; nothing written')
        return 2
    print('%d public repositories watched, %d changed since last seen, %d pages changed their answer'
          % (len(repos), len(changed), len(turned)))
    for u, s in pages:
        print('  %s  %s' % (s, u))
    if dry:
        print('dry run: nothing written')
        return 0
    for path, head, add in ((lp, '# seen_unix\trepository\tpushed_at\n', add_l), (sp, '# seen_unix\tstatus\turl\n', add_s)):
        if not os.path.exists(path):
            io.open(path, 'w', encoding='utf-8', newline='\n').write(head)
        if add:
            io.open(path, 'a', encoding='utf-8', newline='\n').write(add)
    io.open(os.path.join(ROOT, 'NOW.md'), 'w', encoding='utf-8', newline='\n').write(md)
    return 0


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

V11 Control Plane Validation Workflow

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

automationv11 / .github/workflows/v11-control-plane-validation.yml · lines 1–134 of 134 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file programme-state.json. Out: JSON file summary.json.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Runs Validate Control Plane (`scripts/validate_control_plane.py`) and Generate Control Plane Projection (`scripts/generate_control_plane_projection.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
v11 · .github/workflows · workflow
Uses
Validate Control Plane (workflow run), Test Control Plane (workflow run), Generate Control Plane Projection (workflow run)
Used by
none found
Produces
none declared
Defines here
V11 Control Plane Validation
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
v11@debb30e092a1983e775d2ab4126995ab7bb72fe3 .github/workflows/v11-control-plane-validation.yml:1-134 · blob b8b1cdc3df21d5ce38ea22623933961b148d5eb3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
name: V11 Control Plane Validation

on:
  workflow_dispatch:
  pull_request:
    paths:
      - "programme-state.json"
      - "build-plans/**"
      - "capabilities/**"
      - "resources/**"
      - "docs/build-ledger/**"
      - "operator-sessions/**"
      - "scripts/**"
      - "tests/**"
      - "README.md"
      - "index.html"
      - ".github/workflows/v11-control-plane-validation.yml"
  push:
    branches:
      - main
    paths:
      - "programme-state.json"
      - "build-plans/**"
      - "capabilities/**"
      - "resources/**"
      - "docs/build-ledger/**"
      - "operator-sessions/**"
      - "scripts/**"
      - "tests/**"
      - "README.md"
      - "index.html"
      - ".github/workflows/v11-control-plane-validation.yml"

permissions:
  contents: read

concurrency:
  group: v11-control-plane-${{ github.ref }}
  cancel-in-progress: false

jobs:
  validate:
    runs-on: ubuntu-latest
    timeout-minutes: 5

    steps:
      - name: Check out exact review head
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha || github.sha }}

      - name: Set up Python 3.11
        uses: actions/setup-python@v5
        with:
          python-version: "3.11"

      - name: Create evidence directory
        run: mkdir -p v11-validation

      - name: Validate machine control plane
        id: validator
        continue-on-error: true
        run: |
          set -o pipefail
          python -S scripts/validate_control_plane.py | tee v11-validation/control-plane.json

      - name: Run six focused tests
        id: tests
        if: always()
        continue-on-error: true
        run: |
          set -o pipefail
          python -S -m unittest -v tests/test_control_plane.py 2>&1 | tee v11-validation/tests.txt

      - name: Check deterministic projections
        id: projections
        if: always()
        continue-on-error: true
        run: |
          set -o pipefail
          python -S scripts/generate_control_plane_projection.py --check | tee v11-validation/projections.txt

      - name: Write validation summary
        if: always()
        env:
          VALIDATOR_RESULT: ${{ steps.validator.outcome }}
          TEST_RESULT: ${{ steps.tests.outcome }}
          PROJECTION_RESULT: ${{ steps.projections.outcome }}
        run: |
          python -S - <<'PY'
          import json, os, subprocess
          from pathlib import Path
          tested_sha = subprocess.check_output(
              ["git", "rev-parse", "HEAD"], text=True
          ).strip()
          payload = {
              "schema_version": "globalgrid2050.v11.control-plane-validation.v1",
              "repository": "Ventusltd/v11",
              "tested_commit_sha": tested_sha,
              "workflow_sha": os.environ["GITHUB_SHA"],
              "validator": os.environ["VALIDATOR_RESULT"],
              "six_focused_tests": os.environ["TEST_RESULT"],
              "projection_check": os.environ["PROJECTION_RESULT"],
          }
          payload["pass"] = all(
              payload[key] == "success"
              for key in ("validator", "six_focused_tests", "projection_check")
          )
          Path("v11-validation/summary.json").write_text(
              json.dumps(payload, indent=2, sort_keys=True) + "\n",
              encoding="utf-8",
          )
          print(json.dumps(payload, sort_keys=True))
          PY

      - name: Upload validation evidence
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: v11-control-plane-${{ github.run_id }}
          path: v11-validation/
          if-no-files-found: error
          retention-days: 90

      - name: Enforce validation gate
        if: always()
        env:
          VALIDATOR_RESULT: ${{ steps.validator.outcome }}
          TEST_RESULT: ${{ steps.tests.outcome }}
          PROJECTION_RESULT: ${{ steps.projections.outcome }}
        run: |
          test "$VALIDATOR_RESULT" = success
          test "$TEST_RESULT" = success
          test "$PROJECTION_RESULT" = success