@narumitw/pi-worktree 0.25.1 → 0.27.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -11
- package/package.json +1 -1
- package/src/command.ts +153 -39
- package/src/git.ts +6 -5
- package/src/settings.ts +291 -0
- package/src/worktree.ts +25 -2
package/README.md
CHANGED
|
@@ -11,11 +11,12 @@ Pi cannot change its parent process working directory with `cd`. This extension
|
|
|
11
11
|
- Shows compact main, linked, current, detached, locked, and prunable state in worktree selectors.
|
|
12
12
|
- Creates a new branch worktree or attaches an existing unoccupied local branch.
|
|
13
13
|
- Rejects occupied targets and unresolvable symbolic-link ancestors before Git can create a branch.
|
|
14
|
-
- Suggests
|
|
14
|
+
- Suggests `~/.worktrees/<main-worktree-name>/<branch>` by default and lets the user configure the root interactively.
|
|
15
15
|
- Optionally switches Pi into a newly created worktree while continuing the current conversation.
|
|
16
16
|
- Switches among existing registered worktrees through Pi's public session replacement API.
|
|
17
|
-
- Removes
|
|
18
|
-
- Refuses removal when tracked, untracked,
|
|
17
|
+
- Removes unlocked, non-current linked worktrees and preserves their branches.
|
|
18
|
+
- Refuses removal when tracked, untracked, manually index-flagged, submodule, or current unreachable detached-commit data may be lost.
|
|
19
|
+
- Allows ignored-only data such as `node_modules/` after listing it in the destructive confirmation.
|
|
19
20
|
- Names recovery-only administrative commits in the destructive confirmation instead of making ordinary rebase/reset history block cleanup forever.
|
|
20
21
|
- Always previews stale metadata before pruning it and revalidates the preview after confirmation.
|
|
21
22
|
- Runs Git through argv-based subprocess calls, without interpolating user input into shell commands.
|
|
@@ -51,27 +52,53 @@ Choose one action:
|
|
|
51
52
|
|
|
52
53
|
- **Add worktree** — enter a branch, optional start point, and optional path; confirm creation and optionally switch.
|
|
53
54
|
- **Switch worktree** — select another existing worktree and continue this Pi conversation there.
|
|
54
|
-
- **Remove worktree** — remove a
|
|
55
|
+
- **Remove worktree** — remove a linked worktree without deleting its branch; ignored-only data is listed for explicit confirmation.
|
|
55
56
|
- **Prune stale metadata** — inspect Git's dry-run output, then optionally run the matching prune.
|
|
57
|
+
- **Configure worktree root** — set a machine-local default root or submit a blank value to restore `~/.worktrees`.
|
|
56
58
|
|
|
57
|
-
`/worktree` intentionally does not accept text subcommands
|
|
59
|
+
The menu title shows the effective worktree root and whether it comes from the built-in default or the user settings file. `/worktree` intentionally does not accept text subcommands or expose argument autocomplete. Every change is initiated and confirmed through the interactive UI.
|
|
58
60
|
|
|
59
61
|
## 🌿 Add defaults
|
|
60
62
|
|
|
61
63
|
For a new branch, the current symbolic branch is the default start point. If Pi is running from detached HEAD, the command requires an explicit commit-ish. Git must resolve the start point to exactly one commit.
|
|
62
64
|
|
|
63
|
-
The
|
|
65
|
+
The default root is `~/.worktrees`, where `~` is Node's platform home directory. Suggestions use the registered main worktree's directory name, not the current linked-worktree cwd:
|
|
64
66
|
|
|
65
67
|
```text
|
|
66
68
|
main worktree: /home/user/workspace/project
|
|
67
69
|
branch: feat/login
|
|
68
|
-
|
|
70
|
+
root: /home/user/.worktrees
|
|
71
|
+
suggested: /home/user/.worktrees/project/feat-login
|
|
69
72
|
```
|
|
70
73
|
|
|
71
|
-
|
|
74
|
+
On Windows, the equivalent default is such as `C:\Users\Alice\.worktrees`. Branch `/` characters become `-`. The extension does not add hashes or collision suffixes: if two normalized paths collide or the target already exists, Add stops before Git mutation.
|
|
75
|
+
|
|
76
|
+
Leave the path input blank to accept the suggestion. A custom absolute path is used directly; a custom relative path is resolved from the current Pi cwd. The target itself must not exist, and its nearest existing ancestor must resolve without a broken or looping symbolic link. Existing registered worktrees are never moved when this default changes.
|
|
72
77
|
|
|
73
78
|
The MVP does not expose `--force`, `-B`, `--detach`, `--orphan`, or lock options.
|
|
74
79
|
|
|
80
|
+
## ⚙️ Worktree root settings
|
|
81
|
+
|
|
82
|
+
The machine-local user settings file is:
|
|
83
|
+
|
|
84
|
+
```text
|
|
85
|
+
<getAgentDir()>/pi-worktree.json
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
For a default Pi installation this is typically `~/.pi/agent/pi-worktree.json`. Configure it through **Configure worktree root** or edit it manually:
|
|
89
|
+
|
|
90
|
+
```json
|
|
91
|
+
{
|
|
92
|
+
"worktreeRoot": "~/worktrees"
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`worktreeRoot` accepts `~`, a home-prefixed path such as `~/worktrees`, or a native-platform absolute path. It does not expand `$VAR`, `%VAR%`, or other shell syntax. Empty, relative, NUL-containing, non-string, and invalid paths are rejected. There is no project override or extension-specific environment variable.
|
|
97
|
+
|
|
98
|
+
A missing `worktreeRoot` uses `~/.worktrees`. Submitting a blank value in the interactive action removes the override. Unknown JSON fields survive interactive saves and resets. Settings reload on every `session_start`, including `/reload` and workspace replacement; a successful interactive save applies immediately to the next Add flow.
|
|
99
|
+
|
|
100
|
+
Malformed or invalid settings are warned about but never overwritten. An initial failure uses `~/.worktrees`; a later failure retains the last valid effective root. Interactive configuration remains blocked until the invalid file is fixed manually.
|
|
101
|
+
|
|
75
102
|
## 🔀 Pi workspace switching
|
|
76
103
|
|
|
77
104
|
Switching uses Pi's public `SessionManager` and `ctx.switchSession()` APIs:
|
|
@@ -89,11 +116,13 @@ A successfully created Git worktree is never rolled back merely because Pi sessi
|
|
|
89
116
|
|
|
90
117
|
- The main worktree and current worktree cannot be removed.
|
|
91
118
|
- Locked or stale worktrees cannot be removed through this extension.
|
|
92
|
-
- Dirty, untracked,
|
|
119
|
+
- Dirty, untracked, initialized-submodule, and intentional `assume-unchanged`/`skip-worktree` index state causes removal to fail closed. Sparse-checkout-managed `skip-worktree` entries outside the active sparsity rules are allowed when Git's rule checker can confirm them; clear other intentional index flags before removing the worktree.
|
|
120
|
+
- Ignored-only files and directories do not block removal. The confirmation lists them, and the extension rechecks the exact ignored inventory before Git deletes the worktree.
|
|
93
121
|
- A detached HEAD must be reachable from a local branch, tag, or remote ref before removal or prune.
|
|
94
122
|
- Removal and prune inspect reflogs, pseudorefs, per-worktree refs, and `FETCH_HEAD`. Historical commits reachable only through this administrative recovery state are listed by full OID in the destructive confirmation; approval removes those recovery pointers, so Git may later garbage-collect the commits. Create a branch or tag instead when any listed commit should survive.
|
|
95
123
|
- Staged-only administrative index state, a missing attached branch ref, or an unreachable current detached HEAD still blocks prune without an override.
|
|
96
124
|
- Removal never deletes a branch and never uses `--force`.
|
|
125
|
+
- Remove invokes only argv-based `git worktree remove <path>`; production runtime never invokes a shell, `rm`, `rm -rf`, or a Node filesystem directory-deletion API for worktrees.
|
|
97
126
|
- Prune always runs `git worktree prune --dry-run --verbose` before confirmation, inspects candidates omitted from porcelain, rechecks the exact preview and recovery-risk set after confirmation, and uses Git's default expiry. Remove likewise rechecks worktree identity, inventory, administrative path, and the approved recovery-risk set before mutation.
|
|
98
127
|
- The extension does not commit, push, rebase, repair, move, lock, or unlock worktrees.
|
|
99
128
|
|
|
@@ -104,7 +133,7 @@ Use Git directly when you intentionally need force removal, branch deletion, cus
|
|
|
104
133
|
- Git must be installed and the current Pi cwd must be inside a non-bare Git worktree.
|
|
105
134
|
- The command requires a UI-capable Pi mode; print and JSON modes cannot drive its dialogs.
|
|
106
135
|
- Project trust and cwd-bound extension/resource loading during a switch remain owned by Pi.
|
|
107
|
-
- The extension registers no LLM tool, background watcher, settings
|
|
136
|
+
- The extension registers no LLM tool, background watcher, project settings, or statusline item.
|
|
108
137
|
|
|
109
138
|
## 📁 Package layout
|
|
110
139
|
|
|
@@ -114,12 +143,15 @@ extensions/pi-worktree/
|
|
|
114
143
|
│ ├── command.ts
|
|
115
144
|
│ ├── git.ts
|
|
116
145
|
│ ├── session.ts
|
|
146
|
+
│ ├── settings.ts
|
|
117
147
|
│ └── worktree.ts
|
|
118
148
|
├── test/
|
|
119
149
|
│ ├── command.test.ts
|
|
120
150
|
│ ├── git.integration.test.ts
|
|
121
151
|
│ ├── git.test.ts
|
|
122
|
-
│
|
|
152
|
+
│ ├── remove-ignored-command.test.ts
|
|
153
|
+
│ ├── session.test.ts
|
|
154
|
+
│ └── settings.test.ts
|
|
123
155
|
├── package.json
|
|
124
156
|
├── README.md
|
|
125
157
|
├── LICENSE
|
package/package.json
CHANGED
package/src/command.ts
CHANGED
|
@@ -30,21 +30,23 @@ import {
|
|
|
30
30
|
worktreeInventory,
|
|
31
31
|
} from "./git.js";
|
|
32
32
|
import { switchToWorktree } from "./session.js";
|
|
33
|
+
import type { WorktreeSettingsRuntime } from "./settings.js";
|
|
33
34
|
|
|
34
35
|
const ACTION_ADD = "Add worktree";
|
|
35
36
|
const ACTION_SWITCH = "Switch worktree";
|
|
36
37
|
const ACTION_REMOVE = "Remove worktree";
|
|
37
38
|
const ACTION_PRUNE = "Prune stale metadata";
|
|
38
|
-
const
|
|
39
|
+
const ACTION_CONFIGURE_ROOT = "Configure worktree root";
|
|
40
|
+
const ACTIONS = [ACTION_ADD, ACTION_SWITCH, ACTION_REMOVE, ACTION_PRUNE, ACTION_CONFIGURE_ROOT];
|
|
39
41
|
|
|
40
42
|
interface AdministrativeHistoryRisk {
|
|
41
43
|
label: string;
|
|
42
44
|
oids: string[];
|
|
43
45
|
}
|
|
44
46
|
|
|
45
|
-
export function registerWorktreeCommand(pi: ExtensionAPI): void {
|
|
47
|
+
export function registerWorktreeCommand(pi: ExtensionAPI, settings: WorktreeSettingsRuntime): void {
|
|
46
48
|
pi.registerCommand("worktree", {
|
|
47
|
-
description: "Interactively
|
|
49
|
+
description: "Interactively manage Git worktrees and their default root",
|
|
48
50
|
handler: async (args, ctx) => {
|
|
49
51
|
if (args.trim()) {
|
|
50
52
|
safeNotify(
|
|
@@ -63,13 +65,17 @@ export function registerWorktreeCommand(pi: ExtensionAPI): void {
|
|
|
63
65
|
await ctx.waitForIdle();
|
|
64
66
|
const records = await listWorktrees(pi, ctx.cwd, ctx.signal);
|
|
65
67
|
const currentPath = await currentWorktreePath(pi, ctx.cwd, ctx.signal);
|
|
68
|
+
const root = settings.get();
|
|
69
|
+
const warning = root.warning ? " — settings warning" : "";
|
|
66
70
|
const action = await ctx.ui.select(
|
|
67
|
-
stripTerminalControls(
|
|
71
|
+
stripTerminalControls(
|
|
72
|
+
`Git worktrees (${records.length}) — current: ${currentPath}\nWorktree root: ${root.effectiveRoot} (${root.source})${warning}`,
|
|
73
|
+
),
|
|
68
74
|
ACTIONS,
|
|
69
75
|
);
|
|
70
76
|
switch (action) {
|
|
71
77
|
case ACTION_ADD:
|
|
72
|
-
await addFlow(pi, ctx, records);
|
|
78
|
+
await addFlow(pi, ctx, records, root.effectiveRoot);
|
|
73
79
|
return;
|
|
74
80
|
case ACTION_SWITCH:
|
|
75
81
|
await switchFlow(pi, ctx, records, currentPath);
|
|
@@ -80,6 +86,9 @@ export function registerWorktreeCommand(pi: ExtensionAPI): void {
|
|
|
80
86
|
case ACTION_PRUNE:
|
|
81
87
|
await pruneFlow(pi, ctx, records);
|
|
82
88
|
return;
|
|
89
|
+
case ACTION_CONFIGURE_ROOT:
|
|
90
|
+
await configureRootFlow(ctx, settings);
|
|
91
|
+
return;
|
|
83
92
|
}
|
|
84
93
|
} catch (error) {
|
|
85
94
|
safeNotify(ctx, formatError(error), "error");
|
|
@@ -88,10 +97,37 @@ export function registerWorktreeCommand(pi: ExtensionAPI): void {
|
|
|
88
97
|
});
|
|
89
98
|
}
|
|
90
99
|
|
|
100
|
+
async function configureRootFlow(
|
|
101
|
+
ctx: ExtensionCommandContext,
|
|
102
|
+
settings: WorktreeSettingsRuntime,
|
|
103
|
+
): Promise<void> {
|
|
104
|
+
const current = await settings.reload();
|
|
105
|
+
if (!current.canSave) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
current.warning ?? `Fix ${settings.getPath()} before changing pi-worktree settings.`,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
const requested = await ctx.ui.input(
|
|
111
|
+
"Worktree root (blank restores ~/.worktrees)",
|
|
112
|
+
stripTerminalControls(current.configuredRoot ?? current.effectiveRoot),
|
|
113
|
+
);
|
|
114
|
+
if (requested === undefined) return;
|
|
115
|
+
const configuredRoot = requested.trim() || undefined;
|
|
116
|
+
const updated = await settings.save(configuredRoot);
|
|
117
|
+
safeNotify(
|
|
118
|
+
ctx,
|
|
119
|
+
configuredRoot === undefined
|
|
120
|
+
? `Worktree root reset to ${updated.effectiveRoot}.`
|
|
121
|
+
: `Worktree root saved as ${updated.effectiveRoot}.`,
|
|
122
|
+
"info",
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
91
126
|
async function addFlow(
|
|
92
127
|
pi: ExtensionAPI,
|
|
93
128
|
ctx: ExtensionCommandContext,
|
|
94
129
|
records: readonly WorktreeRecord[],
|
|
130
|
+
worktreeRoot: string,
|
|
95
131
|
): Promise<void> {
|
|
96
132
|
const main = records[0];
|
|
97
133
|
if (!main) throw new Error("Git returned no registered worktrees.");
|
|
@@ -133,7 +169,7 @@ async function addFlow(
|
|
|
133
169
|
startOid = await resolveCommit(pi, ctx.cwd, startLabel, ctx.signal);
|
|
134
170
|
}
|
|
135
171
|
|
|
136
|
-
const suggestedPath = defaultWorktreePath(main.path, branch);
|
|
172
|
+
const suggestedPath = defaultWorktreePath(main.path, branch, worktreeRoot);
|
|
137
173
|
const requestedPath = await ctx.ui.input(
|
|
138
174
|
stripTerminalControls(`Worktree path (blank uses ${suggestedPath})`),
|
|
139
175
|
stripTerminalControls(suggestedPath),
|
|
@@ -232,12 +268,7 @@ async function removeFlow(
|
|
|
232
268
|
const candidates = records.filter(
|
|
233
269
|
(record) => !record.isMain && !record.bare && !pathsEqual(record.path, currentPath),
|
|
234
270
|
);
|
|
235
|
-
const selected = await selectWorktree(
|
|
236
|
-
ctx,
|
|
237
|
-
"Remove clean linked worktree",
|
|
238
|
-
candidates,
|
|
239
|
-
currentPath,
|
|
240
|
-
);
|
|
271
|
+
const selected = await selectWorktree(ctx, "Remove linked worktree", candidates, currentPath);
|
|
241
272
|
if (!selected) return;
|
|
242
273
|
if (selected.lockedReason !== undefined) {
|
|
243
274
|
throw new Error(
|
|
@@ -248,10 +279,12 @@ async function removeFlow(
|
|
|
248
279
|
throw new Error("The selected worktree path is stale. Use prune instead of remove.");
|
|
249
280
|
}
|
|
250
281
|
|
|
251
|
-
const inventory =
|
|
252
|
-
|
|
282
|
+
const inventory = classifyRemovalInventory(
|
|
283
|
+
await worktreeInventory(pi, selected.path, ctx.signal),
|
|
284
|
+
);
|
|
285
|
+
if (inventory.protected.length > 0) {
|
|
253
286
|
throw new Error(
|
|
254
|
-
`Removal refused because ${selected.path} contains tracked, untracked,
|
|
287
|
+
`Removal refused because ${selected.path} contains tracked, untracked, index-flagged, or submodule data:\n${inventory.protected.join("\n")}`,
|
|
255
288
|
);
|
|
256
289
|
}
|
|
257
290
|
await assertDetachedHeadIsDurable(pi, ctx, selected);
|
|
@@ -261,17 +294,36 @@ async function removeFlow(
|
|
|
261
294
|
await unreachableAdministrativeHistoryOids(pi, ctx, administrativePath),
|
|
262
295
|
);
|
|
263
296
|
const recoveryWarning = formatAdministrativeRecoveryWarning(approvedHistoryRisks);
|
|
297
|
+
const ignoredWarning = formatIgnoredDataWarning(inventory.ignored);
|
|
298
|
+
const removalWarning =
|
|
299
|
+
ignoredWarning && recoveryWarning
|
|
300
|
+
? `${ignoredWarning}\n${recoveryWarning.trimStart()}`
|
|
301
|
+
: `${ignoredWarning}${recoveryWarning}`;
|
|
302
|
+
const confirmationTitle =
|
|
303
|
+
inventory.ignored.length > 0
|
|
304
|
+
? recoveryWarning
|
|
305
|
+
? "Remove worktree and discard local/recovery data"
|
|
306
|
+
: "Remove worktree and delete ignored files"
|
|
307
|
+
: recoveryWarning
|
|
308
|
+
? "Remove worktree and discard recovery history"
|
|
309
|
+
: "Remove Git worktree";
|
|
264
310
|
if (
|
|
265
311
|
!(await ctx.ui.confirm(
|
|
266
|
-
|
|
267
|
-
stripTerminalControls(
|
|
268
|
-
`Delete the clean worktree directory ${selected.path}? The branch will be preserved.${recoveryWarning}`,
|
|
269
|
-
),
|
|
312
|
+
confirmationTitle,
|
|
313
|
+
`Delete the worktree directory ${stripTerminalControls(selected.path)}? The branch will be preserved.${removalWarning}`,
|
|
270
314
|
))
|
|
271
315
|
) {
|
|
272
316
|
return;
|
|
273
317
|
}
|
|
274
318
|
|
|
319
|
+
await assertAdministrativeHistoryUnchanged(
|
|
320
|
+
pi,
|
|
321
|
+
ctx,
|
|
322
|
+
selected.path,
|
|
323
|
+
administrativePath,
|
|
324
|
+
approvedHistoryRisks,
|
|
325
|
+
);
|
|
326
|
+
|
|
275
327
|
const beforeRemoval = await listWorktrees(pi, ctx.cwd, ctx.signal);
|
|
276
328
|
const latest = beforeRemoval.find((record) => pathsEqual(record.path, selected.path));
|
|
277
329
|
if (!latest) throw new Error(`Worktree ${selected.path} is no longer registered.`);
|
|
@@ -283,30 +335,27 @@ async function removeFlow(
|
|
|
283
335
|
`Worktree ${selected.path} changed state after confirmation; removal was refused.`,
|
|
284
336
|
);
|
|
285
337
|
}
|
|
286
|
-
const latestInventory =
|
|
287
|
-
|
|
338
|
+
const latestInventory = classifyRemovalInventory(
|
|
339
|
+
await worktreeInventory(pi, latest.path, ctx.signal),
|
|
340
|
+
);
|
|
341
|
+
if (latestInventory.protected.length > 0) {
|
|
288
342
|
throw new Error(
|
|
289
|
-
`Removal refused because new local data appeared after confirmation:\n${latestInventory.join("\n")}`,
|
|
343
|
+
`Removal refused because new protected local data appeared after confirmation:\n${latestInventory.protected.join("\n")}`,
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
if (!sameInventory(inventory.ignored, latestInventory.ignored)) {
|
|
347
|
+
throw new Error(
|
|
348
|
+
`Removal refused because ignored data changed after confirmation:\n${latestInventory.ignored.join("\n") || "(none)"}`,
|
|
290
349
|
);
|
|
291
350
|
}
|
|
292
351
|
await assertDetachedHeadIsDurable(pi, ctx, latest);
|
|
293
|
-
|
|
352
|
+
await assertAdministrativeHistoryUnchanged(
|
|
294
353
|
pi,
|
|
354
|
+
ctx,
|
|
295
355
|
latest.path,
|
|
296
|
-
|
|
356
|
+
administrativePath,
|
|
357
|
+
approvedHistoryRisks,
|
|
297
358
|
);
|
|
298
|
-
const latestHistoryRisks = historyRisks(
|
|
299
|
-
latest.path,
|
|
300
|
-
await unreachableAdministrativeHistoryOids(pi, ctx, latestAdministrativePath),
|
|
301
|
-
);
|
|
302
|
-
if (
|
|
303
|
-
!pathsEqual(administrativePath, latestAdministrativePath) ||
|
|
304
|
-
!sameAdministrativeHistoryRisks(approvedHistoryRisks, latestHistoryRisks)
|
|
305
|
-
) {
|
|
306
|
-
throw new Error(
|
|
307
|
-
`Worktree ${selected.path} administrative recovery history changed after confirmation; select it again.`,
|
|
308
|
-
);
|
|
309
|
-
}
|
|
310
359
|
await removeWorktree(pi, ctx.cwd, latest.path, ctx.signal);
|
|
311
360
|
const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
|
|
312
361
|
if (updated.some((record) => pathsEqual(record.path, selected.path))) {
|
|
@@ -350,11 +399,15 @@ async function pruneFlow(
|
|
|
350
399
|
)) {
|
|
351
400
|
await assertDetachedHeadIsDurable(pi, ctx, record);
|
|
352
401
|
}
|
|
402
|
+
const beforePreviewHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
|
|
403
|
+
if (!sameAdministrativeHistoryRisks(approvedHistoryRisks, beforePreviewHistoryRisks)) {
|
|
404
|
+
throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
|
|
405
|
+
}
|
|
353
406
|
const latestPreview = await prunePreview(pi, ctx.cwd, ctx.signal);
|
|
354
|
-
const
|
|
407
|
+
const finalHistoryRisks = await inspectAdministrativePruneCandidates(pi, ctx);
|
|
355
408
|
if (
|
|
356
409
|
latestPreview !== preview ||
|
|
357
|
-
!sameAdministrativeHistoryRisks(approvedHistoryRisks,
|
|
410
|
+
!sameAdministrativeHistoryRisks(approvedHistoryRisks, finalHistoryRisks)
|
|
358
411
|
) {
|
|
359
412
|
throw new Error("Stale worktree metadata changed after confirmation; run prune again.");
|
|
360
413
|
}
|
|
@@ -366,6 +419,32 @@ async function pruneFlow(
|
|
|
366
419
|
);
|
|
367
420
|
}
|
|
368
421
|
|
|
422
|
+
async function assertAdministrativeHistoryUnchanged(
|
|
423
|
+
pi: ExtensionAPI,
|
|
424
|
+
ctx: ExtensionCommandContext,
|
|
425
|
+
selectedPath: string,
|
|
426
|
+
approvedAdministrativePath: string,
|
|
427
|
+
approvedHistoryRisks: readonly AdministrativeHistoryRisk[],
|
|
428
|
+
): Promise<void> {
|
|
429
|
+
const latestAdministrativePath = await worktreeAdministrativeDirectory(
|
|
430
|
+
pi,
|
|
431
|
+
selectedPath,
|
|
432
|
+
ctx.signal,
|
|
433
|
+
);
|
|
434
|
+
const latestHistoryRisks = historyRisks(
|
|
435
|
+
selectedPath,
|
|
436
|
+
await unreachableAdministrativeHistoryOids(pi, ctx, latestAdministrativePath),
|
|
437
|
+
);
|
|
438
|
+
if (
|
|
439
|
+
!pathsEqual(approvedAdministrativePath, latestAdministrativePath) ||
|
|
440
|
+
!sameAdministrativeHistoryRisks(approvedHistoryRisks, latestHistoryRisks)
|
|
441
|
+
) {
|
|
442
|
+
throw new Error(
|
|
443
|
+
`Worktree ${selectedPath} administrative recovery history changed after confirmation; select it again.`,
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
369
448
|
async function inspectAdministrativePruneCandidates(
|
|
370
449
|
pi: ExtensionAPI,
|
|
371
450
|
ctx: ExtensionCommandContext,
|
|
@@ -440,10 +519,45 @@ function sameAdministrativeHistoryRisks(
|
|
|
440
519
|
|
|
441
520
|
function formatAdministrativeRecoveryWarning(risks: readonly AdministrativeHistoryRisk[]): string {
|
|
442
521
|
if (risks.length === 0) return "";
|
|
443
|
-
const entries = risks
|
|
522
|
+
const entries = risks
|
|
523
|
+
.map(
|
|
524
|
+
(risk) =>
|
|
525
|
+
`${stripTerminalControls(risk.label)}: ${risk.oids.map(stripTerminalControls).join(", ")}`,
|
|
526
|
+
)
|
|
527
|
+
.join("; ");
|
|
444
528
|
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.`;
|
|
445
529
|
}
|
|
446
530
|
|
|
531
|
+
interface RemovalInventory {
|
|
532
|
+
ignored: string[];
|
|
533
|
+
protected: string[];
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function classifyRemovalInventory(lines: readonly string[]): RemovalInventory {
|
|
537
|
+
const ignored: string[] = [];
|
|
538
|
+
const protectedData: string[] = [];
|
|
539
|
+
for (const line of lines) {
|
|
540
|
+
(line.startsWith("!! ") ? ignored : protectedData).push(line);
|
|
541
|
+
}
|
|
542
|
+
return {
|
|
543
|
+
ignored: normalizeInventory(ignored),
|
|
544
|
+
protected: normalizeInventory(protectedData),
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function normalizeInventory(lines: readonly string[]): string[] {
|
|
549
|
+
return [...new Set(lines)].sort();
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function sameInventory(left: readonly string[], right: readonly string[]): boolean {
|
|
553
|
+
return JSON.stringify(normalizeInventory(left)) === JSON.stringify(normalizeInventory(right));
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function formatIgnoredDataWarning(ignored: readonly string[]): string {
|
|
557
|
+
if (ignored.length === 0) return "";
|
|
558
|
+
return ` Ignored files and directories that will be deleted:\n${ignored.map(stripTerminalControls).join("\n")}`;
|
|
559
|
+
}
|
|
560
|
+
|
|
447
561
|
async function assertDetachedHeadIsDurable(
|
|
448
562
|
pi: ExtensionAPI,
|
|
449
563
|
ctx: ExtensionCommandContext,
|
package/src/git.ts
CHANGED
|
@@ -120,11 +120,12 @@ export function worktreeForBranch(
|
|
|
120
120
|
return records.find((record) => record.branchRef === branchRef);
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
-
export function defaultWorktreePath(
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
123
|
+
export function defaultWorktreePath(
|
|
124
|
+
mainWorktreePath: string,
|
|
125
|
+
branch: string,
|
|
126
|
+
worktreeRoot: string,
|
|
127
|
+
): string {
|
|
128
|
+
return resolve(worktreeRoot, basename(mainWorktreePath), branch.replaceAll("/", "-"));
|
|
128
129
|
}
|
|
129
130
|
|
|
130
131
|
export function buildAddArguments(input: AddArguments): string[] {
|
package/src/settings.ts
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join, posix, win32 } from "node:path";
|
|
4
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
|
|
6
|
+
export const SETTINGS_FILE = "pi-worktree.json";
|
|
7
|
+
|
|
8
|
+
export type WorktreeSettingsSource = "default" | "user";
|
|
9
|
+
|
|
10
|
+
export interface LoadedWorktreeSettings {
|
|
11
|
+
kind: "missing" | "loaded" | "invalid";
|
|
12
|
+
path: string;
|
|
13
|
+
effectiveRoot: string;
|
|
14
|
+
source: WorktreeSettingsSource;
|
|
15
|
+
configuredRoot?: string;
|
|
16
|
+
document?: Record<string, unknown>;
|
|
17
|
+
warning?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface WorktreeSettingsState {
|
|
21
|
+
effectiveRoot: string;
|
|
22
|
+
source: WorktreeSettingsSource;
|
|
23
|
+
configuredRoot?: string;
|
|
24
|
+
warning?: string;
|
|
25
|
+
canSave: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface SettingsFileOperations {
|
|
29
|
+
write(path: string, data: string): Promise<void>;
|
|
30
|
+
rename(source: string, destination: string): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface WorktreeSettingsRuntime {
|
|
34
|
+
get(): Readonly<WorktreeSettingsState>;
|
|
35
|
+
getPath(): string;
|
|
36
|
+
reload(): Promise<Readonly<WorktreeSettingsState>>;
|
|
37
|
+
save(configuredRoot: string | undefined): Promise<Readonly<WorktreeSettingsState>>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface RuntimeOptions {
|
|
41
|
+
path?: string | (() => string);
|
|
42
|
+
home?: string;
|
|
43
|
+
platform?: NodeJS.Platform;
|
|
44
|
+
operations?: Partial<SettingsFileOperations>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const DEFAULT_FILE_OPERATIONS: SettingsFileOperations = {
|
|
48
|
+
write: (path, data) =>
|
|
49
|
+
writeFile(path, data, { encoding: "utf8", flag: "wx", mode: 0o600 }).then(() => undefined),
|
|
50
|
+
rename,
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export function settingsFilePath(): string {
|
|
54
|
+
return join(getAgentDir(), SETTINGS_FILE);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function defaultWorktreeRoot(
|
|
58
|
+
home = homedir(),
|
|
59
|
+
platform: NodeJS.Platform = process.platform,
|
|
60
|
+
): string {
|
|
61
|
+
return platformPath(platform).join(home, ".worktrees");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function resolveWorktreeRoot(
|
|
65
|
+
value: string,
|
|
66
|
+
home = homedir(),
|
|
67
|
+
platform: NodeJS.Platform = process.platform,
|
|
68
|
+
): string {
|
|
69
|
+
if (!value || value.includes("\0")) {
|
|
70
|
+
throw new Error("worktreeRoot must be a non-empty path without NUL characters.");
|
|
71
|
+
}
|
|
72
|
+
if (hasShellVariableSyntax(value)) {
|
|
73
|
+
throw new Error("worktreeRoot must not contain shell variable syntax.");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const path = platformPath(platform);
|
|
77
|
+
let candidate = value;
|
|
78
|
+
if (value === "~") {
|
|
79
|
+
candidate = home;
|
|
80
|
+
} else if (value.startsWith("~/") || (platform === "win32" && value.startsWith("~\\"))) {
|
|
81
|
+
candidate = path.resolve(home, value.slice(2));
|
|
82
|
+
} else if (value.startsWith("~")) {
|
|
83
|
+
throw new Error("worktreeRoot supports only ~ itself or a path beginning with ~/.");
|
|
84
|
+
}
|
|
85
|
+
if (!path.isAbsolute(candidate)) {
|
|
86
|
+
throw new Error("worktreeRoot must be an absolute path or begin with ~/.");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
const normalized = path.normalize(candidate);
|
|
91
|
+
if (!normalized || !path.isAbsolute(normalized)) {
|
|
92
|
+
throw new Error("normalization did not produce an absolute path");
|
|
93
|
+
}
|
|
94
|
+
return normalized;
|
|
95
|
+
} catch (error) {
|
|
96
|
+
throw new Error(`worktreeRoot could not be normalized: ${formatError(error)}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function loadWorktreeSettings(
|
|
101
|
+
path = settingsFilePath(),
|
|
102
|
+
home = homedir(),
|
|
103
|
+
platform: NodeJS.Platform = process.platform,
|
|
104
|
+
): Promise<LoadedWorktreeSettings> {
|
|
105
|
+
const fallback = defaultWorktreeRoot(home, platform);
|
|
106
|
+
let text: string;
|
|
107
|
+
try {
|
|
108
|
+
const stats = await lstat(path);
|
|
109
|
+
if (stats.isSymbolicLink()) return invalid(path, fallback, "symbolic links are not accepted");
|
|
110
|
+
if (!stats.isFile()) return invalid(path, fallback, "settings path is not a regular file");
|
|
111
|
+
text = await readFile(path, "utf8");
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
114
|
+
return {
|
|
115
|
+
kind: "missing",
|
|
116
|
+
path,
|
|
117
|
+
effectiveRoot: fallback,
|
|
118
|
+
source: "default",
|
|
119
|
+
document: {},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
return invalid(path, fallback, formatError(error));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
try {
|
|
126
|
+
const document = JSON.parse(text) as unknown;
|
|
127
|
+
if (!isRecord(document)) return invalid(path, fallback, "the top level must be a JSON object");
|
|
128
|
+
if (!Object.hasOwn(document, "worktreeRoot")) {
|
|
129
|
+
return {
|
|
130
|
+
kind: "loaded",
|
|
131
|
+
path,
|
|
132
|
+
effectiveRoot: fallback,
|
|
133
|
+
source: "default",
|
|
134
|
+
document,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
if (typeof document.worktreeRoot !== "string") {
|
|
138
|
+
return invalid(path, fallback, "worktreeRoot must be a string");
|
|
139
|
+
}
|
|
140
|
+
const effectiveRoot = resolveWorktreeRoot(document.worktreeRoot, home, platform);
|
|
141
|
+
return {
|
|
142
|
+
kind: "loaded",
|
|
143
|
+
path,
|
|
144
|
+
effectiveRoot,
|
|
145
|
+
source: "user",
|
|
146
|
+
configuredRoot: document.worktreeRoot,
|
|
147
|
+
document,
|
|
148
|
+
};
|
|
149
|
+
} catch (error) {
|
|
150
|
+
return invalid(path, fallback, formatError(error));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function saveWorktreeSettings(
|
|
155
|
+
document: Record<string, unknown>,
|
|
156
|
+
configuredRoot: string | undefined,
|
|
157
|
+
path = settingsFilePath(),
|
|
158
|
+
operations: Partial<SettingsFileOperations> = {},
|
|
159
|
+
): Promise<Record<string, unknown>> {
|
|
160
|
+
const nextDocument = { ...document };
|
|
161
|
+
if (configuredRoot === undefined) delete nextDocument.worktreeRoot;
|
|
162
|
+
else nextDocument.worktreeRoot = configuredRoot;
|
|
163
|
+
|
|
164
|
+
await mkdir(dirname(path), { recursive: true });
|
|
165
|
+
const temporaryPath = temporaryFilePath(path);
|
|
166
|
+
try {
|
|
167
|
+
await (operations.write ?? DEFAULT_FILE_OPERATIONS.write)(
|
|
168
|
+
temporaryPath,
|
|
169
|
+
`${JSON.stringify(nextDocument, null, 2)}\n`,
|
|
170
|
+
);
|
|
171
|
+
await (operations.rename ?? DEFAULT_FILE_OPERATIONS.rename)(temporaryPath, path);
|
|
172
|
+
return nextDocument;
|
|
173
|
+
} catch (error) {
|
|
174
|
+
await unlink(temporaryPath).catch(() => undefined);
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function createWorktreeSettingsRuntime(
|
|
180
|
+
options: RuntimeOptions = {},
|
|
181
|
+
): WorktreeSettingsRuntime {
|
|
182
|
+
const home = options.home ?? homedir();
|
|
183
|
+
const platform = options.platform ?? process.platform;
|
|
184
|
+
let resolvedPath: string | undefined;
|
|
185
|
+
const getPath = () => {
|
|
186
|
+
resolvedPath ??=
|
|
187
|
+
typeof options.path === "function" ? options.path() : (options.path ?? settingsFilePath());
|
|
188
|
+
return resolvedPath;
|
|
189
|
+
};
|
|
190
|
+
let document: Record<string, unknown> = {};
|
|
191
|
+
let operationQueue = Promise.resolve();
|
|
192
|
+
const enqueue = <T>(operation: () => Promise<T>): Promise<T> => {
|
|
193
|
+
const result = operationQueue.then(operation, operation);
|
|
194
|
+
operationQueue = result.then(
|
|
195
|
+
() => undefined,
|
|
196
|
+
() => undefined,
|
|
197
|
+
);
|
|
198
|
+
return result;
|
|
199
|
+
};
|
|
200
|
+
let state: WorktreeSettingsState = {
|
|
201
|
+
effectiveRoot: defaultWorktreeRoot(home, platform),
|
|
202
|
+
source: "default",
|
|
203
|
+
canSave: true,
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
get: () => Object.freeze({ ...state }),
|
|
208
|
+
getPath,
|
|
209
|
+
reload() {
|
|
210
|
+
return enqueue(async () => {
|
|
211
|
+
const loaded = await loadWorktreeSettings(getPath(), home, platform);
|
|
212
|
+
if (loaded.kind === "invalid") {
|
|
213
|
+
state = { ...state, warning: loaded.warning, canSave: false };
|
|
214
|
+
return Object.freeze({ ...state });
|
|
215
|
+
}
|
|
216
|
+
document = loaded.document ?? {};
|
|
217
|
+
state = stateFromLoaded(loaded);
|
|
218
|
+
return Object.freeze({ ...state });
|
|
219
|
+
});
|
|
220
|
+
},
|
|
221
|
+
save(configuredRoot) {
|
|
222
|
+
return enqueue(async () => {
|
|
223
|
+
if (!state.canSave) {
|
|
224
|
+
throw new Error(`Fix the pi-worktree settings file at ${getPath()} before changing it.`);
|
|
225
|
+
}
|
|
226
|
+
const effectiveRoot =
|
|
227
|
+
configuredRoot === undefined
|
|
228
|
+
? defaultWorktreeRoot(home, platform)
|
|
229
|
+
: resolveWorktreeRoot(configuredRoot, home, platform);
|
|
230
|
+
const nextDocument = await saveWorktreeSettings(
|
|
231
|
+
document,
|
|
232
|
+
configuredRoot,
|
|
233
|
+
getPath(),
|
|
234
|
+
options.operations,
|
|
235
|
+
);
|
|
236
|
+
document = nextDocument;
|
|
237
|
+
state = {
|
|
238
|
+
effectiveRoot,
|
|
239
|
+
source: configuredRoot === undefined ? "default" : "user",
|
|
240
|
+
...(configuredRoot === undefined ? {} : { configuredRoot }),
|
|
241
|
+
canSave: true,
|
|
242
|
+
};
|
|
243
|
+
return Object.freeze({ ...state });
|
|
244
|
+
});
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function stateFromLoaded(loaded: LoadedWorktreeSettings): WorktreeSettingsState {
|
|
250
|
+
return {
|
|
251
|
+
effectiveRoot: loaded.effectiveRoot,
|
|
252
|
+
source: loaded.source,
|
|
253
|
+
...(loaded.configuredRoot === undefined ? {} : { configuredRoot: loaded.configuredRoot }),
|
|
254
|
+
...(loaded.warning === undefined ? {} : { warning: loaded.warning }),
|
|
255
|
+
canSave: true,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function invalid(path: string, fallback: string, reason: string): LoadedWorktreeSettings {
|
|
260
|
+
return {
|
|
261
|
+
kind: "invalid",
|
|
262
|
+
path,
|
|
263
|
+
effectiveRoot: fallback,
|
|
264
|
+
source: "default",
|
|
265
|
+
warning: `${SETTINGS_FILE} ignored (${path}: ${reason}); using the safe default or last valid root without overwriting the file.`,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function platformPath(platform: NodeJS.Platform): typeof posix | typeof win32 {
|
|
270
|
+
return platform === "win32" ? win32 : posix;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function hasShellVariableSyntax(value: string): boolean {
|
|
274
|
+
return /\$|%[^%]+%/u.test(value);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function temporaryFilePath(path: string): string {
|
|
278
|
+
return `${path}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
282
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
|
286
|
+
return error instanceof Error && "code" in error;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function formatError(error: unknown): string {
|
|
290
|
+
return error instanceof Error ? error.message : String(error);
|
|
291
|
+
}
|
package/src/worktree.ts
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { registerWorktreeCommand } from "./command.js";
|
|
3
|
+
import {
|
|
4
|
+
createWorktreeSettingsRuntime,
|
|
5
|
+
settingsFilePath,
|
|
6
|
+
type WorktreeSettingsRuntime,
|
|
7
|
+
} from "./settings.js";
|
|
3
8
|
|
|
4
|
-
|
|
5
|
-
|
|
9
|
+
interface WorktreeExtensionOptions {
|
|
10
|
+
settings?: WorktreeSettingsRuntime;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export default function worktreeExtension(
|
|
14
|
+
pi: ExtensionAPI,
|
|
15
|
+
options: WorktreeExtensionOptions = {},
|
|
16
|
+
): void {
|
|
17
|
+
const settings = options.settings ?? createWorktreeSettingsRuntime({ path: settingsFilePath });
|
|
18
|
+
registerWorktreeCommand(pi, settings);
|
|
19
|
+
|
|
20
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
21
|
+
const loaded = await settings.reload();
|
|
22
|
+
if (!loaded.warning || !ctx.hasUI) return;
|
|
23
|
+
try {
|
|
24
|
+
ctx.ui.notify(loaded.warning, "warning");
|
|
25
|
+
} catch {
|
|
26
|
+
// A replacement session may invalidate its predecessor context during async startup.
|
|
27
|
+
}
|
|
28
|
+
});
|
|
6
29
|
}
|