worktree-compose 1.1.2 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +31 -16
  3. package/SKILL.md +73 -76
  4. package/dist/cli.js +85 -10
  5. package/dist/commands/down.d.ts +2 -0
  6. package/dist/commands/down.js +7 -0
  7. package/dist/commands/list.d.ts +2 -0
  8. package/dist/commands/list.js +43 -6
  9. package/dist/commands/passthrough.d.ts +13 -0
  10. package/dist/commands/passthrough.js +27 -0
  11. package/dist/commands/stop.d.ts +3 -1
  12. package/dist/commands/stop.js +2 -2
  13. package/dist/compose/detect.d.ts +19 -0
  14. package/dist/compose/detect.js +56 -0
  15. package/dist/compose/isolation.d.ts +20 -7
  16. package/dist/compose/isolation.js +88 -36
  17. package/dist/compose/override.d.ts +54 -4
  18. package/dist/compose/override.js +179 -52
  19. package/dist/compose/parse.d.ts +11 -0
  20. package/dist/compose/parse.js +260 -13
  21. package/dist/compose/status.d.ts +14 -0
  22. package/dist/compose/status.js +58 -1
  23. package/dist/compose/types.d.ts +56 -0
  24. package/dist/config.d.ts +33 -0
  25. package/dist/context.d.ts +26 -0
  26. package/dist/context.js +140 -29
  27. package/dist/core/clean.d.ts +3 -1
  28. package/dist/core/clean.js +8 -3
  29. package/dist/core/compose.d.ts +87 -13
  30. package/dist/core/compose.js +282 -57
  31. package/dist/core/doctor.d.ts +2 -8
  32. package/dist/core/doctor.js +116 -79
  33. package/dist/core/down.d.ts +37 -0
  34. package/dist/core/down.js +54 -0
  35. package/dist/core/health.d.ts +90 -0
  36. package/dist/core/health.js +198 -0
  37. package/dist/core/list.d.ts +53 -6
  38. package/dist/core/list.js +144 -58
  39. package/dist/core/passthrough.d.ts +69 -0
  40. package/dist/core/passthrough.js +216 -0
  41. package/dist/core/promote.d.ts +4 -2
  42. package/dist/core/promote.js +5 -3
  43. package/dist/core/restart.d.ts +3 -3
  44. package/dist/core/restart.js +6 -5
  45. package/dist/core/seed.d.ts +50 -0
  46. package/dist/core/seed.js +245 -0
  47. package/dist/core/shared.d.ts +63 -0
  48. package/dist/core/shared.js +194 -0
  49. package/dist/core/start.d.ts +32 -5
  50. package/dist/core/start.js +297 -49
  51. package/dist/core/stop.d.ts +3 -1
  52. package/dist/core/stop.js +6 -3
  53. package/dist/core/teardown.d.ts +5 -2
  54. package/dist/core/teardown.js +33 -8
  55. package/dist/core/types.d.ts +2 -0
  56. package/dist/git/promote.d.ts +11 -3
  57. package/dist/git/promote.js +19 -5
  58. package/dist/mcp/server.js +154 -28
  59. package/dist/ports/allocate.d.ts +35 -23
  60. package/dist/ports/allocate.js +108 -58
  61. package/dist/ports/probe.d.ts +11 -0
  62. package/dist/ports/probe.js +40 -0
  63. package/dist/ports/types.d.ts +5 -0
  64. package/dist/selectors.d.ts +17 -0
  65. package/dist/selectors.js +19 -0
  66. package/dist/state/registry.d.ts +23 -3
  67. package/dist/state/registry.js +57 -17
  68. package/dist/sync/env.d.ts +42 -2
  69. package/dist/sync/env.js +79 -8
  70. package/dist/sync/envsync.d.ts +91 -0
  71. package/dist/sync/envsync.js +338 -0
  72. package/dist/sync/files.d.ts +87 -5
  73. package/dist/sync/files.js +343 -18
  74. package/dist/utils/paths.d.ts +2 -0
  75. package/dist/utils/paths.js +9 -0
  76. package/package.json +1 -1
  77. package/wtc.schema.json +155 -13
