@iloom/cli 0.3.4 → 0.4.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 (181) hide show
  1. package/README.md +13 -3
  2. package/dist/{BranchNamingService-A77VI6AI.js → BranchNamingService-GCCWB3LK.js} +4 -3
  3. package/dist/ClaudeContextManager-DK77227F.js +16 -0
  4. package/dist/ClaudeService-W3SA7HVG.js +15 -0
  5. package/dist/GitHubService-RPM27GWD.js +12 -0
  6. package/dist/{LoomLauncher-ZV3ZZIBA.js → LoomLauncher-S3YGJRJQ.js} +43 -27
  7. package/dist/LoomLauncher-S3YGJRJQ.js.map +1 -0
  8. package/dist/PromptTemplateManager-2TDZAUC6.js +9 -0
  9. package/dist/README.md +13 -3
  10. package/dist/{SettingsManager-I2LRCW2A.js → SettingsManager-FJFU6JJD.js} +7 -3
  11. package/dist/SettingsMigrationManager-EH3J2TCN.js +10 -0
  12. package/dist/{chunk-5Q3NDNNV.js → chunk-2W2FBL5G.js} +153 -6
  13. package/dist/chunk-2W2FBL5G.js.map +1 -0
  14. package/dist/{chunk-OXAM2WVC.js → chunk-55TB3FSG.js} +21 -1
  15. package/dist/chunk-55TB3FSG.js.map +1 -0
  16. package/dist/chunk-6UIGZD2N.js +20 -0
  17. package/dist/chunk-6UIGZD2N.js.map +1 -0
  18. package/dist/{chunk-RIEO2WML.js → chunk-74VMN2KC.js} +26 -2
  19. package/dist/chunk-74VMN2KC.js.map +1 -0
  20. package/dist/{chunk-2MAIX45J.js → chunk-BIIQHEXJ.js} +104 -43
  21. package/dist/chunk-BIIQHEXJ.js.map +1 -0
  22. package/dist/{chunk-UAN4A3YU.js → chunk-G6CIIJLT.js} +11 -11
  23. package/dist/{chunk-DLHA5VQ3.js → chunk-HD5SUKI2.js} +36 -179
  24. package/dist/chunk-HD5SUKI2.js.map +1 -0
  25. package/dist/{chunk-2IJEMXOB.js → chunk-IARWMDAX.js} +427 -428
  26. package/dist/chunk-IARWMDAX.js.map +1 -0
  27. package/dist/chunk-IJ7IGJT3.js +192 -0
  28. package/dist/chunk-IJ7IGJT3.js.map +1 -0
  29. package/dist/{chunk-2CXREBLZ.js → chunk-JC5HXN75.js} +8 -6
  30. package/dist/chunk-JC5HXN75.js.map +1 -0
  31. package/dist/{chunk-3RUPPQRG.js → chunk-KO2FOMHL.js} +43 -2
  32. package/dist/{chunk-3RUPPQRG.js.map → chunk-KO2FOMHL.js.map} +1 -1
  33. package/dist/{chunk-4XIDC3NF.js → chunk-MD6HA5IK.js} +2 -2
  34. package/dist/{chunk-OC4H6HJD.js → chunk-O7WHXLCB.js} +2 -2
  35. package/dist/{chunk-M7JJCX53.js → chunk-OEGECBFS.js} +20 -20
  36. package/dist/chunk-OEGECBFS.js.map +1 -0
  37. package/dist/{chunk-MKWYLDFK.js → chunk-OF7BNW4D.js} +43 -3
  38. package/dist/chunk-OF7BNW4D.js.map +1 -0
  39. package/dist/{chunk-PGPI5LR4.js → chunk-POI7KLBH.js} +7 -21
  40. package/dist/chunk-POI7KLBH.js.map +1 -0
  41. package/dist/{chunk-PA6Q6AWM.js → chunk-PSFVTBM7.js} +2 -2
  42. package/dist/chunk-QHA67Q7A.js +281 -0
  43. package/dist/chunk-QHA67Q7A.js.map +1 -0
  44. package/dist/{chunk-SUOXY5WJ.js → chunk-QIUJPPJQ.js} +5 -5
  45. package/dist/chunk-QIUJPPJQ.js.map +1 -0
  46. package/dist/{chunk-ZM3CFL5L.js → chunk-QRBOPFAA.js} +3 -3
  47. package/dist/{chunk-OYF4VIFI.js → chunk-RUC7OULH.js} +147 -22
  48. package/dist/chunk-RUC7OULH.js.map +1 -0
  49. package/dist/{chunk-CE26YH2U.js → chunk-SJ2GZ6RF.js} +48 -50
  50. package/dist/chunk-SJ2GZ6RF.js.map +1 -0
  51. package/dist/{chunk-SSCQCCJ7.js → chunk-THF25ICZ.js} +2 -2
  52. package/dist/chunk-TMZAVPGF.js +667 -0
  53. package/dist/chunk-TMZAVPGF.js.map +1 -0
  54. package/dist/{chunk-5VK4NRSF.js → chunk-UNXRACJ7.js} +35 -36
  55. package/dist/chunk-UNXRACJ7.js.map +1 -0
  56. package/dist/{chunk-AKUJXDNW.js → chunk-UPUAQYAW.js} +3 -3
  57. package/dist/{chunk-GEHQXLEI.js → chunk-UYVWLISQ.js} +18 -35
  58. package/dist/chunk-UYVWLISQ.js.map +1 -0
  59. package/dist/{chunk-OSCLCMDG.js → chunk-UYWAESOT.js} +3 -3
  60. package/dist/{chunk-RW54ZMBM.js → chunk-VAYGNQTE.js} +2 -2
  61. package/dist/{chunk-ZT3YZB4K.js → chunk-VBFDVGAE.js} +12 -12
  62. package/dist/chunk-VBFDVGAE.js.map +1 -0
  63. package/dist/{chunk-IFB4Z76W.js → chunk-VTXCGKV5.js} +13 -12
  64. package/dist/chunk-VTXCGKV5.js.map +1 -0
  65. package/dist/{chunk-CDZERT7Z.js → chunk-VWNS6DH5.js} +48 -4
  66. package/dist/chunk-VWNS6DH5.js.map +1 -0
  67. package/dist/{chunk-CFFQ2Z7A.js → chunk-WUQQNE63.js} +2 -2
  68. package/dist/{chunk-UJL4HI2R.js → chunk-Z5NXYJIG.js} +20 -2
  69. package/dist/chunk-Z5NXYJIG.js.map +1 -0
  70. package/dist/{claude-W52VKI6L.js → claude-ACVXNB6N.js} +8 -5
  71. package/dist/{cleanup-H4VXU3C3.js → cleanup-KDLVTT7M.js} +133 -122
  72. package/dist/cleanup-KDLVTT7M.js.map +1 -0
  73. package/dist/cli.js +953 -430
  74. package/dist/cli.js.map +1 -1
  75. package/dist/{color-F7RU6B6Z.js → color-ZPIIUADB.js} +3 -3
  76. package/dist/{contribute-Y7IQV5QY.js → contribute-HY372S6F.js} +8 -6
  77. package/dist/{contribute-Y7IQV5QY.js.map → contribute-HY372S6F.js.map} +1 -1
  78. package/dist/dev-server-JCJGQ3PV.js +298 -0
  79. package/dist/dev-server-JCJGQ3PV.js.map +1 -0
  80. package/dist/{feedback-XTUCKJNT.js → feedback-7PVBQNLJ.js} +13 -12
  81. package/dist/{feedback-XTUCKJNT.js.map → feedback-7PVBQNLJ.js.map} +1 -1
  82. package/dist/{git-IYA53VIC.js → git-4BVOOOOV.js} +16 -4
  83. package/dist/hooks/iloom-hook.js +258 -0
  84. package/dist/{ignite-T74RYXCA.js → ignite-3B264M7K.js} +245 -39
  85. package/dist/ignite-3B264M7K.js.map +1 -0
  86. package/dist/index.d.ts +461 -124
  87. package/dist/index.js +743 -210
  88. package/dist/index.js.map +1 -1
  89. package/dist/init-LBA6NUK2.js +21 -0
  90. package/dist/{installation-detector-VARGFFRZ.js → installation-detector-6R6YOFVZ.js} +3 -3
  91. package/dist/mcp/issue-management-server.js +2 -1
  92. package/dist/mcp/issue-management-server.js.map +1 -1
  93. package/dist/neon-helpers-L5CXQ5CT.js +11 -0
  94. package/dist/{open-UMXANW5S.js → open-OGCV32Z4.js} +15 -13
  95. package/dist/{open-UMXANW5S.js.map → open-OGCV32Z4.js.map} +1 -1
  96. package/dist/projects-P55273AB.js +73 -0
  97. package/dist/projects-P55273AB.js.map +1 -0
  98. package/dist/{prompt-QALMYTVC.js → prompt-A7GGRHSY.js} +3 -3
  99. package/dist/prompts/init-prompt.txt +49 -0
  100. package/dist/prompts/issue-prompt.txt +110 -8
  101. package/dist/prompts/regular-prompt.txt +90 -0
  102. package/dist/prompts/session-summary-prompt.txt +82 -0
  103. package/dist/{rebase-VJ2VKR6R.js → rebase-4T5FQHNH.js} +11 -9
  104. package/dist/{rebase-VJ2VKR6R.js.map → rebase-4T5FQHNH.js.map} +1 -1
  105. package/dist/{remote-VUNCQZ6J.js → remote-73TZ2ADI.js} +3 -3
  106. package/dist/{run-MJYY4PUT.js → run-HNOP6WE2.js} +15 -13
  107. package/dist/{run-MJYY4PUT.js.map → run-HNOP6WE2.js.map} +1 -1
  108. package/dist/schema/settings.schema.json +49 -0
  109. package/dist/shell-DE3HKJSM.js +240 -0
  110. package/dist/shell-DE3HKJSM.js.map +1 -0
  111. package/dist/summary-GDT7DTRI.js +244 -0
  112. package/dist/summary-GDT7DTRI.js.map +1 -0
  113. package/dist/{test-git-IT5EWQ5C.js → test-git-YMAE57UP.js} +6 -4
  114. package/dist/{test-git-IT5EWQ5C.js.map → test-git-YMAE57UP.js.map} +1 -1
  115. package/dist/{test-prefix-NPWDPUUH.js → test-prefix-YCKL6CMT.js} +6 -4
  116. package/dist/{test-prefix-NPWDPUUH.js.map → test-prefix-YCKL6CMT.js.map} +1 -1
  117. package/dist/{test-tabs-PRMRSHKI.js → test-tabs-3SCJWRKT.js} +4 -4
  118. package/dist/{test-webserver-DAHONWCS.js → test-webserver-VPNLAFZ3.js} +2 -2
  119. package/dist/{update-4TDDUR5K.js → update-LETF5ASC.js} +4 -4
  120. package/dist/{update-notifier-QEX3CJHA.js → update-notifier-H55ZK7NU.js} +3 -3
  121. package/package.json +6 -6
  122. package/dist/ClaudeContextManager-BN7RE5ZQ.js +0 -15
  123. package/dist/ClaudeService-DLYLJUPA.js +0 -14
  124. package/dist/GitHubService-FZHHBOFG.js +0 -11
  125. package/dist/LoomLauncher-ZV3ZZIBA.js.map +0 -1
  126. package/dist/PromptTemplateManager-6HH3PVXV.js +0 -9
  127. package/dist/SettingsMigrationManager-TJ7UWZG5.js +0 -10
  128. package/dist/chunk-2CXREBLZ.js.map +0 -1
  129. package/dist/chunk-2IJEMXOB.js.map +0 -1
  130. package/dist/chunk-2MAIX45J.js.map +0 -1
  131. package/dist/chunk-5Q3NDNNV.js.map +0 -1
  132. package/dist/chunk-5VK4NRSF.js.map +0 -1
  133. package/dist/chunk-CDZERT7Z.js.map +0 -1
  134. package/dist/chunk-CE26YH2U.js.map +0 -1
  135. package/dist/chunk-DLHA5VQ3.js.map +0 -1
  136. package/dist/chunk-GEHQXLEI.js.map +0 -1
  137. package/dist/chunk-IFB4Z76W.js.map +0 -1
  138. package/dist/chunk-M7JJCX53.js.map +0 -1
  139. package/dist/chunk-MKWYLDFK.js.map +0 -1
  140. package/dist/chunk-OXAM2WVC.js.map +0 -1
  141. package/dist/chunk-OYF4VIFI.js.map +0 -1
  142. package/dist/chunk-PGPI5LR4.js.map +0 -1
  143. package/dist/chunk-RIEO2WML.js.map +0 -1
  144. package/dist/chunk-SUOXY5WJ.js.map +0 -1
  145. package/dist/chunk-UJL4HI2R.js.map +0 -1
  146. package/dist/chunk-ZT3YZB4K.js.map +0 -1
  147. package/dist/cleanup-H4VXU3C3.js.map +0 -1
  148. package/dist/ignite-T74RYXCA.js.map +0 -1
  149. package/dist/init-4FHTAM3F.js +0 -19
  150. package/dist/logger-MKYH4UDV.js +0 -12
  151. package/dist/neon-helpers-77PBPGJ5.js +0 -10
  152. package/dist/update-notifier-QEX3CJHA.js.map +0 -1
  153. /package/dist/{BranchNamingService-A77VI6AI.js.map → BranchNamingService-GCCWB3LK.js.map} +0 -0
  154. /package/dist/{ClaudeContextManager-BN7RE5ZQ.js.map → ClaudeContextManager-DK77227F.js.map} +0 -0
  155. /package/dist/{ClaudeService-DLYLJUPA.js.map → ClaudeService-W3SA7HVG.js.map} +0 -0
  156. /package/dist/{GitHubService-FZHHBOFG.js.map → GitHubService-RPM27GWD.js.map} +0 -0
  157. /package/dist/{PromptTemplateManager-6HH3PVXV.js.map → PromptTemplateManager-2TDZAUC6.js.map} +0 -0
  158. /package/dist/{SettingsManager-I2LRCW2A.js.map → SettingsManager-FJFU6JJD.js.map} +0 -0
  159. /package/dist/{SettingsMigrationManager-TJ7UWZG5.js.map → SettingsMigrationManager-EH3J2TCN.js.map} +0 -0
  160. /package/dist/{chunk-UAN4A3YU.js.map → chunk-G6CIIJLT.js.map} +0 -0
  161. /package/dist/{chunk-4XIDC3NF.js.map → chunk-MD6HA5IK.js.map} +0 -0
  162. /package/dist/{chunk-OC4H6HJD.js.map → chunk-O7WHXLCB.js.map} +0 -0
  163. /package/dist/{chunk-PA6Q6AWM.js.map → chunk-PSFVTBM7.js.map} +0 -0
  164. /package/dist/{chunk-ZM3CFL5L.js.map → chunk-QRBOPFAA.js.map} +0 -0
  165. /package/dist/{chunk-SSCQCCJ7.js.map → chunk-THF25ICZ.js.map} +0 -0
  166. /package/dist/{chunk-AKUJXDNW.js.map → chunk-UPUAQYAW.js.map} +0 -0
  167. /package/dist/{chunk-OSCLCMDG.js.map → chunk-UYWAESOT.js.map} +0 -0
  168. /package/dist/{chunk-RW54ZMBM.js.map → chunk-VAYGNQTE.js.map} +0 -0
  169. /package/dist/{chunk-CFFQ2Z7A.js.map → chunk-WUQQNE63.js.map} +0 -0
  170. /package/dist/{claude-W52VKI6L.js.map → claude-ACVXNB6N.js.map} +0 -0
  171. /package/dist/{color-F7RU6B6Z.js.map → color-ZPIIUADB.js.map} +0 -0
  172. /package/dist/{git-IYA53VIC.js.map → git-4BVOOOOV.js.map} +0 -0
  173. /package/dist/{init-4FHTAM3F.js.map → init-LBA6NUK2.js.map} +0 -0
  174. /package/dist/{installation-detector-VARGFFRZ.js.map → installation-detector-6R6YOFVZ.js.map} +0 -0
  175. /package/dist/{logger-MKYH4UDV.js.map → neon-helpers-L5CXQ5CT.js.map} +0 -0
  176. /package/dist/{neon-helpers-77PBPGJ5.js.map → prompt-A7GGRHSY.js.map} +0 -0
  177. /package/dist/{prompt-QALMYTVC.js.map → remote-73TZ2ADI.js.map} +0 -0
  178. /package/dist/{test-tabs-PRMRSHKI.js.map → test-tabs-3SCJWRKT.js.map} +0 -0
  179. /package/dist/{test-webserver-DAHONWCS.js.map → test-webserver-VPNLAFZ3.js.map} +0 -0
  180. /package/dist/{update-4TDDUR5K.js.map → update-LETF5ASC.js.map} +0 -0
  181. /package/dist/{remote-VUNCQZ6J.js.map → update-notifier-H55ZK7NU.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/git.ts"],"sourcesContent":["import path from 'path'\nimport { execa, type ExecaError } from 'execa'\nimport { type GitWorktree } from '../types/worktree.js'\nimport { SettingsManager, type SettingsManager as SettingsManagerType } from '../lib/SettingsManager.js'\nimport { MetadataManager } from '../lib/MetadataManager.js'\nimport { logger } from './logger.js'\n\n/**\n * Execute a Git command and return the stdout result\n * Throws an error if the command fails\n */\nexport async function executeGitCommand(\n args: string[],\n options?: { cwd?: string; timeout?: number; stdio?: 'inherit' | 'pipe'; env?: NodeJS.ProcessEnv }\n): Promise<string> {\n try {\n const result = await execa('git', args, {\n cwd: options?.cwd ?? process.cwd(),\n timeout: options?.timeout ?? 30000,\n encoding: 'utf8',\n stdio: options?.stdio ?? 'pipe',\n verbose: logger.isDebugEnabled(),\n // Spread env conditionally - only include if defined\n ...(options?.env && { env: options.env }),\n })\n\n return result.stdout\n } catch (error) {\n const execaError = error as ExecaError\n const stderr = execaError.stderr ?? execaError.message ?? 'Unknown Git error'\n throw new Error(`Git command failed: ${stderr}`)\n }\n}\n\n/**\n * Parse git worktree list output into structured data\n * @param output - The output from git worktree list --porcelain\n * @param defaultBranch - Default branch name to use for bare repositories (defaults to 'main')\n */\nexport function parseWorktreeList(output: string, defaultBranch?: string): GitWorktree[] {\n const worktrees: GitWorktree[] = []\n const lines = output.trim().split('\\n')\n\n let i = 0\n while (i < lines.length) {\n const pathLine = lines[i]\n if (!pathLine?.startsWith('worktree ')) {\n i++\n continue\n }\n\n // Parse path line: \"worktree /path/to/worktree\"\n const pathMatch = pathLine.match(/^worktree (.+)$/)\n if (!pathMatch) {\n i++\n continue\n }\n\n let branch = ''\n let commit = ''\n let detached = false\n let bare = false\n let locked = false\n let lockReason: string | undefined\n\n // Process subsequent lines for this worktree\n i++\n while (i < lines.length && !lines[i]?.startsWith('worktree ')) {\n const line = lines[i]?.trim()\n if (!line) {\n i++\n continue\n }\n\n if (line === 'bare') {\n bare = true\n branch = defaultBranch ?? 'main' // Default assumption for bare repo\n } else if (line === 'detached') {\n detached = true\n branch = 'HEAD'\n } else if (line.startsWith('locked')) {\n locked = true\n const lockMatch = line.match(/^locked (.+)$/)\n lockReason = lockMatch?.[1]\n branch = branch || 'unknown'\n } else if (line.startsWith('HEAD ')) {\n // Parse commit line: \"HEAD abc123def456...\"\n const commitMatch = line.match(/^HEAD ([a-f0-9]+)/)\n if (commitMatch) {\n commit = commitMatch[1] ?? ''\n }\n } else if (line.startsWith('branch ')) {\n // Parse branch line: \"branch refs/heads/feature-branch\"\n const branchMatch = line.match(/^branch refs\\/heads\\/(.+)$/)\n branch = branchMatch?.[1] ?? line.replace('branch ', '')\n }\n\n i++\n }\n\n const worktree: GitWorktree = {\n path: pathMatch[1] ?? '',\n branch,\n commit,\n bare,\n detached,\n locked,\n }\n\n if (lockReason !== undefined) {\n worktree.lockReason = lockReason\n }\n\n worktrees.push(worktree)\n }\n\n return worktrees\n}\n\n/**\n * Check if a branch name follows PR naming patterns\n */\nexport function isPRBranch(branchName: string): boolean {\n const prPatterns = [\n /^pr\\/\\d+/i, // pr/123, pr/123-feature-name\n /^pull\\/\\d+/i, // pull/123\n /^\\d+[-_]/, // 123-feature-name, 123_feature_name\n /^feature\\/pr[-_]?\\d+/i, // feature/pr123, feature/pr-123\n /^hotfix\\/pr[-_]?\\d+/i, // hotfix/pr123\n ]\n\n return prPatterns.some(pattern => pattern.test(branchName))\n}\n\n/**\n * Extract PR number from branch name\n */\nexport function extractPRNumber(branchName: string): number | null {\n const patterns = [\n /^pr\\/(\\d+)/i, // pr/123\n /^pull\\/(\\d+)/i, // pull/123\n /^(\\d+)[-_]/, // 123-feature-name\n /^feature\\/pr[-_]?(\\d+)/i, // feature/pr123\n /^hotfix\\/pr[-_]?(\\d+)/i, // hotfix/pr123\n /pr[-_]?(\\d+)/i, // anywhere with pr123 or pr-123\n ]\n\n for (const pattern of patterns) {\n const match = branchName.match(pattern)\n if (match?.[1]) {\n const num = parseInt(match[1], 10)\n if (!isNaN(num)) return num\n }\n }\n\n return null\n}\n\n/**\n * Extract issue number from branch name\n * Supports both new format (issue-{issueId}__{slug}) and old format (issue-{number}-{slug})\n * @returns string issue ID (alphanumeric) or null if not found\n */\nexport function extractIssueNumber(branchName: string): string | null {\n // Priority 1: New format - issue-{issueId}__ (alphanumeric ID with double underscore)\n const newFormatPattern = /issue-([^_]+)__/i\n const newMatch = branchName.match(newFormatPattern)\n if (newMatch?.[1]) return newMatch[1]\n\n // Priority 2: Old format - issue-{number}- or issue-{number}$ (numeric only, dash or end)\n const oldFormatPattern = /issue-(\\d+)(?:-|$)/i\n const oldMatch = branchName.match(oldFormatPattern)\n if (oldMatch?.[1]) return oldMatch[1]\n\n // Priority 3: Alphanumeric ID at end (either format without description)\n const alphanumericEndPattern = /issue-([^_\\s/]+)$/i\n const alphanumericMatch = branchName.match(alphanumericEndPattern)\n if (alphanumericMatch?.[1]) return alphanumericMatch[1]\n\n // Priority 4: Legacy patterns (issue_N, leading number)\n const legacyPatterns = [\n /issue_(\\d+)/i, // issue_42\n /^(\\d+)-/, // 42-feature-name\n ]\n for (const pattern of legacyPatterns) {\n const match = branchName.match(pattern)\n if (match?.[1]) return match[1]\n }\n\n return null\n}\n\n/**\n * Check if a path follows worktree naming patterns\n */\nexport function isWorktreePath(path: string): boolean {\n const worktreePatterns = [\n /\\/worktrees?\\//i, // Contains /worktree/ or /worktrees/\n /\\/workspace[-_]?\\d+/i, // workspace123, workspace-123\n /\\/issue[-_]?\\d+/i, // issue123, issue-123\n /\\/pr[-_]?\\d+/i, // pr123, pr-123\n /-worktree$/i, // ends with -worktree\n /\\.worktree$/i, // ends with .worktree\n ]\n\n return worktreePatterns.some(pattern => pattern.test(path))\n}\n\n/**\n * Generate a worktree path based on branch name and root directory\n * For PRs, adds _pr_<PR_NUM> suffix to distinguish from issue branches\n */\nexport function generateWorktreePath(\n branchName: string,\n rootDir: string = process.cwd(),\n options?: { isPR?: boolean; prNumber?: number; prefix?: string }\n): string {\n // Replace slashes with dashes (matches bash line 593)\n let sanitized = branchName.replace(/\\//g, '-')\n\n // Add PR suffix if this is a PR (matches bash lines 595-597)\n if (options?.isPR && options?.prNumber) {\n sanitized = `${sanitized}_pr_${options.prNumber}`\n }\n\n const parentDir = path.dirname(rootDir)\n\n // Handle prefix logic\n let prefix: string\n\n if (options?.prefix === undefined) {\n // No prefix in options - calculate default: <basename>-looms\n const mainFolderName = path.basename(rootDir)\n prefix = mainFolderName ? `${mainFolderName}-looms/` : 'looms/'\n } else if (options.prefix === '') {\n // Empty string = no prefix mode\n prefix = ''\n } else {\n // Custom prefix provided\n prefix = options.prefix\n\n // Check if prefix contains forward slashes (nested directory structure)\n const hasNestedPath = prefix.includes('/')\n\n if (hasNestedPath) {\n // Check if it ends with a separator character (dash, underscore, or slash)\n const endsWithSeparator = /[-_/]$/.test(prefix)\n\n if (!endsWithSeparator) {\n // Has nested path but no trailing separator: auto-append hyphen\n // Example: \"temp/looms\" becomes \"temp/looms-\"\n prefix = `${prefix}-`\n }\n // If it already ends with -, _, or /, keep as-is\n } else {\n // Single-level prefix: auto-append separator if it doesn't end with one\n const endsWithSeparator = /[-_]$/.test(prefix)\n if (!endsWithSeparator) {\n prefix = `${prefix}-`\n }\n }\n }\n\n // Apply prefix (or not, if empty)\n if (prefix === '') {\n return path.join(parentDir, sanitized)\n } else if (prefix.endsWith('/')) {\n // Forward slash = nested directory, use path.join for proper handling\n return path.join(parentDir, prefix, sanitized)\n } else if (prefix.includes('/')) {\n // Contains slash but doesn't end with slash = nested with separator (e.g., \"looms/myprefix-\")\n // Split and handle: last part is prefix with separator, rest is directory path\n const lastSlashIndex = prefix.lastIndexOf('/')\n const dirPath = prefix.substring(0, lastSlashIndex)\n const prefixWithSeparator = prefix.substring(lastSlashIndex + 1)\n return path.join(parentDir, dirPath, `${prefixWithSeparator}${sanitized}`)\n } else {\n // Dash/underscore separator = single directory name\n return path.join(parentDir, `${prefix}${sanitized}`)\n }\n}\n\n/**\n * Validate that a directory is a valid Git repository\n */\nexport async function isValidGitRepo(path: string): Promise<boolean> {\n try {\n await executeGitCommand(['rev-parse', '--git-dir'], { cwd: path })\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Get the current branch name for a repository\n */\nexport async function getCurrentBranch(path: string = process.cwd()): Promise<string | null> {\n try {\n const result = await executeGitCommand(['branch', '--show-current'], { cwd: path })\n return result.trim()\n } catch {\n return null\n }\n}\n\n/**\n * Check if a branch exists (local or remote)\n */\nexport async function branchExists(\n branchName: string,\n path: string = process.cwd(),\n includeRemote = true\n): Promise<boolean> {\n try {\n // Check local branches\n const localResult = await executeGitCommand(['branch', '--list', branchName], { cwd: path })\n if (localResult.trim()) {\n return true\n }\n\n // Check remote branches if requested\n if (includeRemote) {\n const remoteResult = await executeGitCommand(['branch', '-r', '--list', `*/${branchName}`], {\n cwd: path,\n })\n if (remoteResult.trim()) {\n return true\n }\n }\n\n return false\n } catch {\n return false\n }\n}\n\n/**\n * Get the root directory of the current worktree\n * Returns the worktree root when in a linked worktree, or main repo root when in main worktree\n */\nexport async function getWorktreeRoot(path: string = process.cwd()): Promise<string | null> {\n try {\n const result = await executeGitCommand(['rev-parse', '--show-toplevel'], { cwd: path })\n return result.trim()\n } catch {\n return null\n }\n}\n\n/**\n * Get the main repository root directory\n * Returns the main repo root even when called from a linked worktree\n */\nexport async function getRepoRoot(path: string = process.cwd()): Promise<string | null> {\n try {\n // Get the common git directory (shared by all worktrees)\n const gitCommonDir = await executeGitCommand(\n ['rev-parse', '--path-format=absolute', '--git-common-dir'],\n { cwd: path }\n )\n const trimmedPath = gitCommonDir.trim()\n\n // Handle linked worktree: /path/to/repo/.git/worktrees/worktree-name -> /path/to/repo\n // Handle main worktree: /path/to/repo/.git -> /path/to/repo\n const repoRoot = trimmedPath\n .replace(/\\/\\.git\\/worktrees\\/[^/]+$/, '') // Remove /.git/worktrees/name suffix\n .replace(/\\/\\.git$/, '') // Remove /.git suffix\n\n return repoRoot\n } catch(error) {\n logger.warn(`Failed to determine repo root from git-common-dir: ${path}`, error instanceof Error ? error.message : String(error))\n return null\n }\n}\n\n/**\n * Find the worktree path where main branch is checked out\n * Copies bash script approach: parse git worktree list to find main\n */\nexport async function findMainWorktreePath(\n path: string = process.cwd(),\n options?: { mainBranch?: string }\n): Promise<string> {\n try {\n const output = await executeGitCommand(['worktree', 'list', '--porcelain'], { cwd: path })\n const worktrees = parseWorktreeList(output, options?.mainBranch)\n\n // Guard: empty worktree list\n if (worktrees.length === 0) {\n throw new Error('No worktrees found in repository')\n }\n\n // Tier 1: Check for specified mainBranch in options\n if (options?.mainBranch) {\n const specified = worktrees.find(wt => wt.branch === options.mainBranch)\n if (!specified?.path) {\n throw new Error(\n `No worktree found with branch '${options.mainBranch}' (specified in settings). Available worktrees: ${worktrees.map(wt => `${wt.path} (${wt.branch})`).join(', ')}`\n )\n }\n return specified.path\n }\n\n // Tier 2: Look for \"main\" branch\n const mainBranch = worktrees.find(wt => wt.branch === 'main')\n if (mainBranch?.path) {\n return mainBranch.path\n }\n\n // Tier 3: Use first worktree (primary worktree)\n const firstWorktree = worktrees[0]\n if (!firstWorktree?.path) {\n throw new Error('Failed to determine primary worktree path')\n }\n return firstWorktree.path\n } catch (error) {\n if (\n error instanceof Error &&\n (error.message.includes('No worktree found with branch') ||\n error.message.includes('No worktrees found') ||\n error.message.includes('Failed to determine primary worktree'))\n ) {\n // Re-throw our specific errors\n throw error\n }\n throw new Error(`Failed to find main worktree: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\n/**\n * Find main worktree path with automatic settings loading\n *\n * This is a convenience wrapper that:\n * 1. Loads project settings from .iloom/settings.json\n * 2. Extracts mainBranch configuration if present\n * 3. Calls findMainWorktreePath with appropriate options\n *\n * @param path - Path to search from (defaults to process.cwd())\n * @param settingsManager - Optional SettingsManager instance (for DI/testing)\n * @returns Path to main worktree\n * @throws Error if main worktree cannot be found\n */\nexport async function findMainWorktreePathWithSettings(\n path?: string,\n settingsManager?: SettingsManagerType\n): Promise<string> {\n // Lazy load SettingsManager to avoid circular dependencies\n settingsManager ??= new SettingsManager()\n\n const settings = await settingsManager.loadSettings(path)\n const findOptions = settings.mainBranch ? { mainBranch: settings.mainBranch } : undefined\n return findMainWorktreePath(path, findOptions)\n}\n\n/**\n * Find the worktree path where a specific branch is checked out\n *\n * Used by MergeManager to find the correct worktree for child loom merges.\n * When finishing a child loom, we need to find where the PARENT branch is\n * checked out (the merge target), not where settings.mainBranch is checked out.\n *\n * @param branchName - The branch name to find\n * @param path - Path to search from (defaults to process.cwd())\n * @returns Path to worktree where the branch is checked out\n * @throws Error if no worktree has the specified branch checked out\n */\nexport async function findWorktreeForBranch(\n branchName: string,\n path: string = process.cwd()\n): Promise<string> {\n try {\n const output = await executeGitCommand(['worktree', 'list', '--porcelain'], { cwd: path })\n const worktrees = parseWorktreeList(output, branchName)\n\n // Guard: empty worktree list\n if (worktrees.length === 0) {\n throw new Error('No worktrees found in repository')\n }\n\n // Find the worktree with the specified branch\n const targetWorktree = worktrees.find(wt => wt.branch === branchName)\n if (!targetWorktree?.path) {\n throw new Error(\n `No worktree found with branch '${branchName}' checked out. ` +\n `Available worktrees: ${worktrees.map(wt => `${wt.path} (${wt.branch})`).join(', ')}`\n )\n }\n return targetWorktree.path\n } catch (error) {\n if (\n error instanceof Error &&\n (error.message.includes('No worktree found with branch') ||\n error.message.includes('No worktrees found'))\n ) {\n // Re-throw our specific errors\n throw error\n }\n throw new Error(`Failed to find worktree for branch '${branchName}': ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\n/**\n * Check if there are uncommitted changes in a repository\n */\nexport async function hasUncommittedChanges(path: string = process.cwd()): Promise<boolean> {\n try {\n const result = await executeGitCommand(['status', '--porcelain'], { cwd: path })\n return result.trim().length > 0\n } catch {\n return false\n }\n}\n\n/**\n * Get the default branch name for a repository\n */\nexport async function getDefaultBranch(path: string = process.cwd()): Promise<string> {\n try {\n // Try to get from remote\n const remoteResult = await executeGitCommand(['symbolic-ref', 'refs/remotes/origin/HEAD'], {\n cwd: path,\n })\n const match = remoteResult.match(/refs\\/remotes\\/origin\\/(.+)/)\n if (match) return match[1] ?? 'main'\n\n // Fallback to common default branch names\n const commonDefaults = ['main', 'master', 'develop']\n for (const branch of commonDefaults) {\n if (await branchExists(branch, path)) {\n return branch\n }\n }\n\n return 'main' // Final fallback\n } catch {\n return 'main'\n }\n}\n\n/**\n * Find all branches related to a GitHub issue or PR number\n * Matches patterns like:\n * - Issue patterns: issue-25, issue/25, 25-feature, feat-25, feat/issue-25\n * - PR patterns: pr/25, pull/25, pr-25, feature/pr-25\n *\n * Based on bash cleanup-worktree.sh find_issue_branches() (lines 133-154)\n *\n * @param issueNumber - The issue or PR number to search for\n * @param path - Working directory to search from (defaults to process.cwd())\n * @param settingsManager - Optional SettingsManager instance (for DI/testing)\n */\nexport async function findAllBranchesForIssue(\n issueNumber: string | number,\n path: string = process.cwd(),\n settingsManager?: SettingsManagerType\n): Promise<string[]> {\n // Lazy load SettingsManager to avoid circular dependencies\n if (!settingsManager) {\n const { SettingsManager: SM } = await import('../lib/SettingsManager.js')\n settingsManager = new SM()\n }\n\n // Get protected branches list from centralized method\n const protectedBranches = await settingsManager.getProtectedBranches(path)\n\n // Get all branches (local and remote)\n const output = await executeGitCommand(['branch', '-a'], { cwd: path })\n\n const branches: string[] = []\n const lines = output.split('\\n').filter(Boolean)\n\n for (const line of lines) {\n // Skip remotes/origin/HEAD pointer\n if (line.includes('remotes/origin/HEAD')) {\n continue\n }\n\n // Clean the branch name:\n // 1. Remove git status markers (* + spaces at start)\n let cleanBranch = line.replace(/^[*+ ]+/, '')\n\n // 2. Remove 'origin/' prefix if present\n cleanBranch = cleanBranch.replace(/^origin\\//, '')\n\n // 3. Remove 'remotes/origin/' prefix if present\n cleanBranch = cleanBranch.replace(/^remotes\\/origin\\//, '')\n\n // 4. Trim any remaining whitespace\n cleanBranch = cleanBranch.trim()\n\n // Skip protected branches\n if (protectedBranches.includes(cleanBranch)) {\n continue\n }\n\n // Check if branch contains issue number with strict word boundary pattern\n // The issue number must NOT be:\n // - Part of a larger number (preceded or followed by a digit)\n // - After an unknown word (like \"tissue-25\")\n // The issue number CAN be:\n // - At start: \"25-feature\"\n // - After known prefix + separator: \"issue-25\", \"feat-25\", \"fix-25\", \"pr-25\"\n // - After just a separator with no prefix: test_25 (separator at start)\n\n // First check: not part of a larger number\n const notPartOfNumber = new RegExp(`(?<!\\\\d)${issueNumber}(?!\\\\d)`)\n if (!notPartOfNumber.test(cleanBranch)) {\n continue\n }\n\n // Second check: if preceded by letters, validate they're known issue-related prefixes\n // This prevents \"tissue-25\" but allows \"issue-25\", \"feat-25\", etc.\n const beforeNumber = cleanBranch.substring(0, cleanBranch.indexOf(String(issueNumber)))\n\n if (beforeNumber) {\n // Extract the last word (letters) before the number\n const lastWord = beforeNumber.match(/([a-zA-Z]+)[-_/\\s]*$/)\n if (lastWord?.[1]) {\n const word = lastWord[1].toLowerCase()\n // Known prefixes for issue-related branches\n const knownPrefixes = [\n 'issue', 'issues',\n 'feat', 'feature', 'features',\n 'fix', 'fixes', 'bugfix', 'hotfix',\n 'pr', 'pull',\n 'test', 'tests',\n 'chore',\n 'docs',\n 'refactor',\n 'perf',\n 'style',\n 'ci',\n 'build',\n 'revert'\n ]\n\n // If we found a word and it's NOT in the known list, skip this branch\n if (!knownPrefixes.includes(word)) {\n continue\n }\n }\n }\n\n // Passed all checks - add to results\n if (!branches.includes(cleanBranch)) {\n branches.push(cleanBranch)\n }\n }\n\n return branches\n}\n\n/**\n * Check if a repository is empty (has no commits yet)\n * @param path - Repository path to check (defaults to process.cwd())\n * @returns true if repository has no commits, false otherwise\n */\nexport async function isEmptyRepository(path: string = process.cwd()): Promise<boolean> {\n try {\n await executeGitCommand(['rev-parse', '--verify', 'HEAD'], { cwd: path })\n return false // HEAD exists, repo has commits\n } catch {\n return true // HEAD doesn't exist, repo is empty\n }\n}\n\n/**\n * Ensure repository has at least one commit\n * Creates an initial empty commit if repository is empty\n * @param path - Repository path (defaults to process.cwd())\n */\nexport async function ensureRepositoryHasCommits(path: string = process.cwd()): Promise<void> {\n const isEmpty = await isEmptyRepository(path)\n if (isEmpty) {\n await executeGitCommand(['commit', '--no-verify', '--allow-empty', '-m', 'Initial commit'], { cwd: path })\n }\n}\n\n/**\n * Push a branch to remote repository\n * Used for PR workflow to push changes to remote without merging locally\n *\n * @param branchName - The branch name to push\n * @param worktreePath - The worktree path where the branch is checked out\n * @param options - Push options\n * @throws Error if push fails\n */\nexport async function pushBranchToRemote(\n branchName: string,\n worktreePath: string,\n options?: { dryRun?: boolean }\n): Promise<void> {\n if (options?.dryRun) {\n // In dry-run mode, just log what would be done\n return\n }\n\n try {\n // Execute: git push origin <branch-name>\n // This matches the bash script behavior (merge-and-clean.sh line 359)\n await executeGitCommand(['push', 'origin', branchName], {\n cwd: worktreePath,\n timeout: 120000, // 120 second timeout for push operations\n })\n } catch (error) {\n // Provide helpful error message based on common push failures\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n // Check for common error patterns\n if (errorMessage.includes('failed to push') || errorMessage.includes('rejected')) {\n throw new Error(\n `Failed to push changes to origin/${branchName}\\n\\n` +\n ` Possible causes:\\n` +\n ` • Remote branch was deleted\\n` +\n ` • Push was rejected (non-fast-forward)\\n` +\n ` • Network connectivity issues\\n\\n` +\n ` To retry: il finish --pr <number>\\n` +\n ` To force push: git push origin ${branchName} --force`\n )\n }\n\n if (errorMessage.includes('Could not resolve host') || errorMessage.includes('network')) {\n throw new Error(\n `Failed to push changes to origin/${branchName}: Network connectivity issues\\n\\n` +\n ` Check your internet connection and try again.`\n )\n }\n\n if (errorMessage.includes('No such remote')) {\n throw new Error(\n `Failed to push changes: Remote 'origin' not found\\n\\n` +\n ` Configure remote: git remote add origin <url>`\n )\n }\n\n // For other errors, re-throw with original message\n throw new Error(`Failed to push to remote: ${errorMessage}`)\n }\n}\n\n/**\n * Check if a file is tracked by git\n * Uses git ls-files to check if file is in the index\n * @param filePath - Absolute or relative path to the file\n * @param cwd - Working directory (defaults to process.cwd())\n * @returns true if file is tracked, false otherwise\n */\nexport async function isFileTrackedByGit(\n filePath: string,\n cwd: string = process.cwd()\n): Promise<boolean> {\n try {\n const result = await executeGitCommand(\n ['ls-files', '--error-unmatch', filePath],\n { cwd }\n )\n return result.trim().length > 0\n } catch (error) {\n // Only return false if it's the specific \"pathspec did not match\" error\n const errorMessage = error instanceof Error ? error.message : String(error)\n if (errorMessage.includes('pathspec') && errorMessage.includes('did not match')) {\n return false\n }\n // Re-throw other errors\n throw error\n }\n}\n\n/**\n * Check if a file is gitignored\n * Uses `git check-ignore` which handles nested gitignore files and global patterns\n *\n * @param filePath - Path to file to check (relative to repo root)\n * @param cwd - Working directory (defaults to process.cwd())\n * @returns true if file IS ignored, false if NOT ignored or on error\n */\nexport async function isFileGitignored(\n filePath: string,\n cwd: string = process.cwd()\n): Promise<boolean> {\n try {\n await executeGitCommand(['check-ignore', '-q', filePath], { cwd })\n return true // Exit 0 = file IS ignored\n } catch {\n return false // Exit 1 = NOT ignored (or error)\n }\n}\n\n/**\n * Check if a branch is merged into the main branch\n *\n * Uses `git merge-base --is-ancestor` which is more reliable than `git branch -d`'s check.\n * The `-d` flag checks against current HEAD, which can give false positives when:\n * - Running from a worktree where main isn't checked out\n * - Squash or rebase merges were used\n *\n * This function explicitly checks if the branch tip is an ancestor of the main branch,\n * providing consistent results regardless of which worktree the command runs from.\n *\n * @param branchName - The branch to check\n * @param mainBranch - The main branch to check against (defaults to 'main')\n * @param cwd - Working directory (defaults to process.cwd())\n * @returns true if branch is merged into main, false otherwise\n */\nexport async function isBranchMergedIntoMain(\n branchName: string,\n mainBranch: string = 'main',\n cwd: string = process.cwd()\n): Promise<boolean> {\n try {\n // git merge-base --is-ancestor exits 0 if branchName is ancestor of mainBranch, 1 if not\n await executeGitCommand(['merge-base', '--is-ancestor', branchName, mainBranch], { cwd })\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Check if a branch exists on the remote (origin) and is up-to-date with local\n * Useful for GitHub-PR workflows to ensure branch has been pushed and is current\n *\n * @param branchName - Name of the branch to check\n * @param cwd - Working directory to run git command in\n * @returns Promise<boolean> - true if remote branch exists and matches local HEAD, false otherwise\n */\nexport async function isRemoteBranchUpToDate(\n branchName: string,\n cwd: string\n): Promise<boolean> {\n try {\n // First, check if remote branch exists and get its commit hash\n const remoteResult = await executeGitCommand(['ls-remote', '--heads', 'origin', branchName], { cwd })\n\n if (remoteResult.trim().length === 0) {\n // Remote branch doesn't exist\n return false\n }\n\n // Extract the commit hash from ls-remote output (format: \"hash\\trefs/heads/branchname\")\n const remoteCommit = remoteResult.trim().split('\\t')[0]\n\n // Get the local branch's HEAD commit\n const localCommit = await executeGitCommand(['rev-parse', branchName], { cwd })\n\n // Both must exist and match\n return localCommit.trim() === remoteCommit\n } catch {\n return false\n }\n}\n\n/**\n * Result of checking remote branch status for safety validation\n */\nexport interface RemoteBranchStatus {\n /** Whether the remote branch exists */\n exists: boolean\n /** Whether the remote is ahead of local (has commits not present locally) */\n remoteAhead: boolean\n /** Whether local is ahead of remote (has unpushed commits) */\n localAhead: boolean\n /** Whether a network error occurred during the check */\n networkError: boolean\n /** Error message if network error occurred */\n errorMessage?: string\n}\n\n/**\n * Check the status of a remote branch for safety validation during cleanup\n * This function provides detailed status needed for the 5-point safety check:\n *\n * The key insight: we care about DATA LOSS, not about remote state\n * - Remote ahead of local is SAFE (commits exist on remote, no data loss)\n * - Local ahead of remote is DANGEROUS (unpushed commits would be lost)\n *\n * 5-point safety logic:\n * 1. Network error -> BLOCK (can't verify safety)\n * 2. Remote ahead of local -> OK (no data loss - commits exist on remote)\n * 3. Local ahead of remote (unpushed commits) -> BLOCK (data loss risk)\n * 4. No remote, merged to main -> OK (work is in main)\n * 5. No remote, NOT merged to main -> BLOCK (unmerged work would be lost)\n *\n * @param branchName - Name of the branch to check\n * @param cwd - Working directory to run git command in\n * @returns Promise<RemoteBranchStatus> - Detailed status of the remote branch\n */\nexport async function checkRemoteBranchStatus(\n branchName: string,\n cwd: string\n): Promise<RemoteBranchStatus> {\n try {\n // First, fetch to ensure we have the latest remote refs\n // This is important to accurately detect if remote is ahead\n try {\n await executeGitCommand(['fetch', 'origin', branchName], { cwd, timeout: 30000 })\n } catch (fetchError) {\n // Fetch failing for a specific branch is OK - branch might not exist on remote\n // We'll detect this in the ls-remote call\n const fetchErrorMessage = fetchError instanceof Error ? fetchError.message : String(fetchError)\n\n // Check if this is a network error vs branch not found\n if (fetchErrorMessage.includes('Could not resolve host') ||\n fetchErrorMessage.includes('unable to access') ||\n fetchErrorMessage.includes('network') ||\n fetchErrorMessage.includes('Connection refused') ||\n fetchErrorMessage.includes('Connection timed out')) {\n return {\n exists: false,\n remoteAhead: false,\n localAhead: false,\n networkError: true,\n errorMessage: fetchErrorMessage\n }\n }\n // Otherwise continue - branch might just not exist on remote\n }\n\n // Check if remote branch exists using ls-remote\n const remoteResult = await executeGitCommand(['ls-remote', '--heads', 'origin', branchName], { cwd })\n\n if (remoteResult.trim().length === 0) {\n // Remote branch doesn't exist\n return {\n exists: false,\n remoteAhead: false,\n localAhead: false,\n networkError: false\n }\n }\n\n // Remote branch exists - check if it's ahead of local\n // Extract the remote commit hash\n const remoteCommit = remoteResult.trim().split('\\t')[0]\n\n // Guard against undefined (shouldn't happen but TypeScript wants it)\n if (!remoteCommit) {\n return {\n exists: false,\n remoteAhead: false,\n localAhead: false,\n networkError: false\n }\n }\n\n // Get the local branch's HEAD commit\n const localCommit = await executeGitCommand(['rev-parse', branchName], { cwd })\n const localCommitTrimmed = localCommit.trim()\n\n if (remoteCommit === localCommitTrimmed) {\n // Remote and local are at the same commit - safe (no unpushed commits)\n return {\n exists: true,\n remoteAhead: false,\n localAhead: false,\n networkError: false\n }\n }\n\n // Commits differ - check if remote is ahead of local\n // Use merge-base to find common ancestor, then compare\n try {\n // Check if localCommit is an ancestor of remoteCommit (meaning remote is ahead)\n await executeGitCommand(['merge-base', '--is-ancestor', localCommitTrimmed, remoteCommit], { cwd })\n // If we get here, local IS an ancestor of remote, meaning remote is ahead\n // This is SAFE - no data loss because commits exist on remote\n return {\n exists: true,\n remoteAhead: true,\n localAhead: false,\n networkError: false\n }\n } catch {\n // Local is NOT an ancestor of remote\n // This means local is ahead or branches have diverged\n // Either way, local has unpushed commits - this is DANGEROUS (data loss risk)\n return {\n exists: true,\n remoteAhead: false,\n localAhead: true,\n networkError: false\n }\n }\n } catch (error) {\n // Check if this is a network error\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n if (errorMessage.includes('Could not resolve host') ||\n errorMessage.includes('unable to access') ||\n errorMessage.includes('network') ||\n errorMessage.includes('Connection refused') ||\n errorMessage.includes('Connection timed out')) {\n return {\n exists: false,\n remoteAhead: false,\n localAhead: false,\n networkError: true,\n errorMessage\n }\n }\n\n // For other errors, assume remote doesn't exist\n return {\n exists: false,\n remoteAhead: false,\n localAhead: false,\n networkError: false\n }\n }\n}\n\n/**\n * Get the merge target branch for a loom\n * Priority: parent loom metadata (parentLoom.branchName) > configured main branch > 'main'\n *\n * This is the shared utility for determining where a branch should merge to.\n * Child looms merge to their parent branch, standalone looms merge to main.\n *\n * @param worktreePath - Path to load metadata/settings from (defaults to process.cwd())\n * @param options - Optional dependency injection for testing\n * @returns The branch name to merge into\n */\nexport async function getMergeTargetBranch(\n worktreePath: string = process.cwd(),\n options?: {\n settingsManager?: SettingsManagerType\n metadataManager?: MetadataManager\n }\n): Promise<string> {\n const settingsManager = options?.settingsManager ?? new SettingsManager()\n const metadataManager = options?.metadataManager ?? new MetadataManager()\n\n // Check for parent loom metadata first (child looms merge to parent)\n logger.debug(`Checking for parent loom metadata at: ${worktreePath}`)\n const metadata = await metadataManager.readMetadata(worktreePath)\n if (metadata?.parentLoom?.branchName) {\n logger.debug(`Using parent branch as merge target: ${metadata.parentLoom.branchName}`)\n return metadata.parentLoom.branchName\n }\n logger.debug('No parent loom metadata found, falling back to settings')\n\n // Fall back to configured main branch\n const settings = await settingsManager.loadSettings(worktreePath)\n const mainBranch = settings.mainBranch ?? 'main'\n logger.debug(`Using configured main branch as merge target: ${mainBranch}`)\n return mainBranch\n}\n"],"mappings":";;;;;;;;;;;;AAAA,OAAO,UAAU;AACjB,SAAS,aAA8B;AAUvC,eAAsB,kBACpB,MACA,SACiB;AACjB,MAAI;AACF,UAAM,SAAS,MAAM,MAAM,OAAO,M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;AACrF,WAAO,SAAS,WAAW;AAAA,EAC7B;AACA,SAAO,MAAM,yDAAyD;AAGtE,QAAM,WAAW,MAAM,gBAAgB,aAAa,YAAY;AAChE,QAAM,aAAa,SAAS,cAAc;AAC1C,SAAO,MAAM,iDAAiD,UAAU,EAAE;AAC1E,SAAO;AACT;","names":["path"]}
@@ -1,4 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ extractIssueNumber,
4
+ extractPRNumber
5
+ } from "./chunk-2W2FBL5G.js";
2
6
 
3
7
  // src/utils/IdentifierParser.ts
4
8
  var IdentifierParser = class {
@@ -52,6 +56,22 @@ var IdentifierParser = class {
52
56
  }
53
57
  const branchWorktree = await this.gitWorktreeManager.findWorktreeForBranch(cleanId);
54
58
  if (branchWorktree) {
59
+ const prFromBranch = extractPRNumber(cleanId);
60
+ if (prFromBranch !== null) {
61
+ return {
62
+ type: "pr",
63
+ number: prFromBranch,
64
+ originalInput
65
+ };
66
+ }
67
+ const issueFromBranch = extractIssueNumber(cleanId);
68
+ if (issueFromBranch !== null) {
69
+ return {
70
+ type: "issue",
71
+ number: issueFromBranch,
72
+ originalInput
73
+ };
74
+ }
55
75
  return {
56
76
  type: "branch",
57
77
  branchName: cleanId,
@@ -65,4 +85,4 @@ var IdentifierParser = class {
65
85
  export {
66
86
  IdentifierParser
67
87
  };
68
- //# sourceMappingURL=chunk-OXAM2WVC.js.map
88
+ //# sourceMappingURL=chunk-55TB3FSG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/IdentifierParser.ts"],"sourcesContent":["import type { ParsedInput } from '../commands/start.js'\nimport type { GitWorktreeManager } from '../lib/GitWorktreeManager.js'\nimport { extractIssueNumber, extractPRNumber } from './git.js'\n\n/**\n * IdentifierParser provides consistent identifier parsing across commands\n * using pattern-based detection without GitHub API calls.\n *\n * Detection Strategy:\n * 1. For numeric input (e.g., \"42\", \"#66\"):\n * - Check for PR worktree first (_pr_N pattern in path)\n * - Then check for issue worktree (issue-N pattern in branch)\n * 2. For alphanumeric input (e.g., \"ENG-123\"):\n * - Check for issue worktree with alphanumeric identifier\n * 3. For branch-style input (e.g., \"feat/issue-42__description\", \"pr/123\"):\n * - Find matching worktree by branch name\n * - Extract PR number from branch name if present (priority)\n * - Extract issue number from branch name if present\n * - Return as PR/issue type if number found, otherwise branch type\n *\n * This ensures:\n * - No unnecessary GitHub API calls\n * - Consistent behavior across finish/cleanup commands\n * - PR detection takes priority over issue detection\n * - Issue numbers are extracted from branch names for \"Fixes #N\" commit trailers\n */\nexport class IdentifierParser {\n\tconstructor(private gitWorktreeManager: GitWorktreeManager) {}\n\n\t/**\n\t * Parse identifier using pattern-based detection on existing worktrees.\n\t * Does NOT make GitHub API calls - only checks local worktree patterns.\n\t *\n\t * @param identifier - The identifier to parse (e.g., \"42\", \"#66\", \"ENG-123\", \"my-branch\")\n\t * @returns ParsedInput with type, number/branchName, and originalInput\n\t * @throws Error if no matching worktree is found\n\t */\n\tasync parseForPatternDetection(identifier: string): Promise<ParsedInput> {\n\t\t// Remove # prefix if present and trim whitespace\n\t\tconst cleanId = identifier.replace(/^#/, '').trim()\n\t\tconst originalInput = identifier\n\n\t\t// Check if input is numeric (GitHub-style issue/PR numbers)\n\t\tconst numericMatch = cleanId.match(/^(\\d+)$/)\n\n\t\tif (numericMatch?.[1]) {\n\t\t\tconst number = parseInt(numericMatch[1], 10)\n\n\t\t\t// Priority 1: Check for PR worktree (_pr_N pattern)\n\t\t\t// Pass empty string for branch name since we don't know it yet\n\t\t\tconst prWorktree = await this.gitWorktreeManager.findWorktreeForPR(number, '')\n\t\t\tif (prWorktree) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'pr',\n\t\t\t\t\tnumber,\n\t\t\t\t\toriginalInput,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Priority 2: Check for issue worktree (issue-N pattern)\n\t\t\tconst issueWorktree = await this.gitWorktreeManager.findWorktreeForIssue(number)\n\t\t\tif (issueWorktree) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'issue',\n\t\t\t\t\tnumber,\n\t\t\t\t\toriginalInput,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// No matching worktree found for numeric input\n\t\t\tthrow new Error(`No worktree found for identifier: ${identifier}`)\n\t\t}\n\n\t\t// Check if input is alphanumeric issue identifier (Linear/Jira-style: ABC-123, ENG-42)\n\t\tconst alphanumericMatch = cleanId.match(/^([A-Za-z]+-\\d+)$/)\n\n\t\tif (alphanumericMatch?.[1]) {\n\t\t\tconst alphanumericId = alphanumericMatch[1]\n\n\t\t\t// Check for issue worktree with alphanumeric identifier\n\t\t\tconst issueWorktree = await this.gitWorktreeManager.findWorktreeForIssue(alphanumericId)\n\t\t\tif (issueWorktree) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'issue',\n\t\t\t\t\tnumber: alphanumericId,\n\t\t\t\t\toriginalInput,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// No matching worktree found for alphanumeric identifier\n\t\t\tthrow new Error(`No worktree found for identifier: ${identifier}`)\n\t\t}\n\n\t\t// Non-numeric/non-alphanumeric input: treat as branch name\n\t\tconst branchWorktree = await this.gitWorktreeManager.findWorktreeForBranch(cleanId)\n\t\tif (branchWorktree) {\n\t\t\t// Priority 1: Check for PR pattern in the input\n\t\t\tconst prFromBranch = extractPRNumber(cleanId)\n\t\t\tif (prFromBranch !== null) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'pr',\n\t\t\t\t\tnumber: prFromBranch,\n\t\t\t\t\toriginalInput,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Priority 2: Try to extract issue number from branch name\n\t\t\t// This handles cases like \"feat/issue-42__description\" passed as explicit input\n\t\t\tconst issueFromBranch = extractIssueNumber(cleanId)\n\t\t\tif (issueFromBranch !== null) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'issue',\n\t\t\t\t\tnumber: issueFromBranch,\n\t\t\t\t\toriginalInput,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\ttype: 'branch',\n\t\t\t\tbranchName: cleanId,\n\t\t\t\toriginalInput,\n\t\t\t}\n\t\t}\n\n\t\t// No matching worktree found for branch name\n\t\tthrow new Error(`No worktree found for identifier: ${identifier}`)\n\t}\n}\n"],"mappings":";;;;;;;AA0BO,IAAM,mBAAN,MAAuB;AAAA,EAC7B,YAAoB,oBAAwC;AAAxC;AAAA,EAAyC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU7D,MAAM,yBAAyB,YAA0C;AAExE,UAAM,UAAU,WAAW,QAAQ,MAAM,EAAE,EAAE,KAAK;AAClD,UAAM,gBAAgB;AAGtB,UAAM,eAAe,QAAQ,MAAM,SAAS;AAE5C,QAAI,6CAAe,IAAI;AACtB,YAAM,SAAS,SAAS,aAAa,CAAC,GAAG,EAAE;AAI3C,YAAM,aAAa,MAAM,KAAK,mBAAmB,kBAAkB,QAAQ,EAAE;AAC7E,UAAI,YAAY;AACf,eAAO;AAAA,UACN,MAAM;AAAA,UACN;AAAA,UACA;AAAA,QACD;AAAA,MACD;AAGA,YAAM,gBAAgB,MAAM,KAAK,mBAAmB,qBAAqB,MAAM;AAC/E,UAAI,eAAe;AAClB,eAAO;AAAA,UACN,MAAM;AAAA,UACN;AAAA,UACA;AAAA,QACD;AAAA,MACD;AAGA,YAAM,IAAI,MAAM,qCAAqC,UAAU,EAAE;AAAA,IAClE;AAGA,UAAM,oBAAoB,QAAQ,MAAM,mBAAmB;AAE3D,QAAI,uDAAoB,IAAI;AAC3B,YAAM,iBAAiB,kBAAkB,CAAC;AAG1C,YAAM,gBAAgB,MAAM,KAAK,mBAAmB,qBAAqB,cAAc;AACvF,UAAI,eAAe;AAClB,eAAO;AAAA,UACN,MAAM;AAAA,UACN,QAAQ;AAAA,UACR;AAAA,QACD;AAAA,MACD;AAGA,YAAM,IAAI,MAAM,qCAAqC,UAAU,EAAE;AAAA,IAClE;AAGA,UAAM,iBAAiB,MAAM,KAAK,mBAAmB,sBAAsB,OAAO;AAClF,QAAI,gBAAgB;AAEnB,YAAM,eAAe,gBAAgB,OAAO;AAC5C,UAAI,iBAAiB,MAAM;AAC1B,eAAO;AAAA,UACN,MAAM;AAAA,UACN,QAAQ;AAAA,UACR;AAAA,QACD;AAAA,MACD;AAIA,YAAM,kBAAkB,mBAAmB,OAAO;AAClD,UAAI,oBAAoB,MAAM;AAC7B,eAAO;AAAA,UACN,MAAM;AAAA,UACN,QAAQ;AAAA,UACR;AAAA,QACD;AAAA,MACD;AAEA,aAAO;AAAA,QACN,MAAM;AAAA,QACN,YAAY;AAAA,QACZ;AAAA,MACD;AAAA,IACD;AAGA,UAAM,IAAI,MAAM,qCAAqC,UAAU,EAAE;AAAA,EAClE;AACD;","names":[]}
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ logger
4
+ } from "./chunk-UYVWLISQ.js";
5
+
6
+ // src/utils/logger-context.ts
7
+ import { AsyncLocalStorage } from "async_hooks";
8
+ var loggerStorage = new AsyncLocalStorage();
9
+ function getLogger() {
10
+ return loggerStorage.getStore() ?? logger;
11
+ }
12
+ function withLogger(logger2, fn) {
13
+ return loggerStorage.run(logger2, fn);
14
+ }
15
+
16
+ export {
17
+ getLogger,
18
+ withLogger
19
+ };
20
+ //# sourceMappingURL=chunk-6UIGZD2N.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/logger-context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport { logger as defaultLogger, type Logger } from './logger.js'\n\nconst loggerStorage = new AsyncLocalStorage<Logger>()\n\n/**\n * Get current logger from context, or fall back to default\n * Use this instead of importing logger directly to support JSON mode\n */\nexport function getLogger(): Logger {\n return loggerStorage.getStore() ?? defaultLogger\n}\n\n/**\n * Run code with a specific logger in context\n * All code within the callback (including async operations) will use the provided logger\n */\nexport function withLogger<T>(logger: Logger, fn: () => T | Promise<T>): T | Promise<T> {\n return loggerStorage.run(logger, fn)\n}\n"],"mappings":";;;;;;AAAA,SAAS,yBAAyB;AAGlC,IAAM,gBAAgB,IAAI,kBAA0B;AAM7C,SAAS,YAAoB;AAClC,SAAO,cAAc,SAAS,KAAK;AACrC;AAMO,SAAS,WAAcA,SAAgB,IAA0C;AACtF,SAAO,cAAc,IAAIA,SAAQ,EAAE;AACrC;","names":["logger"]}
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  logger
4
- } from "./chunk-GEHQXLEI.js";
4
+ } from "./chunk-UYVWLISQ.js";
5
5
 
6
6
  // src/lib/PromptTemplateManager.ts
7
7
  import { readFile } from "fs/promises";
@@ -125,6 +125,18 @@ var PromptTemplateManager = class {
125
125
  if (variables.VSCODE_SETTINGS_GITIGNORED !== void 0) {
126
126
  result = result.replace(/VSCODE_SETTINGS_GITIGNORED/g, variables.VSCODE_SETTINGS_GITIGNORED);
127
127
  }
128
+ if (variables.SESSION_CONTEXT !== void 0) {
129
+ result = result.replace(/SESSION_CONTEXT/g, variables.SESSION_CONTEXT);
130
+ }
131
+ if (variables.BRANCH_NAME !== void 0) {
132
+ result = result.replace(/BRANCH_NAME/g, variables.BRANCH_NAME);
133
+ }
134
+ if (variables.LOOM_TYPE !== void 0) {
135
+ result = result.replace(/LOOM_TYPE/g, variables.LOOM_TYPE);
136
+ }
137
+ if (variables.COMPACT_SUMMARIES !== void 0) {
138
+ result = result.replace(/COMPACT_SUMMARIES/g, variables.COMPACT_SUMMARIES);
139
+ }
128
140
  return result;
129
141
  }
130
142
  /**
@@ -183,6 +195,18 @@ var PromptTemplateManager = class {
183
195
  } else {
184
196
  result = result.replace(firstTimeUserRegex, "");
185
197
  }
198
+ const interactiveModeRegex = /\{\{#IF INTERACTIVE_MODE\}\}(.*?)\{\{\/IF INTERACTIVE_MODE\}\}/gs;
199
+ if (variables.INTERACTIVE_MODE === true) {
200
+ result = result.replace(interactiveModeRegex, "$1");
201
+ } else {
202
+ result = result.replace(interactiveModeRegex, "");
203
+ }
204
+ const compactSummariesRegex = /\{\{#IF COMPACT_SUMMARIES\}\}(.*?)\{\{\/IF COMPACT_SUMMARIES\}\}/gs;
205
+ if (variables.COMPACT_SUMMARIES !== void 0 && variables.COMPACT_SUMMARIES !== "") {
206
+ result = result.replace(compactSummariesRegex, "$1");
207
+ } else {
208
+ result = result.replace(compactSummariesRegex, "");
209
+ }
186
210
  return result;
187
211
  }
188
212
  /**
@@ -197,4 +221,4 @@ var PromptTemplateManager = class {
197
221
  export {
198
222
  PromptTemplateManager
199
223
  };
200
- //# sourceMappingURL=chunk-RIEO2WML.js.map
224
+ //# sourceMappingURL=chunk-74VMN2KC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/PromptTemplateManager.ts"],"sourcesContent":["import { readFile } from 'fs/promises'\nimport { accessSync } from 'fs'\nimport path from 'path'\nimport { fileURLToPath } from 'url'\nimport { logger } from '../utils/logger.js'\n\nexport interface TemplateVariables {\n\tISSUE_NUMBER?: string | number\n\tPR_NUMBER?: number\n\tISSUE_TITLE?: string\n\tPR_TITLE?: string\n\tWORKSPACE_PATH?: string\n\tPORT?: number\n\tONE_SHOT_MODE?: boolean\n\tINTERACTIVE_MODE?: boolean\n\tSETTINGS_SCHEMA?: string\n\tSETTINGS_GLOBAL_JSON?: string\n\tSETTINGS_JSON?: string\n\tSETTINGS_LOCAL_JSON?: string\n\tSHELL_TYPE?: string\n\tSHELL_CONFIG_PATH?: string\n\tSHELL_CONFIG_CONTENT?: string\n\tREMOTES_INFO?: string\n\tMULTIPLE_REMOTES?: string\n\tSINGLE_REMOTE?: string\n\tSINGLE_REMOTE_NAME?: string\n\tSINGLE_REMOTE_URL?: string\n\tNO_REMOTES?: string\n\tREADME_CONTENT?: string\n\tSETTINGS_SCHEMA_CONTENT?: string\n\tFIRST_TIME_USER?: boolean\n\tVSCODE_SETTINGS_GITIGNORED?: string\n\t// Session summary template variables\n\tSESSION_CONTEXT?: string // Session ID for Claude to reference its conversation\n\tBRANCH_NAME?: string // Branch being finished\n\tLOOM_TYPE?: string // 'issue' or 'pr'\n\tCOMPACT_SUMMARIES?: string // Extracted compact summaries from session transcript\n}\n\nexport class PromptTemplateManager {\n\tprivate templateDir: string\n\n\tconstructor(templateDir?: string) {\n\t\tif (templateDir) {\n\t\t\tthis.templateDir = templateDir\n\t\t} else {\n\t\t\t// Find templates relative to the package installation\n\t\t\t// When running from dist/, templates are copied to dist/prompts/\n\t\t\tconst currentFileUrl = import.meta.url\n\t\t\tconst currentFilePath = fileURLToPath(currentFileUrl)\n\t\t\tconst distDir = path.dirname(currentFilePath) // dist directory (may be chunked file location)\n\n\t\t\t// Walk up to find the dist directory (in case of chunked files)\n\t\t\tlet templateDir = path.join(distDir, 'prompts')\n\t\t\tlet currentDir = distDir\n\n\t\t\t// Try to find the prompts directory by walking up\n\t\t\twhile (currentDir !== path.dirname(currentDir)) {\n\t\t\t\tconst candidatePath = path.join(currentDir, 'prompts')\n\t\t\t\ttry {\n\t\t\t\t\t// Check if this directory exists (sync check for constructor)\n\t\t\t\t\taccessSync(candidatePath)\n\t\t\t\t\ttemplateDir = candidatePath\n\t\t\t\t\tbreak\n\t\t\t\t} catch {\n\t\t\t\t\tcurrentDir = path.dirname(currentDir)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.templateDir = templateDir\n\t\t\tlogger.debug('PromptTemplateManager initialized', {\n\t\t\t\tcurrentFilePath,\n\t\t\t\tdistDir,\n\t\t\t\ttemplateDir: this.templateDir\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Load a template file by name\n\t */\n\tasync loadTemplate(templateName: 'issue' | 'pr' | 'regular' | 'init' | 'session-summary'): Promise<string> {\n\t\tconst templatePath = path.join(this.templateDir, `${templateName}-prompt.txt`)\n\n\t\tlogger.debug('Loading template', {\n\t\t\ttemplateName,\n\t\t\ttemplateDir: this.templateDir,\n\t\t\ttemplatePath\n\t\t})\n\n\t\ttry {\n\t\t\treturn await readFile(templatePath, 'utf-8')\n\t\t} catch (error) {\n\t\t\tlogger.error('Failed to load template', { templateName, templatePath, error })\n\t\t\tthrow new Error(`Template not found: ${templatePath}`)\n\t\t}\n\t}\n\n\t/**\n\t * Substitute variables in a template string\n\t */\n\tsubstituteVariables(template: string, variables: TemplateVariables): string {\n\t\tlet result = template\n\n\t\t// Process conditional sections first\n\t\tresult = this.processConditionalSections(result, variables)\n\n\t\t// Replace each variable if it exists\n\t\tif (variables.ISSUE_NUMBER !== undefined) {\n\t\t\tresult = result.replace(/ISSUE_NUMBER/g, String(variables.ISSUE_NUMBER))\n\t\t}\n\n\t\tif (variables.PR_NUMBER !== undefined) {\n\t\t\tresult = result.replace(/PR_NUMBER/g, String(variables.PR_NUMBER))\n\t\t}\n\n\t\tif (variables.ISSUE_TITLE !== undefined) {\n\t\t\tresult = result.replace(/ISSUE_TITLE/g, variables.ISSUE_TITLE)\n\t\t}\n\n\t\tif (variables.PR_TITLE !== undefined) {\n\t\t\tresult = result.replace(/PR_TITLE/g, variables.PR_TITLE)\n\t\t}\n\n\t\tif (variables.WORKSPACE_PATH !== undefined) {\n\t\t\tresult = result.replace(/WORKSPACE_PATH/g, variables.WORKSPACE_PATH)\n\t\t}\n\n\t\tif (variables.PORT !== undefined) {\n\t\t\tresult = result.replace(/PORT/g, String(variables.PORT))\n\t\t}\n\n\t\tif (variables.SETTINGS_SCHEMA !== undefined) {\n\t\t\tresult = result.replace(/SETTINGS_SCHEMA/g, variables.SETTINGS_SCHEMA)\n\t\t}\n\n\t\tif (variables.SETTINGS_GLOBAL_JSON !== undefined) {\n\t\t\tresult = result.replace(/SETTINGS_GLOBAL_JSON/g, variables.SETTINGS_GLOBAL_JSON)\n\t\t}\n\n\t\tif (variables.SETTINGS_JSON !== undefined) {\n\t\t\tresult = result.replace(/SETTINGS_JSON/g, variables.SETTINGS_JSON)\n\t\t}\n\n\t\tif (variables.SETTINGS_LOCAL_JSON !== undefined) {\n\t\t\tresult = result.replace(/SETTINGS_LOCAL_JSON/g, variables.SETTINGS_LOCAL_JSON)\n\t\t}\n\n\t\tif (variables.SHELL_TYPE !== undefined) {\n\t\t\tresult = result.replace(/SHELL_TYPE/g, variables.SHELL_TYPE)\n\t\t}\n\n\t\tif (variables.SHELL_CONFIG_PATH !== undefined) {\n\t\t\tresult = result.replace(/SHELL_CONFIG_PATH/g, variables.SHELL_CONFIG_PATH)\n\t\t}\n\n\t\tif (variables.SHELL_CONFIG_CONTENT !== undefined) {\n\t\t\tresult = result.replace(/SHELL_CONFIG_CONTENT/g, variables.SHELL_CONFIG_CONTENT)\n\t\t}\n\n\t\tif (variables.REMOTES_INFO !== undefined) {\n\t\t\tresult = result.replace(/REMOTES_INFO/g, variables.REMOTES_INFO)\n\t\t}\n\n\t\tif (variables.MULTIPLE_REMOTES !== undefined) {\n\t\t\tresult = result.replace(/MULTIPLE_REMOTES/g, variables.MULTIPLE_REMOTES)\n\t\t}\n\n\t\tif (variables.SINGLE_REMOTE !== undefined) {\n\t\t\tresult = result.replace(/SINGLE_REMOTE/g, variables.SINGLE_REMOTE)\n\t\t}\n\n\t\tif (variables.SINGLE_REMOTE_NAME !== undefined) {\n\t\t\tresult = result.replace(/SINGLE_REMOTE_NAME/g, variables.SINGLE_REMOTE_NAME)\n\t\t}\n\n\t\tif (variables.SINGLE_REMOTE_URL !== undefined) {\n\t\t\tresult = result.replace(/SINGLE_REMOTE_URL/g, variables.SINGLE_REMOTE_URL)\n\t\t}\n\n\t\tif (variables.NO_REMOTES !== undefined) {\n\t\t\tresult = result.replace(/NO_REMOTES/g, variables.NO_REMOTES)\n\t\t}\n\n\t\tif (variables.README_CONTENT !== undefined) {\n\t\t\tresult = result.replace(/README_CONTENT/g, variables.README_CONTENT)\n\t\t}\n\n\t\tif (variables.SETTINGS_SCHEMA_CONTENT !== undefined) {\n\t\t\tresult = result.replace(/SETTINGS_SCHEMA_CONTENT/g, variables.SETTINGS_SCHEMA_CONTENT)\n\t\t}\n\n\t\tif (variables.VSCODE_SETTINGS_GITIGNORED !== undefined) {\n\t\t\tresult = result.replace(/VSCODE_SETTINGS_GITIGNORED/g, variables.VSCODE_SETTINGS_GITIGNORED)\n\t\t}\n\n\t\t// Session summary template variables\n\t\tif (variables.SESSION_CONTEXT !== undefined) {\n\t\t\tresult = result.replace(/SESSION_CONTEXT/g, variables.SESSION_CONTEXT)\n\t\t}\n\n\t\tif (variables.BRANCH_NAME !== undefined) {\n\t\t\tresult = result.replace(/BRANCH_NAME/g, variables.BRANCH_NAME)\n\t\t}\n\n\t\tif (variables.LOOM_TYPE !== undefined) {\n\t\t\tresult = result.replace(/LOOM_TYPE/g, variables.LOOM_TYPE)\n\t\t}\n\n\t\tif (variables.COMPACT_SUMMARIES !== undefined) {\n\t\t\tresult = result.replace(/COMPACT_SUMMARIES/g, variables.COMPACT_SUMMARIES)\n\t\t}\n\n\t\treturn result\n\t}\n\n\t/**\n\t * Process conditional sections in template\n\t * Format: {{#IF ONE_SHOT_MODE}}content{{/IF ONE_SHOT_MODE}}\n\t *\n\t * Note: /s flag allows . to match newlines\n\t */\n\tprivate processConditionalSections(template: string, variables: TemplateVariables): string {\n\t\tlet result = template\n\n\t\t// Process ONE_SHOT_MODE conditionals\n\t\tconst oneShotRegex = /\\{\\{#IF ONE_SHOT_MODE\\}\\}(.*?)\\{\\{\\/IF ONE_SHOT_MODE\\}\\}/gs\n\n\t\tif (variables.ONE_SHOT_MODE === true) {\n\t\t\t// Include the content, remove the conditional markers\n\t\t\tresult = result.replace(oneShotRegex, '$1')\n\t\t} else {\n\t\t\t// Remove the entire conditional block\n\t\t\tresult = result.replace(oneShotRegex, '')\n\t\t}\n\n\t\t// Process SETTINGS_JSON conditionals\n\t\tconst settingsJsonRegex = /\\{\\{#IF SETTINGS_JSON\\}\\}(.*?)\\{\\{\\/IF SETTINGS_JSON\\}\\}/gs\n\n\t\tif (variables.SETTINGS_JSON !== undefined && variables.SETTINGS_JSON !== '') {\n\t\t\t// Include the content, remove the conditional markers\n\t\t\tresult = result.replace(settingsJsonRegex, '$1')\n\t\t} else {\n\t\t\t// Remove the entire conditional block\n\t\t\tresult = result.replace(settingsJsonRegex, '')\n\t\t}\n\n\t\t// Process SETTINGS_GLOBAL_JSON conditionals\n\t\tconst settingsGlobalJsonRegex = /\\{\\{#IF SETTINGS_GLOBAL_JSON\\}\\}(.*?)\\{\\{\\/IF SETTINGS_GLOBAL_JSON\\}\\}/gs\n\n\t\tif (variables.SETTINGS_GLOBAL_JSON !== undefined && variables.SETTINGS_GLOBAL_JSON !== '') {\n\t\t\t// Include the content, remove the conditional markers\n\t\t\tresult = result.replace(settingsGlobalJsonRegex, '$1')\n\t\t} else {\n\t\t\t// Remove the entire conditional block\n\t\t\tresult = result.replace(settingsGlobalJsonRegex, '')\n\t\t}\n\n\t\t// Process SETTINGS_LOCAL_JSON conditionals\n\t\tconst settingsLocalJsonRegex = /\\{\\{#IF SETTINGS_LOCAL_JSON\\}\\}(.*?)\\{\\{\\/IF SETTINGS_LOCAL_JSON\\}\\}/gs\n\n\t\tif (variables.SETTINGS_LOCAL_JSON !== undefined && variables.SETTINGS_LOCAL_JSON !== '') {\n\t\t\t// Include the content, remove the conditional markers\n\t\t\tresult = result.replace(settingsLocalJsonRegex, '$1')\n\t\t} else {\n\t\t\t// Remove the entire conditional block\n\t\t\tresult = result.replace(settingsLocalJsonRegex, '')\n\t\t}\n\n\t\t// Process MULTIPLE_REMOTES conditionals\n\t\tconst multipleRemotesRegex = /\\{\\{#IF MULTIPLE_REMOTES\\}\\}(.*?)\\{\\{\\/IF MULTIPLE_REMOTES\\}\\}/gs\n\n\t\tif (variables.MULTIPLE_REMOTES !== undefined && variables.MULTIPLE_REMOTES !== '') {\n\t\t\t// Include the content, remove the conditional markers\n\t\t\tresult = result.replace(multipleRemotesRegex, '$1')\n\t\t} else {\n\t\t\t// Remove the entire conditional block\n\t\t\tresult = result.replace(multipleRemotesRegex, '')\n\t\t}\n\n\t\t// Process SINGLE_REMOTE conditionals\n\t\tconst singleRemoteRegex = /\\{\\{#IF SINGLE_REMOTE\\}\\}(.*?)\\{\\{\\/IF SINGLE_REMOTE\\}\\}/gs\n\n\t\tif (variables.SINGLE_REMOTE !== undefined && variables.SINGLE_REMOTE !== '') {\n\t\t\t// Include the content, remove the conditional markers\n\t\t\tresult = result.replace(singleRemoteRegex, '$1')\n\t\t} else {\n\t\t\t// Remove the entire conditional block\n\t\t\tresult = result.replace(singleRemoteRegex, '')\n\t\t}\n\n\t\t// Process NO_REMOTES conditionals\n\t\tconst noRemotesRegex = /\\{\\{#IF NO_REMOTES\\}\\}(.*?)\\{\\{\\/IF NO_REMOTES\\}\\}/gs\n\n\t\tif (variables.NO_REMOTES !== undefined && variables.NO_REMOTES !== '') {\n\t\t\t// Include the content, remove the conditional markers\n\t\t\tresult = result.replace(noRemotesRegex, '$1')\n\t\t} else {\n\t\t\t// Remove the entire conditional block\n\t\t\tresult = result.replace(noRemotesRegex, '')\n\t\t}\n\n\t\t// Process FIRST_TIME_USER conditionals\n\t\tconst firstTimeUserRegex = /\\{\\{#IF FIRST_TIME_USER\\}\\}(.*?)\\{\\{\\/IF FIRST_TIME_USER\\}\\}/gs\n\n\t\tif (variables.FIRST_TIME_USER === true) {\n\t\t\t// Include the content, remove the conditional markers\n\t\t\tresult = result.replace(firstTimeUserRegex, '$1')\n\t\t} else {\n\t\t\t// Remove the entire conditional block\n\t\t\tresult = result.replace(firstTimeUserRegex, '')\n\t\t}\n\n\t\t// Process INTERACTIVE_MODE conditionals\n\t\tconst interactiveModeRegex = /\\{\\{#IF INTERACTIVE_MODE\\}\\}(.*?)\\{\\{\\/IF INTERACTIVE_MODE\\}\\}/gs\n\n\t\tif (variables.INTERACTIVE_MODE === true) {\n\t\t\t// Include the content, remove the conditional markers\n\t\t\tresult = result.replace(interactiveModeRegex, '$1')\n\t\t} else {\n\t\t\t// Remove the entire conditional block\n\t\t\tresult = result.replace(interactiveModeRegex, '')\n\t\t}\n\n\t\t// Process COMPACT_SUMMARIES conditionals\n\t\tconst compactSummariesRegex = /\\{\\{#IF COMPACT_SUMMARIES\\}\\}(.*?)\\{\\{\\/IF COMPACT_SUMMARIES\\}\\}/gs\n\n\t\tif (variables.COMPACT_SUMMARIES !== undefined && variables.COMPACT_SUMMARIES !== '') {\n\t\t\t// Include the content, remove the conditional markers\n\t\t\tresult = result.replace(compactSummariesRegex, '$1')\n\t\t} else {\n\t\t\t// Remove the entire conditional block\n\t\t\tresult = result.replace(compactSummariesRegex, '')\n\t\t}\n\n\t\treturn result\n\t}\n\n\t/**\n\t * Get a fully processed prompt for a workflow type\n\t */\n\tasync getPrompt(\n\t\ttype: 'issue' | 'pr' | 'regular' | 'init' | 'session-summary',\n\t\tvariables: TemplateVariables\n\t): Promise<string> {\n\t\tconst template = await this.loadTemplate(type)\n\t\treturn this.substituteVariables(template, variables)\n\t}\n}\n"],"mappings":";;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAoCvB,IAAM,wBAAN,MAA4B;AAAA,EAGlC,YAAY,aAAsB;AACjC,QAAI,aAAa;AAChB,WAAK,cAAc;AAAA,IACpB,OAAO;AAGN,YAAM,iBAAiB,YAAY;AACnC,YAAM,kBAAkB,cAAc,cAAc;AACpD,YAAM,UAAU,KAAK,QAAQ,eAAe;AAG5C,UAAIA,eAAc,KAAK,KAAK,SAAS,SAAS;AAC9C,UAAI,aAAa;AAGjB,aAAO,eAAe,KAAK,QAAQ,UAAU,GAAG;AAC/C,cAAM,gBAAgB,KAAK,KAAK,YAAY,SAAS;AACrD,YAAI;AAEH,qBAAW,aAAa;AACxB,UAAAA,eAAc;AACd;AAAA,QACD,QAAQ;AACP,uBAAa,KAAK,QAAQ,UAAU;AAAA,QACrC;AAAA,MACD;AAEA,WAAK,cAAcA;AACnB,aAAO,MAAM,qCAAqC;AAAA,QACjD;AAAA,QACA;AAAA,QACA,aAAa,KAAK;AAAA,MACnB,CAAC;AAAA,IACF;AAAA,EACD;AAAA;AA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AO,KAAK,oBAAoB,UAAU,SAAS;AAAA,EACpD;AACD;","names":["templateDir"]}
@@ -1,32 +1,41 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  executeGitCommand,
4
- findMainWorktreePathWithSettings
5
- } from "./chunk-5Q3NDNNV.js";
4
+ findMainWorktreePathWithSettings,
5
+ findWorktreeForBranch,
6
+ getMergeTargetBranch
7
+ } from "./chunk-2W2FBL5G.js";
8
+ import {
9
+ MetadataManager
10
+ } from "./chunk-IJ7IGJT3.js";
6
11
  import {
7
12
  SettingsManager
8
- } from "./chunk-CDZERT7Z.js";
13
+ } from "./chunk-VWNS6DH5.js";
9
14
  import {
10
15
  detectClaudeCli,
11
16
  launchClaude
12
- } from "./chunk-OYF4VIFI.js";
17
+ } from "./chunk-RUC7OULH.js";
13
18
  import {
14
- logger
15
- } from "./chunk-GEHQXLEI.js";
19
+ getLogger
20
+ } from "./chunk-6UIGZD2N.js";
16
21
 
17
22
  // src/lib/MergeManager.ts
18
23
  var MergeManager = class {
19
- constructor(settingsManager) {
24
+ constructor(settingsManager, metadataManager) {
20
25
  this.settingsManager = settingsManager ?? new SettingsManager();
26
+ this.metadataManager = metadataManager ?? new MetadataManager();
21
27
  }
22
28
  /**
23
- * Get the main branch name from settings (defaults to 'main')
24
- * @param worktreePath - Optional path to load settings from (defaults to process.cwd())
29
+ * Get the merge target branch for a loom
30
+ * Priority: parent loom metadata > configured main branch > 'main'
31
+ * @param worktreePath - Optional path to load settings/metadata from (defaults to process.cwd())
25
32
  * @private
26
33
  */
27
34
  async getMainBranch(worktreePath) {
28
- const settings = await this.settingsManager.loadSettings(worktreePath);
29
- return settings.mainBranch ?? "main";
35
+ return getMergeTargetBranch(worktreePath ?? process.cwd(), {
36
+ settingsManager: this.settingsManager,
37
+ metadataManager: this.metadataManager
38
+ });
30
39
  }
31
40
  /**
32
41
  * Rebase current branch on main with fail-fast on conflicts
@@ -39,7 +48,7 @@ var MergeManager = class {
39
48
  async rebaseOnMain(worktreePath, options = {}) {
40
49
  const { dryRun = false, force = false } = options;
41
50
  const mainBranch = await this.getMainBranch(worktreePath);
42
- logger.info(`Starting rebase on ${mainBranch} branch...`);
51
+ getLogger().info(`Starting rebase on ${mainBranch} branch...`);
43
52
  try {
44
53
  await executeGitCommand(["show-ref", "--verify", "--quiet", `refs/heads/${mainBranch}`], {
45
54
  cwd: worktreePath
@@ -53,10 +62,11 @@ Ensure the repository has a "${mainBranch}" branch or create it first.`
53
62
  const statusOutput = await executeGitCommand(["status", "--porcelain"], {
54
63
  cwd: worktreePath
55
64
  });
65
+ let wipCommitHash = null;
56
66
  if (statusOutput.trim()) {
57
- throw new Error(
58
- "Uncommitted changes detected. Please commit or stash changes before rebasing.\nRun: git status to see uncommitted changes\nOr: il finish will automatically commit them for you"
59
- );
67
+ getLogger().info("Uncommitted changes detected, creating temporary WIP commit...");
68
+ wipCommitHash = await this.createWipCommit(worktreePath);
69
+ getLogger().debug(`Created WIP commit: ${wipCommitHash}`);
60
70
  }
61
71
  const mergeBase = await executeGitCommand(["merge-base", mainBranch, "HEAD"], {
62
72
  cwd: worktreePath
@@ -67,7 +77,7 @@ Ensure the repository has a "${mainBranch}" branch or create it first.`
67
77
  const mergeBaseTrimmed = mergeBase.trim();
68
78
  const mainHeadTrimmed = mainHead.trim();
69
79
  if (mergeBaseTrimmed === mainHeadTrimmed) {
70
- logger.success(`Branch is already up to date with ${mainBranch}. No rebase needed.`);
80
+ getLogger().success(`Branch is already up to date with ${mainBranch}. No rebase needed.`);
71
81
  return;
72
82
  }
73
83
  const commitsOutput = await executeGitCommand(["log", "--oneline", `${mainBranch}..HEAD`], {
@@ -76,34 +86,40 @@ Ensure the repository has a "${mainBranch}" branch or create it first.`
76
86
  const commits = commitsOutput.trim();
77
87
  const commitLines = commits ? commits.split("\n") : [];
78
88
  if (commits) {
79
- logger.info(`Found ${commitLines.length} commit(s) to rebase:`);
80
- commitLines.forEach((commit) => logger.info(` ${commit}`));
89
+ getLogger().info(`Found ${commitLines.length} commit(s) to rebase:`);
90
+ commitLines.forEach((commit) => getLogger().info(` ${commit}`));
81
91
  } else {
82
- logger.info(`${mainBranch} branch has moved forward. Rebasing to update branch...`);
92
+ getLogger().info(`${mainBranch} branch has moved forward. Rebasing to update branch...`);
83
93
  }
84
94
  if (!force && !dryRun) {
85
- logger.info("Proceeding with rebase... (use --force to skip confirmations)");
95
+ getLogger().info("Proceeding with rebase... (use --force to skip confirmations)");
86
96
  }
87
97
  if (dryRun) {
88
- logger.info(`[DRY RUN] Would execute: git rebase ${mainBranch}`);
98
+ getLogger().info(`[DRY RUN] Would execute: git rebase ${mainBranch}`);
89
99
  if (commitLines.length > 0) {
90
- logger.info(`[DRY RUN] This would rebase ${commitLines.length} commit(s)`);
100
+ getLogger().info(`[DRY RUN] This would rebase ${commitLines.length} commit(s)`);
91
101
  }
92
102
  return;
93
103
  }
94
104
  try {
95
105
  await executeGitCommand(["rebase", mainBranch], { cwd: worktreePath });
96
- logger.success("Rebase completed successfully!");
106
+ getLogger().success("Rebase completed successfully!");
107
+ if (wipCommitHash) {
108
+ await this.restoreWipCommit(worktreePath, wipCommitHash);
109
+ }
97
110
  } catch (error) {
98
111
  const conflictedFiles = await this.detectConflictedFiles(worktreePath);
99
112
  if (conflictedFiles.length > 0) {
100
- logger.info("Merge conflicts detected, attempting Claude-assisted resolution...");
113
+ getLogger().info("Merge conflicts detected, attempting Claude-assisted resolution...");
101
114
  const resolved = await this.attemptClaudeConflictResolution(
102
115
  worktreePath,
103
116
  conflictedFiles
104
117
  );
105
118
  if (resolved) {
106
- logger.success("Conflicts resolved with Claude assistance, rebase completed");
119
+ getLogger().success("Conflicts resolved with Claude assistance, rebase completed");
120
+ if (wipCommitHash) {
121
+ await this.restoreWipCommit(worktreePath, wipCommitHash);
122
+ }
107
123
  return;
108
124
  }
109
125
  const conflictError = this.formatConflictError(conflictedFiles);
@@ -158,10 +174,20 @@ To fix this:
158
174
  */
159
175
  async performFastForwardMerge(branchName, worktreePath, options = {}) {
160
176
  const { dryRun = false, force = false } = options;
161
- logger.info("Starting fast-forward merge...");
162
- const mainWorktreePath = options.repoRoot ?? await findMainWorktreePathWithSettings(worktreePath, this.settingsManager);
177
+ getLogger().info("Starting fast-forward merge...");
163
178
  const mainBranch = await this.getMainBranch(worktreePath);
164
- logger.debug(`Using ${mainBranch} branch location: ${mainWorktreePath}`);
179
+ let mainWorktreePath;
180
+ if (options.repoRoot) {
181
+ mainWorktreePath = options.repoRoot;
182
+ } else {
183
+ try {
184
+ mainWorktreePath = await findWorktreeForBranch(mainBranch, worktreePath);
185
+ } catch {
186
+ getLogger().debug(`No worktree found for branch '${mainBranch}', falling back to settings-based lookup`);
187
+ mainWorktreePath = await findMainWorktreePathWithSettings(worktreePath, this.settingsManager);
188
+ }
189
+ }
190
+ getLogger().debug(`Using ${mainBranch} branch location: ${mainWorktreePath}`);
165
191
  const currentBranch = await executeGitCommand(["branch", "--show-current"], {
166
192
  cwd: mainWorktreePath
167
193
  });
@@ -178,24 +204,24 @@ This indicates the main worktree detection failed.`
178
204
  });
179
205
  const commits = commitsOutput.trim();
180
206
  if (!commits) {
181
- logger.success(`Branch is already merged into ${mainBranch}. No merge needed.`);
207
+ getLogger().success(`Branch has no commits ahead of ${mainBranch}. No merge needed.`);
182
208
  return;
183
209
  }
184
210
  const commitLines = commits.split("\n");
185
- logger.info(`Found ${commitLines.length} commit(s) to merge:`);
186
- commitLines.forEach((commit) => logger.info(` ${commit}`));
211
+ getLogger().info(`Found ${commitLines.length} commit(s) to merge:`);
212
+ commitLines.forEach((commit) => getLogger().info(` ${commit}`));
187
213
  if (!force && !dryRun) {
188
- logger.info("Proceeding with fast-forward merge... (use --force to skip confirmations)");
214
+ getLogger().info("Proceeding with fast-forward merge... (use --force to skip confirmations)");
189
215
  }
190
216
  if (dryRun) {
191
- logger.info(`[DRY RUN] Would execute: git merge --ff-only ${branchName}`);
192
- logger.info(`[DRY RUN] This would merge ${commitLines.length} commit(s)`);
217
+ getLogger().info(`[DRY RUN] Would execute: git merge --ff-only ${branchName}`);
218
+ getLogger().info(`[DRY RUN] This would merge ${commitLines.length} commit(s)`);
193
219
  return;
194
220
  }
195
221
  try {
196
- logger.debug(`Executing fast-forward merge of ${branchName} into ${mainBranch} using cwd: ${mainWorktreePath}...`);
222
+ getLogger().debug(`Executing fast-forward merge of ${branchName} into ${mainBranch} using cwd: ${mainWorktreePath}...`);
197
223
  await executeGitCommand(["merge", "--ff-only", branchName], { cwd: mainWorktreePath });
198
- logger.success(`Fast-forward merge completed! Merged ${commitLines.length} commit(s).`);
224
+ getLogger().success(`Fast-forward merge completed! Merged ${commitLines.length} commit(s).`);
199
225
  } catch (error) {
200
226
  throw new Error(
201
227
  `Fast-forward merge failed: ${error instanceof Error ? error.message : String(error)}
@@ -222,6 +248,39 @@ To recover:
222
248
  return [];
223
249
  }
224
250
  }
251
+ /**
252
+ * Create a temporary WIP commit to preserve uncommitted changes during rebase
253
+ * Stages all changes (tracked, untracked) using git add -A
254
+ * @param worktreePath - Path to the worktree
255
+ * @returns The commit hash of the WIP commit
256
+ * @private
257
+ */
258
+ async createWipCommit(worktreePath) {
259
+ await executeGitCommand(["add", "-A"], { cwd: worktreePath });
260
+ await executeGitCommand(["commit", "-m", "WIP: Auto-stash for rebase"], { cwd: worktreePath });
261
+ const hash = await executeGitCommand(["rev-parse", "HEAD"], { cwd: worktreePath });
262
+ return hash.trim();
263
+ }
264
+ /**
265
+ * Restore uncommitted changes from WIP commit via soft reset
266
+ * Logs warning but does not fail if soft reset fails (changes are safe in commit history)
267
+ * @param worktreePath - Path to the worktree
268
+ * @param wipCommitHash - Original WIP commit hash for verification logging
269
+ * @private
270
+ */
271
+ async restoreWipCommit(worktreePath, wipCommitHash) {
272
+ getLogger().info("Restoring uncommitted changes from WIP commit...");
273
+ try {
274
+ await executeGitCommand(["reset", "--soft", "HEAD~1"], { cwd: worktreePath });
275
+ await executeGitCommand(["reset", "HEAD"], { cwd: worktreePath });
276
+ getLogger().success("Restored uncommitted changes from WIP commit");
277
+ } catch (error) {
278
+ getLogger().warn(
279
+ `Failed to restore WIP commit (${wipCommitHash}). Your changes are safe in the commit history. Manual recovery: git reset --soft HEAD~1`,
280
+ { error: error instanceof Error ? error.message : String(error) }
281
+ );
282
+ }
283
+ }
225
284
  /**
226
285
  * Helper: Format conflict error message with manual resolution steps
227
286
  * @private
@@ -242,32 +301,34 @@ To recover:
242
301
  async attemptClaudeConflictResolution(worktreePath, conflictedFiles) {
243
302
  const isClaudeAvailable = await detectClaudeCli();
244
303
  if (!isClaudeAvailable) {
245
- logger.debug("Claude CLI not available, skipping conflict resolution");
304
+ getLogger().debug("Claude CLI not available, skipping conflict resolution");
246
305
  return false;
247
306
  }
248
- logger.info(`Launching Claude to resolve conflicts in ${conflictedFiles.length} file(s)...`);
249
- const prompt = `Please help resolve the git rebase conflicts in this repository. Analyze the conflicted files, understand the changes from both branches, fix the conflicts, then run 'git add .' to stage the resolved files, and finally run 'git rebase --continue' to continue the rebase process. Handle the entire workflow for me.`;
307
+ getLogger().info(`Launching Claude to resolve conflicts in ${conflictedFiles.length} file(s)...`);
308
+ const systemPrompt = `Please help resolve the git rebase conflicts in this repository. Analyze the conflicted files, understand the changes from both branches, fix the conflicts, then run 'git add .' to stage the resolved files, and finally run 'git rebase --continue' to continue the rebase process. Once the issue is resolved, tell the user they can use /exit to continue with the process.`;
309
+ const prompt = `Help me with this rebase please.`;
250
310
  try {
251
311
  await launchClaude(prompt, {
312
+ appendSystemPrompt: systemPrompt,
252
313
  addDir: worktreePath,
253
314
  headless: false
254
315
  // Interactive - runs in current terminal with stdio: inherit
255
316
  });
256
317
  const remainingConflicts = await this.detectConflictedFiles(worktreePath);
257
318
  if (remainingConflicts.length > 0) {
258
- logger.warn(
319
+ getLogger().warn(
259
320
  `Conflicts still exist in ${remainingConflicts.length} file(s) after Claude assistance`
260
321
  );
261
322
  return false;
262
323
  }
263
324
  const rebaseInProgress = await this.isRebaseInProgress(worktreePath);
264
325
  if (rebaseInProgress) {
265
- logger.warn("Rebase still in progress after Claude assistance");
326
+ getLogger().warn("Rebase still in progress after Claude assistance");
266
327
  return false;
267
328
  }
268
329
  return true;
269
330
  } catch (error) {
270
- logger.warn("Claude conflict resolution failed", {
331
+ getLogger().warn("Claude conflict resolution failed", {
271
332
  error: error instanceof Error ? error.message : String(error)
272
333
  });
273
334
  return false;
@@ -304,4 +365,4 @@ To recover:
304
365
  export {
305
366
  MergeManager
306
367
  };
307
- //# sourceMappingURL=chunk-2MAIX45J.js.map
368
+ //# sourceMappingURL=chunk-BIIQHEXJ.js.map