Claude Code カスタムサブエージェント完全理解ガイド #AI - Qiita
@okmonn(おか もん)

The Complete Guide to Claude Code Custom Subagents

  • AI
  • AI Utilization
  • AIAgent
  • ClaudeCode
  • Claude
TAG30@@0
Posted at 2026-11-11
TAG40
TAG42

Audience: Those new to Claude Code and those designing custom subagents for the first time

Purpose: Understand “when to create one,” “what to write,” “how to use it safely,” and “how to validate it” through practical templates and concrete examples

Contents

  1. Subagent Basics
  2. Determining Whether a Custom Subagent Is Necessary
  3. Recommended Initial Setup
  4. Agent Definition and Delegation Brief
  5. Final Recommended Core Contract
  6. Meaning of Frontmatter
  7. Leaf Specialist and Orchestrator
  8. Example of a Completed Role Profile
  9. Delegation Brief
  10. Validation and Completion Criteria
  11. Division of Responsibilities among CLAUDE.md, Rules, Skills, and Hooks
  12. Execution Modes
  13. Setup Procedure
  14. Quality Evaluation and Lifecycle
  15. Glossary
  16. Final Checklist

1. Subagent Basics

1.1 What Is a Subagent?

A subagent is a worker to which the main Claude Code delegates specific specialized work.

The parent agent is responsible for the following:

  • Understanding user requirements
  • Task decomposition
  • Selecting the delegate
  • Determining whether to execute in parallel
  • Integrating multiple results
  • Final acceptance
  • Providing the final response to the user

The specialized subagent is responsible for the following:

  • The single delegated responsibility
  • Research or modifications within the specified scope
  • Gathering evidence
  • Applicable verification

The most important principle is as follows.

1 agent = 1 primary responsibility

Combining research, design, implementation, review, and fixes within a single agent makes the authority, completion criteria, and location of responsibility ambiguous.

1.2 Advantages of subagents

  1. Large volumes of search results and logs can be isolated from the main conversation
  2. Implementation, review, and debugging can be separated
  3. Available tools can be restricted according to role
  4. The same specialized work can be repeated using the same quality standards
  5. Only the necessary conclusions can be returned to the main conversation

2. Determine whether a custom subagent is necessary

Before creating a custom definition, check whether a simpler mechanism is sufficient.

What is needed Primary candidate
Small one-off tasks, requirements clarification, final integration Main conversation
Read-only code exploration Built-in Explore
Research during plan mode Built-in Plan
General-purpose multi-stage work involving exploration and changes Built-in general-purpose
Reuse of the same procedure or checklist Skill
Repeated use of the same specialized worker with the same boundaries and permissions Custom subagent
Branching work that inherits the parent conversation Forked subagent
Parallel execution of multiple independent sessions Background agents
Coordination and supervision of multiple sessions Agent teams

Guidelines for creating one

Consider creating one when two or more of the following apply.

  • Repeatedly delegating work of the same kind
  • You want to isolate large volumes of logs and search results from the main context
  • Dedicated tool restrictions are required
  • A dedicated model, effort setting, and turn limit are required
  • A dedicated validation contract is required
  • Domain-specific decision criteria are required
  • We want to standardize the return format to the parent

Examples of things that are better not to create

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

This is because they overlap with built-in functionality or have an overly broad scope of responsibility.

3. Recommended initial configuration

The following four roles are sufficient to start with.

Built-in Explore scoped-implementer spec-code-reviewer root-cause-debugger
  • Explore: Codebase exploration
  • scoped-implementer: Implementation of approved changes
  • spec-code-reviewer: Independent review of completed diffs

After gaps have actually been identified, add roles such as test-engineer and security-reviewer.

4. Agent Definition and Delegation Brief

Agent Definition

Place information that remains almost unchanged each time.

  • Name
  • Automatic selection criteria
  • Single responsibility
  • Standing In Scope / Out of Scope
  • Available tools
  • Role-specific decision criteria
  • Completion criteria
  • Return format to the parent

Delegation Brief

