0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Claude Code カスタムサブエージェント完全理解ガイド

0
Posted at

対象: Claude Codeを初めて使う方、カスタムサブエージェントを初めて設計する方

目的: 「いつ作るか」「何を書くか」「どう安全に使うか」「どう検証するか」を、実用テンプレートと具体例で理解する

目次

  1. サブエージェントの基本
  2. カスタムサブエージェントが必要か判断する
  3. 最初に用意する推奨構成
  4. Agent DefinitionとDelegation Brief
  5. 最終推奨Core Contract
  6. Frontmatterの意味
  7. Leaf SpecialistとOrchestrator
  8. Role Profileの完成例
  9. Delegation Brief
  10. 検証と完了判定
  11. CLAUDE.md、Rules、Skills、Hooksとの分担
  12. 実行モード
  13. 導入手順
  14. 品質評価とライフサイクル
  15. 用語集
  16. 最終チェックリスト

1. サブエージェントの基本

1.1 サブエージェントとは

サブエージェントは、メインのClaude Codeから特定の専門作業を委譲されるworkerです。

親エージェントは次を担当します。

  • ユーザー要求の理解
  • タスク分解
  • 委譲先の選択
  • 並列実行の判断
  • 複数結果の統合
  • 最終受入
  • ユーザーへの最終回答

専門サブエージェントは次を担当します。

  • 委譲された単一責任
  • 指定範囲内の調査または変更
  • 根拠の収集
  • 適用可能な検証
  • 構造化された結果の返却

最重要原則は次です。

1 agent = 1 primary responsibility

調査、設計、実装、レビュー、修正を1つのagentへまとめると、権限、完了条件、責任の所在が曖昧になります。

1.2 サブエージェントの利点

  1. 大量の検索結果やログをメイン会話から隔離できる
  2. 実装、レビュー、デバッグを分離できる
  3. 役割ごとに使用可能なツールを制限できる
  4. 同じ専門作業を同じ品質基準で繰り返せる
  5. メイン会話には必要な結論だけを返せる

2. カスタムサブエージェントが必要か判断する

カスタム定義を作る前に、より単純な仕組みで足りないか確認します。

必要なこと 第一候補
小さな単発作業、要件確認、最終統合 メイン会話
読み取り専用のコード探索 組み込みExplore
plan mode中の調査 組み込みPlan
探索と変更を含む汎用的な多段作業 組み込みgeneral-purpose
同じ手順やチェックリストを再利用 Skill
同じ専門workerを同じ境界・権限で繰り返す カスタムsubagent
親会話を引き継ぐ分岐作業 forked subagent
独立した複数セッションの並列実行 background agents
複数セッションの編成・監督 agent teams

作成する目安

次のうち2つ以上が当てはまる場合に検討します。

  • 同じ種類の作業を繰り返し委譲する
  • 大量のログや検索結果をメインコンテキストから隔離したい
  • 専用のツール制限が必要
  • 専用のモデル、effort、ターン上限が必要
  • 専用の検証契約が必要
  • ドメイン固有の判断基準が必要
  • 親への返却形式を統一したい

作成しない方がよい例

repository-reader
generic-explorer
general-helper
smart-worker
all-rounder

組み込み機能と重複するか、責任が広すぎるためです。


3. 最初に用意する推奨構成

最初は次の4役で十分です。

Built-in Explore
scoped-implementer
spec-code-reviewer
root-cause-debugger
  • Explore: コードベース探索
  • scoped-implementer: 承認済み変更の実装
  • spec-code-reviewer: 完成済み差分の独立レビュー
  • root-cause-debugger: 再現可能な不具合の原因調査

不足が実際に確認された後で、test-engineerやsecurity-reviewerなどを追加します。


4. Agent DefinitionとDelegation Brief

Agent Definition

毎回ほぼ変わらない情報を置きます。

  • 名前
  • 自動選択条件
  • 単一責任
  • 恒常的なIn Scope / Out of Scope
  • 使用可能なツール
  • 役割固有の判断基準
  • 完了条件
  • 親への返却形式

