Back to Insights
AI & Machine Learning•Orchestrating Multiple AI Coding Agents: One Task, Parallel Terminals, Unified Git Workflow•how to•November 28, 2026•22 min read

Orchestrating Multiple AI Coding Agents: One Task, Parallel Terminals, Unified Git Workflow

A practical guide to running multiple AI coding agents in parallel terminals with isolated worktrees, task coordination, and a clean unified Git workflow.

T
Tamiz UddinFull-Stack Engineer

Running one AI coding agent is already unusual: the loop between prompt, edit, test, and review stretches attention across a terminal and an editor. Running several agents against the same task can feel worse—or dramatically better—depending entirely on how you coordinate them.

The difference is isolation. If two agents share one checkout, one agent's formatter can erase another agent's edits, a branch switch can corrupt an in-progress build, and the merge conflict arrives long after anyone remembers which prompt caused it. The reliable pattern is to give every agent its own Git worktree, its own branch, and a narrow, verifiable assignment—then merge through a single integration branch.

This guide builds that pattern from scratch: a small task decomposed across parallel terminal sessions, a shared filesystem for coordination artifacts, and a Git workflow that produces reviewable commits instead of a pile of conflicting diffs.

Table of Contents

1. The Core Model: One Task, Many Isolated Workers

A useful mental model is a build pipeline with a human in the loop:

text
                    ┌──────────────────────────┐
                    │  task.md (shared brief)   │
                    └────────────┬─────────────┘
                                 │
                    ┌────────────▼─────────────┐
                    │  coordinator (you or AI)  │
                    │  split → assign → track   │
                    └────────────┬─────────────┘
         ┌───────────────────────┼───────────────────────┐
         ▼                       ▼                       ▼
  ┌─────────────┐         ┌─────────────┐         ┌─────────────┐
  │ agent-api   │         │ agent-ui    │         │ agent-docs  │
  │ worktree A │         │ worktree B │         │ worktree C │
  │ branch a/* │         │ branch b/* │         │ branch c/* │
  └──────┬──────┘         └──────┬──────┘         └──────┬──────┘
         │                       │                       │
         └───────────────┬───────┴───────────────┬───────┘
                         ▼                       ▼
                  commits + test logs      status.json
                         │                       │
                         └───────────┬───────────┘
                                     ▼
                        ┌───────────────────────┐
                        │  integration branch   │
                        │  merge → test → review│
                        └───────────────────────┘

Four rules make this work:

  1. One worktree per agent. Every agent gets a separate directory and branch. No two agents ever write to the same working tree.
  2. One narrow objective per agent. "Implement the retry policy" is a task. "Make the service better" is not.
  3. One verification command per agent. Each worker must be able to prove its own change locally before it reports back.
  4. One integration point. Branches merge into a single integration branch, never directly into the default branch.

The isolation rule is the one that matters most. It converts a race condition into a merge conflict, and merge conflicts are visible, debuggable, and reviewable.

Why not just use separate directories with git clone?

You can, but worktrees are cheaper and keep a single object database. They share commit history, so merging is fast, and a shared remote means you can push each branch from any session. Worktrees also make cleanup trivial:

bash
git worktree remove ../project-agent-api

The tradeoff is that worktrees share Git metadata. A Git command that operates on the whole repository (a few history rewrites, for example) affects every worktree. For routine parallel feature work, that is a fair price.

2. Prerequisites

You need:

  • Git 2.5+ (worktree support) — realistically, install a current release
  • A project with a committed baseline and a working test suite
  • At least one AI coding CLI you can drive non-interactively or in a persistent session
  • A terminal multiplexer or multiple terminal tabs
  • A clean main branch

Confirm your versions:

bash
git --version
node --version   # or python3 --version, go version, etc.

Verify the baseline before you add agents:

bash
git switch main
git pull --ff-only
git status
npm test

If the test suite is red before you start, fix it first. Parallel agents multiply existing failures; they do not create order from chaos.

A note on agent tooling

This guide is tool-agnostic. It works with any CLI agent that can operate in a working directory and accept a prompt file. What matters is the contract: the agent reads a brief, edits files inside its worktree, runs a verification command, and writes a report.

If you want a starting point for building your own harness, the approach in Tamiz's Insights on agent orchestration patterns is a useful companion reading.

3. Step 1: Define the Task and Decompose It

Create a shared directory for coordination artifacts. Keep it outside the repository so it never lands in a commit:

bash
mkdir -p ~/.agent-orchestration/tasks/checkout-retry
cd ~/.agent-orchestration/tasks/checkout-retry

Write the task brief. The brief is the single source of truth every agent reads:

markdown
# Task: Add idempotent checkout retries

## Context

`POST /checkout` currently fails with a 502 when the payment provider times out,
but the payment may have succeeded upstream. We need a retry policy that does not
double-charge customers.

## Objective

Implement bounded exponential backoff with a jittered delay for transient upstream
failures on the checkout endpoint.

## Out of scope

- Changing the payment provider
- Refactoring the order model
- Any change to the checkout UI

## Constraints

- Retry only on network errors and HTTP 502/503/504
- Maximum 3 attempts total
- Preserve the existing `Idempotency-Key` header semantics
- Do not log full request bodies

## Definition of done

- Unit tests cover retry and non-retry cases
- `npm test` passes
- `npm run lint` passes
- A new env var `CHECKOUT_RETRY_MAX_ATTEMPTS` (default 3) controls the cap

The "Out of scope" section is not decoration. Scope leakage is the most common cause of merge conflicts in parallel agent work: two agents independently decide to refactor the same module.

Now decompose the objective into independent slices. Good slices touch different files and produce separately testable behavior:

markdown
## Slices

| ID  | Scope                                  | Touches                        | Depends on |
|-----|----------------------------------------|--------------------------------|------------|
| A   | Retry policy + backoff calculation     | src/payments/retry.ts          | none       |
| B   | Wire retry into checkout handler       | src/checkout/handler.ts        | A (contract only) |
| C   | Configuration + env parsing           | src/config/env.ts              | none       |
| D   | Unit tests for A and C                 | tests/retry.test.ts            | A, C       |
| E   | Integration test for 502 recovery      | tests/checkout.integration.test.ts | A, B, C  |

Notice that B depends on A's interface, not A's implementation. That is how you can run B and A in parallel: define the interface up front and put it in the brief.

typescript
// Contract both agents must code against
export interface RetryPolicy {
  maxAttempts: number;
  baseDelayMs: number;
  shouldRetry(error: unknown, attempt: number): boolean;
  delayFor(attempt: number): number;
}

When two agents must coordinate on a shared contract, write the contract explicitly. Do not let them infer it from prose and hope the signatures match.

4. Step 2: Create the Integration Branch and Worktrees

From the project root:

bash
cd /path/to/project

git fetch origin
git switch main
git pull --ff-only

# Integration branch: where everything lands
git switch -c feature/checkout-retry

# One worktree and branch per agent
git worktree add -b agent/retry-policy   ../project-agent-retry   feature/checkout-retry
git worktree add -b agent/checkout-wire  ../project-agent-wire    feature/checkout-retry
git worktree add -b agent/config        ../project-agent-config   feature/checkout-retry
git worktree add -b agent/tests         ../project-agent-tests    feature/checkout-retry

# Confirm the layout
git worktree list

Expected output:

text
/path/to/project                   abc1234 [feature/checkout-retry]
/path/to/project-agent-retry       def5678 [agent/retry-policy]
/path/to/project-agent-wire        0123456 [agent/checkout-wire]
/path/to/project-agent-config       89abcde [agent/config]
/path/to/project-agent-tests        fedcba9 [agent/tests]

Each worktree is a full checkout on its own branch. The agent in ../project-agent-wire cannot see uncommitted changes in ../project-agent-retry, which is exactly the point.

A shared scratch directory for read-only artifacts

Agents often need to read the same inputs—API schemas, fixtures, docs. Put those in a directory outside any worktree and mount it read-only conceptually (by convention and by never asking agents to write there):

bash
mkdir -p ~/.agent-orchestration/tasks/checkout-retry/shared
cp docs/payment-api.md ~/.agent-orchestration/tasks/checkout-retry/shared/

For generated fixtures, use a deterministic generator instead of a shared mutable file:

bash
node scripts/generate-fixtures.js --out /tmp/checkout-fixtures --seed 42

Deterministic output means every agent can generate identical inputs independently, with no lock contention.

5. Step 3: Launch One Terminal per Agent

Use a terminal multiplexer so you can watch all sessions from one place. With tmux:

bash
tmux new -s orchestrate

Then create a window per agent. From inside tmux, the shortcut Ctrl-b c creates a new window; rename with Ctrl-b ,.

In each window, cd into the matching worktree and start your agent CLI. The pattern below assumes a generic CLI with a --prompt-file style flag; adapt the invocation to your tool:

bash
cd /path/to/project-agent-retry
claude --dangerously-skip-permissions -p "$(cat ~/.agent-orchestration/tasks/checkout-retry/slices/A.md)"

Or, if you prefer a persistent interactive session, start the agent and paste the brief as your first prompt.

A more robust approach for scripting is to write the prompt to a file and feed it in, so the exact instructions are reproducible:

bash
cat > ~/.agent-orchestration/tasks/checkout-retry/slices/A.md <<'EOF'
You are working in the Git worktree /path/to/project-agent-retry
on branch agent/retry-policy.

Read the task brief at:
  ~/.agent-orchestration/tasks/checkout-retry/brief.md

Implement ONLY slice A: the retry policy and backoff calculation.

Rules:
- Do not modify files outside src/payments/ and tests/retry.test.ts.
- Do not modify the RetryPolicy interface signature.
- Do not run `git commit`, `git merge`, `git rebase`, or `git push`.
- When done, run `npm test -- retry` and `npm run lint`.
- Write a report to /tmp/agent-retry-report.md containing:
  files changed, test output, and any deviations from the brief.
EOF

The report path is a shared contract. Your orchestrator script reads it to learn what each agent did without scraping terminal output.

The commit rule

Tell agents explicitly not to commit, or tell them exactly how to commit. Both work; ambiguity does not.

The safest default for AI agents is: let the agent edit and test, but leave committing to you. You then inspect the diff, stage deliberately, and commit with a message that names the slice. This keeps a malformed commit from a confused agent out of your history.

6. Step 4: Give Each Agent a Scoped Brief

A slice brief should be short, specific, and mechanically checkable. Here is a complete example for the test slice:

markdown
# Slice D: Unit tests for retry policy and config

## Context

The retry policy interface is defined in src/payments/retry.ts as:

  interface RetryPolicy {
    maxAttempts: number;
    baseDelayMs: number;
    shouldRetry(error: unknown, attempt: number): boolean;
    delayFor(attempt: number): number;
  }

## Work

1. Write tests/retry.test.ts covering:
   - shouldRetry returns true for TypeError (network) and HTTP 502/503/504
   - shouldRetry returns false for HTTP 400/422 and for non-retryable errors
   - shouldRetry returns false once attempt >= maxAttempts
   - delayFor grows exponentially and stays within [0, baseDelayMs * 2^(maxAttempts-1)]
   - delayFor includes jitter and remains >= 0
2. Write tests/config.test.ts verifying CHECKOUT_RETRY_MAX_ATTEMPTS
   defaults to 3 and parses an integer from the environment.

## Constraints

- Do not implement production code. If the implementation is missing,
  write the tests against the interface above and note this in your report.
- Use the project's existing test framework and file conventions.
- Do not mock timers globally; inject a delay function if needed.

## Verify

  npm test -- retry config
  npm run lint

## Report

Write /tmp/agent-tests-report.md with the list of test cases added and the
exact commands you ran with their pass/fail status.

Two details in that brief do a lot of work:

  • "Do not implement production code" prevents the test agent from writing a competing implementation that conflicts with slice A.
  • Exact commands give you a machine-checkable completion signal instead of a vague "looks good."

Handling shared-file conflicts

When two slices must touch the same file, pick one of three strategies:

StrategyWhen to useCost
SequentializeThe second slice truly needs the first's outputLoses parallelism
Contract-firstBoth need the same interfaceRequires writing the interface up front
Isolate by fileBoth need the same file but different regionsMerge conflict at integration

Prefer contract-first. When you cannot, serialize the two slices and run them in separate waves.

7. Step 5: Monitor Without Micromanaging

The point of running agents in parallel is that you are not the bottleneck. Resist the urge to interrupt and type instructions into a session every thirty seconds. Instead, build a status surface.

Have each agent write a machine-readable status file when it reaches a milestone:

json
{
  "slice": "A",
  "state": "blocked",
  "summary": "RetryPolicy interface found in src/payments/retry.ts, but it lacks delayFor",
  "files_changed": ["src/payments/retry.ts"],
  "tests": { "command": "npm test -- retry", "status": "failing", "passed": 0, "failed": 3 },
  "needs_from_human": "Confirm whether delayFor belongs on the interface or is a standalone helper"
}

A tiny watcher script can poll these files and print a compact table:

bash
#!/usr/bin/env bash
# watch-status.sh — poll agent status files
STATUS_DIR="${1:-/tmp/agent-status}"

while true; do
  clear
  printf '%-8s %-10s %-9s %s\n' SLICE STATE TESTS SUMMARY
  for f in "$STATUS_DIR"/*.json; do
    [ -e "$f" ] || continue
    slice=$(jq -r '.slice' "$f")
    state=$(jq -r '.state' "$f")
    tests=$(jq -r '.tests.status // "-"' "$f")
    summary=$(jq -r '.summary' "$f")
    printf '%-8s %-10s %-9s %s\n' "$slice" "$state" "$tests" "${summary:0:60}"
  done
  sleep 10
done

Run it in a fifth window:

bash
chmod +x watch-status.sh
./watch-status.sh /tmp/agent-status

When an agent reports blocked, you intervene with a decision, not a suggestion. Write the decision into the shared brief file so every agent sees the same answer:

markdown
## Decisions

- 2024-06-01: `delayFor` stays on the `RetryPolicy` interface. Slice A implements it.
  Slice D tests it through the interface.

This decision log is how you avoid contradictory instructions. Agents read files; they do not read each other's terminals.

8. Step 6: Verify Each Branch Independently

When an agent reports completion, verify its branch yourself. Do not trust the report; verify the claim.

bash
cd /path/to/project-agent-retry

git status --short
git diff --stat main..HEAD
git diff main..HEAD -- src/payments/retry.ts

# Run the verification commands in the worktree
npm ci
npm test -- retry
npm run lint

A useful automated gate is a script that checks each branch against a checklist:

bash
#!/usr/bin/env bash
# verify-branch.sh <worktree-path> <slice-id>
set -euo pipefail

WORKTREE="$1"
SLICE="$2"
cd "$WORKTREE"

echo "==> Verifying $SLICE in $WORKTREE"

# 1. Working tree must be clean after the agent's commit (or have only known changes)
git diff --check

# 2. No forbidden files touched
if git diff --name-only main..HEAD | grep -E '(^|/)\.env|secrets?\.|\.pem$'; then
  echo "FAIL: sensitive file touched" >&2
  exit 1
fi

# 3. Tests and lint
npm test
npm run lint

echo "==> $SLICE passed"

Run it per worktree:

bash
for wt in ../project-agent-*; do
  id=$(basename "$wt" | sed 's/project-agent-//')
  ./verify-branch.sh "$wt" "$id" || echo "FAILED: $id"
done

Commit the agent's work

Once a branch passes verification, commit it from the main worktree's perspective. Because the agent left changes uncommitted in its worktree, you commit inside that worktree:

bash
cd /path/to/project-agent-retry
git add -A
git diff --cached --stat
git commit -m "feat(payments): implement retry policy with jittered backoff

Slice A: RetryPolicy implementation and backoff calculation.

Co-Authored-By: Claude <noreply@anthropic.com>"

Inspect the staged diff before committing. If the agent reformatted unrelated files, unstage them:

bash
git restore --staged src/unrelated/file.ts

9. Step 7: Integrate Through the Integration Branch

Now merge. Start with the branch that has the fewest dependents:

bash
cd /path/to/project
git switch feature/checkout-retry

git merge --no-ff agent/retry-policy -m "merge: slice A retry policy"
git merge --no-ff agent/config       -m "merge: slice C config parsing"

Run the full suite after each merge, not just at the end. A failure after merge three tells you much less than a failure after merge one:

bash
npm ci
npm test
npm run lint

Then merge the dependent slices:

bash
git merge --no-ff agent/checkout-wire -m "merge: slice B checkout wiring"
git test

# If the test slice was written against the contract, it should now pass
git merge --no-ff agent/tests -m "merge: slice D unit tests"
npm test
npm run lint

When a merge conflicts

Conflicts here are a design signal, not a disaster. Two common cases:

Case 1: Both agents changed the same lines. Resolve by hand, then re-run the full suite:

bash
git status
git diff --diff-filter=U
git checkout --conflict=diff3 <path>   # see base, ours, theirs
git add <path>
git commit --no-edit

Case 2: The test branch was written before the implementation existed. If the test agent wrote tests against the contract, they should pass once the implementation lands. If they fail, that is a real bug in either the contract or the implementation—do not paper over it by rewriting the test to match the code.

A safety net: integration tests on every merge

Define a merge gate script and run it after each merge:

bash
#!/usr/bin/env bash
# merge-gate.sh — run after every merge into the integration branch
set -euo pipefail

echo "==> Running merge gate"
npm ci
npm test -- --coverage=false
npm run lint
npm run typecheck 2>/dev/null || true

echo "==> Merge gate passed"

Keep || true off in real use. If a script exists, it should fail the gate.

10. Step 8: Run a Review and Fix Loop

Parallel agents optimize for throughput, not for correctness. A final review pass catches the class of problems that pass unit tests but break the system: inconsistent error handling, duplicated logic, dead code, and inconsistent naming across independently written slices.

Spawn a dedicated review agent on a fresh worktree of the integration branch:

bash
git worktree add -b agent/review ../project-agent-review feature/checkout-retry
cd ../project-agent-review

Brief it to review, not to rewrite:

markdown
# Review the integrated checkout-retry change

Compare feature/checkout-retry against main.

Review for:
1. Correctness bugs and unhandled error paths
2. Inconsistencies between slices (naming, error types, logging style)
3. Duplicated logic that should be shared
4. Missing test coverage for the new behavior
5. Security issues: secrets, injection, unsafe logging of PII

Do NOT fix anything. Produce a findings list, most severe first, with
file:line references and a concrete suggested fix for each finding.

Write the findings to /tmp/agent-review-findings.md as a numbered list.

Then run a fix agent on the integration branch itself, with the findings as input:

bash
cd /path/to/project
claude -p "Read /tmp/agent-review-findings.md. Apply the fixes that are valid and
low-risk to the current branch. For each fix, state whether you applied it or
skipped it and why. Then run npm test and npm run lint."

Review-and-fix loops work best when the reviewer is forbidden from editing. Separation of duties catches more than a single agent that reviews and patches its own work.

Finally, open a pull request:

bash
git push -u origin feature/checkout-retry
bash
gh pr create \
  --base main \
  --head feature/checkout-retry \
  --title "feat(payments): idempotent checkout retries" \
  --body "$(cat <<'EOF'
## Summary

Adds bounded, jittered exponential backoff for transient upstream failures on
the checkout endpoint. The `Idempotency-Key` header semantics are unchanged.

## Slices

- A: retry policy implementation (`src/payments/retry.ts`)
- B: checkout handler wiring (`src/checkout/handler.ts`)
- C: configuration parsing (`src/config/env.ts`)
- D: unit tests (`tests/retry.test.ts`, `tests/config.test.ts`)

## Verification

- `npm test` — passing
- `npm run lint` — passing

🤖 Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"

11. Coordination Patterns That Scale

Pattern: Wave-based execution

When slices have real dependencies, run waves instead of one big parallel batch.

text
Wave 1 (parallel):  A (policy)  |  C (config)
        ↓
Wave 2 (parallel):  B (wiring) |  D (unit tests)
        ↓
Wave 3 (serial):    E (integration test)
        ↓
Wave 4 (serial):    Review + fix

The win: waves 1 and 2 each deliver real parallelism, but you never launch an agent whose prerequisites are missing.

Pattern: Fan-out for exploration, fan-in for implementation

A particularly effective use of parallel agents is read-only investigation. Spawn three agents to explore different aspects of the codebase, have each write findings to a shared file, then let one implementation agent consume them:

bash
# Agent 1: map the data flow
claude -p "Trace how checkout requests flow from route to payment provider.
Write findings to /tmp/explore-flow.md. Do not modify any files."

# Agent 2: find the failure modes
claude -p "Find all error handling around payment provider calls.
Write findings to /tmp/explore-errors.md. Do not modify any files."

# Agent 3: inventory the tests
claude -p "List all existing tests touching checkout and payments, with file paths.
Write findings to /tmp/explore-tests.md. Do not modify any files."

This pattern is fast, safe (no write conflicts possible), and produces better briefs for the implementation agents that follow.

Pattern: Competing hypotheses

For a bug, give two agents the same symptom but different hypotheses and require evidence:

markdown
Agent X hypothesis: the timeout is on the client side; the request never reaches
the provider.
Agent Y hypothesis: the provider succeeds but the response is dropped in transit.

Each must cite file:line evidence and propose a reproduction test.

The agent with the stronger evidence wins; the other becomes a dead end. This is faster than debating hypotheses yourself.

Pattern: Contract-first with a stub

When two agents must build against the same interface, one agent writes the stub, commits it, and the others branch from that commit:

bash
# Agent A writes the interface and stub, commits
git add src/payments/retry.ts
git commit -m "feat(payments): define RetryPolicy interface and stub"

# Other agents branch from the stub commit
git worktree add -b agent/tests ../project-agent-tests a1b2c3d

This serializes one small step and parallelizes everything after it.

12. Common Failure Modes

Agents fight over the same files

Symptom: merge conflicts in files neither agent was assigned.

Cause: vague scope, or a shared formatter/linter running on the whole repo.

Fix: assign explicit file globs to each slice. If two agents need the same file, use the strategies in Step 4. For formatters, run them only at integration time, not during each agent's loop.

Agents commit to the wrong branch

Symptom: a branch contains another slice's work; the diff is enormous.

Cause: the agent ran git checkout or git switch inside its worktree.

Fix: add to every brief:

text
Do not run git checkout, git switch, git merge, git rebase, or git push.
You are on branch agent/<slice>. If you believe you are on the wrong branch, stop
and write the situation to your report instead of changing branches.

Add a post-hoc check in verify-branch.sh:

bash
expected="agent/${SLICE}"
current=$(git rev-parse --abbrev-ref HEAD)
if [ "$current" != "$expected" ]; then
  echo "FAIL: on $current, expected $expected" >&2
  exit 1
fi

Agents "fix" failing tests by weakening them

Symptom: tests pass but assert almost nothing.

Cause: the brief said "make the tests pass" instead of "implement the behavior."

Fix: state expected behavior precisely, and review the test diff specifically. A test agent should never be allowed to modify the assertion it was asked to write.

Duplicate or conflicting configuration

Symptom: two env vars for the same setting; the wrong one wins at runtime.

Cause: two agents independently added configuration.

Fix: assign configuration to exactly one slice and list the variable names in the shared brief.

The integration branch drifts from main

Symptom: merge conflicts that have nothing to do with your change.

Cause: main moved while agents were working.

Fix: rebase each agent branch onto the updated integration branch before merging, and re-run its tests:

bash
cd /path/to/project-agent-wire
git rebase feature/checkout-retry
npm test

If feature/checkout-retry itself needs main, merge main into it first:

bash
cd /path/to/project
git merge main
git push
git worktree list

Agents run long, expensive, or destructive commands

Fix: deny destructive commands in the agent's permission configuration, restrict network access where possible, and set a wall-clock timeout on each session.

13. Production-Grade Guardrails

Cost control

Track token spend per slice. A simple approach is to have each agent report the commands it ran and let the orchestrator budget by slice:

bash
# Pseudocode-style budget check
MAX_TOKENS_PER_SLICE=500000
if [ "$tokens_used" -gt "$MAX_TOKENS_PER_SLICE" ]; then
  echo "Slice $SLICE exceeded budget; escalating to human"
fi

More practically: give each agent a narrow brief and a hard scope. Most cost blowups come from an agent exploring the entire repository because its brief said "investigate the payment system."

Sandbox the agents

Run each agent with restricted filesystem access when you can. Container per worktree:

bash
docker run --rm -it \
  -v /path/to/project-agent-retry:/workspace \
  -v ~/.cache:/root/.cache \
  -w /workspace \
  node:22 bash

For higher assurance, disable outbound network except for the package registry and the model endpoint.

Enforce the merge gate in CI

The local gate script is for fast feedback. The same commands must run in CI on the pull request, where nothing depends on your memory:

yaml
# .github/workflows/pr.yml
name: pr
on:
  pull_request:
    branches: [main]

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: npm run typecheck
      - run: npm test

Keep a provenance record

For each slice, record which agent produced it and what brief it received. Store it in the PR body or in a docs/agent-runs/ directory:

markdown
| Slice | Agent | Brief | Commit | Verification |
|-------|-------|-------|--------|--------------|
| A | claude-sonnet | slices/A.md | abc1234 | npm test -- retry ✅ |
| C | claude-sonnet | slices/C.md | def5678 | npm test -- config ✅ |
| B | gpt-5 | slices/B.md | 0123456 | npm test ✅ |
| D | gpt-5 | slices/D.md | 3456789 | npm test ✅ |

When a reviewer asks "why does this function swallow the error?", you can find the brief that instructed it and the report that flagged it.

Clean up worktrees

bash
# Remove worktrees for merged branches
git worktree remove ../project-agent-retry
git worktree remove ../project-agent-wire
git worktree remove ../project-agent-config
git worktree remove ../project-agent-tests
git worktree remove ../project-agent-review

# Delete the local branches
git branch -d agent/retry-policy
git branch -d agent/checkout-wire
git branch -d agent/config
git branch -d agent/tests
git branch -d agent/review

# Prune any stale administrative entries
git worktree prune

Frequently Asked Questions

How many agents should run in parallel?\n

Start with two or three. The limit is usually your ability to review diffs, not your machine's CPU count. If you cannot review each branch's diff within a few minutes of it finishing, you have too many agents running. Measure your throughput: add agents only while integration remains faster than sequential work.

Should agents commit their own changes?\n

Either approach works. Letting agents commit produces a cleaner handoff and lets you use git log per branch, but you must review each commit before merging. Letting them leave changes uncommitted gives you maximum control over exactly what enters history, at the cost of a manual commit step per branch. For a first implementation, do not commit automatically—review the staged diff every time.

How do I handle a shared file that two agents need to modify?\n

Use one of three strategies in order of preference: write the shared interface up front and let both agents code against it (contract-first); serialize the two slices into separate waves; or, as a last resort, let both edit the file and resolve the conflict at integration. Whichever you choose, say so explicitly in both briefs—agents cannot infer your intent, and guessing produces conflicting rewrites of the same block.

What if one agent finishes much earlier than the others?

Do not let it idle. Either start the next wave's slice that depends only on completed work, or assign it a read-only exploration task for the remaining scope. The key is to keep the parallel frontier moving without creating dependencies on unfinished branches.

Is this different from just running agents sequentially?\n

Yes, in one specific way that matters: parallelism changes the failure mode. Sequential work produces a single coherent diff. Parallel work produces several diffs that must agree at the seams. The whole apparatus here—contracts, scoped briefs, worktree isolation, the merge gate, the review pass—exists to make those seams explicit and verifiable rather than hoping they line up.