My agent runner had a concurrency problem I'd been ignoring: every run worked in the same clone.

One run does git checkout -b fix/x, the next starts forty seconds later in the same directory, and two shells are editing one working tree. The failures look like nonsense — a diff with hunks from someone else's branch, a test that passes alone and fails in sequence — because they are nonsense.

The fix is git worktree add: each run gets a checkout at <runDir>/worktree, its own branch, cut from origin's default branch. The parent stays the object store. That took an afternoon; the next day went to what git worktree does not decide for you.

The push that was aimed at main

Here is the line I wrote first:

gitRun(repo, "worktree", "add", wt, "-b", branch, base) 

base is the SHA of origin/main. Creating a branch from a remote-tracking ref makes git configure that ref as the new branch's upstream. Correct for a human starting feature work, wrong for a machine:

$ git rev-parse --abbrev-ref 'agent/y@{upstream}' origin/main 

The run now has a checkout whose plain git push is aimed at main, and how bad that is depends on one config value. With the default push.default=simple, git refuses:

$ git push fatal: The upstream branch of your current branch does not match the name of your current branch. To push to the upstream branch on the remote, use git push origin HEAD:main 

A fine error to get once. A terrible one inside an agent loop, because the useful reading of it is "do what it says". With push.default=upstream — a setting plenty of long-lived machines still carry — there is no error at all: the run's commits go to main and nothing tells you.

One flag fixes it:

gitRun(repo, "worktree", "add", "--no-track", wt, "-b", branch, base) 

The branch now tracks nothing, so git push has no destination and fails loudly. Pushing has to be the explicit git push -u origin agent/<slug> in the run's build step. I also pass the resolved SHA rather than the branch name, so the base recorded in run.json is the commit the branch holds even if origin moves between the two git calls.

The rule I keep re-learning: a machine that runs git push must be given a branch with no upstream. Anything else is a default you did not choose.

Two runs, one issue

Branch names have to survive a second run on the same issue. The slug is the subject's last path segment, reduced to [a-z0-9-], plus the time component of the run id:

func Slug(subject, id string) string { name, stamp := subjectName(subject), idStamp(id) switch { case name == "": return stamp case stamp == "": return name } return name + "-" + stamp } 

Without the stamp, the second run either adopts the first run's branch — writing into a checkout someone else owns — or dies on -b. Neither is "a worktree of its own".

Deciding when not to delete it

Every run ends, and the tree should not outlive the run, except when it must. The checkout is scratch only if the run's work is settled: done, every edit already on the branch the PR was opened from, the tree regenerable from git.

A run that failed its gate never got its work onto the branch, so its checkout is the only copy of the attempt and of the reason the gate said no. Refused and failed runs are the same. Those trees stay, and a gc pass collects them by age. Cleanup that is too eager deletes exactly the evidence you need from the run that went wrong — cheap to write, expensive to debug.

So removal runs from one terminal path, and only for a settled run:

func CleanupWorktree(runDir string, code int) error { added, err := worktreeRecorded(runDir) if err != nil { return err } if !added { return nil } // remove, then append worktree:remove with the exit code reached } 

The ledger decides whether a tree exists, not the filesystem. A tree someone deleted by hand still needs its registration pruned and its removal recorded.

Exit codes are not proof

git worktree prune exits 0 when a registration is locked even though it did not drop the entry. "The command succeeded" and "the tree is gone" are two different facts, and the second one is what the function promises. So I read git worktree list --porcelain after the attempt and treat a surviving path as an error:

want := resolvePath(path) for _, line := range strings.Split(out, "\n") { if got, ok := strings.CutPrefix(line, "worktree "); ok && resolvePath(got) == want { return true, nil } } 

Both sides are symlink-resolved before comparison, because git prints the path it resolved when the tree was added, not the one it was handed. $HOME is a symlink on a lot of boxes, run directories live under it, and comparing cleaned strings misses the entry — turning a failed removal into a reported success.

The ordering

worktree add first, then write the record, then append the worktree:add event. If either write fails, the tree and its branch come back out: a checkout that exists without the event is invisible to gc, because gc finds runs through their record, so a half-finished add leaks a tree forever.

None of this is worktree trivia. It is the same three questions for any resource a process creates: who names it, when does it stop being deletable, and which signal proves it is gone. git worktree is easy. The ownership is the work.

The runner is agent-runner — Go, one bounded task per invocation, a PR or a recorded refusal at the end.