Skip to content

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?

Section titled “Subagent, skill, fork, or scripted orchestration?”

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

Job shapeBest primitiveWhy
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 contextAgent 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 itConversation fork (/subtask)Inherits parent conversation and reuses prompt cache
Many independent tasks orchestrated repeatably from codeOrchestration patternsControl 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:

  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). 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.

  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:

    ---
    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:

    ---
    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):

    ---
    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

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 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).

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:

  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).
  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

Section titled “When custom subagents misfire or leak context”
SymptomLikely causeRecovery
Subagent never triggers automaticallyDescription is vague or crowded out by too many definitionsRewrite description as a crisp routing rule; invoke explicitly with @agent-<name>
Subagent is missing or a field does nothingBroken 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 editsParent session mode overrode the subagent’s permissionModeRemove Write and Edit from tools and enforce hard limits via permissions.deny
Worktree worker misses recent feature commitsSubagent worktrees branch from the default branchConfigure "worktree": { "baseRef": "head" } or push the base commits first
Works in foreground, fails in backgroundBackground subagents omit certain built-in toolsRestrict prompts to standard tools (Read, Grep, Glob, Bash, Edit, Write) or run in foreground
Frontmatter hooks or inline MCP servers never loadWorkspace 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 quicklySubagent returns verbose free-form proseEnforce a strict, short output schema at the end of the subagent system prompt

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.

not at all a lot