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,72 @@
1
+ import type { WorktreeInfo } from "./worktree.js";
2
+ export interface RepoInfo {
3
+ /** Main worktree path — source of truth for compose/config/env files. */
4
+ mainRoot: string;
5
+ /** Toplevel of the cwd's checkout (equals mainRoot unless run from a linked worktree). */
6
+ currentRoot: string;
7
+ /** Absolute git common dir, shared by every worktree (holds wtc's registry). */
8
+ commonDir: string;
9
+ /**
10
+ * Stable repository name (compose project prefix): basename(mainRoot), or
11
+ * for a bare repository the repo's own name (`proj.git`, `proj/.bare` →
12
+ * `proj`) — the same no matter which worktree wtc runs from.
13
+ */
14
+ repoName: string;
15
+ /** The common dir is a bare repository and every checkout is a linked worktree. */
16
+ bare: boolean;
17
+ /**
18
+ * No main checkout could be identified (a bare repository with no
19
+ * worktree on its default branch, or a `--separate-git-dir` repository
20
+ * seen from a linked worktree, with none recorded): `mainRoot` is only
21
+ * the current checkout. No linked worktree is then treated as the main
22
+ * one, the registry is never written, and commands that would sync
23
+ * files into, start, or remove other checkouts refuse to run (see
24
+ * `fallbackReason`).
25
+ */
26
+ mainRootIsFallback: boolean;
27
+ /** Why the main checkout is unknown and how to fix it (set with `mainRootIsFallback`). */
28
+ fallbackReason?: string;
29
+ /**
30
+ * The main checkout was found in a layout git cannot answer for from
31
+ * every worktree (bare, `--separate-git-dir`): reconcile records it in the
32
+ * registry so later runs find it even when the layout no longer tells
33
+ * (default branch checked out elsewhere, mid-rebase, run from a linked
34
+ * worktree).
35
+ */
36
+ recordMain: boolean;
37
+ /** Notes about how the layout was resolved, for the caller to report. */
38
+ warnings: string[];
39
+ }
40
+ /**
41
+ * Name of a bare repository: basename(commonDir) minus a trailing `.git`
42
+ * (`proj.git` → `proj`); when that leaves `.bare`, `.git` or nothing (the
43
+ * `proj/.bare` + `.git`-file layout), the parent's name (`proj`).
44
+ */
45
+ export declare function bareRepoName(commonDir: string): string;
46
+ /**
47
+ * Locate the repository from `cwd`. Everything keys off the MAIN worktree:
48
+ * agents and the MCP server usually run inside a linked worktree, and using
49
+ * that worktree's toplevel would change the repo name (and therefore every
50
+ * compose project name) and sync infra files from the wrong checkout.
51
+ *
52
+ * Layouts beyond a plain clone:
53
+ * - bare repo + worktrees: the main checkout is the worktree on the bare
54
+ * repo's default branch (HEAD), else the one recorded in the registry;
55
+ * the name comes from the bare repo.
56
+ * - submodules and `--separate-git-dir`: `git worktree list` shows the git
57
+ * dir, not the checkout; the checkout is `core.worktree` (submodules) or,
58
+ * when running from it, the current toplevel. From a linked worktree of a
59
+ * `--separate-git-dir` repo git records no main checkout at all: the one
60
+ * recorded in the registry is used.
61
+ * When none is found, the current checkout stands in, flagged
62
+ * `mainRootIsFallback` (see there).
63
+ */
64
+ export declare function getRepoInfo(cwd?: string): RepoInfo;
65
+ /**
66
+ * The repository's worktrees (see getWorktrees), with the main checkout
67
+ * marked only when it was actually found: a fallback main is just the
68
+ * current checkout, and marking it would hide a live worktree.
69
+ */
70
+ export declare function listRepoWorktrees(repo: RepoInfo): WorktreeInfo[];
71
+ /** Throw when the main checkout is unknown (see RepoInfo.mainRootIsFallback). */
72
+ export declare function assertMainCheckout(repo: RepoInfo, action: string): void;
@@ -0,0 +1,167 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { run, runSafe } from "../utils/exec.js";
4
+ import { peekState } from "../state/registry.js";
5
+ import { getWorktrees, parseWorktreePorcelain, samePath } from "./worktree.js";
6
+ /** Absolute `rev-parse` path output (git < 2.31 has no --path-format: resolve against cwd). */
7
+ function revParsePath(cwd, flag) {
8
+ const abs = runSafe("git", ["-C", cwd, "rev-parse", "--path-format=absolute", flag]);
9
+ if (abs && path.isAbsolute(abs))
10
+ return path.resolve(abs);
11
+ return path.resolve(cwd, run("git", ["-C", cwd, "rev-parse", flag]));
12
+ }
13
+ /**
14
+ * Name of a bare repository: basename(commonDir) minus a trailing `.git`
15
+ * (`proj.git` → `proj`); when that leaves `.bare`, `.git` or nothing (the
16
+ * `proj/.bare` + `.git`-file layout), the parent's name (`proj`).
17
+ */
18
+ export function bareRepoName(commonDir) {
19
+ const name = path.basename(commonDir).replace(/\.git$/, "");
20
+ if (name === "" || name === ".bare" || name === ".git") {
21
+ return path.basename(path.dirname(commonDir));
22
+ }
23
+ return name;
24
+ }
25
+ /**
26
+ * The first `git worktree list` entry is not a checkout: submodules and
27
+ * `--separate-git-dir` repos list their git dir there (it resolves to the
28
+ * common dir, or has no `.git` entry of its own).
29
+ */
30
+ function isNotCheckout(dir, commonDir) {
31
+ return samePath(dir, commonDir) || !fs.existsSync(path.join(dir, ".git"));
32
+ }
33
+ /**
34
+ * The main checkout recorded in the registry (see RepoInfo.recordMain), if
35
+ * it still checks out: `valid` decides. Never throws.
36
+ */
37
+ function recordedMain(commonDir, valid) {
38
+ let recorded;
39
+ try {
40
+ recorded = peekState(commonDir)?.mainCheckout;
41
+ }
42
+ catch {
43
+ return null; // A newer wtc's registry: not ours to interpret.
44
+ }
45
+ if (!recorded || !fs.existsSync(path.join(recorded, ".git")))
46
+ return null;
47
+ try {
48
+ return valid(recorded) ? path.resolve(recorded) : null;
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ /**
55
+ * Locate the repository from `cwd`. Everything keys off the MAIN worktree:
56
+ * agents and the MCP server usually run inside a linked worktree, and using
57
+ * that worktree's toplevel would change the repo name (and therefore every
58
+ * compose project name) and sync infra files from the wrong checkout.
59
+ *
60
+ * Layouts beyond a plain clone:
61
+ * - bare repo + worktrees: the main checkout is the worktree on the bare
62
+ * repo's default branch (HEAD), else the one recorded in the registry;
63
+ * the name comes from the bare repo.
64
+ * - submodules and `--separate-git-dir`: `git worktree list` shows the git
65
+ * dir, not the checkout; the checkout is `core.worktree` (submodules) or,
66
+ * when running from it, the current toplevel. From a linked worktree of a
67
+ * `--separate-git-dir` repo git records no main checkout at all: the one
68
+ * recorded in the registry is used.
69
+ * When none is found, the current checkout stands in, flagged
70
+ * `mainRootIsFallback` (see there).
71
+ */
72
+ export function getRepoInfo(cwd = process.cwd()) {
73
+ const currentRoot = runSafe("git", ["-C", cwd, "rev-parse", "--show-toplevel"]);
74
+ if (!currentRoot) {
75
+ throw new Error("Not inside a git repository (run wtc from your project).");
76
+ }
77
+ const current = path.resolve(currentRoot);
78
+ const commonDir = revParsePath(cwd, "--git-common-dir");
79
+ const worktrees = parseWorktreePorcelain(run("git", ["-C", cwd, "worktree", "list", "--porcelain"]));
80
+ const first = worktrees[0];
81
+ const warnings = [];
82
+ const base = { currentRoot: current, commonDir, warnings };
83
+ if (!first || first.bare) {
84
+ const head = runSafe("git", ["--git-dir", commonDir, "symbolic-ref", "-q", "HEAD"]);
85
+ const branch = head ? head.replace(/^refs\/heads\//, "") : null;
86
+ const live = (w) => !w.bare && !w.prunable && fs.existsSync(path.join(w.path, ".git"));
87
+ const primary = branch ? worktrees.find((w) => live(w) && w.branch === branch) : undefined;
88
+ const repoName = bareRepoName(commonDir);
89
+ if (primary) {
90
+ return { ...base, mainRoot: path.resolve(primary.path), repoName, bare: true, mainRootIsFallback: false, recordMain: true };
91
+ }
92
+ // The main worktree is mid-rebase/bisect, or on another branch for now.
93
+ const recorded = recordedMain(commonDir, (dir) => worktrees.some((w) => live(w) && samePath(w.path, dir)));
94
+ if (recorded) {
95
+ return { ...base, mainRoot: recorded, repoName, bare: true, mainRootIsFallback: false, recordMain: false };
96
+ }
97
+ const fallbackReason = (branch
98
+ ? `no worktree of this bare repository has its default branch (${branch}) checked out ` +
99
+ `(is your main worktree mid-rebase or mid-bisect?), so wtc cannot tell which checkout is the main one. ` +
100
+ `Check ${branch} out in your main worktree (or add one: git worktree add <dir> ${branch}), then retry.`
101
+ : `this bare repository's HEAD names no branch, so wtc cannot tell which checkout is the main one. ` +
102
+ `Point HEAD at your default branch (git --git-dir ${commonDir} symbolic-ref HEAD refs/heads/<branch>) ` +
103
+ `and check that branch out in your main worktree, then retry.`);
104
+ warnings.push(`Cannot locate the main checkout: ${fallbackReason} Until then compose, config and env files are read from ` +
105
+ `the current checkout (${current}), and start, restart and clean refuse to run.`);
106
+ return {
107
+ ...base,
108
+ mainRoot: current,
109
+ repoName,
110
+ bare: true,
111
+ mainRootIsFallback: true,
112
+ fallbackReason,
113
+ recordMain: false,
114
+ };
115
+ }
116
+ let mainRoot = path.resolve(first.path);
117
+ let recordMain = false;
118
+ if (isNotCheckout(first.path, commonDir)) {
119
+ const coreWorktree = runSafe("git", ["--git-dir", commonDir, "config", "core.worktree"]);
120
+ if (coreWorktree) {
121
+ mainRoot = path.resolve(commonDir, coreWorktree);
122
+ }
123
+ else if (samePath(revParsePath(cwd, "--git-dir"), commonDir)) {
124
+ // Running from the main checkout itself: remember it for the others.
125
+ mainRoot = current;
126
+ recordMain = true;
127
+ }
128
+ else {
129
+ const recorded = recordedMain(commonDir, (dir) => samePath(revParsePath(dir, "--git-dir"), commonDir));
130
+ if (recorded) {
131
+ mainRoot = recorded;
132
+ }
133
+ else {
134
+ const fallbackReason = `git does not record where the main checkout of a --separate-git-dir repository is, ` +
135
+ `and wtc has not seen it yet. Run this command from the main checkout ` +
136
+ `(after one 'wtc start' there, wtc finds it from linked worktrees too).`;
137
+ warnings.push(`Cannot locate the main checkout: ${fallbackReason} Until then compose, config and env files are read from ` +
138
+ `the current checkout (${current}), and start, restart and clean refuse to run.`);
139
+ return {
140
+ ...base,
141
+ mainRoot: current,
142
+ repoName: path.basename(current),
143
+ bare: false,
144
+ mainRootIsFallback: true,
145
+ fallbackReason,
146
+ recordMain: false,
147
+ };
148
+ }
149
+ }
150
+ }
151
+ return { ...base, mainRoot, repoName: path.basename(mainRoot), bare: false, mainRootIsFallback: false, recordMain };
152
+ }
153
+ /**
154
+ * The repository's worktrees (see getWorktrees), with the main checkout
155
+ * marked only when it was actually found: a fallback main is just the
156
+ * current checkout, and marking it would hide a live worktree.
157
+ */
158
+ export function listRepoWorktrees(repo) {
159
+ return getWorktrees(repo.mainRoot, repo.mainRootIsFallback ? undefined : repo.mainRoot, repo.commonDir);
160
+ }
161
+ /** Throw when the main checkout is unknown (see RepoInfo.mainRootIsFallback). */
162
+ export function assertMainCheckout(repo, action) {
163
+ if (repo.mainRootIsFallback) {
164
+ throw new Error(`Refusing to ${action}: cannot locate the main checkout (the source of compose, config and env files) — ` +
165
+ `${repo.fallbackReason} Without it wtc could sync files into, start, or remove the wrong checkout.`);
166
+ }
167
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Parse `git status --porcelain -z` output into the affected paths. Each entry
3
+ * is `XY <path>\0`; renames and copies (`R`/`C` in either column) are followed
4
+ * by the original path as an extra NUL-terminated field, which is included.
5
+ */
6
+ export declare function parseStatusZ(output: string): string[];
7
+ /** Every path with uncommitted changes (including untracked files) in a checkout. */
8
+ export declare function getStatusPaths(cwd: string): string[];
@@ -0,0 +1,25 @@
1
+ import { run } from "../utils/exec.js";
2
+ /**
3
+ * Parse `git status --porcelain -z` output into the affected paths. Each entry
4
+ * is `XY <path>\0`; renames and copies (`R`/`C` in either column) are followed
5
+ * by the original path as an extra NUL-terminated field, which is included.
6
+ */
7
+ export function parseStatusZ(output) {
8
+ const fields = output.split("\0");
9
+ const paths = [];
10
+ for (let i = 0; i < fields.length; i++) {
11
+ const entry = fields[i];
12
+ if (entry.length < 4)
13
+ continue;
14
+ const xy = entry.slice(0, 2);
15
+ paths.push(entry.slice(3));
16
+ if (/[RC]/.test(xy) && i + 1 < fields.length) {
17
+ paths.push(fields[++i]);
18
+ }
19
+ }
20
+ return paths;
21
+ }
22
+ /** Every path with uncommitted changes (including untracked files) in a checkout. */
23
+ export function getStatusPaths(cwd) {
24
+ return parseStatusZ(run("git", ["-C", cwd, "status", "--porcelain", "-z", "--untracked-files=all"], { trim: false }));
25
+ }
@@ -1,10 +1,70 @@
1
1
  export interface WorktreeInfo {
2
2
  path: string;
3
+ /** Branch name without `refs/heads/`, or `"detached"`. */
3
4
  branch: string;
5
+ /**
6
+ * The main checkout: the first entry of `git worktree list` (in bare and
7
+ * `--separate-git-dir` layouts that entry is the repository itself), or
8
+ * the linked worktree getWorktrees marked main (see `markedMain`).
9
+ */
4
10
  isMain: boolean;
11
+ /**
12
+ * A linked worktree marked main by getWorktrees (bare layouts: the
13
+ * worktree on the default branch). Git still lists it as a linked
14
+ * worktree, so a record wtc made for it before it became the main
15
+ * checkout is still its record — never an orphan.
16
+ */
17
+ markedMain?: boolean;
18
+ /** Commit checked out (absent for a bare entry or an unborn branch). */
19
+ head?: string;
20
+ bare: boolean;
21
+ detached: boolean;
22
+ locked: boolean;
23
+ /** Git reports the worktree directory as missing on disk. */
24
+ prunable: boolean;
25
+ /**
26
+ * Locked worktree whose checkout is missing on disk (an unmounted drive):
27
+ * git never marks a locked worktree prunable, but it cannot be started.
28
+ * It still exists for identity purposes: its record, index and stack are
29
+ * kept, never pruned.
30
+ */
31
+ missing?: boolean;
32
+ /**
33
+ * The worktree's git admin dir (`<common dir>/worktrees/<name>`), see
34
+ * `worktreeAdminDir`. It survives `git worktree move` and is deleted by
35
+ * `git worktree remove`/`prune`, so wtc keeps its stable id there.
36
+ */
37
+ adminDir?: string;
5
38
  }
6
- export declare function getWorktrees(repoRoot: string): WorktreeInfo[];
39
+ /**
40
+ * Parse `git worktree list --porcelain`. Blocks are separated by blank lines;
41
+ * flag lines (`bare`, `detached`, `locked [reason]`, `prunable [reason]`) may
42
+ * carry a trailing reason.
43
+ */
44
+ export declare function parseWorktreePorcelain(output: string): WorktreeInfo[];
45
+ /** True when two paths name the same directory (resolving symlinks when they exist). */
46
+ export declare function samePath(a: string, b: string): boolean;
47
+ /**
48
+ * A linked worktree's git admin dir (`<common dir>/worktrees/<name>`):
49
+ * read from its `.git` file (`gitdir: …`, relative to the worktree) with no
50
+ * subprocess, else asked of git. `undefined` when neither answers.
51
+ */
52
+ export declare function worktreeAdminDir(wtPath: string): string | undefined;
53
+ /**
54
+ * The admin dir (`<common dir>/worktrees/<name>`) whose `gitdir` file points
55
+ * at `<wtPath>/.git` — found without the checkout, which may be missing.
56
+ */
57
+ export declare function adminDirByPath(commonDir: string, wtPath: string): string | undefined;
58
+ /**
59
+ * Every worktree git knows about, main first, with on-disk checks applied.
60
+ * `mainRoot` (from getRepoInfo, when it found the main checkout) is marked
61
+ * main too: in a bare-repo layout the first entry is the bare repo and the
62
+ * main checkout is one of the linked worktrees — it must never be started,
63
+ * synced onto, or removed. Pass no `mainRoot` when the main checkout is
64
+ * unknown: then no linked worktree is mistaken for it.
65
+ */
66
+ export declare function getWorktrees(repoRoot: string, mainRoot?: string, commonDir?: string): WorktreeInfo[];
67
+ /** Linked worktrees wtc can manage: not the main one, not bare, still on disk. */
68
+ export declare function isCandidate(wt: WorktreeInfo): boolean;
7
69
  export declare function getNonMainWorktrees(repoRoot: string): WorktreeInfo[];
8
- export declare function getWorktreeByIndex(repoRoot: string, index: number): WorktreeInfo | null;
9
70
  export declare function getWorktreeBranch(wtPath: string): string;
10
- export declare function getWorktreeHead(wtPath: string): string;
@@ -1,40 +1,184 @@
1
- import { exec, execSafe } from "../utils/exec.js";
2
- export function getWorktrees(repoRoot) {
3
- const output = exec(`git -C "${repoRoot}" worktree list --porcelain`);
4
- const blocks = output.split("\n\n").filter(Boolean);
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { run, runSafe } from "../utils/exec.js";
4
+ /**
5
+ * Parse `git worktree list --porcelain`. Blocks are separated by blank lines;
6
+ * flag lines (`bare`, `detached`, `locked [reason]`, `prunable [reason]`) may
7
+ * carry a trailing reason.
8
+ */
9
+ export function parseWorktreePorcelain(output) {
5
10
  const worktrees = [];
6
- for (const block of blocks) {
7
- const lines = block.split("\n");
8
- let wtPath = "";
9
- let branch = "detached";
10
- for (const line of lines) {
11
- if (line.startsWith("worktree ")) {
12
- wtPath = line.slice("worktree ".length);
13
- }
14
- if (line.startsWith("branch ")) {
15
- branch = line.slice("branch ".length).replace("refs/heads/", "");
16
- }
11
+ let current = null;
12
+ const flush = () => {
13
+ if (current)
14
+ worktrees.push(current);
15
+ current = null;
16
+ };
17
+ for (const line of output.split("\n")) {
18
+ if (line === "") {
19
+ flush();
20
+ continue;
17
21
  }
18
- if (wtPath) {
19
- worktrees.push({
20
- path: wtPath,
21
- branch,
22
+ if (line.startsWith("worktree ")) {
23
+ flush();
24
+ current = {
25
+ path: path.resolve(line.slice("worktree ".length)),
26
+ branch: "detached",
22
27
  isMain: worktrees.length === 0,
23
- });
28
+ bare: false,
29
+ detached: false,
30
+ locked: false,
31
+ prunable: false,
32
+ };
33
+ continue;
34
+ }
35
+ if (!current)
36
+ continue;
37
+ const wt = current;
38
+ const [key, ...rest] = line.split(" ");
39
+ const value = rest.join(" ");
40
+ switch (key) {
41
+ case "HEAD":
42
+ wt.head = value;
43
+ break;
44
+ case "branch":
45
+ wt.branch = value.replace(/^refs\/heads\//, "");
46
+ break;
47
+ case "bare":
48
+ wt.bare = true;
49
+ break;
50
+ case "detached":
51
+ wt.detached = true;
52
+ break;
53
+ case "locked":
54
+ wt.locked = true;
55
+ break;
56
+ case "prunable":
57
+ wt.prunable = true;
58
+ break;
24
59
  }
25
60
  }
61
+ flush();
26
62
  return worktrees;
27
63
  }
28
- export function getNonMainWorktrees(repoRoot) {
29
- return getWorktrees(repoRoot).filter((wt) => !wt.isMain);
64
+ /** True when two paths name the same directory (resolving symlinks when they exist). */
65
+ export function samePath(a, b) {
66
+ if (path.resolve(a) === path.resolve(b))
67
+ return true;
68
+ try {
69
+ return fs.realpathSync.native(a) === fs.realpathSync.native(b);
70
+ }
71
+ catch {
72
+ return false;
73
+ }
30
74
  }
31
- export function getWorktreeByIndex(repoRoot, index) {
32
- const nonMain = getNonMainWorktrees(repoRoot);
33
- return nonMain[index - 1] ?? null;
75
+ /**
76
+ * A linked worktree's git admin dir (`<common dir>/worktrees/<name>`):
77
+ * read from its `.git` file (`gitdir: …`, relative to the worktree) with no
78
+ * subprocess, else asked of git. `undefined` when neither answers.
79
+ */
80
+ export function worktreeAdminDir(wtPath) {
81
+ try {
82
+ const match = /^gitdir:\s*(.+?)\s*$/m.exec(fs.readFileSync(path.join(wtPath, ".git"), "utf-8"));
83
+ if (match)
84
+ return path.resolve(wtPath, match[1]);
85
+ }
86
+ catch {
87
+ // Not a readable file: ask git below.
88
+ }
89
+ const dir = runSafe("git", ["-C", wtPath, "rev-parse", "--absolute-git-dir"]);
90
+ return dir ? path.resolve(dir) : undefined;
34
91
  }
35
- export function getWorktreeBranch(wtPath) {
36
- return (execSafe(`git -C "${wtPath}" rev-parse --abbrev-ref HEAD`) ?? "detached");
92
+ /**
93
+ * The admin dir (`<common dir>/worktrees/<name>`) whose `gitdir` file points
94
+ * at `<wtPath>/.git` — found without the checkout, which may be missing.
95
+ */
96
+ export function adminDirByPath(commonDir, wtPath) {
97
+ const dir = path.join(commonDir, "worktrees");
98
+ let names;
99
+ try {
100
+ names = fs.readdirSync(dir);
101
+ }
102
+ catch {
103
+ return undefined;
104
+ }
105
+ const target = path.join(path.resolve(wtPath), ".git");
106
+ for (const name of names) {
107
+ const admin = path.join(dir, name);
108
+ let gitdir;
109
+ try {
110
+ gitdir = fs.readFileSync(path.join(admin, "gitdir"), "utf-8").trim();
111
+ }
112
+ catch {
113
+ continue;
114
+ }
115
+ // Absolute, or relative to the admin dir (worktree.useRelativePaths).
116
+ if (gitdir && path.resolve(admin, gitdir) === target)
117
+ return admin;
118
+ }
119
+ return undefined;
120
+ }
121
+ /**
122
+ * Check a linked worktree's checkout on disk: find its admin dir, and flag
123
+ * it when the checkout is gone. Git only reports `prunable` since 2.31, and
124
+ * never for locked worktrees — without this a deleted worktree counted as
125
+ * live and `start` recreated its directory (holding nothing but
126
+ * compose.yaml and .env) to run compose in. A locked one whose checkout is
127
+ * gone (an unmounted drive) is `missing`, not removed: git keeps it, and so
128
+ * does wtc. Its lock is also read from the admin dir, for a git whose
129
+ * porcelain does not report it.
130
+ */
131
+ function inspectCheckout(wt, commonDir) {
132
+ if (wt.isMain || wt.bare || wt.prunable)
133
+ return wt;
134
+ if (!fs.lstatSync(path.join(wt.path, ".git"), { throwIfNoEntry: false })) {
135
+ const common = commonDir();
136
+ const adminDir = common ? adminDirByPath(common, wt.path) : undefined;
137
+ const locked = wt.locked || (adminDir !== undefined && fs.existsSync(path.join(adminDir, "locked")));
138
+ if (!locked)
139
+ return { ...wt, prunable: true };
140
+ return adminDir ? { ...wt, locked: true, missing: true, adminDir } : { ...wt, locked: true, missing: true };
141
+ }
142
+ const adminDir = worktreeAdminDir(wt.path);
143
+ return adminDir ? { ...wt, adminDir } : wt;
144
+ }
145
+ /**
146
+ * Every worktree git knows about, main first, with on-disk checks applied.
147
+ * `mainRoot` (from getRepoInfo, when it found the main checkout) is marked
148
+ * main too: in a bare-repo layout the first entry is the bare repo and the
149
+ * main checkout is one of the linked worktrees — it must never be started,
150
+ * synced onto, or removed. Pass no `mainRoot` when the main checkout is
151
+ * unknown: then no linked worktree is mistaken for it.
152
+ */
153
+ export function getWorktrees(repoRoot, mainRoot, commonDir) {
154
+ let common = commonDir;
155
+ const commonDirOf = () => {
156
+ if (common === undefined) {
157
+ // git < 2.31 has no --path-format: resolve the relative answer instead.
158
+ const abs = runSafe("git", ["-C", repoRoot, "rev-parse", "--path-format=absolute", "--git-common-dir"]);
159
+ const out = abs && path.isAbsolute(abs) ? abs : runSafe("git", ["-C", repoRoot, "rev-parse", "--git-common-dir"]);
160
+ common = out ? path.resolve(repoRoot, out) : "";
161
+ }
162
+ return common || undefined;
163
+ };
164
+ return parseWorktreePorcelain(run("git", ["-C", repoRoot, "worktree", "list", "--porcelain"])).map((wt, i) => {
165
+ // The first entry is the main checkout, the bare repo, or a git dir.
166
+ if (i === 0 || wt.bare)
167
+ return wt;
168
+ const inspected = inspectCheckout(wt, commonDirOf);
169
+ return mainRoot !== undefined && samePath(inspected.path, mainRoot)
170
+ ? { ...inspected, isMain: true, markedMain: true }
171
+ : inspected;
172
+ });
173
+ }
174
+ /** Linked worktrees wtc can manage: not the main one, not bare, still on disk. */
175
+ export function isCandidate(wt) {
176
+ return !wt.isMain && !wt.bare && !wt.prunable && !wt.missing;
37
177
  }
38
- export function getWorktreeHead(wtPath) {
39
- return exec(`git -C "${wtPath}" rev-parse HEAD`);
178
+ export function getNonMainWorktrees(repoRoot) {
179
+ return getWorktrees(repoRoot).filter(isCandidate);
180
+ }
181
+ export function getWorktreeBranch(wtPath) {
182
+ return (runSafe("git", ["-C", wtPath, "rev-parse", "--abbrev-ref", "HEAD"]) ??
183
+ "detached");
40
184
  }
@@ -1 +1,3 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ export declare function createMcpServer(): McpServer;
1
3
  export declare function startMcpServer(): Promise<void>;