@babylonjs-toolkit/agent 1.1.64 → 1.1.68

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 (33) hide show
  1. package/README.md +35 -5
  2. package/bin/bt-agent.js +64 -4
  3. package/lib/claude-settings.js +77 -0
  4. package/lib/doctor.js +36 -0
  5. package/lib/install.js +59 -3
  6. package/lib/persona.js +21 -2
  7. package/lib/reference.js +400 -0
  8. package/package.json +1 -1
  9. package/persona.md +1 -1
  10. package/scripts/postinstall.js +6 -0
  11. package/skills/bt-design/references/3d-hero-scroll.md +2 -2
  12. package/skills/bt-execute/SKILL.md +7 -7
  13. package/skills/bt-execute/templates/dashboard/dashboard.html +96 -21
  14. package/skills/bt-execute/templates/dashboard/data-schema.md +4 -3
  15. package/skills/bt-gauntlet/SKILL.md +2 -2
  16. package/skills/bt-gauntlet/references/unity-pipeline.md +1 -1
  17. package/skills/bt-gauntlet/references/workspace.md +1 -1
  18. package/skills/bt-plan/SKILL.md +2 -2
  19. package/skills/bt-profile/SKILL.md +275 -0
  20. package/skills/bt-profile/scripts/analyze.mjs +683 -0
  21. package/skills/bt-profile/scripts/compare.mjs +87 -0
  22. package/skills/bt-profile/scripts/lib/probe.mjs +225 -0
  23. package/skills/bt-profile/scripts/lib/progress-panel.mjs +275 -0
  24. package/skills/bt-profile/scripts/lib/symbolize.mjs +356 -0
  25. package/skills/bt-profile/scripts/package.json +10 -0
  26. package/skills/bt-profile/scripts/profile.mjs +517 -0
  27. package/skills/bt-profile/scripts/progress.mjs +385 -0
  28. package/skills/bt-profile/scripts/report.mjs +611 -0
  29. package/skills/bt-profile/templates/census.template.mjs +76 -0
  30. package/skills/bt-profile/templates/scenario.template.mjs +69 -0
  31. package/skills/bt-prototype/SKILL.md +1 -1
  32. package/skills/bt-recon/SKILL.md +2 -2
  33. package/skills/bt-spec/SKILL.md +2 -2
@@ -299,10 +299,12 @@
299
299
  .stat-sub { margin-top: 4px; font-size: 12.5px; color: var(--text-muted); }
300
300
 
301
301
  /* ---------- Phase route ---------- */
302
- .route { display: flex; gap: 6px; margin-top: 16px; }
302
+ .route { display: flex; gap: 10px; margin-top: 16px; }
303
303
  .route a {
304
304
  flex: 1;
305
305
  min-width: 0;
306
+ display: flex;
307
+ flex-direction: column;
306
308
  text-decoration: none;
307
309
  color: inherit;
308
310
  }
@@ -310,11 +312,30 @@
310
312
  .route-fill { height: 100%; border-radius: 999px; background: var(--done); }
311
313
  .route a.is-in-progress .route-fill { background: var(--active); }
312
314
  .route a.is-deferred .route-fill, .route a.is-partial .route-fill { background: var(--deferred); }
315
+ /* Each name sits on a panel as wide as its bar; every panel is the row's height, sized for two lines. */
313
316
  .route-label {
317
+ flex: 1;
314
318
  margin-top: 7px;
319
+ padding: 7px 9px;
320
+ min-height: calc(2 * 1.3em + 14px);
321
+ border: 1px solid var(--line);
322
+ border-radius: var(--radius-small);
323
+ background: var(--bg-raised);
315
324
  font: 500 11.5px/1.3 var(--font-mono);
316
325
  color: var(--text-muted);
326
+ transition: border-color 0.15s, color 0.15s;
327
+ }
328
+ /* At most two lines, so one long phase name never stretches the row; the full name is the tooltip. */
329
+ .route-name {
330
+ display: -webkit-box;
331
+ -webkit-box-orient: vertical;
332
+ -webkit-line-clamp: 2;
333
+ line-clamp: 2;
334
+ overflow: hidden;
335
+ overflow-wrap: anywhere;
317
336
  }
337
+ .route a:hover .route-label { border-color: var(--line-strong); color: var(--text); }
338
+ .route a.is-in-progress .route-label { border-color: color-mix(in srgb, var(--active) 45%, transparent); background: var(--active-soft); color: var(--text); }
318
339
 
319
340
  /* ---------- Summary ---------- */
320
341
  .headline { margin: 0 0 12px; font-size: 21px; line-height: 1.35; letter-spacing: -0.01em; }
@@ -802,6 +823,8 @@
802
823
  const VERDICT_BADGE_MAX_LENGTH = 16;
803
824
  // The report's task-by-task testing table starts open for a short plan and folded for a long one.
804
825
  const TESTING_TABLE_OPEN_ROWS = 12;
826
+ // A verifier result that names a live check: "live two-tab race in headless Chrome", "end-to-end on WebGPU".
827
+ const LIVE_CHECK_WORDS = /\blive\b|chrome|browser|webgl|webgpu|unity editor|play ?mode/i;
805
828
  /** Where the Babylon Toolkit Desktop Agent, whose skills generate this dashboard, is published. */
806
829
  const SKILLS_DOWNLOAD_URL = 'https://www.npmjs.com/package/@babylonjs-toolkit/agent';
807
830
  /** Minutes without a live update before the Now banner warns that the run has gone quiet. */
@@ -863,7 +886,7 @@
863
886
 
864
887
  const view = pageView();
865
888
  // Stat tiles and phase bars first; then one slot that follows the run: Current run activity while it runs,
