@babylonjs-toolkit/agent 1.1.46 → 1.1.48

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.46)
1
+ # Babylon Toolkit Desktop Agent (1.1.48)
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
 
@@ -33,6 +33,7 @@ up the skills, instructions and configuration.
33
33
  | `bt-agent targets` | Show every target and the paths it writes to |
34
34
  | `bt-agent bridge` | Connect this computer to the App Builder so it can drive Unity and Blender |
35
35
  | `bt-agent diskinfo` | Show where your disk space is going — read-only, macOS, Windows and Linux |
36
+ | `bt-agent kill` | Free a port or range of ports, stop processes by id, or list listening ports — macOS, Windows and Linux |
36
37
 
37
38
  | Option | Effect |
38
39
  |--------|--------|
@@ -61,6 +62,33 @@ npm / Yarn / pnpm / pip / NuGet caches, Docker and WSL disks, VS Code's C++ cach
61
62
  Trash / Recycle Bin), every `node_modules`, the Unity `Library/` and Unreal `Intermediate/` folders
62
63
  that rebuild themselves, the largest files, and suggested cleanup commands. Nothing is deleted or run.
63
64
 
65
+ ### Freeing ports
66
+
67
+ ```bash
68
+ bt-agent kill --port 4444 # stop whatever is listening on port 4444
69
+ bt-agent kill --port 4444 8888 # several ports (or 4444,8888)
70
+ bt-agent kill --port 8000-8010 # an inclusive range
71
+ bt-agent kill --pid 51234 # stop a process by id (or 51234,51240)
72
+ bt-agent kill --list # every listening port with its process id and name
73
+ bt-agent kill --list 3000-3999 # just these ports; stops nothing
74
+ bt-agent kill --list --pid 51234 # the ports that process listens on
75
+ bt-agent kill --port 4444 --force # skip the polite request and force-kill at once
76
+ bt-agent kill --pid 51234 --force # the same for a process id (-9 works too)
77
+ ```
78
+
79
+ Exactly one of `--port`, `--pid` or `--list` says what the values are, so a bare
80
+ number is never guessed to be a port or a process id.
81
+
82
+ Use it when a dev server is still holding its port and you need to restart it. With
83
+ `--port`, only processes *listening* on a port are matched, so a browser tab connected to your dev
84
+ server is left alone. On macOS and Linux each process gets SIGTERM, then SIGKILL if
85
+ it is still running after 3 seconds. On Windows the process and its children are
86
+ force-killed with `taskkill /T /F`. Afterwards the ports are checked again, and any
87
+ process a watcher (nodemon, pm2 …) has already restarted is reported. Ports are found
88
+ with `lsof` on macOS, `ss` (or `lsof`) on Linux, and `netstat` on Windows. A process
89
+ owned by another user needs `sudo`. bt-agent will not stop itself, the system init
90
+ process, or the Windows System process.
91
+
64
92
  ### Updating
65
93
 
66
94
  ```bash
package/bin/bt-agent.js CHANGED
@@ -26,6 +26,7 @@ Commands
26
26
  targets List the available targets and their paths
27
27
  bridge Connect this computer to the App Builder (Unity/Blender); see bt-agent bridge --help
28
28
  diskinfo Show where your disk space is going (read-only); see bt-agent diskinfo --help
29
+ kill Free ports / stop processes, or list listening ports; see bt-agent kill --help
29
30
 
30
31
  Options
31
32
  --project Install into the current directory instead of $HOME
@@ -47,6 +48,8 @@ Examples
47
48
  bt-agent doctor
48
49
  bt-agent update
49
50
  bt-agent diskinfo
51
+ bt-agent kill --port 4444
52
+ bt-agent kill --list
50
53
  bt-agent bridge --install-service --pair <code from the Unity Bridge dialog>
51
54
  `;
52
55
 
@@ -266,6 +269,13 @@ function main() {
266
269
  return;
267
270
  }
268
271
 
272
+ if (process.argv[2] === 'kill') {
273
+ require('../lib/kill/cli')
274
+ .runKillCli(process.argv.slice(3))
275
+ .then((code) => process.exit(code), (error) => { console.error(error.message); process.exit(1); });
276
+ return;
277
+ }
278
+
269
279
  let opts;
