@narumitw/pi-worktree 0.25.0 → 0.27.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,15 @@ 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
- - 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.
17
+ - Removes unlocked, non-current linked worktrees and preserves their branches.
18
+ - Refuses removal when tracked, untracked, manually index-flagged, submodule, or current unreachable detached-commit data may be lost.
19
+ - Allows ignored-only data such as `node_modules/` after listing it in the destructive confirmation.
20
+ - Names recovery-only administrative commits in the destructive confirmation instead of making ordinary rebase/reset history block cleanup forever.
21
+ - Always previews stale metadata before pruning it and revalidates the preview after confirmation.
19
22
  - Runs Git through argv-based subprocess calls, without interpolating user input into shell commands.
20
23
 
21
24
  ## 📦 Install
@@ -49,7 +52,7 @@ Choose one action:
49
52
 
50
53
  - **Add worktree** — enter a branch, optional start point, and optional path; confirm creation and optionally switch.
51
54
  - **Switch worktree** — select another existing worktree and continue this Pi conversation there.
52
- - **Remove worktree** — remove a confirmed clean linked worktree without deleting its branch.
55
+ - **Remove worktree** — remove a linked worktree without deleting its branch; ignored-only data is listed for explicit confirmation.
53
56
  - **Prune stale metadata** — inspect Git's dry-run output, then optionally run the matching prune.
54
57
 
55
58
  `/worktree` intentionally does not accept text subcommands in this version. Every mutation is initiated and confirmed through the interactive UI.
@@ -66,7 +69,7 @@ branch: feat/login
66
69
  suggested: /home/user/workspace/project-feat-login
