Worktrees

Run several sessions on one project, each on its own branch, with its own port and address.

A worktree session works in a separate git checkout of the project, on its own branch. Two sessions on the same repository cannot overwrite each other’s files, and each can run its own dev server.

Starting one

/worktree new checkout-fix

kcode creates the branch kcode/checkout-fix, checks it out under .kcode/worktrees/checkout-fix, and opens a session there. Its tile sits beside the tile of the base project. /worktree new <name> <start-point> branches from another commit or branch.

The agent starts worktree sessions too, when a task splits into parts that can run side by side.

Files that git ignores

A fresh checkout has no .env and no other file that git ignores. A .worktreeinclude file at the project root, in .gitignore syntax, names the ignored files kcode copies into each new worktree:

.env
.env.local

Ports and addresses

Each worktree takes a slot, and kcode sets PORT in the worktree’s shell to worktree.port_base plus the slot: 3001 for the first worktree with the default base of 3000. The dev server is reached at http://<name>.localhost:<port>. The status bar shows the address as ⎇ checkout-fix :3001, and a click opens it.

A dev server that ignores PORT must be given it, as in vite --port $PORT --strictPort.

A [worktree.env] table in <project>/.kcode/config.toml sets more variables per worktree:

[worktree.env]
VITE_PORT = "{{5173+slot}}"
DATABASE_URL = "postgres://localhost/app_{{slug}}"
Placeholder Value
{{slot}} The worktree’s slot number.
{{slug}} The worktree’s name.
{{project}} The name of the base project’s folder.
{{port}} The worktree’s PORT.
{{domain}} The worktree’s host name, <name>.localhost.
{{5173+slot}} A base number plus the slot.

A separate checkout does not separate a database or any other shared service. The project sets those up itself, with [worktree.env] and a hook on worktree:create.

Merging and removing

Command Result
/worktree list Opens a live panel of the project’s worktrees.
/worktree update Rebases the worktree onto its base branch.
/worktree merge Squash-merges the worktree into its base branch. A conflict is handed to the agent or the merge is aborted.
/worktree remove Deletes the checkout and its branch. It refuses while the worktree has uncommitted changes or unmerged commits.
/worktree adopt <branch> Opens a session on a worktree or a branch that already exists.

Closing a worktree session whose checkout has no uncommitted files and no commits past its base deletes the checkout, its branch and the session. A checkout with either is always kept.

Product video