s/agents-development

Multi-Agent Patterns

Last updated @legostin · 2026-04-11T17:46:46+00:00

Multi-Agent Patterns

One big agent is fine until you need to do three things at once, keep exploration out of the main context, or run something unattended in CI. Then you reach for the multi-agent primitives: headless mode, subagents, and git worktrees. This page covers what each one actually does, and when to use them instead of a single chat.

Headless mode: claude -p

Headless mode runs Claude Code non-interactively. No REPL, no prompt — you pass the task on the command line or stdin and Claude works, then exits. The core flag is -p (or --print):

claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"

It is the entry point for everything programmatic: CI jobs, pre-commit checks, cron tasks, orchestration from another language.

Output formats--output-format controls what stdout looks like:

  • text (default): plain text response.
  • json: structured JSON with result, session_id, usage metadata.
  • stream-json: newline-delimited JSON events for real-time streaming.
# One-shot with JSON output
claude -p "Summarize this project" --output-format json | jq -r '.result'

# Streaming — token-by-token
claude -p "Explain recursion" \
  --output-format stream-json \
  --verbose --include-partial-messages

Bare mode — add --bare to skip auto-discovery of hooks, plugins, MCP servers, CLAUDE.md, and auto memory. This cuts startup time and gives you identical behavior on every machine. Essential for CI.

claude --bare -p "Apply lint fixes" \
  --allowedTools "Read,Edit,Bash(npm run lint)" \
  --permission-mode acceptEdits

In bare mode, authentication must come from ANTHROPIC_API_KEY or apiKeyHelper — keychain reads are skipped.

CI commit-creation pattern:

gh pr diff "$PR_NUM" | claude -p \
  --append-system-prompt "You are a security reviewer. Flag vulnerabilities." \
  --output-format json \
  --bare

Continuing conversations--continue picks up the most recent session, or capture the session id from JSON output and resume explicitly:

session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Now focus on error handling" --resume "$session_id"

Subagents

A subagent is a specialized assistant with its own system prompt, tool restrictions, and context window. When Claude encounters a task that matches a subagent's description, it delegates: the subagent works in isolation and returns only a summary. Your main conversation never sees the search results, the logs, or the hundred files the subagent read.

Why use them:

  • Context preservation. Exploration produces noise. A subagent eats the noise so your main window stays clean.
  • Tool restriction. Give a reviewer agent read-only tools. Give a migration runner only Bash(psql *) and Read.
  • Cost control. Route cheap tasks to Haiku; keep Opus for the thinking.
  • Focus. A tight system prompt beats "try to remember this rule".

Built-in subagents — Claude Code ships with three you'll use constantly:

Agent Model Tools Purpose
Explore Haiku read-only Fast codebase search
Plan inherits read-only Research during plan mode
general-purpose inherits all tools Complex multi-step tasks

Custom subagents — markdown files with YAML frontmatter in .claude/agents/ (project) or ~/.claude/agents/ (user):

---
name: migration-reviewer
description: Reviews SQL migrations for safety, locking, and rollback
tools: Read, Grep, Glob
model: sonnet
permissionMode: plan
---

You are a senior DBA. When asked to review a migration:
1. Check for missing indexes on foreign keys.
2. Flag ALTER TABLE on tables > 1M rows as a risk.
3. Confirm there is a rollback path.
Return: safe / risky / unsafe, with a reason.

Fields that mattertools (allowlist) or disallowedTools (denylist), model, permissionMode, mcpServers (scope servers to this agent only), hooks, skills, memory (persistent memory directory), isolation: worktree (give the subagent a temp git worktree so it cannot stomp on your files), and effort.

Restricting what an agent can spawn — a main-thread agent can be limited to specific subagent types: tools: Agent(worker, researcher).

Defining at launch via CLI:

claude --agents '{
  "debugger": {
    "description": "Debug test failures by analyzing logs",
    "prompt": "You are an expert debugger.",
    "tools": ["Read", "Bash"],
    "model": "sonnet"
  }
}'

Git worktrees for parallel work

A worktree is a second working copy of the same git repo, pointing at a different branch. Claude Code supports this directly: set isolation: worktree on a subagent, and it works in a fresh temporary worktree that is cleaned up if no changes are made.

This is the cleanest way to run multiple agents on the same repo simultaneously without them fighting over files.

Manual pattern for orchestration from the outside:

git worktree add ../repo-fix-auth fix-auth
cd ../repo-fix-auth
claude -p "fix the bug described in issue #123" --bare

Orchestration patterns

Fan-out, reconcile. One driver agent fans out to N subagents, each handling an independent chunk. Driver reconciles results and resolves conflicts.

Use when: the work splits cleanly (linting 10 packages, generating docs for 20 modules).

Plan then apply. One session in plan mode generates a detailed change list. A second session — possibly a subagent with tighter tools — executes it.

Use when: the plan needs human review before touching the repo.

Reviewer loop. One agent writes code, a reviewer subagent checks it, the main agent fixes feedback. Repeat until the reviewer is quiet.

Use when: quality bar is high and you want multi-perspective review without a human in the loop.

CI watcher. A claude -p --bare job runs on PR open, analyzes the diff, and posts a review comment.

When not to reach for subagents

One context window is often enough. Subagents add complexity and hide information. Don't split a task just because you can. Good rules:

  • If the main agent can handle the work in under 20 tool calls, don't delegate.
  • If the subagent's output would just be copied back into your context verbatim, don't delegate.
  • If you can't write a one-sentence description of what the subagent does, it isn't a subagent yet.

Next: MCP (Model Context Protocol)

Sources

Revision {n}
@legostin · Merged by @legostin
View diff
© 2026 HeyUpBuilt with Laravel, Vue and Tailwind.