worktree-compose 0.2.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +501 -143
  2. package/SKILL.md +113 -0
  3. package/dist/cli.js +94 -33
  4. package/dist/commands/clean.d.ts +2 -1
  5. package/dist/commands/clean.js +8 -48
  6. package/dist/commands/doctor.d.ts +3 -0
  7. package/dist/commands/doctor.js +30 -0
  8. package/dist/commands/list.d.ts +4 -1
  9. package/dist/commands/list.js +62 -44
  10. package/dist/commands/promote.d.ts +3 -1
  11. package/dist/commands/promote.js +4 -34
  12. package/dist/commands/prune.d.ts +2 -0
  13. package/dist/commands/prune.js +7 -0
  14. package/dist/commands/restart.d.ts +2 -1
  15. package/dist/commands/restart.js +11 -5
  16. package/dist/commands/skill.d.ts +4 -0
  17. package/dist/commands/skill.js +10 -0
  18. package/dist/commands/start.d.ts +2 -1
  19. package/dist/commands/start.js +7 -34
  20. package/dist/commands/stop.d.ts +1 -1
  21. package/dist/commands/stop.js +6 -23
  22. package/dist/compose/detect.d.ts +1 -2
  23. package/dist/compose/detect.js +1 -10
  24. package/dist/compose/engine.d.ts +61 -0
  25. package/dist/compose/engine.js +129 -0
  26. package/dist/compose/isolation.d.ts +26 -0
  27. package/dist/compose/isolation.js +91 -0
  28. package/dist/compose/override.d.ts +152 -0
  29. package/dist/compose/override.js +542 -0
  30. package/dist/compose/parse.d.ts +12 -0
  31. package/dist/compose/parse.js +199 -29
  32. package/dist/compose/status.d.ts +84 -0
  33. package/dist/compose/status.js +227 -0
  34. package/dist/compose/types.d.ts +43 -0
  35. package/dist/config.d.ts +31 -0
  36. package/dist/config.js +23 -6
  37. package/dist/context.d.ts +104 -3
  38. package/dist/context.js +299 -45
  39. package/dist/core/clean.d.ts +91 -0
  40. package/dist/core/clean.js +347 -0
  41. package/dist/core/compose.d.ts +92 -0
  42. package/dist/core/compose.js +195 -0
  43. package/dist/core/doctor.d.ts +29 -0
  44. package/dist/core/doctor.js +342 -0
  45. package/dist/core/list.d.ts +46 -0
  46. package/dist/core/list.js +101 -0
  47. package/dist/core/promote.d.ts +40 -0
  48. package/dist/core/promote.js +117 -0
  49. package/dist/core/prune.d.ts +32 -0
  50. package/dist/core/prune.js +79 -0
  51. package/dist/core/restart.d.ts +14 -0
  52. package/dist/core/restart.js +18 -0
  53. package/dist/core/start.d.ts +33 -0
  54. package/dist/core/start.js +113 -0
  55. package/dist/core/stop.d.ts +32 -0
  56. package/dist/core/stop.js +58 -0
  57. package/dist/core/teardown.d.ts +123 -0
  58. package/dist/core/teardown.js +305 -0
  59. package/dist/core/types.d.ts +15 -0
  60. package/dist/core/types.js +1 -0
  61. package/dist/git/promote.d.ts +49 -2
  62. package/dist/git/promote.js +160 -38
  63. package/dist/git/repo.d.ts +72 -0
  64. package/dist/git/repo.js +167 -0
  65. package/dist/git/status.d.ts +8 -0
  66. package/dist/git/status.js +25 -0
  67. package/dist/git/worktree.d.ts +63 -3
  68. package/dist/git/worktree.js +173 -29
  69. package/dist/mcp/server.d.ts +2 -0
  70. package/dist/mcp/server.js +230 -115
  71. package/dist/ports/allocate.d.ts +39 -5
  72. package/dist/ports/allocate.js +96 -16
  73. package/dist/ports/extract.d.ts +12 -0
  74. package/dist/ports/extract.js +48 -4
  75. package/dist/ports/types.d.ts +12 -1
  76. package/dist/selectors.d.ts +10 -0
  77. package/dist/selectors.js +106 -0
  78. package/dist/skill.d.ts +13 -0
  79. package/dist/skill.js +28 -0
  80. package/dist/state/registry.d.ts +194 -0
  81. package/dist/state/registry.js +595 -0
  82. package/dist/sync/env.d.ts +93 -2
  83. package/dist/sync/env.js +169 -32
  84. package/dist/sync/files.d.ts +15 -1
  85. package/dist/sync/files.js +126 -38
  86. package/dist/utils/exec.d.ts +69 -4
  87. package/dist/utils/exec.js +221 -15
  88. package/dist/utils/log.d.ts +37 -0
  89. package/dist/utils/log.js +68 -4
  90. package/dist/utils/paths.d.ts +61 -0
  91. package/dist/utils/paths.js +163 -0
  92. package/dist/utils/sanitize.d.ts +7 -0
  93. package/dist/utils/sanitize.js +12 -0
  94. package/dist/version.d.ts +1 -0
  95. package/dist/version.js +3 -0
  96. package/dist/workspaces/resolve.d.ts +21 -0
  97. package/dist/workspaces/resolve.js +235 -0
  98. package/package.json +20 -16
  99. package/wtc.schema.json +62 -0
