worktree-compose 1.1.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +66 -720
  3. package/SKILL.md +73 -76
  4. package/dist/cli.js +85 -10
  5. package/dist/commands/down.d.ts +2 -0
  6. package/dist/commands/down.js +7 -0
  7. package/dist/commands/list.d.ts +2 -0
  8. package/dist/commands/list.js +43 -6
  9. package/dist/commands/passthrough.d.ts +13 -0
  10. package/dist/commands/passthrough.js +27 -0
  11. package/dist/commands/stop.d.ts +3 -1
  12. package/dist/commands/stop.js +2 -2
  13. package/dist/compose/detect.d.ts +19 -0
  14. package/dist/compose/detect.js +56 -0
  15. package/dist/compose/isolation.d.ts +20 -7
  16. package/dist/compose/isolation.js +88 -36
  17. package/dist/compose/override.d.ts +54 -4
  18. package/dist/compose/override.js +179 -52
  19. package/dist/compose/parse.d.ts +11 -0
  20. package/dist/compose/parse.js +260 -13
  21. package/dist/compose/status.d.ts +14 -0
  22. package/dist/compose/status.js +58 -1
  23. package/dist/compose/types.d.ts +56 -0
  24. package/dist/config.d.ts +33 -0
  25. package/dist/context.d.ts +26 -0
  26. package/dist/context.js +140 -29
  27. package/dist/core/clean.d.ts +3 -1
  28. package/dist/core/clean.js +8 -3
  29. package/dist/core/compose.d.ts +87 -13
  30. package/dist/core/compose.js +282 -57
  31. package/dist/core/doctor.d.ts +2 -8
  32. package/dist/core/doctor.js +116 -79
  33. package/dist/core/down.d.ts +37 -0
  34. package/dist/core/down.js +54 -0
  35. package/dist/core/health.d.ts +90 -0
  36. package/dist/core/health.js +198 -0
  37. package/dist/core/list.d.ts +53 -6
  38. package/dist/core/list.js +144 -58
  39. package/dist/core/passthrough.d.ts +69 -0
  40. package/dist/core/passthrough.js +216 -0
  41. package/dist/core/promote.d.ts +4 -2
  42. package/dist/core/promote.js +5 -3
  43. package/dist/core/restart.d.ts +3 -3
  44. package/dist/core/restart.js +6 -5
  45. package/dist/core/seed.d.ts +50 -0
  46. package/dist/core/seed.js +245 -0
  47. package/dist/core/shared.d.ts +63 -0
  48. package/dist/core/shared.js +194 -0
  49. package/dist/core/start.d.ts +32 -5
  50. package/dist/core/start.js +297 -49
  51. package/dist/core/stop.d.ts +3 -1
  52. package/dist/core/stop.js +6 -3
  53. package/dist/core/teardown.d.ts +5 -2
  54. package/dist/core/teardown.js +33 -8
  55. package/dist/core/types.d.ts +2 -0
  56. package/dist/git/promote.d.ts +11 -3
  57. package/dist/git/promote.js +19 -5
  58. package/dist/mcp/server.js +154 -28
  59. package/dist/ports/allocate.d.ts +35 -23
  60. package/dist/ports/allocate.js +108 -58
  61. package/dist/ports/probe.d.ts +11 -0
  62. package/dist/ports/probe.js +40 -0
  63. package/dist/ports/types.d.ts +5 -0
  64. package/dist/selectors.d.ts +17 -0
  65. package/dist/selectors.js +19 -0
  66. package/dist/state/registry.d.ts +23 -3
  67. package/dist/state/registry.js +57 -17
  68. package/dist/sync/env.d.ts +42 -2
  69. package/dist/sync/env.js +79 -8
  70. package/dist/sync/envsync.d.ts +91 -0
  71. package/dist/sync/envsync.js +338 -0
  72. package/dist/sync/files.d.ts +87 -5
  73. package/dist/sync/files.js +343 -18
  74. package/dist/utils/paths.d.ts +2 -0
  75. package/dist/utils/paths.js +9 -0
  76. package/package.json +9 -2
  77. package/wtc.schema.json +155 -13
