Clean up after your AI agents
Every task an AI agent works on gets its own working copy of the code, and nothing removes it when the work is merged. Ours piled up until most of them belonged to work finished days earlier and the disk was nearly full. We now remove a copy only when three things are true, and print the reason whenever we keep one.
What piles up
When agents work in parallel, each task gets its own git worktree: a separate checkout of the repository, so two agents never edit the same files. It is the right design. It also means every task leaves a folder behind, with its own copy of the code.
Nothing cleaned those folders up. When we finally looked, most of the worktrees on the machine belonged to pull requests that had merged days earlier, and the disk was close to full.
Deleting them all is not the answer either. A worktree can hold work that exists nowhere else: a commit that was never pushed, a change not yet committed, a fix made after review.
The three checks
A worktree is removed only when all three of these are true. If any one fails, it stays, and the script prints which check kept it.
Read the diagram as text
- On a branch?. Otherwise: No: keep it, and print why
- Nothing uncommitted? (git status is empty). Otherwise: No: keep it, and print why
- Pull request merged, nothing only on this disk?. Otherwise: No: keep it, and print why
- Remove the worktree
The third check took a second attempt. At first it kept any worktree with commits newer than the merged pull request. That was too careful: after a merge, a worktree often has new commits that only bring the main branch back in, and those exist on the server already. Plenty of space was held for that reason alone. Now a commit only counts if it is not pushed anywhere.
Make the cleanup part of finishing
The rule we work by: leaving a pull request open is not “done”, because review fixes still need the checkout. Merged is done, and done includes cleaning up. So the cleanup runs at the end of every session that created a worktree, not once a month when the disk complains.
Some space cannot be freed from inside an environment at all, and for that the answer is different: we replace the environment that runs the agents on a regular schedule, carrying its records across. That is a topic for another note.
If agents or automated jobs are quietly filling your machines, book a call. The fix is usually small once someone looks.
Related reading
- ai
- automation
- internal-tooling
- operations