@babylonjs-toolkit/agent 1.1.80 → 1.1.82

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.
@@ -30,7 +30,7 @@ Turn a feature spec into `.agents/specs/<slug>/documents/<slug>_plan.md`: an ord
30
30
  ## Step 1. Analyze (required before writing)
31
31
 
32
32
  1. Read the feature spec in full, and `SPEC.md`'s headings, Architecture, Conventions and the systems the feature touches. The plan must conform to SPEC.md — **if it would conflict, stop and tell the user.** Verification procedures described in SPEC.md are tooling you may reuse, not a bar the plan must meet. Note the spec's `spec_impact`, `size` and `proof`.
33
- 2. **Start from the spec's `## Research Notes`, and any bt-recon doc (`.agents/recon/*_recon.md`) it cites or whose scope covers the systems the feature touches** — its Extension Points and End-to-End Flows usually name the integration points directly. Spot-check that the paths exist, then research only what a plan needs beyond them: how the app is built and tested, the real conventions and the closest feature to mirror, the concrete files and integration points, available dependencies, constraints from the agent instructions.
33
+ 2. **Start from the spec's `## Research Notes`, and any bt-recon doc it cites (the feature's own `recon/` copies, or `.agents/recon/*_recon.md`) or whose scope covers the systems the feature touches** — its Extension Points and End-to-End Flows usually name the integration points directly. Spot-check that the paths exist, then research only what a plan needs beyond them: how the app is built and tested, the real conventions and the closest feature to mirror, the concrete files and integration points, available dependencies, constraints from the agent instructions.
34
34
  3. Size the research: `small` → inline; `medium` / `large` (or no Research Notes) → up to 3 **read-only** subagents returning findings and paths, not file dumps. Tell each one verbatim: *"Read-only: you may read, search and report. Do not edit or create files, and do not run builds, tests or any command that writes — not even into a build folder. If a fact needs a build or a test run to establish, report it as unknown and say which command would settle it."*