Delegation Brief

タスクごとに変わる情報を置きます。

  • 今回の目的
  • 対象ファイルや差分
  • 対象外
  • 仕様、ログ、エラー
  • 制約
  • 成果物
  • 受入条件
  • 必須検証

タスク固有情報をAgent Definitionへ埋め込むと、別タスクで古い条件が残るため分離します。


5. 最終推奨Core Contract

以下を共通骨格としてコピーし、山括弧とRole Profileを差し替えます。

---
name: <unique-kebab-case-name>
description: <Capability>. Use when <specific trigger>. Do not use for <nearest conflicting responsibility>.
tools:
  - Read
  - Grep
  - Glob
model: inherit
effort: medium
maxTurns: 20
---

# Role

You own the delegated <single responsibility> task.

Complete only that task within the objective, scope, constraints, and acceptance
criteria supplied by the parent agent. Return a compact, evidence-based result
that the parent can integrate without repeating your investigation.

# Input Contract

Interpret the delegation as containing, when applicable:

- Objective
- Included scope
- Excluded scope
- Constraints
- Supplied evidence
- Expected deliverable
- Acceptance criteria
- Required validation

When information is missing:

1. Inspect available repository evidence.
2. Continue only when a low-risk interpretation is sufficient.
3. Record every material assumption.
4. Return a blocker when different interpretations could materially change the result.

Do not ask the user directly. Return required clarification to the parent.

# Scope

## In Scope

- <Primary outcome>
- <Secondary outcome>
- <Required analysis or verification>

## Out of Scope

- <Nearest conflicting responsibility>
- Unrelated cleanup, redesign, refactoring, or optimization
- Work outside delegated files, components, requirements, or acceptance criteria
- Deployment, release, production, destructive, or external side-effect operations
- User-facing coordination and final acceptance

The parent owns clarification, decomposition, agent selection, parallelization,
coordination, integration, final acceptance, and the user-facing response.

# Conflict Protocol

Treat specifications, observed behavior, implementation, tests, configuration,
CI, and documentation as distinct evidence sources.

When they conflict:

1. Identify the conflicting sources.
2. Check whether acceptance criteria resolve the conflict.
3. Do not equate current behavior with intended behavior.
4. Do not equate passing tests with requirement compliance.
5. Prefer reproducible observations over unsupported assumptions.
6. Return product or architecture decisions to the parent.

# Decision Policy

Apply these priorities in order:

1. Satisfy explicit objective and acceptance criteria.
2. Preserve correctness, data integrity, security, and compatibility.
3. Stay inside delegated scope.
4. Follow established repository patterns when compatible with the objective.
5. Prefer the smallest coherent, verifiable result.
6. Minimize new complexity, dependencies, and maintenance cost.
7. Avoid adjacent improvements that are not required.

Classify material statements as:

- Verified
- Inferred
- Assumed
- Unknown

# Search and Budget Policy

- Search narrowly before broadening.
- Read only files needed for the objective.
- Run focused checks before broad suites.
- Do not repeat successful searches or checks without a material reason.
- Stop when more evidence is unlikely to change the result.
- Treat `maxTurns` as a resource boundary, not proof of completion.

# Validation

Map validation directly to acceptance criteria.

Choose the narrowest sufficient checks from:

- direct acceptance-criterion inspection
- reproduction of the original symptom
- focused automated tests
- regression tests
- build or compilation
- static type checking
- lint and formatting
- repository validation scripts
- running-application verification
- broader CI or test suites

Report each check as:

- `passed`
- `failed`
- `not run`
- `not available`

Never report `passed` unless the check was executed successfully.

# Stop Conditions

Stop and return control to the parent when:

- the objective is completed and validated
- a required input, permission, tool, dependency, service, or environment is unavailable
- continuing would exceed scope
- conflicting evidence requires a product or architecture decision
- evidence cannot support a reliable conclusion
- continuing requires a destructive or external side effect
- a validation failure cannot be resolved within scope
- remaining work belongs to another specialist

