---
name: orchestrating-worktree-agents
description: Orchestrate parallel AI agent sessions across git worktrees in Ghostty terminals. Use when dispatching multiple independent tasks to separate agents, each in its own feature branch and terminal. Combines worktree creation, Ghostty tab/window management, and AI tool auto-detection.
enabled: false
source: github:JuanJoseGonGi/skills
imported-from: github:JuanJoseGonGi/skills
---

# Orchestrating Worktree Agents

Dispatch multiple AI coding agents in parallel, each in its own git worktree and Ghostty terminal tab, working on independent feature branches.

**Core principle:** One worktree + one Ghostty tab + one AI agent = one independent task. The orchestrator stays in the current session and dispatches work.

**Announce at start:** "I'm using the orchestrating-worktree-agents skill to dispatch parallel agents."

## When to Use

**Use when:**
- 2+ independent tasks that can be parallelized
- Each task needs its own feature branch
- Running in Ghostty terminal on macOS
- Orchestrator should stay in current session, monitoring progress

**Don't use when:**
- Tasks are tightly coupled or share state
- Only 1 task (just use a single worktree)
- Tasks must execute sequentially (use `executing-plans` instead)
- Not running in Ghostty (scripts depend on Ghostty keybinds)

## Pre-flight Checks

Run these before dispatching any agents:

```bash
# 1. Verify Ghostty is running
pgrep -x "[Gg]hostty" || echo "Start Ghostty first!"

# 2. Verify clean git state
git status --porcelain  # warn if dirty, suggest stash/commit

# 3. Note current branch (this is the base for all worktrees)
git branch --show-current

# 4. Detect AI tool (launch_worktree_agent.sh does this automatically,
#    but you can check manually — adjust path to where the skill is installed)
#    The script checks: env vars > CLAUDE.md > PATH availability

# 5. Verify/create worktree directory
# The launch script handles this, but check preemptively:
git check-ignore -q .worktrees 2>/dev/null || echo ".worktrees not in .gitignore"
```

If any check fails, fix it before proceeding. Don't dispatch agents into a dirty state.

## Dispatch Workflow

### Step 1: Define Tasks

Break work into independent tasks. Each task needs:
- A **branch name** (e.g., `feature/auth`, `fix/dashboard-api`)
- A **task description** with enough context for an agent working from scratch

### Step 2: Dispatch Each Agent

For each task, run the launch script:

```bash
bash scripts/launch_worktree_agent.sh \
  --branch "feature/auth" \
  --task "You are working on branch feature/auth in a git worktree.
Your task: Implement user authentication with JWT tokens.
- Add login/signup endpoints to src/api/auth.ts
- Add JWT middleware to src/middleware/auth.ts
- Write tests in tests/auth.test.ts
When done, commit your work and report what you implemented." \
  --tool auto
```

The script handles everything: worktree creation, dependency install, Ghostty tab opening, and AI tool launch.

### Step 3: Monitor

After dispatching, report the summary table and wait:

```
Agents dispatched:
| Branch              | Worktree Path               | Tool     | Terminal |
|---------------------|-----------------------------|----------|----------|
| feature/auth        | .worktrees/feature/auth     | opencode | tab      |
| feature/dashboard   | .worktrees/feature/dashboard | opencode | tab      |
| fix/notifications   | .worktrees/fix/notifications | opencode | tab      |

Monitor commands:
  git worktree list                    # see all worktrees
  git log --oneline feature/auth       # check branch progress
  Switch Ghostty tabs to see agents    # Cmd+1, Cmd+2, Cmd+3
```

### Step 4: Integrate and Clean Up

When agents finish their work:

```bash
# Check what each agent committed
git log --oneline main..feature/auth

# Merge or create PR for each branch
git merge feature/auth
# or: gh pr create --head feature/auth --title "Add authentication"

# Remove worktrees
git worktree remove .worktrees/feature/auth
git branch -d feature/auth  # if merged
```

Reference `finishing-a-development-branch` skill for structured completion of each branch.

## Script Reference

### `scripts/launch_worktree_agent.sh`

The main orchestration script. Creates a worktree, opens a Ghostty tab, launches an AI tool.

**Arguments:**

| Flag | Required | Default | Description |
|------|----------|---------|-------------|
| `--branch <name>` | Yes | - | Branch name for the worktree |
| `--task <text>` | Yes | - | Task instructions for the agent |
| `--tool <name>` | No | `auto` | `opencode`, `claude`, `cursor`, or `auto` |
| `--worktree-dir <path>` | No | `.worktrees` | Base directory for worktrees |
| `--no-plan-mode` | No | plan on | Disable plan/read-only mode |
| `--project-root <path>` | No | git root | Project root directory |

**Phases executed:**
1. Creates git worktree with new branch
2. Auto-detects and runs project setup (npm/yarn/pnpm/bun/go/cargo/pip/poetry/uv/bundle)
3. Opens Ghostty tab via keybind simulation (falls back to new window)
4. Launches AI tool with task instructions
5. Outputs JSON summary to stdout

