GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / gridatlas / atlas/modules

Menu Bar Instrument Panel Browser and 4 more files

A JavaScript module in the proofs folder of GridAtlas that works with ventus box (`ventusBox`) and attrib samples (`attribSamples`), covering cables.

673 lines of JavaScript from gridatlas, in 5 files. Topic: Solar and storage design. Section 198 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. G203 Compact SatNav Panel render · gridatlas / atlas/modules/g203-compact-satnav-panel.js lines 1–66
  2. 13 Panel render · gridatlas / tools/lightning/src/13-panel.js lines 1–98
  3. 07 Panel Install interaction · gridatlas / tools/offtakers/src/07-panel-install.js lines 1–42
  4. Menu Bar Instrument Panel Browser render · gridatlas / tools/proofs/202609041250-menu-bar-instrument-panel.browser.mjs lines 1–366
  5. V8 Layers Panel Restored Proof storage · gridatlas / tools/proofs/v8-layers-panel-restored.proof.mjs lines 1–101

G203 Compact SatNav Panel

A JavaScript file in the atlas folder of GridAtlas.

rendergridatlas / atlas/modules/g203-compact-satnav-panel.js · lines 1–66 of 66 · Not reached from any entry point (candidate for review)

What it does
It draws its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: user-supplied file (file picker).
What it achieves
Native controls and route state stay owned by their existing modules.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/g203-compact-satnav-panel.js:1-66 · blob 580bef8c5710a52d8962a9a4956ef655c9a31aff · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
/* V9.203: presentation-only SatNav cartridge. Native controls and route state stay owned by their existing modules. */
void function () {
  if (document.getElementById('g203-satnav-panel-style')) return;
  const style = document.createElement('style');
  style.id = 'g203-satnav-panel-style';
  style.textContent = `
    html #satnav-compact {
      --g203-panel-width: min(208px, calc(100vw - 16px - env(safe-area-inset-left, 0px) - env(safe-area-inset-right, 0px)));
      --g203-panel-top: max(8px, env(safe-area-inset-top, 0px), var(--gridatlas-menu-bar-clear, 8px), var(--satnav-measured-menu-bottom, 8px));
      --g203-panel-reserve: calc(var(--g203-dock-clearance, 64px) + var(--g203-access-reserve, 48px) + env(safe-area-inset-bottom, 0px));
      left: max(8px, env(safe-area-inset-left, 0px)) !important;
      right: auto !important;
      top: var(--g203-panel-top) !important;
      bottom: auto !important;
      width: var(--g203-panel-width) !important;
      box-sizing: border-box;
      max-height: max(44px, calc(100dvh - var(--g203-panel-top) - var(--g203-panel-reserve))) !important;
      overflow-x: hidden;
      overflow-y: auto;
      gap: 3px;
      font: 12px/1.25 system-ui, sans-serif;
    }
    html:has(#satnav-access[open]:not([hidden])) #satnav-compact {
      --g203-access-reserve: calc(40dvh + 4px);
    }
    html #satnav-compact[hidden] { display: none !important; }
    html #satnav-compact button,
    html #satnav-compact select,
    html #satnav-compact summary {
      box-sizing: border-box;
      min-width: 0;
      max-width: 100%;
      min-height: 44px;
      padding: 4px 5px;
      font: inherit;
      overflow-wrap: anywhere;
    }
    html #satnav-compact summary { cursor: pointer; }
    html #satnav-compact .satnav-row { gap: 3px; }
    html #satnav-compact .satnav-row button { flex: 1 1 0; }
    html #satnav-compact .satnav-endpoint b { width: 38px; }
    html #satnav-compact #satnav-walk-actions { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 3px; }
    html #satnav-compact #satnav-walk-actions select { grid-column: 1 / -1; }
    html #satnav-compact #satnav-field-tools { display: grid; gap: 3px; min-width: 0; }
    html #satnav-compact #satnav-field-tools > * { min-width: 0; max-width: 100%; }
    html #satnav-compact details { background: #081820ed; border-radius: 4px; overflow-wrap: anywhere; }
    html #satnav-compact details summary { padding-inline: 6px; }
    html #satnav-compact input:not([type=file]) { min-width: 0; max-width: 100%; box-sizing: border-box; }
    html #satnav-compact .satnav-readout, html #satnav-compact #satnav-walk-guidance { padding: 3px 5px; font-size: 11px; }
    html #satnav-access {
      left: max(8px, env(safe-area-inset-left, 0px)) !important;
      right: auto !important;
      bottom: calc(var(--g203-dock-clearance, 64px) + env(safe-area-inset-bottom, 0px)) !important;
      width: min(208px, calc(100vw - 16px));
      max-width: calc(100vw - 16px);
      box-sizing: border-box;
      max-height: 40dvh;
      overflow-y: auto;
    }
    html #satnav-access summary { min-height: 44px; display: flex; align-items: center; }
    @media (orientation: landscape) and (max-height: 500px) {
      html #satnav-compact { --g203-panel-width: min(190px, calc(100vw - 16px)); }
    }
  `;
  document.head.append(style);
}();

13 Panel

A JavaScript file in the lightning folder of GridAtlas.

rendergridatlas / tools/lightning/src/13-panel.js · lines 1–98 of 98 · Not reached from any entry point (candidate for review)

What it does
It draws its content. Defines q. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'panel'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: form fields (user input).
What it achieves
The Layers-panel group (main and fullscreen curtain), its label and status line, and the batched repaint pt. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/lightning/src · script
Uses
none found
Used by
none found
Produces
q
Defines here
q
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/lightning/src/13-panel.js:1-98 · blob a670f2669adf64d791a587684e9131a5b62217aa · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
/// 13 panel: the Layers-panel group (main and fullscreen curtain), its label and status line, and the batched repaint pt.
///
/// BTN/NAV/DATE: the panel controls, in the shell's own classes. bg: build one panel group (key = main | fs); the menu's
/// bubble-phase click closer never sees these controls.
BTN=(a,t,x)=>`<button type="button" class="map-ctrl-btn" ${a}${x||''}>${t}</button>`,///
  NAV=(k,t,x)=>BTN(`data-lightning-nav="${k}"`,t,x),///
  ROW='style="display:flex;flex-wrap:wrap;gap:4px;margin:4px 0"',
