worktree-compose 0.2.0 → 1.1.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 (99) hide show
  1. package/README.md +501 -143
  2. package/SKILL.md +113 -0
  3. package/dist/cli.js +94 -33
  4. package/dist/commands/clean.d.ts +2 -1
  5. package/dist/commands/clean.js +8 -48
  6. package/dist/commands/doctor.d.ts +3 -0
  7. package/dist/commands/doctor.js +30 -0
  8. package/dist/commands/list.d.ts +4 -1
  9. package/dist/commands/list.js +62 -44
  10. package/dist/commands/promote.d.ts +3 -1
  11. package/dist/commands/promote.js +4 -34
  12. package/dist/commands/prune.d.ts +2 -0
  13. package/dist/commands/prune.js +7 -0
  14. package/dist/commands/restart.d.ts +2 -1
  15. package/dist/commands/restart.js +11 -5
  16. package/dist/commands/skill.d.ts +4 -0
  17. package/dist/commands/skill.js +10 -0
  18. package/dist/commands/start.d.ts +2 -1
  19. package/dist/commands/start.js +7 -34
  20. package/dist/commands/stop.d.ts +1 -1
  21. package/dist/commands/stop.js +6 -23
  22. package/dist/compose/detect.d.ts +1 -2
  23. package/dist/compose/detect.js +1 -10
  24. package/dist/compose/engine.d.ts +61 -0
  25. package/dist/compose/engine.js +129 -0
  26. package/dist/compose/isolation.d.ts +26 -0
  27. package/dist/compose/isolation.js +91 -0
  28. package/dist/compose/override.d.ts +152 -0
  29. package/dist/compose/override.js +542 -0
  30. package/dist/compose/parse.d.ts +12 -0
  31. package/dist/compose/parse.js +199 -29
  32. package/dist/compose/status.d.ts +84 -0
  33. package/dist/compose/status.js +227 -0
  34. package/dist/compose/types.d.ts +43 -0
  35. package/dist/config.d.ts +31 -0
  36. package/dist/config.js +23 -6
  37. package/dist/context.d.ts +104 -3
  38. package/dist/context.js +299 -45
  39. package/dist/core/clean.d.ts +91 -0
  40. package/dist/core/clean.js +347 -0
  41. package/dist/core/compose.d.ts +92 -0
  42. package/dist/core/compose.js +195 -0
  43. package/dist/core/doctor.d.ts +29 -0
  44. package/dist/core/doctor.js +342 -0
  45. package/dist/core/list.d.ts +46 -0
  46. package/dist/core/list.js +101 -0
  47. package/dist/core/promote.d.ts +40 -0
  48. package/dist/core/promote.js +117 -0
  49. package/dist/core/prune.d.ts +32 -0
  50. package/dist/core/prune.js +79 -0
  51. package/dist/core/restart.d.ts +14 -0
  52. package/dist/core/restart.js +18 -0
  53. package/dist/core/start.d.ts +33 -0
  54. package/dist/core/start.js +113 -0
  55. package/dist/core/stop.d.ts +32 -0
  56. package/dist/core/stop.js +58 -0
  57. package/dist/core/teardown.d.ts +123 -0
  58. package/dist/core/teardown.js +305 -0
  59. package/dist/core/types.d.ts +15 -0
  60. package/dist/core/types.js +1 -0
  61. package/dist/git/promote.d.ts +49 -2
  62. package/dist/git/promote.js +160 -38
  63. package/dist/git/repo.d.ts +72 -0
  64. package/dist/git/repo.js +167 -0
  65. package/dist/git/status.d.ts +8 -0
  66. package/dist/git/status.js +25 -0
  67. package/dist/git/worktree.d.ts +63 -3
  68. package/dist/git/worktree.js +173 -29
  69. package/dist/mcp/server.d.ts +2 -0
  70. package/dist/mcp/server.js +230 -115
  71. package/dist/ports/allocate.d.ts +39 -5
  72. package/dist/ports/allocate.js +96 -16
  73. package/dist/ports/extract.d.ts +12 -0
  74. package/dist/ports/extract.js +48 -4
  75. package/dist/ports/types.d.ts +12 -1
  76. package/dist/selectors.d.ts +10 -0
  77. package/dist/selectors.js +106 -0
  78. package/dist/skill.d.ts +13 -0
  79. package/dist/skill.js +28 -0
  80. package/dist/state/registry.d.ts +194 -0
  81. package/dist/state/registry.js +595 -0
  82. package/dist/sync/env.d.ts +93 -2
  83. package/dist/sync/env.js +169 -32
  84. package/dist/sync/files.d.ts +15 -1
  85. package/dist/sync/files.js +126 -38
  86. package/dist/utils/exec.d.ts +69 -4
  87. package/dist/utils/exec.js +221 -15
  88. package/dist/utils/log.d.ts +37 -0
  89. package/dist/utils/log.js +68 -4
  90. package/dist/utils/paths.d.ts +61 -0
  91. package/dist/utils/paths.js +163 -0
  92. package/dist/utils/sanitize.d.ts +7 -0
  93. package/dist/utils/sanitize.js +12 -0
  94. package/dist/version.d.ts +1 -0
  95. package/dist/version.js +3 -0
  96. package/dist/workspaces/resolve.d.ts +21 -0
  97. package/dist/workspaces/resolve.js +235 -0
  98. package/package.json +20 -16
  99. package/wtc.schema.json +62 -0