**Example with all flags:**
```bash
bash scripts/launch_worktree_agent.sh \
  --branch "feature/search" \
  --task "Implement full-text search with Elasticsearch" \
  --tool claude \
  --worktree-dir ".worktrees" \
  --project-root "/path/to/repo"
```

### `scripts/detect_ai_tool.sh`

Detects the current AI coding tool. See [TOOL-LAUNCH-REFERENCE.md](references/TOOL-LAUNCH-REFERENCE.md) for per-tool details.

**Detection priority:**
1. `--tool <name>` argument (explicit override)
2. `preferred-ai-tool:` in CLAUDE.md or AGENTS.md
3. Environment variables (`OPENCODE=1`, `CLAUDE_CODE=1`)
4. PATH availability (`which opencode`, `which claude`, `which cursor`)

**Override in CLAUDE.md:**
```markdown
preferred-ai-tool: opencode
```

## Ghostty Tab Strategy

The launch script uses a three-tier approach for opening terminals:

### Tier 1: Keybind Simulation (Primary)

Parses `ghostty +list-keybinds` to find the exact `new_tab` keybind, converts it to AppleScript modifiers, then simulates the keystroke. Uses clipboard paste (Cmd+V) to inject the `cd` + tool command reliably (avoids character-by-character typing issues).

**Requires:** Ghostty running, accessibility permissions for `osascript`

### Tier 2: New Window (Fallback)

If keybind simulation fails (no accessibility permissions, Ghostty not focused, etc.):

```bash
open -na "Ghostty.app" --args --working-directory=<path> -e <shell> -c "<command>"
```

Opens a new Ghostty window instead of a tab. Always works on macOS.

### Tier 3: Native AppleScript (Future)

When Ghostty adds an AppleScript dictionary (`.sdef`), the script can be extended to use:
```applescript
tell application "Ghostty" to new terminal location tab directory "<path>" command "<cmd>"
```

Currently not supported (Ghostty 1.3.0 has `has scripting terminology: false`).

## Task Instructions Template

When writing task descriptions for dispatched agents, include:

```
You are working on branch <branch-name> in a git worktree at <path>.
Base branch: <main/master>

Your task: <clear description of what to implement>

Requirements:
- <specific requirement 1>
- <specific requirement 2>

Files to focus on:
- <path/to/relevant/file>

When done:
1. Run tests to verify your work
2. Commit with a descriptive message
3. Report what you implemented and any issues found
```

This gives each agent enough context to work independently without knowledge of other parallel tasks.

## Common Mistakes

| Mistake | Fix |
|---------|-----|
| Dispatching dependent tasks in parallel | Identify dependencies first; sequence those, parallelize the rest |
| Not checking Ghostty is running | Pre-flight check catches this |
| Worktree directory not gitignored | Script auto-adds to .gitignore |
| Too many agents (>5) | System resources degrade; batch in groups |
| Dirty git state before dispatch | Commit or stash first |
| Forgetting to clean up worktrees | Use `git worktree remove` + `git branch -d` after merge |
| Agents editing overlapping files | Design tasks with clear file boundaries |

## Integration

| Skill | Relationship |
|-------|-------------|
| `using-git-worktrees` | Same directory conventions and gitignore safety checks |
| `ghostty` | Keybind parsing and terminal creation |
| `dispatching-parallel-agents` | Conceptual parent; this is the physical terminal-based implementation |
| `writing-plans` | Plans can specify tasks for parallel worktree dispatch |
| `finishing-a-development-branch` | Each dispatched agent should use this when completing their branch |
| `subagent-driven-development` | Alternative: in-process subagents vs. separate terminal agents |

## Example: Full Workflow

```
User: I need three features in parallel:
  1. User authentication (JWT)
  2. Dashboard API endpoints
  3. Email notification system

Orchestrator:
  "I'm using the orchestrating-worktree-agents skill to dispatch parallel agents."

  [Pre-flight: Ghostty running, git clean, on main, .worktrees/ ignored, opencode detected]

  Dispatching agent 1/3...
  > bash scripts/launch_worktree_agent.sh --branch feature/auth --task "..."
  > {"branch":"feature/auth","worktree":".worktrees/feature/auth","tool":"opencode",...}

  Dispatching agent 2/3...
  > bash scripts/launch_worktree_agent.sh --branch feature/dashboard-api --task "..."
  > {"branch":"feature/dashboard-api","worktree":".worktrees/feature/dashboard-api",...}

  Dispatching agent 3/3...
  > bash scripts/launch_worktree_agent.sh --branch feature/notifications --task "..."
  > {"branch":"feature/notifications","worktree":".worktrees/feature/notifications",...}

  "All 3 agents dispatched in separate Ghostty tabs:

   Tab 1: feature/auth         - OpenCode running
   Tab 2: feature/dashboard-api - OpenCode running
   Tab 3: feature/notifications - OpenCode running

   Switch between tabs with Cmd+1/2/3.
   Check progress: git log --oneline main..feature/auth
   When all agents finish, I'll help merge the branches."

  [Later, after agents complete:]

  "Cleaning up worktrees..."
  > git worktree remove .worktrees/feature/auth
  > git worktree remove .worktrees/feature/dashboard-api
  > git worktree remove .worktrees/feature/notifications
```
