worktree-compose 0.2.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +501 -143
  2. package/SKILL.md +113 -0
  3. package/dist/cli.js +94 -33
  4. package/dist/commands/clean.d.ts +2 -1
  5. package/dist/commands/clean.js +8 -48
  6. package/dist/commands/doctor.d.ts +3 -0
  7. package/dist/commands/doctor.js +30 -0
  8. package/dist/commands/list.d.ts +4 -1
  9. package/dist/commands/list.js +62 -44
  10. package/dist/commands/promote.d.ts +3 -1
  11. package/dist/commands/promote.js +4 -34
  12. package/dist/commands/prune.d.ts +2 -0
  13. package/dist/commands/prune.js +7 -0
  14. package/dist/commands/restart.d.ts +2 -1
  15. package/dist/commands/restart.js +11 -5
  16. package/dist/commands/skill.d.ts +4 -0
  17. package/dist/commands/skill.js +10 -0
  18. package/dist/commands/start.d.ts +2 -1
  19. package/dist/commands/start.js +7 -34
  20. package/dist/commands/stop.d.ts +1 -1
  21. package/dist/commands/stop.js +6 -23
  22. package/dist/compose/detect.d.ts +1 -2
  23. package/dist/compose/detect.js +1 -10
  24. package/dist/compose/engine.d.ts +61 -0
  25. package/dist/compose/engine.js +129 -0
  26. package/dist/compose/isolation.d.ts +26 -0
  27. package/dist/compose/isolation.js +91 -0
  28. package/dist/compose/override.d.ts +152 -0
  29. package/dist/compose/override.js +542 -0
  30. package/dist/compose/parse.d.ts +12 -0
  31. package/dist/compose/parse.js +199 -29
  32. package/dist/compose/status.d.ts +84 -0
  33. package/dist/compose/status.js +227 -0
  34. package/dist/compose/types.d.ts +43 -0
  35. package/dist/config.d.ts +31 -0
  36. package/dist/config.js +23 -6
  37. package/dist/context.d.ts +104 -3
  38. package/dist/context.js +299 -45
  39. package/dist/core/clean.d.ts +91 -0
  40. package/dist/core/clean.js +347 -0
  41. package/dist/core/compose.d.ts +92 -0
  42. package/dist/core/compose.js +195 -0
  43. package/dist/core/doctor.d.ts +29 -0
  44. package/dist/core/doctor.js +342 -0
  45. package/dist/core/list.d.ts +46 -0
  46. package/dist/core/list.js +101 -0
  47. package/dist/core/promote.d.ts +40 -0
  48. package/dist/core/promote.js +117 -0
  49. package/dist/core/prune.d.ts +32 -0
  50. package/dist/core/prune.js +79 -0
  51. package/dist/core/restart.d.ts +14 -0
  52. package/dist/core/restart.js +18 -0
  53. package/dist/core/start.d.ts +33 -0
  54. package/dist/core/start.js +113 -0
  55. package/dist/core/stop.d.ts +32 -0
  56. package/dist/core/stop.js +58 -0
  57. package/dist/core/teardown.d.ts +123 -0
  58. package/dist/core/teardown.js +305 -0
  59. package/dist/core/types.d.ts +15 -0
  60. package/dist/core/types.js +1 -0
  61. package/dist/git/promote.d.ts +49 -2
  62. package/dist/git/promote.js +160 -38
  63. package/dist/git/repo.d.ts +72 -0
  64. package/dist/git/repo.js +167 -0
  65. package/dist/git/status.d.ts +8 -0
  66. package/dist/git/status.js +25 -0
  67. package/dist/git/worktree.d.ts +63 -3
  68. package/dist/git/worktree.js +173 -29
  69. package/dist/mcp/server.d.ts +2 -0
  70. package/dist/mcp/server.js +230 -115
  71. package/dist/ports/allocate.d.ts +39 -5
  72. package/dist/ports/allocate.js +96 -16
  73. package/dist/ports/extract.d.ts +12 -0
  74. package/dist/ports/extract.js +48 -4
  75. package/dist/ports/types.d.ts +12 -1
  76. package/dist/selectors.d.ts +10 -0
  77. package/dist/selectors.js +106 -0
  78. package/dist/skill.d.ts +13 -0
  79. package/dist/skill.js +28 -0
  80. package/dist/state/registry.d.ts +194 -0
  81. package/dist/state/registry.js +595 -0
  82. package/dist/sync/env.d.ts +93 -2
  83. package/dist/sync/env.js +169 -32
  84. package/dist/sync/files.d.ts +15 -1
  85. package/dist/sync/files.js +126 -38
  86. package/dist/utils/exec.d.ts +69 -4
  87. package/dist/utils/exec.js +221 -15
  88. package/dist/utils/log.d.ts +37 -0
  89. package/dist/utils/log.js +68 -4
  90. package/dist/utils/paths.d.ts +61 -0
  91. package/dist/utils/paths.js +163 -0
  92. package/dist/utils/sanitize.d.ts +7 -0
  93. package/dist/utils/sanitize.js +12 -0
  94. package/dist/version.d.ts +1 -0
  95. package/dist/version.js +3 -0
  96. package/dist/workspaces/resolve.d.ts +21 -0
  97. package/dist/workspaces/resolve.js +235 -0
  98. package/package.json +20 -16
  99. package/wtc.schema.json +62 -0