package/dist/context.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import path from "node:path";
2
- import { detectComposeFile } from "./compose/detect.js";
3
- import { parseComposeFile } from "./compose/parse.js";
2
+ import { resolveComposeRoots } from "./compose/detect.js";
3
+ import { parseComposeFiles } from "./compose/parse.js";
4
4
  import { resolveEngine } from "./compose/engine.js";
5
5
  import { createStackProbe } from "./compose/status.js";
6
- import { composeIsolationWarnings, portCollisionWarnings, rawPortWarnings, remapNotes, } from "./compose/isolation.js";
7
- import { decideRemap } from "./compose/override.js";
6
+ import { composeIsolationWarnings, rawPortWarnings, remapNotes, } from "./compose/isolation.js";
7
+ import { decideRemap, remapBlocker } from "./compose/override.js";
8
8
  import { extractPortMappings } from "./ports/extract.js";
9
9
  import { loadConfig } from "./config.js";
10
10
  import { assertMainCheckout, getRepoInfo, listRepoWorktrees } from "./git/repo.js";
@@ -96,15 +96,40 @@ export function buildContext(cli = {}, opts = {}) {
96
96
  assertMainCheckout(repo, opts.requireMainFor);
97
97
  const repoRoot = repo.mainRoot;
98
98
  const warnings = [...repo.warnings];
99
- const composePath = detectComposeFile(repoRoot);
100
- if (!composePath && !opts.allowMissingCompose) {
101
- throw new Error(`No compose file found in ${repoRoot}. Expected one of: compose.yaml, compose.yml, docker-compose.yaml, docker-compose.yml`);
99
+ const config = resolveConfig(loadConfig(repoRoot), cli);
100
+ let roots;
101
+ try {
102
+ roots = resolveComposeRoots(repoRoot, config.composeFile);
103
+ }
104
+ catch (err) {
105
+ // Commands that work without a compose file (promote, clean, prune) carry on without one.
106
+ if (!opts.allowMissingCompose)
107
+ throw err;
108
+ warnings.push(err instanceof Error ? err.message : String(err));
109
+ roots = { files: [], custom: false };
102
110
  }
111
+ if (roots.files.length === 0 && !opts.allowMissingCompose) {
112
+ throw new Error(`No compose file found in ${repoRoot}. Expected one of: compose.yaml, compose.yml, docker-compose.yaml, docker-compose.yml ` +
113
+ `(or set "composeFile" in .wtcrc.json to where yours is).`);
114
+ }
115
+ if (roots.note)
116
+ warnings.push(roots.note);
117
+ const composePath = roots.files[0] ?? null;
103
118
  const composeFile = composePath
104
- ? parseComposeFile(composePath)
119
+ ? parseComposeFiles(roots.files)
105
120
  : emptyComposeFile(path.join(repoRoot, "compose.yaml"));
106
- const portMappings = extractPortMappings(composeFile.services);
107
- const config = resolveConfig(loadConfig(repoRoot), cli);
121
+ const shared = sharedServices(config, composeFile);
122
+ const composeVars = new Set(extractPortMappings(composeFile.services).flatMap((m) => (m.envVar ? [m.envVar] : [])));
123
+ const clashing = Object.keys(config.ports ?? {}).filter((name) => composeVars.has(name));
124
+ for (const name of clashing) {
125
+ warnings.push(`"ports.${name}" is ignored: the compose file already publishes a port through \${${name}}, which is the variable's one value.`);
126
+ }
127
+ const hostPortMappings = hostPorts(config).filter((m) => !clashing.includes(m.envVar));
128
+ // A shared service runs once, in the main checkout: a worktree stack publishes no port for it.
129
+ const portMappings = [
130
+ ...extractPortMappings(composeFile.services).filter((m) => !shared.has(m.serviceName)),
131
+ ...hostPortMappings,
132
+ ];
108
133
  const portStride = config.portStride ?? 1;
109
134
  if (!Number.isInteger(portStride) || portStride < 1) {
110
135
  throw new Error(`Invalid "portStride": ${String(portStride)}. Expected a positive integer.`);
@@ -152,32 +177,39 @@ export function buildContext(cli = {}, opts = {}) {
152
177
  warnings.push(`The main checkout ${u.path} was worktree ${u.index} (${u.project}) before it became the main checkout; ` +
153
178
  `wtc leaves that stack alone (stop or remove it yourself if you no longer need it).`);
154
179
  }
155
- const decision = opts.probeStacks || opts.resolveRemap
156
- ? decideRemap({
157
- composeFile,
158
- mappings: portMappings,
159
- mainRoot: repoRoot,
160
- commonDir: repo.commonDir,
161
- envFiles: [
162
- findEnvSource(repoRoot, { dir: "", label: "root", envFileName: config.envFile ?? DEFAULT_ENV_FILE }),
163
- path.join(repoRoot, DEFAULT_ENV_FILE),
164
- ],
165
- envOverrides: config.envOverrides,
166
- engine: getEngine,
167
- })
180
+ const remapResolved = Boolean(opts.probeStacks || opts.resolveRemap);
181
+ const customRoots = roots.custom ? roots.files.map((f) => path.relative(repoRoot, f)) : [];
182
+ const remapInputs = {
183
+ mainRoot: repoRoot,
184
+ commonDir: repo.commonDir,
185
+ composeRoots: customRoots,
186
+ envFiles: [
187
+ findEnvSource(repoRoot, { dir: "", label: "root", envFileName: config.envFile ?? DEFAULT_ENV_FILE }),
188
+ path.join(repoRoot, DEFAULT_ENV_FILE),
189
+ ],
190
+ envOverrides: config.envOverrides,
191
+ engine: getEngine,
192
+ };
193
+ const decision = remapResolved
194
+ ? decideRemap({ composeFile, mappings: portMappings, ...remapInputs })
168
195
  : { targets: null, problem: null, warnings: [] };
169
196
  const remap = decision.targets;
170
197
  const remapped = remap?.ports ?? [];
198
+ let remapPossible = remap ? true : decision.problem ? false : null;
199
+ const canRemap = () => {
200
+ if (!remapResolved)
201
+ return false;
202
+ if (remapPossible === null) {
203
+ const blocker = remapBlocker(remapInputs);
204
+ remapPossible = blocker.problem === null && blocker.engine;
205
+ }
206
+ return remapPossible;
207
+ };
171
208
  const isolationWarnings = [
172
209
  ...(decision.problem ? [decision.problem] : []),
173
210
  ...decision.warnings,
174
211
  ...rawPortWarnings(portMappings, remapped),
175
- ...composeIsolationWarnings(composeFile, new Set(remap?.containerNames.map((c) => c.service))),
176
- ...portCollisionWarnings(portMappings, portStride, [
177
- ...reconciled.worktrees.map((w) => w.index),
178
- ...reconciled.orphans.map((o) => o.index),
179
- ...reconciled.unavailable.map((u) => u.index),
180
- ], remapped),
212
+ ...composeIsolationWarnings(composeFile, new Set(remap?.containerNames.map((c) => c.service)), new Set(remap?.networks)),
181
213
  ];
182
214
  return {
183
215
  repo,
@@ -185,6 +217,10 @@ export function buildContext(cli = {}, opts = {}) {
185
217
  repoName: repo.repoName,
186
218
  cwd,
187
219
  composeFile,
220
+ composeRoots: roots.files.length > 0 ? roots.files : [composeFile.composePath],
221
+ composeIsCustom: roots.custom,
222
+ customComposeRoots: customRoots,
223
+ sharedServices: shared,
188
224
  hasComposeFile: composePath !== null,
189
225
  portMappings,
190
226
  config,
@@ -197,10 +233,29 @@ export function buildContext(cli = {}, opts = {}) {
197
233
  isolationWarnings,
198
234
  remap,
199
235
  remapNotes: remap ? remapNotes(remap, portMappings) : [],
236
+ canRemap,
237
+ hostPortMappings,
200
238
  stacks,
201
239
  getEngine,
202
240
  };
203
241
  }
242
+ /** The config's `shared` services that exist in the compose file. */
243
+ export function sharedServices(config, composeFile) {
244
+ const declared = new Set(composeFile.services.map((s) => s.name));
245
+ return new Set((config.shared ?? []).filter((name) => declared.has(name)));
246
+ }
247
+ /** Service name host-process ports are listed under (no compose service has it: parentheses are not allowed). */
248
+ export const HOST_PORTS_SERVICE = "(host)";
249
+ /** The config's `ports` as variable mappings, so they are allocated, recorded and injected like compose's. */
250
+ export function hostPorts(config) {
251
+ return Object.entries(config.ports ?? {}).map(([envVar, defaultPort]) => ({
252
+ serviceName: HOST_PORTS_SERVICE,
253
+ envVar,
254
+ defaultPort,
255
+ containerPort: defaultPort,
256
+ raw: "",
257
+ }));
258
+ }
204
259
  /** Merge CLI overrides over the loaded config and validate it. */
205
260
  export function resolveConfig(config, cli) {
206
261
  const envFile = cli.envFile ?? config.envFile ?? DEFAULT_ENV_FILE;
@@ -225,6 +280,42 @@ export function resolveConfig(config, cli) {
225
280
  cmd.every((c) => typeof c === "string" && c.trim() !== ""))) {
226
281
  throw new Error(`Invalid "composeCommand" config: expected a command string such as "podman compose" or an array such as ["docker-compose"].`);
227
282
  }
283
+ if (config.ports !== undefined) {
284
+ const ports = config.ports;
285
+ if (typeof ports !== "object" || ports === null || Array.isArray(ports)) {
286
+ throw new Error(`Invalid "ports" config: expected an object of VARIABLE -> default port.`);
287
+ }
288
+ for (const [name, port] of Object.entries(ports)) {
289
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) {
290
+ throw new Error(`Invalid "ports" config: "${name}" is not an upper-case variable name such as "PORT".`);
291
+ }
292
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
293
+ throw new Error(`Invalid "ports.${name}": expected a port number (got ${JSON.stringify(port)}).`);
294
+ }
295
+ }
296
+ }
297
+ for (const key of ["services", "shared"]) {
298
+ const value = config[key];
299
+ if (value !== undefined &&
300
+ (!Array.isArray(value) || value.some((v) => typeof v !== "string" || v.trim() === ""))) {
301
+ throw new Error(`Invalid "${key}" config: expected an array of service names.`);
302
+ }
303
+ }
304
+ const seed = config.seedVolumes;
305
+ if (seed !== undefined &&
306
+ typeof seed !== "boolean" &&
307
+ !(Array.isArray(seed) && seed.every((v) => typeof v === "string" && v.trim() !== ""))) {
308
+ throw new Error(`Invalid "seedVolumes" config: expected true, false, or an array of volume names.`);
309
+ }
310
+ if (config.rewriteEnvPorts !== undefined && typeof config.rewriteEnvPorts !== "boolean") {
311
+ throw new Error(`Invalid "rewriteEnvPorts" config: expected true or false.`);
312
+ }
313
+ const composeFiles = config.composeFile;
314
+ if (composeFiles !== undefined &&
315
+ !(typeof composeFiles === "string" && composeFiles.trim() !== "") &&
316
+ !(Array.isArray(composeFiles) && composeFiles.length > 0 && composeFiles.every((f) => typeof f === "string" && f.trim() !== ""))) {
317
+ throw new Error(`Invalid "composeFile" config: expected a repo-relative path such as "docker/compose.yml", or an array of them.`);
318
+ }
228
319
  validateOverrides("envOverrides", config.envOverrides);
229
320
  if (config.workspaceEnvOverrides !== undefined) {
230
321
  const map = config.workspaceEnvOverrides;
@@ -274,10 +365,30 @@ export function getEnvTargets(ctx) {
274
365
  label: "root",
275
366
  envFileName,
276
367
  overrides: ctx.config.envOverrides,
368
+ compose: true,
277
369
  },
278
370
  ];
371
+ // A compose file in a subdirectory makes that directory the compose project's:
372
+ // compose reads its `.env` for `${VAR}` values, so the worktree's ports belong there too.
373
+ const composeDir = path.relative(ctx.repoRoot, path.dirname(ctx.composeFile.composePath)).split(path.sep).join("/");
374
+ const outside = composeDir === ".." || composeDir.startsWith("../") || path.isAbsolute(composeDir);
375
+ if (ctx.hasComposeFile && composeDir !== "" && !outside) {
376
+ targets.push({
377
+ dir: composeDir,
378
+ label: `compose directory (${composeDir})`,
379
+ envFileName: DEFAULT_ENV_FILE,
380
+ compose: true,
381
+ });
382
+ }
279
383
  const workspaces = resolveWorkspaces(ctx.repoRoot, ctx.config.workspaces ?? []);
280
384
  for (const ws of workspaces) {
385
+ // The compose directory's `.env` is already a target: the workspace's overrides
386
+ // go to that one. A workspace there with another env file is a target of its own.
387
+ const same = targets.find((t) => t.dir === ws.dir && t.envFileName === envFileName);
388
+ if (same) {
389
+ same.overrides = { ...same.overrides, ...findWorkspaceOverrides(ctx.config.workspaceEnvOverrides, ws, workspaces) };
390
+ continue;
391
+ }
281
392
  targets.push({
282
393
  dir: ws.dir,
283
394
  label: `workspace ${ws.name} (${ws.dir})`,
@@ -59,7 +59,9 @@ export interface CleanResult {
59
59
  * - the env files wtc writes: `<dir>/<envFile>` for the root and each
60
60
  * configured workspace, plus whatever the worktree's last `start` wrote
61
61
  * (`--env`/`--workspace` may name others) — not every `.env.*` file, so an
62
- * edited `.env.test` or `apps/x/.env.production` is the user's work;
62
+ * edited `.env.test` or `apps/x/.env.production` is the user's work, and
63
+ * never one the branch tracks: wtc does not write those, so an edit there
64
+ * is the user's;
63
65
  * - compose sources (incl. includes), synced Dockerfiles and files under
64
66
  * `sync` entries, but only while they are byte-identical to the main
65
67
  * checkout's copy, i.e. exactly what start's sync wrote. An edit made in
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { buildContext, getEnvTargets } from "../context.js";
4
4
  import { runSafe, run } from "../utils/exec.js";
5
5
  import { isWithin } from "../utils/paths.js";
6
- import { getDockerfiles, resolveSyncEntries } from "../sync/files.js";
6
+ import { getDockerfiles, resolveSyncEntries, trackedPaths } from "../sync/files.js";
7
7
  import { getStatusPaths } from "../git/status.js";
8
8
  import { samePath } from "../git/worktree.js";
9
9
  import { forgetRecords } from "../state/registry.js";
@@ -48,7 +48,9 @@ function mirrorsMain(repoRoot, wtPath, rel) {
48
48
  * - the env files wtc writes: `<dir>/<envFile>` for the root and each
49
49
  * configured workspace, plus whatever the worktree's last `start` wrote
50
50
  * (`--env`/`--workspace` may name others) — not every `.env.*` file, so an
51
- * edited `.env.test` or `apps/x/.env.production` is the user's work;
51
+ * edited `.env.test` or `apps/x/.env.production` is the user's work, and
52
+ * never one the branch tracks: wtc does not write those, so an edit there
53
+ * is the user's;
52
54
  * - compose sources (incl. includes), synced Dockerfiles and files under
53
55
  * `sync` entries, but only while they are byte-identical to the main
54
56
  * checkout's copy, i.e. exactly what start's sync wrote. An edit made in
@@ -74,10 +76,13 @@ export function managedPathMatcher(ctx, wtPath, envFiles = []) {
74
76
  catch {
75
77
  envPaths.add(ctx.config.envFile ?? ".env");
76
78
  }
79
+ // wtc never writes an env file the branch tracks, so a change to one is the user's
80
+ // work (when git cannot say, it counts as theirs too).
81
+ const trackedEnv = trackedPaths(wtPath, [...envPaths]);
77
82
  return (rel) => {
78
83
  const p = rel.replace(/\/+$/, "");
79
84
  if (envPaths.has(p))
80
- return true;
85
+ return trackedEnv !== null && !trackedEnv.has(path.normalize(p));
81
86
  const synced = mirrored.has(p) || prefixes.some((pre) => p === pre || p.startsWith(`${pre}/`));
82
87
  return synced && mirrorsMain(ctx.repoRoot, wtPath, p);
83
88
  };
@@ -1,7 +1,8 @@
1
1
  import type { RunResult } from "../utils/exec.js";
2
2
  import type { ComposeEngine } from "../compose/engine.js";
3
- import type { RemapTargets } from "../compose/override.js";
4
- import type { PortAllocation } from "../ports/types.js";
3
+ import type { OverrideExtras, RemapTargets } from "../compose/override.js";
4
+ import type { ComposeFile } from "../compose/types.js";
5
+ import type { PortAllocation, PortMapping } from "../ports/types.js";
5
6
  import type { Reporter } from "../utils/log.js";
6
7
  import type { WtcContext } from "../context.js";
7
8
  import type { CoreIo } from "./types.js";
@@ -17,7 +18,7 @@ export type ComposeCallEnv = Record<string, string | undefined>;
17
18
  * worktree's `.env` exported by direnv or similar) is removed: it names
18
19
  * another stack's files, or an override that is gone.
19
20
  */
20
- export declare function composeEnv(project: string, allocations: PortAllocation[], composeFile?: string | null, commonDir?: string): ComposeCallEnv;
21
+ export declare function composeEnv(project: string, allocations: PortAllocation[], composeFile?: string | null, commonDir?: string, roots?: readonly string[]): ComposeCallEnv;
21
22
  export interface StackTarget {
22
23
  project: string;
23
24
  index: number;
@@ -31,29 +32,99 @@ export interface PreparedStack {
31
32
  composeFile: string | null;
32
33
  /** Hardcoded settings left as they are in this directory, and why. */
33
34
  warnings: string[];
35
+ /** The compose file the stack runs, as wtc read it. */
36
+ view: StackView;
34
37
  }
38
+ /**
39
+ * The compose file a stack runs, as wtc reads it. A worktree runs its own
40
+ * compose file — the branch may add a service, change a port or a
41
+ * Dockerfile — so ports and remapping come from that file, not from the
42
+ * main checkout's, whenever the two differ.
43
+ */
44
+ export interface StackView {
45
+ composeFile: ComposeFile;
46
+ portMappings: PortMapping[];
47
+ /** What wtc can remap for it, before the directory's own compose override counts; null for nothing. */
48
+ remap: RemapTargets | null;
49
+ /** The directory's compose file differs from the main checkout's. */
50
+ own: boolean;
51
+ /** Hardcoded settings of this compose file that are left alone, and why. */
52
+ warnings: string[];
53
+ }
54
+ /** Paths of the stack's compose files in `dir`, mirroring the main checkout's (root file first). */
55
+ export declare function composeFilesIn(ctx: WtcContext, dir: string): string[];
56
+ /** The directory of the stack's first compose file in `dir`: where compose looks for its own override file. */
57
+ export declare function composeDirIn(ctx: WtcContext, dir: string): string;
58
+ /** Directories the main checkout's own stack may run from: its root, and its compose file's directory. */
59
+ export declare function mainStackDirs(ctx: WtcContext): string[];
60
+ /** Compose projects of this repository's worktree stacks (never the main checkout's). */
61
+ export declare function worktreeProjects(ctx: WtcContext): Set<string>;
62
+ export declare function stackView(ctx: WtcContext, dir: string): StackView;
63
+ /** Forget what was read from `dir`'s compose file (after a sync rewrote it). */
64
+ export declare function resetStackView(ctx: WtcContext, dir: string): void;
35
65
  /**
36
66
  * What wtc remaps for a stack run from `dir`, without writing anything: the
37
- * repository's targets minus what the directory's own compose override sets
38
- * for a service — or nothing when its `.env` sets `COMPOSE_FILE` or
67
+ * compose file's targets minus what the directory's own compose override
68
+ * sets for a service — or nothing when its `.env` sets `COMPOSE_FILE` or
39
69
  * `COMPOSE_PATH_SEPARATOR` (a worktree's unmanaged `.env`, with a custom
40
70
  * envFile; the repository's own settings were checked with the context).
41
71
  */
42
- export declare function stackRemap(ctx: WtcContext, dir: string, project: string): {
72
+ export declare function stackRemap(ctx: WtcContext, dir: string, project: string, view?: StackView): {
43
73
  targets: RemapTargets | null;
44
74
  warnings: string[];
45
75
  };
76
+ /** Where a stack's ports come from besides its compose file. */
77
+ export interface PortSources {
78
+ /** Ports the stack already holds, by label (its registry record). */
79
+ recorded?: Record<string, number>;
80
+ /** Ports the repository's other stacks hold. */
81
+ others: ReadonlySet<number>;
82
+ }
83
+ /** The registry's ports as the context read them (a snapshot). */
84
+ export declare function portSources(ctx: WtcContext, project: string): PortSources;
85
+ export interface StackPortOptions {
86
+ view?: StackView;
87
+ /** Host ports found busy: nothing is allocated on them. */
88
+ blocked?: ReadonlySet<number>;
89
+ /** Defaults to the context's snapshot of the registry. */
90
+ sources?: PortSources;
91
+ }
46
92
  /**
47
93
  * The stack's ports: every variable, plus each hardcoded port in `targets`
48
- * that can move in this worktree to a port the stack does not already
49
- * publish (a hardcoded port it keeps, or one inside a range). Returns the
50
- * targets actually remapped and a warning for each port left as it is.
94
+ * that can move. A port the stack already holds (its registry record)
95
+ * stays; a new one starts from the formula and moves past ports another
96
+ * stack holds, ports this stack publishes as written, and `blocked` ones.
97
+ * Returns the targets actually remapped and a warning for each hardcoded
98
+ * port left as it is.
51
99
  */
52
- export declare function stackAllocations(ctx: WtcContext, index: number, targets: RemapTargets | null): {
100
+ export declare function stackAllocations(ctx: WtcContext, target: StackTarget, targets: RemapTargets | null, opts?: StackPortOptions): {
53
101
  allocations: PortAllocation[];
54
102
  targets: RemapTargets | null;
55
103
  warnings: string[];
56
104
  };
105
+ export interface AssignedPorts {
106
+ /** Host ports found taken: pass them to `prepareStack`, which then allocates the same ports. */
107
+ blocked: ReadonlySet<number>;
108
+ /** Ports the stack held that had to move, because something else took them meanwhile. */
109
+ moved: {
110
+ label: string;
111
+ from: number;
112
+ to: number;
113
+ }[];
114
+ }
115
+ /**
116
+ * Settle a stack's host ports before it starts, and record them. A port the
117
+ * stack already holds stays, unless the stack is not running and something
118
+ * else has taken it; a new port starts from the formula and moves past
119
+ * whatever is taken — by another stack of this repository (the registry),
120
+ * by any running container, or by a process listening on the host.
121
+ *
122
+ * The choice is made and recorded under the registry lock, against the
123
+ * registry as it is at that moment, so two `wtc start` runs in different
124
+ * worktrees never settle on the same port. Probing the host happens
125
+ * outside the lock.
126
+ */
127
+ export declare function assignStackPorts(ctx: WtcContext, target: StackTarget, probe: (port: number) => Promise<boolean>, recheck?: (port: number) => Promise<boolean>): Promise<AssignedPorts>;
57
128
  /**
58
129
  * Ports and compose files for one stack: the `COMPOSE_FILE` list compose
59
130
  * would otherwise pick by itself — the compose file, the directory's own
@@ -62,12 +133,15 @@ export declare function stackAllocations(ctx: WtcContext, index: number, targets
62
133
  *
63
134
  * `start` (`write`) writes the override, after syncing the worktree's
64
135
  * compose file from main. `stop` and teardown use the override the stack
65
- * was started with as it is: rewriting it from main's current compose file
66
- * could name services the worktree's (older) compose file does not have,
67
- * which the `COMPOSE_FILE` in the worktree's env file also loads.
136
+ * was started with as it is: rewriting it from the current compose file
137
+ * could name services the stack was not started with.
68
138
  */
69
139
  export declare function prepareStack(ctx: WtcContext, target: StackTarget, opts: {
70
140
  write: boolean;
141
+ blocked?: ReadonlySet<number>;
142
+ extra?: OverrideExtras;
143
+ /** Write nothing at all: a stack without an override runs without one (read-only callers). */
144
+ readOnly?: boolean;
71
145
  }): PreparedStack;
72
146
  export interface ComposeCallOptions {
73
147
  cwd: string;