Skip to content

$ cat index.mdx$ cat ~/blogs/engineering/claude-code-orchestrator-verify-worker-agents/index.mdx # I put my name on this

Claude Code Orchestrator: Verify Every Worker's Claim

I wrote this. You can take notes.

To run Claude Code as an orchestrator with worker agents, give each worker one task, one git worktree and a JSON report it must fill in. Then treat every report as a claim, not a result: re-run the worker's test command yourself, compare its diff to the files it was allowed to touch, and run the full suite on the merged branches before anything ships. This guide builds that loop in three small scripts and a Stop hook, and shows the real output from running it.

My own orchestrator once told me it had posted five status comments on GitHub. It had posted none. The command had a flag that does not exist, and 2>/dev/null swallowed the error, so the agent saw silence and reported success.

In the same week, a cross-check of 25 pull requests my workers had marked done found "CI green" in reports while CI shards were red. A report describes what one worker saw, not what is true. The orchestrator's job is to check the whole thing before it repeats the claim. Why a worker's "done" proves so little on its own, and what it takes to make it count, is in self-signed done: why your AI agent's "done" proves nothing.

What you will build

orchestrate.sh dispatches two headless workers, verify.sh checks each claim, an integration run tests the merged result, and a Stop hook stops a worker from finishing while tests fail. Everything below ran on 2026-11-23 with Claude Code 2.1.330, Node 24.22.3 and git 2.43.0 on Ubuntu. The two workers cost $0.49 together and ran in parallel, about 10 seconds each.

Prerequisites

  • Claude Code 2.1.302 or newer, logged in. From that version, a -p run starts in Manual mode and denies any tool call that needs approval, so the flags in step 3 matter.
  • Node 18 or newer (for the built-in node --test runner).
  • git and jq.
  • About $1 of usage for the full walkthrough.

If you have not run several agents side by side before, start with how I run multiple Claude Code agents at once.

Step 1: Create a project with two independent bugs

Make a folder called invoice-kit with this layout:

invoice-kit/
  package.json
  src/money.js     formatCents(): cents to "$1,234.50"
  src/slug.js      slugify(): title to "q3-acme-corp"
  src/invoice.js   summarize(): uses both
  test/money.test.js
  test/slug.test.js
  test/invoice.test.js

src/money.js mangles refunds: -150 cents comes out as $-2.-50:

// Format an integer number of cents as US dollars, e.g. 123450 -> "$1,234.50".
export function formatCents(cents) {
  const dollars = Math.floor(cents / 100);
  const rest = String(cents % 100).padStart(2, "0");
  const grouped = String(dollars).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return `$${grouped}.${rest}`;
}

src/slug.js turns every punctuation character into its own dash and never trims the ends:

// Turn an invoice title into a URL slug, e.g. "Q3 -- Acme Corp" -> "q3-acme-corp".
export function slugify(title) {
  return title.toLowerCase().trim().replace(/[^a-z0-9]/g, "-");
}

src/invoice.js uses both:

import { formatCents } from "./money.js";
import { slugify } from "./slug.js";
 
export function summarize(invoice) {
  const total = invoice.lines.reduce((sum, l) => sum + l.cents, 0);
  return { id: slugify(invoice.title), total: formatCents(total) };
}

The tests pin the behavior you want:

// test/money.test.js
import { test } from "node:test";
import assert from "node:assert/strict";
import { formatCents } from "../src/money.js";
 
test("formats whole and fractional dollars", () => {
  assert.equal(formatCents(150), "$1.50");
  assert.equal(formatCents(5), "$0.05");
});
test("formats refunds (negative amounts)", () => {
  assert.equal(formatCents(-150), "-$1.50");
});
// test/slug.test.js
import { test } from "node:test";
import assert from "node:assert/strict";
import { slugify } from "../src/slug.js";
 
test("lowercases and joins words", () => {
  assert.equal(slugify("Acme Corp"), "acme-corp");
});
test("collapses punctuation runs and trims dashes", () => {
  assert.equal(slugify("  Q3 -- Acme Corp! "), "q3-acme-corp");
});
// test/invoice.test.js
import { test } from "node:test";
import assert from "node:assert/strict";
import { summarize } from "../src/invoice.js";
 
test("summarizes a large invoice with a refund line", () => {
  const s = summarize({ title: "Q3 -- Acme Corp", lines: [{ cents: 123500 }, { cents: -50 }] });
  assert.deepEqual(s, { id: "q3-acme-corp", total: "$1,234.50" });
});

