@babylonjs-toolkit/agent 1.1.68 → 1.1.76

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.
@@ -6,22 +6,27 @@
6
6
  * Every write reads `data/progress.js`, parses its strict JSON, changes it and writes it back atomically (a temp file
7
7
  * renamed over the original), so the page never loads a half-written file.
8
8
  *
9
- * node progress.mjs start <slug-folder> [--title "…"] [--brief "…"] [--project <path>] [--url <url>] [--mode fix|analyze]
9
+ * node progress.mjs start <slug-folder> [--title "…"] [--brief "…"] [--project <path>] [--url <url>] [--mode report|auto-fix] [--open true]
10
+ * node progress.mjs set <slug-folder> [--url <url>] [--title "…"] [--brief "…"] [--project <path>] details found after start
10
11
  * node progress.mjs stage <slug-folder> <preflight|baseline|diagnose|fix|verify|report> [--status active|done|skipped] [--note "…"]
11
12
  * node progress.mjs now <slug-folder> "<what is happening this minute>" [--step "<log line, if different>"]
12
13
  * node progress.mjs fix <slug-folder> <F1> [--title "…"] [--status planned|trying|measuring|kept|reverted|skipped] [--before "…"] [--after "…"] [--note "…"]
13
14
  * node progress.mjs metric <slug-folder> "<label>" "<value>" [--note "…"]
14
15
  * node progress.mjs note <slug-folder> "<milestone>"
15
16
  * node progress.mjs end <slug-folder> [--status done|stopped|failed] [--summary "…"]
17
+ * node progress.mjs stop <slug-folder> [--reason "…"] ends a running capture (and its Chrome) and marks the run stopped
18
+ * node progress.mjs resume <slug-folder> reopens a stopped run where it stopped; prints where to continue (JSON)
19
+ * node progress.mjs restart <slug-folder> [--title "…"] [--brief "…"] archives the runs, findings and report, then starts over
16
20
  * node progress.mjs check <slug-folder>
17
21
  * node progress.mjs watch <slug-folder> [--watch <folder>]… [--interval-seconds 60] [--quiet-minutes 5] [--stall-minutes 30] [--max-hours 12]
18
22
  *
19
23
  * <slug-folder> is .agents/profile/<slug> (it holds dashboard.html and data/). Timestamps are this machine's local time.
20
24
  */
21
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
25
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
22
26
  import { basename, dirname, join, relative } from "node:path";
27
+ import { spawn } from "node:child_process";
23
28
 
24
- import { PROGRESS_MARKER, livePage } from "./lib/progress-panel.mjs";
29
+ import { PROGRESS_MARKER, livePage, withProgressPanel } from "./lib/progress-panel.mjs";
25
30
 
26
31
  const PREFIX = "window.PROFILE_PROGRESS";
27
32
  /** The stages every profile run goes through, in order. */