@@ -1,21 +1,40 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { parse as parseYaml } from "yaml";
3
+ import { parseDocument } from "yaml";
4
+ /** The `host:container` string wtc reads a `ports:` entry as, or null (no published port). */
5
+ export function portEntryString(p) {
6
+ if (typeof p === "string")
7
+ return p;
8
+ if (typeof p === "number")
9
+ return String(p);
10
+ if (typeof p === "object" && p !== null) {
11
+ const obj = p;
12
+ if (obj.published != null && obj.target != null) {
13
+ return `${obj.published}:${obj.target}`;
14
+ }
15
+ }
16
+ return null;
17
+ }
4
18
  function parseServicePorts(ports) {
5
19
  if (!Array.isArray(ports))
6
20
  return [];
7
21
  return ports.flatMap((p) => {
8
- if (typeof p === "string")
9
- return [p];
10
- if (typeof p === "number")
11
- return [String(p)];
12
- if (typeof p === "object" && p !== null) {
13
- const obj = p;
14
- if (obj.published != null && obj.target != null) {
15
- return [`${obj.published}:${obj.target}`];
16
- }
17
- }
18
- return [];
22
+ const s = portEntryString(p);
23
+ return s === null ? [] : [s];
24
+ });
25
+ }
26
+ /** Key for deduplicating `ports:` entries across files (same written value). */
27
+ function entryKey(entry) {
28
+ return JSON.stringify(entry) ?? String(entry);
29
+ }
30
+ function uniqueEntries(entries) {
31
+ const seen = new Set();
32
+ return entries.filter((e) => {
33
+ const key = entryKey(e);
34
+ if (seen.has(key))
35
+ return false;
36
+ seen.add(key);
37
+ return true;
19
38
  });
20
39
  }
21
40
  function parseServiceBuild(build) {
@@ -27,6 +46,7 @@ function parseServiceBuild(build) {
27
46
  return {
28
47
  context: typeof obj.context === "string" ? obj.context : undefined,
29
48
  dockerfile: typeof obj.dockerfile === "string" ? obj.dockerfile : undefined,
49
+ ...(typeof obj.dockerfile_inline === "string" ? { inline: true } : {}),
30
50
  };
31
51
  }
32
52
  return undefined;
@@ -39,7 +59,47 @@ function parseEnvFile(envFile) {
39
59
  }
40
60
  return undefined;
41
61
  }
