worktree-compose 1.1.1 → 2.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 (77) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +66 -720
  3. package/SKILL.md +73 -76
  4. package/dist/cli.js +85 -10
  5. package/dist/commands/down.d.ts +2 -0
  6. package/dist/commands/down.js +7 -0
  7. package/dist/commands/list.d.ts +2 -0
  8. package/dist/commands/list.js +43 -6
  9. package/dist/commands/passthrough.d.ts +13 -0
  10. package/dist/commands/passthrough.js +27 -0
  11. package/dist/commands/stop.d.ts +3 -1
  12. package/dist/commands/stop.js +2 -2
  13. package/dist/compose/detect.d.ts +19 -0
  14. package/dist/compose/detect.js +56 -0
  15. package/dist/compose/isolation.d.ts +20 -7
  16. package/dist/compose/isolation.js +88 -36
  17. package/dist/compose/override.d.ts +54 -4
  18. package/dist/compose/override.js +179 -52
  19. package/dist/compose/parse.d.ts +11 -0
  20. package/dist/compose/parse.js +260 -13
  21. package/dist/compose/status.d.ts +14 -0
  22. package/dist/compose/status.js +58 -1
  23. package/dist/compose/types.d.ts +56 -0
  24. package/dist/config.d.ts +33 -0
  25. package/dist/context.d.ts +26 -0
  26. package/dist/context.js +140 -29
  27. package/dist/core/clean.d.ts +3 -1
  28. package/dist/core/clean.js +8 -3
  29. package/dist/core/compose.d.ts +87 -13
  30. package/dist/core/compose.js +282 -57
  31. package/dist/core/doctor.d.ts +2 -8
  32. package/dist/core/doctor.js +116 -79
  33. package/dist/core/down.d.ts +37 -0
  34. package/dist/core/down.js +54 -0
  35. package/dist/core/health.d.ts +90 -0
  36. package/dist/core/health.js +198 -0
  37. package/dist/core/list.d.ts +53 -6
  38. package/dist/core/list.js +144 -58
  39. package/dist/core/passthrough.d.ts +69 -0
  40. package/dist/core/passthrough.js +216 -0
  41. package/dist/core/promote.d.ts +4 -2
  42. package/dist/core/promote.js +5 -3
  43. package/dist/core/restart.d.ts +3 -3
  44. package/dist/core/restart.js +6 -5
  45. package/dist/core/seed.d.ts +50 -0
  46. package/dist/core/seed.js +245 -0
  47. package/dist/core/shared.d.ts +63 -0
  48. package/dist/core/shared.js +194 -0
  49. package/dist/core/start.d.ts +32 -5
  50. package/dist/core/start.js +297 -49
  51. package/dist/core/stop.d.ts +3 -1
  52. package/dist/core/stop.js +6 -3
  53. package/dist/core/teardown.d.ts +5 -2
  54. package/dist/core/teardown.js +33 -8
  55. package/dist/core/types.d.ts +2 -0
  56. package/dist/git/promote.d.ts +11 -3
  57. package/dist/git/promote.js +19 -5
  58. package/dist/mcp/server.js +154 -28
  59. package/dist/ports/allocate.d.ts +35 -23
  60. package/dist/ports/allocate.js +108 -58
  61. package/dist/ports/probe.d.ts +11 -0
  62. package/dist/ports/probe.js +40 -0
  63. package/dist/ports/types.d.ts +5 -0
  64. package/dist/selectors.d.ts +17 -0
  65. package/dist/selectors.js +19 -0
  66. package/dist/state/registry.d.ts +23 -3
  67. package/dist/state/registry.js +57 -17
  68. package/dist/sync/env.d.ts +42 -2
  69. package/dist/sync/env.js +79 -8
  70. package/dist/sync/envsync.d.ts +91 -0
  71. package/dist/sync/envsync.js +338 -0
  72. package/dist/sync/files.d.ts +87 -5
  73. package/dist/sync/files.js +343 -18
  74. package/dist/utils/paths.d.ts +2 -0
  75. package/dist/utils/paths.js +9 -0
  76. package/package.json +9 -2
  77. package/wtc.schema.json +155 -13
package/SKILL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: worktree-compose
3
- description: Run several git worktrees in parallel, each with its own isolated Docker Compose stack (ports, containers, networks, volumes), using worktree-compose (`wtc`). Use when starting, stopping, inspecting, or cleaning up per-worktree Docker stacks, finding a worktree's ports or URL, promoting a worktree's changes, configuring `.wtcrc.json`, or calling the wtc MCP tools (`wtc_start`, `wtc_list`, …).
3
+ description: Run several git worktrees in parallel, each with its own isolated Docker Compose stack (ports, containers, networks, volumes), using worktree-compose (`wtc`). Use when starting, stopping, inspecting, or removing a worktree's Docker stack, finding its ports or URL, running commands or reading logs in its containers, promoting a worktree's changes, configuring `.wtcrc.json`, or calling the wtc MCP tools (`wtc_start`, `wtc_list`, `wtc_exec`, …).
4
4
  ---
5
5
 
6
6
  # worktree-compose (`wtc`)
@@ -11,103 +11,100 @@ description: Run several git worktrees in parallel, each with its own isolated D
11
11
 
12
12
  - Installed globally: `npm install -g worktree-compose`, then run `wtc <command>`.
13
13
  - Never run `npx wtc`: an unrelated npm package is named `wtc`. Without a global install, use `npx worktree-compose <command>`.
14
- - Run from the main checkout or any worktree. Compose file, config, and env files always come from the main checkout.
14
+ - Run it from the worktree you work in. Config comes from the main checkout; the compose file is the worktree's own.
15
15
 
16
- ## Everyday loop
16
+ ## The loop, from inside a worktree
17
17
 
