@davideasden/pi-undo 0.3.6 → 0.3.7

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
@@ -167,7 +167,7 @@ recovery_required
167
167
 
168
168
  ### Performance Notes
169
169
 
170
- 普通文件原生恢复路径保留 5 次完整拓扑扫描。macOS/Linux 的新版 helper 使用不跟随符号链接的目录句柄扫描,仍会发现 Git 忽略目录中的嵌套仓库。小工作区根据上次扫描规模选择 TypeScript 完整重扫,避免进程启动开销;没有使用 TTL 缓存或默认跳过 `node_modules`。
170
+ 普通文件恢复在持有 workspace 独占锁时,先逐项核验 changedPaths 中的叶子文件;若与 checkpoint source 一致,就直接复用 manifest,避免额外 scoped capture 和全目录扫描。目录 scope、内容不匹配或 source 无法证明时仍走 scoped safety capture。成功路径保留 `restore-pre` 与 `restore-post` 两次 topology 检查,并继续执行 scope 内可见路径校验;锁内省略其后的重复 topology 扫描。native helper 仍不跟随符号链接地扫描 ignored 目录中的嵌套仓库;没有默认跳过 `node_modules`,也没有使用 TTL 缓存。
171
171
 
172
172
  原生恢复可处理已有父目录中的普通文件删除、覆盖、创建及混合计划。`restore-files-v2` 覆盖子目录删除和混合 mutation;`restore-files-v3` 会把分散在大量父目录中的文件拆成多个批次,每批最多打开 128 个非根父目录句柄。旧 helper、缺少二进制、目录操作、类型替换及单条路径深度超过句柄预算时继续走 TypeScript 路径。durable pack、逐项内容校验、no-clobber 与恢复依据均保留。
173
173
 
@@ -1,6 +1,6 @@
1
1
  # 原生目录扫描与普通文件恢复性能验证
2
2
 
3
- 本轮实现目录项缓存与 scoped restore 的可见路径检查,保留恢复前后的拓扑校验。目录扫描仍会逐个打开、核验工作区内的目录;缓存减少 `readdir`,没有把整次检查变成只访问 changedPaths 的增量操作。
3
+ 本轮实现目录项缓存与 scoped restore 的可见路径检查;普通一次性扫描仍会逐个打开、核验工作区内的目录,宽目录最多使用 16 个有界 worker 并行处理。常驻 `--serve` 在 macOS 上使用 FSEvents 收集变更父目录,只重新枚举受影响祖先并合并局部 cache;无变化请求复用驻留 cache,事件丢失、监听停止或扫描竞争时回退完整校验。
4
4
 
5
5
  ## Durable pack 准备与批量写入
6
6
 
@@ -74,7 +74,7 @@ plan 额外报告 `plan.validate`、`plan.complete`、`plan.paths`、`plan.diff`
74
74
 
75
75
  小文件冷缓存三次为基线 `[1980, 1922, 1938]`、最终 `[1560, 1526, 1511]`。热缓存、稀疏修改和大文件没有证明稳定提速。未充分覆盖目录的稀疏大 scope 可能增加一次有界探测开销;超过探测预算时回退精确查询,不复用部分结果。
76
76
 
77
- 真实 Pi 1.3.0 SDK、10,000 个 ignored 依赖包场景也分别进行了三次 undo/redo,验证每次内容、历史状态和五次拓扑发现。耗时中位数如下:
77
+ 本轮真实 Pi 1.3.0 SDK、10,000 个 ignored 依赖包场景此前分别进行了三次 undo/redo,验证每次内容、历史状态和五次拓扑发现;该数据记录的是当时版本,不代表当前复用 durable source 的扫描次数。耗时中位数如下:
78
78
 
79
79
  | 场景 | undo 基线 → 最终 | redo 基线 → 最终 |
80
80
  | --- | ---: | ---: |
@@ -105,13 +105,13 @@ metadata inspect 默认每批最多处理 2,048 条路径,并受 1 MiB 路径
105
105
 
106
106
  GitRunner 会对单次 Git stdout 应用 256 MiB 硬上限;超过上限时终止整个 Git 进程组并抛出 `git_output_limit`,避免在 `Buffer.concat(...).toString()` 阶段触发 Node.js `ERR_STRING_TOO_LONG` 或无界内存增长。正常的 blob batch 读取仍按 16 MiB 分批,不受该上限影响。
