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,15 @@
1
+ /**
2
+ * How an operation talks to the outside world. The CLI streams compose output
3
+ * to the terminal; the MCP server captures it (stdout is its JSON-RPC
4
+ * channel) and keeps the event loop free while compose runs.
5
+ */
6
+ export interface CoreIo {
7
+ /** Inherit stdio for compose (CLI) instead of capturing output (MCP). */
8
+ live: boolean;
9
+ /** Directory wtc runs from: locates the repo and resolves `.` selectors. */
10
+ cwd?: string;
11
+ /** Cancels running compose commands (an MCP client's cancellation). */
12
+ signal?: AbortSignal;
13
+ /** Receives captured compose output lines (MCP progress), when not `live`. */
14
+ onOutput?: (line: string) => void;
15
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,4 +1,51 @@
1
- export declare function getChangedFiles(repoRoot: string, wtPath: string, currentBranch: string, wtBranch: string): string[];
1
+ /** Root compose filenames; wtc overwrites these in every worktree. */
2
+ export declare const PROMOTE_EXCLUDES: Set<string>;
3
+ /**
4
+ * Local env files are excluded from promote — wtc rewrites them with
5
+ * per-worktree ports: `.env`, `.env.development`, `.env.local`, …
6
+ */
7
+ export declare function isEnvFile(file: string): boolean;
8
+ /** Split NUL-terminated git output (`-z`) into paths. */
9
+ export declare function splitNul(output: string): string[];
10
+ /** Resolve a ref to a commit id, or throw a readable error. */
11
+ export declare function resolveCommit(cwd: string, ref: string): string;
12
+ /** Merge-base of the target checkout's HEAD and the worktree's HEAD. */
13
+ export declare function getMergeBase(targetRoot: string, wtPath: string): string;
14
+ /**
15
+ * Files the target branch itself changed (committed) since `mergeBase`.
16
+ * Promote copies whole files, so for a file both sides changed it would
17
+ * silently revert the target's commits.
18
+ */
19
+ export declare function getTargetChangedFiles(targetRoot: string, mergeBase: string): string[];
20
+ /**
21
+ * Files a worktree changed relative to its merge-base with `targetRoot`'s
22
+ * HEAD: committed + staged + unstaged changes in one `git diff <merge-base>`
23
+ * (merge-base vs working tree), plus untracked files. `-z` keeps non-ASCII
24
+ * names intact (otherwise `core.quotePath` turns `café.txt` into a quoted
25
+ * escape that matches no file); `--no-renames` reports a rename as delete +
26
+ * add so the old path is removed from the target too.
27
+ */
28
+ export declare function getChangedFiles(targetRoot: string, wtPath: string, excludes?: Set<string>, mergeBase?: string): string[];
29
+ /**
30
+ * Paths in the target checkout that promote must not overwrite: tracked
31
+ * changes (staged or unstaged) AND untracked files — an untracked file in
32
+ * main is just as much unsaved work.
33
+ */
2
34
  export declare function getLocalDirtyFiles(repoRoot: string): string[];
3
35
  export declare function findConflicts(files: string[], dirtyFiles: string[]): string[];
4
- export declare function promoteFiles(repoRoot: string, wtPath: string, files: string[]): void;
36
+ /**
37
+ * Validate every path before anything is written (all-or-nothing): each must
38
+ * stay inside both roots lexically *and* physically — see `assertContained`.
39
+ */
40
+ export declare function assertPromotable(targetRoot: string, wtPath: string, files: string[]): void;
41
+ /**
42
+ * Copy (or delete) each changed file from the worktree into the target.
43
+ * Every path is validated up front (`assertPromotable`) and re-checked
44
+ * before each write — a symlink created earlier in the same run must not be
45
+ * followed either. A symlink at the final component in the target is
46
+ * replaced (unlinked) on write and removed (unlinked, not followed) on
47
+ * delete. Deletions run first. Symlinks are recreated as symlinks. Returns
48
+ * paths that were skipped (directories such as submodules, non-empty
49
+ * directories in the way of a file or symlink).
50
+ */
51
+ export declare function promoteFiles(repoRoot: string, wtPath: string, files: string[]): string[];
@@ -1,58 +1,180 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { exec, execSafe } from "../utils/exec.js";
4
- const PROMOTE_EXCLUDES = new Set([
5
- ".env",
3
+ import { run } from "../utils/exec.js";
4
+ import { parentPlacement, resolveInside, symlinkAncestor } from "../utils/paths.js";
5
+ /** Root compose filenames; wtc overwrites these in every worktree. */
6
+ export const PROMOTE_EXCLUDES = new Set([
6
7
  "docker-compose.yml",
7
8
  "docker-compose.yaml",
8
9
  "compose.yml",
9
10
  "compose.yaml",
10
11
  ]);
11
- function resolveRef(repoRoot, ref) {
12
- return exec(`git -C "${repoRoot}" rev-parse "${ref}"`);
13
- }
14
- export function getChangedFiles(repoRoot, wtPath, currentBranch, wtBranch) {
15
- const currentRef = resolveRef(repoRoot, currentBranch === "HEAD" ? "HEAD" : currentBranch);
16
- const wtRef = resolveRef(wtPath, "HEAD");
17
- const mergeBase = exec(`git -C "${repoRoot}" merge-base "${currentRef}" "${wtRef}"`);
18
- const committed = execSafe(`git -C "${wtPath}" diff --name-only "${mergeBase}" HEAD`) ?? "";
19
- let uncommitted = "";
20
- const hasStagedOrUnstaged = execSafe(`git -C "${wtPath}" diff --quiet`) === null ||
21
- execSafe(`git -C "${wtPath}" diff --cached --quiet`) === null;
22
- if (hasStagedOrUnstaged) {
23
- uncommitted = execSafe(`git -C "${wtPath}" diff --name-only HEAD`) ?? "";
24
- }
25
- const untracked = execSafe(`git -C "${wtPath}" ls-files --others --exclude-standard`) ?? "";
26
- const allFiles = [committed, uncommitted, untracked]
27
- .join("\n")
28
- .split("\n")
29
- .map((f) => f.trim())
30
- .filter(Boolean);
31
- const unique = [...new Set(allFiles)];
32
- return unique.filter((f) => !PROMOTE_EXCLUDES.has(f));
12
+ /** Committed env templates; wtc never writes these, so they stay promotable. */
13
+ const ENV_TEMPLATES = new Set([
14
+ ".env.example",
15
+ ".env.sample",
16
+ ".env.template",
17
+ ".env.dist",
18
+ ".env.defaults",
19
+ ]);
20
+ /**
21
+ * Local env files are excluded from promote — wtc rewrites them with
22
+ * per-worktree ports: `.env`, `.env.development`, `.env.local`, …
23
+ */
24
+ export function isEnvFile(file) {
25
+ const base = path.posix.basename(file);
26
+ if (ENV_TEMPLATES.has(base))
27
+ return false;
28
+ return base === ".env" || base.startsWith(".env.");
29
+ }
30
+ /** Split NUL-terminated git output (`-z`) into paths. */
31
+ export function splitNul(output) {
32
+ return output.split("\0").filter(Boolean);
33
+ }
34
+ /** Like `run`, but keeps NUL separators and trailing whitespace in paths intact. */
35
+ function gitPaths(cwd, args) {
36
+ return splitNul(run("git", ["-C", cwd, ...args], { trim: false }));
37
+ }
38
+ /** Resolve a ref to a commit id, or throw a readable error. */
39
+ export function resolveCommit(cwd, ref) {
40
+ try {
41
+ return run("git", ["-C", cwd, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
42
+ }
43
+ catch {
44
+ throw new Error(`Cannot resolve ${ref} to a commit in ${cwd} (no commits yet?).`);
45
+ }
33
46
  }
47
+ /** Merge-base of the target checkout's HEAD and the worktree's HEAD. */
48
+ export function getMergeBase(targetRoot, wtPath) {
49
+ const targetHead = resolveCommit(targetRoot, "HEAD");
50
+ const wtHead = resolveCommit(wtPath, "HEAD");
51
+ return run("git", ["-C", targetRoot, "merge-base", targetHead, wtHead]);
52
+ }
53
+ /**
54
+ * Files the target branch itself changed (committed) since `mergeBase`.
55
+ * Promote copies whole files, so for a file both sides changed it would
56
+ * silently revert the target's commits.
57
+ */
58
+ export function getTargetChangedFiles(targetRoot, mergeBase) {
59
+ return gitPaths(targetRoot, ["diff", "--name-only", "-z", "--no-renames", mergeBase, "HEAD", "--"]);
60
+ }
61
+ /**
62
+ * Files a worktree changed relative to its merge-base with `targetRoot`'s
63
+ * HEAD: committed + staged + unstaged changes in one `git diff <merge-base>`
64
+ * (merge-base vs working tree), plus untracked files. `-z` keeps non-ASCII
65
+ * names intact (otherwise `core.quotePath` turns `café.txt` into a quoted
66
+ * escape that matches no file); `--no-renames` reports a rename as delete +
67
+ * add so the old path is removed from the target too.
68
+ */
69
+ export function getChangedFiles(targetRoot, wtPath, excludes = PROMOTE_EXCLUDES, mergeBase = getMergeBase(targetRoot, wtPath)) {
70
+ const changed = gitPaths(wtPath, ["diff", "--name-only", "-z", "--no-renames", mergeBase, "--"]);
71
+ const untracked = gitPaths(wtPath, ["ls-files", "--others", "--exclude-standard", "-z"]);
72
+ const unique = [...new Set([...changed, ...untracked])];
73
+ return unique.filter((f) => !excludes.has(f) && !isEnvFile(f));
74
+ }
75
+ /**
76
+ * Paths in the target checkout that promote must not overwrite: tracked
77
+ * changes (staged or unstaged) AND untracked files — an untracked file in
78
+ * main is just as much unsaved work.
79
+ */
34
80
  export function getLocalDirtyFiles(repoRoot) {
35
- const unstaged = execSafe(`git -C "${repoRoot}" diff --name-only HEAD`) ?? "";
36
- const staged = execSafe(`git -C "${repoRoot}" diff --cached --name-only HEAD`) ?? "";
37
- return [...new Set([unstaged, staged].join("\n").split("\n"))]
38
- .map((f) => f.trim())
39
- .filter(Boolean);
81
+ const tracked = gitPaths(repoRoot, ["diff", "--name-only", "-z", "--no-renames", "HEAD", "--"]);
82
+ const untracked = gitPaths(repoRoot, ["ls-files", "--others", "--exclude-standard", "-z"]);
83
+ return [...new Set([...tracked, ...untracked])];
40
84
  }
41
85
  export function findConflicts(files, dirtyFiles) {
42
86
  const dirtySet = new Set(dirtyFiles);
43
87
  return files.filter((f) => dirtySet.has(f));
44
88
  }
89
+ /**
90
+ * Throw when promoting `rel` would pass through a symlink on either side.
91
+ * Target: a symlinked (or non-directory) ancestor would make the write or
92
+ * delete land outside the checkout (`data -> /var/shared`), and the realpath
93
+ * of the directory that will hold the file must stay inside the target.
94
+ * Worktree: content is never read through a symlinked directory the branch
95
+ * planted (`config -> ~/.ssh`).
96
+ */
97
+ function assertContained(targetRoot, wtPath, rel) {
98
+ if (!resolveInside(wtPath, rel) || !resolveInside(targetRoot, rel)) {
99
+ throw new Error(`Refusing to promote "${rel}": path escapes the repository.`);
100
+ }
101
+ const targetLink = symlinkAncestor(targetRoot, rel);
102
+ if (targetLink) {
103
+ throw new Error(`Refusing to promote "${rel}": ${targetLink} in the target is a symlink (or not a directory), so the file would land outside the checkout. Replace it with a real directory first.`);
104
+ }
105
+ if (parentPlacement(targetRoot, rel) !== "inside") {
106
+ throw new Error(`Refusing to promote "${rel}": its directory resolves outside the target checkout.`);
107
+ }
108
+ const wtLink = symlinkAncestor(wtPath, rel);
109
+ if (wtLink) {
110
+ throw new Error(`Refusing to promote "${rel}": ${wtLink} in the worktree is a symlink (or not a directory); promote never reads through one. Apply that change to the target by hand.`);
111
+ }
112
+ }
113
+ /**
114
+ * Validate every path before anything is written (all-or-nothing): each must
115
+ * stay inside both roots lexically *and* physically — see `assertContained`.
116
+ */
117
+ export function assertPromotable(targetRoot, wtPath, files) {
118
+ for (const f of files)
119
+ assertContained(targetRoot, wtPath, f);
120
+ }
121
+ /**
122
+ * Copy (or delete) each changed file from the worktree into the target.
123
+ * Every path is validated up front (`assertPromotable`) and re-checked
124
+ * before each write — a symlink created earlier in the same run must not be
125
+ * followed either. A symlink at the final component in the target is
126
+ * replaced (unlinked) on write and removed (unlinked, not followed) on
127
+ * delete. Deletions run first. Symlinks are recreated as symlinks. Returns
128
+ * paths that were skipped (directories such as submodules, non-empty
129
+ * directories in the way of a file or symlink).
130
+ */
45
131
  export function promoteFiles(repoRoot, wtPath, files) {
46
- for (const f of files) {
47
- const src = path.join(wtPath, f);
48
- const dst = path.join(repoRoot, f);
49
- if (fs.existsSync(src)) {
50
- fs.mkdirSync(path.dirname(dst), { recursive: true });
51
- fs.copyFileSync(src, dst);
132
+ assertPromotable(repoRoot, wtPath, files);
133
+ const resolved = files.map((f) => {
134
+ const src = path.resolve(wtPath, f);
135
+ const dst = path.resolve(repoRoot, f);
136
+ return { f, src, dst, stat: fs.lstatSync(src, { throwIfNoEntry: false }) };
137
+ });
138
+ const skipped = [];
139
+ const deletions = resolved.filter((r) => !r.stat);
140
+ const writes = resolved.filter((r) => r.stat);
141
+ for (const { f, dst } of deletions) {
142
+ assertContained(repoRoot, wtPath, f);
143
+ const existing = fs.lstatSync(dst, { throwIfNoEntry: false });
144
+ if (!existing)
145
+ continue;
146
+ if (existing.isDirectory()) {
147
+ skipped.push(f);
148
+ continue;
149
+ }
150
+ fs.unlinkSync(dst);
151
+ }
152
+ for (const { f, src, dst, stat } of writes) {
153
+ if (!stat.isFile() && !stat.isSymbolicLink()) {
154
+ skipped.push(f);
155
+ continue;
156
+ }
157
+ assertContained(repoRoot, wtPath, f);
158
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
159
+ const existing = fs.lstatSync(dst, { throwIfNoEntry: false });
160
+ if (existing?.isDirectory()) {
161
+ // A file or symlink replacing a directory: only an empty one can go.
162
+ if (fs.readdirSync(dst).length > 0) {
163
+ skipped.push(f);
164
+ continue;
165
+ }
166
+ fs.rmdirSync(dst);
167
+ }
168
+ else if (existing && (stat.isSymbolicLink() || !existing.isFile())) {
169
+ // Never write through a symlink (or into a FIFO) sitting at the path.
170
+ fs.unlinkSync(dst);
171
+ }
172
+ if (stat.isSymbolicLink()) {
173
+ fs.symlinkSync(fs.readlinkSync(src), dst);
52
174
  }
53
175
  else {
54
- if (fs.existsSync(dst))
55
- fs.unlinkSync(dst);
176
+ fs.copyFileSync(src, dst);
56
177
  }
57
178
  }
179
+ return skipped;
58
180
  }
@@ -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;