@narumitw/pi-worktree 0.51.6 → 0.51.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/command.ts CHANGED
@@ -2,32 +2,32 @@ import { existsSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
3
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
4
4
  import {
5
- addWorktree,
6
- administrativeHistoryOids,
7
- administrativePruneCandidates,
8
- currentWorktreePath,
9
- defaultWorktreePath,
10
- durableRefExists,
11
- durableRefsContaining,
12
- formatWorktree,
13
- listWorktrees,
14
- localBranchExists,
15
- pathEntryExists,
16
- pathIdentity,
17
- pathsEqual,
18
- prunePreview,
19
- pruneWorktrees,
20
- removeWorktree,
21
- resolveCommit,
22
- sameWorktreeIdentity,
23
- stripTerminalControls,
24
- symbolicBranch,
25
- unresolvableSymlinkAncestor,
26
- validateBranch,
27
- type WorktreeRecord,
28
- worktreeAdministrativeDirectory,
29
- worktreeForBranch,
30
- worktreeInventory,
5
+ addWorktree,
6
+ administrativeHistoryOids,
7
+ administrativePruneCandidates,
8
+ currentWorktreePath,
9
+ defaultWorktreePath,
10
+ durableRefExists,
11
+ durableRefsContaining,
12
+ formatWorktree,
13
+ listWorktrees,
14
+ localBranchExists,
15
+ pathEntryExists,
16
+ pathIdentity,
17
+ pathsEqual,
18
+ prunePreview,
19
+ pruneWorktrees,
20
+ removeWorktree,
21
+ resolveCommit,
22
+ sameWorktreeIdentity,
23
+ stripTerminalControls,
24
+ symbolicBranch,
25
+ unresolvableSymlinkAncestor,
26
+ validateBranch,
27
+ type WorktreeRecord,
28
+ worktreeAdministrativeDirectory,
29
+ worktreeForBranch,
30
+ worktreeInventory,
31
31
  } from "./git.js";
32
32
  import { switchToWorktree } from "./session.js";
33
33
  import type { WorktreeSettingsRuntime } from "./settings.js";
@@ -40,771 +40,683 @@ const ACTION_REMOVE = "Remove worktree";
40
40
  const ACTION_PRUNE = "Prune stale metadata";
41
41
  const ACTION_CONFIGURE_ROOT = "Configure worktree root";
42
42
  const ACTIONS = {
43
- status: ACTION_STATUS,
44
- add: ACTION_ADD,
45
- switch: ACTION_SWITCH,
46
- remove: ACTION_REMOVE,
47
- prune: ACTION_PRUNE,
48
- configure: ACTION_CONFIGURE_ROOT,
43
+ status: ACTION_STATUS,
44
+ add: ACTION_ADD,
45
+ switch: ACTION_SWITCH,
46
+ remove: ACTION_REMOVE,
47
+ prune: ACTION_PRUNE,
48
+ configure: ACTION_CONFIGURE_ROOT,
49
49
  } as const;
50
50
 
51
51
  interface WorktreeMenuState {
52
- statusCards: WorktreeStatusCard[];
52
+ statusCards: WorktreeStatusCard[];
53
53
  }
54
54
 
55
55
  interface WorktreeMenuOwner {
56
- signal: AbortSignal;
57
- isCurrent(): boolean;
56
+ signal: AbortSignal;
57
+ isCurrent(): boolean;
58
58
  }
59
59
 
60
60
  interface AdministrativeHistoryRisk {
61
- label: string;
62
- oids: string[];
61
+ label: string;
62
+ oids: string[];
63
63
  }
64
64
 
65
65
  interface AddBaseProvenance {
66
- kind: "existing-local-branch" | "current-branch" | "explicit-commit-ish";
67
- label: string;
68
- oid: string;
66
+ kind: "existing-local-branch" | "current-branch" | "explicit-commit-ish";
67
+ label: string;
68
+ oid: string;
69
69
  }
70
70
 
71
71
  export function registerWorktreeCommand(
72
- pi: ExtensionAPI,
73
- settings: WorktreeSettingsRuntime,
74
- getMenuOwner: () => WorktreeMenuOwner,
72
+ pi: ExtensionAPI,
73
+ settings: WorktreeSettingsRuntime,
74
+ getMenuOwner: () => WorktreeMenuOwner,
75
75
  ): void {
76
- pi.registerCommand("worktree", {
77
- description: "Interactively manage Git worktrees and their default root",
78
- handler: async (args, ctx) => {
79
- if (args.trim()) {
80
- safeNotify(
81
- ctx,
82
- "/worktree does not accept arguments; run it without arguments to open the menu.",
83
- "warning",
84
- );
85
- return;
86
- }
87
- if (!ctx.hasUI) {
88
- safeNotify(ctx, "/worktree requires TUI or RPC mode.", "error");
89
- return;
90
- }
91
-
92
- try {
93
- await ctx.waitForIdle();
94
- const records = await listWorktrees(pi, ctx.cwd, ctx.signal);
95
- const currentPath = await currentWorktreePath(pi, ctx.cwd, ctx.signal);
96
- const root = settings.get();
97
- const warning = root.warning ? " — settings warning" : "";
98
- const owner = getMenuOwner();
99
- const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
100
- if (owner.signal.aborted || !owner.isCurrent()) return;
101
- const runFlow = async (flow: () => Promise<void>) => {
102
- try {
103
- await flow();
104
- } catch (error) {
105
- safeNotify(ctx, formatError(error), "error");
106
- }
107
- return { kind: "close" } as const;
108
- };
109
- const state: WorktreeMenuState = { statusCards: [] };
110
- type Screen = "main" | "status";
111
- type Action = keyof typeof ACTIONS;
112
- const menu = defineMenu<WorktreeMenuState, Screen, Action, ExtensionCommandContext>({
113
- start: "main",
114
- screens: {
115
- main: () => ({
116
- kind: "actions",
117
- title: "Git worktrees",
118
- lines: [
119
- `Registered: ${records.length}`,
120
- `Current: ${currentPath}`,
121
- `Worktree root: ${root.effectiveRoot} (${root.source})${warning}`,
122
- ],
123
- items: Object.entries(ACTIONS).map(([id, label]) => ({
124
- id,
125
- label,
126
- action: id as Action,
127
- busyLabel: id === "status" ? "Inspecting worktrees…" : undefined,
128
- })),
129
- hint: "close",
130
- }),
131
- status: ({ state: currentState }) => ({
132
- kind: "browse",
133
- title: "Worktree status",
134
- lines: ["Local Git snapshot; no fetch performed."],
135
- items: currentState.statusCards,
136
- viewportSize: "adaptive",
137
- hint: "back",
138
- }),
139
- },
140
- actions: {
141
- status: async ({ signal }) => {
142
- try {
143
- const statusRecords = await listWorktrees(pi, ctx.cwd, signal);
144
- state.statusCards = await loadWorktreeStatusCards(
145
- pi,
146
- statusRecords,
147
- currentPath,
148
- signal,
149
- );
150
- if (signal.aborted || !owner.isCurrent()) return { kind: "close" };
151
- return { kind: "to", screen: "status" };
152
- } catch (error) {
153
- if (signal.aborted || !owner.isCurrent()) return { kind: "close" };
154
- safeNotify(ctx, formatError(error), "error");
155
- return { kind: "stay" };
156
- }
157
- },
158
- add: async () => runFlow(() => addFlow(pi, ctx, records, root.effectiveRoot)),
159
- switch: async ({ signal }) =>
160
- runFlow(() => switchFlow(pi, ctx, records, currentPath, signal)),
161
- remove: async ({ signal }) =>
162
- runFlow(() => removeFlow(pi, ctx, records, currentPath, signal)),
163
- prune: async () => runFlow(() => pruneFlow(pi, ctx, records)),
164
- configure: async () => runFlow(() => configureRootFlow(ctx, settings)),
165
- },
166
- });
167
- await runMenu(ctx, menu, {
168
- getState: () => state,
169
- signal: owner.signal,
170
- isCurrent: owner.isCurrent,
171
- });
172
- } catch (error) {
173
- safeNotify(ctx, formatError(error), "error");
174
- }
175
- },
176
- });
76
+ pi.registerCommand("worktree", {
77
+ description: "Interactively manage Git worktrees and their default root",
78
+ handler: async (args, ctx) => {
79
+ if (args.trim()) {
80
+ safeNotify(ctx, "/worktree does not accept arguments; run it without arguments to open the menu.", "warning");
81
+ return;
82
+ }
83
+ if (!ctx.hasUI) {
84
+ safeNotify(ctx, "/worktree requires TUI or RPC mode.", "error");
85
+ return;
86
+ }
87
+
88
+ try {
89
+ await ctx.waitForIdle();
90
+ const records = await listWorktrees(pi, ctx.cwd, ctx.signal);
91
+ const currentPath = await currentWorktreePath(pi, ctx.cwd, ctx.signal);
92
+ const root = settings.get();
93
+ const warning = root.warning ? " — settings warning" : "";
94
+ const owner = getMenuOwner();
95
+ const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
96
+ if (owner.signal.aborted || !owner.isCurrent()) return;
97
+ const runFlow = async (flow: () => Promise<void>) => {
98
+ try {
99
+ await flow();
100
+ } catch (error) {
101
+ safeNotify(ctx, formatError(error), "error");
102
+ }
103
+ return { kind: "close" } as const;
104
+ };
105
+ const state: WorktreeMenuState = { statusCards: [] };
106
+ type Screen = "main" | "status";
107
+ type Action = keyof typeof ACTIONS;
108
+ const menu = defineMenu<WorktreeMenuState, Screen, Action, ExtensionCommandContext>({
109
+ start: "main",
110
+ screens: {
111
+ main: () => ({
112
+ kind: "actions",
113
+ title: "Git worktrees",
114
+ lines: [
115
+ `Registered: ${records.length}`,
116
+ `Current: ${currentPath}`,
117
+ `Worktree root: ${root.effectiveRoot} (${root.source})${warning}`,
118
+ ],
119
+ items: Object.entries(ACTIONS).map(([id, label]) => ({
120
+ id,
121
+ label,
122
+ action: id as Action,
123
+ busyLabel: id === "status" ? "Inspecting worktrees…" : undefined,
124
+ })),
125
+ hint: "close",
126
+ }),
127
+ status: ({ state: currentState }) => ({
128
+ kind: "browse",
129
+ title: "Worktree status",
130
+ lines: ["Local Git snapshot; no fetch performed."],
131
+ items: currentState.statusCards,
132
+ viewportSize: "adaptive",
133
+ hint: "back",
134
+ }),
135
+ },
136
+ actions: {
137
+ status: async ({ signal }) => {
138
+ try {
139
+ const statusRecords = await listWorktrees(pi, ctx.cwd, signal);
140
+ state.statusCards = await loadWorktreeStatusCards(pi, statusRecords, currentPath, signal);
141
+ if (signal.aborted || !owner.isCurrent()) return { kind: "close" };
142
+ return { kind: "to", screen: "status" };
143
+ } catch (error) {
144
+ if (signal.aborted || !owner.isCurrent()) return { kind: "close" };
145
+ safeNotify(ctx, formatError(error), "error");
146
+ return { kind: "stay" };
147
+ }
148
+ },
149
+ add: async () => runFlow(() => addFlow(pi, ctx, records, root.effectiveRoot)),
150
+ switch: async ({ signal }) => runFlow(() => switchFlow(pi, ctx, records, currentPath, signal)),
151
+ remove: async ({ signal }) => runFlow(() => removeFlow(pi, ctx, records, currentPath, signal)),
152
+ prune: async () => runFlow(() => pruneFlow(pi, ctx, records)),
153
+ configure: async () => runFlow(() => configureRootFlow(ctx, settings)),
154
+ },
155
+ });
156
+ await runMenu(ctx, menu, {
157
+ getState: () => state,
158
+ signal: owner.signal,
159
+ isCurrent: owner.isCurrent,
160
+ });
161
+ } catch (error) {
162
+ safeNotify(ctx, formatError(error), "error");
163
+ }
164
+ },
165
+ });
177
166
  }
178
167
 
179
- async function configureRootFlow(
180
- ctx: ExtensionCommandContext,
181
- settings: WorktreeSettingsRuntime,
182
- ): Promise<void> {
183
- const current = await settings.reload();
184
- if (!current.canSave) {
185
- throw new Error(
186
- current.warning ?? `Fix ${settings.getPath()} before changing pi-worktree settings.`,
187
- );
188
- }
189
- const requested = await ctx.ui.input(
190
- "Worktree root (blank restores ~/.worktrees)",
191
- stripTerminalControls(current.configuredRoot ?? current.effectiveRoot),
192
- );
193
- if (requested === undefined) return;
194
- const configuredRoot = requested.trim() || undefined;
195
- const updated = await settings.save(configuredRoot);
196
- safeNotify(
197
- ctx,
198
- configuredRoot === undefined
199
- ? `Worktree root reset to ${updated.effectiveRoot}.`
200
- : `Worktree root saved as ${updated.effectiveRoot}.`,
201
- "info",
202
- );
168
+ async function configureRootFlow(ctx: ExtensionCommandContext, settings: WorktreeSettingsRuntime): Promise<void> {
169
+ const current = await settings.reload();
170
+ if (!current.canSave) {
171
+ throw new Error(current.warning ?? `Fix ${settings.getPath()} before changing pi-worktree settings.`);
172
+ }
173
+ const requested = await ctx.ui.input(
174
+ "Worktree root (blank restores ~/.worktrees)",
175
+ stripTerminalControls(current.configuredRoot ?? current.effectiveRoot),
176
+ );
177
+ if (requested === undefined) return;
178
+ const configuredRoot = requested.trim() || undefined;
179
+ const updated = await settings.save(configuredRoot);
180
+ safeNotify(
181
+ ctx,
182
+ configuredRoot === undefined
183
+ ? `Worktree root reset to ${updated.effectiveRoot}.`
184
+ : `Worktree root saved as ${updated.effectiveRoot}.`,
185
+ "info",
186
+ );
203
187
  }
204
188
 
205
189
  async function addFlow(
206
- pi: ExtensionAPI,
207
- ctx: ExtensionCommandContext,
208
- records: readonly WorktreeRecord[],
209
- worktreeRoot: string,
190
+ pi: ExtensionAPI,
191
+ ctx: ExtensionCommandContext,
192
+ records: readonly WorktreeRecord[],
193
+ worktreeRoot: string,
210
194
  ): Promise<void> {
211
- const main = records[0];
212
- if (!main) throw new Error("Git returned no registered worktrees.");
213
- if (main.bare) {
214
- throw new Error("The main worktree is bare; pi-worktree cannot derive a safe default path.");
215
- }
216
- if (!existsSync(main.path)) {
217
- throw new Error(
218
- `The registered main worktree path is stale: ${main.path}. Repair it with Git first.`,
219
- );
220
- }
221
-
222
- const requestedBranch = await ctx.ui.input("Branch for the new worktree", "feat/my-change");
223
- if (requestedBranch === undefined) return;
224
- const branchInput = requestedBranch.trim();
225
- if (!branchInput) throw new Error("Branch name is required.");
226
- const branch = await validateBranch(pi, ctx.cwd, branchInput, ctx.signal);
227
- const branchExists = await localBranchExists(pi, ctx.cwd, branch, ctx.signal);
228
- const occupied = worktreeForBranch(records, branch);
229
- if (occupied) {
230
- throw new Error(`Branch ${branch} is already checked out at ${occupied.path}.`);
231
- }
232
-
233
- let startOid: string | undefined;
234
- let provenance: AddBaseProvenance;
235
- if (branchExists) {
236
- provenance = {
237
- kind: "existing-local-branch",
238
- label: branch,
239
- oid: await resolveCommit(pi, ctx.cwd, `refs/heads/${branch}`, ctx.signal),
240
- };
241
- } else {
242
- const defaultStart = await symbolicBranch(pi, ctx.cwd, ctx.signal);
243
- const requestedStart = await ctx.ui.input(
244
- stripTerminalControls(
245
- defaultStart
246
- ? `Start point for ${branch} (blank uses ${defaultStart})`
247
- : `Start point for ${branch} (required because HEAD is detached)`,
248
- ),
249
- stripTerminalControls(defaultStart ?? "commit-ish"),
250
- );
251
- if (requestedStart === undefined) return;
252
- const explicitStart = requestedStart.trim();
253
- const startLabel = explicitStart || defaultStart;
254
- if (!startLabel) throw new Error("An explicit start point is required from detached HEAD.");
255
- startOid = await resolveCommit(pi, ctx.cwd, startLabel, ctx.signal);
256
- provenance = {
257
- kind: explicitStart ? "explicit-commit-ish" : "current-branch",
258
- label: startLabel,
259
- oid: startOid,
260
- };
261
- }
262
-
263
- const suggestedPath = defaultWorktreePath(main.path, branch, worktreeRoot);
264
- const requestedPath = await ctx.ui.input(
265
- stripTerminalControls(`Worktree path (blank uses ${suggestedPath})`),
266
- stripTerminalControls(suggestedPath),
267
- );
268
- if (requestedPath === undefined) return;
269
- const targetPath = pathIdentity(
270
- requestedPath.trim() ? resolve(ctx.cwd, requestedPath.trim()) : suggestedPath,
271
- );
272
- assertTargetFilesystemAvailable(targetPath);
273
- const pathCollision = records.find((record) => pathsEqual(record.path, targetPath));
274
- if (pathCollision) {
275
- throw new Error(`The target path is already registered as a worktree: ${pathCollision.path}.`);
276
- }
277
-
278
- const summary = formatAddPreview(branch, branchExists, provenance, targetPath);
279
- if (!(await ctx.ui.confirm("Create Git worktree", summary))) return;
280
-
281
- assertTargetFilesystemAvailable(targetPath);
282
- const latestRecords = await listWorktrees(pi, ctx.cwd, ctx.signal);
283
- const latestOccupied = worktreeForBranch(latestRecords, branch);
284
- if (latestOccupied) {
285
- throw new Error(
286
- `Branch ${branch} is now checked out at ${latestOccupied.path}; select it again.`,
287
- );
288
- }
289
- const latestPathCollision = latestRecords.find((record) => pathsEqual(record.path, targetPath));
290
- if (latestPathCollision) {
291
- throw new Error(
292
- `The target path is now registered as a worktree: ${latestPathCollision.path}. Select it again.`,
293
- );
294
- }
295
- const branchStillExists = await localBranchExists(pi, ctx.cwd, branch, ctx.signal);
296
- if (branchStillExists !== branchExists) {
297
- throw new Error(`Branch ${branch} changed after confirmation; select it again.`);
298
- }
299
- if (branchExists) {
300
- const latestOid = await resolveCommit(pi, ctx.cwd, `refs/heads/${branch}`, ctx.signal);
301
- if (latestOid !== provenance.oid) {
302
- throw new Error(`Branch ${branch} moved after confirmation; select it again.`);
303
- }
304
- }
305
-
306
- assertTargetFilesystemAvailable(targetPath);
307
- await addWorktree(pi, ctx.cwd, { path: targetPath, branch, startOid }, ctx.signal);
308
- let created: WorktreeRecord;
309
- try {
310
- const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
311
- const verified = updated.find((record) => pathsEqual(record.path, targetPath));
312
- if (!verified || verified.branch !== branch || verified.head !== provenance.oid) {
313
- throw new Error(
314
- "the expected path, branch, and approved HEAD were not present in Git porcelain output",
315
- );
316
- }
317
- created = verified;
318
- } catch (error) {
319
- throw new Error(
320
- `Git add completed, so the worktree was retained at ${targetPath}, but verification failed: ${formatError(error)}. Inspect git worktree list before retrying.`,
321
- );
322
- }
323
- safeNotify(ctx, `Created worktree ${targetPath} on branch ${branch}.`, "info");
324
-
325
- if (
326
- await ctx.ui.confirm(
327
- "Switch Pi workspace?",
328
- stripTerminalControls(`Continue this conversation in ${targetPath}?`),
329
- )
330
- ) {
331
- const latest = await revalidateWorktreeIdentity(pi, ctx, created);
332
- if (latest.prunableReason !== undefined || !existsSync(latest.path)) {
333
- throw new Error("The newly created worktree became unavailable; select it again.");
334
- }
335
- await switchToWorktree(ctx, latest.path);
336
- }
195
+ const main = records[0];
196
+ if (!main) throw new Error("Git returned no registered worktrees.");
197
+ if (main.bare) {
198
+ throw new Error("The main worktree is bare; pi-worktree cannot derive a safe default path.");
199
+ }
200
+ if (!existsSync(main.path)) {
201
+ throw new Error(`The registered main worktree path is stale: ${main.path}. Repair it with Git first.`);
202
+ }
203
+
204
+ const requestedBranch = await ctx.ui.input("Branch for the new worktree", "feat/my-change");
205
+ if (requestedBranch === undefined) return;
206
+ const branchInput = requestedBranch.trim();
207
+ if (!branchInput) throw new Error("Branch name is required.");
208
+ const branch = await validateBranch(pi, ctx.cwd, branchInput, ctx.signal);
209
+ const branchExists = await localBranchExists(pi, ctx.cwd, branch, ctx.signal);
210
+ const occupied = worktreeForBranch(records, branch);
211
+ if (occupied) {
212
+ throw new Error(`Branch ${branch} is already checked out at ${occupied.path}.`);
213
+ }
214
+
215
+ let startOid: string | undefined;
216
+ let provenance: AddBaseProvenance;
217
+ if (branchExists) {
218
+ provenance = {
219
+ kind: "existing-local-branch",
220
+ label: branch,
221
+ oid: await resolveCommit(pi, ctx.cwd, `refs/heads/${branch}`, ctx.signal),
222
+ };
223
+ } else {
224
+ const defaultStart = await symbolicBranch(pi, ctx.cwd, ctx.signal);
225
+ const requestedStart = await ctx.ui.input(
226
+ stripTerminalControls(
227
+ defaultStart
228
+ ? `Start point for ${branch} (blank uses ${defaultStart})`
229
+ : `Start point for ${branch} (required because HEAD is detached)`,
230
+ ),
231
+ stripTerminalControls(defaultStart ?? "commit-ish"),
232
+ );
233
+ if (requestedStart === undefined) return;
234
+ const explicitStart = requestedStart.trim();
235
+ const startLabel = explicitStart || defaultStart;
236
+ if (!startLabel) throw new Error("An explicit start point is required from detached HEAD.");
237
+ startOid = await resolveCommit(pi, ctx.cwd, startLabel, ctx.signal);
238
+ provenance = {
239
+ kind: explicitStart ? "explicit-commit-ish" : "current-branch",
240
+ label: startLabel,
241
+ oid: startOid,
242
+ };
243
+ }
244
+
245
+ const suggestedPath = defaultWorktreePath(main.path, branch, worktreeRoot);
246
+ const requestedPath = await ctx.ui.input(
247
+ stripTerminalControls(`Worktree path (blank uses ${suggestedPath})`),
248
+ stripTerminalControls(suggestedPath),
249
+ );
250
+ if (requestedPath === undefined) return;
251
+ const targetPath = pathIdentity(requestedPath.trim() ? resolve(ctx.cwd, requestedPath.trim()) : suggestedPath);
252
+ assertTargetFilesystemAvailable(targetPath);
253
+ const pathCollision = records.find((record) => pathsEqual(record.path, targetPath));
254
+ if (pathCollision) {
255
+ throw new Error(`The target path is already registered as a worktree: ${pathCollision.path}.`);
256
+ }
257
+
258
+ const summary = formatAddPreview(branch, branchExists, provenance, targetPath);
259
+ if (!(await ctx.ui.confirm("Create Git worktree", summary))) return;
260
+
261
+ assertTargetFilesystemAvailable(targetPath);
262
+ const latestRecords = await listWorktrees(pi, ctx.cwd, ctx.signal);
263
+ const latestOccupied = worktreeForBranch(latestRecords, branch);
264
+ if (latestOccupied) {
265
+ throw new Error(`Branch ${branch} is now checked out at ${latestOccupied.path}; select it again.`);
266
+ }
267
+ const latestPathCollision = latestRecords.find((record) => pathsEqual(record.path, targetPath));
268
+ if (latestPathCollision) {
269
+ throw new Error(`The target path is now registered as a worktree: ${latestPathCollision.path}. Select it again.`);
270
+ }
271
+ const branchStillExists = await localBranchExists(pi, ctx.cwd, branch, ctx.signal);
272
+ if (branchStillExists !== branchExists) {
273
+ throw new Error(`Branch ${branch} changed after confirmation; select it again.`);
274
+ }
275
+ if (branchExists) {
276
+ const latestOid = await resolveCommit(pi, ctx.cwd, `refs/heads/${branch}`, ctx.signal);
277
+ if (latestOid !== provenance.oid) {
278
+ throw new Error(`Branch ${branch} moved after confirmation; select it again.`);
279
+ }
280
+ }
281
+
282
+ assertTargetFilesystemAvailable(targetPath);
283
+ await addWorktree(pi, ctx.cwd, { path: targetPath, branch, startOid }, ctx.signal);
284
+ let created: WorktreeRecord;
285
+ try {
286
+ const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
287
+ const verified = updated.find((record) => pathsEqual(record.path, targetPath));
288
+ if (!verified || verified.branch !== branch || verified.head !== provenance.oid) {
289
+ throw new Error("the expected path, branch, and approved HEAD were not present in Git porcelain output");
290
+ }
291
+ created = verified;
292
+ } catch (error) {
293
+ throw new Error(
294
+ `Git add completed, so the worktree was retained at ${targetPath}, but verification failed: ${formatError(error)}. Inspect git worktree list before retrying.`,
295
+ );
296
+ }
297
+ safeNotify(ctx, `Created worktree ${targetPath} on branch ${branch}.`, "info");
298
+
299
+ if (
300
+ await ctx.ui.confirm("Switch Pi workspace?", stripTerminalControls(`Continue this conversation in ${targetPath}?`))
301
+ ) {
302
+ const latest = await revalidateWorktreeIdentity(pi, ctx, created);
303
+ if (latest.prunableReason !== undefined || !existsSync(latest.path)) {
304
+ throw new Error("The newly created worktree became unavailable; select it again.");
305
+ }
306
+ await switchToWorktree(ctx, latest.path);
307
+ }
337
308
  }
338
309
 
339
310
  function formatAddPreview(
340
- branch: string,
341
- branchExists: boolean,
342
- provenance: AddBaseProvenance,
343
- targetPath: string,
311
+ branch: string,
312
+ branchExists: boolean,
313
+ provenance: AddBaseProvenance,
314
+ targetPath: string,
344
315
  ): string {
345
- const base =
346
- provenance.kind === "existing-local-branch"
347
- ? `existing local branch ${quoteTerminalValue(provenance.label)}`
348
- : provenance.kind === "current-branch"
349
- ? `current branch ${quoteTerminalValue(provenance.label)}`
350
- : `explicit commit-ish ${quoteTerminalValue(provenance.label)}`;
351
- return [
352
- `Branch: ${quoteTerminalValue(branch)} (${branchExists ? "existing" : "new"} local branch)`,
353
- `Base: ${base}`,
354
- `Base commit: ${provenance.oid}`,
355
- `Path: ${quoteTerminalValue(targetPath)}`,
356
- ].join("; ");
316
+ const base =
317
+ provenance.kind === "existing-local-branch"
318
+ ? `existing local branch ${quoteTerminalValue(provenance.label)}`
319
+ : provenance.kind === "current-branch"
320
+ ? `current branch ${quoteTerminalValue(provenance.label)}`
321
+ : `explicit commit-ish ${quoteTerminalValue(provenance.label)}`;
322
+ return [
323
+ `Branch: ${quoteTerminalValue(branch)} (${branchExists ? "existing" : "new"} local branch)`,
324
+ `Base: ${base}`,
325
+ `Base commit: ${provenance.oid}`,
326
+ `Path: ${quoteTerminalValue(targetPath)}`,
327
+ ].join("; ");
357
328
  }
358
329
 
359
330
  function quoteTerminalValue(value: string): string {
360
- let quoted = "";
361
- for (const character of value) {
362
- const code = character.codePointAt(0) ?? 0;
363
- if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
364
- quoted += `\\u${code.toString(16).padStart(4, "0")}`;
365
- } else if (character === "\\" || character === '"') {
366
- quoted += `\\${character}`;
367
- } else {
368
- quoted += character;
369
- }
370
- }
371
- return `"${quoted}"`;
331
+ let quoted = "";
332
+ for (const character of value) {
333
+ const code = character.codePointAt(0) ?? 0;
334
+ if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
335
+ quoted += `\\u${code.toString(16).padStart(4, "0")}`;
336
+ } else if (character === "\\" || character === '"') {
337
+ quoted += `\\${character}`;
338
+ } else {
339
+ quoted += character;
340
+ }
341
+ }
342
+ return `"${quoted}"`;
372
343
  }
