Sub topic 13
A script to set up and tear down the workflow
The earlier chapters ran each step by hand: create a worktree, copy .env, start an agent, review, merge, remove. This chapter combines those steps into one script you can run the same way every time. It also covers the edge cases that a hand-run workflow tends to get wrong.
Prerequisites
This chapter assumes you can do the following:
- Read and write Bash, including functions, arrays,
set -euo pipefail, and background jobs with&andwait. - Use
git worktree add,list,removeandprune, and you know that a branch can be checked out in only one worktree at a time. - Run a command-line coding agent non-interactively with a prompt argument.
What the script should and should not do
Automate the steps that are mechanical and safe to repeat: creating worktrees, copying local config, starting agents, reporting status, and removing finished worktrees. Leave one step to a person: deciding what gets merged. A script that merges every agent branch automatically will merge broken work.
| Subcommand | What it does | Git commands behind it |
|---|---|---|
| `setup` | Creates one worktree and one `agent/` branch per task | `git worktree add -b` |
| `run` | Starts one agent per worktree in the background and waits | none (shell only) |
| `status` | Shows uncommitted files and new commits per task | `git status`, `git log` |
| `teardown` | Removes worktrees and merged branches, keeps the rest | `git worktree remove`, `git branch -d`, `git worktree prune` |
Review and merge stay manual, between status and teardown.
The script
Save this as agents.sh somewhere on your PATH or in a scripts/ directory, and make it executable with chmod +x agents.sh. Run it from the main checkout, not from a linked worktree. The sibling directory names are derived from the checkout you run it in.
#!/usr/bin/env bash
set -euo pipefail
base=${BASE_BRANCH:-main}
port_base=${AGENT_PORT_BASE:-3100}
repo=$(git rev-parse --show-toplevel)
name=$(basename "$repo")
parent=$(dirname "$repo")
logdir="$parent/$name-logs"
usage() {
echo "usage: $0 {setup|run|status|teardown} task..." >&2
exit 2
}
wt_path() { echo "$parent/$name-$1"; }
check_names() {
for task in "$@"; do
if [[ ! $task =~ ^[a-z0-9][a-z0-9-]*$ ]]; then
echo "invalid task name: $task (use lowercase letters, digits, hyphens)" >&2
exit 2
fi
done
}
setup() {
for task in "$@"; do
path=$(wt_path "$task")
if [ -e "$path" ]; then
echo "skip $task: $path already exists" >&2
continue
fi
git worktree add -b "agent/$task" "$path" "$base"
if [ -f "$repo/.env" ]; then
cp "$repo/.env" "$path/.env"
fi
done
}
run() {
: "${AGENT_CMD:?set AGENT_CMD to your agent command}"
mkdir -p "$logdir"
pids=()
i=0
for task in "$@"; do
path=$(wt_path "$task")
port=$((port_base + i))
(
cd "$path"
PORT="$port" exec "$AGENT_CMD" "Work on the $task task described in TASKS.md"
) >"$logdir/$task.log" 2>&1 &
pids+=($!)
i=$((i + 1))
done
failed=0
for pid in "${pids[@]}"; do
wait "$pid" || failed=1
done
return "$failed"
}
status() {
for task in "$@"; do
path=$(wt_path "$task")
echo "== $task =="
git -C "$path" status --short
git log --oneline "$base..agent/$task"
done
}
teardown() {
for task in "$@"; do
path=$(wt_path "$task")
if git worktree remove "$path"; then
git branch -d "agent/$task" || echo "kept agent/$task: not merged yet" >&2
else
echo "kept $task: worktree is dirty or locked" >&2
fi
done
git worktree prune
}
cmd=${1:-}
[ $# -ge 2 ] || usage
shift
check_names "$@"
case "$cmd" in
setup) setup "$@" ;;
run) run "$@" ;;
status) status "$@" ;;
teardown) teardown "$@" ;;
*) usage ;;
esacTypical use:
./agents.sh setup auth billing search
AGENT_CMD=your-agent-command ./agents.sh run auth billing search
./agents.sh status auth billing searchyour-agent-command is a placeholder for whichever agent CLI you use. It must be a single executable that accepts the prompt as its first argument. If your agent needs flags, put them in a small wrapper script and point AGENT_CMD at that.
Design decisions in the script
Fail early on bad input
set -euo pipefail stops the script on the first unhandled error, on unset variables, and on failures inside pipes. check_names rejects task names that would produce awkward branch names or paths, such as names with spaces, slashes, or a leading dash. Task names end up in a branch name, a directory name and a log file name, so one strict pattern protects all three.
Make `setup` safe to re-run
The [ -e "$path" ] check skips tasks whose directory already exists. If you add a fourth task later, run setup with all four names and the first three are left alone. Without the check, git worktree add would fail on the existing path and set -e would abort the script partway through.
The check does not cover a leftover branch. If agent/auth exists but its worktree was removed, git worktree add -b fails because the branch already exists. That failure is useful. It tells you an earlier run was not cleaned up, and silently reusing the old branch could hide stale work.
Copy untracked files after creating the worktree
A new worktree contains only tracked files. The .env copy puts local configuration into each worktree, as in the earlier chapter on untracked files. Add other files the same way, for example a local settings file. Do not use a symlink to a shared .env if any agent might edit it, because every worktree would then see the change.
Give each agent its own port
run assigns PORT as AGENT_PORT_BASE plus the task's position in the list, so three tasks get 3100, 3101 and 3102. This only helps if your project reads PORT from the environment. If it takes the port from a config file, rewrite that file in setup instead. The port depends on task order, so keep the order of task names the same between runs if you rely on a given number.
Run in subshells and wait for all of them
Each agent starts in a subshell ( ... ) &, so cd affects only that subshell and the main script stays in the repository. exec replaces the subshell with the agent process, so the PID saved in pids belongs to the agent itself. The wait "$pid" || failed=1 pattern waits for every agent, even after one fails. A plain wait would not report exit codes, and a bare wait "$pid" under set -e would end the script at the first failed agent and skip the rest.
Never force-remove in `teardown`
teardown calls git worktree remove without --force. Git refuses to delete a worktree with uncommitted changes or untracked files, and it refuses a locked worktree. The script treats that refusal as information. It prints which worktree was kept and goes on to the next one. Likewise, git branch -d deletes a branch only when it is merged into the current branch. That is why you run teardown from the main checkout after merging into main. If you run it from some other branch, -d compares against that branch and may refuse to delete work you have already merged.
If you have decided that a worktree's contents are worthless, remove it by hand with git worktree remove --force and delete the branch with git branch -D. Making these deliberate manual commands means a typo in the script cannot destroy unmerged work.
The final git worktree prune clears records for worktrees whose directories were deleted by hand, for example with rm -rf. It does not touch any directory that still exists.
Reviewing and merging between `run` and `teardown`
After run finishes, use status to see which branches have commits and which worktrees have loose changes. An agent that exits without committing leaves its work as uncommitted files, so commit them from inside that worktree if they are worth keeping. Then review each branch against main and merge it, one at a time:
git diff main...agent/auth
git switch main
git merge --no-ff agent/authRun tests on main after each merge, not only once at the end. If two branches conflict, the second merge shows it, and you can resolve it with full context of the first. Once all merges are done, ./agents.sh teardown auth billing search removes what is finished and reports anything it kept.
Failure modes to expect
- An agent crashes or exits non-zero.
runreturns a non-zero status, and the log inmyrepo-logsshows why. Other agents are unaffected because each has its own process and worktree. - The script is interrupted during
setup. Some worktrees exist and others do not. Rungit worktree list, then re-runsetup. Existing paths are skipped. - A teardown reports "kept". Either the worktree has uncommitted changes, or the branch is not merged. Inspect it, then commit, merge or discard deliberately.
- A hand-deleted worktree directory.
git worktree liststill shows it as prunable.teardownrunsgit worktree prunefor this, or you can run the command yourself. - Two runs at the same time with the same task names. Both would write to the same logs and share ports. Treat one set of task names as one active batch.
Exercise
You run ./agents.sh teardown auth billing after merging only agent/auth into main. The billing agent finished but left uncommitted edits in its worktree. What does the script do for each task, and why does it not lose the billing work?
Show answer
For auth, git worktree remove succeeds because the worktree is clean, and git branch -d agent/auth succeeds because the branch is merged into main. For billing, git worktree remove refuses because the worktree has uncommitted changes, so the script prints "kept billing: worktree is dirty or locked" and skips the branch deletion. Because the script never uses --force or -D, the uncommitted edits and the unmerged branch both stay intact.
Exercise
Modify the run function so that a task's port is derived from the task name, not its position in the list. Why might that be better than the position-based version?
Show answer
Compute a stable number from the name, for example port=$((port_base + $(printf '%s' "$task" | cksum | cut -d' ' -f1) % 100)). A given task then always gets the same port, even if you pass the tasks in a different order or run only a subset. The trade-off is that two names can hash to the same port, so check for a collision or keep an explicit task-to-port table when that matters.