35
35
  4. Sibling-skill pattern (e.g. bt-design's 3D-Hero-Scroll): read that skill's reference **and templates** *(where skills load through a tool: `load_skill` + `read_skill_resource`, never a guessed path; where they are files: the skills directory this skill was loaded from, e.g. `~/.claude/skills/`, `~/.agents/skills/` or the project's equivalent)*. The plan **copies and configures the template engine — never re-implements it**; each behavioral option the spec records (e.g. `sweep: page`) becomes an Acceptance item stated in observable terms. Prefer copying and wiring the template as the first task, so later tasks only configure it.
36
36
  5. Too ambiguous to plan responsibly → ask the user. **Already built?** If the research shows some or all of the feature already exists, say so first and plan only what is missing (often just tests and the live check).
@@ -85,32 +85,51 @@ Print `✍️ [bt-plan] Writing .agents/specs/<slug>/documents/<slug>_plan.md
85
85
 
86
86
  **`## Estimated execution time`** — **agent time, from the calibration below — never developer-hours, and never by adding up activities.** Builds, exports, captures and browser looks are *not* separate line items: they happen inside a task's own run and are already inside the per-task rate. Counting them separately is how a 10-hour plan gets estimated at 45 hours.
87
87
 
88
- Rate each task by the **kind of work it does** (classify tasks, not the plan — most plans mix kinds), sum, then give a range of **−30 % / +40 %**. Nothing else is added — no per-phase overhead (it did not show up in the measurements):
88
+ Rate each task by the **kind of work it does** (classify tasks, not the plan — most plans mix kinds), sum, then give a range of **−35 % / +50 %**. Nothing else is added — no per-phase overhead (it did not show up in the measurements):
89
89
 
90
90
  | Kind | min/task | What puts a task here |
91
91
  | --- | --- | --- |
92
- | **Code** | 8 | Code + tests, at most a quick browser look or one small scripted export. |
93
- | **Live** | 18 | Proven by running it: live external APIs, browser game builds, live memory or perf runs in one engine, a visual match to a reference image. |
92
+ | **Code** | 6 | Code + tests, at most a quick browser look or one small scripted export. |
93
+ | **Live** | 16 | Proven by running it: live external APIs, a page or scene loaded and probed in a browser, live memory or perf runs in one engine, a visual match to a reference image. |
94
+ | **Game** | 40 | Proven by **playing the running game**: races, laps or levels driven through scenarios, a two-page network session, reproducing an intermittent in-game bug, tuning feel or sound by eye and ear. |
94
95
  | **Unity / parity / GPU** | 35 | Authoring or re-exporting Unity content, measured parity against Unity Play mode, GPU shader backends, perf A/B across beds, exporter DLL + runtime changed together. |
95
96
 
96
- - **Do not budget fix rounds.** They are inside the rates: across the 2026-10 runs about one task in four needed a second attempt, and every one of those is already in the numbers. Defensively budgeting rounds per phase was the single largest source of over-estimation in the first calibration.
97
+ - **Live or Game?** Loading a scene and reading values from it is Live. Playing it until something happens is Game. Game work ran 1.2–2.8× its estimate when it was rated Live, because every scenario is a real-time play session and a bug that only shows on lap three costs three laps each time it is checked.
98
+ - **Do not budget fix rounds.** They are inside the rates: about one task in four needed a second attempt in both calibrations, and every one of those is already in the numbers. Defensively budgeting rounds per phase was the single largest source of over-estimation in the first calibration.
97
99
  - **Do not add a further margin.** The range is the margin. Do not discount for parallel phases either — the rates are wall-clock with bt-execute's usual parallelism.
98
- - **Outsized work:** a task that builds a compiler or transpiler, or must prove coverage across many Unity sample projects, runs about **2×** the Unity rate (shadergraph-transpiler-complete-coverage: 72 min/task). Multiply by ~2 for `proof: parity` only if the plan really carries numeric gates, and by ~2–3 for `bt-execute --strict` (neither measured yet).
99
- - **The estimate covers the plan as written.** Tasks added mid-run cost far more than planned ones — unity-terrain-system-parity's 17 planned tasks took about 6 h, the 9 added during the run about 21 h. Say so in the biggest-uncertainty line when the scope is still moving.
100
-
101
- **Calibration (measured 2026-10-07 from transcript + commit timestamps; 21 clean bt-execute runs across Runtime and AgentWorkspace, 242 tasks, waits on the user and planning subagents excluded):**
102
-
103
- | Kind | Plans (min/task) | Median |
104
- | --- | --- | --- |
105
- | Code | effort-selector 5 · scene-loading-progress 7 · unity-gzip-sidecar-binaries 10 · texture-image-deduplication 11 | 8.5 |
106
- | Live | auto-exposure-parity 10 · procedural-skybox 16 · camera-antialiasing-parity 16 · no-unbilled-usage 16 · kie-sound 16 · tool-loop 17 · media-gateways 18 · managed-agents-engine 21 · scene-dispose-memory-leaks 25 | 16.5 |
107
- | Unity / parity / GPU | shuriken-particle-system 22 · unity-gui-pipeline-parity 23 · unity-export-parity-gaps 27 · camera-antialiasing-taa 28 · hdrp-raster-parity-followup 31 · hdrp-complete-parity 37 · terrain-performance 38 · hdrp-raytracing-polyfill 40 | 29 |
108
-
109
- These rates put 17 of the 21 runs inside the −30 % / +40 % range and 20 of 21 within 0.6–1.6× (the old flat `tasks × 17 + phases × 10`: 13 of 21 within 0.6–1.6×), and the misses ran fast, not slow. Under the flat rate, plans estimated themselves about **2.5× too high** when the work was mostly code and up to **2× too low** when it was Unity, parity or GPU work — wrong in both directions, so classify every task.
100
+ - **Outsized work is 2× the task's own kind rate**, never a flat figure. A task that ports a whole engine subsystem rated as Code is 12 min, not the Unity rate doubled (fusion-networking rated its nine engine-scale code tasks at a flat 72 min each, estimated 15.7 h and ran 6.4 h). A task that builds a compiler or transpiler, or must prove coverage across many Unity sample projects, is 2× Unity (shadergraph-transpiler-complete-coverage: 72 min/task). Multiply by ~2 for `proof: parity` only if the plan really carries numeric gates, and by ~2–3 for `bt-execute --strict` (neither measured yet).
101
+ - **Unity frame-matching runs long.** A task proven by matching Unity frame by frame (animation feel, foot IK, landing poses) is where Unity tasks overran most (starter-assets-third-person: 2.4×). Name it as the biggest uncertainty.
102
+ - **The estimate covers the plan as written.** Tasks added mid-run cost far more than planned ones — unity-terrain-system-parity's 17 planned tasks took about 6 h, the 9 added during the run about 21 h; mario-kart-port grew from 22 to 42 tasks. Say so in the biggest-uncertainty line when the scope is still moving. Tasks added after a plan is complete get their own estimate at these rates.
103
+
104
+ **Calibration (third, 2026-10-19; 40 runs).** 19 new bt-execute runs (Runtime, 2026-10-07 → 10-19, 190 tasks) measured from their `⏱` lines, active time only, with waits on the user excluded, fitted per task kind together with the 21 runs of the 2026-10-07 calibration. Each new run's actual ÷ estimate at these rates:
105
+
106
+ | Run | Mix (tasks by kind, outsized counted 2×) | Active | ÷ estimate |
107
+ | --- | --- | --- | --- |
108
+ | ugui-animation-parity | code 4 · Unity 5 | 80 min | 0.40 |
109
+ | draco-mesh-compression | code 3 · Unity 4 | 90 min | 0.57 |
110
+ | light-probe-network-toggle | code 5 · live 1 | 29 min | 0.63 |
111
+ | mario-kart-audio-parity | code 2 · game 4 | 112 min | 0.65 |
112
+ | navigation-areas-costs | code 9 · live 1 · Unity 2 | 92 min | 0.66 |
113
+ | lens-flares-all-pipelines | code 2 · live 3 · Unity 6 | 204 min | 0.76 |
114
+ | prewarm-behind-splash | code 3 · live 5 · GPU 1 | 103 min | 0.77 |
115
+ | unity-timeline-playback | code 5 · Unity 6 | 186 min | 0.78 |
116
+ | babylon-game-server | code 8 · live 8 | 157 min | 0.89 |
117
+ | mario-kart-leftover-particles | game 5 | 189 min | 0.94 |
118
+ | fusion-networking | code 20 · Unity 8 | 385 min | 0.96 |
119
+ | mario-kart-drift-vfx-parity | Unity 2 · game 1 | 107 min | 0.97 |
120
+ | cinemachine-port | code 10 · Unity 14 | 560 min | 1.02 |
121
+ | vfx-graph-port | code 10 · Unity 7 | 310 min | 1.02 |
122
+ | unity-animator-port (run 1) | code 7 · live 3 · Unity 9 | 455 min | 1.12 |
123
+ | mario-kart-antigravity | Unity 2.3 · game 2 | 230 min | 1.43 |
124
+ | terminal-portals-fps-controller | code 5 · live 1 · Unity 6 | 375 min | 1.46 |
125
+ | prewarm-splash-status | code 1 · live 1 | 36 min | 1.64 |
126
+ | starter-assets-third-person | code 2 · live 1 · Unity 3 · game 1 | 411 min | 2.38 |
127
+
128
+ Across all 40 runs the median actual ÷ estimate is **1.00**; 30 of 40 land inside −35 % / +50 % and 34 of 40 within 0.6–1.6×. The previous rates (code 8 · live 18 · Unity 35, −30 % / +40 %) put only 11 of the 19 new runs inside their range: they ran about 2× high on engine-code plans and up to 2× low on plans that play the game. Excluded from the fit: mario-kart-port (scope grew 22 → 42 tasks mid-run), hdrp-complete-parity's run 2 (a reopened, deferred task), and the user-directed follow-up runs of draco-mesh-compression and unity-animator-port.
110
129
 
111
130
  To recalibrate later, read the `⏱` lines bt-execute writes to each `documents/<slug>_autopilot.md` (older runs: `<plan>_autopilot.md` beside a flat plan) — they carry the plan's estimate, active minutes per phase and per run, and waits already separated out.
112
131
 
113
- Write a table `Phase | Tasks | Kind (code / live / Unity) | What makes it slow | Estimate`, then one **Total** line in hours (days only if over ~16 h), the `--strict` multiplier, and the biggest uncertainty in one line. If the total averages above ~40 or below ~6 min per task, the estimate is wrong before the plan is: re-check it. An estimate, never a pin.
132
+ Write a table `Phase | Tasks | Kind (code / live / game / Unity) | What makes it slow | Estimate`, then one **Total** line in hours (days only if over ~16 h), the `--strict` multiplier, and the biggest uncertainty in one line. If the total averages above ~45 or below ~5 min per task, the estimate is wrong before the plan is: re-check it. An estimate, never a pin.
114
133
 
115
134
  **`## How to execute this plan`** — this text verbatim:
116
135
 
@@ -1,7 +1,7 @@
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 — and, with --auto-fix, 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
- allowed-tools: Read, Grep, Glob, Edit, Write, Bash
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`)."
4
+ allowed-tools: Read, Grep, Glob, Edit, Write, Bash, Agent, Task
5
5
  ---
6
6
 
7
7
  You are an EXPERT BabylonJS, Babylon Toolkit and browser performance engineer. The skill is built for Babylon Toolkit projects but profiles **any web app**: a page with no Babylon engine gets everything except the engine-only numbers (see *Any web app*). Always adhere to any rules or requirements set out in the project's agent instructions (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md).
@@ -14,7 +14,7 @@ Use the user's message after the skill name as the `arguments`.
14
14
 
15
15
  ```
16
16
  /bt-profile [<brief: what is slow, when>] [--project:<path>] [--url:<game URL>] [--scenario:<name|path>] [--slug:<name>]
17
- [--auto-fix] [--snapshots] [--watch] [--gpu-cold] [--no-warm] [--settle:<seconds>] [--runs:<n>] [--trace]
17
+ [--auto-fix] [--recon] [--snapshots] [--watch] [--gpu-cold] [--no-warm] [--settle:<seconds>] [--runs:<n>] [--trace]
18
18
  [--stop[:<slug>]] [--resume[:<slug>]] [--restart[:<slug>]]
19
19
  [--max-fixes:<n>] [--target-fps:<n>] [--dpr:<n>] [--args:key=value,…]
20
20
  ```
@@ -25,6 +25,7 @@ Use the user's message after the skill name as the `arguments`.
25
25
  - **`--scenario:`** — the slug's `data/scenario.mjs`, or a path to copy into it. Default: the slug's own; with none, write one (Phase 0).
26
26
  - **`--slug:`** — the profiled moment, and its folder: `.agents/profile/<slug>/` holds `dashboard.html` and `data/` (config, scenario, findings, runs, logs). Default: the scenario's name (e.g. `race-start`). A new moment gets a new slug; never mix two scenarios' runs in one slug.
27
27
  - **`--auto-fix`** — also apply the fixes: one at a time, each re-measured and kept only when it wins (Phase 3). **Off by default**: a plain run measures and diagnoses, changes no code, and lists every fix. Either way the report has **The fixes** — every fix with its status, expected gain and risk — so the user can spec them one by one or as a group with `bt-spec` (the dashboard copies the command; `findings.md` beside it carries each fix's cause, evidence, code, proposed change, gain, risk and how to verify it). `--no-fix` / `--analyze` from earlier versions mean the default.
28
+ - **`--recon`** — run bt-recon on the code behind the problem (*Recon* below): before measuring, on the code behind the slow moment, so the scenario marks the right phases and the census counts the right calls; after diagnosing, a quick recon of each subsystem whose finding's cause is still inferred from the profile alone, so every cause is traced in the code. **`--auto-fix` always turns it on** — no fix is applied to code that has not been mapped (its callers, invariants and tests), and `--auto-fix --no-recon` is refused. Off by default for a plain run, whose report still offers a recon command for each subsystem.
28
29
  - **`--stop[:<slug>]`** — stop a running profile: ends its capture and Chrome (`progress.mjs stop`), marks the run stopped on the dashboard, rebuilds the report from what was captured. Without a slug: the one running profile in the project (ask when there are several).
29
30
  - **`--resume[:<slug>]`** — continue a stopped profile where it stopped (`progress.mjs resume` prints the stage and the fixes' states): skip what is done, re-measure a fix left half-way, carry on. The dashboard shows it as the next run number.
30
31
  - **`--restart[:<slug>]`** — profile the slug again from a fresh baseline with the same config and scenario (after code changes, a stopped run you do not want to continue, or a finished one): `progress.mjs restart` moves the earlier runs, findings and report to `data/archive/<date-time>/` — compare with them in the new report.
@@ -43,7 +44,7 @@ Use the user's message after the skill name as the `arguments`.
43
44
 
44
45
  # What this skill guarantees
45
46
 
46
- 1. **Measured, never guessed.** Every finding cites the profile: the function, its owner, its ms per frame, the phase, and the code of yours behind it. No fix is made on a hunch.
47
+ 1. **Measured, never guessed.** Every finding cites the profile: the function, its owner, its ms per frame, the phase, and the code of yours behind it, and says whether its cause is `confirmed` in the code or still `inferred` from the profile. No fix is made on a hunch, and with `--auto-fix` none is made on an inferred cause.
47
48
  2. **Fixes are listed; applied only with `--auto-fix`, one at a time, proven.** Each applied fix is re-measured with the same scenario; it is kept only when its target cost falls and the phase it serves gets faster beyond the measured noise. Otherwise it is reverted, and the report says so.
48
49
  3. **The user's work is safe.** Uncommitted changes in the working tree are recorded first and never reverted, stashed or committed. Fixes are made as small, reviewable edits; the report carries each diff. Nothing is committed unless the user asks.
49
50
  4. **It still works and looks the same.** After the fixes: typecheck / build, the project's tests, a clean console, and (`--snapshots`) the same phases screenshotted before and after.
@@ -110,13 +111,15 @@ PROF="$PROJ/.agents/profile"; TOOLS="$PROF/.tools" # shared by e
110
111
  SLUG=<slug>; S="$PROF/$SLUG"; DATA="$S/data"; DASHBOARD="$S/dashboard.html"
111
112
  ```
112
113
 
113
- One folder per profiled moment — everything a slug's runs produce stays inside it:
114
+ One folder per profiled moment — everything a slug's runs produce stays inside it, its recons included, so the folder moves or archives as one piece:
114
115
 
115
116
  ```
116
117
  .agents/profile/
117
118
  .tools/ the installed scripts + node_modules (git-ignored, shared)
118
119
  <slug>/
119
120
  dashboard.html the dashboard — live while a run goes on, the report once it is done
121
+ findings.md the diagnosis as a spec-ready document, with the recon and spec commands
122
+ recon/ this profile's bt-recon docs, one per subsystem (--recon, or the report's commands)
120
123
  data/
121
124
  progress.js the run's live progress, written by progress.mjs (git-ignored)
122
125
  profile.config.json URL, scenario, owner rules (a new slug copies a sibling's owners)
@@ -163,10 +166,11 @@ git -C "$PROJ" status --short > "$DATA/worktree-at-start.txt"
163
166
  "sourceRoots": ["/abs/UnityProject/Assets/Scripts"] } ] }
164
167
  ```
165
168
  Add an owner rule for every script **the user owns that ships without a source map** — typically the Unity exporter's project bundle (`scenes/<Product>.js`), compiled from TypeScript under the Unity project's `Assets/`. `sourceRoots` lets analysis find the class's `.ts` file and method line. Owners marked `yours` are charged with the library work they trigger.
166
- 3. **The scenario.** It must play the moment the user says is slow, the way a player would, and mark its phases. **Enter the app the way a player does**: open the page they open (usually the home page) and click through what they click (the menu, the level's button — `context.expectNavigation()` first when the click loads a new page). Use a URL you build yourself (query parameters, a route the UI never links to) only when that is how players really arrive: it can take a path they never take — in one game a `?scene=…gz.gltf` query made the dev server mislabel the page itself as gzip, and the capture recorded a white screen. Reuse `$DATA/scenario.mjs` when it exists; otherwise copy `templates/scenario.template.mjs` there and adapt it: read the game's code to find what to wait on (a component's phase field, a ready flag) and how to reach it from the page (`window.TOOLKIT.SceneManager.SearchForScriptComponentByName(scene, alias)`, `window.PROJECT.*`). Mark the **reveal** — the moment the loading screen goes away (for a toolkit splash: `#xbabylonjsSplashScreen` gets `opacity: 0`) — as its own phase: games often start their intro behind the splash, and hitches before the reveal are load time, not stutter the player sees. Hold input like a player (keys through `context.keyDown`). If the scenario must keep the game going without a player (a race after the start), hand the player's object to the game's own AI component — never skip or disable work to get there. **Size `settle`** (`--args settle=<seconds>`, the seconds recorded after the moment) to the moment: long enough to cover it and a calm stretch after it (a 3-second launch stutter needs ~15–20 s; a frame rate that sinks over a race needs 90), and short of where the scenario stops being realistic (the car reaches a wall, the level ends).
167
- 4. **Other sessions.** Find the other agent sessions on this machine — the harness's session-listing tool when it has one (Claude Code: `ListAgents`); otherwise the running dev servers and browsers (`ps`, `lsof -iTCP -sTCP:LISTEN`) and recent file times — and check `git status` / `git log` in every repo you may touch. Another session working in the same project or runtime shares the dev server, the runtime build and the commits: tell it which files you change (and ask it to leave them out of its commits), give a one-line heads-up before restarting a dev server or rebuilding a library it serves, and pause captures while it runs timing-sensitive checks. Its edits also move your numbers — compare runs taken on the same code, and say so in the report when you could not.
169
+ 3. **Recon the moment** (with `--recon`, so always with `--auto-fix`). Before writing the scenario, map the code behind the moment the brief names: run bt-recon (*Recon* below) with the brief `the code behind <the moment>: what runs from <the trigger> to <the end>, per frame and once, and what it waits on` and `--slug <slug>`. Its End-to-End Flows tell the scenario what to wait on and where to put the phase marks; its hot-path functions are the census candidates for Phase 2.
170
+ 4. **The scenario.** It must play the moment the user says is slow, the way a player would, and mark its phases. **Enter the app the way a player does**: open the page they open (usually the home page) and click through what they click (the menu, the level's button — `context.expectNavigation()` first when the click loads a new page). Use a URL you build yourself (query parameters, a route the UI never links to) only when that is how players really arrive: it can take a path they never take — in one game a `?scene=…gz.gltf` query made the dev server mislabel the page itself as gzip, and the capture recorded a white screen. Reuse `$DATA/scenario.mjs` when it exists; otherwise copy `templates/scenario.template.mjs` there and adapt it: read the game's code to find what to wait on (a component's phase field, a ready flag) and how to reach it from the page (`window.TOOLKIT.SceneManager.SearchForScriptComponentByName(scene, alias)`, `window.PROJECT.*`). Mark the **reveal** — the moment the loading screen goes away (for a toolkit splash: `#xbabylonjsSplashScreen` gets `opacity: 0`) — as its own phase: games often start their intro behind the splash, and hitches before the reveal are load time, not stutter the player sees. Hold input like a player (keys through `context.keyDown`). If the scenario must keep the game going without a player (a race after the start), hand the player's object to the game's own AI component — never skip or disable work to get there. **Size `settle`** (`--args settle=<seconds>`, the seconds recorded after the moment) to the moment: long enough to cover it and a calm stretch after it (a 3-second launch stutter needs ~15–20 s; a frame rate that sinks over a race needs 90), and short of where the scenario stops being realistic (the car reaches a wall, the level ends).
171
+ 5. **Other sessions.** Find the other agent sessions on this machine — the harness's session-listing tool when it has one (Claude Code: `ListAgents`); otherwise the running dev servers and browsers (`ps`, `lsof -iTCP -sTCP:LISTEN`) and recent file times — and check `git status` / `git log` in every repo you may touch. Another session working in the same project or runtime shares the dev server, the runtime build and the commits: tell it which files you change (and ask it to leave them out of its commits), give a one-line heads-up before restarting a dev server or rebuilding a library it serves, and pause captures while it runs timing-sensitive checks. Its edits also move your numbers — compare runs taken on the same code, and say so in the report when you could not.
168
172
  While anyone else edits the project, **never capture on a watching dev server**: one save hot-patches or reloads the game mid-run (the capture logs `WARNING: … restarted` and the report shows a banner). Profile a frozen copy instead: `git archive HEAD | tar -x -C <scratchpad>/snapshot`, copy in your own uncommitted project changes, link `node_modules` to the live project's, and serve it on a spare port with a config that wraps the project's — `mergeConfig(base, { cacheDir: ".vite-profile-cache", server: { watch: null, hmr: false, fs: { strict: false } } })` (its own optimizer cache, since `node_modules` is shared). Warm it once, then capture against that port. Library builds the project links to (a runtime) are still live — keep the heads-up for those.
169
- 5. **Smoke run** (`node "$TOOLS/profile.mjs" --out runs/smoke --args settle=15 --snapshots true`, from `$DATA`): look at the screenshots and confirm the scenario really did what the user described (the countdown ran, the player moved, the particles fired). Fix the scenario before measuring anything.
173
+ 6. **Smoke run** (`node "$TOOLS/profile.mjs" --out runs/smoke --args settle=15 --snapshots true`, from `$DATA`): look at the screenshots and confirm the scenario really did what the user described (the countdown ran, the player moved, the particles fired). Fix the scenario before measuring anything.
170
174
  - **When it fails** (`scenario failed` or `--seconds` in the log), the log names the evidence: `shots/failed.png` (what the page showed), the page's address and title, its visible text, and its console errors and failed document / script loads. A white page with a failed document load is a server or routing problem, not the game.
171
175
  - **Never read the smoke run for stutter**: each screenshot stalls the page 0.5–2 s — a long frame with no script in it, lined up with a `shot` line in the log. It looks exactly like a hitch.
172
176
  - **The first capture of a session may be the only GPU-cold one** (see `--gpu-cold`): if it shows a hitch the later ones do not, that is a first-visit cost, not noise — re-capture with `--gpu-cold true` to reproduce it at will.
@@ -206,7 +210,9 @@ Work from the brief's phases outward. For each phase that misses the target:
206
210
  7. **Worst frames** name the spikes (a spawn, a burst, a compile) that averages hide.
207
211
  8. **Allocations**: phase `heap` lists show who feeds the garbage collector while playing.
208
212
 
209
- Write `$DATA/findings.json` (schema in `scripts/report.mjs`): per finding a severity, the phases, the cost in ms/frame and % of the phase, the cause in plain language, the evidence (numbers from the analysis), the code locations, the planned fix. Rank by the time it would win in the phases the user cares about.
213
+ 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
+
215
+ 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.
210
216
 
211
217
  ## Phase 3 — Fix, one at a time (only with `--auto-fix`)
212
218
 
@@ -216,6 +222,7 @@ Without `--auto-fix`, skip this phase: no code changes. Every finding still carr
216
222
 
217
223
  For each finding, highest win first:
218
224
 
225
+ 0. **Know what the change must not break.** Read the recon of the finding's subsystem (Phase 2 made one for every inferred cause; make a quick one now for any other subsystem the fix changes) and its `guards`. A finding whose cause is still `inferred` is not fixed: trace it first, or leave it `proposed` with why.
219
226
  1. **Change the cause, not the symptom.** Prefer the smallest change that removes the work: cache instead of recompute, compute once instead of per frame, per object instead of per child, configure the library (freeze, static, refresh rate, capacity), pool instead of create, pre-warm at load instead of at first use. Follow the Agent Reference's coding rules; never disable a feature the user can see or hear to win time.
220
227
  2. **Where the code lives decides how it ships.** Project source: edit it; the dev server reloads. The Babylon Toolkit runtime, when the user owns its source (they say so, or its repo is theirs): fix it there with a regression test in its own test suite, run the suites that touch the area, rebuild the way that repo documents (never a step that copies the build into other repos), and restart the dev server with `--force` so it serves the new build. A project-owned bundle (Unity exporter project bundle): edit its source under the Unity project and rebuild the bundle the way the project documents (e.g. `unity command bt_build_project`), then confirm the served bundle changed. The Babylon Toolkit runtime / BabylonJS / other libraries: do not edit — change the calling code, or record the defect as a finding for the library's owner.
221
228
  3. **Re-measure** with the same scenario and flags (warm the dev server first if it restarted), into `runs/fix-<n>-<short-name>`; analyze; `compare.mjs --before <last kept> --after <this> --focus "<the functions the fix targets>"`.
@@ -248,7 +255,18 @@ node "$TOOLS/report.mjs" --analysis runs/final/cold/analysis.json --baseline run
248
255
  [--snapshots runs/final-shots/cold --snapshots-before runs/baseline-shots/cold] # writes $DASHBOARD (../dashboard.html)
249
256
  ```
250
257
 
251
- (Without `--auto-fix`: `--analysis` is the run that shows the problem — the baseline, or the reproduction run when the baseline did not — and `--warm` its own warm capture when it has one: `--analysis runs/baseline/cold/analysis.json --warm runs/baseline/warm/analysis.json`. Every finding carries `fix` (the proposed change), `gain`, `risk` and `verify`; name the reproduction run and how it differs from a plain capture in the findings' evidence.) Every report lists **The fixes** (each with a copy-able `/bt-spec` command, and one for any group the user ticks) whether they were applied or not. The report also writes `dashboard.pdf` (its **Download PDF** button; `--pdf false` skips it) and `findings.md` (the spec-ready diagnosis). The page has **Print** too. Then end the run — `node "$TOOLS/progress.mjs" end "$S" --summary "<the verdict in one sentence>"` — so the page leaves live mode and the watchdog exits. The dashboard is already open (`start --open true`) and reloads into the report by itself — do not open a second tab; check it renders at desktop and phone width with no console errors (a headless screenshot of the file is enough). Stop every dev server and Chrome the run started. Then tell the user: the verdict in two sentences, each finding with its before → after, what was reverted and why, what remains and what it would take, and the report path.
258
+ (Without `--auto-fix`: `--analysis` is the run that shows the problem — the baseline, or the reproduction run when the baseline did not — and `--warm` its own warm capture when it has one: `--analysis runs/baseline/cold/analysis.json --warm runs/baseline/warm/analysis.json`. Every finding carries `fix` (the proposed change), `gain`, `risk` and `verify`; name the reproduction run and how it differs from a plain capture in the findings' evidence.) Every report lists **The fixes** whether they were applied or not, in two steps: **recon** (one copy-able `/bt-recon` command per subsystem, writing into this profile's `recon/` folder, or a `--refresh` when a deep recon already exists) and **spec** (a `/bt-spec` command per fix and for any group the user ticks, citing those recon docs with `using @…_recon.md`). The report also writes `dashboard.pdf` (its **Download PDF** button; `--pdf false` skips it) and `findings.md` (the spec-ready diagnosis). The page has **Print** too. Then end the run — `node "$TOOLS/progress.mjs" end "$S" --summary "<the verdict in one sentence>"` — so the page leaves live mode and the watchdog exits. The dashboard is already open (`start --open true`) and reloads into the report by itself — do not open a second tab; check it renders at desktop and phone width with no console errors (a headless screenshot of the file is enough). Stop every dev server and Chrome the run started. Then tell the user: the verdict in two sentences, each finding with its before → after, what was reverted and why, what remains and what it would take, and the report path.
259
+
260
+ ---
261
+
262
+ # Recon
263
+
264
+ bt-profile runs bt-recon itself with `--recon` (always under `--auto-fix`): follow bt-recon's SKILL.md, which sits beside this skill (`<skills directory>/bt-recon/SKILL.md`; where skills load through a tool, `load_skill('bt-recon')`). Run it in a subagent where the host has one, and post a `now` line before and after each (a recon takes minutes).
265
+
266
+ - **Flags:** `--quick --no-guide --no-live --slug <subsystem-slug> --out .agents/profile/<slug>/recon`. A profile's recons stay in its own folder.
267
+ - **The brief** names the subsystem, the code locations the findings cite, the findings file (`@.agents/profile/<slug>/findings.md` once written), and the question: how it works, every caller, what drives its per-frame cost, and what a change there must not break.
268
+ - **Reuse before making one.** A recon of the same slug in the profile's `recon/`, or in `.agents/recon/`, is used as it is when its `commit:` still matches the files it covers. Refresh it (`--refresh`) when they changed. Never make a second recon of the same code.
269
+ - **Quick here, deep for the spec.** The recons bt-profile runs are quick ones (`depth: quick` in their header); they are enough to confirm a cause and list the guards. The report's recon commands make the deep recon a spec rests on, and replace the quick one in place.
252
270
 
253
271
  ---
254
272
 
@@ -297,6 +315,8 @@ What a heavy function usually means, and where to look. Always confirm with `cal
297
315
  |---|---|
298
316
  | `.agents/profile/.tools/` | The installed scripts and their node_modules, shared by every slug (git-ignored) |
299
317
  | `.agents/profile/<slug>/dashboard.html` | The dashboard — follows the run live, then holds the report |
318
+ | `.agents/profile/<slug>/findings.md` | The diagnosis as a spec-ready document: the recon command per subsystem and the spec command per fix |
319
+ | `.agents/profile/<slug>/recon/` | This profile's bt-recon docs, one per subsystem — quick ones from `--recon`, deep ones from the report's commands |
300
320
  | `.agents/profile/<slug>/data/progress.js` | The run's live progress: status, stages, fixes, numbers, what is happening now (written only by `progress.mjs`; git-ignored) |
301
321
  | `.agents/profile/<slug>/data/profile.config.json` | URL, scenario, owner rules and source roots |
302
322
  | `.agents/profile/<slug>/data/scenario.mjs` | The repeatable scenario |
@@ -13,9 +13,18 @@
13
13
  * findings.json (written by the agent — the diagnosis in plain language):
14
14
  * { "title", "summary", "findings": [{ "id", "title", "severity": "critical|major|minor", "status": "fixed|proposed|reverted|not-fixed",
15
15
  * "phases": [..], "cost", "cause", "evidence": [..], "code": [{ "file", "line", "label" }], "fix", "before", "after", "diff",
16
- * "gain", "risk", "verify" }] } (gain / risk / verify: optional — the expected win, what could break, how to prove it)
16
+ * "gain", "risk", "verify",
17
+ * "subsystem", "recon", "confidence": "confirmed|inferred", "guards": [..] }] }
18
+ * gain / risk / verify: optional — the expected win, what could break, how to prove it.
19
+ * subsystem: the code the fix lives in, in a few words ("Shadow rendering"); fixes that share one share a recon.
20
+ * recon: the bt-recon doc of that code, from the project root — the profile's own (".agents/profile/<slug>/recon/
21
+ * shadow-rendering_recon.md") or a general one (".agents/recon/shadow-rendering_recon.md").
22
+ * confidence: "confirmed" once the cause is traced in the code, "inferred" while it rests on the profile's shape alone.
23
+ * guards: what a change there must not break — callers, invariants, the tests that cover it (from the recon).
17
24
  * Every build also writes findings.md beside the dashboard: the same diagnosis as a spec-ready document (one section per
18
25
  * finding — cause, evidence, code, proposed fix, gain, risk, how to verify) to fix later with a full spec (bt-spec).
26
+ * Both list a bt-recon command per subsystem (the code behind the fixes, mapped for the spec) and bt-spec commands that
27
+ * cite those recon docs.
19
28
  */
20
29
  import fs from "node:fs";
21
30
  import path from "node:path";
@@ -221,6 +230,9 @@ footer.generated-by a { color: inherit; }
221
230
  table.fixes td.pick, table.fixes th.pick { width: 28px; } table.fixes td.id { font: 600 12px var(--mono); white-space: nowrap; }
222
231
  table.fixes td.act { text-align: right; white-space: nowrap; }
223
232
  table.fixes .badge { white-space: nowrap; }
233
+ table.fixes td.act { white-space: nowrap; } table.fixes td.act .copy-spec + .copy-spec { margin-left: 6px; }
234
+ .badge.confirmed, .badge.recon-deep { color: var(--good); } .badge.inferred, .badge.recon-quick { color: var(--warning); } .badge.recon-none { color: var(--text-muted); }
235
+ .spec-bar code { white-space: pre-wrap; }
224
236
  td.nw { white-space: nowrap; }
225
237
  .hint { color: var(--text-secondary); font-size: 13px; margin: 0 0 10px; }
226
238
  .copy-spec { background: var(--surface-2); color: var(--text-secondary); border: 1px solid var(--surface-3); border-radius: 6px; font-size: 12px; padding: 4px 10px; cursor: pointer; }
@@ -421,38 +433,61 @@ function renderTimeline() {
421
433
  }
422
434
 
423
435
  /**
424
- * The fixes, listed whether or not they were applied: spec one (its row's button) or a group (tick them) with bt-spec.
425
- * The spec command points bt-spec at findings.md, which carries each fix's cause, evidence, code, gain, risk and check.
436
+ * The fixes, listed whether or not they were applied, in two steps: recon the code behind them (one bt-recon per
437
+ * subsystem, so the spec has the callers, invariants and tests mapped), then spec one (its row's button) or a group
438
+ * (tick them) with bt-spec. The spec command points bt-spec at findings.md, which carries each fix's cause, evidence,
439
+ * code, gain, risk and check, and cites the recon docs it rests on.
426
440
  */
427
441
  function renderFixes() {
428
442
  const wrap = $("#fixes-wrap");
429
443
  const list = (findings && findings.findings ? findings.findings : []).filter((f) => f.fix);
430
444
  if (!list.length) { wrap.style.display = "none"; return; }
445
+ const recon = DATA.recon || { groups: [], byId: {} };
446
+ const groupOf = (id) => recon.groups.find((g) => g.slug === recon.byId[id]);
431
447
  const source = "@.agents/profile/" + DATA.slug + "/findings.md";
432
448
  const join = (ids) => ids.length <= 1 ? ids.join("") : ids.slice(0, -1).join(", ") + " and " + ids[ids.length - 1];
433
- const command = (ids) => "/bt-spec Fix " + join(ids) + " from " + source;
449
+ const groupsFor = (ids) => [...new Set(ids.map(groupOf).filter(Boolean))];
450
+ const using = (ids) => { const paths = groupsFor(ids).map((g) => "@" + g.path); return paths.length ? " using " + join(paths) : ""; };
451
+ const specCommand = (ids) => "/bt-spec Fix " + join(ids) + " from " + source + using(ids);
452
+ const reconCommands = (ids) => groupsFor(ids).map((g) => g.command).join("\n");
434
453
  // A fix is done once it is in the code: "kept" (applied and proven by the fix loop) or "fixed".
435
454
  const isDone = (f) => f.status === "kept" || f.status === "fixed";
436
455
  const open = list.filter((f) => !isDone(f)).map((f) => f.id);
456
+ const reconCell = (f) => {
457
+ const g = groupOf(f.id);
458
+ if (!g) return "–";
459
+ const state = g.exists ? '<span class="badge recon-' + esc(g.depth) + '" title="' + esc(g.path) + '">' + esc(g.depth) + "</span>" : '<span class="badge recon-none">none</span>';
460
+ return state + ' <span class="where">' + esc(g.name) + "</span>";
461
+ };
437
462
  const rows = list.map((f) => '<tr><td class="pick"><input type="checkbox" value="' + esc(f.id) + '"' + (!isDone(f) ? " checked" : "") + ' aria-label="Select ' + esc(f.id) + '"></td>' +
438
463
  '<td class="id"><a href="#' + esc(f.id) + '">' + esc(f.id) + '</a></td><td>' + esc(f.title) + '</td>' +
439
464
  '<td><span class="badge ' + esc(f.status) + '">' + esc(f.status) + '</span></td>' +
465
+ '<td>' + (f.confidence ? '<span class="badge ' + esc(f.confidence) + '">' + esc(f.confidence) + "</span>" : "–") + '</td>' +
466
+ '<td>' + reconCell(f) + '</td>' +
440
467
  '<td>' + esc(f.gain || f.cost || "–") + '</td><td>' + esc(f.risk || "–") + '</td>' +
441
- '<td class="act"><button type="button" class="copy-spec" data-ids="' + esc(f.id) + '">Copy spec command</button></td></tr>').join("");
442
- $("#fixes").innerHTML = '<div class="panel"><p class="hint">Each fix can be specced on its own, or several together: tick them and copy one command for <code>/bt-spec</code>. ' +
468
+ '<td class="act"><button type="button" class="copy-spec" data-kind="recon" data-ids="' + esc(f.id) + '">Copy recon command</button>' +
469
+ '<button type="button" class="copy-spec" data-kind="spec" data-ids="' + esc(f.id) + '">Copy spec command</button></td></tr>').join("");
470
+ $("#fixes").innerHTML = '<div class="panel"><p class="hint"><strong>1. Recon</strong> the code behind the fixes with <code>/bt-recon</code>: it maps how that code works, every caller, and what a change must not break. Fixes in the same code share one recon; run each command on its own. ' +
471
+ '<strong>2. Spec</strong> them one at a time or several together with <code>/bt-spec</code>; the command cites the recon docs. ' +
443
472
  (open.length ? open.length + " not fixed yet." : "All of them are fixed.") + '</p>' +
444
- '<div class="scroll"><table class="fixes"><thead><tr><th class="pick"></th><th>ID</th><th>Fix</th><th>Status</th><th>Expected gain</th><th>Risk</th><th class="act"></th></tr></thead><tbody>' + rows + '</tbody></table></div>' +
445
- '<div class="spec-bar"><code id="spec-selected"></code><button type="button" class="copy-spec" id="copy-selected">Copy for the selected</button>' +
446
- (open.length ? '<button type="button" class="copy-spec" data-ids="' + esc(open.join(" ")) + '">Copy for all open fixes</button>' : "") + '</div></div>';
473
+ '<div class="scroll"><table class="fixes"><thead><tr><th class="pick"></th><th>ID</th><th>Fix</th><th>Status</th><th>Cause</th><th>Recon</th><th>Expected gain</th><th>Risk</th><th class="act"></th></tr></thead><tbody>' + rows + '</tbody></table></div>' +
474
+ '<div class="spec-bar"><code id="recon-selected"></code><button type="button" class="copy-spec" data-kind="recon" id="copy-recon-selected">1. Copy recon for the selected</button></div>' +
475
+ '<div class="spec-bar"><code id="spec-selected"></code><button type="button" class="copy-spec" data-kind="spec" id="copy-selected">2. Copy spec for the selected</button>' +
476
+ (open.length ? '<button type="button" class="copy-spec" data-kind="spec" data-ids="' + esc(open.join(" ")) + '">Copy spec for all open fixes</button>' : "") + '</div></div>';
447
477
  const selected = () => [...document.querySelectorAll("#fixes input[type=checkbox]:checked")].map((box) => box.value);
448
- const refresh = () => { const ids = selected(); $("#spec-selected").textContent = ids.length ? command(ids) : "Tick the fixes to spec together"; $("#copy-selected").disabled = !ids.length; };
478
+ const refresh = () => {
479
+ const ids = selected();
480
+ $("#recon-selected").textContent = ids.length ? reconCommands(ids) : "Tick the fixes to recon together";
481
+ $("#spec-selected").textContent = ids.length ? specCommand(ids) : "Tick the fixes to spec together";
482
+ $("#copy-selected").disabled = $("#copy-recon-selected").disabled = !ids.length;
483
+ };
449
484
  $("#fixes").addEventListener("change", refresh);
450
485
  $("#fixes").addEventListener("click", (event) => {
451
486
  const button = event.target.closest(".copy-spec");
452
487
  if (!button) return;
453
- const ids = button.id === "copy-selected" ? selected() : button.dataset.ids.split(" ");
488
+ const ids = button.id === "copy-selected" || button.id === "copy-recon-selected" ? selected() : button.dataset.ids.split(" ");
454
489
  if (!ids.length) return;
455
- const text = command(ids);
490
+ const text = button.dataset.kind === "recon" ? reconCommands(ids) : specCommand(ids);
456
491
  const done = () => { const label = button.textContent; button.textContent = "Copied"; setTimeout(() => { button.textContent = label; }, 1500); };
457
492
  if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(done, done); else done();
458
493
  });
@@ -469,11 +504,12 @@ function renderFindings() {
469
504
  const code = (f.code || []).map((c) => "<li>" + link(c.file, c.line, (c.label ? c.label + " — " : "") + shortPath(c.file) + (c.line ? ":" + c.line : "")) + "</li>").join("");
470
505
  const diff = f.diff ? '<details><summary>The change</summary><pre class="code diff">' + f.diff.split("\n").map((l) => '<div class="row ' + (l.startsWith("+") && !l.startsWith("+++") ? "add" : l.startsWith("-") && !l.startsWith("---") ? "del" : "") + '"><span class="ln"></span>' + esc(l) + '</div>').join("") + '</pre></details>' : "";
471
506
  return '<article class="finding" id="' + esc(f.id) + '"><header><span class="badge ' + esc(f.severity) + '">' + esc(f.severity) + '</span><span class="badge ' + esc(f.status) + '">' + esc(f.status) + '</span><h3>' + esc(f.id + " · " + f.title) + '</h3>' + (f.cost ? '<span class="cost">' + esc(f.cost) + '</span>' : "") + '</header>' +
472
- (f.phases && f.phases.length ? '<div class="meta">phases: ' + esc(f.phases.join(", ")) + '</div>' : "") +
507
+ (f.phases && f.phases.length || f.subsystem ? '<div class="meta">' + [f.phases && f.phases.length ? "phases: " + esc(f.phases.join(", ")) : "", f.subsystem ? "code: " + esc(f.subsystem) : "", f.confidence ? "cause " + (f.confidence === "confirmed" ? "confirmed in the code" : "inferred from the profile") : ""].filter(Boolean).join(" · ") + '</div>' : "") +
473
508
  (f.cause ? "<p><strong>Why it is slow.</strong> " + esc(f.cause) + "</p>" : "") +
474
509
  (f.evidence && f.evidence.length ? "<p><strong>Evidence.</strong></p><ul>" + f.evidence.map((e) => "<li>" + esc(e) + "</li>").join("") + "</ul>" : "") +
475
510
  (code ? "<p><strong>Code.</strong></p><ul>" + code + "</ul>" : "") +
476
511
  (f.fix ? "<p><strong>Fix.</strong> " + esc(f.fix) + "</p>" : "") +
512
+ (f.guards && f.guards.length ? "<p><strong>Must not break.</strong></p><ul>" + f.guards.map((g) => "<li>" + esc(g) + "</li>").join("") + "</ul>" : "") +
477
513
  (f.before || f.after ? '<div class="beforeafter">' + (f.before ? "<span>before: " + esc(f.before) + "</span>" : "") + (f.after ? "<span>after: " + esc(f.after) + "</span>" : "") + "</div>" : "") + diff + "</article>";
478
514
  }).join("");
479
515
  }
@@ -663,13 +699,80 @@ function shotsFrom(dir, reportDir) {
663
699
  }));
