worktree-compose 0.1.4 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +560 -125
  2. package/SKILL.md +113 -0
  3. package/dist/cli.js +94 -33
  4. package/dist/commands/clean.d.ts +2 -1
  5. package/dist/commands/clean.js +8 -48
  6. package/dist/commands/doctor.d.ts +3 -0
  7. package/dist/commands/doctor.js +30 -0
  8. package/dist/commands/list.d.ts +4 -1
  9. package/dist/commands/list.js +62 -44
  10. package/dist/commands/promote.d.ts +3 -1
  11. package/dist/commands/promote.js +4 -34
  12. package/dist/commands/prune.d.ts +2 -0
  13. package/dist/commands/prune.js +7 -0
  14. package/dist/commands/restart.d.ts +2 -1
  15. package/dist/commands/restart.js +11 -5
  16. package/dist/commands/skill.d.ts +4 -0
  17. package/dist/commands/skill.js +10 -0
  18. package/dist/commands/start.d.ts +2 -1
  19. package/dist/commands/start.js +7 -34
  20. package/dist/commands/stop.d.ts +1 -1
  21. package/dist/commands/stop.js +6 -23
  22. package/dist/compose/detect.d.ts +1 -2
  23. package/dist/compose/detect.js +1 -10
  24. package/dist/compose/engine.d.ts +61 -0
  25. package/dist/compose/engine.js +129 -0
  26. package/dist/compose/isolation.d.ts +15 -0
  27. package/dist/compose/isolation.js +62 -0
  28. package/dist/compose/parse.d.ts +5 -0
  29. package/dist/compose/parse.js +200 -12
  30. package/dist/compose/status.d.ts +84 -0
  31. package/dist/compose/status.js +227 -0
  32. package/dist/compose/types.d.ts +25 -0
  33. package/dist/config.d.ts +38 -0
  34. package/dist/config.js +23 -6
  35. package/dist/context.d.ts +90 -3
  36. package/dist/context.js +293 -20
  37. package/dist/core/clean.d.ts +91 -0
  38. package/dist/core/clean.js +343 -0
  39. package/dist/core/compose.d.ts +30 -0
  40. package/dist/core/compose.js +45 -0
  41. package/dist/core/doctor.d.ts +28 -0
  42. package/dist/core/doctor.js +277 -0
  43. package/dist/core/list.d.ts +42 -0
  44. package/dist/core/list.js +94 -0
  45. package/dist/core/promote.d.ts +40 -0
  46. package/dist/core/promote.js +117 -0
  47. package/dist/core/prune.d.ts +32 -0
  48. package/dist/core/prune.js +75 -0
  49. package/dist/core/restart.d.ts +14 -0
  50. package/dist/core/restart.js +18 -0
  51. package/dist/core/start.d.ts +31 -0
  52. package/dist/core/start.js +99 -0
  53. package/dist/core/stop.d.ts +32 -0
  54. package/dist/core/stop.js +57 -0
  55. package/dist/core/teardown.d.ts +121 -0
  56. package/dist/core/teardown.js +298 -0
  57. package/dist/core/types.d.ts +15 -0
  58. package/dist/core/types.js +1 -0
  59. package/dist/git/promote.d.ts +49 -2
  60. package/dist/git/promote.js +160 -38
  61. package/dist/git/repo.d.ts +72 -0
  62. package/dist/git/repo.js +167 -0
  63. package/dist/git/status.d.ts +8 -0
  64. package/dist/git/status.js +25 -0
  65. package/dist/git/worktree.d.ts +63 -3
  66. package/dist/git/worktree.js +173 -29
  67. package/dist/mcp/server.d.ts +2 -0
  68. package/dist/mcp/server.js +230 -116
  69. package/dist/ports/allocate.d.ts +34 -2
  70. package/dist/ports/allocate.js +69 -4
  71. package/dist/selectors.d.ts +10 -0
  72. package/dist/selectors.js +106 -0
  73. package/dist/skill.d.ts +13 -0
  74. package/dist/skill.js +28 -0
  75. package/dist/state/registry.d.ts +194 -0
  76. package/dist/state/registry.js +595 -0
  77. package/dist/sync/env.d.ts +77 -2
  78. package/dist/sync/env.js +151 -32
  79. package/dist/sync/files.d.ts +16 -1
  80. package/dist/sync/files.js +136 -36
  81. package/dist/utils/exec.d.ts +69 -4
  82. package/dist/utils/exec.js +221 -15
  83. package/dist/utils/log.d.ts +37 -0
  84. package/dist/utils/log.js +68 -4
  85. package/dist/utils/paths.d.ts +61 -0
  86. package/dist/utils/paths.js +163 -0
  87. package/dist/utils/sanitize.d.ts +7 -0
  88. package/dist/utils/sanitize.js +12 -0
  89. package/dist/version.d.ts +1 -0
  90. package/dist/version.js +3 -0
  91. package/dist/workspaces/resolve.d.ts +21 -0
  92. package/dist/workspaces/resolve.js +235 -0
  93. package/package.json +13 -9
  94. package/wtc.schema.json +62 -0
package/README.md CHANGED
@@ -1,71 +1,182 @@
1
- # worktree-compose (wtc)
1
+ <div align="center">
2
2
 