107
107
 
108
- - `scan-directories-v2` 在 macOS/Linux 上缓存每个目录的 `dev/ino/mtime/ctime`、Git 标记和直接子目录。每次检查仍核验全部目录的身份与时间戳,匹配时才复用目录项。检查点之间发生变化的目录重新枚举;扫描期间发生变化则显式失败,不接受部分结果。
108
+ - `scan-directories-v2` 在 macOS/Linux 上缓存每个目录的 `dev/ino/mtime/ctime`、Git 标记和直接子目录。一次性 helper 及常驻服务的完整回退路径仍核验全部目录;常驻 macOS 服务收到可靠 FSEvents 后只重新枚举变更父目录和祖先,其他未受影响子树按 cache 整体复用。宽目录按最多 16 个 worker 分批并行,避免为每个目录创建线程。直接命中的 racy 目录不会被局部路径直接复用,而是重新枚举。
109
109
  - 缓存把 racy 标记固化到记录中,以开始枚举目录前的观察时刻计算两秒窗口。长子树扫描或之后的时间流逝不会让旧的 racy 记录自动变成可信记录。时间戳纳秒部分为零、无效或处于未来时采取保守重扫。
110
110
  - 扫描继续进入 ignored 目录,以发现其中的嵌套仓库;不进入名称恰为 `.git` 的元数据目录,不跟随 symlink。目录句柄、父子绑定和工作区身份检查保留。超过 128 层时丢弃原生部分结果,由 TypeScript 从根重扫。
111
111
  - v2 cache 绑定工作区路径与身份,结构解析失败或不匹配时不复用。它位于工作区外的私有临时目录,位置检查会解析 `TMPDIR` 的符号链接;无法安全放置请求时使用 TypeScript。cache 创建失败时使用本次请求目录,cache 写入失败不使成功扫描失败。正常进程退出时尽力清理,强制终止仍可能留下系统临时文件。
112
112
  - 能力探测一次取得 capability 集合;旧 `scan-directories-v1` helper 继续完整扫描,缺少 helper 时使用 TypeScript。扫描仍受操作剩余时间和 `PI_UNDO_OPERATION_TIMEOUT_MS` 限制,取消或未确认退出保持原有处理契约。
113
113
  - `listVisibleLeafPaths` 支持 `includePaths`。带 scope 的 complete restore 只枚举 scope 内的可见叶子;scope 外新增文件保留,scope 内新增可见路径仍会在修改前阻止恢复。未指定 scope 的完整恢复继续枚举整个工作区。嵌套仓库边界、内容、mode、symlink、mutation journal 和 quarantine 检查保留。
114
- - 本轮没有引入 FSEvents/inotify 变更索引,也没有消除 settled 阶段完整 baseline 的枚举成本。因此,目录很多或 baseline 捕获很慢的工作区仍可能有明显等待,不能据此保证用户的 50GB 项目达到秒级响应。
114
+ - 常驻 `--serve` 在 macOS 上使用带 file events 的 FSEvents stream,按事件路径归并到父目录;事件 dropped、路径无法解析、监听线程停止或扫描前后仍有新事件时回退完整扫描。事件取样有短暂 settle 窗口,以覆盖文件操作刚完成但系统尚未投递事件的情况;Linux/Windows 仍使用现有回退路径。
115
115
 
116
116
  缓存信任应用进程创建的私有文件及操作系统提供的目录元数据,不提供跨整个工作区的原子快照,也不提供抵抗同用户篡改 cache 的完整性保证。
117
117
 
@@ -127,6 +127,10 @@ GitRunner 会对单次 Git stdout 应用 256 MiB 硬上限;超过上限时终
127
127
 
128
128
  此前开发中一次 v2 采样为 `[2443, 2423, 2419]` ms;它与最终对比属于不同批次,不合并计算。三次本机采样只能说明这一基准的表现,没有墙钟性能断言,也没有对用户实际 50GB 项目、其他平台或其他磁盘作出速度保证。
129
129
 