270
280
  try {
271
281
  opts = parseArgs(process.argv.slice(2));
@@ -0,0 +1,227 @@
1
+ 'use strict';
2
+
3
+ const { parsePortSpecs, parsePids, findListeners, processName, stopProcesses, isAlive } = require('./ports');
4
+
5
+ const USAGE = `
6
+ bt-agent kill — free ports and stop processes (macOS, Windows, Linux)
7
+
8
+ Stops whatever is listening on the given TCP ports, or the given process ids, so
9
+ a dev server can be restarted. --port matches only processes *listening* on a
10
+ port — a browser that is merely connected to your dev server is left alone. On
11
+ macOS and Linux each process is asked to exit (SIGTERM) and force-killed if it is
12
+ still running after 3 seconds; Windows always force-kills the process and its
13
+ children (taskkill /T /F).
14
+
15
+ Usage
16
+ bt-agent kill --port <port|range> [...] stop whatever listens on these ports
17
+ bt-agent kill --pid <id> [...] stop these processes
18
+ bt-agent kill --list [port|range ...] list listening ports (all, or just these)
19
+ bt-agent kill --list --pid <id> [...] list the ports these processes listen on
20
+
21
+ 4444 one port
22
+ 8000-8010 an inclusive range
23
+ 4444,8888 a list (separate arguments work too; the same for process ids)
24
+
25
+ Options
26
+ --port The values are ports or port ranges
27
+ --pid The values are process ids
28
+ --list, -l Show listening ports with their process id and name; stop nothing
29
+ (--dry-run is the same)
30
+ --force, -9 Force-kill at once (SIGKILL) instead of asking first
31
+ --json Machine-readable output
32
+ -h, --help Show this help
33
+
34
+ Examples
35
+ bt-agent kill --port 4444
36
+ bt-agent kill --port 4444 8888
37
+ bt-agent kill --port 3000-3010
38
+ bt-agent kill --pid 51234
39
+ bt-agent kill --pid 51234 --force
40
+ bt-agent kill --list
41
+ bt-agent kill --list 3000-3999
42
+ `;
43
+
44
+ const MODE_HINT = 'Say what to stop: `bt-agent kill --port 4444`, `bt-agent kill --pid 51234` or `bt-agent kill --list`';
45
+
46
+ function parseKillArgs(argv) {
47
+ const opts = { specs: [], ports: [], pids: [], by: null, list: false, force: false, json: false, help: false };
48
+ const setBy = (by) => {
49
+ if (opts.by && opts.by !== by) throw new Error('Use --port or --pid, not both');
50
+ opts.by = by;
51
+ };
52
+ for (const arg of argv) {
53
+ if (arg === '-h' || arg === '--help') opts.help = true;
54
+ else if (arg === '--list' || arg === '-l' || arg === '--dry-run') opts.list = true;
55
+ else if (arg === '--force' || arg === '-9') opts.force = true;
56
+ else if (arg === '--json') opts.json = true;
57
+ else if (arg === '--port' || arg === '--pid') setBy(arg.slice(2));
58
+ else if (arg.startsWith('--port=') || arg.startsWith('--pid=')) {
59
+ const [flag, value] = arg.split('=');
60
+ setBy(flag.slice(2));
61
+ opts.specs.push(value);
62
+ } else if (arg.startsWith('-')) throw new Error(`Unknown option: ${arg}`);
63
+ else opts.specs.push(arg);
64
+ }
65
+ if (opts.help) return opts;
66
+
67
+ if (opts.list && opts.force) throw new Error('--force stops processes; --list never does — drop one of them');
68
+
69
+ // --list on its own filters by port, the thing it lists.
70
+ if (!opts.by && opts.list) opts.by = 'port';
71
+ if (!opts.by) throw new Error(opts.specs.length ? `${MODE_HINT} — is ${opts.specs[0]} a port or a process id?` : MODE_HINT);
72
+ if (!opts.list && !opts.specs.length) {
73
+ throw new Error(opts.by === 'port' ? '--port needs a port or range, e.g. --port 4444' : '--pid needs a process id, e.g. --pid 51234');
74
+ }
75
+ if (opts.by === 'port') opts.ports = parsePortSpecs(opts.specs);
76
+ else opts.pids = parsePids(opts.specs);
77
+ return opts;
78
+ }
79
+
80
+ function describe(r) {
81
+ if (r.pid == null) return 'a process owned by another user';
82
+ return `${r.command || 'process'} (pid ${r.pid})`;
83
+ }
84
+
85
+ const STATUS_TEXT = {
86
+ stopped: 'stopped',
87
+ killed: 'force-killed',
88
+ 'not-running': 'not running',
89
+ };
90
+
91
+ /** Unique listeners, sorted by port then pid. */
92
+ function uniqueListeners(listeners) {
93
+ const seen = new Set();
94
+ return listeners
95
+ .filter((l) => {
96
+ const key = `${l.port}/${l.pid}`;
97
+ if (seen.has(key)) return false;
98
+ seen.add(key);
99
+ return true;
100
+ })
101
+ .sort((a, b) => a.port - b.port || (a.pid || 0) - (b.pid || 0));
102
+ }
103
+
104
+ function printList(rows, idle, opts, platform) {
105
+ console.log('');
106
+ if (!rows.length && !idle.length) {
107
+ console.log(opts.ports.length || opts.pids.length ? 'Nothing is listening there.' : 'Nothing is listening.');
108
+ } else {
109
+ console.log(` ${'PORT'.padStart(5)} ${'PID'.padStart(7)} PROCESS`);
110
+ for (const l of rows) {
111
+ const who = l.pid == null ? '(another user)' : l.command || '?';
112
+ console.log(` ${String(l.port).padStart(5)} ${String(l.pid == null ? '?' : l.pid).padStart(7)} ${who}`);
113
+ }
114
+ for (const p of idle) {
115
+ console.log(` ${'-'.padStart(5)} ${String(p.pid).padStart(7)} ${p.alive ? `${p.command || '?'} — no listening ports` : 'not running'}`);
116
+ }
117
+ }
118
+ if (platform !== 'win32') console.log('\n(Processes owned by other users are only fully visible with sudo.)');
119
+ console.log('');
120
+ }
121
+
122
+ function printResults(results, respawned, opts, platform) {
123
+ const lines = [];
124
+ for (const r of results) {
125
+ const outcome = STATUS_TEXT[r.status] || `FAILED — ${r.error}`;
126
+ const ports = r.ports.length ? r.ports : ['-'];
127
+ for (const port of ports) lines.push([port === '-' ? Infinity : port, ` ${String(port).padStart(5)} ${describe(r)} ${outcome}`]);
128
+ }
129
+ for (const l of respawned) {
130
+ lines.push([l.port, ` ${String(l.port).padStart(5)} listening again: ${describe(l)} — a watcher or supervisor restarted it`]);
131
+ }
132
+
133
+ console.log('');
134
+ if (!lines.length) {
135
+ console.log(`Nothing is listening on ${opts.specs.join(', ')}.`);
136
+ if (platform !== 'win32') console.log('(A process owned by another user is only visible with sudo.)');
137
+ } else {
138
+ for (const [, line] of lines.sort((a, b) => a[0] - b[0])) console.log(line);
139
+ }
140
+ console.log('');
141
+ }
142
+
143
+ /** `--list`: show listeners, kill nothing. */
144
+ function runList(opts, listeners, platform) {
145
+ const wantedPorts = new Set(opts.ports);
146
+ const wantedPids = new Set(opts.pids);
147
+ const all = !opts.ports.length && !opts.pids.length;
148
+ const rows = uniqueListeners(listeners.filter((l) => all || wantedPorts.has(l.port) || wantedPids.has(l.pid)));
149
+ const idle = opts.pids
150
+ .filter((pid) => !rows.some((l) => l.pid === pid))
151
+ .map((pid) => {
152
+ const alive = isAlive(pid);
153
+ return { pid, alive, command: alive ? processName(pid, platform) : '' };
154
+ });
155
+
156
+ if (opts.json) console.log(JSON.stringify({ listeners: rows, processes: idle }, null, 2));
157
+ else printList(rows, idle, opts, platform);
158
+ return 0;
159
+ }
160
+
161
+ /** Entry point for `bt-agent kill`. Resolves to the process exit code. */
162
+ async function runKillCli(argv, platform = process.platform) {
163
+ let opts;
164
+ try {
165
+ opts = parseKillArgs(argv);
166
+ } catch (err) {
167
+ console.error(`${err.message}\n\nRun \`bt-agent kill --help\` for usage.`);
168
+ return 2;
169
+ }
170
+ if (opts.help) {
171
+ console.log(USAGE);
172
+ return 0;
173
+ }
174
+
175
+ const listeners = findListeners(platform);
176
+ if (opts.list) return runList(opts, listeners, platform);
177
+
178
+ const wanted = new Set(opts.ports);
179
+ const byPid = new Map();
180
+ const unknown = new Set();
181
+ const target = (pid, command) => {
182
+ if (!byPid.has(pid)) byPid.set(pid, { pid, command, ports: [] });
183
+ return byPid.get(pid);
184
+ };
185
+ for (const l of listeners) {
186
+ if (!wanted.has(l.port)) continue;
187
+ if (l.pid == null) unknown.add(l.port);
188
+ else if (!target(l.pid, l.command).ports.includes(l.port)) byPid.get(l.pid).ports.push(l.port);
189
+ }
190
+
191
+ const missing = [];
192
+ for (const pid of opts.pids) {
193
+ if (byPid.has(pid)) continue;
194
+ if (!isAlive(pid)) {
195
+ missing.push({ pid, command: '', ports: [], status: 'not-running', error: null });
196
+ continue;
197
+ }
198
+ const own = listeners.filter((l) => l.pid === pid);
199
+ const t = target(pid, (own[0] && own[0].command) || processName(pid, platform));
200
+ for (const l of own) if (!t.ports.includes(l.port)) t.ports.push(l.port);
201
+ }
202
+ for (const t of byPid.values()) t.ports.sort((a, b) => a - b);
203
+
204
+ const results = await stopProcesses([...byPid.values()], { force: opts.force, platform });
205
+ results.push(...missing);
206
+ for (const port of unknown) {
207
+ results.push({ pid: null, command: '', ports: [port], status: 'failed', error: 'owned by another user — retry with sudo' });
208
+ }
209
+
210
+ // A dev server run under a watcher (nodemon, pm2, a supervisor) can come straight back.
211
+ let respawned = [];
212
+ const freed = new Set(results.filter((r) => r.status === 'stopped' || r.status === 'killed').flatMap((r) => r.ports));
213
+ if (freed.size) {
214
+ respawned = uniqueListeners(findListeners(platform).filter((l) => freed.has(l.port) && !byPid.has(l.pid)));
215
+ }
216
+
217
+ if (opts.json) {
218
+ console.log(JSON.stringify({ ports: opts.specs, pids: opts.pids, results, respawned }, null, 2));
219
+ } else {
220
+ printResults(results, respawned, opts, platform);
221
+ }
222
+
223
+ const failed = results.some((r) => r.status === 'failed' || r.status === 'protected');
224
+ return failed || respawned.length ? 1 : 0;
225
+ }
226
+
227
+ module.exports = { runKillCli, parseKillArgs };
@@ -0,0 +1,254 @@
1
+ 'use strict';
2
+
3
+ const { spawnSync } = require('child_process');
4
+
5
+ const MAX_PORT = 65535;
6
+ const GRACE_MS = 3000;
7
+ const KILL_WAIT_MS = 2000;
8
+
9
+ /**
10
+ * Parse `4444`, `8000-8010`, `4444,8888` or `:4444` into a sorted list of unique ports.
11
+ * Throws with a readable message on anything else.
12
+ */
13
+ function parsePortSpecs(specs) {
14
+ const ports = new Set();
15
+ for (const spec of specs) {
16
+ for (const part of String(spec).split(',')) {
17
+ const token = part.trim().replace(/^:/, '');
18
+ if (!token) continue;
19
+ const m = /^(\d+)(?:\s*-\s*(\d+))?$/.exec(token);
20
+ if (!m) throw new Error(`Not a port or range: ${part.trim()}`);
21
+ const from = Number(m[1]);
22
+ const to = m[2] === undefined ? from : Number(m[2]);
23
+ for (const p of [from, to]) {
24
+ if (p < 1 || p > MAX_PORT) throw new Error(`Port out of range (1-${MAX_PORT}): ${p}`);
25
+ }
26
+ if (to < from) throw new Error(`Range runs backwards: ${token}`);
27
+ for (let p = from; p <= to; p += 1) ports.add(p);
28
+ }
29
+ }
30
+ return [...ports].sort((a, b) => a - b);
31
+ }
32
+
33
+ /** Parse `1234` or `1234,5678` into unique process ids (positive integers only). */
34
+ function parsePids(specs) {
35
+ const pids = new Set();
36
+ for (const spec of specs) {
37
+ for (const part of String(spec).split(',')) {
38
+ const token = part.trim();
39
+ if (!token) continue;
40
+ // 0 and negative ids address whole process groups in kill(2) — never accept them.
41
+ if (!/^\d+$/.test(token) || Number(token) < 1) throw new Error(`Not a process id: ${token}`);
42
+ pids.add(Number(token));
43
+ }
44
+ }
45
+ return [...pids];
46
+ }
47
+
48
+ function portOf(address) {
49
+ const m = /:(\d+)$/.exec(address || '');
50
+ return m ? Number(m[1]) : null;
51
+ }
52
+
53
+ /** `lsof -nP -iTCP -sTCP:LISTEN -Fpcn` → [{ port, pid, command }]. */
54
+ function parseLsof(text) {
55
+ const out = [];
56
+ let pid = null;
57
+ let command = '';
58
+ for (const line of text.split(/\r?\n/)) {
59
+ const tag = line[0];
60
+ const value = line.slice(1);
61
+ if (tag === 'p') {
62
+ pid = Number(value);
63
+ command = '';
64
+ } else if (tag === 'c') {
65
+ command = value;
66
+ } else if (tag === 'n' && pid) {
67
+ const port = portOf(value);
68
+ if (port) out.push({ port, pid, command });
69
+ }
70
+ }
71
+ return out;
72
+ }
73
+
74
+ /**
75
+ * `ss -ltnp` → [{ port, pid, command }]. A listener owned by another user has no
76
+ * process column without root, so it comes back with pid null.
77
+ */
78
+ function parseSs(text) {
79
+ const out = [];
80
+ for (const line of text.split(/\r?\n/)) {
81
+ const cols = line.trim().split(/\s+/);
82
+ if (cols[0] !== 'LISTEN') continue;
83
+ const port = portOf(cols[3]);
84
+ if (!port) continue;
85
+ const users = /users:\((.*)\)/.exec(line);
86
+ const owners = [...(users ? users[1] : '').matchAll(/\("([^"]*)",pid=(\d+)/g)];
87
+ if (!owners.length) out.push({ port, pid: null, command: '' });
88
+ for (const m of owners) out.push({ port, pid: Number(m[2]), command: m[1] });
89
+ }
90
+ return out;
91
+ }
92
+
93
+ /** `netstat -ano` (Windows) → [{ port, pid, command: '' }]. */
94
+ function parseNetstat(text) {
95
+ const out = [];
96
+ for (const line of text.split(/\r?\n/)) {
97
+ const cols = line.trim().split(/\s+/);
98
+ // Proto Local Foreign State PID — the State word is localized, so a listener is
99
+ // recognized by its foreign port 0 instead of by "LISTENING".
100
+ if (cols.length < 5 || cols[0].toUpperCase() !== 'TCP' || !/:0$/.test(cols[2])) continue;
101
+ const port = portOf(cols[1]);
102
+ const pid = Number(cols[cols.length - 1]);
103
+ if (port && Number.isInteger(pid)) out.push({ port, pid, command: '' });
104
+ }
105
+ return out;
106
+ }
107
+
108
+ /** `tasklist /FO CSV /NH` → Map(pid → image name). */
109
+ function parseTasklist(text) {
110
+ const names = new Map();
111
+ for (const line of text.split(/\r?\n/)) {
112
+ const m = /^"([^"]*)","(\d+)"/.exec(line.trim());
113
+ if (m) names.set(Number(m[2]), m[1]);
114
+ }
115
+ return names;
116
+ }
117
+
118
+ function run(cmd, args) {
119
+ const r = spawnSync(cmd, args, { encoding: 'utf8', windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
120
+ return { error: r.error || null, stdout: r.stdout || '' };
121
+ }
122
+
123
+ /** Every TCP listener on this machine that the current user can see. */
124
+ function findListeners(platform = process.platform) {
125
+ if (platform === 'win32') {
126
+ const net = run('netstat', ['-ano']);
127
+ if (net.error) throw new Error(`Could not run netstat: ${net.error.message}`);
128
+ const listeners = parseNetstat(net.stdout);
129
+ const names = parseTasklist(run('tasklist', ['/FO', 'CSV', '/NH']).stdout);
130
+ for (const l of listeners) l.command = names.get(l.pid) || '';
131
+ return listeners;
132
+ }
133
+
134
+ // ss ships with every modern Linux and still reports ports other users hold;
135
+ // macOS has no ss, so lsof goes first there. lsof exits 1 when nothing matches.
136
+ const tools = [
137
+ ['ss', ['-ltnp'], parseSs],
138
+ ['lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-Fpcn'], parseLsof],
139
+ ];
140
+ if (platform !== 'linux') tools.reverse();
141
+ for (const [cmd, args, parse] of tools) {
142
+ const r = run(cmd, args);
143
+ if (!r.error) return parse(r.stdout);
144
+ }
145
+ throw new Error('Neither lsof nor ss is installed — install one of them (e.g. `sudo apt install lsof`).');
146
+ }
147
+
148
+ /** Image name of a running process, or '' when it cannot be read. */
149
+ function processName(pid, platform = process.platform) {
150
+ if (platform === 'win32') {
151
+ return parseTasklist(run('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH']).stdout).get(pid) || '';
152
+ }
153
+ return run('ps', ['-p', String(pid), '-o', 'comm=']).stdout.trim().split('/').pop();
154
+ }
155
+
156
+ function isAlive(pid) {
157
+ try {
158
+ process.kill(pid, 0);
159
+ return true;
160
+ } catch (err) {
161
+ return err.code === 'EPERM';
162
+ }
163
+ }
164
+
165
+ /** Send one stop request. Returns null on success (or already gone), else an error message. */
166
+ function signal(pid, hard, platform) {
167
+ if (platform === 'win32') {
168
+ const r = spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { encoding: 'utf8', windowsHide: true });
169
+ if (r.error) return `could not run taskkill: ${r.error.message}`;
170
+ if (r.status === 0 || !isAlive(pid)) return null;
171
+ return (r.stderr || r.stdout || `taskkill exited ${r.status}`).trim();
172
+ }
173
+ try {
174
+ process.kill(pid, hard ? 'SIGKILL' : 'SIGTERM');
175
+ return null;
176
+ } catch (err) {
177
+ if (err.code === 'ESRCH') return null;
178
+ if (err.code === 'EPERM') return 'permission denied — it belongs to another user; retry with sudo';
179
+ return err.message;
180
+ }
181
+ }
182
+
183
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
184
+
185
+ async function waitForExit(pids, ms) {
186
+ const deadline = Date.now() + ms;
187
+ let alive = pids.filter(isAlive);
188
+ while (alive.length && Date.now() < deadline) {
189
+ await sleep(100);
190
+ alive = alive.filter(isAlive);
191
+ }
192
+ return alive;
193
+ }
194
+
195
+ /**
196
+ * Stop each { pid, command, ports } target. On macOS/Linux a process gets SIGTERM and,
197
+ * if it is still running after graceMs, SIGKILL; `force` (and Windows, where console
198
+ * processes cannot be asked politely) kills at once. Resolves to the targets with a
199
+ * status of stopped | killed | failed | protected and an error message where relevant.
200
+ */
201
+ async function stopProcesses(targets, { force = false, graceMs = GRACE_MS, platform = process.platform } = {}) {
202
+ const hard = force || platform === 'win32';
203
+ const results = targets.map((t) => ({ ...t, status: null, error: null }));
204
+ const pending = [];
205
+
206
+ for (const r of results) {
207
+ if (r.pid === process.pid) {
208
+ r.status = 'protected';
209
+ r.error = 'that is bt-agent itself';
210
+ } else if (platform !== 'win32' && r.pid === 1) {
211
+ r.status = 'protected';
212
+ r.error = 'that is the system init process';
213
+ } else if (platform === 'win32' && r.pid <= 4) {
214
+ r.status = 'protected';
215
+ r.error = 'held by Windows itself (System) — stop the service that owns it, e.g. IIS / http.sys';
216
+ } else {
217
+ const error = signal(r.pid, hard, platform);
218
+ if (error) {
219
+ r.status = 'failed';
220
+ r.error = error;
221
+ } else {
222
+ r.status = hard ? 'killed' : 'stopped';
223
+ pending.push(r);
224
+ }
225
+ }
226
+ }
227
+
228
+ let alive = await waitForExit(pending.map((r) => r.pid), hard ? KILL_WAIT_MS : graceMs);
229
+ if (alive.length && !hard) {
230
+ for (const pid of alive) signal(pid, true, platform);
231
+ for (const r of pending) if (alive.includes(r.pid)) r.status = 'killed';
232
+ alive = await waitForExit(alive, KILL_WAIT_MS);
233
+ }
234
+ for (const r of pending) {
235
+ if (alive.includes(r.pid)) {
236
+ r.status = 'failed';
237
+ r.error = 'still running after being killed';
238
+ }
239
+ }
240
+ return results;
241
+ }
242
+
243
+ module.exports = {
244
+ parsePortSpecs,
245
+ parsePids,
246
+ parseLsof,
247
+ parseSs,
248
+ parseNetstat,
249
+ parseTasklist,
250
+ findListeners,
251
+ processName,
252
+ stopProcesses,
253
+ isAlive,
254
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babylonjs-toolkit/agent",
3
- "version": "1.1.46",
3
+ "version": "1.1.48",
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",
@@ -1,13 +1,16 @@
1
1
  ---
2
2
  name: bt-convert
3
- description: "The Babylon Toolkit Convert Skill converts source code to Babylon Toolkit TypeScript. Use when asked to convert source code or files to BabylonJS/Babylon Toolkit typescript."
3
+ description: "The Babylon Toolkit Convert Skill converts source code to Babylon Toolkit TypeScript or JavaScript. Use when asked to convert source code or files to BabylonJS/Babylon Toolkit TypeScript or JavaScript."
4
4
  allowed-tools: Read, Write, Edit, Glob, Grep
5
5
  ---
6
- Your goal is to convert source code to Babylon Toolkit based TypeScript. Always adhere to any rules or requirements set out in the project's agent instructions (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md) when responding.
6
+ Your goal is to convert source code to Babylon Toolkit based TypeScript or JavaScript. Always adhere to any rules or requirements set out in the project's agent instructions (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md) when responding.
7
7
 
8
- * Create new typescript (.ts) files for converted code
8
+ * Create new files for converted code in the target language: the one the brief names, else the one the project uses, else TypeScript (`.ts`). JavaScript (`.js`) output is equally supported — never push the developer to switch languages
9
9
  * Make sure to convert all source code, do **not** omit anything (methods, properties, comments, etc), convert everything according to instructions
10
10
  * If an interface is only referenced (not defined in the source code being converted), do **not** generate the interface, just reference it
11
+ * Follow the Agent Reference's **Coding Practices — ENFORCED** in every converted file: clean, professional TypeScript or JavaScript in the project's own language; meaningful full-word names, never one- or two-letter names or obfuscation; well-structured, readable, maintainable code for human developers; meaningful JSDoc on every class, function, method and public member. Carry the source's doc comments (C# `///` XML docs and the like) across as JSDoc, and write meaningful JSDoc where the source has none
12
+ * Keep the source's public and serialized names (classes, methods, properties, fields) in camelCase, because exported Unity metadata binds to them by name. Give meaningful names to every local, parameter and helper the conversion introduces, and rename obfuscated or minified locals in the source to meaningful names
13
+ * Before finishing, re-read every converted file against the Coding Practices and fix every violation
11
14
 
12
15
  ---
13
16
 
@@ -23,6 +26,7 @@ Your goal is to convert source code to Babylon Toolkit based TypeScript. Always
23
26
  Example:
24
27
  ```
25
28
  /bt-convert → path/to/file.cs → "Convert to Babylon Toolkit TypeScript"
29
+ /bt-convert → path/to/file.cs → "Convert to Babylon Toolkit JavaScript"
26
30
  ```
27
31
 
28
32
  ---
@@ -40,6 +40,8 @@ NEVER use generic AI-generated aesthetics like overused font families (Inter, Ro
40
40
 
41
41
  Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. NEVER converge on common choices (Space Grotesk, for example) across generations.
42
42
 
43
+ **CODE QUALITY is not traded for visual ambition.** Every component, style and script follows the Agent Reference's **Coding Practices — ENFORCED**: clean, professional TypeScript or JavaScript in the project's own language; meaningful full-word names for components, props, state, variables, functions and CSS classes (never one- or two-letter names or obfuscation); well-structured code a human developer can read and maintain; and meaningful JSDoc on every component, hook, function and exported member. Elaborate effects are split into well-named components and hooks, not packed into one dense file. Before finishing, re-read every file you created or changed against those rules and fix every violation.
44
+
43
45
  **IMPORTANT**: Match implementation complexity to the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well.
44
46
 
45
47
  Remember: You are capable of extraordinary creative work. Don't hold back, show what can truly be created when thinking outside the box and committing fully to a distinctive vision.
@@ -39,19 +39,19 @@ Run tasks from a plan: build each one with its tests, have an independent verifi
39
39
 
40
40
  Work in **phases**: a `### Phase N` group in the plan, or — if the plan has none — up to 3 consecutive tasks (a `live` task, the `Update SPEC.md` task and the last task each close a group). A single task or `NEXT` is a phase of one. Under `--strict` every task is its own phase.
41
41
 
42
- 1. **Build** each task in the phase, in order, **with its tests**: the cases the plan's `Tests:` names (or, with none, meaningful cases for its Acceptance and edge cases), in the repo's test location and style (`./tests` if there is none). Get them green — fix the code, not the test, unless the test is wrong. No testable surface (config, docs, assets) → say so. Boxes stay unticked.
42
+ 1. **Build** each task in the phase, in order, **following the Agent Reference's Coding Practices — ENFORCED** (clean, professional TypeScript or JavaScript in the project's own language; meaningful full-word names, never one- or two-letter names or obfuscation; well-structured, readable, maintainable code for human developers; meaningful JSDoc on every class, function, method and public member), **with its tests**: the cases the plan's `Tests:` names (or, with none, meaningful cases for its Acceptance and edge cases), in the repo's test location and style (`./tests` if there is none). Get them green — fix the code, not the test, unless the test is wrong. No testable surface (config, docs, assets) → say so. Boxes stay unticked.
43
43
  2. **Verify** the phase with a fresh **independent verifier** subagent (charter below), giving it the list of files changed. It returns PASS/FAIL per task, with evidence.
44
44
  3. **Tick** `- [ ]` → `- [x]` for every task that passed, immediately — except a task that depends on one that failed in the same phase, which waits for it. Never tick partial, skipped or unverified work.
45
45
  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)*.
