@iloom/cli 0.3.1 → 0.3.2

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 (101) hide show
  1. package/README.md +5 -3
  2. package/dist/{BranchNamingService-OMWKUYMM.js → BranchNamingService-JYO746H7.js} +2 -2
  3. package/dist/ClaudeContextManager-5WPRJIIW.js +15 -0
  4. package/dist/ClaudeService-Z4KA7QOW.js +14 -0
  5. package/dist/{GitHubService-EBOETDIW.js → GitHubService-UAMH7DMF.js} +2 -2
  6. package/dist/{LoomLauncher-JF7JZMTZ.js → LoomLauncher-FVZECY3C.js} +24 -13
  7. package/dist/LoomLauncher-FVZECY3C.js.map +1 -0
  8. package/dist/README.md +5 -3
  9. package/dist/{SettingsManager-ZCWJ56WP.js → SettingsManager-MTVX57WR.js} +2 -2
  10. package/dist/{chunk-4BGK7T6X.js → chunk-5NTD4MCZ.js} +23 -7
  11. package/dist/chunk-5NTD4MCZ.js.map +1 -0
  12. package/dist/{chunk-U5QDY7ZD.js → chunk-A2P7NZTB.js} +7 -7
  13. package/dist/{chunk-XPKDPZ5D.js → chunk-C7ASXK6J.js} +2 -2
  14. package/dist/{chunk-G2IEYOLQ.js → chunk-F4ENT6AC.js} +16 -1
  15. package/dist/chunk-F4ENT6AC.js.map +1 -0
  16. package/dist/{chunk-IXKLYTWO.js → chunk-FOV7RRQ2.js} +8 -8
  17. package/dist/{chunk-RO26VS3W.js → chunk-FXMLNKLT.js} +2 -2
  18. package/dist/{chunk-ZBQVSHVT.js → chunk-GOG3ZB7O.js} +14 -8
  19. package/dist/chunk-GOG3ZB7O.js.map +1 -0
  20. package/dist/{chunk-JQFO7QQN.js → chunk-GVICXJHW.js} +2 -2
  21. package/dist/{chunk-JQFO7QQN.js.map → chunk-GVICXJHW.js.map} +1 -1
  22. package/dist/{chunk-HBYZH6GD.js → chunk-KG343GSG.js} +90 -47
  23. package/dist/chunk-KG343GSG.js.map +1 -0
  24. package/dist/{chunk-TSKY3JI7.js → chunk-OAP6SASD.js} +2 -2
  25. package/dist/chunk-OXAM2WVC.js +68 -0
  26. package/dist/chunk-OXAM2WVC.js.map +1 -0
  27. package/dist/{chunk-4E4LD3QR.js → chunk-PRE7KTM4.js} +2 -2
  28. package/dist/{chunk-ZE74H5BR.js → chunk-RW54ZMBM.js} +26 -20
  29. package/dist/chunk-RW54ZMBM.js.map +1 -0
  30. package/dist/{chunk-O5OH5MRX.js → chunk-UCZ24SUE.js} +3 -3
  31. package/dist/chunk-UCZ24SUE.js.map +1 -0
  32. package/dist/{chunk-INW24J2W.js → chunk-UERERX6M.js} +2 -2
  33. package/dist/{chunk-IP7SMKIF.js → chunk-UJL4HI2R.js} +59 -60
  34. package/dist/chunk-UJL4HI2R.js.map +1 -0
  35. package/dist/{chunk-ZWFBBPJI.js → chunk-ZLIHIUDQ.js} +4 -2
  36. package/dist/chunk-ZLIHIUDQ.js.map +1 -0
  37. package/dist/{claude-LUZ35IMK.js → claude-KIZYXTSG.js} +4 -2
  38. package/dist/{cleanup-3MONU4PU.js → cleanup-6WYUD5SN.js} +17 -15
  39. package/dist/{cleanup-3MONU4PU.js.map → cleanup-6WYUD5SN.js.map} +1 -1
  40. package/dist/cli.js +207 -71
  41. package/dist/cli.js.map +1 -1
  42. package/dist/{contribute-UWJAGIG7.js → contribute-7YJHZTO7.js} +3 -2
  43. package/dist/{contribute-UWJAGIG7.js.map → contribute-7YJHZTO7.js.map} +1 -1
  44. package/dist/{feedback-W3BXTGIM.js → feedback-752MGDPG.js} +10 -8
  45. package/dist/{feedback-W3BXTGIM.js.map → feedback-752MGDPG.js.map} +1 -1
  46. package/dist/{git-34Z6QVDS.js → git-TAFVDB3J.js} +5 -2
  47. package/dist/{ignite-KVJEFXNO.js → ignite-OAMDUN27.js} +13 -11
  48. package/dist/{ignite-KVJEFXNO.js.map → ignite-OAMDUN27.js.map} +1 -1
  49. package/dist/index.d.ts +20 -7
  50. package/dist/index.js +276 -294
  51. package/dist/index.js.map +1 -1
  52. package/dist/{init-L55Q73H4.js → init-7IIM35LQ.js} +12 -9
  53. package/dist/{init-L55Q73H4.js.map → init-7IIM35LQ.js.map} +1 -1
  54. package/dist/mcp/issue-management-server.js +8 -1
  55. package/dist/mcp/issue-management-server.js.map +1 -1
  56. package/dist/{neon-helpers-WPUACUVC.js → neon-helpers-5HBYO2VP.js} +2 -2
  57. package/dist/{open-LNRZL3UU.js → open-FCHKQ77R.js} +27 -14
  58. package/dist/open-FCHKQ77R.js.map +1 -0
  59. package/dist/prompts/init-prompt.txt +7 -1
  60. package/dist/{rebase-C4WNCVGM.js → rebase-Q7WXK566.js} +10 -8
  61. package/dist/{rebase-C4WNCVGM.js.map → rebase-Q7WXK566.js.map} +1 -1
  62. package/dist/{run-IOGNIOYN.js → run-SJPM6YRI.js} +27 -14
  63. package/dist/run-SJPM6YRI.js.map +1 -0
  64. package/dist/schema/settings.schema.json +1 -1
  65. package/dist/{test-git-J7I5MFYH.js → test-git-DEUE656D.js} +5 -5
  66. package/dist/{test-prefix-ZCONBCBX.js → test-prefix-Y6Z6ZHSF.js} +5 -5
  67. package/dist/{test-tabs-RXDBZ6J7.js → test-tabs-PRMRSHKI.js} +3 -2
  68. package/dist/{test-tabs-RXDBZ6J7.js.map → test-tabs-PRMRSHKI.js.map} +1 -1
  69. package/package.json +1 -1
  70. package/dist/ClaudeContextManager-3VXA6UPR.js +0 -13
  71. package/dist/ClaudeService-6CPK43N4.js +0 -12
  72. package/dist/LoomLauncher-JF7JZMTZ.js.map +0 -1
  73. package/dist/chunk-4BGK7T6X.js.map +0 -1
  74. package/dist/chunk-G2IEYOLQ.js.map +0 -1
  75. package/dist/chunk-HBYZH6GD.js.map +0 -1
  76. package/dist/chunk-IP7SMKIF.js.map +0 -1
  77. package/dist/chunk-O5OH5MRX.js.map +0 -1
  78. package/dist/chunk-ZBQVSHVT.js.map +0 -1
  79. package/dist/chunk-ZE74H5BR.js.map +0 -1
  80. package/dist/chunk-ZWFBBPJI.js.map +0 -1
  81. package/dist/open-LNRZL3UU.js.map +0 -1
  82. package/dist/run-IOGNIOYN.js.map +0 -1
  83. package/dist/terminal-BIRBZ4AZ.js +0 -16
  84. package/dist/terminal-BIRBZ4AZ.js.map +0 -1
  85. /package/dist/{BranchNamingService-OMWKUYMM.js.map → BranchNamingService-JYO746H7.js.map} +0 -0
  86. /package/dist/{ClaudeContextManager-3VXA6UPR.js.map → ClaudeContextManager-5WPRJIIW.js.map} +0 -0
  87. /package/dist/{ClaudeService-6CPK43N4.js.map → ClaudeService-Z4KA7QOW.js.map} +0 -0
  88. /package/dist/{GitHubService-EBOETDIW.js.map → GitHubService-UAMH7DMF.js.map} +0 -0
  89. /package/dist/{SettingsManager-ZCWJ56WP.js.map → SettingsManager-MTVX57WR.js.map} +0 -0
  90. /package/dist/{chunk-U5QDY7ZD.js.map → chunk-A2P7NZTB.js.map} +0 -0
  91. /package/dist/{chunk-XPKDPZ5D.js.map → chunk-C7ASXK6J.js.map} +0 -0
  92. /package/dist/{chunk-IXKLYTWO.js.map → chunk-FOV7RRQ2.js.map} +0 -0
  93. /package/dist/{chunk-RO26VS3W.js.map → chunk-FXMLNKLT.js.map} +0 -0
  94. /package/dist/{chunk-TSKY3JI7.js.map → chunk-OAP6SASD.js.map} +0 -0
  95. /package/dist/{chunk-4E4LD3QR.js.map → chunk-PRE7KTM4.js.map} +0 -0
  96. /package/dist/{chunk-INW24J2W.js.map → chunk-UERERX6M.js.map} +0 -0
  97. /package/dist/{claude-LUZ35IMK.js.map → claude-KIZYXTSG.js.map} +0 -0
  98. /package/dist/{git-34Z6QVDS.js.map → git-TAFVDB3J.js.map} +0 -0
  99. /package/dist/{neon-helpers-WPUACUVC.js.map → neon-helpers-5HBYO2VP.js.map} +0 -0
  100. /package/dist/{test-git-J7I5MFYH.js.map → test-git-DEUE656D.js.map} +0 -0
  101. /package/dist/{test-prefix-ZCONBCBX.js.map → test-prefix-Y6Z6ZHSF.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/LoomManager.ts","../src/lib/VSCodeIntegration.ts","../src/lib/EnvironmentManager.ts","../src/lib/CLIIsolationManager.ts","../src/lib/DatabaseManager.ts","../src/lib/ResourceCleanup.ts"],"sourcesContent":["import path from 'path'\nimport fs from 'fs-extra'\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 { branchExists, executeGitCommand, ensureRepositoryHasCommits, extractIssueNumber, isFileTrackedByGit } from '../utils/git.js'\nimport { installDependencies } from '../utils/package-manager.js'\nimport { generateColorFromBranchName } from '../utils/color.js'\nimport { DatabaseManager } from './DatabaseManager.js'\nimport { loadEnvIntoProcess, findEnvFileForDatabaseUrl } 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 { logger } from '../utils/logger.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 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 ) {}\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 logger.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 logger.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 === 'pr' || input.type === 'branch') {\n logger.info('Checking for existing worktree...')\n const existing = await this.findExistingIloom(input, issueData)\n if (existing) {\n logger.success(`Found existing worktree, reusing: ${existing.path}`)\n return await this.reuseIloom(existing, input, issueData)\n }\n logger.info('No existing worktree found, creating new one...')\n }\n\n // 2. Generate or validate branch name\n logger.info('Preparing branch name...')\n const branchName = await this.prepareBranchName(input, issueData)\n\n // 3. Create git worktree (WITHOUT dependency installation)\n logger.info('Creating git worktree...')\n const worktreePath = await this.createWorktreeOnly(input, branchName)\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 // Pass parent branch name if this is a child loom\n await this.copyIloomSettings(worktreePath, input.parentLoom?.branchName)\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 logger.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 logger.success('Database branch configured')\n databaseBranch = branchName\n }\n } catch (error) {\n logger.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 let cliSymlinks: string[] | undefined = undefined\n if (capabilities.includes('cli')) {\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 logger.warn(\n `Failed to setup CLI isolation: ${error instanceof Error ? error.message : 'Unknown error'}`,\n error\n )\n }\n }\n\n // 11. Apply color synchronization (terminal and VSCode)\n if (!input.options?.skipColorSync) {\n try {\n await this.applyColorSynchronization(worktreePath, branchName)\n } catch (error) {\n // Log warning but don't fail - colors are cosmetic\n logger.warn(\n `Failed to apply color synchronization: ${error instanceof Error ? error.message : 'Unknown error'}`,\n error\n )\n }\n }\n\n // NEW: Move issue to In Progress (for new worktrees)\n if (input.type === 'issue') {\n try {\n logger.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 logger.warn(\n `Failed to move issue to In Progress: ${error instanceof Error ? error.message : 'Unknown error'}`,\n error\n )\n }\n }\n\n // 8. 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 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,\n identifier: input.identifier,\n ...(issueData?.title && { title: issueData.title }),\n oneShot,\n ...(setArguments && { setArguments }),\n ...(executablePath && { executablePath }),\n sourceEnvOnStart: settingsData.sourceEnvOnStart ?? false,\n })\n }\n\n // 9. 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 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 logger.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 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 // Sanitize parent branch name the same way as in createWorktreeOnly (lines 361-363)\n const sanitizedBranchName = parentBranchName\n .replace(/\\//g, '-')\n .replace(/[^a-zA-Z0-9-_]/g, '-')\n\n // Child looms are in directory: {sanitizedBranchName}-looms/\n const pattern = `${sanitizedBranchName}-looms/`\n\n return worktrees.filter(wt => wt.path.includes(pattern))\n } catch (error) {\n logger.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 logger.warn(`Found ${childLooms.length} child loom(s) that should be finished first:`)\n for (const child of childLooms) {\n logger.warn(` - ${child.path}`)\n }\n logger.warn('')\n logger.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 logger.warn(` il finish ${childIdentifier}`)\n }\n logger.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') {\n return await this.issueTracker.fetchIssue(input.identifier as number)\n } else if (input.type === 'pr') {\n // Check if provider supports PRs before calling\n if (!this.issueTracker.supportsPullRequests || !this.issueTracker.fetchPR) {\n throw new Error('Issue tracker does not support pull requests')\n }\n return await this.issueTracker.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' && 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 ): 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 logger.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 logger.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 // 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 logger.info('Fetching all remote branches...')\n try {\n await executeGitCommand(['fetch', 'origin'], { cwd: this.gitWorktree.workingDirectory })\n logger.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 // Check if branch exists locally (used for different purposes depending on type)\n const branchExistedLocally = await branchExists(branchName)\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: use parent's branch for child looms, otherwise use explicit baseBranch or default (main)\n const baseBranch = input.parentLoom?.branchName ?? input.baseBranch\n\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 logger.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 logger.success('Successfully reset to match remote')\n } catch (error) {\n logger.warn(`Failed to reset to match remote: ${error instanceof Error ? error.message : 'Unknown error'}`)\n }\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 logger.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 logger.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 logger.debug(`Copied ${pattern} to worktree`)\n } catch (error) {\n // Handle gracefully if individual file fails to copy\n logger.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 * @param parentBranchName Optional parent branch name for child looms (sets mainBranch)\n */\n private async copyIloomSettings(worktreePath: string, parentBranchName?: 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 logger.warn('settings.local.json already exists in worktree, skipping copy')\n } else {\n await this.environment.copyIfExists(mainSettingsLocalPath, worktreeSettingsLocalPath)\n }\n\n // If this is a child loom, update mainBranch setting\n if (parentBranchName) {\n let existingSettings = {}\n\n try {\n const content = await fs.readFile(worktreeSettingsLocalPath, 'utf8')\n existingSettings = JSON.parse(content)\n } catch {\n // File doesn't exist or invalid, start fresh\n }\n\n const updatedSettings = {\n ...existingSettings,\n mainBranch: parentBranchName,\n }\n\n await fs.writeFile(worktreeSettingsLocalPath, JSON.stringify(updatedSettings, null, 2))\n logger.info(`Set mainBranch to ${parentBranchName} for child loom`)\n }\n } catch (error) {\n logger.warn(`Warning: Failed to copy settings.local.json: ${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') {\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 // Handle gracefully if .env files don't exist\n logger.warn(`Warning: Could not load .env files: ${result.error.message}`)\n } else {\n logger.info('Loaded environment variables using dotenv-flow')\n if (result.parsed && Object.keys(result.parsed).length > 0) {\n logger.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' && typeof input.identifier === 'number') {\n return this.environment.calculatePort({ basePort, issueNumber: input.identifier })\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}`)\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 */\n private async applyColorSynchronization(\n worktreePath: string,\n branchName: string\n ): Promise<void> {\n const colorData = generateColorFromBranchName(branchName)\n\n // Apply VSCode title bar color\n const vscode = new VSCodeIntegration()\n await vscode.setTitleBarColor(worktreePath, colorData.hex)\n\n logger.info(`Applied VSCode title bar color: ${colorData.hex} for branch: ${branchName}`)\n\n // Note: Terminal color is applied during window creation in ClaudeContextManager\n // This ensures the color is set when the new terminal window is opened\n }\n\n /**\n * Map worktrees to loom objects\n * This is a simplified conversion - in production we'd store loom metadata\n */\n private async mapWorktreesToLooms(worktrees: GitWorktree[]): Promise<Loom[]> {\n return await Promise.all(worktrees.map(async (wt) => {\n // Extract identifier from branch name\n let type: 'issue' | 'pr' | 'branch' = 'branch'\n let identifier: string | number = wt.branch\n\n if (wt.branch.startsWith('issue-')) {\n type = 'issue'\n identifier = parseInt(wt.branch.replace('issue-', ''), 10)\n } else if (wt.branch.startsWith('pr-')) {\n type = 'pr'\n identifier = parseInt(wt.branch.replace('pr-', ''), 10)\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 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\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 logger.info('Database branch assumed to be already configured for existing worktree')\n const databaseBranch: string | undefined = undefined\n\n // 6. Move issue to In Progress (for reused worktrees too)\n if (input.type === 'issue') {\n try {\n logger.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 logger.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 setArguments = input.options?.setArguments\n const executablePath = input.options?.executablePath\n\n if (enableClaude || enableCode || enableDevServer || enableTerminal) {\n logger.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,\n identifier: input.identifier,\n ...(issueData?.title && { title: issueData.title }),\n oneShot,\n ...(setArguments && { setArguments }),\n ...(executablePath && { executablePath }),\n sourceEnvOnStart: settingsData.sourceEnvOnStart ?? false,\n })\n }\n\n // 8. 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 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 logger.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 { createLogger } from '../utils/logger.js'\nimport type {\n PortAssignmentOptions,\n} from '../types/environment.js'\nimport {\n parseEnvFile,\n formatEnvLine,\n validateEnvVariable,\n} from '../utils/env.js'\nimport { calculatePortForBranch } from '../utils/port.js'\n\nconst logger = createLogger({ prefix: '📝' })\n\nexport class EnvironmentManager {\n private readonly backupSuffix: string = '.backup'\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 logger.info(`Creating ${filePath} with ${key}...`)\n const content = formatEnvLine(key, value)\n await fs.writeFile(filePath, content, 'utf8')\n logger.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 logger.info(`Adding ${key} to ${filePath}...`)\n newLines.push(formatEnvLine(key, value))\n logger.success(`${key} added successfully`)\n } else {\n logger.info(`Updating ${key} in ${filePath}...`)\n logger.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 logger.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 logger.debug(`Source file ${source} does not exist, skipping copy`)\n return\n }\n\n await fs.copy(source, destination, { overwrite: false })\n logger.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 */\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 // Try to parse as number for backward compatibility\n const numericIssue = typeof options.issueNumber === 'number'\n ? options.issueNumber\n : parseInt(String(options.issueNumber), 10)\n\n if (!isNaN(numericIssue) && String(numericIssue) === String(options.issueNumber)) {\n // Purely numeric issue ID - use arithmetic port calculation\n const port = basePort + numericIssue\n // Validate port range\n if (port > 65535) {\n throw new Error(\n `Calculated port ${port} exceeds maximum (65535). Use a lower base port or issue number.`\n )\n }\n return port\n }\n // Alphanumeric ID - use hash-based calculation\n return calculatePortForBranch(String(options.issueNumber), basePort)\n }\n\n if (options.prNumber !== undefined) {\n const port = basePort + options.prNumber\n // Validate port range\n if (port > 65535) {\n throw new Error(\n `Calculated port ${port} exceeds maximum (65535). Use a lower base port or PR number.`\n )\n }\n return port\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 logger.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 { readPackageJson, hasScript } from '../utils/package-json.js'\nimport { logger } from '../utils/logger.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 readPackageJson(worktreePath)\n\n if (!hasScript(pkgJson, 'build')) {\n logger.warn('No build script found in package.json - skipping build')\n return\n }\n\n logger.info('Building CLI tool...')\n await runScript('build', worktreePath, [], { quiet: true })\n logger.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 logger.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 logger.warn('\\n⚠️ One-time PATH setup required:')\n logger.warn(` Add to ${rcFile}:`)\n logger.warn(` export PATH=\"$HOME/.iloom/bin:$PATH\"`)\n logger.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 logger.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 logger.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 logger.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 logger.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 logger.success(`Removed orphaned symlink: ${symlink.name}`)\n } catch (error) {\n logger.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 { createLogger } from '../utils/logger.js'\nimport { hasVariableInAnyEnvFile } from '../utils/env.js'\nimport fs from 'fs-extra'\n\nconst logger = createLogger({ prefix: '🗂️' })\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 logger.debug(`🔧 DatabaseManager configured with custom variable: ${databaseUrlEnvVarName}`)\n } else {\n logger.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 logger.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 logger.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 logger.warn('Skipping database branch creation: Neon CLI not available')\n logger.warn('Install with: npm install -g neonctl')\n return null\n }\n\n try {\n const isAuth = await this.provider.isAuthenticated(cwd)\n if (!isAuth) {\n logger.warn('Skipping database branch creation: Not authenticated with Neon CLI')\n logger.warn('Run: neon auth')\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 logger.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 logger.success(`Database branch ready: ${this.provider.sanitizeBranchName(branchName)}`)\n return connectionString\n } catch (error) {\n logger.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 logger.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 logger.info('Skipping database branch deletion: CLI tool not available')\n return {\n success: false,\n deleted: false,\n notFound: true,\n error: \"CLI tool not available\",\n branchName\n }\n }\n\n try {\n const isAuth = await this.provider.isAuthenticated(cwd)\n if (!isAuth) {\n logger.warn('Skipping database branch deletion: Not authenticated with DB Provider')\n return {\n success: false,\n deleted: false,\n notFound: false,\n error: \"Not authenticated with DB Provider\",\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 logger.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 logger.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 logger.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 logger.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 logger.debug(`Looking for custom database URL variable: ${this.databaseUrlEnvVarName}`)\n } else {\n logger.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 logger.debug(`✅ Found custom database URL variable: ${this.databaseUrlEnvVarName}`)\n } else {\n logger.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 logger.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 logger.debug('✅ Found fallback DATABASE_URL variable')\n } else {\n logger.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","import path from 'path'\nimport { GitWorktreeManager } from './GitWorktreeManager.js'\nimport { DatabaseManager } from './DatabaseManager.js'\nimport { ProcessManager } from './process/ProcessManager.js'\nimport { CLIIsolationManager } from './CLIIsolationManager.js'\nimport { SettingsManager } from './SettingsManager.js'\nimport { logger } from '../utils/logger.js'\nimport { hasUncommittedChanges, executeGitCommand, findMainWorktreePathWithSettings, extractIssueNumber } from '../utils/git.js'\n\nimport type {\n\tResourceCleanupOptions,\n\tCleanupResult,\n\tOperationResult,\n\tSafetyCheck,\n\tBranchDeleteOptions,\n} from '../types/cleanup.js'\nimport type { GitWorktree } from '../types/worktree.js'\nimport type { ParsedInput } from '../commands/start.js'\n\n/**\n * Manages resource cleanup for worktrees\n * Provides shared cleanup functionality for finish and cleanup commands\n */\nexport class ResourceCleanup {\n\tprivate settingsManager: SettingsManager\n\n\tconstructor(\n\t\tprivate gitWorktree: GitWorktreeManager,\n\t\tprivate processManager: ProcessManager,\n\t\tprivate database?: DatabaseManager,\n\t\tprivate cliIsolation?: CLIIsolationManager,\n\t\tsettingsManager?: SettingsManager\n\t) {\n\t\tthis.settingsManager = settingsManager ?? new SettingsManager()\n\t}\n\n\t/**\n\t * Cleanup a worktree and associated resources\n\t * Main orchestration method\n\t *\n\t * @param parsed - ParsedInput from IdentifierParser with type information\n\t * @param options - Cleanup options\n\t */\n\tasync cleanupWorktree(\n\t\tparsed: ParsedInput,\n\t\toptions: ResourceCleanupOptions = {}\n\t): Promise<CleanupResult> {\n\t\tconst operations: OperationResult[] = []\n\t\tconst errors: Error[] = []\n\n\t\tconst displayIdentifier = parsed.branchName ?? parsed.number?.toString() ?? parsed.originalInput\n\t\tlogger.info(`Starting cleanup for: ${displayIdentifier}`)\n\n\t\t// Extract number from ParsedInput for port calculation\n\t\tconst number = parsed.number\n\n\t\t// Step 1: Terminate dev server if applicable\n\t\tif (number !== undefined) {\n\t\t\tconst port = this.processManager.calculatePort(number)\n\n\t\t\tif (options.dryRun) {\n\t\t\t\toperations.push({\n\t\t\t\t\ttype: 'dev-server',\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tmessage: `[DRY RUN] Would check for dev server on port ${port}`,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tconst terminated = await this.terminateDevServer(port)\n\t\t\t\t\toperations.push({\n\t\t\t\t\t\ttype: 'dev-server',\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\tmessage: terminated\n\t\t\t\t\t\t\t? `Dev server on port ${port} terminated`\n\t\t\t\t\t\t\t: `No dev server running on port ${port}`,\n\t\t\t\t\t})\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst err = error instanceof Error ? error : new Error('Unknown error')\n\t\t\t\t\terrors.push(err)\n\t\t\t\t\toperations.push({\n\t\t\t\t\t\ttype: 'dev-server',\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tmessage: `Failed to terminate dev server`,\n\t\t\t\t\t\terror: err.message,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Step 2: Find worktree using specific methods based on type\n\t\tlet worktree: GitWorktree | null = null\n\t\ttry {\n\t\t\t// Use specific finding methods based on parsed type for precision\n\t\t\tif (parsed.type === 'pr' && parsed.number !== undefined) {\n\t\t\t\t// For PRs, ensure the number is numeric (PRs are always numeric per GitHub)\n\t\t\t\tconst prNumber = typeof parsed.number === 'number' ? parsed.number : Number(parsed.number)\n\t\t\t\tif (isNaN(prNumber) || !isFinite(prNumber)) {\n\t\t\t\t\tthrow new Error(`Invalid PR number: ${parsed.number}. PR numbers must be numeric.`)\n\t\t\t\t}\n\t\t\t\t// For PRs, pass empty string for branchName since we're detecting from path pattern\n\t\t\t\tworktree = await this.gitWorktree.findWorktreeForPR(prNumber, '')\n\t\t\t} else if (parsed.type === 'issue' && parsed.number !== undefined) {\n\t\t\t\tworktree = await this.gitWorktree.findWorktreeForIssue(parsed.number)\n\t\t\t} else if (parsed.type === 'branch' && parsed.branchName) {\n\t\t\t\tworktree = await this.gitWorktree.findWorktreeForBranch(parsed.branchName)\n\t\t\t}\n\n\t\t\tif (!worktree) {\n\t\t\t\tthrow new Error(`No worktree found for identifier: ${displayIdentifier}`)\n\t\t\t}\n\n\t\t\tlogger.debug(`Found worktree: path=\"${worktree.path}\", branch=\"${worktree.branch}\"`)\n\t\t} catch (error) {\n\t\t\tconst err = error instanceof Error ? error : new Error('Unknown error')\n\t\t\terrors.push(err)\n\n\t\t\treturn {\n\t\t\t\tidentifier: displayIdentifier,\n\t\t\t\tsuccess: false,\n\t\t\t\toperations,\n\t\t\t\terrors,\n\t\t\t\trollbackRequired: false,\n\t\t\t}\n\t\t}\n\n\t\t// Step 2.5: Validate safety before proceeding with cleanup (unless force flag is set)\n\t\tif (!options.force) {\n\t\t\tconst safety = await this.validateWorktreeSafety(worktree, parsed.originalInput)\n\n\t\t\tif (!safety.isSafe) {\n\t\t\t\t// Format blocker messages for error output\n\t\t\t\tconst blockerMessage = safety.blockers.join('\\n\\n')\n\t\t\t\tthrow new Error(`Cannot cleanup:\\n\\n${blockerMessage}`)\n\t\t\t}\n\n\t\t\t// Log warnings if any\n\t\t\tif (safety.warnings.length > 0) {\n\t\t\t\tsafety.warnings.forEach(warning => {\n\t\t\t\t\tlogger.warn(warning)\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Step 3: Pre-fetch database configuration before worktree removal\n\t\t// This config is used AFTER worktree deletion when env file no longer exists\n\t\tlet databaseConfig: { shouldCleanup: boolean; envFilePath: string } | null = null\n\t\tif (!options.keepDatabase && worktree) {\n\t\t\tconst envFilePath = path.join(worktree.path, '.env')\n\t\t\ttry {\n\t\t\t\t// Pre-check if database cleanup should happen by reading .env file now\n\t\t\t\tconst shouldCleanup = this.database\n\t\t\t\t\t? await this.database.shouldUseDatabaseBranching(envFilePath)\n\t\t\t\t\t: false\n\t\t\t\tdatabaseConfig = { shouldCleanup, envFilePath }\n\t\t\t} catch (error) {\n\t\t\t\t// If we can't read the config, we'll skip database cleanup\n\t\t\t\tlogger.warn(\n\t\t\t\t\t`Failed to read database config from ${envFilePath}, skipping database cleanup: ${\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t\t}`\n\t\t\t\t)\n\t\t\t\tdatabaseConfig = { shouldCleanup: false, envFilePath }\n\t\t\t}\n\t\t}\n\n\t\t// Step 3.5: Find main worktree path before deletion (needed for branch and database operations)\n\t\tlet mainWorktreePath: string | null = null\n\t\tif (!options.dryRun) {\n\t\t\ttry {\n\t\t\t\tmainWorktreePath = await findMainWorktreePathWithSettings(worktree.path, this.settingsManager)\n\t\t\t} catch (error) {\n\t\t\t\tlogger.warn(\n\t\t\t\t\t`Failed to find main worktree path: ${error instanceof Error ? error.message : String(error)}`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Step 4: Remove worktree\n\t\tif (options.dryRun) {\n\t\t\toperations.push({\n\t\t\t\ttype: 'worktree',\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage: `[DRY RUN] Would remove worktree: ${worktree.path}`,\n\t\t\t})\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tconst worktreeOptions: { force?: boolean; removeDirectory: true; removeBranch: false } =\n\t\t\t\t\t{\n\t\t\t\t\t\tremoveDirectory: true,\n\t\t\t\t\t\tremoveBranch: false, // Handle branch separately\n\t\t\t\t\t}\n\t\t\t\tif (options.force !== undefined) {\n\t\t\t\t\tworktreeOptions.force = options.force\n\t\t\t\t}\n\t\t\t\tawait this.gitWorktree.removeWorktree(worktree.path, worktreeOptions)\n\n\t\t\t\toperations.push({\n\t\t\t\t\ttype: 'worktree',\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tmessage: `Worktree removed: ${worktree.path}`,\n\t\t\t\t})\n\t\t\t} catch (error) {\n\t\t\t\tconst err = error instanceof Error ? error : new Error('Unknown error')\n\t\t\t\terrors.push(err)\n\t\t\t\toperations.push({\n\t\t\t\t\ttype: 'worktree',\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\tmessage: `Failed to remove worktree`,\n\t\t\t\t\terror: err.message,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Step 5: Delete branch if requested\n\t\tif (options.deleteBranch && worktree) {\n\t\t\tif (options.dryRun) {\n\t\t\t\toperations.push({\n\t\t\t\t\ttype: 'branch',\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tmessage: `[DRY RUN] Would delete branch: ${worktree.branch}`,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tconst branchOptions: BranchDeleteOptions = { dryRun: false }\n\t\t\t\t\tif (options.force !== undefined) {\n\t\t\t\t\t\tbranchOptions.force = options.force\n\t\t\t\t\t}\n\t\t\t\t\t// Pass main worktree path to ensure we can execute git commands\n\t\t\t\t\tawait this.deleteBranch(worktree.branch, branchOptions, mainWorktreePath ?? undefined)\n\n\t\t\t\t\toperations.push({\n\t\t\t\t\t\ttype: 'branch',\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\tmessage: `Branch deleted: ${worktree.branch}`,\n\t\t\t\t\t})\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst err = error instanceof Error ? error : new Error('Unknown error')\n\t\t\t\t\terrors.push(err)\n\t\t\t\t\toperations.push({\n\t\t\t\t\t\ttype: 'branch',\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tmessage: `Failed to delete branch`,\n\t\t\t\t\t\terror: err.message,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Step 5.5: Cleanup CLI symlinks if CLI isolation is available\n\t\t// Derive identifier from parsed input (number for issue/PR, branchName for branch)\n\t\tconst cliIdentifier = parsed.number ?? parsed.branchName\n\t\tif (this.cliIsolation && cliIdentifier !== undefined) {\n\t\t\tif (options.dryRun) {\n\t\t\t\toperations.push({\n\t\t\t\t\ttype: 'cli-symlinks',\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tmessage: `[DRY RUN] Would cleanup CLI symlinks for: ${cliIdentifier}`,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tconst removed = await this.cliIsolation.cleanupVersionedExecutables(cliIdentifier)\n\t\t\t\t\toperations.push({\n\t\t\t\t\t\ttype: 'cli-symlinks',\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\tmessage: removed.length > 0\n\t\t\t\t\t\t\t? `CLI symlinks removed: ${removed.length}`\n\t\t\t\t\t\t\t: 'No CLI symlinks to cleanup',\n\t\t\t\t\t})\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Log warning but don't fail\n\t\t\t\t\tconst err = error instanceof Error ? error : new Error('Unknown error')\n\t\t\t\t\terrors.push(err)\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t`CLI symlink cleanup failed: ${err.message}`\n\t\t\t\t\t)\n\t\t\t\t\toperations.push({\n\t\t\t\t\t\ttype: 'cli-symlinks',\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tmessage: 'CLI symlink cleanup failed (non-fatal)',\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Step 6: Cleanup database after worktree and branch removal (using pre-read config)\n\t\tif (databaseConfig && worktree) {\n\t\t\tif (options.dryRun) {\n\t\t\t\toperations.push({\n\t\t\t\t\ttype: 'database',\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tmessage: `[DRY RUN] Would cleanup database branch for: ${worktree.branch}`,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tif (databaseConfig.shouldCleanup && this.database) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Call database deletion with pre-fetched shouldCleanup value and main worktree path\n\t\t\t\t\t\t\t// This avoids reading the already-deleted env file and running commands from deleted directories\n\t\t\t\t\t\t\tconst deletionResult = await this.database.deleteBranchIfConfigured(\n\t\t\t\t\t\t\t\tworktree.branch,\n\t\t\t\t\t\t\t\tdatabaseConfig.shouldCleanup,\n\t\t\t\t\t\t\t\tfalse, // isPreview\n\t\t\t\t\t\t\t\tmainWorktreePath ?? undefined\n\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t// Create operation result based on what actually happened\n\t\t\t\t\t\t\tif (deletionResult.deleted) {\n\t\t\t\t\t\t\t\t// Branch was actually deleted\n\t\t\t\t\t\t\t\tlogger.info(`Database branch deleted: ${worktree.branch}`)\n\t\t\t\t\t\t\t\toperations.push({\n\t\t\t\t\t\t\t\t\ttype: 'database',\n\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\tmessage: `Database branch deleted`,\n\t\t\t\t\t\t\t\t\tdeleted: true,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t} else if (deletionResult.notFound) {\n\t\t\t\t\t\t\t\t// Branch didn't exist - not an error, just nothing to delete\n\t\t\t\t\t\t\t\tlogger.debug(`No database branch found for: ${worktree.branch}`)\n\t\t\t\t\t\t\t\toperations.push({\n\t\t\t\t\t\t\t\t\ttype: 'database',\n\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\tmessage: `No database branch found (skipped)`,\n\t\t\t\t\t\t\t\t\tdeleted: false,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t} else if (deletionResult.userDeclined) {\n\t\t\t\t\t\t\t\t// User declined preview database deletion\n\t\t\t\t\t\t\t\tlogger.info('Preview database deletion declined by user')\n\t\t\t\t\t\t\t\toperations.push({\n\t\t\t\t\t\t\t\t\ttype: 'database',\n\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\tmessage: `Database cleanup skipped (user declined)`,\n\t\t\t\t\t\t\t\t\tdeleted: false,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t} else if (!deletionResult.success) {\n\t\t\t\t\t\t\t\t// Deletion failed with error\n\t\t\t\t\t\t\t\tconst errorMsg = deletionResult.error ?? 'Unknown error'\n\t\t\t\t\t\t\t\terrors.push(new Error(errorMsg))\n\t\t\t\t\t\t\t\tlogger.warn(`Database cleanup failed: ${errorMsg}`)\n\t\t\t\t\t\t\t\toperations.push({\n\t\t\t\t\t\t\t\t\ttype: 'database',\n\t\t\t\t\t\t\t\t\tsuccess: false, // Non-fatal, but report error\n\t\t\t\t\t\t\t\t\tmessage: `Database cleanup failed`,\n\t\t\t\t\t\t\t\t\terror: errorMsg,\n\t\t\t\t\t\t\t\t\tdeleted: false,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Unexpected state - log for debugging\n\t\t\t\t\t\t\t\terrors.push(new Error('Database cleanup in an unknown state'))\n\t\t\t\t\t\t\t\tlogger.warn('Database deletion returned unexpected result state')\n\t\t\t\t\t\t\t\toperations.push({\n\t\t\t\t\t\t\t\t\ttype: 'database',\n\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\tmessage: `Database cleanup in an unknown state`,\n\t\t\t\t\t\t\t\t\tdeleted: false,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t// Unexpected exception (shouldn't happen with result object pattern)\n\t\t\t\t\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)))\n\t\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t\t`Unexpected database cleanup exception: ${error instanceof Error ? error.message : String(error)}`\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\toperations.push({\n\t\t\t\t\t\t\t\ttype: 'database',\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tmessage: `Database cleanup failed`,\n\t\t\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t\t\tdeleted: false,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Database manager not available or not configured\n\t\t\t\t\t\toperations.push({\n\t\t\t\t\t\t\ttype: 'database',\n\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\tmessage: `Database cleanup skipped (not available)`,\n\t\t\t\t\t\t\tdeleted: false,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// This catch block is for any unexpected errors in the outer logic\n\t\t\t\t\tconst err = error instanceof Error ? error : new Error('Unknown error')\n\t\t\t\t\terrors.push(err)\n\t\t\t\t\toperations.push({\n\t\t\t\t\t\ttype: 'database',\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tmessage: `Database cleanup failed`,\n\t\t\t\t\t\terror: err.message,\n\t\t\t\t\t\tdeleted: false,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Calculate overall success\n\t\tconst success = errors.length === 0\n\n\t\treturn {\n\t\t\tidentifier: displayIdentifier,\n\t\t\tbranchName: worktree?.branch,\n\t\t\tsuccess,\n\t\t\toperations,\n\t\t\terrors,\n\t\t\trollbackRequired: false, // Cleanup operations are generally not reversible\n\t\t}\n\t}\n\n\t/**\n\t * Terminate dev server on specified port\n\t */\n\tasync terminateDevServer(port: number): Promise<boolean> {\n\t\tlogger.debug(`Checking for dev server on port ${port}`)\n\n\t\tconst processInfo = await this.processManager.detectDevServer(port)\n\n\t\tif (!processInfo) {\n\t\t\tlogger.debug(`No process found on port ${port}`)\n\t\t\treturn false\n\t\t}\n\n\t\tif (!processInfo.isDevServer) {\n\t\t\tlogger.warn(\n\t\t\t\t`Process on port ${port} (${processInfo.name}) doesn't appear to be a dev server, skipping`\n\t\t\t)\n\t\t\treturn false\n\t\t}\n\n\t\tlogger.info(`Terminating dev server: ${processInfo.name} (PID: ${processInfo.pid})`)\n\n\t\tawait this.processManager.terminateProcess(processInfo.pid)\n\n\t\t// Verify termination\n\t\tconst isFree = await this.processManager.verifyPortFree(port)\n\t\tif (!isFree) {\n\t\t\tthrow new Error(`Dev server may still be running on port ${port}`)\n\t\t}\n\n\t\treturn true\n\t}\n\n\t/**\n\t * Delete a Git branch with safety checks\n\t *\n\t * @param branchName - Name of the branch to delete\n\t * @param options - Delete options (force, dryRun)\n\t * @param cwd - Working directory to execute git command from (defaults to finding main worktree)\n\t */\n\tasync deleteBranch(\n\t\tbranchName: string,\n\t\toptions: BranchDeleteOptions = {},\n\t\tcwd?: string\n\t): Promise<boolean> {\n\t\t// Get protected branches list from centralized method\n\t\tconst protectedBranches = await this.settingsManager.getProtectedBranches(cwd)\n\n\t\t// Check for protected branches\n\t\tif (protectedBranches.includes(branchName)) {\n\t\t\tthrow new Error(`Cannot delete protected branch: ${branchName}`)\n\t\t}\n\n\t\tif (options.dryRun) {\n\t\t\tlogger.info(`[DRY RUN] Would delete branch: ${branchName}`)\n\t\t\treturn true\n\t\t}\n\n\t\t// Use GitWorktreeManager's removeWorktree with removeBranch option\n\t\t// Or execute git branch -D directly via executeGitCommand\n\t\ttry {\n\t\t\t// Use provided cwd, or find main worktree path as fallback\n\t\t\t// This ensures we're not running git commands from a deleted directory\n\t\t\tlet workingDir = cwd ?? await findMainWorktreePathWithSettings(undefined, this.settingsManager)\t\t\t\n\n\t\t\t// Use safe delete (-d) unless force is specified\n\t\t\tconst deleteFlag = options.force ? '-D' : '-d'\n\t\t\tawait executeGitCommand(['branch', deleteFlag, branchName], {\n\t\t\t\tcwd: workingDir\n\t\t\t})\n\n\t\t\tlogger.info(`Branch deleted: ${branchName}`)\n\t\t\treturn true\n\t\t} catch (error) {\n\t\t\tif (options.force) {\n\t\t\t\tthrow error\n\t\t\t}\n\n\t\t\t// For safe delete failures, check if it's actually an unmerged branch error\n\t\t\t// and provide helpful message only in that case, otherwise show the real error\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error)\n\n\t\t\t// Git error for unmerged branch typically contains \"not fully merged\"\n\t\t\tif (errorMessage.includes('not fully merged')) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Cannot delete unmerged branch '${branchName}'. Use --force to delete anyway.`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// For other errors (like branch doesn't exist), show the actual git error\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/**\n\t * Cleanup database branch\n\t * Gracefully handles missing DatabaseManager\n\t *\n\t * @deprecated This method is deprecated and should not be used for post-deletion cleanup.\n\t * Use the pre-fetch mechanism in cleanupWorktree() instead.\n\t * This method will fail if called after worktree deletion because\n\t * it attempts to read the .env file which has been deleted.\n\t *\n\t * @param branchName - Name of the branch to delete\n\t * @param worktreePath - Path to worktree (must still exist with .env file)\n\t */\n\tasync cleanupDatabase(branchName: string, worktreePath: string): Promise<boolean> {\n\t\tif (!this.database) {\n\t\t\tlogger.debug('Database manager not available, skipping database cleanup')\n\t\t\treturn false\n\t\t}\n\n\t\ttry {\n\t\t\t// Pre-fetch configuration before deletion\n\t\t\tconst envFilePath = path.join(worktreePath, '.env')\n\t\t\tconst shouldCleanup = await this.database.shouldUseDatabaseBranching(envFilePath)\n\n\t\t\t// Find main worktree path to avoid running commands from potentially deleted directories\n\t\t\tlet cwd: string | undefined\n\t\t\ttry {\n\t\t\t\tcwd = await findMainWorktreePathWithSettings(worktreePath, this.settingsManager)\n\t\t\t} catch (error) {\n\t\t\t\t// If we can't find main worktree, commands will run from current directory\n\t\t\t\tlogger.debug(\n\t\t\t\t\t`Could not find main worktree path, using current directory: ${error instanceof Error ? error.message : String(error)}`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst result = await this.database.deleteBranchIfConfigured(\n\t\t\t\tbranchName,\n\t\t\t\tshouldCleanup,\n\t\t\t\tfalse, // isPreview\n\t\t\t\tcwd\n\t\t\t)\n\n\t\t\t// Only return true if deletion actually occurred\n\t\t\tif (result.deleted) {\n\t\t\t\tlogger.info(`Database branch deleted: ${branchName}`)\n\t\t\t\treturn true\n\t\t\t} else if (result.notFound) {\n\t\t\t\tlogger.debug(`No database branch found for: ${branchName}`)\n\t\t\t\treturn false\n\t\t\t} else if (result.userDeclined) {\n\t\t\t\tlogger.info('Preview database deletion declined by user')\n\t\t\t\treturn false\n\t\t\t} else if (!result.success) {\n\t\t\t\tlogger.warn(`Database cleanup failed: ${result.error ?? 'Unknown error'}`)\n\t\t\t\treturn false\n\t\t\t} else {\n\t\t\t\t// Unexpected state\n\t\t\t\tlogger.debug('Database deletion returned unexpected result')\n\t\t\t\treturn false\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Unexpected exception\n\t\t\tlogger.warn(\n\t\t\t\t`Unexpected database cleanup error: ${error instanceof Error ? error.message : String(error)}`\n\t\t\t)\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * Cleanup multiple worktrees\n\t */\n\tasync cleanupMultipleWorktrees(\n\t\tidentifiers: string[],\n\t\toptions: ResourceCleanupOptions = {}\n\t): Promise<CleanupResult[]> {\n\t\tconst results: CleanupResult[] = []\n\n\t\tfor (const identifier of identifiers) {\n\t\t\t// Parse the identifier to get ParsedInput format\n\t\t\tconst parsed = this.parseIdentifier(identifier)\n\t\t\tconst result = await this.cleanupWorktree(parsed, options)\n\t\t\tresults.push(result)\n\t\t}\n\n\t\treturn results\n\t}\n\n\t/**\n\t * Validate worktree safety given a worktree object\n\t * Private method used internally when worktree is already known\n\t */\n\tprivate async validateWorktreeSafety(\n\t\tworktree: GitWorktree,\n\t\tidentifier: string\n\t): Promise<SafetyCheck> {\n\t\tconst warnings: string[] = []\n\t\tconst blockers: string[] = []\n\n\t\t// Check if main worktree\n\t\tconst isMain = await this.gitWorktree.isMainWorktree(worktree, this.settingsManager)\n\t\tif (isMain) {\n\t\t\tblockers.push(`Cannot cleanup main worktree: \"${worktree.branch}\" @ \"${worktree.path}\"`)\n\t\t}\n\n\t\t// Check for uncommitted changes\n\t\tconst hasChanges = await hasUncommittedChanges(worktree.path)\n\t\tif (hasChanges) {\n\t\t\t// Create simple blocker message with actionable guidance\n\t\t\tconst blockerMessage =\n\t\t\t\t`Worktree has uncommitted changes.\\n\\n` +\n\t\t\t\t`Please resolve before cleanup - you have some options:\\n` +\n\t\t\t\t` • Commit changes: cd ${worktree.path} && git commit -am \"message\"\\n` +\n\t\t\t\t` • Stash changes: cd ${worktree.path} && git stash\\n` +\n\t\t\t\t` • Force cleanup: il cleanup ${identifier} --force (WARNING: will discard changes)`\n\n\t\t\tblockers.push(blockerMessage)\n\t\t}\n\n\t\treturn {\n\t\t\tisSafe: blockers.length === 0,\n\t\t\twarnings,\n\t\t\tblockers,\n\t\t}\n\t}\n\n\t/**\n\t * Validate cleanup safety\n\t */\n\tasync validateCleanupSafety(identifier: string): Promise<SafetyCheck> {\n\t\tconst warnings: string[] = []\n\t\tconst blockers: string[] = []\n\n\t\t// Find worktree\n\t\tconst worktrees = await this.gitWorktree.findWorktreesByIdentifier(identifier)\n\n\t\tif (worktrees.length === 0) {\n\t\t\tblockers.push(`No worktree found for: ${identifier}`)\n\t\t\treturn { isSafe: false, warnings, blockers }\n\t\t}\n\n\t\tconst worktree = worktrees[0]\n\t\tif (!worktree) {\n\t\t\tblockers.push(`No worktree found for: ${identifier}`)\n\t\t\treturn { isSafe: false, warnings, blockers }\n\t\t}\n\n\t\t// Delegate to private method that validates the worktree\n\t\treturn await this.validateWorktreeSafety(worktree, identifier)\n\t}\n\n\t/**\n\t * Parse identifier to determine type and extract number\n\t * Helper method for port calculation\n\t */\n\tprivate parseIdentifier(identifier: string): ParsedInput {\n\t\t// Check for issue pattern\n\t\tconst issueId = extractIssueNumber(identifier)\n\t\tif (issueId !== null) {\n\t\t\treturn {\n\t\t\t\ttype: 'issue',\n\t\t\t\tnumber: issueId,\n\t\t\t\toriginalInput: identifier\n\t\t\t}\n\t\t}\n\n\t\t// Check for PR pattern\n\t\tconst prMatch = identifier.match(/(?:pr|PR)[/-](\\d+)/)\n\t\tif (prMatch?.[1]) {\n\t\t\treturn {\n\t\t\t\ttype: 'pr',\n\t\t\t\tnumber: parseInt(prMatch[1], 10),\n\t\t\t\toriginalInput: identifier\n\t\t\t}\n\t\t}\n\n\t\t// Check for numeric identifier\n\t\tconst numericMatch = identifier.match(/^#?(\\d+)$/)\n\t\tif (numericMatch?.[1]) {\n\t\t\t// Assume issue for numeric identifiers\n\t\t\treturn {\n\t\t\t\ttype: 'issue',\n\t\t\t\tnumber: parseInt(numericMatch[1], 10),\n\t\t\t\toriginalInput: identifier\n\t\t\t}\n\t\t}\n\n\t\t// Treat as branch name\n\t\treturn {\n\t\t\ttype: 'branch',\n\t\t\tbranchName: identifier,\n\t\t\toriginalInput: identifier\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,WAAU;AACjB,OAAOC,SAAQ;;;ACDf,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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AO,MAAM,KAAK,uBAAuB,UAAU,UAAU;AAAA,EAC9D;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,gBAAgB,YAAiC;AAExD,UAAM,UAAU,mBAAmB,UAAU;AAC7C,QAAI,YAAY,MAAM;AACrB,aAAO;AAAA,QACN,MAAM;AAAA,QACN,QAAQ;AAAA,QACR,eAAe;AAAA,MAChB;AAAA,IACD;AAGA,UAAM,UAAU,WAAW,MAAM,oBAAoB;AACrD,QAAI,mCAAU,IAAI;AACjB,aAAO;AAAA,QACN,MAAM;AAAA,QACN,QAAQ,SAAS,QAAQ,CAAC,GAAG,EAAE;AAAA,QAC/B,eAAe;AAAA,MAChB;AAAA,IACD;AAGA,UAAM,eAAe,WAAW,MAAM,WAAW;AACjD,QAAI,6CAAe,IAAI;AAEtB,aAAO;AAAA,QACN,MAAM;AAAA,QACN,QAAQ,SAAS,aAAa,CAAC,GAAG,EAAE;AAAA,QACpC,eAAe;AAAA,MAChB;AAAA,IACD;AAGA,WAAO;AAAA,MACN,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,eAAe;AAAA,IAChB;AAAA,EACD;AACD;","names":["path","fs","path","fs","fs","logger","fs","fs","path","path","fs","fs","logger","path","path"]}