130
+ ## 本轮追加:撤销前序准备与拓扑扫描
131
+
132
+ 真实 Pi SDK、10,000 个 ignored 依赖包、单文件变更的三次 undo/redo 基准中,改动前 undo 中位数为 2,150 ms、每次 3 次完整拓扑发现;改动后中位数为 1,745 ms、每次 2 次发现。单次诊断中 safety 阶段从 504 ms 降至 90 ms:当 `changedPaths` 全部是叶子且工作区内容逐项匹配 checkpoint source 时,直接复用 source manifest;目录 scope、内容不匹配或无法证明时仍走原 scoped safety capture。运行时持有 workspace lock 后,visible-pre 的可见路径校验保留,但跳过其后的重复 topology 扫描;`restore-pre` 和 `restore-post` 两次检查仍保留。上述为本机样本,墙钟数据会受扫描缓存和负载影响,不构成其他工作区的速度保证。
133
+
130
134
  ## 上一轮原生优化的历史数据
131
135
 
132
136
  下表保留上一轮以 `d7d80230` 为起点的结果,便于追踪原生扫描及普通文件恢复的收益;这些数据不是本轮缓存改动的前后对比。单位为毫秒。
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.6",
3
+ "version": "0.3.7",
4
4
  "description": "Persistent workspace undo and redo for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/controller.ts CHANGED
@@ -322,16 +322,23 @@ export class UndoControllerImpl implements UndoController {
322
322
  return true;
323
323
  }
324
324
 
