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
@@ -0,0 +1,79 @@
1
+ import { buildContext } from "../context.js";
2
+ import { runSafe } from "../utils/exec.js";
3
+ import { forgetRecords } from "../state/registry.js";
4
+ import { overridePath, removeOverride } from "../compose/override.js";
5
+ import { reportContextWarnings, throwIfAborted } from "./compose.js";
6
+ import { orphanSkipReason, teardownStack } from "./teardown.js";
7
+ /**
8
+ * Tear down and forget orphans only: stacks of worktrees deleted with plain
9
+ * `git worktree remove` / `rm -rf`. Live worktrees are not touched.
10
+ */
11
+ export async function prune(options, reporter, io) {
12
+ const dryRun = options.dryRun === true;
13
+ // resolveRemap: tear stacks down with the compose files they were started with.
14
+ const ctx = buildContext({}, { cwd: io.cwd, allowMissingCompose: true, readOnly: dryRun, resolveRemap: !dryRun });
15
+ reportContextWarnings(ctx, reporter, { isolation: false });
16
+ const result = { dryRun, orphans: [], skipped: [], gitPruned: [], failures: 0 };
17
+ if (ctx.orphans.length === 0 && ctx.prunable.length === 0) {
18
+ reporter.info("Nothing to prune: every recorded worktree still exists.");
19
+ return result;
20
+ }
21
+ const engine = ctx.orphans.length > 0 ? ctx.getEngine() : null;
22
+ const forget = [];
23
+ for (const o of ctx.orphans) {
24
+ throwIfAborted(io);
25
+ const entry = { index: o.index, branch: o.branch, path: o.path, project: o.project };
26
+ // Never `down -v` a stack whose worktree is live again (re-checked now,
27
+ // not from the snapshot: the previous teardown may have taken a while).
28
+ const why = orphanSkipReason(ctx, o);
29
+ if (why) {
30
+ result.skipped.push({ project: o.project, path: o.path, reason: why });
31
+ reporter.warn(`Skipping ${o.project}: ${why}.`);
32
+ continue;
33
+ }
34
+ if (dryRun) {
35
+ reporter.info(`Would stop ${o.project} and forget worktree ${o.index} (${o.path})`);
36
+ result.orphans.push({ ...entry, ok: true });
37
+ continue;
38
+ }
39
+ reporter.info(`Stopping ${o.project} (worktree ${o.index} was removed)...`);
40
+ const outcome = await teardownStack(ctx, engine, o, io);
41
+ result.orphans.push({ ...entry, ...outcome });
42
+ if (outcome.ok) {
43
+ forget.push(o.project);
44
+ reporter.success(`Pruned worktree ${o.index} (${o.branch})`);
45
+ }
46
+ else {
47
+ reporter.warn(`Could not stop ${o.project}: ${outcome.error}`);
48
+ }
49
+ }
50
+ for (const wt of ctx.prunable) {
51
+ if (dryRun) {
52
+ reporter.info(`Would prune git metadata for missing worktree ${wt.path}`);
53
+ }
54
+ result.gitPruned.push(wt.path);
55
+ }
56
+ if (!dryRun) {
57
+ if (ctx.prunable.length > 0) {
58
+ runSafe("git", ["-C", ctx.repoRoot, "worktree", "prune"]);
59
+ }
60
+ forgetRecords(ctx.repo.commonDir, forget);
61
+ for (const project of forget)
62
+ removeOverride(overridePath(ctx.repo.commonDir, project));
63
+ }
64
+ const failed = result.orphans.filter((o) => !o.ok).length;
65
+ result.failures = dryRun ? 0 : failed;
66
+ const summary = `${dryRun ? "Dry run complete" : failed > 0 ? "Prune finished with failures" : "Prune complete"}: ` +
67
+ `${result.orphans.length - failed} orphaned stack(s) ${dryRun ? "to remove" : "removed"}` +
68
+ (failed > 0 ? `, ${failed} failed` : "") +
69
+ (result.skipped.length > 0 ? `, ${result.skipped.length} skipped` : "") +
70
+ (result.gitPruned.length > 0
71
+ ? `, ${result.gitPruned.length} missing worktree(s) ${dryRun ? "to prune" : "pruned"} from git`
72
+ : "") +
73
+ ".";
74
+ if (failed > 0)
75
+ reporter.warn(summary);
76
+ else
77
+ reporter.success(summary);
78
+ return result;
79
+ }
@@ -0,0 +1,14 @@
1
+ import type { StartOptions, StartResult } from "./start.js";
2
+ import type { Reporter } from "../utils/log.js";
3
+ import type { CoreIo } from "./types.js";
4
+ /**
5
+ * Stop then start (`compose stop`, then start's sync/inject + `up -d
6
+ * --remove-orphans`): unchanged services are simply started again, changed
7
+ * ones are recreated by compose — which carries their anonymous volumes
8
+ * over, unlike the old `down` + `up`, which brought image-declared volumes
9
+ * back empty — and containers of services removed from the compose file
10
+ * go away, as `down` used to make them. Env options and selectors are
11
+ * validated while every worktree is still running, so a typo never leaves
12
+ * stacks stopped.
13
+ */
14
+ export declare function restartWorktrees(options: StartOptions, reporter: Reporter, io: CoreIo): Promise<StartResult>;
@@ -0,0 +1,18 @@
1
+ import { preflightEnvOptions } from "../context.js";
2
+ import { startWorktrees } from "./start.js";
3
+ import { stopWorktrees } from "./stop.js";
4
+ /**
5
+ * Stop then start (`compose stop`, then start's sync/inject + `up -d
6
+ * --remove-orphans`): unchanged services are simply started again, changed
7
+ * ones are recreated by compose — which carries their anonymous volumes
8
+ * over, unlike the old `down` + `up`, which brought image-declared volumes
9
+ * back empty — and containers of services removed from the compose file
10
+ * go away, as `down` used to make them. Env options and selectors are
11
+ * validated while every worktree is still running, so a typo never leaves
12
+ * stacks stopped.
13
+ */
14
+ export async function restartWorktrees(options, reporter, io) {
15
+ preflightEnvOptions(options, io.cwd, { requireMainFor: "restart worktree stacks" });
16
+ await stopWorktrees({ worktrees: options.worktrees, quiet: true }, reporter, io);
17
+ return startWorktrees({ ...options, removeOrphans: true }, reporter, io);
18
+ }
@@ -0,0 +1,33 @@
1
+ import type { EnvCliOptions } from "../context.js";
2
+ import type { WorktreeSelector } from "../selectors.js";
3
+ import type { Reporter } from "../utils/log.js";
4
+ import type { CoreIo } from "./types.js";
5
+ export interface StartOptions extends EnvCliOptions {
6
+ /** Worktrees to start (index, branch, dir name, path, "."); empty = all. */
7
+ worktrees?: WorktreeSelector[];
8
+ /** Pass `--build` to `compose up` (default true). */
9
+ build?: boolean;
10
+ /**
11
+ * Pass `--remove-orphans` to `compose up` (restart): containers of
12
+ * services the compose file no longer declares would otherwise keep
13
+ * running — and holding their ports — after the restart.
14
+ */
15
+ removeOrphans?: boolean;
16
+ }
17
+ export interface StartedWorktree {
18
+ index: number;
19
+ branch: string;
20
+ path: string;
21
+ project: string;
22
+ ports: Record<string, number>;
23
+ }
24
+ export interface StartResult {
25
+ started: StartedWorktree[];
26
+ }
27
+ /**
28
+ * Sync infra files, inject ports + project name into env files, and run
29
+ * `compose up -d` for each selected worktree (with the stack's runtime
30
+ * override when hardcoded ports or container names are remapped). Stops at
31
+ * the first failure.
32
+ */
33
+ export declare function startWorktrees(options: StartOptions, reporter: Reporter, io: CoreIo): Promise<StartResult>;
@@ -0,0 +1,113 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { buildContext, getEnvTargets } from "../context.js";
4
+ import { samePath } from "../git/worktree.js";
5
+ import { recordEnvFiles } from "../state/registry.js";
6
+ import { allocateWorktreePorts, portLabel, portsByLabel } from "../ports/allocate.js";
7
+ import { inheritedComposeFileNames, overridePath, removeOverride } from "../compose/override.js";
8
+ import { syncWorktreeFiles } from "../sync/files.js";
9
+ import { findEnvSource, injectPortOverrides, prepareEnvFile } from "../sync/env.js";
10
+ import { selectWorktrees } from "../selectors.js";
11
+ import { composeEnv, composeRun, NO_WORKTREES_HINT, prepareStack, reportContextWarnings, throwIfAborted, withContext, } from "./compose.js";
12
+ /**
13
+ * Sync infra files, inject ports + project name into env files, and run
14
+ * `compose up -d` for each selected worktree (with the stack's runtime
15
+ * override when hardcoded ports or container names are remapped). Stops at
16
+ * the first failure.
17
+ */
18
+ export async function startWorktrees(options, reporter, io) {
19
+ const ctx = buildContext(options, { cwd: io.cwd, probeStacks: true, requireMainFor: "start worktree stacks" });
20
+ reportContextWarnings(ctx, reporter, { isolation: true });
21
+ if (ctx.worktrees.length === 0) {
22
+ reporter.warn(NO_WORKTREES_HINT);
23
+ return { started: [] };
24
+ }
25
+ const targets = selectWorktrees(ctx.worktrees, options.worktrees, ctx.cwd);
26
+ const envTargets = getEnvTargets(ctx);
27
+ const engine = ctx.getEngine();
28
+ const build = options.build !== false;
29
+ const started = [];
30
+ for (const wt of targets) {
31
+ throwIfAborted(io);
32
+ // Never treat the env/config source as a worktree, and never recreate a
33
+ // missing checkout just to run compose in it.
34
+ if (samePath(wt.path, ctx.repoRoot)) {
35
+ throw new Error(`Worktree ${wt.index} (${wt.branch}) is the main checkout (${ctx.repoRoot}); wtc does not start it as a worktree.`);
36
+ }
37
+ if (!fs.existsSync(path.join(wt.path, ".git"))) {
38
+ throw new Error(`Worktree ${wt.index} (${wt.branch}) is missing on disk (${wt.path}). Remount it, or run 'git worktree prune' and 'wtc prune'.`);
39
+ }
40
+ // Fail on an unallocatable port before writing anything into the worktree.
41
+ allocateWorktreePorts(ctx.portMappings, wt.index, ctx.portStride, ctx.remap?.ports);
42
+ reporter.header(`Worktree ${wt.index}: ${wt.branch}`);
43
+ reporter.info(`Path: ${wt.path}`);
44
+ reporter.info(`Project: ${wt.project}`);
45
+ const syncWarnings = syncWorktreeFiles(ctx.repoRoot, wt.path, ctx.composeFile, ctx.config.sync);
46
+ // Skipped sync entries were already reported with the context warnings.
47
+ for (const w of syncWarnings)
48
+ if (!ctx.warnings.includes(w))
49
+ reporter.warn(w);
50
+ reporter.success("Synced infrastructure files");
51
+ // After the sync: the worktree's own compose override may be a synced file.
52
+ const stack = prepareStack(ctx, { project: wt.project, index: wt.index, dir: wt.path }, { write: true });
53
+ // A stale override goes, unless an inherited COMPOSE_FILE still lists it.
54
+ const overrideFile = overridePath(ctx.repo.commonDir, wt.project);
55
+ if (stack.composeFile === null && !inheritedComposeFileNames(overrideFile))
56
+ removeOverride(overrideFile);
57
+ for (const w of stack.warnings)
58
+ reporter.warn(w);
59
+ const allocations = stack.allocations;
60
+ reporter.info(`Ports: ${allocations.map((a) => `${portLabel(a)}=${a.port}`).join(" ") || "(none)"}`);
61
+ const injected = [];
62
+ for (const target of envTargets) {
63
+ const envWarnings = [];
64
+ const envPath = prepareEnvFile(ctx.repoRoot, wt.path, target, envWarnings);
65
+ for (const w of envWarnings)
66
+ reporter.warn(w);
67
+ if (!envPath) {
68
+ if (envWarnings.length === 0) {
69
+ reporter.warn(`No ${target.envFileName} (or .env.example) found for ${target.label}; skipped`);
70
+ }
71
+ continue;
72
+ }
73
+ const injection = injectPortOverrides(envPath, allocations, target.overrides, {
74
+ projectName: wt.project,
75
+ writeProjectName: target.dir === "",
76
+ ...(target.dir === "" && stack.composeFile ? { composeFile: stack.composeFile } : {}),
77
+ root: wt.path,
78
+ source: findEnvSource(ctx.repoRoot, target) ?? undefined,
79
+ });
80
+ for (const w of injection.warnings)
81
+ reporter.warn(w);
82
+ injected.push(path.relative(wt.path, envPath));
83
+ }
84
+ if (injected.length > 0) {
85
+ reporter.success(`Injected port overrides into ${injected.join(", ")}`);
86
+ }
87
+ // Remember exactly which env files wtc wrote (before compose runs: they
88
+ // are written even if `up` fails), so clean treats only those as wtc's
89
+ // own changes.
90
+ recordEnvFiles(ctx.repo.commonDir, wt.path, injected);
91
+ try {
92
+ await composeRun(engine, wt.project, ["up", "-d", ...(build ? ["--build"] : []), ...(options.removeOrphans ? ["--remove-orphans"] : [])], {
93
+ cwd: wt.path,
94
+ env: composeEnv(wt.project, allocations, stack.composeFile, ctx.repo.commonDir),
95
+ live: io.live,
96
+ signal: io.signal,
97
+ onLine: io.onOutput,
98
+ });
99
+ }
100
+ catch (err) {
101
+ throw withContext(`Failed to start worktree ${wt.index} (${wt.branch})`, err);
102
+ }
103
+ reporter.success(`Worktree ${wt.index} started`);
104
+ started.push({
105
+ index: wt.index,
106
+ branch: wt.branch,
107
+ path: wt.path,
108
+ project: wt.project,
109
+ ports: portsByLabel(allocations),
110
+ });
111
+ }
112
+ return { started };
113
+ }
@@ -0,0 +1,32 @@
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 StopOptions {
5
+ /** Worktrees to stop (index, branch, dir name, path, "."); empty = all. */
6
+ worktrees?: WorktreeSelector[];
7
+ /** Skip context warnings (restart reports them once, from start). */
8
+ quiet?: boolean;
9
+ }
10
+ export interface StopResult {
11
+ stopped: {
12
+ index: number;
13
+ branch: string;
14
+ project: string;
15
+ }[];
16
+ failed: {
17
+ index: number;
18
+ branch: string;
19
+ project: string;
20
+ error: string;
21
+ }[];
22
+ /** Stacks that could not be stopped (non-zero → exit 1 / MCP isError). */
23
+ failures: number;
24
+ }
25
+ /**
26
+ * `compose stop` for each selected worktree; one failure does not stop the
27
+ * rest. Containers are stopped, not removed: data in volumes declared only
28
+ * by an image (postgres, redis… without a named volume) lives in anonymous
29
+ * volumes that a `down` + `up` would replace with empty ones. `wtc start`
30
+ * resumes the same containers; `clean`/`prune` remove everything.
31
+ */
32
+ export declare function stopWorktrees(options: StopOptions, reporter: Reporter, io: CoreIo): Promise<StopResult>;
@@ -0,0 +1,58 @@
1
+ import { buildContext } from "../context.js";
2
+ import { selectWorktrees } from "../selectors.js";
3
+ import { composeEnv, composeRun, prepareStack, reportContextWarnings, throwIfAborted } from "./compose.js";
4
+ /**
5
+ * `compose stop` for each selected worktree; one failure does not stop the
6
+ * rest. Containers are stopped, not removed: data in volumes declared only
7
+ * by an image (postgres, redis… without a named volume) lives in anonymous
8
+ * volumes that a `down` + `up` would replace with empty ones. `wtc start`
9
+ * resumes the same containers; `clean`/`prune` remove everything.
10
+ */
11
+ export async function stopWorktrees(options, reporter, io) {
12
+ // Probe like start and list: with a lost or corrupt registry, worktrees
13
+ // then adopt their running stacks' identities instead of positional
14
+ // names that never existed (`compose stop` on those is a silent no-op).
15
+ // The probe runs `ps` only when some worktree has no record.
16
+ const ctx = buildContext({}, { cwd: io.cwd, probeStacks: true });
17
+ if (!options.quiet)
18
+ reportContextWarnings(ctx, reporter, { isolation: false });
19
+ const result = { stopped: [], failed: [], failures: 0 };
20
+ if (ctx.worktrees.length === 0) {
21
+ reporter.warn("No worktrees to stop.");
22
+ return result;
23
+ }
24
+ const targets = selectWorktrees(ctx.worktrees, options.worktrees, ctx.cwd);
25
+ const engine = ctx.getEngine();
26
+ for (const wt of targets) {
27
+ throwIfAborted(io);
28
+ reporter.info(`Stopping ${wt.project}...`);
29
+ const entry = { index: wt.index, branch: wt.branch, project: wt.project };
30
+ let env;
31
+ try {
32
+ // The compose files the stack was started with (runtime override included).
33
+ const stack = prepareStack(ctx, { project: wt.project, index: wt.index, dir: wt.path }, { write: false });
34
+ env = composeEnv(wt.project, stack.allocations, stack.composeFile, ctx.repo.commonDir);
35
+ }
36
+ catch {
37
+ env = undefined;
38
+ }
39
+ try {
40
+ await composeRun(engine, wt.project, ["stop"], {
41
+ cwd: wt.path,
42
+ env,
43
+ live: io.live,
44
+ signal: io.signal,
45
+ onLine: io.onOutput,
46
+ });
47
+ reporter.success(`Stopped worktree ${wt.index} (${wt.branch})`);
48
+ result.stopped.push(entry);
49
+ }
50
+ catch (err) {
51
+ const message = err instanceof Error ? err.message : String(err);
52
+ reporter.warn(`Could not stop ${wt.project}: ${message}`);
53
+ result.failed.push({ ...entry, error: message });
54
+ }
55
+ }
56
+ result.failures = result.failed.length;
57
+ return result;
58
+ }
@@ -0,0 +1,123 @@
1
+ import type { ComposeEngine } from "../compose/engine.js";
2
+ import type { Reporter } from "../utils/log.js";
3
+ import type { WtcContext } from "../context.js";
4
+ import type { WorktreeRecord } from "../state/registry.js";
5
+ import type { CoreIo } from "./types.js";
6
+ export interface TeardownTarget {
7
+ project: string;
8
+ index: number;
9
+ /** Worktree directory (may no longer exist for orphans). */
10
+ path: string;
11
+ }
12
+ /**
13
+ * Anonymous volumes (image-declared `VOLUME`s with no named volume in the
14
+ * compose file) mounted by a project's containers. A container recreated
15
+ * by `up` carries its anonymous volume over, and such a carried-over volume
16
+ * survives `down -v`; collecting them first lets teardown remove them too.
17
+ * Best effort: any failure yields an empty list.
18
+ */
19
+ export declare function anonymousVolumes(engine: ComposeEngine, project: string): string[];
20
+ /**
21
+ * `compose -p P down -v --remove-orphans`. Runs from the worktree when it
22
+ * still exists (so declared volumes/networks are resolved from its compose
23
+ * file), otherwise from the main checkout — with the compose files the
24
+ * stack was started with (its runtime override, which is deleted when its
25
+ * record is forgotten). Fallbacks, in order:
26
+ * - plain `down -v` from the same directory (podman-compose < 1.0.6 rejects
27
+ * `--remove-orphans`, which would make every teardown fail);
28
+ * - for the Compose v2 plugin only, `down -v --remove-orphans` from an
29
+ * empty directory: it tears a project down by its labels alone when the
30
+ * compose file no longer parses. Standalone docker-compose v1 and
31
+ * podman-compose always need a compose file, so that retry cannot help.
32
+ * Anonymous volumes the containers mounted are removed afterwards.
33
+ */
34
+ export declare function teardownStack(ctx: WtcContext, engine: ComposeEngine, target: TeardownTarget, io: CoreIo): Promise<{
35
+ ok: boolean;
36
+ error?: string;
37
+ }>;
38
+ /**
39
+ * Re-check an orphan right before tearing it down, with a fresh `git
40
+ * worktree list`: another wtc process (or `git worktree repair` / a moved
41
+ * directory coming back) may have made its worktree live again since the
42
+ * context was built, and `down -v` would then destroy a live stack's data.
43
+ * Same identity rules as reconcile: a record is live when a worktree holds
44
+ * its id, or sits at its path without a conflicting id (a new worktree at a
45
+ * reused path is not the old one, so the orphan can still be pruned).
46
+ * Returns null when the orphan is still gone, else why it must be skipped.
47
+ */
48
+ export declare function orphanSkipReason(ctx: WtcContext, record: WorktreeRecord): string | null;
49
+ /** Runs a container CLI command; throws on failure. Injectable for tests. */
50
+ export type SweepRunner = (file: string, args: string[]) => string;
51
+ export interface SweepBucket {
52
+ removed: string[];
53
+ failed: string[];
54
+ }
55
+ export interface SweepResult {
56
+ /** Removed (or, in a dry run, to be removed) resources, and failed removals. */
57
+ containers: SweepBucket;
58
+ networks: SweepBucket;
59
+ volumes: SweepBucket;
60
+ /**
61
+ * Resources of `<repo>-wt-<n>-` stacks whose working directory no longer
62
+ * exists (typically left by wtc ≤0.2). Removed only with `sweep`; kept
63
+ * and listed otherwise.
64
+ */
65
+ stale: string[];
66
+ /**
67
+ * Resources named like this repo's worktree stacks that this checkout
68
+ * cannot prove it owns: another checkout's stack (same directory name),
69
+ * or nothing left to attribute them by (no labels, no containers). Never
70
+ * removed.
71
+ */
72
+ notOwned: string[];
73
+ /** Set when a listing failed (engine unreachable). */
74
+ error?: string;
75
+ }
76
+ export interface SweepOptions {
77
+ dryRun?: boolean;
78
+ runner?: SweepRunner;
79
+ reporter?: Reporter;
80
+ /** Projects of this repository's registry records (live and orphaned): owned outright. */
81
+ registryProjects?: string[];
82
+ /**
83
+ * Projects to leave alone this run: in a dry run those step 1 would tear
84
+ * down (`down -v` removes them first), and orphans whose worktree came
85
+ * back while cleaning.
86
+ */
87
+ skipProjects?: string[];
88
+ /** The main checkout: a stack that ran from it (or below it) is this repository's. */
89
+ mainRoot?: string;
90
+ /**
91
+ * Current worktree paths plus every registry path: a stack whose
92
+ * `working_dir` is exactly one of them is this repository's.
93
+ */
94
+ checkouts?: string[];
95
+ /**
96
+ * `clean --sweep`: also remove `<repo>-wt-<n>-` stacks whose working
97
+ * directory no longer exists on disk (stale ≤0.2 leftovers). A stack
98
+ * whose directory exists is never removed this way — it may be another
99
+ * checkout's.
100
+ */
101
+ sweep?: boolean;
102
+ /** Whether a directory exists (tests). */
103
+ dirExists?: (dir: string) => boolean;
104
+ }
105
+ /**
106
+ * Remove leftover containers, networks and volumes of this repository's
107
+ * worktree stacks — never another checkout's.
108
+ *
109
+ * A name like `<repo>-wt-<n>-…` proves nothing: the prefix is the checkout
110
+ * directory's basename, which a second clone (or an unrelated repo also
111
+ * called `api`) shares. Ownership comes from compose's labels instead. A
112
+ * project is *owned* when it is in this repository's registry, or when it
113
+ * is a `<repo>-wt-<n>-` project one of whose containers ran
114
+ * (`project.working_dir`) from the main checkout (or below it), a current
115
+ * worktree, or a registry path. Only resources whose project label is owned
116
+ * are removed, one at a time (a volume still in use cannot discard the rest).
117
+ *
118
+ * Name-matching projects that are not owned are kept and listed, in two
119
+ * groups: *stale* ones, whose working directory no longer exists (removed
120
+ * with `sweep`), and the rest — whose directory exists (another checkout),
121
+ * or which have nothing to attribute them by — which are never removed.
122
+ */
123
+ export declare function sweepStaleResources(cliArgv: string[], repoName: string, opts?: SweepOptions): SweepResult;