@@ -1,131 +1,246 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
3
  import { z } from "zod";
4
- import { buildContext, filterWorktrees } from "../context.js";
5
- import { allocateWorktreePorts } from "../ports/allocate.js";
6
- import { composeProjectName } from "../utils/sanitize.js";
7
- import { exec, execSafe } from "../utils/exec.js";
8
- import { syncWorktreeFiles } from "../sync/files.js";
9
- import { copyBaseEnv, injectPortOverrides } from "../sync/env.js";
10
- import { getRepoRoot } from "../compose/detect.js";
11
- import { getWorktreeByIndex, getWorktreeBranch } from "../git/worktree.js";
12
- import { getChangedFiles, getLocalDirtyFiles, findConflicts, promoteFiles, } from "../git/promote.js";
13
- function startWorktrees(indices) {
14
- const ctx = buildContext();
15
- if (ctx.worktrees.length === 0)
16
- return "No worktrees found.";
17
- const targets = filterWorktrees(ctx.worktrees, indices);
18
- const results = [];
19
- for (const wt of targets) {
20
- const idx = ctx.worktrees.indexOf(wt) + 1;
21
- const project = composeProjectName(ctx.repoName, idx, wt.branch);
22
- const allocations = allocateWorktreePorts(ctx.portMappings, idx, ctx.portStride);
23
- syncWorktreeFiles(ctx.repoRoot, wt.path, ctx.composeFile, ctx.config.sync);
24
- copyBaseEnv(ctx.repoRoot, wt.path);
25
- injectPortOverrides(`${wt.path}/.env`, allocations, ctx.config.envOverrides);
26
- exec(`docker compose -p "${project}" up -d --build`, { cwd: wt.path });
27
- const ports = allocations.map((a) => `${a.envVar}=${a.port}`).join(", ");
28
- results.push(`Worktree ${idx} (${wt.branch}): started [${ports}]`);
29
- }
30
- return results.join("\n");
4
+ import { startWorktrees } from "../core/start.js";
5
+ import { restartWorktrees } from "../core/restart.js";
6
+ import { stopWorktrees } from "../core/stop.js";
7
+ import { listWorktrees } from "../core/list.js";
8
+ import { promoteWorktree } from "../core/promote.js";
9
+ import { clean } from "../core/clean.js";
10
+ import { prune } from "../core/prune.js";
11
+ import { doctor } from "../core/doctor.js";
12
+ import { throwIfAborted } from "../core/compose.js";
13
+ import { CollectingReporter } from "../utils/log.js";
14
+ import { VERSION } from "../version.js";
15
+ function text(...parts) {
16
+ return {
17
+ content: parts
18
+ .filter((p) => p !== undefined && p !== "")
19
+ .map((p) => ({ type: "text", text: p })),
20
+ };
31
21
  }
32
- function stopWorktrees(indices) {
33
- const ctx = buildContext();
34
- if (ctx.worktrees.length === 0)
35
- return "No worktrees found.";
36
- const targets = filterWorktrees(ctx.worktrees, indices);
37
- const results = [];
38
- for (const wt of targets) {
39
- const idx = ctx.worktrees.indexOf(wt) + 1;
40
- const project = composeProjectName(ctx.repoName, idx, wt.branch);
41
- try {
42
- exec(`docker compose -p "${project}" down`, { cwd: wt.path });
43
- results.push(`Worktree ${idx} (${wt.branch}): stopped`);
44
- }
45
- catch {
46
- results.push(`Worktree ${idx} (${wt.branch}): already stopped`);
47
- }
48
- }
49
- return results.join("\n");
22
+ const PROGRESS_INTERVAL_MS = 5_000;
23
+ /**
24
+ * Progress notifications for a request that asked for them (progressToken):
25
+ * one per reported line, throttled, plus a heartbeat carrying the latest
26
+ * compose output line while a long `up --build` runs.
27
+ */
28
+ function progressSender(extra) {
29
+ const token = extra?._meta?.progressToken;
30
+ if (token === undefined || !extra)
31
+ return { note: () => { }, stop: () => { } };
32
+ let count = 0;
33
+ let last = "";
34
+ let lastSent = 0;
35
+ const send = (message) => {
36
+ lastSent = Date.now();
37
+ void extra
38
+ .sendNotification({
39
+ method: "notifications/progress",
40
+ params: { progressToken: token, progress: ++count, message },
41
+ })
42
+ .catch(() => { });
43
+ };
44
+ const timer = setInterval(() => {
45
+ if (Date.now() - lastSent >= PROGRESS_INTERVAL_MS && last)
46
+ send(last);
47
+ }, PROGRESS_INTERVAL_MS);
48
+ timer.unref?.();
49
+ return {
50
+ note: (message) => {
51
+ last = message;
52
+ if (Date.now() - lastSent >= 1_000)
53
+ send(message);
54
+ },
55
+ stop: () => clearInterval(timer),
56
+ };
50
57
  }
51
- function listWorktrees() {
52
- const ctx = buildContext();
53
- return ctx.worktrees.map((wt, i) => {
54
- const idx = i + 1;
55
- const project = composeProjectName(ctx.repoName, idx, wt.branch);
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;
59
- return {
60
- index: idx,
61
- branch: wt.branch,
62
- path: wt.path,
63
- project,
64
- status: up ? "up" : "down",
65
- ports: Object.fromEntries(allocations.map((a) => [a.envVar, a.port])),
66
- };
67
- });
58
+ /**
59
+ * Serializes the tools that change stacks or files (start, stop, restart,
60
+ * clean, prune, promote). A client that times out and retries `wtc_start`
61
+ * must not launch a second `compose up` for the same project while the
62
+ * first is still building, and a promote must not copy files while a clean
63
+ * removes the worktree: each call waits its turn. A request cancelled while
64
+ * it waits never runs.
65
+ */
66
+ let mutating = Promise.resolve();
67
+ function exclusive(io, fn) {
68
+ const run = () => {
69
+ throwIfAborted(io);
70
+ return fn();
71
+ };
72
+ const next = mutating.then(run, run);
73
+ mutating = next.catch(() => { });
74
+ return next;
68
75
  }
69
- function promoteWorktree(index) {
70
- const repoRoot = getRepoRoot();
71
- const wt = getWorktreeByIndex(repoRoot, index);
72
- if (!wt)
73
- return `Worktree index ${index} not found.`;
74
- const currentBranch = getWorktreeBranch(repoRoot);
75
- const files = getChangedFiles(repoRoot, wt.path, currentBranch, wt.branch);
76
- if (files.length === 0)
77
- return "No changes to promote.";
78
- const dirtyFiles = getLocalDirtyFiles(repoRoot);
79
- const conflicts = findConflicts(files, dirtyFiles);
80
- if (conflicts.length > 0) {
81
- return `Abort: ${conflicts.length} file(s) have uncommitted changes: ${conflicts.join(", ")}`;
76
+ /**
77
+ * Run an operation with a collecting reporter. Handlers never throw: errors
78
+ * come back as `isError: true` with the progress so far plus the message
79
+ * (which includes compose's stderr tail on compose failures). The request's
80
+ * abort signal cancels running compose commands.
81
+ */
82
+ async function runTool(extra, fn) {
83
+ const progress = progressSender(extra);
84
+ const reporter = new CollectingReporter((line) => progress.note(line));
85
+ // Compose output is captured, never streamed: stdout is the JSON-RPC channel.
86
+ const io = { live: false, signal: extra?.signal, onOutput: (line) => progress.note(line) };
87
+ try {
88
+ const outcome = (await fn(reporter, io)) ?? {};
89
+ const result = text(reporter.text(), ...(outcome.extra ?? []));
90
+ if (result.content.length === 0)
91
+ result.content.push({ type: "text", text: "Done." });
92
+ return outcome.isError ? { ...result, isError: true } : result;
93
+ }
94
+ catch (err) {
95
+ const msg = err instanceof Error ? err.message : String(err);
96
+ return { ...text(reporter.text(), `Error: ${msg}`), isError: true };
97
+ }
98
+ finally {
99
+ progress.stop();
82
100
  }
83
- promoteFiles(repoRoot, wt.path, files);
84
- return `Promoted ${files.length} file(s) from worktree ${index} (${wt.branch}) into ${currentBranch}:\n${files.join("\n")}`;
85
101
  }
86
- export async function startMcpServer() {
102
+ const worktreesSchema = z
103
+ .array(z.union([z.number().int(), z.string()]))
104
+ .optional()
105
+ .describe("Worktrees to act on: indices, branch names, or directory names (as shown by wtc_list). Omit for all.");
106
+ const envFileSchema = z
107
+ .string()
108
+ .optional()
109
+ .describe('Env filename to copy and inject, e.g. ".env.development". Omit to use the configured "envFile" (.wtcrc.json / package.json#wtc), else ".env".');
110
+ const workspacesSchema = z
111
+ .array(z.string())
112
+ .optional()
113
+ .describe("Monorepo workspaces (by package name, directory, or path) that also get env injected.");
114
+ const buildSchema = z
115
+ .boolean()
116
+ .optional()
117
+ .describe("Rebuild images (docker compose up --build). Default: true.");
118
+ export function createMcpServer() {
87
119
  const server = new McpServer({
88
120
  name: "worktree-compose",
89
- version: "0.1.0",
121
+ version: VERSION,
90
122
  });
91
- server.tool("wtc_start", "Start Docker Compose stacks for worktrees. Syncs files, injects isolated ports, runs docker compose up.", { indices: z.array(z.number()).optional().describe("Worktree indices to start. Omit for all.") }, async ({ indices }) => ({
92
- content: [{ type: "text", text: startWorktrees(indices ?? []) }],
93
- }));
94
- server.tool("wtc_stop", "Stop Docker Compose stacks for worktrees.", { indices: z.array(z.number()).optional().describe("Worktree indices to stop. Omit for all.") }, async ({ indices }) => ({
95
- content: [{ type: "text", text: stopWorktrees(indices ?? []) }],
96
- }));
97
- server.tool("wtc_restart", "Restart Docker Compose stacks for worktrees. Use after DB migrations, Dockerfile changes, or config updates.", { indices: z.array(z.number()).optional().describe("Worktree indices to restart. Omit for all.") }, async ({ indices }) => {
98
- stopWorktrees(indices ?? []);
99
- const result = startWorktrees(indices ?? []);
100
- return { content: [{ type: "text", text: result }] };
101
- });
102
- server.tool("wtc_list", "List all worktrees with branch, status, ports, and URLs.", {}, async () => ({
103
- content: [
104
- { type: "text", text: JSON.stringify(listWorktrees(), null, 2) },
105
- ],
123
+ server.registerTool("wtc_start", {
124
+ title: "Start worktree stacks",
125
+ description: "Start Docker Compose stacks for worktrees. Syncs compose/infra files from the main checkout, injects isolated ports and COMPOSE_PROJECT_NAME into env files, remaps hardcoded host ports and container_name through a generated compose override (the compose file is never edited), runs compose up -d. Sends progress notifications when the request carries a progressToken; cancelling the request stops compose.",
126
+ inputSchema: {
127
+ indices: worktreesSchema,
128
+ envFile: envFileSchema,
129
+ workspaces: workspacesSchema,
130
+ build: buildSchema,
131
+ },
132
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
133
+ }, async ({ indices, envFile, workspaces, build }, extra) => runTool(extra, (reporter, io) => exclusive(io, async () => {
134
+ await startWorktrees({ worktrees: indices, envFile, workspaces, build }, reporter, io);
135
+ })));
136
+ server.registerTool("wtc_stop", {
137
+ title: "Stop worktree stacks",
138
+ description: "Stop the containers of worktree stacks (compose stop). Containers, networks and volumes are kept; wtc_start resumes them. To remove a stack and its volumes, use wtc_clean / wtc_prune.",
139
+ inputSchema: { indices: worktreesSchema },
140
+ 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);
143
+ return { isError: result.failures > 0 };
144
+ })));
145
+ server.registerTool("wtc_restart", {
146
+ title: "Restart worktree stacks",
147
+ description: "Restart Docker Compose stacks for worktrees (compose stop, then re-sync files and env and compose up -d, which recreates changed services). Use after DB migrations, Dockerfile changes, or config updates.",
148
+ inputSchema: {
149
+ indices: worktreesSchema,
150
+ envFile: envFileSchema,
151
+ workspaces: workspacesSchema,
152
+ build: buildSchema,
153
+ },
154
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
155
+ }, async ({ indices, envFile, workspaces, build }, extra) => runTool(extra, (reporter, io) => exclusive(io, async () => {
156
+ await restartWorktrees({ worktrees: indices, envFile, workspaces, build }, reporter, io);
157
+ })));
158
+ server.registerTool("wtc_list", {
159
+ 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: {},
162
+ annotations: { readOnlyHint: true, openWorldHint: false },
163
+ }, async (_args, extra) => runTool(extra, async () => {
164
+ const result = listWorktrees({ live: false });
165
+ return {
166
+ extra: [
167
+ JSON.stringify(result.rows, null, 2),
168
+ ...result.warnings.map((w) => `⚠ ${w}`),
169
+ ...(result.isolationWarnings.length > 0
170
+ ? [`⚠ ${result.isolationWarnings.length} isolation warning(s) — run wtc_doctor`]
171
+ : []),
172
+ ],
173
+ };
106
174
  }));
107
- server.tool("wtc_promote", "Copy changed files from a worktree into the current branch as uncommitted changes.", { index: z.number().describe("Worktree index to promote.") }, async ({ index }) => ({
108
- content: [{ type: "text", text: promoteWorktree(index) }],
175
+ server.registerTool("wtc_promote", {
176
+ title: "Promote worktree changes",
177
+ 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.",
178
+ inputSchema: {
179
+ index: z
180
+ .union([z.number().int(), z.string()])
181
+ .describe("Worktree to promote: index, branch name, or directory name."),
182
+ force: z
183
+ .boolean()
184
+ .optional()
185
+ .describe("Also overwrite files the target branch changed since the worktree branched (reverting those commits). Default: false."),
186
+ },
187
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
188
+ }, async ({ index, force }, extra) => runTool(extra, (reporter, io) => exclusive(io, async () => {
189
+ await promoteWorktree({ worktree: index, force }, reporter, io);
190
+ })));
191
+ server.registerTool("wtc_clean", {
192
+ title: "Clean up all worktree stacks",
193
+ description: "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
+ inputSchema: {
195
+ force: z
196
+ .boolean()
197
+ .optional()
198
+ .describe("Also remove worktrees with uncommitted or unreachable work, and locked ones. Default: false."),
199
+ keepWorktrees: z
200
+ .boolean()
201
+ .optional()
202
+ .describe("Tear down stacks (deleting their volumes) but keep every worktree. Default: false."),
203
+ dryRun: z
204
+ .boolean()
205
+ .optional()
206
+ .describe("Only report what would happen; changes nothing (not even wtc's registry). Default: false."),
207
+ sweep: z
208
+ .boolean()
209
+ .optional()
210
+ .describe("Also remove <repo>-wt-N-* stacks whose worktree directory no longer exists (e.g. left by wtc 0.2), judged from their containers: volumes or networks with no container left are listed, never removed. Never a stack whose directory exists. Default: false."),
211
+ },
212
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
213
+ }, async ({ force, keepWorktrees, dryRun, sweep }, extra) => runTool(extra, (reporter, io) => exclusive(io, async () => {
214
+ const result = await clean({ force, keepWorktrees, dryRun, sweep }, reporter, io);
215
+ return { isError: result.failures > 0 };
216
+ })));
217
+ server.registerTool("wtc_prune", {
218
+ title: "Prune removed worktrees",
219
+ description: "Tear down (down -v) and forget the stacks of worktrees that were deleted with git worktree remove or rm -rf. Live worktrees are not touched. Returns isError when a teardown failed.",
220
+ inputSchema: {
221
+ dryRun: z
222
+ .boolean()
223
+ .optional()
224
+ .describe("Only report what would happen; changes nothing (not even wtc's registry). Default: false."),
225
+ },
226
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
227
+ }, async ({ dryRun }, extra) => runTool(extra, (reporter, io) => exclusive(io, async () => {
228
+ const result = await prune({ dryRun }, reporter, io);
229
+ return { isError: result.failures > 0 };
230
+ })));
231
+ server.registerTool("wtc_doctor", {
232
+ title: "Diagnose setup",
233
+ description: "Check git, compose file, config, compose engine and daemon, port isolation, isolation-breaking settings (container_name, shared volumes/networks), port collisions, missing worktrees, orphaned stacks, and busy ports. Returns JSON.",
234
+ inputSchema: {},
235
+ annotations: { readOnlyHint: true, openWorldHint: false },
236
+ }, async (_args, extra) => runTool(extra, async () => {
237
+ const result = await doctor({ live: false });
238
+ return { extra: [JSON.stringify(result, null, 2)] };
109
239
  }));
110
- server.tool("wtc_clean", "Stop all worktree containers, remove all worktrees, prune everything.", {}, async () => {
111
- const { cleanCommand } = await import("../commands/clean.js");
112
- try {
113
- cleanCommand();
114
- return {
115
- content: [{ type: "text", text: "Cleanup complete." }],
116
- };
117
- }
118
- catch (err) {
119
- return {
120
- content: [
121
- {
122
- type: "text",
123
- text: `Cleanup failed: ${err instanceof Error ? err.message : String(err)}`,
124
- },
125
- ],
126
- };
127
- }
128
- });
240
+ return server;
241
+ }
242
+ export async function startMcpServer() {
243
+ const server = createMcpServer();
129
244
  const transport = new StdioServerTransport();
130
245
  await server.connect(transport);
131
246
  }
@@ -1,6 +1,38 @@
1
1
  import type { PortMapping, PortAllocation } from "./types.js";
2
2
  export declare function allocatePort(defaultPort: number, worktreeIndex: number, portStride?: number): number;
3
- export declare function allocateWorktreePorts(mappings: PortMapping[], worktreeIndex: number, portStride?: number): PortAllocation[];
3
+ /**
4
+ * The mappings that get a host port of their own: each `${VAR:-port}`
5
+ * mapping (an exact repeat, e.g. the same variable for tcp and udp, only
6
+ * once), then each hardcoded mapping in `remapped` (remapped at runtime,
7
+ * see compose/override.ts) whose default port is not already covered — the
8
+ * allocated port depends only on the default port, so `53:53/tcp` and
9
+ * `53:53/udp` share one.
10
+ */
11
+ export declare function allocatableMappings(mappings: PortMapping[], remapped?: PortMapping[]): PortMapping[];
12
+ /**
13
+ * Ports for one worktree: every `${VAR:-port}` mapping, plus the hardcoded
14
+ * mappings in `remapped` (envVar null). A hardcoded port that cannot be
15
+ * moved within range (e.g. 65500) gets no allocation and stays as it is;
16
+ * a variable's port that cannot throws, as before.
17
+ */
18
+ export declare function allocateWorktreePorts(mappings: PortMapping[], worktreeIndex: number, portStride?: number, remapped?: PortMapping[]): PortAllocation[];
19
+ /**
20
+ * Environment variables for a `docker compose` invocation so `${VAR}`
21
+ * interpolation resolves to the allocated ports. Shell environment values take
22
+ * precedence over `.env` files, which makes this independent of the configured
23
+ * env filename — Compose never reads `.env.development` (or any custom name)
24
+ * for interpolation, only the project `.env`, `--env-file`, and the process
25
+ * environment.
26
+ */
27
+ export declare function allocationEnv(allocations: PortAllocation[]): Record<string, string>;
28
+ /**
29
+ * How a port is named in output (`wtc list`, `ports` in JSON and MCP): its
30
+ * variable, or `<service>:<default port>` for a hardcoded port remapped at
31
+ * runtime — no variable holds that one.
32
+ */
33
+ export declare function portLabel(a: PortAllocation): string;
34
+ /** `{ label: port }` for output. */
35
+ export declare function portsByLabel(allocations: PortAllocation[]): Record<string, number>;
4
36
  export interface PortCollisionParty {
5
37
  worktreeIndex: number;
6
38
  serviceName: string;
@@ -11,14 +43,16 @@ export interface PortCollision {
11
43
  b: PortCollisionParty;
12
44
  }
13
45
  /**
14
- * Detect cross-worktree port collisions for a given stride across worktree
15
- * indices 1..worktreeCount. Returns one entry per colliding allocation.
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.
16
50
  */
17
- export declare function detectCrossWorktreeCollisions(mappings: PortMapping[], portStride: number, worktreeCount: number): PortCollision[];
51
+ export declare function detectCrossWorktreeCollisions(mappings: PortMapping[], portStride: number, worktrees: number | number[], remapped?: PortMapping[]): PortCollision[];
18
52
  /**
19
53
  * Smallest portStride that is collision-free across a generous worktree
20
54
  * horizon (so the suggestion survives adding more worktrees). Returns -1 if
21
55
  * no stride within the search cap works — which signals duplicate default
22
56
  * ports within a worktree, a case the per-worktree dedup guard already rejects.
23
57
  */
24
- export declare function recommendPortStride(mappings: PortMapping[], worktreeCount: number): number;
58
+ export declare function recommendPortStride(mappings: PortMapping[], worktreeCount: number, remapped?: PortMapping[]): number;
@@ -10,14 +10,64 @@ export function allocatePort(defaultPort, worktreeIndex, portStride = 1) {
10
10
  }
11
11
  return port;
12
12
  }
13
- export function allocateWorktreePorts(mappings, worktreeIndex, portStride = 1) {
14
- const overridable = mappings.filter((m) => m.envVar !== null);
15
- const allocations = overridable.map((m) => ({
16
- serviceName: m.serviceName,
17
- envVar: m.envVar,
18
- port: allocatePort(m.defaultPort, worktreeIndex, portStride),
19
- containerPort: m.containerPort,
20
- }));
13
+ /**
14
+ * The mappings that get a host port of their own: each `${VAR:-port}`
15
+ * mapping (an exact repeat, e.g. the same variable for tcp and udp, only
16
+ * once), then each hardcoded mapping in `remapped` (remapped at runtime,
17
+ * see compose/override.ts) whose default port is not already covered — the
18
+ * allocated port depends only on the default port, so `53:53/tcp` and
19
+ * `53:53/udp` share one.
20
+ */
21
+ export function allocatableMappings(mappings, remapped = []) {
22
+ const out = [];
23
+ const declared = new Set();
24
+ const defaults = new Set();
25
+ for (const m of mappings) {
26
+ const key = `${m.envVar}\0${m.defaultPort}`;
27
+ if (m.envVar === null || declared.has(key))
28
+ continue;
29
+ declared.add(key);
30
+ defaults.add(m.defaultPort);
31
+ out.push(m);
32
+ }
33
+ for (const m of remapped) {
34
+ if (m.envVar !== null || m.range || defaults.has(m.defaultPort))
35
+ continue;
36
+ defaults.add(m.defaultPort);
37
+ out.push(m);
38
+ }
39
+ return out;
40
+ }
41
+ /** `allocatePort`, or null for a hardcoded mapping whose port has nowhere to move (it stays as it is). */
42
+ function allocateOrKeep(m, worktreeIndex, portStride) {
43
+ if (m.envVar !== null)
44
+ return allocatePort(m.defaultPort, worktreeIndex, portStride);
45
+ try {
46
+ return allocatePort(m.defaultPort, worktreeIndex, portStride);
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ /**
53
+ * Ports for one worktree: every `${VAR:-port}` mapping, plus the hardcoded
54
+ * mappings in `remapped` (envVar null). A hardcoded port that cannot be
55
+ * moved within range (e.g. 65500) gets no allocation and stays as it is;
56
+ * a variable's port that cannot throws, as before.
57
+ */
58
+ export function allocateWorktreePorts(mappings, worktreeIndex, portStride = 1, remapped = []) {
59
+ const allocations = allocatableMappings(mappings, remapped).flatMap((m) => {
60
+ const port = allocateOrKeep(m, worktreeIndex, portStride);
61
+ return port === null
62
+ ? []
63
+ : [{
64
+ serviceName: m.serviceName,
65
+ envVar: m.envVar,
66
+ port,
67
+ containerPort: m.containerPort,
68
+ defaultPort: m.defaultPort,
69
+ }];
70
+ });
21
71
  const seen = new Set();
22
72
  for (const a of allocations) {
23
73
  if (seen.has(a.port)) {
@@ -28,16 +78,46 @@ export function allocateWorktreePorts(mappings, worktreeIndex, portStride = 1) {
28
78
  return allocations;
29
79
  }
30
80
  /**
31
- * Detect cross-worktree port collisions for a given stride across worktree
32
- * indices 1..worktreeCount. Returns one entry per colliding allocation.
81
+ * Environment variables for a `docker compose` invocation so `${VAR}`
82
+ * interpolation resolves to the allocated ports. Shell environment values take
83
+ * precedence over `.env` files, which makes this independent of the configured
84
+ * env filename — Compose never reads `.env.development` (or any custom name)
85
+ * for interpolation, only the project `.env`, `--env-file`, and the process
86
+ * environment.
87
+ */
88
+ export function allocationEnv(allocations) {
89
+ return Object.fromEntries(allocations.flatMap((a) => (a.envVar === null ? [] : [[a.envVar, String(a.port)]])));
90
+ }
91
+ /**
92
+ * How a port is named in output (`wtc list`, `ports` in JSON and MCP): its
93
+ * variable, or `<service>:<default port>` for a hardcoded port remapped at
94
+ * runtime — no variable holds that one.
95
+ */
96
+ export function portLabel(a) {
97
+ return a.envVar ?? `${a.serviceName}:${a.defaultPort}`;
98
+ }
99
+ /** `{ label: port }` for output. */
100
+ export function portsByLabel(allocations) {
101
+ return Object.fromEntries(allocations.map((a) => [portLabel(a), a.port]));
102
+ }
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.
33
108
  */
34
- export function detectCrossWorktreeCollisions(mappings, portStride, worktreeCount) {
35
- const overridable = mappings.filter((m) => m.envVar !== null);
109
+ export function detectCrossWorktreeCollisions(mappings, portStride, worktrees, remapped = []) {
110
+ const overridable = allocatableMappings(mappings, remapped);
36
111
  const seen = new Map();
37
112
  const collisions = [];
38
- for (let w = 1; w <= worktreeCount; w++) {
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) {
39
117
  for (const m of overridable) {
40
- const port = allocatePort(m.defaultPort, w, portStride);
118
+ const port = allocateOrKeep(m, w, portStride);
119
+ if (port === null)
120
+ continue;
41
121
  const prev = seen.get(port);
42
122
  if (prev) {
43
123
  collisions.push({
@@ -60,11 +140,11 @@ const STRIDE_SEARCH_CAP = 4096;
60
140
  * no stride within the search cap works — which signals duplicate default
61
141
  * ports within a worktree, a case the per-worktree dedup guard already rejects.
62
142
  */
63
- export function recommendPortStride(mappings, worktreeCount) {
143
+ export function recommendPortStride(mappings, worktreeCount, remapped = []) {
64
144
  const horizon = Math.max(worktreeCount, 100);
65
145
  for (let s = 1; s <= STRIDE_SEARCH_CAP; s++) {
66
146
  try {
67
- if (detectCrossWorktreeCollisions(mappings, s, horizon).length === 0) {
147
+ if (detectCrossWorktreeCollisions(mappings, s, horizon, remapped).length === 0) {
68
148
  return s;
69
149
  }
70
150
  }
@@ -1,4 +1,16 @@
1
1
  import type { ComposeService } from "../compose/types.js";
2
2
  import type { PortMapping } from "./types.js";
3
+ /**
4
+ * Split a `ports:` string into its `:`-separated segments, keeping `${…}`
5
+ * interpolations whole. The protocol suffix (`/tcp`) is stripped first.
6
+ */
7
+ export declare function portSegments(raw: string): string[];
3
8
  export declare function extractPortMappings(services: ComposeService[]): PortMapping[];
4
9
  export declare function suggestEnvVar(serviceName: string): string;
10
+ /**
11
+ * A variable name to suggest for each hardcoded mapping: `<SERVICE>_PORT`,
12
+ * or `<SERVICE>_<CONTAINER>_PORT` for a service's further ports, never one
13
+ * the compose file already uses (two ports sharing a name would get the
14
+ * same value).
15
+ */
16
+ export declare function suggestEnvVars(mappings: PortMapping[]): Map<PortMapping, string>;