46
46
  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)`), and the next task id — for reference only.
47
47
 
48
- **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. 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. Treat an absolute count in the plan as 'named tests pass, no new failures'. [SCOPE] Return PASS/FAIL per task with evidence, listing records-only slips separately."*
48
+ **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, JSDoc type tags in JavaScript; 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; a meaningful JSDoc block (purpose, `@param`, `@returns`, units and side effects, never a restated name) on every class, function, method and public or exported member, kept true to the code. Any violation is a FAIL for that task — quote the offending lines. 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. Treat an absolute count in the plan as 'named tests pass, no new failures'. [SCOPE] Return PASS/FAIL per task with evidence, listing records-only slips separately."*
49
49
 
50
50
  `[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."*
51
51
 
52
52
  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.
53
53
 
54
- **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 URLs), the test command, the project's agent instructions, the *Work fast* rules below, and: *"Do not fetch the Agent Reference or read SPEC.md in full — the parts you need are here, and this overrides any standing instruction to fetch it first. Fetch one sub-document only if you hit an API this brief does not cover, and say which."*
54
+ **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 URLs) — **always including the full `Coding Practices — ENFORCED` section**, since implementers write to it and verifiers fail work that breaks it — the test command, the project's agent instructions, the *Work fast* rules below, and: *"Do not fetch the Agent Reference or read SPEC.md in full — the parts you need are here, and this overrides any standing instruction to fetch it first. Fetch one sub-document only if you hit an API this brief does not cover, and say which."*
55
55
 
