At the advanced level of Claude Code, two features take center stage: Hooks (lifecycle automation) and Orchestration (multi-agent coordination). When mastered, they transform Claude Code from a single-agent tool into a distributed automation platform. This article explores 21 Hooks events, 4 handler types, and DevMoses' proven patterns for running 198 agents in parallel.
Hooks: The Complete Picture
Hooks are automation handlers defined in .claude/settings.json. They respond to events—command execution, file changes, prompt input—and trigger actions automatically.
All 21 Events Classified
| Category | Event Name | Trigger |
|---|---|---|
| Command (4) | onCommandStart | Command execution begins |
| onCommandEnd | Command execution completes | |
| onCommandError | Command fails | |
| onCommandResult | Result is returned | |
| File (6) | onFileCreate | File is created |
| onFileChange | File is modified | |
| onFileDelete | File is deleted | |
| onFileRename | File name changes | |
| onFileLintError | Linter reports issues | |
| onFileValidationError | Validation fails | |
| Prompt (3) | onPromptReceived | User input arrives |
| onPromptProcessed | Input is processed | |
| onPromptError | Processing fails | |
| Agent (4) | onAgentStart | Agent starts |
| onAgentEnd | Agent completes | |
| onAgentError | Agent encounters error | |
| onAgentStateChange | Agent state shifts | |
| Other (4) | onScheduleExecution | Scheduled task runs |
| onWebhookReceived | Webhook arrives | |
| onConfigChange | Settings change | |
| onHeartbeat | Periodic check |
4 Handler Types
1. Command Handler — Skill Invocation
Calls a skill from .claude/skills/. Zero token cost.
{
"hooks": {
"onCommandStart": {
"type": "command",
"command": "validate-inputs",
"timeout": 5000
}
}
}Use cases: Pre-flight validation, input format checks, file formatting.
2. HTTP Handler — External Integration
Sends HTTP requests to Slack, Discord, webhooks, or custom APIs.
{
"hooks": {
"onFileChange": {
"type": "http",
"url": "https://hooks.slack.com/services/YOUR/WEBHOOK/URL",
"method": "POST",
"body": {
"text": "File {{file}} changed in {{project}}"
}
}
}
}Use cases: Slack notifications, GitHub Actions triggers, external API calls.
3. Prompt Handler — Input Preprocessing
Transforms and validates user input. Blocks dangerous operations or prepends guidance.
{
"hooks": {
"onPromptReceived": {
"type": "prompt",
"rules": [
{
"pattern": "^delete.*database",
"action": "block",
"message": "DB deletions require explicit approval"
},
{
"pattern": "^deploy",
"action": "prepend",
"text": "Deployment checklist: staging approved? rollback tested?"
}
]
}
}
}Use cases: Blocking dangerous commands, enforcing guidelines, auto-expansion of templates.
4. Agent Handler — Multi-Agent Control
Spawns a subagent to handle complex tasks like error analysis or recovery.
{
"hooks": {
"onCommandError": {
"type": "agent",
"agent": "error-analyzer",
"timeout": 30000
}
}
}Use cases: Auto-error diagnosis, fallback processing, task distribution.
Complete Hooks Configuration Examples
Level 1: Basic Validation + Notifications
{
"hooks": {
"onCommandStart": {
"type": "command",
"command": "validate-syntax"
},
"onFileChange": {
"type": "http",
"url": "https://hooks.slack.com/services/YOUR/WEBHOOK/URL",
"body": {
"text": "✅ {{file}} updated"
}
}
}
}Level 2: Block Dangerous Ops + Auto-Lint
{
"hooks": {
"onPromptReceived": {
"type": "prompt",
"rules": [
{
"pattern": "^drop table|^delete from",
"action": "block",
"message": "DB deletion blocked. Requires approval."
}
]
},
"onFileChange": {
"type": "command",
"command": "run-eslint"
}
}
}Level 3: Auto-Error Analysis + Pre-Deploy Checks
{
"hooks": {
"onCommandError": {
"type": "agent",
"agent": "error-analyzer"
},
"onPromptReceived": {
"type": "prompt",
"rules": [
{
"pattern": "^deploy.*production",
"action": "prepend",
"text": "Pre-deploy checklist:\n□ staging validated\n□ migration plan ready\n□ rollback tested"
}
]
}
}
}Orchestration: Multi-Agent Coordination
Rather than loading everything onto one agent, distribute work across multiple specialists. This scales complexity handling dramatically.
Subagents: Role-Based Distribution
Three subagent archetypes emerge:
Explore Agent
Maps the project structure, extracts dependencies, identifies critical files.
---
name: "Explore"
description: "Analyze project structure and generate a file map"
---
1. Extract dependencies from package.json
2. Visualize src/ folder hierarchy
3. Extract key design principles from README
4. Identify critical files (config, schema, foundation)Timing: New project onboarding, monthly refreshes, pre-refactor.
Plan Agent
Creates implementation blueprints. Consumes Explore output. Builds timelines.
---
name: "Plan"
description: "Design implementation approach based on Explore analysis"
---
Input: Explore agent output
Tasks:
1. Break requirements into 3 milestone phases
2. Map dependencies between phases
3. List risk factors
4. Provide effort estimates (phase-by-phase)Timing: New feature kickoff, deployment planning.
General-Purpose Agent
Generates code. Consumes Explore and Plan outputs.
$ !orchestrate-general-purpose \
--explore-result="explore_output.json" \
--plan-result="plan_output.json" \
--task="Auth component implementation"Agent Teams: Parallel Independent Contexts
Multiple agents work in parallel with shared state, syncing periodically.
{
"teams": {
"backend_team": {
"agents": ["api-design", "database-schema", "auth-service"],
"context": "shared-project-state",
"sync_interval": "5m"
},
"frontend_team": {
"agents": ["ui-components", "state-management", "styling"],
"context": "shared-project-state",
"sync_interval": "5m"
}
},
"integration": {
"point": "weekly-review",
"conflicts": "manual-review"
}
}Characteristics: Independent progress, shared state sync, human review at integration points.
/batch Skill: Parallel File Processing
Apply changes to 100+ files in parallel. Ideal for migrations, API upgrades, module renames.
---
name: "Migrate to TypeScript Strict Mode"
description: "Apply strict mode across all 500 TypeScript files"
---
Step 1: Generate file list
find src/ -name "*.ts" -o -name "*.tsx" | sort > files.txt
Step 2: Split into batches of 50
split -l 50 files.txt batch_
Step 3: Assign batches to parallel agents
for batch in batch_*; do
/batch --files="$(cat $batch)" --task="convert-to-strict-mode" &
done
Step 4: Consolidate and verify
npm run type-check
npm run testExecution:
$ !batch \
--task="migrate-api-v1-to-v2" \
--file-pattern="src/api/**/*.ts" \
--parallelism=10 \
--rollback-on-errorReal-World Patterns
Pattern A: Startup / Small Team
{
"hooks": {
"onPromptReceived": {
"type": "prompt",
"rules": [
{
"pattern": "^deploy.*production",
"action": "block",
"message": "Prod deployments Friday 4pm only. Notify PM."
}
]
},
"onFileChange": {
"type": "command",
"command": "run-unit-tests"
}
}
}Pattern B: Growth Stage / Mid-Size Team
{
"hooks": {
"onCommandError": {
"type": "agent",
"agent": "error-analyzer"
},
"onFileChange": {
"type": "http",
"url": "https://api.github.com/repos/YOUR/REPO/check-runs",
"body": {
"name": "eslint-check"
}
}
},
"orchestration": {
"default_strategy": "subagents",
"subagents": ["explore", "plan", "implement"]
}
}Pattern C: Enterprise / Large Team
{
"hooks": {
"onPromptReceived": {
"type": "prompt",
"rules": [
{
"pattern": "^deploy",
"action": "prepend",
"text": "Pre-deployment:\n□ JIRA ticket referenced\n□ DevOps/QA/PM notified\n□ 24h staging monitoring"
}
]
}
},
"orchestration": {
"teams": {
"backend": ["api", "database", "auth", "payment"],
"frontend": ["ui", "state", "analytics"],
"devops": ["ci-cd", "monitoring", "security"]
},
"sync_strategy": "real-time"
}
}Lessons from DevMoses: 198-Agent Parallel Execution
DevMoses executed a complex ML pipeline using 198 parallel agents—completing work 100x faster than manual approaches. Success factors:
- Clear role separation — Each agent owns one responsibility
- Asynchronous progress — No waiting; agents work independently
- Regular sync — Check progress and resolve conflicts every 5 minutes
- Fail-safe design — One agent's failure doesn't cascade
- Output integration — Final stage merges all results
Apply these principles to smaller teams: 3–5 role-specialized agents yield significant productivity gains without complexity overhead.
Common Questions
Q1: How do Hooks differ from Skills? Hooks are "event-driven automation"; Skills are "manual-invoked reusable tasks." Use Hooks when you want automatic action on an event; use Skills when you repeat the same workflow.
Q2: How safe is auto-recovery?
Safe boundaries: auto-recovery for read/validate/notify. Require user approval for delete/overwrite/deploy. Use action: "block" to prevent dangerous operations, then manual execution after review.
Q3: How are conflicts resolved in multi-agent teams?
Never auto-merge. Instead: detect conflicts → human review → resolution. Set conflicts: "manual-review" and do weekly integration reviews.
Q4: What's the execution order of multiple Hooks on the same event?
Order follows definition order in .claude/settings.json. If order matters, combine multiple Hooks into a single Hooks entry.
Wrapping Up
Hooks and Orchestration elevate Claude Code from solo automation into a coordinated team. The 21 events, 4 handler types, and multi-agent strategies combine to unlock dramatic quality and productivity improvements.
Start small: begin with onCommandStart input validation, add onFileChange auto-testing, then introduce Subagents for role distribution. Scale incrementally, and you'll compound productivity sustainably.