# Custom subagents in Claude Code: scoped specialists you can verify

URL: https://developertoolkit.ai/en/claude-code/automate/custom-subagents/
Description: Design Claude Code subagents in .claude/agents/, bound their tools and model tiers, isolate parallel edits in worktrees, and verify their reports.

Custom subagents in Claude Code are Markdown definitions under `.claude/agents/` (project) or `~/.claude/agents/` (personal) whose YAML frontmatter bounds name, routing description, tools, model tier, and isolation while the body supplies the system prompt. Each subagent runs in its own context window and returns a concise summary so noisy side work never floods the main session.

Forty minutes into a refactor, your main conversation holds three test logs, two repository-wide grep sweeps, and a migration trace. The invariant you stated at the start ("do not change public API signatures") gets buried, and asking the same session to review its own code fights that clutter. This guide serves developers isolating side work into specialists and tech leads committing shared, verifiable subagents for a whole team.

## Subagent, skill, fork, or scripted orchestration?

Choose the lightest isolation primitive that matches how much conversation history the side task needs:

| Job shape | Best primitive | Why |
| --- | --- | --- |
| Noisy, self-contained side task (test runs, log triage, independent review) | Custom subagent (`.claude/agents/`) | Clean context window, bounded tools, only a fixed summary returns |
| Reusable procedure that needs your current conversation context | [Agent Skill](/en/claude-code/automate/custom-commands/) (`SKILL.md`) | Runs inline in the main session (or isolated when `context: fork` is set) |
| Side task that requires full conversation history without polluting it | Conversation fork (`/subtask`) | Inherits parent conversation and reuses prompt cache |
| Many independent tasks orchestrated repeatably from code | [Orchestration patterns](/en/workflows/automate/orchestration-patterns/) | Control flow lives in versioned scripts rather than one chat thread |

Claude Code includes built-in subagents (such as read-only Explore and Plan, plus general-purpose). Commit a custom subagent when your team repeatedly spawns the same specialist with the same instructions, tool limits, and output contract.

## Anatomy, precedence, and context isolation

Only `name` and `description` are required in frontmatter; the Markdown body replaces the default system prompt for that subagent. When two definitions share a `name`, priority resolves top-down:

1. Managed organization settings (highest)
2. Session CLI `--agents` JSON flag
3. Project `.claude/agents/` (committed to git)
4. Personal `~/.claude/agents/`
5. Enabled plugin `agents/` directory (lowest)

A non-fork subagent starts with **its own system prompt**, the **delegation task message**, your repository's **`CLAUDE.md` hierarchy** (unless you set `omitClaudeMd: true` for task-only isolation), and any **preloaded `skills`**. It does **not** see your main conversation history, previously read files, or main-session auto memory—so any constraint stated only in chat must either live in `CLAUDE.md` or be repeated in the delegation message ([memory system](/en/claude-code/build/memory-system/)). Consult the [official subagents documentation](https://code.claude.com/docs/en/sub-agents) for the full frontmatter reference.

## Three canonical subagents that return evidence

Split side work across three committed specialists: one judges, one absorbs noisy command output, and one edits in isolated worktrees. Every prompt ends in a fixed output format so humans and parent sessions verify facts instead of reading transcripts.

1. **Read-only code reviewer (`.claude/agents/code-reviewer.md`).** Separating the writer from the judge prevents an authoring session from rationalising its own mistakes:

   ```markdown
   ---
   name: code-reviewer
   description: Reviews the current branch diff against main for correctness, security, and missing tests. Use proactively before commits or PRs.
   tools: Read, Grep, Glob, Bash
   disallowedTools: Write, Edit, NotebookEdit
   model: inherit
   ---

   Review changes between the merge base with main and the working tree. Never modify files.
   1. Run `git diff --merge-base main --stat` and read every changed file in full.
   2. Focus on broken logic, unhandled errors, injection, authorization gaps, and untested behaviour.
   3. Cite file:line and name the command or test proving each finding.

   Reply strictly in this shape:
   VERDICT: APPROVE | REQUEST_CHANGES
   FINDINGS:
   - [blocker|major|minor] path:LINE: problem. Evidence: <command or test>
   CHECKED: <commands run and exit codes>
   ```

   Because `Bash` can still modify files through shell commands, remove `Bash` entirely for strict read-only enforcement or pair it with `permissions.deny` rules.

2. **High-volume test runner (`.claude/agents/test-runner.md`).** Route noisy test suites to a faster, cheaper model tier with a strict turn cap so passing logs never bloat your main context:

   ```markdown
   ---
   name: test-runner
   description: Executes test suites and reports only counts and failure lines. Use whenever test output would flood the main session.
   tools: Bash, Read, Grep, Glob
   model: haiku
   maxTurns: 15
   ---

   Run the requested test command (or the project's default test script). Never edit files.
   Before labelling a failure flaky, re-run that single test once and report both results.

   Reply strictly in this shape:
   COMMAND: <exact command>
   EXIT: <exit code>
   RESULT: <passed> passed, <failed> failed, <skipped> skipped
   FAILURES:
   - <test name> at path:LINE: <first 3 assertion lines>
   ```

3. **Worktree-isolated worker (`.claude/agents/migration-worker.md`).** Setting `isolation: worktree` gives each parallel worker its own temporary Git worktree so concurrent batches cannot overwrite one another ([Git worktrees](/en/workflows/harness/git-worktrees/)):

   ```markdown
   ---
   name: migration-worker
   description: Applies a scoped mechanical migration to named files in parallel fan-out batches.
   tools: Read, Edit, Write, Grep, Glob, Bash
   isolation: worktree
   model: sonnet
   effort: medium
   ---

   Apply only the requested transformation to the files listed in the task.
   Run typecheck and related tests, then commit on your worktree branch.
   If checks fail outside your assigned files, stop and report without touching other files.

   Reply with: BRANCH, FILES CHANGED, and each command run with its exit code.
   ```

   Subagent worktrees branch from the repository's default branch unless `.claude/settings.json` sets `"worktree": { "baseRef": "head" }` so workers build on unpushed feature commits.

