@davideasden/pi-undo 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,13 +13,15 @@ Each completed agent run creates a checkpoint that captures both the Pi session
13
13
  - **Deferred prompts** — text, images, `@file` references, and paste content entered during an undo/redo are queued and processed in FIFO order once the operation completes. Prompts are never lost.
14
14
  - **Crash recovery** — a write-ahead log (WAL), mutation journal, and quarantine artifacts allow in-progress operations to be rolled forward or back on restart.
15
15
  - **External concurrency detection** — file fingerprint and inode checks detect external modification. Conflicting changes are never silently overwritten; the system fails closed or enters `recovery required`.
16
+ - **后台持久化故障即时锁定** — durable pack finalization 失败会立即进入 `recovery_required`,不会等到下次启动才暴露问题。
17
+ - **Pi 1.3 生命周期兼容** — `before_agent_start` 会忽略 `pi.sendMessage(..., { triggerTurn: true })` 产生的 custom run,避免把没有用户输入边界的内部任务误记为可撤回 run。
16
18
  - **No Git workflow** — snapshots use a private object database. No `git commit`, `git stash`, `git reset`, branches, or forges are required.
17
19
  - **Nested repositories** and **initialized submodules** are handled as independent roots. Their `.git` metadata is never modified.
18
20
  - **Performance** — batch WAL operations (up to 1,024 files per batch), scoped safety snapshots, prebuilt durable transaction packs, native Rust no-clobber file helper (macOS/Linux, arm64/x64), indexed WAL record and conflict lookups, and parallel manifest blob reads keep restore fast at scale. Unsupported platforms and failed integrity checks automatically use the TypeScript fallback.
19
21
 
20
22
  ## Requirements
21
23
 
22
- - Pi `1.2.0` 或更高版本(已在 1.2.0 上验证,见 [Pi 1.2.0 兼容验证记录](docs/pi-1.2.0-validation.md))。`1.1.x` 及更早版本不再受支持,也不在 CI 中测试:早期版本的扩展生命周期行为不同(例如 `before_agent_start` 的触发范围与会话 busy 语义),不保证撤回语义正确。历史验证记录见 [Pi 0.86.1 撤回修复与验证记录](docs/pi-0.86.1-validation.md)。
24
+ - Pi `1.2.0` 或更高版本(已在 1.2.0 和 1.3.0 上验证,见 [Pi 1.3.0 兼容验证记录](docs/pi-1.3.0-validation.md))。`1.1.x` 及更早版本不再受支持,也不在 CI 中测试:早期版本的扩展生命周期行为不同(例如 `before_agent_start` 的触发范围与会话 busy 语义),不保证撤回语义正确。历史验证记录见 [Pi 0.86.1 撤回修复与验证记录](docs/pi-0.86.1-validation.md)。
23
25
  - Node.js `22.19.0` or later.
24
26
  - Git available on `PATH` (used internally for content-addressed snapshots).
25
27
 
