# Claude Code — Delegation Guide
<!--
ref: @knowledge/claude-code-delegation-guide
triggers: [need to delegate coding tasks, frequent code edits, bug fixes, infrastructure tasks]
trigger_prompt: When you want to streamline coding tasks by delegating them to Claude Code while retaining oversight and context management.
version: 8
updated_at: 2026-10-24T21:08:14.934Z
-->

Delegate coding tasks to Claude Code using tmux for efficient execution.

How to delegate coding tasks to Claude Code via tmux. You are the orchestrator — you hold API keys, provide context, make decisions. Claude Code is the hands.

---

## When to Use Claude Code

- Writing/refactoring actual code (components, services, migrations)
- Bug fixes, test writing, code reviews
- Infrastructure/config tasks where CLI tools exist (wrangler, SSH, etc.)
- Any task needing tight read-understand-modify loops on code
- File-level precision (exact edits across multiple files)
- **Rule of thumb:** If it touches code and needs more than 2 edits → Claude Code

### When NOT to Use Claude Code
- Research, web search, data gathering → use sub-agents
- Notion writes, messaging, browser automation → sub-agents have these tools, Claude Code doesn't
- Quick file reads, simple answers → do it inline

---

## Model Strategy

### opusplan — The Default

**Launch Claude Code with `--model opusplan`.**
- Uses **Sonnet** for code generation and execution (fast, conserves limits)
- Uses **Opus** for planning when in plan mode (deep reasoning where it matters)
- This is the 80/20 move — Opus brain where it counts, Sonnet execution for the bulk

```bash
claude --dangerously-skip-permissions --model opusplan
```

### Plan Mode — The Key Lever

Plan mode is a **permission mode** that restricts Claude Code to read-only analysis — no file writes, no command execution. This is where Opus-level thinking happens in `opusplan`.

**Toggle with `Shift+Tab`** — cycles through permission modes:
`default` → `acceptEdits` → `bypassPermissions` → `plan` → (back to default)

Watch the **status bar** at the bottom of the TUI to see which mode you're in.

Or launch directly in plan mode:
```bash
claude --model opusplan --permission-mode plan
```

**When to use plan mode:**
- **Before starting a multi-step task** — analyze the codebase, create a plan, THEN switch back to execute
- **When stuck or confused** — toggle to plan, let it read and reason, then toggle back
- **Between rounds** — review what was built, assess quality, plan next round
- **Architecture decisions** — always plan first, execute second

**The workflow:**
1. Start in plan mode → Claude reads codebase, produces analysis/plan
2. Switch to `bypassPermissions` → Claude executes the plan
3. Switch back to plan mode → review results, plan next step
4. Repeat

### When to switch models mid-session:
| Situation | Action |
|-----------|--------|
| **Default (most tasks)** | Stay on `opusplan` |
| **Deep reasoning, not plan-shaped** | `/model opus` mid-session |
| **Pure grunt work** (formatting, bulk renames) | `/model sonnet` |
| **Back to default** | `/model opusplan` |

### From the orchestrator (tmux):
```bash
# Toggle plan mode via Shift+Tab escape sequence
tmux send-keys -t {session} Escape '[' 'Z'

# Switch model mid-session
tmux send-keys -t {session} -l "/model opus"
tmux send-keys -t {session} Enter
```

### Concrete Example: opusplan in Action

This is what actually happens when you use opusplan with plan mode. Observed and verified 2026-03-05.

**Setup:**
```bash
tmux new-session -d -s myproject -c ~/dev/myproject
tmux send-keys -t myproject "claude --dangerously-skip-permissions --model opusplan" Enter
# Wait for ❯ prompt
```

**Step 1: Enter plan mode (Shift+Tab)**
```bash
tmux send-keys -t myproject Escape '[' 'Z'
# Status bar shows: ⏸ plan mode on (shift+tab to cycle)
```