866
- // the plan summary (After Action Report) once it is over.
889
+ // the Final plan summary (the After Action Report) once it is over.
867
890
  appRoot.innerHTML = [
868
891
  renderMasthead(feature, allTasks.length, doneCount),
869
892
  renderNav(allUpdates.length, view),
@@ -923,7 +946,7 @@
923
946
  function renderNav(updateCount, view) {
924
947
  const links = [
925
948
  view === 'running' ? ['current-activity', 'Current run'] : null,
926
- view === 'finished' ? ['after-action', 'Plan summary'] : null,
949
+ view === 'finished' ? ['after-action', 'Summary'] : null,
927
950
  ['phases', 'Phases'],
928
951
  ['decisions', 'Decisions'],
929
952
  ['follow-ups', 'Follow ups'],
@@ -938,19 +961,20 @@
938
961
  const phases = report.phases || [];
939
962
  const donePhases = phases.filter((phase) => phase.status === 'done').length;
940
963
  const deferredCount = allTasks.filter((task) => task.status === 'deferred' || task.status === 'failed').length;
941
- const testTotals = allTasks.reduce((totals, task) => {
942
- if (task.tests) {
943
- totals.passed += Number(task.tests.passed) || 0;
944
- totals.failed += Number(task.tests.failed) || 0;
945
- }
946
- return totals;
947
- }, { passed: 0, failed: 0 });
964
+ // The final suites are the true count; each task reports the whole suite it ran, so a sum of tasks over-counts.
965
+ const suites = finalSuites();
966
+ const testsTile = suites.length
967
+ ? statTile('Tests', `${suites.reduce((total, suite) => total + (Number(suite.passed) || 0), 0)}<small> passed</small>`, sumFailed(suites) ? `${sumFailed(suites)} failing` : 'final suites, all green')
968
+ : statTile('Tests', `${allTasks.filter(hasTests).length}<small> / ${allTasks.length}</small>`, 'tasks with tests');
969
+ const activeTime = shortDuration(report.activeTime);
970
+ const estimate = shortEstimate(report.estimate);
948
971
 
949
972
  const tiles = [
950
973
  statTile('Tasks', `${doneCount}<small> / ${allTasks.length}</small>`, 'verified and ticked'),
951
974
  statTile('Phases', `${donePhases}<small> / ${phases.length}</small>`, 'independently verified'),
952
- statTile('Tests', `${testTotals.passed}<small> passed</small>`, testTotals.failed ? `${testTotals.failed} failing` : 'no failures recorded'),
953
- statTile('Active time', escapeHtml(report.activeTime || '—'), report.estimate ? `estimate ${escapeHtml(report.estimate)}` : 'no estimate'),
975
+ testsTile,
976
+ statTile('Active time', activeTime ? durationHtml(activeTime) : '—', estimate ? `of ${/[–-]/.test(estimate) ? '' : '~'}${escapeHtml(estimate)} estimated` : 'no estimate',
977
+ [report.activeTime, report.estimate && `Estimate: ${report.estimate}`].filter(Boolean).join('\n')),
954
978
  statTile('Deferred', String(deferredCount), deferredCount ? 'see Follow ups' : 'nothing deferred'),
955
979
  statTile('Runs', String(report.runs || 0), 'bt-execute runs so far'),
956
980
  ].join('');
@@ -962,15 +986,52 @@
962
986
  const fill = tasks.length ? Math.round(((finished + awaitingVerifier / 2) / tasks.length) * 100) : 0;
963
987
  return `<a href="#phase-${escapeAttribute(phase.number)}" class="is-${escapeAttribute(phase.status || 'pending')}" title="Phase ${escapeAttribute(phase.number)} — ${escapeAttribute(phase.name || '')}">
964
988
  <div class="route-bar"><div class="route-fill" style="width:${fill}%"></div></div>
965
- <div class="route-label">P${escapeHtml(phase.number)} · ${escapeHtml(phase.name || '')}</div>
989
+ <div class="route-label"><span class="route-name">P${escapeHtml(phase.number)} · ${escapeHtml(phase.name || '')}</span></div>
966
990
  </a>`;
967
991
  }).join('');
968
992
 
969
993
  return `<div class="stats">${tiles}</div>${route ? `<nav class="route" aria-label="Phase progress">${route}</nav>` : ''}`;
970
994
  }
971
995
 
972
- function statTile(label, valueHtml, subText) {
973
- return `<div class="card stat"><div class="stat-label">${label}</div><div class="stat-value">${valueHtml}</div><div class="stat-sub">${subText}</div></div>`;
996
+ function statTile(label, valueHtml, subText, title = '') {
997
+ return `<div class="card stat"${title ? ` title="${escapeAttribute(title)}"` : ''}><div class="stat-label">${label}</div><div class="stat-value">${valueHtml}</div><div class="stat-sub">${subText}</div></div>`;
998
+ }
999
+
1000
+ /**
1001
+ * The first duration in a time note — "5 h 54 min (run 5); earlier runs in the run log" → { hours: 5, minutes: 54 }.
1002
+ * The data holds whatever the run log said; the card shows only the time, the full note is its tooltip.
1003
+ */
1004
+ function shortDuration(text) {
1005
+ const match = /(?:(\d+(?:\.\d+)?)\s*h(?:ours?)?\b)?\s*(?:(\d+)\s*min)?/i;
1006
+ for (const candidate of String(text || '').matchAll(new RegExp(match.source, 'gi'))) {
1007
+ if (candidate[1] || candidate[2]) {
1008
+ const total = Math.round(Number(candidate[1] || 0) * 60) + Number(candidate[2] || 0);
1009
+ return { hours: Math.floor(total / 60), minutes: total % 60 };
1010
+ }
1011
+ }
1012
+ return null;
1013
+ }
1014
+
1015
+ function durationText({ hours, minutes }) {
1016
+ return hours ? `${hours} h${minutes ? ` ${minutes} min` : ''}` : `${minutes} min`;
1017
+ }
1018
+
1019
+ function durationHtml({ hours, minutes }) {
1020
+ if (!hours) return `${minutes}<small> min</small>`;
1021
+ return `${hours}<small> h</small>${minutes ? ` ${minutes}<small> min</small>` : ''}`;
1022
+ }
1023
+
1024
+ /**
1025
+ * The headline figure of an estimate note: "about 944 min ≈ 15.7 h of agent time (range …)" → "15.7 h";
1026
+ * "3–6 h" stays a range. Brackets are detail; after a "≈" comes the rounded figure.
1027
+ */
1028
+ function shortEstimate(text) {
1029
+ let main = String(text || '').split('(')[0];
1030
+ if (main.includes('≈')) main = main.slice(main.lastIndexOf('≈') + 1);
1031
+ const hours = /(\d+(?:\.\d+)?(?:\s*[–-]\s*\d+(?:\.\d+)?)?)\s*h\b/i.exec(main);
1032
+ if (hours) return `${hours[1].replace(/\s+/g, '')} h`;
1033
+ const duration = shortDuration(main);
1034
+ return duration ? `${duration.hours ? `${duration.hours} h ` : ''}${duration.minutes ? `${duration.minutes} min` : ''}`.trim() : '';
974
1035
  }
975
1036
 
976
1037
  /**
@@ -1011,7 +1072,7 @@
1011
1072
  }
1012
1073
  return `
1013
1074
  <section id="after-action">
1014
- <div class="section-head"><h2>The plan summary</h2><span class="section-note">The whole plan's execution, start to finish</span></div>
1075
+ <div class="section-head"><h2>Final plan summary</h2><span class="section-note">The whole plan's execution, start to finish</span></div>
1015
1076
  ${body}
1016
1077
  </section>`;
1017
1078
  }
@@ -1033,8 +1094,8 @@
1033
1094
  testsFigure,
1034
1095
  ['Needed a second attempt', String(retried)],
1035
1096
  ['Deferred', String(deferred)],
1036
- ['Active time', report.activeTime || '—'],
1037
- ['Estimate', report.estimate || '—'],
1097
+ ['Active time', shortDuration(report.activeTime) ? durationText(shortDuration(report.activeTime)) : '—'],
1098
+ ['Estimate', shortEstimate(report.estimate) || '—'],
1038
1099
  ['Runs', String(report.runs || 0)],
1039
1100
  ];
1040
1101
  return `<dl class="figures">${rows.map(([label, value]) => `<div><dt>${label}</dt><dd>${escapeHtml(value)}</dd></div>`).join('')}</dl>`;
@@ -1097,7 +1158,7 @@
1097
1158
  const tags = [
1098
1159
  snapshotBadge(task.snapshots),
1099
1160
  task.kind ?`<span class="tag">${escapeHtml(task.kind)}</span>` : '',
1100
- task.verifyLevel === 'live' ? '<span class="tag">live check</span>' : '',
1161
+ hasLiveCheck(task) ? `<span class="tag" title="${escapeAttribute(liveCheckNote(task))}">live check</span>` : '',
1101
1162
  task.attempts > 1 ? `<span class="tag">${escapeHtml(task.attempts)} attempts</span>` : '',
1102
1163
  status === 'built' || status === 'verifying' ? `<span class="status status-${status}">${STATUS_LABELS[status]}</span>` : '',
1103
1164
  updatedBadge(task.updates),
@@ -1240,8 +1301,22 @@
1240
1301
  return Boolean(task.tests && (Number(task.tests.passed) || Number(task.tests.failed)));
1241
1302
  }
1242
1303
 
1304
+ /**
1305
+ * Whether the task was checked by running the real thing. The plan's `verifyLevel` is only the intent — a
1306
+ * verifier often checks a `standard` task live too — so the record of the check counts as well: the
1307
+ * `checkedLive` note, a verbose `liveCheck`, a verifier result that names a live check, or a snapshot
1308
+ * captured in the browser or Unity.
1309
+ */
1243
1310
  function hasLiveCheck(task) {
1244
- return task.verifyLevel === 'live' || Boolean(task.details && task.details.liveCheck);
1311
+ return task.verifyLevel === 'live'
1312
+ || Boolean(task.checkedLive || (task.details && task.details.liveCheck))
1313
+ || LIVE_CHECK_WORDS.test(task.verifier || '')
1314
+ || (task.snapshots || []).some((snapshot) => ['browser', 'unity'].includes(snapshot.source));
1315
+ }
1316
+
1317
+ function liveCheckNote(task) {
1318
+ return task.checkedLive || (task.details && task.details.liveCheck) || (LIVE_CHECK_WORDS.test(task.verifier || '') ? task.verifier : '')
1319
+ || ((task.snapshots || []).length ? 'Snapshots captured from the running result' : 'Checked live');
1245
1320
  }
1246
1321
 
1247
1322
  function testCasesOf(task) {
@@ -1285,7 +1360,7 @@
1285
1360
  : `<span class="cell-note" title="${escapeAttribute(tests.note || '')}">${tests.note ? escapeHtml(tests.note) : '—'}</span>`,
1286
1361
  (tests.files || []).length ? tests.files.map((file) => `<code>${escapeHtml(file)}</code>`).join('<br>') : '—',
1287
1362
  cases.length ? `${cases.length}${casesFailed ? `<div class="count count-fail">${casesFailed} failed</div>` : ''}` : '—',
1288
- hasLiveCheck(task) ? `<span title="${escapeAttribute((task.details && task.details.liveCheck) || 'Checked live')}">Yes</span>` : '—',
1363
+ hasLiveCheck(task) ? `<span title="${escapeAttribute(liveCheckNote(task))}">Yes</span>` : '—',
1289
1364
  ];
1290
1365
  }));