@@ -78,6 +80,10 @@ If an operation fails mid-flight (for example, the process is killed while files
78
80
 
79
81
  to re-run recovery in place: it re-verifies pending journals, settles provably-safe transactions, rebuilds the undo/redo stacks, and refreshes the status line — the in-process equivalent of restarting the session window. If the workspace is still locked afterwards, the blocking transaction belongs to another session in the same workspace; open (or restart) that session and run `/undo-recover` there.
80
82
 
83
+ 如果提示中包含 `workspace_identity_changed`,说明当前 runtime 绑定的工作区 canonical root 已变化,本次输入会继续执行但不会被纳入撤回历史。先停止导致目录切换或替换的操作,再运行 `/undo-recover` 重新发现工作区;不要手动删除 `.pi-undo`。
84
+
85
+ 如果提示包含 `mutation_conflict`,pi-undo 不会猜测应该回滚还是前进。先备份工作区和 session JSONL,停止编辑器、formatter、watcher 以及其他 Pi 实例,按提示中的 `opId` 检查事务;确认文件回到操作前或操作后的完整状态后,再运行 `/undo-recover`。
86
+
81
87
  ### Diff
82
88
 
83
89
  ```text
@@ -163,7 +169,7 @@ recovery_required
163
169
 
164
170
  普通文件原生恢复路径保留 5 次完整拓扑扫描。macOS/Linux 的新版 helper 使用不跟随符号链接的目录句柄扫描,仍会发现 Git 忽略目录中的嵌套仓库。小工作区根据上次扫描规模选择 TypeScript 完整重扫,避免进程启动开销;没有使用 TTL 缓存或默认跳过 `node_modules`。
165
171
 
166
- 原生恢复现支持已有父目录中的普通文件删除,以及覆盖、创建、删除混合计划。扩展能力通过 `restore-files-v2` 探测;旧 helper、缺少二进制、目录操作及超出句柄预算的计划继续走 TypeScript 路径。pack 持久化、内容校验、no-clobber 与恢复依据均保留。
172
+ 原生恢复可处理已有父目录中的普通文件删除、覆盖、创建及混合计划。`restore-files-v2` 覆盖子目录删除和混合 mutation;`restore-files-v3` 会把分散在大量父目录中的文件拆成多个批次,每批最多打开 128 个非根父目录句柄。旧 helper、缺少二进制、目录操作、类型替换及单条路径深度超过句柄预算时继续走 TypeScript 路径。durable pack、逐项内容校验、no-clobber 与恢复依据均保留。
167
173
 
168
174
  本机 macOS arm64 的三次 undo 中位数:3,000 包/1 文件从 1,976 ms 降至 924 ms,10,000 包/1 文件从 5,857 ms 降至 2,755 ms;100 文件的子目录撤销从 517 ms 降至 180 ms,混合撤销从 711 ms 降至 186 ms。测量方法和限制见 [原生性能验证记录](docs/native-performance.md)。
169
175
 
@@ -52,7 +52,9 @@ GitRunner 会对单次 Git stdout 应用 256 MiB 硬上限;超过上限时终
52
52
 
53
53
  上一轮分阶段计时中,3,000 包的五次扫描合计从 1,759 ms 降至 716 ms;10,000 包从 5,470 ms 降至 2,398 ms。另一批四组大型工作区测量覆盖 3,000/10,000 包 × 1/100 文件,中位数依次为 878、923、2,582、2,673 ms;这些独立批次不混算。
54
54
 
55
- 已有 `restore-files-v2` 支持父目录已存在的普通文件覆盖、创建、删除和混合计划,最多保留 128 个非根父目录句柄。目录创建/删除、类型替换、过多父目录和不支持的平台继续使用 TypeScript。durable pack 格式与恢复协议未改变:修改前持久化 pack,逐项校验内容和 mode,失败由现有 recovery 回滚并保留外来冲突文件。历史新增文件测试保留父目录中的 `keep.txt`,不包含目录删除成本。
55
+ `restore-files-v2` 支持父目录已存在的普通文件覆盖、创建、删除和混合计划。`restore-files-v3` 在这一基础上允许变更散布于任意数量的父目录:helper 按最多 128 个非根父目录句柄切分批次,并在每批内依次完成 target 准备、source 隔离、target 安装和验证;跨批失败仍由同一 durable pack 执行恢复。单条路径超过 128 层、目录创建/删除、类型替换和不支持的旧 helper 继续使用 TypeScript。durable pack 格式及逐项内容/mode 校验、no-clobber 语义均未变化。
56
+
57
+ 本轮追加验证了 130 个独立子目录的原生恢复及回滚,并对 10,001 个文件进行了两种本机合成 apply 基准:分散于 334 个包目录的混合恢复约 5.0 秒,根目录 10,001 个 delete-only 恢复约 10.2 秒;TypeScript 回退的前一组约 60.5 秒。上述数值仅用于同一台 macOS arm64 工作站上的路径对比,不是 CI 墙钟门槛或其他项目的性能保证。普通文件 10,001 项之外的负载形状、磁盘和平台可能不同。
56
58
 
57
59
  ## 复现与验证
58
60
 
@@ -0,0 +1,34 @@
1
+ # Pi 1.3.0 兼容验证记录
2
+
3
+ 验证对象:`@davideasden/pi-undo` 当前工作树。
4
+
5
+ 验证环境:Pi 1.3.0、Node.js 23.11.1、macOS arm64。生命周期接口以 Pi 1.3.0 的导出类型和 SDK 行为为准;测试使用离线 faux provider,不请求模型网络。
6
+
7
+ ## 结论
8
+
9
+ pi-undo 使用的扩展生命周期、命令、会话树和编辑器 API 在 Pi 1.3.0 上保持兼容。1.3.0 新增的 `before_agent_start` custom run 不会被 pi-undo 误记为用户 Agent run。
10
+
11
+ 后台 durable pack finalization 失败时,当前 runtime 会立即进入 `recovery_required`,并保留事务供 `/undo-recover` 重试。外部文件与 mutation journal 指纹冲突时仍然 fail closed,不会自动猜测回滚或前进方向。
12
+
13
+ ## 验证项目
14
+
15
+ | 检查 | 结果 |
16
+ | --- | --- |
17
+ | `npm run typecheck` | 通过 |
18
+ | `npm test` | 24 个测试文件通过,2 个跳过;642 项通过,5 项跳过 |
19
+ | Pi 1.3.0 扩展类型兼容性 | 通过 |
20
+ | `before_agent_start` 的 `messageType: "custom"` | 不创建 undo run |
21
+ | `before_agent_start` 的 `messageType: "user"` | 保持原有用户 run 生命周期 |
22
+ | finalization failure 的 controller lock | 通过单元测试 |
23
+ | mutation conflict recovery | 保持 fail closed,并显示 `opId` 与处理提示 |
24
+
25
+ ## 关键边界处理
26
+
27
+ - `pi.sendMessage(..., { triggerTurn: true })` 触发的 custom run 没有用户 `input` 边界,pi-undo 跳过 `beforeAgentStart()`。
28
+ - workspace canonical root 变化时,捕获失败原因包含 `workspace_identity_changed`,用户输入继续执行但不会进入撤回历史;提示用户运行 `/undo-recover` 重新发现工作区。
29
+ - 后台 finalization 失败会锁定当前撤回历史,不再静默等待下次启动。
30
+ - `mutation_conflict` 继续保留事务和隔离文件,要求用户先备份并停止其他写入程序,再根据 `opId` 检查现场。
31
+
32
+ ## 剩余限制
33
+
34
+ 未在 Windows 和 Linux 上重复完整测试。`mutation_conflict` 的自动解除仍然被禁止,这是为了避免在外部写入与 pi-undo 操作无法确定先后时造成不可逆覆盖。
@@ -1,6 +1,7 @@
1
1
  import { performance } from "node:perf_hooks";
2
2
 
3
3
  import type {
4
+ BeforeAgentStartEvent,
4
5
  ExtensionAPI,
5
6
  ExtensionCommandContext,
6
7
  ExtensionContext,
@@ -94,7 +95,18 @@ export function createPiUndoExtension(runtimeFactory: PiUndoRuntimeFactory): (pi
94
95
  next.controller.recoveryReason?.() ?? next.recovery?.reason ?? "pending journal",
95
96
  next.recovery,
96
97
  );
97
- } else next.reporter.setReady(history.undoCount, history.redoCount);
98
+ if (next.recovery?.reason === "mutation_conflict") {
99
+ context.ui.notify(
100
+ "pi-undo 检测到外部文件冲突:请先备份工作区,停止其他写入程序,再检查事务后运行 /undo-recover",
101
+ "error",
102
+ );
103
+ }
104
+ } else {
105
+ next.reporter.setReady(history.undoCount, history.redoCount);
106
+ // 首次会话通常没有可复用的 baseline;把冷 capture 提前到空闲时间。
107
+ // 有历史的 resumed session 已经有持久化叶子缓存,不再额外扫描。
108
+ if (history.undoCount === 0 && history.redoCount === 0) next.controller.warmUp();
109
+ }
98
110
  } catch (error) {
99
111
  if (currentGeneration !== generation) return;
100
112
  runtime = undefined;
@@ -283,8 +295,11 @@ export function createPiUndoExtension(runtimeFactory: PiUndoRuntimeFactory): (pi
283
295
  if (active === undefined) return;
284
296
  const history = active.controller.history();
285
297
  if (history.locked) {
298
+ const reason = active.controller.recoveryReason?.() ?? "pending journal";
286
299
  context.ui.notify(
287
- `pi-undo: still locked (${active.controller.recoveryReason?.() ?? "pending journal"}); resolve the blocking session, then run /undo-recover again`,
300
+ reason === "mutation_conflict"
301
+ ? "pi-undo 仍检测到外部文件冲突:请备份工作区和 session,停止其他写入程序,检查事务后再运行 /undo-recover"
302
+ : `pi-undo: still locked (${reason}); resolve the blocking session, then run /undo-recover again`,
288
303
  "warning",
289
304
  );
290
305
  return;
@@ -345,7 +360,7 @@ export function createPiUndoExtension(runtimeFactory: PiUndoRuntimeFactory): (pi
345
360
  captureFailureNotified = true;
346
361
  const reason = active.controller.captureFailureReason();
347
362
  context.ui.notify(
348
- `pi-undo: pre-input snapshot failed${reason === undefined || reason.length === 0 ? "" : ` (${reason})`}; this run will not be undoable`,
363
+ `pi-undo: pre-input snapshot failed${reason === undefined || reason.length === 0 ? "" : ` (${reason})`}; 本次 run 不可撤回。若原因包含 workspace_identity_changed,请运行 /undo-recover 重建 runtime`,
349
364
  "warning",
350
365
  );
351
366
  }
@@ -362,12 +377,15 @@ export function createPiUndoExtension(runtimeFactory: PiUndoRuntimeFactory): (pi
362
377
  captureFailureNotified = true;
363
378
  const reason = active.controller.captureFailureReason();
364
379
  context.ui.notify(
365
- `pi-undo: pre-input snapshot failed${reason === undefined || reason.length === 0 ? "" : ` (${reason})`}; this run will not be undoable`,
380
+ `pi-undo: pre-input snapshot failed${reason === undefined || reason.length === 0 ? "" : ` (${reason})`}; 本次 run 不可撤回。若原因包含 workspace_identity_changed,请运行 /undo-recover 重建 runtime`,
366
381
  "warning",
367
382
  );
368
383
  }
369
384
  });
370
- pi.on("before_agent_start", async () => {
385
+ pi.on("before_agent_start", async (event: BeforeAgentStartEvent) => {
386
+ // pi 1.2+ 还会为 extension-triggered custom run 派发此事件;这种 run
387
+ // 没有 input 阶段,不应被当成一个可撤回的用户 Agent run。
388
+ if (event.messageType === "custom") return;
371
389
  const active = runtime;
372
390
  const startGeneration = generation;
373
391
  if (active === undefined) return;
Binary file
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@davideasden/pi-undo",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Persistent workspace undo and redo for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -37,7 +37,8 @@
37
37
  "README.md",
38
38
  "docs/native-performance.md",
39
39
  "docs/pi-0.86.1-validation.md",
40
- "docs/pi-1.2.0-validation.md"
40
+ "docs/pi-1.2.0-validation.md",
41
+ "docs/pi-1.3.0-validation.md"
41
42
  ],
42
43
  "scripts": {
43
44
  "test": "vitest run",
@@ -56,9 +57,9 @@
56
57
  "proper-lockfile": "4.1.2"
57
58
  },
58
59
  "devDependencies": {
59
- "@earendil-works/pi-ai": "1.2.0",
60
- "@earendil-works/pi-coding-agent": "1.2.0",
61
- "@earendil-works/pi-tui": "1.2.0",
60
+ "@earendil-works/pi-ai": "1.3.0",
61
+ "@earendil-works/pi-coding-agent": "1.3.0",
62
+ "@earendil-works/pi-tui": "1.3.0",
62
63
  "@types/node": "24.12.4",
63
64
  "@types/proper-lockfile": "4.1.4",
64
65
  "typescript": "5.9.3",
package/src/controller.ts CHANGED
@@ -17,6 +17,7 @@ import type {
17
17
  SnapshotManifest,
18
18
  } from "./model.ts";
19
19
  import type { RestorePlan, RestoreResult } from "./restore-engine.ts";
20
+ import type { CaptureDiagnostic } from "./snapshot-store.ts";
20
21
 
21
22
  const INPUT_CAPTURE_RETRY_DELAY_MS = 250;
22
23
 
@@ -44,7 +45,11 @@ export interface ControllerDependencies {
44
45
  readonly appendControl: (customType: string, data?: unknown) => Promise<string | null>;
45
46
  readonly appendCursor: (cursor: CursorState) => Promise<CursorAppendResult>;
46
47
  readonly capture: (scopePaths?: readonly string[]) => Promise<SnapshotManifest>;
47
- readonly captureBaseline?: (baseline: SnapshotManifest) => Promise<SnapshotManifest>;
48
+ readonly captureBaseline?: (
49
+ baseline: SnapshotManifest,
50
+ onDiagnostics?: (diagnostic: CaptureDiagnostic) => void,
51
+ onTiming?: (phase: string, durationMs: number) => void,
52
+ ) => Promise<SnapshotManifest>;
48
53
  readonly captureSafety?: (
49
54
  referenceManifestId: ManifestId,
50
55
  targetManifestId: ManifestId,
@@ -79,6 +84,7 @@ export interface ControllerDependencies {
79
84
  readonly onOperationStart?: (opId: string) => void;
80
85
  readonly onProcess?: (diagnostic: ProcessDiagnostic) => void;
81
86
  readonly onOperationEnd?: (opId: string, result: OperationResult) => Promise<void>;
87
+ readonly onSettlement?: (diagnostic: SettlementDiagnostic) => void | Promise<void>;
82
88
  }
83
89
 
84
90
  export interface JournalPort {
@@ -109,12 +115,24 @@ export interface OperationTiming {
109
115
  readonly durationMs: number;
110
116
  }
111
117
 
118
+ export interface SettlementDiagnostic {
119
+ readonly outcome: "ok" | "failed";
120
+ readonly durationMs: number;
121
+ readonly timings: readonly OperationTiming[];
122
+ readonly changedFiles?: number;
123
+ readonly failureStage?: string;
124
+ readonly failureName?: string;
125
+ readonly failureCode?: string;
126
+ readonly captures?: readonly CaptureDiagnostic[];
127
+ }
128
+
112
129
  export interface OperationResult {
113
130
  readonly code: ResultCode;
114
131
  readonly changedFiles: number;
115
132
  readonly message?: string;
116
133
  readonly refillPrompt?: string;
117
134
  readonly timings?: readonly OperationTiming[];
135
+ readonly settlement?: SettlementDiagnostic;
118
136
  }
119
137
 
120
138
  export type InputEventResult =
@@ -164,6 +182,8 @@ export interface UndoController {
164
182
  cancelOperation?(): boolean;
165
183
  dispose?(): Promise<void>;
166
184
  recover(): Promise<void>;
185
+ /** 后台耐久化失败时锁住当前 runtime,等待显式 recovery。 */
186
+ markRecoveryRequired?(reason: string): void;
167
187
  history(): HistoryState;
168
188
  /** 当前 recovery lock 的原因;未锁定时返回 undefined。 */
169
189
  recoveryReason?(): string | undefined;
@@ -177,6 +197,7 @@ export interface UndoController {
177
197
 
178
198
  interface RunCompletion {
179
199
  started: boolean;
200
+ settlement?: SettlementDiagnostic;
180
201
  readonly promise: Promise<void>;
181
202
  readonly resolve: () => void;
182
203
  }
@@ -226,7 +247,7 @@ export class UndoControllerImpl implements UndoController {
226
247
  private historyPaused = false;
227
248
  private operationInFlight = false;
228
249
  private operationAction: "undo" | "redo" | undefined;
229
- private operationProfiler: OperationProfiler | undefined;
250
+ private lastSettlementDiagnostic: SettlementDiagnostic | undefined;
230
251
  private promptDeferralInFlight = false;
231
252
  private lastSafetyManifestId: ManifestId | null = null;
232
253
  private lastCaptureFailed = false;
@@ -342,6 +363,10 @@ export class UndoControllerImpl implements UndoController {
342
363
  }
343
364
  }
344
365
 
366
+ markRecoveryRequired(reason: string): void {
367
+ this.lock(reason);
368
+ }
369
+
345
370
  private recoveryResult(changedFiles = 0): OperationResult {
346
371
  return {
347
372
  code: "recovery_required",
@@ -356,7 +381,7 @@ export class UndoControllerImpl implements UndoController {
356
381
 
357
382
  warmUp(): void {
358
383
  if (this.disposed || this.locked || this.warmUpInFlight !== undefined) return;
359
- this.warmUpInFlight = this.runBackground(async () => {
384
+ const warmUp = this.runBackground(async () => {
360
385
  try {
361
386
  this.warmUpManifest = await this.captureWithWorkspaceLock();
362
387
  } catch (error) {
@@ -364,6 +389,12 @@ export class UndoControllerImpl implements UndoController {
364
389
  // 预热是 best-effort:失败静默,正式 capture 会再次尝试并上报。
365
390
  }
366
391
  });
392
+ this.warmUpInFlight = warmUp;
393
+ void warmUp.finally(() => {
394
+ if (this.warmUpInFlight === warmUp && this.warmUpManifest === undefined) {
395
+ this.warmUpInFlight = undefined;
396
+ }
397
+ }).catch(() => {});
367
398
  }
368
399
 
369
400
  captureFailureReason(): string | undefined {
@@ -436,6 +467,7 @@ export class UndoControllerImpl implements UndoController {
436
467
  }
437
468
 
438
469
  private beginRun(): RunCompletion {
470
+ this.lastSettlementDiagnostic = undefined;
439
471
  this.finishRun(this.runCompletion);
440
472
  let resolve!: () => void;
441
473
  const promise = new Promise<void>((done) => { resolve = done; });
@@ -485,6 +517,7 @@ export class UndoControllerImpl implements UndoController {
485
517
  if (warmUp !== undefined) await warmUp;
486
518
  const warmUpManifest = this.warmUpManifest;
487
519
  this.warmUpManifest = undefined;
520
+ if (this.warmUpInFlight === warmUp) this.warmUpInFlight = undefined;
488
521
  const capture = (): Promise<SnapshotManifest> => warmUpManifest !== undefined && this.dependencies.captureBaseline !== undefined
489
522
  ? this.captureBaselineWithWorkspaceLock(warmUpManifest)
490
523
  : this.captureWithWorkspaceLock();
@@ -528,15 +561,16 @@ export class UndoControllerImpl implements UndoController {
528
561
  if (this.disposed) return Promise.resolve();
529
562
  if (this.settling !== undefined) return this.settling;
530
563
  const run = this.runCompletion;
531
- const settled = this.runBackground(() => this.settleRun());
564
+ const settled = this.runBackground(() => this.settleRun(run));
532
565
  this.settling = settled.finally(() => {
533
566
  this.settling = undefined;
567
+ // settleRun 成功或失败后都结束本轮等待凭据。
534
568
  this.finishRun(run);
535
569
  });
536
570
  return this.settling;
537
571
  }
538
572
 
539
- private async settleRun(): Promise<void> {
573
+ private async settleRun(run?: RunCompletion): Promise<void> {
540
574
  const staged = this.staged;
541
575
  this.staged = undefined;
542
576
  if (this.disposed || this.locked || staged === undefined) return;
@@ -552,66 +586,121 @@ export class UndoControllerImpl implements UndoController {
552
586
  await this.dependencies.appendControl("pi-undo:barrier", { reason: "user_entry_missing" }).catch(() => {});
553
587
  return;
554
588
  }
555
- const profiler = this.operationProfiler;
556
- const measure = <T>(phase: string, operation: () => Promise<T>): Promise<T> =>
557
- profiler === undefined ? operation() : profiler.measure(phase, operation);
589
+ const phaseTimings: OperationTiming[] = [];
590
+ const captureDiagnostics: CaptureDiagnostic[] = [];
591
+ const recordCaptureTiming = (phase: string, durationMs: number) => {
592
+ try { phaseTimings.push({ phase, durationMs: Math.round(durationMs) }); } catch { /* diagnostics cannot affect capture */ }
593
+ };
594
+ const startedAt = performance.now();
595
+ let failureStage = "settled.capture";
596
+ let failureName: string | undefined;
597
+ let failureCode: string | undefined;
598
+ let changedFiles: number | undefined;
599
+ let outcome: SettlementDiagnostic["outcome"] = "failed";
600
+ const measure = async <T>(phase: string, operation: () => Promise<T>): Promise<T> => {
601
+ this.dependencies.onProgress?.(phase);
602
+ const phaseStartedAt = performance.now();
603
+ try {
604
+ return await operation();
605
+ } finally {
606
+ phaseTimings.push({ phase, durationMs: Math.round(performance.now() - phaseStartedAt) });
607
+ }
608
+ };
558
609
  try {
559
610
  // settled 复用 run 开始时的 before;helper 在缺少 captureBaseline 时回退完整 capture。
560
611
  // 撕裂捕获(并发写撞上断言窗口)是暂态的:短暂退避后重试一次,成功则不清空历史。
561
612
  const after = await measure("settled.capture", () =>
562
- this.captureSettledBaselineWithRetry(staged.before));
613
+ this.captureSettledBaselineWithRetry(
614
+ staged.before,
615
+ (diagnostic) => captureDiagnostics.push(diagnostic),
616
+ recordCaptureTiming,
617
+ ));
618
+ failureStage = "settled.changedPaths";
563
619
  const changedPaths = await measure("settled.changedPaths", () =>
564
620
  this.dependencies.changedPaths(staged.before, after));
565
- if (changedPaths.length > 0 && this.dependencies.prepareDurableRestore !== undefined) {
566
- // /undo 在流式中断后正等待本次 settled;关键路径只预制立即使用的 after → before。
567
- const preparations = this.operationAction === "undo"
568
- ? [measure("settled.prepareUndo", () =>
569
- this.dependencies.prepareDurableRestore!(after, staged.before, changedPaths))]
570
- : [
571
- measure("settled.prepareRedo", () =>
572
- this.dependencies.prepareDurableRestore!(staged.before, after, changedPaths)),
573
- measure("settled.prepareUndo", () =>
574
- this.dependencies.prepareDurableRestore!(after, staged.before, changedPaths)),
575
- ];
576
- const outcomes = await Promise.allSettled(preparations);
577
- for (const outcome of outcomes) {
578
- if (outcome.status === "rejected" && this.recordUnsafeExit(outcome.reason)) throw outcome.reason;
579
- }
580
- checkOperation();
581
- }
621
+ changedFiles = changedPaths.length;
582
622
  const endLeafId = this.dependencies.getLogicalLeafId() ?? staged.startEntryId;
583
623
  const checkpoint = this.createCheckpoint(staged, after, changedPaths, userEntryId, endLeafId);
624
+ failureStage = "settled.checkpoint";
584
625
  const checkpointEntryId = await measure("settled.checkpoint", () =>
585
626
  this.dependencies.appendControl("pi-undo:checkpoint", checkpoint));
586
627
  if (checkpointEntryId === null) {
628
+ failureStage = "checkpoint_entry_missing";
587
629
  this.lock("checkpoint_entry_missing");
588
630
  await this.dependencies.appendControl("pi-undo:barrier", { reason: "checkpoint_entry_missing" }).catch(() => {});
589
631
  return;
590
632
  }
633
+ outcome = "ok";
591
634
  this.undoStack.push(checkpoint);
635
+ // agentSettled 的 finally 会在结算摘要写入 run 后解除等待;durable pack 继续后台预制。
636
+ // applyRestore 有惰性路径,可在预制未完成时现场创建 durable pack。
637
+ // 两个方向放在同一个后台任务里串行:并发创建两份 durable pack 会让文件 IO
638
+ // 与事件循环压力翻倍,大工作区下足以让 TUI 按键(含 Esc 中断)得不到处理。
639
+ if (changedPaths.length > 0 && this.dependencies.prepareDurableRestore !== undefined) {
640
+ const prepareDurable = this.runBackground(async () => {
641
+ try {
642
+ // undo 是撤回时立即需要的方向,优先预制。
643
+ await this.dependencies.prepareDurableRestore!(after, staged.before, changedPaths);
644
+ if (this.operationAction !== "undo") {
645
+ await this.dependencies.prepareDurableRestore!(staged.before, after, changedPaths);
646
+ }
647
+ } catch (error) {
648
+ // 两个方向都有安全的惰性路径;后台预制失败不应暂停当前历史。
649
+ this.recordUnsafeExit(error);
650
+ }
651
+ });
652
+ void prepareDurable.catch(() => {});
653
+ }
592
654
  } catch (error) {
655
+ const candidate = error as { name?: unknown; code?: unknown };
656
+ failureName = safeDiagnosticLabel(candidate.name) ?? "Error";
657
+ failureCode = safeDiagnosticLabel(candidate.code);
593
658
  this.recordUnsafeExit(error);
594
659
  this.historyPaused = true;
595
660
  this.undoStack.length = 0;
596
661
  this.redoStack.length = 0;
597
662
  await this.dependencies.appendControl("pi-undo:barrier", { reason: "settled_capture_failed" }).catch(() => {});
663
+ } finally {
664
+ const diagnostic: SettlementDiagnostic = {
665
+ outcome,
666
+ durationMs: Math.round(performance.now() - startedAt),
667
+ timings: phaseTimings,
668
+ ...(changedFiles === undefined ? {} : { changedFiles }),
669
+ ...(outcome === "failed" ? { failureStage, failureName, ...(failureCode === undefined ? {} : { failureCode }) } : {}),
670
+ ...(captureDiagnostics.length === 0 ? {} : { captures: captureDiagnostics }),
671
+ };
672
+ if (run !== undefined) run.settlement = diagnostic;
673
+ this.lastSettlementDiagnostic = diagnostic;
674
+ try {
675
+ const report = this.dependencies.onSettlement?.(diagnostic);
676
+ if (report !== undefined) void Promise.resolve(report).catch(() => {});
677
+ } catch { /* 诊断写入失败不能改变检查点结果 */ }
598
678
  }
599
679
  }
600
680
 
601
681
  async undo(): Promise<OperationResult> {
602
682
  if (this.locked) return this.recoveryResult();
603
- if (this.historyPaused) return { code: "history_paused", changedFiles: 0 };
683
+ if (this.historyPaused) return this.historyPausedResult();
604
684
  return this.runOperation("undo");
605
685
  }
606
686
 
607
687
  async redo(): Promise<OperationResult> {
608
688
  if (this.locked) return this.recoveryResult();
609
- if (this.historyPaused) return { code: "history_paused", changedFiles: 0 };
689
+ if (this.historyPaused) return this.historyPausedResult();
610
690
  // 新 run 开始时 redo frontier 已失效;空栈命令不得为了确认 noop 而中断正在运行的 Agent。
611
691
  if (this.redoStack.length === 0) return noop();
612
692
  return this.runOperation("redo");
613
693
  }
614
694
 
695
+ private historyPausedResult(): OperationResult {
696
+ const settlement = this.lastSettlementDiagnostic;
697
+ return {
698
+ code: "history_paused",
699
+ changedFiles: 0,
700
+ ...(settlement === undefined ? {} : { settlement, timings: settlement.timings }),
701
+ };
702
+ }
703
+
615
704
  beforeTree(event: SessionBeforeTreeEvent): Promise<SessionBeforeTreeResult | undefined> {
616
705
  if (this.treeScope !== undefined) return Promise.resolve({ cancel: true });
617
706
  this.treeCancellationRequested = event.signal?.aborted ?? false;
@@ -808,24 +897,31 @@ export class UndoControllerImpl implements UndoController {
808
897
  if (this.locked) return this.recoveryResult();
809
898
  if (this.operationInFlight) return { code: "busy", changedFiles: 0 };
810
899
  const profile = new OperationProfiler(this.dependencies.onProgress);
811
- const done = (result: OperationResult): OperationResult => profile.attach(result);
900
+ let settlement: SettlementDiagnostic | undefined;
901
+ const done = (result: OperationResult): OperationResult => profile.attach({
902
+ ...result,
903
+ ...(settlement === undefined || (settlement.outcome === "ok" && settlement.durationMs < 1_000)
904
+ ? {} : { settlement }),
905
+ });
812
906
  this.operationInFlight = true;
813
907
  this.operationAction = action;
814
- this.operationProfiler = profile;
815
908
  this.promptDeferralInFlight = true;
816
909
  this.lastSafetyManifestId = null;
817
910
  let lease: { release(): Promise<void> } | undefined;
818
911
  try {
912
+ const checkpointRun = this.runCompletion;
819
913
  const [idleReady, checkpointReady] = await Promise.all([
820
914
  profile.measure("idle", () => this.ensureIdle()),
821
915
  profile.measure("checkpoint", () => this.waitForCheckpoint()),
822
916
  ]);
917
+ settlement = checkpointRun?.settlement;
918
+ if (settlement !== undefined) profile.addSettlement(settlement);
823
919
  if (!idleReady || !checkpointReady) {
824
920
  checkOperation();
825
921
  return done({ code: "idle_timeout", changedFiles: 0 });
826
922
  }
827
923
  if (this.locked) return done(this.recoveryResult());
828
- if (this.historyPaused) return done({ code: "history_paused", changedFiles: 0 });
924
+ if (this.historyPaused) return done(this.historyPausedResult());
829
925
  if (this.disposed) return done({ code: "busy", changedFiles: 0 });
830
926
  // Pi 空闲早于扩展 settled 完成;只有本轮完成凭据已终结才能选择目标。
831
927
  const redo = action === "redo" ? this.redoStack.at(-1) : undefined;
@@ -950,7 +1046,6 @@ export class UndoControllerImpl implements UndoController {
950
1046
  await profile.measure("unlock", () =>
951
1047
  activeLease.release().catch(() => { this.lock("workspace_lock_release_failed"); }));
952
1048
  }
953
- if (this.operationProfiler === profile) this.operationProfiler = undefined;
954
1049
  this.operationAction = undefined;
955
1050
  this.promptDeferralInFlight = false;
956
1051
  this.operationInFlight = false;
@@ -1122,16 +1217,28 @@ export class UndoControllerImpl implements UndoController {
1122
1217
  }
1123
1218
  }
1124
1219
 
1125
- private async captureBaselineWithWorkspaceLock(baseline: SnapshotManifest): Promise<SnapshotManifest> {
1220
+ private async captureBaselineWithWorkspaceLock(
1221
+ baseline: SnapshotManifest,
1222
+ onDiagnostics?: (diagnostic: CaptureDiagnostic) => void,
1223
+ onTiming?: (phase: string, durationMs: number) => void,
1224
+ ): Promise<SnapshotManifest> {
1126
1225
  const captureBaseline = this.dependencies.captureBaseline;
1127
1226
  if (captureBaseline === undefined) return this.captureWithWorkspaceLock();
1128
- const lease = await this.dependencies.acquireWorkspaceLock();
1227
+ const lockStartedAt = performance.now();
1228
+ let lease: Awaited<ReturnType<ControllerDependencies["acquireWorkspaceLock"]>>;
1229
+ try {
1230
+ lease = await this.dependencies.acquireWorkspaceLock();
1231
+ } finally {
1232
+ reportCaptureTiming(onTiming, "settled.workspaceLock", performance.now() - lockStartedAt);
1233
+ }
1234
+ const captureStartedAt = performance.now();
1129
1235
  try {
1130
- return await captureBaseline(baseline);
1236
+ return await captureBaseline(baseline, onDiagnostics, onTiming);
1131
1237
  } catch (error) {
1132
1238
  this.recordUnsafeExit(error);
1133
1239
  throw error;
1134
1240
  } finally {
1241
+ reportCaptureTiming(onTiming, "settled.captureBaseline", performance.now() - captureStartedAt);
1135
1242
  if (!this.unsafeExit) await lease.release();
1136
1243
  }
1137
1244
  }
@@ -1141,14 +1248,20 @@ export class UndoControllerImpl implements UndoController {
1141
1248
  * (捕获期间叶子变化)或短暂持有 workspace lock。settled 失败会清空整个 undo 历史,
1142
1249
  * 不能因一次暂态冲突就放弃;持续失败仍由调用方走原有 historyPaused 路径。
1143
1250
  */
1144
- private async captureSettledBaselineWithRetry(baseline: SnapshotManifest): Promise<SnapshotManifest> {
1251
+ private async captureSettledBaselineWithRetry(
1252
+ baseline: SnapshotManifest,
1253
+ onDiagnostics?: (diagnostic: CaptureDiagnostic) => void,
1254
+ onTiming?: (phase: string, durationMs: number) => void,
1255
+ ): Promise<SnapshotManifest> {
1145
1256
  try {
1146
- return await this.captureBaselineWithWorkspaceLock(baseline);
1257
+ return await this.captureBaselineWithWorkspaceLock(baseline, onDiagnostics, onTiming);
1147
1258
  } catch (error) {
1148
1259
  rethrowOperationFailure(error);
1149
1260
  if (!isTransientCaptureFailure(error)) throw error;
1261
+ const retryStartedAt = performance.now();
1150
1262
  await sleep(250);
1151
- return await this.captureBaselineWithWorkspaceLock(baseline);
1263
+ onTiming?.("settled.captureRetryDelay", performance.now() - retryStartedAt);
1264
+ return await this.captureBaselineWithWorkspaceLock(baseline, onDiagnostics, onTiming);
1152
1265
  }
1153
1266
  }
1154
1267
 
@@ -1320,6 +1433,7 @@ function emptyRestorePlan(currentManifestId: ManifestId, targetManifestId: Manif
1320
1433
 
1321
1434
  class OperationProfiler {
1322
1435
  private readonly durations = new Map<string, number>();
1436
+ private settlementTimings: readonly OperationTiming[] = [];
1323
1437
 
1324
1438
  constructor(private readonly onProgress?: (phase: string) => void) {}
1325
1439
 
@@ -1330,19 +1444,30 @@ class OperationProfiler {
1330
1444
  try {
1331
1445
  return await operation();
1332
1446
  } finally {
1333
- this.durations.set(phase, (this.durations.get(phase) ?? 0) + performance.now() - started);
1447
+ this.record(phase, performance.now() - started);
1334
1448
  }
1335
1449
  }
1336
1450
 
1451
+ record(phase: string, durationMs: number): void {
1452
+ this.durations.set(phase, (this.durations.get(phase) ?? 0) + durationMs);
1453
+ }
1454
+
1455
+ addSettlement(settlement: SettlementDiagnostic): void {
1456
+ this.settlementTimings = settlement.timings;
1457
+ }
1458
+
1337
1459
  attach(result: OperationResult): OperationResult {
1338
1460
  const total = [...this.durations.values()].reduce((sum, duration) => sum + duration, 0);
1339
1461
  if (total < 1_000) return result;
1340
1462
  return {
1341
1463
  ...result,
1342
- timings: [...this.durations].map(([phase, durationMs]) => ({
1343
- phase,
1344
- durationMs: Math.round(durationMs),
1345
- })),
1464
+ timings: [
1465
+ ...([...this.durations].map(([phase, durationMs]) => ({
1466
+ phase,
1467
+ durationMs: Math.round(durationMs),
1468
+ }))),
1469
+ ...this.settlementTimings,
1470
+ ],
1346
1471
  };
1347
1472
  }
1348
1473
  }
@@ -1371,6 +1496,18 @@ function noop(): OperationResult {
1371
1496
  return { code: "noop", changedFiles: 0 };
1372
1497
  }
1373
1498
 
1499
+ function reportCaptureTiming(
1500
+ callback: ((phase: string, durationMs: number) => void) | undefined,
1501
+ phase: string,
1502
+ durationMs: number,
1503
+ ): void {
1504
+ try { callback?.(phase, durationMs); } catch { /* diagnostics cannot affect capture */ }
1505
+ }
1506
+
1507
+ function safeDiagnosticLabel(value: unknown): string | undefined {
1508
+ return typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(value) ? value : undefined;
1509
+ }
1510
+
1374
1511
  function truncateReason(reason: string): string {
1375
1512
  return reason.replace(/[\u0000-\u001F\u007F]+/g, " ").trim().slice(0, 120);
1376
1513
  }
@@ -24,7 +24,7 @@ export async function createNativeFileBatch(options: {
24
24
  readonly journal: MutationJournal;
25
25
  /** 测试注入用;默认使用随包分发的平台二进制。 */
26
26
  readonly executable?: string;
27
- readonly requiredCapability?: "restore-files-v2";
27
+ readonly requiredCapability?: "restore-files-v2" | "restore-files-v3";
28
28
  }): Promise<NativeFileBatch | undefined> {
29
29
  if (process.env.PI_UNDO_DISABLE_NATIVE === "1") return undefined;
30
30
  const executable = options.executable ?? nativeExecutable();
@@ -90,11 +90,26 @@ export async function createNativeFileBatch(options: {
90
90
  };
91
91
  }
92
92
 
93
- export function nativeRestoreCapability(pack: DurablePack): "restore-files-v2" | undefined {
93
+ function nativeRestoreBatchRequired(paths: readonly string[]): boolean {
94
+ if (process.platform === "win32") return false;
95
+ const parents = new Set<string>();
96
+ for (const path of paths) {
97
+ const parentEnd = path.lastIndexOf("/");
98
+ let separator = path.indexOf("/");
99
+ while (separator !== -1 && separator <= parentEnd) {
100
+ parents.add(path.slice(0, separator));
101
+ if (parents.size > 128) return true;
102
+ separator = path.indexOf("/", separator + 1);
103
+ }
104
+ }
105
+ return false;
106
+ }
107
+
108
+ export function nativeRestoreCapability(pack: DurablePack): "restore-files-v2" | "restore-files-v3" | undefined {
94
109
  const paths = pack.paths();
95
110
  const deletes = paths.filter((path) => pack.artifacts(path)?.target === null);
96
- return deletes.some((path) => path.includes("/")) || (deletes.length > 0 && deletes.length < paths.length)
97
- ? "restore-files-v2" : undefined;
111
+ const requiresV2 = deletes.some((path) => path.includes("/")) || (deletes.length > 0 && deletes.length < paths.length);
112
+ return nativeRestoreBatchRequired(paths) ? "restore-files-v3" : requiresV2 ? "restore-files-v2" : undefined;
98
113
  }
99
114
 
100
115
  export function nativeExecutable(): string | undefined {
package/src/pi-runtime.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  UndoControllerImpl,
12
12
  type ControllerDependencies,
13
13
  type ControllerInitialState,
14
+ type SettlementDiagnostic,
14
15
  } from "./controller.ts";
15
16
  import { finalizeDurablePack, hasDurablePack, loadDurablePack } from "./durable-pack.ts";
16
17
  import { assertCursor, canonicalJson, checksum, sameWorkspaceSnapshot } from "./encoding.ts";
@@ -24,9 +25,9 @@ import {
24
25
  import { JournalRecovery } from "./recovery.ts";
25
26
  import { QuarantineManager } from "./quarantine.ts";
26
27
  import { RestoreEngine } from "./restore-engine.ts";
27
- import { RootDiscovery } from "./root-discovery.ts";
28
+ import { RootDiscovery, type RootTopology } from "./root-discovery.ts";
28
29
  import { DurableCursorWriter, SessionState, type SessionEntrySource } from "./session-state.ts";
29
- import { SnapshotStore } from "./snapshot-store.ts";
30
+ import { SnapshotStore, type CaptureDiagnostic } from "./snapshot-store.ts";
30
31
  import { StatusReporter } from "./status-reporter.ts";
31
32
  import { WorkspaceLock } from "./workspace-lock.ts";
32
33
  import { allCompleted, checkOperation, configuredTimeout, currentOperationContext, isUnconfirmedExit, operationHasUnconfirmedExit, runWithOperationContext, withRecoveryBudget, type ProcessDiagnostic } from "./operation-context.ts";
@@ -58,16 +59,30 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
58
59
  const capture = async (scopePaths?: readonly string[]) => {
59
60
  const topology = await discovery.discover(context.cwd);
60
61
  if (topology.workspaceIdentity !== initialTopology.workspaceIdentity) {
61
- throw new Error("workspace identity 已变化");
62
+ throw new Error("workspace_identity_changed: workspace root canonical path changed; run /undo-recover");
62
63
  }
63
64
  return store.capture(topology, scopePaths, { topologyAlreadyValidated: true });
64
65
  };
65
- const captureBaseline = async (baseline: SnapshotManifest) => {
66
- const topology = await discovery.discover(context.cwd);
66
+ const captureBaseline = async (
67
+ baseline: SnapshotManifest,
68
+ onDiagnostics?: (diagnostic: CaptureDiagnostic) => void,
69
+ onTiming?: (phase: string, durationMs: number) => void,
70
+ ) => {
71
+ const discoveryStartedAt = performance.now();
72
+ let topology: RootTopology;
73
+ try {
74
+ topology = await discovery.discover(context.cwd);
75
+ } finally {
76
+ try { onTiming?.("settled.rootDiscovery", performance.now() - discoveryStartedAt); } catch { /* diagnostics must not affect capture */ }
77
+ }
67
78
  if (topology.workspaceIdentity !== initialTopology.workspaceIdentity) {
68
- throw new Error("workspace identity 已变化");
79
+ throw new Error("workspace_identity_changed: workspace root canonical path changed; run /undo-recover");
69
80
  }
70
- return store.captureBaseline(topology, baseline, undefined, { topologyAlreadyValidated: true });
81
+ return store.captureBaseline(topology, baseline, undefined, {
82
+ topologyAlreadyValidated: true,
83
+ onDiagnostics,
84
+ onTiming,
85
+ });
71
86
  };
72
87
  const recovery = new JournalRecovery({
73
88
  sessionIdentity,
@@ -150,6 +165,7 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
150
165
 
151
166
  let finalizationQueue: Promise<void> = Promise.resolve();
152
167
  let finalizationFailure: unknown;
168
+ let controller: UndoControllerImpl | undefined;
153
169
  const waitForFinalization = async (): Promise<void> => {
154
170
  await finalizationQueue;
155
171
  if (finalizationFailure !== undefined) throw finalizationFailure;
@@ -179,6 +195,9 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
179
195
  }
180
196
  }))).catch((error: unknown) => {
181
197
  finalizationFailure = error;
198
+ controller?.markRecoveryRequired(`finalization_failed:${opId}`);
199
+ reporter.setRecoveryRequired(`finalization_failed:${opId}`);
200
+ context.ui.notify(`pi-undo 后台持久化失败(op:${opId}):已锁定撤回历史,请运行 /undo-recover 重试`, "error");
182
201
  });
183
202
  };
184
203
  const transactionJournal: ControllerDependencies["journal"] = {
@@ -293,7 +312,15 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
293
312
  const totalMs = Math.round(performance.now() - operationStarted);
294
313
  if (totalMs < 1_000 && (result.code === "ok" || result.code === "noop")) return;
295
314
  await writeJsonAtomic(join(privateRoot, "diagnostics", `${manager.getSessionId()}-latest.json`), {
296
- schemaVersion: 1, opId, code: result.code, totalMs, phases, processes: diagnostics,
315
+ schemaVersion: 1, opId, code: result.code, totalMs, phases,
316
+ operationTimings: result.timings ?? [], settlement: result.settlement ?? null, processes: diagnostics,
317
+ });
318
+ },
319
+ onSettlement: async (settlement: SettlementDiagnostic) => {
320
+ if (settlement.outcome === "ok" && settlement.durationMs < 1_000) return;
321
+ await writeJsonAtomic(join(privateRoot, "diagnostics", `${manager.getSessionId()}-settlement-diagnostic.json`), {
322
+ schemaVersion: 1,
323
+ settlement,
297
324
  });
298
325
  },
299
326
  };
@@ -301,14 +328,16 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
301
328
  initialTopology.workspaceIdentity,
302
329
  () => recovery.recover(),
303
330
  );
304
- const controller = new UndoControllerImpl(dependencies, {
331
+ controller = new UndoControllerImpl(dependencies, {
305
332
  ...rebuildControllerState(manager, sessionIdentity),
306
333
  locked: startupRecovery.kind === "locked",
307
334
  recoveryReason: startupRecovery.kind === "locked" ? startupRecovery.reason : undefined,
308
335
  recoveryCompleted: true,
309
336
  });
337
+ const activeController = controller;
338
+ if (activeController === undefined) throw new Error("pi-undo controller 初始化失败");
310
339
  return {
311
- controller,
340
+ controller: activeController,
312
341
  reporter,
313
342
  diffSource: store,
314
343
  recovery: startupRecovery.kind === "locked"
@@ -316,7 +345,7 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
316
345
  : undefined,
317
346
  async dispose(): Promise<void> {
318
347
  try {
319
- await controller.dispose();
348
+ await activeController.dispose();
320
349
  await finalizationQueue;
321
350
  if (isUnconfirmedExit(finalizationFailure)) throw finalizationFailure;
322
351
  } finally {
@@ -898,7 +898,10 @@ export class RestoreEngine {
898
898
  );
899
899
  }
900
900
  const durablePackEnabled = durablePack !== undefined;
901
- if (nativeFileBatch !== undefined && durablePack !== undefined && this.canUseNativeFilePlan(plan, currentPaths, targetPaths)) {
901
+ if (
902
+ nativeFileBatch !== undefined && durablePack !== undefined &&
903
+ this.canUseNativeFilePlan(plan, currentPaths, targetPaths)
904
+ ) {
902
905
  const result = await this.applyNativeFilePlan(
903
906
  plan,
904
907
  current,
@@ -1018,9 +1021,8 @@ export class RestoreEngine {
1018
1021
  if (!plan.writePaths.every((path) =>
1019
1022
  targetPaths.get(path)?.entry.kind === "file" &&
1020
1023
  (currentPaths.get(path) === undefined || currentPaths.get(path)?.entry.kind === "file"))) return false;
1021
- // 与 helper 的句柄上限一致;目录创建、类型替换及过多父目录继续使用 TypeScript。
1022
- const parents = new Set([...plan.deletePaths, ...plan.writePaths].flatMap(strictPathAncestors));
1023
- return process.platform === "win32" || parents.size <= 128;
1024
+ const paths = [...plan.deletePaths, ...plan.writePaths];
1025
+ return process.platform === "win32" || paths.every((path) => strictPathAncestors(path).length <= 128);
1024
1026
  }
1025
1027
 
1026
1028
  private async applyNativeFilePlan(
@@ -39,6 +39,8 @@ export interface RootTopology {
39
39
  readonly workspaceIdentity: string;
40
40
  readonly roots: readonly DiscoveryRoot[];
41
41
  readonly fingerprint: string;
42
+ /** 本次扫描检查的目录数,仅供性能诊断,不参与 identity/fingerprint。 */
43
+ readonly directoriesVisited?: number;
42
44
  }
43
45
 
44
46
  /**
@@ -119,6 +121,7 @@ export class RootDiscovery {
119
121
  workspaceIdentity,
120
122
  roots,
121
123
  fingerprint: topologyFingerprint(workspaceIdentity, roots),
124
+ directoriesVisited: this.lastDirectoryCount ?? 0,
122
125
  };
123
126
  }
124
127
 
@@ -98,6 +98,7 @@ interface VisibleLeafMetadata {
98
98
  interface VisibleLeaf {
99
99
  readonly relativePath: string;
100
100
  readonly kind: "file" | "symlink";
101
+ readonly size?: number;
101
102
  readonly mode: number;
102
103
  readonly fingerprint: string;
103
104
  /** 不含 ctime,用于把 macOS 元数据写入与内容或路径变化区分开。 */
@@ -145,6 +146,76 @@ interface PersistedLeafCacheEntry {
145
146
  readonly verifiedAtNs: string;
146
147
  }
147
148
 
149
+ export interface CaptureDiagnostic {
150
+ readonly strategy: "full" | "baseline-check" | "baseline-reused" | "baseline-fallback";
151
+ readonly rootCount: number;
152
+ readonly directoriesVisited: number;
153
+ readonly visibleFilesInspected: number;
154
+ readonly baselineProbeFiles: number;
155
+ readonly cacheHits: number;
156
+ readonly hashFilesPlanned: number;
157
+ readonly symlinksPlanned: number;
158
+ readonly hashCommandsPlanned: number;
159
+ readonly hashBytesPlanned: number;
160
+ readonly ignoredFiles: number;
161
+ readonly failureName?: string;
162
+ readonly failureCode?: string;
163
+ }
164
+
165
+ interface MutableCaptureDiagnostic {
166
+ strategy: CaptureDiagnostic["strategy"];
167
+ rootCount: number;
168
+ directoriesVisited: number;
169
+ visibleFilesInspected: number;
170
+ baselineProbeFiles: number;
171
+ cacheHits: number;
172
+ hashFilesPlanned: number;
173
+ symlinksPlanned: number;
174
+ hashCommandsPlanned: number;
175
+ hashBytesPlanned: number;
176
+ ignoredFiles: number;
177
+ failureName?: string;
178
+ failureCode?: string;
179
+ }
180
+
181
+ function createCaptureDiagnostic(
182
+ strategy: CaptureDiagnostic["strategy"],
183
+ rootCount: number,
184
+ directoriesVisited: number,
185
+ ): MutableCaptureDiagnostic {
186
+ return {
187
+ strategy, rootCount, directoriesVisited, visibleFilesInspected: 0, baselineProbeFiles: 0, cacheHits: 0,
188
+ hashFilesPlanned: 0, symlinksPlanned: 0, hashCommandsPlanned: 0, hashBytesPlanned: 0, ignoredFiles: 0,
189
+ };
190
+ }
191
+
192
+ function sumSaturated(left: number, right: number): number {
193
+ return Math.min(Number.MAX_SAFE_INTEGER, left + right);
194
+ }
195
+
196
+ function publishCaptureTiming(callback: CaptureOptions["onTiming"], phase: string, startedAt: number): void {
197
+ try { callback?.(phase, performance.now() - startedAt); } catch { /* diagnostics cannot affect snapshot correctness */ }
198
+ }
199
+
200
+ function safeDiagnosticLabel(value: unknown): string | undefined {
201
+ return typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(value) ? value : undefined;
202
+ }
203
+
204
+ function publishCaptureDiagnostic(
205
+ callback: CaptureOptions["onDiagnostics"],
206
+ diagnostic: MutableCaptureDiagnostic,
207
+ error?: unknown,
208
+ ): void {
209
+ if (error !== undefined) {
210
+ const candidate = error as { name?: unknown; code?: unknown };
211
+ const failureName = safeDiagnosticLabel(candidate.name);
212
+ const failureCode = safeDiagnosticLabel(candidate.code);
213
+ if (failureName !== undefined) diagnostic.failureName = failureName;
214
+ if (failureCode !== undefined) diagnostic.failureCode = failureCode;
215
+ }
216
+ try { callback?.({ ...diagnostic }); } catch { /* diagnostics cannot affect snapshot correctness */ }
217
+ }
218
+
148
219
  export interface SnapshotStoreOptions {
149
220
  readonly storeRoot?: string;
150
221
  readonly git?: GitRunner;
@@ -161,6 +232,10 @@ export interface CaptureOptions {
161
232
  * 因此校验窗口内出现的漂移依然会被拒绝。仅限调用方与本次枚举之间没有文件变更时使用。
162
233
  */
163
234
  readonly topologyAlreadyValidated?: boolean;
235
+ /** 只报告数量和错误类型,不包含路径、文件内容或异常消息。 */
236
+ readonly onDiagnostics?: (diagnostic: CaptureDiagnostic) => void;
237
+ /** 报告 capture 内部 wall-time 阶段;回调失败不影响捕获。 */
238
+ readonly onTiming?: (phase: string, durationMs: number) => void;
164
239
  }
165
240
 
166
241
  export interface VisibleLeafOptions extends CaptureOptions {
@@ -279,15 +354,26 @@ export class SnapshotStore {
279
354
  scope?: readonly string[],
280
355
  options: CaptureOptions = {},
281
356
  ): Promise<SnapshotManifest> {
282
- await this.assertPrivateStore(topology.workspaceIdentity);
283
- const lockIdentity = `snapshot-store:${await prospectiveCanonicalPath(this.storesRoot)}`;
284
- return this.lock.withLock(lockIdentity, () => this.captureLocked(topology, scope, options));
357
+ const diagnostic = createCaptureDiagnostic("full", topology.roots.length, topology.directoriesVisited ?? 0);
358
+ let reported = false;
359
+ try {
360
+ await this.assertPrivateStore(topology.workspaceIdentity);
361
+ const lockIdentity = `snapshot-store:${await prospectiveCanonicalPath(this.storesRoot)}`;
362
+ return await this.lock.withLock(lockIdentity, () => this.captureLocked(topology, scope, options, diagnostic));
363
+ } catch (error) {
364
+ reported = true;
365
+ publishCaptureDiagnostic(options.onDiagnostics, diagnostic, error);
366
+ throw error;
367
+ } finally {
368
+ if (!reported) publishCaptureDiagnostic(options.onDiagnostics, diagnostic);
369
+ }
285
370
  }
286
371
 
287
372
  private async captureLocked(
288
373
  topology: RootTopology,
289
374
  scope: readonly string[] | undefined,
290
375
  options: CaptureOptions,
376
+ diagnostic?: MutableCaptureDiagnostic,
291
377
  ): Promise<SnapshotManifest> {
292
378
  let transactionDirectory: string | undefined;
293
379
  try {
@@ -335,6 +421,7 @@ export class SnapshotStore {
335
421
  activeTransactionDirectory,
336
422
  scope,
337
423
  artifactExclusions,
424
+ diagnostic,
338
425
  );
339
426
  return {
340
427
  root: snapshotRoot(root, captured),
@@ -389,9 +476,19 @@ export class SnapshotStore {
389
476
  scope?: readonly string[],
390
477
  options: CaptureOptions = {},
391
478
  ): Promise<SnapshotManifest> {
392
- await this.assertPrivateStore(topology.workspaceIdentity);
393
- const lockIdentity = `snapshot-store:${await prospectiveCanonicalPath(this.storesRoot)}`;
394
- return this.lock.withLock(lockIdentity, () => this.captureBaselineLocked(topology, baseline, scope, options));
479
+ const diagnostic = createCaptureDiagnostic("baseline-check", topology.roots.length, topology.directoriesVisited ?? 0);
480
+ let reported = false;
481
+ try {
482
+ await this.assertPrivateStore(topology.workspaceIdentity);
483
+ const lockIdentity = `snapshot-store:${await prospectiveCanonicalPath(this.storesRoot)}`;
484
+ return await this.lock.withLock(lockIdentity, () => this.captureBaselineLocked(topology, baseline, scope, options, diagnostic));
485
+ } catch (error) {
486
+ reported = true;
487
+ publishCaptureDiagnostic(options.onDiagnostics, diagnostic, error);
488
+ throw error;
489
+ } finally {
490
+ if (!reported) publishCaptureDiagnostic(options.onDiagnostics, diagnostic);
491
+ }
395
492
  }
396
493
 
397
494
  private async captureBaselineLocked(
@@ -399,6 +496,7 @@ export class SnapshotStore {
399
496
  baseline: SnapshotManifest,
400
497
  scope: readonly string[] | undefined,
401
498
  options: CaptureOptions,
499
+ diagnostic?: MutableCaptureDiagnostic,
402
500
  ): Promise<SnapshotManifest> {
403
501
  try {
404
502
  if (topology.fingerprint !== topologyFingerprint(topology.workspaceIdentity, topology.roots)) {
@@ -411,13 +509,27 @@ export class SnapshotStore {
411
509
  if (brokenRoots.length > 0) {
412
510
  throw new SnapshotStoreError("capture_failed", `broken root 不能静默进入 baseline 校验: ${brokenRoots.join(", ")}`);
413
511
  }
414
- if (await this.isBaselineFresh(topology, baseline, scope, options)) {
512
+ const baselineValidationStartedAt = performance.now();
513
+ let baselineFresh: boolean;
514
+ try {
515
+ baselineFresh = await this.isBaselineFresh(topology, baseline, scope, options, diagnostic);
516
+ } finally {
517
+ publishCaptureTiming(options.onTiming, "settled.baselineValidation", baselineValidationStartedAt);
518
+ }
519
+ if (baselineFresh) {
520
+ if (diagnostic !== undefined) diagnostic.strategy = "baseline-reused";
415
521
  await this.assertTopology(topology, "捕获期间 topology 已变化", "safety-snapshot");
416
522
  await this.touchStore(this.storeDirectory(topology));
417
523
  return baseline;
418
524
  }
419
525
  // 已完成一次捕获前 topology 校验;完整回退仍保留捕获后的校验。
420
- return this.captureLocked(topology, scope, { ...options, topologyAlreadyValidated: true });
526
+ if (diagnostic !== undefined) diagnostic.strategy = "baseline-fallback";
527
+ const fullCaptureStartedAt = performance.now();
528
+ try {
529
+ return await this.captureLocked(topology, scope, { ...options, topologyAlreadyValidated: true }, diagnostic);
530
+ } finally {
531
+ publishCaptureTiming(options.onTiming, "settled.fullCapture", fullCaptureStartedAt);
532
+ }
421
533
  } catch (error) {
422
534
  if (error instanceof SnapshotStoreError) {
423
535
  throw error;
@@ -431,6 +543,7 @@ export class SnapshotStore {
431
543
  baseline: SnapshotManifest,
432
544
  scope: readonly string[] | undefined,
433
545
  options: CaptureOptions,
546
+ diagnostic?: MutableCaptureDiagnostic,
434
547
  ): Promise<boolean> {
435
548
  try {
436
549
  assertManifest(baseline);
@@ -509,6 +622,10 @@ export class SnapshotStore {
509
622
  exactExclusions,
510
623
  transactionDirectory,
511
624
  );
625
+ if (diagnostic !== undefined) {
626
+ diagnostic.visibleFilesInspected += leaves.length;
627
+ diagnostic.baselineProbeFiles += leaves.length;
628
+ }
512
629
  if (!samePathList(
513
630
  leaves.map((leaf) => leaf.relativePath).sort(comparePaths),
514
631
  entries.map((entry) => entry.relativePath).sort(comparePaths),
@@ -534,6 +651,7 @@ export class SnapshotStore {
534
651
  ) {
535
652
  return false;
536
653
  }
654
+ if (diagnostic !== undefined) diagnostic.cacheHits += 1;
537
655
  }
538
656
 
539
657
  const ignoredPresentPaths = await this.captureIgnoredPresentPaths(
@@ -545,6 +663,7 @@ export class SnapshotStore {
545
663
  exactExclusions,
546
664
  transactionDirectory,
547
665
  );
666
+ if (diagnostic !== undefined) diagnostic.ignoredFiles += ignoredPresentPaths.length;
548
667
  if (!samePathList(ignoredPresentPaths, baselineRoot.ignoredPresentPaths)) return false;
549
668
  if (baselineRoot.ignoreClosure !== ignoredPresentClosure({
550
669
  coverage: baselineRoot.coverage,
@@ -1005,6 +1124,7 @@ export class SnapshotStore {
1005
1124
  transactionDirectory: string,
1006
1125
  scope: readonly string[] | undefined,
1007
1126
  artifactExclusions: readonly string[],
1127
+ diagnostic?: MutableCaptureDiagnostic,
1008
1128
  ): Promise<CapturedRootResult> {
1009
1129
  const storeDirectory = this.storeDirectory(topology);
1010
1130
  const gitDirectory = this.rootGitDirectory(storeDirectory, root);
@@ -1032,6 +1152,7 @@ export class SnapshotStore {
1032
1152
  exactExclusions,
1033
1153
  this.visibleLeafCache.get(gitDirectory),
1034
1154
  transactionDirectory,
1155
+ diagnostic,
1035
1156
  );
1036
1157
  const coverage = rootCoverageFromInclusions(inclusions);
1037
1158
  const ignoredPresentPaths = await this.captureIgnoredPresentPaths(
@@ -1043,6 +1164,7 @@ export class SnapshotStore {
1043
1164
  exactExclusions,
1044
1165
  transactionDirectory,
1045
1166
  );
1167
+ if (diagnostic !== undefined) diagnostic.ignoredFiles += ignoredPresentPaths.length;
1046
1168
  const treeId = (await this.runGit(["write-tree"], { cwd: absoluteRoot, env: environment })).trim();
1047
1169
  if (!isObjectId(treeId)) {
1048
1170
  throw new SnapshotStoreError("capture_failed", "git write-tree 未返回有效对象 ID");
@@ -1194,6 +1316,7 @@ export class SnapshotStore {
1194
1316
  exactExclusions: ReadonlySet<string>,
1195
1317
  cache: ReadonlyMap<string, CachedVisibleLeaf> | undefined,
1196
1318
  requestDirectory: string,
1319
+ diagnostic?: MutableCaptureDiagnostic,
1197
1320
  ): Promise<StagedWorktree> {
1198
1321
  const leaves = await this.collectVisibleLeaves(
1199
1322
  cwd,
@@ -1206,6 +1329,8 @@ export class SnapshotStore {
1206
1329
  );
1207
1330
  const objectIds = new Map<string, string>();
1208
1331
  const uncached: VisibleLeaf[] = [];
1332
+ let cacheHits = 0;
1333
+ if (diagnostic !== undefined) diagnostic.visibleFilesInspected += leaves.length;
1209
1334
  for (const leaf of leaves) {
1210
1335
  const cached = cache?.get(leaf.relativePath);
1211
1336
  if (
@@ -1214,11 +1339,23 @@ export class SnapshotStore {
1214
1339
  cached.verifiedAtNs > cached.changedAtNs + RACY_CLEAN_WINDOW_NS
1215
1340
  ) {
1216
1341
  objectIds.set(leaf.relativePath, cached.objectId);
1342
+ cacheHits += 1;
1217
1343
  } else {
1218
1344
  uncached.push(leaf);
1219
1345
  }
1220
1346
  }
1221
1347
  const hashBatches = hashPathBatches(uncached.filter((leaf) => leaf.kind === "file"));
1348
+ const hashedFileLeaves = uncached.filter((leaf) => leaf.kind === "file");
1349
+ const hashedSymlinkCount = uncached.length - hashedFileLeaves.length;
1350
+ if (diagnostic !== undefined) {
1351
+ diagnostic.cacheHits += cacheHits;
1352
+ diagnostic.hashFilesPlanned += hashedFileLeaves.length;
1353
+ diagnostic.symlinksPlanned += hashedSymlinkCount;
1354
+ diagnostic.hashCommandsPlanned += hashBatches.length + hashedSymlinkCount;
1355
+ diagnostic.hashBytesPlanned = sumSaturated(diagnostic.hashBytesPlanned, hashedFileLeaves.reduce(
1356
+ (total, leaf) => sumSaturated(total, leaf.size ?? 0), 0,
1357
+ ));
1358
+ }
1222
1359
  const hashedBatches = await mapConcurrentOrdered(hashBatches, HASH_BATCH_CONCURRENCY, async (batch) => {
1223
1360
  await this.assertVisibleLeavesUnchanged(cwd, batch);
1224
1361
  const output = await this.runGit([
@@ -1242,6 +1379,9 @@ export class SnapshotStore {
1242
1379
  await this.assertVisibleLeafUnchanged(cwd, leaf);
1243
1380
  const linkText = await readlink(join(cwd, ...leaf.relativePath.split("/")), { encoding: "buffer" });
1244
1381
  decodeUtf8(linkText, "symlink target 不是可无损表示的 UTF-8");
1382
+ if (diagnostic !== undefined) {
1383
+ diagnostic.hashBytesPlanned = sumSaturated(diagnostic.hashBytesPlanned, linkText.byteLength);
1384
+ }
1245
1385
  const objectId = (await this.runGit(["hash-object", "-w", "--stdin"], {
1246
1386
  cwd,
1247
1387
  env: environment,
@@ -1262,7 +1402,11 @@ export class SnapshotStore {
1262
1402
  });
1263
1403
  }
1264
1404
  await this.assertVisibleLeavesUnchanged(cwd, leaves, requestDirectory, objectIds, environment);
1265
- return { leaves, objectIds, verifiedAtNs: BigInt(Date.now()) * 1_000_000n };
1405
+ return {
1406
+ leaves,
1407
+ objectIds,
1408
+ verifiedAtNs: BigInt(Date.now()) * 1_000_000n,
1409
+ };
1266
1410
  }
1267
1411
 
1268
1412
  private rememberVisibleLeaves(update: VisibleLeafCacheUpdate): void {
@@ -1557,6 +1701,7 @@ export class SnapshotStore {
1557
1701
  leaves.push({
1558
1702
  relativePath,
1559
1703
  kind: metadata.kind,
1704
+ size: Number(metadata.size > BigInt(Number.MAX_SAFE_INTEGER) ? BigInt(Number.MAX_SAFE_INTEGER) : metadata.size),
1560
1705
  mode: metadata.kind === "symlink"
1561
1706
  ? 0o120000
1562
1707
  : (metadata.mode & 0o111n) === 0n ? 0o100644 : 0o100755,
@@ -78,11 +78,14 @@ export class StatusReporter {
78
78
  const opId = this.progress?.opId;
79
79
  this.endOperation();
80
80
  const details = result.message === undefined ? "" : ` ${sanitize(result.message)}`;
81
- const timing = totalMs !== undefined && totalMs >= 1_000
82
- ? formatTiming(totalMs, result.timings)
83
- : "";
84
- const diagnostic = opId !== undefined && (result.code !== "ok" || (totalMs ?? 0) >= 1_000) ? ` op:${opId}` : "";
85
- const message = sanitize(`${result.code} files:${result.changedFiles}${details}${timing}${diagnostic}`);
81
+ const workload = settlementWorkload(result.settlement, result.code !== "ok" && result.code !== "noop");
82
+ const elapsedMs = totalMs ?? 0;
83
+ const settlementMs = result.settlement?.durationMs ?? 0;
84
+ const timing = elapsedMs >= 1_000
85
+ ? formatTiming(elapsedMs, result.timings)
86
+ : settlementMs >= 1_000 ? formatTiming(settlementMs, result.timings, "settled") : "";
87
+ const diagnostic = opId !== undefined && (result.code !== "ok" || elapsedMs >= 1_000) ? ` op:${opId}` : "";
88
+ const message = sanitize(`${result.code} files:${result.changedFiles}${details}${workload}${timing}${diagnostic}`);
86
89
  const type = result.code === "ok" || result.code === "noop"
87
90
  ? "info"
88
91
  : result.code === "recovery_required" ? "error" : "warning";
@@ -110,16 +113,45 @@ const phaseLabels: Record<string, string> = {
110
113
  capture: "捕获安全快照", load: "读取快照", plan: "准备恢复", journal: "记录事务",
111
114
  navigate: "切换会话", apply: "恢复文件", cursor: "提交历史", commit: "完成持久化",
112
115
  compensate: "恢复操作前状态", unlock: "释放工作区锁", discover_gitlinks: "检查子模块", scan_directories: "扫描目录",
116
+ "settled.capture": "结算快照", "settled.workspaceLock": "等待工作区锁",
117
+ "settled.captureBaseline": "捕获结算基线", "settled.rootDiscovery": "扫描工作区根目录",
118
+ "settled.baselineValidation": "校验快照基线", "settled.fullCapture": "完整捕获快照",
119
+ "settled.changedPaths": "比较变更路径", "settled.checkpoint": "记录检查点",
113
120
  };
114
121
 
115
- function formatTiming(totalMs: number, timings: OperationResult["timings"]): string {
122
+ function settlementWorkload(
123
+ settlement: OperationResult["settlement"],
124
+ includeCheckpointFiles: boolean,
125
+ ): string {
126
+ if (settlement === undefined) return "";
127
+ const details: string[] = [];
128
+ if (includeCheckpointFiles && settlement.changedFiles !== undefined) {
129
+ details.push(`changed:${settlement.changedFiles}`);
130
+ }
131
+ const captures = settlement.captures ?? [];
132
+ if (captures.length > 0) {
133
+ const inspected = captures.reduce((total, capture) => Math.min(Number.MAX_SAFE_INTEGER, total + capture.visibleFilesInspected), 0);
134
+ const hashFiles = captures.reduce((total, capture) => Math.min(Number.MAX_SAFE_INTEGER, total + capture.hashFilesPlanned), 0);
135
+ const cacheHits = captures.reduce((total, capture) => Math.min(Number.MAX_SAFE_INTEGER, total + capture.cacheHits), 0);
136
+ details.push(`scan:${inspected} hit:${cacheHits} hash:${hashFiles}`);
137
+ }
138
+ return details.length === 0 ? "" : ` ${details.join(" ")}`;
139
+ }
140
+
141
+ function formatTiming(totalMs: number, timings: OperationResult["timings"], prefix = "total"): string {
142
+ const hasSettlementBreakdown = timings?.some((timing) => timing.phase.startsWith("settled.")) ?? false;
143
+ const hasNestedCaptureTimings = timings?.some((timing) =>
144
+ timing.phase === "settled.rootDiscovery" || timing.phase === "settled.baselineValidation" ||
145
+ timing.phase === "settled.fullCapture") ?? false;
116
146
  const phases = [...(timings ?? [])]
117
- .filter((timing) => timing.durationMs >= 5)
147
+ .filter((timing) => timing.durationMs >= 5 &&
148
+ !(hasSettlementBreakdown && timing.phase === "checkpoint") &&
149
+ !(hasNestedCaptureTimings && (timing.phase === "settled.capture" || timing.phase === "settled.captureBaseline")))
118
150
  .sort((left, right) => right.durationMs - left.durationMs)
119
151
  .slice(0, 5)
120
152
  .map((timing) => `${timing.phase}:${timing.durationMs}ms`)
121
153
  .join(" ");
122
- return ` total:${Math.round(totalMs)}ms${phases.length === 0 ? "" : ` ${phases}`}`;
154
+ return ` ${prefix}:${Math.round(totalMs)}ms${phases.length === 0 ? "" : ` ${phases}`}`;
123
155
  }
124
156
 
125
157
  function sanitize(value: string): string {