@@ -11,7 +11,7 @@ import {
11
11
  isPRBranch,
12
12
  isValidGitRepo,
13
13
  parseWorktreeList
14
- } from "./chunk-4BGK7T6X.js";
14
+ } from "./chunk-5NTD4MCZ.js";
15
15
 
16
16
  // src/lib/GitWorktreeManager.ts
17
17
  import path from "path";
@@ -386,4 +386,4 @@ var GitWorktreeManager = class {
386
386
  export {
387
387
  GitWorktreeManager
388
388
  };
389
- //# sourceMappingURL=chunk-TSKY3JI7.js.map
389
+ //# sourceMappingURL=chunk-OAP6SASD.js.map
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/utils/IdentifierParser.ts
4
+ var IdentifierParser = class {
5
+ constructor(gitWorktreeManager) {
6
+ this.gitWorktreeManager = gitWorktreeManager;
7
+ }
8
+ /**
9
+ * Parse identifier using pattern-based detection on existing worktrees.
10
+ * Does NOT make GitHub API calls - only checks local worktree patterns.
11
+ *
12
+ * @param identifier - The identifier to parse (e.g., "42", "#66", "ENG-123", "my-branch")
13
+ * @returns ParsedInput with type, number/branchName, and originalInput
14
+ * @throws Error if no matching worktree is found
15
+ */
16
+ async parseForPatternDetection(identifier) {
17
+ const cleanId = identifier.replace(/^#/, "").trim();
18
+ const originalInput = identifier;
19
+ const numericMatch = cleanId.match(/^(\d+)$/);
20
+ if (numericMatch == null ? void 0 : numericMatch[1]) {
21
+ const number = parseInt(numericMatch[1], 10);
22
+ const prWorktree = await this.gitWorktreeManager.findWorktreeForPR(number, "");
23
+ if (prWorktree) {
24
+ return {
25
+ type: "pr",
26
+ number,
27
+ originalInput
28
+ };
29
+ }
30
+ const issueWorktree = await this.gitWorktreeManager.findWorktreeForIssue(number);
31
+ if (issueWorktree) {
32
+ return {
33
+ type: "issue",
34
+ number,
35
+ originalInput
36
+ };
37
+ }
38
+ throw new Error(`No worktree found for identifier: ${identifier}`);
39
+ }
40
+ const alphanumericMatch = cleanId.match(/^([A-Za-z]+-\d+)$/);
41
+ if (alphanumericMatch == null ? void 0 : alphanumericMatch[1]) {
42
+ const alphanumericId = alphanumericMatch[1];
43
+ const issueWorktree = await this.gitWorktreeManager.findWorktreeForIssue(alphanumericId);
44
+ if (issueWorktree) {
45
+ return {
46
+ type: "issue",
47
+ number: alphanumericId,
48
+ originalInput
49
+ };
50
+ }
51
+ throw new Error(`No worktree found for identifier: ${identifier}`);
52
+ }
53
+ const branchWorktree = await this.gitWorktreeManager.findWorktreeForBranch(cleanId);
54
+ if (branchWorktree) {
55
+ return {
56
+ type: "branch",
57
+ branchName: cleanId,
58
+ originalInput
59
+ };
60
+ }
61
+ throw new Error(`No worktree found for identifier: ${identifier}`);
62
+ }
63
+ };
64
+
65
+ export {
66
+ IdentifierParser
67
+ };
68
+ //# sourceMappingURL=chunk-OXAM2WVC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/IdentifierParser.ts"],"sourcesContent":["import type { ParsedInput } from '../commands/start.js'\nimport type { GitWorktreeManager } from '../lib/GitWorktreeManager.js'\n\n/**\n * IdentifierParser provides consistent identifier parsing across commands\n * using pattern-based detection without GitHub API calls.\n *\n * Detection Strategy:\n * 1. For numeric input (e.g., \"42\", \"#66\"):\n * - Check for PR worktree first (_pr_N pattern in path)\n * - Then check for issue worktree (issue-N pattern in branch)\n * 2. For non-numeric input:\n * - Treat as branch name and verify worktree exists\n *\n * This ensures:\n * - No unnecessary GitHub API calls\n * - Consistent behavior across finish/cleanup commands\n * - PR detection takes priority over issue detection\n */\nexport class IdentifierParser {\n\tconstructor(private gitWorktreeManager: GitWorktreeManager) {}\n\n\t/**\n\t * Parse identifier using pattern-based detection on existing worktrees.\n\t * Does NOT make GitHub API calls - only checks local worktree patterns.\n\t *\n\t * @param identifier - The identifier to parse (e.g., \"42\", \"#66\", \"ENG-123\", \"my-branch\")\n\t * @returns ParsedInput with type, number/branchName, and originalInput\n\t * @throws Error if no matching worktree is found\n\t */\n\tasync parseForPatternDetection(identifier: string): Promise<ParsedInput> {\n\t\t// Remove # prefix if present and trim whitespace\n\t\tconst cleanId = identifier.replace(/^#/, '').trim()\n\t\tconst originalInput = identifier\n\n\t\t// Check if input is numeric (GitHub-style issue/PR numbers)\n\t\tconst numericMatch = cleanId.match(/^(\\d+)$/)\n\n\t\tif (numericMatch?.[1]) {\n\t\t\tconst number = parseInt(numericMatch[1], 10)\n\n\t\t\t// Priority 1: Check for PR worktree (_pr_N pattern)\n\t\t\t// Pass empty string for branch name since we don't know it yet\n\t\t\tconst prWorktree = await this.gitWorktreeManager.findWorktreeForPR(number, '')\n\t\t\tif (prWorktree) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'pr',\n\t\t\t\t\tnumber,\n\t\t\t\t\toriginalInput,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Priority 2: Check for issue worktree (issue-N pattern)\n\t\t\tconst issueWorktree = await this.gitWorktreeManager.findWorktreeForIssue(number)\n\t\t\tif (issueWorktree) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'issue',\n\t\t\t\t\tnumber,\n\t\t\t\t\toriginalInput,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// No matching worktree found for numeric input\n\t\t\tthrow new Error(`No worktree found for identifier: ${identifier}`)\n\t\t}\n\n\t\t// Check if input is alphanumeric issue identifier (Linear/Jira-style: ABC-123, ENG-42)\n\t\tconst alphanumericMatch = cleanId.match(/^([A-Za-z]+-\\d+)$/)\n\n\t\tif (alphanumericMatch?.[1]) {\n\t\t\tconst alphanumericId = alphanumericMatch[1]\n\n\t\t\t// Check for issue worktree with alphanumeric identifier\n\t\t\tconst issueWorktree = await this.gitWorktreeManager.findWorktreeForIssue(alphanumericId)\n\t\t\tif (issueWorktree) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'issue',\n\t\t\t\t\tnumber: alphanumericId,\n\t\t\t\t\toriginalInput,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// No matching worktree found for alphanumeric identifier\n\t\t\tthrow new Error(`No worktree found for identifier: ${identifier}`)\n\t\t}\n\n\t\t// Non-numeric/non-alphanumeric input: treat as branch name\n\t\tconst branchWorktree = await this.gitWorktreeManager.findWorktreeForBranch(cleanId)\n\t\tif (branchWorktree) {\n\t\t\treturn {\n\t\t\t\ttype: 'branch',\n\t\t\t\tbranchName: cleanId,\n\t\t\t\toriginalInput,\n\t\t\t}\n\t\t}\n\n\t\t// No matching worktree found for branch name\n\t\tthrow new Error(`No worktree found for identifier: ${identifier}`)\n\t}\n}\n"],"mappings":";;;AAmBO,IAAM,mBAAN,MAAuB;AAAA,EAC7B,YAAoB,oBAAwC;AAAxC;AAAA,EAAyC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU7D,MAAM,yBAAyB,YAA0C;AAExE,UAAM,UAAU,WAAW,QAAQ,MAAM,EAAE,EAAE,KAAK;AAClD,UAAM,gBAAgB;AAGtB,UAAM,eAAe,QAAQ,MAAM,SAAS;AAE5C,QAAI,6CAAe,IAAI;AACtB,YAAM,SAAS,SAAS,aAAa,CAAC,GAAG,EAAE;AAI3C,YAAM,aAAa,MAAM,KAAK,mBAAmB,kBAAkB,QAAQ,EAAE;AAC7E,UAAI,YAAY;AACf,eAAO;AAAA,UACN,MAAM;AAAA,UACN;AAAA,UACA;AAAA,QACD;AAAA,MACD;AAGA,YAAM,gBAAgB,MAAM,KAAK,mBAAmB,qBAAqB,MAAM;AAC/E,UAAI,eAAe;AAClB,eAAO;AAAA,UACN,MAAM;AAAA,UACN;AAAA,UACA;AAAA,QACD;AAAA,MACD;AAGA,YAAM,IAAI,MAAM,qCAAqC,UAAU,EAAE;AAAA,IAClE;AAGA,UAAM,oBAAoB,QAAQ,MAAM,mBAAmB;AAE3D,QAAI,uDAAoB,IAAI;AAC3B,YAAM,iBAAiB,kBAAkB,CAAC;AAG1C,YAAM,gBAAgB,MAAM,KAAK,mBAAmB,qBAAqB,cAAc;AACvF,UAAI,eAAe;AAClB,eAAO;AAAA,UACN,MAAM;AAAA,UACN,QAAQ;AAAA,UACR;AAAA,QACD;AAAA,MACD;AAGA,YAAM,IAAI,MAAM,qCAAqC,UAAU,EAAE;AAAA,IAClE;AAGA,UAAM,iBAAiB,MAAM,KAAK,mBAAmB,sBAAsB,OAAO;AAClF,QAAI,gBAAgB;AACnB,aAAO;AAAA,QACN,MAAM;AAAA,QACN,YAAY;AAAA,QACZ;AAAA,MACD;AAAA,IACD;AAGA,UAAM,IAAI,MAAM,qCAAqC,UAAU,EAAE;AAAA,EAClE;AACD;","names":[]}
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  GitWorktreeManager
4
- } from "./chunk-TSKY3JI7.js";
4
+ } from "./chunk-OAP6SASD.js";
5
5
  import {
6
6
  logger
7
7
  } from "./chunk-GEHQXLEI.js";
