@iloom/cli 0.13.0-beta.0 → 0.13.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 (173) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +3 -18
  3. package/dist/{ClaudeContextManager-RRGREEZQ.js → ClaudeContextManager-ZH6LEA5I.js} +5 -5
  4. package/dist/{ClaudeService-LEPW6QAC.js → ClaudeService-YR66WXZN.js} +4 -4
  5. package/dist/{IssueTrackerFactory-KE2BDCLC.js → IssueTrackerFactory-O2ZBA666.js} +3 -3
  6. package/dist/{LoomLauncher-GKQMR5E6.js → LoomLauncher-V54ENBEF.js} +5 -5
  7. package/dist/{MetadataManager-V4LSJ2PB.js → MetadataManager-HHE6LQF2.js} +2 -2
  8. package/dist/{PromptTemplateManager-I75WKXM4.js → PromptTemplateManager-4RFELNYY.js} +2 -2
  9. package/dist/README.md +3 -18
  10. package/dist/{SettingsManager-KQU7OX7G.js → SettingsManager-SLSYEYDZ.js} +4 -4
  11. package/dist/agents/iloom-artifact-reviewer.md +1 -0
  12. package/dist/agents/iloom-code-reviewer.md +21 -0
  13. package/dist/agents/iloom-issue-analyze-and-plan.md +30 -12
  14. package/dist/agents/iloom-issue-analyzer.md +32 -7
  15. package/dist/agents/iloom-issue-complexity-evaluator.md +32 -12
  16. package/dist/agents/iloom-issue-implementer.md +31 -12
  17. package/dist/agents/iloom-issue-planner.md +30 -12
  18. package/dist/agents/iloom-wave-verifier.md +177 -4
  19. package/dist/{build-V3KADFMO.js → build-ZTGWDHWU.js} +8 -8
  20. package/dist/{chunk-VVQQIG64.js → chunk-55NTREIU.js} +33 -30
  21. package/dist/chunk-55NTREIU.js.map +1 -0
  22. package/dist/{chunk-AYLC633W.js → chunk-7TN5VW4I.js} +65 -7
  23. package/dist/chunk-7TN5VW4I.js.map +1 -0
  24. package/dist/{chunk-RFCAPHL5.js → chunk-C2BVNJW5.js} +2 -2
  25. package/dist/{chunk-3XEXT35Z.js → chunk-E5OM25WK.js} +3 -3
  26. package/dist/{chunk-ZUIFO7B4.js → chunk-ERMEYFT6.js} +7 -2
  27. package/dist/chunk-ERMEYFT6.js.map +1 -0
  28. package/dist/{chunk-WGUGB54H.js → chunk-F5NKWLMQ.js} +21 -24
  29. package/dist/chunk-F5NKWLMQ.js.map +1 -0
  30. package/dist/{chunk-TN2D2RX7.js → chunk-G2DGDCDP.js} +33 -224
  31. package/dist/chunk-G2DGDCDP.js.map +1 -0
  32. package/dist/{chunk-NUUFP53X.js → chunk-GPBX2BY2.js} +2 -2
  33. package/dist/{chunk-SN4S5CWL.js → chunk-GQDVH6FA.js} +2 -2
  34. package/dist/{chunk-YUOVWWJX.js → chunk-HKEXRZMU.js} +5 -310
  35. package/dist/chunk-HKEXRZMU.js.map +1 -0
  36. package/dist/{chunk-TAEVA4QR.js → chunk-HWDQRW3O.js} +3 -3
  37. package/dist/chunk-HWDQRW3O.js.map +1 -0
  38. package/dist/{chunk-KQSV7FOG.js → chunk-J5JOJPK3.js} +2 -2
  39. package/dist/{chunk-PD75ZCFT.js → chunk-KCAWSZUO.js} +18 -17
  40. package/dist/chunk-KCAWSZUO.js.map +1 -0
  41. package/dist/{chunk-QNPJXO53.js → chunk-KGOBNC5A.js} +4 -4
  42. package/dist/{chunk-H3T3EPF3.js → chunk-LNY2Y32V.js} +2 -2
  43. package/dist/{chunk-7RCUWU3I.js → chunk-MRPIDNZU.js} +1 -1
  44. package/dist/chunk-MRPIDNZU.js.map +1 -0
  45. package/dist/{chunk-QQULYI2S.js → chunk-N6DY47YN.js} +80 -45
  46. package/dist/chunk-N6DY47YN.js.map +1 -0
  47. package/dist/{chunk-VIQOQ463.js → chunk-OLJ54WGW.js} +15 -10
  48. package/dist/chunk-OLJ54WGW.js.map +1 -0
  49. package/dist/{chunk-4VQXMEEP.js → chunk-PPQ5LV7U.js} +3 -3
  50. package/dist/{chunk-4VQXMEEP.js.map → chunk-PPQ5LV7U.js.map} +1 -1
  51. package/dist/{chunk-QED2WB2D.js → chunk-PS6K2AOV.js} +5 -5
  52. package/dist/{chunk-JD3K2344.js → chunk-QNRXRSKC.js} +36 -3
  53. package/dist/chunk-QNRXRSKC.js.map +1 -0
  54. package/dist/{chunk-Q7VXHJP6.js → chunk-SM3BCHYB.js} +5 -5
  55. package/dist/{chunk-SA446KA2.js → chunk-T4KFKKEB.js} +7 -7
  56. package/dist/{chunk-XCP2WDYA.js → chunk-T4NESGYB.js} +3 -3
  57. package/dist/{chunk-QXGM32TO.js → chunk-TJDKGKQV.js} +2 -2
  58. package/dist/{chunk-X5DRLONY.js → chunk-UXBVDD7U.js} +6 -6
  59. package/dist/{chunk-JDN4SPV3.js → chunk-WYDLOQYO.js} +2 -2
  60. package/dist/{chunk-4JZEQBWV.js → chunk-XIVLGWUX.js} +3 -1
  61. package/dist/chunk-XIVLGWUX.js.map +1 -0
  62. package/dist/{chunk-NTDY5AMO.js → chunk-ZEFTWM5Z.js} +2 -2
  63. package/dist/{cleanup-RJKLI47I.js → cleanup-BCVY7PEF.js} +22 -22
  64. package/dist/cleanup-BCVY7PEF.js.map +1 -0
  65. package/dist/cli.js +126 -105
  66. package/dist/cli.js.map +1 -1
  67. package/dist/{commit-SUHRUMDE.js → commit-L5JNBU4U.js} +8 -8
  68. package/dist/{compile-2MD346PO.js → compile-GPJOHXH4.js} +8 -8
  69. package/dist/{contribute-P4BMRY7C.js → contribute-QEGCI4PS.js} +4 -4
  70. package/dist/{dev-server-ZNTLWOL5.js → dev-server-67NPVWUN.js} +247 -31
  71. package/dist/dev-server-67NPVWUN.js.map +1 -0
  72. package/dist/{feedback-Q6WG2WX4.js → feedback-2LWXKLQZ.js} +4 -4
  73. package/dist/{git-TX2IEMB3.js → git-IS7AV3ED.js} +4 -4
  74. package/dist/hooks/iloom-hook.js +40 -2
  75. package/dist/{ignite-P644W2PK.js → ignite-VQDJQ37S.js} +12 -14
  76. package/dist/index.d.ts +73 -75
  77. package/dist/index.js +32 -32
  78. package/dist/index.js.map +1 -1
  79. package/dist/{init-5HFY7JG6.js → init-7SDJUAEZ.js} +8 -8
  80. package/dist/{install-deps-J4ALTM27.js → install-deps-NGSFDNUW.js} +8 -8
  81. package/dist/{issues-LZMIF22U.js → issues-4HQKEUP7.js} +5 -5
  82. package/dist/{lint-XIXKU22H.js → lint-C5FOVRXY.js} +8 -8
  83. package/dist/mcp/issue-management-server.js +19 -22
  84. package/dist/mcp/issue-management-server.js.map +1 -1
  85. package/dist/neon-helpers-LCZAN4U4.js +11 -0
  86. package/dist/{open-KUO35JIJ.js → open-WUTLRI6S.js} +19 -15
  87. package/dist/open-WUTLRI6S.js.map +1 -0
  88. package/dist/{plan-7CF56OIR.js → plan-GC3HF73T.js} +86 -66
  89. package/dist/plan-GC3HF73T.js.map +1 -0
  90. package/dist/{projects-L5AHUBGA.js → projects-3F6T3KZL.js} +2 -2
  91. package/dist/prompts/init-prompt.txt +40 -36
  92. package/dist/prompts/issue-prompt.txt +4 -1
  93. package/dist/prompts/plan-prompt.txt +97 -16
  94. package/dist/prompts/regular-prompt.txt +1 -1
  95. package/dist/prompts/swarm-orchestrator-prompt.txt +25 -12
  96. package/dist/{rebase-MAMWPA2L.js → rebase-CSGQICAP.js} +7 -7
  97. package/dist/{recap-IDBO3KM5.js → recap-CKGKFDJL.js} +7 -7
  98. package/dist/{run-RGZHCQ6M.js → run-3YL2IXXI.js} +19 -15
  99. package/dist/run-3YL2IXXI.js.map +1 -0
  100. package/dist/schema/settings.schema.json +35 -31
  101. package/dist/{shell-7ADCDFIV.js → shell-M2YYPNGV.js} +6 -6
  102. package/dist/{summary-7J2HORFD.js → summary-XR4CBJEG.js} +9 -9
  103. package/dist/{test-SRB7EWU6.js → test-ESDAHEVE.js} +8 -8
  104. package/dist/{test-git-G7ATVIXG.js → test-git-KWPLHYSI.js} +4 -4
  105. package/dist/{test-jira-Q2HPA522.js → test-jira-6NK7UHSV.js} +3 -3
  106. package/dist/{test-prefix-JMDGXR5A.js → test-prefix-VVODGHXP.js} +4 -4
  107. package/dist/{test-webserver-GZFVXBGD.js → test-webserver-AHXKC6H4.js} +6 -6
  108. package/dist/{vscode-3I7ISHUU.js → vscode-OY7HOVRO.js} +6 -6
  109. package/package.json +1 -1
  110. package/dist/chunk-4JZEQBWV.js.map +0 -1
  111. package/dist/chunk-7RCUWU3I.js.map +0 -1
  112. package/dist/chunk-AYLC633W.js.map +0 -1
  113. package/dist/chunk-JD3K2344.js.map +0 -1
  114. package/dist/chunk-PD75ZCFT.js.map +0 -1
  115. package/dist/chunk-QQULYI2S.js.map +0 -1
  116. package/dist/chunk-TAEVA4QR.js.map +0 -1
  117. package/dist/chunk-TN2D2RX7.js.map +0 -1
  118. package/dist/chunk-VIQOQ463.js.map +0 -1
  119. package/dist/chunk-VVQQIG64.js.map +0 -1
  120. package/dist/chunk-WGUGB54H.js.map +0 -1
  121. package/dist/chunk-YUOVWWJX.js.map +0 -1
  122. package/dist/chunk-ZUIFO7B4.js.map +0 -1
  123. package/dist/cleanup-RJKLI47I.js.map +0 -1
  124. package/dist/database-helpers-PRDFNDRO.js +0 -11
  125. package/dist/dev-server-ZNTLWOL5.js.map +0 -1
  126. package/dist/open-KUO35JIJ.js.map +0 -1
  127. package/dist/plan-7CF56OIR.js.map +0 -1
  128. package/dist/run-RGZHCQ6M.js.map +0 -1
  129. /package/dist/{ClaudeContextManager-RRGREEZQ.js.map → ClaudeContextManager-ZH6LEA5I.js.map} +0 -0
  130. /package/dist/{ClaudeService-LEPW6QAC.js.map → ClaudeService-YR66WXZN.js.map} +0 -0
  131. /package/dist/{IssueTrackerFactory-KE2BDCLC.js.map → IssueTrackerFactory-O2ZBA666.js.map} +0 -0
  132. /package/dist/{LoomLauncher-GKQMR5E6.js.map → LoomLauncher-V54ENBEF.js.map} +0 -0
  133. /package/dist/{MetadataManager-V4LSJ2PB.js.map → MetadataManager-HHE6LQF2.js.map} +0 -0
  134. /package/dist/{PromptTemplateManager-I75WKXM4.js.map → PromptTemplateManager-4RFELNYY.js.map} +0 -0
  135. /package/dist/{SettingsManager-KQU7OX7G.js.map → SettingsManager-SLSYEYDZ.js.map} +0 -0
  136. /package/dist/{build-V3KADFMO.js.map → build-ZTGWDHWU.js.map} +0 -0
  137. /package/dist/{chunk-RFCAPHL5.js.map → chunk-C2BVNJW5.js.map} +0 -0
  138. /package/dist/{chunk-3XEXT35Z.js.map → chunk-E5OM25WK.js.map} +0 -0
  139. /package/dist/{chunk-NUUFP53X.js.map → chunk-GPBX2BY2.js.map} +0 -0
  140. /package/dist/{chunk-SN4S5CWL.js.map → chunk-GQDVH6FA.js.map} +0 -0
  141. /package/dist/{chunk-KQSV7FOG.js.map → chunk-J5JOJPK3.js.map} +0 -0
  142. /package/dist/{chunk-QNPJXO53.js.map → chunk-KGOBNC5A.js.map} +0 -0
  143. /package/dist/{chunk-H3T3EPF3.js.map → chunk-LNY2Y32V.js.map} +0 -0
  144. /package/dist/{chunk-QED2WB2D.js.map → chunk-PS6K2AOV.js.map} +0 -0
  145. /package/dist/{chunk-Q7VXHJP6.js.map → chunk-SM3BCHYB.js.map} +0 -0
  146. /package/dist/{chunk-SA446KA2.js.map → chunk-T4KFKKEB.js.map} +0 -0
  147. /package/dist/{chunk-XCP2WDYA.js.map → chunk-T4NESGYB.js.map} +0 -0
  148. /package/dist/{chunk-QXGM32TO.js.map → chunk-TJDKGKQV.js.map} +0 -0
  149. /package/dist/{chunk-X5DRLONY.js.map → chunk-UXBVDD7U.js.map} +0 -0
  150. /package/dist/{chunk-JDN4SPV3.js.map → chunk-WYDLOQYO.js.map} +0 -0
  151. /package/dist/{chunk-NTDY5AMO.js.map → chunk-ZEFTWM5Z.js.map} +0 -0
  152. /package/dist/{commit-SUHRUMDE.js.map → commit-L5JNBU4U.js.map} +0 -0
  153. /package/dist/{compile-2MD346PO.js.map → compile-GPJOHXH4.js.map} +0 -0
  154. /package/dist/{contribute-P4BMRY7C.js.map → contribute-QEGCI4PS.js.map} +0 -0
  155. /package/dist/{feedback-Q6WG2WX4.js.map → feedback-2LWXKLQZ.js.map} +0 -0
  156. /package/dist/{database-helpers-PRDFNDRO.js.map → git-IS7AV3ED.js.map} +0 -0
  157. /package/dist/{git-TX2IEMB3.js.map → ignite-VQDJQ37S.js.map} +0 -0
  158. /package/dist/{init-5HFY7JG6.js.map → init-7SDJUAEZ.js.map} +0 -0
  159. /package/dist/{install-deps-J4ALTM27.js.map → install-deps-NGSFDNUW.js.map} +0 -0
  160. /package/dist/{issues-LZMIF22U.js.map → issues-4HQKEUP7.js.map} +0 -0
  161. /package/dist/{lint-XIXKU22H.js.map → lint-C5FOVRXY.js.map} +0 -0
  162. /package/dist/{ignite-P644W2PK.js.map → neon-helpers-LCZAN4U4.js.map} +0 -0
  163. /package/dist/{projects-L5AHUBGA.js.map → projects-3F6T3KZL.js.map} +0 -0
  164. /package/dist/{rebase-MAMWPA2L.js.map → rebase-CSGQICAP.js.map} +0 -0
  165. /package/dist/{recap-IDBO3KM5.js.map → recap-CKGKFDJL.js.map} +0 -0
  166. /package/dist/{shell-7ADCDFIV.js.map → shell-M2YYPNGV.js.map} +0 -0
  167. /package/dist/{summary-7J2HORFD.js.map → summary-XR4CBJEG.js.map} +0 -0
  168. /package/dist/{test-SRB7EWU6.js.map → test-ESDAHEVE.js.map} +0 -0
  169. /package/dist/{test-git-G7ATVIXG.js.map → test-git-KWPLHYSI.js.map} +0 -0
  170. /package/dist/{test-jira-Q2HPA522.js.map → test-jira-6NK7UHSV.js.map} +0 -0
  171. /package/dist/{test-prefix-JMDGXR5A.js.map → test-prefix-VVODGHXP.js.map} +0 -0
  172. /package/dist/{test-webserver-GZFVXBGD.js.map → test-webserver-AHXKC6H4.js.map} +0 -0
  173. /package/dist/{vscode-3I7ISHUU.js.map → vscode-OY7HOVRO.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/LoomManager.ts","../src/lib/VSCodeIntegration.ts","../src/lib/EnvironmentManager.ts","../src/lib/CLIIsolationManager.ts","../src/lib/DatabaseManager.ts"],"sourcesContent":["import path from 'path'\nimport fs from 'fs-extra'\nimport fg from 'fast-glob'\nimport { GitWorktreeManager } from './GitWorktreeManager.js'\nimport type { IssueTracker } from './IssueTracker.js'\nimport type { BranchNamingService } from './BranchNamingService.js'\nimport { EnvironmentManager } from './EnvironmentManager.js'\nimport { ClaudeContextManager } from './ClaudeContextManager.js'\nimport { ProjectCapabilityDetector } from './ProjectCapabilityDetector.js'\nimport { CLIIsolationManager } from './CLIIsolationManager.js'\nimport { VSCodeIntegration } from './VSCodeIntegration.js'\nimport { SettingsManager } from './SettingsManager.js'\nimport { MetadataManager, type WriteMetadataInput } from './MetadataManager.js'\nimport { branchExists, executeGitCommand, ensureRepositoryHasCommits, extractIssueNumber, isFileTrackedByGit, extractPRNumber, PLACEHOLDER_COMMIT_PREFIX, pushBranchToRemote, GitCommandError, fetchOrigin } from '../utils/git.js'\nimport { GitHubService } from './GitHubService.js'\nimport { generateRandomSessionId } from '../utils/claude.js'\nimport { preAcceptClaudeTrust } from '../utils/claude-trust.js'\nimport { installDependencies } from '../utils/package-manager.js'\nimport { generateColorFromBranchName, selectDistinctColor, hexToRgb, type ColorData } from '../utils/color.js'\nimport { detectDarkMode } from '../utils/terminal.js'\nimport { DatabaseManager } from './DatabaseManager.js'\nimport { loadEnvIntoProcess, findEnvFileForDatabaseUrl, isNoEnvFilesFoundError } from '../utils/env.js'\nimport type { Loom, CreateLoomInput } from '../types/loom.js'\nimport type { GitWorktree } from '../types/worktree.js'\nimport type { Issue, PullRequest } from '../types/index.js'\nimport { getLogger } from '../utils/logger-context.js'\nimport { PRManager } from './PRManager.js'\nimport { VCSProviderFactory } from './VCSProviderFactory.js'\n\n/**\n * LoomManager orchestrates the creation and management of looms (isolated workspaces)\n * Bridges the gap between input validation and workspace operations\n */\nexport class LoomManager {\n private metadataManager: MetadataManager\n private githubService: GitHubService | undefined\n\n constructor(\n private gitWorktree: GitWorktreeManager,\n private issueTracker: IssueTracker,\n private branchNaming: BranchNamingService,\n private environment: EnvironmentManager,\n _claude: ClaudeContextManager, // Not stored - kept for DI compatibility, LoomLauncher creates its own\n private capabilityDetector: ProjectCapabilityDetector,\n private cliIsolation: CLIIsolationManager,\n private settings: SettingsManager,\n private database?: DatabaseManager,\n githubService?: GitHubService\n ) {\n this.metadataManager = new MetadataManager()\n this.githubService = githubService\n }\n\n /**\n * Get database branch name for a loom by reading its .env file\n * Returns null if database is not configured or branch cannot be determined\n *\n * @param loomPath - Path to the loom worktree\n */\n async getDatabaseBranchForLoom(loomPath: string): Promise<string | null> {\n if (!this.database) {\n return null\n }\n\n try {\n const envFilePath = path.join(loomPath, '.env')\n const settings = await this.settings.loadSettings()\n const databaseUrlVarName = settings.capabilities?.database?.databaseUrlEnvVarName ?? 'DATABASE_URL'\n\n // Get database connection string from loom's .env file\n const connectionString = await this.environment.getEnvVariable(envFilePath, databaseUrlVarName)\n\n if (!connectionString) {\n return null\n }\n\n return await this.database.getBranchNameFromConnectionString(connectionString, loomPath)\n } catch (error) {\n getLogger().debug(`Could not get database branch for loom at ${loomPath}: ${error instanceof Error ? error.message : 'Unknown error'}`)\n return null\n }\n }\n\n /**\n * Create a new loom (isolated workspace)\n * Orchestrates worktree creation, environment setup, and Claude context generation\n * NEW: Checks for existing worktrees and reuses them if found\n */\n async createIloom(input: CreateLoomInput): Promise<Loom> {\n // 1. Fetch issue/PR data if needed\n getLogger().info('Fetching issue data...')\n const issueData = await this.fetchIssueData(input)\n\n // NEW: Check for existing worktree BEFORE generating branch name (for efficiency)\n if (input.type === 'issue' || input.type === 'epic' || input.type === 'pr' || input.type === 'branch') {\n getLogger().info('Checking for existing worktree...')\n const existing = await this.findExistingIloom(input, issueData)\n if (existing) {\n getLogger().success(`Found existing worktree, reusing: ${existing.path}`)\n return await this.reuseIloom(existing, input, issueData)\n }\n getLogger().info('No existing worktree found, creating new one...')\n }\n\n // 2. Generate or validate branch name\n getLogger().info('Preparing branch name...')\n const branchName = await this.prepareBranchName(input, issueData)\n\n // 3. Create git worktree (WITHOUT dependency installation)\n getLogger().info('Creating git worktree...')\n const worktreePath = await this.createWorktreeOnly(input, branchName, issueData)\n\n // 4. Load main .env variables into process.env (like bash script lines 336-339)\n this.loadMainEnvFile()\n\n // 5. Detect project capabilities\n const { capabilities, binEntries } = await this.capabilityDetector.detectCapabilities(worktreePath)\n\n // 6. Copy environment files (.env) - ALWAYS done regardless of capabilities\n await this.copyEnvironmentFiles(worktreePath)\n\n // 7. Copy Loom settings (settings.local.json) - ALWAYS done regardless of capabilities\n await this.copyIloomSettings(worktreePath)\n\n // 7.1. Copy iloom package local config (package.iloom.local.json)\n await this.copyIloomPackageLocal(worktreePath)\n\n // 7.5. Copy Claude settings (.claude/settings.local.json) - ALWAYS done regardless of capabilities\n await this.copyClaudeSettings(worktreePath)\n\n // 7.6. Copy gitignored files matching configured patterns\n await this.copyGitIgnoredFiles(worktreePath)\n\n // 8. Setup PORT environment variable - ONLY for web projects\n // Load base port from settings\n const settingsData = await this.settings.loadSettings()\n const basePort = settingsData.capabilities?.web?.basePort ?? 3000\n\n let port = basePort // default\n if (capabilities.includes('web')) {\n port = await this.setupPortForWeb(worktreePath, input, basePort)\n }\n\n // 9. Install dependencies AFTER environment setup (like bash script line 757-769)\n try {\n await installDependencies(worktreePath, true, true)\n } catch (error) {\n // Log warning but don't fail - matches bash script behavior\n getLogger().warn(`Failed to install dependencies: ${error instanceof Error ? error.message : 'Unknown error'}`, error)\n }\n\n // 10. Setup database branch if configured\n let databaseBranch: string | undefined = undefined\n if (this.database && !input.options?.skipDatabase) {\n try {\n const connectionString = await this.database.createBranchIfConfigured(\n branchName,\n worktreePath, // workspace path - checks all dotenv-flow files\n undefined, // cwd\n input.parentLoom?.databaseBranch // fromBranch - use parent's database branch for child looms\n )\n\n if (connectionString) {\n const varName = this.database.getConfiguredVariableName()\n const targetFile = await findEnvFileForDatabaseUrl(\n worktreePath,\n varName,\n isFileTrackedByGit,\n async (p) => fs.pathExists(p),\n async (p, v) => this.environment.getEnvVariable(p, v)\n )\n await this.environment.setEnvVar(\n path.join(worktreePath, targetFile),\n varName,\n connectionString\n )\n getLogger().success('Database branch configured')\n databaseBranch = branchName\n }\n } catch (error) {\n getLogger().error(\n `Failed to setup database branch: ${error instanceof Error ? error.message : 'Unknown error'}`\n )\n throw error // Database creation failures are fatal\n }\n }\n\n // 10. Setup CLI isolation if project has CLI capability\n // Skip in branch mode - branch mode workspaces don't have a built dist/cli.js\n let cliSymlinks: string[] | undefined = undefined\n if (capabilities.includes('cli') && input.type !== 'branch') {\n try {\n cliSymlinks = await this.cliIsolation.setupCLIIsolation(\n worktreePath,\n input.identifier,\n binEntries\n )\n } catch (error) {\n // Log warning but don't fail - matches dependency installation behavior\n getLogger().warn(\n `Failed to setup CLI isolation: ${error instanceof Error ? error.message : 'Unknown error'}`,\n error\n )\n }\n }\n\n // 10.5. Handle draft-pr mode - push branch and create draft PR\n let draftPrNumber: number | undefined = undefined\n let draftPrUrl: string | undefined = undefined\n\n const mergeBehavior = settingsData.mergeBehavior ?? { mode: 'local' }\n\n if (mergeBehavior.mode === 'draft-pr' && (input.type === 'issue' || input.type === 'epic' || input.type === 'branch')) {\n const prManager = new PRManager(settingsData)\n\n // Fetch from origin to get latest remote branch state\n // These git operations run regardless of whether the provider supports draft PRs\n getLogger().info('Fetching from origin...')\n await executeGitCommand(['fetch', 'origin'], { cwd: worktreePath })\n\n // Check if remote branch already exists\n let remoteBranchExists = false\n try {\n await executeGitCommand(['rev-parse', '--verify', `origin/${branchName}`], { cwd: worktreePath })\n remoteBranchExists = true\n getLogger().info(`Remote branch origin/${branchName} already exists, resetting local to match...`)\n } catch (error: unknown) {\n // Only treat as \"branch doesn't exist\" if it's a GitCommandError with the expected error patterns\n // Git rev-parse returns exit code 128 for missing refs with messages like:\n // \"fatal: Needed a single revision\" or \"unknown revision\"\n if (error instanceof GitCommandError &&\n (error.stderr.includes('unknown revision') ||\n error.stderr.includes('Needed a single revision') ||\n error.stderr.includes('bad revision'))) {\n // Remote branch doesn't exist - this is the normal case for new branches\n getLogger().debug(`Remote branch origin/${branchName} does not exist`)\n } else {\n // Re-throw unexpected errors (e.g., git crash, permissions, lock file issues)\n throw error\n }\n }\n\n // If remote branch exists, reset local branch to match it (preserves previous work)\n if (remoteBranchExists) {\n await executeGitCommand(['reset', '--hard', `origin/${branchName}`], { cwd: worktreePath })\n await executeGitCommand(['branch', '--set-upstream-to', `origin/${branchName}`], { cwd: worktreePath })\n getLogger().success('Local branch reset to match remote')\n } else {\n // Only create placeholder commit if remote branch didn't exist\n // (if we reset to remote, we already have commits)\n getLogger().info('Creating placeholder commit for draft PR...')\n await executeGitCommand(\n [\n 'commit',\n '--allow-empty',\n '--no-verify',\n '-m',\n `${PLACEHOLDER_COMMIT_PREFIX} Temporary commit for draft PR (will be removed on finish)`\n ],\n { cwd: worktreePath }\n )\n getLogger().debug('Placeholder commit created')\n\n // Push branch to remote (required for draft PR creation)\n getLogger().info('Pushing branch to remote for draft PR...')\n await pushBranchToRemote(branchName, worktreePath, { dryRun: false })\n\n // Remove placeholder from local history - it only needs to exist on remote to keep draft PR open.\n await executeGitCommand(['reset', '--soft', 'HEAD~1'], { cwd: worktreePath })\n getLogger().debug('Placeholder commit removed from local branch (still on remote)')\n }\n\n // Only create draft PR if the VCS provider supports it (or no VCS provider override is configured)\n const vcsProvider = VCSProviderFactory.create(settingsData)\n if (vcsProvider !== null && !vcsProvider.supportsDraftPRs) {\n getLogger().info('VCS provider does not support draft PRs, skipping draft PR creation at start time')\n } else {\n // Check for existing draft PR before creating a new one\n const existingPR = await prManager.checkForExistingPR(branchName, worktreePath)\n\n if (existingPR) {\n // Reuse existing PR\n draftPrNumber = existingPR.number\n draftPrUrl = existingPR.url\n getLogger().success(`Found existing PR: ${existingPR.url}`)\n } else {\n // Generate PR title and body\n // For issue mode: use issue title and reference issue number\n // For branch mode: use branch name and generic description\n const prTitle = issueData?.title ?? `Work on ${branchName}`\n let prBody: string\n if (input.type === 'issue' || input.type === 'epic') {\n const issueBody = issueData?.body ? `\\n\\n## ${issueData.title}\\n\\n${issueData.body}` : ''\n prBody = `Fixes ${prManager.issuePrefix}${input.identifier}${issueBody}\\n\\n---\\n*This PR was created automatically by iloom.*`\n } else {\n prBody = `Branch: ${branchName}\\n\\n---\\n*This PR was created automatically by iloom.*`\n }\n\n // Create draft PR\n // For child looms, target the parent branch; otherwise use the configured main branch\n const draftBaseBranch = input.parentLoom?.branchName ?? settingsData.mainBranch ?? 'main'\n getLogger().info('Creating draft PR...')\n const prResult = await prManager.createDraftPR(\n branchName,\n prTitle,\n prBody,\n draftBaseBranch,\n worktreePath\n )\n\n draftPrNumber = prResult.number\n draftPrUrl = prResult.url\n getLogger().success(`Draft PR created: ${prResult.url}`)\n }\n } // end else (provider supports draft PRs)\n }\n\n // 11. Select color with collision avoidance\n // Get hex colors in use from ALL stored looms across all projects (global collision detection)\n // This prevents color reuse across different repositories for the same user\n const allMetadata = await this.metadataManager.listAllMetadata()\n const usedHexColors: string[] = allMetadata\n .filter((metadata) => metadata.colorHex !== null)\n .map((metadata) => metadata.colorHex as string)\n\n // Detect dark mode and select appropriate color palette\n const themeMode = await detectDarkMode()\n\n // Select distinct color using hex-based comparison\n const colorData = selectDistinctColor(branchName, usedHexColors, themeMode)\n getLogger().debug(`Selected color ${colorData.hex} for branch ${branchName} (${usedHexColors.length} colors in use globally)`)\n\n // Apply color synchronization (terminal and VSCode) based on settings\n try {\n await this.applyColorSynchronization(worktreePath, branchName, colorData, settingsData, input.options)\n } catch (error) {\n // Log warning but don't fail - colors are cosmetic\n getLogger().warn(\n `Failed to apply color synchronization: ${error instanceof Error ? error.message : 'Unknown error'}`,\n error\n )\n }\n\n // NEW: Move issue to In Progress (for new worktrees)\n if (input.type === 'issue' || input.type === 'epic') {\n try {\n getLogger().info('Moving issue to In Progress...')\n // Check if provider supports this optional method\n if (this.issueTracker.moveIssueToInProgress) {\n await this.issueTracker.moveIssueToInProgress(input.identifier as number)\n }\n } catch (error) {\n // Warn but don't fail - matches bash script behavior\n getLogger().warn(\n `Failed to move issue to In Progress: ${error instanceof Error ? error.message : 'Unknown error'}`,\n error\n )\n }\n }\n\n // 11.5. Launch workspace components based on individual flags\n const enableClaude = input.options?.enableClaude !== false\n const enableCode = input.options?.enableCode !== false\n const enableDevServer = input.options?.enableDevServer !== false\n const enableTerminal = input.options?.enableTerminal ?? false\n const oneShot = input.options?.oneShot ?? 'default'\n const complexity = input.options?.complexity\n const setArguments = input.options?.setArguments\n const executablePath = input.options?.executablePath\n\n // Only launch if at least one component is enabled\n if (enableClaude || enableCode || enableDevServer || enableTerminal) {\n const { LoomLauncher } = await import('./LoomLauncher.js')\n const { ClaudeContextManager } = await import('./ClaudeContextManager.js')\n\n // Create ClaudeContextManager with shared SettingsManager to ensure CLI overrides work\n const claudeContext = new ClaudeContextManager(undefined, undefined, this.settings)\n const launcher = new LoomLauncher(claudeContext, this.settings)\n\n await launcher.launchLoom({\n enableClaude,\n enableCode,\n enableDevServer,\n enableTerminal,\n worktreePath,\n branchName,\n port,\n capabilities,\n workflowType: input.type === 'branch' ? 'regular' : input.type === 'epic' ? 'issue' : input.type,\n identifier: input.identifier,\n ...(issueData?.title && { title: issueData.title }),\n oneShot,\n ...(complexity && { complexity }),\n ...(setArguments && { setArguments }),\n ...(executablePath && { executablePath }),\n sourceEnvOnStart: settingsData.sourceEnvOnStart ?? false,\n colorTerminal: input.options?.colorTerminal ?? settingsData.colors?.terminal ?? true,\n colorHex: colorData.hex,\n })\n }\n\n // 12. Write loom metadata (spec section 3.1)\n // Derive description from issue/PR title or branch name\n const description = issueData?.title ?? branchName\n\n // Build issue/pr numbers arrays based on type\n // For PR workflows, extract issue number from branch name if present\n let issue_numbers: string[] = []\n let extractedIssueNum: string | null = null\n if (input.type === 'issue' || input.type === 'epic') {\n issue_numbers = [String(input.identifier)]\n } else if (input.type === 'pr') {\n extractedIssueNum = extractIssueNumber(branchName)\n if (extractedIssueNum) {\n issue_numbers = [extractedIssueNum]\n }\n }\n const pr_numbers: string[] = input.type === 'pr' ? [String(input.identifier)] : []\n\n // If a draft PR was created, add its number to pr_numbers\n // This ensures pr_numbers and prUrls are consistent (fixes #555)\n if (draftPrNumber && !pr_numbers.includes(String(draftPrNumber))) {\n pr_numbers.push(String(draftPrNumber))\n }\n\n // Generate random session ID for Claude Code resume support\n // Each loom gets a unique session ID, enabling fresh Claude sessions\n const sessionId = generateRandomSessionId()\n\n // Build issueUrls/prUrls based on workflow type\n // For PR workflows, construct issue URL by replacing /pull/N with /issues/M\n let issueUrls: Record<string, string> = {}\n if ((input.type === 'issue' || input.type === 'epic') && issueData?.url) {\n issueUrls = { [String(input.identifier)]: issueData.url }\n } else if (input.type === 'pr' && extractedIssueNum && issueData?.url) {\n const issueUrl = issueData.url.replace(`/pull/${input.identifier}`, `/issues/${extractedIssueNum}`)\n issueUrls = { [extractedIssueNum]: issueUrl }\n }\n // Include draft PR URL in prUrls if created\n const prUrls: Record<string, string> = draftPrNumber && draftPrUrl\n ? { [String(draftPrNumber)]: draftPrUrl }\n : input.type === 'pr' && issueData?.url\n ? { [String(input.identifier)]: issueData.url }\n : {}\n\n const metadataInput: WriteMetadataInput = {\n description,\n branchName,\n worktreePath,\n issueType: input.type,\n ...((input.type === 'issue' || input.type === 'epic') && { issueKey: this.issueTracker.normalizeIdentifier(input.identifier) }),\n issue_numbers,\n pr_numbers,\n issueTracker: this.issueTracker.providerName,\n colorHex: colorData.hex,\n sessionId,\n projectPath: this.gitWorktree.workingDirectory,\n issueUrls,\n prUrls,\n capabilities,\n ...(draftPrNumber && { draftPrNumber }),\n ...(input.options?.oneShot && { oneShot: input.options.oneShot }),\n ...(input.options?.complexity && { complexity: input.options.complexity }),\n ...(input.options?.childIssueNumbers && input.options.childIssueNumbers.length > 0 && { childIssueNumbers: input.options.childIssueNumbers }),\n ...(input.options?.childIssues && input.options.childIssues.length > 0 && { childIssues: input.options.childIssues }),\n ...(input.options?.dependencyMap && Object.keys(input.options.dependencyMap).length > 0 && { dependencyMap: input.options.dependencyMap }),\n ...(input.parentLoom && { parentLoom: input.parentLoom }),\n }\n await this.metadataManager.writeMetadata(worktreePath, metadataInput)\n\n // 13. Create and return loom metadata\n const loom: Loom = {\n id: this.generateLoomId(input),\n path: worktreePath,\n branch: branchName,\n type: input.type,\n identifier: input.identifier,\n port,\n description,\n createdAt: new Date(),\n lastAccessed: new Date(),\n ...(databaseBranch !== undefined && { databaseBranch }),\n ...(capabilities.length > 0 && { capabilities }),\n ...(Object.keys(binEntries).length > 0 && { binEntries }),\n ...(cliSymlinks && cliSymlinks.length > 0 && { cliSymlinks }),\n ...(issueData !== null && {\n issueData: {\n title: issueData.title,\n body: issueData.body,\n url: issueData.url,\n state: issueData.state,\n },\n }),\n }\n\n getLogger().success(`Created loom: ${loom.id} at ${loom.path}`)\n return loom\n }\n\n /**\n * Finish a loom (merge work and cleanup)\n * Not yet implemented - see Issue #7\n */\n async finishIloom(_identifier: string): Promise<void> {\n throw new Error('Not implemented - see Issue #7')\n }\n\n\n /**\n * List all active looms\n */\n async listLooms(): Promise<Loom[]> {\n const worktrees = await this.gitWorktree.listWorktrees()\n if (!worktrees) {\n return []\n }\n return await this.mapWorktreesToLooms(worktrees)\n }\n\n /**\n * Find a specific loom by identifier\n * Case-insensitive matching for Linear IDs (MARK-1 vs mark-1)\n */\n async findIloom(identifier: string): Promise<Loom | null> {\n const looms = await this.listLooms()\n const lowerIdentifier = identifier.toLowerCase()\n return (\n looms.find(\n h =>\n h.id.toLowerCase() === lowerIdentifier ||\n h.identifier.toString().toLowerCase() === lowerIdentifier ||\n h.branch.toLowerCase() === lowerIdentifier\n ) ?? null\n )\n }\n\n /**\n * Find child looms for a given parent loom\n * Child looms are worktrees created with the parent loom as their base\n *\n * @param parentBranchName - The parent loom's branch name\n * @returns Array of child loom worktrees\n */\n async findChildLooms(parentBranchName: string): Promise<GitWorktree[]> {\n try {\n const worktrees = await this.gitWorktree.listWorktrees()\n if (!worktrees) {\n return []\n }\n\n // Use metadata-based detection: find all looms whose parentLoom.branchName matches\n const allMetadata = await this.metadataManager.listAllMetadata()\n const childBranches = new Set(\n allMetadata\n .filter(m => m.parentLoom?.branchName === parentBranchName)\n .map(m => m.branchName)\n .filter((b): b is string => b != null),\n )\n\n return worktrees.filter(wt => childBranches.has(wt.branch))\n } catch (error) {\n getLogger().debug(`Failed to find child looms: ${error instanceof Error ? error.message : 'Unknown error'}`)\n return []\n }\n }\n\n /**\n * Check for child looms and warn user if any exist\n * This is useful before finishing or cleaning up a parent loom\n *\n * @param branchName - Optional branch name to check. If not provided, uses current branch.\n * @returns true if child looms were found, false otherwise\n */\n async checkAndWarnChildLooms(branchName?: string): Promise<boolean> {\n // Use provided branch name or get current branch\n let targetBranch: string | null | undefined = branchName\n if (!targetBranch) {\n const { getCurrentBranch } = await import('../utils/git.js')\n targetBranch = await getCurrentBranch()\n }\n\n // Skip if not on a branch\n if (!targetBranch) {\n return false\n }\n\n const childLooms = await this.findChildLooms(targetBranch)\n if (childLooms.length > 0) {\n getLogger().warn(`Found ${childLooms.length} child loom(s) that should be finished first:`)\n for (const child of childLooms) {\n getLogger().warn(` - ${child.path}`)\n }\n getLogger().warn('')\n getLogger().warn('To finish child looms:')\n for (const child of childLooms) {\n // Extract identifier from child branch for finish command\n // Check PR first since PR branches often contain issue numbers too\n const prMatch = child.branch.match(/_pr_(\\d+)/)\n const issueId = extractIssueNumber(child.branch)\n\n const childIdentifier = prMatch\n ? prMatch[1] // PR: use number\n : issueId ?? child.branch // Issue: use extracted ID (alphanumeric or numeric), or branch name\n\n getLogger().warn(` il finish ${childIdentifier}`)\n }\n getLogger().warn('')\n return true\n }\n\n return false\n }\n\n /**\n * Fetch issue/PR data based on input type\n */\n private async fetchIssueData(\n input: CreateLoomInput\n ): Promise<Issue | PullRequest | null> {\n if (input.type === 'issue' || input.type === 'epic') {\n return await this.issueTracker.fetchIssue(input.identifier as number)\n } else if (input.type === 'pr') {\n // Use issue tracker if it supports PRs\n if (this.issueTracker.supportsPullRequests && this.issueTracker.fetchPR) {\n return await this.issueTracker.fetchPR(input.identifier as number)\n }\n // Use injected GitHubService if available\n if (this.githubService) {\n return await this.githubService.fetchPR(input.identifier as number)\n }\n // Create GitHubService on demand for PR fetching\n const github = new GitHubService()\n return await github.fetchPR(input.identifier as number)\n }\n return null\n }\n\n /**\n * Prepare branch name based on input type and issue/PR data\n */\n private async prepareBranchName(\n input: CreateLoomInput,\n issueData: Issue | PullRequest | null\n ): Promise<string> {\n if (input.type === 'branch') {\n return input.identifier as string\n }\n\n if (input.type === 'pr' && issueData && 'branch' in issueData) {\n return issueData.branch\n }\n\n if ((input.type === 'issue' || input.type === 'epic') && issueData) {\n // Use BranchNamingService for AI-powered branch name generation\n const branchName = await this.branchNaming.generateBranchName({\n issueNumber: input.identifier as number,\n title: issueData.title,\n })\n return branchName\n }\n\n // Fallback for edge cases\n if (input.type === 'pr') {\n return `pr-${input.identifier}`\n }\n\n throw new Error(`Unable to determine branch name for input type: ${input.type}`)\n }\n\n /**\n * Create worktree for the loom (without dependency installation)\n */\n private async createWorktreeOnly(\n input: CreateLoomInput,\n branchName: string,\n issueData?: Issue | PullRequest | null\n ): Promise<string> {\n // Ensure repository has at least one commit (needed for worktree creation)\n // This handles the case where the repo is completely empty (post git init, pre-first commit)\n getLogger().info('Ensuring repository has initial commit...')\n await ensureRepositoryHasCommits(this.gitWorktree.workingDirectory)\n\n // Load worktree prefix from settings\n const settingsData = await this.settings.loadSettings()\n let worktreePrefix = settingsData.worktreePrefix\n\n // If this is a child loom, compute dynamic prefix based on parent\n if (input.parentLoom) {\n // Sanitize branch name for directory use\n const sanitizedBranchName = input.parentLoom.branchName\n .replace(/\\//g, '-')\n .replace(/[^a-zA-Z0-9-_]/g, '-')\n worktreePrefix = `${sanitizedBranchName}-looms/`\n getLogger().info(`Creating child loom with prefix: ${worktreePrefix}`)\n }\n\n // Build options object, only including prefix if it's defined\n const pathOptions: { isPR?: boolean; prNumber?: number; prefix?: string } =\n input.type === 'pr'\n ? { isPR: true, prNumber: input.identifier as number }\n : {}\n\n if (worktreePrefix !== undefined) {\n pathOptions.prefix = worktreePrefix\n }\n\n const worktreePath = this.gitWorktree.generateWorktreePath(\n branchName,\n undefined,\n pathOptions\n )\n\n // Detect if this is a fork PR\n const isForkPR = input.type === 'pr' && issueData && 'isFork' in issueData && (issueData as PullRequest).isFork === true\n\n // Fetch all remote branches to ensure we have latest refs (especially for PRs)\n // Ports: bash script lines 667-674\n if (input.type === 'pr') {\n if (isForkPR) {\n // Fork PR: fetch the specific PR ref since the branch doesn't exist on origin\n getLogger().info(`Fetching PR #${input.identifier} ref from origin...`)\n try {\n await executeGitCommand(\n ['fetch', 'origin', `refs/pull/${input.identifier}/head`],\n { cwd: this.gitWorktree.workingDirectory }\n )\n getLogger().success('Successfully fetched PR ref from remote')\n } catch (error) {\n throw new Error(\n `Failed to fetch PR ref: ${error instanceof Error ? error.message : 'Unknown error'}. ` +\n `Make sure you have access to the repository.`\n )\n }\n } else {\n getLogger().info('Fetching all remote branches...')\n try {\n await executeGitCommand(['fetch', 'origin'], { cwd: this.gitWorktree.workingDirectory })\n getLogger().success('Successfully fetched from remote')\n } catch (error) {\n throw new Error(\n `Failed to fetch from remote: ${error instanceof Error ? error.message : 'Unknown error'}. ` +\n `Make sure you have access to the repository.`\n )\n }\n }\n }\n\n // Check if branch exists locally only (used for different purposes depending on type)\n // Pass false for includeRemote to only check local branches - remote branch existence\n // is handled separately in draft-pr mode\n const branchExistedLocally = await branchExists(branchName, process.cwd(), false)\n\n // For non-PRs, throw error if branch exists\n // For PRs, we'll use this to determine if we need to reset later\n if (input.type !== 'pr' && branchExistedLocally) {\n throw new Error(\n `Cannot create worktree: branch '${branchName}' already exists. ` +\n `Use 'git branch -D ${branchName}' to delete it first if needed.`\n )\n }\n\n // Determine base branch based on loom type and merge mode:\n // - Child looms: use parent's local branch (parent may not be pushed yet)\n // - PR modes (pr, draft-pr) for non-child, non-PR type: fetch and use origin/{mainBranch}\n // - Local mode or PR type: use explicit baseBranch or default (main)\n const mergeBehavior = settingsData.mergeBehavior ?? { mode: 'local' }\n const isPRMode = mergeBehavior.mode === 'pr' || mergeBehavior.mode === 'draft-pr'\n const isChildLoom = !!input.parentLoom\n\n let baseBranch: string | undefined\n\n if (isChildLoom) {\n // Child looms: use parent's local branch (no fetch - parent may not be pushed)\n baseBranch = input.parentLoom?.branchName ?? input.baseBranch\n } else if (isPRMode && input.type !== 'pr') {\n // PR modes (non-child, non-PR type): fetch origin and branch from origin/{mainBranch}\n getLogger().info('Fetching from origin to ensure latest main branch...')\n await fetchOrigin(this.gitWorktree.workingDirectory)\n\n const mainBranch = settingsData.mainBranch ?? 'main'\n baseBranch = `origin/${mainBranch}`\n getLogger().info(`Branching from ${baseBranch}`)\n } else {\n // Local mode or PR type: use explicit baseBranch or default (main)\n baseBranch = input.baseBranch\n }\n\n if (isForkPR) {\n // Fork PR: create a new local branch from FETCH_HEAD (the PR ref we just fetched)\n // If the branch already exists locally (e.g. re-running il start on the same fork PR),\n // delete it first since createBranch (-b) would fail\n if (branchExistedLocally) {\n await executeGitCommand(['branch', '-D', branchName], { cwd: this.gitWorktree.workingDirectory })\n }\n await this.gitWorktree.createWorktree({\n path: worktreePath,\n branch: branchName,\n createBranch: true,\n baseBranch: 'FETCH_HEAD',\n })\n // No reset or upstream tracking needed for fork PRs - there's no remote branch on origin\n } else {\n await this.gitWorktree.createWorktree({\n path: worktreePath,\n branch: branchName,\n createBranch: input.type !== 'pr', // PRs use existing branches\n ...(baseBranch && { baseBranch }),\n })\n\n // Reset PR branch to match remote exactly (if we created a new local branch)\n // Ports: bash script lines 689-713\n if (input.type === 'pr' && !branchExistedLocally) {\n getLogger().info('Resetting new PR branch to match remote exactly...')\n try {\n await executeGitCommand(['reset', '--hard', `origin/${branchName}`], { cwd: worktreePath })\n await executeGitCommand(['branch', '--set-upstream-to', `origin/${branchName}`], { cwd: worktreePath })\n getLogger().success('Successfully reset to match remote')\n } catch (error) {\n getLogger().warn(`Failed to reset to match remote: ${error instanceof Error ? error.message : 'Unknown error'}`)\n }\n }\n }\n\n // Pre-accept Claude Code trust for the new worktree path\n try {\n await preAcceptClaudeTrust(worktreePath)\n } catch (error) {\n getLogger().warn(`Failed to pre-accept Claude trust: ${error instanceof Error ? error.message : String(error)}`)\n }\n\n return worktreePath\n }\n\n /**\n * Copy user application environment files (.env) from main repo to worktree\n * Copies all dotenv-flow patterns: .env, .env.local, .env.{NODE_ENV}, .env.{NODE_ENV}.local\n * Only copies files that exist and are NOT tracked by git (tracked files exist via worktree)\n * Always called regardless of project capabilities\n */\n private async copyEnvironmentFiles(worktreePath: string): Promise<void> {\n const mainWorkspacePath = this.gitWorktree.workingDirectory\n const nodeEnv = process.env.DOTENV_FLOW_NODE_ENV ?? 'development'\n\n // Define all dotenv-flow patterns to copy\n const envFilePatterns = [\n '.env',\n '.env.local',\n `.env.${nodeEnv}`,\n `.env.${nodeEnv}.local`\n ]\n\n for (const pattern of envFilePatterns) {\n try {\n const mainEnvPath = path.join(mainWorkspacePath, pattern)\n const worktreeEnvPath = path.join(worktreePath, pattern)\n\n // Skip if file doesn't exist in main workspace\n if (!(await fs.pathExists(mainEnvPath))) {\n continue\n }\n\n // Skip if file is tracked by git (it will exist in worktree via git)\n if (await isFileTrackedByGit(pattern, mainWorkspacePath)) {\n getLogger().debug(`Skipping ${pattern} (tracked by git, already in worktree)`)\n continue\n }\n\n // Skip if file already exists in worktree\n if (await fs.pathExists(worktreeEnvPath)) {\n getLogger().warn(`${pattern} already exists in worktree, skipping copy`)\n continue\n }\n\n // Copy the untracked env file\n await this.environment.copyIfExists(mainEnvPath, worktreeEnvPath)\n getLogger().debug(`Copied ${pattern} to worktree`)\n } catch (error) {\n // Handle gracefully if individual file fails to copy\n getLogger().warn(`Warning: Failed to copy ${pattern}: ${error instanceof Error ? error.message : 'Unknown error'}`)\n }\n }\n }\n\n /**\n * Copy iloom configuration (settings.local.json) from main repo to worktree\n * Always called regardless of project capabilities\n * @param worktreePath Path to the worktree\n */\n private async copyIloomSettings(worktreePath: string): Promise<void> {\n const mainSettingsLocalPath = path.join(process.cwd(), '.iloom', 'settings.local.json')\n\n try {\n const worktreeIloomDir = path.join(worktreePath, '.iloom')\n\n // Ensure .iloom directory exists in worktree\n await fs.ensureDir(worktreeIloomDir)\n\n const worktreeSettingsLocalPath = path.join(worktreeIloomDir, 'settings.local.json')\n\n // Check if settings.local.json already exists in worktree\n if (await fs.pathExists(worktreeSettingsLocalPath)) {\n getLogger().warn('settings.local.json already exists in worktree, skipping copy')\n } else {\n await this.environment.copyIfExists(mainSettingsLocalPath, worktreeSettingsLocalPath)\n }\n } catch (error) {\n getLogger().warn(`Warning: Failed to copy settings.local.json: ${error instanceof Error ? error.message : 'Unknown error'}`)\n }\n }\n\n /**\n * Copy iloom package local config (package.iloom.local.json) from main repo to worktree\n * Always called regardless of project capabilities\n * Follows the same pattern as copyIloomSettings()\n * @param worktreePath Path to the worktree\n */\n private async copyIloomPackageLocal(worktreePath: string): Promise<void> {\n const mainPackageLocalPath = path.join(process.cwd(), '.iloom', 'package.iloom.local.json')\n\n try {\n const worktreeIloomDir = path.join(worktreePath, '.iloom')\n\n // Ensure .iloom directory exists in worktree\n await fs.ensureDir(worktreeIloomDir)\n\n const worktreePackageLocalPath = path.join(worktreeIloomDir, 'package.iloom.local.json')\n\n // Check if package.iloom.local.json already exists in worktree\n if (await fs.pathExists(worktreePackageLocalPath)) {\n getLogger().debug('package.iloom.local.json already exists in worktree, skipping copy')\n } else {\n await this.environment.copyIfExists(mainPackageLocalPath, worktreePackageLocalPath)\n }\n } catch (error) {\n getLogger().warn(`Warning: Failed to copy package.iloom.local.json: ${error instanceof Error ? error.message : 'Unknown error'}`)\n }\n }\n\n /**\n * Copy Claude settings (settings.local.json) from main repo to worktree\n * Always called regardless of project capabilities\n * Follows the same pattern as copyIloomSettings()\n * @param worktreePath Path to the worktree\n */\n private async copyClaudeSettings(worktreePath: string): Promise<void> {\n const mainClaudeSettingsPath = path.join(process.cwd(), '.claude', 'settings.local.json')\n\n try {\n const worktreeClaudeDir = path.join(worktreePath, '.claude')\n\n // Ensure .claude directory exists in worktree\n await fs.ensureDir(worktreeClaudeDir)\n\n const worktreeClaudeSettingsPath = path.join(worktreeClaudeDir, 'settings.local.json')\n\n // Check if settings.local.json already exists in worktree\n if (await fs.pathExists(worktreeClaudeSettingsPath)) {\n getLogger().debug('.claude/settings.local.json already exists in worktree, skipping copy')\n } else {\n await this.environment.copyIfExists(mainClaudeSettingsPath, worktreeClaudeSettingsPath)\n }\n } catch (error) {\n getLogger().warn(`Warning: Failed to copy .claude/settings.local.json: ${error instanceof Error ? error.message : 'Unknown error'}`)\n }\n }\n\n /**\n * Copy gitignored files matching configured patterns from main repo to worktree\n * Uses copyGitIgnoredPatterns from settings to determine which files to copy\n * Only copies files that exist and are NOT tracked by git\n *\n * @param worktreePath Path to the worktree\n */\n private async copyGitIgnoredFiles(worktreePath: string): Promise<void> {\n // Load settings to get patterns\n const settingsData = await this.settings.loadSettings()\n const patterns = settingsData.copyGitIgnoredPatterns\n\n // Exit early if no patterns configured\n if (!patterns || patterns.length === 0) {\n getLogger().debug('No copyGitIgnoredPatterns configured, skipping gitignored file copy')\n return\n }\n\n const mainWorkspacePath = this.gitWorktree.workingDirectory\n\n try {\n // Pass all patterns at once - fast-glob deduplicates automatically\n const allMatches = await fg.glob(patterns, {\n cwd: mainWorkspacePath,\n onlyFiles: true,\n dot: true,\n })\n\n if (allMatches.length === 0) {\n getLogger().debug(`No files matched copyGitIgnoredPatterns: ${patterns.join(', ')}`)\n return\n }\n\n getLogger().info(`Copying ${allMatches.length} gitignored file(s) matching: ${patterns.join(', ')}`)\n\n // Copy each unique file once\n let copiedCount = 0\n for (const relativePath of allMatches) {\n const mainFilePath = path.join(mainWorkspacePath, relativePath)\n const worktreeFilePath = path.join(worktreePath, relativePath)\n\n // Skip if file doesn't exist in main workspace\n if (!(await fs.pathExists(mainFilePath))) {\n continue\n }\n\n // Skip if file is tracked by git (it will exist in worktree via git)\n if (await isFileTrackedByGit(relativePath, mainWorkspacePath)) {\n getLogger().debug(`Skipping ${relativePath} (tracked by git, already in worktree)`)\n continue\n }\n\n // Skip if file already exists in worktree\n if (await fs.pathExists(worktreeFilePath)) {\n getLogger().debug(`Skipping ${relativePath} (already exists in worktree)`)\n continue\n }\n\n // Ensure parent directory exists\n await fs.ensureDir(path.dirname(worktreeFilePath))\n\n // Copy the untracked file\n await this.environment.copyIfExists(mainFilePath, worktreeFilePath)\n getLogger().debug(`Copied gitignored file: ${relativePath}`)\n copiedCount++\n }\n\n if (copiedCount > 0) {\n getLogger().debug(`Copied ${copiedCount} gitignored file(s) to loom`)\n }\n } catch (error) {\n // Warn but don't fail - glob/file failures shouldn't block workflow\n getLogger().warn(`Warning: Failed to copy gitignored files: ${error instanceof Error ? error.message : 'Unknown error'}`)\n }\n }\n\n /**\n * Setup PORT environment variable for web projects\n * Only called when project has web capabilities\n */\n private async setupPortForWeb(\n worktreePath: string,\n input: CreateLoomInput,\n basePort: number\n ): Promise<number> {\n const envFilePath = path.join(worktreePath, '.env.local')\n\n // Calculate port based on input type\n const options: { basePort: number; issueNumber?: number; prNumber?: number; branchName?: string } = { basePort }\n\n if (input.type === 'issue' || input.type === 'epic') {\n options.issueNumber = input.identifier as number\n } else if (input.type === 'pr') {\n options.prNumber = input.identifier as number\n } else if (input.type === 'branch') {\n options.branchName = input.identifier as string\n }\n\n const port = this.environment.calculatePort(options)\n\n await this.environment.setEnvVar(envFilePath, 'PORT', String(port))\n return port\n }\n\n /**\n * Load environment variables from main .env file into process.env\n * Uses dotenv-flow to handle various .env file patterns\n */\n private loadMainEnvFile(): void {\n const result = loadEnvIntoProcess({ path: process.cwd() })\n\n if (result.error) {\n // Only log warning for actual errors, not for \"no .env files found\" which is harmless\n if (isNoEnvFilesFoundError(result.error)) {\n getLogger().debug('No .env files found (this is normal for projects without environment files)')\n } else {\n getLogger().warn(`Warning: Could not load .env files: ${result.error.message}`)\n }\n } else {\n getLogger().info('Loaded environment variables using dotenv-flow')\n if (result.parsed && Object.keys(result.parsed).length > 0) {\n getLogger().debug(`Loaded ${Object.keys(result.parsed).length} environment variables`)\n }\n }\n }\n\n /**\n * Generate a unique loom ID\n */\n private generateLoomId(input: CreateLoomInput): string {\n const prefix = input.type\n return `${prefix}-${input.identifier}`\n }\n\n /**\n * Calculate port for the loom\n * Base port: configurable via settings.capabilities.web.basePort (default 3000) + issue/PR number (or deterministic hash for branches)\n */\n private async calculatePort(input: CreateLoomInput): Promise<number> {\n // Load base port from settings\n const settingsData = await this.settings.loadSettings()\n const basePort = settingsData.capabilities?.web?.basePort ?? 3000\n\n if (input.type === 'issue' || input.type === 'epic') {\n if (typeof input.identifier === 'number') {\n return this.environment.calculatePort({ basePort, issueNumber: input.identifier })\n } else if (typeof input.identifier === 'string') {\n // Alphanumeric issue ID (e.g., Linear: ENG-123) - delegate to EnvironmentManager\n return this.environment.calculatePort({ basePort, issueNumber: input.identifier })\n }\n }\n\n if (input.type === 'pr' && typeof input.identifier === 'number') {\n return this.environment.calculatePort({ basePort, prNumber: input.identifier })\n }\n\n if (input.type === 'branch' && typeof input.identifier === 'string') {\n // Use deterministic hash for branch-based ports\n return this.environment.calculatePort({ basePort, branchName: input.identifier })\n }\n\n // Fallback: basePort only (shouldn't reach here with valid input)\n throw new Error(`Unknown input type: ${input.type} with identifier type: ${typeof input.identifier}`)\n }\n\n\n /**\n * Apply color synchronization to both VSCode and terminal\n * Colors are cosmetic - errors are logged but don't block workflow\n * Respects colors settings for independent control\n *\n * DEFAULTS:\n * - terminal: true (always safe, only affects macOS Terminal.app)\n * - vscode: false (safe default, prevents unexpected file modifications)\n *\n * @param colorData - Pre-computed color data (from collision avoidance)\n */\n private async applyColorSynchronization(\n worktreePath: string,\n branchName: string,\n colorData: ColorData,\n settings: import('./SettingsManager.js').IloomSettings,\n options?: CreateLoomInput['options']\n ): Promise<void> {\n // Determine color settings: options override settings, settings override defaults\n // Note: vscode defaults to FALSE for safety\n const colorVscode = options?.colorVscode ?? settings.colors?.vscode ?? false\n const colorTerminal = options?.colorTerminal ?? settings.colors?.terminal ?? true\n\n if (!colorVscode && !colorTerminal) {\n getLogger().debug('Color synchronization disabled for both VSCode and terminal')\n return\n }\n\n // Apply VSCode title bar color if enabled (default: disabled for safety)\n if (colorVscode) {\n const vscode = new VSCodeIntegration()\n await vscode.setTitleBarColor(worktreePath, colorData.hex)\n getLogger().info(`Applied VSCode title bar color: ${colorData.hex} for branch: ${branchName}`)\n } else {\n getLogger().debug('VSCode color sync disabled (default: false for safety)')\n }\n\n // Note: Terminal color is applied during window creation in LoomLauncher\n // The colorTerminal setting is passed through to launch options\n }\n\n /**\n * Map worktrees to loom objects\n * Reads loom metadata from MetadataManager with branch name parsing as fallback\n */\n private async mapWorktreesToLooms(worktrees: GitWorktree[]): Promise<Loom[]> {\n return await Promise.all(worktrees.map(async (wt) => {\n // Read metadata from persistent storage first\n const loomMetadata = await this.metadataManager.readMetadata(wt.path)\n\n // Priority 1: Use metadata as source of truth if available\n let type: 'issue' | 'pr' | 'branch' | 'epic' = 'branch'\n let identifier: string | number = wt.branch\n\n if (loomMetadata?.issueType) {\n type = loomMetadata.issueType\n\n // Extract identifier from metadata based on type\n // Prefer issueKey (canonical case) over issue_numbers (may be lowercase from branch extraction)\n if (type === 'issue' && (loomMetadata.issueKey || loomMetadata.issue_numbers?.[0])) {\n const issueId = loomMetadata.issueKey ?? loomMetadata.issue_numbers[0] ?? ''\n // Try to parse as number, otherwise keep as string (for alphanumeric IDs)\n const numericId = parseInt(issueId, 10)\n identifier = isNaN(numericId) ? issueId : numericId\n } else if (type === 'pr' && loomMetadata.pr_numbers?.[0]) {\n const prId = loomMetadata.pr_numbers[0]\n // PRs are always numeric\n identifier = parseInt(prId, 10)\n } else if (type === 'branch') {\n identifier = wt.branch\n }\n } else {\n // Priority 2: Fall back to branch name parsing if metadata not available\n\n // Check for PR pattern first (higher priority)\n const prNumber = extractPRNumber(wt.branch)\n if (prNumber !== null) {\n type = 'pr'\n identifier = prNumber\n } else {\n // Check for issue pattern\n const issueNumber = extractIssueNumber(wt.branch)\n if (issueNumber !== null) {\n type = 'issue'\n // Try to parse as number, otherwise keep as string (for alphanumeric IDs)\n const numericId = parseInt(issueNumber, 10)\n identifier = isNaN(numericId) ? issueNumber : numericId\n } else {\n // Default to branch type\n type = 'branch'\n identifier = wt.branch\n }\n }\n }\n\n return {\n id: `${type}-${identifier}`,\n path: wt.path,\n branch: wt.branch,\n type,\n identifier,\n port: await this.calculatePort({ type, identifier, originalInput: '' }),\n ...(loomMetadata?.description && { description: loomMetadata.description }),\n createdAt: new Date(),\n lastAccessed: new Date(),\n }\n }))\n }\n\n /**\n * NEW: Find existing loom for the given input\n * Checks for worktrees matching the issue/PR identifier\n */\n private async findExistingIloom(\n input: CreateLoomInput,\n issueData: Issue | PullRequest | null\n ): Promise<GitWorktree | null> {\n if (input.type === 'issue') {\n return await this.gitWorktree.findWorktreeForIssue(input.identifier as number)\n } else if (input.type === 'pr' && issueData && 'branch' in issueData) {\n return await this.gitWorktree.findWorktreeForPR(\n input.identifier as number,\n issueData.branch\n )\n } else if (input.type === 'branch') {\n return await this.gitWorktree.findWorktreeForBranch(input.identifier as string)\n }\n return null\n }\n\n /**\n * NEW: Reuse an existing loom\n * Includes environment setup and database branching for existing worktrees\n * Ports: handle_existing_worktree() from bash script lines 168-215\n */\n private async reuseIloom(\n worktree: GitWorktree,\n input: CreateLoomInput,\n issueData: Issue | PullRequest | null\n ): Promise<Loom> {\n const worktreePath = worktree.path\n const branchName = worktree.branch\n\n // 1. Load main .env variables into process.env\n this.loadMainEnvFile()\n\n // 2. Detect capabilities (quick, no installation)\n const { capabilities, binEntries } = await this.capabilityDetector.detectCapabilities(worktreePath)\n\n // 3. Defensively copy .env and settings.local.json if missing\n await this.copyEnvironmentFiles(worktreePath)\n await this.copyIloomSettings(worktreePath)\n await this.copyIloomPackageLocal(worktreePath)\n await this.copyClaudeSettings(worktreePath)\n\n // 3.5. Copy gitignored files matching configured patterns\n await this.copyGitIgnoredFiles(worktreePath)\n\n // 4. Setup PORT for web projects (ensure it's set even if .env existed)\n // Load base port from settings\n const settingsData = await this.settings.loadSettings()\n const basePort = settingsData.capabilities?.web?.basePort ?? 3000\n\n let port = basePort\n if (capabilities.includes('web')) {\n port = await this.setupPortForWeb(worktreePath, input, basePort)\n }\n\n // 5. Skip database branch creation for existing worktrees\n // The database branch should have been created when the worktree was first created\n // Matches bash script behavior: handle_existing_worktree() skips all setup\n getLogger().info('Database branch assumed to be already configured for existing worktree')\n const databaseBranch: string | undefined = undefined\n\n // 5.5. Read existing metadata to get colorHex (for reusing stored color)\n const existingMetadata = await this.metadataManager.readMetadata(worktreePath)\n\n // Determine colorHex for launch\n let colorHex: string\n if (existingMetadata?.colorHex) {\n // Use stored hex color (already migrated from colorIndex if needed in readMetadata)\n colorHex = existingMetadata.colorHex\n getLogger().debug(`Reusing stored color ${colorHex} for branch ${branchName}`)\n } else {\n // No metadata - fall back to hash-based with dark mode detection\n const themeMode = await detectDarkMode()\n const colorData = generateColorFromBranchName(branchName, themeMode)\n colorHex = colorData.hex\n getLogger().debug(`No stored color, using hash-based color ${colorHex} for branch ${branchName} (${themeMode} mode)`)\n }\n\n // Apply color synchronization (VSCode colors for reused looms)\n // Mirrors createIloom() behavior at lines 205-214\n try {\n const colorData: ColorData = { hex: colorHex, rgb: hexToRgb(colorHex), index: 0 }\n await this.applyColorSynchronization(worktreePath, branchName, colorData, settingsData, input.options)\n } catch (error) {\n // Log warning but don't fail - colors are cosmetic\n getLogger().warn(\n `Failed to apply color synchronization: ${error instanceof Error ? error.message : 'Unknown error'}`,\n error\n )\n }\n\n // 6. Move issue to In Progress (for reused worktrees too)\n if (input.type === 'issue') {\n try {\n getLogger().info('Moving issue to In Progress...')\n // Check if provider supports this optional method\n if (this.issueTracker.moveIssueToInProgress) {\n await this.issueTracker.moveIssueToInProgress(input.identifier as number)\n }\n } catch (error) {\n getLogger().warn(\n `Failed to move issue to In Progress: ${error instanceof Error ? error.message : 'Unknown error'}`,\n error\n )\n }\n }\n\n // 7. Launch components (same as new worktree)\n const enableClaude = input.options?.enableClaude !== false\n const enableCode = input.options?.enableCode !== false\n const enableDevServer = input.options?.enableDevServer !== false\n const enableTerminal = input.options?.enableTerminal ?? false\n const oneShot = input.options?.oneShot ?? 'default'\n const complexity = input.options?.complexity\n const setArguments = input.options?.setArguments\n const executablePath = input.options?.executablePath\n\n if (enableClaude || enableCode || enableDevServer || enableTerminal) {\n getLogger().info('Launching workspace components...')\n const { LoomLauncher } = await import('./LoomLauncher.js')\n const { ClaudeContextManager } = await import('./ClaudeContextManager.js')\n\n // Create ClaudeContextManager with shared SettingsManager to ensure CLI overrides work\n const claudeContext = new ClaudeContextManager(undefined, undefined, this.settings)\n const launcher = new LoomLauncher(claudeContext, this.settings)\n\n await launcher.launchLoom({\n enableClaude,\n enableCode,\n enableDevServer,\n enableTerminal,\n worktreePath,\n branchName,\n port,\n capabilities,\n workflowType: input.type === 'branch' ? 'regular' : input.type === 'epic' ? 'issue' : input.type,\n identifier: input.identifier,\n ...(issueData?.title && { title: issueData.title }),\n oneShot,\n ...(complexity && { complexity }),\n ...(setArguments && { setArguments }),\n ...(executablePath && { executablePath }),\n sourceEnvOnStart: settingsData.sourceEnvOnStart ?? false,\n colorTerminal: input.options?.colorTerminal ?? settingsData.colors?.terminal ?? true,\n colorHex,\n })\n }\n\n // 8. Write loom metadata if missing (spec section 3.1)\n // For reused looms, only write if metadata file doesn't exist\n const description = existingMetadata?.description ?? issueData?.title ?? branchName\n if (!existingMetadata) {\n // Build issue/pr numbers arrays based on type\n // For PR workflows, extract issue number from branch name if present\n let issue_numbers: string[] = []\n let extractedIssueNum: string | null = null\n if (input.type === 'issue') {\n issue_numbers = [String(input.identifier)]\n } else if (input.type === 'pr') {\n extractedIssueNum = extractIssueNumber(branchName)\n if (extractedIssueNum) {\n issue_numbers = [extractedIssueNum]\n }\n }\n const pr_numbers: string[] = input.type === 'pr' ? [String(input.identifier)] : []\n\n // Generate random session ID for Claude Code resume support\n // Each loom gets a unique session ID, enabling fresh Claude sessions\n const sessionId = generateRandomSessionId()\n\n // Build issueUrls/prUrls based on workflow type\n // For PR workflows, construct issue URL by replacing /pull/N with /issues/M\n let issueUrls: Record<string, string> = {}\n if (input.type === 'issue' && issueData?.url) {\n issueUrls = { [String(input.identifier)]: issueData.url }\n } else if (input.type === 'pr' && extractedIssueNum && issueData?.url) {\n const issueUrl = issueData.url.replace(`/pull/${input.identifier}`, `/issues/${extractedIssueNum}`)\n issueUrls = { [extractedIssueNum]: issueUrl }\n }\n const prUrls: Record<string, string> = input.type === 'pr' && issueData?.url\n ? { [String(input.identifier)]: issueData.url }\n : {}\n\n const metadataInput: WriteMetadataInput = {\n description,\n branchName,\n worktreePath,\n issueType: input.type,\n ...(input.type === 'issue' && { issueKey: this.issueTracker.normalizeIdentifier(input.identifier) }),\n issue_numbers,\n pr_numbers,\n issueTracker: this.issueTracker.providerName,\n colorHex,\n sessionId,\n projectPath: this.gitWorktree.workingDirectory,\n issueUrls,\n prUrls,\n capabilities,\n ...(input.options?.oneShot && { oneShot: input.options.oneShot }),\n ...(input.options?.complexity && { complexity: input.options.complexity }),\n ...(input.options?.childIssueNumbers && input.options.childIssueNumbers.length > 0 && { childIssueNumbers: input.options.childIssueNumbers }),\n ...(input.parentLoom && { parentLoom: input.parentLoom }),\n }\n await this.metadataManager.writeMetadata(worktreePath, metadataInput)\n } else if (input.options?.complexity) {\n // Update existing metadata with complexity override\n await this.metadataManager.updateMetadata(worktreePath, {\n complexity: input.options.complexity,\n })\n }\n\n // 9. Return loom metadata\n const loom: Loom = {\n id: this.generateLoomId(input),\n path: worktreePath,\n branch: branchName,\n type: input.type,\n identifier: input.identifier,\n port,\n description,\n createdAt: new Date(), // We don't have actual creation date, use now\n lastAccessed: new Date(),\n ...(databaseBranch !== undefined && { databaseBranch }),\n ...(capabilities.length > 0 && { capabilities }),\n ...(Object.keys(binEntries).length > 0 && { binEntries }),\n ...(issueData !== null && {\n issueData: {\n title: issueData.title,\n body: issueData.body,\n url: issueData.url,\n state: issueData.state,\n },\n }),\n }\n\n getLogger().success(`Reused existing loom: ${loom.id} at ${loom.path}`)\n return loom\n }\n}\n","import fs from 'fs-extra'\nimport path from 'path'\nimport { parse, modify, applyEdits } from 'jsonc-parser'\nimport { logger } from '../utils/logger.js'\nimport {\n\thexToRgb,\n\trgbToHex,\n\tlightenColor,\n\tcalculateForegroundColor,\n} from '../utils/color.js'\n\n/**\n * VSCode settings structure\n */\ninterface VSCodeSettings {\n\t'workbench.colorCustomizations'?: {\n\t\t// Title Bar\n\t\t'titleBar.activeBackground'?: string\n\t\t'titleBar.inactiveBackground'?: string\n\t\t'titleBar.activeForeground'?: string\n\t\t'titleBar.inactiveForeground'?: string\n\t\t// Status Bar\n\t\t'statusBar.background'?: string\n\t\t'statusBar.foreground'?: string\n\t\t'statusBarItem.hoverBackground'?: string\n\t\t'statusBarItem.remoteBackground'?: string\n\t\t'statusBarItem.remoteForeground'?: string\n\t\t// UI Accents\n\t\t'sash.hoverBorder'?: string\n\t\t'commandCenter.border'?: string\n\t\t[key: string]: string | undefined\n\t}\n\t[key: string]: unknown\n}\n\n/**\n * Manages VSCode settings.json manipulation for workspace color synchronization\n */\nexport class VSCodeIntegration {\n\t/**\n\t * Set VSCode title bar color for a workspace\n\t *\n\t * @param workspacePath - Path to workspace directory\n\t * @param hexColor - Hex color string (e.g., \"#dcebf8\")\n\t */\n\tasync setTitleBarColor(workspacePath: string, hexColor: string): Promise<void> {\n\t\tconst vscodeDir = path.join(workspacePath, '.vscode')\n\t\tconst settingsPath = path.join(vscodeDir, 'settings.json')\n\n\t\ttry {\n\t\t\t// Ensure .vscode directory exists\n\t\t\tawait fs.ensureDir(vscodeDir)\n\n\t\t\t// Read existing settings (or create empty object)\n\t\t\tconst settings = await this.readSettings(settingsPath)\n\n\t\t\t// Merge color settings\n\t\t\tconst updatedSettings = this.mergeColorSettings(settings, hexColor)\n\n\t\t\t// Write settings atomically\n\t\t\tawait this.writeSettings(settingsPath, updatedSettings)\n\n\t\t\tlogger.debug(`Set VSCode title bar color to ${hexColor} for ${workspacePath}`)\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to set VSCode title bar color: ${error instanceof Error ? error.message : 'Unknown error'}`\n\t\t\t)\n\t\t}\n\t}\n\n\t/**\n\t * Read VSCode settings from file\n\t * Supports JSONC (JSON with Comments)\n\t *\n\t * @param settingsPath - Path to settings.json file\n\t * @returns Parsed settings object\n\t */\n\tprivate async readSettings(settingsPath: string): Promise<VSCodeSettings> {\n\t\ttry {\n\t\t\t// Check if file exists\n\t\t\tif (!(await fs.pathExists(settingsPath))) {\n\t\t\t\treturn {}\n\t\t\t}\n\n\t\t\t// Read file content\n\t\t\tconst content = await fs.readFile(settingsPath, 'utf8')\n\n\t\t\t// Parse JSONC (handles comments)\n\t\t\tconst errors: import('jsonc-parser').ParseError[] = []\n\t\t\tconst settings = parse(content, errors, { allowTrailingComma: true })\n\n\t\t\t// Check for parse errors\n\t\t\tif (errors.length > 0) {\n\t\t\t\tconst firstError = errors[0]\n\t\t\t\tthrow new Error(`Invalid JSON: ${firstError ? firstError.error : 'Unknown parse error'}`)\n\t\t\t}\n\n\t\t\treturn settings ?? {}\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to parse settings.json: ${error instanceof Error ? error.message : 'Unknown error'}`\n\t\t\t)\n\t\t}\n\t}\n\n\t/**\n\t * Write VSCode settings to file atomically\n\t * Preserves comments if present (using JSONC parser)\n\t *\n\t * @param settingsPath - Path to settings.json file\n\t * @param settings - Settings object to write\n\t */\n\tprivate async writeSettings(\n\t\tsettingsPath: string,\n\t\tsettings: VSCodeSettings\n\t): Promise<void> {\n\t\ttry {\n\t\t\tlet content: string\n\n\t\t\t// Check if file exists with comments\n\t\t\tif (await fs.pathExists(settingsPath)) {\n\t\t\t\tconst existingContent = await fs.readFile(settingsPath, 'utf8')\n\n\t\t\t\t// Try to preserve comments by using jsonc-parser's modify function\n\t\t\t\tif (existingContent.includes('//') || existingContent.includes('/*')) {\n\t\t\t\t\t// File has comments - use JSONC modify to preserve them\n\t\t\t\t\tcontent = await this.modifyWithCommentsPreserved(existingContent, settings)\n\t\t\t\t} else {\n\t\t\t\t\t// No comments - use standard JSON.stringify\n\t\t\t\t\tcontent = JSON.stringify(settings, null, 2) + '\\n'\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// New file - use standard JSON.stringify\n\t\t\t\tcontent = JSON.stringify(settings, null, 2) + '\\n'\n\t\t\t}\n\n\t\t\t// Write atomically using temp file + rename\n\t\t\tconst tempPath = `${settingsPath}.tmp`\n\t\t\tawait fs.writeFile(tempPath, content, 'utf8')\n\t\t\tawait fs.rename(tempPath, settingsPath)\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to write settings.json: ${error instanceof Error ? error.message : 'Unknown error'}`\n\t\t\t)\n\t\t}\n\t}\n\n\t/**\n\t * Modify JSONC content while preserving comments\n\t *\n\t * @param existingContent - Original JSONC content\n\t * @param newSettings - New settings to apply\n\t * @returns Modified JSONC content with comments preserved\n\t */\n\tprivate async modifyWithCommentsPreserved(\n\t\texistingContent: string,\n\t\tnewSettings: VSCodeSettings\n\t): Promise<string> {\n\t\tlet modifiedContent = existingContent\n\n\t\t// Apply each setting modification\n\t\tfor (const [key, value] of Object.entries(newSettings)) {\n\t\t\tconst edits = modify(modifiedContent, [key], value, {})\n\t\t\tmodifiedContent = applyEdits(modifiedContent, edits)\n\t\t}\n\n\t\treturn modifiedContent\n\t}\n\n\t/**\n\t * Merge color settings into existing settings object\n\t *\n\t * @param existing - Existing settings object\n\t * @param hexColor - Hex color to apply (subtle palette color)\n\t * @returns Updated settings object with color merged\n\t */\n\tprivate mergeColorSettings(existing: VSCodeSettings, hexColor: string): VSCodeSettings {\n\t\t// Clone existing settings\n\t\tconst updated: VSCodeSettings = { ...existing }\n\n\t\t// Initialize workbench.colorCustomizations if needed\n\t\tupdated['workbench.colorCustomizations'] ??= {}\n\n\t\tconst colors = updated['workbench.colorCustomizations']\n\n\t\t// Convert hex to RGB for manipulation\n\t\tconst baseRgb = hexToRgb(hexColor)\n\n\t\t// Calculate foreground color based on background luminance\n\t\tconst foreground = calculateForegroundColor(baseRgb)\n\t\tconst foregroundTransparent = foreground.replace('#', '#') + '99' // Add 60% opacity\n\n\t\t// Create lighter variant for hover states\n\t\tconst lighterRgb = lightenColor(baseRgb, 0.05) // 5% lighter\n\t\tconst lighterHex = rgbToHex(lighterRgb.r, lighterRgb.g, lighterRgb.b)\n\n\t\t// Title Bar - subtle top indicator\n\t\tcolors['titleBar.activeBackground'] = hexColor\n\t\tcolors['titleBar.inactiveBackground'] = hexColor + '99' // Semi-transparent when unfocused\n\t\tcolors['titleBar.activeForeground'] = foreground\n\t\tcolors['titleBar.inactiveForeground'] = foregroundTransparent\n\n\t\t// Status Bar - constant visibility at bottom\n\t\tcolors['statusBar.background'] = hexColor\n\t\tcolors['statusBar.foreground'] = foreground\n\t\tcolors['statusBarItem.hoverBackground'] = lighterHex\n\t\tcolors['statusBarItem.remoteBackground'] = hexColor // When connected to remote\n\t\tcolors['statusBarItem.remoteForeground'] = foreground\n\n\t\t// UI Accents - subtle hints\n\t\tcolors['sash.hoverBorder'] = hexColor // Resize borders\n\t\tcolors['commandCenter.border'] = foregroundTransparent // Search box border\n\n\t\treturn updated\n\t}\n}\n","import fs from 'fs-extra'\nimport { getLogger } from '../utils/logger-context.js'\nimport type {\n PortAssignmentOptions,\n} from '../types/environment.js'\nimport {\n parseEnvFile,\n formatEnvLine,\n validateEnvVariable,\n} from '../utils/env.js'\nimport { calculatePortForBranch, calculatePortFromIdentifier } from '../utils/port.js'\n\nexport class EnvironmentManager {\n private readonly backupSuffix: string = '.backup'\n\n constructor() {\n // No-op - logger now uses AsyncLocalStorage context\n }\n\n /**\n * Set or update an environment variable in a .env file\n * Ports functionality from bash/utils/env-utils.sh:setEnvVar()\n * @returns The backup path if a backup was created\n */\n async setEnvVar(\n filePath: string,\n key: string,\n value: string,\n backup: boolean = false\n ): Promise<string | void> {\n // Validate variable name\n const validation = validateEnvVariable(key, value)\n if (!validation.valid) {\n throw new Error(validation.error ?? 'Invalid variable name')\n }\n\n const fileExists = await fs.pathExists(filePath)\n\n if (!fileExists) {\n // File doesn't exist, create it\n getLogger().info(`Creating ${filePath} with ${key}...`)\n const content = formatEnvLine(key, value)\n await fs.writeFile(filePath, content, 'utf8')\n getLogger().success(`${filePath} created with ${key}`)\n return\n }\n\n // File exists, read and parse it\n const existingContent = await fs.readFile(filePath, 'utf8')\n const envMap = parseEnvFile(existingContent)\n\n // Create backup if requested\n let backupPath: string | undefined\n if (backup) {\n backupPath = await this.createBackup(filePath)\n }\n\n // Update or add the variable\n envMap.set(key, value)\n\n // Rebuild the file content, preserving comments and empty lines\n const lines = existingContent.split('\\n')\n const newLines: string[] = []\n let variableUpdated = false\n\n for (const line of lines) {\n const trimmedLine = line.trim()\n\n // Preserve comments and empty lines\n if (!trimmedLine || trimmedLine.startsWith('#')) {\n newLines.push(line)\n continue\n }\n\n // Remove 'export ' prefix if present\n const cleanLine = trimmedLine.startsWith('export ')\n ? trimmedLine.substring(7)\n : trimmedLine\n\n // Check if this line contains our variable\n const equalsIndex = cleanLine.indexOf('=')\n if (equalsIndex !== -1) {\n const lineKey = cleanLine.substring(0, equalsIndex).trim()\n if (lineKey === key) {\n // Replace this line with the new value\n newLines.push(formatEnvLine(key, value))\n variableUpdated = true\n continue\n }\n }\n\n // Keep other lines as-is\n newLines.push(line)\n }\n\n // If variable wasn't in the file, add it at the end\n if (!variableUpdated) {\n getLogger().info(`Adding ${key} to ${filePath}...`)\n newLines.push(formatEnvLine(key, value))\n getLogger().success(`${key} added successfully`)\n } else {\n getLogger().info(`Updating ${key} in ${filePath}...`)\n getLogger().success(`${key} updated successfully`)\n }\n\n // Write the updated content\n const newContent = newLines.join('\\n')\n await fs.writeFile(filePath, newContent, 'utf8')\n\n return backupPath\n }\n\n /**\n * Read and parse a .env file\n */\n async readEnvFile(filePath: string): Promise<Map<string, string>> {\n try {\n const content = await fs.readFile(filePath, 'utf8')\n return parseEnvFile(content)\n } catch (error) {\n // If file doesn't exist or can't be read, return empty map\n getLogger().debug(\n `Could not read env file ${filePath}: ${error instanceof Error ? error.message : String(error)}`\n )\n return new Map()\n }\n }\n\n /**\n * Get a specific environment variable from a .env file\n * Returns null if file doesn't exist or variable is not found\n */\n async getEnvVariable(filePath: string, variableName: string): Promise<string | null> {\n const envVars = await this.readEnvFile(filePath)\n return envVars.get(variableName) ?? null\n }\n\n /**\n * Generic file copy helper that only copies if source exists\n * Does not throw if source file doesn't exist - just logs and returns\n * @private\n */\n async copyIfExists(\n source: string,\n destination: string\n ): Promise<void> {\n const sourceExists = await fs.pathExists(source)\n if (!sourceExists) {\n getLogger().debug(`Source file ${source} does not exist, skipping copy`)\n return\n }\n\n await fs.copy(source, destination, { overwrite: false })\n getLogger().success(`Copied ${source} to ${destination}`)\n }\n\n /**\n * Calculate unique port for workspace\n * Implements:\n * - Issue/PR: 3000 + issue/PR number\n * - Branch: 3000 + deterministic hash offset (1-999)\n * Delegates to calculatePortFromIdentifier for the core calculation.\n */\n calculatePort(options: PortAssignmentOptions): number {\n const basePort = options.basePort ?? 3000\n\n // Priority: issueNumber > prNumber > branchName > basePort only\n if (options.issueNumber !== undefined) {\n return calculatePortFromIdentifier(options.issueNumber, basePort)\n }\n\n if (options.prNumber !== undefined) {\n return calculatePortFromIdentifier(options.prNumber, basePort)\n }\n\n if (options.branchName !== undefined) {\n // Use deterministic hash for branch-based workspaces\n return calculatePortForBranch(options.branchName, basePort)\n }\n\n // Fallback: basePort only (no offset)\n return basePort\n }\n\n /**\n * Set port environment variable for workspace\n */\n async setPortForWorkspace(\n envFilePath: string,\n issueNumber?: string | number,\n prNumber?: number,\n branchName?: string\n ): Promise<number> {\n const options: PortAssignmentOptions = {}\n if (issueNumber !== undefined) {\n options.issueNumber = issueNumber\n }\n if (prNumber !== undefined) {\n options.prNumber = prNumber\n }\n if (branchName !== undefined) {\n options.branchName = branchName\n }\n const port = this.calculatePort(options)\n await this.setEnvVar(envFilePath, 'PORT', String(port))\n return port\n }\n\n /**\n * Validate environment configuration\n */\n async validateEnvFile(\n filePath: string\n ): Promise<{ valid: boolean; errors: string[] }> {\n try {\n const content = await fs.readFile(filePath, 'utf8')\n const envMap = parseEnvFile(content)\n const errors: string[] = []\n\n // Validate each variable name\n for (const [key, value] of envMap.entries()) {\n const validation = validateEnvVariable(key, value)\n if (!validation.valid) {\n errors.push(`${key}: ${validation.error}`)\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n }\n } catch (error) {\n return {\n valid: false,\n errors: [\n `Failed to read or parse file: ${error instanceof Error ? error.message : String(error)}`,\n ],\n }\n }\n }\n\n /**\n * Create backup of existing file\n */\n private async createBackup(filePath: string): Promise<string> {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-')\n const backupPath = `${filePath}${this.backupSuffix}-${timestamp}`\n await fs.copy(filePath, backupPath)\n getLogger().debug(`Created backup at ${backupPath}`)\n return backupPath\n }\n}\n","import fs from 'fs-extra'\nimport path from 'path'\nimport os from 'os'\nimport { runScript } from '../utils/package-manager.js'\nimport { getPackageConfig, hasScript } from '../utils/package-json.js'\nimport { getLogger } from '../utils/logger-context.js'\n\nexport class CLIIsolationManager {\n private readonly iloomBinDir: string\n\n constructor() {\n this.iloomBinDir = path.join(os.homedir(), '.iloom', 'bin')\n }\n\n /**\n * Setup CLI isolation for a worktree\n * - Build the project\n * - Create versioned symlinks\n * - Check PATH configuration\n * @param worktreePath Path to the worktree\n * @param identifier Issue/PR number or branch identifier\n * @param binEntries Bin entries from package.json\n * @returns Array of created symlink names\n */\n async setupCLIIsolation(\n worktreePath: string,\n identifier: string | number,\n binEntries: Record<string, string>\n ): Promise<string[]> {\n // 1. Build the project\n await this.buildProject(worktreePath)\n\n // 2. Verify bin targets exist and are executable\n await this.verifyBinTargets(worktreePath, binEntries)\n\n // 3. Create ~/.iloom/bin if needed\n await fs.ensureDir(this.iloomBinDir)\n\n // 4. Create versioned symlinks\n const symlinkNames = await this.createVersionedSymlinks(\n worktreePath,\n identifier,\n binEntries\n )\n\n // 5. Check PATH and provide instructions if needed\n await this.ensureIloomBinInPath()\n\n return symlinkNames\n }\n\n /**\n * Build the project using package.json build script\n * @param worktreePath Path to the worktree\n */\n private async buildProject(worktreePath: string): Promise<void> {\n const pkgJson = await getPackageConfig(worktreePath)\n\n if (!hasScript(pkgJson, 'build')) {\n getLogger().warn('No build script found in package.json - skipping build')\n return\n }\n\n getLogger().info('Building CLI tool...')\n await runScript('build', worktreePath, [], { quiet: true })\n getLogger().success('Build completed')\n }\n\n /**\n * Verify bin targets exist and are executable\n * @param worktreePath Path to the worktree\n * @param binEntries Bin entries from package.json\n */\n private async verifyBinTargets(\n worktreePath: string,\n binEntries: Record<string, string>\n ): Promise<void> {\n for (const binPath of Object.values(binEntries)) {\n const targetPath = path.resolve(worktreePath, binPath)\n\n // Check if file exists\n const exists = await fs.pathExists(targetPath)\n if (!exists) {\n throw new Error(`Bin target does not exist: ${targetPath}`)\n }\n\n // Check if file is executable\n try {\n await fs.access(targetPath, fs.constants.X_OK)\n } catch {\n // File is not executable, but that's okay - symlink will work anyway\n // The shebang in the file will determine how it's executed\n }\n }\n }\n\n /**\n * Create versioned symlinks in ~/.iloom/bin\n * @param worktreePath Path to the worktree\n * @param identifier Issue/PR number or branch identifier\n * @param binEntries Bin entries from package.json\n * @returns Array of created symlink names\n */\n private async createVersionedSymlinks(\n worktreePath: string,\n identifier: string | number,\n binEntries: Record<string, string>\n ): Promise<string[]> {\n const symlinkNames: string[] = []\n\n for (const [binName, binPath] of Object.entries(binEntries)) {\n const versionedName = `${binName}-${identifier}`\n const targetPath = path.resolve(worktreePath, binPath)\n const symlinkPath = path.join(this.iloomBinDir, versionedName)\n\n // Create symlink\n await fs.symlink(targetPath, symlinkPath)\n\n getLogger().success(`CLI available: ${versionedName}`)\n symlinkNames.push(versionedName)\n }\n\n return symlinkNames\n }\n\n /**\n * Check if ~/.iloom/bin is in PATH and provide setup instructions\n */\n private async ensureIloomBinInPath(): Promise<void> {\n const currentPath = process.env.PATH ?? ''\n if (currentPath.includes('.iloom/bin')) {\n return // Already configured\n }\n\n // Detect shell and RC file\n const shell = this.detectShell()\n const rcFile = this.getShellRcFile(shell)\n\n // Print setup instructions\n getLogger().warn('\\n⚠️ One-time PATH setup required:')\n getLogger().warn(` Add to ${rcFile}:`)\n getLogger().warn(` export PATH=\"$HOME/.iloom/bin:$PATH\"`)\n getLogger().warn(` Then run: source ${rcFile}\\n`)\n }\n\n /**\n * Detect current shell\n * @returns Shell name (zsh, bash, fish, etc.)\n */\n private detectShell(): string {\n const shell = process.env.SHELL ?? ''\n return shell.split('/').pop() ?? 'bash'\n }\n\n /**\n * Get RC file path for shell\n * @param shell Shell name\n * @returns RC file path\n */\n private getShellRcFile(shell: string): string {\n const rcFiles: Record<string, string> = {\n zsh: '~/.zshrc',\n bash: '~/.bashrc',\n fish: '~/.config/fish/config.fish'\n }\n return rcFiles[shell] ?? '~/.bashrc'\n }\n\n /**\n * Cleanup versioned CLI executables for a specific identifier\n * Removes all symlinks matching the pattern: {binName}-{identifier}\n *\n * @param identifier - Issue/PR number or branch identifier\n * @returns Array of removed symlink names\n */\n async cleanupVersionedExecutables(identifier: string | number): Promise<string[]> {\n const removed: string[] = []\n\n try {\n const files = await fs.readdir(this.iloomBinDir)\n\n for (const file of files) {\n if (this.matchesIdentifier(file, identifier)) {\n const symlinkPath = path.join(this.iloomBinDir, file)\n\n try {\n await fs.unlink(symlinkPath)\n removed.push(file)\n } catch (error) {\n // Silently skip if symlink already gone (ENOENT)\n const isEnoent = error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT'\n if (isEnoent) {\n removed.push(file)\n continue\n }\n\n // Log warning for other errors but continue cleanup\n getLogger().warn(\n `Failed to remove symlink ${file}: ${error instanceof Error ? error.message : 'Unknown error'}`\n )\n }\n }\n }\n } catch (error) {\n // Handle missing bin directory gracefully\n const isEnoent = error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT'\n if (isEnoent) {\n getLogger().warn('No CLI executables directory found - nothing to cleanup')\n return []\n }\n\n // Re-throw unexpected errors\n throw error\n }\n\n if (removed.length > 0) {\n getLogger().success(`Removed CLI executables: ${removed.join(', ')}`)\n }\n\n return removed\n }\n\n /**\n * Find orphaned symlinks in ~/.iloom/bin\n * Returns symlinks that point to non-existent targets\n *\n * @returns Array of orphaned symlink information\n */\n async findOrphanedSymlinks(): Promise<Array<{ name: string; path: string; brokenTarget: string }>> {\n const orphaned: Array<{ name: string; path: string; brokenTarget: string }> = []\n\n try {\n const files = await fs.readdir(this.iloomBinDir)\n\n for (const file of files) {\n const symlinkPath = path.join(this.iloomBinDir, file)\n\n try {\n const stats = await fs.lstat(symlinkPath)\n\n if (stats.isSymbolicLink()) {\n const target = await fs.readlink(symlinkPath)\n\n // Check if target exists\n try {\n await fs.access(target)\n } catch {\n // Target doesn't exist - this is an orphaned symlink\n orphaned.push({\n name: file,\n path: symlinkPath,\n brokenTarget: target\n })\n }\n }\n } catch (error) {\n // Skip files we can't read\n getLogger().warn(\n `Failed to check symlink ${file}: ${error instanceof Error ? error.message : 'Unknown error'}`\n )\n }\n }\n } catch (error) {\n // Handle missing bin directory\n const isEnoent = error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT'\n if (isEnoent) {\n return []\n }\n\n // Re-throw unexpected errors\n throw error\n }\n\n return orphaned\n }\n\n /**\n * Cleanup all orphaned symlinks\n * Removes symlinks that point to non-existent targets\n *\n * @returns Number of symlinks removed\n */\n async cleanupOrphanedSymlinks(): Promise<number> {\n const orphaned = await this.findOrphanedSymlinks()\n let removedCount = 0\n\n for (const symlink of orphaned) {\n try {\n await fs.unlink(symlink.path)\n removedCount++\n getLogger().success(`Removed orphaned symlink: ${symlink.name}`)\n } catch (error) {\n getLogger().warn(\n `Failed to remove orphaned symlink ${symlink.name}: ${error instanceof Error ? error.message : 'Unknown error'}`\n )\n }\n }\n\n return removedCount\n }\n\n /**\n * Check if a filename matches the versioned pattern for an identifier\n * Pattern: {binName}-{identifier}\n *\n * @param fileName - Name of the file to check\n * @param identifier - Issue/PR number or branch identifier\n * @returns True if the filename matches the pattern\n */\n private matchesIdentifier(fileName: string, identifier: string | number): boolean {\n const suffix = `-${identifier}`\n return fileName.endsWith(suffix)\n }\n}\n","import type { DatabaseProvider } from '../types/index.js'\nimport { EnvironmentManager } from './EnvironmentManager.js'\nimport { getLogger } from '../utils/logger-context.js'\nimport { hasVariableInAnyEnvFile } from '../utils/env.js'\nimport fs from 'fs-extra'\n\n/**\n * Database Manager - orchestrates database operations with conditional execution\n * Ports functionality from bash scripts with guard conditions:\n * 1. Database provider must be properly configured (provider.isConfigured())\n * 2. The worktree's .env file must contain the configured database URL variable (default: DATABASE_URL)\n *\n * This ensures database branching only occurs for projects that actually use databases\n */\nexport class DatabaseManager {\n constructor(\n private provider: DatabaseProvider,\n private environment: EnvironmentManager,\n private databaseUrlEnvVarName: string = 'DATABASE_URL'\n ) {\n // Debug: Show which database URL variable name is configured\n if (databaseUrlEnvVarName !== 'DATABASE_URL') {\n getLogger().debug(`DatabaseManager configured with custom variable: ${databaseUrlEnvVarName}`)\n } else {\n getLogger().debug('DatabaseManager using default variable: DATABASE_URL')\n }\n }\n\n /**\n * Get the configured database URL environment variable name\n */\n getConfiguredVariableName(): string {\n return this.databaseUrlEnvVarName\n }\n\n /**\n * Check if database branching should be used\n * Requires BOTH conditions:\n * 1. Database provider is properly configured (checked via provider.isConfigured())\n * 2. Any dotenv-flow file contains the configured database URL variable\n */\n async shouldUseDatabaseBranching(workspacePath: string): Promise<boolean> {\n // Check for provider configuration\n if (!this.provider.isConfigured()) {\n getLogger().debug('Skipping database branching: Database provider not configured')\n return false\n }\n\n // Check if any dotenv-flow file has the configured database URL variable\n const hasDatabaseUrl = await this.hasDatabaseUrlInEnv(workspacePath)\n if (!hasDatabaseUrl) {\n getLogger().debug(\n 'Skipping database branching: configured database URL variable not found in any env file'\n )\n return false\n }\n\n return true\n }\n\n /**\n * Create database branch only if configured\n * Returns connection string if branch was created, null if skipped\n *\n * @param branchName - Name of the branch to create\n * @param workspacePath - Path to workspace for configuration checks (checks all dotenv-flow files)\n * @param cwd - Optional working directory to run commands from\n * @param fromBranch - Optional parent branch to create from (for child looms)\n */\n async createBranchIfConfigured(\n branchName: string,\n workspacePath: string,\n cwd?: string,\n fromBranch?: string\n ): Promise<string | null> {\n // Guard condition: check if database branching should be used\n if (!(await this.shouldUseDatabaseBranching(workspacePath))) {\n return null\n }\n\n // Check CLI availability and authentication\n if (!(await this.provider.isCliAvailable())) {\n getLogger().warn(`Skipping database branch creation: ${this.provider.displayName} CLI not available`)\n getLogger().warn(`Install with: ${this.provider.installHint}`)\n return null\n }\n\n try {\n const isAuth = await this.provider.isAuthenticated(cwd)\n if (!isAuth) {\n getLogger().warn(`Skipping database branch creation: Not authenticated with ${this.provider.displayName} CLI`)\n return null\n }\n } catch (error) {\n // Authentication check failed with an unexpected error - surface it\n const errorMessage = error instanceof Error ? error.message : String(error)\n getLogger().error(`Database authentication check failed: ${errorMessage}`)\n throw error\n }\n\n try {\n // Create the branch (which checks for preview first)\n // Pass fromBranch if provided (for child looms), otherwise undefined (uses configured parent)\n const connectionString = await this.provider.createBranch(branchName, fromBranch, cwd)\n getLogger().success(`Database branch ready: ${this.provider.sanitizeBranchName(branchName)}`)\n return connectionString\n } catch (error) {\n getLogger().error(\n `Failed to create database branch: ${error instanceof Error ? error.message : String(error)}`\n )\n throw error\n }\n }\n\n /**\n * Delete database branch only if configured\n * Returns result object indicating what happened\n *\n * @param branchName - Name of the branch to delete\n * @param shouldCleanup - Boolean indicating if database cleanup should be performed (pre-fetched config)\n * @param isPreview - Whether this is a preview database branch\n * @param cwd - Optional working directory to run commands from (prevents issues with deleted directories)\n */\n async deleteBranchIfConfigured(\n branchName: string,\n shouldCleanup: boolean,\n isPreview: boolean = false,\n cwd?: string\n ): Promise<import('../types/index.js').DatabaseDeletionResult> {\n // If shouldCleanup is explicitly false, skip immediately\n if (shouldCleanup === false) {\n return {\n success: true,\n deleted: false,\n notFound: true, // Treat \"not configured\" as \"nothing to delete\"\n branchName\n }\n }\n\n // If shouldCleanup is explicitly true, validate provider configuration\n if (!this.provider.isConfigured()) {\n getLogger().debug('Skipping database branch deletion: Database provider not configured')\n return {\n success: true,\n deleted: false,\n notFound: true,\n branchName\n }\n }\n\n // Check CLI availability and authentication\n if (!(await this.provider.isCliAvailable())) {\n getLogger().info(`Skipping database branch deletion: ${this.provider.displayName} CLI not available. Install with: ${this.provider.installHint}`)\n return {\n success: false,\n deleted: false,\n notFound: true,\n error: `${this.provider.displayName} CLI not available`,\n branchName\n }\n }\n\n try {\n const isAuth = await this.provider.isAuthenticated(cwd)\n if (!isAuth) {\n getLogger().warn(`Skipping database branch deletion: Not authenticated with ${this.provider.displayName}`)\n return {\n success: false,\n deleted: false,\n notFound: false,\n error: `Not authenticated with ${this.provider.displayName}`,\n branchName\n }\n }\n } catch (error) {\n // Authentication check failed with an unexpected error - surface it\n const errorMessage = error instanceof Error ? error.message : String(error)\n getLogger().error(`Database authentication check failed: ${errorMessage}`)\n return {\n success: false,\n deleted: false,\n notFound: false,\n error: `Authentication check failed: ${errorMessage}`,\n branchName\n }\n }\n\n try {\n // Call provider and return its result directly\n const result = await this.provider.deleteBranch(branchName, isPreview, cwd)\n return result\n } catch (error) {\n // Unexpected error (shouldn't happen since provider returns result object)\n getLogger().warn(\n `Unexpected error in database deletion: ${error instanceof Error ? error.message : String(error)}`\n )\n return {\n success: false,\n deleted: false,\n notFound: false,\n error: error instanceof Error ? error.message : String(error),\n branchName\n }\n }\n }\n\n /**\n * Get database branch name from connection string (reverse lookup)\n * Returns branch name if provider supports reverse lookup, null otherwise\n *\n * @param connectionString - Database connection string\n * @param cwd - Optional working directory to run commands from\n */\n async getBranchNameFromConnectionString(connectionString: string, cwd?: string): Promise<string | null> {\n // Check if provider supports reverse lookup (duck typing)\n if (!this.provider.isConfigured()) {\n getLogger().debug('Provider not configured, skipping reverse lookup')\n return null\n }\n\n if ('getBranchNameFromConnectionString' in this.provider &&\n typeof this.provider.getBranchNameFromConnectionString === 'function') {\n return this.provider.getBranchNameFromConnectionString(connectionString, cwd)\n }\n\n getLogger().debug('Provider does not support reverse lookup')\n return null\n }\n\n /**\n * Check if any dotenv-flow file has the configured database URL variable\n * CRITICAL: If user explicitly configured a custom variable name (not default),\n * throw an error if it's missing from all env files\n */\n private async hasDatabaseUrlInEnv(workspacePath: string): Promise<boolean> {\n try {\n // Debug: Show what we're looking for\n if (this.databaseUrlEnvVarName !== 'DATABASE_URL') {\n getLogger().debug(`Looking for custom database URL variable: ${this.databaseUrlEnvVarName}`)\n } else {\n getLogger().debug('Looking for default database URL variable: DATABASE_URL')\n }\n\n // Check all dotenv-flow files for the configured variable\n const hasConfiguredVar = await hasVariableInAnyEnvFile(\n workspacePath,\n this.databaseUrlEnvVarName,\n async (p) => fs.pathExists(p),\n async (p, v) => this.environment.getEnvVariable(p, v)\n )\n\n if (hasConfiguredVar) {\n if (this.databaseUrlEnvVarName !== 'DATABASE_URL') {\n getLogger().debug(`✅ Found custom database URL variable: ${this.databaseUrlEnvVarName}`)\n } else {\n getLogger().debug(`✅ Found default database URL variable: DATABASE_URL`)\n }\n return true\n }\n\n // If user explicitly configured a custom variable name (not the default)\n // and it's missing, throw an error\n if (this.databaseUrlEnvVarName !== 'DATABASE_URL') {\n getLogger().debug(`❌ Custom database URL variable '${this.databaseUrlEnvVarName}' not found in any env file`)\n throw new Error(\n `Configured database URL environment variable '${this.databaseUrlEnvVarName}' not found in any dotenv-flow file. ` +\n `Please add it to an .env file or update your iloom configuration.`\n )\n }\n\n // Fall back to DATABASE_URL when using default configuration\n const hasDefaultVar = await hasVariableInAnyEnvFile(\n workspacePath,\n 'DATABASE_URL',\n async (p) => fs.pathExists(p),\n async (p, v) => this.environment.getEnvVariable(p, v)\n )\n\n if (hasDefaultVar) {\n getLogger().debug('✅ Found fallback DATABASE_URL variable')\n } else {\n getLogger().debug('❌ No DATABASE_URL variable found in any env file')\n }\n return hasDefaultVar\n } catch (error) {\n // Re-throw configuration errors\n if (error instanceof Error && error.message.includes('not found in')) {\n throw error\n }\n // Return false for other errors\n return false\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,WAAU;AACjB,OAAOC,SAAQ;AACf,OAAO,QAAQ;;;ACFf,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,OAAO,QAAQ,kBAAkB;AAoCnC,IAAM,oBAAN,MAAwB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO9B,MAAM,iBAAiB,eAAuB,UAAiC;AAC9E,UAAM,YAAY,KAAK,KAAK,eAAe,SAAS;AACpD,UAAM,eAAe,KAAK,KAAK,WAAW,eAAe;AAEzD,QAAI;AAEH,YAAM,GAAG,UAAU,SAAS;AAG5B,YAAM,WAAW,MAAM,KAAK,aAAa,YAAY;AAGrD,YAAM,kBAAkB,KAAK,mBAAmB,UAAU,QAAQ;AAGlE,YAAM,KAAK,cAAc,cAAc,eAAe;AAEtD,aAAO,MAAM,iCAAiC,QAAQ,QAAQ,aAAa,EAAE;AAAA,IAC9E,SAAS,OAAO;AACf,YAAM,IAAI;AAAA,QACT,yCAAyC,iBAAiB,QAAQ,MAAM,UAAU,eAAe;AAAA,MAClG;AAAA,IACD;AAAA,EACD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAc,aAAa,cAA+C;AACzE,QAAI;AAEH,UAAI,CAAE,MAAM,GAAG,WAAW,YAAY,GAAI;AACzC,eAAO,CAAC;AAAA,MACT;AAGA,YAAM,UAAU,MAAM,GAAG,SAAS,cAAc,MAAM;AAGtD,YAAM,SAA8C,CAAC;AACrD,YAAM,WAAW,MAAM,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C;AAAA,QAC5B,OAAO,GAAG,MAAM,KAAK,YAAY,eAAe,GAAG,CAAC;AAAA,MACtD;AAEA,UAAI,eAAe;AACjB,kBAAU,EAAE,MAAM,6CAAwC;AAAA,MAC5D,OAAO;AACL,kBAAU,EAAE,MAAM,uDAAkD;AAAA,MACtE;AACA,aAAO;AAAA,IACT,SAAS,OAAO;AAEd,UAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,cAAc,GAAG;AACpE,cAAM;AAAA,MACR;AAEA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["path","fs","path","fs","fs","fs","fs","path","path","fs","fs"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/SettingsManager.ts"],"sourcesContent":["import { readFile } from 'fs/promises'\nimport path from 'path'\nimport os from 'os'\nimport { z } from 'zod'\nimport deepmerge from 'deepmerge'\nimport { logger } from '../utils/logger.js'\n\n// Merge mode: canonical values + legacy aliases accepted at parse time\nexport const mergeModeValues = ['local', 'pr', 'draft-pr', 'github-pr', 'github-draft-pr', 'bitbucket-pr'] as const\nexport type MergeMode = 'local' | 'pr' | 'draft-pr'\nconst mergeModeTransform = (val: string): MergeMode => {\n\tconst map: Record<string, MergeMode> = { 'github-pr': 'pr', 'github-draft-pr': 'draft-pr', 'bitbucket-pr': 'pr' }\n\treturn (map[val] ?? val) as MergeMode\n}\n\n/**\n * Zod schema for base agent settings (without nested agents)\n */\nexport const BaseAgentSettingsSchema = z.object({\n\tmodel: z\n\t\t.enum(['sonnet', 'opus', 'haiku'])\n\t\t.optional()\n\t\t.describe('Claude model shorthand: sonnet, opus, or haiku'),\n\tswarmModel: z\n\t\t.enum(['sonnet', 'opus', 'haiku'])\n\t\t.optional()\n\t\t.describe('Model to use for this agent in swarm mode. Overrides the base model when running inside swarm workers.'),\n\tenabled: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Whether this agent is enabled. Defaults to true.'),\n\tproviders: z\n\t\t.record(\n\t\t\tz.enum(['claude', 'gemini', 'codex']),\n\t\t\tz.string()\n\t\t)\n\t\t.optional()\n\t\t.describe('Map of review providers to model names. Keys: claude, gemini, codex. Values: model name strings (e.g., \"sonnet\", \"gemini-3-pro-preview\", \"gpt-5.2-codex\")'),\n\treview: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Whether artifacts from this agent should be reviewed before posting (defaults to false)'),\n\tswarmReview: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Whether artifacts from this agent should be reviewed in swarm mode. Defaults to false if not set (review is off in swarm mode for speed and cost unless explicitly enabled).'),\n})\n\n/**\n * Zod schema for agent settings.\n */\nexport const AgentSettingsSchema = BaseAgentSettingsSchema\n\n/**\n * Zod schema for spin agent settings with default model\n * Used for the spin orchestrator configuration\n */\nexport const SpinAgentSettingsSchema = z.object({\n\tmodel: z\n\t\t.enum(['sonnet', 'opus', 'haiku'])\n\t\t.default('opus')\n\t\t.describe('Claude model shorthand for spin orchestrator'),\n\tswarmModel: z\n\t\t.enum(['sonnet', 'opus', 'haiku'])\n\t\t.optional()\n\t\t.describe('Model for the spin orchestrator when running in swarm mode. Overrides spin.model for swarm workflows.'),\n\tpostSwarmReview: z\n\t\t.boolean()\n\t\t.default(true)\n\t\t.describe('Run a full code review after swarm completion, auto-fixing issues with confidence 80+. Defaults to true.'),\n})\n\n/**\n * Zod schema for plan command settings with default model\n * Used for the plan command configuration\n */\nexport const PlanCommandSettingsSchema = z.object({\n\tmodel: z\n\t\t.enum(['sonnet', 'opus', 'haiku'])\n\t\t.default('opus')\n\t\t.describe('Claude model shorthand for plan command'),\n\tplanner: z\n\t\t.enum(['claude', 'gemini', 'codex'])\n\t\t.default('claude')\n\t\t.describe('AI provider for creating the plan'),\n\treviewer: z\n\t\t.enum(['claude', 'gemini', 'codex', 'none'])\n\t\t.default('none')\n\t\t.describe('AI provider for reviewing the plan (none to skip review)'),\n\twaveVerification: z\n\t\t.boolean()\n\t\t.default(true)\n\t\t.describe('When enabled, the planner generates verification child issues between dependency waves to catch integration issues early.'),\n})\n\n/**\n * Zod schema for summary settings with default model\n * Used for session summary generation configuration\n */\nexport const SummarySettingsSchema = z.object({\n\tmodel: z\n\t\t.enum(['sonnet', 'opus', 'haiku'])\n\t\t.default('sonnet')\n\t\t.describe('Claude model shorthand for session summary generation'),\n})\n\n/**\n * Zod schema for workflow permission configuration\n */\nexport const WorkflowPermissionSchema = z.object({\n\tpermissionMode: z\n\t\t.enum(['plan', 'acceptEdits', 'bypassPermissions', 'default'])\n\t\t.optional()\n\t\t.describe('Permission mode for Claude CLI in this workflow type'),\n\tnoVerify: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Skip pre-commit hooks (--no-verify) when committing during commit and finish workflows'),\n\tstartIde: z\n\t\t.boolean()\n\t\t.default(true)\n\t\t.describe('Launch IDE (code) when starting this workflow type'),\n\tstartDevServer: z\n\t\t.boolean()\n\t\t.default(true)\n\t\t.describe('Launch development server when starting this workflow type'),\n\tstartAiAgent: z\n\t\t.boolean()\n\t\t.default(true)\n\t\t.describe('Launch Claude Code agent when starting this workflow type'),\n\tstartTerminal: z\n\t\t.boolean()\n\t\t.default(false)\n\t\t.describe('Launch terminal window without dev server when starting this workflow type'),\n\tgenerateSummary: z\n\t\t.boolean()\n\t\t.default(true)\n\t\t.describe('Generate and post Claude session summary when finishing this workflow type'),\n})\n\n/**\n * Non-defaulting variant for pre-merge validation\n * This prevents Zod from polluting partial settings with default values before merge\n */\nexport const WorkflowPermissionSchemaNoDefaults = z.object({\n\tpermissionMode: z\n\t\t.enum(['plan', 'acceptEdits', 'bypassPermissions', 'default'])\n\t\t.optional()\n\t\t.describe('Permission mode for Claude CLI in this workflow type'),\n\tnoVerify: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Skip pre-commit hooks (--no-verify) when committing during commit and finish workflows'),\n\tstartIde: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Launch IDE (code) when starting this workflow type'),\n\tstartDevServer: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Launch development server when starting this workflow type'),\n\tstartAiAgent: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Launch Claude Code agent when starting this workflow type'),\n\tstartTerminal: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Launch terminal window without dev server when starting this workflow type'),\n\tgenerateSummary: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Generate and post Claude session summary when finishing this workflow type'),\n})\n\n/**\n * Zod schema for workflows settings\n */\nexport const WorkflowsSettingsSchema = z\n\t.object({\n\t\tissue: WorkflowPermissionSchema.optional(),\n\t\tpr: WorkflowPermissionSchema.optional(),\n\t\tregular: WorkflowPermissionSchema.optional(),\n\t})\n\t.optional()\n\n/**\n * Non-defaulting variant for pre-merge validation\n */\nexport const WorkflowsSettingsSchemaNoDefaults = z\n\t.object({\n\t\tissue: WorkflowPermissionSchemaNoDefaults.optional(),\n\t\tpr: WorkflowPermissionSchemaNoDefaults.optional(),\n\t\tregular: WorkflowPermissionSchemaNoDefaults.optional(),\n\t})\n\t.optional()\n\n/**\n * Zod schema for capabilities settings\n */\nexport const CapabilitiesSettingsSchema = z\n\t.object({\n\t\tweb: z\n\t\t\t.object({\n\t\t\t\tbasePort: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.min(1, 'Base port must be >= 1')\n\t\t\t\t\t.max(65535, 'Base port must be <= 65535')\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Base port for web workspace port calculations (default: 3000)'),\n\t\t\t\tdevServer: z\n\t\t\t\t\t.enum(['process', 'docker'])\n\t\t\t\t\t.default('process')\n\t\t\t\t\t.describe('Dev server mode: \"process\" runs natively, \"docker\" runs inside a Docker container with port mapping'),\n\t\t\t\tdockerFile: z\n\t\t\t\t\t.string()\n\t\t\t\t\t.default('./Dockerfile')\n\t\t\t\t\t.describe('Path to Dockerfile relative to worktree root (only used when devServer is \"docker\")'),\n\t\t\t\tcontainerPort: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.min(1, 'Container port must be >= 1')\n\t\t\t\t\t.max(65535, 'Container port must be <= 65535')\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Port the app runs on inside the Docker container (auto-detected from EXPOSE directive if not set)'),\n\t\t\t\tdockerBuildArgs: z\n\t\t\t\t\t.record(z.string())\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Build arguments to pass to docker build (e.g., {\"NODE_ENV\": \"development\"})'),\n\t\t\t\tdockerRunArgs: z\n\t\t\t\t\t.array(z.string())\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Additional arguments for docker run (e.g., [\"-v\", \"./src:/app/src\"] for volume mounts)'),\n\t\t\t})\n\t\t\t.optional()\n\t\t\t.describe('Web dev server settings. To declare a project as a web project, add \"web\" to the capabilities array in .iloom/package.iloom.json or .iloom/package.iloom.local.json.'),\n\t\tdatabase: z\n\t\t\t.object({\n\t\t\t\tdatabaseUrlEnvVarName: z\n\t\t\t\t\t.string()\n\t\t\t\t\t.min(1, 'Database URL variable name cannot be empty')\n\t\t\t\t\t.regex(/^[A-Z_][A-Z0-9_]*$/, 'Must be valid env var name (uppercase, underscores)')\n\t\t\t\t\t.optional()\n\t\t\t\t\t.default('DATABASE_URL')\n\t\t\t\t\t.describe('Name of environment variable for database connection URL'),\n\t\t\t})\n\t\t\t.optional(),\n\t})\n\t.optional()\n\n/**\n * Non-defaulting variant for pre-merge validation\n */\nexport const CapabilitiesSettingsSchemaNoDefaults = z\n\t.object({\n\t\tweb: z\n\t\t\t.object({\n\t\t\t\tbasePort: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.min(1, 'Base port must be >= 1')\n\t\t\t\t\t.max(65535, 'Base port must be <= 65535')\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Base port for web workspace port calculations (default: 3000)'),\n\t\t\t\tdevServer: z\n\t\t\t\t\t.enum(['process', 'docker'])\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Dev server mode: \"process\" runs natively, \"docker\" runs inside a Docker container with port mapping'),\n\t\t\t\tdockerFile: z\n\t\t\t\t\t.string()\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Path to Dockerfile relative to worktree root (only used when devServer is \"docker\")'),\n\t\t\t\tcontainerPort: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.min(1, 'Container port must be >= 1')\n\t\t\t\t\t.max(65535, 'Container port must be <= 65535')\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Port the app runs on inside the Docker container (auto-detected from EXPOSE directive if not set)'),\n\t\t\t\tdockerBuildArgs: z\n\t\t\t\t\t.record(z.string())\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Build arguments to pass to docker build (e.g., {\"NODE_ENV\": \"development\"})'),\n\t\t\t\tdockerRunArgs: z\n\t\t\t\t\t.array(z.string())\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Additional arguments for docker run (e.g., [\"-v\", \"./src:/app/src\"] for volume mounts)'),\n\t\t\t})\n\t\t\t.optional()\n\t\t\t.describe('Web dev server settings. To declare a project as a web project, add \"web\" to the capabilities array in .iloom/package.iloom.json or .iloom/package.iloom.local.json.'),\n\t\tdatabase: z\n\t\t\t.object({\n\t\t\t\tdatabaseUrlEnvVarName: z\n\t\t\t\t\t.string()\n\t\t\t\t\t.min(1, 'Database URL variable name cannot be empty')\n\t\t\t\t\t.regex(/^[A-Z_][A-Z0-9_]*$/, 'Must be valid env var name (uppercase, underscores)')\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Name of environment variable for database connection URL'),\n\t\t\t})\n\t\t\t.optional(),\n\t})\n\t.optional()\n\n/**\n * Zod schema for Docker dev server settings\n */\nexport const DevServerSettingsSchema = z.object({\n\tmode: z\n\t\t.enum(['docker'])\n\t\t.default('docker')\n\t\t.describe('Dev server mode. Currently only \"docker\" is supported.'),\n\tdocker: z\n\t\t.object({\n\t\t\tdockerFile: z\n\t\t\t\t.string()\n\t\t\t\t.default('./Dockerfile')\n\t\t\t\t.refine(\n\t\t\t\t\t(val) => {\n\t\t\t\t\t\t// Must be a relative path (no leading slash)\n\t\t\t\t\t\tif (path.isAbsolute(val)) return false\n\t\t\t\t\t\t// Must not traverse outside the project root\n\t\t\t\t\t\tconst normalized = path.normalize(val)\n\t\t\t\t\t\tif (normalized.startsWith('..')) return false\n\t\t\t\t\t\treturn true\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t'dockerFile must be a relative path that does not traverse outside the project root (no leading \"/\" and no \"../\" escaping)',\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t\t.describe('Path to Dockerfile relative to worktree root'),\n\t\t\tcontainerPort: z\n\t\t\t\t.number()\n\t\t\t\t.min(1, 'Container port must be >= 1')\n\t\t\t\t.max(65535, 'Container port must be <= 65535')\n\t\t\t\t.optional()\n\t\t\t\t.describe('Port the app runs on inside the Docker container (auto-detected from EXPOSE directive if not set)'),\n\t\t\tbuildArgs: z\n\t\t\t\t.record(z.string(), z.string())\n\t\t\t\t.optional()\n\t\t\t\t.describe('Build arguments to pass to docker build'),\n\t\t\trunArgs: z\n\t\t\t\t.array(z.string())\n\t\t\t\t.optional()\n\t\t\t\t.describe('Additional arguments for docker run'),\n\t\t})\n\t\t.optional(),\n})\n\n/**\n * Non-defaulting variant of DevServerSettingsSchema for pre-merge validation\n * This prevents Zod from polluting partial settings with default values before merge\n */\nexport const DevServerSettingsSchemaNoDefaults = z.object({\n\tmode: z\n\t\t.enum(['docker'])\n\t\t.optional()\n\t\t.describe('Dev server mode. Currently only \"docker\" is supported.'),\n\tdocker: z\n\t\t.object({\n\t\t\tdockerFile: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.refine(\n\t\t\t\t\t(val) => {\n\t\t\t\t\t\tif (val === undefined) return true\n\t\t\t\t\t\tif (path.isAbsolute(val)) return false\n\t\t\t\t\t\tconst normalized = path.normalize(val)\n\t\t\t\t\t\tif (normalized.startsWith('..')) return false\n\t\t\t\t\t\treturn true\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t'dockerFile must be a relative path that does not traverse outside the project root (no leading \"/\" and no \"../\" escaping)',\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t\t.describe('Path to Dockerfile relative to worktree root'),\n\t\t\tcontainerPort: z\n\t\t\t\t.number()\n\t\t\t\t.min(1, 'Container port must be >= 1')\n\t\t\t\t.max(65535, 'Container port must be <= 65535')\n\t\t\t\t.optional()\n\t\t\t\t.describe('Port the app runs on inside the Docker container (auto-detected from EXPOSE directive if not set)'),\n\t\t\tbuildArgs: z\n\t\t\t\t.record(z.string(), z.string())\n\t\t\t\t.optional()\n\t\t\t\t.describe('Build arguments to pass to docker build'),\n\t\t\trunArgs: z\n\t\t\t\t.array(z.string())\n\t\t\t\t.optional()\n\t\t\t\t.describe('Additional arguments for docker run'),\n\t\t})\n\t\t.optional(),\n})\n\n/**\n * Zod schema for Neon database provider settings\n */\nexport const NeonSettingsSchema = z.object({\n\tprojectId: z\n\t\t.string()\n\t\t.min(1)\n\t\t.regex(/^[a-zA-Z0-9-]+$/, 'Neon project ID must contain only letters, numbers, and hyphens')\n\t\t.describe('Neon project ID found in your project URL (e.g., \"fantastic-fox-3566354\")'),\n\tparentBranch: z\n\t\t.string()\n\t\t.min(1)\n\t\t.describe('Branch from which new database branches are created'),\n})\n\n/**\n * Zod schema for Supabase database provider settings\n */\nexport const SupabaseSettingsSchema = z.object({\n\tprojectRef: z\n\t\t.string()\n\t\t.min(1)\n\t\t.describe('Supabase project reference ID (e.g., \"abcdefghijklmnop\")'),\n\tparentBranch: z\n\t\t.string()\n\t\t.min(1)\n\t\t.optional()\n\t\t.describe('Reserved for future use. Supabase currently always branches from the default branch.'),\n\twithData: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Whether to include data when creating a new branch (defaults to true)'),\n})\n\n/**\n * Zod schema for database provider settings\n */\nexport const DatabaseProvidersSettingsSchema = z\n\t.object({\n\t\tneon: NeonSettingsSchema.optional().describe(\n\t\t\t'Neon database configuration. Requires Neon CLI installed and authenticated for database branching.',\n\t\t),\n\t\tsupabase: SupabaseSettingsSchema.optional().describe(\n\t\t\t'Supabase database configuration. Requires Supabase CLI installed and authenticated for database branching.',\n\t\t),\n\t})\n\t.optional()\n\n/**\n * Zod schema for iloom settings\n */\nexport const IloomSettingsSchema = z.object({\n\tmainBranch: z\n\t\t.string()\n\t\t.min(1, \"Settings 'mainBranch' cannot be empty\")\n\t\t.optional()\n\t\t.describe('Name of the main/primary branch for the repository'),\n\tsourceEnvOnStart: z\n\t\t.boolean()\n\t\t.default(false)\n\t\t.describe(\n\t\t\t'Source all dotenv-flow files (.env, .env.local, .env.development, .env.development.local) when launching terminal processes (Claude, dev server, terminal). ' +\n\t\t\t\t'Files are sourced in precedence order so later files override earlier ones. ' +\n\t\t\t\t'NOTE TO AI AGENTS: Before making changes to settings files, YOU MUST OFFER to check .env file compatibility. ' +\n\t\t\t\t'WARNING: Unquoted values in .env files may break sourcing in bash/zsh shells. ' +\n\t\t\t\t'Before enabling, verify ALL your .env.* files do not contain unquoted special characters ' +\n\t\t\t\t'(e.g., database URLs with ?, &, or other shell metacharacters). ' +\n\t\t\t\t'Shell compatibility issues may cause processes to fail or behave unexpectedly.',\n\t\t),\n\tworktreePrefix: z\n\t\t.string()\n\t\t.optional()\n\t\t.refine(\n\t\t\t(val) => {\n\t\t\t\tif (val === undefined) return true // undefined = use default calculation\n\t\t\t\tif (val === '') return true // empty string = no prefix mode\n\n\t\t\t\t// Allowlist: only alphanumeric, hyphens, underscores, and forward slashes\n\t\t\t\tconst allowedChars = /^[a-zA-Z0-9\\-_/]+$/\n\t\t\t\tif (!allowedChars.test(val)) return false\n\n\t\t\t\t// Reject if only special characters (no alphanumeric content)\n\t\t\t\tif (/^[-_/]+$/.test(val)) return false\n\n\t\t\t\t// Check each segment (split by /) contains at least one alphanumeric character\n\t\t\t\tconst segments = val.split('/')\n\t\t\t\tfor (const segment of segments) {\n\t\t\t\t\tif (segment && /^[-_]+$/.test(segment)) {\n\t\t\t\t\t\t// Segment exists but contains only hyphens/underscores\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true\n\t\t\t},\n\t\t\t{\n\t\t\t\tmessage:\n\t\t\t\t\t\"worktreePrefix contains invalid characters. Only alphanumeric characters, hyphens (-), underscores (_), and forward slashes (/) are allowed. Use forward slashes for nested directories.\",\n\t\t\t},\n\t\t)\n\t\t.describe(\n\t\t\t'Prefix for worktree directories. Empty string disables prefix. Defaults to <repo-name>-looms if not set.',\n\t\t),\n\tprotectedBranches: z\n\t\t.array(z.string().min(1, 'Protected branch name cannot be empty'))\n\t\t.optional()\n\t\t.describe('List of branches that cannot be deleted (defaults to [mainBranch, \"main\", \"master\", \"develop\"])'),\n\tcopyGitIgnoredPatterns: z\n\t\t.array(z.string().min(1, 'Pattern cannot be empty'))\n\t\t.optional()\n\t\t.describe('Glob patterns for gitignored files to copy to looms (e.g., [\"*.db\", \"data/*.sqlite\"]). Great for local dbs and large test data files that are too big to commit to git. Note: .env (dotenv-flow) files, iloom\\'s and claude\\'s local settings are automatically copied and do not need to be specified here.'),\n\tworkflows: WorkflowsSettingsSchema.describe('Per-workflow-type permission configurations'),\n\tagents: z\n\t\t.record(z.string(), AgentSettingsSchema)\n\t\t.optional()\n\t\t.nullable()\n\t\t.describe(\n\t\t\t'Per-agent configuration overrides. Available agents: ' +\n\t\t\t\t'iloom-issue-analyzer (analyzes issues), ' +\n\t\t\t\t'iloom-issue-planner (creates implementation plans), ' +\n\t\t\t\t'iloom-issue-analyze-and-plan (combined analysis and planning), ' +\n\t\t\t\t'iloom-issue-complexity-evaluator (evaluates complexity), ' +\n\t\t\t\t'iloom-issue-enhancer (enhances issue descriptions), ' +\n\t\t\t\t'iloom-issue-implementer (implements code changes), ' +\n\t\t\t\t'iloom-code-reviewer (reviews code changes against requirements), ' +\n\t\t\t\t'iloom-artifact-reviewer (reviews artifacts before posting), ' +\n\t\t\t\t'iloom-swarm-worker (swarm worker agent, dynamically generated). ' +\n\t\t\t\t'Use swarmModel on any agent to override its model in swarm mode.',\n\t\t),\n\tspin: SpinAgentSettingsSchema.optional().describe(\n\t\t'Spin orchestrator configuration. Model defaults to opus when not configured.',\n\t),\n\tplan: PlanCommandSettingsSchema.optional().describe(\n\t\t'Plan command configuration. Model defaults to opus, planner to claude, reviewer to none when not configured.',\n\t),\n\tsummary: SummarySettingsSchema.optional().describe(\n\t\t'Session summary generation configuration. Model defaults to sonnet when not configured.',\n\t),\n\tcapabilities: CapabilitiesSettingsSchema.describe('Project capability configurations'),\n\tdevServer: DevServerSettingsSchema.optional().describe('Docker-based dev server configuration'),\n\tdatabaseProviders: DatabaseProvidersSettingsSchema.describe('Database provider configurations'),\n\tissueManagement: z\n\t\t.object({\n\t\t\t// SYNC: If this default changes, update displayDefaultsBox() in src/utils/first-run-setup.ts\n\t\t\tprovider: z.enum(['github', 'linear', 'jira']).optional().default('github').describe('Issue tracker provider (github, linear, jira)'),\n\t\t\tgithub: z\n\t\t\t\t.object({\n\t\t\t\t\tremote: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'Remote name cannot be empty')\n\t\t\t\t\t\t.describe('Git remote name to use for GitHub operations'),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t\tlinear: z\n\t\t\t\t.object({\n\t\t\t\t\tteamId: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'Team ID cannot be empty')\n\t\t\t\t\t\t.describe('Linear team identifier (e.g., \"ENG\", \"PLAT\")'),\n\t\t\t\t\tbranchFormat: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Branch naming template for Linear issues'),\n\t\t\t\t\tapiToken: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Linear API token (lin_api_...). SECURITY: Store in settings.local.json only, never commit to source control.'),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t\tjira: z\n\t\t\t\t.object({\n\t\t\t\t\thost: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'Jira host cannot be empty')\n\t\t\t\t\t\t.describe('Jira instance URL (e.g., \"https://yourcompany.atlassian.net\")'),\n\t\t\t\t\tusername: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'Jira username/email cannot be empty')\n\t\t\t\t\t\t.describe('Jira username or email address'),\n\t\t\t\t\tapiToken: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Jira API token. SECURITY: Store in settings.local.json only, never commit to source control. Generate at: https://id.atlassian.com/manage-profile/security/api-tokens'),\n\t\t\t\t\tprojectKey: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'Project key cannot be empty')\n\t\t\t\t\t\t.describe('Jira project key (e.g., \"PROJ\", \"ENG\")'),\n\t\t\t\t\tboardId: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Jira board ID for sprint/workflow operations (optional)'),\n\t\t\t\t\ttransitionMappings: z\n\t\t\t\t\t\t.record(z.string(), z.string())\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Map iloom states to Jira transition names (e.g., {\"In Review\": \"Start Review\"})'),\n\t\t\t\t\tdefaultIssueType: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1)\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.default('Task')\n\t\t\t\t\t\t.describe('Default Jira issue type name for creating issues (e.g., \"Task\", \"Story\", \"Bug\")'),\n\t\t\t\t\tdefaultSubtaskType: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1)\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.default('Subtask')\n\t\t\t\t\t\t.describe('Default Jira issue type name for creating subtasks/child issues (e.g., \"Subtask\", \"Sub-task\")'),\n\t\t\t\t\tdoneStatuses: z\n\t\t\t\t\t\t.array(z.string())\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.default(['Done'])\n\t\t\t\t\t\t.describe('Status names to exclude from issue lists (e.g., [\"Done\", \"Closed\", \"Verify\"])'),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t})\n\t\t.optional()\n\t\t.describe('Issue management configuration'),\n\tversionControl: z\n\t\t.object({\n\t\t\tprovider: z.enum(['github', 'bitbucket']).optional().default('github').describe('Version control provider (github, bitbucket)'),\n\t\t\tbitbucket: z\n\t\t\t\t.object({\n\t\t\t\t\tusername: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'BitBucket username cannot be empty')\n\t\t\t\t\t\t.describe('BitBucket username'),\n\t\t\t\t\tapiToken: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('BitBucket API token. SECURITY: Store in settings.local.json only, never commit to source control. Generate at: https://bitbucket.org/account/settings/app-passwords/ (Note: App passwords deprecated Sep 2025, use API tokens)'),\n\t\t\t\t\tworkspace: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('BitBucket workspace (optional, auto-detected from git remote if not provided)'),\n\t\t\t\t\trepoSlug: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('BitBucket repository slug (optional, auto-detected from git remote if not provided)'),\n\t\t\t\treviewers: z\n\t\t\t\t\t.array(z.string().describe('Reviewer username'))\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('List of usernames to add as PR reviewers. Usernames are resolved to Bitbucket account IDs at PR creation time.'),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t})\n\t\t.optional()\n\t\t.describe('Version control provider configuration'),\n\tmergeBehavior: z\n\t\t.object({\n\t\t\t// SYNC: If this default changes, update displayDefaultsBox() in src/utils/first-run-setup.ts\n\t\t\tmode: z.enum(mergeModeValues).default('local').transform(mergeModeTransform),\n\t\t\tremote: z.string().optional(),\n\t\t\tautoCommitPush: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\t\t\t'Auto-commit and push after code review in draft PR mode. Defaults to true when mode is draft-pr.'\n\t\t\t\t),\n\t\t\tprTitlePrefix: z.boolean().default(false).optional().describe('Prefix PR titles with the issue number (e.g., \"QLH-123: Title\"). Default: false'),\n\t\t\topenBrowserOnFinish: z\n\t\t\t\t.boolean()\n\t\t\t\t.default(true)\n\t\t\t\t.describe(\n\t\t\t\t\t'Open the PR in the default browser after finishing in pr or draft-pr mode. Use --no-browser flag to override.'\n\t\t\t\t),\n\t\t})\n\t\t.optional()\n\t\t.describe('Merge behavior configuration: local (merge locally), pr (create PR), or draft-pr (create draft PR at start, mark ready on finish)'),\n\tide: z\n\t\t.object({\n\t\t\t// SYNC: If this default changes, update displayDefaultsBox() in src/utils/first-run-setup.ts\n\t\t\ttype: z\n\t\t\t\t.enum(['vscode', 'cursor', 'webstorm', 'sublime', 'intellij', 'windsurf', 'antigravity'])\n\t\t\t\t.default('vscode')\n\t\t\t\t.describe(\n\t\t\t\t\t'IDE to launch when starting a loom. Options: vscode (Visual Studio Code), cursor (Cursor AI editor), ' +\n\t\t\t\t\t\t'webstorm (JetBrains WebStorm), sublime (Sublime Text), intellij (JetBrains IntelliJ IDEA), ' +\n\t\t\t\t\t\t'windsurf (Windsurf editor), antigravity (Antigravity IDE).'\n\t\t\t\t),\n\t\t})\n\t\t.optional()\n\t\t.describe(\n\t\t\t'IDE configuration for workspace launches. Controls which editor opens when you start a loom. ' +\n\t\t\t\t'Supports VSCode, Cursor, WebStorm, Sublime Text, IntelliJ, Windsurf, and Antigravity. ' +\n\t\t\t\t'Note: Color synchronization (title bar colors) only works with VSCode-compatible editors (vscode, cursor, windsurf, antigravity).'\n\t\t),\n\tcolors: z\n\t\t.object({\n\t\t\tterminal: z\n\t\t\t\t.boolean()\n\t\t\t\t.default(true)\n\t\t\t\t.describe('Apply terminal background colors based on branch name (macOS only)'),\n\t\t\tvscode: z\n\t\t\t\t.boolean()\n\t\t\t\t.default(false)\n\t\t\t\t.describe(\n\t\t\t\t\t'Apply VSCode/Cursor title bar colors based on branch name. ' +\n\t\t\t\t\t\t'Note: This modifies .vscode/settings.json which may be in source control. ' +\n\t\t\t\t\t\t'Default is false for safety; enable via init or explicitly if .vscode is gitignored.'\n\t\t\t\t),\n\t\t})\n\t\t.optional()\n\t\t.describe('Color synchronization settings for workspace identification'),\n\tattribution: z\n\t\t.enum(['off', 'upstreamOnly', 'on'])\n\t\t.default('upstreamOnly')\n\t\t.describe(\n\t\t\t'Controls when iloom attribution appears in session summaries. ' +\n\t\t\t\t'\"off\" - never show attribution. ' +\n\t\t\t\t'\"upstreamOnly\" - only show for contributions to external repositories (e.g., open source). ' +\n\t\t\t\t'\"on\" - always show attribution.'\n\t\t),\n\tgit: z\n\t\t.object({\n\t\t\tcommitTimeout: z\n\t\t\t\t.number()\n\t\t\t\t.min(1000, 'Commit timeout must be at least 1000ms')\n\t\t\t\t.max(600000, 'Commit timeout cannot exceed 600000ms (10 minutes)')\n\t\t\t\t.default(60000)\n\t\t\t\t.describe('Timeout in milliseconds for git commit operations. Increase for long-running pre-commit hooks.'),\n\t\t})\n\t\t.default({ }) // ensures the object always exists and uses default for the inner properties\n\t\t.describe('Git operation settings'),\n})\n\n/**\n * Non-defaulting variant for pre-merge validation\n * This prevents Zod from polluting partial settings with default values before merge\n */\nexport const IloomSettingsSchemaNoDefaults = z.object({\n\tmainBranch: z\n\t\t.string()\n\t\t.min(1, \"Settings 'mainBranch' cannot be empty\")\n\t\t.optional()\n\t\t.describe('Name of the main/primary branch for the repository'),\n\tsourceEnvOnStart: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Source all dotenv-flow files (.env, .env.local, .env.development, .env.development.local) when launching terminal processes (Claude, dev server, terminal). ' +\n\t\t\t\t'Files are sourced in precedence order so later files override earlier ones. ' +\n\t\t\t\t'NOTE TO AI AGENTS: Before making changes to settings files, YOU MUST OFFER to check .env compatibility. ' +\n\t\t\t\t'WARNING: Unquoted values in .env files may break sourcing in bash/zsh shells. ' +\n\t\t\t\t'Before enabling, verify ALL your .env.* files do not contain unquoted special characters ' +\n\t\t\t\t'(e.g., database URLs with ?, &, or other shell metacharacters). ' +\n\t\t\t\t'Shell compatibility issues may cause processes to fail or behave unexpectedly.',\n\t\t),\n\tworktreePrefix: z\n\t\t.string()\n\t\t.optional()\n\t\t.refine(\n\t\t\t(val) => {\n\t\t\t\tif (val === undefined) return true // undefined = use default calculation\n\t\t\t\tif (val === '') return true // empty string = no prefix mode\n\n\t\t\t\t// Allowlist: only alphanumeric, hyphens, underscores, and forward slashes\n\t\t\t\tconst allowedChars = /^[a-zA-Z0-9\\-_/]+$/\n\t\t\t\tif (!allowedChars.test(val)) return false\n\n\t\t\t\t// Reject if only special characters (no alphanumeric content)\n\t\t\t\tif (/^[-_/]+$/.test(val)) return false\n\n\t\t\t\t// Check each segment (split by /) contains at least one alphanumeric character\n\t\t\t\tconst segments = val.split('/')\n\t\t\t\tfor (const segment of segments) {\n\t\t\t\t\tif (segment && /^[-_]+$/.test(segment)) {\n\t\t\t\t\t\t// Segment exists but contains only hyphens/underscores\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true\n\t\t\t},\n\t\t\t{\n\t\t\t\tmessage:\n\t\t\t\t\t\"worktreePrefix contains invalid characters. Only alphanumeric characters, hyphens (-), underscores (_), and forward slashes (/) are allowed. Use forward slashes for nested directories.\",\n\t\t\t},\n\t\t)\n\t\t.describe(\n\t\t\t'Prefix for worktree directories. Empty string disables prefix. Defaults to <repo-name>-looms if not set.',\n\t\t),\n\tprotectedBranches: z\n\t\t.array(z.string().min(1, 'Protected branch name cannot be empty'))\n\t\t.optional()\n\t\t.describe('List of branches that cannot be deleted (defaults to [mainBranch, \"main\", \"master\", \"develop\"])'),\n\tcopyGitIgnoredPatterns: z\n\t\t.array(z.string().min(1, 'Pattern cannot be empty'))\n\t\t.optional()\n\t\t.describe('Glob patterns for gitignored files to copy to looms (e.g., [\"*.db\", \"data/*.sqlite\"]). Great for local dbs and large test data files that are too big to commit to git. Note: .env (dotenv-flow) files, iloom\\'s and claude\\'s local settings are automatically copied and do not need to be specified here.'),\n\tworkflows: WorkflowsSettingsSchemaNoDefaults.describe('Per-workflow-type permission configurations'),\n\tagents: z\n\t\t.record(z.string(), AgentSettingsSchema)\n\t\t.optional()\n\t\t.nullable()\n\t\t.describe(\n\t\t\t'Per-agent configuration overrides. Available agents: ' +\n\t\t\t\t'iloom-issue-analyzer (analyzes issues), ' +\n\t\t\t\t'iloom-issue-planner (creates implementation plans), ' +\n\t\t\t\t'iloom-issue-analyze-and-plan (combined analysis and planning), ' +\n\t\t\t\t'iloom-issue-complexity-evaluator (evaluates complexity), ' +\n\t\t\t\t'iloom-issue-enhancer (enhances issue descriptions), ' +\n\t\t\t\t'iloom-issue-implementer (implements code changes), ' +\n\t\t\t\t'iloom-code-reviewer (reviews code changes against requirements), ' +\n\t\t\t\t'iloom-artifact-reviewer (reviews artifacts before posting), ' +\n\t\t\t\t'iloom-swarm-worker (swarm worker agent, dynamically generated). ' +\n\t\t\t\t'Use swarmModel on any agent to override its model in swarm mode.',\n\t\t),\n\tspin: z\n\t\t.object({\n\t\t\tmodel: z.enum(['sonnet', 'opus', 'haiku']).optional(),\n\t\t\tswarmModel: z.enum(['sonnet', 'opus', 'haiku']).optional(),\n\t\t\tpostSwarmReview: z.boolean().optional(),\n\t\t})\n\t\t.optional()\n\t\t.describe('Spin orchestrator configuration'),\n\tplan: z\n\t\t.object({\n\t\t\tmodel: z.enum(['sonnet', 'opus', 'haiku']).optional(),\n\t\t\tplanner: z.enum(['claude', 'gemini', 'codex']).optional(),\n\t\t\treviewer: z.enum(['claude', 'gemini', 'codex', 'none']).optional(),\n\t\t\twaveVerification: z.boolean().optional(),\n\t\t})\n\t\t.optional()\n\t\t.describe('Plan command configuration'),\n\tsummary: z\n\t\t.object({\n\t\t\tmodel: z.enum(['sonnet', 'opus', 'haiku']).optional(),\n\t\t})\n\t\t.optional()\n\t\t.describe('Session summary generation configuration'),\n\tcapabilities: CapabilitiesSettingsSchemaNoDefaults.describe('Project capability configurations'),\n\tdevServer: DevServerSettingsSchemaNoDefaults.optional().describe('Docker-based dev server configuration'),\n\tdatabaseProviders: DatabaseProvidersSettingsSchema.describe('Database provider configurations'),\n\tissueManagement: z\n\t\t.object({\n\t\t\tprovider: z.enum(['github', 'linear', 'jira']).optional().describe('Issue tracker provider (github, linear, jira)'),\n\t\t\tgithub: z\n\t\t\t\t.object({\n\t\t\t\t\tremote: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'Remote name cannot be empty')\n\t\t\t\t\t\t.describe('Git remote name to use for GitHub operations'),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t\tlinear: z\n\t\t\t\t.object({\n\t\t\t\t\tteamId: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'Team ID cannot be empty')\n\t\t\t\t\t\t.describe('Linear team identifier (e.g., \"ENG\", \"PLAT\")'),\n\t\t\t\t\tbranchFormat: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Branch naming template for Linear issues'),\n\t\t\t\t\tapiToken: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Linear API token (lin_api_...). SECURITY: Store in settings.local.json only, never commit to source control.'),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t\tjira: z\n\t\t\t\t.object({\n\t\t\t\t\thost: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'Jira host cannot be empty')\n\t\t\t\t\t\t.describe('Jira instance URL (e.g., \"https://yourcompany.atlassian.net\")'),\n\t\t\t\t\tusername: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'Jira username/email cannot be empty')\n\t\t\t\t\t\t.describe('Jira username or email address'),\n\t\t\t\t\tapiToken: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Jira API token. SECURITY: Store in settings.local.json only, never commit to source control. Generate at: https://id.atlassian.com/manage-profile/security/api-tokens'),\n\t\t\t\t\tprojectKey: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'Project key cannot be empty')\n\t\t\t\t\t\t.describe('Jira project key (e.g., \"PROJ\", \"ENG\")'),\n\t\t\t\t\tboardId: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Jira board ID for sprint/workflow operations (optional)'),\n\t\t\t\t\ttransitionMappings: z\n\t\t\t\t\t\t.record(z.string(), z.string())\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Map iloom states to Jira transition names (e.g., {\"In Review\": \"Start Review\"})'),\n\t\t\t\t\tdefaultIssueType: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1)\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Default Jira issue type name for creating issues (e.g., \"Task\", \"Story\", \"Bug\")'),\n\t\t\t\t\tdefaultSubtaskType: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1)\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('Default Jira issue type name for creating subtasks/child issues (e.g., \"Subtask\", \"Sub-task\")'),\n\t\t\t\t\tdoneStatuses: z\n\t\t\t\t\t\t.array(z.string())\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.default(['Done'])\n\t\t\t\t\t\t.describe('Status names to exclude from issue lists (e.g., [\"Done\", \"Closed\", \"Verify\"])'),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t})\n\t\t.optional()\n\t\t.describe('Issue management configuration'),\n\tversionControl: z\n\t\t.object({\n\t\t\tprovider: z.enum(['github', 'bitbucket']).optional().describe('Version control provider (github, bitbucket)'),\n\t\t\tbitbucket: z\n\t\t\t\t.object({\n\t\t\t\t\tusername: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.min(1, 'BitBucket username cannot be empty')\n\t\t\t\t\t\t.describe('BitBucket username'),\n\t\t\t\t\tapiToken: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('BitBucket API token. SECURITY: Store in settings.local.json only, never commit to source control. Generate at: https://bitbucket.org/account/settings/app-passwords/ (Note: App passwords deprecated Sep 2025, use API tokens)'),\n\t\t\t\t\tworkspace: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('BitBucket workspace (optional, auto-detected from git remote if not provided)'),\n\t\t\t\t\trepoSlug: z\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.optional()\n\t\t\t\t\t\t.describe('BitBucket repository slug (optional, auto-detected from git remote if not provided)'),\n\t\t\t\treviewers: z\n\t\t\t\t\t.array(z.string().describe('Reviewer username'))\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('List of usernames to add as PR reviewers. Usernames are resolved to Bitbucket account IDs at PR creation time.'),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t})\n\t\t.optional()\n\t\t.describe('Version control provider configuration'),\n\tmergeBehavior: z\n\t\t.object({\n\t\t\tmode: z.enum(mergeModeValues).transform(mergeModeTransform).optional(),\n\t\t\tremote: z.string().optional(),\n\t\t\tautoCommitPush: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\t\t\t'Auto-commit and push after code review in draft PR mode. Defaults to true when mode is draft-pr.'\n\t\t\t\t),\n\t\t\tprTitlePrefix: z.boolean().optional(),\n\t\t\topenBrowserOnFinish: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\t\t\t'Open the PR in the default browser after finishing in pr or draft-pr mode. Use --no-browser flag to override.'\n\t\t\t\t),\n\t\t})\n\t\t.optional()\n\t\t.describe('Merge behavior configuration: local (merge locally), pr (create PR), or draft-pr (create draft PR at start, mark ready on finish)'),\n\tide: z\n\t\t.object({\n\t\t\ttype: z\n\t\t\t\t.enum(['vscode', 'cursor', 'webstorm', 'sublime', 'intellij', 'windsurf', 'antigravity'])\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\t\t\t'IDE to launch when starting a loom. Options: vscode (Visual Studio Code), cursor (Cursor AI editor), ' +\n\t\t\t\t\t\t'webstorm (JetBrains WebStorm), sublime (Sublime Text), intellij (JetBrains IntelliJ IDEA), ' +\n\t\t\t\t\t\t'windsurf (Windsurf editor), antigravity (Antigravity IDE).'\n\t\t\t\t),\n\t\t})\n\t\t.optional()\n\t\t.describe(\n\t\t\t'IDE configuration for workspace launches. Controls which editor opens when you start a loom. ' +\n\t\t\t\t'Supports VSCode, Cursor, WebStorm, Sublime Text, IntelliJ, Windsurf, and Antigravity. ' +\n\t\t\t\t'Note: Color synchronization (title bar colors) only works with VSCode-compatible editors (vscode, cursor, windsurf, antigravity).'\n\t\t),\n\tcolors: z\n\t\t.object({\n\t\t\tterminal: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe('Apply terminal background colors based on branch name (macOS only)'),\n\t\t\tvscode: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\t\t\t'Apply VSCode/Cursor title bar colors based on branch name. ' +\n\t\t\t\t\t\t'Note: This modifies .vscode/settings.json which may be in source control.'\n\t\t\t\t),\n\t\t})\n\t\t.optional()\n\t\t.describe('Color synchronization settings for workspace identification'),\n\tattribution: z\n\t\t.enum(['off', 'upstreamOnly', 'on'])\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Controls when iloom attribution appears in session summaries. ' +\n\t\t\t\t'\"off\" - never show attribution. ' +\n\t\t\t\t'\"upstreamOnly\" - only show for contributions to external repositories (e.g., open source). ' +\n\t\t\t\t'\"on\" - always show attribution.'\n\t\t),\n\tgit: z\n\t\t.object({\n\t\t\tcommitTimeout: z\n\t\t\t\t.number()\n\t\t\t\t.min(1000, 'Commit timeout must be at least 1000ms')\n\t\t\t\t.max(600000, 'Commit timeout cannot exceed 600000ms (10 minutes)')\n\t\t\t\t.optional()\n\t\t\t\t.describe('Timeout in milliseconds for git commit operations. Increase for long-running pre-commit hooks.'),\n\t\t})\n\t\t.optional()\n\t\t.describe('Git operation settings'),\n})\n\n/**\n * TypeScript type for dev server settings derived from Zod schema\n */\nexport type DevServerSettings = z.infer<typeof DevServerSettingsSchema>\n\n/**\n * TypeScript type for Neon settings derived from Zod schema\n */\nexport type NeonSettings = z.infer<typeof NeonSettingsSchema>\n\n/**\n * TypeScript type for Supabase settings derived from Zod schema\n */\nexport type SupabaseSettings = z.infer<typeof SupabaseSettingsSchema>\n\n/**\n * TypeScript type for database providers settings derived from Zod schema\n */\nexport type DatabaseProvidersSettings = z.infer<typeof DatabaseProvidersSettingsSchema>\n\n/**\n * TypeScript type for agent settings derived from Zod schema\n */\nexport type AgentSettings = z.infer<typeof AgentSettingsSchema>\n\n/**\n * TypeScript type for spin agent settings derived from Zod schema\n */\nexport type SpinAgentSettings = z.infer<typeof SpinAgentSettingsSchema>\n\n/**\n * TypeScript type for plan command settings derived from Zod schema\n */\nexport type PlanCommandSettings = z.infer<typeof PlanCommandSettingsSchema>\n\n/**\n * TypeScript type for summary settings derived from Zod schema\n */\nexport type SummarySettings = z.infer<typeof SummarySettingsSchema>\n\n/**\n * TypeScript type for workflow permission configuration derived from Zod schema\n */\nexport type WorkflowPermission = z.infer<typeof WorkflowPermissionSchema>\n\n/**\n * TypeScript type for workflows settings derived from Zod schema\n */\nexport type WorkflowsSettings = z.infer<typeof WorkflowsSettingsSchema>\n\n/**\n * TypeScript type for capabilities settings derived from Zod schema\n */\nexport type CapabilitiesSettings = z.infer<typeof CapabilitiesSettingsSchema>\n\n/**\n * TypeScript type for IDE settings derived from Zod schema\n */\nexport type IdeSettings = z.infer<typeof IloomSettingsSchema>['ide']\n\n/**\n * TypeScript type for iloom settings derived from Zod schema\n */\nexport type IloomSettings = z.infer<typeof IloomSettingsSchema>\n\n/**\n * TypeScript input type for iloom settings (before Zod defaults are applied)\n * Used for validation where partial/input objects need to be accepted\n */\nexport type IloomSettingsInput = z.input<typeof IloomSettingsSchema>\n\n/**\n * Recursively redact sensitive fields (tokens, secrets, passwords) from an object.\n * Returns a deep copy with sensitive string values replaced by '[REDACTED]'.\n */\nexport function redactSensitiveFields(obj: unknown): unknown {\n\tif (obj === null || obj === undefined) return obj\n\tif (typeof obj !== 'object') return obj\n\tif (Array.isArray(obj)) return obj.map(redactSensitiveFields)\n\n\tconst sensitiveKeys = ['apitoken', 'token', 'secret', 'password', 'credential']\n\tconst result: Record<string, unknown> = {}\n\tfor (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n\t\tconst lowerKey = key.toLowerCase()\n\t\tif (sensitiveKeys.some(s => lowerKey.includes(s)) && typeof value === 'string') {\n\t\t\tresult[key] = '[REDACTED]'\n\t\t} else if (typeof value === 'object' && value !== null) {\n\t\t\tresult[key] = redactSensitiveFields(value)\n\t\t} else {\n\t\t\tresult[key] = value\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Manages project-level settings from .iloom/settings.json\n */\nexport class SettingsManager {\n\t/**\n\t * Load settings from global, project, and local sources with proper precedence\n\t * Merge hierarchy (lowest to highest priority):\n\t * 1. Global settings (~/.config/iloom-ai/settings.json)\n\t * 2. Project settings (<PROJECT_ROOT>/.iloom/settings.json)\n\t * 3. Local settings (<PROJECT_ROOT>/.iloom/settings.local.json)\n\t * 4. CLI overrides (--set flags)\n\t * Returns empty object if all files don't exist (not an error)\n\t */\n\tasync loadSettings(\n\t\tprojectRoot?: string,\n\t\tcliOverrides?: Partial<IloomSettings>,\n\t): Promise<IloomSettings> {\n\t\tconst root = this.getProjectRoot(projectRoot)\n\n\t\t// Load global settings (lowest priority)\n\t\tconst globalSettings = await this.loadGlobalSettingsFile()\n\t\tconst globalSettingsPath = this.getGlobalSettingsPath()\n\t\tlogger.debug(`🌍 Global settings from ${globalSettingsPath}:`, JSON.stringify(redactSensitiveFields(globalSettings), null, 2))\n\n\t\t// Load base settings from settings.json\n\t\tconst baseSettings = await this.loadSettingsFile(root, 'settings.json')\n\t\tconst baseSettingsPath = path.join(root, '.iloom', 'settings.json')\n\t\tlogger.debug(`📄 Base settings from ${baseSettingsPath}:`, JSON.stringify(redactSensitiveFields(baseSettings), null, 2))\n\n\t\t// Load local overrides from settings.local.json\n\t\tconst localSettings = await this.loadSettingsFile(root, 'settings.local.json')\n\t\tconst localSettingsPath = path.join(root, '.iloom', 'settings.local.json')\n\t\tlogger.debug(`📄 Local settings from ${localSettingsPath}:`, JSON.stringify(redactSensitiveFields(localSettings), null, 2))\n\n\t\t// Deep merge with priority: cliOverrides > localSettings > baseSettings > globalSettings\n\t\tlet merged = this.mergeSettings(this.mergeSettings(globalSettings, baseSettings), localSettings)\n\t\tlogger.debug('🔄 After merging global + base + local settings:', JSON.stringify(redactSensitiveFields(merged), null, 2))\n\n\t\tif (cliOverrides && Object.keys(cliOverrides).length > 0) {\n\t\t\tlogger.debug('⚙️ CLI overrides to apply:', JSON.stringify(redactSensitiveFields(cliOverrides), null, 2))\n\t\t\tmerged = this.mergeSettings(merged, cliOverrides)\n\t\t\tlogger.debug('🔄 After applying CLI overrides:', JSON.stringify(redactSensitiveFields(merged), null, 2))\n\t\t}\n\n\t\t// Validate merged result\n\t\ttry {\n\t\t\tconst finalSettings = IloomSettingsSchema.parse(merged)\n\n\t\t\t// Debug: Log final merged configuration\n\t\t\tthis.logFinalConfiguration(finalSettings)\n\n\t\t\treturn finalSettings\n\t\t} catch (error) {\n\t\t\t// Show all Zod validation errors\n\t\t\tif (error instanceof z.ZodError) {\n\t\t\t\tconst errorMsg = this.formatAllZodErrors(error, '<merged settings>')\n\t\t\t\t// Enhance error message if CLI overrides were applied\n\t\t\t\tif (cliOverrides && Object.keys(cliOverrides).length > 0) {\n\t\t\t\t\tthrow new Error(`${errorMsg.message}\\n\\nNote: CLI overrides were applied. Check your --set arguments.`)\n\t\t\t\t}\n\t\t\t\tthrow errorMsg\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/**\n\t * Log the final merged configuration for debugging\n\t */\n\tprivate logFinalConfiguration(settings: IloomSettings): void {\n\t\tlogger.debug('📋 Final merged configuration:', JSON.stringify(redactSensitiveFields(settings), null, 2))\n\t}\n\n\t/**\n\t * Load and parse a single settings file\n\t * Returns empty object if file doesn't exist (not an error)\n\t * Uses non-defaulting schema to prevent polluting partial settings with defaults before merge\n\t */\n\tprivate async loadSettingsFile(\n\t\tprojectRoot: string,\n\t\tfilename: string,\n\t): Promise<z.infer<typeof IloomSettingsSchemaNoDefaults>> {\n\t\tconst settingsPath = path.join(projectRoot, '.iloom', filename)\n\n\t\ttry {\n\t\t\tconst content = await readFile(settingsPath, 'utf-8')\n\t\t\tlet parsed: unknown\n\n\t\t\ttry {\n\t\t\t\tparsed = JSON.parse(content)\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Failed to parse settings file at ${settingsPath}: ${error instanceof Error ? error.message : 'Invalid JSON'}`,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// Basic type checking - ensure it's an object, but don't validate schema completeness\n\t\t\t// Individual files may be incomplete (e.g., Linear config split between files)\n\t\t\t// Final validation will happen on the merged result in loadSettings()\n\t\t\tif (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Settings validation failed at ${filename}:\\n - root: Expected object, received ${typeof parsed}`\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn parsed as z.infer<typeof IloomSettingsSchemaNoDefaults>\n\t\t} catch (error) {\n\t\t\t// File not found is not an error - return empty settings\n\t\t\tif ((error as { code?: string }).code === 'ENOENT') {\n\t\t\t\tlogger.debug(`No settings file found at ${settingsPath}, using defaults`)\n\t\t\t\treturn {}\n\t\t\t}\n\n\t\t\t// Re-throw parsing errors\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/**\n\t * Deep merge two settings objects with priority to override\n\t * Uses deepmerge library with array replacement strategy\n\t */\n\tprivate mergeSettings(\n\t\tbase: Partial<IloomSettings> | z.infer<typeof IloomSettingsSchemaNoDefaults>,\n\t\toverride: Partial<IloomSettings> | z.infer<typeof IloomSettingsSchemaNoDefaults>,\n\t): IloomSettings {\n\t\t// Use deepmerge with array replacement (not concatenation)\n\t\t// Type assertion is safe because the merged result will be validated with IloomSettingsSchema\n\t\t// which applies all the defaults after merging\n\t\treturn deepmerge(base as Record<string, unknown>, override as Record<string, unknown>, {\n\t\t\t// Replace arrays instead of concatenating them\n\t\t\tarrayMerge: (_destinationArray, sourceArray) => sourceArray,\n\t\t}) as IloomSettings\n\t}\n\n\t/**\n\t * Format all Zod validation errors into a single error message\n\t */\n\tprivate formatAllZodErrors(error: z.ZodError, settingsPath: string): Error {\n\t\tconst errorMessages = error.issues.map(issue => {\n\t\t\tconst path = issue.path.length > 0 ? issue.path.join('.') : 'root'\n\t\t\treturn ` - ${path}: ${issue.message}`\n\t\t})\n\n\t\treturn new Error(\n\t\t\t`Settings validation failed at ${settingsPath}:\\n${errorMessages.join('\\n')}`,\n\t\t)\n\t}\n\n\t/**\n\t * Validate settings structure and model names using Zod schema\n\t * This method is kept for testing purposes but uses Zod internally\n\t * @internal - Only used in tests via bracket notation\n\t */\n\t// @ts-expect-error - Used in tests via bracket notation, TypeScript can't detect this usage\n\tprivate validateSettings(settings: IloomSettingsInput): void {\n\t\ttry {\n\t\t\tIloomSettingsSchema.parse(settings)\n\t\t} catch (error) {\n\t\t\tif (error instanceof z.ZodError) {\n\t\t\t\tthrow this.formatAllZodErrors(error, '<validation>')\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/**\n\t * Get project root (defaults to process.cwd())\n\t */\n\tprivate getProjectRoot(projectRoot?: string): string {\n\t\treturn projectRoot ?? process.cwd()\n\t}\n\n\t/**\n\t * Get global config directory path (~/.config/iloom-ai)\n\t */\n\tprivate getGlobalConfigDir(): string {\n\t\treturn path.join(os.homedir(), '.config', 'iloom-ai')\n\t}\n\n\t/**\n\t * Get global settings file path (~/.config/iloom-ai/settings.json)\n\t */\n\tprivate getGlobalSettingsPath(): string {\n\t\treturn path.join(this.getGlobalConfigDir(), 'settings.json')\n\t}\n\n\t/**\n\t * Load and parse global settings file\n\t * Returns empty object if file doesn't exist (not an error)\n\t * Warns but returns empty object on validation/parse errors (graceful degradation)\n\t */\n\tprivate async loadGlobalSettingsFile(): Promise<z.infer<typeof IloomSettingsSchemaNoDefaults>> {\n\t\tconst settingsPath = this.getGlobalSettingsPath()\n\n\t\ttry {\n\t\t\tconst content = await readFile(settingsPath, 'utf-8')\n\t\t\tlet parsed: unknown\n\n\t\t\ttry {\n\t\t\t\tparsed = JSON.parse(content)\n\t\t\t} catch (error) {\n\t\t\t\tlogger.warn(\n\t\t\t\t\t`Failed to parse global settings file at ${settingsPath}: ${error instanceof Error ? error.message : 'Invalid JSON'}. Ignoring global settings.`,\n\t\t\t\t)\n\t\t\t\treturn {}\n\t\t\t}\n\n\t\t\t// Validate with non-defaulting schema\n\t\t\ttry {\n\t\t\t\tconst validated = IloomSettingsSchemaNoDefaults.strict().parse(parsed)\n\t\t\t\treturn validated\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof z.ZodError) {\n\t\t\t\t\tconst errorMsg = this.formatAllZodErrors(error, 'global settings')\n\t\t\t\t\tlogger.warn(`${errorMsg.message}. Ignoring global settings.`)\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn(`Validation error in global settings: ${error instanceof Error ? error.message : 'Unknown error'}. Ignoring global settings.`)\n\t\t\t\t}\n\t\t\t\treturn {}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// File not found is not an error - return empty settings\n\t\t\tif ((error as { code?: string }).code === 'ENOENT') {\n\t\t\t\tlogger.debug(`No global settings file found at ${settingsPath}`)\n\t\t\t\treturn {}\n\t\t\t}\n\n\t\t\t// Other file system errors - warn and continue\n\t\t\tlogger.warn(`Error reading global settings file at ${settingsPath}: ${error instanceof Error ? error.message : 'Unknown error'}. Ignoring global settings.`)\n\t\t\treturn {}\n\t\t}\n\t}\n\n\t/**\n\t * Get effective protected branches list with mainBranch always included\n\t *\n\t * This method provides a single source of truth for protected branches logic:\n\t * 1. Use configured protectedBranches if provided\n\t * 2. Otherwise use defaults: [mainBranch, 'main', 'master', 'develop']\n\t * 3. ALWAYS ensure mainBranch is included even if user configured custom list\n\t *\n\t * @param projectRoot - Optional project root directory (defaults to process.cwd())\n\t * @returns Array of protected branch names with mainBranch guaranteed to be included\n\t */\n\tasync getProtectedBranches(projectRoot?: string): Promise<string[]> {\n\t\tconst settings = await this.loadSettings(projectRoot)\n\t\t// SYNC: If this default changes, update displayDefaultsBox() in src/utils/first-run-setup.ts\n\t\tconst mainBranch = settings.mainBranch ?? 'main'\n\n\t\t// Build protected branches list:\n\t\t// 1. Use configured protectedBranches if provided\n\t\t// 2. Otherwise use defaults: [mainBranch, 'main', 'master', 'develop']\n\t\t// 3. ALWAYS ensure mainBranch is included even if user configured custom list\n\t\tlet protectedBranches: string[]\n\t\tif (settings.protectedBranches) {\n\t\t\t// Use configured list but ensure mainBranch is always included\n\t\t\tprotectedBranches = settings.protectedBranches.includes(mainBranch)\n\t\t\t\t? settings.protectedBranches\n\t\t\t\t: [mainBranch, ...settings.protectedBranches]\n\t\t} else {\n\t\t\t// Use defaults with current mainBranch\n\t\t\tprotectedBranches = [mainBranch, 'main', 'master', 'develop']\n\t\t}\n\n\t\treturn protectedBranches\n\t}\n\n\t/**\n\t * Get the spin orchestrator model with default applied\n\t * Default is defined in SpinAgentSettingsSchema\n\t *\n\t * @param settings - Pre-loaded settings object\n\t * @returns Model shorthand ('opus', 'sonnet', or 'haiku')\n\t */\n\tgetSpinModel(settings?: IloomSettings, mode?: 'swarm'): 'sonnet' | 'opus' | 'haiku' {\n\t\tif (mode === 'swarm') {\n\t\t\tif (settings?.spin?.swarmModel) {\n\t\t\t\treturn settings.spin.swarmModel\n\t\t\t}\n\t\t\t// Default to opus for swarm orchestrator (\"Balanced\" mode)\n\t\t\treturn 'opus'\n\t\t}\n\t\treturn settings?.spin?.model ?? SpinAgentSettingsSchema.parse({}).model\n\t}\n\n\t/**\n\t * Get the plan command model with default applied\n\t * Default is defined in PlanCommandSettingsSchema\n\t *\n\t * @param settings - Pre-loaded settings object\n\t * @returns Model shorthand ('opus', 'sonnet', or 'haiku')\n\t */\n\tgetPlanModel(settings?: IloomSettings): 'sonnet' | 'opus' | 'haiku' {\n\t\treturn settings?.plan?.model ?? PlanCommandSettingsSchema.parse({}).model\n\t}\n\n\t/**\n\t * Get the plan command planner with default applied\n\t * Default is 'claude'\n\t *\n\t * @param settings - Pre-loaded settings object\n\t * @returns Planner provider ('claude', 'gemini', or 'codex')\n\t */\n\tgetPlanPlanner(settings?: IloomSettings): 'claude' | 'gemini' | 'codex' {\n\t\treturn settings?.plan?.planner ?? 'claude'\n\t}\n\n\t/**\n\t * Get the plan command reviewer with default applied\n\t * Default is 'none' (no review step)\n\t *\n\t * @param settings - Pre-loaded settings object\n\t * @returns Reviewer provider ('claude', 'gemini', 'codex', or 'none')\n\t */\n\tgetPlanReviewer(settings?: IloomSettings): 'claude' | 'gemini' | 'codex' | 'none' {\n\t\treturn settings?.plan?.reviewer ?? 'none'\n\t}\n\n\t/**\n\t * Get the plan command waveVerification setting with default applied\n\t * Default is true (verification tasks are generated)\n\t *\n\t * @param settings - Pre-loaded settings object\n\t * @returns Whether wave verification is enabled\n\t */\n\tgetPlanWaveVerification(settings?: IloomSettings): boolean {\n\t\treturn settings?.plan?.waveVerification !== false\n\t}\n\n\t/**\n\t * Get the session summary model with default applied\n\t * Default is defined in SummarySettingsSchema\n\t *\n\t * @param settings - Pre-loaded settings object\n\t * @returns Model shorthand ('opus', 'sonnet', or 'haiku')\n\t */\n\tgetSummaryModel(settings?: IloomSettings): 'sonnet' | 'opus' | 'haiku' {\n\t\treturn settings?.summary?.model ?? SummarySettingsSchema.parse({}).model\n\t}\n}\n"],"mappings":";;;;;;AAAA,SAAS,gBAAgB;AACzB,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAS,SAAS;AAClB,OAAO,eAAe;AAIf,IAAM,kBAAkB,CAAC,SAAS,MAAM,YAAY,aAAa,mBAAmB,cAAc;AAEzG,IAAM,qBAAqB,CAAC,QAA2B;AACtD,QAAM,MAAiC,EAAE,aAAa,MAAM,mBAAmB,YAAY,gBAAgB,KAAK;AAChH,SAAQ,IAAI,GAAG,KAAK;AACrB;AAKO,IAAM,0BAA0B,EAAE,OAAO;AAAA,EAC/C,OAAO,EACL,KAAK,CAAC,UAAU,QAAQ,OAAO,CAAC,EAChC,SAAS,EACT,SAAS,gDAAgD;AAAA,EAC3D,YAAY,EACV,KAAK,CAAC,UAAU,QAAQ,OAAO,CAAC,EAChC,SAAS,EACT,SAAS,wGAAwG;AAAA,EACnH,SAAS,EACP,QAAQ,EACR,SAAS,EACT,SAAS,kDAAkD;AAAA,EAC7D,WAAW,EACT;AAAA,IACA,EAAE,KAAK,CAAC,UAAU,UAAU,OAAO,CAAC;AAAA,IACpC,EAAE,OAAO;AAAA,EACV,EACC,SAAS,EACT,SAAS,2JAA2J;AAAA,EACtK,QAAQ,EACN,QAAQ,EACR,SAAS,EACT,SAAS,yFAAyF;AAAA,EACpG,aAAa,EACX,QAAQ,EACR,SAAS,EACT,SAAS,8KAA8K;AAC1L,CAAC;AAKM,IAAM,sBAAsB;AAM5B,IAAM,0BAA0B,EAAE,OAAO;AAAA,EAC/C,OAAO,EACL,KAAK,CAAC,UAAU,QAAQ,OAAO,CAAC,EAChC,QAAQ,MAAM,EACd,SAAS,8CAA8C;AAAA,EACzD,YAAY,EACV,KAAK,CAAC,UAAU,QAAQ,OAAO,CAAC,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