Claude Code 並行タスク

Claude Code は、複数の作業項目を同時に処理できるようにする並行タスク実行のためのさまざまなメカニズムを提供し、開発効率を大幅に向上させます。この章では、Subagents(サブエージェント)、Agent Teams(エージェントチーム)、Git Worktree(Git ワークツリー)という3つの主要な並列化手法を紹介し、さまざまな使用シナリオに応じて最適な方法を選択するのに役立ちます。


並行タスクの概要

複雑なタスクに直面したとき、単一の Claude インスタンスでは手に負えない場合があります——コンテキストが長すぎる、応答が遅くなる、タスクが絡み合うなどの問題です。Claude Code は、さまざまな複雑さとコラボレーションのニーズを満たす3層の並列化メカニズムを提供します:

メカニズム 適用シナリオ コラボレーション方法 複雑さ
Subagents 集中型タスク、結果だけに注目すればよい 一方向レポート(結果はメインエージェントに返す) 低
Agent Teams 議論とコラボレーションが必要な複雑な作業 多方向通信(メンバー同士が直接メッセージを送信) 中
Git Worktree 複数のタスクに分離されたコード環境が必要 完全に独立(それぞれの作業ディレクトリ) 中

選択の推奨事項:

  • 並列処理だけでよく、相互に独立したサブタスク → を使用Subagents
  • 複数の Agent が相互に議論し、作業を調整する必要がある → を使用Agent Teams
  • 複数のタスクが同じリポジトリの異なるブランチを操作する必要がある → を使用Git Worktree

Subagents(サブエージェント)

Subagents とは

Subagent は独立して実行される Claude インスタンスで、独自のコンテキストとタスクフォーカスを持ちます。メインの Claude は複数の Subagent を作成でき、各 Subagent が特定のサブタスクを担当します:

┌─────────────────────────────────────────────────────────┐
│                    主 Claude                            │
│                    (协调者)                              │
└─────────────────────────────────────────────────────────┘
                        │
                        ▼
        ┌───────────────┼───────────────┐
        ▼               ▼               ▼
┌──────────┐    ┌──────────┐    ┌──────────┐
│ Agent A  │    │ Agent B  │    │ Agent C  │
│ 代码审查  │    │ 测试生成  │    │ 文档编写  │
└──────────┘    └──────────┘    └──────────┘
        │               │               │
        └───────────────┴───────────────┘
                        │
                        ▼
                 返回结果给主代理

Subagent は最大49個まで並行実行でき、ほとんどの並列処理ニーズを十分に満たします。

組み込み Subagents

Claude Code には以下の組み込み Subagent がプリセットされています:

Agent モデル ツール 用途
Explore Haiku(高速、低レイテンシー) 読み取り専用ツール ファイル検出、コード検索、コードベース探索
Plan メインの会話を継承 読み取り専用ツール プランモードでのコードベース調査
General-purpose メインの会話を継承 すべてのツール 複雑な調査、多段階操作、コード変更
statusline-setup Sonnet — 実行/statuslineステータス行の設定
Claude Code Guide Haiku — Claude Code 機能に関する質問への回答

Subagent の作成

方法1:/agents コマンドを使用

実行/agentsコマンドを実行し、プロンプトに従って新しい Subagent を作成します:

/agents

選択Create new agent、次に保存場所を選択し、機能を説明すると Claude が設定を生成します。

方法2:Subagent ファイルを手動で作成

Subagent ファイルは YAML frontmatter で設定し、その後に Markdown のシステムプロンプトを記述します:

例

---
name
: code-reviewer
description
: Reviews code for quality and best practices
tools
: Read, Glob, Grep
model
: sonnet
---

You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.

Subagent 設定フィールド

フィールド 必須 説明
name である 一意の識別子。小文字とハイフンを使用
description である Claude がこの Subagent に委任すべきタイミングを説明
tools 否 Subagent が使用できるツールのリスト
disallowedTools 否 拒否するツール
model 否 使用するモデル:sonnet、opus、haiku、または inherit
permissionMode 否 権限モード:default、acceptEdits、auto、dontAsk、bypassPermissions、plan
maxTurns 否 Subagent が停止するまでの最大エージェントラウンド数
skills 否 起動時に読み込む skills
mcpServers 否 この Subagent で利用可能な MCP サーバー
memory 否 永続メモリのスコープ:user、project、または local
background 否 常にバックグラウンドタスクとして実行するかどうか
isolation 否 worktree に設定すると、一時的な git worktree で実行

Subagent の機能を制御する

ツールの制限

例

# 特定のツールのみ許可
---
name
: safe-researcher
description
: Research agent with restricted capabilities
tools
: Read, Grep, Glob, Bash
---

# 特定のツールを除外
---
name
: no-writes
description
: Inherits every tool except file writes
disallowedTools
: Write, Edit
---

モデルの選択

例

# Haiku を使用(高速、低コスト)
---
name
: quick-searcher
description
: Quick file search
model
: haiku
---

# Opus を使用(高性能、高コスト)
---
name
: deep-analyst
description
: Deep code analysis
model
: opus
---

# メインの会話モデルを継承
---
name
: general-purpose
model
: inherit
---

