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