What a worktree is
A worktree is another working folder of the same repository. It has its own branch, its own files and its own index. It shares the commits, the objects and the remotes of the main checkout, so it needs no second clone.
The four commands
# A new branch from origin/main, in a folder beside the repository git worktree add --no-track -b feature/HB-412 ../worktrees/billing-core-HB-412 origin/main # Every worktree of the repository, with its branch git worktree list # Remove a worktree after its pull request merges git worktree remove ../worktrees/billing-core-HB-412 # Forget the worktrees whose folders you deleted by hand git worktree prune
--no-track keeps the new branch from tracking origin/main. The first git push -u origin feature/HB-412 then gives the branch its own upstream.
Git checks out a branch in one worktree at a time. A second git worktree add of the same branch fails, so two agents cannot share a branch by mistake.
Why coding agents need worktrees
Two agents in one checkout edit the same files, and each one reads the other’s unfinished changes. With a worktree for each ticket, an agent works while you keep your own checkout, and a second agent works on another ticket at the same time. Each change stays on its own branch, ready for its own pull request.
What a new worktree lacks
Git checks out only the files that it tracks. A new worktree has no .env, no node_modules, no build output and no local configuration. Copy the ignored files that the project needs, then run its setup command:
cp .env ../worktrees/billing-core-HB-412/ cd ../worktrees/billing-core-HB-412 && npm ci
Without this step, the agent’s first test run fails, and so can a commit hook that needs the project’s dependencies.
A ticket in two repositories
When a ticket changes two repositories, give each one a worktree on the same branch name, such as feature/HB-412. Each pull request then names the ticket, and the reviewer finds both.
Clean up
Stop what still runs in the worktree, such as docker compose up, before you remove it. git worktree remove refuses a worktree with changes that are not committed; --force removes it anyway, with those changes.
How Kanjin does it
Prepare Worktrees, step 1 of a ticket, does all of this. Your agent chooses the repositories that the ticket needs. Each one then gets the branch feature/<KEY> from its base branch, in worktrees/<repository>-<KEY> beside the repository, with --no-track. The base branch comes from the repository’s own instructions, such as AGENTS.md or CONTRIBUTING.md, and else from its default branch.
Each repository has a worktree setup: the files to copy, in the patterns of .gitignore, a setup command and a teardown command. Kanjin runs the setup after it creates a worktree, and the teardown before it deletes one. The agent then writes only in the ticket’s worktrees, and Run Locally starts each worktree on a port of its own when the repository allows it.