373
344
 
374
345
  function assertTargetFilesystemAvailable(targetPath: string): void {
375
- if (pathEntryExists(targetPath)) {
376
- throw new Error(`The target path already exists: ${targetPath}.`);
377
- }
378
- const unsafeAncestor = unresolvableSymlinkAncestor(targetPath);
379
- if (unsafeAncestor) {
380
- throw new Error(
381
- `The target path has an unresolvable symbolic-link ancestor: ${unsafeAncestor}.`,
382
- );
383
- }
346
+ if (pathEntryExists(targetPath)) {
347
+ throw new Error(`The target path already exists: ${targetPath}.`);
348
+ }
349
+ const unsafeAncestor = unresolvableSymlinkAncestor(targetPath);
350
+ if (unsafeAncestor) {
351
+ throw new Error(`The target path has an unresolvable symbolic-link ancestor: ${unsafeAncestor}.`);
352
+ }
384
353
  }
385
354
 
386
355
  async function switchFlow(
387
- pi: ExtensionAPI,
388
- ctx: ExtensionCommandContext,
389
- records: readonly WorktreeRecord[],
390
- currentPath: string,
391
- signal?: AbortSignal,
356
+ pi: ExtensionAPI,
357
+ ctx: ExtensionCommandContext,
358
+ records: readonly WorktreeRecord[],
359
+ currentPath: string,
360
+ signal?: AbortSignal,
392
361
  ): Promise<void> {
393
- const candidates = records.filter(
394
- (record) =>
395
- !record.bare &&
396
- record.prunableReason === undefined &&
397
- existsSync(record.path) &&
398
- !pathsEqual(record.path, currentPath),
399
- );
400
- const selected = await selectWorktree(ctx, "Switch to worktree", candidates, currentPath, signal);
401
- if (!selected) return;
402
- const latest = await revalidateWorktreeIdentity(pi, ctx, selected);
403
- if (
404
- latest.bare ||
405
- latest.prunableReason !== undefined ||
406
- !existsSync(latest.path) ||
407
- pathsEqual(latest.path, currentPath)
408
- ) {
409
- throw new Error("The selected worktree changed state; select it again.");
410
- }
411
- await switchToWorktree(ctx, latest.path);
362
+ const candidates = records.filter(
363
+ (record) =>
364
+ !record.bare &&
365
+ record.prunableReason === undefined &&
366
+ existsSync(record.path) &&
367
+ !pathsEqual(record.path, currentPath),
368
+ );
369
+ const selected = await selectWorktree(ctx, "Switch to worktree", candidates, currentPath, signal);
370
+ if (!selected) return;
371
+ const latest = await revalidateWorktreeIdentity(pi, ctx, selected);
372
+ if (
373
+ latest.bare ||
374
+ latest.prunableReason !== undefined ||
375
+ !existsSync(latest.path) ||
376
+ pathsEqual(latest.path, currentPath)
377
+ ) {
378
+ throw new Error("The selected worktree changed state; select it again.");
379
+ }
380
+ await switchToWorktree(ctx, latest.path);
412
381
  }
