@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,735 @@
1
+ /**
2
+ * bt-profile analysis: reads one capture folder (written by profile.mjs) and works out where the time goes —
3
+ * per phase of the scenario, per second, per function and per owner — and, most importantly, which of YOUR
4
+ * functions is responsible for it, including the library work they trigger (a `scene.pick` called from your
5
+ * update loop is charged to your update loop).
6
+ *
7
+ * Writes analysis.json next to the capture and prints a plain-text summary for the agent.
8
+ *
9
+ * Usage:
10
+ * node analyze.mjs --capture runs/<run>/cold [--config profile.config.json] [--project /abs/project] [--top 25]
11
+ * (run from `.agents/profile/<slug>/data`; the config is found by walking up from the capture)
12
+ */
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import { createSymbolizer } from "./lib/symbolize.mjs";
16
+
17
+ /** Frame budget used for "slow frame" counts, in milliseconds (60 FPS). */
18
+ const FRAME_BUDGET_MS = 1000 / 60;
19
+ /** Width of the timeline buckets, in seconds. */
20
+ const BUCKET_SECONDS = 1;
21
+ /** Lines shown around a function in a code excerpt. */
22
+ const EXCERPT_LINES_BEFORE = 2;
23
+ const EXCERPT_LINES_AFTER = 28;
24
+ /**
25
+ * Engine entry points that run a whole frame. Work beneath them belongs to the engine's frame (or to the deeper
26
+ * code of yours that it calls back — component updates, observers), not to the render-loop callback that started it.
27
+ */
28
+ const FRAME_DRIVERS = /^(Scene\.render|Scene\._renderFrame|AbstractEngine\._renderLoop|AbstractEngine\._processFrame|AbstractEngine\._renderFrame|(Abstract)?Engine\.runRenderLoop|.*_boundRenderFunction)$/;
29
+ /** Time before the first phase mark shorter than this joins the first phase (ms). */
30
+ const MIN_LEAD_IN_PHASE_MS = 1500;
31
+ /** Inclusive entries above this share of busy time are frame shells (render loop wrappers), not causes. */
32
+ const SHELL_PCT = 75;
33
+
34
+ /**
35
+ * Reads `--name value` pairs from the command line.
36
+ * @param {string[]} argv - process.argv.slice(2)
37
+ * @returns {Record<string, string>} the parsed flags
38
+ */
39
+ function parseArguments(argv) {
40
+ const flags = {};
41
+ for (let i = 0; i < argv.length; i += 2) flags[argv[i].replace(/^--/, "")] = argv[i + 1];
42
+ return flags;
43
+ }
44
+
45
+ /** Rounds to the given number of decimals. */
46
+ const round = (value, decimals = 1) => (value == null || Number.isNaN(value) ? null : +value.toFixed(decimals));
47
+
48
+ /** Percentile of an already sorted array. */
49
+ const percentile = (sorted, fraction) => (sorted.length === 0 ? null : sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * fraction))]);
50
+
51
+ /**
52
+ * Loads the slug's config (`.agents/profile/<slug>/data/profile.config.json`, the nearest one above the capture).
53
+ * @returns {{projectRoot: string, owners: object[]}} the config with an absolute project root
54
+ */
55
+ function loadConfig(flags, captureDir) {
56
+ const configPath = flags.config ? path.resolve(flags.config) : findUp(captureDir, "profile.config.json");
57
+ const config = configPath && fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, "utf8")) : {};
58
+ const configDir = configPath ? path.dirname(configPath) : captureDir;
59
+ const projectRoot = flags.project ? path.resolve(flags.project)
60
+ : config.projectRoot ? path.resolve(configDir, config.projectRoot) : projectRootAbove(configDir);
61
+ return { ...config, projectRoot, owners: config.owners || [], configPath };
62
+ }
63
+
64
+ /** The project that holds a folder inside its `.agents/`: the parent of the nearest `.agents` above it (else the folder). */
65
+ function projectRootAbove(dir) {
66
+ for (let current = path.resolve(dir); path.dirname(current) !== current; current = path.dirname(current)) {
67
+ if (path.basename(current) === ".agents") return path.dirname(current);
68
+ }
69
+ return path.resolve(dir);
70
+ }
71
+
72
+ /** Walks up from a folder looking for a relative path; returns the first match or null. */
73
+ function findUp(startDir, relative) {
74
+ let directory = startDir;
75
+ for (;;) {
76
+ const candidate = path.join(directory, relative);
77
+ if (fs.existsSync(candidate)) return candidate;
78
+ const parent = path.dirname(directory);
79
+ if (parent === directory) return null;
80
+ directory = parent;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Prepares the CPU profile: parent links, each sample's epoch time (synced to the page clock through the sync
86
+ * marker) and duration.
87
+ * @returns {{byId: Map, sampleNodes: number[], sampleTimes: Float64Array, sampleWeights: Float64Array}}
88
+ */
89
+ function prepareProfile(profile, sync) {
90
+ const byId = new Map(profile.nodes.map((node) => [node.id, node]));
91
+ for (const node of profile.nodes) for (const child of node.children || []) byId.get(child).parent = node.id;
92
+ const count = profile.samples.length;
93
+ const timestampsUs = new Float64Array(count);
94
+ let time = profile.startTime;
95
+ for (let i = 0; i < count; i++) { time += profile.timeDeltas[i] || 0; timestampsUs[i] = time; }
96
+ const markerIds = new Set(profile.nodes.filter((node) => node.callFrame.functionName === sync.markerName).map((node) => node.id));
97
+ let offsetMs = null;
98
+ for (let i = 0; i < count; i++) {
99
+ if (markerIds.has(profile.samples[i])) { offsetMs = sync.epochMs - timestampsUs[i] / 1000; break; }
100
+ }
101
+ if (offsetMs == null) offsetMs = sync.epochMs - profile.startTime / 1000;
102
+ const sampleTimes = new Float64Array(count);
103
+ const sampleWeights = new Float64Array(count);
104
+ for (let i = 0; i < count; i++) {
105
+ sampleTimes[i] = timestampsUs[i] / 1000 + offsetMs;
106
+ const nextUs = i + 1 < count ? timestampsUs[i + 1] : timestampsUs[i];
107
+ sampleWeights[i] = Math.max(0, (nextUs - timestampsUs[i]) / 1000);
108
+ }
109
+ return { byId, sampleNodes: profile.samples, sampleTimes, sampleWeights, markerIds, offsetMs };
110
+ }
111
+
112
+ /**
113
+ * Precomputes, for every profile node: its symbol, its effective owner (browser API calls take their caller's
114
+ * owner), the unique function keys on its stack (for inclusive time), the nearest of YOUR frames on its stack
115
+ * ("who is responsible"), and the first non-yours frame called from it ("what it spent the time in").
116
+ */
117
+ function annotateNodes(prepared, symbolizer) {
118
+ const { byId } = prepared;
119
+ const info = new Map();
120
+ const visit = (id) => {
121
+ if (info.has(id)) return info.get(id);
122
+ const node = byId.get(id);
123
+ const symbol = symbolizer.frame(node.callFrame);
124
+ const parentInfo = node.parent != null ? visit(node.parent) : null;
125
+ let owner = symbol.owner;
126
+ if (owner === "native" && parentInfo && !["root", "idle", "program", "gc"].includes(parentInfo.owner)) owner = parentInfo.owner;
127
+ const stackKeys = parentInfo ? parentInfo.stackKeys : new Set();
128
+ let keys = stackKeys;
129
+ if (!["root", "idle"].includes(symbol.special) && !stackKeys.has(symbol.key)) { keys = new Set(stackKeys); keys.add(symbol.key); }
130
+ const isYours = symbolizer.yours.has(symbol.owner);
131
+ const isFrameDriver = !isYours && FRAME_DRIVERS.test(symbol.name);
132
+ const inherited = parentInfo ? parentInfo.responsible : null;
133
+ const responsible = isYours ? symbol : isFrameDriver ? null : inherited;
134
+ // The library entry point your code called: the first non-yours frame below your nearest frame.
135
+ let calledInto = null;
136
+ if (!isYours && !isFrameDriver && parentInfo) calledInto = parentInfo.isYours ? symbol : parentInfo.calledInto;
137
+ // Where this owner's code was entered from: the nearest caller that belongs to a different owner.
138
+ const crossing = !parentInfo || parentInfo.owner === "root" ? null : parentInfo.owner === owner ? parentInfo.crossing : parentInfo.symbol;
139
+ const entry = {
140
+ symbol, owner, stackKeys: keys, isYours, responsible, calledInto, crossing, parent: parentInfo ? parentInfo.symbol : null,
141
+ positionTicks: node.positionTicks || null, scriptId: node.callFrame.scriptId, url: node.callFrame.url,
142
+ };
143
+ info.set(id, entry);
144
+ return entry;
145
+ };
146
+ for (const id of byId.keys()) visit(id);
147
+ return info;
148
+ }
149
+
150
+ /**
151
+ * Aggregates the samples that fall inside [from, to) epoch ms.
152
+ * @returns {object} self / inclusive time per function, time per owner, responsible-function time, totals
153
+ */
154
+ function aggregateWindow(prepared, info, from, to) {
155
+ const self = new Map();
156
+ const inclusive = new Map();
157
+ const owners = new Map();
158
+ const responsible = new Map();
159
+ const symbols = new Map();
160
+ const selfDetail = new Map();
161
+ let totalMs = 0;
162
+ let idleMs = 0;
163
+ const { sampleNodes, sampleTimes, sampleWeights, markerIds } = prepared;
164
+ for (let i = 0; i < sampleNodes.length; i++) {
165
+ const time = sampleTimes[i];
166
+ if (time < from || time >= to) continue;
167
+ const nodeId = sampleNodes[i];
168
+ if (markerIds.has(nodeId)) continue;
169
+ const weight = sampleWeights[i];
170
+ const entry = info.get(nodeId);
171
+ totalMs += weight;
172
+ if (entry.owner === "idle") { idleMs += weight; continue; }
173
+ if (entry.owner === "root") continue;
174
+ owners.set(entry.owner, (owners.get(entry.owner) || 0) + weight);
175
+ const key = entry.symbol.key;
176
+ symbols.set(key, entry.symbol);
177
+ self.set(key, (self.get(key) || 0) + weight);
178
+ const detail = selfDetail.get(key) || { parents: new Map(), crossings: new Map(), yours: new Map() };
179
+ const tally = (map, symbol) => { if (symbol) map.set(symbol.name, (map.get(symbol.name) || 0) + weight); };
180
+ tally(detail.parents, entry.parent);
181
+ tally(detail.crossings, entry.crossing);
182
+ tally(detail.yours, entry.responsible);
183
+ selfDetail.set(key, detail);
184
+ for (const stackKey of entry.stackKeys) inclusive.set(stackKey, (inclusive.get(stackKey) || 0) + weight);
185
+ if (entry.responsible) {
186
+ const blame = responsible.get(entry.responsible.key) || { symbol: entry.responsible, totalMs: 0, selfMs: 0, callees: new Map(), owners: new Map() };
187
+ blame.totalMs += weight;
188
+ if (entry.isYours) blame.selfMs += weight;
189
+ else {
190
+ const callee = entry.calledInto || entry.symbol;
191
+ const calleeEntry = blame.callees.get(callee.key) || { symbol: callee, ms: 0 };
192
+ calleeEntry.ms += weight;
193
+ blame.callees.set(callee.key, calleeEntry);
194
+ blame.owners.set(entry.owner, (blame.owners.get(entry.owner) || 0) + weight);
195
+ }
196
+ responsible.set(entry.responsible.key, blame);
197
+ symbols.set(entry.responsible.key, entry.responsible);
198
+ }
199
+ }
200
+ for (const [id, entry] of info) for (const key of entry.stackKeys) if (!symbols.has(key) && inclusive.has(key)) symbols.set(key, entry.symbol.key === key ? entry.symbol : symbols.get(key));
201
+ return { self, inclusive, owners, responsible, symbols, selfDetail, totalMs, idleMs, busyMs: totalMs - idleMs };
202
+ }
203
+
204
+ /** Summarizes the probe's frames inside a window. */
205
+ function frameStats(frames, from, to) {
206
+ const inside = frames.filter((frame) => frame.at >= from && frame.at < to);
207
+ if (inside.length < 2) return { frames: inside.length, fps: inside.length ? null : 0 };
208
+ const intervals = [];
209
+ for (let i = 1; i < inside.length; i++) intervals.push(inside[i].at - inside[i - 1].at);
210
+ const sortedIntervals = [...intervals].sort((first, second) => first - second);
211
+ const cpu = inside.map((frame) => frame.cpuMs).filter((value) => typeof value === "number").sort((first, second) => first - second);
212
+ const seconds = (inside[inside.length - 1].at - inside[0].at) / 1000;
213
+ const mean = (key) => {
214
+ const values = inside.map((frame) => frame[key]).filter((value) => typeof value === "number");
215
+ return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : null;
216
+ };
217
+ return {
218
+ frames: inside.length,
219
+ fps: round((inside.length - 1) / Math.max(seconds, 1e-3)),
220
+ intervalP50Ms: round(percentile(sortedIntervals, 0.5)),
221
+ intervalP95Ms: round(percentile(sortedIntervals, 0.95)),
222
+ worstIntervalMs: round(sortedIntervals[sortedIntervals.length - 1]),
223
+ slowFrames: intervals.filter((interval) => interval > FRAME_BUDGET_MS * 1.5).length,
224
+ cpuMeanMs: cpu.length ? round(cpu.reduce((sum, value) => sum + value, 0) / cpu.length, 2) : null,
225
+ cpuP95Ms: cpu.length ? round(percentile(cpu, 0.95), 2) : null,
226
+ draws: round(mean("draws"), 0),
227
+ activeMeshes: round(mean("activeMeshes"), 0),
228
+ particles: round(mean("particles"), 0),
229
+ renderMs: round(mean("renderMs"), 2),
230
+ targetsMs: round(mean("targetsMs"), 2),
231
+ evaluateMs: round(mean("evaluateMs"), 2),
232
+ animationsMs: round(mean("animationsMs"), 2),
233
+ physicsMs: round(mean("physicsMs"), 2),
234
+ particlesMs: round(mean("particlesMs"), 2),
235
+ };
236
+ }
237
+
238
+ /** Converts a window aggregate into sorted, serializable top lists. */
239
+ function topLists(aggregate, frames, top, labels) {
240
+ const perFrame = (ms) => (frames > 0 ? round(ms / frames, 3) : null);
241
+ const pct = (ms) => round((ms / Math.max(aggregate.busyMs, 1e-6)) * 100, 1);
242
+ const describe = (key, ms) => {
243
+ const symbol = aggregate.symbols.get(key);
244
+ return { key, name: symbol ? symbol.name : key, owner: symbol ? symbol.owner : "?", file: symbol ? symbol.file : null, line: symbol ? symbol.line : null, url: symbol ? symbol.url : "", ms: round(ms), msPerFrame: perFrame(ms), pctBusy: pct(ms) };
245
+ };
246
+ const topOf = (map, count) => [...map].sort((a, b) => b[1] - a[1]).slice(0, count).map(([name, ms]) => ({ name, ms: round(ms) }));
247
+ const selfTop = [...aggregate.self].sort((a, b) => b[1] - a[1]).slice(0, top).map(([key, ms]) => {
248
+ const detail = aggregate.selfDetail.get(key);
249
+ return { ...describe(key, ms), callers: detail ? topOf(detail.parents, 3) : [], enteredFrom: detail ? topOf(detail.crossings, 3) : [], yours: detail ? topOf(detail.yours, 3) : [] };
250
+ });
251
+ const inclusiveTop = [...aggregate.inclusive].filter(([key]) => !["root", "program", "gc", "idle"].includes(key)).sort((a, b) => b[1] - a[1]).slice(0, top * 2)
252
+ .map(([key, ms]) => ({ ...describe(key, ms), selfMs: round(aggregate.self.get(key) || 0) }))
253
+ .map((entry) => ({ ...entry, shell: entry.pctBusy >= SHELL_PCT }));
254
+ const yoursTop = [...aggregate.responsible.values()].sort((a, b) => b.totalMs - a.totalMs).slice(0, top).map((blame) => ({
255
+ key: blame.symbol.key, name: blame.symbol.name, owner: blame.symbol.owner, file: blame.symbol.file, line: blame.symbol.line,
256
+ ms: round(blame.totalMs), msPerFrame: perFrame(blame.totalMs), pctBusy: pct(blame.totalMs), ownCodeMs: round(blame.selfMs),
257
+ triggered: [...blame.owners].sort((a, b) => b[1] - a[1]).map(([owner, ms]) => ({ owner, label: labels[owner] || owner, ms: round(ms) })),
258
+ callees: [...blame.callees.values()].sort((a, b) => b.ms - a.ms).slice(0, 6).map((callee) => ({ name: callee.symbol.name, owner: callee.symbol.owner, file: callee.symbol.file, line: callee.symbol.line, ms: round(callee.ms) })),
259
+ }));
260
+ const owners = [...aggregate.owners].sort((a, b) => b[1] - a[1]).map(([owner, ms]) => ({ owner, label: labels[owner] || owner, ms: round(ms), pctBusy: pct(ms), msPerFrame: perFrame(ms) }));
261
+ const yoursMs = [...aggregate.responsible.values()].reduce((sum, blame) => sum + blame.totalMs, 0);
262
+ return { selfTop, inclusiveTop, yoursTop, owners, busyMs: round(aggregate.busyMs), idleMs: round(aggregate.idleMs), yoursMs: round(yoursMs), yoursPct: pct(yoursMs) };
263
+ }
264
+
265
+ /** Builds the scenario phases from the probe's marks (each runs until the next mark). */
266
+ function buildPhases(marks, startMs, endMs) {
267
+ const sorted = [...marks].sort((a, b) => a.at - b.at).filter((mark) => mark.name !== "end");
268
+ const phases = [];
269
+ // Time before the first mark only becomes its own phase when it is long enough to matter; otherwise it belongs
270
+ // to the first phase, so runs whose first mark lands a little later still compare phase by phase.
271
+ const leadIn = sorted.length ? sorted[0].at - startMs : endMs - startMs;
272
+ if (sorted.length === 0 || leadIn > MIN_LEAD_IN_PHASE_MS) phases.push({ name: "start", from: startMs, to: sorted.length ? sorted[0].at : endMs });
273
+ sorted.forEach((mark, index) => phases.push({ name: mark.name, from: index === 0 && leadIn <= MIN_LEAD_IN_PHASE_MS ? startMs : mark.at, to: index + 1 < sorted.length ? sorted[index + 1].at : endMs }));
274
+ return phases.filter((phase) => phase.to > phase.from);
275
+ }
276
+
277
+ /**
278
+ * Reads the allocation profiles of a capture: one per phase (heap/<index>-<phase>.heapprofile) or a single
279
+ * heap.heapprofile from older captures.
280
+ * @returns {{phase: string, profile: object}[]} the profiles in phase order
281
+ */
282
+ function loadHeapProfiles(captureDir) {
283
+ const heapDir = path.join(captureDir, "heap");
284
+ if (fs.existsSync(heapDir)) {
285
+ return fs.readdirSync(heapDir).filter((name) => name.endsWith(".heapprofile")).sort().map((name) => ({
286
+ phase: name.replace(/^\d+-/, "").replace(/\.heapprofile$/, ""),
287
+ profile: JSON.parse(fs.readFileSync(path.join(heapDir, name), "utf8")),
288
+ }));
289
+ }
290
+ const single = path.join(captureDir, "heap.heapprofile");
291
+ return fs.existsSync(single) ? [{ phase: "all", profile: JSON.parse(fs.readFileSync(single, "utf8")) }] : [];
292
+ }
293
+
294
+ /**
295
+ * Aggregates allocation profiles per function and per responsible function of yours. Sample sizes are already
296
+ * scaled by the sampler, so their sum estimates the bytes allocated (collected objects included when supported).
297
+ */
298
+ function analyzeHeap(heapProfiles, symbolizer, seconds, top) {
299
+ if (!heapProfiles || heapProfiles.length === 0) return null;
300
+ const self = new Map();
301
+ const responsible = new Map();
302
+ const symbols = new Map();
303
+ let total = 0;
304
+ for (const heapProfile of heapProfiles) {
305
+ const bytesByNode = new Map();
306
+ if (heapProfile.samples && heapProfile.samples.length) {
307
+ for (const sample of heapProfile.samples) bytesByNode.set(sample.nodeId, (bytesByNode.get(sample.nodeId) || 0) + sample.size);
308
+ }
309
+ const walk = (node, responsibleSymbol) => {
310
+ const symbol = symbolizer.frame(node.callFrame);
311
+ const isYours = symbolizer.yours.has(symbol.owner);
312
+ const mine = isYours ? symbol : FRAME_DRIVERS.test(symbol.name) ? null : responsibleSymbol;
313
+ const bytes = bytesByNode.size ? bytesByNode.get(node.id) || 0 : node.selfSize || 0;
314
+ if (bytes > 0 && symbol.special !== "root") {
315
+ total += bytes;
316
+ self.set(symbol.key, (self.get(symbol.key) || 0) + bytes);
317
+ symbols.set(symbol.key, symbol);
318
+ if (mine) { responsible.set(mine.key, (responsible.get(mine.key) || 0) + bytes); symbols.set(mine.key, mine); }
319
+ }
320
+ for (const child of node.children || []) walk(child, mine);
321
+ };
322
+ walk(heapProfile.head, null);
323
+ }
324
+ const wallSeconds = seconds;
325
+ const describe = ([key, bytes]) => {
326
+ const symbol = symbols.get(key);
327
+ return { name: symbol.name, owner: symbol.owner, file: symbol.file, line: symbol.line, mb: round(bytes / 1048576, 2), mbPerSecond: round(bytes / 1048576 / Math.max(wallSeconds, 1), 2) };
328
+ };
329
+ return {
330
+ totalMb: round(total / 1048576, 1),
331
+ mbPerSecond: round(total / 1048576 / Math.max(wallSeconds, 1), 2),
332
+ selfTop: [...self].sort((a, b) => b[1] - a[1]).slice(0, top).map(describe),
333
+ yoursTop: [...responsible].sort((a, b) => b[1] - a[1]).slice(0, top).map(describe),
334
+ };
335
+ }
336
+
337
+ /** Line-level self time inside your functions, from the profile's position ticks. */
338
+ function hotLines(prepared, info, symbolizer, top) {
339
+ const lines = new Map();
340
+ const totalByNode = new Map();
341
+ for (let i = 0; i < prepared.sampleNodes.length; i++) totalByNode.set(prepared.sampleNodes[i], (totalByNode.get(prepared.sampleNodes[i]) || 0) + prepared.sampleWeights[i]);
342
+ for (const [nodeId, entry] of info) {
343
+ if (!entry.isYours || !entry.positionTicks) continue;
344
+ const nodeMs = totalByNode.get(nodeId) || 0;
345
+ const ticks = entry.positionTicks.reduce((sum, tick) => sum + tick.ticks, 0);
346
+ if (ticks === 0 || nodeMs === 0) continue;
347
+ for (const tick of entry.positionTicks) {
348
+ const location = symbolizer.line(entry.scriptId, entry.url, tick.line);
349
+ const key = `${location.file}:${location.line}`;
350
+ const current = lines.get(key) || { file: location.file, line: location.line, function: entry.symbol.name, owner: entry.symbol.owner, ms: 0 };
351
+ current.ms += (nodeMs * tick.ticks) / ticks;
352
+ lines.set(key, current);
353
+ }
354
+ }
355
+ return [...lines.values()].sort((a, b) => b.ms - a.ms).slice(0, top).map((entry) => ({ ...entry, ms: round(entry.ms) }));
356
+ }
357
+
358
+ /** Reads a few lines of source around a function, marking the hot lines. */
359
+ function excerpt(symbolizer, file, line, hot) {
360
+ if (!file || !line) return null;
361
+ const text = symbolizer.readFile(file);
362
+ if (!text) return null;
363
+ const lines = text.split("\n");
364
+ const from = Math.max(1, line - EXCERPT_LINES_BEFORE);
365
+ const to = Math.min(lines.length, line + EXCERPT_LINES_AFTER);
366
+ const hotSet = new Map((hot || []).filter((entry) => entry.file === file).map((entry) => [entry.line, entry.ms]));
367
+ const rows = [];
368
+ for (let number = from; number <= to; number++) rows.push({ number, text: lines[number - 1].replace(/\t/g, " ").slice(0, 220), hotMs: hotSet.get(number) || null });
369
+ return { file, from, to, rows };
370
+ }
371
+
372
+ /** Counts the shader modules and pipelines / programs the page created inside a window. */
373
+ function compilesIn(gpuCompiles, from, to) {
374
+ let pipelines = 0;
375
+ let shaderModules = 0;
376
+ for (const entry of gpuCompiles || []) {
377
+ if (entry.at < from || entry.at >= to) continue;
378
+ if (entry.kind === "shaderModule") shaderModules++;
379
+ else pipelines++;
380
+ }
381
+ return { pipelines, shaderModules };
382
+ }
383
+
384
+ /**
385
+ * The worst frames of the run, each with the functions and owners that filled it. A frame is bad for one of two reasons:
386
+ * its own CPU work (`kind: "cpu"`), or a long gap before it while the main thread mostly waited (`kind: "wait"`) — the GPU
387
+ * process compiling pipelines, a GPU-bound frame, the browser's own work. A wait never shows in CPU time, so both rank.
388
+ */
389
+ function worstFrames(frames, prepared, info, phases, gpuCompiles, top) {
390
+ const candidates = frames.map((frame, index) => {
391
+ const previous = index > 0 ? frames[index - 1] : null;
392
+ const intervalMs = previous ? frame.at - previous.at : null;
393
+ const timed = typeof frame.cpuMs === "number";
394
+ // The gap before this frame, minus the CPU work of the frame that opened it, is time the main thread did not draw.
395
+ const waitMs = intervalMs == null ? 0 : intervalMs - (previous && typeof previous.cpuMs === "number" ? previous.cpuMs : 0);
396
+ const cpuCost = timed ? frame.cpuMs : 0;
397
+ const waits = !timed || waitMs > cpuCost;
398
+ return {
399
+ ...frame, intervalMs, kind: timed ? (waits ? "wait" : "cpu") : "gap", cost: waits ? (intervalMs ?? 0) : cpuCost,
400
+ from: waits ? frame.at - (intervalMs ?? 0) : frame.at, to: waits ? frame.at : frame.at + cpuCost,
401
+ };
402
+ });
403
+ const worst = [...candidates].sort((a, b) => b.cost - a.cost).slice(0, top);
404
+ return worst.map((frame) => {
405
+ const aggregate = aggregateWindow(prepared, info, frame.from, frame.to);
406
+ const phase = phases.find((candidate) => frame.at >= candidate.from && frame.at < candidate.to);
407
+ // Pipelines created just before a wait (up to 2 s) are what the GPU process may still be compiling during it.
408
+ const compiles = compilesIn(gpuCompiles, frame.from - 2000, frame.to);
409
+ return {
410
+ at: frame.at, cpuMs: round(frame.cpuMs), intervalMs: round(frame.intervalMs), kind: frame.kind, phase: phase ? phase.name : null,
411
+ scriptMs: round(aggregate.busyMs), pipelinesNear: compiles.pipelines, shaderModulesNear: compiles.shaderModules,
412
+ draws: frame.draws, particles: frame.particles,
413
+ top: [...aggregate.self].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([key, ms]) => ({ name: aggregate.symbols.get(key).name, owner: aggregate.symbols.get(key).owner, ms: round(ms) })),
414
+ yours: [...aggregate.responsible.values()].sort((a, b) => b.totalMs - a.totalMs).slice(0, 3).map((blame) => ({ name: blame.symbol.name, file: blame.symbol.file, line: blame.symbol.line, ms: round(blame.totalMs) })),
415
+ owners: [...aggregate.owners].sort((a, b) => b[1] - a[1]).slice(0, 4).map(([owner, ms]) => ({ owner, ms: round(ms) })),
416
+ };
417
+ });
418
+ }
419
+
420
+ /** One entry per timeline bucket: frame rate, CPU work, busy time per owner, new shader programs, top function. */
421
+ function buildTimeline(prepared, info, frames, counters, startMs, endMs) {
422
+ const buckets = [];
423
+ for (let from = startMs; from < endMs; from += BUCKET_SECONDS * 1000) {
424
+ const to = Math.min(endMs, from + BUCKET_SECONDS * 1000);
425
+ const aggregate = aggregateWindow(prepared, info, from, to);
426
+ const stats = frameStats(frames, from, to);
427
+ const counterInside = counters.filter((counter) => counter.at >= from && counter.at < to);
428
+ const counterBefore = counters.filter((counter) => counter.at < from).pop();
429
+ const lastCounter = counterInside[counterInside.length - 1] || counterBefore || {};
430
+ const firstCompiled = (counterBefore && counterBefore.compiledEffects) ?? (counterInside[0] && counterInside[0].compiledEffects) ?? null;
431
+ const topSelf = [...aggregate.self].sort((a, b) => b[1] - a[1])[0];
432
+ const topYours = [...aggregate.responsible.values()].sort((a, b) => b.totalMs - a.totalMs)[0];
433
+ buckets.push({
434
+ t: round((from - startMs) / 1000, 1),
435
+ fps: stats.fps ?? 0,
436
+ frames: stats.frames,
437
+ worstMs: stats.worstIntervalMs,
438
+ cpuMeanMs: stats.cpuMeanMs ?? null,
439
+ busyPct: round((aggregate.busyMs / Math.max(aggregate.totalMs, 1e-6)) * 100, 0),
440
+ owners: Object.fromEntries([...aggregate.owners].map(([owner, ms]) => [owner, round(ms, 0)])),
441
+ newShaders: lastCounter.compiledEffects != null && firstCompiled != null ? lastCounter.compiledEffects - firstCompiled : null,
442
+ compiledEffects: lastCounter.compiledEffects ?? null,
443
+ particles: stats.particles ?? null,
444
+ draws: stats.draws ?? null,
445
+ heapMb: lastCounter.heapMb ?? null,
446
+ meshes: lastCounter.meshes ?? null,
447
+ materials: lastCounter.materials ?? null,
448
+ top: topSelf ? { name: aggregate.symbols.get(topSelf[0]).name, owner: aggregate.symbols.get(topSelf[0]).owner, ms: round(topSelf[1], 0) } : null,
449
+ topYours: topYours ? { name: topYours.symbol.name, ms: round(topYours.totalMs, 0) } : null,
450
+ });
451
+ }
452
+ return buckets;
453
+ }
454
+
455
+ /** Groups long-animation-frame script attributions by function. */
456
+ function summarizeLoafs(loafs, top) {
457
+ const groups = new Map();
458
+ for (const loaf of loafs || []) {
459
+ for (const script of loaf.scripts || []) {
460
+ const key = `${script.sourceFunction || script.invoker}|${(script.sourceUrl || "").replace(/\?.*$/, "")}`;
461
+ const group = groups.get(key) || { function: script.sourceFunction || script.invoker, url: (script.sourceUrl || "").replace(/^https?:\/\/[^/]+/, "").replace(/\?.*$/, ""), invokerType: script.invokerType, count: 0, ms: 0 };
462
+ group.count++;
463
+ group.ms += script.durationMs;
464
+ groups.set(key, group);
465
+ }
466
+ }
467
+ return { longFrames: (loafs || []).length, scripts: [...groups.values()].sort((a, b) => b.ms - a.ms).slice(0, top).map((group) => ({ ...group, ms: round(group.ms) })) };
468
+ }
469
+
470
+ /** Plain-language signals the agent should look at first. They point; the agent diagnoses. */
471
+ function signals(analysis) {
472
+ const notes = [];
473
+ const overall = analysis.overall.lists;
474
+ const ownerPct = (owner) => (overall.owners.find((entry) => entry.owner === owner) || { pctBusy: 0 }).pctBusy;
475
+ if (ownerPct("gc") >= 5) notes.push(`Garbage collection takes ${ownerPct("gc")}% of busy time — look at the allocation list (heap.yoursTop) for per-frame garbage.`);
476
+ if (ownerPct("shader") >= 5) notes.push(`GLSL → WGSL shader translation takes ${ownerPct("shader")}% of busy time — new material / particle shader variants are being compiled on the main thread.`);
477
+ for (const phase of analysis.phases) {
478
+ if (phase.beforeFirstFrame || phase.frames.fps == null || phase.frames.fps >= 45 || phase.durationSeconds < 1) continue;
479
+ const lead = phase.lists.inclusiveTop.find((entry) => !entry.shell && entry.owner !== "program");
480
+ const cpu = phase.frames.cpuMeanMs != null ? `CPU ${phase.frames.cpuMeanMs} ms/frame, ` : "";
481
+ const rate = phase.frames.frames < 2 ? `draws ${phase.frames.frames} frame(s) in ${phase.durationSeconds} s` : `runs at ${phase.frames.fps} FPS`;
482
+ notes.push(`Phase "${phase.name}" ${rate} (${cpu}main thread ${phase.busyPct}% busy)${phase.lists.yoursTop[0] ? `; your heaviest code: ${phase.lists.yoursTop[0].name} (${phase.lists.yoursTop[0].msPerFrame != null ? `${phase.lists.yoursTop[0].msPerFrame} ms/frame` : `${phase.lists.yoursTop[0].ms} ms`})` : ""}${lead ? `; heaviest stack entry: ${lead.name}` : ""}.`);
483
+ }
484
+ // The first-visit stutter signature: long frames the main thread spent waiting, right after new pipelines were created.
485
+ const waits = analysis.worstFrames.filter((frame) => frame.kind === "wait" && frame.intervalMs >= 250 && frame.scriptMs < frame.intervalMs * 0.25);
486
+ if (waits.length) {
487
+ const withCompiles = waits.filter((frame) => frame.pipelinesNear > 0);
488
+ notes.push(`${waits.length} frame(s) of ${waits.map((frame) => `${frame.intervalMs} ms at ${frame.t}s`).slice(0, 4).join(", ")} were spent waiting, not running script (main thread ${waits.map((frame) => frame.scriptMs).slice(0, 4).join(" / ")} ms)` +
489
+ (withCompiles.length ? ` — ${withCompiles.length} of them right after new GPU pipelines / programs were created: the GPU process compiling shaders.${analysis.gpuCold ? " This capture was GPU-cold (--gpu-cold), as on a first visit." : " A later visit may hide it (shader caches): confirm with --gpu-cold true."}` : ` — GPU-bound frames or browser work; check draws and the GPU timers.`));
490
+ }
491
+ const shaderBuckets = analysis.timeline.filter((bucket) => bucket.newShaders > 0);
492
+ if (shaderBuckets.length) {
493
+ const late = shaderBuckets.filter((bucket) => bucket.t > 0.6 * analysis.timeline.length);
494
+ notes.push(`${shaderBuckets.reduce((sum, bucket) => sum + bucket.newShaders, 0)} new shader programs / pipelines were created during the run${late.length ? `, ${late.reduce((sum, bucket) => sum + bucket.newShaders, 0)} of them late (after 60% of the run)` : ""}.`);
495
+ }
496
+ return notes;
497
+ }
498
+
499
+ /**
500
+ * Breaks a function's time into what it calls: for every sample under a frame named `name` (outermost occurrence),
501
+ * the time goes to the frame directly below it ("(self)" when the sample is in the function itself).
502
+ * @returns {{totalMs: number, callees: {name: string, owner: string, ms: number}[]}} the breakdown inside the window
503
+ */
504
+ function drillDown(prepared, info, byId, name, from, to, top) {
505
+ const callees = new Map();
506
+ let totalMs = 0;
507
+ const { sampleNodes, sampleTimes, sampleWeights } = prepared;
508
+ for (let i = 0; i < sampleNodes.length; i++) {
509
+ if (sampleTimes[i] < from || sampleTimes[i] >= to) continue;
510
+ let calleeOfOutermost;
511
+ let below = null;
512
+ for (let nodeId = sampleNodes[i]; nodeId != null; nodeId = byId.get(nodeId).parent) {
513
+ const symbol = info.get(nodeId).symbol;
514
+ if (symbol.name === name) calleeOfOutermost = below;
515
+ below = symbol;
516
+ }
517
+ if (calleeOfOutermost === undefined) continue;
518
+ totalMs += sampleWeights[i];
519
+ const key = calleeOfOutermost ? calleeOfOutermost.name : "(self)";
520
+ const current = callees.get(key) || { name: key, owner: calleeOfOutermost ? calleeOfOutermost.owner : "", ms: 0 };
521
+ current.ms += sampleWeights[i];
522
+ callees.set(key, current);
523
+ }
524
+ return { totalMs: round(totalMs), callees: [...callees.values()].sort((a, b) => b.ms - a.ms).slice(0, top).map((entry) => ({ ...entry, ms: round(entry.ms) })) };
525
+ }
526
+
527
+ /**
528
+ * Who calls a function: for every sample under a frame named `name` (outermost occurrence), the time goes to that
529
+ * occurrence's direct caller, and separately to the nearest caller from a different owner (where the work was asked for).
530
+ * @returns {{totalMs: number, callers: object[], from: object[]}} the breakdown inside the window
531
+ */
532
+ function callersOf(prepared, info, byId, name, from, to, top) {
533
+ const direct = new Map();
534
+ const crossing = new Map();
535
+ let totalMs = 0;
536
+ const { sampleNodes, sampleTimes, sampleWeights } = prepared;
537
+ const tally = (map, symbol, weight) => {
538
+ const key = symbol ? symbol.name : "(root)";
539
+ const current = map.get(key) || { name: key, owner: symbol ? symbol.owner : "", file: symbol ? symbol.file : null, line: symbol ? symbol.line : null, ms: 0 };
540
+ current.ms += weight;
541
+ map.set(key, current);
542
+ };
543
+ for (let i = 0; i < sampleNodes.length; i++) {
544
+ if (sampleTimes[i] < from || sampleTimes[i] >= to) continue;
545
+ let outermost = null;
546
+ for (let nodeId = sampleNodes[i]; nodeId != null; nodeId = byId.get(nodeId).parent) if (info.get(nodeId).symbol.name === name) outermost = nodeId;
547
+ if (outermost == null) continue;
548
+ const weight = sampleWeights[i];
549
+ totalMs += weight;
550
+ const ownOwner = info.get(outermost).owner;
551
+ const parentId = byId.get(outermost).parent;
552
+ tally(direct, parentId != null ? info.get(parentId).symbol : null, weight);
553
+ let crossingSymbol = null;
554
+ for (let nodeId = parentId; nodeId != null; nodeId = byId.get(nodeId).parent) {
555
+ const entry = info.get(nodeId);
556
+ if (entry.owner !== ownOwner && !["native", "root"].includes(entry.owner)) { crossingSymbol = entry.symbol; break; }
557
+ }
558
+ tally(crossing, crossingSymbol, weight);
559
+ }
560
+ const sorted = (map) => [...map.values()].sort((a, b) => b.ms - a.ms).slice(0, top).map((entry) => ({ ...entry, ms: round(entry.ms) }));
561
+ return { totalMs: round(totalMs), callers: sorted(direct), from: sorted(crossing) };
562
+ }
563
+
564
+ /** Prints the summary the agent reads. */
565
+ function printSummary(analysis) {
566
+ const out = [];
567
+ const line = (text = "") => out.push(text);
568
+ line(`bt-profile analysis — ${analysis.capture.label} capture of ${analysis.capture.url} (${analysis.capture.engine}, scenario ${analysis.capture.scenario})`);
569
+ if (analysis.capture.disturbed) line(`WARNING: the game restarted under this capture — ${analysis.capture.disturbed.reason}. Not comparable: re-capture on a server with file watching off.`);
570
+ line(`Wall ${analysis.capture.wallSeconds}s · main thread busy ${analysis.overall.busyPct}% · your code (incl. what it triggers) ${analysis.overall.lists.yoursPct}% of busy time · heap ${analysis.heap ? analysis.heap.mbPerSecond + " MB/s allocated" : "n/a"}`);
571
+ line();
572
+ line("PHASES");
573
+ for (const phase of analysis.phases) {
574
+ line(` ${phase.name.padEnd(14)} ${String(phase.durationSeconds + "s").padStart(6)} ${String(phase.frames.fps ?? "-").padStart(5)} fps p95 ${String(phase.frames.intervalP95Ms ?? "-").padStart(6)} ms cpu ${String(phase.frames.cpuMeanMs ?? "-").padStart(6)} ms/frame busy ${String(phase.busyPct).padStart(3)}% particles ${phase.frames.particles ?? "-"} draws ${phase.frames.draws ?? "-"}`);
575
+ line(` owners: ${phase.lists.owners.slice(0, 6).map((entry) => `${entry.owner} ${entry.pctBusy}%`).join(" · ")}`);
576
+ line(` yours: ${phase.lists.yoursTop.slice(0, 3).map((entry) => (entry.msPerFrame != null ? `${entry.name} ${entry.msPerFrame}ms/f` : `${entry.name} ${entry.ms}ms`)).join(" · ") || "-"}`);
577
+ if (phase.gpuCompiles && (phase.gpuCompiles.pipelines || phase.gpuCompiles.shaderModules)) line(` gpu: ${phase.gpuCompiles.pipelines} pipelines / programs, ${phase.gpuCompiles.shaderModules} shader modules created`);
578
+ if (phase.heap) line(` alloc: ${phase.heap.mbPerSecond} MB/s · ${phase.heap.selfTop.slice(0, 3).map((entry) => `${entry.name} ${entry.mbPerSecond}MB/s`).join(" · ")}`);
579
+ line(` hot: ${phase.lists.inclusiveTop.filter((entry) => entry.owner !== "program" && !entry.shell).slice(0, 5).map((entry) => `${entry.name} ${entry.pctBusy}%`).join(" · ")}`);
580
+ }
581
+ line();
582
+ line("WORST FRAMES — cpu: the frame's own work · wait: a gap the main thread mostly waited through (GPU, browser)");
583
+ for (const frame of analysis.worstFrames.slice(0, 8)) {
584
+ const cost = frame.kind === "cpu" ? `${frame.cpuMs} ms cpu` : `${frame.intervalMs} ms ${frame.kind}`;
585
+ line(` ${String(frame.t + "s").padStart(8)} ${cost.padEnd(16)} ${String(frame.phase || "-").padEnd(14)} script ${frame.scriptMs} ms · ${frame.pipelinesNear} pipelines near · ${frame.top.slice(0, 2).map((entry) => `${entry.name} ${entry.ms}`).join(", ") || "-"}`);
586
+ }
587
+ if (analysis.gpuCold) line(` (--gpu-cold: ${analysis.gpuCold.tagged} fragment shaders made unique, so every pipeline compiled as on a first visit)`);
588
+ line();
589
+ line("YOUR CODE — time spent, including the library work it triggers (whole run)");
590
+ for (const entry of analysis.overall.lists.yoursTop.slice(0, 15)) {
591
+ line(` ${String(entry.ms).padStart(8)} ms ${String(entry.pctBusy).padStart(5)}% ${entry.name} ${shortFile(entry.file)}:${entry.line} [own ${entry.ownCodeMs} ms; ${entry.callees.slice(0, 3).map((callee) => `${callee.name} ${callee.ms}`).join(", ")}]`);
592
+ }
593
+ line();
594
+ line("HEAVIEST FUNCTIONS — self time (whole run)");
595
+ for (const entry of analysis.overall.lists.selfTop.slice(0, 15)) {
596
+ line(` ${String(entry.ms).padStart(8)} ms ${String(entry.pctBusy).padStart(5)}% [${entry.owner}] ${entry.name} ${shortFile(entry.file) || entry.url}:${entry.line ?? ""}`);
597
+ line(` called by: ${entry.callers.map((caller) => `${caller.name} ${caller.ms}`).join(", ")}${entry.yours.length ? ` · yours: ${entry.yours.map((owner) => `${owner.name} ${owner.ms}`).join(", ")}` : ""}`);
598
+ }
599
+ line();
600
+ line("HEAVIEST SUBTREES — inclusive time, frame shells removed (whole run)");
601
+ for (const entry of analysis.overall.lists.inclusiveTop.filter((candidate) => !candidate.shell).slice(0, 20)) line(` ${String(entry.ms).padStart(8)} ms ${String(entry.pctBusy).padStart(5)}% [${entry.owner}] ${entry.name} (self ${entry.selfMs})`);
602
+ if (analysis.heap) {
603
+ line();
604
+ line(`ALLOCATIONS — ${analysis.heap.totalMb} MB sampled (${analysis.heap.mbPerSecond} MB/s); top responsible of yours:`);
605
+ for (const entry of analysis.heap.yoursTop.slice(0, 8)) line(` ${String(entry.mb).padStart(8)} MB ${entry.name} ${shortFile(entry.file)}:${entry.line}`);
606
+ }
607
+ line();
608
+ line("SIGNALS");
609
+ for (const note of analysis.signals) line(` - ${note}`);
610
+ process.stdout.write(out.join("\n") + "\n");
611
+ }
612
+
613
+ /** Shortens an absolute path for printing. */
614
+ function shortFile(file) {
615
+ if (!file) return "";
616
+ return file.replace(/^.*\/node_modules\//, "node_modules/").replace(/^\/Users\/[^/]+\//, "~/");
617
+ }
618
+
619
+ /** Entry point. */
620
+ function main() {
621
+ const flags = parseArguments(process.argv.slice(2));
622
+ if (!flags.capture) throw new Error("Pass --capture <run>/cold (a folder written by profile.mjs)");
623
+ const captureDir = path.resolve(flags.capture);
624
+ const top = Number(flags.top || 25);
625
+ const config = loadConfig(flags, captureDir);
626
+ const capture = JSON.parse(fs.readFileSync(path.join(captureDir, "capture.json"), "utf8"));
627
+ const profile = JSON.parse(fs.readFileSync(path.join(captureDir, "cpu.cpuprofile"), "utf8"));
628
+ const heapProfiles = loadHeapProfiles(captureDir);
629
+ const symbolizer = createSymbolizer({ scriptsDir: path.join(captureDir, "scripts"), projectRoot: config.projectRoot, owners: config.owners });
630
+
631
+ const prepared = prepareProfile(profile, capture.sync);
632
+ const info = annotateNodes(prepared, symbolizer);
633
+ const probe = capture.probe || { frames: [], counters: [], marks: [], loafs: [] };
634
+ const startMs = capture.sync.epochMs;
635
+ const endMark = probe.marks.find((mark) => mark.name === "end");
636
+ const endMs = endMark ? endMark.at : prepared.sampleTimes[prepared.sampleTimes.length - 1];
637
+ const frames = probe.frames;
638
+ const phases = buildPhases(probe.marks, startMs, endMs);
639
+
640
+ const overallAggregate = aggregateWindow(prepared, info, startMs, endMs);
641
+ const overallFrames = frameStats(frames, startMs, endMs);
642
+ const overallLists = topLists(overallAggregate, overallFrames.frames, top, symbolizer.labels);
643
+ const lines = hotLines(prepared, info, symbolizer, 40);
644
+
645
+ const phaseResults = phases.map((phase) => {
646
+ const aggregate = aggregateWindow(prepared, info, phase.from, phase.to);
647
+ const stats = frameStats(frames, phase.from, phase.to);
648
+ return {
649
+ name: phase.name,
650
+ startSeconds: round((phase.from - startMs) / 1000, 1),
651
+ durationSeconds: round((phase.to - phase.from) / 1000, 1),
652
+ busyPct: round((aggregate.busyMs / Math.max(aggregate.totalMs, 1e-6)) * 100, 0),
653
+ // A phase over before the first frame (the page loading) has no frame rate to judge — it is load time.
654
+ beforeFirstFrame: frames.length === 0 || phase.to <= frames[0].at,
655
+ gpuCompiles: compilesIn(probe.gpuCompiles, phase.from, phase.to),
656
+ frames: stats,
657
+ lists: topLists(aggregate, stats.frames, Math.min(top, 15), symbolizer.labels),
658
+ };
659
+ });
660
+
661
+ for (const phase of phaseResults) {
662
+ const profiles = heapProfiles.filter((entry) => entry.phase === phase.name.replace(/[^\w+.-]+/g, "_")).map((entry) => entry.profile);
663
+ phase.heap = profiles.length ? analyzeHeap(profiles, symbolizer, phase.durationSeconds, 8) : null;
664
+ }
665
+
666
+ const excerptsFor = new Map();
667
+ const addExcerpt = (entry) => {
668
+ if (!entry.file || !entry.line || excerptsFor.has(`${entry.file}:${entry.line}`)) return;
669
+ const block = excerpt(symbolizer, entry.file, entry.line, lines);
670
+ if (block) excerptsFor.set(`${entry.file}:${entry.line}`, { name: entry.name, owner: entry.owner, ...block });
671
+ };
672
+ overallLists.yoursTop.slice(0, 15).forEach(addExcerpt);
673
+ for (const phase of phaseResults) phase.lists.yoursTop.slice(0, 5).forEach(addExcerpt);
674
+
675
+ const analysis = {
676
+ version: 1,
677
+ capture: {
678
+ dir: captureDir, label: capture.label, url: capture.url, engine: probe.engine, scenario: capture.scenario && capture.scenario.name,
679
+ scenarioDescription: capture.scenario && capture.scenario.description, capturedAt: capture.capturedAt, browser: capture.browser, platform: capture.platform,
680
+ viewport: capture.viewport, wallSeconds: round((endMs - startMs) / 1000, 1), samplingIntervalUs: capture.samplingIntervalUs,
681
+ heapIncludesCollected: capture.heapIncludesCollected, scenarioError: capture.scenarioError, consoleErrors: capture.consoleErrors, census: capture.census,
682
+ disturbed: capture.disturbed || null,
683
+ clockOffsetMs: round(prepared.offsetMs, 3), startEpochMs: startMs,
684
+ },
685
+ ownerLabels: symbolizer.labels,
686
+ yourOwners: [...symbolizer.yours],
687
+ overall: { busyPct: round((overallAggregate.busyMs / Math.max(overallAggregate.totalMs, 1e-6)) * 100, 0), frames: overallFrames, lists: overallLists },
688
+ phases: phaseResults,
689
+ timeline: buildTimeline(prepared, info, frames, probe.counters, startMs, endMs),
690
+ marks: probe.marks.map((mark) => ({ name: mark.name, t: round((mark.at - startMs) / 1000, 2) })),
691
+ worstFrames: worstFrames(frames, prepared, info, phases, probe.gpuCompiles, 15).map((frame) => ({ ...frame, t: round((frame.at - startMs) / 1000, 2) })),
692
+ gpuCompiles: (probe.gpuCompiles || []).map((entry) => ({ kind: entry.kind, t: round((entry.at - startMs) / 1000, 2) })),
693
+ gpuCold: capture.gpuCold || null,
694
+ hotLines: lines,
695
+ excerpts: [...excerptsFor.values()],
696
+ heap: analyzeHeap(heapProfiles.map((entry) => entry.profile), symbolizer, (endMs - startMs) / 1000, top),
697
+ loaf: summarizeLoafs(probe.loafs, 15),
698
+ counters: probe.counters.map((counter) => ({ ...counter, t: round((counter.at - startMs) / 1000, 1) })),
699
+ shots: fs.existsSync(path.join(captureDir, "shots")) ? fs.readdirSync(path.join(captureDir, "shots")).filter((name) => name.endsWith(".png")) : [],
700
+ filmstrip: fs.existsSync(path.join(captureDir, "filmstrip.json")) ? JSON.parse(fs.readFileSync(path.join(captureDir, "filmstrip.json"), "utf8")).map((frame) => ({ ...frame, t: round((frame.at - startMs) / 1000, 2) })) : [],
701
+ };
702
+ analysis.signals = signals(analysis);
703
+ if (flags.drill) {
704
+ analysis.drill = flags.drill.split(",").map((name) => ({
705
+ name,
706
+ overall: drillDown(prepared, info, prepared.byId, name, startMs, endMs, 20),
707
+ phases: phases.map((phase) => ({ phase: phase.name, ...drillDown(prepared, info, prepared.byId, name, phase.from, phase.to, 6) })),
708
+ }));
709
+ }
710
+ const outFile = path.join(captureDir, "analysis.json");
711
+ fs.writeFileSync(outFile, JSON.stringify(analysis));
712
+ if (flags.callers) {
713
+ analysis.callers = flags.callers.split(",").map((name) => ({
714
+ name,
715
+ overall: callersOf(prepared, info, prepared.byId, name, startMs, endMs, 15),
716
+ phases: phases.map((phase) => ({ phase: phase.name, ...callersOf(prepared, info, prepared.byId, name, phase.from, phase.to, 4) })),
717
+ }));
718
+ }
719
+ if (flags.quiet !== "true") printSummary(analysis);
720
+ for (const entry of analysis.callers || []) {
721
+ process.stdout.write(`\nCALLERS ${entry.name} — ${entry.overall.totalMs} ms over the run\n direct:\n`);
722
+ for (const caller of entry.overall.callers) process.stdout.write(` ${String(caller.ms).padStart(9)} ms [${caller.owner}] ${caller.name} ${shortFile(caller.file)}${caller.line ? ":" + caller.line : ""}\n`);
723
+ process.stdout.write(" asked for by (nearest other owner):\n");
724
+ for (const caller of entry.overall.from) process.stdout.write(` ${String(caller.ms).padStart(9)} ms [${caller.owner}] ${caller.name} ${shortFile(caller.file)}${caller.line ? ":" + caller.line : ""}\n`);
725
+ for (const phase of entry.phases) if (phase.totalMs > 0) process.stdout.write(` ${phase.phase.padEnd(12)} ${String(phase.totalMs).padStart(8)} ms · ${phase.from.slice(0, 3).map((caller) => `${caller.name} ${caller.ms}`).join(" · ")}\n`);
726
+ }
727
+ for (const drill of analysis.drill || []) {
728
+ process.stdout.write(`\nDRILL ${drill.name} — ${drill.overall.totalMs} ms over the run\n`);
729
+ for (const callee of drill.overall.callees) process.stdout.write(` ${String(callee.ms).padStart(9)} ms [${callee.owner}] ${callee.name}\n`);
730
+ for (const phase of drill.phases) if (phase.totalMs > 0) process.stdout.write(` ${phase.phase.padEnd(12)} ${String(phase.totalMs).padStart(8)} ms · ${phase.callees.slice(0, 4).map((callee) => `${callee.name} ${callee.ms}`).join(" · ")}\n`);
731
+ }
732
+ process.stderr.write(`wrote ${outFile}\n`);
733
+ }
734
+
735
+ main();