@@ -2,8 +2,12 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { CommandError, runAsync } from "../utils/exec.js";
4
4
  import { composeArgs, composeBin } from "../compose/engine.js";
5
- import { composeFileValue, composePathSeparator, envFileComposeFile, envFileValue, findUserOverride, isUserComposeFile, isWtcComposeFile, overridePath, remapIsEmpty, renderOverride, withoutUserOverride, writeOverride, } from "../compose/override.js";
6
- import { allocateWorktreePorts, allocationEnv } from "../ports/allocate.js";
5
+ import { composeFileValue, composePathSeparator, envFileComposeFile, envFileValue, findUserOverride, isUserComposeFile, isWtcComposeFile, extrasAreEmpty, overridePath, remapCandidates, remapIsEmpty, renderOverride, withoutUserOverride, writeOverride, } from "../compose/override.js";
6
+ import { allocationEnv, portsByLabel, resolveWorktreePorts } from "../ports/allocate.js";
7
+ import { peekState, stateFile, withStateLock, writeState } from "../state/registry.js";
8
+ import { extractPortMappings } from "../ports/extract.js";
9
+ import { parseComposeFiles } from "../compose/parse.js";
10
+ import { samePath } from "../git/worktree.js";
7
11
  import { COMPOSE_FILE_VAR, PROJECT_NAME_VAR } from "../sync/env.js";
8
12
  /**
9
13
  * Process environment for a compose call on a worktree stack: the project
@@ -15,27 +19,105 @@ import { COMPOSE_FILE_VAR, PROJECT_NAME_VAR } from "../sync/env.js";
15
19
  * worktree's `.env` exported by direnv or similar) is removed: it names
16
20
  * another stack's files, or an override that is gone.
17
21
  */