67
70
  ```
68
71
 
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.
72
+ 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
73
 
71
74
  The MVP does not expose `--force`, `-B`, `--detach`, `--orphan`, or lock options.
72
75
 
@@ -87,11 +90,13 @@ A successfully created Git worktree is never rolled back merely because Pi sessi
87
90
 
88
91
  - The main worktree and current worktree cannot be removed.
89
92
  - Locked or stale worktrees cannot be removed through this extension.
90
- - Dirty, untracked, ignored, and initialized-submodule data causes removal to fail closed.
93
+ - Dirty, untracked, 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.
94
+ - Ignored-only files and directories do not block removal. The confirmation lists them, and the extension rechecks the exact ignored inventory before Git deletes the worktree.
91
95
  - 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.
96
+ - 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.
97
+ - Staged-only administrative index state, a missing attached branch ref, or an unreachable current detached HEAD still blocks prune without an override.
93
98
  - 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.
99
+ - 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
100
  - The extension does not commit, push, rebase, repair, move, lock, or unlock worktrees.
96
101
 
97
102
  Use Git directly when you intentionally need force removal, branch deletion, custom prune expiry, detach/orphan creation, move, repair, lock, or unlock behavior.
@@ -116,6 +121,7 @@ extensions/pi-worktree/
116
121
  │ ├── command.test.ts
117
122
  │ ├── git.integration.test.ts
118
123
  │ ├── git.test.ts
124
+ │ ├── remove-ignored-command.test.ts
119
125
  │ └── session.test.ts
120
126
  ├── package.json
121
127
  ├── README.md
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-worktree",
3
- "version": "0.25.0",
3
+ "version": "0.27.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,
@@ -213,12 +232,7 @@ async function removeFlow(
213
232
  const candidates = records.filter(
214
233
  (record) => !record.isMain && !record.bare && !pathsEqual(record.path, currentPath),
215
234
  );
216
- const selected = await selectWorktree(
217
- ctx,
218
- "Remove clean linked worktree",
219
- candidates,
220
- currentPath,
221
- );
235
+ const selected = await selectWorktree(ctx, "Remove linked worktree", candidates, currentPath);
222
236
  if (!selected) return;
223
237
  if (selected.lockedReason !== undefined) {
224
238
  throw new Error(
@@ -229,29 +243,51 @@ async function removeFlow(
229
243
  throw new Error("The selected worktree path is stale. Use prune instead of remove.");
230
244
  }
231
245
 
232
- const inventory = await worktreeInventory(pi, selected.path, ctx.signal);
233
- if (inventory.length > 0) {
246
+ const inventory = classifyRemovalInventory(
247
+ await worktreeInventory(pi, selected.path, ctx.signal),
248
+ );
249
+ if (inventory.protected.length > 0) {
234
250
  throw new Error(
235
- `Removal refused because ${selected.path} contains tracked, untracked, ignored, or submodule data:\n${inventory.join("\n")}`,
251
+ `Removal refused because ${selected.path} contains tracked, untracked, index-flagged, or submodule data:\n${inventory.protected.join("\n")}`,
236
252
  );
237
253
  }
238
254
  await assertDetachedHeadIsDurable(pi, ctx, selected);
239
- await assertAdministrativeHistoryIsDurable(
240
- pi,
241
- ctx,
242
- await worktreeAdministrativeDirectory(pi, selected.path, ctx.signal),
255
+ const administrativePath = await worktreeAdministrativeDirectory(pi, selected.path, ctx.signal);
256
+ const approvedHistoryRisks = historyRisks(
257
+ selected.path,
258
+ await unreachableAdministrativeHistoryOids(pi, ctx, administrativePath),
243
259
  );
260
+ const recoveryWarning = formatAdministrativeRecoveryWarning(approvedHistoryRisks);
261
+ const ignoredWarning = formatIgnoredDataWarning(inventory.ignored);
262
+ const removalWarning =
263
+ ignoredWarning && recoveryWarning
264
+ ? `${ignoredWarning}\n${recoveryWarning.trimStart()}`
265
+ : `${ignoredWarning}${recoveryWarning}`;
266
+ const confirmationTitle =
267
+ inventory.ignored.length > 0
268
+ ? recoveryWarning
269
+ ? "Remove worktree and discard local/recovery data"
270
+ : "Remove worktree and delete ignored files"
271
+ : recoveryWarning
272
+ ? "Remove worktree and discard recovery history"
273
+ : "Remove Git worktree";
244
274
  if (
245
275
  !(await ctx.ui.confirm(
246
- "Remove Git worktree",
247
- stripTerminalControls(
248
- `Delete the clean worktree directory ${selected.path}? The branch will be preserved.`,
249
- ),
276
+ confirmationTitle,
277
+ `Delete the worktree directory ${stripTerminalControls(selected.path)}? The branch will be preserved.${removalWarning}`,
250
278
  ))
251
279
  ) {
252
280
  return;
253
281
  }
254
282
 
283
+ await assertAdministrativeHistoryUnchanged(
284
+ pi,
285
+ ctx,
286
+ selected.path,
287
+ administrativePath,
288
+ approvedHistoryRisks,
289
+ );
290
+
255
291
  const beforeRemoval = await listWorktrees(pi, ctx.cwd, ctx.signal);
256
292
  const latest = beforeRemoval.find((record) => pathsEqual(record.path, selected.path));
257
293
  if (!latest) throw new Error(`Worktree ${selected.path} is no longer registered.`);
@@ -263,17 +299,26 @@ async function removeFlow(
263
299
  `Worktree ${selected.path} changed state after confirmation; removal was refused.`,
264
300
  );
265
301
  }
266
- const latestInventory = await worktreeInventory(pi, latest.path, ctx.signal);
267
- if (latestInventory.length > 0) {
302
+ const latestInventory = classifyRemovalInventory(
303
+ await worktreeInventory(pi, latest.path, ctx.signal),
304
+ );
305
+ if (latestInventory.protected.length > 0) {
306
+ throw new Error(
307
+ `Removal refused because new protected local data appeared after confirmation:\n${latestInventory.protected.join("\n")}`,
308
+ );
309
+ }
310
+ if (!sameInventory(inventory.ignored, latestInventory.ignored)) {
268
311
  throw new Error(
269
- `Removal refused because new local data appeared after confirmation:\n${latestInventory.join("\n")}`,
312
+ `Removal refused because ignored data changed after confirmation:\n${latestInventory.ignored.join("\n") || "(none)"}`,
270
313
  );
271
314
  }
272
315
  await assertDetachedHeadIsDurable(pi, ctx, latest);
273
- await assertAdministrativeHistoryIsDurable(
316
+ await assertAdministrativeHistoryUnchanged(
274
317
  pi,
275
318
  ctx,
276
- await worktreeAdministrativeDirectory(pi, latest.path, ctx.signal),
319
+ latest.path,
320
+ administrativePath,
321
+ approvedHistoryRisks,
277
322
  );
278
323
  await removeWorktree(pi, ctx.cwd, latest.path, ctx.signal);
279
324
  const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
@@ -298,17 +343,38 @@ async function pruneFlow(
298
343
  ctx.ui.notify("Git found no stale worktree metadata to prune.", "info");
299
344
  return;
300
345
  }
301
- await assertAdministrativePruneCandidatesAreDurable(pi, ctx);
346
+ const approvedHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
302
347
  const safePreview = stripTerminalControls(preview);
348
+ const recoveryWarning = formatAdministrativeRecoveryWarning(approvedHistoryRisks);
303
349
  ctx.ui.notify(`git worktree prune --dry-run --verbose\n${safePreview}`, "warning");
304
- if (!(await ctx.ui.confirm("Prune stale worktree metadata", safePreview))) return;
350
+ if (
351
+ !(await ctx.ui.confirm(
352
+ recoveryWarning
353
+ ? "Prune metadata and discard recovery history"
354
+ : "Prune stale worktree metadata",
355
+ stripTerminalControls(`${safePreview}${recoveryWarning}`),
356
+ ))
357
+ ) {
358
+ return;
359
+ }
305
360
  const latest = await listWorktrees(pi, ctx.cwd, ctx.signal);
306
361
  for (const record of latest.filter(
307
362
  (candidate) => candidate.prunableReason !== undefined && candidate.detached,
308
363
  )) {
309
364
  await assertDetachedHeadIsDurable(pi, ctx, record);
310
365
  }
311
- await assertAdministrativePruneCandidatesAreDurable(pi, ctx);
366
+ const beforePreviewHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
367
+ if (!sameAdministrativeHistoryRisks(approvedHistoryRisks, beforePreviewHistoryRisks)) {
368
+ throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
369
+ }
370
+ const latestPreview = await prunePreview(pi, ctx.cwd, ctx.signal);
371
+ const finalHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
372
+ if (
373
+ latestPreview !== preview ||
374
+ !sameAdministrativeHistoryRisks(approvedHistoryRisks, finalHistoryRisks)
375
+ ) {
376
+ throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
377
+ }
312
378
  const output = await pruneWorktrees(pi, ctx.cwd, ctx.signal);
313
379
  safeNotify(
314
380
  ctx,
@@ -317,17 +383,43 @@ async function pruneFlow(
317
383
  );
318
384
  }
319
385
 
320
- async function assertAdministrativePruneCandidatesAreDurable(
386
+ async function assertAdministrativeHistoryUnchanged(
321
387
  pi: ExtensionAPI,
322
388
  ctx: ExtensionCommandContext,
389
+ selectedPath: string,
390
+ approvedAdministrativePath: string,
391
+ approvedHistoryRisks: readonly AdministrativeHistoryRisk[],
323
392
  ): Promise<void> {
393
+ const latestAdministrativePath = await worktreeAdministrativeDirectory(
394
+ pi,
395
+ selectedPath,
396
+ ctx.signal,
397
+ );
398
+ const latestHistoryRisks = historyRisks(
399
+ selectedPath,
400
+ await unreachableAdministrativeHistoryOids(pi, ctx, latestAdministrativePath),
401
+ );
402
+ if (
403
+ !pathsEqual(approvedAdministrativePath, latestAdministrativePath) ||
404
+ !sameAdministrativeHistoryRisks(approvedHistoryRisks, latestHistoryRisks)
405
+ ) {
406
+ throw new Error(
407
+ `Worktree ${selectedPath} administrative recovery history changed after confirmation; select it again.`,
408
+ );
409
+ }
410
+ }
411
+
412
+ async function inspectAdministrativePruneCandidates(
413
+ pi: ExtensionAPI,
414
+ ctx: ExtensionCommandContext,
415
+ ): Promise<AdministrativeHistoryRisk[]> {
416
+ const risks: AdministrativeHistoryRisk[] = [];
324
417
  for (const candidate of await administrativePruneCandidates(pi, ctx.cwd, ctx.signal)) {
325
418
  if (candidate.indexDirty) {
326
419
  throw new Error(
327
420
  `Prune refused because administrative worktree ${candidate.id} contains staged-only index changes.`,
328
421
  );
329
422
  }
330
- await assertAdministrativeHistoryIsDurable(pi, ctx, candidate.administrativePath);
331
423
  if (candidate.head) {
332
424
  const refs = await durableRefsContaining(pi, ctx.cwd, candidate.head, ctx.signal);
333
425
  if (refs.length === 0) {
@@ -335,9 +427,7 @@ async function assertAdministrativePruneCandidatesAreDurable(
335
427
  `Prune refused because administrative worktree ${candidate.id} has detached HEAD ${candidate.head}, which is not reachable from a durable ref.`,
336
428
  );
337
429
  }
338
- continue;
339
- }
340
- if (
430
+ } else if (
341
431
  !candidate.branchRef ||
342
432
  !(await durableRefExists(pi, ctx.cwd, candidate.branchRef, ctx.signal))
343
433
  ) {
@@ -345,22 +435,91 @@ async function assertAdministrativePruneCandidatesAreDurable(
345
435
  `Prune refused because administrative worktree ${candidate.id} does not resolve to a durable ref.`,
346
436
  );
347
437
  }
438
+ risks.push(
439
+ ...historyRisks(
440
+ candidate.id,
441
+ await unreachableAdministrativeHistoryOids(pi, ctx, candidate.administrativePath),
442
+ ),
443
+ );
348
444
  }
445
+ return normalizeAdministrativeHistoryRisks(risks);
349
446
  }
350
447
 
351
- async function assertAdministrativeHistoryIsDurable(
448
+ async function unreachableAdministrativeHistoryOids(
352
449
  pi: ExtensionAPI,
353
450
  ctx: ExtensionCommandContext,
354
451
  administrativePath: string,
355
- ): Promise<void> {
452
+ ): Promise<string[]> {
453
+ const unreachable: string[] = [];
356
454
  for (const oid of await administrativeHistoryOids(pi, ctx.cwd, administrativePath, ctx.signal)) {
357
455
  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
- }
456
+ if (refs.length === 0) unreachable.push(oid);
457
+ }
458
+ return [...new Set(unreachable)].sort();
459
+ }
460
+
461
+ function historyRisks(label: string, oids: string[]): AdministrativeHistoryRisk[] {
462
+ return oids.length > 0 ? [{ label, oids }] : [];
463
+ }
464
+
465
+ function normalizeAdministrativeHistoryRisks(
466
+ risks: readonly AdministrativeHistoryRisk[],
467
+ ): AdministrativeHistoryRisk[] {
468
+ return risks
469
+ .map((risk) => ({ label: risk.label, oids: [...new Set(risk.oids)].sort() }))
470
+ .filter((risk) => risk.oids.length > 0)
471
+ .sort((left, right) => left.label.localeCompare(right.label));
472
+ }
473
+
474
+ function sameAdministrativeHistoryRisks(
475
+ left: readonly AdministrativeHistoryRisk[],
476
+ right: readonly AdministrativeHistoryRisk[],
477
+ ): boolean {
478
+ return (
479
+ JSON.stringify(normalizeAdministrativeHistoryRisks(left)) ===
480
+ JSON.stringify(normalizeAdministrativeHistoryRisks(right))
481
+ );
482
+ }
483
+
484
+ function formatAdministrativeRecoveryWarning(risks: readonly AdministrativeHistoryRisk[]): string {
485
+ if (risks.length === 0) return "";
486
+ const entries = risks
487
+ .map(
488
+ (risk) =>
489
+ `${stripTerminalControls(risk.label)}: ${risk.oids.map(stripTerminalControls).join(", ")}`,
490
+ )
491
+ .join("; ");
492
+ 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.`;
493
+ }
494
+
495
+ interface RemovalInventory {
496
+ ignored: string[];
497
+ protected: string[];
498
+ }
499
+
500
+ function classifyRemovalInventory(lines: readonly string[]): RemovalInventory {
501
+ const ignored: string[] = [];
502
+ const protectedData: string[] = [];
503
+ for (const line of lines) {
504
+ (line.startsWith("!! ") ? ignored : protectedData).push(line);
363
505
  }
506
+ return {
507
+ ignored: normalizeInventory(ignored),
508
+ protected: normalizeInventory(protectedData),
509
+ };
510
+ }
511
+
512
+ function normalizeInventory(lines: readonly string[]): string[] {
513
+ return [...new Set(lines)].sort();
514
+ }
515
+
516
+ function sameInventory(left: readonly string[], right: readonly string[]): boolean {
517
+ return JSON.stringify(normalizeInventory(left)) === JSON.stringify(normalizeInventory(right));
518
+ }
519
+
520
+ function formatIgnoredDataWarning(ignored: readonly string[]): string {
521
+ if (ignored.length === 0) return "";
522
+ return ` Ignored files and directories that will be deleted:\n${ignored.map(stripTerminalControls).join("\n")}`;
364
523
  }
365
524
 
366
525
  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
  }