@davideasden/pi-undo 0.2.6 → 0.2.8

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
@@ -15,7 +15,7 @@ Each completed agent run creates a checkpoint that captures both the Pi session
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
16
  - **No Git workflow** — snapshots use a private object database. No `git commit`, `git stash`, `git reset`, branches, or forges are required.
17
17
  - **Nested repositories** and **initialized submodules** are handled as independent roots. Their `.git` metadata is never modified.
18
- - **Performance** — batch WAL operations (up to 1,024 files per batch), scoped safety snapshots, prebuilt durable transaction packs, native Rust no-clobber file helper for macOS arm64, 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 path.
18
+ - **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
19
 
20
20
  ## Requirements
21
21
 
@@ -23,28 +23,47 @@ Each completed agent run creates a checkpoint that captures both the Pi session
23
23
  - Node.js `22.19.0` or later.
24
24
  - Git available on `PATH` (used internally for content-addressed snapshots).
25
25
 
26
+ ### Rust 原生加速
27
+
28
+ pi-undo 包含跨平台 Rust 原生 helper(`pi-undo-fs`),用于加速文件系统操作。发布包会同时包含以下六个预编译二进制:
29
+
30
+ | 平台 | 架构 | 二进制名称 |
31
+ |---|---|---|
32
+ | macOS | arm64 | `pi-undo-fs-darwin-arm64` |
33
+ | macOS | x64 | `pi-undo-fs-darwin-x64` |
34
+ | Linux | arm64 | `pi-undo-fs-linux-arm64` |
35
+ | Linux | x64 | `pi-undo-fs-linux-x64` |
36
+ | Windows | arm64 | `pi-undo-fs-win32-arm64.exe` |
37
+ | Windows | x64 | `pi-undo-fs-win32-x64.exe` |
38
+
39
+ 扩展会根据当前运行环境自动选择对应二进制,因此用户无需安装 Rust,也无需手动选择平台。Windows 二进制带有 `.exe` 后缀。对于尚未提供预编译二进制的平台,扩展会自动回退到 TypeScript 路径,功能仍然可用。
40
+
26
41
  ## Installation
27
42
 
28
- Install the published package from npm:
43
+ ### npm 安装(推荐)
44
+
45
+ 所有受支持的平台使用同一个安装命令;npm 包会包含 macOS/Linux/Windows 的 arm64/x64 预编译 Rust helper,扩展启动时自动选择当前平台的版本:
29
46
 
30
47
  ```bash
31
48
  pi install npm:@davideasden/pi-undo
32
49
  ```
33
50
 
34
- Restart Pi if the extension is not already loaded.
51
+ 重启 Pi 即可加载扩展。用户不需要安装 Rust,也不需要手动选择或安装平台专用包。
35
52
 
36
- To install from a local checkout:
53
+ ### 从本地源码安装
37
54
 
38
55
  ```bash
39
56
  pi install /path/to/pi-undo
40
57
  ```
41
58
 
42
- During development, load the extension directly:
59
+ ### 开发模式直接加载
43
60
 
44
61
  ```bash
45
62
  pi -e /absolute/path/to/pi-undo/extensions/pi-undo.ts
46
63
  ```
47
64
 
65
+ > **注意**:`pi install` 会将整个包(包括 `native/bin/` 下的预编译二进制)复制到 Pi 的扩展目录。如果你从源码构建后想要包含新编译的原生二进制,确保运行 `npm run build:native` 后再执行 `pi install`。
66
+
48
67
  ## Usage
49
68
 
50
69
  Work with Pi normally. `pi-undo` automatically records a boundary after each completed agent run.
@@ -227,6 +246,8 @@ A transaction directory may contain `descriptor.json`, `restore-plan.json`, `sta
227
246
 
228
247
  ## Development
229
248
 
249
+ ### 依赖
250
+
230
251
  Clone the repository and install dependencies:
231
252
 
232
253
  ```bash
@@ -235,6 +256,25 @@ cd pi-undo
235
256
  npm install