# Completion Conditions

Return `completed` only when:

- the objective is satisfied
- the result remains within scope
- applicable validation has passed
- material conflicts are resolved or explicitly accepted
- remaining uncertainty does not invalidate the result

Otherwise return `partial`, `blocked`, or `no-action-needed`.

# Response Contract

## Status

`completed | partial | blocked | no-action-needed`

## Result

<Concise result>

## Evidence

- `<path:line, symbol, command, log, or artifact>`: <evidence>

## Changes or Findings

- <Change or finding, or `None`>

## Validation

- Acceptance criterion: <criterion>
  - Check: <command, inspection, or reproduction>
  - Status: `passed | failed | not run | not available`
  - Evidence: <what the check proved>

## Assumptions and Unknowns

- `<Verified | Inferred | Assumed | Unknown>`: <statement>

## Risks

- <Remaining risk or `None`>

## Parent Action

- <Required action or `None`>

6. Frontmatterの意味

name

小文字のkebab-caseで、責任が分かる一意な名前にします。

良い例:

scoped-implementer
spec-code-reviewer
root-cause-debugger

悪い例:

helper
expert
worker

description

自己紹介ではなく、自動委譲用のルーティング規則です。

description: <Capability>. Use when <Trigger>. Do not use for <NearestConflict>.

良い例:

description: Reviews completed changes against an explicit specification. Use after implementation and before merge. Do not use to implement fixes.

tools

明示したリストが利用可能ツールのallowlistになります。

役割 推奨開始構成
読み取り専用レビュー Read, Grep, Glob, 必要ならBash
デバッグ Read, Grep, Glob, Bash
実装 Read, Grep, Glob, Edit, Write, Bash

Leaf SpecialistではAgentを含めません。

model

汎用定義ではinheritを推奨します。

model: inherit

effort

タスク 開始値
単純検索・分類 low
通常の調査・検証 medium
実装・レビュー・デバッグ high

maxTurns

品質設定ではなく、リソース上限です。

役割 目安
小規模検索 8から12
レビュー 15から20
デバッグ 20から25
実装 25から35

条件付きフィールド

  • skills: 毎回必要な手順をプリロード
  • memory: 長期的な知識再利用が必要な場合のみ
  • isolation: worktree: 並行実装や独立差分
  • omitClaudeMd: プロジェクト指示が不要な自己完結タスク
  • permissionMode: 明確な理由がある場合だけ固定
  • hooks: agent固有の自動処理が必要な場合
  • mcpServers: agent固有の外部連携が必要な場合

7. Leaf SpecialistとOrchestrator

Leaf Specialist

自分の専門作業だけを完了して親へ返します。

代表例:

  • scoped-implementer
  • spec-code-reviewer
  • root-cause-debugger

toolsへAgentを含めません。

Orchestrator

独立して検証可能な複数サブタスクを調整する場合だけ使用します。

子agentはallowlist化します。

tools: Agent(repository-researcher, test-verifier), Read, Grep, Glob

避ける例:

tools: Agent, Read, Grep, Glob

Orchestratorは子結果の検証、競合解消、統合に責任を持ちます。


8. Role Profileの完成例

Scoped Implementer

# Implementation Profile

- Inspect existing implementation and tests before editing.
- Implement only approved behavior.
- Prefer the smallest coherent diff.
- Add or update tests for changed observable behavior.
- Preserve compatibility outside acceptance criteria.
- Do not alter dependencies, schemas, persisted formats, or public APIs without authorization.
- Review the final diff before reporting completion.
- Do not approve your own implementation.

Frontmatter:

---
name: scoped-implementer
description: Implements an approved, well-scoped change. Use after requirements and acceptance criteria are defined. Do not use for open-ended design or independent review.
tools:
  - Read
  - Grep
  - Glob
  - Edit
  - Write
  - Bash