413
382
 
414
383
  async function removeFlow(
415
- pi: ExtensionAPI,
416
- ctx: ExtensionCommandContext,
417
- records: readonly WorktreeRecord[],
418
- currentPath: string,
419
- signal?: AbortSignal,
384
+ pi: ExtensionAPI,
385
+ ctx: ExtensionCommandContext,
386
+ records: readonly WorktreeRecord[],
387
+ currentPath: string,
388
+ signal?: AbortSignal,
420
389
  ): Promise<void> {
421
- const candidates = records.filter(
422
- (record) => !record.isMain && !record.bare && !pathsEqual(record.path, currentPath),
423
- );
424
- const selected = await selectWorktree(
425
- ctx,
426
- "Remove linked worktree",
427
- candidates,
428
- currentPath,
429
- signal,
430
- );
431
- if (!selected) return;
432
- if (selected.lockedReason !== undefined) {
433
- throw new Error(
434
- `Worktree is locked${selected.lockedReason ? `: ${selected.lockedReason}` : "."} Unlock it explicitly with Git before removal.`,
435
- );
436
- }
437
- if (selected.prunableReason !== undefined || !existsSync(selected.path)) {
438
- throw new Error("The selected worktree path is stale. Use prune instead of remove.");
439
- }
440
-
441
- const inventory = classifyRemovalInventory(
442
- await worktreeInventory(pi, selected.path, ctx.signal),
443
- );
444
- if (inventory.protected.length > 0) {
445
- throw new Error(
446
- `Removal refused because ${selected.path} contains tracked, untracked, index-flagged, or submodule data:\n${inventory.protected.join("\n")}`,
447
- );
448
- }
449
- await assertDetachedHeadIsDurable(pi, ctx, selected);
450
- const administrativePath = await worktreeAdministrativeDirectory(pi, selected.path, ctx.signal);
451
- const approvedHistoryRisks = historyRisks(
452
- selected.path,
453
- await unreachableAdministrativeHistoryOids(pi, ctx, administrativePath),
454
- );
455
- const recoveryWarning = formatAdministrativeRecoveryWarning(approvedHistoryRisks);
456
- const ignoredWarning = formatIgnoredDataWarning(inventory.ignored);
457
- const removalWarning =
458
- ignoredWarning && recoveryWarning
459
- ? `${ignoredWarning}\n${recoveryWarning.trimStart()}`
460
- : `${ignoredWarning}${recoveryWarning}`;
461
- const confirmationTitle =
462
- inventory.ignored.length > 0
463
- ? recoveryWarning
464
- ? "Remove worktree and discard local/recovery data"
465
- : "Remove worktree and delete ignored files"
466
- : recoveryWarning
467
- ? "Remove worktree and discard recovery history"
468
- : "Remove Git worktree";
469
- if (
470
- !(await ctx.ui.confirm(
471
- confirmationTitle,
472
- `Delete the worktree directory ${stripTerminalControls(selected.path)}? The branch will be preserved.${removalWarning}`,
473
- ))
474
- ) {
475
- return;
476
- }
477
-
478
- await assertAdministrativeHistoryUnchanged(
479
- pi,
480
- ctx,
481
- selected.path,
482
- administrativePath,
483
- approvedHistoryRisks,
484
- );
485
-
486
- const beforeRemoval = await listWorktrees(pi, ctx.cwd, ctx.signal);
487
- const latest = beforeRemoval.find((record) => pathsEqual(record.path, selected.path));
488
- if (!latest) throw new Error(`Worktree ${selected.path} is no longer registered.`);
489
- if (!sameWorktreeIdentity(selected, latest)) {
490
- throw new Error(`Worktree ${selected.path} changed identity; select it again.`);
491
- }
492
- if (latest.isMain || latest.lockedReason !== undefined || latest.prunableReason !== undefined) {
493
- throw new Error(
494
- `Worktree ${selected.path} changed state after confirmation; removal was refused.`,
495
- );
496
- }
497
- const latestInventory = classifyRemovalInventory(
498
- await worktreeInventory(pi, latest.path, ctx.signal),
499
- );
500
- if (latestInventory.protected.length > 0) {
501
- throw new Error(
502
- `Removal refused because new protected local data appeared after confirmation:\n${latestInventory.protected.join("\n")}`,
503
- );
504
- }
505
- if (!sameInventory(inventory.ignored, latestInventory.ignored)) {
506
- throw new Error(
507
- `Removal refused because ignored data changed after confirmation:\n${latestInventory.ignored.join("\n") || "(none)"}`,
508
- );
509
- }
510
- await assertDetachedHeadIsDurable(pi, ctx, latest);
511
- await assertAdministrativeHistoryUnchanged(
512
- pi,
513
- ctx,
514
- latest.path,
515
- administrativePath,
516
- approvedHistoryRisks,
517
- );
518
- await removeWorktree(pi, ctx.cwd, latest.path, ctx.signal);
519
- const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
520
- if (updated.some((record) => pathsEqual(record.path, selected.path))) {
521
- throw new Error(`Git remove returned success, but ${selected.path} is still registered.`);
522
- }
523
- safeNotify(ctx, `Removed worktree ${selected.path}. Its branch was preserved.`, "info");
390
+ const candidates = records.filter(
391
+ (record) => !record.isMain && !record.bare && !pathsEqual(record.path, currentPath),
392
+ );
393
+ const selected = await selectWorktree(ctx, "Remove linked worktree", candidates, currentPath, signal);
394
+ if (!selected) return;
395
+ if (selected.lockedReason !== undefined) {
396
+ throw new Error(
397
+ `Worktree is locked${selected.lockedReason ? `: ${selected.lockedReason}` : "."} Unlock it explicitly with Git before removal.`,
398
+ );
399
+ }
400
+ if (selected.prunableReason !== undefined || !existsSync(selected.path)) {
401
+ throw new Error("The selected worktree path is stale. Use prune instead of remove.");
402
+ }
403
+
404
+ const inventory = classifyRemovalInventory(await worktreeInventory(pi, selected.path, ctx.signal));
405
+ if (inventory.protected.length > 0) {
406
+ throw new Error(
407
+ `Removal refused because ${selected.path} contains tracked, untracked, index-flagged, or submodule data:\n${inventory.protected.join("\n")}`,
408
+ );
409
+ }
410
+ await assertDetachedHeadIsDurable(pi, ctx, selected);
411
+ const administrativePath = await worktreeAdministrativeDirectory(pi, selected.path, ctx.signal);
412
+ const approvedHistoryRisks = historyRisks(
413
+ selected.path,
414
+ await unreachableAdministrativeHistoryOids(pi, ctx, administrativePath),
415
+ );
416
+ const recoveryWarning = formatAdministrativeRecoveryWarning(approvedHistoryRisks);
417
+ const ignoredWarning = formatIgnoredDataWarning(inventory.ignored);
418
+ const removalWarning =
419
+ ignoredWarning && recoveryWarning
420
+ ? `${ignoredWarning}\n${recoveryWarning.trimStart()}`
421
+ : `${ignoredWarning}${recoveryWarning}`;
422
+ const confirmationTitle =
423
+ inventory.ignored.length > 0
424
+ ? recoveryWarning
425
+ ? "Remove worktree and discard local/recovery data"
426
+ : "Remove worktree and delete ignored files"
427
+ : recoveryWarning
428
+ ? "Remove worktree and discard recovery history"
429
+ : "Remove Git worktree";
430
+ if (
431
+ !(await ctx.ui.confirm(
432
+ confirmationTitle,
433
+ `Delete the worktree directory ${stripTerminalControls(selected.path)}? The branch will be preserved.${removalWarning}`,
434
+ ))
435
+ ) {
436
+ return;
437
+ }
438
+
439
+ await assertAdministrativeHistoryUnchanged(pi, ctx, selected.path, administrativePath, approvedHistoryRisks);
440
+
441
+ const beforeRemoval = await listWorktrees(pi, ctx.cwd, ctx.signal);
442
+ const latest = beforeRemoval.find((record) => pathsEqual(record.path, selected.path));
443
+ if (!latest) throw new Error(`Worktree ${selected.path} is no longer registered.`);
444
+ if (!sameWorktreeIdentity(selected, latest)) {
445
+ throw new Error(`Worktree ${selected.path} changed identity; select it again.`);
446
+ }
447
+ if (latest.isMain || latest.lockedReason !== undefined || latest.prunableReason !== undefined) {
448
+ throw new Error(`Worktree ${selected.path} changed state after confirmation; removal was refused.`);
449
+ }
450
+ const latestInventory = classifyRemovalInventory(await worktreeInventory(pi, latest.path, ctx.signal));
451
+ if (latestInventory.protected.length > 0) {
452
+ throw new Error(
453
+ `Removal refused because new protected local data appeared after confirmation:\n${latestInventory.protected.join("\n")}`,
454
+ );
455
+ }
456
+ if (!sameInventory(inventory.ignored, latestInventory.ignored)) {
457
+ throw new Error(
458
+ `Removal refused because ignored data changed after confirmation:\n${latestInventory.ignored.join("\n") || "(none)"}`,
459
+ );
460
+ }
461
+ await assertDetachedHeadIsDurable(pi, ctx, latest);
462
+ await assertAdministrativeHistoryUnchanged(pi, ctx, latest.path, administrativePath, approvedHistoryRisks);
463
+ await removeWorktree(pi, ctx.cwd, latest.path, ctx.signal);
464
+ const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
465
+ if (updated.some((record) => pathsEqual(record.path, selected.path))) {
466
+ throw new Error(`Git remove returned success, but ${selected.path} is still registered.`);
467
+ }
468
+ safeNotify(ctx, `Removed worktree ${selected.path}. Its branch was preserved.`, "info");
524
469
  }