236
257
  ```
237
258
 
259
+ ### 构建 Rust 原生 helper
260
+
261
+ 如果需要构建或更新原生二进制,确保已安装 [Rust 工具链](https://rustup.rs/):
262
+
263
+ ```bash
264
+ npm run build:native
265
+ ```
266
+
267
+ `npm run build:native` 会在 `native/pi-undo-fs/target/release/` 下生成当前构建平台的 `pi-undo-fs`。发布流程会在 macOS、Linux 和 Windows runner 上分别构建 arm64/x64 版本,统一重命名后放入 `native/bin/`,再打包成包含六个二进制的 npm 包。
268
+
269
+ 本地开发时,如果只需要验证当前平台,可以将生成的文件复制到 `native/bin/` 并按平台重命名,例如:Windows 生成的文件应使用对应的 `.exe` 文件名。
270
+
271
+ ```bash
272
+ cp native/pi-undo-fs/target/release/pi-undo-fs native/bin/pi-undo-fs-darwin-arm64
273
+ chmod +x native/bin/pi-undo-fs-darwin-arm64
274
+ ```
275
+
276
+ 发布包必须包含 Requirements 中列出的六个平台二进制;CI 会在打包前检查这一点,并在推送 `v*` tag 时发布该 CI 构建的完整 npm 包。npm 仓库需要为此 GitHub Actions workflow 配置 npm Trusted Publishing(OIDC)。如果当前平台没有对应二进制,扩展会自动使用 TypeScript 回退路径。
277
+
238
278
  ### Project Layout
239
279
 
240
280
  ```text
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@davideasden/pi-undo",
3
- "version": "0.2.6",
3
+ "version": "0.2.8",
4
4
  "description": "Persistent workspace undo and redo for Pi",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -6,7 +6,7 @@ import { fsyncDirectory, fsyncFile } from "./atomic-fs.ts";
6
6
  import { canonicalJson, checksum } from "./encoding.ts";
7
7
  import type { MutationJournal } from "./mutation-journal.ts";
8
8
  import { assertNoSymlinkEscape, relativeSafePath } from "./path-safety.ts";
9
- import { fingerprintAbsent, fingerprintBytes, fingerprintFile, fingerprintSymlink } from "./quarantine.ts";
9
+ import { fingerprintAbsent, fingerprintBytes, fingerprintFile, fingerprintLeaf, fingerprintSymlink } from "./quarantine.ts";
10
10
 
11
11
  const PACK_FILE = "durable-pack-v1.bin";
12
12
  const MAGIC = Buffer.from("PIUNDO-PACK-V1\0", "ascii");
