@babylonjs-toolkit/agent 1.1.68 → 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.
- package/README.md +2 -2
- package/package.json +1 -1
- package/skills/bt-design/SKILL.md +7 -0
- package/skills/bt-design/templates/3d-hero-scroll/hero-scroll.js +27 -9
- package/skills/bt-execute/SKILL.md +2 -2
- package/skills/bt-gauntlet/references/critic-rubrics.md +1 -0
- package/skills/bt-plan/SKILL.md +1 -1
- package/skills/bt-profile/SKILL.md +77 -34
- package/skills/bt-profile/scripts/analyze.mjs +67 -15
- package/skills/bt-profile/scripts/lib/chrome.mjs +22 -0
- package/skills/bt-profile/scripts/lib/probe.mjs +117 -2
- package/skills/bt-profile/scripts/lib/progress-panel.mjs +103 -7
- package/skills/bt-profile/scripts/profile.mjs +89 -40
- package/skills/bt-profile/scripts/progress.mjs +141 -10
- package/skills/bt-profile/scripts/report.mjs +203 -11
- package/skills/bt-profile/templates/scenario.template.mjs +28 -19
- package/skills/bt-prototype/SKILL.md +1 -1
|
@@ -17,14 +17,22 @@
|
|
|
17
17
|
* Usage (from `.agents/profile/<slug>/data`, whose profile.config.json supplies the defaults for --url and --scenario):
|
|
18
18
|
* node ../../.tools/profile.mjs --out runs/baseline [--url http://localhost:5173/play] [--scenario scenario.mjs]
|
|
19
19
|
* [--seconds 150] [--dpr 2] [--width 1600] [--height 900] [--headed true] [--interval 250] [--warm true]
|
|
20
|
-
* [--trace true] [--uncapped true] [--heap false] [--snapshots true] [--filmstrip-interval 1] [--autoplay gesture] [--
|
|
20
|
+
* [--trace true] [--uncapped true] [--heap false] [--snapshots true] [--filmstrip-interval 1] [--autoplay gesture] [--watch true]
|
|
21
|
+
* [--gpu-cold true] [--args key=value,key2=value2]
|
|
22
|
+
*
|
|
23
|
+
* `--gpu-cold true` makes every fragment shader unique to the load, so the GPU compiles every pipeline as on a first visit
|
|
24
|
+
* (a fresh Chrome profile alone does not: macOS keeps compiled Metal pipelines in a system cache outside it).
|
|
25
|
+
*
|
|
26
|
+
* A scenario that fails or runs past --seconds still ends the capture: every step after it has a time limit, and the run
|
|
27
|
+
* folder gets `shots/failed.png` plus the page's address, title and console errors in the log.
|
|
21
28
|
*/
|
|
22
29
|
import fs from "node:fs";
|
|
23
30
|
import os from "node:os";
|
|
24
31
|
import path from "node:path";
|
|
25
32
|
import { pathToFileURL } from "node:url";
|
|
26
33
|
import puppeteer from "puppeteer-core";
|
|
27
|
-
import { installProbe } from "./lib/probe.mjs";
|
|
34
|
+
import { installProbe, installGpuCold } from "./lib/probe.mjs";
|
|
35
|
+
import { findChrome } from "./lib/chrome.mjs";
|
|
28
36
|
|
|
29
37
|
/** Default sampling interval of the CPU profiler, in microseconds (DevTools uses 100–1000). */
|
|
30
38
|
const DEFAULT_SAMPLING_INTERVAL_US = 250;
|
|
@@ -70,29 +78,29 @@ function parseScenarioArguments(text) {
|
|
|
70
78
|
return options;
|
|
71
79
|
}
|
|
72
80
|
|
|
81
|
+
/** Pauses for the given number of seconds. */
|
|
82
|
+
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
83
|
+
|
|
73
84
|
/**
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
* @
|
|
85
|
+
* Waits for a DevTools call at most `seconds`. The browser has no per-call timeout (a scenario may wait minutes), so every
|
|
86
|
+
* step after the scenario uses this: a stuck page must never keep the capture from finishing.
|
|
87
|
+
* @returns {Promise<*>} the call's result, or `fallback` when it fails or takes too long
|
|
77
88
|
*/
|
|
78
|
-
function
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
throw new Error("No Chrome found. Set CHROME_PATH to a Chrome or Chromium executable.");
|
|
89
|
+
async function limit(promise, seconds, fallback, log, what) {
|
|
90
|
+
let timer;
|
|
91
|
+
const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(limit.TIMED_OUT), seconds * 1000); });
|
|
92
|
+
try {
|
|
93
|
+
const result = await Promise.race([promise, timeout]);
|
|
94
|
+
if (result === limit.TIMED_OUT) { log(`${what}: no answer within ${seconds} s — skipped`); return fallback; }
|
|
95
|
+
return result;
|
|
96
|
+
} catch (error) {
|
|
97
|
+
log(`${what}: ${String(error && error.message ? error.message : error).split("\n")[0]}`);
|
|
98
|
+
return fallback;
|
|
99
|
+
} finally {
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
}
|
|
92
102
|
}
|
|
93
|
-
|
|
94
|
-
/** Pauses for the given number of seconds. */
|
|
95
|
-
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
103
|
+
limit.TIMED_OUT = Symbol("timed out");
|
|
96
104
|
|
|
97
105
|
/**
|
|
98
106
|
* Runs the sync marker in the page: a named function that busy-waits a few milliseconds. Its first sample in the CPU
|
|
@@ -191,9 +199,10 @@ function createScenarioContext(page, targetUrl, shotsDir, options, log, snapshot
|
|
|
191
199
|
/** Waits until a page function returns truthy (polls every 100 ms). */
|
|
192
200
|
waitFor: (pageFunction, { timeout = 600000, polling = 100, args = [] } = {}) =>
|
|
193
201
|
page.waitForFunction(pageFunction, { timeout, polling }, ...args),
|
|
194
|
-
/** Waits until the
|
|
202
|
+
/** Waits until the page has rendered at least `count` frames (Babylon frames on a Babylon page, else browser frames). */
|
|
195
203
|
waitForFrames: (count = 10, timeout = 600000) =>
|
|
196
|
-
|
|
204
|
+
// Babylon frames on a Babylon page; the browser's own frames on any other page
|
|
205
|
+
page.waitForFunction((minimum) => window.__btProfile && (window.BABYLON ? window.__btProfile.frames.length : window.__btProfile.rafFrames.length) >= minimum, { timeout, polling: 100 }, count),
|
|
197
206
|
evaluate: (pageFunction, ...args) => page.evaluate(pageFunction, ...args),
|
|
198
207
|
keyDown: (key) => page.keyboard.down(key),
|
|
199
208
|
keyUp: (key) => page.keyboard.up(key),
|
|
@@ -365,6 +374,11 @@ async function captureOnce(browser, flags, scenario, runDir, label) {
|
|
|
365
374
|
// Document loads only: a router's history.pushState / replaceState is a same-document "navigation" and is not a reload.
|
|
366
375
|
page.on("domcontentloaded", () => navigations.push({ at: Date.now(), url: page.url() }));
|
|
367
376
|
page.on("pageerror", (error) => consoleErrors.push({ type: "pageerror", text: String(error).slice(0, 600) }));
|
|
377
|
+
// A document that fails to load (a bad response, a decoding error) shows a white page and no console line of its own.
|
|
378
|
+
page.on("requestfailed", (request) => {
|
|
379
|
+
if (request.resourceType() === "document" || request.resourceType() === "script") consoleErrors.push({ type: "requestfailed", text: `${request.resourceType()} ${request.url().slice(0, 300)} — ${request.failure() ? request.failure().errorText : "failed"}` });
|
|
380
|
+
});
|
|
381
|
+
if (flags["gpu-cold"] === "true") await page.evaluateOnNewDocument(installGpuCold);
|
|
368
382
|
await page.evaluateOnNewDocument(installProbe);
|
|
369
383
|
|
|
370
384
|
// Start on a same-origin document so the renderer process (and the V8 isolate the profiler is attached to)
|
|
@@ -412,24 +426,35 @@ async function captureOnce(browser, flags, scenario, runDir, label) {
|
|
|
412
426
|
log(`scenario failed: ${scenarioError.split("\n")[0]}`);
|
|
413
427
|
}
|
|
414
428
|
if (timedOut) log(`scenario still running after --seconds ${maxSeconds}; stopping the capture there`);
|
|
415
|
-
|
|
429
|
+
// From here on the page may be stuck (a failed load, a hung game): every call has a time limit.
|
|
430
|
+
await limit(context.mark("end"), 10, null, log, "mark end");
|
|
416
431
|
|
|
417
|
-
const filmstrip = stopFilmstrip ? await stopFilmstrip() : [];
|
|
418
|
-
const
|
|
432
|
+
const filmstrip = stopFilmstrip ? await limit(stopFilmstrip(), 15, [], log, "filmstrip") : [];
|
|
433
|
+
const stopped = await limit(session.send("Profiler.stop"), 120, null, log, "CPU profile");
|
|
434
|
+
const profile = stopped ? stopped.profile : { nodes: [], samples: [], timeDeltas: [], startTime: 0, endTime: 0 };
|
|
419
435
|
fs.writeFileSync(path.join(runDir, "cpu.cpuprofile"), JSON.stringify(profile));
|
|
420
|
-
if (heapEnabled && heapPhase !== "end") await rotateHeap("end");
|
|
421
|
-
if (stopTrace) await stopTrace();
|
|
422
|
-
const probe = await page.evaluate(() => (window.__btProfile ? window.__btProfile.dump() : null));
|
|
436
|
+
if (heapEnabled && heapPhase !== "end") await limit(rotateHeap("end"), 60, null, log, "allocation profile");
|
|
437
|
+
if (stopTrace) await limit(stopTrace(), 180, null, log, "trace");
|
|
438
|
+
const probe = await limit(page.evaluate(() => (window.__btProfile ? window.__btProfile.dump() : null)), 30, null, log, "probe");
|
|
423
439
|
if (probe) {
|
|
424
440
|
const recorded = new Set(probe.marks.map((mark) => mark.name));
|
|
425
441
|
for (const mark of context.nodeMarks) if (!recorded.has(mark.name)) probe.marks.push({ ...mark, fromNode: true });
|
|
426
442
|
probe.marks.sort((first, second) => first.at - second.at);
|
|
427
443
|
}
|
|
428
|
-
const census = await page.evaluate(() => (window.__btProfile ? window.__btProfile.census() : null))
|
|
429
|
-
if (snapshots) await page.screenshot({ path: path.join(shotsDir, "end.png") })
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
444
|
+
const census = await limit(page.evaluate(() => (window.__btProfile ? window.__btProfile.census() : null)), 20, null, log, "census");
|
|
445
|
+
if (snapshots) await limit(page.screenshot({ path: path.join(shotsDir, "end.png") }), 20, null, log, "end screenshot");
|
|
446
|
+
// A failed or overrun scenario leaves the evidence behind: what the page showed, where it was, what it complained about.
|
|
447
|
+
if (scenarioError || timedOut) {
|
|
448
|
+
const failedShot = path.join(shotsDir, "failed.png");
|
|
449
|
+
const shot = await limit(page.screenshot({ path: failedShot }), 20, null, log, "failure screenshot");
|
|
450
|
+
const where = await limit(page.evaluate(() => ({ url: location.href, title: document.title, text: (document.body ? document.body.innerText : "").trim().slice(0, 300) })), 10, null, log, "page state");
|
|
451
|
+
log(`failure evidence: ${shot ? "shots/failed.png" : "no screenshot"} · page ${where ? `${where.url} "${where.title}" · text: ${JSON.stringify(where.text) || "(none)"}` : "not answering"}`);
|
|
452
|
+
for (const entry of consoleErrors.slice(-12)) log(` console ${entry.type}: ${entry.text.split("\n")[0].slice(0, 240)}`);
|
|
453
|
+
if (consoleErrors.length === 0) log(" console: no errors or warnings");
|
|
454
|
+
}
|
|
455
|
+
const scripts = stopped ? await limit(saveProfiledScripts(session, profile, scriptsDir), 300, [], log, "saving scripts") : [];
|
|
456
|
+
await limit(session.detach(), 10, null, log, "detach");
|
|
457
|
+
await limit(page.close(), 15, null, log, "closing the page");
|
|
433
458
|
|
|
434
459
|
const capture = {
|
|
435
460
|
label,
|
|
@@ -445,6 +470,7 @@ async function captureOnce(browser, flags, scenario, runDir, label) {
|
|
|
445
470
|
samplingIntervalUs: Number(flags.interval || DEFAULT_SAMPLING_INTERVAL_US),
|
|
446
471
|
heapIncludesCollected,
|
|
447
472
|
snapshots,
|
|
473
|
+
gpuCold: flags["gpu-cold"] === "true" ? (probe && probe.gpuCold) || { tagged: 0, untagged: 0 } : null,
|
|
448
474
|
filmstripFrames: filmstrip.length,
|
|
449
475
|
sync: { markerName: SYNC_MARKER_NAME, epochMs: syncEpochMs },
|
|
450
476
|
census,
|
|
@@ -456,7 +482,9 @@ async function captureOnce(browser, flags, scenario, runDir, label) {
|
|
|
456
482
|
};
|
|
457
483
|
fs.writeFileSync(path.join(runDir, "capture.json"), JSON.stringify(capture));
|
|
458
484
|
if (capture.disturbed) log(`WARNING: ${capture.disturbed.reason} — this capture is not comparable; profile a server with file watching off (SKILL.md › Other sessions)`);
|
|
459
|
-
log(`
|
|
485
|
+
if (capture.gpuCold) log(`gpu-cold: ${capture.gpuCold.tagged} fragment shader(s) made unique${capture.gpuCold.untagged ? `, ${capture.gpuCold.untagged} left as they were (no fragment entry found)` : ""}`);
|
|
486
|
+
const compiles = probe && probe.gpuCompiles ? probe.gpuCompiles.filter((entry) => entry.kind !== "shaderModule").length : 0;
|
|
487
|
+
log(`done: ${probe ? probe.frames.length : 0} frames, ${profile.samples.length} CPU samples, ${scripts.length} scripts, ${compiles} pipelines / programs created, engine ${probe && probe.engine}`);
|
|
460
488
|
return capture;
|
|
461
489
|
}
|
|
462
490
|
|
|
@@ -488,12 +516,31 @@ async function main() {
|
|
|
488
516
|
if (flags.autoplay !== "gesture") args.push("--autoplay-policy=no-user-gesture-required");
|
|
489
517
|
if (flags.uncapped === "true") args.push("--disable-frame-rate-limit", "--disable-gpu-vsync");
|
|
490
518
|
const browser = await puppeteer.launch({
|
|
519
|
+
// No 180 s cap on one DevTools call: a scenario may wait minutes (a slow load, a user who drives the run).
|
|
520
|
+
protocolTimeout: 0,
|
|
491
521
|
executablePath: findChrome(),
|
|
492
|
-
|
|
522
|
+
// --watch true (or --headed true): a visible window the user can watch while the profile runs
|
|
523
|
+
headless: (flags.headed === "true" || flags.watch === "true") ? false : "new",
|
|
493
524
|
defaultViewport: null,
|
|
494
525
|
userDataDir,
|
|
495
526
|
args,
|
|
496
527
|
});
|
|
528
|
+
// The lock names this capture's process and its Chrome, so `progress.mjs stop` (/bt-profile --stop) can end both. It
|
|
529
|
+
// lives in the slug's data folder (the working folder of every capture), and goes when the capture ends.
|
|
530
|
+
const lockPath = fs.existsSync("profile.config.json") ? path.resolve("capture.lock.json") : path.join(runDir, "capture.lock.json");
|
|
531
|
+
const browserProcess = typeof browser.process === "function" ? browser.process() : null;
|
|
532
|
+
fs.writeFileSync(lockPath, JSON.stringify({ pid: process.pid, browserPid: browserProcess ? browserProcess.pid : null, out: runDir, startedAt: new Date().toISOString() }, null, 2));
|
|
533
|
+
const removeLock = () => { try { fs.rmSync(lockPath, { force: true }); } catch { /* already gone */ } };
|
|
534
|
+
process.on("exit", removeLock);
|
|
535
|
+
const removeProfile = () => { try { fs.rmSync(userDataDir, { recursive: true, force: true }); } catch { /* Chrome still letting go */ } };
|
|
536
|
+
for (const signal of ["SIGTERM", "SIGINT"]) {
|
|
537
|
+
process.on(signal, () => {
|
|
538
|
+
removeLock();
|
|
539
|
+
try { browser.process()?.kill("SIGKILL"); } catch { /* gone */ }
|
|
540
|
+
removeProfile();
|
|
541
|
+
process.exit(130);
|
|
542
|
+
});
|
|
543
|
+
}
|
|
497
544
|
try {
|
|
498
545
|
const cold = await captureOnce(browser, flags, scenario, path.join(runDir, "cold"), "cold");
|
|
499
546
|
const summary = { runDir, cold: path.join(runDir, "cold") };
|
|
@@ -501,13 +548,15 @@ async function main() {
|
|
|
501
548
|
await captureOnce(browser, flags, scenario, path.join(runDir, "warm"), "warm");
|
|
502
549
|
summary.warm = path.join(runDir, "warm");
|
|
503
550
|
}
|
|
504
|
-
if (cold.
|
|
551
|
+
if (cold.scenarioError || cold.timedOut) process.stderr.write("WARNING: the scenario did not finish — this capture shows the failure, not the moment; see the failure evidence above.\n");
|
|
552
|
+
else if (cold.probe && cold.probe.engine == null) process.stderr.write("note: no Babylon engine on this page — frames are browser frames (requestAnimationFrame): FPS and frame gaps, no draw calls or engine timers.\n");
|
|
505
553
|
if (cold.census && /swiftshader|llvmpipe|software/i.test(cold.census.adapter || "")) process.stderr.write("WARNING: Chrome rendered with a software adapter — GPU numbers are not representative.\n");
|
|
506
554
|
fs.writeFileSync(path.join(runDir, "run.json"), JSON.stringify({ ...summary, flags, scenario: scenario.meta }, null, 2));
|
|
507
555
|
process.stdout.write(JSON.stringify(summary) + "\n");
|
|
508
556
|
} finally {
|
|
509
|
-
await browser.close();
|
|
510
|
-
|
|
557
|
+
const closed = await limit(browser.close(), 20, null, (message) => process.stderr.write(`[bt-profile] ${message}\n`), "closing Chrome");
|
|
558
|
+
if (closed === null) try { browser.process()?.kill("SIGKILL"); } catch { /* gone */ }
|
|
559
|
+
removeProfile();
|
|
511
560
|
}
|
|
512
561
|
}
|
|
513
562
|
|
|
@@ -6,22 +6,27 @@
|
|
|
6
6
|
* Every write reads `data/progress.js`, parses its strict JSON, changes it and writes it back atomically (a temp file
|
|
7
7
|
* renamed over the original), so the page never loads a half-written file.
|
|
8
8
|
*
|
|
9
|
-
* node progress.mjs start <slug-folder> [--title "…"] [--brief "…"] [--project <path>] [--url <url>] [--mode fix
|
|
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
|
|
10
11
|
* node progress.mjs stage <slug-folder> <preflight|baseline|diagnose|fix|verify|report> [--status active|done|skipped] [--note "…"]
|
|
11
12
|
* node progress.mjs now <slug-folder> "<what is happening this minute>" [--step "<log line, if different>"]
|
|
12
13
|
* node progress.mjs fix <slug-folder> <F1> [--title "…"] [--status planned|trying|measuring|kept|reverted|skipped] [--before "…"] [--after "…"] [--note "…"]
|
|
13
14
|
* node progress.mjs metric <slug-folder> "<label>" "<value>" [--note "…"]
|
|
14
15
|
* node progress.mjs note <slug-folder> "<milestone>"
|
|
15
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
|
|
16
20
|
* node progress.mjs check <slug-folder>
|
|
17
21
|
* node progress.mjs watch <slug-folder> [--watch <folder>]… [--interval-seconds 60] [--quiet-minutes 5] [--stall-minutes 30] [--max-hours 12]
|
|
18
22
|
*
|
|
19
23
|
* <slug-folder> is .agents/profile/<slug> (it holds dashboard.html and data/). Timestamps are this machine's local time.
|
|
20
24
|
*/
|
|
21
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
25
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
22
26
|
import { basename, dirname, join, relative } from "node:path";
|
|
27
|
+
import { spawn } from "node:child_process";
|
|
23
28
|
|
|
24
|
-
import { PROGRESS_MARKER, livePage } from "./lib/progress-panel.mjs";
|
|
29
|
+
import { PROGRESS_MARKER, livePage, withProgressPanel } from "./lib/progress-panel.mjs";
|
|
25
30
|
|
|
26
31
|
const PREFIX = "window.PROFILE_PROGRESS";
|
|
27
32
|
/** The stages every profile run goes through, in order. */
|
|
@@ -121,15 +126,21 @@ function setNow(progress, activity, step, source = "agent") {
|
|
|
121
126
|
/** Starts a run: a fresh progress file, and a live dashboard when the slug has none that carries the panel. */
|
|
122
127
|
function start(folder, argumentList) {
|
|
123
128
|
const { options } = parseOptions(argumentList);
|
|
124
|
-
|
|
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";
|
|
125
131
|
const stamp = localTime().stamp;
|
|
126
132
|
const stages = STAGES.map((stage) => ({ ...stage, status: "pending", started: "", finished: "", note: "" }));
|
|
127
133
|
stages[0].status = "active";
|
|
128
134
|
stages[0].started = localTime().clock;
|
|
129
|
-
if (mode === "
|
|
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
|
+
}
|
|
130
139
|
const progress = {
|
|
131
140
|
schema: 1,
|
|
132
141
|
status: "running",
|
|
142
|
+
slug: basename(folder),
|
|
143
|
+
run: Number(options.run || 1),
|
|
133
144
|
title: String(options.title || `${basename(folder)} profile`),
|
|
134
145
|
brief: String(options.brief || ""),
|
|
135
146
|
project: String(options.project || ""),
|
|
@@ -150,12 +161,38 @@ function start(folder, argumentList) {
|
|
|
150
161
|
const dashboard = join(folder, "dashboard.html");
|
|
151
162
|
const current = existsSync(dashboard) ? readFileSync(dashboard, "utf8") : "";
|
|
152
163
|
if (!current.includes(PROGRESS_MARKER)) {
|
|
153
|
-
//
|
|
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;
|
|
154
167
|
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)" : ""}`);
|
|
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)" : ""}`);
|
|
157
170
|
}
|
|
158
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);
|
|
159
196
|
}
|
|
160
197
|
|
|
161
198
|
function stage(folder, argumentList) {
|
|
@@ -371,10 +408,104 @@ function heartbeat(folder, progress, roots, quietMinutes, stallMinutes) {
|
|
|
371
408
|
console.log(`watchdog ${localTime(moment).clock}: ${activity}`);
|
|
372
409
|
}
|
|
373
410
|
|
|
374
|
-
|
|
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 };
|
|
375
506
|
|
|
376
507
|
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");
|
|
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");
|
|
378
509
|
process.exit(2);
|
|
379
510
|
}
|
|
380
511
|
try {
|