Skip to main content

Command Palette

Search for a command to run...

Custom Subagents: 90% of Developers Set Them Up Wrong

After debugging 47 subagent failures, I found the same 4 configuration mistakes. — the complete fix guide.

Updated
11 min readView as Markdown
Custom Subagents: 90% of Developers Set Them Up Wrong

📖 Read the full article on Medium → — with better formatting, code highlights, and community discussion.



Custom Subagents: 90% of Developers Set Them Up Wrong

After debugging 47 subagent failures, I found the same 4 configuration mistakes. — the complete fix guide.

My 47th subagent failed to activate during a code review last time. I’d configured it perfectly — clear description, scoped tools, focused system prompt.

Claude just… did the review itself. Again.

After debugging dozens of subagent configurations across three production codebases, I found the same four mistakes killing activation rates. The official documentation covers how to create subagents. This article covers why yours fail — and the production-tested fixes that actually work.

Note: AI helped research and organize this article. The experiments, observations, and honest assessment? That’s all from my testing.

Why Subagents Matter (When They Work)

Each subagent runs in its own context window. That’s 200k tokens of dedicated focus, isolated from your main conversation. When Claude Code delegates to a subagent, the specialist does its work independently and returns only the results — not the 47 files it read to get there.

The potential is significant:

  • Context preservation: Exploration doesn’t pollute your main thread

  • Parallel execution: Multiple specialists working simultaneously

  • Scoped permissions: Read-only reviewers can’t accidentally delete your production database

  • Cost optimization: Route simple tasks to Haiku, complex ones to Sonnet

But here’s what the documentation doesn’t emphasize: Claude Code prefers to handle tasks itself. Without intentional configuration, your carefully crafted subagents sit unused while Claude Code burns through your main context window doing everything directly.

These four mistakes — and their solutions — make the difference.

Mistake 1: Allowing All Tools to All Agents

The Problem

When you omit the tools field from your subagent configuration, the agent inherits all tools from the main thread. Every tool. Including MCP servers, bash access, file write permissions — everything.

This creates three problems:

  1. Context pollution: Tool definitions consume tokens even when unused

  2. Security risk: A “read-only reviewer” with inherited write permissions isn’t read-only

  3. Confused behavior: Agents attempt operations outside their expertise

I discovered this when my “documentation analyst” subagent started editing source files. It had inherited Edit and Write tools I never intended it to use.

The Solution: Explicit Tool Allowlists

Best Practice: Start from deny-all. Allowlist only the tools each subagent needs for its specific job.

Here’s the pattern for different agent types:

Read-only agents (reviewers, auditors, analyzers):

---
name: code-reviewer
description: Reviews code for quality, security, and maintainability issues
tools: Read, Grep, Glob
---

Research agents (documentation lookup, codebase exploration):

---
name: research-agent
description: Investigates technical questions by searching docs and code
tools: Read, Grep, Glob, WebFetch
---

Code modification agents (implementers, fixers):

---
name: implementer
description: Implements features and fixes bugs in the codebase
tools: Read, Write, Edit, Bash, Glob, Grep
---

The Rule: If you can’t explain why an agent needs a specific tool, it doesn’t need that tool.

Mistake 2: Vague Descriptions That Claude Can’t Match

The Problem

Claude uses the description field to decide when to delegate tasks. Vague descriptions mean Claude Code can't match your intent to the right specialist.

This doesn’t work:

description: "Helps with code stuff"

Claude reads this and thinks: “I help with code stuff too. I’ll handle it myself.”

The Solution: Action-Oriented Descriptions with Trigger Keywords

Best Practice: Write descriptions that answer three questions:

  1. What specific action does this agent perform?

  2. When should Claude Code delegate to it?

  3. What keywords should trigger delegation?

Here’s the pattern:

description: "Reviews code for security vulnerabilities, performance issues, and style violations. Use PROACTIVELY after writing or modifying code. Invoke when analyzing pull requests, reviewing changes before commit, or auditing existing code for quality issues."

Notice the components:

  • Action verb + specific domain: “Reviews code for security vulnerabilities, performance issues, and style violations”

  • Trigger directive: “Use PROACTIVELY” tells Claude to delegate without being asked

  • Use cases: “analyzing pull requests, reviewing changes before commit” gives Claude Code concrete scenarios

Pro Tip: The phrases “Use PROACTIVELY” and “MUST BE USED” in your description field significantly increase automatic delegation. Claude’s matching algorithm weights these directives heavily.

More examples of good descriptions:

# Database specialist
description: "MUST BE USED for all database migrations, schema changes, and SQL optimization. Expert in PostgreSQL patterns, index design, and query performance."

# Test automation
description: "Use PROACTIVELY to run tests after code changes. Analyzes test failures, identifies root causes, and suggests minimal fixes while preserving test intent."

# Security auditor  
description: "Invoke IMMEDIATELY for authentication code, API endpoints handling user data, or any security-sensitive changes. Reviews for OWASP vulnerabilities and access control issues."

Mistake 3: Context Pollution from Research Tasks

The Problem

Without isolation, subagent work dumps into your main conversation. Your 200k context window fills with intermediate results, file contents from exploration, and research artifacts you’ll never reference again.

