@narumitw/pi-worktree 0.25.0 → 0.25.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.
package/README.md CHANGED
@@ -10,12 +10,14 @@ Pi cannot change its parent process working directory with `cd`. This extension
10
10
 
11
11
  - Shows compact main, linked, current, detached, locked, and prunable state in worktree selectors.
12
12
  - Creates a new branch worktree or attaches an existing unoccupied local branch.
13
+ - Rejects occupied targets and unresolvable symbolic-link ancestors before Git can create a branch.
13
14
  - Suggests a sibling path such as `/workspace/project-feat-login` for `feat/login`.
14
15
  - Optionally switches Pi into a newly created worktree while continuing the current conversation.
15
16
  - Switches among existing registered worktrees through Pi's public session replacement API.
16
17
  - Removes only clean, unlocked, non-current linked worktrees and preserves their branches.
17
- - Refuses removal when tracked, untracked, ignored, submodule, or unreachable detached-commit data may be lost.
18
- - Always previews stale metadata before pruning it.
18
+ - Refuses removal when tracked, untracked, ignored, manually index-flagged, submodule, or current unreachable detached-commit data may be lost.
19
+ - Names recovery-only administrative commits in the destructive confirmation instead of making ordinary rebase/reset history block cleanup forever.
20
+ - Always previews stale metadata before pruning it and revalidates the preview after confirmation.
19
21
  - Runs Git through argv-based subprocess calls, without interpolating user input into shell commands.
20
22
 
21
23
  ## 📦 Install
@@ -66,7 +68,7 @@ branch: feat/login
66
68
  suggested: /home/user/workspace/project-feat-login
