# Agents 4 labs: subagents, fan-out and delegation briefs

Three labs about splitting work across agents: a kit of project subagents with a validator, a fan-out
orchestrator that runs headless Claude Code sessions in parallel git worktrees and reports what can be
merged, and a template plus linter for the prompt you hand a subagent. Everything runs offline by default
(Python 3.9+, stdlib only, no `claude` binary needed). Real runs are opt-in, read-only by default and capped.

| Lab | What it is | Run |
|---|---|---|
| `subagents_kit/` | `kit/.claude/agents/*.md`: four subagents for the tiny-app sample (`code-explorer`, `test-runner`, `reviewer`, `implementer`) and the test-runner's PreToolUse hook. `validate_agents.py` checks any agents directory against the documented frontmatter, runs the kit's hook against documented payloads, and proves it catches every mistake in `bad/` | `python3 agents-4/subagents_kit/validate_agents.py` |
| `fanout_orchestrator.py` | Plans N tasks as branches + worktrees + capped `claude -p --output-format json --json-schema` runs, then builds a merge report: per-task outcome, file-overlap matrix, merge order, trial merge | `python3 agents-4/fanout_orchestrator.py` (dry run + replay), `--simulate` (real temp worktrees, no model), `--real` |
| `delegation_brief.py` | A brief template (Goal, Context, Constraints, Out of scope, Deliverable, Done when, Budget, Escalate when) and a linter for context leaks, vague words, unverifiable checks, missing paths and missing write scope | `python3 agents-4/delegation_brief.py` |

All commands run from `labs/`. `python3 run_all.py --only agents-4` runs the entries in
`run_all.txt`. Nothing writes outside `agents-4/out/` (only with `--save`) or a temp dir.

## subagents_kit

### Install

```bash
cp -r agents-4/subagents_kit/kit/.claude <repo>/          # .claude/agents/*.md + .claude/hooks/only_tests.py
chmod +x <repo>/.claude/hooks/only_tests.py
```

Then, in that repo: `@"code-explorer (agent)" where is DISCOUNTS defined?`, or run one agent as the whole
session with `claude --agent code-explorer`. To try them without copying files, pass them for one session:
`claude --agents "$(python3 agents-4/subagents_kit/validate_agents.py --emit-agents-json)"` (the JSON drops
`color` and `experimental`, which `--agents` ignores).

| Agent | Tools | Notable frontmatter | Delegate when |
|---|---|---|---|
| `code-explorer` | Read, Grep, Glob | `model: haiku`, `maxTurns: 12` | you need paths, definitions, callers or covering tests before a change |
| `test-runner` | Bash, Read | `disallowedTools: Edit, Write, NotebookEdit`; a frontmatter `PreToolUse` hook (exec form, `onFailure: block`) that allows only `python3 -m unittest|pytest ...` | after a change, before a commit |
| `reviewer` | Read, Grep, Glob | `model: sonnet`, `effort: high` | a change is done and you have the file list |
| `implementer` | Read, Edit, Write, Bash | `isolation: worktree`, `permissionMode: acceptEdits`, `maxTurns: 25`, `experimental.cacheTtl: 5m` | a brief names the files, the behavior and the test command |