18
- export function composeEnv(project, allocations, composeFile = null, commonDir) {
22
+ export function composeEnv(project, allocations, composeFile = null, commonDir, roots = []) {
19
23
  const inherited = process.env[COMPOSE_FILE_VAR];
20
24
  const files = composeFile
21
25
  ? { [COMPOSE_FILE_VAR]: composeFile, COMPOSE_PATH_SEPARATOR: composePathSeparator() }
22
- : commonDir && inherited && isWtcComposeFile(inherited, commonDir)
26
+ : commonDir && inherited && isWtcComposeFile(inherited, commonDir, roots)
23
27
  ? { [COMPOSE_FILE_VAR]: undefined }
24
28
  : {};
25
29
  return { [PROJECT_NAME_VAR]: project, ...allocationEnv(allocations), ...files };
26
30
  }
31
+ const viewCache = new WeakMap();
32
+ /** Paths of the stack's compose files in `dir`, mirroring the main checkout's (root file first). */
33
+ export function composeFilesIn(ctx, dir) {
34
+ return ctx.composeRoots.map((file) => path.join(dir, path.relative(ctx.repoRoot, file)));
35
+ }
36
+ /** The directory of the stack's first compose file in `dir`: where compose looks for its own override file. */
37
+ export function composeDirIn(ctx, dir) {
38
+ return path.dirname(composeFilesIn(ctx, dir)[0]);
39
+ }
40
+ /** Directories the main checkout's own stack may run from: its root, and its compose file's directory. */
41
+ export function mainStackDirs(ctx) {
42
+ return [...new Set([ctx.repoRoot, path.dirname(ctx.composeFile.composePath)])];
43
+ }
44
+ /** Compose projects of this repository's worktree stacks (never the main checkout's). */
45
+ export function worktreeProjects(ctx) {
46
+ return new Set([...ctx.worktrees, ...ctx.orphans, ...ctx.unavailable].map((w) => w.project));
47
+ }
48
+ /** True when a compose source file of the main checkout exists in `dir` with other content. */
49
+ function composeDiffers(ctx, dir) {
50
+ for (const file of ctx.composeFile.sourceFiles) {
51
+ const rel = path.relative(ctx.repoRoot, file);
52
+ if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel))
53
+ continue;
54
+ let own;
55
+ try {
56
+ own = fs.readFileSync(path.join(dir, rel));
57
+ }
58
+ catch {
59
+ continue; // missing in the worktree: start copies the main checkout's
60
+ }
61
+ if (!own.equals(fs.readFileSync(file)))
62
+ return true;
63
+ }
64
+ return false;
65
+ }
66
+ export function stackView(ctx, dir) {
67
+ const base = {
68
+ composeFile: ctx.composeFile,
69
+ portMappings: ctx.portMappings,
70
+ remap: ctx.remap,
71
+ own: false,
72
+ warnings: [],
73
+ };
74
+ if (!ctx.hasComposeFile || samePath(dir, ctx.repoRoot))
75
+ return base;
76
+ let cache = viewCache.get(ctx);
77
+ if (!cache)
78
+ viewCache.set(ctx, (cache = new Map()));
79
+ const key = path.resolve(dir);
80
+ const cached = cache.get(key);
81
+ if (cached)
82
+ return cached;
83
+ let view = base;
84
+ const files = composeFilesIn(ctx, dir);
85
+ if (fs.existsSync(files[0]) && composeDiffers(ctx, dir)) {
86
+ const composeFile = parseComposeFiles(files);
87
+ const portMappings = [
88
+ ...extractPortMappings(composeFile.services).filter((m) => !ctx.sharedServices.has(m.serviceName)),
89
+ ...ctx.hostPortMappings,
90
+ ];
91
+ let remap = null;
92
+ const warnings = [];
93
+ if (ctx.canRemap()) {
94
+ // The worktree's own compose override is taken into account by `stackRemap`.
95
+ const candidates = remapCandidates(composeFile, portMappings);
96
+ remap = remapIsEmpty(candidates.targets) ? null : candidates.targets;
97
+ warnings.push(...candidates.skipped);
98
+ }
99
+ view = { composeFile, portMappings, remap, own: true, warnings };
100
+ }
101
+ cache.set(key, view);
102
+ return view;
103
+ }
104
+ /** Forget what was read from `dir`'s compose file (after a sync rewrote it). */
105
+ export function resetStackView(ctx, dir) {
106
+ viewCache.get(ctx)?.delete(path.resolve(dir));
107
+ }
27
108
  /**
28
109
  * What wtc remaps for a stack run from `dir`, without writing anything: the
29
- * repository's targets minus what the directory's own compose override sets
30
- * for a service — or nothing when its `.env` sets `COMPOSE_FILE` or
110
+ * compose file's targets minus what the directory's own compose override
111
+ * sets for a service — or nothing when its `.env` sets `COMPOSE_FILE` or
31
112
  * `COMPOSE_PATH_SEPARATOR` (a worktree's unmanaged `.env`, with a custom
32
113
  * envFile; the repository's own settings were checked with the context).
33
114
  */
