worktree-compose 1.0.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.
@@ -6,9 +6,12 @@ import { detectComposeFile } from "../compose/detect.js";
6
6
  import { parseComposeFile } from "../compose/parse.js";
7
7
  import { daemonCheckArgs, resolveEngine } from "../compose/engine.js";
8
8
  import { createStackProbe, stackStatus } from "../compose/status.js";
9
- import { composeIsolationWarnings, portCollisionWarnings, rawPortWarnings } from "../compose/isolation.js";
9
+ import { composeIsolationWarnings, portCollisionWarnings, rawPortWarnings, remapNotes, } from "../compose/isolation.js";
10
+ import { decideRemap } from "../compose/override.js";
10
11
  import { extractPortMappings } from "../ports/extract.js";
11
- import { allocateWorktreePorts } from "../ports/allocate.js";
12
+ import { portLabel } from "../ports/allocate.js";
13
+ import { stackAllocations, stackRemap } from "./compose.js";
14
+ import { DEFAULT_ENV_FILE, findEnvSource } from "../sync/env.js";
12
15
  import { getRepoInfo } from "../git/repo.js";
13
16
  import { ENGINE_PROBE_TIMEOUT_MS, runSafe } from "../utils/exec.js";
14
17
  /** True when binding `port` on `host` fails with EADDRINUSE. */
@@ -50,9 +53,10 @@ function versionLine(output) {
50
53
  }
51
54
  /**
52
55
  * Diagnose the setup: git, repo layout, compose file, config, compose
53
- * engine and daemon, port isolation, isolation-breaking compose settings,
54
- * worktree/registry health, and host ports already taken for stopped stacks.
55
- * Each check is independent so one failure never hides the others.
56
+ * engine and daemon, port isolation (including what is remapped at
57
+ * runtime), isolation-breaking compose settings, worktree/registry health,
58
+ * and host ports already taken for stopped stacks. Each check is
59
+ * independent so one failure never hides the others.
56
60
  */