1291
1366
 
@@ -77,7 +77,7 @@ instead of a blank page if something still cannot render — it keeps checking a
77
77
  - A task added to the plan after it was complete is added here as `pending`, in plan order, with an `updates`
78
78
  note saying why — and `complete` becomes `paused`.
79
79
  - The status picks the page's top slot: `in-progress` shows *Current run activity* (the live file and the
80
- milestones); `paused`, `complete` and `incomplete` show *The plan summary* (the After Action Report, marked
80
+ milestones); `paused`, `complete` and `incomplete` show *Final plan summary* (the After Action Report, marked
81
81
  *Interim* while paused).
82
82
  - **Cadence is per task.** A task's entry changes the moment it starts (`in-progress`), the moment it is built
83
83
  (`built` — summary, files, tests and snapshots filled in right then), while the verifier checks it
@@ -95,8 +95,8 @@ Top level:
95
95
  | `status` | see *Status* |
96
96
  | `detail` | `"normal"`, or `"verbose"` once any run used `bt-execute --verbose` (never set back) |
97
97
  | `updatedAt` | last write, `"YYYY-MM-DD HH:MM"` |
98
- | `estimate` | the plan's Total line, e.g. `"3–6 h"` |
99
- | `activeTime` | from the run log's `⏱` lines, e.g. `"2 h 10 min"` |
98
+ | `estimate` | the plan's Total, short: `"3–6 h"` or `"about 7 h"` — the card shows its hours; keep ranges and working-out in the plan |
99
+ | `activeTime` | the plan's total active time across **every run so far** — each run's `active` from its `⏱ Run <n> end` line, added up — as the duration only: `"14 h 10 min"`, no notes. The card shows it beside the estimate, so one run's time alone understates the plan |
100
100
  | `runs` | number of bt-execute runs so far |
101
101
  | `afterAction` | the After Action Report (below) |
102
102
  | `phases` | the plan's phases, each with its tasks (below) |
@@ -154,6 +154,7 @@ Each task:
154
154
  | `files` | paths changed |
155
155
  | `tests` | `{ "passed", "failed", "files": [".agents/specs/<slug>/tests/…"], "note" }` or `null` |
156
156
  | `verifier` | `"PASS — independent subagent; live check in Chrome"` |
157
+ | `checkedLive` | every run, not only `--verbose`: one line on what the verifier ran live and where — `"two-tab Shared race in headless Chrome, 150 ms lag"`; `""` when it was proven by tests alone. The page's *live check* badge and column read it (a task the plan marked `live` always counts) |
157
158
  | `attempts`, `commit`, `doneAt` | as recorded |
158
159
  | `deferredReason` | why it was deferred, if it was |
159
160
  | `decisions` | `"DECISION T1: … — source"` lines |
@@ -67,11 +67,11 @@ Downgrading is not a neutral choice. A critic that is the same context which jus
67
67
 
68
68
  ## ⚠️ Required Reading Before Any Babylon Work
69
69
 
70
- For any round involving Babylon, BabylonJS, or the Babylon Toolkit, first ensure you have already fetched and read the Babylon Toolkit Agent Reference in the current remembered session/context:
70
+ For any round involving Babylon, BabylonJS, or the Babylon Toolkit, first ensure you have already read the Babylon Toolkit Agent Reference in the current remembered session/context:
71
71
 
72
72
  https://raw.githubusercontent.com/babylontoolkit/agent/main/reference.md
73
73
 
74
- If you have not read it in this session/context, or you no longer remember it due to context loss/compaction (which WILL be the case on `--resume` in a fresh session), fetch and read it before writing any code. Treat it as the authority for conventions, API, and patterns; fetch its linked subpages only when relevant — and for a `unity` job the Unity Exporter subpage is **always** relevant, plus the Blender CLI subpage whenever model work is in scope. Do not refetch what you still remember. If a required fetch fails, STOP and tell the user. Do not guess at the API. Builders spawned as subagents must be given (or told to fetch) the Agent Reference too — a subagent does not inherit your context.
74
+ If you have not read it in this session/context, or you no longer remember it due to context loss/compaction (which WILL be the case on `--resume` in a fresh session), read it before writing any code. Treat it as the authority for conventions, API, and patterns; read its linked subpages only when relevant — and for a `unity` job the Unity Exporter subpage is **always** relevant, plus the Blender CLI subpage whenever model work is in scope. Do not re-read what you still remember. If a required document cannot be read, STOP and tell the user. Do not guess at the API. Builders spawned as subagents must be given (or told to read) the Agent Reference too — a subagent does not inherit your context.
75
75
 
76
76
  ## ⚠️ Babylon Toolkit Component Authority (supplied interactive assets)
77
77
 
@@ -38,7 +38,7 @@ scenes; geometry, UVs, PBR maps, LODs and skinning for models.
38
38
  > container** (`selection != null`, components but no scene metadata). A model used in a level ships inside
39
39
  > that level's export; there is nothing asset-specific to do for it. See § 6.B.
40
40
 
