{"slug": "claude-code-subagents-best-delegation-guide", "title": "Claude Code Subagents: Best Delegation Guide", "summary": "A developer published a hands-on guide to Claude Code Subagents, showing how to define specialized AI assistants as markdown files with YAML frontmatter that run in isolated context windows with their own toolsets and system prompts. The guide covers loading agents via the --agents CLI flag, project-level .claude/agents/ directories, or user-level ~/.claude/agents/, with a documented priority order of managed, CLI, project, user, then plugin. It also details frontmatter options for restricting tools, selecting models, controlling reasoning depth, and isolating worktrees so subagents can modify code without touching the main working tree.", "body_md": "*Cross-posted from [Iqraa.tech](https://iqraa.tech/ai-genai/claude/claude-code-subagents/?utm_source=devto&utm_medium=referral&utm_campaign=claude-code) — hands-on tutorials for Claude Code, AI agents, cloud, and system design.*\n\nClaude Code Subagents enable parallel task delegation through specialized AI assistants with isolated context windows, toolsets, and system prompts. This guide covers creating, configuring, and working with subagents defined as markdown files with YAML frontmatter, which can be managed via CLI flags, project directories, or user directories across different projects.\n\nSubagents can also leverage [advanced MCP configuration](https://iqraa.tech/ai-genai/claude/claude-code-mcp-configuration/) to access external tools and data sources.\n\nSubagents maintain clean context during lengthy tasks, enable parallel work, and allow packaging domain expertise into reusable agents. Configuration options include tool restrictions, model selection, reasoning depth control, and isolation settings like worktree separation for safe code modifications without affecting the main working tree.\n\n**Claude Code Subagents** enable parallel task delegation. This guide covers agent isolation, multi-agent workflows, and when to delegate work to subagents.\n\nFor a side-by-side comparison of when to choose subagents over skills, hooks, or plugins, see our [extensibility decision guide](https://iqraa.tech/ai-genai/claude/claude-code-extensibility/).\n\nIn this guide to **Claude Code Subagents**, you'll work through practical, hands-on steps with real examples. **Claude Code Subagents** is explained from the ground up so you can apply it immediately in your own projects.\n\nSubagents enable Claude to hand off work to specialized AI assistants, each operating with its own isolated context window, toolset, and system prompt. This approach keeps context clean during lengthy tasks, enables parallel work, and lets you package domain expertise into reusable agents. This lesson walks through creating, configuring, and working with subagents.\n\nSubagents are defined as markdown files with YAML frontmatter. You can make them available in several ways: use the `--agents` CLI flag for a single session, place them in `.claude/agents/` for project-wide availability (and commit them to git), or put them in `~/.claude/agents/` for personal use across all projects. Plugins can also bundle agents. The priority order is: managed first, then CLI flag, project, user, and finally plugin. Built-in subagents are always present and don’t participate in the name-override system. The `/agents` command opens an interactive menu to create, edit, and manage your agents.\n\nThe frontmatter establishes the agent’s identity, while the markdown body serves as its system prompt. Think of it as briefing a specialist:\n\n```\n---\nname: security-reviewer\ndescription: Security-focused code reviewer. Use proactively after writing authentication, authorization, or data handling code.\ntools: Read, Grep, Glob\n---\n\nYou are a senior security engineer specializing in application security.\n\nReview priorities:\n1. Authentication and authorization flaws\n2. Injection vulnerabilities (SQL, XSS, command)\n3. Data exposure and sensitive information handling\n4. Cryptographic weaknesses\n5. Insecure direct object references\n\nFor each finding, provide: severity (Critical/High/Medium/Low), location (file:line), description, and a concrete fix with code example.\n\nWhen invoked: run `git diff HEAD` first to focus on changed code.\n```\n\nThe `tools` field limits which tools the agent can access. A security reviewer only needs `Read`, `Grep`, and `Glob`. No write permissions required. An implementation agent, on the other hand, needs the complete toolset. Restricting tools makes agents both safer and more predictable. If you leave out the `tools` field, the agent inherits every available tool.\n\nBeyond basic tool access, the frontmatter supports a range of powerful configuration options. The `model` field selects which model the agent runs on: `haiku` for quick lightweight tasks, `sonnet` for balanced workloads, or `opus` for complex reasoning. Use `inherit` to take the parent’s model. The `effort` field controls reasoning depth on supported models, accepting values `low`, `medium`, `high`, `xhigh`, `max`, and `auto`. `maxTurns` limits how long the agent can run, and `permissionMode` sets the permission level. Additional fields include `disallowedTools`, `skills` to preload specific skills, `mcpServers` for agent-scoped MCP access, and `initialPrompt` to automatically submit the first turn.\n\nThe `memory` field gives agents persistent storage that survives across sessions. The first 200 lines of a `MEMORY.md` file in the agent’s memory directory are automatically loaded into its system prompt. Claude writes to this file as it learns:\n\n```\n---\nname: researcher\nmemory: user\ndescription: Long-running research assistant with persistent notes\n---\nYou are a research assistant. Check your MEMORY.md at session start to recall previous findings. Update it with new discoveries.\n```\n\nSetting `isolation: worktree` gives the agent its own git worktree and branch, so it can make changes without touching your main working tree. When the agent completes, it returns the worktree path and branch name for you to review and merge. If no changes were made, the worktree is automatically cleaned up. While the agent is running, Claude locks the worktree to prevent concurrent cleanup, releasing the lock once it finishes. The worktree branches from your repository’s default branch (`origin/HEAD`) unless you configure `worktree.baseRef` to `head` in settings, which makes isolated agents start from your local `HEAD` and carry along unpushed work.\n\nSetting `background: true` forces the agent to always run as a background task, freeing up the main conversation. You can also press `Ctrl+B` to background an agent that’s currently running in the foreground.\n\nTwo CLI flags extend what a session can reach. `--add-dir <path>` grants Read/Edit access to extra directories beyond the primary working directory, handy when your code references shared libraries or monorepo packages in sibling folders. Skills in `.claude/skills/` within added directories load automatically. Persist these with `permissions.additionalDirectories` in settings. `--mcp-config <path>` loads MCP server definitions from JSON files for the current session only, merged with your user/project sources. Add `--strict-mcp-config` to ignore user/project sources and use only the provided files:\n\n```\nclaude --add-dir ~/projects/shared-types --add-dir ~/projects/design-tokens\nclaude --mcp-config ./ci-servers.json\n```\n\nClaude invokes agents automatically when a task matches the agent’s `description` field. Phrases like “use proactively” can encourage delegation, but for reliable results when you need a specific agent, explicit invocation is the way to go. Use the `@\"agent-name (agent)\"` syntax to guarantee a specific agent is used, bypassing automatic matching.\n\nNatural language explicit invocation also works:\n\n```\nUse the security-reviewer agent to audit the new auth module.\nHave the test-engineer agent write integration tests for the payment service.\nAsk the debugger agent to investigate the memory leak in src/workers/queue.ts.\n```\n\nAgents can be chained sequentially, where one agent’s output feeds into the next. Running `claude agents` from the terminal opens the **Agent view**, a roster of all Claude Code sessions showing their state (working, waiting, completed, failed, idle, stopped) and last activity. This is great for monitoring multiple agents running in parallel. Pass `--cwd <path>` to filter the roster to sessions started under that directory, useful when you juggle several repos and want a scoped view. Set `CLAUDE_CODE_DISABLE_AGENT_VIEW=1` to disable it. You can also run a full session with a specific agent via `claude --agent <name>`, and restrict which agents a coordinator can spawn using `Agent(...)` tool allowlists.\n\n```\n# Only show agent sessions started under ~/work/api\nclaude agents --cwd ~/work/api\n```\n\nFor scripts that need to consume the roster (tmux-resurrect-style boot scripts, custom status bars, session pickers), pass `--json` to `claude agents` to get machine-readable data as an array instead of the interactive view. Each entry includes `pid`, `cwd`, `kind`, and `startedAt`, plus `sessionId`, `name`, and `status` when available. When `status` is `waiting`, `waitingFor` specifies exactly what the session is blocked on, such as `permission prompt` or `input needed`, allowing scripts to route those cases to different actions:\n\n```\n# Wake up every session that's blocked on a permission prompt\nclaude agents --json   | jq -r '.[] | select(.status == \"waiting\" and .waitingFor == \"permission prompt\") | .sessionId'   | xargs -I {} claude respawn {}\nFirst use the code-analyzer agent to find performance bottlenecks, then use the optimizer agent to fix them.\n```\n\nClaude Code includes several built-in agents you don’t need to create: `general-purpose` handles broad multi-step tasks, `Explore` uses Haiku for fast read-only codebase analysis, `Plan` researches the codebase before presenting implementation plans, and `claude-code-guide` answers questions about Claude Code features. Agents can also be resumable, allowing Claude to continue a previous agent conversation by ID when a workflow spans multiple turns.\n\nSet `CLAUDE_CODE_FORK_SUBAGENT=1` to enable forked subagents. A forked subagent inherits the full conversation context from the main session instead of starting from scratch. When enabled, `/fork` spawns a forked subagent rather than acting as an alias for `/branch`, and all subagent spawns run in the background. This works in interactive sessions, non-interactive mode, the Agent SDK, and on external builds:\n\n```\nCLAUDE_CODE_FORK_SUBAGENT=1 claude\n```\n\nThe experimental Agent Teams feature (requires `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` or the `--agent-teams` CLI flag) coordinates multiple Claude instances working in parallel through a shared task list and mailbox. This is designed for large multi-file projects where independent agents can work on different parts simultaneously without stepping on each other.\n\n`SendMessage` automatically resumes stopped agents when a message is sent to them, so you no longer need to explicitly resume an agent before communicating with it. As of v2.1.178, the `TeamCreate` and `TeamDelete` tools were removed: with the flag set, every session already has one implicit team, so you spawn teammates directly through the Agent tool’s `name` parameter (no setup step) and cleanup happens automatically when the session exits.\n\nHere are production-ready subagent definitions you can drop into your project’s `.claude/agents/` directory:\n\nA specialized reviewer that automatically inspects modified code for security vulnerabilities, performance issues, and quality standards:\n\n```\n---\nname: code-reviewer\ndescription: Expert code review specialist. Use PROACTIVELY after writing or modifying code.\ntools: Read, Grep, Glob, Bash\nmodel: inherit\n---\n\n# Code Reviewer Agent\n\nWhen invoked:\n1. Run git diff to see recent changes\n2. Focus on modified files\n3. Begin review immediately\n\n## Review Priorities (in order)\n1. Security Issues - Authentication, authorization, data exposure\n2. Performance Problems - O(n^2) operations, memory leaks, inefficient queries\n3. Code Quality - Readability, naming, documentation\n4. Test Coverage - Missing tests, edge cases\n5. Design Patterns - SOLID principles, architecture\n```\n\nAn agent that profiles, identifies bottlenecks, and implements optimizations with before/after metrics:\n\n```\n---\nname: performance-optimizer\ndescription: Performance analysis and optimization specialist. Use PROACTIVELY after writing or modifying code.\ntools: Read, Edit, Bash, Grep, Glob\nmodel: inherit\n---\n\n# Performance Optimizer Agent\n\nWhen invoked:\n1. Profile the target code or system\n2. Identify the most impactful bottlenecks\n3. Propose and implement optimizations\n4. Measure and verify improvements\n\n## Common Profiling Commands\n# Node.js\nnode --prof app.js\n\n# Python\npython -m cProfile -s cumulative script.py\n\n# Go\ngo test -cpuprofile=cpu.out ./...\n\n# Database (PostgreSQL)\nEXPLAIN ANALYZE SELECT ...;\n```\n\nA test automation expert that writes comprehensive tests including edge cases and error scenarios:\n\nFor automated pipelines, [Claude Code headless mode](https://iqraa.tech/ai-genai/claude/claude-code-headless-mode/) lets you script subagent interactions without interactive prompts.\n\n```\n---\nname: test-engineer\ndescription: Test automation expert. Use PROACTIVELY when new features are implemented.\ntools: Read, Write, Bash, Grep\nmodel: inherit\n---\n\n# Test Engineer Agent\n\n## Coverage Requirements\n- Minimum 80% code coverage\n- 100% for critical paths (auth, payments, data handling)\n\n## Test Structure Example\ndescribe('Feature: User Authentication', () => {\n  beforeEach(() => { /* Setup */ });\n  afterEach(() => { /* Cleanup */ });\n\n  it('should authenticate valid credentials', async () => {\n    // Arrange, Act, Assert\n  });\n\n  it('should reject invalid credentials', async () => {\n    // Test error case\n  });\n});\n```\n\nDeciding whether a task belongs inline or in a subagent is the first skill to develop once you start using subagents at all. The instinct is to spin up a subagent for anything that looks large, but that is wasteful for short tasks where the delegation overhead - the spawn cost, the context hand-off, and the result merge - exceeds the work itself. A useful rule: delegate when the task has a self-contained goal, produces a discrete artifact, and would otherwise pollute the main context with detail the orchestrator does not need to reason about again.\n\nSubagents shine on investigative work where the journey matters less than the destination. A security audit that reads dozens of files, a dependency upgrade that requires checking changelogs across a tree, or a test-coverage analysis that maps every uncovered branch are all good fits. The main agent hands over the question, the subagents do the reading, and the main agent receives a structured answer plus the evidence it needs to act. The reading never enters the main context window, which is the whole point.\n\nTasks that need tight back-and-forth with the user, or that change direction mid-flight based on a judgment the orchestrator must make, are usually better inline. A subagent cannot pause to ask the user a clarifying question in the middle of its run; it works from the prompt it was given. If you find yourself wanting to interject, the task was probably not a clean delegation candidate, and forcing it into a subagent produces a worse result than handling it inline.\n\nEvery subagent has its own context window, separate from the main agent's, and managing the budget across the two is what separates a clean delegation from a frustrating one. The main agent's context is precious: it holds the conversation history, the user's intent, and the accumulated state of the session. Pushing large reads into subagents keeps that window lean, which directly improves the quality of the main agent's reasoning because it has less noise to weight against the signal.\n\nA subagent's prompt should be self-contained. It needs to know the goal, any constraints (style guides, file boundaries, things not to touch), and the expected shape of the result. The mistake to avoid is a vague prompt that forces the subagent to come back with questions, because each round-trip costs a full subagent context cycle. Spending two minutes writing a precise prompt almost always saves ten minutes of back-and-forth.\n\nThe result a subagent returns should be shaped for the main agent's consumption, not for a human reader. A summary paragraph plus a structured list of findings, with file paths and line numbers, lets the orchestrator act immediately. A subagent that returns five thousand words of narrative forces the main agent to re-read and re-summarize, which wastes the context savings the delegation was supposed to deliver. Tight, structured returns are the hallmark of well-designed subagents.\n\nWhen a task splits into independent pieces, parallel subagents finish in the wall-clock time of the slowest piece rather than the sum of all pieces. Running a frontend audit, a backend audit, and an infrastructure audit as three parallel subagents takes roughly as long as the longest of the three, whereas running them sequentially takes the combined time. For large reviews this is the difference between a few minutes and a quarter of an hour.\n\nSequential delegation is the right choice when later steps depend on earlier results. If step two needs the output of step one to know where to look, parallelizing them wastes work - the second subagent would have to guess or wait. The discipline is to map the dependency graph first: tasks with no edges between them go parallel, tasks that form a chain go sequential, and a mixed graph can be scheduled in waves where each wave is a parallel batch whose outputs feed the next.\n\nA subtlety: parallel subagents do not share live state. If two subagents both edit the same file, the second write can clobber the first unless the work is partitioned by file or by region. The clean solution is to partition the work so no two subagents touch the same artifact, or to have parallel subagents only investigate and propose, leaving all writes to a final sequential step the orchestrator controls. Investigation parallelizes freely; mutation does not.\n\nA subagent can fail in a few distinct ways, and each has a different recovery path. The most common is an ambiguous result: the subagent ran, returned something, but the answer does not clearly resolve the question. The fix is rarely to re-run the same subagent; it is to sharpen the prompt and run again, because a vague prompt produces a vague result on every retry. Treating the first run as a prompt-refinement cycle rather than a failure is the productive framing.\n\nThe second failure mode is a tool error inside the subagent: a command returned a non-zero exit, a file was missing, a permission was denied. Most subagent frameworks surface these in the result, and the orchestrator can decide whether to retry, to fall back to a different approach, or to escalate to the user. Retrying a flaky tool once is reasonable; retrying it five times in a loop is a sign the environment is broken and the session should pause for a human.\n\nThe third and most serious failure is a subagent that runs away: it consumes far more tokens or wall-clock than expected, often because the prompt was too open-ended or the search space was larger than anticipated. Hard limits on subagent execution - a maximum number of tool calls, a maximum token budget, a timeout - turn a runaway into a bounded failure that returns a partial result and a reason, rather than an unbounded spend. Every production setup that uses subagents at scale should configure these limits.\n\nA subagent inherits a subset of the main session's permissions, and tightening that subset is one of the most effective safety levers available. A subagent whose only job is to read files and report findings does not need write access, and removing write access from its scope means a prompt-injection or a misjudgment inside the subagent cannot modify the codebase. The principle of least privilege applies here exactly as it does in operating-system process design.\n\nNetwork access is the other permission to scrutinize. A subagent that fetches external resources - package registries, documentation sites, APIs - can be manipulated if any of those sources are untrusted, because the content it fetches becomes part of its reasoning. For subagents that touch the network, scoping the allowed hosts and treating fetched content as untrusted input (never as instructions) closes the main injection vector.\n\nThe cleanest pattern for high-risk delegations is the sandboxed subagent: read-only filesystem access, no network, a bounded tool set, and a result that is data rather than code. A security reviewer subagent that inspects a third-party library fits this profile perfectly. It can read everything, conclude everything, and change nothing, which is exactly the safety property you want when the delegation target is untrusted content.\n\nWhen a subagent's result is wrong but not obviously broken, the cause is almost always in the prompt or the tool surface, not in the model. Debugging starts with reproduction: re-run the subagent with verbose logging enabled so the full tool-call trace is visible. The trace shows which files it read, which commands it ran, and where its reasoning diverged from the expected path. Most debugging sessions resolve in the first read of that trace.\n\nA common cause of subtly wrong results is a stale tool surface. If the subagent was configured against a set of MCP servers or skills and one of them changed, the subagent may call a tool that no longer behaves as the prompt assumes. Version-pinning the tool surface, or at least recording what was available when the subagent was designed, makes regressions diagnosable instead of mysterious. A subagent that worked last month and broke this week is almost always a tool-surface drift.\n\nPrompt bloat is the other chronic cause. Over time, as edge cases are patched, prompts accumulate qualifications and exceptions until they contradict themselves. A subagent whose prompt says both \"be thorough\" and \"be fast\" will resolve the tension unpredictably. Periodic prompt review - reading the full prompt as a human would read a function body, looking for contradictions and dead instructions - keeps delegations reliable as they evolve.\n\nA subagent definition that lives in one developer's local config is invisible to the rest of the team, which means the team cannot benefit from it, cannot review it, and cannot notice when it goes stale. Checking subagent definitions into the repository - under a convention like `.claude/agents/` - makes them a shared asset that code review, version history, and onboarding documentation can all reach.\n\nReviewing a subagent definition is a distinct skill from reviewing code. The reviewer asks: does the prompt match the delegated responsibility, are the permissions the minimum required, is the expected result shape documented, and does the subagent have a clear failure mode? A definition that fails any of these questions is a liability, because a misbehaving subagent can affect every teammate who invokes it. Treating agent definitions as first-class, reviewed artifacts is what separates a team that uses subagents from a team that is used by them.\n\nOnboarding benefits compound. A new teammate who inherits a library of reviewed subagents for the codebase starts productive on day one, because the subagents encode the team's investigation patterns - how they audit, how they upgrade, how they triage. Documenting when to use each one, in a short index alongside the definitions, turns tribal knowledge into a reusable toolchain rather than a months-long apprenticeship.\n\nA subagent is not a set-and-forget artifact. The prompt that worked against last quarter's codebase may be subtly wrong against this quarter's, because file layouts change, tool surfaces evolve, and the questions the team asks drift. A periodic review cadence - quarterly for actively used subagents, and a sweep on any major codebase restructure - catches drift before it produces a wrong result that someone trusts.\n\nDeprecation is part of the lifecycle too. A subagent that solved a problem which no longer exists, or which has been superseded by a better tool, should be retired explicitly rather than left to rot. A short deprecation note in the definition - \"superseded by X, remove after Y\" - signals to teammates that they should not start using it and gives a removal date. Graveyards of half-working subagents are worse than none at all, because they waste every invoker's time until they are cleaned up.\n\nVersioning helps when a subagent's behavior must change in a way that breaks existing callers. Naming the definition with a version suffix, or keeping a changelog entry per subagent, lets a caller pin to a known-good version while a new one soaks. This is the same discipline applied to any shared library interface, and it matters for exactly the same reason: a silent behavior change in a dependency is a bug report waiting to happen.\n\nEvery subagent invocation has a cost that is worth understanding quantitatively, because the difference between a delegation that pays off and one that wastes budget is often a matter of scale. A subagent that does a few hundred words of reading and returns a short structured result costs little; a subagent that reads a thousand files and produces a long narrative costs correspondingly more. The cost is driven by the subagent's own context - everything it reads becomes tokens it reasons over - so the lever is how much it reads, not how often it runs.\n\nWall-clock time is the other dimension. A subagent runs in its own context, and for long tasks that time is the main user-facing cost: the orchestrator waits while the subagent works. Parallel delegation mitigates this when the task is parallelizable, but a single long sequential subagent is a wait the user feels. Estimating a subagent's expected runtime before launching it - based on the size of the search space and the number of tool calls it will likely make - lets you set a sensible timeout and avoid the worst case of a subagent that runs for ten minutes on a task that should take one.\n\nSubagents also have an indirect cost on the orchestrator: the result they return enters the main context, and a verbose result consumes budget there too. This is the argument for tight, structured returns rather than long narratives. A subagent that returns fifty lines of structured findings costs the orchestrator fifty lines of context; one that returns five hundred lines of prose costs ten times as much, for rarely ten times the value. Designing the return shape is a performance decision, not just a usability one.\n\nThe clearest case against a subagent is a task that needs the orchestrator's judgment mid-flight. A subagent runs from its prompt and cannot easily pause to consult the user or the broader session state, so a task whose direction depends on an interim decision is a poor fit. Forcing such a task into a subagent produces either a vague prompt (and a vague result) or a series of aborted runs as the orchestrator tries to steer a process it cannot interrupt. Inline work is the right tool when the path is not knowable in advance.\n\nShort tasks are the other case against delegation. The overhead of spawning a subagent - the prompt construction, the context hand-off, the result merge - is a fixed cost, and for a task that would take the orchestrator a few tool calls inline, that overhead exceeds the savings. A useful heuristic: if the task would take fewer than, say, a dozen tool calls and would not bloat the main context past what compaction handles easily, keep it inline. Subagents are for work whose volume or isolation justifies the overhead.\n\nTasks that modify shared state are usually poor delegation candidates unless the writes are carefully partitioned. A subagent that edits files in parallel with the orchestrator risks conflicting writes, because the two do not coordinate on the filesystem. The safe pattern for delegated mutation is to partition the work so no two agents touch the same file, or to confine the subagent to read-only investigation and perform all writes in a sequential step the orchestrator controls. Subagents are safest when they investigate; mutation wants a single coordinator.\n\n`Read, Grep, Glob`. You can always add tools later when requirements demand it.`description` field so Claude delegates automatically when the situation arises, instead of waiting for explicit requests.`.claude/agents/` into git so your whole team benefits from the same specialized subagents and configuration stays consistent.\nBuild a team of specialized subagents to automate your code review workflow end-to-end.\n\nCreate a project-level subagent team with two agents: a **read-only security reviewer** and a **test engineer** that can write missing tests. Then chain them so that security findings are addressed before test coverage is checked.\n\n`secure-reviewer.md` with YAML frontmatter granting only `Read, Grep` tools and a system prompt focused on authentication, injection, and data-exposure vulnerabilities. Include the phrase `test-engineer.md` with tools `Read, Write, Bash, Grep` and a prompt targeting >80% coverage and edge-case identification.`/agents` to verify both agents appear in the interactive list.\nTwo subagent files in `.claude/agents/`, both visible in `/agents`, chained execution producing a security report followed by new or updated test files, and confirmation that tool restrictions were enforced.\n\nRemember that the `tools` field controls what each agent can do. Omit it to inherit everything, or list specific tools like `tools: Read, Grep` for a read-only agent. Use the `@` prefix (e.g. `@\"secure-reviewer (agent)\"`) to guarantee a specific agent is invoked.\n\nTest your understanding of Claude Code subagents with these questions:\n\n**A)** They are faster\n\n**B)** They operate in a separate, clean context window preventing context pollution\n\n**C)** They can use more tools\n\n**D)** They have better error handling\n\n*Correct answer: B*. Subagents get a fresh context window, receiving only what the main agent passes. This prevents the main conversation from being polluted with task-specific details.\n\n**A)** Project > User > CLI\n\n**B)** CLI > Project > User\n\n**C)** User > Project > CLI\n\n**D)** They all have equal priority\n\n*Correct answer: B*. CLI-defined agents (`--agents` flag) override Project-level (`.claude/agents/`), which override User-level (`~/.claude/agents/`).\n\n**A)** general-purpose\n\n**B)** Plan\n\n**C)** Explore\n\n**D)** Bash\n\n*Correct answer: C*. The Explore subagent uses Haiku for fast, read-only codebase exploration. It supports three thoroughness levels: quick, medium, very thorough.\n\n**A)** Use `allowed-agents:` field\n\n**B)** Use `Task(agent_name)` syntax in the `tools` field\n\n**C)** Set `spawn-limit: 2`\n\n**D)** Use `restrict-agents: [name1, name2]`\n\n*Correct answer: B*. Adding `Task(worker, researcher)` in the tools field creates an allowlist. The agent can only spawn subagents named “worker” or “researcher”.\n\n`isolation: worktree` do for a subagent?\n**A)** Runs the agent in a Docker container\n\n**B)** Gives the agent its own git worktree so changes don’t affect the main tree\n\n**C)** Prevents the agent from reading any files\n\n**D)** Runs the agent in a sandbox\n\n*Correct answer: B*. Worktree isolation creates a separate git worktree. If the agent makes no changes, it auto-cleans up. If changes are made, the worktree path and branch are returned.\n\n[ays_quiz id=\"10\"]\n\n| Resource | Type | What You'll Learn | \n|---|---|---|\n| [Official Subagents Documentation](https://code.claude.com/docs/en/sub-agents) | Docs | Core concepts, configuration fields, and the full lifecycle of a subagent | \n| [Agent Teams (Experimental)](https://code.claude.com/docs/en/agent-teams) | Docs | Multi-agent coordination with shared task lists and inter-agent messaging | \n| [CLI Reference: `--agents` flag](https://code.claude.com/docs/en/cli-reference) | Reference | Defining agents via JSON for single-session use | \n| [Claude Code Changelog](https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md) | Changelog | Subagent nesting (v2.1.172), case-insensitive matching (v2.1.140), observability headers (v2.1.139) | \n| [Plugins Guide](https://code.claude.com/docs/en/plugins) | Guide | Bundling subagents into distributable plugin packages | \n\n**Claude Code Subagents** gives you a solid, repeatable workflow. Bookmark this **Claude Code Subagents** guide and revisit the steps whenever you need them.\n\nSubagents earn their keep on tasks that are well-scoped but noisy, the kind of work that would otherwise fill your main context with file listings, log output, and dead ends. This walkthrough builds a `migration-runner` subagent that can safely apply a database migration in isolation and hand back a clean summary.\n\n`.claude/agents/migration-runner.md` with frontmatter that limits the toolset to exactly what the task needs and turns on worktree isolation:\n\n```\n   ---\n   name: migration-runner\n   description: Applies pending database migrations and reports the result. Use PROACTIVELY when the user mentions running or testing a migration.\n   tools: Read, Bash, Grep\n   isolation: worktree\n   ---\n\n   You are a database migration specialist. Run pending migrations against\n   the test database, capture the output, and report success or the exact\n   failure. Never touch the production connection string.\n```\n\n`Read`, `Bash`, and `Grep`. No `Write` or `Edit`, since it only needs to run commands and inspect output, not modify application code.`@\"migration-runner (agent)\"` syntax to guarantee it's the one that runs, rather than relying on automatic matching while you're still building confidence in its behavior.`claude agents` in a second terminal to see the subagent's live status (working, waiting, or completed), which is especially useful once you're running more than one subagent for the same task.\nThe pattern generalizes past database migrations: any task with a clear boundary, a small toolset, and output you don't want cluttering your main conversation is a good candidate for one of your Claude Code Subagents. The isolation and tool restrictions are what make delegation safe rather than just convenient.\n\nSubagents are easy to misuse in ways that cost more time than they save. These four mistakes show up most often once teams start delegating work.\n\nNo. Each of the Claude Code Subagents starts with a fresh, isolated context window and only receives what the main agent explicitly passes to it.\n\nYes, subject to nesting limits and any Task(...) allowlist set in the parent's tools field, which restricts which named agents it's permitted to spawn.\n\nThe worktree is cleaned up automatically. If changes were made, Claude Code returns the worktree path and branch name so you can review before merging.\n\nUse the @\"agent-name (agent)\" syntax, or ask in plain language: \"use the test-engineer agent to...\", for reliable, explicit invocation.\n\nMatch the model to the task: haiku for fast, lightweight work, sonnet for balanced tasks, and opus for complex reasoning, or set model: inherit to match the parent session.", "url": "https://wpnews.pro/news/claude-code-subagents-best-delegation-guide", "canonical_source": "https://dev.to/amarti/claude-code-subagents-best-delegation-guide-2pio", "published_at": "2026-11-05 21:50:38+00:00", "updated_at": "2026-11-05 21:54:29.707217+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "large-language-models"], "entities": ["Claude Code", "Anthropic", "Iqraa.tech"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/claude-code-subagents-best-delegation-guide", "markdown": "https://wpnews.pro/news/claude-code-subagents-best-delegation-guide.md", "text": "https://wpnews.pro/news/claude-code-subagents-best-delegation-guide.txt", "jsonld": "https://wpnews.pro/news/claude-code-subagents-best-delegation-guide.jsonld"}}