CLAUDE LABJP
FORK — Claude Code 2.1.212 changes what /fork does: it copies your conversation into a new background session with its own row in claude agents, so you can keep working. The old in-session subagent is now /subtaskLIMITS — WebSearch calls are now capped at 200 per session by default, and subagent spawns get the same 200 ceiling, so a runaway search or delegation loop stops on its ownMCPBG — MCP tool calls running past two minutes now move to the background automatically, keeping the session usable. Tune the threshold with CLAUDE_CODE_MCP_AUTO_BACKGROUND_MSPLANFIX — Fixed plan mode auto-running file-modifying Bash commands such as touch and rm without a permission prompt or an SDK canUseTool callbackSONNET5 — Claude Sonnet 5 is running on introductory pricing of $2 per million input tokens and $10 per million output. After August 31 it moves to $3 and $15IPO — Bankers are reportedly lining up investor meetings for Anthropic ahead of a possible public listing as soon as OctoberFORK — Claude Code 2.1.212 changes what /fork does: it copies your conversation into a new background session with its own row in claude agents, so you can keep working. The old in-session subagent is now /subtaskLIMITS — WebSearch calls are now capped at 200 per session by default, and subagent spawns get the same 200 ceiling, so a runaway search or delegation loop stops on its ownMCPBG — MCP tool calls running past two minutes now move to the background automatically, keeping the session usable. Tune the threshold with CLAUDE_CODE_MCP_AUTO_BACKGROUND_MSPLANFIX — Fixed plan mode auto-running file-modifying Bash commands such as touch and rm without a permission prompt or an SDK canUseTool callbackSONNET5 — Claude Sonnet 5 is running on introductory pricing of $2 per million input tokens and $10 per million output. After August 31 it moves to $3 and $15IPO — Bankers are reportedly lining up investor meetings for Anthropic ahead of a possible public listing as soon as October
Articles/Claude Code
Claude Code/2026-03-27Advanced

Claude Code Mastery — Hooks, Orchestration & Multi-Agent Operations

Master Hooks and Orchestration in Claude Code. Learn 21 lifecycle events, 4 handler patterns, and multi-agent coordination strategies inspired by DevMoses' 198-agent parallel execution.

claude-code129hooks14orchestration7subagents6agent-teams3advanced11

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

CategoryEvent NameTrigger
Command (4)onCommandStartCommand execution begins
onCommandEndCommand execution completes
onCommandErrorCommand fails
onCommandResultResult is returned
File (6)onFileCreateFile is created
onFileChangeFile is modified
onFileDeleteFile is deleted
onFileRenameFile name changes
onFileLintErrorLinter reports issues
onFileValidationErrorValidation fails
Prompt (3)onPromptReceivedUser input arrives
onPromptProcessedInput is processed
onPromptErrorProcessing fails
Agent (4)onAgentStartAgent starts
onAgentEndAgent completes
onAgentErrorAgent encounters error
onAgentStateChangeAgent state shifts
Other (4)onScheduleExecutionScheduled task runs
onWebhookReceivedWebhook arrives
onConfigChangeSettings change
onHeartbeatPeriodic 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 test

Execution:

$ !batch \
  --task="migrate-api-v1-to-v2" \
  --file-pattern="src/api/**/*.ts" \
  --parallelism=10 \
  --rollback-on-error

Real-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:

  1. Clear role separation — Each agent owns one responsibility
  2. Asynchronous progress — No waiting; agents work independently
  3. Regular sync — Check progress and resolve conflicts every 5 minutes
  4. Fail-safe design — One agent's failure doesn't cascade
  5. 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.

Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

Claude Code2026-03-27
Retracing Claude Code's Five Levels in Real Use — I Stalled at Level 3 and Level 5
Claude Code mastery is usually described as five levels, from Raw Prompting to Orchestration. Retracing them as an indie developer running apps and four sites, I found the steps are nowhere near equal in height.
Claude Code2026-03-15
Building Production-Grade Multi-Agent Systems with Claude Code: Complete Implementation Guide
Master advanced multi-agent orchestration patterns using Claude Code and Agent SDK. Learn parallel execution, dependency management, automatic retries, and dynamic task distribution. Complete implementations for financial analysis, web scraping, and complex workflows.
Claude Code2026-06-14
Running Claude Code Hooks as a Quality Gate Without Breaking Your Pipeline
An implementation note on running Claude Code Hooks as a safety valve for automation: when to block with exit code 2 versus JSON output, how to keep formatters from looping or over-blocking, and how to log every hook firing so misfires are traceable.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →