worktree-compose 0.2.0 → 1.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 (94) hide show
  1. package/README.md +458 -140
  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 +15 -0
  27. package/dist/compose/isolation.js +62 -0
  28. package/dist/compose/parse.d.ts +5 -0
  29. package/dist/compose/parse.js +89 -11
  30. package/dist/compose/status.d.ts +84 -0
  31. package/dist/compose/status.js +227 -0
  32. package/dist/compose/types.d.ts +20 -0
  33. package/dist/config.d.ts +31 -0
  34. package/dist/config.js +23 -6
  35. package/dist/context.d.ts +89 -3
  36. package/dist/context.js +278 -45
  37. package/dist/core/clean.d.ts +91 -0
  38. package/dist/core/clean.js +343 -0
  39. package/dist/core/compose.d.ts +30 -0
  40. package/dist/core/compose.js +45 -0
  41. package/dist/core/doctor.d.ts +28 -0
  42. package/dist/core/doctor.js +277 -0
  43. package/dist/core/list.d.ts +42 -0
  44. package/dist/core/list.js +94 -0
  45. package/dist/core/promote.d.ts +40 -0
  46. package/dist/core/promote.js +117 -0
  47. package/dist/core/prune.d.ts +32 -0
  48. package/dist/core/prune.js +75 -0
  49. package/dist/core/restart.d.ts +14 -0
  50. package/dist/core/restart.js +18 -0
  51. package/dist/core/start.d.ts +31 -0
  52. package/dist/core/start.js +99 -0
  53. package/dist/core/stop.d.ts +32 -0
  54. package/dist/core/stop.js +57 -0
  55. package/dist/core/teardown.d.ts +121 -0
  56. package/dist/core/teardown.js +298 -0
  57. package/dist/core/types.d.ts +15 -0
  58. package/dist/core/types.js +1 -0
  59. package/dist/git/promote.d.ts +49 -2
  60. package/dist/git/promote.js +160 -38
  61. package/dist/git/repo.d.ts +72 -0
  62. package/dist/git/repo.js +167 -0
  63. package/dist/git/status.d.ts +8 -0
  64. package/dist/git/status.js +25 -0
  65. package/dist/git/worktree.d.ts +63 -3
  66. package/dist/git/worktree.js +173 -29
  67. package/dist/mcp/server.d.ts +2 -0
  68. package/dist/mcp/server.js +230 -115
  69. package/dist/ports/allocate.d.ts +14 -3
  70. package/dist/ports/allocate.js +20 -4
  71. package/dist/selectors.d.ts +10 -0
  72. package/dist/selectors.js +106 -0
  73. package/dist/skill.d.ts +13 -0
  74. package/dist/skill.js +28 -0
  75. package/dist/state/registry.d.ts +194 -0
  76. package/dist/state/registry.js +595 -0
  77. package/dist/sync/env.d.ts +77 -2
  78. package/dist/sync/env.js +151 -32
  79. package/dist/sync/files.d.ts +15 -1
  80. package/dist/sync/files.js +126 -38
  81. package/dist/utils/exec.d.ts +69 -4
  82. package/dist/utils/exec.js +221 -15
  83. package/dist/utils/log.d.ts +37 -0
  84. package/dist/utils/log.js +68 -4
  85. package/dist/utils/paths.d.ts +61 -0
  86. package/dist/utils/paths.js +163 -0
  87. package/dist/utils/sanitize.d.ts +7 -0
  88. package/dist/utils/sanitize.js +12 -0
  89. package/dist/version.d.ts +1 -0
  90. package/dist/version.js +3 -0
  91. package/dist/workspaces/resolve.d.ts +21 -0
  92. package/dist/workspaces/resolve.js +235 -0
  93. package/package.json +18 -14
  94. package/wtc.schema.json +62 -0
