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** — the full task text (will be passed via `--prompt-file` in Step 2)
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
135
136All three prompt ingestion modes (`--prompt`, `--prompt-file`, `--prompt-stdin`) are equally safe from shell-escaping issues. Use `--prompt-file` for convenience when managing multi-line prompts in an editor or passing skill-generated files.
137
138**Recommended (use this by default):**
139```bash
140# Write the full prompt to a temp file, then pass the path.
141# `trap` ensures the file is cleaned up even if `gw new` fails.
142trap 'rm -f /tmp/gw-prompt-$$.txt' EXIT
143cat > /tmp/gw-prompt-$$.txt <<'PROMPT'
144<task description — multi-line OK, quotes OK, no escaping needed>
145PROMPT
146gw new <branch-name> -T <terminal-method> --prompt-file /tmp/gw-prompt-$$.txt
147```
148
149**Short one-liner alternative:**
150```bash
151gw new <branch-name> -T <terminal-method> --prompt "<short task>"
152```
153
154**Piping from another command:**
155```bash
156generate-spec | gw new <branch-name> --prompt-stdin
157```
158
159Note: `--prompt-stdin` consumes the process's stdin. Avoid combining it with
160`-T <terminal-method>` — the spawned terminal may inherit a closed stdin and
161behave unpredictably. Use `--prompt-file` if you need to specify a terminal launcher alongside the prompt.
162
163Only one of `--prompt`, `--prompt-file`, `--prompt-stdin` may be given per invocation.
164
165### Branch name rules
166- Lowercase, hyphen-separated, max ~50 chars
167- Strip filler words (the, a, an, for, in, on, etc.)
168- Examples:
169  - "Fix the JWT token expiration check in auth" → `fix-jwt-token-expiration`
170  - "Add user avatar upload feature" → `feat-avatar-upload`
171  - "Refactor the database connection pool" → `refactor-db-connection-pool`
172
173### Terminal method selection
174- **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.
175- 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)
176- Once the user specifies a method, remember it for subsequent calls in the same session.
177
178## Quick Reference
179
180| Command | Description |
181|---------|-------------|
182| `gw new <branch> [--prompt-file <path> \| --prompt "..." \| --prompt-stdin]` | Create worktree + optionally launch AI with task |
183| `gw delete <branch>` | Delete worktree and branch |
184| `gw list` | List all worktrees with status |
185| `gw status` | Show current worktree info |
186| `gw resume [branch]` | Resume AI session in worktree |
187| `gw pr [branch]` | Create GitHub Pull Request |
188| `gw merge [branch]` | Merge branch into base |
189| `gw sync [--all]` | Rebase worktree(s) onto base branch |
190| `gw clean [--merged]` | Batch cleanup of worktrees |
191| `gw diff <b1> <b2>` | Compare two branches |
192| `gw change-base <new> [branch]` | Change base branch |
193| `gw config <action>` | Configuration management |
194| `gw doctor` | Run diagnostics |
195| `gw tree` / `gw stats` | Visual hierarchy / statistics |
196| `gw backup <action>` | Backup and restore worktrees |
197| `gw stash <action>` | Worktree-aware stash management |
198| `gw shell [worktree]` | Open shell in worktree |
199
200## Delegate a task to a new worktree
201
202Three ways to supply the initial prompt (mutually exclusive):
203
204| Flag | When to use |
205|------|-------------|
206| `--prompt-file <path>` ⭐ | Convenient for multi-line prompts, editor-managed content, or skill-generated files. |
207| `--prompt "<text>"` | Short single-line prompts only. |
208| `--prompt-stdin` | Piping from another command (`cmd \| gw new ... --prompt-stdin`). |
209
210Example (recommended):
211```bash
212trap 'rm -f /tmp/gw-prompt-$$.txt' EXIT
213cat > /tmp/gw-prompt-$$.txt <<'PROMPT'
214Fix JWT token expiration check in src/auth.rs.
215Make sure to cover the "leeway" edge case and add a unit test.
216PROMPT
217gw new fix-auth -T w-t --prompt-file /tmp/gw-prompt-$$.txt
218```
219
220Example (short form):
221```bash
222gw new fix-auth -T w-t --prompt "Fix JWT token expiration check"
223```
224
225### Terminal methods (use with -T flag)
226- `w-t` — WezTerm new tab
227- `w-t-b` — WezTerm new tab (background, no focus steal)
228- `w-w` — WezTerm new window
229- `i-t` — iTerm2 new tab
230- `i-w` — iTerm2 new window
231- `t` — tmux new session
232- `t-w` — tmux new window
233- `d` — detached (background, no terminal)
234
235Use the method matching the user's terminal. If unsure, ask.
236
237## Common Workflows
238
239### Feature development
240```bash
241trap 'rm -f /tmp/gw-prompt-$$.txt' EXIT
242cat > /tmp/gw-prompt-$$.txt <<'PROMPT'
243Implement feature X
244PROMPT
245# `-T` omitted — uses the default launcher from `gw config get launch.method`.
246gw new feature-x --prompt-file /tmp/gw-prompt-$$.txt
247# ... work is done in the new worktree ...
248gw pr feature-x                    # create PR
249gw delete feature-x                # cleanup after merge
250```
251
252### Keep worktrees in sync
253```bash
254gw sync --all                      # rebase all worktrees onto their base
255gw sync --all --ai-merge           # use AI to resolve conflicts
256```
257
258### Batch cleanup
259```bash
260gw clean --merged                  # delete worktrees for merged branches
261gw clean --older-than 30d --dry-run  # preview old worktree cleanup
262```
263
264### Global mode (across repos)
265```bash
266gw -g list                         # list worktrees across all repos
267gw -g scan --dir ~/projects        # discover repositories
268```
269
270## Guidelines
271
272- Use descriptive branch names: `fix-auth`, `feat-login-page`, `refactor-api`
273- Specify base branch if not main/master:
274  ```bash
275  trap 'rm -f /tmp/gw-prompt-$$.txt' EXIT
276  cat > /tmp/gw-prompt-$$.txt <<'PROMPT'
277  <task description>
278  PROMPT
279  gw new fix-auth --base develop -T w-t --prompt-file /tmp/gw-prompt-$$.txt
280  ```
281- One focused task per worktree
282- The delegated Claude Code instance works independently in its own worktree directory
283- You can delegate multiple tasks in parallel to different worktrees
284- **Fire-and-forget**: Once a worktree task is spawned, you CANNOT stop it, send follow-up messages, or interact with it. The initial prompt is the ONLY instruction the delegated instance receives. Therefore:
285  - Make the prompt comprehensive — include all requirements, constraints, and acceptance criteria upfront
286  - Use `--prompt-file` for complex or skill-generated prompts to manage them conveniently
287  - If the user's request is vague or ambiguous, ask clarifying questions BEFORE spawning
288  - Do NOT spawn a task assuming you can "correct course later" — you cannot
289
290## Full command reference
291
292For detailed flags and options for all commands, see [gw-commands.md](references/gw-commands.md).
293"#
294}
295
296fn reference_content() -> &'static str {
297    r#"# gw Command Reference
298
299Complete reference for all gw (git-worktree-manager) commands.
300
301## Core Worktree Management
302
303### `gw new <branch> [OPTIONS]`
304Create new worktree for feature branch.
305- `-p, --path <PATH>` — Custom worktree path (default: `../<repo>-<branch>`)
306- `-b, --base <BASE>` — Base branch to create from (default: from config or auto-detect)
307- `--no-term` — Skip AI tool launch
308- `-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.
309- `--bg` — Launch AI tool in background
310- `--prompt <PROMPT>` — Initial prompt as a CLI string (single-line, best for short prompts)
311- `--prompt-file <PATH>` — Read initial prompt from a file (recommended for multi-line / quoted content)
312- `--prompt-stdin` — Read initial prompt from standard input (for piping). Avoid combining with `-T <terminal>` — the spawned terminal may inherit a closed stdin.
313
314Only one of `--prompt`, `--prompt-file`, `--prompt-stdin` may be used per invocation.
315
316### `gw delete [target] [OPTIONS]`
317Delete a worktree.
318- `-k, --keep-branch` — Keep the branch (only remove worktree directory)
319- `-r, --delete-remote` — Also delete the remote branch
320- `--no-force` — Don't use --force flag
321- `-w, --worktree` — Resolve target as worktree directory name
322- `-b, --branch` — Resolve target as branch name
323
324### `gw list`
325List all worktrees with status indicators (active, clean, modified, stale). Alias: `gw ls`.
326
327### `gw status`
328Show detailed info about the current worktree.
329
330### `gw resume [branch] [OPTIONS]`
331Resume AI work in a worktree. Auto-detects existing Claude sessions and uses `--continue`.
332- `-T, --term <METHOD>` — Terminal launch method (same format as `gw new`)
333- `--bg` — Launch AI tool in background
334- `-w, --worktree` — Resolve as worktree name
335- `-b, --by-branch` — Resolve as branch name
336
337### `gw shell [worktree] [COMMAND...]`
338Open interactive shell in a worktree, or execute a command.
339```bash
340gw shell feature-x           # interactive shell
341gw shell feature-x npm test  # run command
342```
343
344## Git Workflow
345
346### `gw pr [branch] [OPTIONS]`
347Create GitHub Pull Request from worktree.
348- `-t, --title <TITLE>` — PR title
349- `-B, --body <BODY>` — PR body
350- `-d, --draft` — Create as draft PR
351- `--no-push` — Skip pushing to remote
352- `-w, --worktree` / `-b, --by-branch` — Target resolution
353
354### `gw merge [branch] [OPTIONS]`
355Merge feature branch into base branch.
356- `-i, --interactive` — Interactive rebase
357- `--dry-run` — Show what would happen
358- `--push` — Push to remote after merge
359- `--ai-merge` — Use AI to resolve merge conflicts
360- `-w, --worktree` — Resolve as worktree name
361
362### `gw sync [branch] [OPTIONS]`
363Sync worktree with base branch (rebase).
364- `--all` — Sync all worktrees
365- `--fetch-only` — Only fetch without rebasing
366- `--ai-merge` — Use AI to resolve conflicts
367- `-w, --worktree` / `-b, --by-branch` — Target resolution
368
369### `gw change-base <new-base> [branch] [OPTIONS]`
370Change base branch for a worktree.
371- `--dry-run` — Show what would happen
372- `-i, --interactive` — Interactive rebase
373- `-w, --worktree` / `-b, --by-branch` — Target resolution
374
375### `gw diff <branch1> <branch2> [OPTIONS]`
376Compare two branches.
377- `-s, --summary` — Show statistics only
378- `-f, --files` — Show changed files only
379
380## Maintenance
381
382### `gw clean [OPTIONS]`
383Batch cleanup of worktrees.
384- `--merged` — Delete worktrees for branches already merged to base
385- `--older-than <DURATION>` — Delete worktrees older than duration (e.g., `7d`, `2w`, `1m`)
386- `-i, --interactive` — Interactive selection
387- `--dry-run` — Preview without deleting
388
389### `gw doctor`
390Run health check: git version, worktree accessibility, uncommitted changes, behind-base detection, merge conflicts, Claude Code integration.
391
392### `gw upgrade`
393Check for updates and install latest version from GitHub Releases.
394
395### `gw tree`
396Display worktree hierarchy as a visual tree.
397
398### `gw stats`
399Show worktree statistics (count, age, size).
400
401## Backup & Stash
402
403### `gw backup create [branch] [--all]`
404Create git bundle backup of worktree(s).
405
406### `gw backup list [branch] [--all]`
407List available backups.
408
409### `gw backup restore <branch> [--path <PATH>] [--id <ID>]`
410Restore worktree from backup.
411
412### `gw stash save [message]`
413Save changes to worktree-aware stash.
414
415### `gw stash list`
416List stashes organized by worktree/branch.
417
418### `gw stash apply <target-branch> [-s <stash-ref>]`
419Apply stash to a different worktree.
420
421## Configuration
422
423### `gw config show`
424Show current configuration.
425
426### `gw config list`
427List all configuration keys with descriptions.
428
429### `gw config get <KEY>`
430Get a config value. Keys use dot notation (see Key Config Keys section below).
431
432### `gw config set <KEY> <VALUE>`
433Set a config value. Key-specific valid values:
434- `ai_tool.command` — Preset name (`claude`, `claude-yolo`, `claude-remote`, `claude-yolo-remote`, `codex`, `codex-yolo`, `no-op`) or any command name
435- `launch.method` — Any terminal launch method name or alias (see Terminal Launch Methods)
436- `update.auto_check` — `true` or `false`
437
438### `gw config use-preset <NAME>`
439Use a predefined AI tool preset: `claude`, `claude-yolo`, `claude-remote`, `claude-yolo-remote`, `codex`, `codex-yolo`, `no-op`.
440
441### `gw config list-presets`
442List available presets.
443
444### `gw config reset`
445Reset configuration to defaults.
446
447## Hooks
448
449### `gw hook add <EVENT> <COMMAND> [--id <ID>] [-d <DESC>]`
450Add a lifecycle hook.
451
452### `gw hook remove <EVENT> <HOOK_ID>`
453Remove a hook.
454
455### `gw hook list [EVENT]`
456List hooks.
457
458### `gw hook enable/disable <EVENT> <HOOK_ID>`
459Toggle hook on/off.
460
461### `gw hook run <EVENT> [--dry-run]`
462Manually run hooks for an event.
463
464**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`
465
466## Export / Import
467
468### `gw export [-o <FILE>]`
469Export worktree configuration to JSON.
470
471### `gw import <FILE> [--apply]`
472Import configuration (preview by default, `--apply` to apply).
473
474## Global Mode
475
476Add `-g` or `--global` to any command to operate across all registered repositories.
477
478### `gw -g list`
479List worktrees across all registered repos.
480
481### `gw scan [--dir <DIR>]`
482Scan for and register git repositories.
483
484### `gw prune`
485Clean up stale registry entries.
486
487## Shell Integration
488
489### `gw shell-setup`
490Interactive setup for shell integration (gw-cd function).
491
492### `gw-cd [branch]`
493Shell function to navigate to worktree by branch name. Supports:
494- `gw-cd` — interactive selector
495- `gw-cd feature-x` — direct navigation
496- `gw-cd -g feature-x` — global (across repos)
497- `gw-cd repo:branch` — repo-scoped navigation
498
499## Terminal Launch Methods
500
501Used with `-T` flag on `gw new` and `gw resume`. Supports `method:session-name` for tmux/zellij (e.g., `tmux:mywork`, `z:task1`).
502
503| Method | Alias | Description |
504|--------|-------|-------------|
505| `foreground` | `fg` | Block in current terminal |
506| `detach` | `d` | Fully detached process |
507| `iterm-window` | `i-w` | iTerm2 new window |
508| `iterm-tab` | `i-t` | iTerm2 new tab |
509| `iterm-pane-h` | `i-p-h` | iTerm2 horizontal pane |
510| `iterm-pane-v` | `i-p-v` | iTerm2 vertical pane |
511| `tmux` | `t` | tmux new session |
512| `tmux-window` | `t-w` | tmux new window |
513| `tmux-pane-h` | `t-p-h` | tmux horizontal pane |
514| `tmux-pane-v` | `t-p-v` | tmux vertical pane |
515| `zellij` | `z` | Zellij new session |
516| `zellij-tab` | `z-t` | Zellij new tab |
517| `zellij-pane-h` | `z-p-h` | Zellij horizontal pane |
518| `zellij-pane-v` | `z-p-v` | Zellij vertical pane |
519| `wezterm-window` | `w-w` | WezTerm new window |
520| `wezterm-tab` | `w-t` | WezTerm new tab |
521| `wezterm-tab-bg` | `w-t-b` | WezTerm new tab (background, no focus steal) |
522| `wezterm-pane-h` | `w-p-h` | WezTerm horizontal pane |
523| `wezterm-pane-v` | `w-p-v` | WezTerm vertical pane |
524
525## Key Config Keys
526
527| Key | Description | Default |
528|-----|-------------|---------|
529| `ai_tool.command` | AI tool name or preset | `claude` |
530| `ai_tool.args` | Additional arguments | `[]` |
531| `launch.method` | Default terminal method | `foreground` |
532| `launch.tmux_session_prefix` | tmux session prefix | `gw` |
533| `launch.wezterm_ready_timeout` | WezTerm ready timeout (secs) | `5.0` |
534| `update.auto_check` | Auto-check for updates | `true` |
535
536## Helper Commands (for scripting and completion)
537
538These hidden commands output newline-separated values, useful for scripting:
539- `gw _config-keys` — List all config key names
540- `gw _term-values` — List all valid `--term` values (canonical + aliases)
541- `gw _preset-names` — List all AI tool preset names
542- `gw _hook-events` — List all valid hook event names
543- `gw _path --list-branches [-g]` — List worktree branch names
544"#
545}