67
69
  ```
68
70
 
69
- Leave the path input blank to accept the suggestion. A custom absolute path is used directly; a custom relative path is resolved from the current Pi cwd.
71
+ Leave the path input blank to accept the suggestion. A custom absolute path is used directly; a custom relative path is resolved from the current Pi cwd. The target itself must not exist, and its nearest existing ancestor must resolve without a broken or looping symbolic link.
70
72
 
71
73
  The MVP does not expose `--force`, `-B`, `--detach`, `--orphan`, or lock options.
72
74
 
@@ -87,11 +89,12 @@ A successfully created Git worktree is never rolled back merely because Pi sessi
87
89
 
88
90
  - The main worktree and current worktree cannot be removed.
89
91
  - Locked or stale worktrees cannot be removed through this extension.
90
- - Dirty, untracked, ignored, and initialized-submodule data causes removal to fail closed.
92
+ - Dirty, untracked, ignored, initialized-submodule, and intentional `assume-unchanged`/`skip-worktree` index state causes removal to fail closed. Sparse-checkout-managed `skip-worktree` entries outside the active sparsity rules are allowed when Git's rule checker can confirm them; clear other intentional index flags before removing the worktree.
91
93
  - A detached HEAD must be reachable from a local branch, tag, or remote ref before removal or prune.
92
- - Removal and prune also protect reflog-only and per-worktree administrative history, including `FETCH_HEAD`: every discovered commit must remain reachable from a durable branch, tag, or remote ref. This can require creating a branch or tag after a fetch, reset, or rebase, even when the worktree is otherwise clean.
94
+ - Removal and prune inspect reflogs, pseudorefs, per-worktree refs, and `FETCH_HEAD`. Historical commits reachable only through this administrative recovery state are listed by full OID in the destructive confirmation; approval removes those recovery pointers, so Git may later garbage-collect the commits. Create a branch or tag instead when any listed commit should survive.
95
+ - Staged-only administrative index state, a missing attached branch ref, or an unreachable current detached HEAD still blocks prune without an override.
93
96
  - Removal never deletes a branch and never uses `--force`.
94
- - Prune always runs `git worktree prune --dry-run --verbose` before confirmation, inspects linked-worktree administrative HEAD, index, reflog, pseudoref, and per-worktree ref state (including candidates omitted from porcelain), and uses Git's default expiry.
97
+ - Prune always runs `git worktree prune --dry-run --verbose` before confirmation, inspects candidates omitted from porcelain, rechecks the exact preview and recovery-risk set after confirmation, and uses Git's default expiry. Remove likewise rechecks worktree identity, inventory, administrative path, and the approved recovery-risk set before mutation.
95
98
  - The extension does not commit, push, rebase, repair, move, lock, or unlock worktrees.
96
99
 
97
100
  Use Git directly when you intentionally need force removal, branch deletion, custom prune expiry, detach/orphan creation, move, repair, lock, or unlock behavior.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-worktree",
3
- "version": "0.25.0",
3
+ "version": "0.25.1",
4
4
  "description": "Pi extension for safe interactive Git worktree management and workspace switching.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/command.ts CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  sameWorktreeIdentity,
23
23
  stripTerminalControls,
24
24
  symbolicBranch,
25
+ unresolvableSymlinkAncestor,
25
26
  validateBranch,
26
27
  type WorktreeRecord,
27
28
  worktreeAdministrativeDirectory,
@@ -36,6 +37,11 @@ const ACTION_REMOVE = "Remove worktree";
36
37
  const ACTION_PRUNE = "Prune stale metadata";
37
38
  const ACTIONS = [ACTION_ADD, ACTION_SWITCH, ACTION_REMOVE, ACTION_PRUNE];
38
39
 
40
+ interface AdministrativeHistoryRisk {
41
+ label: string;
42
+ oids: string[];
43
+ }
44
+
39
45
  export function registerWorktreeCommand(pi: ExtensionAPI): void {
40
46
  pi.registerCommand("worktree", {
41
47
  description: "Interactively add, switch, remove, or prune Git worktrees",
@@ -114,10 +120,12 @@ async function addFlow(
114
120
  if (!branchExists) {
115
121
  const defaultStart = await symbolicBranch(pi, ctx.cwd, ctx.signal);
116
122
  const requestedStart = await ctx.ui.input(
117
- defaultStart
118
- ? `Start point for ${branch} (blank uses ${defaultStart})`
119
- : `Start point for ${branch} (required because HEAD is detached)`,
120
- defaultStart ?? "commit-ish",
123
+ stripTerminalControls(
124
+ defaultStart
125
+ ? `Start point for ${branch} (blank uses ${defaultStart})`
126
+ : `Start point for ${branch} (required because HEAD is detached)`,
127
+ ),
128
+ stripTerminalControls(defaultStart ?? "commit-ish"),
121
129
  );
122
130
  if (requestedStart === undefined) return;
123
131
  startLabel = requestedStart.trim() || defaultStart;
@@ -134,9 +142,7 @@ async function addFlow(
134
142
  const targetPath = pathIdentity(
135
143
  requestedPath.trim() ? resolve(ctx.cwd, requestedPath.trim()) : suggestedPath,
136
144
  );
137
- if (pathEntryExists(targetPath)) {
138
- throw new Error(`The target path already exists: ${targetPath}.`);
139
- }
145
+ assertTargetFilesystemAvailable(targetPath);
140
146
  const pathCollision = records.find((record) => pathsEqual(record.path, targetPath));
141
147
  if (pathCollision) {
142
148
  throw new Error(`The target path is already registered as a worktree: ${pathCollision.path}.`);
@@ -147,6 +153,7 @@ async function addFlow(
147
153
  : `Create branch ${branch} from ${startLabel} at ${targetPath}?`;
148
154
  if (!(await ctx.ui.confirm("Create Git worktree", stripTerminalControls(summary)))) return;
149
155
 
156
+ assertTargetFilesystemAvailable(targetPath);
150
157
  await addWorktree(pi, ctx.cwd, { path: targetPath, branch, startOid }, ctx.signal);
151
158
  let created: WorktreeRecord;
152
159
  try {
@@ -177,6 +184,18 @@ async function addFlow(
177
184
  }
178
185
  }
179
186
 
187
+ function assertTargetFilesystemAvailable(targetPath: string): void {
188
+ if (pathEntryExists(targetPath)) {
189
+ throw new Error(`The target path already exists: ${targetPath}.`);
190
+ }
191
+ const unsafeAncestor = unresolvableSymlinkAncestor(targetPath);
192
+ if (unsafeAncestor) {
193
+ throw new Error(
194
+ `The target path has an unresolvable symbolic-link ancestor: ${unsafeAncestor}.`,
195
+ );
196
+ }
197
+ }
198
+
180
199
  async function switchFlow(
181
200
  pi: ExtensionAPI,
182
201
  ctx: ExtensionCommandContext,
@@ -236,16 +255,17 @@ async function removeFlow(
236
255
  );
237
256
  }
238
257
  await assertDetachedHeadIsDurable(pi, ctx, selected);
239
- await assertAdministrativeHistoryIsDurable(
240
- pi,
241
- ctx,
242
- await worktreeAdministrativeDirectory(pi, selected.path, ctx.signal),
258
+ const administrativePath = await worktreeAdministrativeDirectory(pi, selected.path, ctx.signal);
259
+ const approvedHistoryRisks = historyRisks(
260
+ selected.path,
261
+ await unreachableAdministrativeHistoryOids(pi, ctx, administrativePath),
243
262
  );
263
+ const recoveryWarning = formatAdministrativeRecoveryWarning(approvedHistoryRisks);
244
264
  if (
245
265
  !(await ctx.ui.confirm(
246
- "Remove Git worktree",
266
+ recoveryWarning ? "Remove worktree and discard recovery history" : "Remove Git worktree",
247
267
  stripTerminalControls(
248
- `Delete the clean worktree directory ${selected.path}? The branch will be preserved.`,
268
+ `Delete the clean worktree directory ${selected.path}? The branch will be preserved.${recoveryWarning}`,
249
269
  ),
250
270
  ))
251
271
  ) {
@@ -270,11 +290,23 @@ async function removeFlow(
270
290
  );
271
291
  }
272
292
  await assertDetachedHeadIsDurable(pi, ctx, latest);
273
- await assertAdministrativeHistoryIsDurable(
293
+ const latestAdministrativePath = await worktreeAdministrativeDirectory(
274
294
  pi,
275
- ctx,
276
- await worktreeAdministrativeDirectory(pi, latest.path, ctx.signal),
295
+ latest.path,
296
+ ctx.signal,
297
+ );
298
+ const latestHistoryRisks = historyRisks(
299
+ latest.path,
300
+ await unreachableAdministrativeHistoryOids(pi, ctx, latestAdministrativePath),
277
301
  );
302
+ if (
303
+ !pathsEqual(administrativePath, latestAdministrativePath) ||
304
+ !sameAdministrativeHistoryRisks(approvedHistoryRisks, latestHistoryRisks)
305
+ ) {
306
+ throw new Error(
307
+ `Worktree ${selected.path} administrative recovery history changed after confirmation; select it again.`,
308
+ );
309
+ }
278
310
  await removeWorktree(pi, ctx.cwd, latest.path, ctx.signal);
279
311
  const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
280
312
  if (updated.some((record) => pathsEqual(record.path, selected.path))) {
@@ -298,17 +330,34 @@ async function pruneFlow(
298
330
  ctx.ui.notify("Git found no stale worktree metadata to prune.", "info");
299
331
  return;
300
332
  }
301
- await assertAdministrativePruneCandidatesAreDurable(pi, ctx);
333
+ const approvedHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
302
334
  const safePreview = stripTerminalControls(preview);
335
+ const recoveryWarning = formatAdministrativeRecoveryWarning(approvedHistoryRisks);
303
336
  ctx.ui.notify(`git worktree prune --dry-run --verbose\n${safePreview}`, "warning");
304
- if (!(await ctx.ui.confirm("Prune stale worktree metadata", safePreview))) return;
337
+ if (
338
+ !(await ctx.ui.confirm(
339
+ recoveryWarning
340
+ ? "Prune metadata and discard recovery history"
341
+ : "Prune stale worktree metadata",
342
+ stripTerminalControls(`${safePreview}${recoveryWarning}`),
343
+ ))
344
+ ) {
345
+ return;
346
+ }
305
347
  const latest = await listWorktrees(pi, ctx.cwd, ctx.signal);
306
348
  for (const record of latest.filter(
307
349
  (candidate) => candidate.prunableReason !== undefined && candidate.detached,
308
350
  )) {
309
351
  await assertDetachedHeadIsDurable(pi, ctx, record);
310
352
  }
311
- await assertAdministrativePruneCandidatesAreDurable(pi, ctx);
353
+ const latestPreview = await prunePreview(pi, ctx.cwd, ctx.signal);
354
+ const latestHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
355
+ if (
356
+ latestPreview !== preview ||
357
+ !sameAdministrativeHistoryRisks(approvedHistoryRisks, latestHistoryRisks)
358
+ ) {
359
+ throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
360
+ }
312
361
  const output = await pruneWorktrees(pi, ctx.cwd, ctx.signal);
313
362
  safeNotify(
314
363
  ctx,
@@ -317,17 +366,17 @@ async function pruneFlow(
317
366
  );
318
367
  }
319
368
 
320
- async function assertAdministrativePruneCandidatesAreDurable(
369
+ async function inspectAdministrativePruneCandidates(
321
370
  pi: ExtensionAPI,
322
371
  ctx: ExtensionCommandContext,
323
- ): Promise<void> {
372
+ ): Promise<AdministrativeHistoryRisk[]> {
373
+ const risks: AdministrativeHistoryRisk[] = [];
324
374
  for (const candidate of await administrativePruneCandidates(pi, ctx.cwd, ctx.signal)) {
325
375
  if (candidate.indexDirty) {
326
376
  throw new Error(
327
377
  `Prune refused because administrative worktree ${candidate.id} contains staged-only index changes.`,
328
378
  );
329
379
  }
330
- await assertAdministrativeHistoryIsDurable(pi, ctx, candidate.administrativePath);
331
380
  if (candidate.head) {
332
381
  const refs = await durableRefsContaining(pi, ctx.cwd, candidate.head, ctx.signal);
333
382
  if (refs.length === 0) {
@@ -335,9 +384,7 @@ async function assertAdministrativePruneCandidatesAreDurable(
335
384
  `Prune refused because administrative worktree ${candidate.id} has detached HEAD ${candidate.head}, which is not reachable from a durable ref.`,
336
385
  );
337
386
  }
338
- continue;
339
- }
340
- if (
387
+ } else if (
341
388
  !candidate.branchRef ||
342
389
  !(await durableRefExists(pi, ctx.cwd, candidate.branchRef, ctx.signal))
343
390
  ) {
@@ -345,22 +392,56 @@ async function assertAdministrativePruneCandidatesAreDurable(
345
392
  `Prune refused because administrative worktree ${candidate.id} does not resolve to a durable ref.`,
346
393
  );
347
394
  }
395
+ risks.push(
396
+ ...historyRisks(
397
+ candidate.id,
398
+ await unreachableAdministrativeHistoryOids(pi, ctx, candidate.administrativePath),
399
+ ),
400
+ );
348
401
  }
402
+ return normalizeAdministrativeHistoryRisks(risks);
349
403
  }
350
404
 
351
- async function assertAdministrativeHistoryIsDurable(
405
+ async function unreachableAdministrativeHistoryOids(
352
406
  pi: ExtensionAPI,
353
407
  ctx: ExtensionCommandContext,
354
408
  administrativePath: string,
355
- ): Promise<void> {
409
+ ): Promise<string[]> {
410
+ const unreachable: string[] = [];
356
411
  for (const oid of await administrativeHistoryOids(pi, ctx.cwd, administrativePath, ctx.signal)) {
357
412
  const refs = await durableRefsContaining(pi, ctx.cwd, oid, ctx.signal);
358
- if (refs.length === 0) {
359
- throw new Error(
360
- `Operation refused because worktree administrative history contains ${oid}, which is not reachable from a durable ref. Create a branch or tag for it first.`,
361
- );
362
- }
413
+ if (refs.length === 0) unreachable.push(oid);
363
414
  }
415
+ return [...new Set(unreachable)].sort();
416
+ }
417
+
418
+ function historyRisks(label: string, oids: string[]): AdministrativeHistoryRisk[] {
419
+ return oids.length > 0 ? [{ label, oids }] : [];
420
+ }
421
+
422
+ function normalizeAdministrativeHistoryRisks(
423
+ risks: readonly AdministrativeHistoryRisk[],
424
+ ): AdministrativeHistoryRisk[] {
425
+ return risks
426
+ .map((risk) => ({ label: risk.label, oids: [...new Set(risk.oids)].sort() }))
427
+ .filter((risk) => risk.oids.length > 0)
428
+ .sort((left, right) => left.label.localeCompare(right.label));
429
+ }
430
+
431
+ function sameAdministrativeHistoryRisks(
432
+ left: readonly AdministrativeHistoryRisk[],
433
+ right: readonly AdministrativeHistoryRisk[],
434
+ ): boolean {
435
+ return (
436
+ JSON.stringify(normalizeAdministrativeHistoryRisks(left)) ===
437
+ JSON.stringify(normalizeAdministrativeHistoryRisks(right))
438
+ );
439
+ }
440
+
441
+ function formatAdministrativeRecoveryWarning(risks: readonly AdministrativeHistoryRisk[]): string {
442
+ if (risks.length === 0) return "";
443
+ const entries = risks.map((risk) => `${risk.label}: ${risk.oids.join(", ")}`).join("; ");
444
+ return ` Administrative recovery warning: these commits are not reachable from a branch, tag, or remote ref: ${entries}. Discarding their recovery pointers means they may later be garbage-collected.`;
364
445
  }
365
446
 
366
447
  async function assertDetachedHeadIsDurable(
package/src/git.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { spawn } from "node:child_process";
1
2
  import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
2
3
  import { basename, dirname, resolve } from "node:path";
3
4
  import type { ExecResult, ExtensionAPI } from "@earendil-works/pi-coding-agent";
@@ -152,6 +153,37 @@ export function pathEntryExists(path: string): boolean {
152
153
  }
153
154
  }
154
155
 
156
+ export function unresolvableSymlinkAncestor(path: string): string | undefined {
157
+ let current = dirname(resolve(path));
158
+ while (true) {
159
+ try {
160
+ const stat = lstatSync(current);
161
+ if (!stat.isSymbolicLink()) return undefined;
162
+ try {
163
+ realpathSync.native(current);
164
+ return undefined;
165
+ } catch (error) {
166
+ if (isNodeError(error) && (error.code === "ENOENT" || error.code === "ELOOP")) {
167
+ return current;
168
+ }
169
+ throw new GitWorktreeError(
170
+ `Cannot resolve filesystem ancestor ${current}: ${formatError(error)}`,
171
+ );
172
+ }
173
+ } catch (error) {
174
+ if (!isNodeError(error) || error.code !== "ENOENT") {
175
+ if (error instanceof GitWorktreeError) throw error;
176
+ throw new GitWorktreeError(
177
+ `Cannot inspect filesystem ancestor ${current}: ${formatError(error)}`,
178
+ );
179
+ }
180
+ const parent = dirname(current);
181
+ if (parent === current) return undefined;
182
+ current = parent;
183
+ }
184
+ }
185
+ }
186
+
155
187
  export function pathsEqual(left: string, right: string): boolean {
156
188
  return pathIdentity(left) === pathIdentity(right);
157
189
  }
@@ -283,6 +315,8 @@ export async function worktreeInventory(
283
315
  "--ignore-submodules=none",
284
316
  ];
285
317
  const status = await runGit(pi, statusArgs, path, signal);
318
+ const indexFlags = await runGit(pi, ["ls-files", "-v", "-z"], path, signal);
319
+ const indexInventory = await indexFlagInventory(pi, indexFlags.stdout, path, signal);
286
320
  const submoduleStatus = await runGit(pi, ["submodule", "status", "--recursive"], path, signal);
287
321
  const initializedSubmodules = nonEmptyLines(submoduleStatus.stdout)
288
322
  .filter((line) => !line.startsWith("-"))
@@ -301,6 +335,7 @@ export async function worktreeInventory(
301
335
  );
302
336
  return [
303
337
  ...nonEmptyLines(status.stdout),
338
+ ...indexInventory,
304
339
  ...initializedSubmodules,
305
340
  ...nonEmptyLines(submodules.stdout),
306
341
  ];
@@ -613,6 +648,157 @@ function nonEmptyLines(value: string): string[] {
613
648
  return value.split(/\r?\n/u).filter((line) => line.length > 0);
614
649
  }
615
650
 
651
+ interface IndexFlagEntry {
652
+ path: string;
653
+ skipWorktree: boolean;
654
+ assumeUnchanged: boolean;
655
+ }
656
+
657
+ async function indexFlagInventory(
658
+ pi: Pick<ExtensionAPI, "exec">,
659
+ value: string,
660
+ cwd: string,
661
+ signal?: AbortSignal,
662
+ ): Promise<string[]> {
663
+ const entries = parseIndexFlagEntries(value);
664
+ const sparseManagedPaths = await sparseManagedSkipWorktreePaths(
665
+ pi,
666
+ cwd,
667
+ entries.filter((entry) => entry.skipWorktree).map((entry) => entry.path),
668
+ signal,
669
+ );
670
+ const inventory: string[] = [];
671
+ for (const entry of entries) {
672
+ const flags = [
673
+ entry.skipWorktree && !sparseManagedPaths.has(entry.path) ? "skip-worktree" : undefined,
674
+ entry.assumeUnchanged ? "assume-unchanged" : undefined,
675
+ ].filter((flag): flag is string => flag !== undefined);
676
+ if (flags.length > 0) inventory.push(`index flag ${flags.join("+")}: ${entry.path}`);
677
+ }
678
+ return inventory;
679
+ }
680
+
681
+ function parseIndexFlagEntries(value: string): IndexFlagEntry[] {
682
+ const entries: IndexFlagEntry[] = [];
683
+ for (const entry of value.split("\0")) {
684
+ if (!entry) continue;
685
+ if (entry.length < 3 || entry[1] !== " ") {
686
+ throw new GitWorktreeError("Git returned malformed ls-files index-flag output.");
687
+ }
688
+ const tag = entry[0] ?? "";
689
+ const skipWorktree = tag.toUpperCase() === "S";
690
+ const assumeUnchanged = /[a-z]/u.test(tag);
691
+ if (skipWorktree || assumeUnchanged) {
692
+ entries.push({ path: entry.slice(2), skipWorktree, assumeUnchanged });
693
+ }
694
+ }
695
+ return entries;
696
+ }
697
+
698
+ async function sparseManagedSkipWorktreePaths(
699
+ pi: Pick<ExtensionAPI, "exec">,
700
+ cwd: string,
701
+ paths: readonly string[],
702
+ signal?: AbortSignal,
703
+ ): Promise<ReadonlySet<string>> {
704
+ if (paths.length === 0) return new Set();
705
+ const configArgs = ["config", "--bool", "--get", "core.sparseCheckout"];
706
+ const config = await runGitAllowFailure(pi, configArgs, cwd, signal);
707
+ if (config.killed) throw killedError(configArgs);
708
+ if (config.code !== 0 || config.stdout.trim() !== "true") return new Set();
709
+
710
+ const candidates = new Set(paths);
711
+ const checkArgs = ["sparse-checkout", "check-rules", "-z"];
712
+ const checked = await runGitWithInputAllowFailure(
713
+ checkArgs,
714
+ cwd,
715
+ `${[...candidates].join("\0")}\0`,
716
+ signal,
717
+ );
718
+ if (checked.killed) throw killedError(checkArgs);
719
+ // Older Git versions lack check-rules; retain every flag rather than guessing.
720
+ if (checked.code !== 0) return new Set();
721
+
722
+ const included = new Set(nulSeparatedPaths(checked.stdout, "sparse-checkout rules"));
723
+ if ([...included].some((path) => !candidates.has(path))) {
724
+ throw new GitWorktreeError("Git returned an unexpected sparse-checkout path.");
725
+ }
726
+ return new Set([...candidates].filter((path) => !included.has(path)));
727
+ }
728
+
729
+ function runGitWithInputAllowFailure(
730
+ args: string[],
731
+ cwd: string,
732
+ input: string,
733
+ signal?: AbortSignal,
734
+ timeout = GIT_TIMEOUT_MS,
735
+ ): Promise<ExecResult> {
736
+ if (signal?.aborted) {
737
+ return Promise.resolve({ stdout: "", stderr: "", code: 1, killed: true });
738
+ }
739
+ return new Promise((resolveResult, reject) => {
740
+ // ExtensionAPI.exec has no stdin channel, so this read-only check uses an argv-only child.
741
+ const child = spawn("git", args, { cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
742
+ let stdout = "";
743
+ let stderr = "";
744
+ let killed = false;
745
+ let settled = false;
746
+ const finish = (result: ExecResult) => {
747
+ if (settled) return;
748
+ settled = true;
749
+ clearTimeout(timeoutHandle);
750
+ signal?.removeEventListener("abort", stop);
751
+ resolveResult(result);
752
+ };
753
+ const fail = (error: unknown) => {
754
+ if (settled) return;
755
+ settled = true;
756
+ clearTimeout(timeoutHandle);
757
+ signal?.removeEventListener("abort", stop);
758
+ child.kill();
759
+ const message = formatError(error);
760
+ reject(
761
+ /\bENOENT\b|not found/i.test(message)
762
+ ? new GitWorktreeError("Git executable was not found. Install Git and retry.", args)
763
+ : new GitWorktreeError(
764
+ `Could not start git ${args.slice(0, 2).join(" ")}: ${message}`,
765
+ args,
766
+ ),
767
+ );
768
+ };
769
+ const stop = () => {
770
+ killed = true;
771
+ child.kill();
772
+ };
773
+ const timeoutHandle = setTimeout(stop, timeout);
774
+ child.stdout.setEncoding("utf8");
775
+ child.stderr.setEncoding("utf8");
776
+ child.stdout.on("data", (chunk: string) => {
777
+ stdout += chunk;
778
+ });
779
+ child.stderr.on("data", (chunk: string) => {
780
+ stderr += chunk;
781
+ });
782
+ child.stdin.on("error", (error) => {
783
+ if (!isNodeError(error) || error.code !== "EPIPE") fail(error);
784
+ });
785
+ child.once("error", fail);
786
+ child.once("close", (code, closeSignal) => {
787
+ finish({ stdout, stderr, code: code ?? 1, killed: killed || closeSignal !== null });
788
+ });
789
+ signal?.addEventListener("abort", stop, { once: true });
790
+ if (signal?.aborted) stop();
791
+ child.stdin.end(input);
792
+ });
793
+ }
794
+
795
+ function nulSeparatedPaths(value: string, source: string): string[] {
796
+ if (value && !value.endsWith("\0")) {
797
+ throw new GitWorktreeError(`Git returned malformed ${source} output.`);
798
+ }
799
+ return value.split("\0").filter(Boolean);
800
+ }
801
+
616
802
  function combineOutput(result: ExecResult): string {
617
803
  return [result.stdout.trimEnd(), result.stderr.trimEnd()].filter(Boolean).join("\n");
618
804
  }