@firstpick/pi-package-webui 0.5.5 → 0.5.7

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.
@@ -0,0 +1,512 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { mkdir, readdir, realpath, stat } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+
7
+ export const WORKTREE_ERROR_CODES = Object.freeze({
8
+ NOT_A_GIT_REPO: "NOT_A_GIT_REPO",
9
+ DETACHED_HEAD: "DETACHED_HEAD",
10
+ BARE_REPO_UNSUPPORTED: "BARE_REPO_UNSUPPORTED",
11
+ INVALID_BRANCH_NAME: "INVALID_BRANCH_NAME",
12
+ BRANCH_CHECKED_OUT_ELSEWHERE: "BRANCH_CHECKED_OUT_ELSEWHERE",
13
+ TARGET_NOT_EMPTY: "TARGET_NOT_EMPTY",
14
+ TARGET_ESCAPES_PARENT: "TARGET_ESCAPES_PARENT",
15
+ DIRTY_WORKTREE: "DIRTY_WORKTREE",
16
+ WORKTREE_BUSY: "WORKTREE_BUSY",
17
+ IS_MAIN_WORKTREE: "IS_MAIN_WORKTREE",
18
+ WORKTREE_NOT_FOUND: "WORKTREE_NOT_FOUND",
19
+ GIT_COMMAND_FAILED: "GIT_COMMAND_FAILED",
20
+ });
21
+
22
+ const GIT_DEFAULT_TIMEOUT_MS = 10_000;
23
+ const GIT_MUTATION_TIMEOUT_MS = 10 * 60 * 1000;
24
+ const GIT_OUTPUT_LIMIT = 200_000;
25
+ const mutationLocks = new Map();
26
+
27
+ export function makeGitWorktreeError(code, message, details = {}) {
28
+ const error = new Error(message);
29
+ error.code = code;
30
+ error.statusCode = details.statusCode || 400;
31
+ error.details = { ...details };
32
+ delete error.details.statusCode;
33
+ return error;
34
+ }
35
+
36
+ export function gitWorktreeErrorPayload(error) {
37
+ return {
38
+ ok: false,
39
+ code: error?.code || WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED,
40
+ error: error?.message || String(error || "Git worktree operation failed"),
41
+ details: error?.details && typeof error.details === "object" ? error.details : {},
42
+ };
43
+ }
44
+
45
+ function runCommand(command, args, { cwd, timeoutMs = GIT_DEFAULT_TIMEOUT_MS, maxOutputLength = GIT_OUTPUT_LIMIT } = {}) {
46
+ return new Promise((resolve) => {
47
+ const child = spawn(command, args, {
48
+ cwd,
49
+ stdio: ["ignore", "pipe", "pipe"],
50
+ windowsHide: true,
51
+ });
52
+ let stdout = "";
53
+ let stderr = "";
54
+ let settled = false;
55
+ const finish = (result) => {
56
+ if (settled) return;
57
+ settled = true;
58
+ clearTimeout(timeout);
59
+ resolve(result);
60
+ };
61
+ const timeout = setTimeout(() => {
62
+ child.kill("SIGKILL");
63
+ finish({ exitCode: undefined, stdout, stderr, timedOut: true });
64
+ }, timeoutMs);
65
+ child.stdout.on("data", (chunk) => {
66
+ stdout += String(chunk);
67
+ if (stdout.length > maxOutputLength) stdout = stdout.slice(-maxOutputLength);
68
+ });
69
+ child.stderr.on("data", (chunk) => {
70
+ stderr += String(chunk);
71
+ if (stderr.length > maxOutputLength) stderr = stderr.slice(-maxOutputLength);
72
+ });
73
+ child.on("error", (error) => finish({ exitCode: undefined, stdout, stderr, error: error?.message || String(error) }));
74
+ child.on("exit", (exitCode, signal) => finish({ exitCode, signal, stdout, stderr, timedOut: false }));
75
+ });
76
+ }
77
+
78
+ function formatGitCommand(args) {
79
+ return ["git", ...args].map((part) => (/\s/.test(part) ? JSON.stringify(part) : part)).join(" ");
80
+ }
81
+
82
+ function gitFailureMessage(args, result) {
83
+ if (result?.timedOut) return `${formatGitCommand(args)} timed out`;
84
+ return String(result?.stderr || result?.stdout || result?.error || `${formatGitCommand(args)} failed with exit code ${result?.exitCode ?? "unknown"}`).trim();
85
+ }
86
+
87
+ async function runGit(args, { cwd, timeoutMs = GIT_DEFAULT_TIMEOUT_MS, maxOutputLength = GIT_OUTPUT_LIMIT, code = WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED } = {}) {
88
+ const result = await runCommand("git", args, { cwd, timeoutMs, maxOutputLength });
89
+ if (result.exitCode === 0 && !result.timedOut && !result.error) return result.stdout;
90
+ throw makeGitWorktreeError(code, gitFailureMessage(args, result), { command: formatGitCommand(args), cwd, exitCode: result.exitCode });
91
+ }
92
+
93
+ async function runGitResult(args, { cwd, timeoutMs = GIT_DEFAULT_TIMEOUT_MS, maxOutputLength = GIT_OUTPUT_LIMIT } = {}) {
94
+ return runCommand("git", args, { cwd, timeoutMs, maxOutputLength });
95
+ }
96
+
97
+ function isLockFailure(result) {
98
+ const text = String(`${result?.stderr || ""}\n${result?.stdout || ""}\n${result?.error || ""}`).toLowerCase();
99
+ return /(?:index\.lock|cannot lock ref|unable to create .*\.lock|another git process|file exists)/i.test(text);
100
+ }
101
+
102
+ async function runGitMutationWithRetry(args, { cwd, attempts = 3 } = {}) {
103
+ let lastResult = null;
104
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
105
+ const result = await runGitResult(args, { cwd, timeoutMs: GIT_MUTATION_TIMEOUT_MS, maxOutputLength: GIT_OUTPUT_LIMIT });
106
+ if (result.exitCode === 0 && !result.timedOut && !result.error) return result;
107
+ lastResult = result;
108
+ if (!isLockFailure(result) || attempt === attempts - 1) break;
109
+ await delay(140 * (attempt + 1));
110
+ }
111
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, gitFailureMessage(args, lastResult), { command: formatGitCommand(args), cwd, exitCode: lastResult?.exitCode });
112
+ }
113
+
114
+ async function withMutationLock(lockKey, fn) {
115
+ const key = String(lockKey || "global");
116
+ const previous = mutationLocks.get(key) || Promise.resolve();
117
+ let release = () => {};
118
+ const blocker = new Promise((resolve) => { release = resolve; });
119
+ const chain = previous.catch(() => {}).then(() => blocker);
120
+ mutationLocks.set(key, chain);
121
+ await previous.catch(() => {});
122
+ try {
123
+ return await fn();
124
+ } finally {
125
+ release();
126
+ if (mutationLocks.get(key) === chain) mutationLocks.delete(key);
127
+ }
128
+ }
129
+
130
+ async function canonicalPath(value) {
131
+ const resolved = path.resolve(String(value || ""));
132
+ try {
133
+ return await realpath(resolved);
134
+ } catch {
135
+ return resolved;
136
+ }
137
+ }
138
+
139
+ function samePath(left, right) {
140
+ return path.resolve(String(left || "")) === path.resolve(String(right || ""));
141
+ }
142
+
143
+ export function pathInside(parentPath, childPath) {
144
+ const parent = path.resolve(String(parentPath || ""));
145
+ const child = path.resolve(String(childPath || ""));
146
+ const relative = path.relative(parent, child);
147
+ return !relative || (!relative.startsWith("..") && !path.isAbsolute(relative));
148
+ }
149
+
150
+ async function directoryEntries(targetPath) {
151
+ try {
152
+ return await readdir(targetPath);
153
+ } catch (error) {
154
+ if (error?.code === "ENOENT") return null;
155
+ throw error;
156
+ }
157
+ }
158
+
159
+ async function assertTargetUsable(targetPath, { explicit = false, allowedParent = "" } = {}) {
160
+ const resolved = path.resolve(targetPath);
161
+ if (resolved.includes("\0")) {
162
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.TARGET_ESCAPES_PARENT, "Worktree path contains a NUL byte", { path: resolved });
163
+ }
164
+ if (allowedParent && !pathInside(allowedParent, resolved)) {
165
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.TARGET_ESCAPES_PARENT, `Worktree path must stay inside ${allowedParent}`, { path: resolved, allowedParent });
166
+ }
167
+ let info = null;
168
+ try {
169
+ info = await stat(resolved);
170
+ } catch (error) {
171
+ if (error?.code !== "ENOENT") throw error;
172
+ }
173
+ if (!info) return resolved;
174
+ if (!info.isDirectory()) {
175
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.TARGET_NOT_EMPTY, `Worktree path already exists and is not a directory: ${resolved}`, { path: resolved });
176
+ }
177
+ const entries = await directoryEntries(resolved);
178
+ if (entries && entries.length > 0) {
179
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.TARGET_NOT_EMPTY, `Worktree path already exists and is not empty: ${resolved}`, { path: resolved, explicit });
180
+ }
181
+ return resolved;
182
+ }
183
+
184
+ function branchFromRef(ref) {
185
+ const text = String(ref || "").trim();
186
+ return text.startsWith("refs/heads/") ? text.slice("refs/heads/".length) : text || null;
187
+ }
188
+
189
+ export function parseGitWorktreePorcelain(text = "") {
190
+ const worktrees = [];
191
+ let current = null;
192
+ const pushCurrent = () => {
193
+ if (!current) return;
194
+ current.branch = current.detached ? null : current.branch || null;
195
+ current.head = current.head || "";
196
+ current.detached = current.detached === true || !current.branch;
197
+ current.bare = current.bare === true;
198
+ current.locked = current.locked === true;
199
+ current.prunable = current.prunable === true;
200
+ worktrees.push(current);
201
+ };
202
+
203
+ for (const line of String(text || "").split(/\r?\n/)) {
204
+ if (!line.trim()) continue;
205
+ if (line.startsWith("worktree ")) {
206
+ pushCurrent();
207
+ current = {
208
+ path: line.slice("worktree ".length).trim(),
209
+ branch: null,
210
+ head: "",
211
+ detached: false,
212
+ bare: false,
213
+ locked: false,
214
+ prunable: false,
215
+ };
216
+ continue;
217
+ }
218
+ if (!current) continue;
219
+ if (line.startsWith("HEAD ")) current.head = line.slice("HEAD ".length).trim();
220
+ else if (line.startsWith("branch ")) current.branch = branchFromRef(line.slice("branch ".length));
221
+ else if (line === "detached") current.detached = true;
222
+ else if (line === "bare") current.bare = true;
223
+ else if (line.startsWith("locked")) {
224
+ current.locked = true;
225
+ current.lockedReason = line.slice("locked".length).trim();
226
+ } else if (line.startsWith("prunable")) {
227
+ current.prunable = true;
228
+ current.prunableReason = line.slice("prunable".length).trim();
229
+ }
230
+ }
231
+ pushCurrent();
232
+ return worktrees;
233
+ }
234
+
235
+ async function decorateWorktree(raw, repo, currentPath) {
236
+ const resolvedPath = await canonicalPath(raw.path);
237
+ const mainPath = repo.mainWorktreePath;
238
+ return {
239
+ repoRoot: mainPath,
240
+ commonGitDir: repo.commonGitDir,
241
+ path: resolvedPath,
242
+ branch: raw.branch || null,
243
+ head: raw.head || "",
244
+ detached: raw.detached === true,
245
+ bare: raw.bare === true,
246
+ locked: raw.locked === true,
247
+ prunable: raw.prunable === true,
248
+ current: samePath(resolvedPath, currentPath),
249
+ isMainWorktree: samePath(resolvedPath, mainPath),
250
+ ...(raw.lockedReason ? { lockedReason: raw.lockedReason } : {}),
251
+ ...(raw.prunableReason ? { prunableReason: raw.prunableReason } : {}),
252
+ };
253
+ }
254
+
255
+ async function discoverRepository(cwd) {
256
+ const sourceCwd = path.resolve(String(cwd || process.cwd()));
257
+ let currentTopLevel;
258
+ try {
259
+ currentTopLevel = (await runGit(["rev-parse", "--show-toplevel"], { cwd: sourceCwd, code: WORKTREE_ERROR_CODES.NOT_A_GIT_REPO })).trim();
260
+ } catch (error) {
261
+ if (error?.code === WORKTREE_ERROR_CODES.NOT_A_GIT_REPO || /not a git repository/i.test(error?.message || "")) {
262
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.NOT_A_GIT_REPO, `Not inside a Git repository: ${sourceCwd}`, { cwd: sourceCwd, statusCode: 404 });
263
+ }
264
+ throw error;
265
+ }
266
+ const currentWorktreePath = await canonicalPath(currentTopLevel);
267
+ const commonRaw = (await runGit(["rev-parse", "--git-common-dir"], { cwd: currentWorktreePath })).trim();
268
+ const commonGitDir = await canonicalPath(path.isAbsolute(commonRaw) ? commonRaw : path.resolve(currentWorktreePath, commonRaw));
269
+ const listText = await runGit(["worktree", "list", "--porcelain"], { cwd: currentWorktreePath, maxOutputLength: GIT_OUTPUT_LIMIT });
270
+ const rawWorktrees = parseGitWorktreePorcelain(listText);
271
+ if (!rawWorktrees.length) {
272
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.NOT_A_GIT_REPO, `Cannot list Git worktrees for ${currentWorktreePath}`, { cwd: sourceCwd });
273
+ }
274
+ if (rawWorktrees[0]?.bare) {
275
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.BARE_REPO_UNSUPPORTED, "Bare repositories are not supported by Pi worktree tabs yet", { cwd: sourceCwd, commonGitDir });
276
+ }
277
+ const mainWorktreePath = await canonicalPath(rawWorktrees[0].path);
278
+ const repoName = path.basename(mainWorktreePath) || "repo";
279
+ const defaultWorktreesRoot = path.join(path.dirname(mainWorktreePath), `${repoName}.worktrees`);
280
+ return {
281
+ sourceCwd,
282
+ currentWorktreePath,
283
+ commonGitDir,
284
+ mainWorktreePath,
285
+ repoName,
286
+ defaultWorktreesRoot,
287
+ rawWorktrees,
288
+ };
289
+ }
290
+
291
+ async function readWorktreeData(cwd) {
292
+ const repo = await discoverRepository(cwd);
293
+ const worktrees = await Promise.all(repo.rawWorktrees.map((item) => decorateWorktree(item, repo, repo.currentWorktreePath)));
294
+ const current = worktrees.find((item) => item.current) || null;
295
+ const occupiedBranches = worktrees
296
+ .filter((item) => item.branch && !item.bare && !item.prunable)
297
+ .map((item) => ({ branch: item.branch, path: item.path, current: item.current, isMainWorktree: item.isMainWorktree }));
298
+ return {
299
+ cwd: repo.sourceCwd,
300
+ sourceCwd: repo.sourceCwd,
301
+ repoRoot: repo.mainWorktreePath,
302
+ commonGitDir: repo.commonGitDir,
303
+ currentWorktreePath: repo.currentWorktreePath,
304
+ currentBranch: current?.branch || null,
305
+ defaultWorktreesRoot: repo.defaultWorktreesRoot,
306
+ generatedAt: new Date().toISOString(),
307
+ worktrees,
308
+ occupiedBranches,
309
+ };
310
+ }
311
+
312
+ export async function listGitWorktrees(cwd) {
313
+ return readWorktreeData(cwd);
314
+ }
315
+
316
+ function cleanBranchName(value) {
317
+ const branch = String(value || "").trim();
318
+ if (!branch || branch.includes("\0") || branch.includes("@{") || branch.startsWith("-") || branch.startsWith("/")) {
319
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.INVALID_BRANCH_NAME, "Invalid Git branch name", { branch });
320
+ }
321
+ return branch;
322
+ }
323
+
324
+ async function validateBranchName(repo, branch) {
325
+ const result = await runGitResult(["check-ref-format", "--branch", branch], { cwd: repo.repoRoot, timeoutMs: 5000, maxOutputLength: 20_000 });
326
+ if (result.exitCode !== 0 || result.timedOut || result.error) {
327
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.INVALID_BRANCH_NAME, gitFailureMessage(["check-ref-format", "--branch", branch], result), { branch });
328
+ }
329
+ }
330
+
331
+ async function branchExists(repoRoot, branch) {
332
+ const result = await runGitResult(["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], { cwd: repoRoot, timeoutMs: 5000, maxOutputLength: 20_000 });
333
+ if (result.exitCode === 0) return true;
334
+ if (result.exitCode === 1) return false;
335
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED, gitFailureMessage(["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], result), { branch });
336
+ }
337
+
338
+ export function slugifyWorktreeBranch(branch) {
339
+ const slug = String(branch || "")
340
+ .toLowerCase()
341
+ .replace(/[^a-z0-9._-]+/g, "-")
342
+ .replace(/[-.]{2,}/g, "-")
343
+ .replace(/^-+|-+$/g, "")
344
+ .slice(0, 96);
345
+ return slug || "branch";
346
+ }
347
+
348
+ function branchHash(branch) {
349
+ return createHash("sha1").update(String(branch || "")).digest("hex").slice(0, 6);
350
+ }
351
+
352
+ async function pathExistsNonEmpty(targetPath) {
353
+ const info = await stat(targetPath).catch((error) => {
354
+ if (error?.code === "ENOENT") return null;
355
+ throw error;
356
+ });
357
+ if (!info) return false;
358
+ if (!info.isDirectory()) return true;
359
+ const entries = await readdir(targetPath).catch(() => []);
360
+ return entries.length > 0;
361
+ }
362
+
363
+ async function defaultWorktreePath(repo, branch, worktrees) {
364
+ const root = repo.defaultWorktreesRoot;
365
+ await mkdir(root, { recursive: true });
366
+ const slug = slugifyWorktreeBranch(branch);
367
+ const candidates = [path.join(root, slug), path.join(root, `${slug}-${branchHash(branch)}`)];
368
+ for (let i = 2; i <= 25; i += 1) candidates.push(path.join(root, `${slug}-${i}`));
369
+
370
+ for (const candidate of candidates) {
371
+ const occupied = worktrees.find((item) => samePath(item.path, candidate));
372
+ if (occupied && occupied.branch === branch) return candidate;
373
+ if (occupied) continue;
374
+ if (!(await pathExistsNonEmpty(candidate))) return candidate;
375
+ }
376
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.TARGET_NOT_EMPTY, `No available worktree path under ${root} for ${branch}`, { branch, defaultWorktreesRoot: root });
377
+ }
378
+
379
+ async function resolveCreateTarget(repo, branch, worktrees, requestedPath) {
380
+ if (requestedPath) {
381
+ const targetPath = path.resolve(repo.sourceCwd, String(requestedPath));
382
+ if (pathInside(repo.commonGitDir, targetPath)) {
383
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.TARGET_ESCAPES_PARENT, "Worktree path cannot be inside the Git common directory", { path: targetPath, commonGitDir: repo.commonGitDir });
384
+ }
385
+ if (samePath(targetPath, repo.repoRoot)) {
386
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.TARGET_NOT_EMPTY, "Worktree path cannot be the main checkout", { path: targetPath });
387
+ }
388
+ return assertTargetUsable(targetPath, { explicit: true });
389
+ }
390
+ const targetPath = await defaultWorktreePath(repo, branch, worktrees);
391
+ return assertTargetUsable(targetPath, { allowedParent: repo.defaultWorktreesRoot });
392
+ }
393
+
394
+ function responseBase(data, worktree) {
395
+ return {
396
+ repoRoot: data.repoRoot,
397
+ commonGitDir: data.commonGitDir,
398
+ currentWorktreePath: data.currentWorktreePath,
399
+ defaultWorktreesRoot: data.defaultWorktreesRoot,
400
+ worktree,
401
+ worktrees: data.worktrees,
402
+ occupiedBranches: data.occupiedBranches,
403
+ };
404
+ }
405
+
406
+ function occupiedBranch(worktrees, branch) {
407
+ return worktrees.find((item) => item.branch === branch && !item.bare && !item.prunable) || null;
408
+ }
409
+
410
+ export async function createGitWorktree(cwd, request = {}) {
411
+ const branch = cleanBranchName(request.branchName || request.branch);
412
+ let data = await readWorktreeData(cwd);
413
+ await validateBranchName(data, branch);
414
+
415
+ return withMutationLock(data.commonGitDir, async () => {
416
+ data = await readWorktreeData(cwd);
417
+ const existing = occupiedBranch(data.worktrees, branch);
418
+ if (existing) {
419
+ return {
420
+ ok: true,
421
+ created: false,
422
+ openedExisting: true,
423
+ code: WORKTREE_ERROR_CODES.BRANCH_CHECKED_OUT_ELSEWHERE,
424
+ message: `Branch ${branch} is already checked out at ${existing.path}`,
425
+ branch,
426
+ ...responseBase(data, existing),
427
+ };
428
+ }
429
+
430
+ const targetPath = await resolveCreateTarget(data, branch, data.worktrees, request.path);
431
+ const exists = await branchExists(data.repoRoot, branch);
432
+ const baseRef = String(request.baseRef || "").trim();
433
+ const args = exists
434
+ ? ["worktree", "add", targetPath, branch]
435
+ : ["worktree", "add", "-b", branch, targetPath, ...(baseRef ? [baseRef] : [])];
436
+ const worktreeAddCwd = data.currentWorktreePath || data.repoRoot;
437
+
438
+ try {
439
+ await runGitMutationWithRetry(args, { cwd: worktreeAddCwd });
440
+ } catch (error) {
441
+ const refreshed = await readWorktreeData(cwd).catch(() => data);
442
+ const occupied = occupiedBranch(refreshed.worktrees || [], branch);
443
+ if (occupied) {
444
+ return {
445
+ ok: true,
446
+ created: false,
447
+ openedExisting: true,
448
+ code: WORKTREE_ERROR_CODES.BRANCH_CHECKED_OUT_ELSEWHERE,
449
+ message: `Branch ${branch} is already checked out at ${occupied.path}`,
450
+ branch,
451
+ ...responseBase(refreshed, occupied),
452
+ };
453
+ }
454
+ throw error;
455
+ }
456
+
457
+ const refreshed = await readWorktreeData(targetPath);
458
+ const created = refreshed.worktrees.find((item) => samePath(item.path, targetPath)) || occupiedBranch(refreshed.worktrees, branch);
459
+ return {
460
+ ok: true,
461
+ created: true,
462
+ openedExisting: false,
463
+ branch,
464
+ path: targetPath,
465
+ ...responseBase(refreshed, created || { path: targetPath, branch }),
466
+ };
467
+ });
468
+ }
469
+
470
+ export async function openGitWorktree(cwd, worktreePath) {
471
+ const data = await readWorktreeData(cwd);
472
+ const requested = path.resolve(data.sourceCwd || cwd, String(worktreePath || ""));
473
+ const requestedCanonical = await canonicalPath(requested);
474
+ const worktree = data.worktrees.find((item) => samePath(item.path, requestedCanonical));
475
+ if (!worktree) {
476
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.WORKTREE_NOT_FOUND, `Git worktree not found: ${requested}`, { path: requested });
477
+ }
478
+ return { ok: true, ...responseBase(data, worktree) };
479
+ }
480
+
481
+ export async function removeGitWorktree(cwd, worktreePath, { force = false } = {}) {
482
+ let data = await readWorktreeData(cwd);
483
+ const requested = path.resolve(data.sourceCwd || cwd, String(worktreePath || ""));
484
+ const requestedCanonical = await canonicalPath(requested);
485
+ const worktree = data.worktrees.find((item) => samePath(item.path, requestedCanonical));
486
+ if (!worktree) {
487
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.WORKTREE_NOT_FOUND, `Git worktree not found: ${requested}`, { path: requested });
488
+ }
489
+ if (worktree.isMainWorktree) {
490
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.IS_MAIN_WORKTREE, "Refusing to remove the main worktree", { path: worktree.path });
491
+ }
492
+
493
+ if (!force) {
494
+ const statusText = await runGit(["status", "--porcelain=v1", "--untracked-files=all"], { cwd: worktree.path, maxOutputLength: 120_000 });
495
+ if (statusText.trim()) {
496
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.DIRTY_WORKTREE, "Refusing to remove a dirty worktree without force", { path: worktree.path });
497
+ }
498
+ }
499
+
500
+ return withMutationLock(data.commonGitDir, async () => {
501
+ data = await readWorktreeData(cwd);
502
+ const fresh = data.worktrees.find((item) => samePath(item.path, requestedCanonical));
503
+ if (!fresh) return { ok: true, removed: false, path: requestedCanonical, ...responseBase(data, worktree) };
504
+ if (fresh.isMainWorktree) {
505
+ throw makeGitWorktreeError(WORKTREE_ERROR_CODES.IS_MAIN_WORKTREE, "Refusing to remove the main worktree", { path: fresh.path });
506
+ }
507
+ const args = ["worktree", "remove", ...(force ? ["--force"] : []), fresh.path];
508
+ await runGitMutationWithRetry(args, { cwd: data.repoRoot });
509
+ const refreshed = await readWorktreeData(data.repoRoot).catch(() => data);
510
+ return { ok: true, removed: true, path: fresh.path, branch: fresh.branch, ...responseBase(refreshed, fresh) };
511
+ });
512
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstpick/pi-package-webui",
3
- "version": "0.5.5",
3
+ "version": "0.5.7",
4
4
  "description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/Firstp1ck/npm-packages/tree/main/pi-package-webui#readme",
