auto-optimize 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. auto_optimize/__init__.py +3 -0
  2. auto_optimize/__main__.py +5 -0
  3. auto_optimize/cli.py +651 -0
  4. auto_optimize/skills/auto-optimize-code/LICENSE +21 -0
  5. auto_optimize/skills/auto-optimize-code/SKILL.md +251 -0
  6. auto_optimize/skills/auto-optimize-code/VERSION +1 -0
  7. auto_optimize/skills/auto-optimize-code/references/algorithm.md +182 -0
  8. auto_optimize/skills/auto-optimize-code/references/changes.md +146 -0
  9. auto_optimize/skills/auto-optimize-code/references/cli.md +206 -0
  10. auto_optimize/skills/auto-optimize-code/references/dashboard.md +203 -0
  11. auto_optimize/skills/auto-optimize-code/references/documents.md +55 -0
  12. auto_optimize/skills/auto-optimize-code/references/extending.md +87 -0
  13. auto_optimize/skills/auto-optimize-code/references/external-validation.md +98 -0
  14. auto_optimize/skills/auto-optimize-code/references/glossary.md +134 -0
  15. auto_optimize/skills/auto-optimize-code/references/idea-miner.md +108 -0
  16. auto_optimize/skills/auto-optimize-code/references/issue-bugs.md +182 -0
  17. auto_optimize/skills/auto-optimize-code/references/layout.md +300 -0
  18. auto_optimize/skills/auto-optimize-code/references/main-session.md +45 -0
  19. auto_optimize/skills/auto-optimize-code/references/measuring.md +208 -0
  20. auto_optimize/skills/auto-optimize-code/references/pr-optimization.md +127 -0
  21. auto_optimize/skills/auto-optimize-code/references/pr-tests.md +254 -0
  22. auto_optimize/skills/auto-optimize-code/references/promotion.md +133 -0
  23. auto_optimize/skills/auto-optimize-code/references/reading-a-search.md +65 -0
  24. auto_optimize/skills/auto-optimize-code/references/repo-mode.md +224 -0
  25. auto_optimize/skills/auto-optimize-code/references/resume.md +81 -0
  26. auto_optimize/skills/auto-optimize-code/references/shared-knowledge.md +114 -0
  27. auto_optimize/skills/auto-optimize-code/references/step0-interview.md +298 -0
  28. auto_optimize/skills/auto-optimize-code/references/step1-unit-tests.md +136 -0
  29. auto_optimize/skills/auto-optimize-code/references/step2-baseline.md +708 -0
  30. auto_optimize/skills/auto-optimize-code/references/step3-rounds.md +350 -0
  31. auto_optimize/skills/auto-optimize-code/references/step4-final.md +121 -0
  32. auto_optimize/skills/auto-optimize-code/references/step5-ship.md +220 -0
  33. auto_optimize/skills/auto-optimize-code/references/step6-finish.md +67 -0
  34. auto_optimize/skills/auto-optimize-code/references/subagent.md +467 -0
  35. auto_optimize/skills/auto-optimize-code/references/symptoms.md +67 -0
  36. auto_optimize/skills/auto-optimize-code/references/writing-briefs.md +117 -0
  37. auto_optimize/skills/auto-optimize-code/scripts/attribution.py +156 -0
  38. auto_optimize/skills/auto-optimize-code/scripts/autoopt.py +12863 -0
  39. auto_optimize/skills/auto-optimize-code/scripts/check_seeding.py +334 -0
  40. auto_optimize/skills/auto-optimize-code/scripts/cold.py +90 -0
  41. auto_optimize/skills/auto-optimize-code/scripts/dashboard/README.md +165 -0
  42. auto_optimize/skills/auto-optimize-code/scripts/dashboard/autoopt_monitor.py +850 -0
  43. auto_optimize/skills/auto-optimize-code/scripts/dashboard/gpu_scan.py +954 -0
  44. auto_optimize/skills/auto-optimize-code/scripts/dashboard/monitor_writer.py +684 -0
  45. auto_optimize/skills/auto-optimize-code/scripts/dashboard/scan.py +1030 -0
  46. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.css +775 -0
  47. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.js +3652 -0
  48. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/index.html +191 -0
  49. auto_optimize/skills/auto-optimize-code/scripts/issue_body.py +2118 -0
  50. auto_optimize/skills/auto-optimize-code/scripts/lint_text.py +448 -0
  51. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_body.py +894 -0
  52. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_tables.py +367 -0
  53. auto_optimize/skills/auto-optimize-code/scripts/paired.py +188 -0
  54. auto_optimize/skills/auto-optimize-code/scripts/preflight.py +280 -0
  55. auto_optimize/skills/auto-optimize-code/scripts/probe_run.py +72 -0
  56. auto_optimize/skills/auto-optimize-code/scripts/publish.py +385 -0
  57. auto_optimize/skills/auto-optimize-code/scripts/run_iteration.py +1382 -0
  58. auto_optimize/skills/auto-optimize-code/scripts/ship.py +1193 -0
  59. auto_optimize/skills/auto-optimize-code/scripts/stages.py +651 -0
  60. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_body.py +1267 -0
  61. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_push.py +426 -0
  62. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_tables.py +779 -0
  63. auto_optimize-1.0.0.dist-info/METADATA +610 -0
  64. auto_optimize-1.0.0.dist-info/RECORD +67 -0
  65. auto_optimize-1.0.0.dist-info/WHEEL +4 -0
  66. auto_optimize-1.0.0.dist-info/entry_points.txt +2 -0
  67. auto_optimize-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,3652 @@
