@narumitw/pi-worktree 0.51.2 → 0.51.3

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/dist/index.ts ADDED
@@ -0,0 +1,1893 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+
4
+ // src/command.ts
5
+ import { existsSync as existsSync4 } from "node:fs";
6
+ import { resolve as resolve2 } from "node:path";
7
+
8
+ // src/git.ts
9
+ import { spawn } from "node:child_process";
10
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
11
+ import { basename, dirname, resolve } from "node:path";
12
+ var GIT_TIMEOUT_MS = 15e3;
13
+ var GIT_MUTATION_TIMEOUT_MS = 6e4;
14
+ var LOCAL_BRANCH_PREFIX = "refs/heads/";
15
+ var GitWorktreeError = class extends Error {
16
+ args;
17
+ constructor(message, args) {
18
+ super(message);
19
+ this.name = "GitWorktreeError";
20
+ this.args = args;
21
+ }
22
+ };
23
+ function parseWorktreePorcelain(output) {
24
+ const records = [];
25
+ let current;
26
+ const finish = () => {
27
+ if (!current) return;
28
+ records.push({ ...current, isMain: records.length === 0 });
29
+ current = void 0;
30
+ };
31
+ for (const field of output.split("\0")) {
32
+ if (field === "") {
33
+ finish();
34
+ continue;
35
+ }
36
+ const separator = field.indexOf(" ");
37
+ const key = separator < 0 ? field : field.slice(0, separator);
38
+ const value = separator < 0 ? "" : field.slice(separator + 1);
39
+ if (key === "worktree") {
40
+ finish();
41
+ if (!value) throw new GitWorktreeError("Worktree porcelain record is missing path.");
42
+ current = { path: value, bare: false, detached: false };
43
+ continue;
44
+ }
45
+ if (!current) {
46
+ throw new GitWorktreeError(
47
+ `Worktree porcelain field ${JSON.stringify(key)} appears before worktree.`
48
+ );
49
+ }
50
+ switch (key) {
51
+ case "HEAD":
52
+ current.head = value;
53
+ break;
54
+ case "branch":
55
+ current.branchRef = value;
56
+ current.branch = value.startsWith(LOCAL_BRANCH_PREFIX) ? value.slice(LOCAL_BRANCH_PREFIX.length) : void 0;
57
+ break;
58
+ case "bare":
59
+ current.bare = true;
60
+ break;
61
+ case "detached":
62
+ current.detached = true;
63
+ break;
64
+ case "locked":
65
+ current.lockedReason = value;
66
+ break;
67
+ case "prunable":
68
+ current.prunableReason = value;
69
+ break;
70
+ }
71
+ }
72
+ finish();
73
+ return records;
74
+ }
75
+ function worktreeForBranch(records, branch) {
76
+ const branchRef = `${LOCAL_BRANCH_PREFIX}${branch}`;
77
+ return records.find((record) => record.branchRef === branchRef);
78
+ }
79
+ function defaultWorktreePath(mainWorktreePath, branch, worktreeRoot) {
80
+ return resolve(worktreeRoot, basename(mainWorktreePath), branch.replaceAll("/", "-"));
81
+ }
82
+ function buildAddArguments(input) {
83
+ return input.startOid ? ["worktree", "add", "-b", input.branch, input.path, input.startOid] : ["worktree", "add", input.path, input.branch];
84
+ }
85
+ function pathIdentity(path) {
86
+ const absolute = resolve(path);
87
+ if (!existsSync(absolute)) return absolute;
88
+ try {
89
+ return realpathSync.native(absolute);
90
+ } catch {
91
+ return absolute;
92
+ }
93
+ }
94
+ function pathEntryExists(path) {
95
+ try {
96
+ lstatSync(path);
97
+ return true;
98
+ } catch (error) {
99
+ if (isNodeError(error) && error.code === "ENOENT") return false;
100
+ throw new GitWorktreeError(`Cannot inspect filesystem path ${path}: ${formatError(error)}`);
101
+ }
102
+ }
103
+ function unresolvableSymlinkAncestor(path) {
104
+ let current = dirname(resolve(path));
105
+ while (true) {
106
+ try {
107
+ const stat = lstatSync(current);
108
+ if (!stat.isSymbolicLink()) return void 0;
109
+ try {
110
+ realpathSync.native(current);
111
+ return void 0;
112
+ } catch (error) {
113
+ if (isNodeError(error) && (error.code === "ENOENT" || error.code === "ELOOP")) {
114
+ return current;
115
+ }
116
+ throw new GitWorktreeError(
117
+ `Cannot resolve filesystem ancestor ${current}: ${formatError(error)}`
118
+ );
119
+ }
120
+ } catch (error) {
121
+ if (!isNodeError(error) || error.code !== "ENOENT") {
122
+ if (error instanceof GitWorktreeError) throw error;
123
+ throw new GitWorktreeError(
124
+ `Cannot inspect filesystem ancestor ${current}: ${formatError(error)}`
125
+ );
126
+ }
127
+ const parent = dirname(current);
128
+ if (parent === current) return void 0;
129
+ current = parent;
130
+ }
131
+ }
132
+ }
133
+ function pathsEqual(left, right) {
134
+ return pathIdentity(left) === pathIdentity(right);
135
+ }
136
+ function sameWorktreeIdentity(left, right) {
137
+ return pathsEqual(left.path, right.path) && left.head === right.head && left.branchRef === right.branchRef && left.detached === right.detached && left.isMain === right.isMain && left.bare === right.bare;
138
+ }
139
+ async function listWorktrees(pi, cwd, signal) {
140
+ const result = await runGit(pi, ["worktree", "list", "--porcelain", "-z"], cwd, signal);
141
+ return parseWorktreePorcelain(result.stdout);
142
+ }
143
+ async function currentWorktreePath(pi, cwd, signal) {
144
+ const result = await runGit(pi, ["rev-parse", "--show-toplevel"], cwd, signal);
145
+ const path = removeLineEnding(result.stdout);
146
+ if (!path) throw new GitWorktreeError("Git did not return the current worktree path.");
147
+ return pathIdentity(path);
148
+ }
149
+ async function symbolicBranch(pi, cwd, signal) {
150
+ const result = await runGitAllowFailure(
151
+ pi,
152
+ ["symbolic-ref", "--quiet", "--short", "HEAD"],
153
+ cwd,
154
+ signal
155
+ );
156
+ if (result.killed) throw killedError(["symbolic-ref", "--quiet", "--short", "HEAD"]);
157
+ if (result.code !== 0) return void 0;
158
+ return result.stdout.trim() || void 0;
159
+ }
160
+ async function validateBranch(pi, cwd, branch, signal) {
161
+ const result = await runGit(pi, ["check-ref-format", "--branch", branch], cwd, signal);
162
+ const normalized = result.stdout.trim();
163
+ if (!normalized) throw new GitWorktreeError("Git returned an empty branch name.");
164
+ return normalized;
165
+ }
166
+ async function localBranchExists(pi, cwd, branch, signal) {
167
+ const result = await runGitAllowFailure(
168
+ pi,
169
+ ["show-ref", "--verify", "--quiet", `${LOCAL_BRANCH_PREFIX}${branch}`],
170
+ cwd,
171
+ signal
172
+ );
173
+ if (result.killed) throw killedError(["show-ref", "--verify", "--quiet"]);
174
+ if (result.code === 0) return true;
175
+ if (result.code === 1) return false;
176
+ throw gitFailure(["show-ref", "--verify", "--quiet"], result);
177
+ }
178
+ async function resolveCommit(pi, cwd, startPoint, signal) {
179
+ const result = await runGit(
180
+ pi,
181
+ ["rev-parse", "--verify", "--end-of-options", `${startPoint}^{commit}`],
182
+ cwd,
183
+ signal
184
+ );
185
+ const oid = result.stdout.trim();
186
+ if (!/^[0-9a-fA-F]{40,64}$/u.test(oid)) {
187
+ throw new GitWorktreeError(`Git returned an invalid commit object for ${startPoint}.`);
188
+ }
189
+ return oid;
190
+ }
191
+ async function addWorktree(pi, cwd, input, signal) {
192
+ await runGit(pi, buildAddArguments(input), cwd, signal, GIT_MUTATION_TIMEOUT_MS);
193
+ }
194
+ async function removeWorktree(pi, cwd, path, signal) {
195
+ await runGit(pi, ["worktree", "remove", path], cwd, signal, GIT_MUTATION_TIMEOUT_MS);
196
+ }
197
+ async function worktreeInventory(pi, path, signal) {
198
+ const statusArgs = [
199
+ "status",
200
+ "--porcelain=v1",
201
+ "--untracked-files=all",
202
+ "--ignored=matching",
203
+ "--ignore-submodules=none"
204
+ ];
205
+ const status = await runGit(pi, statusArgs, path, signal);
206
+ const indexFlags = await runGit(pi, ["ls-files", "-v", "-z"], path, signal);
207
+ const indexInventory = await indexFlagInventory(pi, indexFlags.stdout, path, signal);
208
+ const submoduleStatus = await runGit(pi, ["submodule", "status", "--recursive"], path, signal);
209
+ const initializedSubmodules = nonEmptyLines(submoduleStatus.stdout).filter((line) => !line.startsWith("-")).map((line) => `initialized submodule: ${line.slice(1).trimStart()}`);
210
+ const submodules = await runGit(
211
+ pi,
212
+ [
213
+ "submodule",
214
+ "foreach",
215
+ "--recursive",
216
+ "--quiet",
217
+ "git status --porcelain=v1 --untracked-files=all --ignored=matching --ignore-submodules=none"
218
+ ],
219
+ path,
220
+ signal
221
+ );
222
+ return [
223
+ ...nonEmptyLines(status.stdout),
224
+ ...indexInventory,
225
+ ...initializedSubmodules,
226
+ ...nonEmptyLines(submodules.stdout)
227
+ ];
228
+ }
229
+ async function worktreeAdministrativeDirectory(pi, cwd, signal) {
230
+ const result = await runGit(
231
+ pi,
232
+ ["rev-parse", "--path-format=absolute", "--git-dir"],
233
+ cwd,
234
+ signal
235
+ );
236
+ const value = removeLineEnding(result.stdout);
237
+ if (!value) throw new GitWorktreeError("Git did not return its worktree administrative path.");
238
+ return resolve(cwd, value);
239
+ }
240
+ async function administrativeHistoryOids(pi, cwd, administrativePath, signal) {
241
+ const gitDirArgument = `--git-dir=${administrativePath}`;
242
+ const values = readAdministrativeReflogOids(resolve(administrativePath, "logs"));
243
+ const refs = await runGit(
244
+ pi,
245
+ [gitDirArgument, "for-each-ref", "--format=%(objectname)", "refs/worktree", "refs/bisect"],
246
+ cwd,
247
+ signal
248
+ );
249
+ values.push(...splitAdministrativeOids(refs.stdout, "per-worktree refs"));
250
+ for (const name of [
251
+ "ORIG_HEAD",
252
+ "MERGE_HEAD",
253
+ "REBASE_HEAD",
254
+ "CHERRY_PICK_HEAD",
255
+ "REVERT_HEAD",
256
+ "BISECT_HEAD"
257
+ ]) {
258
+ const contents = readAdministrativeFile(administrativePath, name);
259
+ if (contents === void 0) continue;
260
+ values.push(...splitAdministrativeOids(contents, name));
261
+ }
262
+ const fetchHead = readAdministrativeFile(administrativePath, "FETCH_HEAD");
263
+ if (fetchHead !== void 0) {
264
+ values.push(...splitFetchHeadOids(fetchHead));
265
+ }
266
+ return [...new Set(values)];
267
+ }
268
+ async function administrativePruneCandidates(pi, cwd, signal) {
269
+ const commonResult = await runGit(
270
+ pi,
271
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
272
+ cwd,
273
+ signal
274
+ );
275
+ const commonValue = removeLineEnding(commonResult.stdout);
276
+ if (!commonValue) throw new GitWorktreeError("Git did not return its common directory.");
277
+ const commonDirectory = resolve(cwd, commonValue);
278
+ const administrativeRoot = resolve(commonDirectory, "worktrees");
279
+ if (!existsSync(administrativeRoot)) return [];
280
+ const candidates = [];
281
+ for (const entry of readdirSync(administrativeRoot, { withFileTypes: true })) {
282
+ const administrativePath = resolve(administrativeRoot, entry.name);
283
+ if (!entry.isDirectory() || entry.isSymbolicLink()) {
284
+ throw new GitWorktreeError(
285
+ `Unexpected Git worktree administrative entry: ${administrativePath}.`
286
+ );
287
+ }
288
+ if (existsSync(resolve(administrativePath, "locked"))) continue;
289
+ const gitdirPath = resolve(administrativePath, "gitdir");
290
+ let registeredGitFile;
291
+ try {
292
+ registeredGitFile = removeLineEnding(readFileSync(gitdirPath, "utf8"));
293
+ } catch (error) {
294
+ if (!isNodeError(error) || error.code !== "ENOENT") throw error;
295
+ }
296
+ if (registeredGitFile) {
297
+ const targetGitFile = resolve(administrativePath, registeredGitFile);
298
+ if (existsSync(targetGitFile)) continue;
299
+ }
300
+ const headPath = resolve(administrativePath, "HEAD");
301
+ let headValue;
302
+ try {
303
+ if (!lstatSync(headPath).isFile()) {
304
+ throw new GitWorktreeError(`Git worktree administrative HEAD is not a file: ${headPath}.`);
305
+ }
306
+ headValue = removeLineEnding(readFileSync(headPath, "utf8"));
307
+ } catch (error) {
308
+ if (error instanceof GitWorktreeError) throw error;
309
+ throw new GitWorktreeError(
310
+ `Cannot inspect Git worktree administrative HEAD ${headPath}: ${formatError(error)}`
311
+ );
312
+ }
313
+ const indexDirty = await administrativeIndexIsDirty(pi, cwd, administrativePath, signal);
314
+ if (headValue.startsWith("ref: ")) {
315
+ const branchRef = headValue.slice("ref: ".length);
316
+ if (!branchRef) {
317
+ throw new GitWorktreeError(
318
+ `Git worktree administrative HEAD has an empty ref: ${headPath}.`
319
+ );
320
+ }
321
+ candidates.push({
322
+ id: entry.name,
323
+ administrativePath,
324
+ branchRef,
325
+ indexDirty
326
+ });
327
+ continue;
328
+ }
329
+ if (!/^[0-9a-fA-F]{40,64}$/u.test(headValue)) {
330
+ throw new GitWorktreeError(`Git worktree administrative HEAD is malformed: ${headPath}.`);
331
+ }
332
+ candidates.push({
333
+ id: entry.name,
334
+ administrativePath,
335
+ head: headValue,
336
+ indexDirty
337
+ });
338
+ }
339
+ return candidates;
340
+ }
341
+ async function administrativeIndexIsDirty(pi, cwd, administrativePath, signal) {
342
+ const args = [
343
+ `--git-dir=${administrativePath}`,
344
+ "diff",
345
+ "--cached",
346
+ "--quiet",
347
+ "--no-ext-diff",
348
+ "--no-textconv",
349
+ "--ignore-submodules=none",
350
+ "--"
351
+ ];
352
+ const result = await runGitAllowFailure(pi, args, cwd, signal);
353
+ if (result.killed) throw killedError(args);
354
+ if (result.code === 0) return false;
355
+ if (result.code === 1) return true;
356
+ throw gitFailure(args, result);
357
+ }
358
+ async function durableRefExists(pi, cwd, ref, signal) {
359
+ if (!ref.startsWith("refs/") || ref.includes("\0")) {
360
+ throw new GitWorktreeError("Git worktree administrative HEAD contains an invalid ref.");
361
+ }
362
+ const result = await runGitAllowFailure(
363
+ pi,
364
+ ["show-ref", "--verify", "--quiet", ref],
365
+ cwd,
366
+ signal
367
+ );
368
+ if (result.killed) throw killedError(["show-ref", "--verify", "--quiet"]);
369
+ if (result.code === 0) return true;
370
+ if (result.code === 1) return false;
371
+ throw gitFailure(["show-ref", "--verify", "--quiet"], result);
372
+ }
373
+ async function durableRefsContaining(pi, cwd, head, signal) {
374
+ if (!/^[0-9a-fA-F]{40,64}$/u.test(head)) {
375
+ throw new GitWorktreeError("Detached worktree has an invalid HEAD object.");
376
+ }
377
+ const result = await runGit(
378
+ pi,
379
+ [
380
+ "for-each-ref",
381
+ "--format=%(refname)",
382
+ `--contains=${head}`,
383
+ "refs/heads",
384
+ "refs/tags",
385
+ "refs/remotes"
386
+ ],
387
+ cwd,
388
+ signal
389
+ );
390
+ return nonEmptyLines(result.stdout);
391
+ }
392
+ async function prunePreview(pi, cwd, signal) {
393
+ const result = await runGit(pi, ["worktree", "prune", "--dry-run", "--verbose"], cwd, signal);
394
+ return combineOutput(result);
395
+ }
396
+ async function pruneWorktrees(pi, cwd, signal) {
397
+ const result = await runGit(
398
+ pi,
399
+ ["worktree", "prune", "--verbose"],
400
+ cwd,
401
+ signal,
402
+ GIT_MUTATION_TIMEOUT_MS
403
+ );
404
+ return combineOutput(result);
405
+ }
406
+ function formatWorktree(record, currentPath) {
407
+ const labels = [
408
+ currentPath && pathsEqual(record.path, currentPath) ? "current" : void 0,
409
+ record.isMain ? "main" : void 0,
410
+ record.bare ? "bare" : void 0,
411
+ record.detached ? "detached" : record.branch,
412
+ record.lockedReason !== void 0 ? `locked${record.lockedReason ? `: ${record.lockedReason}` : ""}` : void 0,
413
+ record.prunableReason !== void 0 ? `prunable${record.prunableReason ? `: ${record.prunableReason}` : ""}` : void 0
414
+ ].filter((label) => Boolean(label));
415
+ const head = record.head ? record.head.slice(0, 8) : "no HEAD";
416
+ return stripTerminalControls(`${record.path} [${labels.join(", ") || "unknown"}] ${head}`);
417
+ }
418
+ function stripTerminalControls(value) {
419
+ return [...value].filter((character) => {
420
+ const code = character.codePointAt(0) ?? 0;
421
+ return code > 31 && (code < 127 || code > 159);
422
+ }).join("");
423
+ }
424
+ async function runGit(pi, args, cwd, signal, timeout = GIT_TIMEOUT_MS) {
425
+ const result = await runGitAllowFailure(pi, args, cwd, signal, timeout);
426
+ if (result.killed) throw killedError(args);
427
+ if (result.code !== 0) throw gitFailure(args, result);
428
+ return result;
429
+ }
430
+ async function runGitAllowFailure(pi, args, cwd, signal, timeout = GIT_TIMEOUT_MS) {
431
+ try {
432
+ return await pi.exec("git", args, { cwd, signal, timeout });
433
+ } catch (error) {
434
+ const message = formatError(error);
435
+ if (/\bENOENT\b|not found/i.test(message)) {
436
+ throw new GitWorktreeError("Git executable was not found. Install Git and retry.", args);
437
+ }
438
+ throw new GitWorktreeError(
439
+ `Could not start git ${args.slice(0, 2).join(" ")}: ${message}`,
440
+ args
441
+ );
442
+ }
443
+ }
444
+ function gitFailure(args, result) {
445
+ const detail = stripTerminalControls(
446
+ [result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n")
447
+ );
448
+ const hint = /not a git repository/i.test(detail) ? "The current Pi workspace is not inside a Git repository." : detail || `Git exited with code ${result.code}.`;
449
+ return new GitWorktreeError(`git ${args.slice(0, 2).join(" ")} failed: ${hint}`, args);
450
+ }
451
+ function killedError(args) {
452
+ return new GitWorktreeError(
453
+ `git ${args.slice(0, 2).join(" ")} timed out or was cancelled.`,
454
+ args
455
+ );
456
+ }
457
+ function nonEmptyLines(value) {
458
+ return value.split(/\r?\n/u).filter((line) => line.length > 0);
459
+ }
460
+ async function indexFlagInventory(pi, value, cwd, signal) {
461
+ const entries = parseIndexFlagEntries(value);
462
+ const sparseManagedPaths = await sparseManagedSkipWorktreePaths(
463
+ pi,
464
+ cwd,
465
+ entries.filter((entry) => entry.skipWorktree).map((entry) => entry.path),
466
+ signal
467
+ );
468
+ const inventory = [];
469
+ for (const entry of entries) {
470
+ const flags = [
471
+ entry.skipWorktree && !sparseManagedPaths.has(entry.path) ? "skip-worktree" : void 0,
472
+ entry.assumeUnchanged ? "assume-unchanged" : void 0
473
+ ].filter((flag) => flag !== void 0);
474
+ if (flags.length > 0) inventory.push(`index flag ${flags.join("+")}: ${entry.path}`);
475
+ }
476
+ return inventory;
477
+ }
478
+ function parseIndexFlagEntries(value) {
479
+ const entries = [];
480
+ for (const entry of value.split("\0")) {
481
+ if (!entry) continue;
482
+ if (entry.length < 3 || entry[1] !== " ") {
483
+ throw new GitWorktreeError("Git returned malformed ls-files index-flag output.");
484
+ }
485
+ const tag = entry[0] ?? "";
486
+ const skipWorktree = tag.toUpperCase() === "S";
487
+ const assumeUnchanged = /[a-z]/u.test(tag);
488
+ if (skipWorktree || assumeUnchanged) {
489
+ entries.push({ path: entry.slice(2), skipWorktree, assumeUnchanged });
490
+ }
491
+ }
492
+ return entries;
493
+ }
494
+ async function sparseManagedSkipWorktreePaths(pi, cwd, paths, signal) {
495
+ if (paths.length === 0) return /* @__PURE__ */ new Set();
496
+ const configArgs = ["config", "--bool", "--get", "core.sparseCheckout"];
497
+ const config = await runGitAllowFailure(pi, configArgs, cwd, signal);
498
+ if (config.killed) throw killedError(configArgs);
499
+ if (config.code !== 0 || config.stdout.trim() !== "true") return /* @__PURE__ */ new Set();
500
+ const candidates = new Set(paths);
501
+ const checkArgs = ["sparse-checkout", "check-rules", "-z"];
502
+ const checked = await runGitWithInputAllowFailure(
503
+ checkArgs,
504
+ cwd,
505
+ `${[...candidates].join("\0")}\0`,
506
+ signal
507
+ );
508
+ if (checked.killed) throw killedError(checkArgs);
509
+ if (checked.code !== 0) return /* @__PURE__ */ new Set();
510
+ const included = new Set(nulSeparatedPaths(checked.stdout, "sparse-checkout rules"));
511
+ if ([...included].some((path) => !candidates.has(path))) {
512
+ throw new GitWorktreeError("Git returned an unexpected sparse-checkout path.");
513
+ }
514
+ return new Set([...candidates].filter((path) => !included.has(path)));
515
+ }
516
+ function runGitWithInputAllowFailure(args, cwd, input, signal, timeout = GIT_TIMEOUT_MS) {
517
+ if (signal?.aborted) {
518
+ return Promise.resolve({ stdout: "", stderr: "", code: 1, killed: true });
519
+ }
520
+ return new Promise((resolveResult, reject) => {
521
+ const child = spawn("git", args, { cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
522
+ let stdout = "";
523
+ let stderr = "";
524
+ let killed = false;
525
+ let settled = false;
526
+ const finish = (result) => {
527
+ if (settled) return;
528
+ settled = true;
529
+ clearTimeout(timeoutHandle);
530
+ signal?.removeEventListener("abort", stop);
531
+ resolveResult(result);
532
+ };
533
+ const fail = (error) => {
534
+ if (settled) return;
535
+ settled = true;
536
+ clearTimeout(timeoutHandle);
537
+ signal?.removeEventListener("abort", stop);
538
+ child.kill();
539
+ const message = formatError(error);
540
+ reject(
541
+ /\bENOENT\b|not found/i.test(message) ? new GitWorktreeError("Git executable was not found. Install Git and retry.", args) : new GitWorktreeError(
542
+ `Could not start git ${args.slice(0, 2).join(" ")}: ${message}`,
543
+ args
544
+ )
545
+ );
546
+ };
547
+ const stop = () => {
548
+ killed = true;
549
+ child.kill();
550
+ };
551
+ const timeoutHandle = setTimeout(stop, timeout);
552
+ child.stdout.setEncoding("utf8");
553
+ child.stderr.setEncoding("utf8");
554
+ child.stdout.on("data", (chunk) => {
555
+ stdout += chunk;
556
+ });
557
+ child.stderr.on("data", (chunk) => {
558
+ stderr += chunk;
559
+ });
560
+ child.stdin.on("error", (error) => {
561
+ if (!isNodeError(error) || error.code !== "EPIPE") fail(error);
562
+ });
563
+ child.once("error", fail);
564
+ child.once("close", (code, closeSignal) => {
565
+ finish({ stdout, stderr, code: code ?? 1, killed: killed || closeSignal !== null });
566
+ });
567
+ signal?.addEventListener("abort", stop, { once: true });
568
+ if (signal?.aborted) stop();
569
+ child.stdin.end(input);
570
+ });
571
+ }
572
+ function nulSeparatedPaths(value, source) {
573
+ if (value && !value.endsWith("\0")) {
574
+ throw new GitWorktreeError(`Git returned malformed ${source} output.`);
575
+ }
576
+ return value.split("\0").filter(Boolean);
577
+ }
578
+ function combineOutput(result) {
579
+ return [result.stdout.trimEnd(), result.stderr.trimEnd()].filter(Boolean).join("\n");
580
+ }
581
+ function removeLineEnding(value) {
582
+ if (value.endsWith("\r\n")) return value.slice(0, -2);
583
+ if (value.endsWith("\n")) return value.slice(0, -1);
584
+ return value;
585
+ }
586
+ function splitAdministrativeOids(value, source) {
587
+ const normalized = value.endsWith("\n") ? value.slice(0, -1) : value;
588
+ if (!normalized) return [];
589
+ const values = normalized.split("\n").map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
590
+ if (values.some((oid) => !/^[0-9a-fA-F]{40,64}$/u.test(oid))) {
591
+ throw new GitWorktreeError(`Git returned malformed object IDs for ${source}.`);
592
+ }
593
+ return values;
594
+ }
595
+ function splitFetchHeadOids(value) {
596
+ const normalized = value.endsWith("\n") ? value.slice(0, -1) : value;
597
+ if (!normalized) return [];
598
+ return normalized.split("\n").map((line) => {
599
+ const match = /^([0-9a-fA-F]{40,64})\t/u.exec(line);
600
+ if (!match?.[1]) {
601
+ throw new GitWorktreeError("Git worktree administrative FETCH_HEAD is malformed.");
602
+ }
603
+ return match[1];
604
+ });
605
+ }
606
+ function readAdministrativeFile(administrativePath, name) {
607
+ const path = resolve(administrativePath, name);
608
+ let stat;
609
+ try {
610
+ stat = lstatSync(path);
611
+ } catch (error) {
612
+ if (isNodeError(error) && error.code === "ENOENT") return void 0;
613
+ throw new GitWorktreeError(
614
+ `Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`
615
+ );
616
+ }
617
+ if (stat.isSymbolicLink() || !stat.isFile()) {
618
+ throw new GitWorktreeError(
619
+ `Git worktree administrative ${name} must be a regular file: ${path}.`
620
+ );
621
+ }
622
+ try {
623
+ return readFileSync(path, "utf8");
624
+ } catch (error) {
625
+ throw new GitWorktreeError(
626
+ `Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`
627
+ );
628
+ }
629
+ }
630
+ function readAdministrativeReflogOids(logPath) {
631
+ if (!existsSync(logPath)) return [];
632
+ let stat;
633
+ try {
634
+ stat = lstatSync(logPath);
635
+ } catch (error) {
636
+ throw new GitWorktreeError(`Cannot inspect Git reflog path ${logPath}: ${formatError(error)}`);
637
+ }
638
+ if (stat.isSymbolicLink()) {
639
+ throw new GitWorktreeError(`Git reflog path must not be a symbolic link: ${logPath}.`);
640
+ }
641
+ if (stat.isDirectory()) {
642
+ const values2 = [];
643
+ for (const entry of readdirSync(logPath, { withFileTypes: true })) {
644
+ values2.push(...readAdministrativeReflogOids(resolve(logPath, entry.name)));
645
+ }
646
+ return values2;
647
+ }
648
+ if (!stat.isFile()) {
649
+ throw new GitWorktreeError(`Unexpected Git reflog entry type: ${logPath}.`);
650
+ }
651
+ let contents;
652
+ try {
653
+ contents = readFileSync(logPath, "utf8");
654
+ } catch (error) {
655
+ throw new GitWorktreeError(`Cannot read Git reflog ${logPath}: ${formatError(error)}`);
656
+ }
657
+ const normalized = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
658
+ if (!normalized) return [];
659
+ const values = [];
660
+ for (const line of normalized.split("\n")) {
661
+ const match = /^([0-9a-fA-F]{40,64}) ([0-9a-fA-F]{40,64}) /u.exec(line);
662
+ if (!match?.[1] || !match[2] || match[1].length !== match[2].length) {
663
+ throw new GitWorktreeError(`Git worktree reflog is malformed: ${logPath}.`);
664
+ }
665
+ for (const oid of [match[1], match[2]]) {
666
+ if (!/^0+$/u.test(oid)) values.push(oid);
667
+ }
668
+ }
669
+ return values;
670
+ }
671
+ function isNodeError(error) {
672
+ return error instanceof Error && "code" in error;
673
+ }
674
+ function formatError(error) {
675
+ return error instanceof Error ? error.message : String(error);
676
+ }
677
+
678
+ // src/session.ts
679
+ import { existsSync as existsSync2, writeFileSync } from "node:fs";
680
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
681
+ async function switchToWorktree(ctx, targetPath) {
682
+ let sessionPath;
683
+ try {
684
+ sessionPath = createTargetSession(ctx, targetPath);
685
+ const result = await ctx.switchSession(sessionPath, {
686
+ withSession: async (replacementCtx) => {
687
+ replacementCtx.ui.notify(
688
+ stripTerminalControls(`Switched Pi workspace to ${targetPath}.`),
689
+ "info"
690
+ );
691
+ }
692
+ });
693
+ if (result.cancelled) {
694
+ ctx.ui.notify(
695
+ stripTerminalControls(
696
+ `Workspace switch was cancelled. The prepared target session was retained at ${sessionPath}.`
697
+ ),
698
+ "info"
699
+ );
700
+ return "cancelled";
701
+ }
702
+ return "switched";
703
+ } catch (error) {
704
+ const retained = sessionPath ? " The prepared target session was retained." : "";
705
+ const message = stripTerminalControls(
706
+ `Could not switch Pi workspace to ${targetPath}.${retained} The worktree was retained. Retry from /worktree. ${formatError2(error)}`
707
+ );
708
+ try {
709
+ ctx.ui.notify(message, "error");
710
+ } catch {
711
+ console.error(message);
712
+ }
713
+ return "failed";
714
+ }
715
+ }
716
+ function createTargetSession(ctx, targetPath) {
717
+ const sourceFile = ctx.sessionManager.getSessionFile();
718
+ if (sourceFile && existsSync2(sourceFile)) {
719
+ const persisted = SessionManager.open(sourceFile);
720
+ const activeLeaf = ctx.sessionManager.getLeafId();
721
+ if (persisted.getLeafId() === activeLeaf) {
722
+ const forked = SessionManager.forkFrom(sourceFile, targetPath);
723
+ const targetFile = forked.getSessionFile();
724
+ if (!targetFile || !existsSync2(targetFile)) {
725
+ throw new Error("Pi did not create the target worktree session file.");
726
+ }
727
+ return targetFile;
728
+ }
729
+ if (activeLeaf !== null && !persisted.getEntry(activeLeaf)) {
730
+ throw new Error("The active Pi session branch is not present in the persisted source file.");
731
+ }
732
+ return writeTargetSession(targetPath, ctx.sessionManager.getBranch(), sourceFile, activeLeaf);
733
+ }
734
+ if (ctx.sessionManager.getEntries().length > 0) {
735
+ return writeTargetSession(
736
+ targetPath,
737
+ ctx.sessionManager.getBranch(),
738
+ void 0,
739
+ ctx.sessionManager.getLeafId()
740
+ );
741
+ }
742
+ return writeTargetSession(targetPath, [], void 0, null);
743
+ }
744
+ function writeTargetSession(targetPath, entries, parentSession, expectedLeaf) {
745
+ const target = SessionManager.create(targetPath, void 0, { parentSession });
746
+ const targetFile = target.getSessionFile();
747
+ const header = target.getHeader();
748
+ if (!targetFile || !header) throw new Error("Pi could not prepare a target session.");
749
+ const document = [header, ...entries].map((entry) => JSON.stringify(entry)).join("\n");
750
+ writeFileSync(targetFile, `${document}
751
+ `, {
752
+ encoding: "utf8",
753
+ flag: "wx",
754
+ mode: 384
755
+ });
756
+ const verified = SessionManager.open(targetFile);
757
+ if (verified.getCwd() !== targetPath || verified.getLeafId() !== expectedLeaf) {
758
+ throw new Error("Pi could not verify the target session cwd and active branch.");
759
+ }
760
+ return targetFile;
761
+ }
762
+ function formatError2(error) {
763
+ return error instanceof Error ? error.message : String(error);
764
+ }
765
+
766
+ // src/status.ts
767
+ import { existsSync as existsSync3 } from "node:fs";
768
+ var GIT_STATUS_TIMEOUT_MS = 15e3;
769
+ var DEFAULT_STATUS_CONCURRENCY = 4;
770
+ var OID_PATTERN = /^[0-9a-fA-F]{40,64}$/u;
771
+ var STATUS_XY_PATTERN = /^[.MADRCUT]{2}$/u;
772
+ function parseWorktreeStatusPorcelain(output) {
773
+ if (output && !output.endsWith("\0")) {
774
+ throw new Error("Git status porcelain output is not NUL-terminated.");
775
+ }
776
+ const entries = output ? output.slice(0, -1).split("\0") : [];
777
+ const snapshot = {
778
+ detached: false,
779
+ staged: 0,
780
+ unstaged: 0,
781
+ untracked: 0,
782
+ conflicts: 0
783
+ };
784
+ for (let index = 0; index < entries.length; index += 1) {
785
+ const entry = entries[index] ?? "";
786
+ if (entry.startsWith("# ")) {
787
+ parseBranchHeader(snapshot, entry);
788
+ continue;
789
+ }
790
+ if (entry.startsWith("1 ")) {
791
+ assertFieldCount(entry, 9, "ordinary");
792
+ countTrackedState(snapshot, statusCode(entry));
793
+ continue;
794
+ }
795
+ if (entry.startsWith("2 ")) {
796
+ assertFieldCount(entry, 10, "renamed");
797
+ countTrackedState(snapshot, statusCode(entry));
798
+ const originalPath = entries[index + 1];
799
+ if (!originalPath) throw new Error("Git status returned a malformed renamed record.");
800
+ index += 1;
801
+ continue;
802
+ }
803
+ if (entry.startsWith("u ")) {
804
+ assertFieldCount(entry, 11, "unmerged");
805
+ statusCode(entry);
806
+ snapshot.conflicts += 1;
807
+ continue;
808
+ }
809
+ if (entry.startsWith("? ")) {
810
+ if (entry.length === 2) throw new Error("Git status returned a malformed untracked record.");
811
+ snapshot.untracked += 1;
812
+ continue;
813
+ }
814
+ if (entry.startsWith("! ")) continue;
815
+ throw new Error("Git status returned an unknown porcelain-v2 record.");
816
+ }
817
+ return snapshot;
818
+ }
819
+ function formatWorktreeStatusCard(record, currentPath, result) {
820
+ const path = safeDisplay(record.path);
821
+ const identity = [
822
+ pathsEqual(record.path, currentPath) ? "current" : void 0,
823
+ record.isMain ? "main" : void 0,
824
+ record.bare ? "bare" : void 0,
825
+ record.detached ? "detached" : void 0
826
+ ].filter((value) => value !== void 0);
827
+ const label = safeDisplay(
828
+ record.branch ?? (record.detached ? `Detached ${record.head?.slice(0, 8) ?? "HEAD"}` : record.bare ? "Bare worktree" : "Unknown worktree")
829
+ );
830
+ const statePrefix = identity.length > 0 ? `${identity.join(" \xB7 ")} \xB7 ` : "";
831
+ const baseDetails = [
832
+ `Path: ${path}`,
833
+ `Identity: ${identity.join(" \xB7 ") || "linked"}`,
834
+ `Registered HEAD: ${safeDisplay(record.head ?? "unavailable")}`
835
+ ];
836
+ if (record.lockedReason !== void 0) {
837
+ baseDetails.push(
838
+ record.lockedReason ? `Locked: ${safeDisplay(record.lockedReason)}` : "Locked: no reason provided"
839
+ );
840
+ }
841
+ if (record.prunableReason !== void 0) {
842
+ baseDetails.push(
843
+ record.prunableReason ? `Prunable: ${safeDisplay(record.prunableReason)}` : "Prunable: no reason provided"
844
+ );
845
+ }
846
+ if (result.kind === "unavailable") {
847
+ const reason = safeDisplay(result.reason);
848
+ return {
849
+ id: record.path,
850
+ label,
851
+ description: path,
852
+ statusText: `${statePrefix}unavailable`,
853
+ searchText: `${label} ${path} ${identity.join(" ")} unavailable ${reason}`,
854
+ details: [
855
+ ...baseDetails,
856
+ `Status: ${reason}`,
857
+ "Snapshot: local Git state; no fetch performed."
858
+ ]
859
+ };
860
+ }
861
+ const { snapshot, lastCommit } = result;
862
+ const workingState = formatWorkingState(snapshot);
863
+ const upstream = snapshot.upstream ? snapshot.ahead !== void 0 && snapshot.behind !== void 0 ? `${safeDisplay(snapshot.upstream)} \xB7 ahead ${snapshot.ahead} \xB7 behind ${snapshot.behind}` : `${safeDisplay(snapshot.upstream)} \xB7 ahead/behind unavailable` : "not configured; ahead/behind unavailable";
864
+ const details = [
865
+ ...baseDetails,
866
+ `Snapshot HEAD: ${safeDisplay(snapshot.headOid ?? "unborn")}`,
867
+ `Working tree: ${workingState}`,
868
+ `Upstream: ${upstream}`,
869
+ lastCommit ? `Last commit: ${safeDisplay(lastCommit.committedAt)} \xB7 ${safeDisplay(lastCommit.subject || "(no subject)")}` : "Last commit: unavailable",
870
+ "Snapshot: local Git state; no fetch performed; removal uses stricter checks."
871
+ ];
872
+ return {
873
+ id: record.path,
874
+ label,
875
+ description: path,
876
+ statusText: `${statePrefix}${workingState}`,
877
+ searchText: `${label} ${path} ${identity.join(" ")} ${workingState} ${safeDisplay(snapshot.upstream ?? "")}`,
878
+ details
879
+ };
880
+ }
881
+ async function loadWorktreeStatusCards(pi, records, currentPath, signal, options = {}) {
882
+ const concurrency = Math.max(
883
+ 1,
884
+ Math.min(options.concurrency ?? DEFAULT_STATUS_CONCURRENCY, records.length || 1)
885
+ );
886
+ const cards = new Array(records.length);
887
+ let nextIndex = 0;
888
+ const worker = async () => {
889
+ while (true) {
890
+ throwIfAborted(signal);
891
+ const index = nextIndex;
892
+ if (index >= records.length) return;
893
+ nextIndex += 1;
894
+ const record = records[index];
895
+ if (!record) return;
896
+ const unavailable = unavailableReason(record);
897
+ if (unavailable) {
898
+ cards[index] = formatWorktreeStatusCard(record, currentPath, {
899
+ kind: "unavailable",
900
+ reason: unavailable
901
+ });
902
+ continue;
903
+ }
904
+ try {
905
+ const status = await runGit2(
906
+ pi,
907
+ [
908
+ "status",
909
+ "--porcelain=v2",
910
+ "--branch",
911
+ "-z",
912
+ "--untracked-files=all",
913
+ "--ignore-submodules=none"
914
+ ],
915
+ record.path,
916
+ signal
917
+ );
918
+ const snapshot = parseWorktreeStatusPorcelain(status.stdout);
919
+ const lastCommit = snapshot.headOid ? parseLastCommit(
920
+ (await runGit2(
921
+ pi,
922
+ ["show", "-s", "--format=%aI%x00%s", "--end-of-options", snapshot.headOid],
923
+ record.path,
924
+ signal
925
+ )).stdout
926
+ ) : void 0;
927
+ cards[index] = formatWorktreeStatusCard(record, currentPath, {
928
+ kind: "available",
929
+ snapshot,
930
+ lastCommit
931
+ });
932
+ } catch (error) {
933
+ throwIfAborted(signal);
934
+ cards[index] = formatWorktreeStatusCard(record, currentPath, {
935
+ kind: "unavailable",
936
+ reason: `Status failed: ${formatError3(error)}`
937
+ });
938
+ }
939
+ }
940
+ };
941
+ await Promise.all(Array.from({ length: concurrency }, worker));
942
+ throwIfAborted(signal);
943
+ return cards;
944
+ }
945
+ function parseBranchHeader(snapshot, entry) {
946
+ if (entry.startsWith("# branch.oid ")) {
947
+ const oid = entry.slice("# branch.oid ".length);
948
+ if (oid === "(initial)") {
949
+ snapshot.headOid = void 0;
950
+ return;
951
+ }
952
+ if (!OID_PATTERN.test(oid)) throw new Error("Git status returned a malformed branch OID.");
953
+ snapshot.headOid = oid;
954
+ return;
955
+ }
956
+ if (entry.startsWith("# branch.head ")) {
957
+ const branch = entry.slice("# branch.head ".length);
958
+ if (!branch) throw new Error("Git status returned a malformed branch head.");
959
+ snapshot.detached = branch === "(detached)";
960
+ snapshot.branch = snapshot.detached || branch === "(unknown)" ? void 0 : branch;
961
+ return;
962
+ }
963
+ if (entry.startsWith("# branch.upstream ")) {
964
+ const upstream = entry.slice("# branch.upstream ".length);
965
+ if (!upstream) throw new Error("Git status returned a malformed upstream.");
966
+ snapshot.upstream = upstream;
967
+ return;
968
+ }
969
+ if (entry.startsWith("# branch.ab ")) {
970
+ const match = /^# branch\.ab \+(\d+) -(\d+)$/u.exec(entry);
971
+ if (!match?.[1] || !match[2]) {
972
+ throw new Error("Git status returned malformed ahead/behind counts.");
973
+ }
974
+ snapshot.ahead = Number.parseInt(match[1], 10);
975
+ snapshot.behind = Number.parseInt(match[2], 10);
976
+ }
977
+ }
978
+ function statusCode(entry) {
979
+ const code = entry.slice(2, 4);
980
+ if (!STATUS_XY_PATTERN.test(code)) {
981
+ throw new Error("Git status returned a malformed tracked status code.");
982
+ }
983
+ return code;
984
+ }
985
+ function countTrackedState(snapshot, code) {
986
+ if (code[0] !== ".") snapshot.staged += 1;
987
+ if (code[1] !== ".") snapshot.unstaged += 1;
988
+ }
989
+ function assertFieldCount(entry, minimum, kind) {
990
+ if (entry.split(" ").length < minimum) {
991
+ throw new Error(`Git status returned a malformed ${kind} record.`);
992
+ }
993
+ }
994
+ function formatWorkingState(snapshot) {
995
+ const values = [
996
+ snapshot.conflicts > 0 ? `${snapshot.conflicts} conflict${snapshot.conflicts === 1 ? "" : "s"}` : void 0,
997
+ snapshot.staged > 0 ? `${snapshot.staged} staged` : void 0,
998
+ snapshot.unstaged > 0 ? `${snapshot.unstaged} unstaged` : void 0,
999
+ snapshot.untracked > 0 ? `${snapshot.untracked} untracked` : void 0
1000
+ ].filter((value) => value !== void 0);
1001
+ return values.join(" \xB7 ") || "clean";
1002
+ }
1003
+ function unavailableReason(record) {
1004
+ if (record.bare) return "Bare worktree cannot be inspected";
1005
+ if (record.prunableReason !== void 0) {
1006
+ return record.prunableReason ? `Prunable: ${record.prunableReason}` : "Prunable worktree metadata";
1007
+ }
1008
+ if (!existsSync3(record.path)) return "Worktree path is missing";
1009
+ return void 0;
1010
+ }
1011
+ async function runGit2(pi, args, cwd, signal) {
1012
+ throwIfAborted(signal);
1013
+ const result = await pi.exec("git", args, { cwd, signal, timeout: GIT_STATUS_TIMEOUT_MS });
1014
+ if (result.killed) {
1015
+ throwIfAborted(signal);
1016
+ throw new Error(`git ${args.slice(0, 2).join(" ")} timed out.`);
1017
+ }
1018
+ if (result.code !== 0) {
1019
+ const detail = [result.stderr.trim(), result.stdout.trim()].filter(Boolean).join(" ");
1020
+ throw new Error(detail || `git ${args.slice(0, 2).join(" ")} exited with code ${result.code}.`);
1021
+ }
1022
+ return result;
1023
+ }
1024
+ function parseLastCommit(output) {
1025
+ const separator = output.indexOf("\0");
1026
+ if (separator <= 0 || output.indexOf("\0", separator + 1) >= 0) {
1027
+ throw new Error("Git returned malformed last-commit details.");
1028
+ }
1029
+ const committedAt = output.slice(0, separator);
1030
+ const subject = removeLineEnding2(output.slice(separator + 1));
1031
+ if (!committedAt) throw new Error("Git returned an empty last-commit timestamp.");
1032
+ return { committedAt, subject };
1033
+ }
1034
+ function safeDisplay(value) {
1035
+ return stripTerminalControls(value);
1036
+ }
1037
+ function throwIfAborted(signal) {
1038
+ if (signal?.aborted) {
1039
+ throw new DOMException("Worktree status loading was aborted.", "AbortError");
1040
+ }
1041
+ }
1042
+ function removeLineEnding2(value) {
1043
+ if (value.endsWith("\r\n")) return value.slice(0, -2);
1044
+ if (value.endsWith("\n")) return value.slice(0, -1);
1045
+ return value;
1046
+ }
1047
+ function formatError3(error) {
1048
+ const message = error instanceof Error ? error.message : String(error);
1049
+ return safeDisplay(message).slice(0, 500);
1050
+ }
1051
+
1052
+ // src/command.ts
1053
+ var ACTION_STATUS = "Worktree status";
1054
+ var ACTION_ADD = "Add worktree";
1055
+ var ACTION_SWITCH = "Switch worktree";
1056
+ var ACTION_REMOVE = "Remove worktree";
1057
+ var ACTION_PRUNE = "Prune stale metadata";
1058
+ var ACTION_CONFIGURE_ROOT = "Configure worktree root";
1059
+ var ACTIONS = {
1060
+ status: ACTION_STATUS,
1061
+ add: ACTION_ADD,
1062
+ switch: ACTION_SWITCH,
1063
+ remove: ACTION_REMOVE,
1064
+ prune: ACTION_PRUNE,
1065
+ configure: ACTION_CONFIGURE_ROOT
1066
+ };
1067
+ function registerWorktreeCommand(pi, settings, getMenuOwner) {
1068
+ pi.registerCommand("worktree", {
1069
+ description: "Interactively manage Git worktrees and their default root",
1070
+ handler: async (args, ctx) => {
1071
+ if (args.trim()) {
1072
+ safeNotify(
1073
+ ctx,
1074
+ "/worktree does not accept arguments; run it without arguments to open the menu.",
1075
+ "warning"
1076
+ );
1077
+ return;
1078
+ }
1079
+ if (!ctx.hasUI) {
1080
+ safeNotify(ctx, "/worktree requires TUI or RPC mode.", "error");
1081
+ return;
1082
+ }
1083
+ try {
1084
+ await ctx.waitForIdle();
1085
+ const records = await listWorktrees(pi, ctx.cwd, ctx.signal);
1086
+ const currentPath = await currentWorktreePath(pi, ctx.cwd, ctx.signal);
1087
+ const root = settings.get();
1088
+ const warning = root.warning ? " \u2014 settings warning" : "";
1089
+ const owner = getMenuOwner();
1090
+ const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
1091
+ if (owner.signal.aborted || !owner.isCurrent()) return;
1092
+ const runFlow = async (flow) => {
1093
+ try {
1094
+ await flow();
1095
+ } catch (error) {
1096
+ safeNotify(ctx, formatError4(error), "error");
1097
+ }
1098
+ return { kind: "close" };
1099
+ };
1100
+ const state = { statusCards: [] };
1101
+ const menu = defineMenu({
1102
+ start: "main",
1103
+ screens: {
1104
+ main: () => ({
1105
+ kind: "actions",
1106
+ title: "Git worktrees",
1107
+ lines: [
1108
+ `Registered: ${records.length}`,
1109
+ `Current: ${currentPath}`,
1110
+ `Worktree root: ${root.effectiveRoot} (${root.source})${warning}`
1111
+ ],
1112
+ items: Object.entries(ACTIONS).map(([id, label]) => ({
1113
+ id,
1114
+ label,
1115
+ action: id,
1116
+ busyLabel: id === "status" ? "Inspecting worktrees\u2026" : void 0
1117
+ })),
1118
+ hint: "close"
1119
+ }),
1120
+ status: ({ state: currentState }) => ({
1121
+ kind: "browse",
1122
+ title: "Worktree status",
1123
+ lines: ["Local Git snapshot; no fetch performed."],
1124
+ items: currentState.statusCards,
1125
+ viewportSize: "adaptive",
1126
+ hint: "back"
1127
+ })
1128
+ },
1129
+ actions: {
1130
+ status: async ({ signal }) => {
1131
+ try {
1132
+ const statusRecords = await listWorktrees(pi, ctx.cwd, signal);
1133
+ state.statusCards = await loadWorktreeStatusCards(
1134
+ pi,
1135
+ statusRecords,
1136
+ currentPath,
1137
+ signal
1138
+ );
1139
+ if (signal.aborted || !owner.isCurrent()) return { kind: "close" };
1140
+ return { kind: "to", screen: "status" };
1141
+ } catch (error) {
1142
+ if (signal.aborted || !owner.isCurrent()) return { kind: "close" };
1143
+ safeNotify(ctx, formatError4(error), "error");
1144
+ return { kind: "stay" };
1145
+ }
1146
+ },
1147
+ add: async () => runFlow(() => addFlow(pi, ctx, records, root.effectiveRoot)),
1148
+ switch: async ({ signal }) => runFlow(() => switchFlow(pi, ctx, records, currentPath, signal)),
1149
+ remove: async ({ signal }) => runFlow(() => removeFlow(pi, ctx, records, currentPath, signal)),
1150
+ prune: async () => runFlow(() => pruneFlow(pi, ctx, records)),
1151
+ configure: async () => runFlow(() => configureRootFlow(ctx, settings))
1152
+ }
1153
+ });
1154
+ await runMenu(ctx, menu, {
1155
+ getState: () => state,
1156
+ signal: owner.signal,
1157
+ isCurrent: owner.isCurrent
1158
+ });
1159
+ } catch (error) {
1160
+ safeNotify(ctx, formatError4(error), "error");
1161
+ }
1162
+ }
1163
+ });
1164
+ }
1165
+ async function configureRootFlow(ctx, settings) {
1166
+ const current = await settings.reload();
1167
+ if (!current.canSave) {
1168
+ throw new Error(
1169
+ current.warning ?? `Fix ${settings.getPath()} before changing pi-worktree settings.`
1170
+ );
1171
+ }
1172
+ const requested = await ctx.ui.input(
1173
+ "Worktree root (blank restores ~/.worktrees)",
1174
+ stripTerminalControls(current.configuredRoot ?? current.effectiveRoot)
1175
+ );
1176
+ if (requested === void 0) return;
1177
+ const configuredRoot = requested.trim() || void 0;
1178
+ const updated = await settings.save(configuredRoot);
1179
+ safeNotify(
1180
+ ctx,
1181
+ configuredRoot === void 0 ? `Worktree root reset to ${updated.effectiveRoot}.` : `Worktree root saved as ${updated.effectiveRoot}.`,
1182
+ "info"
1183
+ );
1184
+ }
1185
+ async function addFlow(pi, ctx, records, worktreeRoot) {
1186
+ const main = records[0];
1187
+ if (!main) throw new Error("Git returned no registered worktrees.");
1188
+ if (main.bare) {
1189
+ throw new Error("The main worktree is bare; pi-worktree cannot derive a safe default path.");
1190
+ }
1191
+ if (!existsSync4(main.path)) {
1192
+ throw new Error(
1193
+ `The registered main worktree path is stale: ${main.path}. Repair it with Git first.`
1194
+ );
1195
+ }
1196
+ const requestedBranch = await ctx.ui.input("Branch for the new worktree", "feat/my-change");
1197
+ if (requestedBranch === void 0) return;
1198
+ const branchInput = requestedBranch.trim();
1199
+ if (!branchInput) throw new Error("Branch name is required.");
1200
+ const branch = await validateBranch(pi, ctx.cwd, branchInput, ctx.signal);
1201
+ const branchExists = await localBranchExists(pi, ctx.cwd, branch, ctx.signal);
1202
+ const occupied = worktreeForBranch(records, branch);
1203
+ if (occupied) {
1204
+ throw new Error(`Branch ${branch} is already checked out at ${occupied.path}.`);
1205
+ }
1206
+ let startOid;
1207
+ let provenance;
1208
+ if (branchExists) {
1209
+ provenance = {
1210
+ kind: "existing-local-branch",
1211
+ label: branch,
1212
+ oid: await resolveCommit(pi, ctx.cwd, `refs/heads/${branch}`, ctx.signal)
1213
+ };
1214
+ } else {
1215
+ const defaultStart = await symbolicBranch(pi, ctx.cwd, ctx.signal);
1216
+ const requestedStart = await ctx.ui.input(
1217
+ stripTerminalControls(
1218
+ defaultStart ? `Start point for ${branch} (blank uses ${defaultStart})` : `Start point for ${branch} (required because HEAD is detached)`
1219
+ ),
1220
+ stripTerminalControls(defaultStart ?? "commit-ish")
1221
+ );
1222
+ if (requestedStart === void 0) return;
1223
+ const explicitStart = requestedStart.trim();
1224
+ const startLabel = explicitStart || defaultStart;
1225
+ if (!startLabel) throw new Error("An explicit start point is required from detached HEAD.");
1226
+ startOid = await resolveCommit(pi, ctx.cwd, startLabel, ctx.signal);
1227
+ provenance = {
1228
+ kind: explicitStart ? "explicit-commit-ish" : "current-branch",
1229
+ label: startLabel,
1230
+ oid: startOid
1231
+ };
1232
+ }
1233
+ const suggestedPath = defaultWorktreePath(main.path, branch, worktreeRoot);
1234
+ const requestedPath = await ctx.ui.input(
1235
+ stripTerminalControls(`Worktree path (blank uses ${suggestedPath})`),
1236
+ stripTerminalControls(suggestedPath)
1237
+ );
1238
+ if (requestedPath === void 0) return;
1239
+ const targetPath = pathIdentity(
1240
+ requestedPath.trim() ? resolve2(ctx.cwd, requestedPath.trim()) : suggestedPath
1241
+ );
1242
+ assertTargetFilesystemAvailable(targetPath);
1243
+ const pathCollision = records.find((record) => pathsEqual(record.path, targetPath));
1244
+ if (pathCollision) {
1245
+ throw new Error(`The target path is already registered as a worktree: ${pathCollision.path}.`);
1246
+ }
1247
+ const summary = formatAddPreview(branch, branchExists, provenance, targetPath);
1248
+ if (!await ctx.ui.confirm("Create Git worktree", summary)) return;
1249
+ assertTargetFilesystemAvailable(targetPath);
1250
+ const latestRecords = await listWorktrees(pi, ctx.cwd, ctx.signal);
1251
+ const latestOccupied = worktreeForBranch(latestRecords, branch);
1252
+ if (latestOccupied) {
1253
+ throw new Error(
1254
+ `Branch ${branch} is now checked out at ${latestOccupied.path}; select it again.`
1255
+ );
1256
+ }
1257
+ const latestPathCollision = latestRecords.find((record) => pathsEqual(record.path, targetPath));
1258
+ if (latestPathCollision) {
1259
+ throw new Error(
1260
+ `The target path is now registered as a worktree: ${latestPathCollision.path}. Select it again.`
1261
+ );
1262
+ }
1263
+ const branchStillExists = await localBranchExists(pi, ctx.cwd, branch, ctx.signal);
1264
+ if (branchStillExists !== branchExists) {
1265
+ throw new Error(`Branch ${branch} changed after confirmation; select it again.`);
1266
+ }
1267
+ if (branchExists) {
1268
+ const latestOid = await resolveCommit(pi, ctx.cwd, `refs/heads/${branch}`, ctx.signal);
1269
+ if (latestOid !== provenance.oid) {
1270
+ throw new Error(`Branch ${branch} moved after confirmation; select it again.`);
1271
+ }
1272
+ }
1273
+ assertTargetFilesystemAvailable(targetPath);
1274
+ await addWorktree(pi, ctx.cwd, { path: targetPath, branch, startOid }, ctx.signal);
1275
+ let created;
1276
+ try {
1277
+ const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
1278
+ const verified = updated.find((record) => pathsEqual(record.path, targetPath));
1279
+ if (!verified || verified.branch !== branch || verified.head !== provenance.oid) {
1280
+ throw new Error(
1281
+ "the expected path, branch, and approved HEAD were not present in Git porcelain output"
1282
+ );
1283
+ }
1284
+ created = verified;
1285
+ } catch (error) {
1286
+ throw new Error(
1287
+ `Git add completed, so the worktree was retained at ${targetPath}, but verification failed: ${formatError4(error)}. Inspect git worktree list before retrying.`
1288
+ );
1289
+ }
1290
+ safeNotify(ctx, `Created worktree ${targetPath} on branch ${branch}.`, "info");
1291
+ if (await ctx.ui.confirm(
1292
+ "Switch Pi workspace?",
1293
+ stripTerminalControls(`Continue this conversation in ${targetPath}?`)
1294
+ )) {
1295
+ const latest = await revalidateWorktreeIdentity(pi, ctx, created);
1296
+ if (latest.prunableReason !== void 0 || !existsSync4(latest.path)) {
1297
+ throw new Error("The newly created worktree became unavailable; select it again.");
1298
+ }
1299
+ await switchToWorktree(ctx, latest.path);
1300
+ }
1301
+ }
1302
+ function formatAddPreview(branch, branchExists, provenance, targetPath) {
1303
+ const base = provenance.kind === "existing-local-branch" ? `existing local branch ${quoteTerminalValue(provenance.label)}` : provenance.kind === "current-branch" ? `current branch ${quoteTerminalValue(provenance.label)}` : `explicit commit-ish ${quoteTerminalValue(provenance.label)}`;
1304
+ return [
1305
+ `Branch: ${quoteTerminalValue(branch)} (${branchExists ? "existing" : "new"} local branch)`,
1306
+ `Base: ${base}`,
1307
+ `Base commit: ${provenance.oid}`,
1308
+ `Path: ${quoteTerminalValue(targetPath)}`
1309
+ ].join("; ");
1310
+ }
1311
+ function quoteTerminalValue(value) {
1312
+ let quoted = "";
1313
+ for (const character of value) {
1314
+ const code = character.codePointAt(0) ?? 0;
1315
+ if (code <= 31 || code >= 127 && code <= 159) {
1316
+ quoted += `\\u${code.toString(16).padStart(4, "0")}`;
1317
+ } else if (character === "\\" || character === '"') {
1318
+ quoted += `\\${character}`;
1319
+ } else {
1320
+ quoted += character;
1321
+ }
1322
+ }
1323
+ return `"${quoted}"`;
1324
+ }
1325
+ function assertTargetFilesystemAvailable(targetPath) {
1326
+ if (pathEntryExists(targetPath)) {
1327
+ throw new Error(`The target path already exists: ${targetPath}.`);
1328
+ }
1329
+ const unsafeAncestor = unresolvableSymlinkAncestor(targetPath);
1330
+ if (unsafeAncestor) {
1331
+ throw new Error(
1332
+ `The target path has an unresolvable symbolic-link ancestor: ${unsafeAncestor}.`
1333
+ );
1334
+ }
1335
+ }
1336
+ async function switchFlow(pi, ctx, records, currentPath, signal) {
1337
+ const candidates = records.filter(
1338
+ (record) => !record.bare && record.prunableReason === void 0 && existsSync4(record.path) && !pathsEqual(record.path, currentPath)
1339
+ );
1340
+ const selected = await selectWorktree(ctx, "Switch to worktree", candidates, currentPath, signal);
1341
+ if (!selected) return;
1342
+ const latest = await revalidateWorktreeIdentity(pi, ctx, selected);
1343
+ if (latest.bare || latest.prunableReason !== void 0 || !existsSync4(latest.path) || pathsEqual(latest.path, currentPath)) {
1344
+ throw new Error("The selected worktree changed state; select it again.");
1345
+ }
1346
+ await switchToWorktree(ctx, latest.path);
1347
+ }
1348
+ async function removeFlow(pi, ctx, records, currentPath, signal) {
1349
+ const candidates = records.filter(
1350
+ (record) => !record.isMain && !record.bare && !pathsEqual(record.path, currentPath)
1351
+ );
1352
+ const selected = await selectWorktree(
1353
+ ctx,
1354
+ "Remove linked worktree",
1355
+ candidates,
1356
+ currentPath,
1357
+ signal
1358
+ );
1359
+ if (!selected) return;
1360
+ if (selected.lockedReason !== void 0) {
1361
+ throw new Error(
1362
+ `Worktree is locked${selected.lockedReason ? `: ${selected.lockedReason}` : "."} Unlock it explicitly with Git before removal.`
1363
+ );
1364
+ }
1365
+ if (selected.prunableReason !== void 0 || !existsSync4(selected.path)) {
1366
+ throw new Error("The selected worktree path is stale. Use prune instead of remove.");
1367
+ }
1368
+ const inventory = classifyRemovalInventory(
1369
+ await worktreeInventory(pi, selected.path, ctx.signal)
1370
+ );
1371
+ if (inventory.protected.length > 0) {
1372
+ throw new Error(
1373
+ `Removal refused because ${selected.path} contains tracked, untracked, index-flagged, or submodule data:
1374
+ ${inventory.protected.join("\n")}`
1375
+ );
1376
+ }
1377
+ await assertDetachedHeadIsDurable(pi, ctx, selected);
1378
+ const administrativePath = await worktreeAdministrativeDirectory(pi, selected.path, ctx.signal);
1379
+ const approvedHistoryRisks = historyRisks(
1380
+ selected.path,
1381
+ await unreachableAdministrativeHistoryOids(pi, ctx, administrativePath)
1382
+ );
1383
+ const recoveryWarning = formatAdministrativeRecoveryWarning(approvedHistoryRisks);
1384
+ const ignoredWarning = formatIgnoredDataWarning(inventory.ignored);
1385
+ const removalWarning = ignoredWarning && recoveryWarning ? `${ignoredWarning}
1386
+ ${recoveryWarning.trimStart()}` : `${ignoredWarning}${recoveryWarning}`;
1387
+ const confirmationTitle = inventory.ignored.length > 0 ? recoveryWarning ? "Remove worktree and discard local/recovery data" : "Remove worktree and delete ignored files" : recoveryWarning ? "Remove worktree and discard recovery history" : "Remove Git worktree";
1388
+ if (!await ctx.ui.confirm(
1389
+ confirmationTitle,
1390
+ `Delete the worktree directory ${stripTerminalControls(selected.path)}? The branch will be preserved.${removalWarning}`
1391
+ )) {
1392
+ return;
1393
+ }
1394
+ await assertAdministrativeHistoryUnchanged(
1395
+ pi,
1396
+ ctx,
1397
+ selected.path,
1398
+ administrativePath,
1399
+ approvedHistoryRisks
1400
+ );
1401
+ const beforeRemoval = await listWorktrees(pi, ctx.cwd, ctx.signal);
1402
+ const latest = beforeRemoval.find((record) => pathsEqual(record.path, selected.path));
1403
+ if (!latest) throw new Error(`Worktree ${selected.path} is no longer registered.`);
1404
+ if (!sameWorktreeIdentity(selected, latest)) {
1405
+ throw new Error(`Worktree ${selected.path} changed identity; select it again.`);
1406
+ }
1407
+ if (latest.isMain || latest.lockedReason !== void 0 || latest.prunableReason !== void 0) {
1408
+ throw new Error(
1409
+ `Worktree ${selected.path} changed state after confirmation; removal was refused.`
1410
+ );
1411
+ }
1412
+ const latestInventory = classifyRemovalInventory(
1413
+ await worktreeInventory(pi, latest.path, ctx.signal)
1414
+ );
1415
+ if (latestInventory.protected.length > 0) {
1416
+ throw new Error(
1417
+ `Removal refused because new protected local data appeared after confirmation:
1418
+ ${latestInventory.protected.join("\n")}`
1419
+ );
1420
+ }
1421
+ if (!sameInventory(inventory.ignored, latestInventory.ignored)) {
1422
+ throw new Error(
1423
+ `Removal refused because ignored data changed after confirmation:
1424
+ ${latestInventory.ignored.join("\n") || "(none)"}`
1425
+ );
1426
+ }
1427
+ await assertDetachedHeadIsDurable(pi, ctx, latest);
1428
+ await assertAdministrativeHistoryUnchanged(
1429
+ pi,
1430
+ ctx,
1431
+ latest.path,
1432
+ administrativePath,
1433
+ approvedHistoryRisks
1434
+ );
1435
+ await removeWorktree(pi, ctx.cwd, latest.path, ctx.signal);
1436
+ const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
1437
+ if (updated.some((record) => pathsEqual(record.path, selected.path))) {
1438
+ throw new Error(`Git remove returned success, but ${selected.path} is still registered.`);
1439
+ }
1440
+ safeNotify(ctx, `Removed worktree ${selected.path}. Its branch was preserved.`, "info");
1441
+ }
1442
+ async function pruneFlow(pi, ctx, records) {
1443
+ for (const record of records.filter(
1444
+ (candidate) => candidate.prunableReason !== void 0 && candidate.detached
1445
+ )) {
1446
+ await assertDetachedHeadIsDurable(pi, ctx, record);
1447
+ }
1448
+ const preview = await prunePreview(pi, ctx.cwd, ctx.signal);
1449
+ if (!preview) {
1450
+ ctx.ui.notify("Git found no stale worktree metadata to prune.", "info");
1451
+ return;
1452
+ }
1453
+ const approvedHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
1454
+ const safePreview = stripTerminalControls(preview);
1455
+ const recoveryWarning = formatAdministrativeRecoveryWarning(approvedHistoryRisks);
1456
+ ctx.ui.notify(`git worktree prune --dry-run --verbose
1457
+ ${safePreview}`, "warning");
1458
+ if (!await ctx.ui.confirm(
1459
+ recoveryWarning ? "Prune metadata and discard recovery history" : "Prune stale worktree metadata",
1460
+ stripTerminalControls(`${safePreview}${recoveryWarning}`)
1461
+ )) {
1462
+ return;
1463
+ }
1464
+ const latest = await listWorktrees(pi, ctx.cwd, ctx.signal);
1465
+ for (const record of latest.filter(
1466
+ (candidate) => candidate.prunableReason !== void 0 && candidate.detached
1467
+ )) {
1468
+ await assertDetachedHeadIsDurable(pi, ctx, record);
1469
+ }
1470
+ const beforePreviewHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
1471
+ if (!sameAdministrativeHistoryRisks(approvedHistoryRisks, beforePreviewHistoryRisks)) {
1472
+ throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
1473
+ }
1474
+ const latestPreview = await prunePreview(pi, ctx.cwd, ctx.signal);
1475
+ const finalHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
1476
+ if (latestPreview !== preview || !sameAdministrativeHistoryRisks(approvedHistoryRisks, finalHistoryRisks)) {
1477
+ throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
1478
+ }
1479
+ const output = await pruneWorktrees(pi, ctx.cwd, ctx.signal);
1480
+ safeNotify(
1481
+ ctx,
1482
+ output ? `Pruned stale worktree metadata:
1483
+ ${output}` : "Pruned stale worktree metadata.",
1484
+ "info"
1485
+ );
1486
+ }
1487
+ async function assertAdministrativeHistoryUnchanged(pi, ctx, selectedPath, approvedAdministrativePath, approvedHistoryRisks) {
1488
+ const latestAdministrativePath = await worktreeAdministrativeDirectory(
1489
+ pi,
1490
+ selectedPath,
1491
+ ctx.signal
1492
+ );
1493
+ const latestHistoryRisks = historyRisks(
1494
+ selectedPath,
1495
+ await unreachableAdministrativeHistoryOids(pi, ctx, latestAdministrativePath)
1496
+ );
1497
+ if (!pathsEqual(approvedAdministrativePath, latestAdministrativePath) || !sameAdministrativeHistoryRisks(approvedHistoryRisks, latestHistoryRisks)) {
1498
+ throw new Error(
1499
+ `Worktree ${selectedPath} administrative recovery history changed after confirmation; select it again.`
1500
+ );
1501
+ }
1502
+ }
1503
+ async function inspectAdministrativePruneCandidates(pi, ctx) {
1504
+ const risks = [];
1505
+ for (const candidate of await administrativePruneCandidates(pi, ctx.cwd, ctx.signal)) {
1506
+ if (candidate.indexDirty) {
1507
+ throw new Error(
1508
+ `Prune refused because administrative worktree ${candidate.id} contains staged-only index changes.`
1509
+ );
1510
+ }
1511
+ if (candidate.head) {
1512
+ const refs = await durableRefsContaining(pi, ctx.cwd, candidate.head, ctx.signal);
1513
+ if (refs.length === 0) {
1514
+ throw new Error(
1515
+ `Prune refused because administrative worktree ${candidate.id} has detached HEAD ${candidate.head}, which is not reachable from a durable ref.`
1516
+ );
1517
+ }
1518
+ } else if (!candidate.branchRef || !await durableRefExists(pi, ctx.cwd, candidate.branchRef, ctx.signal)) {
1519
+ throw new Error(
1520
+ `Prune refused because administrative worktree ${candidate.id} does not resolve to a durable ref.`
1521
+ );
1522
+ }
1523
+ risks.push(
1524
+ ...historyRisks(
1525
+ candidate.id,
1526
+ await unreachableAdministrativeHistoryOids(pi, ctx, candidate.administrativePath)
1527
+ )
1528
+ );
1529
+ }
1530
+ return normalizeAdministrativeHistoryRisks(risks);
1531
+ }
1532
+ async function unreachableAdministrativeHistoryOids(pi, ctx, administrativePath) {
1533
+ const unreachable = [];
1534
+ for (const oid of await administrativeHistoryOids(pi, ctx.cwd, administrativePath, ctx.signal)) {
1535
+ const refs = await durableRefsContaining(pi, ctx.cwd, oid, ctx.signal);
1536
+ if (refs.length === 0) unreachable.push(oid);
1537
+ }
1538
+ return [...new Set(unreachable)].sort();
1539
+ }
1540
+ function historyRisks(label, oids) {
1541
+ return oids.length > 0 ? [{ label, oids }] : [];
1542
+ }
1543
+ function normalizeAdministrativeHistoryRisks(risks) {
1544
+ return risks.map((risk) => ({ label: risk.label, oids: [...new Set(risk.oids)].sort() })).filter((risk) => risk.oids.length > 0).sort((left, right) => left.label.localeCompare(right.label));
1545
+ }
1546
+ function sameAdministrativeHistoryRisks(left, right) {
1547
+ return JSON.stringify(normalizeAdministrativeHistoryRisks(left)) === JSON.stringify(normalizeAdministrativeHistoryRisks(right));
1548
+ }
1549
+ function formatAdministrativeRecoveryWarning(risks) {
1550
+ if (risks.length === 0) return "";
1551
+ const entries = risks.map(
1552
+ (risk) => `${stripTerminalControls(risk.label)}: ${risk.oids.map(stripTerminalControls).join(", ")}`
1553
+ ).join("; ");
1554
+ 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.`;
1555
+ }
1556
+ function classifyRemovalInventory(lines) {
1557
+ const ignored = [];
1558
+ const protectedData = [];
1559
+ for (const line of lines) {
1560
+ (line.startsWith("!! ") ? ignored : protectedData).push(line);
1561
+ }
1562
+ return {
1563
+ ignored: normalizeInventory(ignored),
1564
+ protected: normalizeInventory(protectedData)
1565
+ };
1566
+ }
1567
+ function normalizeInventory(lines) {
1568
+ return [...new Set(lines)].sort();
1569
+ }
1570
+ function sameInventory(left, right) {
1571
+ return JSON.stringify(normalizeInventory(left)) === JSON.stringify(normalizeInventory(right));
1572
+ }
1573
+ function formatIgnoredDataWarning(ignored) {
1574
+ if (ignored.length === 0) return "";
1575
+ return ` Ignored files and directories that will be deleted:
1576
+ ${ignored.map(stripTerminalControls).join("\n")}`;
1577
+ }
1578
+ async function assertDetachedHeadIsDurable(pi, ctx, record) {
1579
+ if (!record.detached) return;
1580
+ if (!record.head)
1581
+ throw new Error(`Detached worktree ${record.path} has no HEAD object; refusing.`);
1582
+ const refs = await durableRefsContaining(pi, ctx.cwd, record.head, ctx.signal);
1583
+ if (refs.length === 0) {
1584
+ throw new Error(
1585
+ `Detached HEAD ${record.head} at ${record.path} is not reachable from a local branch, tag, or remote ref. Preserve it before continuing.`
1586
+ );
1587
+ }
1588
+ }
1589
+ async function revalidateWorktreeIdentity(pi, ctx, selected) {
1590
+ const latest = (await listWorktrees(pi, ctx.cwd, ctx.signal)).find(
1591
+ (record) => pathsEqual(record.path, selected.path)
1592
+ );
1593
+ if (!latest) throw new Error(`Worktree ${selected.path} is no longer registered.`);
1594
+ if (!sameWorktreeIdentity(selected, latest)) {
1595
+ throw new Error(`Worktree ${selected.path} changed identity; select it again.`);
1596
+ }
1597
+ return latest;
1598
+ }
1599
+ async function selectWorktree(ctx, title, records, currentPath, signal) {
1600
+ if (records.length === 0) {
1601
+ ctx.ui.notify("No eligible worktrees are available for this action.", "info");
1602
+ return void 0;
1603
+ }
1604
+ const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
1605
+ if (signal?.aborted || ctx.signal?.aborted) return void 0;
1606
+ let selected;
1607
+ const menu = defineMenu({
1608
+ start: "worktrees",
1609
+ screens: {
1610
+ worktrees: () => ({
1611
+ kind: "choice",
1612
+ title,
1613
+ enableSearch: true,
1614
+ items: records.map((record, index) => ({
1615
+ id: record.path,
1616
+ label: `${index + 1}. ${formatWorktree(record, currentPath)}`,
1617
+ searchText: [record.path, record.branch, record.head].filter(Boolean).join(" ")
1618
+ })),
1619
+ action: "choose",
1620
+ hint: "close"
1621
+ })
1622
+ },
1623
+ actions: {
1624
+ choose: async ({ itemId }) => {
1625
+ selected = records.find((record) => record.path === itemId);
1626
+ return selected ? { kind: "close" } : { kind: "rejected" };
1627
+ }
1628
+ }
1629
+ });
1630
+ await runMenu(ctx, menu, {
1631
+ getState: () => void 0,
1632
+ signal,
1633
+ isCurrent: () => !signal?.aborted
1634
+ });
1635
+ return selected;
1636
+ }
1637
+ function safeNotify(ctx, message, level) {
1638
+ try {
1639
+ ctx.ui.notify(stripTerminalControls(message), level);
1640
+ } catch {
1641
+ console.error(message);
1642
+ }
1643
+ }
1644
+ function formatError4(error) {
1645
+ return error instanceof Error ? error.message : String(error);
1646
+ }
1647
+
1648
+ // src/settings.ts
1649
+ import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
1650
+ import { homedir } from "node:os";
1651
+ import { dirname as dirname2, join, posix, win32 } from "node:path";
1652
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
1653
+ var SETTINGS_FILE = "pi-worktree.json";
1654
+ var DEFAULT_FILE_OPERATIONS = {
1655
+ write: (path, data) => writeFile(path, data, { encoding: "utf8", flag: "wx", mode: 384 }).then(() => void 0),
1656
+ rename
1657
+ };
1658
+ function settingsFilePath() {
1659
+ return join(getAgentDir(), SETTINGS_FILE);
1660
+ }
1661
+ function defaultWorktreeRoot(home = homedir(), platform = process.platform) {
1662
+ return platformPath(platform).join(home, ".worktrees");
1663
+ }
1664
+ function resolveWorktreeRoot(value, home = homedir(), platform = process.platform) {
1665
+ if (!value || value.includes("\0")) {
1666
+ throw new Error("worktreeRoot must be a non-empty path without NUL characters.");
1667
+ }
1668
+ if (hasShellVariableSyntax(value)) {
1669
+ throw new Error("worktreeRoot must not contain shell variable syntax.");
1670
+ }
1671
+ const path = platformPath(platform);
1672
+ let candidate = value;
1673
+ if (value === "~") {
1674
+ candidate = home;
1675
+ } else if (value.startsWith("~/") || platform === "win32" && value.startsWith("~\\")) {
1676
+ candidate = path.resolve(home, value.slice(2));
1677
+ } else if (value.startsWith("~")) {
1678
+ throw new Error("worktreeRoot supports only ~ itself or a path beginning with ~/.");
1679
+ }
1680
+ if (!path.isAbsolute(candidate)) {
1681
+ throw new Error("worktreeRoot must be an absolute path or begin with ~/.");
1682
+ }
1683
+ try {
1684
+ const normalized = path.normalize(candidate);
1685
+ if (!normalized || !path.isAbsolute(normalized)) {
1686
+ throw new Error("normalization did not produce an absolute path");
1687
+ }
1688
+ return normalized;
1689
+ } catch (error) {
1690
+ throw new Error(`worktreeRoot could not be normalized: ${formatError5(error)}`);
1691
+ }
1692
+ }
1693
+ async function loadWorktreeSettings(path = settingsFilePath(), home = homedir(), platform = process.platform) {
1694
+ const fallback = defaultWorktreeRoot(home, platform);
1695
+ let text;
1696
+ try {
1697
+ const stats = await lstat(path);
1698
+ if (stats.isSymbolicLink()) return invalid(path, fallback, "symbolic links are not accepted");
1699
+ if (!stats.isFile()) return invalid(path, fallback, "settings path is not a regular file");
1700
+ text = await readFile(path, "utf8");
1701
+ } catch (error) {
1702
+ if (isNodeError2(error) && error.code === "ENOENT") {
1703
+ return {
1704
+ kind: "missing",
1705
+ path,
1706
+ effectiveRoot: fallback,
1707
+ source: "default",
1708
+ document: {}
1709
+ };
1710
+ }
1711
+ return invalid(path, fallback, formatError5(error));
1712
+ }
1713
+ try {
1714
+ const document = JSON.parse(text);
1715
+ if (!isRecord(document)) return invalid(path, fallback, "the top level must be a JSON object");
1716
+ if (!Object.hasOwn(document, "worktreeRoot")) {
1717
+ return {
1718
+ kind: "loaded",
1719
+ path,
1720
+ effectiveRoot: fallback,
1721
+ source: "default",
1722
+ document
1723
+ };
1724
+ }
1725
+ if (typeof document.worktreeRoot !== "string") {
1726
+ return invalid(path, fallback, "worktreeRoot must be a string");
1727
+ }
1728
+ const effectiveRoot = resolveWorktreeRoot(document.worktreeRoot, home, platform);
1729
+ return {
1730
+ kind: "loaded",
1731
+ path,
1732
+ effectiveRoot,
1733
+ source: "user",
1734
+ configuredRoot: document.worktreeRoot,
1735
+ document
1736
+ };
1737
+ } catch (error) {
1738
+ return invalid(path, fallback, formatError5(error));
1739
+ }
1740
+ }
1741
+ async function saveWorktreeSettings(document, configuredRoot, path = settingsFilePath(), operations = {}) {
1742
+ const nextDocument = { ...document };
1743
+ if (configuredRoot === void 0) delete nextDocument.worktreeRoot;
1744
+ else nextDocument.worktreeRoot = configuredRoot;
1745
+ await mkdir(dirname2(path), { recursive: true });
1746
+ const temporaryPath = temporaryFilePath(path);
1747
+ try {
1748
+ await (operations.write ?? DEFAULT_FILE_OPERATIONS.write)(
1749
+ temporaryPath,
1750
+ `${JSON.stringify(nextDocument, null, 2)}
1751
+ `
1752
+ );
1753
+ await (operations.rename ?? DEFAULT_FILE_OPERATIONS.rename)(temporaryPath, path);
1754
+ return nextDocument;
1755
+ } catch (error) {
1756
+ await unlink(temporaryPath).catch(() => void 0);
1757
+ throw error;
1758
+ }
1759
+ }
1760
+ function createWorktreeSettingsRuntime(options = {}) {
1761
+ const home = options.home ?? homedir();
1762
+ const platform = options.platform ?? process.platform;
1763
+ let resolvedPath;
1764
+ const getPath = () => {
1765
+ resolvedPath ??= typeof options.path === "function" ? options.path() : options.path ?? settingsFilePath();
1766
+ return resolvedPath;
1767
+ };
1768
+ let operationQueue = Promise.resolve();
1769
+ const enqueue = (operation) => {
1770
+ const result = operationQueue.then(operation, operation);
1771
+ operationQueue = result.then(
1772
+ () => void 0,
1773
+ () => void 0
1774
+ );
1775
+ return result;
1776
+ };
1777
+ let state = {
1778
+ effectiveRoot: defaultWorktreeRoot(home, platform),
1779
+ source: "default",
1780
+ canSave: true
1781
+ };
1782
+ return {
1783
+ get: () => Object.freeze({ ...state }),
1784
+ getPath,
1785
+ async flush() {
1786
+ await operationQueue;
1787
+ },
1788
+ reload() {
1789
+ return enqueue(async () => {
1790
+ const loaded = await loadWorktreeSettings(getPath(), home, platform);
1791
+ if (loaded.kind === "invalid") {
1792
+ state = { ...state, warning: loaded.warning, canSave: false };
1793
+ return Object.freeze({ ...state });
1794
+ }
1795
+ state = stateFromLoaded(loaded);
1796
+ return Object.freeze({ ...state });
1797
+ });
1798
+ },
1799
+ save(configuredRoot) {
1800
+ return enqueue(async () => {
1801
+ if (!state.canSave) {
1802
+ throw new Error(`Fix the pi-worktree settings file at ${getPath()} before changing it.`);
1803
+ }
1804
+ const effectiveRoot = configuredRoot === void 0 ? defaultWorktreeRoot(home, platform) : resolveWorktreeRoot(configuredRoot, home, platform);
1805
+ const latest = await loadWorktreeSettings(getPath(), home, platform);
1806
+ if (latest.kind === "invalid") {
1807
+ state = { ...state, warning: latest.warning, canSave: false };
1808
+ throw new Error(`Fix the pi-worktree settings file at ${getPath()} before changing it.`);
1809
+ }
1810
+ await saveWorktreeSettings(
1811
+ latest.document ?? {},
1812
+ configuredRoot,
1813
+ getPath(),
1814
+ options.operations
1815
+ );
1816
+ state = {
1817
+ effectiveRoot,
1818
+ source: configuredRoot === void 0 ? "default" : "user",
1819
+ ...configuredRoot === void 0 ? {} : { configuredRoot },
1820
+ canSave: true
1821
+ };
1822
+ return Object.freeze({ ...state });
1823
+ });
1824
+ }
1825
+ };
1826
+ }
1827
+ function stateFromLoaded(loaded) {
1828
+ return {
1829
+ effectiveRoot: loaded.effectiveRoot,
1830
+ source: loaded.source,
1831
+ ...loaded.configuredRoot === void 0 ? {} : { configuredRoot: loaded.configuredRoot },
1832
+ ...loaded.warning === void 0 ? {} : { warning: loaded.warning },
1833
+ canSave: true
1834
+ };
1835
+ }
1836
+ function invalid(path, fallback, reason) {
1837
+ return {
1838
+ kind: "invalid",
1839
+ path,
1840
+ effectiveRoot: fallback,
1841
+ source: "default",
1842
+ warning: `${SETTINGS_FILE} ignored (${path}: ${reason}); using the safe default or last valid root without overwriting the file.`
1843
+ };
1844
+ }
1845
+ function platformPath(platform) {
1846
+ return platform === "win32" ? win32 : posix;
1847
+ }
1848
+ function hasShellVariableSyntax(value) {
1849
+ return /\$|%[^%]+%/u.test(value);
1850
+ }
1851
+ function temporaryFilePath(path) {
1852
+ return `${path}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;
1853
+ }
1854
+ function isRecord(value) {
1855
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1856
+ }
1857
+ function isNodeError2(error) {
1858
+ return error instanceof Error && "code" in error;
1859
+ }
1860
+ function formatError5(error) {
1861
+ return error instanceof Error ? error.message : String(error);
1862
+ }
1863
+
1864
+ // src/worktree.ts
1865
+ function worktreeExtension(pi, options = {}) {
1866
+ const settings = options.settings ?? createWorktreeSettingsRuntime({ path: settingsFilePath });
1867
+ let sessionGeneration = 0;
1868
+ let menuController = new AbortController();
1869
+ registerWorktreeCommand(pi, settings, () => {
1870
+ const generation = sessionGeneration;
1871
+ return {
1872
+ signal: menuController.signal,
1873
+ isCurrent: () => generation === sessionGeneration && !menuController.signal.aborted
1874
+ };
1875
+ });
1876
+ pi.on("session_start", async (_event, ctx) => {
1877
+ const generation = ++sessionGeneration;
1878
+ menuController.abort(new DOMException("Worktree session replaced", "AbortError"));
1879
+ menuController = new AbortController();
1880
+ const loaded = await settings.reload();
1881
+ if (generation !== sessionGeneration || !loaded.warning || !ctx.hasUI) return;
1882
+ ctx.ui.notify(loaded.warning, "warning");
1883
+ });
1884
+ pi.on("session_shutdown", async () => {
1885
+ sessionGeneration += 1;
1886
+ menuController.abort(new DOMException("Worktree session shut down", "AbortError"));
1887
+ await settings.flush?.();
1888
+ });
1889
+ }
1890
+ export {
1891
+ worktreeExtension as default
1892
+ };
1893
+ //# sourceMappingURL=index.ts.map