worktree-compose 1.1.2 → 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.
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,18 +2,109 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { buildContext, getEnvTargets } from "../context.js";
4
4
  import { samePath } from "../git/worktree.js";
5
- import { recordEnvFiles } from "../state/registry.js";
6
- import { allocateWorktreePorts, portLabel, portsByLabel } from "../ports/allocate.js";
5
+ import { recordEnvFiles, recordServices } from "../state/registry.js";
6
+ import { portLabel, portsByLabel } from "../ports/allocate.js";
7
+ import { cachedPortProbe, isPortBusy } from "../ports/probe.js";
7
8
  import { inheritedComposeFileNames, overridePath, removeOverride } from "../compose/override.js";
9
+ import { listContainers } from "../compose/status.js";
8
10
  import { syncWorktreeFiles } from "../sync/files.js";
9
- import { findEnvSource, injectPortOverrides, prepareEnvFile } from "../sync/env.js";
10
- import { selectWorktrees } from "../selectors.js";
11
- import { composeEnv, composeRun, NO_WORKTREES_HINT, prepareStack, reportContextWarnings, throwIfAborted, withContext, } from "./compose.js";
11
+ import { isLocalEnvFileName } from "../sync/env.js";
12
+ import { excludeFromGit, injectEnvTargets, syncEnvFiles } from "../sync/envsync.js";
13
+ import { implicitScopeNote, selectScope } from "../selectors.js";
14
+ import { assignStackPorts, composeEnv, composeRun, mainStackDirs, NO_WORKTREES_HINT, prepareStack, reportContextWarnings, resetStackView, stackAllocations, stackRemap, stackView, throwIfAborted, withContext, worktreeProjects, } from "./compose.js";
15
+ import { describeService, diagnoseStack, expectedServices, serviceClosure, serviceLogTails, waitForStack, } from "./health.js";
16
+ import { linkSharedServices, sharedExtras } from "./shared.js";
17
+ import { seedVolumes } from "./seed.js";
18
+ /** How long `--wait` waits for a stack unless told otherwise. */
19
+ export const DEFAULT_WAIT_SECONDS = 300;
20
+ /** The services a start brings up: this run's, else the ones remembered for the worktree, else the config's. */
21
+ function servicesFor(options, ctx, wt, view) {
22
+ if (options.allServices)
23
+ return null;
24
+ const asked = options.services?.length ? options.services : null;
25
+ const chosen = asked ?? wt.services ?? ctx.config.services ?? null;
26
+ if (!chosen || chosen.length === 0)
27
+ return null;
28
+ const declared = new Set(view.composeFile.services.map((s) => s.name));
29
+ const unknown = chosen.filter((s) => !declared.has(s));
30
+ if (asked && unknown.length > 0) {
31
+ throw new Error(`Unknown service${unknown.length === 1 ? "" : "s"} ${unknown.map((s) => `"${s}"`).join(", ")}. ` +
32
+ `Services: ${[...declared].sort().join(", ") || "(none)"}.`);
33
+ }
34
+ // A remembered or configured name the branch's compose file no longer has is dropped, not fatal.
35
+ const known = chosen.filter((s) => declared.has(s));
36
+ if (known.length === 0)
37
+ return null;
38
+ const shared = known.filter((s) => ctx.sharedServices.has(s));
39
+ if (asked && shared.length > 0) {
40
+ throw new Error(`${shared.map((s) => `"${s}"`).join(", ")} ${shared.length === 1 ? "is a shared service" : "are shared services"}: ` +
41
+ `worktree stacks use the main checkout's instance, so start it there (docker compose up -d ${shared.join(" ")}).`);
42
+ }
43
+ const own = known.filter((s) => !ctx.sharedServices.has(s));
44
+ if (own.length === 0) {
45
+ // `compose up` without a service name would start everything: an empty selection is not "all".
46
+ throw new Error(`Every service selected for worktree ${wt.index} (${known.join(", ")}) is shared with the main checkout, so there is nothing for its stack to start. ` +
47
+ `Change "services" or "shared" in the config, or pass --service <name> / --all-services.`);
48
+ }
49
+ return own;
50
+ }
51
+ /**
52
+ * Fail on a service selection a target's compose file cannot satisfy,
53
+ * without touching anything: `restart` asks before it stops the stacks.
54
+ */
55
+ export function preflightServices(options, io) {
56
+ if (!options.services?.length || options.allServices)
57
+ return;
58
+ const ctx = buildContext(options, { cwd: io.cwd, readOnly: true, requireMainFor: "start worktree stacks" });
59
+ if (ctx.worktrees.length === 0)
60
+ return;
61
+ for (const wt of selectScope(ctx.worktrees, options.worktrees, ctx.cwd, options.all).targets) {
62
+ servicesFor(options, ctx, wt, stackView(ctx, wt.path));
63
+ }
64
+ }
65
+ /**
66
+ * Env files a service reads on top of a tracked env file wtc could not
67
+ * write to (its `.local` sibling). A sidecar belongs right after its
68
+ * file: where the service reads further env files after that one, its
69
+ * whole list is given in order (`envFileLists`), so a later file keeps the
70
+ * last word. Otherwise — and for a list wtc cannot reproduce exactly — the
71
+ * sidecars are added at the end (`envFiles`).
72
+ */
73
+ function sidecarEnvFiles(ctx, wtPath, view, env) {
74
+ const envFiles = {};
75
+ const envFileLists = {};
76
+ if (env.sidecars.size === 0)
77
+ return { envFiles };
78
+ // The view's paths are the main checkout's, unless the worktree's own compose file was read.
79
+ const viewRoot = view.own ? wtPath : ctx.repoRoot;
80
+ for (const svc of view.composeFile.services) {
81
+ const baseDir = svc.baseDir ?? path.dirname(svc.sourcePath);
82
+ const entries = svc.envFile ?? [];
83
+ const inWorktree = (entry) => path.isAbsolute(entry) ? entry : path.join(wtPath, path.relative(viewRoot, path.resolve(baseDir, entry)));
84
+ const sidecarOf = (entry) => (entry.includes("$") ? undefined : env.sidecars.get(inWorktree(entry)));
85
+ const extra = entries.flatMap((entry) => sidecarOf(entry) ?? []);
86
+ if (extra.length === 0)
87
+ continue;
88
+ const lastWithSidecar = entries.reduce((last, entry, i) => (sidecarOf(entry) ? i : last), -1);
89
+ const exact = svc.envFileSimple === true && entries.every((entry) => !entry.includes("$"));
90
+ if (lastWithSidecar < entries.length - 1 && exact) {
91
+ envFileLists[svc.name] = entries.flatMap((entry) => {
92
+ const sidecar = sidecarOf(entry);
93
+ // A sidecar that is itself a later entry of the list is read there.
94
+ return sidecar && !entries.some((e) => inWorktree(e) === sidecar) ? [inWorktree(entry), sidecar] : [inWorktree(entry)];
95
+ });
96
+ }
97
+ else {
98
+ envFiles[svc.name] = extra;
99
+ }
100
+ }
101
+ return { envFiles, ...(Object.keys(envFileLists).length > 0 ? { envFileLists } : {}) };
102
+ }
12
103
  /**
13
- * Sync infra files, inject ports + project name into env files, and run
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.
104
+ * Sync infra files, settle the stack's ports, bring its env files up to
105
+ * date, and run `compose up -d` for each selected worktree (with the
106
+ * stack's runtime override when hardcoded settings are remapped). Stops at
107
+ * the first failure, saying which services failed and what they logged.
17
108
  */
