@davideasden/pi-undo 0.3.2 → 0.3.4

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
@@ -169,7 +169,7 @@ recovery_required
169
169
 
170
170
  普通文件原生恢复路径保留 5 次完整拓扑扫描。macOS/Linux 的新版 helper 使用不跟随符号链接的目录句柄扫描,仍会发现 Git 忽略目录中的嵌套仓库。小工作区根据上次扫描规模选择 TypeScript 完整重扫,避免进程启动开销;没有使用 TTL 缓存或默认跳过 `node_modules`。
171
171
 
172
- 原生恢复现支持已有父目录中的普通文件删除,以及覆盖、创建、删除混合计划。扩展能力通过 `restore-files-v2` 探测;旧 helper、缺少二进制、目录操作及超出句柄预算的计划继续走 TypeScript 路径。pack 持久化、内容校验、no-clobber 与恢复依据均保留。
172
+ 原生恢复可处理已有父目录中的普通文件删除、覆盖、创建及混合计划。`restore-files-v2` 覆盖子目录删除和混合 mutation;`restore-files-v3` 会把分散在大量父目录中的文件拆成多个批次,每批最多打开 128 个非根父目录句柄。旧 helper、缺少二进制、目录操作、类型替换及单条路径深度超过句柄预算时继续走 TypeScript 路径。durable pack、逐项内容校验、no-clobber 与恢复依据均保留。
173
173
 
