worktree-compose 0.1.3 → 0.2.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.
package/README.md CHANGED
@@ -1,12 +1,22 @@
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
+ # worktree-compose · `wtc`
4
4
 
5
- Zero-config Docker Compose isolation for git worktrees.
5
+ ### Zero-config Docker Compose isolation for git worktrees
6
6
 
7
- Every worktree gets its own ports, database, cache, and containers — automatically.
7
+ Every worktree gets its own ports, database, cache, and containers — **automatically**.
8
8
 
9
- https://github.com/LevwTech/worktree-compose/raw/main/wtc-explainer.mp4
9
+ [![npm version](https://img.shields.io/npm/v/worktree-compose?label=npm&color=cb3837&logo=npm)](https://www.npmjs.com/package/worktree-compose)
10
+ [![downloads](https://img.shields.io/npm/dm/worktree-compose?color=cb3837)](https://www.npmjs.com/package/worktree-compose)
11
+ [![node](https://img.shields.io/node/v/worktree-compose?color=339933&logo=node.js&logoColor=white)](https://nodejs.org)
12
+ [![license](https://img.shields.io/npm/l/worktree-compose?color=blue)](./LICENSE)
13
+ [![DevHunt](https://img.shields.io/badge/DevHunt-%231%20Product%20of%20the%20Week-ff6154)](https://devhunt.org/tool/worktree-compose)
14
+
15
+ <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" />
16
+
17
+ <em>The full <code>wtc</code> workflow: an isolated Docker stack per worktree, several AI agents building in parallel, compared live on their own ports — then promote the winner.</em>
18
+
19
+ </div>
10
20
 
11
21
  ```bash
12
22
  npm install -D worktree-compose
@@ -26,6 +36,82 @@ npx wtc list
26
36
  └───────┴───────────────┴────────┴────────────────────────┴─────────────────────────────────────────────────────────┘
27
37
  ```
28
38
 
39
+ ## Contents
40
+
41
+ - [Why wtc?](#why-wtc)
42
+ - [How is this different from `docker compose -p`?](#how-is-this-different-from-docker-compose--p)
43
+ - [Quick Start](#quick-start)
44
+ - [Usage](#usage)
45
+ - [Preparing your docker-compose.yml](#preparing-your-docker-composeyml)
46
+ - [How It Works](#how-it-works)
47
+ - [Commands](#commands)
48
+ - [Configuration (Optional)](#configuration-optional)
49
+ - [MCP Server](#mcp-server)
50
+ - [Full Example](#full-example)
51
+ - [Requirements](#requirements)
52
+ - [Troubleshooting](#troubleshooting)
53
+ - [Contributing](#contributing)
54
+ - [License](#license)
55
+
56
+ ## Why wtc?
57
+
58
+ 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.
59
+
60
+ `wtc` reads your existing `docker-compose.yml` and turns every worktree into a fully isolated, side-by-side environment — unique host ports, separate containers, networks, and volumes — with **zero configuration**.
61
+
62
+ - ⚡ **Zero config** — reads your existing `docker-compose.yml`, no new files required
63
+ - 🔌 **Automatic ports** — unique, collision-free host ports per worktree
64
+ - 📦 **Full isolation** — separate containers, networks, and volumes for each stack
65
+ - 🧪 **True side-by-side** — run `N` stacks at once and compare them in the browser
66
+ - 🔄 **One-command promote** — pull a worktree's changes back into your branch
67
+ - 🤖 **Built-in MCP server** — let AI agents start, stop, and manage their own stacks
68
+
69
+ <table>
70
+ <tr><th>Without <code>wtc</code></th><th>With <code>wtc</code></th></tr>
71
+ <tr><td>
72
+
73
+ ```bash
74
+ git worktree add ../app-feat feat
75
+ # hand-pick non-colliding host ports
76
+ # edit ../app-feat/.env per service
77
+ # copy compose file + Dockerfiles over
78
+ docker compose -p app-feat up -d --build
79
+ # ...remember to tear it all down later
80
+ ```
81
+
82
+ </td><td>
83
+
84
+ ```bash
85
+ git worktree add ../app-feat feat
86
+ wtc start
87
+
88
+ # ...and when you're done:
89
+ wtc clean
90
+ ```
91
+
92
+ </td></tr>
93
+ </table>
94
+
95
+ ## How is this different from `docker compose -p`?
96
+
97
+ `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, and tear everything down yourself. `wtc` builds on that same project-name isolation and automates the rest: collision-free **port allocation**, per-worktree **`.env` injection**, infra-file **sync**, one-command **`promote`**, and a built-in **MCP server** so AI agents can drive it all themselves.
98
+
99
+ ## Quick Start
100
+
101
+ ```bash
102
+ # 1. Install
103
+ npm install -D worktree-compose
104
+
105
+ # 2. Create a worktree for some parallel work
106
+ git worktree add ../myapp-feature feature-branch
107
+
108
+ # 3. Boot an isolated stack for it
109
+ npx wtc start
110
+
111
+ # 4. See everything that's running
112
+ npx wtc list
113
+ ```
114
+
29
115
  ## Usage
30
116
 
31
117
  ```bash
@@ -53,15 +139,7 @@ npx wtc promote 1
53
139
  npx wtc clean
54
140
  ```
55
141
 
56
- ## The Problem
57
-
58
- 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.
59
-
60
- ## The Solution
61
-
62
- `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.
63
-
64
- ## Preparing Your docker-compose.yml
142
+ ## Preparing your docker-compose.yml
65
143
 
66
144
  For `wtc` to isolate a service's port, the host port must use the `${VAR:-default}` pattern:
67
145
 
@@ -107,11 +185,25 @@ If `wtc` finds hardcoded ports, it warns you and suggests the fix:
107
185
  protocol: tcp
108
186
  ```
109
187
 
188
+ ### Included compose files
189
+
190
+ 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.
191
+
192
+ ```yaml
193
+ include:
194
+ - ./db/compose.yml
195
+ - path: ./services/api/compose.yml
196
+ ```
197
+
198
+ 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.)
199
+
110
200
  ## How It Works
111
201
 
112
202
  ### Port Allocation
113
203
 
114
- Each worktree N gets unique ports: `20000 + default_port + worktree_index`
204
+ Each worktree N gets unique ports: `20000 + default_port + (worktree_index × portStride)`
205
+
206
+ `portStride` defaults to `1`, so by default the table below holds:
115
207
 
116
208
  | Service | Main (default) | Worktree 1 | Worktree 2 | Worktree 3 |
117
209
  |----------|---------------|------------|------------|------------|
@@ -120,13 +212,27 @@ Each worktree N gets unique ports: `20000 + default_port + worktree_index`
120
212
  | backend | 8000 | 28001 | 28002 | 28003 |
121
213
  | frontend | 5173 | 25174 | 25175 | 25176 |
122
214
 
215
+ The table is illustrative — every value follows the formula above. (If an allocation would exceed `65535`, `wtc` falls back to `default_port + 100 × index`.)
216
+
217
+ #### Clustered default ports and `portStride`
218
+
219
+ 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.
220
+
221
+ When `wtc` detects such a collision across your current worktrees it prints a warning 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:
222
+
223
+ ```json
224
+ { "portStride": 100 }
225
+ ```
226
+
227
+ 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` (no `wtc` env) is unaffected — only each worktree's `.env` override block changes.
228
+
123
229
  ### Container Isolation
124
230
 
125
- Each worktree gets its own `COMPOSE_PROJECT_NAME`: `{repo}-wt-{index}-{branch}`. This means separate containers, networks, and volumes. Nothing is shared.
231
+ Each worktree gets its own `COMPOSE_PROJECT_NAME` — `{repo}-wt-{index}-{branch}`, lowercased and sanitized to a Docker-safe name. That means separate containers, networks, and volumes. Nothing is shared.
126
232
 
127
233
  ### File Sync
128
234
 
129
- 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.
235
+ Before starting, `wtc` copies infrastructure files from main into each worktree: the compose file (plus any files it pulls in via `include:`), every Dockerfile referenced by a service's `build`, and your base `.env` (falling back to `.env.example`, or an empty file if neither exists). This keeps every worktree on the latest Docker setup.
130
236
 
131
237
  ### Env Injection
132
238
 
@@ -143,6 +249,8 @@ FRONTEND_PORT=25174
143
249
  # --- end wtc ---
144
250
  ```
145
251
 
252
+ Re-running `wtc start` strips and rewrites this block, so it never accumulates.
253
+
146
254
  ## Commands
147
255
 
148
256
  ### `wtc start [indices...]`
@@ -182,7 +290,7 @@ npx wtc list
182
290
 
183
291
  ### `wtc promote <index>`
184
292
 
185
- 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.
293
+ Copy a worktree's changed files — added, modified, and deleted — into your current branch as uncommitted changes. Skips `.env` and compose files, and aborts if any file it would touch has uncommitted local changes.
186
294
 
187
295
  ```bash
188
296
  npx wtc promote 1
@@ -205,11 +313,12 @@ npx wtc clean
205
313
  "sync": [".generated/prisma-client", "local-certs/"],
206
314
  "envOverrides": {
207
315
  "VITE_API_URL": "http://localhost:${BACKEND_PORT}"
208
- }
316
+ },
317
+ "portStride": 100
209
318
  }
210
319
  ```
211
320
 
212
- Or use a `"wtc"` key in `package.json`.
321
+ Or use a `"wtc"` key in `package.json`. (`.wtcrc.json` takes precedence.)
213
322
 
214
323
  ### `sync`
215
324
 
@@ -219,6 +328,10 @@ Extra files/directories to copy from main into each worktree on start. Use for g
219
328
 
220
329
  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`).
221
330
 
331
+ ### `portStride`
332
+
333
+ Port spacing between consecutive worktree indices (default `1`). 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.
334
+
222
335
  ## MCP Server
223
336
 
224
337
  Built-in [MCP](https://modelcontextprotocol.io/) server so AI agents can manage their stack programmatically.
@@ -303,6 +416,12 @@ npx wtc clean
303
416
 
304
417
  **Stale containers** — Run `wtc clean`, or manually: `docker ps -a --filter "name=-wt-" -q | xargs docker rm -f`
305
418
 
419
+ ## Contributing
420
+
421
+ 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.
422
+
306
423
  ## License
307
424
 
308
- MIT
425
+ [MIT](./LICENSE)
426
+ </content>
427
+ </invoke>
@@ -45,7 +45,7 @@ export function listCommand() {
45
45
  const wt = ctx.worktrees[i];
46
46
  const idx = i + 1;
47
47
  const project = composeProjectName(ctx.repoName, idx, wt.branch);
48
- const allocations = allocateWorktreePorts(ctx.portMappings, idx);
48
+ const allocations = allocateWorktreePorts(ctx.portMappings, idx, ctx.portStride);
49
49
  const up = isWorktreeUp(project, wt.path);
50
50
  const ports = allocations
51
51
  .map((a) => `${a.serviceName}:${a.port}`)
@@ -16,7 +16,7 @@ export function startCommand(indices) {
16
16
  for (const wt of targets) {
17
17
  const idx = ctx.worktrees.indexOf(wt) + 1;
18
18
  const project = composeProjectName(ctx.repoName, idx, wt.branch);
19
- const allocations = allocateWorktreePorts(ctx.portMappings, idx);
19
+ const allocations = allocateWorktreePorts(ctx.portMappings, idx, ctx.portStride);
20
20
  log.header(`Worktree ${idx}: ${wt.branch}`);
21
21
  log.info(`Path: ${wt.path}`);
22
22
  log.info(`Project: ${project}`);
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import path from "node:path";
2
3
  import { parse as parseYaml } from "yaml";
3
4
  function parseServicePorts(ports) {
4
5
  if (!Array.isArray(ports))
@@ -38,18 +39,127 @@ function parseEnvFile(envFile) {
38
39
  }
39
40
  return undefined;
40
41
  }
41
- export function parseComposeFile(composePath) {
42
- const raw = fs.readFileSync(composePath, "utf-8");
43
- const doc = parseYaml(raw, { uniqueKeys: false });
44
- if (!doc || typeof doc !== "object" || !("services" in doc)) {
45
- return { services: [], composePath };
42
+ function parseServicesObject(doc, sourcePath) {
43
+ if (!("services" in doc) || !doc.services || typeof doc.services !== "object") {
44
+ return [];
46
45
  }
47
46
  const servicesObj = doc.services;
48
- const services = Object.entries(servicesObj).map(([name, svc]) => ({
49
- name,
50
- ports: parseServicePorts(svc.ports),
51
- build: parseServiceBuild(svc.build),
52
- envFile: parseEnvFile(svc.env_file),
53
- }));
54
- return { services, composePath };
47
+ return Object.entries(servicesObj).map(([name, svc]) => {
48
+ // An empty service definition (`foo:` with no body) parses to null.
49
+ const s = svc ?? {};
50
+ return {
51
+ name,
52
+ ports: parseServicePorts(s.ports),
53
+ build: parseServiceBuild(s.build),
54
+ envFile: parseEnvFile(s.env_file),
55
+ sourcePath,
56
+ };
57
+ });
58
+ }
59
+ /**
60
+ * Normalize a top-level `include:` value into a list of resolved absolute
61
+ * paths. Each entry is a string path or a long-form object whose `path` is a
62
+ * string or list of strings. Paths resolve relative to the directory of the
63
+ * file currently being parsed.
64
+ */
65
+ function normalizeIncludes(include, parentPath) {
66
+ if (!Array.isArray(include))
67
+ return [];
68
+ const dir = path.dirname(parentPath);
69
+ const out = [];
70
+ for (const entry of include) {
71
+ let paths = [];
72
+ if (typeof entry === "string") {
73
+ paths = [entry];
74
+ }
75
+ else if (entry && typeof entry === "object" && "path" in entry) {
76
+ const p = entry.path;
77
+ if (typeof p === "string") {
78
+ paths = [p];
79
+ }
80
+ else if (Array.isArray(p)) {
81
+ paths = p.filter((s) => typeof s === "string");
82
+ }
83
+ }
84
+ for (const p of paths)
85
+ out.push(path.resolve(dir, p));
86
+ }
87
+ return out;
88
+ }
89
+ /**
90
+ * Combine two definitions of the same service. Docker Compose deep-merges
91
+ * same-named services across included/overriding files rather than replacing
92
+ * them wholesale, so a later definition that omits `ports` must NOT discard the
93
+ * earlier one's ports — otherwise that service silently loses its per-worktree
94
+ * port isolation. We merge the fields wtc relies on: ports are unioned (deduped
95
+ * by raw mapping so the allocator never sees a duplicate), while build/envFile
96
+ * fall back to the base when the override doesn't set them. sourcePath stays
97
+ * aligned with whichever file actually declared `build`, so getDockerfiles
98
+ * resolves the context relative to the right directory.
99
+ */
100
+ function mergeService(base, override) {
101
+ const ports = [...base.ports];
102
+ for (const p of override.ports) {
103
+ if (!ports.includes(p))
104
+ ports.push(p);
105
+ }
106
+ const sourcePath = override.build !== undefined
107
+ ? override.sourcePath
108
+ : base.build !== undefined
109
+ ? base.sourcePath
110
+ : override.sourcePath;
111
+ return {
112
+ name: override.name,
113
+ ports,
114
+ build: override.build ?? base.build,
115
+ envFile: override.envFile ?? base.envFile,
116
+ sourcePath,
117
+ };
118
+ }
119
+ /**
120
+ * Fold services in declaration order (included first, in include order, then
121
+ * local), deep-merging any later definition of an already-seen service name
122
+ * onto the earlier one. Replaces a previous wholesale last-writer-wins merge,
123
+ * which silently dropped the base's ports when an override redefined a service
124
+ * without repeating them.
125
+ */
126
+ function foldServices(services) {
127
+ const byName = new Map();
128
+ for (const svc of services) {
129
+ const existing = byName.get(svc.name);
130
+ byName.set(svc.name, existing ? mergeService(existing, svc) : svc);
131
+ }
132
+ return [...byName.values()];
133
+ }
134
+ function parseRecursive(filePath, seen, sourceFiles) {
135
+ if (!fs.existsSync(filePath)) {
136
+ console.warn(`wtc: included compose file not found, skipping: ${filePath}`);
137
+ return [];
138
+ }
139
+ // Key on the realpath so symlinked duplicates and cycles are caught.
140
+ const key = fs.realpathSync.native(filePath);
141
+ if (seen.has(key))
142
+ return [];
143
+ seen.add(key);
144
+ const raw = fs.readFileSync(filePath, "utf-8");
145
+ const doc = parseYaml(raw, { uniqueKeys: false });
146
+ if (!doc || typeof doc !== "object")
147
+ return [];
148
+ sourceFiles.push(key);
149
+ // Recurse into includes first so local services can override included ones.
150
+ let included = [];
151
+ if ("include" in doc) {
152
+ for (const inc of normalizeIncludes(doc.include, filePath)) {
153
+ included = included.concat(parseRecursive(inc, seen, sourceFiles));
154
+ }
155
+ }
156
+ const local = parseServicesObject(doc, key);
157
+ return foldServices([...included, ...local]);
158
+ }
159
+ export function parseComposeFile(composePath) {
160
+ const abs = path.resolve(composePath);
161
+ const seen = new Set();
162
+ const sourceFiles = [];
163
+ const services = parseRecursive(abs, seen, sourceFiles);
164
+ return { services, composePath: abs, sourceFiles };
55
165
  }
@@ -6,8 +6,13 @@ export interface ComposeService {
6
6
  dockerfile?: string;
7
7
  };
8
8
  envFile?: string[];
9
+ /** Absolute path of the compose file that declared this service. */
10
+ sourcePath: string;
9
11
  }
10
12
  export interface ComposeFile {
11
13
  services: ComposeService[];
14
+ /** Resolved absolute path of the root compose file. */
12
15
  composePath: string;
16
+ /** Absolute paths of the root file plus all transitively-included files, root first. */
17
+ sourceFiles: string[];
13
18
  }
package/dist/config.d.ts CHANGED
@@ -1,5 +1,12 @@
1
1
  export interface WtcConfig {
2
2
  sync?: string[];
3
3
  envOverrides?: Record<string, string>;
4
+ /**
5
+ * Per-worktree-index port stride. Allocated port =
6
+ * 20000 + defaultPort + worktreeIndex * portStride. Defaults to 1.
7
+ * Raise it (e.g. 100) when a project exposes clustered default host
8
+ * ports so that adjacent worktrees do not collide across services.
9
+ */
10
+ portStride?: number;
4
11
  }
5
12
  export declare function loadConfig(repoRoot: string): WtcConfig;
package/dist/context.d.ts CHANGED
@@ -8,6 +8,7 @@ export interface WtcContext {
8
8
  composeFile: ComposeFile;
9
9
  portMappings: PortMapping[];
10
10
  config: WtcConfig;
11
+ portStride: number;
11
12
  worktrees: WorktreeInfo[];
12
13
  }
13
14
  export declare function buildContext(): WtcContext;
package/dist/context.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { getRepoRoot, getRepoName, detectComposeFile } from "./compose/detect.js";
2
2
  import { parseComposeFile } from "./compose/parse.js";
3
3
  import { extractPortMappings } from "./ports/extract.js";
4
+ import { detectCrossWorktreeCollisions, recommendPortStride, } from "./ports/allocate.js";
4
5
  import { loadConfig } from "./config.js";
5
6
  import { getNonMainWorktrees } from "./git/worktree.js";
7
+ import * as log from "./utils/log.js";
6
8
  export function buildContext() {
7
9
  const repoRoot = getRepoRoot();
8
10
  const repoName = getRepoName(repoRoot);
@@ -13,8 +15,46 @@ export function buildContext() {
13
15
  const composeFile = parseComposeFile(composePath);
14
16
  const portMappings = extractPortMappings(composeFile.services);
15
17
  const config = loadConfig(repoRoot);
18
+ const portStride = config.portStride ?? 1;
19
+ if (!Number.isInteger(portStride) || portStride < 1) {
20
+ throw new Error(`Invalid "portStride": ${String(portStride)}. Expected a positive integer.`);
21
+ }
16
22
  const worktrees = getNonMainWorktrees(repoRoot);
17
- return { repoRoot, repoName, composeFile, portMappings, config, worktrees };
23
+ warnOnPortCollisions(portMappings, portStride, worktrees.length);
24
+ return {
25
+ repoRoot,
26
+ repoName,
27
+ composeFile,
28
+ portMappings,
29
+ config,
30
+ portStride,
31
+ worktrees,
32
+ };
33
+ }
34
+ function warnOnPortCollisions(portMappings, portStride, worktreeCount) {
35
+ if (worktreeCount < 2)
36
+ return;
37
+ // Collision detection is advisory; an allocation failure here must never
38
+ // abort the command that triggered the warning.
39
+ let collisions;
40
+ try {
41
+ collisions = detectCrossWorktreeCollisions(portMappings, portStride, worktreeCount);
42
+ }
43
+ catch {
44
+ return;
45
+ }
46
+ if (collisions.length === 0)
47
+ return;
48
+ const examples = collisions
49
+ .slice(0, 3)
50
+ .map((c) => `${c.port} (wt${c.a.worktreeIndex}/${c.a.serviceName} ↔ wt${c.b.worktreeIndex}/${c.b.serviceName})`)
51
+ .join(", ");
52
+ const recommended = recommendPortStride(portMappings, worktreeCount);
53
+ const fix = recommended > 0
54
+ ? `Set "portStride": ${recommended} in .wtcrc.json (or package.json#wtc) to resolve.`
55
+ : `No single portStride resolves this — check for services sharing the same default port.`;
56
+ log.warn(`Cross-worktree port collisions detected with portStride=${portStride} ` +
57
+ `across ${worktreeCount} worktrees: ${collisions.length} collision(s), e.g. ${examples}. ${fix}`);
18
58
  }
19
59
  export function filterWorktrees(worktrees, indices) {
20
60
  if (indices.length === 0)
@@ -19,7 +19,7 @@ function startWorktrees(indices) {
19
19
  for (const wt of targets) {
20
20
  const idx = ctx.worktrees.indexOf(wt) + 1;
21
21
  const project = composeProjectName(ctx.repoName, idx, wt.branch);
22
- const allocations = allocateWorktreePorts(ctx.portMappings, idx);
22
+ const allocations = allocateWorktreePorts(ctx.portMappings, idx, ctx.portStride);
23
23
  syncWorktreeFiles(ctx.repoRoot, wt.path, ctx.composeFile, ctx.config.sync);
24
24
  copyBaseEnv(ctx.repoRoot, wt.path);
25
25
  injectPortOverrides(`${wt.path}/.env`, allocations, ctx.config.envOverrides);
@@ -53,10 +53,9 @@ function listWorktrees() {
53
53
  return ctx.worktrees.map((wt, i) => {
54
54
  const idx = i + 1;
55
55
  const project = composeProjectName(ctx.repoName, idx, wt.branch);
56
- const allocations = allocateWorktreePorts(ctx.portMappings, idx);
57
- const up = execSafe(`docker compose -p "${project}" ps --format json`, {
58
- cwd: wt.path,
59
- }) !== null;
56
+ const allocations = allocateWorktreePorts(ctx.portMappings, idx, ctx.portStride);
57
+ const psOutput = execSafe(`docker compose -p "${project}" ps --format json`, { cwd: wt.path });
58
+ const up = psOutput !== null && psOutput.length > 2;
60
59
  return {
61
60
  index: idx,
62
61
  branch: wt.branch,
@@ -1,3 +1,24 @@
1
1
  import type { PortMapping, PortAllocation } from "./types.js";
2
- export declare function allocatePort(defaultPort: number, worktreeIndex: number): number;
3
- export declare function allocateWorktreePorts(mappings: PortMapping[], worktreeIndex: number): PortAllocation[];
2
+ export declare function allocatePort(defaultPort: number, worktreeIndex: number, portStride?: number): number;
3
+ export declare function allocateWorktreePorts(mappings: PortMapping[], worktreeIndex: number, portStride?: number): PortAllocation[];
4
+ export interface PortCollisionParty {
5
+ worktreeIndex: number;
6
+ serviceName: string;
7
+ }
8
+ export interface PortCollision {
9
+ port: number;
10
+ a: PortCollisionParty;
11
+ b: PortCollisionParty;
12
+ }
13
+ /**
14
+ * Detect cross-worktree port collisions for a given stride across worktree
15
+ * indices 1..worktreeCount. Returns one entry per colliding allocation.
16
+ */
17
+ export declare function detectCrossWorktreeCollisions(mappings: PortMapping[], portStride: number, worktreeCount: number): PortCollision[];
18
+ /**
19
+ * Smallest portStride that is collision-free across a generous worktree
20
+ * horizon (so the suggestion survives adding more worktrees). Returns -1 if
21
+ * no stride within the search cap works — which signals duplicate default
22
+ * ports within a worktree, a case the per-worktree dedup guard already rejects.
23
+ */
24
+ export declare function recommendPortStride(mappings: PortMapping[], worktreeCount: number): number;
@@ -1,6 +1,6 @@
1
1
  const BASE_OFFSET = 20000;
2
- export function allocatePort(defaultPort, worktreeIndex) {
3
- let port = BASE_OFFSET + defaultPort + worktreeIndex;
2
+ export function allocatePort(defaultPort, worktreeIndex, portStride = 1) {
3
+ let port = BASE_OFFSET + defaultPort + worktreeIndex * portStride;
4
4
  if (port > 65535) {
5
5
  port = defaultPort + 100 * worktreeIndex;
6
6
  }
@@ -10,12 +10,12 @@ export function allocatePort(defaultPort, worktreeIndex) {
10
10
  }
11
11
  return port;
12
12
  }
13
- export function allocateWorktreePorts(mappings, worktreeIndex) {
13
+ export function allocateWorktreePorts(mappings, worktreeIndex, portStride = 1) {
14
14
  const overridable = mappings.filter((m) => m.envVar !== null);
15
15
  const allocations = overridable.map((m) => ({
16
16
  serviceName: m.serviceName,
17
17
  envVar: m.envVar,
18
- port: allocatePort(m.defaultPort, worktreeIndex),
18
+ port: allocatePort(m.defaultPort, worktreeIndex, portStride),
19
19
  containerPort: m.containerPort,
20
20
  }));
21
21
  const seen = new Set();
@@ -27,3 +27,52 @@ export function allocateWorktreePorts(mappings, worktreeIndex) {
27
27
  }
28
28
  return allocations;
29
29
  }
30
+ /**
31
+ * Detect cross-worktree port collisions for a given stride across worktree
32
+ * indices 1..worktreeCount. Returns one entry per colliding allocation.
33
+ */
34
+ export function detectCrossWorktreeCollisions(mappings, portStride, worktreeCount) {
35
+ const overridable = mappings.filter((m) => m.envVar !== null);
36
+ const seen = new Map();
37
+ const collisions = [];
38
+ for (let w = 1; w <= worktreeCount; w++) {
39
+ for (const m of overridable) {
40
+ const port = allocatePort(m.defaultPort, w, portStride);
41
+ const prev = seen.get(port);
42
+ if (prev) {
43
+ collisions.push({
44
+ port,
45
+ a: prev,
46
+ b: { worktreeIndex: w, serviceName: m.serviceName },
47
+ });
48
+ }
49
+ else {
50
+ seen.set(port, { worktreeIndex: w, serviceName: m.serviceName });
51
+ }
52
+ }
53
+ }
54
+ return collisions;
55
+ }
56
+ const STRIDE_SEARCH_CAP = 4096;
57
+ /**
58
+ * Smallest portStride that is collision-free across a generous worktree
59
+ * horizon (so the suggestion survives adding more worktrees). Returns -1 if
60
+ * no stride within the search cap works — which signals duplicate default
61
+ * ports within a worktree, a case the per-worktree dedup guard already rejects.
62
+ */
63
+ export function recommendPortStride(mappings, worktreeCount) {
64
+ const horizon = Math.max(worktreeCount, 100);
65
+ for (let s = 1; s <= STRIDE_SEARCH_CAP; s++) {
66
+ try {
67
+ if (detectCrossWorktreeCollisions(mappings, s, horizon).length === 0) {
68
+ return s;
69
+ }
70
+ }
71
+ catch {
72
+ // This stride overflows the valid range at the chosen horizon; it could
73
+ // not be used safely anyway, so skip it and try the next one.
74
+ continue;
75
+ }
76
+ }
77
+ return -1;
78
+ }
@@ -1,2 +1,3 @@
1
1
  import type { ComposeFile } from "../compose/types.js";
2
+ export declare function getDockerfiles(composeFile: ComposeFile, repoRoot: string): string[];
2
3
  export declare function syncWorktreeFiles(repoRoot: string, wtPath: string, composeFile: ComposeFile, extraSync?: string[]): void;
@@ -21,23 +21,35 @@ function copyDir(src, dst) {
21
21
  }
22
22
  }
23
23
  }
24
- function getDockerfiles(composeFile, repoRoot) {
24
+ /** True if a repo-relative path escapes the repo root (or is absolute). */
25
+ function escapesRepo(rel) {
26
+ return path.isAbsolute(rel) || rel === ".." || rel.startsWith(`..${path.sep}`);
27
+ }
28
+ export function getDockerfiles(composeFile, repoRoot) {
25
29
  const files = [];
26
30
  for (const svc of composeFile.services) {
27
31
  if (!svc.build)
28
32
  continue;
29
33
  const context = svc.build.context ?? ".";
30
34
  const dockerfile = svc.build.dockerfile ?? "Dockerfile";
31
- const resolvedDir = path.resolve(path.dirname(composeFile.composePath), context);
35
+ // Build contexts are relative to the file that declared the service, which
36
+ // may be an included file rather than the root compose file.
37
+ const resolvedDir = path.resolve(path.dirname(svc.sourcePath), context);
32
38
  const fullPath = path.join(resolvedDir, dockerfile);
33
39
  const rel = path.relative(repoRoot, fullPath);
40
+ if (escapesRepo(rel))
41
+ continue;
34
42
  files.push(rel);
35
43
  }
36
44
  return [...new Set(files)];
37
45
  }
38
46
  export function syncWorktreeFiles(repoRoot, wtPath, composeFile, extraSync) {
39
- const composeRel = path.relative(repoRoot, composeFile.composePath);
40
- copyFile(path.join(repoRoot, composeRel), path.join(wtPath, composeRel));
47
+ for (const src of composeFile.sourceFiles) {
48
+ const rel = path.relative(repoRoot, src);
49
+ if (escapesRepo(rel))
50
+ continue;
51
+ copyFile(path.join(repoRoot, rel), path.join(wtPath, rel));
52
+ }
41
53
  for (const df of getDockerfiles(composeFile, repoRoot)) {
42
54
  copyFile(path.join(repoRoot, df), path.join(wtPath, df));
43
55
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktree-compose",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Zero-config Docker Compose isolation for git worktrees",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,12 +13,6 @@
13
13
  "engines": {
14
14
  "node": ">=18"
15
15
  },
16
- "scripts": {
17
- "build": "tsc",
18
- "dev": "tsx src/cli.ts",
19
- "test": "NODE_OPTIONS='--experimental-vm-modules' jest --coverage",
20
- "prepublishOnly": "npm run build"
21
- },
22
16
  "keywords": [
23
17
  "git",
24
18
  "worktree",
@@ -31,12 +25,12 @@
31
25
  ],
32
26
  "repository": {
33
27
  "type": "git",
34
- "url": "git+https://github.com/LevwTech/worktree-compose.git"
28
+ "url": "git+https://github.com/mostafasudo/worktree-compose.git"
35
29
  },
36
30
  "bugs": {
37
- "url": "https://github.com/LevwTech/worktree-compose/issues"
31
+ "url": "https://github.com/mostafasudo/worktree-compose/issues"
38
32
  },
39
- "homepage": "https://github.com/LevwTech/worktree-compose#readme",
33
+ "homepage": "https://github.com/mostafasudo/worktree-compose#readme",
40
34
  "license": "MIT",
41
35
  "dependencies": {
42
36
  "@modelcontextprotocol/sdk": "^1.12.1",
@@ -53,5 +47,11 @@
53
47
  "ts-jest": "^29.3.4",
54
48
  "tsx": "^4.19.4",
55
49
  "typescript": "^5.8.3"
50
+ },
51
+ "scripts": {
52
+ "build": "tsc",
53
+ "dev": "tsx src/cli.ts",
54
+ "test": "NODE_OPTIONS='--experimental-vm-modules' jest --coverage",
55
+ "release": "set -a && . ./.env && set +a && pnpm publish --no-git-checks"
56
56
  }
57
- }
57
+ }