@davideasden/pi-undo 0.2.34 → 0.3.1

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.
@@ -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.34",
3
+ "version": "0.3.1",
4
4
  "description": "Persistent workspace undo and redo for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
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> {