Skip to main content

git_worktree_manager/operations/
setup_claude.rs

1/// Claude Code skill installation for worktree task delegation.
2use 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
14/// Get the skill base directory.
15fn skill_dir() -> PathBuf {
16    home_dir_or_fallback()
17        .join(".claude")
18        .join("skills")
19        .join(SKILL_DIR)
20}
21
22/// Get the skill installation path.
23pub fn skill_path() -> PathBuf {
24    skill_dir().join(SKILL_FILE)
25}
26
27/// Get the reference file path.
28fn reference_path() -> PathBuf {
29    skill_dir().join("references").join(REFERENCE_FILE)
30}
31
32/// Check if the Claude Code skill is already installed.
33pub fn is_skill_installed() -> bool {
34    skill_path().exists()
35}
36
37/// Write a file if its content differs from the new content.
38/// Returns true if the file was written (created or updated).
39fn 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
56/// Remove the legacy gw-delegate skill directory if it exists.
57fn 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
67/// Install or update the Claude Code skill for worktree task delegation.
68pub 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        // File existed before we wrote (we just overwrote it)
90        "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- Use the method matching the user's terminal. If unsure, ask on first use.
150- Common methods: `w-t` (WezTerm tab), `i-t` (iTerm2 tab), `t` (tmux session), `d` (detached/background)
151- Once known, remember the user's preferred terminal for subsequent calls.
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-w` — WezTerm new window
194- `i-t` — iTerm2 new tab
195- `i-w` — iTerm2 new window
196- `t` — tmux new session
197- `t-w` — tmux new window
198- `d` — detached (background, no terminal)
199
200Use the method matching the user's terminal. If unsure, ask.
201
202## Common Workflows
203
204### Feature development
205```bash
206gw new feature-x --prompt "Implement feature X"
207# ... work is done in the new worktree ...
208gw pr feature-x                    # create PR
209gw delete feature-x                # cleanup after merge
210```
211
212### Keep worktrees in sync
213```bash
214gw sync --all                      # rebase all worktrees onto their base
215gw sync --all --ai-merge           # use AI to resolve conflicts
216```
217
218### Batch cleanup
219```bash
220gw clean --merged                  # delete worktrees for merged branches
221gw clean --older-than 30d --dry-run  # preview old worktree cleanup
222```
223
224### Global mode (across repos)
225```bash
226gw -g list                         # list worktrees across all repos
227gw -g scan --dir ~/projects        # discover repositories
228```
229
230## Guidelines
231
232- Use descriptive branch names: `fix-auth`, `feat-login-page`, `refactor-api`
233- Specify base branch if not main/master: `gw new fix-auth --base develop -T w-t --prompt "..."`
234- One focused task per worktree
235- The delegated Claude Code instance works independently in its own worktree directory
236- You can delegate multiple tasks in parallel to different worktrees
237
238## Full command reference
239
240For detailed flags and options for all commands, see [gw-commands.md](references/gw-commands.md).
241"#
242}
243
244fn reference_content() -> &'static str {
245    r#"# gw Command Reference
246
247Complete reference for all gw (git-worktree-manager) commands.
248
249## Core Worktree Management
250
251### `gw new <branch> [OPTIONS]`
252Create new worktree for feature branch.
253- `-p, --path <PATH>` — Custom worktree path (default: `../<repo>-<branch>`)
254- `-b, --base <BASE>` — Base branch to create from (default: from config or auto-detect)
255- `--no-term` — Skip AI tool launch
256- `-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.
257- `--bg` — Launch AI tool in background
258- `--prompt <PROMPT>` — Initial prompt to pass to AI tool (interactive session)
259
260### `gw delete [target] [OPTIONS]`
261Delete a worktree.
262- `-k, --keep-branch` — Keep the branch (only remove worktree directory)
263- `-r, --delete-remote` — Also delete the remote branch
264- `--no-force` — Don't use --force flag
265- `-w, --worktree` — Resolve target as worktree directory name
266- `-b, --branch` — Resolve target as branch name
267
268### `gw list`
269List all worktrees with status indicators (active, clean, modified, stale). Alias: `gw ls`.
270
271### `gw status`
272Show detailed info about the current worktree.
273
274### `gw resume [branch] [OPTIONS]`
275Resume AI work in a worktree. Auto-detects existing Claude sessions and uses `--continue`.
276- `-T, --term <METHOD>` — Terminal launch method (same format as `gw new`)
277- `--bg` — Launch AI tool in background
278- `-w, --worktree` — Resolve as worktree name
279- `-b, --by-branch` — Resolve as branch name
280
281### `gw shell [worktree] [COMMAND...]`
282Open interactive shell in a worktree, or execute a command.
283```bash
284gw shell feature-x           # interactive shell
285gw shell feature-x npm test  # run command
286```
287
288## Git Workflow
289
290### `gw pr [branch] [OPTIONS]`
291Create GitHub Pull Request from worktree.
292- `-t, --title <TITLE>` — PR title
293- `-B, --body <BODY>` — PR body
294- `-d, --draft` — Create as draft PR
295- `--no-push` — Skip pushing to remote
296- `-w, --worktree` / `-b, --by-branch` — Target resolution
297
298### `gw merge [branch] [OPTIONS]`
299Merge feature branch into base branch.
300- `-i, --interactive` — Interactive rebase
301- `--dry-run` — Show what would happen
302- `--push` — Push to remote after merge
303- `--ai-merge` — Use AI to resolve merge conflicts
304- `-w, --worktree` — Resolve as worktree name
305
306### `gw sync [branch] [OPTIONS]`
307Sync worktree with base branch (rebase).
308- `--all` — Sync all worktrees
309- `--fetch-only` — Only fetch without rebasing
310- `--ai-merge` — Use AI to resolve conflicts
311- `-w, --worktree` / `-b, --by-branch` — Target resolution
312
313### `gw change-base <new-base> [branch] [OPTIONS]`
314Change base branch for a worktree.
315- `--dry-run` — Show what would happen
316- `-i, --interactive` — Interactive rebase
317- `-w, --worktree` / `-b, --by-branch` — Target resolution
318
319### `gw diff <branch1> <branch2> [OPTIONS]`
320Compare two branches.
321- `-s, --summary` — Show statistics only
322- `-f, --files` — Show changed files only
323
324## Maintenance
325
326### `gw clean [OPTIONS]`
327Batch cleanup of worktrees.
328- `--merged` — Delete worktrees for branches already merged to base
329- `--older-than <DURATION>` — Delete worktrees older than duration (e.g., `7d`, `2w`, `1m`)
330- `-i, --interactive` — Interactive selection
331- `--dry-run` — Preview without deleting
332
333### `gw doctor`
334Run health check: git version, worktree accessibility, uncommitted changes, behind-base detection, merge conflicts, Claude Code integration.
335
336### `gw upgrade`
337Check for updates and install latest version from GitHub Releases.
338
339### `gw tree`
340Display worktree hierarchy as a visual tree.
341
342### `gw stats`
343Show worktree statistics (count, age, size).
344
345## Backup & Stash
346
347### `gw backup create [branch] [--all]`
348Create git bundle backup of worktree(s).
349
350### `gw backup list [branch] [--all]`
351List available backups.
352
353### `gw backup restore <branch> [--path <PATH>] [--id <ID>]`
354Restore worktree from backup.
355
356### `gw stash save [message]`
357Save changes to worktree-aware stash.
358
359### `gw stash list`
360List stashes organized by worktree/branch.
361
362### `gw stash apply <target-branch> [-s <stash-ref>]`
363Apply stash to a different worktree.
364
365## Configuration
366
367### `gw config show`
368Show current configuration.
369
370### `gw config list`
371List all configuration keys with descriptions.
372
373### `gw config get <KEY>`
374Get a config value. Keys use dot notation (see Key Config Keys section below).
375
376### `gw config set <KEY> <VALUE>`
377Set a config value. Key-specific valid values:
378- `ai_tool.command` — Preset name (`claude`, `claude-yolo`, `claude-remote`, `claude-yolo-remote`, `codex`, `codex-yolo`, `no-op`) or any command name
379- `launch.method` — Any terminal launch method name or alias (see Terminal Launch Methods)
380- `update.auto_check` — `true` or `false`
381
382### `gw config use-preset <NAME>`
383Use a predefined AI tool preset: `claude`, `claude-yolo`, `claude-remote`, `claude-yolo-remote`, `codex`, `codex-yolo`, `no-op`.
384
385### `gw config list-presets`
386List available presets.
387
388### `gw config reset`
389Reset configuration to defaults.
390
391## Hooks
392
393### `gw hook add <EVENT> <COMMAND> [--id <ID>] [-d <DESC>]`
394Add a lifecycle hook.
395
396### `gw hook remove <EVENT> <HOOK_ID>`
397Remove a hook.
398
399### `gw hook list [EVENT]`
400List hooks.
401
402### `gw hook enable/disable <EVENT> <HOOK_ID>`
403Toggle hook on/off.
404
405### `gw hook run <EVENT> [--dry-run]`
406Manually run hooks for an event.
407
408**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`
409
410## Export / Import
411
412### `gw export [-o <FILE>]`
413Export worktree configuration to JSON.
414
415### `gw import <FILE> [--apply]`
416Import configuration (preview by default, `--apply` to apply).
417
418## Global Mode
419
420Add `-g` or `--global` to any command to operate across all registered repositories.
421
422### `gw -g list`
423List worktrees across all registered repos.
424
425### `gw scan [--dir <DIR>]`
426Scan for and register git repositories.
427
428### `gw prune`
429Clean up stale registry entries.
430
431## Shell Integration
432
433### `gw shell-setup`
434Interactive setup for shell integration (gw-cd function).
435
436### `gw-cd [branch]`
437Shell function to navigate to worktree by branch name. Supports:
438- `gw-cd` — interactive selector
439- `gw-cd feature-x` — direct navigation
440- `gw-cd -g feature-x` — global (across repos)
441- `gw-cd repo:branch` — repo-scoped navigation
442
443## Terminal Launch Methods
444
445Used with `-T` flag on `gw new` and `gw resume`. Supports `method:session-name` for tmux/zellij (e.g., `tmux:mywork`, `z:task1`).
446
447| Method | Alias | Description |
448|--------|-------|-------------|
449| `foreground` | `fg` | Block in current terminal |
450| `detach` | `d` | Fully detached process |
451| `iterm-window` | `i-w` | iTerm2 new window |
452| `iterm-tab` | `i-t` | iTerm2 new tab |
453| `iterm-pane-h` | `i-p-h` | iTerm2 horizontal pane |
454| `iterm-pane-v` | `i-p-v` | iTerm2 vertical pane |
455| `tmux` | `t` | tmux new session |
456| `tmux-window` | `t-w` | tmux new window |
457| `tmux-pane-h` | `t-p-h` | tmux horizontal pane |
458| `tmux-pane-v` | `t-p-v` | tmux vertical pane |
459| `zellij` | `z` | Zellij new session |
460| `zellij-tab` | `z-t` | Zellij new tab |
461| `zellij-pane-h` | `z-p-h` | Zellij horizontal pane |
462| `zellij-pane-v` | `z-p-v` | Zellij vertical pane |
463| `wezterm-window` | `w-w` | WezTerm new window |
464| `wezterm-tab` | `w-t` | WezTerm new tab |
465| `wezterm-pane-h` | `w-p-h` | WezTerm horizontal pane |
466| `wezterm-pane-v` | `w-p-v` | WezTerm vertical pane |
467
468## Key Config Keys
469
470| Key | Description | Default |
471|-----|-------------|---------|
472| `ai_tool.command` | AI tool name or preset | `claude` |
473| `ai_tool.args` | Additional arguments | `[]` |
474| `launch.method` | Default terminal method | `foreground` |
475| `launch.tmux_session_prefix` | tmux session prefix | `gw` |
476| `launch.wezterm_ready_timeout` | WezTerm ready timeout (secs) | `5.0` |
477| `update.auto_check` | Auto-check for updates | `true` |
478
479## Helper Commands (for scripting and completion)
480
481These hidden commands output newline-separated values, useful for scripting:
482- `gw _config-keys` — List all config key names
483- `gw _term-values` — List all valid `--term` values (canonical + aliases)
484- `gw _preset-names` — List all AI tool preset names
485- `gw _hook-events` — List all valid hook event names
486- `gw _path --list-branches [-g]` — List worktree branch names
487"#
488}