ikanban-web 0.1.1

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 (175) hide show
  1. package/README.md +65 -0
  2. package/bin/cli.js +1055 -0
  3. package/dist/apple-touch-icon-120x120.png +0 -0
  4. package/dist/apple-touch-icon-152x152.png +0 -0
  5. package/dist/apple-touch-icon-167x167.png +0 -0
  6. package/dist/apple-touch-icon-180x180.png +0 -0
  7. package/dist/apple-touch-icon.png +0 -0
  8. package/dist/apple-touch-icon.svg +16 -0
  9. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  10. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  11. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  12. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  13. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  14. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  15. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  16. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  17. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  18. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  19. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  20. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  21. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  22. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  23. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  24. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  25. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  26. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  27. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  28. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  29. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  30. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  31. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  32. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  33. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  34. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  35. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  36. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  37. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  38. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  39. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  40. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  41. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  42. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  43. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  44. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  45. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  46. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  47. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  48. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  49. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  50. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  51. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  52. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  53. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  54. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  55. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  56. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  57. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  58. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  59. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  60. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  61. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  62. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  63. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  64. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  65. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  66. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  67. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  68. package/dist/assets/ToolOutputDialog-BgFj3J4u.js +5 -0
  69. package/dist/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  70. package/dist/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  71. package/dist/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  72. package/dist/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  73. package/dist/assets/ibm-plex-mono-latin-600-normal-BgSNZQsw.woff2 +0 -0
  74. package/dist/assets/ibm-plex-mono-latin-600-normal-DWFSQ4vo.woff +0 -0
  75. package/dist/assets/ibm-plex-sans-latin-400-normal-CDDApCn2.woff2 +0 -0
  76. package/dist/assets/ibm-plex-sans-latin-400-normal-CYLoc0-x.woff +0 -0
  77. package/dist/assets/ibm-plex-sans-latin-500-normal-6ng42L7E.woff2 +0 -0
  78. package/dist/assets/ibm-plex-sans-latin-500-normal-BgVn5rGT.woff +0 -0
  79. package/dist/assets/ibm-plex-sans-latin-600-normal-Cu4Hd6ag.woff +0 -0
  80. package/dist/assets/ibm-plex-sans-latin-600-normal-CuJfVYMP.woff2 +0 -0
  81. package/dist/assets/index-BQJPAP5f.css +1 -0
  82. package/dist/assets/index-MBuF9PXk.js +2 -0
  83. package/dist/assets/main-C1GggQif.css +1 -0
  84. package/dist/assets/main-Dyy8WvPJ.js +311 -0
  85. package/dist/assets/vendor--DEobTDja.css +1 -0
  86. package/dist/assets/vendor-.bun-KwPUu5oc.js +4594 -0
  87. package/dist/assets/wasm-CG6Dc4jp.js +1 -0
  88. package/dist/assets/worker-suRQxAtO.js +155 -0
  89. package/dist/favicon-16.png +0 -0
  90. package/dist/favicon-32.png +0 -0
  91. package/dist/favicon.png +0 -0
  92. package/dist/favicon.svg +15 -0
  93. package/dist/index.html +325 -0
  94. package/dist/logo-dark-192x192.png +0 -0
  95. package/dist/logo-dark-512x512.svg +16 -0
  96. package/dist/logo-light-192x192.png +0 -0
  97. package/dist/logo-light-512x512.svg +16 -0
  98. package/dist/pwa-192.png +0 -0
  99. package/dist/pwa-512.png +0 -0
  100. package/dist/pwa-maskable-192.png +0 -0
  101. package/dist/pwa-maskable-512.png +0 -0
  102. package/dist/site.webmanifest +22 -0
  103. package/dist/sw.js +1 -0
  104. package/package.json +102 -0
  105. package/public/apple-touch-icon-120x120.png +0 -0
  106. package/public/apple-touch-icon-152x152.png +0 -0
  107. package/public/apple-touch-icon-167x167.png +0 -0
  108. package/public/apple-touch-icon-180x180.png +0 -0
  109. package/public/apple-touch-icon.png +0 -0
  110. package/public/apple-touch-icon.svg +16 -0
  111. package/public/favicon-16.png +0 -0
  112. package/public/favicon-32.png +0 -0
  113. package/public/favicon.png +0 -0
  114. package/public/favicon.svg +15 -0
  115. package/public/logo-dark-192x192.png +0 -0
  116. package/public/logo-dark-512x512.svg +16 -0
  117. package/public/logo-light-192x192.png +0 -0
  118. package/public/logo-light-512x512.svg +16 -0
  119. package/public/pwa-192.png +0 -0
  120. package/public/pwa-512.png +0 -0
  121. package/public/pwa-maskable-192.png +0 -0
  122. package/public/pwa-maskable-512.png +0 -0
  123. package/public/site.webmanifest +22 -0
  124. package/server/TERMINAL_INPUT_WS_PROTOCOL.md +44 -0
  125. package/server/index.d.ts +28 -0
  126. package/server/index.js +11181 -0
  127. package/server/lib/cloudflare-tunnel.js +196 -0
  128. package/server/lib/git-credentials.js +74 -0
  129. package/server/lib/git-identity-storage.js +110 -0
  130. package/server/lib/git-service.js +2690 -0
  131. package/server/lib/github-auth.js +307 -0
  132. package/server/lib/github-device-flow.js +50 -0
  133. package/server/lib/github-octokit.js +10 -0
  134. package/server/lib/github-repo.js +55 -0
  135. package/server/lib/notification-message.js +49 -0
  136. package/server/lib/notification-message.test.js +59 -0
  137. package/server/lib/opencode-auth.js +81 -0
  138. package/server/lib/opencode-config.js +1840 -0
  139. package/server/lib/opencode-config.js.d.ts +12 -0
  140. package/server/lib/package-manager.js +255 -0
  141. package/server/lib/quota/DOCUMENTATION.md +52 -0
  142. package/server/lib/quota/index.js +21 -0
  143. package/server/lib/quota/providers/claude.js +107 -0
  144. package/server/lib/quota/providers/codex.js +111 -0
  145. package/server/lib/quota/providers/copilot.js +165 -0
  146. package/server/lib/quota/providers/google/api.js +92 -0
  147. package/server/lib/quota/providers/google/auth.js +108 -0
  148. package/server/lib/quota/providers/google/index.js +124 -0
  149. package/server/lib/quota/providers/google/transforms.js +109 -0
  150. package/server/lib/quota/providers/index.js +128 -0
  151. package/server/lib/quota/providers/interface.js +55 -0
  152. package/server/lib/quota/providers/kimi.js +108 -0
  153. package/server/lib/quota/providers/nanogpt.js +124 -0
  154. package/server/lib/quota/providers/openai.js +91 -0
  155. package/server/lib/quota/providers/openrouter.js +92 -0
  156. package/server/lib/quota/providers/zai.js +91 -0
  157. package/server/lib/quota/utils/auth.js +46 -0
  158. package/server/lib/quota/utils/formatters.js +76 -0
  159. package/server/lib/quota/utils/index.js +10 -0
  160. package/server/lib/quota/utils/transformers.js +55 -0
  161. package/server/lib/skills-catalog/cache.js +29 -0
  162. package/server/lib/skills-catalog/clawdhub/api.js +158 -0
  163. package/server/lib/skills-catalog/clawdhub/index.js +30 -0
  164. package/server/lib/skills-catalog/clawdhub/install.js +223 -0
  165. package/server/lib/skills-catalog/clawdhub/scan.js +113 -0
  166. package/server/lib/skills-catalog/curated-sources.js +21 -0
  167. package/server/lib/skills-catalog/git.js +76 -0
  168. package/server/lib/skills-catalog/install.js +280 -0
  169. package/server/lib/skills-catalog/scan.js +221 -0
  170. package/server/lib/skills-catalog/source.js +85 -0
  171. package/server/lib/summarization-service.js +171 -0
  172. package/server/lib/terminal-input-ws-protocol.js +66 -0
  173. package/server/lib/terminal-input-ws-protocol.test.js +138 -0
  174. package/server/lib/tts-service.js +162 -0
  175. package/server/lib/ui-auth.js +518 -0
