git_worktree_manager/operations/
setup_claude.rs1use std::path::PathBuf;
3
4use console::style;
5
6use crate::constants::home_dir_or_fallback;
7use crate::error::Result;
8
9const SKILL_DIR: &str = "gw";
10const LEGACY_SKILL_DIR: &str = "gw-delegate";
11const SKILL_FILE: &str = "SKILL.md";
12const REFERENCE_FILE: &str = "gw-commands.md";
13
14fn skill_dir() -> PathBuf {
16 home_dir_or_fallback()
17 .join(".claude")
18 .join("skills")
19 .join(SKILL_DIR)
20}
21
22pub fn skill_path() -> PathBuf {
24 skill_dir().join(SKILL_FILE)
25}
26
27fn reference_path() -> PathBuf {
29 skill_dir().join("references").join(REFERENCE_FILE)
30}
31
32pub fn is_skill_installed() -> bool {
34 skill_path().exists()
35}
36
37fn write_if_changed(
40 path: &PathBuf,
41 new_content: &str,
42) -> std::result::Result<bool, std::io::Error> {
43 if path.exists() {
44 let existing = std::fs::read_to_string(path).unwrap_or_default();
45 if existing == new_content {
46 return Ok(false);
47 }
48 }
49 if let Some(parent) = path.parent() {
50 std::fs::create_dir_all(parent)?;
51 }
52 std::fs::write(path, new_content)?;
53 Ok(true)
54}
55
56fn remove_legacy_skill() {
58 let legacy_dir = home_dir_or_fallback()
59 .join(".claude")
60 .join("skills")
61 .join(LEGACY_SKILL_DIR);
62 if legacy_dir.exists() {
63 let _ = std::fs::remove_dir_all(&legacy_dir);
64 }
65}
66
67pub fn setup_claude() -> Result<()> {
69 remove_legacy_skill();
70
71 let skill = skill_path();
72 let reference = reference_path();
73
74 let skill_changed = write_if_changed(&skill, skill_content())?;
75 let ref_changed = write_if_changed(&reference, reference_content())?;
76
77 if !skill_changed && !ref_changed {
78 println!(
79 "{} Claude Code skill is already up to date.\n",
80 style("*").green()
81 );
82 println!(" Location: {}", style(skill_dir().display()).dim());
83 return Ok(());
84 }
85
86 let action = if !skill_changed && ref_changed {
87 "updated"
88 } else if skill.exists() && skill_changed {
89 "updated"
91 } else {
92 "installed"
93 };
94
95 println!(
96 "{} Claude Code skill {} successfully!\n",
97 style("*").green().bold(),
98 action
99 );
100 println!(" Location: {}", style(skill_dir().display()).dim());
101 println!(
102 " Use {} in Claude Code to delegate tasks to worktrees.",
103 style("/gw").cyan()
104 );
105 println!(
106 " Or just ask Claude about {} — it will use gw automatically.\n",
107 style("worktree management").cyan()
108 );
109
110 Ok(())
111}
112
113fn skill_content() -> &'static str {
114 r#"---
115name: gw
116description: "Delegate coding tasks to isolated git worktrees. Invoke with: /gw <natural language task description>. Also handles worktree management: list, sync, clean, PR, merge, etc."
117allowed-tools: Bash
118---
119
120# git-worktree-manager (gw)
121
122CLI tool integrating git worktree with AI coding assistants. Single binary, ~3ms startup.
123
124## Natural Language Task Delegation
125
126When the user invokes `/gw <task description>` (e.g., `/gw fix the auth token expiration bug`), follow these steps:
127
128### Step 1: Parse the user's intent
129From the natural language input, determine:
130- **Task description** — what to pass as `--prompt`
131- **Branch name** — generate a short, descriptive branch name from the task (e.g., `fix-auth-token-expiration`). Use conventional prefixes: `fix-`, `feat-`, `refactor-`, `docs-`, `test-`, `chore-`.
132- **Base branch** — use the default unless the user specifies otherwise
133
134### Step 2: Confirm and execute
135Show the user what you're about to run, then execute:
136```bash
137gw new <branch-name> -T <terminal-method> --prompt "<task description>"
138```
139
140### Branch name rules
141- Lowercase, hyphen-separated, max ~50 chars
142- Strip filler words (the, a, an, for, in, on, etc.)
143- Examples:
144 - "Fix the JWT token expiration check in auth" → `fix-jwt-token-expiration`
145 - "Add user avatar upload feature" → `feat-avatar-upload`
146 - "Refactor the database connection pool" → `refactor-db-connection-pool`
147
148### Terminal method selection
149- **Default: omit the `-T` flag** to use the system default (`gw config get launch.method`). Only add `-T` if the user explicitly requests a specific terminal method.
150- If the user explicitly asks for a specific method, use it. Common methods: `w-t` (WezTerm tab), `w-t-b` (WezTerm tab, background — no focus steal), `i-t` (iTerm2 tab), `t` (tmux session), `d` (detached/background)
151- Once the user specifies a method, remember it for subsequent calls in the same session.
152
153## Quick Reference
154
155| Command | Description |
156|---------|-------------|
157| `gw new <branch> [--prompt "..."]` | Create worktree + optionally launch AI with task |
158| `gw delete <branch>` | Delete worktree and branch |
159| `gw list` | List all worktrees with status |
160| `gw status` | Show current worktree info |
161| `gw resume [branch]` | Resume AI session in worktree |
162| `gw pr [branch]` | Create GitHub Pull Request |
163| `gw merge [branch]` | Merge branch into base |
164| `gw sync [--all]` | Rebase worktree(s) onto base branch |
165| `gw clean [--merged]` | Batch cleanup of worktrees |
166| `gw diff <b1> <b2>` | Compare two branches |
167| `gw change-base <new> [branch]` | Change base branch |
168| `gw config <action>` | Configuration management |
169| `gw doctor` | Run diagnostics |
170| `gw tree` / `gw stats` | Visual hierarchy / statistics |
171| `gw backup <action>` | Backup and restore worktrees |
172| `gw stash <action>` | Worktree-aware stash management |
173| `gw shell [worktree]` | Open shell in worktree |
174
175## Delegate a task to a new worktree
176
177```bash
178gw new <branch-name> -T <terminal-method> --prompt "<task description>"
179```
180
181Example:
182```bash
183gw new fix-auth -T w-t --prompt "Fix JWT token expiration check in src/auth.rs"
184```
185
186This will:
1871. Create a new git worktree on a new branch based on the current base branch
1882. Open a new terminal (e.g. WezTerm tab)
1893. Start Claude Code with the given prompt in interactive mode
190
191### Terminal methods (use with -T flag)
192- `w-t` — WezTerm new tab
193- `w-t-b` — WezTerm new tab (background, no focus steal)
194- `w-w` — WezTerm new window
195- `i-t` — iTerm2 new tab
196- `i-w` — iTerm2 new window
197- `t` — tmux new session
198- `t-w` — tmux new window
199- `d` — detached (background, no terminal)
200
201Use the method matching the user's terminal. If unsure, ask.
202
203## Common Workflows
204
205### Feature development
206```bash
207gw new feature-x --prompt "Implement feature X"
208# ... work is done in the new worktree ...
209gw pr feature-x # create PR
210gw delete feature-x # cleanup after merge
211```
212
213### Keep worktrees in sync
214```bash
215gw sync --all # rebase all worktrees onto their base
216gw sync --all --ai-merge # use AI to resolve conflicts
217```
218
219### Batch cleanup
220```bash
221gw clean --merged # delete worktrees for merged branches
222gw clean --older-than 30d --dry-run # preview old worktree cleanup
223```
224
225### Global mode (across repos)
226```bash
227gw -g list # list worktrees across all repos
228gw -g scan --dir ~/projects # discover repositories
229```
230
231## Guidelines
232
233- Use descriptive branch names: `fix-auth`, `feat-login-page`, `refactor-api`
234- Specify base branch if not main/master: `gw new fix-auth --base develop -T w-t --prompt "..."`
235- One focused task per worktree
236- The delegated Claude Code instance works independently in its own worktree directory
237- You can delegate multiple tasks in parallel to different worktrees
238
239## Full command reference
240
241For detailed flags and options for all commands, see [gw-commands.md](references/gw-commands.md).
242"#
243}
244
245fn reference_content() -> &'static str {
246 r#"# gw Command Reference
247
248Complete reference for all gw (git-worktree-manager) commands.
249
250## Core Worktree Management
251
252### `gw new <branch> [OPTIONS]`
253Create new worktree for feature branch.
254- `-p, --path <PATH>` — Custom worktree path (default: `../<repo>-<branch>`)
255- `-b, --base <BASE>` — Base branch to create from (default: from config or auto-detect)
256- `--no-term` — Skip AI tool launch
257- `-T, --term <METHOD>` — Terminal launch method. Accepts canonical name (e.g., `tmux`, `wezterm-tab`) or alias (e.g., `t`, `w-t`). Supports `method:session-name` for tmux/zellij (e.g., `tmux:mywork`). See Terminal Launch Methods section below.
258- `--bg` — Launch AI tool in background
259- `--prompt <PROMPT>` — Initial prompt to pass to AI tool (interactive session)
260
261### `gw delete [target] [OPTIONS]`
262Delete a worktree.
263- `-k, --keep-branch` — Keep the branch (only remove worktree directory)
264- `-r, --delete-remote` — Also delete the remote branch
265- `--no-force` — Don't use --force flag
266- `-w, --worktree` — Resolve target as worktree directory name
267- `-b, --branch` — Resolve target as branch name
268
269### `gw list`
270List all worktrees with status indicators (active, clean, modified, stale). Alias: `gw ls`.
271
272### `gw status`
273Show detailed info about the current worktree.
274
275### `gw resume [branch] [OPTIONS]`
276Resume AI work in a worktree. Auto-detects existing Claude sessions and uses `--continue`.
277- `-T, --term <METHOD>` — Terminal launch method (same format as `gw new`)
278- `--bg` — Launch AI tool in background
279- `-w, --worktree` — Resolve as worktree name
280- `-b, --by-branch` — Resolve as branch name
281
282### `gw shell [worktree] [COMMAND...]`
283Open interactive shell in a worktree, or execute a command.
284```bash
285gw shell feature-x # interactive shell
286gw shell feature-x npm test # run command
287```
288
289## Git Workflow
290
291### `gw pr [branch] [OPTIONS]`
292Create GitHub Pull Request from worktree.
293- `-t, --title <TITLE>` — PR title
294- `-B, --body <BODY>` — PR body
295- `-d, --draft` — Create as draft PR
296- `--no-push` — Skip pushing to remote
297- `-w, --worktree` / `-b, --by-branch` — Target resolution
298
299### `gw merge [branch] [OPTIONS]`
300Merge feature branch into base branch.
301- `-i, --interactive` — Interactive rebase
302- `--dry-run` — Show what would happen
303- `--push` — Push to remote after merge
304- `--ai-merge` — Use AI to resolve merge conflicts
305- `-w, --worktree` — Resolve as worktree name
306
307### `gw sync [branch] [OPTIONS]`
308Sync worktree with base branch (rebase).
309- `--all` — Sync all worktrees
310- `--fetch-only` — Only fetch without rebasing
311- `--ai-merge` — Use AI to resolve conflicts
312- `-w, --worktree` / `-b, --by-branch` — Target resolution
313
314### `gw change-base <new-base> [branch] [OPTIONS]`
315Change base branch for a worktree.
316- `--dry-run` — Show what would happen
317- `-i, --interactive` — Interactive rebase
318- `-w, --worktree` / `-b, --by-branch` — Target resolution
319
320### `gw diff <branch1> <branch2> [OPTIONS]`
321Compare two branches.
322- `-s, --summary` — Show statistics only
323- `-f, --files` — Show changed files only
324
325## Maintenance
326
327### `gw clean [OPTIONS]`
328Batch cleanup of worktrees.
329- `--merged` — Delete worktrees for branches already merged to base
330- `--older-than <DURATION>` — Delete worktrees older than duration (e.g., `7d`, `2w`, `1m`)
331- `-i, --interactive` — Interactive selection
332- `--dry-run` — Preview without deleting
333
334### `gw doctor`
335Run health check: git version, worktree accessibility, uncommitted changes, behind-base detection, merge conflicts, Claude Code integration.
336
337### `gw upgrade`
338Check for updates and install latest version from GitHub Releases.
339
340### `gw tree`
341Display worktree hierarchy as a visual tree.
342
343### `gw stats`
344Show worktree statistics (count, age, size).
345
346## Backup & Stash
347
348### `gw backup create [branch] [--all]`
349Create git bundle backup of worktree(s).
350
351### `gw backup list [branch] [--all]`
352List available backups.
353
354### `gw backup restore <branch> [--path <PATH>] [--id <ID>]`
355Restore worktree from backup.
356
357### `gw stash save [message]`
358Save changes to worktree-aware stash.
359
360### `gw stash list`
361List stashes organized by worktree/branch.
362
363### `gw stash apply <target-branch> [-s <stash-ref>]`
364Apply stash to a different worktree.
365
366## Configuration
367
368### `gw config show`
369Show current configuration.
370
371### `gw config list`
372List all configuration keys with descriptions.
373
374### `gw config get <KEY>`
375Get a config value. Keys use dot notation (see Key Config Keys section below).
376
377### `gw config set <KEY> <VALUE>`
378Set a config value. Key-specific valid values:
379- `ai_tool.command` — Preset name (`claude`, `claude-yolo`, `claude-remote`, `claude-yolo-remote`, `codex`, `codex-yolo`, `no-op`) or any command name
380- `launch.method` — Any terminal launch method name or alias (see Terminal Launch Methods)
381- `update.auto_check` — `true` or `false`
382
383### `gw config use-preset <NAME>`
384Use a predefined AI tool preset: `claude`, `claude-yolo`, `claude-remote`, `claude-yolo-remote`, `codex`, `codex-yolo`, `no-op`.
385
386### `gw config list-presets`
387List available presets.
388
389### `gw config reset`
390Reset configuration to defaults.
391
392## Hooks
393
394### `gw hook add <EVENT> <COMMAND> [--id <ID>] [-d <DESC>]`
395Add a lifecycle hook.
396
397### `gw hook remove <EVENT> <HOOK_ID>`
398Remove a hook.
399
400### `gw hook list [EVENT]`
401List hooks.
402
403### `gw hook enable/disable <EVENT> <HOOK_ID>`
404Toggle hook on/off.
405
406### `gw hook run <EVENT> [--dry-run]`
407Manually run hooks for an event.
408
409**Available events:** `worktree.pre_create`, `worktree.post_create`, `worktree.pre_delete`, `worktree.post_delete`, `merge.pre`, `merge.post`, `pr.pre`, `pr.post`, `resume.pre`, `resume.post`, `sync.pre`, `sync.post`
410
411## Export / Import
412
413### `gw export [-o <FILE>]`
414Export worktree configuration to JSON.
415
416### `gw import <FILE> [--apply]`
417Import configuration (preview by default, `--apply` to apply).
418
419## Global Mode
420
421Add `-g` or `--global` to any command to operate across all registered repositories.
422
423### `gw -g list`
424List worktrees across all registered repos.
425
426### `gw scan [--dir <DIR>]`
427Scan for and register git repositories.
428
429### `gw prune`
430Clean up stale registry entries.
431
432## Shell Integration
433
434### `gw shell-setup`
435Interactive setup for shell integration (gw-cd function).
436
437### `gw-cd [branch]`
438Shell function to navigate to worktree by branch name. Supports:
439- `gw-cd` — interactive selector
440- `gw-cd feature-x` — direct navigation
441- `gw-cd -g feature-x` — global (across repos)
442- `gw-cd repo:branch` — repo-scoped navigation
443
444## Terminal Launch Methods
445
446Used with `-T` flag on `gw new` and `gw resume`. Supports `method:session-name` for tmux/zellij (e.g., `tmux:mywork`, `z:task1`).
447
448| Method | Alias | Description |
449|--------|-------|-------------|
450| `foreground` | `fg` | Block in current terminal |
451| `detach` | `d` | Fully detached process |
452| `iterm-window` | `i-w` | iTerm2 new window |
453| `iterm-tab` | `i-t` | iTerm2 new tab |
454| `iterm-pane-h` | `i-p-h` | iTerm2 horizontal pane |
455| `iterm-pane-v` | `i-p-v` | iTerm2 vertical pane |
456| `tmux` | `t` | tmux new session |
457| `tmux-window` | `t-w` | tmux new window |
458| `tmux-pane-h` | `t-p-h` | tmux horizontal pane |
459| `tmux-pane-v` | `t-p-v` | tmux vertical pane |
460| `zellij` | `z` | Zellij new session |
461| `zellij-tab` | `z-t` | Zellij new tab |
462| `zellij-pane-h` | `z-p-h` | Zellij horizontal pane |
463| `zellij-pane-v` | `z-p-v` | Zellij vertical pane |
464| `wezterm-window` | `w-w` | WezTerm new window |
465| `wezterm-tab` | `w-t` | WezTerm new tab |
466| `wezterm-tab-bg` | `w-t-b` | WezTerm new tab (background, no focus steal) |
467| `wezterm-pane-h` | `w-p-h` | WezTerm horizontal pane |
468| `wezterm-pane-v` | `w-p-v` | WezTerm vertical pane |
469
470## Key Config Keys
471
472| Key | Description | Default |
473|-----|-------------|---------|
474| `ai_tool.command` | AI tool name or preset | `claude` |
475| `ai_tool.args` | Additional arguments | `[]` |
476| `launch.method` | Default terminal method | `foreground` |
477| `launch.tmux_session_prefix` | tmux session prefix | `gw` |
478| `launch.wezterm_ready_timeout` | WezTerm ready timeout (secs) | `5.0` |
479| `update.auto_check` | Auto-check for updates | `true` |
480
481## Helper Commands (for scripting and completion)
482
483These hidden commands output newline-separated values, useful for scripting:
484- `gw _config-keys` — List all config key names
485- `gw _term-values` — List all valid `--term` values (canonical + aliases)
486- `gw _preset-names` — List all AI tool preset names
487- `gw _hook-events` — List all valid hook event names
488- `gw _path --list-branches [-g]` — List worktree branch names
489"#
490}