Claude and Claude Code 2027Section 7 · lesson 1 of 4
1234section 7 lessons
Section 7. Subagents, Parallel Sessions, and Agent Swarms

Subagents — Roles, YAML Metadata, Context Isolation, and Access Restrictions

≈ 15 minNeuroBober

When should you offload a task from your main conversation into a separate subagent instead of handling everything in one long chat? Picture a typical workday scenario: you are building a new feature in a large repository on Opus 5.5, and along the way you need to read docs for an unfamiliar module, run a security audit across a dozen files, and inspect logs from failing tests. Doing all of that in the main window fills the context with hundreds of lines of search results and intermediate guesses within minutes—responses bog down, and every follow-up turn gets more expensive.

A subagent in Claude Code solves this exact problem: it moves noisy grunt work into an isolated context window and returns only a condensed summary to the main chat. But to keep that helper from burning budget needlessly, breaking neighboring files, or misfiring on triggers, it needs a sharply defined role, tools trimmed down under the , and a compact trigger in its YAML metadata.

Why Use a Subagent: Context Isolation and Background Execution

There is a fundamental architectural boundary between a skill (SKILL.md), which you covered in Section 5, and a subagent in .claude/agents/. A skill runs right inside your current session: it loads a checklist or step-by-step playbook into it, sharing the exact same context window and the same model with you.

A subagent works differently—it is an independent child run inside your session with its own clean context. It receives its own Markdown file body as a system prompt along with basic environment details, but it does not see your main conversation history, previously read files, or the main chat's .

By default, custom subagents launch in the background (background: true is built into delegation logic) so the main conversation does not stall while waiting. While one agent on the inexpensive Haiku 5.5 model scans thirty project files in the background for a specific contract, you keep designing architecture in the main window on Opus 5.5, and then receive a clean, structured summary.

Subagent context isolation: the main agent on Opus 5.5 delegates search and review to background subagents with a fresh context window, restricted permissions, and a separate model, receiving a condensed report back.

It is important to understand the economics and lifecycle of these background helpers. A subagent's usage counts against the same subscription limits or API balance as the main session, yet its prompt cache lives for 5 minutes by default (versus ~1 hour in an interactive subscription session; you can extend the TTL to one hour if needed with experimental: { cacheTtl: 1h }). At the same time, the subagent's transcript is stored separately at ~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonl and is not wiped when the main conversation compacts, so any subagent can be resumed via SendMessage by name or ID with an already warmed cache.

Even before creating your own files, you have built-in subagents that Claude Code registers automatically: Explore, Plan, general-purpose, claude, statusline-setup, claude-code-guide, and web-fetch. The most common ones are Explore (with three search depth levels: quick, medium, and very thorough) and Plan: for speed and protection against accidental edits, Edit, Write, and NotebookEdit are intentionally stripped from them, and at startup they do not even spend tokens on CLAUDE.md or a git status snapshot. If built-in agents interfere with your own routing, Explore and Plan can be disabled with CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1, and in non-interactive -p mode or the Agent SDK all built-in roles can be removed via CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS=1.

Built-in Protection Against Injection in Subagent Reports

Because a subagent may read untrusted external code or web pages, Claude Code automatically scans its final report (Subagent output scanning). If pseudo-tags like <system-reminder> or lines starting with Human: / Assistant: appear in the text, the harness backslash-escapes them, flags them with [harness: subagent output matched instruction-shaped pattern(s): ...], and prepends a reminder to the summary stating that the subagent's words do not carry user authority.

Contrary to outdated notes from earlier versions, subagents are no longer locked to a single level: by default, nesting up to 3 levels below the main conversation is allowed (controlled by CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, while setting it to 1 completely forbids child spawns). At least 20 subagents can run concurrently within a single session (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS, and in ultracode mode this ceiling is lifted altogether).

Anatomy of a Subagent File: YAML Metadata, Models, and Least Privilege

Physically, a custom subagent is a plain Markdown file with a YAML frontmatter block at the top and detailed instructions below. At the configuration level, only two fields are required—name (up to 256 characters, no leading hyphen or colon) and description, which the main agent uses to decide whether this specialist fits the current request.