@@ -53,7 +53,7 @@
53
53
  "test": "node tests/run-all.mjs"
54
54
  },
55
55
  "dependencies": {
56
- "@earendil-works/pi-coding-agent": "^0.79.8",
56
+ "@earendil-works/pi-coding-agent": "^0.80.2",
57
57
  "mermaid": "^11.15.0"
58
58
  },
59
59
  "optionalDependencies": {
@@ -64,7 +64,7 @@
64
64
  "@firstpick/pi-extension-safety-guard": "^0.2.3",
65
65
  "@firstpick/pi-extension-setup-skills": "^0.1.8",
66
66
  "@firstpick/pi-extension-stats": "^0.2.6",
67
- "@firstpick/pi-extension-todo-progress": "^0.2.4",
67
+ "@firstpick/pi-extension-todo-progress": "^0.2.5",
68
68
  "@firstpick/pi-extension-tools": "^0.1.6",
69
69
  "@firstpick/pi-extension-workflows": "^0.1.0",
70
70
  "@firstpick/pi-package-remote-webui": "^0.1.2",
@@ -79,7 +79,7 @@
79
79
  "public",
80
80
  "images",
81
81
  "tests",
82
- "dev/docs/WEBUI_TUI_NATIVE_PARITY.json",
82
+ "lib/WEBUI_TUI_NATIVE_PARITY.json",
83
83
  "README.md",
84
84
  "LICENSE"
85
85
  ],