34
- export function stackRemap(ctx, dir, project) {
35
- if (!ctx.remap)
115
+ export function stackRemap(ctx, dir, project, view = stackView(ctx, dir)) {
116
+ if (!view.remap)
36
117
  return { targets: null, warnings: [] };
37
118
  const separator = separatorConflicts(dir);
38
- if (separator || isUserComposeFile(envFileComposeFile(path.join(dir, ".env")), ctx.repo.commonDir)) {
119
+ if (separator ||
120
+ isUserComposeFile(envFileComposeFile(path.join(dir, ".env")), ctx.repo.commonDir, ctx.customComposeRoots)) {
39
121
  return {
40
122
  targets: null,
41
123
  warnings: [
@@ -43,7 +125,7 @@ export function stackRemap(ctx, dir, project) {
43
125
  ],
44
126
  };
45
127
  }
46
- const { targets, warnings } = withoutUserOverride(ctx.remap, dir);
128
+ const { targets, warnings } = withoutUserOverride(view.remap, composeDirIn(ctx, dir));
47
129
  return { targets: remapIsEmpty(targets) ? null : targets, warnings };
48
130
  }
49
131
  /** Whether `dir`'s `.env` sets a `COMPOSE_PATH_SEPARATOR` that would split wtc's list differently. */
@@ -54,52 +136,187 @@ function separatorConflicts(dir) {
54
136
  /** Host ports a stack keeps as written: hardcoded ones wtc does not move, ranges whole. */
55
137
  function keptHostPorts(mappings, moving) {
56
138
  const moved = new Set(moving);
57
- return mappings
58
- .filter((m) => m.envVar === null && !moved.has(m))
59
- .map((m) => [m.defaultPort, m.rangeEnd ?? m.defaultPort]);
139
+ const kept = new Set();
140
+ for (const m of mappings) {
141
+ if (m.envVar !== null || moved.has(m))
142
+ continue;
143
+ for (let p = m.defaultPort; p <= (m.rangeEnd ?? m.defaultPort); p++)
144
+ kept.add(p);
145
+ }
146
+ return kept;
147
+ }
148
+ /** The registry's ports as the context read them (a snapshot). */
149
+ export function portSources(ctx, project) {
150
+ const others = new Set();
151
+ let recorded;
152
+ for (const r of [...ctx.worktrees, ...ctx.orphans, ...ctx.unavailable]) {
153
+ if (r.project === project)
154
+ recorded = r.ports;
155
+ else
156
+ for (const p of Object.values(r.ports ?? {}))
157
+ others.add(p);
158
+ }
159
+ return { recorded, others };
60
160
  }
61
161
  /**
62
162
  * The stack's ports: every variable, plus each hardcoded port in `targets`
63
- * that can move in this worktree to a port the stack does not already
64
- * publish (a hardcoded port it keeps, or one inside a range). Returns the
65
- * targets actually remapped and a warning for each port left as it is.
163
+ * that can move. A port the stack already holds (its registry record)
164
+ * stays; a new one starts from the formula and moves past ports another
165
+ * stack holds, ports this stack publishes as written, and `blocked` ones.
166
+ * Returns the targets actually remapped and a warning for each hardcoded
167
+ * port left as it is.
66
168
  */
67
- export function stackAllocations(ctx, index, targets) {
68
- if (!targets) {
69
- return { allocations: allocateWorktreePorts(ctx.portMappings, index, ctx.portStride), targets: null, warnings: [] };
70
- }
71
- const allocations = allocateWorktreePorts(ctx.portMappings, index, ctx.portStride, targets.ports);
169
+ export function stackAllocations(ctx, target, targets, opts = {}) {
170
+ const view = opts.view ?? stackView(ctx, target.dir);
171
+ const sources = opts.sources ?? portSources(ctx, target.project);
172
+ const resolve = (moving) => resolveWorktreePorts(view.portMappings, target.index, ctx.portStride, moving, {
173
+ recorded: sources.recorded,
174
+ taken: new Set([...sources.others, ...(opts.blocked ?? []), ...keptHostPorts(view.portMappings, moving)]),
175
+ });
176
+ if (!targets)
177
+ return { allocations: resolve([]), targets: null, warnings: [] };
178
+ // A hardcoded port with nowhere to move stays, and is then one the stack
179
+ // publishes as written — which the others must stay clear of: repeat
180
+ // until nothing more has to stay.
72
181
  const stays = new Map();
73
- // A port that stays is one the stack keeps, which can block another
74
- // port's move in turn: repeat until nothing more has to stay.
75
- for (let moving = targets.ports, changed = true; changed; moving = moving.filter((m) => !stays.has(m.defaultPort))) {
182
+ let moving = targets.ports;
183
+ let allocations = resolve(moving);
184
+ for (let changed = true; changed;) {
76
185
  changed = false;
77
- const kept = keptHostPorts(ctx.portMappings, moving);
78
186
  for (const m of moving) {
79
- if (stays.has(m.defaultPort))
187
+ if (allocations.some((a) => a.defaultPort === m.defaultPort))
80
188
  continue;
81
- const a = allocations.find((x) => x.defaultPort === m.defaultPort);
82
- if (!a) {
83
- stays.set(m.defaultPort, `Service "${m.serviceName}": hardcoded host port ${m.defaultPort} has no free port to move to in worktree ${index} (ports end at 65535), so it stays ${m.defaultPort}.`);
84
- changed = true;
85
- }
86
- else if (kept.some(([from, to]) => a.port >= from && a.port <= to)) {
87
- // Also when the port is a variable's (same default port, e.g. tcp
88
- // and udp): the hardcoded entry would publish it a second time.
89
- stays.set(m.defaultPort, `Service "${m.serviceName}": hardcoded host port ${m.defaultPort} would move to ${a.port}, which this stack already publishes, so it stays ${m.defaultPort}.`);
90
- changed = true;
91
- }
189
+ stays.set(m.defaultPort, `Service "${m.serviceName}": hardcoded host port ${m.defaultPort} has no free port to move to in worktree ${target.index} (ports end at 65535), so it stays ${m.defaultPort}.`);
190
+ changed = true;
191
+ }
192
+ if (changed) {
193
+ moving = moving.filter((m) => !stays.has(m.defaultPort));
194
+ allocations = resolve(moving);
92
195
  }
93
196
  }
94
197
  if (stays.size === 0)
95
198
  return { allocations, targets, warnings: [] };
96
- const remaining = { ...targets, ports: targets.ports.filter((m) => !stays.has(m.defaultPort)) };
199
+ const remaining = { ...targets, ports: moving };
97
200
  return {
98
- allocations: allocations.filter((a) => a.envVar !== null || !stays.has(a.defaultPort)),
201
+ allocations,
99
202
  targets: remapIsEmpty(remaining) ? null : remaining,
100
203
  warnings: [...stays.values()],
101
204
  };
102
205
  }
206
+ /** Ports published by this stack's running containers, and by every other running container. */
207
+ function enginePorts(ctx, project) {
208
+ const own = new Set();
209
+ const others = new Set();
210
+ for (const c of ctx.stacks?.containers() ?? []) {
211
+ for (const port of c.hostPorts)
212
+ (c.project === project ? own : others).add(port);
213
+ }
214
+ for (const port of own)
215
+ others.delete(port);
216
+ return { own, others };
217
+ }
218
+ const HELD_PORT_RECHECKS = 3;
219
+ const HELD_PORT_RECHECK_MS = 250;
220
+ /**
221
+ * Settle a stack's host ports before it starts, and record them. A port the
222
+ * stack already holds stays, unless the stack is not running and something
223
+ * else has taken it; a new port starts from the formula and moves past
224
+ * whatever is taken — by another stack of this repository (the registry),
225
+ * by any running container, or by a process listening on the host.
226
+ *
227
+ * The choice is made and recorded under the registry lock, against the
228
+ * registry as it is at that moment, so two `wtc start` runs in different
229
+ * worktrees never settle on the same port. Probing the host happens
230
+ * outside the lock.
231
+ */
232
+ export async function assignStackPorts(ctx, target, probe, recheck = probe) {
233
+ const commonDir = ctx.repo.commonDir;
234
+ const engine = enginePorts(ctx, target.project);
235
+ const blocked = new Set(engine.others);
236
+ // Ports this stack's own containers publish are its own: never "taken".
237
+ const free = new Set(engine.own);
238
+ const before = portSources(ctx, target.project).recorded ?? {};
239
+ const held = new Set(Object.values(before));
240
+ // Without a container listing (an engine whose `ps` output wtc cannot read)
241
+ // a running stack's ports cannot be told from someone else's: the ports it
242
+ // recorded are taken to be its own, rather than moved on every start.
243
+ if (ctx.stacks && ctx.stacks.containers() === null && (ctx.stacks.state(target.project)?.running ?? 1) > 0) {
244
+ for (const port of held)
245
+ free.add(port);
246
+ }
247
+ const persisted = fs.existsSync(stateFile(commonDir));
248
+ for (let round = 0; round < 100; round++) {
249
+ const settle = () => {
250
+ const state = persisted ? peekState(commonDir) : null;
251
+ if (state)
252
+ refreshRecordedPorts(ctx, state);
253
+ const view = stackView(ctx, target.dir);
254
+ const remap = stackRemap(ctx, target.dir, target.project, view);
255
+ // Every record the registry holds right now counts, also of a worktree
256
+ // another process registered after this context was built.
257
+ const sources = state ? registrySources(state, target.project) : undefined;
258
+ const { allocations } = stackAllocations(ctx, target, remap.targets, { view, blocked, sources });
259
+ const unknown = allocations.map((a) => a.port).filter((p) => !free.has(p));
260
+ if (unknown.length > 0)
261
+ return unknown;
262
+ const ports = portsByLabel(allocations);
263
+ const record = state?.worktrees.find((r) => r.project === target.project);
264
+ if (state && record && JSON.stringify(record.ports ?? {}) !== JSON.stringify(ports)) {
265
+ record.ports = ports;
266
+ writeState(commonDir, state);
267
+ }
268
+ for (const r of [...ctx.worktrees, ...ctx.orphans, ...ctx.unavailable]) {
269
+ if (r.project === target.project)
270
+ r.ports = ports;
271
+ }
272
+ return ports;
273
+ };
274
+ const outcome = persisted ? withStateLock(commonDir, settle) : settle();
275
+ if (!Array.isArray(outcome)) {
276
+ const moved = Object.entries(outcome).flatMap(([label, to]) => {
277
+ const from = before[label];
278
+ return from !== undefined && from !== to ? [{ label, from, to }] : [];
279
+ });
280
+ return { blocked, moved };
281
+ }
282
+ for (const port of new Set(outcome)) {
283
+ let busy = await probe(port);
284
+ // A port the stack held a moment ago may still be on its way out (a
285
+ // restart probes right after `compose stop`): moving it would change the
286
+ // stack's URLs for nothing, so it gets a little time before that.
287
+ for (let attempt = 0; busy && held.has(port) && attempt < HELD_PORT_RECHECKS; attempt++) {
288
+ await new Promise((resolve) => setTimeout(resolve, HELD_PORT_RECHECK_MS));
289
+ busy = await recheck(port);
290
+ }
291
+ if (busy)
292
+ blocked.add(port);
293
+ else
294
+ free.add(port);
295
+ }
296
+ }
297
+ throw new Error(`Could not find free host ports for ${target.project}: too many are taken.`);
298
+ }
299
+ /** A stack's port sources straight from the registry. */
300
+ function registrySources(state, project) {
301
+ const others = new Set();
302
+ let recorded;
303
+ for (const r of state.worktrees) {
304
+ if (r.project === project)
305
+ recorded = r.ports;
306
+ else
307
+ for (const p of Object.values(r.ports ?? {}))
308
+ others.add(p);
309
+ }
310
+ return { recorded, others };
311
+ }
312
+ /** Bring the context's copy of every record's ports up to date with the registry. */
313
+ function refreshRecordedPorts(ctx, state) {
314
+ const byProject = new Map(state.worktrees.map((r) => [r.project, r.ports]));
315
+ for (const r of [...ctx.worktrees, ...ctx.orphans, ...ctx.unavailable]) {
316
+ if (byProject.has(r.project))
317
+ r.ports = byProject.get(r.project);
318
+ }
319
+ }
103
320
  /**
104
321
  * Ports and compose files for one stack: the `COMPOSE_FILE` list compose
105
322
  * would otherwise pick by itself — the compose file, the directory's own
@@ -108,47 +325,55 @@ export function stackAllocations(ctx, index, targets) {
108
325
  *
109
326
  * `start` (`write`) writes the override, after syncing the worktree's
110
327
  * compose file from main. `stop` and teardown use the override the stack
111
- * was started with as it is: rewriting it from main's current compose file
112
- * could name services the worktree's (older) compose file does not have,
113
- * which the `COMPOSE_FILE` in the worktree's env file also loads.
328
+ * was started with as it is: rewriting it from the current compose file
329
+ * could name services the stack was not started with.
114
330
  */
115
331
  export function prepareStack(ctx, target, opts) {
116
332
  const file = overridePath(ctx.repo.commonDir, target.project);
333
+ const view = stackView(ctx, target.dir);
334
+ const roots = composeFilesIn(ctx, target.dir);
117
335
  const filesWith = (override) => {
118
- const userOverride = findUserOverride(target.dir);
119
- return composeFileValue([
120
- path.join(target.dir, path.basename(ctx.composeFile.composePath)),
121
- ...(userOverride ? [userOverride] : []),
122
- override,
123
- ]);
336
+ // Compose loads a compose override next to the file by itself only when one file is given.
337
+ const userOverride = roots.length === 1 ? findUserOverride(path.dirname(roots[0])) : null;
338
+ return composeFileValue([...roots, ...(userOverride ? [userOverride] : []), override]);
124
339
  };
125
- const remap = stackRemap(ctx, target.dir, target.project);
126
- const stack = stackAllocations(ctx, target.index, remap.targets);
127
- const warnings = [...remap.warnings, ...stack.warnings];
340
+ const remap = stackRemap(ctx, target.dir, target.project, view);
341
+ const stack = stackAllocations(ctx, target, remap.targets, { view, blocked: opts.blocked });
342
+ const warnings = [...view.warnings, ...remap.warnings, ...stack.warnings];
343
+ const extra = opts.extra && !extrasAreEmpty(opts.extra) ? opts.extra : undefined;
128
344
  if (!opts.write && fs.existsSync(file)) {
129
345
  const composeFile = filesWith(file);
130
346
  if (composeFile !== null)
131
- return { allocations: stack.allocations, composeFile, warnings: [] };
347
+ return { allocations: stack.allocations, composeFile, warnings: [], view };
348
+ }
349
+ const multiFile = roots.length > 1 || ctx.composeIsCustom;
350
+ if ((!stack.targets && !extra) || opts.readOnly) {
351
+ // Several compose files, or one compose would not find by itself: name them for every call.
352
+ return {
353
+ allocations: stack.allocations,
354
+ composeFile: multiFile ? composeFileValue(roots) : null,
355
+ warnings,
356
+ view,
357
+ };
132
358
  }
133
- if (!stack.targets)
134
- return { allocations: stack.allocations, composeFile: null, warnings };
135
359
  const composeFile = filesWith(file);
136
360
  if (composeFile === null) {
137
361
  return {
138
- allocations: allocateWorktreePorts(ctx.portMappings, target.index, ctx.portStride),
362
+ allocations: stackAllocations(ctx, target, null, { view, blocked: opts.blocked }).allocations,
139
363
  composeFile: null,
140
364
  warnings: [
141
365
  ...warnings,
142
366
  `A path of ${target.project}'s compose files contains the COMPOSE_FILE separator, so wtc does not remap hardcoded ports or container_name for it.`,
143
367
  ],
368
+ view,
144
369
  };
145
370
  }
146
371
  // `stop`/teardown of a stack started before wtc remapped (or whose file
147
372
  // was deleted) recreate it.
148
373
  if (opts.write || !fs.existsSync(file)) {
149
- writeOverride(file, renderOverride(target.project, ctx.composeFile, stack.targets, stack.allocations));
374
+ writeOverride(file, renderOverride(target.project, view.composeFile, stack.targets ?? { ports: [], containerNames: [] }, stack.allocations, extra));
150
375
  }
151
- return { allocations: stack.allocations, composeFile, warnings };
376
+ return { allocations: stack.allocations, composeFile, warnings, view };
152
377
  }
153
378
  /** Run `<compose> -p <project> <args…>` without blocking the event loop. */
154
379
  export function composeRun(engine, project, args, opts) {
@@ -1,4 +1,6 @@
1
+ import { isPortBusy } from "../ports/probe.js";
1
2
  import type { CoreIo } from "./types.js";
3
+ export { isPortBusy };
2
4
  export type CheckStatus = "ok" | "warn" | "fail";
3
5
  export interface DoctorCheck {
4
6
  status: CheckStatus;
@@ -11,14 +13,6 @@ export interface DoctorResult {
11
13
  ok: boolean;
12
14
  checks: DoctorCheck[];
13
15
  }
14
- /**
15
- * True when something already listens on `port`. Docker publishes on all
16
- * interfaces, but local dev servers and Homebrew databases usually bind
17
- * 127.0.0.1 or ::1 only — and on macOS (BSD sockets, libuv's SO_REUSEADDR)
18
- * a wildcard bind succeeds next to them, so each address is probed. Only
19
- * EADDRINUSE counts as busy (no IPv6 → not busy).
20
- */
21
- export declare function isPortBusy(port: number): Promise<boolean>;
22
16
  /**
23
17
  * Diagnose the setup: git, repo layout, compose file, config, compose
24
18
  * engine and daemon, port isolation (including what is remapped at