However, the real engineering leverage comes from optional parameters in , which turn a plain text persona into a strictly bounded module. The key control fields are:

  • Model and reasoning effort (model, effort): model accepts the aliases haiku, sonnet, opus, fable, a full model ID, or inherit (the default). Precedence is strict: a model parameter passed at invocation overrides the model field in the file, which overrides CLAUDE_CODE_SUBAGENT_MODEL, which overrides the parent's model (setting CLAUDE_CODE_SUBAGENT_MODEL_FORCE=1 forcefully overrides the first two). Reasoning depth can be tuned further with effort (low, medium, high, xhigh, max).
  • Hard tool restrictions (tools, disallowedTools): tools defines an allowlist of permitted tools (Read, Grep, Glob, Edit, Write, Bash), while disallowedTools defines a denylist. If both are specified, disallowedTools runs first and tools filters the remaining pool; for MCP servers, patterns such as mcp__github__*, mcp__github (blocking the whole server), or mcp__* (blocking all MCP servers) are supported.
  • Safety fuse and context (maxTurns, autoCompactWindow, omitClaudeMd): maxTurns sets a hard step ceiling so a background agent cannot spin into an infinite loop, autoCompactWindow (an integer from 100000 upward) controls the compaction threshold for long searches, and omitClaudeMd: true skips loading the project CLAUDE.md when the subagent handles a narrow autonomous task.
  • Skills, hooks, and persistent memory (skills, hooks, memory, isolation): skills can preload up to 32 unique skills, hooks can attach local PreToolUse, PostToolUse, and Stop hooks, isolation: worktree gives the agent a dedicated Git worktree (covered in the next lesson), and memory (user, project, or local) creates a persistent folder at ~/.claude/agent-memory/<name>/, .claude/agent-memory/<name>/, or .claude/agent-memory-local/<name>/, automatically loading the first 200 lines or 25 KB of MEMORY.md and enabling Read, Write, and Edit.

When configuring least privilege, two common pitfalls often cause a "safe" subagent to silently retain excessive powers or lose a tool it actually needs.

Two Pitfalls When Restricting Permissions in YAML Frontmatter

First, setting tools: Read, Grep, Glob, Bash does not make a subagent read-only: through Bash, the model can easily modify or delete files using commands like sed or rm. For guaranteed read-only mode, exclude Bash from tools completely or attach a deterministic PreToolUse hook returning exit 2. Second, writing disallowedTools: Bash(git push *) directly in frontmatter removes the entire Bash tool rather than a single command—granular bans on specific subcommands must be configured via permissions.deny in settings.json.

Another nuance involves permissionMode (default/manual, acceptEdits, auto, dontAsk, bypassPermissions, plan) and plugins. If your main session is already running in bypassPermissions, acceptEdits, auto, or plan, the subagent's permissionMode field is ignored and the parent's mode is inherited (moreover, bypassPermissions inside a subagent only works if the main session itself was launched in that mode). Meanwhile, in subagents loaded from third-party plugins, hooks, mcpServers, permissionMode, and initialPrompt are blocked by the platform by default for security.

Finally, you can restrict even the main agent itself if you want it to delegate work only to strictly approved roles: in the main agent's frontmatter, specify tools: Agent(worker, researcher), Read, Bash (starting in v2.1.63, the former Task tool was renamed to Agent, though the old name still works as an alias). You can also ban specific subagents at the project level via "permissions": { "deny": ["Agent(Explore)", "Agent(my-agent)"] } in settings.json or with the launch flag claude --disallowedTools "Agent(Explore)".

Load Precedence, Hot Reloading, and the 15,000-Token Description Budget

To avoid confusion over where .md files should live and which definition wins when names collide, review the official source hierarchy in Claude Code. The platform resolves name conflicts from highest priority to lowest:

PriorityDefinition SourceScopeNotes & Practical Meaning
1 (Highest)Organization managed settingsAll company machinesCorporate standard that cannot be overridden locally
2CLI --agents flagCurrent session onlyOne-off or scripted roles (claude -p --agents ./agents.json "...")
3.claude/agents/ directoryCurrent repositoryScanned recursively and upward from cwd to Git root; easy to commit for the team
4~/.claude/agents/ directoryAll user projectsYour personal assistants portable across repositories
5 (Lowest)agents/ folder inside a pluginWhile plugin is activehooks, mcpServers, permissionMode, and initialPrompt are ignored

Note two welcome quality-of-life details when working with .claude/agents/ and ~/.claude/agents/. First is hot reloading: Claude Code continuously watches both directories and picks up new or edited files within a few seconds without restarting the current session (a restart is only required for folders from --add-dir or when starting with --disable-slash-commands). Second is the change to /agents: starting in v2.1.198, it no longer opens the old tabbed step-by-step wizard and instead prompts you to edit files in .claude/agents/ or ask Claude to create the file, while active subagents and their models are conveniently inspected with /tasks.

Passing a temporary subagent on the fly without writing to disk is easy via --agents, and in non-interactive -p mode you can supply an entire JSON file. Below is a working example of launching a one-off reviewer and validating the agents directory before starting work:

# One-off session launch with a temporary read-only reviewer on Sonnet 5.5
claude --agents '{
  "quick-reviewer": {
    "description": "Use right after major edits to check for regressions and code style issues",
    "prompt": "You are a strict reviewer. Inspect only changed files and list real bugs without fluff.",
    "tools": ["Read", "Grep", "Glob"],
    "model": "sonnet"
  }
}'

# Non-interactive run with agent configuration from a separate JSON file
claude -p --agents ./agents.json "Audit the current branch for leaked secrets"

# Validate YAML frontmatter syntax across all project subagents before a session
claude plugin validate .claude/agents

Running claude plugin validate .claude/agents immediately catches YAML frontmatter typos, forbidden characters in name, or invalid field types before a session even starts. If a field in a valid-looking file still does not take effect, run claude --debug and search for does not recognize or apply in ~/.claude/debug/<session-id>.txt—it pinpoints the exact frontmatter key dropped by the parser.