525
470
 
526
471
  async function pruneFlow(
527
- pi: ExtensionAPI,
528
- ctx: ExtensionCommandContext,
529
- records: readonly WorktreeRecord[],
472
+ pi: ExtensionAPI,
473
+ ctx: ExtensionCommandContext,
474
+ records: readonly WorktreeRecord[],
530
475
  ): Promise<void> {
531
- for (const record of records.filter(
532
- (candidate) => candidate.prunableReason !== undefined && candidate.detached,
533
- )) {
534
- await assertDetachedHeadIsDurable(pi, ctx, record);
535
- }
536
- const preview = await prunePreview(pi, ctx.cwd, ctx.signal);
537
- if (!preview) {
538
- ctx.ui.notify("Git found no stale worktree metadata to prune.", "info");
539
- return;
540
- }
541
- const approvedHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
542
- const safePreview = stripTerminalControls(preview);
543
- const recoveryWarning = formatAdministrativeRecoveryWarning(approvedHistoryRisks);
544
- ctx.ui.notify(`git worktree prune --dry-run --verbose\n${safePreview}`, "warning");
545
- if (
546
- !(await ctx.ui.confirm(
547
- recoveryWarning
548
- ? "Prune metadata and discard recovery history"
549
- : "Prune stale worktree metadata",
550
- stripTerminalControls(`${safePreview}${recoveryWarning}`),
551
- ))
552
- ) {
553
- return;
554
- }
555
- const latest = await listWorktrees(pi, ctx.cwd, ctx.signal);
556
- for (const record of latest.filter(
557
- (candidate) => candidate.prunableReason !== undefined && candidate.detached,
558
- )) {
559
- await assertDetachedHeadIsDurable(pi, ctx, record);
560
- }
561
- const beforePreviewHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
562
- if (!sameAdministrativeHistoryRisks(approvedHistoryRisks, beforePreviewHistoryRisks)) {
563
- throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
564
- }
565
- const latestPreview = await prunePreview(pi, ctx.cwd, ctx.signal);
566
- const finalHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
567
- if (
568
- latestPreview !== preview ||
569
- !sameAdministrativeHistoryRisks(approvedHistoryRisks, finalHistoryRisks)
570
- ) {
571
- throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
572
- }
573
- const output = await pruneWorktrees(pi, ctx.cwd, ctx.signal);
574
- safeNotify(
575
- ctx,
576
- output ? `Pruned stale worktree metadata:\n${output}` : "Pruned stale worktree metadata.",
577
- "info",
578
- );
476
+ for (const record of records.filter((candidate) => candidate.prunableReason !== undefined && candidate.detached)) {
477
+ await assertDetachedHeadIsDurable(pi, ctx, record);
478
+ }
479
+ const preview = await prunePreview(pi, ctx.cwd, ctx.signal);
480
+ if (!preview) {
481
+ ctx.ui.notify("Git found no stale worktree metadata to prune.", "info");
482
+ return;
483
+ }
484
+ const approvedHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
485
+ const safePreview = stripTerminalControls(preview);
486
+ const recoveryWarning = formatAdministrativeRecoveryWarning(approvedHistoryRisks);
487
+ ctx.ui.notify(`git worktree prune --dry-run --verbose\n${safePreview}`, "warning");
488
+ if (
489
+ !(await ctx.ui.confirm(
490
+ recoveryWarning ? "Prune metadata and discard recovery history" : "Prune stale worktree metadata",
491
+ stripTerminalControls(`${safePreview}${recoveryWarning}`),
492
+ ))
493
+ ) {
494
+ return;
495
+ }
496
+ const latest = await listWorktrees(pi, ctx.cwd, ctx.signal);
497
+ for (const record of latest.filter((candidate) => candidate.prunableReason !== undefined && candidate.detached)) {
498
+ await assertDetachedHeadIsDurable(pi, ctx, record);
499
+ }
500
+ const beforePreviewHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
501
+ if (!sameAdministrativeHistoryRisks(approvedHistoryRisks, beforePreviewHistoryRisks)) {
502
+ throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
503
+ }
504
+ const latestPreview = await prunePreview(pi, ctx.cwd, ctx.signal);
505
+ const finalHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
506
+ if (latestPreview !== preview || !sameAdministrativeHistoryRisks(approvedHistoryRisks, finalHistoryRisks)) {
507
+ throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
508
+ }
509
+ const output = await pruneWorktrees(pi, ctx.cwd, ctx.signal);
510
+ safeNotify(ctx, output ? `Pruned stale worktree metadata:\n${output}` : "Pruned stale worktree metadata.", "info");
579
511
  }
