@babylonjs-toolkit/agent 1.1.85 → 1.1.88

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.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: bt-profile
3
- description: "The Babylon Toolkit Profile Skill finds what makes a web app slow and lists the fixes (applying them one at a time with --auto-fix) — built for BabylonJS / Babylon Toolkit games, and just as usable on any front end with no Babylon in it (point it at a URL and the project folder). 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 and lists the fixes — each with its expected gain and risk, ready to spec one by one or as a group with bt-spec, with a bt-recon command per subsystem that maps the code behind them for the spec — and, with --recon, runs bt-recon itself to map the code behind the slow moment and confirm each inferred cause in the code; with --auto-fix (which always turns --recon on), applies them one at a time, re-measuring the same scenario to prove each 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 --auto-fix the race start crawls`, `/bt-profile http://localhost:5173/play --scenario level-start`)."
3
+ description: "The Babylon Toolkit Profile Skill finds what makes a web app slow and lists the fixes (applying them one at a time with --auto-fix) — built for BabylonJS / Babylon Toolkit games, and just as usable on any front end with no Babylon in it (point it at a URL and the project folder). 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 every late-stutter source after the loading screen lifts (the Babylon Toolkit's late shader compiles with their cause and render pass, GPU pipelines, textures, downloads, audio decodes, garbage collection), 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 and lists the fixes — each with its expected gain and risk, ready to spec one by one or as a group with bt-spec, with a bt-recon command per subsystem that maps the code behind them for the spec — and, with --recon, runs bt-recon itself to map the code behind the slow moment and confirm each inferred cause in the code; with --auto-fix (which always turns --recon on), applies them one at a time, re-measuring the same scenario to prove each 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 --auto-fix the race start crawls`, `/bt-profile http://localhost:5173/play --scenario level-start`)."
4
4
  allowed-tools: Read, Grep, Glob, Edit, Write, Bash, Agent, Task
5
5
  ---
6
6
 
@@ -100,7 +100,7 @@ The clock of the CPU profile is tied to the page's clock by a named busy-wait ma
100
100
 
101
101
  # Pipeline
102
102
 
103
- 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.
103
+ 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, `networking.md` for networked play) before the first run in a session — unless your prompt already carries those excerpts.
104
104
 
105
105
  The names below are shorthand for absolute paths used throughout this skill — write them out in every command (or set them at the top of the same command): most agent shells keep no variables between commands.
106
106
 
@@ -208,10 +208,28 @@ Work from the brief's phases outward. For each phase that misses the target:
208
208
  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. GPU pipelines need no census: every capture records each shader module / pipeline / program with its time (`gpuCompiles` in `analysis.json`, per phase in the summary); line them up with the marks and the scenario's own progress (a distance, a spawn) to name what first drew them.
209
209
  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.
210
210
  7. **Worst frames** name the spikes (a spawn, a burst, a compile) that averages hide.
211
+ 8. **Late stutter — read the summary's `LATE STUTTER` section every run** (the report's *Late stutter — after the reveal*). The reveal comes from the Babylon Toolkit itself (`SceneManager.OnSceneRevealedObservable`), else the scenario's `reveal` mark. Every hitch after it (a frame over 3× the median and 50 ms) is listed with its likely cause and suspects. On a toolkit game the probe also listens to the toolkit's late-compile detector, which names every shader or pipeline built after the reveal by mesh and material, particle system, post process or render pass, turning it on even in a production build. **A finished game has zero late compiles**, so each cause is a finding, even under the WebGPU safety net, where a late pipeline shows as a frame or two of pop-in instead of a freeze. Read them three ways:
212
+ - **By render pass first.** Many compiles in one pass other than `main` (`Camera <name>.Rig` is the camera the toolkit creates for a Unity camera; or a render target) mean a camera or target the pre-warm never drew. Toolkit 1.1.88+ warms every screen camera in the scene at the reveal (`SceneShaderWarmup.WarmAllCamerasOnReveal`, on by default). So the cause is a camera or target created after the reveal (create it at load), the switch turned off, or a toolkit older than 1.1.88, which warms only the camera active while it runs. One fix covers the whole pass. BtMarioKartWeb's race start had 34 late compiles and a 1.1 s countdown freeze on the old toolkit, every one in the race camera's pass, because the intro camera was the one active during the pre-warm; 1.1.88 removed them.
213
+ - **By cause.** Particles mean a system never pre-warmed (`WarmParticleSystem`, or the prefab that spawns it registered with `WarmPrefab`). A mesh spawned during play means its prefab was never registered (`WarmPrefab`). A mesh already in the scene means a variant change during play, covered by the toolkit's authoring rules: a light added or enabled, fog or clip planes toggled, a first instance, a texture transform moved off the identity, a look-alike material. Post processes and render passes created during play should be created at load.
214
+ - **The other first-use sources.** Downloads finished during play (a texture, model or sound fetched late: preload it behind the splash). Textures created during play (first-use uploads). Audio decodes (decode at load). A GC spike (allocation churn at a moment: phase `heap`). Scene growth (content created during play: pool it or create it at load). A page without the toolkit still gets every hitch, its GPU pipelines, downloads, textures and audio decodes; only the causes of its compiles are missing.
215
+
216
+ Re-capture with `--gpu-cold true` whenever a hitch or a late compile appears: it makes every capture a first visit, so the fix can be proven.
211
217
  8. **Allocations**: phase `heap` lists show who feeds the garbage collector while playing.
212
218
 
213
219
  9. **Trace every inferred cause in the code** (with `--recon`). Group the findings by the code they live in (`subsystem`). For each group with a finding whose cause is still `inferred`, run a quick bt-recon of that subsystem (*Recon* below), then re-read the finding against it: the cause becomes `confirmed` with `path:line` evidence, or the finding changes. Copy into each finding's `guards` what the recon says a change there must not break: callers, invariants, the tests that cover it.
214
220
 
221
+ **Where each late-stutter fix goes** — say it in the finding's `fix`. The Agent Reference's *Prewarming Content* guide (`references/prewarming-content.md`) is the authority on registrations: register only what a late-compile record names, one `WarmPrefab` per container, never speculatively.
222
+
223
+ | Cause | Fixed in | How |
224
+ |---|---|---|
225
+ | Content spawned during play that was never registered (a prefab, an idle particle system) | Game code | `--auto-fix`: `WarmPrefab` / `WarmParticleSystem` before the reveal — small, code-only, proven by a GPU-cold re-capture |
226
+ | A variant change during play (a light, fog, an instance, a texture transform, a look-alike material) | The Unity scene or the game's setup | A spec (`bt-spec` from the report): Unity authoring and a re-export, following the toolkit's authoring rules |
227
+ | A camera or render target created after the reveal | Game code | Create it at load and switch to it later |
228
+ | A case the pre-warm misses | The Babylon Toolkit runtime | The user owns it: fix it there with a regression test (Phase 3 step 2), or spec it in the runtime repo |
229
+ | A late download, decode or texture upload | Game code or the export settings | Preload behind the splash, or ship it in the scene |
230
+
231
+ `bt-optimize` is not the tool for late stutter: it lowers the GPU cost of every frame (bakes, merges, fewer draws), not one-off first-use work.
232
+
215
233
  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 and its `confidence` (`confirmed` once traced in the code, else `inferred`), the evidence (numbers from the analysis), the code locations, the `subsystem` it lives in (fixes in the same code share one name, and so one recon), its `recon` path when one exists, its `guards`, and the planned fix. Rank by the time it would win in the phases the user cares about.