Place information that changes from task to task.

  • Objective of this task
  • Target files or diffs
  • Out of scope
  • Specifications, logs, and errors
  • Constraints
  • Deliverables
  • Acceptance criteria
  • Required validation

If task-specific information is embedded in the Agent Definition, outdated conditions may remain in other tasks, so keep them separate.

5. Final Recommended Core Contract

Copy the following as a common skeleton, and replace the angle brackets and 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 @@TAG@@- 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 resultOtherwise 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. Meaning of Frontmatter

name

Use a unique lowercase kebab-case name that makes the responsibility clear.

Good examples:

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

Bad examples:

helper expert worker

description

This is not a self-introduction, but a routing rule for automatic delegation.

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

Good example:

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

tools

The explicit list serves as the allowlist of available tools.

Role Recommended starting configuration
Read-only review Read, Grep, Glob, Bash if necessary
Debugging Read, Grep, Glob, Bash
Implementation Read, Grep, Glob, Edit, Write, Bash

Leaf Specialist does not include Agent.

model

For general-purpose definitions, inherit is recommended.

model: inherit

effort

Task Starting value
Simple search/classification low
Standard research/verification medium
Implementation/review/debugging high

maxTurns

This is a resource limit, not a quality setting.

Role Guideline
Small-scale search 8 to 12
Review 15 to 20
Debugging 20 to 25
Implementation 25 to 35

Conditional fields

  • skills: Preload procedures needed every time
  • memory: Only when long-term knowledge reuse is required
  • isolation: worktree: Parallel implementation or independent diffs
  • omitClaudeMd: Self-contained tasks that do not require project instructions
  • permissionMode: Set it only when there is a clear reason
  • hooks: When agent-specific automated processing is required
  • mcpServers: When agent-specific external integration is required

7. Leaf Specialist and Orchestrator

Leaf Specialist

Complete only your own specialized work and return it to the parent.

Representative examples:

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

Do not include Agent in tools.

Orchestrator

Use only when coordinating multiple subtasks that can be independently verified.

Allowlist subagents.

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

Example to avoid:

tools: Agent, Read, Grep, Glob

The Orchestrator is responsible for validating subagent results, resolving conflicts, and integrating them.

8. Example of a completed 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

Task-specific information passed by the parent at startup.

# Delegation Brief ## Objective ## Scope ### Included - , components, diffs, questions>, questions>> ### 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 - <Compatibility,Security,areas where changes are prohibited> ## Deliverable <Investigation results, fixes, review findings, tests, etc.> ## Acceptance Criteria - [ ] <Observable success condition 1> - [ ] <Observable success condition 2> ## Required Validation - <test, build, reproduction steps, real-app verification, or None> ## Execution Mode - Mode: `foreground | background | worktree` - Reason: <reason for selection> - Parallel-safe: `yes | no` - Dependencies: <preceding task or None> ## Return Focus <Information the parent needs to make the next decision>

Ensure that even a non-fork subagent can start with this Brief alone.

10. Verification and Completion Criteria

Verification is not a list of commands, but a mechanism for proving the acceptance criteria.

Priority:

  1. Direct verification of the acceptance criteria
  2. Reproduction of the original bug
  3. focused test
  4. regression test
  5. typecheck, lint, build
  6. Verification in the running application
  7. Broad suite or CI

Bad example:

Tests passed.

Good example:

## 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, and Hooks

Information Location
Automatic delegation criteria description
Role-specific responsibilities .claude/agents/
Purpose and acceptance criteria for this particular task Delegation Brief
Facts needed for all sessions CLAUDE.md
Rules for specific paths .claude/rules/
Repeatable procedures Skill
Absolutely prohibited operations deny rules, sandbox, managed settings
Mandatory procedures Hooks
Mandatory verification before completion Stop hook, CI

Prompts, CLAUDE.md, Rules, Skills, and agent body text are nondeterministic instructions interpreted by the model.

Hard requirements are enforced through deny rules, Hooks, sandbox, CI, etc.

Recommended directory:

.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. Execution Modes

