GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / globalgrid2050 / kuiper-grid/drawing

Kuiper Programs and 4 more files

A JavaScript file in the cartridges folder of GlobalGrid2050 that makes body (`makeBody`), sets tag (`setTag`), makes app buttons (`makeAppButtons`) and calculates planar distances.

580 lines of JavaScript and HTML from globalgrid2050, in 5 files. Topic: Kuiper, cosmos and drawing engines. Section 1239 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. Renderer render · globalgrid2050 / kuiper-grid/drawing/renderer.html lines 701–829
  2. Site Scale interaction · globalgrid2050 / kuiper-grid/drawing/site-scale.js lines 1–164
  3. View Mode render · globalgrid2050 / kuiper-grid/drawing/view-mode.js lines 1–29
  4. Kuiper Chrome interaction · globalgrid2050 / kuiper-grid/i0073/cartridges/003200000000-kuiper-chrome.js lines 1–35
  5. Kuiper Programs interaction · globalgrid2050 / kuiper-grid/i0073/cartridges/003300000000-kuiper-programs.js lines 1–223

Renderer

A web page in the drawing folder of GlobalGrid2050 that draws programs. Published at https://globalgrid2050.com/kuiper-grid/drawing/renderer.html. It builds link (`buildLink`) and parses link (`parseLink`).

renderglobalgrid2050 / kuiper-grid/drawing/renderer.html · lines 701–829 of 829 (continued from section 1238) · Entry point · pattern frameOnce (shared by 6 files)

What it does
It draws programs. Defines 34 functions or classes, including buildLink, complaints, parseLink, fmt, day. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file programs.json; form fields (user input). Out: web page; WebGL/WebGPU drawing.
Downstream impact
Used directly by 1 file: Kuiper Grid — Drawing Page (globalgrid2050, https://globalgrid2050.com/kuiper-grid/drawing/). Reached from 109 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/). It is itself an entry point, published at https://globalgrid2050.com/kuiper-grid/drawing/renderer.html.
What it achieves
Its `describe` function gives human readable address description from resolved address and repository metadata (VEDIC: explain). It reads `cosmos/programs.json`. It responds to error, webglcontextlost and resize events.
Why it matters
Loaded by the Drawing page at https://globalgrid2050.com/kuiper-grid/drawing/.
Application
globalgrid2050 · kuiper-grid/drawing · page
VEDIC
EXPLAIN (GG2050-VEDIC-000040): Kuiper / Code navigation · Computer science / Interactive visualisation. resolved_address, repository_metadata → human_readable_address_description
Uses
Kuiper Card (script src), Kuiper Programs (script src), Kuiper Pointer (script src), Kuiper Controls (script src), Kuiper Chrome (script src), Public Start (script src)
Used by
embedded by Kuiper Grid — Drawing Page (iframe), mentioned in Standalone (comment link)
Produces
buildLink, complaints, parseLink, fmt, day, words, prog, U, tsv, boot, appFor, narrow
Defines here
edge
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/drawing/renderer.html:701-829 · blob e8e2d6ef52f7b28f3ff4e46202e23baed4214907 · GitHub at these lines
State
achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: production_core
    gl.finish(); ms = performance.now() - t0; }

  if (iso && body && body.shown && BP) {
    gl.useProgram(BP); gl.disable(gl.BLEND);
    gl.bindBuffer(gl.ARRAY_BUFFER, bodyBuf); const at = gl.getAttribLocation(BP, 'a_pos');
    gl.enableVertexAttribArray(at); gl.vertexAttribPointer(at, 2, gl.FLOAT, false, 0, 0);
    gl.uniform2f(U(BP,'u_res'), W, H); gl.uniform2f(U(BP,'u_center'), cx, cy); gl.uniform1f(U(BP,'u_zoom'), zoom);
    gl.uniform1f(U(BP,'u_size'), bodyDrawnDiameter());
    gl.uniform3f(U(BP,'u_on'), iso.prog.on.colour[0], iso.prog.on.colour[1], iso.prog.on.colour[2]);
    gl.drawArrays(gl.POINTS, 0, body.n);
    gl.disableVertexAttribArray(at); gl.bindBuffer(gl.ARRAY_BUFFER, null); }
  if (iso && glowCount && !glowOff && PG && (iso.prog.on.size || 0) > 0 && !(body && body.shown)) {
    // ADDITIVE, so sparks that fall together burn brighter, which is what a lot of work in one place
    // should look like. The state is put back exactly as it was found.
    gl.useProgram(PG); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE);
    gl.bindBuffer(gl.ARRAY_BUFFER, glowBuf); const at = gl.getAttribLocation(PG, 'a_pos');
    gl.enableVertexAttribArray(at); gl.vertexAttribPointer(at, 2, gl.FLOAT, false, 0, 0);
    gl.uniform2f(U(PG,'u_res'), W, H); gl.uniform2f(U(PG,'u_center'), cx, cy); gl.uniform1f(U(PG,'u_zoom'), zoom);
    gl.uniform1f(U(PG,'u_size'), iso.prog.on.size * (window.devicePixelRatio || 1)); gl.uniform1f(U(PG,'u_front'), iso.front);
    gl.uniform3f(U(PG,'u_on'), iso.prog.on.colour[0], iso.prog.on.colour[1], iso.prog.on.colour[2]);
    // A DENSE BODY MUST NOT BURN OUT TO WHITE. Light adds, so thousands of sparks packed into a small
    // body on a phone summed to a featureless blob. Each spark is turned down by how crowded the body
    // is, in step with how far the gathering has gone, so the body keeps its colour and its grain.
    { const sz = iso.prog.on.size * (window.devicePixelRatio || 1), Rp = Math.sqrt(SPACE) * zoom * GATHER_RADIUS;
      const crowd = Math.max(1, glowCount * sz * sz * 0.10 / Math.max(1, Math.PI * Rp * Rp));
      const g = iso.to ? (iso.g === undefined ? 1 : iso.g) : 0;
      gl.uniform1f(U(PG,'u_bright'), (iso.prog.on.bright || 1) / (1 + g * (crowd - 1))); }
    gl.drawArrays(gl.POINTS, 0, glowCount);
    gl.disableVertexAttribArray(at); gl.bindBuffer(gl.ARRAY_BUFFER, null); gl.disable(gl.BLEND); }
  const L = [], D = [];
  D.push(points ? 'RESOLVED · every issued key whose radius is in the field, drawn at its own place'
                : 'UNRESOLVED · up to ' + words(1/(Math.PI*zoom*zoom)) + ' keys to a pixel · each pixel’s issued count is computed from the law, not drawn');
  if (points) D.push(fmt(total) + ' issued keys from ' + fmt(segs.length) + ' commits passed to the GPU in ' + ms.toFixed(0) + ' ms');
  D.push('the whole · ' + fmt(N) + ' issued + ' + fmt(SPACE - N) + ' silent = ' + fmt(SPACE) + ' addresses');
  if (iso) L.push('ISOLATED \u00b7 ' + iso.app.button + ' \u00b7 ' + fmt(iso.lit) + ' pieces of work lit \u00b7 '
    + fmt(iso.dark) + ' dark \u00b7 ' + day(iso.first) + ' to ' + day(iso.last));
  if (litRepo >= 0) { const rt = linesByRunningTotals(litRepo), rr = repos[litRepo];
    // the number on screen is the one the shading is made of, not the one the belt declared; if
    // they differ the HUD says so rather than picking the prettier of the two
    // WHAT IS HIGHLIGHTED, IN WORDS A READER CAME WITH. Whether two running totals agree is how
    // this page knows it is not lying, which matters, and belongs where the rest of the working
    // is: behind d. What stays on the face is the disagreement itself, if there ever is one,
    // because a reader must never be shown a number the page has reason to doubt.
    L.push('HIGHLIGHTED · ' + rr.name + ' · ' + fmt(rr.commits) + ' pieces of work · '
           + day(rr.t0) + ' to ' + day(rr.t1));
    D.push('running totals ' + (rt === rr.lines ? 'agree with the belt' : 'DISAGREE with the belt'));
    if (rt !== rr.lines) L.push('THIS COUNT IS IN DOUBT · two measurements of it disagree, so it is not shown');
    const wpx = widestRunPx(litRepo, zoom);
    // Said exactly, because 269 pixels of a repository whose widest run is a tenth of a pixel are
    // lit: the runs are so close together that pixel centres keep landing inside them. The claim
    // is about the run, not about the light.
    if (wpx < 1) L.push('TOO SMALL TO SEE AT THIS ZOOM · what is lit is only where this work happens to fall · zoom in to see it whole'); }
  D.push(zoom >= 1 ? 'zoom ' + zoom.toFixed(1) + ' px per key spacing' : 'zoom 1 px = ' + words(1/zoom) + ' units');
  hud.textContent = (detail ? L.concat(D) : L).join('\n');
  // A PANEL DRAWN FOR WORDS THAT ARE NOT THERE. With nothing highlighted the readout is empty, and
  // an empty bordered box sat in the corner at 1366 looking like something that had failed to load.
  hud.style.display = hud.textContent.trim() ? '' : 'none';
  o2.clearRect(0,0,ov.width,ov.height);
  { const x0 = (0 - cx)*zoom + ov.width/2, y0 = ov.height/2 + cy*zoom, M = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
    const a = new Date(commits[0].unix*1000), b = new Date(commits[commits.length-1].unix*1000); let lastPx = -99;
    o2.font = '10px ui-monospace,Consolas,monospace'; o2.lineWidth = 1;
    for (let y = a.getUTCFullYear(), m = a.getUTCMonth() + 1; y < b.getUTCFullYear() || (y === b.getUTCFullYear() && m <= b.getUTCMonth()); m++) {
      if (m > 11) { m = 0; y++; }
      const t = Date.UTC(y, m, 1)/1000, i = Math.min(commits.length-1, findBy('unix', t - 1) + 1), rp = Math.sqrt(commits[i].k0)*zoom;
      if (rp - lastPx < 26 || rp > 6000) continue; lastPx = rp;
      o2.strokeStyle = 'rgba(46,230,230,.30)'; o2.beginPath(); o2.arc(x0, y0, rp, 0, 6.2832); o2.stroke();
      o2.fillStyle = 'rgba(46,230,230,.85)'; o2.fillText(M[m] + ' ' + String(y).slice(2), x0 + rp*0.5 + 4, y0 - rp*0.866 - 3); } }
  if (target && target.boundary && zoom >= POINTS_FROM) {
    // at this zoom the boundary circle is straight across the screen: perpendicular to the radius
    const x = (target.x - cx)*zoom + ov.width/2, y = ov.height/2 - (target.y - cy)*zoom, rr = Math.hypot(target.x, target.y) || 1;
    const tx = -target.y/rr, ty = target.x/rr, Lp = Math.hypot(ov.width, ov.height);
    o2.strokeStyle = 'rgba(255,199,107,.95)'; o2.lineWidth = 2; o2.setLineDash([10,6]); o2.beginPath();
    o2.moveTo(x - tx*Lp, y + ty*Lp); o2.lineTo(x + tx*Lp, y - ty*Lp); o2.stroke(); o2.setLineDash([]);
    o2.font = '12px ui-monospace,Consolas,monospace'; o2.fillStyle = 'rgba(255,199,107,1)';
    // outward is newer, and which way outward points on screen depends on where this key sits, so
    // the words are placed along the real radius rather than assumed to read left to right
    const ox = target.x/rr, oy = -target.y/rr;
    o2.textAlign = 'center';
    o2.fillText('NEW CODE', x + ox*110, y + oy*110); o2.fillStyle = 'rgba(213,220,234,.85)';
    o2.fillText('older', x - ox*110, y - oy*110); o2.fillStyle = 'rgba(255,199,107,1)';
    o2.fillText('the boundary', x + tx*150, y - ty*150 - 8); o2.textAlign = 'start'; }
  if (arrow) {
    const p = keyPlace(arrow.k);
    const fx = (0 - cx)*zoom + ov.width/2, fy = ov.height/2 + cy*zoom;          // the middle: where the record begins
    const bx = (p[0] - cx)*zoom + ov.width/2, by = ov.height/2 - (p[1] - cy)*zoom;
    // WHEN THE BEGINNING IS OFF THE SCREEN, AND AFTER THE CAMERA FLIES IT ALWAYS IS, the arrow keeps
    // the true line and starts where that line crosses the edge of the window. Direction is the whole
    // of what it says; a stub of a line thousands of screen widths long says nothing at all.
    let ax = fx, ay = fy;
    { const W = ov.width, H = ov.height, dx = fx - bx, dy = fy - by;
      const far = fx < 0 || fy < 0 || fx > W || fy > H;
      if (far && (dx || dy)) {
        let t = Infinity;
        const edge = (num, den) => { if (den === 0) return; const u = num / den;
          if (u > 0 && u < t) { const x = bx + dx*u, y = by + dy*u;
            if (x >= -1 && x <= W + 1 && y >= -1 && y <= H + 1) t = u; } };
        edge(-bx, dx); edge(W - bx, dx); edge(-by, dy); edge(H - by, dy);
        if (t !== Infinity) { ax = bx + dx*t*0.98; ay = by + dy*t*0.98; }
      } }
    const u = Math.min(1, (performance.now() - arrow.t0) / ARROW_MS), e = 1 - Math.pow(1 - u, 3);
    const tx = ax + (bx - ax)*e, ty = ay + (by - ay)*e, th = Math.atan2(by - ay, bx - ax);
    o2.strokeStyle = 'rgba(255,43,214,.95)'; o2.lineWidth = 2; o2.beginPath();
    o2.moveTo(ax, ay); o2.lineTo(tx, ty);
    for (const d of [-0.36, 0.36]) { o2.moveTo(tx, ty); o2.lineTo(tx - 13*Math.cos(th + d), ty - 13*Math.sin(th + d)); }
    o2.stroke();
    // WHERE THE POINT REALLY IS, not where it was aimed. The page can be asked afterwards, and an
    // arrow that lands NEAR the answer is worse than no arrow at all, because it is believed.
    arrowTip = { x:tx, y:ty, x0:ax, y0:ay, fromX:fx, fromY:fy, done:u >= 1 };
    if (u >= 1 && !arrow.held) arrow.held = performance.now();
    if (arrow.held && performance.now() - arrow.held > ARROW_HOLD) arrow = null;     // it has said its piece
    dirty = true;
  }
  if (target) { const x = (target.x - cx)*zoom + ov.width/2, y = ov.height/2 - (target.y - cy)*zoom;
    o2.strokeStyle = 'rgba(255,43,214,.98)'; o2.lineWidth = 1.5; o2.beginPath();
    for (const [a,b,c,d] of [[-16,0,-6,0],[6,0,16,0],[0,-16,0,-6],[0,6,0,16]]) { o2.moveTo(x+a,y+b); o2.lineTo(x+c,y+d); } o2.stroke(); }
}
</script>
<script src="kuiper-card.js"></script>
<script src="kuiper-programs.js"></script>
<script src="kuiper-pointer.js"></script>
<script src="kuiper-controls.js"></script>
<script src="kuiper-chrome.js"></script>
<script>
'use strict';
// every part has arrived: load the record and start drawing
boot(); requestAnimationFrame(frame);
</script>
<script src="public-start.js"></script></body>
</html>

