Custom subagents in Claude Code: scoped specialists you can verify
PLCustom 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?
Section titled “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 (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 | 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
Section titled “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:
- Managed organization settings (highest)
- Session CLI
--agentsJSON flag - Project
.claude/agents/(committed to git) - Personal
~/.claude/agents/ - 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). Consult the official subagents documentation for the full frontmatter reference.
Three canonical subagents that return evidence
Section titled “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.
-
Read-only code reviewer (
.claude/agents/code-reviewer.md). Separating the writer from the judge prevents an authoring session from rationalising its own mistakes:---name: code-reviewerdescription: Reviews the current branch diff against main for correctness, security, and missing tests. Use proactively before commits or PRs.tools: Read, Grep, Glob, BashdisallowedTools: Write, Edit, NotebookEditmodel: 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_CHANGESFINDINGS:- [blocker|major|minor] path:LINE: problem. Evidence: <command or test>CHECKED: <commands run and exit codes>Because
Bashcan still modify files through shell commands, removeBashentirely for strict read-only enforcement or pair it withpermissions.denyrules. -
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:---name: test-runnerdescription: Executes test suites and reports only counts and failure lines. Use whenever test output would flood the main session.tools: Bash, Read, Grep, Globmodel: haikumaxTurns: 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> skippedFAILURES:- <test name> at path:LINE: <first 3 assertion lines> -
Worktree-isolated worker (
.claude/agents/migration-worker.md). Settingisolation: worktreegives each parallel worker its own temporary Git worktree so concurrent batches cannot overwrite one another (Git worktrees):---name: migration-workerdescription: Applies a scoped mechanical migration to named files in parallel fan-out batches.tools: Read, Edit, Write, Grep, Glob, Bashisolation: worktreemodel: sonneteffort: 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.jsonsets"worktree": { "baseRef": "head" }so workers build on unpushed feature commits.
Controlling routing, permissions, and model tiers
Section titled “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 usingpermissions.deny(for exampleAgent(migration-worker)). - Treat
toolsandpermissions.denyas your real boundaries. AdisallowedToolsentry removes the entire tool rather than a single subcommand—usepermissions.denyfor fine-grainedBash(...)blocks. In addition, an active parent permission mode (such as auto mode oracceptEdits) can override a subagent’spermissionModefield, background subagents receive a narrower built-in tool set, and plugin-supplied subagents ignorehooks,mcpServers, andpermissionMode. - Scope specialist integrations cleanly. Defining inline
mcpServersor frontmatterhooksinside 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).
Verifying subagent reports and linting agent files
Section titled “Verifying subagent reports and linting agent files”A subagent’s summary is a model claim written outside your view. Verify it systematically:
- Validate
.claude/agents/in CI. Claude Code silently skips subagent files with invalid YAML or missingname/descriptionand silently ignores misspelt keys (such asdisallowed_toolsinstead of camelCasedisallowedTools). Add a read-only CI check that parses YAML frontmatter and rejects unknown keys, protect.claude/agents/and.github/underCODEOWNERS, and runnpx @wondelai/harness-auditto audit subagent and hook coverage (Harness Audit). - Require verifiable evidence and re-run decisive checks. Every reported blocker must cite
path:lineand 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. - 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
SubagentStophook when you need durable audit logs beyond default transcript retention.
When custom subagents misfire or leak context
Section titled “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
Section titled “Official docs and next steps”Refer to the official Claude Code subagents reference for current frontmatter fields, concurrency limits, and task monitoring commands.
Comparing multi-agent tooling? See Codex cloud environments and Cursor Cloud Agents.
Did this guide help you?
One tap, no sign-in.
What will you do with it?
How did it read?
What got in the way? Pick any that apply
Your role?
Thanks. I read every answer. Michał Jaskólski
Did this guide help?
One tap each. Close whenever you like.
no sign-in