@babylonjs-toolkit/agent 1.1.86 → 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.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Babylon Toolkit Desktop Agent (1.1.86)
1
+ # Babylon Toolkit Desktop Agent (1.1.88)
2
2
 
3
3
  The desktop agent owns the entire pipeline end to end — frontend and UI design, gameplay code, shaders, generated art and audio, 3D models in headless Blender, whole game levels and prefabs in a terminal-driven Unity Editor, the interactive glTF export, the web build, the dev server, and visual QA by screenshotting both Unity and the running browser.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babylonjs-toolkit/agent",
3
- "version": "1.1.86",
3
+ "version": "1.1.88",
4
4
  "description": "Installs the Babylon Toolkit Desktop Agent for Claude Code, Codex, GitHub Copilot, Gemini CLI and Antigravity.",
5
5
  "keywords": [
6
6
  "babylonjs",
@@ -32,6 +32,7 @@ Run tasks from a plan: build each one with its tests, have an independent verifi
32
32
  ## Ground rules
33
33
 
34
34
  - **TIME MATTERS** — on by default; `--no-time-limit` turns it off. Treat the arguments as ending with `TIME MATTERS`: the user is waiting on this run, so finish quickly — follow the *Work fast* rules below to the letter, take the direct route to each task's Acceptance, and do not re-read what you already have. Begin every implementer and verifier prompt with `TIME MATTERS.` Print `⏱️ [bt-execute] TIME MATTERS` at the start (`--no-time-limit`: print `⏱️ [bt-execute] No time limit`, and do not add it). Speed never relaxes tests, the independent verifier, live checks, or "tick only on PASS".
35
+ - **Snapshots — ENFORCED.** The dashboard's snapshots are the chronicle of how the feature was built; a row of "No snapshot" loses that record for good. Every snapshot reaches the dashboard **only** through `node <skills>/bt-execute/scripts/dashboard.mjs snapshot <feature-folder> <T<n>|P<N>|plan> --src snapshots/… --caption "…"` (`--before … --after …` for a comparison, `--frame "src|stage|caption"` repeated for a progression). Never write or brief a snapshot JSON shape — every brief carries that exact command line with the paths filled in, and a subagent that cannot run it returns paths and captions for you to add. `dashboard.mjs check <feature-folder>` is a gate, not a courtesy: run it before every phase commit and at run end, and never commit or end the run while it fails. Then open `dashboard.html` headless and look: every snapshot slot shows its image.
35
36
  - **Scope.** Implement only the selected task(s). No "while I'm here" work on other tasks. Ambiguous, or blocked by an unfinished task → stop and tell the user *(auto-pilot: decide and log it)*.
36
37
  - **Open the run before anything else.** The first actions of every run — before reading docs, reading code, checking the repo or any other pre-flight work — are, in order: take the clock; append the `⏱ Run <n> start` line to the run log; sync the dashboard with the plan and set `status: "in-progress"` (*Run start* under *Feature folder and dashboard*); write the live file (`role: "orchestrator"`, `title: "Starting run <n> — <what you are checking first>"`); and launch the watchdog in the background (*Never let the dashboard go stale*). From then on the pre-flight work is narrated in the live file like any other step. Until the run is opened the dashboard still shows the last run's end state — a user who restarts a run and refreshes must see it running within a minute, not after the pre-flight is over.
37
38
  - **Read the docs once.** For Babylon work, if you have not read the Agent Reference this session, read it once — https://raw.githubusercontent.com/babylontoolkit/agent/main/reference.md — plus only the sub-documents the plan's tasks need, searching a large one for the part you need rather than reading it whole. It is the authority for conventions and API. Cannot be read → stop and tell the user *(auto-pilot: retry 3×, then continue on what you know and log it)*. Read the plan's checklist and the parts of `SPEC.md` the tasks touch; re-read after a context compaction.
@@ -54,13 +55,13 @@ Work in **phases**: a `### Phase N` group in the plan, or — if the plan has no
54
55
  4. **Fix loop** for a task that failed: fix the code in the context that wrote it; re-run its tests; re-verify with a **fresh** verifier given only the failed items and the evidence (`--strict`: the whole task). A records-only slip (a stale number or note) is fixed directly and re-checked by you. 3 attempts (`--strict`: 5), each changing something material; stop early if two attempts fail the same way with no new idea. Still failing → leave it unticked, stop and report *(auto-pilot: defer and continue)*.
55
56
  5. **Report:** tasks done (for `ALL` / ranges: the range asked for, completed/total, and whether the plan is now finished; if fewer than `n` tasks remained for `NEXT:<n>`, say so), files changed, tests run (`tests: 4 passed (implementer) · verifier-checked`), verifier result (`verified (independent subagent)` or `verified (self)`), the dashboard path (`.agents/specs/<slug>/dashboard.html` — open it in a browser), the plan summary path when this run wrote it (`.agents/specs/<slug>/documents/<slug>_summary.html`), and the next task id — for reference only.
56
57
 
57
- **The verifier is told:** *"Confirm each task's Acceptance is genuinely met and run its `Verify` commands against the stated expected output. Re-run the tests and the relevant suite once; check they really cover the Acceptance and named edge cases and could fail — missing or vacuous tests are a FAIL. Read the diff for real defects: logic errors, broken callers, unhandled edge cases the plan names, a documented behavior dropped or inverted, a sibling-skill template re-implemented instead of copied. Check every code file the task created or changed against the Agent Reference's Coding Practices — ENFORCED: clean, professional TypeScript or JavaScript in the language the project already uses (never converted to the other unasked); strict types with no needless `any` in TypeScript; meaningful full-word names for every class, method, property, variable and parameter (one- or two-letter names, cryptic abbreviations and code-golf tricks are violations, except the allowed loop counters, axis/`uv` names and toolkit aliases, and names that bind to exported data); no dead code, unused imports or leftover `console.log`; well-structured code a developer new to the project can read and maintain. Any violation is a FAIL for that task — quote the offending lines. Check every HUD, overlay or GUI file the task created or changed against the Agent Reference's Game UI Performance — ENFORCED: a value that changes every frame (speed, RPM, needles, timers, bars, markers) set through React state, props, context or a store, or posted on the EventBus per frame; a state setter, `dispatch(`, store update or `EventBus.PostMessage(` inside `requestAnimationFrame`, a frame-loop hook, a render observable or a component's `update()`; `width` / `height` / `top` / `left` / `innerHTML` / SVG geometry written per frame, or layout read in the loop; a Babylon GUI control assigned every frame without a changed-value check; a frame loop (`requestAnimationFrame`, `useFrameLoop`, `setInterval`, an animation-library tick) on a menu, pause / settings / results screen, splash, preloader or landing page, or driving motion CSS could do (a real-time 3D / canvas / scroll-scrubbed hero is allowed when it pauses off-screen and writes nothing at rest); a HUD loop that keeps writing while its HUD is hidden, behind a modal or the game is paused; a CSS `transition` on a property the frame loop writes. Any of these is a FAIL for that task — quote the offending lines. JSDoc is never a FAIL: missing, thin or stale JSDoc (including JavaScript type tags) never fails a test, a verification or an Acceptance item — list it under a separate non-blocking `JSDoc notes` heading. For any task whose correctness shows only at runtime — rendering, UI, interaction, Unity↔Babylon parity — check it live in the browser (and Unity where relevant) whether or not the plan marks it `live`, and do the plan's final end-to-end check live: look at the running result, beside the reference image when there is one, and judge it as a user would; passing unit tests never substitute. Do all of a phase's live checks in one session on the already-running dev server, and re-export from Unity only if the phase changed that scene's export — then only the project and the scenes the phase works on. Save the frames from your live session that show each visual task's verified result to `[SNAPSHOTS]` as `T<n>-<NN>-<stage>.png` — the same camera or viewport as the implementer's progression frames, plus any angle or comparison (Unity beside browser, before beside after) that proves the Acceptance — and return each path with a one-line caption saying what it shows. Snapshots never add a page session or an export of their own. Keep the dashboard current as you go: set each task `verifying` when you start checking it, and rewrite the live file at each check (what you are checking, on what) — never 15 minutes without a write. Treat an absolute count in the plan as 'named tests pass, no new failures'. [SCOPE] Return PASS/FAIL per task with evidence and one line on what you ran live and where (or `none — tests only`), listing records-only slips separately."*
58
+ **The verifier is told:** *"Confirm each task's Acceptance is genuinely met and run its `Verify` commands against the stated expected output. Re-run the tests and the relevant suite once; check they really cover the Acceptance and named edge cases and could fail — missing or vacuous tests are a FAIL. Read the diff for real defects: logic errors, broken callers, unhandled edge cases the plan names, a documented behavior dropped or inverted, a sibling-skill template re-implemented instead of copied. Check every code file the task created or changed against the Agent Reference's Coding Practices — ENFORCED: clean, professional TypeScript or JavaScript in the language the project already uses (never converted to the other unasked); strict types with no needless `any` in TypeScript; meaningful full-word names for every class, method, property, variable and parameter (one- or two-letter names, cryptic abbreviations and code-golf tricks are violations, except the allowed loop counters, axis/`uv` names and toolkit aliases, and names that bind to exported data); no dead code, unused imports or leftover `console.log`; well-structured code a developer new to the project can read and maintain. Any violation is a FAIL for that task — quote the offending lines. Check every HUD, overlay or GUI file the task created or changed against the Agent Reference's Game UI Performance — ENFORCED: a value that changes every frame (speed, RPM, needles, timers, bars, markers) set through React state, props, context or a store, or posted on the EventBus per frame; a state setter, `dispatch(`, store update or `EventBus.PostMessage(` inside `requestAnimationFrame`, a frame-loop hook, a render observable or a component's `update()`; `width` / `height` / `top` / `left` / `innerHTML` / SVG geometry written per frame, or layout read in the loop; a Babylon GUI control assigned every frame without a changed-value check; a frame loop (`requestAnimationFrame`, `useFrameLoop`, `setInterval`, an animation-library tick) on a menu, pause / settings / results screen, splash, preloader or landing page, or driving motion CSS could do (a real-time 3D / canvas / scroll-scrubbed hero is allowed when it pauses off-screen and writes nothing at rest); a HUD loop that keeps writing while its HUD is hidden, behind a modal or the game is paused; a CSS `transition` on a property the frame loop writes. Any of these is a FAIL for that task — quote the offending lines. JSDoc is never a FAIL: missing, thin or stale JSDoc (including JavaScript type tags) never fails a test, a verification or an Acceptance item — list it under a separate non-blocking `JSDoc notes` heading. For any task whose correctness shows only at runtime — rendering, UI, interaction, Unity↔Babylon parity — check it live in the browser (and Unity where relevant) whether or not the plan marks it `live`, and do the plan's final end-to-end check live: look at the running result, beside the reference image when there is one, and judge it as a user would; passing unit tests never substitute. Do all of a phase's live checks in one session on the already-running dev server, and re-export from Unity only if the phase changed that scene's export — then only the project and the scenes the phase works on. Save the frames from your live session that show each visual task's verified result to `[SNAPSHOTS]` as `T<n>-<NN>-<stage>.png` — the same camera or viewport as the implementer's progression frames, plus any angle or comparison (Unity beside browser, before beside after) that proves the Acceptance — and add each one to its task with `node <skills>/bt-execute/scripts/dashboard.mjs snapshot <feature-folder> T<n> --src snapshots/… --caption "…"` (never snapshot JSON), returning each path with its one-line caption. Snapshots never add a page session or an export of their own. Keep the dashboard current as you go: set each task `verifying` when you start checking it, and rewrite the live file at each check (what you are checking, on what) — never 15 minutes without a write. Treat an absolute count in the plan as 'named tests pass, no new failures'. [SCOPE] Return PASS/FAIL per task with evidence and one line on what you ran live and where (or `none — tests only`), listing records-only slips separately."*
58
59
 
59
60
  `[SNAPSHOTS]` is the feature folder's `snapshots/` path (`.agents/specs/<slug>/snapshots/`). `[SCOPE]` is one of two sentences. **Standard:** *"Do not add mutation testing, fuzzing, restarts or audits of untouched files unless something you found points there; aim for about 25 tool calls and report rather than expand."* **`--strict`:** *"Be adversarial: actively look for any reason the Acceptance is NOT met, using whatever you judge worthwhile — mutation checks against the tests, randomized inputs, re-deriving values from the plan's Decisions and Design Reference, live QA of every rendered or exported surface."*
60
61
 
61
62
  For a task built on a sibling skill (e.g. bt-design's 3D-Hero-Scroll), give the verifier the relevant part of that skill *(where skills load through a tool: `load_skill` + `read_skill_resource`; where they are files: the skills directory this skill was loaded from, e.g. `~/.claude/skills/`, `~/.agents/skills/` or the project's equivalent)* — its documented options (e.g. `sweep: page` really reaches the document bottom) are part of Acceptance.
62
63
 
63
- **Every subagent gets a brief, not homework:** the task block(s), the plan Decisions / Design Reference entries they cite, the SPEC.md parts touched, the Agent Reference excerpts needed (with their links) — **always including the full `Coding Practices — ENFORCED` section**, since implementers write to it and verifiers fail work that breaks it — the test command and the feature folder's `tests/` path, the `snapshots/` path and *Snapshots tell the story* (for any phase with visible output), the dashboard and live file paths with the per-task update rules from *Feature folder and dashboard* (with `--verbose`, the `details` fields that role writes), the project's agent instructions, the *Work fast* rules below, and: *"Do not read the Agent Reference or SPEC.md in full — the parts you need are here, and this overrides any standing instruction to read it first. Read one sub-document (search it for the API, never the whole file) only if you hit an API this brief does not cover, and say which."*
64
+ **Every subagent gets a brief, not homework:** the task block(s), the plan Decisions / Design Reference entries they cite, the SPEC.md parts touched, the Agent Reference excerpts needed (with their links) — **always including the full `Coding Practices — ENFORCED` section**, since implementers write to it and verifiers fail work that breaks it — the test command and the feature folder's `tests/` path, the `snapshots/` path and *Snapshots tell the story* (for any phase with visible output), the dashboard and live file paths with the per-task update rules from *Feature folder and dashboard* (with `--verbose`, the `details` fields that role writes) and **the exact `dashboard.mjs snapshot` command line with the feature folder filled in** — never a snapshot JSON shape of your own (a hand-written `{path, caption}` entry has twice reached a dashboard as a row of "No snapshot"), the project's agent instructions, the *Work fast* rules below, and: *"Do not read the Agent Reference or SPEC.md in full — the parts you need are here, and this overrides any standing instruction to read it first. Read one sub-document (search it for the API, never the whole file) only if you hit an API this brief does not cover, and say which."*
64
65
 
65
66
  ## Feature folder and dashboard
66
67
 
@@ -95,12 +96,12 @@ Every feature lives in one folder, created by bt-spec (or by bt-plan for a Quick
95
96
 
96
97
  - **The live file — at every meaningful step.** Rewrite `documents/<slug>_live.js` whole (it is small) when a task starts, at each milestone inside it, before anything slow (a build, an export, a bake, a capture, a test run), at each fix attempt, at the hand-over to the verifier and while it checks each task, and at the commit: the phase, the task, the role, one plain-language sentence on what is happening now, and the task's step log. Never let it go 15 minutes without a write during active work — the page flags a 20-minute silence. Between tasks, `task: ""` and a `title` (`Verifying phase 2`, `Committing phase 2`).
97
98
  - **The dashboard data — at every task boundary:** a task becomes `in-progress` when it starts; `built` the moment it is built and its tests are green — with its summary of what was actually done (and anything surprising), files, tests and snapshots filled in **right then**, not at the phase end; `verifying` while the verifier checks it; `done` when it passes (verifier result, attempts, commit, done time, its `DECISION` lines, and `checkedLive` — one line on what the verifier ran live and where, for every task it checked in the browser or Unity whatever the plan's verify level, `""` when tests alone proved it); back to `in-progress` with `attempts` + 1 on a FAIL. Each change also adds an `activity` line and refreshes `updatedAt`.
98
- - **Every write goes through this skill's `scripts/dashboard.mjs` — never hand-edited.** Each data file is one `window.… =` prefix and one strict-JSON value (the prefix only lets a page opened from disk load it); the helper parses it, changes it, checks the shapes and writes it back atomically, so the page never sees a half-written or malformed file. Use it, not a one-off script of your own: `node <skills>/bt-execute/scripts/dashboard.mjs live <feature-folder> --task T7 --role implementer --activity "…" --step "…"` · `task <feature-folder> T7 --set '{"status":"built","summary":"…"}'` · `activity <feature-folder> "…"` · `status <feature-folder> in-progress` · `check <feature-folder>` (all options in the script's header). Only where Node cannot run, fall back to the parse-and-write-back recipe in `data-schema.md`. Keep each field its documented shape too — a list stays a list (`updates`, `snapshots`, `files`, `decisions`, `notes` …: append, never assign a string); a helper script you give subagents checks the shapes before it writes.
99
+ - **Every write goes through this skill's `scripts/dashboard.mjs` — never hand-edited.** Each data file is one `window.… =` prefix and one strict-JSON value (the prefix only lets a page opened from disk load it); the helper parses it, changes it, checks the shapes and writes it back atomically, so the page never sees a half-written or malformed file. Use it, not a one-off script of your own: `node <skills>/bt-execute/scripts/dashboard.mjs live <feature-folder> --task T7 --role implementer --activity "…" --step "…"` · `task <feature-folder> T7 --set '{"status":"built","summary":"…"}'` · `snapshot <feature-folder> T7 --src snapshots/T7-01-stage.png --caption "…"` (or `--before … --after …`, or `--frame "src|stage|caption"` repeated) · `activity <feature-folder> "…"` · `status <feature-folder> in-progress` · `check <feature-folder>` (all options in the script's header). **Snapshots go in only through `snapshot`** — it builds the shape the page renders and refuses an image that is not on disk. As a backstop, every helper write repairs an entry the page could not show (an image under `path`, `file`, `image`, `url` or `href` moves to `src`; an unknown `source` becomes `browser`), `check` repairs any already in the file, and the watchdog repairs one written around the helper within a minute; an image that is not on disk is still refused. Run `check` at every phase boundary and at run end; a failure there is fixed before the commit. Only where Node cannot run, fall back to the parse-and-write-back recipe in `data-schema.md`. Keep each field its documented shape too — a list stays a list (`updates`, `snapshots`, `files`, `decisions`, `notes` …: append, never assign a string); a helper script you give subagents checks the shapes before it writes.
99
100
 
100
101
  On top of the per-task updates:
101
102
 
102
103
  - **Run start — the first thing the run does** (*Open the run before anything else*): make sure the default `.agents` folders exist — `.agents/specs/`, `.agents/complete/`, `.agents/archived/`, `.agents/profile/` and `.agents/recon/`, each with an empty `.gitkeep` (write only the ones missing); **refresh `dashboard.html`** — copy it again from the template with `{{slug}}` replaced (it is never edited, so this is always safe, and it is how layout fixes reach dashboards created by older versions), and `documents/<slug>_summary.html` the same way from `templates/summary/summary.html` when the feature already has one; then **sync the dashboard with the plan file** — re-read its checklist and add any phase or task (including sub-tasks like `T3.1`) the dashboard lacks, in plan order, as `pending`, with an `updates` note on it (`Added to the plan after <the plan was complete / phase 2 ran> — <why, if the plan says>`); a task the plan no longer has is removed with an `activity` line saying so. Then `status: "in-progress"`, `runs` + 1, the run-log document link, an `activity` line, the first live-file write, and the watchdog launched in the background. In a git repository, check `.gitignore` has `.agents/*/*/documents/*_live.js` and append it once if not — the live file is never staged or committed; `<slug>_dashboard.js` and `snapshots/` are.
103
- - **Each phase, after its ticks and before its commit:** the phase's status, times and minutes (from its `⏱` line), its verifier result and a two-or-three-sentence summary of what it delivered; the phase-level snapshots (a progression spanning several tasks — below); `decisions`; `activeTime` — the plan's total across **every run so far** (each finished run's `active` from its `⏱ Run <n> end` line, plus this run's so far), never this run alone; an `activity` line; and a current "so far" `outcome` headline.
104
+ - **Each phase, after its ticks and before its commit:** the phase's status, times and minutes (from its `⏱` line), its verifier result and a two-or-three-sentence summary of what it delivered; the phase-level snapshots (a progression spanning several tasks — below), each added with `dashboard.mjs snapshot`, and `dashboard.mjs check` passing; `decisions`; `activeTime` — the plan's total across **every run so far** (each finished run's `active` from its `⏱ Run <n> end` line, plus this run's so far), never this run alone; an `activity` line; and a current "so far" `outcome` headline.
104
105
  - **A deferral:** the task's `status: "deferred"` and `deferredReason`, an `activity` line.
105
106
  - **Run end — the After Action Report.** **decide the status by re-reading the plan file's checkboxes, never from memory:** `complete` when every task in the plan is `- [x]`; `incomplete` when every task is either ticked or marked ⏭️ DEFERRED; otherwise `paused` (the run covered only a slice, or tasks were added). The page refuses a `complete` it can see is false — it shows the plan as paused with a warning — but the plan file is the authority; never leave `in-progress` behind, because the status picks the page's top slot: `in-progress` shows *Current run activity* (the live file and the milestones), any other run-ended status shows the After Action Report in its place. Write `followUps` for a human, and `afterAction` — the whole plan's execution, start to finish: a one-sentence headline of what the plan delivered; two to four paragraphs on what was built, how it was proven and what surprised; highlights; and **one before/after for the plan as a whole** (`comparison`) — the plan-wide "before" frame beside a final "after" taken now from the same camera or viewport (the end-to-end check's session supplies it). Add the plan's key progression to `afterAction.snapshots` if one tells the story better than any single phase. Write `afterAction.testing` on every run, not only `--verbose`: run every test suite the plan touched **once more, in full, at run end** and record each as a `suites` entry (name, command, passed, failed, how many tests this plan added, and a `note` for any failure that pre-dates the plan) — never add up the tasks' counts, which re-count the same suite once per task; a `summary` of how the plan was tested (unit tests, the verifier's re-runs, what was checked live and on what, the end-to-end check); and `gaps` — what no test or live check covers. The page builds the task-by-task table and the list of test cases from the tasks. The figures (tasks, tests, retries, time) are computed by the page — never type them in. A run that ends before the plan is finished writes it too; the page marks it *Interim* while `paused`, and the next run revises it with an `updates` entry. **A reopened plan** (tasks added after it was complete) works the same way: the run that finishes the added tasks rewrites the After Action Report to cover them, notes the change in its `updates` (`Revised — T7 added after completion: <why>`), and retakes the plan-wide "after" from the same camera so the comparison shows the plan as it now stands.
106
107
  - **Run end — the plan summary, only when the plan is `complete`.** Write the feature's plan summary, a formatted page that opens straight from disk. It is the plan told to people who never see the code: what it delivered, what it means for existing users and content, what was wrong, what changed, what did not, and how it was checked. Use on-screen names in **bold** and real values. Leave out file names, task IDs and test counts. Like the dashboard, the page is a fixed template and the content is data, both from this skill's `templates/summary/`. Copy `summary.html` to `documents/<slug>_summary.html` with `{{slug}}` replaced and nothing else edited; only `dashboard.html` sits at the feature root. Write `documents/<slug>_summary.js` beside it, whole as strict JSON behind `window.PLAN_SUMMARY =`. **`summary-guide.md` has the audience, the fields and the section order, and `summary.template.js` is a worked example. Read both.** **Leave out any section that does not apply to this plan**, and adapt a heading's wording where the default does not fit (a feature has *Why it was needed* in place of *What was wrong*). Then set `afterAction.planSummary: "documents/<slug>_summary.html"` so the After Action Report links to the page. A `paused` or `incomplete` run writes no summary. **A reopened plan** keeps its existing summary while the added tasks run. The run that completes them rewrites the data to cover the plan as it now stands, adds the new date to `stamp` (`Fixed on 2026-10-19; updated on 2026-11-02`) and says in the lead what the update added. Commit both files with the dashboard data.
@@ -121,7 +122,7 @@ The snapshots are how a human sees what was built, so choose them for meaning, n
121
122
  - **Then whatever proves the point.** A comparison when a change is best seen side by side (a fix, the state before the phase, Unity beside the browser for parity); a second angle when one view hides it (overview, ground level, close detail); a still when one image proves one thing.
122
123
  - **As many frames as the build has meaningful stages** — usually 3–8 for a visual task, none for a task with nothing to see. No near-duplicates, no frame per iteration, and a failed attempt only when it explains a decision (say so in the caption).
123
124
  - **Who takes them.** At the start of the first run, before T1 changes anything, take the **plan-wide "before"** (`snapshots/plan-before.png`) from the camera or viewport that will best show the finished feature — the starting state, even if that is an empty scene or the old page; skip it only when the plan has nothing to see. The implementer saves a "before" frame before the first change of a visual phase, and saves milestone frames while it builds — it is already capturing to iterate, so it keeps the meaningful ones instead of discarding them. The verifier adds the verified final frames from its live session. You pick and order them into the dashboard. Frames come from sessions and exports the work already runs — never an extra page session or re-export just for a picture.
124
- - **Files.** `snapshots/T<n>-<NN>-<stage>.png` (phase-level: `P<N>-<NN>-<stage>.png`), at most about 1600 px wide; prefer JPEG or WebP for large scenes. Unity frames come through the bridge's camera capture, browser frames through the browser tool.
125
+ - **Files.** `snapshots/T<n>-<NN>-<stage>.png` (phase-level: `P<N>-<NN>-<stage>.png`), at most about 1600 px wide; prefer JPEG or WebP for large scenes. Unity frames come through the bridge's camera capture, browser frames through the browser tool. Each frame reaches the dashboard through `dashboard.mjs snapshot` (task `T<n>`, phase `P<N>` or `plan`); a subagent without the helper returns its paths and captions and you add them.
125
126
 
126
127
  ## Work fast
127
128
 
@@ -8,12 +8,19 @@
8
8
  *
9
9
  * node dashboard.mjs live <feature-folder> --task T19 --role implementer --activity "…" [--phase 7] [--step "…"]… [--reset] [--title "…"]
10
10
  * node dashboard.mjs task <feature-folder> <task-id> --set '{"status":"built","summary":"…"}' [--note "why an earlier result changed" --by T21]
11
+ * node dashboard.mjs snapshot <feature-folder> <T7|P2|plan> --src snapshots/T7-01-stage.png --caption "…" [--title "…"] [--source unity]
12
+ * (comparison: --before snapshots/a.png --after snapshots/b.png [--before-caption …] [--after-caption …];
13
+ * progression: --frame "snapshots/x.png|stage|caption" repeated)
11
14
  * node dashboard.mjs activity <feature-folder> "Phase 2 verified — T4–T6 PASS"
12
15
  * node dashboard.mjs status <feature-folder> in-progress|paused|complete|incomplete
13
16
  * node dashboard.mjs check <feature-folder>
14
17
  * node dashboard.mjs watch <feature-folder> [--watch <folder>]… [--interval-seconds 60] [--quiet-minutes 10] [--stall-minutes 30] [--max-hours 12]
15
18
  *
16
19
  * <feature-folder> is .agents/specs/<slug>. Timestamps come from this machine's local clock.
20
+ *
21
+ * Snapshots go in only through `snapshot`. `task --set` and `check` refuse any snapshot entry the page cannot show —
22
+ * an image under `path` (or `file`, `image`, …) instead of `src`, or a `src` that is not a file under the feature
23
+ * folder — because such an entry renders as "No snapshot".
17
24
  */
18
25
  import { existsSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs';
19
26
  import { basename, join, relative } from 'node:path';
@@ -30,6 +37,17 @@ const TASK_LIST_FIELDS = ['files', 'decisions', 'snapshots', 'updates'];
30
37
  const TASK_OBJECT_FIELDS = ['tests', 'details'];
31
38
  /** Statuses that mean a task is being worked on right now. */
32
39
  const ACTIVE_TASK_STATUSES = new Set(['in-progress', 'built', 'verifying']);
40
+ /** Where a snapshot's image may come from. */
41
+ const SNAPSHOT_SOURCES = ['browser', 'unity', 'blender', 'reference'];
42
+ /** Keys agents reach for instead of `src`; the page reads none of them, so the image never shows. */
43
+ const WRONG_IMAGE_KEYS = ['path', 'file', 'image', 'url', 'href'];
44
+ /** The three snapshot shapes, quoted in every refusal so the writer can fix the entry in one go. */
45
+ const SNAPSHOT_SHAPES_HELP = [
46
+ 'still { "title", "caption", "source", "src": "snapshots/T3-01-stage.png", "updates": [] }',
47
+ 'comparison { "title", "caption", "source", "before": { "src", "caption" }, "after": { "src", "caption" }, "updates": [] }',
48
+ 'progression { "title", "caption", "source", "frames": [{ "src", "stage", "caption", "task", "at" }], "updates": [] }',
49
+ 'Easier: node dashboard.mjs snapshot <feature-folder> <T3|P1|plan> --src snapshots/… --caption "…" builds the entry for you.',
50
+ ].join('\n ');
33
51
 
34
52
  const [command, featureFolder, ...rest] = process.argv.slice(2);
35
53
 
@@ -67,6 +85,10 @@ function readData(path) {
67
85
  * @param {any} data The value to write.
68
86
  */
69
87
  function writeData(path, prefix, data) {
88
+ // Every dashboard write repairs snapshot entries first, so an image filed under `path` (or any key the page never
89
+ // reads) can never reach the page as "No snapshot", whoever wrote it.
90
+ if (data && Array.isArray(data.phases)) repairSnapshots(data);
91
+ if (data && Array.isArray(data.decisions)) repairDecisions(data);
70
92
  const temporaryPath = `${path}.${process.pid}.tmp`;
71
93
  writeFileSync(temporaryPath, `${prefix} = ${JSON.stringify(data, null, 2)};\n`, 'utf8');
72
94
  renameSync(temporaryPath, path);
@@ -163,6 +185,12 @@ function writeTask(folder, argumentList) {
163
185
  if (!task) throw new Error(`task ${taskId} is not in ${dashboardPath} — sync the dashboard with the plan first`);
164
186
  const changes = JSON.parse(options.set);
165
187
  checkTaskShape(changes);
188
+ if (Array.isArray(changes.snapshots)) {
189
+ const repairs = repairSnapshotList(changes.snapshots, `${taskId}.snapshots`);
190
+ repairs.forEach((repair) => console.log(`repaired ${repair}`));
191
+ const problems = changes.snapshots.flatMap((snapshot, index) => snapshotProblems(folder, snapshot, `${taskId}.snapshots[${index}]`));
192
+ if (problems.length) throw new Error(snapshotRefusal(problems));
193
+ }
166
194
  Object.assign(task, changes);
167
195
  const now = localTime();
168
196
  if (typeof options.note === 'string') {
@@ -188,6 +216,238 @@ function checkTaskShape(changes) {
188
216
  }
189
217
  }
190
218
 
219
+ /**
220
+ * Lists what is wrong with one snapshot entry: an unknown shape, an image under a key the page never reads
221
+ * (`path` instead of `src` — the page then shows "No snapshot"), or an image file that is not on disk.
222
+ * @param {string} folder The feature folder; `src` paths are relative to it.
223
+ * @param {any} snapshot The entry.
224
+ * @param {string} where Where the entry sits, for the message, e.g. `T3.snapshots[0]`.
225
+ * @returns {string[]} One line per problem; empty when the entry renders.
226
+ */
227
+ function snapshotProblems(folder, snapshot, where) {
228
+ if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) return [`${where} is not an object`];
229
+ const problems = [];
230
+ const checkImage = (image, imageWhere) => {
231
+ if (!image || typeof image !== 'object') {
232
+ problems.push(`${imageWhere} is missing`);
233
+ return;
234
+ }
235
+ const wrongKey = WRONG_IMAGE_KEYS.find((key) => key in image);
236
+ if (wrongKey) problems.push(`${imageWhere} has "${wrongKey}" — the page reads only "src"; rename it`);
237
+ if (typeof image.src !== 'string' || !image.src) {
238
+ if (!wrongKey) problems.push(`${imageWhere} has no "src"`);
239
+ return;
240
+ }
241
+ if (/^[a-z]+:/i.test(image.src)) return;
242
+ if (!existsSync(join(folder, image.src))) problems.push(`${imageWhere}.src "${image.src}" is not a file under ${folder}`);
243
+ };
244
+ if (Array.isArray(snapshot.frames)) {
245
+ if (!snapshot.frames.length) problems.push(`${where}.frames is empty`);
246
+ snapshot.frames.forEach((frame, index) => checkImage(frame, `${where}.frames[${index}]`));
247
+ } else if (snapshot.before !== undefined || snapshot.after !== undefined) {
248
+ checkImage(snapshot.before, `${where}.before`);
249
+ checkImage(snapshot.after, `${where}.after`);
250
+ } else {
251
+ checkImage(snapshot, where);
252
+ }
253
+ if (snapshot.source !== undefined && !SNAPSHOT_SOURCES.includes(snapshot.source)) {
254
+ problems.push(`${where}.source "${snapshot.source}" must be one of ${SNAPSHOT_SOURCES.join(', ')}`);
255
+ }
256
+ if (snapshot.updates !== undefined && !Array.isArray(snapshot.updates)) problems.push(`${where}.updates must be a list`);
257
+ return problems;
258
+ }
259
+
260
+ /**
261
+ * Builds the refusal message for bad snapshot entries, quoting the shapes the page renders.
262
+ * @param {string[]} problems What is wrong, one line each.
263
+ * @returns {string}
264
+ */
265
+ function snapshotRefusal(problems) {
266
+ return `refused — these snapshots would show "No snapshot" on the page:\n ${problems.join('\n ')}\nThe shapes:\n ${SNAPSHOT_SHAPES_HELP}`;
267
+ }
268
+
269
+ /**
270
+ * Finds the snapshot list a target names: a task (`T3`, `T12.2`), a phase (`P2`) or the plan-wide After Action
271
+ * Report (`plan`).
272
+ * @param {any} dashboard The dashboard data.
273
+ * @param {string} target The target.
274
+ * @returns {any[]} The live list inside `dashboard`, created when it was missing.
275
+ */
276
+ function snapshotListFor(dashboard, target) {
277
+ if (target === 'plan') {
278
+ dashboard.afterAction = dashboard.afterAction && typeof dashboard.afterAction === 'object' ? dashboard.afterAction : {};
279
+ if (!Array.isArray(dashboard.afterAction.snapshots)) dashboard.afterAction.snapshots = [];
280
+ return dashboard.afterAction.snapshots;
281
+ }
282
+ const phaseMatch = /^P(\d+)$/i.exec(target);
283
+ const owner = phaseMatch
284
+ ? (dashboard.phases || []).find((phase) => phase.number === Number(phaseMatch[1]))
285
+ : findTask(dashboard, target);
286
+ if (!owner) throw new Error(`no ${phaseMatch ? 'phase' : 'task'} "${target}" in the dashboard — sync it with the plan first`);
287
+ if (!Array.isArray(owner.snapshots)) owner.snapshots = [];
288
+ return owner.snapshots;
289
+ }
290
+
291
+ /**
292
+ * Appends one snapshot — a still (`--src`), a comparison (`--before` and `--after`) or a progression (`--frame`,
293
+ * repeated, each `src|stage|caption`) — to a task, a phase or the plan, building the shape the page renders and
294
+ * refusing an image that is not on disk. This is the way to add snapshots: nobody writes snapshot JSON by hand.
295
+ * @param {string} folder The feature folder.
296
+ * @param {string[]} argumentList The target and options.
297
+ */
298
+ function writeSnapshot(folder, argumentList) {
299
+ const { options, positional } = parseOptions(argumentList, ['frame']);
300
+ const [target] = positional;
301
+ const usage = 'usage: snapshot <feature-folder> <T3|P1|plan> (--src snapshots/x.png | --before snapshots/a.png --after snapshots/b.png | --frame "snapshots/x.png|stage|caption"…) --caption "…" [--title "…"] [--source browser|unity|blender|reference] [--before-caption "…"] [--after-caption "…"] [--task T3]';
302
+ if (!target) throw new Error(usage);
303
+ const caption = typeof options.caption === 'string' ? options.caption : '';
304
+ const snapshot = { title: typeof options.title === 'string' ? options.title : caption, caption, source: typeof options.source === 'string' ? options.source : 'browser' };
305
+ if (typeof options.src === 'string') {
306
+ snapshot.src = options.src;
307
+ } else if (typeof options.before === 'string' && typeof options.after === 'string') {
308
+ snapshot.before = { src: options.before, caption: typeof options['before-caption'] === 'string' ? options['before-caption'] : 'Before' };
309
+ snapshot.after = { src: options.after, caption: typeof options['after-caption'] === 'string' ? options['after-caption'] : 'After' };
310
+ } else if (options.frame.length) {
311
+ const now = localTime();
312
+ snapshot.frames = options.frame.map((frame) => {
313
+ const [src, stage = '', frameCaption = ''] = String(frame).split('|');
314
+ return { src, stage, caption: frameCaption, task: typeof options.task === 'string' ? options.task : target, at: now.clock };
315
+ });
316
+ } else {
317
+ throw new Error(usage);
318
+ }
319
+ snapshot.updates = [];
320
+ const problems = snapshotProblems(folder, snapshot, target);
321
+ if (problems.length) throw new Error(snapshotRefusal(problems));
322
+ const { dashboardPath } = dataPaths(folder);
323
+ const { prefix, data } = readData(dashboardPath);
324
+ snapshotListFor(data, target).push(snapshot);
325
+ data.updatedAt = localTime().stamp;
326
+ writeData(dashboardPath, prefix, data);
327
+ }
328
+
329
+ /**
330
+ * Moves an image filed under a key the page never reads (`path`, `file`, `image`, `url`, `href`) to `src`.
331
+ * @param {any} image A still, or a comparison's `before` / `after`, or a progression frame.
332
+ * @param {string} where Where the image sits, for the repair report.
333
+ * @returns {string[]} One line per repair made.
334
+ */
335
+ function repairImage(image, where) {
336
+ if (!image || typeof image !== 'object' || Array.isArray(image)) return [];
337
+ const wrongKey = WRONG_IMAGE_KEYS.find((key) => typeof image[key] === 'string' && image[key]);
338
+ if (!wrongKey) return [];
339
+ if (typeof image.src !== 'string' || !image.src) image.src = image[wrongKey];
340
+ WRONG_IMAGE_KEYS.forEach((key) => delete image[key]);
341
+ return [`${where}: "${wrongKey}" → "src"`];
342
+ }
343
+
344
+ /**
345
+ * Repairs every entry of one snapshot list in place, so each renders an image: a bare path string becomes a still,
346
+ * an image under a wrong key moves to `src`, and an unknown `source` becomes `browser`.
347
+ * @param {any[]} list The snapshot list.
348
+ * @param {string} owner Where the list sits, e.g. `T3.snapshots`.
349
+ * @returns {string[]} One line per repair made.
350
+ */
351
+ function repairSnapshotList(list, owner) {
352
+ const repairs = [];
353
+ list.forEach((snapshot, index) => {
354
+ const where = `${owner}[${index}]`;
355
+ if (typeof snapshot === 'string' && snapshot) {
356
+ list[index] = { title: '', caption: '', source: 'browser', src: snapshot, updates: [] };
357
+ repairs.push(`${where}: a bare path → a still`);
358
+ return;
359
+ }
360
+ repairs.push(...repairSnapshot(snapshot, where));
361
+ });
362
+ return repairs;
363
+ }
364
+
365
+ /**
366
+ * Repairs one snapshot entry in place (see `repairSnapshotList`).
367
+ * @param {any} snapshot A still, comparison or progression.
368
+ * @param {string} where Where it sits.
369
+ * @returns {string[]} One line per repair made.
370
+ */
371
+ function repairSnapshot(snapshot, where) {
372
+ if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) return [];
373
+ const repairs = [];
374
+ if (Array.isArray(snapshot.frames)) {
375
+ snapshot.frames.forEach((frame, index) => repairs.push(...repairImage(frame, `${where}.frames[${index}]`)));
376
+ } else if (snapshot.before !== undefined || snapshot.after !== undefined) {
377
+ repairs.push(...repairImage(snapshot.before, `${where}.before`), ...repairImage(snapshot.after, `${where}.after`));
378
+ } else {
379
+ repairs.push(...repairImage(snapshot, where));
380
+ }
381
+ if (snapshot.source !== undefined && !SNAPSHOT_SOURCES.includes(snapshot.source)) {
382
+ repairs.push(`${where}.source "${snapshot.source}" → "browser"`);
383
+ snapshot.source = 'browser';
384
+ }
385
+ return repairs;
386
+ }
387
+
388
+ /**
389
+ * Repairs every snapshot in the dashboard in place: the After Action Report's list and comparison, each phase's and
390
+ * each task's list.
391
+ * @param {any} dashboard The dashboard data.
392
+ * @returns {string[]} One line per repair made.
393
+ */
394
+ function repairSnapshots(dashboard) {
395
+ const repairs = [];
396
+ const repairList = (list, owner) => {
397
+ if (Array.isArray(list)) repairs.push(...repairSnapshotList(list, owner));
398
+ };
399
+ if (dashboard.afterAction && typeof dashboard.afterAction === 'object') {
400
+ repairList(dashboard.afterAction.snapshots, 'afterAction.snapshots');
401
+ repairs.push(...repairSnapshot(dashboard.afterAction.comparison, 'afterAction.comparison'));
402
+ }
403
+ for (const phase of dashboard.phases || []) {
404
+ repairList(phase.snapshots, `P${phase.number}.snapshots`);
405
+ for (const task of phase.tasks || []) repairList(task.snapshots, `${task.id}.snapshots`);
406
+ }
407
+ return repairs;
408
+ }
409
+
410
+ /**
411
+ * Repairs the plan-level decisions in place: a decision written as plain text (`"D3 — The filter is …"`) renders as
412
+ * an empty row, so it becomes `{ "id": "D3", "text": "The filter is …", "updates": [] }`. A leading parenthesis after
413
+ * the id (`"D9 (confirmed by the user) — …"`) stays in the text; text with no leading id keeps an empty id.
414
+ * @param {any} dashboard The dashboard data.
415
+ * @returns {string[]} One line per repair made.
416
+ */
417
+ function repairDecisions(dashboard) {
418
+ const repairs = [];
419
+ if (!Array.isArray(dashboard.decisions)) return repairs;
420
+ dashboard.decisions = dashboard.decisions.map((decision, index) => {
421
+ if (typeof decision !== 'string') return decision;
422
+ const match = decision.match(/^([A-Z]+\d+[a-z]?)(\s*\([^)]*\))?\s+[—–-]\s+([\s\S]*)$/);
423
+ const id = match ? match[1] : '';
424
+ const text = match ? `${match[2] ? `${match[2].trim()} ` : ''}${match[3]}` : decision;
425
+ repairs.push(`decisions[${index}]: plain text → { "id": "${id}", "text" }`);
426
+ return { id, text, updates: [] };
427
+ });
428
+ return repairs;
429
+ }
430
+
431
+ /**
432
+ * Every snapshot entry in the dashboard with where it sits: the After Action Report, each phase and each task.
433
+ * @param {any} dashboard The dashboard data.
434
+ * @returns {{ snapshot: any, where: string }[]}
435
+ */
436
+ function allSnapshots(dashboard) {
437
+ const entries = [];
438
+ const collect = (list, owner) => (Array.isArray(list) ? list : []).forEach((snapshot, index) => entries.push({ snapshot, where: `${owner}.snapshots[${index}]` }));
439
+ if (dashboard.afterAction) {
440
+ collect(dashboard.afterAction.snapshots, 'afterAction');
441
+ const comparison = dashboard.afterAction.comparison;
442
+ if (comparison) entries.push({ snapshot: comparison, where: 'afterAction.comparison' });
443
+ }
444
+ for (const phase of dashboard.phases || []) {
445
+ collect(phase.snapshots, `P${phase.number}`);
446
+ for (const task of phase.tasks || []) collect(task.snapshots, task.id);
447
+ }
448
+ return entries;
449
+ }
450
+
191
451
  /**
192
452
  * Appends one milestone to the activity log.
193
453
  * @param {string} folder The feature folder.
@@ -222,14 +482,28 @@ function writeStatus(folder, argumentList) {
222
482
  }
223
483
 
224
484
  /**
225
- * Confirms both data files parse.
485
+ * Confirms both data files parse and every snapshot entry will show its image; fails listing each one that would
486
+ * show "No snapshot".
226
487
  * @param {string} folder The feature folder.
488
+ * @throws {Error} When a file does not parse or a snapshot entry is broken.
227
489
  */
228
490
  function checkData(folder) {
229
491
  const { dashboardPath, livePath } = dataPaths(folder);
230
- readData(dashboardPath);
492
+ const { prefix, data } = readData(dashboardPath);
231
493
  if (existsSync(livePath)) readData(livePath);
232
- console.log(`ok: ${dashboardPath}${existsSync(livePath) ? ` and ${livePath}` : ''} parse`);
494
+ const repairs = repairSnapshots(data);
495
+ const decisionRepairs = repairDecisions(data);
496
+ if (repairs.length || decisionRepairs.length) writeData(dashboardPath, prefix, data);
497
+ if (repairs.length) {
498
+ console.log(`repaired ${repairs.length} snapshot entr${repairs.length === 1 ? 'y' : 'ies'} the page could not show:\n ${repairs.join('\n ')}`);
499
+ }
500
+ if (decisionRepairs.length) {
501
+ console.log(`repaired ${decisionRepairs.length} decision${decisionRepairs.length === 1 ? '' : 's'} written as plain text:\n ${decisionRepairs.join('\n ')}`);
502
+ }
503
+ const snapshots = allSnapshots(data);
504
+ const problems = snapshots.flatMap(({ snapshot, where }) => snapshotProblems(folder, snapshot, where));
505
+ if (problems.length) throw new Error(snapshotRefusal(problems));
506
+ console.log(`ok: ${dashboardPath}${existsSync(livePath) ? ` and ${livePath}` : ''} parse; ${snapshots.length} snapshot entries all show an image`);
233
507
  }
234
508
 
235
509
  /**
@@ -316,6 +590,7 @@ async function watch(folder, argumentList) {
316
590
  console.log(`watchdog: dashboard status is "${dashboard.status}" — the run is over, exiting`);
317
591
  return;
318
592
  }
593
+ if (dashboard) repairWrittenSnapshots(dashboardPath);
319
594
  if (dashboard && existsSync(livePath)) {
320
595
  try {
321
596
  checkLive(dashboard, livePath, roots, projectRoot, quietMinutes, stallMinutes);
@@ -327,6 +602,23 @@ async function watch(folder, argumentList) {
327
602
  }
328
603
  }
329
604
 
605
+ /**
606
+ * Watchdog repair: a snapshot or decision an agent wrote around the helper (a hand edit, its own script) is repaired
607
+ * within a minute, re-read just before the write so nothing the agent wrote meanwhile is lost.
608
+ * @param {string} dashboardPath The dashboard data file.
609
+ */
610
+ function repairWrittenSnapshots(dashboardPath) {
611
+ try {
612
+ const { prefix, data } = readData(dashboardPath);
613
+ const repairs = [...repairSnapshots(data), ...repairDecisions(data)];
614
+ if (!repairs.length) return;
615
+ writeData(dashboardPath, prefix, data);
616
+ console.log(`watchdog: repaired ${repairs.length} entr${repairs.length === 1 ? 'y' : 'ies'} — ${repairs.join('; ')}`);
617
+ } catch (error) {
618
+ console.log(`watchdog: snapshot repair skipped a round — ${error.message}`);
619
+ }
620
+ }
621
+
330
622
  /**
331
623
  * One watchdog round (see `watch`).
332
624
  * @param {any} dashboard The dashboard data.
@@ -383,10 +675,10 @@ function checkLive(dashboard, livePath, roots, projectRoot, quietMinutes, stallM
383
675
  console.log(`watchdog ${clock}: ${activity}`);
384
676
  }
385
677
 
386
- const commands = { live: writeLive, task: writeTask, activity: writeActivity, status: writeStatus, check: checkData, watch };
678
+ const commands = { live: writeLive, task: writeTask, snapshot: writeSnapshot, activity: writeActivity, status: writeStatus, check: checkData, watch };
387
679
 
388
680
  if (!commands[command] || !featureFolder) {
389
- console.error('usage: node dashboard.mjs <live|task|activity|status|check|watch> <feature-folder> [options] — see the header of this file');
681
+ console.error('usage: node dashboard.mjs <live|task|snapshot|activity|status|check|watch> <feature-folder> [options] — see the header of this file');
390
682
  process.exit(2);
391
683
  }
392
684
  try {
@@ -1725,11 +1725,37 @@
1725
1725
  if (typeof value === 'string' && value) return [{ note: value }];
1726
1726
  return asList(value).map((update) => (typeof update === 'string' ? { note: update } : update)).filter((update) => update && typeof update === 'object');
1727
1727
  };
1728
+ // An image written under `path` (or `file`, `image`, `url`) instead of `src` would show "No snapshot": read it
1729
+ // from there and say so in the console, so the slip shows its picture and still gets fixed at the source.
1730
+ const imageKeys = ['path', 'file', 'image', 'url'];
1731
+ const repairImage = (image) => {
1732
+ if (!image || typeof image !== 'object' || image.src) return image;
1733
+ const wrongKey = imageKeys.find((key) => typeof image[key] === 'string' && image[key]);
1734
+ if (wrongKey) {
1735
+ console.warn(`Dashboard: a snapshot has its image under "${wrongKey}" instead of "src" (${image[wrongKey]}) — write snapshots with dashboard.mjs snapshot.`);
1736
+ image.src = image[wrongKey];
1737
+ }
1738
+ return image;
1739
+ };
1728
1740
  const repairSnapshots = (snapshots) => asList(snapshots)
1729
1741
  .filter((snapshot) => snapshot && typeof snapshot === 'object')
1730
- .map((snapshot) => Object.assign(snapshot, { updates: asUpdates(snapshot.updates) }, snapshot.frames !== undefined ? { frames: asList(snapshot.frames) } : {}));
1742
+ .map((snapshot) => {
1743
+ repairImage(snapshot);
1744
+ repairImage(snapshot.before);
1745
+ repairImage(snapshot.after);
1746
+ return Object.assign(snapshot, { updates: asUpdates(snapshot.updates) }, snapshot.frames !== undefined ? { frames: asList(snapshot.frames).map(repairImage) } : {});
1747
+ });
1731
1748
  data.phases = asList(data.phases);
1732
- data.decisions = asList(data.decisions).map((decision) => Object.assign(decision, { updates: asUpdates(decision.updates) }));
1749
+ // A decision written as plain text ("D3 — …") would render as an empty row: split off its id and show the text.
1750
+ const asDecision = (decision) => {
1751
+ if (typeof decision !== 'string') return decision;
1752
+ const match = decision.match(/^([A-Z]+\d+[a-z]?)(\s*\([^)]*\))?\s+[—–-]\s+([\s\S]*)$/);
1753
+ if (!match) return { id: '', text: decision };
1754
+ return { id: match[1], text: `${match[2] ? `${match[2].trim()} ` : ''}${match[3]}` };
1755
+ };
1756
+ data.decisions = asList(data.decisions).map(asDecision)
1757
+ .filter((decision) => decision && typeof decision === 'object')
1758
+ .map((decision) => Object.assign(decision, { updates: asUpdates(decision.updates) }));
1733
1759
  data.followUps = asList(data.followUps);
1734
1760
  data.activity = asList(data.activity);
1735
1761
  if (data.afterAction && typeof data.afterAction === 'object') {
@@ -100,7 +100,7 @@ Top level:
100
100
  | `runs` | number of bt-execute runs so far |
101
101
  | `afterAction` | the After Action Report (below) |
102
102
  | `phases` | the plan's phases, each with its tasks (below) |
103
- | `decisions` | `[{ "id": "D1" \| "T7", "text", "source", "updates" }]` |
103
+ | `decisions` | `[{ "id": "D1" \| "T7", "text", "source", "updates" }]` — objects, never plain `"D1 — …"` strings (the page and `check` repair one, but it is a slip) |
104
104
  | `followUps` | plain strings — what a human should look at next |
105
105
  | `activity` | `[{ "at", "text" }]`, oldest first — the milestones (the page shows newest first) |
106
106
 
@@ -178,6 +178,8 @@ Each task:
178
178
 
179
179
  ## Snapshot shapes
180
180
 
181
+ **Add snapshots with `node <skills>/bt-execute/scripts/dashboard.mjs snapshot <feature-folder> <T3|P1|plan> --src snapshots/… --caption "…"`** (`--before`/`--after` for a comparison, `--frame "src|stage|caption"` repeated for a progression) — never by writing the JSON yourself. The image key is **`src`**, relative to the feature folder; an entry with `path` (or `file`, `image`, `url`, `href`) instead would render as "No snapshot", so every helper write repairs it to `src` (and an unknown `source` to `"browser"`), `check` repairs any already in the file, the watchdog repairs one written around the helper within a minute, and the page reads those keys too. An image that is not on disk is refused — `check` fails on it. **The snapshots are the chronicle of the build: `check` passing is part of every phase commit and of run end.**
182
+
181
183
  Any list of snapshots may mix them. `source` names where the image came from: `"browser"`, `"unity"`,
182
184
  `"blender"`, `"reference"`.
183
185
 
@@ -51,7 +51,9 @@ idiom bt-prototype uses with bt-hero — **pre-resolve everything at spec time s
51
51
  job genuinely reports DONE (or a loop-card boundary fires and the user accepts the parked result — record
52
52
  which). The gauntlet's own critic evidence IS the acceptance evidence; the bt-execute verifier reads
53
53
  `progress.md` + the last round journal rather than re-judging the art. bt-execute copies the gauntlet's best
54
- evidence frames, round by round, into the feature's `snapshots/` as a progression for the feature dashboard.
54
+ evidence frames, round by round, into the feature's `snapshots/` and adds them to the feature dashboard as a
55
+ progression only through `node <skills>/bt-execute/scripts/dashboard.mjs snapshot <feature-folder> T<n> --frame "snapshots/…|<stage>|<caption>"`
56
+ (repeated per frame), then runs `dashboard.mjs check <feature-folder>` — never by writing snapshot JSON.
55
57
 
56
58
  bt-gauntlet never orchestrates bt-spec itself — composition is always initiated from the spec side.
57
59
 
@@ -149,7 +149,7 @@ Each task above is a checkbox. To implement:
149
149
  Print `🗂️ [bt-plan] Writing the feature dashboard …`. **A spec from bt-spec already has a dashboard, in its `specified` state** (showing the bt-plan commands): read its `<slug>_dashboard.js` first and keep its `feature`, `decisions` and `activity`; everything below then fills it in and moves it to `planned`. A Quick Plan, or a spec with no dashboard, creates it here. 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)*:
150
150
 
151
151
  - copy `dashboard.html` to `.agents/specs/<slug>/dashboard.html`, replacing `{{slug}}` with the slug and changing nothing else (always — over a copy bt-spec wrote too, so the page is the current template);
152
- - write `.agents/specs/<slug>/documents/<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` or `quick-plan`, size, proof, a plain-language summary), `documents` (Spec — omitted for a Quick Plan — and Plan), `status: "planned"`, `updatedAt` from the shell clock (`date '+%Y-%m-%d %H:%M'`; with no shell, the current local time), `estimate` (the Total line), every phase and task from the plan as `pending` (id, title, kind from the estimate table, verify level), an empty `afterAction` and no snapshots, the plan's Decisions as `decisions` (Heavy Plan; otherwise the spec's), and one more `activity` line: `Plan written — <n> tasks in <k> phases, estimated <range>` (after bt-spec's `Spec written` line when there is one);
152
+ - write `.agents/specs/<slug>/documents/<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` or `quick-plan`, size, proof, a plain-language summary), `documents` (Spec — omitted for a Quick Plan — and Plan), `status: "planned"`, `updatedAt` from the shell clock (`date '+%Y-%m-%d %H:%M'`; with no shell, the current local time), `estimate` (the Total line), every phase and task from the plan as `pending` (id, title, kind from the estimate table, verify level), an empty `afterAction` and no snapshots, the plan’s Decisions as `decisions` (Heavy Plan; otherwise the spec’s), each an object `{ "id": "D1", "text": "…", "updates": [] }` (never a plain `"D1 — …"` string, which shows as an empty row), and one more `activity` line: `Plan written — <n> tasks in <k> phases, estimated <range>` (after bt-spec's `Spec written` line when there is one);
153
153
  - write `.agents/specs/<slug>/documents/<slug>_live.js` from `live.template.js`, the same way (whole, strict JSON): no task, `role: "orchestrator"`, `title: "Plan written — waiting for bt-execute"`, no steps (bt-execute rewrites it at every step of a run).
154
154
  - in a git repository, make sure `.gitignore` (at the repository root) contains the line `.agents/*/*/documents/*_live.js` — append it once if missing. The live file is rewritten at every step of a run and is not history worth keeping; `<slug>_dashboard.js` is, and stays tracked. A live file git already tracks is left as it is.
155
155
 
@@ -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
 
@@ -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 |
@@ -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
 
@@ -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