@babylonjs-toolkit/agent 1.1.66 → 1.1.68

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,385 @@
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 fix|analyze]
10
+ * node progress.mjs stage <slug-folder> <preflight|baseline|diagnose|fix|verify|report> [--status active|done|skipped] [--note "…"]
11
+ * node progress.mjs now <slug-folder> "<what is happening this minute>" [--step "<log line, if different>"]
12
+ * node progress.mjs fix <slug-folder> <F1> [--title "…"] [--status planned|trying|measuring|kept|reverted|skipped] [--before "…"] [--after "…"] [--note "…"]
13
+ * node progress.mjs metric <slug-folder> "<label>" "<value>" [--note "…"]
14
+ * node progress.mjs note <slug-folder> "<milestone>"
15
+ * node progress.mjs end <slug-folder> [--status done|stopped|failed] [--summary "…"]
16
+ * node progress.mjs check <slug-folder>
17
+ * node progress.mjs watch <slug-folder> [--watch <folder>]… [--interval-seconds 60] [--quiet-minutes 5] [--stall-minutes 30] [--max-hours 12]
18
+ *
19
+ * <slug-folder> is .agents/profile/<slug> (it holds dashboard.html and data/). Timestamps are this machine's local time.
20
+ */
21
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
22
+ import { basename, dirname, join, relative } from "node:path";
23
+
24
+ import { PROGRESS_MARKER, livePage } from "./lib/progress-panel.mjs";
25
+
26
+ const PREFIX = "window.PROFILE_PROGRESS";
27
+ /** The stages every profile run goes through, in order. */
28
+ const STAGES = [
29
+ { id: "preflight", name: "Preflight" },
30
+ { id: "baseline", name: "Baseline" },
31
+ { id: "diagnose", name: "Diagnose" },
32
+ { id: "fix", name: "Fix" },
33
+ { id: "verify", name: "Verify" },
34
+ { id: "report", name: "Report" },
35
+ ];
36
+ /** How the watchdog says what each stage is doing ("Still measuring the baseline …"). */
37
+ const STAGE_DOING = {
38
+ preflight: "preparing the run",
39
+ baseline: "measuring the baseline",
40
+ diagnose: "diagnosing",
41
+ fix: "working on fixes",
42
+ verify: "verifying",
43
+ report: "writing the report",
44
+ };
45
+ const STAGE_STATUSES = new Set(["pending", "active", "done", "skipped"]);
46
+ const FIX_STATUSES = new Set(["planned", "trying", "measuring", "kept", "reverted", "skipped"]);
47
+ const END_STATUSES = new Set(["done", "stopped", "failed"]);
48
+ /** How many lines the live step log keeps. */
49
+ const MAXIMUM_STEPS = 12;
50
+ /** Folders the watchdog never descends into. */
51
+ const IGNORED_FOLDERS = new Set(["node_modules", ".git", ".tools", "Library", "Temp", "Logs", "obj", "dist", "build", ".cache", ".vite", ".vite-profile-cache"]);
52
+ const MAXIMUM_SCAN_DEPTH = 6;
53
+
54
+ const [command, slugFolder, ...rest] = process.argv.slice(2);
55
+
56
+ const progressPath = (folder) => join(folder, "data", "progress.js");
57
+
58
+ function localTime(moment = new Date()) {
59
+ const pad = (value) => String(value).padStart(2, "0");
60
+ const clock = `${pad(moment.getHours())}:${pad(moment.getMinutes())}`;
61
+ return { stamp: `${moment.getFullYear()}-${pad(moment.getMonth() + 1)}-${pad(moment.getDate())} ${clock}`, clock };
62
+ }
63
+
64
+ function parseStamp(stamp) {
65
+ const match = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})/.exec(String(stamp || ""));
66
+ if (!match) return null;
67
+ const [, year, month, day, hour, minute] = match.map(Number);
68
+ return new Date(year, month - 1, day, hour, minute);
69
+ }
70
+
71
+ /** Reads `--name value` options; names listed in `repeatable` collect every occurrence. */
72
+ function parseOptions(argumentList, repeatable = []) {
73
+ const options = Object.fromEntries(repeatable.map((name) => [name, []]));
74
+ const positional = [];
75
+ for (let index = 0; index < argumentList.length; index += 1) {
76
+ const argument = argumentList[index];
77
+ if (!argument.startsWith("--")) {
78
+ positional.push(argument);
79
+ continue;
80
+ }
81
+ const name = argument.slice(2);
82
+ const next = argumentList[index + 1];
83
+ const value = next === undefined || next.startsWith("--") ? true : argumentList[++index];
84
+ if (repeatable.includes(name)) options[name].push(value);
85
+ else options[name] = value;
86
+ }
87
+ return { options, positional };
88
+ }
89
+
90
+ function readProgress(folder) {
91
+ const file = progressPath(folder);
92
+ if (!existsSync(file)) throw new Error(`${file} does not exist — run "progress.mjs start" first`);
93
+ const text = readFileSync(file, "utf8");
94
+ const separator = text.indexOf("=");
95
+ if (separator < 0) throw new Error(`${file} has no "${PREFIX} =" prefix`);
96
+ return JSON.parse(text.slice(separator + 1).trim().replace(/;\s*$/, ""));
97
+ }
98
+
99
+ function writeProgress(folder, progress) {
100
+ const file = progressPath(folder);
101
+ mkdirSync(dirname(file), { recursive: true });
102
+ progress.updatedAt = localTime().stamp;
103
+ const temporary = `${file}.${process.pid}.tmp`;
104
+ writeFileSync(temporary, `${PREFIX} = ${JSON.stringify(progress, null, 2)};\n`, "utf8");
105
+ renameSync(temporary, file);
106
+ }
107
+
108
+ /** Adds a milestone and, unless the step says otherwise, the same line to the live step log. */
109
+ function addMilestone(progress, text) {
110
+ progress.activity = Array.isArray(progress.activity) ? progress.activity : [];
111
+ progress.activity.push({ at: localTime().stamp, text });
112
+ }
113
+
114
+ function setNow(progress, activity, step, source = "agent") {
115
+ const now = progress.now && typeof progress.now === "object" ? progress.now : {};
116
+ const steps = Array.isArray(now.steps) ? now.steps : [];
117
+ if (step) steps.push({ at: localTime().clock, text: step });
118
+ progress.now = { ...now, updatedAt: localTime().stamp, activity, source, steps: steps.slice(-MAXIMUM_STEPS) };
119
+ }
120
+
121
+ /** Starts a run: a fresh progress file, and a live dashboard when the slug has none that carries the panel. */
122
+ function start(folder, argumentList) {
123
+ const { options } = parseOptions(argumentList);
124
+ const mode = options.mode === "analyze" ? "analyze" : "fix";
125
+ const stamp = localTime().stamp;
126
+ const stages = STAGES.map((stage) => ({ ...stage, status: "pending", started: "", finished: "", note: "" }));
127
+ stages[0].status = "active";
128
+ stages[0].started = localTime().clock;
129
+ if (mode === "analyze") Object.assign(stages.find((stage) => stage.id === "fix"), { status: "skipped", note: "--analyze: no code changes" });
130
+ const progress = {
131
+ schema: 1,
132
+ status: "running",
133
+ title: String(options.title || `${basename(folder)} profile`),
134
+ brief: String(options.brief || ""),
135
+ project: String(options.project || ""),
136
+ url: String(options.url || ""),
137
+ mode,
138
+ startedAt: stamp,
139
+ finishedAt: "",
140
+ summary: "",
141
+ stages,
142
+ metrics: [],
143
+ fixes: [],
144
+ now: { updatedAt: stamp, activity: "Starting the profile — checking the project, the dev server and the scenario.", source: "agent", steps: [] },
145
+ activity: [],
146
+ };
147
+ addMilestone(progress, `Profile started${progress.brief ? ` — ${progress.brief}` : ""}`);
148
+ writeProgress(folder, progress);
149
+
150
+ const dashboard = join(folder, "dashboard.html");
151
+ const current = existsSync(dashboard) ? readFileSync(dashboard, "utf8") : "";
152
+ if (!current.includes(PROGRESS_MARKER)) {
153
+ // A report from before the panel existed is kept beside the data, not lost while the run replaces it.
154
+ if (current) writeFileSync(join(folder, "data", "previous-dashboard.html"), current);
155
+ writeFileSync(dashboard, livePage({ title: progress.title }));
156
+ console.log(`wrote the live page ${dashboard}${current ? " (the previous report is in data/previous-dashboard.html)" : ""}`);
157
+ }
158
+ console.log(`progress: started ${progress.title} (${mode})`);
159
+ }
160
+
161
+ function stage(folder, argumentList) {
162
+ const { options, positional } = parseOptions(argumentList);
163
+ const id = positional[0];
164
+ const status = String(options.status || "active");
165
+ if (!STAGE_STATUSES.has(status)) throw new Error(`stage status must be one of ${[...STAGE_STATUSES].join(", ")}`);
166
+ const progress = readProgress(folder);
167
+ const target = (progress.stages || []).find((candidate) => candidate.id === id);
168
+ if (!target) throw new Error(`unknown stage "${id}" — one of ${STAGES.map((candidate) => candidate.id).join(", ")}`);
169
+ const clock = localTime().clock;
170
+ if (status === "active") {
171
+ // One stage is active at a time: starting one finishes the one before it.
172
+ for (const other of progress.stages) {
173
+ if (other !== target && other.status === "active") Object.assign(other, { status: "done", finished: clock });
174
+ }
175
+ Object.assign(target, { status, started: target.started || clock, finished: "" });
176
+ progress.now = { ...(progress.now || {}), steps: [] };
177
+ setNow(progress, options.note ? String(options.note) : `${target.name} started.`, `${target.name} started`);
178
+ addMilestone(progress, `${target.name} started${options.note ? ` — ${options.note}` : ""}`);
179
+ } else {
180
+ Object.assign(target, { status, finished: status === "done" ? clock : target.finished });
181
+ addMilestone(progress, `${target.name} ${status}${options.note ? ` — ${options.note}` : ""}`);
182
+ }
183
+ if (options.note) target.note = String(options.note);
184
+ writeProgress(folder, progress);
185
+ }
186
+
187
+ function now(folder, argumentList) {
188
+ const { options, positional } = parseOptions(argumentList);
189
+ const activity = positional.join(" ").trim();
190
+ if (!activity) throw new Error('say what is happening: progress.mjs now <slug-folder> "<sentence>"');
191
+ const progress = readProgress(folder);
192
+ setNow(progress, activity, options.step ? String(options.step) : activity);
193
+ writeProgress(folder, progress);
194
+ }
195
+
196
+ function fix(folder, argumentList) {
197
+ const { options, positional } = parseOptions(argumentList);
198
+ const id = positional[0];
199
+ if (!id) throw new Error("name the fix: progress.mjs fix <slug-folder> F1 …");
200
+ if (options.status && !FIX_STATUSES.has(options.status)) throw new Error(`fix status must be one of ${[...FIX_STATUSES].join(", ")}`);
201
+ const progress = readProgress(folder);
202
+ progress.fixes = Array.isArray(progress.fixes) ? progress.fixes : [];
203
+ let entry = progress.fixes.find((candidate) => candidate.id === id);
204
+ if (!entry) {
205
+ entry = { id, title: "", status: "planned", before: "", after: "", note: "" };
206
+ progress.fixes.push(entry);
207
+ }
208
+ const previousStatus = entry.status;
209
+ for (const field of ["title", "status", "before", "after", "note"]) if (options[field] !== undefined && options[field] !== true) entry[field] = String(options[field]);
210
+ if (entry.status !== previousStatus || !previousStatus) {
211
+ const line = `${id} ${entry.status}: ${entry.title}${entry.before || entry.after ? ` (${entry.before || "–"} → ${entry.after || "…"})` : ""}`;
212
+ addMilestone(progress, line);
213
+ setNow(progress, progress.now && progress.now.activity ? progress.now.activity : line, line);
214
+ }
215
+ writeProgress(folder, progress);
216
+ }
217
+
218
+ function metric(folder, argumentList) {
219
+ const { options, positional } = parseOptions(argumentList);
220
+ const [label, value] = positional;
221
+ if (!label || value === undefined) throw new Error('progress.mjs metric <slug-folder> "<label>" "<value>" [--note "…"]');
222
+ const progress = readProgress(folder);
223
+ progress.metrics = Array.isArray(progress.metrics) ? progress.metrics : [];
224
+ const entry = progress.metrics.find((candidate) => candidate.label === label);
225
+ const note = options.note && options.note !== true ? String(options.note) : entry ? entry.note : "";
226
+ if (entry) Object.assign(entry, { value: String(value), note });
227
+ else progress.metrics.push({ label, value: String(value), note });
228
+ writeProgress(folder, progress);
229
+ }
230
+
231
+ function note(folder, argumentList) {
232
+ const text = argumentList.join(" ").trim();
233
+ if (!text) throw new Error('progress.mjs note <slug-folder> "<milestone>"');
234
+ const progress = readProgress(folder);
235
+ addMilestone(progress, text);
236
+ writeProgress(folder, progress);
237
+ }
238
+
239
+ function end(folder, argumentList) {
240
+ const { options } = parseOptions(argumentList);
241
+ const status = String(options.status || "done");
242
+ if (!END_STATUSES.has(status)) throw new Error(`end status must be one of ${[...END_STATUSES].join(", ")}`);
243
+ const progress = readProgress(folder);
244
+ const clock = localTime().clock;
245
+ for (const candidate of progress.stages || []) {
246
+ if (candidate.status === "active" && status === "done") Object.assign(candidate, { status: "done", finished: clock });
247
+ }
248
+ Object.assign(progress, { status, finishedAt: localTime().stamp, summary: options.summary && options.summary !== true ? String(options.summary) : progress.summary });
249
+ setNow(progress, status === "done" ? "Finished — the report is written." : `Ended (${status}).`, `Run ${status}`);
250
+ addMilestone(progress, `Profile ${status}${progress.summary ? ` — ${progress.summary}` : ""}`);
251
+ writeProgress(folder, progress);
252
+ }
253
+
254
+ function check(folder) {
255
+ const progress = readProgress(folder);
256
+ const problems = [];
257
+ for (const field of ["stages", "metrics", "fixes", "activity"]) if (!Array.isArray(progress[field])) problems.push(`${field} is not a list`);
258
+ if (!progress.now || typeof progress.now !== "object") problems.push("now is not an object");
259
+ else if (!Array.isArray(progress.now.steps)) problems.push("now.steps is not a list");
260
+ if (problems.length) throw new Error(problems.join("; "));
261
+ console.log(`progress.js is valid — ${progress.status}, ${progress.fixes.length} fixes, ${progress.activity.length} milestones`);
262
+ }
263
+
264
+ /* ===================== Watchdog ===================== */
265
+
266
+ /** The most recently changed file under some folders, skipping dependency, build and cache folders. */
267
+ function latestChange(roots) {
268
+ let latest = null;
269
+ const visit = (folder, depth) => {
270
+ let entries;
271
+ try {
272
+ entries = readdirSync(folder, { withFileTypes: true });
273
+ } catch {
274
+ return;
275
+ }
276
+ for (const entry of entries) {
277
+ const path = join(folder, entry.name);
278
+ if (entry.isDirectory()) {
279
+ if (depth < MAXIMUM_SCAN_DEPTH && !IGNORED_FOLDERS.has(entry.name)) visit(path, depth + 1);
280
+ continue;
281
+ }
282
+ // The progress file and the page are written by the agent and the watchdog — not a sign of work.
283
+ if (!entry.isFile() || entry.name.endsWith(".tmp") || entry.name === "progress.js" || entry.name === "dashboard.html") continue;
284
+ try {
285
+ const modified = statSync(path).mtimeMs;
286
+ if (!latest || modified > latest.modified) latest = { path, modified };
287
+ } catch {
288
+ /* the file vanished between listing and stat */
289
+ }
290
+ }
291
+ };
292
+ roots.forEach((root) => visit(root, 0));
293
+ return latest;
294
+ }
295
+
296
+ /** The last meaningful line of the newest capture log — what profile.mjs or analyze.mjs is doing right now. */
297
+ function latestLogLine(folder) {
298
+ const logs = join(folder, "data", "logs");
299
+ let newest = null;
300
+ try {
301
+ for (const name of readdirSync(logs)) {
302
+ const path = join(logs, name);
303
+ const modified = statSync(path).mtimeMs;
304
+ if (!newest || modified > newest.modified) newest = { path, name, modified };
305
+ }
306
+ } catch {
307
+ return null;
308
+ }
309
+ if (!newest) return null;
310
+ const lines = readFileSync(newest.path, "utf8").split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
311
+ const line = lines.pop();
312
+ return line ? { log: newest.name, line: line.length > 160 ? `${line.slice(0, 157)}…` : line } : null;
313
+ }
314
+
315
+ /**
316
+ * The watchdog. While the run is in progress it checks every interval; when the agent has written nothing for
317
+ * `quiet-minutes` it writes a heartbeat naming the newest file and the newest capture log's last line, and when no
318
+ * file has changed for `stall-minutes` either, it says the run may be stalled. It exits when the run ends, or
319
+ * after `max-hours` (a killed run leaves the status at running, and the watchdog must not outlive it forever).
320
+ */
321
+ async function watch(folder, argumentList) {
322
+ const { options } = parseOptions(argumentList, ["watch"]);
323
+ const intervalSeconds = Number(options["interval-seconds"] || 60);
324
+ const quietMinutes = Number(options["quiet-minutes"] || 5);
325
+ const stallMinutes = Number(options["stall-minutes"] || 30);
326
+ const stopAt = Date.now() + Number(options["max-hours"] || 12) * 3600000;
327
+ const roots = [folder, ...options.watch.map(String)];
328
+ console.log(`watchdog: watching ${roots.join(", ")} every ${intervalSeconds} s (quiet after ${quietMinutes} min, stalled after ${stallMinutes} min)`);
329
+ for (;;) {
330
+ if (Date.now() > stopAt) return console.log("watchdog: reached its maximum lifetime — exiting");
331
+ let progress = null;
332
+ try {
333
+ progress = readProgress(folder);
334
+ } catch {
335
+ /* caught mid-write or briefly missing — try again next round */
336
+ }
337
+ if (progress && progress.status !== "running") return console.log(`watchdog: the run is ${progress.status} — exiting`);
338
+ if (progress) {
339
+ try {
340
+ heartbeat(folder, progress, roots, quietMinutes, stallMinutes);
341
+ } catch (error) {
342
+ console.log(`watchdog: skipped a round — ${error.message}`);
343
+ }
344
+ }
345
+ await new Promise((resolve) => setTimeout(resolve, intervalSeconds * 1000));
346
+ }
347
+ }
348
+
349
+ function heartbeat(folder, progress, roots, quietMinutes, stallMinutes) {
350
+ const moment = new Date();
351
+ const lastWrite = parseStamp(progress.now && progress.now.updatedAt);
352
+ const quietFor = lastWrite ? Math.floor((moment - lastWrite) / 60000) : Infinity;
353
+ if (quietFor < quietMinutes) return;
354
+ const change = latestChange(roots);
355
+ const changedAgo = change ? Math.floor((moment - change.modified) / 60000) : Infinity;
356
+ const where = change ? `${relative(folder, change.path) || change.path} at ${localTime(new Date(change.modified)).clock}` : "no file changes found";
357
+ const log = latestLogLine(folder);
358
+ const logText = log ? ` — ${log.log}: "${log.line}"` : "";
359
+ const activeStage = (progress.stages || []).find((candidate) => candidate.status === "active");
360
+ let activity;
361
+ let step;
362
+ if (changedAgo >= stallMinutes) {
363
+ 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.`;
364
+ step = `Watchdog: possible stall — last change: ${where}`;
365
+ } else {
366
+ activity = `Still ${(activeStage && STAGE_DOING[activeStage.id]) || "working"} — no update from the agent for ${quietFor} min; latest: ${where}${logText}.`;
367
+ step = `Watchdog: still working — ${where}`;
368
+ }
369
+ setNow(progress, activity, step, "watchdog");
370
+ writeProgress(folder, progress);
371
+ console.log(`watchdog ${localTime(moment).clock}: ${activity}`);
372
+ }
373
+
374
+ const commands = { start, stage, now, fix, metric, note, end, check, watch };
375
+
376
+ if (!commands[command] || !slugFolder) {
377
+ console.error("usage: node progress.mjs <start|stage|now|fix|metric|note|end|check|watch> <slug-folder> [options] — see the header of this file");
378
+ process.exit(2);
379
+ }
380
+ try {
381
+ await commands[command](slugFolder, rest);
382
+ } catch (error) {
383
+ console.error(`progress.mjs ${command}: ${error.message}`);
384
+ process.exit(1);
385
+ }