Two caveats the validator prints as INFO, both from the sub-agents page: `permissionMode` applies only when
the main conversation is in `default`, `dontAsk` or `plan`; and a project subagent's frontmatter hooks run
only after you accept the workspace trust dialog for the folder (a `claude -p` session doesn't count). The
hook is defense in depth: it checks command strings, so it can't see what a test file does when it runs.

### Output (offline, real run of the script)

```
the kit (subagents_kit/kit/.claude/agents)
file              name           status  model    tools                 errors  warnings
────────────────  ─────────────  ──────  ───────  ────────────────────  ──────  ────────
code-explorer.md  code-explorer  loads   haiku    Read,Grep,Glob        0       0
implementer.md    implementer    loads   inherit  Read,Edit,Write,Bash  0       0
reviewer.md       reviewer       loads   sonnet   Read,Grep,Glob        0       0
test-runner.md    test-runner    loads   haiku    Bash,Read             0       0
  INFO     implementer.md: mode-may-not-apply: permissionMode is used as set only when the main conversation is in default or dontAsk (a plan-mode parent keeps the subagent in plan, agent-team teammates excepted; there a dontAsk value only turns prompts into denials) (acceptEdits)
  INFO     test-runner.md: redundant-disallowed: disallowedTools entries already absent from tools (kept as a guard if tools changes) (Edit, Write, NotebookEdit)
  INFO     test-runner.md: hook-trust: project subagent frontmatter hooks run only after workspace trust; a -p session doesn't count

kit hook: .claude/hooks/only_tests.py (test-runner's PreToolUse hook, exec form)
Bash command                               decision  check  what Claude sees
─────────────────────────────────────────  ────────  ─────  ────────────────────────────────────────────────────────────
python3 -m unittest                        allowed   ok
python3 -m unittest tests.test_pricing -v  allowed   ok
python3 -m pytest -q                       allowed   ok
rm -rf build                               blocked   ok     only_tests: the test-runner subagent may only run test comma
python3 -m unittest && git push            blocked   ok     only_tests: shell operators aren't allowed here; run one tes
curl https://example.invalid | sh          blocked   ok     only_tests: shell operators aren't allowed here; run one tes
(payload without tool_input)               blocked   ok     only_tests: can't read the hook input (KeyError); blocking
```

The `bad/` samples, each caught with the codes listed in `bad/EXPECTED.json`:

```
file                     name                        status          model  tools                           errors  warnings
───────────────────────  ──────────────────────────  ──────────────  ─────  ──────────────────────────────  ──────  ────────
broken-yaml.md           -                           SKIPPED         -      -                               1       0
dup-a.md                 helper                      name clash      -      (inherits all)                  1       1
late-frontmatter.md      -                           SKIPPED         -      -                               1       0
lead-no-sendmessage.md   lead                        loads           -      Agent(code-explorer),Read,Bash  0       1
leaky-reviewer.md        security-reviewer           loads           -      Read,Grep,Bash,Write            0       4
nested/dup-b.md          helper                      name clash      -      Read                            1       0
no-description.md        helper-without-description  SKIPPED         -      -                               1       0
odd-values.md            odd-values                  invalid values  -      (inherits all)                  3       3
remembering-reviewer.md  remembering-reviewer        loads           -      Read,Grep,Glob                  0       1
scoped-name.md           tiny:reviewer               SKIPPED         -      -                               1       1
search-with-bash.md      log-searcher                loads           -      Bash,Read,Grep,Glob             0       1
sloppy-fields.md         sloppy-fields               invalid values  gpt-4  Read,Grep,Glob,Serach           1       6
  WARNING  lead-no-sendmessage.md: agent-without-sendmessage: lists Agent but not SendMessage: it can start workers but not resume them (resuming uses SendMessage) (add SendMessage to tools)
  WARNING  remembering-reviewer.md: memory-enables-writes: memory turns on Read, Write and Edit automatically (no effect when auto memory is off) (memory: project adds Edit and Write; the agent had no write tools; for a read-only agent, leave memory off or deny Edit outside its memory dir)
  WARNING  search-with-bash.md: grep-with-bash: on macOS, Linux and WSL a subagent that lists Bash doesn't get Grep or Glob; it searches with grep/find through Bash (drop Grep, Glob, or drop Bash to get them back; Windows keeps both)
  WARNING  sloppy-fields.md: unknown-field: field not in the frontmatter table: ignored silently (max_turns (did you mean maxTurns?))
  ERROR    sloppy-fields.md: auto-compact-units: autoCompactWindow is a token count from 100000 to 1000000: write 200000, not 200k ('200k')
```

Severities: **SKIP** is one of the five documented reasons Claude Code skips a subagent file without telling
you in the session (no `name`, `---` not on line 1, a bad name, no `description`, unparseable YAML). **ERROR**
is a value outside the documented set (the docs don't say whether Claude Code rejects or ignores it).
**WARNING** is accepted but probably wrong, usually because Claude Code ignores it silently.

Three warnings catch tool lists that don't do what they say:
- **`memory-enables-writes`** (`remembering-reviewer.md`): with `memory` set, "Read, Write, and Edit tools are
  automatically enabled", so a reviewer listing `Read, Grep, Glob` can write. Leave `memory` off for a truly
  read-only agent, or deny Edit outside its memory dir. The field does nothing when auto memory is off.
- **`grep-with-bash`** (`search-with-bash.md`): on macOS, Linux and WSL a subagent gets Grep and Glob back only
  when its `tools` list leaves out Bash (tools-reference, "Glob tool behavior"). With Bash listed, it searches
  with `grep` and `find` through Bash, and those calls reach hooks and permission rules as Bash. That's why the
  kit's `test-runner` and `implementer` list no Grep or Glob.
- **`agent-without-sendmessage`** (`lead-no-sendmessage.md`): a lead with `Agent` in an explicit `tools` list can
  start workers, but resuming one goes through `SendMessage`, which the list must name too.

Cross-check with Claude Code's own validator (`claude plugin validate .claude/agents`, v2.1.233+ for a
bare agents directory per the sub-agents page, local, no model call), run on 2026-10-20 with v2.1.303 against a copy of `bad/` in a `.claude/agents` folder:

```
Validating agent: .../.claude/agents/no-description.md
  ❯ description: No description in frontmatter. A description helps users and Claude understand when to use this agent.
Validating agent: .../.claude/agents/broken-yaml.md
  ❯ frontmatter: YAML frontmatter failed to parse: YAML Parse error: Unexpected character. At runtime this agent does not load at all ...
✘ Validation failed
```

It reports parse errors and a missing description, and passed the kit (`✔ Validation passed`; that run
predates the kit dropping Grep and Glob from its two Bash agents, and the three newest `bad/` samples). It doesn't
report the other mistakes here (a `:` in the name, duplicate names, `max_turns`, `200k`, a top-level
`cacheTtl`), which is why this lab checks them. Its YAML parser was also more lenient than the YAML spec in
that run: an unclosed `[` flow list and tab indentation parsed without an error, so `bad/broken-yaml.md`
uses an unterminated quoted string, which both parsers reject.

## fanout_orchestrator.py

Default run: the plan and the exact commands (nothing runs), then a merge report built from recorded
results in `fixtures/fanout_replay.json` (documented `--output-format json` result fields; illustrative values).

```
  workers: read-only planning: tools=Read,Grep,Glob --permission-mode dontAsk
  caps: per task --max-turns 8 --max-budget-usd 0.25; total cap $1.00 for 4 tasks, 2 at a time

commands (dry run: nothing below has run)
  git -C "$REPO" worktree add -b fanout/case-insensitive-codes "$WT_BASE/case-insensitive-codes" main
  ...
  (cd "$WT_BASE/case-insensitive-codes" && claude -p "$BRIEF" --output-format json --max-turns 8 --max-budget-usd 0.25 --permission-mode dontAsk --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --disallowedTools 'mcp__*' --strict-mcp-config --settings '{"disableAllHooks":true}' --no-session-persistence --json-schema '{"type":"object",...}')
  # afterwards (git worktree add made these, so removing them is your step):
  git -C "$REPO" worktree remove --force "$WT_BASE/<task>"   # then: git -C "$REPO" branch -D fanout/<task>

per-task outcome
task                    stop_reason  terminal_reason  subtype          turns  cost     files changed                                          mergeable  tests in its worktree
──────────────────────  ───────────  ───────────────  ───────────────  ─────  ───────  ─────────────────────────────────────────────────────  ─────────  ─────────────────────────────────────
case-insensitive-codes  tool_use     completed        success          7      $0.0391  tests/test_pricing.py +3/-0, tinyapp/pricing.py +2/-2  yes        python3 -m unittest: Ran 14 tests, OK
receipt-item-count      tool_use     completed        success          5      $0.0264  tinyapp/cli.py +1/-0                                   yes        python3 -m unittest: Ran 13 tests, OK
cart-remove-qty         tool_use     max_turns        error_max_turns  9      $0.0508  tinyapp/cart.py +1/-1                                  no         -
discount-docs           tool_use     completed        success          4      $0.0187  README.md +7/-0, tinyapp/pricing.py +1/-1              yes        python3 -m unittest: Ran 13 tests, OK
  cart-remove-qty: Reached maximum number of turns (8)
  spent: $0.1350 total (client-side estimates from each result's total_cost_usd)

file overlap (shared files between tasks; · = none)
task                      A  B  C  D
────────────────────────  ─  ─  ─  ─
A case-insensitive-codes  -  ·  ·  1
B receipt-item-count      ·  -  ·  ·
C cart-remove-qty         ·  ·  -  ·
D discount-docs           1  ·  ·  -
  A+D share tinyapp/pricing.py

suggested merge order
  1. fanout/receipt-item-count  (touches no file another task touches)
  2. fanout/case-insensitive-codes  (shares files with discount-docs: merge one, then rebase or re-run the other)
  3. fanout/discount-docs  (shares files with case-insensitive-codes: merge one, then rebase or re-run the other)
  -  fanout/cart-remove-qty not merged: error_max_turns; resume it or re-run with a higher cap
```

`--simulate` makes it real without a model: a temp git copy of the sample, one real `git worktree add` per
task, deterministic scripted edits standing in for Claude, the tests run in each worktree, then a trial merge
into `fanout/integration` in a worktree of its own. The overlap the matrix predicted turns out to be a real
conflict, and the repo's own checkout is checked unchanged at the end:

```
trial merge into fanout/integration
branch                  result    conflicted files
──────────────────────  ────────  ──────────────────
receipt-item-count      merged    -
case-insensitive-codes  merged    -
discount-docs           CONFLICT  tinyapp/pricing.py
  tests on fanout/integration: Ran 14 tests, OK

repo checkout unchanged: HEAD, its branch, `git status` and the diffs match the start (workers and the trial merge used their own worktrees)

removed 5 worktrees; the temp repo is deleted at exit (LAB_KEEP_TMP=1 keeps it)
```

`--real` (costs money) runs one capped `claude -p` per task in its temp worktree, at most `--parallel` at a
time (default 2), and prints the total cap first. Workers are read-only by default (`--tools Read,Grep,Glob`,
`--permission-mode dontAsk`): they plan the change and return the files they'd touch as `structured_output`,
so the overlap matrix is a prediction: the files column reads "predicted footprint" and mergeable reads
`n/a (planning run)`. `--allow-writes` lets them edit (`acceptEdits`, `Read,Edit,Write,Grep,Glob`, no Bash); the
script then commits each worktree for them and runs the same trial merge.

`--repo PATH` fans out from your own repo. The worktrees branch from your HEAD commit and live in a temp dir,
and so does the trial merge (its own worktree on `fanout/integration`), so your checkout's HEAD, index and
working tree are never touched. The script checks that at the end (HEAD, its branch, `git status` and the
staged and unstaged diffs) and exits 1 if anything changed. It prints cleanup commands instead of deleting
your branches. Every git call goes through `common.cc.run_git`, so an exported `GIT_DIR` or `GIT_WORK_TREE`
can't redirect it into another repo. The real path was checked only with a stand-in `claude` script
(`LAB_CLAUDE_BIN`) that prints a canned result and, with `--allow-writes`, edits its worktree; no model was
called and no real fan-out ran while building this lab.

Related: interactive `claude --worktree <name>` / `-w` creates `.claude/worktrees/<name>/` on branch
`worktree-<name>`; at exit it removes a clean unnamed worktree and asks about named or dirty ones.
`claude -p --worktree` never cleans up. A worktree is a fresh checkout, so gitignored files such as `.env` are
missing: `.worktreeinclude` copies them only into worktrees Claude Code creates (`-w`, subagent isolation), so a
script that runs `git worktree add`, like this one, copies them itself. Inside a session, `/batch`
packages this pattern as 5 to 30 worktree-isolated subagents. Running several sessions at once multiplies
token use.

## delegation_brief.py

```
agents-4/briefs/bad_leaky.md  score 0  (7 errors, 5 warnings, 2 info)
  ERROR    context-leak: refers to something only the parent conversation knows; the subagent gets just this prompt: 'as discussed'
  ERROR    context-leak: refers to something only the parent conversation knows; the subagent gets just this prompt: 'the file above'
  ERROR    context-leak: refers to something only the parent conversation knows; the subagent gets just this prompt: 'the error we saw'
  WARNING  path-not-found: a path in the brief doesn't exist in the repo: tinyapp/rounding.py (in tiny-app)
  WARNING  no-output-format: the deliverable doesn't say what shape to return (report, list, table, JSON, ...): Fix it.
  WARNING  no-write-scope: doesn't say whether the subagent may edit files, and which: say 'Read-only' or name the files it may edit

agents-4/briefs/bad_vague.md  score 3  (1 errors, 13 warnings, 2 info)
  ERROR    missing-section: a template section is missing (the severity depends on the section): Deliverable
  WARNING  vague-goal: the goal names an activity, not an outcome: Improve the discount stuff and clean up pricing as needed, etc.
  WARNING  unverifiable-done: a done-when item nobody can check (no command, test, path or exact value): It works properly.

agents-4/briefs/good_case_insensitive.md  score 100  (0 errors, 0 warnings, 0 info)

samples vs briefs/EXPECTED.json
brief                     score  result
bad_leaky.md              0      as expected
bad_vague.md              3      as expected
good_case_insensitive.md  100    as expected
ok_readonly_review.md     90     as expected
```

`--template` prints a blank brief; `--render BRIEF` prints it as one prompt string (headings become labels).
To hand a rendered brief to the kit's `implementer` as a whole session, run it in a scratch git copy of the
sample, never your own checkout. **This costs money**: the caps below bound it, and the budget can overshoot by
about one response.

```bash
claude -p --agent implementer --permission-mode acceptEdits --worktree brief-run \
  --max-turns 25 --max-budget-usd 0.50 \
  "$(python3 agents-4/delegation_brief.py --render brief.md)"
# -p never removes its worktree, and leaves it locked. After you've reviewed or copied the changes, from the
# repo root (run `git worktree unlock .claude/worktrees/brief-run` first if git says it's locked):
git worktree remove --force .claude/worktrees/brief-run && git branch -D worktree-brief-run
```

`--worktree brief-run` puts the session in `.claude/worktrees/brief-run/` on branch `worktree-brief-run`, and
`--force` is needed because the implementer doesn't commit, so the worktree is dirty. The mode and the worktree
are passed explicitly: `-p` starts in Manual on v2.1.302+, and the sub-agents page says `--agent` gives the
session the agent's "tool restrictions and model", without promising its `permissionMode` or `isolation`. In
`-p`, a Bash call that still needs approval in acceptEdits is denied, since nobody can approve it (add an
`--allowedTools` rule for the test command if the run should execute it). The rules are heuristics (regexes
over the text); treat a finding as a question to answer, not a verdict.

## Docs used (fetched 2026-10-20)

- Subagents: https://code.claude.com/docs/en/sub-agents (frontmatter reference, skipped files, tools and
  filters, permission modes, memory, frontmatter hooks, `--agents` JSON, what loads at startup)
- Plugin subagents: https://code.claude.com/docs/en/plugins/components#agents
- Agent SDK subagents: https://code.claude.com/docs/en/agent-sdk/subagents ("The only content you pass from
  parent to subagent is the Agent tool's prompt string")
- Worktrees: https://code.claude.com/docs/en/worktrees ; parallel work and `/batch`: https://code.claude.com/docs/en/agents
- Headless and structured output: https://code.claude.com/docs/en/headless ; flags: https://code.claude.com/docs/en/cli-reference
- Result fields: https://code.claude.com/docs/en/agent-sdk/typescript#sdkresultmessage
- Hooks (input, exit code 2, exec form): https://code.claude.com/docs/en/hooks
- git: https://git-scm.com/docs/git-worktree , https://git-scm.com/docs/git-diff (`--numstat`)