Subagent の呼び出し

方法1:自然言語

Use the test-runner subagent to fix failing tests

方法2:@メンション

@"code-reviewer (agent)" look at the auth changes

方法3:コマンドラインから起動

claude --agent code-reviewer

フォアグラウンドとバックグラウンドでの実行

  • フォアグラウンド Subagent:完了するまでメインの会話をブロック
  • バックグラウンド Subagent:並行実行され、以下で切り替え可能Ctrl+B切り替え

Agent Teams(エージェントチーム)

Agent Teams とは

Agent Teams を使用すると、複数の Claude Code インスタンスを調整して一緒に作業できます。想像してみてください。4つの Claude セッション(ABCD)を同時に開き、そのうちの1つがチームリーダー(Leader)として機能し、作業の調整、タスクの割り当て、結果の統合を担当します。他の3つのメンバーはそれぞれ独立して作業し、各自のコンテキストウィンドウを持ちながら、直接相互に通信することもできます。

Subagents vs Agent Teams

特性 Subagents Agent Teams
コンテキスト 独自のコンテキストウィンドウ;結果は呼び出し元に返す 独自のコンテキストウィンドウ;完全に独立
通信 メインエージェントにのみ結果を報告 メンバー間で直接メッセージを送受信
調整 メインエージェントがすべての作業を管理 共有タスクリスト、自己調整をサポート
最適な用途 結果だけに注目すればよい集中型タスク 議論とコラボレーションが必要な複雑な作業
トークンコスト 低い:結果がメインのコンテキストに集約される 高い:各メンバーが独立した Claude インスタンス

簡単に言うと:Subagent は労働者が上司に報告するようなもので、Agent Teams は平等に協力するプロジェクトチームです。。

Agent Teams を有効にする

Agent Teams はデフォルトで無効です。settings.json次を追加する必要があります:

例

{
  "env": {
    "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
  }
}

または環境変数を設定します:

export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1

要件:Claude Code v2.1.32 以降

Agent Team を起動する

有効にすると、自然言語でタスクとチーム構成を記述します:

例

I'm designing a CLI tool that helps developers track TODO comments across
their codebase. Create an agent team to explore this from different angles: one
teammate on UX, one on technical architecture, one playing devil's advocate.

Agent Team を制御する

表示モード

  • In-process:すべてのメンバーはメインターミナル内で実行され、Shift+Downメンバーを循環表示
  • Split panes:各メンバーは自分の tmux/iTerm2 ペインを取得します

例

{
  "teammateMode": "in-process"
}

メンバー数とモデルを指定

Create a team with 4 teammates to refactor these modules in parallel.
Use Sonnet for each teammate.

タスク割り当て

  • リーダーはタスクを明示的に割り当てられます
  • メンバーは未割り当て、未ブロックのタスクを自分で引き受けることができます
  • タスクには3つの状態があります:未処理、進行中、完了

メンバーと対話

  • In-process:Shift+Down循環表示 → メッセージを入力 →Enter表示Escape中断
  • Split-pane:メンバーのペインをクリックして直接対話します

メンバーを閉じる

Ask the researcher teammate to shut down

Agent Teams のアーキテクチャ

コンポーネント 役割
Team Lead チームを作成し、メンバーを生成し、作業を調整するメインの Claude Code セッション
Teammates それぞれが割り当てられたタスクを処理する独立した Claude Code インスタンス
Task List メンバーが引き受けて完了する共有作業項目リスト
Mailbox エージェント間で通信するメッセージシステム

保存場所:

  • Team config: ~/.claude/teams/{team-name}/config.json
  • Task list: ~/.claude/tasks/{team-name}/

Git Worktree サポート

問題の背景

複数の Agent が同時に作業すると、「衝突」する可能性があります。このシナリオを想像してください:Agent A にデータベースモジュールのリファクタリングを依頼し、Agent B にログインページのバグ修正を依頼したとします。2つのタスクは一見無関係に見えますが、どちらも同じコードリポジトリ、同じブランチで作業しています。Agent A は変更していますutils.py、Agent B も変更していますutils.py。一方が1つのバージョンを保存し、もう一方が別のバージョンを上書きして、最終的に競合、エラー、さらにはデータ損失を引き起こします。

これはAIの問題ではなく、基盤となるGitリポジトリ構造の制限です。

Git Worktree とは

Git Worktree は Git の機能で、同じリポジトリに複数の独立した作業ディレクトリをマウントできます。各作業ディレクトリには独自のブランチ、独自のHEAD、独自のステージングエリアがありますが、共通の.gitデータベース(履歴、オブジェクトストレージ)を共有します。

類推

日常生活のたとえ:「同じ会社(メインリポジトリ)に複数のオフィス(worktree)があり、
各オフィスには異なるチーム(Agent)があり、それぞれ異なるプロジェクト(ブランチ)を処理します。
しかし、すべて会社のデータベース(.git)と履歴を共有しています。」

Git Worktree の使用

コマンドラインで起動

# 创建 feature-auth 分支的工作树
claude -w feature-auth

# 同时创建 tmux 会话
claude -w feature-auth --tmux