@@ -299,4 +299,4 @@ Please consult your shell's documentation for setting up custom completions.
299
299
  export {
300
300
  ShellCompletion
301
301
  };
302
- //# sourceMappingURL=chunk-4E4LD3QR.js.map
302
+ //# sourceMappingURL=chunk-PRE7KTM4.js.map
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ buildEnvSourceCommands
4
+ } from "./chunk-UJL4HI2R.js";
2
5
 
3
6
  // src/utils/terminal.ts
4
7
  import { execa } from "execa";
@@ -23,7 +26,7 @@ async function openTerminalWindow(options) {
23
26
  );
24
27
  }
25
28
  const hasITerm2 = await detectITerm2();
26
- const applescript = hasITerm2 ? buildITerm2SingleTabScript(options) : buildAppleScript(options);
29
+ const applescript = hasITerm2 ? await buildITerm2SingleTabScript(options) : await buildAppleScript(options);
27
30
  try {
28
31
  await execa("osascript", ["-e", applescript]);
29
32
  if (!hasITerm2) {
@@ -35,7 +38,7 @@ async function openTerminalWindow(options) {
35
38
  );
36
39
  }
37
40
  }
38
- function buildAppleScript(options) {
41
+ async function buildAppleScript(options) {
39
42
  const {
40
43
  workspacePath,
41
44
  command,
@@ -48,8 +51,12 @@ function buildAppleScript(options) {
48
51
  if (workspacePath) {
49
52
  commands.push(`cd '${escapePathForAppleScript(workspacePath)}'`);
50
53
  }
51
- if (includeEnvSetup) {
52
- commands.push("source .env");
54
+ if (includeEnvSetup && workspacePath) {
55
+ const sourceCommands = await buildEnvSourceCommands(
56
+ workspacePath,
57
+ async (p) => existsSync(p)
58
+ );
59
+ commands.push(...sourceCommands);
53
60
  }
54
61
  if (includePortExport && port !== void 0) {
55
62
  commands.push(`export PORT=${port}`);
@@ -77,8 +84,8 @@ function escapePathForAppleScript(path) {
77
84
  function escapeForAppleScript(command) {
78
85
  return command.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
79
86
  }
80
- function buildITerm2SingleTabScript(options) {
81
- const command = buildCommandSequence(options);
87
+ async function buildITerm2SingleTabScript(options) {
88
+ const command = await buildCommandSequence(options);
82
89
  let script = 'tell application id "com.googlecode.iterm2"\n';
83
90
  script += " create window with default profile\n";
84
91
  script += " set s1 to current session of current window\n\n";
@@ -99,7 +106,7 @@ function buildITerm2SingleTabScript(options) {
99
106
  script += "end tell";
100
107
  return script;
101
108
  }
102
- function buildCommandSequence(options) {
109
+ async function buildCommandSequence(options) {
103
110
  const {
104
111
  workspacePath,
105
112
  command,
@@ -111,8 +118,12 @@ function buildCommandSequence(options) {
111
118
  if (workspacePath) {
112
119
  commands.push(`cd '${escapePathForAppleScript(workspacePath)}'`);
113
120
  }
114
- if (includeEnvSetup) {
115
- commands.push("source .env");
121
+ if (includeEnvSetup && workspacePath) {
122
+ const sourceCommands = await buildEnvSourceCommands(
123
+ workspacePath,
124
+ async (p) => existsSync(p)
125
+ );
126
+ commands.push(...sourceCommands);
116
127
  }
117
128
  if (includePortExport && port !== void 0) {
118
129
  commands.push(`export PORT=${port}`);
@@ -123,7 +134,7 @@ function buildCommandSequence(options) {
123
134
  const fullCommand = commands.join(" && ");
124
135
  return ` ${fullCommand}`;
125
136
  }
126
- function buildITerm2MultiTabScript(optionsArray) {
137
+ async function buildITerm2MultiTabScript(optionsArray) {
127
138
  if (optionsArray.length < 2) {
128
139
  throw new Error("buildITerm2MultiTabScript requires at least 2 terminal options");
129
140
  }
@@ -134,7 +145,7 @@ function buildITerm2MultiTabScript(optionsArray) {
134
145
  if (!options1) {
135
146
  throw new Error("First terminal option is undefined");
136
147
  }
137
- const command1 = buildCommandSequence(options1);
148
+ const command1 = await buildCommandSequence(options1);
138
149
  script += " set s1 to current session of newWindow\n\n";
139
150
  if (options1.backgroundColor) {
140
151
  const { r, g, b } = options1.backgroundColor;
@@ -154,7 +165,7 @@ function buildITerm2MultiTabScript(optionsArray) {
154
165
  if (!options) {
155
166
  throw new Error(`Terminal option at index ${i} is undefined`);
156
167
  }
157
- const command = buildCommandSequence(options);
168
+ const command = await buildCommandSequence(options);
158
169
  const sessionVar = `s${i + 1}`;
159
170
  script += " tell newWindow\n";
160
171
  script += ` set newTab${i} to (create tab with default profile)
@@ -193,7 +204,7 @@ async function openMultipleTerminalWindows(optionsArray) {
193
204
  }
194
205
  const hasITerm2 = await detectITerm2();
195
206
  if (hasITerm2) {
196
- const applescript = buildITerm2MultiTabScript(optionsArray);
207
+ const applescript = await buildITerm2MultiTabScript(optionsArray);
197
208
  try {
198
209
  await execa("osascript", ["-e", applescript]);
199
210
  } catch (error) {
@@ -214,15 +225,10 @@ async function openMultipleTerminalWindows(optionsArray) {
214
225
  }
215
226
  }
216
227
  }
217
- async function openDualTerminalWindow(options1, options2) {
218
- await openMultipleTerminalWindows([options1, options2]);
219
- }
220
228
 
221
229
  export {
222
- detectPlatform,
223
230
  detectITerm2,
224
231
  openTerminalWindow,
225
- openMultipleTerminalWindows,
226
- openDualTerminalWindow
232
+ openMultipleTerminalWindows
227
233
  };
228
- //# sourceMappingURL=chunk-ZE74H5BR.js.map
234
+ //# sourceMappingURL=chunk-RW54ZMBM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/terminal.ts"],"sourcesContent":["import { execa } from 'execa'\nimport { existsSync } from 'node:fs'\nimport type { Platform } from '../types/index.js'\nimport { buildEnvSourceCommands } from './env.js'\n\nexport interface TerminalWindowOptions {\n\tworkspacePath?: string\n\tcommand?: string\n\tbackgroundColor?: { r: number; g: number; b: number }\n\tport?: number\n\tincludeEnvSetup?: boolean // source .env\n\tincludePortExport?: boolean // export PORT=<port>\n\ttitle?: string // Terminal tab title\n}\n\n/**\n * Detect current platform\n */\nexport function detectPlatform(): Platform {\n\tconst platform = process.platform\n\tif (platform === 'darwin') return 'darwin'\n\tif (platform === 'linux') return 'linux'\n\tif (platform === 'win32') return 'win32'\n\treturn 'unsupported'\n}\n\n/**\n * Detect if iTerm2 is installed on macOS\n * Returns false on non-macOS platforms\n */\nexport async function detectITerm2(): Promise<boolean> {\n\tconst platform = detectPlatform()\n\tif (platform !== 'darwin') return false\n\n\t// Check if iTerm.app exists at standard location\n\treturn existsSync('/Applications/iTerm.app')\n}\n\n/**\n * Open new terminal window with specified options\n * Currently supports macOS only\n */\nexport async function openTerminalWindow(\n\toptions: TerminalWindowOptions\n): Promise<void> {\n\tconst platform = detectPlatform()\n\n\tif (platform !== 'darwin') {\n\t\tthrow new Error(\n\t\t\t`Terminal window launching not yet supported on ${platform}. ` +\n\t\t\t\t`Currently only macOS is supported.`\n\t\t)\n\t}\n\n\t// Detect if iTerm2 is available\n\tconst hasITerm2 = await detectITerm2()\n\n\t// Build appropriate AppleScript based on terminal availability\n\tconst applescript = hasITerm2\n\t\t? await buildITerm2SingleTabScript(options)\n\t\t: await buildAppleScript(options)\n\n\ttry {\n\t\tawait execa('osascript', ['-e', applescript])\n\n\t\t// Activate the appropriate terminal application (only needed for Terminal.app)\n\t\t// iTerm2 script includes its own activation\n\t\tif (!hasITerm2) {\n\t\t\tawait execa('osascript', ['-e', 'tell application \"Terminal\" to activate'])\n\t\t}\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Failed to open terminal window: ${error instanceof Error ? error.message : 'Unknown error'}`\n\t\t)\n\t}\n}\n\n/**\n * Build AppleScript for macOS Terminal.app\n */\nasync function buildAppleScript(options: TerminalWindowOptions): Promise<string> {\n\tconst {\n\t\tworkspacePath,\n\t\tcommand,\n\t\tbackgroundColor,\n\t\tport,\n\t\tincludeEnvSetup,\n\t\tincludePortExport,\n\t} = options\n\n\t// Build command sequence\n\tconst commands: string[] = []\n\n\t// Navigate to workspace\n\tif (workspacePath) {\n\t\tcommands.push(`cd '${escapePathForAppleScript(workspacePath)}'`)\n\t}\n\n\t// Source all dotenv-flow files\n\tif (includeEnvSetup && workspacePath) {\n\t\tconst sourceCommands = await buildEnvSourceCommands(\n\t\t\tworkspacePath,\n\t\t\tasync (p) => existsSync(p)\n\t\t)\n\t\tcommands.push(...sourceCommands)\n\t}\n\n\t// Export PORT variable\n\tif (includePortExport && port !== undefined) {\n\t\tcommands.push(`export PORT=${port}`)\n\t}\n\n\t// Add custom command\n\tif (command) {\n\t\tcommands.push(command)\n\t}\n\n\t// Join with &&\n\tconst fullCommand = commands.join(' && ')\n\n\t// Prefix with space to prevent shell history pollution\n\t// Most shells (bash/zsh) ignore commands starting with space when HISTCONTROL=ignorespace\n\tconst historyFreeCommand = ` ${fullCommand}`\n\n\t// Build AppleScript\n\tlet script = `tell application \"Terminal\"\\n`\n\tscript += ` set newTab to do script \"${escapeForAppleScript(historyFreeCommand)}\"\\n`\n\n\t// Apply background color if provided\n\tif (backgroundColor) {\n\t\tconst { r, g, b } = backgroundColor\n\t\t// Convert 8-bit RGB (0-255) to 16-bit RGB (0-65535)\n\t\tscript += ` set background color of newTab to {${Math.round(r * 257)}, ${Math.round(g * 257)}, ${Math.round(b * 257)}}\\n`\n\t}\n\n\tscript += `end tell`\n\n\treturn script\n}\n\n/**\n * Escape path for AppleScript string\n * Single quotes in path need special escaping\n */\nfunction escapePathForAppleScript(path: string): string {\n\t// Replace single quote with '\\''\n\treturn path.replace(/'/g, \"'\\\\''\")\n}\n\n/**\n * Escape command for AppleScript do script\n * Must handle double quotes and backslashes\n */\nfunction escapeForAppleScript(command: string): string {\n\treturn (\n\t\tcommand\n\t\t\t.replace(/\\\\/g, '\\\\\\\\') // Escape backslashes\n\t\t\t.replace(/\"/g, '\\\\\"') // Escape double quotes\n\t)\n}\n\n/**\n * Build iTerm2 AppleScript for single tab\n */\nasync function buildITerm2SingleTabScript(options: TerminalWindowOptions): Promise<string> {\n\tconst command = await buildCommandSequence(options)\n\n\tlet script = 'tell application id \"com.googlecode.iterm2\"\\n'\n\tscript += ' create window with default profile\\n'\n\tscript += ' set s1 to current session of current window\\n\\n'\n\n\t// Set background color\n\tif (options.backgroundColor) {\n\t\tconst { r, g, b } = options.backgroundColor\n\t\tscript += ` set background color of s1 to {${Math.round(r * 257)}, ${Math.round(g * 257)}, ${Math.round(b * 257)}}\\n`\n\t}\n\n\t// Execute command\n\tscript += ` tell s1 to write text \"${escapeForAppleScript(command)}\"\\n\\n`\n\n\t// Set session name (tab title)\n\tif (options.title) {\n\t\tscript += ` set name of s1 to \"${escapeForAppleScript(options.title)}\"\\n\\n`\n\t}\n\n\t// Activate iTerm2\n\tscript += ' activate\\n'\n\tscript += 'end tell'\n\n\treturn script\n}\n\n/**\n * Build command sequence for terminal\n */\nasync function buildCommandSequence(options: TerminalWindowOptions): Promise<string> {\n\tconst {\n\t\tworkspacePath,\n\t\tcommand,\n\t\tport,\n\t\tincludeEnvSetup,\n\t\tincludePortExport,\n\t} = options\n\n\tconst commands: string[] = []\n\n\t// Navigate to workspace\n\tif (workspacePath) {\n\t\tcommands.push(`cd '${escapePathForAppleScript(workspacePath)}'`)\n\t}\n\n\t// Source all dotenv-flow files\n\tif (includeEnvSetup && workspacePath) {\n\t\tconst sourceCommands = await buildEnvSourceCommands(\n\t\t\tworkspacePath,\n\t\t\tasync (p) => existsSync(p)\n\t\t)\n\t\tcommands.push(...sourceCommands)\n\t}\n\n\t// Export PORT variable\n\tif (includePortExport && port !== undefined) {\n\t\tcommands.push(`export PORT=${port}`)\n\t}\n\n\t// Add custom command\n\tif (command) {\n\t\tcommands.push(command)\n\t}\n\n\t// Join with &&\n\tconst fullCommand = commands.join(' && ')\n\n\t// Prefix with space to prevent shell history pollution\n\treturn ` ${fullCommand}`\n}\n\n/**\n * Build iTerm2 AppleScript for multiple tabs (2+) in single window\n */\nasync function buildITerm2MultiTabScript(\n\toptionsArray: TerminalWindowOptions[]\n): Promise<string> {\n\tif (optionsArray.length < 2) {\n\t\tthrow new Error('buildITerm2MultiTabScript requires at least 2 terminal options')\n\t}\n\n\tlet script = 'tell application id \"com.googlecode.iterm2\"\\n'\n\tscript += ' create window with default profile\\n'\n\tscript += ' set newWindow to current window\\n'\n\n\t// First tab\n\tconst options1 = optionsArray[0]\n\tif (!options1) {\n\t\tthrow new Error('First terminal option is undefined')\n\t}\n\tconst command1 = await buildCommandSequence(options1)\n\n\tscript += ' set s1 to current session of newWindow\\n\\n'\n\n\t// Set background color for first tab\n\tif (options1.backgroundColor) {\n\t\tconst { r, g, b } = options1.backgroundColor\n\t\tscript += ` set background color of s1 to {${Math.round(r * 257)}, ${Math.round(g * 257)}, ${Math.round(b * 257)}}\\n`\n\t}\n\n\t// Execute command in first tab\n\tscript += ` tell s1 to write text \"${escapeForAppleScript(command1)}\"\\n\\n`\n\n\t// Set tab title for first tab\n\tif (options1.title) {\n\t\tscript += ` set name of s1 to \"${escapeForAppleScript(options1.title)}\"\\n\\n`\n\t}\n\n\t// Subsequent tabs (2, 3, ...)\n\tfor (let i = 1; i < optionsArray.length; i++) {\n\t\tconst options = optionsArray[i]\n\t\tif (!options) {\n\t\t\tthrow new Error(`Terminal option at index ${i} is undefined`)\n\t\t}\n\t\tconst command = await buildCommandSequence(options)\n\t\tconst sessionVar = `s${i + 1}`\n\n\t\t// Create tab\n\t\tscript += ' tell newWindow\\n'\n\t\tscript += ` set newTab${i} to (create tab with default profile)\\n`\n\t\tscript += ' end tell\\n'\n\t\tscript += ` set ${sessionVar} to current session of newTab${i}\\n\\n`\n\n\t\t// Set background color\n\t\tif (options.backgroundColor) {\n\t\t\tconst { r, g, b } = options.backgroundColor\n\t\t\tscript += ` set background color of ${sessionVar} to {${Math.round(r * 257)}, ${Math.round(g * 257)}, ${Math.round(b * 257)}}\\n`\n\t\t}\n\n\t\t// Execute command\n\t\tscript += ` tell ${sessionVar} to write text \"${escapeForAppleScript(command)}\"\\n\\n`\n\n\t\t// Set tab title\n\t\tif (options.title) {\n\t\t\tscript += ` set name of ${sessionVar} to \"${escapeForAppleScript(options.title)}\"\\n\\n`\n\t\t}\n\t}\n\n\t// Activate iTerm2\n\tscript += ' activate\\n'\n\tscript += 'end tell'\n\n\treturn script\n}\n\n/**\n * Open multiple terminal windows/tabs (2+) with specified options\n * If iTerm2 is available on macOS, creates single window with multiple tabs\n * Otherwise falls back to multiple separate Terminal.app windows\n */\nexport async function openMultipleTerminalWindows(\n\toptionsArray: TerminalWindowOptions[]\n): Promise<void> {\n\tif (optionsArray.length < 2) {\n\t\tthrow new Error('openMultipleTerminalWindows requires at least 2 terminal options. Use openTerminalWindow for single terminal.')\n\t}\n\n\tconst platform = detectPlatform()\n\n\tif (platform !== 'darwin') {\n\t\tthrow new Error(\n\t\t\t`Terminal window launching not yet supported on ${platform}. ` +\n\t\t\t\t`Currently only macOS is supported.`\n\t\t)\n\t}\n\n\t// Detect if iTerm2 is available\n\tconst hasITerm2 = await detectITerm2()\n\n\tif (hasITerm2) {\n\t\t// Use iTerm2 with multiple tabs in single window\n\t\tconst applescript = await buildITerm2MultiTabScript(optionsArray)\n\n\t\ttry {\n\t\t\tawait execa('osascript', ['-e', applescript])\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to open iTerm2 window: ${error instanceof Error ? error.message : 'Unknown error'}`\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Fall back to multiple Terminal.app windows\n\t\tfor (let i = 0; i < optionsArray.length; i++) {\n\t\t\tconst options = optionsArray[i]\n\t\t\tif (!options) {\n\t\t\t\tthrow new Error(`Terminal option at index ${i} is undefined`)\n\t\t\t}\n\t\t\tawait openTerminalWindow(options)\n\n\t\t\t// Brief pause between terminals (except after last one)\n\t\t\tif (i < optionsArray.length - 1) {\n\t\t\t\t// eslint-disable-next-line no-undef\n\t\t\t\tawait new Promise<void>((resolve) => setTimeout(resolve, 1000))\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Open dual terminal windows/tabs with specified options\n * If iTerm2 is available on macOS, creates single window with two tabs\n * Otherwise falls back to two separate Terminal.app windows\n */\nexport async function openDualTerminalWindow(\n\toptions1: TerminalWindowOptions,\n\toptions2: TerminalWindowOptions\n): Promise<void> {\n\t// Delegate to openMultipleTerminalWindows for consistency\n\tawait openMultipleTerminalWindows([options1, options2])\n}\n"],"mappings":";;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,kBAAkB;AAiBpB,SAAS,iBAA2B;AAC1C,QAAM,WAAW,QAAQ;AACzB,MAAI,aA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