325
- private runBackground<T>(body: () => Promise<T>): Promise<T> {
325
+ private runBackground<T>(body: () => Promise<T>, deferStart = false): Promise<T> {
326
326
  const scope = createOperationScope({ timeoutMs: this.operationTimeout() });
327
327
  this.backgroundScopes.add(scope);
328
- const task = runWithOperationContext(scope.context, async () => {
328
+ const start = (): Promise<T> => runWithOperationContext(scope.context, async () => {
329
329
  try {
330
330
  return await body();
331
331
  } finally {
332
332
  if (operationHasUnconfirmedExit()) this.recordUnsafeExit({ code: "process_exit_unconfirmed" });
333
333
  }
334
- }).finally(() => {
334
+ });
335
+ let task!: Promise<T>;
336
+ const execution = deferStart
337
+ ? new Promise<T>((resolve, reject) => {
338
+ setImmediate(() => start().then(resolve, reject));
339
+ })
340
+ : start();
341
+ task = execution.finally(() => {
335
342
  scope.dispose();
336
343
  this.backgroundScopes.delete(scope);
337
344
  this.backgroundTasks.delete(task);
@@ -387,12 +394,12 @@ export class UndoControllerImpl implements UndoController {
387
394
  if (this.disposed || this.locked || this.warmUpInFlight !== undefined) return;
388
395
  const warmUp = this.runBackground(async () => {
389
396
  try {
390
- this.warmUpManifest = await this.captureWithWorkspaceLock();
397
+ this.warmUpManifest = await this.captureWithWorkspaceLock(true);
391
398
  } catch (error) {
392
399
  this.recordUnsafeExit(error);
393
400
  // 预热是 best-effort:失败静默,正式 capture 会再次尝试并上报。
394
401
  }
395
- });
402
+ }, true);
396
403
  this.warmUpInFlight = warmUp;
397
404
  void warmUp.finally(() => {
398
405
  if (this.warmUpInFlight === warmUp && this.warmUpManifest === undefined) {
@@ -439,7 +446,7 @@ export class UndoControllerImpl implements UndoController {
439
446
  this.lastCaptureFailureMessage = undefined;
440
447
  this.deferAgentStartUntilMessageEnd = true;
441
448
  const token = Symbol("input-capture");
442
- const promise = this.runBackground(() => this.captureInputForToken(text, token));
449
+ const promise = this.runBackground(() => this.captureInputForToken(text, token), true);
443
450
  this.pendingInputCapture = { token, promise };
444
451
  void promise.then(() => {
445
452
  if (this.pendingInputCapture?.token === token) this.pendingInputCapture = undefined;
@@ -519,6 +526,8 @@ export class UndoControllerImpl implements UndoController {
519
526
  // warm-up 仍在进行时先等待,确保随后可以消费已完成的 baseline,而不是再次完整 capture。
520
527
  const warmUp = this.warmUpInFlight;
521
528
  if (warmUp !== undefined) await warmUp;
529
+ // 输入事件已经返回后再进入实际捕获,优先让终端处理 Esc、命令和重绘。
530
+ await yieldToEventLoop();
522
531
  const warmUpManifest = this.warmUpManifest;
523
532
  this.warmUpManifest = undefined;
524
533
  if (this.warmUpInFlight === warmUp) this.warmUpInFlight = undefined;
@@ -565,7 +574,7 @@ export class UndoControllerImpl implements UndoController {
565
574
  if (this.disposed) return Promise.resolve();
566
575
  if (this.settling !== undefined) return this.settling;
567
576
  const run = this.runCompletion;
568
- const settled = this.runBackground(() => this.settleRun(run));
577
+ const settled = this.runBackground(() => this.settleRun(run), true);
569
578
  this.settling = settled.finally(() => {
570
579
  this.settling = undefined;
571
580
  // settleRun 成功或失败后都结束本轮等待凭据。
@@ -1216,10 +1225,9 @@ export class UndoControllerImpl implements UndoController {
1216
1225
  }
1217
1226
  }
1218
1227
 
1219
- private async captureWithWorkspaceLock(): Promise<SnapshotManifest> {
1220
- // 预热可能仍持有 workspace lock:先等它完成再 acquire,避免排队超时;
1221
- // 此时进程内缓存已暖,本次 capture 只需指纹校验。
1222
- const warmUp = this.warmUpInFlight;
1228
+ private async captureWithWorkspaceLock(skipWarmUpWait = false): Promise<SnapshotManifest> {
1229
+ // 预热任务本身不能等待 warmUpInFlight,否则会等待自己的 Promise。
1230
+ const warmUp = skipWarmUpWait ? undefined : this.warmUpInFlight;
1223
1231
  if (warmUp !== undefined) await warmUp;
1224
1232
  const lease = await this.dependencies.acquireWorkspaceLock();
1225
1233
  try {
@@ -1540,6 +1548,10 @@ function isTransientCaptureFailure(error: unknown): boolean {
1540
1548
  (name === "WorkspaceLockError" && code === "lock_timeout");
1541
1549
  }
1542
1550
 
1551
+ function yieldToEventLoop(): Promise<void> {
1552
+ return new Promise((resolve) => setImmediate(resolve));
1553
+ }
1554
+
1543
1555
  function sleep(ms: number): Promise<void> {
1544
1556
  return new Promise((resolve) => setTimeout(resolve, ms));
1545
1557
  }
package/src/pi-runtime.ts CHANGED
@@ -167,6 +167,7 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
167
167
  opId: operation.opId,
168
168
  mutationJournal: journal.mutationJournal(operation.opId),
169
169
  forceTargetArtifactSync: true,
170
+ workspaceLockHeld: true,
170
171
  }),
171
172
  settle: (opId, phase) => journal.settleRecovery(opId, phase),
172
173
  });
@@ -276,6 +277,9 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
276
277
  store.loadManifest(targetManifestId),
277
278
  ]);
278
279
  if (await restore.canReuseDurableSource(reference, target, scopePaths)) return reference;
280
+ // durable pack 可能仍在后台预制;若当前 scope 已经与 reference manifest 一致,
281
+ // 不必为 rollback 再做一次全量目录扫描。apply 仍会在 mutation 前复核 topology。
282
+ if (await restore.canReuseManifestSource(reference, target, scopePaths)) return reference;
279
283
  return capture(scopePaths);
280
284
  },
281
285
  changedPaths: async (before, after) => {
@@ -292,6 +296,7 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
292
296
  opId: operation.opId,
293
297
  mutationJournal: journal.mutationJournal(operation.opId),
294
298
  deferDurability: true,
299
+ workspaceLockHeld: true,
295
300
  onTiming: (phase, durationMs) => {
296
301
  try {
297
302
  phases.push({ phase, elapsedMs: Math.round(performance.now() - operationStarted) });
@@ -79,6 +79,8 @@ export interface RestoreApplyOptions {
79
79
  readonly mutationJournal: MutationJournal;
80
80
  readonly forceTargetArtifactSync?: boolean;
81
81
  readonly deferDurability?: boolean;
82
+ /** 调用方已持有 workspace 独占锁时,可略过 visible-pre 枚举后的重复 topology 扫描。 */
83
+ readonly workspaceLockHeld?: boolean;
82
84
  /** 报告 apply 内部阶段耗时;回调异常不影响恢复结果。 */
83
85
  readonly onTiming?: (phase: string, durationMs: number) => void;
84
86
  }
@@ -250,7 +252,6 @@ export class RestoreEngine {
250
252
  const scope = scopePaths === undefined ? undefined : this.canonicalScope(scopePaths);
251
253
  const canonicalScopePaths = scope === undefined ? undefined : [...scope];
252
254
  assertCompatibleManifests(current, target, scope);
253
- const isScopedPath = (path: string): boolean => scope === undefined || scope.has(path);
254
255
  reportDurablePackTiming(options, "plan.validate", validationStarted);
255
256
  const completeStarted = performance.now();
256
257
  await allCompleted([
@@ -258,6 +259,29 @@ export class RestoreEngine {
258
259
  this.store.assertComplete(target.manifestId, canonicalScopePaths),
259
260
  ]);
260
261
  reportDurablePackTiming(options, "plan.complete", completeStarted);
262
+ return this.computePlan(current, target, scope, canonicalScopePaths, options);
263
+ }
264
+
265
+ private async computePlan(
266
+ current: SnapshotManifest,
267
+ target: SnapshotManifest,
268
+ scope: ReadonlySet<string> | undefined,
269
+ canonicalScopePaths: readonly string[] | undefined,
270
+ options: DurablePackPreparationOptions = {},
271
+ ): Promise<RestorePlan> {
272
+ const isScopedPath = (path: string): boolean => scope === undefined || scope.has(path);
273
+ const prepared = canonicalScopePaths === undefined
274
+ ? undefined
275
+ : this.findPreparedPlan(current.manifestId, target.manifestId, canonicalScopePaths);
276
+ if (prepared !== undefined) {
277
+ // 后台 durable prepare 已读取并验证过同一对 immutable manifest;复用路径表,
278
+ // 避免 undo 前再执行一轮 listTree 与 diff。
279
+ const pathsStarted = performance.now();
280
+ reportDurablePackTiming(options, "plan.paths", pathsStarted);
281
+ const diffStarted = performance.now();
282
+ reportDurablePackTiming(options, "plan.diff", diffStarted);
283
+ return cloneRestorePlan(prepared.plan);
284
+ }
261
285
 
262
286
  const pathsStarted = performance.now();
263
287
  const [currentPaths, targetPaths] = await allCompleted([
@@ -318,6 +342,11 @@ export class RestoreEngine {
318
342
  return plan;
319
343
  }
320
344
 
345
+ /**
346
+ * 仅验证缓存 durable pack 对应 scope 的 source 文件。
347
+ * topology 的权威检查在 apply 的 restore-pre 阶段执行,避免同一 undo
348
+ * 在 safety reuse 与真正 mutation 前重复扫描整个工作区。
349
+ */
321
350
  async canReuseDurableSource(
322
351
  current: SnapshotManifest,
323
352
  target: SnapshotManifest,
@@ -341,11 +370,16 @@ export class RestoreEngine {
341
370
  try {
342
371
  if (await this.assertWorkspaceRootIdentity() !== current.workspaceIdentity) return false;
343
372
  if (fromPersistentIndex) {
344
- const expected = await this.plan(current, target, scopePaths);
373
+ assertManifest(current);
374
+ assertManifest(target);
375
+ const scope = this.canonicalScope(scopePaths);
376
+ assertCompatibleManifests(current, target, scope);
377
+ const expected = await this.computePlan(current, target, scope, [...scope]);
345
378
  if (expected.planDigest !== cached.planDigest) return false;
346
379
  }
347
- const topology = await this.discovery.discover(this.workspaceRoot, "safety-snapshot");
348
- this.assertCurrentTopology(current, target, topology);
380
+ // 这里只验证 durable pack 对应的 scope 源文件;完整 topology 校验由 apply
381
+ // 的 restore-pre 阶段负责。若在这里再次 discover,成功路径会为同一个操作
382
+ // 做两次全量目录扫描,而 apply 仍必须在真正 mutation 前重新确认 topology。
349
383
  const native = await createNativeFileBatch({
350
384
  workspaceRoot: this.workspaceRoot,
351
385
  planDigest: cached.planDigest,
@@ -372,6 +406,48 @@ export class RestoreEngine {
372
406
  }
373
407
  }
374
408
 
409
+ /**
410
+ * durable pack 尚未完成时,尝试直接证明当前 workspace 就是 rollback source。
411
+ * 只核验本次 restore scope 的叶子,不扫描整个 workspace;完整 topology 与可见路径
412
+ * 仍由 apply 的 restore-pre/visible-pre 在真正 mutation 前复核。
413
+ */
414
+ async canReuseManifestSource(
415
+ current: SnapshotManifest,
416
+ target: SnapshotManifest,
417
+ scopePaths: readonly string[],
418
+ ): Promise<boolean> {
419
+ try {
420
+ assertManifest(current);
421
+ assertManifest(target);
422
+ if (await this.assertWorkspaceRootIdentity() !== current.workspaceIdentity) return false;
423
+ const scope = [...this.canonicalScope(scopePaths)];
424
+ assertCompatibleManifests(current, target, new Set(scope));
425
+ const prepared = this.findPreparedPlan(current.manifestId, target.manifestId, scope);
426
+ const currentPaths = prepared === undefined
427
+ ? await this.readOwnedPaths(current, scope)
428
+ : prepared.currentPaths;
429
+ for (const path of scope) {
430
+ if (path === "." || currentPaths.get(path)?.entry.kind === "directory") {
431
+ // 目录 scope 不能由单个 lstat 证明全部 rollback 内容,继续走 scoped capture。
432
+ return false;
433
+ }
434
+ }
435
+ const matches = await mapConcurrentOrdered(scope, RESTORE_FILE_VERIFY_CONCURRENCY, async (path) => {
436
+ const owned = currentPaths.get(path);
437
+ if (owned === undefined) {
438
+ await assertNoSymlinkEscape(this.workspaceRoot, path);
439
+ return this.pathIsAbsent(path);
440
+ }
441
+ await this.verifyEntry(current.manifestId, owned);
442
+ return true;
443
+ });
444
+ return matches.every(Boolean);
445
+ } catch (error) {
446
+ rethrowOperationFailure(error);
447
+ return false;
448
+ }
449
+ }
450
+
375
451
  async prepareDurableRestore(
376
452
  current: SnapshotManifest,
377
453
  target: SnapshotManifest,
@@ -382,7 +458,11 @@ export class RestoreEngine {
382
458
  const plan = await this.plan(current, target, scopePaths, options);
383
459
  const prepared = this.takePreparedPlan(plan);
384
460
  reportDurablePackTiming(options, "prepare.plan", started);
385
- if (prepared === undefined || !this.canUseNativeFilePlan(plan, prepared.currentPaths, prepared.targetPaths)) return;
461
+ if (prepared === undefined) return;
462
+ // durable pack 的 blob 读取和编码可能持续一段时间;保留已完成的 plan/path 表,
463
+ // 让用户在此窗口触发 undo 时复用前序准备结果,而不是重新 listTree。
464
+ this.rememberPreparedPlan(plan, prepared.currentPaths, prepared.targetPaths);
465
+ if (!this.canUseNativeFilePlan(plan, prepared.currentPaths, prepared.targetPaths)) return;
386
466
  const cacheRoot = await this.store.durableCacheDirectory();
387
467
  const cacheOpId = `cache-${plan.planDigest}`;
388
468
  const cacheJournal = new MutationJournal(
@@ -672,6 +752,26 @@ export class RestoreEngine {
672
752
  return this.durablePackCacheMaxBytes + 1;
673
753
  }
674
754
 
755
+ private findPreparedPlan(
756
+ currentManifestId: ManifestId,
757
+ targetManifestId: ManifestId,
758
+ scopePaths: readonly string[],
759
+ ): PreparedRestorePlan | undefined {
760
+ const canonicalScope = [...new Set(scopePaths)].sort(comparePaths);
761
+ for (const prepared of this.preparedPlans.values()) {
762
+ const candidate = prepared.plan;
763
+ if (
764
+ candidate.currentManifestId !== currentManifestId ||
765
+ candidate.targetManifestId !== targetManifestId ||
766
+ candidate.scopePaths === undefined ||
767
+ candidate.scopePaths.length !== canonicalScope.length ||
768
+ candidate.scopePaths.some((path, index) => path !== canonicalScope[index])
769
+ ) continue;
770
+ return prepared;
771
+ }
772
+ return undefined;
773
+ }
774
+
675
775
  private rememberPreparedPlan(
676
776
  plan: RestorePlan,
677
777
  currentPaths: ReadonlyMap<string, OwnedPath>,
@@ -864,24 +964,24 @@ export class RestoreEngine {
864
964
  return { code: "recovery_required", verifiedPaths: 0, totalPaths: currentPaths.size };
865
965
  }
866
966
  const t1 = performance.now();
867
- try {
868
- // 兼容恢复路径会先在此窗口内补偿 pending mutations,因此只有非补偿路径可以跳过枚举入口的重复发现。
869
- await this.assertCompleteVisibleSubset(
870
- topologyBefore,
871
- [current, target],
872
- options.mutationJournal,
873
- {
874
- topologyValidated: !compatibilityMode,
875
- scopePaths: plan.scopePaths,
876
- ownedPaths: [currentPaths, targetPaths],
877
- },
878
- );
879
- } catch (error) {
880
- rethrowOperationFailure(error);
881
- return { code: "restore_failed_safe", verifiedPaths: 0, totalPaths: 0 };
882
- } finally {
883
- reportRestoreTiming(options.onTiming, "apply.visiblePre", t1);
884
- }
967
+ const visiblePreflight = this.assertCompleteVisibleSubset(
968
+ topologyBefore,
969
+ [current, target],
970
+ options.mutationJournal,
971
+ {
972
+ topologyValidated: !compatibilityMode,
973
+ // Pi runtime 持有 workspace 独占锁;restore-post 仍会复核 topology。
974
+ skipPostTopologyCheck: options.workspaceLockHeld === true,
975
+ scopePaths: plan.scopePaths,
976
+ ownedPaths: [currentPaths, targetPaths],
977
+ },
978
+ ).then(
979
+ () => true,
980
+ (error: unknown) => {
981
+ rethrowOperationFailure(error);
982
+ return false;
983
+ },
984
+ ).finally(() => reportRestoreTiming(options.onTiming, "apply.visiblePre", t1));
885
985
  let durablePack: DurablePack | undefined;
886
986
  if (
887
987
  !compatibilityMode &&
@@ -940,6 +1040,9 @@ export class RestoreEngine {
940
1040
  durablePack = undefined;
941
1041
  }
942
1042
  if (pinsDeferred && durablePack === undefined) {
1043
+ if (!await visiblePreflight) {
1044
+ return { code: "restore_failed_safe", verifiedPaths: 0, totalPaths: 0 };
1045
+ }
943
1046
  return this.applyWithOptions(
944
1047
  plan,
945
1048
  target,
@@ -952,6 +1055,9 @@ export class RestoreEngine {
952
1055
  nativeFileBatch !== undefined && durablePack !== undefined &&
953
1056
  this.canUseNativeFilePlan(plan, currentPaths, targetPaths)
954
1057
  ) {
1058
+ if (!await visiblePreflight) {
1059
+ return { code: "restore_failed_safe", verifiedPaths: 0, totalPaths: 0 };
1060
+ }
955
1061
  const result = await this.applyNativeFilePlan(
956
1062
  plan, current, target, currentPaths, targetPaths, topologyBefore, options, durablePack, nativeFileBatch.run,
957
1063
  );
@@ -970,10 +1076,13 @@ export class RestoreEngine {
970
1076
  [...targetPaths.keys()].filter((path) => !isPathAffectedByMutations(path, plan.deletePaths, plan.writePaths)),
971
1077
  );
972
1078
  const t3 = performance.now();
973
- const preflight = await this.verifyKnownState(
1079
+ const preflightPromise = this.verifyKnownState(
974
1080
  current, target, currentPaths, targetPaths, plan.scopePaths, reusableTargetPaths,
975
- );
976
- reportRestoreTiming(options.onTiming, "apply.preflight", t3);
1081
+ ).finally(() => reportRestoreTiming(options.onTiming, "apply.preflight", t3));
1082
+ const [visiblePathsValid, preflight] = await allCompleted([visiblePreflight, preflightPromise]);
1083
+ if (!visiblePathsValid) {
1084
+ return { code: "restore_failed_safe", verifiedPaths: 0, totalPaths: 0 };
1085
+ }
977
1086
  if (!preflight.ok) {
978
1087
  return {
979
1088
  code: "restore_failed_safe",