@narumitw/pi-worktree 0.31.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -56,7 +56,12 @@ Choose one action:
56
56
  - **Prune stale metadata** — inspect Git's dry-run output, then optionally run the matching prune.
57
57
  - **Configure worktree root** — set a machine-local default root or submit a blank value to restore `~/.worktrees`.
58
58
 
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.
59
+ The standard root menu shows the registered count, current path, effective worktree root, its source,
60
+ and any settings warning. Escape closes it. `/worktree` intentionally does not accept text
61
+ subcommands or expose argument autocomplete. Every change is initiated and confirmed through TUI or
62
+ RPC dialogs; print and JSON modes reject the command observably. Operation-specific branch/path
63
+ inputs, worktree identity selectors, preflight previews, and destructive confirmations remain
64
+ extension-owned because they carry Git safety and commit-aware revalidation.
60
65
 
61
66
  ## 🌿 Add defaults
62
67
 
@@ -95,9 +100,9 @@ For a default Pi installation this is typically `~/.pi/agent/pi-worktree.json`.
95
100
 
96
101
  `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
102
 
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.
103
+ A missing `worktreeRoot` uses `~/.worktrees`; the settings file is created only by a successful interactive change. Submitting a blank value in the interactive action removes the override. Within one Pi process, queued saves run in invocation order, reread the latest valid document immediately before merging `worktreeRoot`, and preserve concurrent unknown-field edits. Settings reload on every `session_start`, including `/reload` and workspace replacement; a successful interactive save applies immediately to the next Add flow.
99
104
 
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.
105
+ Malformed or invalid settings are warned about but never overwritten, including an invalid edit made while a settings action is open. 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. Failed publication leaves the prior file and effective runtime root unchanged, and the save queue remains usable after rejection.
101
106
 
102
107
  ## 🔀 Pi workspace switching
103
108
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-worktree",
3
- "version": "0.31.0",
3
+ "version": "0.38.0",
4
4
  "description": "Pi extension for safe interactive Git worktree management and workspace switching.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -41,5 +41,8 @@
41
41
  "type": "git",
42
42
  "url": "https://github.com/narumiruna/pi-extensions",
43
43
  "directory": "extensions/pi-worktree"
44
+ },
45
+ "dependencies": {
46
+ "@narumitw/pi-tui-kit": "<1"
44
47
  }
45
48
  }
package/src/command.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
3
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
4
+ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
4
5
  import {
5
6
  addWorktree,
6
7
  administrativeHistoryOids,
@@ -37,14 +38,29 @@ const ACTION_SWITCH = "Switch worktree";
37
38
  const ACTION_REMOVE = "Remove worktree";
38
39
  const ACTION_PRUNE = "Prune stale metadata";
39
40
  const ACTION_CONFIGURE_ROOT = "Configure worktree root";
40
- const ACTIONS = [ACTION_ADD, ACTION_SWITCH, ACTION_REMOVE, ACTION_PRUNE, ACTION_CONFIGURE_ROOT];
41
+ const ACTIONS = {
42
+ add: ACTION_ADD,
43
+ switch: ACTION_SWITCH,
44
+ remove: ACTION_REMOVE,
45
+ prune: ACTION_PRUNE,
46
+ configure: ACTION_CONFIGURE_ROOT,
47
+ } as const;
48
+
49
+ interface WorktreeMenuOwner {
50
+ signal: AbortSignal;
51
+ isCurrent(): boolean;
52
+ }
41
53
 
42
54
  interface AdministrativeHistoryRisk {
43
55
  label: string;
44
56
  oids: string[];
45
57
  }
46
58
 
47
- export function registerWorktreeCommand(pi: ExtensionAPI, settings: WorktreeSettingsRuntime): void {
59
+ export function registerWorktreeCommand(
60
+ pi: ExtensionAPI,
61
+ settings: WorktreeSettingsRuntime,
62
+ getMenuOwner: () => WorktreeMenuOwner,
63
+ ): void {
48
64
  pi.registerCommand("worktree", {
49
65
  description: "Interactively manage Git worktrees and their default root",
50
66
  handler: async (args, ctx) => {
@@ -57,7 +73,7 @@ export function registerWorktreeCommand(pi: ExtensionAPI, settings: WorktreeSett
57
73
  return;
58
74
  }
59
75
  if (!ctx.hasUI) {
60
- safeNotify(ctx, "/worktree requires an interactive Pi UI.", "error");
76
+ safeNotify(ctx, "/worktree requires TUI or RPC mode.", "error");
61
77
  return;
62
78
  }
63
79
 
@@ -67,29 +83,49 @@ export function registerWorktreeCommand(pi: ExtensionAPI, settings: WorktreeSett
67
83
  const currentPath = await currentWorktreePath(pi, ctx.cwd, ctx.signal);
68
84
  const root = settings.get();
69
85
  const warning = root.warning ? " — settings warning" : "";
70
- const action = await ctx.ui.select(
71
- stripTerminalControls(
72
- `Git worktrees (${records.length}) — current: ${currentPath}\nWorktree root: ${root.effectiveRoot} (${root.source})${warning}`,
73
- ),
74
- ACTIONS,
75
- );
76
- switch (action) {
77
- case ACTION_ADD:
78
- await addFlow(pi, ctx, records, root.effectiveRoot);
79
- return;
80
- case ACTION_SWITCH:
81
- await switchFlow(pi, ctx, records, currentPath);
82
- return;
83
- case ACTION_REMOVE:
84
- await removeFlow(pi, ctx, records, currentPath);
85
- return;
86
- case ACTION_PRUNE:
87
- await pruneFlow(pi, ctx, records);
88
- return;
89
- case ACTION_CONFIGURE_ROOT:
90
- await configureRootFlow(ctx, settings);
91
- return;
92
- }
86
+ const owner = getMenuOwner();
87
+ const runFlow = async (flow: () => Promise<void>) => {
88
+ try {
89
+ await flow();
90
+ } catch (error) {
91
+ safeNotify(ctx, formatError(error), "error");
92
+ }
93
+ return { kind: "close" } as const;
94
+ };
95
+ type Screen = "main";
96
+ type Action = keyof typeof ACTIONS;
97
+ const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
98
+ start: "main",
99
+ screens: {
100
+ main: () => ({
101
+ kind: "actions",
102
+ title: "Git worktrees",
103
+ lines: [
104
+ `Registered: ${records.length}`,
105
+ `Current: ${currentPath}`,
106
+ `Worktree root: ${root.effectiveRoot} (${root.source})${warning}`,
107
+ ],
108
+ items: Object.entries(ACTIONS).map(([id, label]) => ({
109
+ id,
110
+ label,
111
+ action: id as Action,
112
+ })),
113
+ hint: "close",
114
+ }),
115
+ },
116
+ actions: {
117
+ add: async () => runFlow(() => addFlow(pi, ctx, records, root.effectiveRoot)),
118
+ switch: async () => runFlow(() => switchFlow(pi, ctx, records, currentPath)),
119
+ remove: async () => runFlow(() => removeFlow(pi, ctx, records, currentPath)),
120
+ prune: async () => runFlow(() => pruneFlow(pi, ctx, records)),
121
+ configure: async () => runFlow(() => configureRootFlow(ctx, settings)),
122
+ },
123
+ });
124
+ await runMenu(ctx, menu, {
125
+ getState: () => undefined,
126
+ signal: owner.signal,
127
+ isCurrent: owner.isCurrent,
128
+ });
93
129
  } catch (error) {
94
130
  safeNotify(ctx, formatError(error), "error");
95
131
  }
package/src/settings.ts CHANGED
@@ -35,6 +35,7 @@ export interface WorktreeSettingsRuntime {
35
35
  getPath(): string;
36
36
  reload(): Promise<Readonly<WorktreeSettingsState>>;
37
37
  save(configuredRoot: string | undefined): Promise<Readonly<WorktreeSettingsState>>;
38
+ flush?(): Promise<void>;
38
39
  }
39
40
 
40
41
  interface RuntimeOptions {
@@ -187,7 +188,6 @@ export function createWorktreeSettingsRuntime(
187
188
  typeof options.path === "function" ? options.path() : (options.path ?? settingsFilePath());
188
189
  return resolvedPath;
189
190
  };
190
- let document: Record<string, unknown> = {};
191
191
  let operationQueue = Promise.resolve();
192
192
  const enqueue = <T>(operation: () => Promise<T>): Promise<T> => {
193
193
  const result = operationQueue.then(operation, operation);
@@ -206,6 +206,9 @@ export function createWorktreeSettingsRuntime(
206
206
  return {
207
207
  get: () => Object.freeze({ ...state }),
208
208
  getPath,
209
+ async flush() {
210
+ await operationQueue;
211
+ },
209
212
  reload() {
210
213
  return enqueue(async () => {
211
214
  const loaded = await loadWorktreeSettings(getPath(), home, platform);
@@ -213,7 +216,6 @@ export function createWorktreeSettingsRuntime(
213
216
  state = { ...state, warning: loaded.warning, canSave: false };
214
217
  return Object.freeze({ ...state });
215
218
  }
216
- document = loaded.document ?? {};
217
219
  state = stateFromLoaded(loaded);
218
220
  return Object.freeze({ ...state });
219
221
  });
@@ -227,13 +229,17 @@ export function createWorktreeSettingsRuntime(
227
229
  configuredRoot === undefined
228
230
  ? defaultWorktreeRoot(home, platform)
229
231
  : resolveWorktreeRoot(configuredRoot, home, platform);
230
- const nextDocument = await saveWorktreeSettings(
231
- document,
232
+ const latest = await loadWorktreeSettings(getPath(), home, platform);
233
+ if (latest.kind === "invalid") {
234
+ state = { ...state, warning: latest.warning, canSave: false };
235
+ throw new Error(`Fix the pi-worktree settings file at ${getPath()} before changing it.`);
236
+ }
237
+ await saveWorktreeSettings(
238
+ latest.document ?? {},
232
239
  configuredRoot,
233
240
  getPath(),
234
241
  options.operations,
235
242
  );
236
- document = nextDocument;
237
243
  state = {
238
244
  effectiveRoot,
239
245
  source: configuredRoot === undefined ? "default" : "user",
package/src/worktree.ts CHANGED
@@ -15,15 +15,27 @@ export default function worktreeExtension(
15
15
  options: WorktreeExtensionOptions = {},
16
16
  ): void {
17
17
  const settings = options.settings ?? createWorktreeSettingsRuntime({ path: settingsFilePath });
18
- registerWorktreeCommand(pi, settings);
18
+ let sessionGeneration = 0;
19
+ let menuController = new AbortController();
20
+ registerWorktreeCommand(pi, settings, () => {
21
+ const generation = sessionGeneration;
22
+ return {
23
+ signal: menuController.signal,
24
+ isCurrent: () => generation === sessionGeneration && !menuController.signal.aborted,
25
+ };
26
+ });
19
27
 
20
28
  pi.on("session_start", async (_event, ctx) => {
29
+ const generation = ++sessionGeneration;
30
+ menuController.abort(new DOMException("Worktree session replaced", "AbortError"));
31
+ menuController = new AbortController();
21
32
  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
- }
33
+ if (generation !== sessionGeneration || !loaded.warning || !ctx.hasUI) return;
34
+ ctx.ui.notify(loaded.warning, "warning");
35
+ });
36
+ pi.on("session_shutdown", async () => {
37
+ sessionGeneration += 1;
38
+ menuController.abort(new DOMException("Worktree session shut down", "AbortError"));
39
+ await settings.flush?.();
28
40
  });
29
41
  }