GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / claude / sessions/202609031559-skin-architecture/prototype

Skin Architecture — Prototype Page

A web page in the sessions folder of Claude that draws desktop, glanceable, tenfoot and broken compact. It paints switcher (`paintSwitcher`), applies tokens (`applyTokens`) and renders shell (`renderShell`).

700 lines of HTML from claude, in 1 file. Topic: AI agents and coordination. Section 1616 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. Skin Architecture — Prototype Page render · claude / sessions/202609031559-skin-architecture/prototype/index.html lines 1–700

Skin Architecture — Prototype Page

A web page in the sessions folder of Claude that draws desktop, glanceable, tenfoot and broken compact. It paints switcher (`paintSwitcher`), applies tokens (`applyTokens`) and renders shell (`renderShell`).

renderclaude / sessions/202609031559-skin-architecture/prototype/index.html · lines 1–700 of 710 · version 2026-09-03 15:59 · Entry point · pattern drawMap (shared by 3 files)

What it does
It draws desktop, glanceable, tenfoot and broken compact. Defines 20 functions or classes, including $, cls, show, fill, paintSwitcher. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV.
Inputs & outputs
In: JSON file desktop.json; JSON file glanceable.json; JSON file tenfoot.json; JSON file broken-compact.json; JSON file substations.json; form fields (user input). Out: web page; canvas drawing. Voltage levels named: 400kV.
Downstream impact
It is itself an entry point (page); no other file was found loading it.
What it achieves
Defines `cls`, `show`, `fill` and 15 more. Its code works with 400 kV. It reads `substations.json`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
claude · sessions/202609031559-skin-architecture/prototype · page
Uses
Engine (script src)
Used by
none found
Produces
$, cls, show, fill, paintSwitcher, applyTokens, renderShell, drawMap, px, currentReading, render, sync
Defines here
$, cls, show, fill, paintSwitcher, applyTokens, renderShell, drawMap, px, currentReading, render, sync, live, rnd, paintStats, paintFacets, sec, paintRows, note, refresh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
claude@df9da02425fdf0c65d11a84f32cd9b3ef927b309 sessions/202609031559-skin-architecture/prototype/index.html:1-700 · blob 20e60bdce94e726d1cfcb0d5492f9f0e1c2ecf71 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unknown
<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GridAtlas — skin architecture prototype</title>
<style>
  :root{
    --page:#070f0d; --card:#0d1a17; --rule:#1d3a34; --ink:#cfe9e4; --dim:#7f9a95;
    --hot:#7ff3d8; --warn:#f0c674; --bad:#ff7a7a; --scen:#ff8fbf;
    --mono:ui-monospace,"Cascadia Mono","SF Mono",Menlo,Consolas,monospace;
  }
  *{box-sizing:border-box}
  html,body{margin:0;background:var(--page);color:var(--ink);font:13px/1.5 var(--mono)}
  a{color:var(--hot)}
  h1{font-size:16px;margin:0;letter-spacing:.14em;text-transform:uppercase}
  h2{font-size:12px;margin:0 0 10px;letter-spacing:.18em;text-transform:uppercase;color:var(--dim)}
  .wrap{max-width:1500px;margin:0 auto;padding:18px 20px 80px}
  .bar{display:flex;flex-wrap:wrap;gap:12px;align-items:center;
       border-bottom:1px solid var(--rule);padding-bottom:14px;margin-bottom:18px}
  .grow{flex:1 1 auto}
  .panel{border:1px solid var(--rule);background:var(--card);border-radius:6px;padding:14px;margin-bottom:16px}
  .cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(330px,1fr));gap:16px;align-items:start}
  button{font:inherit;background:#12241f;color:var(--ink);border:1px solid var(--rule);
         border-radius:4px;padding:9px 12px;min-height:44px;cursor:pointer}
  button:hover{border-color:var(--hot)}
  button[aria-pressed=true]{background:var(--hot);color:#04120e;border-color:var(--hot);font-weight:700}
  button.slim{min-height:30px;padding:4px 9px}
  .tag{display:inline-block;padding:2px 7px;border-radius:99px;font-size:10px;letter-spacing:.1em;
       text-transform:uppercase;border:1px solid var(--rule);color:var(--dim)}
  .tag.auto{border-color:var(--warn);color:var(--warn)}
  .tag.chosen{border-color:var(--hot);color:var(--hot)}
  .tag.url{border-color:var(--scen);color:var(--scen)}
  table{border-collapse:collapse;width:100%;font-size:12px}
  th,td{text-align:left;padding:4px 8px;border-bottom:1px solid #14282400;vertical-align:top}
  tbody tr:nth-child(odd){background:#0a1613}
  th{color:var(--dim);font-weight:400;border-bottom:1px solid var(--rule)}
  td.v{color:var(--hot)}
  td.v.off{color:var(--dim)}
  td.v.absent{color:var(--bad)}
  .note{color:var(--dim);font-size:11.5px;line-height:1.55}
  .bad{color:var(--bad)} .warn{color:var(--warn)} .ok{color:var(--hot)}
  code{color:var(--warn)}

  /* ---------- the stage: skins render here ---------- */
  .stage{display:flex;gap:18px;flex-wrap:wrap;align-items:flex-start}
  .device{border:1px solid var(--rule);border-radius:10px;overflow:hidden;background:#000;
          box-shadow:0 0 0 6px #0b1512}
  .device .cap{font-size:10.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--dim);
               padding:6px 10px;background:#0b1613;border-bottom:1px solid var(--rule);
               display:flex;justify-content:space-between;gap:10px}
  .device .cap b{color:var(--ink);font-weight:400}

  /* The SHELL. Every skin is this markup; only custom properties change. */
  .shell{position:relative;overflow:hidden;background:var(--sk-ground);color:var(--sk-ink);
         font-size:calc(var(--sk-base) * 1px);line-height:var(--sk-lh)}
  .shell .surface{position:absolute;inset:0}              /* full-bleed by default */
  .shell canvas.map{position:absolute;inset:0;width:100%;height:100%}
  .shell .card{position:absolute;background:var(--sk-panel);padding:calc(var(--sk-base)*0.85px);
               overflow:auto;-webkit-overflow-scrolling:touch}
  .shell[data-chrome="right-panel"] .card{top:10px;right:10px;bottom:10px;width:var(--sk-panelw);
        border:1px solid var(--sk-rule);border-radius:6px}
  .shell[data-chrome="none"] .card{left:0;right:0;bottom:0;max-height:100%;
        border-top:1px solid var(--sk-rule)}
  .shell[data-chrome="bottom-band"] .card{left:5%;right:5%;bottom:5%;max-height:60%;
        border:2px solid var(--sk-rule);border-radius:10px}
  .shell .title{font-size:calc(var(--sk-base)*1.15px);font-weight:700;margin:0 0 .35em}
  .shell .hero{font-size:calc(var(--sk-hero)*1px);color:var(--sk-hero-c);font-weight:700;
               line-height:1.15;margin:.15em 0}
  .shell .stat{font-size:calc(var(--sk-base)*1.25px);color:var(--sk-hero-c)}
  .shell .line{margin:.15em 0}
  .shell .dim,.shell .note{color:var(--sk-dim);font-size:calc(var(--sk-base)*0.82px);margin:.3em 0}
  .shell .group{color:var(--sk-dim);text-transform:uppercase;letter-spacing:.14em;
                font-size:calc(var(--sk-base)*0.72px);margin:.9em 0 .1em;
                border-top:1px solid var(--sk-rule);padding-top:.6em}
  .shell .qualifier{color:var(--sk-ink);opacity:.92;font-size:calc(var(--sk-base)*0.82px);
                margin:.25em 0;border-left:2px solid var(--sk-rule);padding-left:.6em}
  .shell .badge{display:inline-block;font-size:calc(var(--sk-base)*0.7px);letter-spacing:.12em;
                text-transform:uppercase;padding:.25em .6em;border-radius:99px;margin-bottom:.5em;
                border:1px solid var(--sk-rule);color:var(--sk-dim)}
  .shell .badge[data-scenario="1"]{border-color:var(--sk-scen);color:#1a0b13;
                background:var(--sk-scen);font-weight:700}
  .shell .notice{color:var(--sk-warn);font-size:calc(var(--sk-base)*0.86px);margin:.35em 0}
  .shell .refusal{padding:14px;color:#ffb3b3;background:#2a0e0e;border:1px solid #6b2020;
                  border-radius:6px;font-size:12px;line-height:1.5}
  .shell .refusal b{color:#ff7a7a}
  .shell[data-scenario="1"]{outline:3px solid var(--sk-scen);outline-offset:-3px}

  /* ---------- layer panel ---------- */
  .lp{display:grid;grid-template-columns:190px 1fr;gap:14px}
  .facet{font-size:11.5px}
  .facet h3{font-size:10.5px;letter-spacing:.14em;text-transform:uppercase;color:var(--dim);
            margin:12px 0 4px;font-weight:400}
  .facet button{display:block;width:100%;text-align:left;min-height:26px;padding:2px 7px;
                margin-bottom:2px;font-size:11.5px;border-color:#14282400;background:#0a1613}
  .facet button[aria-pressed=true]{background:var(--hot);color:#04120e}
  .vlist{height:300px;overflow:auto;border:1px solid var(--rule);border-radius:4px;position:relative;
         background:#08120f}
  .vlist .spacer{position:relative}
  .vrow{position:absolute;left:0;right:0;height:30px;display:flex;align-items:center;gap:8px;
        padding:0 8px;border-bottom:1px solid #0f1f1b;font-size:11.5px;white-space:nowrap}
  .vrow .nm{flex:1 1 auto;overflow:hidden;text-overflow:ellipsis}
  .vrow .st{width:78px;text-align:right;font-size:10px;letter-spacing:.08em;text-transform:uppercase}
  .st.declared{color:#54706b} .st.loaded{color:var(--hot)} .st.minimised{color:var(--warn)}
  .st.loading{color:var(--scen)}
  .log{height:120px;overflow:auto;background:#08120f;border:1px solid var(--rule);border-radius:4px;
       padding:6px 8px;font-size:11px;color:var(--dim)}
  input[type=range]{width:100%}
  input[type=search],input[type=text]{font:inherit;background:#08120f;color:var(--ink);
       border:1px solid var(--rule);border-radius:4px;padding:8px;width:100%;min-height:38px}
  .kv{display:grid;grid-template-columns:auto 1fr;gap:2px 12px;font-size:11.5px}
  .kv dt{color:var(--dim)} .kv dd{margin:0;color:var(--ink)}
</style>
</head>
<body>
<div class="wrap">

  <div class="bar">
    <h1>GridAtlas · skin architecture</h1>
    <span class="tag" id="genTag">engine 202609031316 · v9.89</span>
    <span class="grow"></span>
    <span class="note" id="visNote"></span>
  </div>

  <!-- ============ PART 2: the switch ============ -->
  <div class="panel">
    <h2>Active skin — detection chooses the default, you choose the truth</h2>
    <div class="bar" style="border:0;margin:0;padding:0">
      <span id="skinButtons" style="display:flex;gap:8px;flex-wrap:wrap"></span>
      <span class="grow"></span>
      <span id="howTag" class="tag"></span>
      <button class="slim" id="resetSkin">Reset to automatic</button>
      <button class="slim" id="copyPin">Copy a link that pins this skin</button>
    </div>
    <p class="note" id="whyLine"></p>
  </div>

  <!-- ============ PART 3: the stage ============ -->
  <div class="panel">
    <h2>One engine, three shells — the identical reading, rendered by three declarative skins</h2>
    <div class="bar" style="border:0;margin:0 0 12px;padding:0">
      <label class="note">Project&nbsp;
        <select id="subjectPick" style="font:inherit;background:#08120f;color:var(--ink);border:1px solid var(--rule);border-radius:4px;padding:7px;min-height:38px"></select>
      </label>
      <label class="note" style="min-width:230px">Move it east/west&nbsp;<span id="dxLabel">0.00°</span>
        <input type="range" id="dx" min="-250" max="250" value="0"></label>
      <label class="note" style="min-width:230px">Move it north/south&nbsp;<span id="dyLabel">0.00°</span>
        <input type="range" id="dy" min="-250" max="250" value="0"></label>
      <label class="note" style="min-width:200px">Capacity&nbsp;<span id="mwLabel"></span>
        <input type="range" id="mw" min="1" max="3000" value="840"></label>
      <button class="slim" id="resetScenario">Back to the record</button>
      <button class="slim" id="simRecompute">Show the recomputing state</button>
    </div>
    <div class="stage" id="stage"></div>
    <p class="note" id="engineCall"></p>
  </div>

  <!-- ============ the refusal ============ -->
  <div class="panel">
    <h2>The gate — a skin that drops a qualifier does not render</h2>
    <p class="note">
      <code>skins/broken-compact.json</code> is a plausible, well-meaning skin: name the substation,
      print the number, drop the sentences to save space. Nothing in the engine mentions it by name.
      It is refused because <code>FIELDS['measurement.headline'].mandatory_with</code> says a
      superlative may not appear without the sample, the word <b>straight</b>, and the record/scenario
      marker <b>in the same view</b>.
    </p>
    <div class="stage" id="brokenStage"></div>
  </div>

  <!-- ============ PART 1: detection ============ -->
  <div class="panel">
    <h2>Part 1 — what this browser will actually tell us</h2>
    <div class="cols">
      <div><table id="probeA"></table></div>
      <div><table id="probeB"></table></div>
    </div>
    <p class="note" id="probeNote"></p>
  </div>

  <!-- ============ 1000 layers ============ -->
  <div class="panel">
    <h2>The layer registry at 1000 — declared is cheap, loaded is not, minimised is not unloaded</h2>
    <div class="bar" style="border:0;margin:0 0 10px;padding:0">
      <span class="note" id="regStats"></span>
      <span class="grow"></span>
      <button class="slim" id="loadTen">Load 10 more</button>
      <button class="slim" id="hitCeiling">Load until the ceiling refuses</button>
      <button class="slim" id="minAll">Minimise everything loaded</button>
      <button class="slim" id="healthBtn">Check health against the map</button>
      <button class="slim" id="corruptBtn">Corrupt one layer behind the registry's back</button>
    </div>
    <div class="lp">
      <div class="facet" id="facets"></div>
      <div>
        <input type="search" id="layerSearch" placeholder="Search 1000 layers — the list is never a list">
        <p class="note" id="listNote" style="margin:6px 0"></p>
        <div class="vlist" id="vlist"><div class="spacer" id="spacer"></div></div>
        <p class="note" style="margin:8px 0 4px">Registry events — health is observed, never self-reported:</p>
        <div class="log" id="log"></div>
      </div>
    </div>
  </div>

  <p class="note">
    Prototype only. Not deployed to gridatlas, not part of any Atlas composition.
    Session <code>202609031559-skin-architecture</code>.
  </p>
</div>

<script src="engine.js"></script>
<script>
(async () => {
  'use strict';
  const E = window.GRIDATLAS_ENGINE;
  const $ = s => document.querySelector(s);

  /* --------------------------------------------------------------
     0. Load the skins. Adding a skin is: drop a .json in skins/ and
        add its filename here. No engine change, no host change.
     -------------------------------------------------------------- */
  const SKIN_FILES = ['desktop.json', 'glanceable.json', 'tenfoot.json', 'broken-compact.json'];
  const skins = [];
  for (const f of SKIN_FILES) {
    try { skins.push(await (await fetch('skins/' + f)).json()); }
    catch (err) { console.warn('skin failed to load: ' + f, err); }
  }
  const SHOWN = skins.filter(s => s.id !== 'broken-compact');
  const BROKEN = skins.find(s => s.id === 'broken-compact');

  /* --------------------------------------------------------------
     1. Data. Real substations, real coordinates, real voltages.
     -------------------------------------------------------------- */
  const subsDoc = await (await fetch('substations.json')).json();
  const SUBS = subsDoc.rows.map(r => ({ name: r[0] || 'Unnamed substation', kv: r[1], at: [r[2], r[3]] }));

  const SUBJECTS = [
    { id: 'botley', name: 'Botley West, Botley — Botley West Solar Project', repd_ref: 12588,
      capacity_mw: 840, technology: 'solar', status: 'application submitted',
      address: 'Botley West, Botley, Oxford · OX29 4DZ · Oxfordshire',
      at: [-1.3489728, 51.8132088] },
    { id: 'ossian', name: 'Ossian', repd_ref: 13429, capacity_mw: 3600,
      technology: 'wind_offshore', status: 'application submitted',
      address: 'Offshore', at: [0.15, 53.88] },
    { id: 'worthing', name: 'Worthing Heat Network — Energy Centre', repd_ref: 15205,
      capacity_mw: 3, technology: 'other', status: 'application submitted',
      address: 'Worthing', at: [-0.36839, 50.81255] }
  ];

  /* --------------------------------------------------------------
     2. Detection matrix
     -------------------------------------------------------------- */
  const P = E.probe();
  $('#visNote').innerHTML = P.hidden
    ? '<span class="bad">document.hidden = true</span> — rendering measurements from this tab are not trustworthy. Detection values below are static device facts and are unaffected.'
    : '<span class="ok">document.hidden = false</span> — the tab is visible.';

  const RELIABLE = {
    pointer_coarse:'reliable, but only about the PRIMARY input',
    pointer_fine:'reliable', pointer_none:'reliable',
    any_pointer_coarse:'reliable — the honest one for hybrids',
    hover_hover:'reliable', any_hover_hover:'reliable',
    maxTouchPoints:'reliable', innerWidth:'reliable', innerHeight:'reliable',
    screenWidth:'reliable', screenHeight:'reliable', dpr:'reliable',
    uad_mobile:'coarse — a 2-value flag; a tablet, a TV and a car all say false',
    uad_platform:'reliable but useless for form factor',
    uad_brands:'reliable', deviceMemory:'BUCKETED (0.25/0.5/1/2/4/8) and capped at 8',
    hardwareConcurrency:'reliable', effectiveType:'a guess, and it changes',
    saveData:'reliable when true; false means nothing',
    reduced_motion:'reliable', dark:'reliable', orientation:'reliable',
    nav_tv:'UA sniffing — brittle, but it is the ONLY TV signal there is',
    nav_watch:'UA sniffing', nav_car:'UA sniffing', standalone:'reliable', hidden:'reliable'
  };
  const rowsA = ['hidden','pointer_coarse','pointer_fine','pointer_none','any_pointer_coarse',
                 'hover_hover','any_hover_hover','maxTouchPoints','innerWidth','innerHeight',
                 'screenWidth','screenHeight','dpr'];
  const rowsB = ['uad_mobile','uad_platform','uad_brands','deviceMemory','hardwareConcurrency',
                 'effectiveType','saveData','reduced_motion','dark','orientation',
                 'nav_tv','nav_watch','nav_car','standalone'];
  const cls = v => v === null || v === undefined ? 'v absent' : (v === false ? 'v off' : 'v');
  const show = v => v === null || v === undefined ? 'ABSENT / UNSUPPORTED' : String(v);
  const fill = (el, keys) => {
    el.innerHTML = '<thead><tr><th>signal</th><th>value here</th><th>how far to trust it</th></tr></thead><tbody>'
      + keys.map(k => `<tr><td>${k}</td><td class="${cls(P[k])}">${show(P[k])}</td>`
        + `<td class="note">${RELIABLE[k] || ''}</td></tr>`).join('') + '</tbody>';
  };
  fill($('#probeA'), rowsA); fill($('#probeB'), rowsB);
  $('#probeNote').innerHTML =
    'A TV and this laptop both report <code>pointer: fine</code> and <code>hover: hover</code>. '
    + 'Nothing in this table separates them except user-agent sniffing, which is not a measurement. '
    + '<b>That is the whole argument for the switcher:</b> the two environments that most need '
    + 'different layouts are the two the browser cannot tell apart.';

  /* --------------------------------------------------------------
     3. Skin selection — url > stored > detected
     -------------------------------------------------------------- */
  let choice = E.chooseSkin(SHOWN, P);
  let activeId = choice.id;

  function paintSwitcher() {
    $('#skinButtons').innerHTML = SHOWN.map(s =>
      `<button data-skin="${s.id}" aria-pressed="${s.id === activeId}">${s.label}</button>`).join('');
    $('#skinButtons').querySelectorAll('button').forEach(b => b.onclick = () => {
      activeId = b.dataset.skin;
      E.rememberSkin(activeId);
      choice = { id: activeId, how: 'chosen', why: ['you chose this skin; it survives reload, and a deep link arrives in it'] };
      paintSwitcher(); render();
    });
    const t = $('#howTag');
    t.className = 'tag ' + choice.how;
    t.textContent = choice.how === 'auto' ? 'auto-chosen — you can change it'
      : (choice.how === 'url' ? 'pinned by ?skin= in the URL' : 'your choice, remembered');
    $('#whyLine').innerHTML = 'Why <b>' + activeId + '</b>: ' + choice.why.join('; ') + '.'
      + (choice.ranked ? '  Ranking: ' + choice.ranked.map(r => r.id + ' ' + r.score).join(' · ') : '')
      + '  Precedence is <code>?skin=</code> &gt; your stored choice &gt; detection. '
      + 'Detection never overrides you.';
  }
  $('#resetSkin').onclick = () => {
    E.forgetSkin();
    choice = E.chooseSkin(SHOWN, P); activeId = choice.id; paintSwitcher(); render();
  };
  $('#copyPin').onclick = () => {
    const u = new URL(location.href); u.searchParams.set('skin', activeId);
    navigator.clipboard?.writeText(u.toString());
    $('#copyPin').textContent = 'copied: ?skin=' + activeId;
    setTimeout(() => $('#copyPin').textContent = 'Copy a link that pins this skin', 2200);
  };

  /* --------------------------------------------------------------
     4. Rendering a skin. THIS IS THE ONLY RENDERER. It knows no skin
        id, no project, no technology. It reads FIELDS and the skin's
        block list, and it refuses when the engine says to.
     -------------------------------------------------------------- */
  function applyTokens(el, skin) {
    const p = skin.palette, t = skin.type, s = skin.surface;
    el.style.setProperty('--sk-ink', p.ink);
    el.style.setProperty('--sk-dim', p.dim);
    el.style.setProperty('--sk-hero-c', p.hero);
    el.style.setProperty('--sk-ground', p.ground);
    el.style.setProperty('--sk-panel', p.panel);
    el.style.setProperty('--sk-rule', p.rule);
    el.style.setProperty('--sk-warn', p.warn);
    el.style.setProperty('--sk-scen', p.scenario);
    el.style.setProperty('--sk-base', t.base);
    el.style.setProperty('--sk-hero', t.hero);
    el.style.setProperty('--sk-lh', t.lineHeight);
    el.style.setProperty('--sk-panelw', s.panelWidth + 'px');
    el.dataset.chrome = s.chromePosition;
  }

  function renderShell(skin, reading, w, h) {
    const shell = document.createElement('div');
    shell.className = 'shell';
    shell.style.width = w + 'px'; shell.style.height = h + 'px';
    applyTokens(shell, skin);
    shell.dataset.scenario = reading.scenario.kind === 'modified' ? '1' : '0';

    /* the surface leads — full-bleed is the DEFAULT, not a mode, and
       no requestFullscreen() is called anywhere to achieve it */
    const surface = document.createElement('div');
    surface.className = 'surface';
    const cv = document.createElement('canvas');
    cv.className = 'map';
    surface.appendChild(cv);
    shell.appendChild(surface);

    const view = skin.views[0];
    const problems = E.validateView(view);
    const card = document.createElement('div');
    card.className = 'card';

    if (problems.length) {
      card.innerHTML = '<div class="refusal"><b>This skin does not render.</b><br>'
        + problems.map(m => '“' + m.field + '” may not appear without “' + m.needs
            + '” in the same view.').join('<br>')
        + '<br><br>The engine refused. The skin author changes the skin, not the engine.</div>';
    } else {
      for (const b of view.blocks) {
        const f = E.FIELDS[b.field];
        if (!f) continue;
        const v = f.get(reading);
        if (v == null || v === '') continue;
        const node = document.createElement('div');
        node.className = b.style;
        node.textContent = v;
        if (b.field === 'qualifier.scenario')
          node.dataset.scenario = reading.scenario.kind === 'modified' ? '1' : '0';
        card.appendChild(node);
      }
    }
    shell.appendChild(card);
    requestAnimationFrame(() => drawMap(cv, reading));
    setTimeout(() => drawMap(cv, reading), 0);   // hidden tabs never fire rAF
    return shell;
  }

  /* A deliberately dumb map. No WebGL, no rAF dependence — so this
     prototype renders correctly in a backgrounded tab, which the live
     Atlas does not (see 00-SKINS.md §1.1). */
  function drawMap(cv, reading) {
    const r = cv.getBoundingClientRect();
    const dpr = Math.min(devicePixelRatio || 1, 2);
    cv.width = Math.max(1, Math.round((r.width || cv.clientWidth || 300) * dpr));
    cv.height = Math.max(1, Math.round((r.height || cv.clientHeight || 300) * dpr));
    const g = cv.getContext('2d'); if (!g) return;
    g.scale(dpr, dpr);
    const W = cv.width / dpr, H = cv.height / dpr;
    g.fillStyle = '#04100d'; g.fillRect(0, 0, W, H);
    const o = reading.subject.at;
    const span = 1.4;
    const px = ll => [W / 2 + ((ll[0] - o[0]) / span) * W * 0.5,
                      H / 2 - ((ll[1] - o[1]) / (span * 0.6)) * H * 0.5];
    g.strokeStyle = '#0d2a24'; g.lineWidth = 1;
    for (let i = 1; i < 8; i++) { g.beginPath(); g.moveTo(0, H*i/8); g.lineTo(W, H*i/8); g.stroke();
      g.beginPath(); g.moveTo(W*i/8, 0); g.lineTo(W*i/8, H); g.stroke(); }
    for (const s of SUBS) {
      const [x, y] = px(s.at);
      if (x < -20 || x > W + 20 || y < -20 || y > H + 20) continue;
      g.fillStyle = s.kv[0] >= 400 ? '#d8c96a' : (s.kv[0] >= 132 ? '#3f7a70' : '#22453f');
      g.beginPath(); g.arc(x, y, s.kv[0] >= 400 ? 3 : 1.8, 0, 7); g.fill();
    }
    if (reading.measurement) {
      const a = px(o), b = px(reading.measurement.target_at);
      g.strokeStyle = reading.measurement.out_of_range ? '#5a4a2a' : '#7ff3d8';
      g.setLineDash(reading.measurement.out_of_range ? [4, 5] : []);
      g.lineWidth = 2; g.beginPath(); g.moveTo(a[0], a[1]); g.lineTo(b[0], b[1]); g.stroke();
      g.setLineDash([]);
      g.fillStyle = '#ffd479'; g.beginPath(); g.arc(b[0], b[1], 5, 0, 7); g.fill();
    }
    const a = px(o);
    g.strokeStyle = reading.scenario.kind === 'modified' ? '#ff8fbf' : '#7ff3d8';
    g.lineWidth = 2; g.beginPath(); g.arc(a[0], a[1], 9, 0, 7); g.stroke();
  }

  /* --------------------------------------------------------------
     5. The scenario driver — a value that changes while you watch.
        The sandbox behaviour itself belongs to another cartridge;
        this only proves the presentation accommodates it.
     -------------------------------------------------------------- */
  let subjectId = 'botley', dx = 0, dy = 0, mw = 840, forcedState = null;
  $('#subjectPick').innerHTML = SUBJECTS.map(s =>
    `<option value="${s.id}">${s.name}</option>`).join('');

  function currentReading() {
    const base = SUBJECTS.find(s => s.id === subjectId);
    const moved = dx !== 0 || dy !== 0;
    const capChanged = mw !== base.capacity_mw;
    const at = [base.at[0] + dx / 100, base.at[1] + dy / 200];
    const km = E.distanceKm(base.at[0], base.at[1], at[0], at[1]);
    const subject = Object.assign({}, base, {
      at, capacity_mw: mw,
      scenario: (moved || capChanged) ? {
        kind: 'modified',
        moved_km: moved ? km : null,
        capacity_delta_mw: capChanged ? mw - base.capacity_mw : null,
        of_record: base.repd_ref
      } : { kind: 'record' }
    });
    return E.read(subject, SUBS, { minKv: 400, state: forcedState || 'settled' });
  }

  const DEVICES = {
    desktop:   { w: 700, h: 420, cap: 'laptop — 1400×900 logical, shown at half scale' },
    glanceable:{ w: 320, h: 320, cap: 'watch / car head unit / phone peek' },
    tenfoot:   { w: 640, h: 360, cap: '1920×1080 TV, shown at one third' }
  };

  function render() {
    const reading = currentReading();
    const stage = $('#stage'); stage.innerHTML = '';
    for (const skin of SHOWN) {
      const d = DEVICES[skin.id] || { w: 380, h: 320, cap: '' };
      const box = document.createElement('div');
      box.className = 'device';
      box.style.outline = skin.id === activeId ? '2px solid #7ff3d8' : 'none';
      box.innerHTML = `<div class="cap"><b>${skin.label}</b><span>${d.cap}</span></div>`;
      box.appendChild(renderShell(skin, reading, d.w, d.h));
      stage.appendChild(box);
    }
    const bs = $('#brokenStage'); bs.innerHTML = '';
    if (BROKEN) {
      const box = document.createElement('div');
      box.className = 'device';
      box.innerHTML = `<div class="cap"><b>${BROKEN.label}</b><span>refused by the engine</span></div>`;
      box.appendChild(renderShell(BROKEN, reading, 340, 300));
      bs.appendChild(box);
    }
    const m = reading.measurement;
    $('#engineCall').innerHTML = 'One engine call produced all of the above: '
      + '<code>read(subject, ' + SUBS.length + ' substations, {minKv:400})</code> → '
      + (m ? '<b>' + m.target_name + '</b>, ' + m.straight_km.toFixed(3) + ' km straight, '
             + m.target_kv + ' kV, considered ' + reading.sample.considered
             + ' of ' + subsDoc.source_features + ' mapped features; '
             + reading.sample.located + '/' + reading.sample.published + ' published points carry '
             + 'coordinates (' + reading.sample.located_pct + '%).'
           : 'no substation at or above 400 kV in the loaded set.')
      + '  Every skin above received that <i>same frozen object</i>. '
      + 'The live Atlas prints 15.76 km for Botley West; this engine prints '
      + (subjectId === 'botley' && dx === 0 && dy === 0 && m ? m.straight_km.toFixed(2) + ' km.' : 'the same for the unmoved record.');
  }

  const sync = () => {
    $('#dxLabel').textContent = (dx / 100).toFixed(2) + '°';
    $('#dyLabel').textContent = (dy / 200).toFixed(2) + '°';
    $('#mwLabel').textContent = mw + ' MW';
  };
  $('#subjectPick').onchange = e => {
    subjectId = e.target.value; dx = 0; dy = 0;
    mw = SUBJECTS.find(s => s.id === subjectId).capacity_mw;
    $('#dx').value = 0; $('#dy').value = 0; $('#mw').value = mw; sync(); render();
  };
  const live = () => { dx = +$('#dx').value; dy = +$('#dy').value; mw = +$('#mw').value; sync(); render(); };
  $('#dx').oninput = live; $('#dy').oninput = live; $('#mw').oninput = live;
  $('#resetScenario').onclick = () => {
    dx = 0; dy = 0; mw = SUBJECTS.find(s => s.id === subjectId).capacity_mw;
    $('#dx').value = 0; $('#dy').value = 0; $('#mw').value = mw; forcedState = null; sync(); render();
  };
  $('#simRecompute').onclick = () => {
    forcedState = 'recomputing'; render();
    setTimeout(() => { forcedState = null; render(); }, 2600);
  };

  /* --------------------------------------------------------------
     6. The layer registry at 1000.
     -------------------------------------------------------------- */
  const attached = new Set();                 // stands in for the map
  const registry = E.LayerRegistry({
    paintBudget: 24,
    memoryBudget: 120,
    adapter: {
      attach: id => attached.add(id),
      detach: id => attached.delete(id),
      isAttached: id => attached.has(id)
    },
    fetchPayload: r => new Promise(res => setTimeout(res, 4 + Math.random() * 25))
  });

  const GROUPS = ['Transmission', 'Distribution', 'Generation', 'Demand', 'Constraint',
                  'Planning', 'Environment', 'Market', 'Telemetry', 'Scenario'];
  const KINDS  = ['substation', 'circuit', 'boundary', 'point', 'raster', 'flow', 'heatmap'];
  const KVS    = [400, 275, 132, 66, 33, 11, null];
  const REGIONS= ['GB', 'Scotland', 'North', 'Midlands', 'South West', 'South East', 'Offshore', 'Wales'];
  const SOURCES= ['NESD ETYS', 'OpenStreetMap', 'REPD', 'NESO', 'DNO open data', 'GridAtlas derived'];
  let seed = 20260903;
  const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
  for (let i = 0; i < 1000; i++) {
    const g = GROUPS[Math.floor(rnd() * GROUPS.length)];
    const k = KINDS[Math.floor(rnd() * KINDS.length)];
    const kv = KVS[Math.floor(rnd() * KVS.length)];
    const rg = REGIONS[Math.floor(rnd() * REGIONS.length)];
    registry.declare({
      id: 'ly-' + String(i).padStart(4, '0'),
      label: g + ' · ' + k + (kv ? ' · ' + kv + ' kV' : '') + ' · ' + rg,
      group: g, kind: k, kv, region: rg,
      source: SOURCES[Math.floor(rnd() * SOURCES.length)],
      bytes: Math.round(8000 + rnd() * 2500000)
    });
  }

  const q = { text: '', group: null, kind: null, kv: null };
  const ROW_H = 30;
  let page = { total: 0, rows: [] };

  function paintStats() {
    const s = registry.stats();
    $('#regStats').innerHTML =
      `<b>${s.declared}</b> declared (${(s.manifest_bytes / 1024).toFixed(1)} KiB of manifest) · `
      + `<span class="ok">${s.painted}</span>/${s.paintBudget} painted · `
      + `${s.resident}/${s.memoryBudget} resident · `
      + `all payloads would be <span class="warn">${(s.payload_bytes_if_all_loaded / 1048576).toFixed(0)} MiB</span>, `
      + `which is why existence must be cheap`;
  }

  function paintFacets() {
    const f = registry.facets();
    const sec = (title, key, entries, fmt) =>
      `<h3>${title}</h3>` + `<button data-f="${key}" data-v="" aria-pressed="${q[key] === null}">any</button>`
      + entries.slice(0, 10).map(([v, n]) =>
        `<button data-f="${key}" data-v="${v}" aria-pressed="${String(q[key]) === String(v)}">`
        + `${fmt ? fmt(v) : v} <span style="opacity:.6">${n}</span></button>`).join('');
    $('#facets').innerHTML = sec('Group', 'group', f.group)
      + sec('Kind', 'kind', f.kind)
      + sec('Voltage', 'kv', f.kv, v => v + ' kV');
    $('#facets').querySelectorAll('button').forEach(b => b.onclick = () => {
      q[b.dataset.f] = b.dataset.v === '' ? null : b.dataset.v;
      paintFacets(); refresh();
    });
  }

  /* The list is never a list: fixed-height rows, absolute positioning,
     only the visible window is in the DOM. */
  function paintRows() {
    const vl = $('#vlist'), sp = $('#spacer');
    const first = Math.max(0, Math.floor(vl.scrollTop / ROW_H) - 4);
    const count = Math.ceil(vl.clientHeight / ROW_H) + 8;
    const res = registry.query({ ...q, offset: first, limit: count });
    page = res;
    sp.style.height = (res.total * ROW_H) + 'px';
    sp.innerHTML = res.rows.map((r, i) => {
      const top = (first + i) * ROW_H;
      return `<div class="vrow" style="top:${top}px" data-id="${r.id}">`
        + `<span class="nm">${r.label}</span>`
        + `<span class="note" style="width:110px;text-align:right">${r.source}</span>`
        + `<span class="st ${r.state}">${r.state}</span>`
        + `<button class="slim" data-act="load" style="min-height:22px">on</button>`
        + `<button class="slim" data-act="min" style="min-height:22px">min</button>`
        + `<button class="slim" data-act="unload" style="min-height:22px">off</button></div>`;
    }).join('');
    $('#listNote').innerHTML = `${res.total} match · <b>${res.rows.length}</b> DOM rows exist right now. `
      + `A flat checkbox list of ${registry.size()} would be ${registry.size()} nodes and about `
      + `${(registry.size() * ROW_H / 1000).toFixed(1)}k px of scroll.`;
  }
  $('#vlist').onscroll = paintRows;
  $('#vlist').onclick = async e => {
    const btn = e.target.closest('button'); if (!btn) return;
    const id = e.target.closest('.vrow').dataset.id;
    if (btn.dataset.act === 'load') {
      const r = await registry.load(id);
      if (!r.ok) note('REFUSED — ' + r.reason);
    } else if (btn.dataset.act === 'min') registry.minimise(id);
    else registry.unload(id, 'reader turned it off');
    refresh();
  };
  $('#layerSearch').oninput = e => { q.text = e.target.value; $('#vlist').scrollTop = 0; refresh(); };

  const logEl = $('#log');
  function note(s) {
    const d = document.createElement('div');
    d.textContent = new Date().toISOString().slice(11, 19) + '  ' + s;
    logEl.appendChild(d); logEl.scrollTop = logEl.scrollHeight;
  }
  registry.onEvent(e => note(e.type.toUpperCase() + ' ' + (e.id || '')
    + (e.cost_ms != null ? ' (' + e.cost_ms + ' ms)' : '')
    + (e.reason ? ' — ' + e.reason : '') + (e.why ? ' — ' + e.why : '')));

  const refresh = () => { paintStats(); paintRows(); };

  $('#loadTen').onclick = async () => {
    const res = registry.query({ ...q, offset: 0, limit: 400 });
    let n = 0;
    for (const r of res.rows) {
      if (r.state === 'loaded') continue;
      const out = await registry.load(r.id);
      if (!out.ok) { note('REFUSED — ' + out.reason); break; }
      if (++n >= 10) break;
    }
    refresh();
  };
  $('#hitCeiling').onclick = async () => {
    const res = registry.query({ offset: 0, limit: 1000 });
    for (const r of res.rows) {
      const out = await registry.load(r.id);
      if (!out.ok) { note('CEILING REACHED — ' + out.reason); break; }
    }
    refresh();
  };
  $('#minAll').onclick = () => {
    registry.query({ state: 'loaded', offset: 0, limit: 1000 }).rows.forEach(r => registry.minimise(r.id));
    note('Minimised. Payloads retained — reopening any of these costs 0 ms.');
    refresh();
  };
  $('#healthBtn').onclick = () => {
    const h = registry.health();
    note(h.disagreements.length
      ? 'HEALTH: ' + h.disagreements.length + ' of ' + h.checked + ' disagree with the map: '
        + h.disagreements.map(d => d.id + ' says ' + d.says + ', map says ' + d.map_says).join('; ')
      : 'HEALTH: ' + h.checked + ' layers checked against the map, no disagreement.');
  };
  $('#corruptBtn').onclick = () => {
    const loaded = registry.query({ state: 'loaded', offset: 0, limit: 1 }).rows[0];
    if (!loaded) { note('Load something first.'); return; }
    attached.delete(loaded.id);          // the map drops it; the registry is not told
    note('Removed ' + loaded.id + ' from the map WITHOUT telling the registry. '
       + 'The registry still says "loaded" — exactly the false green that let three '
       + 'technology buckets ship dark. Now press "Check health".');
  };

  paintFacets(); refresh();

  /* --------------------------------------------------------------
     7. Self-minimising chrome, demonstrated on the layer panel.
     -------------------------------------------------------------- */
  const layersPanel = $('#facets').closest('.panel');
  E.autoCollapse({
    el: layersPanel,
    isExempt: () => {
      const ae = document.activeElement;
      if (ae && layersPanel.contains(ae) && ae.matches('input,select,textarea')) return true; // mid-edit
      if ($('#layerSearch').value) return true;                                               // uncommitted value
      if (registry.query({ state: 'loading', offset: 0, limit: 1 }).total) return true;        // in flight
      return false;
    },
    onCollapse: () => note('AUTO-COLLAPSE would fire here (idle ' + E.AUTOCOLLAPSE.idle_ms
      + ' ms). Suppressed in this prototype so the panel stays inspectable; the exemptions '
      + '(' + E.AUTOCOLLAPSE.never.join(', ') + ') are enforced above and were all checked.')
  });

  paintSwitcher(); sync(); render();

  /* validate every skin at boot and shout in the console */