174
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)。
175
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
 
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.2",
3
+ "version": "0.3.4",
4
4
  "description": "Persistent workspace undo and redo for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
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 =
@@ -179,6 +197,7 @@ export interface UndoController {
179
197
 
180
198
  interface RunCompletion {
181
199
  started: boolean;
200
+ settlement?: SettlementDiagnostic;
182
201
  readonly promise: Promise<void>;
183
202
  readonly resolve: () => void;
184
203
  }
@@ -228,7 +247,7 @@ export class UndoControllerImpl implements UndoController {
228
247
  private historyPaused = false;
229
248
  private operationInFlight = false;
230
249
  private operationAction: "undo" | "redo" | undefined;
231
- private operationProfiler: OperationProfiler | undefined;
250
+ private lastSettlementDiagnostic: SettlementDiagnostic | undefined;
232
251
  private promptDeferralInFlight = false;
233
252
  private lastSafetyManifestId: ManifestId | null = null;
234
253
  private lastCaptureFailed = false;
@@ -448,6 +467,7 @@ export class UndoControllerImpl implements UndoController {
448
467
  }
449
468
 
450
469
  private beginRun(): RunCompletion {
470
+ this.lastSettlementDiagnostic = undefined;
451
471
  this.finishRun(this.runCompletion);
452
472
  let resolve!: () => void;
453
473
  const promise = new Promise<void>((done) => { resolve = done; });
@@ -541,15 +561,16 @@ export class UndoControllerImpl implements UndoController {
541
561
  if (this.disposed) return Promise.resolve();
542
562
  if (this.settling !== undefined) return this.settling;
543
563
  const run = this.runCompletion;
544
- const settled = this.runBackground(() => this.settleRun());
564
+ const settled = this.runBackground(() => this.settleRun(run));
545
565
  this.settling = settled.finally(() => {
546
566
  this.settling = undefined;
567
+ // settleRun 成功或失败后都结束本轮等待凭据。
547
568
  this.finishRun(run);
548
569
  });
549
570
  return this.settling;
550
571
  }
551
572
 
552
- private async settleRun(): Promise<void> {
573
+ private async settleRun(run?: RunCompletion): Promise<void> {
553
574
  const staged = this.staged;
554
575
  this.staged = undefined;
555
576
  if (this.disposed || this.locked || staged === undefined) return;
@@ -565,70 +586,121 @@ export class UndoControllerImpl implements UndoController {
565
586
  await this.dependencies.appendControl("pi-undo:barrier", { reason: "user_entry_missing" }).catch(() => {});
566
587
  return;
567
588
  }
568
- const profiler = this.operationProfiler;
569
- const measure = <T>(phase: string, operation: () => Promise<T>): Promise<T> =>
570
- 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
+ };
571
609
  try {
572
610
  // settled 复用 run 开始时的 before;helper 在缺少 captureBaseline 时回退完整 capture。
573
611
  // 撕裂捕获(并发写撞上断言窗口)是暂态的:短暂退避后重试一次,成功则不清空历史。
574
612
  const after = await measure("settled.capture", () =>
575
- this.captureSettledBaselineWithRetry(staged.before));
613
+ this.captureSettledBaselineWithRetry(
614
+ staged.before,
615
+ (diagnostic) => captureDiagnostics.push(diagnostic),
616
+ recordCaptureTiming,
617
+ ));
618
+ failureStage = "settled.changedPaths";
576
619
  const changedPaths = await measure("settled.changedPaths", () =>
577
620
  this.dependencies.changedPaths(staged.before, after));
578
- if (changedPaths.length > 0 && this.dependencies.prepareDurableRestore !== undefined) {
579
- // undo 是完成后最常见、也最需要即时响应的方向;redo cache 放到后台构建,
580
- // 避免每个普通 run 的 agent_settled 同步等待两套 durable pack。
581
- await measure("settled.prepareUndo", () =>
582
- this.dependencies.prepareDurableRestore!(after, staged.before, changedPaths));
583
- checkOperation();
584
- }
621
+ changedFiles = changedPaths.length;
585
622
  const endLeafId = this.dependencies.getLogicalLeafId() ?? staged.startEntryId;
586
623
  const checkpoint = this.createCheckpoint(staged, after, changedPaths, userEntryId, endLeafId);
624
+ failureStage = "settled.checkpoint";
587
625
  const checkpointEntryId = await measure("settled.checkpoint", () =>
588
626
  this.dependencies.appendControl("pi-undo:checkpoint", checkpoint));
589
627
  if (checkpointEntryId === null) {
628
+ failureStage = "checkpoint_entry_missing";
590
629
  this.lock("checkpoint_entry_missing");
591
630
  await this.dependencies.appendControl("pi-undo:barrier", { reason: "checkpoint_entry_missing" }).catch(() => {});
592
631
  return;
593
632
  }
633
+ outcome = "ok";
594
634
  this.undoStack.push(checkpoint);
595
- if (
596
- changedPaths.length > 0 && this.dependencies.prepareDurableRestore !== undefined &&
597
- this.operationAction !== "undo"
598
- ) {
599
- const prepareRedo = this.runBackground(async () => {
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 () => {
600
641
  try {
601
- await this.dependencies.prepareDurableRestore!(staged.before, after, changedPaths);
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
+ }
602
647
  } catch (error) {
603
- // redo 有安全的惰性路径;后台预制失败不应拖慢或暂停当前历史。
648
+ // 两个方向都有安全的惰性路径;后台预制失败不应暂停当前历史。
604
649
  this.recordUnsafeExit(error);
605
650
  }
606
651
  });
607
- void prepareRedo.catch(() => {});
652
+ void prepareDurable.catch(() => {});
608
653
  }
609
654
  } catch (error) {
655
+ const candidate = error as { name?: unknown; code?: unknown };
656
+ failureName = safeDiagnosticLabel(candidate.name) ?? "Error";
657
+ failureCode = safeDiagnosticLabel(candidate.code);
610
658
  this.recordUnsafeExit(error);
611
659
  this.historyPaused = true;
612
660
  this.undoStack.length = 0;
613
661
  this.redoStack.length = 0;
614
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 { /* 诊断写入失败不能改变检查点结果 */ }
615
678
  }
616
679
  }
617
680
 
618
681
  async undo(): Promise<OperationResult> {
619
682
  if (this.locked) return this.recoveryResult();
620
- if (this.historyPaused) return { code: "history_paused", changedFiles: 0 };
683
+ if (this.historyPaused) return this.historyPausedResult();
621
684
  return this.runOperation("undo");
622
685
  }
623
686
 
624
687
  async redo(): Promise<OperationResult> {
625
688
  if (this.locked) return this.recoveryResult();
626
- if (this.historyPaused) return { code: "history_paused", changedFiles: 0 };
689
+ if (this.historyPaused) return this.historyPausedResult();
627
690
  // 新 run 开始时 redo frontier 已失效;空栈命令不得为了确认 noop 而中断正在运行的 Agent。
628
691
  if (this.redoStack.length === 0) return noop();
629
692
  return this.runOperation("redo");
630
693
  }
631
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
+
632
704
  beforeTree(event: SessionBeforeTreeEvent): Promise<SessionBeforeTreeResult | undefined> {
633
705
  if (this.treeScope !== undefined) return Promise.resolve({ cancel: true });
634
706
  this.treeCancellationRequested = event.signal?.aborted ?? false;
@@ -825,24 +897,31 @@ export class UndoControllerImpl implements UndoController {
825
897
  if (this.locked) return this.recoveryResult();
826
898
  if (this.operationInFlight) return { code: "busy", changedFiles: 0 };
827
899
  const profile = new OperationProfiler(this.dependencies.onProgress);
828
- 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
+ });
829
906
  this.operationInFlight = true;
830
907
  this.operationAction = action;
831
- this.operationProfiler = profile;
832
908
  this.promptDeferralInFlight = true;
833
909
  this.lastSafetyManifestId = null;
834
910
  let lease: { release(): Promise<void> } | undefined;
835
911
  try {
912
+ const checkpointRun = this.runCompletion;
836
913
  const [idleReady, checkpointReady] = await Promise.all([
837
914
  profile.measure("idle", () => this.ensureIdle()),
838
915
  profile.measure("checkpoint", () => this.waitForCheckpoint()),
839
916
  ]);
917
+ settlement = checkpointRun?.settlement;
918
+ if (settlement !== undefined) profile.addSettlement(settlement);
840
919
  if (!idleReady || !checkpointReady) {
841
920
  checkOperation();
842
921
  return done({ code: "idle_timeout", changedFiles: 0 });
843
922
  }
844
923
  if (this.locked) return done(this.recoveryResult());
845
- if (this.historyPaused) return done({ code: "history_paused", changedFiles: 0 });
924
+ if (this.historyPaused) return done(this.historyPausedResult());
846
925
  if (this.disposed) return done({ code: "busy", changedFiles: 0 });
847
926
  // Pi 空闲早于扩展 settled 完成;只有本轮完成凭据已终结才能选择目标。
848
927
  const redo = action === "redo" ? this.redoStack.at(-1) : undefined;
@@ -967,7 +1046,6 @@ export class UndoControllerImpl implements UndoController {
967
1046
  await profile.measure("unlock", () =>
968
1047
  activeLease.release().catch(() => { this.lock("workspace_lock_release_failed"); }));
969
1048
  }
970
- if (this.operationProfiler === profile) this.operationProfiler = undefined;
971
1049
  this.operationAction = undefined;
972
1050
  this.promptDeferralInFlight = false;
973
1051
  this.operationInFlight = false;
@@ -1139,16 +1217,28 @@ export class UndoControllerImpl implements UndoController {
1139
1217
  }
1140
1218
  }
1141
1219
 
1142
- 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> {
1143
1225
  const captureBaseline = this.dependencies.captureBaseline;
1144
1226
  if (captureBaseline === undefined) return this.captureWithWorkspaceLock();
1145
- 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();
1146
1235
  try {
1147
- return await captureBaseline(baseline);
1236
+ return await captureBaseline(baseline, onDiagnostics, onTiming);
1148
1237
  } catch (error) {
1149
1238
  this.recordUnsafeExit(error);
1150
1239
  throw error;
1151
1240
  } finally {
1241
+ reportCaptureTiming(onTiming, "settled.captureBaseline", performance.now() - captureStartedAt);
1152
1242
  if (!this.unsafeExit) await lease.release();
1153
1243
  }
1154
1244
  }
@@ -1158,14 +1248,20 @@ export class UndoControllerImpl implements UndoController {
1158
1248
  * (捕获期间叶子变化)或短暂持有 workspace lock。settled 失败会清空整个 undo 历史,
1159
1249
  * 不能因一次暂态冲突就放弃;持续失败仍由调用方走原有 historyPaused 路径。
1160
1250
  */
1161
- 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> {
1162
1256
  try {
1163
- return await this.captureBaselineWithWorkspaceLock(baseline);
1257
+ return await this.captureBaselineWithWorkspaceLock(baseline, onDiagnostics, onTiming);
1164
1258
  } catch (error) {
1165
1259
  rethrowOperationFailure(error);
1166
1260
  if (!isTransientCaptureFailure(error)) throw error;
1261
+ const retryStartedAt = performance.now();
1167
1262
  await sleep(250);
1168
- return await this.captureBaselineWithWorkspaceLock(baseline);
1263
+ onTiming?.("settled.captureRetryDelay", performance.now() - retryStartedAt);
1264
+ return await this.captureBaselineWithWorkspaceLock(baseline, onDiagnostics, onTiming);
1169
1265
  }
1170
1266
  }
1171
1267
 
@@ -1337,6 +1433,7 @@ function emptyRestorePlan(currentManifestId: ManifestId, targetManifestId: Manif
1337
1433
 
1338
1434
  class OperationProfiler {
1339
1435
  private readonly durations = new Map<string, number>();
1436
+ private settlementTimings: readonly OperationTiming[] = [];
1340
1437
 
1341
1438
  constructor(private readonly onProgress?: (phase: string) => void) {}
1342
1439
 
@@ -1347,19 +1444,30 @@ class OperationProfiler {
1347
1444
  try {
1348
1445
  return await operation();
1349
1446
  } finally {
1350
- this.durations.set(phase, (this.durations.get(phase) ?? 0) + performance.now() - started);
1447
+ this.record(phase, performance.now() - started);
1351
1448
  }
1352
1449
  }
1353
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
+
1354
1459
  attach(result: OperationResult): OperationResult {
1355
1460
  const total = [...this.durations.values()].reduce((sum, duration) => sum + duration, 0);
1356
1461
  if (total < 1_000) return result;
1357
1462
  return {
1358
1463
  ...result,
1359
- timings: [...this.durations].map(([phase, durationMs]) => ({
1360
- phase,
1361
- durationMs: Math.round(durationMs),
1362
- })),
1464
+ timings: [
1465
+ ...([...this.durations].map(([phase, durationMs]) => ({
1466
+ phase,
1467
+ durationMs: Math.round(durationMs),
1468
+ }))),
1469
+ ...this.settlementTimings,
1470
+ ],
1363
1471
  };
1364
1472
  }
1365
1473
  }
@@ -1388,6 +1496,18 @@ function noop(): OperationResult {
1388
1496
  return { code: "noop", changedFiles: 0 };
1389
1497
  }
1390
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
+
1391
1511
  function truncateReason(reason: string): string {
1392
1512
  return reason.replace(/[\u0000-\u001F\u007F]+/g, " ").trim().slice(0, 120);
1393
1513
  }
@@ -118,6 +118,10 @@ export class DurablePack {
118
118
  return this.entries.get(path)?.targetFingerprint;
119
119
  }
120
120
 
121
+ withStoragePath(storagePath: string): DurablePack {
122
+ return new DurablePack(this.opId, this.planDigest, storagePath, this.packChecksum, this.entries);
123
+ }
124
+
121
125
  leaf(path: string, fingerprint: string): DurableLeaf | undefined {
122
126
  const leaf = this.entries.get(path)?.variants.get(fingerprint);
123
127
  if (leaf === undefined) return undefined;
@@ -282,16 +286,36 @@ export async function hasDurablePack(journal: MutationJournal): Promise<boolean>
282
286
  }
283
287
  }
284
288
 
289
+ export async function publishResidentDurablePack(
290
+ cached: DurablePack,
291
+ journal: MutationJournal,
292
+ expectedPlanDigest: string,
293
+ ): Promise<DurablePack> {
294
+ if (cached.planDigest !== expectedPlanDigest) throw new Error("durable cache planDigest 不匹配");
295
+ const target = durablePackPath(journal);
296
+ await rm(target, { force: true });
297
+ try {
298
+ await link(cached.storagePath, target);
299
+ await fsyncDirectory(dirname(target));
300
+ } catch (error) {
301
+ if (!hasErrorCode(error, "EXDEV")) throw error;
302
+ await copyFile(cached.storagePath, target);
303
+ await fsyncFile(target);
304
+ await fsyncDirectory(dirname(target));
305
+ }
306
+ return cached.withStoragePath(target);
307
+ }
308
+
285
309
  export async function publishCachedDurablePack(
286
310
  cachedPath: string,
287
311
  journal: MutationJournal,
288
312
  expectedPlanDigest: string,
289
313
  expectedPackChecksum: string,
290
314
  ): Promise<DurablePack> {
291
- const target = durablePackPath(journal);
292
315
  if (checksum(await readFile(cachedPath)) !== expectedPackChecksum) {
293
316
  throw new Error("durable cache pack checksum 不匹配");
294
317
  }
318
+ const target = durablePackPath(journal);
295
319
  await rm(target, { force: true });
296
320
  try {
297
321
  await link(cachedPath, target);
@@ -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";
@@ -62,12 +63,26 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
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
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,
@@ -297,7 +312,15 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
297
312
  const totalMs = Math.round(performance.now() - operationStarted);
298
313
  if (totalMs < 1_000 && (result.code === "ok" || result.code === "noop")) return;
299
314
  await writeJsonAtomic(join(privateRoot, "diagnostics", `${manager.getSessionId()}-latest.json`), {
300
- 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,
301
324
  });
302
325
  },
303
326
  };
@@ -11,6 +11,7 @@ import {
11
11
  hasDurablePack,
12
12
  loadDurablePack,
13
13
  publishCachedDurablePack,
14
+ publishResidentDurablePack,
14
15
  removeDurablePack,
15
16
  type DurableLeafInput,
16
17
  type DurablePack,
@@ -189,6 +190,7 @@ export class RestoreEngine {
189
190
  private readonly preparedPlans = new Map<string, PreparedRestorePlan>();
190
191
  private readonly durablePackCache = new Map<string, CachedDurablePack>();
191
192
  private readonly durablePackByPair = new Map<string, CachedDurablePair>();
193
+ private readonly verifiedDurablePacks = new Set<string>();
192
194
  private readonly durableIndexLock = new WorkspaceLock({
193
195
  leaseMs: 10_000,
194
196
  retryMs: 25,
@@ -343,6 +345,7 @@ export class RestoreEngine {
343
345
  false,
344
346
  );
345
347
  }
348
+ this.verifiedDurablePacks.add(`${pairKey}:${cached.planDigest}`);
346
349
  return true;
347
350
  } catch (error) {
348
351
  rethrowOperationFailure(error);
@@ -859,12 +862,25 @@ export class RestoreEngine {
859
862
  cached.currentManifestId === current.manifestId &&
860
863
  cached.targetManifestId === target.manifestId
861
864
  ) {
862
- durablePack = await publishCachedDurablePack(
863
- cached.path,
864
- options.mutationJournal,
865
- plan.planDigest,
866
- cached.packChecksum,
867
- );
865
+ const pairKey = durablePairKey(current.manifestId, target.manifestId, plan.scopePaths ?? []);
866
+ const residentKey = `${pairKey}:${plan.planDigest}`;
867
+ const resident = this.verifiedDurablePacks.has(residentKey)
868
+ ? this.durablePackByPair.get(pairKey)
869
+ : undefined;
870
+ if (resident?.planDigest === plan.planDigest && resident.pack.packChecksum === cached.packChecksum) {
871
+ durablePack = await publishResidentDurablePack(
872
+ resident.pack,
873
+ options.mutationJournal,
874
+ plan.planDigest,
875
+ );
876
+ } else {
877
+ durablePack = await publishCachedDurablePack(
878
+ cached.path,
879
+ options.mutationJournal,
880
+ plan.planDigest,
881
+ cached.packChecksum,
882
+ );
883
+ }
868
884
  } else {
869
885
  durablePack = await createDurablePack(options.mutationJournal, {
870
886
  opId: options.opId,
@@ -898,7 +914,10 @@ export class RestoreEngine {
898
914
  );
899
915
  }
900
916
  const durablePackEnabled = durablePack !== undefined;
901
- if (nativeFileBatch !== undefined && durablePack !== undefined && this.canUseNativeFilePlan(plan, currentPaths, targetPaths)) {
917
+ if (
918
+ nativeFileBatch !== undefined && durablePack !== undefined &&
919
+ this.canUseNativeFilePlan(plan, currentPaths, targetPaths)
920
+ ) {
902
921
  const result = await this.applyNativeFilePlan(
903
922
  plan,
904
923
  current,
@@ -1018,9 +1037,8 @@ export class RestoreEngine {
1018
1037
  if (!plan.writePaths.every((path) =>
1019
1038
  targetPaths.get(path)?.entry.kind === "file" &&
1020
1039
  (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;
1040
+ const paths = [...plan.deletePaths, ...plan.writePaths];
1041
+ return process.platform === "win32" || paths.every((path) => strictPathAncestors(path).length <= 128);
1024
1042
  }
1025
1043
 
1026
1044
  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 {