Foreground

  • Implementation
  • Interactive debugging
  • Operations requiring approval
  • Tasks where the parent agent checks progress along the way

Background

  • Large-scale log analysis
  • Read-only investigation
  • Independent review from multiple perspectives

Worktree

  • Parallel implementation
  • Independent changes
  • Prototyping isolated from the main working tree

As a rule, consider foreground execution or a worktree for implementation work that requires editing.

13. Introduction Procedure

  1. Choose one responsibility to delegate repeatedly
  2. Check whether it can be replaced by a built-in agent or Skill
  3. Determine the closest competing role
  4. Write the description in the form “Capability. Use when Trigger. Do not use for Conflict.”
  5. Choose the minimum necessary tools
  6. Copy the Core Contract
  7. Write In Scope and Out of Scope
  8. Add one Role Profile
  9. Pass task-specific information through the Delegation Brief
  10. Test with 2 positive examples, 2 negative examples, and 1 boundary case
  11. Run validation corresponding to the acceptance criteria
  12. Audit with /doctor prompt-audit .claude/agents
  13. Test with 5 to 10 actual tasks
  14. Decide whether to retain, revise, integrate, or delete

14. Quality Evaluation and Lifecycle

Score each item from 0 to 2 points.

Evaluation criterion 0 points 1 point 2 points
Routing precision No conditions Capability or Trigger only Capability, Trigger, and Conflict are clear
Single responsibility Multiple responsibilities Ambiguous boundaries Separated into a single responsibility
Least privilegeAll tools Some restrictions Minimum necessary
Input robustness Infer what is missing General guidelines available Brief, assumptions, and block conditions are clear
Conflict handling Acting unilaterally Report contradictions Return to the parent via the protocol
Validation None General Mapped to acceptance criteria
Handoff Free-form text Partially structured Results, rationale, verification, risks, and next steps
Context efficiency Lengthy Some duplication Only role-specific information
Enforcement Prompt only Enforcement candidates available Separated into the harness

Guidelines:

  • 16 to 18 points: Ready for practical use
  • 13 to 15 points: Improve after a small-scale trial
  • 12 points or below: Redesign

Maintain

  • Used repeatedly
  • Better suited than built-in features or Skills
  • Fewer misdelegations

Consolidate

  • Positive and negative examples for multiple agents are nearly identical
  • Have the same tools and Role Profile
  • Cannot explain how to distinguish between them

Delete

  • Not used for a long period
  • Replaced by built-in functionality
  • A Skill was sufficient
  • No improvement in misdelegation

15.

Glossary Meaning
Parent agent An agent responsible for decomposition, delegation, integration, and final acceptance
Subagent An agent to which specialized work is delegated by the parent
Leaf Specialist An agent that does not launch child agents and returns only its own specialized work
Orchestrator An agent that divides work among permitted child agents and integrates the results
Delegation Brief A document that conveys the current objective, scope, constraints, and acceptance criteria
Core Contract A common framework for roles, boundaries, validation, and return formats
Role Profile Role-specific variations such as implementation, review, and debugging
Acceptance Criteria Criteria for observably determining completion
Harness Controls Deterministic controls such as deny, sandbox, Hooks, and CI
Skill Reusable knowledge, checklists, and procedures
Worktree A mechanism that isolates changes in an independent Git working tree

16. Final Checklist

  • The built-in Explore or Skill is insufficient
  • The primary responsibility can be stated in one sentence
  • The closest competing role can be identified
  • The description includes Capability, Trigger, and Conflict
  • The tools are kept to the minimum necessary
  • Leaf does not include Agent in tools
  • Orchestrator allowlists child agents
  • There are In Scope and Out of Scope sections
  • Task-specific information has been separated into the Delegation Brief
  • It can be started with just the Brief even without forking
  • Acceptance criteria are observable
  • Verification aligns with the acceptance criteria
  • Use passed only when execution succeeds
  • The parent can integrate it without re-investigating
  • Absolute conditions do not rely on wording alone
  • The conditions for removing this definition are defined

If you cannot explain even one item, first try using a regular prompt, a built-in agent, or a Skill.

Official References