580
512
 
581
513
  async function assertAdministrativeHistoryUnchanged(
582
- pi: ExtensionAPI,
583
- ctx: ExtensionCommandContext,
584
- selectedPath: string,
585
- approvedAdministrativePath: string,
586
- approvedHistoryRisks: readonly AdministrativeHistoryRisk[],
514
+ pi: ExtensionAPI,
515
+ ctx: ExtensionCommandContext,
516
+ selectedPath: string,
517
+ approvedAdministrativePath: string,
518
+ approvedHistoryRisks: readonly AdministrativeHistoryRisk[],
587
519
  ): Promise<void> {
588
- const latestAdministrativePath = await worktreeAdministrativeDirectory(
589
- pi,
590
- selectedPath,
591
- ctx.signal,
592
- );
593
- const latestHistoryRisks = historyRisks(
594
- selectedPath,
595
- await unreachableAdministrativeHistoryOids(pi, ctx, latestAdministrativePath),
596
- );
597
- if (
598
- !pathsEqual(approvedAdministrativePath, latestAdministrativePath) ||
599
- !sameAdministrativeHistoryRisks(approvedHistoryRisks, latestHistoryRisks)
600
- ) {
601
- throw new Error(
602
- `Worktree ${selectedPath} administrative recovery history changed after confirmation; select it again.`,
603
- );
604
- }
520
+ const latestAdministrativePath = await worktreeAdministrativeDirectory(pi, selectedPath, ctx.signal);
521
+ const latestHistoryRisks = historyRisks(
522
+ selectedPath,
523
+ await unreachableAdministrativeHistoryOids(pi, ctx, latestAdministrativePath),
524
+ );
525
+ if (
526
+ !pathsEqual(approvedAdministrativePath, latestAdministrativePath) ||
527
+ !sameAdministrativeHistoryRisks(approvedHistoryRisks, latestHistoryRisks)
528
+ ) {
529
+ throw new Error(
530
+ `Worktree ${selectedPath} administrative recovery history changed after confirmation; select it again.`,
531
+ );
532
+ }
605
533
  }