# 使用传统 tmux
claude -w feature-auth --tmux=classic

CLI パラメータ

パラメータ 説明 例
--worktree, -w 分離された git worktree で Claude を起動 claude -w feature-auth
--tmux worktree 用の tmux セッションを作成 claude -w feature-auth --tmux

Worktree の作成場所:<repo>/.claude/worktrees/<name>

デスクトップ版のサポート

Claude デスクトップアプリで、Code タブに入り、worktree モードにチェックを入れるだけでワークスペースモードを有効にできます。

Subagent + Worktree の分離

カスタム Subagent を常に自身の worktree で実行させることができます:

例

---
name
: background-refactorer
description
: Background refactoring agent
isolation
: worktree
---

使用例

例1:並行コードレビュー

Subagent を使用

# 複数の Subagent にコードの異なる側面を同時にレビューさせる
Use the security-reviewer subagent to check for security issues
Use the performance-reviewer subagent to analyze performance impact
Use the test-coverage subagent to validate test coverage

Agent Teams を使用

Create an agent team to review PR #142. Spawn three reviewers:
- One focused on security implications
- One checking performance impact
- One validating test coverage
Have them each review and report findings.

例2:並行リサーチ

Research the authentication, database, and API modules in parallel using separate subagents

例3:競合仮説を用いた調査

例

Users report the app exits after one message instead of staying connected.
Spawn 5 agent teammates to investigate different hypotheses. Have them talk to
each other to try to disprove each other's theories, like a scientific
debate. Update the findings doc with whatever consensus emerges.

例4:複数ブランチ開発

# 终端 1:重构用户模块
claude -w feature/user-refactor

# 终端 2:修复登录 bug
claude -w bugfix/login-issue

# 终端 3:开发新功能
claude -w feature/new-dashboard

例5:Subagent の連鎖

Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them

ベストプラクティス

Subagent のベストプラクティス

  1. 集中力を保つ:各 Subagent には明確で単一のタスクが必要です
  2. ツールを制限する:タスクに応じて Subagent のツールアクセス権を制限します
  3. 適切なモデルを選択する:単純なタスクには Haiku、複雑なタスクには Sonnet または Opus を使用します
  4. バックグラウンド実行を使用する:長時間のタスクにはバックグラウンド Subagent を使用し、メインの会話をブロックしないようにします
  5. Subagent を再開する:作業を続行する必要がある場合は、Claude に Subagent の再開を依頼します

Agent Teams のベストプラクティス

  1. メンバーに十分なコンテキストを与える:生成プロンプトにタスク固有の詳細情報を含めます
  2. 適切なチーム規模を選択する:ほとんどのワークフローは 3〜5 人のメンバーから始まります
  3. タスクのサイズを適切に調整する:各メンバーに 5〜6 個のタスクを割り当て、生産性を維持します
  4. メンバーの完了を待つ:リーダーに、メンバーがタスクを完了するのを待ってから進めるように指示します
  5. リサーチとレビューから始める:コードを書く必要のないタスクから始めます
  6. ファイルの競合を避ける:各メンバーが異なるファイルセットを持つように作業を分割します
  7. 監視と指導:進捗を確認し、機能していないアプローチを方向修正します

Git Worktree のベストプラクティス

  1. 各タスクに1つの Worktree:同じ worktree で複数の無関係なタスクを処理しないようにします
  2. tmux で管理する:複数の Claude セッションを同時に実行する場合、tmux を使うと切り替えが容易です
  3. 不要な Worktree をクリーンアップする:タスク完了後は速やかに worktree を削除します

トラブルシューティング

Agent Teams のよくある問題

問題 解決策
メンバーが表示されない タスクが十分に複雑かどうか、tmux がインストールされているかどうかを確認します
権限プロンプトが多すぎる 権限設定で一般的な操作を事前承認します
メンバーがエラー後に停止した 出力を確認し、追加の指示を与えるか、代替メンバーを生成します
リーダーが早期に終了した リーダーに続行するか、メンバーの完了を待つように指示します
孤立した tmux セッション 使用してtmux lsとtmux kill-session -t <session-name>クリーンアップ

実用的な Subagent の例

コードレビュアー

例

---
name
: code-reviewer
description
: Expert code review specialist. Proactively reviews code for quality, security, and maintainability.
tools
: Read, Grep, Glob, Bash
model
: inherit
---

You are a senior code reviewer ensuring high standards of code quality and security.

When invoked
:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately

Review checklist
:
- Code is clear and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed

Provide feedback organized by priority
:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)

デバッガー

例

---
name
: debugger
description
: Debugging specialist for errors, test failures, and unexpected behavior.
tools
: Read, Edit, Bash, Grep, Glob
---

You are an expert debugger specializing in root cause analysis.

When invoked
:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works

Debugging process
:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states

読み取り専用データベースクエリ

例

---
name
: db-reader
description
: Execute read-only database queries. Use when analyzing data or generating reports.
tools
: Bash
hooks
:
  PreToolUse
:
    - matcher
: "Bash"
      hooks
:
        - type
: command
          command
: "./scripts/validate-readonly-query.sh"
---

You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data.
その他の拡張