@iloom/cli 0.1.19 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/README.md +290 -30
  2. package/dist/BranchNamingService-3OQPRSWT.js +13 -0
  3. package/dist/ClaudeContextManager-MUQSDY2E.js +13 -0
  4. package/dist/ClaudeService-HG4VQ7AW.js +12 -0
  5. package/dist/GitHubService-EBOETDIW.js +11 -0
  6. package/dist/{LoomLauncher-UMMLPIZO.js → LoomLauncher-FLEMBCSQ.js} +64 -33
  7. package/dist/LoomLauncher-FLEMBCSQ.js.map +1 -0
  8. package/dist/ProjectCapabilityDetector-34LU7JJ4.js +9 -0
  9. package/dist/{PromptTemplateManager-WII75TKH.js → PromptTemplateManager-A52RUAMS.js} +2 -2
  10. package/dist/README.md +290 -30
  11. package/dist/{SettingsManager-SKLUVE3K.js → SettingsManager-WHHFGSL7.js} +12 -4
  12. package/dist/SettingsMigrationManager-AGIIIPDQ.js +10 -0
  13. package/dist/agents/iloom-issue-analyze-and-plan.md +125 -35
  14. package/dist/agents/iloom-issue-analyzer.md +284 -32
  15. package/dist/agents/iloom-issue-complexity-evaluator.md +40 -21
  16. package/dist/agents/iloom-issue-enhancer.md +69 -48
  17. package/dist/agents/iloom-issue-implementer.md +36 -25
  18. package/dist/agents/iloom-issue-planner.md +35 -24
  19. package/dist/agents/iloom-issue-reviewer.md +62 -9
  20. package/dist/chunk-3KATJIKO.js +55 -0
  21. package/dist/chunk-3KATJIKO.js.map +1 -0
  22. package/dist/{chunk-JXQXSC45.js → chunk-3RUPPQRG.js} +1 -18
  23. package/dist/chunk-3RUPPQRG.js.map +1 -0
  24. package/dist/{chunk-PR7FKQBG.js → chunk-47KSHUCR.js} +3 -3
  25. package/dist/chunk-47KSHUCR.js.map +1 -0
  26. package/dist/{chunk-IO4WFTL2.js → chunk-4HHRTA7Q.js} +3 -3
  27. package/dist/{chunk-IO4WFTL2.js.map → chunk-4HHRTA7Q.js.map} +1 -1
  28. package/dist/chunk-5EF7Z346.js +1987 -0
  29. package/dist/chunk-5EF7Z346.js.map +1 -0
  30. package/dist/{chunk-VVH3ANF2.js → chunk-AWOFAD5O.js} +12 -12
  31. package/dist/chunk-AWOFAD5O.js.map +1 -0
  32. package/dist/{chunk-DEPYQRRB.js → chunk-C5QCTEQK.js} +2 -2
  33. package/dist/{chunk-CWR2SANQ.js → chunk-EBISESAP.js} +1 -1
  34. package/dist/{chunk-ELFT36PV.js → chunk-FIAT22G7.js} +4 -16
  35. package/dist/chunk-FIAT22G7.js.map +1 -0
  36. package/dist/{chunk-ZWXJBSUW.js → chunk-G2IEYOLQ.js} +11 -38
  37. package/dist/chunk-G2IEYOLQ.js.map +1 -0
  38. package/dist/{chunk-ZMNQBJUI.js → chunk-IP7SMKIF.js} +61 -22
  39. package/dist/chunk-IP7SMKIF.js.map +1 -0
  40. package/dist/{chunk-JNKJ7NJV.js → chunk-JKXJ7BGL.js} +6 -2
  41. package/dist/{chunk-JNKJ7NJV.js.map → chunk-JKXJ7BGL.js.map} +1 -1
  42. package/dist/{chunk-LAPY6NAE.js → chunk-JQFO7QQN.js} +68 -12
  43. package/dist/{chunk-LAPY6NAE.js.map → chunk-JQFO7QQN.js.map} +1 -1
  44. package/dist/{SettingsMigrationManager-MTQIMI54.js → chunk-KLBYVHPK.js} +3 -2
  45. package/dist/{chunk-KOCQAD2E.js → chunk-MAVL6PJF.js} +26 -3
  46. package/dist/chunk-MAVL6PJF.js.map +1 -0
  47. package/dist/{chunk-USVVV3FP.js → chunk-MKWYLDFK.js} +5 -5
  48. package/dist/chunk-ML3NRPNB.js +396 -0
  49. package/dist/chunk-ML3NRPNB.js.map +1 -0
  50. package/dist/{chunk-FXV24OYZ.js → chunk-PA6Q6AWM.js} +24 -4
  51. package/dist/chunk-PA6Q6AWM.js.map +1 -0
  52. package/dist/chunk-RO26VS3W.js +444 -0
  53. package/dist/chunk-RO26VS3W.js.map +1 -0
  54. package/dist/{chunk-PV3GAXQO.js → chunk-VAYCCUXW.js} +72 -2
  55. package/dist/{chunk-PV3GAXQO.js.map → chunk-VAYCCUXW.js.map} +1 -1
  56. package/dist/{chunk-SPYPLHMK.js → chunk-VU3QMIP2.js} +34 -2
  57. package/dist/chunk-VU3QMIP2.js.map +1 -0
  58. package/dist/{chunk-PVAVNJKS.js → chunk-WEN5C5DM.js} +10 -1
  59. package/dist/chunk-WEN5C5DM.js.map +1 -0
  60. package/dist/{chunk-PXZBAC2M.js → chunk-XXV3UFZL.js} +4 -4
  61. package/dist/{chunk-PXZBAC2M.js.map → chunk-XXV3UFZL.js.map} +1 -1
  62. package/dist/{chunk-RSRO7564.js → chunk-ZE74H5BR.js} +28 -3
  63. package/dist/chunk-ZE74H5BR.js.map +1 -0
  64. package/dist/{chunk-GZP4UGGM.js → chunk-ZM3CFL5L.js} +2 -2
  65. package/dist/{chunk-BLCTGFZN.js → chunk-ZT3YZB4K.js} +3 -4
  66. package/dist/chunk-ZT3YZB4K.js.map +1 -0
  67. package/dist/{claude-7LUVDZZ4.js → claude-GOP6PFC7.js} +2 -2
  68. package/dist/{cleanup-ZHROIBSQ.js → cleanup-7RWLBSLE.js} +86 -25
  69. package/dist/cleanup-7RWLBSLE.js.map +1 -0
  70. package/dist/cli.js +2513 -64
  71. package/dist/cli.js.map +1 -1
  72. package/dist/{contribute-3MQJ3XAQ.js → contribute-BS2L4FZR.js} +9 -6
  73. package/dist/{contribute-3MQJ3XAQ.js.map → contribute-BS2L4FZR.js.map} +1 -1
  74. package/dist/{feedback-ZOUCCHN4.js → feedback-N4ECWIPF.js} +15 -14
  75. package/dist/{feedback-ZOUCCHN4.js.map → feedback-N4ECWIPF.js.map} +1 -1
  76. package/dist/{git-OUYMVYJX.js → git-TDXKRTXM.js} +4 -2
  77. package/dist/{ignite-HICLZEYU.js → ignite-VM64QO3J.js} +32 -27
  78. package/dist/ignite-VM64QO3J.js.map +1 -0
  79. package/dist/index.d.ts +379 -45
  80. package/dist/index.js +1241 -448
  81. package/dist/index.js.map +1 -1
  82. package/dist/{init-UMKNHNV5.js → init-G3T64SC4.js} +104 -40
  83. package/dist/init-G3T64SC4.js.map +1 -0
  84. package/dist/mcp/issue-management-server.js +934 -0
  85. package/dist/mcp/issue-management-server.js.map +1 -0
  86. package/dist/{neon-helpers-ZVIRPKCI.js → neon-helpers-WPUACUVC.js} +3 -3
  87. package/dist/{open-ETZUFSE4.js → open-KXDXEKRZ.js} +39 -36
  88. package/dist/open-KXDXEKRZ.js.map +1 -0
  89. package/dist/{prompt-ANTQWHUF.js → prompt-7INJ7YRU.js} +4 -2
  90. package/dist/prompt-7INJ7YRU.js.map +1 -0
  91. package/dist/prompts/init-prompt.txt +563 -91
  92. package/dist/prompts/issue-prompt.txt +27 -27
  93. package/dist/{rebase-KBWFDZCN.js → rebase-Q7GMM7EI.js} +6 -6
  94. package/dist/{remote-GJEZWRCC.js → remote-VUNCQZ6J.js} +5 -2
  95. package/dist/remote-VUNCQZ6J.js.map +1 -0
  96. package/dist/{run-4SVQ3WEU.js → run-PAWJJCSX.js} +39 -36
  97. package/dist/run-PAWJJCSX.js.map +1 -0
  98. package/dist/schema/settings.schema.json +74 -0
  99. package/dist/{terminal-3D6TUAKJ.js → terminal-BIRBZ4AZ.js} +2 -2
  100. package/dist/terminal-BIRBZ4AZ.js.map +1 -0
  101. package/dist/{test-git-MKZATGZN.js → test-git-3WDLNQCA.js} +3 -3
  102. package/dist/{test-prefix-ZNLWDI3K.js → test-prefix-EVGAWAJW.js} +3 -3
  103. package/dist/{test-tabs-JRKY3QMM.js → test-tabs-RXDBZ6J7.js} +2 -2
  104. package/dist/{test-webserver-M2I3EV4J.js → test-webserver-DAHONWCS.js} +4 -4
  105. package/dist/test-webserver-DAHONWCS.js.map +1 -0
  106. package/package.json +2 -1
  107. package/dist/ClaudeContextManager-JKR4WGNU.js +0 -13
  108. package/dist/ClaudeService-55DQGB7T.js +0 -12
  109. package/dist/GitHubService-LWP4GKGH.js +0 -11
  110. package/dist/LoomLauncher-UMMLPIZO.js.map +0 -1
  111. package/dist/add-issue-X56V3XPB.js +0 -69
  112. package/dist/add-issue-X56V3XPB.js.map +0 -1
  113. package/dist/chunk-BLCTGFZN.js.map +0 -1
  114. package/dist/chunk-ELFT36PV.js.map +0 -1
  115. package/dist/chunk-FXV24OYZ.js.map +0 -1
  116. package/dist/chunk-H4E4THUZ.js +0 -55
  117. package/dist/chunk-H4E4THUZ.js.map +0 -1
  118. package/dist/chunk-H5LDRGVK.js +0 -642
  119. package/dist/chunk-H5LDRGVK.js.map +0 -1
  120. package/dist/chunk-JXQXSC45.js.map +0 -1
  121. package/dist/chunk-KOCQAD2E.js.map +0 -1
  122. package/dist/chunk-PR7FKQBG.js.map +0 -1
  123. package/dist/chunk-PVAVNJKS.js.map +0 -1
  124. package/dist/chunk-Q2KYPAH2.js +0 -545
  125. package/dist/chunk-Q2KYPAH2.js.map +0 -1
  126. package/dist/chunk-RSRO7564.js.map +0 -1
  127. package/dist/chunk-SPYPLHMK.js.map +0 -1
  128. package/dist/chunk-VCMMAFXQ.js +0 -54
  129. package/dist/chunk-VCMMAFXQ.js.map +0 -1
  130. package/dist/chunk-VVH3ANF2.js.map +0 -1
  131. package/dist/chunk-VYQLLHZ7.js +0 -239
  132. package/dist/chunk-VYQLLHZ7.js.map +0 -1
  133. package/dist/chunk-ZMNQBJUI.js.map +0 -1
  134. package/dist/chunk-ZWXJBSUW.js.map +0 -1
  135. package/dist/cleanup-ZHROIBSQ.js.map +0 -1
  136. package/dist/enhance-VGWUX474.js +0 -176
  137. package/dist/enhance-VGWUX474.js.map +0 -1
  138. package/dist/finish-QJSK6Z7J.js +0 -1355
  139. package/dist/finish-QJSK6Z7J.js.map +0 -1
  140. package/dist/ignite-HICLZEYU.js.map +0 -1
  141. package/dist/init-UMKNHNV5.js.map +0 -1
  142. package/dist/mcp/chunk-6SDFJ42P.js +0 -62
  143. package/dist/mcp/chunk-6SDFJ42P.js.map +0 -1
  144. package/dist/mcp/claude-YHHHLSXH.js +0 -249
  145. package/dist/mcp/claude-YHHHLSXH.js.map +0 -1
  146. package/dist/mcp/color-QS5BFCNN.js +0 -168
  147. package/dist/mcp/color-QS5BFCNN.js.map +0 -1
  148. package/dist/mcp/github-comment-server.js +0 -168
  149. package/dist/mcp/github-comment-server.js.map +0 -1
  150. package/dist/mcp/terminal-SDCMDVD7.js +0 -202
  151. package/dist/mcp/terminal-SDCMDVD7.js.map +0 -1
  152. package/dist/open-ETZUFSE4.js.map +0 -1
  153. package/dist/run-4SVQ3WEU.js.map +0 -1
  154. package/dist/start-CT2ZEFP2.js +0 -983
  155. package/dist/start-CT2ZEFP2.js.map +0 -1
  156. package/dist/test-webserver-M2I3EV4J.js.map +0 -1
  157. /package/dist/{ClaudeContextManager-JKR4WGNU.js.map → BranchNamingService-3OQPRSWT.js.map} +0 -0
  158. /package/dist/{ClaudeService-55DQGB7T.js.map → ClaudeContextManager-MUQSDY2E.js.map} +0 -0
  159. /package/dist/{GitHubService-LWP4GKGH.js.map → ClaudeService-HG4VQ7AW.js.map} +0 -0
  160. /package/dist/{PromptTemplateManager-WII75TKH.js.map → GitHubService-EBOETDIW.js.map} +0 -0
  161. /package/dist/{SettingsManager-SKLUVE3K.js.map → ProjectCapabilityDetector-34LU7JJ4.js.map} +0 -0
  162. /package/dist/{claude-7LUVDZZ4.js.map → PromptTemplateManager-A52RUAMS.js.map} +0 -0
  163. /package/dist/{git-OUYMVYJX.js.map → SettingsManager-WHHFGSL7.js.map} +0 -0
  164. /package/dist/{neon-helpers-ZVIRPKCI.js.map → SettingsMigrationManager-AGIIIPDQ.js.map} +0 -0
  165. /package/dist/{chunk-DEPYQRRB.js.map → chunk-C5QCTEQK.js.map} +0 -0
  166. /package/dist/{chunk-CWR2SANQ.js.map → chunk-EBISESAP.js.map} +0 -0
  167. /package/dist/{SettingsMigrationManager-MTQIMI54.js.map → chunk-KLBYVHPK.js.map} +0 -0
  168. /package/dist/{chunk-USVVV3FP.js.map → chunk-MKWYLDFK.js.map} +0 -0
  169. /package/dist/{chunk-GZP4UGGM.js.map → chunk-ZM3CFL5L.js.map} +0 -0
  170. /package/dist/{prompt-ANTQWHUF.js.map → claude-GOP6PFC7.js.map} +0 -0
  171. /package/dist/{remote-GJEZWRCC.js.map → git-TDXKRTXM.js.map} +0 -0
  172. /package/dist/{terminal-3D6TUAKJ.js.map → neon-helpers-WPUACUVC.js.map} +0 -0
  173. /package/dist/{rebase-KBWFDZCN.js.map → rebase-Q7GMM7EI.js.map} +0 -0
  174. /package/dist/{test-git-MKZATGZN.js.map → test-git-3WDLNQCA.js.map} +0 -0
  175. /package/dist/{test-prefix-ZNLWDI3K.js.map → test-prefix-EVGAWAJW.js.map} +0 -0
  176. /package/dist/{test-tabs-JRKY3QMM.js.map → test-tabs-RXDBZ6J7.js.map} +0 -0
