README
¶
worktree-manager
Go CLI that creates a ready-to-use git worktree and manages its full lifecycle: creation, stack startup, stop, removal, plus a pre-migrated database backup (Postgres, MySQL, MariaDB, MongoDB or SQLite) that makes bootstrapping a database fast.
It has no runtime dependency beyond git and docker: port allocation,
compose project naming and the stack lifecycle are all handled directly.
Port assignments follow the same formula
worktree-compose used, and
the same .env markers, so a worktree created with that tool keeps the ports
it already had.
Requirements
| Why | When | |
|---|---|---|
| Go >= 1.26 | to install the binary | install only |
git >= 2.31 |
worktrees, and --path-format to resolve the repository from inside one |
always |
docker with Compose v2 |
starting a worktree's stack | projects that have one |
Nothing else, on your machine or in the target project: no Node, no plugin, no file to add to the repository you point it at. A project without a compose file works too, there is simply no stack to start.
Compose !override is used to rebase ports declared as literals, which needs
Compose v2.24 or later.
Installation
No clone required:
go install github.com/Hy0sh/worktree-manager/cmd/wtm@latest
That puts the binary in $(go env GOPATH)/bin, usually ~/go/bin, which is
not always on your PATH. Either add it, for your shell:
echo 'export PATH="$(go env GOPATH)/bin:$PATH"' >> ~/.zshrc # zsh
echo 'export PATH="$(go env GOPATH)/bin:$PATH"' >> ~/.bashrc # bash
fish_add_path (go env GOPATH)/bin # fish, persists on its own
then open a new terminal. Or send the binary somewhere already on it:
GOBIN=$HOME/.local/bin go install github.com/Hy0sh/worktree-manager/cmd/wtm@latest
Check it with wtm --version, which reports the tag it was installed from, or
the commit when built from a working copy.
Without Go, take the binary from the
latest release,
which carries one per platform (darwin and linux, arm64 and amd64) plus a
SHA256SUMS to check them against:
tar -xzf wtm_v1.5.0_darwin_arm64.tar.gz wtm # the tag, v included
mv wtm ~/.local/bin/
Archives released after 1.5.0 also carry a build provenance attestation, which
ties each one to the workflow run that built it, independently of SHA256SUMS:
gh attestation verify wtm_<tag>_darwin_arm64.tar.gz --repo Hy0sh/worktree-manager.
Those are built by go install from the tag itself, so they report their
version exactly like an installed one.
Once installed, wtm update replaces the binary being run with the latest
release for its platform, after checking it against SHA256SUMS; neither Go nor
gh is needed for that, and wtm update --check only says whether one is out.
wtm update --force installs the latest release even when the running build
is not behind it, a build from a working copy for instance.
A symbolic link is kept, the file it points to is what gets replaced. Versions
before it have no such command: upgrade them once the way they were installed.
When a newer release is out, a command run in a terminal says so on one line of
stderr, under its own output. The published version is looked up at most once
a day, in the background, and kept in latest.json next to config.json; a
command never waits for it. Nothing is printed, nor looked up, when stdout or
stderr is not a terminal, so scripts and agents never see it.
wtm tui shows the same line under its keys, in green, and asks the cache
again with each refresh, so a release out while it is open shows up there.
WTM_NO_UPDATE_CHECK=1 turns both off.
From a clone, for hacking on it: go install ./cmd/wtm, or go build -o wtm ./cmd/wtm to build without installing. Rerun it after each change to refresh
the installed binary.
Shell completion
Completion scripts are generated for bash, zsh, fish and powershell. Each
shell has its own conventions; wtm completion <shell> --help prints the
exact steps for yours. The usual ones:
# zsh: any directory on your fpath works
mkdir -p ~/.zsh/completions
wtm completion zsh > ~/.zsh/completions/_wtm
# then, in ~/.zshrc, before compinit runs:
# fpath=(~/.zsh/completions $fpath)
# autoload -Uz compinit && compinit
# bash: requires the bash-completion package
wtm completion bash > ~/.local/share/bash-completion/completions/wtm
# fish
wtm completion fish > ~/.config/fish/completions/wtm.fish
With oh-my-zsh, ~/.oh-my-zsh/completions is already on the fpath, so
dropping _wtm there is enough and no .zshrc change is needed.
Open a new shell afterwards. The script queries the binary at completion time, so it only needs regenerating when you upgrade to a version that adds commands. Arguments complete too, not just subcommands and flags:
wtm <TAB> # subcommands
wtm stop <TAB> # projects, plus branches that have a worktree
wtm stop myapp <TAB> # that project's worktree branches
wtm backup refresh <TAB> # registered project names
Usage
# register a project (once)
wtm project create # asks, the name included
wtm project create my-app # asks for the rest
wtm project create my-app --dir ~/dev/projects/my-app --base develop
wtm project list
wtm project remove my-app # refused while it has worktrees: the next project would reuse its port offset
wtm project remove my-app -y # without the confirmation
# change a registered project, its backup settings included
wtm project edit my-app # asks, step by step
wtm project edit my-app --dump --app-service backend
# create a worktree + start its stack
wtm create my-app feat/my-branch # base = the project's own
wtm create feat/my-branch # project = current repo
wtm create feat/my-branch main # explicit base
wtm create feat/my-branch --from-here # base = the current directory's branch
wtm create feat/my-branch --no-start # without starting the stack
wtm create feat/my-branch --no-post-create # stack started, post_create skipped
wtm create feat/my-branch --run claude # a command on your machine, once ready
wtm create feat/my-branch --exec 'manage.py load_fixture demo' # in the container
wtm create feat/my-branch --ignore-memory # never ask, however tight the RAM
# adopt a worktree wtm did not create
cd ~/dev/my-app/.claude/worktrees/curry && wtm adopt
wtm adopt my-app worktree-curry # or name it from anywhere
wtm adopt --as feat/my-feature # renaming the branch on the way in
wtm adopt worktree-curry -y # do not ask, for a script
wtm adopt --no-start # adopt now, bring the stack up later
wtm switch feat/next --from origin/main # same worktree, next branch, fresh stack
# lifecycle
wtm list # worktrees of this project
wtm tui # the same, live, with the selected one's addresses
# s start · x stop · d remove, their output under the table
# enter shell · l logs, both in the terminal
# o picks one of its urls, enter opens it in the browser
# a adopts a worktree left to adopt, asking first
# j/k or ↑/↓ move · r refresh · q or esc quit
# while a job runs: esc hides its output, p shows it,
# ctrl+c interrupts it (twice kills); esc closes a finished one
wtm start feat/my-branch # bring a stopped stack back up
wtm start feat/my-branch --profile light # only the services that profile names
wtm stop feat/my-branch # containers kept stopped, start brings them back
wtm stop --all # every worktree of the project
wtm remove feat/my-branch # stack, volumes and built images go, branch kept
wtm remove feat/my-branch --force # despite modified tracked files, or a lock
wtm remove --all # lists them, asks once, -y answers for a script
wtm remove --merged # the clean ones merged into the base, after a report
# inside the worktree's containers
wtm exec feat/my-branch -- python manage.py seed_data
wtm exec feat/my-branch -- bash
wtm exec feat/my-branch --service db -- psql -U postgres
# on your machine, from the worktree directory, with COMPOSE_PROJECT_NAME
# and COMPOSE_FILE pointing at this worktree's stack. Ports written as
# ${VAR:-default} get their variable set to this worktree's port (a generic PORT
# included); ports written as literals are reached through run_env (see "How
# ports are isolated")
wtm run feat/my-branch -- claude
wtm run feat/my-branch -- git status
wtm run feat/my-branch -- scripts/some-compose-script.sh
wtm logs feat/my-branch # follows the stack's logs, from the last 200 lines
cd $(wtm path feat/my-branch) # a bare `docker compose` there reaches the worktree's
# stack too, through a generated compose.override.yaml,
# unless the project has an override of its own: wtm
# then leaves it alone and warns, and the rebased ports
# live only in .wtm-ports.yaml, written either way. A
# script reading ports from compose.override.yaml
# finds none there, .wtm-ports.yaml is the stable place
eval "$(wtm env feat/my-branch)" # the same environment as run, for a shell or direnv:
# the only way a bare compose interpolates ${PORT}s right
wtm ports # typed from a worktree, ports, path, env, exec, run and logs take its branch
wtm ports feat/my-branch # the addresses `start` printed, one service per line
# database backup
wtm backup refresh my-app # starts the db if needed, and stops it again after
wtm backup list
wtm backup remove my-app # asks first, -y answers for a script
If the first argument is a registered project, it's treated as such;
otherwise it's a branch of the current directory's project. create puts the
worktree under the repository's own .worktrees/ directory; anything outside
it is a worktree to adopt.
Creation deliberately sits behind the create verb. It used to be the bare
form, wtm <branch>, until a mistyped wtm list created a branch called
list along with its worktree: any unknown word silently mutated the
repository. Now only a real subcommand runs, and anything else is rejected.
<base> completes to the local branches plus the remote ones no local branch
stands for. It is resolved in the main repository, never in the worktree the
command was typed from, so from a worktree on feat/a a create starts from the
project's base and not from feat/a. --from-here is for the other intent:
wtm create feat/my-branch --from-here
It resolves the branch of the current directory and passes it by name, which is
what the -C on the main repository would otherwise defeat. It refuses
alongside a positional base, and on a branch that already exists, since the
base is ignored there and a flag doing nothing quietly is worse than no flag.
The base is cut from the local ref, which nothing refreshes: only the branch being created is ever fetched. So a create says when that ref trails its remote, and does not move the cut:
note: develop is 12 commit(s) behind origin/develop, this worktree starts from the local ref
Starting from the tracking ref instead cannot conflict, but it moves the starting point: unpushed commits on the base would silently be left out. Which ref to cut from stays yours.
create picks up an existing branch rather than shadowing it. A local
branch is checked out as-is; a branch that only exists on a remote is
checked out tracking it, fetching first in case it was pushed since your
last fetch. <base> is ignored in both cases, and only used for a branch
that exists nowhere yet. Should two remotes carry the same branch name, wtm
refuses to guess, as git does.
--run plays its line with the compose environment wtm run sets, --exec
after the project's own post_create. Both may be given at once, --exec
first so a fixture depending on the seed finds it, and --run last since it is
the one taking over the terminal. A failure is a warning naming the line that
replays it, never a failed creation. Neither is remembered: they are flags of
one create and never reach config.json, so nothing in a repository can hand
wtm a command to play on its own. What the command itself does is another
matter, and --run runs on the host with your rights, in a checkout of a
branch that may not be yours: creating someone else's branch and playing its
package.json scripts in one line is exactly as trusting as it sounds.
--exec is bounded by the container.
remove --merged prints every worktree with REMOVE or KEEP and the
reason, then asks once for the REMOVE ones; -y skips the question and never
the report, and nothing to remove asks nothing. A worktree qualifies only when
git status shows nothing, untracked files included, and a merge commit
brought its branch into the base, local or its tracking ref as they stand:
nothing is fetched. A branch that never diverged sits on the base's
first-parent line exactly like a fast-forwarded one, so both are kept, and a
squashed or rebased branch is kept too, its commits being no longer the ones
the base holds. Switched, detached and locked worktrees are kept as well. The
branch itself survives, as with any remove. It picks the worktrees itself and
never forces, so it refuses --all and --force.
exec and run are deliberately distinct: exec enters the stack's
container, run stays on your machine with the worktree as working
directory, which is what an editor or a coding agent needs. wtm list
reports whether each stack is up, and falls back to - rather than hanging
when docker is slow or down.
Adopting a worktree wtm did not create
Plenty of worktrees exist before wtm hears about them: a claude --worktree
one under .claude/worktrees, a git worktree add anywhere else. wtm adopt
gives one of those what a created worktree gets, without moving it:
cd ~/dev/my-app/.claude/worktrees/curry
wtm adopt
wtm list names them, marked adoptable, so nothing has to be remembered:
that is what to read to bring a second worktree of the same session in, or to
bring one back whose adoption was released to free a machine.
Staying put is the point. Something is usually working in that directory, an
agent included, and pulling it out from under them to satisfy a naming
convention would be a poor trade. The worktree gets a stable index, remapped
ports, the provisioned .env files and compose overrides, the restored dump
and its stack, and wtm list, stop, exec, run and path address it like
any other from then on.
Since the directory came from somewhere else, so does its fate: wtm remove on
an adopted worktree takes the stack, the volumes and the images down, takes
wtm's own files back out of the checkout, and leaves the checkout itself
exactly where it found it. Whatever created the worktree remains the one that
removes it.
An .env the worktree already carries is never overwritten, only its port
block is written; and adopting asks before writing anything, since the
directory is not wtm's own. -y answers that question for a script.
claude --worktree names its branches for itself, and that name becomes the
handle of every later wtm command. --as renames it on the way in:
wtm adopt --as feat/my-feature
Adopting is the moment for it. The branch is part of the compose project name, so renaming once a stack exists orphans the stack that name addressed. The directory keeps its own name, which nothing can fix without moving the worktree.
Everything create offers once the worktree stands is offered here too, from
the same declaration so the two verbs cannot drift apart: --no-start leaves
the stack down and still records the adoption, --no-post-create skips the
seed, and --run and --exec behave as described under Usage.
Only how the worktree appears differs; what happens to
it next does not.
A worktree on a detached HEAD cannot be adopted: wtm keys a worktree by its branch, and there is none to key it by.
That key is also why a bare git switch -c in an adopted worktree strands its
stack: the stack stays filed under the old branch. A stack belongs to the
directory it was started in, so wtm follows it there: wtm list shows it as
old (now on new), stop, start and remove reach it by the branch the
worktree holds, or by the old one while no other worktree has that checked out,
and adopt refuses to give that directory a second one. wtm switch is the way
to move one to its next branch, typed from inside it:
wtm switch feat/next-task --from origin/main
It checks the branch out first (an existing one as-is, one only a remote
carries tracked, any other cut from --from, the project's base by default),
then drops the old branch's stack with its database and starts a fresh one on
the restored dump. The index moves with the worktree, so the ports do not
change. Tracked files left modified refuse the switch before anything moves;
it never asks a question, which suits an agent; and if it fails halfway,
running the same command again finishes it, which also repairs a worktree a
bare git switch already moved. Only adopted worktrees switch: a created one
is named after its branch, and wtm create makes the next one.
Configuring the backup
Nothing is hardcoded: service names, database user, migration command, and how the database is designated are specific to each project. Real examples, all expressible in configuration:
# Django + poetry (dependencies installed at container startup)
wtm project create my-app --dir ~/dev/projects/my-app \
--dump --git-container --app-service backend \
--deps 'poetry install --no-root --with dev' \
--migrate 'python manage.py migrate' \
--env 'DB_NAME={{database}}'
# Prisma + bun, differently named database, non-postgres user
wtm project create my-api --dir ~/dev/projects/my-api \
--dump --db-user appuser --app-service api \
--deps 'bun install --frozen-lockfile' \
--migrate 'bunx prisma migrate deploy' \
--env 'DATABASE_URL=postgresql://appuser:secret@db:5432/{{database}}'
# MikroORM + pnpm, database service named "postgres"
wtm project create my-service --dir ~/dev/projects/my-service \
--dump --db-service postgres --app-service api \
--deps 'pnpm install' \
--migrate 'pnpm --filter @acme/api migration:up' \
--env 'DATABASE_URL=postgresql://postgres:postgres@postgres:5432/{{database}}'
{{database}} gets replaced by the temporary database's name. --db-service
defaults to db and --db-user defaults to postgres.
Seeding a fresh worktree
The dump carries what the migrations create and never seed data, so a new
worktree comes up migrated and empty. --post-create is the command that makes
it usable, played in the application service once the database answers and that
service reports itself healthy (or seed it by hand through wtm exec):
wtm project edit my-app --post-create 'python manage.py seed_data && python manage.py create_dev_users'
wtm waits, because a container docker calls started is not one that can run a
management command: a stack installing its dependencies from its command: (a
poetry install or an npm ci at boot) answers minutes later. A declared
healthcheck: is what it waits on. A service without one is waited on by its
first published port, read inside the container, since the host side of that
port accepts a connection while nothing listens behind it yet. A service with
neither, a queue worker for instance, leaves nothing to wait for: the command
runs as soon as the database answers, and a warning says so.
Both waits are bounded, and a project can say by how much:
wtm project edit my-app --ready-timeout 2m --ready-interval 10s
ready_timeout is how long each service gets, ready_interval how often it is
asked. Left unset, a database gets a minute and an application ten, asked every
second, and a wait that holds repeats itself every thirty seconds with the time
elapsed. A timeout, like a failing command, is not a failed creation: the
worktree stands, and the warning names the wtm exec line that replays the
command.
Do not point it at a script that resets the database: dropping the schema to migrate it again throws away the restored dump and pays for the migrations wtm exists to skip. Seed only.
Postgres, MySQL, MariaDB, MongoDB and SQLite are supported. The engine is
read from the database service's image in the compose file and offered as the
default at registration, then recorded as backup.db_engine (--db-engine
overrides it). Every engine command (the probe, the dump, the restore) reads
the database credentials from the container's own environment (POSTGRES_*,
MYSQL_ROOT_PASSWORD, MONGO_INITDB_*). What --env passes is stored,
though, in ~/.config/wtm/config.json, which is created 0600.
SQLite has no database service, so it is chosen explicitly with
--db-engine sqlite (there is no image to detect it from). Its snapshot is
the database file itself: the migration runs in the disposable app container
as usual, targeting a throwaway file that {{database}} points at, and the
result is collected through the app service's bind mount — mounting the
project directory into that service is required. Each worktree then gets the
file copied to db_path (default db.sqlite3), and only when nothing is
there yet: a database being worked in is never overwritten.
None of this has to be known in advance: wtm project create <name> without
--dir, and wtm project edit <name> without any flag, ask one question at a
time, offer the services found in the project's compose file, and only bring up
the migration command once the backup is enabled. The questions that assume
knowing how wtm works come with a line saying what they are for. Every question
defaults to what the project already has, so editing is a run of empty answers
plus the one field being changed. Flags and questions mix: what is passed on the
command line becomes the answer offered by default. --no-input turns a missing
value into an error rather than a question, for scripts and CI.
The project answers what it can, and each answer becomes the default offered:
| Question | Read from |
|---|---|
| repository directory | the repository the command runs in |
| base branch | its local branches, listed when there are eight or fewer |
| database service | the service running a database image, whatever it is called |
| database engine | that image |
| database user | POSTGRES_USER in its compose environment; not asked for the other engines, which connect as root |
| database file | asked instead of the user for SQLite, db.sqlite3 by default |
| service running the migrations | the one service built from the repository (build:), with the others listed |
| migration command and pathspec | the framework, from manage.py, bin/console, artisan, bin/rails, prisma/schema.prisma or alembic.ini at the root |
| services besides the database | only asked when the service depends on others, named in the question |
| variables | the database variables the service's compose environment: sets, the name replaced by {{database}} |
.git-container |
only asked when a volume mounts .git |
The walk ends on a summary of what the answers change, saved only
once confirmed; create then prints the next commands to run.
What the backup questions ask, for a Symfony project whose database service is
called database:
| Question | What it is for | Typical answer |
|---|---|---|
| git pathspec of the migration files | Nothing is run from it: a commit touching these files marks the dump stale. A project without migration files, its schema synced from the code, names what defines the schema instead. | Enter: *migrations/* covers migrations/ |
| does the migration command need services besides the database? | The migration runs next to the database alone; y when it also reaches a cache, object storage or a search index. |
n |
| variables pointing the migration at that database | The migration targets a temporary database; {{database}} stands for its name. |
DATABASE_URL=postgresql://app:app@database:5432/{{database}}?serverVersion=17 |
wtm project edit never touches the port offset nor the recorded worktree
indices, which is what re-registering a project would do: every running stack
would change ports and compose project name. The settings can also be reviewed
directly in config.json.
The base branch is the one question whose empty answer records nothing: a
project that names none follows default_base_branch from config.json, and
develop when that is unset too. Answering it pins the project instead
(--base does the same), which is what you want for the odd repository that
branches off something else.
--git-container is only useful for projects whose compose bind-mounts the
git-dir into a container: in a worktree .git is a pointer file Docker on macOS
cannot mount, so wtm links .git-container to the real git-dir. Left off, it
creates nothing, and the stepper only asks about it when a volume in the compose
file mounts .git or .git-container.
backup list also reports how far each dump has fallen behind, by counting the
commits touching migrations since the revision recorded next to it, and create
says so when replaying that delta would cost time. A stale dump still works, the
application simply migrates on top of it, so this is never a blocker. The
migration files are found through migrations_path (--migrations-path),
whose default matches Django, Prisma and MikroORM alike. A layout it does not
match, db/migrate/* for Rails or src/main/resources/db/migration/* for
Flyway, has to say so: no commit ever touches the default pathspec there, so
every dump would be reported as up to date forever.
Starting part of a stack
A worktree rarely needs every service its project declares. profiles names
the subsets worth starting, and --profile picks one on create, adopt,
switch or start:
"profiles": {
"light": ["db", "backend", "frontend"],
"async": ["db", "backend", "frontend", "celery_worker", "celery_beat"]
}
wtm project create and wtm project edit write them with --profile-set,
repeatable and replacing the whole set:
wtm project edit my-app --profile-set light=db,backend,frontend \
--profile-set async=db,backend,frontend,celery_worker,celery_beat \
--profile-description 'async=Celery tasks and periodic jobs'
wtm project profiles [project] is what to read before choosing one: for each
profile, the services it names, those depends_on pulls in on top, those it
leaves out, and its description.
async db, backend, frontend, celery_worker, celery_beat
plus, through depends_on: mail, storage
leaves out: admin_ui
Celery tasks and periodic jobs
light db, backend, frontend
plus, through depends_on: mail, storage
leaves out: admin_ui, celery_worker, celery_beat
(none) all 8 services
What that saves is memory, not time. Measured on a Django project, dropping the admin UI, a kubectl sidecar and the periodic-task worker took the stack from 1510 MiB to 969; the containers start in parallel, so the start itself only lost a second out of ten. On an 8 GB Docker VM that is five worktrees at once instead of eight, which is the whole point when several agents share a machine.
These are not compose's profiles. Those live in the project's compose file and state a choice its team made once; these live in the registry and state one a worktree makes. Nothing is remembered: no flag means the whole stack, which is what it has always meant, and a worktree that quietly came up narrowed months after someone typed a flag would be a puzzle worth more than the word it saves. A name the project does not declare fails before anything starts, since bringing up everything in silence is the one outcome worth refusing.
The list is a floor, not an exact set: compose up -d db backend also brings
up whatever backend declares in depends_on. Leaving a service out only
keeps it down when nothing started depends on it. Narrowing is not retroactive
either — starting again with a wider profile adds what was missing and leaves
the rest running, which is how a service a profile forgot is brought in. Two
caveats there: removing one needs a wtm stop first, and any service with a
build: section is recreated by the --build every start passes, so widening
restarts the application containers even though they were already up.
Sharing dependencies across stacks
An image that installs the dependencies, mounted over named node_modules
volumes, still makes every fresh stack copy that tree into its own empty
volumes: on a JavaScript monorepo, minutes of Creating for 100k files. Every
compose call of a stack gets WTM_DEPS_KEY, a short hash of the lockfiles at
the worktree root (pnpm-lock.yaml, package-lock.json, yarn.lock,
composer.lock, poetry.lock, uv.lock, Gemfile.lock, go.sum…), so the
compose file can name those volumes after it and let every stack on the same
lockfile mount one copy:
services:
api:
image: shop-dev-api:${WTM_DEPS_KEY:-local}
build:
context: .
labels: [wtm.shared=true]
volumes:
- deps:/app/node_modules
volumes:
deps:
external: ${WTM_DEPS_EXTERNAL:-false}
name: shop-deps-${WTM_DEPS_KEY:-local}
- wtm exports
WTM_DEPS_EXTERNAL=true, so under wtm the volume is external: created by wtm beforeupwhen docker lacks it, and docker fills an empty one from the image on first mount. The first stack of a lockfile pays the copy, the next ones none. Compose never removes an external volume, sowtm removekeeps it. - A bare
docker compose upoutside wtm seesexternal: falseand createsshop-deps-localitself instead of failing on a volume that does not exist. - An image labelled
wtm.sharedsurviveswtm remove, which otherwise drops every image the stack built and makes the next one unpack it again. - A branch that changes its lockfile gets another key, hence its own volumes: it never installs into a tree another stack is running on.
- Keep a tree a running tool writes into (a bundler cache) per stack.
- A volume wtm creates is labelled
wtm.deps-key=<key>when its name carries the key.wtm doctorlists those that no container mounts and that no worktree, nor any registered project's main checkout, uses any more;wtm cleanwithout a project drops them. Volumes created by an earlier wtm carry no label and stay manual:docker volume rmthem. Images stay:docker rmithem by name.
How ports are isolated
Every published port is rebased so a worktree stack never fights the main one:
20000 + project offset + default port + worktree index * stride, with a
fallback above 65535. Ports declared as ${VAR:-default} are written into the
worktree's .env, and ports written as literals into a generated compose file
that replaces the service's ports list, since compose appends otherwise.
The index is allocated when the worktree first needs a stack and recorded in
config.json (worktree_indices), so it never changes afterwards. Deriving
it from git worktree list order — what earlier versions did — renumbered
worktrees whenever a new one sorted before them, handing a new stack the very
ports of a running neighbour. A worktree created before indices were recorded
is backfilled from the compose project label its containers and volumes still
carry, or from its listing position when docker holds no trace. A freed index
is only reused once docker — when it can be asked — no longer holds any
container or volume of a previous worktree there; while docker is
unreachable, wtm resolves indices in memory and records nothing.
An index is also stepped over when a recorded worktree already publishes one of
the ports it would take, which happens as soon as two services sit closer
together than the stride: with the default stride of 1, a project publishing
db on 5432 and db_test on 5433 has index 2 land on index 1's db_test
port. The line index N skipped: ... names the port and the neighbour holding
it, and the next index is tried.
The stride is read from portStride in the project's .wtcrc.json, or
wtc.portStride in its package.json, the files worktree-compose used, so an
existing setup keeps its ports. Raise it above the spread of your closest
ports, then recreate the worktrees, whose .env carry the old ones.
Three details earned their place the hard way. The reference is the project's
merged compose configuration, not just the base file: a project already
remapping a port on purpose keeps that mapping. The project offset exists
because the formula otherwise knows nothing about the project, so two projects
whose database listens on 5432 would land on the same host port; it is assigned
at registration, and the first project keeps 0 so its existing worktrees are
untouched. It is recorded as the project's port_offset in config.json, the
key to raise by hand when two projects still clash. And a .env tracked by git is left alone, the generated compose
file carrying the ports instead, so starting a stack never dirties the
worktree. The port variables still reach compose through the environment of
every call wtm makes, which compose reads ahead of .env: an
environment: API_URL: http://localhost:${API_PORT} gets the worktree's port
either way.
Host commands: run_env
For a port published as a literal, wtm exports no variable, so a script run on
your machine falls back to its default port, which is the main stack's (it
fails when that stack is stopped, and writes into it when it runs). When the
project has no override of its own, wtm generates compose.override.yaml with
the rebased ports, and a script that reads it already aims at the worktree's
stack. When the project has its own override, wtm copies it unchanged and the
rebased ports live only in .wtm-ports.yaml, in the same ports: shape: a
script reading compose.override.yaml finds the main stack's ports. Either
read .wtm-ports.yaml, or use run_env, a per-project set of variables whose
values may name a port of the stack:
wtm project edit my-app \
--run-env 'AUTH_ADMIN_URL=http://localhost:{{port:auth:4434}}' \
--run-env 'DATABASE_URL=postgresql://app:secret@localhost:{{port:db:5432}}/my_app'
wtm run feat/my-branch -- pnpm some-script # gets both, on this worktree's ports
eval "$(wtm env feat/my-branch)" # the same, for a shell
{{port:<service>:<container port>}} is the host port this worktree publishes
for that container port, whether the compose file wrote it as a literal or as a
variable. A template that does not resolve (the service does not publish that
port on this branch) is an error and the command does not run: a variable left
out would send the script back to the main stack. --run-env replaces the
whole set, and --run-env '' clears it.
Only commands started with wtm run, wtm create --run or wtm env receive
these variables, and never a docker compose call, whose environment would
carry a host URL into a container. A command typed bare in the worktree still
aims at the default ports. A variable of the same name in your own environment
is overridden. Values can hold a password: they live in config.json, and a
value given on the command line shows in ps and the shell history.
Addresses behind a proxy
A service reached through a reverse proxy publishes no port of its own, so
nothing in the port list says where to open it. Behind Traefik, wtm reads it
from the routers: each Host() of a router, on the host port the proxy
publishes for that router's entrypoint, https when the router or the
entrypoint sets tls. Nothing to declare:
services:
proxy:
image: traefik:v3
command: ["--entrypoints.web.address=:80"]
ports: ["80:80"]
front:
labels:
- "traefik.http.routers.front.rule=Host(`front.${APP_NAME}.localhost`)"
start and wtm ports then print front/url http://front.myapp.localhost:20081,
in a urls block ahead of the ports. Entrypoints defined in a mounted
traefik.yml are out of sight, so the proxy's published 80, or 443 for tls,
stands in.
The proxy is told by its image, whatever registry it comes from:
| Proxy | Image | Host names from | Port |
|---|---|---|---|
| Traefik | traefik |
each router's Host() |
the router's entrypoint |
| nginx-proxy | nginx-proxy, or nginx next to docker-gen |
VIRTUAL_HOST |
80, or the proxy's HTTP_PORT; 443 when only https is published |
| caddy-docker-proxy | caddy-docker-proxy |
the caddy, caddy_0… labels |
443 in https, as Caddy serves a bare name; 80 for http:// or under auto_https off |
A proxy configured from a mounted file, a stock caddy with its Caddyfile
say, shows wtm nothing to read: its services are listed by port only. Routes
are read from docker compose config, so ${APP_NAME} resolves as it does
for the stack itself. A service the profile left down, or a proxy it left
down, prints no address.
Diagnostics
wtm doctor
Reports, in order: the version running and whether a newer one is published,
with the wtm update that installs it; the config and
backups paths, the memory actually used by the Docker VM, the size of the build
cache, then per project its port stride, offset and, when its backup is
enabled, database engine. Below that come the problems nothing else mentions: the ports two
projects would both publish, the ports two worktrees of one project would both
publish (with the portStride remedy), the recorded indices no worktree stands
behind — each pushing new worktrees one index further out — the worktrees whose
branch was switched under them, the worktrees whose index the registry does not
carry, and what removed worktrees left behind: their stacks, still holding
containers, their volumes (which squat the indices their ports came from) and
the images their stacks built. Each of those lines carries the command that
drops them.
A switched worktree is not a leftover: its index and its stack stay, filed
under the old branch, and stop, start and remove reach that stack by the
branch the worktree holds. Its line carries the command that moves the stack to the branch
the worktree now holds: wtm switch <held> from an adopted worktree; for a
worktree wtm created, switching it back, or wtm remove <old> then
wtm start <held>.
A worktree with no recorded index is named for a reason: its stack cannot be
told from one a removed worktree left, so the three leftover reports hold back
for its whole project rather than risk a docker rmi on a live worktree.
wtm start <branch> records the index and lifts the hold. A project with no
compose file starts no stack at all, so its worktrees are not counted.
After those comes what git no longer lists: the worktree directories still on
disk, left by a pruned administrative directory. Nothing else can see them,
since every other command reads git worktree list, and they make wtm create
refuse their branch. wtm clean deliberately leaves them, because their git
metadata is gone and nothing can say any more whether they hold uncommitted
work: wtm remove <project> <branch> --force deletes one.
Then the dumps that commits to the migrations have overtaken, as backup list
counts them, each with its wtm backup refresh: advice, never a blocker, for
the reason given under Seeding a fresh worktree.
Then the dependency volumes of a lockfile no worktree and no main checkout uses any more, when no container mounts them; nothing is reported if a registered project cannot be listed.
Last come the anonymous volumes no container mounts, left by images that name their own data directory: those belong to no project, so they are counted even with an empty registry, with the command that drops them.
wtm clean # every registered project, as doctor reads them
wtm clean my-app # that project alone
wtm clean -y # do not ask, for a script
wtm clean plays those commands for you, on the findings that are leftovers
rather than advice: the recorded indices, and the stacks, volumes and images of
worktrees that no longer exist. Without a project argument it also drops the
unused dependency volumes, under their own heading; wtm clean my-app leaves
them, since a lockfile belongs to no single project. It prints what it found
and asks once. Port clashes stay out, being a configuration matter, and stale
dumps, whose refresh starts a database; so do the anonymous volumes and the
build cache, which belong to no project, and the directories git has
forgotten, which no check can declare expendable. The forgotten directories
and the anonymous volumes are named at the end of the run anyway, with the
command that settles each: a finding reported by doctor and unmentioned by
clean reads as the two disagreeing.
Indices go first, because releasing one takes down the stack left at that index and sweeps whatever carries its label. Docker is then scanned again before anything is dropped by name, so a volume the release already took is never asked for twice, and a cleanup that went through is never reported as failed. The stacks come next, and the volumes and images after them: a volume some container still mounts refuses to go.
A create does not wait for that verb: before allocating its own index, it releases the ones its project records with no worktree behind them. That is where the leftover costs something, since an index the allocator skips lands the new worktree further out, on ports its neighbours never used. A release that fails prints a warning and the create carries on.
The build cache is only ever reported. Buildkit attributes none of it to a project, so only you can decide it is expendable.
Before a stack goes up, wtm measures what the memory it has to fit into already
holds and says when one more would not. On a native Linux docker that pool is
the whole machine, session and browser included; Docker Desktop gives the
containers a budget of their own. When it is tight, a create, an adopt, a switch or a start asks
whether to go ahead, and answering no leaves the worktree without its stack, to
be started later with wtm start. The question only comes on a terminal: the
estimate is an average over the running stacks, worth a person's judgement and
never worth failing a script or an agent over. --ignore-memory answers it in
advance, for an automation that runs under a terminal with nobody behind it.
That average is the consumption observed, never the declared mem_limits: one
stack here declares over 13 GB of cumulative caps while actually running in
2 GB. Ephemeral compose run containers are left out of it.
How the database restore works
A worktree starting from an empty database replays the entire migration
history, which on a large project means tens of minutes and a memory peak
that can get the container OOM-killed. backup refresh records that work
once as a dump, and every worktree restores it in seconds.
The dump holds the database exactly as migrate left it, data included: not
just the schema, but everything the migrations create, permissions and
reference data among them. It stops there. Seed data is not in it, because
seeds change far more often than migrations and are quick to replay, whereas
the migration history is not: measured on a real project, seeding took 33
seconds against the twenty minutes the migration history costs. How a fresh
worktree gets seeded is in Seeding a fresh worktree.
A project whose seed is slow can put it in the dump anyway: migrate_command
is a shell line, so manage.py migrate && manage.py seed_data seeds the
throwaway database before it is dumped, and post_create then has nothing left
to play. What that saves is more than the seed itself — with no post_create
and no --exec, a create hands back as soon as the stack is up instead of
waiting for the application to answer. On one Django project of ~200
migrations, wtm create went from 98 seconds to 22, of which the seed was 27.
The counterpart is that backup list still dates the dump on migrations_path
alone, so a commit touching the seeder leaves it reported as up to date.
Such a command often needs more than the database. A migration only ever talks
to one, which is why the refresh runs its container with --no-deps; a seed may
reach for object storage, a cache or a search index, and fails without them.
start_dependencies (--start-dependencies) lifts that, bringing up what the
application service declares in depends_on for the duration, and taking back
down whatever it started. It is off by default, since it costs containers and
memory a plain migration has no use for.
A seed may also write to a second database on the same server, the one an
identity provider keeps its accounts in, while the app database stores their
ids. extra_databases (--extra-database auth, repeatable) dumps each of them
next to the main one, and a new worktree restores them all, creating a
database that is not there yet. Postgres only. Their name is fixed in the
compose file, where {{database}} cannot reach, so they are dumped as the
refresh leaves them on the project's own database server, not through a
throwaway copy: the seed runs against the real one and has to tolerate finding
its accounts already there. A refresh publishes the whole set or nothing. An
init script of the project's own that creates such a database runs after the
restore, so it has to skip one that already exists.
Nothing is asked of the project. wtm links .db-snapshot to the central
backup directory, writes a restore script next to the dump, and generates a
.wtm-snapshot.yaml in the worktree that mounts both into the database
service. That file is passed to docker as an extra -f when the stack starts,
after the project's own compose files.
Creation lays those down and so does every start, links, *.env copies and
compose overrides alike: they belong to the stack rather than to the checkout,
and a worktree that lost them, cut by an older wtm or cleaned up by hand, would
otherwise fail deep inside docker on a raw mount error. What the worktree
already holds is left as it is, an env file tweaked for the task at hand being
its own state and not a stale copy.
Other files git leaves out, a .env.local or an editor's local settings, only
follow when the project lists them, as patterns relative to its root:
wtm project edit my-app --copy .env.local --copy 'config/*.local.json'
A match git tracks stays the branch's own, and a directory is not copied: name the files in it.
None of it belongs in a commit, and a project's .gitignore knows nothing
about names wtm invented, so wtm records them in the repository's
.git/info/exclude: not versioned, hence nothing to leak into the project's
history, and read from the common git-dir, so the same block covers every
worktree plus the .worktrees directory and the .git-container link left in
the main checkout. A repository that refuses that write still gets its stack,
with a warning.
Putting the mount in the project's compose instead would tie the behaviour to the branch the worktree was cut from, since that file is versioned.
The official postgres, mysql, mariadb and mongo images all run
docker-entrypoint-initdb.d only on an empty data directory, which gives the
right semantics for free: a fresh worktree restores, an existing one is
untouched, and no race with the application's own migrations is possible
since the database reports healthy only once the restore is done.
Storage
| What | Where |
|---|---|
| Project registry | ~/.config/wtm/config.json |
| Dumps + metadata | ~/.config/wtm/backups/<project>/<project>.dump |
| Worktree indices | ~/.config/wtm/config.json, worktree_indices per project |
| Registry write lock | ~/.config/wtm/config.lock, an OS file lock; the file staying around is normal |
A single dump per project, never duplicated: each worktree accesses it
through a .db-snapshot directory symlink. WTM_CONFIG_DIR and
WTM_BACKUPS_DIR let you relocate these paths.
Contributing
Pull requests are welcome. main is the only long-lived branch: branch off it,
keep the branch short, open a PR. What changed between published versions is in
CHANGELOG.md.
go test -race ./...
go vet ./...
gofmt -l .
go build ./...
The test suite needs neither git, docker nor node: every external command goes
through an injectable runner (internal/execx), which keeps it fast and
hermetic. Please keep it that way.
CI runs those four, plus govulncheck, staticcheck, and a docker integration job
driving the real binary through testdata/integration/run.sh (create, backup
refresh, list, remove, doctor, clean); it has to be green to merge. One thing
neither covers, to check by hand: wtm create <project> <branch> --no-start
leaves the *.env files and the .git-container and .db-snapshot symlinks in
the worktree.
Publishing a version is a changelog entry and a tag:
# CHANGELOG.md: turn Unreleased into the version being cut, then commit it
git tag -a v1.1.0 -m "One line on what this version brings"
git push origin v1.1.0
From 1.0.0, breaking a command, a flag or the config.json format takes a
major version. The tag is what publishes: the module proxy resolves it, so go install ...@v1.1.0 works straight away. Pushing it also runs the release workflow,
which creates the GitHub release with that version's changelog section as its
notes and <tag>: <annotation> as its title (the tag alone without one). A tag with no section in the
changelog fails the workflow rather than getting notes invented from the commit
log; document it, then replay the run from the Actions tab.
Credits
The initial idea came from Clément's
Claude Code skills built around wtc: they were what showed that a worktree
could carry its own isolated compose stack, and wtm grew out of making that
work without a node dependency.
License
MIT, see LICENSE.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
wtm
command
Command wtm is the single entry point for the lifecycle of a project worktree: create, start, stop, remove, plus the pre-migrated database dump that makes a fresh one cheap to bootstrap.
|
Command wtm is the single entry point for the lifecycle of a project worktree: create, start, stop, remove, plus the pre-migrated database dump that makes a fresh one cheap to bootstrap. |
|
internal
|
|
|
backup
Package backup produces and manages the pre-migrated database dump shared by every worktree of a project.
|
Package backup produces and manages the pre-migrated database dump shared by every worktree of a project. |
|
compose
Package compose locates compose files and inspects how they declare ports.
|
Package compose locates compose files and inspects how they declare ports. |
|
config
Package config reads and writes the project registry used by wtm.
|
Package config reads and writes the project registry used by wtm. |
|
dbengine
Package dbengine describes how each supported engine is probed, dumped and restored.
|
Package dbengine describes how each supported engine is probed, dumped and restored. |
|
dockermem
Package dockermem measures the memory a stack has to fit into, and what is already in it.
|
Package dockermem measures the memory a stack has to fit into, and what is already in it. |
|
execx
Package execx wraps os/exec behind an interface, so command sequences can be asserted in tests without git, docker or node being installed.
|
Package execx wraps os/exec behind an interface, so command sequences can be asserted in tests without git, docker or node being installed. |
|
gitx
Package gitx answers the few git questions wtm asks about the current directory.
|
Package gitx answers the few git questions wtm asks about the current directory. |
|
index
Package index owns the branch→index mapping of a project's worktrees.
|
Package index owns the branch→index mapping of a project's worktrees. |
|
mark
Package mark maintains a delimited block inside a file whose other lines belong to someone else: a project's .env, a repository's info/exclude.
|
Package mark maintains a delimited block inside a file whose other lines belong to someone else: a project's .env, a repository's info/exclude. |
|
proxy
Package proxy reads the host names a reverse proxy routes to the services of a compose project, and the host port each one is reached through.
|
Package proxy reads the host names a reverse proxy routes to the services of a compose project, and the host port each one is reached through. |
|
safefile
Package safefile writes at paths a git checkout controls, where a component may be a symlink a hostile branch committed: a link at the leaf is replaced by a regular file, a directory chain resolving outside the root is refused.
|
Package safefile writes at paths a git checkout controls, where a component may be a symlink a hostile branch committed: a link at the leaf is replaced by a regular file, a directory chain resolving outside the root is refused. |
|
stack
Package stack owns everything about a worktree's docker stack: how it is named, which ports it gets, and how it goes up and down.
|
Package stack owns everything about a worktree's docker stack: how it is named, which ports it gets, and how it goes up and down. |
|
tui
Package tui is the `wtm tui` dashboard.
|
Package tui is the `wtm tui` dashboard. |
|
worktree
Package worktree creates, starts, stops and removes project worktrees, and drives the docker stack that goes with each one.
|
Package worktree creates, starts, stops and removes project worktrees, and drives the docker stack that goes with each one. |