I watched my main context hit 80% capacity after a single “investigate the authentication flow” request. The subagent had read 34 files, and every byte landed in my primary thread.

The Solution: Context Fork for Isolated Execution

Best Practice: Use context: fork for any agent that performs exploration, research, or multi-step investigation.

---
name: research-agent
description: Deep research without polluting main context. Use for investigating technical questions, exploring unfamiliar codebases, or gathering context for planning.
context: fork
tools: Read, Grep, Glob, WebFetch
---

How it works: The forked agent gets its own isolated context window. It can read 50 files, search through documentation, and explore dependencies — then return only a distilled summary to your main conversation.

When to use context fork:

  • Codebase exploration before planning

  • Documentation research

  • Multi-file investigation for debugging

  • Any task where the process generates more content than the result

When NOT to use context fork:

  • Agents that need to reference ongoing conversation context

  • Quick, single-file operations

  • Agents that must maintain state across multiple invocations

The isolation keeps your main thread focused on what matters: the actual implementation work.

Mistake 4: Claude Code Ignores Your Subagents

The Problem

This is the silent killer. You’ve configured everything correctly, but Claude Code still handles tasks itself instead of delegating.

From my testing and community reports, Claude Code “rarely summons subagents automatically” without additional configuration. The model prefers direct action over delegation — it’s faster and doesn’t require coordination overhead.

The Solution: Explicit Delegation Rules + Pipeline Hooks

Best Practice #1: Add delegation rules to your CLAUDE.md file.

## Task Delegation Rules

During implementation, delegate to specialized subagents based on their expertise:
- Code review tasks → Use `code-reviewer` subagent
- Database changes → Use `database-admin` subagent  
- Test failures → Use `test-runner` subagent
- Security-sensitive code → Use `security-auditor` subagent
Do not attempt these tasks directly. Always delegate to the appropriate specialist.

Best Practice #2: Use SubagentStop hooks for pipeline handoffs.

For sequential workflows where one agent’s output feeds another, configure hooks in your .claude/settings.json:

{
  "hooks": {
    "SubagentStop": [
      {
        "matcher": "pm-spec",
        "hooks": [
          {
            "type": "command",
            "command": "echo 'Next: Use the architect-review subagent to validate this specification'"
          }
        ]
      },
      {
        "matcher": "architect-review", 
        "hooks": [
          {
            "type": "command",
            "command": "echo 'Next: Use the implementer-tester subagent to build this feature'"
          }
        ]
      }
    ]
  }
}

The hook prints the next suggested command to stdout, which appears in Claude’s transcript. This creates a guided pipeline where each agent completion suggests the next step.

Best Practice #3: Agent-scoped hooks for validation.

Define hooks directly in the subagent’s frontmatter for operations that need validation:

---
name: db-reader
description: Execute read-only database queries for analysis and reporting
tools: Bash
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-readonly-query.sh"
---

This configuration ensures the db-reader agent can only execute queries that pass your validation script — enforcing read-only access at the tool level.

Enterprise Workflow Patterns

Two patterns have emerged from production deployments that solve the “Claude Code ignores subagents” problem through architecture rather than configuration.

Pattern 1: Sequential Pipeline with Human Gates (PubNub)

pm-spec → [approval] → architect-review → [approval] → implementer-tester → [approval] → PR

How it works:

  1. pm-spec agent: Writes product specification from requirements (tools: Read, Grep, WebFetch)

  2. Human reviews and approves the spec

  3. architect-review agent: Validates architecture decisions, flags risks (tools: Read, Grep, Glob)

  4. Human reviews architecture

  5. implementer-tester agent: Implements code AND writes tests (tools: Read, Write, Edit, Bash, Grep, Glob)

  6. Human reviews implementation

Why it works: Each agent (subagent) has a single clear responsibility. SubagentStop hooks suggest the next step. Human approval gates prevent runaway automation while maintaining the pipeline structure.

Configuration for pm-spec:

---
name: pm-spec
description: "MUST BE USED first for any new feature. Writes product specifications from requirements. Produces structured spec documents with acceptance criteria."
tools: Read, Grep, WebFetch
model: sonnet
---
You are a product specification writer. When invoked:
1. Analyze the feature requirements
2. Research existing patterns in the codebase
3. Write a structured specification including:
   - Problem statement
   - Proposed solution
   - Acceptance criteria
   - Technical constraints
   - Dependencies
Output format: Markdown document saved to ./specs/{feature-name}-spec.md

Pattern 2: Parallel Specialists (Zach Wills)

/add-linear-ticket
    ├── PM agent (200k context)
    ├── UX-Designer agent (200k context)  
    └── Software-Engineer agent (200k context)

How it works: A single command spawns three specialists in parallel. Each uses its dedicated 200k context window to focus on one domain. Results are synthesized into a comprehensive ticket.

Why it works: Context windows don’t compete. The PM can analyze all user research while the engineer reviews technical constraints — neither needs to hold the other’s context.

When to use each pattern:

Pattern Use When Sequential Pipeline High-risk changes requiring approval gates, compliance requirements, complex multi-stage features Parallel Specialists Multi-stakeholder analysis, research tasks, ticket creation, any work benefiting from diverse perspectives

Complete Production Example

Here’s a full subagent configuration with all best practices applied:

---
name: code-reviewer
description: "Reviews code for security vulnerabilities, performance issues, and style violations. Use PROACTIVELY after writing or modifying code. MUST BE USED for all pull request reviews and pre-commit analysis."
tools: Read, Grep, Glob
model: sonnet
context: fork
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-readonly.sh"
---
You are a senior code reviewer focused on production-quality code.
## Review Checklist
When invoked:
1. Run `git diff` to identify changed files
2. Analyze each change for:
   - Security vulnerabilities (injection, XSS, auth bypass)
   - Performance issues (N+1 queries, memory leaks, blocking operations)
   - Style violations (naming conventions, code organization, documentation)
## Output Format
Categorize findings by severity:
**CRITICAL** - Must fix before merge
- Security vulnerabilities
- Data loss risks
- Breaking changes without migration
**WARNING** - Should fix
- Performance concerns
- Missing error handling
- Incomplete documentation
**INFO** - Consider improving
- Style suggestions
- Refactoring opportunities
- Test coverage gaps
## Constraints
- Never modify code directly
- Always explain the "why" behind each finding
- Include specific line numbers and file paths
- Suggest concrete fixes with code examples

What this configuration achieves:

  • Explicit tool restriction: Read, Grep, Glob only — can’t accidentally modify files

  • Strong description: Action verbs, trigger keywords, specific use cases

  • Context isolation: context: fork keeps research out of main thread

  • Validation hook: PreToolUse ensures no write operations slip through

  • Structured output: Clear categories make findings actionable

Best Practices Checklist

Before deploying any subagent to production, verify these requirements:

Tool Configuration

  • [ ] tools field explicitly defined (never rely on inheritance)

  • [ ] Read-only agents use: Read, Grep, Glob

  • [ ] Write agents use minimal required set: Read, Write, Edit, Bash, Glob, Grep

  • [ ] MCP tools explicitly included only when needed

Description Quality

  • [ ] Starts with action verb + specific domain

  • [ ] Includes “Use PROACTIVELY” or “MUST BE USED” trigger phrase

  • [ ] Lists 2–3 concrete use cases for delegation

  • [ ] Contains domain-specific keywords for matching

Context Management

  • [ ] Research/exploration agents use context: fork

  • [ ] Implementation agents that need conversation context do NOT use fork

  • [ ] Long-running tasks designed for isolation

Activation Strategy

  • [ ] CLAUDE.md contains explicit delegation rules

  • [ ] SubagentStop hooks configured for pipeline workflows

  • [ ] PreToolUse hooks validate constrained operations

What I’m Still Figuring Out

Subagent activation remains inconsistent. Even with all these fixes applied, Claude Code sometimes decides to handle tasks directly. The workarounds help significantly, but they’re workarounds — not guarantees.

Open questions from my testing:

  • Activation reliability: How do we get consistent delegation without explicit commands?

  • Cross-session state: Subagents start fresh each invocation. For long-running analysis, this means re-gathering context repeatedly.

  • Skill visibility control: GitHub issue #12633 requests the ability to hide skills from the main agent. Currently, all skills are visible even when intended only for subagents.

The Bottom Line

Subagents aren’t magic — they’re infrastructure. Like any infrastructure, they require intentional design to deliver value.

The four fixes that matter:

  1. Explicit tool allowlists — deny by default, allowlist what’s needed

  2. Action-oriented descriptions — tell Claude Code exactly when to delegate

  3. Context fork for research — isolate exploration from your main thread

  4. Delegation rules + hooks — guide Claude Code toward your specialists

For codebases under 50 files, the setup overhead probably isn’t worth it.

The 2–3 hours of configuration investment pays off after day three. My code reviews are more thorough, my context window stays focused, and Claude Code actually uses the specialists I’ve built.

Worth the investment? For production codebases, yes. Just don’t expect it to work out of the box.


What activation patterns have worked in your subagent configurations? I’m particularly curious about approaches I haven’t tried. Drop your experience in the comments.


✨ Thanks for reading! If you’d like more practical insights on AI and tech, hit subscribe to stay updated.

I’d also love to hear your thoughts — drop a comment with your ideas, questions, or even the kind of topics you’d enjoy seeing here next. Your input really helps shape the direction of this channel.

About the Author

Me, Alireza Rezvani work as a CTO @ an HealthTech startup in Berlin and architect AI development systems for my engineering and product teams. I write about turning individual expertise into collective infrastructure through practical automation.

Connect: Website | LinkedIn Read more on Medium: Reza Rezvani


🚀 Enjoyed this? Read more on Medium

📖 Read the original article on Medium →

Follow me on Medium for more production-tested guides on OpenClaw, Claude Code, and AI agent development.

Originally published on Medium

More from this blog

O

OpenClaw and AI Agent Harness Best Practices Master Class

30 posts

The #1 resource for OpenClaw & Claude Code. Production-tested guides, best practices, and master classes from a CTO running AI agents in production daily.