@davideasden/pi-undo 0.2.33 → 0.3.0

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.
@@ -0,0 +1,63 @@
1
+ # Pi 0.86.1 撤回修复与验证记录
2
+
3
+ 验证环境:macOS 26.5.2、arm64、Node.js 23.11.1、Pi SDK 0.86.1。原生路径使用仓库已有的 macOS arm64 helper;本次未修改 Rust 二进制协议。所有 SDK 场景使用离线 faux provider,不请求模型网络。
4
+
5
+ ## 支持范围与行为
6
+
7
+ - 最低支持版本调整为 Pi 0.86.1,开发依赖与测试夹具固定为 0.86.1,不再承诺 0.84.4 兼容。
8
+ - 撤回先停止当前运行,等待输入快照和本轮检查点完成,再选择目标并获取工作区锁。检查点失败会暂停历史,不会撤回上一轮来代替。
9
+ - `/undo-cancel` 请求停止当前撤回或重做。Git 默认 120 秒,操作默认 300 秒,分别通过 `PI_UNDO_GIT_TIMEOUT_MS`、`PI_UNDO_OPERATION_TIMEOUT_MS` 调整。
10
+ - 取消后等在途任务和并行分支收敛,未提交的操作使用独立预算恢复;cursor 已持久提交时继续完成持久化。不能确认子进程停止时保留隔离,拒绝重建 runtime。
11
+ - `/tree` 在适配层区分物理节点、逻辑目标和摘要后的实际逻辑叶。摘要错误或其他扩展取消时,即使缺少 `session_tree` 事件,也会在确认 Pi 导航结束后清理准备事务。
12
+ - runtime 重建及退出会等待旧任务与后台持久化。重建时排队文本恢复到编辑器;迟到的 settled 事件不再追加检查点。
13
+ - 普通文件原生恢复路径将完整拓扑扫描从 7 次降到 5 次,目录枚举采用有界并发。仍发现忽略目录中的嵌套仓库,保留枚举后与恢复后的复核。
14
+ - 沿用 schemaVersion 1 的会话记录、manifest、journal 与 WAL;旧记录仍可读取,不重建缺失或损坏的历史。
15
+
16
+ 长操作和错误的最近一次诊断写入 `<sessionDir>/.pi-undo/diagnostics/<sessionId>-latest.json`,只保留操作 ID、阶段、耗时、已知 Git 子命令名及退出结果,不记录提示词、文件内容、完整参数或进程输出。
17
+
18
+ ## 回归覆盖
19
+
20
+ 真实 SDK 回归包含普通 undo/redo、同一 JSONL 重启重建、第二轮 settled 未结束时撤回、用户节点与根目标导航、摘要导航、摘要失败、其他扩展取消导航。
21
+
22
+ 故障注入包含挂起 Git 和后台后代终止、外部信号终止后清理后代、native helper 取消、TypeScript 部分写入取消、native 写入后验证前取消、cursor 提交前后分流、不可中断任务结束前保留锁、未确认退出时拒绝 runtime 重建,以及丢失事件和排队输入的处理。
23
+
24
+ 验证命令:
25
+
26
+ ```bash
27
+ npm run typecheck
28
+ npm test
29
+ PI_UNDO_DISABLE_NATIVE=1 npm test
30
+ cargo test --manifest-path native/pi-undo-fs/Cargo.toml
31
+ npm run pack:dry-run
32
+ PI_UNDO_LARGE_WORKSPACE=1 PI_UNDO_BENCH_REPORT=/tmp/pi-undo-large-results.jsonl npx vitest run test/large-workspace.test.ts
33
+ ```
34
+
35
+ 验证结果:
36
+
37
+ | 检查 | 结果 |
38
+ | --- | --- |
39
+ | TypeScript 类型检查 | 通过 |
40
+ | 标准完整套件 | 593 项通过,4 个按需大型基准用例跳过 |
41
+ | 禁用 native helper 的完整套件 | 585 项通过,12 项按条件跳过 |
42
+ | Rust 原生测试 | 3 项通过 |
43
+ | 大型工作区真实 SDK 基准 | 4 组通过,每组三次撤回/重做 |
44
+ | npm 打包清单、Git 空白错误检查 | 通过 |
45
+
46
+ 标准套件包含 native helper 的专项测试;回退套件跳过依赖 native 能力的用例。大型基准单独显式开启并通过,不计入标准套件的通过数。
47
+
48
+ ## 大型工作区测量
49
+
50
+ 每组构建 3,000 或 10,000 个模拟依赖包,每包包含 `lib/index.js`,依赖目录由 `.gitignore` 忽略;工作区不初始化真实 Git 仓库。实际修改 1 或 100 个文件,使用真实 Pi SDK 执行三次 undo/redo,逐文件断言内容与历史状态。下面的耗时仅统计 undo。
51
+
52
+ | 依赖包数 | 修改文件数 | 三次撤回耗时(毫秒) | 中位数(毫秒) | 每次完整扫描 | 进程峰值 RSS(MiB) | 事件循环延迟 P99(毫秒) |
53
+ | ---: | ---: | --- | ---: | --- | ---: | ---: |
54
+ | 3,000 | 1 | 1743 / 1769 / 1978 | 1769 | 5 / 5 / 5 | 228 | 13 |
55
+ | 3,000 | 100 | 1811 / 1804 / 1800 | 1804 | 5 / 5 / 5 | 354 | 13 |
56
+ | 10,000 | 1 | 5366 / 6051 / 6276 | 6051 | 5 / 5 / 5 | 422 | 15 |
57
+ | 10,000 | 100 | 5730 / 5666 / 6138 | 5730 | 5 / 5 / 5 | 447 | 15 |
58
+
59
+ RSS 是同一测试进程连续执行各组时的观测峰值,包含 Pi SDK 和缓存,不是单次撤回的新增内存。事件循环延迟覆盖三轮撤回与重做,不等同于 TUI 的绘制耗时。墙钟数据受文件系统和机器负载影响,因此常规 CI 使用扫描次数和正确性断言,不设置固定耗时门槛。
60
+
61
+ ## 边界
62
+
63
+ 本次测试平台为 macOS arm64,未在 Windows 或 Linux 上重新执行整套验证。不可中断的底层磁盘 I/O 必须实际结束后才安全释放隔离,不能承诺任意磁盘故障都在固定秒数内解除锁。大型工作区仍需要完整扫描;本次没有增加 Rust 目录扫描协议或默认排除目录。
@@ -0,0 +1,31 @@
1
+ # Pi 1.2.0 兼容验证记录
2
+
3
+ 验证环境:macOS arm64、Node.js 23.11.1、Pi SDK 1.2.0(`~/.pi/agent/install/releases/1.2.0`)。所有 SDK 场景使用离线 faux provider,不请求模型网络。
4
+
5
+ ## 结论
6
+
7
+ pi-undo 0.2.32 在 Pi 1.2.0 上无需改动源码即可运行。最低支持版本由 0.86.1 提升到 1.2.0,开发依赖与测试夹具固定为 1.2.0。
8
+
9
+ ## 验证内容
10
+
11
+ | 检查 | 0.86.1 | 1.2.0 |
12
+ | --- | --- | --- |
13
+ | `npm run typecheck`(`src`/`extensions`/`test`) | 通过 | 通过 |
14
+ | `npm test` | 24 文件通过/1 跳过,635 项通过、4 项跳过 | 完全一致 |
15
+ | 真实加载器加载 `extensions/pi-undo.ts` | — | 0 错误,注册 `undo`/`redo`/`diff`/`undo-cancel`/`undo-recover` 与全部 8 个事件处理器 |
16
+
17
+ 加载器检查使用 1.2.0 的 `discoverAndLoadExtensions()`(与 Pi 启动时相同的 jiti 路径),在隔离目录中加载扩展文件,断言 `errors` 为空且命令与事件齐全。跳过项是需显式开启的大型工作区基准(`PI_UNDO_LARGE_WORKSPACE=1`)。
18
+
19
+ ## 1.1.0 → 1.2.0 破坏性变更核对
20
+
21
+ - `before_agent_start` 现在是联合类型,且对 `pi.sendMessage(..., { triggerTurn: true })` 触发的自定义消息 run 也会触发。pi-undo 的处理器不读取事件对象;自定义 run 没有 staged 输入,`beforeAgentStart()` 与 `agentSettled()` 都会提前返回,因此只多一次空调用。
22
+ - 会话在 run 启动期间(含 `before_agent_start` 处理器内)记为 busy,`pi.sendUserMessage()` 此时需要 `deliverAs`。pi-undo 只在撤回/重做完成且空闲后重放排队输入;即使出现竞态,运行时也会把错误作为扩展错误上报,不会中断 Pi。
23
+ - `agent_settled` 新增 `aborted` 字段,纯增量,pi-undo 不使用。
24
+
25
+ ## 版本解析
26
+
27
+ Pi 的 jiti 加载器通过虚拟模块把 `@earendil-works/pi-coding-agent`、`@earendil-works/pi-tui` 等映射到运行实例,因此扩展不会与本地 `node_modules` 中的旧版本混用。
28
+
29
+ ## 边界
30
+
31
+ 未在 Windows/Linux 上重复整套验证;未覆盖与其他扩展同时触发 `before_agent_start` 的交互式 TUI 场景。0.86.1 的历史记录见 [pi-0.86.1-validation.md](pi-0.86.1-validation.md)。
@@ -382,17 +382,28 @@ export function createPiUndoExtension(runtimeFactory: PiUndoRuntimeFactory): (pi
382
382
  acceptedReplay = undefined;
383
383
  }
