In this section
- Audit ingest · galaxies-wafers / iterations/42-counts-that-say-themselves/audit.mjs lines 1–104
- Counts render · galaxies-wafers / iterations/42-counts-that-say-themselves/counts.css lines 1–42
- Iterations — 42 Counts That Say Themselves Page render · galaxies-wafers / iterations/42-counts-that-say-themselves/index.html lines 1–76
- Iterations — 44 Vaccine Immunity render · galaxies-wafers / iterations/44-vaccine-immunity/app.mjs lines 1–478
Audit
A JavaScript module in the iterations folder of Galaxies Wafers that parses count (`parseCount`), finds typed (`findTyped`) and parses lines header (`parseLinesHeader`). Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/.
ingestgalaxies-wafers / iterations/42-counts-that-say-themselves/audit.mjs · lines 1–104 of 104 · pattern statusOf (shared by 2 files)
- What it does
- It lists and searches its content. Defines 10 functions or classes, including parseCount, fmt, statusOf, locate, findTyped.
- Downstream impact
- Used directly by 1 file: Iterations — 42 Counts That Say Themselves (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/). Reached from 1 other entry point, including Iterations — 42 Counts That Say Themselves Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/).
- What it achieves
- It parses count (`parseCount`), finds typed (`findTyped`) and parses lines header (`parseLinesHeader`). Counts That Say Themselves — the rules.
- Why it matters
- Imported by Iterations — 42 Counts That Say Themselves.
- Application
- galaxies-wafers · iterations/42-counts-that-say-themselves · JavaScript module
- Uses
- none found
- Used by
- imported by Iterations — 42 Counts That Say Themselves (import)
- Produces
- STATUS, parseCount, fmt, statusOf, locate, NOUNS, findTyped, starsCounts, parseLinesHeader, lineRowCounter, ITER_DIR
- Defines here
- parseCount, fmt, statusOf, locate, findTyped, starsCounts, sSum, parseLinesHeader, lineRowCounter, take
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/42-counts-that-say-themselves/audit.mjs:1-104 · blob 5348e6140c1430f93631df8346d161b4ae81a9d4 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
/* Counts That Say Themselves — the rules. Pure functions: no DOM, no network.
app.mjs hands every function here the text or JSON it fetched at run time. */
export const STATUS = { MATCH: 'MATCH', DIFFERS: 'DIFFERS', UNKNOWN: 'NOT YET KNOWN' };
/* A number as a sentence prints it: "265,480" -> 265480. */
export const parseCount = s => (s == null ? null : Number(String(s).replace(/,/g, '')));
export const fmt = n => (n == null || Number.isNaN(n) ? 'not yet known' : Number(n).toLocaleString('en-GB'));
export function statusOf(stated, recount) {
if (stated == null || recount == null || Number.isNaN(stated) || Number.isNaN(recount)) return STATUS.UNKNOWN;
return stated === recount ? STATUS.MATCH : STATUS.DIFFERS;
}
/* The line of `text` where `re` first matches: 1-based line number, the line, the match. */
export function locate(text, re) {
if (typeof text !== 'string') return null;
const m = re.exec(text);
if (!m) return null;
const before = text.slice(0, m.index);
const line = before.split('\n').length;
const start = before.lastIndexOf('\n') + 1;
const endAt = text.indexOf('\n', m.index);
return { line, text: text.slice(start, endAt < 0 ? text.length : endAt), match: m };
}
/* ── typed counts: digits written into the source next to a counted noun ──
A number inside ${…} is computed; digits written as digits are typed. A
number after "first", "top", "at most", "up to" is a cap, not a count, and
is skipped. Nouns are the ones the estate's count sentences use. */
export const NOUNS = ['named blocks', 'function families', 'unique numbered lines', 'unique lines', 'blocks', 'categories', 'groups', 'families', 'repositories'];
const NOUN_RE = new RegExp(`(^|[^\\w$#.{-])(\\d{1,3}(?:,\\d{3})+|\\d{2,})\\s+(${NOUNS.map(n => n.replace(/ /g, '\\s+')).join('|')})\\b`, 'g');
const CAP_RE = /(first|top|at most|up to|max|limit|every)\s*$/i;
export function findTyped(text) {
const out = [];
if (typeof text !== 'string') return out;
const lines = text.split('\n');
lines.forEach((ln, i) => {
NOUN_RE.lastIndex = 0;
let m;
while ((m = NOUN_RE.exec(ln))) {
const at = m.index + m[1].length;
if (CAP_RE.test(ln.slice(Math.max(0, at - 12), at))) continue;
const trimmed = ln.trim();
const comment = /^(\/\/|\/?\*|#|<!--)/.test(trimmed) || ln.slice(0, at).includes('// ');
out.push({ line: i + 1, text: ln, number: parseCount(m[2]), noun: m[3].replace(/\s+/g, ' '), comment });
}
});
return out;
}
/* ── recount rules over the stars data ───────────────────────────────────── */
export function starsCounts(blocksDoc, families, index) {
const blocks = blocksDoc && Array.isArray(blocksDoc.blocks) ? blocksDoc.blocks : null;
const syms = blocks ? new Set(blocks.map(b => b.symbol)) : null;
const famKeys = families && typeof families === 'object' ? Object.keys(families) : null;
const famSet = families ? new Set(Object.values(families).flat()) : null;
return {
blocksAll: blocks ? blocks.length : null,
blocksNamedByKind: blocks ? blocks.filter(b => b.kind !== 'auto').length : null,
blocksAuto: blocks ? blocks.filter(b => b.kind === 'auto').length : null,
functionsSum: blocks ? blocks.reduce((s, b) => s + (b.functions || 0), 0) : null,
familiesPerBlockSum: blocks && families ? blocks.reduce((s, b) => s + (families[b.symbol] || []).length, 0) : null,
categories: blocksDoc && Array.isArray(blocksDoc.categories) ? blocksDoc.categories.length : null,
groupKeys: famKeys ? famKeys.length : null,
unnamedGroups: famKeys && syms ? famKeys.filter(g => !syms.has(g)).length : null,
familiesDistinct: famSet ? famSet.size : null,
repositories: blocks ? new Set(blocks.flatMap(b => (b.repos || []).map(r => r.replace(/^Ventusltd\//, '')))).size : null,
apps: blocks ? blocks.filter(b => b.kind === 'app').length : null,
indexFamilies: index ? index.families ?? null : null,
indexLines: index ? index.lines ?? null : null,
indexElements: index ? index.elements ?? null : null,
};
}
/* LINES.md header: "265,480 unique lines, numbered 1 to 364,138." */
export function parseLinesHeader(text) {
const m = /([\d,]+) unique lines, numbered ([\d,]+) to ([\d,]+)/.exec(text || '');
return m ? { line: m[0], unique: parseCount(m[1]), first: parseCount(m[2]), last: parseCount(m[3]) } : null;
}
/* Streaming row counter for LINES.md: rows are "number<TAB>code". Nothing is kept
but the counts, so 23 MB passes through without being held. */
export function lineRowCounter() {
let carry = '', rows = 0, max = 0, min = Infinity, header = null, badOrder = 0, prev = 0;
const take = ln => {
if (header == null && /unique lines, numbered/.test(ln)) header = ln;
const tab = ln.indexOf('\t');
if (tab < 1 || tab > 7) return;
const k = ln.slice(0, tab);
if (!/^\d+$/.test(k)) return;
const n = +k;
rows++; if (n > max) max = n; if (n < min) min = n; if (n <= prev) badOrder++; prev = n;
};
return {
push(chunk) { const parts = (carry + chunk).split('\n'); carry = parts.pop(); for (const p of parts) take(p); },
end() { if (carry) take(carry); carry = ''; return { rows, max, min: rows ? min : null, header, badOrder }; },
get rows() { return rows; },
};
}
/* galaxy: iteration directories are NN-slug (build_iterations_index.py) */
export const ITER_DIR = /^(\d{2})-([a-z0-9-]+)$/;Counts
A style sheet in the iterations folder of Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/.
rendergalaxies-wafers / iterations/42-counts-that-say-themselves/counts.css · lines 1–42 of 42 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Downstream impact
- Used directly by 1 file: Iterations — 42 Counts That Say Themselves Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/). Reached from 1 other entry point, including Iterations — 42 Counts That Say Themselves (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Loaded by the 42 Counts That Say Themselves page at https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/.
- Application
- galaxies-wafers · iterations/42-counts-that-say-themselves · style sheet
- Uses
- none found
- Used by
- loaded by Iterations — 42 Counts That Say Themselves Page (stylesheet)
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/42-counts-that-say-themselves/counts.css:1-42 · blob fa214324541b5f2b1cf92c0fa43ed9127f5aeeda · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
:root{--ink:#d8dee9;--dim:#8b93a7;--ground:#0b0d12;--edge:#1b2030;--beam:#5ec8f2;--grey:#8b93a7}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
padding:calc(env(safe-area-inset-top,0px) + .8rem) 1rem calc(env(safe-area-inset-bottom,0px) + 2rem)}
main{max-width:52rem;margin:0 auto}
h1{font-size:14px;letter-spacing:.18em;font-weight:600;margin:0 0 .35rem;color:#fff}
p{margin:.35rem 0}
.dim{color:var(--dim)} .small{font-size:11.5px}
a{color:var(--beam);overflow-wrap:anywhere}
code{color:var(--beam);overflow-wrap:anywhere}
.summary{border-left:3px solid #fff;padding:.35rem .6rem;background:#10131b;margin:.6rem 0}
.sec{border:1px solid var(--edge);border-radius:.45rem;background:#0e1118;margin:.5rem 0}
.sec>summary{cursor:pointer;min-height:44px;display:flex;align-items:center;padding:.3rem .65rem;overflow-wrap:anywhere}
.sec>summary::before{content:"+";color:var(--beam);margin-right:.5rem;flex:none}
.sec[open]>summary::before{content:"\2212"}
.sec>summary::-webkit-details-marker{display:none}
.sec[open]>summary{border-bottom:1px solid var(--edge)}
.sec .lead{margin:.45rem .65rem}
.rows{list-style:none;margin:0;padding:.4rem;display:grid;gap:.45rem}
.row{border:1px solid var(--edge);border-left-width:4px;border-radius:.4rem;background:#10131b;padding:.45rem .6rem;overflow-wrap:anywhere;min-width:0}
.row.match{border-left-color:#eceff4;border-left-style:solid}
.row.differs{border-left-color:#eceff4;border-left-style:double;border-left-width:6px}
.row.unknown{border-left-color:var(--grey);border-left-style:dotted}
.rhead{display:flex;flex-wrap:wrap;gap:.2rem .6rem;align-items:baseline}
.st{font-weight:600;letter-spacing:.08em;color:#fff;font-size:12px}
.row.unknown .st{color:var(--grey)}
.row.differs .st{text-decoration:underline;text-underline-offset:3px}
.served{display:block;background:#05060a;border:1px solid var(--edge);border-radius:.3rem;padding:.3rem .45rem;margin:.3rem 0;color:#cfd6e4;font-size:11.5px;white-space:pre-wrap;max-height:9.5em;overflow:auto}
.nums b{color:#fff;font-size:13.5px}
.tag{color:var(--dim)} .tag.typed{color:#fff;border:1px dashed #fff;border-radius:.25rem;padding:0 .3rem}
.rule .note{color:var(--ink);margin-top:.2rem}
.pick{display:flex;flex-wrap:wrap;gap:.4rem;margin:.45rem .65rem}
.pick select{flex:1 1 14rem;min-width:0;font:inherit;font-size:16px;color:#fff;background:#05060a;border:1px solid var(--edge);border-radius:.35rem;min-height:44px}
.pick button{font:inherit;color:var(--ink);background:#07080c;border:1px solid var(--edge);border-radius:.35rem;min-height:44px;min-width:72px}
.pick button:disabled{opacity:.4}
.questions{border:1px solid var(--edge);border-radius:.45rem;background:#10131b;padding:0 .65rem;margin:1.2rem 0 .5rem}
.questions summary{font-size:11px;letter-spacing:.14em;text-transform:uppercase;cursor:pointer;color:var(--beam);min-height:44px;display:flex;align-items:center}
.questions dt{color:#fff;margin-top:.5rem;font-size:12px}
.questions dd{margin:.2rem 0 .6rem;font-size:11.5px;overflow-wrap:anywhere}
.machine{border-left:3px solid var(--beam);padding:.35rem .6rem;background:#07080c;overflow-wrap:anywhere}
footer{margin-top:1.2rem;overflow-wrap:anywhere}Iterations — 42 Counts That Say Themselves Page
A web page in Galaxies Wafers that reads inputs for layer pick. Published at https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/.
rendergalaxies-wafers / iterations/42-counts-that-say-themselves/index.html · lines 1–76 of 76 · Entry point
- What it does
- It draws its content. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: JSON file index.json; form fields (user input). Out: web page.
- Downstream impact
- Used directly by 1 file: Iterations — 42 Counts That Say Themselves (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/.
- What it achieves
- The README says: The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/.
- Why it matters
- Imported by Iterations — 42 Counts That Say Themselves.
- Application
- galaxies-wafers · iterations/42-counts-that-say-themselves · page
- Uses
- Counts (stylesheet), Galaxies Wafers — Iterations Page (link), Iterations — 42 Counts That Say Themselves (script src)
- Used by
- referenced by Iterations — 42 Counts That Say Themselves (new URL import.meta.url)
- 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
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/42-counts-that-say-themselves/index.html:1-76 · blob c83f75b86aab10b0128d4666d2bd980185b234db · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<title>Counts That Say Themselves</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="counts.css">
</head>
<body>
<main>
<header>
<h1>COUNTS THAT SAY THEMSELVES</h1>
<p class="dim">The estate's grammar says every quantity is computed from live data, never typed, and missing data reads "not yet known". This page tests that rule against the count sentences the public pages publish. Open a section: it fetches each served page and each data file it names, finds the sentence and the line that makes it, recomputes the number from the data under the rule the code … [line shortened here: 589 characters; full line on GitHub]
<p id="summary" class="summary">WAIT: nothing is fetched until you open a section.</p>
</header>
<details class="sec" data-sec="stars">
<summary><span id="lbl-stars" data-base-label="The stars site · start, table and code pages">The stars site · start, table and code pages [WAIT]</span></summary>
<p class="lead small dim">Reads ventusltd.github.io/stars/ start.html, table.html, code.html, blocks/blocks.json, blocks/families.json, code/index.json and the first 2 kB of LINES.md.</p>
<ul class="rows" id="rows-stars"></ul>
</details>
<details class="sec" data-sec="lenses">
<summary><span id="lbl-lenses" data-base-label="The lenses · countsLine and the pages around it">The lenses · countsLine and the pages around it [WAIT]</span></summary>
<p class="lead small dim">The lenses at globalgrid2050.com/testcode read the same stars files, and their countsLine functions are numbered lines of stars LINES.md. Reads three core.js files, nine lens pages and the stars data.</p>
<ul class="rows" id="rows-lenses"></ul>
</details>
<details class="sec" data-sec="lines">
<summary><span id="lbl-lines" data-base-label="LINES.md · every row counted">LINES.md · every row counted [WAIT]</span></summary>
<p class="lead small dim">One large file, streamed and counted row by row; only the counts are kept. It must finish inside the 15 s timeout, or the counts read NOT YET KNOWN.</p>
<ul class="rows" id="rows-lines"></ul>
</details>
<details class="sec" data-sec="iter">
<summary><span id="lbl-iter" data-base-label="This galaxy · iterations/index.json">This galaxy · iterations/index.json [WAIT]</span></summary>
<p class="lead small dim">The index's count against its own rows, the directories in the repository listing, and the directories this host serves.</p>
<ul class="rows" id="rows-iter"></ul>
</details>
<details class="sec" data-sec="layers">
<summary><span id="lbl-layers" data-base-label="This galaxy · layers/manifest.json">This galaxy · layers/manifest.json [WAIT]</span></summary>
<p class="lead small dim">The manifest's layers against the files in the repository and the files served (one HEAD request each). Feature counts are checked one layer at a time, when you ask.</p>
<div class="pick"><select id="layer-pick" aria-label="layer to count"><option>open the section first</option></select><button type="button" id="layer-check" disabled>count</button></div>
<ul class="rows" id="rows-layers"></ul>
</details>
<details class="sec" data-sec="elements">
<summary><span id="lbl-elements" data-base-label="The elements catalogue · provenance.json">The elements catalogue · provenance.json [WAIT]</span></summary>
<p class="lead small dim">provenance.json counts against the lengths of its JSON arrays, the numbered database it names, and the live register and LINES.md header served now.</p>
<ul class="rows" id="rows-elements"></ul>
</details>
<details id="questions" class="questions">
<summary>Questions</summary>
<dl>
<dt>1. How does this help draw a system or a single-line diagram?</dt>
<dd>It draws no busbar, feeder, transformer, cable route, protection or earthing: none yet. It checks the sentences that tell a reader what a drawing draws, because a drawing that states a wrong count misleads the reader about what it draws. The fields it checks: <code>blocks[]</code> and <code>blocks[].kind</code> of stars <code>blocks/blocks.json</code>, the lists of <code>blocks/families. … [line shortened here: 734 characters; full line on GitHub]
<dt>2. What is this code used for?</dt>
<dd><code>countsLine</code> in <code>testcode/202609141350/core.js</code> (copied at 202609141423, 202609141522 and 202609141754) is called by each lens page after <code>loadUniverse()</code> to print its header; rows of stars <code>LINES.md</code> that call <code>countsLine()</code> were found by text search at stars commit 7f9490a5f6d8 (name-match inference). <code>core.countsLine</code> i … [line shortened here: 1,137 characters; full line on GitHub]
<dt>3. Where does it lead next?</dt>
<dd id="q-next">not yet known: open a section.</dd>
</dl>
</details>
<p id="machine" class="machine small">Machine detail · not yet known: open a section.</p>
<footer class="dim small">
<p>Loading, as Grid Atlas does it: every section exists from the start and fetches nothing until opened; one queue of 4 carries every request, each with a 15 s timeout; one promise per URL, removed on failure so a retry is possible; only the changed row or label is rewritten. Closing a section keeps what was read.</p>
<p>MATCH has a solid rule, DIFFERS a double rule, NOT YET KNOWN a dotted grey rule. Sources are read at main when a section opens, so a row changes when its file changes. <a href="../">every version</a></p>
</footer>
</main>
<script type="module" src="app.mjs"></script>
</body>
</html>Iterations — 44 Vaccine Immunity
A JavaScript module in Galaxies Wafers that draws last fired, using SHA-256 and uses data from GitHub API and the CVAA repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/44-vaccine-immunity/.
rendergalaxies-wafers / iterations/44-vaccine-immunity/app.mjs · lines 1–478 of 630 · Entry point · pattern HttpError (shared by 2 files)
- What it does
- It draws last fired. Defines 48 functions or classes, including short, $, el, link, FetchQueue. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
- Inputs & outputs
- In: data source: cvaa data; data source: GitHub API; JSON file last-fired.json. Out: canvas drawing.
- Downstream impact
- Used directly by 1 file: Iterations — 44 Vaccine Immunity Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/44-vaccine-immunity/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/44-vaccine-immunity/.
- What it achieves
- It fetches queue (`FetchQueue`), fetches once (`fetchOnce`) and updates ui state (`updateUIState`). Loading in Grid Atlas grammar; one canvas for the ring, one card and one integrity table re-filled. It responds to click, change and toggle events.
- Why it matters
- Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/iterations/44-vaccine-immunity/.
- Application
- galaxies-wafers · iterations/44-vaccine-immunity · JavaScript module
- Uses
- Vax (import)
- Used by
- loaded by Iterations — 44 Vaccine Immunity Page (script src)
- Produces
- short, $, el, link, FetchQueue, HttpError, fetchOnce, updateUIState, tick, setText, hydrate, loadListing
- Defines here
- short, $, el, link, FetchQueue, HttpError, fetchOnce, updateUIState, tick, setText, hydrate, loadListing, readWindow, sha256hex, loadFile, pr, capText, parsedMap, refresh, counts, paintSummary, paintIntegrity, need, paintQuestions, paintMachine, tsWords, select, row, paintCard, DOSES_OK
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/44-vaccine-immunity/app.mjs:1-478 · blob b9d8908699e4aa7d0f3da55385a6c5c3d34b2a05 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* Immunity — the page. Loading in Grid Atlas grammar; one canvas for the ring,
one card and one integrity table re-filled. Parsing and counting live in
vax.mjs. No antibody is ever executed here: its source is text. */
import * as V from './vax.mjs';
/* Ventusltd/cvaa origin/main when this page was built; every file is read at this commit */
const COMMIT = '48393ff23b4602b045fbc9d7c1db16ffc5b6e6d4';
const RAW = `https://raw.githubusercontent.com/Ventusltd/cvaa/${COMMIT}/`;
const BLOB = `https://github.com/Ventusltd/cvaa/blob/${COMMIT}/`;
const URL_LIST = `https://api.github.com/repos/Ventusltd/cvaa/contents/vaccines?ref=${COMMIT}`;
const URL_LOCK = RAW + 'vaccines.lock';
const URL_FIRED = RAW + 'vaccines/last-fired.json';
const URL_SELFTEST = RAW + 'tools/selftest.mjs';
const WINDOW = 48; // vaccine files read per window of the Files layer
const TEXT_CAP = 96; // parsed files whose section text is kept; beyond it the oldest drop their text, never their counts
const short = s => String(s).slice(0, 12);
const $ = id => document.getElementById(id);
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const link = (href, text, cls) => { const a = el('a', cls, text); a.href = href; a.rel = 'noopener'; return a; };
/* ── loading, as Grid Atlas does it ─────────────────────────────────────── */
class FetchQueue {
constructor(concurrency) { this.concurrency = concurrency; this.active = 0; this.queue = []; this.peak = 0; }
async add(task) {
if (this.active >= this.concurrency) await new Promise(resolve => this.queue.push(resolve));
this.active++; this.peak = Math.max(this.peak, this.active);
try { return await task(); }
finally { this.active--; if (this.queue.length > 0) this.queue.shift()(); }
}
}
const queue = new FetchQueue(4);
const urlCache = new Map();
const NET = { fetches: 0, bytes: 0 };
class HttpError extends Error { constructor(status, source) { super(`HTTP ${status}`); this.status = status; this.source = source || 'http'; } }
function fetchOnce(url, as) {
if (urlCache.has(url)) return urlCache.get(url);
const p = queue.add(async () => {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 15000);
NET.fetches++;
try {
const res = await fetch(url, { signal: controller.signal, headers: as === 'github' ? { Accept: 'application/vnd.github+json' } : undefined });
if (!res.ok) throw new HttpError(res.status);
const buf = await res.arrayBuffer();
NET.bytes += buf.byteLength;
if (as === 'bytes') return buf;
const text = new TextDecoder('utf-8').decode(buf);
if (as === 'text') return text;
try { return JSON.parse(text); } catch (e) { throw new Error('not valid JSON: ' + e.message); }
} catch (err) {
if (err instanceof HttpError) throw err;
throw new Error(err && err.name === 'AbortError' ? 'timed out after 15 s' : (err && err.message) || String(err));
} finally { clearTimeout(timer); }
}).catch(err => { urlCache.delete(url); throw err; });
urlCache.set(url, p);
return p;
}
const LAYERS = ['ring', 'files', 'gen', 'dose', 'sup', 'fired'];
const RT = Object.fromEntries(LAYERS.map(id => [id, { loaded: false, loading: null, visible: false }]));
function updateUIState(id, state, detail) {
const span = $('lbl-' + id);
const text = `${span.getAttribute('data-base-label')} [${detail ? state + ' · ' + detail : state}]`;
if (span.textContent !== text) span.textContent = text;
}
function tick(id) { const box = document.querySelector(`input[data-layer="${id}"]`); if (box && !box.checked) box.checked = true; RT[id].visible = true; }
function setText(id, text) { const n = $(id); if (n && n.textContent !== text) n.textContent = text; }
/* ── data ───────────────────────────────────────────────────────────────── */
const D = {
names: null, listMethod: '', listNote: '',
lock: null,
ring: [], broken: [], others: [], dup: 0,
parsed: new Map(), // file → { p (parsed), status, rawHex, lfHex, bytes, adapted, failed }
pending: new Map(), // file → promise
filesRead: 0, // how many ring files the Files layer has asked for
fired: undefined, firedWhy: '',
edges: { gen: [], dose: [], sup: [], reasons: [] },
selftest: undefined,
};
const S = { sel: -1, epoch: 0, view: { x: 0, y: 0, k: 0 }, fitted: false };
function hydrate(id) {
const rt = RT[id];
if (rt.loaded) return Promise.resolve(true);
if (rt.loading) return rt.loading;
updateUIState(id, 'LOAD');
rt.loading = (async () => {
try {
if (id === 'ring') {
const [names, lock] = await Promise.all([loadListing(), fetchOnce(URL_LOCK, 'json')]);
if (!lock || typeof lock !== 'object' || Array.isArray(lock)) throw new Error('vaccines.lock is not an object of file → sha256');
D.lock = lock; D.names = names;
const o = V.orderRing(names);
D.ring = o.placed; D.broken = o.broken; D.others = o.others; D.dup = o.duplicateTimestamps;
rt.loaded = true;
if (!D.ring.length) updateUIState(id, 'EMPTY', `no file in vaccines/ at ${short(COMMIT)} matches <12 digits>-<slug>.md`);
else updateUIState(id, 'OK', `${D.ring.length} vaccines placed by timestamp${D.broken.length ? ` · ${D.broken.length} names break the rule and are not placed` : ''}`);
if (!S.fitted) fit();
} else if (id === 'files') {
await hydrate('ring');
if (!RT.ring.loaded) throw new Error('the ring could not be read');
await readWindow();
rt.loaded = true;
} else if (id === 'gen' || id === 'dose' || id === 'sup') {
tick('files');
await hydrate('files');
if (!RT.files.loaded) throw new Error('the vaccine files could not be read');
rt.loaded = true;
} else if (id === 'fired') {
await hydrate('ring');
try {
if (D.names && !/fallback/.test(D.listMethod) && !D.names.includes('last-fired.json')) throw new HttpError(404, 'listing');
const lf = await fetchOnce(URL_FIRED, 'json');
if (!lf || typeof lf !== 'object' || Array.isArray(lf)) throw new Error('last-fired.json is not an object of vaccine → {sha, at}');
D.fired = lf;
const n = Object.keys(lf).length;
updateUIState(id, n ? 'OK' : 'EMPTY', n ? `${n} vaccines with a recorded firing` : 'the file lists no firing');
} catch (err) {
if (err.status === 404) {
D.fired = null;
D.firedWhy = `vaccines/last-fired.json is not present at commit ${short(COMMIT)} (${err.source === 'listing' ? 'absent from the vaccines/ listing at that commit, so it was not fetched' : 'HTTP 404'}). inoculate.mjs writes this sidecar on runs without --no-write, recording the commit and time for each vaccine that found something; no copy is committed at this pin, so no firing can be re … [line shortened here: 405 characters; full line on GitHub]
urlCache.delete(URL_FIRED);
urlCache.set(URL_FIRED, Promise.resolve(null));
updateUIState(id, 'EMPTY', `not present at ${short(COMMIT)} (${err.source === 'listing' ? 'not in the listing' : 'HTTP 404'}) · no firing recorded`);
} else throw err;
}
rt.loaded = true;
}
rt.loading = null;
refresh();
return true;
} catch (err) {
rt.loading = null;
updateUIState(id, 'FAIL', (err.message || String(err)) + ' · tick again to retry');
const box = document.querySelector(`input[data-layer="${id}"]`);
if (box) box.checked = false;
rt.visible = false;
if (id === 'ring') setText('summary', `FAIL — ${err.message}. No vaccine is drawn in its place.`);
refresh();
return false;
}
})();
return rt.loading;
}
/* The list of vaccine files: the repository's own listing at the pinned commit;
when GitHub refuses it (rate limit), the file names in vaccines.lock, said so. */
async function loadListing() {
try {
const list = await fetchOnce(URL_LIST, 'github');
if (!Array.isArray(list)) throw new Error('the listing is not a list');
D.listMethod = 'the GitHub contents listing of vaccines/ at the pinned commit';
return list.filter(x => x && x.type === 'file').map(x => x.name);
} catch (err) {
const lock = await fetchOnce(URL_LOCK, 'json');
D.listMethod = 'the file names in vaccines.lock (fallback)';
D.listNote = `The contents listing was refused (${err.message}); files present but absent from the lock cannot be seen, and "lock entries without a file" cannot be established.`;
return Object.keys(lock || {});
}
}
async function readWindow() {
const from = D.filesRead, to = Math.min(D.ring.length, from + WINDOW);
D.filesRead = to;
let done = 0;
const total = to - from;
updateUIState('files', 'LOAD', `0 of ${total} files`);
await Promise.all(D.ring.slice(from, to).map(v => loadFile(v.file).then(() => { done++; updateUIState('files', 'LOAD', `${done} of ${total} files`); })));
const read = [...D.parsed.values()].filter(x => !x.failed).length;
const failed = [...D.parsed.values()].filter(x => x.failed).length;
updateUIState('files', 'OK', `${read} of ${D.ring.length} files read${failed ? ` · ${failed} could not be read (tap one to retry)` : ''}`);
const w = $('window');
if (D.filesRead < D.ring.length) {
w.hidden = false; w.textContent = '';
w.append(`Files are read ${WINDOW} at a time in timestamp order; ${D.ring.length - D.filesRead} remain. `);
const b = el('button', 'btn', `read the next ${Math.min(WINDOW, D.ring.length - D.filesRead)}`);
b.type = 'button';
b.addEventListener('click', () => { b.disabled = true; readWindow().then(refresh); });
w.append(b);
} else { w.hidden = true; }
}
async function sha256hex(buf) {
if (!(globalThis.crypto && crypto.subtle && crypto.subtle.digest)) return null;
return V.hex(await crypto.subtle.digest('SHA-256', buf));
}
function loadFile(file) {
const have = D.parsed.get(file);
if (have && !have.failed && !have.textDropped) return Promise.resolve(have);
if (D.pending.has(file)) return D.pending.get(file);
const url = RAW + 'vaccines/' + file;
const pr = (async () => {
try {
const buf = await fetchOnce(url, 'bytes');
const text = new TextDecoder('utf-8').decode(buf);
const p = V.parseVaccine(file, text);
const rawHex = await sha256hex(buf);
const norm = V.normalise(text);
const lfHex = rawHex == null ? null : (norm === text ? rawHex : await sha256hex(new TextEncoder().encode(norm)));
const status = V.lockStatus(D.lock, file, rawHex, lfHex);
const adapted = V.hasPrivateWord(text) || V.hasPrivateWord(file);
const entry = { p, status, rawHex, lfHex, bytes: buf.byteLength, adapted, failed: false, textDropped: false, at: NET.fetches };
D.parsed.set(file, entry);
capText();
return entry;
} catch (err) {
const entry = { p: null, failed: true, why: err.message, status: { state: 'NOT COMPUTED', detail: `the file could not be read: ${err.message}` } };
D.parsed.set(file, entry);
return entry;
} finally {
urlCache.delete(url); // the parsed record is kept; the bytes are not
D.pending.delete(file);
}
})();
D.pending.set(file, pr);
return pr;
}
/* keep counts for every file, section text for at most TEXT_CAP of them */
function capText() {
const withText = [...D.parsed.entries()].filter(([, e]) => !e.failed && !e.textDropped);
if (withText.length <= TEXT_CAP) return;
const selFile = S.sel >= 0 ? D.ring[S.sel].file : null;
withText.sort((a, b) => a[1].at - b[1].at);
for (const [f, e] of withText) {
if (withText.filter(([, x]) => !x.textDropped).length <= TEXT_CAP) break;
if (f === selFile) continue;
e.p = { ...e.p, sections: null, code: null }; e.textDropped = true;
}
}
document.querySelectorAll('input[data-layer]').forEach(box => {
box.checked = false;
box.addEventListener('change', () => {
const id = box.dataset.layer;
RT[id].visible = box.checked;
if (box.checked) hydrate(id); else if (!RT[id].loaded && !RT[id].loading) updateUIState(id, 'WAIT');
refresh();
});
});
/* ── derived state ──────────────────────────────────────────────────────── */
function parsedMap() { const m = new Map(); for (const [f, e] of D.parsed) if (!e.failed && e.p) m.set(f, e.p); return m; }
function refresh() {
if (RT.ring.loaded) {
D.edges = V.buildEdges(D.ring, parsedMap());
if (RT.gen.loaded) updateUIState('gen', D.edges.gen.length ? 'OK' : 'EMPTY', D.edges.gen.length ? `${D.edges.gen.length} edges` : 'no two consecutive vaccines with readable generations');
if (RT.dose.loaded) {
const by = {}; for (const e of D.edges.dose) by[e.dose] = (by[e.dose] || 0) + 1;
updateUIState('dose', D.edges.dose.length ? 'OK' : 'EMPTY', D.edges.dose.length ? `${D.edges.dose.length} edges · ${Object.entries(by).map(([k, n]) => `${k} ${n}`).join(' · ')}` : 'no dose is shared by two readable vaccines');
}
if (RT.sup.loaded) updateUIState('sup', D.edges.sup.length ? 'OK' : 'EMPTY', D.edges.sup.length ? `${D.edges.sup.length} edge${D.edges.sup.length === 1 ? '' : 's'}` : 'no vaccine read names a superseded_by successor that exists');
}
paintSummary();
paintIntegrity();
paintQuestions();
paintMachine();
schedule();
}
function counts() {
const files = D.ring.map(v => D.parsed.get(v.file)).filter(Boolean);
const read = files.filter(e => !e.failed);
const lockKeys = D.lock ? Object.keys(D.lock) : [];
const nameSet = new Set(D.names || []);
return {
found: D.ring.length + D.broken.length,
placed: D.ring.length,
named: D.ring.filter(v => D.lock && v.file in D.lock).length,
read: read.length,
locked: read.filter(e => e.status.state === 'LOCKED').length,
differs: read.filter(e => e.status.state === 'HASH DIFFERS').length,
notComputed: files.filter(e => e.status.state === 'NOT COMPUTED').length,
orphan: lockKeys.filter(k => !nameSet.has(k)),
unlocked: [...D.ring, ...D.broken].filter(v => !(D.lock && v.file in D.lock)).map(v => v.file),
superseded: read.filter(e => e.p.meta && e.p.meta.superseded_by),
fm: read.filter(e => e.p.problems.length),
adapted: read.filter(e => e.adapted),
};
}
function paintSummary() {
if (!RT.ring.loaded) return;
const c = counts();
const parts = [`${c.placed} vaccines on the ring, ordered by timestamp.`];
if (c.read) parts.push(`${c.read} files read: ${c.locked} LOCKED, ${c.differs} HASH DIFFERS${c.notComputed ? `, ${c.notComputed} NOT COMPUTED` : ''}.`);
else parts.push('Tick Files or open Registry integrity to hash every file against vaccines.lock.');
setText('summary', parts.join(' '));
}
function paintIntegrity() {
if (!RT.ring.loaded) return;
const c = counts();
const allRead = RT.files.loaded && D.filesRead >= D.ring.length;
const need = n => (allRead ? String(n) : `${n} so far (${c.read} of ${c.placed} files read)`);
const listApi = !/fallback/.test(D.listMethod);
setText('i-found', `${c.found} .md files (${c.placed} placed on the ring)`);
setText('i-named', `${c.named} of ${c.placed}`);
setText('i-locked', c.read ? need(c.locked) : 'not yet known: tick Files');
setText('i-differs', c.read ? need(c.differs) : 'not yet known: tick Files');
setText('i-orphan', listApi ? `${c.orphan.length}${c.orphan.length ? ': ' + c.orphan.map(V.adapt).join(', ') : ''}` : 'not established: the contents listing was refused, so the lock itself supplied the names');
setText('i-unlocked', `${c.unlocked.length}${c.unlocked.length ? ': ' + c.unlocked.map(V.adapt).join(', ') : ''}`);
setText('i-super', c.read ? need(c.superseded.length) + (c.superseded.length ? ' · ' + c.superseded.map(e => `${V.adapt(e.p.meta.vaccine)} → ${V.adapt(e.p.meta.superseded_by)}`).join(', ') : '') : 'not yet known: tick Files');
setText('i-names', listApi ? `${c.found ? D.broken.length : 0}${D.broken.length ? ': ' + D.broken.map(b => `${V.adapt(b.file)} (${b.why})`).join('; ') : ''}` : 'not established: the listing was refused');
setText('i-dup', String(D.dup));
setText('i-fm', c.read ? need(c.fm.length) : 'not yet known: tick Files');
setText('i-other', listApi ? `${D.others.length}${D.others.length ? ': ' + D.others.map(V.adapt).join(', ') + ' (not vaccines)' : ''}` : 'not established: the listing was refused');
setText('i-adapted', c.read ? need(c.adapted.length) + (c.adapted.length ? ' · shown by file slug: ' + c.adapted.map(e => V.adapt(e.p.name.ok ? e.p.name.slug : e.p.file)).join(', ') : '') : 'not yet known: tick Files');
const lines = [];
if (D.listNote) lines.push(D.listNote);
for (const e of c.fm) for (const pr of e.p.problems) lines.push(`${V.adapt(e.p.file)}: ${V.adapt(pr)}`);
for (const r of D.edges.reasons) lines.push(V.adapt(r));
for (const v of D.ring) { const e = D.parsed.get(v.file); if (e && (e.failed || e.status.state !== 'LOCKED')) lines.push(`${V.adapt(v.file)}: ${e.status.state} — ${V.adapt(e.status.detail)}`); }
const key = lines.join('\n');
const ul = $('i-list');
if (ul.dataset.key !== key) { ul.dataset.key = key; ul.replaceChildren(...lines.map(t => el('li', null, t))); }
}
const SLD_RE = /\b(substations?|cables?|busbars?|feeders?|transformers?|earthing|leaf|dead ends?|grid)\b/i;
function paintQuestions() {
if (!$('questions').open) return;
const read = D.ring.map(v => [v, D.parsed.get(v.file)]).filter(([, e]) => e && !e.failed);
const key = `${read.length}:${D.edges.sup.length}`;
if ($('q-draw').dataset.key === key) return;
$('q-draw').dataset.key = key;
if (!read.length) return;
const items = [];
const repos = new Map();
let noText = 0;
for (const [v, e] of read) {
if (!e.p.sections) { noText++; continue; }
const hay = `${e.p.sections.Disease || ''}\n${e.p.sections.Symptom || ''}`;
const m = hay.match(SLD_RE);
if (m) {
const first = (e.p.sections.Disease || '').split(/(?<=\.)\s/)[0];
const li = el('li');
li.append(el('code', null, V.adapt(v.slug)), ` matched "${m[0]}": ${V.adapt(first)}`);
items.push(li);
}
for (const r of V.reposNamed(e.p.sections.Provenance || '')) repos.set(r, (repos.get(r) || []).concat(v.slug));
}
$('q-draw').replaceChildren(...(items.length ? items : [el('li', 'dim', `EMPTY — none of the ${read.length} files read names a grid element in Disease or Symptom.`)]));
const next = $('q-next'); next.textContent = '';
const sup = D.edges.sup.map(e => `${V.adapt(D.ring[e.a].slug)} is retired in favour of ${V.adapt(D.ring[e.b].slug)}`);
next.append(sup.length ? `Inside the registry: ${sup.join('; ')}. ` : 'Inside the registry: no superseded_by edge among the files read. ');
const rs = [...repos.entries()].sort((a, b) => b[1].length - a[1].length);
next.append(rs.length ? `Out of the registry, the repositories named in Provenance, where each disease was first observed (name-match on "Ventusltd/…"): ${rs.map(([r, s]) => `${r} (${s.length})`).join(', ')}. ` : 'Out of the registry: no Provenance read names a Ventusltd repository. ');
next.append(`Each consumer workflow runs inoculate.mjs on its own push, so the next element is that repository's pinned call; which cvaa commit each consumer pins is not established here.${noText ? ` ${noText} files had their text dropped by the memory cap and were not searched; tap one to read it again.` : ''}`);
}
function paintMachine() {
const c = RT.ring.loaded ? counts() : null;
setText('machine', `Machine detail · inputs: GitHub contents listing of vaccines/ at ${COMMIT} (JSON: file name, bytes); vaccines.lock (JSON: file name → sha256, 64 hex); each vaccine file (UTF-8 markdown bytes); vaccines/last-fired.json (JSON: vaccine name → sha, the 40-hex commit of the repository inoculated, and at, ISO-8601 UTC). Outputs: ring rank by 12-digit timestamp (dimensionless), sha2 … [line shortened here: 891 characters; full line on GitHub]
}
/* ── the card ───────────────────────────────────────────────────────────── */
const DOSE_WORDS = { 'every-loop': 'every loop', 'every-commit': 'every commit', 'every-deploy': 'every deploy' };
const tsWords = ts => `${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)} ${ts.slice(8, 10)}:${ts.slice(10, 12)}`;
async function select(i) {
if (!D.ring.length) return;
S.sel = (i + D.ring.length) % D.ring.length;
const epoch = ++S.epoch;
const v = D.ring[S.sel];
schedule();
const card = $('card');
card.replaceChildren(el('h3', null, V.adapt(v.slug)), el('p', 'dim', `LOAD — reading ${V.adapt(v.file)} at ${short(COMMIT)}…`));
tick('fired');
const [e] = await Promise.all([loadFile(v.file), hydrate('fired')]);
if (epoch !== S.epoch) return;
paintCard(v, e);
refresh();
}
function row(dl, dt, dd) { dl.append(el('dt', null, dt)); const d = el('dd'); if (typeof dd === 'string') d.textContent = dd; else d.append(...[].concat(dd)); dl.append(d); return d; }
function paintCard(v, e) {
const card = $('card');
const nodes = [];
const h = el('h3', null, V.adapt(v.slug));
nodes.push(h);
if (e.adapted) { const note = el('p'); note.append(el('span', 'adapted', 'wording adapted for this page: a private word for illusion is shown as "illusion"; the file on GitHub holds the original bytes, and the hash below is over those bytes')); nodes.push(note); }
const dl = el('dl');
row(dl, 'timestamp', `${tsWords(v.ts)} · ${v.ts}, position ${S.sel + 1} of ${D.ring.length} on the ring`);
if (e.failed) {
row(dl, 'file', `FAIL — ${e.why}. Tap the node again to retry.`);
D.parsed.delete(v.file);
} else {
const m = e.p.meta || {};
row(dl, 'generation', m.generation ? `${m.generation}${m.generation === v.ts ? ' (equals the filename timestamp)' : ' (differs from the filename timestamp)'}` : 'EMPTY — no generation in front matter');
row(dl, 'dose', m.dose ? `${DOSES_OK(m.dose)}` : 'EMPTY — no dose in front matter');
row(dl, 'superseded_by', m.superseded_by ? `${V.adapt(m.superseded_by)} — this vaccine is retired and inoculate.mjs skips it` : 'none: this vaccine is active');
if (!e.p.sections) row(dl, 'sections', 'the section text was dropped by the memory cap; tap again to read it');
else {
row(dl, 'Disease', V.adapt(e.p.sections.Disease || 'EMPTY — no Disease section'));
row(dl, 'Symptom', V.adapt(e.p.sections.Symptom || 'EMPTY — no Symptom section'));
row(dl, 'Dose', V.adapt(e.p.sections.Dose || 'EMPTY — no Dose section'));
row(dl, 'Provenance', V.adapt(e.p.sections.Provenance || 'EMPTY — no Provenance section'));
const pre = el('pre');
pre.textContent = e.p.code == null ? 'EMPTY — no ```js block' : V.adapt(e.p.code); // text only, never executed
row(dl, 'Antibody (source, not run)', pre);
}
const st = el('span', 'state', e.status.state);
row(dl, 'sha256', [st, ` — ${V.adapt(e.status.detail)}`, el('br'), el('code', null, e.rawHex || 'NOT COMPUTED: SubtleCrypto is not available in this browser context'), ` over ${e.bytes} bytes`]);
if (e.p.problems.length) row(dl, 'rules', V.adapt(e.p.problems.join('; ')));
}
const name = (e.p && e.p.meta && e.p.meta.vaccine) || v.slug;
if (D.fired && D.fired[name]) {
const f = D.fired[name];
row(dl, 'last fired', `${f.at || 'time not recorded'} · commit ${f.sha || 'not recorded'}`);
} else if (D.fired === null) row(dl, 'last fired', `no firing recorded — ${D.firedWhy}`);
else if (D.fired) row(dl, 'last fired', 'no firing recorded — last-fired.json has no entry for this vaccine');
else row(dl, 'last fired', `not yet known — ${($('lbl-fired').textContent.match(/\[(.*)\]/) || [])[1] || 'WAIT'}`);
nodes.push(dl);
const btns = el('p', 'btns');
btns.append(link(BLOB + 'vaccines/' + v.file, 'CODE', 'btn'), link(BLOB + 'README.md', 'APP', 'btn'));
nodes.push(btns);
const fx = el('details', 'fixture');
fx.append(el('summary', 'small', 'Diseased fixture in tools/selftest.mjs'), el('p', 'small dim', 'WAIT — opens on tap.'));
fx.addEventListener('toggle', () => { if (fx.open) paintFixture(fx, v.slug); });
nodes.push(fx);
card.replaceChildren(...nodes);
}
const DOSES_OK = d => (V.DOSES.includes(d) ? `${d}: the antibody is meant to run ${DOSE_WORDS[d]}` : `${V.adapt(d)} — not one of ${V.DOSES.join(' | ')}`);
async function paintFixture(fx, slug) {
const p = fx.querySelector('p');
p.textContent = 'LOAD — reading tools/selftest.mjs…';
try {
const src = await fetchOnce(URL_SELFTEST, 'text');
const lines = src.split('\n');
const idx = lines.findIndex(l => l.includes(`'${slug}':`) || l.includes(`"${slug}":`));
p.textContent = '';
if (idx < 0) { p.append(`EMPTY — no DISEASED entry keyed '${V.adapt(slug)}' found by name-match in tools/selftest.mjs; the selftest may exercise this antibody another way.`); return; }
p.append(`The DISEASED table keys a fixture for this vaccine at line ${idx + 1} (name-match). selftest requires the antibody to fire on it and stay silent on CLEAN. `, link(`${BLOB}tools/selftest.mjs#L${idx + 1}`, 'CODE', 'btn'));
const pre = el('pre');
pre.textContent = V.adapt(lines.slice(idx, idx + 6).join('\n'));
p.after(pre);
} catch (err) { p.textContent = `FAIL — ${err.message}. Close and open again to retry.`; }
}
/* ── the ring ───────────────────────────────────────────────────────────── */
const canvas = $('ring');
const ctx = canvas.getContext('2d');
let W = 0, H = 0, DPR = 1;
function resize() {
const r = canvas.getBoundingClientRect();
DPR = Math.min(2, window.devicePixelRatio || 1);
W = r.width; H = r.height;
canvas.width = Math.round(W * DPR); canvas.height = Math.round(H * DPR);
if (!S.fitted) fit(); else schedule();
}
const baseK = () => Math.min(W, H) * (W >= 700 ? 0.3 : 0.4);
function fit() { S.view = { x: 0, y: 0, k: baseK() }; S.fitted = W > 0; schedule(); }
const sx = x => W / 2 + (x - S.view.x) * S.view.k;
const sy = y => H / 2 + (y - S.view.y) * S.view.k;
const wx = px => (px - W / 2) / S.view.k + S.view.x;
const wy = py => (py - H / 2) / S.view.k + S.view.y;
const pos = i => { const t = -Math.PI / 2 + (2 * Math.PI * i) / D.ring.length; return [Math.cos(t), Math.sin(t), t]; };
let queued = false, lastDraw = 0;
function schedule() { if (!queued) { queued = true; requestAnimationFrame(() => { queued = false; draw(); }); } }
function cased(path, color, width, dash) {
ctx.setLineDash([]); ctx.lineCap = 'round';
ctx.strokeStyle = '#000'; ctx.lineWidth = width + 3; path(); ctx.stroke();
ctx.setLineDash(dash || []); ctx.strokeStyle = color; ctx.lineWidth = width; path(); ctx.stroke();
ctx.setLineDash([]);
}
const COL = { gen: '#9aa3b8', 'every-loop': '#5ec8f2', 'every-commit': '#c9a2ff', 'every-deploy': '#f2a7c8' };
function draw() {
const t0 = performance.now();