606
534
 
607
535
  async function inspectAdministrativePruneCandidates(
608
- pi: ExtensionAPI,
609
- ctx: ExtensionCommandContext,
536
+ pi: ExtensionAPI,
537
+ ctx: ExtensionCommandContext,
610
538
  ): Promise<AdministrativeHistoryRisk[]> {
611
- const risks: AdministrativeHistoryRisk[] = [];
612
- for (const candidate of await administrativePruneCandidates(pi, ctx.cwd, ctx.signal)) {
613
- if (candidate.indexDirty) {
614
- throw new Error(
615
- `Prune refused because administrative worktree ${candidate.id} contains staged-only index changes.`,
616
- );
617
- }
618
- if (candidate.head) {
619
- const refs = await durableRefsContaining(pi, ctx.cwd, candidate.head, ctx.signal);
620
- if (refs.length === 0) {
621
- throw new Error(
622
- `Prune refused because administrative worktree ${candidate.id} has detached HEAD ${candidate.head}, which is not reachable from a durable ref.`,
623
- );
624
- }
625
- } else if (
626
- !candidate.branchRef ||
627
- !(await durableRefExists(pi, ctx.cwd, candidate.branchRef, ctx.signal))
628
- ) {
629
- throw new Error(
630
- `Prune refused because administrative worktree ${candidate.id} does not resolve to a durable ref.`,
631
- );
632
- }
633
- risks.push(
634
- ...historyRisks(
635
- candidate.id,
636
- await unreachableAdministrativeHistoryOids(pi, ctx, candidate.administrativePath),
637
- ),
638
- );
639
- }
640
- return normalizeAdministrativeHistoryRisks(risks);
539
+ const risks: AdministrativeHistoryRisk[] = [];
540
+ for (const candidate of await administrativePruneCandidates(pi, ctx.cwd, ctx.signal)) {
541
+ if (candidate.indexDirty) {
542
+ throw new Error(
543
+ `Prune refused because administrative worktree ${candidate.id} contains staged-only index changes.`,
544
+ );
545
+ }
546
+ if (candidate.head) {
547
+ const refs = await durableRefsContaining(pi, ctx.cwd, candidate.head, ctx.signal);
548
+ if (refs.length === 0) {
549
+ throw new Error(
550
+ `Prune refused because administrative worktree ${candidate.id} has detached HEAD ${candidate.head}, which is not reachable from a durable ref.`,
551
+ );
552
+ }
553
+ } else if (!candidate.branchRef || !(await durableRefExists(pi, ctx.cwd, candidate.branchRef, ctx.signal))) {
554
+ throw new Error(
555
+ `Prune refused because administrative worktree ${candidate.id} does not resolve to a durable ref.`,
556
+ );
557
+ }
558
+ risks.push(
559
+ ...historyRisks(candidate.id, await unreachableAdministrativeHistoryOids(pi, ctx, candidate.administrativePath)),
560
+ );
561
+ }
562
+ return normalizeAdministrativeHistoryRisks(risks);
641
563
  }