216
234
 
217
235
  ## Phase 3 — Fix, one at a time (only with `--auto-fix`)
@@ -296,6 +314,8 @@ What a heavy function usually means, and where to look. Always confirm with `cal
296
314
  | `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) |
297
315
  | `Node._getDescendants` / `getChildMeshes` / `getChildren` | A hierarchy walk — expensive when done per frame or per object | Per-frame lookups that should be cached at start |
298
316
  | **Long frame, almost no script** — a `wait` in WORST FRAMES (LoAF `blockingMs` ≈ 0), right after new pipelines / programs were created (`pipelines near`, `gpu:` per phase) | **The GPU process compiling pipelines** for shaders drawn for the first time. The main thread is idle, so the CPU profile shows nothing; the browser's and the OS's shader caches hide it on later visits, so it is a **first-visit** stutter — every capture after the first may be smooth | Reproduce with `--gpu-cold true`. Which materials / effects are first drawn after the loading screen lifts (the car, the road 10 m in, a first particle burst). Fix: compile them behind the loading screen — wait for the scene and those materials to be ready (`scene.whenReadyAsync()`, `material.forceCompilationAsync(mesh)`, the toolkit's shader warm-up) and render a few frames hidden before revealing, instead of revealing on a fixed timer |
317
+ | A hitch after the reveal with toolkit late compiles near it (`LATE STUTTER`) | **A shader the pre-warm missed** — the cause names it: the mesh and material, particle system, post process or render pass | By render pass first (one pass other than `main` = a camera or target the pre-warm never drew), then by cause — see Phase 2 › *Late stutter* |
318
+ | A hitch after the reveal with a download, texture creation or audio decode near it | **First-use asset work during play**: fetched, decoded or uploaded on that frame | Preload it behind the splash; create its texture or decode its sound at load |
299
319
  | `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 |
300
320
  | `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`) |
301
321
  | `ShadowGenerator._renderSubMeshForShadowMap` | Shadow passes re-drawing casters every frame | Casters list, refresh rate, number of shadowed lights |
@@ -306,6 +326,7 @@ What a heavy function usually means, and where to look. Always confirm with `cal
306
326
  | `(program)` | Browser-internal work (parse, compile, style, layout, GPU IPC) | Large during load = script parse / compile; during play = DOM / layout churn (HUD) |
307
327
  | React (`react` owner) above ~0% during play, `jsxDEV` among the heaviest functions | A HUD re-rendering every frame: speed, timers, needles or bars pushed through React state, props or per-frame EventBus messages | The HUD's frame loop (`yours` names the component). Fix: the Agent Reference's *Live HUD Values — ENFORCED* — render once, one frame loop, write through refs only on change. Budget: ≤ 0.5 ms/frame, `react` near 0% in play phases |
308
328
  | `AdvancedDynamicTexture._checkUpdate` / `_render`, `updateDynamicTexture` every frame | A Babylon GUI control assigned every frame: each change re-lays out, redraws and re-uploads the whole GUI texture | Assign a control only when its shown value changes (*Game UI Performance — ENFORCED*) |
329
+ | A UI frame loop (`requestAnimationFrame` / `useFrameLoop` callback, `yours`) busy during a load, menu, pause or at-rest phase; `Recalculate Style` / `Layout` every frame with nothing moving | Per-frame code where no per-frame update is needed: a splash, menu or landing page animated from JavaScript, a HUD loop still running behind a modal or while paused, a scroll loop rewriting the page at rest, `width` / `top` animated | Move decorative motion to CSS `transform` / `opacity`; stop or skip the loop while its UI is hidden; skip writes at rest; throttle readouts nobody reads at 60 Hz (the Agent Reference's `ui-design-system.md` › *Per frame or not*) |
309
330
 
310
331
  ---
311
332
 
@@ -467,6 +467,129 @@ function summarizeLoafs(loafs, top) {
467
467
  return { longFrames: (loafs || []).length, scripts: [...groups.values()].sort((a, b) => b.ms - a.ms).slice(0, top).map((group) => ({ ...group, ms: round(group.ms) })) };
468
468
  }
469
469
 
470
+ /** Frames slower than this many times the run's median frame interval, and at least HITCH_MIN_MS, count as hitches. */
471
+ const HITCH_FACTOR = 3;
472
+ /** The shortest frame interval (ms) that counts as a hitch the player can see. */
473
+ const HITCH_MIN_MS = 50;
474
+
475
+ /**
476
+ * The late-stutter view: everything that happened for the first time after the game was revealed, and the hitches it
477
+ * lined up with. The reveal is the Babylon Toolkit's own (OnSceneRevealedObservable), else the scenario's `reveal` mark.
478
+ * Every hitch after it gets its suspects — late compiles with their cause, GPU pipelines, textures created, downloads
479
+ * that finished, audio decodes, garbage collection, scene growth and the script that ran — and a likely cause.
480
+ * @returns {object|null} null when the run has no frames
481
+ */
482
+ function lateStutter(probe, frames, counters, prepared, info, phases, startMs, endMs) {
483
+ if (!frames.length) return null;
484
+ const toolkitReveal = (probe.reveals || []).find((reveal) => reveal.at != null && reveal.at >= startMs);
485
+ const revealMark = (probe.marks || []).find((mark) => /reveal/i.test(mark.name));
486
+ const revealAt = toolkitReveal ? toolkitReveal.at : revealMark ? revealMark.at : null;
487
+ const after = (at) => at != null && (revealAt == null || at >= revealAt) && at <= endMs;
488
+ const t = (at) => (at == null ? null : round((at - startMs) / 1000, 2));
489
+
490
+ // Late compiles the toolkit named, grouped by what caused them.
491
+ const groups = new Map();
492
+ for (const record of probe.lateCompiles || []) {
493
+ const key = record.cause || `${record.causeKind} (no cause)`;
494
+ if (!groups.has(key)) {
495
+ groups.set(key, {
496
+ cause: key, causeKind: record.causeKind, meshName: record.meshName || "", materialName: record.materialName || "",
497
+ particleSystemName: record.particleSystemName || "", postProcessName: record.postProcessName || "", renderPassName: record.renderPassName || "",
498
+ effects: new Set(), kinds: {}, count: 0, firstT: null, firstMsAfterReveal: null,
499
+ });
500
+ }
501
+ const group = groups.get(key);
502
+ group.count++;
503
+ group.kinds[record.kind] = (group.kinds[record.kind] || 0) + 1;
504
+ if (record.effectName) group.effects.add(record.effectName);
505
+ const recordT = record.at != null ? t(record.at) : null;
506
+ if (group.firstT == null || (recordT != null && recordT < group.firstT)) group.firstT = recordT;
507
+ if (group.firstMsAfterReveal == null || record.msSinceReveal < group.firstMsAfterReveal) group.firstMsAfterReveal = round(record.msSinceReveal, 0);
508
+ }
509
+ const lateCompiles = [...groups.values()].map((group) => ({ ...group, effects: [...group.effects] })).sort((a, b) => b.count - a.count);
510
+ // The same late compiles by render pass: many compiles in one pass other than the main one mean a camera, rig or render
511
+ // target first drawn after the reveal — the pre-warm builds pipelines only for the passes it draws.
512
+ const passes = new Map();
513
+ for (const record of probe.lateCompiles || []) {
514
+ const name = record.renderPassName || "(unknown pass)";
515
+ const pass = passes.get(name) || { pass: name, count: 0, causes: new Set(), firstMsAfterReveal: null };
516
+ pass.count++;
517
+ pass.causes.add(record.cause || record.causeKind);
518
+ if (pass.firstMsAfterReveal == null || record.msSinceReveal < pass.firstMsAfterReveal) pass.firstMsAfterReveal = round(record.msSinceReveal, 0);
519
+ passes.set(name, pass);
520
+ }
521
+ const lateCompilePasses = [...passes.values()].map((pass) => ({ ...pass, causes: pass.causes.size })).sort((a, b) => b.count - a.count);
522
+
523
+ // Frame intervals: a hitch is a frame far slower than the run's typical one.
524
+ const intervals = [];
525
+ for (let index = 1; index < frames.length; index++) intervals.push(frames[index].at - frames[index - 1].at);
526
+ const sorted = [...intervals].sort((a, b) => a - b);
527
+ const median = sorted.length ? sorted[Math.floor(sorted.length / 2)] : 16.7;
528
+ const threshold = Math.max(HITCH_MIN_MS, median * HITCH_FACTOR);
529
+ const hitchFrames = [];
530
+ for (let index = 1; index < frames.length; index++) {
531
+ const interval = frames[index].at - frames[index - 1].at;
532
+ if (interval >= threshold && after(frames[index].at)) hitchFrames.push({ from: frames[index - 1].at, to: frames[index].at, intervalMs: interval });
533
+ }
534
+ const counterAt = (at) => {
535
+ let found = null;
536
+ for (const counter of counters || []) { if (counter.at <= at) found = counter; else break; }
537
+ return found;
538
+ };
539
+ const inWindow = (list, from, to) => (list || []).filter((entry) => entry.at != null && entry.at >= from && entry.at <= to);
540
+ const hitches = hitchFrames.sort((a, b) => b.intervalMs - a.intervalMs).slice(0, 25).map((hitch) => {
541
+ const aggregate = aggregateWindow(prepared, info, hitch.from, hitch.to);
542
+ const gcMs = aggregate.owners.get("gc") || 0;
543
+ const compiles = inWindow(probe.lateCompiles, hitch.from - 1000, hitch.to);
544
+ const pipelines = inWindow(probe.gpuCompiles, hitch.from - 2000, hitch.to).filter((entry) => entry.kind !== "shaderModule").length;
545
+ const textures = inWindow(probe.textures, hitch.from - 500, hitch.to);
546
+ const downloads = inWindow(probe.resources, hitch.from - 1000, hitch.to);
547
+ const decodes = (probe.audioDecodes || []).filter((entry) => entry.at >= hitch.from - 1000 && entry.startAt <= hitch.to);
548
+ const before = counterAt(hitch.from - 500);
549
+ const afterCounter = counterAt(hitch.to + 600);
550
+ const growth = {};
551
+ if (before && afterCounter) {
552
+ for (const name of ["meshes", "materials", "particleSystems", "textures"]) {
553
+ const delta = (afterCounter[name] ?? 0) - (before[name] ?? 0);
554
+ if (delta > 0) growth[name] = delta;
555
+ }
556
+ }
557
+ const scriptMs = aggregate.busyMs - gcMs;
558
+ // The likely cause, strongest evidence first; the agent confirms it.
559
+ let likely = "GPU or browser work (little script, nothing new)";
560
+ if (compiles.length || (pipelines && scriptMs < hitch.intervalMs * 0.4)) likely = "shader / pipeline compile";
561
+ else if (gcMs >= hitch.intervalMs * 0.3) likely = "garbage collection";
562
+ else if (downloads.length || decodes.length || textures.length) likely = "first-use asset: download, decode or texture upload";
563
+ else if (Object.keys(growth).length) likely = "content created during play";
564
+ else if (scriptMs >= hitch.intervalMs * 0.5) likely = "script";
565
+ const phase = phases.find((candidate) => hitch.to >= candidate.from && hitch.to < candidate.to);
566
+ return {
567
+ t: t(hitch.to), msAfterReveal: revealAt != null ? round(hitch.to - revealAt, 0) : null, phase: phase ? phase.name : null,
568
+ intervalMs: round(hitch.intervalMs), scriptMs: round(scriptMs), gcMs: round(gcMs), likely,
569
+ lateCompiles: [...new Set(compiles.map((record) => record.cause || record.causeKind))].slice(0, 6), lateCompileCount: compiles.length,
570
+ pipelines, textures: textures.length, downloads: downloads.slice(0, 5).map((entry) => ({ name: entry.name.split(/[?#]/)[0].split("/").slice(-1)[0] || entry.name, type: entry.type, kb: entry.kb })),
571
+ audioDecodes: decodes.length, growth,
572
+ top: [...aggregate.self].sort((a, b) => b[1] - a[1]).slice(0, 4).map(([key, ms]) => ({ name: aggregate.symbols.get(key).name, owner: aggregate.symbols.get(key).owner, ms: round(ms) })),
573
+ yours: [...aggregate.responsible.values()].sort((a, b) => b.totalMs - a.totalMs).slice(0, 3).map((blame) => ({ name: blame.symbol.name, file: blame.symbol.file, line: blame.symbol.line, ms: round(blame.totalMs) })),
574
+ };
575
+ }).sort((a, b) => a.t - b.t);
576
+
577
+ const laterDownloads = (probe.resources || []).filter((entry) => after(entry.at)).sort((a, b) => b.kb - a.kb).slice(0, 15)
578
+ .map((entry) => ({ t: t(entry.at), name: entry.name, type: entry.type, kb: entry.kb, ms: entry.ms }));
579
+ return {
580
+ revealT: t(revealAt), revealSource: toolkitReveal ? "toolkit" : revealMark ? `mark "${revealMark.name}"` : null,
581
+ toolkit: probe.toolkit || null,
582
+ medianFrameMs: round(median), hitchThresholdMs: round(threshold),
583
+ hitchCount: hitchFrames.length, hitchMs: round(hitchFrames.reduce((sum, hitch) => sum + hitch.intervalMs, 0)),
584
+ hitches,
585
+ lateCompileCount: (probe.lateCompiles || []).length, lateCompiles, lateCompilePasses,
586
+ pipelinesAfterReveal: (probe.gpuCompiles || []).filter((entry) => entry.kind !== "shaderModule" && after(entry.at)).length,
587
+ texturesAfterReveal: (probe.textures || []).filter((entry) => after(entry.at)).length,
588
+ audioDecodesAfterReveal: (probe.audioDecodes || []).filter((entry) => after(entry.at)).length,
589
+ downloadsAfterReveal: laterDownloads,
590
+ };
591
+ }
592
+
470
593
  /** Plain-language signals the agent should look at first. They point; the agent diagnoses. */
471
594
  function signals(analysis) {
472
595
  const notes = [];
@@ -488,6 +611,18 @@ function signals(analysis) {
488
611
  notes.push(`${waits.length} frame(s) of ${waits.map((frame) => `${frame.intervalMs} ms at ${frame.t}s`).slice(0, 4).join(", ")} were spent waiting, not running script (main thread ${waits.map((frame) => frame.scriptMs).slice(0, 4).join(" / ")} ms)` +
489
612
  (withCompiles.length ? ` — ${withCompiles.length} of them right after new GPU pipelines / programs were created: the GPU process compiling shaders.${analysis.gpuCold ? " This capture was GPU-cold (--gpu-cold), as on a first visit." : " A later visit may hide it (shader caches): confirm with --gpu-cold true."}` : ` — GPU-bound frames or browser work; check draws and the GPU timers.`));
490
613
  }
614
+ const late = analysis.lateStutter;
615
+ if (late && late.lateCompileCount) {
616
+ notes.push(`${late.lateCompileCount} shader / pipeline compile(s) after the reveal${late.revealT != null ? ` (${late.revealT}s)` : ""}, from ${late.lateCompiles.length} cause(s): ${late.lateCompiles.slice(0, 4).map((group) => `${group.cause} ×${group.count}`).join("; ")}. Each is a first-use stutter the pre-warm missed (see LATE STUTTER).`);
617
+ } else if (late && late.pipelinesAfterReveal) {
618
+ notes.push(`${late.pipelinesAfterReveal} GPU pipelines / programs were created after the reveal${late.toolkit ? "" : " (no Babylon Toolkit late-compile detector on this page, so no causes)"} — first-use shader work during play.`);
619
+ }
620
+ if (late && late.hitchCount) {
621
+ const byCause = {};
622
+ for (const hitch of late.hitches) byCause[hitch.likely] = (byCause[hitch.likely] || 0) + 1;
623
+ notes.push(`${late.hitchCount} hitch(es) after the reveal (frames over ${late.hitchThresholdMs} ms; ${late.hitchMs} ms in all). Likely causes of the worst: ${Object.entries(byCause).map(([cause, count]) => `${cause} ×${count}`).join(" · ")}.`);
624
+ }
625
+ if (late && late.downloadsAfterReveal.length) notes.push(`${late.downloadsAfterReveal.length} download(s) finished after the reveal, largest ${late.downloadsAfterReveal[0].name.split(/[?#]/)[0].split("/").slice(-1)[0]} (${late.downloadsAfterReveal[0].kb} KB) — fetched, decoded and uploaded during play instead of behind the loading screen.`);
491
626
  const shaderBuckets = analysis.timeline.filter((bucket) => bucket.newShaders > 0);
492
627
  if (shaderBuckets.length) {
493
628
  const late = shaderBuckets.filter((bucket) => bucket.t > 0.6 * analysis.timeline.length);
@@ -585,6 +720,30 @@ function printSummary(analysis) {
585
720
  line(` ${String(frame.t + "s").padStart(8)} ${cost.padEnd(16)} ${String(frame.phase || "-").padEnd(14)} script ${frame.scriptMs} ms · ${frame.pipelinesNear} pipelines near · ${frame.top.slice(0, 2).map((entry) => `${entry.name} ${entry.ms}`).join(", ") || "-"}`);
586
721
  }
587
722
  if (analysis.gpuCold) line(` (--gpu-cold: ${analysis.gpuCold.tagged} fragment shaders made unique, so every pipeline compiled as on a first visit)`);
723
+ const late = analysis.lateStutter;
724
+ if (late) {
725
+ line();
726
+ line(`LATE STUTTER — after the reveal (${late.revealT != null ? `${late.revealT}s, from the ${late.revealSource}` : "no reveal found: mark one in the scenario"}) · median frame ${late.medianFrameMs} ms · hitch = over ${late.hitchThresholdMs} ms`);
727
+ if (late.toolkit) line(` toolkit: late-compile detector ${late.toolkit.lateCompileDetector ? (late.toolkit.forcedReporting ? "on (turned on by the probe)" : "on") : "not in this toolkit version"} · safety net ${late.toolkit.safetyNet == null ? "n/a" : late.toolkit.safetyNet ? "on (a late pipeline skips its draw: pop-in, not a freeze)" : "off"}`);
728
+ line(` ${late.hitchCount} hitch(es), ${late.hitchMs} ms · ${late.lateCompileCount} late compile(s) · ${late.pipelinesAfterReveal} pipelines · ${late.texturesAfterReveal} textures · ${late.audioDecodesAfterReveal} audio decodes · ${late.downloadsAfterReveal.length} downloads after the reveal`);
729
+ for (const hitch of late.hitches.slice(0, 12)) {
730
+ const suspects = [
731
+ hitch.lateCompileCount ? `${hitch.lateCompileCount} late compile(s): ${hitch.lateCompiles.slice(0, 2).join("; ")}` : "",
732
+ hitch.pipelines ? `${hitch.pipelines} pipelines` : "", hitch.gcMs ? `gc ${hitch.gcMs} ms` : "", hitch.textures ? `${hitch.textures} textures` : "",
733
+ hitch.downloads.length ? `downloads ${hitch.downloads.map((entry) => entry.name).join(", ")}` : "", hitch.audioDecodes ? `${hitch.audioDecodes} audio decode(s)` : "",
734
+ Object.keys(hitch.growth).length ? `new ${Object.entries(hitch.growth).map(([name, count]) => `${count} ${name}`).join(", ")}` : "",
735
+ ].filter(Boolean).join(" · ");
736
+ line(` ${String(hitch.t + "s").padStart(8)} ${String(hitch.intervalMs + " ms").padEnd(10)} ${String(hitch.phase || "-").padEnd(12)} ${hitch.likely} — script ${hitch.scriptMs} ms${suspects ? " · " + suspects : ""}`);
737
+ }
738
+ if (late.lateCompilePasses.length) {
739
+ line(" late compiles by render pass (a pass other than \"main\" with many: a camera or render target the pre-warm never drew — created after the reveal, WarmAllCamerasOnReveal off, or a toolkit before 1.1.88):");
740
+ for (const pass of late.lateCompilePasses.slice(0, 6)) line(` ×${String(pass.count).padEnd(4)} pass "${pass.pass}" — ${pass.causes} cause(s), first ${pass.firstMsAfterReveal} ms after the reveal`);
741
+ }
742
+ if (late.lateCompiles.length) {
743
+ line(" late compiles by cause:");
744
+ for (const group of late.lateCompiles.slice(0, 12)) line(` ×${String(group.count).padEnd(4)} ${group.cause} [${group.effects.join(", ") || "?"}] first ${group.firstMsAfterReveal} ms after the reveal`);
745
+ }
746
+ }
588
747
  line();
589
748
  line("YOUR CODE — time spent, including the library work it triggers (whole run)");
590
749
  for (const entry of analysis.overall.lists.yoursTop.slice(0, 15)) {
@@ -699,6 +858,7 @@ function main() {
699
858
  shots: fs.existsSync(path.join(captureDir, "shots")) ? fs.readdirSync(path.join(captureDir, "shots")).filter((name) => name.endsWith(".png")) : [],
700
859
  filmstrip: fs.existsSync(path.join(captureDir, "filmstrip.json")) ? JSON.parse(fs.readFileSync(path.join(captureDir, "filmstrip.json"), "utf8")).map((frame) => ({ ...frame, t: round((frame.at - startMs) / 1000, 2) })) : [],
701
860
  };
861
+ analysis.lateStutter = lateStutter(probe, frames, probe.counters, prepared, info, phases, startMs, endMs);
702
862
  analysis.signals = signals(analysis);
703
863
  if (flags.drill) {
704
864
  analysis.drill = flags.drill.split(",").map((name) => ({
@@ -10,7 +10,9 @@
10
10
  * programs / pipelines), JS heap;
11
11
  * - long animation frames (LoAF) with their script attribution, when the browser supports them;
12
12
  * - every shader module / pipeline (WebGPU) and program (WebGL) the page creates, with its time (`gpuCompiles`);
13
- * - phase marks set by the scenario (`__btProfile.mark("countdown")`).
13
+ * - phase marks set by the scenario (`__btProfile.mark("countdown")`);
14
+ * - the late-stutter sources: the Babylon Toolkit's reveal and every late compile it names with its cause (`reveals`,
15
+ * `lateCompiles`), downloads (`resources`), GPU textures created (`textures`) and audio decodes (`audioDecodes`).
14
16
  *
15
17
  * Every time is an epoch time in milliseconds (`performance.timeOrigin + performance.now()`), so frames, marks and
16
18
  * the CPU profile line up across page navigations.
@@ -183,6 +185,104 @@ export function installProbe() {
183
185
  if (typeof window[name] !== "undefined") wrapCompile(window[name].prototype, "linkProgram", "program");
184
186
  }
185
187
 
188
+ // First-use work that lands after the game is revealed — the late-stutter sources. The Babylon Toolkit announces its
189
+ // reveal (SceneManager.OnSceneRevealedObservable) and names every shader / pipeline built after it with its cause
190
+ // (SceneShaderWarmup.OnLateCompileObservable). The probe turns that detector on even in a production build, so a
191
+ // profiled deployed game reports its late compiles too.
192
+ state.reveals = [];
193
+ state.lateCompiles = [];
194
+ state.toolkit = null;
195
+ const MAX_LATE_RECORDS = 5000;
196
+ const hookToolkit = () => {
197
+ const toolkit = window.TOOLKIT;
198
+ if (state.toolkit || !toolkit || !toolkit.SceneShaderWarmup || !toolkit.SceneManager) return;
199
+ const warmup = toolkit.SceneShaderWarmup;
200
+ state.toolkit = { warmup: true, lateCompileDetector: !!warmup.OnLateCompileObservable, forcedReporting: false };
201
+ try {
202
+ if (warmup.OnLateCompileObservable && typeof warmup.IsLateCompileReportingEnabled === "function" && !warmup.IsLateCompileReportingEnabled()) {
203
+ warmup.LateCompileReporting = true;
204
+ state.toolkit.forcedReporting = true;
205
+ }
206
+ } catch { /* an older toolkit without the switch */ }
207
+ try {
208
+ if (toolkit.SceneManager.OnSceneRevealedObservable) {
209
+ toolkit.SceneManager.OnSceneRevealedObservable.add((scene) => {
210
+ state.reveals.push({ at: epochNow(), sceneUniqueId: scene ? scene.uniqueId : null });
211
+ try { state.toolkit.safetyNet = typeof warmup.IsSafetyNetEnabled === "function" && scene ? warmup.IsSafetyNetEnabled(scene.getEngine()) : null; } catch { /* not on WebGL */ }
212
+ });
213
+ }
214
+ } catch { /* an older toolkit without the reveal observable */ }
215
+ try {
216
+ if (warmup.OnLateCompileObservable) {
217
+ warmup.OnLateCompileObservable.add((record) => {
218
+ if (state.lateCompiles.length >= MAX_LATE_RECORDS) return;
219
+ state.lateCompiles.push({
220
+ at: epochNow(), kind: record.kind, causeKind: record.causeKind, cause: record.cause, meshName: record.meshName,
221
+ materialName: record.materialName, particleSystemName: record.particleSystemName, postProcessName: record.postProcessName,
222
+ renderPassName: record.renderPassName, effectName: record.effectName, effectKey: String(record.effectKey || "").slice(0, 400),
223
+ msSinceReveal: record.msSinceReveal, sceneUniqueId: record.sceneUniqueId,
224
+ });
225
+ });
226
+ }
227
+ } catch { /* an older toolkit without the detector */ }
228
+ };
229
+ setInterval(hookToolkit, ATTACH_POLL_MS);
230
+
231
+ // Downloads: what the page fetched and when it finished — a texture, model or sound fetched during play is decoded and
232
+ // uploaded right after it arrives, often in one long frame.
233
+ state.resources = [];
234
+ try {
235
+ const resourceObserver = new PerformanceObserver((list) => {
236
+ for (const entry of list.getEntries()) {
237
+ if (state.resources.length >= MAX_LATE_RECORDS) return;
238
+ state.resources.push({
239
+ startAt: performance.timeOrigin + entry.startTime, at: performance.timeOrigin + entry.responseEnd,
240
+ name: String(entry.name || "").slice(0, 300), type: entry.initiatorType,
241
+ kb: +(((entry.encodedBodySize || entry.transferSize || 0)) / 1024).toFixed(1), ms: +entry.duration.toFixed(1),
242
+ });
243
+ }
244
+ });
245
+ resourceObserver.observe({ type: "resource", buffered: true });
246
+ } catch { /* resource timing unavailable */ }
247
+
248
+ // GPU textures created (WebGPU createTexture, WebGL texture storage / compressed uploads): a first-time texture during
249
+ // play costs its decode and upload on that frame.
250
+ state.textures = [];
251
+ const recordTexture = (width, height) => { if (state.textures.length < MAX_GPU_COMPILES) state.textures.push({ at: epochNow(), width: width || null, height: height || null }); };
252
+ const wrapTexture = (prototype, method, size) => {
253
+ if (!prototype || typeof prototype[method] !== "function") return;
254
+ const original = prototype[method];
255
+ prototype[method] = function (...args) { try { const [width, height] = size(args); recordTexture(width, height); } catch { recordTexture(null, null); } return original.apply(this, args); };
256
+ };
257
+ if (typeof GPUDevice !== "undefined") {
258
+ wrapTexture(GPUDevice.prototype, "createTexture", (args) => {
259
+ const size = args[0] && args[0].size;
260
+ return Array.isArray(size) ? [size[0], size[1]] : size ? [size.width, size.height] : [null, null];
261
+ });
262
+ }
263
+ if (typeof WebGL2RenderingContext !== "undefined") {
264
+ wrapTexture(WebGL2RenderingContext.prototype, "texStorage2D", (args) => [args[3], args[4]]);
265
+ wrapTexture(WebGL2RenderingContext.prototype, "compressedTexImage2D", (args) => (args[1] === 0 ? [args[3], args[4]] : [null, null]));
266
+ }
267
+
268
+ // Audio decoding: a sound decoded the first time it plays stalls that moment (decodeAudioData runs off the main thread,
269
+ // but its arrival and the buffer it creates land on a frame).
270
+ state.audioDecodes = [];
271
+ try {
272
+ const audioPrototype = typeof BaseAudioContext !== "undefined" ? BaseAudioContext.prototype : null;
273
+ if (audioPrototype && typeof audioPrototype.decodeAudioData === "function") {
274
+ const decode = audioPrototype.decodeAudioData;
275
+ audioPrototype.decodeAudioData = function (data, ...rest) {
276
+ const startAt = epochNow();
277
+ const kb = data && data.byteLength ? +(data.byteLength / 1024).toFixed(1) : null;
278
+ const result = decode.call(this, data, ...rest);
279
+ const done = () => { if (state.audioDecodes.length < MAX_LATE_RECORDS) state.audioDecodes.push({ startAt, at: epochNow(), kb }); };
280
+ if (result && typeof result.then === "function") result.then(done, done);
281
+ return result;
282
+ };
283
+ }
284
+ } catch { /* no Web Audio */ }
285
+
186
286
  // Long Animation Frames name the script, function and invoker behind every frame over 50 ms.
187
287
  try {
188
288
  const observer = new PerformanceObserver((list) => {
@@ -249,7 +349,24 @@ export function installProbe() {
249
349
  };
250
350
 
251
351
  /** Everything the probe recorded, for the capture script to save. */
252
- state.dump = () => ({
352
+ state.dump = () => {
353
+ // A toolkit found only after its reveal: take the late compiles it kept (their own reveal-relative times).
354
+ try {
355
+ const toolkit = window.TOOLKIT;
356
+ const scene = currentScene();
357
+ if (toolkit && toolkit.SceneShaderWarmup && scene && state.lateCompiles.length === 0 && typeof toolkit.SceneShaderWarmup.GetLateCompiles === "function") {
358
+ for (const record of toolkit.SceneShaderWarmup.GetLateCompiles(scene) || []) state.lateCompiles.push({ ...record, at: null });
359
+ }
360
+ } catch { /* nothing to recover */ }
361
+ return state.snapshot();
362
+ };
363
+ state.snapshot = () => ({
364
+ reveals: state.reveals,
365
+ lateCompiles: state.lateCompiles,
366
+ toolkit: state.toolkit,
367
+ resources: state.resources,
368
+ textures: state.textures,
369
+ audioDecodes: state.audioDecodes,
253
370
  engine: state.engine || null,
254
371
  engineAttachedAt: state.engineAttachedAt,
255
372
  scenesSeen: state.scenesSeen,
@@ -108,6 +108,7 @@ function pageData(analysis, reportDir, captureDir) {
108
108
  timeline,
109
109
  marks: analysis.marks,
110
110
  worstFrames: analysis.worstFrames,
111
+ lateStutter: analysis.lateStutter || null,
111
112
  hotLines: analysis.hotLines,
112
113
  excerpts: analysis.excerpts,
113
114
  heap: analysis.heap,
@@ -565,6 +566,46 @@ function renderWorst() {
565
566
  $("#worst").innerHTML = "<div class='scroll'><table><thead><tr><th class='num'>at</th><th>Phase</th><th>Kind</th><th class='num'>CPU ms</th><th class='num'>gap ms</th><th class='num'>script ms</th><th class='num'>new pipelines</th><th>Filled by</th><th>Your code in it</th></tr></thead><tbody>" + run.worstFrames.map((f) => "<tr><td class='num'>" + fmt(f.t) + "s</td><td class='nw'>" + esc(f.phase || "") + "</td><td class='nw'>" + esc(kindLabel[f.kind] || "–") + "</td><td class='num'>" + fmt(f.cpuMs) + "</td><td class='num'>" + fmt(f.intervalMs) + "</td><td class='num'>" + fmt(f.scriptMs) + "</td><td class='num'>" + fmt(f.pipelinesNear) + "</td><td class='where'>" + esc(f.top.map((e) => e.name + " " + e.ms).join(" · ")) + "</td><td class='where'>" + (f.yours.map((e) => link(e.file, e.line, e.name + " " + e.ms + " ms")).join(" · ") || "–") + "</td></tr>").join("") + "</tbody></table></div>";
566
567
  }
567
568
 
569
+ /**
570
+ * Late stutter: what happened for the first time after the reveal, and the hitches it lined up with. Late compiles are
571
+ * grouped by cause, each with the fix that usually removes it (the Babylon Toolkit's pre-warm rules).
572
+ */
573
+ function renderLate() {
574
+ const late = run.lateStutter;
575
+ const wrap = $("#late-wrap");
576
+ if (!late || (!late.hitchCount && !late.lateCompileCount && !late.pipelinesAfterReveal)) { wrap.style.display = "none"; return; }
577
+ const kindFix = {
578
+ particles: "Particles: pre-warm the system with TOOLKIT.SceneShaderWarmup.WarmParticleSystem(system), or register the prefab that spawns it with WarmPrefab.",
579
+ postprocess: "Post processes: create them at load and toggle them; never create one during play.",
580
+ renderpass: "Render passes: create render targets, mirrors, probes and cameras at load; stop their refresh instead of creating them later.",
581
+ mesh: "Meshes: spawned during play → register the prefab with WarmPrefab before the reveal. Already in the scene → a variant change during play (a light added, fog or clip planes toggled, a first instance, a texture transform moved, a look-alike material) — or a pass the pre-warm never drew (see the passes above).",
582
+ unknown: "Unknown cause: re-run on a development build so the toolkit's detector names it.",
583
+ };
584
+ const isMainPass = (name) => /^main$/i.test(name);
585
+ const summary = '<p class="meta">Revealed at ' + (late.revealT != null ? fmt(late.revealT) + " s (" + esc(late.revealSource) + ")" : "— no reveal found") +
586
+ " · " + fmt(late.hitchCount, 0) + " hitch(es) over " + fmt(late.hitchThresholdMs, 0) + " ms (" + fmt(late.hitchMs, 0) + " ms in all) · " + fmt(late.lateCompileCount, 0) + " late compile(s) · " +
587
+ fmt(late.pipelinesAfterReveal, 0) + " pipelines · " + fmt(late.texturesAfterReveal, 0) + " textures · " + fmt(late.audioDecodesAfterReveal, 0) + " audio decodes · " + fmt((late.downloadsAfterReveal || []).length, 0) + " downloads after the reveal" +
588
+ (late.toolkit && late.toolkit.safetyNet ? ". The WebGPU safety net is on: a late pipeline skips its draw for a frame or two, so it shows as pop-in rather than a freeze." : ".") + "</p>";
589
+ const suspects = (h) => [
590
+ h.lateCompileCount ? h.lateCompileCount + " late compile(s): " + h.lateCompiles.slice(0, 2).join("; ") : "",
591
+ h.pipelines ? h.pipelines + " pipelines" : "", h.gcMs ? "GC " + fmt(h.gcMs) + " ms" : "", h.textures ? h.textures + " textures" : "",
592
+ h.downloads.length ? "downloads " + h.downloads.map((d) => d.name).join(", ") : "", h.audioDecodes ? h.audioDecodes + " audio decode(s)" : "",
593
+ Object.keys(h.growth).length ? "new " + Object.keys(h.growth).map((k) => h.growth[k] + " " + k).join(", ") : "",
594
+ ].filter(Boolean).join(" · ");
595
+ const hitches = late.hitches.length ? "<div class='scroll'><table><thead><tr><th class='num'>at</th><th class='num'>after reveal</th><th>Phase</th><th class='num'>frame ms</th><th>Likely cause</th><th class='num'>script ms</th><th>Suspects</th><th>Your code in it</th></tr></thead><tbody>" +
596
+ late.hitches.map((h) => "<tr><td class='num'>" + fmt(h.t) + "s</td><td class='num'>" + (h.msAfterReveal != null ? fmt(h.msAfterReveal / 1000) + "s" : "–") + "</td><td class='nw'>" + esc(h.phase || "") + "</td><td class='num'>" + fmt(h.intervalMs) + "</td><td>" + esc(h.likely) + "</td><td class='num'>" + fmt(h.scriptMs) + "</td><td class='where'>" + esc(suspects(h) || "–") + "</td><td class='where'>" + (h.yours.map((e) => link(e.file, e.line, e.name + " " + e.ms + " ms")).join(" · ") || "–") + "</td></tr>").join("") + "</tbody></table></div>" : "<p class='meta'>No hitches after the reveal.</p>";
597
+ const passes = (late.lateCompilePasses || []).length ? "<h3>Late compiles by render pass</h3><div class='scroll'><table><thead><tr><th class='num'>count</th><th>Render pass</th><th class='num'>causes</th><th class='num'>first after reveal</th><th>What it means</th></tr></thead><tbody>" +
598
+ late.lateCompilePasses.map((p) => "<tr><td class='num'>" + fmt(p.count, 0) + "</td><td class='where'>" + esc(p.pass) + "</td><td class='num'>" + fmt(p.causes, 0) + "</td><td class='num'>" + fmt(p.firstMsAfterReveal / 1000) + "s</td><td>" +
599
+ esc(isMainPass(p.pass) ? "The main pass: see the causes below." : "A camera or render target the pre-warm never drew: one created after the reveal (create it at load), or WarmAllCamerasOnReveal turned off. Toolkit 1.1.88+ warms every screen camera in the scene at the reveal; an older toolkit warms only the camera active while it runs.") + "</td></tr>").join("") + "</tbody></table></div>" : "";
600
+ const kinds = [...new Set(late.lateCompiles.map((g) => g.causeKind || "unknown"))];
601
+ const compiles = late.lateCompiles.length ? "<h3>Late compiles by cause</h3><div class='scroll'><table><thead><tr><th class='num'>count</th><th>Cause</th><th>Shader</th><th class='num'>first after reveal</th></tr></thead><tbody>" +
602
+ late.lateCompiles.map((g) => "<tr><td class='num'>" + fmt(g.count, 0) + "</td><td class='where'>" + esc(g.cause) + "</td><td class='nw'>" + esc(g.effects.join(", ") || "–") + "</td><td class='num'>" + fmt(g.firstMsAfterReveal / 1000) + "s</td></tr>").join("") + "</tbody></table></div>" +
603
+ "<p class='meta'><strong>What usually fixes them.</strong></p><ul class='meta'>" + kinds.map((k) => "<li>" + esc(kindFix[k] || kindFix.unknown) + "</li>").join("") + "</ul>" : "";
604
+ const downloads = (late.downloadsAfterReveal || []).length ? "<h3>Downloads that finished after the reveal</h3><div class='scroll'><table><thead><tr><th class='num'>at</th><th>File</th><th>Type</th><th class='num'>KB</th><th class='num'>ms</th></tr></thead><tbody>" +
605
+ late.downloadsAfterReveal.map((d) => "<tr><td class='num'>" + fmt(d.t) + "s</td><td class='where'>" + esc(d.name) + "</td><td class='nw'>" + esc(d.type) + "</td><td class='num'>" + fmt(d.kb, 0) + "</td><td class='num'>" + fmt(d.ms, 0) + "</td></tr>").join("") + "</tbody></table></div>" : "";
606
+ $("#late").innerHTML = summary + hitches + passes + compiles + downloads;
607
+ }
608
+
568
609
  function renderShots() {
569
610
  if (!run.shots.length) { $("#shots-wrap").style.display = "none"; return; }
570
611
  $("#shots").innerHTML = run.shots.map((s) => {
@@ -606,7 +647,7 @@ $("#theme").addEventListener("click", () => {
606
647
  const dark = root.dataset.theme ? root.dataset.theme === "dark" : !matchMedia("(prefers-color-scheme: light)").matches;
607
648
  root.dataset.theme = dark ? "light" : "dark";
608
649
  });
609
- renderTiles(); renderFindings(); renderFixes(); renderTimeline(); renderPhases(); renderOwners(); renderFunctions(); renderHeap(); renderWorst(); renderShots(); renderWarm(); renderMeta();
650
+ renderTiles(); renderFindings(); renderFixes(); renderTimeline(); renderPhases(); renderOwners(); renderFunctions(); renderHeap(); renderWorst(); renderLate(); renderShots(); renderWarm(); renderMeta();
610
651
  let resizeTimer; addEventListener("resize", () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(renderTimeline, 150); });
611
652
  `;
612
653
 
@@ -649,6 +690,10 @@ function buildPage({ title, verdict, data, pdfName }) {
649
690
  <section class="panel"><div class="legend" id="owner-legend"></div><div id="chart-owners"></div>
650
691
  <div id="film-wrap"><div class="film" id="film"></div></div></section>
651
692
 
693
+ <div id="late-wrap"><h2>Late stutter — after the reveal</h2>
694
+ <p class="meta">What happened for the first time after the loading screen lifted, and the hitches it lined up with. A finished game drives the late compiles to zero: everything it draws is compiled behind the splash.</p>
695
+ <section class="panel" id="late"></section></div>
696
+
652
697
  <h2>Phases</h2>
653
698
  <section class="phases" id="phases"></section>
654
699
 
@@ -133,7 +133,7 @@ Each prototype subagent gets: its **direction**, the **theme**, the **world anch
133
133
  3. **Produce assets** via any mix of the available workflows: Pinterest pulls for reference, **GPT Image 2** for stills, **KIE MCP servers (default) / the Higgsfield CLI (Kling, Seedance, etc.)** for motion/video, hand-authored WebGL/SVG/CSS. All assets stay faithful to the world anchor and live in the prototype's folder. **On Higgsfield, every generation goes through the reference's `scripts/hf-generate.mjs` wrapper** with `--out .agents/prototypes/<NN-slug>/<file>`: the CLI alone only returns a CDN URL, and a prototype must never hot-link one. Local reference images are passed as file paths (`--image-references`, `--start-image`, `--end-image`) and uploaded automatically.
134
134
  4. **3D-hero-scroll directions:** follow *The 3D-hero-scroll batch rule* below.
135
135
  5. Run its own **iteration passes** (Step 4) before returning.
136
- 6. **Write clean, readable code.** Every file follows the Coding Practices: clean, professional TypeScript or JavaScript in the project's own language; meaningful full-word names, never one- or two-letter names or obfuscation; well-structured, readable, maintainable code for human developers; meaningful JSDoc on every class, function, method and public member (always written, but never a reason to fail a test or verification). The chosen prototype becomes the user's real front end, so its code must be maintainable. Every HUD follows the Agent Reference's **Game UI Performance — ENFORCED**: per-frame values (speed, timers, bars, needles) reach the screen through refs and one frame loop, never React state or a per-frame EventBus message.
136
+ 6. **Write clean, readable code.** Every file follows the Coding Practices: clean, professional TypeScript or JavaScript in the project's own language; meaningful full-word names, never one- or two-letter names or obfuscation; well-structured, readable, maintainable code for human developers; meaningful JSDoc on every class, function, method and public member (always written, but never a reason to fail a test or verification). The chosen prototype becomes the user's real front end, so its code must be maintainable. Every HUD follows the Agent Reference's **Game UI Performance — ENFORCED**: per-frame values (speed, timers, bars, needles) reach the screen through refs and one frame loop, never React state or a per-frame EventBus message. And nothing runs per frame that does not need to: the "otherworldly animation" is CSS `@keyframes` / `transition` on `transform` and `opacity` wherever CSS can do it; a WebGL / canvas / scroll-scrubbed scene pauses off-screen (`IntersectionObserver`) and in a background tab, writes nothing while the scroll is at rest, and honors `prefers-reduced-motion`; nothing animates `width` / `height` / `top` / `left` or reads layout per frame (`ui-design-system.md` › **Per frame or not**). Spectacle that costs frames when nothing is moving is not finished.
137
137
 
138
138
  ## The 3D-hero-scroll batch rule
139
139
 
@@ -69,7 +69,7 @@ Split the scope map into cohesive **slices** — by module, feature or layer, ro
69
69
  > 2. **Entry points & activation** — how its code is reached: URLs, query params, routes, flags, events, init calls, lifecycle hooks.
70
70
  > 3. **Public API** — exported classes, functions, components, web components, custom elements, with full signatures.
71
71
  > 4. **State & data shapes** — types, models and their fields; defaults; which are persisted and where; which are runtime only.
72
- > 5. **UI inventory** — every panel, dialog, toolbar, menu and overlay; for each, every control (button, input, toggle, slider, list, hotkey, mouse / touch gesture) → what it does → its handler `path:line`. Include enabled/disabled and visibility conditions.
72
+ > 5. **UI inventory** — every panel, dialog, toolbar, menu and overlay; for each, every control (button, input, toggle, slider, list, hotkey, mouse / touch gesture) → what it does → its handler `path:line`. Include enabled/disabled and visibility conditions. For every live value a HUD, overlay or GUI shows, record how it is updated (event, frame loop, throttle, CSS) and `path:line`, and flag each break of the Agent Reference's **Game UI Performance — ENFORCED** — per-frame React state or EventBus posts, unchanged values rewritten every frame, layout written or read per frame, a frame loop on a menu / splash / landing page or running while its UI is hidden — as a maintenance risk.
73
73
  > 6. **Events & messages** — emitted and consumed events, observables, callbacks, postMessage, pub/sub topics, and who listens.
74
74
  > 7. **External I/O** — every network call: method, URL or URL template, request body/params shape, response shape as consumed, auth/headers, error and retry handling. Every storage use: localStorage, IndexedDB, cookies, files.
75
75
  > 8. **Rendering & pipelines** — cameras, render targets, passes, post-processes, shaders and materials, offscreen renders and image exports: what each produces, at what size and format, and what each output encodes (e.g. which geometry a mask isolates, what a color or channel means).
@@ -38,7 +38,7 @@ Git is optional. **Where git is available:** stop now if the working tree has un
38
38
 
39
39
  - **`SPEC.md`** (repository root) is the project's source of truth for architecture, systems, conventions and decisions. Read its headings, Architecture, Conventions, and the systems this feature touches. The feature must fit it. **If the idea conflicts with SPEC.md, stop and tell the user before writing.** Verification procedures described in SPEC.md are tooling the feature may reuse, not requirements it inherits.
40
40
  - **If `SPEC.md` is missing or an empty stub, ask the user first** whether to create it from the scaffold at the end of this file. Yes → write it, then continue against it. No → continue, and note in the spec: `"No project SPEC.md content yet — following existing codebase conventions."`
41
- - **`DESIGN.md`** (only if the feature has UI): it is the single source of truth for design — never Figma or invented values. Cite the tokens and shared components the feature uses in 3–8 bullets. Missing → note `"No DESIGN.md design system found — follow the existing UI conventions already in the codebase."` No UI → say no design tokens apply.
41
+ - **`DESIGN.md`** (only if the feature has UI): it is the single source of truth for design — never Figma or invented values. Cite the tokens and shared components the feature uses in 3–8 bullets. Missing → note `"No DESIGN.md design system found — follow the existing UI conventions already in the codebase."` No UI → say no design tokens apply. When the feature has a HUD, overlay, menu, splash or landing page, add one bullet naming its live values and their cadence under the Agent Reference's **Game UI Performance — ENFORCED** (state on events, telemetry through the frame loop, throttled readouts, decorative motion in CSS, no frame loop on menus / splash / landing pages), so the plan builds it that way.
42
42
  - **Recon docs (`.agents/recon/*_recon.md`, written by bt-recon):** if any recon's `scope` covers a system this feature touches, read its Summary, Architecture, the relevant Feature Inventory / UI Reference / External Interfaces sections, Known Issues and Extension Points — it is the grounding for code nobody else documented, so build on it instead of re-deriving it. Cite it in `## Research Notes`. If its `commit:` is well behind HEAD for the files this feature touches, note the drift there and suggest `bt-recon --refresh`.
43
43
  - **Recons the brief cites (`… using @<path>_recon.md`):** bt-profile's fix commands cite the recon of the code behind the fixes, kept in the profile's own folder (`.agents/profile/<slug>/recon/`) or in `.agents/recon/`. Always read a cited recon in full, whatever its scope says. It is the map of the code the fix changes: callers, invariants, tests, extension points. Turn what it says must not break into Acceptance Criteria or named test cases. **Copy each cited recon into this feature's `recon/` folder** and cite the copy in `## Research Notes`. The feature folder then holds everything it rests on, and still works after the profile is archived or moved. A cited recon that does not exist yet: say so, give the `/bt-recon` command that makes it (the profile report's **Copy recon command**), and carry on with your own research.
44
44
  - **Research the codebase, sized to the feature.** Find the closest existing feature to mirror, the real conventions, and the integration points. For a `small` feature do this inline; fan out to up to 3 **read-only** subagents only for `medium` / `large` (they report findings and file paths, never draft the spec; if a finding contradicts SPEC.md, raise it with the user rather than resolving it silently). Record the result in the spec's `## Research Notes` so bt-plan starts from it.
@@ -135,7 +135,7 @@ Write the dashboard **straight after its spec, before anything else** — a spec
135
135
  Print `🗂️ [bt-spec] Writing the feature dashboard …`. The feature's dashboard exists from the spec on: until a plan is written it shows the `bt-plan` commands that plan this spec — a standard plan, `--heavy`, `--parity`, `--no-time-limit` — each with a copy button, and a *Build your own* with those options and a brief. From bt-execute's `templates/dashboard/` *(where skills load through a tool: `load_skill('bt-execute')` + `read_skill_resource`; where they are files: the sibling `bt-execute/` folder in the skills directory this skill was loaded from)*:
136
136
 
137
137
  - copy `dashboard.html` to `.agents/specs/<feature_slug>/dashboard.html`, replacing `{{slug}}` with the slug and changing nothing else;
138
- - write `.agents/specs/<feature_slug>/documents/<feature_slug>_dashboard.js` from the starter `dashboard.template.js`, written whole as strict JSON behind its `window.FEATURE_DASHBOARD =` prefix — double-quoted keys, no comments, no trailing commas (`data-schema.md` documents every field): `feature` (title, slug, branch, `origin: "spec"`, size, proof, a plain-language summary from the spec's Summary), `documents` (the Spec alone), **`status: "specified"`**, `updatedAt` (the current local time, `YYYY-MM-DD HH:MM`), `estimate` empty, **no phases**, an empty `afterAction`, the spec's Decisions as `decisions` when it has any (`D1` …), no follow ups, and one `activity` line: `Spec written — <size>, <proof> proof`;
138
+ - write `.agents/specs/<feature_slug>/documents/<feature_slug>_dashboard.js` from the starter `dashboard.template.js`, written whole as strict JSON behind its `window.FEATURE_DASHBOARD =` prefix — double-quoted keys, no comments, no trailing commas (`data-schema.md` documents every field): `feature` (title, slug, branch, `origin: "spec"`, size, proof, a plain-language summary from the spec's Summary), `documents` (the Spec alone), **`status: "specified"`**, `updatedAt` (the current local time, `YYYY-MM-DD HH:MM`), `estimate` empty, **no phases**, an empty `afterAction`, the spec’s Decisions as `decisions` when it has any, each an object `{ "id": "D1", "text": "…", "updates": [] }` (never a plain `"D1 — …"` string, which shows as an empty row), no follow ups, and one `activity` line: `Spec written — <size>, <proof> proof`;
139
139
  - write `.agents/specs/<feature_slug>/documents/<feature_slug>_live.js` from `live.template.js`, the same way: no task, `role: "orchestrator"`, `title: "Spec written — waiting for bt-plan"`, no steps;
140
140
  - in a git repository, make sure `.gitignore` (at the repository root) contains the line `.agents/*/*/documents/*_live.js` — append it once if missing.
141
141