GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / testcode / sandbox/capsules/grid-compute

Contract and 7 more files

A JavaScript module in the deeplink folder of Ventus Grid Engine covering the Renewable Energy Planning Database (REPD) register, wind and solar, and uses data from the GridAtlas repository.

599 lines of JavaScript and HTML and Python from testcode, v11, ventus-grid-engine, in 8 files. Topic: Websites and apps. Section 2015 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. Server ingest · testcode / sandbox/capsules/grid-compute/server.py lines 1–24
  2. Verify Live storage · testcode / sandbox/capsules/grid-compute/verify-live.py lines 1–26
  3. Compose storage · testcode / sandbox/capsules/tool-layers/compose.mjs lines 1–26
  4. Ownership transform · testcode / sandbox/capsules/tool-layers/ownership.mjs lines 1–16
  5. Source Scopes transform · testcode / sandbox/capsules/tool-layers/source-scopes.mjs lines 1–46
  6. Table — Block Page Rnd Page render · testcode / table/20260914T144622Z-block-page-rnd/index.html lines 1–173
  7. V11 — Index Page render · v11 / index.html lines 1–39
  8. Contract ingest · ventus-grid-engine / deeplink/contract.js lines 1–249

Server

A Python module in the grid compute folder of Testcode that works with do post (`do_POST`).

ingesttestcode / sandbox/capsules/grid-compute/server.py · lines 1–24 of 24 · Not reached from any entry point (candidate for review) · pattern do_POST (shared by 2 files)