DATE=k=>`<input type="date" class="search-input" data-lightning-date="${k}" aria-label="${k} date (UTC)" style="width:9.5em;color-scheme:dark">`,
bg=key=>{///
    let g=document.createElement('div');///
    g.className='key-group';///
    g.style.gridColumn='1/-1';///
    g.dataset.lightningGroup=key;
g.innerHTML=`<div class="key-title">${TITLE}</div><label class="key-item"><input type="checkbox" data-lightning-control="toggle"> <span data-lightning-label="${key}" style="color:#ffdf44">${BASE} [WAIT]</span></label>`
+`<div data-lightning-controls="${key}" hidden><div role="group" ${ROW}>${PERIODS.map(p=>BTN(`data-lightning-period="${p[0]}"`,p[0].toUpperCase())).join('')}</div>`
+`<div class="radius-input-row" data-lightning-custom style="display:none;flex-wrap:wrap;margin:4px 0"><span class="radius-unit">From (UTC)</span>${DATE('from')}<span class="radius-unit">To (incl.)</span>${DATE('to')}${NAV('apply','APPLY')}</div>`
+`<div ${ROW}>${NAV('prev','◀ PREV')}${NAV('latest','LATEST',' disabled')}${NAV('next','NEXT ▶',' disabled')}${NAV('points','LOAD POINTS',' hidden')}${NAV('fit','FIT FLASHES',' hidden')}</div>`
+`<div class="status-legend" style="border:0;margin:0;padding:2px 0"><div class="status-dot" style="color:#bbb"><span data-lightning-dot style="background:#888"></span>LOADING</div></div>`
+`<div id="gridatlas-lightning-caption-${key}" data-lightning-caption role="status" aria-live="polite" style="font:12px/1.5 'Courier New',monospace;color:#bbb;overflow-wrap:break-word">`
+['window','days','actual','flashes','refresh','searched','warning',///
      'footer'].map(k=>`<div data-cap="${k}"${k==='days'?' style="font-weight:bold"':k==='warning'?' style="color:#ffcc00"':k==='footer'?' style="font-size:11px;color:#bbb"':''}></div>`).join('')+'</div></div>';
if(ph())g.querySelectorAll('.map-ctrl-btn').forEach(b=>b.style.cssText+='min-height:44px;min-width:44px');
let q=s=>g.querySelector(s),sf={///
      key,group:g,toggle:q('[data-lightning-control]'),label:q('[data-lightning-label]'),ctl:q('[data-lightning-controls]'),custom:q('[data-lightning-custom]'),from:q('[data-lightning-date="from"]'),to:q('[data-lightning-date="to"]'),dot:q('[data-lightning-dot]'),stx:q('.status-dot').lastChild,caps:{},nav:{},chips:{}///
    };
g.querySelectorAll('[data-cap],[data-lightning-nav],[data-lightning-period]').forEach(n=>{///
        let d=n.dataset;///
        if(d.cap)sf.caps[d.cap]=n;///
        else if(d.lightningNav)sf.nav[d.lightningNav]=n;///
        else sf.chips[d.lightningPeriod]=n///
      });
g.addEventListener('click',ev=>{///
        let b=ev.target.closest('button');///
        if(!b||!g.contains(b))return;///
        if(b.dataset.lightningPeriod)sp(b.dataset.lightningPeriod);///
        else if(b.dataset.lightningNav)nv(b.dataset.lightningNav,sf)///
      });
return sf},
/// txt/flag: write only on change. lt: the Layers label ("Lightning Flashes (Optical) [...]"); sl: the status line.
txt=(n,s)=>{if(n&&n.textContent!==s)n.textContent=s},///
  flag=(n,a,on)=>{if(n)on?n.setAttribute(a,''):n.removeAttribute(a)},
lt=(r,c,loading)=>{///
    if(!S.on)return BASE+' [WAIT]';///
    if(loading)return BASE+' [LOAD]';///
    if(!r||c.st==='FAIL')return BASE+' [FAIL]';
let n=fn(r);///
    return`${BASE} [${r.mode==='feed'?(n?N(n):'none seen')+' | '+(r.old?'last 7 days only':'live feed'):/UNKNOWN|BEFORE/.test(c.st)?(r.before?'UNKNOWN':'not yet searched')+' | '+(r.before?'before archive':sv(r,c)):(n?N(n):'none found')+' | '+sv(r,c)}]`///
  },///
  fn=r=>r.mode==='overview'||r.mode==='detail'&&(r.sk.length||r.fl.length)?r.arch:r.ev.length,
