@babylonjs-toolkit/agent 1.1.66 → 1.1.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,516 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * bt-profile progress: the one way the agent tells the dashboard what a profile run is doing, plus the watchdog
4
+ * that keeps it honest while a long capture or analysis runs and the agent is silent.
5
+ *
6
+ * Every write reads `data/progress.js`, parses its strict JSON, changes it and writes it back atomically (a temp file
7
+ * renamed over the original), so the page never loads a half-written file.
8
+ *
9
+ * node progress.mjs start <slug-folder> [--title "…"] [--brief "…"] [--project <path>] [--url <url>] [--mode report|auto-fix] [--open true]
10
+ * node progress.mjs set <slug-folder> [--url <url>] [--title "…"] [--brief "…"] [--project <path>] details found after start
11
+ * node progress.mjs stage <slug-folder> <preflight|baseline|diagnose|fix|verify|report> [--status active|done|skipped] [--note "…"]
12
+ * node progress.mjs now <slug-folder> "<what is happening this minute>" [--step "<log line, if different>"]
13
+ * node progress.mjs fix <slug-folder> <F1> [--title "…"] [--status planned|trying|measuring|kept|reverted|skipped] [--before "…"] [--after "…"] [--note "…"]
14
+ * node progress.mjs metric <slug-folder> "<label>" "<value>" [--note "…"]
15
+ * node progress.mjs note <slug-folder> "<milestone>"
16
+ * node progress.mjs end <slug-folder> [--status done|stopped|failed] [--summary "…"]
17
+ * node progress.mjs stop <slug-folder> [--reason "…"] ends a running capture (and its Chrome) and marks the run stopped
18
+ * node progress.mjs resume <slug-folder> reopens a stopped run where it stopped; prints where to continue (JSON)
19
+ * node progress.mjs restart <slug-folder> [--title "…"] [--brief "…"] archives the runs, findings and report, then starts over
20
+ * node progress.mjs check <slug-folder>
21
+ * node progress.mjs watch <slug-folder> [--watch <folder>]… [--interval-seconds 60] [--quiet-minutes 5] [--stall-minutes 30] [--max-hours 12]
22
+ *
23
+ * <slug-folder> is .agents/profile/<slug> (it holds dashboard.html and data/). Timestamps are this machine's local time.
24
+ */
25
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
26
+ import { basename, dirname, join, relative } from "node:path";
27
+ import { spawn } from "node:child_process";
28
+
29
+ import { PROGRESS_MARKER, livePage, withProgressPanel } from "./lib/progress-panel.mjs";
30
+
31
+ const PREFIX = "window.PROFILE_PROGRESS";
32
+ /** The stages every profile run goes through, in order. */
33
+ const STAGES = [
34
+ { id: "preflight", name: "Preflight" },
35
+ { id: "baseline", name: "Baseline" },
36
+ { id: "diagnose", name: "Diagnose" },
37
+ { id: "fix", name: "Fix" },
38
+ { id: "verify", name: "Verify" },
39
+ { id: "report", name: "Report" },
40
+ ];
41
+ /** How the watchdog says what each stage is doing ("Still measuring the baseline …"). */
42
+ const STAGE_DOING = {
43
+ preflight: "preparing the run",
44
+ baseline: "measuring the baseline",
45
+ diagnose: "diagnosing",
46
+ fix: "working on fixes",
47
+ verify: "verifying",
48
+ report: "writing the report",
49
+ };
50
+ const STAGE_STATUSES = new Set(["pending", "active", "done", "skipped"]);
51
+ const FIX_STATUSES = new Set(["planned", "trying", "measuring", "kept", "reverted", "skipped"]);
52
+ const END_STATUSES = new Set(["done", "stopped", "failed"]);
53
+ /** How many lines the live step log keeps. */
54
+ const MAXIMUM_STEPS = 12;
55
+ /** Folders the watchdog never descends into. */
56
+ const IGNORED_FOLDERS = new Set(["node_modules", ".git", ".tools", "Library", "Temp", "Logs", "obj", "dist", "build", ".cache", ".vite", ".vite-profile-cache"]);
57
+ const MAXIMUM_SCAN_DEPTH = 6;
58
+
59
+ const [command, slugFolder, ...rest] = process.argv.slice(2);
60
+
61
+ const progressPath = (folder) => join(folder, "data", "progress.js");
62
+
63
+ function localTime(moment = new Date()) {
64
+ const pad = (value) => String(value).padStart(2, "0");
65
+ const clock = `${pad(moment.getHours())}:${pad(moment.getMinutes())}`;
66
+ return { stamp: `${moment.getFullYear()}-${pad(moment.getMonth() + 1)}-${pad(moment.getDate())} ${clock}`, clock };
67
+ }
68
+
69
+ function parseStamp(stamp) {
70
+ const match = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})/.exec(String(stamp || ""));
71
+ if (!match) return null;
72
+ const [, year, month, day, hour, minute] = match.map(Number);
73
+ return new Date(year, month - 1, day, hour, minute);
74
+ }
75
+
76
+ /** Reads `--name value` options; names listed in `repeatable` collect every occurrence. */
77
+ function parseOptions(argumentList, repeatable = []) {
78
+ const options = Object.fromEntries(repeatable.map((name) => [name, []]));
79
+ const positional = [];
80
+ for (let index = 0; index < argumentList.length; index += 1) {
81
+ const argument = argumentList[index];
82
+ if (!argument.startsWith("--")) {
83
+ positional.push(argument);
84
+ continue;
85
+ }
86
+ const name = argument.slice(2);
87
+ const next = argumentList[index + 1];
88
+ const value = next === undefined || next.startsWith("--") ? true : argumentList[++index];
89
+ if (repeatable.includes(name)) options[name].push(value);
90
+ else options[name] = value;
91
+ }
92
+ return { options, positional };
93
+ }
94
+
95
+ function readProgress(folder) {
96
+ const file = progressPath(folder);
97
+ if (!existsSync(file)) throw new Error(`${file} does not exist — run "progress.mjs start" first`);
98
+ const text = readFileSync(file, "utf8");
99
+ const separator = text.indexOf("=");
100
+ if (separator < 0) throw new Error(`${file} has no "${PREFIX} =" prefix`);
101
+ return JSON.parse(text.slice(separator + 1).trim().replace(/;\s*$/, ""));
102
+ }
103
+
104
+ function writeProgress(folder, progress) {
105
+ const file = progressPath(folder);
106
+ mkdirSync(dirname(file), { recursive: true });
107
+ progress.updatedAt = localTime().stamp;
108
+ const temporary = `${file}.${process.pid}.tmp`;
109
+ writeFileSync(temporary, `${PREFIX} = ${JSON.stringify(progress, null, 2)};\n`, "utf8");
110
+ renameSync(temporary, file);
111
+ }
112
+
113
+ /** Adds a milestone and, unless the step says otherwise, the same line to the live step log. */
114
+ function addMilestone(progress, text) {
115
+ progress.activity = Array.isArray(progress.activity) ? progress.activity : [];
116
+ progress.activity.push({ at: localTime().stamp, text });
117
+ }
118
+
119
+ function setNow(progress, activity, step, source = "agent") {
120
+ const now = progress.now && typeof progress.now === "object" ? progress.now : {};
121
+ const steps = Array.isArray(now.steps) ? now.steps : [];
122
+ if (step) steps.push({ at: localTime().clock, text: step });
123
+ progress.now = { ...now, updatedAt: localTime().stamp, activity, source, steps: steps.slice(-MAXIMUM_STEPS) };
124
+ }
125
+
126
+ /** Starts a run: a fresh progress file, and a live dashboard when the slug has none that carries the panel. */
127
+ function start(folder, argumentList) {
128
+ const { options } = parseOptions(argumentList);
129
+ // Fixing is opt-in (--auto-fix): without it the run measures, diagnoses and lists the fixes, and changes no code.
130
+ const mode = (options.mode === "auto-fix" || options.mode === "fix") ? "auto-fix" : "report";
131
+ const stamp = localTime().stamp;
132
+ const stages = STAGES.map((stage) => ({ ...stage, status: "pending", started: "", finished: "", note: "" }));
133
+ stages[0].status = "active";
134
+ stages[0].started = localTime().clock;
135
+ if (mode === "report") {
136
+ Object.assign(stages.find((stage) => stage.id === "fix"), { status: "skipped", note: "fixes listed, not applied (add --auto-fix to apply them)" });
137
+ Object.assign(stages.find((stage) => stage.id === "verify"), { status: "skipped", note: "no code changed, nothing to verify" });
138
+ }
139
+ const progress = {
140
+ schema: 1,
141
+ status: "running",
142
+ slug: basename(folder),
143
+ run: Number(options.run || 1),
144
+ title: String(options.title || `${basename(folder)} profile`),
145
+ brief: String(options.brief || ""),
146
+ project: String(options.project || ""),
147
+ url: String(options.url || ""),
148
+ mode,
149
+ startedAt: stamp,
150
+ finishedAt: "",
151
+ summary: "",
152
+ stages,
153
+ metrics: [],
154
+ fixes: [],
155
+ now: { updatedAt: stamp, activity: "Starting the profile — checking the project, the dev server and the scenario.", source: "agent", steps: [] },
156
+ activity: [],
157
+ };
158
+ addMilestone(progress, `Profile started${progress.brief ? ` — ${progress.brief}` : ""}`);
159
+ writeProgress(folder, progress);
160
+
161
+ const dashboard = join(folder, "dashboard.html");
162
+ const current = existsSync(dashboard) ? readFileSync(dashboard, "utf8") : "";
163
+ if (!current.includes(PROGRESS_MARKER)) {
164
+ // Never replace a report: one from before the panel existed keeps every chart, table and finding, with the live
165
+ // panel added on top (a copy stays in data/previous-dashboard.html). Only a slug with no report gets the bare live page.
166
+ const upgraded = current ? withProgressPanel(current) : null;
167
+ if (current) writeFileSync(join(folder, "data", "previous-dashboard.html"), current);
168
+ writeFileSync(dashboard, upgraded || livePage({ title: progress.title }));
169
+ console.log(upgraded ? `added the live panel to the existing report ${dashboard}` : `wrote the live page ${dashboard}${current ? " (the previous report is in data/previous-dashboard.html)" : ""}`);
170
+ }
171
+ console.log(`progress: started ${progress.title} (${mode})`);
172
+ // The user watches the run live, so the page opens with it (once — it reloads itself from then on).
173
+ if (options.open === "true" || options.open === true) openInBrowser(dashboard);
174
+ }
175
+
176
+ /** Opens a file in the default browser, without waiting for it. */
177
+ function openInBrowser(file) {
178
+ const opener = process.platform === "darwin" ? ["open", [file]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", file]] : ["xdg-open", [file]];
179
+ try {
180
+ spawn(opener[0], opener[1], { detached: true, stdio: "ignore" }).on("error", () => console.log(`open ${file} in a browser`)).unref();
181
+ } catch {
182
+ console.log(`open ${file} in a browser`);
183
+ }
184
+ }
185
+
186
+ /** Updates the run's details once they are known (the URL is often found after `start`, by reading the code). */
187
+ function set(folder, argumentList) {
188
+ const { options } = parseOptions(argumentList);
189
+ const progress = readProgress(folder);
190
+ const changed = [];
191
+ for (const field of ["title", "brief", "project", "url"]) {
192
+ if (options[field] !== undefined && options[field] !== true) { progress[field] = String(options[field]); changed.push(field); }
193
+ }
194
+ if (!changed.length) throw new Error("progress.mjs set <slug-folder> [--url …] [--title …] [--brief …] [--project …]");
195
+ writeProgress(folder, progress);
196
+ }
197
+
198
+ function stage(folder, argumentList) {
199
+ const { options, positional } = parseOptions(argumentList);
200
+ const id = positional[0];
201
+ const status = String(options.status || "active");
202
+ if (!STAGE_STATUSES.has(status)) throw new Error(`stage status must be one of ${[...STAGE_STATUSES].join(", ")}`);
203
+ const progress = readProgress(folder);
204
+ const target = (progress.stages || []).find((candidate) => candidate.id === id);
205
+ if (!target) throw new Error(`unknown stage "${id}" — one of ${STAGES.map((candidate) => candidate.id).join(", ")}`);
206
+ const clock = localTime().clock;
207
+ if (status === "active") {
208
+ // One stage is active at a time: starting one finishes the one before it.
209
+ for (const other of progress.stages) {
210
+ if (other !== target && other.status === "active") Object.assign(other, { status: "done", finished: clock });
211
+ }
212
+ Object.assign(target, { status, started: target.started || clock, finished: "" });
213
+ progress.now = { ...(progress.now || {}), steps: [] };
214
+ setNow(progress, options.note ? String(options.note) : `${target.name} started.`, `${target.name} started`);
215
+ addMilestone(progress, `${target.name} started${options.note ? ` — ${options.note}` : ""}`);
216
+ } else {
217
+ Object.assign(target, { status, finished: status === "done" ? clock : target.finished });
218
+ addMilestone(progress, `${target.name} ${status}${options.note ? ` — ${options.note}` : ""}`);
219
+ }
220
+ if (options.note) target.note = String(options.note);
221
+ writeProgress(folder, progress);
222
+ }
223
+
224
+ function now(folder, argumentList) {
225
+ const { options, positional } = parseOptions(argumentList);
226
+ const activity = positional.join(" ").trim();
227
+ if (!activity) throw new Error('say what is happening: progress.mjs now <slug-folder> "<sentence>"');
228
+ const progress = readProgress(folder);
229
+ setNow(progress, activity, options.step ? String(options.step) : activity);
230
+ writeProgress(folder, progress);
231
+ }
232
+
233
+ function fix(folder, argumentList) {
234
+ const { options, positional } = parseOptions(argumentList);
235
+ const id = positional[0];
236
+ if (!id) throw new Error("name the fix: progress.mjs fix <slug-folder> F1 …");
237
+ if (options.status && !FIX_STATUSES.has(options.status)) throw new Error(`fix status must be one of ${[...FIX_STATUSES].join(", ")}`);
238
+ const progress = readProgress(folder);
239
+ progress.fixes = Array.isArray(progress.fixes) ? progress.fixes : [];
240
+ let entry = progress.fixes.find((candidate) => candidate.id === id);
241
+ if (!entry) {
242
+ entry = { id, title: "", status: "planned", before: "", after: "", note: "" };
243
+ progress.fixes.push(entry);
244
+ }
245
+ const previousStatus = entry.status;
246
+ for (const field of ["title", "status", "before", "after", "note"]) if (options[field] !== undefined && options[field] !== true) entry[field] = String(options[field]);
247
+ if (entry.status !== previousStatus || !previousStatus) {
248
+ const line = `${id} ${entry.status}: ${entry.title}${entry.before || entry.after ? ` (${entry.before || "–"} → ${entry.after || "…"})` : ""}`;
249
+ addMilestone(progress, line);
250
+ setNow(progress, progress.now && progress.now.activity ? progress.now.activity : line, line);
251
+ }
252
+ writeProgress(folder, progress);
253
+ }
254
+
255
+ function metric(folder, argumentList) {
256
+ const { options, positional } = parseOptions(argumentList);
257
+ const [label, value] = positional;
258
+ if (!label || value === undefined) throw new Error('progress.mjs metric <slug-folder> "<label>" "<value>" [--note "…"]');
259
+ const progress = readProgress(folder);
260
+ progress.metrics = Array.isArray(progress.metrics) ? progress.metrics : [];
261
+ const entry = progress.metrics.find((candidate) => candidate.label === label);
262
+ const note = options.note && options.note !== true ? String(options.note) : entry ? entry.note : "";
263
+ if (entry) Object.assign(entry, { value: String(value), note });
264
+ else progress.metrics.push({ label, value: String(value), note });
265
+ writeProgress(folder, progress);
266
+ }
267
+
268
+ function note(folder, argumentList) {
269
+ const text = argumentList.join(" ").trim();
270
+ if (!text) throw new Error('progress.mjs note <slug-folder> "<milestone>"');
271
+ const progress = readProgress(folder);
272
+ addMilestone(progress, text);
273
+ writeProgress(folder, progress);
274
+ }
275
+
276
+ function end(folder, argumentList) {
277
+ const { options } = parseOptions(argumentList);
278
+ const status = String(options.status || "done");
279
+ if (!END_STATUSES.has(status)) throw new Error(`end status must be one of ${[...END_STATUSES].join(", ")}`);
280
+ const progress = readProgress(folder);
281
+ const clock = localTime().clock;
282
+ for (const candidate of progress.stages || []) {
283
+ if (candidate.status === "active" && status === "done") Object.assign(candidate, { status: "done", finished: clock });
284
+ }
285
+ Object.assign(progress, { status, finishedAt: localTime().stamp, summary: options.summary && options.summary !== true ? String(options.summary) : progress.summary });
286
+ setNow(progress, status === "done" ? "Finished — the report is written." : `Ended (${status}).`, `Run ${status}`);
287
+ addMilestone(progress, `Profile ${status}${progress.summary ? ` — ${progress.summary}` : ""}`);
288
+ writeProgress(folder, progress);
289
+ }
290
+
291
+ function check(folder) {
292
+ const progress = readProgress(folder);
293
+ const problems = [];
294
+ for (const field of ["stages", "metrics", "fixes", "activity"]) if (!Array.isArray(progress[field])) problems.push(`${field} is not a list`);
295
+ if (!progress.now || typeof progress.now !== "object") problems.push("now is not an object");
296
+ else if (!Array.isArray(progress.now.steps)) problems.push("now.steps is not a list");
297
+ if (problems.length) throw new Error(problems.join("; "));
298
+ console.log(`progress.js is valid — ${progress.status}, ${progress.fixes.length} fixes, ${progress.activity.length} milestones`);
299
+ }
300
+
301
+ /* ===================== Watchdog ===================== */
302
+
303
+ /** The most recently changed file under some folders, skipping dependency, build and cache folders. */
304
+ function latestChange(roots) {
305
+ let latest = null;
306
+ const visit = (folder, depth) => {
307
+ let entries;
308
+ try {
309
+ entries = readdirSync(folder, { withFileTypes: true });
310
+ } catch {
311
+ return;
312
+ }
313
+ for (const entry of entries) {
314
+ const path = join(folder, entry.name);
315
+ if (entry.isDirectory()) {
316
+ if (depth < MAXIMUM_SCAN_DEPTH && !IGNORED_FOLDERS.has(entry.name)) visit(path, depth + 1);
317
+ continue;
318
+ }
319
+ // The progress file and the page are written by the agent and the watchdog — not a sign of work.
320
+ if (!entry.isFile() || entry.name.endsWith(".tmp") || entry.name === "progress.js" || entry.name === "dashboard.html") continue;
321
+ try {
322
+ const modified = statSync(path).mtimeMs;
323
+ if (!latest || modified > latest.modified) latest = { path, modified };
324
+ } catch {
325
+ /* the file vanished between listing and stat */
326
+ }
327
+ }
328
+ };
329
+ roots.forEach((root) => visit(root, 0));
330
+ return latest;
331
+ }
332
+
333
+ /** The last meaningful line of the newest capture log — what profile.mjs or analyze.mjs is doing right now. */
334
+ function latestLogLine(folder) {
335
+ const logs = join(folder, "data", "logs");
336
+ let newest = null;
337
+ try {
338
+ for (const name of readdirSync(logs)) {
339
+ const path = join(logs, name);
340
+ const modified = statSync(path).mtimeMs;
341
+ if (!newest || modified > newest.modified) newest = { path, name, modified };
342
+ }
343
+ } catch {
344
+ return null;
345
+ }
346
+ if (!newest) return null;
347
+ const lines = readFileSync(newest.path, "utf8").split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
348
+ const line = lines.pop();
349
+ return line ? { log: newest.name, line: line.length > 160 ? `${line.slice(0, 157)}…` : line } : null;
350
+ }
351
+
352
+ /**
353
+ * The watchdog. While the run is in progress it checks every interval; when the agent has written nothing for
354
+ * `quiet-minutes` it writes a heartbeat naming the newest file and the newest capture log's last line, and when no
355
+ * file has changed for `stall-minutes` either, it says the run may be stalled. It exits when the run ends, or
356
+ * after `max-hours` (a killed run leaves the status at running, and the watchdog must not outlive it forever).
357
+ */
358
+ async function watch(folder, argumentList) {
359
+ const { options } = parseOptions(argumentList, ["watch"]);
360
+ const intervalSeconds = Number(options["interval-seconds"] || 60);
361
+ const quietMinutes = Number(options["quiet-minutes"] || 5);
362
+ const stallMinutes = Number(options["stall-minutes"] || 30);
363
+ const stopAt = Date.now() + Number(options["max-hours"] || 12) * 3600000;
364
+ const roots = [folder, ...options.watch.map(String)];
365
+ console.log(`watchdog: watching ${roots.join(", ")} every ${intervalSeconds} s (quiet after ${quietMinutes} min, stalled after ${stallMinutes} min)`);
366
+ for (;;) {
367
+ if (Date.now() > stopAt) return console.log("watchdog: reached its maximum lifetime — exiting");
368
+ let progress = null;
369
+ try {
370
+ progress = readProgress(folder);
371
+ } catch {
372
+ /* caught mid-write or briefly missing — try again next round */
373
+ }
374
+ if (progress && progress.status !== "running") return console.log(`watchdog: the run is ${progress.status} — exiting`);
375
+ if (progress) {
376
+ try {
377
+ heartbeat(folder, progress, roots, quietMinutes, stallMinutes);
378
+ } catch (error) {
379
+ console.log(`watchdog: skipped a round — ${error.message}`);
380
+ }
381
+ }
382
+ await new Promise((resolve) => setTimeout(resolve, intervalSeconds * 1000));
383
+ }
384
+ }
385
+
386
+ function heartbeat(folder, progress, roots, quietMinutes, stallMinutes) {
387
+ const moment = new Date();
388
+ const lastWrite = parseStamp(progress.now && progress.now.updatedAt);
389
+ const quietFor = lastWrite ? Math.floor((moment - lastWrite) / 60000) : Infinity;
390
+ if (quietFor < quietMinutes) return;
391
+ const change = latestChange(roots);
392
+ const changedAgo = change ? Math.floor((moment - change.modified) / 60000) : Infinity;
393
+ const where = change ? `${relative(folder, change.path) || change.path} at ${localTime(new Date(change.modified)).clock}` : "no file changes found";
394
+ const log = latestLogLine(folder);
395
+ const logText = log ? ` — ${log.log}: "${log.line}"` : "";
396
+ const activeStage = (progress.stages || []).find((candidate) => candidate.status === "active");
397
+ let activity;
398
+ let step;
399
+ if (changedAgo >= stallMinutes) {
400
+ activity = `No update for ${quietFor} min and no file has changed for ${changedAgo === Infinity ? "the whole watch" : `${changedAgo} min`} — the run may be stalled or waiting on something.`;
401
+ step = `Watchdog: possible stall — last change: ${where}`;
402
+ } else {
403
+ activity = `Still ${(activeStage && STAGE_DOING[activeStage.id]) || "working"} — no update from the agent for ${quietFor} min; latest: ${where}${logText}.`;
404
+ step = `Watchdog: still working — ${where}`;
405
+ }
406
+ setNow(progress, activity, step, "watchdog");
407
+ writeProgress(folder, progress);
408
+ console.log(`watchdog ${localTime(moment).clock}: ${activity}`);
409
+ }
410
+
411
+ /* ===================== Stop, resume, restart ===================== */
412
+
413
+ /** True while a process id is alive (signal 0 only checks). */
414
+ function isAlive(pid) {
415
+ try { process.kill(pid, 0); return true; } catch { return false; }
416
+ }
417
+
418
+ /**
419
+ * Ends the slug's running capture — the profile.mjs process and its Chrome, named by data/capture.lock.json — then
420
+ * marks the run stopped (the watchdog exits on its own once the run is no longer running). The agent rebuilds the
421
+ * report from what was captured; `resume` continues from the stage it stopped in.
422
+ */
423
+ function stop(folder, argumentList) {
424
+ const { options } = parseOptions(argumentList);
425
+ const lockPath = join(folder, "data", "capture.lock.json");
426
+ const ended = [];
427
+ if (existsSync(lockPath)) {
428
+ let lock = null;
429
+ try { lock = JSON.parse(readFileSync(lockPath, "utf8")); } catch { /* unreadable: nothing to end */ }
430
+ for (const [label, pid] of [["capture", lock && lock.pid], ["Chrome", lock && lock.browserPid]]) {
431
+ if (!pid || !isAlive(pid)) continue;
432
+ try { process.kill(pid, "SIGTERM"); ended.push(`${label} ${pid}`); } catch { /* already gone */ }
433
+ }
434
+ const deadline = Date.now() + 3000;
435
+ const pause = new Int32Array(new SharedArrayBuffer(4));
436
+ while (Date.now() < deadline && lock && [lock.pid, lock.browserPid].some((pid) => pid && isAlive(pid))) Atomics.wait(pause, 0, 0, 100); // let them exit
437
+ for (const pid of lock ? [lock.pid, lock.browserPid] : []) if (pid && isAlive(pid)) { try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } }
438
+ rmSync(lockPath, { force: true });
439
+ }
440
+ const progress = readProgress(folder);
441
+ const active = (progress.stages || []).find((candidate) => candidate.status === "active");
442
+ const reason = options.reason && options.reason !== true ? String(options.reason) : "Stopped by the user";
443
+ Object.assign(progress, { status: "stopped", finishedAt: localTime().stamp, stoppedStage: active ? active.id : "", summary: `${reason}${active ? ` during ${active.name}` : ""}.` });
444
+ setNow(progress, `Stopped${active ? ` during ${active.name}` : ""} — continue with /bt-profile --resume:${progress.slug || basename(folder)}`, "Run stopped");
445
+ addMilestone(progress, `Run ${progress.run || 1} stopped${active ? ` during ${active.name}` : ""}${ended.length ? ` (ended ${ended.join(", ")})` : ""}`);
446
+ writeProgress(folder, progress);
447
+ console.log(`stopped ${progress.slug || basename(folder)}${active ? ` during ${active.name}` : ""}${ended.length ? ` — ended ${ended.join(", ")}` : " — no capture was running"}`);
448
+ }
449
+
450
+ /**
451
+ * Reopens a stopped (or failed) run where it stopped, as the next run number, and prints where to continue as JSON:
452
+ * the stage to resume, the stages already done, and every fix with its status (re-measure one left trying / measuring).
453
+ */
454
+ function resume(folder) {
455
+ const progress = readProgress(folder);
456
+ if (progress.status === "running") throw new Error("the run is still running — stop it first, or just keep going");
457
+ if (progress.status === "done") throw new Error("the run finished — use restart to profile it again from a fresh baseline");
458
+ const stages = progress.stages || [];
459
+ const target = stages.find((candidate) => candidate.id === progress.stoppedStage) || stages.find((candidate) => candidate.status === "active") || stages.find((candidate) => candidate.status === "pending") || stages[stages.length - 1];
460
+ for (const candidate of stages) if (candidate.status === "active" && candidate !== target) candidate.status = "done";
461
+ Object.assign(target, { status: "active", note: target.note || "resumed" });
462
+ progress.run = Number(progress.run || 1) + 1;
463
+ Object.assign(progress, { status: "running", finishedAt: "", summary: "" });
464
+ delete progress.stoppedStage;
465
+ setNow(progress, `Run ${progress.run} — resuming ${target.name}`, `Run ${progress.run} resumed`);
466
+ addMilestone(progress, `Run ${progress.run} — resumed during ${target.name}`);
467
+ writeProgress(folder, progress);
468
+ console.log(JSON.stringify({
469
+ run: progress.run,
470
+ resumeStage: target.id,
471
+ doneStages: stages.filter((candidate) => candidate.status === "done").map((candidate) => candidate.id),
472
+ fixes: (progress.fixes || []).map((entry) => ({ id: entry.id, title: entry.title, status: entry.status })),
473
+ }, null, 2));
474
+ }
475
+
476
+ /**
477
+ * Starts the slug over from a fresh baseline with the same config and scenario: the earlier runs, findings and
478
+ * report move to data/archive/<date-time>/ (kept, so the new run can be compared with them), then a new run opens.
479
+ */
480
+ function restart(folder, argumentList) {
481
+ const { options } = parseOptions(argumentList);
482
+ let previous = null;
483
+ try { previous = readProgress(folder); } catch { /* no earlier run */ }
484
+ if (previous && previous.status === "running") throw new Error("the run is still running — stop it first");
485
+ const stamp = localTime().stamp.replace(/[^0-9]/g, "").slice(0, 12);
486
+ const archive = join(folder, "data", "archive", stamp);
487
+ mkdirSync(archive, { recursive: true });
488
+ for (const name of ["runs", "findings.json", "progress.js"]) {
489
+ const source = join(folder, "data", name);
490
+ if (existsSync(source)) renameSync(source, join(archive, name));
491
+ }
492
+ if (existsSync(join(folder, "dashboard.html"))) copyFileSync(join(folder, "dashboard.html"), join(archive, "dashboard.html"));
493
+ mkdirSync(join(folder, "data", "runs"), { recursive: true });
494
+ const carried = ["title", "brief", "project", "url", "mode"].flatMap((key) => {
495
+ const value = options[key] && options[key] !== true ? options[key] : (previous ? previous[key] : "");
496
+ return value ? [`--${key}`, String(value)] : [];
497
+ });
498
+ start(folder, [...carried, "--run", String(previous ? Number(previous.run || 1) + 1 : 1)]);
499
+ const progress = readProgress(folder);
500
+ addMilestone(progress, `Restarted from a fresh baseline — the earlier runs are in data/archive/${stamp}/`);
501
+ writeProgress(folder, progress);
502
+ console.log(`restarted ${basename(folder)} — earlier runs, findings and report archived in data/archive/${stamp}/`);
503
+ }
504
+
505
+ const commands = { start, set, stage, now, fix, metric, note, end, check, watch, stop, resume, restart };
506
+
507
+ if (!commands[command] || !slugFolder) {
508
+ console.error("usage: node progress.mjs <start|set|stage|now|fix|metric|note|end|stop|resume|restart|check|watch> <slug-folder> [options] — see the header of this file");
509
+ process.exit(2);
510
+ }
511
+ try {
512
+ await commands[command](slugFolder, rest);
513
+ } catch (error) {
514
+ console.error(`progress.mjs ${command}: ${error.message}`);
515
+ process.exit(1);
516
+ }