1
+ 'use strict';
2
+
3
+ /* dashboard.js -- the auto-optimize-code monitor.
4
+
5
+ One entry point, `window.startAutoopt(root, transport, options)`. The mount
6
+ supplies the transport: the notebook passes one that reads published JSON
7
+ through Jupyter's Contents API, the standalone page (tests only) one that
8
+ fetches the same files over HTTP, and an export one that reads an embedded
9
+ snapshot. Nothing below knows which.
10
+
11
+ Loaded as an ES module, and it must stay one. As a classic script a second
12
+ copy in one page throws `Identifier ... has already been declared`, the
13
+ second copy never runs, and the first keeps serving a stale page silently.
14
+
15
+ Sections are delimited by `==== SECTION: <name> ====` and match the ones in
16
+ dashboard.css and index.html. */
17
+
18
+ /* ==== SECTION: core ==== */
19
+
20
+ let STATE_INTERVAL = 20000;
21
+ let RESOURCE_INTERVAL = 3000;
22
+
23
+ const state = {
24
+ snapshot: null,
25
+ resources: null,
26
+ lastGpus: null, // {gpus, sampledAt}: the last sample that had GPUs
27
+ selection: null, // Set of iteration ids, or null for "everything"
28
+ hidden: new Set(), // categories hidden by a chip's dot
29
+ emphasised: new Set(), // categories emphasised by clicking their chip
30
+ assetsStale: false,
31
+ pinned: null, // iteration clicked: its runs are outlined in Every run
32
+ pinnedSeed: null, // the run clicked, when it was a run's own dot
33
+ hideFailed: false,
34
+ showStair: true,
35
+ showStages: true, // a dashed line wherever the tree's generation changes
36
+ showCI: false, // dotted whiskers: each median's bootstrap interval
37
+ showRuns: false, // every seed's own score, not just the median
38
+ treeNode: null, // iteration whose panel is open under the tree
39
+ readmes: {}, // id -> whole README text (null: could not be read)
40
+ readmeFor: {}, // id -> the payload excerpt the text was fetched against
41
+ logFull: new Set(), // log entries showing their whole README (SHOW MORE)
42
+ diffOpen: null, // iteration whose code change is open under the objective chart
43
+ diffs: {}, // id -> payload (null: could not be read, with diffTried)
44
+ diffFor: {}, // id -> the commit the payload was fetched for
45
+ diffTried: {}, // id -> browser time of a failed fetch
46
+ diffShown: null, // what the panel last drew, so a poll redraws only a change
47
+ };
48
+
49
+ /* The version this script was fetched with. The mount bakes a cache-busting
50
+ query into the URL, so if the published front end differs from this copy,
51
+ this copy is stale and only re-running the cell replaces it. */
52
+ const LOADED_ASSETS = (() => {
53
+ try {
54
+ return new URL(import.meta.url).searchParams.get('v');
55
+ } catch (error) {
56
+ return null;
57
+ }
58
+ })();
59
+
60
+ let ROOT = document.body;
61
+ let TRANSPORT = null;
62
+ const timers = [];
63
+
64
+ const $ = (id) => ROOT.querySelector('#' + id);
65
+ const css = (name) => getComputedStyle(ROOT).getPropertyValue(name).trim();
66
+
67
+ /* `$(id).replaceChildren()` on a missing node throws inside the poll's try,
68
+ which silently stops every later panel. This keeps the rest alive. */
69
+ function fill(id, ...children) {
70
+ const node = $(id);
71
+ if (node) node.replaceChildren(...children.filter((c) =>
72
+ c !== null && c !== undefined && c !== false));
73
+ return node;
74
+ }
75
+
76
+ /* `el('div', {class, text, style, dataset, onclick}, [children])`. Null
77
+ children are dropped: `replaceChildren(null)` inserts the text "null". */
78
+ function el(tag, attrs, children) {
79
+ const node = document.createElement(tag);
80
+
81
+ for (const [key, value] of Object.entries(attrs || {})) {
82
+ if (value === null || value === undefined || value === false) continue;
83
+ if (key === 'text') node.textContent = value;
84
+ else if (key === 'class') node.className = value;
85
+ else if (key === 'dataset') Object.assign(node.dataset, value);
86
+ else if (key.startsWith('on')) node.addEventListener(key.slice(2), value);
87
+ else node.setAttribute(key, value === true ? '' : value);
88
+ }
89
+
90
+ for (const child of [].concat(children || []))
91
+ if (child !== null && child !== undefined && child !== false)
92
+ node.append(child.nodeType ? child : document.createTextNode(child));
93
+
94
+ return node;
95
+ }
96
+
97
+ const missing = (x) => x === null || x === undefined || Number.isNaN(x);
98
+
99
+ // `A107`: every iteration is shown with the label's letter, as the scripts
100
+ // print it.
101
+ const tag = (id) => missing(id) ? '–' : 'A' + id;
102
+
103
+ const fmt = {
104
+ int: (x) => missing(x) ? '–' : Math.round(x).toLocaleString(),
105
+ num: (x, digits = 3) => missing(x) ? '–' : Number(x).toFixed(digits),
106
+ /* Four significant digits, scientific only outside [1e-4, 1e6). */
107
+ sig: (x, digits = 4) => {
108
+ if (missing(x)) return '–';
109
+ const size = Math.abs(x);
110
+ if (size !== 0 && (size < 1e-4 || size >= 1e6))
111
+ return Number(x).toExponential(2);
112
+ return Number(Number(x).toPrecision(digits)).toString();
113
+ },
114
+ signed: (x, digits = 2) => missing(x) ? '–'
115
+ : (x >= 0 ? '+' : '') + Number(x).toFixed(digits),
116
+ pct: (x) => missing(x) ? '–' : Math.round(x) + '%',
117
+ signedPct: (x) => missing(x) ? '–' : (x >= 0 ? '+' : '') + Math.round(x) + '%',
118
+ bytes: (x) => {
119
+ if (missing(x)) return '–';
120
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
121
+ let i = 0;
122
+ while (x >= 1024 && i < units.length - 1) { x /= 1024; i += 1; }
123
+ return x.toFixed(x >= 100 || i === 0 ? 0 : 1) + ' ' + units[i];
124
+ },
125
+ duration: (seconds) => {
126
+ if (missing(seconds)) return '–';
127
+ seconds = Math.max(0, Math.round(seconds));
128
+ const d = Math.floor(seconds / 86400);
129
+ const h = Math.floor((seconds % 86400) / 3600);
130
+ const m = Math.floor((seconds % 3600) / 60);
131
+ if (d) return `${d}d ${h}h`;
132
+ if (h) return `${h}h ${m}m`;
133
+ if (m) return `${m}m ${seconds % 60}s`;
134
+ return `${seconds}s`;
135
+ },
136
+ };
137
+
138
+ const escape = (text) => String(missing(text) ? '' : text)
139
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
140
+
141
+ /* ==== SECTION: colour ==== */
142
+
143
+ /* A token as a plain colour Plotly and canvas can parse. `css()` returns the
144
+ token's text, and `--running` is a `color-mix()` that Plotly rejects and a
145
+ canvas reads back as `color(srgb ...)`; painting one pixel and reading it
146
+ back gives `#rrggbb` (or `rgba()` when translucent). Takes a token name or
147
+ a colour. Use it for every colour that reaches Plotly or a canvas. */
148
+ const resolvedCache = new Map();
149
+ let resolveCtx = null;
150
+
151
+ function resolved(token) {
152
+ const value = token.startsWith('--') ? css(token) : token;
153
+ if (/^#[0-9a-f]{6}$/i.test(value) || /^rgba?\(/i.test(value)) return value;
154
+ if (resolvedCache.has(value)) return resolvedCache.get(value);
155
+
156
+ resolveCtx = resolveCtx || document.createElement('canvas')
157
+ .getContext('2d', { willReadFrequently: true });
158
+ resolveCtx.clearRect(0, 0, 1, 1);
159
+ resolveCtx.fillStyle = value;
160
+ resolveCtx.fillRect(0, 0, 1, 1);
161
+
162
+ const [r, g, b, a] = resolveCtx.getImageData(0, 0, 1, 1).data;
163
+ const hex = '#' + [r, g, b].map((c) => c.toString(16).padStart(2, '0'))
164
+ .join('');
165
+ const out = a === 255 ? hex : `rgba(${r},${g},${b},${(a / 255).toFixed(3)})`;
166
+
167
+ resolvedCache.set(value, out);
168
+ return out;
169
+ }
170
+
171
+ /* Four muted hues, then the shape carries the group as a second channel:
172
+ group i takes hue i % 4 and symbol floor(i / 4). Pink is not a slot: it
173
+ is the frontier line and the headline. A catch-all group (any name in
174
+ CATCH_ALL) is always grey circles. Indices come from every group in the
175
+ payload, never the visible subset, so a group keeps its colour and shape
176
+ when a filter changes. */
177
+ const CAT_SLOTS = ['--cat-0', '--cat-1', '--cat-2', '--cat-3', '--cat-4',
178
+ '--cat-5', '--cat-6', '--cat-7', '--cat-8', '--cat-9'];
179
+ const LINE_SLOTS = CAT_SLOTS.slice(0, 8).concat(['--line-4', '--line-5']);
180
+
181
+ /* A grouping whose values are verdicts (pass / marginal / fail) takes the
182
+ state tones, not the categorical slots: muted for the bulk, full strength
183
+ for emphasis. An unrecognised value is the catch-all grey. */
184
+ const VERDICT_TONES = { pass: 'good', ok: 'good', good: 'good',
185
+ marginal: 'warn', warn: 'warn', fail: 'bad', bad: 'bad' };
186
+
187
+ const verdictSlot = (value) => {
188
+ const tone = VERDICT_TONES[String(value).toLowerCase()];
189
+ return tone ? `--${tone}-muted` : '--cat-other';
190
+ };
191
+
192
+ /* The full-strength hue behind each muted slot, for emphasis: a frontier
193
+ point, a selected point, an emphasised category. */
194
+ const FULL = { '--cat-0': '--cyan', '--cat-1': '--purple', '--cat-2': '--orange',
195
+ '--cat-3': '--green', '--cat-4': '--blue', '--cat-5': '--olive',
196
+ '--cat-6': '--lime', '--cat-7': '--orchid', '--cat-8': '--clay',
197
+ '--cat-9': '--steel', '--line-4': '--yellow', '--line-5': '--cat-other-strong',
198
+ '--cat-other': '--cat-other-strong', '--cat-root': '--cat-root-strong',
199
+ '--good-muted': '--good', '--warn-muted': '--warn', '--bad-muted': '--bad' };
200
+ const emphasis = (slot) => resolved(FULL[slot] || slot);
201
+
202
+ const verdictColour = (value, emphasised) => emphasised
203
+ ? emphasis(verdictSlot(value)) : resolved(verdictSlot(value));
204
+
205
+ /* autoopt.py's catch-all category, and the baseline's own. ROOT holds only
206
+ iteration 0 and takes a fixed neutral outside the slots, so adding it
207
+ moved no other category's colour. */
208
+ const CATCH_ALL = new Set(['MISC']);
209
+ const ROOT_CATEGORY = 'ROOT';
210
+
211
+ /* Categories are the fixed list autoopt.py allows, so a category keeps its
212
+ colour across searches and whatever the chips hide. */
213
+ const CATEGORY_ORDER = ['CACHE_MISS', 'CACHING', 'MICRO', 'NUMBA', 'OPTIMIZATION',
214
+ 'PARALLEL', 'PRECISION', 'REORGANIZATION', 'IO', 'ALGORITHM'];
215
+
216
+ function groupIndex(group) {
217
+ const fixed = CATEGORY_ORDER.indexOf(group);
218
+ if (fixed >= 0) return fixed;
219
+ const extra = [...((state.snapshot || {}).categories || [])]
220
+ .filter((g) => !CATCH_ALL.has(g) && g !== ROOT_CATEGORY
221
+ && !CATEGORY_ORDER.includes(g)).sort();
222
+ const at = extra.indexOf(group);
223
+ return at < 0 ? -1 : CATEGORY_ORDER.length + at;
224
+ }
225
+
226
+ function groupSlot(group) {
227
+ if (group === ROOT_CATEGORY) return '--cat-root';
228
+ const i = groupIndex(group);
229
+ return i < 0 ? '--cat-other' : CAT_SLOTS[i % CAT_SLOTS.length];
230
+ }
231
+
232
+ /* Display order: ROOT first, the catch-all last, the rest by name. */
233
+ const categoryOrder = (a, b) => (b === ROOT_CATEGORY) - (a === ROOT_CATEGORY)
234
+ || CATCH_ALL.has(a) - CATCH_ALL.has(b) || a.localeCompare(b);
235
+
236
+ /* The legend mirrors the mark: same hue, same shape. symbol: a Plotly
237
+ marker symbol, 'x', or 'line', 'dotted', 'dashed' for a line trace;
238
+ opacity for a key of a faint layer. */
239
+ function markerKey(colour, symbol, opacity) {
240
+ // A line or dotted-line key for a trace drawn as a line (a frontier, a
241
+ // reference): the key draws the mark it names.
242
+ const lines = { line: `height:2px;width:12px;background:${colour}`,
243
+ dotted: `height:0;width:12px;border-top:2px dotted ${colour}`,
244
+ dashed: `height:0;width:12px;border-top:2px dashed ${colour}` };
245
+
246
+ const shapes = {
247
+ circle: 'border-radius:50%',
248
+ square: '',
249
+ diamond: 'transform:rotate(45deg) scale(.8)',
250
+ 'triangle-up': 'clip-path:polygon(50% 0,100% 100%,0 100%)',
251
+ cross: 'clip-path:polygon(38% 0,62% 0,62% 38%,100% 38%,100% 62%,'
252
+ + '62% 62%,62% 100%,38% 100%,38% 62%,0 62%,0 38%,38% 38%)',
253
+ // The baseline's mark: a cross rotated 45 degrees.
254
+ x: 'transform:rotate(45deg);clip-path:polygon(38% 0,62% 0,62% 38%,'
255
+ + '100% 38%,100% 62%,62% 62%,62% 100%,38% 100%,38% 62%,0 62%,'
256
+ + '0 38%,38% 38%)',
257
+ // Plotly's x-thin-open: an abandoned iteration.
258
+ 'x-thin': 'transform:rotate(45deg);clip-path:polygon(44% 0,56% 0,56% 44%,'
259
+ + '100% 44%,100% 56%,56% 56%,56% 100%,44% 100%,44% 56%,0 56%,'
260
+ + '0 44%,44% 44%)',
261
+ };
262
+
263
+ // .mark-key: a legend key is a mark, never a divider (spacing_check).
264
+ return el('span', { class: 'mark-key', style: 'display:inline-flex;width:12px;height:12px;'
265
+ + 'align-items:center;justify-content:center'
266
+ + (opacity !== undefined ? `;opacity:${opacity}` : '') }, [
267
+ el('span', { style: lines[symbol] || `width:9px;height:9px;background:${colour};`
268
+ + (shapes[symbol] || '') })]);
269
+ }
270
+
271
+ /* ==== SECTION: summary ==== */
272
+
273
+ function tile(label, value, delta, tone) {
274
+ return el('div', { class: 'tile', 'data-tone': tone || null }, [
275
+ el('div', { class: 'label', text: label }),
276
+ el('div', { class: 'value', text: value }),
277
+ el('div', { class: 'delta', text: delta || ' ' }),
278
+ ]);
279
+ }
280
+
281
+ /* ==== SECTION: sidebar ==== */
282
+
283
+ /* rows: [key, value, tone?]; a null row is skipped. */
284
+ function statCard(title, rows, note) {
285
+ return el('div', { class: 'stat-card' }, [
286
+ el('h3', { text: title }),
287
+ ...rows.filter(Boolean).map(([key, value, tone]) =>
288
+ el('div', { class: 'stat-row' }, [
289
+ el('span', { class: 'key', text: key, title: key }),
290
+ el('span', { class: 'val' + (tone ? ' ' + tone : ''),
291
+ text: value })])),
292
+ note ? el('div', { class: 'stat-note', text: note }) : null,
293
+ ]);
294
+ }
295
+
296
+ /* entries: [key, n]; colour(key) gives each bar its fill. */
297
+ function barCard(title, entries, colour, note) {
298
+ const max = Math.max(1, ...entries.map(([, n]) => n));
299
+
300
+ return el('div', { class: 'stat-card' }, [
301
+ el('h3', { text: title }),
302
+ el('div', { class: 'bar-list' }, entries.map(([key, n]) =>
303
+ el('div', { class: 'bar-row' }, [
304
+ el('span', { class: 'key', text: key, title: key }),
305
+ // True proportion: a floor would draw small counts larger
306
+ // than they are. One pixel only so a non-zero count shows.
307
+ el('span', { class: 'bar', style: `width:${100 * n / max}%;`
308
+ + `${n > 0 ? 'min-width:1px;' : ''}background:${colour(key)}` }),
309
+ el('span', { class: 'n', text: fmt.int(n) })]))),
310
+ note ? el('div', { class: 'stat-note', text: note }) : null,
311
+ ]);
312
+ }
313
+
314
+ /* ==== SECTION: plots ==== */
315
+
316
+ const plotted = new Set();
317
+ const plotly = () => window.Plotly || null;
318
+
319
+ /* The axis title keeps a standoff from the tick labels, and automargin
320
+ makes room for both, so the two never meet. A caller's `title` is merged
321
+ into the default rather than replacing it. With `automargin: false` (a
322
+ fixed margin), leave the y title out and name the quantity in the panel
323
+ title instead. */
324
+ function axis(overrides) {
325
+ overrides = overrides || {};
326
+ const title = Object.assign({ font: { color: resolved('--text-faint'),
327
+ size: 11 }, standoff: 8 }, overrides.title || {});
328
+
329
+ return Object.assign({
330
+ gridcolor: resolved('--line-soft'),
331
+ zeroline: false,
332
+ linecolor: resolved('--line'),
333
+ tickcolor: resolved('--line'),
334
+ tickfont: { color: resolved('--text-faint'), size: 10 },
335
+ automargin: true,
336
+ }, overrides, { title });
337
+ }
338
+
339
+ /* The ticks of a log axis: gridlines and labels at decades only (1, 10,
340
+ 100), or at 1-2-5 when the positive values span two decades or less; the
341
+ 2-9 between are short unlabelled minor ticks with no gridline. Every label
342
+ is the tick's full value (20, 50, 200): Plotly's own 1-2-5 mode ('D2')
343
+ prints the 2s and 5s as bare leading digits. Spread into axis() whenever
344
+ scaleOf() says 'log'; a linear axis gets {}. */
345
+ function logTicks(values, type) {
346
+ if (type !== 'log') return {};
347
+
348
+ // The range is set here rather than left to Plotly's autorange, so the
349
+ // rule decides from the axis as drawn: the data's decades plus 5% of
350
+ // them (at least 0.05) either side. Two decades or less of drawn axis
351
+ // is 1-2-5; more is decades. spacing_check reads the same range.
352
+ const positive = values.filter((v) => v > 0);
353
+ if (!positive.length) return {};
354
+ const lo = Math.log10(Math.min(...positive));
355
+ const hi = Math.log10(Math.max(...positive));
356
+ const pad = Math.max(0.05, 0.05 * (hi - lo));
357
+ const range = [lo - pad, hi + pad];
358
+
359
+ let tickvals = logTickValues(range, range[1] - range[0] <= 2 ? [1, 2, 5] : [1]);
360
+ // A narrow axis (forced to log by its button) may hold fewer than two of
361
+ // those; then every 1-9 step is labelled.
362
+ if (tickvals.length < 2) tickvals = logTickValues(range, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
363
+
364
+ return { range, autorange: false, tickmode: 'array', tickvals,
365
+ ticktext: tickvals.map((value) => value.toLocaleString('en-US',
366
+ { maximumSignificantDigits: 1 })),
367
+ minor: { ticks: 'outside', ticklen: 3, tickcolor: resolved('--line'),
368
+ showgrid: false, dtick: 'D1' } };
369
+ }
370
+
371
+ /* The values step x 10^k (for each step given) that fall inside a log
372
+ axis's range, which is in log10 units. */
373
+ function logTickValues(range, steps) {
374
+ const values = [];
375
+ for (let k = Math.floor(range[0]) - 1; k <= Math.ceil(range[1]); k++)
376
+ for (const step of steps) {
377
+ const value = Number((step * 10 ** k).toPrecision(1));
378
+ const at = Math.log10(value);
379
+ if (at >= range[0] && at <= range[1]) values.push(value);
380
+ }
381
+ return values;
382
+ }
383
+
384
+ /* Flat: paper and plot area are the page colour, so the data sits on the
385
+ page with no box. Faint grid on both axes. The hover label is monospace,
386
+ which the aligned tooltip block needs. */
387
+ function plotLayout(overrides) {
388
+ return Object.assign({
389
+ // Every plot sits in a panel.
390
+ paper_bgcolor: resolved('--panel'),
391
+ plot_bgcolor: resolved('--panel'),
392
+ font: { family: 'system-ui, -apple-system, sans-serif', size: 11,
393
+ color: resolved('--text-dim') },
394
+ margin: { l: 54, r: 14, t: 10, b: 40 },
395
+ hovermode: 'closest',
396
+ hoverlabel: { bgcolor: resolved('--tip-bg'), bordercolor: resolved('--line'),
397
+ font: { color: resolved('--text'), size: 11,
398
+ family: 'ui-monospace, Menlo, monospace' }, align: 'left' },
399
+ showlegend: false,
400
+ dragmode: 'lasso',
401
+ xaxis: axis(),
402
+ yaxis: axis(),
403
+ }, overrides || {});
404
+ }
405
+
406
+ /* Charts that start a selection keep a trimmed modebar, so the reader can
407
+ swap between lasso, box select and zoom. */
408
+ const SELECT_CONFIG = {
409
+ responsive: true,
410
+ displaylogo: false,
411
+ modeBarButtonsToRemove: ['toImage', 'sendDataToCloud', 'toggleSpikelines',
412
+ 'hoverClosestCartesian', 'hoverCompareCartesian', 'autoScale2d'],
413
+ };
414
+ const PLAIN_CONFIG = { displayModeBar: false, responsive: true };
415
+
416
+ /* options: {ids, selectable, onHover, onClick, config}. `ids[i]` is the row
417
+ behind input point i, so a selection event can be turned back into ids
418
+ whatever the trace layout. onClick(id) and onHover(id) receive the point's
419
+ customdata; onHover(null) when the pointer leaves the points. Each handler
420
+ is wired once per node. */
421
+ function draw(id, traces, layout, options) {
422
+ const P = plotly();
423
+ const node = $(id);
424
+ if (!node) return null;
425
+
426
+ if (!P) {
427
+ node.replaceChildren(el('div', { class: 'empty', text: 'Plotly failed '
428
+ + 'to load, so the charts are unavailable. The sidebar still '
429
+ + 'carries the numbers.' }));
430
+ return null;
431
+ }
432
+
433
+ options = options || {};
434
+ plotted.add(id);
435
+ if (options.ids) node._ids = options.ids;
436
+
437
+ // A node whose plot was replaced (an empty state filled in, then data
438
+ // again) still carries Plotly's layout, and react() would skip the
439
+ // redraw. Purge it, and its handlers with it.
440
+ if (node.layout && !node.querySelector('.main-svg')) {
441
+ P.purge(node);
442
+ node._wired = node._clickWired = node._hoverWired = false;
443
+ }
444
+
445
+ P.react(node, traces, layout, options.config || PLAIN_CONFIG);
446
+ if (sizeWatch) sizeWatch.observe(node);
447
+
448
+ if (options.selectable && !node._wired) {
449
+ node._wired = true;
450
+ node.on('plotly_selected', (event) => onBrush(node, event));
451
+ node.on('plotly_deselect', () => setSelection(null));
452
+ node.on('plotly_doubleclick', () => setSelection(null));
453
+ }
454
+
455
+ node._onClick = options.onClick;
456
+ node._onHover = options.onHover;
457
+
458
+ if (options.onHover && !node._hoverWired) {
459
+ node._hoverWired = true;
460
+ node.on('plotly_hover', (event) => {
461
+ const point = event.points && event.points[0];
462
+ if (point && point.customdata !== undefined && node._onHover)
463
+ node._onHover(point.customdata);
464
+ });
465
+ node.on('plotly_unhover', () => { if (node._onHover) node._onHover(null); });
466
+ }
467
+
468
+ if (options.onClick && !node._clickWired) {
469
+ node._clickWired = true;
470
+ node.on('plotly_click', (event) => {
471
+ const point = event.points && event.points[0];
472
+ if (point && point.customdata !== undefined && node._onClick)
473
+ node._onClick(point.customdata);
474
+ });
475
+ }
476
+
477
+ return node;
478
+ }
479
+
480
+ let rendering = false;
481
+
482
+ /* Re-rendering the other charts wipes this one's lasso, and Plotly reports
483
+ that as a fresh selection of nothing. Ignore our own redraws and every
484
+ empty selection; clearing is explicit (deselect, double-click, the Clear
485
+ button). */
486
+ function onBrush(node, event) {
487
+ if (rendering || !event || !event.points || !event.points.length) return;
488
+
489
+ const ids = new Set();
490
+
491
+ for (const point of event.points) {
492
+ if (point.pointNumbers && node._ids) {
493
+ for (const index of point.pointNumbers)
494
+ if (node._ids[index] !== undefined) ids.add(node._ids[index]);
495
+ } else if (point.customdata !== undefined) {
496
+ ids.add(point.customdata);
497
+ }
498
+ }
499
+
500
+ setSelection(ids.size ? ids : null);
501
+ }
502
+
503
+ /* Everything that follows a selection registers here: charts, tables, the
504
+ tree. `setSelection` re-renders each, under the redraw guard. */
505
+ const selectionListeners = [];
506
+
507
+ function setSelection(ids) {
508
+ state.selection = ids;
509
+ $('clear-selection').hidden = !ids;
510
+
511
+ rendering = true;
512
+ try {
513
+ for (const render of selectionListeners) render();
514
+ } finally {
515
+ setTimeout(() => { rendering = false; }, 250);
516
+ }
517
+ }
518
+
519
+ /* A row is emphasised when it is in the selection (or there is none) and its
520
+ group is emphasised by a chip (or none is). `groupOf` reads the row's
521
+ group; rows without one follow the selection only. */
522
+ function isEmphasised(row, groupOf) {
523
+ const group = (groupOf || ((r) => r.group))(row);
524
+ return (!state.selection || state.selection.has(row.id))
525
+ && (!state.emphasised.size || group === undefined
526
+ || state.emphasised.has(group));
527
+ }
528
+
529
+ /* Indices of the emphasised `rows`, or undefined when nothing is selected
530
+ or emphasised, which Plotly reads as "everything selected". */
531
+ function selectedIndices(rows, groupOf) {
532
+ if (!state.selection && !state.emphasised.size) return undefined;
533
+
534
+ const out = [];
535
+ rows.forEach((row, index) => {
536
+ if (isEmphasised(row, groupOf)) out.push(index);
537
+ });
538
+
539
+ return out;
540
+ }
541
+
542
+ /* One chip per category with its count. Clicking a chip emphasises its
543
+ category in every linked chart (the rest fade, as in a selection); several
544
+ may be emphasised, and clicking again clears. The dot at the chip's end
545
+ hides the category instead: gone from every chart and the log, dimmed in
546
+ a tree. `hidden` and `emphasised` are Sets the caller owns and every
547
+ renderer reads; `onChange` re-renders all of them, this included. */
548
+ function categoryChips(holderId, counts, colourOf, hidden, emphasised,
549
+ onChange) {
550
+ fill(holderId, ...Object.entries(counts).map(([category, n]) => {
551
+ const shown = !hidden.has(category);
552
+ const on = emphasised.has(category);
553
+
554
+ return el('span', { class: 'chip', style: `color:${colourOf(category)}`,
555
+ dataset: { category, emphasised: String(on), hidden: String(!shown) } }, [
556
+ el('button', { class: 'chip-main', type: 'button',
557
+ 'aria-pressed': String(on), title: 'Emphasise in every chart',
558
+ onclick: () => {
559
+ if (on) emphasised.delete(category);
560
+ else { emphasised.add(category); hidden.delete(category); }
561
+ onChange();
562
+ } }, [
563
+ el('span', { class: 'dot', style: `background:${colourOf(category)}` }),
564
+ el('b', { text: fmt.int(n) }), category]),
565
+ el('button', { class: 'eye', type: 'button',
566
+ 'aria-pressed': String(shown), text: shown ? '●' : '○',
567
+ title: shown ? 'Hide everywhere' : 'Show again',
568
+ onclick: () => {
569
+ if (shown) { hidden.add(category); emphasised.delete(category); }
570
+ else hidden.delete(category);
571
+ onChange();
572
+ } }),
573
+ ]);
574
+ }));
575
+ }
576
+
577
+ /* Log axes: automatic, with a per-plot override. An axis flagged log-able
578
+ goes log when its positive values span at least a decade; the buttons
579
+ under the plot override that, and say how many points a log axis hides,
580
+ because Plotly omits non-positive values on one silently. */
581
+ const SCALES = {};
582
+
583
+ function autoLog(values) {
584
+ const positive = values.filter((v) => v > 0);
585
+ return positive.length > 1
586
+ && Math.log10(Math.max(...positive) / Math.min(...positive)) >= 1;
587
+ }
588
+
589
+ function scaleOf(plot, which, values, logable) {
590
+ const chosen = (SCALES[plot] || {})[which];
591
+ if (chosen) return chosen;
592
+ return logable && autoLog(values) ? 'log' : 'linear';
593
+ }
594
+
595
+ /* `rerender` redraws whatever reads SCALES after a click. */
596
+ function renderScales(plot, axes, rerender) {
597
+ fill('scales-' + plot, ...axes.map(({ which, values, logable }) => {
598
+ const log = scaleOf(plot, which, values, logable) === 'log';
599
+ const dropped = values.filter((v) => !missing(v) && v <= 0).length;
600
+ const auto = !(SCALES[plot] || {})[which];
601
+
602
+ return el('button', { type: 'button', 'aria-pressed': String(log),
603
+ text: which + ' log' + (dropped ? ` (${dropped} hidden)` : ''),
604
+ title: (auto ? 'Automatic. ' : '') + (dropped ? `${dropped} `
605
+ + 'point(s) are <= 0 and a log axis omits them.'
606
+ : `Switch the ${which} axis between linear and log.`),
607
+ onclick: () => {
608
+ SCALES[plot] = SCALES[plot] || {};
609
+ SCALES[plot][which] = log ? 'linear' : 'log';
610
+ rerender();
611
+ } });
612
+ }));
613
+ }
614
+
615
+ /* Hover text as an aligned label/value block. Labels pad to a fixed width
616
+ with   -- Plotly renders each line as an SVG tspan, where runs of
617
+ ordinary spaces collapse -- and numbers right-align in their field so a
618
+ minus sign does not shift the digits. Blank lines separate groups. */
619
+ const TIP_LABEL = 13;
620
+ const TIP_NUMBER = 9;
621
+
622
+ function tipRow(label, value) {
623
+ if (value === null || value === undefined || value === '') return null;
624
+
625
+ const text = String(value);
626
+ return escape(label).padEnd(TIP_LABEL, ' ')
627
+ + escape(text).padStart(TIP_NUMBER, ' ');
628
+ }
629
+
630
+ /* A tipRow whose value is coloured in parts: [[text, token or null]]. The
631
+ padding counts the plain text, so the parts align like any value. */
632
+ function tipRowParts(label, parts) {
633
+ const text = parts.map(([part]) => part).join('');
634
+ return escape(label).padEnd(TIP_LABEL, ' ')
635
+ + ' '.repeat(Math.max(0, TIP_NUMBER - text.length))
636
+ + parts.map(([part, token]) => token ? `<span style="color:${resolved(token)}">`
637
+ + `${escape(part)}</span>` : escape(part)).join('');
638
+ }
639
+
640
+ /* An iteration's code change against its parent, from their merge
641
+ base, in GitHub's colours: lines added and deleted, and the files added,
642
+ modified and deleted. The baseline and anything in flight have none. */
643
+ const DIFF_FILES = [['modified', 4, '--diff-mod', 'diff-mod'],
644
+ ['added', 2, '--diff-add', 'diff-add'], ['deleted', 3, '--diff-del', 'diff-del']];
645
+
646
+ function diffTipRows(row) {
647
+ const stat = row.diffstat;
648
+ if (!stat) return [];
649
+ if (!stat.some(Boolean)) return [tipRow('code', 'unchanged')];
650
+ return [tipRowParts('lines', [['+' + fmt.int(stat[0]), '--diff-add'],
651
+ [' ', null], ['−' + fmt.int(stat[1]), '--diff-del']]),
652
+ ...DIFF_FILES.filter(([, index]) => stat[index]).map(([word, index, token]) =>
653
+ tipRowParts('files ' + word, [[fmt.int(stat[index]), token]]))];
654
+ }
655
+
656
+ function diffLine(row) {
657
+ const stat = row.diffstat;
658
+ if (!stat) return null;
659
+ if (!stat.some(Boolean)) return el('div', { class: 'log-diffstat',
660
+ text: 'no change to the code' });
661
+ const files = DIFF_FILES.filter(([, index]) => stat[index]).map(([word, index, , cls]) =>
662
+ el('span', { class: cls },
663
+ `${fmt.int(stat[index])} ${stat[index] === 1 ? 'file' : 'files'} ${word}`));
664
+ return el('div', { class: 'log-diffstat' }, [
665
+ el('span', { class: 'diff-add', text: '+' + fmt.int(stat[0]) }),
666
+ el('span', { class: 'diff-del', text: '−' + fmt.int(stat[1]) }),
667
+ ...files]);
668
+ }
669
+
670
+ /* A hover label taller than its plot does not render at all -- Plotly draws
671
+ it inside the plot's SVG -- so the block is cut to what the plot can hold.
672
+ Empirical: 15 px per line plus 30 px, which gives 18 lines at 300 px. */
673
+ function tipBlock(groups, plotId) {
674
+ const node = plotId ? $(plotId) : null;
675
+ const budget = Math.max(8, Math.floor((((node && node.clientHeight) || 300)
676
+ - 30) / 15));
677
+ const lines = [];
678
+
679
+ for (const group of groups) {
680
+ const rows = group.filter((row) => row !== null && row !== undefined);
681
+ if (!rows.length) continue;
682
+ if (lines.length) lines.push('');
683
+ lines.push(...rows);
684
+ }
685
+
686
+ return lines.slice(0, budget).join('<br>');
687
+ }
688
+
689
+ const HOVER = '%{text}<extra></extra>';
690
+
691
+ /* The sequential heatmap scale as a Plotly colorscale. */
692
+ function sequentialScale() {
693
+ return [[0, resolved('--seq-0')], [0.35, resolved('--seq-1')], [0.7, resolved('--seq-2')],
694
+ [1, resolved('--seq-3')]];
695
+ }
696
+
697
+ /* Plotly sizes a plot from its container when it draws it. A plot drawn
698
+ while the output is hidden (the cell scrolled out of view or collapsed when
699
+ a new round rebuilds the validation cards) takes Plotly's default 700 px
700
+ and keeps it, and no window resize comes to fix it. So every plotted node
701
+ is watched, and resized whenever its own width stops matching the plot's. */
702
+ const sizeWatch = typeof ResizeObserver === 'undefined' ? null
703
+ : new ResizeObserver((entries) => {
704
+ const P = plotly();
705
+ if (!P) return;
706
+ for (const entry of entries) {
707
+ const node = entry.target;
708
+ const width = Math.round(entry.contentRect.width);
709
+ if (width > 0 && node._fullLayout && node.isConnected
710
+ && Math.abs(node._fullLayout.width - width) > 1) P.Plots.resize(node);
711
+ }
712
+ });
713
+
714
+ /* A chart in a fresh output box renders one pixel wide until the cell
715
+ settles, so every plot is resized on window resize and once after mount. */
716
+ function resizePlots() {
717
+ const P = plotly();
718
+ if (!P) return;
719
+
720
+ for (const id of plotted) {
721
+ const node = $(id);
722
+ if (node) P.Plots.resize(node);
723
+ }
724
+ }
725
+
726
+ /* ==== SECTION: reorder ==== */
727
+
728
+ /* Drag to reorder, from a grip handle only -- Plotly owns the pointer over a
729
+ plot, where a drag is a lasso -- with the order stored per run in
730
+ localStorage so a poll or a reopened notebook does not undo it.
731
+
732
+ `order(key, names)` returns the saved order reconciled with `names`: kept
733
+ entries first, new ones appended, vanished ones dropped. `wire(card, key,
734
+ name, names, rerender, axis)` makes `card` a drop target whose `.grip`
735
+ starts the drag; axis 'x' for a row of panels, 'y' for a list. */
736
+ const reorder = {
737
+ dragging: null,
738
+
739
+ storageKey(key) {
740
+ return 'autoopt:order:' + key + ':' + ((state.snapshot || {}).root || '');
741
+ },
742
+
743
+ order(key, names) {
744
+ let saved = null;
745
+
746
+ try {
747
+ saved = JSON.parse(localStorage.getItem(reorder.storageKey(key)));
748
+ } catch (error) { /* storage unavailable: per-session only */ }
749
+
750
+ if (!Array.isArray(saved)) return names.slice();
751
+
752
+ const kept = saved.filter((name) => names.includes(name));
753
+ return kept.concat(names.filter((name) => !kept.includes(name)));
754
+ },
755
+
756
+ save(key, names) {
757
+ try {
758
+ localStorage.setItem(reorder.storageKey(key), JSON.stringify(names));
759
+ } catch (error) { /* per-session only */ }
760
+ },
761
+
762
+ wire(card, key, name, names, rerender, axisName) {
763
+ const grip = card.querySelector('.grip');
764
+ const horizontal = axisName !== 'y';
765
+
766
+ grip.setAttribute('draggable', 'true');
767
+
768
+ grip.addEventListener('dragstart', (event) => {
769
+ reorder.dragging = { key, name };
770
+ card.dataset.dragging = 'true';
771
+ event.dataTransfer.effectAllowed = 'move';
772
+ event.dataTransfer.setData('text/plain', name);
773
+
774
+ // Drag the panel, not the handle.
775
+ if (event.dataTransfer.setDragImage)
776
+ event.dataTransfer.setDragImage(card, 30, 14);
777
+ });
778
+
779
+ grip.addEventListener('dragend', () => {
780
+ reorder.dragging = null;
781
+ delete card.dataset.dragging;
782
+ for (const other of ROOT.querySelectorAll('[data-drop]'))
783
+ delete other.dataset.drop;
784
+ });
785
+
786
+ card.addEventListener('dragover', (event) => {
787
+ const drag = reorder.dragging;
788
+ if (!drag || drag.key !== key || drag.name === name) return;
789
+
790
+ event.preventDefault();
791
+ event.dataTransfer.dropEffect = 'move';
792
+
793
+ const box = card.getBoundingClientRect();
794
+ const after = horizontal
795
+ ? event.clientX > box.left + box.width / 2
796
+ : event.clientY > box.top + box.height / 2;
797
+ card.dataset.drop = after ? 'after' : 'before';
798
+ });
799
+
800
+ card.addEventListener('dragleave', () => { delete card.dataset.drop; });
801
+
802
+ card.addEventListener('drop', (event) => {
803
+ event.preventDefault();
804
+
805
+ const drag = reorder.dragging;
806
+ const after = card.dataset.drop === 'after';
807
+ delete card.dataset.drop;
808
+
809
+ if (!drag || drag.key !== key || drag.name === name) return;
810
+
811
+ const next = reorder.order(key, names)
812
+ .filter((entry) => entry !== drag.name);
813
+ const at = next.indexOf(name);
814
+ next.splice(at < 0 ? next.length : at + (after ? 1 : 0), 0,
815
+ drag.name);
816
+
817
+ reorder.save(key, next);
818
+ rerender();
819
+ });
820
+ },
821
+ };
822
+
823
+ /* ==== SECTION: density ==== */
824
+
825
+ const DENSITY_LIMIT = 5000;
826
+
827
+ /* Marks by n: opaque size 7 up to 500 points (on the dark page
828
+ translucent marks vanish at small n), size 5 at opacity
829
+ 0.3 up to DENSITY_LIMIT, a density beyond. */
830
+ const markStyle = (n) => n <= 500 ? { size: 7, opacity: 1 }
831
+ : { size: 5, opacity: 0.3 };
832
+
833
+ /* A layer that is only faint context behind the data ("All runs" behind
834
+ per-iteration medians) keeps these at any n: the density rule is for the
835
+ data. */
836
+ const CONTEXT_MARKS = { size: 4, opacity: 0.3 };
837
+
838
+ /* A context layer draws in its data's own muted hue, faint, never grey, so
839
+ it cannot read as the catch-all group; its legend key is that hue at the
840
+ same opacity. */
841
+ const contextMarker = (slot) => Object.assign({ color: resolved(slot) },
842
+ CONTEXT_MARKS);
843
+
844
+ /* Emphasis is colour plus size: an emphasised point (selected, or in an
845
+ emphasised category) is its hue at full strength, opaque, and 2px larger
846
+ than the trace's density-rule size; the rest fade to 0.08. */
847
+ const emphasisStyle = (slot, marks) => ({
848
+ selected: { marker: { opacity: 1, color: emphasis(slot),
849
+ size: marks.size + 2 } },
850
+ unselected: { marker: { opacity: 0.08 } },
851
+ });
852
+
853
+ /* Past DENSITY_LIMIT points: counts per bin on the sequential scale,
854
+ binned in the axis's own space so a log axis gets log-width bins. The
855
+ caption says it is a density and gives n. */
856
+ function densityTrace(xs, ys, xType, yType) {
857
+ const keep = xs.map((x, i) => [x, ys[i]]).filter(([x, y]) => !missing(x)
858
+ && !missing(y) && (xType !== 'log' || x > 0) && (yType !== 'log' || y > 0));
859
+
860
+ return {
861
+ type: 'histogram2d',
862
+ x: keep.map(([x]) => xType === 'log' ? Math.log10(x) : x),
863
+ y: keep.map(([, y]) => yType === 'log' ? Math.log10(y) : y),
864
+ colorscale: sequentialScale(), nbinsx: 60, nbinsy: 60,
865
+ showscale: false, hovertemplate: 'n = %{z}<extra></extra>',
866
+ };
867
+ }
868
+
869
+ /* ==== SECTION: tooltip ==== */
870
+
871
+ function showTip(event, children) {
872
+ const tip = $('tip');
873
+ if (!tip) return;
874
+
875
+ tip.replaceChildren(...children);
876
+ tip.classList.add('show');
877
+
878
+ const bounds = ROOT.getBoundingClientRect();
879
+ const rect = tip.getBoundingClientRect();
880
+ let left = event.clientX - bounds.left + 14;
881
+ if (left + rect.width > bounds.width) left = event.clientX - bounds.left
882
+ - rect.width - 14;
883
+
884
+ // Flip above the pointer rather than running off the bottom.
885
+ const below = event.clientY - bounds.top + 14;
886
+ const above = event.clientY - bounds.top - rect.height - 10;
887
+
888
+ tip.style.left = Math.max(4, left) + 'px';
889
+ tip.style.top = (below + rect.height > bounds.height && above > 0
890
+ ? above : below) + 'px';
891
+ }
892
+
893
+ function hideTip() {
894
+ const tip = $('tip');
895
+ if (tip) tip.classList.remove('show');
896
+ }
897
+
898
+ /* ==== SECTION: gpu ==== */
899
+
900
+ /* Utilisation over the samples the publisher kept, as a Tufte sparkline:
901
+ the line, a dot at its minimum and maximum, and the last value at the
902
+ right end. The card's numbers are a snapshot; this says whether the GPU
903
+ has been busy or just was at the poll. The line stretches to the width;
904
+ the dots are HTML so they stay round. */
905
+ function sparkline(values, width) {
906
+ const height = 26;
907
+ const ns = 'http://www.w3.org/2000/svg';
908
+ const svg = document.createElementNS(ns, 'svg');
909
+ const holder = el('div', { class: 'spark', role: 'img',
910
+ 'aria-label': 'Recent utilisation' }, [svg]);
911
+
912
+ svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
913
+ svg.setAttribute('preserveAspectRatio', 'none');
914
+ svg.setAttribute('width', '100%');
915
+ svg.setAttribute('height', String(height));
916
+
917
+ const last = el('span', { class: 'spark-last',
918
+ text: values.length ? fmt.pct(values[values.length - 1]) : '' });
919
+
920
+ if (values.length < 2) return [holder, last];
921
+
922
+ const step = width / (values.length - 1);
923
+ const yOf = (value) => height - ((value || 0) / 100) * height;
924
+ const line = document.createElementNS(ns, 'polyline');
925
+
926
+ line.setAttribute('points', values.map((value, i) =>
927
+ `${(i * step).toFixed(1)},${yOf(value).toFixed(1)}`).join(' '));
928
+ line.setAttribute('fill', 'none');
929
+ line.setAttribute('stroke', resolved('--cyan-muted'));
930
+ line.setAttribute('stroke-width', '1.5');
931
+ line.setAttribute('stroke-linejoin', 'round');
932
+ line.setAttribute('vector-effect', 'non-scaling-stroke');
933
+ svg.append(line);
934
+
935
+ const low = values.indexOf(Math.min(...values));
936
+ const high = values.indexOf(Math.max(...values));
937
+
938
+ for (const [index, kind] of [[low, 'min'], [high, 'max']])
939
+ holder.append(el('span', { class: 'mark', 'data-mark': kind,
940
+ title: `${kind} ${fmt.pct(values[index])}`,
941
+ style: `left:${100 * index / (values.length - 1)}%;`
942
+ + `top:${100 * yOf(values[index]) / height}%` }));
943
+
944
+ return [holder, last];
945
+ }
946
+
947
+ /* One of this run's processes on a GPU: what it is working on first. */
948
+ function gpuProcess(proc) {
949
+ return el('div', { class: 'gpu-proc' }, [
950
+ el('div', { class: 'row' }, [
951
+ el('code', { text: proc.target || proc.kind || '(unidentified)' }),
952
+ el('span', { class: 'muted', text: `pid ${proc.pid}` })]),
953
+ el('div', { class: 'row muted' }, [
954
+ el('span', { text: `SM ${fmt.pct(proc.sm)} · `
955
+ + `${fmt.int(proc.gpu_memory)} MiB` }),
956
+ el('span', { text: `CPU ${fmt.pct(proc.cpu_percent)} · `
957
+ + fmt.bytes(proc.rss) })]),
958
+ el('div', { class: 'row muted' }, [
959
+ el('span', { text: proc.kind || 'process' }),
960
+ el('span', { text: fmt.duration(proc.elapsed) })]),
961
+ ]);
962
+ }
963
+
964
+ /* A visible drag bar for a horizontally scrolling strip, because the native
965
+ scrollbar is an overlay with nothing to grab. Hidden when the strip fits;
966
+ generic over any (strip, bar, thumb). */
967
+ function wireDragBar(stripId, barId, thumbId) {
968
+ const strip = $(stripId);
969
+ const bar = $(barId);
970
+ const thumb = $(thumbId);
971
+ if (!strip || !bar || !thumb) return;
972
+
973
+ const sync = () => {
974
+ // Not laid out: the cell is scrolled out of a windowed notebook or
975
+ // collapsed. A zero width there would show the bar.
976
+ if (!strip.clientWidth) return;
977
+
978
+ const ratio = strip.clientWidth / (strip.scrollWidth || 1);
979
+ bar.hidden = ratio >= 0.999;
980
+ if (bar.hidden) return;
981
+
982
+ const width = Math.max(24, bar.clientWidth * ratio);
983
+ const scrollable = strip.scrollWidth - strip.clientWidth;
984
+
985
+ thumb.style.width = width + 'px';
986
+ thumb.style.left = (scrollable > 0 ? strip.scrollLeft / scrollable
987
+ * (bar.clientWidth - width) : 0) + 'px';
988
+ };
989
+
990
+ if (!bar._wired) {
991
+ bar._wired = true;
992
+
993
+ const to = (clientX) => {
994
+ const rect = bar.getBoundingClientRect();
995
+ const width = thumb.getBoundingClientRect().width;
996
+ const fraction = Math.max(0, Math.min(1, (clientX - rect.left
997
+ - width / 2) / Math.max(1, rect.width - width)));
998
+ strip.scrollLeft = fraction * (strip.scrollWidth - strip.clientWidth);
999
+ };
1000
+
1001
+ bar.addEventListener('mousedown', (event) => {
1002
+ bar.dataset.dragging = 'true';
1003
+ to(event.clientX);
1004
+ event.preventDefault();
1005
+ });
1006
+ window.addEventListener('mousemove', (event) => {
1007
+ if (bar.dataset.dragging === 'true') to(event.clientX);
1008
+ });
1009
+ window.addEventListener('mouseup', () => { bar.dataset.dragging = 'false'; });
1010
+ strip.addEventListener('scroll', sync);
1011
+ window.addEventListener('resize', sync);
1012
+ if (typeof ResizeObserver !== 'undefined') new ResizeObserver(sync).observe(strip);
1013
+ }
1014
+
1015
+ sync();
1016
+ }
1017
+
1018
+ /* The GPU strip's height only grows while the page is mounted. A card
1019
+ gains or loses a process block as jobs come and go, and every change in
1020
+ the strip's height moves everything below it; when the strip is above
1021
+ the viewport, that is the whole notebook jumping. */
1022
+ function holdHeight(id) {
1023
+ const node = $(id);
1024
+ if (!node || !node.offsetHeight) return;
1025
+
1026
+ const tallest = Math.max(node.offsetHeight, parseFloat(node.style.minHeight) || 0);
1027
+ node.style.minHeight = tallest + 'px';
1028
+ }
1029
+
1030
+ const BADGE = { ours: 'this run', leased: 'leased', busy: 'other',
1031
+ free: 'free' };
1032
+
1033
+ function gpuCard(gpu, history) {
1034
+ const processes = gpu.processes || [];
1035
+ const mine = processes.filter((p) => p.mine);
1036
+ const others = processes.length - mine.length;
1037
+ const series = history.map((point) => (point.gpu || {})[gpu.index])
1038
+ .filter((value) => !missing(value));
1039
+
1040
+ // Whose lease it is, when a lease tool holds it and none of ours is on it.
1041
+ const lease = gpu.lease && !gpu.mine ? el('div', { class: 'gpu-proc muted',
1042
+ title: gpu.lease.note || '' }, [el('div', { class: 'row' }, [
1043
+ el('span', { text: `${gpu.lease.user || '?'} — `
1044
+ + `${gpu.lease.note || 'no note'}` })])]) : null;
1045
+
1046
+ const idle = processes.length || lease ? null : el('div', {
1047
+ class: 'gpu-proc muted', text: 'idle' });
1048
+
1049
+ return el('div', { class: 'gpu-card', 'data-state': gpu.state }, [
1050
+ el('div', { class: 'gpu-head' }, [
1051
+ el('span', { class: 'gpu-title', text: `GPU ${gpu.index}` }),
1052
+ el('span', { class: 'badge', 'data-state': gpu.state,
1053
+ text: BADGE[gpu.state] || gpu.state })]),
1054
+ el('div', { class: 'gpu-util', text: fmt.pct(gpu.utilization) }),
1055
+ // One span per stat: `gap` does not apply to bare text nodes.
1056
+ el('div', { class: 'gpu-stats' }, [
1057
+ `${fmt.int(gpu.memory_used)} / ${fmt.int(gpu.memory_total)} MiB`,
1058
+ missing(gpu.temperature) ? null : `${fmt.int(gpu.temperature)} °C`,
1059
+ missing(gpu.power) ? null
1060
+ : `${fmt.int(gpu.power)} / ${fmt.int(gpu.power_limit)} W`,
1061
+ gpu.name,
1062
+ ].filter(Boolean).map((text) => el('span', { text, title: text }))),
1063
+ el('div', { class: 'gpu-spark' }, sparkline(series, 100)),
1064
+ ...mine.map(gpuProcess),
1065
+ others ? el('div', { class: 'gpu-proc muted', text: `${others} `
1066
+ + `process${others > 1 ? 'es' : ''} from another job` }) : null,
1067
+ lease,
1068
+ idle,
1069
+ ]);
1070
+ }
1071
+
1072
+ /* A process that only mentions the run and does nothing is noise. */
1073
+ const interesting = (proc) => proc.kind !== 'other' || proc.target
1074
+ || ((proc.tree || {}).cpu_percent || 0) > 1
1075
+ || ((proc.tree || {}).rss || 0) > 2e8;
1076
+
1077
+ /* How long a GPU reading may lag the poll before the cards say so: a few
1078
+ hardware samples, since nvidia-smi on a busy host takes seconds. */
1079
+ const GPU_STALE_SECONDS = 30;
1080
+
1081
+ function renderResources(resources) {
1082
+ const host = resources.host || {};
1083
+
1084
+ // A sample with no GPUs after ones with GPUs is nvidia-smi failing or
1085
+ // timing out, not the GPUs leaving: keep the last cards, and say how
1086
+ // old they are, rather than drop the strip and jump the notebook.
1087
+ let gpus = resources.gpus || [];
1088
+ let sampledAt = resources.gpu_sampled_at;
1089
+
1090
+ if (gpus.length) {
1091
+ state.lastGpus = { gpus, sampledAt: sampledAt || resources.timestamp };
1092
+ } else if (state.lastGpus) {
1093
+ ({ gpus, sampledAt } = state.lastGpus);
1094
+ }
1095
+
1096
+ const age = missing(sampledAt) || missing(resources.timestamp) ? 0
1097
+ : resources.timestamp - sampledAt;
1098
+ const stale = gpus.length && age > Math.max(GPU_STALE_SECONDS,
1099
+ 3 * cadence('resource') / 1000);
1100
+
1101
+ // The host first: two machines can publish one search, and the strip
1102
+ // shows the GPUs of whichever one is publishing.
1103
+ $('host-summary').textContent = (resources.hostname
1104
+ ? `${resources.hostname} · ` : '') + (host.cpu_count
1105
+ ? `${fmt.pct(host.cpu_percent)} of ${host.cpu_count} cores · load `
1106
+ + `${(host.load || []).map((x) => x.toFixed(1)).join(' ')} · `
1107
+ + `${fmt.bytes(host.memory_used)} of ${fmt.bytes(host.memory_total)} RAM`
1108
+ : 'psutil is not installed, so the host summary is unavailable.')
1109
+ + (stale ? ` · GPU reading ${fmt.duration(age)} old: nvidia-smi is `
1110
+ + 'slow or failing' : '');
1111
+
1112
+ const cards = fill('gpu-cards', ...gpus.map((gpu) =>
1113
+ gpuCard(gpu, resources.history || [])));
1114
+ if (cards) cards.dataset.stale = stale ? 'true' : 'false';
1115
+ wireDragBar('gpu-cards', 'gpu-scroll', 'gpu-scroll-thumb');
1116
+ holdHeight('gpu-cards');
1117
+
1118
+ const all = resources.processes || [];
1119
+ const shown = all.filter(interesting);
1120
+ const hidden = all.length - shown.length;
1121
+
1122
+ // Without psutil the table is empty because nothing can be listed, not
1123
+ // because nothing runs: say so.
1124
+ const blind = resources.psutil === false;
1125
+ $('process-card').hidden = !shown.length && !blind;
1126
+ $('process-note').textContent = blind
1127
+ ? 'psutil is not installed, so this search\'s processes cannot be listed'
1128
+ : hidden ? `${hidden} idle process${hidden > 1 ? 'es' : ''} hidden` : '';
1129
+
1130
+ fill('process-body', ...shown.map((proc) => el('tr', {}, [
1131
+ el('td', { class: 'num', text: String(proc.pid) }),
1132
+ el('td', { text: proc.kind }),
1133
+ el('td', {}, [el('code', { text: proc.target || '–' })]),
1134
+ el('td', { class: 'num', text: fmt.pct((proc.tree || {}).cpu_percent) }),
1135
+ el('td', { class: 'num', text: fmt.bytes((proc.tree || {}).rss) }),
1136
+ el('td', { class: 'num', text: fmt.duration(proc.elapsed) })])));
1137
+ }
1138
+
1139
+ /* ==== SECTION: lineage-tree ==== */
1140
+
1141
+ /* A search lineage as an SVG tree, root at the top, one row per generation.
1142
+
1143
+ nodes: [{id, parent, status, category, value, title, on_frontier, is_root}]
1144
+ status is ok | gate-failed | running; depth is computed from `parent`.
1145
+
1146
+ Past LINEAGE_MANY nodes the tree is condensed: roots, the frontier path,
1147
+ anything running and the newest LINEAGE_RECENT are drawn, and the rest
1148
+ stand in as one tally per (parent, depth). 2,600 iterations forked from
1149
+ one parent otherwise draw one 119,000 px row. Nodes keep a legible
1150
+ spacing (LINEAGE_MIN_GAP) and the panel scrolls rather than squeezing.
1151
+
1152
+ Ink: nodes are plain discs in their category's muted hue; the frontier is
1153
+ the same hue at full strength, not a ring. Hovering a node lights its
1154
+ ancestry and pushes everything else back. */
1155
+ const LINEAGE_MANY = 120;
1156
+ const LINEAGE_RECENT = 12;
1157
+ const LINEAGE_GAP = 46;
1158
+ const LINEAGE_MIN_GAP = 34;
1159
+ const LINEAGE_ROW = 72;
1160
+ const LINEAGE_PAD = 26;
1161
+ const LINEAGE_GUTTER = 40;
1162
+ const LINEAGE_R = 7;
1163
+ const LINEAGE_LABEL = 20; // the id label's baseline, below the node's centre
1164
+
1165
+ function lineageDepths(nodes) {
1166
+ const byId = new Map(nodes.map((n) => [n.id, n]));
1167
+ const depth = new Map();
1168
+
1169
+ const walk = (id, seen) => {
1170
+ if (depth.has(id)) return depth.get(id);
1171
+ const node = byId.get(id);
1172
+ const parent = node ? node.parent : null;
1173
+ const d = (node === undefined || parent === null || parent === undefined
1174
+ || parent === id || seen.has(parent) || !byId.has(parent))
1175
+ ? 0 : walk(parent, new Set(seen).add(id)) + 1;
1176
+ depth.set(id, d);
1177
+ return d;
1178
+ };
1179
+
1180
+ for (const node of nodes) node.depth = walk(node.id, new Set());
1181
+ return nodes;
1182
+ }
1183
+
1184
+ function condenseLineage(nodes) {
1185
+ if (nodes.length <= LINEAGE_MANY) return { nodes, collapsed: 0 };
1186
+
1187
+ const newest = new Set(nodes.map((n) => n.id).sort((a, b) => a - b)
1188
+ .slice(-LINEAGE_RECENT));
1189
+ const keep = [];
1190
+ const dropped = new Map();
1191
+
1192
+ for (const node of nodes) {
1193
+ if (node.is_root || node.on_frontier || node.status === 'running'
1194
+ || newest.has(node.id)) {
1195
+ keep.push(node);
1196
+ } else {
1197
+ const key = node.parent + '|' + node.depth;
1198
+ if (!dropped.has(key)) dropped.set(key, []);
1199
+ dropped.get(key).push(node);
1200
+ }
1201
+ }
1202
+
1203
+ let collapsed = 0;
1204
+ for (const group of dropped.values()) {
1205
+ collapsed += group.length;
1206
+ const values = group.map((n) => n.value).filter((v) => !missing(v));
1207
+ keep.push({ id: null, parent: group[0].parent, depth: group[0].depth,
1208
+ status: 'collapsed', n: group.length,
1209
+ n_ok: group.filter((n) => n.status === 'ok').length,
1210
+ best: values.length ? Math.max(...values) : null });
1211
+ }
1212
+
1213
+ return { nodes: keep, collapsed };
1214
+ }
1215
+
1216
+ /* The chain from the root down to `id`, root first. */
1217
+ function lineagePath(nodes, id) {
1218
+ const byId = new Map(nodes.map((n) => [n.id, n]));
1219
+ const path = [];
1220
+
1221
+ for (let at = id; at !== null && at !== undefined && byId.has(at)
1222
+ && path.length < 200; at = byId.get(at).parent)
1223
+ path.unshift(byId.get(at));
1224
+
1225
+ return path;
1226
+ }
1227
+
1228
+ function renderLineage(holderId, mapId, allNodes, options) {
1229
+ const holder = $(holderId);
1230
+ if (!holder) return;
1231
+
1232
+ options = options || {};
1233
+ const colourSlot = options.slotOf || (() => '--cat-other');
1234
+ const hidden = options.hidden || new Set();
1235
+ const emphasised = options.emphasised || new Set();
1236
+ const full = lineageDepths(allNodes.map((n) => Object.assign({}, n)));
1237
+ const { nodes, collapsed } = condenseLineage(full);
1238
+
1239
+ if (!nodes.length) {
1240
+ holder.replaceChildren(el('div', { class: 'empty', text: 'No iterations yet.' }));
1241
+ return { collapsed: 0 };
1242
+ }
1243
+
1244
+ const depth = Math.max(...nodes.map((n) => n.depth));
1245
+ const rows = [];
1246
+ for (let level = 0; level <= depth; level++)
1247
+ rows.push(nodes.filter((n) => n.depth === level)
1248
+ .sort((a, b) => (a.id === null) - (b.id === null) || a.id - b.id));
1249
+
1250
+ const widest = Math.max(...rows.map((r) => r.length), 1);
1251
+ const available = Math.max((holder.clientWidth || 900) - 2 * LINEAGE_PAD
1252
+ - LINEAGE_GUTTER, 320);
1253
+ const gap = widest > 1 ? Math.max(LINEAGE_MIN_GAP,
1254
+ Math.min(LINEAGE_GAP, available / (widest - 1))) : LINEAGE_GAP;
1255
+ const keyOf = (n) => n.id === null ? `c${n.depth}-${n.parent}` : `i${n.id}`;
1256
+ const labelled = gap >= 26;
1257
+
1258
+ let width = Math.max(LINEAGE_GUTTER + 2 * LINEAGE_PAD + (widest - 1) * gap, 520);
1259
+ const height = 2 * LINEAGE_PAD + (depth + 1) * LINEAGE_ROW;
1260
+ const place = {};
1261
+
1262
+ rows.forEach((row, level) => {
1263
+ const left = LINEAGE_GUTTER + (width - LINEAGE_GUTTER) / 2
1264
+ - (row.length - 1) * gap / 2;
1265
+ row.forEach((n, i) => {
1266
+ place[keyOf(n)] = { x: left + i * gap, y: LINEAGE_PAD + level * LINEAGE_ROW };
1267
+ });
1268
+ });
1269
+
1270
+ // Centre each parent over its children, deepest row first; otherwise a
1271
+ // lone root sits mid-canvas, off the edge of the panel.
1272
+ for (let level = rows.length - 1; level > 0; level--) {
1273
+ const children = {};
1274
+ for (const n of rows[level]) {
1275
+ const at = place[keyOf(n)];
1276
+ if (n.parent !== null && n.parent !== undefined && at)
1277
+ (children[n.parent] = children[n.parent] || []).push(at.x);
1278
+ }
1279
+ for (const n of rows[level - 1]) {
1280
+ const xs = children[n.id];
1281
+ if (xs && xs.length) place[keyOf(n)].x = xs.reduce((a, b) => a + b) / xs.length;
1282
+ }
1283
+ }
1284
+
1285
+ // Then push apart anything centring dropped onto a neighbour.
1286
+ for (const row of rows) {
1287
+ const ordered = row.map((n) => place[keyOf(n)]).sort((a, b) => a.x - b.x);
1288
+ for (let i = 1; i < ordered.length; i++)
1289
+ ordered[i].x = Math.max(ordered[i].x, ordered[i - 1].x + gap);
1290
+ if (ordered.length) width = Math.max(width, ordered[ordered.length - 1].x + LINEAGE_PAD);
1291
+ }
1292
+
1293
+ const NS = 'http://www.w3.org/2000/svg';
1294
+ const make = (tag, attrs) => {
1295
+ const node = document.createElementNS(NS, tag);
1296
+ for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, v);
1297
+ return node;
1298
+ };
1299
+
1300
+ const svg = make('svg', { width: Math.ceil(width), height,
1301
+ viewBox: `0 0 ${Math.ceil(width)} ${height}`, class: 'lineage' });
1302
+
1303
+ const colourOf = (n, strong) => n.status === 'running'
1304
+ ? resolved('--running')
1305
+ : strong ? emphasis(colourSlot(n.category)) : resolved(colourSlot(n.category));
1306
+
1307
+ // Edges first, stopping short of each disc so a fork does not trace a
1308
+ // ring around its parent.
1309
+ for (const n of nodes) {
1310
+ const child = place[keyOf(n)];
1311
+ const parent = n.parent === null || n.parent === undefined ? null
1312
+ : place[`i${n.parent}`];
1313
+ if (!child || !parent) continue;
1314
+
1315
+ // Below the parent's id label when labels are drawn (its baseline is
1316
+ // 20px under the centre), else just off the disc: an edge from the
1317
+ // disc runs through the label.
1318
+ const from = parent.y + (labelled ? LINEAGE_LABEL + 4 : LINEAGE_R + 3);
1319
+ const to = child.y - LINEAGE_R - 3;
1320
+ const mid = (from + to) / 2;
1321
+
1322
+ svg.append(make('path', { class: 'lineage-edge',
1323
+ d: `M ${parent.x} ${from} C ${parent.x} ${mid}, ${child.x} ${mid}, ${child.x} ${to}`,
1324
+ stroke: n.status === 'collapsed' ? resolved('--line') : colourOf(n, n.on_frontier),
1325
+ 'stroke-opacity': n.on_frontier ? 1 : 0.45,
1326
+ 'data-node-id': n.id === null ? '' : String(n.id),
1327
+ 'data-dim': String(hidden.has(n.category)
1328
+ || (emphasised.size > 0 && !emphasised.has(n.category))) }));
1329
+ }
1330
+
1331
+ for (const n of nodes) {
1332
+ const at = place[keyOf(n)];
1333
+
1334
+ if (n.status === 'collapsed') {
1335
+ const tally = make('g', { class: 'lineage-node lineage-tally' });
1336
+ tally.append(make('rect', { x: at.x - 18, y: at.y - 9, width: 36,
1337
+ // A transparent fill, not 'none': an unfilled rect takes no
1338
+ // pointer events inside it, so it would show no tooltip.
1339
+ height: 18, rx: 6, fill: 'transparent', stroke: resolved('--line'),
1340
+ 'stroke-dasharray': '3 2' }));
1341
+ const count = make('text', { x: at.x, y: at.y + 4 });
1342
+ count.textContent = '+' + fmt.int(n.n);
1343
+ tally.append(count);
1344
+ tally.addEventListener('mouseenter', (event) => showTip(event, [
1345
+ el('div', { class: 'head', text: `${fmt.int(n.n)} iterations` }),
1346
+ el('div', { text: `forked from #${n.parent}, ${fmt.int(n.n_ok)} ok` }),
1347
+ el('div', { text: tipRow('best value', fmt.sig(n.best)) }),
1348
+ el('div', { text: 'none on the frontier' })]));
1349
+ tally.addEventListener('mouseleave', hideTip);
1350
+ svg.append(tally);
1351
+ continue;
1352
+ }
1353
+
1354
+ // Hidden or outside the emphasis: dimmed, never removed, which would
1355
+ // cut the lineage through it.
1356
+ const dim = (state.selection && !state.selection.has(n.id))
1357
+ || hidden.has(n.category)
1358
+ || (emphasised.size > 0 && !emphasised.has(n.category));
1359
+ const group = make('g', { class: 'lineage-node',
1360
+ 'data-node-id': String(n.id), 'data-dim': String(Boolean(dim)),
1361
+ 'data-frontier': String(Boolean(n.on_frontier)) });
1362
+
1363
+ // A larger invisible target, so the pointer need not hit a 7px dot.
1364
+ group.append(make('circle', { cx: at.x, cy: at.y, r: 16, fill: 'transparent' }));
1365
+
1366
+ const running = n.status === 'running';
1367
+ const radius = n.is_root ? LINEAGE_R + 2 : LINEAGE_R;
1368
+
1369
+ group.append(make('circle', { class: 'dot', cx: at.x, cy: at.y,
1370
+ r: radius,
1371
+ fill: running ? 'none' : colourOf(n, n.on_frontier || n.is_root),
1372
+ 'fill-opacity': n.status === 'ok' || running ? 1 : 0.4,
1373
+ stroke: running ? colourOf(n) : 'none', 'stroke-dasharray': '3 2' }));
1374
+
1375
+ if (n.status === 'gate-failed')
1376
+ group.append(make('path', { d: `M ${at.x - 4} ${at.y - 4} L ${at.x + 4} `
1377
+ + `${at.y + 4} M ${at.x + 4} ${at.y - 4} L ${at.x - 4} ${at.y + 4}`,
1378
+ stroke: resolved('--bad'), 'stroke-width': 1.6 }));
1379
+
1380
+ if (labelled) {
1381
+ const label = make('text', { x: at.x, y: at.y + LINEAGE_LABEL });
1382
+ label.textContent = tag(n.id);
1383
+ group.append(label);
1384
+ }
1385
+
1386
+ group.addEventListener('mouseenter', (event) => {
1387
+ const ids = new Set(lineagePath(full, n.id).map((p) => p.id));
1388
+ svg.dataset.hovering = 'true';
1389
+ for (const item of svg.querySelectorAll('[data-node-id]'))
1390
+ item.dataset.onPath = String(ids.has(Number(item.dataset.nodeId)));
1391
+
1392
+ const path = lineagePath(full, n.id);
1393
+ showTip(event, [
1394
+ el('div', { class: 'head', text: `${tag(n.id)} ${n.title || ''}` }),
1395
+ ...path.slice(0, -1).map((p) => el('div', { class: 'dim',
1396
+ text: ` ${tag(p.id)} ${p.title || ''}` })),
1397
+ el('div', { text: tipRow('value', fmt.sig(n.value)) }),
1398
+ el('div', { text: `${n.category} · ${n.status}`
1399
+ + (n.on_frontier ? ' · frontier' : '') })]);
1400
+ if (options.onHover) options.onHover(n.id);
1401
+ });
1402
+ group.addEventListener('mouseleave', () => {
1403
+ delete svg.dataset.hovering;
1404
+ hideTip();
1405
+ if (options.onHover) options.onHover(null);
1406
+ });
1407
+ group.addEventListener('click', () => options.onPin && options.onPin(n.id));
1408
+
1409
+ svg.append(group);
1410
+ }
1411
+
1412
+ rows.forEach((row, level) => {
1413
+ const text = make('text', { x: 4, y: LINEAGE_PAD + level * LINEAGE_ROW + 4,
1414
+ class: 'lineage-rowlabel' });
1415
+ text.textContent = level === 0 ? 'root' : 'gen ' + level;
1416
+ svg.append(text);
1417
+ });
1418
+
1419
+ holder.replaceChildren(svg);
1420
+
1421
+ // One dot per generation with its size; clicking scrolls the panel to
1422
+ // that row, centred on its best node.
1423
+ if (mapId && $(mapId)) fill(mapId, ...rows.map((row, level) => {
1424
+ const best = row.filter((n) => n.id !== null && !missing(n.value))
1425
+ .sort((a, b) => b.value - a.value)[0];
1426
+ return el('button', { class: 'lineage-level', type: 'button',
1427
+ title: `${level === 0 ? 'root' : 'generation ' + level}: `
1428
+ + `${row.length} node(s)`,
1429
+ onclick: () => {
1430
+ const at = best ? place[keyOf(best)] : place[keyOf(row[0])];
1431
+ holder.scrollTo({ left: at.x - holder.clientWidth / 2,
1432
+ top: at.y - holder.clientHeight / 2, behavior: 'smooth' });
1433
+ } }, [
1434
+ el('span', { class: 'dot', style: `background:${best
1435
+ ? colourOf(best) : resolved('--line')}` }),
1436
+ el('span', { class: 'n', text: fmt.int(row.reduce((a, n) =>
1437
+ a + (n.n || 1), 0)) }),
1438
+ el('span', { class: 'lbl', text: level === 0 ? 'root' : 'gen ' + level })]);
1439
+ }));
1440
+
1441
+ return { collapsed, width: Math.ceil(width) };
1442
+ }
1443
+
1444
+ /* ==== SECTION: expandable-log ==== */
1445
+
1446
+ /* Newest-first entries on one line each, under a header row sharing the
1447
+ same fixed-width grid (an `auto` column would resolve separately in each
1448
+ row and the header would drift off the values). Each entry has a left
1449
+ rule in its category's colour; a frontier entry shows its id at full
1450
+ strength. Clicking expands the detail and calls `onPin(id)`.
1451
+
1452
+ columns: [{key, label, width, format}] -- widths in px, the last column
1453
+ (the title) takes the rest. detail(row) returns [[key, value]] pairs, or a
1454
+ DOM Node to insert as it is (a README, a small plot); the Node is kept
1455
+ while the entry stays open, so the log's own re-render (another entry
1456
+ clicked, a chip toggled) re-inserts it rather than calling detail again.
1457
+ Rows need a numeric `id`: entries sort newest first by `b.id - a.id`, so
1458
+ string ids give an unordered log with no error. onPin(id, opened) fires
1459
+ on every click, with whether the entry is now open. `options.hidden`
1460
+ removes a category's entries; `options.emphasised`, when non-empty, fades
1461
+ every entry outside it. */
1462
+ const logOpen = {};
1463
+ const logDetails = {};
1464
+
1465
+ function logDetailBlock(details, row, detail) {
1466
+ if (details.has(row.id)) return details.get(row.id);
1467
+
1468
+ // Pairs are rebuilt on every render, so live values stay current; a
1469
+ // Node is built once and kept while the entry is open.
1470
+ const made = detail(row);
1471
+ if (made && made.nodeType) {
1472
+ const node = el('div', { class: 'log-detail' }, [made]);
1473
+ details.set(row.id, node);
1474
+ return node;
1475
+ }
1476
+
1477
+ // A key may be a Node (a label with its own colour) or plain text.
1478
+ return el('div', { class: 'log-detail pairs' }, made.map(([key, value, title]) =>
1479
+ el('div', { class: 'pair' }, [
1480
+ el('span', { class: 'k' }, [key]),
1481
+ el('span', { class: 'v', text: value, title })])));
1482
+ }
1483
+
1484
+ function renderLog(holderId, rows, columns, options) {
1485
+ const holder = $(holderId);
1486
+ if (!holder) return;
1487
+
1488
+ options = options || {};
1489
+ const open = logOpen[holderId] = logOpen[holderId] || new Set();
1490
+ const details = logDetails[holderId] = logDetails[holderId] || new Map();
1491
+ const hidden = options.hidden || new Set();
1492
+ const emphasised = options.emphasised || new Set();
1493
+ const visibleRows = rows.filter((row) => !hidden.has(row.category))
1494
+ .sort((a, b) => b.id - a.id);
1495
+
1496
+ holder.style.setProperty('--log-cols', columns.map((c) => c.width
1497
+ ? c.width + 'px' : 'minmax(0, 1fr)').join(' '));
1498
+
1499
+ if (!visibleRows.length) {
1500
+ holder.replaceChildren(el('div', { class: 'empty', text: 'No entries yet.' }));
1501
+ return;
1502
+ }
1503
+
1504
+ const cell = (column, row) => {
1505
+ const value = row[column.key];
1506
+ return el('span', { class: 'm' + (column.num ? ' num' : ''),
1507
+ style: column.colour ? `color:${column.colour(value, row)}` : null,
1508
+ text: column.format ? column.format(value, row)
1509
+ : missing(value) ? '–' : String(value) });
1510
+ };
1511
+ // The row's rule colour: its category's.
1512
+ const slotOfRow = (row) => (options.slotOf || (() => '--cat-other'))(
1513
+ row.category);
1514
+
1515
+ holder.replaceChildren(
1516
+ el('div', { class: 'log-header' }, columns.map((c) =>
1517
+ el('span', { class: c.num ? 'num' : null, text: c.label }))),
1518
+ ...visibleRows.map((row) => {
1519
+ const colour = resolved(slotOfRow(row));
1520
+ const isOpen = open.has(row.id);
1521
+ const faded = emphasised.size > 0 && !emphasised.has(row.category);
1522
+
1523
+ return el('div', { class: 'log-entry', dataset: { id: String(row.id),
1524
+ open: String(isOpen), frontier: String(Boolean(row.on_frontier)),
1525
+ faded: String(faded) },
1526
+ style: `border-left-color:${colour}`,
1527
+ onclick: (event) => {
1528
+ // A click inside an inserted detail Node (a link, a
1529
+ // selection of text) is not a click on the entry.
1530
+ if (event.target.closest('.log-detail')) return;
1531
+ if (open.has(row.id)) { open.delete(row.id); details.delete(row.id); }
1532
+ else open.add(row.id);
1533
+ if (options.onPin) options.onPin(row.id, open.has(row.id));
1534
+ renderLog(holderId, rows, columns, options);
1535
+ } }, [
1536
+ el('div', { class: 'log-row' }, columns.map((c) => cell(c, row))),
1537
+ isOpen && options.detail ? logDetailBlock(details, row, options.detail) : null,
1538
+ ]);
1539
+ }));
1540
+
1541
+ // The frontier entry's id at full strength: the one the reader looks for.
1542
+ for (const entry of holder.querySelectorAll('.log-entry[data-frontier="true"]')) {
1543
+ const row = visibleRows.find((r) => String(r.id) === entry.dataset.id);
1544
+ entry.querySelector('.m').style.color = emphasis(slotOfRow(row));
1545
+ }
1546
+ }
1547
+
1548
+ /* ==== SECTION: search ==== */
1549
+
1550
+ /* The rows every chart reads. Everything is drawn from
1551
+ `state.snapshot.iterations`, one row per iteration, so a lasso in any chart
1552
+ turns into a set of iteration ids that every other panel can follow. */
1553
+
1554
+ const SHORT = { MICRO: 'micro', NUMBA: 'numba', CACHING: 'cache',
1555
+ CACHE_MISS: 'miss', PRECISION: 'prec', PARALLEL: 'par', REORGANIZATION: 'reorg',
1556
+ IO: 'io', ALGORITHM: 'algo', OPTIMIZATION: 'opt', MISC: 'misc', ROOT: 'root' };
1557
+
1558
+ /* Marker shape carries the iteration's status; colour carries its category. */
1559
+ const STATUS_SYMBOL = { ok: 'circle', 'gate-failed': 'x', error: 'circle-open',
1560
+ partial: 'square-open' };
1561
+
1562
+ const catSlot = (category) => groupSlot(category);
1563
+
1564
+ function settled() {
1565
+ return state.snapshot ? state.snapshot.iterations
1566
+ .filter((row) => row.status !== 'running') : [];
1567
+ }
1568
+
1569
+ /* In-flight iterations, honouring the chips: a chip that hid an iteration's
1570
+ points but left its in-flight marker would make the filter look broken. */
1571
+ function running() {
1572
+ return state.snapshot ? state.snapshot.iterations.filter((row) =>
1573
+ row.status === 'running' && !state.hidden.has(row.category)) : [];
1574
+ }
1575
+
1576
+ /* Settled iterations the chips and "Gate failures" have not hidden. A hidden row is gone from every chart at once. */
1577
+ function visible() {
1578
+ return settled().filter((row) => !state.hidden.has(row.category)
1579
+ && !(state.hideFailed && row.status !== 'ok'));
1580
+ }
1581
+
1582
+ const plottable = () => visible().filter((row) => !missing(row.value));
1583
+
1584
+ function byId(identifier) {
1585
+ return (state.snapshot ? state.snapshot.iterations : [])
1586
+ .find((row) => row.id === identifier) || null;
1587
+ }
1588
+
1589
+ /* Where an iteration sits on the x axis: its id. */
1590
+ const xOf = (row) => row.id;
1591
+
1592
+ /* The frontier staircase: the running best, one step per improvement. */
1593
+ const frontierSteps = () => state.snapshot.frontier.steps || [];
1594
+
1595
+ /* Break `text` into at most `limit` lines of about `width` characters,
1596
+ ending with an ellipsis when there was more. */
1597
+ function wrapText(text, width, limit) {
1598
+ const words = text.split(' ').filter(Boolean);
1599
+ const lines = [];
1600
+ let current = '';
1601
+
1602
+ for (const word of words) {
1603
+ if ((current + ' ' + word).trim().length > width) {
1604
+ lines.push(current.trim());
1605
+ current = word;
1606
+ if (lines.length === limit) break;
1607
+ } else {
1608
+ current = (current + ' ' + word).trim();
1609
+ }
1610
+ }
1611
+
1612
+ if (lines.length < limit && current) lines.push(current.trim());
1613
+ if (lines.length && words.join(' ').length > lines.join(' ').length)
1614
+ lines[lines.length - 1] += '…';
1615
+
1616
+ return lines;
1617
+ }
1618
+
1619
+ /* The aligned hover block for one iteration: what it is, what it scored,
1620
+ what it was held to, what else was recorded, where it sits, and the top
1621
+ of its README last, so the README is what a short plot cuts. */
1622
+ function hoverText(row, plotId) {
1623
+ const snapshot = state.snapshot;
1624
+ const stats = row.objective || {};
1625
+ const baseline = snapshot.frontier.baseline;
1626
+ const title = (row.title || '(untitled)');
1627
+
1628
+ const notes = row.notes ? wrapText(row.notes.replace(/^#+ .*$/m, '')
1629
+ .replace(/[*`|#]/g, '').replace(/\s+/g, ' ').trim(), 44, 2)
1630
+ .map((line) => '<i>' + escape(line) + '</i>')
1631
+ : ['<i>no README.md written</i>'];
1632
+
1633
+ return tipBlock([
1634
+ [`<b>${tag(row.id)} ${escape(title.length > 44 ? title.slice(0, 43) + '…'
1635
+ : title)}</b>`,
1636
+ tipRow('category', SHORT[row.category] || row.category),
1637
+ minedStages() && !missing(row.mining_stage)
1638
+ ? tipRow('miner stage', 'S' + row.mining_stage) : null,
1639
+ tipRow('status', row.status + (row.stage ? ' · ' + row.stage : '')),
1640
+ row.working ? tipRow('subagent', 'working: checks and README pending, last '
1641
+ + 'activity ' + (missing(row.idle) ? '–' : fmt.duration(row.idle) + ' ago'))
1642
+ : null,
1643
+ row.on_frontier ? tipRow('frontier', 'yes') : null],
1644
+ [tipRow(snapshot.objective.name, fmt.sig(row.value)),
1645
+ tipRow('sd', fmt.sig(stats.std)),
1646
+ tipRow('min', fmt.sig(stats.min)), tipRow('max', fmt.sig(stats.max)),
1647
+ stats.ci ? tipRow('95% CI of median', `${fmt.sig(stats.ci[0])} – `
1648
+ + `${fmt.sig(stats.ci[1])}`) : null,
1649
+ tipRow('runs', row.n_runs),
1650
+ missing(baseline) || missing(row.value) ? null
1651
+ : tipRow('vs baseline', fmt.signed(row.value - baseline, 4)),
1652
+ row.n_failed ? tipRow('failed runs', row.n_failed) : null],
1653
+ Object.entries(row.gates || {}).map(([name, gate]) =>
1654
+ tipRow(`${name} ${gate.op} ${fmt.sig(gate.threshold)}`,
1655
+ `${gate.pass ? 'pass' : 'FAIL'} ${fmt.sig(gate.worst)}`)),
1656
+ Object.entries(row.observers || {}).map(([name, observer]) =>
1657
+ tipRow(name, fmt.sig(observer.median))),
1658
+ diffTipRows(row),
1659
+ [tipRow('parent', tag(row.parent)),
1660
+ tipRow('round', row.round), tipRow('wall clock', fmt.duration(row.seconds)),
1661
+ row.topic ? tipRow('topic', row.topic) : null,
1662
+ row.best_run ? tipRow('best run', row.best_run) : null],
1663
+ notes,
1664
+ ], plotId);
1665
+ }
1666
+
1667
+ /* ==== SECTION: objective ==== */
1668
+
1669
+ selectionListeners.push(() => renderMain());
1670
+
1671
+ /* Grouped by category. The frontier is its hue at full strength; everything
1672
+ else is muted. */
1673
+ function medianTraces(rows, yOf, plotId) {
1674
+ const groups = [...new Set(rows.map((row) => row.category))].sort().map(
1675
+ (category) => ({ key: category, slot: catSlot(category),
1676
+ rows: rows.filter((row) => row.category === category) }));
1677
+
1678
+ const marks = markStyle(rows.length);
1679
+
1680
+ return groups.filter((g) => g.rows.length).map((g) => ({
1681
+ type: 'scatter', mode: 'markers', name: g.key,
1682
+ x: g.rows.map(xOf), y: g.rows.map(yOf),
1683
+ text: g.rows.map((row) => hoverText(row, plotId)),
1684
+ customdata: g.rows.map((row) => row.id),
1685
+ hovertemplate: HOVER,
1686
+ selectedpoints: selectedIndices(g.rows, (row) => row.category),
1687
+ ...emphasisStyle(g.slot, marks),
1688
+ // The frontier is emphasis too: full strength, opaque, 2px larger.
1689
+ marker: {
1690
+ color: g.rows.map((row) => row.on_frontier ? emphasis(g.slot)
1691
+ : resolved(g.slot)),
1692
+ // A subagent still working on a measured iteration (checks and
1693
+ // README pending): larger, opaque, and a thick ring in its category's colour,
1694
+ // so a search whose runs finished does not look idle.
1695
+ size: g.rows.map((row) => row.working ? marks.size + 6
1696
+ : row.on_frontier ? marks.size + 2 : marks.size),
1697
+ opacity: g.rows.map((row) => row.on_frontier || row.working ? 1
1698
+ : marks.opacity),
1699
+ symbol: g.rows.map((row) => STATUS_SYMBOL[row.status] || 'circle'),
1700
+ line: { width: g.rows.map((row) => row.working ? 3 : 1.2),
1701
+ color: g.rows.map((row) => row.working
1702
+ ? emphasis(g.slot)
1703
+ : row.on_frontier ? emphasis(g.slot) : resolved(g.slot)) },
1704
+ },
1705
+ }));
1706
+ }
1707
+
1708
+ /* Iterations set aside without a measured run (`iterations/<id>.abandoned`,
1709
+ scan.py's `abandoned`), honouring the chips and the hide-failed toggle like
1710
+ every other point. */
1711
+ function abandonedRows() {
1712
+ return ((state.snapshot && state.snapshot.abandoned) || []).filter((row) =>
1713
+ !state.hidden.has(row.category) && !state.hideFailed);
1714
+ }
1715
+
1716
+ /* An abandoned iteration has no objective, so it is drawn at the baseline's
1717
+ value: a thin ✕ in its category's hue at its own x, one trace per category so
1718
+ chip emphasis colours it like the medians. Shape is the status here as
1719
+ everywhere on this chart; the thin ✕ is not the gate-failed ✕. */
1720
+ function abandonedTraces(rows, y, total) {
1721
+ const marks = markStyle(total);
1722
+ // Grouped as the medians are, by category, so each trace is one colour.
1723
+ const groups = [...new Set(rows.map((row) => row.category))].sort().map(
1724
+ (category) => ({ key: category, slot: catSlot(category),
1725
+ rows: rows.filter((row) => row.category === category) }));
1726
+
1727
+ return groups.filter((g) => g.rows.length).map((g) => ({
1728
+ type: 'scatter', mode: 'markers', name: 'abandoned ' + g.key,
1729
+ x: g.rows.map(xOf), y: g.rows.map(() => y),
1730
+ text: g.rows.map(abandonedHover),
1731
+ // No customdata: there is no measured iteration behind the mark, so
1732
+ // hovering or clicking it draws and pins nothing.
1733
+ hovertemplate: HOVER, showlegend: false,
1734
+ selectedpoints: selectedIndices(g.rows, (row) => row.category),
1735
+ ...emphasisStyle(g.slot, marks),
1736
+ marker: { symbol: 'x-thin-open', size: marks.size + 4, color: resolved(g.slot),
1737
+ opacity: marks.opacity, line: { width: 1.8, color: resolved(g.slot) } },
1738
+ }));
1739
+ }
1740
+
1741
+ function abandonedHover(row) {
1742
+ const title = row.title || '(untitled)';
1743
+ const notes = row.notes ? wrapText(row.notes.replace(/^#+ .*$/m, '')
1744
+ .replace(/[*`|#]/g, '').replace(/\s+/g, ' ').trim(), 44, 3)
1745
+ .map((line) => '<i>' + escape(line) + '</i>')
1746
+ : ['<i>no README.md written</i>'];
1747
+
1748
+ return tipBlock([
1749
+ [`<b>${tag(row.id)} ${escape(title.length > 44 ? title.slice(0, 43) + '…'
1750
+ : title)}</b>`,
1751
+ tipRow('category', SHORT[row.category] || row.category),
1752
+ tipRow('status', 'abandoned: closed without a measured run'),
1753
+ tipRow('drawn at', 'the baseline\'s value')],
1754
+ [tipRow('parent', tag(row.parent)), tipRow('round', row.round),
1755
+ row.topic ? tipRow('topic', row.topic) : null],
1756
+ notes,
1757
+ ], 'main-chart');
1758
+ }
1759
+
1760
+ /* Each median's confidence interval (scan.py's bootstrap of the median over
1761
+ its runs) as a dotted vertical whisker with a cap at each end, one trace per
1762
+ category in its muted hue, under the medians. An iteration with fewer than
1763
+ two runs has no interval and draws none. */
1764
+ function ciTraces(rows) {
1765
+ return [...new Set(rows.map((row) => row.category))].sort().map((category) => {
1766
+ const x = [], y = [];
1767
+
1768
+ for (const row of rows.filter((r) => r.category === category)) {
1769
+ const ci = (row.objective || {}).ci;
1770
+ if (!ci || missing(ci[0]) || missing(ci[1])) continue;
1771
+ x.push(xOf(row), xOf(row), null);
1772
+ y.push(ci[0], ci[1], null);
1773
+ }
1774
+
1775
+ return { type: 'scatter', mode: 'lines+markers', name: 'ci ' + category,
1776
+ x, y, hoverinfo: 'skip', showlegend: false, connectgaps: false,
1777
+ line: { color: resolved(catSlot(category)), width: 1.2, dash: 'dot' },
1778
+ marker: { symbol: 'line-ew-open', size: 7,
1779
+ line: { width: 1.2, color: resolved(catSlot(category)) } } };
1780
+ }).filter((trace) => trace.x.length);
1781
+ }
1782
+
1783
+ /* Every run's own score, one small faint dot per seed stacked at its
1784
+ iteration's x, under the medians: the spread the median hides. A
1785
+ background context layer, so CONTEXT_MARKS at any n, never the density. */
1786
+ function runTraces(rows) {
1787
+ return [...new Set(rows.map((row) => row.category))].sort().map((category) => {
1788
+ const x = [], y = [], text = [], owners = [], keys = [];
1789
+
1790
+ for (const row of rows.filter((r) => r.category === category))
1791
+ for (const run of row.runs || []) {
1792
+ if (missing(run.objective)) continue;
1793
+ owners.push(row);
1794
+ keys.push(`${row.id}:${run.seed}`);
1795
+ x.push(xOf(row));
1796
+ y.push(run.objective);
1797
+ text.push(tipBlock([[`<b>#${row.id}</b>`, tipRow('seed', run.seed),
1798
+ tipRow(state.snapshot.objective.name, fmt.sig(run.objective)),
1799
+ tipRow('wall clock', fmt.duration(run.seconds))]], 'main-chart'));
1800
+ }
1801
+
1802
+ // Follows chip emphasis and the selection like the medians, but stays
1803
+ // context: an emphasised run keeps CONTEXT_MARKS, the rest nearly vanish.
1804
+ return { type: 'scatter', mode: 'markers', name: 'runs ' + category, x, y,
1805
+ text, customdata: keys, hovertemplate: HOVER, showlegend: false,
1806
+ selectedpoints: selectedIndices(owners, (row) => row.category),
1807
+ selected: { marker: { opacity: CONTEXT_MARKS.opacity } },
1808
+ unselected: { marker: { opacity: 0.04 } },
1809
+ marker: contextMarker(catSlot(category)) };
1810
+ }).filter((trace) => trace.x.length);
1811
+ }
1812
+
1813
+ /* Tree depth by id: the baseline is 0, each iteration one below its parent.
1814
+ The same generations the search tree draws its rows by. */
1815
+ function treeDepths() {
1816
+ const rows = state.snapshot ? state.snapshot.iterations : [];
1817
+ const parent = new Map(rows.map((row) => [row.id, row.parent]));
1818
+ const depth = new Map();
1819
+
1820
+ const walk = (id, seen) => {
1821
+ if (depth.has(id)) return depth.get(id);
1822
+ const up = parent.get(id);
1823
+ // A missing or cyclic parent roots its own tree rather than looping.
1824
+ const d = up === null || up === undefined || !parent.has(up) || seen.has(up)
1825
+ ? 0 : walk(up, seen.add(id)) + 1;
1826
+ depth.set(id, d);
1827
+ return d;
1828
+ };
1829
+
1830
+ for (const row of rows) walk(row.id, new Set());
1831
+ return depth;
1832
+ }
1833
+
1834
+ /* Whether the search records idea-miner stages. Without them, boundaries
1835
+ fall back to tree generations. */
1836
+ const minedStages = () => ((state.snapshot || {}).iterations || []).some(
1837
+ (row) => !missing(row.mining_stage) && row.mining_stage > 0);
1838
+
1839
+ /* Where the objective chart draws a stage boundary: halfway between two
1840
+ neighbouring iterations (in x order, running ones
1841
+ included) whose idea-miner stage differs, so the chart shows whether a
1842
+ fresh batch of ideas moved the objective. The baseline counts as stage 0.
1843
+ Without stages, whose tree generations differ. Structural, so the chips
1844
+ and "Gate failures" do not move it. */
1845
+ function stageBoundaries() {
1846
+ const mined = minedStages();
1847
+ const depth = mined ? new Map(((state.snapshot || {}).iterations || []).map(
1848
+ (row) => [row.id, row.mining_stage || 0])) : treeDepths();
1849
+ const out = [];
1850
+
1851
+ const rows = (state.snapshot ? state.snapshot.iterations : []).slice()
1852
+ .sort((a, b) => xOf(a) - xOf(b));
1853
+
1854
+ for (let i = 1; i < rows.length; i++)
1855
+ if (depth.get(rows[i].id) !== depth.get(rows[i - 1].id))
1856
+ out.push({ x: (xOf(rows[i - 1]) + xOf(rows[i])) / 2,
1857
+ generation: depth.get(rows[i].id) });
1858
+
1859
+ return out;
1860
+ }
1861
+
1862
+ function renderMain() {
1863
+ const snapshot = state.snapshot;
1864
+ if (!snapshot) return;
1865
+
1866
+ const rows = plottable();
1867
+ const ys = rows.map((row) => row.value);
1868
+ const yType = scaleOf('main', 'y', ys, true);
1869
+ const dense = rows.length > DENSITY_LIMIT;
1870
+ const xType = dense ? 'linear' : scaleOf('main', 'x', rows.map(xOf), false);
1871
+
1872
+ const traces = dense
1873
+ ? [densityTrace(rows.map(xOf), ys, 'linear', yType)]
1874
+ : (state.showRuns ? runTraces(rows) : []).concat(
1875
+ state.showCI ? ciTraces(rows) : [],
1876
+ medianTraces(rows, (row) => row.value, 'main-chart'));
1877
+
1878
+ // A density is binned in log10 already, so its y values are log10 and so
1879
+ // is every line drawn over it.
1880
+ const yv = (value) => dense && yType === 'log' ? Math.log10(value) : value;
1881
+
1882
+ // The staircase is the running best. It steps only where an iteration
1883
+ // improved, so the flat stretches are the search finding nothing, drawn
1884
+ // to scale.
1885
+ if (state.showStair) {
1886
+ const steps = frontierSteps();
1887
+
1888
+ if (steps.length && !(steps.length < 2 && !rows.length)) {
1889
+ const xs = steps.map((step) => byId(step.id) ? xOf(byId(step.id)) : step.id);
1890
+ // Carried to the last iteration, so a search that stopped
1891
+ // improving reads as flat rather than finished.
1892
+ const end = rows.length ? Math.max(...rows.map(xOf)) : xs[xs.length - 1];
1893
+
1894
+ traces.unshift({
1895
+ type: 'scatter', mode: 'lines', name: 'frontier',
1896
+ x: xs.concat([Math.max(end, xs[xs.length - 1])]),
1897
+ y: steps.map((s) => yv(s.value)).concat([yv(steps[steps.length - 1].value)]),
1898
+ line: { color: resolved('--pink'), width: 1.6, shape: 'hv',
1899
+ dash: 'dot' },
1900
+ hoverinfo: 'skip', showlegend: false,
1901
+ });
1902
+ }
1903
+ }
1904
+
1905
+ // Still running: no objective yet, so drawn on the floor of the chart.
1906
+ const inFlight = running();
1907
+
1908
+ if (inFlight.length && rows.length) {
1909
+ const floor = Math.min(...ys);
1910
+
1911
+ traces.push({
1912
+ type: 'scatter', mode: 'markers', name: 'running',
1913
+ x: inFlight.map(xOf), y: inFlight.map(() => yv(floor)),
1914
+ text: inFlight.map((row) => tipBlock([[`<b>${tag(row.id)} `
1915
+ + `${escape(row.title || '')}</b>`,
1916
+ tipRow('running for', fmt.duration(row.elapsed))]], 'main-chart')),
1917
+ customdata: inFlight.map((row) => row.id),
1918
+ hovertemplate: HOVER, showlegend: false,
1919
+ marker: { color: resolved('--running'), size: 9,
1920
+ symbol: 'diamond-open',
1921
+ line: { width: 1.5, color: resolved('--running') } },
1922
+ });
1923
+ }
1924
+
1925
+ // Closed without a measured run: a thin ✕ at the baseline's value.
1926
+ const closed = abandonedRows();
1927
+ const baselineValue = snapshot.frontier.baseline;
1928
+
1929
+ if (!dense && closed.length && rows.length && !missing(baselineValue))
1930
+ traces.push(...abandonedTraces(closed, yv(baselineValue), rows.length));
1931
+
1932
+ // The headline, first in reading order: the number the search exists to
1933
+ // move, as HTML under the title rather than a Plotly annotation.
1934
+ const sep = () => el('span', { class: 'sep', text: '•' });
1935
+ const headline = (value, id, percent, against) => missing(value)
1936
+ ? ['no frontier yet'] : [
1937
+ `${snapshot.objective.name} `, el('b', { text: fmt.sig(value) }),
1938
+ sep(), 'iteration ', el('b', { text: tag(id) }),
1939
+ ...(missing(percent) ? [] : [sep(),
1940
+ el('b', { text: fmt.signedPct(percent) }), ` over ${against}`])];
1941
+
1942
+ const frontier = scopedFrontier();
1943
+ fill('main-headline', ...headline(frontier.value, frontier.id,
1944
+ frontier.total_percent, 'baseline'));
1945
+
1946
+ const yLabel = snapshot.objective.name + (snapshot.objective.unit
1947
+ ? ` (${snapshot.objective.unit})` : '') + ', median per iteration';
1948
+
1949
+ draw('main-chart', traces, plotLayout({
1950
+ // x log is manual only (never automatic): the baseline sits at x = 0,
1951
+ // which a log axis cannot draw, and the scale button says so.
1952
+ xaxis: axis({ type: xType, ...logTicks(traces.flatMap((t) =>
1953
+ t.type === 'scatter' ? t.x : []).filter((v) => !missing(v)), xType),
1954
+ ...iterationTicks(traces.flatMap((t) => t.type === 'scatter' ? t.x
1955
+ : []), xType),
1956
+ title: { text: 'iteration',
1957
+ font: { size: 11, color: resolved('--text-faint') } } }),
1958
+ yaxis: axis({ type: dense ? 'linear' : yType,
1959
+ // logTicks fixes the range, so it sees every y any trace draws:
1960
+ // runs, the staircases, the in-flight markers on the floor.
1961
+ ...logTicks(traces.flatMap((t) => t.type === 'scatter' ? t.y : [])
1962
+ .filter((v) => !missing(v)), dense ? 'linear' : yType), title: { text:
1963
+ (dense && yType === 'log' ? 'log10 ' : '') + yLabel,
1964
+ font: { size: 11, color: resolved('--text-faint') } } }),
1965
+ margin: { l: 62, r: 16, t: 10, b: 40 },
1966
+ // Shapes, not traces: a boundary spans the plot whatever the y range,
1967
+ // and cannot be hovered, lassoed or pinned.
1968
+ shapes: state.showStages && !dense ? stageBoundaries().map((b) => ({
1969
+ type: 'line', xref: 'x', yref: 'paper', x0: b.x, x1: b.x, y0: 0, y1: 1,
1970
+ layer: 'below', line: { color: resolved('--purple'), width: 1.2,
1971
+ dash: 'dash' } })) : [],
1972
+ }), { selectable: true, ids: rows.map((row) => row.id), config: SELECT_CONFIG,
1973
+ onClick: openDiff });
1974
+
1975
+ renderScales('main', dense ? [{ which: 'y', values: ys, logable: true }]
1976
+ : [{ which: 'x', values: rows.map(xOf), logable: false },
1977
+ { which: 'y', values: ys, logable: true }], renderMain);
1978
+ renderMainLegend(dense, rows.length);
1979
+ }
1980
+
1981
+ /* A marker key for the status shapes, drawn the way Plotly draws them. */
1982
+ function statusKey(shape, colour) {
1983
+ const hollow = `background:none;border:1.5px solid ${colour};`;
1984
+ const styles = {
1985
+ circle: `background:${colour};border-radius:50%`,
1986
+ hollow: hollow + 'border-radius:50%',
1987
+ square: hollow,
1988
+ diamond: hollow + 'transform:rotate(45deg) scale(.8)',
1989
+ small: `background:${colour};border-radius:50%;width:5px;height:5px;opacity:.6`,
1990
+ };
1991
+
1992
+ if (shape === 'x') return markerKey(colour, 'x');
1993
+
1994
+ return el('span', { class: 'mark-key', style: 'display:inline-flex;width:12px;height:12px;'
1995
+ + 'align-items:center;justify-content:center' }, [
1996
+ el('span', { style: 'width:9px;height:9px;box-sizing:border-box;'
1997
+ + styles[shape] })]);
1998
+ }
1999
+
2000
+ function renderMainLegend(dense, n) {
2001
+ const dim = css('--text-dim');
2002
+
2003
+ if (dense) {
2004
+ fill('main-legend', el('span', { class: 'legend-item', text: `density of `
2005
+ + `${fmt.int(n)} iterations, darker to cyan = more iterations per bin` }));
2006
+ return;
2007
+ }
2008
+
2009
+ fill('main-legend',
2010
+ // A context layer's key: its data's muted hue at the layer's opacity.
2011
+ state.showRuns ? el('span', { class: 'legend-item', dataset: { key: 'runs' } },
2012
+ [markerKey(resolved(CAT_SLOTS[0]), 'circle', CONTEXT_MARKS.opacity),
2013
+ 'one run (seed), faint, in its category\'s hue']) : null,
2014
+ // The staircase is pink; a frontier point is its own hue, at full
2015
+ // strength and larger.
2016
+ el('span', { class: 'legend-item', dataset: { key: 'frontier-line' } }, [
2017
+ markerKey(resolved('--pink'), 'dotted'), 'frontier (running best)']),
2018
+ state.showCI ? el('span', { class: 'legend-item', dataset: { key: 'ci' } },
2019
+ [markerKey(css('--text-dim'), 'dotted'), '95% confidence interval of the '
2020
+ + 'median: a bootstrap over the iteration\'s runs (at 3 runs, at most '
2021
+ + 'min to max)']) : null,
2022
+ state.showStages ? el('span', { class: 'legend-item',
2023
+ dataset: { key: 'stage-boundary' } }, [markerKey(resolved('--purple'), 'dashed'),
2024
+ minedStages() ? 'stage boundary: the idea miner\'s next batch of ideas'
2025
+ : 'depth boundary: the next level of the search tree']) : null,
2026
+ el('span', { class: 'legend-item', dataset: { key: 'frontier-point' } }, [
2027
+ el('span', { class: 'mark-key', style: 'display:inline-flex;width:12px;'
2028
+ + 'height:12px;align-items:center;justify-content:center' }, [
2029
+ el('span', { style: `width:11px;height:11px;border-radius:50%;`
2030
+ + `background:${css('--text')}` })]),
2031
+ 'on the frontier: its hue at full strength, 2px larger']),
2032
+ el('span', { class: 'legend-item' }, [statusKey('circle', dim), 'passed']),
2033
+ // ✕ is gate failed here, an accepted exception to x-for-baseline.
2034
+ el('span', { class: 'legend-item' }, [statusKey('x', dim),
2035
+ '✕ gate failed']),
2036
+ el('span', { class: 'legend-item' }, [statusKey('hollow', dim), 'run errored']),
2037
+ el('span', { class: 'legend-item' }, [statusKey('square', dim),
2038
+ 'under depth (too few runs)']),
2039
+ abandonedRows().length ? el('span', { class: 'legend-item',
2040
+ dataset: { key: 'abandoned' } }, [markerKey(dim, 'x-thin'),
2041
+ 'thin ✕ abandoned: closed without a measured run, drawn at the '
2042
+ + 'baseline\'s value']) : null,
2043
+ el('span', { class: 'legend-item' }, [statusKey('diamond',
2044
+ resolved('--running')), 'still running, on the floor']));
2045
+ }
2046
+
2047
+ /* ==== SECTION: observers ==== */
2048
+
2049
+ selectionListeners.push(() => renderObservers());
2050
+
2051
+ const observerId = (name) => 'observer-' + String(name).replace(/[^A-Za-z0-9_-]/g, '_');
2052
+
2053
+ function observerCard(name) {
2054
+ const id = observerId(name);
2055
+
2056
+ return el('figure', { class: 'card reorder-card', dataset: { panel: name } }, [
2057
+ el('figcaption', {}, [
2058
+ el('span', { class: 'grip', title: 'Drag to reorder', text: '⠿' }),
2059
+ el('span', { text: name })]),
2060
+ el('div', { class: 'plot', id }),
2061
+ el('div', { class: 'plot-scales', id: 'scales-' + id }),
2062
+ ]);
2063
+ }
2064
+
2065
+ function renderObservers() {
2066
+ const snapshot = state.snapshot;
2067
+ const holder = $('observer-charts');
2068
+ if (!snapshot || !holder) return;
2069
+
2070
+ const configured = (snapshot.observers || []).map((o) => o.name);
2071
+ $('section-observers').hidden = !configured.length;
2072
+ if (!configured.length) return;
2073
+
2074
+ const names = reorder.order('observers', configured);
2075
+
2076
+ // Built once per arrangement and only react()ed into afterwards.
2077
+ if (holder.dataset.keys !== names.join(',')) {
2078
+ holder.dataset.keys = names.join(',');
2079
+ for (const id of [...plotted]) if (id.startsWith('observer-')) plotted.delete(id);
2080
+ holder.replaceChildren(...names.map((name) => {
2081
+ const card = observerCard(name);
2082
+ reorder.wire(card, 'observers', name, names, renderObservers, 'x');
2083
+ return card;
2084
+ }));
2085
+ }
2086
+
2087
+ for (const name of names) {
2088
+ const id = observerId(name);
2089
+ const unit = ((snapshot.observers || []).find((o) => o.name === name) || {}).unit;
2090
+ const rows = visible().filter((row) => (row.observers || {})[name]
2091
+ && !missing(row.observers[name].median));
2092
+ const ys = rows.map((row) => row.observers[name].median);
2093
+ const yType = scaleOf(id, 'y', ys, true);
2094
+
2095
+ draw(id, medianTraces(rows, (row) => row.observers[name].median, id),
2096
+ plotLayout({
2097
+ margin: { l: 58, r: 12, t: 8, b: 34 },
2098
+ xaxis: axis({ ...iterationTicks(rows.map((row) => row.id), 'linear'),
2099
+ title: { text: 'iteration', font: { size: 10, color: resolved('--text-faint') } } }),
2100
+ yaxis: axis({ type: yType, ...logTicks(ys, yType), title: { text: name + (unit ? ` (${unit})`
2101
+ : '') + ', median', font: { size: 10, color: resolved('--text-faint') } } }),
2102
+ }), { selectable: true, ids: rows.map((row) => row.id),
2103
+ config: SELECT_CONFIG, onClick: (pid) => setPinned(Number(pid)) });
2104
+
2105
+ renderScales(id, [{ which: 'y', values: ys, logable: true }], renderObservers);
2106
+ }
2107
+ }
2108
+
2109
+ /* ==== SECTION: validation ==== */
2110
+
2111
+ /* The external validation: one small multiple per numeric measure over
2112
+ rounds, each round's value marked in its verdict's tone. Run against that
2113
+ round's root on inputs the search never measures; it is not a gate and
2114
+ chose nothing, which the section says before any number. A search without
2115
+ one hides the section. Not linked to the selection: a point is a round,
2116
+ not an iteration. */
2117
+ const NOT_A_GATE = 'Not a gate: it chose nothing and rejected nothing, and '
2118
+ + 'its numbers need not be comparable to the objective.';
2119
+
2120
+ const validationId = (name) => 'validation-'
2121
+ + String(name).replace(/[^A-Za-z0-9_-]/g, '_');
2122
+ const verdictWord = (record) => record.ok ? 'ok' : 'needs attention';
2123
+
2124
+ /* The verdict line of a hover; "needs attention" in the bad tone, as on the
2125
+ panel's point and in the sidebar. */
2126
+ const verdictTip = (record) => record.ok ? tipRow('verdict', verdictWord(record))
2127
+ : `<span style="color:${resolved('--bad')}">`
2128
+ + tipRow('verdict', verdictWord(record)) + '</span>';
2129
+ const isNumber = (value) => typeof value === 'number' && Number.isFinite(value);
2130
+
2131
+ /* A measure's name with its unit, when the validation names one. */
2132
+ const withUnit = (name) => {
2133
+ const unit = (((state.snapshot || {}).validation || {}).units || {})[name];
2134
+ return unit ? `${name} (${unit})` : name;
2135
+ };
2136
+
2137
+ function renderValidation() {
2138
+ const snapshot = state.snapshot;
2139
+ const holder = $('validation-charts');
2140
+ if (!snapshot || !holder) return;
2141
+
2142
+ const block = snapshot.validation;
2143
+ $('section-validation').hidden = !block;
2144
+ if (!block) return;
2145
+
2146
+ const records = block.records || [];
2147
+ fill('validation-note', el('span', { class: 'not-a-gate', text: NOT_A_GATE }),
2148
+ ' Run once a round against that round\'s root, on inputs the search '
2149
+ + 'does not otherwise touch' + (block.note ? `: ${block.note}.` : '.'));
2150
+
2151
+ const numeric = block.measures.filter((name) =>
2152
+ records.some((record) => isNumber(record.measures[name])));
2153
+ const key = numeric.join(',') + '|' + records.length + '|'
2154
+ + JSON.stringify(block.units || {});
2155
+
2156
+ // Built once per set of measures and only react()ed into afterwards.
2157
+ if (holder.dataset.keys !== key) {
2158
+ holder.dataset.keys = key;
2159
+ for (const id of [...plotted]) if (id.startsWith('validation-')) plotted.delete(id);
2160
+
2161
+ holder.replaceChildren(...(numeric.length ? numeric.map((name) =>
2162
+ el('figure', { class: 'card', dataset: { measure: name } }, [
2163
+ el('figcaption', {}, [el('span', { text: withUnit(name) })]),
2164
+ el('div', { class: 'plot short', id: validationId(name) })]))
2165
+ : [el('div', { class: 'empty', text: records.length
2166
+ ? 'No measure reported a number; the sidebar lists what each did.'
2167
+ : 'Configured' + (block.approved ? ' and approved' : ', not yet '
2168
+ + 'approved') + '; no round has been validated yet.' })]));
2169
+ }
2170
+
2171
+ for (const name of numeric) {
2172
+ const traces = [(() => {
2173
+ const rows = records.filter((record) => isNumber(record.measures[name]))
2174
+ .sort((a, b) => a.round - b.round);
2175
+
2176
+ return {
2177
+ type: 'scatter', mode: 'lines+markers', name,
2178
+ x: rows.map((record) => record.round),
2179
+ y: rows.map((record) => record.measures[name]),
2180
+ line: { color: resolved('--line'), width: 1.2 },
2181
+ // The script's own verdict: ok in the muted good tone, needs
2182
+ // attention in the bad tone at full strength, the one to find.
2183
+ marker: { size: 8, color: rows.map((record) => record.ok
2184
+ ? verdictColour('ok') : verdictColour('bad', true)) },
2185
+ // Eight lines fit a short plot; "not a gate" rides in the head so
2186
+ // the cut never takes it.
2187
+ text: rows.map((record) => tipBlock([
2188
+ [`<b>${escape(withUnit(name))}</b> · not a gate`,
2189
+ tipRow('value', fmt.sig(record.measures[name]))],
2190
+ [tipRow('round', record.round),
2191
+ tipRow('iteration', tag(record.iteration)),
2192
+ verdictTip(record)],
2193
+ record.note ? [escape(record.note)] : [],
2194
+ ], validationId(name))),
2195
+ hovertemplate: HOVER,
2196
+ };
2197
+ })()].filter((trace) => trace.x.length);
2198
+
2199
+ draw(validationId(name), traces, plotLayout({
2200
+ margin: { l: 54, r: 12, t: 8, b: 34 },
2201
+ dragmode: false,
2202
+ xaxis: axis({ dtick: 1, title: { text: 'round',
2203
+ font: { size: 10, color: resolved('--text-faint') } } }),
2204
+ // The panel title names the measure; a rotated y title would
2205
+ // collide with the tick labels in this fixed margin.
2206
+ yaxis: axis({ automargin: false }),
2207
+ }), { config: PLAIN_CONFIG });
2208
+ }
2209
+ }
2210
+
2211
+ /* The latest round's values, for the sidebar. */
2212
+ function validationCard() {
2213
+ const block = (state.snapshot || {}).validation;
2214
+ if (!block) return null;
2215
+
2216
+ const records = block.records || [];
2217
+ const latest = records[records.length - 1];
2218
+
2219
+ if (!latest)
2220
+ return statCard('External validation', [
2221
+ ['approved', block.approved ? 'yes' : 'not yet'],
2222
+ ['rounds validated', '0']], NOT_A_GATE);
2223
+
2224
+ const value = (x) => missing(x) ? 'not reported'
2225
+ : isNumber(x) ? fmt.sig(x) : String(x);
2226
+
2227
+ return statCard('External validation', [
2228
+ ['round', `${latest.round} · #${latest.iteration}`],
2229
+ ...block.measures.map((name) => [withUnit(name), value(latest.measures[name])]),
2230
+ ['verdict', verdictWord(latest), latest.ok ? 'good' : 'bad'],
2231
+ ], (latest.note ? latest.note + '. ' : '') + NOT_A_GATE);
2232
+ }
2233
+
2234
+ /* ==== SECTION: diff ==== */
2235
+
2236
+ /* A click on a point of the objective chart opens that iteration's code
2237
+ change against its parent under the chart, in two columns: the old file on
2238
+ the left, the new on the right. A second click on the same point, or
2239
+ 'close', shuts it. A median's customdata is its iteration id; a run dot's
2240
+ is "id:seed". */
2241
+ function openDiff(key) {
2242
+ // A mark with no iteration behind it (an abandoned one) opens nothing.
2243
+ if (key === null || key === undefined) return;
2244
+ const id = Number(String(key).split(':')[0]);
2245
+ if (!byId(id)) return;
2246
+ state.diffOpen = state.diffOpen === id ? null : id;
2247
+ state.diffShown = null;
2248
+ renderDiff();
2249
+ if (state.diffOpen !== null)
2250
+ $('diff-card').scrollIntoView({ block: 'nearest', behavior: 'smooth' });
2251
+ }
2252
+
2253
+ /* The publisher writes diffs/<id>.json once per commit; a failed read tries
2254
+ again after ten seconds, since the writer fills the files in newest first. */
2255
+ async function loadDiff(row) {
2256
+ const id = row.id;
2257
+ if (!TRANSPORT || !TRANSPORT.diff || !row.commit || row.parent === null
2258
+ || row.parent === undefined || state.diffFor[id] === row.commit) return;
2259
+ if (Date.now() - (state.diffTried[id] || 0) < 10000) return;
2260
+ state.diffFor[id] = row.commit;
2261
+ try {
2262
+ const payload = await TRANSPORT.diff(id);
2263
+ state.diffs[id] = payload && Array.isArray(payload.files) ? payload : null;
2264
+ } catch (error) {
2265
+ state.diffs[id] = null;
2266
+ }
2267
+ if (state.diffs[id] === null) {
2268
+ delete state.diffFor[id];
2269
+ state.diffTried[id] = Date.now();
2270
+ }
2271
+ if (state.diffOpen === id) renderDiff();
2272
+ }
2273
+
2274
+ /* A hunk's rows as table rows: unchanged lines on both sides, and each run
2275
+ of deletions beside the run of additions that follows it. */
2276
+ function diffHunkRows(hunk) {
2277
+ const cell = (number, text, kind, side) => [
2278
+ el('td', { class: 'num ' + kind + (side ? ' side' : ''),
2279
+ text: number === null ? '' : String(number) }),
2280
+ el('td', { class: kind, text: text === null ? '' : text })];
2281
+ const out = [el('tr', {}, [el('td', { class: 'hunk', colspan: 4,
2282
+ text: `@@ -${hunk.old} +${hunk.new} @@ ${hunk.head}` })])];
2283
+ let oldNo = hunk.old, newNo = hunk.new, removed = [], added = [];
2284
+
2285
+ const flush = () => {
2286
+ for (let i = 0; i < Math.max(removed.length, added.length); i++) {
2287
+ const left = i < removed.length, right = i < added.length;
2288
+ out.push(el('tr', {}, [
2289
+ ...cell(left ? oldNo : null, left ? removed[i] : null, left ? 'del' : 'empty'),
2290
+ ...cell(right ? newNo : null, right ? added[i] : null, right ? 'add' : 'empty', true)]));
2291
+ if (left) oldNo++;
2292
+ if (right) newNo++;
2293
+ }
2294
+ removed = [];
2295
+ added = [];
2296
+ };
2297
+
2298
+ for (const [mark, text] of hunk.rows) {
2299
+ if (mark === '-') removed.push(text);
2300
+ else if (mark === '+') added.push(text);
2301
+ else {
2302
+ flush();
2303
+ out.push(el('tr', {}, [...cell(oldNo++, text, 'ctx'), ...cell(newNo++, text, 'ctx', true)]));
2304
+ }
2305
+ }
2306
+ flush();
2307
+
2308
+ return out;
2309
+ }
2310
+
2311
+ function diffFile(file, open) {
2312
+ const rename = file.old && file.old !== file.path;
2313
+ const note = file.binary ? 'Binary file.'
2314
+ : file.truncated ? 'Too large to show here; the counts are complete.'
2315
+ : !file.hunks.length ? (rename ? 'Renamed, no change to its lines.'
2316
+ : 'No change to its lines (a mode change).') : null;
2317
+
2318
+ return el('details', { class: 'diff-file', open }, [
2319
+ el('summary', {}, [
2320
+ el('span', { class: 'diff-status', text: file.status }),
2321
+ el('span', { class: 'diff-path', text: rename ? `${file.old} → ${file.path}` : file.path }),
2322
+ el('span', { class: 'diff-add', text: '+' + fmt.int(file.additions) }),
2323
+ el('span', { class: 'diff-del', text: '−' + fmt.int(file.deletions) })]),
2324
+ note ? el('div', { class: 'diff-note', text: note })
2325
+ : el('div', { class: 'diff-scroll' }, [el('table', { class: 'diff-table' }, [
2326
+ el('colgroup', {}, ['num', 'code', 'num', 'code'].map((kind) =>
2327
+ el('col', kind === 'num' ? { style: 'width:48px' } : {}))),
2328
+ el('tbody', {}, file.hunks.flatMap(diffHunkRows))])])]);
2329
+ }
2330
+
2331
+ function renderDiff() {
2332
+ const card = $('diff-card');
2333
+ const row = state.diffOpen === null ? null : byId(state.diffOpen);
2334
+
2335
+ if (!row) {
2336
+ state.diffOpen = null;
2337
+ state.diffShown = null;
2338
+ card.hidden = true;
2339
+ $('diff-summary').replaceChildren();
2340
+ $('diff-files').replaceChildren();
2341
+ return;
2342
+ }
2343
+
2344
+ const hasParent = row.parent !== null && row.parent !== undefined;
2345
+ const reading = hasParent && row.status !== 'running' && row.commit;
2346
+ if (reading) loadDiff(row);
2347
+ const payload = reading ? state.diffs[row.id] : undefined;
2348
+
2349
+ // A poll that changed nothing about this panel leaves it alone, so the
2350
+ // files a reader collapsed stay collapsed.
2351
+ const shown = [row.id, row.commit, row.status, payload ? 'ready'
2352
+ : payload === null ? 'failed' : 'loading'].join('|');
2353
+ if (shown === state.diffShown && !card.hidden) return;
2354
+ state.diffShown = shown;
2355
+
2356
+ const message = !hasParent ? `${tag(row.id)} is the original code: there is no parent to compare it with.`
2357
+ : row.status === 'running' ? `${tag(row.id)} is still running; its code change appears when it settles.`
2358
+ : !row.commit ? `${tag(row.id)} has no commit to compare.`
2359
+ : payload === null ? 'The code change could not be read yet; the publisher writes them newest first.'
2360
+ : payload === undefined ? 'Loading the code change…' : null;
2361
+
2362
+ card.hidden = false;
2363
+ $('diff-title').textContent = 'Code change';
2364
+ $('diff-summary').replaceChildren(
2365
+ el('span', { class: 'diff-idea', text: `${tag(row.id)} ${row.title || ''}`.trim() }),
2366
+ hasParent ? el('span', { text: `against its parent ${tag(row.parent)}` }) : null,
2367
+ hasParent ? diffLine(row) : null);
2368
+
2369
+ const files = payload ? payload.files : [];
2370
+ $('diff-files').replaceChildren(...(message ? [el('p', { class: 'diff-note', text: message })]
2371
+ : files.length ? files.map((file, index) => diffFile(file, index < 25
2372
+ || files.length <= 25))
2373
+ : [el('p', { class: 'diff-note', text: 'No change to the code.' })]));
2374
+ }
2375
+
2376
+ /* ==== SECTION: run-table ==== */
2377
+
2378
+ /* The data-table widget, plus two things it
2379
+ lacks: an initial sort, and a pinned set of rows that is outlined and
2380
+ scrolled to. `options.pinned(row)` names them; `reveal` moves to their
2381
+ page and scrolls the box, and is set only when the pin changed, so a
2382
+ poll never yanks the table away from where someone scrolled it. */
2383
+ const TABLE_PAGE = 40;
2384
+ const tables = {};
2385
+
2386
+ function renderDataTable(holderId, rows, columns, options, reveal) {
2387
+ const holder = $(holderId);
2388
+ if (!holder) return;
2389
+
2390
+ options = options || {};
2391
+ const view = tables[holderId] = tables[holderId] || {
2392
+ sort: options.sort || columns[0].key, dir: options.dir || 1, page: 0,
2393
+ query: '', filters: {}, rows, columns, options };
2394
+ Object.assign(view, { rows, columns, options });
2395
+
2396
+ if (!holder.dataset.built) {
2397
+ holder.dataset.built = 'true';
2398
+ const search = el('input', { type: 'search', class: 'table-search',
2399
+ placeholder: 'Search…', 'aria-label': 'Search the table' });
2400
+ search.addEventListener('input', () => {
2401
+ view.query = search.value.trim().toLowerCase();
2402
+ view.page = 0;
2403
+ drawTable(holderId);
2404
+ });
2405
+
2406
+ const selects = (options.filters || []).map((filter) => {
2407
+ const select = el('select', { 'aria-label': filter.label,
2408
+ dataset: { key: filter.key } });
2409
+ select.addEventListener('change', () => {
2410
+ view.filters[filter.key] = select.value;
2411
+ view.page = 0;
2412
+ drawTable(holderId);
2413
+ });
2414
+ return select;
2415
+ });
2416
+
2417
+ holder.replaceChildren(
2418
+ el('div', { class: 'table-controls' }, [search, ...selects,
2419
+ el('span', { class: 'table-count muted' })]),
2420
+ el('div', { class: 'table-scroll' }, [el('table', {}, [
2421
+ el('thead', {}, [el('tr')]), el('tbody')])]),
2422
+ el('div', { class: 'table-foot' }, [
2423
+ el('button', { class: 'ghost small', type: 'button', text: 'Previous',
2424
+ onclick: () => { view.page = Math.max(0, view.page - 1); drawTable(holderId); } }),
2425
+ el('span', { class: 'table-page muted' }),
2426
+ el('button', { class: 'ghost small', type: 'button', text: 'Next',
2427
+ onclick: () => { view.page += 1; drawTable(holderId); } })]));
2428
+ }
2429
+
2430
+ for (const select of holder.querySelectorAll('.table-controls select')) {
2431
+ const key = select.dataset.key;
2432
+ const label = (options.filters.find((f) => f.key === key) || {}).label;
2433
+ const values = [...new Set(rows.map((r) => r[key]))]
2434
+ .filter((v) => !missing(v)).sort();
2435
+ const current = view.filters[key] || '';
2436
+ select.replaceChildren(el('option', { value: '', text: `All ${label}` }),
2437
+ ...values.map((v) => el('option', { value: String(v), text: String(v) })));
2438
+ select.value = values.map(String).includes(current) ? current : '';
2439
+ }
2440
+
2441
+ drawTable(holderId, reveal);
2442
+ }
2443
+
2444
+ function drawTable(holderId, reveal) {
2445
+ const holder = $(holderId);
2446
+ const view = tables[holderId];
2447
+ const { columns, sort, dir } = view;
2448
+ const pinned = view.options.pinned || (() => false);
2449
+
2450
+ holder.querySelector('thead tr').replaceChildren(...columns.map((c) =>
2451
+ el('th', { class: c.num ? 'num' : null, scope: 'col',
2452
+ title: c.title || 'Sort', onclick: () => {
2453
+ if (view.sort === c.key) view.dir *= -1;
2454
+ else { view.sort = c.key; view.dir = 1; }
2455
+ drawTable(holderId);
2456
+ } }, [c.label, el('span', { class: 'arrow', text: c.key === sort
2457
+ ? (dir > 0 ? ' ▲' : ' ▼') : '' })])));
2458
+
2459
+ const matches = view.rows.filter((row) => {
2460
+ for (const [key, value] of Object.entries(view.filters))
2461
+ if (value && String(row[key]) !== value) return false;
2462
+ return !view.query || columns.some((c) => !missing(row[c.key])
2463
+ && String(row[c.key]).toLowerCase().includes(view.query));
2464
+ }).sort((a, b) => {
2465
+ const x = a[sort], y = b[sort];
2466
+ if (x === y) return (a._order || 0) - (b._order || 0);
2467
+ if (missing(x)) return 1;
2468
+ if (missing(y)) return -1;
2469
+ return (typeof x === 'number' ? x - y
2470
+ : String(x).localeCompare(String(y))) * dir;
2471
+ });
2472
+
2473
+ const pages = Math.max(1, Math.ceil(matches.length / TABLE_PAGE));
2474
+ if (reveal) {
2475
+ const first = matches.findIndex(pinned);
2476
+ if (first >= 0) view.page = Math.floor(first / TABLE_PAGE);
2477
+ }
2478
+ view.page = Math.min(view.page, pages - 1);
2479
+ const page = matches.slice(view.page * TABLE_PAGE, (view.page + 1) * TABLE_PAGE);
2480
+
2481
+ holder.querySelector('.table-count').textContent =
2482
+ `${fmt.int(matches.length)} of ${fmt.int(view.rows.length)} shown`;
2483
+ holder.querySelector('.table-page').textContent =
2484
+ `page ${view.page + 1} of ${pages}`;
2485
+
2486
+ holder.querySelector('tbody').replaceChildren(...page.map((row) =>
2487
+ el('tr', { dataset: { pinned: String(Boolean(pinned(row))),
2488
+ selected: String(Boolean(view.options.selected
2489
+ ? view.options.selected(row)
2490
+ : state.selection && state.selection.has(row.id))) } },
2491
+ columns.map((c) => {
2492
+ const value = row[c.key];
2493
+ const text = c.format ? c.format(value, row) : missing(value) ? '–'
2494
+ : c.num ? Number(value).toFixed(c.digits ?? 0) : String(value);
2495
+ return el('td', { class: [c.num ? 'num' : null, c.cls || null]
2496
+ .filter(Boolean).join(' ') || null, text,
2497
+ style: c.colour ? `color:${c.colour(value, row)}` : null,
2498
+ title: c.cls === 'note' ? text : null,
2499
+ dataset: c.tone && c.tone(value, row) ? { tone: c.tone(value, row) }
2500
+ : {} });
2501
+ }))));
2502
+
2503
+ // Scroll the box, not the page: the chart that was clicked stays put.
2504
+ const target = reveal && holder.querySelector('tbody tr[data-pinned="true"]');
2505
+ if (target) {
2506
+ const box = holder.querySelector('.table-scroll');
2507
+ const head = holder.querySelector('thead').getBoundingClientRect().height;
2508
+ const offset = target.getBoundingClientRect().top
2509
+ - box.getBoundingClientRect().top;
2510
+ // Flush with the sticky header's bottom edge: any less and a sliver
2511
+ // of the row above shows beneath it.
2512
+ if (offset < head || offset > box.clientHeight - target.offsetHeight)
2513
+ box.scrollTop += offset - head;
2514
+ }
2515
+ }
2516
+
2517
+ /* Same test the runner applies (autoopt.OPS), so a red cell is a run that
2518
+ broke the gate. */
2519
+ function gatePasses(value, gate) {
2520
+ const tol = gate.tol || 0;
2521
+ switch (gate.op) {
2522
+ case '<=': return value <= gate.threshold + tol;
2523
+ case '<': return value < gate.threshold + tol;
2524
+ case '>=': return value >= gate.threshold - tol;
2525
+ case '>': return value > gate.threshold - tol;
2526
+ case '==': return Math.abs(value - gate.threshold) <= tol;
2527
+ default: return true;
2528
+ }
2529
+ }
2530
+
2531
+ /* One row per run: every settled, visible iteration's seeds, and its failed
2532
+ seeds with their error in the note column. */
2533
+ function runRows() {
2534
+ const rows = [];
2535
+ let order = 0;
2536
+
2537
+ for (const row of visible().slice().sort((a, b) => b.id - a.id)) {
2538
+ const common = { id: row.id, iteration: row.id, category: row.category,
2539
+ title: row.title || '', status: row.status, parent: row.parent,
2540
+ round: row.round,
2541
+ commit: (row.commit || '').slice(0, 8),
2542
+ tests: row.tests === true ? 'pass' : row.tests === false ? 'FAIL' : '' };
2543
+
2544
+ for (const run of row.runs || []) {
2545
+ const out = { ...common, _order: order++, seed: run.seed,
2546
+ run_status: 'ok', objective: run.objective,
2547
+ wall: run.seconds, note: run.note || '' };
2548
+ for (const [name, value] of Object.entries(run.gates || {}))
2549
+ out['g:' + name] = value;
2550
+ for (const [name, value] of Object.entries(run.observers || {}))
2551
+ out['o:' + name] = value;
2552
+ rows.push(out);
2553
+ }
2554
+
2555
+ for (const failure of row.failures || [])
2556
+ rows.push({ ...common, _order: order++, seed: failure.seed,
2557
+ run_status: 'error', objective: null, wall: failure.seconds,
2558
+ note: String(failure.error || '') });
2559
+ }
2560
+
2561
+ return rows;
2562
+ }
2563
+
2564
+ function runColumns(rows) {
2565
+ const snapshot = state.snapshot;
2566
+ const unit = (u) => u ? ` (${u})` : '';
2567
+ const numeric = (key) => ({ digits: columnDigits(rows.map((r) => r[key])) });
2568
+
2569
+ return [
2570
+ { key: 'iteration', label: '#', format: tag },
2571
+ { key: 'category', label: 'type', format: (v) => (SHORT[v] || v).toUpperCase() },
2572
+ { key: 'seed', label: 'seed', num: true },
2573
+ { key: 'objective', label: snapshot.objective.name + unit(snapshot.objective.unit),
2574
+ num: true, ...numeric('objective'),
2575
+ format: (v) => missing(v) ? '–'
2576
+ : v.toFixed(columnDigits(rows.map((r) => r.objective))) },
2577
+ ...(snapshot.gates || []).map((gate) => ({ key: 'g:' + gate.name,
2578
+ label: gate.name, num: true, title: `gate: ${gate.op} ${gate.threshold}`
2579
+ + (gate.tol ? ` ± ${gate.tol}` : ''),
2580
+ format: (v) => missing(v) ? '–' : fmt.sig(v),
2581
+ tone: (v) => !missing(v) && !gatePasses(v, gate) ? 'bad' : null })),
2582
+ ...(snapshot.observers || []).map((observer) => ({ key: 'o:' + observer.name,
2583
+ label: observer.name + unit(observer.unit), num: true,
2584
+ format: (v) => missing(v) ? '–' : fmt.sig(v) })),
2585
+ // Seconds to two places, so runs a fraction of a second apart differ.
2586
+ { key: 'wall', label: 'wall clock (s)', num: true,
2587
+ format: (v) => missing(v) ? '–' : Number(v).toFixed(2) },
2588
+ { key: 'run_status', label: 'run', tone: (v) => v === 'ok' ? null : 'bad' },
2589
+ { key: 'status', label: 'iteration',
2590
+ tone: (v) => v === 'ok' ? null : 'bad' },
2591
+ { key: 'tests', label: 'tests', tone: (v) => v === 'FAIL' ? 'bad' : null },
2592
+ { key: 'parent', label: 'parent', format: tag },
2593
+ { key: 'round', label: 'round', num: true },
2594
+ { key: 'commit', label: 'commit', cls: 'mono' },
2595
+ { key: 'title', label: 'idea' },
2596
+ { key: 'note', label: 'note', cls: 'note' },
2597
+ ].filter(Boolean);
2598
+ }
2599
+
2600
+ function renderRunTable(reveal) {
2601
+ if (!state.snapshot) return;
2602
+ const rows = runRows();
2603
+
2604
+ fill('run-note', `${fmt.int(rows.length)} runs. Click a point in the chart `
2605
+ + 'to outline its runs here; a run dot (All runs) outlines that one run. '
2606
+ + 'A red value broke its gate.');
2607
+
2608
+ renderDataTable('run-table', rows, runColumns(rows), {
2609
+ sort: 'iteration', dir: -1,
2610
+ filters: [{ key: 'status', label: 'statuses' },
2611
+ { key: 'category', label: 'types' }],
2612
+ pinned: (row) => state.pinned !== null && row.iteration === state.pinned
2613
+ && (state.pinnedSeed === null || row.seed === state.pinnedSeed),
2614
+ }, reveal);
2615
+ }
2616
+
2617
+ selectionListeners.push(() => renderRunTable(false));
2618
+
2619
+ /* A second click on the same point or node drops the pin. */
2620
+ function setPinned(identifier, seed) {
2621
+ seed = seed === undefined ? null : seed;
2622
+ const same = state.pinned === identifier && state.pinnedSeed === seed;
2623
+ state.pinned = same ? null : identifier;
2624
+ state.pinnedSeed = same ? null : seed;
2625
+ renderRunTable(true);
2626
+ }
2627
+
2628
+ /* ==== SECTION: log ==== */
2629
+
2630
+ /* One fixed decimal count for a column of values, so the digits align: four
2631
+ significant figures of the largest. */
2632
+ // Decimals that give the column's smallest nonzero value four significant
2633
+ // figures (at most 6): after a large speedup the baseline's 1.671 and the
2634
+ // root's 0.002741 share a column, and decimals set by the largest value
2635
+ // would print both as 0.003.
2636
+ // Whole-number ticks on an iteration axis that spans few iterations, where
2637
+ // Plotly would otherwise tick at 0.5 or 0.2; wider spans tick in whole steps
2638
+ // already.
2639
+ function iterationTicks(xs, type) {
2640
+ const top = Math.max(0, ...xs.filter((v) => !missing(v)));
2641
+ return type !== 'log' && top <= 15 ? { tick0: 0, dtick: 1 } : {};
2642
+ }
2643
+
2644
+ function columnDigits(values) {
2645
+ const sizes = values.filter((v) => !missing(v) && Number(v) !== 0)
2646
+ .map((v) => Math.abs(Number(v)));
2647
+ const low = sizes.length ? Math.min(...sizes) : 0;
2648
+ return low ? Math.max(0, Math.min(6, 3 - Math.floor(Math.log10(low)))) : 3;
2649
+ }
2650
+
2651
+ function logColumns() {
2652
+ const snapshot = state.snapshot;
2653
+ const digits = columnDigits(snapshot.iterations.map((row) => row.value));
2654
+
2655
+ return [
2656
+ { key: 'id', label: '#', width: 44, format: tag },
2657
+ { key: 'category', label: 'type', width: 50,
2658
+ format: (v) => (SHORT[v] || v).toUpperCase() },
2659
+ { key: 'value', label: snapshot.objective.name, width: 78, num: true,
2660
+ format: (v, row) => row.status === 'running' ? 'running' : fmt.num(v, digits) },
2661
+ { key: 'n_runs', label: 'runs', width: 34, num: true,
2662
+ format: (v) => v ? fmt.int(v) : '' },
2663
+ { key: 'seconds', label: 'time', width: 54, num: true,
2664
+ format: (v) => v ? fmt.duration(v) : '' },
2665
+ { key: 'status', label: 'status', width: 82,
2666
+ format: (v) => v === 'ok' ? '' : v },
2667
+ { key: 'title', label: 'idea', format: (v) => v || '(untitled)' },
2668
+ ].filter(Boolean);
2669
+ }
2670
+
2671
+ /* Where an iteration's time went. Only the steps the scripts time are
2672
+ measured; the remainder is the subagent's own work, inferred, since every
2673
+ subagent structures its reading, editing and checking differently. */
2674
+ function timeRows(time) {
2675
+ if (!time || missing(time.total)) return [];
2676
+ const share = (s) => time.total > 0 ? ` · ${Math.round(100 * s / time.total)}%` : '';
2677
+ const line = (s, note) => `${fmt.duration(s)}${share(s)}${note ? ' · ' + note : ''}`;
2678
+ return [
2679
+ ['time total', fmt.duration(time.total)],
2680
+ ['time: runs', line(time.runs, `${time.n_runs} run${time.n_runs === 1 ? '' : 's'}`)],
2681
+ ...(missing(time.tests) ? [] : [['time: unit tests',
2682
+ line(time.tests, time.tests_scope === 'subset' ? 'subset' : 'full suite')]]),
2683
+ ...(missing(time.validation) ? [] : [['time: validation', line(time.validation)]]),
2684
+ ['time: subagent work', line(time.subagent, 'the rest, inferred')],
2685
+ ];
2686
+ }
2687
+
2688
+ function iterationDetail(row) {
2689
+ const snapshot = state.snapshot;
2690
+ const objective = row.objective || {};
2691
+ const baseline = snapshot.frontier.baseline;
2692
+
2693
+ return [
2694
+ ['status', row.status + (row.stage ? ' · ' + row.stage : '')],
2695
+ ['category', row.category],
2696
+ ...(minedStages() && !missing(row.mining_stage)
2697
+ ? [['miner stage', 'S' + row.mining_stage]] : []),
2698
+ ['parent', tag(row.parent)],
2699
+ ['round', String(row.round)],
2700
+ ['runs', `${row.n_runs}` + (row.n_failed ? ` (${row.n_failed} failed)` : '')],
2701
+ ['median', fmt.sig(row.value)],
2702
+ ['mean ± sd', `${fmt.sig(objective.mean)} ± ${fmt.sig(objective.std)}`],
2703
+ ['min … max', `${fmt.sig(objective.min)} … ${fmt.sig(objective.max)}`],
2704
+ ['vs baseline', missing(baseline) || missing(row.value) ? '–'
2705
+ : fmt.signed(row.value - baseline, 4)],
2706
+ ['frontier at start', fmt.sig(row.frontier_at_start)],
2707
+ ['noise band', fmt.sig(row.noise_band)],
2708
+ ['wall clock', fmt.duration(row.seconds)],
2709
+ ...timeRows(row.time),
2710
+ ['branch', row.branch || '–'],
2711
+ ...(row.toolchain ? [['toolchain', row.toolchain, row.toolchain === 'specific'
2712
+ ? 'not promotable: the change depends on a compiler or toolchain choice'
2713
+ : null]] : []),
2714
+ ['commit', (row.commit || '–').slice(0, 10)],
2715
+ ['best run', row.best_run || '–'],
2716
+ ...Object.entries(row.gates || {}).map(([name, gate]) => [kindKey('gate', name),
2717
+ `${gate.pass ? 'pass' : 'FAIL'} ${gate.op} ${fmt.sig(gate.threshold)}, `
2718
+ + `worst ${fmt.sig(gate.worst)}`]),
2719
+ ...Object.entries(row.observers || {}).map(([name, observer]) =>
2720
+ [kindKey('obs', name), fmt.sig(observer.median)]),
2721
+ ...(row.runs || []).map((run) => [kindKey('seed', run.seed),
2722
+ `${fmt.sig(run.objective)} · ${fmt.duration(run.seconds)}`]),
2723
+ ...(row.failures || []).map((failure) => [kindKey('seed',
2724
+ `${failure.seed} failed`), String(failure.error)]),
2725
+ ];
2726
+ }
2727
+
2728
+ /* A detail key naming a gate, an observer or a seed: the kind in capitals
2729
+ in its own muted hue (`--tag-gate`, `--tag-obs`, `--tag-seed`), so the
2730
+ three groups of rows can be told apart at a glance. */
2731
+ const KIND_CLASS = { gate: 'k-tag k-gate', obs: 'k-tag k-obs', seed: 'k-tag k-seed' };
2732
+
2733
+ function kindKey(kind, name) {
2734
+ return el('span', {}, [el('span', { class: KIND_CLASS[kind],
2735
+ text: kind.toUpperCase() }), ' ' + name]);
2736
+ }
2737
+
2738
+ /* The README as it should read on screen: the markdown these files use,
2739
+ turned into elements. The title and the metadata line are dropped, since
2740
+ both are already in the entry. With `options.more` (the log), the code
2741
+ change leads, and an excerpt the payload cut ends in SHOW MORE, which
2742
+ swaps in the whole README fetched from readmes/<id>.json; the choice
2743
+ survives the log's re-render on every poll. */
2744
+ function describe(row, options) {
2745
+ const more = Boolean(options && options.more);
2746
+ const lead = more ? diffLine(row) : null;
2747
+ if (!row.notes) return el('div', { class: 'log-desc' },
2748
+ [lead, el('p', { class: 'log-p', text: 'No README written.' })]);
2749
+
2750
+ if (more && row.notes_cut && state.logFull.has(row.id)) {
2751
+ loadReadme(row.id);
2752
+ const text = state.readmes[row.id];
2753
+ if (typeof text === 'string')
2754
+ return el('div', { class: 'log-desc' }, [lead,
2755
+ markdown(readmeBody(text)), moreButton(row, true)]);
2756
+ return el('div', { class: 'log-desc' }, [lead, excerptBlocks(row),
2757
+ el('p', { class: 'log-p muted', text: text === null ? 'The whole README '
2758
+ + 'could not be read.' : 'Loading the whole README…' }),
2759
+ moreButton(row, true)]);
2760
+ }
2761
+
2762
+ return el('div', { class: 'log-desc' }, [lead, excerptBlocks(row),
2763
+ more && row.notes_cut ? moreButton(row, false) : null]);
2764
+ }
2765
+
2766
+ /* The README without what the entry already shows: the title, the
2767
+ metadata line and the per-run table. */
2768
+ function readmeBody(text) {
2769
+ return text.split('\n').filter((line) => !/^#\s/.test(line.trim())
2770
+ && !/^\*\*Category:/.test(line.trim()) && !/^\s*\|/.test(line)).join('\n');
2771
+ }
2772
+
2773
+ /* SHOW MORE at the cut, SHOW LESS once open. A click here is not a click on
2774
+ the entry, which would close it. */
2775
+ function moreButton(row, open) {
2776
+ return el('button', { class: 'ghost small log-more', type: 'button',
2777
+ 'aria-expanded': String(open), text: open ? 'SHOW LESS' : 'SHOW MORE',
2778
+ onclick: (event) => {
2779
+ event.stopPropagation();
2780
+ if (open) state.logFull.delete(row.id);
2781
+ else state.logFull.add(row.id);
2782
+ renderIterationLog();
2783
+ } });
2784
+ }
2785
+
2786
+ /* The payload's excerpt as paragraphs and headings. */
2787
+ function excerptBlocks(row) {
2788
+ const blocks = [];
2789
+ let paragraph = [];
2790
+ const flush = () => {
2791
+ if (paragraph.length) {
2792
+ blocks.push(el('p', { class: 'log-p',
2793
+ text: paragraph.join(' ').replace(/[*`]/g, '') }));
2794
+ paragraph = [];
2795
+ }
2796
+ };
2797
+
2798
+ for (const raw of row.notes.split('\n')) {
2799
+ const line = raw.trim();
2800
+ if (!line) { flush(); continue; }
2801
+ if (/^#\s/.test(line) || /^\*\*Category:/.test(line) || /^\|/.test(line))
2802
+ continue;
2803
+ if (/^#{2,}\s/.test(line)) {
2804
+ flush();
2805
+ blocks.push(el('div', { class: 'log-h', text: line.replace(/^#+\s*/, '') }));
2806
+ continue;
2807
+ }
2808
+ paragraph.push(line);
2809
+ }
2810
+ flush();
2811
+
2812
+ // The excerpt is cut at a character budget; a trailing heading with
2813
+ // nothing under it, or a few words of a sentence, is noise.
2814
+ while (blocks.length) {
2815
+ const last = blocks[blocks.length - 1];
2816
+ if (!(last.className === 'log-h' || (last.textContent.length < 40
2817
+ && last.textContent.endsWith('…')))) break;
2818
+ blocks.pop();
2819
+ }
2820
+
2821
+ return el('div', {}, blocks.length ? blocks
2822
+ : [el('p', { class: 'log-p', text: row.notes })]);
2823
+ }
2824
+
2825
+ /* The widget draws the one-line entries and the key/value detail; the
2826
+ README goes in above the detail of every open entry. */
2827
+ function decorateLog() {
2828
+ for (const entry of ROOT.querySelectorAll('#log .log-entry[data-open="true"]')) {
2829
+ const row = byId(Number(entry.dataset.id));
2830
+ const detail = entry.querySelector('.log-detail');
2831
+ if (row && detail && !entry.querySelector('.log-desc'))
2832
+ entry.insertBefore(describe(row, { more: true }), detail);
2833
+ }
2834
+ }
2835
+
2836
+ function renderIterationLog() {
2837
+ const snapshot = state.snapshot;
2838
+ if (!snapshot) return;
2839
+
2840
+ renderLog('log', snapshot.iterations, logColumns(), { slotOf: catSlot,
2841
+ hidden: state.hidden, emphasised: state.emphasised, detail: iterationDetail,
2842
+ // Opening an entry outlines its runs in Every run. The widget
2843
+ // re-renders the log after this returns.
2844
+ onPin: (id, opened) => {
2845
+ if (opened) { state.pinned = null; setPinned(id); }
2846
+ queueMicrotask(decorateLog);
2847
+ } });
2848
+ decorateLog();
2849
+ }
2850
+
2851
+ /* ==== SECTION: tree ==== */
2852
+
2853
+ selectionListeners.push(() => renderTree());
2854
+
2855
+ /* The lineage of the whole search. */
2856
+ function renderTree() {
2857
+ const snapshot = state.snapshot;
2858
+ const holder = $('tree-holder');
2859
+ if (!snapshot || !holder) return;
2860
+
2861
+ // The column is built once; the widget needs its holder in the page to
2862
+ // measure it.
2863
+ if (!holder.firstChild)
2864
+ holder.replaceChildren(el('div', { class: 'tree-col' }, [
2865
+ el('div', { class: 'lineage-wrap' }, [
2866
+ el('div', { class: 'lineage-holder', id: 'lineage-0' }),
2867
+ el('div', { class: 'lineage-map', id: 'lineage-map-0' })]),
2868
+ ]));
2869
+
2870
+ const roots = new Set(((snapshot.state || {}).roots || []).map((r) => r.id));
2871
+ const nodes = snapshot.iterations.map((row) => ({ id: row.id,
2872
+ parent: row.parent,
2873
+ status: row.status, category: row.category, value: row.value,
2874
+ title: row.title, round: row.round, on_frontier: row.on_frontier,
2875
+ is_root: roots.has(row.id) }));
2876
+
2877
+ const drawn = renderLineage('lineage-0', 'lineage-map-0', nodes, {
2878
+ slotOf: catSlot, hidden: state.hidden, emphasised: state.emphasised,
2879
+ onPin: (id) => { setPinned(id); toggleTreeNode(id); } });
2880
+
2881
+ renderTreeNote((drawn && drawn.collapsed) || 0);
2882
+ renderTreeNode();
2883
+ }
2884
+
2885
+ /* ==== the node panel: a clicked tree node's whole README and every number ==== */
2886
+
2887
+ /* A click opens the node's panel under the tree; clicking the same node, or
2888
+ 'close', shuts it. */
2889
+ function toggleTreeNode(id) {
2890
+ state.treeNode = state.treeNode === id ? null : id;
2891
+ renderTreeNode();
2892
+ }
2893
+
2894
+ /* The payload carries only an excerpt of each README; the whole file is
2895
+ fetched when its panel opens, and again when the excerpt changes (a
2896
+ subagent still writing it). */
2897
+ async function loadReadme(id) {
2898
+ const row = byId(id);
2899
+ const excerpt = row ? row.notes || '' : '';
2900
+ // No README in the row means none to fetch; a readmes/<id>.json on disk
2901
+ // then belongs to another search a handover published.
2902
+ if (!row || !row.has_readme) return;
2903
+ if (!TRANSPORT || !TRANSPORT.readme || state.readmeFor[id] === excerpt) return;
2904
+ state.readmeFor[id] = excerpt;
2905
+ try {
2906
+ const payload = await TRANSPORT.readme(id);
2907
+ state.readmes[id] = payload && typeof payload.text === 'string' ? payload.text : null;
2908
+ } catch (error) {
2909
+ state.readmes[id] = null;
2910
+ }
2911
+ if (state.treeNode === id) renderTreeNode();
2912
+ if (state.logFull.has(id)) renderIterationLog();
2913
+ }
2914
+
2915
+ function renderTreeNode() {
2916
+ const holder = $('tree-node');
2917
+ if (!holder) return;
2918
+ const row = state.treeNode === null ? null : byId(state.treeNode);
2919
+ if (!row) {
2920
+ holder.hidden = true;
2921
+ holder.replaceChildren();
2922
+ return;
2923
+ }
2924
+
2925
+ loadReadme(row.id);
2926
+ const text = state.readmes[row.id];
2927
+ const readme = text ? markdown(text)
2928
+ : el('div', {}, [
2929
+ el('p', { class: 'muted', text: text === null ? 'The whole README could not '
2930
+ + 'be read; this is the excerpt the payload carries.'
2931
+ : (row.notes ? 'Loading the whole README…' : '') }),
2932
+ describe(row)]);
2933
+
2934
+ const pairs = iterationDetail(row);
2935
+
2936
+ holder.hidden = false;
2937
+ holder.replaceChildren(
2938
+ el('div', { class: 'tree-node-head' }, [
2939
+ el('span', { class: 'tree-node-id', text: tag(row.id) }),
2940
+ el('span', { class: 'tree-node-title', text: row.title || '' }),
2941
+ el('button', { class: 'ghost small', type: 'button', text: 'close',
2942
+ onclick: () => { state.treeNode = null; renderTreeNode(); } })]),
2943
+ el('div', { class: 'tree-node-body' }, [
2944
+ el('div', { class: 'tree-node-readme' }, [readme]),
2945
+ el('div', { class: 'log-detail pairs tree-node-detail' }, pairs.map(([key, value]) =>
2946
+ el('div', { class: 'pair' }, [
2947
+ el('span', { class: 'k' }, [key]),
2948
+ el('span', { class: 'v', text: value })])))]));
2949
+ }
2950
+
2951
+ /* The whole README, rendered: headings, paragraphs, lists, tables and code
2952
+ blocks, with `code` and **bold** spans. Everything from the file goes in
2953
+ as text, never as markup. */
2954
+ function markdown(text) {
2955
+ const LIST = /^\s*([-*]|\d+\.)\s+/;
2956
+ const OTHER = /^(#{1,6}\s|```|\s*\|)/;
2957
+ const inline = (line) => {
2958
+ const parts = [];
2959
+ const span = /(`[^`]+`|\*\*[^*]+\*\*)/g;
2960
+ let last = 0;
2961
+ let match;
2962
+ while ((match = span.exec(line))) {
2963
+ if (match.index > last) parts.push(line.slice(last, match.index));
2964
+ const token = match[0];
2965
+ parts.push(token[0] === '`' ? el('code', { text: token.slice(1, -1) })
2966
+ : el('strong', { text: token.slice(2, -2) }));
2967
+ last = match.index + token.length;
2968
+ }
2969
+ if (last < line.length) parts.push(line.slice(last));
2970
+ return parts;
2971
+ };
2972
+
2973
+ const lines = text.split('\n');
2974
+ const blocks = [];
2975
+ let i = 0;
2976
+ while (i < lines.length) {
2977
+ const line = lines[i];
2978
+ if (/^```/.test(line.trim())) {
2979
+ const body = [];
2980
+ for (i++; i < lines.length && !/^```/.test(lines[i].trim()); i++) body.push(lines[i]);
2981
+ i++;
2982
+ blocks.push(el('pre', { class: 'md-pre', text: body.join('\n') }));
2983
+ continue;
2984
+ }
2985
+ const heading = /^(#{1,6})\s+(.*)$/.exec(line);
2986
+ if (heading) {
2987
+ blocks.push(el('div', { class: heading[1].length === 1 ? 'md-h1' : 'md-h' },
2988
+ inline(heading[2])));
2989
+ i++;
2990
+ continue;
2991
+ }
2992
+ if (/^\s*\|/.test(line)) {
2993
+ const rows = [];
2994
+ for (; i < lines.length && /^\s*\|/.test(lines[i]); i++)
2995
+ if (!/^\s*\|[\s:|-]+\|?\s*$/.test(lines[i])) rows.push(lines[i]);
2996
+ const cells = (row) => row.trim().replace(/^\|/, '').replace(/\|$/, '')
2997
+ .split('|').map((cell) => cell.trim());
2998
+ blocks.push(el('table', { class: 'md-table' }, rows.map((row, k) =>
2999
+ el('tr', {}, cells(row).map((cell) => el(k === 0 ? 'th' : 'td', {},
3000
+ inline(cell)))))));
3001
+ continue;
3002
+ }
3003
+ if (LIST.test(line)) {
3004
+ const items = [];
3005
+ for (; i < lines.length; i++) {
3006
+ if (LIST.test(lines[i])) items.push({ nested: lines[i].search(/\S/) >= 2,
3007
+ text: lines[i].replace(LIST, '') });
3008
+ else if (/^\s{2,}\S/.test(lines[i])) items[items.length - 1].text += ' '
3009
+ + lines[i].trim();
3010
+ else break;
3011
+ }
3012
+ blocks.push(el('ul', { class: 'md-ul' }, items.map((item) => el('li',
3013
+ { class: item.nested ? 'md-li-nested' : null }, inline(item.text)))));
3014
+ continue;
3015
+ }
3016
+ if (!line.trim()) { i++; continue; }
3017
+ const paragraph = [];
3018
+ for (; i < lines.length && lines[i].trim() && !OTHER.test(lines[i])
3019
+ && !LIST.test(lines[i]); i++) paragraph.push(lines[i].trim());
3020
+ blocks.push(el('p', { class: 'md-p' }, inline(paragraph.join(' '))));
3021
+ }
3022
+ return el('div', { class: 'md' }, blocks);
3023
+ }
3024
+
3025
+ function renderTreeNote(collapsed) {
3026
+ const snapshot = state.snapshot;
3027
+ const roots = ((snapshot.state || {}).roots || []).length;
3028
+
3029
+ $('tree-note').textContent = (collapsed ? `Condensed: ${fmt.int(collapsed)} `
3030
+ + 'iterations off the frontier are tallied rather than drawn. Roots, the '
3031
+ + 'frontier path, anything running and the 12 most recent are drawn '
3032
+ + 'individually. ' : '')
3033
+ + 'Each promotion makes an iteration the root, and the next generation '
3034
+ + `forks from it. ${roots} root(s).`;
3035
+
3036
+ fill('tree-legend',
3037
+ ...[...(state.snapshot.categories || [])].sort(categoryOrder)
3038
+ .map((category) => el('span', { class: 'legend-item' }, [
3039
+ el('span', { class: 'swatch round', style: `background:`
3040
+ + `${css(catSlot(category))}` }), SHORT[category] || category])),
3041
+ el('span', { class: 'legend-item' }, [markerKey(css('--text'), 'circle'),
3042
+ 'root or frontier: its hue at full strength']),
3043
+ el('span', { class: 'legend-item' }, [statusKey('hollow', resolved('--running')),
3044
+ 'running']),
3045
+ el('span', { class: 'legend-item' }, [markerKey(css('--bad'), 'x'),
3046
+ 'gate failed']),
3047
+ el('span', { class: 'legend-item' }, [el('span', { class: 'tally-key mark-key',
3048
+ text: '+N' }), 'N iterations tallied, hover for detail']));
3049
+ }
3050
+
3051
+ /* The frontier the tiles and the sidebar describe. */
3052
+ function scopedFrontier() {
3053
+ const snapshot = state.snapshot;
3054
+ const frontier = snapshot.frontier;
3055
+
3056
+ return { value: frontier.value, id: frontier.id,
3057
+ baseline: frontier.baseline, total_gain: frontier.total_gain,
3058
+ total_percent: frontier.total_percent,
3059
+ steps: snapshot.stats.n_frontier };
3060
+ }
3061
+
3062
+ /* The ending in the topbar and the stages as text, both from the
3063
+ search's own state files, in stages.py's own words. */
3064
+
3065
+ function renderAfterLines(after) {
3066
+ const ended = after.ended;
3067
+ const line = $('ended-line');
3068
+ line.hidden = !ended;
3069
+ if (ended) {
3070
+ const unit = ended.unit ? ` ${ended.unit}` : '';
3071
+ line.textContent = `ended ${String(ended.at || '').slice(0, 10)} · `
3072
+ + `${ended.winner || '–'} ${fmt.sig(ended.winner_median)}${unit} vs A0 `
3073
+ + `${fmt.sig(ended.zero_median)}${unit} · ${ended.reason || 'no reason stated'}`;
3074
+ line.title = ended.paired ? `paired timing: ${ended.paired}` : '';
3075
+ }
3076
+
3077
+ const strip = $('stage-strip');
3078
+ strip.hidden = !(after.stages || []).length;
3079
+ strip.textContent = (after.stages || []).map(([name, status]) =>
3080
+ `${name} ${status}`).join(' · ');
3081
+ }
3082
+
3083
+ function renderSummary() {
3084
+ const snapshot = state.snapshot;
3085
+ if (!snapshot) return;
3086
+
3087
+ const counts = snapshot.counts;
3088
+ const plan = snapshot.plan;
3089
+ const frontier = scopedFrontier();
3090
+ const unit = snapshot.objective.unit ? ` (${snapshot.objective.unit})` : '';
3091
+ const gpus = (state.lastGpus || {}).gpus || [];
3092
+ const improved = !missing(frontier.total_gain) && frontier.total_gain !== 0
3093
+ && (frontier.total_gain > 0) === (snapshot.objective.direction === 'max');
3094
+
3095
+ $('run-root').textContent = snapshot.root;
3096
+ renderAfterLines(snapshot.after || {});
3097
+ $('hero-value').textContent = fmt.int(counts.iterations);
3098
+ $('hero-sub').textContent = `${fmt.int(counts.runs)} runs`
3099
+ + (counts.running ? ` · ${fmt.int(counts.running)} in flight` : '')
3100
+ + (counts.working ? ` · ${fmt.int(counts.working)} subagent${counts.working === 1 ? '' : 's'} working` : '');
3101
+
3102
+ fill('tiles',
3103
+ tile('Frontier',
3104
+ fmt.sig(frontier.value), `${snapshot.objective.name}${unit}`
3105
+ + (missing(frontier.id) ? '' : ` · iteration ${tag(frontier.id)}`),
3106
+ 'pink'),
3107
+ tile('Gain over baseline',
3108
+ missing(frontier.total_gain) ? '–' : fmt.signed(frontier.total_gain, 4),
3109
+ `${snapshot.objective.name}${unit} · ${fmt.signedPct(frontier.total_percent)}`,
3110
+ improved ? 'good' : null),
3111
+ tile('Rounds', fmt.int(counts.rounds), `summarized · on round ${counts.round}`),
3112
+ tile('Frontier steps', fmt.int(frontier.steps),
3113
+ `iterations · ${fmt.int(snapshot.stats.n_gate_failed)} gate-failed`),
3114
+ tile('Runs per iteration', plan.staged
3115
+ ? `${plan.runs_per_iteration}→${plan.confirm_runs}`
3116
+ : String(plan.runs_per_iteration), plan.staged
3117
+ ? 'seeds · staged: screen, then confirm' : 'seeds · fixed'),
3118
+ tile('GPUs in use', `${gpus.filter((g) => g.mine).length} / ${gpus.length}`,
3119
+ 'this search / on the machine'));
3120
+
3121
+ $('objective-note').textContent = `${snapshot.objective.name}, `
3122
+ + `${snapshot.objective.direction === 'max' ? 'higher' : 'lower'} is better. `
3123
+ + (snapshot.task || '') + ' Lasso or box-select in any chart to select the '
3124
+ + 'same iterations everywhere; double-click or Clear selection to drop it.';
3125
+
3126
+ renderCategoryBar();
3127
+ markRowStarts('tiles');
3128
+ }
3129
+
3130
+ /* Tiles may wrap. A tile that opens a row (it sits on a different row from
3131
+ the tile or hero before it) is marked `data-row-start`, and the CSS drops
3132
+ its divider but keeps its indent, so its text stays in the column of the
3133
+ tile above. Re-run on every render and on resize. */
3134
+ function markRowStarts(holderId) {
3135
+ const holder = $(holderId);
3136
+ if (!holder) return;
3137
+
3138
+ let prev = holder.previousElementSibling;
3139
+ for (const item of holder.children) {
3140
+ const top = Math.round(item.getBoundingClientRect().top);
3141
+ const start = !prev || Math.round(prev.getBoundingClientRect().top) !== top;
3142
+ if (start) item.dataset.rowStart = 'true';
3143
+ else delete item.dataset.rowStart;
3144
+ prev = item;
3145
+ }
3146
+ }
3147
+
3148
+ /* Every category autoopt.py allows, empty ones included, the catch-all last. */
3149
+ function renderCategoryBar() {
3150
+ const snapshot = state.snapshot;
3151
+ const counts = snapshot.counts.by_category || {};
3152
+ const ordered = {};
3153
+
3154
+ for (const category of [...(snapshot.categories || Object.keys(counts))].sort(
3155
+ categoryOrder))
3156
+ ordered[category] = counts[category] || 0;
3157
+
3158
+ // Clicking a chip emphasises its category in every chart, the log and
3159
+ // the tree; its dot hides the category.
3160
+ categoryChips('catbar', ordered, (c) => css(catSlot(c)), state.hidden,
3161
+ state.emphasised, () => {
3162
+ renderCategoryBar();
3163
+ renderCharts();
3164
+ renderTree();
3165
+ });
3166
+ }
3167
+
3168
+ /* ==== SECTION: sidebar-autoopt ==== */
3169
+
3170
+ /* What each step of the frontier bought: a bar apiece at true proportion,
3171
+ coloured by the kind of idea that made it. */
3172
+ function gainCard(steps) {
3173
+ const biggest = Math.max(...steps.map((s) => Math.abs(s.gain)), 1e-12);
3174
+ const digits = columnDigits(steps.map((s) => s.gain));
3175
+
3176
+ return el('div', { class: 'stat-card' }, [
3177
+ el('h3', { text: 'Gain per step' }),
3178
+ el('div', { class: 'bar-list gain-list' }, steps.map((step) =>
3179
+ el('div', { class: 'bar-row' }, [
3180
+ el('span', { class: 'key', text: tag(step.id), title: step.title || '' }),
3181
+ el('span', { class: 'bar', style: `width:${100 * Math.abs(step.gain)
3182
+ / biggest}%;min-width:1px;background:${css(catSlot(step.category))}` }),
3183
+ el('span', { class: 'n', text: fmt.signed(step.gain, digits) })]))),
3184
+ el('div', { class: 'stat-note', text: 'Each bar is the change in '
3185
+ + `${state.snapshot.objective.name} over the step before it, coloured by `
3186
+ + 'the kind of idea that made it.' }),
3187
+ ]);
3188
+ }
3189
+
3190
+ function renderSidebar() {
3191
+ const snapshot = state.snapshot;
3192
+ if (!snapshot) return;
3193
+
3194
+ const stats = snapshot.stats;
3195
+ const counts = snapshot.counts;
3196
+ const frontier = scopedFrontier();
3197
+ const hours = (x) => missing(x) ? '–' : fmt.sig(x) + ' h';
3198
+ const steps = (snapshot.frontier.steps || []).filter((step) => step.gain);
3199
+ const perCategory = Object.entries(stats.per_category || {})
3200
+ .sort((a, b) => b[1].n - a[1].n);
3201
+ const onFrontier = perCategory.filter(([, e]) => e.frontier)
3202
+ .map(([c, e]) => `${SHORT[c] || c} ${e.frontier}`).join(', ');
3203
+
3204
+ fill('sidebar',
3205
+ statCard('Search', [
3206
+ ['root', tag(snapshot.state.root)],
3207
+ ['round', String(counts.round ?? '–')],
3208
+ ['iterations', fmt.int(counts.iterations)],
3209
+ ['in flight', fmt.int(counts.running), counts.running ? 'warn' : null],
3210
+ ['subagents working', fmt.int(counts.working || 0), counts.working ? 'warn' : null],
3211
+ ['runs', fmt.int(counts.runs)],
3212
+ ]),
3213
+ statCard('Frontier', [
3214
+ [snapshot.objective.name, fmt.sig(frontier.value), 'pink'],
3215
+ ['baseline', fmt.sig(frontier.baseline)],
3216
+ ['total gain', fmt.signed(frontier.total_gain, 4)],
3217
+ ['relative', fmt.signedPct(frontier.total_percent)],
3218
+ ['steps', fmt.int(frontier.steps)],
3219
+ ], missing(frontier.id) ? null : `Held by iteration ${tag(frontier.id)}.`),
3220
+ steps.length ? gainCard(steps) : null,
3221
+ statCard('Throughput', [
3222
+ ['iterations/hour', fmt.sig(stats.iterations_per_hour)],
3223
+ ['runs/hour', fmt.sig(stats.runs_per_hour)],
3224
+ ['seconds/run', fmt.sig(stats.seconds_per_run)],
3225
+ ['median iteration', missing(stats.median_iteration_minutes) ? '–'
3226
+ : fmt.sig(stats.median_iteration_minutes) + ' min'],
3227
+ ['compute', hours(stats.compute_hours)],
3228
+ ['wall clock', hours(stats.wall_hours)],
3229
+ stats.runs_saved == null ? null
3230
+ : ['runs saved', fmt.int(stats.runs_saved), 'good'],
3231
+ ], stats.runs_saved == null ? null : 'Runs saved is what the staged '
3232
+ + 'evaluation did not spend: iterations that stopped at the '
3233
+ + 'screening depth.'),
3234
+ statCard('Outcomes', [
3235
+ ['passing', fmt.int(stats.n_ok), 'good'],
3236
+ ['gate-failed', fmt.int(stats.n_gate_failed), stats.n_gate_failed ? 'bad' : null],
3237
+ ['errored', fmt.int(stats.n_error), stats.n_error ? 'warn' : null],
3238
+ // Only a row when it happened: an under-depth iteration is a smoke
3239
+ // test or an interruption, not an outcome of the search.
3240
+ stats.n_partial ? ['under depth', fmt.int(stats.n_partial), 'warn'] : null,
3241
+ ['pass rate', missing(stats.gate_pass_rate) ? '–'
3242
+ : fmt.pct(100 * stats.gate_pass_rate)],
3243
+ ], 'Pass rate is passing over every settled iteration except those '
3244
+ + 'under depth.'),
3245
+ validationCard(),
3246
+ perCategory.length ? barCard('By category', perCategory.map(([c, e]) =>
3247
+ [c, e.n]), (c) => css(catSlot(c)), 'Settled iterations per category.'
3248
+ + (onFrontier ? ` On the frontier: ${onFrontier}.` : '')) : null,
3249
+ (stats.rounds || []).length ? statCard('Summaries', stats.rounds.map((entry) =>
3250
+ ['round ' + entry.round, entry.path.split('/').pop()])) : null);
3251
+ }
3252
+
3253
+ function renderCharts() {
3254
+ renderMain();
3255
+ renderObservers();
3256
+ renderValidation();
3257
+ renderRunTable(false);
3258
+ renderIterationLog();
3259
+ }
3260
+
3261
+ function renderAll() {
3262
+ renderSummary();
3263
+ renderCharts();
3264
+ renderDiff();
3265
+ renderTree();
3266
+ renderSidebar();
3267
+ }
3268
+ /* ==== SECTION: polling ==== */
3269
+
3270
+ let lastUpdate = 0; // browser time state.json last changed
3271
+ let lastSeen = {}; // the stamps it changed from
3272
+ let WRITER_LOG = null;
3273
+ let SNAPSHOT = null; // set for a static export: no polling, no pulse
3274
+
3275
+ /* Freshness, not fetch success: a dead writer leaves its files readable, so
3276
+ the page must notice that they stopped changing. */
3277
+ function noteChange(kind, stamp) {
3278
+ if (stamp !== undefined && stamp !== lastSeen[kind]) {
3279
+ lastSeen[kind] = stamp;
3280
+ lastUpdate = Date.now();
3281
+ }
3282
+ }
3283
+
3284
+ async function pollState() {
3285
+ try {
3286
+ const snapshot = await TRANSPORT.state();
3287
+ state.snapshot = snapshot;
3288
+ noteChange('state', snapshot.generated);
3289
+
3290
+ state.assetsStale = Boolean(LOADED_ASSETS && snapshot.assets
3291
+ && String(snapshot.assets) !== String(LOADED_ASSETS));
3292
+
3293
+ renderAll();
3294
+
3295
+ $('footer').textContent = `Scanned ${snapshot.root} · monitor up `
3296
+ + `${fmt.duration(snapshot.uptime)} · full scan every `
3297
+ + `${fmt.duration(cadence('state') / 1000)}, hardware every `
3298
+ + `${fmt.duration(cadence('resource') / 1000)}.`;
3299
+ } catch (error) {
3300
+ console.warn('state poll failed', error);
3301
+ }
3302
+
3303
+ updatePulse();
3304
+ }
3305
+
3306
+ /* The Live toggle. While it is on, and the tab is showing, the page touches
3307
+ the publisher's live file every LIVE_BEAT and polls every LIVE_INTERVAL;
3308
+ the publisher samples every second for as long as the file is fresh and
3309
+ returns to its own clock when it stops. Nothing is sampled for a hidden
3310
+ or closed tab. */
3311
+ const LIVE_INTERVAL = 1000;
3312
+ const LIVE_BEAT = 3000;
3313
+ let liveTimers = [];
3314
+ let polling = false;
3315
+
3316
+ function setLive(on) {
3317
+ state.live = on;
3318
+ liveTimers.forEach((timer) => {
3319
+ clearInterval(timer);
3320
+ const at = timers.indexOf(timer);
3321
+ if (at >= 0) timers.splice(at, 1);
3322
+ });
3323
+ liveTimers = [];
3324
+
3325
+ if (on) {
3326
+ const beat = () => {
3327
+ if (document.hidden) return;
3328
+ TRANSPORT.live().catch((error) => {
3329
+ console.warn('live request failed', error);
3330
+ state.liveError = String(error.message || error);
3331
+ $('toggle-live').setAttribute('aria-pressed', 'false');
3332
+ setLive(false);
3333
+ });
3334
+ };
3335
+
3336
+ state.liveError = null;
3337
+ beat();
3338
+ liveTimers = [setInterval(beat, LIVE_BEAT),
3339
+ setInterval(() => { if (!document.hidden) pollResources(); },
3340
+ LIVE_INTERVAL)];
3341
+ timers.push(...liveTimers);
3342
+ }
3343
+
3344
+ updateLiveButton();
3345
+ }
3346
+
3347
+ /* Says what the publisher did with the request: its resources.json carries
3348
+ `writer.live`. A publisher that never confirms is running outdated code. */
3349
+ function updateLiveButton() {
3350
+ const button = $('toggle-live');
3351
+ if (!button) return;
3352
+
3353
+ button.hidden = !(TRANSPORT && TRANSPORT.live && !SNAPSHOT);
3354
+ const confirmed = (((state.resources || {}).writer) || {}).live === true;
3355
+
3356
+ // The label says what the publisher is doing: with idle GPUs the cards
3357
+ // look the same at one second as at three, so a colour change alone
3358
+ // would not show the toggle took effect.
3359
+ button.textContent = state.liveError ? 'Live unavailable'
3360
+ : !state.live ? 'Live'
3361
+ : confirmed ? 'Live · 1 s' : 'Live · waiting';
3362
+ button.title = state.liveError
3363
+ ? `Live is unavailable: ${state.liveError}`
3364
+ : !state.live ? 'Sample the GPUs every second while this tab is open'
3365
+ : confirmed ? 'The publisher is sampling every second'
3366
+ : 'Asked the publisher for live samples; waiting for it to answer';
3367
+ }
3368
+
3369
+ async function pollResources() {
3370
+ if (polling) return;
3371
+ polling = true;
3372
+
3373
+ try {
3374
+ state.resources = await TRANSPORT.resources();
3375
+ renderResources(state.resources);
3376
+ updateLiveButton();
3377
+ if (state.snapshot) renderSummary();
3378
+ } catch (error) {
3379
+ console.warn('resource poll failed', error);
3380
+ }
3381
+
3382
+ polling = false;
3383
+ updatePulse();
3384
+ }
3385
+
3386
+ /* The gap the writer actually keeps between scans ('state') or hardware
3387
+ samples ('resource'), in ms, from what it publishes about itself in
3388
+ resources.json; never shorter than the configured clock. A scan or an
3389
+ nvidia-smi call slower than its interval is a slow publisher, not a
3390
+ stopped one. */
3391
+ function cadence(kind) {
3392
+ const writer = (state.resources || {}).writer || {};
3393
+ const measured = 1000 * (Number(writer[kind + '_cadence']) || 0);
3394
+ return Math.max(kind === 'state' ? STATE_INTERVAL : RESOURCE_INTERVAL,
3395
+ measured);
3396
+ }
3397
+
3398
+ /* Freshness is state.json's age against the writer's scan cadence: live
3399
+ while it changed within 2.5 scans, stale up to 10, down beyond, and down
3400
+ says the publisher stopped and where its log is. resources.json is left
3401
+ out because it comes from its own thread and keeps ticking while every
3402
+ scan fails. A failing scan, which the writer reports in resources.json,
3403
+ is named, as is any iteration the scan could not read. A page older
3404
+ than the published front end says so instead, because no amount of
3405
+ polling replaces a script the browser already has. */
3406
+ function updatePulse() {
3407
+ const pulse = $('pulse');
3408
+ const updated = $('updated');
3409
+
3410
+ if (SNAPSHOT) {
3411
+ pulse.hidden = true;
3412
+ updated.textContent = 'snapshot of ' + new Date(SNAPSHOT * 1000)
3413
+ .toLocaleString();
3414
+ return;
3415
+ }
3416
+
3417
+ if (state.assetsStale) {
3418
+ pulse.dataset.state = 'stale';
3419
+ updated.replaceChildren(el('b', { text: 'the dashboard has been '
3420
+ + 'updated — re-run the cell' }));
3421
+ return;
3422
+ }
3423
+
3424
+ if (!lastUpdate) {
3425
+ updated.textContent = 'connecting…';
3426
+ return;
3427
+ }
3428
+
3429
+ const every = cadence('state');
3430
+ const age = Date.now() - lastUpdate;
3431
+ const failing = ((state.resources || {}).writer || {}).scan_error;
3432
+ const unreadable = (state.snapshot || {}).unreadable || [];
3433
+ const log = WRITER_LOG ? ` · see ${WRITER_LOG}` : '';
3434
+
3435
+ pulse.dataset.state = age < 2.5 * every && !failing ? 'live'
3436
+ : age < 10 * every ? 'stale' : 'down';
3437
+
3438
+ if (failing)
3439
+ updated.replaceChildren(el('b', { text: 'scan failing' }),
3440
+ ` · ${failing} · last good scan ${fmt.duration(age / 1000)} ago${log}`);
3441
+ else if (pulse.dataset.state === 'down')
3442
+ updated.replaceChildren(el('b', { text: 'publisher stopped' }), log);
3443
+ else
3444
+ updated.textContent = `updated ${fmt.duration(age / 1000)} ago`;
3445
+
3446
+ if (unreadable.length) {
3447
+ updated.append(` · ${unreadable.length} unreadable: `
3448
+ + unreadable.slice(0, 5).map((entry) => tag(entry.id)).join(', ')
3449
+ + (unreadable.length > 5 ? ' …' : ''));
3450
+ updated.title = unreadable.map((entry) => `${tag(entry.id)}: `
3451
+ + entry.error).join('\n');
3452
+ } else {
3453
+ updated.removeAttribute('title');
3454
+ }
3455
+ }
3456
+
3457
+ /* Drag the handle under the search tree to give it more height; double-click
3458
+ for the default. The height lives in --tree-height on the section, which
3459
+ the re-rendered tree reads, so it survives every refresh. */
3460
+ const TREE_MIN = 160, TREE_DEFAULT = 430;
3461
+
3462
+ function treeResize() {
3463
+ const handle = $('tree-resize');
3464
+ const section = $('section-tree');
3465
+ const current = () => {
3466
+ const holder = ROOT.querySelector('#tree-holder .lineage-holder');
3467
+ return holder ? holder.getBoundingClientRect().height : TREE_DEFAULT;
3468
+ };
3469
+
3470
+ handle.addEventListener('pointerdown', (event) => {
3471
+ event.preventDefault();
3472
+ handle.setPointerCapture(event.pointerId);
3473
+ handle.dataset.dragging = 'true';
3474
+ const startY = event.clientY;
3475
+ const startHeight = Math.max(current(),
3476
+ parseFloat(section.style.getPropertyValue('--tree-height')) || TREE_DEFAULT);
3477
+ const move = (e) => {
3478
+ const height = Math.max(TREE_MIN, Math.round(startHeight + e.clientY - startY));
3479
+ section.style.setProperty('--tree-height', height + 'px');
3480
+ };
3481
+ const up = () => {
3482
+ delete handle.dataset.dragging;
3483
+ handle.removeEventListener('pointermove', move);
3484
+ handle.removeEventListener('pointerup', up);
3485
+ handle.removeEventListener('pointercancel', up);
3486
+ };
3487
+ handle.addEventListener('pointermove', move);
3488
+ handle.addEventListener('pointerup', up);
3489
+ handle.addEventListener('pointercancel', up);
3490
+ });
3491
+
3492
+ handle.addEventListener('dblclick', () => section.style.removeProperty('--tree-height'));
3493
+ }
3494
+
3495
+ /* Every id the render functions need. A notebook saved with its output and
3496
+ reopened without re-running restores markup from an earlier script version
3497
+ under the current script; this names what is missing instead of rendering
3498
+ half a page. */
3499
+ const REQUIRED_IDS = ['pulse', 'updated', 'run-root', 'hero-value', 'hero-sub',
3500
+ 'tiles', 'sidebar', 'footer', 'clear-selection', 'tip',
3501
+ 'catbar', 'objective-note', 'toggle-runs', 'toggle-failed', 'toggle-stair',
3502
+ 'toggle-stages', 'toggle-ci',
3503
+ 'main-headline', 'main-chart', 'scales-main', 'main-legend',
3504
+ 'diff-card', 'diff-title', 'diff-summary', 'diff-files', 'diff-close',
3505
+ 'section-observers', 'observer-charts', 'section-validation',
3506
+ 'validation-note', 'validation-charts', 'ended-line',
3507
+ 'stage-strip', 'tree-holder',
3508
+ 'tree-note', 'tree-legend', 'tree-resize', 'log', 'run-table', 'run-note',
3509
+ 'host-summary', 'toggle-live', 'gpu-cards', 'gpu-scroll', 'process-card', 'process-body',
3510
+ 'process-note'];
3511
+
3512
+ function reportStaleMarkup(missingIds) {
3513
+ const banner = el('div', { class: 'empty', id: 'stale-markup',
3514
+ style: 'border-color:var(--bad);color:var(--text);margin:var(--space-3)' }, [
3515
+ el('strong', { text: 'This page is older than the dashboard code it '
3516
+ + 'just loaded.' }),
3517
+ el('div', { style: 'margin-top:var(--space-2)', text: `Missing: `
3518
+ + `${missingIds.join(', ')}. This is saved notebook output being `
3519
+ + 'restored instead of rebuilt; re-run the cell.' })]);
3520
+
3521
+ ROOT.prepend(banner);
3522
+ console.error('stale markup; missing: ' + missingIds.join(', '));
3523
+ }
3524
+
3525
+ /* A ghost toggle: flips aria-pressed and reports the new value. */
3526
+ function toggle(id, onChange) {
3527
+ const node = $(id);
3528
+
3529
+ node.addEventListener('click', () => {
3530
+ const on = node.getAttribute('aria-pressed') !== 'true';
3531
+ node.setAttribute('aria-pressed', String(on));
3532
+ onChange(on);
3533
+ });
3534
+ }
3535
+
3536
+ function init() {
3537
+ const absent = REQUIRED_IDS.filter((id) => !$(id));
3538
+
3539
+ // Rendering into half the markup would draw half a page under a banner
3540
+ // nobody reads; the banner alone says what to do.
3541
+ if (absent.length) {
3542
+ reportStaleMarkup(absent);
3543
+ return;
3544
+ }
3545
+
3546
+ $('clear-selection').addEventListener('click', () => setSelection(null));
3547
+ $('diff-close').addEventListener('click', () => { state.diffOpen = null; renderDiff(); });
3548
+ toggle('toggle-live', setLive);
3549
+ setLive(false);
3550
+ toggle('toggle-runs', (on) => { state.showRuns = on; renderMain(); });
3551
+ toggle('toggle-failed', (on) => { state.hideFailed = !on; renderCharts(); });
3552
+ toggle('toggle-stair', (on) => { state.showStair = on; renderMain(); });
3553
+ toggle('toggle-stages', (on) => { state.showStages = on; renderMain(); });
3554
+ toggle('toggle-ci', (on) => { state.showCI = on; renderMain(); });
3555
+ treeResize();
3556
+
3557
+ window.addEventListener('resize', () => { resizePlots(); markRowStarts('tiles'); });
3558
+ setTimeout(resizePlots, 350);
3559
+
3560
+ pollState();
3561
+ pollResources();
3562
+
3563
+ if (SNAPSHOT) {
3564
+ updatePulse();
3565
+ return;
3566
+ }
3567
+
3568
+ // Two clocks, skipped while the tab is hidden.
3569
+ timers.push(setInterval(() => { if (!document.hidden) pollState(); },
3570
+ STATE_INTERVAL));
3571
+ timers.push(setInterval(() => { if (!document.hidden) pollResources(); },
3572
+ RESOURCE_INTERVAL));
3573
+ timers.push(setInterval(updatePulse, 2000));
3574
+ }
3575
+
3576
+ /* Mount into `root`, reading through `transport`. Each copy of the script is
3577
+ a separate module instance with its own timers, so the earlier instance's
3578
+ are stopped first; without this a re-run cell leaves two copies polling. */
3579
+ window.startAutoopt = function (root, transport, options) {
3580
+ options = options || {};
3581
+
3582
+ if (window.__autooptStop) window.__autooptStop();
3583
+ window.__autooptStop = () => { while (timers.length) clearInterval(timers.pop()); };
3584
+
3585
+ ROOT = root;
3586
+ TRANSPORT = transport;
3587
+ plotted.clear();
3588
+
3589
+ if (options.stateInterval) STATE_INTERVAL = options.stateInterval;
3590
+ if (options.resourceInterval) RESOURCE_INTERVAL = options.resourceInterval;
3591
+ WRITER_LOG = options.writerLog || null;
3592
+ SNAPSHOT = options.snapshot || null;
3593
+ lastUpdate = 0;
3594
+ lastSeen = {};
3595
+
3596
+ // The quickest way to tell a rendering problem from a data problem.
3597
+ window.autooptDashboard = { state, setSelection, renderAll, renderMain,
3598
+ renderTree, reorder, xOf, draw, markRowStarts, colour: { resolved, emphasis,
3599
+ verdictColour, groupSlot, contextMarker, markerKey, CATCH_ALL, CAT_SLOTS,
3600
+ LINE_SLOTS } };
3601
+
3602
+ init();
3603
+ };
3604
+
3605
+ /* A static export (`autoopt_monitor.py --export`) carries every payload in
3606
+ one JSON script element and needs no server: read-only, no polling. */
3607
+ const embedded = document.getElementById('autoopt-snapshot');
3608
+
3609
+ if (embedded) {
3610
+ const data = JSON.parse(embedded.textContent);
3611
+ const read = async (name) => {
3612
+ if (!(name in data.files)) throw new Error(name + ': not in this export');
3613
+ return data.files[name];
3614
+ };
3615
+
3616
+ window.startAutoopt(document.body, {
3617
+ readme: (id) => read('readmes/' + id + '.json'),
3618
+ diff: (id) => read('diffs/' + id + '.json'),
3619
+ state: () => read('state.json'),
3620
+ resources: () => read('resources.json'),
3621
+ }, { snapshot: data.generated });
3622
+
3623
+ /* Standalone (tests): the directory serving this file serves the JSON. Module
3624
+ scripts are deferred and `document.currentScript` is null inside them, so
3625
+ the marker lives on <body>. `data-state-interval` and
3626
+ `data-resource-interval` on <body> shorten the clocks for a test. */
3627
+ } else if (document.body && document.body.dataset.standalone !== undefined) {
3628
+ const json = async (name) => {
3629
+ const response = await fetch(name + '?_=' + Date.now());
3630
+ if (!response.ok) throw new Error(name + ': ' + response.status);
3631
+ return response.json();
3632
+ };
3633
+
3634
+ const intervals = document.body.dataset;
3635
+ const start = () => window.startAutoopt(document.body, {
3636
+ state: () => json('state.json'),
3637
+ readme: (id) => json('readmes/' + id + '.json'),
3638
+ diff: (id) => json('diffs/' + id + '.json'),
3639
+ resources: () => json('resources.json'),
3640
+ live: async () => {
3641
+ const response = await fetch('live.json', { method: 'PUT',
3642
+ body: '{}' });
3643
+ if (!response.ok) throw new Error('live.json: ' + response.status);
3644
+ },
3645
+ }, { stateInterval: Number(intervals.stateInterval) || 0,
3646
+ resourceInterval: Number(intervals.resourceInterval) || 0 });
3647
+
3648
+ if (document.readyState === 'loading')
3649
+ document.addEventListener('DOMContentLoaded', start);
3650
+ else
3651
+ start();
3652
+ }