384
384
  });
385
- pi.on("agent_settled", async () => {
385
+ pi.on("agent_settled", (event, context) => {
386
386
  const active = runtime;
387
387
  const settledGeneration = generation;
388
388
  if (active === undefined) return;
389
- await active.controller.agentSettled();
390
- if (runtime !== active || generation !== settledGeneration) return;
391
- if (activeCommands.size === 0) resumeDeferredPrompts(
392
- active,
393
- settledGeneration,
394
- active.controller.recoveryReason?.() ?? "session state ambiguous",
395
- );
389
+ const finishSettled = (): void => {
390
+ if (runtime !== active || generation !== settledGeneration) return;
391
+ if (activeCommands.size === 0) resumeDeferredPrompts(
392
+ active,
393
+ settledGeneration,
394
+ active.controller.recoveryReason?.() ?? "session state ambiguous",
395
+ );
396
+ };
397
+ const failSettled = (error: unknown): void => {
398
+ if (runtime !== active || generation !== settledGeneration) return;
399
+ active.reporter.setRecoveryRequired(errorMessage(error));
400
+ restoreDeferredPrompts(runtimeContext);
401
+ };
402
+ const settling = active.controller.agentSettled();
403
+ // RPC/print 的正常调用仍保留“prompt 返回即检查点完成”的契约;用户中断的 run
404
+ // 和交互式 TUI 则必须让生命周期事件立即返回,否则 Esc/树导航会被快照拖住。
405
+ if (context.mode !== "tui" && !event.aborted) return settling.then(finishSettled, failSettled);
406
+ void settling.then(finishSettled, failSettled);
396
407
  });
397
408
  pi.on("session_before_tree", async (event: PiSessionBeforeTreeEvent, context: ExtensionContext) => {
398
409
  if (runtime === undefined || initializing) return { cancel: true };
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.2.33",
3
+ "version": "0.3.0",
4
4
  "description": "Persistent workspace undo and redo for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -35,7 +35,9 @@
35
35
  "src",
36
36
  "native/bin",
37
37
  "README.md",
38
- "docs/native-performance.md"
38
+ "docs/native-performance.md",
39
+ "docs/pi-0.86.1-validation.md",
40
+ "docs/pi-1.2.0-validation.md"
39
41
  ],
40
42
  "scripts": {
41
43
  "test": "vitest run",
package/src/controller.ts CHANGED
@@ -816,11 +816,11 @@ export class UndoControllerImpl implements UndoController {
816
816
  this.lastSafetyManifestId = null;
817
817
  let lease: { release(): Promise<void> } | undefined;
818
818
  try {
819
- if (!await profile.measure("idle", () => this.ensureIdle())) {
820
- checkOperation();
821
- return done({ code: "idle_timeout", changedFiles: 0 });
822
- }
823
- if (!await profile.measure("checkpoint", () => this.waitForCheckpoint())) {
819
+ const [idleReady, checkpointReady] = await Promise.all([
820
+ profile.measure("idle", () => this.ensureIdle()),
821
+ profile.measure("checkpoint", () => this.waitForCheckpoint()),
822
+ ]);
823
+ if (!idleReady || !checkpointReady) {
824
824
  checkOperation();
825
825
  return done({ code: "idle_timeout", changedFiles: 0 });
826
826
  }
@@ -7,6 +7,7 @@ import { GitRunError, runSupervisedProcess } from "./git-runner.ts";
7
7
  import { probeNativeCapabilities } from "./native-capabilities.ts";
8
8
  import { nativeExecutable } from "./native-restore.ts";
9
9
  import { checkOperation, configuredTimeout, OperationError, operationProcessOptions } from "./operation-context.ts";
10
+ import { ResidentScanClient } from "./resident-scan-client.ts";
10
11
 
11
12
  export interface NativeRepositoryCandidate {
12
13
  readonly path: string;
@@ -21,6 +22,10 @@ export interface NativeDirectoryScan {
21
22
 
22
23
  export interface NativeDirectoryScanPort {
23
24
  scan(workspaceRoot: string): Promise<NativeDirectoryScan | undefined>;
25
+ /** 可选的会话级预热;测试替身和旧调用方无需实现。 */
26
+ prewarm?(workspaceRoot: string): void;
27
+ /** 运行时销毁时关闭常驻 helper,避免跨会话遗留进程。 */
28
+ dispose?(): Promise<void>;
24
29
  }
25
30
 
26
31
  const nativeScanCacheDirectories = new Set<string>();
@@ -45,30 +50,92 @@ function isPathInside(root: string, candidate: string): boolean {
45
50
  /** 原生 helper 能力之外,目录快照只在逐目录元数据仍可证明时复用。 */
46
51
  export class NativeDirectoryScanner implements NativeDirectoryScanPort {
47
52
  private readonly executable: string | undefined;
48
- private capability: Promise<"v2" | "v1" | undefined> | undefined;
53
+ private capabilities: Promise<ReadonlySet<string>> | undefined;
49
54
  private cacheDirectory: Promise<string> | undefined;
55
+ private resident: { readonly workspaceRoot: string; readonly client: ResidentScanClient } | undefined;
56
+ private prewarmInFlight: { readonly workspaceRoot: string; readonly promise: Promise<void> } | undefined;
50
57
 
51
58
  constructor(executable = nativeExecutable()) {
52
59
  this.executable = process.env.PI_UNDO_DISABLE_NATIVE === "1" || process.platform === "win32"
53
60
  ? undefined : executable;
54
61
  }
55
62
 
63
+ /**
64
+ * 会话初始化时只预热常驻扫描,不触发一次性 helper。
65
+ * 正式 discover 会等待这次预热完成,然后请求同一个 serve 缓存,保证变化仍被事件失效检查覆盖。
66
+ */
67
+ prewarm(workspaceRoot: string): void {
68
+ if (this.executable === undefined || this.prewarmInFlight?.workspaceRoot === workspaceRoot) return;
69
+ const promise = this.prewarmResident(workspaceRoot).catch(() => undefined).finally(() => {
70
+ if (this.prewarmInFlight?.promise === promise) this.prewarmInFlight = undefined;
71
+ });
72
+ this.prewarmInFlight = { workspaceRoot, promise };
73
+ }
74
+
75
+ /** 运行时销毁时关闭常驻 helper。 */
76
+ async dispose(): Promise<void> {
77
+ await this.prewarmInFlight?.promise;
78
+ await this.resident?.client.close();
79
+ this.resident = undefined;
80
+ }
81
+
82
+ private async prewarmResident(workspaceRoot: string): Promise<void> {
83
+ const temporaryRoot = await realpath(tmpdir()).catch(() => undefined);
84
+ if (temporaryRoot === undefined || isPathInside(workspaceRoot, temporaryRoot)) return;
85
+ const requestDirectory = await mkdtemp(join(temporaryRoot, "pi-undo-native-serve-probe-"));
86
+ try {
87
+ const capabilities = await this.probeCapabilities(requestDirectory);
88
+ if (!capabilities.has("scan-serve-v1")) return;
89
+ const client = this.ensureResident(workspaceRoot);
90
+ if (client !== undefined) await client.prewarm();
91
+ } finally {
92
+ await rm(requestDirectory, { recursive: true, force: true }).catch(() => {});
93
+ }
94
+ }
95
+
96
+ private ensureResident(workspaceRoot: string): ResidentScanClient | undefined {
97
+ if (this.executable === undefined) return undefined;
98
+ if (this.resident?.workspaceRoot === workspaceRoot) return this.resident.client;
99
+ if (this.resident !== undefined) void this.resident.client.close();
100
+ const client = new ResidentScanClient(
101
+ this.executable,
102
+ workspaceRoot,
103
+ configuredTimeout("PI_UNDO_OPERATION_TIMEOUT_MS", 300_000),
104
+ );
105
+ this.resident = { workspaceRoot, client };
106
+ return client;
107
+ }
108
+
56
109
  async scan(workspaceRoot: string): Promise<NativeDirectoryScan | undefined> {
57
110
  checkOperation();
58
- if (this.executable === undefined ||
59
- (this.capability !== undefined && await this.capability === undefined)) return undefined;
111
+ if (this.executable === undefined) return undefined;
112
+ const pendingPrewarm = this.prewarmInFlight;
113
+ if (pendingPrewarm?.workspaceRoot === workspaceRoot) await pendingPrewarm.promise;
114
+ checkOperation();
60
115
  // TMPDIR 可能通过符号链接指向工作区;先核验真实路径,再创建任何请求或缓存。
61
116
  const temporaryRoot = await realpath(tmpdir()).catch(() => undefined);
62
117
  if (temporaryRoot === undefined || isPathInside(workspaceRoot, temporaryRoot)) return undefined;
63
118
  const requestDirectory = await mkdtemp(join(temporaryRoot, "pi-undo-native-scan-"));
64
119
  try {
65
- this.capability ??= this.supportsScan(requestDirectory).catch((error) => {
66
- // 取消或未确认终止不能污染后续操作的能力缓存。
67
- this.capability = undefined;
68
- throw error;
69
- });
70
- const version = await this.capability;
120
+ const capabilities = await this.probeCapabilities(requestDirectory);
121
+ const version = capabilities.has("scan-directories-v2") ? "v2"
122
+ : capabilities.has("scan-directories-v1") ? "v1" : undefined;
71
123
  if (version === undefined) return undefined;
124
+
125
+ if (capabilities.has("scan-serve-v1")) {
126
+ const client = this.ensureResident(workspaceRoot);
127
+ if (client !== undefined) {
128
+ const response = await client.scan();
129
+ checkOperation();
130
+ if (response !== undefined) {
131
+ const parsed = parseResidentResponse(response);
132
+ if (parsed !== undefined) return parsed;
133
+ client.reset();
134
+ }
135
+ }
136
+ // serve 失败或协议无效:继续使用一次性 helper。
137
+ }
138
+
72
139
  const budget = operationProcessOptions(configuredTimeout("PI_UNDO_OPERATION_TIMEOUT_MS", 300_000));
73
140
  const requestPath = join(requestDirectory, "request.json");
74
141
  const cachePath = version === "v2"
@@ -102,15 +169,22 @@ export class NativeDirectoryScanner implements NativeDirectoryScanPort {
102
169
  }
103
170
  }
104
171
 
105
- private async supportsScan(directory: string): Promise<"v2" | "v1" | undefined> {
172
+ private async probeCapabilities(directory: string): Promise<ReadonlySet<string>> {
106
173
  try {
107
174
  await access(this.executable!, constants.X_OK);
108
175
  } catch {
109
- return undefined;
176
+ return new Set<string>();
110
177
  }
111
- const capabilities = await probeNativeCapabilities(this.executable!, directory);
112
- if (capabilities.has("scan-directories-v2")) return "v2";
113
- return capabilities.has("scan-directories-v1") ? "v1" : undefined;
178
+ if (this.capabilities === undefined) {
179
+ const probe = probeNativeCapabilities(this.executable!, directory).catch((error) => {
180
+ // 取消或未确认退出不能污染后续操作的能力缓存;普通的不支持结果由
181
+ // probeNativeCapabilities 返回空集合并可安全缓存。
182
+ this.capabilities = undefined;
183
+ throw error;
184
+ });
185
+ this.capabilities = probe;
186
+ }
187
+ return await this.capabilities;
114
188
  }
115
189
 
116
190
  private async directoryCachePath(
@@ -163,6 +237,34 @@ function parseScanResponse(text: string): NativeDirectoryScan | undefined {
163
237
  return { directories: value.directories as number, repositories };
164
238
  }
165
239
 
240
+ function parseResidentResponse(value: Record<string, unknown>): NativeDirectoryScan | undefined {
241
+ try {
242
+ return parseScanValue(value);
243
+ } catch {
244
+ return undefined;
245
+ }
246
+ }
247
+
248
+ function parseScanValue(value: unknown): NativeDirectoryScan | undefined {
249
+ if (!isRecord(value) || value.ok !== true || !Number.isSafeInteger(value.directories) ||
250
+ (value.directories as number) < 1 || !Array.isArray(value.repositories) ||
251
+ value.repositories.length >= (value.directories as number)) {
252
+ throw new Error("native 目录扫描响应无效");
253
+ }
254
+ const seen = new Set<string>();
255
+ const repositories: NativeRepositoryCandidate[] = [];
256
+ for (const candidate of value.repositories) {
257
+ if (!isRecord(candidate) || typeof candidate.path !== "string" || candidate.path.includes("\0") ||
258
+ candidate.path.split("/").some((part) => part === "" || part === "." || part === ".." || part === ".git") ||
259
+ seen.has(candidate.path)) {
260
+ throw new Error("native 仓库候选路径无效");
261
+ }
262
+ seen.add(candidate.path);
263
+ repositories.push({ path: candidate.path, dev: parseIdentity(candidate.dev), ino: parseIdentity(candidate.ino) });
264
+ }
265
+ return { directories: value.directories as number, repositories };
266
+ }
267
+
166
268
  function parseIdentity(value: unknown): bigint {
167
269
  if (typeof value !== "string" || !/^(?:0|[1-9][0-9]{0,19})$/.test(value) || BigInt(value) > (1n << 64n) - 1n) {
168
270
  throw new Error("native 目录身份字段无效");
package/src/pi-runtime.ts CHANGED
@@ -45,6 +45,9 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
45
45
  const privateRoot = join(manager.getSessionDir(), ".pi-undo");
46
46
  const discovery = new RootDiscovery();
47
47
  const initialTopology = await discovery.discover(context.cwd);
48
+ // 初始 topology 建立后启动常驻 helper,避免冷启动预热与首次 discovery 争用目录读取;
49
+ // 首次 prompt capture 会等待这次预热完成并复用同一缓存。
50
+ discovery.warmScanCache(context.cwd);
48
51
  const store = new SnapshotStore({ storeRoot: privateRoot, discovery });
49
52
  const restore = new RestoreEngine({ workspaceRoot: context.cwd, store, discovery });
50
53
  const journal = new JournalStore({ transactionsRoot: join(privateRoot, "transactions") });
@@ -312,10 +315,14 @@ async function initializePiUndoRuntime(context: ExtensionContext, pi: ExtensionA
312
315
  ? { reason: startupRecovery.reason, files: startupRecovery.files, opId: startupRecovery.opId }
313
316
  : undefined,
314
317
  async dispose(): Promise<void> {
315
- await controller.dispose();
316
- await finalizationQueue;
317
- if (isUnconfirmedExit(finalizationFailure)) throw finalizationFailure;
318
- reporter.endOperation();
318
+ try {
319
+ await controller.dispose();
320
+ await finalizationQueue;
321
+ if (isUnconfirmedExit(finalizationFailure)) throw finalizationFailure;
322
+ } finally {
323
+ await discovery.dispose();
324
+ reporter.endOperation();
325
+ }
319
326
  },
320
327
  setCommandContext(next: ExtensionCommandContext | undefined): void {
321
328
  commandContext = next;
@@ -0,0 +1,254 @@
1
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
+
3
+ import { currentOperationContext } from "./operation-context.ts";
4
+
5
+ const MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
6
+
7
+ type JsonObject = Record<string, unknown>;
8
+
9
+ type LineWaiter = {
10
+ readonly child: ChildProcessWithoutNullStreams;
11
+ readonly resolve: (line: string | undefined) => void;
12
+ readonly timer: ReturnType<typeof setTimeout>;
13
+ readonly signal?: AbortSignal;
14
+ readonly onAbort?: () => void;
15
+ };
16
+
17
+ /**
18
+ * 一个 workspace 对应一个 `--serve` 子进程。
19
+ *
20
+ * stdout 持续保留行缓冲,因为握手响应和首次扫描响应可能在同一个 data
21
+ * chunk 中到达。请求按顺序排队;取消、超时、协议错误或子进程退出都会
22
+ * 丢弃整个进程,调用方随后回退一次性扫描。
23
+ */
24
+ export class ResidentScanClient {
25
+ private child: ChildProcessWithoutNullStreams | undefined;
26
+ private starting: Promise<ChildProcessWithoutNullStreams | undefined> | undefined;
27
+ private queue: Promise<unknown> = Promise.resolve();
28
+ private buffer = "";
29
+ private waiter: LineWaiter | undefined;
30
+ private closed = false;
31
+ private idleTimer: ReturnType<typeof setTimeout> | undefined;
32
+
33
+ constructor(
34
+ private readonly executable: string,
35
+ private readonly workspaceRoot: string,
36
+ private readonly timeoutMs: number,
37
+ ) {}
38
+
39
+ /** 建立进程并完成首次全量扫描;失败静默,正式扫描会回退。 */
40
+ prewarm(): Promise<void> {
41
+ return this.scan(5_000).then(() => undefined, () => undefined);
42
+ }
43
+
44
+ scan(timeoutMs = this.timeoutMs): Promise<JsonObject | undefined> {
45
+ const result = this.queue.then(
46
+ () => this.scanOne(timeoutMs),
47
+ () => this.scanOne(timeoutMs),
48
+ );
49
+ const settled = result.finally(() => this.scheduleIdle());
50
+ this.queue = settled.then(() => undefined, () => undefined);
51
+ return settled;
52
+ }
53
+
54
+ private async scanOne(timeoutMs: number): Promise<JsonObject | undefined> {
55
+ if (this.closed) return undefined;
56
+ const child = await this.ensureChild(timeoutMs);
57
+ if (child === undefined) return undefined;
58
+ const line = await this.requestLine(child, JSON.stringify({ schemaVersion: 1 }), timeoutMs);
59
+ if (line === undefined) return undefined;
60
+ try {
61
+ return parseObject(line);
62
+ } catch {
63
+ this.invalidate(child);
64
+ return undefined;
65
+ }
66
+ }
67
+
68
+ private async ensureChild(timeoutMs: number): Promise<ChildProcessWithoutNullStreams | undefined> {
69
+ if (this.child !== undefined && this.child.exitCode === null) return this.child;
70
+ this.starting ??= this.spawnChild(timeoutMs).finally(() => { this.starting = undefined; });
71
+ return await this.starting;
72
+ }
73
+
74
+ private async spawnChild(timeoutMs: number): Promise<ChildProcessWithoutNullStreams | undefined> {
75
+ if (this.closed) return undefined;
76
+ let child: ChildProcessWithoutNullStreams;
77
+ try {
78
+ child = spawn(this.executable, ["--serve"], {
79
+ stdio: ["pipe", "pipe", "pipe"],
80
+ windowsHide: true,
81
+ });
82
+ } catch {
83
+ return undefined;
84
+ }
85
+ this.child = child;
86
+ this.buffer = "";
87
+ child.stdout.setEncoding("utf8");
88
+ child.stdout.on("data", (chunk: string | Buffer) => this.receive(child, chunk.toString()));
89
+ child.stderr.resume();
90
+ child.once("error", () => this.childExited(child));
91
+ child.once("exit", () => this.childExited(child));
92
+ try {
93
+ const handshakeLine = await this.requestLine(child, JSON.stringify({
94
+ schemaVersion: 1,
95
+ workspaceRoot: this.workspaceRoot,
96
+ }), timeoutMs);
97
+ const handshake = handshakeLine === undefined ? undefined : parseObjectOrUndefined(handshakeLine);
98
+ if (handshake?.ok !== true || handshake.ready !== true) {
99
+ this.invalidate(child);
100
+ return undefined;
101
+ }
102
+ // Rust helper 会在 ready 后发送首次全量扫描响应;必须消费,避免
103
+ // 下一次请求把这条旧响应误认为自己的结果。
104
+ const initialLine = await this.readLine(child, timeoutMs);
105
+ const initial = initialLine === undefined ? undefined : parseObjectOrUndefined(initialLine);
106
+ if (initial?.ok !== true) {
107
+ this.invalidate(child);
108
+ return undefined;
109
+ }
110
+ return child;
111
+ } catch {
112
+ this.invalidate(child);
113
+ return undefined;
114
+ }
115
+ }
116
+
117
+ private requestLine(child: ChildProcessWithoutNullStreams, request: string, timeoutMs: number): Promise<string | undefined> {
118
+ if (this.child !== child || child.exitCode !== null) return Promise.resolve(undefined);
119
+ try {
120
+ child.stdin.write(`${request}\n`);
121
+ } catch {
122
+ this.invalidate(child);
123
+ return Promise.resolve(undefined);
124
+ }
125
+ return this.readLine(child, timeoutMs);
126
+ }
127
+
128
+ private readLine(child: ChildProcessWithoutNullStreams, timeoutMs: number): Promise<string | undefined> {
129
+ const buffered = this.takeLine();
130
+ if (buffered !== undefined) return Promise.resolve(buffered);
131
+ if (this.waiter !== undefined) return Promise.resolve(undefined);
132
+ const context = currentOperationContext();
133
+ const remaining = context === undefined
134
+ ? timeoutMs
135
+ : Math.min(timeoutMs, Math.max(1, context.deadline - Date.now()));
136
+ return new Promise((resolve) => {
137
+ const timer = setTimeout(() => {
138
+ this.invalidate(child);
139
+ resolve(undefined);
140
+ }, remaining);
141
+ const onAbort = context === undefined ? undefined : (): void => {
142
+ this.invalidate(child);
143
+ resolve(undefined);
144
+ };
145
+ this.waiter = {
146
+ child,
147
+ resolve,
148
+ timer,
149
+ ...(context === undefined ? {} : { signal: context.signal }),
150
+ ...(onAbort === undefined ? {} : { onAbort }),
151
+ };
152
+ if (context?.signal.aborted === true) onAbort?.();
153
+ else if (onAbort !== undefined) context?.signal.addEventListener("abort", onAbort, { once: true });
154
+ });
155
+ }
156
+
157
+ private receive(child: ChildProcessWithoutNullStreams, chunk: string): void {
158
+ if (this.child !== child) return;
159
+ this.buffer += chunk;
160
+ if (Buffer.byteLength(this.buffer, "utf8") > MAX_RESPONSE_BYTES) {
161
+ const waiter = this.waiter;
162
+ this.invalidate(child);
163
+ waiter?.resolve(undefined);
164
+ return;
165
+ }
166
+ const waiter = this.waiter;
167
+ if (waiter === undefined) return;
168
+ const line = this.takeLine();
169
+ if (line === undefined) return;
170
+ this.detachWaiter(child);
171
+ waiter.resolve(line);
172
+ }
173
+
174
+ private takeLine(): string | undefined {
175
+ const newline = this.buffer.indexOf("\n");
176
+ if (newline < 0) return undefined;
177
+ const line = this.buffer.slice(0, newline);
178
+ this.buffer = this.buffer.slice(newline + 1);
179
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
180
+ }
181
+
182
+ private detachWaiter(child: ChildProcessWithoutNullStreams): LineWaiter | undefined {
183
+ const waiter = this.waiter;
184
+ if (waiter === undefined || waiter.child !== child) return undefined;
185
+ clearTimeout(waiter.timer);
186
+ if (waiter.signal !== undefined && waiter.onAbort !== undefined) {
187
+ waiter.signal.removeEventListener("abort", waiter.onAbort);
188
+ }
189
+ this.waiter = undefined;
190
+ return waiter;
191
+ }
192
+
193
+ private childExited(child: ChildProcessWithoutNullStreams): void {
194
+ if (this.child !== child) return;
195
+ const waiter = this.detachWaiter(child);
196
+ this.child = undefined;
197
+ this.buffer = "";
198
+ waiter?.resolve(undefined);
199
+ }
200
+
201
+ private invalidate(child: ChildProcessWithoutNullStreams): void {
202
+ const waiter = this.detachWaiter(child);
203
+ if (this.child === child) {
204
+ this.child = undefined;
205
+ this.buffer = "";
206
+ }
207
+ if (child.exitCode === null) child.kill("SIGKILL");
208
+ waiter?.resolve(undefined);
209
+ }
210
+
211
+ private scheduleIdle(): void {
212
+ if (this.idleTimer !== undefined) clearTimeout(this.idleTimer);
213
+ if (this.closed) return;
214
+ this.idleTimer = setTimeout(() => {
215
+ void this.close();
216
+ }, 70_000);
217
+ this.idleTimer.unref?.();
218
+ }
219
+
220
+ /** 丢弃当前进程但保留客户端,使下一次请求可以重新握手。 */
221
+ reset(): void {
222
+ this.closed = false;
223
+ if (this.idleTimer !== undefined) clearTimeout(this.idleTimer);
224
+ const child = this.child;
225
+ if (child !== undefined) this.invalidate(child);
226
+ this.buffer = "";
227
+ }
228
+
229
+ async close(): Promise<void> {
230
+ this.closed = true;
231
+ if (this.idleTimer !== undefined) clearTimeout(this.idleTimer);
232
+ const child = this.child;
233
+ if (child !== undefined) this.invalidate(child);
234
+ await this.queue;
235
+ this.child?.kill("SIGKILL");
236
+ this.child = undefined;
237
+ }
238
+ }
239
+
240
+ function parseObjectOrUndefined(line: string): JsonObject | undefined {
241
+ try {
242
+ return parseObject(line);
243
+ } catch {
244
+ return undefined;
245
+ }
246
+ }
247
+
248
+ function parseObject(line: string): JsonObject {
249
+ const value: unknown = JSON.parse(line);
250
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
251
+ throw new Error("serve 响应不是对象");
252
+ }
253
+ return value as JsonObject;
254
+ }
@@ -73,9 +73,22 @@ export interface RootDiscovery {
73
73
  export class RootDiscovery {
74
74
  private readonly git: GitRunner;
75
75
  private lastDirectoryCount: number | undefined;
76
+ private readonly nativeScan: NativeDirectoryScanPort;
76
77
 
77
- constructor(git = new GitRunner(), private readonly nativeScan: NativeDirectoryScanPort = new NativeDirectoryScanner()) {
78
+ constructor(git = new GitRunner(), nativeScan: NativeDirectoryScanPort = new NativeDirectoryScanner()) {
78
79
  this.git = git;
80
+ this.nativeScan = nativeScan;
81
+ }
82
+
83
+ /** 常驻扫描预热:仅对后续会选择 native 的大目录树启动 helper。 */
84
+ warmScanCache(workspaceRoot: string): void {
85
+ if (this.lastDirectoryCount === undefined || this.lastDirectoryCount < NATIVE_SCAN_MIN_DIRECTORIES) return;
86
+ this.nativeScan.prewarm?.(workspaceRoot);
87
+ }
88
+
89
+ /** 关闭 native 常驻扫描客户端。 */
90
+ async dispose(): Promise<void> {
91
+ await this.nativeScan.dispose?.();
79
92
  }
80
93
 
81
94
  async discover(workspaceRoot: string, reason: RootDiscoveryReason = "unspecified"): Promise<RootTopology> {