18
109
  export async function startWorktrees(options, reporter, io) {
19
110
  const ctx = buildContext(options, { cwd: io.cwd, probeStacks: true, requireMainFor: "start worktree stacks" });
@@ -22,11 +113,24 @@ export async function startWorktrees(options, reporter, io) {
22
113
  reporter.warn(NO_WORKTREES_HINT);
23
114
  return { started: [] };
24
115
  }
25
- const targets = selectWorktrees(ctx.worktrees, options.worktrees, ctx.cwd);
116
+ const scope = selectScope(ctx.worktrees, options.worktrees, ctx.cwd, options.all);
117
+ if (scope.implicit)
118
+ reporter.info(implicitScopeNote(scope.implicit));
119
+ const targets = scope.targets;
26
120
  const envTargets = getEnvTargets(ctx);
27
121
  const engine = ctx.getEngine();
28
122
  const build = options.build !== false;
29
123
  const started = [];
124
+ const probe = cachedPortProbe(io.portProbe ?? isPortBusy);
125
+ const stackProjects = worktreeProjects(ctx);
126
+ const mainDirs = mainStackDirs(ctx);
127
+ // Leaving a service out of a stack takes compose's !override tag, like remapping does.
128
+ // Without it the stack would run its own copy on the main checkout's ports: say so first.
129
+ if (ctx.sharedServices.size > 0 && !ctx.canRemap()) {
130
+ throw new Error(`"shared" (${[...ctx.sharedServices].join(", ")}) cannot be applied: it takes a compose override wtc controls ` +
131
+ `(Docker Compose 2.24.4 or newer, and no COMPOSE_FILE of your own). Run 'wtc doctor' to see what is in the way, or remove "shared" from the config.`);
132
+ }
133
+ const seed = options.seed === false ? false : options.seed === true ? true : (ctx.config.seedVolumes ?? false);
30
134
  for (const wt of targets) {
31
135
  throwIfAborted(io);
32
136
  // Never treat the env/config source as a worktree, and never recreate a
@@ -37,76 +141,220 @@ export async function startWorktrees(options, reporter, io) {
37
141
  if (!fs.existsSync(path.join(wt.path, ".git"))) {
38
142
  throw new Error(`Worktree ${wt.index} (${wt.branch}) is missing on disk (${wt.path}). Remount it, or run 'git worktree prune' and 'wtc prune'.`);
39
143
  }
144
+ const target = { project: wt.project, index: wt.index, dir: wt.path };
40
145
  // Fail on an unallocatable port before writing anything into the worktree.
41
- allocateWorktreePorts(ctx.portMappings, wt.index, ctx.portStride, ctx.remap?.ports);
146
+ stackAllocations(ctx, target, stackRemap(ctx, wt.path, wt.project).targets);
42
147
  reporter.header(`Worktree ${wt.index}: ${wt.branch}`);
43
148
  reporter.info(`Path: ${wt.path}`);
44
149
  reporter.info(`Project: ${wt.project}`);
45
- const syncWarnings = syncWorktreeFiles(ctx.repoRoot, wt.path, ctx.composeFile, ctx.config.sync);
150
+ const synced = syncWorktreeFiles(ctx.repoRoot, wt.path, ctx.composeFile, ctx.config.sync);
46
151
  // Skipped sync entries were already reported with the context warnings.
47
- for (const w of syncWarnings)
152
+ for (const w of synced.warnings)
48
153
  if (!ctx.warnings.includes(w))
49
154
  reporter.warn(w);
50
155
  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 });
156
+ if (synced.copied.length > 0) {
157
+ reporter.info(`Copied untracked files the stack needs from the main checkout: ${synced.copied.join(", ")}`);
158
+ }
159
+ for (const rel of synced.data) {
160
+ reporter.info(`${rel} is bind-mounted, untracked, and holds a service's data: not copied, so this stack starts with its own. Add "${rel}" to "sync" in .wtcrc.json to copy the main checkout's.`);
161
+ }
162
+ for (const rel of synced.tooLarge) {
163
+ reporter.warn(`${rel}/ is bind-mounted but untracked, and too large to copy unasked: this stack starts with an empty one. Add "${rel}" to "sync" in .wtcrc.json to copy it.`);
164
+ }
165
+ // After the sync: the worktree's compose file or its own compose override may be a synced file.
166
+ resetStackView(ctx, wt.path);
167
+ const view = stackView(ctx, wt.path);
168
+ if (view.own)
169
+ reporter.info("Compose file: this worktree's own (it differs from the main checkout's)");
170
+ const services = servicesFor(options, ctx, wt, view);
171
+ const assigned = await assignStackPorts(ctx, target, probe, io.portProbe ?? isPortBusy);
172
+ for (const m of assigned.moved) {
173
+ reporter.info(`Port ${m.label} moved from ${m.from} to ${m.to}: ${m.from} is in use by something else.`);
174
+ }
175
+ const ports = stackAllocations(ctx, target, stackRemap(ctx, wt.path, wt.project, view).targets, {
176
+ view,
177
+ blocked: assigned.blocked,
178
+ }).allocations;
179
+ const envInput = {
180
+ repoRoot: ctx.repoRoot,
181
+ wtPath: wt.path,
182
+ commonDir: ctx.repo.commonDir,
183
+ targets: envTargets,
184
+ allocations: ports,
185
+ rewritePorts: ctx.config.rewriteEnvPorts !== false,
186
+ // An env file a service reads through `env_file:` was copied by the file sync
187
+ // just now: it is wtc's copy as well, so its ports are rewritten and it is recorded.
188
+ managed: [
189
+ ...(wt.envFiles ?? []),
190
+ ...synced.copied
191
+ .map((f) => f.split(path.sep).join("/"))
192
+ .filter((f) => isLocalEnvFileName(path.posix.basename(f))),
193
+ ],
194
+ moved: new Map(assigned.moved.map((m) => [m.from, m.to])),
195
+ };
196
+ const env = syncEnvFiles(envInput);
197
+ for (const w of env.warnings)
198
+ reporter.warn(w);
199
+ for (const n of env.notes)
200
+ reporter.info(n);
201
+ const extra = {
202
+ ...sharedExtras(view.composeFile, ctx.sharedServices),
203
+ ...sidecarEnvFiles(ctx, wt.path, view, env),
204
+ };
205
+ const stack = prepareStack(ctx, target, { write: true, blocked: assigned.blocked, extra });
206
+ if (extra.shared?.length && stack.composeFile === null) {
207
+ // No override could be written (see the warning): the stack would start its own copies.
208
+ throw new Error(`"shared" (${extra.shared.join(", ")}) cannot be applied to worktree ${wt.index}: a path of its compose files contains the COMPOSE_FILE separator, so wtc cannot give compose an override for it.`);
209
+ }
53
210
  // A stale override goes, unless an inherited COMPOSE_FILE still lists it.
54
211
  const overrideFile = overridePath(ctx.repo.commonDir, wt.project);
55
- if (stack.composeFile === null && !inheritedComposeFileNames(overrideFile))
212
+ if ((stack.composeFile === null || !stack.composeFile.includes(overrideFile)) &&
213
+ !inheritedComposeFileNames(overrideFile)) {
56
214
  removeOverride(overrideFile);
215
+ }
57
216
  for (const w of stack.warnings)
58
217
  reporter.warn(w);
59
218
  const allocations = stack.allocations;
60
219
  reporter.info(`Ports: ${allocations.map((a) => `${portLabel(a)}=${a.port}`).join(" ") || "(none)"}`);
61
- const injected = [];
62
- for (const target of envTargets) {
63
- const envWarnings = [];
64
- const envPath = prepareEnvFile(ctx.repoRoot, wt.path, target, envWarnings);
65
- for (const w of envWarnings)
66
- reporter.warn(w);
67
- if (!envPath) {
68
- if (envWarnings.length === 0) {
69
- reporter.warn(`No ${target.envFileName} (or .env.example) found for ${target.label}; skipped`);
70
- }
71
- continue;
72
- }
73
- const injection = injectPortOverrides(envPath, allocations, target.overrides, {
74
- projectName: wt.project,
75
- writeProjectName: target.dir === "",
76
- ...(target.dir === "" && stack.composeFile ? { composeFile: stack.composeFile } : {}),
77
- root: wt.path,
78
- source: findEnvSource(ctx.repoRoot, target) ?? undefined,
79
- });
80
- for (const w of injection.warnings)
81
- reporter.warn(w);
82
- injected.push(path.relative(wt.path, envPath));
83
- }
84
- if (injected.length > 0) {
85
- reporter.success(`Injected port overrides into ${injected.join(", ")}`);
220
+ const injected = injectEnvTargets({ ...envInput, allocations }, env, {
221
+ projectName: wt.project,
222
+ composeFile: stack.composeFile,
223
+ });
224
+ for (const w of injected.warnings)
225
+ reporter.warn(w);
226
+ if (injected.written.length > 0) {
227
+ reporter.success(`Injected port overrides into ${injected.written.join(", ")}`);
86
228
  }
87
229
  // Remember exactly which env files wtc wrote (before compose runs: they
88
230
  // are written even if `up` fails), so clean treats only those as wtc's
89
231
  // own changes.
90
- recordEnvFiles(ctx.repo.commonDir, wt.path, injected);
232
+ // Files of the user's in which wtc only keeps a block stay the user's: not recorded.
233
+ const written = [...new Set([...env.written, ...injected.written])];
234
+ recordEnvFiles(ctx.repo.commonDir, wt.path, written);
235
+ wt.envFiles = [...new Set([...(wt.envFiles ?? []), ...written.map((f) => f.split(path.sep).join("/"))])];
236
+ // An env file wtc wrote must not show up in `git status` (and from there, with
237
+ // its secrets and this machine's paths, in a commit).
238
+ // Only files that are wtc's: one of the user's must stay visible to git, or
239
+ // `wtc clean` would take its worktree for clean and remove the file with it.
240
+ const excluded = excludeFromGit(ctx.repo.commonDir, wt.path, written);
241
+ if (excluded.length > 0) {
242
+ reporter.info(`Added ${excluded.join(", ")} to .git/info/exclude, so wtc's env files stay out of git status.`);
243
+ }
244
+ const rootTarget = env.destinations.find((d) => d.target.dir === "");
245
+ if (rootTarget?.sidecar && rootTarget.target.envFileName === ".env") {
246
+ reporter.info("Plain 'docker compose' in this worktree would not see its project name (compose reads only .env, which the branch tracks): use 'wtc compose' / 'wtc exec' / 'wtc logs' here.");
247
+ }
248
+ if (options.services?.length || options.allServices) {
249
+ recordServices(ctx.repo.commonDir, wt.path, options.allServices ? null : services);
250
+ wt.services = services ?? undefined;
251
+ }
252
+ if (services)
253
+ reporter.info(`Services: ${services.join(", ")} (and what they depend on)`);
254
+ if (extra.shared?.length)
255
+ reporter.info(`Shared with the main checkout: ${extra.shared.join(", ")}`);
256
+ // What this start brings up: with a selection, the rest of the stack is not its concern.
257
+ const scope = serviceClosure(view.composeFile.services, services, ctx.sharedServices);
258
+ const callEnv = composeEnv(wt.project, allocations, stack.composeFile, ctx.repo.commonDir, ctx.customComposeRoots);
259
+ const call = { cwd: wt.path, env: callEnv, signal: io.signal };
260
+ let containers = [];
91
261
  try {
92
- await composeRun(engine, wt.project, ["up", "-d", ...(build ? ["--build"] : []), ...(options.removeOrphans ? ["--remove-orphans"] : [])], {
93
- cwd: wt.path,
94
- env: composeEnv(wt.project, allocations, stack.composeFile, ctx.repo.commonDir),
95
- live: io.live,
262
+ containers = ctx.stacks?.containers() ?? [];
263
+ }
264
+ catch {
265
+ containers = [];
266
+ }
267
+ if (seed !== false) {
268
+ const mounted = new Set(view.composeFile.services
269
+ .filter((s) => !ctx.sharedServices.has(s.name) && (!scope || scope.has(s.name)))
270
+ .flatMap((s) => s.volumeKeys ?? []));
271
+ const seeded = await seedVolumes({
272
+ engine,
273
+ project: wt.project,
274
+ composeFile: view.composeFile,
275
+ volumes: seed,
276
+ mounted,
277
+ mainDirs,
278
+ mainProjectName: ctx.composeFile.projectName,
279
+ worktreeProjects: stackProjects,
280
+ containers,
281
+ reporter,
96
282
  signal: io.signal,
97
- onLine: io.onOutput,
98
283
  });
284
+ for (const w of seeded.warnings)
285
+ reporter.warn(w);
286
+ if (seeded.seeded.length > 0) {
287
+ reporter.success(`Seeded volumes from the main checkout: ${seeded.seeded.join(", ")}`);
288
+ }
289
+ }
290
+ const linkShared = () => {
291
+ const linked = linkSharedServices({
292
+ engine,
293
+ project: wt.project,
294
+ composeFile: view.composeFile,
295
+ shared: ctx.sharedServices,
296
+ mainDirs,
297
+ mainProjectName: ctx.composeFile.projectName,
298
+ worktreeProjects: stackProjects,
299
+ });
300
+ return linked.warnings;
301
+ };
302
+ const up = (flags) => composeRun(engine, wt.project, ["up", ...flags, ...(options.removeOrphans ? ["--remove-orphans"] : []), ...(services ?? [])], { cwd: wt.path, env: callEnv, live: io.live, signal: io.signal, onLine: io.onOutput });
303
+ try {
304
+ if (extra.shared?.length) {
305
+ // The stack's services must find the shared ones under their names from
306
+ // the first moment: create the stack without starting it, connect the main
307
+ // checkout's containers to its networks, and only then start it.
308
+ await up(["--no-start", ...(build ? ["--build"] : [])]);
309
+ for (const w of linkShared())
310
+ reporter.warn(w);
311
+ await up(["-d"]);
312
+ }
313
+ else {
314
+ await up(["-d", ...(build ? ["--build"] : [])]);
315
+ }
99
316
  }
100
317
  catch (err) {
101
- throw withContext(`Failed to start worktree ${wt.index} (${wt.branch})`, err);
318
+ const diagnosis = io.signal?.aborted ? "" : await diagnoseStack(engine, wt.project, call, undefined, scope);
319
+ const failure = withContext(`Failed to start worktree ${wt.index} (${wt.branch})`, err);
320
+ if (diagnosis)
321
+ failure.message += `\n${diagnosis}`;
322
+ throw failure;
323
+ }
324
+ let ready;
325
+ if (options.wait) {
326
+ const timeoutSeconds = options.waitTimeoutSeconds ?? DEFAULT_WAIT_SECONDS;
327
+ const state = await waitForStack(engine, wt.project, {
328
+ timeoutMs: timeoutSeconds * 1000,
329
+ signal: io.signal,
330
+ onProgress: (message) => reporter.info(message),
331
+ list: () => listContainers(engine),
332
+ only: scope,
333
+ // A selected service that has no container (removed meanwhile) is not "ready".
334
+ expected: services ? expectedServices(view.composeFile.services, services, ctx.sharedServices) : undefined,
335
+ });
336
+ if (!state.ready) {
337
+ const troubled = [...state.failed, ...state.pending];
338
+ const logs = await serviceLogTails(engine, wt.project, troubled.map((s) => s.service), call);
339
+ throw new Error(`Worktree ${wt.index} (${wt.branch}) started, but is not ready` +
340
+ (state.timedOut ? ` after ${timeoutSeconds}s` : "") +
341
+ `: ${troubled.map(describeService).join(", ") || "no containers"}.` +
342
+ (logs ? `\n${logs}` : ""));
343
+ }
344
+ ready = true;
345
+ reporter.success(`Worktree ${wt.index} is ready`);
346
+ }
347
+ else {
348
+ reporter.success(`Worktree ${wt.index} started`);
102
349
  }
103
- reporter.success(`Worktree ${wt.index} started`);
104
350
  started.push({
105
351
  index: wt.index,
106
352
  branch: wt.branch,
107
353
  path: wt.path,
108
354
  project: wt.project,
109
355
  ports: portsByLabel(allocations),
356
+ ...(services ? { services } : {}),
357
+ ...(ready !== undefined ? { ready } : {}),
110
358
  });
111
359
  }
112
360
  return { started };
@@ -2,8 +2,10 @@ import type { WorktreeSelector } from "../selectors.js";
2
2
  import type { Reporter } from "../utils/log.js";
3
3
  import type { CoreIo } from "./types.js";
4
4
  export interface StopOptions {
5
- /** Worktrees to stop (index, branch, dir name, path, "."); empty = all. */
5
+ /** Worktrees to stop (index, branch, dir name, path, "."); none: the current one, or all from the main checkout. */
6
6
  worktrees?: WorktreeSelector[];
7
+ /** Every worktree, even when run from inside one. */
8
+ all?: boolean;
7
9
  /** Skip context warnings (restart reports them once, from start). */
8
10
  quiet?: boolean;
9
11
  }
package/dist/core/stop.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { buildContext } from "../context.js";
2
- import { selectWorktrees } from "../selectors.js";
2
+ import { implicitScopeNote, selectScope } from "../selectors.js";
3
3
  import { composeEnv, composeRun, prepareStack, reportContextWarnings, throwIfAborted } from "./compose.js";
4
4
  /**
5
5
  * `compose stop` for each selected worktree; one failure does not stop the
@@ -21,7 +21,10 @@ export async function stopWorktrees(options, reporter, io) {
21
21
  reporter.warn("No worktrees to stop.");
22
22
  return result;
23
23
  }
24
- const targets = selectWorktrees(ctx.worktrees, options.worktrees, ctx.cwd);
24
+ const scope = selectScope(ctx.worktrees, options.worktrees, ctx.cwd, options.all);
25
+ if (scope.implicit && !options.quiet)
26
+ reporter.info(implicitScopeNote(scope.implicit));
27
+ const targets = scope.targets;
25
28
  const engine = ctx.getEngine();
26
29
  for (const wt of targets) {
27
30
  throwIfAborted(io);
@@ -31,7 +34,7 @@ export async function stopWorktrees(options, reporter, io) {
31
34
  try {
32
35
  // The compose files the stack was started with (runtime override included).
33
36
  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);
37
+ env = composeEnv(wt.project, stack.allocations, stack.composeFile, ctx.repo.commonDir, ctx.customComposeRoots);
35
38
  }
36
39
  catch {
37
40
  env = undefined;
@@ -31,9 +31,12 @@ export declare function anonymousVolumes(engine: ComposeEngine, project: string)
31
31
  * podman-compose always need a compose file, so that retry cannot help.
32
32
  * Anonymous volumes the containers mounted are removed afterwards.
33
33
  */
34
- export declare function teardownStack(ctx: WtcContext, engine: ComposeEngine, target: TeardownTarget, io: CoreIo): Promise<{
34
+ export declare function teardownStack(ctx: WtcContext, engine: ComposeEngine, target: TeardownTarget, io: CoreIo, opts?: {
35
+ keepVolumes?: boolean;
36
+ }): Promise<{
35
37
  ok: boolean;
36
- error?: string;
38
+ error?: string; /** Networks of the stack that are still there: something else holds them. */
39
+ leftNetworks?: string[];
37
40
  }>;
38
41
  /**
39
42
  * Re-check an orphan right before tearing it down, with a fresh `git
@@ -10,7 +10,8 @@ import { field, labelsOf, parseJsonListing, parsePsContainers, PROJECT_LABELS, }
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, prepareStack } from "./compose.js";
13
+ import { composeEnv, composeRun, mainStackDirs, prepareStack, stackView, worktreeProjects } from "./compose.js";
14
+ import { linkSharedServices, stackNetworkNames, unlinkSharedServices } from "./shared.js";
14
15
  /** Anonymous volumes are named by a 64-hex id; named volumes never are. */
15
16
  const ANONYMOUS_VOLUME = /^[0-9a-f]{64}$/;
16
17
  /**
@@ -64,28 +65,32 @@ export function anonymousVolumes(engine, project) {
64
65
  * podman-compose always need a compose file, so that retry cannot help.
65
66
  * Anonymous volumes the containers mounted are removed afterwards.
66
67
  */
67
- export async function teardownStack(ctx, engine, target, io) {
68
+ export async function teardownStack(ctx, engine, target, io, opts = {}) {
68
69
  const cwd = fs.existsSync(target.path) ? target.path : ctx.repoRoot;
70
+ // The main checkout's shared containers may sit on this stack's networks (also after
71
+ // `shared` left the config): let go of them first, or the networks cannot be removed.
72
+ const unlinked = unlinkSharedServices(engine, target.project, mainStackDirs(ctx));
73
+ const volumes = opts.keepVolumes ? [] : ["-v"];
69
74
  let env;
70
75
  try {
71
76
  // The compose files the stack was started with (runtime override included).
72
77
  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);
78
+ env = composeEnv(target.project, stack.allocations, stack.composeFile, ctx.repo.commonDir, ctx.customComposeRoots);
74
79
  }
75
80
  catch {
76
81
  env = undefined;
77
82
  }
78
83
  // The label-only retry must not load any compose file, wtc's or an inherited list.
79
84
  const labelsOnlyEnv = { ...env, [COMPOSE_FILE_VAR]: undefined };
80
- const anonymous = anonymousVolumes(engine, target.project);
85
+ const anonymous = opts.keepVolumes ? [] : anonymousVolumes(engine, target.project);
81
86
  const call = { live: io.live, signal: io.signal, onLine: io.onOutput };
82
87
  const attempts = [
83
- { args: ["down", "-v", "--remove-orphans"], dir: () => cwd, env },
84
- { args: ["down", "-v"], dir: () => cwd, env },
88
+ { args: ["down", ...volumes, "--remove-orphans"], dir: () => cwd, env },
89
+ { args: ["down", ...volumes], dir: () => cwd, env },
85
90
  ];
86
91
  if (isComposePlugin(engine)) {
87
92
  attempts.push({
88
- args: ["down", "-v", "--remove-orphans"],
93
+ args: ["down", ...volumes, "--remove-orphans"],
89
94
  dir: () => fs.mkdtempSync(path.join(os.tmpdir(), "wtc-down-")),
90
95
  env: labelsOnlyEnv,
91
96
  });
@@ -101,7 +106,10 @@ export async function teardownStack(ctx, engine, target, io) {
101
106
  const [file, args] = cliCall(engine, "volume", "rm", volume);
102
107
  runSafe(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS });
103
108
  }
104
- return { ok: true };
109
+ // Compose leaves a network a container of another project still uses, and
110
+ // calls that a success: wtc does not disconnect what it did not connect.
111
+ const leftNetworks = [...stackNetworkNames(engine, target.project).values()];
112
+ return { ok: true, ...(leftNetworks.length > 0 ? { leftNetworks } : {}) };
105
113
  }
106
114
  catch (err) {
107
115
  firstError ??= err;
@@ -111,6 +119,23 @@ export async function teardownStack(ctx, engine, target, io) {
111
119
  fs.rmSync(dir, { recursive: true, force: true });
112
120
  }
113
121
  }
122
+ // The stack is still there, but no longer reaches its shared services: connect them again.
123
+ if (unlinked > 0 && ctx.sharedServices.size > 0) {
124
+ try {
125
+ linkSharedServices({
126
+ engine,
127
+ project: target.project,
128
+ composeFile: stackView(ctx, cwd).composeFile,
129
+ shared: ctx.sharedServices,
130
+ mainDirs: mainStackDirs(ctx),
131
+ mainProjectName: ctx.composeFile.projectName,
132
+ worktreeProjects: worktreeProjects(ctx),
133
+ });
134
+ }
135
+ catch {
136
+ // Best effort: the next `wtc start` connects them.
137
+ }
138
+ }
114
139
  return {
115
140
  ok: false,
116
141
  error: firstError instanceof Error ? firstError.message : String(firstError ?? "cancelled"),
@@ -12,4 +12,6 @@ export interface CoreIo {
12
12
  signal?: AbortSignal;
13
13
  /** Receives captured compose output lines (MCP progress), when not `live`. */
14
14
  onOutput?: (line: string) => void;
15
+ /** Answers "is this host port taken?" (defaults to probing the host; tests replace it). */
16
+ portProbe?: (port: number) => Promise<boolean>;
15
17
  }
@@ -1,8 +1,9 @@
1
1
  /** Root compose filenames; wtc overwrites these in every worktree. */
2
2
  export declare const PROMOTE_EXCLUDES: Set<string>;
3
3
  /**
4
- * Local env files are excluded from promote — wtc rewrites them with
5
- * per-worktree ports: `.env`, `.env.development`, `.env.local`, …
4
+ * Local env files: `.env`, `.env.development`, `.env.local`, … (not the
5
+ * templates). An untracked one is excluded from promote — wtc fills it
6
+ * with per-worktree ports.
6
7
  */
7
8
  export declare function isEnvFile(file: string): boolean;
8
9
  /** Split NUL-terminated git output (`-z`) into paths. */
@@ -24,8 +25,15 @@ export declare function getTargetChangedFiles(targetRoot: string, mergeBase: str
24
25
  * names intact (otherwise `core.quotePath` turns `café.txt` into a quoted
25
26
  * escape that matches no file); `--no-renames` reports a rename as delete +
26
27
  * add so the old path is removed from the target too.
28
+ *
29
+ * Left out is what wtc itself put into the worktree, which is per-worktree
30
+ * and never the branch's work: untracked env files and untracked copies of
31
+ * the compose files (`excludes`), and every file in `managed` (the env
32
+ * files wtc recorded writing). A compose or env file the branch tracks is
33
+ * the branch's own — wtc never changes those — so its changes promote like
34
+ * any other file's.
27
35
  */
28
- export declare function getChangedFiles(targetRoot: string, wtPath: string, excludes?: Set<string>, mergeBase?: string): string[];
36
+ export declare function getChangedFiles(targetRoot: string, wtPath: string, excludes?: Set<string>, mergeBase?: string, managed?: ReadonlySet<string>): string[];
29
37
  /**
30
38
  * Paths in the target checkout that promote must not overwrite: tracked
31
39
  * changes (staged or unstaged) AND untracked files — an untracked file in
@@ -18,8 +18,9 @@ const ENV_TEMPLATES = new Set([
18
18
  ".env.defaults",
19
19
  ]);
20
20
  /**
21
- * Local env files are excluded from promote — wtc rewrites them with
22
- * per-worktree ports: `.env`, `.env.development`, `.env.local`, …
21
+ * Local env files: `.env`, `.env.development`, `.env.local`, … (not the
22
+ * templates). An untracked one is excluded from promote — wtc fills it
23
+ * with per-worktree ports.
23
24
  */
24
25
  export function isEnvFile(file) {
25
26
  const base = path.posix.basename(file);
@@ -65,12 +66,25 @@ export function getTargetChangedFiles(targetRoot, mergeBase) {
65
66
  * names intact (otherwise `core.quotePath` turns `café.txt` into a quoted
66
67
  * escape that matches no file); `--no-renames` reports a rename as delete +
67
68
  * add so the old path is removed from the target too.
69
+ *
70
+ * Left out is what wtc itself put into the worktree, which is per-worktree
71
+ * and never the branch's work: untracked env files and untracked copies of
72
+ * the compose files (`excludes`), and every file in `managed` (the env
73
+ * files wtc recorded writing). A compose or env file the branch tracks is
74
+ * the branch's own — wtc never changes those — so its changes promote like
75
+ * any other file's.
68
76
  */
69
- export function getChangedFiles(targetRoot, wtPath, excludes = PROMOTE_EXCLUDES, mergeBase = getMergeBase(targetRoot, wtPath)) {
77
+ export function getChangedFiles(targetRoot, wtPath, excludes = PROMOTE_EXCLUDES, mergeBase = getMergeBase(targetRoot, wtPath), managed = new Set()) {
70
78
  const changed = gitPaths(wtPath, ["diff", "--name-only", "-z", "--no-renames", mergeBase, "--"]);
71
- const untracked = gitPaths(wtPath, ["ls-files", "--others", "--exclude-standard", "-z"]);
79
+ const untracked = new Set(gitPaths(wtPath, ["ls-files", "--others", "--exclude-standard", "-z"]));
72
80
  const unique = [...new Set([...changed, ...untracked])];
73
- return unique.filter((f) => !excludes.has(f) && !isEnvFile(f));
81
+ return unique.filter((f) => {
82
+ if (managed.has(f))
83
+ return false;
84
+ if (!untracked.has(f))
85
+ return true;
86
+ return !excludes.has(f) && !isEnvFile(f);
87
+ });
74
88
  }
75
89
  /**
76
90
  * Paths in the target checkout that promote must not overwrite: tracked