18
18
  ```bash
19
- git worktree add -b my-feature ../myapp-my-feature # 1. create the worktree
20
- cd ../myapp-my-feature
21
- wtc start . # 2. sync infra files, inject ports, compose up -d --build
22
- wtc list # 3. status, URL and ports (wtc list --json for parsing)
23
- wtc restart . # after Dockerfile, compose, env or migration changes
24
- wtc stop . # pause; containers and data are kept, start resumes them
19
+ wtc start --wait # this worktree's stack: ports, env files, compose up -d --build; returns when healthy
20
+ wtc list . --json # its ports, URL, and every service's state and health
21
+ wtc exec web bin/test # a command in this worktree's own "web" container
22
+ wtc logs web --tail 50 # why a service fails
23
+ wtc restart --wait # after changing the compose file, a Dockerfile, env values or config
24
+ wtc down # done: remove this stack and its volumes
25
25
  ```
26
26
 
27
- Prefer `.` (the worktree containing the current directory) when working inside a worktree. Other selectors: the stable **index** (`2`), the **branch** (`my-feature`), the **directory name** (`myapp-my-feature`), or a **path**. No selector = all worktrees. A number that is both an index and another worktree's branch/directory name is rejected as ambiguous; pass the branch, directory name, or the path the error suggests (e.g. `../2`).
27
+ Inside a worktree, `start`, `stop`, `restart`, `down`, `exec`, `logs` and `compose` without a selector act on **that worktree only**; `list` shows every worktree (`wtc list .` is this one). Other selectors: the stable **index** (`2`), the **branch**, the **directory name**, a **path**, or `.`; `--all` means every worktree. From the main checkout, `start` / `stop` / `restart` without a selector act on every worktree, and `down` must be told which.
28
+
29
+ ## Rules that prevent mistakes
30
+
31
+ - **Read the ports, never assume them.** A worktree's ports differ from the compose file's. Take them from `wtc start`'s output or `wtc list --json` (`url`, `ports`, `services[].ports[].url`).
32
+ - **Use `wtc exec` / `wtc logs` / `wtc compose`, not `docker exec <name>`.** Container names in the project's scripts and Makefiles (`web`, `db`…) belong to the main checkout's stack: `docker exec web …` from a worktree runs in the wrong stack. `wtc compose <args>` runs any compose command on the worktree's stack.
33
+ - **`wtc down` removes one stack; `wtc clean` removes all of them.** `clean` and `prune` delete volumes of other worktrees too: get the user's go-ahead, preview with `--dry-run`, and never add `--force` unasked.
34
+ - **Do not commit wtc's files.** `wtc` never changes a tracked file and keeps what it writes out of `git status`, so `git status` in a worktree shows your work only.
35
+ - A stack that fails to start: the error names the services that are not ready and shows their last log lines. Fix, then `wtc restart --wait`.
28
36
 
29
37
  ## Commands
30
38
 
31
39
  | Command | Effect |
32
40
  |---------|--------|
