@narumitw/pi-worktree 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 narumiruna
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,132 @@
1
+ # 🌳 pi-worktree — Safe Git Worktree Management for Pi
2
+
3
+ [![npm](https://img.shields.io/npm/v/@narumitw/pi-worktree)](https://www.npmjs.com/package/@narumitw/pi-worktree) [![Pi extension](https://img.shields.io/badge/Pi-extension-blue)](https://pi.dev) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
4
+
5
+ `@narumitw/pi-worktree` adds one interactive `/worktree` command for common Git worktree operations and Pi workspace switching.
6
+
7
+ Pi cannot change its parent process working directory with `cd`. This extension performs the safe equivalent: it prepares a Pi session whose cwd is the selected worktree and switches to that session, preserving the current conversation when it has already been persisted.
8
+
9
+ ## ✨ Features
10
+
11
+ - Shows compact main, linked, current, detached, locked, and prunable state in worktree selectors.
12
+ - Creates a new branch worktree or attaches an existing unoccupied local branch.
13
+ - Suggests a sibling path such as `/workspace/project-feat-login` for `feat/login`.
14
+ - Optionally switches Pi into a newly created worktree while continuing the current conversation.
15
+ - 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.
19
+ - Runs Git through argv-based subprocess calls, without interpolating user input into shell commands.
20
+
21
+ ## 📦 Install
22
+
23
+ ```bash
24
+ pi install npm:@narumitw/pi-worktree
25
+ ```
26
+
27
+ Try without installing permanently:
28
+
29
+ ```bash
30
+ pi -e npm:@narumitw/pi-worktree
31
+ ```
32
+
33
+ Try this package locally from the repository root:
34
+
35
+ ```bash
36
+ just try-worktree
37
+ # or: pi -e ./extensions/pi-worktree
38
+ ```
39
+
40
+ ## 💬 Usage
41
+
42
+ Run the command without arguments:
43
+
44
+ ```text
45
+ /worktree
46
+ ```
47
+
48
+ Choose one action:
49
+
50
+ - **Add worktree** — enter a branch, optional start point, and optional path; confirm creation and optionally switch.
51
+ - **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.
53
+ - **Prune stale metadata** — inspect Git's dry-run output, then optionally run the matching prune.
54
+
55
+ `/worktree` intentionally does not accept text subcommands in this version. Every mutation is initiated and confirmed through the interactive UI.
56
+
57
+ ## 🌿 Add defaults
58
+
59
+ For a new branch, the current symbolic branch is the default start point. If Pi is running from detached HEAD, the command requires an explicit commit-ish. Git must resolve the start point to exactly one commit.
60
+
61
+ The suggested path is a sibling of the main worktree:
62
+
63
+ ```text
64
+ main worktree: /home/user/workspace/project
65
+ branch: feat/login
66
+ suggested: /home/user/workspace/project-feat-login
67
+ ```
68
+
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.
70
+
71
+ The MVP does not expose `--force`, `-B`, `--detach`, `--orphan`, or lock options.
72
+
73
+ ## 🔀 Pi workspace switching
74
+
75
+ Switching uses Pi's public `SessionManager` and `ctx.switchSession()` APIs:
76
+
77
+ 1. The command waits for Pi to become fully idle so the current assistant/tool results are persisted.
78
+ 2. A linear persisted session is forked into the target worktree. If `/tree` currently points at an older branch, the documented session entries for that active branch are written to the target instead, so switching cannot jump to a newer serialized leaf.
79
+ 3. Pi tears down the old cwd-bound runtime and creates the target runtime.
80
+ 4. The extension reports success only through the fresh replacement-session context.
81
+
82
+ If the current session is completely empty, the extension creates a valid empty Pi session for the target. If the current session is ephemeral (`--no-session`), the extension copies its active conversation branch into a persisted target session so the workspace switch does not lose context.
83
+
84
+ A successfully created Git worktree is never rolled back merely because Pi session switching fails. Re-run `/worktree` and choose **Switch worktree** after resolving the reported Pi/session issue.
85
+
86
+ ## 🛡️ Safety boundaries
87
+
88
+ - The main worktree and current worktree cannot be removed.
89
+ - Locked or stale worktrees cannot be removed through this extension.
90
+ - Dirty, untracked, ignored, and initialized-submodule data causes removal to fail closed.
91
+ - 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.
93
+ - 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.
95
+ - The extension does not commit, push, rebase, repair, move, lock, or unlock worktrees.
96
+
97
+ Use Git directly when you intentionally need force removal, branch deletion, custom prune expiry, detach/orphan creation, move, repair, lock, or unlock behavior.
98
+
99
+ ## Requirements and limits
100
+
101
+ - Git must be installed and the current Pi cwd must be inside a non-bare Git worktree.
102
+ - The command requires a UI-capable Pi mode; print and JSON modes cannot drive its dialogs.
103
+ - Project trust and cwd-bound extension/resource loading during a switch remain owned by Pi.
104
+ - The extension registers no LLM tool, background watcher, settings file, or statusline item.
105
+
106
+ ## 📁 Package layout
107
+
108
+ ```text
109
+ extensions/pi-worktree/
110
+ ├── src/
111
+ │ ├── command.ts
112
+ │ ├── git.ts
113
+ │ ├── session.ts
114
+ │ └── worktree.ts
115
+ ├── test/
116
+ │ ├── command.test.ts
117
+ │ ├── git.integration.test.ts
118
+ │ ├── git.test.ts
119
+ │ └── session.test.ts
120
+ ├── package.json
121
+ ├── README.md
122
+ ├── LICENSE
123
+ └── tsconfig.json
124
+ ```
125
+
126
+ ## 🏷️ Keywords
127
+
128
+ `pi-package`, `pi-extension`, `git`, `worktree`, `workspace`, `session`
129
+
130
+ ## 📄 License
131
+
132
+ MIT
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@narumitw/pi-worktree",
3
+ "version": "0.24.0",
4
+ "description": "Pi extension for safe interactive Git worktree management and workspace switching.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "keywords": [
9
+ "pi-package",
10
+ "pi-extension",
11
+ "pi",
12
+ "git",
13
+ "worktree",
14
+ "workspace"
15
+ ],
16
+ "files": [
17
+ "src",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "pi": {
22
+ "extensions": [
23
+ "./src/worktree.ts"
24
+ ]
25
+ },
26
+ "scripts": {
27
+ "check": "biome check --vcs-use-ignore-file=false src test package.json README.md tsconfig.json && npm run typecheck",
28
+ "format": "biome check --write --vcs-use-ignore-file=false src test package.json README.md tsconfig.json",
29
+ "typecheck": "tsc --noEmit"
30
+ },
31
+ "peerDependencies": {
32
+ "@earendil-works/pi-coding-agent": "*"
33
+ },
34
+ "devDependencies": {
35
+ "@biomejs/biome": "2.5.3",
36
+ "@earendil-works/pi-coding-agent": "0.80.10",
37
+ "@types/node": "26.1.1",
38
+ "typescript": "7.0.2"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/narumiruna/pi-extensions",
43
+ "directory": "extensions/pi-worktree"
44
+ }
45
+ }
package/src/command.ts ADDED
@@ -0,0 +1,429 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
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
+ validateBranch,
26
+ type WorktreeRecord,
27
+ worktreeAdministrativeDirectory,
28
+ worktreeForBranch,
29
+ worktreeInventory,
30
+ } from "./git.js";
31
+ import { switchToWorktree } from "./session.js";
32
+
33
+ const ACTION_ADD = "Add worktree";
34
+ const ACTION_SWITCH = "Switch worktree";
35
+ const ACTION_REMOVE = "Remove worktree";
36
+ const ACTION_PRUNE = "Prune stale metadata";
37
+ const ACTIONS = [ACTION_ADD, ACTION_SWITCH, ACTION_REMOVE, ACTION_PRUNE];
38
+
39
+ export function registerWorktreeCommand(pi: ExtensionAPI): void {
40
+ pi.registerCommand("worktree", {
41
+ description: "Interactively add, switch, remove, or prune Git worktrees",
42
+ handler: async (args, ctx) => {
43
+ if (args.trim()) {
44
+ safeNotify(
45
+ ctx,
46
+ "/worktree does not accept arguments; run it without arguments to open the menu.",
47
+ "warning",
48
+ );
49
+ return;
50
+ }
51
+ if (!ctx.hasUI) {
52
+ safeNotify(ctx, "/worktree requires an interactive Pi UI.", "error");
53
+ return;
54
+ }
55
+
56
+ try {
57
+ await ctx.waitForIdle();
58
+ const records = await listWorktrees(pi, ctx.cwd, ctx.signal);
59
+ const currentPath = await currentWorktreePath(pi, ctx.cwd, ctx.signal);
60
+ const action = await ctx.ui.select(
61
+ stripTerminalControls(`Git worktrees (${records.length}) — current: ${currentPath}`),
62
+ ACTIONS,
63
+ );
64
+ switch (action) {
65
+ case ACTION_ADD:
66
+ await addFlow(pi, ctx, records);
67
+ return;
68
+ case ACTION_SWITCH:
69
+ await switchFlow(pi, ctx, records, currentPath);
70
+ return;
71
+ case ACTION_REMOVE:
72
+ await removeFlow(pi, ctx, records, currentPath);
73
+ return;
74
+ case ACTION_PRUNE:
75
+ await pruneFlow(pi, ctx, records);
76
+ return;
77
+ }
78
+ } catch (error) {
79
+ safeNotify(ctx, formatError(error), "error");
80
+ }
81
+ },
82
+ });
83
+ }
84
+
85
+ async function addFlow(
86
+ pi: ExtensionAPI,
87
+ ctx: ExtensionCommandContext,
88
+ records: readonly WorktreeRecord[],
89
+ ): Promise<void> {
90
+ const main = records[0];
91
+ if (!main) throw new Error("Git returned no registered worktrees.");
92
+ if (main.bare) {
93
+ throw new Error("The main worktree is bare; pi-worktree cannot derive a safe default path.");
94
+ }
95
+ if (!existsSync(main.path)) {
96
+ throw new Error(
97
+ `The registered main worktree path is stale: ${main.path}. Repair it with Git first.`,
98
+ );
99
+ }
100
+
101
+ const requestedBranch = await ctx.ui.input("Branch for the new worktree", "feat/my-change");
102
+ if (requestedBranch === undefined) return;
103
+ const branchInput = requestedBranch.trim();
104
+ if (!branchInput) throw new Error("Branch name is required.");
105
+ const branch = await validateBranch(pi, ctx.cwd, branchInput, ctx.signal);
106
+ const branchExists = await localBranchExists(pi, ctx.cwd, branch, ctx.signal);
107
+ const occupied = worktreeForBranch(records, branch);
108
+ if (occupied) {
109
+ throw new Error(`Branch ${branch} is already checked out at ${occupied.path}.`);
110
+ }
111
+
112
+ let startOid: string | undefined;
113
+ let startLabel: string | undefined;
114
+ if (!branchExists) {
115
+ const defaultStart = await symbolicBranch(pi, ctx.cwd, ctx.signal);
116
+ 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",
121
+ );
122
+ if (requestedStart === undefined) return;
123
+ startLabel = requestedStart.trim() || defaultStart;
124
+ if (!startLabel) throw new Error("An explicit start point is required from detached HEAD.");
125
+ startOid = await resolveCommit(pi, ctx.cwd, startLabel, ctx.signal);
126
+ }
127
+
128
+ const suggestedPath = defaultWorktreePath(main.path, branch);
129
+ const requestedPath = await ctx.ui.input(
130
+ stripTerminalControls(`Worktree path (blank uses ${suggestedPath})`),
131
+ stripTerminalControls(suggestedPath),
132
+ );
133
+ if (requestedPath === undefined) return;
134
+ const targetPath = pathIdentity(
135
+ requestedPath.trim() ? resolve(ctx.cwd, requestedPath.trim()) : suggestedPath,
136
+ );
137
+ if (pathEntryExists(targetPath)) {
138
+ throw new Error(`The target path already exists: ${targetPath}.`);
139
+ }
140
+ const pathCollision = records.find((record) => pathsEqual(record.path, targetPath));
141
+ if (pathCollision) {
142
+ throw new Error(`The target path is already registered as a worktree: ${pathCollision.path}.`);
143
+ }
144
+
145
+ const summary = branchExists
146
+ ? `Attach existing branch ${branch} at ${targetPath}?`
147
+ : `Create branch ${branch} from ${startLabel} at ${targetPath}?`;
148
+ if (!(await ctx.ui.confirm("Create Git worktree", stripTerminalControls(summary)))) return;
149
+
150
+ await addWorktree(pi, ctx.cwd, { path: targetPath, branch, startOid }, ctx.signal);
151
+ let created: WorktreeRecord;
152
+ try {
153
+ const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
154
+ const verified = updated.find((record) => pathsEqual(record.path, targetPath));
155
+ if (!verified || verified.branch !== branch) {
156
+ throw new Error("the expected path and branch were not present in Git porcelain output");
157
+ }
158
+ created = verified;
159
+ } catch (error) {
160
+ throw new Error(
161
+ `Git add completed, so the worktree was retained at ${targetPath}, but verification failed: ${formatError(error)}. Inspect git worktree list before retrying.`,
162
+ );
163
+ }
164
+ safeNotify(ctx, `Created worktree ${targetPath} on branch ${branch}.`, "info");
165
+
166
+ if (
167
+ await ctx.ui.confirm(
168
+ "Switch Pi workspace?",
169
+ stripTerminalControls(`Continue this conversation in ${targetPath}?`),
170
+ )
171
+ ) {
172
+ const latest = await revalidateWorktreeIdentity(pi, ctx, created);
173
+ if (latest.prunableReason !== undefined || !existsSync(latest.path)) {
174
+ throw new Error("The newly created worktree became unavailable; select it again.");
175
+ }
176
+ await switchToWorktree(ctx, latest.path);
177
+ }
178
+ }
179
+
180
+ async function switchFlow(
181
+ pi: ExtensionAPI,
182
+ ctx: ExtensionCommandContext,
183
+ records: readonly WorktreeRecord[],
184
+ currentPath: string,
185
+ ): Promise<void> {
186
+ const candidates = records.filter(
187
+ (record) =>
188
+ !record.bare &&
189
+ record.prunableReason === undefined &&
190
+ existsSync(record.path) &&
191
+ !pathsEqual(record.path, currentPath),
192
+ );
193
+ const selected = await selectWorktree(ctx, "Switch to worktree", candidates, currentPath);
194
+ if (!selected) return;
195
+ const latest = await revalidateWorktreeIdentity(pi, ctx, selected);
196
+ if (
197
+ latest.bare ||
198
+ latest.prunableReason !== undefined ||
199
+ !existsSync(latest.path) ||
200
+ pathsEqual(latest.path, currentPath)
201
+ ) {
202
+ throw new Error("The selected worktree changed state; select it again.");
203
+ }
204
+ await switchToWorktree(ctx, latest.path);
205
+ }
206
+
207
+ async function removeFlow(
208
+ pi: ExtensionAPI,
209
+ ctx: ExtensionCommandContext,
210
+ records: readonly WorktreeRecord[],
211
+ currentPath: string,
212
+ ): Promise<void> {
213
+ const candidates = records.filter(
214
+ (record) => !record.isMain && !record.bare && !pathsEqual(record.path, currentPath),
215
+ );
216
+ const selected = await selectWorktree(
217
+ ctx,
218
+ "Remove clean linked worktree",
219
+ candidates,
220
+ currentPath,
221
+ );
222
+ if (!selected) return;
223
+ if (selected.lockedReason !== undefined) {
224
+ throw new Error(
225
+ `Worktree is locked${selected.lockedReason ? `: ${selected.lockedReason}` : "."} Unlock it explicitly with Git before removal.`,
226
+ );
227
+ }
228
+ if (selected.prunableReason !== undefined || !existsSync(selected.path)) {
229
+ throw new Error("The selected worktree path is stale. Use prune instead of remove.");
230
+ }
231
+
232
+ const inventory = await worktreeInventory(pi, selected.path, ctx.signal);
233
+ if (inventory.length > 0) {
234
+ throw new Error(
235
+ `Removal refused because ${selected.path} contains tracked, untracked, ignored, or submodule data:\n${inventory.join("\n")}`,
236
+ );
237
+ }
238
+ await assertDetachedHeadIsDurable(pi, ctx, selected);
239
+ await assertAdministrativeHistoryIsDurable(
240
+ pi,
241
+ ctx,
242
+ await worktreeAdministrativeDirectory(pi, selected.path, ctx.signal),
243
+ );
244
+ if (
245
+ !(await ctx.ui.confirm(
246
+ "Remove Git worktree",
247
+ stripTerminalControls(
248
+ `Delete the clean worktree directory ${selected.path}? The branch will be preserved.`,
249
+ ),
250
+ ))
251
+ ) {
252
+ return;
253
+ }
254
+
255
+ const beforeRemoval = await listWorktrees(pi, ctx.cwd, ctx.signal);
256
+ const latest = beforeRemoval.find((record) => pathsEqual(record.path, selected.path));
257
+ if (!latest) throw new Error(`Worktree ${selected.path} is no longer registered.`);
258
+ if (!sameWorktreeIdentity(selected, latest)) {
259
+ throw new Error(`Worktree ${selected.path} changed identity; select it again.`);
260
+ }
261
+ if (latest.isMain || latest.lockedReason !== undefined || latest.prunableReason !== undefined) {
262
+ throw new Error(
263
+ `Worktree ${selected.path} changed state after confirmation; removal was refused.`,
264
+ );
265
+ }
266
+ const latestInventory = await worktreeInventory(pi, latest.path, ctx.signal);
267
+ if (latestInventory.length > 0) {
268
+ throw new Error(
269
+ `Removal refused because new local data appeared after confirmation:\n${latestInventory.join("\n")}`,
270
+ );
271
+ }
272
+ await assertDetachedHeadIsDurable(pi, ctx, latest);
273
+ await assertAdministrativeHistoryIsDurable(
274
+ pi,
275
+ ctx,
276
+ await worktreeAdministrativeDirectory(pi, latest.path, ctx.signal),
277
+ );
278
+ await removeWorktree(pi, ctx.cwd, latest.path, ctx.signal);
279
+ const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
280
+ if (updated.some((record) => pathsEqual(record.path, selected.path))) {
281
+ throw new Error(`Git remove returned success, but ${selected.path} is still registered.`);
282
+ }
283
+ safeNotify(ctx, `Removed worktree ${selected.path}. Its branch was preserved.`, "info");
284
+ }
285
+
286
+ async function pruneFlow(
287
+ pi: ExtensionAPI,
288
+ ctx: ExtensionCommandContext,
289
+ records: readonly WorktreeRecord[],
290
+ ): Promise<void> {
291
+ for (const record of records.filter(
292
+ (candidate) => candidate.prunableReason !== undefined && candidate.detached,
293
+ )) {
294
+ await assertDetachedHeadIsDurable(pi, ctx, record);
295
+ }
296
+ const preview = await prunePreview(pi, ctx.cwd, ctx.signal);
297
+ if (!preview) {
298
+ ctx.ui.notify("Git found no stale worktree metadata to prune.", "info");
299
+ return;
300
+ }
301
+ await assertAdministrativePruneCandidatesAreDurable(pi, ctx);
302
+ const safePreview = stripTerminalControls(preview);
303
+ ctx.ui.notify(`git worktree prune --dry-run --verbose\n${safePreview}`, "warning");
304
+ if (!(await ctx.ui.confirm("Prune stale worktree metadata", safePreview))) return;
305
+ const latest = await listWorktrees(pi, ctx.cwd, ctx.signal);
306
+ for (const record of latest.filter(
307
+ (candidate) => candidate.prunableReason !== undefined && candidate.detached,
308
+ )) {
309
+ await assertDetachedHeadIsDurable(pi, ctx, record);
310
+ }
311
+ await assertAdministrativePruneCandidatesAreDurable(pi, ctx);
312
+ const output = await pruneWorktrees(pi, ctx.cwd, ctx.signal);
313
+ safeNotify(
314
+ ctx,
315
+ output ? `Pruned stale worktree metadata:\n${output}` : "Pruned stale worktree metadata.",
316
+ "info",
317
+ );
318
+ }
319
+
320
+ async function assertAdministrativePruneCandidatesAreDurable(
321
+ pi: ExtensionAPI,
322
+ ctx: ExtensionCommandContext,
323
+ ): Promise<void> {
324
+ for (const candidate of await administrativePruneCandidates(pi, ctx.cwd, ctx.signal)) {
325
+ if (candidate.indexDirty) {
326
+ throw new Error(
327
+ `Prune refused because administrative worktree ${candidate.id} contains staged-only index changes.`,
328
+ );
329
+ }
330
+ await assertAdministrativeHistoryIsDurable(pi, ctx, candidate.administrativePath);
331
+ if (candidate.head) {
332
+ const refs = await durableRefsContaining(pi, ctx.cwd, candidate.head, ctx.signal);
333
+ if (refs.length === 0) {
334
+ throw new Error(
335
+ `Prune refused because administrative worktree ${candidate.id} has detached HEAD ${candidate.head}, which is not reachable from a durable ref.`,
336
+ );
337
+ }
338
+ continue;
339
+ }
340
+ if (
341
+ !candidate.branchRef ||
342
+ !(await durableRefExists(pi, ctx.cwd, candidate.branchRef, ctx.signal))
343
+ ) {
344
+ throw new Error(
345
+ `Prune refused because administrative worktree ${candidate.id} does not resolve to a durable ref.`,
346
+ );
347
+ }
348
+ }
349
+ }
350
+
351
+ async function assertAdministrativeHistoryIsDurable(
352
+ pi: ExtensionAPI,
353
+ ctx: ExtensionCommandContext,
354
+ administrativePath: string,
355
+ ): Promise<void> {
356
+ for (const oid of await administrativeHistoryOids(pi, ctx.cwd, administrativePath, ctx.signal)) {
357
+ 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
+ }
363
+ }
364
+ }
365
+
366
+ async function assertDetachedHeadIsDurable(
367
+ pi: ExtensionAPI,
368
+ ctx: ExtensionCommandContext,
369
+ record: WorktreeRecord,
370
+ ): Promise<void> {
371
+ if (!record.detached) return;
372
+ if (!record.head)
373
+ throw new Error(`Detached worktree ${record.path} has no HEAD object; refusing.`);
374
+ const refs = await durableRefsContaining(pi, ctx.cwd, record.head, ctx.signal);
375
+ if (refs.length === 0) {
376
+ throw new Error(
377
+ `Detached HEAD ${record.head} at ${record.path} is not reachable from a local branch, tag, or remote ref. Preserve it before continuing.`,
378
+ );
379
+ }
380
+ }
381
+
382
+ async function revalidateWorktreeIdentity(
383
+ pi: ExtensionAPI,
384
+ ctx: ExtensionCommandContext,
385
+ selected: WorktreeRecord,
386
+ ): Promise<WorktreeRecord> {
387
+ const latest = (await listWorktrees(pi, ctx.cwd, ctx.signal)).find((record) =>
388
+ pathsEqual(record.path, selected.path),
389
+ );
390
+ if (!latest) throw new Error(`Worktree ${selected.path} is no longer registered.`);
391
+ if (!sameWorktreeIdentity(selected, latest)) {
392
+ throw new Error(`Worktree ${selected.path} changed identity; select it again.`);
393
+ }
394
+ return latest;
395
+ }
396
+
397
+ async function selectWorktree(
398
+ ctx: ExtensionCommandContext,
399
+ title: string,
400
+ records: readonly WorktreeRecord[],
401
+ currentPath: string,
402
+ ): Promise<WorktreeRecord | undefined> {
403
+ if (records.length === 0) {
404
+ ctx.ui.notify("No eligible worktrees are available for this action.", "info");
405
+ return undefined;
406
+ }
407
+ const labels = records.map(
408
+ (record, index) => `${index + 1}. ${formatWorktree(record, currentPath)}`,
409
+ );
410
+ const selected = await ctx.ui.select(title, labels);
411
+ const index = selected === undefined ? -1 : labels.indexOf(selected);
412
+ return index < 0 ? undefined : records[index];
413
+ }
414
+
415
+ function safeNotify(
416
+ ctx: ExtensionCommandContext,
417
+ message: string,
418
+ level: "info" | "warning" | "error",
419
+ ): void {
420
+ try {
421
+ ctx.ui.notify(stripTerminalControls(message), level);
422
+ } catch {
423
+ console.error(message);
424
+ }
425
+ }
426
+
427
+ function formatError(error: unknown): string {
428
+ return error instanceof Error ? error.message : String(error);
429
+ }