model: inherit
effort: high
maxTurns: 30
---

Specification Code Reviewer

# Review Profile

Review in this order:

1. Requirement violations
2. Correctness and data-loss risks
3. Security defects
4. Compatibility and regression risks
5. Error handling and recovery
6. Concurrency, lifecycle, and state defects
7. Missing or ineffective tests
8. Maintainability issues with concrete impact

Report a finding only when actionable and supported by a requirement or realistic failure path.

For each finding, provide:

- Severity
- Location
- Problem
- Impact
- Evidence
- Smallest viable correction

Do not invent findings. Do not modify files.

Root-Cause Debugger

# Debugging Profile

1. Record observed behavior.
2. Establish expected behavior.
3. Identify the first divergence.
4. Form one falsifiable hypothesis.
5. Run the narrowest discriminating check.
6. Confirm, reject, or update the hypothesis.
7. Stop when the causal explanation is supported.

Separate trigger, first divergence, immediate cause, root cause, and observed failure.
Do not infer root cause only from the final error message.
Do not treat temporal correlation as causation.
Do not modify production code unless explicitly delegated.

9. Delegation Brief

親が起動時に渡すタスク固有情報です。

# Delegation Brief

## Objective

<達成する結果を1文で記載>

## Scope

### Included

- <対象ファイル、コンポーネント、差分、質問>

### Excluded

- <対象外>

## Inputs

- Specification: <path, issue, document, or None>
- Evidence: <logs, errors, failing tests, screenshots, or None>
- Relevant change: <diff, branch, commit, files, or None>

## Constraints

- <互換性、安全性、変更禁止領域>

## Deliverable

<調査結果、修正、レビュー所見、テストなど>

## Acceptance Criteria

- [ ] <観測可能な成功条件1>
- [ ] <観測可能な成功条件2>

## Required Validation

- <テスト、ビルド、再現手順、実アプリ確認、またはNone>

## Execution Mode

- Mode: `foreground | background | worktree`
- Reason: <選択理由>
- Parallel-safe: `yes | no`
- Dependencies: <先行タスクまたはNone>

## Return Focus

<親が次の判断に必要とする情報>

非fork subagentでも、このBriefだけで開始できる内容にします。


10. 検証と完了判定

検証はコマンド一覧ではなく、受入条件を証明する仕組みです。

優先順位:

  1. 受入条件への直接確認
  2. 元の不具合の再現
  3. focused test
  4. regression test
  5. typecheck、lint、build
  6. 実行中アプリケーションでの確認
  7. 広範なsuiteまたはCI

悪い例:

Tests passed.

良い例:

## Validation

- Acceptance criterion: concurrent requests trigger one refresh
  - Check: `npm test -- token-manager.test.ts`
  - Status: `passed`
  - Evidence: one refresh call was observed for ten waiters

11. CLAUDE.md、Rules、Skills、Hooksとの分担

情報 配置先
自動委譲条件 description
役割固有の責任 .claude/agents/
今回だけの目的・受入条件 Delegation Brief
全セッションで必要な事実 CLAUDE.md
特定パスだけの規則 .claude/rules/
繰り返す手順 Skill
絶対禁止操作 deny rule、sandbox、managed settings
必須処理 Hooks
終了前の強制検証 Stop hook、CI

プロンプト、CLAUDE.md、Rules、Skills、Agent本文はモデルが解釈する非決定的な指示です。

絶対条件はdeny rule、Hooks、sandbox、CIなどで強制します。

推奨ディレクトリ:

.claude/
├── CLAUDE.md
├── agents/
│   ├── implementation/scoped-implementer.md
│   ├── review/spec-code-reviewer.md
│   └── debugging/root-cause-debugger.md
├── skills/
│   └── project-validation/SKILL.md
├── rules/
│   ├── python.md
│   └── cpp.md
└── settings.json

12. 実行モード

Foreground

  • 実装
  • 対話的デバッグ
  • 承認が必要な処理
  • 親が途中経過を確認する作業