642
564
 
643
565
  async function unreachableAdministrativeHistoryOids(
644
- pi: ExtensionAPI,
645
- ctx: ExtensionCommandContext,
646
- administrativePath: string,
566
+ pi: ExtensionAPI,
567
+ ctx: ExtensionCommandContext,
568
+ administrativePath: string,
647
569
  ): Promise<string[]> {
648
- const unreachable: string[] = [];
649
- for (const oid of await administrativeHistoryOids(pi, ctx.cwd, administrativePath, ctx.signal)) {
650
- const refs = await durableRefsContaining(pi, ctx.cwd, oid, ctx.signal);
651
- if (refs.length === 0) unreachable.push(oid);
652
- }
653
- return [...new Set(unreachable)].sort();
570
+ const unreachable: string[] = [];
571
+ for (const oid of await administrativeHistoryOids(pi, ctx.cwd, administrativePath, ctx.signal)) {
572
+ const refs = await durableRefsContaining(pi, ctx.cwd, oid, ctx.signal);
573
+ if (refs.length === 0) unreachable.push(oid);
574
+ }
575
+ return [...new Set(unreachable)].sort();
654
576
  }
655
577
 
656
578
  function historyRisks(label: string, oids: string[]): AdministrativeHistoryRisk[] {
657
- return oids.length > 0 ? [{ label, oids }] : [];
579
+ return oids.length > 0 ? [{ label, oids }] : [];
658
580
  }
659
581
 