56
56
  ## Work fast
57
57
 
@@ -39,7 +39,7 @@ Use the user's message after the skill name as the `arguments`.
39
39
 
40
40
  | Kind | Builder edits | Evidence is | Pipeline reference |
41
41
  |---|---|---|---|
42
- | **`web-game`** | BabylonJS / Toolkit TypeScript, scene code, shaders, UI | the running game in a browser | *(built in; no extra reference)* |
42
+ | **`web-game`** | BabylonJS / Toolkit TypeScript or JavaScript, scene code, shaders, UI | the running game in a browser | *(built in; no extra reference)* |
43
43
  | **`unity`** | a Unity scene via the Unity CLI — terrain, light rig, probes, bake settings, volumes, materials — with **headless Blender as the tool** for low-level model and asset work (in place, so GUIDs survive) | **in-loop: a Unity camera snapshot** rendered straight to PNG from the locked camera. Export + browser only at checkpoints (round 1, and when the work is done) | `references/unity-pipeline.md` |
44
44
 
45
45
  > **Unity is the content-creation tool and the asset manager. Blender is a tool inside it.** There is one Unity pipeline, whether the job is polishing a whole level or one asset in it. Blender does low-level model and asset creation and edits — **in place**, so GUIDs and importer settings survive — and its job ends the moment the model is back in Unity. From there the model is simply an asset in a scene: it gets its materials, colliders, LOD group, rig and Toolkit components there, and it is judged there, lit by that scene. **What gets exported is the user's call at the time** — by prompt, or from the Unity Export buttons: the whole scene as a game level (`selection == null`, full scene metadata), or one asset as an asset container (`selection != null`, components only). An asset used in a level ships inside that level's export; nothing asset-specific is required.
