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