@@ -1,37 +1,10 @@
1
- import { buildContext, filterWorktrees } from "../context.js";
2
- import { allocateWorktreePorts } from "../ports/allocate.js";
3
- import { composeProjectName } from "../utils/sanitize.js";
4
- import { execLive } from "../utils/exec.js";
5
- import { syncWorktreeFiles } from "../sync/files.js";
6
- import { copyBaseEnv, injectPortOverrides } from "../sync/env.js";
7
- import * as log from "../utils/log.js";
1
+ import { startWorktrees } from "../core/start.js";
2
+ import { consoleReporter, print } from "../utils/log.js";
8
3
  import { listCommand } from "./list.js";
9
- export function startCommand(indices) {
10
- const ctx = buildContext();
11
- if (ctx.worktrees.length === 0) {
12
- log.warn("No extra worktrees found. Create one with:\n git worktree add ../my-branch my-branch");
4
+ export async function startCommand(worktrees, options = {}) {
5
+ const result = await startWorktrees({ ...options, worktrees }, consoleReporter, { live: true });
6
+ if (result.started.length === 0)
13
7
  return;
14
- }
15
- const targets = filterWorktrees(ctx.worktrees, indices);
16
- for (const wt of targets) {
17
- const idx = ctx.worktrees.indexOf(wt) + 1;
18
- const project = composeProjectName(ctx.repoName, idx, wt.branch);
19
- const allocations = allocateWorktreePorts(ctx.portMappings, idx, ctx.portStride);
20
- log.header(`Worktree ${idx}: ${wt.branch}`);
21
- log.info(`Path: ${wt.path}`);
22
- log.info(`Project: ${project}`);
23
- log.info(`Ports: ${allocations.map((a) => `${a.envVar}=${a.port}`).join(" ")}`);
24
- syncWorktreeFiles(ctx.repoRoot, wt.path, ctx.composeFile, ctx.config.sync);
25
- log.success("Synced infrastructure files");
26
- copyBaseEnv(ctx.repoRoot, wt.path);
27
- injectPortOverrides(`${wt.path}/.env`, allocations, ctx.config.envOverrides);
28
- log.success("Injected port overrides into .env");
29
- execLive(`docker compose -p "${project}" up -d --build`, {
30
- cwd: wt.path,
31
- env: { ...process.env, COMPOSE_PROJECT_NAME: project },
32
- });
33
- log.success(`Worktree ${idx} started`);
34
- }
35
- console.log("");
36
- listCommand();
8
+ print("");
9
+ await listCommand({ quiet: true });
37
10
  }
@@ -1 +1 @@
1
- export declare function stopCommand(indices: number[]): void;
1
+ export declare function stopCommand(worktrees: string[]): Promise<void>;
@@ -1,24 +1,7 @@
1
- import { buildContext, filterWorktrees } from "../context.js";
2
- import { composeProjectName } from "../utils/sanitize.js";
3
- import { execLive } from "../utils/exec.js";
4
- import * as log from "../utils/log.js";
5
- export function stopCommand(indices) {
6
- const ctx = buildContext();
7
- if (ctx.worktrees.length === 0) {
8
- log.warn("No worktrees to stop.");
9
- return;
10
- }
11
- const targets = filterWorktrees(ctx.worktrees, indices);
12
- for (const wt of targets) {
13
- const idx = ctx.worktrees.indexOf(wt) + 1;
14
- const project = composeProjectName(ctx.repoName, idx, wt.branch);
15
- log.info(`Stopping ${project}...`);
16
- try {
17
- execLive(`docker compose -p "${project}" down`, { cwd: wt.path });
18
- log.success(`Stopped worktree ${idx} (${wt.branch})`);
19
- }
20
- catch {
21
- log.warn(`Could not stop ${project} (may already be stopped)`);
22
- }
23
- }
1
+ import { stopWorktrees } from "../core/stop.js";
2
+ import { consoleReporter } from "../utils/log.js";
3
+ export async function stopCommand(worktrees) {
4
+ const result = await stopWorktrees({ worktrees }, consoleReporter, { live: true });
5
+ if (result.failures > 0)
6
+ process.exitCode = 1;
24
7
  }
@@ -1,3 +1,2 @@
1
- export declare function getRepoRoot(cwd?: string): string;
2
- export declare function getRepoName(repoRoot: string): string;
1
+ export declare const COMPOSE_FILENAMES: string[];
3
2
  export declare function detectComposeFile(repoRoot: string): string | null;
@@ -1,20 +1,11 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { exec } from "../utils/exec.js";
4
- const COMPOSE_FILENAMES = [
3
+ export const COMPOSE_FILENAMES = [
5
4
  "compose.yaml",
6
5
  "compose.yml",
7
6
  "docker-compose.yaml",
8
7
  "docker-compose.yml",
9
8
  ];
10
- export function getRepoRoot(cwd) {
11
- return exec("git rev-parse --show-toplevel", {
12
- cwd: cwd ?? process.cwd(),
13
- });
14
- }
15
- export function getRepoName(repoRoot) {
16
- return path.basename(repoRoot);
17
- }
18
9
  export function detectComposeFile(repoRoot) {
19
10
  for (const name of COMPOSE_FILENAMES) {
20
11
  const full = path.join(repoRoot, name);
@@ -0,0 +1,61 @@
1
+ import type { WtcConfig } from "../config.js";
2
+ export interface ComposeEngine {
3
+ /** argv prefix for compose, e.g. ["docker","compose"], ["podman","compose"], ["docker-compose"], ["podman-compose"] */
4
+ compose: string[];
5
+ /** Container CLI flavor used for sweeps/status: "docker" | "podman". */
6
+ cli: "docker" | "podman";
7
+ /**
8
+ * argv prefix for container-CLI calls (`ps`, `info`, sweeps): the binary
9
+ * plus any global flags that preceded `compose` (`docker --context colima
10
+ * compose` → `["docker", "--context", "colima"]`), so status and sweeps
11
+ * talk to the same daemon compose does.
12
+ */
13
+ cliArgv: string[];
14
+ /** Human label, e.g. "docker compose". */
15
+ label: string;
16
+ }
17
+ /** Returns true when `<argv> version` runs successfully. */
18
+ export type EngineProbe = (argv: string[]) => boolean;
19
+ /** Returns true when the container daemon behind `cliArgv` answers. */
20
+ export type DaemonProbe = (cliArgv: string[]) => boolean;
21
+ /** Auto-detection order: Compose v2 plugin first, then Podman, then standalone binaries. */
22
+ export declare const ENGINE_CANDIDATES: string[][];
23
+ export declare const NO_ENGINE_MESSAGE: string;
24
+ /**
25
+ * `<cliArgv> info`: talks to the daemon (or podman machine), so it exits
26
+ * non-zero when that is down — unlike `version`, which succeeds client-only.
27
+ */
28
+ export declare function daemonCheckArgs(engine: Pick<ComposeEngine, "cliArgv">): [string, string[]];
29
+ export declare function engineFromArgv(argv: string[]): ComposeEngine;
30
+ /** True when `argv` is exactly one of the known compose commands. */
31
+ export declare function isKnownComposeCommand(argv: string[]): boolean;
32
+ /**
33
+ * Pick the compose command: `WTC_COMPOSE_COMMAND`, then config
34
+ * `composeCommand`, then auto-detection (cached per process). Resolved
35
+ * lazily — only commands that touch containers need it, so `promote` works
36
+ * without Docker installed.
37
+ *
38
+ * `composeCommand` comes from a file committed to the repository, so it may
39
+ * only *choose* one of the known compose tools: an arbitrary argv there
40
+ * would let a cloned repo run any program — even from `wtc doctor` /
41
+ * `wtc_doctor`, which agents treat as read-only — and extra flags such as
42
+ * `docker --config ./dir compose` load repo-shipped CLI plugins. Custom
43
+ * commands belong in `WTC_COMPOSE_COMMAND`, which the user controls.
44
+ *
45
+ * Auto-detection finds the installed candidates (`version` succeeds,
46
+ * which needs no daemon). When more than one is installed it prefers the
47
+ * first whose daemon answers (`info`), so a quit Docker Desktop does not
48
+ * shadow a running Podman; when none answers — or only one is installed —
49
+ * it takes the first installed one.
50
+ */
51
+ export declare function resolveEngine(config: WtcConfig, env?: NodeJS.ProcessEnv, probe?: EngineProbe, daemonProbe?: DaemonProbe): ComposeEngine;
52
+ /** Forget the cached auto-detected engine (tests). */
53
+ export declare function resetEngineCache(): void;
54
+ /** Arguments (after `engine.compose[0]`) for a compose call on `project`. */
55
+ export declare function composeArgs(engine: ComposeEngine, project: string, ...rest: string[]): string[];
56
+ /** The executable for compose calls. */
57
+ export declare function composeBin(engine: ComposeEngine): string;
58
+ /** `[file, args]` for a container-CLI call (`ps`, `volume ls`, …) on the engine's daemon. */
59
+ export declare function cliCall(engine: Pick<ComposeEngine, "cliArgv">, ...args: string[]): [string, string[]];
60
+ /** True for the Compose v2 plugin (`docker compose`, `podman compose`). */
61
+ export declare function isComposePlugin(engine: ComposeEngine): boolean;
@@ -0,0 +1,129 @@
1
+ import path from "node:path";
2
+ import { ENGINE_PROBE_TIMEOUT_MS, runSafe } from "../utils/exec.js";
3
+ /** Auto-detection order: Compose v2 plugin first, then Podman, then standalone binaries. */
4
+ export const ENGINE_CANDIDATES = [
5
+ ["docker", "compose"],
6
+ ["podman", "compose"],
7
+ ["docker-compose"],
8
+ ["podman-compose"],
9
+ ];
10
+ export const NO_ENGINE_MESSAGE = `No container compose tool found. Install Docker with Compose v2, or Podman ` +
11
+ `(podman compose / podman-compose), or set WTC_COMPOSE_COMMAND / "composeCommand".`;
12
+ const defaultProbe = (argv) => runSafe(argv[0], [...argv.slice(1), "version"], { timeoutMs: ENGINE_PROBE_TIMEOUT_MS }) !== null;
13
+ /**
14
+ * `<cliArgv> info`: talks to the daemon (or podman machine), so it exits
15
+ * non-zero when that is down — unlike `version`, which succeeds client-only.
16
+ */
17
+ export function daemonCheckArgs(engine) {
18
+ return cliCall(engine, "info");
19
+ }
20
+ const defaultDaemonProbe = (cliArgv) => {
21
+ const [file, args] = daemonCheckArgs({ cliArgv });
22
+ return runSafe(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS }) !== null;
23
+ };
24
+ let detected = null;
25
+ export function engineFromArgv(argv) {
26
+ const cli = path.basename(argv[0]).includes("podman") ? "podman" : "docker";
27
+ // `<bin> [global flags…] compose`: everything before the `compose`
28
+ // subcommand also applies to plain container-CLI calls.
29
+ const sub = argv.indexOf("compose", 1);
30
+ const cliArgv = sub > 0 ? argv.slice(0, sub) : [cli];
31
+ return { compose: argv, cli, cliArgv, label: argv.join(" ") };
32
+ }
33
+ function splitCommand(value) {
34
+ return value.trim().split(/\s+/).filter(Boolean);
35
+ }
36
+ function fromConfig(value, source) {
37
+ const argv = typeof value === "string"
38
+ ? splitCommand(value)
39
+ : Array.isArray(value) && value.every((v) => typeof v === "string")
40
+ ? value.filter((v) => v.trim() !== "")
41
+ : null;
42
+ if (!argv || argv.length === 0) {
43
+ throw new Error(`Invalid ${source}: expected a command such as "docker compose" or ["podman", "compose"].`);
44
+ }
45
+ return argv;
46
+ }
47
+ /** True when `argv` is exactly one of the known compose commands. */
48
+ export function isKnownComposeCommand(argv) {
49
+ return ENGINE_CANDIDATES.some((c) => c.length === argv.length && c.every((part, i) => part === argv[i]));
50
+ }
51
+ /**
52
+ * Pick the compose command: `WTC_COMPOSE_COMMAND`, then config
53
+ * `composeCommand`, then auto-detection (cached per process). Resolved
54
+ * lazily — only commands that touch containers need it, so `promote` works
55
+ * without Docker installed.
56
+ *
57
+ * `composeCommand` comes from a file committed to the repository, so it may
58
+ * only *choose* one of the known compose tools: an arbitrary argv there
59
+ * would let a cloned repo run any program — even from `wtc doctor` /
60
+ * `wtc_doctor`, which agents treat as read-only — and extra flags such as
61
+ * `docker --config ./dir compose` load repo-shipped CLI plugins. Custom
62
+ * commands belong in `WTC_COMPOSE_COMMAND`, which the user controls.
63
+ *
64
+ * Auto-detection finds the installed candidates (`version` succeeds,
65
+ * which needs no daemon). When more than one is installed it prefers the
66
+ * first whose daemon answers (`info`), so a quit Docker Desktop does not
67
+ * shadow a running Podman; when none answers — or only one is installed —
68
+ * it takes the first installed one.
69
+ */
70
+ export function resolveEngine(config, env = process.env, probe, daemonProbe) {
71
+ const fromEnv = env.WTC_COMPOSE_COMMAND;
72
+ if (fromEnv !== undefined && fromEnv.trim() !== "") {
73
+ return engineFromArgv(fromConfig(fromEnv, "WTC_COMPOSE_COMMAND"));
74
+ }
75
+ if (config.composeCommand !== undefined) {
76
+ const argv = fromConfig(config.composeCommand, `"composeCommand" config`);
77
+ if (!isKnownComposeCommand(argv)) {
78
+ throw new Error(`"composeCommand" ${JSON.stringify(argv.join(" "))} is not a known compose tool ` +
79
+ `(${ENGINE_CANDIDATES.map((c) => c.join(" ")).join(", ")}). ` +
80
+ `Repository config may only choose one of those; to run a custom command, ` +
81
+ `set WTC_COMPOSE_COMMAND in your environment.`);
82
+ }
83
+ return engineFromArgv(argv);
84
+ }
85
+ const injected = probe !== undefined || daemonProbe !== undefined;
86
+ if (!injected && detected)
87
+ return detected;
88
+ const check = probe ?? defaultProbe;
89
+ // An injected version probe without a daemon probe means "daemons are up".
90
+ const daemonProbeFn = daemonProbe ?? (probe ? () => true : defaultDaemonProbe);
91
+ const installed = ENGINE_CANDIDATES.filter((candidate) => check(candidate)).map(engineFromArgv);
92
+ if (installed.length === 0)
93
+ throw new Error(NO_ENGINE_MESSAGE);
94
+ let chosen = installed[0];
95
+ if (installed.length > 1) {
96
+ // `docker compose` and `docker-compose` share a daemon: ask it once.
97
+ const answers = new Map();
98
+ const daemonUp = (engine) => {
99
+ const key = engine.cliArgv.join("\0");
100
+ if (!answers.has(key))
101
+ answers.set(key, daemonProbeFn(engine.cliArgv));
102
+ return answers.get(key) === true;
103
+ };
104
+ chosen = installed.find(daemonUp) ?? installed[0];
105
+ }
106
+ if (!injected)
107
+ detected = chosen;
108
+ return chosen;
109
+ }
110
+ /** Forget the cached auto-detected engine (tests). */
111
+ export function resetEngineCache() {
112
+ detected = null;
113
+ }
114
+ /** Arguments (after `engine.compose[0]`) for a compose call on `project`. */
115
+ export function composeArgs(engine, project, ...rest) {
116
+ return [...engine.compose.slice(1), "-p", project, ...rest];
117
+ }
118
+ /** The executable for compose calls. */
119
+ export function composeBin(engine) {
120
+ return engine.compose[0];
121
+ }
122
+ /** `[file, args]` for a container-CLI call (`ps`, `volume ls`, …) on the engine's daemon. */
123
+ export function cliCall(engine, ...args) {
124
+ return [engine.cliArgv[0], [...engine.cliArgv.slice(1), ...args]];
125
+ }
126
+ /** True for the Compose v2 plugin (`docker compose`, `podman compose`). */
127
+ export function isComposePlugin(engine) {
128
+ return engine.compose.length >= 2 && engine.compose.includes("compose", 1);
129
+ }
@@ -0,0 +1,15 @@
1
+ import type { PortMapping } from "../ports/types.js";
2
+ import type { ComposeFile } from "./types.js";
3
+ /**
4
+ * Compose settings that defeat per-worktree isolation: a fixed
5
+ * `container_name` (the second stack cannot start), and volumes/networks with
6
+ * a fixed `name:` or `external` (every stack shares them).
7
+ */
8
+ export declare function composeIsolationWarnings(composeFile: ComposeFile): string[];
9
+ /** Raw `host:container` port mappings that cannot be remapped per worktree. */
10
+ export declare function rawPortWarnings(portMappings: PortMapping[]): string[];
11
+ /**
12
+ * Advisory cross-worktree collision warning over the indices actually in use
13
+ * (live worktrees plus orphans that still reserve theirs).
14
+ */
15
+ export declare function portCollisionWarnings(portMappings: PortMapping[], portStride: number, indices: number[]): string[];
@@ -0,0 +1,62 @@
1
+ import { suggestEnvVar } from "../ports/extract.js";
2
+ import { detectCrossWorktreeCollisions, recommendPortStride, } from "../ports/allocate.js";
3
+ import { isProjectScopedName } from "./parse.js";
4
+ /**
5
+ * Compose settings that defeat per-worktree isolation: a fixed
6
+ * `container_name` (the second stack cannot start), and volumes/networks with
7
+ * a fixed `name:` or `external` (every stack shares them).
8
+ */
9
+ export function composeIsolationWarnings(composeFile) {
10
+ const warnings = [];
11
+ for (const svc of composeFile.services) {
12
+ if (svc.containerName && !isProjectScopedName(svc.containerName)) {
13
+ warnings.push(`Service "${svc.name}" sets container_name "${svc.containerName}" — every worktree stack would use the same name and the second one fails to start. Remove container_name.`);
14
+ }
15
+ }
16
+ for (const v of composeFile.sharedVolumes) {
17
+ warnings.push(`Volume "${v.key}" has a fixed name/external — it is shared by every worktree stack (not isolated).`);
18
+ }
19
+ for (const n of composeFile.sharedNetworks) {
20
+ warnings.push(`Network "${n.key}" has a fixed name/external — it is shared by every worktree stack (not isolated).`);
21
+ }
22
+ return warnings;
23
+ }
24
+ /** Raw `host:container` port mappings that cannot be remapped per worktree. */
25
+ export function rawPortWarnings(portMappings) {
26
+ return portMappings
27
+ .filter((m) => m.envVar === null)
28
+ .map((p) => `Service "${p.serviceName}" uses a raw port mapping (${p.raw}). ` +
29
+ `To enable port isolation, change it to: "\${${suggestEnvVar(p.serviceName)}:-${p.defaultPort}}:${p.containerPort}"`);
30
+ }
31
+ /**
32
+ * Advisory cross-worktree collision warning over the indices actually in use
33
+ * (live worktrees plus orphans that still reserve theirs).
34
+ */
35
+ export function portCollisionWarnings(portMappings, portStride, indices) {
36
+ const inUse = [...new Set(indices)];
37
+ if (inUse.length < 2)
38
+ return [];
39
+ // Collision detection is advisory; an allocation failure here must never
40
+ // abort the command that triggered the warning.
41
+ let collisions;
42
+ try {
43
+ collisions = detectCrossWorktreeCollisions(portMappings, portStride, inUse);
44
+ }
45
+ catch {
46
+ return [];
47
+ }
48
+ if (collisions.length === 0)
49
+ return [];
50
+ const examples = collisions
51
+ .slice(0, 3)
52
+ .map((c) => `${c.port} (wt${c.a.worktreeIndex}/${c.a.serviceName} ↔ wt${c.b.worktreeIndex}/${c.b.serviceName})`)
53
+ .join(", ");
54
+ const recommended = recommendPortStride(portMappings, Math.max(...inUse));
55
+ const fix = recommended > 0
56
+ ? `Set "portStride": ${recommended} in .wtcrc.json (or package.json#wtc) to resolve.`
57
+ : `No single portStride resolves this — check for services sharing the same default port.`;
58
+ return [
59
+ `Cross-worktree port collisions detected with portStride=${portStride} ` +
60
+ `across worktrees ${inUse.sort((a, b) => a - b).join(", ")}: ${collisions.length} collision(s), e.g. ${examples}. ${fix}`,
61
+ ];
62
+ }
@@ -1,2 +1,7 @@
1
1
  import type { ComposeFile } from "./types.js";
2
+ /**
3
+ * A name built from `${COMPOSE_PROJECT_NAME}` is still per-stack: wtc sets
4
+ * that variable for every worktree (process env and root env file).
5
+ */
6
+ export declare function isProjectScopedName(name: string): boolean;
2
7
  export declare function parseComposeFile(composePath: string): ComposeFile;
@@ -27,6 +27,7 @@ function parseServiceBuild(build) {
27
27
  return {
28
28
  context: typeof obj.context === "string" ? obj.context : undefined,
29
29
  dockerfile: typeof obj.dockerfile === "string" ? obj.dockerfile : undefined,
30
+ ...(typeof obj.dockerfile_inline === "string" ? { inline: true } : {}),
30
31
  };
31
32
  }
32
33
  return undefined;
@@ -52,10 +53,65 @@ function parseServicesObject(doc, sourcePath) {
52
53
  ports: parseServicePorts(s.ports),
53
54
  build: parseServiceBuild(s.build),
54
55
  envFile: parseEnvFile(s.env_file),
56
+ ...(typeof s.container_name === "string" && s.container_name
57
+ ? { containerName: s.container_name }
58
+ : {}),
55
59
  sourcePath,
56
60
  };
57
61
  });
58
62
  }
63
+ /**
64
+ * Top-level `volumes:` / `networks:` entries. Only `name:` and `external`
65
+ * matter to wtc: either one takes the resource out of the project scope, so
66
+ * every worktree stack would share it.
67
+ */
68
+ function parseResources(section) {
69
+ const out = new Map();
70
+ if (!section || typeof section !== "object" || Array.isArray(section)) {
71
+ return out;
72
+ }
73
+ for (const [key, raw] of Object.entries(section)) {
74
+ const def = raw && typeof raw === "object" ? raw : {};
75
+ // `external: true`, or the legacy `external: { name: x }` form.
76
+ const external = def.external === true ||
77
+ (typeof def.external === "object" && def.external !== null);
78
+ const legacyName = typeof def.external === "object" && def.external !== null
79
+ ? def.external.name
80
+ : undefined;
81
+ const name = typeof def.name === "string" && def.name
82
+ ? def.name
83
+ : typeof legacyName === "string" && legacyName
84
+ ? legacyName
85
+ : undefined;
86
+ out.set(key, { ...(name ? { name } : {}), external });
87
+ }
88
+ return out;
89
+ }
90
+ /** Later definitions override earlier ones field by field, like services. */
91
+ function mergeResources(into, from) {
92
+ for (const [key, def] of from) {
93
+ const existing = into.get(key);
94
+ into.set(key, existing
95
+ ? { name: def.name ?? existing.name, external: def.external || existing.external }
96
+ : def);
97
+ }
98
+ }
99
+ /**
100
+ * A name built from `${COMPOSE_PROJECT_NAME}` is still per-stack: wtc sets
101
+ * that variable for every worktree (process env and root env file).
102
+ */
103
+ export function isProjectScopedName(name) {
104
+ return /\$\{?COMPOSE_PROJECT_NAME\b/.test(name);
105
+ }
106
+ function sharedOnly(defs) {
107
+ const out = [];
108
+ for (const [key, def] of defs) {
109
+ if (!def.external && (!def.name || isProjectScopedName(def.name)))
110
+ continue;
111
+ out.push({ key, ...(def.name ? { name: def.name } : {}), external: def.external });
112
+ }
113
+ return out;
114
+ }
59
115
  /**
60
116
  * Normalize a top-level `include:` value into a list of resolved absolute
61
117
  * paths. Each entry is a string path or a long-form object whose `path` is a
@@ -113,6 +169,9 @@ function mergeService(base, override) {
113
169
  ports,
114
170
  build: override.build ?? base.build,
115
171
  envFile: override.envFile ?? base.envFile,
172
+ ...((override.containerName ?? base.containerName)
173
+ ? { containerName: override.containerName ?? base.containerName }
174
+ : {}),
116
175
  sourcePath,
117
176
  };
118
177
  }
@@ -131,35 +190,54 @@ function foldServices(services) {
131
190
  }
132
191
  return [...byName.values()];
133
192
  }
134
- function parseRecursive(filePath, seen, sourceFiles) {
193
+ function parseRecursive(filePath, st) {
135
194
  if (!fs.existsSync(filePath)) {
136
195
  console.warn(`wtc: included compose file not found, skipping: ${filePath}`);
137
196
  return [];
138
197
  }
139
198
  // Key on the realpath so symlinked duplicates and cycles are caught.
140
199
  const key = fs.realpathSync.native(filePath);
141
- if (seen.has(key))
200
+ if (st.seen.has(key))
142
201
  return [];
143
- seen.add(key);
202
+ st.seen.add(key);
144
203
  const raw = fs.readFileSync(filePath, "utf-8");
145
- const doc = parseYaml(raw, { uniqueKeys: false });
204
+ let doc;
205
+ try {
206
+ doc = parseYaml(raw, { uniqueKeys: false });
207
+ }
208
+ catch (err) {
209
+ throw new Error(`Invalid YAML in ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
210
+ }
146
211
  if (!doc || typeof doc !== "object")
147
212
  return [];
148
- sourceFiles.push(key);
213
+ st.sourceFiles.push(key);
149
214
  // Recurse into includes first so local services can override included ones.
150
215
  let included = [];
151
216
  if ("include" in doc) {
152
217
  for (const inc of normalizeIncludes(doc.include, filePath)) {
153
- included = included.concat(parseRecursive(inc, seen, sourceFiles));
218
+ included = included.concat(parseRecursive(inc, st));
154
219
  }
155
220
  }
156
- const local = parseServicesObject(doc, key);
221
+ const record = doc;
222
+ mergeResources(st.volumes, parseResources(record.volumes));
223
+ mergeResources(st.networks, parseResources(record.networks));
224
+ const local = parseServicesObject(record, key);
157
225
  return foldServices([...included, ...local]);
158
226
  }
159
227
  export function parseComposeFile(composePath) {
160
228
  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 };
229
+ const st = {
230
+ seen: new Set(),
231
+ sourceFiles: [],
232
+ volumes: new Map(),
233
+ networks: new Map(),
234
+ };
235
+ const services = parseRecursive(abs, st);
236
+ return {
237
+ services,
238
+ composePath: abs,
239
+ sourceFiles: st.sourceFiles,
240
+ sharedVolumes: sharedOnly(st.volumes),
241
+ sharedNetworks: sharedOnly(st.networks),
242
+ };
165
243
  }
@@ -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;