Claude Certified Developer · प्रोफेसनल
Module 7: Fleets of coding agents: worktrees, gates and review
Study notes written by Sanjay Shah. Not official Anthropic material. Facts marked "check before relying on it" may have changed.
On this page
Study notes, not official course material. Our take on official course 7 (patterns and controls for fleets of coding agents). Facts checked 2026-11-25. This is how I actually work on a multi-tenant SaaS platform I build, shown generically.
The video opens on a grid of five terminals, each in its own worktree, each busy, with a counter: "5 agents · 5 branches · 0 merges to main". Five coding agents are changing one codebase at once, and none of them can merge without passing the same gates. This module covers how to get the throughput of a fleet without the collisions, skipped tests, leaked secrets and confident nonsense that fleets produce when nobody designs the controls.
What you'll be able to do
Split work so parallel agents don't collide, and give each one its own git worktree and branch.
Write a brief that an agent can finish without asking you anything.
Set project rules in
CLAUDE.md, pick a permission mode that fits the task, and write permission rules.Write PreToolUse hooks that actually block (exit code 2), fail closed, and keep an agent inside its brief.
Build branch gates that catch what agents do to "make it green": skipped tests, fewer tests, secrets, risky dependencies.
Run an independent review, keep the merge decision with a person, and merge one branch at a time.
Run the fleet day to day: a coordinator, hand-over notes, budgets, and knowing when to restart an agent instead of nudging it.
1. Why run a fleet, and how fleets fail
A single coding agent is limited by its context and by your attention: you wait while it works, then review. With several agents on independent tasks, the waiting overlaps, and your time goes into briefing and reviewing, which is where a person adds the most.
Fleets fail in a small number of predictable ways:
| Failure | What it looks like | Control that stops it |
|---|---|---|
| Collision | Two agents edit src/tickets/list.ts in the same checkout; one overwrites the other's half-finished change | One worktree per task; tasks split by files |
| Green by cheating | A failing test gets .skip, an assertion is loosened, or a test file is deleted | Gates: test count can't drop, no new skips |
| Scope creep | Asked to fix pagination, the agent "also tidies" the auth middleware | Brief with explicit out-of-scope; a scope hook |
| Dangerous action | git push --force, rm -rf, editing .env, a migration against a real database | Hooks + deny rules + no credentials for those actions |
| Secret in a commit | A test API key pasted into a fixture | Secret scan gate; keys rotated if it happens |
| Confident nonsense | Plausible code that compiles, passes weak tests and is wrong | Fresh-context review, then a person |
| Endless loop | 40 turns on a flaky test, spend climbing | Turn and spend budget; restart with a better brief |
Every control below maps to one of these rows. If you can't say which failure a control prevents, you probably don't need it.
2. The shape of the fleet
One task = one worktree = one branch
A git worktree is a second (or fifth) checkout of the same repository, on its own branch, in its own folder, sharing one .git store. Agents in different worktrees can't overwrite each other's files, and each branch can be gated and reviewed alone.
# scripts/new-worktree.sh <task-name>: one isolated checkout per agent
set -euo pipefail
name="$1"
git fetch origin main
git worktree add "../wt/$name" -b "agent/$name" origin/main
cp "briefs/$name.md" "../wt/$name/BRIEF.md"
echo "worktree ready: ../wt/$name on branch agent/$name"Claude Code can also create the worktree for you: claude --worktree <name> starts a session in its own isolated worktree, and running it again with a different name in a second terminal gives you a second parallel session. A worktree is created from an existing commit, so a brand-new repository needs at least one commit first.
Clean up when the branch is merged: git worktree remove ../wt/<name>, then delete the branch.
Split by files, not by feature names
Worktrees stop agents overwriting each other's working files, but two branches that change the same lines still conflict at merge time. When the coordinator splits work, it checks which files each task will touch. If two tasks need the same file, run them one after the other, or carve out the shared change as its own small first task. In the course lab the three tasks were picked so they barely overlap: CSV export (new files), the pagination bug (src/tickets/list.ts) and a rate-limit header (src/http/middleware.ts).
Lockfiles (package-lock.json) are the classic hidden overlap: two agents each adding a dependency will conflict. A brief rule like "don't add dependencies; report if you need one" avoids most of it.
3. The brief: the agent's whole world
An agent starts each task knowing nothing about your conversation. The brief is the only context it gets, so it has to be complete. The template:
# Brief: <task name>
## Goal
One or two sentences on the outcome, in user terms.
## Files in scope
- src/tickets/list.ts
- src/tickets/list.test.ts
## Out of scope
- Anything under src/auth/ and src/billing/
- Dependencies (don't add or upgrade any; report if one is needed)
- Test baselines and CI config
## Done when
- `npm test` passes, with a new test that fails on the old code
- `npm run lint` and `npx tsc --noEmit` pass
- No skipped or deleted tests
## Report
- What changed and why (3–5 lines)
- Anything you were unsure about or didn't do
- Commands you ran to verify"Done when" is the most important section. Without it the agent decides when it's finished, and it usually decides early. "A new test that fails on the old code" stops the common trick of a test that passes either way.
"What to report" saves your review time: you read the agent's account of its uncertainty before you read the diff.
4. Guardrails inside the agent
There are three layers inside Claude Code, each for a different job.
CLAUDE.md: project rules
CLAUDE.md at the repo root is loaded into every session, so it holds the rules every agent should follow: how to run tests, code style, "never edit generated files", "migrations go through a person". It's guidance the model reads and usually follows. It is not enforcement. Anything that must never happen also needs a hook or a rule.
Permission modes and rules
Claude Code's permission mode sets the baseline for what runs without asking (values for permissions.defaultMode and --permission-mode, checked 2026-11-25):
| Mode | What it does | Fleet use |
|---|---|---|
default | Asks before most edits, shell commands and network access | Interactive work you're watching |
acceptEdits | Also auto-approves file edits and common file commands in the working directories | An agent in its own worktree doing routine edits |
plan | Researches and proposes; doesn't edit until you approve the plan | Scoping a risky task before briefing |
auto | Runs without routine prompts; a classifier reviews actions and blocks risky ones | Longer unattended runs, where enabled |
dontAsk | Auto-denies anything that would prompt; only pre-approved tools run | Locked-down CI and scripts |
bypassPermissions | Skips prompts and safety checks | Only inside isolated containers or VMs |
Two details catch people out. A project .claude/settings.json ignores auto and bypassPermissions as defaultMode (so a repo can't silently grant itself that power), and --dangerously-skip-permissions is the same as bypassPermissions.
Rules sit on top of the mode, under permissions.allow, ask and deny. They're evaluated deny first, then ask, then allow, and deny rules block in every mode, even bypassPermissions (where allow rules have no effect).
{
"permissions": {
"allow": ["Bash(npm test)", "Bash(npm run lint)", "Bash(npx tsc --noEmit)"],
"ask": ["Bash(npm install *)"],
"deny": ["Bash(git push *)", "Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)"]
}
}Bash(git push *) also matches a bare git push. Read(./.env) uses gitignore-style path patterns relative to the settings' project.
One honest limit, stated in the docs: a Bash rule matches the command text Claude writes, so a deny rule stops the usual form of a command, not every way of running that program. Rules and hooks are guardrails. The real boundary is credentials: if the agent's environment has no token that can push to main or reach the production database, no clever command can.
Hooks: code that runs on every tool call
Hooks are your own scripts that Claude Code runs at fixed points. For a fleet the important one is PreToolUse, which runs before a tool call and can block it. Hooks are configured in .claude/settings.json by event, then matcher, then handlers:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-dangerous.sh" }]
},
{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/scope-guard.sh" }]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/format.sh" }]
}
]
}
}A matcher like Bash or Edit|Write is an exact name or a |-separated list; anything with other characters is treated as a regular expression. A handler can also have an if field with permission-rule syntax (for example "if": "Bash(rm *)") to narrow it further.
The hook gets JSON on stdin, including session_id, cwd, permission_mode, hook_event_name, tool_name, tool_input and tool_use_id. For Bash, tool_input.command is the command; for Edit and Write, tool_input.file_path is the file.
How a PreToolUse hook blocks:
Exit code 2 blocks the call. Whatever the script writes to stderr is shown to Claude as the reason, so write a reason that tells it what to do instead.
Any other non-zero exit code (like 1) is a non-blocking error. The tool call goes ahead. This is the most common hook bug: a policy script that "fails" with exit 1 and enforces nothing.
Or exit 0 and print JSON with
hookSpecificOutput.permissionDecisionset to"deny"(other values:"allow","ask","defer") and apermissionDecisionReason. If a hook exits 2, the call stays blocked even if JSON says allow.
The free kit's block-dangerous.sh:
#!/usr/bin/env bash
# PreToolUse hook (matcher: Bash). Exit 2 = block; stderr is shown to Claude.
cmd=$(jq -r '.tool_input.command // ""') || {
echo "block-dangerous: could not read the tool input, blocking to be safe" >&2
exit 2 # fail closed, not open
}
deny='(^|[;&|[:space:]])(git[[:space:]]+push|git[[:space:]]+reset[[:space:]]+--hard|rm[[:space:]]+-rf|curl[^|]*\|[[:space:]]*(ba)?sh)'
if printf '%s' "$cmd" | grep -Eiq "$deny"; then
echo "Blocked: '$cmd' isn't allowed for fleet agents. Don't retry it; note it in your report and continue." >&2
exit 2
fi
exit 0Why no set -e here: with set -e, a jq failure on unexpected input would end the script with jq's own exit code (not 2), which is a non-blocking error, so the hook would fail open. Handling the error explicitly and exiting 2 makes it fail closed.
The scope guard keeps edits inside the brief. new-worktree.sh writes the brief's "files in scope" list to .agent-scope, one path prefix per line:
#!/usr/bin/env bash
# PreToolUse hook (matcher: Edit|Write). Allow edits only under paths in .agent-scope.
file=$(jq -r '.tool_input.file_path // empty') || { echo "scope-guard: bad input" >&2; exit 2; }
root="${CLAUDE_PROJECT_DIR:?}"
[ -n "$file" ] || { echo "scope-guard: no file_path" >&2; exit 2; }
case "$file" in *..*) echo "scope-guard: relative path segments aren't allowed" >&2; exit 2 ;; esac
rel="${file#"$root"/}"
case "$rel" in
.env|.env.*|*/.env|.agent-scope|test-baseline.json|.github/*|.claude/*)
echo "scope-guard: $rel is protected; ask a person if it must change" >&2; exit 2 ;;
esac
while IFS= read -r allowed; do
[ -n "$allowed" ] || continue
case "$rel" in "$allowed"*) exit 0 ;; esac
done < "$root/.agent-scope"
echo "scope-guard: $rel is outside this brief. Stay in scope, or report that it needs changing." >&2
exit 2Note what it protects besides the brief: the scope file itself, the test baseline, CI config and the hooks folder. An agent that can edit its own guardrails doesn't have guardrails.
A gap hooks don't cover: when a person types @.env in a prompt, Claude Code includes the file without making a tool call, so PreToolUse hooks don't run. To protect a path from reads, use a Read deny rule (as in the settings above), which those references respect.
format.sh (PostToolUse) runs the formatter on the edited file. PostToolUse runs after the tool, so it can't prevent anything; it's for tidying and feedback, not policy.
5. Gates on the branch
Hooks guard each action as it happens. Gates check the finished branch, in CI, where the agent can't touch them. Every agent branch runs the same workflow:
# .github/workflows/agent-gates.yml
name: agent-gates
on:
pull_request:
branches: [main]
jobs:
gates:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- uses: actions/setup-node@v4
with: { node-version: 22 }
- run: npm ci
- run: npm run lint
- run: npx tsc --noEmit
- run: npx jest --json --outputFile=test-results.json
- run: npx tsx scripts/test-count-guard.ts test-results.json
- run: "! git diff origin/main...HEAD -- '*.ts' | grep -E '^\\+.*\\b(it|test|describe)\\.(skip|only)\\('"
- run: npm audit --audit-level=high
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}The two "anti-cheating" gates are what make a fleet safe:
// scripts/test-count-guard.ts: compare with MAIN's baseline, never the branch's copy
import { execSync } from "node:child_process";
import { readFileSync } from "node:fs";
const now = JSON.parse(readFileSync(process.argv[2], "utf8"));
const base = JSON.parse(execSync("git show origin/main:test-baseline.json", { encoding: "utf8" }));
const problems: string[] = [];
if (now.numTotalTests < base.numTotalTests)
problems.push(`test count dropped: ${base.numTotalTests} -> ${now.numTotalTests}`);
if (now.numPendingTests > base.numPendingTests)
problems.push(`skipped tests rose: ${base.numPendingTests} -> ${now.numPendingTests}`);
if (problems.length) {
console.error(problems.join("\n"));
process.exit(1);
}numTotalTests and numPendingTests (skipped) come from Jest's JSON output. The baseline is read with git show origin/main:…, so an agent that edits test-baseline.json on its branch changes nothing. A person updates the baseline on main when tests are deliberately removed.
Worked example: the .skip
The pagination agent can't get one test to pass. It changes it("returns page 2", …) to it.skip(…), runs the suite, sees green and reports "done, all tests pass". Two gates fail: the skipped count went from 0 to 1, and the diff grep finds + it.skip(. The PR is blocked and the agent's report ("all tests pass") is exposed as misleading. The fix is a better brief, not a cleverer agent: "Done when: the existing page-2 test passes; if you think the test is wrong, stop and report why."
Worked example: out of scope
The rate-limit agent decides the header logic belongs in src/auth/session.ts. The scope guard blocks the edit with "outside this brief", and the agent reports that the brief may be wrong. That's the outcome you want: a question for the coordinator, not a silent edit to auth code.
6. Review: fresh eyes, then a person
Gates check what code can check. Correctness, design and security need review, and the author is the worst reviewer of its own work: an agent asked "double-check your change" in the same session mostly re-reads its own reasoning.
A separate reviewer agent with fresh context. It gets the brief, the diff and a reviewer prompt, nothing else. It can run headless in CI:
git diff origin/main...HEAD | claude -p "$(cat review/reviewer-prompt.md)" > review.md. The prompt asks for correctness, security issues, changes outside the brief, and missing tests, each with a file and line.Check the findings. Reviewer agents also produce confident wrong findings. Each finding is verified (does the bug actually reproduce?) before anyone acts on it.
A person reads the diff and decides. The reviewer's report and the author's own "what I'm unsure about" section make this fast, but the decision stays human.
Agents never merge. Enforce it with your Git host's branch protection: main requires passing checks and an approving human review, and the agents' credentials can't push to main or approve PRs at all.
Merge one at a time
Three green PRs are only green against the main they started from. Merge one, then the others rebase on the new main and re-run their gates. When a rebase conflicts, the conflict goes back to the owning agent (with its brief), not to the coordinator, which doesn't know that branch's intent. A small merge-one.sh that a person runs (merge the chosen PR, then tell the other worktrees to rebase) keeps this boring.
7. Running it day to day
One coordinator session. It splits work, writes the briefs, starts worktrees and reads the reports. It doesn't write feature code itself.
A shared notes folder outside the repo for hand-overs between sessions: findings, decisions, "file X is being changed by agent Y". Treat what another session wrote there as information to check, not as instructions.
Budgets. Each agent gets a turn limit and a spend limit. Track time and cost per task; a task that costs three times the others is telling you something about the brief.
Stuck? Restart, don't nudge. After a long struggle an agent's context is full of failed attempts, and more hints rarely help. Stop it, rewrite the brief with what you learned (the flaky test, the real file, a narrower done criterion), and start fresh.
Subagents for research. "Find everywhere we build pagination cursors" is a read-only task that a subagent can do in its own context and report back, keeping the main agent's context clean.
On a multi-tenant SaaS platform I build, this is the normal shape of a week: a coordinator session, three to five agents in worktrees on narrow briefs, a hook kit like the one above, the same gate workflow on every branch, a reviewer pass, and one person merging. The controls cost a day to set up once and save that day every week.
Trade-offs
Fleet size vs review capacity. Throughput is limited by how many diffs a person can read well. Five agents producing five PRs a day you can't review properly is worse than two you can.
Narrow vs broad briefs. Narrow briefs mean more scope-guard blocks and more coordinator work, but smaller, reviewable diffs. Broad briefs feel faster and produce diffs nobody can review.
Hooks vs gates. Hooks stop dangerous actions as they happen, but they run in the agent's environment and see one call at a time. Gates see the whole branch and can't be edited by the agent, but they catch problems late. Use both.
Permission mode. More autonomy (
acceptEdits,auto) means fewer interruptions and more reliance on hooks, gates and credentials.bypassPermissionsbelongs only in a disposable, isolated environment.Reviewer agent vs human-only review. The reviewer agent is fast and catches mechanical issues; it also adds false findings to check. It speeds up the person; it doesn't replace them.
Common mistakes
Several agents in one checkout, or tasks split by feature name with heavy file overlap.
Briefs with no "done when" and no "out of scope".
Treating
CLAUDE.mdas enforcement.A policy hook that exits 1 (non-blocking) instead of 2, or one that fails open when its own parsing fails.
Hooks and baselines the agent can edit.
Relying on hooks alone to protect
.env, forgetting that@file references don't make tool calls; addReaddeny rules.Agents holding credentials that can push to
mainor reach production.Gates that only check "tests pass", so
.skipand deleted tests sail through.Comparing the test count with the branch's own baseline file.
The author agent reviewing its own work, or an agent merging.
Merging several green PRs at once without rebasing and re-running gates.
Nudging a stuck agent for an hour instead of restarting it with a better brief.
Remember
One task = one worktree = one branch, and tasks don't share files.
The brief is the agent's whole world: goal, in scope, out of scope, done when, what to report.
CLAUDE.mdguides; hooks and deny rules enforce; credentials are the real boundary.A PreToolUse hook blocks with exit 2. Exit 1 lets the call through. Fail closed.
Gates check what cheating looks like: no fewer tests, no new skips, no secrets, measured against main.
Fresh-context reviewer, then a person decides. Agents never merge. Merge one at a time.
Budget every agent; restart a stuck one with a better brief.
Check before relying on it
Permission modes (
default,acceptEdits,plan,auto,dontAsk,bypassPermissions), the rule that project settings ignoreautoandbypassPermissionsasdefaultMode, and "deny always blocks, even inbypassPermissions" are from the Claude Code docs on 2026-11-25. Whetherautois available depends on your plan and setup.Hook behaviour (exit 2 blocks with stderr as the reason, other non-zero codes don't block, the
permissionDecisionJSON, theiffield and matcher syntax) is from the hooks reference on 2026-11-25. The hook event list is long and grows; check it for new events.CLAUDE_PROJECT_DIRinside a worktree session: I expect it to point at the worktree, not the main checkout, but haven't confirmed it. Check before a scope guard depends on it.claude --worktree <name>: checked in the common-workflows docs on 2026-11-25; where it places worktrees and how cleanup works is on the Worktrees page.gitleaks/gitleaks-action@v2may need a licence key for organisation repositories; check its README, or run thegitleaksCLI instead.The hook scripts,
test-count-guard.tsand the workflow are our course code (the free M7 kit), not Anthropic features. The deny regex inblock-dangerous.shis a guardrail, not a complete list.