Agent frontmatter hooks: PreToolUse, PostToolUse, Stop only.
Settings-level hooks affect ALL subagents -- configure in settings.json or plugin/hooks/hooks.json.
Agent Scope & Precedence
Priority
Location
Scope
How to Create
1 (highest)
--agents CLI flag
Current session
JSON at launch
2
.claude/agents/
Project
Manual or /agents
3
~/.claude/agents/
User (all projects)
Manual or /agents
4 (lowest)
plugin/agents/
Where plugin enabled
Installed with plugin
⚠️Protected-path (v3.4.70): Agent Write targets → .claude/<subdir>/ (project-relative, whitelisted in permission-guard.sh). ~/.claude/* blocked ALL modes; check BEFORE hooks → $HOME/.claude/* whitelist = dead. Exceptions: commands|agents|skills|worktrees. See memory protected_path_write_block.md.
CLI JSON Format (session-only)
claude --agents '{
"code-reviewer": {
"description": "Expert reviewer. Use after code changes.",
"prompt": "You are a senior code reviewer...",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'
⚠️ Subagents Cannot Spawn Subagents
Архитектурное ограничение: субагенты используют SubAgentLoop, из которого исключен AgentTool (Task tool). Вложенный запуск агентов невозможен ни одним способом:
Попытка
Результат
Task(subagent_type=...) из субагента
Tool отсутствует в toolset -- субагент явно сообщает что не может
Не сработает -- context: fork использует тот же AgentTool для spawn
claude -p через Bash
Технически запустит, но не рекомендуется: OOM crashes, потеря контекста, неуправляемость
Указание Task в tools: frontmatter
Игнорируется -- docs: "Task(agent_type) has no effect in subagent definitions"
Рекомендуемые паттерны:
Паттерн
Как
Chaining
Main agent запускает агентов последовательно, передавая результат
Preloaded skills
skills: в frontmatter -- контент инжектируется при старте (не runtime)
File-based communication
Агенты пишут результаты в файлы, следующий агент читает
Agent Teams (v2.1.33+)
Lead координирует teammates (но teammates тоже не спавнят sub-teammates)
Agent Teams -- lead coordinates teammates via Task API tools: TaskCreate, TaskUpdate, TaskList, TaskGet, TaskOutput, TaskStop. Hook events: TeammateIdle, TaskCompleted, TaskCreated (v2.1.84). One level deep only.
What a subagent receives at runtime (important for system prompt design):
Context
Inherited?
Notes
CLAUDE.md (project + user)
Yes
Via <system-reminder>, with "may or may not be relevant" disclaimer
.claude/rules/*.md
Yes
Bundled with CLAUDE.md injection
Git status
Yes
Basic project state
Permissions
Yes
Override via permissionMode
Tools / MCP servers
Yes
Configurable via tools/disallowedTools/mcpServers
Skills from skills: field
Yes
Full content injected at startup (not runtime)
Agent memory (memory: field)
Yes
First 200 lines of MEMORY.md; auto-adds Read/Write/Edit
Full Claude Code system prompt
No
Replaced with short ~294-token agent prompt
Parent conversation history
No
Clean slate each invocation
Parent's invoked skills
No
Must list explicitly in skills: field
Parent's auto memory (memory/MEMORY.md)
No
Only agent-specific memory
Design implication: Don't duplicate CLAUDE.md rules in agent body -- they're already injected. Focus system prompt on agent-specific role, patterns, and checklists.
Known bugs: See Known Bugs section below for full list and workarounds.
Skills Injection
Skills in frontmatter are injected as full content into agent context at startup.
skills:api-conventions, error-handling
List skills explicitly per agent -- no inheritance from parent.
Reference-Aware Skills
When an agent spawns from a skill that uses references/, the agent does NOT have skill_base_dir.
<example>user:"exact phrase user would say"<commentary>Why THIS agent, not another</commentary></example>
No Context: line needed — keep minimal
No assistant: response needed — Claude doesn't need to see what it would say
<commentary> is required — it's the selection signal
Vary phrasing: don't repeat same pattern twice
Common Agent Types
Type
Model
Tools
Focus
developer-*
opus
Read, Write, Edit, Bash, Task
Implementation
reviewer
opus
Read, Glob, Grep
Code review
tester
sonnet
Read, Bash
Test execution
arch-*
opus
Read, Glob, Grep, WebFetch
Architecture (read-only)
docs-*
sonnet
Read, Write, Edit
Documentation
explorer
haiku
Read, Glob, Grep
Quick search
Best Practices
Practice
Benefit
Scope tools per agent
Principle of least privilege
Single clear goal
Focused behavior
Include checklist
Definition of Done
Ask before major changes
User control
Start restrictive
Expand tools as validated
Define next steps
Clear handoffs
Complete Agent Examples
Production-ready agents showing frontmatter + system prompt essentials.
code-reviewer
Field
Value
model
opus
color
cyan
tools
Read, Glob, Grep
---name:code-reviewerdescription:Reviews code for quality, security, patterns. Use after code changes or for PR review.model:opuscolor:cyantools:Read, Glob, Grep---
Output: Structured report with severity levels (Critical/High/Medium/Low)
Read-only: no modifications, only analysis and recommendations
Report format: findings table with file, line, severity, issue, recommendation
test-generator
Field
Value
model
sonnet
color
green
tools
Read, Write, Edit, Bash
---name:test-generatordescription:Creates unit tests for Java/Kotlin code. Use when tests needed for new features.model:sonnetcolor:greentools:Read, Write, Edit, Bash---
System prompt key elements:
Role: QA engineer specializing in JUnit 5, Mockito, AssertJ
Patterns: BDD format (GIVEN/WHEN/THEN), @DisplayName on methods, .as() on assertions
Validation: mvn test after generation, no compilation errors
Output: test file path, coverage summary, command to run tests
doc-generator
Field
Value
model
sonnet
color
green
tools
Read, Write, Edit
---name:doc-generatordescription:Generates technical documentation from code. Use for README, API docs, architecture.model:sonnetcolor:greentools:Read, Write, Edit---
System prompt key elements:
Role: Technical writer optimizing for LLM consumption
Format: Tables over prose, code blocks over text, bullets over numbered lists
Token efficiency: no filler words, dense content, positive framing
Output: markdown files with consistent structure and clear navigation
security-analyzer
Field
Value
model
opus
color
red
tools
Read, Glob, Grep, Bash
---name:security-analyzerdescription:Scans code for security vulnerabilities. Use before releases or after security incidents.model:opuscolor:redtools:Read, Glob, Grep, Bash---
System prompt key elements:
Role: Security expert specializing in OWASP Top 10