@@ -121,15 +126,21 @@ function setNow(progress, activity, step, source = "agent") {
121
126
  /** Starts a run: a fresh progress file, and a live dashboard when the slug has none that carries the panel. */
122
127
  function start(folder, argumentList) {
123
128
  const { options } = parseOptions(argumentList);
124
- const mode = options.mode === "analyze" ? "analyze" : "fix";
129
+ // Fixing is opt-in (--auto-fix): without it the run measures, diagnoses and lists the fixes, and changes no code.
130
+ const mode = (options.mode === "auto-fix" || options.mode === "fix") ? "auto-fix" : "report";
125
131
  const stamp = localTime().stamp;
126
132
  const stages = STAGES.map((stage) => ({ ...stage, status: "pending", started: "", finished: "", note: "" }));
127
133
  stages[0].status = "active";
128
134
  stages[0].started = localTime().clock;
129
- if (mode === "analyze") Object.assign(stages.find((stage) => stage.id === "fix"), { status: "skipped", note: "--analyze: no code changes" });
135
+ if (mode === "report") {
136
+ Object.assign(stages.find((stage) => stage.id === "fix"), { status: "skipped", note: "fixes listed, not applied (add --auto-fix to apply them)" });
137
+ Object.assign(stages.find((stage) => stage.id === "verify"), { status: "skipped", note: "no code changed, nothing to verify" });
138
+ }
130
139
  const progress = {
131
140
  schema: 1,
132
141
  status: "running",
142
+ slug: basename(folder),
143
+ run: Number(options.run || 1),
133
144
  title: String(options.title || `${basename(folder)} profile`),
134
145
  brief: String(options.brief || ""),
135
146
  project: String(options.project || ""),
@@ -150,12 +161,38 @@ function start(folder, argumentList) {
150
161
  const dashboard = join(folder, "dashboard.html");
151
162
  const current = existsSync(dashboard) ? readFileSync(dashboard, "utf8") : "";
152
163
  if (!current.includes(PROGRESS_MARKER)) {
153
- // A report from before the panel existed is kept beside the data, not lost while the run replaces it.
164
+ // Never replace a report: one from before the panel existed keeps every chart, table and finding, with the live
165
+ // panel added on top (a copy stays in data/previous-dashboard.html). Only a slug with no report gets the bare live page.
166
+ const upgraded = current ? withProgressPanel(current) : null;
154
167
  if (current) writeFileSync(join(folder, "data", "previous-dashboard.html"), current);
155
- writeFileSync(dashboard, livePage({ title: progress.title }));
156
- console.log(`wrote the live page ${dashboard}${current ? " (the previous report is in data/previous-dashboard.html)" : ""}`);
168
+ writeFileSync(dashboard, upgraded || livePage({ title: progress.title }));
169
+ console.log(upgraded ? `added the live panel to the existing report ${dashboard}` : `wrote the live page ${dashboard}${current ? " (the previous report is in data/previous-dashboard.html)" : ""}`);
157
170
  }
158
171
  console.log(`progress: started ${progress.title} (${mode})`);
172
+ // The user watches the run live, so the page opens with it (once — it reloads itself from then on).
173
+ if (options.open === "true" || options.open === true) openInBrowser(dashboard);
174
+ }
175
+
176
+ /** Opens a file in the default browser, without waiting for it. */
177
+ function openInBrowser(file) {
178
+ const opener = process.platform === "darwin" ? ["open", [file]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", file]] : ["xdg-open", [file]];
179
+ try {
180
+ spawn(opener[0], opener[1], { detached: true, stdio: "ignore" }).on("error", () => console.log(`open ${file} in a browser`)).unref();
181
+ } catch {
182
+ console.log(`open ${file} in a browser`);
183
+ }
184
+ }
185
+
186
+ /** Updates the run's details once they are known (the URL is often found after `start`, by reading the code). */
187
+ function set(folder, argumentList) {
188
+ const { options } = parseOptions(argumentList);
189
+ const progress = readProgress(folder);
190
+ const changed = [];
191
+ for (const field of ["title", "brief", "project", "url"]) {
192
+ if (options[field] !== undefined && options[field] !== true) { progress[field] = String(options[field]); changed.push(field); }
193
+ }
194
+ if (!changed.length) throw new Error("progress.mjs set <slug-folder> [--url …] [--title …] [--brief …] [--project …]");
195
+ writeProgress(folder, progress);
159
196
  }
160
197
 
161
198
  function stage(folder, argumentList) {
@@ -371,10 +408,104 @@ function heartbeat(folder, progress, roots, quietMinutes, stallMinutes) {
371
408
  console.log(`watchdog ${localTime(moment).clock}: ${activity}`);
372
409
  }
373
410
 
374
- const commands = { start, stage, now, fix, metric, note, end, check, watch };
411
+ /* ===================== Stop, resume, restart ===================== */
412
+
413
+ /** True while a process id is alive (signal 0 only checks). */
414
+ function isAlive(pid) {
415
+ try { process.kill(pid, 0); return true; } catch { return false; }
416
+ }
417
+
418
+ /**
419
+ * Ends the slug's running capture — the profile.mjs process and its Chrome, named by data/capture.lock.json — then
420
+ * marks the run stopped (the watchdog exits on its own once the run is no longer running). The agent rebuilds the
421
+ * report from what was captured; `resume` continues from the stage it stopped in.
422
+ */
423
+ function stop(folder, argumentList) {
424
+ const { options } = parseOptions(argumentList);
425
+ const lockPath = join(folder, "data", "capture.lock.json");
426
+ const ended = [];
427
+ if (existsSync(lockPath)) {
428
+ let lock = null;
429
+ try { lock = JSON.parse(readFileSync(lockPath, "utf8")); } catch { /* unreadable: nothing to end */ }
430
+ for (const [label, pid] of [["capture", lock && lock.pid], ["Chrome", lock && lock.browserPid]]) {
431
+ if (!pid || !isAlive(pid)) continue;
432
+ try { process.kill(pid, "SIGTERM"); ended.push(`${label} ${pid}`); } catch { /* already gone */ }
433
+ }
434
+ const deadline = Date.now() + 3000;
435
+ const pause = new Int32Array(new SharedArrayBuffer(4));
436
+ while (Date.now() < deadline && lock && [lock.pid, lock.browserPid].some((pid) => pid && isAlive(pid))) Atomics.wait(pause, 0, 0, 100); // let them exit
437
+ for (const pid of lock ? [lock.pid, lock.browserPid] : []) if (pid && isAlive(pid)) { try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } }
438
+ rmSync(lockPath, { force: true });
439
+ }
440
+ const progress = readProgress(folder);
441
+ const active = (progress.stages || []).find((candidate) => candidate.status === "active");
442
+ const reason = options.reason && options.reason !== true ? String(options.reason) : "Stopped by the user";
443
+ Object.assign(progress, { status: "stopped", finishedAt: localTime().stamp, stoppedStage: active ? active.id : "", summary: `${reason}${active ? ` during ${active.name}` : ""}.` });
444
+ setNow(progress, `Stopped${active ? ` during ${active.name}` : ""} — continue with /bt-profile --resume:${progress.slug || basename(folder)}`, "Run stopped");
445
+ addMilestone(progress, `Run ${progress.run || 1} stopped${active ? ` during ${active.name}` : ""}${ended.length ? ` (ended ${ended.join(", ")})` : ""}`);
446
+ writeProgress(folder, progress);
447
+ console.log(`stopped ${progress.slug || basename(folder)}${active ? ` during ${active.name}` : ""}${ended.length ? ` — ended ${ended.join(", ")}` : " — no capture was running"}`);
448
+ }
449
+
450
+ /**
451
+ * Reopens a stopped (or failed) run where it stopped, as the next run number, and prints where to continue as JSON:
452
+ * the stage to resume, the stages already done, and every fix with its status (re-measure one left trying / measuring).
453
+ */
454
+ function resume(folder) {
455
+ const progress = readProgress(folder);
456
+ if (progress.status === "running") throw new Error("the run is still running — stop it first, or just keep going");
457
+ if (progress.status === "done") throw new Error("the run finished — use restart to profile it again from a fresh baseline");
458
+ const stages = progress.stages || [];
459
+ const target = stages.find((candidate) => candidate.id === progress.stoppedStage) || stages.find((candidate) => candidate.status === "active") || stages.find((candidate) => candidate.status === "pending") || stages[stages.length - 1];
460
+ for (const candidate of stages) if (candidate.status === "active" && candidate !== target) candidate.status = "done";
461
+ Object.assign(target, { status: "active", note: target.note || "resumed" });
462
+ progress.run = Number(progress.run || 1) + 1;
463
+ Object.assign(progress, { status: "running", finishedAt: "", summary: "" });
464
+ delete progress.stoppedStage;
465
+ setNow(progress, `Run ${progress.run} — resuming ${target.name}`, `Run ${progress.run} resumed`);
466
+ addMilestone(progress, `Run ${progress.run} — resumed during ${target.name}`);
467
+ writeProgress(folder, progress);
468
+ console.log(JSON.stringify({
469
+ run: progress.run,
470
+ resumeStage: target.id,
471
+ doneStages: stages.filter((candidate) => candidate.status === "done").map((candidate) => candidate.id),
472
+ fixes: (progress.fixes || []).map((entry) => ({ id: entry.id, title: entry.title, status: entry.status })),
473
+ }, null, 2));
474
+ }
475
+
476
+ /**
477
+ * Starts the slug over from a fresh baseline with the same config and scenario: the earlier runs, findings and
478
+ * report move to data/archive/<date-time>/ (kept, so the new run can be compared with them), then a new run opens.
479
+ */
480
+ function restart(folder, argumentList) {
481
+ const { options } = parseOptions(argumentList);
482
+ let previous = null;
483
+ try { previous = readProgress(folder); } catch { /* no earlier run */ }
484
+ if (previous && previous.status === "running") throw new Error("the run is still running — stop it first");
485
+ const stamp = localTime().stamp.replace(/[^0-9]/g, "").slice(0, 12);
486
+ const archive = join(folder, "data", "archive", stamp);
487
+ mkdirSync(archive, { recursive: true });
488
+ for (const name of ["runs", "findings.json", "progress.js"]) {
489
+ const source = join(folder, "data", name);
490
+ if (existsSync(source)) renameSync(source, join(archive, name));
491
+ }
492
+ if (existsSync(join(folder, "dashboard.html"))) copyFileSync(join(folder, "dashboard.html"), join(archive, "dashboard.html"));
493
+ mkdirSync(join(folder, "data", "runs"), { recursive: true });
494
+ const carried = ["title", "brief", "project", "url", "mode"].flatMap((key) => {
495
+ const value = options[key] && options[key] !== true ? options[key] : (previous ? previous[key] : "");
496
+ return value ? [`--${key}`, String(value)] : [];
497
+ });
498
+ start(folder, [...carried, "--run", String(previous ? Number(previous.run || 1) + 1 : 1)]);
499
+ const progress = readProgress(folder);
500
+ addMilestone(progress, `Restarted from a fresh baseline — the earlier runs are in data/archive/${stamp}/`);
501
+ writeProgress(folder, progress);
502
+ console.log(`restarted ${basename(folder)} — earlier runs, findings and report archived in data/archive/${stamp}/`);
503
+ }
504
+
505
+ const commands = { start, set, stage, now, fix, metric, note, end, check, watch, stop, resume, restart };
375
506
 
376
507
  if (!commands[command] || !slugFolder) {
377
- console.error("usage: node progress.mjs <start|stage|now|fix|metric|note|end|check|watch> <slug-folder> [options] — see the header of this file");
508
+ console.error("usage: node progress.mjs <start|set|stage|now|fix|metric|note|end|stop|resume|restart|check|watch> <slug-folder> [options] — see the header of this file");
378
509
  process.exit(2);
379
510
  }
380
511
  try {
@@ -5,14 +5,17 @@
5
5
  * Usage (from `.agents/profile/<slug>/data`):
6
6
  * node ../../.tools/report.mjs --analysis runs/<run>/cold/analysis.json [--out ../dashboard.html]
7
7
  * [--baseline runs/<baseline>/cold/analysis.json] [--warm runs/<run>/warm/analysis.json]
8
- * [--findings ./findings.json] [--title "Race start"]
8
+ * [--findings ./findings.json] [--title "Race start"] [--pdf false]
9
9
  * [--snapshots runs/<snapshots run>/cold] [--snapshots-before <dir of earlier shots>]
10
10
  * `--snapshots` shows the screenshots of a separate `--snapshots true` capture (so the measured run stays free of
11
11
  * screenshot overhead); `--snapshots-before` sets them beside earlier shots of the same names (e.g. the smoke run).
12
12
  *
13
13
  * findings.json (written by the agent — the diagnosis in plain language):
14
14
  * { "title", "summary", "findings": [{ "id", "title", "severity": "critical|major|minor", "status": "fixed|proposed|reverted|not-fixed",
15
- * "phases": [..], "cost", "cause", "evidence": [..], "code": [{ "file", "line", "label" }], "fix", "before", "after", "diff" }] }
15
+ * "phases": [..], "cost", "cause", "evidence": [..], "code": [{ "file", "line", "label" }], "fix", "before", "after", "diff",
16
+ * "gain", "risk", "verify" }] } (gain / risk / verify: optional — the expected win, what could break, how to prove it)
17
+ * Every build also writes findings.md beside the dashboard: the same diagnosis as a spec-ready document (one section per
18
+ * finding — cause, evidence, code, proposed fix, gain, risk, how to verify) to fix later with a full spec (bt-spec).
16
19
  */
17
20
  import fs from "node:fs";
18
21
  import path from "node:path";
@@ -151,7 +154,9 @@ h3 { font-size: 15px; margin: 0 0 6px; }
151
154
  .meta { color: var(--text-muted); font: 12px/1.6 var(--mono); }
152
155
  .verdict.disturbed { border-left-color: var(--serious); }
153
156
  .verdict { background: var(--surface-1); border: 1px solid var(--surface-3); border-left: 3px solid var(--accent); border-radius: 8px; padding: 14px 16px; margin: 16px 0; color: var(--text-primary); font-size: 15px; }
154
- .tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
157
+ /* Balanced rows of equal tiles: renderTiles sets --tile-columns (8 tiles → 2 × 4, 6 → 2 × 3); two per row on a phone */
158
+ .tiles { display: grid; grid-template-columns: repeat(var(--tile-columns, 4), minmax(0, 1fr)); grid-auto-rows: 1fr; gap: 10px; }
159
+ @media (max-width: 720px) { .tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
155
160
  .tile { background: var(--surface-1); border: 1px solid var(--surface-3); border-radius: 8px; padding: 12px 14px; }
156
161
  .tile .label { color: var(--text-secondary); font-size: 12px; }
157
162
  .tile .value { font-size: 26px; font-weight: 600; margin-top: 2px; font-variant-numeric: tabular-nums; }
@@ -211,6 +216,30 @@ details { margin-top: 8px; } summary { cursor: pointer; color: var(--text-second
211
216
  .signals li { margin: 4px 0; color: var(--text-secondary); }
212
217
  .two { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(420px, 100%), 1fr)); gap: 12px; }
213
218
  @media (max-width: 520px) { .two { grid-template-columns: 1fr; } .tile .value { font-size: 22px; } }
219
+ footer.generated-by { margin-top: 64px; padding-top: 20px; border-top: 1px solid var(--surface-3); color: var(--text-muted); font-size: 12.5px; }
220
+ footer.generated-by a { color: inherit; }
221
+ table.fixes td.pick, table.fixes th.pick { width: 28px; } table.fixes td.id { font: 600 12px var(--mono); white-space: nowrap; }
222
+ table.fixes td.act { text-align: right; white-space: nowrap; }
223
+ table.fixes .badge { white-space: nowrap; }
224
+ td.nw { white-space: nowrap; }
225
+ .hint { color: var(--text-secondary); font-size: 13px; margin: 0 0 10px; }
226
+ .copy-spec { background: var(--surface-2); color: var(--text-secondary); border: 1px solid var(--surface-3); border-radius: 6px; font-size: 12px; padding: 4px 10px; cursor: pointer; }
227
+ .copy-spec:disabled { opacity: 0.5; cursor: default; }
228
+ .spec-bar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-top: 12px; }
229
+ .spec-bar code { flex: 1 1 320px; font: 12px var(--mono); background: var(--surface-0); border: 1px solid var(--surface-3); border-radius: 6px; padding: 6px 10px; overflow-wrap: anywhere; }
230
+ @media print { .pick, .act, .spec-bar, #fixes .hint { display: none !important; } }
231
+ .actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
232
+ a.toggle { text-decoration: none; display: inline-block; }
233
+ @media print {
234
+ :root, :root[data-theme] { color-scheme: light; --surface-0: #ffffff; --surface-1: #ffffff; --surface-2: #f4f4f2; --surface-3: #d9d8d3; --text-primary: #0b0b0b; --text-secondary: #3d3c39; --text-muted: #5f5e59; }
235
+ body { background: #ffffff !important; }
236
+ main { max-width: none !important; padding: 0 !important; }
237
+ .actions, .btp-toolbar, .btp-next, .btp-copy { display: none !important; }
238
+ .panel, .finding, .tile, .verdict, figure, tr, .btp-card { break-inside: avoid; page-break-inside: avoid; }
239
+ h2 { break-after: avoid; page-break-after: avoid; }
240
+ .panel { overflow: visible !important; }
241
+ a { color: inherit; text-decoration: none; }
242
+ }
214
243
  .toggle { background: var(--surface-2); color: var(--text-secondary); border: 1px solid var(--surface-3); border-radius: 6px; font-size: 12px; padding: 4px 10px; cursor: pointer; }
215
244
  `;
216
245
 
@@ -249,7 +278,7 @@ function settledPhase(analysis) {
249
278
 
250
279
  function renderTiles() {
251
280
  const settled = settledPhase(run), settledBase = base ? settledPhase(base) : null;
252
- const worstPhase = [...run.phases].filter((p) => p.frames.fps != null && p.durationSeconds >= 1).sort((a, b) => a.frames.fps - b.frames.fps)[0];
281
+ const worstPhase = [...run.phases].filter((p) => !p.beforeFirstFrame && p.frames.fps != null && p.durationSeconds >= 1).sort((a, b) => a.frames.fps - b.frames.fps)[0];
253
282
  const worstBase = base && worstPhase ? base.phases.find((p) => p.name === worstPhase.name) : null;
254
283
  const gc = (a) => (a.overall.lists.owners.find((o) => o.owner === "gc") || { pctBusy: 0 }).pctBusy;
255
284
  const shaders = (a) => a.timeline.reduce((sum, b) => sum + (b.shaders || 0), 0);
@@ -263,6 +292,8 @@ function renderTiles() {
263
292
  { label: "Allocated", value: run.heap ? fmt(run.heap.mbPerSecond, 0) + " MB/s" : "–", delta: base && base.heap && run.heap ? delta(run.heap.mbPerSecond, base.heap.mbPerSecond, true, " MB/s", 0) : "" },
264
293
  { label: "Shaders compiled in run", value: fmt(shaders(run), 0), delta: base ? delta(shaders(run), shaders(base), true, "", 0) : "" },
265
294
  ];
295
+ const rows = Math.ceil(tiles.length / 4);
296
+ $("#tiles").style.setProperty("--tile-columns", String(Math.max(1, Math.ceil(tiles.length / rows))));
266
297
  $("#tiles").innerHTML = tiles.map((t) => '<div class="tile"><div class="label">' + esc(t.label) + '</div><div class="value">' + t.value + '</div>' + (t.delta || "") + '</div>').join("");
267
298
  }
268
299
 
@@ -389,6 +420,45 @@ function renderTimeline() {
389
420
  } else $("#film-wrap").style.display = "none";
390
421
  }
391
422
 
423
+ /**
424
+ * The fixes, listed whether or not they were applied: spec one (its row's button) or a group (tick them) with bt-spec.
425
+ * The spec command points bt-spec at findings.md, which carries each fix's cause, evidence, code, gain, risk and check.
426
+ */
427
+ function renderFixes() {
428
+ const wrap = $("#fixes-wrap");
429
+ const list = (findings && findings.findings ? findings.findings : []).filter((f) => f.fix);
430
+ if (!list.length) { wrap.style.display = "none"; return; }
431
+ const source = "@.agents/profile/" + DATA.slug + "/findings.md";
432
+ const join = (ids) => ids.length <= 1 ? ids.join("") : ids.slice(0, -1).join(", ") + " and " + ids[ids.length - 1];
433
+ const command = (ids) => "/bt-spec Fix " + join(ids) + " from " + source;
434
+ // A fix is done once it is in the code: "kept" (applied and proven by the fix loop) or "fixed".
435
+ const isDone = (f) => f.status === "kept" || f.status === "fixed";
436
+ const open = list.filter((f) => !isDone(f)).map((f) => f.id);
437
+ const rows = list.map((f) => '<tr><td class="pick"><input type="checkbox" value="' + esc(f.id) + '"' + (!isDone(f) ? " checked" : "") + ' aria-label="Select ' + esc(f.id) + '"></td>' +
438
+ '<td class="id"><a href="#' + esc(f.id) + '">' + esc(f.id) + '</a></td><td>' + esc(f.title) + '</td>' +
439
+ '<td><span class="badge ' + esc(f.status) + '">' + esc(f.status) + '</span></td>' +
440
+ '<td>' + esc(f.gain || f.cost || "–") + '</td><td>' + esc(f.risk || "–") + '</td>' +
441
+ '<td class="act"><button type="button" class="copy-spec" data-ids="' + esc(f.id) + '">Copy spec command</button></td></tr>').join("");
442
+ $("#fixes").innerHTML = '<div class="panel"><p class="hint">Each fix can be specced on its own, or several together: tick them and copy one command for <code>/bt-spec</code>. ' +
443
+ (open.length ? open.length + " not fixed yet." : "All of them are fixed.") + '</p>' +
444
+ '<div class="scroll"><table class="fixes"><thead><tr><th class="pick"></th><th>ID</th><th>Fix</th><th>Status</th><th>Expected gain</th><th>Risk</th><th class="act"></th></tr></thead><tbody>' + rows + '</tbody></table></div>' +
445
+ '<div class="spec-bar"><code id="spec-selected"></code><button type="button" class="copy-spec" id="copy-selected">Copy for the selected</button>' +
446
+ (open.length ? '<button type="button" class="copy-spec" data-ids="' + esc(open.join(" ")) + '">Copy for all open fixes</button>' : "") + '</div></div>';
447
+ const selected = () => [...document.querySelectorAll("#fixes input[type=checkbox]:checked")].map((box) => box.value);
448
+ const refresh = () => { const ids = selected(); $("#spec-selected").textContent = ids.length ? command(ids) : "Tick the fixes to spec together"; $("#copy-selected").disabled = !ids.length; };
449
+ $("#fixes").addEventListener("change", refresh);
450
+ $("#fixes").addEventListener("click", (event) => {
451
+ const button = event.target.closest(".copy-spec");
452
+ if (!button) return;
453
+ const ids = button.id === "copy-selected" ? selected() : button.dataset.ids.split(" ");
454
+ if (!ids.length) return;
455
+ const text = command(ids);
456
+ const done = () => { const label = button.textContent; button.textContent = "Copied"; setTimeout(() => { button.textContent = label; }, 1500); };
457
+ if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(done, done); else done();
458
+ });
459
+ refresh();
460
+ }
461
+
392
462
  function renderFindings() {
393
463
  const box = $("#findings");
394
464
  if (!findings || !findings.findings || !findings.findings.length) {
@@ -455,7 +525,8 @@ function renderHeap() {
455
525
  }
456
526
 
457
527
  function renderWorst() {
458
- $("#worst").innerHTML = "<div class='scroll'><table><thead><tr><th class='num'>at</th><th>Phase</th><th class='num'>CPU ms</th><th class='num'>gap ms</th><th>Filled by</th><th>Your code in it</th></tr></thead><tbody>" + run.worstFrames.map((f) => "<tr><td class='num'>" + fmt(f.t) + "s</td><td>" + esc(f.phase || "") + "</td><td class='num'>" + fmt(f.cpuMs) + "</td><td class='num'>" + fmt(f.intervalMs) + "</td><td class='where'>" + esc(f.top.map((e) => e.name + " " + e.ms).join(" · ")) + "</td><td class='where'>" + (f.yours.map((e) => link(e.file, e.line, e.name + " " + e.ms + " ms")).join(" · ") || "–") + "</td></tr>").join("") + "</tbody></table></div>";
528
+ const kindLabel = { cpu: "CPU work", wait: "waited", gap: "gap" };
529
+ $("#worst").innerHTML = "<div class='scroll'><table><thead><tr><th class='num'>at</th><th>Phase</th><th>Kind</th><th class='num'>CPU ms</th><th class='num'>gap ms</th><th class='num'>script ms</th><th class='num'>new pipelines</th><th>Filled by</th><th>Your code in it</th></tr></thead><tbody>" + run.worstFrames.map((f) => "<tr><td class='num'>" + fmt(f.t) + "s</td><td class='nw'>" + esc(f.phase || "") + "</td><td class='nw'>" + esc(kindLabel[f.kind] || "–") + "</td><td class='num'>" + fmt(f.cpuMs) + "</td><td class='num'>" + fmt(f.intervalMs) + "</td><td class='num'>" + fmt(f.scriptMs) + "</td><td class='num'>" + fmt(f.pipelinesNear) + "</td><td class='where'>" + esc(f.top.map((e) => e.name + " " + e.ms).join(" · ")) + "</td><td class='where'>" + (f.yours.map((e) => link(e.file, e.line, e.name + " " + e.ms + " ms")).join(" · ") || "–") + "</td></tr>").join("") + "</tbody></table></div>";
459
530
  }
460
531
 
461
532
  function renderShots() {
@@ -486,17 +557,25 @@ function renderMeta() {
486
557
  ].map(([k, v]) => "<tr><th>" + esc(k) + "</th><td>" + (k === "CPU profile" ? v : esc(v)) + "</td></tr>").join("") + "</tbody></table>";
487
558
  }
488
559
 
560
+ // Print (and Save as PDF from the print dialog): every collapsed section opens for the print and closes again after.
561
+ let openedForPrint = [];
562
+ addEventListener("beforeprint", () => {
563
+ openedForPrint = [...document.querySelectorAll("details:not([open])")];
564
+ openedForPrint.forEach((details) => { details.open = true; });
565
+ });
566
+ addEventListener("afterprint", () => { openedForPrint.forEach((details) => { details.open = false; }); openedForPrint = []; });
567
+ $("#print").addEventListener("click", () => window.print());
489
568
  $("#theme").addEventListener("click", () => {
490
569
  const root = document.documentElement;
491
570
  const dark = root.dataset.theme ? root.dataset.theme === "dark" : !matchMedia("(prefers-color-scheme: light)").matches;
492
571
  root.dataset.theme = dark ? "light" : "dark";
493
572
  });
494
- renderTiles(); renderFindings(); renderTimeline(); renderPhases(); renderOwners(); renderFunctions(); renderHeap(); renderWorst(); renderShots(); renderWarm(); renderMeta();
573
+ renderTiles(); renderFindings(); renderFixes(); renderTimeline(); renderPhases(); renderOwners(); renderFunctions(); renderHeap(); renderWorst(); renderShots(); renderWarm(); renderMeta();
495
574
  let resizeTimer; addEventListener("resize", () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(renderTimeline, 150); });
496
575
  `;
497
576
 
498
577
  /** Builds the HTML page. */
499
- function buildPage({ title, verdict, data }) {
578
+ function buildPage({ title, verdict, data, pdfName }) {
500
579
  const json = JSON.stringify(data).replace(/</g, "\\u003c");
501
580
  return `<!doctype html>
502
581
  <html lang="en">
@@ -510,7 +589,11 @@ function buildPage({ title, verdict, data }) {
510
589
  <main>
511
590
  <header class="top">
512
591
  <h1>${escapeHtml(title)}</h1>
513
- <button class="toggle" id="theme" type="button">Light / dark</button>
592
+ <div class="actions">
593
+ <button class="toggle" id="print" type="button" title="Print the report, or choose Save as PDF in the print dialog">Print</button>
594
+ ${pdfName ? `<a class="toggle" id="pdf" href="${escapeHtml(pdfName)}" download title="The report as a PDF, written with it">Download PDF</a>` : ""}
595
+ <button class="toggle" id="theme" type="button">Light / dark</button>
596
+ </div>
514
597
  </header>
515
598
  ${progressMarkup()}
516
599
  <div class="meta">${escapeHtml(data.run.capture.capturedAt)} · ${escapeHtml(data.run.capture.engine || "")} · scenario ${escapeHtml(data.run.capture.scenario || "")} · ${escapeHtml(data.run.capture.wallSeconds)} s${data.baseline ? " · compared with baseline " + escapeHtml(data.baseline.capture.capturedAt) : ""}</div>
@@ -521,6 +604,8 @@ function buildPage({ title, verdict, data }) {
521
604
  <h2>The bottlenecks</h2>
522
605
  <section id="findings"></section>
523
606
 
607
+ <div id="fixes-wrap"><h2>The fixes</h2><section id="fixes"></section></div>
608
+
524
609
  <h2>Frame rate over the run</h2>
525
610
  <section class="panel"><div class="legend" id="fps-legend"></div><div id="chart-fps"></div></section>
526
611
 
@@ -548,6 +633,7 @@ function buildPage({ title, verdict, data }) {
548
633
  <section class="panel" id="heap"></section>
549
634
 
550
635
  <h2>Worst frames</h2>
636
+ <p class="meta">“CPU work”: the frame's own script was the cost. “Waited”: a long gap the main thread mostly sat through — the GPU process compiling pipelines (new pipelines just before it), a GPU-bound frame, or browser work.</p>
551
637
  <section class="panel" id="worst"></section>
552
638
 
553
639
  <div id="warm-wrap"><h2>Cold load vs warm load</h2><section class="panel" id="warm"></section></div>
@@ -555,6 +641,7 @@ function buildPage({ title, verdict, data }) {
555
641
 
556
642
  <h2>Capture</h2>
557
643
  <section class="panel" id="capture"></section>
644
+ <footer class="generated-by">Generated by the <a href="https://www.npmjs.com/package/@babylonjs-toolkit/agent" target="_blank" rel="noopener noreferrer">Babylon Toolkit Desktop Agent</a></footer>
558
645
  </main>
559
646
  <div class="tooltip" id="tooltip" role="status"></div>
560
647
  <script type="application/json" id="bt-data">${json}</script>
@@ -576,8 +663,105 @@ function shotsFrom(dir, reportDir) {
576
663
  }));
577
664
  }
578
665
 
666
+ /**
667
+ * The diagnosis as a spec-ready Markdown document (findings.md beside the dashboard): what was measured and how, what is
668
+ * still to fix, then one section per finding with its cause, evidence, code, proposed fix, expected gain, risk and how
669
+ * to verify it — the input for a later fix with a full spec (`bt-spec @.agents/profile/<slug>/findings.md`).
670
+ * @returns {string} the Markdown
671
+ */
672
+ function findingsMarkdown(findings, analysis, slugName) {
673
+ const capture = analysis.capture || {};
674
+ const list = (findings && Array.isArray(findings.findings)) ? findings.findings : [];
675
+ // A fix is done once it is in the code: "kept" (applied and proven by the fix loop) or "fixed".
676
+ const isDone = (finding) => finding.status === "kept" || finding.status === "fixed";
677
+ const open = list.filter((finding) => !isDone(finding));
678
+ const lines = [];
679
+ const push = (text = "") => lines.push(text);
680
+ push(`# ${findings && findings.title ? findings.title : "Performance findings"}`);
681
+ push();
682
+ if (findings && findings.summary) { push(findings.summary); push(); }
683
+ push(`- **Measured:** ${capture.url || "–"} · scenario \`${capture.scenario || "–"}\` · ${capture.engine || "no Babylon engine (browser frames)"} · captured ${capture.capturedAt || "–"}`);
684
+ push(`- **Dashboard:** \`dashboard.html\` beside this file · **Data:** \`data/\` (runs, findings.json)`);
685
+ push(`- **Re-measure after a fix:** \`/bt-profile --slug:${slugName}\` (same scenario) and compare the phases named below`);
686
+ push();
687
+ const fixable = list.filter((finding) => finding.fix);
688
+ const source = `@.agents/profile/${slugName}/findings.md`;
689
+ const join = (ids) => ids.length <= 1 ? ids.join("") : `${ids.slice(0, -1).join(", ")} and ${ids[ids.length - 1]}`;
690
+ const cell = (text) => String(text || "–").replace(/\|/g, "\\|").replace(/\n/g, " ");
691
+ push(`## The fixes (${open.length} not fixed yet)`);
692
+ push();
693
+ push("Spec them one at a time, or several together — each command points bt-spec at this file, which carries every fix's cause, evidence, code, gain, risk and how to verify it.");
694
+ push();
695
+ if (fixable.length) {
696
+ push("| ID | Fix | Status | Expected gain | Risk | Spec it |");
697
+ push("|---|---|---|---|---|---|");
698
+ for (const finding of fixable) push(`| ${finding.id} | ${cell(finding.title)} | ${finding.status || "proposed"} | ${cell(finding.gain || finding.cost)} | ${cell(finding.risk)} | \`/bt-spec Fix ${finding.id} from ${source}\` |`);
699
+ push();
700
+ const openIds = open.filter((finding) => finding.fix).map((finding) => finding.id);
701
+ if (openIds.length > 1) { push(`**All open fixes together:** \`/bt-spec Fix ${join(openIds)} from ${source}\``); push(); }
702
+ // The example group names real fixes: the first and last open ones, or the first two in the table.
703
+ const exampleIds = openIds.length > 2 ? [openIds[0], openIds[openIds.length - 1]] : fixable.slice(0, 2).map((finding) => finding.id);
704
+ if (exampleIds.length > 1) push(`**A group of your choice:** \`/bt-spec Fix ${join(exampleIds)} from ${source}\` (any IDs from the table)`);
705
+ } else {
706
+ push("No fixes proposed.");
707
+ }
708
+ push();
709
+ for (const finding of list) {
710
+ push(`## ${finding.id} · ${finding.title}`);
711
+ push();
712
+ push(`**Severity:** ${finding.severity || "–"} · **Status:** ${finding.status || "–"} · **Phases:** ${(finding.phases || []).join(", ") || "–"}${finding.cost ? ` · **Cost:** ${finding.cost}` : ""}`);
713
+ push();
714
+ if (finding.cause) { push("### Why it is slow"); push(); push(finding.cause); push(); }
715
+ if (finding.evidence && finding.evidence.length) { push("### Evidence"); push(); for (const item of finding.evidence) push(`- ${item}`); push(); }
716
+ if (finding.code && finding.code.length) { push("### Code"); push(); for (const location of finding.code) push(`- \`${location.file}${location.line ? `:${location.line}` : ""}\`${location.label ? ` — ${location.label}` : ""}`); push(); }
717
+ if (finding.fix) { push(isDone(finding) ? "### The fix" : "### Proposed fix"); push(); push(finding.fix); push(); }
718
+ if (finding.gain) { push(`**Expected gain:** ${finding.gain}`); push(); }
719
+ if (finding.risk) { push(`**Risk:** ${finding.risk}`); push(); }
720
+ if (finding.verify) { push(`**How to verify:** ${finding.verify}`); push(); }
721
+ if (finding.before || finding.after) { push(`**Before:** ${finding.before || "–"} · **After:** ${finding.after || "not fixed yet"}`); push(); }
722
+ if (finding.diff) { push("<details><summary>The change</summary>"); push(); push("```diff"); push(finding.diff); push("```"); push(); push("</details>"); push(); }
723
+ }
724
+ return lines.join("\n");
725
+ }
726
+
727
+ /**
728
+ * Prints the report to a PDF beside it (the page's Download PDF button), with the Chrome the capture drives: the print
729
+ * stylesheet, every collapsed section open, backgrounds kept. A machine without puppeteer or Chrome only skips the PDF.
730
+ */
731
+ async function writePdf(htmlFile, pdfFile) {
732
+ let puppeteer = null;
733
+ try {
734
+ puppeteer = (await import("puppeteer-core")).default;
735
+ } catch {
736
+ process.stdout.write("skipped the PDF (puppeteer-core is not installed next to report.mjs)\n");
737
+ return;
738
+ }
739
+ let browser = null;
740
+ try {
741
+ const { findChrome } = await import("./lib/chrome.mjs");
742
+ browser = await puppeteer.launch({ executablePath: findChrome(), headless: "new", args: ["--allow-file-access-from-files"] });
743
+ const page = await browser.newPage();
744
+ await page.setViewport({ width: 1280, height: 900, deviceScaleFactor: 1 });
745
+ await page.goto("file://" + path.resolve(htmlFile), { waitUntil: "load" });
746
+ await new Promise((resolve) => setTimeout(resolve, 1200)); // charts and the progress panel render after load
747
+ await page.evaluate(() => {
748
+ // The PDF is the report: a run still marked running (the report is written just before the run ends) keeps
749
+ // its live panel off the page.
750
+ if (document.documentElement.classList.contains("btp-running")) document.querySelectorAll("#bt-progress, .btp-toolbar").forEach((element) => element.remove());
751
+ document.querySelectorAll("details").forEach((details) => { details.open = true; });
752
+ });
753
+ await page.emulateMediaType("print");
754
+ await page.pdf({ path: pdfFile, format: "A4", printBackground: true, margin: { top: "12mm", right: "10mm", bottom: "12mm", left: "10mm" } });
755
+ process.stdout.write(`wrote ${pdfFile}\n`);
756
+ } catch (error) {
757
+ process.stdout.write(`skipped the PDF: ${error.message}\n`);
758
+ } finally {
759
+ if (browser) await browser.close();
760
+ }
761
+ }
762
+
579
763
  /** Entry point. */
580
- function main() {
764
+ async function main() {
581
765
  const flags = parseArguments(process.argv.slice(2));
582
766
  if (!flags.analysis) throw new Error("Pass --analysis <analysis.json> [--out <dashboard.html>]");
583
767
  const runDir = (file) => (file ? path.dirname(path.resolve(file)) : null);
@@ -598,14 +782,22 @@ function main() {
598
782
  warm: warm ? pageData(warm, reportDir, runDir(flags.warm)) : null,
599
783
  findings,
600
784
  groups: OWNER_GROUPS,
785
+ slug: path.basename(reportDir),
601
786
  };
602
787
  if (flags.snapshots) data.run.shots = shotsFrom(path.resolve(flags.snapshots), reportDir);
603
788
  if (flags["snapshots-before"]) {
604
789
  // Shown beside this run's shots of the same names (needs --baseline, whose own shots they replace).
605
790
  if (data.baseline) data.baseline.shots = shotsFrom(path.resolve(flags["snapshots-before"]), reportDir);
606
791
  }
607
- fs.writeFileSync(outFile, buildPage({ title, verdict: findings && findings.summary, data }));
792
+ const pdfFile = flags.pdf === "false" ? null : outFile.replace(/\.html?$/i, "") + ".pdf";
793
+ fs.writeFileSync(outFile, buildPage({ title, verdict: findings && findings.summary, data, pdfName: pdfFile ? path.basename(pdfFile) : null }));
608
794
  process.stdout.write(`wrote ${outFile}\n`);
795
+ if (findings) {
796
+ const markdownFile = path.join(path.dirname(outFile), "findings.md");
797
+ fs.writeFileSync(markdownFile, findingsMarkdown(findings, analysis, path.basename(path.dirname(outFile))));
798
+ process.stdout.write(`wrote ${markdownFile}\n`);
799
+ }
800
+ if (pdfFile) return writePdf(outFile, pdfFile);
609
801
  }
610
802
 
611
- main();
803
+ main().catch((error) => { process.stderr.write(String(error && error.stack ? error.stack : error) + "\n"); process.exit(1); });