42
- function parseServicesObject(doc, sourcePath) {
62
+ /** Network names a service joins: the keys of the map form, or the list form. */
63
+ function parseServiceNetworks(networks) {
64
+ if (Array.isArray(networks))
65
+ return networks.filter((n) => typeof n === "string");
66
+ if (networks && typeof networks === "object")
67
+ return Object.keys(networks);
68
+ return undefined;
69
+ }
70
+ /** `extends: base` or `extends: { service, file }`. */
71
+ function parseExtends(ext) {
72
+ if (typeof ext === "string" && ext)
73
+ return { service: ext };
74
+ if (ext && typeof ext === "object") {
75
+ const o = ext;
76
+ if (typeof o.service === "string" && o.service) {
77
+ return { service: o.service, ...(typeof o.file === "string" && o.file ? { file: o.file } : {}) };
78
+ }
79
+ }
80
+ return undefined;
81
+ }
82
+ /**
83
+ * Container names a service joins by name: `network_mode`, `ipc` or `pid`
84
+ * set to `container:<name>`, and `volumes_from: [container:<name>[:ro]]`.
85
+ */
86
+ export function parseContainerRefs(s) {
87
+ const refs = [];
88
+ const add = (v) => {
89
+ if (typeof v === "string" && v.startsWith("container:")) {
90
+ const name = v.slice("container:".length).split(":")[0];
91
+ if (name)
92
+ refs.push(name);
93
+ }
94
+ };
95
+ add(s.network_mode);
96
+ add(s.ipc);
97
+ add(s.pid);
98
+ if (Array.isArray(s.volumes_from))
99
+ s.volumes_from.forEach(add);
100
+ return refs;
101
+ }
102
+ function parseServicesObject(doc, sourcePath, tagOf = () => undefined) {
43
103
  if (!("services" in doc) || !doc.services || typeof doc.services !== "object") {
44
104
  return [];
45
105
  }
@@ -47,15 +107,85 @@ function parseServicesObject(doc, sourcePath) {
47
107
  return Object.entries(servicesObj).map(([name, svc]) => {
48
108
  // An empty service definition (`foo:` with no body) parses to null.
49
109
  const s = svc ?? {};
110
+ const portsTag = tagOf(name, "ports");
111
+ // `!reset` clears the attribute whatever its payload says.
112
+ const portsReset = portsTag === "!reset";
113
+ const nameReset = tagOf(name, "container_name") === "!reset";
114
+ const networks = parseServiceNetworks(s.networks);
115
+ const extendsFrom = parseExtends(s.extends);
116
+ const containerRefs = parseContainerRefs(s);
50
117
  return {
51
118
  name,
52
- ports: parseServicePorts(s.ports),
119
+ ports: portsReset ? [] : parseServicePorts(s.ports),
120
+ portEntries: portsReset ? [] : Array.isArray(s.ports) ? uniqueEntries(s.ports) : [],
121
+ ...(portsTag === "!override" || portsReset ? { portsReplace: true } : {}),
122
+ ...(s.extends != null ? { extends: true } : {}),
123
+ ...(extendsFrom ? { extendsFrom } : {}),
124
+ ...(containerRefs.length > 0 ? { containerRefs } : {}),
125
+ ...(networks ? { networks } : {}),
126
+ ...(s.network_mode != null ? { networkMode: true } : {}),
53
127
  build: parseServiceBuild(s.build),
54
128
  envFile: parseEnvFile(s.env_file),
129
+ ...(nameReset ? { containerNameReset: true } : {}),
130
+ ...(!nameReset && typeof s.container_name === "string" && s.container_name
131
+ ? { containerName: s.container_name }
132
+ : {}),
55
133
  sourcePath,
56
134
  };
57
135
  });
58
136
  }
137
+ /**
138
+ * Top-level `volumes:` / `networks:` entries. Only `name:` and `external`
139
+ * matter to wtc: either one takes the resource out of the project scope, so
140
+ * every worktree stack would share it.
141
+ */
142
+ function parseResources(section) {
143
+ const out = new Map();
144
+ if (!section || typeof section !== "object" || Array.isArray(section)) {
145
+ return out;
146
+ }
147
+ for (const [key, raw] of Object.entries(section)) {
148
+ const def = raw && typeof raw === "object" ? raw : {};
149
+ // `external: true`, or the legacy `external: { name: x }` form.
150
+ const external = def.external === true ||
151
+ (typeof def.external === "object" && def.external !== null);
152
+ const legacyName = typeof def.external === "object" && def.external !== null
153
+ ? def.external.name
154
+ : undefined;
155
+ const name = typeof def.name === "string" && def.name
156
+ ? def.name
157
+ : typeof legacyName === "string" && legacyName
158
+ ? legacyName
159
+ : undefined;
160
+ out.set(key, { ...(name ? { name } : {}), external });
161
+ }
162
+ return out;
163
+ }
164
+ /** Later definitions override earlier ones field by field, like services. */
165
+ function mergeResources(into, from) {
166
+ for (const [key, def] of from) {
167
+ const existing = into.get(key);
168
+ into.set(key, existing
169
+ ? { name: def.name ?? existing.name, external: def.external || existing.external }
170
+ : def);
171
+ }
172
+ }
173
+ /**
174
+ * A name built from `${COMPOSE_PROJECT_NAME}` is still per-stack: wtc sets
175
+ * that variable for every worktree (process env and root env file).
176
+ */
177
+ export function isProjectScopedName(name) {
178
+ return /\$\{?COMPOSE_PROJECT_NAME\b/.test(name);
179
+ }
180
+ function sharedOnly(defs) {
181
+ const out = [];
182
+ for (const [key, def] of defs) {
183
+ if (!def.external && (!def.name || isProjectScopedName(def.name)))
184
+ continue;
185
+ out.push({ key, ...(def.name ? { name: def.name } : {}), external: def.external });
186
+ }
187
+ return out;
188
+ }
59
189
  /**
60
190
  * Normalize a top-level `include:` value into a list of resolved absolute
61
191
  * paths. Each entry is a string path or a long-form object whose `path` is a
@@ -98,21 +228,41 @@ function normalizeIncludes(include, parentPath) {
98
228
  * resolves the context relative to the right directory.
99
229
  */
100
230
  function mergeService(base, override) {
101
- const ports = [...base.ports];
102
- for (const p of override.ports) {
103
- if (!ports.includes(p))
104
- ports.push(p);
231
+ // `ports: !override` / `!reset` in the later file replaces the list.
232
+ const ports = override.portsReplace ? [...override.ports] : [...base.ports];
233
+ if (!override.portsReplace) {
234
+ for (const p of override.ports) {
235
+ if (!ports.includes(p))
236
+ ports.push(p);
237
+ }
105
238
  }
106
239
  const sourcePath = override.build !== undefined
107
240
  ? override.sourcePath
108
241
  : base.build !== undefined
109
242
  ? base.sourcePath
110
243
  : override.sourcePath;
244
+ const containerName = override.containerNameReset
245
+ ? override.containerName
246
+ : (override.containerName ?? base.containerName);
247
+ const networks = [...new Set([...(base.networks ?? []), ...(override.networks ?? [])])];
111
248
  return {
112
249
  name: override.name,
113
250
  ports,
251
+ portEntries: override.portsReplace
252
+ ? (override.portEntries ?? [])
253
+ : uniqueEntries([...(base.portEntries ?? []), ...(override.portEntries ?? [])]),
254
+ ...(base.portsReplace || override.portsReplace ? { portsReplace: true } : {}),
255
+ ...(base.extends || override.extends ? { extends: true } : {}),
256
+ ...((override.extendsFrom ?? base.extendsFrom) ? { extendsFrom: override.extendsFrom ?? base.extendsFrom } : {}),
257
+ ...(base.containerRefs || override.containerRefs
258
+ ? { containerRefs: [...new Set([...(base.containerRefs ?? []), ...(override.containerRefs ?? [])])] }
259
+ : {}),
260
+ ...(base.networks || override.networks ? { networks } : {}),
261
+ ...(base.networkMode || override.networkMode ? { networkMode: true } : {}),
114
262
  build: override.build ?? base.build,
115
263
  envFile: override.envFile ?? base.envFile,
264
+ ...(containerName ? { containerName } : {}),
265
+ ...(override.containerNameReset ? { containerNameReset: true } : {}),
116
266
  sourcePath,
117
267
  };
118
268
  }
@@ -131,35 +281,55 @@ function foldServices(services) {
131
281
  }
132
282
  return [...byName.values()];
133
283
  }
134
- function parseRecursive(filePath, seen, sourceFiles) {
284
+ function parseRecursive(filePath, st) {
135
285
  if (!fs.existsSync(filePath)) {
136
286
  console.warn(`wtc: included compose file not found, skipping: ${filePath}`);
137
287
  return [];
138
288
  }
139
289
  // Key on the realpath so symlinked duplicates and cycles are caught.
140
290
  const key = fs.realpathSync.native(filePath);
141
- if (seen.has(key))
291
+ if (st.seen.has(key))
142
292
  return [];
143
- seen.add(key);
293
+ st.seen.add(key);
144
294
  const raw = fs.readFileSync(filePath, "utf-8");
145
- const doc = parseYaml(raw, { uniqueKeys: false });
295
+ // Merge keys (`<<: *anchor`) resolved as compose resolves them; compose's
296
+ // own tags (`!reset`, `!override`) kept on the nodes, without warnings.
297
+ const document = parseDocument(raw, { uniqueKeys: false, merge: true });
298
+ if (document.errors.length > 0) {
299
+ throw new Error(`Invalid YAML in ${filePath}: ${document.errors[0].message}`);
300
+ }
301
+ const doc = document.toJS();
146
302
  if (!doc || typeof doc !== "object")
147
303
  return [];
148
- sourceFiles.push(key);
304
+ const tagOf = (service, k) => document.getIn(["services", service, k], true)?.tag;
305
+ st.sourceFiles.push(key);
149
306
  // Recurse into includes first so local services can override included ones.
150
307
  let included = [];
151
308
  if ("include" in doc) {
152
309
  for (const inc of normalizeIncludes(doc.include, filePath)) {
153
- included = included.concat(parseRecursive(inc, seen, sourceFiles));
310
+ included = included.concat(parseRecursive(inc, st));
154
311
  }
155
312
  }
156
- const local = parseServicesObject(doc, key);
313
+ const record = doc;
314
+ mergeResources(st.volumes, parseResources(record.volumes));
315
+ mergeResources(st.networks, parseResources(record.networks));
316
+ const local = parseServicesObject(record, key, tagOf);
157
317
  return foldServices([...included, ...local]);
158
318
  }
159
319
  export function parseComposeFile(composePath) {
160
320
  const abs = path.resolve(composePath);
161
- const seen = new Set();
162
- const sourceFiles = [];
163
- const services = parseRecursive(abs, seen, sourceFiles);
164
- return { services, composePath: abs, sourceFiles };
321
+ const st = {
322
+ seen: new Set(),
323
+ sourceFiles: [],
324
+ volumes: new Map(),
325
+ networks: new Map(),
326
+ };
327
+ const services = parseRecursive(abs, st);
328
+ return {
329
+ services,
330
+ composePath: abs,
331
+ sourceFiles: st.sourceFiles,
332
+ sharedVolumes: sharedOnly(st.volumes),
333
+ sharedNetworks: sharedOnly(st.networks),
334
+ };
165
335
  }
@@ -0,0 +1,84 @@
1
+ import type { ComposeEngine } from "./engine.js";
2
+ export interface StackState {
3
+ running: number;
4
+ total: number;
5
+ }
6
+ export declare const PROJECT_LABELS: string[];
7
+ /**
8
+ * Parse Docker's `Labels` string (`k=v,k=v`, in random order). Values may
9
+ * themselves contain commas (e.g. `config_files=/a.yml,/b.yml`), so only
10
+ * split on a comma that starts a new `key=`. A key starts with a letter and
11
+ * may contain `/` (Docker Desktop adds `desktop.docker.io/binds/0/Source`
12
+ * to every container with a bind mount); a value such as `/my dir/a=b.yml`
13
+ * or `C:\x=y.yml` after a comma starts with `/` or holds `:` / `\`, so it
14
+ * is never mistaken for a new key.
15
+ */
16
+ export declare function parseLabelString(labels: string): Record<string, string>;
17
+ /** Case-insensitive field lookup: Docker uses `Labels`/`ID`, Podman `labels`/`Id`. */
18
+ export declare function field(obj: Record<string, unknown>, name: string): unknown;
19
+ export declare function labelsOf(container: Record<string, unknown>): Record<string, string>;
20
+ /**
21
+ * Parse `--format json` listings (`ps`, `network ls`, `volume ls`): Docker
22
+ * emits NDJSON, Podman one JSON array. Throws when the output is neither.
23
+ */
24
+ export declare function parseJsonListing(output: string): Record<string, unknown>[];
25
+ /** A container from `ps -a --format json`, reduced to what wtc needs. */
26
+ export interface PsContainer {
27
+ id: string;
28
+ /** First container name. */
29
+ name: string;
30
+ /** Compose project label, or `null` for non-compose containers. */
31
+ project: string | null;
32
+ /** Compose's `project.working_dir` label (the directory compose ran in). */
33
+ workingDir: string | null;
34
+ /** Lower-cased engine state: `running`, `exited`, `created`, `paused`… */
35
+ state: string;
36
+ running: boolean;
37
+ /** `compose run` container (one-off), not part of the stack's services. */
38
+ oneoff: boolean;
39
+ }
40
+ /**
41
+ * Every container of a `ps -a --format json` listing with what wtc needs per
42
+ * container: compose project, working_dir (to adopt a running stack into
43
+ * the registry), state, and whether it is a one-off. Sibling of
44
+ * `parsePsJson`, which reduces the same listing to per-project counts.
45
+ */
46
+ export declare function parsePsContainers(output: string): PsContainer[];
47
+ /**
48
+ * Count running/total containers per compose project from `ps -a --format json`.
49
+ * Docker emits NDJSON with a `Labels` string; Podman emits one JSON array with
50
+ * a `Labels` object. One-off `compose run` containers are not counted: they
51
+ * are not part of the stack, and counting them shows a healthy stack as
52
+ * `partial` until clean. Throws when the output is neither shape.
53
+ */
54
+ export declare function parsePsJson(output: string): Map<string, StackState>;
55
+ /** One `<cli> ps -a --format json` call (bounded by a timeout). Throws on failure. */
56
+ export declare function listContainers(engine: ComposeEngine): PsContainer[];
57
+ /** One `<cli> ps -a --format json` call → state per compose project. Throws on failure. */
58
+ export declare function getStackStates(engine: ComposeEngine): Map<string, StackState>;
59
+ /**
60
+ * Per-project fallback: `compose -p P ps -q` (running) and `ps -a -q` (total).
61
+ * podman-compose's `ps` accepts only `-q` and always lists every container,
62
+ * so it cannot tell running from stopped: its state is unknown.
63
+ */
64
+ export declare function probeStackDirect(engine: ComposeEngine, project: string, cwd?: string): StackState | null;
65
+ /** Answers "what state is project P in?" — `null` means unknown (engine unreachable). */
66
+ export interface StackProbe {
67
+ readonly engine: ComposeEngine | null;
68
+ /** Why states are unknown (no engine, daemon down), when they are. */
69
+ readonly problem: string | null;
70
+ state(project: string): StackState | null;
71
+ /**
72
+ * Every container the engine reports (one-offs included, flagged), or
73
+ * `null` when that listing is unavailable (engine down, or unparseable
74
+ * `ps` output — then `problem` is null and states come per project).
75
+ */
76
+ containers(): PsContainer[] | null;
77
+ }
78
+ /**
79
+ * Lazily fetch stack states once, falling back to per-project compose calls
80
+ * when the `ps` JSON cannot be parsed (older engines, unexpected shapes).
81
+ */
82
+ export declare function createStackProbe(engine: ComposeEngine | null, engineProblem?: string | null, cwd?: string): StackProbe;
83
+ export type StackStatus = "up" | "partial" | "exited" | "down" | "?";
84
+ export declare function stackStatus(state: StackState | null): StackStatus;
@@ -0,0 +1,227 @@
1
+ import path from "node:path";
2
+ import { CommandError, ENGINE_PROBE_TIMEOUT_MS, run, runSafe } from "../utils/exec.js";
3
+ import { cliCall, composeArgs, composeBin } from "./engine.js";
4
+ export const PROJECT_LABELS = ["com.docker.compose.project", "io.podman.compose.project"];
5
+ const WORKING_DIR_LABEL = "com.docker.compose.project.working_dir";
6
+ const ONEOFF_LABEL = "com.docker.compose.oneoff";
7
+ /**
8
+ * Parse Docker's `Labels` string (`k=v,k=v`, in random order). Values may
9
+ * themselves contain commas (e.g. `config_files=/a.yml,/b.yml`), so only
10
+ * split on a comma that starts a new `key=`. A key starts with a letter and
11
+ * may contain `/` (Docker Desktop adds `desktop.docker.io/binds/0/Source`
12
+ * to every container with a bind mount); a value such as `/my dir/a=b.yml`
13
+ * or `C:\x=y.yml` after a comma starts with `/` or holds `:` / `\`, so it
14
+ * is never mistaken for a new key.
15
+ */
16
+ export function parseLabelString(labels) {
17
+ const out = {};
18
+ if (!labels)
19
+ return out;
20
+ for (const pair of labels.split(/,(?=[A-Za-z][A-Za-z0-9_.\/-]*=)/)) {
21
+ const eq = pair.indexOf("=");
22
+ if (eq <= 0)
23
+ continue;
24
+ out[pair.slice(0, eq)] = pair.slice(eq + 1);
25
+ }
26
+ return out;
27
+ }
28
+ /** Case-insensitive field lookup: Docker uses `Labels`/`ID`, Podman `labels`/`Id`. */
29
+ export function field(obj, name) {
30
+ if (name in obj)
31
+ return obj[name];
32
+ const lower = name.toLowerCase();
33
+ for (const [k, v] of Object.entries(obj)) {
34
+ if (k.toLowerCase() === lower)
35
+ return v;
36
+ }
37
+ return undefined;
38
+ }
39
+ export function labelsOf(container) {
40
+ const labels = field(container, "Labels");
41
+ if (typeof labels === "string")
42
+ return parseLabelString(labels);
43
+ if (labels && typeof labels === "object") {
44
+ const out = {};
45
+ for (const [k, v] of Object.entries(labels)) {
46
+ if (typeof v === "string")
47
+ out[k] = v;
48
+ }
49
+ return out;
50
+ }
51
+ return {};
52
+ }
53
+ /**
54
+ * Parse `--format json` listings (`ps`, `network ls`, `volume ls`): Docker
55
+ * emits NDJSON, Podman one JSON array. Throws when the output is neither.
56
+ */
57
+ export function parseJsonListing(output) {
58
+ const text = output.trim();
59
+ if (!text)
60
+ return [];
61
+ let entries;
62
+ if (text.startsWith("[")) {
63
+ const parsed = JSON.parse(text);
64
+ if (!Array.isArray(parsed))
65
+ throw new Error("Unexpected JSON listing");
66
+ entries = parsed;
67
+ }
68
+ else {
69
+ entries = text
70
+ .split("\n")
71
+ .map((line) => line.trim())
72
+ .filter(Boolean)
73
+ .map((line) => JSON.parse(line));
74
+ }
75
+ return entries.map((e) => {
76
+ if (!e || typeof e !== "object" || Array.isArray(e))
77
+ throw new Error("Unexpected JSON listing entry");
78
+ return e;
79
+ });
80
+ }
81
+ function firstName(value) {
82
+ if (Array.isArray(value))
83
+ return String(value[0] ?? "");
84
+ return String(value ?? "").split(",")[0].trim();
85
+ }
86
+ /**
87
+ * Every container of a `ps -a --format json` listing with what wtc needs per
88
+ * container: compose project, working_dir (to adopt a running stack into
89
+ * the registry), state, and whether it is a one-off. Sibling of
90
+ * `parsePsJson`, which reduces the same listing to per-project counts.
91
+ */
92
+ export function parsePsContainers(output) {
93
+ return parseJsonListing(output).map((c) => {
94
+ const labels = labelsOf(c);
95
+ const name = firstName(field(c, "Names"));
96
+ const project = PROJECT_LABELS.map((l) => labels[l]).find(Boolean) ?? null;
97
+ // Docker labels `compose run` containers oneoff=True (services carry
98
+ // oneoff=False, so compare the value); podman-compose names them
99
+ // `<project>_<service>_tmp<n>`.
100
+ const oneoff = (labels[ONEOFF_LABEL] ?? "").toLowerCase() === "true" ||
101
+ (project !== null && /_tmp\d+$/.test(name) && Boolean(labels["io.podman.compose.project"]));
102
+ const state = String(field(c, "State") ?? "").toLowerCase();
103
+ return {
104
+ id: String(field(c, "ID") ?? ""),
105
+ name,
106
+ project,
107
+ workingDir: labels[WORKING_DIR_LABEL] || null,
108
+ state,
109
+ running: state === "running",
110
+ oneoff,
111
+ };
112
+ });
113
+ }
114
+ /**
115
+ * Count running/total containers per compose project from `ps -a --format json`.
116
+ * Docker emits NDJSON with a `Labels` string; Podman emits one JSON array with
117
+ * a `Labels` object. One-off `compose run` containers are not counted: they
118
+ * are not part of the stack, and counting them shows a healthy stack as
119
+ * `partial` until clean. Throws when the output is neither shape.
120
+ */
121
+ export function parsePsJson(output) {
122
+ return statesOf(parsePsContainers(output));
123
+ }
124
+ function statesOf(containers) {
125
+ const states = new Map();
126
+ for (const c of containers) {
127
+ if (!c.project || c.oneoff)
128
+ continue;
129
+ const state = states.get(c.project) ?? { running: 0, total: 0 };
130
+ state.total++;
131
+ if (c.running)
132
+ state.running++;
133
+ states.set(c.project, state);
134
+ }
135
+ return states;
136
+ }
137
+ /** One `<cli> ps -a --format json` call (bounded by a timeout). Throws on failure. */
138
+ export function listContainers(engine) {
139
+ const [file, args] = cliCall(engine, "ps", "-a", "--format", "json");
140
+ return parsePsContainers(run(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS }));
141
+ }
142
+ /** One `<cli> ps -a --format json` call → state per compose project. Throws on failure. */
143
+ export function getStackStates(engine) {
144
+ return statesOf(listContainers(engine));
145
+ }
146
+ /**
147
+ * Per-project fallback: `compose -p P ps -q` (running) and `ps -a -q` (total).
148
+ * podman-compose's `ps` accepts only `-q` and always lists every container,
149
+ * so it cannot tell running from stopped: its state is unknown.
150
+ */
151
+ export function probeStackDirect(engine, project, cwd) {
152
+ if (path.basename(engine.compose[0]) === "podman-compose")
153
+ return null;
154
+ const count = (out) => out === null ? null : out.split("\n").filter((l) => l.trim()).length;
155
+ const opts = { cwd, timeoutMs: ENGINE_PROBE_TIMEOUT_MS };
156
+ const running = count(runSafe(composeBin(engine), composeArgs(engine, project, "ps", "-q"), opts));
157
+ const total = count(runSafe(composeBin(engine), composeArgs(engine, project, "ps", "-a", "-q"), opts));
158
+ if (running === null || total === null)
159
+ return null;
160
+ return { running, total };
161
+ }
162
+ /**
163
+ * Lazily fetch stack states once, falling back to per-project compose calls
164
+ * when the `ps` JSON cannot be parsed (older engines, unexpected shapes).
165
+ */
166
+ export function createStackProbe(engine, engineProblem = null, cwd) {
167
+ let mode = engine ? "pending" : "unavailable";
168
+ let states = new Map();
169
+ let listed = [];
170
+ let problem = engine ? null : engineProblem;
171
+ const cache = new Map();
172
+ const load = () => {
173
+ if (mode !== "pending" || !engine)
174
+ return;
175
+ try {
176
+ listed = listContainers(engine);
177
+ states = statesOf(listed);
178
+ mode = "map";
179
+ }
180
+ catch (err) {
181
+ if (err instanceof CommandError) {
182
+ // The CLI itself failed (daemon down, timed out, binary missing): states are unknown.
183
+ mode = "unavailable";
184
+ const last = err.message.split("\n").slice(-1)[0];
185
+ problem =
186
+ `Container engine not reachable (${engine.cliArgv.join(" ")} ps failed: ${last}). ` +
187
+ `Start it, or set WTC_COMPOSE_COMMAND to use another engine (e.g. "podman compose").`;
188
+ }
189
+ else {
190
+ // Unparseable output: ask compose per project instead.
191
+ mode = "fallback";
192
+ }
193
+ }
194
+ };
195
+ return {
196
+ engine,
197
+ get problem() {
198
+ load();
199
+ return problem;
200
+ },
201
+ state(project) {
202
+ load();
203
+ if (mode === "unavailable")
204
+ return null;
205
+ if (mode === "map")
206
+ return states.get(project) ?? { running: 0, total: 0 };
207
+ if (!cache.has(project))
208
+ cache.set(project, probeStackDirect(engine, project, cwd));
209
+ return cache.get(project) ?? null;
210
+ },
211
+ containers() {
212
+ load();
213
+ return mode === "map" ? listed : null;
214
+ },
215
+ };
216
+ }
217
+ export function stackStatus(state) {
218
+ if (!state)
219
+ return "?";
220
+ if (state.total === 0)
221
+ return "down";
222
+ if (state.running === state.total)
223
+ return "up";
224
+ if (state.running === 0)
225
+ return "exited";
226
+ return "partial";
227
+ }
@@ -1,18 +1,61 @@
1
1
  export interface ComposeService {
2
2
  name: string;
3
3
  ports: string[];
4
+ /**
5
+ * Every `ports:` entry as written (string, number, or long-form object),
6
+ * merged across files like `ports`. A runtime override that replaces the
7
+ * list must reproduce the entries it does not remap exactly.
8
+ */
9
+ portEntries?: unknown[];
10
+ /** `ports: !override` / `!reset`: the list replaces earlier files' lists instead of adding to them. */
11
+ portsReplace?: boolean;
12
+ /** The service uses `extends:`, so it may inherit ports wtc cannot see. */
13
+ extends?: boolean;
14
+ /** What `extends:` names: a service, in another file when `file` is set. */
15
+ extendsFrom?: {
16
+ service: string;
17
+ file?: string;
18
+ };
19
+ /** Container names the service joins by name (`network_mode: container:<name>`, `volumes_from`, …). */
20
+ containerRefs?: string[];
21
+ /** Networks the service joins (absent: only the project's `default`). */
22
+ networks?: string[];
23
+ /** The service sets `network_mode` (host, none, another container…): no networks of its own. */
24
+ networkMode?: boolean;
25
+ /** `container_name: !reset` in a later file dropped any earlier name. */
26
+ containerNameReset?: boolean;
4
27
  build?: {
5
28
  context?: string;
6
29
  dockerfile?: string;
30
+ /** `dockerfile_inline` is set: there is no Dockerfile on disk to sync. */
31
+ inline?: boolean;
7
32
  };
8
33
  envFile?: string[];
34
+ /** Fixed `container_name` — breaks running the same stack twice. */
35
+ containerName?: string;
9
36
  /** Absolute path of the compose file that declared this service. */
10
37
  sourcePath: string;
11
38
  }
39
+ /**
40
+ * A top-level volume or network that is NOT scoped to the compose project:
41
+ * it sets an explicit `name:` or is `external`. Every worktree stack would
42
+ * share it.
43
+ */
44
+ export interface SharedResource {
45
+ /** Key under `volumes:` / `networks:`. */
46
+ key: string;
47
+ /** Explicit `name:` when set. */
48
+ name?: string;
49
+ external: boolean;
50
+ }
12
51
  export interface ComposeFile {
13
52
  services: ComposeService[];
14
53
  /** Resolved absolute path of the root compose file. */
15
54
  composePath: string;
16
55
  /** Absolute paths of the root file plus all transitively-included files, root first. */
17
56
  sourceFiles: string[];
57
+ /** Top-level volumes with a fixed name or `external`. */
58
+ sharedVolumes: SharedResource[];
59
+ /** Top-level networks with a fixed name or `external`. */
60
+ sharedNetworks: SharedResource[];
18
61
  }