GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / globalgrid2050 / testcode/202609141754/grid-engine

GlobalGrid2050 — Testcode and 2 more files

A JavaScript module that draws blocks, families, names and entangled, using SHA-256, and uses data from raw.githubusercontent.com and the stars repository.

700 lines of JavaScript and HTML from globalgrid2050, in 3 files. Topic: Websites and apps. Section 1973 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. Testcode — Grid Engine Page render · globalgrid2050 / testcode/202609141754/grid-engine/index.html lines 1–254
  2. Amend Pack storage · globalgrid2050 / testcode/202609142202/amend_pack.mjs lines 1–64
  3. GlobalGrid2050 — Testcode render · globalgrid2050 / testcode/202609142225/core.js lines 1–382

Testcode — Grid Engine Page

A web page in GlobalGrid2050 that draws engine graph and uses data from Elexon Balancing Mechanism Reporting Service (BMRS) and the ventus-grid-engine and data-federation-map-for-GlobalGrid2050-all-repos repositories. Published at https://globalgrid2050.com/testcode/202609141754/grid-engine/.

renderglobalgrid2050 / testcode/202609141754/grid-engine/index.html · lines 1–254 of 254 · version 2026-09-14 17:54 · Entry point · pattern setHint (shared by 2 files)

What it does
It draws engine graph, genome spider and solar. Defines 20 functions or classes, including applyRootLinks, S, rebuildSelect, actionable, openUrl. 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 (path 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: solar.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: data-federation-map-for-globalgrid2050-all-repos data; data source: Elexon BMRS; JSON file nodes.json; JSON file edges.json; JSON file engine-graph.json; JSON file genome-spider.json; DuckDB queries. Out: web page; SVG drawing.
Downstream impact
It is itself an entry point, published at https://globalgrid2050.com/testcode/202609141754/grid-engine/.
What it achieves
It applies root links (`applyRootLinks`), rebuilds select (`rebuildSelect`) and opens URL (`openUrl`). Public copy of ventusltd.github.io (testcode ): same live data, plain public wording via `../corporate.js`. It responds to change and click events.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · testcode/202609141754/grid-engine · page
Uses
Federation Radial (stylesheet), Corporate (script src), Live Sandbox — Federation Control Ledger Page (estate URL)
Used by
none found
Produces
applyRootLinks, S, rebuildSelect, actionable, openUrl, handleTap, drillInto, popTo, neighbours, goLabel, setHint, distribute
Defines here
applyRootLinks, S, rebuildSelect, actionable, openUrl, handleTap, drillInto, popTo, neighbours, goLabel, setHint, distribute, reshapeNodes, loadJSON, loadRoot, placeholderScope, resolveRef, normaliseGenericGraph, loadManifestScope, wireReceiver
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609141754/grid-engine/index.html:1-254 · blob 3cc2cd8f02695b599df4c98681d14e3b7ec274ad · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: experimental · users: none · canonical: production_core
<!DOCTYPE html>
<html lang="en">
<!-- Public copy of https://ventusltd.github.io/ventus-grid-engine/ (testcode 202609141754): same live data, plain public wording via ../corporate.js. -->
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>GlobalGrid2050 · Grid Engine Sandbox</title>
<style>
  :root{
    --bg:#0b0d12;--panel:#12151c;--panel2:#151923;--line:#262b36;--text:#eef2fb;--muted:#9aa3b5;--cyan:#00e5ff;
    --e-data:#00e5ff;--e-governance:#b47cff;--e-archive:#7da0c8;--e-external:#5f76a4;--e-repo:#b8ccff;--e-workflow:#00ffff;
    --safe-x:clamp(12px,2.3vw,28px);--shell:1040px;--card:220px;--gap:14px;
  }
  *{box-sizing:border-box}
  html,body{margin:0;min-height:100%}
  body{background:radial-gradient(1200px 700px at 50% -10%,rgba(0,229,255,.06),transparent 60%),var(--bg);color:var(--text);font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;height:100dvh;overflow:hidden;display:flex;flex-direction:column}
  button,select{font:inherit}
  .top{border-bottom:1px solid var(--line);background:rgba(11,13,18,.92);backdrop-filter:blur(16px)}
  .bar,.controls,.crumbs,.hint{width:min(var(--shell),calc(100vw - var(--safe-x)*2));margin:0 auto}
  .bar{display:flex;align-items:center;gap:10px 14px;flex-wrap:wrap;padding:max(env(safe-area-inset-top),12px) 0 10px}
  .brand{display:flex;flex-direction:column;line-height:1.05;min-width:190px}
  .brand a.ey{text-decoration:none}
  .brand .ey{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.6rem;letter-spacing:.22em;text-transform:uppercase;color:var(--cyan)}
  .brand h1{margin:2px 0 0;font-size:1rem;font-weight:650}
  .pick{display:flex;align-items:center;gap:8px;flex:1 1 280px;min-width:0}
  .pick label,.grouplabel{font-family:ui-monospace,monospace;font-size:.58rem;letter-spacing:.16em;text-transform:uppercase;color:var(--muted);flex:none}
  select{flex:1 1 auto;min-width:0;background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:10px;padding:9px 32px 9px 12px;font-size:.85rem;cursor:pointer;appearance:none;background-image:linear-gradient(45deg,transparent 50%,var(--muted) 50%),linear-gradient(135deg,var(--muted) 50%,transparent 50%);background-position:calc(100% - 16px) center,calc(100% - 11px) center;b  … [line shortened here: 459 characters; full line on GitHub]
  select:focus-visible,button:focus-visible{outline:none;border-color:var(--cyan);box-shadow:0 0 0 2px rgba(0,229,255,.18)}
  .count{font-family:ui-monospace,monospace;font-size:.72rem;color:var(--muted);margin-left:auto;white-space:nowrap}
  .count b{color:var(--text);font-weight:600}
  .controls{display:flex;align-items:center;gap:8px 14px;flex-wrap:wrap;padding:8px 0 4px}
  .seg{display:inline-flex;border:1px solid var(--line);border-radius:999px;overflow:hidden;flex:none;background:rgba(18,21,28,.7)}
  .seg button{border:0;background:transparent;color:var(--muted);font-size:.72rem;padding:7px 13px;cursor:pointer;white-space:nowrap}
  .seg button[aria-pressed="true"]{background:rgba(0,229,255,.16);color:var(--text)}
  .seg button.gh[aria-pressed="true"]{background:rgba(184,204,255,.18)}
  .seg button.ext[aria-pressed="true"]{background:rgba(95,118,164,.28)}
  .seg button:disabled{opacity:.4;cursor:not-allowed}
  .viewbtn{border:1px solid rgba(255,255,255,.55);background:rgba(255,255,255,.08);color:#fff;border-radius:999px;padding:6px 12px;cursor:pointer;font-size:.86rem;line-height:1;display:inline-flex;align-items:center;gap:7px}
  .viewbtn[aria-pressed="true"]{border-color:var(--cyan);background:rgba(0,229,255,.16);box-shadow:0 0 22px rgba(0,229,255,.12)}
  .srctag{margin-left:auto;font-family:ui-monospace,monospace;font-size:.56rem;letter-spacing:.1em;text-transform:uppercase;color:var(--muted);border:1px solid var(--line);border-radius:999px;padding:2px 8px}
  .srctag.live{color:var(--cyan);border-color:rgba(0,229,255,.4)}
  .crumbs{display:flex;align-items:center;gap:6px;padding:2px 0 0;font-family:ui-monospace,monospace;font-size:.66rem;color:var(--muted);min-height:18px}
  .crumbs a{color:var(--cyan);cursor:pointer;text-decoration:none}
  .crumbs .sep{opacity:.5}
  .hint{padding:4px 0 8px;font-family:ui-monospace,monospace;font-size:.62rem;color:var(--muted)}
  .hint b{color:var(--text);font-weight:600}
  .stage{flex:1;min-height:0;position:relative;overflow:hidden}
  .overlay{position:absolute;inset:0}
  .overlay.column{overflow-y:auto;overflow-x:hidden;padding:16px var(--safe-x) max(env(safe-area-inset-bottom),22px)}
  .shell{width:min(var(--shell),100%);margin:0 auto;display:flex;flex-direction:column;gap:12px}
  .card{border:1px solid var(--line);border-radius:14px;background:linear-gradient(160deg,rgba(255,255,255,.055),rgba(255,255,255,.014));padding:10px 12px;display:flex;flex-direction:column;gap:6px;min-height:74px;box-shadow:0 16px 44px rgba(0,0,0,.12)}
  .card .row{display:flex;align-items:center;gap:7px}
  .badge{font-family:ui-monospace,monospace;font-size:.55rem;letter-spacing:.07em;border:1px solid var(--line);border-radius:6px;padding:2px 5px;color:var(--muted);flex:none}
  .name{font-size:.85rem;font-weight:650;line-height:1.15;overflow-wrap:anywhere}
  .dot{width:9px;height:9px;border-radius:50%;flex:none;margin-left:auto;box-shadow:0 0 8px currentColor}
  .reason{font-size:.68rem;color:var(--muted);line-height:1.25}
  .relrow{display:flex;align-items:center;gap:6px;flex-wrap:wrap}
  .reltag{font-family:ui-monospace,monospace;font-size:.55rem;letter-spacing:.05em;text-transform:uppercase;padding:1px 7px;border-radius:999px;border:1px solid currentColor}
  .arrow{font-family:ui-monospace,monospace;font-size:.62rem;color:var(--muted)}
  .go{font-family:ui-monospace,monospace;font-size:.6rem;color:var(--cyan);margin-left:auto}
  .is-center{border-color:var(--cyan);box-shadow:0 0 0 1px rgba(0,229,255,.22),0 0 26px rgba(0,229,255,.12)}
  .is-center .name{font-size:.95rem}
  .contents{align-self:flex-start;margin-top:3px;font-family:ui-monospace,monospace;font-size:.62rem;color:var(--cyan);border:1px solid rgba(0,229,255,.4);border-radius:999px;padding:4px 10px;background:rgba(0,229,255,.08);cursor:pointer}
  .inert{opacity:.34}
  .sect{font-family:ui-monospace,monospace;font-size:.6rem;letter-spacing:.14em;text-transform:uppercase;color:var(--muted);margin:16px 2px 4px}
  .branch{position:relative;padding-left:20px;display:flex;flex-direction:column;gap:9px}
  .branch::before{content:"";position:absolute;left:7px;top:-6px;bottom:14px;width:2px;background:var(--line)}
  .twig{position:relative;cursor:pointer}
  .twig::before{content:"";position:absolute;left:-13px;top:28px;width:13px;height:2px;background:var(--twig,var(--line))}
  .twig .card{border-left:3px solid var(--twig,var(--line))}
  .empty{color:var(--muted);font-size:.78rem;padding:6px 2px}
  .overlay.spider{overflow:auto;cursor:grab;background:radial-gradient(circle at center,rgba(0,229,255,.045),transparent 45%)}
  .overlay.spider.dragging{cursor:grabbing;user-select:none}
  .spiderCanvas{position:relative;min-width:100%;min-height:100%}
  .spiderGrid{position:absolute;inset:0;background-image:linear-gradient(rgba(255,255,255,.03) 1px, transparent 1px),linear-gradient(90deg,rgba(255,255,255,.03) 1px, transparent 1px);background-size:80px 80px;mask-image:radial-gradient(circle at center,black,transparent 78%);pointer-events:none}
  .wires{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible}
  .spoke{stroke-width:1.8;fill:none;opacity:.88}
  .place{position:absolute;transform:translate(-50%,-50%);width:var(--card);cursor:pointer}
  .place.center{width:250px;cursor:default}
  .legend{position:sticky;left:14px;bottom:10px;display:flex;flex-wrap:wrap;gap:5px 12px;width:max-content;max-width:70%;pointer-events:none;padding:4px 0 10px 14px}
  .legend span{display:flex;align-items:center;gap:6px;font-family:ui-monospace,monospace;font-size:.58rem;letter-spacing:.05em;text-transform:uppercase;color:var(--muted)}
  .legend i{width:15px;height:0;border-top:2px solid;display:inline-block}
  .maphint{position:sticky;top:12px;left:14px;width:max-content;max-width:min(560px,calc(100vw - 32px));font-family:ui-monospace,monospace;font-size:.62rem;color:var(--muted);background:rgba(18,21,28,.8);border:1px solid var(--line);border-radius:999px;padding:5px 10px;backdrop-filter:blur(10px);z-index:5}
  @media (max-width:680px){:root{--safe-x:14px}.brand{min-width:100%}.bar{gap:8px}.count{width:100%;margin-left:0}.controls{gap:7px 10px}.seg button{padding:7px 10px;font-size:.68rem}.viewbtn{padding:6px 10px}.srctag{margin-left:0}.shell{gap:10px}.card{border-radius:12px}.name{font-size:.82rem}}
</style>
<link rel="stylesheet" href="https://ventusltd.github.io/ventus-grid-engine/spider/federation_radial.css" />
<script src="../corporate.js"></script>
</head>
<body>
  <div class="top">
    <div class="bar">
      <div class="brand"><a class="ey" href="https://globalgrid2050.com/">GlobalGrid2050</a><h1>Grid Engine Sandbox</h1></div>
      <div class="pick"><label for="focus">Focus</label><select id="focus"></select></div>
      <div class="count" id="count"></div>
    </div>
    <div class="controls">
      <span class="grouplabel">Show</span>
      <div class="seg" id="relSeg" role="group" aria-label="Relationship direction">
        <button data-mode="both" aria-pressed="true">Both</button>
        <button data-mode="out" aria-pressed="false">Outgoing</button>
        <button data-mode="in" aria-pressed="false">Incoming</button>
      </div>
      <button class="viewbtn" id="spiderToggle" aria-pressed="false" title="Switch between the list view and the canvas view"><span id="viewLabel">Canvas</span></button>
      <span class="grouplabel">Tap does</span>
      <div class="seg" id="actSeg" role="group" aria-label="Tap action">
        <button data-act="explore" aria-pressed="true">Explore</button>
        <button class="gh" data-act="github" aria-pressed="false">GitHub</button>
        <button class="ext" data-act="external" aria-pressed="false">External</button>
        <button data-act="status" aria-pressed="false" disabled title="Enables when the page reads live scanner data">Status</button>
      </div>
      <span class="srctag" id="srcTag" title="Data source for this view">snapshot</span>
    </div>
    <div class="crumbs" id="crumbs"></div>
    <div class="hint" id="hint"></div>
  </div>
  <div class="stage" id="stage"><div class="overlay column" id="overlay"></div></div>
<script>
const GH_BASE="https://github.com/Ventusltd/data-federation-map-for-globalgrid2050-all-repos";
const LIVE_PAGE="https://ventusltd.github.io/data-federation-map-for-globalgrid2050-all-repos/live_sandbox/federation_control_ledger/";
const EXT_HOME={"DuckDB":"https://duckdb.org","Parquet":"https://parquet.apache.org","GitHub Actions":"https://github.com/features/actions","Elexon BMRS API":"https://bmrs.elexon.co.uk","GitHub Pages":"https://pages.github.com"};
const PAGE_HOME={"globalgrid2050":"https://globalgrid2050.com/","globalgrid2050-hompage":"https://globalgrid2050.com/","data-federation-map-for-globalgrid2050-all-repos":LIVE_PAGE};
const ROOT_NODES=[
  {label:"data-federation-map-for-globalgrid2050-all-repos",type:"data",rag:"green",reason:"active federation repository",child:"data-federation"},
  {label:"data-gb-electricity",type:"data",rag:"red",reason:"contract finding surfaced"},
  {label:"data-interconnectors",type:"data",rag:"red",reason:"contract finding surfaced"},
  {label:"gb-electricity-ui",type:"ui",rag:"red",reason:"depends on verified data repos"},
  {label:"globalgrid2050",type:"source_archive",rag:"blue",reason:"source archive"},
  {label:"globalgrid2050-hompage",type:"homepage",rag:"green",reason:"homepage dependency surfaced"},
  {label:"pandapower",type:"unknown",rag:"grey",reason:"not fully classified"},
  {label:"Podcast-transcripts",type:"unknown",rag:"amber",reason:"workflow finding"},
  {label:"pv-arc-protection-circuit",type:"unknown",rag:"amber",reason:"workflow finding"},
  {label:"Solar-PV-Hybrid-and-off-grid",type:"unknown",rag:"amber",reason:"workflow finding"},
  {label:"solar-repowering-whitepaper",type:"unknown",rag:"amber",reason:"workflow finding"},
  {label:"youengineer-code-review",type:"ui",rag:"amber",reason:"reference UI pattern source"},
  {label:"DuckDB",type:"external",rag:"blue",reason:"proof query engine"},
  {label:"Parquet",type:"external",rag:"blue",reason:"columnar proof store"},
  {label:"Elexon BMRS API",type:"external",rag:"blue",reason:"external electricity source"},
  {label:"GitHub Actions",type:"external",rag:"blue",reason:"static build runner"},
];
const ROOT_EDGES=[
  [0,12,"external"],[0,13,"external"],[0,5,"governance"],[0,15,"external"],[0,14,"external"],
  [1,4,"archive"],[1,5,"governance"],[1,14,"external"],[1,15,"external"],[1,12,"external"],[1,13,"external"],
  [2,4,"archive"],[2,5,"governance"],[2,14,"external"],[2,13,"external"],[2,1,"repo"],[2,3,"repo"],[2,15,"external"],[2,12,"external"],
  [3,1,"data"],[3,2,"data"],[3,5,"governance"],[3,15,"external"],
  [4,14,"external"],[4,15,"external"],
  [5,14,"external"],[5,0,"data"],[5,1,"data"],[5,2,"data"],[5,3,"repo"],[5,4,"archive"],[5,12,"external"],[5,13,"external"],[5,15,"external"],
  [6,15,"external"],
];
function applyRootLinks(nodes){nodes.forEach(n=>{n.gh=n.type==="external"?null:`https://github.com/Ventusltd/${n.label}`;n.ext=EXT_HOME[n.label]||PAGE_HOME[n.label]||null;});return nodes;}
applyRootLinks(ROOT_NODES);
const CHILD_NODES=[
  {label:"data-federation repo",type:"data",rag:"green",reason:"root of this child scope",gh:GH_BASE+"/tree/main"},
  {label:"live dashboard page",type:"ui",rag:"green",reason:"GitHub Pages browser UI in this repo",gh:GH_BASE+"/tree/main/live_sandbox/federation_control_ledger",ext:LIVE_PAGE},
  {label:"index.html",type:"ui",rag:"green",reason:"page shell for the board",gh:GH_BASE+"/blob/main/live_sandbox/federation_control_ledger/index.html"},
  {label:"app.js",type:"ui",rag:"green",reason:"board renderer and interaction logic",gh:GH_BASE+"/blob/main/live_sandbox/federation_control_ledger/app.js"},
  {label:"style.css",type:"ui",rag:"green",reason:"board visual system",gh:GH_BASE+"/blob/main/live_sandbox/federation_control_ledger/style.css"},
  {label:"data cartridge folder",type:"data",rag:"green",reason:"manifest, nodes, edges, layers, sectors",gh:GH_BASE+"/tree/main/live_sandbox/federation_control_ledger/data"},
  {label:"data/manifest.json",type:"data",rag:"amber",reason:"root cartridge manifest; key still flagged",gh:GH_BASE+"/blob/main/live_sandbox/federation_control_ledger/data/manifest.json"},
  {label:"data/nodes.json",type:"data",rag:"green",reason:"repo and source nodes for the board",gh:GH_BASE+"/blob/main/live_sandbox/federation_control_ledger/data/nodes.json"},
  {label:"data/edges.json",type:"data",rag:"green",reason:"relationship lines for the board",gh:GH_BASE+"/blob/main/live_sandbox/federation_control_ledger/data/edges.json"},
  {label:"reports folder",type:"unknown",rag:"green",reason:"scan reports and evidence",gh:GH_BASE+"/tree/main/reports"},
  {label:"FEDERATION_MAP_LATEST.md",type:"unknown",rag:"green",reason:"latest human-readable scan report",gh:GH_BASE+"/blob/main/reports/FEDERATION_MAP_LATEST.md"},
  {label:"governance documents",type:"unknown",rag:"green",reason:"governance notes and addenda",gh:GH_BASE+"/tree/main/every-drop-is-the-ocean"},
  {label:"GitHub Pages",type:"external",rag:"blue",reason:"static public hosting",ext:LIVE_PAGE},
  {label:"GitHub Actions",type:"external",rag:"blue",reason:"future scanner and validation runner",ext:EXT_HOME["GitHub Actions"],gh:GH_BASE+"/actions"},
];
const CHILD_EDGES=[[0,1,"repo"],[1,2,"repo"],[1,3,"repo"],[1,4,"repo"],[1,5,"data"],[3,5,"data"],[5,6,"data"],[5,7,"data"],[5,8,"data"],[0,9,"governance"],[9,10,"governance"],[0,11,"governance"],[1,12,"external"],[0,13,"external"],[3,13,"external"]];
const SCOPES={"root":{label:"Repositories",nodes:ROOT_NODES,edges:ROOT_EDGES},"data-federation":{label:"Data federation internals",nodes:CHILD_NODES,edges:CHILD_EDGES}};
const RAG={green:"#00ff88",amber:"#ffcc00",red:"#ff5555",blue:"#3aa0ff",grey:"#9298a6"};
const ECSS={data:"#00e5ff",governance:"#b47cff",archive:"#7da0c8",external:"#5f76a4",repo:"#b8ccff",workflow:"#00ffff"};
const BADGE={data:"DB",ui:"UI",homepage:"WEB",source_archive:"SRC",unknown:"REPO",external:"EXT"};
const REL={data:"data",governance:"governance",archive:"archive",external:"external",repo:"repo ref",workflow:"workflow"};
const SVGNS="http://www.w3.org/2000/svg";
let mode="both", action="explore", view="column", current=0, scopeKey="root", stack=[];
const sel=document.getElementById("focus"), overlay=document.getElementById("overlay"), elCount=document.getElementById("count"), elCrumbs=document.getElementById("crumbs"), elHint=document.getElementById("hint"), spiderToggle=document.getElementById("spiderToggle"), viewLabel=document.getElementById("viewLabel");
function S(){return SCOPES[scopeKey];}
function rebuildSelect(){sel.innerHTML="";S().nodes.forEach((n,i)=>{const o=document.createElement("option");o.value=i;o.textContent=Corporate.label(n.label,n.type);sel.appendChild(o);});sel.value=current;}
sel.addEventListener("change",()=>{current=+sel.value;draw();});
document.querySelectorAll("#relSeg button").forEach(b=>b.addEventListener("click",()=>{mode=b.dataset.mode;document.querySelectorAll("#relSeg button").forEach(x=>x.setAttribute("aria-pressed",String(x===b)));draw();}));
document.querySelectorAll("#actSeg button").forEach(b=>b.addEventListener("click",()=>{if(b.disabled)return;action=b.dataset.act;document.querySelectorAll("#actSeg button").forEach(x=>x.setAttribute("aria-pressed",String(x===b)));draw();}));
spiderToggle.addEventListener("click",()=>{view=view==="spider"?"column":"spider";spiderToggle.setAttribute("aria-pressed",String(view==="spider"));viewLabel.textContent=view==="spider"?"List":"Canvas";draw();});
let rt;new ResizeObserver(()=>{clearTimeout(rt);rt=setTimeout(draw,80);}).observe(document.getElementById("stage"));
function actionable(n){return action==="explore" ? true : action==="github" ? !!n.gh : action==="external" ? !!n.ext : false;}
function openUrl(u){u=Corporate.link(u);if(u)window.open(u,"_blank","noopener");}
function handleTap(i){const n=S().nodes[i];if(action==="explore"){current=i;sel.value=i;draw();}else if(action==="github"){openUrl(n.gh);}else if(action==="external"){openUrl(n.ext);}}
function drillInto(childKey){stack.push({key:scopeKey,current});scopeKey=childKey;current=0;mode="both";document.querySelectorAll("#relSeg button").forEach(x=>x.setAttribute("aria-pressed",String(x.dataset.mode==="both")));rebuildSelect();draw();}
function popTo(idx){const target=stack[idx];stack=stack.slice(0,idx);scopeKey=target.key;current=target.current;rebuildSelect();draw();}
function neighbours(idx){const out=[],inc=[];S().edges.forEach(([f,t,ty])=>{if(f===idx)out.push({other:t,type:ty});if(t===idx)inc.push({other:f,type:ty});});return {out,inc};}
function cardInner(node,opts={}){const center=opts.center, rel=opts.rel, dim=opts.dim;let relHTML="";if(rel){const c=ECSS[rel.type]||ECSS.repo;relHTML=`<div class="relrow"><span class="arrow">${rel.dir==="out"?"depends on →":"← depended on by"}</span><span class="reltag" style="color:${c}">${Corporate.type(REL[rel.type]||rel.type)}</span>${opts.go?`<span class="go">${opts.go}</span>`:""}</div>`;}l  … [line shortened here: 1,018 characters; full line on GitHub]
function goLabel(n){return action==="github"&&n.gh?"open ↗":action==="external"&&n.ext?"open ↗":"";}
function setHint(){const base={explore:"<b>Explore</b> — tap a card to re-centre on it.",github:"<b>GitHub</b> — tap a repo to open it. Cards with no repo are dimmed.",external:"<b>External</b> — tap an external system to open it. Others are dimmed."};elHint.innerHTML=(base[action]||"")+(view==="spider"?" &nbsp; <b>Canvas view</b> — scroll or drag to move around.":"");}
function setCrumbs(){elCrumbs.innerHTML="";const trail=[...stack.map((s,i)=>({label:SCOPES[s.key].label,idx:i})),{label:S().label,idx:-1}];trail.forEach((c,k)=>{if(k)elCrumbs.insertAdjacentHTML("beforeend",`<span class="sep">›</span>`);if(c.idx===-1){const s=document.createElement("strong");s.textContent=Corporate.text(c.label);s.style.color="var(--text)";elCrumbs.appendChild(s);}else{const a=docu  … [line shortened here: 536 characters; full line on GitHub]
function draw(){const nodes=S().nodes,focus=nodes[current];let {out,inc}=neighbours(current);let lo=mode==="in"?[]:out,li=mode==="out"?[]:inc;elCount.innerHTML=`<b>${out.length}</b> dependencies &nbsp;·&nbsp; <b>${inc.length}</b> dependents`;setHint();setCrumbs();overlay.innerHTML="";overlay.className="overlay "+view;if(view==="spider")drawSpider(focus,lo,li);else drawColumn(focus,lo,li);overlay.q  … [line shortened here: 523 characters; full line on GitHub]
function drawColumn(focus,out,inc){const nodes=S().nodes;const shell=document.createElement("div");shell.className="shell";shell.innerHTML=`<div class="focuswrap">${cardInner(focus,{center:true,dim:!actionable(focus),go:goLabel(focus)})}</div>`;const section=(title,items,dir)=>{const s=document.createElement("div");s.innerHTML=`<div class="sect">${title}</div>`;if(!items.length){const e=document.c  … [line shortened here: 1,162 characters; full line on GitHub]
function marker(defs,type){const m=document.createElementNS(SVGNS,"marker");m.id="arr-"+type;m.setAttribute("viewBox","0 0 10 10");m.setAttribute("refX","9");m.setAttribute("refY","5");m.setAttribute("markerWidth","8");m.setAttribute("markerHeight","8");m.setAttribute("orient","auto");const p=document.createElementNS(SVGNS,"path");p.setAttribute("d","M0,0 L10,5 L0,10 z");p.setAttribute("fill",ECSS  … [line shortened here: 457 characters; full line on GitHub]
function distribute(items,side,cx,cy,gap,xGap){const n=items.length;if(!n)return[];return items.map((it,k)=>{const y=cy+(k-(n-1)/2)*gap;const stagger=(n>5&&k%2?90:0);const x=cx+side*(xGap+stagger);return{...it,dir:side>0?"out":"in",x,y};});}
function drawSpider(focus,out,inc){const stage=document.getElementById("stage");const sw=stage.clientWidth,sh=stage.clientHeight;const maxSide=Math.max(out.length,inc.length,1);const gap=176;const xGap=Math.max(420,260+maxSide*38);const cw=Math.max(sw,Math.ceil(680+xGap*2+maxSide*120));const ch=Math.max(sh,Math.ceil(520+gap*(maxSide+1)));const cx=cw/2,cy=ch/2;const pts=[...distribute(out,1,cx,cy,g  … [line shortened here: 2,611 characters; full line on GitHub]
function enableDragPan(el){let down=false,captured=false,pid=null,sx=0,sy=0,sl=0,st=0;el.onpointerdown=e=>{if(e.target.closest("button,select"))return;down=true;captured=false;pid=e.pointerId;sx=e.clientX;sy=e.clientY;sl=el.scrollLeft;st=el.scrollTop;};el.onpointermove=e=>{if(!down)return;const dx=e.clientX-sx,dy=e.clientY-sy;if(!captured){if(Math.abs(dx)<6&&Math.abs(dy)<6)return;captured=true;el.  … [line shortened here: 683 characters; full line on GitHub]
const ORIGIN="https://ventusltd.github.io/ventus-grid-engine/";
const DATA_BASE=ORIGIN+"spider/data/";
const CHILD_KEY="data-federation";
function reshapeNodes(fc){return (fc.features||[]).map(f=>{const p=f.properties||{};const cm=p.child_manifest||null;return {label:p.label||f.id,type:p.repo_type||p.scope_type||"unknown",rag:p.rag||p.status||"grey",reason:p.status_reason||"",child:(cm&&/data-federation/.test(cm))?CHILD_KEY:null};});}
async function loadJSON(path){const r=await fetch(DATA_BASE+path,{cache:"no-cache"});if(!r.ok)throw new Error(path+" "+r.status);return r.json();}
async function loadRoot(){try{const [nf,ef]=await Promise.all([loadJSON("nodes.json"),loadJSON("edges.json")]);const nodes=reshapeNodes(nf);if(!nodes.length)throw new Error("empty");applyRootLinks(nodes);SCOPES.root.nodes=nodes;SCOPES.root.edges=(ef.edges||[]).map(e=>[e[0],e[1],e[2]]);return "live";}catch(e){return "snapshot";}}
const CONTENTS_BASE=ORIGIN+"spider/data/contents/";
const MONO_GH="https://github.com/Ventusltd/globalgrid2050";
const CONTENTS_KEY="globalgrid2050-contents";
async function loadContents(){try{const get=p=>fetch(CONTENTS_BASE+p,{cache:"no-cache"}).then(r=>{if(!r.ok)throw new Error(p+" "+r.status);return r.json();});const [mf,nf,ef]=await Promise.all([get("manifest.json"),get("nodes.json"),get("edges.json")]);if(!Array.isArray(nf)||!nf.length)throw new Error("empty nodes");BADGE.eye_app="APP";BADGE.sense_app="APP";BADGE.served_surface="PAGE";REL.contains  … [line shortened here: 1,113 characters; full line on GitHub]

const RECEIVER_MANIFEST_PATH=ORIGIN+"spider/manifest.json";
const MANIFEST_FALLBACK={graphs:[
  {id:"engine-graph",title:"Engine population",path:"./genome/engine-graph.json",source_spider:"genome-spider (population phase)",description:"The ventus-grid-engine population graph. Not owned by this page; may not exist yet."},
  {id:"genome-spider",title:"genome-spider output",path:"./spider/data/genome-spider.json",source_spider:"spiders/species/genome-spider",description:"Documented empty slot for spiders/species/genome-spider's own output, which did not exist when this receiver was built."}
]};
function placeholderScope(title,path){return {label:title,nodes:[{label:title+" — no data yet",type:"unknown",rag:"grey",reason:"Shown once its data is published."}],edges:[]};}
function resolveRef(ids,r){return ids[r]!==undefined?ids[r]:r;}
function normaliseGenericGraph(raw){
  const rawNodes=Array.isArray(raw.nodes)?raw.nodes:(Array.isArray(raw.features)?raw.features.map(f=>({id:f.id,...(f.properties||{})})):[]);
  const ids={};
  const nodes=rawNodes.map((n,i)=>{const id=n.id!==undefined?n.id:i;ids[id]=i;return {label:n.label||n.title||String(id),type:n.type||n.nodeKind||n.repo_type||"unknown",rag:n.rag||n.status||"grey",reason:n.reason||n.status_reason||n.path||"",gh:n.gh||null,ext:n.ext||null};});
  const rawEdges=Array.isArray(raw.edges)?raw.edges:(Array.isArray(raw.links)?raw.links:[]);
  const edges=rawEdges.map(e=>Array.isArray(e)?[resolveRef(ids,e[0]),resolveRef(ids,e[1]),e[2]||"repo"]:[resolveRef(ids,e.from!==undefined?e.from:e.source),resolveRef(ids,e.to!==undefined?e.to:e.target),e.type||"repo"]).filter(e=>typeof e[0]==="number"&&typeof e[1]==="number");
  return {nodes,edges};
}
async function loadManifestScope(entry){
  try{const r=await fetch(new URL(entry.path,ORIGIN),{cache:"no-cache"});if(!r.ok)throw new Error(entry.path+" "+r.status);const raw=await r.json();const g=normaliseGenericGraph(raw);if(!g.nodes.length)throw new Error("empty");return {label:Corporate.graphTitle(entry.id,entry.title),nodes:g.nodes,edges:g.edges,live:true};}
  catch(e){return {...placeholderScope(Corporate.graphTitle(entry.id,entry.title),entry.path),live:false};}
}
async function wireReceiver(){
  let manifest=MANIFEST_FALLBACK;
  try{const r=await fetch(RECEIVER_MANIFEST_PATH,{cache:"no-cache"});if(r.ok){const live=await r.json();if(Array.isArray(live.graphs)&&live.graphs.length)manifest=live;}}catch(e){}
  const BUILT_IN=new Set(["federation","globalgrid2050-contents"]);
  const extra=(manifest.graphs||[]).filter(g=>g&&g.id&&g.path&&!BUILT_IN.has(g.id));
  for(const entry of extra){
    const scope=await loadManifestScope(entry);
    SCOPES[entry.id]=scope;
    SCOPES.root.nodes.push({label:Corporate.graphTitle(entry.id,entry.title),origLabel:entry.title,type:"unknown",rag:scope.live?"green":"grey",reason:Corporate.graphDescription(entry.id,entry.description||""),child:entry.id,gh:null,ext:null});
  }
  const qp=new URLSearchParams(location.search);
  const want=Corporate.graphId(qp.get("graph"));
  if(want){const key=want==="federation"?"root":want;if(SCOPES[key]){stack=key==="root"?[]:[{key:"root",current:0}];scopeKey=key;current=0;}}
  const wantFocus=qp.get("focus");
  if(wantFocus){
    const ns=S().nodes;
    let i=ns.findIndex(n=>n.label===wantFocus||n.origLabel===wantFocus);
    if(i<0){const lc=wantFocus.toLowerCase();i=ns.findIndex(n=>String(n.label||"").toLowerCase()===lc);}
    if(i>=0)current=i;
  }
  rebuildSelect();draw();
}
(async()=>{const src=await loadRoot();await loadContents();const tag=document.getElementById("srcTag");if(tag){tag.textContent=src;tag.classList.toggle("live",src==="live");}await wireReceiver();})();
</script>
</body>
</html>

Amend Pack

A JavaScript module in the testcode folder of GlobalGrid2050 that fetches provenance and electron, using SHA-256. It fetches verified (`fetchVerified`) and is built from the sha256 step (`sha256`).

storageglobalgrid2050 / testcode/202609142202/amend_pack.mjs · lines 1–64 of 64 · version 2026-09-14 22:02 · Not reached from any entry point (candidate for review) · pattern fetchVerified (shared by 4 files)

What it does
It fetches provenance and electron. Defines sha256, fetchVerified. Uses libraries node:crypto, node:fs/promises, node:path, node:url. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path 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. README: "amended 2026-09-14T22:57:08Z by `amend_pack.mjs` (focus_default, conduction band, bucket size — see generation 1)."
Inputs & outputs
In: JSON file provenance.json; JSON file electron.json; JSON file index.json; JSON file graph.json. Out: JSON file electron.json; JSON file provenance.json.
What it achieves
Repair round 1: add to the pack three facts the page used to carry as code literals.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/202609142202 · JavaScript module
Uses
Build State (import), node:crypto, node:fs/promises, node:path, node:url
Used by
none found
Produces
sha256, fetchVerified
Defines here
sha256, fetchVerified
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609142202/amend_pack.mjs:1-64 · blob 0731f2f4f776b30f11d0d8b2f9161b4cc2a34eaa · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: experimental · users: none · canonical: unreached_review
// amend_pack.mjs — repair round 1: add to the pack three facts the page used to carry as code literals.
// Fetches ONLY code/index.json, electron/graph.json and ELECTRON.md (the same public URLs build_state.mjs used),
// verifies their sha256 against data/provenance.json → sources (so the sources are provably the bytes the pack was built from),
// then adds: electron.json.focus_default, electron.json.conduction_band_electron_md, provenance.checks.index_bucket_size,
// provenance.checks.index_buckets. Nothing else in data/ is touched. Run:  node amend_pack.mjs
import { createHash } from 'node:crypto';
import { readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseConductionBand } from './build_state.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const DATA = path.join(HERE, 'data');
const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');

const prov = JSON.parse(await readFile(path.join(DATA, 'provenance.json'), 'utf8'));
const electronBuf = await readFile(path.join(DATA, 'electron.json'));
const electron = JSON.parse(electronBuf.toString('utf8'));
const recorded = prov.outputs.find((o) => o.file === 'electron.json');
if (sha256(electronBuf) !== recorded.sha256) throw new Error(`data/electron.json on disk (${sha256(electronBuf)}) is not the pack's output (${recorded.sha256}); refusing to amend`);

async function fetchVerified(urlEnd) {
  const src = prov.sources.find((s) => s.url.endsWith(urlEnd));
  if (!src) throw new Error(`provenance.json has no source ending ${urlEnd}`);
  const res = await fetch(src.url, { headers: { 'user-agent': 'quantum-twin-star-amend/1 (node)' } });
  if (!res.ok) throw new Error(`HTTP ${res.status} for ${src.url}`);
  const buf = Buffer.from(await res.arrayBuffer());
  const h = sha256(buf);
  const same = h === src.sha256 && buf.length === src.bytes;
  console.log(`${src.url}\n  ${buf.length} bytes sha256 ${h} — ${same ? 'matches the pack build' : 'DIFFERS from the pack build (' + src.sha256 + ')'}`);
  if (!same) throw new Error(`live bytes of ${src.url} differ from the pack's fetch at ${src.fetched_utc}; re-run build_state.mjs instead of amending`);
  return { buf, src };
}

const [idx, graph, md] = await Promise.all([
  fetchVerified('/code/index.json'),
  fetchVerified('/electron/graph.json'),
  fetchVerified('/ELECTRON.md'),
]);
const index = JSON.parse(idx.buf.toString('utf8'));
const eGraph = JSON.parse(graph.buf.toString('utf8'));
const band = parseConductionBand(md.buf.toString('utf8'));

electron.focus_default = typeof eGraph.focus_default === 'string' ? eGraph.focus_default : null;
electron.conduction_band_electron_md = band;
prov.checks.index_bucket_size = Number.isInteger(index.bucket_size) ? index.bucket_size : null;
prov.checks.index_buckets = Array.isArray(index.buckets) ? index.buckets.slice() : null;

const electronOut = Buffer.from(JSON.stringify(electron));
recorded.bytes = electronOut.length; recorded.sha256 = sha256(electronOut);
const shippedBefore = prov.checks.shipped_bytes;
prov.checks.shipped_bytes = prov.outputs.reduce((s, o) => s + o.bytes, 0);
prov.amendments = (prov.amendments || []).concat([{
  utc: new Date().toISOString(), script: 'amend_pack.mjs',
  added: ['electron.json.focus_default', 'electron.json.conduction_band_electron_md', 'checks.index_bucket_size', 'checks.index_buckets'],
  sources_reverified: [idx.src.url, graph.src.url, md.src.url],
  electron_json_bytes_before: electronBuf.length, electron_json_bytes_after: electronOut.length,
  shipped_bytes_before: shippedBefore, shipped_bytes_after: prov.checks.shipped_bytes,
}]);
await writeFile(path.join(DATA, 'electron.json'), electronOut);
await writeFile(path.join(DATA, 'provenance.json'), Buffer.from(JSON.stringify(prov, null, 1)));
console.log(`electron.json: focus_default=${JSON.stringify(electron.focus_default)} conduction_band=${JSON.stringify(band)}`);
console.log(`provenance.checks: index_bucket_size=${prov.checks.index_bucket_size} index_buckets=${prov.checks.index_buckets.length} entries`);
console.log(`electron.json ${electronBuf.length} → ${electronOut.length} bytes, sha256 ${recorded.sha256}; shipped ${shippedBefore} → ${prov.checks.shipped_bytes} bytes`);

GlobalGrid2050 — Testcode

A JavaScript module that draws blocks, families, names and entangled, using SHA-256, and uses data from raw.githubusercontent.com and the stars repository.

renderglobalgrid2050 / testcode/202609142225/core.js · lines 1–382 of 382 · version 2026-09-14 22:25 · Entry point · pattern footerText (shared by 2 files)

What it does
It draws blocks, families, names and entangled. Defines 39 functions or classes, including $, esc, el, getJSON, fail. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path 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. README: "A read-only lab page: `index.html` + `style.css` + `core.js` + `gl.js` + `ui.js` + `lenses/*.js` (ES modules, WebGL2, no CDN, no framework, no build step)."
Inputs & outputs
In: data source: raw.githubusercontent.com; data source: stars data; JSON file blocks.json; JSON file families.json; JSON file index.json; JSON file names.json; JSON file random.json; JSON file entangled.json.
Downstream impact
Used directly by 12 files: Testcode — V01 Spider Drill Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141522/v01-spider-drill/); Testcode — V03 Particle Universe Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141522/v03-particle-universe/); Testcode — V04 Periodic Arrows Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141522/v04-periodic-arrows/); Testcode — V02 Radial Sunburst Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141522/v02-radial-sunburst/); and 8 more.
What it achieves
It gets JSON (`getJSON`), loads universe (`loadUniverse`) and loads names (`loadNames`). GlobalGrid2050 Star Generator — `core.js` (GRAMMAR §0, §1, §5). It responds to click events.
Why it matters
Loaded by the V01 Spider Drill page at https://globalgrid2050.com/testcode/202609141522/v01-spider-drill/ and 9 other pages. Also imported by Gl and UI.
Application
globalgrid2050 · testcode/202609142225 · JavaScript module
Uses
Stars — Index Page (estate URL)
Used by
loaded by Testcode — V01 Spider Drill Page (script src), loaded by Testcode — V03 Particle Universe Page (script src), loaded by Testcode — V04 Periodic Arrows Page (script src), loaded by Testcode — V02 Radial Sunburst Page (script src), loaded by Testcode — V05 Chord Dependencies Page (script src), loaded by Testcode — V06 Treemap Lines Page (script src), loaded by Testcode — V07 Flow Repos Page (script src), loaded by Testcode — V08 Ring Journey Page (script src), and 4 more
Produces
STARS, PACK, REL, REL_WORDS, KIND, PAL, CLS, CLS_WORD, CLS_KEY, LENSES, KIND_WORD, KIND_TEXT
Defines here
$, esc, el, getJSON, fail, fmt, stamp, shortUtc, loadUniverse, loadNames, catColour, catTitle, blockLabel, blockFamilies, blockDeps, blockUsers, buildEntities, put, addEdge, buildCSR, mk, scan, buildTier1Edges, family, familyLines, familyLinks, famName, loadPack, endpoint, countsLine
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/202609142225/core.js:1-382 · blob 7b95f0ab4afb84a6fe70ecffcda7efaef540ad17 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
/* GLOBALGRID2050 Star Generator — core.js (GRAMMAR §0, §1, §5).
 * Descends from testcode/202609141522/core.js and keeps its exported names.
 * Holds keys, never text: entity index (categories, repositories, blocks, groups, families), CSR edges per kind,
 * the numbered-line index from the pack, labels, the count sentence, the URL grammar, the trail, grid picking.
 * Tier 1 (before first paint): stars/blocks/blocks.json, stars/blocks/families.json, stars/code/index.json.
 * Tier 2 (after first paint): the packed state vector at ../202609142202/data/ by RELATIVE path.
 * Lazy forever: stars/code/f/<bucket>.json per family; source text from raw.githubusercontent.com.
 * Every number on screen comes from these files; missing data reads "not yet known".
 */
export const STARS = 'https://ventusltd.github.io/stars/';
export const PACK = '../202609142202/data/';
export const REL = { 'contains': '#8b93a7', 'depends on': '#ffd54a', 'uses': '#00e5ff', 'used by': '#ff7ab6', 'shared line': '#39d353', 'random link': '#8b93a7', 'entangled': '#b8ccff' };
export const REL_WORDS = Object.keys(REL);                    // legend order; kind index = position (3 = used by, a reading)
export const KIND = { 'contains': 0, 'depends on': 1, 'uses': 2, 'used by': 3, 'shared line': 4, 'random link': 5, 'entangled': 6, 'journey': 7 };
export const PAL = { body: '#0b0d12', text: '#d8dee9', accent: '#00e5ff', panel: '#0f1218', border: '#2a3140', chip: '#12151c', chipBorder: '#385464', code: '#07090d', key: '#ffd54a', muted: '#8b93a7', counts: '#7da0c8', footer: '#566079', busbar: '#eef2fb' };
export const CLS = { cat: 0, repo: 1, block: 2, group: 3, family: 4 };
export const CLS_WORD = ['category', 'repository', 'block', 'group', 'family'];
export const CLS_KEY = ['cat', 'repo', 'block', 'group', 'family'];
export const LENSES = ['ring', 'particle', 'chord', 'river', 'table', 'column'];
export const KIND_WORD = ['constant', 'engine', 'cartridge', 'layer', 'deeplink', 'app', 'tool', 'auto'];
export const KIND_TEXT = { constant: 'A constant: a value the whole estate must agree on.', engine: 'An engine: a calculation that answers a question.', cartridge: 'A cartridge: a plug-in part of the GridAtlas map.', layer: 'A layer: data drawn on the map.', deeplink: 'A deep link: how a link lands a reader on the right place.', app: 'An app: a page a reader can open and use.', tool: 'A tool: code  … [line shortened here: 543 characters; full line on GitHub]

export const U = { blocks: null, cats: [], groups: null, index: null, names: null, famToGroup: new Map(), famGroups: new Map(), buckets: new Map(), texts: new Map(), trail: [], pack: null, prov: null, random: null, entangled: null, packStats: null, packSha: null, edgesDrawnLitOnly: false };

export const $ = (s, r = document) => r.querySelector(s);
export const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
export function el(tag, attrs = {}, ...kids) {
  const e = document.createElement(tag);
  for (const [k, v] of Object.entries(attrs)) { if (k === 'on') for (const [ev, fn] of Object.entries(v)) e.addEventListener(ev, fn); else if (k === 'html') e.innerHTML = v; else if (v != null && v !== false) e.setAttribute(k, v); }
  for (const k of kids.flat()) if (k != null && k !== false) e.append(k.nodeType ? k : document.createTextNode(k));
  return e;
}
export async function getJSON(url) {
  const r = await fetch(url, { cache: 'default' });
  if (!r.ok) throw new Error(`${url} returned HTTP ${r.status}`);
  return r.json();
}
export function fail(where, err) {
  const box = $(where) || document.body;
  box.prepend(el('div', { class: 'u-fail' }, `Could not load live data: ${err.message}. Check the internet connection and reload.`));
}
export const fmt = n => Number(n).toLocaleString('en-GB');
export const stamp = iso => { const m = String(iso || '').match(/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)/); return m ? m.slice(1).join('') : ''; };
export const shortUtc = iso => { const m = String(iso || '').match(/^(\d{4}-\d\d-\d\d)T(\d\d:\d\d)/); return m ? `${m[1]} ${m[2]} UTC` : 'not yet known'; };

/* ================= tier 1 ================= */
export async function loadUniverse() {
  const [b, groups, index] = await Promise.all([getJSON(STARS + 'blocks/blocks.json'), getJSON(STARS + 'blocks/families.json'), getJSON(STARS + 'code/index.json')]);
  U.blocks = b.blocks; U.cats = b.categories; U.groups = groups; U.index = index; U.generated = b.generated_utc;
  U.bySym = new Map(U.blocks.map(x => [x.symbol, x]));
  U.famGroups = new Map();
  for (const [g, fams] of Object.entries(groups)) for (const n of fams) { if (!U.famGroups.has(n)) U.famGroups.set(n, []); U.famGroups.get(n).push(g); }
  for (const [n, gs] of U.famGroups) U.famToGroup.set(n, gs.find(g => U.bySym.has(g)) || gs[0]);
  U.catOf = new Map(U.cats.map(c => [c.id, c]));
  U.unnamed = Object.keys(groups).filter(g => !U.bySym.has(g));
  buildEntities();
  return U;
}
export async function loadNames() { if (!U.names) { U.names = await getJSON(STARS + 'code/names.json'); U.nameOf = new Map(); for (const [k, ns] of Object.entries(U.names)) for (const n of ns) if (!U.nameOf.has(n)) U.nameOf.set(n, k); } return U.names; }
export const catColour = id => (U.catOf.get(id) || {}).colour || PAL.muted;
export const catTitle = id => (U.catOf.get(id) || {}).title || id;
export function blockLabel(sym) { const b = U.bySym.get(sym); return b ? `${sym} · ${b.title}` : `${sym} · (not yet named)`; }
export function blockFamilies(sym) { return U.groups[sym] || []; }
export function blockDeps(sym) { const b = U.bySym.get(sym); return b ? (b.depends_on || []).map(d => d.symbol || d).filter(s => U.bySym.has(s) || U.groups[s]) : []; }
export function blockUsers(sym) { const b = U.bySym.get(sym); return b ? (b.used_by || []).filter(s => U.bySym.has(s) || U.groups[s]) : []; }

/* ================= entity index (§1.2) ================= */
export const core = {};                      // the object lenses receive; filled by buildEntities and the loaders
core.REL = REL; core.KIND = KIND; core.CLS = CLS; core.CLS_WORD = CLS_WORD; core.PAL = PAL; core.U = U;
core.GEOM = { muted: 12, rel: 13, shared: 13 + KIND['shared line'], busbar: 20 };   // geometry colour indexes into the gl.js palette (12 categories, muted, 7 legend colours, busbar)
function buildEntities() {
  const cats = U.cats, catIdx = new Map(cats.map((c, i) => [c.id, i]));
  const repos = [...new Set(U.blocks.flatMap(b => b.repos || []))].map(r => r.replace(/^Ventusltd\//, '')).sort();
  const blocks = [...U.blocks].sort((a, b) => ((catIdx.get(a.category) ?? 99) - (catIdx.get(b.category) ?? 99)) || (a.number - b.number));
  const groups = U.unnamed.slice().sort();
  const fams = [...new Set(Object.values(U.groups).flat())].sort((a, b) => a - b);
  const N = cats.length + repos.length + blocks.length + groups.length + fams.length;
  const range = {}; let at = 0;
  range.cat = [at, at += cats.length]; range.repo = [at, at += repos.length]; range.block = [at, at += blocks.length]; range.group = [at, at += groups.length]; range.family = [at, at += fams.length];
  const keyStr = new Array(N), cls = new Uint8Array(N), cat = new Uint8Array(N).fill(255), parent = new Int32Array(N).fill(-1), mass = new Float32Array(N), rec = new Array(N), byKey = new Map();
  const put = (i, key, c, ct, r) => { keyStr[i] = key; cls[i] = c; cat[i] = ct; rec[i] = r; byKey.set(key, i); };
  cats.forEach((c, i) => put(range.cat[0] + i, `cat:${c.id}`, 0, i, c));
  repos.forEach((r, i) => put(range.repo[0] + i, `repo:${r}`, 1, 255, r));
  blocks.forEach((b, i) => { const idx = range.block[0] + i; put(idx, `block:${b.symbol}`, 2, catIdx.get(b.category) ?? 255, b); parent[idx] = byKey.get(`cat:${b.category}`) ?? -1; });
  groups.forEach((g, i) => put(range.group[0] + i, `group:${g}`, 3, 255, g));
  fams.forEach((n, i) => { const idx = range.family[0] + i; put(idx, `family:${n}`, 4, 255, n); const g = U.famToGroup.get(n); const p = byKey.get(U.bySym.has(g) ? `block:${g}` : `group:${g}`); parent[idx] = p ?? -1; if (p != null) cat[idx] = cat[p]; });
  // families sorted so each container is a contiguous range of famOrder
  const famOrder = new Uint32Array(fams.length); for (let i = 0; i < fams.length; i++) famOrder[i] = range.family[0] + i;
  famOrder.sort((a, b) => (parent[a] - parent[b]) || (a - b));
  const famOff = new Int32Array(N).fill(-1), famCount = new Uint32Array(N);
  for (let i = 0; i < famOrder.length; i++) { const p = parent[famOrder[i]]; if (p < 0) continue; if (famOff[p] < 0) famOff[p] = i; famCount[p]++; }
  for (let i = range.family[0]; i < range.family[1]; i++) mass[i] = 1;
  for (let i = range.block[0]; i < range.group[1]; i++) mass[i] = famCount[i];
  for (let i = range.cat[0]; i < range.cat[1]; i++) mass[i] = blocks.filter(b => catIdx.get(b.category) === i).length;
  repos.forEach((r, i) => { mass[range.repo[0] + i] = U.blocks.filter(b => (b.repos || []).some(x => x.replace(/^Ventusltd\//, '') === r)).length; });
  Object.assign(core, { N, range, keyStr, cls, cat, parent, mass, rec, byKey, famOrder, famOff, famCount, catIdx, blocksOrdered: blocks, reposOrdered: repos, groupsOrdered: groups, famNum: fams });
  core.famName = new Array(N).fill(null); core.famKind = new Array(N).fill(null); core.famRec = new Array(N).fill(null);
  buildTier1Edges();
}
core.ordinal = idx => idx - core.range.block[0];   // block ordinal 0..209: category order then number
core.clsOf = idx => core.cls[idx];
core.isClass = (idx, c) => idx >= 0 && idx < core.N && core.cls[idx] === CLS[c];
core.familiesOf = idx => { const o = core.famOff[idx]; return o < 0 ? new Uint32Array(0) : core.famOrder.subarray(o, o + core.famCount[idx]); };

/* ================= edges (§1.3): CSR per kind, both directions, doubling buffer ================= */
const E = { a: new Uint32Array(4096), b: new Uint32Array(4096), kind: new Uint8Array(4096), w: new Float32Array(4096), n: 0, dirty: true, out: null, in: null, seen: new Set(), via: new Map() };
core.edges = E;
export function addEdge(a, b, kind, w = 1, via = null) {
  if (a < 0 || b < 0 || a === b) return -1;
  const sig = kind === 4 || kind === 5 ? `${Math.min(a, b)}:${Math.max(a, b)}:${kind}` : `${a}:${b}:${kind}`;
  if (E.seen.has(sig)) return -1; E.seen.add(sig);
  if (E.n === E.a.length) { const g = f => { const t = new f.constructor(f.length * 2); t.set(f); return t; }; E.a = g(E.a); E.b = g(E.b); E.kind = g(E.kind); E.w = g(E.w); }
  E.a[E.n] = a; E.b[E.n] = b; E.kind[E.n] = kind; E.w[E.n] = w; if (via) E.via.set(E.n, via); E.dirty = true; return E.n++;
}
function buildCSR() {
  const N = core.N, n = E.n;
  const mk = (src) => { const off = new Uint32Array(N + 1); for (let i = 0; i < n; i++) off[src[i] + 1]++; for (let i = 0; i < N; i++) off[i + 1] += off[i]; const idx = new Uint32Array(n), fill = off.slice(0, N); for (let i = 0; i < n; i++) idx[fill[src[i]]++] = i; return { off, idx }; };
  E.out = mk(E.a); E.in = mk(E.b); E.dirty = false;
}
/** neighbour indexes of idx over edges of `kind` (dir 'out' | 'in' | 'both'); kind -1 = any kind in mask */
core.edgesOf = function edgesOf(idx, kind, dir = 'out', mask = 0x7f) {
  if (E.dirty) buildCSR();
  const outl = [];
  const scan = (csr, other) => { for (let k = csr.off[idx]; k < csr.off[idx + 1]; k++) { const e = csr.idx[k]; if (kind >= 0 ? E.kind[e] !== kind : !((mask >> E.kind[e]) & 1)) continue; outl.push(other[e]); } };
  if (dir === 'out' || dir === 'both') scan(E.out, E.b);
  if (dir === 'in' || dir === 'both') scan(E.in, E.a);
  return Uint32Array.from(outl);
};
core.edgeIds = function edgeIds(idx, kind, dir = 'out') {
  if (E.dirty) buildCSR();
  const outl = []; const scan = csr => { for (let k = csr.off[idx]; k < csr.off[idx + 1]; k++) { const e = csr.idx[k]; if (kind < 0 || E.kind[e] === kind) outl.push(e); } };
  if (dir === 'out' || dir === 'both') scan(E.out); if (dir === 'in' || dir === 'both') scan(E.in); return outl;
};
function buildTier1Edges() {
  const { byKey, range, parent } = core;
  for (let i = range.block[0]; i < range.group[1]; i++) { if (parent[i] >= 0) addEdge(parent[i], i, 0); for (const f of core.familiesOf(i)) addEdge(i, f, 0); }
  for (const b of U.blocks) { const bi = byKey.get(`block:${b.symbol}`); for (const r of b.repos || []) addEdge(byKey.get(`repo:${r.replace(/^Ventusltd\//, '')}`) ?? -1, bi, 0); }
  let dep = 0;
  for (const b of U.blocks) { const bi = byKey.get(`block:${b.symbol}`); for (const d of b.depends_on || []) { const t = byKey.get(`block:${d.symbol}`) ?? byKey.get(`group:${d.symbol}`) ?? -1; if (addEdge(bi, t, 1, 1, d.via && d.via.length ? d.via : null) >= 0) dep++; } }
  core.dependsOnCount = dep;
}
core.viaOf = (a, b) => { for (const e of core.edgeIds(a, 1, 'out')) if (E.b[e] === b) return E.via.get(e) || null; return null; };

/* ================= families: buckets (lazy forever) ================= */
export async function family(n) {
  const b = Math.floor(n / (U.index.bucket_size || 500));
  if (!U.buckets.has(b)) U.buckets.set(b, getJSON(`${STARS}code/f/${b}.json`));
  const bucket = await U.buckets.get(b);
  const rec = bucket[String(n)] || null;
  const idx = core.byKey.get(`family:${n}`);
  if (rec && idx != null) { core.famRec[idx] = rec; if (!core.famName[idx] && rec.names && rec.names[0]) core.famName[idx] = rec.names[0]; if (!core.famKind[idx]) core.famKind[idx] = rec.kind || null; }
  return rec;
}
export async function familyLines(rec) {
  const p = (rec.places || [])[0];
  if (!p) return rec.lines.map(k => ({ key: k, text: '(source not yet known: no place recorded)' }));
  const id = `${p.repo}@${p.commit}:${p.path}`;
  if (!U.texts.has(id)) U.texts.set(id, fetch(`https://raw.githubusercontent.com/${p.repo}/${p.commit}/${p.path.split('/').map(encodeURIComponent).join('/')}`).then(r => { if (!r.ok) throw new Error(`GitHub returned HTTP ${r.status}`); return r.text(); }).then(t => t.split('\n')));
  const all = await U.texts.get(id);
  const src = all.slice(p.first - 1, p.last);
  return rec.lines.map((k, i) => ({ key: k, text: src[i] ?? '' }));
}
export function familyLinks(rec, n) {
  const p = (rec.places || [])[0];
  return { page: `${STARS}code.html?family=${n}`, gh: p ? `https://github.com/${p.repo}/blob/${p.commit}/${p.path}#L${p.first}-L${p.last}` : null, live: (rec.places || []).map(x => x.live).find(Boolean) || null };
}
export const famName = rec => (rec && rec.names && rec.names[0]) || '(name not yet known)';
/** kind 2 edges from the focus family's bucket record, appended once per family (§1.3) */
const famEdgesDone = new Set();
core.loadFamilyEdges = async function (idx) {
  if (!core.isClass(idx, 'family') || famEdgesDone.has(idx)) return core.famRec[idx];
  const rec = await family(core.rec[idx]); famEdgesDone.add(idx); if (!rec) return null;
  for (const u of rec.uses || []) { const t = core.byKey.get(`family:${u.family}`); if (t != null) addEdge(idx, t, 2); }
  for (const u of rec.used_by || []) { const s = core.byKey.get(`family:${u.family}`); if (s != null) addEdge(s, idx, 2); }
  return rec;
};

/* ================= tier 2: the pack (§1.1, §1.2 lines) ================= */
let packPromise = null;
export function loadPack() {
  if (packPromise) return packPromise;
  packPromise = (async () => {
    const [fams, bin, random, entangled, prov] = await Promise.all([getJSON(PACK + 'families.json'), fetch(PACK + 'lines.bin', { cache: 'default' }).then(r => { if (!r.ok) throw new Error(`${PACK}lines.bin returned HTTP ${r.status}`); return r.arrayBuffer(); }), getJSON(PACK + 'random.json'), getJSON(PACK + 'entangled.json'), getJSON(PACK + 'provenance.json')]);
    U.pack = fams; U.random = random; U.entangled = entangled; U.prov = prov; U.packBytes = bin;
    U.packSha = ((prov.outputs || []).find(o => o.file === 'lines.bin') || {}).sha256 || null;
    const { byKey, range } = core;
    const lineKey = new Uint32Array(bin), M = lineKey.length, lineFam = new Uint32Array(M).fill(0xffffffff);
    let orphans = 0, maxKey = 0; const nameToFam = new Map();
    core.famPack = new Array(core.N).fill(null);
    for (const f of fams) {
      const idx = byKey.get(`family:${f.n}`);
      if (idx == null) { orphans++; continue; }
      core.famPack[idx] = f; core.famName[idx] = f.name && f.name !== '(anonymous)' ? f.name : core.famName[idx]; core.famKind[idx] = f.kind || core.famKind[idx]; core.mass[idx] = Math.max(1, f.lineCount || 0);
      if (f.name && !nameToFam.has(f.name)) nameToFam.set(f.name, idx);
      lineFam.fill(idx, f.lineOffset, f.lineOffset + f.lineCount);
    }
    for (let i = 0; i < M; i++) if (lineKey[i] > maxKey) maxKey = lineKey[i];
    // counting sort by key → lineOrder; distinct keys → lineIndex with lineFirst offsets
    const count = new Uint32Array(maxKey + 2); for (let i = 0; i < M; i++) count[lineKey[i] + 1]++;
    for (let k = 0; k <= maxKey; k++) count[k + 1] += count[k];
    const lineOrder = new Uint32Array(M), fill = count.slice(0, maxKey + 1); for (let i = 0; i < M; i++) lineOrder[fill[lineKey[i]]++] = i;
    let distinct = 0; for (let k = 0; k <= maxKey; k++) if (count[k + 1] > count[k]) distinct++;
    const lineIndex = new Uint32Array(distinct), lineFirst = new Uint32Array(distinct + 1); let d = 0;
    for (let k = 0; k <= maxKey; k++) if (count[k + 1] > count[k]) { lineIndex[d] = k; lineFirst[d] = count[k]; d++; } lineFirst[distinct] = M;
    const lineShared = new Uint8Array(M); for (let j = 0; j < distinct; j++) { const a = lineFirst[j], b = lineFirst[j + 1]; if (b - a > 1) { const fs = new Set(); for (let q = a; q < b; q++) fs.add(lineFam[lineOrder[q]]); if (fs.size > 1) for (let q = a; q < b; q++) lineShared[lineOrder[q]] = 1; } }
    Object.assign(core, { lineKey, lineFam, lineOrder, lineIndex, lineFirst, lineShared, nameToFam });
    core.packStats = U.packStats = { instances: M, distinct, unique: U.index.lines, orphans, built: prov.built_utc, sha: U.packSha };
    // kind 5 random link (family ↔ family, joined by name: random.json numbers states, not families — see GRAMMAR deviations)
    const endpoint = s => { let m = String(s).match(/^#\d+ (.+)$/); if (m) { const nm = m[1].split('/').pop(); return nameToFam.has(nm) ? nameToFam.get(nm) : -1; } return -1; };
    let rDrawn = 0; for (const e of random.edges || []) { const a = endpoint(e.from), b = endpoint(e.to); if (a >= 0 && b >= 0 && addEdge(a, b, 5, typeof e.p === 'number' ? e.p : 0.25) >= 0) rDrawn++; }
    core.randomStats = { edges: (random.edges || []).length, drawn: rDrawn, seed: ((random.sources || [])[0] || {}).seed || null };
    // kind 6 entangled (family → repository, joined by name)
    let eDrawn = 0, eJoined = 0; const reg = entangled.soul_md || {};   // the state register of the star-maker, read from the file it is stored in (the field name is left as the pack writes it)
    for (const x of entangled.entanglements || []) { const f = nameToFam.get(x.name); if (f == null) continue; eJoined++; for (const r of x.called_from || []) { const ri = byKey.get(`repo:${r}`); if (ri != null && addEdge(f, ri, 6) >= 0) eDrawn++; } }
    core.entangledStats = { stated: reg.entanglements_stated ?? null, listed: (entangled.entanglements || []).length, joined: eJoined, drawn: eDrawn };
    return core.packStats;
  })();
  return packPromise;
}
core.packLoaded = () => !!U.pack;
/** families carrying line number n → Uint32Array of family idx (distinct, in pack order); null before tier 2 */
core.familiesOfLine = function (n) {
  if (!core.lineIndex) return null;
  const L = core.lineIndex; let lo = 0, hi = L.length - 1;
  while (lo <= hi) { const m = (lo + hi) >> 1; if (L[m] < n) lo = m + 1; else if (L[m] > n) hi = m - 1; else { const s = new Set(); for (let q = core.lineFirst[m]; q < core.lineFirst[m + 1]; q++) { const f = core.lineFam[core.lineOrder[q]]; if (f !== 0xffffffff) s.add(f); } return Uint32Array.from(s); } }
  return new Uint32Array(0);
};
/** kind 4 shared line for one family over the whole pack, ≤ 8 partners per line key, w = shared count; cached */
const sharedDone = new Map();
core.sharedOf = function (idx) {
  if (sharedDone.has(idx)) return sharedDone.get(idx);
  const f = core.famPack && core.famPack[idx]; const acc = new Map();
  if (f) for (let i = f.lineOffset; i < f.lineOffset + f.lineCount; i++) { const fs = core.familiesOfLine(core.lineKey[i]); let k = 0; for (const g of fs) { if (g === idx) continue; if (k++ >= 8) break; acc.set(g, (acc.get(g) || 0) + 1); } }
  const out = [...acc.entries()].sort((a, b) => b[1] - a[1]).map(([g, w]) => { addEdge(idx, g, 4, w); return { idx: g, w }; });
  sharedDone.set(idx, out); return out;
};
/** shared partners among loaded bucket records only (before tier 2), as core.js did */
core.sharedLoaded = async function (n, lines) {
  const keys = new Set(lines), shared = new Map();
  for (const p of U.buckets.values()) { const bucket = await p.catch(() => ({})); for (const [m, r] of Object.entries(bucket)) { if (+m === n) continue; const hit = (r.lines || []).filter(k => keys.has(k)).length; if (hit) shared.set(+m, hit); } }
  return [...shared.entries()].map(([m, w]) => ({ idx: core.byKey.get(`family:${m}`), n: m, w })).filter(x => x.idx != null);
};

/* ================= labels, keys, counts (§0) ================= */
core.label = function label(idx) {
  if (idx < 0 || idx >= core.N) return 'not yet known';
  const r = core.rec[idx];
  switch (core.cls[idx]) {
    case 0: return r.title;
    case 1: return r;
    case 2: return `${r.symbol} · ${r.title}`;
    case 3: return `${r} · (not yet named)`;
    default: { const nm = core.famName[idx] || (U.nameOf && U.nameOf.get(r)); return nm ? `#${r} ${nm}` : (U.pack ? `#${r} (name not yet known)` : `#${r}`); }
  }
};
core.labelKey = function (key) {
  const m = /^line:(\d+)$/.exec(key);
  if (m) { const fs = core.familiesOfLine(+m[1]); return `line ${fmt(m[1])} · ${fs === null ? '(line index still loading)' : fs.length ? core.label(fs[0]) : '(families not yet known)'}`; }
  const i = core.resolve(key); return i >= 0 ? core.label(i) : `Key ${key} is not in the published records.`;
};
core.short = idx => core.cls[idx] === 2 || core.cls[idx] === 3 ? core.rec[idx].symbol || core.rec[idx] : core.cls[idx] === 4 ? `#${core.rec[idx]}` : core.label(idx);
core.colour = idx => { const c = core.cat[idx]; return c < U.cats.length ? U.cats[c].colour || PAL.muted : PAL.muted; };
/** A line key names a line, not a family. NAVIGATE (§4) focuses its first family; COMPOSE must not guess (repair round, major 1):
 *  lineChoice holds the family a person picked for a line carried by several; composeEntity() returns -1 until they do. */
core.lineChoice = new Map();
core.resolveLine = function (n) { const fs = core.familiesOfLine(n); if (fs === null) return { fams: null, idx: -1, chosen: false }; if (fs.length === 1) return { fams: fs, idx: fs[0], chosen: false }; const c = core.lineChoice.get(n); return { fams: fs, idx: c != null && fs.includes(c) ? c : -1, chosen: c != null && fs.includes(c) }; };
core.composeEntity = function (key) { const m = /^line:(\d+)$/.exec(String(key).trim()); if (m) return core.resolveLine(+m[1]).idx; return core.resolve(key); };
core.resolve = function resolve(str) {
  if (typeof str !== 'string') return -1;
  const s = str.trim();
  if (core.byKey.has(s)) return core.byKey.get(s);
  let m;
  if ((m = /^line:(\d+)$/.exec(s))) { const r = core.resolveLine(+m[1]); if (r.idx >= 0) return r.idx; const fs = r.fams; return fs && fs.length ? fs[0] : -1; }
  if ((m = /^#?(\d+)$/.exec(s))) return core.byKey.get(`family:${m[1]}`) ?? -1;
  if (/^[A-Z][a-z]?$/.test(s)) return core.byKey.get(`block:${s}`) ?? -1;
  if (/^x\d+$/.test(s)) return core.byKey.get(`group:${s}`) ?? -1;
  return -1;
};
core.countsLine = function countsLine() {
  const named = U.blocks.filter(b => b.kind !== 'auto').length, auto = U.blocks.filter(b => b.kind === 'auto').length;
  return `${fmt(U.blocks.length)} blocks on the table (${fmt(named)} named · ${fmt(auto)} found automatically) · ${fmt(U.unnamed.length)} groups off the table · ${fmt(U.index.families)} function families · ${fmt(U.index.lines)} unique numbered lines · ${fmt(core.reposOrdered.length)} repositories · data ${shortUtc(U.generated)}`;
};
core.countsTitle = () => U.packStats ? `${fmt(U.packStats.unique)} per code/index.json · ${fmt(U.packStats.instances)} line instances · ${fmt(U.packStats.distinct)} distinct numbers in this pack` : null;
export const countsLine = () => core.countsLine();
core.kindSentence = b => KIND_TEXT[b.kind] || 'not yet known';

/* ================= paging ================= */
export function pageList(host, items, render, step = 40, label = 'more') {
  let shown = 0; const more = el('button', { class: 'u-chip u-more' });
  const fill = () => { const next = items.slice(shown, shown + step); next.forEach(it => host.insertBefore(render(it), more)); shown += next.length; if (shown >= items.length) more.remove(); else more.textContent = `show ${Math.min(step, items.length - shown)} ${label} (${items.length - shown} left)`; };
  host.append(more); more.addEventListener('click', fill); fill();
  return host;
}

/* ================= state, trail, URL grammar (§1.4, §4, §5) ================= */
export const state = { lens: 'ring', focus: -1, measure: -1, trail: [], recipe: [], kindsOn: 0x7f, cat: -1 };
core.state = state;
export function trailPush(idx) { const t = state.trail; if (t.length && t[t.length - 1] === idx) return; t.push(idx); U.trail = t; }
export function trailVisits(idx) { return state.trail.filter(x => x === idx).length; }
const EDGE_INITIALS = 'cdubsre';
export function writeQuery(st = state) {
  const p = [];
  p.push(`lens=${st.lens}`);
  if (st.focus >= 0) p.push(`key=${st.focusKey || core.keyStr[st.focus]}`);
  if (st.trail.length) p.push(`trail=${st.trail.slice(-12).map(i => core.keyStr[i]).join(',')}`);
  if (st.recipe.length) p.push(`recipe=${st.recipe.slice(0, 24).map(k => typeof k === 'string' ? k : core.keyStr[k]).join(',')}`);
  if (st.measure >= 0 && st.measure !== st.focus) p.push(`m=${st.measureKey || core.keyStr[st.measure]}`);
  if (st.kindsOn !== 0x7f) p.push(`edges=${[...EDGE_INITIALS].filter((c, i) => (st.kindsOn >> i) & 1).join('')}`);
  if (st.cat >= 0) p.push(`cat=${U.cats[st.cat].id}`);
  p.push(`data=${stamp(U.generated)}`);
  return '?' + p.join('&');
}
/** parse the query (and the inbound grammars of the other pages) once on load; returns a partial state + notes */
export function readQuery(search = location.search, hash = location.hash) {
  const q = new URLSearchParams(search), out = { notes: [] }, h = new URLSearchParams(hash.replace(/^#/, ''));
  let key = q.get('key');
  if (!key && h.get('family')) key = `family:${h.get('family')}`;
  if (!key && h.get('block')) key = `block:${h.get('block')}`;
  if (!key && q.get('block')) { key = `block:${q.get('block')}`; out.lens = 'table'; }
  if (!key && q.get('family')) { key = `family:${q.get('family')}`; out.lens = 'column'; }
  if (!key && q.get('graph') === 'periodic-table' && q.get('focus')) {
    const f = q.get('focus'), sym = f.split(' · ')[0].trim(); out.lens = 'column';
    let b = U.bySym.get(sym) || U.blocks.find(x => x.title === f) || U.blocks.find(x => x.title.toLowerCase() === f.toLowerCase());
    if (b) key = `block:${b.symbol}`; else out.notes.push('key not yet known');
  }
  if (q.get('blocks') && !q.get('recipe')) { out.lens = out.lens || 'table'; out.recipe = q.get('blocks').split(',').filter(Boolean).map(s => `block:${s.trim()}`); }
  if (q.get('lens') && LENSES.includes(q.get('lens'))) out.lens = q.get('lens');
  if (key) out.key = key;
  if (q.get('trail')) out.trail = q.get('trail').split(',').filter(Boolean);
  if (q.get('recipe')) out.recipe = q.get('recipe').split(',').filter(Boolean);
  if (q.get('m')) out.m = q.get('m');
  if (q.get('edges') != null) { let mask = 0; for (const c of q.get('edges')) { const i = EDGE_INITIALS.indexOf(c); if (i >= 0) mask |= 1 << i; } out.kindsOn = mask; }
  if (q.get('cat')) out.cat = q.get('cat');
  if (q.get('data')) { out.data = q.get('data'); if (out.data < stamp(U.generated)) out.notes.push(`link made against data of ${out.data.replace(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)$/, '$1-$2-$3 $4:$5 UTC')}`); }
  return out;
}

/* ================= picking: CPU uniform grid 32×32 over target positions (§1.5) ================= */
export function buildGrid(pos, N) {
  let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
  for (let i = 0; i < N; i++) { const x = pos[2 * i], y = pos[2 * i + 1]; if (x !== x) continue; if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }
  if (!isFinite(x0)) return { empty: true, cells: [], x0: 0, y0: 0, cw: 1, ch: 1 };
  const cw = (x1 - x0) / 32 || 1, ch = (y1 - y0) / 32 || 1, cells = Array.from({ length: 1024 }, () => []);
  for (let i = 0; i < N; i++) { const x = pos[2 * i], y = pos[2 * i + 1]; if (x !== x) continue; const cx = Math.min(31, ((x - x0) / cw) | 0), cy = Math.min(31, ((y - y0) / ch) | 0); cells[cy * 32 + cx].push(i); }
  return { empty: false, cells, x0, y0, cw, ch, pos, N };
}
/** nearest entity within r (layout units) of (x,y); returns { idx, d, second, d2 } — the shell decides ambiguity */
export function pick(grid, x, y, r, prefer = null) {
  if (grid.empty) return { idx: -1, d: Infinity, second: -1, d2: Infinity };
  const { cells, x0, y0, cw, ch, pos } = grid; let best = -1, bd = Infinity, sec = -1, sd = Infinity;
  const cx0 = Math.max(0, ((x - r - x0) / cw) | 0), cx1 = Math.min(31, ((x + r - x0) / cw) | 0), cy0 = Math.max(0, ((y - r - y0) / ch) | 0), cy1 = Math.min(31, ((y + r - y0) / ch) | 0);
  for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) for (const i of cells[cy * 32 + cx]) {
    let px = pos[2 * i], py = pos[2 * i + 1]; if (prefer) { const o = prefer(i); if (o) { px += o[0]; py += o[1]; } }
    const d = Math.hypot(px - x, py - y); if (d > r) continue;
    if (d < bd) { sec = best; sd = bd; best = i; bd = d; } else if (d < sd) { sec = i; sd = d; }
  }
  return { idx: best, d: bd, second: sec, d2: sd };
}

/* ================= search resolver (§3.2) ================= */
core.search = function (q) {
  q = q.trim(); const hits = []; let m;
  if (!q) return hits;
  if ((m = /^#?(\d+)$/.exec(q))) { const n = +m[1]; const fi = core.byKey.get(`family:${n}`); if (fi != null) hits.push({ key: `family:${n}`, label: core.label(fi) }); const fs = core.familiesOfLine(n); if (fs === null && !q.startsWith('#')) hits.push({ note: 'line index still loading' }); else if (fs && fs.length) hits.push({ key: `line:${n}`, label: core.labelKey(`line:${n}`) }); if (!hits.lengt  … [line shortened here: 483 characters; full line on GitHub]
  if ((m = /^(?:L|line )(\d+)$/i.exec(q))) { const n = +m[1], fs = core.familiesOfLine(n); if (fs === null) hits.push({ note: 'line index still loading' }); else if (fs.length) hits.push({ key: `line:${n}`, label: core.labelKey(`line:${n}`) }); else hits.push({ note: `Key line:${n} is not in the published records.` }); return hits; }
  if (/^[A-Z][a-z]$/.test(q) && core.byKey.has(`block:${q}`)) return [{ key: `block:${q}`, label: core.label(core.byKey.get(`block:${q}`)) }];
  if (/^x\d+$/.test(q) && core.byKey.has(`group:${q}`)) return [{ key: `group:${q}`, label: core.label(core.byKey.get(`group:${q}`)) }];
  if (q.length < 2) return hits;
  if (!U.names) return [{ note: 'names still loading' }];
  const lq = q.toLowerCase(); const found = Object.keys(U.names).filter(k => k.toLowerCase().includes(lq)).sort((a, b) => a.length - b.length).slice(0, 12);
  for (const k of found) for (const n of U.names[k].slice(0, 3)) if (core.byKey.has(`family:${n}`)) hits.push({ key: `family:${n}`, label: `#${n} ${k}` });
  if (!hits.length) hits.push({ note: 'No function name contains that text.' });
  return hits;
};

export function footerText(id, lens) {
  let s = `${id} · built ${window.BUILT || ''} UTC · live data: ${STARS}blocks/, ${STARS}code/, raw.githubusercontent.com · GLOBALGRID2050`;
  if (lens) s += ` · lens ${lens.id} from ${lens.from}`;
  if (U.packStats) s += ` · pack ${shortUtc(U.packStats.built)} sha256 ${(U.packStats.sha || '').slice(0, 7)}`;
  return s;
}
export { core as default };