57
61
  export async function doctor(io) {
58
62
  const checks = [];
@@ -173,7 +177,27 @@ export async function doctor(io) {
173
177
  return finish();
174
178
  // ports and isolation
175
179
  const mappings = extractPortMappings(composeFile.services);
176
- const isolatable = mappings.filter((m) => m.envVar !== null);
180
+ const remap = decideRemap({
181
+ composeFile,
182
+ mappings,
183
+ mainRoot: repo.mainRoot,
184
+ commonDir: repo.commonDir,
185
+ envFiles: [
186
+ findEnvSource(repo.mainRoot, { dir: "", label: "root", envFileName: config?.envFile ?? DEFAULT_ENV_FILE }),
187
+ path.join(repo.mainRoot, DEFAULT_ENV_FILE),
188
+ ],
189
+ envOverrides: config?.envOverrides,
190
+ engine: () => {
191
+ if (!engine || !composeWorks)
192
+ throw new Error("no working compose engine");
193
+ return engine;
194
+ },
195
+ });
196
+ const remapped = remap.targets?.ports ?? [];
197
+ const isolatable = [
198
+ ...mappings.filter((m) => m.envVar !== null).map((m) => `${m.serviceName}:${m.envVar}`),
199
+ ...remapped.map((m) => `${m.serviceName}:${m.defaultPort} (remapped at runtime)`),
200
+ ];
177
201
  if (mappings.length === 0) {
178
202
  add({ status: "ok", title: "No published ports" });
179
203
  }
@@ -181,15 +205,38 @@ export async function doctor(io) {
181
205
  add({
182
206
  status: "ok",
183
207
  title: `${isolatable.length} isolatable port(s)`,
184
- detail: isolatable.map((m) => `${m.serviceName}:${m.envVar}`).join(", ") || undefined,
208
+ detail: isolatable.join(", ") || undefined,
209
+ });
210
+ }
211
+ if (remap.targets) {
212
+ add({
213
+ status: "ok",
214
+ title: "Hardcoded settings remapped at runtime (compose file unchanged)",
215
+ detail: remapNotes(remap.targets, mappings).join(" "),
216
+ });
217
+ }
218
+ if (remap.problem) {
219
+ add({
220
+ status: "warn",
221
+ title: "Runtime remapping unavailable",
222
+ detail: remap.problem,
223
+ hint: "Or change the compose file as the warnings below suggest.",
185
224
  });
186
225
  }
187
- for (const w of rawPortWarnings(mappings)) {
226
+ for (const w of remap.warnings) {
227
+ add({ status: "warn", title: "Not remapped", detail: w });
228
+ }
229
+ for (const w of rawPortWarnings(mappings, remapped)) {
188
230
  add({ status: "warn", title: "Raw port mapping (not isolated)", detail: w });
189
231
  }
190
- const isolation = composeIsolationWarnings(composeFile);
232
+ const isolation = composeIsolationWarnings(composeFile, new Set(remap.targets?.containerNames.map((c) => c.service)));
191
233
  if (isolation.length === 0) {
192
- add({ status: "ok", title: "No container_name or shared volumes/networks" });
234
+ add({
235
+ status: "ok",
236
+ title: remap.targets?.containerNames.length
237
+ ? "No shared volumes/networks (container_name is dropped at runtime)"
238
+ : "No container_name or shared volumes/networks",
239
+ });
193
240
  }
194
241
  for (const w of isolation) {
195
242
  add({ status: "warn", title: "Isolation", detail: w });
@@ -212,13 +259,30 @@ export async function doctor(io) {
212
259
  ...ctx.orphans.map((o) => o.index),
213
260
  ...ctx.unavailable.map((u) => u.index),
214
261
  ];
215
- const collisions = portCollisionWarnings(ctx.portMappings, ctx.portStride, indices);
262
+ const collisions = portCollisionWarnings(ctx.portMappings, ctx.portStride, indices, remapped);
216
263
  if (collisions.length === 0) {
217
264
  add({ status: "ok", title: "No cross-worktree port collisions" });
218
265
  }
219
266
  for (const w of collisions) {
220
267
  add({ status: "warn", title: "Port collisions", detail: w });
221
268
  }
269
+ // As start sees each worktree: its own compose override counts, and a
270
+ // port may have nowhere to move at that worktree's index.
271
+ const withRemap = { ...ctx, remap: remap.targets };
272
+ if (remap.targets) {
273
+ for (const wt of [...ctx.worktrees].sort((a, b) => a.index - b.index)) {
274
+ let notes;
275
+ try {
276
+ const own = stackRemap(withRemap, wt.path, wt.project);
277
+ notes = [...own.warnings, ...stackAllocations(withRemap, wt.index, own.targets).warnings];
278
+ }
279
+ catch {
280
+ continue; // reported by the busy-port check below
281
+ }
282
+ for (const n of notes)
283
+ add({ status: "warn", title: `Worktree ${wt.index}: not remapped`, detail: n });
284
+ }
285
+ }
222
286
  // Missing worktrees, registry problems, skipped sync entries.
223
287
  for (const w of ctx.warnings) {
224
288
  add({ status: "warn", title: w });
@@ -250,7 +314,8 @@ export async function doctor(io) {
250
314
  probed++;
251
315
  let allocations;
252
316
  try {
253
- allocations = allocateWorktreePorts(ctx.portMappings, wt.index, ctx.portStride);
317
+ // As start allocates them: this worktree's own compose override counts.
318
+ allocations = stackAllocations(withRemap, wt.index, stackRemap(withRemap, wt.path, wt.project).targets).allocations;
254
319
  }
255
320
  catch (err) {
256
321
  add({ status: "fail", title: `Worktree ${wt.index}: cannot allocate ports`, detail: message(err) });
@@ -258,7 +323,7 @@ export async function doctor(io) {
258
323
  }
259
324
  for (const a of allocations) {
260
325
  if (await isPortBusy(a.port)) {
261
- busy.push(`worktree ${wt.index} (${wt.branch}) ${a.envVar}=${a.port}`);
326
+ busy.push(`worktree ${wt.index} (${wt.branch}) ${portLabel(a)}=${a.port}`);
262
327
  }
263
328
  }
264
329
  }
@@ -11,6 +11,10 @@ export interface ListRow {
11
11
  running: number | null;
12
12
  total: number | null;
13
13
  url: string | null;
14
+ /**
15
+ * Allocated host ports by variable — or by `<service>:<default port>` for
16
+ * hardcoded ports remapped at runtime.
17
+ */
14
18
  ports: Record<string, number>;
15
19
  /** The worktree was removed but its registry record (and maybe its stack) remains. */
16
20
  orphan: boolean;
@@ -23,7 +27,7 @@ export interface ListRow {
23
27
  }
24
28
  export interface ListResult {
25
29
  rows: ListRow[];
26
- /** Default (main checkout) ports of isolatable services. */
30
+ /** Default (main checkout) ports of isolated services, remapped hardcoded ones included. */
27
31
  mainPorts: {
28
32
  service: string;
29
33
  port: number;
package/dist/core/list.js CHANGED
@@ -1,9 +1,15 @@
1
+ import fs from "node:fs";
1
2
  import { buildContext } from "../context.js";
2
- import { allocateWorktreePorts } from "../ports/allocate.js";
3
+ import { allocatableMappings, portsByLabel } from "../ports/allocate.js";
4
+ import { stackAllocations, stackRemap } from "./compose.js";
3
5
  import { stackStatus } from "../compose/status.js";
4
- function safeAllocate(ctx, index) {
6
+ /**
7
+ * A stack's ports as `start` allocates them, run from `dir` (its worktree,
8
+ * or the main checkout when the worktree is gone): read-only.
9
+ */
10
+ function safeAllocate(ctx, index, dir, project) {
5
11
  try {
6
- return allocateWorktreePorts(ctx.portMappings, index, ctx.portStride);
12
+ return stackAllocations(ctx, index, stackRemap(ctx, dir, project).targets).allocations;
7
13
  }
8
14
  catch {
9
15
  return [];
@@ -30,7 +36,7 @@ export function listWorktrees(io) {
30
36
  const stacks = ctx.stacks;
31
37
  const rows = [];
32
38
  for (const wt of ctx.worktrees) {
33
- const allocations = safeAllocate(ctx, wt.index);
39
+ const allocations = safeAllocate(ctx, wt.index, wt.path, wt.project);
34
40
  const state = stacks.state(wt.project);
35
41
  rows.push({
36
42
  index: wt.index,
@@ -41,13 +47,13 @@ export function listWorktrees(io) {
41
47
  running: state?.running ?? null,
42
48
  total: state?.total ?? null,
43
49
  url: pickUrl(allocations),
44
- ports: Object.fromEntries(allocations.map((a) => [a.envVar, a.port])),
50
+ ports: portsByLabel(allocations),
45
51
  orphan: false,
46
52
  unavailable: null,
47
53
  });
48
54
  }
49
55
  for (const u of ctx.unavailable) {
50
- const allocations = safeAllocate(ctx, u.index);
56
+ const allocations = safeAllocate(ctx, u.index, u.path, u.project);
51
57
  const state = stacks.state(u.project);
52
58
  rows.push({
53
59
  index: u.index,
@@ -58,13 +64,13 @@ export function listWorktrees(io) {
58
64
  running: state?.running ?? null,
59
65
  total: state?.total ?? null,
60
66
  url: null,
61
- ports: Object.fromEntries(allocations.map((a) => [a.envVar, a.port])),
67
+ ports: portsByLabel(allocations),
62
68
  orphan: false,
63
69
  unavailable: u.reason,
64
70
  });
65
71
  }
66
72
  for (const o of ctx.orphans) {
67
- const allocations = safeAllocate(ctx, o.index);
73
+ const allocations = safeAllocate(ctx, o.index, fs.existsSync(o.path) ? o.path : ctx.repoRoot, o.project);
68
74
  const state = stacks.state(o.project);
69
75
  rows.push({
70
76
  index: o.index,
@@ -75,7 +81,7 @@ export function listWorktrees(io) {
75
81
  running: state?.running ?? null,
76
82
  total: state?.total ?? null,
77
83
  url: null,
78
- ports: Object.fromEntries(allocations.map((a) => [a.envVar, a.port])),
84
+ ports: portsByLabel(allocations),
79
85
  orphan: true,
80
86
  unavailable: null,
81
87
  });
@@ -85,9 +91,10 @@ export function listWorktrees(io) {
85
91
  warnings.push(stacks.problem);
86
92
  return {
87
93
  rows,
88
- mainPorts: ctx.portMappings
89
- .filter((m) => m.envVar !== null)
90
- .map((m) => ({ service: m.serviceName, port: m.defaultPort })),
94
+ mainPorts: allocatableMappings(ctx.portMappings, ctx.remap?.ports).map((m) => ({
95
+ service: m.serviceName,
96
+ port: m.defaultPort,
97
+ })),
91
98
  warnings,
92
99
  isolationWarnings: ctx.isolationWarnings,
93
100
  };
@@ -1,6 +1,7 @@
1
1
  import { buildContext } from "../context.js";
2
2
  import { runSafe } from "../utils/exec.js";
3
3
  import { forgetRecords } from "../state/registry.js";
4
+ import { overridePath, removeOverride } from "../compose/override.js";
4
5
  import { reportContextWarnings, throwIfAborted } from "./compose.js";
5
6
  import { orphanSkipReason, teardownStack } from "./teardown.js";
6
7
  /**
@@ -9,7 +10,8 @@ import { orphanSkipReason, teardownStack } from "./teardown.js";
9
10
  */
10
11
  export async function prune(options, reporter, io) {
11
12
  const dryRun = options.dryRun === true;
12
- const ctx = buildContext({}, { cwd: io.cwd, allowMissingCompose: true, readOnly: dryRun });
13
+ // resolveRemap: tear stacks down with the compose files they were started with.
14
+ const ctx = buildContext({}, { cwd: io.cwd, allowMissingCompose: true, readOnly: dryRun, resolveRemap: !dryRun });
13
15
  reportContextWarnings(ctx, reporter, { isolation: false });
14
16
  const result = { dryRun, orphans: [], skipped: [], gitPruned: [], failures: 0 };
15
17
  if (ctx.orphans.length === 0 && ctx.prunable.length === 0) {
@@ -56,6 +58,8 @@ export async function prune(options, reporter, io) {
56
58
  runSafe("git", ["-C", ctx.repoRoot, "worktree", "prune"]);
57
59
  }
58
60
  forgetRecords(ctx.repo.commonDir, forget);
61
+ for (const project of forget)
62
+ removeOverride(overridePath(ctx.repo.commonDir, project));
59
63
  }
60
64
  const failed = result.orphans.filter((o) => !o.ok).length;
61
65
  result.failures = dryRun ? 0 : failed;
@@ -26,6 +26,8 @@ export interface StartResult {
26
26
  }
27
27
  /**
28
28
  * Sync infra files, inject ports + project name into env files, and run
29
- * `compose up -d` for each selected worktree. Stops at the first failure.
29
+ * `compose up -d` for each selected worktree (with the stack's runtime
30
+ * override when hardcoded ports or container names are remapped). Stops at
31
+ * the first failure.
30
32
  */
31
33
  export declare function startWorktrees(options: StartOptions, reporter: Reporter, io: CoreIo): Promise<StartResult>;
@@ -3,14 +3,17 @@ import path from "node:path";
3
3
  import { buildContext, getEnvTargets } from "../context.js";
4
4
  import { samePath } from "../git/worktree.js";
5
5
  import { recordEnvFiles } from "../state/registry.js";
6
- import { allocateWorktreePorts } from "../ports/allocate.js";
6
+ import { allocateWorktreePorts, portLabel, portsByLabel } from "../ports/allocate.js";
7
+ import { inheritedComposeFileNames, overridePath, removeOverride } from "../compose/override.js";
7
8
  import { syncWorktreeFiles } from "../sync/files.js";
8
9
  import { findEnvSource, injectPortOverrides, prepareEnvFile } from "../sync/env.js";
9
10
  import { selectWorktrees } from "../selectors.js";
10
- import { composeEnv, composeRun, NO_WORKTREES_HINT, reportContextWarnings, throwIfAborted, withContext, } from "./compose.js";
11
+ import { composeEnv, composeRun, NO_WORKTREES_HINT, prepareStack, reportContextWarnings, throwIfAborted, withContext, } from "./compose.js";
11
12
  /**
12
13
  * Sync infra files, inject ports + project name into env files, and run
13
- * `compose up -d` for each selected worktree. Stops at the first failure.
14
+ * `compose up -d` for each selected worktree (with the stack's runtime
15
+ * override when hardcoded ports or container names are remapped). Stops at
16
+ * the first failure.
14
17
  */
15
18
  export async function startWorktrees(options, reporter, io) {
16
19
  const ctx = buildContext(options, { cwd: io.cwd, probeStacks: true, requireMainFor: "start worktree stacks" });
@@ -34,17 +37,27 @@ export async function startWorktrees(options, reporter, io) {
34
37
  if (!fs.existsSync(path.join(wt.path, ".git"))) {
35
38
  throw new Error(`Worktree ${wt.index} (${wt.branch}) is missing on disk (${wt.path}). Remount it, or run 'git worktree prune' and 'wtc prune'.`);
36
39
  }
37
- const allocations = allocateWorktreePorts(ctx.portMappings, wt.index, ctx.portStride);
40
+ // Fail on an unallocatable port before writing anything into the worktree.
41
+ allocateWorktreePorts(ctx.portMappings, wt.index, ctx.portStride, ctx.remap?.ports);
38
42
  reporter.header(`Worktree ${wt.index}: ${wt.branch}`);
39
43
  reporter.info(`Path: ${wt.path}`);
40
44
  reporter.info(`Project: ${wt.project}`);
41
- reporter.info(`Ports: ${allocations.map((a) => `${a.envVar}=${a.port}`).join(" ") || "(none)"}`);
42
45
  const syncWarnings = syncWorktreeFiles(ctx.repoRoot, wt.path, ctx.composeFile, ctx.config.sync);
43
46
  // Skipped sync entries were already reported with the context warnings.
44
47
  for (const w of syncWarnings)
45
48
  if (!ctx.warnings.includes(w))
46
49
  reporter.warn(w);
47
50
  reporter.success("Synced infrastructure files");
51
+ // After the sync: the worktree's own compose override may be a synced file.
52
+ const stack = prepareStack(ctx, { project: wt.project, index: wt.index, dir: wt.path }, { write: true });
53
+ // A stale override goes, unless an inherited COMPOSE_FILE still lists it.
54
+ const overrideFile = overridePath(ctx.repo.commonDir, wt.project);
55
+ if (stack.composeFile === null && !inheritedComposeFileNames(overrideFile))
56
+ removeOverride(overrideFile);
57
+ for (const w of stack.warnings)
58
+ reporter.warn(w);
59
+ const allocations = stack.allocations;
60
+ reporter.info(`Ports: ${allocations.map((a) => `${portLabel(a)}=${a.port}`).join(" ") || "(none)"}`);
48
61
  const injected = [];
49
62
  for (const target of envTargets) {
50
63
  const envWarnings = [];
@@ -60,6 +73,7 @@ export async function startWorktrees(options, reporter, io) {
60
73
  const injection = injectPortOverrides(envPath, allocations, target.overrides, {
61
74
  projectName: wt.project,
62
75
  writeProjectName: target.dir === "",
76
+ ...(target.dir === "" && stack.composeFile ? { composeFile: stack.composeFile } : {}),
63
77
  root: wt.path,
64
78
  source: findEnvSource(ctx.repoRoot, target) ?? undefined,
65
79
  });
@@ -77,7 +91,7 @@ export async function startWorktrees(options, reporter, io) {
77
91
  try {
78
92
  await composeRun(engine, wt.project, ["up", "-d", ...(build ? ["--build"] : []), ...(options.removeOrphans ? ["--remove-orphans"] : [])], {
79
93
  cwd: wt.path,
80
- env: composeEnv(wt.project, allocations),
94
+ env: composeEnv(wt.project, allocations, stack.composeFile, ctx.repo.commonDir),
81
95
  live: io.live,
82
96
  signal: io.signal,
83
97
  onLine: io.onOutput,
@@ -92,7 +106,7 @@ export async function startWorktrees(options, reporter, io) {
92
106
  branch: wt.branch,
93
107
  path: wt.path,
94
108
  project: wt.project,
95
- ports: Object.fromEntries(allocations.map((a) => [a.envVar, a.port])),
109
+ ports: portsByLabel(allocations),
96
110
  });
97
111
  }
98
112
  return { started };
package/dist/core/stop.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { buildContext } from "../context.js";
2
- import { allocateWorktreePorts } from "../ports/allocate.js";
3
2
  import { selectWorktrees } from "../selectors.js";
4
- import { composeEnv, composeRun, reportContextWarnings, throwIfAborted } from "./compose.js";
3
+ import { composeEnv, composeRun, prepareStack, reportContextWarnings, throwIfAborted } from "./compose.js";
5
4
  /**
6
5
  * `compose stop` for each selected worktree; one failure does not stop the
7
6
  * rest. Containers are stopped, not removed: data in volumes declared only
@@ -30,7 +29,9 @@ export async function stopWorktrees(options, reporter, io) {
30
29
  const entry = { index: wt.index, branch: wt.branch, project: wt.project };
31
30
  let env;
32
31
  try {
33
- env = composeEnv(wt.project, allocateWorktreePorts(ctx.portMappings, wt.index, ctx.portStride));
32
+ // The compose files the stack was started with (runtime override included).
33
+ const stack = prepareStack(ctx, { project: wt.project, index: wt.index, dir: wt.path }, { write: false });
34
+ env = composeEnv(wt.project, stack.allocations, stack.composeFile, ctx.repo.commonDir);
34
35
  }
35
36
  catch {
36
37
  env = undefined;
@@ -20,7 +20,9 @@ export declare function anonymousVolumes(engine: ComposeEngine, project: string)
20
20
  /**
21
21
  * `compose -p P down -v --remove-orphans`. Runs from the worktree when it
22
22
  * still exists (so declared volumes/networks are resolved from its compose
23
- * file), otherwise from the main checkout. Fallbacks, in order:
23
+ * file), otherwise from the main checkout — with the compose files the
24
+ * stack was started with (its runtime override, which is deleted when its
25
+ * record is forgotten). Fallbacks, in order:
24
26
  * - plain `down -v` from the same directory (podman-compose < 1.0.6 rejects
25
27
  * `--remove-orphans`, which would make every teardown fail);
26
28
  * - for the Compose v2 plugin only, `down -v --remove-orphans` from an
@@ -4,13 +4,13 @@ import path from "node:path";
4
4
  import { ENGINE_PROBE_TIMEOUT_MS, run, runSafe } from "../utils/exec.js";
5
5
  import { isWithin } from "../utils/paths.js";
6
6
  import { sanitize, worktreeResourcePattern } from "../utils/sanitize.js";
7
- import { allocateWorktreePorts } from "../ports/allocate.js";
8
7
  import { cliCall, isComposePlugin } from "../compose/engine.js";
8
+ import { COMPOSE_FILE_VAR } from "../sync/env.js";
9
9
  import { field, labelsOf, parseJsonListing, parsePsContainers, PROJECT_LABELS, } from "../compose/status.js";
10
10
  import { samePath } from "../git/worktree.js";
11
11
  import { listRepoWorktrees } from "../git/repo.js";
12
12
  import { recordIsLive } from "../state/registry.js";
13
- import { composeEnv, composeRun } from "./compose.js";
13
+ import { composeEnv, composeRun, prepareStack } from "./compose.js";
14
14
  /** Anonymous volumes are named by a 64-hex id; named volumes never are. */
15
15
  const ANONYMOUS_VOLUME = /^[0-9a-f]{64}$/;
16
16
  /**
@@ -53,7 +53,9 @@ export function anonymousVolumes(engine, project) {
53
53
  /**
54
54
  * `compose -p P down -v --remove-orphans`. Runs from the worktree when it
55
55
  * still exists (so declared volumes/networks are resolved from its compose
56
- * file), otherwise from the main checkout. Fallbacks, in order:
56
+ * file), otherwise from the main checkout — with the compose files the
57
+ * stack was started with (its runtime override, which is deleted when its
58
+ * record is forgotten). Fallbacks, in order:
57
59
  * - plain `down -v` from the same directory (podman-compose < 1.0.6 rejects
58
60
  * `--remove-orphans`, which would make every teardown fail);
59
61
  * - for the Compose v2 plugin only, `down -v --remove-orphans` from an
@@ -63,24 +65,29 @@ export function anonymousVolumes(engine, project) {
63
65
  * Anonymous volumes the containers mounted are removed afterwards.
64
66
  */
65
67
  export async function teardownStack(ctx, engine, target, io) {
68
+ const cwd = fs.existsSync(target.path) ? target.path : ctx.repoRoot;
66
69
  let env;
67
70
  try {
68
- env = composeEnv(target.project, allocateWorktreePorts(ctx.portMappings, target.index, ctx.portStride));
71
+ // The compose files the stack was started with (runtime override included).
72
+ const stack = prepareStack(ctx, { project: target.project, index: target.index, dir: cwd }, { write: false });
73
+ env = composeEnv(target.project, stack.allocations, stack.composeFile, ctx.repo.commonDir);
69
74
  }
70
75
  catch {
71
76
  env = undefined;
72
77
  }
73
- const cwd = fs.existsSync(target.path) ? target.path : ctx.repoRoot;
78
+ // The label-only retry must not load any compose file, wtc's or an inherited list.
79
+ const labelsOnlyEnv = { ...env, [COMPOSE_FILE_VAR]: undefined };
74
80
  const anonymous = anonymousVolumes(engine, target.project);
75
- const call = { env, live: io.live, signal: io.signal, onLine: io.onOutput };
81
+ const call = { live: io.live, signal: io.signal, onLine: io.onOutput };
76
82
  const attempts = [
77
- { args: ["down", "-v", "--remove-orphans"], dir: () => cwd },
78
- { args: ["down", "-v"], dir: () => cwd },
83
+ { args: ["down", "-v", "--remove-orphans"], dir: () => cwd, env },
84
+ { args: ["down", "-v"], dir: () => cwd, env },
79
85
  ];
80
86
  if (isComposePlugin(engine)) {
81
87
  attempts.push({
82
88
  args: ["down", "-v", "--remove-orphans"],
83
89
  dir: () => fs.mkdtempSync(path.join(os.tmpdir(), "wtc-down-")),
90
+ env: labelsOnlyEnv,
84
91
  });
85
92
  }
86
93
  let firstError = null;
@@ -89,7 +96,7 @@ export async function teardownStack(ctx, engine, target, io) {
89
96
  break;
90
97
  const dir = attempt.dir();
91
98
  try {
92
- await composeRun(engine, target.project, attempt.args, { ...call, cwd: dir });
99
+ await composeRun(engine, target.project, attempt.args, { ...call, env: attempt.env, cwd: dir });
93
100
  for (const volume of anonymous) {
94
101
  const [file, args] = cliCall(engine, "volume", "rm", volume);
95
102
  runSafe(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS });
@@ -122,7 +122,7 @@ export function createMcpServer() {
122
122
  });
123
123
  server.registerTool("wtc_start", {
124
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, runs compose up -d. Sends progress notifications when the request carries a progressToken; cancelling the request stops compose.",
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
126
  inputSchema: {
127
127
  indices: worktreesSchema,
128
128
  envFile: envFileSchema,
@@ -1,6 +1,21 @@
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[];
4
19
  /**
5
20
  * Environment variables for a `docker compose` invocation so `${VAR}`
6
21
  * interpolation resolves to the allocated ports. Shell environment values take
@@ -10,6 +25,14 @@ export declare function allocateWorktreePorts(mappings: PortMapping[], worktreeI
10
25
  * environment.
11
26
  */
12
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>;
13
36
  export interface PortCollisionParty {
14
37
  worktreeIndex: number;
15
38
  serviceName: string;
@@ -25,11 +48,11 @@ export interface PortCollision {
25
48
  * indices can have gaps (e.g. 2, 3, 7), and only the ones actually assigned
26
49
  * can collide. Returns one entry per colliding allocation.
27
50
  */
28
- export declare function detectCrossWorktreeCollisions(mappings: PortMapping[], portStride: number, worktrees: number | number[]): PortCollision[];
51
+ export declare function detectCrossWorktreeCollisions(mappings: PortMapping[], portStride: number, worktrees: number | number[], remapped?: PortMapping[]): PortCollision[];
29
52
  /**
30
53
  * Smallest portStride that is collision-free across a generous worktree
31
54
  * horizon (so the suggestion survives adding more worktrees). Returns -1 if
32
55
  * no stride within the search cap works — which signals duplicate default
33
56
  * ports within a worktree, a case the per-worktree dedup guard already rejects.
34
57
  */
35
- export declare function recommendPortStride(mappings: PortMapping[], worktreeCount: number): number;
58
+ export declare function recommendPortStride(mappings: PortMapping[], worktreeCount: number, remapped?: PortMapping[]): number;