What it does
It loads data. Defines Handler, __init__, log_message, do_POST. Uses libraries json, re, threading, datetime, pathlib. Side effects: reads or writes files.
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 latest.json.
What it achieves
It is built from the handler class (`Handler`), the log message helper (`log_message`) and the do post helper (`do_POST`). Local artifact server + append-only computation receipt collector.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/grid-compute · Python module
Uses
json, re, threading, datetime, pathlib, http.server
Used by
none found
Produces
Handler
Defines here
Handler, __init__, log_message, do_POST
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/capsules/grid-compute/server.py:1-24 · blob 4e0fdae2f88526c10d63c528e65e2a4cd2ef95c6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
"""Local artifact server + append-only computation receipt collector."""
import json,re,threading,datetime
from pathlib import Path
from http.server import ThreadingHTTPServer,SimpleHTTPRequestHandler
HERE=Path(__file__).resolve().parent;config=json.loads((HERE/'latest.json').read_text());OUT=Path(config['output']);lock=threading.Lock()
class Handler(SimpleHTTPRequestHandler):
 def __init__(self,*args,**kwargs):super().__init__(*args,directory=config['webroot'],**kwargs)
 def log_message(self,*args):pass
 def do_POST(self):
  if self.path!='/__testcode/receipt':self.send_error(404);return
  try:
   length=int(self.headers.get('Content-Length',0));assert 0<length<262144
   event=json.loads(self.rfile.read(length));assert event['schema']=='testcode.browser-compute-event.v1'
   visit=event['visit_id'];assert re.fullmatch(r'[a-zA-Z0-9_-]{1,100}',visit)
   event['received_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat()
   with lock:
    dest=OUT/'receipts';dest.mkdir(exist_ok=True)
    with (dest/(visit+'.jsonl')).open('a',encoding='utf8') as f:f.write(json.dumps(event,separators=(',',':'))+'\n')
   self.send_response(204);self.end_headers()
  except Exception as error:self.send_error(400,str(error))
server=ThreadingHTTPServer(('127.0.0.1',8877),Handler)
print(json.dumps({'url':config['base'],'evidence':str(OUT),'receipt_endpoint':'/__testcode/receipt'}),flush=True)
try:server.serve_forever()
except KeyboardInterrupt:server.server_close()

Verify Live

A Python module in the grid compute folder of Testcode that fetches publish candidate and live byte verification, using SHA-256. It is built from the check step (`check`).

storagetestcode / sandbox/capsules/grid-compute/verify-live.py · lines 1–26 of 26 · Not reached from any entry point (candidate for review)

What it does
It fetches publish candidate and live byte verification. Defines check. Uses libraries urllib.request, urllib.error, hashlib, subprocess, time. Side effects: reads or writes files; makes network requests; 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 publish-candidate.json. Out: JSON file live-byte-verification.json.
What it achieves
Compare every deployed candidate byte with its committed source; no screenshots.
Why it matters
No other file in the estate was found to import it.
Application
testcode · sandbox/capsules/grid-compute · Python module
Uses
urllib.request, urllib.error, hashlib, subprocess, time, json, datetime, concurrent.futures
Used by
none found
Produces
check
Defines here
check
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/capsules/grid-compute/verify-live.py:1-26 · blob 9b9206880d64c0722ef3979a1c3b7a369916096a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: experimental · users: none · canonical: unreached_review
"""Compare every deployed candidate byte with its committed source; no screenshots."""
import urllib.request,urllib.error,hashlib,subprocess,time,json,datetime,concurrent.futures
from pathlib import Path
H=Path(__file__).resolve().parent;cfg=json.loads((H/'publish-candidate.json').read_text());repo=Path(cfg['webroot']);gen=cfg['generation'];prefix='testcode/'+gen+'/';base='https://www.globalgrid2050.com/'
commit=subprocess.check_output(['git','rev-parse','HEAD'],cwd=repo,text=True).strip()
paths=subprocess.check_output(['git','ls-tree','-r','--name-only',commit,'--',prefix],cwd=repo,text=True).splitlines();assert len(paths)>100
for attempt in range(45):
 try:
  with urllib.request.urlopen(base+prefix+'index.html',timeout=15) as r:body=r.read()
  if ('Grid computation detector '+gen).encode() in body:break
 except Exception:pass
 if attempt%3==0:print('Waiting for committed candidate '+gen+' to be served',flush=True)
 time.sleep(20)
else:raise SystemExit('Publication not observable after 15 minutes')
def check(p):
 expected=subprocess.check_output(['git','show',commit+':'+p],cwd=repo)
 try:
  with urllib.request.urlopen(urllib.request.Request(base+p,headers={'Cache-Control':'no-cache'}),timeout=40) as r:actual=r.read();status=r.status;url=r.url
  return {'path':p,'status':status,'url':url,'bytes':len(actual),'sha256':hashlib.sha256(actual).hexdigest(),'matches_commit':actual==expected}
 except Exception as e:return {'path':p,'error':str(e),'matches_commit':False}
with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:results=list(pool.map(check,paths))
with urllib.request.urlopen(base,timeout=40) as r:homepage=r.read().decode()
record={'checked_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'commit':commit,'homepage_has_test_code':'<h2>Test Code</h2>' in homepage and prefix in homepage,'results':results}
out=Path(cfg['output'])/'live-byte-verification.json';out.write_text(json.dumps(record,indent=2)+'\n')
print(json.dumps({'files':len(results),'matching':sum(x['matches_commit'] for x in results),'homepage':record['homepage_has_test_code'],'failed':[x for x in results if not x['matches_commit']]}),flush=True)
raise SystemExit(0 if record['homepage_has_test_code'] and all(x['matches_commit'] for x in results) else 1)

Compose

A JavaScript module in the tool layers folder of Testcode that uses SHA-256. It is built from the compose tool owner helper (`composeToolOwner`).

storagetestcode / sandbox/capsules/tool-layers/compose.mjs · lines 1–26 of 26

What it does
Defines hash, composeToolOwner, git. Uses libraries node:child_process, node:crypto, node:fs/promises, node:path. Side effects: reads or writes files; 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.
Downstream impact
Used directly by 2 files: Build (testcode); Compose Test (testcode). Reached from 3 other entry points, including Codex Cartridges Workflow (testcode); Controls Layout Workflow (testcode); Offshore Route Workflow (testcode).
What it achieves
Defines `hash`, `composeToolOwner` and `git`.
Why it matters
Run by Build. Checked by Compose Test.
Application
testcode · sandbox/capsules/tool-layers · JavaScript module
Uses
node:child_process, node:crypto, node:fs/promises, node:path
Used by
run by Build (script call), run by Compose Test (script call)
Produces
composeToolOwner
Defines here
hash, composeToolOwner, git
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/capsules/tool-layers/compose.mjs:1-26 · blob d89eabebbc873cc4df3f05ec50d8cc8aa5e98195 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: supporting_data
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import {mkdir,writeFile} from 'node:fs/promises';
import path from 'node:path';
const hash = b => createHash('sha256').update(b).digest('hex');
/** Only committed, manifest-checked producer bytes enter a candidate. */
export async function composeToolOwner(root, owner, revision, release) {
  if (!/^[a-f0-9]{40}$/.test(revision) || !/^\d{12}$/.test(release)) throw Error('Full owner commit and release timestamp required');
  const git = (...args) => execFileSync('git',['-C',owner,...args],{maxBuffer:64*1024*1024,windowsHide:true});
  const prefix = `releases/${release}/`;
  const raw = git('show',`${revision}:${prefix}manifest.json`);
  const manifest = JSON.parse(raw);
  if (manifest.generation !== release || !manifest.files?.length) throw Error('Invalid producer manifest');
  const prepared = [];
  for (const file of manifest.files) {
    if (!file.path || file.path.includes('\\') || file.path.split('/').some(p=>p==='..'||p==='') || path.isAbsolute(file.path)) throw Error('Unsafe producer path');
    const bytes = git('show',`${revision}:${prefix}${file.path}`);
    if (hash(bytes)!==file.sha256 || bytes.length!==file.bytes) throw Error(`Producer mismatch: ${file.path}`);
    prepared.push({file,bytes});
  }
  for (const {file,bytes} of prepared) {
    const target = path.join(root,'layer-apps',file.path);
    await mkdir(path.dirname(target),{recursive:true}); await writeFile(target,bytes);
  }
  return {repository:git('remote','get-url','origin').toString().trim(),commit:revision,release,manifestSha256:hash(raw),applications:manifest.applications,rootOriginDependencies:manifest.rootOriginDependencies};
}

Ownership

A JavaScript module in the tool layers folder of Testcode that resolves one explicit producer per tool while retaining historical bundle manifests. It merges tool ownership (`mergeToolOwnership`).

transformtestcode / sandbox/capsules/tool-layers/ownership.mjs · lines 1–16 of 16 · pattern identity (shared by 11 files)

What it does
It calculates its inputs. Defines mergeToolOwnership, pin, identity.
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.
Downstream impact
Used directly by 2 files: Build (testcode); Ownership Test (testcode). Reached from 3 other entry points, including Codex Cartridges Workflow (testcode); Controls Layout Workflow (testcode); Offshore Route Workflow (testcode).
What it achieves
Defines `mergeToolOwnership`, `pin` and `identity`.
Why it matters
Run by Build. Checked by Ownership Test.
Application
testcode · sandbox/capsules/tool-layers · JavaScript module
Uses
none found
Used by
run by Build (script call), imported by Ownership Test (import)
Produces
mergeToolOwnership
Defines here
mergeToolOwnership, pin, identity
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/capsules/tool-layers/ownership.mjs:1-16 · blob fdaa6e710b1dfc3319e4d90c63e466f5f6152531 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unknown
/** Resolve one explicit producer per tool while retaining historical bundle manifests. */
export function mergeToolOwnership(previous, owner, applications, names = {}) {
  const pin = ({repository,commit,release,manifestSha256}) => ({repository,commit,release,manifestSha256});
  const combined = new Map(previous.tools.map(tool => {
    if (tool.owner) return [tool.id,tool];
    const candidates = previous.owners.filter(item => item.applications.some(app => app.id === tool.id));
    if (candidates.length !== 1) throw Error(`Ambiguous historical owner for ${tool.id}`);
    return [tool.id,{...tool,owner:pin(candidates[0])}];
  }));
  for (const app of applications) combined.set(app.id, {
    id:app.id,title:names[app.id] || app.id,entry:'../layer-apps/'+app.entry,owner:pin(owner)
  });
  const identity = item => JSON.stringify(pin(item));
  const owners = new Map(previous.owners.concat(owner).map(item=>[identity(item),item]));
  return {owners:[...owners.values()],tools:[...combined.values()]};
}

Source Scopes

A JavaScript module in the tool layers folder of Testcode that uses SHA-256.

transformtestcode / sandbox/capsules/tool-layers/source-scopes.mjs · lines 1–46 of 46

What it does
It calculates its inputs. Defines sha, buildToolSourceScopes, safe. Uses libraries node:path, node:crypto.
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. README: "`source-scopes.mjs` builds `layer-source-scopes.json` as a separate per-tool inventory."
Downstream impact
Used directly by 2 files: Build (testcode); Source Scopes Test (testcode). Reached from 3 other entry points, including Codex Cartridges Workflow (testcode); Controls Layout Workflow (testcode); Offshore Route Workflow (testcode).
What it achieves
It builds tool source scopes (`buildToolSourceScopes`) and is built from the sha step (`sha`) and the safe step (`safe`). The README says: `source-scopes.mjs` builds `layer-source-scopes.json` as a separate per-tool inventory.
Why it matters
Run by Build. Checked by Source Scopes Test.
Application
testcode · sandbox/capsules/tool-layers · JavaScript module
Uses
node:path, node:crypto
Used by
run by Build (script call), imported by Source Scopes Test (import)
Produces
buildToolSourceScopes
Defines here
sha, buildToolSourceScopes, safe
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/capsules/tool-layers/source-scopes.mjs:1-46 · blob 932520ca41946a82288bfbef6a6ed3a40441c6ab · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unknown
import path from 'node:path';
import {createHash} from 'node:crypto';
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
/** Index standalone source boundaries without concatenating code or executing it. */
export async function buildToolSourceScopes(registry, readManifest, readCandidate) {
  const apps=[];
  for(const tool of registry) {
    const raw=await readManifest(tool.owner);
    if(sha(raw)!==tool.owner.manifestSha256)throw Error('Tool manifest pin mismatch: '+tool.id);
    const manifest=JSON.parse(raw);
    if(manifest.generation!==tool.owner.release)throw Error('Tool release identity mismatch');
    const safe=value=>typeof value==='string'&&!/[\\:%?#]/.test(value)&&!value.split('/').some(part=>!part||part==='.'||part==='..');
    if(!['globalgrid.original-runtime.v1','globalgrid.derived-runtime.v1'].includes(manifest.schema)||!Array.isArray(manifest.applications)||!manifest.applications.length||!Array.isArray(manifest.files)||!manifest.files.length)throw Error('Invalid tool source manifest schema');
    const ids=new Set(),entries=new Set(),paths=new Set();
    for(const item of manifest.applications){if(typeof item.id!=='string'||!item.id||ids.has(item.id)||!safe(item.entry)||entries.has(item.entry))throw Error('Invalid tool source application');ids.add(item.id);entries.add(item.entry);}
    for(const file of manifest.files){if(!safe(file.path)||paths.has(file.path)||!Number.isSafeInteger(file.bytes)||file.bytes<0||!/^[a-f0-9]{64}$/.test(file.sha256))throw Error('Invalid tool source member');paths.add(file.path);}
    let dependencyManifest=manifest;
    if(manifest.baseline){
      const baseline=manifest.baseline;
      if(!/^[a-f0-9]{40}$/.test(baseline.commit||'')||!/^\d{12}$/.test(baseline.generation||'')||!/^[a-f0-9]{64}$/.test(baseline.manifestSha256||''))throw Error('Invalid baseline dependency pin');
      const original=await readManifest({...tool.owner,commit:baseline.commit,release:baseline.generation,manifestSha256:baseline.manifestSha256});
      if(sha(original)!==baseline.manifestSha256)throw Error('Baseline dependency manifest mismatch');
      dependencyManifest=JSON.parse(original);
      if(dependencyManifest.schema!=='globalgrid.original-runtime.v1'||dependencyManifest.generation!==baseline.generation)throw Error('Baseline dependency identity mismatch');
    }
    for(const record of [manifest,dependencyManifest])for(const key of ['externalLiteralUrls','rootOriginDependencies'])if(record[key]!==undefined&&(!Array.isArray(record[key])||record[key].some(value=>typeof value!=='string')))throw Error('Invalid dependency declarations');
    if(manifest.crossOwnerNavigation!==undefined&&!Array.isArray(manifest.crossOwnerNavigation))throw Error('Invalid navigation declarations');

    const app=manifest.applications?.find(app=>app.id===tool.id);
    if(!app || '../layer-apps/'+app.entry!==tool.entry)throw Error('Tool source entry mismatch');
    const own=path.posix.dirname(app.entry)+'/', others=manifest.applications.filter(a=>a.id!==tool.id).map(a=>path.posix.dirname(a.entry)+'/');
    const selected=manifest.files.filter(file=>file.path.startsWith(own)||!others.some(prefix=>file.path.startsWith(prefix)));
    const files=[],seen=new Set();
    for(const file of selected) {
      if(typeof file.path!=='string'||/[\\:%?#]/.test(file.path)||file.path.split('/').some(part=>!part||part==='.'||part==='..')||seen.has(file.path))throw Error('Unsafe or duplicate tool source path');
      seen.add(file.path);const candidate='layer-apps/'+file.path,bytes=await readCandidate(candidate);
      if(bytes.length!==file.bytes||sha(bytes)!==file.sha256)throw Error('Composed source differs from owner: '+candidate);
      files.push({path:candidate,bytes:file.bytes,sha256:file.sha256,kind:/\.(?:js|mjs|css|html)$/.test(file.path)?'source':'data'});
    }
    if(!seen.has(app.entry))throw Error('Tool entry absent from source scope');
    apps.push({id:tool.id,title:tool.title,entry:tool.entry,owner:tool.owner,files,
      externalDependencies:manifest.externalLiteralUrls||dependencyManifest.externalLiteralUrls||[],rootOriginDependencies:manifest.rootOriginDependencies||[],
      baselineNavigation:manifest.crossOwnerNavigation||[]});
  }
  return {schema:'ventus.layer-source-scopes.v1',apps,scope:'Each composed standalone tool indexed separately. External and root-origin dependencies are declared, not bundled or verified here. No runtime source concatenation.'};
}

Table — Block Page Rnd Page

A web page in Testcode that draws blocks, reactions, substations and solar, and uses data from the stars, ventus-grid-engine and code-generator repositories.

rendertestcode / table/20260914T144622Z-block-page-rnd/index.html · lines 1–173 of 173 · version 2026-09-14 14:46 · Entry point · pattern showCategory (shared by 3 files)

What it does
It draws blocks, reactions, substations and solar. Defines 13 functions or classes, including $, esc, byName, reactionsFor, healthOf. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
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: substations, solar. README: "The publication checkout is sparse: `index.html` and the complete `uk_renewables_pipeline/` tree."
Inputs & outputs
In: data source: stars data; data source: ventus-grid-engine data; data source: code-generator data; JSON file blocks.json; JSON file reactions.json; form fields (user input). Out: web page.
Downstream impact
It is itself an entry point (page); no other file was found loading it.
What it achieves
It builds search index (`buildSearchIndex`), wires search (`wireSearch`) and closes panel (`closePanel`). Periodic table of GlobalGrid2050 architecture development.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
testcode · table/20260914T144622Z-block-page-rnd · page
Uses
Start (link), Code (link), Code Generator — Index Page (link), Table (link)
Used by
none found
Produces
$, esc, byName, reactionsFor, healthOf, compatHTML, cls, buildSearchIndex, wireSearch, closePanel, show, showCategory
Defines here
$, esc, byName, reactionsFor, healthOf, compatHTML, cls, buildSearchIndex, wireSearch, closePanel, show, showCategory, tile
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 table/20260914T144622Z-block-page-rnd/index.html:1-173 · blob 7554d4d546d8ffdee2149ce32eeece856fb0c9ba · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: experimental · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Periodic table of globalgrid2050 architecture development</title>
<style>
  :root{color-scheme:dark}
  body{margin:0;padding:16px 18px 40px;background:#0b0d12;color:#eef2fb;font:14px/1.5 Inter,ui-sans-serif,system-ui,sans-serif}
  a{color:#00e5ff}
  h1{font-size:22px;margin:0 0 4px}
  .ey{font-family:ui-monospace,monospace;font-size:11px;letter-spacing:.2em;text-transform:uppercase;color:#00e5ff}
  .nav{display:flex;flex-wrap:wrap;gap:6px 14px;margin:8px 0 10px;font-size:13px;font-family:ui-monospace,monospace}
  .muted{color:#9aa3b5}
  .cat{margin:18px 0 6px;display:flex;align-items:baseline;gap:10px;flex-wrap:wrap;scroll-margin-top:8px}
  .cat h2{font-size:14px;margin:0;letter-spacing:.06em;text-transform:uppercase}
  .cat.on h2{text-decoration:underline;text-underline-offset:4px}
  .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(112px,1fr));gap:8px}
  .tile{border:1px solid #262b36;border-radius:10px;padding:8px 9px;background:linear-gradient(160deg,rgba(255,255,255,.055),rgba(255,255,255,.014));cursor:pointer;min-height:78px;display:flex;flex-direction:column;gap:2px}
  .tile:hover,.tile.on{border-color:#00e5ff;box-shadow:0 0 0 1px rgba(0,229,255,.22)}
  .tile .sym{font-family:ui-monospace,monospace;font-size:20px;font-weight:700;line-height:1}
  .tile .num{font-family:ui-monospace,monospace;font-size:10px;color:#9aa3b5}
  .tile .t{font-size:11.5px;line-height:1.2;color:#dfe6f3}
  .tile .n{font-family:ui-monospace,monospace;font-size:10px;color:#9aa3b5;margin-top:auto}
  .panel{position:sticky;bottom:0;border:1px solid #00e5ff;border-radius:14px;background:#12151c;padding:14px;margin-top:18px;box-shadow:0 -10px 40px rgba(0,0,0,.4);max-height:70vh;overflow:auto}
  .panel h3{margin:0 0 4px;font-size:18px;padding-right:36px}
  .close{position:absolute;top:8px;right:10px;background:none;border:1px solid #385464;color:#9aa3b5;border-radius:999px;width:28px;height:28px;font:inherit;cursor:pointer}
  .close:hover{border-color:#00e5ff;color:#eef2fb}
  .btn{display:inline-block;background:#0f1218;border:1px solid #385464;color:#eef2fb;padding:7px 12px;border-radius:999px;font:inherit;font-size:13px;cursor:pointer;margin:6px 6px 0 0;text-decoration:none}
  .btn:hover{border-color:#00e5ff}
  .btn.first{border-color:#00e5ff}
  details{margin-top:8px}summary{cursor:pointer;color:#9aa3b5;font-size:13px}
  .inside{font-family:ui-monospace,monospace;font-size:12px;columns:2;column-gap:20px}
  .filter{margin:8px 0 0;font-size:13px}
  .search{width:100%;box-sizing:border-box;background:#0f1218;border:1px solid #385464;color:#eef2fb;border-radius:999px;padding:10px 16px;font:inherit;font-size:15px;margin:6px 0}
  .search:focus{outline:none;border-color:#00e5ff;box-shadow:0 0 0 2px rgba(0,229,255,.18)}
  #results{margin:2px 0 6px}
  #results a{display:inline-block;margin:3px 6px 3px 0;padding:4px 10px;border:1px solid #262b36;border-radius:999px;text-decoration:none;font-size:12.5px}
  #results a:hover{border-color:#00e5ff}
  #results .fam{color:#9aa3b5;font-family:ui-monospace,monospace}
  .chip{display:inline-block;padding:2px 9px;border-radius:999px;font-size:11.5px;font-family:ui-monospace,monospace;border:1px solid;margin:0 4px 0 0}
  .chip.green{color:#69f0ae;border-color:rgba(105,240,174,.5)}
  .chip.amber{color:#ffd54a;border-color:rgba(255,213,74,.5)}
  .chip.red{color:#ff6e6e;border-color:rgba(255,110,110,.5)}
  .chip.grey{color:#9aa3b5;border-color:#385464}
  .compat{margin-top:8px}
  .compat a{margin-right:2px}
  .purpose{margin:2px 0 6px;color:#c7d0e0}
  @media(max-width:600px){.inside{columns:1}.grid{grid-template-columns:repeat(auto-fill,minmax(96px,1fr))}body{padding:12px 12px 40px}}
</style>
<div class="ey">Ventus · Global Grid 2050</div>
<h1>Periodic table of globalgrid2050 architecture development</h1>
<nav class="nav"><a href="https://ventusltd.github.io/ventus-grid-engine/?graph=periodic-table">← Map</a><a href="https://globalgrid2050.com/">Home</a><a href="https://ventusltd.github.io/stars/start.html">Start here</a><a href="https://ventusltd.github.io/stars/code.html">Code report</a></nav>
<div class="muted" id="status">Loading…</div>
<div class="muted">Tap a block to see what it does, where it runs, what it is proven to work with, and what it needs.</div>
<input class="search" id="search" type="search" placeholder="Search 208 blocks and 10,811 functions - try distance, substation, voltage, Ug" autocomplete="off" spellcheck="false">
<div id="results"></div>
<div class="filter" id="filter" hidden></div>
<div id="table"></div>
<div class="panel" id="panel" hidden></div>
<p class="muted" style="margin-top:20px">Every block has a permanent number. Numbers 1 to 47 are the original elements; later numbers are blocks added as the code is read. Underneath each block are its functions, each with its own permanent number; they are the parts list, kept in the background. <a href="https://github.com/Ventusltd/stars/blob/main/MODULAR-STAR.md">What this is</a> · <a href="htt  … [line shortened here: 546 characters; full line on GitHub]
<script>
const $ = s => document.querySelector(s);
const esc = s => String(s).replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
const byName = (a, b) => String(a).localeCompare(String(b), 'en');
let data, reactions = { reactions: [] }, bySym = {}, searchIndex = [];
const BUILTINS = new Set(['document','window','fetch','history','console','localStorage','sessionStorage','location','navigator','Math','JSON','Object','Array','String','Number','Date','Promise','Map','Set','setTimeout','setInterval','requestAnimationFrame','URL','URLSearchParams','globalResult','undefined','globalThis','performance','crypto','structuredClone']);
const GRID_PURPOSE = { geodesy:'Turns coordinates into real distances and bearings - the first step in siting and routing a grid connection.', 'grid-network':'Models substations, circuits and their ratings - where new power can actually flow.', capacity:'Firm capacity, headroom and connection sizing - whether a project can connect, and how much.', cartridges:'A plug-in part of the interactive Grid  … [line shortened here: 1,062 characters; full line on GitHub]
function reactionsFor(sym){ return (reactions.reactions||[]).filter(p => p.a===sym || p.b===sym); }
function healthOf(sym){
  const rs = reactionsFor(sym);
  const mixed = rs.filter(p => p.verdict==='mixed evidence' || / red /.test(' '+(p.basis||'')+' '));
  if (mixed.length) return {cls:'amber', label:mixed.length+' pair'+(mixed.length>1?'s':'')+' with failing tests'};
  if (rs.length) return {cls:'green', label:'no failing pair'};
  return {cls:'grey', label:'not yet tested with another block'};
}
function compatHTML(sym){
  const rs = reactionsFor(sym).map(p => ({ other:(p.a===sym?p.b:p.a), v:p.verdict, basis:p.basis, prob:p.probability, n:p.together }))
    .sort((x,y)=> (y.prob||0)-(x.prob||0) || (y.n||0)-(x.n||0));
  if (!rs.length) return '';
  const cls = v => v==='mixed evidence' ? 'amber' : v==='seen together' ? 'green' : 'grey';
  const rows = rs.slice(0,8).map(r => { const o = bySym[r.other];
    return `<a href="?block=${esc(r.other)}"><span class="chip ${cls(r.v)}">${esc(r.other)}</span>${esc(o?o.title:r.other)}</a> <span class="muted">${esc(r.basis||'')}</span>`; }).join('<br>');
  return `<div class="compat"><span class="muted">Proven to work with (from real apps and composition tests):</span><br>${rows}${rs.length>8?`<br><span class="muted">...and ${rs.length-8} more</span>`:''}</div>`;
}
function buildSearchIndex(){ searchIndex = [];
  for (const b of data.blocks){ searchIndex.push({t:'block', sym:b.symbol, label:b.symbol+' '+b.title, key:(b.symbol+' '+b.title+' '+(b.description||'')).toLowerCase()});
    for (const f of (b.inside||[])) searchIndex.push({t:'fn', sym:b.symbol, family:f.family, label:'#'+f.family+' '+f.name, sub:b.symbol+' '+b.title, key:(f.name+' #'+f.family).toLowerCase(), places:f.places}); } }
function wireSearch(){ const box=$('#search'), out=$('#results'); let timer;
  box.oninput = () => { clearTimeout(timer); timer=setTimeout(()=>{ const q=box.value.trim().toLowerCase(); if(q.length<2){out.innerHTML='';return;}
    const hits = searchIndex.filter(x => x.key.includes(q));
    const blocks = hits.filter(x=>x.t==='block').slice(0,12);
    const fns = hits.filter(x=>x.t==='fn').sort((a,b)=>(b.places||0)-(a.places||0)).slice(0,14);
    out.innerHTML = (blocks.length?`<div>${blocks.map(b=>`<a href="?block=${esc(b.sym)}">${esc(b.label)}</a>`).join('')}</div>`:'')
      + (fns.length?`<div style="margin-top:4px"><span class="muted" style="font-size:12px">functions:</span> ${fns.map(f=>`<a href="https://ventusltd.github.io/stars/code.html?family=${f.family}"><span class="fam">#${f.family}</span> ${esc(f.label.replace('#'+f.family+' ',''))} <span class="muted">in ${esc(f.sym)} x${f.places}</span></a>`).join('')}</div>`:'')
      + (!blocks.length&&!fns.length?`<span class="muted">Nothing matches "${esc(box.value)}".</span>`:'');
    out.querySelectorAll('a[href^="?block="]').forEach(a=>a.onclick=e=>{e.preventDefault();show(new URLSearchParams(a.getAttribute('href')).get('block'));window.scrollTo({top:0});}); }, 120); }; }
function closePanel() {
  $('#panel').hidden = true;
  document.querySelectorAll('.tile.on').forEach(t => t.classList.remove('on'));
  const q = new URLSearchParams(location.search); q.delete('block');
  history.replaceState(null, '', q.toString() ? '?' + q : location.pathname);
}
function show(sym) {
  const b = data.blocks.find(x => x.symbol === sym); if (!b) return;
  document.querySelectorAll('.tile').forEach(t => t.classList.toggle('on', t.dataset.sym === sym));
  const autos = $('#autos'); if (autos && b.kind === 'auto') autos.open = true;
  const cat = data.categories.find(c => c.id === b.category) || { title: 'Other tools', colour: '#9aa3b5' };
  const p = $('#panel'); p.hidden = false;
  const kind = { constant: 'a value everyone must agree on', engine: 'an engine module', cartridge: 'a plug-in part of the map', layer: 'a map layer', deeplink: 'a link contract', app: 'an app', tool: 'a tool', auto: 'found automatically from one source file' }[b.kind] || b.kind;
  const state = b.state === 'UNSETTLED' ? ' · value not yet agreed' : b.state === 'SETTLED' ? ' · agreed' : '';
  const deps = (b.depends_on || []).slice().sort((x, y) => byName(x.title, y.title));
  const usedBy = (b.used_by || []).slice().sort(byName);
  const inside = (b.inside || []).slice().sort((x, y) => (y.places - x.places) || byName(x.name, y.name));
  const buttons = [
    b.live[0] ? `<a class="btn first" href="${esc(b.live[0])}" target="_blank" rel="noopener">Open the live page</a>` : '',
    `<a class="btn" href="https://ventusltd.github.io/ventus-grid-engine/?graph=periodic-table&focus=${encodeURIComponent(b.symbol + ' · ' + b.title)}">See it on the map</a>`,
    b.functions ? `<a class="btn" href="https://ventusltd.github.io/code-generator/?blocks=${encodeURIComponent(b.symbol)}">Add to an app</a>` : '',
    b.files[0] ? `<a class="btn" href="https://github.com/${esc(b.files[0].repo)}/blob/${esc(b.files[0].commit)}/${esc(b.files[0].path)}" target="_blank" rel="noopener">Source on GitHub</a>` : ''
  ].join('');
  p.innerHTML = `<button class="close" id="close" title="Close" aria-label="Close">×</button>
    <div class="ey" style="color:${cat.colour}">${esc(cat.title)} · block ${b.number}</div>
    <h3><span style="font-family:ui-monospace,monospace">${esc(b.symbol)}</span> ${esc(b.title)}</h3>
    <div>${esc(b.description)}</div>
    ${GRID_PURPOSE[b.category] ? `<div class="purpose">${esc(GRID_PURPOSE[b.category])}</div>` : ''}
    <div style="margin-top:4px"><span class="chip ${healthOf(b.symbol).cls}">${healthOf(b.symbol).label}</span></div>
    <div class="muted" style="margin-top:6px">${esc(kind)}${state}${b.functions ? ` · ${b.functions} functions inside (${b.named_functions} named)` : ' · no code of its own'}${b.repos.length ? ' · lives in ' + b.repos.map(r => esc(r.split('/')[1])).sort(byName).join(', ') : ''}${b.first_written ? ' · first written ' + b.first_written.slice(0, 10) : ''}</div>
    <div>${buttons}</div>
    ${deps.length ? `<div style="margin-top:8px"><span class="muted">Depends on:</span> ${deps.map(d => `<a href="?block=${esc(d.symbol)}">${esc(d.symbol)} ${esc(d.title)}</a> <span class="muted">(through ${d.via.map(esc).join(", ")})</span>`).join("; ")}</div>` : ""}${usedBy.length ? `<div><span class="muted">Used by:</span> ${usedBy.map(s => `<a href="?block=${esc(s)}">${esc(s)}</a>`).join(", ")  … [line shortened here: 414 characters; full line on GitHub]
    ${(() => { const real = (b.needs||[]).filter(n => !BUILTINS.has(n.name)); const builtin = (b.needs||[]).length - real.length;
      return real.length ? `<div style="margin-top:6px"><span style="color:#ffd54a">Needs from elsewhere:</span> ${real.slice(0,10).map(n => esc(n.meaning||n.name)).join('; ')}${builtin?` <span class="muted">(plus ${builtin} standard browser features)</span>`:''}</div>` : (builtin ? `<div style="margin-top:6px" class="muted">Uses only standard browser features.</div>` : ''); })()}
    ${compatHTML(b.symbol)}
    ${inside.length ? `<details><summary>Inside: the parts list (${inside.length} of ${b.named_functions} named functions, most used first)</summary><div class="inside">${inside.map(f => `<div><a href="https://ventusltd.github.io/stars/code.html?family=${f.family}">#${f.family}</a> ${esc(f.name)} <span class="muted">×${f.places}</span></div>`).join('')}</div></details>` : ''}`;
  $('#close').onclick = closePanel;
  document.querySelectorAll('#panel a[href^="?block="]').forEach(a => a.onclick = e => { e.preventDefault(); show(new URLSearchParams(a.getAttribute('href')).get('block')); });
  const q = new URLSearchParams(location.search); q.set('block', sym);
  history.replaceState(null, '', '?' + q);
}
function showCategory(id) {
  const cat = data.categories.find(c => c.id === id); const f = $('#filter');
  document.querySelectorAll('.cat').forEach(el => el.classList.toggle('on', el.dataset.cat === id));
  if (!cat) { f.hidden = true; return; }
  f.hidden = false;
  f.innerHTML = `Showing the subject <b style="color:${cat.colour}">${esc(cat.title)}</b> · <a href="https://ventusltd.github.io/stars/table.html">show every subject</a>`;
  const h = document.getElementById('h-' + id); if (h) h.scrollIntoView({ block: 'start' });
}
(async () => {
  try {
    data = await (await fetch('https://ventusltd.github.io/stars/blocks/blocks.json', {cache: 'no-cache'})).json();
    try { reactions = await (await fetch('https://ventusltd.github.io/stars/blocks/reactions.json', {cache: 'no-cache'})).json(); } catch (e) { reactions = { reactions: [] }; }
    bySym = Object.fromEntries(data.blocks.map(b => [b.symbol, b]));
    buildSearchIndex();
    wireSearch();
    const named = data.blocks.filter(b => b.kind !== 'auto'), autos = data.blocks.filter(b => b.kind === 'auto');
    $('#status').textContent = `${named.length} named blocks and ${autos.length} blocks found automatically from source files · ${data.blocks.reduce((s, b) => s + b.functions, 0).toLocaleString('en-GB')} functions underneath · updated ${data.generated_utc.slice(0, 16).replace('T', ' ')} UTC`;
    const t = $('#table');
    const tile = (b, c) => `<div class="tile" data-sym="${esc(b.symbol)}" style="border-top:3px solid ${c.colour}"><div class="num">${b.number}</div><div class="sym">${esc(b.symbol)}</div><div class="t">${esc(b.title)}</div><div class="n">${b.functions ? b.functions + ' functions' : 'data only'}${b.state === 'UNSETTLED' ? ' · not agreed' : ''}</div></div>`;
    for (const c of data.categories) {
      const all = data.blocks.filter(b => b.category === c.id && (b.kind !== 'auto' || b.functions >= 8)).sort((a, b) => a.number - b.number);
      if (!all.length) continue;
      const bs = all.filter(b => b.kind !== 'auto'), as = all.filter(b => b.kind === 'auto');
      t.insertAdjacentHTML('beforeend', `<div class="cat" id="h-${esc(c.id)}" data-cat="${esc(c.id)}"><h2 style="color:${c.colour}"><a href="?category=${esc(c.id)}" style="color:inherit;text-decoration:none">${esc(c.title)}</a></h2><span class="muted">${esc(c.blurb)}</span></div>`);
      if (bs.length) t.insertAdjacentHTML('beforeend', `<div class="grid">${bs.map(b => tile(b, c)).join('')}</div>`);
      if (as.length) t.insertAdjacentHTML('beforeend', `<details id="autos"><summary>${as.length} blocks found automatically from source files, in number order (tap to show)</summary><div class="grid" style="margin-top:8px">${as.map(b => tile(b, c)).join('')}</div></details>`);
    }
    document.querySelectorAll('.tile').forEach(el => el.onclick = () => show(el.dataset.sym));
    document.querySelectorAll('.cat h2 a').forEach(a => a.onclick = e => { e.preventDefault(); const id = new URLSearchParams(a.getAttribute('href')).get('category'); history.replaceState(null, '', '?category=' + id); showCategory(id); });
    const q = new URLSearchParams(location.search);
    if (q.get('category')) showCategory(q.get('category'));
    if (q.get('block')) show(q.get('block'));
  } catch (e) { $('#status').textContent = 'The table is not published yet: ' + e.message; }
})();
</script>
</html>

V11 — Index Page

A web page.

renderv11 / index.html · lines 1–39 of 39 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
README: "`index.html` and this README are rendered from:"
Inputs & outputs
Out: web page.
Downstream impact
It is itself an entry point (page); no other file was found loading it.
What it achieves
The README says: `index.html` and this README are rendered from…
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
v11 · / · page
Uses
none found
Used by
none found
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
v11@debb30e092a1983e775d2ab4126995ab7bb72fe3 index.html:1-39 · blob b7aa41a7445bdea87d40f5ea858324c4832475ca · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>V11 Control Plane</title>
<style>
:root{--bg:#0b0d10;--panel:#14181d;--text:#edf1f5;--muted:#9da8b3;--line:#2a3139;--accent:#f2c94c}
*{box-sizing:border-box} body{margin:0;background:var(--bg);color:var(--text);font:16px/1.5 system-ui,sans-serif}
main{max-width:1100px;margin:auto;padding:48px 24px 80px} h1{font-size:clamp(2.4rem,7vw,5.5rem);line-height:.95;margin:0 0 18px}
h2{margin-top:40px} .eyebrow,.state{color:var(--accent);font-weight:700;text-transform:uppercase;letter-spacing:.08em}
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:14px} .card{background:var(--panel);border:1px solid var(--line);padding:20px}
.card strong{display:block;font-size:1.25rem;margin-top:6px} table{width:100%;border-collapse:collapse;background:var(--panel)}
th,td{text-align:left;padding:12px;border-bottom:1px solid var(--line)} code{overflow-wrap:anywhere} .warning{border-left:4px solid var(--accent);padding:14px 18px;background:var(--panel)}
a{color:var(--text)} footer{color:var(--muted);margin-top:48px}
</style>
</head>
<body><main>
<p class="eyebrow">GlobalGrid2050 engineering authority</p>
<h1>V11 Control Plane</h1>
<p>Deterministic status projection from V11 machine-state files. This page displays authority; it does not create it.</p>
<div class="warning"><strong>V11-001 is under validation.</strong> No final TEST PASS is claimed and no later unit is authorised.</div>
<section class="grid">
<div class="card">Active repository<strong>Ventusltd/v11</strong></div>
<div class="card">Active unit<strong>V11-001 — Active repository control plane</strong></div>
<div class="card">Validation<strong>pending</strong></div>
<div class="card">Next unit<strong>None authorised</strong></div>
</section>
<h2>Current objective</h2><p>Establish the V11-native control plane without claiming laboratory capabilities as current V11 authority.</p>
<h2>Programme units</h2><table><thead><tr><th>ID</th><th>Unit</th><th>State</th></tr></thead><tbody><tr><td><code>V11-001</code></td><td>Active repository control plane</td><td><span class='state'>active</span></td></tr><tr><td><code>V11-002</code></td><td>Clean installation and one start command</td><td><span class='state'>planned</span></td></tr><tr><td><code>V11-003</code></td><td>Laboratory re  … [line shortened here: 610 characters; full line on GitHub]
<h2>Capabilities</h2><table><thead><tr><th>ID</th><th>Capability</th><th>State</th></tr></thead><tbody><tr><td><code>CAP-CONTROL-PLANE</code></td><td>V11 engineering control plane</td><td><span class='state'>under_validation</span></td></tr><tr><td><code>CAP-CLEAN-START</code></td><td>Clean installation and one start command</td><td><span class='state'>planned</span></td></tr><tr><td><code>CAP-LAB  … [line shortened here: 703 characters; full line on GitHub]
<h2>Read-only laboratory resource</h2>
<div class="card"><p><strong>Ventusltd/solar-electrical-topology-analysis-engine-text-based</strong></p><p>Anchor: <code>d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9</code></p><p>Mode: <span class="state">read_only</span></p><p>Laboratory results are not current V11 authority.</p></div>
<h2>Validation commands</h2>
<pre><code>python -S scripts/validate_control_plane.py
python -S -m unittest -v tests/test_control_plane.py
python -S scripts/generate_control_plane_projection.py --check</code></pre>
<footer>Programme <code>v11-native-control-plane-20260802</code> · generated deterministically with no runtime timestamp.</footer>
</main></body></html>

Contract

A JavaScript module in the deeplink folder of Ventus Grid Engine covering the Renewable Energy Planning Database (REPD) register, wind and solar, and uses data from the GridAtlas repository.

ingestventus-grid-engine / deeplink/contract.js · lines 1–249 of 249 · Entry point · pattern auditProjectRows (shared by 2 files)

What it does
It lists and searches the REPD register, wind, solar and battery storage (BESS). Defines 9 functions or classes, including layerIdForBucket, bucketHasLayer, isRetiredReceiver, strip, auditProjectRows.
Why it exists in the grid workflow
Domain terms in the code: the REPD register, wind, solar, battery storage (BESS).
Downstream impact
Used directly by 5 files: Build Graph (ventus-grid-engine, https://ventusltd.github.io/ventus-grid-engine/genome/); Deeplink Receiver Proof (ventus-grid-engine); Deeplink Proof (ventus-grid-engine); Audit Receivers (ventus-grid-engine); and 1 more. Reached from 2 other entry points, including Deeplink Receiver Audit Workflow (ventus-grid-engine); Genome Workflow (ventus-grid-engine).
What it achieves
It audits project rows (`auditProjectRows`), builds deep link (`buildDeepLink`) and parses deep link (`parseDeepLink`). The MAP-button deep link, as one testable thing.
Why it matters
Loaded by the Genome page at https://ventusltd.github.io/ventus-grid-engine/genome/. Also imported by 4 files, including Build Graph, Deeplink Receiver Proof and Deeplink Proof.
Application
ventus-grid-engine · deeplink · JavaScript module
VEDIC
AUDIT PROJECT MAP LINKS (GG2050-VEDIC-000088): Ventus Grid Engine · Map integration. rows, options → Per-row link evidence and aggregate counts.
VEDIC
BUILD PROJECT MAP LINK (GG2050-VEDIC-000086): Ventus Grid Engine · Map integration. base, project → URL string with supported project query parameters.
VEDIC
PARSE PROJECT MAP LINK (GG2050-VEDIC-000087): Ventus Grid Engine · Map integration. href → Parsed project and layer fields.
Uses
GridAtlas — Atlas Page (estate URL), GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL)
Used by
named by URL in Build Graph (estate URL), imported by Deeplink Receiver Proof (import), imported by Deeplink Proof (import), imported by Audit Receivers (import), named by URL in Ventus Grid Engine — Genome Page (estate URL)
Produces
IDENTITY_PARAM, PARAMS, BUCKETS, REPD_LAYER_IDS, LAYER_ID_FOR_BUCKET, layerIdForBucket, bucketHasLayer, CANONICAL_RECEIVER, RETIRED_RECEIVERS, isRetiredReceiver, auditProjectRows, buildDeepLink
Defines here
layerIdForBucket, bucketHasLayer, isRetiredReceiver, strip, auditProjectRows, buildDeepLink, parseDeepLink, get, num
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
ventus-grid-engine@ad566356a44e006682e956483d569f31ddbb9630 deeplink/contract.js:1-249 · blob c0c9103f9198d2e8c76221fdc5138ad1e1f1da73 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: production_core
/* deeplink/contract.js — the MAP-button deep link, as one testable thing.
 *
 * Before this repo, the contract existed only as an agreement between two
 * codebases that never imported each other: Pipeline News built a URL, and
 * GridAtlas parsed it, and nothing checked that the two still matched. They
 * stopped matching, and it cost a third of the register (see BUCKETS below).
 *
 * So the contract lives here once, as data plus two pure functions. The
 * emitter and the receiver are both meant to import it. Until they do, the
 * proof in proofs/deeplink.proof.mjs at least holds it to itself.
 *
 * Sources, all at their committed HEADs at extraction time:
 *   emitter   pipelinenews @ ade103ae
 *             releases/.../assets/202608312037-atlas-pointer-deep-link.mjs
 *   receiver  gridatlas @ 64268fd0
 *             atlas/parts/.../sld-sandbox-technology-buckets.js  (runDeepLink)
 *             ventus-corev8engine-exact-repd-delegation.js:66    (REPD_IDS)
 */

/* ── Identity ─────────────────────────────────────────────────────────────
 * The project is identified by repd_ref. NOT repd_id. Both names appear in
 * the estate and they are not interchangeable; the emitter sends repd_ref
 * and the receiver reads repd_ref, and the proof asserts that they agree
 * rather than leaving it to memory.
 */
export const IDENTITY_PARAM = 'repd_ref';

/* ── Parameters the link carries ─────────────────────────────────────────── */
export const PARAMS = Object.freeze({
    repd_ref:   { type: 'string', required: true,  note: 'REPD reference; the project identity' },
    technology: { type: 'string', required: true,  note: 'a bucket from BUCKETS, not a layer id' },
    latitude:   { type: 'number', required: false, units: 'degrees north' },
    longitude:  { type: 'number', required: false, units: 'degrees east' },
    zoom:       { type: 'number', required: false, note: 'MapLibre zoom level' }
});

/* ── The bucket vocabulary the emitter may send ───────────────────────────
 * These are Pipeline News' technology names. They are NOT the engine's layer
 * ids, and the difference is the whole bug.
 */
export const BUCKETS = Object.freeze([
    'solar', 'wind_onshore', 'wind_offshore', 'bess', 'biomass', 'hydro',
    'hydrogen', 'tidal', 'geothermal', 'flywheel', 'caes', 'act', 'other'
]);

/* ── The engine's real layer ids ──────────────────────────────────────────
 * Verbatim from REPD_IDS, ventus-corev8engine-exact-repd-delegation.js:66.
 * Note what is absent: there is no `wind_onshore`, no `wind_offshore`, and
 * no `other`. There is one `wind`.
 */
export const REPD_LAYER_IDS = Object.freeze([
    'solar', 'solar_operational', 'solar_roof', 'wind',
    'wind_onshore_operational', 'wind_offshore_operational',
    'bess', 'bess_operational', 'biomass', 'tidal', 'hydrogen',
    'hydro', 'flywheel', 'act', 'geothermal', 'caes'
]);

/* ── The table that fixed it ──────────────────────────────────────────────
 * Introduced in gridatlas generation 202609041244 (v9.109); first carried to
 * production in generation 202609041330 (v9.111), because live had been
 * sitting on v9.108.
 *
 * What it replaced: a set-membership test. The old code asked "is
 * wind_onshore one of the project technologies?", got true, and reported
 * technology_layer.enabled = true — while the DOM lookup for a checkbox
 * literally named `wind_onshore` failed every single time, because no such
 * control has ever existed. Measured blast radius: 2,508 of 7,680 register
 * rows, a third of the register, reporting green while the layer sat off.
 *
 * `other` maps to null deliberately. No layer exists for it. A caller must
 * say so rather than search for one and then quietly claim success — that
 * short-circuit is the honest branch, and the proof asserts it stays honest.
 */
export const LAYER_ID_FOR_BUCKET = Object.freeze({
    wind_onshore:  'wind',
    wind_offshore: 'wind',
    other:         null
});

/**
 * The engine layer id a Pipeline News bucket resolves to.
 * Returns null when no layer exists (the `other` case) — never a guess.
 * Any bucket not in the table maps to itself, which is correct for every
 * bucket whose name already matches a real layer id.
 */
export function layerIdForBucket(tech) {
    const id = String(tech == null ? '' : tech);
    return Object.prototype.hasOwnProperty.call(LAYER_ID_FOR_BUCKET, id)
        ? LAYER_ID_FOR_BUCKET[id] : id;
}

/** True when this bucket resolves to a layer the engine can actually show. */
export function bucketHasLayer(tech) {
    const id = layerIdForBucket(tech);
    return id !== null && REPD_LAYER_IDS.includes(id);
}

/**
 * Which receiver a deep link must be built against.
 *
 * The contract used to take the base from the caller and say nothing about
 * which one was right. Every consumer therefore chose its own, and on
 * 2026-09-05 the MAP button in Pipeline News v9.7 was measured pointing at the
 * V8 overlay -- a page that still serves, so nothing 404'd, but which carries
 * no cartridge and no current.json, so no arrival there could ever compute a
 * nearest substation. The route was hard-coded in the consumer and the engine
 * published nothing for it to disagree with.
 *
 * These are the same values as deeplink/receivers.json, which is the published
 * form for anything that cannot import this module. The proof asserts the two
 * agree, so they cannot drift apart.
 */
export const CANONICAL_RECEIVER = 'https://ventusltd.github.io/gridatlas/atlas/';

export const RETIRED_RECEIVERS = Object.freeze([
    'https://globalgrid2050.com/repd_grid_atlasv8/'
]);

/**
 * True if a base is a receiver that cannot honour a deep link.
 *
 * Trailing slashes and query strings are ignored: a consumer that appends its
 * own parameters must still be caught, and the fault this exists to prevent
 * would have slipped past an equality test.
 */
export function isRetiredReceiver(base) {
    if (!base) return false;
    const strip = (value) => String(value).split('?')[0].split('#')[0].replace(/\/+$/, '');
    const target = strip(base);
    return RETIRED_RECEIVERS.some((route) => strip(route) === target);
}

/**
 * The query: every project row that carries an REPD identity, and the link it
 * should have.
 *
 * "define a query that targets all project rows on pipeline news that have an
 * REPD id and if they do then the algorithm or spiders or git via cvaa needs to
 * auto update each of those links" -- the architect, 2026-09-05.
 *
 * It is defined HERE, once, rather than in the updater, so that the thing which
 * proves the links offline and the workflow which rewrites them are running the
 * same code. An audit that uses different logic from the fix it gates is not a
 * gate.
 *
 * Returns one entry per row. `linkable` is false for a row with no REPD
 * identity or no usable geometry -- those are reported, never silently skipped,
 * because a row that quietly gets no link is exactly how 28 projects in the
 * v9.5.1 corpus ended up with a dead MAP button that nobody saw.
 *
 * @param {Array<object>} rows
 * @param {object} [options] { requireGeometry: true }
 */
export function auditProjectRows(rows, options) {
    const requireGeometry = !options || options.requireGeometry !== false;
    const list = Array.isArray(rows) ? rows : [];
    const entries = list.map((row) => {
        const identity = row ? row[IDENTITY_PARAM] : null;
        const hasIdentity = identity !== undefined && identity !== null && identity !== '';
        const hasGeometry = Boolean(row)
            && row.latitude !== undefined && row.latitude !== null && row.latitude !== ''
            && row.longitude !== undefined && row.longitude !== null && row.longitude !== '';
        const linkable = hasIdentity && (!requireGeometry || hasGeometry);
        return {
            [IDENTITY_PARAM]: hasIdentity ? identity : null,
            has_identity: hasIdentity,
            has_geometry: hasGeometry,
            linkable,
            current_href: row && row.href ? String(row.href) : null,
            current_is_retired: Boolean(row && row.href && isRetiredReceiver(row.href)),
            expected_href: linkable ? buildDeepLink(row) : null
        };
    });
    return {
        total: entries.length,
        with_identity: entries.filter((e) => e.has_identity).length,
        linkable: entries.filter((e) => e.linkable).length,
        no_geometry: entries.filter((e) => e.has_identity && !e.has_geometry).length,
        on_retired_receiver: entries.filter((e) => e.current_is_retired).length,
        needs_update: entries.filter((e) => e.linkable && e.current_href && e.current_href !== e.expected_href).length,
        entries
    };
}

/**
 * Build a deep link. The emitter's job, expressed once.
 *
 * Call it with one argument and the contract supplies the canonical receiver,
 * which is the form every consumer should use. The two-argument form is kept
 * for a caller that genuinely needs another base -- a local harness, a staged
 * copy -- and it REFUSES a retired receiver rather than quietly building a
 * link that lands somewhere inert.
 *
 * @param {string|object} base    the receiver, or the project when omitted
 * @param {object} [project]      { repd_ref, technology, latitude, longitude, zoom }
 * @returns {string}
 */
export function buildDeepLink(base, project) {
    if (project === undefined && base && typeof base === 'object') {
        project = base;
        base = CANONICAL_RECEIVER;
    }
    if (!project || project[IDENTITY_PARAM] == null || project[IDENTITY_PARAM] === '') {
        throw new Error('buildDeepLink: ' + IDENTITY_PARAM + ' is required and is the project identity');
    }
    if (isRetiredReceiver(base)) {
        throw new Error(
            'buildDeepLink: ' + base + ' is a retired receiver and carries no engine; '
            + 'a link built against it cannot compute anything. Use the canonical receiver '
            + CANONICAL_RECEIVER + ' (call buildDeepLink(project) and the contract supplies it).'
        );
    }
    const url = new URL(base);
    for (const key of Object.keys(PARAMS)) {
        const value = project[key];
        if (value === undefined || value === null || value === '') continue;
        url.searchParams.set(key, String(value));
    }
    return url.toString();
}

/**
 * Parse a deep link. The receiver's job, expressed once.
 *
 * Returns what the link asked for AND what the engine can honour, separately.
 * `layer_id` is the resolved engine layer; `layer_exists` says whether one
 * exists at all. A receiver that conflates those two is the v9.108 bug.
 */
export function parseDeepLink(href) {
    const url = new URL(href);
    const get = (k) => url.searchParams.get(k);
    const num = (k) => {
        const raw = get(k);
        if (raw === null || raw.trim() === '') return null;
        const n = Number(raw);
        return Number.isFinite(n) ? n : null;
    };
    const technology = get('technology');
    return {
        repd_ref:     get(IDENTITY_PARAM),
        technology,
        latitude:     num('latitude'),
        longitude:    num('longitude'),
        zoom:         num('zoom'),
        layer_id:     technology === null ? null : layerIdForBucket(technology),
        layer_exists: technology === null ? false : bucketHasLayer(technology),
        known_bucket: technology !== null && BUCKETS.includes(technology)
    };
}