@@ -315,13 +315,36 @@ export async function finalizeDurablePack(
315
315
  const directories = new Set<string>();
316
316
  await mapConcurrent(pack.paths(), FINALIZE_CONCURRENCY, async (path) => {
317
317
  const targetFingerprint = pack.targetFingerprint(path);
318
- if (targetFingerprint === undefined || targetFingerprint === null) return;
319
- const leaf = pack.leaf(path, targetFingerprint);
320
- if (leaf === undefined || leaf.kind === "absent") throw new Error(`durable pack target leaf 缺失:${path}`);
318
+ const targetLeaf = targetFingerprint === undefined || targetFingerprint === null
319
+ ? undefined
320
+ : pack.leaf(path, targetFingerprint);
321
321
  relativeSafePath(canonicalRoot, path);
322
322
  await assertNoSymlinkEscape(canonicalRoot, path);
323
323
  const absolute = join(canonicalRoot, ...path.split("/"));
324
324
  directories.add(dirname(absolute));
325
+ if (targetLeaf?.kind === "absent") {
326
+ if (await fingerprintLeaf(absolute, path) !== fingerprintAbsent(path)) {
327
+ throw new Error(`durable finalization delete 原路径不是 absent:${path}`);
328
+ }
329
+ const sourceFingerprint = pack.sourceFingerprint(path);
330
+ const sourceArtifact = pack.artifacts(path)?.source;
331
+ if (sourceFingerprint === undefined || sourceArtifact === undefined) {
332
+ throw new Error(`durable finalization delete source 缺失:${path}`);
333
+ }
334
+ const sourcePath = join(canonicalRoot, ...sourceArtifact.split("/"));
335
+ try {
336
+ if (await fingerprintFile(sourcePath, path) !== sourceFingerprint) {
337
+ throw new Error(`durable finalization delete source fingerprint 冲突:${path}`);
338
+ }
339
+ await fsyncFile(sourcePath);
340
+ directories.add(dirname(sourcePath));
341
+ } catch (error) {
342
+ if (!hasErrorCode(error, "ENOENT") || mutationStates?.get(path) !== "CLEANED") throw error;
343
+ }
344
+ return;
345
+ }
346
+ const leaf = targetLeaf;
347
+ if (leaf === undefined) throw new Error(`durable pack target leaf 缺失:${path}`);
325
348
  if (leaf.kind === "file") {
326
349
  const artifacts = pack.artifacts(path);
327
350
  if (artifacts?.target === null || artifacts?.target === undefined) {
@@ -48,10 +48,8 @@ export async function createNativeFileBatch(options: {
48
48
  const targetFingerprint = pack.targetFingerprint(path);
49
49
  if (
50
50
  artifacts === undefined ||
51
- artifacts.target === null ||
52
51
  sourceFingerprint === undefined ||
53
- targetFingerprint === undefined ||
54
- targetFingerprint === null
52
+ targetFingerprint === undefined
55
53
  ) {
56
54
  throw new Error(`native file batch pack entry 无效:${path}`);
57
55
  }
@@ -84,10 +82,12 @@ export async function createNativeFileBatch(options: {
84
82
  function nativeExecutable(): string | undefined {
85
83
  const platform = process.platform === "darwin"
86
84
  ? "darwin"
87
- : process.platform === "linux" ? "linux" : undefined;
85
+ : process.platform === "linux" ? "linux"
86
+ : process.platform === "win32" ? "win32" : undefined;
88
87
  const architecture = process.arch === "arm64" ? "arm64" : process.arch === "x64" ? "x64" : undefined;
89
88
  if (platform === undefined || architecture === undefined) return undefined;
90
- return fileURLToPath(new URL(`../native/bin/pi-undo-fs-${platform}-${architecture}`, import.meta.url));
89
+ const extension = process.platform === "win32" ? ".exe" : "";
90
+ return fileURLToPath(new URL(`../native/bin/pi-undo-fs-${platform}-${architecture}${extension}`, import.meta.url));
91
91
  }
92
92
 
93
93
  function runNative(executable: string, requestPath: string, expected: number): Promise<void> {
@@ -44,20 +44,28 @@ export async function recoverPackedMutations(options: {
44
44
  const pack = await loadDurablePack(options.journal, options.planDigest, true);
45
45
  const records = await ensurePackedIntents(options.journal, pack, await options.journal.load());
46
46
  await mapConcurrent(records, PACKED_RECOVERY_CONCURRENCY, async (record) => {
47
- if (record.kind !== "write" || record.targetArtifact === null) throw new Error("packed recovery 只支持普通文件 write");
47
+ if (record.state === "CLEANED" && record.kind === "delete") {
48
+ if (options.decision === "rollback") {
49
+ throw new Error(`CLEANED delete mutation 不能 rollback:${record.path}`);
50
+ }
51
+ return;
52
+ }
48
53
  const source = pack.leaf(record.path, record.sourceFingerprint);
49
54
  const target = pack.leaf(record.path, record.targetFingerprint);
50
- if (source === undefined || target === undefined || target.kind !== "file") {
55
+ if (source === undefined || target === undefined) {
51
56
  throw new Error(`packed recovery variant 缺失:${record.path}`);
52
57
  }
53
- await normalizeRecord(
54
- workspaceRoot,
55
- record,
56
- source,
57
- target,
58
- options.decision,
59
- options.retainArtifacts === true,
60
- );
58
+ if (record.kind === "delete") {
59
+ if (record.targetArtifact !== null || source.kind !== "file" || target.kind !== "absent") {
60
+ throw new Error(`packed recovery delete variant 无效:${record.path}`);
61
+ }
62
+ await normalizeDeletedRecord(workspaceRoot, record, source, options.decision, options.retainArtifacts === true);
63
+ return;
64
+ }
65
+ if (record.kind !== "write" || record.targetArtifact === null || target.kind !== "file") {
66
+ throw new Error(`packed recovery write variant 无效:${record.path}`);
67
+ }
68
+ await normalizeRecord(workspaceRoot, record, source, target, options.decision, options.retainArtifacts === true);
61
69
  });
62
70
  const terminalState: MutationState = options.retainArtifacts === true ? "TARGET_VERIFIED" : "CLEANED";
63
71
  const terminalIndex = stateOrder.indexOf(terminalState);
@@ -87,20 +95,29 @@ export async function cleanupPackedMutations(options: {
87
95
  const records = [...await options.journal.load()];
88
96
  const cleanupDirectories = new Set<string>();
89
97
  await mapConcurrent(records, PACKED_RECOVERY_CONCURRENCY, async (record) => {
90
- if (
91
- (record.state !== "TARGET_VERIFIED" && record.state !== "CLEANED") ||
92
- record.kind !== "write" ||
93
- record.targetArtifact === null
94
- ) {
98
+ if (record.state !== "TARGET_VERIFIED" && record.state !== "CLEANED") {
95
99
  throw new Error(`packed cleanup mutation 状态无效:${record.path}`);
96
100
  }
97
101
  relativeSafePath(workspaceRoot, record.path);
98
102
  await assertNoSymlinkEscape(workspaceRoot, record.path);
99
103
  const original = join(workspaceRoot, ...record.path.split("/"));
100
104
  const sourceArtifact = join(workspaceRoot, ...record.sourceArtifact.split("/"));
101
- const targetArtifact = join(workspaceRoot, ...record.targetArtifact.split("/"));
102
105
  const source = pack.leaf(record.path, record.sourceFingerprint);
103
106
  if (source === undefined) throw new Error(`packed cleanup source variant 缺失:${record.path}`);
107
+ if (record.kind === "delete") {
108
+ if (record.targetArtifact !== null || pack.targetFingerprint(record.path) !== fingerprintAbsent(record.path)) {
109
+ throw new Error(`packed cleanup delete mutation 无效:${record.path}`);
110
+ }
111
+ if (await fingerprintLeaf(original, record.path) !== fingerprintAbsent(record.path)) {
112
+ throw new Error(`packed cleanup delete original 不是 absent:${record.path}`);
113
+ }
114
+ await cleanupArtifact(sourceArtifact, record.path, record.sourceFingerprint, cleanupDirectories);
115
+ return;
116
+ }
117
+ if (record.kind !== "write" || record.targetArtifact === null) {
118
+ throw new Error(`packed cleanup write mutation 无效:${record.path}`);
119
+ }
120
+ const targetArtifact = join(workspaceRoot, ...record.targetArtifact.split("/"));
104
121
  if (await pathExists(targetArtifact)) {
105
122
  await assertSameFileIdentity(original, targetArtifact, record.path);
106
123
  } else if (record.state !== "CLEANED") {
@@ -140,22 +157,18 @@ function packedIntent(pack: DurablePack, path: string) {
140
157
  const artifacts = pack.artifacts(path);
141
158
  const sourceFingerprint = pack.sourceFingerprint(path);
142
159
  const targetFingerprint = pack.targetFingerprint(path);
143
- if (
144
- artifacts === undefined ||
145
- artifacts.target === null ||
146
- sourceFingerprint === undefined ||
147
- targetFingerprint === undefined ||
148
- targetFingerprint === null
149
- ) {
160
+ if (artifacts === undefined || sourceFingerprint === undefined || targetFingerprint === undefined) {
150
161
  throw new Error(`packed recovery intent 缺失:${path}`);
151
162
  }
152
163
  return {
153
- kind: "write" as const,
164
+ kind: artifacts.target === null && (targetFingerprint === null || targetFingerprint === fingerprintAbsent(path))
165
+ ? "delete" as const
166
+ : "write" as const,
154
167
  path,
155
168
  sourceArtifact: artifacts.source,
156
169
  targetArtifact: artifacts.target,
157
170
  sourceFingerprint,
158
- targetFingerprint,
171
+ targetFingerprint: targetFingerprint ?? fingerprintAbsent(path),
159
172
  };
160
173
  }
161
174
 
@@ -173,6 +186,35 @@ function assertPackedRecord(pack: DurablePack, path: string, record: MutationRec
173
186
  }
174
187
  }
175
188
 
189
+ async function normalizeDeletedRecord(
190
+ workspaceRoot: string,
191
+ record: MutationRecord,
192
+ source: DurableLeaf,
193
+ decision: "rollback" | "roll_forward",
194
+ retainArtifacts: boolean,
195
+ ): Promise<void> {
196
+ if (source.kind !== "file" || record.targetArtifact !== null) {
197
+ throw new Error(`delete mutation variant 无效:${record.path}`);
198
+ }
199
+ relativeSafePath(workspaceRoot, record.path);
200
+ await assertNoSymlinkEscape(workspaceRoot, record.path);
201
+ const original = join(workspaceRoot, ...record.path.split("/"));
202
+ const sourceArtifact = join(workspaceRoot, ...record.sourceArtifact.split("/"));
203
+ const absent = fingerprintAbsent(record.path);
204
+ const observed = await fingerprintLeaf(original, record.path);
205
+ if (observed !== absent && observed !== record.sourceFingerprint) {
206
+ throw new Error(`delete mutation original 冲突:${record.path}`);
207
+ }
208
+ await assertArtifact(sourceArtifact, record.path, record.sourceFingerprint, false);
209
+ if (decision === "rollback") {
210
+ if (observed === absent) await materialize(original, record.path, source);
211
+ if (!retainArtifacts) await cleanupArtifact(sourceArtifact, record.path, record.sourceFingerprint);
212
+ return;
213
+ }
214
+ if (observed !== absent) throw new Error(`delete mutation roll-forward original 未删除:${record.path}`);
215
+ if (!retainArtifacts) await cleanupArtifact(sourceArtifact, record.path, record.sourceFingerprint);
216
+ }
217
+
176
218
  async function normalizeRecord(
177
219
  workspaceRoot: string,
178
220
  record: MutationRecord,
package/src/pi-runtime.ts CHANGED
@@ -4,7 +4,6 @@ import type {
4
4
  ExtensionAPI,
5
5
  ExtensionCommandContext,
6
6
  ExtensionContext,
7
- ReadonlySessionManager,
8
7
  } from "@earendil-works/pi-coding-agent";
9
8
 
10
9
  import {
@@ -30,6 +29,8 @@ import { SnapshotStore } from "./snapshot-store.ts";
30
29
  import { StatusReporter } from "./status-reporter.ts";
31
30
  import { WorkspaceLock } from "./workspace-lock.ts";
32
31
 
32
+ type ReadonlySessionManager = ExtensionContext["sessionManager"];
33
+
33
34
  export async function createPiUndoRuntime(context: ExtensionContext, pi: ExtensionAPI) {
34
35
  const manager = context.sessionManager;
35
36
  const sessionState = sessionStateFor(manager);
@@ -253,7 +253,7 @@ export class RestoreEngine {
253
253
  ): Promise<void> {
254
254
  const plan = await this.plan(current, target, scopePaths);
255
255
  const prepared = this.takePreparedPlan(plan);
256
- if (prepared === undefined || !this.canUseNativeFilePlan(plan, prepared.targetPaths)) return;
256
+ if (prepared === undefined || !this.canUseNativeFilePlan(plan, prepared.currentPaths, prepared.targetPaths)) return;
257
257
  const cacheRoot = await this.store.durableCacheDirectory();
258
258
  const cacheOpId = `cache-${plan.planDigest}`;
259
259
  const cacheJournal = new MutationJournal(
@@ -528,7 +528,7 @@ export class RestoreEngine {
528
528
  !compatibilityMode &&
529
529
  options.deferDurability === true &&
530
530
  options.forceTargetArtifactSync !== true &&
531
- this.canUseNativeFilePlan(plan, targetPaths)
531
+ this.canUseNativeFilePlan(plan, currentPaths, targetPaths)
532
532
  ) {
533
533
  try {
534
534
  const cached = this.durablePackCache.get(plan.planDigest);
@@ -574,7 +574,7 @@ export class RestoreEngine {
574
574
  );
575
575
  }
576
576
  const durablePackEnabled = durablePack !== undefined;
577
- if (nativeFileBatch !== undefined && durablePack !== undefined && this.canUseNativeFilePlan(plan, targetPaths)) {
577
+ if (nativeFileBatch !== undefined && durablePack !== undefined && this.canUseNativeFilePlan(plan, currentPaths, targetPaths)) {
578
578
  const result = await this.applyNativeFilePlan(
579
579
  plan,
580
580
  current,
@@ -661,11 +661,20 @@ export class RestoreEngine {
661
661
 
662
662
  private canUseNativeFilePlan(
663
663
  plan: RestorePlan,
664
+ currentPaths: ReadonlyMap<string, OwnedPath>,
664
665
  targetPaths: ReadonlyMap<string, OwnedPath>,
665
666
  ): boolean {
666
- return plan.deletePaths.length === 0 &&
667
+ const writeOnly = plan.deletePaths.length === 0 &&
667
668
  plan.writePaths.length > 0 &&
668
669
  plan.writePaths.every((path) => targetPaths.get(path)?.entry.kind === "file");
670
+ const deleteOnly = process.platform !== "win32" &&
671
+ plan.writePaths.length === 0 &&
672
+ plan.deletePaths.length > 0 &&
673
+ plan.deletePaths.every((path) =>
674
+ currentPaths.get(path)?.entry.kind === "file" &&
675
+ targetPaths.get(path) === undefined &&
676
+ !path.includes("/"));
677
+ return writeOnly || deleteOnly;
669
678
  }
670
679
 
671
680
  private async applyNativeFilePlan(
@@ -694,10 +703,11 @@ export class RestoreEngine {
694
703
  : [artifacts.source, ...(artifacts.target === null ? [] : [artifacts.target])];
695
704
  }),
696
705
  );
706
+ const totalPaths = plan.deletePaths.length + plan.writePaths.length;
697
707
  if ((await options.mutationJournal.load()).length !== 0) {
698
- return { code: "recovery_required", verifiedPaths: 0, totalPaths: plan.writePaths.length };
708
+ return { code: "recovery_required", verifiedPaths: 0, totalPaths };
699
709
  }
700
- return { code: "ok", verifiedPaths: plan.writePaths.length, totalPaths: plan.writePaths.length };
710
+ return { code: "ok", verifiedPaths: totalPaths, totalPaths };
701
711
  } catch {
702
712
  const packedRecovery = await recoverPackedMutations({
703
713
  workspaceRoot: this.workspaceRoot,
@@ -706,7 +716,11 @@ export class RestoreEngine {
706
716
  decision: "rollback",
707
717
  });
708
718
  if (packedRecovery.kind !== "clean") {
709
- return { code: "recovery_required", verifiedPaths: 0, totalPaths: plan.writePaths.length };
719
+ return {
720
+ code: "recovery_required",
721
+ verifiedPaths: 0,
722
+ totalPaths: plan.deletePaths.length + plan.writePaths.length,
723
+ };
710
724
  }
711
725
  return this.rollback(
712
726
  current,
@@ -761,7 +775,7 @@ export class RestoreEngine {
761
775
  sourceArtifact: artifact("source"),
762
776
  targetArtifact: targetLeaf?.kind === "file" ? artifact("target") : null,
763
777
  sourceFingerprint: currentLeaf?.fingerprint ?? absent.fingerprint,
764
- targetFingerprint: targetLeaf?.fingerprint ?? null,
778
+ targetFingerprint: targetLeaf?.fingerprint ?? absent.fingerprint,
765
779
  variants: [...variants.values()],
766
780
  });
767
781
  }