@@ -0,0 +1,2690 @@
1
+ import simpleGit from 'simple-git';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import os from 'os';
5
+ import { execFile } from 'child_process';
6
+ import { promisify } from 'util';
7
+
8
+ const fsp = fs.promises;
9
+ const execFileAsync = promisify(execFile);
10
+ const gpgconfCandidates = ['gpgconf', '/opt/homebrew/bin/gpgconf', '/usr/local/bin/gpgconf'];
11
+
12
+ /**
13
+ * Escape an SSH key path for use in core.sshCommand.
14
+ * Handles Windows/Unix differences and prevents command injection.
15
+ */
16
+ function escapeSshKeyPath(sshKeyPath) {
17
+ const isWindows = process.platform === 'win32';
18
+
19
+ // Normalize path first on Windows (convert backslashes to forward slashes)
20
+ let normalizedPath = sshKeyPath;
21
+ if (isWindows) {
22
+ normalizedPath = sshKeyPath.replace(/\\/g, '/');
23
+ }
24
+
25
+ // Validate: reject paths with characters that could enable injection
26
+ // Allow only alphanumeric, path separators, dots, dashes, underscores, spaces, and colons (for Windows drives)
27
+ // Note: backslash is not in this list since we've already normalized Windows paths
28
+ const dangerousChars = /[`$!"';&|<>(){}[\]*?#~]/;
29
+ if (dangerousChars.test(normalizedPath)) {
30
+ throw new Error(`SSH key path contains invalid characters: ${sshKeyPath}`);
31
+ }
32
+
33
+ if (isWindows) {
34
+ // On Windows, Git (via MSYS/MinGW) expects Unix-style paths
35
+ // Convert "C:/path" to "/c/path" for MSYS compatibility
36
+ let unixPath = normalizedPath;
37
+ const driveMatch = unixPath.match(/^([A-Za-z]):\//);
38
+ if (driveMatch) {
39
+ unixPath = `/${driveMatch[1].toLowerCase()}${unixPath.slice(2)}`;
40
+ }
41
+
42
+ // Use single quotes for the path (prevents shell interpretation)
43
+ return `'${unixPath}'`;
44
+ } else {
45
+ // On Unix, use single quotes and escape any single quotes in the path
46
+ // Single quotes prevent all shell interpretation except for single quotes themselves
47
+ const escaped = normalizedPath.replace(/'/g, "'\\''");
48
+ return `'${escaped}'`;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Build the SSH command string for git config
54
+ */
55
+ function buildSshCommand(sshKeyPath) {
56
+ const escapedPath = escapeSshKeyPath(sshKeyPath);
57
+ return `ssh -i ${escapedPath} -o IdentitiesOnly=yes`;
58
+ }
59
+
60
+ const isSocketPath = async (candidate) => {
61
+ if (!candidate || typeof candidate !== 'string') {
62
+ return false;
63
+ }
64
+ try {
65
+ const stat = await fsp.stat(candidate);
66
+ return typeof stat.isSocket === 'function' && stat.isSocket();
67
+ } catch {
68
+ return false;
69
+ }
70
+ };
71
+
72
+ const resolveSshAuthSock = async () => {
73
+ const existing = (process.env.SSH_AUTH_SOCK || '').trim();
74
+ if (existing) {
75
+ return existing;
76
+ }
77
+
78
+ if (process.platform === 'win32') {
79
+ return null;
80
+ }
81
+
82
+ const gpgSock = path.join(os.homedir(), '.gnupg', 'S.gpg-agent.ssh');
83
+ if (await isSocketPath(gpgSock)) {
84
+ return gpgSock;
85
+ }
86
+
87
+ const runGpgconf = async (args) => {
88
+ for (const candidate of gpgconfCandidates) {
89
+ try {
90
+ const { stdout } = await execFileAsync(candidate, args);
91
+ return String(stdout || '');
92
+ } catch {
93
+ continue;
94
+ }
95
+ }
96
+ return '';
97
+ };
98
+
99
+ const candidate = (await runGpgconf(['--list-dirs', 'agent-ssh-socket'])).trim();
100
+ if (candidate && await isSocketPath(candidate)) {
101
+ return candidate;
102
+ }
103
+
104
+ if (candidate) {
105
+ await runGpgconf(['--launch', 'gpg-agent']);
106
+ const retried = (await runGpgconf(['--list-dirs', 'agent-ssh-socket'])).trim();
107
+ if (retried && await isSocketPath(retried)) {
108
+ return retried;
109
+ }
110
+ }
111
+
112
+ return null;
113
+ };
114
+
115
+ const buildGitEnv = async () => {
116
+ const env = { ...process.env };
117
+ if (!env.SSH_AUTH_SOCK || !env.SSH_AUTH_SOCK.trim()) {
118
+ const resolved = await resolveSshAuthSock();
119
+ if (resolved) {
120
+ env.SSH_AUTH_SOCK = resolved;
121
+ }
122
+ }
123
+ return env;
124
+ };
125
+
126
+ const createGit = async (directory) => {
127
+ const env = await buildGitEnv();
128
+ if (!directory) {
129
+ return simpleGit({ env });
130
+ }
131
+ return simpleGit({ baseDir: normalizeDirectoryPath(directory), env });
132
+ };
133
+
134
+ const normalizeDirectoryPath = (value) => {
135
+ if (typeof value !== 'string') {
136
+ return value;
137
+ }
138
+
139
+ const trimmed = value.trim();
140
+ if (!trimmed) {
141
+ return trimmed;
142
+ }
143
+
144
+ if (trimmed === '~') {
145
+ return os.homedir();
146
+ }
147
+
148
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
149
+ return path.join(os.homedir(), trimmed.slice(2));
150
+ }
151
+
152
+ return trimmed;
153
+ };
154
+
155
+ const cleanBranchName = (branch) => {
156
+ if (!branch) {
157
+ return branch;
158
+ }
159
+ if (branch.startsWith('refs/heads/')) {
160
+ return branch.substring('refs/heads/'.length);
161
+ }
162
+ if (branch.startsWith('heads/')) {
163
+ return branch.substring('heads/'.length);
164
+ }
165
+ if (branch.startsWith('refs/')) {
166
+ return branch.substring('refs/'.length);
167
+ }
168
+ return branch;
169
+ };
170
+
171
+ const OPENCODE_ADJECTIVES = [
172
+ 'brave',
173
+ 'calm',
174
+ 'clever',
175
+ 'cosmic',
176
+ 'crisp',
177
+ 'curious',
178
+ 'eager',
179
+ 'gentle',
180
+ 'glowing',
181
+ 'happy',
182
+ 'hidden',
183
+ 'jolly',
184
+ 'kind',
185
+ 'lucky',
186
+ 'mighty',
187
+ 'misty',
188
+ 'neon',
189
+ 'nimble',
190
+ 'playful',
191
+ 'proud',
192
+ 'quick',
193
+ 'quiet',
194
+ 'shiny',
195
+ 'silent',
196
+ 'stellar',
197
+ 'sunny',
198
+ 'swift',
199
+ 'tidy',
200
+ 'witty',
201
+ ];
202
+
203
+ const OPENCODE_NOUNS = [
204
+ 'cabin',
205
+ 'cactus',
206
+ 'canyon',
207
+ 'circuit',
208
+ 'comet',
209
+ 'eagle',
210
+ 'engine',
211
+ 'falcon',
212
+ 'forest',
213
+ 'garden',
214
+ 'harbor',
215
+ 'island',
216
+ 'knight',
217
+ 'lagoon',
218
+ 'meadow',
219
+ 'moon',
220
+ 'mountain',
221
+ 'nebula',
222
+ 'orchid',
223
+ 'otter',
224
+ 'panda',
225
+ 'pixel',
226
+ 'planet',
227
+ 'river',
228
+ 'rocket',
229
+ 'sailor',
230
+ 'squid',
231
+ 'star',
232
+ 'tiger',
233
+ 'wizard',
234
+ 'wolf',
235
+ ];
236
+
237
+ const OPENCODE_WORKTREE_ATTEMPTS = 26;
238
+
239
+ const getOpenCodeDataPath = () => {
240
+ const xdgDataHome = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share');
241
+ return path.join(xdgDataHome, 'opencode');
242
+ };
243
+
244
+ const pickRandom = (values) => values[Math.floor(Math.random() * values.length)];
245
+
246
+ const generateOpenCodeRandomName = () => `${pickRandom(OPENCODE_ADJECTIVES)}-${pickRandom(OPENCODE_NOUNS)}`;
247
+
248
+ const slugWorktreeName = (value) => {
249
+ return String(value || '')
250
+ .trim()
251
+ .replace(/^refs\/heads\//, '')
252
+ .replace(/^heads\//, '')
253
+ .replace(/\s+/g, '-')
254
+ .replace(/^\/+|\/+$/g, '')
255
+ .split('/').join('-')
256
+ .replace(/[^A-Za-z0-9._-]+/g, '-')
257
+ .replace(/-+/g, '-')
258
+ .replace(/^-+/, '')
259
+ .replace(/-+$/, '')
260
+ .slice(0, 80);
261
+ };
262
+
263
+ const parseWorktreePorcelain = (raw) => {
264
+ const lines = String(raw || '').split('\n').map((line) => line.trim());
265
+ const entries = [];
266
+ let current = null;
267
+
268
+ for (const line of lines) {
269
+ if (!line) {
270
+ if (current?.worktree) {
271
+ entries.push(current);
272
+ }
273
+ current = null;
274
+ continue;
275
+ }
276
+
277
+ if (line.startsWith('worktree ')) {
278
+ if (current?.worktree) {
279
+ entries.push(current);
280
+ }
281
+ current = { worktree: line.substring('worktree '.length).trim() };
282
+ continue;
283
+ }
284
+
285
+ if (!current) {
286
+ continue;
287
+ }
288
+
289
+ if (line.startsWith('HEAD ')) {
290
+ current.head = line.substring('HEAD '.length).trim();
291
+ continue;
292
+ }
293
+
294
+ if (line.startsWith('branch ')) {
295
+ const branchRef = line.substring('branch '.length).trim();
296
+ current.branchRef = branchRef;
297
+ current.branch = cleanBranchName(branchRef);
298
+ }
299
+ }
300
+
301
+ if (current?.worktree) {
302
+ entries.push(current);
303
+ }
304
+
305
+ return entries;
306
+ };
307
+
308
+ const canonicalPath = async (input) => {
309
+ const absolutePath = path.resolve(input);
310
+ const realPath = await fsp.realpath(absolutePath).catch(() => absolutePath);
311
+ const normalized = path.normalize(realPath);
312
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
313
+ };
314
+
315
+ const checkPathExists = async (targetPath) => {
316
+ try {
317
+ await fsp.stat(targetPath);
318
+ return true;
319
+ } catch {
320
+ return false;
321
+ }
322
+ };
323
+
324
+ const normalizeStartRef = (value) => {
325
+ const trimmed = String(value || '').trim();
326
+ if (!trimmed) {
327
+ return 'HEAD';
328
+ }
329
+ return trimmed;
330
+ };
331
+
332
+ const parseRemoteBranchRef = (value) => {
333
+ const trimmed = String(value || '').trim();
334
+ if (!trimmed) {
335
+ return null;
336
+ }
337
+
338
+ if (trimmed.startsWith('refs/remotes/')) {
339
+ const rest = trimmed.substring('refs/remotes/'.length);
340
+ const slashIndex = rest.indexOf('/');
341
+ if (slashIndex <= 0 || slashIndex === rest.length - 1) {
342
+ return null;
343
+ }
344
+ return {
345
+ remote: rest.slice(0, slashIndex),
346
+ branch: rest.slice(slashIndex + 1),
347
+ remoteRef: rest,
348
+ fullRef: `refs/remotes/${rest}`,
349
+ };
350
+ }
351
+
352
+ if (trimmed.startsWith('remotes/')) {
353
+ return parseRemoteBranchRef(`refs/${trimmed}`);
354
+ }
355
+
356
+ const slashIndex = trimmed.indexOf('/');
357
+ if (slashIndex <= 0 || slashIndex === trimmed.length - 1) {
358
+ return null;
359
+ }
360
+
361
+ return {
362
+ remote: trimmed.slice(0, slashIndex),
363
+ branch: trimmed.slice(slashIndex + 1),
364
+ remoteRef: trimmed,
365
+ fullRef: `refs/remotes/${trimmed}`,
366
+ };
367
+ };
368
+
369
+ const normalizeUpstreamTarget = (remote, branch) => {
370
+ const remoteName = String(remote || '').trim();
371
+ const branchName = String(branch || '').trim();
372
+ if (!remoteName || !branchName) {
373
+ return null;
374
+ }
375
+ return {
376
+ remote: remoteName,
377
+ branch: branchName,
378
+ full: `${remoteName}/${branchName}`,
379
+ };
380
+ };
381
+
382
+ const parseGitErrorText = (error) => {
383
+ const stderr = typeof error?.stderr === 'string' ? error.stderr : '';
384
+ const stdout = typeof error?.stdout === 'string' ? error.stdout : '';
385
+ const message = typeof error?.message === 'string' ? error.message : '';
386
+ return [stderr, stdout, message]
387
+ .map((chunk) => String(chunk || '').trim())
388
+ .filter(Boolean)
389
+ .join('\n')
390
+ .trim();
391
+ };
392
+
393
+ const runGitCommand = async (cwd, args) => {
394
+ try {
395
+ const { stdout, stderr } = await execFileAsync('git', args, {
396
+ cwd,
397
+ env: await buildGitEnv(),
398
+ maxBuffer: 20 * 1024 * 1024,
399
+ });
400
+ return {
401
+ success: true,
402
+ exitCode: 0,
403
+ stdout: String(stdout || ''),
404
+ stderr: String(stderr || ''),
405
+ };
406
+ } catch (error) {
407
+ return {
408
+ success: false,
409
+ exitCode: typeof error?.code === 'number' ? error.code : 1,
410
+ stdout: String(error?.stdout || ''),
411
+ stderr: String(error?.stderr || ''),
412
+ message: parseGitErrorText(error),
413
+ };
414
+ }
415
+ };
416
+
417
+ const runGitCommandOrThrow = async (cwd, args, fallbackMessage) => {
418
+ const result = await runGitCommand(cwd, args);
419
+ if (!result.success) {
420
+ throw new Error(result.message || fallbackMessage || 'Git command failed');
421
+ }
422
+ return result;
423
+ };
424
+
425
+ const ensureOpenCodeProjectId = async (primaryWorktree) => {
426
+ const gitDir = path.join(primaryWorktree, '.git');
427
+ const idFile = path.join(gitDir, 'opencode');
428
+ const existing = await fsp.readFile(idFile, 'utf8').then((value) => value.trim()).catch(() => '');
429
+ if (existing) {
430
+ return existing;
431
+ }
432
+
433
+ const rootsResult = await runGitCommandOrThrow(
434
+ primaryWorktree,
435
+ ['rev-list', '--max-parents=0', '--all'],
436
+ 'Failed to resolve repository roots'
437
+ );
438
+
439
+ const roots = rootsResult.stdout
440
+ .split('\n')
441
+ .map((line) => line.trim())
442
+ .filter(Boolean)
443
+ .sort((a, b) => a.localeCompare(b));
444
+
445
+ const projectId = roots[0] || '';
446
+ if (!projectId) {
447
+ throw new Error('Failed to derive OpenCode project ID');
448
+ }
449
+
450
+ await fsp.mkdir(gitDir, { recursive: true }).catch(() => undefined);
451
+ await fsp.writeFile(idFile, projectId, 'utf8').catch(() => undefined);
452
+
453
+ return projectId;
454
+ };
455
+
456
+ const resolveWorktreeProjectContext = async (directory) => {
457
+ const directoryPath = normalizeDirectoryPath(directory);
458
+ if (!directoryPath) {
459
+ throw new Error('Directory is required');
460
+ }
461
+
462
+ const topResult = await runGitCommandOrThrow(
463
+ directoryPath,
464
+ ['rev-parse', '--show-toplevel'],
465
+ 'Failed to resolve git top-level directory'
466
+ );
467
+ const sandbox = path.resolve(directoryPath, topResult.stdout.trim());
468
+
469
+ const commonResult = await runGitCommandOrThrow(
470
+ sandbox,
471
+ ['rev-parse', '--git-common-dir'],
472
+ 'Failed to resolve git common directory'
473
+ );
474
+ const commonDir = path.resolve(sandbox, commonResult.stdout.trim());
475
+ const primaryWorktree = path.dirname(commonDir);
476
+ const projectID = await ensureOpenCodeProjectId(primaryWorktree);
477
+ const worktreeRoot = path.join(getOpenCodeDataPath(), 'worktree', projectID);
478
+
479
+ return {
480
+ projectID,
481
+ sandbox,
482
+ primaryWorktree,
483
+ worktreeRoot,
484
+ };
485
+ };
486
+
487
+ const listWorktreeEntries = async (directory) => {
488
+ const rawResult = await runGitCommandOrThrow(
489
+ directory,
490
+ ['worktree', 'list', '--porcelain'],
491
+ 'Failed to list git worktrees'
492
+ );
493
+ return parseWorktreePorcelain(rawResult.stdout);
494
+ };
495
+
496
+ const resolveWorktreeNameCandidates = (baseName) => {
497
+ const normalizedBase = slugWorktreeName(baseName || '');
498
+ if (!normalizedBase) {
499
+ return Array.from({ length: OPENCODE_WORKTREE_ATTEMPTS }, () => generateOpenCodeRandomName());
500
+ }
501
+ return Array.from({ length: OPENCODE_WORKTREE_ATTEMPTS }, (_, index) => {
502
+ if (index === 0) {
503
+ return normalizedBase;
504
+ }
505
+ return `${normalizedBase}-${generateOpenCodeRandomName()}`;
506
+ });
507
+ };
508
+
509
+ const resolveCandidateDirectory = async (worktreeRoot, preferredName, explicitBranchName, primaryWorktree) => {
510
+ const candidates = resolveWorktreeNameCandidates(preferredName);
511
+
512
+ for (const name of candidates) {
513
+ const directory = path.join(worktreeRoot, name);
514
+ if (await checkPathExists(directory)) {
515
+ continue;
516
+ }
517
+
518
+ if (explicitBranchName) {
519
+ return { name, directory, branch: explicitBranchName };
520
+ }
521
+
522
+ const branch = `ikanban/${name}`;
523
+ const branchRef = `refs/heads/${branch}`;
524
+ const branchExists = await runGitCommand(primaryWorktree, ['show-ref', '--verify', '--quiet', branchRef]);
525
+ if (branchExists.success) {
526
+ continue;
527
+ }
528
+
529
+ return { name, directory, branch };
530
+ }
531
+
532
+ throw new Error('Failed to generate a unique worktree name');
533
+ };
534
+
535
+ const resolveBranchForExistingMode = async (primaryWorktree, existingBranch, preferredBranchName) => {
536
+ const requested = String(existingBranch || '').trim();
537
+ if (!requested) {
538
+ throw new Error('existingBranch is required in existing mode');
539
+ }
540
+
541
+ const normalizedLocal = cleanBranchName(requested);
542
+ const localRef = `refs/heads/${normalizedLocal}`;
543
+ const localExists = await runGitCommand(primaryWorktree, ['show-ref', '--verify', '--quiet', localRef]);
544
+ if (localExists.success) {
545
+ return {
546
+ localBranch: normalizedLocal,
547
+ checkoutRef: normalizedLocal,
548
+ createLocalBranch: false,
549
+ remoteRef: null,
550
+ };
551
+ }
552
+
553
+ const remoteRef = parseRemoteBranchRef(requested);
554
+ if (!remoteRef) {
555
+ throw new Error(`Branch not found: ${requested}`);
556
+ }
557
+
558
+ const remoteExists = await runGitCommand(primaryWorktree, ['show-ref', '--verify', '--quiet', remoteRef.fullRef]);
559
+ if (!remoteExists.success) {
560
+ await fetchRemoteBranchRef(primaryWorktree, remoteRef.remote, remoteRef.branch).catch(() => undefined);
561
+ const recheck = await runGitCommand(primaryWorktree, ['show-ref', '--verify', '--quiet', remoteRef.fullRef]);
562
+ if (!recheck.success) {
563
+ throw new Error(`Remote branch not found: ${requested}`);
564
+ }
565
+ }
566
+
567
+ const localBranch = cleanBranchName(preferredBranchName || remoteRef.branch || requested);
568
+ if (!localBranch) {
569
+ throw new Error('Failed to resolve local branch name for existing branch worktree');
570
+ }
571
+
572
+ return {
573
+ localBranch,
574
+ checkoutRef: remoteRef.remoteRef,
575
+ createLocalBranch: true,
576
+ remoteRef,
577
+ };
578
+ };
579
+
580
+ const findBranchInUse = async (primaryWorktree, localBranchName) => {
581
+ if (!localBranchName) {
582
+ return null;
583
+ }
584
+ const entries = await listWorktreeEntries(primaryWorktree);
585
+ const targetRef = `refs/heads/${localBranchName}`;
586
+ const targetClean = cleanBranchName(targetRef);
587
+ return entries.find((entry) => {
588
+ const entryRef = String(entry.branchRef || '').trim();
589
+ const entryClean = cleanBranchName(entryRef || entry.branch || '');
590
+ return entryRef === targetRef || entryClean === targetClean;
591
+ }) || null;
592
+ };
593
+
594
+ const runWorktreeStartCommand = async (directory, command) => {
595
+ const text = String(command || '').trim();
596
+ if (!text) {
597
+ return { success: true };
598
+ }
599
+
600
+ if (process.platform === 'win32') {
601
+ const result = await execFileAsync('cmd', ['/c', text], {
602
+ cwd: directory,
603
+ env: await buildGitEnv(),
604
+ maxBuffer: 20 * 1024 * 1024,
605
+ }).then(({ stdout, stderr }) => ({ success: true, stdout, stderr })).catch((error) => ({
606
+ success: false,
607
+ stdout: error?.stdout,
608
+ stderr: error?.stderr,
609
+ message: parseGitErrorText(error),
610
+ }));
611
+ return result;
612
+ }
613
+
614
+ const result = await execFileAsync('bash', ['-lc', text], {
615
+ cwd: directory,
616
+ env: await buildGitEnv(),
617
+ maxBuffer: 20 * 1024 * 1024,
618
+ }).then(({ stdout, stderr }) => ({ success: true, stdout, stderr })).catch((error) => ({
619
+ success: false,
620
+ stdout: error?.stdout,
621
+ stderr: error?.stderr,
622
+ message: parseGitErrorText(error),
623
+ }));
624
+ return result;
625
+ };
626
+
627
+ const loadProjectStartCommand = async (projectID) => {
628
+ const storagePath = path.join(getOpenCodeDataPath(), 'storage', 'project', `${projectID}.json`);
629
+ try {
630
+ const raw = await fsp.readFile(storagePath, 'utf8');
631
+ const parsed = JSON.parse(raw);
632
+ const start = typeof parsed?.commands?.start === 'string' ? parsed.commands.start.trim() : '';
633
+ return start || '';
634
+ } catch {
635
+ return '';
636
+ }
637
+ };
638
+
639
+ const getProjectStoragePath = (projectID) => {
640
+ return path.join(getOpenCodeDataPath(), 'storage', 'project', `${projectID}.json`);
641
+ };
642
+
643
+ const updateProjectSandboxes = async (projectID, primaryWorktree, updater) => {
644
+ const storagePath = getProjectStoragePath(projectID);
645
+ await fsp.mkdir(path.dirname(storagePath), { recursive: true });
646
+
647
+ const now = Date.now();
648
+ const base = {
649
+ id: projectID,
650
+ worktree: primaryWorktree,
651
+ vcs: 'git',
652
+ sandboxes: [],
653
+ time: {
654
+ created: now,
655
+ updated: now,
656
+ },
657
+ };
658
+
659
+ const parsed = await fsp.readFile(storagePath, 'utf8').then((raw) => JSON.parse(raw)).catch(() => null);
660
+ const current = parsed && typeof parsed === 'object' ? { ...base, ...parsed } : base;
661
+ current.id = String(current.id || projectID);
662
+ current.worktree = String(current.worktree || primaryWorktree);
663
+ current.vcs = current.vcs || 'git';
664
+ current.sandboxes = Array.isArray(current.sandboxes)
665
+ ? current.sandboxes.map((entry) => String(entry || '').trim()).filter(Boolean)
666
+ : [];
667
+ const createdAt = Number(current?.time?.created);
668
+ current.time = {
669
+ created: Number.isFinite(createdAt) && createdAt > 0 ? createdAt : now,
670
+ updated: now,
671
+ };
672
+
673
+ updater(current);
674
+
675
+ current.sandboxes = [...new Set(
676
+ (Array.isArray(current.sandboxes) ? current.sandboxes : [])
677
+ .map((entry) => String(entry || '').trim())
678
+ .filter(Boolean)
679
+ )];
680
+
681
+ await fsp.writeFile(storagePath, `${JSON.stringify(current, null, 2)}\n`, 'utf8');
682
+ };
683
+
684
+ const syncProjectSandboxAdd = async (projectID, primaryWorktree, sandboxPath) => {
685
+ const sandbox = String(sandboxPath || '').trim();
686
+ if (!sandbox) {
687
+ return;
688
+ }
689
+ await updateProjectSandboxes(projectID, primaryWorktree, (project) => {
690
+ if (!project.sandboxes.includes(sandbox)) {
691
+ project.sandboxes.push(sandbox);
692
+ }
693
+ });
694
+ };
695
+
696
+ const syncProjectSandboxRemove = async (projectID, primaryWorktree, sandboxPath) => {
697
+ const sandbox = String(sandboxPath || '').trim();
698
+ if (!sandbox) {
699
+ return;
700
+ }
701
+ await updateProjectSandboxes(projectID, primaryWorktree, (project) => {
702
+ project.sandboxes = project.sandboxes.filter((entry) => entry !== sandbox);
703
+ });
704
+ };
705
+
706
+ const queueWorktreeStartScripts = (directory, projectID, startCommand) => {
707
+ setTimeout(() => {
708
+ const run = async () => {
709
+ const projectStart = await loadProjectStartCommand(projectID);
710
+ if (projectStart) {
711
+ const projectResult = await runWorktreeStartCommand(directory, projectStart);
712
+ if (!projectResult.success) {
713
+ console.warn('Worktree project start command failed:', projectResult.message || projectResult.stderr || projectResult.stdout);
714
+ return;
715
+ }
716
+ }
717
+
718
+ const extraCommand = String(startCommand || '').trim();
719
+ if (!extraCommand) {
720
+ return;
721
+ }
722
+ const extraResult = await runWorktreeStartCommand(directory, extraCommand);
723
+ if (!extraResult.success) {
724
+ console.warn('Worktree start command failed:', extraResult.message || extraResult.stderr || extraResult.stdout);
725
+ }
726
+ };
727
+
728
+ void run().catch((error) => {
729
+ console.warn('Worktree start script task failed:', error instanceof Error ? error.message : String(error));
730
+ });
731
+ }, 0);
732
+ };
733
+
734
+ const ensureRemoteWithUrl = async (primaryWorktree, remoteName, remoteUrl) => {
735
+ const name = String(remoteName || '').trim();
736
+ const url = String(remoteUrl || '').trim();
737
+ if (!name || !url) {
738
+ return;
739
+ }
740
+
741
+ const getUrl = await runGitCommand(primaryWorktree, ['remote', 'get-url', name]);
742
+ if (getUrl.success) {
743
+ const currentUrl = String(getUrl.stdout || '').trim();
744
+ if (currentUrl !== url) {
745
+ await runGitCommandOrThrow(primaryWorktree, ['remote', 'set-url', name, url], 'Failed to update git remote URL');
746
+ }
747
+ return;
748
+ }
749
+
750
+ await runGitCommandOrThrow(primaryWorktree, ['remote', 'add', name, url], 'Failed to add git remote');
751
+ };
752
+
753
+ const fetchRemoteBranchRef = async (primaryWorktree, remoteName, branchName) => {
754
+ const remote = String(remoteName || '').trim();
755
+ const branch = String(branchName || '').trim();
756
+ if (!remote || !branch) {
757
+ return;
758
+ }
759
+
760
+ const refspec = `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`;
761
+ await runGitCommandOrThrow(
762
+ primaryWorktree,
763
+ ['fetch', remote, refspec],
764
+ `Failed to fetch ${remote}/${branch}`
765
+ );
766
+ };
767
+
768
+ const checkRemoteBranchExists = async (primaryWorktree, remoteName, branchName, remoteUrl = '') => {
769
+ const remote = String(remoteName || '').trim();
770
+ const branch = String(branchName || '').trim();
771
+ const url = String(remoteUrl || '').trim();
772
+ if (!remote || !branch) {
773
+ return { success: false, found: false };
774
+ }
775
+
776
+ const target = url || remote;
777
+ const lsRemote = await runGitCommand(
778
+ primaryWorktree,
779
+ ['ls-remote', '--heads', target, `refs/heads/${branch}`]
780
+ );
781
+ if (!lsRemote.success) {
782
+ return { success: false, found: false };
783
+ }
784
+
785
+ return {
786
+ success: true,
787
+ found: Boolean(String(lsRemote.stdout || '').trim()),
788
+ };
789
+ };
790
+
791
+ const setBranchTrackingFallback = async (worktreeDirectory, localBranch, upstream) => {
792
+ await runGitCommandOrThrow(
793
+ worktreeDirectory,
794
+ ['config', `branch.${localBranch}.remote`, upstream.remote],
795
+ `Failed to set branch.${localBranch}.remote`
796
+ );
797
+ await runGitCommandOrThrow(
798
+ worktreeDirectory,
799
+ ['config', `branch.${localBranch}.merge`, `refs/heads/${upstream.branch}`],
800
+ `Failed to set branch.${localBranch}.merge`
801
+ );
802
+ };
803
+
804
+ const applyUpstreamConfiguration = async (args) => {
805
+ const {
806
+ primaryWorktree,
807
+ worktreeDirectory,
808
+ localBranch,
809
+ setUpstream,
810
+ upstreamRemote,
811
+ upstreamBranch,
812
+ ensureRemoteName,
813
+ ensureRemoteUrl,
814
+ } = args;
815
+
816
+ if (!setUpstream) {
817
+ return;
818
+ }
819
+
820
+ if (ensureRemoteName && ensureRemoteUrl) {
821
+ await ensureRemoteWithUrl(primaryWorktree, ensureRemoteName, ensureRemoteUrl);
822
+ }
823
+
824
+ const upstream = normalizeUpstreamTarget(upstreamRemote, upstreamBranch);
825
+ if (!upstream || !localBranch) {
826
+ return;
827
+ }
828
+
829
+ let fetched = true;
830
+ try {
831
+ await fetchRemoteBranchRef(primaryWorktree, upstream.remote, upstream.branch);
832
+ } catch {
833
+ fetched = false;
834
+ }
835
+
836
+ if (fetched) {
837
+ await runGitCommandOrThrow(
838
+ worktreeDirectory,
839
+ ['branch', `--set-upstream-to=${upstream.full}`, localBranch],
840
+ `Failed to set upstream to ${upstream.full}`
841
+ );
842
+ return;
843
+ }
844
+
845
+ await setBranchTrackingFallback(worktreeDirectory, localBranch, upstream);
846
+ };
847
+
848
+ export async function isGitRepository(directory) {
849
+ const directoryPath = normalizeDirectoryPath(directory);
850
+ if (!directoryPath || !fs.existsSync(directoryPath)) {
851
+ return false;
852
+ }
853
+
854
+ const gitDir = path.join(directoryPath, '.git');
855
+ return fs.existsSync(gitDir);
856
+ }
857
+
858
+ export async function getGlobalIdentity() {
859
+ const git = await createGit();
860
+
861
+ try {
862
+ const userName = await git.getConfig('user.name', 'global').catch(() => null);
863
+ const userEmail = await git.getConfig('user.email', 'global').catch(() => null);
864
+ const sshCommand = await git.getConfig('core.sshCommand', 'global').catch(() => null);
865
+
866
+ return {
867
+ userName: userName?.value || null,
868
+ userEmail: userEmail?.value || null,
869
+ sshCommand: sshCommand?.value || null
870
+ };
871
+ } catch (error) {
872
+ console.error('Failed to get global Git identity:', error);
873
+ return {
874
+ userName: null,
875
+ userEmail: null,
876
+ sshCommand: null
877
+ };
878
+ }
879
+ }
880
+
881
+ export async function getRemoteUrl(directory, remoteName = 'origin') {
882
+ const git = await createGit(directory);
883
+
884
+ try {
885
+ const url = await git.remote(['get-url', remoteName]);
886
+ return url?.trim() || null;
887
+ } catch {
888
+ return null;
889
+ }
890
+ }
891
+
892
+ export async function getCurrentIdentity(directory) {
893
+ const git = await createGit(directory);
894
+
895
+ try {
896
+
897
+ const userName = await git.getConfig('user.name', 'local').catch(() =>
898
+ git.getConfig('user.name', 'global')
899
+ );
900
+
901
+ const userEmail = await git.getConfig('user.email', 'local').catch(() =>
902
+ git.getConfig('user.email', 'global')
903
+ );
904
+
905
+ const sshCommand = await git.getConfig('core.sshCommand', 'local').catch(() =>
906
+ git.getConfig('core.sshCommand', 'global')
907
+ );
908
+
909
+ return {
910
+ userName: userName?.value || null,
911
+ userEmail: userEmail?.value || null,
912
+ sshCommand: sshCommand?.value || null
913
+ };
914
+ } catch (error) {
915
+ console.error('Failed to get current Git identity:', error);
916
+ return {
917
+ userName: null,
918
+ userEmail: null,
919
+ sshCommand: null
920
+ };
921
+ }
922
+ }
923
+
924
+ export async function hasLocalIdentity(directory) {
925
+ const git = await createGit(directory);
926
+
927
+ try {
928
+ const localName = await git.getConfig('user.name', 'local').catch(() => null);
929
+ const localEmail = await git.getConfig('user.email', 'local').catch(() => null);
930
+ return Boolean(localName?.value || localEmail?.value);
931
+ } catch {
932
+ return false;
933
+ }
934
+ }
935
+
936
+ export async function setLocalIdentity(directory, profile) {
937
+ const git = await createGit(directory);
938
+
939
+ try {
940
+
941
+ await git.addConfig('user.name', profile.userName, false, 'local');
942
+ await git.addConfig('user.email', profile.userEmail, false, 'local');
943
+
944
+ const authType = profile.authType || 'ssh';
945
+
946
+ if (authType === 'ssh' && profile.sshKey) {
947
+ await git.addConfig(
948
+ 'core.sshCommand',
949
+ buildSshCommand(profile.sshKey),
950
+ false,
951
+ 'local'
952
+ );
953
+ await git.raw(['config', '--local', '--unset', 'credential.helper']).catch(() => {});
954
+ } else if (authType === 'token' && profile.host) {
955
+ await git.addConfig(
956
+ 'credential.helper',
957
+ 'store',
958
+ false,
959
+ 'local'
960
+ );
961
+ await git.raw(['config', '--local', '--unset', 'core.sshCommand']).catch(() => {});
962
+ }
963
+
964
+ return true;
965
+ } catch (error) {
966
+ console.error('Failed to set Git identity:', error);
967
+ throw error;
968
+ }
969
+ }
970
+
971
+ export async function getStatus(directory) {
972
+ const directoryPath = normalizeDirectoryPath(directory);
973
+ const git = await createGit(directoryPath);
974
+
975
+ try {
976
+ // Use -uall to show all untracked files individually, not just directories
977
+ const status = await git.status(['-uall']);
978
+
979
+ const [stagedStatsRaw, workingStatsRaw] = await Promise.all([
980
+ git.raw(['diff', '--cached', '--numstat']).catch(() => ''),
981
+ git.raw(['diff', '--numstat']).catch(() => ''),
982
+ ]);
983
+
984
+ const diffStatsMap = new Map();
985
+
986
+ const accumulateStats = (raw) => {
987
+ if (!raw) return;
988
+ raw
989
+ .split('\n')
990
+ .map((line) => line.trim())
991
+ .filter(Boolean)
992
+ .forEach((line) => {
993
+ const parts = line.split('\t');
994
+ if (parts.length < 3) {
995
+ return;
996
+ }
997
+ const [insertionsRaw, deletionsRaw, ...pathParts] = parts;
998
+ const path = pathParts.join('\t');
999
+ if (!path) {
1000
+ return;
1001
+ }
1002
+ const insertions = insertionsRaw === '-' ? 0 : parseInt(insertionsRaw, 10) || 0;
1003
+ const deletions = deletionsRaw === '-' ? 0 : parseInt(deletionsRaw, 10) || 0;
1004
+
1005
+ const existing = diffStatsMap.get(path) || { insertions: 0, deletions: 0 };
1006
+ diffStatsMap.set(path, {
1007
+ insertions: existing.insertions + insertions,
1008
+ deletions: existing.deletions + deletions,
1009
+ });
1010
+ });
1011
+ };
1012
+
1013
+ accumulateStats(stagedStatsRaw);
1014
+ accumulateStats(workingStatsRaw);
1015
+
1016
+ const diffStats = Object.fromEntries(diffStatsMap.entries());
1017
+
1018
+ const newFileStats = await Promise.all(
1019
+ status.files.map(async (file) => {
1020
+ const working = (file.working_dir || '').trim();
1021
+ const indexStatus = (file.index || '').trim();
1022
+ const statusCode = working || indexStatus;
1023
+
1024
+ if (statusCode !== '?' && statusCode !== 'A') {
1025
+ return null;
1026
+ }
1027
+
1028
+ const existing = diffStats[file.path];
1029
+ if (existing && existing.insertions > 0) {
1030
+ return null;
1031
+ }
1032
+
1033
+ const absolutePath = path.join(directoryPath, file.path);
1034
+
1035
+ try {
1036
+ const stat = await fsp.stat(absolutePath);
1037
+ if (!stat.isFile()) {
1038
+ return null;
1039
+ }
1040
+
1041
+ const buffer = await fsp.readFile(absolutePath);
1042
+ if (buffer.indexOf(0) !== -1) {
1043
+ return {
1044
+ path: file.path,
1045
+ insertions: existing?.insertions ?? 0,
1046
+ deletions: existing?.deletions ?? 0,
1047
+ };
1048
+ }
1049
+
1050
+ const normalized = buffer.toString('utf8').replace(/\r\n/g, '\n');
1051
+ if (!normalized.length) {
1052
+ return {
1053
+ path: file.path,
1054
+ insertions: 0,
1055
+ deletions: 0,
1056
+ };
1057
+ }
1058
+
1059
+ const segments = normalized.split('\n');
1060
+ if (normalized.endsWith('\n')) {
1061
+ segments.pop();
1062
+ }
1063
+
1064
+ const lineCount = segments.length;
1065
+ return {
1066
+ path: file.path,
1067
+ insertions: lineCount,
1068
+ deletions: 0,
1069
+ };
1070
+ } catch (error) {
1071
+ console.warn('Failed to estimate diff stats for new file', file.path, error);
1072
+ return null;
1073
+ }
1074
+ })
1075
+ );
1076
+
1077
+ for (const entry of newFileStats) {
1078
+ if (!entry) continue;
1079
+ diffStats[entry.path] = {
1080
+ insertions: entry.insertions,
1081
+ deletions: entry.deletions,
1082
+ };
1083
+ }
1084
+
1085
+ const selectBaseRefForUnpublished = async () => {
1086
+ const candidates = [];
1087
+
1088
+ const originHead = await git
1089
+ .raw(['symbolic-ref', '-q', 'refs/remotes/origin/HEAD'])
1090
+ .then((value) => String(value || '').trim())
1091
+ .catch(() => '');
1092
+
1093
+ if (originHead) {
1094
+ // "refs/remotes/origin/main" -> "origin/main"
1095
+ candidates.push(originHead.replace(/^refs\/remotes\//, ''));
1096
+ }
1097
+
1098
+ candidates.push('origin/main', 'origin/master', 'main', 'master');
1099
+
1100
+ for (const ref of candidates) {
1101
+ const exists = await git
1102
+ .raw(['rev-parse', '--verify', ref])
1103
+ .then((value) => String(value || '').trim())
1104
+ .catch(() => '');
1105
+ if (exists) return ref;
1106
+ }
1107
+
1108
+ return null;
1109
+ };
1110
+
1111
+ let tracking = status.tracking || null;
1112
+ let ahead = status.ahead;
1113
+ let behind = status.behind;
1114
+
1115
+ // When no upstream is configured (common for new worktree branches), Git doesn't report ahead/behind.
1116
+ // We still want to show the number of unpublished commits to the user.
1117
+ if (!tracking && status.current) {
1118
+ const baseRef = await selectBaseRefForUnpublished();
1119
+ if (baseRef) {
1120
+ const countRaw = await git
1121
+ .raw(['rev-list', '--count', `${baseRef}..HEAD`])
1122
+ .then((value) => String(value || '').trim())
1123
+ .catch(() => '');
1124
+ const count = parseInt(countRaw, 10);
1125
+ if (Number.isFinite(count)) {
1126
+ ahead = count;
1127
+ behind = 0;
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ // Check for in-progress operations
1133
+ let mergeInProgress = null;
1134
+ let rebaseInProgress = null;
1135
+
1136
+ try {
1137
+ // Check MERGE_HEAD for merge in progress
1138
+ const mergeHeadExists = await git
1139
+ .raw(['rev-parse', '--verify', '--quiet', 'MERGE_HEAD'])
1140
+ .then(() => true)
1141
+ .catch(() => false);
1142
+
1143
+ if (mergeHeadExists) {
1144
+ const mergeHead = await git.raw(['rev-parse', 'MERGE_HEAD']).catch(() => '');
1145
+ const headSha = mergeHead.trim().slice(0, 7);
1146
+ // Only set mergeInProgress if we actually have a valid head SHA
1147
+ if (headSha) {
1148
+ const mergeMsg = await fsp.readFile(path.join(directoryPath, '.git', 'MERGE_MSG'), 'utf8').catch(() => '');
1149
+ mergeInProgress = {
1150
+ head: headSha,
1151
+ message: mergeMsg.split('\n')[0] || '',
1152
+ };
1153
+ }
1154
+ }
1155
+ } catch {
1156
+ // ignore
1157
+ }
1158
+
1159
+ try {
1160
+ // Check for rebase in progress (.git/rebase-merge or .git/rebase-apply)
1161
+ const rebaseMergeExists = await fsp.stat(path.join(directoryPath, '.git', 'rebase-merge')).then(() => true).catch(() => false);
1162
+ const rebaseApplyExists = await fsp.stat(path.join(directoryPath, '.git', 'rebase-apply')).then(() => true).catch(() => false);
1163
+
1164
+ if (rebaseMergeExists || rebaseApplyExists) {
1165
+ const rebaseDir = rebaseMergeExists ? 'rebase-merge' : 'rebase-apply';
1166
+ const headName = await fsp.readFile(path.join(directoryPath, '.git', rebaseDir, 'head-name'), 'utf8').catch(() => '');
1167
+ const onto = await fsp.readFile(path.join(directoryPath, '.git', rebaseDir, 'onto'), 'utf8').catch(() => '');
1168
+
1169
+ const headNameTrimmed = headName.trim().replace('refs/heads/', '');
1170
+ const ontoTrimmed = onto.trim().slice(0, 7);
1171
+
1172
+ // Only set rebaseInProgress if we have valid data
1173
+ if (headNameTrimmed || ontoTrimmed) {
1174
+ rebaseInProgress = {
1175
+ headName: headNameTrimmed,
1176
+ onto: ontoTrimmed,
1177
+ };
1178
+ }
1179
+ }
1180
+ } catch {
1181
+ // ignore
1182
+ }
1183
+
1184
+ return {
1185
+ current: status.current,
1186
+ tracking,
1187
+ ahead,
1188
+ behind,
1189
+ files: status.files.map((f) => ({
1190
+ path: f.path,
1191
+ index: f.index,
1192
+ working_dir: f.working_dir,
1193
+ })),
1194
+ isClean: status.isClean(),
1195
+ diffStats,
1196
+ mergeInProgress,
1197
+ rebaseInProgress,
1198
+ };
1199
+ } catch (error) {
1200
+ console.error('Failed to get Git status:', error);
1201
+ throw error;
1202
+ }
1203
+ }
1204
+
1205
+ export async function getDiff(directory, { path, staged = false, contextLines = 3 } = {}) {
1206
+ const git = await createGit(directory);
1207
+
1208
+ try {
1209
+ const args = ['diff', '--no-color'];
1210
+
1211
+ if (typeof contextLines === 'number' && !Number.isNaN(contextLines)) {
1212
+ args.push(`-U${Math.max(0, contextLines)}`);
1213
+ }
1214
+
1215
+ if (staged) {
1216
+ args.push('--cached');
1217
+ }
1218
+
1219
+ if (path) {
1220
+ args.push('--', path);
1221
+ }
1222
+
1223
+ const diff = await git.raw(args);
1224
+ if (diff && diff.trim().length > 0) {
1225
+ return diff;
1226
+ }
1227
+
1228
+ if (staged) {
1229
+ return diff;
1230
+ }
1231
+
1232
+ try {
1233
+ await git.raw(['ls-files', '--error-unmatch', path]);
1234
+ return diff;
1235
+ } catch {
1236
+ const noIndexArgs = ['diff', '--no-color'];
1237
+ if (typeof contextLines === 'number' && !Number.isNaN(contextLines)) {
1238
+ noIndexArgs.push(`-U${Math.max(0, contextLines)}`);
1239
+ }
1240
+ noIndexArgs.push('--no-index', '--', '/dev/null', path);
1241
+ try {
1242
+ const noIndexDiff = await git.raw(noIndexArgs);
1243
+ return noIndexDiff;
1244
+ } catch (noIndexError) {
1245
+ // git diff --no-index returns exit code 1 when differences exist (not a real error)
1246
+ if (noIndexError.exitCode === 1 && noIndexError.message) {
1247
+ return noIndexError.message;
1248
+ }
1249
+ throw noIndexError;
1250
+ }
1251
+ }
1252
+ } catch (error) {
1253
+ console.error('Failed to get Git diff:', error);
1254
+ throw error;
1255
+ }
1256
+ }
1257
+
1258
+ export async function getRangeDiff(directory, { base, head, path, contextLines = 3 } = {}) {
1259
+ const git = await createGit(directory);
1260
+ const baseRef = typeof base === 'string' ? base.trim() : '';
1261
+ const headRef = typeof head === 'string' ? head.trim() : '';
1262
+ if (!baseRef || !headRef) {
1263
+ throw new Error('base and head are required');
1264
+ }
1265
+
1266
+ // Prefer remote-tracking base ref so merged commits don't reappear
1267
+ // when local base branch is stale (common when user stays on feature branch).
1268
+ let resolvedBase = baseRef;
1269
+ const originCandidate = `refs/remotes/origin/${baseRef}`;
1270
+ try {
1271
+ const verified = await git.raw(['rev-parse', '--verify', originCandidate]);
1272
+ if (verified && verified.trim()) {
1273
+ resolvedBase = `origin/${baseRef}`;
1274
+ }
1275
+ } catch {
1276
+ // ignore
1277
+ }
1278
+
1279
+ const args = ['diff', '--no-color'];
1280
+ if (typeof contextLines === 'number' && !Number.isNaN(contextLines)) {
1281
+ args.push(`-U${Math.max(0, contextLines)}`);
1282
+ }
1283
+ args.push(`${resolvedBase}...${headRef}`);
1284
+ if (path) {
1285
+ args.push('--', path);
1286
+ }
1287
+ const diff = await git.raw(args);
1288
+ return diff;
1289
+ }
1290
+
1291
+ export async function getRangeFiles(directory, { base, head } = {}) {
1292
+ const git = await createGit(directory);
1293
+ const baseRef = typeof base === 'string' ? base.trim() : '';
1294
+ const headRef = typeof head === 'string' ? head.trim() : '';
1295
+ if (!baseRef || !headRef) {
1296
+ throw new Error('base and head are required');
1297
+ }
1298
+
1299
+ let resolvedBase = baseRef;
1300
+ const originCandidate = `refs/remotes/origin/${baseRef}`;
1301
+ try {
1302
+ const verified = await git.raw(['rev-parse', '--verify', originCandidate]);
1303
+ if (verified && verified.trim()) {
1304
+ resolvedBase = `origin/${baseRef}`;
1305
+ }
1306
+ } catch {
1307
+ // ignore
1308
+ }
1309
+
1310
+ const raw = await git.raw(['diff', '--name-only', `${resolvedBase}...${headRef}`]);
1311
+ return String(raw || '')
1312
+ .split('\n')
1313
+ .map((l) => l.trim())
1314
+ .filter(Boolean);
1315
+ }
1316
+
1317
+ const IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico', 'bmp', 'avif'];
1318
+
1319
+ function isImageFile(filePath) {
1320
+ const ext = filePath.split('.').pop()?.toLowerCase();
1321
+ return IMAGE_EXTENSIONS.includes(ext || '');
1322
+ }
1323
+
1324
+ function getImageMimeType(filePath) {
1325
+ const ext = filePath.split('.').pop()?.toLowerCase();
1326
+ const mimeMap = {
1327
+ 'png': 'image/png',
1328
+ 'jpg': 'image/jpeg',
1329
+ 'jpeg': 'image/jpeg',
1330
+ 'gif': 'image/gif',
1331
+ 'svg': 'image/svg+xml',
1332
+ 'webp': 'image/webp',
1333
+ 'ico': 'image/x-icon',
1334
+ 'bmp': 'image/bmp',
1335
+ 'avif': 'image/avif',
1336
+ };
1337
+ return mimeMap[ext] || 'application/octet-stream';
1338
+ }
1339
+
1340
+ export async function getFileDiff(directory, { path: filePath, staged = false } = {}) {
1341
+ if (!directory || !filePath) {
1342
+ throw new Error('directory and path are required for getFileDiff');
1343
+ }
1344
+
1345
+ const directoryPath = normalizeDirectoryPath(directory);
1346
+ const git = await createGit(directoryPath);
1347
+ const isImage = isImageFile(filePath);
1348
+ const mimeType = isImage ? getImageMimeType(filePath) : null;
1349
+
1350
+ let original = '';
1351
+ try {
1352
+ if (isImage) {
1353
+ // For images, use git show with raw output and convert to base64
1354
+ try {
1355
+ const { stdout } = await execFileAsync('git', ['show', `HEAD:${filePath}`], {
1356
+ cwd: directoryPath,
1357
+ encoding: 'buffer',
1358
+ maxBuffer: 50 * 1024 * 1024, // 50MB max
1359
+ });
1360
+ if (stdout && stdout.length > 0) {
1361
+ original = `data:${mimeType};base64,${stdout.toString('base64')}`;
1362
+ }
1363
+ } catch {
1364
+ original = '';
1365
+ }
1366
+ } else {
1367
+ original = await git.show([`HEAD:${filePath}`]);
1368
+ }
1369
+ } catch {
1370
+ original = '';
1371
+ }
1372
+
1373
+ const fullPath = path.join(directoryPath, filePath);
1374
+ let modified = '';
1375
+ try {
1376
+ const stat = await fsp.stat(fullPath);
1377
+ if (stat.isFile()) {
1378
+ if (isImage) {
1379
+ // For images, read as binary and convert to data URL
1380
+ const buffer = await fsp.readFile(fullPath);
1381
+ modified = `data:${mimeType};base64,${buffer.toString('base64')}`;
1382
+ } else {
1383
+ modified = await fsp.readFile(fullPath, 'utf8');
1384
+ }
1385
+ }
1386
+ } catch (error) {
1387
+ if (error && typeof error === 'object' && error.code === 'ENOENT') {
1388
+ modified = '';
1389
+ } else {
1390
+ console.error('Failed to read modified file contents for diff:', error);
1391
+ throw error;
1392
+ }
1393
+ }
1394
+
1395
+ return {
1396
+ original,
1397
+ modified,
1398
+ path: filePath,
1399
+ };
1400
+ }
1401
+
1402
+ export async function revertFile(directory, filePath) {
1403
+ const directoryPath = normalizeDirectoryPath(directory);
1404
+ const git = await createGit(directoryPath);
1405
+ const repoRoot = path.resolve(directoryPath);
1406
+ const absoluteTarget = path.resolve(repoRoot, filePath);
1407
+
1408
+ if (!absoluteTarget.startsWith(repoRoot + path.sep) && absoluteTarget !== repoRoot) {
1409
+ throw new Error('Invalid file path');
1410
+ }
1411
+
1412
+ const isTracked = await git
1413
+ .raw(['ls-files', '--error-unmatch', filePath])
1414
+ .then(() => true)
1415
+ .catch(() => false);
1416
+
1417
+ if (!isTracked) {
1418
+ try {
1419
+ await git.raw(['clean', '-f', '-d', '--', filePath]);
1420
+ return;
1421
+ } catch (cleanError) {
1422
+ try {
1423
+ await fsp.rm(absoluteTarget, { recursive: true, force: true });
1424
+ return;
1425
+ } catch (fsError) {
1426
+ if (fsError && typeof fsError === 'object' && fsError.code === 'ENOENT') {
1427
+ return;
1428
+ }
1429
+ console.error('Failed to remove untracked file during revert:', fsError);
1430
+ throw fsError;
1431
+ }
1432
+ }
1433
+ }
1434
+
1435
+ try {
1436
+ await git.raw(['restore', '--staged', filePath]);
1437
+ } catch (error) {
1438
+ await git.raw(['reset', 'HEAD', '--', filePath]).catch(() => {});
1439
+ }
1440
+
1441
+ try {
1442
+ await git.raw(['restore', filePath]);
1443
+ } catch (error) {
1444
+ try {
1445
+ await git.raw(['checkout', '--', filePath]);
1446
+ } catch (fallbackError) {
1447
+ console.error('Failed to revert git file:', fallbackError);
1448
+ throw fallbackError;
1449
+ }
1450
+ }
1451
+ }
1452
+
1453
+ export async function collectDiffs(directory, files = []) {
1454
+ const results = [];
1455
+ for (const filePath of files) {
1456
+ try {
1457
+ const diff = await getDiff(directory, { path: filePath });
1458
+ if (diff && diff.trim().length > 0) {
1459
+ results.push({ path: filePath, diff });
1460
+ }
1461
+ } catch (error) {
1462
+ console.error(`Failed to diff ${filePath}:`, error);
1463
+ }
1464
+ }
1465
+ return results;
1466
+ }
1467
+
1468
+ export async function pull(directory, options = {}) {
1469
+ const git = await createGit(directory);
1470
+
1471
+ try {
1472
+ const result = await git.pull(
1473
+ options.remote || 'origin',
1474
+ options.branch,
1475
+ options.options || {}
1476
+ );
1477
+
1478
+ return {
1479
+ success: true,
1480
+ summary: result.summary,
1481
+ files: result.files,
1482
+ insertions: result.insertions,
1483
+ deletions: result.deletions
1484
+ };
1485
+ } catch (error) {
1486
+ console.error('Failed to pull:', error);
1487
+ throw error;
1488
+ }
1489
+ }
1490
+
1491
+ export async function push(directory, options = {}) {
1492
+ const git = await createGit(directory);
1493
+
1494
+ const describePushError = (error) => {
1495
+ const fromNestedGit = error?.git && typeof error.git === 'object'
1496
+ ? [error.git.message, error.git.stderr, error.git.stdout]
1497
+ : [];
1498
+ const candidates = [
1499
+ error?.message,
1500
+ error?.stderr,
1501
+ error?.stdout,
1502
+ ...fromNestedGit,
1503
+ ]
1504
+ .map((value) => String(value || '').trim())
1505
+ .filter(Boolean);
1506
+
1507
+ return candidates[0] || 'Failed to push to remote';
1508
+ };
1509
+
1510
+ const buildUpstreamOptions = (raw) => {
1511
+ if (Array.isArray(raw)) {
1512
+ return raw.includes('--set-upstream') ? raw : [...raw, '--set-upstream'];
1513
+ }
1514
+
1515
+ if (raw && typeof raw === 'object') {
1516
+ return { ...raw, '--set-upstream': null };
1517
+ }
1518
+
1519
+ return ['--set-upstream'];
1520
+ };
1521
+
1522
+ const looksLikeMissingUpstream = (error) => {
1523
+ const message = String(error?.message || error?.stderr || '').toLowerCase();
1524
+ return (
1525
+ message.includes('has no upstream') ||
1526
+ message.includes('no upstream') ||
1527
+ message.includes('set-upstream') ||
1528
+ message.includes('set upstream') ||
1529
+ (message.includes('upstream') && message.includes('push') && message.includes('-u'))
1530
+ );
1531
+ };
1532
+
1533
+ const normalizePushResult = (result) => {
1534
+ return {
1535
+ success: true,
1536
+ pushed: result.pushed,
1537
+ repo: result.repo,
1538
+ ref: result.ref,
1539
+ };
1540
+ };
1541
+
1542
+ const remote = String(options.remote || '').trim();
1543
+
1544
+ if (!remote && !options.branch) {
1545
+ try {
1546
+ await git.push();
1547
+ return {
1548
+ success: true,
1549
+ pushed: [],
1550
+ repo: directory,
1551
+ ref: null,
1552
+ };
1553
+ } catch (error) {
1554
+ if (!looksLikeMissingUpstream(error)) {
1555
+ const message = describePushError(error);
1556
+ console.error('Failed to push:', error);
1557
+ throw new Error(message);
1558
+ }
1559
+
1560
+ try {
1561
+ const status = await git.status();
1562
+ const branch = status.current;
1563
+ const remotes = await git.getRemotes(true);
1564
+ const fallbackRemote = remotes.find((entry) => entry.name === 'origin')?.name || remotes[0]?.name;
1565
+ if (!branch || !fallbackRemote) {
1566
+ const message = describePushError(error);
1567
+ throw new Error(message);
1568
+ }
1569
+
1570
+ const result = await git.push(fallbackRemote, branch, buildUpstreamOptions(options.options));
1571
+ return normalizePushResult(result);
1572
+ } catch (fallbackError) {
1573
+ const message = describePushError(fallbackError);
1574
+ console.error('Failed to push (including upstream fallback):', fallbackError);
1575
+ throw new Error(message);
1576
+ }
1577
+ }
1578
+ }
1579
+
1580
+ const remoteName = remote || 'origin';
1581
+
1582
+ // If caller didn't specify a branch, this is the common "Push"/"Commit & Push" path.
1583
+ // When there's no upstream yet (typical for freshly-created worktree branches), publish it on first push.
1584
+ if (!options.branch) {
1585
+ try {
1586
+ const status = await git.status();
1587
+ if (status.current && !status.tracking) {
1588
+ const result = await git.push(remoteName, status.current, buildUpstreamOptions(options.options));
1589
+ return normalizePushResult(result);
1590
+ }
1591
+ } catch (error) {
1592
+ // If we can't read status, fall back to the regular push path below.
1593
+ console.warn('Failed to read git status before push:', error);
1594
+ }
1595
+ }
1596
+
1597
+ try {
1598
+ const result = await git.push(remoteName, options.branch, options.options || {});
1599
+ return normalizePushResult(result);
1600
+ } catch (error) {
1601
+ // Last-resort fallback: retry with upstream if the error suggests it's missing.
1602
+ if (!looksLikeMissingUpstream(error)) {
1603
+ const message = describePushError(error);
1604
+ console.error('Failed to push:', error);
1605
+ throw new Error(message);
1606
+ }
1607
+
1608
+ try {
1609
+ const status = await git.status();
1610
+ const branch = options.branch || status.current;
1611
+ if (!branch) {
1612
+ console.error('Failed to push: missing branch name for upstream setup:', error);
1613
+ throw error;
1614
+ }
1615
+
1616
+ const result = await git.push(remoteName, branch, buildUpstreamOptions(options.options));
1617
+ return normalizePushResult(result);
1618
+ } catch (fallbackError) {
1619
+ const message = describePushError(fallbackError);
1620
+ console.error('Failed to push (including upstream fallback):', fallbackError);
1621
+ throw new Error(message);
1622
+ }
1623
+ }
1624
+ }
1625
+
1626
+ export async function deleteRemoteBranch(directory, options = {}) {
1627
+ const { branch, remote } = options;
1628
+ if (!branch) {
1629
+ throw new Error('branch is required to delete remote branch');
1630
+ }
1631
+
1632
+ const git = await createGit(directory);
1633
+ const targetBranch = branch.startsWith('refs/heads/')
1634
+ ? branch.substring('refs/heads/'.length)
1635
+ : branch;
1636
+ const remoteName = remote || 'origin';
1637
+
1638
+ try {
1639
+ await git.push(remoteName, `:${targetBranch}`);
1640
+ return { success: true };
1641
+ } catch (error) {
1642
+ console.error('Failed to delete remote branch:', error);
1643
+ throw error;
1644
+ }
1645
+ }
1646
+
1647
+ export async function fetch(directory, options = {}) {
1648
+ const git = await createGit(directory);
1649
+
1650
+ try {
1651
+ await git.fetch(
1652
+ options.remote || 'origin',
1653
+ options.branch,
1654
+ options.options || {}
1655
+ );
1656
+
1657
+ return { success: true };
1658
+ } catch (error) {
1659
+ console.error('Failed to fetch:', error);
1660
+ throw error;
1661
+ }
1662
+ }
1663
+
1664
+ export async function commit(directory, message, options = {}) {
1665
+ const git = await createGit(directory);
1666
+
1667
+ try {
1668
+
1669
+ if (options.addAll) {
1670
+ await git.add('.');
1671
+ } else if (Array.isArray(options.files) && options.files.length > 0) {
1672
+ await git.add(options.files);
1673
+ }
1674
+
1675
+ const commitArgs =
1676
+ !options.addAll && Array.isArray(options.files) && options.files.length > 0
1677
+ ? options.files
1678
+ : undefined;
1679
+
1680
+ const result = await git.commit(message, commitArgs);
1681
+
1682
+ return {
1683
+ success: true,
1684
+ commit: result.commit,
1685
+ branch: result.branch,
1686
+ summary: result.summary
1687
+ };
1688
+ } catch (error) {
1689
+ console.error('Failed to commit:', error);
1690
+ throw error;
1691
+ }
1692
+ }
1693
+
1694
+ export async function getBranches(directory) {
1695
+ const git = await createGit(directory);
1696
+
1697
+ try {
1698
+ const result = await git.branch();
1699
+
1700
+ const allBranches = result.all;
1701
+ const remoteBranches = allBranches.filter(branch => branch.startsWith('remotes/'));
1702
+ const activeRemoteBranches = await filterActiveRemoteBranches(git, remoteBranches);
1703
+
1704
+ const filteredAll = [
1705
+ ...allBranches.filter(branch => !branch.startsWith('remotes/')),
1706
+ ...activeRemoteBranches
1707
+ ];
1708
+
1709
+ return {
1710
+ all: filteredAll,
1711
+ current: result.current,
1712
+ branches: result.branches
1713
+ };
1714
+ } catch (error) {
1715
+ console.error('Failed to get branches:', error);
1716
+ throw error;
1717
+ }
1718
+ }
1719
+
1720
+ async function filterActiveRemoteBranches(git, remoteBranches) {
1721
+ try {
1722
+
1723
+ const lsRemoteResult = await git.raw(['ls-remote', '--heads', 'origin']);
1724
+ const actualRemoteBranches = new Set();
1725
+
1726
+ const lines = lsRemoteResult.trim().split('\n');
1727
+ for (const line of lines) {
1728
+ if (line.includes('\trefs/heads/')) {
1729
+ const branchName = line.split('\t')[1].replace('refs/heads/', '');
1730
+ actualRemoteBranches.add(branchName);
1731
+ }
1732
+ }
1733
+
1734
+ return remoteBranches.filter(remoteBranch => {
1735
+
1736
+ const match = remoteBranch.match(/^remotes\/[^\/]+\/(.+)$/);
1737
+ if (!match) return false;
1738
+
1739
+ const branchName = match[1];
1740
+ return actualRemoteBranches.has(branchName);
1741
+ });
1742
+ } catch (error) {
1743
+ console.warn('Failed to filter active remote branches, returning all:', error.message);
1744
+ return remoteBranches;
1745
+ }
1746
+ }
1747
+
1748
+ export async function createBranch(directory, branchName, options = {}) {
1749
+ const git = await createGit(directory);
1750
+
1751
+ try {
1752
+ await git.checkoutBranch(branchName, options.startPoint || 'HEAD');
1753
+ return { success: true, branch: branchName };
1754
+ } catch (error) {
1755
+ console.error('Failed to create branch:', error);
1756
+ throw error;
1757
+ }
1758
+ }
1759
+
1760
+ export async function checkoutBranch(directory, branchName) {
1761
+ const git = await createGit(directory);
1762
+
1763
+ try {
1764
+ await git.checkout(branchName);
1765
+ return { success: true, branch: branchName };
1766
+ } catch (error) {
1767
+ console.error('Failed to checkout branch:', error);
1768
+ throw error;
1769
+ }
1770
+ }
1771
+
1772
+ export async function getWorktrees(directory) {
1773
+ const directoryPath = normalizeDirectoryPath(directory);
1774
+ if (!directoryPath || !fs.existsSync(directoryPath) || !fs.existsSync(path.join(directoryPath, '.git'))) {
1775
+ return [];
1776
+ }
1777
+ try {
1778
+ const result = await runGitCommandOrThrow(
1779
+ directoryPath,
1780
+ ['worktree', 'list', '--porcelain'],
1781
+ 'Failed to list git worktrees'
1782
+ );
1783
+ return parseWorktreePorcelain(result.stdout).map((entry) => ({
1784
+ head: entry.head || '',
1785
+ name: path.basename(entry.worktree || ''),
1786
+ branch: entry.branch || '',
1787
+ path: entry.worktree,
1788
+ }));
1789
+ } catch (error) {
1790
+ console.warn('Failed to list worktrees, returning empty list:', error?.message || error);
1791
+ return [];
1792
+ }
1793
+ }
1794
+
1795
+ export async function validateWorktreeCreate(directory, input = {}) {
1796
+ const mode = input?.mode === 'existing' ? 'existing' : 'new';
1797
+ const errors = [];
1798
+
1799
+ try {
1800
+ const context = await resolveWorktreeProjectContext(directory);
1801
+ const preferredBranchName = cleanBranchName(String(input?.branchName || '').trim());
1802
+ const startRef = normalizeStartRef(input?.startRef);
1803
+ const ensureRemoteName = String(input?.ensureRemoteName || '').trim();
1804
+ const ensureRemoteUrl = String(input?.ensureRemoteUrl || '').trim();
1805
+
1806
+ let localBranch = '';
1807
+ let inferredUpstream = null;
1808
+
1809
+ if (mode === 'existing') {
1810
+ try {
1811
+ const requestedExistingBranch = String(input?.existingBranch || '').trim();
1812
+ const parsedExistingRemote = parseRemoteBranchRef(requestedExistingBranch);
1813
+ if (parsedExistingRemote && ensureRemoteName && ensureRemoteUrl && ensureRemoteName === parsedExistingRemote.remote) {
1814
+ const lsRemote = await runGitCommand(
1815
+ context.primaryWorktree,
1816
+ ['ls-remote', '--heads', ensureRemoteUrl, `refs/heads/${parsedExistingRemote.branch}`]
1817
+ );
1818
+ if (!lsRemote.success) {
1819
+ throw new Error(`Unable to query remote ${ensureRemoteName}`);
1820
+ }
1821
+ if (!String(lsRemote.stdout || '').trim()) {
1822
+ throw new Error(`Remote branch not found: ${parsedExistingRemote.remoteRef}`);
1823
+ }
1824
+ localBranch = cleanBranchName(preferredBranchName || parsedExistingRemote.branch);
1825
+ inferredUpstream = {
1826
+ remote: parsedExistingRemote.remote,
1827
+ branch: parsedExistingRemote.branch,
1828
+ };
1829
+ } else {
1830
+ const resolved = await resolveBranchForExistingMode(context.primaryWorktree, requestedExistingBranch, preferredBranchName);
1831
+ localBranch = resolved.localBranch || '';
1832
+ if (resolved.remoteRef) {
1833
+ inferredUpstream = {
1834
+ remote: resolved.remoteRef.remote,
1835
+ branch: resolved.remoteRef.branch,
1836
+ };
1837
+ }
1838
+ }
1839
+ } catch (error) {
1840
+ errors.push({
1841
+ code: 'branch_not_found',
1842
+ message: error instanceof Error ? error.message : 'Existing branch not found',
1843
+ });
1844
+ }
1845
+ } else {
1846
+ if (preferredBranchName) {
1847
+ const exists = await runGitCommand(context.primaryWorktree, ['show-ref', '--verify', '--quiet', `refs/heads/${preferredBranchName}`]);
1848
+ if (exists.success) {
1849
+ errors.push({
1850
+ code: 'branch_exists',
1851
+ message: `Branch already exists: ${preferredBranchName}`,
1852
+ });
1853
+ }
1854
+ localBranch = preferredBranchName;
1855
+ }
1856
+
1857
+ const parsedRemoteRef = parseRemoteBranchRef(startRef);
1858
+ if (startRef && startRef !== 'HEAD') {
1859
+ if (parsedRemoteRef && ensureRemoteName && ensureRemoteUrl && ensureRemoteName === parsedRemoteRef.remote) {
1860
+ const remoteCheck = await checkRemoteBranchExists(
1861
+ context.primaryWorktree,
1862
+ parsedRemoteRef.remote,
1863
+ parsedRemoteRef.branch,
1864
+ ensureRemoteUrl
1865
+ );
1866
+ if (!remoteCheck.success) {
1867
+ errors.push({
1868
+ code: 'remote_unreachable',
1869
+ message: `Unable to query remote ${ensureRemoteName}`,
1870
+ });
1871
+ } else if (!remoteCheck.found) {
1872
+ errors.push({
1873
+ code: 'start_ref_not_found',
1874
+ message: `Remote branch not found: ${parsedRemoteRef.remoteRef}`,
1875
+ });
1876
+ }
1877
+ } else if (parsedRemoteRef) {
1878
+ const remoteCheck = await checkRemoteBranchExists(
1879
+ context.primaryWorktree,
1880
+ parsedRemoteRef.remote,
1881
+ parsedRemoteRef.branch
1882
+ );
1883
+ if (!remoteCheck.success) {
1884
+ errors.push({
1885
+ code: 'remote_unreachable',
1886
+ message: `Unable to query remote ${parsedRemoteRef.remote}`,
1887
+ });
1888
+ } else if (!remoteCheck.found) {
1889
+ errors.push({
1890
+ code: 'start_ref_not_found',
1891
+ message: `Remote branch not found: ${parsedRemoteRef.remoteRef}`,
1892
+ });
1893
+ }
1894
+ } else {
1895
+ const startRefExists = await runGitCommand(context.primaryWorktree, ['rev-parse', '--verify', '--quiet', startRef]);
1896
+ if (!startRefExists.success) {
1897
+ errors.push({
1898
+ code: 'start_ref_not_found',
1899
+ message: `Start ref not found: ${startRef}`,
1900
+ });
1901
+ }
1902
+ }
1903
+ }
1904
+
1905
+ if (parsedRemoteRef) {
1906
+ inferredUpstream = {
1907
+ remote: parsedRemoteRef.remote,
1908
+ branch: parsedRemoteRef.branch,
1909
+ };
1910
+ }
1911
+ }
1912
+
1913
+ if (localBranch) {
1914
+ const inUse = await findBranchInUse(context.primaryWorktree, localBranch);
1915
+ if (inUse) {
1916
+ errors.push({
1917
+ code: 'branch_in_use',
1918
+ message: `Branch is already checked out in ${inUse.worktree}`,
1919
+ });
1920
+ }
1921
+ }
1922
+
1923
+ if ((ensureRemoteName && !ensureRemoteUrl) || (!ensureRemoteName && ensureRemoteUrl)) {
1924
+ errors.push({
1925
+ code: 'invalid_remote_config',
1926
+ message: 'Both ensureRemoteName and ensureRemoteUrl are required together',
1927
+ });
1928
+ }
1929
+
1930
+ const shouldSetUpstream = Boolean(input?.setUpstream);
1931
+ if (shouldSetUpstream) {
1932
+ const upstreamRemote = String(input?.upstreamRemote || inferredUpstream?.remote || '').trim();
1933
+ const upstreamBranch = String(input?.upstreamBranch || inferredUpstream?.branch || '').trim();
1934
+
1935
+ if (!upstreamRemote || !upstreamBranch) {
1936
+ errors.push({
1937
+ code: 'upstream_incomplete',
1938
+ message: 'upstreamRemote and upstreamBranch are required when setUpstream is true',
1939
+ });
1940
+ } else {
1941
+ const remoteExists = await runGitCommand(context.primaryWorktree, ['remote', 'get-url', upstreamRemote]);
1942
+ if (!remoteExists.success && (!ensureRemoteName || ensureRemoteName !== upstreamRemote)) {
1943
+ errors.push({
1944
+ code: 'remote_not_found',
1945
+ message: `Remote not found: ${upstreamRemote}`,
1946
+ });
1947
+ }
1948
+ }
1949
+ }
1950
+
1951
+ return {
1952
+ ok: errors.length === 0,
1953
+ errors,
1954
+ resolved: {
1955
+ mode,
1956
+ localBranch: localBranch || null,
1957
+ },
1958
+ };
1959
+ } catch (error) {
1960
+ return {
1961
+ ok: false,
1962
+ errors: [{
1963
+ code: 'validation_failed',
1964
+ message: error instanceof Error ? error.message : 'Failed to validate worktree creation',
1965
+ }],
1966
+ };
1967
+ }
1968
+ }
1969
+
1970
+ export async function createWorktree(directory, input = {}) {
1971
+ const mode = input?.mode === 'existing' ? 'existing' : 'new';
1972
+ const context = await resolveWorktreeProjectContext(directory);
1973
+ await fsp.mkdir(context.worktreeRoot, { recursive: true });
1974
+
1975
+ const preferredName = String(input?.worktreeName || input?.name || '').trim();
1976
+ const preferredBranchName = cleanBranchName(String(input?.branchName || '').trim());
1977
+ const startRef = normalizeStartRef(input?.startRef);
1978
+ const ensureRemoteName = String(input?.ensureRemoteName || '').trim();
1979
+ const ensureRemoteUrl = String(input?.ensureRemoteUrl || '').trim();
1980
+
1981
+ const candidate = await resolveCandidateDirectory(
1982
+ context.worktreeRoot,
1983
+ preferredName,
1984
+ mode === 'new' && preferredBranchName ? preferredBranchName : '',
1985
+ context.primaryWorktree
1986
+ );
1987
+
1988
+ let localBranch = '';
1989
+ let inferredUpstream = null;
1990
+ const worktreeAddArgs = ['worktree', 'add', '--no-checkout'];
1991
+
1992
+ if (mode === 'existing') {
1993
+ const requestedExistingBranch = String(input?.existingBranch || '').trim();
1994
+ const parsedExistingRemote = parseRemoteBranchRef(requestedExistingBranch);
1995
+ if (parsedExistingRemote && ensureRemoteName && ensureRemoteUrl && parsedExistingRemote.remote === ensureRemoteName) {
1996
+ await ensureRemoteWithUrl(context.primaryWorktree, ensureRemoteName, ensureRemoteUrl);
1997
+ await fetchRemoteBranchRef(context.primaryWorktree, parsedExistingRemote.remote, parsedExistingRemote.branch);
1998
+ }
1999
+
2000
+ const resolved = await resolveBranchForExistingMode(context.primaryWorktree, requestedExistingBranch, preferredBranchName);
2001
+ localBranch = resolved.localBranch;
2002
+
2003
+ const inUse = await findBranchInUse(context.primaryWorktree, localBranch);
2004
+ if (inUse) {
2005
+ throw new Error(`Branch is already checked out in ${inUse.worktree}`);
2006
+ }
2007
+
2008
+ if (resolved.createLocalBranch) {
2009
+ worktreeAddArgs.push('-b', localBranch);
2010
+ }
2011
+ worktreeAddArgs.push(candidate.directory, resolved.checkoutRef);
2012
+
2013
+ if (resolved.remoteRef) {
2014
+ inferredUpstream = {
2015
+ remote: resolved.remoteRef.remote,
2016
+ branch: resolved.remoteRef.branch,
2017
+ };
2018
+ }
2019
+ } else {
2020
+ localBranch = candidate.branch;
2021
+ if (!localBranch) {
2022
+ throw new Error('Failed to resolve branch name for new worktree');
2023
+ }
2024
+
2025
+ const branchExists = await runGitCommand(context.primaryWorktree, ['show-ref', '--verify', '--quiet', `refs/heads/${localBranch}`]);
2026
+ if (branchExists.success) {
2027
+ throw new Error(`Branch already exists: ${localBranch}`);
2028
+ }
2029
+
2030
+ const inUse = await findBranchInUse(context.primaryWorktree, localBranch);
2031
+ if (inUse) {
2032
+ throw new Error(`Branch is already checked out in ${inUse.worktree}`);
2033
+ }
2034
+
2035
+ worktreeAddArgs.push('-b', localBranch, candidate.directory);
2036
+ if (startRef && startRef !== 'HEAD') {
2037
+ worktreeAddArgs.push(startRef);
2038
+ }
2039
+
2040
+ const parsedRemoteStartRef = parseRemoteBranchRef(startRef);
2041
+ if (parsedRemoteStartRef) {
2042
+ inferredUpstream = {
2043
+ remote: parsedRemoteStartRef.remote,
2044
+ branch: parsedRemoteStartRef.branch,
2045
+ };
2046
+ }
2047
+ }
2048
+
2049
+ if (ensureRemoteName && ensureRemoteUrl) {
2050
+ await ensureRemoteWithUrl(context.primaryWorktree, ensureRemoteName, ensureRemoteUrl);
2051
+ }
2052
+
2053
+ if (mode === 'new') {
2054
+ const parsedRemoteStartRef = parseRemoteBranchRef(startRef);
2055
+ if (parsedRemoteStartRef) {
2056
+ await fetchRemoteBranchRef(context.primaryWorktree, parsedRemoteStartRef.remote, parsedRemoteStartRef.branch);
2057
+ }
2058
+ }
2059
+
2060
+ await runGitCommandOrThrow(context.primaryWorktree, worktreeAddArgs, 'Failed to create git worktree');
2061
+ await runGitCommandOrThrow(candidate.directory, ['reset', '--hard'], 'Failed to populate worktree');
2062
+
2063
+ try {
2064
+ await syncProjectSandboxAdd(context.projectID, context.primaryWorktree, candidate.directory);
2065
+ } catch (error) {
2066
+ console.warn('Failed to sync OpenCode sandbox metadata (add):', error instanceof Error ? error.message : String(error));
2067
+ }
2068
+
2069
+ const shouldSetUpstream = Boolean(input?.setUpstream);
2070
+ const upstreamRemote = String(input?.upstreamRemote || inferredUpstream?.remote || '').trim();
2071
+ const upstreamBranch = String(input?.upstreamBranch || inferredUpstream?.branch || '').trim();
2072
+
2073
+ if (shouldSetUpstream) {
2074
+ await applyUpstreamConfiguration({
2075
+ primaryWorktree: context.primaryWorktree,
2076
+ worktreeDirectory: candidate.directory,
2077
+ localBranch,
2078
+ setUpstream: shouldSetUpstream,
2079
+ upstreamRemote,
2080
+ upstreamBranch,
2081
+ ensureRemoteName,
2082
+ ensureRemoteUrl,
2083
+ });
2084
+ }
2085
+
2086
+ queueWorktreeStartScripts(candidate.directory, context.projectID, input?.startCommand);
2087
+
2088
+ const headResult = await runGitCommand(candidate.directory, ['rev-parse', 'HEAD']);
2089
+ const head = String(headResult.stdout || '').trim();
2090
+
2091
+ return {
2092
+ head,
2093
+ name: candidate.name,
2094
+ branch: localBranch,
2095
+ path: candidate.directory,
2096
+ };
2097
+ }
2098
+
2099
+ export async function removeWorktree(directory, input = {}) {
2100
+ const targetDirectory = normalizeDirectoryPath(input?.directory);
2101
+ if (!targetDirectory) {
2102
+ throw new Error('Worktree directory is required');
2103
+ }
2104
+
2105
+ const context = await resolveWorktreeProjectContext(directory);
2106
+ const deleteLocalBranch = input?.deleteLocalBranch === true;
2107
+
2108
+ const targetCanonical = await canonicalPath(targetDirectory);
2109
+ const primaryCanonical = await canonicalPath(context.primaryWorktree);
2110
+ if (targetCanonical === primaryCanonical) {
2111
+ throw new Error('Cannot remove the primary workspace');
2112
+ }
2113
+
2114
+ const entries = await listWorktreeEntries(context.primaryWorktree);
2115
+ const matchedEntry = await (async () => {
2116
+ for (const entry of entries) {
2117
+ if (!entry?.worktree) {
2118
+ continue;
2119
+ }
2120
+ const entryCanonical = await canonicalPath(entry.worktree);
2121
+ if (entryCanonical === targetCanonical) {
2122
+ return entry;
2123
+ }
2124
+ }
2125
+ return null;
2126
+ })();
2127
+
2128
+ if (!matchedEntry?.worktree) {
2129
+ const targetExists = await checkPathExists(targetDirectory);
2130
+ if (targetExists) {
2131
+ await fsp.rm(targetDirectory, { recursive: true, force: true });
2132
+ }
2133
+
2134
+ try {
2135
+ await syncProjectSandboxRemove(context.projectID, context.primaryWorktree, targetDirectory);
2136
+ } catch (error) {
2137
+ console.warn('Failed to sync OpenCode sandbox metadata (remove):', error instanceof Error ? error.message : String(error));
2138
+ }
2139
+
2140
+ return true;
2141
+ }
2142
+
2143
+ await runGitCommandOrThrow(
2144
+ context.primaryWorktree,
2145
+ ['worktree', 'remove', '--force', matchedEntry.worktree],
2146
+ 'Failed to remove git worktree'
2147
+ );
2148
+
2149
+ if (deleteLocalBranch) {
2150
+ const branchName = cleanBranchName(String(matchedEntry.branchRef || matchedEntry.branch || '').trim());
2151
+ if (branchName) {
2152
+ await runGitCommandOrThrow(
2153
+ context.primaryWorktree,
2154
+ ['branch', '-D', branchName],
2155
+ `Failed to delete local branch ${branchName}`
2156
+ );
2157
+ }
2158
+ }
2159
+
2160
+ try {
2161
+ await syncProjectSandboxRemove(context.projectID, context.primaryWorktree, matchedEntry.worktree);
2162
+ } catch (error) {
2163
+ console.warn('Failed to sync OpenCode sandbox metadata (remove):', error instanceof Error ? error.message : String(error));
2164
+ }
2165
+
2166
+ return true;
2167
+ }
2168
+
2169
+ export async function deleteBranch(directory, branch, options = {}) {
2170
+ const git = await createGit(directory);
2171
+
2172
+ try {
2173
+ const branchName = branch.startsWith('refs/heads/')
2174
+ ? branch.substring('refs/heads/'.length)
2175
+ : branch;
2176
+ const args = ['branch', options.force ? '-D' : '-d', branchName];
2177
+ await git.raw(args);
2178
+ return { success: true };
2179
+ } catch (error) {
2180
+ console.error('Failed to delete branch:', error);
2181
+ throw error;
2182
+ }
2183
+ }
2184
+
2185
+ export async function getLog(directory, options = {}) {
2186
+ const git = await createGit(directory);
2187
+
2188
+ try {
2189
+ const maxCount = options.maxCount || 50;
2190
+ const baseLog = await git.log({
2191
+ maxCount,
2192
+ from: options.from,
2193
+ to: options.to,
2194
+ file: options.file
2195
+ });
2196
+
2197
+ const logArgs = [
2198
+ 'log',
2199
+ `--max-count=${maxCount}`,
2200
+ '--date=iso',
2201
+ '--pretty=format:%H%x1f%an%x1f%ae%x1f%ad%x1f%s%x1e',
2202
+ '--shortstat'
2203
+ ];
2204
+
2205
+ if (options.from && options.to) {
2206
+ logArgs.push(`${options.from}..${options.to}`);
2207
+ } else if (options.from) {
2208
+ logArgs.push(`${options.from}..HEAD`);
2209
+ } else if (options.to) {
2210
+ logArgs.push(options.to);
2211
+ }
2212
+
2213
+ if (options.file) {
2214
+ logArgs.push('--', options.file);
2215
+ }
2216
+
2217
+ const rawLog = await git.raw(logArgs);
2218
+ const records = rawLog
2219
+ .split('\x1e')
2220
+ .map((entry) => entry.trim())
2221
+ .filter(Boolean);
2222
+
2223
+ const statsMap = new Map();
2224
+
2225
+ records.forEach((record) => {
2226
+ const lines = record.split('\n').filter((line) => line.trim().length > 0);
2227
+ const header = lines.shift() || '';
2228
+ const [hash] = header.split('\x1f');
2229
+ if (!hash) {
2230
+ return;
2231
+ }
2232
+
2233
+ let filesChanged = 0;
2234
+ let insertions = 0;
2235
+ let deletions = 0;
2236
+
2237
+ lines.forEach((line) => {
2238
+ const filesMatch = line.match(/(\d+)\s+files?\s+changed/);
2239
+ const insertMatch = line.match(/(\d+)\s+insertions?\(\+\)/);
2240
+ const deleteMatch = line.match(/(\d+)\s+deletions?\(-\)/);
2241
+
2242
+ if (filesMatch) {
2243
+ filesChanged = parseInt(filesMatch[1], 10);
2244
+ }
2245
+ if (insertMatch) {
2246
+ insertions = parseInt(insertMatch[1], 10);
2247
+ }
2248
+ if (deleteMatch) {
2249
+ deletions = parseInt(deleteMatch[1], 10);
2250
+ }
2251
+ });
2252
+
2253
+ statsMap.set(hash, { filesChanged, insertions, deletions });
2254
+ });
2255
+
2256
+ const merged = baseLog.all.map((entry) => {
2257
+ const stats = statsMap.get(entry.hash) || { filesChanged: 0, insertions: 0, deletions: 0 };
2258
+ return {
2259
+ hash: entry.hash,
2260
+ date: entry.date,
2261
+ message: entry.message,
2262
+ refs: entry.refs || '',
2263
+ body: entry.body || '',
2264
+ author_name: entry.author_name,
2265
+ author_email: entry.author_email,
2266
+ filesChanged: stats.filesChanged,
2267
+ insertions: stats.insertions,
2268
+ deletions: stats.deletions
2269
+ };
2270
+ });
2271
+
2272
+ return {
2273
+ all: merged,
2274
+ latest: merged[0] || null,
2275
+ total: baseLog.total
2276
+ };
2277
+ } catch (error) {
2278
+ console.error('Failed to get log:', error);
2279
+ throw error;
2280
+ }
2281
+ }
2282
+
2283
+ export async function isLinkedWorktree(directory) {
2284
+ const git = await createGit(directory);
2285
+ try {
2286
+ const [gitDir, gitCommonDir] = await Promise.all([
2287
+ git.raw(['rev-parse', '--git-dir']).then((output) => output.trim()),
2288
+ git.raw(['rev-parse', '--git-common-dir']).then((output) => output.trim())
2289
+ ]);
2290
+ return gitDir !== gitCommonDir;
2291
+ } catch (error) {
2292
+ console.error('Failed to determine worktree type:', error);
2293
+ return false;
2294
+ }
2295
+ }
2296
+
2297
+ export async function getCommitFiles(directory, commitHash) {
2298
+ const git = await createGit(directory);
2299
+
2300
+ try {
2301
+
2302
+ const numstatRaw = await git.raw([
2303
+ 'show',
2304
+ '--numstat',
2305
+ '--format=',
2306
+ commitHash
2307
+ ]);
2308
+
2309
+ const files = [];
2310
+ const lines = numstatRaw.trim().split('\n').filter(Boolean);
2311
+
2312
+ for (const line of lines) {
2313
+ const parts = line.split('\t');
2314
+ if (parts.length < 3) continue;
2315
+
2316
+ const [insertionsRaw, deletionsRaw, ...pathParts] = parts;
2317
+ const filePath = pathParts.join('\t');
2318
+ if (!filePath) continue;
2319
+
2320
+ const insertions = insertionsRaw === '-' ? 0 : parseInt(insertionsRaw, 10) || 0;
2321
+ const deletions = deletionsRaw === '-' ? 0 : parseInt(deletionsRaw, 10) || 0;
2322
+ const isBinary = insertionsRaw === '-' && deletionsRaw === '-';
2323
+
2324
+ let changeType = 'M';
2325
+ let displayPath = filePath;
2326
+
2327
+ if (filePath.includes(' => ')) {
2328
+ changeType = 'R';
2329
+
2330
+ const match = filePath.match(/(?:\{[^}]*\s=>\s[^}]*\}|.*\s=>\s.*)/);
2331
+ if (match) {
2332
+ displayPath = filePath;
2333
+ }
2334
+ }
2335
+
2336
+ files.push({
2337
+ path: displayPath,
2338
+ insertions,
2339
+ deletions,
2340
+ isBinary,
2341
+ changeType
2342
+ });
2343
+ }
2344
+
2345
+ const nameStatusRaw = await git.raw([
2346
+ 'show',
2347
+ '--name-status',
2348
+ '--format=',
2349
+ commitHash
2350
+ ]).catch(() => '');
2351
+
2352
+ const statusMap = new Map();
2353
+ const statusLines = nameStatusRaw.trim().split('\n').filter(Boolean);
2354
+ for (const line of statusLines) {
2355
+ const match = line.match(/^([AMDRC])\d*\t(.+)$/);
2356
+ if (match) {
2357
+ const [, status, path] = match;
2358
+ statusMap.set(path, status);
2359
+ }
2360
+ }
2361
+
2362
+ for (const file of files) {
2363
+ const basePath = file.path.includes(' => ')
2364
+ ? file.path.split(' => ').pop()?.replace(/[{}]/g, '') || file.path
2365
+ : file.path;
2366
+
2367
+ const status = statusMap.get(basePath) || statusMap.get(file.path);
2368
+ if (status) {
2369
+ file.changeType = status;
2370
+ }
2371
+ }
2372
+
2373
+ return { files };
2374
+ } catch (error) {
2375
+ console.error('Failed to get commit files:', error);
2376
+ throw error;
2377
+ }
2378
+ }
2379
+
2380
+ export async function renameBranch(directory, oldName, newName) {
2381
+ const git = await createGit(directory);
2382
+
2383
+ try {
2384
+ // Use git branch -m command to rename the branch
2385
+ await git.raw(['branch', '-m', oldName, newName]);
2386
+ return { success: true, branch: newName };
2387
+ } catch (error) {
2388
+ console.error('Failed to rename branch:', error);
2389
+ throw error;
2390
+ }
2391
+ }
2392
+
2393
+ export async function getRemotes(directory) {
2394
+ const git = await createGit(directory);
2395
+
2396
+ try {
2397
+ const remotes = await git.getRemotes(true);
2398
+
2399
+ return remotes.map((remote) => ({
2400
+ name: remote.name,
2401
+ fetchUrl: remote.refs.fetch,
2402
+ pushUrl: remote.refs.push
2403
+ }));
2404
+ } catch (error) {
2405
+ console.error('Failed to get remotes:', error);
2406
+ throw error;
2407
+ }
2408
+ }
2409
+
2410
+ export async function rebase(directory, options = {}) {
2411
+ const git = await createGit(directory);
2412
+
2413
+ try {
2414
+ const { onto } = options;
2415
+ if (!onto) {
2416
+ throw new Error('onto parameter is required for rebase');
2417
+ }
2418
+
2419
+ await git.rebase([onto]);
2420
+
2421
+ return {
2422
+ success: true,
2423
+ conflict: false
2424
+ };
2425
+ } catch (error) {
2426
+ const errorMessage = String(error?.message || error || '').toLowerCase();
2427
+ const isConflict = errorMessage.includes('conflict') ||
2428
+ errorMessage.includes('could not apply') ||
2429
+ errorMessage.includes('merge conflict');
2430
+
2431
+ if (isConflict) {
2432
+ // Get list of conflicted files
2433
+ const status = await git.status().catch(() => ({ conflicted: [] }));
2434
+ return {
2435
+ success: false,
2436
+ conflict: true,
2437
+ conflictFiles: status.conflicted || []
2438
+ };
2439
+ }
2440
+
2441
+ console.error('Failed to rebase:', error);
2442
+ throw error;
2443
+ }
2444
+ }
2445
+
2446
+ export async function abortRebase(directory) {
2447
+ const git = await createGit(directory);
2448
+
2449
+ try {
2450
+ await git.rebase(['--abort']);
2451
+ return { success: true };
2452
+ } catch (error) {
2453
+ console.error('Failed to abort rebase:', error);
2454
+ throw error;
2455
+ }
2456
+ }
2457
+
2458
+ export async function merge(directory, options = {}) {
2459
+ const git = await createGit(directory);
2460
+
2461
+ try {
2462
+ const { branch } = options;
2463
+ if (!branch) {
2464
+ throw new Error('branch parameter is required for merge');
2465
+ }
2466
+
2467
+ await git.merge([branch]);
2468
+
2469
+ return {
2470
+ success: true,
2471
+ conflict: false
2472
+ };
2473
+ } catch (error) {
2474
+ const errorMessage = String(error?.message || error || '').toLowerCase();
2475
+ const isConflict = errorMessage.includes('conflict') ||
2476
+ errorMessage.includes('merge conflict') ||
2477
+ errorMessage.includes('automatic merge failed');
2478
+
2479
+ if (isConflict) {
2480
+ // Get list of conflicted files
2481
+ const status = await git.status().catch(() => ({ conflicted: [] }));
2482
+ return {
2483
+ success: false,
2484
+ conflict: true,
2485
+ conflictFiles: status.conflicted || []
2486
+ };
2487
+ }
2488
+
2489
+ console.error('Failed to merge:', error);
2490
+ throw error;
2491
+ }
2492
+ }
2493
+
2494
+ export async function abortMerge(directory) {
2495
+ const git = await createGit(directory);
2496
+
2497
+ try {
2498
+ await git.merge(['--abort']);
2499
+ return { success: true };
2500
+ } catch (error) {
2501
+ console.error('Failed to abort merge:', error);
2502
+ throw error;
2503
+ }
2504
+ }
2505
+
2506
+ export async function continueRebase(directory) {
2507
+ const directoryPath = normalizeDirectoryPath(directory);
2508
+ const git = await createGit(directoryPath);
2509
+
2510
+ try {
2511
+ // Set GIT_EDITOR to prevent editor prompts
2512
+ await git.env('GIT_EDITOR', 'true').rebase(['--continue']);
2513
+ return { success: true, conflict: false };
2514
+ } catch (error) {
2515
+ const errorMessage = String(error?.message || error || '').toLowerCase();
2516
+ const isConflict = errorMessage.includes('conflict') ||
2517
+ errorMessage.includes('needs merge') ||
2518
+ errorMessage.includes('unmerged') ||
2519
+ errorMessage.includes('fix conflicts');
2520
+
2521
+ if (isConflict) {
2522
+ const status = await git.status().catch(() => ({ conflicted: [] }));
2523
+ return {
2524
+ success: false,
2525
+ conflict: true,
2526
+ conflictFiles: status.conflicted || []
2527
+ };
2528
+ }
2529
+
2530
+ // Check for "nothing to commit" which means rebase step is complete
2531
+ if (errorMessage.includes('nothing to commit') || errorMessage.includes('no changes')) {
2532
+ // Skip this commit and continue
2533
+ try {
2534
+ await git.env('GIT_EDITOR', 'true').rebase(['--skip']);
2535
+ return { success: true, conflict: false };
2536
+ } catch {
2537
+ // If skip also fails, the rebase may be complete
2538
+ return { success: true, conflict: false };
2539
+ }
2540
+ }
2541
+
2542
+ console.error('Failed to continue rebase:', error);
2543
+ throw error;
2544
+ }
2545
+ }
2546
+
2547
+ export async function continueMerge(directory) {
2548
+ const directoryPath = normalizeDirectoryPath(directory);
2549
+ const git = await createGit(directoryPath);
2550
+
2551
+ try {
2552
+ // Check if there are still unmerged files
2553
+ const status = await git.status();
2554
+ if (status.conflicted && status.conflicted.length > 0) {
2555
+ return {
2556
+ success: false,
2557
+ conflict: true,
2558
+ conflictFiles: status.conflicted
2559
+ };
2560
+ }
2561
+
2562
+ // For merge, we commit after resolving conflicts
2563
+ // Use --no-edit to use the default merge commit message
2564
+ await git.env('GIT_EDITOR', 'true').commit([], { '--no-edit': null });
2565
+ return { success: true, conflict: false };
2566
+ } catch (error) {
2567
+ const errorMessage = String(error?.message || error || '').toLowerCase();
2568
+ const isConflict = errorMessage.includes('conflict') ||
2569
+ errorMessage.includes('needs merge') ||
2570
+ errorMessage.includes('unmerged') ||
2571
+ errorMessage.includes('fix conflicts');
2572
+
2573
+ if (isConflict) {
2574
+ const status = await git.status().catch(() => ({ conflicted: [] }));
2575
+ return {
2576
+ success: false,
2577
+ conflict: true,
2578
+ conflictFiles: status.conflicted || []
2579
+ };
2580
+ }
2581
+
2582
+ // "nothing to commit" can happen if all conflicts resolved to one side
2583
+ if (errorMessage.includes('nothing to commit') || errorMessage.includes('no changes added')) {
2584
+ // The merge is effectively complete (all changes already committed or no changes needed)
2585
+ return { success: true, conflict: false };
2586
+ }
2587
+
2588
+ console.error('Failed to continue merge:', error);
2589
+ throw error;
2590
+ }
2591
+ }
2592
+
2593
+ export async function getConflictDetails(directory) {
2594
+ const directoryPath = normalizeDirectoryPath(directory);
2595
+ const git = await createGit(directoryPath);
2596
+
2597
+ try {
2598
+ // Get git status --porcelain
2599
+ const statusPorcelain = await git.raw(['status', '--porcelain']).catch(() => '');
2600
+
2601
+ // Get unmerged files
2602
+ const unmergedFilesRaw = await git.raw(['diff', '--name-only', '--diff-filter=U']).catch(() => '');
2603
+ const unmergedFiles = unmergedFilesRaw
2604
+ .split('\n')
2605
+ .map((line) => line.trim())
2606
+ .filter(Boolean);
2607
+
2608
+ // Get current diff
2609
+ const diff = await git.raw(['diff']).catch(() => '');
2610
+
2611
+ // Detect operation type and get head info
2612
+ let operation = 'merge';
2613
+ let headInfo = '';
2614
+
2615
+ // Check for MERGE_HEAD (merge in progress)
2616
+ const mergeHeadExists = await git
2617
+ .raw(['rev-parse', '--verify', '--quiet', 'MERGE_HEAD'])
2618
+ .then(() => true)
2619
+ .catch(() => false);
2620
+
2621
+ if (mergeHeadExists) {
2622
+ operation = 'merge';
2623
+ const mergeHead = await git.raw(['rev-parse', 'MERGE_HEAD']).catch(() => '');
2624
+ const mergeMsg = await fsp
2625
+ .readFile(path.join(directoryPath, '.git', 'MERGE_MSG'), 'utf8')
2626
+ .catch(() => '');
2627
+ headInfo = `MERGE_HEAD: ${mergeHead.trim()}\n${mergeMsg}`;
2628
+ } else {
2629
+ // Check for REBASE_HEAD (rebase in progress)
2630
+ const rebaseHeadExists = await git
2631
+ .raw(['rev-parse', '--verify', '--quiet', 'REBASE_HEAD'])
2632
+ .then(() => true)
2633
+ .catch(() => false);
2634
+
2635
+ if (rebaseHeadExists) {
2636
+ operation = 'rebase';
2637
+ const rebaseHead = await git.raw(['rev-parse', 'REBASE_HEAD']).catch(() => '');
2638
+ headInfo = `REBASE_HEAD: ${rebaseHead.trim()}`;
2639
+ }
2640
+ }
2641
+
2642
+ return {
2643
+ statusPorcelain: statusPorcelain.trim(),
2644
+ unmergedFiles,
2645
+ diff: diff.trim(),
2646
+ headInfo: headInfo.trim(),
2647
+ operation,
2648
+ };
2649
+ } catch (error) {
2650
+ console.error('Failed to get conflict details:', error);
2651
+ throw error;
2652
+ }
2653
+ }
2654
+
2655
+ // ============== Stash Operations ==============
2656
+
2657
+ export async function stash(directory, options = {}) {
2658
+ const git = await createGit(directory);
2659
+
2660
+ try {
2661
+ const args = ['stash', 'push'];
2662
+
2663
+ // Include untracked files by default
2664
+ if (options.includeUntracked !== false) {
2665
+ args.push('--include-untracked');
2666
+ }
2667
+
2668
+ if (options.message) {
2669
+ args.push('-m', options.message);
2670
+ }
2671
+
2672
+ await git.raw(args);
2673
+ return { success: true };
2674
+ } catch (error) {
2675
+ console.error('Failed to stash:', error);
2676
+ throw error;
2677
+ }
2678
+ }
2679
+
2680
+ export async function stashPop(directory) {
2681
+ const git = await createGit(directory);
2682
+
2683
+ try {
2684
+ await git.raw(['stash', 'pop']);
2685
+ return { success: true };
2686
+ } catch (error) {
2687
+ console.error('Failed to pop stash:', error);
2688
+ throw error;
2689
+ }
2690
+ }