sl=(r,c)=>{let st=c.st,n=fn(r),z=c.stale?' · '+lr(c.g,Date.now(),c.f).toUpperCase()+' · STALE':'';
return st==='FAIL'?'FAIL · '+c.rs.join('; ')+z:(r.mode==='feed'?`${pl(n,'flash','es')} · ${r.old?'last 7 days only · older not yet collected':'live 7-day feed · searched unknown'}`:/UNKNOWN|BEFORE/.test(st)?(r.before?'unknown':'not yet searched')+' · '+(r.before?'before archive (from '+dm(r.idx.cutoff)+')':sv(r,c)):`${n?(r.sk&&r.sk.length?N(r.ev.length)+' of ':'')+pl(n,'flash','es'):st==='EMPTY-CO  … [line shortened here: 478 characters; full line on GitHub]
  },
/// pt: one batched repaint of every group: toggle, label, chips, CUSTOM, PREV/NEXT/LATEST, status dot and captions; S.last
/// is the published summary.
pt=loading=>{///
    S.busy=loading;///
    let now=Date.now(),r=S.res,c=r?cf(r,now):null,L=r?cp(r,now,c):null,text=lt(r,c,loading),fail=!!(c&&c.st==='FAIL'),w=r?r.w:null;
for(let sf of S.sfs){///
      if(sf.toggle.checked!==S.on)sf.toggle.checked=S.on;///
      txt(sf.label,text);///
      sf.label.style.opacity=fail?'0.6':'1'///
    }
for(let sf of S.sfs){flag(sf.ctl,'hidden',!S.on);if(!S.on)continue;
for(let k in sf.chips){///
        let b=sf.chips[k],na=!S.idx&&!!S.ie&&LONG.includes(k);///
        b.setAttribute('aria-pressed',b.classList.toggle('active',k===S.period));
if(LONG.includes(k)){///
          let d=b.lastChild;///
          if(!d||!d.tagName){///
            d=document.createElement('span');///
            d.style.opacity='.55';///
            ap(b,d)///
          }txt(d,na?' •':'');///
          b.title=na?'7-day feed only: the archive is not available yet':''///
        }///
      }
let cu=S.period==='custom';///
      sf.custom.style.display=cu?'flex':'none';///
      if(S.idx)sf.from.min=sf.to.min=S.idx.cutoffDate;///
      sf.from.max=sf.to.max=ymd(now);///
      if(sf.from.value!==S.from)sf.from.value=S.from;///
      if(sf.to.value!==S.to)sf.to.value=S.to;
sf.nav.prev.disabled=loading||cu||!S.idx||!w||w.s<=S.idx.covStart||w.s-w.span<S.idx.cutoff;///
      sf.nav.next.disabled=sf.nav.latest.disabled=loading||cu||!w||w.atLatest;///
      flag(sf.nav.points,'hidden',!(r&&r.clp&&!r.big));///
      flag(sf.nav.fit,'hidden',loading||!(r&&r.ev.length));
sf.dot.style.background=loading?COLOUR('L'):c.colour;///
      txt(sf.stx,loading?'LOADING':sl(r,c));///
      if(!loading){///
        for(let k in L)txt(sf.caps[k],L[k]);///
        if(c)sf.caps.days.style.color=c.colour///
      }///
    }
if(r&&!loading)S.last={///
      state:c.st,stale:c.stale,mode:r.mode,period:w.period,drawn:r.ev.length,cluster:!!r.cl,cap:cap(),cap_source:r.cs||null,index_count:r.ic===undefined?null:r.ic,failures:r.fl.length,reasons:c.rs,cells:r.gd?r.gd.fc.features.length:0///
    };///
    if(S.installed)fit()///
  },

07 Panel Install

A JavaScript file in the offtakers folder of GridAtlas covering the Renewable Energy Planning Database (REPD) register and substations.

interactiongridatlas / tools/offtakers/src/07-panel-install.js · lines 1–42 of 42 · Not reached from any entry point (candidate for review)

What it does
It draws the REPD register and substations. Defines q. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'panel'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: the REPD register, substations.
Inputs & outputs
In: form fields (user input).
What it achieves
The Layers group. It responds to click, change and gridatlas events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/offtakers/src · script
Uses
none found
Used by
none found
Produces
q
Defines here
q
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/offtakers/src/07-panel-install.js:1-42 · blob 2d58a510bd6525acf8d5f869f4b8d30369309381 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
/// ---- the Layers group ----
BTN=(a,t)=>`<button type="button" class="map-ctrl-btn" ${a}>${t}</button>`,
bg=key=>{let g=document.createElement('div');g.className='key-group';g.style.gridColumn='1/-1';g.dataset.offtakersGroup=key;
 g.innerHTML=`<div class="key-title">${TITLE}</div><label class="key-item"><input type="checkbox" data-offtakers-control="toggle"> <span data-offtakers-label="${key}" style="color:#8fb4ff">${BASE}</span></label>`
 +`<div data-offtakers-controls="${key}" hidden><div role="group" aria-label="Offtaker classes" style="display:flex;flex-wrap:wrap;gap:4px;margin:4px 0">${BTN('data-offtakers-all','All')}${CK.filter(k=>k!='c').map(k=>BTN(`data-offtakers-class="${k}" aria-pressed="false"`,CLS[k][0])).join('')}</div>`
 +`<div role="group" aria-label="Data centres" data-offtakers-dc style="display:flex;flex-wrap:wrap;align-items:center;gap:4px 8px;margin:4px 0;padding:4px;border:1px solid #6f4fc2;border-radius:3px">${BTN('data-offtakers-class="c" aria-pressed="false"',CLS.c[0]+' · 30/30/30')}${DK.map(k=>`<span style="font-size:11px;color:#ccc;white-space:nowrap"><span style="display:inline-block;width:8px;height  … [line shortened here: 561 characters; full line on GitHub]
 +`<div role="group" aria-label="Power station status" style="display:flex;flex-wrap:wrap;align-items:center;gap:4px;margin:4px 0"><span style="font-size:11px;color:#bbb">Power stations:</span>${BK.map(k=>BTN(`data-offtakers-bst="${k}" aria-pressed="true"`,BST[k])).join('')}</div>`
 +`</div><div data-offtakers-status role="status" aria-live="polite" style="font:12px/1.5 'Courier New',monospace;color:#bbb;overflow-wrap:break-word"></div><div data-offtakers-foot hidden style="font-size:11px;color:#bbb">${LEG} ${DLEG} ${FOOT}</div>`;
 g.querySelectorAll('.map-ctrl-btn').forEach(b=>{b.style.cssText+='min-height:44px;min-width:44px';let k=b.dataset.offtakersClass||(b.dataset.offtakersBst?'b':'');if(k)b.style.borderLeft='4px solid '+CLS[k][1]});
 let q=s=>g.querySelector(s),o={key,group:g,toggle:q('[data-offtakers-control]'),label:q('[data-offtakers-label]'),ctl:q('[data-offtakers-controls]'),st:q('[data-offtakers-status]'),ft:q('[data-offtakers-foot]'),chips:{}};
 o.bchips={};g.querySelectorAll('[data-offtakers-class]').forEach(b=>o.chips[b.dataset.offtakersClass]=b);g.querySelectorAll('[data-offtakers-bst]').forEach(b=>o.bchips[b.dataset.offtakersBst]=b);
 g.addEventListener('click',ev=>{let b=ev.target.closest('button');if(!b||!g.contains(b))return;let d=b.dataset;if(d.offtakersClass)S.cls[d.offtakersClass]=!S.cls[d.offtakersClass];else if(d.offtakersBst)S.bst[d.offtakersBst]=!S.bst[d.offtakersBst];else if(d.offtakersAll!=null){for(let k of CK)S.cls[k]=!!CLS[k][5];for(let k of BK)S.bst[k]=true}else return;
  rf();let r=S.pp&&S.pp.r;if(r&&(!S.cls[r.k]||r.k=='b'&&!S.bst[r.t]))pc();pt()});
 g.addEventListener('change',ev=>{let t=ev.target;if(t&&t.dataset&&t.dataset.offtakersControl==='toggle')so(!!t.checked)});return o},
txt=(n,s)=>{if(n&&n.textContent!==s)n.textContent=s},
pt=()=>{let d=S.data,n=d?d.dots.filter(r=>S.cls[r.k]&&(r.k!='b'||S.bst[r.t])).length:0,lab=!S.on?BASE:S.busy?BASE+' [LOAD]':S.err?BASE+' [FAIL]':`${BASE} [${N(n)} sites]`,
 st=!S.on?'':S.busy?'Loading the pinned open data…':S.err?'Nothing drawn: '+S.err:`${N(n)} sites drawn (${CK.filter(k=>S.cls[k]).map(k=>CLS[k][0]+' '+N(d.counts[k])).join(' · ')||'no class selected'}) · tap a site for its 15 nearest REPD sites and 5 nearest substations, a data centre for 30 substations, 30 REPD sites and 30 conventional power sites (straight line) · data centres: ${d.pl?`${N(d.pl.  … [line shortened here: 684 characters; full line on GitHub]
 for(let o of S.sfs){if(o.toggle.checked!==S.on)o.toggle.checked=S.on;txt(o.label,lab);o.label.style.opacity=S.err?'0.8':'1';o.ctl.hidden=o.ft.hidden=!S.on;txt(o.st,st);
  for(let k in o.chips){let b=o.chips[k];b.setAttribute('aria-pressed',S.cls[k]);b.classList.toggle('active',S.cls[k])}
  for(let k in o.bchips){let b=o.bchips[k];b.setAttribute('aria-pressed',S.bst[k]);b.classList.toggle('active',S.bst[k])}}if(S.installed)fit()},
ld=async()=>{let sn=++S.serial;S.busy=true;S.err=null;pt();
 try{let o=await rd();if(sn!==S.serial||!S.on)return;S.data=S.data||nm(o.features);S.from=DATA;dw();top();lp(sn)}
 catch(e){if(sn!==S.serial)return;S.err=msg(e);note(e);cx()}finally{if(sn===S.serial){S.busy=false;pt()}}},
/// the data-centre pipeline, read after the sites are drawn (lazily, once per page, pinned and hashed, capped); its records
/// replace the OpenStreetMap data centres; a failure keeps those and says why
lp=sn=>{let d=S.data;if(!DCF||d.pl)return;if(!d.c0){d.c0=d.dots.filter(r=>r.k=='c');sw(d,[])}
 (S.cache.p||(S.cache.p=gx(DCF,DCFSHA,PCAP).then(o=>(o&&o.type==='FeatureCollection'&&AI(o.features)||E('data check failed (not a feature collection)'),dn(o.features))).catch(e=>{S.cache.p=null;throw e})))
 .then(v=>{if(sn!==S.serial||!S.on||d.pl)return;S.pe=null;d.pl=v;sw(d,v.o)},e=>{if(sn===S.serial){S.pe=msg(e);note('data centres: '+S.pe);sw(d,d.c0)}})},
/// swap the data-centre dots (re-indexed; a data-centre card open on a removed dot closes)
sw=(d,a)=>{d.dots=[...d.dots.filter(r=>r.k!='c'),...a];d.dots.forEach((r,i)=>r.i=i);d.counts.c=a.length;if(S.pp&&S.pp.r&&S.pp.r.k=='c'&&!a.includes(S.pp.r))pc();dw();top();pt()},
so=on=>{if(S.on===on)return;S.on=on;let m=mh();
 if(on){if(m&&typeof m.on==='function'){m.on('click',tap);m.on('resize',cpos)}W.addEventListener('gridatlas:card-open',co);ld()}
 else{S.serial++;S.busy=false;S.err=null;cx();if(m&&typeof m.off==='function'){m.off('click',tap);m.off('resize',cpos);m.off('moveend',cw)}W.removeEventListener('gridatlas:card-open',co);pt()}},
fit=()=>{let d=Q('gridatlas-dash-toggle'),b=d&&gr(d),v=b&&b.height;for(let o of S.sfs){let g=o.group,last=!g.nextElementSibling,s=g.style;s.paddingBottom=last?(v?innerHeight-b.top+16:96)+'px':'';s.paddingRight=last&&v?MX(0,gr(g).right-b.left+16)+'px':''}},
put=(host,o)=>{let lg=host.querySelector('[data-lightning-group]');lg?host.insertBefore(o.group,lg):ap(host,o.group);S.sfs.push(o)},
ins=()=>{if(S.installed)return true;let M=NS.menuBar,P=W.__GRIDATLAS_PIPELINE_LAYERS__,host=Q('scada-ui-container'),miss=[];
 if(!(M&&M.installed===true))miss.push('menuBar');if(!(P&&P.installed))miss.push('pipelineLayers');if(!mh())miss.push('map');if(!host||!host.querySelector('.key-group'))miss.push('groups');S.waiting_for=miss;if(miss.length)return false;
 put(host,bg('main'));let cur=Q('fs-curtain-keys');if(cur)put(cur,bg('fs'));S.installed=true;pt();for(let t of[0,1e3,5e3])setTimeout(fit,t);return true};
if(typeof setInterval==='function'&&typeof MutationObserver==='function'){let ob=new MutationObserver(()=>tick()),poll=setInterval(()=>tick(),250),
 tick=()=>{try{if(ins()){clearInterval(poll);ob.disconnect()}}catch(e){note('install: '+msg(e))}};ob.observe(document.documentElement,{childList:true,subtree:true})}
NS.ukOfftakers=Object.freeze({schema:S.schema,generation:GEN,state:S,install:ins,setOn:so});
})();

Menu Bar Instrument Panel Browser

A JavaScript module in the proofs folder of GridAtlas that works with ventus box (`ventusBox`) and attrib samples (`attribSamples`), covering cables.

rendergridatlas / tools/proofs/202609041250-menu-bar-instrument-panel.browser.mjs · lines 1–366 of 366 · version 2026-09-04 12:50 · Entry point · pattern fixtureHtml (shared by 2 files)

What it does
It lists and searches cables. Defines 7 functions or classes, including fixtureHtml, check, ventusBox, attribSamples, panelRects. Uses libraries node:assert/strict, node:path, node:url, playwright. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'panel'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables.
Inputs & outputs
In: form fields (user input).
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
It is built from the fixture HTML helper (`fixtureHtml`), the check step (`check`) and the ventus box helper (`ventusBox`). Proof for: the v8 VENTUS masthead and the SCADA layer panel are restored around the six-menu bar (`atlas/modules/` anything `tools/proofs/menu-bar-attrib-clearance.browser.mjs` or `tools/proofs/menu-bar-mobile-hit.browser.mjs` already prove.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/proofs · JavaScript module
Uses
node:assert/strict, node:path, node:url, playwright
Used by
mentioned in Standalone (comment link)
Produces
fixtureHtml, check, ventusBox, attribSamples, panelRects, gridControlSizes, allPanelControlSizes
Defines here
fixtureHtml, check, ventusBox, attribSamples, panelRects, gridControlSizes, allPanelControlSizes
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/202609041250-menu-bar-instrument-panel.browser.mjs:1-366 · blob 84f8aaeddffe47ab92723f4f36dde6d190ae12c1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env node
/**
 * Proof for generation 202609041250: the v8 VENTUS masthead and the SCADA
 * layer panel are restored around the six-menu bar (atlas/modules/
 * 202609031958-menu-bar.js) instead of being lost to it, without weakening
 * anything tools/proofs/menu-bar-attrib-clearance.browser.mjs or
 * tools/proofs/menu-bar-mobile-hit.browser.mjs already prove.
 *
 * Four measured defects this closes:
 *
 *   E — the masthead race. The architect's "VENTUS branding has been lost"
 *       was the v8 masthead (.hud-header > .ventus-brand) being moved into
 *       a closed About panel on install; measured live, that produced a
 *       masthead visible for the first ~1.5s of every arrival and then torn
 *       out. Checked at every width: the wordmark is present and has a
 *       non-zero, unclipped box BEFORE install (the raw v8 page) and AFTER
 *       install (fused into the bar) -- never absent in between.
 *   C — the SCADA panel. Measured live: #scada-ui-container held 63 real
 *       checkboxes at 17x17 px, 5 px tall, pinned off the bottom of the
 *       viewport, with an inert open/close toggle. Checked: the Grid panel
 *       is closed on arrival, one activation opens it, it carries the real
 *       .scada-brand and .status-legend nodes (moved, not cloned), and
 *       every control inside it -- the <input> itself, not only its label
 *       -- measures >=44 CSS px on its smaller axis.
 *   F — panel anchoring. Measured live: the About panel resolved to x=-95
 *       at 1568 px, a quarter of its own control off the left edge of the
 *       window. Checked, for EACH of the six menus in turn, at four widths:
 *       no panel ever has a negative x and no panel's right edge ever
 *       exceeds the viewport width.
 *   B — attribution occlusion by an open panel, not only by the bar.
 *       Measured live: with the Scope panel open, elementFromPoint at
 *       50/70/90% of the credit's own width resolved to the panel's own
 *       button, even though the credit's top already cleared the bar.
 *       Checked, for EACH of the six menus in turn, at 393 and 1280 px:
 *       elementFromPoint at 10/30/50/70/90% of the credit's width resolves
 *       INSIDE .custom-map-attrib, not a menu bar panel.
 */

import assert from 'node:assert/strict';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const menuPath = path.join(ROOT, 'atlas', 'modules', '202609031958-menu-bar.js');

const SHELL_ATTRIB_CSS = `
.custom-map-attrib { position: absolute; top: 10px; left: 10px; background: rgba(5, 5, 5, 0.7); color: #888; font-family: 'Courier New', monospace; font-size: 9px; border-radius: 4px; padding: 4px 8px; z-index: 10; border: 1px solid #333; pointer-events: auto; max-width: calc(100% - 60px); line-height: 1.6; }
.custom-map-attrib a { color: #00ffff; text-decoration: none; }
body.fs-active .custom-map-attrib { top: 44px; }
`;

// The real v8 masthead and SCADA-panel classes (ventusv8.css, immutable
// shell) -- laid out well enough here for genuine layout/measurement, not
// approximated shorthand.
const SHELL_V8_CSS = `
.dashboard{display:flex;flex-direction:column;height:100vh;width:100vw;box-sizing:border-box}
.hud-header{background:#0a0a0a;border:1px solid #333;padding:6px 12px;display:flex;justify-content:space-between;align-items:center}
.hud-val{font-size:16px;font-weight:bold;color:#0ff}
.ventus-brand{text-align:center;display:flex;flex-direction:column;align-items:center}
.ventus-main{font-size:17px;font-weight:800;color:#fff;letter-spacing:5px;text-transform:uppercase}
.ventus-sub{font-size:6.5px;color:#888;letter-spacing:2px;text-transform:uppercase}
.scada-wrapper{background:#050505;border:1px solid #444;padding:12px}
.scada-brand{display:flex;align-items:center;gap:8px;padding-bottom:8px;margin-bottom:8px;border-bottom:1px solid #222}
.scada-brand-main{font-size:11px;font-weight:800;color:#fff;letter-spacing:4px;text-transform:uppercase}
.scada-brand-sub{font-size:6px;color:#555;letter-spacing:2px;text-transform:uppercase}
.status-legend{display:flex;gap:8px;flex-wrap:wrap;padding:4px 0 6px}
.status-dot{display:inline-flex;align-items:center;gap:4px;font-size:8px;color:#555}
.key-group{border-left:2px solid #333;padding-left:10px;margin-bottom:4px}
.key-title{font-size:10px;color:#6cf;text-transform:uppercase;margin-bottom:6px;font-weight:bold}
.key-item{display:block;min-height:22px}
`;

const engineIds = Array.from({ length: 60 }, (_, index) =>
  index === 37 ? 'dlr' : `engine-${index}`);
const engineControls = engineIds.map((id) => `
  <label class="key-item"><input type="checkbox" data-layer-id="${id}">
    <span data-base-label="${id === 'dlr' ? 'DLR' : id}">${id}</span></label>`).join('');
const pipelineControls = ['same-tech', 'wider-fleet', 'all-pipeline'].map((id) => `
  <label class="key-item"><input type="checkbox" data-pn-layer="${id}">
    <span data-pn-label="${id}">${id}</span></label>`).join('');

function fixtureHtml() {
  return `<!doctype html>
<html><head><meta name="viewport" content="width=device-width,initial-scale=1"><style>
  html,body{margin:0;width:100%;height:100%;font:12px sans-serif;background:#071217}
  .map-container{position:relative;width:100%;height:100%}
  .map-controls{position:absolute;top:50px;left:4px}
  ${SHELL_V8_CSS}
  ${SHELL_ATTRIB_CSS}
</style></head><body>
  <div id="dashboard" class="dashboard">
  <div class="hud-header">
    <div><small>SYSTEM TIME</small><br><span class="hud-val" id="clock">13:00:00</span></div>
    <div class="ventus-brand"><div class="ventus-main">Ventus</div>
      <div class="ventus-sub">Cables &amp; Connectivity&reg;</div></div>
    <div><small>2050 TARGET</small><br><span class="hud-val" id="days">8519 DAYS</span></div>
  </div>
  <div id="map-container" class="map-container">
    <div class="search-bar-wrapper"><input class="search-input" id="search-input"><div id="search-results"></div></div>
    <div class="map-controls">
      <button id="btn-export">Export</button><button id="btn-status">Status</button>
      <button id="btn-radius">Radius</button><button id="btn-radius-area">Area</button>
      <button id="btn-zonedraw">Zone</button><button id="btn-measure">Measure</button>
    </div>
    <button id="btn-fullscreen">Fullscreen</button>
    <div class="custom-map-attrib">Data &copy; <a href="#">OpenStreetMap contributors</a> | &copy; CARTO | EV data &copy; <a href="#">Open Charge Map</a></div>
  </div>
  <div class="scada-wrapper">
    <div class="scada-brand"><div><div class="scada-brand-main">Ventus</div>
      <div class="scada-brand-sub">Cables &amp; Connectivity&reg;</div></div></div>
    <div class="status-legend">
      <div class="status-dot"><span style="background:#0f8"></span>Operational</div>
      <div class="status-dot"><span style="background:#fc0"></span>Under Construction</div>
    </div>
    <div id="scada-ui-container">
      <div class="key-group"><div class="key-title">Engine layers</div>${engineControls}</div>
      <div class="key-group"><div class="key-title">Pipeline News</div>${pipelineControls}</div>
    </div>
  </div>
  <button id="gridatlas-dash-toggle">Layers</button>
  <button id="btn-fullscreen-exit">Exit</button>
  <div id="fs-curtain-tab">Layers</div>
  <button id="gridatlas-version-ledger">Versions</button>
  </div>
</body></html>`;
}

const failures = [];
function check(label, condition, detail) {
  if (condition) {
    console.log(`  [PASS] ${label}`);
  } else {
    console.log(`  [FAIL] ${label}${detail ? ' -- ' + detail : ''}`);
    failures.push(label);
  }
}

async function ventusBox(page) {
  return page.evaluate(() => {
    const nodes = Array.from(document.querySelectorAll('.ventus-main'))
      .filter((node) => node.getBoundingClientRect().width > 0
        && node.getBoundingClientRect().height > 0
        && getComputedStyle(node).visibility !== 'hidden'
        && getComputedStyle(node).display !== 'none');
    if (!nodes.length) return null;
    const rect = nodes[0].getBoundingClientRect();
    return { width: rect.width, height: rect.height, text: nodes[0].textContent.trim() };
  });
}

async function attribSamples(page) {
  return page.evaluate(() => {
    const node = document.querySelector('.custom-map-attrib');
    if (!node) return null;
    const rect = node.getBoundingClientRect();
    const fractions = [0.1, 0.3, 0.5, 0.7, 0.9];
    const y = rect.top + rect.height / 2;
    return fractions.map((fraction) => {
      const x = rect.left + rect.width * fraction;
      const top = document.elementFromPoint(x, y);
      return {
        fraction, x, y,
        insideAttrib: !!top && (top === node || node.contains(top)),
        hit: top ? `${top.tagName}#${top.id}.${String(top.className).slice(0, 40)}` : null,
      };
    });
  });
}

async function panelRects(page) {
  return page.evaluate(() => {
    const vw = innerWidth;
    return Array.from(document.querySelectorAll('#gridatlas-menu-bar .gm-panel'))
      .filter((panel) => !panel.hidden)
      .map((panel) => {
        const rect = panel.getBoundingClientRect();
        return {
          id: panel.id, left: rect.left, right: rect.right, width: rect.width,
          withinViewport: rect.left >= -0.5 && rect.right <= vw + 0.5,
        };
      });
  });
}

async function gridControlSizes(page) {
  return page.evaluate(() => {
    const grid = document.getElementById('gridatlas-menu-bar-panel-4'); // Grid is index 4
    if (!grid) return null;
    const inputs = Array.from(grid.querySelectorAll('input'));
    return inputs.map((input) => {
      const rect = input.getBoundingClientRect();
      return Math.min(rect.width, rect.height);
    });
  });
}

async function allPanelControlSizes(page) {
  // Scoped to the panel that is actually open: a hidden sibling panel's
  // controls legitimately measure 0x0 (display:none) and are not part of
  // what this check is asking about. A control the shell itself hides by
  // design in this state (body:not(.fs-active) #btn-fullscreen-exit, for
  // instance) is excluded the same way -- display:none, not a size fault.
  return page.evaluate(() => {
    const controls = Array.from(document.querySelectorAll(
      '#gridatlas-menu-bar .gm-panel:not([hidden]) button, '
      + '#gridatlas-menu-bar .gm-panel:not([hidden]) [role="button"], '
      + '#gridatlas-menu-bar .gm-panel:not([hidden]) input'))
      .filter((node) => {
        const style = getComputedStyle(node);
        return style.display !== 'none' && style.visibility !== 'hidden';
      });
    return controls.map((node) => {
      const rect = node.getBoundingClientRect();
      return { tag: node.tagName, id: node.id, min: Math.min(rect.width, rect.height) };
    });
  });
}

const WIDTHS_PANEL_CONTAINMENT = [393, 456, 1280, 1568];
const WIDTHS_ATTRIB = [393, 1280];

const browser = await chromium.launch({ headless: true });
try {
  const context = await browser.newContext();
  const page = await context.newPage();
  const pageErrors = [];
  page.on('pageerror', (error) => pageErrors.push(String(error?.message || error)));

  // ---- Defect E: the masthead must never disappear across the install
  //      transition, at a representative phone and desktop width. ----
  for (const width of [393, 1280]) {
    const ctx = await browser.newContext({ viewport: { width, height: 900 } });
    const p = await ctx.newPage();
    await p.setContent(fixtureHtml());

    const before = await ventusBox(p);
    check(`${width}px: VENTUS wordmark present and visible in the raw v8 page, before install`,
      !!before && before.width > 0 && before.height > 0, JSON.stringify(before));

    await p.addScriptTag({ path: menuPath });
    await p.waitForFunction(() => window.__GRIDATLAS_MODULES__?.menuBar?.installed === true);
    await p.evaluate(() => new Promise((resolve) => requestAnimationFrame(() =>
      requestAnimationFrame(resolve))));

    const after = await ventusBox(p);
    check(`${width}px: VENTUS wordmark still present and visible immediately after install `
      + '(fused into the bar, not moved into a closed panel)',
      !!after && after.width > 0 && after.height > 0, JSON.stringify(after));
    check(`${width}px: the wordmark text itself is unchanged across the transition`,
      before && after && before.text === after.text, `${before?.text} -> ${after?.text}`);

    await ctx.close();
  }

  // ---- Defect C: the SCADA panel -- closed on arrival, one activation
  //      opens it, real branded nodes, every control >=44px. ----
  {
    const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
    const p = await ctx.newPage();
    await p.setContent(fixtureHtml());
    await p.addScriptTag({ path: menuPath });
    await p.waitForFunction(() => window.__GRIDATLAS_MODULES__?.menuBar?.installed === true);

    const closedOnArrival = await p.evaluate(() =>
      document.getElementById('gridatlas-menu-bar-panel-4').hidden === true);
    check('the Grid panel is closed on arrival', closedOnArrival === true);

    await p.getByRole('button', { name: 'Grid', exact: true }).click();
    const openAfterOneClick = await p.evaluate(() =>
      document.getElementById('gridatlas-menu-bar-panel-4').hidden === false);
    check('one activation of Grid opens the panel', openAfterOneClick === true);

    const branded = await p.evaluate(() => {
      const grid = document.getElementById('gridatlas-menu-bar-panel-4');
      return {
        brand: !!grid.querySelector('.scada-brand-main'),
        legend: !!grid.querySelector('.status-legend'),
      };
    });
    check('the restored panel carries the real .scada-brand node (moved, not cloned)',
      branded.brand === true);
    check('the restored panel carries the real .status-legend node',
      branded.legend === true);

    const sizes = await gridControlSizes(p);
    check(`every one of the ${sizes?.length ?? 0} Grid layer controls measures >=44px on its `
      + 'smaller axis (the <input> itself, not only its label)',
      Array.isArray(sizes) && sizes.length === 63
      && sizes.every((size) => size >= 44),
      sizes ? `min=${Math.min(...sizes)}` : 'no controls found');

    // Every control in every panel, not only Grid's.
    for (const name of ['File', 'Edit', 'View', 'Scope', 'About']) {
      await p.getByRole('button', { name, exact: true }).click();
      const controls = await allPanelControlSizes(p);
      const under = controls.filter((c) => c.min < 44);
      check(`${name}: every panel control (${controls.length} visible) measures >=44px on its `
        + 'smaller axis',
        under.length === 0,
        under.map((c) => `${c.tag}#${c.id}:${c.min.toFixed(1)}`).join(', '));
    }

    await ctx.close();
  }

  // ---- Defect F: no panel ever resolves negative-x or off the right
  //      edge, with each of the six menus opened in turn. ----
  for (const width of WIDTHS_PANEL_CONTAINMENT) {
    const ctx = await browser.newContext({ viewport: { width, height: 900 } });
    const p = await ctx.newPage();
    await p.setContent(fixtureHtml());
    await p.addScriptTag({ path: menuPath });
    await p.waitForFunction(() => window.__GRIDATLAS_MODULES__?.menuBar?.installed === true);

    for (const name of ['File', 'Edit', 'View', 'Scope', 'Grid', 'About']) {
      await p.getByRole('button', { name, exact: true }).click();
      const rects = await panelRects(p);
      const bad = rects.filter((r) => !r.withinViewport);
      check(`${width}px, ${name} panel: fully within the viewport (no negative x, no `
        + 'overflow past the right edge)',
        rects.length > 0 && bad.length === 0,
        bad.map((r) => `${r.id} left=${r.left.toFixed(1)} right=${r.right.toFixed(1)}`).join(', '));
    }
    await ctx.close();
  }

  // ---- Defect B: attribution outranks every open panel, sampled across
  //      its own width, not only its centre. ----
  for (const width of WIDTHS_ATTRIB) {
    const ctx = await browser.newContext({ viewport: { width, height: 900 } });
    const p = await ctx.newPage();
    await p.setContent(fixtureHtml());
    await p.addScriptTag({ path: menuPath });
    await p.waitForFunction(() => window.__GRIDATLAS_MODULES__?.menuBar?.installed === true);
    await p.evaluate(() => new Promise((resolve) => requestAnimationFrame(() =>
      requestAnimationFrame(resolve))));

    for (const name of ['File', 'Edit', 'View', 'Scope', 'Grid', 'About']) {
      await p.getByRole('button', { name, exact: true }).click();
      const samples = await attribSamples(p);
      const covered = (samples || []).filter((s) => !s.insideAttrib);
      check(`${width}px, ${name} panel open: attribution unoccluded across its full width `
        + '(10/30/50/70/90%), not only its centre',
        Array.isArray(samples) && samples.length === 5 && covered.length === 0,
        covered.map((s) => `${Math.round(s.fraction * 100)}%->${s.hit}`).join(', '));
    }
    await ctx.close();
  }

  assert.deepEqual(pageErrors, [], `page errors: ${pageErrors.join(' | ')}`);
  await context.close();

  console.log(`\n${failures.length === 0 ? 'ALL' : 'SOME'} checks passed (${failures.length} failure(s))`);
  if (failures.length) {
    console.error('\nFAILURES');
    for (const failure of failures) console.error('  ' + failure);
    process.exitCode = 1;
  } else {
    console.log('the VENTUS masthead survives install at every width, the SCADA panel is '
      + 'closed on arrival with every control >=44px, no panel ever resolves outside the '
      + 'viewport, and the attribution outranks every open panel across its full width.');
  }
} finally {
  await browser.close();
}

V8 Layers Panel Restored Proof

A JavaScript module in the proofs folder of GridAtlas. It is built from the composed step (`composed`) and the check step (`check`).

storagegridatlas / tools/proofs/v8-layers-panel-restored.proof.mjs · lines 1–101 of 101 · Not reached from any entry point (candidate for review) · pattern composed (shared by 4 files)

What it does
It loads data. Defines composed, check. Uses libraries node:fs/promises, node:path, node:url. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'panel'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file current.json.
What it achieves
The v8 layers panel is back beneath the menus, asserted against the COMPOSED bytes named by `atlas/current.json` - never against the parts.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · tools/proofs · JavaScript module
Uses
node:fs/promises, node:path, node:url
Used by
none found
Produces
composed, check
Defines here
composed, check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/proofs/v8-layers-panel-restored.proof.mjs:1-101 · blob 07f5addb2857a16d799a11113e9b99f28bffb7b5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process, storage · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
/* The v8 layers panel is back beneath the menus, asserted against the
 * COMPOSED bytes named by atlas/current.json - never against the parts.
 *
 * What was measured on live v9.115 at 1400x900 and at an iPhone 13 viewport,
 * 202609041957: all 60 engine layer switches present in the DOM, every
 * container holding them at 0x0 or display:none, scrollHeight equal to the
 * viewport so the page could not even scroll to them - ZERO of 120 layer
 * controls reachable without first opening a menu. The rule responsible was
 * one line: '.gridatlas-menu-hosted .scada-wrapper{display:none!important}',
 * justified by a circular argument (the rule hid the panel, so the panel's
 * toggle looked inert, which justified the rule).
 *
 * The architect's instruction, 2026-09-04: "restore v8 panels but keep
 * dropdowns file, edit, scope, grid, about" - both, not either. And: "don't
 * lose the grid engines" - so the arrival and its measurement are proven
 * separately by deep-link-visibility.browser.mjs and the five-case arrival
 * proof, run against the same composed bytes, before this generation ships.
 *
 * Run: node tools/proofs/v8-layers-panel-restored.proof.mjs
 */

import { readFile } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const REPO = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
const ATLAS = join(REPO, 'atlas');
const current = JSON.parse(await readFile(join(ATLAS, 'current.json'), 'utf8'));
const byId = new Map(current.cartridges.map(c => [c.id, c]));

async function composed(id) {
    const entry = byId.get(id);
    if (!entry) throw new Error('no cartridge ' + id + ' in current.json');
    return (await readFile(join(ATLAS, entry.path.replace(/^\.\//, '')), 'utf8'))
        .replace(/\r\n/g, '\n');
}

const intelligence = await composed('substation-intelligence');   // carries the menu bar
const sld = await composed('sld-sandbox');                         // carries the panel default

const failures = [];
let passed = 0;
const check = (name, ok) => { if (ok) passed += 1; else failures.push(name); };

/* ── The panel is shown, not hidden ─────────────────────────────────────── */

check('the rule that hid the whole v8 layers panel is gone from the served bytes',
    !/\.gridatlas-menu-hosted \.scada-wrapper\{display:none!important\}/.test(intelligence));

check('and the panel is positively shown beneath the menu bar, as v8 always drew it',
    /\.gridatlas-menu-hosted \.scada-wrapper\{display:flex!important\}/.test(intelligence));

check('the panel\'s own show/hide toggle is no longer hidden by the menu bar - '
    + 'with the panel restored it is the only control that opens and closes it',
    /if \(dashToggle\) dashToggle\.hidden = false;/.test(intelligence)
    && !/if \(dashToggle\) dashToggle\.hidden = true;/.test(intelligence)
    && /#gridatlas-dash-toggle\{display:inline-flex!important\}/.test(intelligence));

/* ── The menus stay ─────────────────────────────────────────────────────── */

check('all six dropdowns survive, in order: the architect asked for both, not either',
    /var MENUS = \['File', 'Edit', 'View', 'Scope', 'Grid', 'About'\];/.test(intelligence));

check('the Grid dropdown still proxies the same original inputs the panel shows, so '
    + 'the two surfaces cannot disagree about which layer is on',
    /data-gridatlas-layer-proxy/.test(intelligence));

/* ── One identity surface is still honoured ─────────────────────────────── */

check('the VENTUS wordmark is still fused into the bar and the SCADA brand node is '
    + 'MOVED into the Grid panel head, not cloned - restoring the panel does not '
    + 'bring back a second wordmark',
    /gm-brand-slot/.test(intelligence)
    && /\.gridatlas-menu-hosted #fs-letterhead\{display:none!important\}/.test(intelligence));

/* ── The default is right for each screen ───────────────────────────────── */

check('on a phone the panel starts collapsed - measured, an open panel held 31.6% of '
    + 'a 393x852 screen against the map\'s 29.3% - and on a desktop it starts open, '
    + 'as v8 always did',
    /let collapsed = coarse \|\| \(isFinite\(width\) && width > 0 && width <= 700\);/.test(sld));

check('an UNKNOWN width is not a phone: the width must be a real positive number '
    + 'before it argues for starting collapsed, so a host that publishes none gets '
    + 'the desktop default rather than an empty-looking page',
    /width > 0 && width <= 700/.test(sld)
    && !/let collapsed = true;/.test(sld));

check('a choice the reader has already made still wins over both defaults',
    /window\.localStorage\.getItem\(KEY\)/.test(sld)
    && /if \(v !== null\) collapsed = v === '1';/.test(sld));

/* ── Report ─────────────────────────────────────────────────────────────── */

if (failures.length) {
    console.error('v8 layers panel proof FAILED (' + failures.length + ' of '
        + (failures.length + passed) + '):\n- ' + failures.join('\n- '));
    process.exit(1);
}
console.log('v8 layers panel restored: PASS — ' + passed + ' checks against the '
    + 'composed bytes of generation ' + current.generation);