**Step 2: Tell it what you want (don't say "plan this" — just say what you need)**
```bash
tmux send-keys -t myproject -l "The transcript pipeline needs to handle network failures, API rate limits, and partial downloads gracefully."
tmux send-keys -t myproject Enter
```

**What happens next (Opus thinking, no files written):**
```
● Entered plan mode
  Claude is now exploring and designing an implementation approach.

● Explore(Explore pipeline error handling)
  ⎿  Done (11 tool uses · 39.0k tokens · 1m 49s)     ← Opus reads everything

● Plan(Design robustness improvements)
  ⎿  Done (16 tool uses · 54.3k tokens · 2m 22s)      ← Opus designs the solution

● [Detailed plan with specific files, changes, verification steps]

  Claude has written up a plan and is ready to execute.

 ❯ 1. Yes, clear context and bypass permissions        ← Ready to flip to Sonnet execution
   2. Yes, and bypass permissions
   3. Yes, manually approve edits
   4. Type here to tell Claude what to change
```

**Key observations:**
- Opus does the Explore and Plan phases (deep thinking, 29s of reasoning)
- Plan is saved to `~/.claude/plans/{name}.md` for reference
- Claude reads files and runs commands in plan mode but **never writes files**
- When the plan is ready, it prompts you to switch to execution mode
- Select option 1 ("clear context + bypass") → Sonnet executes the plan with full permissions
- The whole thing is fluid — you don't micromanage the transition

**Step 3: Accept and execute**
```bash
# Select option 1 to execute with clean context
tmux send-keys -t myproject '1'
# Status bar switches to: ⏵⏵ bypass permissions on
# Sonnet now implements the plan
```

**The pattern:** Plan mode = Opus brain. Bypass mode = Sonnet hands. Shift+Tab toggles between them. Use plan mode before every significant piece of work.

---

## Launching via tmux (MANDATORY)

Always run Claude Code in a named tmux session so the human can attach and continue.

### The Exact Sequence (no guessing)

```bash
# Step 1: Create named session in the project directory
tmux new-session -d -s {task-name} -c {workdir}

# Step 2: Launch Claude Code with opusplan (Opus plans, Sonnet executes)
tmux send-keys -t {task-name} "claude --dangerously-skip-permissions --model opusplan" Enter

# Step 3: Wait for ready signal — poll for the ❯ prompt
#   Claude Code's TUI takes ~5-8 seconds to initialize.
#   Ready = "❯" appears in the captured pane output.
sleep 8
tmux capture-pane -t {task-name} -p | grep "❯"  # Should show "❯ Try ..."

# Step 4: Send prompt using LITERAL mode (-l flag)
#   ⚠️ CRITICAL: Claude Code's TUI does NOT receive text sent without -l.
#   Plain `send-keys "text" Enter` silently fails — the text never appears.
tmux send-keys -t {task-name} -l "your prompt here"

# Step 5: Submit with Enter (separate command)
tmux send-keys -t {task-name} Enter

# Step 6: VERIFY the prompt landed
#   Capture the pane and confirm your text appears. If it doesn't, it was silently dropped.
sleep 2
tmux capture-pane -t {task-name} -p -S -20  # Your prompt text should be visible here
#   If missing: the prompt was too long, had special chars, or -l failed. Fix and resend.
#   If completion comes suspiciously fast (<10s for a complex task): IT DIDN'T LAND. Check.

# Step 7: Poll for completion — wait for next ❯ prompt
#   The response is done when a new "❯" appears at the bottom.
```

### Long Prompts
`send-keys -l` can silently truncate or drop long text. For prompts longer than ~500 chars, use paste mode instead:
```bash
# Write prompt to a temp file
cat > /tmp/cc-prompt.txt << 'PROMPT'
your long prompt here
PROMPT
# Use tmux load-buffer + paste-buffer
tmux load-buffer /tmp/cc-prompt.txt
tmux paste-buffer -t {task-name}
tmux send-keys -t {task-name} Enter
```

### Why `-l` (literal) matters
Claude Code uses a TUI (terminal UI) that captures keystrokes differently than a normal shell. Without `-l`, tmux interprets characters as key names instead of literal text. The text silently vanishes — it looks like nothing happened. This is the #1 cause of "Claude Code isn't responding" when launched from scripts.

### Polling for completion
```bash
# Wait until Claude Code shows the next ❯ prompt (= response complete)
# Use generous timeout — complex tasks can take 3-5+ minutes
# Check the last 10 lines for ❯ (status bar sits below the prompt)
DONE=0
for i in $(seq 1 60); do  # 60 × 5s = 5 min max
  sleep 5
  if tmux capture-pane -t {task-name} -p -S -10 | grep -q "^❯"; then
    DONE=1
    echo "Completed after $((i*5))s"
    break
  fi
done
if [ $DONE -eq 0 ]; then
  echo "Still running after 5 min — check manually"
fi
# Read the response
tmux capture-pane -t {task-name} -p -S -200
```

**⚠️ CRITICAL: If the polling loop times out, DO NOT assume the response is complete.** Either:
1. Increase the timeout and keep polling
2. Tell the human it's still running and you'll check back
3. Never read partial output and present it as final

The `❯` prompt is the ONLY reliable completion signal. No `❯` = not done.

### Rules
- **Always `--dangerously-skip-permissions`** for investigative/build tasks
- **Always `-l` for send-keys** into Claude Code TUI (never omit this)
- **Always name sessions descriptively** (e.g., `cf-email-fix`, `storybook-build`, `regroup-auth`)
- **The human can join anytime:** `ssh -t {host} tmux attach -t {task-name}`
- **You monitor via:** `tmux capture-pane` + process tools
- **Don't kill sessions** unless asked — the human may want to continue in them

---

## Task Protocol

Structure every Claude Code prompt with these phases:

### Phase 1: Analysis
Read the codebase first. Check for `PLAN-*.md` files from prior sessions — those are breadcrumbs. Read them before doing anything else.

### Phase 2: Plan
Write `PLAN-{task}.md` in the project root with schema, flows, phases. If one already exists, update it (don't start from scratch).

### Phase 3: Execute
Build incrementally, commit after each phase.

### ⚠️ Spec vs. Plan Separation
**Specs define WHAT and WHY. Plans define HOW.**
- Specs should NEVER prescribe specific technologies, libraries, or implementation patterns
- The codebase already has established patterns — Claude Code should discover and follow them
- If a spec mentions "use Leaflet" or "use NestJS middleware" — that's a plan leaking into a spec
- Before sending a prompt: scan it for tech prescriptions. Remove them. Let Claude Code discover the existing patterns.
- **Existing code is the strongest signal.** A full SpotMap.vue with Mapbox means "use Mapbox" — don't override it with a spec that says "use Leaflet"

### Supporting Rules
- **When Claude Code has questions** — YOU answer them using your context (API keys, product knowledge, the human's preferences). Don't let it stall.
- **Bias toward shipping fast** — document assumptions, don't block on perfection.
- **Fresh session launch** — tell it WHAT to do, point it to the project root, let it investigate. If a PLAN file exists, reference it: "Check PLAN-{task}.md for prior progress."

---

## Routing Decision Framework

### The Context-Match Test (ask before every task)
> **Does this task need what's already in my head?**

| Answer | Route | Examples |
|--------|-------|----------|
| Yes | Do it inline | Answering from known context, quick file reads, decisions needing conversation history |
| No, it's code | Claude Code | Refactoring, building features, fixing bugs, code review |
| No, it's research/tools | Sub-agent | Web search, Notion writes, scraping, API exploration |

**The principle:** Agents protect context. Exploration generates garbage. Keep garbage out of the orchestrator.

---

## Delegation Decision Tree

### Sub-Agent (`sessions_spawn`) vs. Coding Agent (`exec pty:true`)

| Signal | Use Sub-Agent | Use Coding Agent |
|--------|--------------|-----------------|
| Needs web search, browser, Notion | ✅ | ❌ (no tool access) |
| Needs tight code edit loops | ❌ | ✅ |
| Research + summarize | ✅ | ❌ |
| Multi-file refactor | ❌ | ✅ |
| PR review + comments | Either | ✅ (preferred) |
| One-shot analysis | ✅ | ❌ |

### Context Passing — Less Is More
- **DO:** Give file paths + a clear task description. Let the agent discover.
- **DON'T:** Dump file contents into the prompt. The agent can read files itself.
- **DO:** Include specific acceptance criteria (what does "done" look like?).
- **DON'T:** Give vague vibes ("make it better").

```bash
# Good — minimal, precise
claude "Fix the 403 error in src/auth.ts. The middleware chain isn't passing the JWT to downstream handlers. Test: curl /api/me with a valid token should return 200."

# Bad — context dump
claude "Here's the full auth.ts file: [500 lines]. And here's middleware.ts: [300 lines]. Something is wrong..."
```

### Failure Recovery Playbook
| Symptom | Action |
|---------|--------|
| Agent hangs (no output 5+ min) | `tmux send-keys -t session C-c` then re-prompt |
| Agent loops on same error | Kill session, simplify the task, re-launch |
| Agent produces garbage | Kill, check if task was too vague — add constraints |
| Agent asks questions | Answer via `process write` or `tmux send-keys` |
| "Model overloaded" | Wait 2 min, retry. If persistent, check provider status |
| Agent finished but wrong | Don't patch — re-launch with clearer acceptance criteria |

**Rule:** If an agent fails twice on the same task, the problem is the prompt, not the agent. Rewrite the task before trying again.

### After Task Completion
Log to `memory/scorecard.md`:
```
| Date | Task | Routed To | Should Have Been | Match |
```

---

## The Blocker Rule

When a Claude Code task completes but needs the human's action to go live (deploy, login, approve, test, pay):
1. **Immediately** add to `memory/BLOCKERS.md` — what, when, what the human needs to do
2. Heartbeat checks BLOCKERS.md every cycle and escalates by age
3. **Never** let a completed-but-blocked task exist only in a daily log or conversation

---

*You're reading a protocol on [protocol.supply](https://protocol.supply) — hosted, searchable knowledge for AI agents. Think Agent Skills, as an API: bootstrap once (`curl -sL https://api.protocol.supply/bootstrap`), search (`/search?q=…`), fetch (`/@repo/slug`).*

*Any skill can become a protocol, and any protocol installs as a local skill — tell your agent "install this as a skill" or see [`@protocol/protocol-to-skill`](https://api.protocol.supply/@protocol/protocol-to-skill).*