@davideasden/pi-undo 0.3.0 → 0.3.2

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
@@ -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.0",
3
+ "version": "0.3.2",
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
@@ -164,6 +164,8 @@ export interface UndoController {
164
164
  cancelOperation?(): boolean;
165
165
  dispose?(): Promise<void>;
166
166
  recover(): Promise<void>;
167
+ /** 后台耐久化失败时锁住当前 runtime,等待显式 recovery。 */
168
+ markRecoveryRequired?(reason: string): void;
167
169
  history(): HistoryState;
168
170
  /** 当前 recovery lock 的原因;未锁定时返回 undefined。 */
169
171
  recoveryReason?(): string | undefined;
@@ -342,6 +344,10 @@ export class UndoControllerImpl implements UndoController {
342
344
  }
343
345
  }
344
346
 
347
+ markRecoveryRequired(reason: string): void {
348
+ this.lock(reason);
349
+ }
350
+
345
351
  private recoveryResult(changedFiles = 0): OperationResult {
346
352
  return {
347
353
  code: "recovery_required",
@@ -356,7 +362,7 @@ export class UndoControllerImpl implements UndoController {
356
362
 
357
363
  warmUp(): void {
358
364
  if (this.disposed || this.locked || this.warmUpInFlight !== undefined) return;
359
- this.warmUpInFlight = this.runBackground(async () => {
365
+ const warmUp = this.runBackground(async () => {
360
366
  try {
361
367
  this.warmUpManifest = await this.captureWithWorkspaceLock();
362
368
  } catch (error) {
@@ -364,6 +370,12 @@ export class UndoControllerImpl implements UndoController {
364
370
  // 预热是 best-effort:失败静默,正式 capture 会再次尝试并上报。
365
371
  }
366
372
  });
373
+ this.warmUpInFlight = warmUp;
374
+ void warmUp.finally(() => {
375
+ if (this.warmUpInFlight === warmUp && this.warmUpManifest === undefined) {
376
+ this.warmUpInFlight = undefined;
377
+ }
378
+ }).catch(() => {});
367
379
  }
368
380
 
369
381
  captureFailureReason(): string | undefined {
@@ -485,6 +497,7 @@ export class UndoControllerImpl implements UndoController {
485
497
  if (warmUp !== undefined) await warmUp;
486
498
  const warmUpManifest = this.warmUpManifest;
487
499
  this.warmUpManifest = undefined;
500
+ if (this.warmUpInFlight === warmUp) this.warmUpInFlight = undefined;
488
501
  const capture = (): Promise<SnapshotManifest> => warmUpManifest !== undefined && this.dependencies.captureBaseline !== undefined
489
502
  ? this.captureBaselineWithWorkspaceLock(warmUpManifest)
490
503
  : this.captureWithWorkspaceLock();
@@ -563,20 +576,10 @@ export class UndoControllerImpl implements UndoController {
563
576
  const changedPaths = await measure("settled.changedPaths", () =>
564
577
  this.dependencies.changedPaths(staged.before, after));
565
578
  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
- }
579
+ // undo 是完成后最常见、也最需要即时响应的方向;redo cache 放到后台构建,
580
+ // 避免每个普通 run 的 agent_settled 同步等待两套 durable pack。
581
+ await measure("settled.prepareUndo", () =>
582
+ this.dependencies.prepareDurableRestore!(after, staged.before, changedPaths));
580
583
  checkOperation();
581
584
  }
582
585
  const endLeafId = this.dependencies.getLogicalLeafId() ?? staged.startEntryId;
@@ -589,6 +592,20 @@ export class UndoControllerImpl implements UndoController {
589
592
  return;
590
593
  }
591
594
  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 () => {
600
+ try {
601
+ await this.dependencies.prepareDurableRestore!(staged.before, after, changedPaths);
602
+ } catch (error) {
603
+ // redo 有安全的惰性路径;后台预制失败不应拖慢或暂停当前历史。
604
+ this.recordUnsafeExit(error);
605
+ }
606
+ });
607
+ void prepareRedo.catch(() => {});
608
+ }
592
609
  } catch (error) {
593
610
  this.recordUnsafeExit(error);
594
611
  this.historyPaused = true;
package/src/pi-runtime.ts CHANGED
@@ -58,14 +58,14 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
58
58
  const capture = async (scopePaths?: readonly string[]) => {
59
59
  const topology = await discovery.discover(context.cwd);
60
60
  if (topology.workspaceIdentity !== initialTopology.workspaceIdentity) {
61
- throw new Error("workspace identity 已变化");
61
+ throw new Error("workspace_identity_changed: workspace root canonical path changed; run /undo-recover");
62
62
  }
63
63
  return store.capture(topology, scopePaths, { topologyAlreadyValidated: true });
64
64
  };
65
65
  const captureBaseline = async (baseline: SnapshotManifest) => {
66
66
  const topology = await discovery.discover(context.cwd);
67
67
  if (topology.workspaceIdentity !== initialTopology.workspaceIdentity) {
68
- throw new Error("workspace identity 已变化");
68
+ throw new Error("workspace_identity_changed: workspace root canonical path changed; run /undo-recover");
69
69
  }
70
70
  return store.captureBaseline(topology, baseline, undefined, { topologyAlreadyValidated: true });
71
71
  };
@@ -150,6 +150,7 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
150
150
 
151
151
  let finalizationQueue: Promise<void> = Promise.resolve();
152
152
  let finalizationFailure: unknown;
153
+ let controller: UndoControllerImpl | undefined;
153
154
  const waitForFinalization = async (): Promise<void> => {
154
155
  await finalizationQueue;
155
156
  if (finalizationFailure !== undefined) throw finalizationFailure;
@@ -179,6 +180,9 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
179
180
  }
180
181
  }))).catch((error: unknown) => {
181
182
  finalizationFailure = error;
183
+ controller?.markRecoveryRequired(`finalization_failed:${opId}`);
184
+ reporter.setRecoveryRequired(`finalization_failed:${opId}`);
185
+ context.ui.notify(`pi-undo 后台持久化失败(op:${opId}):已锁定撤回历史,请运行 /undo-recover 重试`, "error");
182
186
  });
183
187
  };
184
188
  const transactionJournal: ControllerDependencies["journal"] = {
@@ -301,14 +305,16 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
301
305
  initialTopology.workspaceIdentity,
302
306
  () => recovery.recover(),
303
307
  );
304
- const controller = new UndoControllerImpl(dependencies, {
308
+ controller = new UndoControllerImpl(dependencies, {
305
309
  ...rebuildControllerState(manager, sessionIdentity),
306
310
  locked: startupRecovery.kind === "locked",
307
311
  recoveryReason: startupRecovery.kind === "locked" ? startupRecovery.reason : undefined,
308
312
  recoveryCompleted: true,
309
313
  });
314
+ const activeController = controller;
315
+ if (activeController === undefined) throw new Error("pi-undo controller 初始化失败");
310
316
  return {
311
- controller,
317
+ controller: activeController,
312
318
  reporter,
313
319
  diffSource: store,
314
320
  recovery: startupRecovery.kind === "locked"
@@ -316,7 +322,7 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
316
322
  : undefined,
317
323
  async dispose(): Promise<void> {
318
324
  try {
319
- await controller.dispose();
325
+ await activeController.dispose();
320
326
  await finalizationQueue;
321
327
  if (isUnconfirmedExit(finalizationFailure)) throw finalizationFailure;
322
328
  } finally {