664
700
  }
665
701
 
702
+ /** Lowercase kebab-case, `a-z 0-9 -` only, at most 40 characters — bt-recon's slug rule. */
703
+ function kebab(text) {
704
+ return String(text || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/g, "");
705
+ }
706
+
707
+ /** Reads a recon doc's depth from its header (`depth: quick`); a recon written before the field existed is deep. */
708
+ function reconDepth(file) {
709
+ try {
710
+ const head = fs.readFileSync(file, "utf8").slice(0, 2000);
711
+ const match = head.match(/depth:\s*(quick|deep)/);
712
+ return match ? match[1] : "deep";
713
+ } catch {
714
+ return null;
715
+ }
716
+ }
717
+
718
+ /**
719
+ * Groups the fixes by the code they live in — one bt-recon per subsystem — and builds each group's recon command.
720
+ * A finding's `recon` path names its group; else its `subsystem`; else its own title. A profile's recons live in its
721
+ * own `recon/` folder; a general recon of the same name in the project's `.agents/recon/` is used when the profile has
722
+ * none. The folders are read to tell which recons exist and how deep they are.
723
+ * @param {object[]} list the findings
724
+ * @param {string} profileSlug the profile's slug
725
+ * @param {string} projectAgents the project's `.agents` folder
726
+ * @returns {{ groups: object[], byId: Object<string, string> }} the groups, and each finding id's group slug
727
+ */
728
+ function reconGroups(list, profileSlug, projectAgents) {
729
+ const ownFolder = `.agents/profile/${profileSlug}/recon`;
730
+ const groups = new Map();
731
+ const byId = {};
732
+ for (const finding of list.filter((item) => item.fix)) {
733
+ const fromPath = finding.recon ? path.basename(String(finding.recon)).replace(/_recon\.md$/, "") : "";
734
+ const slug = kebab(fromPath || finding.subsystem || finding.title) || kebab(finding.id);
735
+ if (!groups.has(slug)) {
736
+ // The profile's own recon first, then a general one; a new recon goes in the profile's folder.
737
+ const candidates = [`${ownFolder}/${slug}_recon.md`, `.agents/recon/${slug}_recon.md`];
738
+ if (finding.recon) candidates.unshift(String(finding.recon).replace(/^\.?\//, ""));
739
+ const found = candidates.map((relative) => ({ relative, depth: reconDepth(path.join(projectAgents, "..", relative)) })).find((candidate) => candidate.depth !== null);
740
+ groups.set(slug, {
741
+ slug, name: finding.subsystem || finding.title,
742
+ path: found ? found.relative : candidates[candidates.length - 2], exists: Boolean(found), depth: found ? found.depth : null,
743
+ ids: [], code: [],
744
+ });
745
+ }
746
+ const group = groups.get(slug);
747
+ group.ids.push(finding.id);
748
+ for (const location of finding.code || []) {
749
+ const where = `${location.file}${location.line ? `:${location.line}` : ""}`;
750
+ if (!group.code.includes(where)) group.code.push(where);
751
+ }
752
+ byId[finding.id] = slug;
753
+ }
754
+ for (const group of groups.values()) {
755
+ const ids = group.ids.length <= 1 ? group.ids.join("") : `${group.ids.slice(0, -1).join(", ")} and ${group.ids[group.ids.length - 1]}`;
756
+ const anchors = group.code.slice(0, 6).join(", ");
757
+ // A deep recon that exists only needs refreshing after code changes; a quick one (or none) gets a deep one,
758
+ // written into the profile's own recon folder.
759
+ if (group.exists && group.depth === "deep") {
760
+ group.command = `/bt-recon --refresh @${group.path}`;
761
+ } else {
762
+ group.path = `${ownFolder}/${group.slug}_recon.md`;
763
+ group.command = `/bt-recon --slug ${group.slug} --out ${ownFolder} --no-guide "${group.name.replace(/"/g, "'")} — the code behind ${ids} in @.agents/profile/${profileSlug}/findings.md${anchors ? ` (${anchors})` : ""}: how it works, every caller, what drives its per-frame cost, and what a change there must not break"`;
764
+ }
765
+ }
766
+ return { groups: [...groups.values()], byId };
767
+ }
768
+
666
769
  /**
667
770
  * The diagnosis as a spec-ready Markdown document (findings.md beside the dashboard): what was measured and how, what is
668
771
  * still to fix, then one section per finding with its cause, evidence, code, proposed fix, expected gain, risk and how
669
772
  * to verify it — the input for a later fix with a full spec (`bt-spec @.agents/profile/<slug>/findings.md`).
670
773
  * @returns {string} the Markdown
671
774
  */
672
- function findingsMarkdown(findings, analysis, slugName) {
775
+ function findingsMarkdown(findings, analysis, slugName, recon) {
673
776
  const capture = analysis.capture || {};
674
777
  const list = (findings && Array.isArray(findings.findings)) ? findings.findings : [];
675
778
  // A fix is done once it is in the code: "kept" (applied and proven by the fix loop) or "fixed".
@@ -690,18 +793,34 @@ function findingsMarkdown(findings, analysis, slugName) {
690
793
  const cell = (text) => String(text || "–").replace(/\|/g, "\\|").replace(/\n/g, " ");
691
794
  push(`## The fixes (${open.length} not fixed yet)`);
692
795
  push();
693
- push("Spec them one at a time, or several together — each command points bt-spec at this file, which carries every fix's cause, evidence, code, gain, risk and how to verify it.");
796
+ push("Two steps: **recon** the code behind the fixes (bt-recon maps how it works, every caller and what a change must not break), then **spec** them one at a time or several together. Each spec command points bt-spec at this file, which carries every fix's cause, evidence, code, gain, risk and how to verify it, and cites the recon docs as its grounding.");
694
797
  push();
798
+ // The recon docs a set of fixes rests on, as bt-spec's `using` clause.
799
+ const using = (ids) => {
800
+ const paths = [...new Set(ids.map((id) => recon.byId[id]).filter(Boolean))].map((slug) => `@${recon.groups.find((group) => group.slug === slug).path}`);
801
+ return paths.length ? ` using ${join(paths)}` : "";
802
+ };
803
+ const specCommand = (ids) => `/bt-spec Fix ${join(ids)} from ${source}${using(ids)}`;
695
804
  if (fixable.length) {
696
- push("| ID | Fix | Status | Expected gain | Risk | Spec it |");
697
- push("|---|---|---|---|---|---|");
698
- for (const finding of fixable) push(`| ${finding.id} | ${cell(finding.title)} | ${finding.status || "proposed"} | ${cell(finding.gain || finding.cost)} | ${cell(finding.risk)} | \`/bt-spec Fix ${finding.id} from ${source}\` |`);
805
+ push("### 1. Recon the code behind them");
806
+ push();
807
+ push("One recon per subsystem — fixes in the same code share it. Run each command on its own.");
808
+ push();
809
+ push("| Subsystem | Fixes | Recon | Command |");
810
+ push("|---|---|---|---|");
811
+ for (const group of recon.groups) push(`| ${cell(group.name)} | ${group.ids.join(", ")} | ${group.exists ? `\`${group.path}\` (${group.depth})` : "not yet"} | \`${cell(group.command)}\` |`);
812
+ push();
813
+ push("### 2. Spec them");
814
+ push();
815
+ push("| ID | Fix | Status | Cause | Expected gain | Risk | Spec it |");
816
+ push("|---|---|---|---|---|---|---|");
817
+ for (const finding of fixable) push(`| ${finding.id} | ${cell(finding.title)} | ${finding.status || "proposed"} | ${finding.confidence || "–"} | ${cell(finding.gain || finding.cost)} | ${cell(finding.risk)} | \`${specCommand([finding.id])}\` |`);
699
818
  push();
700
819
  const openIds = open.filter((finding) => finding.fix).map((finding) => finding.id);
701
- if (openIds.length > 1) { push(`**All open fixes together:** \`/bt-spec Fix ${join(openIds)} from ${source}\``); push(); }
820
+ if (openIds.length > 1) { push(`**All open fixes together:** \`${specCommand(openIds)}\``); push(); }
702
821
  // The example group names real fixes: the first and last open ones, or the first two in the table.
703
822
  const exampleIds = openIds.length > 2 ? [openIds[0], openIds[openIds.length - 1]] : fixable.slice(0, 2).map((finding) => finding.id);
704
- if (exampleIds.length > 1) push(`**A group of your choice:** \`/bt-spec Fix ${join(exampleIds)} from ${source}\` (any IDs from the table)`);
823
+ if (exampleIds.length > 1) push(`**A group of your choice:** \`${specCommand(exampleIds)}\` (any IDs from the table)`);
705
824
  } else {
706
825
  push("No fixes proposed.");
707
826
  }
@@ -711,12 +830,18 @@ function findingsMarkdown(findings, analysis, slugName) {
711
830
  push();
712
831
  push(`**Severity:** ${finding.severity || "–"} · **Status:** ${finding.status || "–"} · **Phases:** ${(finding.phases || []).join(", ") || "–"}${finding.cost ? ` · **Cost:** ${finding.cost}` : ""}`);
713
832
  push();
833
+ const group = recon.groups.find((candidate) => candidate.slug === recon.byId[finding.id]);
834
+ if (finding.confidence || finding.subsystem || group) {
835
+ push(`**Cause:** ${finding.confidence === "confirmed" ? "confirmed in the code" : finding.confidence === "inferred" ? "inferred from the profile — not yet traced in the code" : "–"}${finding.subsystem ? ` · **Subsystem:** ${finding.subsystem}` : ""}${group ? ` · **Recon:** \`${group.path}\` ${group.exists ? `(${group.depth})` : "(not yet — run the command above)"}` : ""}`);
836
+ push();
837
+ }
714
838
  if (finding.cause) { push("### Why it is slow"); push(); push(finding.cause); push(); }
715
839
  if (finding.evidence && finding.evidence.length) { push("### Evidence"); push(); for (const item of finding.evidence) push(`- ${item}`); push(); }
716
840
  if (finding.code && finding.code.length) { push("### Code"); push(); for (const location of finding.code) push(`- \`${location.file}${location.line ? `:${location.line}` : ""}\`${location.label ? ` — ${location.label}` : ""}`); push(); }
717
841
  if (finding.fix) { push(isDone(finding) ? "### The fix" : "### Proposed fix"); push(); push(finding.fix); push(); }
718
842
  if (finding.gain) { push(`**Expected gain:** ${finding.gain}`); push(); }
719
843
  if (finding.risk) { push(`**Risk:** ${finding.risk}`); push(); }
844
+ if (finding.guards && finding.guards.length) { push("### Must not break"); push(); for (const guard of finding.guards) push(`- ${guard}`); push(); }
720
845
  if (finding.verify) { push(`**How to verify:** ${finding.verify}`); push(); }
721
846
  if (finding.before || finding.after) { push(`**Before:** ${finding.before || "–"} · **After:** ${finding.after || "not fixed yet"}`); push(); }
722
847
  if (finding.diff) { push("<details><summary>The change</summary>"); push(); push("```diff"); push(finding.diff); push("```"); push(); push("</details>"); push(); }
@@ -784,6 +909,9 @@ async function main() {
784
909
  groups: OWNER_GROUPS,
785
910
  slug: path.basename(reportDir),
786
911
  };
912
+ // The profile's slug folder is <project>/.agents/profile/<slug>/: its recons sit in recon/ inside it, general ones in
913
+ // <project>/.agents/recon/.
914
+ data.recon = reconGroups(findings && Array.isArray(findings.findings) ? findings.findings : [], data.slug, path.join(reportDir, "..", ".."));
787
915
  if (flags.snapshots) data.run.shots = shotsFrom(path.resolve(flags.snapshots), reportDir);
788
916
  if (flags["snapshots-before"]) {
789
917
  // Shown beside this run's shots of the same names (needs --baseline, whose own shots they replace).
@@ -794,7 +922,7 @@ async function main() {
794
922
  process.stdout.write(`wrote ${outFile}\n`);
795
923
  if (findings) {
796
924
  const markdownFile = path.join(path.dirname(outFile), "findings.md");
797
- fs.writeFileSync(markdownFile, findingsMarkdown(findings, analysis, path.basename(path.dirname(outFile))));
925
+ fs.writeFileSync(markdownFile, findingsMarkdown(findings, analysis, path.basename(path.dirname(outFile)), data.recon));
798
926
  process.stdout.write(`wrote ${markdownFile}\n`);
799
927
  }
800
928
  if (pdfFile) return writePdf(outFile, pdfFile);
@@ -7,7 +7,7 @@ allowed-tools: Read, Grep, Glob, Write, Bash(git log:*), Bash(git show:*), Bash(
7
7
  Run reconnaissance on existing code nobody has documented — one subsystem or the whole codebase — and bring back everything it does as a grounding spec that `bt-spec` and `bt-plan` build future features on, plus a plain-language user guide when there is something a user operates. Follow the project's agent instructions (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md). The user's message after the skill name is the `arguments`.
8
8
 
9
9
  ```
10
- /bt-recon [--guide|--no-guide] [--no-live] [--quick] [--out <dir>] <brief>
10
+ /bt-recon [--guide|--no-guide] [--no-live] [--quick] [--out <dir>] [--slug <name>] <brief>
11
11
  /bt-recon --refresh @.agents/recon/<slug>_recon.md
12
12
 
13
13
  /bt-recon "the default camera system"
@@ -20,7 +20,8 @@ Run reconnaissance on existing code nobody has documented — one subsystem or t
20
20
  - `--guide` — always write the user guide. `--no-guide` — never write it. Neither → write it when the scope has UI — anything a person operates (Step 8).
21
21
  - `--no-live` — skip the live pass (Step 5) even when the brief gives a URL.
22
22
  - `--quick` — a lighter recon: one reader per slice, no coverage audit (Step 6). The output keeps the same sections.
23
- - `--out <dir>` — write the outputs to `<dir>` instead of `.agents/recon/`.
23
+ - `--out <dir>` — write the outputs to `<dir>` instead of `.agents/recon/` (the doc, the guide and the screenshot folder all go there). Other skills use it to keep a recon inside the folder it belongs to — bt-profile writes a profile's recons to `.agents/profile/<slug>/recon/`, so everything about one profiled moment moves or archives as one folder.
24
+ - `--slug <name>` — use this `recon_slug` instead of deriving one from the brief (same rule: `a-z 0-9 -`, max 40 chars). Other skills pass it so they know the file name in advance and can cite it (bt-profile's report builds the `bt-spec … using @<recon>` command before the recon exists).
24
25
  - `--refresh @<recon file>` — update an existing recon against what changed since it was written (Refresh mode, at the end).
25
26
  - Strip the flags first; they are never part of the brief or the file name. No brief → ask for one. Never guess a path or URL.
26
27
 
@@ -43,7 +44,7 @@ From the flag-stripped brief derive `recon_title` (Title Case, e.g. `Session Cam
43
44
 
44
45
  Note any URL (it enables the live pass), and any audience or emphasis hints ("focus on the CMS endpoints") — emphasis deepens a section, it never drops one. If you cannot infer a sensible title, ask.
45
46
 
46
- If `.agents/recon/<recon_slug>_recon.md` already exists, ask whether to refresh it (Refresh mode) or replace it. Never overwrite it silently.
47
+ If `<out>/<recon_slug>_recon.md` already exists (`<out>` is `--out`, else `.agents/recon`), ask whether to refresh it (Refresh mode) or replace it. Never overwrite it silently — with one exception: a deep run replaces an existing **quick** recon (`depth: quick` in its header) without asking, and says so. Asking there would only ever get one answer, and a skill that runs recon unattended (bt-profile) must not stop on a question.
47
48
 
48
49
  ## Step 2. Locate and map the scope
49
50
 
@@ -117,7 +118,7 @@ Include every section. A section that genuinely does not apply says so in one li
117
118
 
118
119
  scope: <the brief, one line> · kind: <subsystem|codebase>
119
120
  commit: <short sha> · date: <YYYY-MM-DD> · files: <n> (<total> lines)
120
- guide: <.agents/recon/<slug>_guide.md | none> · live: <yes | no (<reason>)>
121
+ guide: <.agents/recon/<slug>_guide.md | none> · live: <yes | no (<reason>)> · depth: <deep | quick>
121
122
  confidence tags: [code] read in source · [live] seen running · [history] from git · [inferred] deduced
122
123
 
123
124
  ## Summary