Now for the main scaling constraint that teams often forget as their agent library grows. Under progressive disclosure, at the start of every session Claude Code loads the names and description fields of all custom subagents into the system context so the model knows whom to call and when.

15,000-Token Description Budget Ceiling

The combined size of description fields across all your custom subagents (excluding built-in ones) is capped at 15,000 tokens. Once your library grows past that threshold, Claude Code prints a startup warning and automatic role-selection accuracy drops due to attention dilution. Keep each description to 2–3 crisp trigger sentences (adding Use proactively when... if helpful), and move all detailed algorithms, checklists, and report formats into the Markdown body—which is loaded into memory only when that specific agent is invoked.

Three Baseline Roles for Any Repository: Researcher, Reviewer, and Test Runner

Starting with a dozen exotic personas makes little sense—in almost any project, three proven baseline roles cover 90% of daily routine and immediately demonstrate separation of permissions and models. A practical example is reviewing a new module or large specification: one agent on a cheap model gathers scattered facts across the repo or web, a second in strict read-only mode hunts for logic gaps and contract mismatches, and a third runs the test suite in the terminal.

Baseline Three-Subagent Kit for a Working Repository

Below are two ready-to-use templates for .claude/agents/—a strictly read-only reviewer and a fast codebase researcher. Notice how both files combine model choice, tool allowlists/denylists, the maxTurns step limiter, and a compact trigger description.

Create .claude/agents/strict-reviewer.md when you need an independent second pair of eyes on finished changes before committing or opening a pull request:

---
name: strict-reviewer
description: Use proactively after code edits or before committing to audit diff, edge cases, and security issues in read-only mode.
model: sonnet
tools: Read, Grep, Glob
disallowedTools: Edit, Write, NotebookEdit, Bash
permissionMode: plan
maxTurns: 12
color: blue
---
You are an independent senior staff reviewer seeing this code for the first time.

Inspect only the modified files and their related interfaces. Check for:
1. Edge cases, error handling, and potential data races.
2. Accidental leaks of secrets, debug keys, or API contract mismatches.
3. Unnecessary abstractions and duplication of existing project utilities.

Do not rewrite anything and do not suggest cosmetic style refactors. Return a concise prioritized list of findings (Critical / Major / Minor) with exact file paths and line numbers.

Notice why Bash is omitted from tools and also listed in disallowedTools: this reviewer is physically unable to edit a file or run a workaround shell command. And maxTurns: 12 ensures that when reviewing a large diff, the agent will not get bogged down endlessly traversing adjacent modules.

Next, add a second helper alongside it—.claude/agents/code-researcher.md for rapidly mapping an unfamiliar part of the project before planning edits:

---
name: code-researcher
description: Use when you need to trace how a feature, endpoint, or module works across multiple files without filling the main context.
model: haiku
tools: Read, Grep, Glob
disallowedTools: Edit, Write, NotebookEdit, Bash
omitClaudeMd: true
maxTurns: 15
color: green
memory: project
---
You are a fast codebase researcher. Your job is to answer the given question as accurately and compactly as possible.

Work step by step:
1. Locate entry points and key symbols using Glob and Grep.
2. Read only relevant file slices without dumping entire modules into the report.
3. Record a brief map of stable modules in project memory if you uncover a non-obvious link.

In your final answer, list: the direct call chain, exact file paths, and potential risk points when modifying.

Thanks to model: haiku and omitClaudeMd: true, this subagent runs at a fraction of the cost and latency of the main session, while memory: project lets it accumulate a compact repository map in .claude/agent-memory/code-researcher/MEMORY.md without inflating the main context. You can easily add the third role—.claude/agents/test-runner.md—following the same pattern, allowing Read, Grep, Glob, Bash in tools (so the agent can run pytest, vitest, or a linter while still blocked from editing source code via Edit and Write, within maxTurns: 10).

To make sure your new kit behaves predictably, watch the first couple of runs to verify that auto-delegation triggers without false positives: if the main agent stubbornly reads 20 files itself—or conversely calls the reviewer for a one-line typo—tweak the wording in description (hot reload applies the change in a couple of seconds). Once subagents reliably take routine search and review off your main window, you will be ready for the next step: editing code simultaneously across multiple branches without conflicts using /fork and isolated Git Worktrees.

What to Apply Right Now

  • Create a .claude/agents/ directory in your current repository and add two baseline subagents: a read-only reviewer (strict-reviewer.md on Sonnet 5.5 without Bash, Edit, or Write) and a fast researcher (code-researcher.md on Haiku 5.5 with omitClaudeMd: true).
  • Validate all YAML frontmatter files with claude plugin validate .claude/agents and confirm each description stays within 2–3 sentences to preserve headroom under the 15,000-token budget.
  • Test hot reloading and least privilege: invoke strict-reviewer in an open session, ask it to edit a line in a file, and verify that write tools are unavailable while active tasks appear in /tasks.
  • If your repository already has project agents and unwanted built-in search triggers occur, check permissions.deny with Agent(...) or the local override hierarchy between .claude/agents/ and ~/.claude/agents/.