660
- function normalizeAdministrativeHistoryRisks(
661
- risks: readonly AdministrativeHistoryRisk[],
662
- ): AdministrativeHistoryRisk[] {
663
- return risks
664
- .map((risk) => ({ label: risk.label, oids: [...new Set(risk.oids)].sort() }))
665
- .filter((risk) => risk.oids.length > 0)
666
- .sort((left, right) => left.label.localeCompare(right.label));
582
+ function normalizeAdministrativeHistoryRisks(risks: readonly AdministrativeHistoryRisk[]): AdministrativeHistoryRisk[] {
583
+ return risks
584
+ .map((risk) => ({ label: risk.label, oids: [...new Set(risk.oids)].sort() }))
585
+ .filter((risk) => risk.oids.length > 0)
586
+ .sort((left, right) => left.label.localeCompare(right.label));
667
587
  }
668
588
 
669
589
  function sameAdministrativeHistoryRisks(
670
- left: readonly AdministrativeHistoryRisk[],
671
- right: readonly AdministrativeHistoryRisk[],
590
+ left: readonly AdministrativeHistoryRisk[],
591
+ right: readonly AdministrativeHistoryRisk[],
672
592
  ): boolean {
673
- return (
674
- JSON.stringify(normalizeAdministrativeHistoryRisks(left)) ===
675
- JSON.stringify(normalizeAdministrativeHistoryRisks(right))
676
- );
593
+ return (
594
+ JSON.stringify(normalizeAdministrativeHistoryRisks(left)) ===
595
+ JSON.stringify(normalizeAdministrativeHistoryRisks(right))
596
+ );
677
597
  }
678
598
 
679
599
  function formatAdministrativeRecoveryWarning(risks: readonly AdministrativeHistoryRisk[]): string {
680
- if (risks.length === 0) return "";
681
- const entries = risks
682
- .map(
683
- (risk) =>
684
- `${stripTerminalControls(risk.label)}: ${risk.oids.map(stripTerminalControls).join(", ")}`,
685
- )
686
- .join("; ");
687
- 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.`;
600
+ if (risks.length === 0) return "";
601
+ const entries = risks
602
+ .map((risk) => `${stripTerminalControls(risk.label)}: ${risk.oids.map(stripTerminalControls).join(", ")}`)
603
+ .join("; ");
604
+ 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.`;
688
605
  }
689
606
 
690
607
  interface RemovalInventory {
691
- ignored: string[];
692
- protected: string[];
608
+ ignored: string[];
609
+ protected: string[];
693
610
  }
694
611
 
695
612
  function classifyRemovalInventory(lines: readonly string[]): RemovalInventory {
696
- const ignored: string[] = [];
697
- const protectedData: string[] = [];
698
- for (const line of lines) {
699
- (line.startsWith("!! ") ? ignored : protectedData).push(line);
700
- }
701
- return {
702
- ignored: normalizeInventory(ignored),
703
- protected: normalizeInventory(protectedData),
704
- };
613
+ const ignored: string[] = [];
614
+ const protectedData: string[] = [];
615
+ for (const line of lines) {
616
+ (line.startsWith("!! ") ? ignored : protectedData).push(line);
617
+ }
618
+ return {
619
+ ignored: normalizeInventory(ignored),
620
+ protected: normalizeInventory(protectedData),
621
+ };
705
622
  }
706
623
 
707
624
  function normalizeInventory(lines: readonly string[]): string[] {
708
- return [...new Set(lines)].sort();
625
+ return [...new Set(lines)].sort();
709
626
  }
710
627
 
711
628
  function sameInventory(left: readonly string[], right: readonly string[]): boolean {
712
- return JSON.stringify(normalizeInventory(left)) === JSON.stringify(normalizeInventory(right));
629
+ return JSON.stringify(normalizeInventory(left)) === JSON.stringify(normalizeInventory(right));
713
630
  }
714
631
 
715
632
  function formatIgnoredDataWarning(ignored: readonly string[]): string {
716
- if (ignored.length === 0) return "";
717
- return ` Ignored files and directories that will be deleted:\n${ignored.map(stripTerminalControls).join("\n")}`;
633
+ if (ignored.length === 0) return "";
634
+ return ` Ignored files and directories that will be deleted:\n${ignored.map(stripTerminalControls).join("\n")}`;
718
635
  }
719
636
 
720
637
  async function assertDetachedHeadIsDurable(
721
- pi: ExtensionAPI,
722
- ctx: ExtensionCommandContext,
723
- record: WorktreeRecord,
638
+ pi: ExtensionAPI,
639
+ ctx: ExtensionCommandContext,
640
+ record: WorktreeRecord,
724
641
  ): Promise<void> {
725
- if (!record.detached) return;
726
- if (!record.head)
727
- throw new Error(`Detached worktree ${record.path} has no HEAD object; refusing.`);
728
- const refs = await durableRefsContaining(pi, ctx.cwd, record.head, ctx.signal);
729
- if (refs.length === 0) {
730
- throw new Error(
731
- `Detached HEAD ${record.head} at ${record.path} is not reachable from a local branch, tag, or remote ref. Preserve it before continuing.`,
732
- );
733
- }
642
+ if (!record.detached) return;
643
+ if (!record.head) throw new Error(`Detached worktree ${record.path} has no HEAD object; refusing.`);
644
+ const refs = await durableRefsContaining(pi, ctx.cwd, record.head, ctx.signal);
645
+ if (refs.length === 0) {
646
+ throw new Error(
647
+ `Detached HEAD ${record.head} at ${record.path} is not reachable from a local branch, tag, or remote ref. Preserve it before continuing.`,
648
+ );
649
+ }
734
650
  }
735
651
 
736
652
  async function revalidateWorktreeIdentity(
737
- pi: ExtensionAPI,
738
- ctx: ExtensionCommandContext,
739
- selected: WorktreeRecord,
653
+ pi: ExtensionAPI,
654
+ ctx: ExtensionCommandContext,
655
+ selected: WorktreeRecord,
740
656
  ): Promise<WorktreeRecord> {
741
- const latest = (await listWorktrees(pi, ctx.cwd, ctx.signal)).find((record) =>
742
- pathsEqual(record.path, selected.path),
743
- );
744
- if (!latest) throw new Error(`Worktree ${selected.path} is no longer registered.`);
745
- if (!sameWorktreeIdentity(selected, latest)) {
746
- throw new Error(`Worktree ${selected.path} changed identity; select it again.`);
747
- }
748
- return latest;
657
+ const latest = (await listWorktrees(pi, ctx.cwd, ctx.signal)).find((record) =>
658
+ pathsEqual(record.path, selected.path),
659
+ );
660
+ if (!latest) throw new Error(`Worktree ${selected.path} is no longer registered.`);
661
+ if (!sameWorktreeIdentity(selected, latest)) {
662
+ throw new Error(`Worktree ${selected.path} changed identity; select it again.`);
663
+ }
664
+ return latest;
749
665
  }
750
666
 
751
667
  async function selectWorktree(
752
- ctx: ExtensionCommandContext,
753
- title: string,
754
- records: readonly WorktreeRecord[],
755
- currentPath: string,
756
- signal?: AbortSignal,
668
+ ctx: ExtensionCommandContext,
669
+ title: string,
670
+ records: readonly WorktreeRecord[],
671
+ currentPath: string,
672
+ signal?: AbortSignal,
757
673
  ): Promise<WorktreeRecord | undefined> {
758
- if (records.length === 0) {
759
- ctx.ui.notify("No eligible worktrees are available for this action.", "info");
760
- return undefined;
761
- }
762
- const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
763
- if (signal?.aborted || ctx.signal?.aborted) return undefined;
764
- let selected: WorktreeRecord | undefined;
765
- const menu = defineMenu<undefined, "worktrees", "choose", ExtensionCommandContext>({
766
- start: "worktrees",
767
- screens: {
768
- worktrees: () => ({
769
- kind: "choice",
770
- title,
771
- enableSearch: true,
772
- items: records.map((record, index) => ({
773
- id: record.path,
774
- label: `${index + 1}. ${formatWorktree(record, currentPath)}`,
775
- searchText: [record.path, record.branch, record.head].filter(Boolean).join(" "),
776
- })),
777
- action: "choose",
778
- hint: "close",
779
- }),
780
- },
781
- actions: {
782
- choose: async ({ itemId }) => {
783
- selected = records.find((record) => record.path === itemId);
784
- return selected ? { kind: "close" } : { kind: "rejected" };
785
- },
786
- },
787
- });
788
- await runMenu(ctx, menu, {
789
- getState: () => undefined,
790
- signal,
791
- isCurrent: () => !signal?.aborted,
792
- });
793
- return selected;
674
+ if (records.length === 0) {
675
+ ctx.ui.notify("No eligible worktrees are available for this action.", "info");
676
+ return undefined;
677
+ }
678
+ const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
679
+ if (signal?.aborted || ctx.signal?.aborted) return undefined;
680
+ let selected: WorktreeRecord | undefined;
681
+ const menu = defineMenu<undefined, "worktrees", "choose", ExtensionCommandContext>({
682
+ start: "worktrees",
683
+ screens: {
684
+ worktrees: () => ({
685
+ kind: "choice",
686
+ title,
687
+ enableSearch: true,
688
+ items: records.map((record, index) => ({
689
+ id: record.path,
690
+ label: `${index + 1}. ${formatWorktree(record, currentPath)}`,
691
+ searchText: [record.path, record.branch, record.head].filter(Boolean).join(" "),
692
+ })),
693
+ action: "choose",
694
+ hint: "close",
695
+ }),
696
+ },
697
+ actions: {
698
+ choose: async ({ itemId }) => {
699
+ selected = records.find((record) => record.path === itemId);
700
+ return selected ? { kind: "close" } : { kind: "rejected" };
701
+ },
702
+ },
703
+ });
704
+ await runMenu(ctx, menu, {
705
+ getState: () => undefined,
706
+ signal,
707
+ isCurrent: () => !signal?.aborted,
708
+ });
709
+ return selected;
794
710
  }
795
711
 
796
- function safeNotify(
797
- ctx: ExtensionCommandContext,
798
- message: string,
799
- level: "info" | "warning" | "error",
800
- ): void {
801
- try {
802
- ctx.ui.notify(stripTerminalControls(message), level);
803
- } catch {
804
- console.error(message);
805
- }
712
+ function safeNotify(ctx: ExtensionCommandContext, message: string, level: "info" | "warning" | "error"): void {
713
+ try {
714
+ ctx.ui.notify(stripTerminalControls(message), level);
715
+ } catch {
716
+ console.error(message);
717
+ }
806
718
  }
807
719
 
808
720
  function formatError(error: unknown): string {
809
- return error instanceof Error ? error.message : String(error);
721
+ return error instanceof Error ? error.message : String(error);
810
722
  }