@@ -0,0 +1,542 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { Document, parseDocument } from "yaml";
5
+ import { ENGINE_PROBE_TIMEOUT_MS, runSafe } from "../utils/exec.js";
6
+ import { allocatePort } from "../ports/allocate.js";
7
+ import { portSegments } from "../ports/extract.js";
8
+ import { stateDir } from "../state/registry.js";
9
+ import { COMPOSE_FILE_VAR } from "../sync/env.js";
10
+ import { COMPOSE_FILENAMES } from "./detect.js";
11
+ import { composeArgs, composeBin } from "./engine.js";
12
+ import { isProjectScopedName, parseContainerRefs, portEntryString } from "./parse.js";
13
+ /**
14
+ * Runtime remapping. Two compose settings make every worktree stack collide
15
+ * with the others: a hardcoded host port (`8080:80`) and a fixed
16
+ * `container_name`. Instead of asking for the compose file to be edited, wtc
17
+ * writes a compose override for each worktree stack that replaces the
18
+ * service's `ports` (`!override`, hardcoded host ports swapped for the
19
+ * worktree's allocated ones) and drops `container_name` (`!reset`, keeping
20
+ * the old name as a network alias), and adds it to `COMPOSE_FILE` for every
21
+ * compose call on that stack — and in the worktree's root env file, so plain
22
+ * `docker compose` there agrees. The compose file itself is never changed.
23
+ *
24
+ * A plain override cannot do this: compose merges `ports` lists, so the
25
+ * hardcoded port would still be published. The `!override`/`!reset` tags
26
+ * need Docker Compose 2.24.4+ (and are partial or missing in other
27
+ * engines), so wtc first checks that the engine merges them as expected,
28
+ * and otherwise keeps warning as before.
29
+ */
30
+ /** Override files compose loads next to the compose file, in its order of preference. */
31
+ export const USER_OVERRIDE_FILENAMES = [
32
+ "compose.override.yml",
33
+ "compose.override.yaml",
34
+ "docker-compose.override.yml",
35
+ "docker-compose.override.yaml",
36
+ ];
37
+ export function remapIsEmpty(t) {
38
+ return t.ports.length === 0 && t.containerNames.length === 0;
39
+ }
40
+ /** Whether a service's port entries use `${…}` interpolation anywhere. */
41
+ function portsUseVariables(svc) {
42
+ return (svc.portEntries ?? svc.ports).some((e) => (JSON.stringify(e) ?? "").includes("$"));
43
+ }
44
+ /** Whether a hardcoded host port can move at all: allocated ports end at 65535. */
45
+ function canMove(port) {
46
+ try {
47
+ allocatePort(port, 1, 1);
48
+ return true;
49
+ }
50
+ catch {
51
+ return false;
52
+ }
53
+ }
54
+ /**
55
+ * Settings wtc could remap: hardcoded host ports (not ranges) and fixed
56
+ * container names, plus why some are left alone:
57
+ * - a service that uses `extends` may inherit ports wtc cannot see, which
58
+ * a replaced list would drop;
59
+ * - a service from an included file whose ports use variables: compose
60
+ * fills those in from that file's own env (its directory's `.env`), but
61
+ * an override is interpolated with the main project's;
62
+ * - a port too high to move (above 65435);
63
+ * - a container name another service joins by name (`network_mode:
64
+ * container:<name>`, `volumes_from`, `ipc`, `pid`): an alias cannot stand
65
+ * in for a container identity.
66
+ */
67
+ export function remapCandidates(composeFile, mappings) {
68
+ const root = composeFile.sourceFiles[0];
69
+ const skipped = [];
70
+ const keep = new Set();
71
+ for (const svc of composeFile.services) {
72
+ if (!mappings.some((m) => m.serviceName === svc.name && m.envVar === null && !m.range))
73
+ continue;
74
+ if (svc.extends) {
75
+ keep.add(svc.name);
76
+ skipped.push(`Service "${svc.name}" uses extends, which may bring in ports wtc cannot see, so wtc does not remap its hardcoded ports.`);
77
+ }
78
+ else if (root !== undefined && svc.sourcePath !== root && portsUseVariables(svc)) {
79
+ keep.add(svc.name);
80
+ skipped.push(`Service "${svc.name}" comes from an included file (${path.basename(svc.sourcePath)}) whose port variables compose fills in from that file's own env, so wtc does not remap its hardcoded ports.`);
81
+ }
82
+ }
83
+ const stuck = new Set();
84
+ const ports = mappings.filter((m) => {
85
+ if (m.envVar !== null || m.range || keep.has(m.serviceName))
86
+ return false;
87
+ if (canMove(m.defaultPort))
88
+ return true;
89
+ if (!stuck.has(m.defaultPort)) {
90
+ stuck.add(m.defaultPort);
91
+ skipped.push(`Service "${m.serviceName}": hardcoded host port ${m.defaultPort} is too high to move (ports end at 65535), so wtc leaves it.`);
92
+ }
93
+ return false;
94
+ });
95
+ const joinedBy = new Map();
96
+ for (const s of composeFile.services) {
97
+ for (const ref of s.containerRefs ?? [])
98
+ if (!joinedBy.has(ref))
99
+ joinedBy.set(ref, s.name);
100
+ }
101
+ const containerNames = composeFile.services.flatMap((s) => {
102
+ if (!s.containerName || isProjectScopedName(s.containerName))
103
+ return [];
104
+ const by = joinedBy.get(s.containerName);
105
+ if (by) {
106
+ skipped.push(`Service "${s.name}": service "${by}" joins container:${s.containerName} by name, so wtc does not drop its container_name.`);
107
+ return [];
108
+ }
109
+ return [{ service: s.name, name: s.containerName }];
110
+ });
111
+ return { targets: { ports, containerNames }, skipped };
112
+ }
113
+ /** The compose override file compose would load from `dir` by itself, or null. */
114
+ export function findUserOverride(dir) {
115
+ for (const name of USER_OVERRIDE_FILENAMES) {
116
+ const file = path.join(dir, name);
117
+ if (fs.existsSync(file))
118
+ return file;
119
+ }
120
+ return null;
121
+ }
122
+ /**
123
+ * Parse YAML that may use compose's custom tags (`!reset`, `!override`):
124
+ * unknown tags are fine (no warning printed), merge keys (`<<: *anchor`)
125
+ * are resolved as compose resolves them, syntax errors throw.
126
+ */
127
+ function parseComposeYaml(text) {
128
+ const doc = parseDocument(text, { uniqueKeys: false, merge: true });
129
+ if (doc.errors.length > 0)
130
+ throw doc.errors[0];
131
+ return doc.toJS();
132
+ }
133
+ /** Each service's definition in a compose file, or null when it cannot be read. */
134
+ function serviceDefs(file) {
135
+ let doc;
136
+ try {
137
+ doc = parseComposeYaml(fs.readFileSync(file, "utf-8"));
138
+ }
139
+ catch {
140
+ return null;
141
+ }
142
+ const out = new Map();
143
+ const services = doc && typeof doc === "object" ? doc.services : null;
144
+ if (services && typeof services === "object") {
145
+ for (const [name, svc] of Object.entries(services)) {
146
+ if (svc && typeof svc === "object")
147
+ out.set(name, svc);
148
+ }
149
+ }
150
+ return out;
151
+ }
152
+ /**
153
+ * Leave alone what the user's own compose override in `dir` also sets for
154
+ * a service (`ports` or `extends`, `container_name`): replacing it would
155
+ * discard theirs. A container name one of its services joins by name
156
+ * (`network_mode: container:<name>`, …) is kept too. Where it sets the
157
+ * service's networks, the old container name gets no alias (theirs could
158
+ * be `network_mode`). Returns what remains, with a warning for each
159
+ * setting left alone.
160
+ */
161
+ export function withoutUserOverride(targets, dir) {
162
+ const file = findUserOverride(dir);
163
+ if (!file || remapIsEmpty(targets))
164
+ return { targets, warnings: [] };
165
+ const name = path.basename(file);
166
+ const defs = serviceDefs(file);
167
+ if (!defs) {
168
+ return {
169
+ targets: { ports: [], containerNames: [] },
170
+ warnings: [`Could not read ${name}, so wtc does not remap hardcoded ports or container_name at runtime.`],
171
+ };
172
+ }
173
+ const sets = (service, key) => defs.get(service)?.[key] !== undefined;
174
+ const joinedBy = new Map();
175
+ for (const [service, def] of defs) {
176
+ for (const ref of parseContainerRefs(def))
177
+ if (!joinedBy.has(ref))
178
+ joinedBy.set(ref, service);
179
+ }
180
+ const warnings = [];
181
+ const skippedPorts = new Set(targets.ports
182
+ .filter((m) => sets(m.serviceName, "ports") || sets(m.serviceName, "extends"))
183
+ .map((m) => m.serviceName));
184
+ for (const service of skippedPorts) {
185
+ warnings.push(`Service "${service}": ${name} also sets its ports, so wtc does not remap its hardcoded ports.`);
186
+ }
187
+ const containerNames = targets.containerNames.flatMap((c) => {
188
+ if (sets(c.service, "container_name")) {
189
+ warnings.push(`Service "${c.service}": ${name} also sets container_name, so wtc does not drop it.`);
190
+ return [];
191
+ }
192
+ const by = joinedBy.get(c.name);
193
+ if (by) {
194
+ warnings.push(`Service "${c.service}": service "${by}" in ${name} joins container:${c.name} by name, so wtc does not drop its container_name.`);
195
+ return [];
196
+ }
197
+ return sets(c.service, "networks") || sets(c.service, "network_mode") || sets(c.service, "extends")
198
+ ? [{ ...c, noAlias: true }]
199
+ : [c];
200
+ });
201
+ return {
202
+ targets: { ports: targets.ports.filter((m) => !skippedPorts.has(m.serviceName)), containerNames },
203
+ warnings,
204
+ };
205
+ }
206
+ /** The separator compose splits `COMPOSE_FILE` on (wtc's calls and the env files it writes). */
207
+ export function composePathSeparator() {
208
+ return process.env.COMPOSE_PATH_SEPARATOR || path.delimiter;
209
+ }
210
+ /** A `COMPOSE_FILE` value for `files`, or null when a path contains the separator. */
211
+ export function composeFileValue(files) {
212
+ const sep = composePathSeparator();
213
+ return files.some((f) => f.includes(sep)) ? null : files.join(sep);
214
+ }
215
+ /**
216
+ * The value an env file assigns to `key`: its last assignment, in either
217
+ * form compose's dotenv parser accepts (`KEY=value`, `KEY: value`),
218
+ * unquoted. Null when the file or the key is missing.
219
+ */
220
+ export function envFileValue(file, key) {
221
+ if (!file)
222
+ return null;
223
+ let text;
224
+ try {
225
+ text = fs.readFileSync(file, "utf-8");
226
+ }
227
+ catch {
228
+ return null;
229
+ }
230
+ let value = null;
231
+ for (const m of text.matchAll(new RegExp(`^[ \\t]*(?:export[ \\t]+)?${key}[ \\t]*[=:](.*)$`, "gm"))) {
232
+ value = m[1].trim().replace(/^(['"])(.*)\1$/, "$2");
233
+ }
234
+ return value;
235
+ }
236
+ /** The `COMPOSE_FILE` an env file sets, or null. */
237
+ export function envFileComposeFile(file) {
238
+ return envFileValue(file, COMPOSE_FILE_VAR);
239
+ }
240
+ /** Why an env file's `COMPOSE_PATH_SEPARATOR` would split wtc's list differently, or null. */
241
+ function separatorConflict(file) {
242
+ const sep = envFileValue(file, "COMPOSE_PATH_SEPARATOR");
243
+ return sep && sep !== composePathSeparator()
244
+ ? `${path.basename(file)} sets COMPOSE_PATH_SEPARATOR, which would split wtc's COMPOSE_FILE differently`
245
+ : null;
246
+ }
247
+ /** Where wtc keeps a stack's override: inside the git directory, never committed. */
248
+ export function overridePath(commonDir, project) {
249
+ return path.join(stateDir(commonDir), "compose", `${project}.yaml`);
250
+ }
251
+ /**
252
+ * True when a `COMPOSE_FILE` value is exactly a list wtc writes — the
253
+ * compose file, then the compose override compose itself would pick in
254
+ * that directory if there is one, then one of wtc's overrides: the line
255
+ * wtc wrote into a worktree's env file, exported into the shell by a tool
256
+ * that loads `.env` (direnv's `dotenv`, mise, autoenv). That is not a file
257
+ * list of the user's, so it must not switch remapping off. Any other list
258
+ * (a file added, another override picked) is the user's.
259
+ */
260
+ export function isWtcComposeFile(value, commonDir) {
261
+ const dir = path.dirname(overridePath(commonDir, "_"));
262
+ const files = value.split(composePathSeparator()).map((f) => f.trim()).filter(Boolean);
263
+ if (files.length < 2 || files.length > 3)
264
+ return false;
265
+ if (path.dirname(path.resolve(files[files.length - 1])) !== dir)
266
+ return false;
267
+ if (!COMPOSE_FILENAMES.includes(path.basename(files[0])))
268
+ return false;
269
+ const userOverride = findUserOverride(path.dirname(path.resolve(files[0])));
270
+ return files.length === 2
271
+ ? userOverride === null
272
+ : userOverride !== null && path.resolve(files[1]) === userOverride;
273
+ }
274
+ /**
275
+ * Whether the inherited `COMPOSE_FILE` names `file`: a list the shell still
276
+ * holds (direnv, or one the user extended) would break if it were deleted.
277
+ */
278
+ export function inheritedComposeFileNames(file) {
279
+ const value = process.env[COMPOSE_FILE_VAR];
280
+ return !!value && value.split(composePathSeparator()).some((f) => f.trim() && path.resolve(f.trim()) === file);
281
+ }
282
+ /** A `COMPOSE_FILE` the user set (not one wtc wrote), from a value. */
283
+ export function isUserComposeFile(value, commonDir) {
284
+ return !!value?.trim() && !isWtcComposeFile(value, commonDir);
285
+ }
286
+ export function writeOverride(file, content) {
287
+ fs.mkdirSync(path.dirname(file), { recursive: true });
288
+ const tmp = `${file}.${process.pid}.tmp`;
289
+ fs.writeFileSync(tmp, content, "utf-8");
290
+ fs.renameSync(tmp, file);
291
+ }
292
+ export function removeOverride(file) {
293
+ try {
294
+ fs.rmSync(file, { force: true });
295
+ }
296
+ catch {
297
+ // Best effort: a leftover file is only read through COMPOSE_FILE.
298
+ }
299
+ }
300
+ /** `entry` with its hardcoded host port replaced by `port` (same IP, protocol, and fields). */
301
+ function withHostPort(entry, port) {
302
+ if (typeof entry === "object" && entry !== null) {
303
+ return { ...entry, published: String(port) };
304
+ }
305
+ const s = String(entry);
306
+ const protocol = /\/(tcp|udp|sctp)$/i.exec(s)?.[0] ?? "";
307
+ const segments = portSegments(s);
308
+ if (segments.length === 2)
309
+ return `${port}:${segments[1]}${protocol}`;
310
+ if (segments.length === 3)
311
+ return `${segments[0]}:${port}:${segments[2]}${protocol}`;
312
+ return entry;
313
+ }
314
+ /**
315
+ * Networks on which a service whose container_name is dropped keeps the old
316
+ * name as an alias, so containers that reach it by that name still do. Only
317
+ * the stack's own networks: on one shared by every stack (fixed `name:`,
318
+ * `external`) the alias would answer for several stacks at once. What a
319
+ * service inherits through `extends` counts: a `network_mode` there leaves
320
+ * no networks (compose rejects `networks` next to it), and its `networks`
321
+ * add to the service's. When `extends` points into another file, wtc
322
+ * cannot see what it brings, so no alias.
323
+ */
324
+ function aliasNetworks(composeFile, svc, name) {
325
+ // A `${…}` name would be interpolated with the main project's env, not the name's own.
326
+ if (name.includes("$"))
327
+ return [];
328
+ const byName = new Map(composeFile.services.map((s) => [s.name, s]));
329
+ const networks = new Set();
330
+ const seen = new Set();
331
+ for (let s = svc; s;) {
332
+ if (seen.has(s.name) || s.networkMode)
333
+ return [];
334
+ seen.add(s.name);
335
+ for (const n of s.networks ?? [])
336
+ networks.add(n);
337
+ if (!s.extendsFrom) {
338
+ if (s.extends)
339
+ return []; // an `extends` form wtc does not read
340
+ break;
341
+ }
342
+ if (s.extendsFrom.file)
343
+ return [];
344
+ s = byName.get(s.extendsFrom.service);
345
+ if (!s)
346
+ return [];
347
+ }
348
+ const shared = new Set(composeFile.sharedNetworks.map((n) => n.key));
349
+ return (networks.size > 0 ? [...networks] : ["default"]).filter((n) => !shared.has(n));
350
+ }
351
+ /**
352
+ * The override YAML for one stack. A service whose hardcoded ports are
353
+ * remapped gets its whole `ports` list (`!override` replaces it): every
354
+ * entry as written, except the remapped host ports. A service whose
355
+ * container_name is dropped (`!reset`) keeps the old name as an alias on
356
+ * its own networks. Strings are quoted, so YAML 1.1 parsers never read
357
+ * `2222:22` as a base-60 number.
358
+ */
359
+ export function renderOverride(project, composeFile, targets, allocations) {
360
+ const byDefault = new Map(allocations.map((a) => [a.defaultPort, a.port]));
361
+ const remapped = new Map();
362
+ for (const m of targets.ports) {
363
+ const port = byDefault.get(m.defaultPort);
364
+ if (port === undefined)
365
+ continue;
366
+ const forService = remapped.get(m.serviceName) ?? new Map();
367
+ forService.set(m.raw, port);
368
+ remapped.set(m.serviceName, forService);
369
+ }
370
+ const reset = new Map(targets.containerNames.map((c) => [c.service, c]));
371
+ const out = {};
372
+ for (const svc of composeFile.services) {
373
+ const ports = remapped.get(svc.name);
374
+ const name = reset.get(svc.name);
375
+ if (!ports && !name)
376
+ continue;
377
+ const entry = {};
378
+ if (ports) {
379
+ entry.ports = (svc.portEntries ?? svc.ports).map((e) => {
380
+ const raw = portEntryString(e);
381
+ const port = raw === null ? undefined : ports.get(raw);
382
+ return port === undefined ? e : withHostPort(e, port);
383
+ });
384
+ }
385
+ if (name) {
386
+ entry.container_name = null;
387
+ const networks = name.noAlias ? [] : aliasNetworks(composeFile, svc, name.name);
388
+ if (networks.length > 0) {
389
+ entry.networks = Object.fromEntries(networks.map((n) => [n, { aliases: [name.name] }]));
390
+ }
391
+ }
392
+ out[svc.name] = entry;
393
+ }
394
+ const doc = new Document({ services: out });
395
+ for (const [name, entry] of Object.entries(out)) {
396
+ if ("ports" in entry) {
397
+ const node = doc.getIn(["services", name, "ports"], true);
398
+ if (node)
399
+ node.tag = "!override";
400
+ }
401
+ if ("container_name" in entry) {
402
+ const node = doc.getIn(["services", name, "container_name"], true);
403
+ if (node)
404
+ node.tag = "!reset";
405
+ }
406
+ }
407
+ doc.commentBefore =
408
+ ` Generated by wtc for ${project}; rewritten on every start, do not edit.\n` +
409
+ ` Remaps hardcoded host ports and drops fixed container names so this stack\n` +
410
+ ` runs next to the others. The compose file itself is not changed.`;
411
+ return doc.toString({ defaultStringType: "QUOTE_DOUBLE", defaultKeyType: "PLAIN", lineWidth: 0 });
412
+ }
413
+ const PROBE_COMPOSE = [
414
+ "services:",
415
+ " probe:",
416
+ " image: wtc-probe",
417
+ " container_name: wtc-probe",
418
+ " ports:",
419
+ ' - "1:1"',
420
+ "",
421
+ ].join("\n");
422
+ const PROBE_OVERRIDE = [
423
+ "services:",
424
+ " probe:",
425
+ " container_name: !reset null",
426
+ " ports: !override",
427
+ ' - "2:1"',
428
+ "",
429
+ ].join("\n");
430
+ /** True when `config` output shows the probe override applied: one port, published on 2, no container_name. */
431
+ export function probeApplied(stdout) {
432
+ let doc;
433
+ try {
434
+ doc = parseComposeYaml(stdout);
435
+ }
436
+ catch {
437
+ return false;
438
+ }
439
+ const services = doc && typeof doc === "object" ? doc.services : null;
440
+ const svc = services && typeof services === "object" ? services.probe : null;
441
+ if (!svc || typeof svc !== "object" || "container_name" in svc)
442
+ return false;
443
+ const ports = svc.ports;
444
+ if (!Array.isArray(ports) || ports.length !== 1)
445
+ return false;
446
+ const p = ports[0];
447
+ const published = typeof p === "object" && p !== null
448
+ ? p.published
449
+ : portSegments(String(p)).at(-2);
450
+ return String(published) === "2";
451
+ }
452
+ /** A failed probe is retried after this long (a long-lived MCP server must not stay off for good). */
453
+ const PROBE_RETRY_MS = 60_000;
454
+ const probeCache = new Map();
455
+ /** Forget cached probe results (tests). */
456
+ export function resetRemapProbeCache() {
457
+ probeCache.clear();
458
+ }
459
+ /**
460
+ * Whether the engine merges `!override` and `!reset` the way runtime
461
+ * remapping needs: `config` on a throwaway project in a temp directory,
462
+ * passed through `COMPOSE_FILE` exactly like the real override. It needs
463
+ * no daemon and touches no containers. Cached per process and engine (a
464
+ * failure for a minute).
465
+ */
466
+ export function engineSupportsRemap(engine) {
467
+ const key = engine.compose.join("\0");
468
+ const cached = probeCache.get(key);
469
+ if (cached && (cached.supported || Date.now() - cached.at < PROBE_RETRY_MS))
470
+ return cached.supported;
471
+ let supported = false;
472
+ let dir = null;
473
+ try {
474
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "wtc-remap-probe-"));
475
+ const base = path.join(dir, "compose.yaml");
476
+ const override = path.join(dir, "override.yaml");
477
+ fs.writeFileSync(base, PROBE_COMPOSE);
478
+ fs.writeFileSync(override, PROBE_OVERRIDE);
479
+ const files = composeFileValue([base, override]);
480
+ if (files !== null) {
481
+ const out = runSafe(composeBin(engine), composeArgs(engine, "wtc-remap-probe", "config"), {
482
+ cwd: dir,
483
+ env: { ...process.env, [COMPOSE_FILE_VAR]: files },
484
+ timeoutMs: ENGINE_PROBE_TIMEOUT_MS,
485
+ });
486
+ supported = out !== null && probeApplied(out);
487
+ }
488
+ }
489
+ catch {
490
+ supported = false;
491
+ }
492
+ finally {
493
+ if (dir)
494
+ fs.rmSync(dir, { recursive: true, force: true });
495
+ }
496
+ probeCache.set(key, { supported, at: Date.now() });
497
+ return supported;
498
+ }
499
+ /** Decide what to remap for this repository (see the module comment). */
500
+ export function decideRemap(inputs) {
501
+ const none = { targets: null, problem: null, warnings: [] };
502
+ const { targets: candidates, skipped } = remapCandidates(inputs.composeFile, inputs.mappings);
503
+ if (remapIsEmpty(candidates))
504
+ return { ...none, warnings: skipped };
505
+ // A COMPOSE_FILE of the user's lists the files compose loads; wtc's
506
+ // would replace it, dropping theirs.
507
+ const cannot = (why) => ({
508
+ ...none,
509
+ problem: `wtc cannot remap hardcoded ports or container_name at runtime: ${why}.`,
510
+ });
511
+ if (isUserComposeFile(process.env[COMPOSE_FILE_VAR], inputs.commonDir)) {
512
+ return cannot("COMPOSE_FILE is set in the environment, and wtc would replace it");
513
+ }
514
+ for (const file of new Set(inputs.envFiles)) {
515
+ if (isUserComposeFile(envFileComposeFile(file), inputs.commonDir)) {
516
+ return cannot(`${path.basename(file)} sets COMPOSE_FILE, and wtc would replace it`);
517
+ }
518
+ const conflict = separatorConflict(file);
519
+ if (conflict)
520
+ return cannot(conflict);
521
+ }
522
+ if (inputs.envOverrides && COMPOSE_FILE_VAR in inputs.envOverrides) {
523
+ return cannot("envOverrides sets COMPOSE_FILE, and wtc would replace it");
524
+ }
525
+ const separator = inputs.envOverrides?.COMPOSE_PATH_SEPARATOR;
526
+ if (separator !== undefined && separator !== composePathSeparator()) {
527
+ return cannot("envOverrides sets COMPOSE_PATH_SEPARATOR, which would split wtc's COMPOSE_FILE differently");
528
+ }
529
+ let engine;
530
+ try {
531
+ engine = inputs.engine();
532
+ }
533
+ catch {
534
+ // No engine: nothing runs, and the engine problem is reported elsewhere.
535
+ return none;
536
+ }
537
+ if (!engineSupportsRemap(engine)) {
538
+ return cannot(`${engine.label} does not apply compose's !override / !reset tags (Docker Compose 2.24.4 or newer does)`);
539
+ }
540
+ const { targets, warnings } = withoutUserOverride(candidates, inputs.mainRoot);
541
+ return { targets: remapIsEmpty(targets) ? null : targets, problem: null, warnings: [...skipped, ...warnings] };
542
+ }
@@ -1,2 +1,14 @@
1
1
  import type { ComposeFile } from "./types.js";
2
+ /** The `host:container` string wtc reads a `ports:` entry as, or null (no published port). */
3
+ export declare function portEntryString(p: unknown): string | null;
4
+ /**
5
+ * Container names a service joins by name: `network_mode`, `ipc` or `pid`
6
+ * set to `container:<name>`, and `volumes_from: [container:<name>[:ro]]`.
7
+ */
8
+ export declare function parseContainerRefs(s: Record<string, unknown>): string[];
9
+ /**
10
+ * A name built from `${COMPOSE_PROJECT_NAME}` is still per-stack: wtc sets
11
+ * that variable for every worktree (process env and root env file).
12
+ */
13
+ export declare function isProjectScopedName(name: string): boolean;
2
14
  export declare function parseComposeFile(composePath: string): ComposeFile;