@@ -78,6 +78,7 @@ If you have not read it in this session/context, or you no longer remember it du
78
78
  The doctrine lives in the Agent Reference — `references/scene-components.md` § "Babylon Toolkit Component Authority" (https://raw.githubusercontent.com/babylontoolkit/agent/main/references/scene-components.md): supplied GLTF/GLB files are **interactive prefabs** whose `extras.metadata.components` carry configured physics, tuning and gameplay intent; `TOOLKIT.*` components are the first-class engine implementation — compose and tune them through `PROJECT.*` ScriptComponents, never reimplement, bypass, or delete them; replacement requires that document's evidence checklist. Read it before any round touching supplied interactive assets. The gauntlet-specific mechanics:
79
79
 
80
80
  - **Round 1 writes the inventory to disk** — `_gauntlet/<name>/components.md`: every component grouped by scene node, classified **protected-system** (`TOOLKIT.*` — tune, never replace), **project** (`PROJECT.*` — modifiable), or **authoring-only**, with safe-to-tune properties verified against `babylon.toolkit.d.ts`. A resumed cold session READS this instead of re-deriving it; the round that changes supplied assets updates it.
81
+ - **Builders write code to the Agent Reference's Coding Practices — ENFORCED** — clean, professional TypeScript or JavaScript in the project's own language, meaningful full-word names (never one- or two-letter names or obfuscation), well-structured, readable and maintainable by human developers, with meaningful JSDoc on every class, function, method and public member. Every builder brief carries that section in full; critics fail a part that breaks it (the *Coding practices* hard gate in `references/critic-rubrics.md`).
81
82
  - **Builders build against the manifest** — given `components.md` alongside the Agent Reference. Unity-authored serialized values are preserved unless a *measured* issue justifies the change, and the measurement goes in the round journal.
82
83
  - **Critics enforce it** — reimplementing, bypassing (e.g. direct transform updates beside an attached physics controller), or deleting a protected component is a **FAIL regardless of how the evidence looks**, unless the round journal carries the full replacement-evidence checklist.
83
84
 
@@ -100,6 +100,7 @@ threshold AND every gate passes.**
100
100
  | **Perf** | the loop card's FPS / draw-call / load-time / memory budget is missed |
101
101
  | **Console** | any error in the browser console (warnings are reported, not fatal, unless the card says otherwise) |
102
102
  | **Component authority** | a protected `TOOLKIT.*` component was reimplemented, bypassed or deleted without the full replacement-evidence checklist in the round journal |
103
+ | **Coding practices** | any code the round created or changed breaks the Agent Reference's **Coding Practices — ENFORCED**: TypeScript or JavaScript that is not clean and professional (needless `any` or loose typing, JavaScript without JSDoc type tags, code converted to the other language unasked), one- or two-letter or obfuscated names (outside the allowed loop counters, axis/`uv` names, toolkit aliases and names that bind to exported data), dead code or leftover `console.log`, a missing or meaningless JSDoc block on a class, function, method or public member, or code a developer new to the project could not read and maintain. Quote the offending lines |
103
104
  | **Camera lock** | the evidence was not captured from the transform recorded in `cameras.md` |
104
105
  | **Pipeline gate** | whatever the deliverable kind's pipeline reference declares (export-boundary integrity, GUID survival, licence tier …) |
105
106
 
@@ -49,7 +49,8 @@ Execution time is mostly *how the work is proven*, not the code. Keep proof stro
49
49
  6. **Proportional safety.** When the spec requires a safety outcome (nothing unfinished reaches the user's folders, the app keeps working between tasks), pick the cheapest mechanism that achieves it — normally a feature branch, a build output the user's folders do not read, and one copy across at the end after the live check. Version control is the archive. Add staged promotions, per-step archives or hash records only if the brief asks for them by name.
50
50
  7. **Minimal exports.** A task's Steps re-export only the Unity project the task tests and only the scenes it works on, and only when the change alters that scene's export. Never write "re-export every scene" or "re-export all projects" for consistency — other scenes pick the change up at their next natural export. Name the scenes explicitly.
51
51
  8. **No ceremony.** No standalone "verification sweep / open the review / final check" tasks, and no ledgers, md5 or environment records, archives, checked-in capture trees, standing evidence suites, doc-integrity registration or staged promotions — unless the brief asks.
52
- 8. **No brittle pins.** Never pin counts later tasks will change (tests passed, suite sizes, hashes). Say "the named tests pass, no new failures versus the baseline".
52
+ 9. **No brittle pins.** Never pin counts later tasks will change (tests passed, suite sizes, hashes). Say "the named tests pass, no new failures versus the baseline".
53
+ 10. **Plan code follows the Agent Reference's Coding Practices — ENFORCED.** Every snippet, signature, interface, class, method, property, variable, constant and file name the plan writes or decides is clean, professional TypeScript or JavaScript in the language the project uses (never switched unasked), with meaningful full-word names (never one- or two-letter names, cryptic abbreviations or code-golf tricks), well structured, readable and maintainable by human developers, and carries meaningful JSDoc on every class, function, method, interface and public member it defines. The executor copies plan code word for word, so a badly named snippet ships badly named. Names that bind to exported data (component properties, serialized fields, Unity property names) keep the source's names. Code-quality checks are never a separate task; bt-execute's verifier enforces them on every task.
53
54
 
54
55
  ## Step 3. Write the plan
55
56
 
@@ -126,12 +127,12 @@ Run a single task with `bt-execute _specs/<feature-name>_plan.md T1`, or every t
126
127
 
127
128
  Use when the plan will be executed in fresh contexts, over days, or by a cheaper model than the one planning. The plan file is then the only memory that survives between tasks: **whatever it does not say, task 40 will re-decide differently from task 3.** So a heavy plan decides everything once, in one place, and every task cites it. Print `🏋️ [bt-plan] Heavy Plan mode`. Everything above still applies; the document gains two sections and richer task blocks. There is no limit on how much a heavy plan may say — write what the executor needs — but the number of tasks still follows the spec's `size`.
128
129
 
129
- In Step 1, collect plan-grade detail: `file:line` references, the real signatures the feature calls or changes, verbatim 10–30-line snippets of the conventions to mirror, the exact API usage from the Agent Reference sub-documents, and the test baseline (command, current state, pre-existing failures). Carry the spec's Decisions forward and resolve every Open Question — with the user if needed. "TBD", "as appropriate", "the implementer may choose" are forbidden.
130
+ In Step 1, collect plan-grade detail: `file:line` references, the real signatures the feature calls or changes, verbatim 10–30-line snippets of the conventions to mirror, the exact API usage from the Agent Reference sub-documents, the Agent Reference's full `Coding Practices — ENFORCED` section, and the test baseline (command, current state, pre-existing failures). Carry the spec's Decisions forward and resolve every Open Question — with the user if needed. "TBD", "as appropriate", "the implementer may choose" are forbidden.
130
131
 
131
132
  Sections, in order: `## Codebase Analysis` (plus the test baseline) · **`## Decisions`** · **`## Design Reference`** · `## Tasks` · `## Estimated execution time` · `## How to execute this plan`.
132
133
 
133
134
  - **`## Decisions`** — numbered `D1, D2 …`, one per choice that binds more than one task or rejects a plausible alternative — architecture, file layout, naming, algorithms and constants, error policy, dependencies (exact packages and versions, or "no new dependencies"), sibling-skill option values, test strategy:
134
135
  `- **D3 — <decision, stated as a fact>.** <why / precedent with file:line> Rejected: <alternative> (<why not>). Binds: T4, T7.`
135
- - **`## Design Reference`** — the shared blueprint, written as code wherever the code *is* the decision: File map (path · create/modify/delete · responsibility · tasks) · Module boundaries · Interfaces & contracts (full signatures, in the project's language) · Data shapes & state · Control flow · Algorithms & formulas with their constants · Error & edge-case policy (`when X → Y`) · Conventions to mirror (verbatim, with `file:line`) · API usage · Test strategy. Omit a heading only if it truly does not apply.
136
- - **Heavy task block** — adds to the standard block: `Depends on:` · `Applies:` (the D-numbers and Design Reference entries it must match) · `Steps:` numbered instructions, each naming the file, a real anchor (prefer quoted code over bare line numbers) and the change · `Code:` when the code is the decision · `Do not:` the tempting wrong turns · `Verify:` commands with expected output. `Depends on`, `Files`, `Applies`, `Steps`, `Tests`, `Acceptance`, `Verify` and `Verify level` are required on every heavy task. A task never says "like T3" — it cites the Design Reference; a name, signature or value a step introduces is added to the Design Reference first, so task 40 types what task 3 typed. Say what keeps the app working between tasks (shim, flag) and which task removes it. The `Update SPEC.md` task carries the exact text to write.
137
- - **Cold-context audit (one pass).** After the draft, launch one fresh read-only subagent (or re-read it yourself) with: *"You have never seen this repo. For every task, check the plan against the real files and list each point where you would have to decide, guess or look something up: a missing signature, name, value or anchor; an anchor that does not match the file; a goal stated instead of an instruction; a dependence on remembering an earlier task; a name used in a task but not defined in the Design Reference; a test without an expected outcome; a Verify without an expected output; vague words ("appropriate", "as needed", "etc."); a task that would not fit in one sitting; an edge case with no decided behavior; an API call not shown. Also flag micro-tasks to merge, ceremony tasks nobody asked for, and pinned counts later tasks will change. Report `T<n> · step · what is missing`. Change nothing."* Fix every gap in the plan, ask the user what only they can answer, list any gap you chose not to resolve (with why) in Codebase Analysis, then finalize: `💾 [bt-plan] Plan finalized — <n> tasks, <k> decisions`, and report the two or three most consequential decisions and anything left unresolved.
136
+ - **`## Design Reference`** — the shared blueprint, written as code wherever the code *is* the decision: File map (path · create/modify/delete · responsibility · tasks) · Module boundaries · Interfaces & contracts (full signatures, in the project's language) · Data shapes & state · Control flow · Algorithms & formulas with their constants · Error & edge-case policy (`when X → Y`) · Conventions to mirror (verbatim, with `file:line`) · API usage · Test strategy. Omit a heading only if it truly does not apply. **All of it is written to the Agent Reference's **Coding Practices — ENFORCED****: every interface, signature, data shape, constant and snippet uses meaningful full-word names, strict types (JSDoc type tags in JavaScript) and meaningful JSDoc, and reads cleanly to a developer new to the project. Mirror the structure of existing conventions, but never copy one- or two-letter names or obfuscated code into a new name.
137
+ - **Heavy task block** — adds to the standard block: `Depends on:` · `Applies:` (the D-numbers and Design Reference entries it must match) · `Steps:` numbered instructions, each naming the file, a real anchor (prefer quoted code over bare line numbers) and the change · `Code:` when the code is the decision, written to the Coding Practices exactly as it must ship · `Do not:` the tempting wrong turns · `Verify:` commands with expected output. `Depends on`, `Files`, `Applies`, `Steps`, `Tests`, `Acceptance`, `Verify` and `Verify level` are required on every heavy task. A task never says "like T3" — it cites the Design Reference; a name, signature or value a step introduces is added to the Design Reference first, so task 40 types what task 3 typed. Say what keeps the app working between tasks (shim, flag) and which task removes it. The `Update SPEC.md` task carries the exact text to write.
138
+ - **Cold-context audit (one pass).** After the draft, launch one fresh read-only subagent (or re-read it yourself) with: *"You have never seen this repo. For every task, check the plan against the real files and list each point where you would have to decide, guess or look something up: a missing signature, name, value or anchor; an anchor that does not match the file; a goal stated instead of an instruction; a dependence on remembering an earlier task; a name used in a task but not defined in the Design Reference; a test without an expected outcome; a Verify without an expected output; vague words ("appropriate", "as needed", "etc."); a task that would not fit in one sitting; an edge case with no decided behavior; an API call not shown; any snippet, signature or name that breaks the Agent Reference's Coding Practices — ENFORCED (code in the wrong language for the project, loose typing or needless `any`, a missing or meaningless JSDoc block, one- or two-letter or obfuscated names, code-golf tricks, code a developer new to the project could not read and maintain). Also flag micro-tasks to merge, ceremony tasks nobody asked for, and pinned counts later tasks will change. Report `T<n> · step · what is missing`. Change nothing."* Fix every gap in the plan, ask the user what only they can answer, list any gap you chose not to resolve (with why) in Codebase Analysis, then finalize: `💾 [bt-plan] Plan finalized — <n> tasks, <k> decisions`, and report the two or three most consequential decisions and anything left unresolved.
@@ -126,13 +126,14 @@ If the user wants a genuine faithful rebuild of **one specific** award-winning s
126
126
 
127
127
  Build the N prototypes **in parallel via subagents** — if a subagent-spawning/workflow tool is available (Claude Code's `Task`/Agent, a Workflow, or the host's equivalent), launch one per prototype (cap concurrency to what the host allows; queue the rest). If no subagent tool is available, build them sequentially yourself. Never call a subagent tool you don't have.
128
128
 
129
- Each prototype subagent gets: its **direction**, the **theme**, the **world anchor** (screenshots + extracted palette/mood/silhouettes), the **`--type`**, and the **asset workflows** available. It must:
129
+ Each prototype subagent gets: its **direction**, the **theme**, the **world anchor** (screenshots + extracted palette/mood/silhouettes), the **`--type`**, and the **asset workflows** available, plus the full text of the Agent Reference's **Coding Practices — ENFORCED**. It must:
130
130
 
131
131
  1. **Own its folder.** Create `_prototypes/<NN-slug>/` and put **everything self-contained inside it** — markup, styles, scripts, and all generated/downloaded assets. No shared globals; a prototype is copy-out-able on its own.
132
132
  2. **Build to the Fable bar for its lens** — advanced 3D tactics, otherworldly animation, exceptional palette, novel type. Not a template with the colors swapped; a distinct, *mind-blowing* execution of that direction for this game. **Full-bleed console UI by default** (bt-design's *Layout Philosophy*): fill the whole viewport edge-to-edge like a console dashboard / game menu, not a centered fixed-width website — unless this direction is the noted contained exception.
133
133
  3. **Produce assets** via any mix of the available workflows: Pinterest pulls for reference, **GPT Image 2** for stills, **KIE MCP servers (default) / the Higgsfield CLI (Kling, Seedance, etc.)** for motion/video, hand-authored WebGL/SVG/CSS. All assets stay faithful to the world anchor and live in the prototype's folder. **On Higgsfield, every generation goes through the reference's `scripts/hf-generate.mjs` wrapper** with `--out _prototypes/<NN-slug>/<file>`: the CLI alone only returns a CDN URL, and a prototype must never hot-link one. Local reference images are passed as file paths (`--image-references`, `--start-image`, `--end-image`) and uploaded automatically.
134
134
  4. **3D-hero-scroll directions:** follow *The 3D-hero-scroll batch rule* below.
135
135
  5. Run its own **iteration passes** (Step 4) before returning.
136
+ 6. **Write clean, readable code.** Every file follows the Coding Practices: clean, professional TypeScript or JavaScript in the project's own language; meaningful full-word names, never one- or two-letter names or obfuscation; well-structured, readable, maintainable code for human developers; meaningful JSDoc on every class, function, method and public member. The chosen prototype becomes the user's real front end, so its code must be maintainable.
136
137
 
137
138
  ## The 3D-hero-scroll batch rule
138
139