41
- > **Required reading before round 1.** Fetch and read the Agent Reference's
41
+ > **Required reading before round 1.** Read the Agent Reference's
42
42
  > [Unity Exporter Instructions](https://raw.githubusercontent.com/babylontoolkit/agent/main/references/unity-exporter-cli.md)
43
43
  > and [Unity Authoring Recipes](https://raw.githubusercontent.com/babylontoolkit/agent/main/references/unity-authoring-recipes.md)
44
44
  > in full — and, for any round that touches Blender, the
@@ -119,7 +119,7 @@ progress.md updated: attempt 3/5, stall -> approaching (same top gap twice)
119
119
 
120
120
  1. Resolve the job: explicit name → that job; one job in `.agents/gauntlet/` → resume it; several → list them and
121
121
  ask.
122
- 2. Fetch/read the Babylon Toolkit Agent Reference if not already remembered in this session.
122
+ 2. Read the Babylon Toolkit Agent Reference if not already remembered in this session.
123
123
  3. Read `.agents/gauntlet/<name>/loop-card.md` → `progress.md` → `pipeline.md` → `cameras.md` →
124
124
  `components.md` (if present) → the last 1–2 `rounds/*.md`.
125
125
  4. Read the pipeline reference for the job's `Kind` and **re-run its prerequisite gate**. This is not
@@ -23,9 +23,9 @@ Turn a feature spec into `.agents/specs/<slug>/documents/<slug>_plan.md`: an ord
23
23
 
24
24
  - **TIME MATTERS** — on by default; `--no-time-limit` turns it off. Treat the arguments as ending with `TIME MATTERS`: the user is waiting on this run, so finish quickly — research only what the plan needs, keep subagents few and their questions narrow, and do not re-read what you already have. Begin every subagent prompt with `TIME MATTERS.` Print `⏱️ [bt-plan] TIME MATTERS` at the start (`--no-time-limit`: print `⏱️ [bt-plan] No time limit`, and do not add it). Speed never skips a required step, the Heavy Plan cold-context audit, or anything the plan needs to be complete.
25
25
  - **Planning only — in every mode.** Research read-only; the only files you write are the plan and the dashboard (`dashboard.html` and its data files) in the feature folder, plus the one `.gitignore` line Step 4 names. Never implement a task, edit source, or run builds/tests — not even a trivial first task. Writing the plan is the last action; the user runs `bt-execute` separately.
26
- - **Babylon work:** if you have not read the Babylon Toolkit Agent Reference in this session, fetch and read it once: https://raw.githubusercontent.com/babylontoolkit/agent/main/reference.md — the authority for conventions and API; fetch sub-documents only when relevant, and again only if a context compaction made you forget it. If the fetch fails, stop and tell the user — do not guess at the API.
26
+ - **Babylon work:** if you have not read the Babylon Toolkit Agent Reference in this session, read it once: https://raw.githubusercontent.com/babylontoolkit/agent/main/reference.md — the authority for conventions and API; read sub-documents only when relevant, and again only if a context compaction made you forget it. If it cannot be read, stop and tell the user — do not guess at the API.
27
27
  - **Say what you are doing.** Before any step that takes more than a few seconds print one short line — `🔎 [bt-plan] <what> …` — and one when it returns; one line per subagent going out and coming back. A silent run looks like a hang and gets cancelled.
28
- - **Subagents:** running this skill is the user's request to use them where it says so. Use whatever subagent tool your host provides (its name varies by host — e.g. `Agent` or `Task`); if there is none, work inline and say so. Tell exploration subagents they need not fetch the Agent Reference.
28
+ - **Subagents:** running this skill is the user's request to use them where it says so. Use whatever subagent tool your host provides (its name varies by host — e.g. `Agent` or `Task`); if there is none, work inline and say so. Tell exploration subagents they need not read the Agent Reference.
29
29
 
30
30
  ## Step 1. Analyze (required before writing)
31
31
 
@@ -0,0 +1,275 @@
1
+ ---
2
+ name: bt-profile
3
+ description: "The Babylon Toolkit Profile Skill finds and fixes what makes a BabylonJS / Babylon Toolkit web game slow. It drives the running game in a real Chrome over the DevTools protocol through a repeatable scenario (a cold load, a level start, a countdown, a boss fight), records a full CPU profile, per-phase allocation profiles, every frame's CPU work and Babylon timers, and maps every sampled millisecond back to the original source line and its owner — your game code, a project-owned script bundle (e.g. the Unity exporter's project bundle), the Babylon Toolkit runtime, BabylonJS, Havok, shader translation, React, the browser. It charges library work to the code of yours that triggered it, splits everything by phase and by second, then diagnoses each bottleneck, fixes it one at a time, re-measures the same scenario to prove the gain (reverting anything that does not help), and writes a code-dashboard report to `.agents/profile/<slug>/dashboard.html` (everything the slug's runs produced sits beside it in `.agents/profile/<slug>/data/`). Use when the user says the game is slow, stutters, crawls at a moment (load, start, many particles), or wants a performance analysis (e.g. `/bt-profile the race start crawls for a minute`, `/bt-profile --analyze`, `/bt-profile http://localhost:5173/play --scenario level-start`)."
4
+ allowed-tools: Read, Grep, Glob, Edit, Write, Bash
5
+ ---
6
+
7
+ You are an EXPERT BabylonJS, Babylon Toolkit and browser performance engineer. Always adhere to any rules or requirements set out in the project's agent instructions (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md).
8
+
9
+ Use the user's message after the skill name as the `arguments`.
10
+
11
+ ---
12
+
13
+ # Invocation
14
+
15
+ ```
16
+ /bt-profile [<brief: what is slow, when>] [--project:<path>] [--url:<game URL>] [--scenario:<name|path>] [--slug:<name>]
17
+ [--analyze] [--snapshots] [--no-warm] [--settle:<seconds>] [--runs:<n>] [--trace]
18
+ [--max-fixes:<n>] [--target-fps:<n>] [--dpr:<n>] [--args:key=value,…]
19
+ ```
20
+
21
+ - **`<brief>`** — the user's words about the slowdown ("the race start crawls for a minute", "stutters when particles spawn"). It decides the scenario and which phases matter most.
22
+ - **`--project:`** — the web project to profile: its folder, or any folder or file inside it (absolute, `~/…`, or relative to the working directory). Default: the working directory's project (see **Which project** below).
23
+ - **`--url:`** — the page that runs the game. Default: `profile.config.json` → `url`, else the dev server's `/play` (or `/`).
24
+ - **`--scenario:`** — the slug's `data/scenario.mjs`, or a path to copy into it. Default: the slug's own; with none, write one (Phase 0).
25
+ - **`--slug:`** — the profiled moment, and its folder: `.agents/profile/<slug>/` holds `dashboard.html` and `data/` (config, scenario, findings, runs, logs). Default: the scenario's name (e.g. `race-start`). A new moment gets a new slug; never mix two scenarios' runs in one slug.
26
+ - **`--analyze`** — measure, diagnose and report only. Changes no code.
27
+ - **`--snapshots`** — phase screenshots plus a filmstrip (about one small frame per second, lined up under the frame-rate chart), and the before/after look comparison. **Off by default**: a full-size screenshot stalls the game for a moment and would show up in the very profile it explains. Turn it on for the visual verification runs, or whenever the user asks.
28
+ - **`--no-warm`** — skip the second, warm load in the same browser (on by default for the baseline: cold vs warm separates first-use costs from steady per-frame work).
29
+ - **`--settle:`** — seconds recorded after the scenario's main event (passed to the scenario as `--args settle=`).
30
+ - **`--runs:`** — baseline captures used to measure run-to-run noise (default 2).
31
+ - **`--trace`** — also save a full DevTools performance trace (`trace.json`, large) for the user to open in Chrome.
32
+ - **`--max-fixes:`** — stop after this many kept fixes (default: until the target is met or nothing worth fixing is left).
33
+ - **`--target-fps:`** — the goal for the phases the brief names (default 60).
34
+ - **`--dpr:`** — device pixel ratio of the profiled window (default 2, a Retina laptop).
35
+
36
+ ---
37
+
38
+ # What this skill guarantees
39
+
40
+ 1. **Measured, never guessed.** Every finding cites the profile: the function, its owner, its ms per frame, the phase, and the code of yours behind it. No fix is made on a hunch.
41
+ 2. **One fix at a time, proven.** Each fix is re-measured with the same scenario; it is kept only when its target cost falls and the phase it serves gets faster beyond the measured noise. Otherwise it is reverted, and the report says so.
42
+ 3. **The user's work is safe.** Uncommitted changes in the working tree are recorded first and never reverted, stashed or committed. Fixes are made as small, reviewable edits; the report carries each diff. Nothing is committed unless the user asks.
43
+ 4. **It still works and looks the same.** After the fixes: typecheck / build, the project's tests, a clean console, and (`--snapshots`) the same phases screenshotted before and after.
44
+ 5. **Libraries are not patched.** BabylonJS, Havok, React and other node_modules code is never edited. When the time is spent inside a library, the fix changes how your code uses it (call it less, on less, configure it, cache, freeze, pool) — or, for a toolkit / engine defect, the report states it with evidence for its owner.
45
+
46
+ # Talk to the user while you work
47
+
48
+ Long runs lose people. At every phase change, post one short plain-language update: **Done** (with numbers) · **Doing now** · **Next**. When a finding is confirmed, say it in one sentence a non-specialist understands ("Physics copies every body's position back every step — 7 ms of each frame").
49
+
50
+ # Live progress — the dashboard follows the run
51
+
52
+ The user watches `dashboard.html` while the profile runs, not only after it. From the run's first minute the page shows **what is happening right now**, the stages (Preflight → Baseline → Diagnose → Fix → Verify → Report), every fix with its status and before → after, and the numbers so far; it checks for changes every 10 s and, when the run ends, reloads into the finished report (where the run folds into a *How this profile ran* summary). All of it comes from `data/progress.js`, which **only `progress.mjs` writes** — never edit it by hand:
53
+
54
+ ```bash
55
+ P="node $TOOLS/progress.mjs"; S="$PROF/$SLUG" # S is the slug folder (it holds dashboard.html and data/)
56
+ $P start "$S" --title "<Project> — <scenario> performance" --brief "<the user's words>" --project "$PROJ" --url "<url>" [--mode analyze]
57
+ $P stage "$S" baseline [--note "2 cold captures + 1 warm, 90 s settle"] # starting a stage finishes the one before
58
+ $P now "$S" "Capturing baseline 1 of 2 — about 3 min" # what is happening this minute
59
+ $P metric "$S" "Race start FPS" "24" --note "baseline · target 60"
60
+ $P fix "$S" F1 --title "Stop forced world-matrix recomputes" --status trying # then measuring → kept | reverted
61
+ $P fix "$S" F1 --status kept --before "24 fps" --after "41 fps" --note "−14 ms/frame in the countdown"
62
+ $P note "$S" "Noise floor ±1.8 fps — a fix must beat it" # a milestone
63
+ $P end "$S" --summary "<the verdict in one sentence>" # or --status stopped|failed with why
64
+ ```
65
+
66
+ - **Open the run before anything else** (the first lines of Phase 0): `start`, then the watchdog in the background — `node "$TOOLS/progress.mjs" watch "$S" --watch "$PROJ/src" > "$DATA/logs/watchdog.log" 2>&1 &` (add `--watch` for every other folder the fixes touch: a runtime, a Unity project's scripts). `start` writes a live page when the slug has no dashboard yet, and keeps an older report that has no panel in `data/previous-dashboard.html`.
67
+ - **Write before every long command, never after only.** A capture, an analysis, a build or a test run gets a `now` line first that says what it is and roughly how long it takes; the result gets the next one. Never let 10 minutes pass without a write. The watchdog covers a silent stretch — after 5 quiet minutes it posts a heartbeat naming the newest file and the newest capture log's last line, after 30 without any file change it warns of a stall — but it is the backstop, not the narrator.
68
+ - **`stage`** at every phase change, **`metric`** for the figures the user cares about as soon as they are known (the brief's phases' FPS and CPU ms/frame, the noise floor, the target, the best so far — update the same label as they move), **`fix`** at every step of the fix loop: `planned` when diagnosed, `trying` while editing, `measuring` while re-capturing, then `kept` or `reverted` with before → after.
69
+ - **Plain language** a non-specialist follows: "Re-measuring the race start with the particle fix", not "runs/fix-3 cold".
70
+ - **End the run every time** — `end` after the report is written, or `end --status stopped|failed --summary "<why>"` when it cannot finish; a run left `running` keeps the page in live mode (the watchdog exits on its own after 12 hours).
71
+ - Subagents that capture or fix get these commands and the slug folder, and write their own `now` lines.
72
+
73
+ ---
74
+
75
+ # How it works
76
+
77
+ `scripts/` holds four Node tools, installed once per project into `<project>/.agents/profile/.tools` — shared by every slug, since it is the tooling, not a run's data (never into the project's own package.json):
78
+
79
+ | Tool | Does |
80
+ |---|---|
81
+ | `profile.mjs` | Launches Chrome (GPU on, fresh profile = cold caches), runs the scenario, records the V8 CPU profile, per-phase allocation profiles, the in-page probe (every frame's CPU work, draws, particles, SceneInstrumentation timers, scene counters, compiled shader count, long animation frames, phase marks), and the source + source map of every sampled script. `--warm true` repeats the scenario in the same browser. `--snapshots true` adds screenshots and the filmstrip |
82
+ | `analyze.mjs` | (`--drill "Class.fn,…"` breaks a function's time into its direct callees, per phase — use it on every heavy library function before deciding what to change.) Maps every sample to its original file / line / class (source maps, then class-span scan of the script, then the config's `sourceRoots` for bundles without maps), assigns owners, charges library time to the nearest code of yours (the render loop is a frame driver and never takes the blame), and writes `analysis.json`: per phase, per second, per function (self, inclusive, callers, "your code behind it"), allocations, worst frames, hot lines, code excerpts. Prints a summary to read |
83
+ | `compare.mjs` | Before → after per phase, owner and function, for the fix loop |
84
+ | `report.mjs` | Builds the dashboard HTML from an analysis, an optional baseline and warm analysis, and the agent's `findings.json`, with the live progress panel at its top |
85
+ | `progress.mjs` | Writes the run's live progress (`start`, `stage`, `now`, `metric`, `fix`, `note`, `end`) and runs the watchdog (`watch`) — see *Live progress*. No dependencies, so it runs before `npm install` |
86
+
87
+ The clock of the CPU profile is tied to the page's clock by a named busy-wait marker, so frames, phase marks and samples line up exactly.
88
+
89
+ ---
90
+
91
+ # Pipeline
92
+
93
+ Read the Babylon Toolkit Agent Reference router and the sub-documents the project's code touches (`node-esm.md` or `classic.md`, `scene-components.md`, `react-framework.md` for a React host, `fusion-networking.md` for networked play) before the first run in a session — unless your prompt already carries those excerpts.
94
+
95
+ ```bash
96
+ PROJ=<absolute web project root> # holds package.json — resolved as in "Which project" below
97
+ SKILL_DIR=<absolute path of this skill's folder>
98
+ PROF="$PROJ/.agents/profile"; TOOLS="$PROF/.tools" # shared by every slug
99
+ SLUG=<slug>; S="$PROF/$SLUG"; DATA="$S/data"; DASHBOARD="$S/dashboard.html"
100
+ ```
101
+
102
+ One folder per profiled moment — everything a slug's runs produce stays inside it:
103
+
104
+ ```
105
+ .agents/profile/
106
+ .tools/ the installed scripts + node_modules (git-ignored, shared)
107
+ <slug>/
108
+ dashboard.html the dashboard — live while a run goes on, the report once it is done
109
+ data/
110
+ progress.js the run's live progress, written by progress.mjs (git-ignored)
111
+ profile.config.json URL, scenario, owner rules (a new slug copies a sibling's owners)
112
+ scenario.mjs the repeatable scenario
113
+ findings.json the diagnosis, each fix's status, before / after, diff
114
+ worktree-at-start.txt the user's uncommitted work when the slug started
115
+ runs/<run>/{cold,warm}/ captures and analyses (git-ignored)
116
+ logs/<run>.log capture logs (git-ignored)
117
+ ```
118
+
119
+ Run every tool from `$DATA` (`cd "$DATA"`): run paths stay short (`runs/baseline`) and the tools read `profile.config.json` there.
120
+
121
+ ## Which project
122
+
123
+ Resolve `$PROJ` before anything else, in this order, and say which project you picked and why in the first update:
124
+
125
+ 1. **`--project:<path>`** — walk up from the path to the nearest folder with a `package.json`.
126
+ 2. **A project named in the brief** — a path, or a folder name ("profile BtMarioKartWeb's race start") that matches a project in or next to the working directory.
127
+ 3. **The working directory** — walk up from it to the nearest `package.json`.
128
+ 4. **One level down** — when the working directory holds no project (e.g. a folder of games), look in its immediate subfolders; use the one game project found.
129
+
130
+ A candidate counts only when it is a **web game**: a `package.json` with a dev/start script and a BabylonJS dependency (`@babylonjs/core`, `babylonjs` or `@babylonjs-toolkit/*`). A `package.json` that is not a game (a tool, a library, the Babylon Toolkit runtime itself) is skipped and the walk goes on. When steps 1–4 find none, or step 4 finds several, **ask the user** with the candidates listed — never guess between projects.
131
+
132
+ ## Phase 0 — Preflight
133
+
134
+ ```bash
135
+ mkdir -p "$TOOLS" "$DATA/runs" "$DATA/logs"
136
+ cp -R "$SKILL_DIR"/scripts/* "$TOOLS/" # refresh on every skill update
137
+ node "$TOOLS/progress.mjs" start "$S" --title "<Project> — <scenario> performance" --brief "<the user's words>" --project "$PROJ" --url "<url>"
138
+ node "$TOOLS/progress.mjs" watch "$S" --watch "$PROJ/src" > "$DATA/logs/watchdog.log" 2>&1 & # the watchdog (see Live progress)
139
+ (cd "$TOOLS" && npm install --silent) # puppeteer-core, source-map-js
140
+ printf '.tools/\n*/data/runs/\n*/data/logs/\n*/data/progress.js\n*/data/previous-dashboard.html\n' > "$PROF/.gitignore"
141
+ git -C "$PROJ" status --short > "$DATA/worktree-at-start.txt" # the user's own uncommitted work
142
+ ```
143
+
144
+ 1. **The game must be served.** Find the dev server (package.json `dev` script, its port) and check it answers; start it in the background if it does not. Content served from elsewhere (a Unity exporter dev server, a CDN) must answer too — read the project's CLAUDE.md / SPEC for how. Profile the **dev server** by default: modules arrive one file each with source maps, so attribution is exact. Mention that React runs in development mode there (its share is inflated); profile a source-mapped production build (`vite build --sourcemap` + `vite preview`) when the React share matters.
145
+ 2. **`profile.config.json`** in `$DATA` (create it if missing; copy `owners` from a sibling slug's config when there is one):
146
+ ```json
147
+ { "projectRoot": "../../../..", "url": "http://localhost:5173/play", "scenario": "scenario.mjs",
148
+ "owners": [ { "match": "/scenes/<project>\\.js", "owner": "kit", "label": "Project script bundle (Unity)", "yours": true,
149
+ "sourceRoots": ["/abs/UnityProject/Assets/Scripts"] } ] }
150
+ ```
151
+ Add an owner rule for every script **the user owns that ships without a source map** — typically the Unity exporter's project bundle (`scenes/<Product>.js`), compiled from TypeScript under the Unity project's `Assets/`. `sourceRoots` lets analysis find the class's `.ts` file and method line. Owners marked `yours` are charged with the library work they trigger.
152
+ 3. **The scenario.** It must play the moment the user says is slow, the way a player would, and mark its phases. Reuse `$DATA/scenario.mjs` when it exists; otherwise copy `templates/scenario.template.mjs` there and adapt it: read the game's code to find what to wait on (a component's phase field, a ready flag) and how to reach it from the page (`window.TOOLKIT.SceneManager.SearchForScriptComponentByName(scene, alias)`, `window.PROJECT.*`). Mark the **reveal** — the moment the loading screen goes away (for a toolkit splash: `#xbabylonjsSplashScreen` gets `opacity: 0`) — as its own phase: games often start their intro behind the splash, and hitches before the reveal are load time, not stutter the player sees. Hold input like a player (keys through `context.keyDown`). If the scenario must keep the game going without a player (a race after the start), hand the player's object to the game's own AI component — never skip or disable work to get there.
153
+ 4. **Other sessions.** List the other agent sessions on this machine (`ListAgents`) and check `git status` / `git log` in every repo you may touch. Another session working in the same project or runtime shares the dev server, the runtime build and the commits: tell it which files you change (and ask it to leave them out of its commits), give a one-line heads-up before restarting a dev server or rebuilding a library it serves, and pause captures while it runs timing-sensitive checks. Its edits also move your numbers — compare runs taken on the same code, and say so in the report when you could not.
154
+ While anyone else edits the project, **never capture on a watching dev server**: one save hot-patches or reloads the game mid-run (the capture logs `WARNING: … restarted` and the report shows a banner). Profile a frozen copy instead: `git archive HEAD | tar -x -C <scratchpad>/snapshot`, copy in your own uncommitted project changes, link `node_modules` to the live project's, and serve it on a spare port with a config that wraps the project's — `mergeConfig(base, { cacheDir: ".vite-profile-cache", server: { watch: null, hmr: false, fs: { strict: false } } })` (its own optimizer cache, since `node_modules` is shared). Warm it once, then capture against that port. Library builds the project links to (a runtime) are still live — keep the heads-up for those.
155
+ 5. **Smoke run** (`node "$TOOLS/profile.mjs" --out runs/smoke --args settle=15 --snapshots true`, from `$DATA`): look at the screenshots and confirm the scenario really did what the user described (the countdown ran, the player moved, the particles fired). Fix the scenario before measuring anything.
156
+
157
+ ## Phase 1 — Measure the baseline
158
+
159
+ `progress.mjs stage "$S" baseline`, a `now` line before each capture and analysis, and `metric`s for the baseline figures and the noise floor as soon as they are known.
160
+
161
+ ```bash
162
+ cd "$DATA" # --url / --scenario default to profile.config.json here
163
+ node "$TOOLS/profile.mjs" --out runs/baseline --warm true --args settle=90 > logs/baseline.log 2>&1
164
+ node "$TOOLS/profile.mjs" --out runs/baseline-2 --args settle=90 > logs/baseline-2.log 2>&1 # noise
165
+ node "$TOOLS/analyze.mjs" --capture runs/baseline/cold > runs/baseline/cold/summary.txt
166
+ node "$TOOLS/analyze.mjs" --capture runs/baseline/warm > runs/baseline/warm/summary.txt
167
+ node "$TOOLS/analyze.mjs" --capture runs/baseline-2/cold --quiet true
168
+ node "$TOOLS/compare.mjs" --before runs/baseline/cold/analysis.json --after runs/baseline-2/cold/analysis.json # = the noise floor
169
+ ```
170
+
171
+ **A capture right after a dev-server restart is not comparable:** Vite's first load after `--force` re-optimizes dependencies and transforms every module (seconds of `(program)` time in the first phase). Load the page once (a throwaway headless visit) before every capture that follows a restart.
172
+
173
+ Read `summary.txt` in full. Check first: the engine is the one the game uses (WebGPU vs WebGL — a fallback changes everything), the console errors, and that each phase lasted as long as it should. **The noise floor** is the per-phase FPS and CPU ms/frame difference between the two baseline captures; a fix must beat it.
174
+
175
+ ## Phase 2 — Diagnose
176
+
177
+ `progress.mjs stage "$S" diagnose`; a `now` line for each drill or census; a `fix … --status planned` for each confirmed finding.
178
+
179
+ Work from the brief's phases outward. For each phase that misses the target:
180
+
181
+ 1. **Is the main thread the limit?** `busy` near 100% with CPU ms/frame near the frame interval → CPU-bound: find the code. `busy` low with long frame intervals → GPU-bound or waiting: draw calls, fill rate, render scale (the toolkit's `bt-optimize` skill owns scene-side GPU work).
182
+ 2. **Visible or hidden?** Judge stutter only in phases after the reveal mark; a worst frame behind the loading screen costs load time (still worth shortening) but the player never sees it. Check the filmstrip when unsure.
183
+ 3. **Owners.** Which owner grew in this phase compared with the calm phases? A phase that is slow only cold (compare the warm summary) is first-use work: downloads, decoding, shader compilation, pipeline creation, JIT.
184
+ 4. **Subtrees, then functions.** In `inclusiveTop` (frame shells removed) find the subtree that dominates, then its heaviest self-time functions and their `callers` / `enteredFrom` / `yours` columns: those name the code that asks for the work. Re-run `analyze.mjs --drill "<function>"` to split a heavy function into its callees per phase — a cost that **grows** phase by phase while the scene stays the same is accumulating state (more systems switched on, caches invalidated), not load.
185
+ 5. **Count, live, when the profile cannot say why.** A function that is cheap per call but runs too often needs a census: copy `templates/census.template.mjs` to the scratchpad (outside the project), adapt how it reaches the moment, and run it with `--args method=TransformNode.prototype.computeWorldMatrix,seconds=1`: it wraps the method for that long and counts calls per object with a sample stack. It names the object and the caller in one run — the Mario Kart run found 16,000 world-matrix recomputes per frame this way.
186
+ 6. **Read the code.** Open the files and lines named (`yoursTop`, `excerpts`, `hotLines`) and the library function the time lands in. Find the mechanism — what runs, how often, on how many objects, why. A finding is not done until you can say *why* it costs what it costs.
187
+ 7. **Worst frames** name the spikes (a spawn, a burst, a compile) that averages hide.
188
+ 8. **Allocations**: phase `heap` lists show who feeds the garbage collector while playing.
189
+
190
+ Write `$DATA/findings.json` (schema in `scripts/report.mjs`): per finding a severity, the phases, the cost in ms/frame and % of the phase, the cause in plain language, the evidence (numbers from the analysis), the code locations, the planned fix. Rank by the time it would win in the phases the user cares about.
191
+
192
+ ## Phase 3 — Fix, one at a time (skipped with `--analyze`)
193
+
194
+ `progress.mjs stage "$S" fix`; each fix moves `trying` → `measuring` → `kept` or `reverted`, with before → after (see *Live progress*).
195
+
196
+ For each finding, highest win first:
197
+
198
+ 1. **Change the cause, not the symptom.** Prefer the smallest change that removes the work: cache instead of recompute, compute once instead of per frame, per object instead of per child, configure the library (freeze, static, refresh rate, capacity), pool instead of create, pre-warm at load instead of at first use. Follow the Agent Reference's coding rules; never disable a feature the user can see or hear to win time.
199
+ 2. **Where the code lives decides how it ships.** Project source: edit it; the dev server reloads. The Babylon Toolkit runtime, when the user owns its source (they say so, or its repo is theirs): fix it there with a regression test in its own test suite, run the suites that touch the area, rebuild the way that repo documents (never a step that copies the build into other repos), and restart the dev server with `--force` so it serves the new build. A project-owned bundle (Unity exporter project bundle): edit its source under the Unity project and rebuild the bundle the way the project documents (e.g. `unity command bt_build_project`), then confirm the served bundle changed. The Babylon Toolkit runtime / BabylonJS / other libraries: do not edit — change the calling code, or record the defect as a finding for the library's owner.
200
+ 3. **Re-measure** with the same scenario and flags (warm the dev server first if it restarted), into `runs/fix-<n>-<short-name>`; analyze; `compare.mjs --before <last kept> --after <this> --focus "<the functions the fix targets>"`.
201
+ 4. **Keep or revert.** Keep when the targeted cost fell and the phase's CPU ms/frame or FPS improved beyond the noise floor without another phase getting worse. Otherwise revert this fix only (never touch lines that were already uncommitted at the start) and record it as `reverted` with the numbers. Update `findings.json` (`status`, `before`, `after`, `diff`).
202
+ 5. Run the project's typecheck / tests after every kept fix that touched code they cover.
203
+
204
+ Stop when the target FPS is met in the brief's phases, `--max-fixes` is reached, or what is left is not worth the change (say what it would take).
205
+
206
+ ## Phase 4 — Verify
207
+
208
+ `progress.mjs stage "$S" verify`, with a `now` line for the final captures, the tests and the screenshots.
209
+
210
+ ```bash
211
+ node "$TOOLS/profile.mjs" --out runs/final --warm true --args settle=90 > logs/final.log 2>&1
212
+ node "$TOOLS/analyze.mjs" --capture runs/final/cold > runs/final/cold/summary.txt
213
+ node "$TOOLS/analyze.mjs" --capture runs/final/warm --quiet true
214
+ ```
215
+
216
+ With `--snapshots` (or when any kept fix could change what is drawn): capture `runs/final-shots` and, on the original code, `runs/baseline-shots` with `--snapshots true` (the smoke run's shots serve as the "before" when the code has already changed), and compare the phase screenshots side by side — same effects, same lighting, same HUD. Typecheck / build and tests must pass; the console must hold no new errors.
217
+
218
+ ## Phase 5 — Report
219
+
220
+ `progress.mjs stage "$S" report`.
221
+
222
+ ```bash
223
+ node "$TOOLS/report.mjs" --analysis runs/final/cold/analysis.json --baseline runs/baseline/cold/analysis.json \
224
+ --warm runs/final/warm/analysis.json --findings findings.json --title "<Project> — <scenario> performance" \
225
+ [--snapshots runs/final-shots/cold --snapshots-before runs/baseline-shots/cold] # writes $DASHBOARD (../dashboard.html)
226
+ ```
227
+
228
+ (With `--analyze`: `--analysis runs/baseline/cold/analysis.json --warm runs/baseline/warm/analysis.json`.) Then end the run — `node "$TOOLS/progress.mjs" end "$S" --summary "<the verdict in one sentence>"` — so the page leaves live mode and the watchdog exits. Open the report in the browser, screenshot it at desktop and phone width, and check it renders with no console errors. Then tell the user: the verdict in two sentences, each finding with its before → after, what was reverted and why, what remains and what it would take, and the report path.
229
+
230
+ ---
231
+
232
+ # Reading BabylonJS hot spots
233
+
234
+ What a heavy function usually means, and where to look. Always confirm with `callers` / `yours` before acting.
235
+
236
+ | Hot in the profile | Usually means | Look at |
237
+ |---|---|---|
238
+ | `TransformNode.computeWorldMatrix` (deep self-recursion) | **Forced recomputes** (`computeWorldMatrix(true)`): a forced recompute forces every ancestor and bumps its child-update id, which marks every sibling subtree out of date, so the render and the next forced call recompute everything again — a feedback loop. Count recomputes per node live before blaming the scene size | Who calls `computeWorldMatrix(true)` per frame / per physics step (Havok pre-step, sync helpers, animator root motion, particle emitters): one forced call per frame on any node under a level's root invalidates the whole level. Probe the level root's `_childUpdateId` per frame and the forcing stacks. Fix: read the current matrix with `TOOLKIT.Utilities.CurrentWorldMatrix(node)` (recomputes only the changed nodes of the chain); static props never frozen |
239
+ | `HavokPlugin.setPhysicsBodyTransformation` / `_getTransformInfos` | Havok TELEPORT pre-step: each body whose `disablePreStep` is false is force-synced from its node before every step. Should only be bodies that move by transform (kinematic) | Count bodies by motion type × pre-step live. Static colliders with pre-step on are pure cost (the Babylon Toolkit runtime turned it on for every exported collider before 9.30.x) |
240
+ | `Node._getDescendants` / `getChildMeshes` / `getChildren` | A hierarchy walk — expensive when done per frame or per object | Per-frame lookups that should be cached at start |
241
+ | `ProcessIncludes`, `MaterialPluginManager` code injection, `Effect` / `ShaderProcessor`, shader regexes, `glslang` / `twgsl` wasm | A **new shader variant** being built: a material's defines changed, a new material / particle system appeared, a plugin toggled | New materials or defines appearing after load (first particle burst, boost flames, item effects) — pre-warm them at load |
242
+ | `WebGPUEngine._draw`, `getBindGroups`, `setSubData`, `UniformBuffer.update*`, `Mesh.render`, `SubMesh.render` | Per-draw CPU cost: the frame has too many draws (meshes × passes) | Draw counts per phase, shadow casters, hidden-but-rendered meshes, instancing / merging (`bt-optimize`) |
243
+ | `ShadowGenerator._renderSubMeshForShadowMap` | Shadow passes re-drawing casters every frame | Casters list, refresh rate, number of shadowed lights |
244
+ | `Scene._evaluateActiveMeshes` | Culling every mesh every frame | `freezeActiveMeshes` for static content, `alwaysSelectAsActiveMesh`, mesh count |
245
+ | `ThinParticleSystem.animate` → `Buffer.updateDirectly` / `WebGPUBufferManager.setRawData` | A **started system with zero particles still uploads its whole vertex buffer** every frame (Babylon reads a vertex count of 0 as "all"). Cost grows as more effects get their first play and stay started while idle | Started-but-empty systems × capacity (census `particleSystems`); the toolkit's `ShurikenParticles.SkipEmptyVertexUploads` guard |
246
+ | `ParticleSystem.animate` / `_update`, `ShurikenParticles.sys._update` | CPU particle simulation: emit rate × lifetime × systems | Systems started together at an event, capacity, GPU particles |
247
+ | `(garbage collector)` | Short-lived allocations per frame | Phase `heap` lists: vectors / arrays / closures created in update loops |
248
+ | `(program)` | Browser-internal work (parse, compile, style, layout, GPU IPC) | Large during load = script parse / compile; during play = DOM / layout churn (HUD) |
249
+
250
+ ---
251
+
252
+ # Files
253
+
254
+ | Path | Holds |
255
+ |---|---|
256
+ | `.agents/profile/.tools/` | The installed scripts and their node_modules, shared by every slug (git-ignored) |
257
+ | `.agents/profile/<slug>/dashboard.html` | The dashboard — follows the run live, then holds the report |
258
+ | `.agents/profile/<slug>/data/progress.js` | The run's live progress: status, stages, fixes, numbers, what is happening now (written only by `progress.mjs`; git-ignored) |
259
+ | `.agents/profile/<slug>/data/profile.config.json` | URL, scenario, owner rules and source roots |
260
+ | `.agents/profile/<slug>/data/scenario.mjs` | The repeatable scenario |
261
+ | `.agents/profile/<slug>/data/findings.json` | The diagnosis and each fix's status, before / after and diff |
262
+ | `.agents/profile/<slug>/data/runs/<run>/{cold,warm}/` | `capture.json`, `cpu.cpuprofile` (opens in DevTools), `heap/`, `scripts/`, `analysis.json`, `summary.txt`, `shots/`, `filmstrip/` (git-ignored) |
263
+ | `.agents/profile/<slug>/data/logs/` | Capture logs (git-ignored) |
264
+
265
+ # Troubleshooting
266
+
267
+ | Symptom | Cause / fix |
268
+ |---|---|
269
+ | `engine` is WebGL when the game asks for WebGPU, or the adapter is SwiftShader | Chrome fell back: the numbers do not represent the user's machine. Run `--headed true` or check the GPU flags |
270
+ | No frames recorded | The page never set `window.BABYLON` (a pure ESM build without the toolkit globals): expose the engine on `window.BABYLON.EngineStore` or extend the probe |
271
+ | A phase lasts far longer than expected | The scenario waited on the wrong condition — check its log lines and the screenshots |
272
+ | Functions show `(anonymous)` in a bundle | Minified without names and without a source map: profile a dev build or a `--sourcemap` build |
273
+ | Capture logs `WARNING: … restarted`, a phase shows 0 FPS, or the compiled-shader count drops mid-run | The dev server reloaded or hot-patched the game because someone saved a file. Discard the run and capture a frozen snapshot (Phase 0 › Other sessions) |
274
+ | The profile is smooth but the user feels a stutter | The scenario does not play the way the user does. Close the gap one difference at a time: `--headed true` (a visible window), `--autoplay gesture` (audio stays locked until the first key, as in a normal browser — the unlock can be the hitch), no idle waits where the player acts at once (throttle the moment the loading screen lifts), the same build and URL the user plays (dev server vs a deployed site). If it is still smooth, **let the user drive**: give the scenario a watch-only mode (`--args driver=human`: it loads the moment cold, marks progress such as distance travelled, and sends no keys), run it `--headed true`, and tell the user exactly when it is their turn and for how long |
275
+ | Numbers jump between runs | Background load on the machine, a different rival / random seed, or a cold vs warm mix-up: compare cold with cold, and use the noise floor |