## Controlling routing, permissions, and model tiers

- **Stop guessing about auto-routing when dispatch matters.** Naming a subagent in prose is advisory; `@agent-<name>` guarantees that subagent runs for the task, and starting a session with `--agent <name>` runs the entire thread as that specialist. Block unwanted subagents permanently in settings using `permissions.deny` (for example `Agent(migration-worker)`).
- **Treat `tools` and `permissions.deny` as your real boundaries.** A `disallowedTools` entry removes the entire tool rather than a single subcommand—use `permissions.deny` for fine-grained `Bash(...)` blocks. In addition, an active parent permission mode (such as auto mode or `acceptEdits`) can override a subagent's `permissionMode` field, background subagents receive a narrower built-in tool set, and plugin-supplied subagents ignore `hooks`, `mcpServers`, and `permissionMode`.
- **Scope specialist integrations cleanly.** Defining inline `mcpServers` or frontmatter `hooks` inside a trusted project subagent connects them only while that subagent runs, keeping main-session context lean.
- **Match model tier and effort to cognitive load.** Keep judgement work (review, debugging, architecture) on `inherit` (your default model), move mechanical high-volume work (test runs, log summaries, bulk renames) to smaller/faster model tiers, and tune reasoning effort before switching tiers ([models hub](/en/ecosystem/models/)).

**Copy-paste prompt: scaffold repo-grounded subagents**

```text
Create three project subagents in .claude/agents/ tailored to this repository:
1. code-reviewer (read-only: tools Read, Grep, Glob, Bash; disallowedTools Write, Edit, NotebookEdit; model inherit).
2. test-runner (tools Bash, Read, Grep, Glob; fast/smaller model tier; maxTurns 15).
3. migration-worker (isolation: worktree; balanced model tier; effort medium).
Insert this repo's real test, typecheck, and lint commands. Keep every description under 40 words stating when to delegate, and end every prompt with a fixed evidence format (verdict/result, path:line findings, commands with exit codes). Show drafts before writing.
```

## Verifying subagent reports and linting agent files

A subagent's summary is a model claim written outside your view. Verify it systematically:

1. **Validate `.claude/agents/` in CI.** Claude Code silently skips subagent files with invalid YAML or missing `name`/`description` and silently ignores misspelt keys (such as `disallowed_tools` instead of camelCase `disallowedTools`). Add a read-only CI check that parses YAML frontmatter and rejects unknown keys, protect `.claude/agents/` and `.github/` under `CODEOWNERS`, and run `npx @wondelai/harness-audit` to audit subagent and hook coverage ([Harness Audit](/en/harness-audit/)).
2. **Require verifiable evidence and re-run decisive checks.** Every reported blocker must cite `path:line` and a reproduction command. Re-run critical pass/fail commands once in the main thread and keep CI—never a subagent verdict—as the merge gate.
3. **Watch prompt-injection markers and archive transcripts.** Inspect warning banners if a subagent report echoes untrusted instructions (such as asking to loosen permissions), and attach a `SubagentStop` hook when you need durable audit logs beyond default transcript retention.

## When custom subagents misfire or leak context

| Symptom | Likely cause | Recovery |
| --- | --- | --- |
| Subagent never triggers automatically | Description is vague or crowded out by too many definitions | Rewrite `description` as a crisp routing rule; invoke explicitly with `@agent-<name>` |
| Subagent is missing or a field does nothing | Broken YAML, missing `---` on line 1, or snake_case field typo (`disallowed_tools`) | Validate with your CI frontmatter linter and run `claude --debug` to inspect load errors |
| `permissionMode: plan` failed to stop edits | Parent session mode overrode the subagent's `permissionMode` | Remove `Write` and `Edit` from `tools` and enforce hard limits via `permissions.deny` |
| Worktree worker misses recent feature commits | Subagent worktrees branch from the default branch | Configure `"worktree": { "baseRef": "head" }` or push the base commits first |
| Works in foreground, fails in background | Background subagents omit certain built-in tools | Restrict prompts to standard tools (`Read`, `Grep`, `Glob`, `Bash`, `Edit`, `Write`) or run in foreground |
| Frontmatter hooks or inline MCP servers never load | Workspace folder is untrusted (non-interactive `-p` runs are untrusted) | Trust the workspace interactively or move shared checks into repo-level settings |
| Main context still fills up quickly | Subagent returns verbose free-form prose | Enforce a strict, short output schema at the end of the subagent system prompt |

## Official docs and next steps

Refer to the [official Claude Code subagents reference](https://code.claude.com/docs/en/sub-agents) for current frontmatter fields, concurrency limits, and task monitoring commands.

- [Custom commands and skills](/en/claude-code/automate/custom-commands/) — Preload skills into subagents or fork heavy slash commands cleanly.
- [Hooks automation](/en/claude-code/automate/hooks-automation/) — Constrain and audit subagents deterministically with PreToolUse and SubagentStop.
- [Orchestration patterns](/en/workflows/automate/orchestration-patterns/) — Coordinate multi-agent pipelines beyond a single interactive session.
- [Git worktrees](/en/workflows/harness/git-worktrees/) — Isolate files, ports, and local databases across parallel agent workers.

Comparing multi-agent tooling? See [Codex cloud environments](/en/codex/automate/cloud-environments/) and [Cursor Cloud Agents](/en/cursor-ide/automate/cloud-agents-automations/).