Add { "name": "invoice-kit", "type": "module", "scripts": { "test": "node --test" } } as package.json, then commit it on main:

git init -b main && git add -A && git commit -m "invoice-kit: initial"
node --test

Check: the run ends with three failures.

ℹ tests 5
ℹ pass 2
ℹ fail 3
✖ summarizes a large invoice with a refund line
✖ formats refunds (negative amounts)
✖ collapses punctuation runs and trims dashes

Step 2: Write the report contract before the brief

A free-text "done, all tests pass" cannot be checked. A report with named fields can. Decide the fields first, then write the brief around them:

{
  "type": "object",
  "properties": {
    "status":        { "enum": ["done", "blocked"] },
    "files_changed": { "type": "array", "items": { "type": "string" } },
    "test_command":  { "type": "string" },
    "tests_passed":  { "type": "boolean" },
    "summary":       { "type": "string" }
  },
  "required": ["status", "files_changed", "test_command", "tests_passed", "summary"]
}

Each field maps to a check the orchestrator runs itself:

FieldThe orchestrator checks
files_changedgit diff --name-only main in the worker's worktree
test_commandruns that exact command again, itself
tests_passedcompares its own exit code to this value
status"done" with an empty diff is an automatic reject

Claude Code enforces the shape for you. Pass the schema with --json-schema and the validated object comes back in a structured_output field of the JSON result. If the run produces nothing valid, the field is missing and the verifier fails it.

Step 3: Dispatch the workers in their own worktrees

Save this as orchestrate.sh next to the invoice-kit folder:

#!/usr/bin/env bash
# Dispatch one headless Claude Code worker per task, each in its own git worktree.
set -euo pipefail
REPO="$1"; cd "$REPO"
 
SCHEMA='{"type":"object","properties":{
  "status":{"enum":["done","blocked"]},
  "files_changed":{"type":"array","items":{"type":"string"}},
  "test_command":{"type":"string"},
  "tests_passed":{"type":"boolean"},
  "summary":{"type":"string"}},
  "required":["status","files_changed","test_command","tests_passed","summary"]}'
 