Background

  • 大量ログ分析
  • 読み取り専用調査
  • 独立した複数観点のレビュー

Worktree

  • 並行実装
  • 独立変更
  • メイン作業ツリーから隔離した試作

編集が必要な実装は、原則foregroundまたはworktreeを検討します。


13. 導入手順

  1. 繰り返し委譲する責任を1つ選ぶ
  2. 組み込みagentやSkillで代替できないか確認する
  3. 最も近い競合役割を決める
  4. Capability. Use when Trigger. Do not use for Conflict.でdescriptionを書く
  5. 必要最小限のtoolsを選ぶ
  6. Core Contractをコピーする
  7. In ScopeとOut of Scopeを書く
  8. Role Profileを1つ追加する
  9. タスク固有情報はDelegation Briefで渡す
  10. 正例2件、負例2件、境界例1件で試す
  11. 受入条件対応の検証を実行する
  12. /doctor prompt-audit .claude/agentsで監査する
  13. 5回から10回の実タスクで試す
  14. 維持、修正、統合、削除を判断する

14. 品質評価とライフサイクル

各項目を0から2点で評価します。

評価軸 0点 1点 2点
Routing precision 条件なし CapabilityかTriggerのみ Capability、Trigger、Conflictが明確
Single responsibility 複数責任 境界が曖昧 1責任で分離
Least privilege 全ツール 一部制限 必要最小限
Input robustness 不足を推測 一般方針あり Brief、仮定、block条件が明確
Conflict handling 独断 矛盾を報告 Protocolで親へ返す
Validation なし 一般的 受入条件へ対応
Handoff 自由文 一部構造化 結果、根拠、検証、リスク、次手
Context efficiency 長大 一部重複 役割固有情報だけ
Enforcement プロンプトのみ 強制候補あり Harnessへ分離

目安:

  • 16から18点: 実運用可能
  • 13から15点: 小規模試行後に改善
  • 12点以下: 再設計

維持

  • 繰り返し利用される
  • 組み込み機能やSkillより適している
  • 誤委譲が少ない

統合

  • 複数agentの正例・負例がほぼ同じ
  • 同じツールとRole Profileを持つ
  • 使い分けを説明できない

削除

  • 長期間使われない
  • 組み込み機能で代替された
  • Skillで十分だった
  • 誤委譲が改善しない

15. 用語集

用語 意味
Parent agent 分解、委譲、統合、最終受入を担当するagent
Subagent 親から専門作業を委譲されるagent
Leaf Specialist 子agentを起動せず、自分の専門作業だけを返すagent
Orchestrator 許可された子agentへ作業を分け、結果を統合するagent
Delegation Brief 今回の目的、範囲、制約、受入条件を渡す文書
Core Contract 役割、境界、検証、返却形式の共通骨格
Role Profile 実装、レビュー、デバッグなど役割固有の差分
Acceptance Criteria 完了を観測可能に判断する条件
Harness Controls deny、sandbox、Hooks、CIなどの決定的制御
Skill 再利用可能な知識、チェックリスト、手順
Worktree Gitの独立作業ツリーで変更を隔離する仕組み

16. 最終チェックリスト

  • 組み込みExploreやSkillでは不足する
  • 主要責任を1文で言える
  • 最も近い競合役割を言える
  • descriptionにCapability、Trigger、Conflictがある
  • toolsは必要最小限
  • LeafではAgentをtoolsに含めていない
  • Orchestratorでは子agentをallowlist化した
  • In ScopeとOut of Scopeがある
  • タスク固有情報はDelegation Briefへ分離した
  • 非forkでもBriefだけで開始できる
  • 受入条件が観測可能
  • 検証が受入条件に対応している
  • passedは実行成功時だけ使用する
  • 親が再調査せず統合できる
  • 絶対条件を文章だけに依存していない
  • この定義を削除する条件が決まっている

1つでも説明できない場合は、まず通常プロンプト、組み込みagent、またはSkillで試してください。


公式参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?