@@ -1,1355 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- MergeManager
4
- } from "./chunk-VVH3ANF2.js";
5
- import {
6
- ResourceCleanup
7
- } from "./chunk-Q2KYPAH2.js";
8
- import {
9
- IdentifierParser
10
- } from "./chunk-H4E4THUZ.js";
11
- import {
12
- ProcessManager
13
- } from "./chunk-SPYPLHMK.js";
14
- import {
15
- CLIIsolationManager,
16
- DatabaseManager,
17
- EnvironmentManager
18
- } from "./chunk-H5LDRGVK.js";
19
- import {
20
- loadEnvIntoProcess
21
- } from "./chunk-ZMNQBJUI.js";
22
- import {
23
- detectPackageManager,
24
- installDependencies,
25
- runScript
26
- } from "./chunk-BLCTGFZN.js";
27
- import {
28
- createNeonProviderFromSettings
29
- } from "./chunk-LAPY6NAE.js";
30
- import {
31
- ProjectCapabilityDetector
32
- } from "./chunk-CWR2SANQ.js";
33
- import {
34
- hasScript,
35
- readPackageJson
36
- } from "./chunk-2ZPFJQ3B.js";
37
- import {
38
- getConfiguredRepoFromSettings,
39
- hasMultipleRemotes
40
- } from "./chunk-FXV24OYZ.js";
41
- import {
42
- GitHubService
43
- } from "./chunk-ZWXJBSUW.js";
44
- import "./chunk-JXQXSC45.js";
45
- import {
46
- detectClaudeCli,
47
- launchClaude
48
- } from "./chunk-PXZBAC2M.js";
49
- import {
50
- GitWorktreeManager
51
- } from "./chunk-IO4WFTL2.js";
52
- import {
53
- SettingsManager
54
- } from "./chunk-VYQLLHZ7.js";
55
- import {
56
- executeGitCommand,
57
- findMainWorktreePathWithSettings
58
- } from "./chunk-KOCQAD2E.js";
59
- import "./chunk-JNKJ7NJV.js";
60
- import {
61
- logger
62
- } from "./chunk-GEHQXLEI.js";
63
-
64
- // src/lib/ValidationRunner.ts
65
- var ValidationRunner = class {
66
- /**
67
- * Run all validations in sequence: typecheck → lint → test
68
- * Fails fast on first error
69
- */
70
- async runValidations(worktreePath, options = {}) {
71
- const startTime = Date.now();
72
- const steps = [];
73
- if (!options.skipTypecheck) {
74
- const typecheckResult = await this.runTypecheck(
75
- worktreePath,
76
- options.dryRun ?? false
77
- );
78
- steps.push(typecheckResult);
79
- if (!typecheckResult.passed && !typecheckResult.skipped) {
80
- return {
81
- success: false,
82
- steps,
83
- totalDuration: Date.now() - startTime
84
- };
85
- }
86
- }
87
- if (!options.skipLint) {
88
- const lintResult = await this.runLint(worktreePath, options.dryRun ?? false);
89
- steps.push(lintResult);
90
- if (!lintResult.passed && !lintResult.skipped) {
91
- return { success: false, steps, totalDuration: Date.now() - startTime };
92
- }
93
- }
94
- if (!options.skipTests) {
95
- const testResult = await this.runTests(
96
- worktreePath,
97
- options.dryRun ?? false
98
- );
99
- steps.push(testResult);
100
- if (!testResult.passed && !testResult.skipped) {
101
- return { success: false, steps, totalDuration: Date.now() - startTime };
102
- }
103
- }
104
- return { success: true, steps, totalDuration: Date.now() - startTime };
105
- }
106
- /**
107
- * Run typecheck validation
108
- */
109
- async runTypecheck(worktreePath, dryRun) {
110
- const stepStartTime = Date.now();
111
- try {
112
- const pkgJson = await readPackageJson(worktreePath);
113
- const hasTypecheckScript = hasScript(pkgJson, "typecheck");
114
- if (!hasTypecheckScript) {
115
- logger.debug("Skipping typecheck - no typecheck script found");
116
- return {
117
- step: "typecheck",
118
- passed: true,
119
- skipped: true,
120
- duration: Date.now() - stepStartTime
121
- };
122
- }
123
- } catch (error) {
124
- if (error instanceof Error && error.message.includes("package.json not found")) {
125
- logger.debug("Skipping typecheck - no package.json found (non-Node.js project)");
126
- return {
127
- step: "typecheck",
128
- passed: true,
129
- skipped: true,
130
- duration: Date.now() - stepStartTime
131
- };
132
- }
133
- throw error;
134
- }
135
- const packageManager = await detectPackageManager(worktreePath);
136
- if (dryRun) {
137
- const command = packageManager === "npm" ? "npm run typecheck" : `${packageManager} typecheck`;
138
- logger.info(`[DRY RUN] Would run: ${command}`);
139
- return {
140
- step: "typecheck",
141
- passed: true,
142
- skipped: false,
143
- duration: Date.now() - stepStartTime
144
- };
145
- }
146
- logger.info("Running typecheck...");
147
- try {
148
- await runScript("typecheck", worktreePath, [], { quiet: true });
149
- logger.success("Typecheck passed");
150
- return {
151
- step: "typecheck",
152
- passed: true,
153
- skipped: false,
154
- duration: Date.now() - stepStartTime
155
- };
156
- } catch {
157
- const fixed = await this.attemptClaudeFix(
158
- "typecheck",
159
- worktreePath,
160
- packageManager
161
- );
162
- if (fixed) {
163
- return {
164
- step: "typecheck",
165
- passed: true,
166
- skipped: false,
167
- duration: Date.now() - stepStartTime
168
- };
169
- }
170
- const runCommand = packageManager === "npm" ? "npm run typecheck" : `${packageManager} typecheck`;
171
- throw new Error(
172
- `Error: Typecheck failed.
173
- Fix type errors before merging.
174
-
175
- Run '${runCommand}' to see detailed errors.`
176
- );
177
- }
178
- }
179
- /**
180
- * Run lint validation
181
- */
182
- async runLint(worktreePath, dryRun) {
183
- const stepStartTime = Date.now();
184
- try {
185
- const pkgJson = await readPackageJson(worktreePath);
186
- const hasLintScript = hasScript(pkgJson, "lint");
187
- if (!hasLintScript) {
188
- logger.debug("Skipping lint - no lint script found");
189
- return {
190
- step: "lint",
191
- passed: true,
192
- skipped: true,
193
- duration: Date.now() - stepStartTime
194
- };
195
- }
196
- } catch (error) {
197
- if (error instanceof Error && error.message.includes("package.json not found")) {
198
- logger.debug("Skipping lint - no package.json found (non-Node.js project)");
199
- return {
200
- step: "lint",
201
- passed: true,
202
- skipped: true,
203
- duration: Date.now() - stepStartTime
204
- };
205
- }
206
- throw error;
207
- }
208
- const packageManager = await detectPackageManager(worktreePath);
209
- if (dryRun) {
210
- const command = packageManager === "npm" ? "npm run lint" : `${packageManager} lint`;
211
- logger.info(`[DRY RUN] Would run: ${command}`);
212
- return {
213
- step: "lint",
214
- passed: true,
215
- skipped: false,
216
- duration: Date.now() - stepStartTime
217
- };
218
- }
219
- logger.info("Running lint...");
220
- try {
221
- await runScript("lint", worktreePath, [], { quiet: true });
222
- logger.success("Linting passed");
223
- return {
224
- step: "lint",
225
- passed: true,
226
- skipped: false,
227
- duration: Date.now() - stepStartTime
228
- };
229
- } catch {
230
- const fixed = await this.attemptClaudeFix(
231
- "lint",
232
- worktreePath,
233
- packageManager
234
- );
235
- if (fixed) {
236
- return {
237
- step: "lint",
238
- passed: true,
239
- skipped: false,
240
- duration: Date.now() - stepStartTime
241
- };
242
- }
243
- const runCommand = packageManager === "npm" ? "npm run lint" : `${packageManager} lint`;
244
- throw new Error(
245
- `Error: Linting failed.
246
- Fix linting errors before merging.
247
-
248
- Run '${runCommand}' to see detailed errors.`
249
- );
250
- }
251
- }
252
- /**
253
- * Run test validation
254
- */
255
- async runTests(worktreePath, dryRun) {
256
- const stepStartTime = Date.now();
257
- try {
258
- const pkgJson = await readPackageJson(worktreePath);
259
- const hasTestScript = hasScript(pkgJson, "test");
260
- if (!hasTestScript) {
261
- logger.debug("Skipping tests - no test script found");
262
- return {
263
- step: "test",
264
- passed: true,
265
- skipped: true,
266
- duration: Date.now() - stepStartTime
267
- };
268
- }
269
- } catch (error) {
270
- if (error instanceof Error && error.message.includes("package.json not found")) {
271
- logger.debug("Skipping tests - no package.json found (non-Node.js project)");
272
- return {
273
- step: "test",
274
- passed: true,
275
- skipped: true,
276
- duration: Date.now() - stepStartTime
277
- };
278
- }
279
- throw error;
280
- }
281
- const packageManager = await detectPackageManager(worktreePath);
282
- if (dryRun) {
283
- const command = packageManager === "npm" ? "npm run test" : `${packageManager} test`;
284
- logger.info(`[DRY RUN] Would run: ${command}`);
285
- return {
286
- step: "test",
287
- passed: true,
288
- skipped: false,
289
- duration: Date.now() - stepStartTime
290
- };
291
- }
292
- logger.info("Running tests...");
293
- try {
294
- await runScript("test", worktreePath, [], { quiet: true });
295
- logger.success("Tests passed");
296
- return {
297
- step: "test",
298
- passed: true,
299
- skipped: false,
300
- duration: Date.now() - stepStartTime
301
- };
302
- } catch {
303
- const fixed = await this.attemptClaudeFix(
304
- "test",
305
- worktreePath,
306
- packageManager
307
- );
308
- if (fixed) {
309
- return {
310
- step: "test",
311
- passed: true,
312
- skipped: false,
313
- duration: Date.now() - stepStartTime
314
- };
315
- }
316
- const runCommand = packageManager === "npm" ? "npm run test" : `${packageManager} test`;
317
- throw new Error(
318
- `Error: Tests failed.
319
- Fix test failures before merging.
320
-
321
- Run '${runCommand}' to see detailed errors.`
322
- );
323
- }
324
- }
325
- /**
326
- * Attempt to fix validation errors using Claude
327
- * Pattern based on MergeManager.attemptClaudeConflictResolution
328
- *
329
- * @param validationType - Type of validation that failed ('typecheck' | 'lint' | 'test')
330
- * @param worktreePath - Path to the worktree
331
- * @param packageManager - Detected package manager
332
- * @returns true if Claude fixed the issue, false otherwise
333
- */
334
- async attemptClaudeFix(validationType, worktreePath, packageManager) {
335
- const isClaudeAvailable = await detectClaudeCli();
336
- if (!isClaudeAvailable) {
337
- logger.debug("Claude CLI not available, skipping auto-fix");
338
- return false;
339
- }
340
- const validationCommand = this.getValidationCommand(validationType, packageManager);
341
- const prompt = this.getClaudePrompt(validationType, validationCommand);
342
- const validationTypeCapitalized = validationType.charAt(0).toUpperCase() + validationType.slice(1);
343
- logger.info(`Launching Claude to help fix ${validationTypeCapitalized} errors...`);
344
- try {
345
- await launchClaude(prompt, {
346
- addDir: worktreePath,
347
- headless: false,
348
- // Interactive mode
349
- permissionMode: "acceptEdits",
350
- // Auto-accept edits
351
- model: "sonnet"
352
- // Use Sonnet model
353
- });
354
- logger.info(`Re-running ${validationTypeCapitalized} after Claude's fixes...`);
355
- try {
356
- await runScript(validationType, worktreePath, [], { quiet: true });
357
- logger.success(`${validationTypeCapitalized} passed after Claude auto-fix`);
358
- return true;
359
- } catch {
360
- logger.warn(`${validationTypeCapitalized} still failing after Claude's help`);
361
- return false;
362
- }
363
- } catch (error) {
364
- logger.warn("Claude auto-fix failed", {
365
- error: error instanceof Error ? error.message : String(error)
366
- });
367
- return false;
368
- }
369
- }
370
- /**
371
- * Get validation command string for prompts
372
- */
373
- getValidationCommand(validationType, packageManager) {
374
- if (packageManager === "npm") {
375
- return `npm run ${validationType}`;
376
- }
377
- return `${packageManager} ${validationType}`;
378
- }
379
- /**
380
- * Get Claude prompt for specific validation type
381
- * Matches bash script prompts exactly
382
- */
383
- getClaudePrompt(validationType, validationCommand) {
384
- switch (validationType) {
385
- case "typecheck":
386
- return `There are TypeScript errors in this codebase. Please analyze the typecheck output, identify all type errors, and fix them. Run '${validationCommand}' to see the errors, then make the necessary code changes to resolve all type issues. When you are done, tell the user to quit using /exit to continue the validation process.`;
387
- case "lint":
388
- return `There are ESLint errors in this codebase. Please analyze the linting output, identify all linting issues, and fix them. Run '${validationCommand}' to see the errors, then make the necessary code changes to resolve all linting issues. Focus on code quality, consistency, and following the project's linting rules. When you are done, tell the user to quit using /exit to continue the validation process.`;
389
- case "test":
390
- return `There are unit test failures in this codebase. Please analyze the test output to understand what's failing, then fix the issues. This might involve updating test code, fixing bugs in the source code, or updating tests to match new behavior. Run '${validationCommand}' to see the detailed test failures, then make the necessary changes to get all tests passing. When you are done, tell the user to quit using /exit to continue the validation process.`;
391
- }
392
- }
393
- };
394
-
395
- // src/lib/CommitManager.ts
396
- var CommitManager = class {
397
- /**
398
- * Detect uncommitted changes in a worktree
399
- * Parses git status --porcelain output into structured GitStatus
400
- */
401
- async detectUncommittedChanges(worktreePath) {
402
- const porcelainOutput = await executeGitCommand(["status", "--porcelain"], {
403
- cwd: worktreePath
404
- });
405
- const { stagedFiles, unstagedFiles } = this.parseGitStatus(porcelainOutput);
406
- const currentBranch = await executeGitCommand(["branch", "--show-current"], {
407
- cwd: worktreePath
408
- });
409
- return {
410
- hasUncommittedChanges: stagedFiles.length > 0 || unstagedFiles.length > 0,
411
- unstagedFiles,
412
- stagedFiles,
413
- currentBranch: currentBranch.trim(),
414
- // Defer these to future enhancement
415
- isAheadOfRemote: false,
416
- isBehindRemote: false
417
- };
418
- }
419
- /**
420
- * Stage all changes and commit with Claude-generated or simple message
421
- * Tries Claude first, falls back to simple message if Claude unavailable or fails
422
- */
423
- async commitChanges(worktreePath, options) {
424
- if (options.dryRun) {
425
- logger.info("[DRY RUN] Would run: git add -A");
426
- logger.info("[DRY RUN] Would generate commit message with Claude (if available)");
427
- const fallbackMessage = this.generateFallbackMessage(options);
428
- const verifyFlag = options.skipVerify ? " --no-verify" : "";
429
- logger.info(`[DRY RUN] Would commit with message${verifyFlag}: ${fallbackMessage}`);
430
- return;
431
- }
432
- await executeGitCommand(["add", "-A"], { cwd: worktreePath });
433
- let message = null;
434
- if (!options.message) {
435
- try {
436
- message = await this.generateClaudeCommitMessage(worktreePath, options.issueNumber);
437
- } catch (error) {
438
- logger.debug("Claude commit message generation failed, using fallback", { error });
439
- }
440
- }
441
- message ??= this.generateFallbackMessage(options);
442
- if (options.skipVerify) {
443
- logger.warn("\u26A0\uFE0F Skipping pre-commit hooks (--no-verify configured in settings)");
444
- }
445
- try {
446
- if (options.noReview || options.message) {
447
- const commitArgs = ["commit", "-m", message];
448
- if (options.skipVerify) {
449
- commitArgs.push("--no-verify");
450
- }
451
- await executeGitCommand(commitArgs, { cwd: worktreePath });
452
- } else {
453
- logger.info("Opening git editor for commit message review...");
454
- const commitArgs = ["commit", "-e", "-m", message];
455
- if (options.skipVerify) {
456
- commitArgs.push("--no-verify");
457
- }
458
- await executeGitCommand(commitArgs, {
459
- cwd: worktreePath,
460
- stdio: "inherit",
461
- timeout: 3e5
462
- // 5 minutes for interactive editing
463
- });
464
- }
465
- } catch (error) {
466
- if (error instanceof Error && error.message.includes("nothing to commit")) {
467
- logger.info("No changes to commit");
468
- return;
469
- }
470
- throw error;
471
- }
472
- }
473
- /**
474
- * Generate simple fallback commit message when Claude unavailable
475
- * Used as fallback for Claude-powered commit messages
476
- */
477
- generateFallbackMessage(options) {
478
- if (options.message) {
479
- return options.message;
480
- }
481
- if (options.issueNumber) {
482
- return `WIP: Auto-commit for issue #${options.issueNumber}
483
-
484
- Fixes #${options.issueNumber}`;
485
- } else {
486
- return "WIP: Auto-commit uncommitted changes";
487
- }
488
- }
489
- /**
490
- * Parse git status --porcelain output
491
- * Format: "XY filename" where X=index, Y=worktree
492
- * Examples:
493
- * "M file.ts" - staged modification
494
- * " M file.ts" - unstaged modification
495
- * "MM file.ts" - both staged and unstaged
496
- * "?? file.ts" - untracked
497
- */
498
- parseGitStatus(porcelainOutput) {
499
- const stagedFiles = [];
500
- const unstagedFiles = [];
501
- if (!porcelainOutput.trim()) {
502
- return { stagedFiles, unstagedFiles };
503
- }
504
- const lines = porcelainOutput.split("\n").filter((line) => line.trim());
505
- for (const line of lines) {
506
- if (line.length < 3) continue;
507
- const indexStatus = line[0];
508
- const worktreeStatus = line[1];
509
- const filename = line.substring(3);
510
- if (indexStatus !== " " && indexStatus !== "?") {
511
- stagedFiles.push(filename);
512
- }
513
- if (worktreeStatus !== " " || line.startsWith("??")) {
514
- unstagedFiles.push(filename);
515
- }
516
- }
517
- return { stagedFiles, unstagedFiles };
518
- }
519
- /**
520
- * Generate commit message using Claude AI
521
- * Claude examines the git repository directly via --add-dir option
522
- * Returns null if Claude unavailable or fails validation
523
- */
524
- async generateClaudeCommitMessage(worktreePath, issueNumber) {
525
- const startTime = Date.now();
526
- logger.info("Starting Claude commit message generation...", {
527
- worktreePath: worktreePath.split("/").pop(),
528
- // Just show the folder name for privacy
529
- issueNumber
530
- });
531
- logger.debug("Checking Claude CLI availability...");
532
- const isClaudeAvailable = await detectClaudeCli();
533
- if (!isClaudeAvailable) {
534
- logger.info("Claude CLI not available, skipping Claude commit message generation");
535
- return null;
536
- }
537
- logger.debug("Claude CLI is available");
538
- logger.debug("Building commit message prompt...");
539
- const prompt = this.buildCommitMessagePrompt(issueNumber);
540
- logger.debug("Prompt built", { promptLength: prompt.length });
541
- logger.debug("Claude prompt content:", {
542
- prompt,
543
- truncatedPreview: prompt.substring(0, 500) + (prompt.length > 500 ? "...[truncated]" : "")
544
- });
545
- try {
546
- logger.info("Calling Claude CLI for commit message generation...");
547
- const claudeStartTime = Date.now();
548
- const claudeOptions = {
549
- headless: true,
550
- addDir: worktreePath,
551
- model: "claude-haiku-4-5-20251001",
552
- // Fast, cost-effective model
553
- timeout: 12e4
554
- // 120 second timeout
555
- };
556
- logger.debug("Claude CLI call parameters:", {
557
- options: claudeOptions,
558
- worktreePathForAnalysis: worktreePath,
559
- addDirContents: "Will include entire worktree directory for analysis"
560
- });
561
- const result = await launchClaude(prompt, claudeOptions);
562
- const claudeDuration = Date.now() - claudeStartTime;
563
- logger.debug("Claude API call completed", { duration: `${claudeDuration}ms` });
564
- if (typeof result !== "string") {
565
- logger.warn("Claude returned non-string result", { resultType: typeof result });
566
- return null;
567
- }
568
- logger.debug("Raw Claude output received", {
569
- outputLength: result.length,
570
- preview: result.substring(0, 200) + (result.length > 200 ? "..." : "")
571
- });
572
- logger.debug("Sanitizing Claude output...");
573
- const sanitized = this.sanitizeClaudeOutput(result);
574
- logger.debug("Output sanitized", {
575
- originalLength: result.length,
576
- sanitizedLength: sanitized.length,
577
- sanitized: sanitized.substring(0, 200) + (sanitized.length > 200 ? "..." : "")
578
- });
579
- if (!sanitized) {
580
- logger.warn("Claude returned empty message after sanitization");
581
- return null;
582
- }
583
- let finalMessage = sanitized;
584
- if (issueNumber) {
585
- if (!finalMessage.includes(`Fixes #${issueNumber}`)) {
586
- finalMessage = `${finalMessage}
587
-
588
- Fixes #${issueNumber}`;
589
- logger.debug(`Added "Fixes #${issueNumber}" trailer to commit message`);
590
- } else {
591
- logger.debug(`"Fixes #${issueNumber}" already present in commit message`);
592
- }
593
- }
594
- const totalDuration = Date.now() - startTime;
595
- logger.info("Claude commit message generated successfully", {
596
- message: finalMessage,
597
- totalDuration: `${totalDuration}ms`,
598
- claudeApiDuration: `${claudeDuration}ms`
599
- });
600
- return finalMessage;
601
- } catch (error) {
602
- const totalDuration = Date.now() - startTime;
603
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
604
- if (errorMessage.includes("timed out") || errorMessage.includes("timeout")) {
605
- logger.warn("Claude commit message generation timed out after 45 seconds", {
606
- totalDuration: `${totalDuration}ms`,
607
- worktreePath: worktreePath.split("/").pop()
608
- });
609
- } else {
610
- logger.warn("Failed to generate commit message with Claude", {
611
- error: errorMessage,
612
- totalDuration: `${totalDuration}ms`,
613
- worktreePath: worktreePath.split("/").pop()
614
- });
615
- }
616
- return null;
617
- }
618
- }
619
- /**
620
- * Build structured XML prompt for commit message generation
621
- * Uses XML format for clear task definition and output expectations
622
- */
623
- buildCommitMessagePrompt(issueNumber) {
624
- const issueContext = issueNumber ? `
625
- <IssueContext>
626
- This commit is associated with GitHub issue #${issueNumber}.
627
- If the changes appear to resolve the issue, include "Fixes #${issueNumber}" at the end of the first line of commit message.
628
- </IssueContext>` : "";
629
- return `<Task>
630
- You are a software engineer writing a commit message for this repository.
631
- Examine the staged changes in the git repository and generate a concise, meaningful commit message.
632
- </Task>
633
-
634
- <Requirements>
635
- <Format>The first line must be a brief summary of the changes made as a full sentence. If it references an issue, include "Fixes #N" at the end of this line.
636
-
637
- Add 2 newlines, then add a bullet-point form description of the changes made, each change on a new line.</Format>
638
- <Mood>Use imperative mood (e.g., "Add feature" not "Added feature")</Mood>
639
- <Focus>Be specific about what was changed and why</Focus>
640
- <Conciseness>Keep message under 72 characters for subject line when possible</Conciseness>
641
- <NoMeta>CRITICAL: Do NOT include ANY explanatory text, analysis, or meta-commentary. Output ONLY the raw commit message.</NoMeta>
642
- <Examples>
643
- Good: "Add user authentication with JWT tokens. Fixes #42
644
-
645
- - Implement login and registration endpoints
646
- - Secure routes with JWT middleware
647
- - Update user model to store hashed passwords"
648
- Good: "Fix navigation bug in sidebar menu."
649
- Bad: "Based on the changes, I'll create: Add user authentication"
650
- Bad: "Looking at the files, this commit should be: Fix navigation bug"
651
- </Examples>
652
- ${issueContext}
653
- </Requirements>
654
-
655
- <Output>
656
- IMPORTANT: Your entire response will be used directly as the git commit message.
657
- Do not include any explanatory text before or after the commit message.
658
- Start your response immediately with the commit message text.
659
- </Output>`;
660
- }
661
- /**
662
- * Sanitize Claude output to remove meta-commentary and clean formatting
663
- * Handles cases where Claude includes explanatory text despite instructions
664
- */
665
- sanitizeClaudeOutput(rawOutput) {
666
- let cleaned = rawOutput.trim();
667
- const metaPatterns = [
668
- /^.*?based on.*?changes.*?:/i,
669
- /^.*?looking at.*?files.*?:/i,
670
- /^.*?examining.*?:/i,
671
- /^.*?analyzing.*?:/i,
672
- /^.*?i'll.*?generate.*?:/i,
673
- /^.*?let me.*?:/i,
674
- /^.*?the commit message.*?should be.*?:/i,
675
- /^.*?here.*?is.*?commit.*?message.*?:/i
676
- ];
677
- for (const pattern of metaPatterns) {
678
- cleaned = cleaned.replace(pattern, "").trim();
679
- }
680
- if (cleaned.includes(":")) {
681
- const colonIndex = cleaned.indexOf(":");
682
- const beforeColon = cleaned.substring(0, colonIndex).trim().toLowerCase();
683
- const metaIndicators = [
684
- "here is the commit message",
685
- "commit message",
686
- "here is",
687
- "the message should be",
688
- "i suggest",
689
- "my suggestion"
690
- ];
691
- const isMetaCommentary = metaIndicators.some((indicator) => beforeColon.includes(indicator));
692
- if (isMetaCommentary) {
693
- const afterColon = cleaned.substring(colonIndex + 1).trim();
694
- if (afterColon && afterColon.length > 10) {
695
- cleaned = afterColon;
696
- }
697
- }
698
- }
699
- if (cleaned.startsWith('"') && cleaned.endsWith('"') || cleaned.startsWith("'") && cleaned.endsWith("'")) {
700
- cleaned = cleaned.slice(1, -1).trim();
701
- }
702
- return cleaned;
703
- }
704
- };
705
-
706
- // src/lib/BuildRunner.ts
707
- var BuildRunner = class {
708
- constructor(capabilityDetector) {
709
- this.capabilityDetector = capabilityDetector ?? new ProjectCapabilityDetector();
710
- }
711
- /**
712
- * Run build verification in the specified directory
713
- * @param buildPath - Path where build should run (typically main worktree path)
714
- * @param options - Build options
715
- */
716
- async runBuild(buildPath, options = {}) {
717
- const startTime = Date.now();
718
- try {
719
- const pkgJson = await readPackageJson(buildPath);
720
- const hasBuildScript = hasScript(pkgJson, "build");
721
- if (!hasBuildScript) {
722
- logger.debug("Skipping build - no build script found");
723
- return {
724
- success: true,
725
- skipped: true,
726
- reason: "No build script found in package.json",
727
- duration: Date.now() - startTime
728
- };
729
- }
730
- } catch (error) {
731
- if (error instanceof Error && error.message.includes("package.json not found")) {
732
- logger.debug("Skipping build - no package.json found (non-Node.js project)");
733
- return {
734
- success: true,
735
- skipped: true,
736
- reason: "No package.json found in project",
737
- duration: Date.now() - startTime
738
- };
739
- }
740
- throw error;
741
- }
742
- const capabilities = await this.capabilityDetector.detectCapabilities(buildPath);
743
- const isCLIProject = capabilities.capabilities.includes("cli");
744
- if (!isCLIProject) {
745
- logger.debug("Skipping build - not a CLI project (no bin field)");
746
- return {
747
- success: true,
748
- skipped: true,
749
- reason: "Project is not a CLI project (no bin field in package.json)",
750
- duration: Date.now() - startTime
751
- };
752
- }
753
- const packageManager = await detectPackageManager(buildPath);
754
- if (options.dryRun) {
755
- const command = packageManager === "npm" ? "npm run build" : `${packageManager} build`;
756
- logger.info(`[DRY RUN] Would run: ${command}`);
757
- return {
758
- success: true,
759
- skipped: false,
760
- duration: Date.now() - startTime
761
- };
762
- }
763
- logger.info("Running build...");
764
- try {
765
- await runScript("build", buildPath, [], { quiet: true });
766
- logger.success("Build completed successfully");
767
- return {
768
- success: true,
769
- skipped: false,
770
- duration: Date.now() - startTime
771
- };
772
- } catch {
773
- const runCommand = packageManager === "npm" ? "npm run build" : `${packageManager} build`;
774
- throw new Error(
775
- `Error: Build failed.
776
- Fix build errors before proceeding.
777
-
778
- Run '${runCommand}' to see detailed errors.`
779
- );
780
- }
781
- }
782
- };
783
-
784
- // src/commands/finish.ts
785
- import path from "path";
786
- var FinishCommand = class {
787
- constructor(gitHubService, gitWorktreeManager, validationRunner, commitManager, mergeManager, identifierParser, resourceCleanup, buildRunner, settingsManager) {
788
- const envResult = loadEnvIntoProcess();
789
- if (envResult.error) {
790
- logger.debug(`Environment loading warning: ${envResult.error.message}`);
791
- }
792
- if (envResult.parsed) {
793
- logger.debug(`Loaded ${Object.keys(envResult.parsed).length} environment variables`);
794
- }
795
- this.gitHubService = gitHubService ?? new GitHubService();
796
- this.gitWorktreeManager = gitWorktreeManager ?? new GitWorktreeManager();
797
- this.validationRunner = validationRunner ?? new ValidationRunner();
798
- this.commitManager = commitManager ?? new CommitManager();
799
- this.mergeManager = mergeManager ?? new MergeManager();
800
- this.identifierParser = identifierParser ?? new IdentifierParser(this.gitWorktreeManager);
801
- this.settingsManager = settingsManager ?? new SettingsManager();
802
- if (resourceCleanup) {
803
- this.resourceCleanup = resourceCleanup;
804
- }
805
- this.buildRunner = buildRunner ?? new BuildRunner();
806
- }
807
- /**
808
- * Lazy initialization of ResourceCleanup with properly configured DatabaseManager
809
- */
810
- async ensureResourceCleanup() {
811
- var _a, _b;
812
- if (this.resourceCleanup) {
813
- return;
814
- }
815
- const settings = await this.settingsManager.loadSettings();
816
- const databaseUrlEnvVarName = ((_b = (_a = settings.capabilities) == null ? void 0 : _a.database) == null ? void 0 : _b.databaseUrlEnvVarName) ?? "DATABASE_URL";
817
- const environmentManager = new EnvironmentManager();
818
- const neonProvider = createNeonProviderFromSettings(settings);
819
- const databaseManager = new DatabaseManager(neonProvider, environmentManager, databaseUrlEnvVarName);
820
- const cliIsolationManager = new CLIIsolationManager();
821
- this.resourceCleanup = new ResourceCleanup(
822
- this.gitWorktreeManager,
823
- new ProcessManager(),
824
- databaseManager,
825
- cliIsolationManager
826
- );
827
- }
828
- /**
829
- * Main entry point for finish command
830
- */
831
- async execute(input) {
832
- try {
833
- const settings = await this.settingsManager.loadSettings();
834
- let repo;
835
- const multipleRemotes = await hasMultipleRemotes();
836
- if (multipleRemotes) {
837
- repo = await getConfiguredRepoFromSettings(settings);
838
- logger.info(`Using GitHub repository: ${repo}`);
839
- }
840
- const parsed = await this.parseInput(input.identifier, input.options);
841
- const worktrees = await this.validateInput(parsed, input.options, repo);
842
- logger.info(`Validated input: ${this.formatParsedInput(parsed)}`);
843
- const worktree = worktrees[0];
844
- if (!worktree) {
845
- throw new Error("No worktree found");
846
- }
847
- if (parsed.type === "pr") {
848
- if (!parsed.number) {
849
- throw new Error("Invalid PR number");
850
- }
851
- const pr = await this.gitHubService.fetchPR(parsed.number, repo);
852
- await this.executePRWorkflow(parsed, input.options, worktree, pr);
853
- } else {
854
- await this.executeIssueWorkflow(parsed, input.options, worktree);
855
- }
856
- } catch (error) {
857
- if (error instanceof Error) {
858
- logger.error(`${error.message}`);
859
- } else {
860
- logger.error("An unknown error occurred");
861
- }
862
- throw error;
863
- }
864
- }
865
- /**
866
- * Parse input to determine type and extract relevant data
867
- * Supports auto-detection from current directory when identifier is undefined
868
- */
869
- async parseInput(identifier, options) {
870
- if (options.pr !== void 0) {
871
- return {
872
- type: "pr",
873
- number: options.pr,
874
- originalInput: `--pr ${options.pr}`,
875
- autoDetected: false
876
- };
877
- }
878
- if (identifier == null ? void 0 : identifier.trim()) {
879
- return await this.parseExplicitInput(identifier.trim());
880
- }
881
- return await this.autoDetectFromCurrentDirectory();
882
- }
883
- /**
884
- * Parse explicit identifier input using pattern-based detection
885
- * (No GitHub API calls - uses IdentifierParser)
886
- */
887
- async parseExplicitInput(identifier) {
888
- const prPattern = /^(?:pr|PR)[/-](\d+)$/;
889
- const prMatch = identifier.match(prPattern);
890
- if (prMatch == null ? void 0 : prMatch[1]) {
891
- return {
892
- type: "pr",
893
- number: parseInt(prMatch[1], 10),
894
- originalInput: identifier,
895
- autoDetected: false
896
- };
897
- }
898
- const parsed = await this.identifierParser.parseForPatternDetection(identifier);
899
- if (parsed.type === "description") {
900
- throw new Error("Description input type is not supported in finish command");
901
- }
902
- const result = {
903
- type: parsed.type,
904
- originalInput: parsed.originalInput,
905
- autoDetected: false
906
- };
907
- if (parsed.number !== void 0) {
908
- result.number = parsed.number;
909
- }
910
- if (parsed.branchName !== void 0) {
911
- result.branchName = parsed.branchName;
912
- }
913
- return result;
914
- }
915
- /**
916
- * Auto-detect PR or issue from current directory
917
- * Ports logic from merge-current-issue.sh lines 30-52
918
- */
919
- async autoDetectFromCurrentDirectory() {
920
- const currentDir = path.basename(process.cwd());
921
- const prPattern = /_pr_(\d+)$/;
922
- const prMatch = currentDir.match(prPattern);
923
- if (prMatch == null ? void 0 : prMatch[1]) {
924
- const prNumber = parseInt(prMatch[1], 10);
925
- logger.debug(`Auto-detected PR #${prNumber} from directory: ${currentDir}`);
926
- return {
927
- type: "pr",
928
- number: prNumber,
929
- originalInput: currentDir,
930
- autoDetected: true
931
- };
932
- }
933
- const issuePattern = /issue-(\d+)/;
934
- const issueMatch = currentDir.match(issuePattern);
935
- if (issueMatch == null ? void 0 : issueMatch[1]) {
936
- const issueNumber = parseInt(issueMatch[1], 10);
937
- logger.debug(
938
- `Auto-detected issue #${issueNumber} from directory: ${currentDir}`
939
- );
940
- return {
941
- type: "issue",
942
- number: issueNumber,
943
- originalInput: currentDir,
944
- autoDetected: true
945
- };
946
- }
947
- const repoInfo = await this.gitWorktreeManager.getRepoInfo();
948
- const currentBranch = repoInfo.currentBranch;
949
- if (!currentBranch) {
950
- throw new Error(
951
- "Could not auto-detect identifier. Please provide an issue number, PR number, or branch name.\nExpected directory pattern: feat/issue-XX-description OR worktree with _pr_N suffix"
952
- );
953
- }
954
- const branchIssueMatch = currentBranch.match(issuePattern);
955
- if (branchIssueMatch == null ? void 0 : branchIssueMatch[1]) {
956
- const issueNumber = parseInt(branchIssueMatch[1], 10);
957
- logger.debug(
958
- `Auto-detected issue #${issueNumber} from branch: ${currentBranch}`
959
- );
960
- return {
961
- type: "issue",
962
- number: issueNumber,
963
- originalInput: currentBranch,
964
- autoDetected: true
965
- };
966
- }
967
- return {
968
- type: "branch",
969
- branchName: currentBranch,
970
- originalInput: currentBranch,
971
- autoDetected: true
972
- };
973
- }
974
- /**
975
- * Validate the parsed input based on its type
976
- */
977
- async validateInput(parsed, options, repo) {
978
- switch (parsed.type) {
979
- case "pr": {
980
- if (!parsed.number) {
981
- throw new Error("Invalid PR number");
982
- }
983
- const pr = await this.gitHubService.fetchPR(parsed.number);
984
- logger.debug(`Validated PR #${parsed.number} (state: ${pr.state})`);
985
- return await this.findWorktreeForIdentifier(parsed);
986
- }
987
- case "issue": {
988
- if (!parsed.number) {
989
- throw new Error("Invalid issue number");
990
- }
991
- const issue = await this.gitHubService.fetchIssue(parsed.number, repo);
992
- if (issue.state === "closed" && !options.force) {
993
- throw new Error(
994
- `Issue #${parsed.number} is closed. Use --force to finish anyway.`
995
- );
996
- }
997
- logger.debug(`Validated issue #${parsed.number} (state: ${issue.state})`);
998
- return await this.findWorktreeForIdentifier(parsed);
999
- }
1000
- case "branch": {
1001
- if (!parsed.branchName) {
1002
- throw new Error("Invalid branch name");
1003
- }
1004
- if (!this.isValidBranchName(parsed.branchName)) {
1005
- throw new Error(
1006
- "Invalid branch name. Use only letters, numbers, hyphens, underscores, and slashes"
1007
- );
1008
- }
1009
- logger.debug(`Validated branch name: ${parsed.branchName}`);
1010
- return await this.findWorktreeForIdentifier(parsed);
1011
- }
1012
- default: {
1013
- const unknownType = parsed;
1014
- throw new Error(`Unknown input type: ${unknownType.type}`);
1015
- }
1016
- }
1017
- }
1018
- /**
1019
- * Find worktree for the given identifier using specific methods based on type
1020
- * (uses precise pattern matching instead of broad substring matching)
1021
- * Throws error if not found
1022
- */
1023
- async findWorktreeForIdentifier(parsed) {
1024
- let worktree = null;
1025
- switch (parsed.type) {
1026
- case "pr": {
1027
- if (!parsed.number) {
1028
- throw new Error("Invalid PR number");
1029
- }
1030
- worktree = await this.gitWorktreeManager.findWorktreeForPR(
1031
- parsed.number,
1032
- ""
1033
- );
1034
- break;
1035
- }
1036
- case "issue": {
1037
- if (!parsed.number) {
1038
- throw new Error("Invalid issue number");
1039
- }
1040
- worktree = await this.gitWorktreeManager.findWorktreeForIssue(
1041
- parsed.number
1042
- );
1043
- break;
1044
- }
1045
- case "branch": {
1046
- if (!parsed.branchName) {
1047
- throw new Error("Invalid branch name");
1048
- }
1049
- worktree = await this.gitWorktreeManager.findWorktreeForBranch(
1050
- parsed.branchName
1051
- );
1052
- break;
1053
- }
1054
- default: {
1055
- const unknownType = parsed;
1056
- throw new Error(`Unknown input type: ${unknownType.type}`);
1057
- }
1058
- }
1059
- if (!worktree) {
1060
- throw new Error(
1061
- `No worktree found for ${this.formatParsedInput(parsed)}. Use 'il list' to see available worktrees.`
1062
- );
1063
- }
1064
- logger.debug(`Found worktree: ${worktree.path}`);
1065
- return [worktree];
1066
- }
1067
- /**
1068
- * Validate branch name format
1069
- */
1070
- isValidBranchName(branch) {
1071
- return /^[a-zA-Z0-9/_-]+$/.test(branch);
1072
- }
1073
- /**
1074
- * Format parsed input for display
1075
- */
1076
- formatParsedInput(parsed) {
1077
- const autoLabel = parsed.autoDetected ? " (auto-detected)" : "";
1078
- switch (parsed.type) {
1079
- case "pr":
1080
- return `PR #${parsed.number}${autoLabel}`;
1081
- case "issue":
1082
- return `Issue #${parsed.number}${autoLabel}`;
1083
- case "branch":
1084
- return `Branch '${parsed.branchName}'${autoLabel}`;
1085
- default:
1086
- return "Unknown input";
1087
- }
1088
- }
1089
- /**
1090
- * Execute workflow for issues and branches (merge into main)
1091
- * This is the traditional workflow: validate → commit → rebase → merge → cleanup
1092
- */
1093
- async executeIssueWorkflow(parsed, options, worktree) {
1094
- var _a, _b;
1095
- if (!options.dryRun) {
1096
- logger.info("Running pre-merge validations...");
1097
- await this.validationRunner.runValidations(worktree.path, {
1098
- dryRun: options.dryRun ?? false
1099
- });
1100
- logger.success("All validations passed");
1101
- } else {
1102
- logger.info("[DRY RUN] Would run pre-merge validations");
1103
- }
1104
- const gitStatus = await this.commitManager.detectUncommittedChanges(worktree.path);
1105
- if (gitStatus.hasUncommittedChanges) {
1106
- if (options.dryRun) {
1107
- logger.info("[DRY RUN] Would auto-commit uncommitted changes (validation passed)");
1108
- } else {
1109
- logger.info("Validation passed, auto-committing uncommitted changes...");
1110
- const settings = await this.settingsManager.loadSettings(worktree.path);
1111
- const skipVerify = ((_b = (_a = settings.workflows) == null ? void 0 : _a.issue) == null ? void 0 : _b.noVerify) ?? false;
1112
- const commitOptions = {
1113
- dryRun: options.dryRun ?? false,
1114
- skipVerify
1115
- };
1116
- if (parsed.type === "issue" && parsed.number) {
1117
- commitOptions.issueNumber = parsed.number;
1118
- }
1119
- await this.commitManager.commitChanges(worktree.path, commitOptions);
1120
- logger.success("Changes committed successfully");
1121
- }
1122
- } else {
1123
- logger.debug("No uncommitted changes found");
1124
- }
1125
- logger.info("Rebasing branch on main...");
1126
- const mergeOptions = {
1127
- dryRun: options.dryRun ?? false,
1128
- force: options.force ?? false
1129
- };
1130
- await this.mergeManager.rebaseOnMain(worktree.path, mergeOptions);
1131
- logger.success("Branch rebased successfully");
1132
- logger.info("Performing fast-forward merge...");
1133
- await this.mergeManager.performFastForwardMerge(worktree.branch, worktree.path, mergeOptions);
1134
- logger.success("Fast-forward merge completed successfully");
1135
- if (options.dryRun) {
1136
- logger.info("[DRY RUN] Would install dependencies in main worktree");
1137
- } else {
1138
- logger.info("Installing dependencies in main worktree...");
1139
- const mainWorktreePath = await findMainWorktreePathWithSettings(worktree.path, this.settingsManager);
1140
- await installDependencies(mainWorktreePath, true);
1141
- }
1142
- if (!options.skipBuild) {
1143
- await this.runPostMergeBuild(worktree.path, options);
1144
- } else {
1145
- logger.debug("Skipping build verification (--skip-build flag provided)");
1146
- }
1147
- await this.performPostMergeCleanup(parsed, options, worktree);
1148
- }
1149
- /**
1150
- * Execute workflow for Pull Requests
1151
- * Behavior depends on PR state:
1152
- * - OPEN: Commit changes, push to remote, keep worktree active
1153
- * - CLOSED/MERGED: Skip to cleanup
1154
- */
1155
- async executePRWorkflow(parsed, options, worktree, pr) {
1156
- var _a, _b;
1157
- if (pr.state === "closed" || pr.state === "merged") {
1158
- logger.info(`PR #${parsed.number} is ${pr.state.toUpperCase()} - skipping to cleanup`);
1159
- const gitStatus = await this.commitManager.detectUncommittedChanges(worktree.path);
1160
- if (gitStatus.hasUncommittedChanges && !options.force) {
1161
- logger.warn("PR has uncommitted changes");
1162
- throw new Error(
1163
- "Cannot cleanup PR with uncommitted changes. Commit or stash changes, then run again with --force to cleanup anyway."
1164
- );
1165
- }
1166
- await this.performPRCleanup(parsed, options, worktree);
1167
- logger.success(`PR #${parsed.number} cleanup completed`);
1168
- } else {
1169
- logger.info(`PR #${parsed.number} is OPEN - will push changes and keep worktree active`);
1170
- const gitStatus = await this.commitManager.detectUncommittedChanges(worktree.path);
1171
- if (gitStatus.hasUncommittedChanges) {
1172
- if (options.dryRun) {
1173
- logger.info("[DRY RUN] Would commit uncommitted changes");
1174
- } else {
1175
- logger.info("Committing uncommitted changes...");
1176
- const settings = await this.settingsManager.loadSettings(worktree.path);
1177
- const skipVerify = ((_b = (_a = settings.workflows) == null ? void 0 : _a.pr) == null ? void 0 : _b.noVerify) ?? false;
1178
- await this.commitManager.commitChanges(worktree.path, {
1179
- dryRun: false,
1180
- skipVerify
1181
- // Do NOT pass issueNumber for PRs - no "Fixes #" trailer needed
1182
- });
1183
- logger.success("Changes committed");
1184
- }
1185
- } else {
1186
- logger.debug("No uncommitted changes found");
1187
- }
1188
- if (options.dryRun) {
1189
- logger.info(`[DRY RUN] Would push changes to origin/${pr.branch}`);
1190
- } else {
1191
- logger.info("Pushing changes to remote...");
1192
- const { pushBranchToRemote } = await import("./git-OUYMVYJX.js");
1193
- await pushBranchToRemote(pr.branch, worktree.path, {
1194
- dryRun: false
1195
- });
1196
- logger.success(`Changes pushed to PR #${parsed.number}`);
1197
- }
1198
- logger.success(`PR #${parsed.number} updated successfully`);
1199
- logger.info("Worktree remains active for continued work");
1200
- logger.info(`To cleanup when done: il cleanup ${parsed.number}`);
1201
- }
1202
- }
1203
- /**
1204
- * Perform cleanup for closed/merged PRs
1205
- * Similar to performPostMergeCleanup but with different messaging
1206
- */
1207
- async performPRCleanup(parsed, options, worktree) {
1208
- const cleanupInput = {
1209
- type: parsed.type,
1210
- originalInput: parsed.originalInput,
1211
- ...parsed.number !== void 0 && { number: parsed.number },
1212
- ...parsed.branchName !== void 0 && { branchName: parsed.branchName }
1213
- };
1214
- const cleanupOptions = {
1215
- dryRun: options.dryRun ?? false,
1216
- deleteBranch: true,
1217
- // Delete branch for closed/merged PRs
1218
- keepDatabase: false,
1219
- force: options.force ?? false
1220
- };
1221
- try {
1222
- await this.ensureResourceCleanup();
1223
- if (!this.resourceCleanup) {
1224
- throw new Error("Failed to initialize ResourceCleanup");
1225
- }
1226
- const result = await this.resourceCleanup.cleanupWorktree(cleanupInput, cleanupOptions);
1227
- this.reportCleanupResults(result);
1228
- if (!result.success) {
1229
- logger.warn("Some cleanup operations failed - manual cleanup may be required");
1230
- this.showManualCleanupInstructions(worktree);
1231
- } else {
1232
- if (this.isRunningFromWithinWorktree(worktree.path)) {
1233
- this.showTerminalCloseWarning(worktree);
1234
- }
1235
- }
1236
- } catch (error) {
1237
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1238
- logger.warn(`Cleanup failed: ${errorMessage}`);
1239
- this.showManualCleanupInstructions(worktree);
1240
- throw error;
1241
- }
1242
- }
1243
- /**
1244
- * Run post-merge build verification for CLI projects
1245
- * Runs in main worktree to verify merged code builds successfully
1246
- */
1247
- async runPostMergeBuild(worktreePath, options) {
1248
- const mainWorktreePath = await findMainWorktreePathWithSettings(worktreePath, this.settingsManager);
1249
- if (options.dryRun) {
1250
- logger.info("[DRY RUN] Would run post-merge build");
1251
- return;
1252
- }
1253
- logger.info("Running post-merge build...");
1254
- const result = await this.buildRunner.runBuild(mainWorktreePath, {
1255
- dryRun: options.dryRun ?? false
1256
- });
1257
- if (result.skipped) {
1258
- logger.debug(`Build skipped: ${result.reason}`);
1259
- } else {
1260
- logger.success("Post-merge build completed successfully");
1261
- }
1262
- }
1263
- /**
1264
- * Perform post-merge cleanup operations
1265
- * Converts ParsedFinishInput to ParsedInput and calls ResourceCleanup
1266
- * Handles failures gracefully without throwing
1267
- */
1268
- async performPostMergeCleanup(parsed, options, worktree) {
1269
- const cleanupInput = {
1270
- type: parsed.type,
1271
- originalInput: parsed.originalInput,
1272
- ...parsed.number !== void 0 && { number: parsed.number },
1273
- ...parsed.branchName !== void 0 && { branchName: parsed.branchName }
1274
- };
1275
- const cleanupOptions = {
1276
- dryRun: options.dryRun ?? false,
1277
- deleteBranch: true,
1278
- // Delete branch after successful merge
1279
- keepDatabase: false,
1280
- // Clean up database after merge
1281
- force: options.force ?? false
1282
- };
1283
- try {
1284
- logger.info("Starting post-merge cleanup...");
1285
- await this.ensureResourceCleanup();
1286
- if (!this.resourceCleanup) {
1287
- throw new Error("Failed to initialize ResourceCleanup");
1288
- }
1289
- const result = await this.resourceCleanup.cleanupWorktree(cleanupInput, cleanupOptions);
1290
- this.reportCleanupResults(result);
1291
- if (!result.success) {
1292
- logger.warn("Some cleanup operations failed - manual cleanup may be required");
1293
- this.showManualCleanupInstructions(worktree);
1294
- } else {
1295
- logger.success("Post-merge cleanup completed successfully");
1296
- }
1297
- if (this.isRunningFromWithinWorktree(worktree.path)) {
1298
- this.showTerminalCloseWarning(worktree);
1299
- }
1300
- } catch (error) {
1301
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1302
- logger.warn(`Cleanup failed: ${errorMessage}`);
1303
- logger.warn("Merge completed successfully, but manual cleanup is required");
1304
- this.showManualCleanupInstructions(worktree);
1305
- }
1306
- }
1307
- /**
1308
- * Report cleanup operation results to user
1309
- */
1310
- reportCleanupResults(result) {
1311
- if (result.operations.length === 0) {
1312
- return;
1313
- }
1314
- logger.info("Cleanup operations:");
1315
- for (const op of result.operations) {
1316
- const status = op.success ? "\u2713" : "\u2717";
1317
- const message = op.error ? `${op.message}: ${op.error}` : op.message;
1318
- if (op.success) {
1319
- logger.info(` ${status} ${message}`);
1320
- } else {
1321
- logger.warn(` ${status} ${message}`);
1322
- }
1323
- }
1324
- }
1325
- /**
1326
- * Show manual cleanup instructions when cleanup fails
1327
- */
1328
- showManualCleanupInstructions(worktree) {
1329
- logger.info("\nManual cleanup commands:");
1330
- logger.info(` 1. Remove worktree: git worktree remove ${worktree.path}`);
1331
- logger.info(` 2. Delete branch: git branch -d ${worktree.branch}`);
1332
- logger.info(` 3. Check dev servers: lsof -i :PORT (and kill if needed)`);
1333
- }
1334
- /**
1335
- * Check if current working directory is within the target worktree
1336
- */
1337
- isRunningFromWithinWorktree(worktreePath) {
1338
- const normalizedCwd = path.normalize(process.cwd());
1339
- const normalizedWorktree = path.normalize(worktreePath);
1340
- return normalizedCwd.startsWith(normalizedWorktree);
1341
- }
1342
- /**
1343
- * Display warning to close terminal/IDE when running from within finished loom
1344
- */
1345
- showTerminalCloseWarning(worktree) {
1346
- logger.info("");
1347
- logger.info("You are currently in the directory of the loom that was just finished.");
1348
- logger.info("Please close this terminal and any IDE/terminal windows using this directory.");
1349
- logger.info(`Directory: ${worktree.path}`);
1350
- }
1351
- };
1352
- export {
1353
- FinishCommand
1354
- };
1355
- //# sourceMappingURL=finish-QJSK6Z7J.js.map