dispatch() {  # name, allowed file, test file, task
  local name=$1 file=$2 test=$3 task=$4
  git worktree add -q "../wt-$name" -b "fix/$name"
  ( cd "../wt-$name" && claude -p "$task
Rules: edit only $file. Do not edit tests. When finished, run: node --test $test
Report what you changed and whether that command passed." \
      --model sonnet \
      --permission-mode acceptEdits \
      --allowedTools "Read" "Edit" "Bash(node --test:*)" \
      --max-budget-usd 1 \
      --output-format json --json-schema "$SCHEMA" \
      > "../report-$name.json" ) &
}
 
dispatch money src/money.js test/money.test.js \
  "Fix formatCents in src/money.js so refunds format as -\$1.50, not \$-1.50."
dispatch slug src/slug.js test/slug.test.js \
  "Fix slugify in src/slug.js so runs of punctuation become one dash and leading/trailing dashes are trimmed."
wait
echo "workers finished"

What each flag is doing:

  • git worktree add gives each worker its own checkout and branch, so two agents never edit the same files on disk.
  • --permission-mode acceptEdits lets the worker edit files without a prompt nobody is there to answer.
  • --allowedTools lets the worker read, edit and run node --test, and nothing else.
  • --max-budget-usd 1 caps what a confused worker can spend.
  • The brief names the one file the worker may edit; step 4 enforces it.

Run it:

chmod +x orchestrate.sh
./orchestrate.sh invoice-kit
jq -c '{num_turns, total_cost_usd, out: .structured_output | {status, files_changed, tests_passed}}' report-*.json

Check: two reports, both claiming success. From my run:

{"num_turns":5,"total_cost_usd":0.2434829,"out":{"status":"done","files_changed":["src/money.js"],"tests_passed":true}}
{"num_turns":6,"total_cost_usd":0.2440124,"out":{"status":"done","files_changed":["src/slug.js"],"tests_passed":true}}

Both say done. Neither of those lines is evidence yet.

Step 4: Verify each claim against fresh evidence

Save this as verify.sh:

#!/usr/bin/env bash
# Check one worker's claim against fresh evidence. Exit non-zero on any mismatch.
set -uo pipefail
WT="$1"; REPORT="$2"; ALLOWED="$3"
claim() { jq -r ".structured_output.$1" "$REPORT"; }
fail=0
 
echo "== $WT"
echo "claimed: status=$(claim status) tests_passed=$(claim tests_passed) files=$(jq -c .structured_output.files_changed "$REPORT")"
 
changed=$(git -C "$WT" diff --name-only main)
echo "actual diff vs main: ${changed:-<none>}"
[ -n "$changed" ] || { echo "FAIL: worker claims done but changed nothing"; fail=1; }
for f in $changed; do
  [ "$f" = "$ALLOWED" ] || { echo "FAIL: edited $f outside its scope ($ALLOWED)"; fail=1; }
done
 
cmd=$(claim test_command)
if ( cd "$WT" && eval "$cmd" ) >/dev/null 2>&1; then rerun=true; else rerun=false; fi
echo "re-ran '$cmd' myself: passed=$rerun"
[ "$rerun" = "$(claim tests_passed)" ] || { echo "FAIL: claimed tests_passed=$(claim tests_passed), re-run says $rerun"; fail=1; }
 
[ $fail -eq 0 ] && echo "VERIFIED" || echo "REJECTED"
exit $fail

It asks three questions, and none of them goes to the worker:

  1. Did anything change at all?
  2. Did the change stay inside the file the worker was given?
  3. Does the test command pass when I run it, right now?

Run it on both workers:

chmod +x verify.sh
./verify.sh wt-money report-money.json src/money.js
./verify.sh wt-slug  report-slug.json  src/slug.js

Check: both come back verified.

== wt-money
claimed: status=done tests_passed=true files=["src/money.js"]
actual diff vs main: src/money.js
re-ran 'node --test test/money.test.js' myself: passed=true
VERIFIED
== wt-slug
claimed: status=done tests_passed=true files=["src/slug.js"]
actual diff vs main: src/slug.js
re-ran 'node --test test/slug.test.js' myself: passed=true
VERIFIED

Both workers were honest, which proves nothing about the gate. A check you have never seen fail is a check you have not tested. So I staged a fake worker: an untouched worktree with a report that claims the refund fix is done.

git -C invoice-kit worktree add ../wt-liar -b fix/liar
jq '.structured_output = {status:"done",files_changed:["src/money.js"],test_command:"node --test test/money.test.js",tests_passed:true,summary:"Fixed refunds."}' \
  report-money.json > report-liar.json
./verify.sh wt-liar report-liar.json src/money.js; echo "exit=$?"
== wt-liar
claimed: status=done tests_passed=true files=["src/money.js"]
actual diff vs main: <none>
FAIL: worker claims done but changed nothing
re-ran 'node --test test/money.test.js' myself: passed=false
FAIL: claimed tests_passed=true, re-run says false
REJECTED
exit=1

A check that prints FAIL and then lets the next command run anyway is decoration. One of my scans once found exactly what it was looking for, but it was chained with && to an unrelated test, and the post went out anyway. Wire verify.sh so its exit code stops the pipeline.

Step 5: Run the full suite on the merged result

Each worker ran only its own test file, so no worker has seen the whole suite.

Commit each worktree and run the full suite on each branch alone first (output condensed):

for n in money slug; do (cd wt-$n && git commit -qam "fix: $n" && node --test); done
fix/money alone:  pass 3, fail 2   (slug test, invoice test)
fix/slug alone:   pass 4, fail 1   (refund test)

I expected the invoice test to need both fixes. It only needed the slug fix: its two lines add up to a positive $1,234.50, so the refund bug never touches it. My mental model of the code was wrong, and only the run showed it.

Now merge both branches and run everything:

cd invoice-kit
git checkout -b integration main
git merge --no-edit fix/money fix/slug
node --test
ℹ tests 5
ℹ pass 5
ℹ fail 0

Only this result means "done". My orchestrator once merged two branches with no conflicts and still produced a compile-time fatal error in PHP, because one side added a bare return; inside a closure the other side had typed to return an array. "No conflicts" only says the text combined.

Step 6: Add a Stop hook the worker cannot talk past

The verifier runs after the worker exits. A hook runs before it is allowed to exit. Claude Code fires a Stop hook when the agent tries to finish, and a hook that exits with code 2 blocks the stop and feeds its stderr back to the agent as the reason.

Save this as .claude/hooks/require-tests.sh inside the worktree:

#!/usr/bin/env bash
# Stop hook: refuse to let the agent finish while the test suite fails.
input=$(cat)
# Already continuing because of this hook? Let it stop, or it can loop.
[ "$(echo "$input" | jq -r .stop_hook_active)" = "true" ] && exit 0
if ! out=$(node --test 2>&1); then
  echo "Tests are failing. Fix them before you stop:" >&2
  echo "$out" | grep -E "^✖|ℹ (pass|fail)" | sort -u >&2
  exit 2
fi
exit 0

Make it executable with chmod +x .claude/hooks/require-tests.sh. A hook that cannot run is a non-blocking error, so the gate would silently do nothing.

Then register it in .claude/settings.json:

{
  "hooks": {
    "Stop": [
      { "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/require-tests.sh" } ] }
    ]
  }
}

