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,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,26 @@
1
+ import type { PortMapping } from "../ports/types.js";
2
+ import type { RemapTargets } from "./override.js";
3
+ import type { ComposeFile } from "./types.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). Services in
8
+ * `reset` have their container_name dropped at runtime, so they are fine.
9
+ */
10
+ export declare function composeIsolationWarnings(composeFile: ComposeFile, reset?: ReadonlySet<string>): string[];
11
+ /**
12
+ * Hardcoded `host:container` port mappings that stay the same in every
13
+ * worktree: those not in `remapped` (remapped at runtime).
14
+ */
15
+ export declare function rawPortWarnings(portMappings: PortMapping[], remapped?: PortMapping[]): string[];
16
+ /**
17
+ * What runtime remapping does, for `wtc start` (info, not warnings: the
18
+ * stacks no longer collide). Remapped ports have no variable, so env values
19
+ * cannot follow them; the hint says how to give one a name.
20
+ */
21
+ export declare function remapNotes(targets: RemapTargets, portMappings: PortMapping[]): string[];
22
+ /**
23
+ * Advisory cross-worktree collision warning over the indices actually in use
24
+ * (live worktrees plus orphans that still reserve theirs).
25
+ */
26
+ export declare function portCollisionWarnings(portMappings: PortMapping[], portStride: number, indices: number[], remapped?: PortMapping[]): string[];
@@ -0,0 +1,91 @@
1
+ import { suggestEnvVars } 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). Services in
8
+ * `reset` have their container_name dropped at runtime, so they are fine.
9
+ */
10
+ export function composeIsolationWarnings(composeFile, reset = new Set()) {
11
+ const warnings = [];
12
+ for (const svc of composeFile.services) {
13
+ if (svc.containerName && !isProjectScopedName(svc.containerName) && !reset.has(svc.name)) {
14
+ 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.`);
15
+ }
16
+ }
17
+ for (const v of composeFile.sharedVolumes) {
18
+ warnings.push(`Volume "${v.key}" has a fixed name/external — it is shared by every worktree stack (not isolated).`);
19
+ }
20
+ for (const n of composeFile.sharedNetworks) {
21
+ warnings.push(`Network "${n.key}" has a fixed name/external — it is shared by every worktree stack (not isolated).`);
22
+ }
23
+ return warnings;
24
+ }
25
+ /**
26
+ * Hardcoded `host:container` port mappings that stay the same in every
27
+ * worktree: those not in `remapped` (remapped at runtime).
28
+ */
29
+ export function rawPortWarnings(portMappings, remapped = []) {
30
+ const suggestions = suggestEnvVars(portMappings);
31
+ const done = new Set(remapped);
32
+ return portMappings
33
+ .filter((m) => m.envVar === null && !done.has(m))
34
+ .map((p) => p.range
35
+ ? `Service "${p.serviceName}" publishes a host port range (${p.raw}) — every worktree stack binds the same ports. ` +
36
+ `wtc cannot remap ranges; publish single ports, or leave the range out of worktree stacks.`
37
+ : `Service "${p.serviceName}" uses a raw port mapping (${p.raw}). ` +
38
+ `To enable port isolation, change it to: "\${${suggestions.get(p)}:-${p.defaultPort}}:${p.containerPort}"`);
39
+ }
40
+ /**
41
+ * What runtime remapping does, for `wtc start` (info, not warnings: the
42
+ * stacks no longer collide). Remapped ports have no variable, so env values
43
+ * cannot follow them; the hint says how to give one a name.
44
+ */
45
+ export function remapNotes(targets, portMappings) {
46
+ const notes = [];
47
+ if (targets.ports.length > 0) {
48
+ const suggestions = suggestEnvVars(portMappings);
49
+ const first = targets.ports[0];
50
+ notes.push(`Remapping hardcoded host ports per worktree at runtime (your compose file is unchanged): ` +
51
+ `${targets.ports.map((m) => `${m.serviceName} ${m.raw}`).join(", ")}. ` +
52
+ `To use one in env values, give it a variable, e.g. "\${${suggestions.get(first)}:-${first.defaultPort}}:${first.containerPort}".`);
53
+ }
54
+ if (targets.containerNames.length > 0) {
55
+ notes.push(`Dropping fixed container names per worktree at runtime (your compose file is unchanged): ` +
56
+ `${targets.containerNames.map((c) => `${c.service} ("${c.name}")`).join(", ")}.`);
57
+ }
58
+ return notes;
59
+ }
60
+ /**
61
+ * Advisory cross-worktree collision warning over the indices actually in use
62
+ * (live worktrees plus orphans that still reserve theirs).
63
+ */
64
+ export function portCollisionWarnings(portMappings, portStride, indices, remapped = []) {
65
+ const inUse = [...new Set(indices)];
66
+ if (inUse.length < 2)
67
+ return [];
68
+ // Collision detection is advisory; an allocation failure here must never
69
+ // abort the command that triggered the warning.
70
+ let collisions;
71
+ try {
72
+ collisions = detectCrossWorktreeCollisions(portMappings, portStride, inUse, remapped);
73
+ }
74
+ catch {
75
+ return [];
76
+ }
77
+ if (collisions.length === 0)
78
+ return [];
79
+ const examples = collisions
80
+ .slice(0, 3)
81
+ .map((c) => `${c.port} (wt${c.a.worktreeIndex}/${c.a.serviceName} ↔ wt${c.b.worktreeIndex}/${c.b.serviceName})`)
82
+ .join(", ");
83
+ const recommended = recommendPortStride(portMappings, Math.max(...inUse), remapped);
84
+ const fix = recommended > 0
85
+ ? `Set "portStride": ${recommended} in .wtcrc.json (or package.json#wtc) to resolve.`
86
+ : `No single portStride resolves this — check for services sharing the same default port.`;
87
+ return [
88
+ `Cross-worktree port collisions detected with portStride=${portStride} ` +
89
+ `across worktrees ${inUse.sort((a, b) => a - b).join(", ")}: ${collisions.length} collision(s), e.g. ${examples}. ${fix}`,
90
+ ];
91
+ }
@@ -0,0 +1,152 @@
1
+ import type { ComposeEngine } from "./engine.js";
2
+ import type { ComposeFile } from "./types.js";
3
+ import type { PortAllocation, PortMapping } from "../ports/types.js";
4
+ /**
5
+ * Runtime remapping. Two compose settings make every worktree stack collide
6
+ * with the others: a hardcoded host port (`8080:80`) and a fixed
7
+ * `container_name`. Instead of asking for the compose file to be edited, wtc
8
+ * writes a compose override for each worktree stack that replaces the
9
+ * service's `ports` (`!override`, hardcoded host ports swapped for the
10
+ * worktree's allocated ones) and drops `container_name` (`!reset`, keeping
11
+ * the old name as a network alias), and adds it to `COMPOSE_FILE` for every
12
+ * compose call on that stack — and in the worktree's root env file, so plain
13
+ * `docker compose` there agrees. The compose file itself is never changed.
14
+ *
15
+ * A plain override cannot do this: compose merges `ports` lists, so the
16
+ * hardcoded port would still be published. The `!override`/`!reset` tags
17
+ * need Docker Compose 2.24.4+ (and are partial or missing in other
18
+ * engines), so wtc first checks that the engine merges them as expected,
19
+ * and otherwise keeps warning as before.
20
+ */
21
+ /** Override files compose loads next to the compose file, in its order of preference. */
22
+ export declare const USER_OVERRIDE_FILENAMES: string[];
23
+ /** What wtc remaps for a stack. */
24
+ export interface RemapTargets {
25
+ /** Hardcoded host-port mappings: each gets the worktree's allocated port. */
26
+ ports: PortMapping[];
27
+ /**
28
+ * Fixed container names: dropped, so compose names the containers per
29
+ * project. The old name stays reachable inside the stack as a network
30
+ * alias, unless `noAlias` (the user's own override sets the networks).
31
+ */
32
+ containerNames: {
33
+ service: string;
34
+ name: string;
35
+ noAlias?: boolean;
36
+ }[];
37
+ }
38
+ export declare function remapIsEmpty(t: RemapTargets): boolean;
39
+ /**
40
+ * Settings wtc could remap: hardcoded host ports (not ranges) and fixed
41
+ * container names, plus why some are left alone:
42
+ * - a service that uses `extends` may inherit ports wtc cannot see, which
43
+ * a replaced list would drop;
44
+ * - a service from an included file whose ports use variables: compose
45
+ * fills those in from that file's own env (its directory's `.env`), but
46
+ * an override is interpolated with the main project's;
47
+ * - a port too high to move (above 65435);
48
+ * - a container name another service joins by name (`network_mode:
49
+ * container:<name>`, `volumes_from`, `ipc`, `pid`): an alias cannot stand
50
+ * in for a container identity.
51
+ */
52
+ export declare function remapCandidates(composeFile: ComposeFile, mappings: PortMapping[]): {
53
+ targets: RemapTargets;
54
+ skipped: string[];
55
+ };
56
+ /** The compose override file compose would load from `dir` by itself, or null. */
57
+ export declare function findUserOverride(dir: string): string | null;
58
+ /**
59
+ * Leave alone what the user's own compose override in `dir` also sets for
60
+ * a service (`ports` or `extends`, `container_name`): replacing it would
61
+ * discard theirs. A container name one of its services joins by name
62
+ * (`network_mode: container:<name>`, …) is kept too. Where it sets the
63
+ * service's networks, the old container name gets no alias (theirs could
64
+ * be `network_mode`). Returns what remains, with a warning for each
65
+ * setting left alone.
66
+ */
67
+ export declare function withoutUserOverride(targets: RemapTargets, dir: string): {
68
+ targets: RemapTargets;
69
+ warnings: string[];
70
+ };
71
+ /** The separator compose splits `COMPOSE_FILE` on (wtc's calls and the env files it writes). */
72
+ export declare function composePathSeparator(): string;
73
+ /** A `COMPOSE_FILE` value for `files`, or null when a path contains the separator. */
74
+ export declare function composeFileValue(files: string[]): string | null;
75
+ /**
76
+ * The value an env file assigns to `key`: its last assignment, in either
77
+ * form compose's dotenv parser accepts (`KEY=value`, `KEY: value`),
78
+ * unquoted. Null when the file or the key is missing.
79
+ */
80
+ export declare function envFileValue(file: string | null, key: string): string | null;
81
+ /** The `COMPOSE_FILE` an env file sets, or null. */
82
+ export declare function envFileComposeFile(file: string | null): string | null;
83
+ /** Where wtc keeps a stack's override: inside the git directory, never committed. */
84
+ export declare function overridePath(commonDir: string, project: string): string;
85
+ /**
86
+ * True when a `COMPOSE_FILE` value is exactly a list wtc writes — the
87
+ * compose file, then the compose override compose itself would pick in
88
+ * that directory if there is one, then one of wtc's overrides: the line
89
+ * wtc wrote into a worktree's env file, exported into the shell by a tool
90
+ * that loads `.env` (direnv's `dotenv`, mise, autoenv). That is not a file
91
+ * list of the user's, so it must not switch remapping off. Any other list
92
+ * (a file added, another override picked) is the user's.
93
+ */
94
+ export declare function isWtcComposeFile(value: string, commonDir: string): boolean;
95
+ /**
96
+ * Whether the inherited `COMPOSE_FILE` names `file`: a list the shell still
97
+ * holds (direnv, or one the user extended) would break if it were deleted.
98
+ */
99
+ export declare function inheritedComposeFileNames(file: string): boolean;
100
+ /** A `COMPOSE_FILE` the user set (not one wtc wrote), from a value. */
101
+ export declare function isUserComposeFile(value: string | null | undefined, commonDir: string): boolean;
102
+ export declare function writeOverride(file: string, content: string): void;
103
+ export declare function removeOverride(file: string): void;
104
+ /**
105
+ * The override YAML for one stack. A service whose hardcoded ports are
106
+ * remapped gets its whole `ports` list (`!override` replaces it): every
107
+ * entry as written, except the remapped host ports. A service whose
108
+ * container_name is dropped (`!reset`) keeps the old name as an alias on
109
+ * its own networks. Strings are quoted, so YAML 1.1 parsers never read
110
+ * `2222:22` as a base-60 number.
111
+ */
112
+ export declare function renderOverride(project: string, composeFile: ComposeFile, targets: RemapTargets, allocations: PortAllocation[]): string;
113
+ /** True when `config` output shows the probe override applied: one port, published on 2, no container_name. */
114
+ export declare function probeApplied(stdout: string): boolean;
115
+ /** Forget cached probe results (tests). */
116
+ export declare function resetRemapProbeCache(): void;
117
+ /**
118
+ * Whether the engine merges `!override` and `!reset` the way runtime
119
+ * remapping needs: `config` on a throwaway project in a temp directory,
120
+ * passed through `COMPOSE_FILE` exactly like the real override. It needs
121
+ * no daemon and touches no containers. Cached per process and engine (a
122
+ * failure for a minute).
123
+ */
124
+ export declare function engineSupportsRemap(engine: ComposeEngine): boolean;
125
+ export interface RemapDecision {
126
+ /** What wtc remaps at runtime; null when there is nothing to remap or it cannot. */
127
+ targets: RemapTargets | null;
128
+ /** Why the candidates are not remapped, or null. */
129
+ problem: string | null;
130
+ /** Hardcoded settings left alone, and why. */
131
+ warnings: string[];
132
+ }
133
+ export interface RemapInputs {
134
+ composeFile: ComposeFile;
135
+ mappings: PortMapping[];
136
+ /** The main checkout (where its own compose override would be). */
137
+ mainRoot: string;
138
+ /** The git common dir (where wtc keeps the overrides). */
139
+ commonDir: string;
140
+ /**
141
+ * Env files that could carry a `COMPOSE_FILE` of the user's: the root
142
+ * env file wtc copies into worktrees, and the main checkout's `.env`
143
+ * (which compose reads by itself).
144
+ */
145
+ envFiles: (string | null)[];
146
+ /** The root `envOverrides`, which wtc writes into the worktree's env file. */
147
+ envOverrides?: Record<string, string>;
148
+ /** Resolves the engine; throwing means "no engine" (nothing to remap with). */
149
+ engine: () => ComposeEngine;
150
+ }
151
+ /** Decide what to remap for this repository (see the module comment). */
152
+ export declare function decideRemap(inputs: RemapInputs): RemapDecision;