@babylonjs-toolkit/agent 1.1.66 → 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.
@@ -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 |