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
@@ -0,0 +1,277 @@
1
+ import net from "node:net";
2
+ import path from "node:path";
3
+ import { buildContext, resolveConfig } from "../context.js";
4
+ import { loadConfigWithSource } from "../config.js";
5
+ import { detectComposeFile } from "../compose/detect.js";
6
+ import { parseComposeFile } from "../compose/parse.js";
7
+ import { daemonCheckArgs, resolveEngine } from "../compose/engine.js";
8
+ import { createStackProbe, stackStatus } from "../compose/status.js";
9
+ import { composeIsolationWarnings, portCollisionWarnings, rawPortWarnings } from "../compose/isolation.js";
10
+ import { extractPortMappings } from "../ports/extract.js";
11
+ import { allocateWorktreePorts } from "../ports/allocate.js";
12
+ import { getRepoInfo } from "../git/repo.js";
13
+ import { ENGINE_PROBE_TIMEOUT_MS, runSafe } from "../utils/exec.js";
14
+ /** True when binding `port` on `host` fails with EADDRINUSE. */
15
+ function bindFails(port, host) {
16
+ return new Promise((resolve) => {
17
+ const server = net.createServer();
18
+ server.unref();
19
+ server.once("error", (err) => {
20
+ resolve(err.code === "EADDRINUSE");
21
+ });
22
+ server.once("listening", () => {
23
+ server.close(() => resolve(false));
24
+ });
25
+ server.listen({ port, host, exclusive: true });
26
+ });
27
+ }
28
+ /**
29
+ * True when something already listens on `port`. Docker publishes on all
30
+ * interfaces, but local dev servers and Homebrew databases usually bind
31
+ * 127.0.0.1 or ::1 only — and on macOS (BSD sockets, libuv's SO_REUSEADDR)
32
+ * a wildcard bind succeeds next to them, so each address is probed. Only
33
+ * EADDRINUSE counts as busy (no IPv6 → not busy).
34
+ */
35
+ export async function isPortBusy(port) {
36
+ for (const host of ["0.0.0.0", "127.0.0.1", "::1"]) {
37
+ if (await bindFails(port, host))
38
+ return true;
39
+ }
40
+ return false;
41
+ }
42
+ function message(err) {
43
+ return err instanceof Error ? err.message : String(err);
44
+ }
45
+ function versionLine(output) {
46
+ if (!output)
47
+ return undefined;
48
+ const lines = output.split("\n").map((l) => l.trim()).filter(Boolean);
49
+ return lines.find((l) => /version/i.test(l)) ?? lines[0];
50
+ }
51
+ /**
52
+ * Diagnose the setup: git, repo layout, compose file, config, compose
53
+ * engine and daemon, port isolation, isolation-breaking compose settings,
54
+ * worktree/registry health, and host ports already taken for stopped stacks.
55
+ * Each check is independent so one failure never hides the others.
56
+ */
57
+ export async function doctor(io) {
58
+ const checks = [];
59
+ const add = (c) => checks.push(c);
60
+ const finish = () => ({ ok: !checks.some((c) => c.status === "fail"), checks });
61
+ const cwd = path.resolve(io.cwd ?? process.cwd());
62
+ // git + repository layout
63
+ const gitVersion = runSafe("git", ["--version"]);
64
+ if (!gitVersion) {
65
+ add({ status: "fail", title: "git not found", hint: "Install git (2.31+ recommended)." });
66
+ return finish();
67
+ }
68
+ add({ status: "ok", title: gitVersion });
69
+ let repo;
70
+ try {
71
+ repo = getRepoInfo(cwd);
72
+ }
73
+ catch (err) {
74
+ add({ status: "fail", title: "Not inside a git repository", detail: message(err), hint: "Run wtc from your project." });
75
+ return finish();
76
+ }
77
+ add({
78
+ status: "ok",
79
+ title: repo.mainRootIsFallback
80
+ ? `Repository "${repo.repoName}"${repo.bare ? " (bare)" : ""}: main checkout unknown, reading files from ${repo.currentRoot}`
81
+ : repo.bare
82
+ ? `Repository "${repo.repoName}" (bare; main checkout ${repo.mainRoot})`
83
+ : `Repository "${repo.repoName}" (main worktree ${repo.mainRoot})`,
84
+ detail: repo.currentRoot !== repo.mainRoot && !repo.mainRootIsFallback
85
+ ? `Running from linked worktree ${repo.currentRoot}; compose, config and env files are read from ${repo.mainRoot}.`
86
+ : undefined,
87
+ });
88
+ for (const w of repo.warnings)
89
+ add({ status: "warn", title: w });
90
+ // compose file
91
+ let composeFile = null;
92
+ const composePath = detectComposeFile(repo.mainRoot);
93
+ if (!composePath) {
94
+ add({
95
+ status: "fail",
96
+ title: "No compose file found",
97
+ detail: `Looked in ${repo.mainRoot}`,
98
+ hint: "Add compose.yaml (or docker-compose.yml) to the main worktree.",
99
+ });
100
+ }
101
+ else {
102
+ try {
103
+ composeFile = parseComposeFile(composePath);
104
+ const includes = composeFile.sourceFiles.length - 1;
105
+ add({
106
+ status: "ok",
107
+ title: `${path.basename(composePath)}: ${composeFile.services.length} service(s)` +
108
+ (includes > 0 ? `, ${includes} included file(s)` : ""),
109
+ detail: includes > 0
110
+ ? composeFile.sourceFiles.slice(1).map((f) => path.relative(repo.mainRoot, f)).join(", ")
111
+ : undefined,
112
+ });
113
+ }
114
+ catch (err) {
115
+ add({ status: "fail", title: `Could not parse ${path.basename(composePath)}`, detail: message(err) });
116
+ }
117
+ }
118
+ // config
119
+ let config = null;
120
+ try {
121
+ const loaded = loadConfigWithSource(repo.mainRoot);
122
+ config = resolveConfig(loaded.config, {});
123
+ add({
124
+ status: "ok",
125
+ title: loaded.source ? `Config: ${path.relative(repo.mainRoot, loaded.source) || loaded.source}` : "No config (zero-config defaults)",
126
+ });
127
+ }
128
+ catch (err) {
129
+ add({ status: "fail", title: "Invalid wtc config", detail: message(err), hint: "Fix .wtcrc.json (or package.json#wtc)." });
130
+ }
131
+ // compose engine + daemon
132
+ let engine = null;
133
+ let composeWorks = false;
134
+ try {
135
+ engine = resolveEngine(config ?? {});
136
+ const output = runSafe(engine.compose[0], [...engine.compose.slice(1), "version"], {
137
+ timeoutMs: ENGINE_PROBE_TIMEOUT_MS,
138
+ });
139
+ composeWorks = output !== null;
140
+ const source = process.env.WTC_COMPOSE_COMMAND?.trim()
141
+ ? "WTC_COMPOSE_COMMAND"
142
+ : config?.composeCommand !== undefined
143
+ ? `"composeCommand" config`
144
+ : null;
145
+ add(composeWorks
146
+ ? { status: "ok", title: `Compose engine: ${engine.label}`, detail: versionLine(output) }
147
+ : {
148
+ status: "fail",
149
+ title: `Compose engine not working: ${engine.label}`,
150
+ detail: `'${engine.label} version' failed (${source ? `set by ${source}` : "auto-detected"}).`,
151
+ hint: source
152
+ ? `Check ${source}: the command must exist and support 'version'.`
153
+ : "Install Docker with Compose v2, or Podman — or set WTC_COMPOSE_COMMAND.",
154
+ });
155
+ }
156
+ catch (err) {
157
+ add({ status: "fail", title: "No compose engine", detail: message(err) });
158
+ }
159
+ let daemonUp = false;
160
+ if (engine) {
161
+ const [file, args] = daemonCheckArgs(engine);
162
+ daemonUp = runSafe(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS }) !== null;
163
+ const start = engine.cli === "podman" ? "Start it with 'podman machine start'" : "Start Docker Desktop (or the docker service)";
164
+ add(daemonUp
165
+ ? { status: "ok", title: `${engine.cli} daemon reachable` }
166
+ : {
167
+ status: "fail",
168
+ title: `${engine.cli} daemon not reachable`,
169
+ hint: `${start}, or set WTC_COMPOSE_COMMAND to use another engine (e.g. "podman compose").`,
170
+ });
171
+ }
172
+ if (!composeFile)
173
+ return finish();
174
+ // ports and isolation
175
+ const mappings = extractPortMappings(composeFile.services);
176
+ const isolatable = mappings.filter((m) => m.envVar !== null);
177
+ if (mappings.length === 0) {
178
+ add({ status: "ok", title: "No published ports" });
179
+ }
180
+ else {
181
+ add({
182
+ status: "ok",
183
+ title: `${isolatable.length} isolatable port(s)`,
184
+ detail: isolatable.map((m) => `${m.serviceName}:${m.envVar}`).join(", ") || undefined,
185
+ });
186
+ }
187
+ for (const w of rawPortWarnings(mappings)) {
188
+ add({ status: "warn", title: "Raw port mapping (not isolated)", detail: w });
189
+ }
190
+ const isolation = composeIsolationWarnings(composeFile);
191
+ if (isolation.length === 0) {
192
+ add({ status: "ok", title: "No container_name or shared volumes/networks" });
193
+ }
194
+ for (const w of isolation) {
195
+ add({ status: "warn", title: "Isolation", detail: w });
196
+ }
197
+ if (!config)
198
+ return finish();
199
+ // worktrees, registry, collisions, busy ports. Read-only: a diagnosis
200
+ // (and the readOnlyHint wtc_doctor) must not assign identities, create
201
+ // worktree ids, or move a corrupt registry aside — it only reports.
202
+ let ctx;
203
+ try {
204
+ ctx = buildContext({}, { cwd, readOnly: true });
205
+ }
206
+ catch (err) {
207
+ add({ status: "fail", title: "Could not load worktrees", detail: message(err) });
208
+ return finish();
209
+ }
210
+ const indices = [
211
+ ...ctx.worktrees.map((w) => w.index),
212
+ ...ctx.orphans.map((o) => o.index),
213
+ ...ctx.unavailable.map((u) => u.index),
214
+ ];
215
+ const collisions = portCollisionWarnings(ctx.portMappings, ctx.portStride, indices);
216
+ if (collisions.length === 0) {
217
+ add({ status: "ok", title: "No cross-worktree port collisions" });
218
+ }
219
+ for (const w of collisions) {
220
+ add({ status: "warn", title: "Port collisions", detail: w });
221
+ }
222
+ // Missing worktrees, registry problems, skipped sync entries.
223
+ for (const w of ctx.warnings) {
224
+ add({ status: "warn", title: w });
225
+ }
226
+ if (ctx.orphans.length > 0) {
227
+ add({
228
+ status: "warn",
229
+ title: `${ctx.orphans.length} orphaned stack record(s)`,
230
+ detail: ctx.orphans.map((o) => `${o.index}:${o.branch} (${o.project})`).join(", "),
231
+ hint: "Their worktrees were removed. Run 'wtc prune' to stop the stacks and free the indices.",
232
+ });
233
+ }
234
+ const probe = createStackProbe(daemonUp && composeWorks ? engine : null, null, ctx.repoRoot);
235
+ const byIndex = [...ctx.worktrees].sort((a, b) => a.index - b.index);
236
+ const summary = byIndex.map((w) => `${w.index}:${w.branch} (${stackStatus(probe.state(w.project))})`);
237
+ add({
238
+ status: "ok",
239
+ title: `${ctx.worktrees.length} worktree(s)`,
240
+ detail: summary.join(", ") || undefined,
241
+ });
242
+ const busy = [];
243
+ let probed = 0;
244
+ for (const wt of byIndex) {
245
+ // Stacks with nothing running (down, or stopped containers) hold no
246
+ // ports themselves, so whatever listens there is something else.
247
+ const state = probe.state(wt.project);
248
+ if (!state || state.running > 0)
249
+ continue;
250
+ probed++;
251
+ let allocations;
252
+ try {
253
+ allocations = allocateWorktreePorts(ctx.portMappings, wt.index, ctx.portStride);
254
+ }
255
+ catch (err) {
256
+ add({ status: "fail", title: `Worktree ${wt.index}: cannot allocate ports`, detail: message(err) });
257
+ continue;
258
+ }
259
+ for (const a of allocations) {
260
+ if (await isPortBusy(a.port)) {
261
+ busy.push(`worktree ${wt.index} (${wt.branch}) ${a.envVar}=${a.port}`);
262
+ }
263
+ }
264
+ }
265
+ if (busy.length > 0) {
266
+ add({
267
+ status: "warn",
268
+ title: `${busy.length} allocated port(s) already in use`,
269
+ detail: busy.join(", "),
270
+ hint: "Something else is listening there: starting that worktree would fail, or its localhost URL would reach the other process. Stop it, or change portStride.",
271
+ });
272
+ }
273
+ else if (probed > 0) {
274
+ add({ status: "ok", title: `Allocated ports are free for ${probed} stopped worktree(s)` });
275
+ }
276
+ return finish();
277
+ }
@@ -0,0 +1,42 @@
1
+ import type { StackStatus } from "../compose/status.js";
2
+ import type { PortAllocation } from "../ports/types.js";
3
+ import type { CoreIo } from "./types.js";
4
+ export interface ListRow {
5
+ index: number;
6
+ branch: string;
7
+ path: string;
8
+ project: string;
9
+ /** up · partial · exited · down · ? (engine unavailable) */
10
+ status: StackStatus;
11
+ running: number | null;
12
+ total: number | null;
13
+ url: string | null;
14
+ ports: Record<string, number>;
15
+ /** The worktree was removed but its registry record (and maybe its stack) remains. */
16
+ orphan: boolean;
17
+ /**
18
+ * The worktree still exists but cannot be started: `missing` (locked, its
19
+ * checkout missing on disk — an unmounted drive) or `main` (it became the
20
+ * main checkout). Its record and stack are kept; prune never touches it.
21
+ */
22
+ unavailable: "missing" | "main" | null;
23
+ }
24
+ export interface ListResult {
25
+ rows: ListRow[];
26
+ /** Default (main checkout) ports of isolatable services. */
27
+ mainPorts: {
28
+ service: string;
29
+ port: number;
30
+ }[];
31
+ warnings: string[];
32
+ isolationWarnings: string[];
33
+ }
34
+ /** Guess the URL a human wants: a frontend-ish service, else the last port. */
35
+ export declare function pickUrl(allocations: PortAllocation[]): string | null;
36
+ /**
37
+ * Worktrees (and orphaned stacks) with status, ports, and URL. Read-only
38
+ * (wtc_list carries readOnlyHint): identities of worktrees seen for the
39
+ * first time are computed, adopting running stacks, but never recorded —
40
+ * no registry write, no `wtc-id`, a corrupt registry left in place.
41
+ */
42
+ export declare function listWorktrees(io: CoreIo): ListResult;
@@ -0,0 +1,94 @@
1
+ import { buildContext } from "../context.js";
2
+ import { allocateWorktreePorts } from "../ports/allocate.js";
3
+ import { stackStatus } from "../compose/status.js";
4
+ function safeAllocate(ctx, index) {
5
+ try {
6
+ return allocateWorktreePorts(ctx.portMappings, index, ctx.portStride);
7
+ }
8
+ catch {
9
+ return [];
10
+ }
11
+ }
12
+ /** Guess the URL a human wants: a frontend-ish service, else the last port. */
13
+ export function pickUrl(allocations) {
14
+ const frontend = allocations.find((a) => a.serviceName.includes("frontend") ||
15
+ a.serviceName.includes("web") ||
16
+ a.serviceName.includes("app") ||
17
+ a.serviceName.includes("ui"));
18
+ const chosen = frontend ?? allocations[allocations.length - 1];
19
+ return chosen ? `http://localhost:${chosen.port}` : null;
20
+ }
21
+ /**
22
+ * Worktrees (and orphaned stacks) with status, ports, and URL. Read-only
23
+ * (wtc_list carries readOnlyHint): identities of worktrees seen for the
24
+ * first time are computed, adopting running stacks, but never recorded —
25
+ * no registry write, no `wtc-id`, a corrupt registry left in place.
26
+ */
27
+ export function listWorktrees(io) {
28
+ const ctx = buildContext({}, { cwd: io.cwd, probeStacks: true, readOnly: true });
29
+ const warnings = [...ctx.warnings];
30
+ const stacks = ctx.stacks;
31
+ const rows = [];
32
+ for (const wt of ctx.worktrees) {
33
+ const allocations = safeAllocate(ctx, wt.index);
34
+ const state = stacks.state(wt.project);
35
+ rows.push({
36
+ index: wt.index,
37
+ branch: wt.branch,
38
+ path: wt.path,
39
+ project: wt.project,
40
+ status: stackStatus(state),
41
+ running: state?.running ?? null,
42
+ total: state?.total ?? null,
43
+ url: pickUrl(allocations),
44
+ ports: Object.fromEntries(allocations.map((a) => [a.envVar, a.port])),
45
+ orphan: false,
46
+ unavailable: null,
47
+ });
48
+ }
49
+ for (const u of ctx.unavailable) {
50
+ const allocations = safeAllocate(ctx, u.index);
51
+ const state = stacks.state(u.project);
52
+ rows.push({
53
+ index: u.index,
54
+ branch: u.branch,
55
+ path: u.path,
56
+ project: u.project,
57
+ status: stackStatus(state),
58
+ running: state?.running ?? null,
59
+ total: state?.total ?? null,
60
+ url: null,
61
+ ports: Object.fromEntries(allocations.map((a) => [a.envVar, a.port])),
62
+ orphan: false,
63
+ unavailable: u.reason,
64
+ });
65
+ }
66
+ for (const o of ctx.orphans) {
67
+ const allocations = safeAllocate(ctx, o.index);
68
+ const state = stacks.state(o.project);
69
+ rows.push({
70
+ index: o.index,
71
+ branch: o.branch,
72
+ path: o.path,
73
+ project: o.project,
74
+ status: stackStatus(state),
75
+ running: state?.running ?? null,
76
+ total: state?.total ?? null,
77
+ url: null,
78
+ ports: Object.fromEntries(allocations.map((a) => [a.envVar, a.port])),
79
+ orphan: true,
80
+ unavailable: null,
81
+ });
82
+ }
83
+ rows.sort((a, b) => a.index - b.index);
84
+ if (rows.length > 0 && stacks.problem)
85
+ warnings.push(stacks.problem);
86
+ return {
87
+ rows,
88
+ mainPorts: ctx.portMappings
89
+ .filter((m) => m.envVar !== null)
90
+ .map((m) => ({ service: m.serviceName, port: m.defaultPort })),
91
+ warnings,
92
+ isolationWarnings: ctx.isolationWarnings,
93
+ };
94
+ }
@@ -0,0 +1,40 @@
1
+ import type { WorktreeSelector } from "../selectors.js";
2
+ import type { Reporter } from "../utils/log.js";
3
+ import type { CoreIo } from "./types.js";
4
+ export interface PromoteOptions {
5
+ worktree: WorktreeSelector;
6
+ /**
7
+ * Promote even files the target branch also changed (committed) since the
8
+ * worktree branched — overwriting, i.e. reverting, those commits. Meant for
9
+ * promote → commit → keep iterating → promote again.
10
+ */
11
+ force?: boolean;
12
+ }
13
+ export interface PromoteResult {
14
+ worktree: {
15
+ index: number;
16
+ branch: string;
17
+ path: string;
18
+ };
19
+ /** Checkout that received the files (the one wtc ran from). */
20
+ target: string;
21
+ targetBranch: string;
22
+ files: string[];
23
+ /** Paths that could not be copied (directories such as submodules). */
24
+ skipped: string[];
25
+ }
26
+ /** Files both the target branch (committed) and the worktree changed since they diverged. */
27
+ export declare class PromoteDivergedError extends Error {
28
+ files: string[];
29
+ constructor(files: string[], target: string, mergeRef: string, wtBranch: string, wtPath: string);
30
+ }
31
+ export declare class PromoteConflictError extends Error {
32
+ conflicts: string[];
33
+ constructor(conflicts: string[]);
34
+ }
35
+ /**
36
+ * Copy a worktree's changes (committed, staged, unstaged, untracked) into the
37
+ * checkout wtc runs from, as uncommitted changes. Compose and env files are
38
+ * excluded: wtc rewrites them per worktree.
39
+ */
40
+ export declare function promoteWorktree(options: PromoteOptions, reporter: Reporter, io: CoreIo): Promise<PromoteResult>;
@@ -0,0 +1,117 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { buildContext } from "../context.js";
4
+ import { selectWorktrees } from "../selectors.js";
5
+ import { escapesRoot } from "../utils/paths.js";
6
+ import { PROMOTE_EXCLUDES, assertPromotable, findConflicts, getChangedFiles, getLocalDirtyFiles, getMergeBase, getTargetChangedFiles, promoteFiles, resolveCommit, } from "../git/promote.js";
7
+ import { getWorktreeBranch } from "../git/worktree.js";
8
+ import { throwIfAborted } from "./compose.js";
9
+ /**
10
+ * True when promoting `a` over `b` would change nothing: both missing (both
11
+ * sides deleted it), both symlinks with the same target, or both regular
12
+ * files with identical bytes.
13
+ */
14
+ function sameContent(a, b) {
15
+ try {
16
+ const sa = fs.lstatSync(a, { throwIfNoEntry: false });
17
+ const sb = fs.lstatSync(b, { throwIfNoEntry: false });
18
+ if (!sa || !sb)
19
+ return !sa && !sb;
20
+ if (sa.isSymbolicLink() && sb.isSymbolicLink())
21
+ return fs.readlinkSync(a) === fs.readlinkSync(b);
22
+ if (!sa.isFile() || !sb.isFile() || sa.size !== sb.size)
23
+ return false;
24
+ return fs.readFileSync(a).equals(fs.readFileSync(b));
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ }
30
+ /** Files both the target branch (committed) and the worktree changed since they diverged. */
31
+ export class PromoteDivergedError extends Error {
32
+ files;
33
+ constructor(files, target, mergeRef, wtBranch, wtPath) {
34
+ super(`Abort: ${files.length} file(s) also changed on ${target} since ${wtBranch} branched; promoting would revert those commits` +
35
+ ` — merge ${target} into the worktree first (git -C ${wtPath} merge ${mergeRef}), then re-run promote` +
36
+ ` (or pass --force / MCP force to overwrite them anyway):\n` +
37
+ files.map((f) => ` ${f}`).join("\n"));
38
+ this.name = "PromoteDivergedError";
39
+ this.files = files;
40
+ }
41
+ }
42
+ export class PromoteConflictError extends Error {
43
+ conflicts;
44
+ constructor(conflicts) {
45
+ super(`Abort: ${conflicts.length} file(s) have uncommitted or untracked changes in the target and would be overwritten:\n` +
46
+ conflicts.map((f) => ` ${f}`).join("\n") +
47
+ "\nCommit or stash your local changes first, then re-run promote.");
48
+ this.name = "PromoteConflictError";
49
+ this.conflicts = conflicts;
50
+ }
51
+ }
52
+ /**
53
+ * Copy a worktree's changes (committed, staged, unstaged, untracked) into the
54
+ * checkout wtc runs from, as uncommitted changes. Compose and env files are
55
+ * excluded: wtc rewrites them per worktree.
56
+ */
57
+ export async function promoteWorktree(options, reporter, io) {
58
+ const ctx = buildContext({}, { cwd: io.cwd, allowMissingCompose: true });
59
+ for (const w of ctx.warnings)
60
+ reporter.warn(w);
61
+ const [wt] = selectWorktrees(ctx.worktrees, [options.worktree], ctx.cwd);
62
+ const target = ctx.repo.currentRoot;
63
+ if (path.resolve(wt.path) === path.resolve(target)) {
64
+ throw new Error(`Worktree ${wt.index} (${wt.branch}) is the current checkout. Run promote from the checkout that should receive the changes (usually the main worktree).`);
65
+ }
66
+ const targetBranch = getWorktreeBranch(target);
67
+ const displayTarget = targetBranch === "HEAD" ? "detached HEAD" : targetBranch;
68
+ reporter.info(`Promoting worktree ${wt.index} (${wt.branch}) into ${displayTarget}`);
69
+ const excludes = new Set(PROMOTE_EXCLUDES);
70
+ for (const src of ctx.composeFile.sourceFiles) {
71
+ const rel = path.relative(ctx.repoRoot, src);
72
+ if (rel && !escapesRoot(rel))
73
+ excludes.add(rel.split(path.sep).join("/"));
74
+ }
75
+ const mergeBase = getMergeBase(target, wt.path);
76
+ const files = getChangedFiles(target, wt.path, excludes, mergeBase);
77
+ const result = {
78
+ worktree: { index: wt.index, branch: wt.branch, path: wt.path },
79
+ target,
80
+ targetBranch,
81
+ files,
82
+ skipped: [],
83
+ };
84
+ if (files.length === 0) {
85
+ reporter.info("No changes to promote.");
86
+ return result;
87
+ }
88
+ // Containment first (all-or-nothing, before anything is read for the
89
+ // checks below): no path may pass through a symlink on either side.
90
+ assertPromotable(target, wt.path, files);
91
+ // A dirty target file that already matches the worktree's copy (e.g. from
92
+ // an earlier promote) loses nothing when overwritten, so it isn't a conflict.
93
+ const conflicts = findConflicts(files, getLocalDirtyFiles(target)).filter((f) => !sameContent(path.join(wt.path, f), path.join(target, f)));
94
+ if (conflicts.length > 0)
95
+ throw new PromoteConflictError(conflicts);
96
+ // Whole-file copies would silently revert what the target committed since
97
+ // the worktree branched — unless the target already has the same content.
98
+ if (!options.force) {
99
+ const promoted = new Set(files);
100
+ const diverged = getTargetChangedFiles(target, mergeBase).filter((f) => promoted.has(f) && !sameContent(path.join(wt.path, f), path.join(target, f)));
101
+ if (diverged.length > 0) {
102
+ const mergeRef = targetBranch === "HEAD" ? resolveCommit(target, "HEAD").slice(0, 12) : targetBranch;
103
+ const wtName = wt.detached ? `worktree ${wt.index}` : wt.branch;
104
+ throw new PromoteDivergedError(diverged, displayTarget, mergeRef, wtName, wt.path);
105
+ }
106
+ }
107
+ // Last point to back out: a request cancelled meanwhile writes nothing.
108
+ throwIfAborted(io);
109
+ result.skipped = promoteFiles(target, wt.path, files);
110
+ const copied = files.filter((f) => !result.skipped.includes(f));
111
+ reporter.success(`Promoted ${copied.length} file(s). Changes are uncommitted in ${displayTarget}.`);
112
+ for (const f of copied)
113
+ reporter.info(` ${f}`);
114
+ for (const f of result.skipped)
115
+ reporter.warn(`Skipped ${f} (not a regular file)`);
116
+ return result;
117
+ }
@@ -0,0 +1,32 @@
1
+ import type { Reporter } from "../utils/log.js";
2
+ import type { CoreIo } from "./types.js";
3
+ export interface PruneOptions {
4
+ /** Report what would be pruned; change nothing — not even the registry. */
5
+ dryRun?: boolean;
6
+ }
7
+ export interface PruneResult {
8
+ dryRun: boolean;
9
+ orphans: {
10
+ index: number;
11
+ branch: string;
12
+ path: string;
13
+ project: string;
14
+ ok: boolean;
15
+ error?: string;
16
+ }[];
17
+ /** Orphans left alone because their worktree is live again. */
18
+ skipped: {
19
+ project: string;
20
+ path: string;
21
+ reason: string;
22
+ }[];
23
+ /** Missing-on-disk worktrees whose git metadata was pruned. */
24
+ gitPruned: string[];
25
+ /** Orphaned stacks that could not be torn down (non-zero → exit 1 / MCP isError). */
26
+ failures: number;
27
+ }
28
+ /**
29
+ * Tear down and forget orphans only: stacks of worktrees deleted with plain
30
+ * `git worktree remove` / `rm -rf`. Live worktrees are not touched.
31
+ */
32
+ export declare function prune(options: PruneOptions, reporter: Reporter, io: CoreIo): Promise<PruneResult>;
@@ -0,0 +1,75 @@
1
+ import { buildContext } from "../context.js";
2
+ import { runSafe } from "../utils/exec.js";
3
+ import { forgetRecords } from "../state/registry.js";
4
+ import { reportContextWarnings, throwIfAborted } from "./compose.js";
5
+ import { orphanSkipReason, teardownStack } from "./teardown.js";
6
+ /**
7
+ * Tear down and forget orphans only: stacks of worktrees deleted with plain
8
+ * `git worktree remove` / `rm -rf`. Live worktrees are not touched.
9
+ */
10
+ export async function prune(options, reporter, io) {
11
+ const dryRun = options.dryRun === true;
12
+ const ctx = buildContext({}, { cwd: io.cwd, allowMissingCompose: true, readOnly: dryRun });
13
+ reportContextWarnings(ctx, reporter, { isolation: false });
14
+ const result = { dryRun, orphans: [], skipped: [], gitPruned: [], failures: 0 };
15
+ if (ctx.orphans.length === 0 && ctx.prunable.length === 0) {
16
+ reporter.info("Nothing to prune: every recorded worktree still exists.");
17
+ return result;
18
+ }
19
+ const engine = ctx.orphans.length > 0 ? ctx.getEngine() : null;
20
+ const forget = [];
21
+ for (const o of ctx.orphans) {
22
+ throwIfAborted(io);
23
+ const entry = { index: o.index, branch: o.branch, path: o.path, project: o.project };
24
+ // Never `down -v` a stack whose worktree is live again (re-checked now,
25
+ // not from the snapshot: the previous teardown may have taken a while).
26
+ const why = orphanSkipReason(ctx, o);
27
+ if (why) {
28
+ result.skipped.push({ project: o.project, path: o.path, reason: why });
29
+ reporter.warn(`Skipping ${o.project}: ${why}.`);
30
+ continue;
31
+ }
32
+ if (dryRun) {
33
+ reporter.info(`Would stop ${o.project} and forget worktree ${o.index} (${o.path})`);
34
+ result.orphans.push({ ...entry, ok: true });
35
+ continue;
36
+ }
37
+ reporter.info(`Stopping ${o.project} (worktree ${o.index} was removed)...`);
38
+ const outcome = await teardownStack(ctx, engine, o, io);
39
+ result.orphans.push({ ...entry, ...outcome });
40
+ if (outcome.ok) {
41
+ forget.push(o.project);
42
+ reporter.success(`Pruned worktree ${o.index} (${o.branch})`);
43
+ }
44
+ else {
45
+ reporter.warn(`Could not stop ${o.project}: ${outcome.error}`);
46
+ }
47
+ }
48
+ for (const wt of ctx.prunable) {
49
+ if (dryRun) {
50
+ reporter.info(`Would prune git metadata for missing worktree ${wt.path}`);
51
+ }
52
+ result.gitPruned.push(wt.path);
53
+ }
54
+ if (!dryRun) {
55
+ if (ctx.prunable.length > 0) {
56
+ runSafe("git", ["-C", ctx.repoRoot, "worktree", "prune"]);
57
+ }
58
+ forgetRecords(ctx.repo.commonDir, forget);
59
+ }
60
+ const failed = result.orphans.filter((o) => !o.ok).length;
61
+ result.failures = dryRun ? 0 : failed;
62
+ const summary = `${dryRun ? "Dry run complete" : failed > 0 ? "Prune finished with failures" : "Prune complete"}: ` +
63
+ `${result.orphans.length - failed} orphaned stack(s) ${dryRun ? "to remove" : "removed"}` +
64
+ (failed > 0 ? `, ${failed} failed` : "") +
65
+ (result.skipped.length > 0 ? `, ${result.skipped.length} skipped` : "") +
66
+ (result.gitPruned.length > 0
67
+ ? `, ${result.gitPruned.length} missing worktree(s) ${dryRun ? "to prune" : "pruned"} from git`
68
+ : "") +
69
+ ".";
70
+ if (failed > 0)
71
+ reporter.warn(summary);
72
+ else
73
+ reporter.success(summary);
74
+ return result;
75
+ }