Sub topic 7
Starting agents in parallel
This chapter assumes you can create a worktree with a new branch for each task (covered earlier in this tutorial). It also assumes you can run a command-line coding agent on a single task, and that you know basic shell job control (&, wait, redirection). You will learn how to start several agents at once, one in each worktree. You will also learn how to capture their output, detect failures, limit how many run at a time, and stop them cleanly.
What "in parallel" means here
Each agent is an ordinary operating system process. It reads and writes files in its current working directory. A linked worktree is a separate directory, so a process started inside it edits only that directory's files. Starting agents in parallel therefore comes down to running several processes at once, each with a different working directory.
Git does not run the agents for you, and it does not coordinate them. The shell does the work. The one thing to get right is the working directory of each process.
The basic launcher
Assume the worktrees ../myrepo-auth, ../myrepo-billing and ../myrepo-search already exist, each on its own agent/ branch. This loop starts one agent per worktree:
for task in auth billing search; do
(
cd "../myrepo-$task"
cp ../myrepo/.env .env
your-agent-command "Work on the $task task described in TASKS.md"
) &
done
waityour-agent-command is a placeholder. Substitute the command for the agent CLI you use, and check how it accepts a prompt and how it runs without prompting for input.
Four details in this loop matter.
- The parentheses create a subshell.
cdinside the subshell changes only that subshell's directory. Your launcher stays inmyrepo, so the next loop iteration resolves../myrepo-billingfrom the right place. Without the parentheses, the secondcdwould run relative to the first worktree and fail. - The trailing
&backgrounds the whole subshell. The loop does not block on the first agent. All three start within milliseconds of each other. cp ../myrepo/.env .envsupplies an untracked file. Git does not copy untracked files into a new worktree. The.envfile lives only in the main checkout, so each agent would otherwise start without its configuration. Later chapters cover dependencies, ports and other local configuration in more detail.waitblocks until every background job finishes. Without it, the script exits while the agents are still running. That is harmless in an interactive terminal but wrong in a script that goes on to review or merge.
Give each agent a self-contained task description
An agent started in a worktree sees that worktree's files and nothing else. It does not know about the other agents. The prompt should therefore say everything the agent needs to know.
- Name the task and the files or directories it should touch.
- Say what counts as done, such as a test command that must pass.
- Tell it to commit its work on the current branch and to leave other branches alone.
The examples above point each agent at a TASKS.md file. Remember that a file you write in the main checkout is not present in the worktrees unless it is committed on main before you create them. Either commit it first or write a different file into each worktree. Otherwise the agent will report that TASKS.md does not exist.
Capture output and exit codes
Three agents writing to one terminal produce interleaved, unreadable output. Redirect each agent's output to its own log file. Record each process ID so you can check its exit status afterwards.
#!/usr/bin/env bash
set -uo pipefail
tasks=(auth billing search)
pids=()
mkdir -p ../agent-logs
for task in "${tasks[@]}"; do
(
cd "../myrepo-$task" || exit 1
cp ../myrepo/.env .env
exec your-agent-command "Work on the $task task described in TASKS.md" \
> "../agent-logs/$task.log" 2>&1
) &
pids+=("$!")
done
failed=0
for i in "${!tasks[@]}"; do
if wait "${pids[$i]}"; then
echo "${tasks[$i]}: finished"
else
echo "${tasks[$i]}: failed, see ../agent-logs/${tasks[$i]}.log"
failed=1
fi
done
exit "$failed"Run this script from the myrepo directory. The script uses these techniques:
$!holds the process ID of the most recent background job. Saving it right after the&lets you wait on that job later.wait PIDreturns the exit status of that process. A non-zero status means the agent reported an error.execreplaces the subshell with the agent process. The recorded process ID is then the agent's own, so a signal sent to it reaches the agent and not just a wrapper shell.- The script does not use
set -e. With-e, one failingwaitwould end the script before it had checked the other agents.
The logs live in ../agent-logs, which is next to the repository. That keeps them out of every worktree, so they never appear in git status or end up in a commit.
Limit how many agents run at once
Running every task at once is not always sensible. Each agent uses CPU, memory and network capacity. Most hosted agents also enforce API rate limits, and many agents running together can hit them. Start with two or three at a time and raise the number only if your machine and your rate limits allow it.
xargs -P caps the number of concurrent jobs and works in older versions of Bash and in other shells:
printf '%s\n' auth billing search docs lint-fixes |
xargs -P 2 -I{} sh -c '
cd "../myrepo-{}" &&
your-agent-command "Work on the {} task described in TASKS.md" \
> "../agent-logs/{}.log" 2>&1
'-P 2 keeps at most two jobs running. When one finishes, xargs starts the next task from the list. Only use this form with task names that you wrote yourself, because {} is substituted directly into the shell command text.
Interactive agents and terminal multiplexers
Some agents expect a person at the keyboard and ask for confirmations. A background process with its output sent to a file cannot answer those prompts. You have two options.
- Run the agent in a non-interactive or headless mode if it has one, and pre-approve the actions it needs. Check what permissions you are granting, and grant only what the task needs.
- Start each agent in its own terminal pane or window, for example with
tmux, so you can switch between them and answer prompts.
A minimal tmux launcher creates one window per worktree:
tmux new-session -d -s agents -c ../myrepo-auth -n auth 'your-agent-command "Work on the auth task described in TASKS.md"'
tmux new-window -t agents -c ../myrepo-billing -n billing 'your-agent-command "Work on the billing task described in TASKS.md"'
tmux new-window -t agents -c ../myrepo-search -n search 'your-agent-command "Work on the search task described in TASKS.md"'
tmux attach -t agentsThe -c option sets each window's starting directory. That plays the same role as cd in the subshell version.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `cd: ../myrepo-billing: No such file or directory` | The launcher was not started from the main checkout, or `cd` ran outside a subshell. | Run from `myrepo` and keep `cd` inside parentheses. |
| Two agents change the same files | Tasks overlap, or an agent was started in the main checkout. | Check `pwd` and `git branch --show-current` in each agent's directory. Revisit the task split. |
| Agent says `TASKS.md` is missing | The file was never committed on `main`, so new worktrees do not contain it. | Commit it before creating worktrees, or write it into each worktree. |
| Agent fails on missing configuration | Untracked files such as `.env` were not copied. | Copy them in the launcher, as shown above. |
| Script exits while agents still run | `wait` is missing. | Add `wait`, or wait on each saved process ID. |
| Agents stop with rate-limit or timeout errors | Too many concurrent API requests. | Lower the concurrency with `xargs -P`. |
| `fatal: ... index.lock` appears in logs | Two Git processes tried to use the same worktree's index at once. | Make sure only one agent works in each worktree. |
Stopping a run
To stop everything, send a termination signal to the saved process IDs. Do it in a way that lets each agent exit and leaves its worktree intact:
kill "${pids[@]}"
waitAfter a stop, inspect each worktree with git status before restarting it. An interrupted agent may leave uncommitted edits. Those edits are still in the worktree directory, so you can commit them, discard them with git restore ., or let the next run continue from them. Decide that per worktree. Do not delete a worktree you have not looked at.
Check before you walk away
Before leaving the agents to run, check four things.
- Each agent's directory is a different worktree (
git worktree list). - Each worktree is on its own branch.
- Each agent can find the files and configuration it needs.
- Each agent writes its log to a separate file.
Exercise
A launcher loop starts each agent with cd "../myrepo-$task" and no parentheses around the cd, cp and agent command, followed by & on the agent command. What goes wrong, and how do you fix it?
Show answer
Without a subshell, cd changes the launcher shell's own directory, so the next iteration resolves ../myrepo-billing from inside myrepo-auth and fails. Because only the agent command is backgrounded, the cd and cp also run in the launcher. The fix is to wrap the cd, cp and agent command in ( ... ) &, so the directory change stays in the subshell and the whole unit runs in the background.
Exercise
Your script waits on each saved process ID and reports ok for an agent that exited with status 0. Why is that not enough to trust the branch, and what do you check next?
Show answer
Status 0 only means the process ended normally. An agent can exit cleanly after failing to finish the task or after failed tests. Check the branch with git log and git diff main...agent/<task>, and run the project's test suite in that worktree before merging.