Headless -p runs load project hooks unless you pass --bare, so the same worker command from step 3 picks this up.

I ran the money worker again in a fresh worktree with this hook installed, using --output-format stream-json --verbose --include-hook-events to see the hook fire. Here is the Stop event that blocked it (test timings trimmed):

{"hook_event":"Stop","exit_code":2,"outcome":"error",
 "stderr":"Tests are failing. Fix them before you stop:\n✖ collapses punctuation runs and trims dashes\n✖ failing tests:\nℹ fail 2\nℹ pass 3\n✖ summarizes a large invoice with a refund line\n"}

The hook runs the whole suite and the slug bug was still on main, so the worker could not pass without breaking its brief. It kept its edit inside src/money.js and ended with this report instead of "done":

I haven't fixed the two failing tests. The stop hook runs the whole suite with `node --test`.
The two failures are in `src/slug.js`, and you told me to edit only `src/money.js`, so I left that file alone.

It then named the cause and proposed the exact one-line slug fix. That run cost $0.23.

Two lessons from that run:

  • Match the hook to the brief. A full-suite hook on a scoped worker forces a choice between breaking scope and failing the gate. Give a worker a hook that runs its own tests, and keep the full suite for the integration step.
  • The loop guard means the hook blocks only once. Without the stop_hook_active check, a worker that cannot pass loops until Claude Code's cap of 8 consecutive continuations. With it, the hook blocks once, so it improves the report and verify.sh still makes the call.

The checks that catch each failure

Failure modes from my own worker runs on real pull requests, plus two this demo staged on purpose:

What the worker reportsWhat actually happenedThe check that catches it
"Posted the comments"The command failed and stderr was discardedHold the URL of what was created, never the exit silence
"Tests pass" (this demo)One test file passed; the suite was never runRe-run the full suite on the merged branch
"CI green"Some CI shards were redRead the CI status yourself, every shard
"Done" on unit tests aloneCore behavior was never run for realRequire proof from a real run in the brief, and reject without it
"Merged cleanly"The merged code does not compileBuild and test after the merge, not before
"Done" (this demo's fake worker)Nothing changedEmpty diff equals automatic reject

In every row, the worker reported the slice it saw. Only the orchestrator sees all the slices, so only it can check them.

Scaling this past two workers

The same contract works with Claude Code's built-in tools:

  • Subagents. Define a worker in .claude/agents/<name>.md with isolation: worktree, a tools list and maxTurns. Each subagent starts with a fresh context and only its final summary returns to the main agent, and that summary is a claim to verify. Up to 20 run at once by default.
  • Agent teams. Still experimental and off by default (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1). The docs warn that teammates sometimes fail to mark tasks complete and the lead can decide the team is finished early. A TaskCompleted hook that exits 2 blocks a task from being marked done: the team-level version of step 6.
  • Long-lived workers. For work that runs for hours, I keep workers in herdr panes and send each one a written brief file. The rule stays the same: never repeat a claim you have not checked.

Pick the model by the job. The rule that held up in my runs: Opus for security fixes and changes that touch several entry points, Sonnet for medium work, and Haiku only for small, contained tasks, with no more than 8 workers at once.

Worktrees made with git worktree add are never removed for you, so clean up:

git -C invoice-kit worktree remove --force ../wt-money
git -C invoice-kit worktree remove --force ../wt-slug
git -C invoice-kit worktree remove --force ../wt-liar

Where to go next

Start with the contract in step 2 on your next multi-agent task, even if you skip everything else. Once a worker has to name its test command and its files, you can check both in seconds, and "done" becomes something you can test.

$ ls ~/read/related

my other essays