Site Scale

A JavaScript file in the drawing folder of GlobalGrid2050 that draws synthetic project. Served with the page at https://globalgrid2050.com/kuiper-grid/drawing/. It cleans recipe (`cleanRecipe`), validates project (`validateProject`) and loads project (`loadProject`).

interactionglobalgrid2050 / kuiper-grid/drawing/site-scale.js · lines 1–164 of 164 · Entry point · pattern storageKey (shared by 2 files)

What it does
It draws synthetic project. Defines 32 functions or classes, including $, copy, stringKey, cleanRecipe, storageKey. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: browser storage (getItem); user-supplied file (file picker); form fields (user input). Out: JSON file -synthetic-project.json; browser storage (setItem); canvas drawing.
Downstream impact
Used directly by 1 file: Kuiper Grid — Drawing Page (globalgrid2050, https://globalgrid2050.com/kuiper-grid/drawing/). Reached from 109 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/). It is itself an entry point, published at https://globalgrid2050.com/kuiper-grid/drawing/.
What it achieves
Local synthetic hierarchy. Arithmetic instance addressing; no electrical solver or surveyed placement. It responds to kuiper, pointerdown and pointerup events.
Why it matters
Loaded by the Drawing page at https://globalgrid2050.com/kuiper-grid/drawing/.
Application
globalgrid2050 · kuiper-grid/drawing · script
Uses
none found
Used by
loaded by Kuiper Grid — Drawing Page (script src)
Produces
$, copy, stringKey, cleanRecipe, storageKey, projectState, validateProject, persist, loadProject, saveCurrent, fail, number
Defines here
$, copy, stringKey, cleanRecipe, storageKey, projectState, validateProject, persist, loadProject, saveCurrent, fail, number, bid, makeSpec, countInBlock, parseAddress, stopTrace, clearOldDrawing, cells, buildNative, status, show, generate, openItem, focusComponent, inspect, up, command, attempt, exportProject
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/drawing/site-scale.js:1-164 · blob e09235817199df53790363dfd6298c0b99fa9d59 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: agent_infra · users: ai_agent · canonical: production_core
/* Local synthetic hierarchy. Arithmetic instance addressing; no electrical solver or surveyed placement. */
'use strict';
(function boot(){
  const frame=document.getElementById('kuiper-frame'),lab=window.__arrayLab,win=frame?.contentWindow;
  if(!lab?.engineReady||!win?.FIRE){setTimeout(boot,200);return;}
  const MAX_GLYPHS=400,STRINGS_PER_BLOCK=32,MIN_WAIT=650;
  const panel=document.createElement('details');panel.id='site-scale';panel.style.cssText='padding:10px 17px;border-bottom:1px solid #35475a;background:#0c1825';
  panel.innerHTML='<summary>Generic 500 MWp farm · explore any component</summary><div class="actions" style="margin-top:10px"><label>Size · DC MWp <input id="scale-mw" type="number" min="0.001" max="1000000" step="1" value="500" style="width:95px"></label><label>Assumed module Wp <input id="scale-wp" type="number" min="100" max="2000" value="660" style="width:80px"></label><label>Modules / string  … [line shortened here: 1,421 characters; full line on GitHub]
  document.querySelector('main').prepend(panel);
  const farmButton=document.createElement('button');farmButton.id='open-500mw-farm';farmButton.textContent='Explore 500 MWp farm';farmButton.style.cssText='margin:8px 17px';panel.before(farmButton);farmButton.onclick=()=>attempt(()=>{panel.open=true;generate(500);});
  const scopeStyle=document.createElement('style');scopeStyle.textContent='body.synthetic-scale-active main>.summary,body.synthetic-scale-active main>.detail,body.synthetic-scale-active main>.legend{display:none}';document.head.append(scopeStyle);
  const $=id=>panel.querySelector('#'+id);
  const persistence=document.createElement('div');persistence.innerHTML='<div class="actions"><button id="scale-export">Download project</button><button id="scale-import">Import project</button><input id="scale-project-file" type="file" accept=".json,application/json" hidden></div><p id="scale-save-state" class="note">Sparse synthetic edits save in this browser, by site/block/string. Up to 128 edi  … [line shortened here: 705 characters; full line on GitHub]
  let spec=null,level={kind:'site'},items=[],context=null,savedRecipe=lab.recipe(),active=false,viewToken=0,wheelTimer=0,lastTransition=0,peakShapes=0;
  const STORE_PREFIX='kuiper.public.synthetic-project/1:',MAX_EDITED_STRINGS=128,MAX_PROJECT_BYTES=4*1024*1024;
  let project=null,loadingDetail=false,saveError=null;
  const copy=value=>JSON.parse(JSON.stringify(value));
  const stringKey=a=>bid(a.block)+'/'+sid(a.string);
  function cleanRecipe(r){const clean=copy(r);delete clean.syntheticContext;return clean;}
  function storageKey(id){return STORE_PREFIX+id;}
  function projectState(message){$('scale-save-state').textContent=message||((saveError?'Not saved: '+saveError:'Saved in this browser')+' · '+Object.keys(project?.edits||{}).length+'/'+MAX_EDITED_STRINGS+' independently edited strings · scenario '+(project?.site.id||'none')+'. Undo is limited to this visit. Download a project backup. Project data stays in this browser.');}
  function validateProject(value){
    if(!value||value.schema!=='kuiper.synthetic-project/1'||value.namespace!=='synthetic')throw Error('Expected kuiper.synthetic-project/1 in the synthetic namespace.');
    const s=value.site,canonical=makeSpec(s?.requestedMW,s?.moduleWp,s?.series);if(s.id!==canonical.id||s.moduleCount!==canonical.moduleCount||s.stringCount!==canonical.stringCount||s.blockCount!==canonical.blockCount)throw Error('Project site counts or identity are inconsistent.');
    if(!value.edits||typeof value.edits!=='object'||Array.isArray(value.edits))throw Error('Project edits must be keyed by global block/string ID.');
    if(Object.keys(value.edits).length>MAX_EDITED_STRINGS)throw Error('Project exceeds '+MAX_EDITED_STRINGS+' edited strings.');
    const base=cleanRecipe(value.baseRecipe);if(base.rows!==1||base.count!==canonical.series)throw Error('Base recipe must describe one indexed string.');lab.build(base);
    const edits={};
    for(const [key,raw] of Object.entries(value.edits)){
      const m=/^B(\d{4,})\/S(\d{3})$/.exec(key);if(!m)throw Error('Invalid global string ID '+key+'.');const b=Number(m[1]),n=Number(m[2]),count=Math.min(STRINGS_PER_BLOCK,canonical.stringCount-(b-1)*STRINGS_PER_BLOCK);
      if(b<1||b>canonical.blockCount||n<1||n>count||key!==bid(b)+'/'+sid(n))throw Error('String outside project: '+key+'.');
      if(raw?.syntheticContext)throw Error('Stored recipes must use local IDs; context comes from the global project key.');
      const r=cleanRecipe(raw);if(r.rows!==1||r.count!==canonical.series)throw Error('Recipe '+key+' changes indexed membership.');lab.build(r);edits[key]=r;
    }
    const result={schema:'kuiper.synthetic-project/1',namespace:'synthetic',site:canonical,baseRecipe:base,edits};if(new Blob([JSON.stringify(result)]).size>MAX_PROJECT_BYTES)throw Error('Project exceeds the 4 MB sparse-edit limit.');return result;
  }
  function persist(){if(!project)return;const raw=JSON.stringify(project);if(new Blob([raw]).size>MAX_PROJECT_BYTES)throw Error('Project exceeds 4 MB. Download and split the study before adding more edits.');localStorage.setItem(storageKey(project.site.id),raw);saveError=null;projectState();}
  function loadProject(next,base){
    const raw=localStorage.getItem(storageKey(next.id));if(raw){if(raw.length>MAX_PROJECT_BYTES)throw Error('Stored project exceeds size limit.');project=validateProject(JSON.parse(raw));}
    else project={schema:'kuiper.synthetic-project/1',namespace:'synthetic',site:copy(next),baseRecipe:cleanRecipe(base),edits:{}};
    saveError=null;projectState();
  }
  function saveCurrent(r){
    if(loadingDetail||!project||!r.syntheticContext||r.syntheticContext.siteId!==project.site.id)return;
    const c=r.syntheticContext;if(c.string===null||c.string===undefined)return;const key=stringKey(c),clean=cleanRecipe(r);
    if(clean.rows!==1||clean.count!==project.site.series)throw Error('Cannot save changed indexed membership.');
    const edited=JSON.stringify(clean)!==JSON.stringify(project.baseRecipe);if(edited&&!Object.hasOwn(project.edits,key)&&Object.keys(project.edits).length>=MAX_EDITED_STRINGS)throw Error('This scenario already has 128 edited strings. Download/split the project before editing another.');
    if(edited)project.edits[key]=clean;else delete project.edits[key];persist();
  }
  window.addEventListener('kuiper:recipe-changed',e=>{try{saveCurrent(e.detail.recipe);}catch(err){saveError=err.message;projectState();}});
  const metrics={builds:0,totalBuildMs:0,lastBuildMs:0,peakShapes:0,materializedModules:0,jumps:0,lastJumpMs:0,frameSamples:[]};
  function fail(message){$('scale-status').textContent=message;}
  function number(value,name,min,max){const n=Number(value);if(!Number.isFinite(n)||n<min||n>max)throw Error(name+' must be between '+min+' and '+max+'.');return n;}
  const bid=n=>'B'+String(n).padStart(4,'0'),sid=n=>'S'+String(n).padStart(3,'0'),mid=n=>'M'+String(n).padStart(3,'0');
  function makeSpec(mw,wp,series){
    mw=number(mw,'Requested MW',.001,1000000);wp=number(wp,'Assumed module Wp',100,2000);series=number(series,'Modules per string',2,60);
    if(!Number.isInteger(series))throw Error('Modules per string must be a whole number.');
    const stringCount=Math.ceil(mw*1e6/(wp*series)),moduleCount=stringCount*series,blockCount=Math.ceil(stringCount/STRINGS_PER_BLOCK);
    if(!Number.isSafeInteger(moduleCount))throw Error('Site count is outside the exact integer range.');
    return {schema:'kuiper.synthetic-site/1',id:'SYN-'+mw+'MW-'+wp+'WP-'+series+'M',requestedMW:mw,moduleWp:wp,series,stringCount,moduleCount,blockCount,stringsPerBlock:STRINGS_PER_BLOCK,modeledMW:moduleCount*wp/1e6,placement:'synthetic-index-grid',electricalState:'unsolved',source:'entered assumptions'};
  }
  function countInBlock(b){return Math.max(0,Math.min(STRINGS_PER_BLOCK,spec.stringCount-(b-1)*STRINGS_PER_BLOCK));}
  function parseAddress(text){
    if(!spec)throw Error('Open a synthetic site first.');
    const clean=String(text).trim().toUpperCase().replaceAll('−','-').replace(/^INSPECT\s+/,'');
    const match=/^B(\d+)(?:\/S(\d+))?(?:\/M(\d+))?(?:\/(JB[+-]|C[+-]))?$/.exec(clean);
    if(!match)throw Error('Use inspect B0001/S001/M030/C+ (component suffix optional).');
    const b=Number(match[1]),s=match[2]?Number(match[2]):null,m=match[3]?Number(match[3]):null,part=match[4]||null;
    if(!Number.isSafeInteger(b)||b<1||b>spec.blockCount)throw Error('Block outside 1…'+spec.blockCount+'.');
    if(s!==null&&(!Number.isInteger(s)||s<1||s>countInBlock(b)))throw Error('String outside this block (1…'+countInBlock(b)+').');
    if(m!==null&&(s===null||!Number.isInteger(m)||m<1||m>spec.series))throw Error('Module outside this string (1…'+spec.series+').');
    if(part&&m===null)throw Error('A component address needs a module.');
    const stringIndex=s===null?null:(b-1)*STRINGS_PER_BLOCK+s-1,moduleIndex=m===null?null:stringIndex*spec.series+m-1;
    return {siteId:spec.id,block:b,string:s,module:m,part,address:bid(b)+(s===null?'':'/'+sid(s))+(m===null?'':'/'+mid(m))+(part?'/'+part:''),stringIndex,moduleIndex};
  }
  function stopTrace(){const b=document.getElementById('trace');if(b?.classList.contains('active'))b.click();}
  function clearOldDrawing(){stopTrace();win.eval('atHome=false');}
  function cells(){
    if(level.kind==='site'){
      const size=Math.max(1,Math.ceil(spec.blockCount/MAX_GLYPHS)),result=[];
      for(let first=1;first<=spec.blockCount;first+=size){const last=Math.min(spec.blockCount,first+size-1),strings=Math.min(spec.stringCount,last*STRINGS_PER_BLOCK)-(first-1)*STRINGS_PER_BLOCK;result.push({key:bid(first)+(last>first?'–'+bid(last):''),kind:last>first?'range':'block',first,last,blocks:last-first+1,strings,modules:strings*spec.series});}
      return result;
    }
    if(level.kind==='range'){const result=[],size=Math.max(1,Math.ceil((level.last-level.first+1)/MAX_GLYPHS));for(let first=level.first;first<=level.last;first+=size){const last=Math.min(level.last,first+size-1),strings=Math.min(spec.stringCount,last*STRINGS_PER_BLOCK)-(first-1)*STRINGS_PER_BLOCK;result.push({key:bid(first)+(last>first?'–'+bid(last):''),kind:last>first?'range':'block',first,last,  … [line shortened here: 474 characters; full line on GitHub]
    if(level.kind==='block')return Array.from({length:countInBlock(level.block)},(_,i)=>({key:bid(level.block)+'/'+sid(i+1),kind:'string',block:level.block,string:i+1,strings:1,modules:spec.series}));
    return [];
  }
  function buildNative(){
    const t0=performance.now();items=cells();
    if(items.length>MAX_GLYPHS)throw Error('Hierarchy level exceeds bounded glyph budget.');
    const cols=Math.max(1,Math.ceil(Math.sqrt(items.length*1.7))),rows=Math.ceil(items.length/cols),w=1,h=.58,gap=.12,spanX=cols*(w+gap)-gap,spanY=rows*(h+gap)-gap,scale=1.72/Math.max(spanX,spanY),shapes=[],marks=[];
    items.forEach((item,i)=>{
      const x=(i%cols)*(w+gap),y=Math.floor(i/cols)*(h+gap),x0=(x-spanX/2)*scale,y0=(spanY/2-y-h)*scale;
      item.rect=[x0,y0,x0+w*scale,y0+h*scale];
      shapes.push({role:'module',node:item.key,order:0,pot:0,pts:[[x0,y0],[x0+w*scale,y0],[x0+w*scale,y0+h*scale],[x0,y0+h*scale],[x0,y0]],fill:'#123849',weight:1});
      marks.push({x:x0+w*scale/2,y:y0+h*scale*.68,text:items.length>64?bid(item.first):item.key,size:items.length>64?8:9,colour:'#b8dfea',minPx:0,mid:true,rank:0});
      if(items.length<=64)marks.push({x:x0+w*scale/2,y:y0+h*scale*.29,text:item.modules.toLocaleString()+' modules',size:9,colour:'#739bb0',minPx:0,mid:true,rank:1});
    });
    const title=level.kind==='site'?'Synthetic site':level.kind==='range'?'Block range '+bid(level.first)+'–'+bid(level.last):'Block '+bid(level.block);
    const words=[{pinned:3,note:true,text:title+' · '+spec.moduleCount.toLocaleString()+' indexed modules · '+spec.stringCount.toLocaleString()+' strings · '+spec.blockCount.toLocaleString()+' blocks',small:title+' · synthetic'},
      {pinned:4,note:true,text:'Requested '+spec.requestedMW.toLocaleString()+' MWp DC · modeled '+spec.modeledMW.toFixed(5)+' MWp DC at assumed '+spec.moduleWp+' Wp · '+items.length+' visible aggregate glyphs',small:items.length+' aggregate glyphs · electrical state unsolved'},
      {pinned:5,note:true,text:'Synthetic index layout; no surveyed positions or solved volts/current. Click an item, zoom inward over it, or enter an exact component ID.',small:'Synthetic placement · no electrical solver'}];
    const g={c:{sheet:0,view:'macro'},N:spec.moduleCount,pitch:1,short:[],links:[],rows,cols,rowY:[],order:[],bothNear:true,ret:0,row:spanX,lead_m:0,field_m:0,ohm:0};
    const D={kind:'string',opened:true,shapes,marks,words,conns:[],terminals:[],wiring:false,crossings:[],perM:scale,open:false,g,firstModuleX:-.86,volts:0,volts_open:0,earth_node:'earth',bounds:{x0:-spanX*scale/2-.025,y0:-spanY*scale/2-.025,x1:spanX*scale/2+.025,y1:spanY*scale/2+.025},near:{x:0,y:0},mPerUnit:1/scale,amps:0,front:-1,head:-1,walk:null,t0:0,siteScale:{siteId:spec.id,kind:level.kind,  … [line shortened here: 425 characters; full line on GitHub]
    g.__draw=D;metrics.builds++;metrics.lastBuildMs=performance.now()-t0;metrics.totalBuildMs+=metrics.lastBuildMs;peakShapes=Math.max(peakShapes,shapes.length);metrics.peakShapes=peakShapes;metrics.materializedModules=0;
    return {numbers:{indexed_modules:spec.moduleCount,indexed_strings:spec.stringCount,indexed_blocks:spec.blockCount,visible_aggregate_glyphs:shapes.length,requested_mw:spec.requestedMW,modeled_mw:spec.modeledMW,electrical_state:'unsolved'},said:title+'. Indexed synthetic hierarchy, generated at the visible level only.',how:'Existing Kuiper native shape renderer and camera. Aggregate layout is sc  … [line shortened here: 470 characters; full line on GitHub]
  }
  win.FIRE.register('synthetic-site','SYNTHETIC SCALE',buildNative,[]);win.FIRE_SLD_KIND['synthetic-site']='string';
  function status(){
    if(!spec){fail('Ready to generate an indexed synthetic site from the entered size and module rating.');return;}
    const here=context?context.address:level.kind==='site'?'site overview':level.kind==='range'?bid(level.first)+'–'+bid(level.last):bid(level.block);
    panel.querySelector('summary').textContent='Synthetic '+spec.requestedMW.toLocaleString()+' MWp DC · '+here+' · electrical state unsolved';
    fail(spec.requestedMW.toLocaleString()+' MWp DC requested / '+spec.modeledMW.toFixed(5)+' MWp DC modeled · '+spec.moduleCount.toLocaleString()+' modules indexed, '+spec.stringCount.toLocaleString()+' strings · '+here+' · '+(context?spec.series+' module detail':items.length+' aggregate glyphs')+'. Synthetic placement; electrical state unsolved.');
  }
  function show(newLevel){
    if(!spec)throw Error('Open a synthetic site first.');clearOldDrawing();active=true;context=null;level=newLevel;const token=++viewToken;lastTransition=performance.now();
    win.fireCommand('fire synthetic-site {}',null);
    document.body.classList.add('synthetic-scale-active');document.getElementById('view-status').textContent='Synthetic hierarchy · entered Wp · no circuit solve';
    const select=$('scale-items');select.replaceChildren(...items.map(item=>new Option(item.key,item.key)));
    setTimeout(()=>{if(token!==viewToken||!active)return;win.eval('atHome=false;bodyAnim=null;if(body&&body.sld)bodyJump(0);stringWholeView();dirty=true');},180);
    status();
    window.dispatchEvent(new CustomEvent('kuiper:view-changed',{detail:{kind:'synthetic-site',level:copy(level),siteId:spec.id}}));
  }
  function generate(mw=$('scale-mw').value,wp=$('scale-wp').value,series=$('scale-series').value){
    const next=makeSpec(mw,wp,series);if(!active&&!lab.recipe().syntheticContext)savedRecipe=lab.recipe();const base=cleanRecipe(savedRecipe);base.rows=1;base.count=next.series;base.modulePlacements={};base.routeWaypoints={};base.orders={};if(base.wiring==='custom')base.wiring='sequential';lab.build(base);loadProject(next,base);spec=next;$('scale-mw').value=next.requestedMW;$('scale-wp').value=nex  … [line shortened here: 528 characters; full line on GitHub]
  }
  function openItem(item){if(!item)return;if(item.kind==='range')show({kind:'range',first:item.first,last:item.last});else if(item.kind==='block')show({kind:'block',block:item.first});else inspect(item.key);}
  function focusComponent(address){
    const local='S01-M'+String(address.module||1).padStart(2,'0');
    const selectedLink=lab.read().links.findIndex(l=>l.from===local||l.to===local);if(selectedLink>=0){const select=document.getElementById('link-select');select.value=String(selectedLink);select.dispatchEvent(new Event('change'));}
    lab.focusModule(local,{part:address.part,label:address.address});
  }
  function inspect(text){
    const t0=performance.now(),address=parseAddress(text);
    if(address.string===null){show({kind:'block',block:address.block});return address;}
    clearOldDrawing();const r=copy(project.edits[stringKey(address)]||project.baseRecipe);r.schema='kuiper.table/2';
    r.syntheticContext={...address,siteSpec:structuredClone(spec),identityMapping:'local S01-Mnn maps to '+bid(address.block)+'/'+sid(address.string)+'/Mnnn',placement:'synthetic-index-grid',electricalState:'unsolved'};
    active=false;document.body.classList.remove('synthetic-scale-active');context=address;level={kind:'detail',block:address.block,string:address.string};const token=++viewToken;lastTransition=performance.now();loadingDetail=true;try{lab.apply(r);lab.resetHistory();}finally{loadingDetail=false;}lab.setProjection('kuiper');metrics.materializedModules=spec.series;metrics.jumps++;metrics.lastJumpMs=p  … [line shortened here: 420 characters; full line on GitHub]
    setTimeout(()=>{if(token!==viewToken)return;win.eval('atHome=false;bodyAnim=null;if(body&&body.sld)bodyJump(0);dirty=true');if(address.module!==null)focusComponent(address);},500);
    $('scale-command').value='inspect '+address.address;status();return address;
  }
  function up(){if(!spec)return;if(level.kind==='detail')show({kind:'block',block:level.block});else show({kind:'site'});}
  function command(text){const m=/^site\s+([\d.]+)\s*MWp?$/i.exec(String(text).trim());if(m)return generate(m[1]);return inspect(text);}
  function attempt(f){try{return f();}catch(e){fail(e.message);return null;}}
  $('scale-build').onclick=()=>attempt(()=>generate());$('scale-home').onclick=()=>attempt(()=>show({kind:'site'}));$('scale-up').onclick=()=>attempt(up);$('scale-go').onclick=()=>attempt(()=>command($('scale-command').value));$('scale-command').onkeydown=e=>{if(e.key==='Enter')attempt(()=>command($('scale-command').value));};$('scale-open').onclick=()=>attempt(()=>openItem(items.find(i=>i.key===$  … [line shortened here: 425 characters; full line on GitHub]
  function exportProject(){if(!project)throw Error('Open a synthetic site first.');return copy(project);}
  function importProject(value){const next=validateProject(copy(value)),raw=JSON.stringify(next);localStorage.setItem(storageKey(next.site.id),raw);project=next;spec=copy(next.site);savedRecipe=copy(next.baseRecipe);saveError=null;$('scale-mw').value=spec.requestedMW;$('scale-wp').value=spec.moduleWp;$('scale-series').value=String(spec.series);projectState();show({kind:'site'});return{siteId:spec.  … [line shortened here: 453 characters; full line on GitHub]
  $('scale-export').onclick=()=>attempt(()=>{const blob=new Blob([JSON.stringify(exportProject(),null,2)],{type:'application/json'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=spec.id+'-synthetic-project.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);});
  $('scale-import').onclick=()=>$('scale-project-file').click();$('scale-project-file').onchange=async()=>{try{const f=$('scale-project-file').files[0];if(!f)return;if(f.size>MAX_PROJECT_BYTES)throw Error('Project file exceeds 4 MB.');importProject(JSON.parse(await f.text()));}catch(err){fail(err.message);}finally{$('scale-project-file').value='';}};
  function activeDrawing(){return active&&win.eval('sldShapes&&sldShapes.siteScale')?.siteId===spec?.id;}
  function hit(x,y){return items.find(item=>{const a=win.shapePoint([item.rect[0],item.rect[1]]),b=win.shapePoint([item.rect[2],item.rect[3]]);return x>=Math.min(a[0],b[0])&&x<=Math.max(a[0],b[0])&&y>=Math.min(a[1],b[1])&&y<=Math.max(a[1],b[1]);});}
  let down=null;
  win.document.addEventListener('pointerdown',e=>{if(activeDrawing()&&e.target.tagName==='CANVAS')down=[e.clientX,e.clientY];},true);
  win.document.addEventListener('pointerup',e=>{if(!down)return;const moved=Math.hypot(e.clientX-down[0],e.clientY-down[1]);down=null;if(moved>5||!activeDrawing())return;const item=hit(e.clientX,e.clientY);if(item)attempt(()=>openItem(item));},true);
  win.document.addEventListener('wheel',e=>{
    if(!activeDrawing()||performance.now()-lastTransition<MIN_WAIT)return;clearTimeout(wheelTimer);const x=e.clientX,y=e.clientY,d=e.deltaY;
    wheelTimer=setTimeout(()=>{if(!activeDrawing())return;const item=hit(x,y);if(d<0&&item){const a=win.shapePoint([item.rect[0],item.rect[1]]),b=win.shapePoint([item.rect[2],item.rect[3]]);if(Math.abs(b[0]-a[0])>180)attempt(()=>openItem(item));}else if(d>0&&level.kind!=='site'){const D=win.eval('sldShapes'),width=(D.bounds.x1-D.bounds.x0)*win.shapeScale();if(width<win.innerWidth*.45)attempt(up);}  … [line shortened here: 407 characters; full line on GitHub]
  },{capture:true,passive:true});
  let lastFrame=0;
  win.__wafer?.onDraw?.add(()=>{if(!activeDrawing()){document.body.classList.remove('synthetic-scale-active');return;}const now=performance.now();if(lastFrame&&metrics.frameSamples.length<300)metrics.frameSamples.push(now-lastFrame);lastFrame=now;if(win.eval('!!bodyAnim || (body&&body.sld&&!body.shown)')){win.eval('bodyAnim=null;if(body&&body.sld)bodyJump(0);dirty=true');win.drawSldShapes();}});
  win.__wafer?.onDraw?.add(()=>{if(!activeDrawing())return;const c=win.document.getElementById('sldshapes'),ctx=c.getContext('2d'),dpr=Math.min(3,win.devicePixelRatio||1);ctx.save();ctx.setTransform(dpr,0,0,dpr,0,0);ctx.font='9px system-ui';ctx.textAlign='center';ctx.fillStyle='#99d4e1';for(const item of items){const a=win.shapePoint(item.rect.slice(0,2)),b=win.shapePoint(item.rect.slice(2,4)),wid  … [line shortened here: 634 characters; full line on GitHub]
  window.__siteScale={generate,inspect,command,up,show,parseAddress,exportProject,importProject,read:()=>({spec:spec&&structuredClone(spec),level:structuredClone(level),context:context&&structuredClone(context),visibleItems:items.map(({key,kind,first,last,block,string,modules})=>({key,kind,first,last,block,string,modules})),active,metrics:structuredClone(metrics),maxGlyphs:MAX_GLYPHS,persistence:{  … [line shortened here: 809 characters; full line on GitHub]
  status();
})();

View Mode

A JavaScript file in the drawing folder of GlobalGrid2050 that marks advanced (`markAdvanced`). Served with the page at https://globalgrid2050.com/kuiper-grid/drawing/. It marks advanced (`markAdvanced`).

renderglobalgrid2050 / kuiper-grid/drawing/view-mode.js · lines 1–29 of 29 · Entry point

What it does
It draws its content. Defines markAdvanced, set. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
Used directly by 1 file: Kuiper Grid — Drawing Page (globalgrid2050, https://globalgrid2050.com/kuiper-grid/drawing/). Reached from 109 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/). It is itself an entry point, published at https://globalgrid2050.com/kuiper-grid/drawing/.
What it achieves
Defines `markAdvanced` and `set`.
Why it matters
Loaded by the Drawing page at https://globalgrid2050.com/kuiper-grid/drawing/.
Application
globalgrid2050 · kuiper-grid/drawing · script
Uses
none found
Used by
loaded by Kuiper Grid — Drawing Page (script src)
Produces
markAdvanced, set
Defines here
markAdvanced, set
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/drawing/view-mode.js:1-29 · blob a844037c0837973f95ef9b30ff34ef6a04e15cfe · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: production_core
'use strict';
(function boot(){
 if(!window.__arrayLab?.engineReady){setTimeout(boot,200);return;}
 const style=document.createElement('style');
 style.textContent='.proposal-explore .app{grid-template-columns:minmax(0,1fr)}.proposal-explore aside,.proposal-explore main>.detail,.proposal-explore #circuit-workbench,.proposal-explore #mppt-workbench,.proposal-explore #pair-workbench,.proposal-explore #ac-station,.proposal-explore .placement-tools{display:none!important}.proposal-explore .stage{height:66vh}.view-mode-bar{display:flex;gap:10px  … [line shortened here: 644 characters; full line on GitHub]
 document.head.append(style);
 style.textContent+=' .proposal-explore #site-navigation,.proposal-explore .explore-advanced{display:none!important}';
 function markAdvanced(){
  document.getElementById('scale-command')?.closest('.actions')?.classList.add('explore-advanced');
  document.getElementById('scale-export')?.parentElement?.parentElement?.classList.add('explore-advanced');
  document.querySelectorAll('#site-scale>p.note:not(#scale-status)').forEach(p=>p.classList.add('explore-advanced'));
 }
 const bar=document.createElement('nav');bar.className='view-mode-bar';bar.setAttribute('aria-label','Detail level');
 bar.innerHTML='<button id="view-explore" type="button" aria-pressed="false">Explore proposal</button><button id="view-engineer" type="button" aria-pressed="true">Design &amp; engineering</button><p id="view-mode-note">One shared model. Proposed geometry and entered ratings remain development assumptions.</p>';
 document.querySelector('header').after(bar);
 document.getElementById('edit-placement')?.closest('.toolbar')?.classList.add('placement-tools');
 let current='engineer';
 function set(mode){
  if(!['explore','engineer'].includes(mode))throw Error('Unknown detail level');
  markAdvanced();current=mode;document.body.classList.toggle('proposal-explore',mode==='explore');
  for(const key of ['explore','engineer'])document.getElementById('view-'+key).setAttribute('aria-pressed',String(mode===key));
  document.getElementById('view-mode-note').textContent=mode==='explore'?'Explore the same design: open the site controls to size the proposal, then select blocks and strings. Layout is provisional; capacity is DC nameplate, not grid export.':'One shared model. Proposed geometry and entered ratings remain development assumptions.';
  if(mode==='explore'){const scale=document.getElementById('site-scale');if(scale)scale.open=true;}
  window.dispatchEvent(new Event('resize'));
 }
 document.getElementById('view-explore').onclick=()=>set('explore');
 document.getElementById('view-engineer').onclick=()=>set('engineer');
 window.__viewMode={set,get current(){return current;}};
})();

Kuiper Chrome

A JavaScript file in the cartridges folder of GlobalGrid2050. It is built from the set step (`set`).

Set aside from the main view: 94% of its lines are the same as kuiper-grid/i0073/releases/003100000000-kuiper-shell/kuiper-chrome.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 94% of lines shared with Kuiper Chrome; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9412 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/releases/003100000000-kuiper-shell/kuiper-chrome.js:1-35 d9dc0447ad4c76dbc2422b62760784f6cd573415
  • sha256 05ee8c545607daa8a7c91644fb9a9f137e50967205019fe8727468b9bd2c8a91
  • target sha256 3ff552f830d65402ccebe9a97fe1fe0a4a8da3ae11a7d57228bcdc79a55d4df6
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

interactionglobalgrid2050 / kuiper-grid/i0073/cartridges/003200000000-kuiper-chrome.js · lines 1–35 of 35 · Not reached from any entry point (candidate for review)

What it does
It draws its content. Defines set. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
What it achieves
A cartridge of the Kuiper shell: HOW THE PAGE IS DRESSED. It responds to click and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · kuiper-grid/i0073/cartridges · script
Uses
none found
Used by
none found
Produces
set
Defines here
set
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/cartridges/003200000000-kuiper-chrome.js:1-35 · blob ecfe396130d7b4374c630826ebc5c077da9a5919 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
'use strict';
// kuiper-chrome.js - a cartridge of the Kuiper shell: HOW THE PAGE IS DRESSED. What sits over the disc,
// and how much of it. The shell is never edited, so the dressing lives here, where it can be changed.
//
// ON A PHONE THE KUIPER IS THE MAIN EVENT. GridAtlas settled this already (v9.43: tools collapse behind
// one chip): the application buttons fold behind ONE chip, the top box is one word, and the disc gets
// the room. Nothing is removed: one tap opens the row, and choosing an application closes it again.
// A desktop has the room and is left exactly as it is. The warranty line is on the screen at every width.
(function(){
  const css = document.createElement('style');
  css.textContent = `
  #appschip{display:none}
  @media (max-width:640px){
    #use{display:none} #top.open #use{display:block}
    #top{padding:5px 10px} #big{font-size:12px}
    #appschip{display:inline-block;background:#061018;color:#00ffff;border:1px solid #1d6470;padding:8px 12px;
      font:inherit;font-weight:bold;letter-spacing:.08em;cursor:pointer;touch-action:manipulation;margin-bottom:6px}
    #appschip.on{background:#00ffff;color:#000}
    #apps{display:none} #foot.appsopen #apps{display:flex}
    #keys{flex-wrap:nowrap;gap:4px} #keys button{padding:8px 7px;font-size:10px;letter-spacing:.02em;white-space:nowrap}
    #foot .short{margin-top:4px;font-size:10px;line-height:1.35}
  }`;
  document.head.appendChild(css);
  const foot = document.getElementById('foot'), apps = document.getElementById('apps');
  const chip = document.createElement('button'); chip.id = 'appschip'; chip.type = 'button'; chip.textContent = 'APPS';
  chip.setAttribute('aria-expanded', 'false');
  foot.insertBefore(chip, apps);
  const set = open => { foot.classList.toggle('appsopen', open); chip.setAttribute('aria-expanded', String(open));
    if (typeof layout === 'function') layout(); if (typeof atHome !== 'undefined' && atHome && typeof homeCamera === 'function' && SPACE) { const h = homeCamera(); flyTo(h.x, h.y, h.z); } dirty = true; };
  chip.addEventListener('click', e => { e.stopPropagation(); set(!foot.classList.contains('appsopen')); });
  // choosing an application puts the row away again, so the show has the screen; the chip says which is on
  apps.addEventListener('click', e => { const b = e.target.closest ? e.target.closest('button') : null; if (!b) return;
    chip.textContent = b.textContent; chip.classList.add('on'); set(false); });
  addEventListener('keydown', e => { if (e.key === 'Backspace') { chip.textContent = 'APPS'; chip.classList.remove('on'); } });
})();

Kuiper Programs

A JavaScript file in the cartridges folder of GlobalGrid2050 that makes body (`makeBody`), sets tag (`setTag`), makes app buttons (`makeAppButtons`) and calculates planar distances.

Set aside from the main view: 95% of its lines are the same as kuiper-grid/i0073/cartridges/003600000000-kuiper-programs.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 95% of lines shared with Kuiper Programs; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9541 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/cartridges/003600000000-kuiper-programs.js:1-231 184adf2f5f171a549400904c755c6d72ce1143e0
  • sha256 3d6a52c16dd80afa8bd1711b57d7539d053f7df1cd67dd927fa2cab71922f5c5
  • target sha256 a9675c6b9c3e20969c3847ff230eaa3c1d90fbed6366bf23ec068b47999132ed
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

interactionglobalgrid2050 / kuiper-grid/i0073/cartridges/003300000000-kuiper-programs.js · lines 1–223 of 223 · Not reached from any entry point (candidate for review) · pattern bodyDrawnDiameter (shared by 54 files)

What it does
Defines 27 functions or classes, including closestPair, blackSky, nameInLines, makeBody, bodyTo. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
What it achieves
It makes body (`makeBody`), sets tag (`setTag`) and makes app buttons (`makeAppButtons`). A cartridge of the Kuiper shell. It responds to click and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · kuiper-grid/i0073/cartridges · script
Uses
./assemble.mjs
Used by
none found
Produces
closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet, setTag
Defines here
closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet, setTag, revealCode, sparksTo, ensureGlow, makeAppButtons, isolateNow, isolate, raiseTile, endIsolate, unisolate, appCard, closeCard, codeWindow, lh, padTop, place
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/cartridges/003300000000-kuiper-programs.js:1-223 · blob e1d0b6507f7ea0bd0ac2772a1f2bc4d644982ff4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: duplicate_candidate
'use strict';
// kuiper-programs.js - a cartridge of the Kuiper shell. Cut from the whole page with no change of behaviour;
// replaced, when it is, by a newer file the pointer names and the composer checks by its hash.
let ASM = null, gatherAnim = null, homeAnim = null;
// ===== THE BODY: a smaller Kuiper of one application's own work =====================================
let body = null, bodyAnim = null, BP = null, bodyBuf = null;
// THE PALETTE OF THE ONE PULSE. The ring that sweeps the disc is white and ice blue; what it leaves lit is
// the same light, at full brightness. No second look: the saturated green was one, and it is gone.
const FARADAY = [0.80, 0.96, 1.0];
// THE BODY FILLS THE INNER DISC, so a third of the gap is a bigger dot and the body reads from across a
// room without a single dot breaking the rule that makes it a population and not a patch.
const BODY_RADIUS = 0.55, BODY_RADIUS_MAX = 0.92, DOT_MAX_PX = 5, DOT_MIN_PX = 1.0;
const VS_BODY = `#version 300 es
precision highp float;
in vec2 a_pos; uniform float u_zoom, u_size; uniform vec2 u_center, u_res;
void main(){ gl_Position = vec4((a_pos - u_center) * u_zoom / (0.5*u_res), 0.0, 1.0); gl_PointSize = u_size; }`;
// A DOT IS A DISC WITH A HARD EDGE, AND IT IS NOT ADDED TO WHAT IS UNDER IT. Light that adds is how
// neighbours merge into a white patch; here a dot covers what it covers and nothing more.
const FS_BODY = `#version 300 es
precision highp float; uniform vec3 u_on; out vec4 o;
void main(){ if (length(gl_PointCoord - 0.5) > 0.5) discard; o = vec4(u_on, 1.0); }`;
// THE GAP, MEASURED. The nearest two centres among the places the module returned, found with a grid
// so a large application costs no more than a small one. Nothing here is judged by eye.
function closestPair(pos){
  const m = pos.length / 2; if (m < 2) return Infinity;
  let x0 = 1e300, x1 = -1e300, y0 = 1e300, y1 = -1e300;
  for (let q = 0; q < pos.length; q += 2) { x0 = Math.min(x0, pos[q]); x1 = Math.max(x1, pos[q]); y0 = Math.min(y0, pos[q+1]); y1 = Math.max(y1, pos[q+1]); }
  const cell = Math.max(1e-9, Math.sqrt(Math.max(1e-18, (x1 - x0) * (y1 - y0)) / m)), grid = new Map();
  let best = Infinity;
  for (let j = 0; j < m; j++) { const gx = Math.floor((pos[2*j] - x0) / cell), gy = Math.floor((pos[2*j+1] - y0) / cell);
    for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) { const cellm = grid.get((gx + dx) + ':' + (gy + dy)); if (!cellm) continue;
      for (const k of cellm) { const d = Math.hypot(pos[2*j] - pos[2*k], pos[2*j+1] - pos[2*k+1]); if (d < best) best = d; } }
    const key = gx + ':' + gy; (grid.get(key) || grid.set(key, []).get(key)).push(j); }
  return best;
}
// THE BLACK SKY RULE, as one question any body can be asked: are all centres at least three dot radii
// apart? It is the same function the page obeys and the test plants a too tight body against.
function blackSky(pos, dotRadius){ const gap = closestPair(pos); return { gap, dotRadius, ok: gap >= 3 * dotRadius * (1 - 1e-4) }; }   // exactly a third is allowed; the margin is for rounding, not for squeezing
function nameInLines(words){ const w = String(words).split(' '); if (String(words).length <= 9 || w.length < 2) return String(words);
  const half = Math.ceil(w.length / 2); return w.slice(0, half).join(' ') + ' / ' + w.slice(half).join(' '); }
function makeBody(st){
  if (!ASM || !st.idx.length) return null;
  const seq = (st.prog.on.sequence && st.prog.on.sequence.length) ? st.prog.on.sequence : (st.prog.on.shape ? [{ shape:st.prog.on.shape }] : []);
  if (!seq.length) return null;
  const m = st.idx.length, R = Math.sqrt(SPACE), from = new Float32Array(2 * m);
  // ONE DOT FOR EVERY PIECE OF WORK, IN ORDER OF KEY: the module puts dot j at place j, and place 0 is
  // the middle, so the oldest work is the middle of the small Kuiper and the newest is its rim.
  st.idx.forEach((ci, j) => { const c0 = commits[ci], p = keyPlace(c0.k0 + Math.floor((c0.k1 - c0.k0) / 2)); from[2*j] = p[0]; from[2*j+1] = p[1]; });
  // THE SIZE THE SHOW WILL REALLY BE SEEN AT. On a phone the short tile rises under the picture and the
  // disc is refitted smaller above it, so what resolves is decided for THAT size, not for the empty screen.
  const zHome = homeCamera().z * (narrow() ? 0.62 : 1), states = [];
  for (const step of seq) { const shape = step.shape === 'text' ? 'text:' + nameInLines(st.app.button) : step.shape;
    // A NAME NEEDS ENOUGH DOTS TO BE A NAME: about six to a letter. Nine pieces of work cannot spell
    // two words, and a scatter that means nothing is worse than the small Kuiper it would replace.
    // A NAME ONLY WHEN IT CAN BE READ. A letter is a shape of squares and needs a dot for every one of them;
    // with fewer, letters lose strokes (85 pieces of work spelt CABL S). Counted from the module's own
    // lettering, not estimated.
    if (step.shape === 'text') { const ink = ASM.raster ? ASM.raster(nameInLines(st.app.button)) : null;
      const squares = ink ? ink.on.reduce((t, v) => t + v, 0) : 1e9; if (m < squares) continue; }
    let unit; try { unit = ASM.targets(shape, m); } catch (e) { continue; }
    const unitGap = closestPair(unit);
    // large enough that a dot a third of the gap wide is at least a pixel; never larger than the disc
    let frac = BODY_RADIUS; const need = DOT_MIN_PX * 3 / Math.max(1e-12, unitGap * R * zHome);
    if (need > frac) frac = Math.min(BODY_RADIUS_MAX, need);
    const to = new Float32Array(unit.length); for (let q = 0; q < unit.length; q++) to[q] = unit[q] * R * frac;
    const gap = unitGap * R * frac;
    const unresolved = gap * zHome / 3 < DOT_MIN_PX * 0.999;
    // WHAT CANNOT BE RESOLVED IS NOT SHOWN AS IF IT COULD. A state that would need dots under a pixel is
    // left out, and the show ends on the last state that does resolve: the work gathers and STAYS, it
    // is never simply gone from the middle of the disc, which is what a phone showed.
    if (unresolved && states.length) continue;
    states.push({ shape, to, gap, frac, hold:step.hold_ms || 0, unresolved }); }
  if (!states.length) return null;
  return { n:m, from, pos:new Float32Array(from), states, k:-1, gap:0, shown:false };
}
function bodyTo(arr){ if (body) body.live = closestPair(arr);
  if (!BP) { BP = prog(VS_BODY, FS_BODY); bodyBuf = gl.createBuffer(); }
  gl.bindBuffer(gl.ARRAY_BUFFER, bodyBuf); gl.bufferData(gl.ARRAY_BUFFER, arr, gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); }
function labels(show){ const o = document.getElementById('o'); if (o) o.style.visibility = show ? 'visible' : 'hidden'; }
function bodyJump(k){ if (!body) return; labels(false); const stt = body.states[k]; body.pos.set(stt.to); body.k = k; body.gap = stt.gap; body.shown = true; bodyAnim = null; bodyTo(body.pos); dirty = true; }
function bodyMove(k){ if (!body) return; labels(false); bodyAnim = { k, t0:performance.now(), from:new Float32Array(body.pos), gap0:body.shown ? body.gap : body.states[k].gap, phase:'move' };
  body.shown = true; dirty = true; }
// the dot's radius ON THE SCREEN, from the measured gap and the zoom of this moment: a third of the
// gap, never more, however the visitor zooms
// THE SIZE FOLLOWS THE CANVAS, NOT THE SCREEN. This canvas is as many pixels as the window is wide, so a
// point size is already in the units the gap is measured in. Multiplying by the screen's pixel ratio
// drew every dot at twice its size on a real screen and at its right size in every test.
function bodyDrawnDiameter(){ return Math.max(1, 2 * bodyDotPx() * (cv.width / Math.max(1, innerWidth))); }
// A THIRD OF THE GAP AS THE DOTS ARE NOW. At rest the gap is the state's own; in flight it is measured
// from where the dots are at that frame, because leaving the rim they are almost on top of one another
// and no resting spacing describes them.
function bodyDotPx(){ const gap = body.live !== undefined ? body.live : body.gap;      // measured every time the dots are placed
  return Math.max(0.5, Math.min(DOT_MAX_PX, gap * zoom / 3)); }
const asmReady = import('./assemble.mjs').then(m => { ASM = m; }).catch(() => { ASM = null; });
const GATHER_RADIUS = 0.30;                      // of the record's own radius: a body, with the dark disc still around it
function sheet(title, sub){
  const mine = ++cardToken;
  card.classList.remove('short');
  card.replaceChildren();
  card.style.display = 'block';
  card.scrollTop = 0;
  const x = el('button', 'cc-x', '\u00d7'); x.type = 'button'; x.setAttribute('aria-label', 'close');
  x.addEventListener('click', closeCard);
  card.append(x, el('span', 'cc-title', title));
  if (sub) card.append(el('span', 'cc-grey', sub));
  const tagLine = el('div', 'cc-tagline'), tag = el('span', 'cc-tag'), msg = el('span', 'cc-grey');
  tagLine.append(tag, msg); card.append(tagLine);
  const body = el('div', 'cc-body'); card.append(body);
  // THE SINGLE WRITER OF THE STATE. Nothing else touches the chip, and a writer for a card that has
  // been replaced does nothing at all.
  const setTag = (st, text) => { if (mine !== cardToken) return false;
    tag.dataset.s = st; tag.textContent = st; if (text != null) msg.textContent = text; return true; };
  dirty = true;
  return { mine, body, setTag, live: () => mine === cardToken };
}
function revealCode(){
  const w = cardShown && cardShown.window; if (!w) return;
  const cr = card.getBoundingClientRect(), pr = w.node.getBoundingClientRect();
  if (pr.bottom > cr.bottom - 4) card.scrollTop += pr.bottom - cr.bottom + 8;
  else if (pr.top < cr.top) card.scrollTop -= cr.top - pr.top + 8;
  w.scrollToTarget();
}
function sparksTo(arr){ ensureGlow(); gl.bindBuffer(gl.ARRAY_BUFFER, glowBuf);
  gl.bufferData(gl.ARRAY_BUFFER, arr, gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); }
function ensureGlow(){ if (!PG) { PG = prog(VS_GLOW, FS_GLOW); glowBuf = gl.createBuffer(); } }
// ===== ISOLATE AN APPLICATION =================================================================
function makeAppButtons(){
  const bar = document.getElementById('apps'); bar.replaceChildren();
  for (const pr of programs) { const ap = apps.find(x => x.app === pr.select.app);
    if (!ap || !(appWork[ap.app] || []).length) continue;        // nothing of it on this record: no button
    const b = el('button', null, pr.button); b.type = 'button'; b.setAttribute('data-app', pr.name);
    b.addEventListener('click', e => { e.stopPropagation(); isolate(pr.name); }); bar.append(b); }
  if (typeof layout === 'function') layout();
}
// THE STATE ITSELF, with no animation, so it can be arrived at by a link and asked for by a test.
function isolateNow(name, front){
  const asData = programs.find(x => x.name === name); if (!asData) return null;
  const prog = Object.assign({}, asData, { on:Object.assign({}, asData.on, { colour:FARADAY }) });
  const ap = apps.find(x => x.app === prog.select.app); if (!ap) return null;
  name = ap.app;
  const idx = []; for (const sha of (appWork[name] || [])) { const i = bySha.get(sha); if (i !== undefined) idx.push(i); }
  idx.sort((x, y) => x - y);
  litRepo = -1; litK = [-1,-1]; litCi = null; newFrom = -1; flash = 0; litPath = null; target = null; arrow = null;
  iso = { app:ap, prog, front:front === undefined ? 1e30 : front, idx, set:new Set(idx), lit:idx.length, dark:commits.length - idx.length,
          first:idx.length ? commits[idx[0]].unix : 0, last:idx.length ? commits[idx[idx.length - 1]].unix : 0 };
  raiseFlags(idx);
  { // A FEW SPARKS FOR EVERY PIECE OF WORK, spread through its own lines so a big piece of work is a
    // scatter around its ring and a small one a point or two. Never more than the program allows.
    const per = Math.max(1, Math.min(24, (prog.on.sparks | 0) || 8)), pts = [];
    for (const i of idx) { const c0 = commits[i], len = Math.max(1, c0.k1 - c0.k0), take = Math.min(per, len);
      for (let j = 0; j < take; j++) { const p = keyPlace(c0.k0 + Math.floor((j + 0.5) * len / take)); pts.push(p[0], p[1]); } }
    ensureGlow();
    iso.from = new Float32Array(pts); iso.pos = iso.from; iso.to = null;
    glowCount = pts.length / 2; iso.sparks = glowCount; sparksTo(iso.from); }
  body = makeBody(iso);
  // arrived at by a link, or asked for outright: the END of the program, with no waiting
  if (front === undefined && body) bodyJump(body.states.length - 1);
  for (const b of document.querySelectorAll('#apps button')) b.classList.toggle('on', b.getAttribute('data-app') === prog.name);
  if (front === undefined) raiseTile();
  dirty = true;
  return iso;
}
// PRESS: the pulse runs out through the record, which on this picture is forward through time, and
// where it has passed the rest goes dark. The pulse is the page's own; nothing new is animated.
function isolate(name){
  const prog = programs.find(x => x.name === name); if (!prog) return;
  closeCard(); unisolate(true); anim = null; flash = 0; newFrom = -1; target = null; arrow = null;
  { const h = homeCamera(); cx = h.x; cy = h.y; zoom = h.z; tween = null; atHome = true; }
  // the selection is made at once and the FRONT starts at the origin with nothing switched; each dot
  // switches when the front reaches it, so the darkening is seen to travel
  if (!isolateNow(name, 0)) return;
  bodyAnim = null; if (body) body.shown = false;
  isoAnim = { name, t0:performance.now(), R:Math.sqrt(SPACE), ms:Math.max(200, (prog.pulse.seconds || 1.5) * 1000) }; dirty = true;
}
function raiseTile(){ if (!iso || !(iso.prog.end && iso.prog.end.tile)) return;
  appCard(iso); if (atHome) { const h = homeCamera(); flyTo(h.x, h.y, h.z); } dirty = true; }
// ANY OTHER ACTION FIRST ENDS THE ISOLATE. Called by everything that shows something else, before it
// does anything, so the darkening can never outlive the thing it was for.
function endIsolate(){ if (iso || isoAnim || bodyAnim) { unisolate(true); closeCard(); } }
function unisolate(quiet){ labels(true); iso = null; isoAnim = null; gatherAnim = null; homeAnim = null; body = null; bodyAnim = null; pulse = -1;
  for (const b of document.querySelectorAll('#apps button')) b.classList.remove('on');
  if (!quiet) dirty = true; }
// THE TILE OF AN ISOLATED APPLICATION: its name, what it does for a project, OPEN. Then how much of
// the record is lit and how much has gone dark, because the two must make the whole.
function appCard(st){
  cardToken++; cardShown = null; card.replaceChildren(); card.style.display = 'block'; card.scrollTop = 0;
  card.classList.add('short');
  const x = el('button', 'cc-x', '\u00d7'); x.type = 'button'; x.setAttribute('aria-label', 'close');
  x.addEventListener('click', () => { card.style.display = 'none'; dirty = true; });
  const t = el('a', 'cc-tile cc-app'); t.href = st.app.live; t.target = '_blank'; t.rel = 'noopener'; t.setAttribute('data-app', st.app.app);
  t.append(el('div', 'cc-tile-name', st.app.button));
  if (whatItDoes[st.app.live]) t.append(el('div', 'cc-tile-what', whatItDoes[st.app.live] + '.'));
  t.append(el('span', 'cc-tile-open', 'OPEN ' + st.app.button));
  const brand = el('div', 'scada-brand'), inner = el('div');
  inner.append(el('div', 'scada-brand-main', 'Ventus'), el('div', 'scada-brand-sub', 'Cables & Connectivity\u00ae')); brand.append(inner);
  const plain = el('div', 'cc-plain cc-count', fmt(st.lit) + ' pieces of work lit, ' + fmt(st.dark) + ' gone dark, '
    + fmt(st.lit + st.dark) + ' in all \u00b7 ' + day(st.first) + ' to ' + day(st.last));
  card.append(x, t, brand, plain);
  if (typeof layout === 'function') layout();
}
function closeCard(){ cardToken++; card.style.display = 'none'; card.replaceChildren();
  target = null; cardShown = null; dirty = true; }
addEventListener('keydown', e => {
  if (e.key === 'Escape' && card.style.display !== 'none') { e.preventDefault(); closeCard(); } });

function codeWindow(lines, a, b, at){
  const pre = el('pre', 'cc-code');
  pre.setAttribute('aria-label', 'the code around this line');
  const bar = el('div', 'cc-hi cc-hi-target');
  const out = [];
  for (let i = a; i <= b; i++) out.push(String(i).padStart(6) + '  ' + lines[i - 1]);
  pre.append(bar, document.createTextNode(out.join('\n')));
  const lh = () => parseFloat(getComputedStyle(pre).lineHeight) || 16;
  const padTop = () => parseFloat(getComputedStyle(pre).paddingTop) || 0;
  const place = () => { bar.style.top = (padTop() + (at - a) * lh()) + 'px'; bar.style.height = lh() + 'px'; };
  return { node:pre, bar, place, first:a, last:b, at,
    scrollToTarget(){ place(); pre.scrollTop = Math.max(0, (at - a) * lh() - pre.clientHeight/2 + lh()/2); } };
}

// WHAT A TAP OPENS. One way in for every kind of answer: the work and the day it was done, a state
// chip saying how much of it is proved, and, where the code for that line is carried on this site,
// the code itself with the tapped line marked. Nothing here sends a reader to GitHub to READ code;
// the link is there for the detail and the history, which is what GitHub is good for.