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.
- package/LICENSE +2 -2
- package/README.md +66 -720
- package/SKILL.md +73 -76
- package/dist/cli.js +85 -10
- package/dist/commands/down.d.ts +2 -0
- package/dist/commands/down.js +7 -0
- package/dist/commands/list.d.ts +2 -0
- package/dist/commands/list.js +43 -6
- package/dist/commands/passthrough.d.ts +13 -0
- package/dist/commands/passthrough.js +27 -0
- package/dist/commands/stop.d.ts +3 -1
- package/dist/commands/stop.js +2 -2
- package/dist/compose/detect.d.ts +19 -0
- package/dist/compose/detect.js +56 -0
- package/dist/compose/isolation.d.ts +20 -7
- package/dist/compose/isolation.js +88 -36
- package/dist/compose/override.d.ts +54 -4
- package/dist/compose/override.js +179 -52
- package/dist/compose/parse.d.ts +11 -0
- package/dist/compose/parse.js +260 -13
- package/dist/compose/status.d.ts +14 -0
- package/dist/compose/status.js +58 -1
- package/dist/compose/types.d.ts +56 -0
- package/dist/config.d.ts +33 -0
- package/dist/context.d.ts +26 -0
- package/dist/context.js +140 -29
- package/dist/core/clean.d.ts +3 -1
- package/dist/core/clean.js +8 -3
- package/dist/core/compose.d.ts +87 -13
- package/dist/core/compose.js +282 -57
- package/dist/core/doctor.d.ts +2 -8
- package/dist/core/doctor.js +116 -79
- package/dist/core/down.d.ts +37 -0
- package/dist/core/down.js +54 -0
- package/dist/core/health.d.ts +90 -0
- package/dist/core/health.js +198 -0
- package/dist/core/list.d.ts +53 -6
- package/dist/core/list.js +144 -58
- package/dist/core/passthrough.d.ts +69 -0
- package/dist/core/passthrough.js +216 -0
- package/dist/core/promote.d.ts +4 -2
- package/dist/core/promote.js +5 -3
- package/dist/core/restart.d.ts +3 -3
- package/dist/core/restart.js +6 -5
- package/dist/core/seed.d.ts +50 -0
- package/dist/core/seed.js +245 -0
- package/dist/core/shared.d.ts +63 -0
- package/dist/core/shared.js +194 -0
- package/dist/core/start.d.ts +32 -5
- package/dist/core/start.js +297 -49
- package/dist/core/stop.d.ts +3 -1
- package/dist/core/stop.js +6 -3
- package/dist/core/teardown.d.ts +5 -2
- package/dist/core/teardown.js +33 -8
- package/dist/core/types.d.ts +2 -0
- package/dist/git/promote.d.ts +11 -3
- package/dist/git/promote.js +19 -5
- package/dist/mcp/server.js +154 -28
- package/dist/ports/allocate.d.ts +35 -23
- package/dist/ports/allocate.js +108 -58
- package/dist/ports/probe.d.ts +11 -0
- package/dist/ports/probe.js +40 -0
- package/dist/ports/types.d.ts +5 -0
- package/dist/selectors.d.ts +17 -0
- package/dist/selectors.js +19 -0
- package/dist/state/registry.d.ts +23 -3
- package/dist/state/registry.js +57 -17
- package/dist/sync/env.d.ts +42 -2
- package/dist/sync/env.js +79 -8
- package/dist/sync/envsync.d.ts +91 -0
- package/dist/sync/envsync.js +338 -0
- package/dist/sync/files.d.ts +87 -5
- package/dist/sync/files.js +343 -18
- package/dist/utils/paths.d.ts +2 -0
- package/dist/utils/paths.js +9 -0
- package/package.json +9 -2
- package/wtc.schema.json +155 -13
package/dist/mcp/server.js
CHANGED
|
@@ -9,6 +9,8 @@ import { promoteWorktree } from "../core/promote.js";
|
|
|
9
9
|
import { clean } from "../core/clean.js";
|
|
10
10
|
import { prune } from "../core/prune.js";
|
|
11
11
|
import { doctor } from "../core/doctor.js";
|
|
12
|
+
import { downWorktrees } from "../core/down.js";
|
|
13
|
+
import { execArgs, logsArgs, resolveStackCall, runCaptured } from "../core/passthrough.js";
|
|
12
14
|
import { throwIfAborted } from "../core/compose.js";
|
|
13
15
|
import { CollectingReporter } from "../utils/log.js";
|
|
14
16
|
import { VERSION } from "../version.js";
|
|
@@ -102,7 +104,27 @@ async function runTool(extra, fn) {
|
|
|
102
104
|
const worktreesSchema = z
|
|
103
105
|
.array(z.union([z.number().int(), z.string()]))
|
|
104
106
|
.optional()
|
|
105
|
-
.describe(
|
|
107
|
+
.describe('Worktrees to act on: indices, branch names, directory names or paths (as shown by wtc_list), or "." for the worktree the server runs in. Omit for the worktree the server runs in; when it runs in the main checkout, omitting means every worktree.');
|
|
108
|
+
const allSchema = z
|
|
109
|
+
.boolean()
|
|
110
|
+
.optional()
|
|
111
|
+
.describe("Act on every worktree, even when the server runs inside one. Default: false.");
|
|
112
|
+
const worktreeSchema = z
|
|
113
|
+
.union([z.number().int(), z.string()])
|
|
114
|
+
.optional()
|
|
115
|
+
.describe("Worktree whose stack to use: index, branch name, directory name or path. Omit for the worktree the server runs in.");
|
|
116
|
+
const servicesSchema = z
|
|
117
|
+
.array(z.string())
|
|
118
|
+
.optional()
|
|
119
|
+
.describe("Bring up only these compose services (and what they depend on) instead of the whole stack. Remembered for the worktree: later starts and restarts use the same ones until allServices is set.");
|
|
120
|
+
const INSTRUCTIONS = [
|
|
121
|
+
"worktree-compose (wtc) gives each git worktree its own Docker Compose stack: its own host ports, containers, networks and volumes.",
|
|
122
|
+
"Called from inside a worktree, the tools act on that worktree's stack unless told otherwise.",
|
|
123
|
+
"Typical loop: wtc_start (returns when the stack is ready, with its ports), wtc_list for URLs and per-service state, wtc_exec to run commands in a service container, wtc_logs when something fails, wtc_down when the stack is no longer needed.",
|
|
124
|
+
"Use wtc_exec and wtc_logs rather than `docker exec <name>` or a plain `docker compose`: container names from the project's scripts (web, db…) belong to the main checkout's stack, not this worktree's.",
|
|
125
|
+
"Ports differ per worktree: read them from wtc_start or wtc_list, never assume the compose file's defaults.",
|
|
126
|
+
"wtc_clean ends every worktree's stack and deletes all their volumes; to remove one stack use wtc_down.",
|
|
127
|
+
].join(" ");
|
|
106
128
|
const envFileSchema = z
|
|
107
129
|
.string()
|
|
108
130
|
.optional()
|
|
@@ -115,53 +137,106 @@ const buildSchema = z
|
|
|
115
137
|
.boolean()
|
|
116
138
|
.optional()
|
|
117
139
|
.describe("Rebuild images (docker compose up --build). Default: true.");
|
|
140
|
+
const startOptions = {
|
|
141
|
+
indices: worktreesSchema,
|
|
142
|
+
all: allSchema,
|
|
143
|
+
envFile: envFileSchema,
|
|
144
|
+
workspaces: workspacesSchema,
|
|
145
|
+
build: buildSchema,
|
|
146
|
+
services: servicesSchema,
|
|
147
|
+
allServices: z
|
|
148
|
+
.boolean()
|
|
149
|
+
.optional()
|
|
150
|
+
.describe("Bring up every service again, forgetting a remembered services selection. Default: false."),
|
|
151
|
+
wait: z
|
|
152
|
+
.boolean()
|
|
153
|
+
.optional()
|
|
154
|
+
.describe("Return only once every service is running and healthy (or finished with exit code 0). When one fails or the time is up, the result is an error naming the services with their last log lines. Default: true."),
|
|
155
|
+
waitTimeoutSeconds: z
|
|
156
|
+
.number()
|
|
157
|
+
.positive()
|
|
158
|
+
.optional()
|
|
159
|
+
.describe("How long wait gives a stack, in seconds. Default: 300."),
|
|
160
|
+
seed: z
|
|
161
|
+
.boolean()
|
|
162
|
+
.optional()
|
|
163
|
+
.describe('Copy the main checkout stack\'s named volumes (database, caches) into a stack that has none yet, so it starts with data. Default: the "seedVolumes" config.'),
|
|
164
|
+
};
|
|
165
|
+
function startArgs(args) {
|
|
166
|
+
return {
|
|
167
|
+
worktrees: args.indices,
|
|
168
|
+
all: args.all,
|
|
169
|
+
envFile: args.envFile,
|
|
170
|
+
workspaces: args.workspaces,
|
|
171
|
+
build: args.build,
|
|
172
|
+
services: args.services,
|
|
173
|
+
allServices: args.allServices,
|
|
174
|
+
// An agent asks for a stack to use it: by default it gets one that is ready, or the reason it is not.
|
|
175
|
+
wait: args.wait !== false,
|
|
176
|
+
waitTimeoutSeconds: args.waitTimeoutSeconds,
|
|
177
|
+
seed: args.seed,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
118
180
|
export function createMcpServer() {
|
|
119
181
|
const server = new McpServer({
|
|
120
182
|
name: "worktree-compose",
|
|
121
183
|
version: VERSION,
|
|
122
|
-
});
|
|
184
|
+
}, { instructions: INSTRUCTIONS });
|
|
123
185
|
server.registerTool("wtc_start", {
|
|
124
186
|
title: "Start worktree stacks",
|
|
125
|
-
description: "Start Docker Compose
|
|
126
|
-
inputSchema:
|
|
127
|
-
indices: worktreesSchema,
|
|
128
|
-
envFile: envFileSchema,
|
|
129
|
-
workspaces: workspacesSchema,
|
|
130
|
-
build: buildSchema,
|
|
131
|
-
},
|
|
187
|
+
description: "Start the Docker Compose stack of a worktree (the one the server runs in, unless others are named) and return when it is ready. Gives the stack its own host ports (kept across restarts), copies the untracked files it needs from the main checkout (env files, bind-mounted certificates), points localhost:<port> env values at its own ports, remaps hardcoded host ports, container_name and fixed subnets through a generated compose override (tracked files are never changed), and runs compose up -d. The last content item is JSON: the started stacks with their ports. On failure the error names the services that are not ready, with their last log lines. Sends progress notifications when the request carries a progressToken; cancelling the request stops compose.",
|
|
188
|
+
inputSchema: startOptions,
|
|
132
189
|
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
133
|
-
}, async (
|
|
134
|
-
await startWorktrees(
|
|
190
|
+
}, async (args, extra) => runTool(extra, (reporter, io) => exclusive(io, async () => {
|
|
191
|
+
const result = await startWorktrees(startArgs(args), reporter, io);
|
|
192
|
+
return { extra: [JSON.stringify(result.started, null, 2)] };
|
|
135
193
|
})));
|
|
136
194
|
server.registerTool("wtc_stop", {
|
|
137
195
|
title: "Stop worktree stacks",
|
|
138
|
-
description: "Stop the containers of worktree
|
|
139
|
-
inputSchema: { indices: worktreesSchema },
|
|
196
|
+
description: "Stop the containers of a worktree's stack (compose stop). Containers, networks and volumes are kept; wtc_start resumes them. To remove a stack and its volumes, use wtc_down.",
|
|
197
|
+
inputSchema: { indices: worktreesSchema, all: allSchema },
|
|
140
198
|
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
141
|
-
}, async ({ indices }, extra) => runTool(extra, (reporter, io) => exclusive(io, async () => {
|
|
142
|
-
const result = await stopWorktrees({ worktrees: indices }, reporter, io);
|
|
199
|
+
}, async ({ indices, all }, extra) => runTool(extra, (reporter, io) => exclusive(io, async () => {
|
|
200
|
+
const result = await stopWorktrees({ worktrees: indices, all }, reporter, io);
|
|
143
201
|
return { isError: result.failures > 0 };
|
|
144
202
|
})));
|
|
145
203
|
server.registerTool("wtc_restart", {
|
|
146
204
|
title: "Restart worktree stacks",
|
|
147
|
-
description: "Restart
|
|
205
|
+
description: "Restart a worktree's stack (compose stop, then everything wtc_start does with compose up -d, which recreates changed services and keeps their volumes) and return when it is ready. Use after changing the compose file, a Dockerfile, env values or config.",
|
|
206
|
+
inputSchema: startOptions,
|
|
207
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
208
|
+
}, async (args, extra) => runTool(extra, (reporter, io) => exclusive(io, async () => {
|
|
209
|
+
const result = await restartWorktrees(startArgs(args), reporter, io);
|
|
210
|
+
return { extra: [JSON.stringify(result.started, null, 2)] };
|
|
211
|
+
})));
|
|
212
|
+
server.registerTool("wtc_down", {
|
|
213
|
+
title: "Remove worktree stacks",
|
|
214
|
+
description: "Remove a worktree's stack: its containers, networks and volumes (compose down -v), so its data is deleted. The worktree, its index and its ports stay; wtc_start brings up a fresh stack. Acts on the worktree the server runs in unless others are named; from the main checkout the worktrees must be named or all set. Other worktrees' stacks are not touched (wtc_clean removes every stack).",
|
|
148
215
|
inputSchema: {
|
|
149
216
|
indices: worktreesSchema,
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
217
|
+
all: z.boolean().optional().describe("Remove every worktree's stack. Default: false."),
|
|
218
|
+
keepVolumes: z
|
|
219
|
+
.boolean()
|
|
220
|
+
.optional()
|
|
221
|
+
.describe("Keep the stack's named volumes (its data); only containers and networks go. Default: false."),
|
|
153
222
|
},
|
|
154
|
-
annotations: { readOnlyHint: false, destructiveHint:
|
|
155
|
-
}, async ({ indices,
|
|
156
|
-
await
|
|
223
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
|
|
224
|
+
}, async ({ indices, all, keepVolumes }, extra) => runTool(extra, (reporter, io) => exclusive(io, async () => {
|
|
225
|
+
const result = await downWorktrees({ worktrees: indices, all, keepVolumes }, reporter, io);
|
|
226
|
+
return { isError: result.failures > 0 };
|
|
157
227
|
})));
|
|
158
228
|
server.registerTool("wtc_list", {
|
|
159
229
|
title: "List worktrees",
|
|
160
|
-
description: "List worktrees with index, branch, path, compose project, status (up/partial/exited/down/?), running/total containers, URL, and ports. The first content item is the JSON array (same as `wtc list --json`); warnings follow as separate items. Rows with orphan=true are removed worktrees whose stack or record remains (clean up with wtc_prune); rows with unavailable set (\"missing\": a locked worktree whose directory is missing, e.g. an unmounted drive; \"main\": it became the main checkout) still exist and are left alone by wtc_prune and wtc_clean. Read-only: never writes wtc's registry.",
|
|
161
|
-
inputSchema: {
|
|
230
|
+
description: "List worktrees with index, branch, path, compose project, status (up/partial/exited/down/?), health (healthy/starting/unhealthy), running/total containers, URL, ports, and services: every service with its state, health, exit code and host ports with URLs. The first content item is the JSON array (same as `wtc list --json`); warnings follow as separate items. Rows with orphan=true are removed worktrees whose stack or record remains (clean up with wtc_prune); rows with unavailable set (\"missing\": a locked worktree whose directory is missing, e.g. an unmounted drive; \"main\": it became the main checkout) still exist and are left alone by wtc_prune and wtc_clean. Read-only: never writes wtc's registry.",
|
|
231
|
+
inputSchema: {
|
|
232
|
+
indices: z
|
|
233
|
+
.array(z.union([z.number().int(), z.string()]))
|
|
234
|
+
.optional()
|
|
235
|
+
.describe('Only these worktrees: indices, branch names, directory names, paths, or "." for the one the server runs in. Omit for all.'),
|
|
236
|
+
},
|
|
162
237
|
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
163
|
-
}, async (
|
|
164
|
-
const result = listWorktrees({ live: false });
|
|
238
|
+
}, async ({ indices }, extra) => runTool(extra, async () => {
|
|
239
|
+
const result = listWorktrees({ live: false }, { worktrees: indices });
|
|
165
240
|
return {
|
|
166
241
|
extra: [
|
|
167
242
|
JSON.stringify(result.rows, null, 2),
|
|
@@ -172,6 +247,57 @@ export function createMcpServer() {
|
|
|
172
247
|
],
|
|
173
248
|
};
|
|
174
249
|
}));
|
|
250
|
+
server.registerTool("wtc_exec", {
|
|
251
|
+
title: "Run a command in a service",
|
|
252
|
+
description: "Run a command in a running service container of a worktree's stack (compose exec, no TTY) and return its exit code and the end of its output. Use it for tests, migrations, consoles and one-off scripts: it always reaches this worktree's container, whereas `docker exec <name>` from the project's scripts reaches the main checkout's. A non-zero exit code comes back as an error with the output.",
|
|
253
|
+
inputSchema: {
|
|
254
|
+
service: z.string().describe("Compose service to run the command in (see wtc_list)."),
|
|
255
|
+
command: z
|
|
256
|
+
.array(z.string())
|
|
257
|
+
.min(1)
|
|
258
|
+
.describe('The command and its arguments, one per item, e.g. ["bin/rspec", "spec/models/user_spec.rb"]. No shell: use ["sh", "-c", "…"] for pipes or &&.'),
|
|
259
|
+
worktree: worktreeSchema,
|
|
260
|
+
timeoutSeconds: z.number().positive().optional().describe("Stop the command after this many seconds. Default: 600."),
|
|
261
|
+
},
|
|
262
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
|
263
|
+
}, async ({ service, command, worktree, timeoutSeconds }, extra) => runTool(extra, async (_reporter, io) => {
|
|
264
|
+
const call = resolveStackCall(worktree, io);
|
|
265
|
+
const result = await runCaptured(call, execArgs(service, command, false), {
|
|
266
|
+
signal: io.signal,
|
|
267
|
+
timeoutMs: (timeoutSeconds ?? 600) * 1000,
|
|
268
|
+
maxLines: 300,
|
|
269
|
+
});
|
|
270
|
+
return {
|
|
271
|
+
extra: [
|
|
272
|
+
`${call.worktree.project} ${service}: exit code ${result.exitCode}${result.truncated ? " (output cut to its end)" : ""}`,
|
|
273
|
+
result.output || "(no output)",
|
|
274
|
+
],
|
|
275
|
+
isError: result.exitCode !== 0,
|
|
276
|
+
};
|
|
277
|
+
}));
|
|
278
|
+
server.registerTool("wtc_logs", {
|
|
279
|
+
title: "Read a stack's logs",
|
|
280
|
+
description: "The last log lines of a worktree stack's services (compose logs). Use it to see why a service is unhealthy, exited, or answers with an error.",
|
|
281
|
+
inputSchema: {
|
|
282
|
+
services: z.array(z.string()).optional().describe("Services to read. Omit for all."),
|
|
283
|
+
worktree: worktreeSchema,
|
|
284
|
+
tail: z.number().int().min(1).max(2000).optional().describe("Lines from the end of each service's log. Default: 100."),
|
|
285
|
+
since: z.string().optional().describe('Only lines newer than this, e.g. "10m" or "2h".'),
|
|
286
|
+
},
|
|
287
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
288
|
+
}, async ({ services, worktree, tail, since }, extra) => runTool(extra, async (_reporter, io) => {
|
|
289
|
+
const call = resolveStackCall(worktree, io, { readOnly: true });
|
|
290
|
+
const lines = tail ?? 100;
|
|
291
|
+
const result = await runCaptured(call, logsArgs({ services, tail: lines, since }), {
|
|
292
|
+
signal: io.signal,
|
|
293
|
+
timeoutMs: 60_000,
|
|
294
|
+
maxLines: Math.max(lines * Math.max(services?.length ?? 4, 1), 200),
|
|
295
|
+
});
|
|
296
|
+
return {
|
|
297
|
+
extra: [result.output || "(no log lines)"],
|
|
298
|
+
isError: result.exitCode !== 0,
|
|
299
|
+
};
|
|
300
|
+
}));
|
|
175
301
|
server.registerTool("wtc_promote", {
|
|
176
302
|
title: "Promote worktree changes",
|
|
177
303
|
description: "Copy changed files (committed, staged, unstaged, untracked) from a worktree into the checkout the server runs in, as uncommitted changes; files the worktree deleted are deleted there. Aborts if any of those files has local changes there, or was also changed (committed) on that branch since the worktree branched — unless force is set.",
|
|
@@ -190,7 +316,7 @@ export function createMcpServer() {
|
|
|
190
316
|
})));
|
|
191
317
|
server.registerTool("wtc_clean", {
|
|
192
318
|
title: "Clean up all worktree stacks",
|
|
193
|
-
description: "
|
|
319
|
+
description: "Ends the session for EVERY worktree, not only the current one (to remove one stack use wtc_down): tear down every worktree stack (down -v: deletes their volumes), remove worktrees that hold no work of their own (no uncommitted changes, no commits on a detached HEAD, no unpushed submodule commits; never the current one or the main checkout), remove leftover containers/networks/volumes of stacks this checkout owns, and prune. Stacks merely named like this repo's (e.g. another clone with the same directory name) are listed, never removed. Returns isError when a teardown or removal failed. Use dryRun first to preview.",
|
|
194
320
|
inputSchema: {
|
|
195
321
|
force: z
|
|
196
322
|
.boolean()
|
|
@@ -230,7 +356,7 @@ export function createMcpServer() {
|
|
|
230
356
|
})));
|
|
231
357
|
server.registerTool("wtc_doctor", {
|
|
232
358
|
title: "Diagnose setup",
|
|
233
|
-
description: "Check git, compose file, config, compose engine and daemon, port isolation, isolation-breaking settings (
|
|
359
|
+
description: "Check git, compose file, config, compose engine and daemon, port isolation, what is remapped at runtime, isolation-breaking settings (shared volumes/networks/host paths, host ports written into a service's environment), the untracked files copied into worktrees, missing worktrees, orphaned stacks, and busy ports. Returns JSON.",
|
|
234
360
|
inputSchema: {},
|
|
235
361
|
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
236
362
|
}, async (_args, extra) => runTool(extra, async () => {
|
package/dist/ports/allocate.d.ts
CHANGED
|
@@ -16,6 +16,41 @@ export declare function allocatableMappings(mappings: PortMapping[], remapped?:
|
|
|
16
16
|
* a variable's port that cannot throws, as before.
|
|
17
17
|
*/
|
|
18
18
|
export declare function allocateWorktreePorts(mappings: PortMapping[], worktreeIndex: number, portStride?: number, remapped?: PortMapping[]): PortAllocation[];
|
|
19
|
+
/**
|
|
20
|
+
* How a mapping's port is keyed in the registry and named in output: its
|
|
21
|
+
* variable, or `<service>:<default port>` for a hardcoded host port.
|
|
22
|
+
*/
|
|
23
|
+
export declare function mappingLabel(m: Pick<PortMapping, "envVar" | "serviceName" | "defaultPort">): string;
|
|
24
|
+
/** Prefix of the variables wtc generates for hardcoded ports. */
|
|
25
|
+
export declare const GENERATED_VAR_PREFIX = "WTC_";
|
|
26
|
+
/**
|
|
27
|
+
* The name each allocatable mapping's port goes by in env values: its
|
|
28
|
+
* compose variable, or `WTC_<SERVICE>_PORT` (`WTC_<SERVICE>_<CONTAINER>_PORT`
|
|
29
|
+
* for a service's further ports) for a hardcoded one. The prefix keeps a
|
|
30
|
+
* generated name from ever shadowing a variable the project uses for
|
|
31
|
+
* something else, such as an in-container `REDIS_PORT`.
|
|
32
|
+
*/
|
|
33
|
+
export declare function portVariables(mappings: PortMapping[]): Map<PortMapping, string>;
|
|
34
|
+
export interface ResolvePortsOptions {
|
|
35
|
+
/** Ports this worktree's stack already holds, by label (the registry). */
|
|
36
|
+
recorded?: Record<string, number>;
|
|
37
|
+
/**
|
|
38
|
+
* Host ports nothing may be allocated on: the ports other worktrees hold,
|
|
39
|
+
* ports this stack keeps as written, and ports found busy on the host.
|
|
40
|
+
*/
|
|
41
|
+
taken?: ReadonlySet<number>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Ports for one worktree's stack. A port the worktree already holds stays.
|
|
45
|
+
* Every other mapping starts from `20000 + default + index × stride` and,
|
|
46
|
+
* when that port is taken (by another worktree, another mapping of this
|
|
47
|
+
* stack, or the host), moves up to the next free one — so clustered default
|
|
48
|
+
* ports, a second repository on the same formula, or a busy host port never
|
|
49
|
+
* make two stacks collide. A hardcoded port with nowhere to move gets no
|
|
50
|
+
* allocation and stays as written; a variable's port that cannot be
|
|
51
|
+
* allocated throws.
|
|
52
|
+
*/
|
|
53
|
+
export declare function resolveWorktreePorts(mappings: PortMapping[], worktreeIndex: number, portStride?: number, remapped?: PortMapping[], opts?: ResolvePortsOptions): PortAllocation[];
|
|
19
54
|
/**
|
|
20
55
|
* Environment variables for a `docker compose` invocation so `${VAR}`
|
|
21
56
|
* interpolation resolves to the allocated ports. Shell environment values take
|
|
@@ -33,26 +68,3 @@ export declare function allocationEnv(allocations: PortAllocation[]): Record<str
|
|
|
33
68
|
export declare function portLabel(a: PortAllocation): string;
|
|
34
69
|
/** `{ label: port }` for output. */
|
|
35
70
|
export declare function portsByLabel(allocations: PortAllocation[]): Record<string, number>;
|
|
36
|
-
export interface PortCollisionParty {
|
|
37
|
-
worktreeIndex: number;
|
|
38
|
-
serviceName: string;
|
|
39
|
-
}
|
|
40
|
-
export interface PortCollision {
|
|
41
|
-
port: number;
|
|
42
|
-
a: PortCollisionParty;
|
|
43
|
-
b: PortCollisionParty;
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Detect cross-worktree port collisions for a given stride. `worktrees` is
|
|
47
|
-
* either a count (indices 1..n) or the exact indices in use — persistent
|
|
48
|
-
* indices can have gaps (e.g. 2, 3, 7), and only the ones actually assigned
|
|
49
|
-
* can collide. Returns one entry per colliding allocation.
|
|
50
|
-
*/
|
|
51
|
-
export declare function detectCrossWorktreeCollisions(mappings: PortMapping[], portStride: number, worktrees: number | number[], remapped?: PortMapping[]): PortCollision[];
|
|
52
|
-
/**
|
|
53
|
-
* Smallest portStride that is collision-free across a generous worktree
|
|
54
|
-
* horizon (so the suggestion survives adding more worktrees). Returns -1 if
|
|
55
|
-
* no stride within the search cap works — which signals duplicate default
|
|
56
|
-
* ports within a worktree, a case the per-worktree dedup guard already rejects.
|
|
57
|
-
*/
|
|
58
|
-
export declare function recommendPortStride(mappings: PortMapping[], worktreeCount: number, remapped?: PortMapping[]): number;
|
package/dist/ports/allocate.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { suggestEnvVars } from "./extract.js";
|
|
1
2
|
const BASE_OFFSET = 20000;
|
|
2
3
|
export function allocatePort(defaultPort, worktreeIndex, portStride = 1) {
|
|
3
4
|
let port = BASE_OFFSET + defaultPort + worktreeIndex * portStride;
|
|
@@ -27,7 +28,10 @@ export function allocatableMappings(mappings, remapped = []) {
|
|
|
27
28
|
if (m.envVar === null || declared.has(key))
|
|
28
29
|
continue;
|
|
29
30
|
declared.add(key);
|
|
30
|
-
|
|
31
|
+
// A port for a process on the host (`raw` is empty) is not a compose publish: a
|
|
32
|
+
// hardcoded compose port with the same default still needs a port of its own.
|
|
33
|
+
if (m.raw !== "")
|
|
34
|
+
defaults.add(m.defaultPort);
|
|
31
35
|
out.push(m);
|
|
32
36
|
}
|
|
33
37
|
for (const m of remapped) {
|
|
@@ -77,6 +81,105 @@ export function allocateWorktreePorts(mappings, worktreeIndex, portStride = 1, r
|
|
|
77
81
|
}
|
|
78
82
|
return allocations;
|
|
79
83
|
}
|
|
84
|
+
/**
|
|
85
|
+
* How a mapping's port is keyed in the registry and named in output: its
|
|
86
|
+
* variable, or `<service>:<default port>` for a hardcoded host port.
|
|
87
|
+
*/
|
|
88
|
+
export function mappingLabel(m) {
|
|
89
|
+
return m.envVar ?? `${m.serviceName}:${m.defaultPort}`;
|
|
90
|
+
}
|
|
91
|
+
/** Prefix of the variables wtc generates for hardcoded ports. */
|
|
92
|
+
export const GENERATED_VAR_PREFIX = "WTC_";
|
|
93
|
+
/**
|
|
94
|
+
* The name each allocatable mapping's port goes by in env values: its
|
|
95
|
+
* compose variable, or `WTC_<SERVICE>_PORT` (`WTC_<SERVICE>_<CONTAINER>_PORT`
|
|
96
|
+
* for a service's further ports) for a hardcoded one. The prefix keeps a
|
|
97
|
+
* generated name from ever shadowing a variable the project uses for
|
|
98
|
+
* something else, such as an in-container `REDIS_PORT`.
|
|
99
|
+
*/
|
|
100
|
+
export function portVariables(mappings) {
|
|
101
|
+
const out = new Map();
|
|
102
|
+
const suggested = suggestEnvVars(mappings);
|
|
103
|
+
// A project may itself declare a variable called WTC_WEB_PORT: a generated name steps aside.
|
|
104
|
+
const taken = new Set(mappings.flatMap((m) => (m.envVar ? [m.envVar] : [])));
|
|
105
|
+
for (const m of mappings) {
|
|
106
|
+
if (m.envVar) {
|
|
107
|
+
out.set(m, m.envVar);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const base = `${GENERATED_VAR_PREFIX}${suggested.get(m)}`;
|
|
111
|
+
let name = base;
|
|
112
|
+
for (let n = 2; taken.has(name); n++)
|
|
113
|
+
name = `${base}_${n}`;
|
|
114
|
+
taken.add(name);
|
|
115
|
+
out.set(m, name);
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Ports for one worktree's stack. A port the worktree already holds stays.
|
|
121
|
+
* Every other mapping starts from `20000 + default + index × stride` and,
|
|
122
|
+
* when that port is taken (by another worktree, another mapping of this
|
|
123
|
+
* stack, or the host), moves up to the next free one — so clustered default
|
|
124
|
+
* ports, a second repository on the same formula, or a busy host port never
|
|
125
|
+
* make two stacks collide. A hardcoded port with nowhere to move gets no
|
|
126
|
+
* allocation and stays as written; a variable's port that cannot be
|
|
127
|
+
* allocated throws.
|
|
128
|
+
*/
|
|
129
|
+
export function resolveWorktreePorts(mappings, worktreeIndex, portStride = 1, remapped = [], opts = {}) {
|
|
130
|
+
const list = allocatableMappings(mappings, remapped);
|
|
131
|
+
const variables = portVariables(mappings);
|
|
132
|
+
const used = new Set(opts.taken ?? []);
|
|
133
|
+
const chosen = new Map();
|
|
134
|
+
for (const m of list) {
|
|
135
|
+
const port = opts.recorded?.[mappingLabel(m)];
|
|
136
|
+
if (port === undefined || used.has(port))
|
|
137
|
+
continue;
|
|
138
|
+
chosen.set(m, port);
|
|
139
|
+
used.add(port);
|
|
140
|
+
}
|
|
141
|
+
// Formula ports first, so one busy port does not push its neighbours off theirs.
|
|
142
|
+
const pending = [];
|
|
143
|
+
for (const m of list) {
|
|
144
|
+
if (chosen.has(m))
|
|
145
|
+
continue;
|
|
146
|
+
const port = allocateOrKeep(m, worktreeIndex, portStride);
|
|
147
|
+
if (port === null)
|
|
148
|
+
continue;
|
|
149
|
+
if (used.has(port)) {
|
|
150
|
+
pending.push({ mapping: m, from: port });
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
chosen.set(m, port);
|
|
154
|
+
used.add(port);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
for (const { mapping, from } of pending) {
|
|
158
|
+
let port = from + 1;
|
|
159
|
+
while (port <= 65535 && used.has(port))
|
|
160
|
+
port++;
|
|
161
|
+
if (port > 65535) {
|
|
162
|
+
if (mapping.envVar === null)
|
|
163
|
+
continue;
|
|
164
|
+
throw new Error(`Cannot allocate a free port for ${mapping.envVar} (default ${mapping.defaultPort}) at worktree index ${worktreeIndex}: every port from ${from} to 65535 is taken.`);
|
|
165
|
+
}
|
|
166
|
+
chosen.set(mapping, port);
|
|
167
|
+
used.add(port);
|
|
168
|
+
}
|
|
169
|
+
return list.flatMap((m) => {
|
|
170
|
+
const port = chosen.get(m);
|
|
171
|
+
return port === undefined
|
|
172
|
+
? []
|
|
173
|
+
: [{
|
|
174
|
+
serviceName: m.serviceName,
|
|
175
|
+
envVar: m.envVar,
|
|
176
|
+
port,
|
|
177
|
+
containerPort: m.containerPort,
|
|
178
|
+
defaultPort: m.defaultPort,
|
|
179
|
+
variable: variables.get(m),
|
|
180
|
+
}];
|
|
181
|
+
});
|
|
182
|
+
}
|
|
80
183
|
/**
|
|
81
184
|
* Environment variables for a `docker compose` invocation so `${VAR}`
|
|
82
185
|
* interpolation resolves to the allocated ports. Shell environment values take
|
|
@@ -86,7 +189,10 @@ export function allocateWorktreePorts(mappings, worktreeIndex, portStride = 1, r
|
|
|
86
189
|
* environment.
|
|
87
190
|
*/
|
|
88
191
|
export function allocationEnv(allocations) {
|
|
89
|
-
return Object.fromEntries(allocations.flatMap((a) =>
|
|
192
|
+
return Object.fromEntries(allocations.flatMap((a) => {
|
|
193
|
+
const name = a.envVar ?? a.variable;
|
|
194
|
+
return name ? [[name, String(a.port)]] : [];
|
|
195
|
+
}));
|
|
90
196
|
}
|
|
91
197
|
/**
|
|
92
198
|
* How a port is named in output (`wtc list`, `ports` in JSON and MCP): its
|
|
@@ -100,59 +206,3 @@ export function portLabel(a) {
|
|
|
100
206
|
export function portsByLabel(allocations) {
|
|
101
207
|
return Object.fromEntries(allocations.map((a) => [portLabel(a), a.port]));
|
|
102
208
|
}
|
|
103
|
-
/**
|
|
104
|
-
* Detect cross-worktree port collisions for a given stride. `worktrees` is
|
|
105
|
-
* either a count (indices 1..n) or the exact indices in use — persistent
|
|
106
|
-
* indices can have gaps (e.g. 2, 3, 7), and only the ones actually assigned
|
|
107
|
-
* can collide. Returns one entry per colliding allocation.
|
|
108
|
-
*/
|
|
109
|
-
export function detectCrossWorktreeCollisions(mappings, portStride, worktrees, remapped = []) {
|
|
110
|
-
const overridable = allocatableMappings(mappings, remapped);
|
|
111
|
-
const seen = new Map();
|
|
112
|
-
const collisions = [];
|
|
113
|
-
const indices = Array.isArray(worktrees)
|
|
114
|
-
? [...new Set(worktrees)].sort((a, b) => a - b)
|
|
115
|
-
: Array.from({ length: worktrees }, (_, i) => i + 1);
|
|
116
|
-
for (const w of indices) {
|
|
117
|
-
for (const m of overridable) {
|
|
118
|
-
const port = allocateOrKeep(m, w, portStride);
|
|
119
|
-
if (port === null)
|
|
120
|
-
continue;
|
|
121
|
-
const prev = seen.get(port);
|
|
122
|
-
if (prev) {
|
|
123
|
-
collisions.push({
|
|
124
|
-
port,
|
|
125
|
-
a: prev,
|
|
126
|
-
b: { worktreeIndex: w, serviceName: m.serviceName },
|
|
127
|
-
});
|
|
128
|
-
}
|
|
129
|
-
else {
|
|
130
|
-
seen.set(port, { worktreeIndex: w, serviceName: m.serviceName });
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
return collisions;
|
|
135
|
-
}
|
|
136
|
-
const STRIDE_SEARCH_CAP = 4096;
|
|
137
|
-
/**
|
|
138
|
-
* Smallest portStride that is collision-free across a generous worktree
|
|
139
|
-
* horizon (so the suggestion survives adding more worktrees). Returns -1 if
|
|
140
|
-
* no stride within the search cap works — which signals duplicate default
|
|
141
|
-
* ports within a worktree, a case the per-worktree dedup guard already rejects.
|
|
142
|
-
*/
|
|
143
|
-
export function recommendPortStride(mappings, worktreeCount, remapped = []) {
|
|
144
|
-
const horizon = Math.max(worktreeCount, 100);
|
|
145
|
-
for (let s = 1; s <= STRIDE_SEARCH_CAP; s++) {
|
|
146
|
-
try {
|
|
147
|
-
if (detectCrossWorktreeCollisions(mappings, s, horizon, remapped).length === 0) {
|
|
148
|
-
return s;
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
catch {
|
|
152
|
-
// This stride overflows the valid range at the chosen horizon; it could
|
|
153
|
-
// not be used safely anyway, so skip it and try the next one.
|
|
154
|
-
continue;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
return -1;
|
|
158
|
-
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* True when something already listens on `port`. Docker publishes on all
|
|
3
|
+
* interfaces, but local dev servers and Homebrew databases usually bind
|
|
4
|
+
* 127.0.0.1 or ::1 only — and on macOS (BSD sockets, libuv's SO_REUSEADDR)
|
|
5
|
+
* a wildcard bind succeeds next to them, so each address is probed. Only
|
|
6
|
+
* EADDRINUSE counts as busy (no IPv6 → not busy).
|
|
7
|
+
*/
|
|
8
|
+
export declare function isPortBusy(port: number): Promise<boolean>;
|
|
9
|
+
/** Answers "is this host port taken?", remembering each answer for the run. */
|
|
10
|
+
export type PortProbe = (port: number) => Promise<boolean>;
|
|
11
|
+
export declare function cachedPortProbe(probe?: PortProbe): PortProbe;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import net from "node:net";
|
|
2
|
+
/** True when binding `port` on `host` fails with EADDRINUSE. */
|
|
3
|
+
function bindFails(port, host) {
|
|
4
|
+
return new Promise((resolve) => {
|
|
5
|
+
const server = net.createServer();
|
|
6
|
+
server.unref();
|
|
7
|
+
server.once("error", (err) => {
|
|
8
|
+
resolve(err.code === "EADDRINUSE");
|
|
9
|
+
});
|
|
10
|
+
server.once("listening", () => {
|
|
11
|
+
server.close(() => resolve(false));
|
|
12
|
+
});
|
|
13
|
+
server.listen({ port, host, exclusive: true });
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* True when something already listens on `port`. Docker publishes on all
|
|
18
|
+
* interfaces, but local dev servers and Homebrew databases usually bind
|
|
19
|
+
* 127.0.0.1 or ::1 only — and on macOS (BSD sockets, libuv's SO_REUSEADDR)
|
|
20
|
+
* a wildcard bind succeeds next to them, so each address is probed. Only
|
|
21
|
+
* EADDRINUSE counts as busy (no IPv6 → not busy).
|
|
22
|
+
*/
|
|
23
|
+
export async function isPortBusy(port) {
|
|
24
|
+
for (const host of ["0.0.0.0", "127.0.0.1", "::1"]) {
|
|
25
|
+
if (await bindFails(port, host))
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
export function cachedPortProbe(probe = isPortBusy) {
|
|
31
|
+
const answers = new Map();
|
|
32
|
+
return (port) => {
|
|
33
|
+
let answer = answers.get(port);
|
|
34
|
+
if (!answer) {
|
|
35
|
+
answer = probe(port);
|
|
36
|
+
answers.set(port, answer);
|
|
37
|
+
}
|
|
38
|
+
return answer;
|
|
39
|
+
};
|
|
40
|
+
}
|
package/dist/ports/types.d.ts
CHANGED
|
@@ -21,4 +21,9 @@ export interface PortAllocation {
|
|
|
21
21
|
containerPort: number;
|
|
22
22
|
/** The host port the compose file publishes in the main checkout. */
|
|
23
23
|
defaultPort: number;
|
|
24
|
+
/**
|
|
25
|
+
* A name for this port in env values (`envOverrides`, the env file): the
|
|
26
|
+
* compose variable, or `WTC_<SERVICE>_PORT` for a hardcoded port.
|
|
27
|
+
*/
|
|
28
|
+
variable?: string;
|
|
24
29
|
}
|
package/dist/selectors.d.ts
CHANGED
|
@@ -8,3 +8,20 @@ export type WorktreeSelector = number | string;
|
|
|
8
8
|
* worktree containing `cwd`). An empty selection means every live worktree.
|
|
9
9
|
*/
|
|
10
10
|
export declare function selectWorktrees(worktrees: ResolvedWorktree[], selectors: WorktreeSelector[] | undefined, cwd?: string): ResolvedWorktree[];
|
|
11
|
+
export interface Scope {
|
|
12
|
+
targets: ResolvedWorktree[];
|
|
13
|
+
/**
|
|
14
|
+
* No worktree was named and the command runs inside one: it acts on that
|
|
15
|
+
* worktree alone. The caller says so, and how to reach all of them.
|
|
16
|
+
*/
|
|
17
|
+
implicit: ResolvedWorktree | null;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The worktrees a command acts on. Named ones, when any are given; with
|
|
21
|
+
* `all`, every worktree; otherwise the worktree that contains `cwd` — an
|
|
22
|
+
* agent working in its own worktree means its own stack, not everyone's —
|
|
23
|
+
* and, from the main checkout (or anywhere else), every worktree.
|
|
24
|
+
*/
|
|
25
|
+
export declare function selectScope(worktrees: ResolvedWorktree[], selectors: WorktreeSelector[] | undefined, cwd?: string, all?: boolean): Scope;
|
|
26
|
+
/** The line a command prints when it acts on the current worktree because none was named. */
|
|
27
|
+
export declare function implicitScopeNote(wt: ResolvedWorktree): string;
|
package/dist/selectors.js
CHANGED
|
@@ -104,3 +104,22 @@ export function selectWorktrees(worktrees, selectors, cwd = process.cwd()) {
|
|
|
104
104
|
}
|
|
105
105
|
return out;
|
|
106
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* The worktrees a command acts on. Named ones, when any are given; with
|
|
109
|
+
* `all`, every worktree; otherwise the worktree that contains `cwd` — an
|
|
110
|
+
* agent working in its own worktree means its own stack, not everyone's —
|
|
111
|
+
* and, from the main checkout (or anywhere else), every worktree.
|
|
112
|
+
*/
|
|
113
|
+
export function selectScope(worktrees, selectors, cwd = process.cwd(), all = false) {
|
|
114
|
+
if (selectors && selectors.length > 0) {
|
|
115
|
+
return { targets: selectWorktrees(worktrees, selectors, cwd), implicit: null };
|
|
116
|
+
}
|
|
117
|
+
if (all)
|
|
118
|
+
return { targets: worktrees, implicit: null };
|
|
119
|
+
const current = containing(worktrees, cwd);
|
|
120
|
+
return current ? { targets: [current], implicit: current } : { targets: worktrees, implicit: null };
|
|
121
|
+
}
|
|
122
|
+
/** The line a command prints when it acts on the current worktree because none was named. */
|
|
123
|
+
export function implicitScopeNote(wt) {
|
|
124
|
+
return `No worktree named: acting on the current one (${wt.index}: ${wt.branch}). Pass --all for every worktree.`;
|
|
125
|
+
}
|