33
- | `wtc start [wt...] [--env <file>] [--workspace <ws>]... [--no-build]` | Sync compose/Dockerfiles/`sync` paths from main, copy env files fresh from main, inject ports + `COMPOSE_PROJECT_NAME`, remap hardcoded host ports and `container_name` at runtime, `compose up -d --build`. Stops at the first failure. |
34
- | `wtc stop [wt...]` | `compose stop`. Containers and **all volumes are kept**. |
35
- | `wtc restart [wt...] [same flags]` | `compose stop`, then start with `--remove-orphans`; changed services are recreated, volumes kept. |
36
- | `wtc list` / `wtc ls` `[--json]` | Read-only. Rows: `index, branch, path, project, status, running, total, url, ports, orphan, unavailable`. Status: `up`, `partial`, `exited` (stopped), `down` (no containers), `?` (engine unreachable). `unavailable`: `"missing"` (locked, directory missing — e.g. unmounted drive), `"main"` (became the main checkout), or `null`. |
37
- | `wtc promote <wt> [--force]` | Copy the worktree's changes (committed since it branched, staged, unstaged, untracked; deletions too) into the checkout you run it from, uncommitted. Skips compose files and local env files. |
41
+ | `wtc start [wt...] [--wait] [--wait-timeout <s>] [--service <name>]... [--all-services] [--seed] [--all] [--env <file>] [--workspace <ws>]... [--no-build]` | Settle the stack's host ports (kept from then on), copy the untracked files it needs from main, write its env files, remap hardcoded ports / `container_name` / fixed subnets at runtime, `compose up -d --build`. `--wait`: return when every service is running and healthy, or fail with the reason. `--service`: only those services and their dependencies (remembered for the worktree; `--all-services` forgets). `--seed`: copy the main stack's volumes into a stack that has none yet. |
42
+ | `wtc stop [wt...] [--all]` | `compose stop`. Containers and **all volumes are kept**; `start` resumes. |
43
+ | `wtc restart [wt...] [same flags as start]` | `compose stop`, then start with `--remove-orphans`; changed services are recreated, volumes kept. |
44
+ | `wtc down [wt...] [--all] [--keep-volumes]` | `compose down -v` on the selected stacks (**deletes their volumes**). Worktree, index and ports stay. |
45
+ | `wtc list [wt...]` / `wtc ls` `[--json]` | Read-only. Rows: `index, branch, path, project, status, health, running, total, url, ports, services, detached, orphan, unavailable`. `status`: `up`, `partial`, `exited`, `down`, `?`. `health`: `healthy`, `starting`, `unhealthy` (a service failed, or one the stack should run has no container), or null. `services[]`: `name, state, health, exitCode, ports[{host, container, url}]` (`url` is null for a non-HTTP port such as a database's); state `shared` = the main checkout's instance is used. |
46
+ | `wtc exec [-w <wt>] <service> <command...>` | Run a command in a running service container of the stack; its exit code is passed through. |
47
+ | `wtc logs [-w <wt>] [services...] [--tail <n>] [--since <t>] [-f]` | The stack's logs. |
48
+ | `wtc compose [-w <wt>] <args...>` | Any compose command on the stack, with its project, files and ports (`wtc compose run --rm web bin/setup`). |
49
+ | `wtc promote <wt> [--force]` | Copy the worktree's changes (committed since it branched, staged, unstaged, untracked; deletions too) into the checkout you run it from, uncommitted. Leaves out the env files wtc wrote. |
38
50
  | `wtc prune [--dry-run]` | Tear down (`down -v`, **deletes volumes**) and forget stacks of worktrees that were already deleted. |
39
51
  | `wtc clean [--dry-run] [--force] [--keep-worktrees] [--sweep]` | `down -v` on **every** stack (**deletes all their volumes**), remove worktrees that hold no work, sweep leftovers this checkout owns. |
40
- | `wtc doctor [--json]` | Diagnose git, compose file, config, engine + daemon, port isolation (and what is remapped at runtime, or why not), `container_name` / shared volumes, collisions, orphans, busy ports. Exit 1 on any ✖. |
52
+ | `wtc doctor [--json]` | Diagnose git, compose file, config, engine + daemon, ports and what is remapped, isolation problems, untracked files copied into worktrees, orphans, busy ports. Exit 1 on any ✖. |
41
53
  | `wtc skill [--install] [--dir <path>]` | Print this skill, or install it to `~/.claude/skills/worktree-compose/SKILL.md` (or `<path>/worktree-compose/`). |
42
54
  | `wtc mcp` | MCP server on stdio. |
43
55
 
44
- ## Data safety: stop vs. clean
45
-
46
- - To pause or free CPU/RAM, use `wtc stop`. Data survives; `wtc start` resumes.
47
- - `wtc clean` and `wtc prune` delete volumes (databases, caches). `clean` deletes them for **every** stack, including worktrees it keeps and with `--keep-worktrees`. Get the user's go-ahead before running them, preview with `--dry-run`, and never add `--force` on your own.
48
- - `clean` never removes the main checkout or the worktree it runs from. Without `--force` it also keeps worktrees with uncommitted changes (other than files wtc wrote), commits on a detached HEAD that no branch/tag/remote has, unpushed submodule commits, or a lock, and prints why.
49
- - `clean` only removes Docker resources of stacks this checkout owns. `--sweep` also removes `<repo>-wt-<n>-…` stacks whose worktree directory no longer exists (e.g. left by wtc 0.2), as long as they still have a container; volumes or networks with no container left are listed for the user to remove, never removed.
50
-
51
- ## Identity, ports, project names
52
-
53
- - A worktree's index and compose project are recorded in `.git/wtc/state.json` the first time wtc acts on it (`list`, `doctor` and dry runs only read) and never change: removing a worktree never renumbers the others, renaming its branch keeps the project, `git worktree move` keeps everything. A new worktree gets the lowest free index.
54
- - A deleted worktree becomes an orphan: `wtc list` shows `(removed)` and its index stays reserved until `wtc prune` or `wtc clean`. A worktree git still lists is never an orphan: a locked one whose directory is missing shows `(locked, missing on disk)` and `prune`/`clean` leave its stack alone.
55
- - If wtc cannot tell which checkout is the main one (bare repo whose default-branch worktree is mid-rebase/on another branch, or a `--separate-git-dir` repo seen from a linked worktree before wtc ran in the main checkout), `start`, `restart` and `clean` refuse with the fix in the message; tell the user rather than working around it.
56
- - Ports: `20000 + default_port + index × portStride` (`portStride` default `1`). A host port written as `${VAR:-default}` (upper-case `VAR`) gets `VAR` in the worktree's env file. A hardcoded one (`"8080:80"`) and a fixed `container_name` are remapped at runtime by a generated compose override in `.git/wtc/compose/` (needs Docker Compose 2.24.4+; the compose file is never edited; the old container name stays a network alias inside the stack). A remapped port has no variable: `wtc list` shows it as `<service>:<default port>` (`web:8080=28081`). With an engine that can't remap, hardcoded ports and `container_name` are only warned about.
57
- - Project: `{repo}-wt-{index}-{branch}`, sanitized (e.g. `myapp-wt-1-feature-auth`).
58
-
59
- ## Env files
60
-
61
- - Every start/restart copies `<envFile>` (default `.env`, fallback `.env.example`) **fresh from main**, then writes `COMPOSE_PROJECT_NAME` (root only), the allocated `*_PORT` variables, and `envOverrides`. Existing keys are rewritten in place; the rest go in a `# --- wtc port overrides ---` block.
62
- - 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`.
63
- - Only those keys are written. A value with a port inside (`DATABASE_URL=…:5434/app`) needs an override: `"DATABASE_URL": "postgresql://app:app@localhost:${POSTGRES_PORT}/app"`. `${COMPOSE_PROJECT_NAME}` interpolates too.
64
- - With the default `.env`, a plain `docker compose ps|logs|exec` inside the worktree reaches the worktree's stack. When hardcoded settings are remapped, the root env file also gets `COMPOSE_FILE`, so a plain `docker compose up` from the worktree's root uses the same ports (not from a subdirectory: prefer `wtc restart .`). With a custom `envFile` (e.g. `.env.development`), add `--env-file .env.development` or `-p <project>` (from `wtc list --json`); `-p` is enough for `ps|logs|exec`, but `up` needs `--env-file` (it carries the remap's `COMPOSE_FILE`) — or use `wtc restart .`.
65
- - Monorepos: `--env .env.development --workspace server` (repeatable) also copies and injects `apps/server/.env.development`. Use `--env`, never `--env-file` (Node intercepts it).
56
+ ## What start does to a worktree
66
57
 
67
- ## Promote rules
68
-
69
- `wtc promote <wt>` runs from the checkout that should receive the changes (usually main) and aborts before writing anything when:
70
-
71
- - a file it would touch has uncommitted or untracked changes there: commit or stash first;
72
- - a file it would touch was also committed on that branch since the worktree branched: promoting would revert those commits. Merge that branch into the worktree first (the error prints the command); `--force` overwrites anyway;
73
- - a path escapes the repo or goes through a symlinked directory, or the worktree is the current checkout.
74
-
75
- ## Diagnose
76
-
77
- Run `wtc doctor` first when a stack won't start, ports look wrong, or `wtc list` shows `?` or `(removed)` rows. Typical fixes: drop fixed `name:`/`external` on volumes and networks, raise `portStride` on collisions, give a port a `${VAR:-default}` variable when an env value (e.g. `DATABASE_URL` via `envOverrides`) needs it; where runtime remapping is unavailable, remove `container_name` (or use `${COMPOSE_PROJECT_NAME}`) and write host ports as `${VAR:-default}`; `wtc prune` for orphans, start the Docker/Podman daemon or set `WTC_COMPOSE_COMMAND`.
58
+ - **Ports.** Recorded per worktree in `.git/wtc/state.json` and kept. A new port starts from `20000 + default + index × portStride` and moves to the next free one when taken (another worktree, another repository, anything on the host). A stopped stack's port that something else took moves at the next start, which says so.
59
+ - **Compose file.** The worktree's own: a branch can add services or change ports and start them. Hardcoded host ports, `container_name` (kept as a network alias) and pinned subnets are remapped by a generated override in `.git/wtc/compose/` (Docker Compose 2.24.4+). The compose file is never edited.
60
+ - **Untracked files.** Bind-mount sources, `env_file`s and secret / config files that git does not track, and what `.worktreeinclude` lists, are copied from main where the worktree lacks them. Not copied unasked: a service's data (database files and directories, mounts at `/var/lib/…` or `…/data`) and directories over 2000 files or 200 MB. Add those to `sync` if the worktree needs main's.
61
+ - **Env files.** The configured env file (default `.env`) is copied fresh from main on every start; other untracked `.env*` files are copied when missing. Then `wtc` writes `COMPOSE_PROJECT_NAME`, `COMPOSE_FILE` when needed, the port variables, and `envOverrides`. `localhost:<port>` values are pointed at the worktree's ports. Edits made only in a worktree's copy of the configured env file are lost on the next start: put lasting values in main's file or in `envOverrides`.
62
+ - **Tracked files are never written.** A tracked env file stays as the branch has it; its values go to `<file>.local` (a key that file already sets itself is left alone), and those of `.env` / `.env.development` to `.env.local` as well. If the app reads neither, set `envFile` to an untracked file it does read.
63
+ - **Plain `docker compose`** in a worktree reaches its stack from the worktree's root when the env file is `.env`; with another `envFile`, add `--env-file .env.development`. `wtc compose` needs neither.
64
+ - **Port names.** A port written `${VAR:-8000}:8000` is `VAR`. A hardcoded one is `WTC_<SERVICE>_PORT` (`WTC_WEB_PORT`; further ports `WTC_WEB_443_PORT`). Both are in the env file and usable in `envOverrides`.
65
+ - **Project.** `{repo}-wt-{index}-{branch}`, sanitized (`myapp-wt-1-feature-auth`). Index and project never change; removing a worktree never renumbers the others. A deleted worktree shows as `(removed)` until `wtc prune`.
78
66
 
79
67
  ## Config (optional)
80
68
 
81
- `.wtcrc.json` at the main checkout's root (or `"wtc"` in `package.json`):
82
-
83
- ```json
84
- {
85
- "$schema": "https://unpkg.com/worktree-compose/wtc.schema.json",
86
- "sync": [".generated/prisma-client"],
87
- "envFile": ".env.development",
88
- "workspaces": ["server"],
89
- "envOverrides": { "VITE_API_URL": "http://localhost:${BACKEND_PORT}" },
90
- "workspaceEnvOverrides": { "server": { "DATABASE_URL": "postgresql://app:app@localhost:${POSTGRES_PORT}/app" } },
91
- "portStride": 100,
92
- "composeCommand": "podman compose"
93
- }
94
- ```
95
-
96
- Engines: auto-detects `docker compose` → `podman compose` → `docker-compose` → `podman-compose` (preferring one whose daemon answers). `composeCommand` may only be one of those four; anything custom (e.g. `docker --context colima compose`) goes in the `WTC_COMPOSE_COMMAND` environment variable.
69
+ `.wtcrc.json` at the root of the main checkout, or `"wtc"` in `package.json`. Schema: `https://unpkg.com/worktree-compose/wtc.schema.json`.
70
+
71
+ | Key | Meaning |
72
+ |-----|---------|
73
+ | `services` | Services `start` brings up by default (with dependencies), instead of all. |
74
+ | `shared` | Services a worktree stack does not run: it uses the main checkout's instance under the same name. They must be running in the main checkout. Their data is shared. |
75
+ | `seedVolumes` | `true` or volume keys: copied from the main stack into a worktree stack the first time it starts. |
76
+ | `envOverrides` | Variables for the root env file. Values interpolate `${VAR}` port variables and `${COMPOSE_PROJECT_NAME}`. |
77
+ | `ports` | Ports for processes outside compose: `{ "PORT": 3000 }`. One value per worktree, in its env file. |
78
+ | `composeFile` | A compose file elsewhere than the root, or several to merge. |
79
+ | `sync` | Extra paths copied from main on every start. |
80
+ | `envFile`, `workspaces`, `workspaceEnvOverrides` | Custom env filename; monorepo workspaces that also get env files. |
81
+ | `rewriteEnvPorts` | `false`: leave `localhost:<port>` env values as they are. |
82
+ | `portStride`, `composeCommand` | Where new ports start; which compose tool (`WTC_COMPOSE_COMMAND` for custom commands). |
97
83
 
98
84
  ## MCP tools
99
85
 
100
- Register: `claude mcp add --scope user wtc -- wtc mcp` (Claude Code), or `{"command": "wtc", "args": ["mcp"]}` in `.mcp.json` / `.cursor/mcp.json`, or `[mcp_servers.wtc]` with `command = "wtc"`, `args = ["mcp"]` in `~/.codex/config.toml`. The server acts on the repo of the directory it starts in.
86
+ Register it in Claude Code for every project with `claude mcp add --scope user wtc -- wtc mcp` (other clients: `"command": "wtc", "args": ["mcp"]`). The server acts on the repository of the directory it starts in; started inside a worktree, tools without a worktree act on that worktree.
101
87
 
102
88
  | Tool | Parameters | Notes |
103
89
  |------|-----------|-------|
104
- | `wtc_start` | `indices?`, `envFile?`, `workspaces?`, `build?` (default true) | |
105
- | `wtc_stop` | `indices?` | keeps containers and volumes |
106
- | `wtc_restart` | `indices?`, `envFile?`, `workspaces?`, `build?` | |
107
- | `wtc_list` | — | read-only; `content[0]` is the JSON array, warnings follow |
108
- | `wtc_promote` | `index`, `force?` | destructive: writes into the server's checkout |
109
- | `wtc_clean` | `force?`, `keepWorktrees?`, `dryRun?`, `sweep?` | destructive: deletes volumes, removes worktrees |
110
- | `wtc_prune` | `dryRun?` | destructive: deletes removed worktrees' volumes |
111
- | `wtc_doctor` | — | read-only; returns JSON |
112
-
113
- `indices` is an array of numbers (always indices) or strings (index, branch, directory name, path, `.`); omit it for all worktrees. Failures return `isError: true` with the reason. Mutating tools run one at a time; cancelling a request stops its compose command, and a request cancelled while it waits its turn does not run.
90
+ | `wtc_start` | `indices?`, `all?`, `services?`, `allServices?`, `wait?` (default true), `waitTimeoutSeconds?`, `seed?`, `build?` (default true), `envFile?`, `workspaces?` | Returns when the stack is ready; last content item is JSON with the started stacks and their ports. Failure names the services that are not ready, with logs. |
91
+ | `wtc_stop` | `indices?`, `all?` | Keeps containers and volumes. |
92
+ | `wtc_restart` | same as `wtc_start` | |
93
+ | `wtc_down` | `indices?`, `all?`, `keepVolumes?` | **Destructive**: deletes the stack's volumes. |
94
+ | `wtc_list` | `indices?` | First content item is the JSON array of `wtc list --json`. Read-only. |
95
+ | `wtc_exec` | `service`, `command: string[]`, `worktree?`, `timeoutSeconds?` | Exit code and the end of the output; non-zero exit is an error result. No shell: `["sh", "-c", "…"]` for pipes. |
96
+ | `wtc_logs` | `services?`, `worktree?`, `tail?`, `since?` | Read-only. |
97
+ | `wtc_promote` | `index`, `force?` | **Destructive**: overwrites files in the checkout the server runs in. |
98
+ | `wtc_clean` | `force?`, `keepWorktrees?`, `dryRun?`, `sweep?` | **Destructive**: every worktree's stack and volumes. |
99
+ | `wtc_prune` | `dryRun?` | **Destructive**: deleted worktrees' stacks. |
100
+ | `wtc_doctor` | — | JSON. Read-only. |
101
+
102
+ `indices` is an array of numbers (always indices) or strings (index, branch, directory name, path, `.`). Failures return `isError: true` with the reason. Tools that change stacks run one at a time; cancelling a request stops its compose command.
103
+
104
+ ## Troubleshooting
105
+
106
+ - Start with `wtc doctor`.
107
+ - "No compose file found": the main checkout has none at its root and none in a usual subdirectory; set `composeFile`.
108
+ - A service cannot reach a shared one: start it in the main checkout (`docker compose up -d <service>`), then `wtc start` again.
109
+ - A stack shows `(removed)`: its worktree was deleted. `wtc prune`.
110
+ - "…was written by a newer wtc": upgrade wtc (`npm install -g worktree-compose@latest`) and restart the MCP client.
package/dist/cli.js CHANGED
@@ -7,6 +7,8 @@ import { listCommand } from "./commands/list.js";
7
7
  import { promoteCommand } from "./commands/promote.js";
8
8
  import { cleanCommand } from "./commands/clean.js";
9
9
  import { pruneCommand } from "./commands/prune.js";
10
+ import { downCommand } from "./commands/down.js";
11
+ import { composeCommand, execCommand, logsCommand } from "./commands/passthrough.js";
10
12
  import { doctorCommand } from "./commands/doctor.js";
11
13
  import { skillCommand } from "./commands/skill.js";
12
14
  import { startMcpServer } from "./mcp/server.js";
@@ -16,23 +18,48 @@ const program = new Command();
16
18
  program
17
19
  .name("wtc")
18
20
  .description("Zero-config Docker Compose isolation for git worktrees")
19
- .version(VERSION);
20
- function collectWorkspace(value, previous) {
21
+ .version(VERSION)
22
+ // `wtc exec web ls -la` and `wtc compose logs -f`: options after the
23
+ // subcommand's first argument belong to the command being run.
24
+ .enablePositionalOptions();
25
+ function collect(value, previous) {
21
26
  return [...previous, value];
22
27
  }
23
28
  function startCliOptions(options) {
29
+ let waitTimeoutSeconds;
30
+ if (options.waitTimeout !== undefined) {
31
+ waitTimeoutSeconds = Number(options.waitTimeout);
32
+ if (!Number.isFinite(waitTimeoutSeconds) || waitTimeoutSeconds <= 0) {
33
+ throw new Error(`Invalid --wait-timeout "${options.waitTimeout}": expected a number of seconds.`);
34
+ }
35
+ }
24
36
  return {
25
37
  envFile: options.env,
26
38
  workspaces: options.workspace,
27
39
  build: options.build !== false,
40
+ all: options.all,
41
+ services: options.service,
42
+ allServices: options.allServices,
43
+ // A timeout only makes sense when waiting.
44
+ wait: options.wait || waitTimeoutSeconds !== undefined,
45
+ waitTimeoutSeconds,
46
+ seed: options.seed,
28
47
  };
29
48
  }
30
- const WORKTREES_ARG_HELP = "Worktrees by index, branch, directory name, path, or . (omit for all)";
49
+ const WORKTREES_ARG_HELP = "Worktrees by index, branch, directory name, path, or . (none: the worktree you are in; from the main checkout, all)";
50
+ const WORKTREE_OPTION = ["-w, --worktree <worktree>", "Worktree whose stack to use (default: the one you are in)"];
31
51
  function withStartOptions(command) {
32
52
  return command
33
53
  .option("--env <name>", 'Env filename to copy and inject (default: config "envFile", else ".env")')
34
- .option("--workspace <name>", "Workspace to also inject env into (repeatable)", collectWorkspace, [])
35
- .option("--no-build", "Skip --build on docker compose up");
54
+ .option("--workspace <name>", "Workspace to also inject env into (repeatable)", collect, [])
55
+ .option("--no-build", "Skip --build on docker compose up")
56
+ .option("--all", "Every worktree, even when run from inside one")
57
+ .option("--service <name>", "Bring up only this service and what it depends on (repeatable; remembered for the worktree)", collect, [])
58
+ .option("--all-services", "Bring up every service again, forgetting --service")
59
+ .option("--wait", "Return once every service is running and healthy; fail with their logs otherwise")
60
+ .option("--wait-timeout <seconds>", "How long --wait waits (default 300; implies --wait)")
61
+ .option("--seed", "Copy the main checkout stack's volumes into a stack that has none yet")
62
+ .option("--no-seed", 'Do not copy volumes, whatever "seedVolumes" says');
36
63
  }
37
64
  withStartOptions(program
38
65
  .command("start")
@@ -44,8 +71,55 @@ program
44
71
  .command("stop")
45
72
  .description("Stop the containers of worktree stacks (start resumes them)")
46
73
  .argument("[worktrees...]", WORKTREES_ARG_HELP)
47
- .action(async (worktrees) => {
48
- await wrap(() => stopCommand(worktrees));
74
+ .option("--all", "Every worktree, even when run from inside one")
75
+ .action(async (worktrees, options) => {
76
+ await wrap(() => stopCommand(worktrees, options));
77
+ });
78
+ program
79
+ .command("down")
80
+ .description("Remove the stacks of worktrees (down -v: deletes their volumes); the worktrees, their indices and ports stay")
81
+ .argument("[worktrees...]", "Worktrees by index, branch, directory name, path, or . (none: the worktree you are in)")
82
+ .option("--all", "Every worktree's stack")
83
+ .option("--keep-volumes", "Remove containers and networks, keep the volumes")
84
+ .action(async (worktrees, options) => {
85
+ await wrap(() => downCommand(worktrees, options));
86
+ });
87
+ program
88
+ .command("exec")
89
+ .description("Run a command in a service container of a worktree's stack")
90
+ .argument("<service>", "Compose service")
91
+ .argument("<command...>", "Command and its arguments")
92
+ .option(...WORKTREE_OPTION)
93
+ .passThroughOptions()
94
+ .action(async (service, command, options) => {
95
+ await wrap(() => execCommand(service, command, options));
96
+ });
97
+ program
98
+ .command("logs")
99
+ .description("Show the logs of a worktree's stack")
100
+ .argument("[services...]", "Services (default: all)")
101
+ .option(...WORKTREE_OPTION)
102
+ .option("--tail <lines>", "Lines from the end of each service's log", "100")
103
+ .option("--since <time>", "Only logs newer than this (e.g. 10m)")
104
+ .option("-f, --follow", "Keep following the logs")
105
+ .action(async (services, options) => {
106
+ await wrap(() => {
107
+ const tail = Number(options.tail);
108
+ if (!Number.isInteger(tail) || tail < 0) {
109
+ throw new Error(`Invalid --tail "${options.tail}": expected a number of lines.`);
110
+ }
111
+ return logsCommand(services, { ...options, tail });
112
+ });
113
+ });
114
+ program
115
+ .command("compose")
116
+ .description("Run any compose command on a worktree's stack (its project, files and ports)")
117
+ .argument("<args...>", "Compose command and its arguments, e.g. ps, or run --rm web bin/setup")
118
+ .option(...WORKTREE_OPTION)
119
+ .allowUnknownOption()
120
+ .passThroughOptions()
121
+ .action(async (args, options) => {
122
+ await wrap(() => composeCommand(args, options));
49
123
  });
50
124
  withStartOptions(program
51
125
  .command("restart")
@@ -56,10 +130,11 @@ withStartOptions(program
56
130
  program
57
131
  .command("list")
58
132
  .alias("ls")
59
- .description("List worktrees with status, ports and URLs")
133
+ .description("List worktrees with status, services, ports and URLs")
134
+ .argument("[worktrees...]", "Only these worktrees (index, branch, directory name, path, or .)")
60
135
  .option("--json", "Print machine-readable JSON")
61
- .action(async (options) => {
62
- await wrap(() => listCommand({ json: options.json }));
136
+ .action(async (worktrees, options) => {
137
+ await wrap(() => listCommand({ json: options.json, worktrees }));
63
138
  });
64
139
  program
65
140
  .command("promote")
@@ -0,0 +1,2 @@
1
+ import type { DownOptions } from "../core/down.js";
2
+ export declare function downCommand(worktrees: string[], options?: Omit<DownOptions, "worktrees">): Promise<void>;
@@ -0,0 +1,7 @@
1
+ import { downWorktrees } from "../core/down.js";
2
+ import { consoleReporter } from "../utils/log.js";
3
+ export async function downCommand(worktrees, options = {}) {
4
+ const result = await downWorktrees({ ...options, worktrees }, consoleReporter, { live: true });
5
+ if (result.failures > 0)
6
+ process.exitCode = 1;
7
+ }
@@ -1,4 +1,6 @@
1
+ import type { WorktreeSelector } from "../selectors.js";
1
2
  export declare function listCommand(options?: {
2
3
  json?: boolean;
3
4
  quiet?: boolean;
5
+ worktrees?: WorktreeSelector[];
4
6
  }): Promise<void>;
@@ -1,13 +1,33 @@
1
1
  import Table from "cli-table3";
2
2
  import chalk from "chalk";
3
- import { listWorktrees } from "../core/list.js";
3
+ import { listWorktrees, worktreeLabel } from "../core/list.js";
4
4
  import { print, warn } from "../utils/log.js";
5
+ /** `kibana exited (1)`, `web unhealthy`: the services that keep a stack from being fully up, a few of them. */
6
+ function troubled(row) {
7
+ const names = row.services
8
+ .filter((s) => s.health === "unhealthy" ||
9
+ s.health === "starting" ||
10
+ (s.state === "exited" && s.exitCode !== null && s.exitCode !== 0) ||
11
+ ["created", "restarting", "dead", "paused"].includes(s.state))
12
+ .map((s) => s.state === "running"
13
+ ? `${s.name} ${s.health}`
14
+ : s.state === "exited"
15
+ ? `${s.name} exited (${s.exitCode})`
16
+ : `${s.name} ${s.state}`);
17
+ if (names.length === 0)
18
+ return "";
19
+ return `: ${names.slice(0, 3).join(", ")}${names.length > 3 ? `, +${names.length - 3}` : ""}`;
20
+ }
5
21
  function renderStatus(row) {
6
22
  switch (row.status) {
7
23
  case "up":
8
- return chalk.green("up");
24
+ return row.health === "unhealthy"
25
+ ? chalk.red(`up, unhealthy${troubled(row)}`)
26
+ : row.health === "starting"
27
+ ? chalk.yellow(`up, starting${troubled(row)}`)
28
+ : chalk.green("up");
9
29
  case "partial":
10
- return chalk.yellow(`partial ${row.running}/${row.total}`);
30
+ return chalk.yellow(`partial ${row.running}/${row.total}${troubled(row)}`);
11
31
  case "exited":
12
32
  return chalk.yellow("exited");
13
33
  case "down":
@@ -17,7 +37,7 @@ function renderStatus(row) {
17
37
  }
18
38
  }
19
39
  export async function listCommand(options = {}) {
20
- const result = listWorktrees({ live: true });
40
+ const result = listWorktrees({ live: true }, { worktrees: options.worktrees });
21
41
  if (options.json) {
22
42
  // Keep stdout machine-readable: warnings go to stderr.
23
43
  for (const w of result.warnings)
@@ -35,6 +55,21 @@ export async function listCommand(options = {}) {
35
55
  print("\nNo extra worktrees found. Create one with:\n git worktree add ../my-branch my-branch\n");
36
56
  return;
37
57
  }
58
+ // A stack with twenty ports does not fit on a line: the last two columns wrap
59
+ // within the terminal's width.
60
+ const width = Math.max(process.stdout.columns || 160, 100);
61
+ const widest = (values, cap) => Math.min(cap, Math.max(...values.map((v) => v.length))) + 2;
62
+ const labels = result.rows.map((r) => {
63
+ const label = worktreeLabel(r);
64
+ return r.orphan ? `${label} (removed)` : r.unavailable ? `${label} (${r.unavailable})` : label;
65
+ });
66
+ const fixed = [
67
+ 7,
68
+ widest(["Branch", ...labels, "main"], 40),
69
+ widest(["Status", ...result.rows.map((r) => `partial 00/00${troubled(r)}`)], 34),
70
+ widest(["URL", ...result.rows.map((r) => r.url ?? "-")], 34),
71
+ ];
72
+ const portsWidth = Math.max(24, width - fixed.reduce((a, b) => a + b, 0) - 6);
38
73
  const table = new Table({
39
74
  head: [
40
75
  chalk.white("Index"),
@@ -43,6 +78,8 @@ export async function listCommand(options = {}) {
43
78
  chalk.white("URL"),
44
79
  chalk.white("Ports"),
45
80
  ],
81
+ colWidths: [...fixed, portsWidth],
82
+ wordWrap: true,
46
83
  });
47
84
  table.push([
48
85
  chalk.dim("-"),
@@ -63,7 +100,7 @@ export async function listCommand(options = {}) {
63
100
  : "now the main checkout";
64
101
  table.push([
65
102
  chalk.dim(String(row.index)),
66
- chalk.dim(`${row.branch} (${note})`),
103
+ chalk.dim(`${worktreeLabel(row)} (${note})`),
67
104
  renderStatus(row),
68
105
  chalk.dim("-"),
69
106
  chalk.dim(ports),
@@ -73,7 +110,7 @@ export async function listCommand(options = {}) {
73
110
  const url = row.url ?? "-";
74
111
  table.push([
75
112
  String(row.index),
76
- row.branch,
113
+ worktreeLabel(row),
77
114
  renderStatus(row),
78
115
  row.status === "up" || row.status === "partial" ? chalk.underline(url) : chalk.dim(url),
79
116
  ports,
@@ -0,0 +1,13 @@
1
+ import type { LogsOptions } from "../core/passthrough.js";
2
+ /** `wtc compose [-w <worktree>] <args…>`: any compose command on the worktree's stack. */
3
+ export declare function composeCommand(args: string[], options: {
4
+ worktree?: string;
5
+ }): Promise<void>;
6
+ /** `wtc exec [-w <worktree>] <service> <command…>`: a command in a running service container. */
7
+ export declare function execCommand(service: string, command: string[], options: {
8
+ worktree?: string;
9
+ }): Promise<void>;
10
+ /** `wtc logs [-w <worktree>] [services…]`: the stack's logs. */
11
+ export declare function logsCommand(services: string[], options: {
12
+ worktree?: string;
13
+ } & Omit<LogsOptions, "services">): Promise<void>;
@@ -0,0 +1,27 @@
1
+ import { composeSubcommand, execArgs, logsArgs, resolveStackCall, runAttached } from "../core/passthrough.js";
2
+ import { unlinkSharedServices } from "../core/shared.js";
3
+ /** `wtc compose [-w <worktree>] <args…>`: any compose command on the worktree's stack. */
4
+ export async function composeCommand(args, options) {
5
+ if (args.length === 0)
6
+ throw new Error("Give a compose command to run, e.g. 'wtc compose ps'.");
7
+ const call = resolveStackCall(options.worktree, { live: true });
8
+ // The main checkout's shared containers sit on the stack's networks: `down` cannot remove
9
+ // those otherwise. A dry run changes nothing, so it must not disconnect them either.
10
+ const { command, dryRun } = composeSubcommand(args);
11
+ if (command === "down" && !dryRun)
12
+ unlinkSharedServices(call.engine, call.worktree.project, call.mainDirs);
13
+ process.exitCode = await runAttached(call, args);
14
+ }
15
+ /** `wtc exec [-w <worktree>] <service> <command…>`: a command in a running service container. */
16
+ export async function execCommand(service, command, options) {
17
+ if (command.length === 0)
18
+ throw new Error(`Give a command to run in "${service}", e.g. 'wtc exec ${service} sh'.`);
19
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
20
+ process.exitCode = await runAttached(resolveStackCall(options.worktree, { live: true }), execArgs(service, command, interactive));
21
+ }
22
+ /** `wtc logs [-w <worktree>] [services…]`: the stack's logs. */
23
+ export async function logsCommand(services, options) {
24
+ process.exitCode = await runAttached(resolveStackCall(options.worktree, { live: true }, { readOnly: true }),
25
+ // In a terminal compose colours the service names itself.
26
+ logsArgs({ ...options, services }).filter((a) => a !== "--no-color" || !process.stdout.isTTY));
27
+ }
@@ -1 +1,3 @@
1
- export declare function stopCommand(worktrees: string[]): Promise<void>;
1
+ export declare function stopCommand(worktrees: string[], options?: {
2
+ all?: boolean;
3
+ }): Promise<void>;
@@ -1,7 +1,7 @@
1
1
  import { stopWorktrees } from "../core/stop.js";
2
2
  import { consoleReporter } from "../utils/log.js";
3
- export async function stopCommand(worktrees) {
4
- const result = await stopWorktrees({ worktrees }, consoleReporter, { live: true });
3
+ export async function stopCommand(worktrees, options = {}) {
4
+ const result = await stopWorktrees({ worktrees, all: options.all }, consoleReporter, { live: true });
5
5
  if (result.failures > 0)
6
6
  process.exitCode = 1;
7
7
  }
@@ -1,2 +1,21 @@
1
1
  export declare const COMPOSE_FILENAMES: string[];
2
2
  export declare function detectComposeFile(repoRoot: string): string | null;
3
+ export interface ComposeRoots {
4
+ /** The files compose is given, absolute, in order; empty when none was found. */
5
+ files: string[];
6
+ /**
7
+ * Compose would not find these by itself from the repository root (a
8
+ * custom name, a subdirectory, several files): every call must name them.
9
+ */
10
+ custom: boolean;
11
+ /** Said once, when wtc picked a file outside the repository root by itself. */
12
+ note?: string;
13
+ }
14
+ /**
15
+ * The project's compose files: the config's `composeFile` (one path or
16
+ * several, relative to the repository root), else a default name at the
17
+ * root, else the single compose file in a usual subdirectory (`docker/`,
18
+ * `deploy/`, `.devcontainer/`…). Several candidates there are an error
19
+ * that names them: wtc does not guess which one is the project's.
20
+ */
21
+ export declare function resolveComposeRoots(repoRoot: string, configured?: string | string[]): ComposeRoots;
@@ -1,11 +1,14 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { resolveInside } from "../utils/paths.js";
3
4
  export const COMPOSE_FILENAMES = [
4
5
  "compose.yaml",
5
6
  "compose.yml",
6
7
  "docker-compose.yaml",
7
8
  "docker-compose.yml",
8
9
  ];
10
+ /** Directories searched for a compose file when the repository root has none. */
11
+ const COMPOSE_DIRS = ["docker", ".docker", "compose", "deploy", "infra", ".devcontainer"];
9
12
  export function detectComposeFile(repoRoot) {
10
13
  for (const name of COMPOSE_FILENAMES) {
11
14
  const full = path.join(repoRoot, name);
@@ -14,3 +17,56 @@ export function detectComposeFile(repoRoot) {
14
17
  }
15
18
  return null;
16
19
  }
20
+ /**
21
+ * The project's compose files: the config's `composeFile` (one path or
22
+ * several, relative to the repository root), else a default name at the
23
+ * root, else the single compose file in a usual subdirectory (`docker/`,
24
+ * `deploy/`, `.devcontainer/`…). Several candidates there are an error
25
+ * that names them: wtc does not guess which one is the project's.
26
+ */
27
+ export function resolveComposeRoots(repoRoot, configured) {
28
+ if (configured !== undefined) {
29
+ const entries = Array.isArray(configured) ? configured : [configured];
30
+ const files = entries.map((entry) => {
31
+ const abs = resolveInside(repoRoot, entry);
32
+ if (!abs) {
33
+ throw new Error(`Invalid "composeFile" entry "${entry}": it must be a path inside the repository.`);
34
+ }
35
+ const stat = fs.statSync(abs, { throwIfNoEntry: false });
36
+ if (!stat) {
37
+ throw new Error(`"composeFile" entry "${entry}" does not exist (${abs}).`);
38
+ }
39
+ if (!stat.isFile()) {
40
+ throw new Error(`"composeFile" entry "${entry}" is not a file (${abs}): name the compose file itself.`);
41
+ }
42
+ return abs;
43
+ });
44
+ const isDefault = files.length === 1 &&
45
+ path.dirname(files[0]) === path.resolve(repoRoot) &&
46
+ detectComposeFile(repoRoot) === files[0];
47
+ return { files, custom: !isDefault };
48
+ }
49
+ const atRoot = detectComposeFile(repoRoot);
50
+ if (atRoot)
51
+ return { files: [atRoot], custom: false };
52
+ const found = [];
53
+ for (const dir of COMPOSE_DIRS) {
54
+ const file = detectComposeFile(path.join(repoRoot, dir));
55
+ if (file)
56
+ found.push(file);
57
+ }
58
+ if (found.length === 1) {
59
+ const rel = path.relative(repoRoot, found[0]);
60
+ return {
61
+ files: found,
62
+ custom: true,
63
+ note: `Using ${rel} as the compose file (none at the repository root). Set "composeFile" in .wtcrc.json to choose another.`,
64
+ };
65
+ }
66
+ if (found.length > 1) {
67
+ throw new Error(`No compose file at the root of ${repoRoot}, and several elsewhere: ${found
68
+ .map((f) => path.relative(repoRoot, f))
69
+ .join(", ")}. Set "composeFile" in .wtcrc.json to the one (or the list) your project runs.`);
70
+ }
71
+ return { files: [], custom: false };
72
+ }