3
- [![npm](https://img.shields.io/npm/v/worktree-compose?label=npm)](https://www.npmjs.com/package/worktree-compose)
3
+ <img src="https://raw.githubusercontent.com/mostafasudo/worktree-compose/main/worktree-compose.jpg" alt="worktree-compose logo" width="140" />
4
4
 
5
- Zero-config Docker Compose isolation for git worktrees.
5
+ # worktree-compose · `wtc`
6
6
 
7
- Every worktree gets its own ports, database, cache, and containers — automatically.
7
+ ### Zero-config Docker Compose isolation for git worktrees
8
8
 
9
+ Every worktree gets its own ports, database, cache, and containers — **automatically**.
9
10
 
10
- https://github.com/user-attachments/assets/fe05a2ff-954b-4e4f-b01b-ad17f1233abf
11
+ [![npm version](https://img.shields.io/npm/v/worktree-compose?label=npm&color=cb3837&logo=npm)](https://www.npmjs.com/package/worktree-compose)
12
+ [![downloads](https://img.shields.io/npm/dm/worktree-compose?color=cb3837)](https://www.npmjs.com/package/worktree-compose)
13
+ [![node](https://img.shields.io/node/v/worktree-compose?color=339933&logo=node.js&logoColor=white)](https://nodejs.org)
14
+ [![license](https://img.shields.io/npm/l/worktree-compose?color=blue)](https://github.com/mostafasudo/worktree-compose/blob/main/LICENSE)
15
+ [![DevHunt](https://img.shields.io/badge/DevHunt-%231%20Product%20of%20the%20Week-ff6154)](https://devhunt.org/tool/worktree-compose)
11
16
 
17
+ **[worktree-compose.com](https://www.worktree-compose.com)** · [Changelog](https://github.com/mostafasudo/worktree-compose/blob/main/CHANGELOG.md) · [Agent skill](https://github.com/mostafasudo/worktree-compose/blob/main/SKILL.md) · [GitHub](https://github.com/mostafasudo/worktree-compose)
18
+
19
+ <img src="https://raw.githubusercontent.com/mostafasudo/worktree-compose/main/wtc-explainer.gif" alt="worktree-compose demo — isolated Docker stacks per git worktree" width="820" />
20
+
21
+ <em>The full <code>wtc</code> workflow: an isolated Docker stack per worktree, four AI agents building in parallel, compared live on their own ports — then promote the winner and clean up. <a href="https://www.worktree-compose.com/#demo">Watch the video</a>.</em>
22
+
23
+ </div>
12
24
 
13
25
  ```bash
14
- npm install -D worktree-compose
26
+ npm install -g worktree-compose
15
27
  ```
16
28
 
17
29
  ```
18
- npx wtc list
30
+ wtc list
31
+
32
+ ┌───────┬──────────────┬────────┬────────────────────────┬────────────────────────────────────────────────────────────┐
33
+ │ Index │ Branch │ Status │ URL │ Ports │
34
+ ├───────┼──────────────┼────────┼────────────────────────┼────────────────────────────────────────────────────────────┤
35
+ │ - │ main │ - │ - │ postgres:5434 backend:8000 frontend:5173 │
36
+ ├───────┼──────────────┼────────┼────────────────────────┼────────────────────────────────────────────────────────────┤
37
+ │ 1 │ feature-auth │ up │ http://localhost:25174 │ POSTGRES_PORT=25435 BACKEND_PORT=28001 FRONTEND_PORT=25174 │
38
+ ├───────┼──────────────┼────────┼────────────────────────┼────────────────────────────────────────────────────────────┤
39
+ │ 2 │ fix-billing │ exited │ http://localhost:25175 │ POSTGRES_PORT=25436 BACKEND_PORT=28002 FRONTEND_PORT=25175 │
40
+ └───────┴──────────────┴────────┴────────────────────────┴────────────────────────────────────────────────────────────┘
41
+ ```
42
+
43
+ > **Type `wtc`, not `npx wtc`.** An unrelated npm package is named `wtc`, so without the global install `npx wtc` downloads and runs that package instead. For a one-off run without installing, use `npx worktree-compose <command>` (for example `npx worktree-compose list`).
44
+
45
+ ## Contents
46
+
47
+ - [Why wtc?](#why-wtc)
48
+ - [How is this different from `docker compose -p`?](#how-is-this-different-from-docker-compose--p)
49
+ - [Quick Start](#quick-start)
50
+ - [Usage](#usage)
51
+ - [Selecting worktrees](#selecting-worktrees)
52
+ - [Preparing your compose file](#preparing-your-compose-file)
53
+ - [Monorepos & custom env files](#monorepos--custom-env-files)
54
+ - [How It Works](#how-it-works) — [stable identity](#stable-worktree-identity), [ports](#port-allocation), [project names](#container-isolation-and-compose_project_name), [file sync](#file-sync), [env files](#env-files)
55
+ - [Commands](#commands) — [what each one does to your data](#what-each-command-does-to-your-data)
56
+ - [Configuration (Optional)](#configuration-optional)
57
+ - [Docker, Podman, OrbStack, Colima](#docker-podman-orbstack-colima)
58
+ - [MCP Server](#mcp-server)
59
+ - [Agent Skill](#agent-skill)
60
+ - [Full Example](#full-example)
61
+ - [Upgrading from 0.2](#upgrading-from-02)
62
+ - [Requirements](#requirements)
63
+ - [Troubleshooting](#troubleshooting)
64
+ - [Contributing](#contributing)
65
+ - [License](#license)
66
+
67
+ ## Why wtc?
68
+
69
+ Spin up multiple developers or AI agents on the same repo — each in its own [git worktree](https://git-scm.com/docs/git-worktree) — and they immediately fight over a single Docker Compose setup: port conflicts, a shared database, a shared cache, colliding containers. You can't run two stacks side by side.
70
+
71
+ `wtc` reads your existing compose file and turns every worktree into a fully isolated, side-by-side environment — unique host ports, separate containers, networks, and volumes — with **zero configuration**.
72
+
73
+ - ⚡ **Zero config** — reads your existing `docker-compose.yml` / `compose.yaml`, no new files required
74
+ - 🔌 **Automatic ports** — unique, collision-free host ports per worktree
75
+ - 📦 **Full isolation** — separate containers, networks, and volumes for each stack
76
+ - 📌 **Stable identity** — a worktree keeps its index, ports, and project name; removing one never renumbers the others
77
+ - 🧪 **True side-by-side** — run `N` stacks at once and compare them in the browser
78
+ - 🔄 **One-command promote** — pull a worktree's changes back into your branch
79
+ - 🐳 **Docker or Podman** — Docker Compose v2, Podman, OrbStack, Colima
80
+ - 🩺 **`wtc doctor`** — finds what would break isolation before it bites
81
+ - 🤖 **Built-in MCP server + agent skill** — let AI agents start, stop, and manage their own stacks
82
+
83
+ <table>
84
+ <tr><th>Without <code>wtc</code></th><th>With <code>wtc</code></th></tr>
85
+ <tr><td>
19
86
 
20
- ┌───────┬───────────────┬────────┬────────────────────────┬─────────────────────────────────────────────────────────┐
21
- │ Index │ Branch │ Status │ URL │ Ports │
22
- ├───────┼───────────────┼────────┼────────────────────────┼─────────────────────────────────────────────────────────┤
23
- │ - │ main │ - │ - │ postgres:5434 redis:6380 backend:8000 frontend:5173 │
24
- ├───────┼───────────────┼────────┼────────────────────────┼─────────────────────────────────────────────────────────┤
25
- │ 1 │ feature-auth │ up │ http://localhost:25174 │ postgres:25435 redis:26381 backend:28001 frontend:25174 │
26
- ├───────┼───────────────┼────────┼────────────────────────┼─────────────────────────────────────────────────────────┤
27
- │ 2 │ fix-billing │ down │ http://localhost:25175 │ postgres:25436 redis:26382 backend:28002 frontend:25175 │
28
- └───────┴───────────────┴────────┴────────────────────────┴─────────────────────────────────────────────────────────┘
87
+ ```bash
88
+ git worktree add ../app-feat feat
89
+ # hand-pick non-colliding host ports
90
+ # edit ../app-feat/.env per service
91
+ # copy compose file + Dockerfiles over
92
+ docker compose -p app-feat up -d --build
93
+ # ...remember to tear it all down later
29
94
  ```
30
95
 
31
- ## Usage
96
+ </td><td>
32
97
 
33
98
  ```bash
34
- # Start isolated stacks for all worktrees
35
- npx wtc start
99
+ git worktree add ../app-feat feat
100
+ wtc start
101
+
102
+ # ...and when you're done:
103
+ wtc clean
104
+ ```
105
+
106
+ </td></tr>
107
+ </table>
108
+
109
+ ## How is this different from `docker compose -p`?
110
+
111
+ `docker compose -p` only namespaces the project. You'd still hand-pick free host ports, hand-edit each worktree's `.env`, copy infra files in, remember which project belongs to which worktree, and tear everything down yourself. `wtc` builds on that same project-name isolation and automates the rest: collision-free **port allocation**, a **stable index and project name** per worktree, per-worktree **env file injection** (including `COMPOSE_PROJECT_NAME`, so plain `docker compose` in the worktree hits the right stack), infra-file **sync**, one-command **`promote`**, safe **cleanup**, and a built-in **MCP server** so AI agents can drive it all themselves.
36
112
 
37
- # Start specific worktrees
38
- npx wtc start 1
39
- npx wtc start 1 2 3
113
+ ## Quick Start
40
114
 
41
- # See what's running
42
- npx wtc list
115
+ ```bash
116
+ # 1. Install once, globally
117
+ npm install -g worktree-compose
118
+
119
+ # 2. Create a worktree for some parallel work
120
+ git worktree add -b feature ../myapp-feature
121
+
122
+ # 3. Boot an isolated stack for it ("." = the worktree you're in)
123
+ cd ../myapp-feature
124
+ wtc start .
125
+
126
+ # 4. See every stack, its status, URL, and ports
127
+ wtc list
128
+
129
+ # 5. Something off? Ask the doctor
130
+ wtc doctor
131
+ ```
132
+
133
+ `wtc` works from the main checkout or from any worktree: it always reads the compose file, config, and env files from the main checkout.
134
+
135
+ ## Usage
136
+
137
+ ```bash
138
+ wtc start # start every worktree's stack
139
+ wtc start . # just the worktree you're in
140
+ wtc start 1 fix-billing # by index, branch, directory name, or path
141
+ wtc start --no-build # skip the image rebuild
142
+ wtc start --env .env.development --workspace server # monorepo env files
43
143
 
44
- # Stop worktrees
45
- npx wtc stop
46
- npx wtc stop 1
144
+ wtc list # status, URL, and ports (alias: wtc ls; --json for scripts)
145
+ wtc stop 1 # stop the containers; data is kept and start resumes them
146
+ wtc restart . # re-sync files and env, recreate what changed
47
147
 
48
- # Restart (re-sync files, rebuild containers)
49
- npx wtc restart 1
148
+ wtc promote fix-billing # copy a worktree's changes into the current checkout
50
149
 
51
- # Pull a worktree's changes into your current branch
52
- npx wtc promote 1
150
+ wtc prune # tear down stacks of worktrees you already deleted
151
+ wtc clean --dry-run # preview the full cleanup
152
+ wtc clean # tear down every stack (deletes volumes), remove worktrees that hold no work
53
153
 
54
- # Tear down everything (containers, worktrees, volumes)
55
- npx wtc clean
154
+ wtc doctor # check git, engine, ports, isolation, orphans
155
+ wtc skill --install # install the agent skill
156
+ wtc mcp # MCP server for AI agents (stdio)
56
157
  ```
57
158
 
58
- ## The Problem
159
+ ## Selecting worktrees
59
160
 
60
- Multiple developers or AI agents working in parallel on the same repo — each in a [git worktree](https://git-scm.com/docs/git-worktree) — share the same Docker Compose setup. This means port conflicts, shared databases, shared caches, and container collisions. You can't run two stacks side by side.
161
+ `start`, `stop`, and `restart` take any number of worktrees (none means all); `promote` takes exactly one. Each one can be given as:
61
162
 
62
- ## The Solution
163
+ | Selector | Example | Matches |
164
+ |----------|---------|---------|
165
+ | index | `2` | the worktree's stable index (the `Index` column of `wtc list`) |
166
+ | branch | `fix-billing` | the branch checked out in the worktree |
167
+ | directory name | `myapp-fix-billing` | the basename of the worktree's directory |
168
+ | path | `../myapp-fix-billing` | a path, resolved against the current directory (symlinks such as macOS `/tmp` are followed) |
169
+ | `.` | `.` | the worktree that contains the current directory |
63
170
 
64
- `wtc` reads your `docker-compose.yml`, finds every service that exposes a port via `${VAR:-default}`, assigns unique ports per worktree, injects them into each worktree's `.env`, and starts isolated containers. No configuration needed.
171
+ - A name that matches several worktrees (say, two directories with the same basename in different places) is an error listing them; use the index instead.
172
+ - A number is an index, unless it also names a *different* worktree (a branch or directory called `2`). Then `wtc` refuses and asks for the branch, the directory name, or a path — the message suggests one that works from where you are (e.g. `../2`).
173
+ - Through MCP, a JSON number is always an index; a string follows the rules above.
65
174
 
66
- ## Preparing Your docker-compose.yml
175
+ ## Preparing your compose file
67
176
 
68
- For `wtc` to isolate a service's port, the host port must use the `${VAR:-default}` pattern:
177
+ `wtc` looks for `compose.yaml`, `compose.yml`, `docker-compose.yaml`, or `docker-compose.yml` (in that order) at the root of the main checkout.
178
+
179
+ For `wtc` to isolate a service's port, the host port must use the `${VAR:-default}` pattern, with an upper-case variable name:
69
180
 
70
181
  ```yaml
71
182
  # wtc CAN isolate this
@@ -80,8 +191,7 @@ ports:
80
191
  If `wtc` finds hardcoded ports, it warns you and suggests the fix:
81
192
 
82
193
  ```
83
- ⚠ Service "nginx" uses a raw port mapping (8080:80).
84
- To enable port isolation, change it to: "${NGINX_PORT:-8080}:80"
194
+ ⚠ Service "nginx" uses a raw port mapping (8080:80). To enable port isolation, change it to: "${NGINX_PORT:-8080}:80"
85
195
  ```
86
196
 
87
197
  ### Supported port formats
@@ -109,202 +219,527 @@ If `wtc` finds hardcoded ports, it warns you and suggests the fix:
109
219
  protocol: tcp
110
220
  ```
111
221
 
222
+ ### Settings that break isolation
223
+
224
+ `wtc start` and `wtc doctor` warn about compose settings that make worktree stacks collide or share data (`wtc list` only prints how many there are):
225
+
226
+ - **`container_name: db`** — every stack would use the same container name, so the second one fails to start. Remove it, or make it per-stack: `container_name: ${COMPOSE_PROJECT_NAME:-myapp}-db`.
227
+ - **Top-level volumes or networks with a fixed `name:` or `external: true`** — every stack shares them. A `name:` that contains `${COMPOSE_PROJECT_NAME}` is per-stack and fine.
228
+ - **Hardcoded host ports** — see above.
229
+ - **Cross-worktree port collisions** — see [`portStride`](#clustered-default-ports-and-portstride).
230
+
231
+ ### Included compose files
232
+
233
+ If your compose file pulls in others via the top-level [`include:`](https://docs.docker.com/reference/compose-file/include/) directive, `wtc` follows them recursively — services defined in included files get the same port isolation as top-level ones, and the included files are copied into each worktree alongside the main one.
234
+
235
+ ```yaml
236
+ include:
237
+ - ./db/compose.yml
238
+ - path: ./services/api/compose.yml
239
+ ```
240
+
241
+ Build contexts in an included file resolve relative to that file's own directory, just as Docker Compose does. (Included files that live outside the repo still have their ports isolated, but aren't copied into the worktree.)
242
+
243
+ ## Monorepos & custom env files
244
+
245
+ In a monorepo, local env files usually live next to each app (`apps/server/.env.development`) instead of at the repo root, and the filename isn't always `.env`. Use `envFile` plus workspace selectors to keep every worktree's env files consistent:
246
+
247
+ ```bash
248
+ # Copy + inject apps/server/.env.development and apps/homepage/.env.development
249
+ # into the worktree, in addition to the root env file
250
+ wtc start --env .env.development --workspace server --workspace homepage
251
+ ```
252
+
253
+ Or make it the project default in `.wtcrc.json`:
254
+
255
+ ```json
256
+ {
257
+ "$schema": "https://unpkg.com/worktree-compose/wtc.schema.json",
258
+ "envFile": ".env.development",
259
+ "workspaces": ["server", "homepage"],
260
+ "workspaceEnvOverrides": {
261
+ "server": {
262
+ "DATABASE_URL": "postgresql://postgres:postgres@localhost:${POSTGRES_PORT}/postgres"
263
+ }
264
+ }
265
+ }
266
+ ```
267
+
268
+ How workspace selection works:
269
+
270
+ - Workspaces come from `package.json#workspaces` (npm/bun/yarn) or `pnpm-workspace.yaml#packages`. Only directories with a `package.json` count. In a repo that declares no workspaces, `--workspace server` looks for a `package.json` in `server`, `apps/server`, `packages/server`, or `libs/server`.
271
+ - `--workspace` matches by package **name**, directory name, or repo-relative path, and may be repeated. On the command line it replaces the configured `workspaces` for that run; `--env` likewise replaces `envFile`.
272
+ - The **repo root is always processed** — docker compose interpolates `${POSTGRES_PORT:-5434}` from the root env file, so skipping it would break port isolation. Only the root env file gets `COMPOSE_PROJECT_NAME`.
273
+ - Every target gets the allocated port variables. A selected workspace with no env file (and no `.env.example`) is skipped with a warning.
274
+ - `workspaceEnvOverrides` keys match a workspace by package name, then by directory name (only when no other workspace shares it), then by repo-relative path.
275
+ - `restart` checks `--env` and `--workspace` before stopping anything, so a typo never leaves stacks stopped.
276
+
277
+ > **Why `--env`, not `--env-file`?** Node.js intercepts `--env-file` in its own argv parsing — even after the script path — so the flag never reaches `wtc`. `--env` is the safe spelling; the config key stays `envFile`. It must be a bare filename such as `.env.development`.
278
+
112
279
  ## How It Works
113
280
 
281
+ ### Stable worktree identity
282
+
283
+ The first time `wtc` acts on a worktree (`start`, `stop`, …), it records the worktree's **index** (which decides its ports) and its **compose project name** in `.git/wtc/state.json`: inside the git directory every worktree shares, never committed. From then on they don't change. `wtc list`, `wtc doctor`, and dry runs only read: they show the identity a new worktree will get without recording it.
284
+
285
+ - **Removing a worktree never renumbers the others.** (0.2 derived the index from the position in `git worktree list`, so removing worktree 1 silently moved worktree 2 onto new ports and a new project, orphaning its running stack — [#9](https://github.com/mostafasudo/worktree-compose/issues/9).)
286
+ - **A new worktree gets the lowest index no record holds.**
287
+ - **Renaming the branch keeps the project name**, and **`git worktree move` keeps the index, ports, and project**: `wtc` keeps an id in the worktree's git admin directory (`.git/worktrees/<name>/wtc-id`), which a move keeps and `git worktree remove` deletes. Restart a moved worktree so bind mounts follow the new path.
288
+ - **A worktree you delete becomes an orphan.** After `git worktree remove` or `rm -rf`, `wtc list` shows it as `(removed)`. Its index stays reserved, because its stack may still be running on those ports, until `wtc prune` (or `wtc clean`) tears the stack down and forgets it.
289
+ - **A worktree git still lists is never an orphan**, even when `wtc` can't start it: a [locked](https://git-scm.com/docs/git-worktree#_commands) worktree whose directory is missing (an unmounted drive) shows as `(locked, missing on disk)` and keeps its index, record, and stack until it is back; `prune` and `clean` leave it alone.
290
+
291
+ ```
292
+ git worktree remove ../myapp-spike-cache
293
+ git worktree add -b docs ../myapp-docs
294
+ wtc list
295
+
296
+ ┌───────┬───────────────────────┬────────┬────────────────────────┬────────────────────────────────────────────────────────────┐
297
+ │ Index │ Branch │ Status │ URL │ Ports │
298
+ ├───────┼───────────────────────┼────────┼────────────────────────┼────────────────────────────────────────────────────────────┤
299
+ │ - │ main │ - │ - │ postgres:5434 backend:8000 frontend:5173 │
300
+ ├───────┼───────────────────────┼────────┼────────────────────────┼────────────────────────────────────────────────────────────┤
301
+ │ 1 │ feature-auth │ up │ http://localhost:25174 │ POSTGRES_PORT=25435 BACKEND_PORT=28001 FRONTEND_PORT=25174 │
302
+ ├───────┼───────────────────────┼────────┼────────────────────────┼────────────────────────────────────────────────────────────┤
303
+ │ 2 │ fix-billing │ exited │ http://localhost:25175 │ POSTGRES_PORT=25436 BACKEND_PORT=28002 FRONTEND_PORT=25175 │
304
+ ├───────┼───────────────────────┼────────┼────────────────────────┼────────────────────────────────────────────────────────────┤
305
+ │ 3 │ spike-cache (removed) │ up │ - │ POSTGRES_PORT=25437 BACKEND_PORT=28003 FRONTEND_PORT=25176 │
306
+ ├───────┼───────────────────────┼────────┼────────────────────────┼────────────────────────────────────────────────────────────┤
307
+ │ 4 │ docs │ down │ http://localhost:25177 │ POSTGRES_PORT=25438 BACKEND_PORT=28004 FRONTEND_PORT=25177 │
308
+ └───────┴───────────────────────┴────────┴────────────────────────┴────────────────────────────────────────────────────────────┘
309
+ (removed) = the worktree is gone but its stack/record remains. Run 'wtc prune' to tear it down.
310
+ ```
311
+
312
+ **Coming from 0.2?** On the first run, `wtc` gives existing worktrees the same positional indices 0.2 used, and a worktree whose 0.2 stack is still running adopts that stack's index and project (matched by the directory compose ran in). Running stacks are picked up, not duplicated. If `state.json` is ever lost or unreadable, it is rebuilt the same way (an unreadable file is first moved aside as `state.json.bak-<time>`).
313
+
114
314
  ### Port Allocation
115
315
 
116
- Each worktree N gets unique ports: `20000 + default_port + worktree_index`
316
+ Each worktree gets unique ports from its index: `20000 + default_port + (worktree_index × portStride)`
317
+
318
+ `portStride` defaults to `1`, so by default the table below holds:
117
319
 
118
320
  | Service | Main (default) | Worktree 1 | Worktree 2 | Worktree 3 |
119
321
  |----------|---------------|------------|------------|------------|
120
322
  | postgres | 5434 | 25435 | 25436 | 25437 |
121
- | redis | 6380 | 26381 | 26382 | 26383 |
122
323
  | backend | 8000 | 28001 | 28002 | 28003 |
123
324
  | frontend | 5173 | 25174 | 25175 | 25176 |
124
325
 
125
- ### Container Isolation
326
+ The table is illustrative — every value follows the formula above. (If an allocation would exceed `65535`, `wtc` falls back to `default_port + 100 × index`.)
327
+
328
+ #### Clustered default ports and `portStride`
329
+
330
+ With the default stride of `1`, two worktrees collide on a port whenever a pair of services has default host ports whose difference equals the worktrees' index difference. Projects with **clustered** default ports (e.g. mocks on `8081`–`8086`) therefore collide even between adjacent worktrees, and the second `docker compose up` fails to bind.
331
+
332
+ When `wtc` detects such a collision across the indices in use (live worktrees and orphans) it warns, naming the colliding ports and the recommended stride. Set `portStride` in your config (`.wtcrc.json` or `package.json#wtc`) to spread each worktree's ports far enough apart:
333
+
334
+ ```json
335
+ { "portStride": 100 }
336
+ ```
337
+
338
+ A stride of `100` gives every worktree a 100-port band, which is collision-free unless some pair of default ports differs by an exact multiple of the stride. The recommended value in the warning is the smallest stride that is collision-free over a generous worktree horizon. The canonical `docker compose up` in the main checkout is unaffected — only the worktrees' ports change.
339
+
340
+ ### Container isolation and `COMPOSE_PROJECT_NAME`
341
+
342
+ Each worktree's stack runs as the compose project `{repo}-wt-{index}-{branch}`, lowercased with anything other than `a-z`, `0-9`, and `-` turned into `-` — for example `myapp-wt-1-feature-auth`. Compose names containers, networks, and volumes after the project, so nothing is shared. `{repo}` is the main checkout's directory name (for a bare repository, the repository's own name), so it is the same from every worktree.
343
+
344
+ `wtc` passes `-p <project>` on every compose call, exports `COMPOSE_PROJECT_NAME` and the allocated ports into compose's environment, and writes `COMPOSE_PROJECT_NAME=<project>` into the worktree's root env file. With the default `.env`, a plain `docker compose ps` / `logs` / `exec` (or a Makefile) run inside the worktree therefore reaches the same stack on the same ports.
345
+
346
+ Compose only reads a file named `.env` on its own. With a custom `envFile` such as `.env.development`, pass it explicitly (`docker compose --env-file .env.development ps`) or pass `-p <project>` (the `project` field of `wtc list --json`).
126
347
 
127
- Each worktree gets its own `COMPOSE_PROJECT_NAME`: `{repo}-wt-{index}-{branch}`. This means separate containers, networks, and volumes. Nothing is shared.
348
+ `${COMPOSE_PROJECT_NAME}` is also available in `envOverrides` and `workspaceEnvOverrides` values, e.g. `"QUEUE_PREFIX": "${COMPOSE_PROJECT_NAME}-jobs"`.
128
349
 
129
350
  ### File Sync
130
351
 
131
- Before starting, `wtc` copies infrastructure files from main into the worktree: the compose file, every Dockerfile referenced in `build.dockerfile`, and `.env`. This ensures the worktree always has the latest Docker setup.
352
+ Before every start, `wtc` copies infrastructure files from the main checkout into the worktree, so every worktree runs the latest Docker setup:
132
353
 
133
- ### Env Injection
354
+ - the compose file, plus every file it pulls in via `include:` (inside the repo);
355
+ - every Dockerfile a service's `build` points to (remote build contexts and `dockerfile_inline` have none);
356
+ - the extra paths listed in [`sync`](#sync). Entries must stay inside the repository; absolute or `../` entries are skipped with a warning.
134
357
 
135
- After copying `.env`, `wtc` appends an idempotent block with allocated port overrides:
358
+ Sync copies over what is at those paths and removes nothing else: files that only the worktree has stay. Symlinks are recreated as symlinks, never followed. `wtc` never writes through a symlink it finds at a destination (it replaces the link) and skips any destination whose directory resolves outside the worktree. Where main has a symlink but the worktree has a real directory, the directory is left alone with a warning.
359
+
360
+ ### Env Files
361
+
362
+ On every `start` and `restart`, for the root and each selected workspace:
363
+
364
+ 1. **Copy fresh from main:** `<envFile>` (default `.env`), falling back to `.env.example`. The root gets an empty file if neither exists; a workspace with neither is skipped.
365
+ 2. **Inject:** `COMPOSE_PROJECT_NAME` (root only), every allocated port variable, then `envOverrides` (root) or `workspaceEnvOverrides` (that workspace). **A key that already exists is rewritten in place** — comments, ordering, and all other lines are preserved. Keys that don't exist are appended in a marked block, which is replaced on every run and never accumulates.
366
+
367
+ With `"envOverrides": { "DATABASE_URL": "postgresql://app:app@localhost:${POSTGRES_PORT}/app" }` and a main `.env` of
136
368
 
137
369
  ```bash
138
- # existing .env content stays untouched...
370
+ POSTGRES_PORT=5434
371
+ DATABASE_URL=postgresql://app:app@localhost:5434/app
372
+ ```
139
373
 
140
- # --- wtc port overrides ---
374
+ worktree 1 gets:
375
+
376
+ ```bash
141
377
  POSTGRES_PORT=25435
142
- REDIS_PORT=26381
378
+ DATABASE_URL=postgresql://app:app@localhost:25435/app
379
+
380
+ # --- wtc port overrides ---
381
+ COMPOSE_PROJECT_NAME=myapp-wt-1-feature-auth
143
382
  BACKEND_PORT=28001
144
383
  FRONTEND_PORT=25174
145
384
  # --- end wtc ---
146
385
  ```
147
386
 
148
- ## Commands
387
+ Two consequences of copying fresh every time:
149
388
 
150
- ### `wtc start [indices...]`
389
+ - **Edits made only in a worktree's env file are lost on the next start.** Put lasting values in main's env file, or in `envOverrides` / `workspaceEnvOverrides`.
390
+ - **Only the keys above are written.** A value with a port inside it, like `DATABASE_URL` above, keeps main's port unless you add an override for it.
151
391
 
152
- Start Docker Compose stacks. Syncs files, injects ports, runs `docker compose up -d --build`.
392
+ If a worktree's env file is a symlink (for example to main's `.env`), `wtc` replaces the link with a regular copy and never writes through it.
153
393
 
154
- ```bash
155
- npx wtc start # all worktrees
156
- npx wtc start 1 # worktree 1 only
157
- npx wtc start 1 2 3 # worktrees 1, 2, and 3
394
+ The allocated ports are also exported into the environment of the compose process `wtc` launches. Compose resolves `${VAR:-default}` from the process environment, `--env-file`, and the project `.env` — never from a service's `env_file:`, and never from a custom filename like `.env.development`. Exporting the ports keeps published host ports correct when the project uses a custom `envFile`.
395
+
396
+ ### Repository layouts
397
+
398
+ Besides a plain clone, `wtc` handles bare repositories with worktrees (the worktree on the repository's default branch acts as the main checkout and is never started, synced into, or removed), submodules, and `--separate-git-dir` checkouts. Locked worktrees work normally; a locked worktree whose directory is missing (an unmounted drive) is skipped with a warning, and its stack and index are kept.
399
+
400
+ Two layouts don't tell from every worktree which checkout is the main one: a bare repository whose default-branch worktree is mid-rebase, mid-bisect, or on another branch for now, and a `--separate-git-dir` repository seen from a linked worktree. `wtc` remembers the main checkout (in `.git/wtc/state.json`) once it has run there or found it, and uses that. When it can't tell at all, it warns, uses the current checkout's compose and config files for `list`, `doctor`, `stop`, `promote`, and `prune`, records nothing, and refuses `start`, `restart`, and `clean` — they would sync files into, start, or remove checkouts based on the wrong one. The error says how to fix it: check the default branch out in your main worktree, or run `wtc start` from the main checkout.
401
+
402
+ ## Commands
403
+
404
+ ### `wtc start`
405
+
406
+ ```
407
+ wtc start [worktrees...] [--env <name>] [--workspace <name>]... [--no-build]
158
408
  ```
159
409
 
160
- ### `wtc stop [indices...]`
410
+ For each selected worktree (all when none are given): sync infrastructure files, copy and inject env files, then run `compose -p <project> up -d --build`. Stops at the first failure; on success it prints `wtc list`. A worktree whose directory is missing is refused (see `wtc prune`). The main checkout's own stack is not managed by `wtc`: run `docker compose` there as usual.
161
411
 
162
- Stop stacks. Runs `docker compose down`. Volumes are preserved.
412
+ | Flag | |
413
+ |------|-|
414
+ | `--env <name>` | Env filename to copy and inject for this run (default: `envFile`, else `.env`) |
415
+ | `--workspace <name>` | Workspace to also inject env into; repeatable (see [Monorepos](#monorepos--custom-env-files)) |
416
+ | `--no-build` | Run `compose up -d` without `--build` |
417
+
418
+ ### `wtc stop`
163
419
 
164
- ```bash
165
- npx wtc stop # all
166
- npx wtc stop 1 # worktree 1 only
420
+ ```
421
+ wtc stop [worktrees...]
167
422
  ```
168
423
 
169
- ### `wtc restart [indices...]`
424
+ Runs `compose stop`: containers are stopped, **not removed**, and all volumes are kept — including the anonymous ones images like postgres and redis create — so `wtc start` resumes the same containers with their data. `wtc list` shows a stopped stack as `exited`. One failure doesn't stop the rest; the exit code is 1 if any stack failed to stop.
170
425
 
171
- Full restart: stop, re-sync files, re-inject env, rebuild, start. Use after migrations, Dockerfile changes, or config updates.
426
+ ### `wtc restart`
172
427
 
173
- ```bash
174
- npx wtc restart 1
428
+ ```
429
+ wtc restart [worktrees...] [--env <name>] [--workspace <name>]... [--no-build]
175
430
  ```
176
431
 
177
- ### `wtc list` / `wtc ls`
432
+ `compose stop`, then everything `start` does, with `up -d --build --remove-orphans`: unchanged services start again, changed ones are recreated (keeping their volumes), and containers of services you removed from the compose file go away. Use it after migrations, Dockerfile changes, or config updates. Env options and selectors are validated before anything is stopped.
178
433
 
179
- Show all worktrees with branch, status, URL, and ports.
434
+ ### `wtc list`
180
435
 
181
- ```bash
182
- npx wtc list
436
+ ```
437
+ wtc list [--json] # alias: wtc ls
183
438
  ```
184
439
 
185
- ### `wtc promote <index>`
440
+ Every worktree with its index, branch, status, URL, and ports, plus a row for main's default ports. Status is `up`, `partial` (with running/total, e.g. `partial 2/3`), `exited` (containers stopped), `down` (no containers), or `?` (no reachable engine). One-off `docker compose run` containers are not counted. Removed worktrees whose record remains are shown as `(removed)`; worktrees git still lists but `wtc` can't start as `(locked, missing on disk)` or `(now the main checkout)`. Read-only: it never writes the registry.
186
441
 
187
- Copy changed files from a worktree into your current branch as uncommitted changes. Automatically excludes `.env` and compose files. Aborts if it would overwrite uncommitted local changes.
442
+ `--json` prints an array of `{ index, branch, path, project, status, running, total, url, ports, orphan, unavailable }` to stdout (`unavailable` is `"missing"`, `"main"`, or `null`); warnings go to stderr. The URL is the first service whose name contains `frontend`, `web`, `app`, or `ui`, else the last isolated port.
188
443
 
189
- ```bash
190
- npx wtc promote 1
444
+ ### `wtc promote`
445
+
446
+ ```
447
+ wtc promote <worktree> [--force]
191
448
  ```
192
449
 
450
+ Copies a worktree's changes into the checkout you run it from (usually main) as uncommitted changes: everything it changed since it branched — committed, staged, unstaged, and untracked — with deleted files deleted and renames applied as delete + add. Compose files and local env files (`.env`, `.env.development`, … — committed templates like `.env.example` still promote) are skipped, because `wtc` rewrites them per worktree. Symlinks are copied as symlinks; directories such as submodules are skipped with a warning. Works without Docker.
451
+
452
+ It refuses, before writing anything:
453
+
454
+ - **conflicts** — a file it would touch has uncommitted or untracked changes in the target (unless the target already has identical content). Commit or stash first.
455
+ - **reverts** — a file it would touch was also changed (committed) on the target branch since the worktree branched. Promote copies whole files, so this would silently undo those commits. Merge the target branch into the worktree first (the error prints the command), or pass `--force` to overwrite them anyway.
456
+ - **unsafe paths** — a path that escapes the repository or passes through a symlinked directory on either side.
457
+ - promoting a worktree into itself.
458
+
193
459
  ### `wtc clean`
194
460
 
195
- Stop all containers, remove all worktrees, prune stale Docker resources.
461
+ ```
462
+ wtc clean [--dry-run] [--force] [--keep-worktrees] [--sweep]
463
+ ```
196
464
 
197
- ```bash
198
- npx wtc clean
465
+ Ends the session for every worktree:
466
+
467
+ 1. **Tears down every stack `wtc` knows** — all live worktrees and all orphans — with `compose down -v --remove-orphans`. **This deletes their volumes**, including the stacks of worktrees that step 2 keeps and with `--keep-worktrees`. To stop everything but keep the data, use `wtc stop`.
468
+ 2. **Removes worktrees that hold no work of their own** (skipped entirely with `--keep-worktrees`). Never removed: the main checkout and the worktree you run `clean` from. Kept unless you pass `--force`:
469
+ - uncommitted changes, tracked or untracked — other than the files `wtc` itself wrote there (the env files it injects, and compose/Dockerfile/`sync` copies that still match main);
470
+ - a detached HEAD with commits no branch, tag, or remote contains;
471
+ - submodules with commits not pushed to any remote;
472
+ - locked worktrees.
473
+
474
+ Each kept worktree is listed with the reason.
475
+ 3. **Sweeps leftover containers, networks, and volumes, one at a time — only of stacks this checkout owns:** projects in its registry, or `<repo>-wt-<n>-…` projects whose containers ran from the main checkout, one of its worktrees, or a recorded worktree path. Stacks that are merely *named* like this repo's (another clone with the same directory name) are listed and never removed. Ownership is judged from containers: volumes and networks of a project with **no container left** carry no working directory, so they are listed, never removed — see [leftovers](#troubleshooting).
476
+ 4. Runs `git worktree prune`, and forgets the records of removed worktrees and torn-down orphans. Worktrees that stay keep their index.
477
+
478
+ | Flag | |
479
+ |------|-|
480
+ | `--dry-run` | Print exactly what would be stopped, removed, and swept; change nothing (not even `wtc`'s registry) |
481
+ | `--force` | Also remove worktrees with uncommitted changes, unreachable commits, unpushed submodule commits, and locked ones |
482
+ | `--keep-worktrees` | Tear down the stacks (deleting their volumes), keep every worktree |
483
+ | `--sweep` | Also remove `<repo>-wt-<n>-…` stacks whose working directory no longer exists — e.g. left behind by wtc 0.2 — judged from their containers: volumes or networks with no container left are listed, never removed. Never a stack whose directory exists |
484
+
485
+ ### `wtc prune`
486
+
487
+ ```
488
+ wtc prune [--dry-run]
199
489
  ```
200
490
 
491
+ Tears down (`compose down -v --remove-orphans`, deleting volumes) and forgets **orphans only**: stacks of worktrees you deleted with `git worktree remove` or `rm -rf`. Live worktrees are not touched — nor is any worktree git still lists, such as a locked one on an unmounted drive; each orphan is re-checked right before teardown. Also runs `git worktree prune` when git still lists worktrees whose directory is gone.
492
+
493
+ ### `wtc doctor`
494
+
495
+ ```
496
+ wtc doctor [--json]
497
+ ```
498
+
499
+ A ✔ / ⚠ / ✖ checklist with hints: git version; repository and main-checkout detection; compose file found and parsed (services, included files); config parsed (`.wtcrc.json` or `package.json#wtc`); compose engine and version (when it doesn't work, whether `WTC_COMPOSE_COMMAND`, `composeCommand`, or auto-detection chose it); daemon reachable; isolatable vs. hardcoded ports; [isolation warnings](#settings-that-break-isolation); cross-worktree port collisions; missing worktrees; orphaned stacks; each worktree's stack state; and allocated ports already taken by something else for worktrees whose stack isn't running. Read-only. Exits 1 if any check fails.
500
+
501
+ ### `wtc skill`
502
+
503
+ ```
504
+ wtc skill [--install] [--dir <path>]
505
+ ```
506
+
507
+ Prints the bundled [agent skill](#agent-skill). `--install` writes it to `~/.claude/skills/worktree-compose/SKILL.md`; `--dir <path>` installs it to `<path>/worktree-compose/SKILL.md` instead.
508
+
509
+ ### `wtc mcp`
510
+
511
+ Starts the [MCP server](#mcp-server) on stdio.
512
+
513
+ ### What each command does to your data
514
+
515
+ | Command | Containers | Volumes (your data) | Worktrees |
516
+ |---------|-----------|---------------------|-----------|
517
+ | `wtc stop` | stopped, kept | kept | kept |
518
+ | `wtc restart` | stopped, then started; changed services recreated | kept | kept |
519
+ | `wtc prune` | removed (deleted worktrees' stacks only) | **deleted** (those stacks only) | — |
520
+ | `wtc clean` | removed (every stack) | **deleted** (every stack) | removed unless they hold work; never main or the current one |
521
+ | `wtc clean --keep-worktrees` | removed (every stack) | **deleted** (every stack) | kept |
522
+
523
+ Exit codes: any error exits 1. `stop`, `clean`, and `prune` also exit 1 when a stack, removal, or sweep failed (worktrees kept on purpose don't count); `doctor` exits 1 when a check fails.
524
+
201
525
  ## Configuration (Optional)
202
526
 
203
- `wtc` works zero-config. For project-specific needs, create `.wtcrc.json` in your repo root:
527
+ `wtc` works zero-config. For project-specific needs, create `.wtcrc.json` at the root of the main checkout:
204
528
 
205
529
  ```json
206
530
  {
531
+ "$schema": "https://unpkg.com/worktree-compose/wtc.schema.json",
207
532
  "sync": [".generated/prisma-client", "local-certs/"],
533
+ "envFile": ".env.development",
534
+ "workspaces": ["server", "homepage"],
208
535
  "envOverrides": {
209
536
  "VITE_API_URL": "http://localhost:${BACKEND_PORT}"
210
- }
537
+ },
538
+ "workspaceEnvOverrides": {
539
+ "server": {
540
+ "DATABASE_URL": "postgresql://postgres:postgres@localhost:${POSTGRES_PORT}/postgres"
541
+ }
542
+ },
543
+ "portStride": 100,
544
+ "composeCommand": "podman compose"
211
545
  }
212
546
  ```
213
547
 
214
- Or use a `"wtc"` key in `package.json`.
548
+ Or use a `"wtc"` key in `package.json`. (`.wtcrc.json` takes precedence.) The `$schema` line gives editors completion and validation for every key; `wtc` ignores it.
215
549
 
216
550
  ### `sync`
217
551
 
218
- Extra files/directories to copy from main into each worktree on start. Use for gitignored or generated files that Docker needs but aren't committed — like generated clients, local certificates, or build artifacts.
552
+ Extra files/directories to copy from main into each worktree on start. Use for gitignored or generated files that Docker needs but aren't committed — like generated clients, local certificates, or build artifacts. Paths are repo-relative; entries that are absolute or leave the repository are skipped with a warning.
553
+
554
+ ### `envFile`
555
+
556
+ Env filename to copy from main and inject overrides into, for the root and every selected workspace. Defaults to `.env`. Must be a bare filename. Per-run override: `--env`.
557
+
558
+ ### `workspaces`
559
+
560
+ Monorepo workspaces that also get their env file copied and injected, in addition to the root. Accepts package names, directory names, or repo-relative paths. Omitted → root only. Per-run override: `--workspace`. See [Monorepos & custom env files](#monorepos--custom-env-files).
219
561
 
220
562
  ### `envOverrides`
221
563
 
222
- Additional env vars injected into `.env`. Supports `${VAR}` interpolation with allocated port values. Use when env vars depend on allocated ports (e.g. `VITE_API_URL`).
564
+ Additional env vars injected into the **root** env file. Values interpolate `${VAR}` with the allocated port variables and `${COMPOSE_PROJECT_NAME}`. Existing keys are rewritten in place; new keys are appended in the override block.
565
+
566
+ ### `workspaceEnvOverrides`
567
+
568
+ Per-workspace overrides, keyed by workspace package name (a unique directory name or the repo-relative path also work). Applied only to that workspace's env file, with the same interpolation and in-place rewrite behavior as `envOverrides`.
569
+
570
+ ### `portStride`
571
+
572
+ Port spacing between consecutive worktree indices (default `1`, must be a positive integer). Allocated port = `20000 + default_port + worktree_index × portStride`. Raise it (e.g. `100`) when your project exposes clustered default ports that would otherwise collide across worktrees — see [Port Allocation](#port-allocation). `wtc` warns and recommends a value when it detects a collision.
573
+
574
+ ### `composeCommand`
575
+
576
+ Which compose tool to use instead of auto-detection: exactly one of `"docker compose"`, `"podman compose"`, `"docker-compose"`, or `"podman-compose"` (a string, or an array such as `["podman", "compose"]`). Repository config is limited to these four so a cloned repository can't make `wtc` run an arbitrary program; anything custom goes in the `WTC_COMPOSE_COMMAND` environment variable, which takes precedence. See [Docker, Podman, OrbStack, Colima](#docker-podman-orbstack-colima).
577
+
578
+ ## Docker, Podman, OrbStack, Colima
579
+
580
+ `wtc` picks the compose command in this order:
581
+
582
+ 1. **`WTC_COMPOSE_COMMAND`** environment variable — any command, split on whitespace: `WTC_COMPOSE_COMMAND="podman compose"`, an absolute path, or global flags such as `WTC_COMPOSE_COMMAND="docker --context colima compose"`.
583
+ 2. **`composeCommand`** in `.wtcrc.json` / `package.json#wtc` — one of the four standard commands below.
584
+ 3. **Auto-detection**, in order: `docker compose` (Compose v2) → `podman compose` → `docker-compose` (standalone, including legacy v1) → `podman-compose`. When more than one is installed, the first whose daemon answers wins, so a quit Docker Desktop doesn't shadow a running Podman machine.
585
+
586
+ | Engine | How |
587
+ |--------|-----|
588
+ | Docker Desktop / Docker Engine | `docker compose` (auto-detected) |
589
+ | OrbStack, Colima | through the `docker` CLI and its current context (auto-detected); for another context, `WTC_COMPOSE_COMMAND="docker --context <name> compose"` |
590
+ | Podman | `podman compose` or `podman-compose` (auto-detected); on macOS and Windows, start its VM with `podman machine start` |
591
+ | Anything else (e.g. `nerdctl compose`) | `WTC_COMPOSE_COMMAND` |
592
+
593
+ Status checks, teardown, and cleanup use the same CLI and global flags as compose, so they always talk to the same daemon. `wtc doctor` shows which engine was picked and its version, and whether its daemon is reachable. `wtc promote` doesn't need an engine at all.
223
594
 
224
595
  ## MCP Server
225
596
 
226
- Built-in [MCP](https://modelcontextprotocol.io/) server so AI agents can manage their stack programmatically.
597
+ Built-in [MCP](https://modelcontextprotocol.io/) server, so AI agents can manage their stacks themselves. It works on the git repository of the directory it starts in — your agent's project. The setups below use the global install.
227
598
 
228
599
  ### Setup
229
600
 
230
- **Claude Code** (`.claude/settings.json`):
601
+ **Claude Code** — for every project:
602
+
603
+ ```bash
604
+ claude mcp add --scope user wtc -- wtc mcp
605
+ ```
606
+
607
+ (Without `--scope user`, Claude Code registers it for the current project only.) Or share it with your team through a project `.mcp.json`:
231
608
 
232
609
  ```json
233
610
  {
234
611
  "mcpServers": {
235
- "wtc": {
236
- "command": "npx",
237
- "args": ["wtc", "mcp"]
238
- }
612
+ "wtc": { "command": "wtc", "args": ["mcp"] }
239
613
  }
240
614
  }
241
615
  ```
242
616
 
243
- **Codex:**
617
+ **Codex** — `~/.codex/config.toml`:
618
+
619
+ ```toml
620
+ [mcp_servers.wtc]
621
+ command = "wtc"
622
+ args = ["mcp"]
623
+ ```
624
+
625
+ **Cursor** — `.cursor/mcp.json`, with the same JSON as `.mcp.json` above.
626
+
627
+ **Without a global install**, use `npx` with the package name (never `npx wtc`):
244
628
 
245
629
  ```json
246
- {
247
- "servers": {
248
- "wtc": {
249
- "command": "npx",
250
- "args": ["wtc", "mcp"]
251
- }
252
- }
253
- }
630
+ { "command": "npx", "args": ["-y", "worktree-compose", "mcp"] }
254
631
  ```
255
632
 
633
+ After upgrading `wtc`, restart your MCP client so it runs the new version.
634
+
256
635
  ### Tools
257
636
 
258
- | Tool | Parameters | Description |
259
- |------|-----------|-------------|
260
- | `wtc_start` | `indices?: number[]` | Start worktree stacks |
261
- | `wtc_stop` | `indices?: number[]` | Stop worktree stacks |
262
- | `wtc_restart` | `indices?: number[]` | Restart after migrations/config changes |
263
- | `wtc_list` | none | List worktrees (returns JSON) |
264
- | `wtc_promote` | `index: number` | Pull worktree changes into current branch |
265
- | `wtc_clean` | none | Tear down everything |
637
+ | Tool | Parameters | What it does | Safety |
638
+ |------|-----------|--------------|--------|
639
+ | `wtc_start` | `indices?: (number \| string)[]`, `envFile?: string`, `workspaces?: string[]`, `build?: boolean` (default `true`) | Same as `wtc start` | not destructive |
640
+ | `wtc_stop` | `indices?: (number \| string)[]` | Same as `wtc stop` (`compose stop`) | not destructive: containers and volumes are kept |
641
+ | `wtc_restart` | same as `wtc_start` | Same as `wtc restart` | not destructive |
642
+ | `wtc_list` | — | First content item is the JSON array of `wtc list --json`; warnings follow as separate items | read-only: never writes the registry |
643
+ | `wtc_promote` | `index: number \| string`, `force?: boolean` | Same as `wtc promote`, into the checkout the server runs in | **destructive**: overwrites and deletes files there |
644
+ | `wtc_clean` | `force?`, `keepWorktrees?`, `dryRun?`, `sweep?` (all `boolean`) | Same as `wtc clean` | **destructive**: deletes volumes, removes worktrees |
645
+ | `wtc_prune` | `dryRun?: boolean` | Same as `wtc prune` | **destructive**: deletes removed worktrees' volumes |
646
+ | `wtc_doctor` | — | Same checks as `wtc doctor`, as JSON | read-only |
647
+
648
+ `indices` / `index` take [selectors](#selecting-worktrees): a JSON number is always an index; a string can be an index, branch, directory name, path, or `.`. Omit `indices` for all worktrees.
649
+
650
+ - Tools that change stacks or files (start, stop, restart, promote, clean, prune) run one at a time, so a client retry can't launch a second `compose up` for the same stack.
651
+ - Cancelling a request stops the compose command it started; a request cancelled while it waits its turn does not run at all. Requests with a `progressToken` get progress notifications while compose runs.
652
+ - Every tool returns its progress lines. Failures come back as `isError: true` with the reason (including the tail of compose's error output) — also when a teardown or removal inside `wtc_stop`, `wtc_clean`, or `wtc_prune` failed.
653
+ - Tool annotations mark `wtc_list` and `wtc_doctor` read-only and `wtc_promote`, `wtc_clean`, and `wtc_prune` destructive, so clients can ask before running them.
654
+ - stdout carries only JSON-RPC; all logging goes to stderr.
655
+
656
+ ## Agent Skill
657
+
658
+ `wtc` ships an [agent skill](https://docs.claude.com/en/docs/claude-code/skills) ([`SKILL.md`](https://github.com/mostafasudo/worktree-compose/blob/main/SKILL.md)) that teaches AI coding agents the worktree workflow: commands and selectors, stop vs. clean, ports, env files, config, and the MCP tools. Install the copy that matches your installed version:
659
+
660
+ ```bash
661
+ wtc skill --install # ~/.claude/skills/worktree-compose/SKILL.md
662
+ wtc skill --dir ~/my-agent/skills # <dir>/worktree-compose/SKILL.md
663
+ wtc skill # print it
664
+ ```
665
+
666
+ Re-run `wtc skill --install` after upgrading `wtc`.
266
667
 
267
668
  ## Full Example
268
669
 
269
670
  ```bash
270
671
  cd myapp
271
- pnpm add -D worktree-compose
672
+ npm install -g worktree-compose
272
673
 
273
- git branch agent-1-auth
274
- git branch agent-2-auth
275
- git worktree add ../myapp-agent-1 agent-1-auth
276
- git worktree add ../myapp-agent-2 agent-2-auth
674
+ git worktree add -b agent-1-auth ../myapp-agent-1
675
+ git worktree add -b agent-2-auth ../myapp-agent-2
277
676
 
278
- npx wtc start
279
- # Worktree 1: backend:28001 frontend:25174
280
- # Worktree 2: backend:28002 frontend:25175
677
+ wtc start
678
+ # Worktree 1: BACKEND_PORT=28001 FRONTEND_PORT=25174
679
+ # Worktree 2: BACKEND_PORT=28002 FRONTEND_PORT=25175
281
680
 
282
681
  # Compare side by side
283
682
  # http://localhost:25174 (agent 1)
284
683
  # http://localhost:25175 (agent 2)
285
684
 
286
- npx wtc promote 1
685
+ wtc promote agent-1-auth
287
686
  git add -A && git commit -m "feat: auth from agent 1"
288
- npx wtc clean
687
+
688
+ wtc clean --dry-run # preview
689
+ wtc clean # worktrees with uncommitted work are kept; --force discards them
289
690
  ```
290
691
 
692
+ ## Upgrading from 0.2
693
+
694
+ 1.0 changes a few behaviors; the [changelog](https://github.com/mostafasudo/worktree-compose/blob/main/CHANGELOG.md#upgrading-from-02) has the full list.
695
+
696
+ - **Node.js 20+.**
697
+ - **Install globally and type `wtc`** — without an install, `npx wtc` runs an unrelated package. Update MCP configs to `"command": "wtc", "args": ["mcp"]`.
698
+ - **Indices are stable.** Your existing stacks keep their names on the first run; after that, removing a worktree never shifts the others. Deleted worktrees show as `(removed)` until `wtc prune`.
699
+ - **`wtc stop` keeps containers** (`compose stop` instead of `down`); `start` resumes them. Only `clean` and `prune` remove stacks and volumes.
700
+ - **`wtc clean` keeps worktrees that hold work** (uncommitted changes, unreachable commits, unpushed submodule commits, locked) unless you pass `--force`, and only removes Docker resources of stacks it owns. Stale 0.2 stacks that still have containers: `wtc clean --sweep`. 0.2's `wtc stop` kept named volumes, so a worktree deleted after `wtc stop` can leave volumes with no container; `wtc clean` lists those but never removes them. Find them with `docker volume ls --filter label=com.docker.compose.project=<project>` and remove them with `docker volume rm`.
701
+ - **Env keys are rewritten in place**, and the root env file now gets `COMPOSE_PROJECT_NAME`.
702
+ - **`wtc promote`** also aborts when the target branch changed the same files since the worktree branched (`--force` overrides), and untracked files in the target now count as conflicts.
703
+
291
704
  ## Requirements
292
705
 
293
- - **Node.js** >= 18
294
- - **Git** with worktree support
295
- - **Docker** with Compose v2 (`docker compose`)
296
- - `docker-compose.yml` with `${VAR:-default}` port patterns
706
+ - **Node.js** >= 20
707
+ - **Git** 2.17 or newer, with worktree support (2.31+ recommended)
708
+ - **Docker** with Compose v2 (`docker compose`), or **Podman** (`podman compose` / `podman-compose`) — see [engines](#docker-podman-orbstack-colima)
709
+ - A compose file with `${VAR:-default}` host ports
297
710
 
298
711
  ## Troubleshooting
299
712
 
300
- **"No compose file found"** — `wtc` looks in the git repo root, not the current directory.
713
+ Start with **`wtc doctor`**: it checks the engine, the daemon, ports, isolation settings, missing worktrees, and orphaned stacks, and says what to do.
714
+
715
+ **`npx wtc` does something unexpected** — when worktree-compose isn't installed, it downloads and runs an unrelated npm package named `wtc`. Install globally (`npm install -g worktree-compose`) and type `wtc`, or use `npx worktree-compose <command>`.
716
+
717
+ **"No compose file found"** — `wtc` reads the compose file from the root of the main checkout, not the current directory: `compose.yaml`, `compose.yml`, `docker-compose.yaml`, or `docker-compose.yml`.
718
+
719
+ **"No extra worktrees found"** — Create worktrees first: `git worktree add -b my-branch ../my-feature`
720
+
721
+ **Ports not changing** — Use `${VAR:-default}` with an upper-case variable for host ports, not hardcoded numbers. `wtc doctor` lists which ports are isolatable.
722
+
723
+ **"Bind for 0.0.0.0:25435 failed: port is already allocated"** — Something else listens on that port. `wtc doctor` reports allocated ports that are already taken; stop the other process, or raise `portStride`. If you run `docker compose` yourself with a custom `envFile`, pass `--env-file <envFile>` (Compose only reads `.env` on its own) or export the port (e.g. `POSTGRES_PORT=25435 docker compose up`).
724
+
725
+ **A stack shows as `(removed)`** — its worktree was deleted but its stack or record remains. `wtc prune` tears it down (and frees its index); preview with `wtc prune --dry-run`.
726
+
727
+ **Leftover containers, networks, or volumes** — `wtc clean --dry-run` shows what `wtc clean` would remove. Leftovers of stacks whose worktree directory no longer exists (e.g. from wtc 0.2) are listed, and removed with `wtc clean --sweep` as long as the stack still has a container (that is where the working directory is recorded). Volumes or networks with no container left, and resources merely *named* like this repo's stacks, are listed and never removed by `wtc`. Inspect one project exactly before removing anything yourself: `docker ps -a --filter label=com.docker.compose.project=<project>` shows nothing for volume-only leftovers, so also run `docker volume ls --filter label=com.docker.compose.project=<project>` and `docker network ls --filter label=com.docker.compose.project=<project>`.
728
+
729
+ **"Refusing to start worktree stacks: cannot locate the main checkout"** (also `restart`, `clean`) — the repository layout doesn't say which checkout is the main one (see [repository layouts](#repository-layouts)). In a bare repository, check the default branch out in your main worktree again (finish the rebase or bisect), or add a worktree for it; with `--separate-git-dir`, run it from the main checkout (after one `wtc start` there, linked worktrees find it too).
730
+
731
+ **`wtc clean` kept a worktree** — it prints why (uncommitted changes, unreachable commits, unpushed submodule commits, locked, or the worktree you're in). Commit or push the work, or pass `--force` to discard it.
732
+
733
+ **"Timed out waiting for the wtc state lock"** — another `wtc` command (or MCP call) is updating `.git/wtc/state.json`; retry when it finishes. If no `wtc` process is running at all, delete the lock file the message names.
734
+
735
+ **"…was written by a newer wtc (state version N); upgrade wtc."** — an older `wtc` (often an MCP server started by a cached install) met a registry written by a newer one. Upgrade it (`npm install -g worktree-compose@latest`) and restart your MCP client. The older version leaves the file untouched.
301
736
 
302
- **"No extra worktrees found"** — Create worktrees first: `git worktree add ../my-feature my-branch`
737
+ **Wrong engine, or the daemon is down** — `wtc doctor` shows which engine was picked and whether its daemon answers. Start the daemon, or set `WTC_COMPOSE_COMMAND` (e.g. `"podman compose"`).
303
738
 
304
- **Ports not changing** — Use `${VAR:-default}` for host ports, not hardcoded numbers.
739
+ ## Contributing
305
740
 
306
- **Stale containers** — Run `wtc clean`, or manually: `docker ps -a --filter "name=-wt-" -q | xargs docker rm -f`
741
+ Issues and pull requests are welcome. Found a bug or have an idea? [Open an issue](https://github.com/mostafasudo/worktree-compose/issues) — and if `wtc` saves you time, a ⭐ on the [repo](https://github.com/mostafasudo/worktree-compose) helps others find it. Docs and demos live at [worktree-compose.com](https://www.worktree-compose.com).
307
742
 
308
743
  ## License
309
744
 
310
- MIT
745
+ [MIT](https://github.com/mostafasudo/worktree-compose/blob/main/LICENSE)