{"repo_name": "BMAD-METHOD", "file_name": "/BMAD-METHOD/tools/installer/lib/module-manager.js", "inference_info": {"prefix_code": "/**\n * Module Manager - Centralized dynamic import management\n * Handles loading and caching of ES modules to reduce memory overhead\n */\n\n", "suffix_code": "\n\n// Singleton instance\nconst moduleManager = new ModuleManager();\n\nmodule.exports = moduleManager;", "middle_code": "class ModuleManager {\n constructor() {\n this._cache = new Map();\n this._loadingPromises = new Map();\n }\n async initializeCommonModules() {\n const modules = await Promise.all([\n this.getModule('chalk'),\n this.getModule('ora'),\n this.getModule('inquirer')\n ]);\n return {\n chalk: modules[0],\n ora: modules[1],\n inquirer: modules[2]\n };\n }\n async getModule(moduleName) {\n if (this._cache.has(moduleName)) {\n return this._cache.get(moduleName);\n }\n if (this._loadingPromises.has(moduleName)) {\n return this._loadingPromises.get(moduleName);\n }\n const loadPromise = this._loadModule(moduleName);\n this._loadingPromises.set(moduleName, loadPromise);\n try {\n const module = await loadPromise;\n this._cache.set(moduleName, module);\n this._loadingPromises.delete(moduleName);\n return module;\n } catch (error) {\n this._loadingPromises.delete(moduleName);\n throw error;\n }\n }\n async _loadModule(moduleName) {\n switch (moduleName) {\n case 'chalk':\n return (await import('chalk')).default;\n case 'ora':\n return (await import('ora')).default;\n case 'inquirer':\n return (await import('inquirer')).default;\n case 'glob':\n return (await import('glob')).glob;\n case 'globSync':\n return (await import('glob')).globSync;\n default:\n throw new Error(`Unknown module: ${moduleName}`);\n }\n }\n clearCache() {\n this._cache.clear();\n this._loadingPromises.clear();\n }\n async getModules(moduleNames) {\n const modules = await Promise.all(\n moduleNames.map(name => this.getModule(name))\n );\n return moduleNames.reduce((acc, name, index) => {\n acc[name] = modules[index];\n return acc;\n }, {});\n }\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/BMAD-METHOD/tools/installer/lib/resource-locator.js", "/**\n * Resource Locator - Centralized file path resolution and caching\n * Reduces duplicate file system operations and memory usage\n */\n\nconst path = require('node:path');\nconst fs = require('fs-extra');\nconst moduleManager = require('./module-manager');\n\nclass ResourceLocator {\n constructor() {\n this._pathCache = new Map();\n this._globCache = new Map();\n this._bmadCorePath = null;\n this._expansionPacksPath = null;\n }\n\n /**\n * Get the base path for bmad-core\n */\n getBmadCorePath() {\n if (!this._bmadCorePath) {\n this._bmadCorePath = path.join(__dirname, '../../../bmad-core');\n }\n return this._bmadCorePath;\n }\n\n /**\n * Get the base path for expansion packs\n */\n getExpansionPacksPath() {\n if (!this._expansionPacksPath) {\n this._expansionPacksPath = path.join(__dirname, '../../../expansion-packs');\n }\n return this._expansionPacksPath;\n }\n\n /**\n * Find all files matching a pattern, with caching\n * @param {string} pattern - Glob pattern\n * @param {Object} options - Glob options\n * @returns {Promise} Array of matched file paths\n */\n async findFiles(pattern, options = {}) {\n const cacheKey = `${pattern}:${JSON.stringify(options)}`;\n \n if (this._globCache.has(cacheKey)) {\n return this._globCache.get(cacheKey);\n }\n\n const { glob } = await moduleManager.getModules(['glob']);\n const files = await glob(pattern, options);\n \n // Cache for 5 minutes\n this._globCache.set(cacheKey, files);\n setTimeout(() => this._globCache.delete(cacheKey), 5 * 60 * 1000);\n \n return files;\n }\n\n /**\n * Get agent path with caching\n * @param {string} agentId - Agent identifier\n * @returns {Promise} Path to agent file or null if not found\n */\n async getAgentPath(agentId) {\n const cacheKey = `agent:${agentId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n // Check in bmad-core\n let agentPath = path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n if (await fs.pathExists(agentPath)) {\n this._pathCache.set(cacheKey, agentPath);\n return agentPath;\n }\n\n // Check in expansion packs\n const expansionPacks = await this.getExpansionPacks();\n for (const pack of expansionPacks) {\n agentPath = path.join(pack.path, 'agents', `${agentId}.md`);\n if (await fs.pathExists(agentPath)) {\n this._pathCache.set(cacheKey, agentPath);\n return agentPath;\n }\n }\n\n return null;\n }\n\n /**\n * Get available agents with metadata\n * @returns {Promise} Array of agent objects\n */\n async getAvailableAgents() {\n const cacheKey = 'all-agents';\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const agents = [];\n const yaml = require('js-yaml');\n const { extractYamlFromAgent } = require('../../lib/yaml-utils');\n\n // Get agents from bmad-core\n const coreAgents = await this.findFiles('agents/*.md', {\n cwd: this.getBmadCorePath()\n });\n\n for (const agentFile of coreAgents) {\n const content = await fs.readFile(\n path.join(this.getBmadCorePath(), agentFile),\n 'utf8'\n );\n const yamlContent = extractYamlFromAgent(content);\n if (yamlContent) {\n try {\n const metadata = yaml.load(yamlContent);\n agents.push({\n id: path.basename(agentFile, '.md'),\n name: metadata.agent_name || path.basename(agentFile, '.md'),\n description: metadata.description || 'No description available',\n source: 'core'\n });\n } catch (e) {\n // Skip invalid agents\n }\n }\n }\n\n // Cache for 10 minutes\n this._pathCache.set(cacheKey, agents);\n setTimeout(() => this._pathCache.delete(cacheKey), 10 * 60 * 1000);\n\n return agents;\n }\n\n /**\n * Get available expansion packs\n * @returns {Promise} Array of expansion pack objects\n */\n async getExpansionPacks() {\n const cacheKey = 'expansion-packs';\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const packs = [];\n const expansionPacksPath = this.getExpansionPacksPath();\n\n if (await fs.pathExists(expansionPacksPath)) {\n const entries = await fs.readdir(expansionPacksPath, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory()) {\n const configPath = path.join(expansionPacksPath, entry.name, 'config.yaml');\n if (await fs.pathExists(configPath)) {\n try {\n const yaml = require('js-yaml');\n const config = yaml.load(await fs.readFile(configPath, 'utf8'));\n packs.push({\n id: entry.name,\n name: config.name || entry.name,\n version: config.version || '1.0.0',\n description: config.description || 'No description available',\n shortTitle: config['short-title'] || config.description || 'No description available',\n author: config.author || 'Unknown',\n path: path.join(expansionPacksPath, entry.name)\n });\n } catch (e) {\n // Skip invalid packs\n }\n }\n }\n }\n }\n\n // Cache for 10 minutes\n this._pathCache.set(cacheKey, packs);\n setTimeout(() => this._pathCache.delete(cacheKey), 10 * 60 * 1000);\n\n return packs;\n }\n\n /**\n * Get team configuration\n * @param {string} teamId - Team identifier\n * @returns {Promise} Team configuration or null\n */\n async getTeamConfig(teamId) {\n const cacheKey = `team:${teamId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const teamPath = path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n \n if (await fs.pathExists(teamPath)) {\n try {\n const yaml = require('js-yaml');\n const content = await fs.readFile(teamPath, 'utf8');\n const config = yaml.load(content);\n this._pathCache.set(cacheKey, config);\n return config;\n } catch (e) {\n return null;\n }\n }\n\n return null;\n }\n\n /**\n * Get resource dependencies for an agent\n * @param {string} agentId - Agent identifier\n * @returns {Promise} Dependencies object\n */\n async getAgentDependencies(agentId) {\n const cacheKey = `deps:${agentId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const agentPath = await this.getAgentPath(agentId);\n if (!agentPath) {\n return { all: [], byType: {} };\n }\n\n const content = await fs.readFile(agentPath, 'utf8');\n const { extractYamlFromAgent } = require('../../lib/yaml-utils');\n const yamlContent = extractYamlFromAgent(content);\n\n if (!yamlContent) {\n return { all: [], byType: {} };\n }\n\n try {\n const yaml = require('js-yaml');\n const metadata = yaml.load(yamlContent);\n const dependencies = metadata.dependencies || {};\n \n // Flatten dependencies\n const allDeps = [];\n const byType = {};\n \n for (const [type, deps] of Object.entries(dependencies)) {\n if (Array.isArray(deps)) {\n byType[type] = deps;\n for (const dep of deps) {\n allDeps.push(`.bmad-core/${type}/${dep}`);\n }\n }\n }\n\n const result = { all: allDeps, byType };\n this._pathCache.set(cacheKey, result);\n return result;\n } catch (e) {\n return { all: [], byType: {} };\n }\n }\n\n /**\n * Clear all caches to free memory\n */\n clearCache() {\n this._pathCache.clear();\n this._globCache.clear();\n }\n\n /**\n * Get IDE configuration\n * @param {string} ideId - IDE identifier\n * @returns {Promise} IDE configuration or null\n */\n async getIdeConfig(ideId) {\n const cacheKey = `ide:${ideId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const idePath = path.join(this.getBmadCorePath(), 'ide-rules', `${ideId}.yaml`);\n \n if (await fs.pathExists(idePath)) {\n try {\n const yaml = require('js-yaml');\n const content = await fs.readFile(idePath, 'utf8');\n const config = yaml.load(content);\n this._pathCache.set(cacheKey, config);\n return config;\n } catch (e) {\n return null;\n }\n }\n\n return null;\n }\n}\n\n// Singleton instance\nconst resourceLocator = new ResourceLocator();\n\nmodule.exports = resourceLocator;"], ["/BMAD-METHOD/tools/installer/lib/ide-base-setup.js", "/**\n * Base IDE Setup - Common functionality for all IDE setups\n * Reduces duplication and provides shared methods\n */\n\nconst path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst fileManager = require(\"./file-manager\");\nconst resourceLocator = require(\"./resource-locator\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\n\nclass BaseIdeSetup {\n constructor() {\n this._agentCache = new Map();\n this._pathCache = new Map();\n }\n\n /**\n * Get all agent IDs with caching\n */\n async getAllAgentIds(installDir) {\n const cacheKey = `all-agents:${installDir}`;\n if (this._agentCache.has(cacheKey)) {\n return this._agentCache.get(cacheKey);\n }\n\n const allAgents = new Set();\n \n // Get core agents\n const coreAgents = await this.getCoreAgentIds(installDir);\n coreAgents.forEach(id => allAgents.add(id));\n \n // Get expansion pack agents\n const expansionPacks = await this.getInstalledExpansionPacks(installDir);\n for (const pack of expansionPacks) {\n const packAgents = await this.getExpansionPackAgents(pack.path);\n packAgents.forEach(id => allAgents.add(id));\n }\n \n const result = Array.from(allAgents);\n this._agentCache.set(cacheKey, result);\n return result;\n }\n\n /**\n * Get core agent IDs\n */\n async getCoreAgentIds(installDir) {\n const coreAgents = [];\n const corePaths = [\n path.join(installDir, \".bmad-core\", \"agents\"),\n path.join(installDir, \"bmad-core\", \"agents\")\n ];\n\n for (const agentsDir of corePaths) {\n if (await fileManager.pathExists(agentsDir)) {\n const files = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n coreAgents.push(...files.map(file => path.basename(file, \".md\")));\n break; // Use first found\n }\n }\n\n return coreAgents;\n }\n\n /**\n * Find agent path with caching\n */\n async findAgentPath(agentId, installDir) {\n const cacheKey = `agent-path:${agentId}:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n // Use resource locator for efficient path finding\n let agentPath = await resourceLocator.getAgentPath(agentId);\n \n if (!agentPath) {\n // Check installation-specific paths\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"common\", \"agents\", `${agentId}.md`)\n ];\n\n for (const testPath of possiblePaths) {\n if (await fileManager.pathExists(testPath)) {\n agentPath = testPath;\n break;\n }\n }\n }\n\n if (agentPath) {\n this._pathCache.set(cacheKey, agentPath);\n }\n return agentPath;\n }\n\n /**\n * Get agent title from metadata\n */\n async getAgentTitle(agentId, installDir) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n if (!agentPath) return agentId;\n\n try {\n const content = await fileManager.readFile(agentPath);\n const yamlContent = extractYamlFromAgent(content);\n if (yamlContent) {\n const metadata = yaml.load(yamlContent);\n return metadata.agent_name || agentId;\n }\n } catch (error) {\n // Fallback to agent ID\n }\n return agentId;\n }\n\n /**\n * Get installed expansion packs\n */\n async getInstalledExpansionPacks(installDir) {\n const cacheKey = `expansion-packs:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const expansionPacks = [];\n \n // Check for dot-prefixed expansion packs\n const dotExpansions = await resourceLocator.findFiles(\".bmad-*\", { cwd: installDir });\n \n for (const dotExpansion of dotExpansions) {\n if (dotExpansion !== \".bmad-core\") {\n const packPath = path.join(installDir, dotExpansion);\n const packName = dotExpansion.substring(1); // remove the dot\n expansionPacks.push({\n name: packName,\n path: packPath\n });\n }\n }\n \n // Check other dot folders that have config.yaml\n const allDotFolders = await resourceLocator.findFiles(\".*\", { cwd: installDir });\n for (const folder of allDotFolders) {\n if (!folder.startsWith(\".bmad-\") && folder !== \".bmad-core\") {\n const packPath = path.join(installDir, folder);\n const configPath = path.join(packPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n expansionPacks.push({\n name: folder.substring(1), // remove the dot\n path: packPath\n });\n }\n }\n }\n\n this._pathCache.set(cacheKey, expansionPacks);\n return expansionPacks;\n }\n\n /**\n * Get expansion pack agents\n */\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n return [];\n }\n \n const agentFiles = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n return agentFiles.map(file => path.basename(file, \".md\"));\n }\n\n /**\n * Create agent rule content (shared logic)\n */\n async createAgentRuleContent(agentId, agentPath, installDir, format = 'mdc') {\n const agentContent = await fileManager.readFile(agentPath);\n const agentTitle = await this.getAgentTitle(agentId, installDir);\n const yamlContent = extractYamlFromAgent(agentContent);\n \n let content = \"\";\n \n if (format === 'mdc') {\n // MDC format for Cursor\n content = \"---\\n\";\n content += \"description: \\n\";\n content += \"globs: []\\n\";\n content += \"alwaysApply: false\\n\";\n content += \"---\\n\\n\";\n content += `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n content += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${agentTitle} agent persona.\\n\\n`;\n content += \"## Agent Activation\\n\\n\";\n content += \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n content += \"```yaml\\n\";\n content += yamlContent || agentContent.replace(/^#.*$/m, \"\").trim();\n content += \"\\n```\\n\\n\";\n content += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n content += `The complete agent definition is available in [${relativePath}](mdc:${relativePath}).\\n\\n`;\n content += \"## Usage\\n\\n\";\n content += `When the user types \\`@${agentId}\\`, activate this ${agentTitle} persona and follow all instructions defined in the YAML configuration above.\\n`;\n } else if (format === 'claude') {\n // Claude Code format\n content = `# /${agentId} Command\\n\\n`;\n content += `When this command is used, adopt the following agent persona:\\n\\n`;\n content += agentContent;\n }\n \n return content;\n }\n\n /**\n * Clear all caches\n */\n clearCache() {\n this._agentCache.clear();\n this._pathCache.clear();\n }\n}\n\nmodule.exports = BaseIdeSetup;"], ["/BMAD-METHOD/tools/installer/lib/installer.js", "const path = require(\"node:path\");\nconst fs = require(\"fs-extra\");\nconst chalk = require(\"chalk\");\nconst ora = require(\"ora\");\nconst inquirer = require(\"inquirer\");\nconst fileManager = require(\"./file-manager\");\nconst configLoader = require(\"./config-loader\");\nconst ideSetup = require(\"./ide-setup\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\nconst resourceLocator = require(\"./resource-locator\");\n\nclass Installer {\n async getCoreVersion() {\n try {\n // Always use package.json version\n const packagePath = path.join(__dirname, '..', '..', '..', 'package.json');\n const packageJson = require(packagePath);\n return packageJson.version;\n } catch (error) {\n console.warn(\"Could not read version from package.json, using 'unknown'\");\n return \"unknown\";\n }\n }\n\n async install(config) {\n const spinner = ora(\"Analyzing installation directory...\").start();\n \n try {\n // Store the original CWD where npx was executed\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n \n // Resolve installation directory relative to where the user ran the command\n let installDir = path.isAbsolute(config.directory) \n ? config.directory \n : path.resolve(originalCwd, config.directory);\n \n if (path.basename(installDir) === '.bmad-core') {\n // If user points directly to .bmad-core, treat its parent as the project root\n installDir = path.dirname(installDir);\n }\n \n // Log resolved path for clarity\n if (!path.isAbsolute(config.directory)) {\n spinner.text = `Resolving \"${config.directory}\" to: ${installDir}`;\n }\n\n // Check if directory exists and handle non-existent directories\n if (!(await fileManager.pathExists(installDir))) {\n spinner.stop();\n console.log(`\\nThe directory ${installDir} does not exist.`);\n \n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n {\n name: 'Create the directory and continue',\n value: 'create'\n },\n {\n name: 'Choose a different directory',\n value: 'change'\n },\n {\n name: 'Cancel installation',\n value: 'cancel'\n }\n ]\n }\n ]);\n\n if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n } else if (action === 'change') {\n const { newDirectory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'newDirectory',\n message: 'Enter the new directory path:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid directory path';\n }\n return true;\n }\n }\n ]);\n // Preserve the original CWD for the recursive call\n config.directory = newDirectory;\n return await this.install(config); // Recursive call with new directory\n } else if (action === 'create') {\n try {\n await fileManager.ensureDirectory(installDir);\n console.log(`āœ“ Created directory: ${installDir}`);\n } catch (error) {\n console.error(`Failed to create directory: ${error.message}`);\n console.error('You may need to check permissions or use a different path.');\n process.exit(1);\n }\n }\n \n spinner.start(\"Analyzing installation directory...\");\n }\n\n // If this is an update request from early detection, handle it directly\n if (config.installType === 'update') {\n const state = await this.detectInstallationState(installDir);\n if (state.type === 'v4_existing') {\n return await this.performUpdate(config, installDir, state.manifest, spinner);\n } else {\n spinner.fail('No existing v4 installation found to update');\n throw new Error('No existing v4 installation found');\n }\n }\n\n // Detect current state\n const state = await this.detectInstallationState(installDir);\n\n // Handle different states\n switch (state.type) {\n case \"clean\":\n return await this.performFreshInstall(config, installDir, spinner);\n\n case \"v4_existing\":\n return await this.handleExistingV4Installation(\n config,\n installDir,\n state,\n spinner\n );\n\n case \"v3_existing\":\n return await this.handleV3Installation(\n config,\n installDir,\n state,\n spinner\n );\n\n case \"unknown_existing\":\n return await this.handleUnknownInstallation(\n config,\n installDir,\n state,\n spinner\n );\n }\n } catch (error) {\n // Check if modules were initialized\n if (spinner) {\n spinner.fail(\"Installation failed\");\n } else {\n console.error(\"Installation failed:\", error.message);\n }\n throw error;\n }\n }\n\n async detectInstallationState(installDir) {\n const state = {\n type: \"clean\",\n hasV4Manifest: false,\n hasV3Structure: false,\n hasBmadCore: false,\n hasOtherFiles: false,\n manifest: null,\n expansionPacks: {},\n };\n\n // Check if directory exists\n if (!(await fileManager.pathExists(installDir))) {\n return state; // clean install\n }\n\n // Check for V4 installation (has .bmad-core with manifest)\n const bmadCorePath = path.join(installDir, \".bmad-core\");\n const manifestPath = path.join(bmadCorePath, \"install-manifest.yaml\");\n\n if (await fileManager.pathExists(manifestPath)) {\n state.type = \"v4_existing\";\n state.hasV4Manifest = true;\n state.hasBmadCore = true;\n state.manifest = await fileManager.readManifest(installDir);\n return state;\n }\n\n // Check for V3 installation (has bmad-agent directory)\n const bmadAgentPath = path.join(installDir, \"bmad-agent\");\n if (await fileManager.pathExists(bmadAgentPath)) {\n state.type = \"v3_existing\";\n state.hasV3Structure = true;\n return state;\n }\n\n // Check for .bmad-core without manifest (broken V4 or manual copy)\n if (await fileManager.pathExists(bmadCorePath)) {\n state.type = \"unknown_existing\";\n state.hasBmadCore = true;\n return state;\n }\n\n // Check if directory has other files\n const files = await resourceLocator.findFiles(\"**/*\", {\n cwd: installDir,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n\n if (files.length > 0) {\n // Directory has other files, but no BMad installation.\n // Treat as clean install but record that it isn't empty.\n state.hasOtherFiles = true;\n }\n\n // Check for expansion packs (folders starting with .)\n const expansionPacks = await this.detectExpansionPacks(installDir);\n state.expansionPacks = expansionPacks;\n\n return state; // clean install\n }\n\n async performFreshInstall(config, installDir, spinner, options = {}) {\n spinner.text = \"Installing BMad Method...\";\n\n let files = [];\n\n if (config.installType === \"full\") {\n // Full installation - copy entire .bmad-core folder as a subdirectory\n spinner.text = \"Copying complete .bmad-core folder...\";\n const sourceDir = resourceLocator.getBmadCorePath();\n const bmadCoreDestDir = path.join(installDir, \".bmad-core\");\n await fileManager.copyDirectoryWithRootReplacement(sourceDir, bmadCoreDestDir, \".bmad-core\");\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n\n // Get list of all files for manifest\n const foundFiles = await resourceLocator.findFiles(\"**/*\", {\n cwd: bmadCoreDestDir,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n files = foundFiles.map((file) => path.join(\".bmad-core\", file));\n } else if (config.installType === \"single-agent\") {\n // Single agent installation\n spinner.text = `Installing ${config.agent} agent...`;\n\n // Copy agent file with {root} replacement\n const agentPath = configLoader.getAgentPath(config.agent);\n const destAgentPath = path.join(\n installDir,\n \".bmad-core\",\n \"agents\",\n `${config.agent}.md`\n );\n await fileManager.copyFileWithRootReplacement(agentPath, destAgentPath, \".bmad-core\");\n files.push(`.bmad-core/agents/${config.agent}.md`);\n\n // Copy dependencies\n const { all: dependencies } = await resourceLocator.getAgentDependencies(\n config.agent\n );\n const sourceBase = resourceLocator.getBmadCorePath();\n\n for (const dep of dependencies) {\n spinner.text = `Copying dependency: ${dep}`;\n\n if (dep.includes(\"*\")) {\n // Handle glob patterns with {root} replacement\n const copiedFiles = await fileManager.copyGlobPattern(\n dep.replace(\".bmad-core/\", \"\"),\n sourceBase,\n path.join(installDir, \".bmad-core\"),\n \".bmad-core\"\n );\n files.push(...copiedFiles.map(f => `.bmad-core/${f}`));\n } else {\n // Handle single files with {root} replacement if needed\n const sourcePath = path.join(\n sourceBase,\n dep.replace(\".bmad-core/\", \"\")\n );\n const destPath = path.join(\n installDir,\n dep\n );\n\n const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, \".bmad-core\");\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n files.push(dep);\n }\n }\n }\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n const commonFiles = await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n files.push(...commonFiles);\n } else if (config.installType === \"team\") {\n // Team installation\n spinner.text = `Installing ${config.team} team...`;\n \n // Get team dependencies\n const teamDependencies = await configLoader.getTeamDependencies(config.team);\n const sourceBase = resourceLocator.getBmadCorePath();\n \n // Install all team dependencies\n for (const dep of teamDependencies) {\n spinner.text = `Copying team dependency: ${dep}`;\n \n if (dep.includes(\"*\")) {\n // Handle glob patterns with {root} replacement\n const copiedFiles = await fileManager.copyGlobPattern(\n dep.replace(\".bmad-core/\", \"\"),\n sourceBase,\n path.join(installDir, \".bmad-core\"),\n \".bmad-core\"\n );\n files.push(...copiedFiles.map(f => `.bmad-core/${f}`));\n } else {\n // Handle single files with {root} replacement if needed\n const sourcePath = path.join(sourceBase, dep.replace(\".bmad-core/\", \"\"));\n const destPath = path.join(installDir, dep);\n \n const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, \".bmad-core\");\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n files.push(dep);\n }\n }\n }\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n const commonFiles = await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n files.push(...commonFiles);\n } else if (config.installType === \"expansion-only\") {\n // Expansion-only installation - DO NOT create .bmad-core\n // Only install expansion packs\n spinner.text = \"Installing expansion packs only...\";\n }\n\n // Install expansion packs if requested\n const expansionFiles = await this.installExpansionPacks(installDir, config.expansionPacks, spinner, config);\n files.push(...expansionFiles);\n\n // Install web bundles if requested\n if (config.includeWebBundles && config.webBundlesDirectory) {\n spinner.text = \"Installing web bundles...\";\n // Resolve web bundles directory using the same logic as the main installation directory\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n let resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory) \n ? config.webBundlesDirectory \n : path.resolve(originalCwd, config.webBundlesDirectory);\n await this.installWebBundles(resolvedWebBundlesDir, config, spinner);\n }\n\n // Set up IDE integration if requested\n const ides = config.ides || (config.ide ? [config.ide] : []);\n if (ides.length > 0) {\n for (const ide of ides) {\n spinner.text = `Setting up ${ide} integration...`;\n const preConfiguredSettings = ide === 'github-copilot' ? config.githubCopilotConfig : null;\n await ideSetup.setup(ide, installDir, config.agent, spinner, preConfiguredSettings);\n }\n }\n\n // Modify core-config.yaml if sharding preferences were provided\n if (config.installType !== \"expansion-only\" && (config.prdSharded !== undefined || config.architectureSharded !== undefined)) {\n spinner.text = \"Configuring document sharding settings...\";\n await fileManager.modifyCoreConfig(installDir, config);\n }\n\n // Create manifest (skip for expansion-only installations)\n if (config.installType !== \"expansion-only\") {\n spinner.text = \"Creating installation manifest...\";\n await fileManager.createManifest(installDir, config, files);\n }\n\n spinner.succeed(\"Installation complete!\");\n this.showSuccessMessage(config, installDir, options);\n }\n\n async handleExistingV4Installation(config, installDir, state, spinner) {\n spinner.stop();\n\n const currentVersion = state.manifest.version;\n const newVersion = await this.getCoreVersion();\n const versionCompare = this.compareVersions(currentVersion, newVersion);\n\n console.log(chalk.yellow(\"\\nšŸ” Found existing BMad v4 installation\"));\n console.log(` Directory: ${installDir}`);\n console.log(` Current version: ${currentVersion}`);\n console.log(` Available version: ${newVersion}`);\n console.log(\n ` Installed: ${new Date(\n state.manifest.installed_at\n ).toLocaleDateString()}`\n );\n\n // Check file integrity\n spinner.start(\"Checking installation integrity...\");\n const integrity = await fileManager.checkFileIntegrity(installDir, state.manifest);\n spinner.stop();\n \n const hasMissingFiles = integrity.missing.length > 0;\n const hasModifiedFiles = integrity.modified.length > 0;\n const hasIntegrityIssues = hasMissingFiles || hasModifiedFiles;\n \n if (hasIntegrityIssues) {\n console.log(chalk.red(\"\\nāš ļø Installation issues detected:\"));\n if (hasMissingFiles) {\n console.log(chalk.red(` Missing files: ${integrity.missing.length}`));\n if (integrity.missing.length <= 5) {\n integrity.missing.forEach(file => console.log(chalk.dim(` - ${file}`)));\n }\n }\n if (hasModifiedFiles) {\n console.log(chalk.yellow(` Modified files: ${integrity.modified.length}`));\n if (integrity.modified.length <= 5) {\n integrity.modified.forEach(file => console.log(chalk.dim(` - ${file}`)));\n }\n }\n }\n\n // Show existing expansion packs\n if (Object.keys(state.expansionPacks).length > 0) {\n console.log(chalk.cyan(\"\\nšŸ“¦ Installed expansion packs:\"));\n for (const [packId, packInfo] of Object.entries(state.expansionPacks)) {\n if (packInfo.hasManifest && packInfo.manifest) {\n console.log(` - ${packId} (v${packInfo.manifest.version || 'unknown'})`);\n } else {\n console.log(` - ${packId} (no manifest)`);\n }\n }\n }\n\n let choices = [];\n \n if (versionCompare < 0) {\n console.log(chalk.cyan(\"\\nā¬†ļø Upgrade available for BMad core\"));\n choices.push({ name: `Upgrade BMad core (v${currentVersion} → v${newVersion})`, value: \"upgrade\" });\n } else if (versionCompare === 0) {\n if (hasIntegrityIssues) {\n // Offer repair option when files are missing or modified\n choices.push({ \n name: \"Repair installation (restore missing/modified files)\", \n value: \"repair\" \n });\n }\n console.log(chalk.yellow(\"\\nāš ļø Same version already installed\"));\n choices.push({ name: `Force reinstall BMad core (v${currentVersion} - reinstall)`, value: \"reinstall\" });\n } else {\n console.log(chalk.yellow(\"\\nā¬‡ļø Installed version is newer than available\"));\n choices.push({ name: `Downgrade BMad core (v${currentVersion} → v${newVersion})`, value: \"reinstall\" });\n }\n \n choices.push(\n { name: \"Add/update expansion packs only\", value: \"expansions\" },\n { name: \"Cancel\", value: \"cancel\" }\n );\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: choices,\n },\n ]);\n\n switch (action) {\n case \"upgrade\":\n return await this.performUpdate(config, installDir, state.manifest, spinner);\n case \"repair\":\n // For repair, restore missing/modified files while backing up modified ones\n return await this.performRepair(config, installDir, state.manifest, integrity, spinner);\n case \"reinstall\":\n // For reinstall, don't check for modifications - just overwrite\n return await this.performReinstall(config, installDir, spinner);\n case \"expansions\":\n // Ask which expansion packs to install\n const availableExpansionPacks = await resourceLocator.getExpansionPacks();\n \n if (availableExpansionPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs available.\"));\n return;\n }\n \n const { selectedPacks } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedPacks',\n message: 'Select expansion packs to install/update:',\n choices: availableExpansionPacks.map(pack => ({\n name: `${pack.name} (v${pack.version}) .${pack.id}`,\n value: pack.id,\n checked: state.expansionPacks[pack.id] !== undefined\n }))\n }\n ]);\n \n if (selectedPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs selected.\"));\n return;\n }\n \n spinner.start(\"Installing expansion packs...\");\n const expansionFiles = await this.installExpansionPacks(installDir, selectedPacks, spinner, { ides: config.ides || [] });\n spinner.succeed(\"Expansion packs installed successfully!\");\n \n console.log(chalk.green(\"\\nāœ“ Installation complete!\"));\n console.log(chalk.green(`āœ“ Expansion packs installed/updated:`));\n for (const packId of selectedPacks) {\n console.log(chalk.green(` - ${packId} → .${packId}/`));\n }\n return;\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async handleV3Installation(config, installDir, state, spinner) {\n spinner.stop();\n\n console.log(\n chalk.yellow(\"\\nšŸ” Found BMad v3 installation (bmad-agent/ directory)\")\n );\n console.log(` Directory: ${installDir}`);\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: [\n { name: \"Upgrade from v3 to v4 (recommended)\", value: \"upgrade\" },\n { name: \"Install v4 alongside v3\", value: \"alongside\" },\n { name: \"Cancel\", value: \"cancel\" },\n ],\n },\n ]);\n\n switch (action) {\n case \"upgrade\": {\n console.log(chalk.cyan(\"\\nšŸ“¦ Starting v3 to v4 upgrade process...\"));\n const V3ToV4Upgrader = require(\"../../upgraders/v3-to-v4-upgrader\");\n const upgrader = new V3ToV4Upgrader();\n return await upgrader.upgrade({ \n projectPath: installDir,\n ides: config.ides || [] // Pass IDE selections from initial config\n });\n }\n case \"alongside\":\n return await this.performFreshInstall(config, installDir, spinner);\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async handleUnknownInstallation(config, installDir, state, spinner) {\n spinner.stop();\n\n console.log(chalk.yellow(\"\\nāš ļø Directory contains existing files\"));\n console.log(` Directory: ${installDir}`);\n\n if (state.hasBmadCore) {\n console.log(\" Found: .bmad-core directory (but no manifest)\");\n }\n if (state.hasOtherFiles) {\n console.log(\" Found: Other files in directory\");\n }\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: [\n { name: \"Install anyway (may overwrite files)\", value: \"force\" },\n { name: \"Choose different directory\", value: \"different\" },\n { name: \"Cancel\", value: \"cancel\" },\n ],\n },\n ]);\n\n switch (action) {\n case \"force\":\n return await this.performFreshInstall(config, installDir, spinner);\n case \"different\": {\n const { newDir } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"newDir\",\n message: \"Enter new installation directory:\",\n default: path.join(path.dirname(installDir), \"bmad-project\"),\n },\n ]);\n config.directory = newDir;\n return await this.install(config);\n }\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async performUpdate(newConfig, installDir, manifest, spinner) {\n spinner.start(\"Checking for updates...\");\n\n try {\n // Get current and new versions\n const currentVersion = manifest.version;\n const newVersion = await this.getCoreVersion();\n const versionCompare = this.compareVersions(currentVersion, newVersion);\n \n // Only check for modified files if it's an actual version upgrade\n let modifiedFiles = [];\n if (versionCompare !== 0) {\n spinner.text = \"Checking for modified files...\";\n modifiedFiles = await fileManager.checkModifiedFiles(\n installDir,\n manifest\n );\n }\n\n if (modifiedFiles.length > 0) {\n spinner.warn(\"Found modified files\");\n console.log(chalk.yellow(\"\\nThe following files have been modified:\"));\n for (const file of modifiedFiles) {\n console.log(` - ${file}`);\n }\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"How would you like to proceed?\",\n choices: [\n { name: \"Backup and overwrite modified files\", value: \"backup\" },\n { name: \"Skip modified files\", value: \"skip\" },\n { name: \"Cancel update\", value: \"cancel\" },\n ],\n },\n ]);\n\n if (action === \"cancel\") {\n console.log(\"Update cancelled.\");\n return;\n }\n\n if (action === \"backup\") {\n spinner.start(\"Backing up modified files...\");\n for (const file of modifiedFiles) {\n const filePath = path.join(installDir, file);\n const backupPath = await fileManager.backupFile(filePath);\n console.log(\n chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`)\n );\n }\n }\n }\n\n // Perform update by re-running installation\n spinner.text = versionCompare === 0 ? \"Reinstalling files...\" : \"Updating files...\";\n const config = {\n installType: manifest.install_type,\n agent: manifest.agent,\n directory: installDir,\n ides: newConfig?.ides || manifest.ides_setup || [],\n };\n\n await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n } catch (error) {\n spinner.fail(\"Update failed\");\n throw error;\n }\n }\n\n async performRepair(config, installDir, manifest, integrity, spinner) {\n spinner.start(\"Preparing to repair installation...\");\n\n try {\n // Back up modified files\n if (integrity.modified.length > 0) {\n spinner.text = \"Backing up modified files...\";\n for (const file of integrity.modified) {\n const filePath = path.join(installDir, file);\n if (await fileManager.pathExists(filePath)) {\n const backupPath = await fileManager.backupFile(filePath);\n console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));\n }\n }\n }\n\n // Restore missing and modified files\n spinner.text = \"Restoring files...\";\n const sourceBase = resourceLocator.getBmadCorePath();\n const filesToRestore = [...integrity.missing, ...integrity.modified];\n \n for (const file of filesToRestore) {\n // Skip the manifest file itself\n if (file.endsWith('install-manifest.yaml')) continue;\n \n const relativePath = file.replace('.bmad-core/', '');\n const destPath = path.join(installDir, file);\n \n // Check if this is a common/ file that needs special processing\n const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));\n const commonSourcePath = path.join(commonBase, 'common', relativePath);\n \n if (await fileManager.pathExists(commonSourcePath)) {\n // This is a common/ file - needs template processing\n const fs = require('fs').promises;\n const content = await fs.readFile(commonSourcePath, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, '.bmad-core');\n await fileManager.ensureDirectory(path.dirname(destPath));\n await fs.writeFile(destPath, updatedContent, 'utf8');\n spinner.text = `Restored: ${file}`;\n } else {\n // Regular file from bmad-core\n const sourcePath = path.join(sourceBase, relativePath);\n if (await fileManager.pathExists(sourcePath)) {\n await fileManager.copyFile(sourcePath, destPath);\n spinner.text = `Restored: ${file}`;\n \n // If this is a .yaml file, check for and remove corresponding .yml file\n if (file.endsWith('.yaml')) {\n const ymlFile = file.replace(/\\.yaml$/, '.yml');\n const ymlPath = path.join(installDir, ymlFile);\n if (await fileManager.pathExists(ymlPath)) {\n const fs = require('fs').promises;\n await fs.unlink(ymlPath);\n console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${file})`));\n }\n }\n } else {\n console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));\n }\n }\n }\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n \n spinner.succeed(\"Repair completed successfully!\");\n \n // Show summary\n console.log(chalk.green(\"\\nāœ“ Installation repaired!\"));\n if (integrity.missing.length > 0) {\n console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));\n }\n if (integrity.modified.length > 0) {\n console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));\n }\n \n // Warning for Cursor custom modes if agents were repaired\n const ides = manifest.ides_setup || [];\n if (ides.includes('cursor')) {\n console.log(chalk.yellow.bold(\"\\nāš ļø IMPORTANT: Cursor Custom Modes Update Required\"));\n console.log(chalk.yellow(\"Since agent files have been repaired, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs.\"));\n }\n \n } catch (error) {\n spinner.fail(\"Repair failed\");\n throw error;\n }\n }\n\n async performReinstall(config, installDir, spinner) {\n spinner.start(\"Preparing to reinstall BMad Method...\");\n\n // Remove existing .bmad-core\n const bmadCorePath = path.join(installDir, \".bmad-core\");\n if (await fileManager.pathExists(bmadCorePath)) {\n spinner.text = \"Removing existing installation...\";\n await fileManager.removeDirectory(bmadCorePath);\n }\n \n spinner.text = \"Installing fresh copy...\";\n const result = await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n \n return result;\n }\n\n showSuccessMessage(config, installDir, options = {}) {\n console.log(chalk.green(\"\\nāœ“ BMad Method installed successfully!\\n\"));\n\n const ides = config.ides || (config.ide ? [config.ide] : []);\n if (ides.length > 0) {\n for (const ide of ides) {\n const ideConfig = configLoader.getIdeConfiguration(ide);\n if (ideConfig?.instructions) {\n console.log(\n chalk.bold(`To use BMad agents in ${ideConfig.name}:`)\n );\n console.log(ideConfig.instructions);\n }\n }\n } else {\n console.log(chalk.yellow(\"No IDE configuration was set up.\"));\n console.log(\n \"You can manually configure your IDE using the agent files in:\",\n installDir\n );\n }\n\n // Information about installation components\n console.log(chalk.bold(\"\\nšŸŽÆ Installation Summary:\"));\n if (config.installType !== \"expansion-only\") {\n console.log(chalk.green(\"āœ“ .bmad-core framework installed with all agents and workflows\"));\n }\n \n if (config.expansionPacks && config.expansionPacks.length > 0) {\n console.log(chalk.green(`āœ“ Expansion packs installed:`));\n for (const packId of config.expansionPacks) {\n console.log(chalk.green(` - ${packId} → .${packId}/`));\n }\n }\n \n if (config.includeWebBundles && config.webBundlesDirectory) {\n const bundleInfo = this.getWebBundleInfo(config);\n // Resolve the web bundles directory for display\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n const resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory) \n ? config.webBundlesDirectory \n : path.resolve(originalCwd, config.webBundlesDirectory);\n console.log(chalk.green(`āœ“ Web bundles (${bundleInfo}) installed to: ${resolvedWebBundlesDir}`));\n }\n \n if (ides.length > 0) {\n const ideNames = ides.map(ide => {\n const ideConfig = configLoader.getIdeConfiguration(ide);\n return ideConfig?.name || ide;\n }).join(\", \");\n console.log(chalk.green(`āœ“ IDE rules and configurations set up for: ${ideNames}`));\n }\n\n // Information about web bundles\n if (!config.includeWebBundles) {\n console.log(chalk.bold(\"\\nšŸ“¦ Web Bundles Available:\"));\n console.log(\"Pre-built web bundles are available and can be added later:\");\n console.log(chalk.cyan(\" Run the installer again to add them to your project\"));\n console.log(\"These bundles work independently and can be shared, moved, or used\");\n console.log(\"in other projects as standalone files.\");\n }\n\n if (config.installType === \"single-agent\") {\n console.log(\n chalk.dim(\n \"\\nNeed other agents? Run: npx bmad-method install --agent=\"\n )\n );\n console.log(\n chalk.dim(\"Need everything? Run: npx bmad-method install --full\")\n );\n }\n\n // Warning for Cursor custom modes if agents were updated\n if (options.isUpdate && ides.includes('cursor')) {\n console.log(chalk.yellow.bold(\"\\nāš ļø IMPORTANT: Cursor Custom Modes Update Required\"));\n console.log(chalk.yellow(\"Since agents have been updated, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs.\"));\n }\n\n // Important notice to read the user guide\n console.log(chalk.red.bold(\"\\nšŸ“– IMPORTANT: Please read the user guide installed at .bmad-core/user-guide.md\"));\n console.log(chalk.red(\"This guide contains essential information about the BMad workflow and how to use the agents effectively.\"));\n }\n\n // Legacy method for backward compatibility\n async update() {\n console.log(chalk.yellow('The \"update\" command is deprecated.'));\n console.log(\n 'Please use \"install\" instead - it will detect and offer to update existing installations.'\n );\n\n const installDir = await this.findInstallation();\n if (installDir) {\n const config = {\n installType: \"full\",\n directory: path.dirname(installDir),\n ide: null,\n };\n return await this.install(config);\n }\n console.log(chalk.red(\"No BMad installation found.\"));\n }\n\n async listAgents() {\n const agents = await resourceLocator.getAvailableAgents();\n\n console.log(chalk.bold(\"\\nAvailable BMad Agents:\\n\"));\n\n for (const agent of agents) {\n console.log(chalk.cyan(` ${agent.id.padEnd(20)}`), agent.description);\n }\n\n console.log(\n chalk.dim(\"\\nInstall with: npx bmad-method install --agent=\\n\")\n );\n }\n\n async listExpansionPacks() {\n const expansionPacks = await resourceLocator.getExpansionPacks();\n\n console.log(chalk.bold(\"\\nAvailable BMad Expansion Packs:\\n\"));\n\n if (expansionPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs found.\"));\n return;\n }\n\n for (const pack of expansionPacks) {\n console.log(chalk.cyan(` ${pack.id.padEnd(20)}`), \n `${pack.name} v${pack.version}`);\n console.log(chalk.dim(` ${' '.repeat(22)}${pack.description}`));\n if (pack.author && pack.author !== 'Unknown') {\n console.log(chalk.dim(` ${' '.repeat(22)}by ${pack.author}`));\n }\n console.log();\n }\n\n console.log(\n chalk.dim(\"Install with: npx bmad-method install --full --expansion-packs \\n\")\n );\n }\n\n async showStatus() {\n const installDir = await this.findInstallation();\n\n if (!installDir) {\n console.log(\n chalk.yellow(\"No BMad installation found in current directory tree\")\n );\n return;\n }\n\n const manifest = await fileManager.readManifest(installDir);\n\n if (!manifest) {\n console.log(chalk.red(\"Invalid installation - manifest not found\"));\n return;\n }\n\n console.log(chalk.bold(\"\\nBMad Installation Status:\\n\"));\n console.log(` Directory: ${installDir}`);\n console.log(` Version: ${manifest.version}`);\n console.log(\n ` Installed: ${new Date(\n manifest.installed_at\n ).toLocaleDateString()}`\n );\n console.log(` Type: ${manifest.install_type}`);\n\n if (manifest.agent) {\n console.log(` Agent: ${manifest.agent}`);\n }\n\n if (manifest.ides_setup && manifest.ides_setup.length > 0) {\n console.log(` IDE Setup: ${manifest.ides_setup.join(', ')}`);\n }\n\n console.log(` Total Files: ${manifest.files.length}`);\n\n // Check for modifications\n const modifiedFiles = await fileManager.checkModifiedFiles(\n installDir,\n manifest\n );\n if (modifiedFiles.length > 0) {\n console.log(chalk.yellow(` Modified Files: ${modifiedFiles.length}`));\n }\n\n console.log(\"\");\n }\n\n async getAvailableAgents() {\n return resourceLocator.getAvailableAgents();\n }\n\n async getAvailableExpansionPacks() {\n return resourceLocator.getExpansionPacks();\n }\n\n async getAvailableTeams() {\n return configLoader.getAvailableTeams();\n }\n\n async installExpansionPacks(installDir, selectedPacks, spinner, config = {}) {\n if (!selectedPacks || selectedPacks.length === 0) {\n return [];\n }\n\n const installedFiles = [];\n\n for (const packId of selectedPacks) {\n spinner.text = `Installing expansion pack: ${packId}...`;\n \n try {\n const expansionPacks = await resourceLocator.getExpansionPacks();\n const pack = expansionPacks.find(p => p.id === packId);\n \n if (!pack) {\n console.warn(`Expansion pack ${packId} not found, skipping...`);\n continue;\n }\n \n // Check if expansion pack already exists\n let expansionDotFolder = path.join(installDir, `.${packId}`);\n const existingManifestPath = path.join(expansionDotFolder, 'install-manifest.yaml');\n \n if (await fileManager.pathExists(existingManifestPath)) {\n spinner.stop();\n const existingManifest = await fileManager.readExpansionPackManifest(installDir, packId);\n \n console.log(chalk.yellow(`\\nšŸ” Found existing ${pack.name} installation`));\n console.log(` Current version: ${existingManifest.version || 'unknown'}`);\n console.log(` New version: ${pack.version}`);\n \n // Check integrity of existing expansion pack\n const packIntegrity = await fileManager.checkFileIntegrity(installDir, existingManifest);\n const hasPackIntegrityIssues = packIntegrity.missing.length > 0 || packIntegrity.modified.length > 0;\n \n if (hasPackIntegrityIssues) {\n console.log(chalk.red(\" āš ļø Installation issues detected:\"));\n if (packIntegrity.missing.length > 0) {\n console.log(chalk.red(` Missing files: ${packIntegrity.missing.length}`));\n }\n if (packIntegrity.modified.length > 0) {\n console.log(chalk.yellow(` Modified files: ${packIntegrity.modified.length}`));\n }\n }\n \n const versionCompare = this.compareVersions(existingManifest.version || '0.0.0', pack.version);\n \n if (versionCompare === 0) {\n console.log(chalk.yellow(' āš ļø Same version already installed'));\n \n const choices = [];\n if (hasPackIntegrityIssues) {\n choices.push({ name: 'Repair (restore missing/modified files)', value: 'repair' });\n }\n choices.push(\n { name: 'Force reinstall (overwrite)', value: 'overwrite' },\n { name: 'Skip this expansion pack', value: 'skip' },\n { name: 'Cancel installation', value: 'cancel' }\n );\n \n const { action } = await inquirer.prompt([{\n type: 'list',\n name: 'action',\n message: `${pack.name} v${pack.version} is already installed. What would you like to do?`,\n choices: choices\n }]);\n \n if (action === 'skip') {\n spinner.start();\n continue;\n } else if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n } else if (action === 'repair') {\n // Repair the expansion pack\n await this.repairExpansionPack(installDir, packId, pack, packIntegrity, spinner);\n continue;\n }\n } else if (versionCompare < 0) {\n console.log(chalk.cyan(' ā¬†ļø Upgrade available'));\n \n const { proceed } = await inquirer.prompt([{\n type: 'confirm',\n name: 'proceed',\n message: `Upgrade ${pack.name} from v${existingManifest.version} to v${pack.version}?`,\n default: true\n }]);\n \n if (!proceed) {\n spinner.start();\n continue;\n }\n } else {\n console.log(chalk.yellow(' ā¬‡ļø Installed version is newer than available version'));\n \n const { action } = await inquirer.prompt([{\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n { name: 'Keep current version', value: 'skip' },\n { name: 'Downgrade to available version', value: 'downgrade' },\n { name: 'Cancel installation', value: 'cancel' }\n ]\n }]);\n \n if (action === 'skip') {\n spinner.start();\n continue;\n } else if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n }\n }\n \n // If we get here, we're proceeding with installation\n spinner.start(`Removing old ${pack.name} installation...`);\n await fileManager.removeDirectory(expansionDotFolder);\n }\n\n const expansionPackDir = pack.path;\n \n // Ensure dedicated dot folder exists for this expansion pack\n expansionDotFolder = path.join(installDir, `.${packId}`);\n await fileManager.ensureDirectory(expansionDotFolder);\n \n // Define the folders to copy from expansion packs\n const foldersToSync = [\n 'agents',\n 'agent-teams',\n 'templates',\n 'tasks',\n 'checklists',\n 'workflows',\n 'data',\n 'utils',\n 'schemas'\n ];\n\n // Copy each folder if it exists\n for (const folder of foldersToSync) {\n const sourceFolder = path.join(expansionPackDir, folder);\n \n // Check if folder exists in expansion pack\n if (await fileManager.pathExists(sourceFolder)) {\n // Get all files in this folder\n const files = await resourceLocator.findFiles('**/*', {\n cwd: sourceFolder,\n nodir: true\n });\n\n // Copy each file to the expansion pack's dot folder with {root} replacement\n for (const file of files) {\n const sourcePath = path.join(sourceFolder, file);\n const destPath = path.join(expansionDotFolder, folder, file);\n \n const needsRootReplacement = file.endsWith('.md') || file.endsWith('.yaml') || file.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, `.${packId}`);\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n \n if (success) {\n installedFiles.push(path.join(`.${packId}`, folder, file));\n }\n }\n }\n }\n\n // Copy config.yaml with {root} replacement\n const configPath = path.join(expansionPackDir, 'config.yaml');\n if (await fileManager.pathExists(configPath)) {\n const configDestPath = path.join(expansionDotFolder, 'config.yaml');\n if (await fileManager.copyFileWithRootReplacement(configPath, configDestPath, `.${packId}`)) {\n installedFiles.push(path.join(`.${packId}`, 'config.yaml'));\n }\n }\n \n // Copy README if it exists with {root} replacement\n const readmePath = path.join(expansionPackDir, 'README.md');\n if (await fileManager.pathExists(readmePath)) {\n const readmeDestPath = path.join(expansionDotFolder, 'README.md');\n if (await fileManager.copyFileWithRootReplacement(readmePath, readmeDestPath, `.${packId}`)) {\n installedFiles.push(path.join(`.${packId}`, 'README.md'));\n }\n }\n\n // Copy common/ items to expansion pack folder\n spinner.text = `Copying common utilities to ${packId}...`;\n await this.copyCommonItems(installDir, `.${packId}`, spinner);\n \n // Check and resolve core dependencies\n await this.resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner);\n \n // Check and resolve core agents referenced by teams\n await this.resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner);\n\n // Create manifest for this expansion pack\n spinner.text = `Creating manifest for ${packId}...`;\n const expansionConfig = {\n installType: 'expansion-pack',\n expansionPackId: packId,\n expansionPackName: pack.name,\n expansionPackVersion: pack.version,\n ides: config.ides || [] // Use ides_setup instead of ide_setup\n };\n \n // Get all files installed in this expansion pack\n const foundFiles = await resourceLocator.findFiles('**/*', {\n cwd: expansionDotFolder,\n nodir: true\n });\n const expansionPackFiles = foundFiles.map(f => path.join(`.${packId}`, f));\n \n await fileManager.createExpansionPackManifest(installDir, packId, expansionConfig, expansionPackFiles);\n\n console.log(chalk.green(`āœ“ Installed expansion pack: ${pack.name} to ${`.${packId}`}`));\n } catch (error) {\n console.error(`Failed to install expansion pack ${packId}: ${error.message}`);\n console.error(`Stack trace: ${error.stack}`);\n }\n }\n\n return installedFiles;\n }\n\n async resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner) {\n const yaml = require('js-yaml');\n const fs = require('fs').promises;\n \n // Find all agent files in the expansion pack\n const agentFiles = await resourceLocator.findFiles('agents/*.md', {\n cwd: expansionDotFolder\n });\n\n for (const agentFile of agentFiles) {\n const agentPath = path.join(expansionDotFolder, agentFile);\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML frontmatter to check dependencies\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n try {\n const agentConfig = yaml.load(yamlContent);\n const dependencies = agentConfig.dependencies || {};\n \n // Check for core dependencies (those that don't exist in the expansion pack)\n for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {\n const deps = dependencies[depType] || [];\n \n for (const dep of deps) {\n const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep : \n (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);\n const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);\n \n // Check if dependency exists in expansion pack dot folder\n if (!(await fileManager.pathExists(expansionDepPath))) {\n // Try to find it in expansion pack source\n const sourceDepPath = path.join(pack.path, depType, depFileName);\n \n if (await fileManager.pathExists(sourceDepPath)) {\n // Copy from expansion pack source\n spinner.text = `Copying ${packId} dependency ${dep}...`;\n const destPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(sourceDepPath, destPath, `.${packId}`);\n console.log(chalk.dim(` Added ${packId} dependency: ${depType}/${depFileName}`));\n } else {\n // Try to find it in core\n const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);\n \n if (await fileManager.pathExists(coreDepPath)) {\n spinner.text = `Copying core dependency ${dep} for ${packId}...`;\n \n // Copy from core to expansion pack dot folder with {root} replacement\n const destPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(coreDepPath, destPath, `.${packId}`);\n \n console.log(chalk.dim(` Added core dependency: ${depType}/${depFileName}`));\n } else {\n console.warn(chalk.yellow(` Warning: Dependency ${depType}/${dep} not found in core or expansion pack`));\n }\n }\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse agent dependencies: ${error.message}`);\n }\n }\n }\n }\n\n async resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner) {\n const yaml = require('js-yaml');\n const fs = require('fs').promises;\n \n // Find all team files in the expansion pack\n const teamFiles = await resourceLocator.findFiles('agent-teams/*.yaml', {\n cwd: expansionDotFolder\n });\n\n // Also get existing agents in the expansion pack\n const existingAgents = new Set();\n const agentFiles = await resourceLocator.findFiles('agents/*.md', {\n cwd: expansionDotFolder\n });\n for (const agentFile of agentFiles) {\n const agentName = path.basename(agentFile, '.md');\n existingAgents.add(agentName);\n }\n\n // Process each team file\n for (const teamFile of teamFiles) {\n const teamPath = path.join(expansionDotFolder, teamFile);\n const teamContent = await fs.readFile(teamPath, 'utf8');\n \n try {\n const teamConfig = yaml.load(teamContent);\n const agents = teamConfig.agents || [];\n \n // Add bmad-orchestrator if not present (required for all teams)\n if (!agents.includes('bmad-orchestrator')) {\n agents.unshift('bmad-orchestrator');\n }\n \n // Check each agent in the team\n for (const agentId of agents) {\n if (!existingAgents.has(agentId)) {\n // Agent not in expansion pack, try to get from core\n const coreAgentPath = path.join(resourceLocator.getBmadCorePath(), 'agents', `${agentId}.md`);\n \n if (await fileManager.pathExists(coreAgentPath)) {\n spinner.text = `Copying core agent ${agentId} for ${packId}...`;\n \n // Copy agent file with {root} replacement\n const destPath = path.join(expansionDotFolder, 'agents', `${agentId}.md`);\n await fileManager.copyFileWithRootReplacement(coreAgentPath, destPath, `.${packId}`);\n existingAgents.add(agentId);\n \n console.log(chalk.dim(` Added core agent: ${agentId}`));\n \n // Now resolve this agent's dependencies too\n const agentContent = await fs.readFile(coreAgentPath, 'utf8');\n const yamlContent = extractYamlFromAgent(agentContent, true);\n \n if (yamlContent) {\n try {\n \n const agentConfig = yaml.load(yamlContent);\n const dependencies = agentConfig.dependencies || {};\n \n // Copy all dependencies for this agent\n for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {\n const deps = dependencies[depType] || [];\n \n for (const dep of deps) {\n const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep : \n (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);\n const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);\n \n // Check if dependency exists in expansion pack\n if (!(await fileManager.pathExists(expansionDepPath))) {\n // Try to find it in core\n const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);\n \n if (await fileManager.pathExists(coreDepPath)) {\n const destDepPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(coreDepPath, destDepPath, `.${packId}`);\n console.log(chalk.dim(` Added agent dependency: ${depType}/${depFileName}`));\n } else {\n // Try common folder\n const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root\n const commonDepPath = path.join(sourceBase, 'common', depType, depFileName);\n if (await fileManager.pathExists(commonDepPath)) {\n const destDepPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFile(commonDepPath, destDepPath);\n console.log(chalk.dim(` Added agent dependency from common: ${depType}/${depFileName}`));\n }\n }\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse agent ${agentId} dependencies: ${error.message}`);\n }\n }\n } else {\n console.warn(chalk.yellow(` Warning: Core agent ${agentId} not found for team ${path.basename(teamFile, '.yaml')}`));\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse team file ${teamFile}: ${error.message}`);\n }\n }\n }\n\n getWebBundleInfo(config) {\n const webBundleType = config.webBundleType || 'all';\n \n switch (webBundleType) {\n case 'all':\n return 'all bundles';\n case 'agents':\n return 'individual agents only';\n case 'teams':\n return config.selectedWebBundleTeams ? \n `teams: ${config.selectedWebBundleTeams.join(', ')}` : \n 'selected teams';\n case 'custom':\n const parts = [];\n if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {\n parts.push(`teams: ${config.selectedWebBundleTeams.join(', ')}`);\n }\n if (config.includeIndividualAgents) {\n parts.push('individual agents');\n }\n return parts.length > 0 ? parts.join(' + ') : 'custom selection';\n default:\n return 'selected bundles';\n }\n }\n\n async installWebBundles(webBundlesDirectory, config, spinner) {\n \n try {\n // Find the dist directory in the BMad installation\n const distDir = configLoader.getDistPath();\n \n if (!(await fileManager.pathExists(distDir))) {\n console.warn('Web bundles not found. Run \"npm run build\" to generate them.');\n return;\n }\n\n // Ensure web bundles directory exists\n await fileManager.ensureDirectory(webBundlesDirectory);\n \n const webBundleType = config.webBundleType || 'all';\n \n if (webBundleType === 'all') {\n // Copy the entire dist directory structure\n await fileManager.copyDirectory(distDir, webBundlesDirectory);\n console.log(chalk.green(`āœ“ Installed all web bundles to: ${webBundlesDirectory}`));\n } else {\n let copiedCount = 0;\n \n // Copy specific selections based on type\n if (webBundleType === 'agents' || (webBundleType === 'custom' && config.includeIndividualAgents)) {\n const agentsSource = path.join(distDir, 'agents');\n const agentsTarget = path.join(webBundlesDirectory, 'agents');\n if (await fileManager.pathExists(agentsSource)) {\n await fileManager.copyDirectory(agentsSource, agentsTarget);\n console.log(chalk.green(`āœ“ Copied individual agent bundles`));\n copiedCount += 10; // Approximate count for agents\n }\n }\n \n if (webBundleType === 'teams' || webBundleType === 'custom') {\n if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {\n const teamsSource = path.join(distDir, 'teams');\n const teamsTarget = path.join(webBundlesDirectory, 'teams');\n await fileManager.ensureDirectory(teamsTarget);\n \n for (const teamId of config.selectedWebBundleTeams) {\n const teamFile = `${teamId}.txt`;\n const sourcePath = path.join(teamsSource, teamFile);\n const targetPath = path.join(teamsTarget, teamFile);\n \n if (await fileManager.pathExists(sourcePath)) {\n await fileManager.copyFile(sourcePath, targetPath);\n copiedCount++;\n console.log(chalk.green(`āœ“ Copied team bundle: ${teamId}`));\n }\n }\n }\n }\n \n // Always copy expansion packs if they exist\n const expansionSource = path.join(distDir, 'expansion-packs');\n const expansionTarget = path.join(webBundlesDirectory, 'expansion-packs');\n if (await fileManager.pathExists(expansionSource)) {\n await fileManager.copyDirectory(expansionSource, expansionTarget);\n console.log(chalk.green(`āœ“ Copied expansion pack bundles`));\n }\n \n console.log(chalk.green(`āœ“ Installed ${copiedCount} selected web bundles to: ${webBundlesDirectory}`));\n }\n } catch (error) {\n console.error(`Failed to install web bundles: ${error.message}`);\n }\n }\n\n async copyCommonItems(installDir, targetSubdir, spinner) {\n \n const fs = require('fs').promises;\n const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root\n const commonPath = path.join(sourceBase, 'common');\n const targetPath = path.join(installDir, targetSubdir);\n const copiedFiles = [];\n \n // Check if common/ exists\n if (!(await fileManager.pathExists(commonPath))) {\n console.warn('Warning: common/ folder not found');\n return copiedFiles;\n }\n \n // Copy all items from common/ to target\n const commonItems = await resourceLocator.findFiles('**/*', {\n cwd: commonPath,\n nodir: true\n });\n \n for (const item of commonItems) {\n const sourcePath = path.join(commonPath, item);\n const destPath = path.join(targetPath, item);\n \n // Read the file content\n const content = await fs.readFile(sourcePath, 'utf8');\n \n // Replace {root} with the target subdirectory\n const updatedContent = content.replace(/\\{root\\}/g, targetSubdir);\n \n // Ensure directory exists\n await fileManager.ensureDirectory(path.dirname(destPath));\n \n // Write the updated content\n await fs.writeFile(destPath, updatedContent, 'utf8');\n copiedFiles.push(path.join(targetSubdir, item));\n }\n \n console.log(chalk.dim(` Added ${commonItems.length} common utilities`));\n return copiedFiles;\n }\n\n async detectExpansionPacks(installDir) {\n const expansionPacks = {};\n const glob = require(\"glob\");\n \n // Find all dot folders that might be expansion packs\n const dotFolders = glob.sync(\".*\", {\n cwd: installDir,\n ignore: [\".git\", \".git/**\", \".bmad-core\", \".bmad-core/**\"],\n });\n \n for (const folder of dotFolders) {\n const folderPath = path.join(installDir, folder);\n const stats = await fileManager.pathExists(folderPath);\n \n if (stats) {\n // Check if it has a manifest\n const manifestPath = path.join(folderPath, \"install-manifest.yaml\");\n if (await fileManager.pathExists(manifestPath)) {\n const manifest = await fileManager.readExpansionPackManifest(installDir, folder.substring(1));\n if (manifest) {\n expansionPacks[folder.substring(1)] = {\n path: folderPath,\n manifest: manifest,\n hasManifest: true\n };\n }\n } else {\n // Check if it has a config.yaml (expansion pack without manifest)\n const configPath = path.join(folderPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n expansionPacks[folder.substring(1)] = {\n path: folderPath,\n manifest: null,\n hasManifest: false\n };\n }\n }\n }\n }\n \n return expansionPacks;\n }\n\n async repairExpansionPack(installDir, packId, pack, integrity, spinner) {\n spinner.start(`Repairing ${pack.name}...`);\n \n try {\n const expansionDotFolder = path.join(installDir, `.${packId}`);\n \n // Back up modified files\n if (integrity.modified.length > 0) {\n spinner.text = \"Backing up modified files...\";\n for (const file of integrity.modified) {\n const filePath = path.join(installDir, file);\n if (await fileManager.pathExists(filePath)) {\n const backupPath = await fileManager.backupFile(filePath);\n console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));\n }\n }\n }\n \n // Restore missing and modified files\n spinner.text = \"Restoring files...\";\n const filesToRestore = [...integrity.missing, ...integrity.modified];\n \n for (const file of filesToRestore) {\n // Skip the manifest file itself\n if (file.endsWith('install-manifest.yaml')) continue;\n \n const relativePath = file.replace(`.${packId}/`, '');\n const sourcePath = path.join(pack.path, relativePath);\n const destPath = path.join(installDir, file);\n \n // Check if this is a common/ file that needs special processing\n const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));\n const commonSourcePath = path.join(commonBase, 'common', relativePath);\n \n if (await fileManager.pathExists(commonSourcePath)) {\n // This is a common/ file - needs template processing\n const fs = require('fs').promises;\n const content = await fs.readFile(commonSourcePath, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, `.${packId}`);\n await fileManager.ensureDirectory(path.dirname(destPath));\n await fs.writeFile(destPath, updatedContent, 'utf8');\n spinner.text = `Restored: ${file}`;\n } else if (await fileManager.pathExists(sourcePath)) {\n // Regular file from expansion pack\n await fileManager.copyFile(sourcePath, destPath);\n spinner.text = `Restored: ${file}`;\n } else {\n console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));\n }\n }\n \n spinner.succeed(`${pack.name} repaired successfully!`);\n \n // Show summary\n console.log(chalk.green(`\\nāœ“ ${pack.name} repaired!`));\n if (integrity.missing.length > 0) {\n console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));\n }\n if (integrity.modified.length > 0) {\n console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));\n }\n \n } catch (error) {\n if (spinner) spinner.fail(`Failed to repair ${pack.name}`);\n console.error(`Error: ${error.message}`);\n }\n }\n\n compareVersions(v1, v2) {\n // Simple semver comparison\n const parts1 = v1.split('.').map(Number);\n const parts2 = v2.split('.').map(Number);\n \n for (let i = 0; i < 3; i++) {\n const part1 = parts1[i] || 0;\n const part2 = parts2[i] || 0;\n \n if (part1 > part2) return 1;\n if (part1 < part2) return -1;\n }\n \n return 0;\n }\n\n async cleanupLegacyYmlFiles(installDir, spinner) {\n const glob = require('glob');\n const fs = require('fs').promises;\n \n try {\n // Find all .yml files in the installation directory\n const ymlFiles = glob.sync('**/*.yml', {\n cwd: installDir,\n ignore: ['**/node_modules/**', '**/.git/**']\n });\n \n let deletedCount = 0;\n \n for (const ymlFile of ymlFiles) {\n // Check if corresponding .yaml file exists\n const yamlFile = ymlFile.replace(/\\.yml$/, '.yaml');\n const ymlPath = path.join(installDir, ymlFile);\n const yamlPath = path.join(installDir, yamlFile);\n \n if (await fileManager.pathExists(yamlPath)) {\n // .yaml counterpart exists, delete the .yml file\n await fs.unlink(ymlPath);\n deletedCount++;\n console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${yamlFile})`));\n }\n }\n \n if (deletedCount > 0) {\n console.log(chalk.green(`āœ“ Cleaned up ${deletedCount} legacy .yml files`));\n }\n \n } catch (error) {\n console.warn(`Warning: Could not cleanup legacy .yml files: ${error.message}`);\n }\n }\n\n async findInstallation() {\n // Look for .bmad-core in current directory or parent directories\n let currentDir = process.cwd();\n\n while (currentDir !== path.dirname(currentDir)) {\n const bmadDir = path.join(currentDir, \".bmad-core\");\n const manifestPath = path.join(bmadDir, \"install-manifest.yaml\");\n\n if (await fileManager.pathExists(manifestPath)) {\n return bmadDir;\n }\n\n currentDir = path.dirname(currentDir);\n }\n\n // Also check if we're inside a .bmad-core directory\n if (path.basename(process.cwd()) === \".bmad-core\") {\n const manifestPath = path.join(process.cwd(), \"install-manifest.yaml\");\n if (await fileManager.pathExists(manifestPath)) {\n return process.cwd();\n }\n }\n\n return null;\n }\n}\n\nmodule.exports = new Installer();\n"], ["/BMAD-METHOD/tools/upgraders/v3-to-v4-upgrader.js", "const fs = require(\"fs\").promises;\nconst path = require(\"path\");\nconst { glob } = require(\"glob\");\n\n// Dynamic imports for ES modules\nlet chalk, ora, inquirer;\n\n// Initialize ES modules\nasync function initializeModules() {\n chalk = (await import(\"chalk\")).default;\n ora = (await import(\"ora\")).default;\n inquirer = (await import(\"inquirer\")).default;\n}\n\nclass V3ToV4Upgrader {\n constructor() {\n // Constructor remains empty\n }\n\n async upgrade(options = {}) {\n try {\n // Initialize ES modules\n await initializeModules();\n // Keep readline open throughout the process\n process.stdin.resume();\n\n // 1. Welcome message\n console.log(\n chalk.bold(\"\\nWelcome to BMad-Method V3 to V4 Upgrade Tool\\n\")\n );\n console.log(\n \"This tool will help you upgrade your BMad-Method V3 project to V4.\\n\"\n );\n console.log(chalk.cyan(\"What this tool does:\"));\n console.log(\"- Creates a backup of your V3 files (.bmad-v3-backup/)\");\n console.log(\"- Installs the new V4 .bmad-core structure\");\n console.log(\n \"- Preserves your PRD, Architecture, and Stories in the new format\\n\"\n );\n console.log(chalk.yellow(\"What this tool does NOT do:\"));\n console.log(\n \"- Modify your document content (use doc-migration-task after upgrade)\"\n );\n console.log(\"- Touch any files outside bmad-agent/ and docs/\\n\");\n\n // 2. Get project path\n const projectPath = await this.getProjectPath(options.projectPath);\n\n // 3. Validate V3 structure\n const validation = await this.validateV3Project(projectPath);\n if (!validation.isValid) {\n console.error(\n chalk.red(\"\\nError: This doesn't appear to be a V3 project.\")\n );\n console.error(\"Expected to find:\");\n console.error(\"- bmad-agent/ directory\");\n console.error(\"- docs/ directory\\n\");\n console.error(\n \"Please check you're in the correct directory and try again.\"\n );\n return;\n }\n\n // 4. Pre-flight check\n const analysis = await this.analyzeProject(projectPath);\n await this.showPreflightCheck(analysis, options);\n\n if (!options.dryRun) {\n const { confirm } = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirm\",\n message: \"Continue with upgrade?\",\n default: true,\n },\n ]);\n\n if (!confirm) {\n console.log(\"Upgrade cancelled.\");\n return;\n }\n }\n\n // 5. Create backup\n if (options.backup !== false && !options.dryRun) {\n await this.createBackup(projectPath);\n }\n\n // 6. Install V4 structure\n if (!options.dryRun) {\n await this.installV4Structure(projectPath);\n }\n\n // 7. Migrate documents\n if (!options.dryRun) {\n await this.migrateDocuments(projectPath, analysis);\n }\n\n // 8. Setup IDE\n if (!options.dryRun) {\n await this.setupIDE(projectPath, options.ides);\n }\n\n // 9. Show completion report\n this.showCompletionReport(projectPath, analysis);\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red(\"\\nUpgrade error:\"), error.message);\n process.exit(1);\n }\n }\n\n async getProjectPath(providedPath) {\n if (providedPath) {\n return path.resolve(providedPath);\n }\n\n const { projectPath } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"projectPath\",\n message: \"Please enter the path to your V3 project:\",\n default: process.cwd(),\n },\n ]);\n\n return path.resolve(projectPath);\n }\n\n async validateV3Project(projectPath) {\n const spinner = ora(\"Validating project structure...\").start();\n\n try {\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n const docsPath = path.join(projectPath, \"docs\");\n\n const hasBmadAgent = await this.pathExists(bmadAgentPath);\n const hasDocs = await this.pathExists(docsPath);\n\n if (hasBmadAgent) {\n spinner.text = \"āœ“ Found bmad-agent/ directory\";\n console.log(chalk.green(\"\\nāœ“ Found bmad-agent/ directory\"));\n }\n\n if (hasDocs) {\n console.log(chalk.green(\"āœ“ Found docs/ directory\"));\n }\n\n const isValid = hasBmadAgent && hasDocs;\n\n if (isValid) {\n spinner.succeed(\"This appears to be a valid V3 project\");\n } else {\n spinner.fail(\"Invalid V3 project structure\");\n }\n\n return { isValid, hasBmadAgent, hasDocs };\n } catch (error) {\n spinner.fail(\"Validation failed\");\n throw error;\n }\n }\n\n async analyzeProject(projectPath) {\n const docsPath = path.join(projectPath, \"docs\");\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n\n // Find PRD\n const prdCandidates = [\"prd.md\", \"PRD.md\", \"product-requirements.md\"];\n let prdFile = null;\n for (const candidate of prdCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n prdFile = candidate;\n break;\n }\n }\n\n // Find Architecture\n const archCandidates = [\n \"architecture.md\",\n \"Architecture.md\",\n \"technical-architecture.md\",\n ];\n let archFile = null;\n for (const candidate of archCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n archFile = candidate;\n break;\n }\n }\n\n // Find Front-end Architecture (V3 specific)\n const frontEndCandidates = [\n \"front-end-architecture.md\",\n \"frontend-architecture.md\",\n \"ui-architecture.md\",\n ];\n let frontEndArchFile = null;\n for (const candidate of frontEndCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n frontEndArchFile = candidate;\n break;\n }\n }\n\n // Find UX/UI spec\n const uxSpecCandidates = [\n \"ux-ui-spec.md\",\n \"ux-ui-specification.md\",\n \"ui-spec.md\",\n \"ux-spec.md\",\n ];\n let uxSpecFile = null;\n for (const candidate of uxSpecCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxSpecFile = candidate;\n break;\n }\n }\n\n // Find v0 prompt or UX prompt\n const uxPromptCandidates = [\n \"v0-prompt.md\",\n \"ux-prompt.md\",\n \"ui-prompt.md\",\n \"design-prompt.md\",\n ];\n let uxPromptFile = null;\n for (const candidate of uxPromptCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxPromptFile = candidate;\n break;\n }\n }\n\n // Find epic files\n const epicFiles = await glob(\"epic*.md\", { cwd: docsPath });\n\n // Find story files\n const storiesPath = path.join(docsPath, \"stories\");\n let storyFiles = [];\n if (await this.pathExists(storiesPath)) {\n storyFiles = await glob(\"*.md\", { cwd: storiesPath });\n }\n\n // Count custom files in bmad-agent\n const bmadAgentFiles = await glob(\"**/*.md\", {\n cwd: bmadAgentPath,\n ignore: [\"node_modules/**\"],\n });\n\n return {\n prdFile,\n archFile,\n frontEndArchFile,\n uxSpecFile,\n uxPromptFile,\n epicFiles,\n storyFiles,\n customFileCount: bmadAgentFiles.length,\n };\n }\n\n async showPreflightCheck(analysis, options) {\n console.log(chalk.bold(\"\\nProject Analysis:\"));\n console.log(\n `- PRD found: ${\n analysis.prdFile\n ? `docs/${analysis.prdFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- Architecture found: ${\n analysis.archFile\n ? `docs/${analysis.archFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n if (analysis.frontEndArchFile) {\n console.log(\n `- Front-end Architecture found: docs/${analysis.frontEndArchFile}`\n );\n }\n console.log(\n `- UX/UI Spec found: ${\n analysis.uxSpecFile\n ? `docs/${analysis.uxSpecFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- UX/Design Prompt found: ${\n analysis.uxPromptFile\n ? `docs/${analysis.uxPromptFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- Epic files found: ${analysis.epicFiles.length} files (epic*.md)`\n );\n console.log(\n `- Stories found: ${analysis.storyFiles.length} files in docs/stories/`\n );\n console.log(`- Custom files in bmad-agent/: ${analysis.customFileCount}`);\n\n if (!options.dryRun) {\n console.log(\"\\nThe following will be backed up to .bmad-v3-backup/:\");\n console.log(\"- bmad-agent/ (entire directory)\");\n console.log(\"- docs/ (entire directory)\");\n\n if (analysis.epicFiles.length > 0) {\n console.log(\n chalk.green(\n \"\\nNote: Epic files found! They will be placed in docs/prd/ with an index.md file.\"\n )\n );\n console.log(\n chalk.green(\n \"Since epic files exist, you won't need to shard the PRD after upgrade.\"\n )\n );\n }\n }\n }\n\n async createBackup(projectPath) {\n const spinner = ora(\"Creating backup...\").start();\n\n try {\n const backupPath = path.join(projectPath, \".bmad-v3-backup\");\n\n // Check if backup already exists\n if (await this.pathExists(backupPath)) {\n spinner.fail(\"Backup directory already exists\");\n console.error(\n chalk.red(\n \"\\nError: Backup directory .bmad-v3-backup/ already exists.\"\n )\n );\n console.error(\"\\nThis might mean an upgrade was already attempted.\");\n console.error(\n \"Please remove or rename the existing backup and try again.\"\n );\n throw new Error(\"Backup already exists\");\n }\n\n // Create backup directory\n await fs.mkdir(backupPath, { recursive: true });\n spinner.text = \"āœ“ Created .bmad-v3-backup/\";\n console.log(chalk.green(\"\\nāœ“ Created .bmad-v3-backup/\"));\n\n // Move bmad-agent\n const bmadAgentSrc = path.join(projectPath, \"bmad-agent\");\n const bmadAgentDest = path.join(backupPath, \"bmad-agent\");\n await fs.rename(bmadAgentSrc, bmadAgentDest);\n console.log(chalk.green(\"āœ“ Moved bmad-agent/ to backup\"));\n\n // Move docs\n const docsSrc = path.join(projectPath, \"docs\");\n const docsDest = path.join(backupPath, \"docs\");\n await fs.rename(docsSrc, docsDest);\n console.log(chalk.green(\"āœ“ Moved docs/ to backup\"));\n\n spinner.succeed(\"Backup created successfully\");\n } catch (error) {\n spinner.fail(\"Backup failed\");\n throw error;\n }\n }\n\n async installV4Structure(projectPath) {\n const spinner = ora(\"Installing V4 structure...\").start();\n\n try {\n // Get the source bmad-core directory (without dot prefix)\n const sourcePath = path.join(__dirname, \"..\", \"..\", \"bmad-core\");\n const destPath = path.join(projectPath, \".bmad-core\");\n\n // Copy .bmad-core\n await this.copyDirectory(sourcePath, destPath);\n spinner.text = \"āœ“ Copied fresh .bmad-core/ directory from V4\";\n console.log(\n chalk.green(\"\\nāœ“ Copied fresh .bmad-core/ directory from V4\")\n );\n\n // Create docs directory\n const docsPath = path.join(projectPath, \"docs\");\n await fs.mkdir(docsPath, { recursive: true });\n console.log(chalk.green(\"āœ“ Created new docs/ directory\"));\n\n // Create install manifest for future updates\n await this.createInstallManifest(projectPath);\n console.log(chalk.green(\"āœ“ Created install manifest\"));\n\n console.log(\n chalk.yellow(\n \"\\nNote: Your V3 bmad-agent content has been backed up and NOT migrated.\"\n )\n );\n console.log(\n chalk.yellow(\n \"The new V4 agents are completely different and look for different file structures.\"\n )\n );\n\n spinner.succeed(\"V4 structure installed successfully\");\n } catch (error) {\n spinner.fail(\"V4 installation failed\");\n throw error;\n }\n }\n\n async migrateDocuments(projectPath, analysis) {\n const spinner = ora(\"Migrating your project documents...\").start();\n\n try {\n const backupDocsPath = path.join(projectPath, \".bmad-v3-backup\", \"docs\");\n const newDocsPath = path.join(projectPath, \"docs\");\n let copiedCount = 0;\n\n // Copy PRD\n if (analysis.prdFile) {\n const src = path.join(backupDocsPath, analysis.prdFile);\n const dest = path.join(newDocsPath, analysis.prdFile);\n await fs.copyFile(src, dest);\n console.log(chalk.green(`\\nāœ“ Copied PRD to docs/${analysis.prdFile}`));\n copiedCount++;\n }\n\n // Copy Architecture\n if (analysis.archFile) {\n const src = path.join(backupDocsPath, analysis.archFile);\n const dest = path.join(newDocsPath, analysis.archFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(`āœ“ Copied Architecture to docs/${analysis.archFile}`)\n );\n copiedCount++;\n }\n\n // Copy Front-end Architecture if exists\n if (analysis.frontEndArchFile) {\n const src = path.join(backupDocsPath, analysis.frontEndArchFile);\n const dest = path.join(newDocsPath, analysis.frontEndArchFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(\n `āœ“ Copied Front-end Architecture to docs/${analysis.frontEndArchFile}`\n )\n );\n console.log(\n chalk.yellow(\n \"Note: V4 uses a single full-stack-architecture.md - use doc-migration-task to merge\"\n )\n );\n copiedCount++;\n }\n\n // Copy UX/UI Spec if exists\n if (analysis.uxSpecFile) {\n const src = path.join(backupDocsPath, analysis.uxSpecFile);\n const dest = path.join(newDocsPath, analysis.uxSpecFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(`āœ“ Copied UX/UI Spec to docs/${analysis.uxSpecFile}`)\n );\n copiedCount++;\n }\n\n // Copy UX/Design Prompt if exists\n if (analysis.uxPromptFile) {\n const src = path.join(backupDocsPath, analysis.uxPromptFile);\n const dest = path.join(newDocsPath, analysis.uxPromptFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(\n `āœ“ Copied UX/Design Prompt to docs/${analysis.uxPromptFile}`\n )\n );\n copiedCount++;\n }\n\n // Copy stories\n if (analysis.storyFiles.length > 0) {\n const storiesDir = path.join(newDocsPath, \"stories\");\n await fs.mkdir(storiesDir, { recursive: true });\n\n for (const storyFile of analysis.storyFiles) {\n const src = path.join(backupDocsPath, \"stories\", storyFile);\n const dest = path.join(storiesDir, storyFile);\n await fs.copyFile(src, dest);\n }\n console.log(\n chalk.green(\n `āœ“ Copied ${analysis.storyFiles.length} story files to docs/stories/`\n )\n );\n copiedCount += analysis.storyFiles.length;\n }\n\n // Copy epic files to prd subfolder\n if (analysis.epicFiles.length > 0) {\n const prdDir = path.join(newDocsPath, \"prd\");\n await fs.mkdir(prdDir, { recursive: true });\n\n for (const epicFile of analysis.epicFiles) {\n const src = path.join(backupDocsPath, epicFile);\n const dest = path.join(prdDir, epicFile);\n await fs.copyFile(src, dest);\n }\n console.log(\n chalk.green(\n `āœ“ Found and copied ${analysis.epicFiles.length} epic files to docs/prd/`\n )\n );\n\n // Create index.md for the prd folder\n await this.createPrdIndex(projectPath, analysis);\n console.log(chalk.green(\"āœ“ Created index.md in docs/prd/\"));\n\n console.log(\n chalk.green(\n \"\\nNote: Epic files detected! These are compatible with V4 and have been copied.\"\n )\n );\n console.log(\n chalk.green(\n \"You won't need to shard the PRD since epics already exist.\"\n )\n );\n copiedCount += analysis.epicFiles.length;\n }\n\n spinner.succeed(`Migrated ${copiedCount} documents successfully`);\n } catch (error) {\n spinner.fail(\"Document migration failed\");\n throw error;\n }\n }\n\n async setupIDE(projectPath, selectedIdes) {\n // Use the IDE selections passed from the installer\n if (!selectedIdes || selectedIdes.length === 0) {\n console.log(chalk.dim(\"No IDE setup requested - skipping\"));\n return;\n }\n\n const ideSetup = require(\"../installer/lib/ide-setup\");\n const spinner = ora(\"Setting up IDE rules for all agents...\").start();\n\n try {\n const ideMessages = {\n cursor: \"Rules created in .cursor/rules/\",\n \"claude-code\": \"Commands created in .claude/commands/BMad/\",\n windsurf: \"Rules created in .windsurf/rules/\",\n trae: \"Rules created in.trae/rules/\",\n roo: \"Custom modes created in .roomodes\",\n cline: \"Rules created in .clinerules/\",\n };\n\n // Setup each selected IDE\n for (const ide of selectedIdes) {\n spinner.text = `Setting up ${ide}...`;\n await ideSetup.setup(ide, projectPath);\n console.log(chalk.green(`\\nāœ“ ${ideMessages[ide]}`));\n }\n\n spinner.succeed(`IDE setup complete for ${selectedIdes.length} IDE(s)!`);\n } catch (error) {\n spinner.fail(\"IDE setup failed\");\n console.error(\n chalk.yellow(\"IDE setup failed, but upgrade is complete.\")\n );\n }\n }\n\n showCompletionReport(projectPath, analysis) {\n console.log(chalk.bold.green(\"\\nāœ“ Upgrade Complete!\\n\"));\n console.log(chalk.bold(\"Summary:\"));\n console.log(`- V3 files backed up to: .bmad-v3-backup/`);\n console.log(`- V4 structure installed: .bmad-core/ (fresh from V4)`);\n\n const totalDocs =\n (analysis.prdFile ? 1 : 0) +\n (analysis.archFile ? 1 : 0) +\n (analysis.frontEndArchFile ? 1 : 0) +\n (analysis.uxSpecFile ? 1 : 0) +\n (analysis.uxPromptFile ? 1 : 0) +\n analysis.storyFiles.length;\n console.log(\n `- Documents migrated: ${totalDocs} files${\n analysis.epicFiles.length > 0\n ? ` + ${analysis.epicFiles.length} epics`\n : \"\"\n }`\n );\n\n console.log(chalk.bold(\"\\nImportant Changes:\"));\n console.log(\n \"- The V4 agents (sm, dev, etc.) expect different file structures than V3\"\n );\n console.log(\n \"- Your V3 bmad-agent content was NOT migrated (it's incompatible)\"\n );\n if (analysis.epicFiles.length > 0) {\n console.log(\n \"- Epic files were found and copied - no PRD sharding needed!\"\n );\n }\n if (analysis.frontEndArchFile) {\n console.log(\n \"- Front-end architecture found - V4 uses full-stack-architecture.md, migration needed\"\n );\n }\n if (analysis.uxSpecFile || analysis.uxPromptFile) {\n console.log(\n \"- UX/UI design files found and copied - ready for use with V4\"\n );\n }\n\n console.log(chalk.bold(\"\\nNext Steps:\"));\n console.log(\"1. Review your documents in the new docs/ folder\");\n console.log(\n \"2. Use @bmad-master agent to run the doc-migration-task to align your documents with V4 templates\"\n );\n if (analysis.epicFiles.length === 0) {\n console.log(\n \"3. Use @bmad-master agent to shard the PRD to create epic files\"\n );\n }\n\n console.log(\n chalk.dim(\n \"\\nYour V3 backup is preserved in .bmad-v3-backup/ and can be restored if needed.\"\n )\n );\n }\n\n async pathExists(filePath) {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n async copyDirectory(src, dest) {\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await this.copyDirectory(srcPath, destPath);\n } else {\n await fs.copyFile(srcPath, destPath);\n }\n }\n }\n\n async createPrdIndex(projectPath, analysis) {\n const prdIndexPath = path.join(projectPath, \"docs\", \"prd\", \"index.md\");\n const prdPath = path.join(\n projectPath,\n \"docs\",\n analysis.prdFile || \"prd.md\"\n );\n\n let indexContent = \"# Product Requirements Document\\n\\n\";\n\n // Try to read the PRD to get the title and intro content\n if (analysis.prdFile && (await this.pathExists(prdPath))) {\n try {\n const prdContent = await fs.readFile(prdPath, \"utf8\");\n const lines = prdContent.split(\"\\n\");\n\n // Find the first heading\n const titleMatch = lines.find((line) => line.startsWith(\"# \"));\n if (titleMatch) {\n indexContent = titleMatch + \"\\n\\n\";\n }\n\n // Get any content before the first ## section\n let introContent = \"\";\n let foundFirstSection = false;\n for (const line of lines) {\n if (line.startsWith(\"## \")) {\n foundFirstSection = true;\n break;\n }\n if (!line.startsWith(\"# \")) {\n introContent += line + \"\\n\";\n }\n }\n\n if (introContent.trim()) {\n indexContent += introContent.trim() + \"\\n\\n\";\n }\n } catch (error) {\n // If we can't read the PRD, just use default content\n }\n }\n\n // Add sections list\n indexContent += \"## Sections\\n\\n\";\n\n // Sort epic files for consistent ordering\n const sortedEpics = [...analysis.epicFiles].sort();\n\n for (const epicFile of sortedEpics) {\n // Extract epic name from filename\n const epicName = epicFile\n .replace(/\\.md$/, \"\")\n .replace(/^epic-?/i, \"\")\n .replace(/-/g, \" \")\n .replace(/^\\d+\\s*/, \"\") // Remove leading numbers\n .trim();\n\n const displayName = epicName.charAt(0).toUpperCase() + epicName.slice(1);\n indexContent += `- [${\n displayName || epicFile.replace(\".md\", \"\")\n }](./${epicFile})\\n`;\n }\n\n await fs.writeFile(prdIndexPath, indexContent);\n }\n\n async createInstallManifest(projectPath) {\n const fileManager = require(\"../installer/lib/file-manager\");\n const { glob } = require(\"glob\");\n\n // Get all files in .bmad-core for the manifest\n const bmadCorePath = path.join(projectPath, \".bmad-core\");\n const files = await glob(\"**/*\", {\n cwd: bmadCorePath,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n\n // Prepend .bmad-core/ to file paths for manifest\n const manifestFiles = files.map((file) => path.join(\".bmad-core\", file));\n\n const config = {\n installType: \"full\",\n agent: null,\n ide: null, // Will be set if IDE setup is done later\n };\n\n await fileManager.createManifest(projectPath, config, manifestFiles);\n }\n}\n\nmodule.exports = V3ToV4Upgrader;\n"], ["/BMAD-METHOD/tools/installer/lib/ide-setup.js", "const path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst inquirer = require(\"inquirer\");\nconst fileManager = require(\"./file-manager\");\nconst configLoader = require(\"./config-loader\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\nconst BaseIdeSetup = require(\"./ide-base-setup\");\nconst resourceLocator = require(\"./resource-locator\");\n\nclass IdeSetup extends BaseIdeSetup {\n constructor() {\n super();\n this.ideAgentConfig = null;\n }\n\n async loadIdeAgentConfig() {\n if (this.ideAgentConfig) return this.ideAgentConfig;\n \n try {\n const configPath = path.join(__dirname, '..', 'config', 'ide-agent-config.yaml');\n const configContent = await fs.readFile(configPath, 'utf8');\n this.ideAgentConfig = yaml.load(configContent);\n return this.ideAgentConfig;\n } catch (error) {\n console.warn('Failed to load IDE agent configuration, using defaults');\n return {\n 'roo-permissions': {},\n 'cline-order': {}\n };\n }\n }\n\n async setup(ide, installDir, selectedAgent = null, spinner = null, preConfiguredSettings = null) {\n const ideConfig = await configLoader.getIdeConfiguration(ide);\n\n if (!ideConfig) {\n console.log(chalk.yellow(`\\nNo configuration available for ${ide}`));\n return false;\n }\n\n switch (ide) {\n case \"cursor\":\n return this.setupCursor(installDir, selectedAgent);\n case \"claude-code\":\n return this.setupClaudeCode(installDir, selectedAgent);\n case \"windsurf\":\n return this.setupWindsurf(installDir, selectedAgent);\n case \"trae\":\n return this.setupTrae(installDir, selectedAgent);\n case \"roo\":\n return this.setupRoo(installDir, selectedAgent);\n case \"cline\":\n return this.setupCline(installDir, selectedAgent);\n case \"gemini\":\n return this.setupGeminiCli(installDir, selectedAgent);\n case \"github-copilot\":\n return this.setupGitHubCopilot(installDir, selectedAgent, spinner, preConfiguredSettings);\n default:\n console.log(chalk.yellow(`\\nIDE ${ide} not yet supported`));\n return false;\n }\n }\n\n async setupCursor(installDir, selectedAgent) {\n const cursorRulesDir = path.join(installDir, \".cursor\", \"rules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(cursorRulesDir);\n\n for (const agentId of agents) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const mdcContent = await this.createAgentRuleContent(agentId, agentPath, installDir, 'mdc');\n const mdcPath = path.join(cursorRulesDir, `${agentId}.mdc`);\n await fileManager.writeFile(mdcPath, mdcContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.mdc`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Cursor rules in ${cursorRulesDir}`));\n return true;\n }\n\n async setupClaudeCode(installDir, selectedAgent) {\n // Setup bmad-core commands\n const coreSlashPrefix = await this.getCoreSlashPrefix(installDir);\n const coreAgents = selectedAgent ? [selectedAgent] : await this.getCoreAgentIds(installDir);\n const coreTasks = await this.getCoreTaskIds(installDir);\n await this.setupClaudeCodeForPackage(installDir, \"core\", coreSlashPrefix, coreAgents, coreTasks, \".bmad-core\");\n\n // Setup expansion pack commands\n const expansionPacks = await this.getInstalledExpansionPacks(installDir);\n for (const packInfo of expansionPacks) {\n const packSlashPrefix = await this.getExpansionPackSlashPrefix(packInfo.path);\n const packAgents = await this.getExpansionPackAgents(packInfo.path);\n const packTasks = await this.getExpansionPackTasks(packInfo.path);\n \n if (packAgents.length > 0 || packTasks.length > 0) {\n // Use the actual directory name where the expansion pack is installed\n const rootPath = path.relative(installDir, packInfo.path);\n await this.setupClaudeCodeForPackage(installDir, packInfo.name, packSlashPrefix, packAgents, packTasks, rootPath);\n }\n }\n\n return true;\n }\n\n async setupClaudeCodeForPackage(installDir, packageName, slashPrefix, agentIds, taskIds, rootPath) {\n const commandsBaseDir = path.join(installDir, \".claude\", \"commands\", slashPrefix);\n const agentsDir = path.join(commandsBaseDir, \"agents\");\n const tasksDir = path.join(commandsBaseDir, \"tasks\");\n\n // Ensure directories exist\n await fileManager.ensureDirectory(agentsDir);\n await fileManager.ensureDirectory(tasksDir);\n\n // Setup agents\n for (const agentId of agentIds) {\n // Find the agent file - for expansion packs, prefer the expansion pack version\n let agentPath;\n if (packageName !== \"core\") {\n // For expansion packs, first try to find the agent in the expansion pack directory\n const expansionPackPath = path.join(installDir, rootPath, \"agents\", `${agentId}.md`);\n if (await fileManager.pathExists(expansionPackPath)) {\n agentPath = expansionPackPath;\n } else {\n // Fall back to core if not found in expansion pack\n agentPath = await this.findAgentPath(agentId, installDir);\n }\n } else {\n // For core, use the normal search\n agentPath = await this.findAgentPath(agentId, installDir);\n }\n \n const commandPath = path.join(agentsDir, `${agentId}.md`);\n\n if (agentPath) {\n // Create command file with agent content\n let agentContent = await fileManager.readFile(agentPath);\n \n // Replace {root} placeholder with the appropriate root path for this context\n agentContent = agentContent.replace(/{root}/g, rootPath);\n\n // Add command header\n let commandContent = `# /${agentId} Command\\n\\n`;\n commandContent += `When this command is used, adopt the following agent persona:\\n\\n`;\n commandContent += agentContent;\n\n await fileManager.writeFile(commandPath, commandContent);\n console.log(chalk.green(`āœ“ Created agent command: /${agentId}`));\n }\n }\n\n // Setup tasks\n for (const taskId of taskIds) {\n // Find the task file - for expansion packs, prefer the expansion pack version\n let taskPath;\n if (packageName !== \"core\") {\n // For expansion packs, first try to find the task in the expansion pack directory\n const expansionPackPath = path.join(installDir, rootPath, \"tasks\", `${taskId}.md`);\n if (await fileManager.pathExists(expansionPackPath)) {\n taskPath = expansionPackPath;\n } else {\n // Fall back to core if not found in expansion pack\n taskPath = await this.findTaskPath(taskId, installDir);\n }\n } else {\n // For core, use the normal search\n taskPath = await this.findTaskPath(taskId, installDir);\n }\n \n const commandPath = path.join(tasksDir, `${taskId}.md`);\n\n if (taskPath) {\n // Create command file with task content\n let taskContent = await fileManager.readFile(taskPath);\n \n // Replace {root} placeholder with the appropriate root path for this context\n taskContent = taskContent.replace(/{root}/g, rootPath);\n\n // Add command header\n let commandContent = `# /${taskId} Task\\n\\n`;\n commandContent += `When this command is used, execute the following task:\\n\\n`;\n commandContent += taskContent;\n\n await fileManager.writeFile(commandPath, commandContent);\n console.log(chalk.green(`āœ“ Created task command: /${taskId}`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Claude Code commands for ${packageName} in ${commandsBaseDir}`));\n console.log(chalk.dim(` - Agents in: ${agentsDir}`));\n console.log(chalk.dim(` - Tasks in: ${tasksDir}`));\n }\n\n async setupWindsurf(installDir, selectedAgent) {\n const windsurfRulesDir = path.join(installDir, \".windsurf\", \"rules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(windsurfRulesDir);\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n const mdPath = path.join(windsurfRulesDir, `${agentId}.md`);\n\n // Create MD content (similar to Cursor but without frontmatter)\n let mdContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n mdContent += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n mdContent += \"## Agent Activation\\n\\n\";\n mdContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n } else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `When the user types \\`@${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n\n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Windsurf rules in ${windsurfRulesDir}`));\n\n return true;\n }\n\n async setupTrae(installDir, selectedAgent) {\n const traeRulesDir = path.join(installDir, \".trae\", \"rules\");\n const agents = selectedAgent? [selectedAgent] : await this.getAllAgentIds(installDir);\n \n await fileManager.ensureDirectory(traeRulesDir);\n \n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n \n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n const mdPath = path.join(traeRulesDir, `${agentId}.md`);\n \n // Create MD content (similar to Cursor but without frontmatter)\n let mdContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n mdContent += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n mdContent += \"## Agent Activation\\n\\n\";\n mdContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n }\n else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `When the user types \\`@${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n \n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.md`));\n }\n }\n }\n\n async findAgentPath(agentId, installDir) {\n // Try to find the agent file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"agents\", `${agentId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${agentId}.md`));\n }\n \n for (const agentPath of possiblePaths) {\n if (await fileManager.pathExists(agentPath)) {\n return agentPath;\n }\n }\n \n return null;\n }\n\n async getAllAgentIds(installDir) {\n const glob = require(\"glob\");\n const allAgentIds = [];\n \n // Check core agents in .bmad-core or root\n let agentsDir = path.join(installDir, \".bmad-core\", \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n agentsDir = path.join(installDir, \"agents\");\n }\n \n if (await fileManager.pathExists(agentsDir)) {\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n allAgentIds.push(...agentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Also check for expansion pack agents in dot folders\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n const fullExpDir = path.join(installDir, expDir);\n const expAgentFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allAgentIds.push(...expAgentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Remove duplicates\n return [...new Set(allAgentIds)];\n }\n\n async getCoreAgentIds(installDir) {\n const allAgentIds = [];\n \n // Check core agents in .bmad-core or root only\n let agentsDir = path.join(installDir, \".bmad-core\", \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n agentsDir = path.join(installDir, \"bmad-core\", \"agents\");\n }\n \n if (await fileManager.pathExists(agentsDir)) {\n const glob = require(\"glob\");\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n allAgentIds.push(...agentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n return [...new Set(allAgentIds)];\n }\n\n async getCoreTaskIds(installDir) {\n const allTaskIds = [];\n \n // Check core tasks in .bmad-core or root only\n let tasksDir = path.join(installDir, \".bmad-core\", \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n tasksDir = path.join(installDir, \"bmad-core\", \"tasks\");\n }\n \n if (await fileManager.pathExists(tasksDir)) {\n const glob = require(\"glob\");\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n allTaskIds.push(...taskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check common tasks\n const commonTasksDir = path.join(installDir, \"common\", \"tasks\");\n if (await fileManager.pathExists(commonTasksDir)) {\n const commonTaskFiles = glob.sync(\"*.md\", { cwd: commonTasksDir });\n allTaskIds.push(...commonTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n return [...new Set(allTaskIds)];\n }\n\n async getAgentTitle(agentId, installDir) {\n // Try to find the agent file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"agents\", `${agentId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${agentId}.md`));\n }\n \n for (const agentPath of possiblePaths) {\n if (await fileManager.pathExists(agentPath)) {\n try {\n const agentContent = await fileManager.readFile(agentPath);\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n \n if (yamlMatch) {\n const yaml = yamlMatch[1];\n const titleMatch = yaml.match(/title:\\s*(.+)/);\n if (titleMatch) {\n return titleMatch[1].trim();\n }\n }\n } catch (error) {\n console.warn(`Failed to read agent title for ${agentId}: ${error.message}`);\n }\n }\n }\n \n // Fallback to formatted agent ID\n return agentId.split('-').map(word => \n word.charAt(0).toUpperCase() + word.slice(1)\n ).join(' ');\n }\n\n async getAllTaskIds(installDir) {\n const glob = require(\"glob\");\n const allTaskIds = [];\n \n // Check core tasks in .bmad-core or root\n let tasksDir = path.join(installDir, \".bmad-core\", \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n tasksDir = path.join(installDir, \"bmad-core\", \"tasks\");\n }\n \n if (await fileManager.pathExists(tasksDir)) {\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n allTaskIds.push(...taskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check common tasks\n const commonTasksDir = path.join(installDir, \"common\", \"tasks\");\n if (await fileManager.pathExists(commonTasksDir)) {\n const commonTaskFiles = glob.sync(\"*.md\", { cwd: commonTasksDir });\n allTaskIds.push(...commonTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Also check for expansion pack tasks in dot folders\n const expansionDirs = glob.sync(\".*/tasks\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n const fullExpDir = path.join(installDir, expDir);\n const expTaskFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allTaskIds.push(...expTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check expansion-packs folder tasks\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const expPackDirs = glob.sync(\"*/tasks\", { cwd: expansionPacksDir });\n for (const expDir of expPackDirs) {\n const fullExpDir = path.join(expansionPacksDir, expDir);\n const expTaskFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allTaskIds.push(...expTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n }\n \n // Remove duplicates\n return [...new Set(allTaskIds)];\n }\n\n async findTaskPath(taskId, installDir) {\n // Try to find the task file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"tasks\", `${taskId}.md`),\n path.join(installDir, \"bmad-core\", \"tasks\", `${taskId}.md`),\n path.join(installDir, \"common\", \"tasks\", `${taskId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n \n // Check dot folder expansion packs\n const expansionDirs = glob.sync(\".*/tasks\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${taskId}.md`));\n }\n \n // Check expansion-packs folder\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const expPackDirs = glob.sync(\"*/tasks\", { cwd: expansionPacksDir });\n for (const expDir of expPackDirs) {\n possiblePaths.push(path.join(expansionPacksDir, expDir, `${taskId}.md`));\n }\n }\n \n for (const taskPath of possiblePaths) {\n if (await fileManager.pathExists(taskPath)) {\n return taskPath;\n }\n }\n \n return null;\n }\n\n async getCoreSlashPrefix(installDir) {\n try {\n const coreConfigPath = path.join(installDir, \".bmad-core\", \"core-config.yaml\");\n if (!(await fileManager.pathExists(coreConfigPath))) {\n // Try bmad-core directory\n const altConfigPath = path.join(installDir, \"bmad-core\", \"core-config.yaml\");\n if (await fileManager.pathExists(altConfigPath)) {\n const configContent = await fileManager.readFile(altConfigPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || \"BMad\";\n }\n return \"BMad\"; // fallback\n }\n \n const configContent = await fileManager.readFile(coreConfigPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || \"BMad\";\n } catch (error) {\n console.warn(`Failed to read core slashPrefix, using default 'BMad': ${error.message}`);\n return \"BMad\";\n }\n }\n\n async getInstalledExpansionPacks(installDir) {\n const expansionPacks = [];\n \n // Check for dot-prefixed expansion packs in install directory\n const glob = require(\"glob\");\n const dotExpansions = glob.sync(\".bmad-*\", { cwd: installDir });\n \n for (const dotExpansion of dotExpansions) {\n if (dotExpansion !== \".bmad-core\") {\n const packPath = path.join(installDir, dotExpansion);\n const packName = dotExpansion.substring(1); // remove the dot\n expansionPacks.push({\n name: packName,\n path: packPath\n });\n }\n }\n \n // Check for expansion-packs directory style\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const packDirs = glob.sync(\"*\", { cwd: expansionPacksDir });\n \n for (const packDir of packDirs) {\n const packPath = path.join(expansionPacksDir, packDir);\n if ((await fileManager.pathExists(packPath)) && \n (await fileManager.pathExists(path.join(packPath, \"config.yaml\")))) {\n expansionPacks.push({\n name: packDir,\n path: packPath\n });\n }\n }\n }\n \n return expansionPacks;\n }\n\n async getExpansionPackSlashPrefix(packPath) {\n try {\n const configPath = path.join(packPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n const configContent = await fileManager.readFile(configPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || path.basename(packPath);\n }\n } catch (error) {\n console.warn(`Failed to read expansion pack slashPrefix from ${packPath}: ${error.message}`);\n }\n \n return path.basename(packPath); // fallback to directory name\n }\n\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n return [];\n }\n \n try {\n const glob = require(\"glob\");\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n return agentFiles.map(file => path.basename(file, \".md\"));\n } catch (error) {\n console.warn(`Failed to read expansion pack agents from ${packPath}: ${error.message}`);\n return [];\n }\n }\n\n async getExpansionPackTasks(packPath) {\n const tasksDir = path.join(packPath, \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n return [];\n }\n \n try {\n const glob = require(\"glob\");\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n return taskFiles.map(file => path.basename(file, \".md\"));\n } catch (error) {\n console.warn(`Failed to read expansion pack tasks from ${packPath}: ${error.message}`);\n return [];\n }\n }\n\n async setupRoo(installDir, selectedAgent) {\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n // Check for existing .roomodes file in project root\n const roomodesPath = path.join(installDir, \".roomodes\");\n let existingModes = [];\n let existingContent = \"\";\n\n if (await fileManager.pathExists(roomodesPath)) {\n existingContent = await fileManager.readFile(roomodesPath);\n // Parse existing modes to avoid duplicates\n const modeMatches = existingContent.matchAll(/- slug: ([\\w-]+)/g);\n for (const match of modeMatches) {\n existingModes.push(match[1]);\n }\n console.log(chalk.yellow(`Found existing .roomodes file with ${existingModes.length} modes`));\n }\n\n // Create new modes content\n let newModesContent = \"\";\n\n // Load dynamic agent permissions from configuration\n const config = await this.loadIdeAgentConfig();\n const agentPermissions = config['roo-permissions'] || {};\n\n for (const agentId of agents) {\n // Skip if already exists\n // Check both with and without bmad- prefix to handle both cases\n const checkSlug = agentId.startsWith('bmad-') ? agentId : `bmad-${agentId}`;\n if (existingModes.includes(checkSlug)) {\n console.log(chalk.dim(`Skipping ${agentId} - already exists in .roomodes`));\n continue;\n }\n\n // Read agent file to extract all information\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n\n // Extract YAML content\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n const yaml = yamlMatch[1];\n\n // Extract agent info from YAML\n const titleMatch = yaml.match(/title:\\s*(.+)/);\n const iconMatch = yaml.match(/icon:\\s*(.+)/);\n const whenToUseMatch = yaml.match(/whenToUse:\\s*\"(.+)\"/);\n const roleDefinitionMatch = yaml.match(/roleDefinition:\\s*\"(.+)\"/);\n\n const title = titleMatch ? titleMatch[1].trim() : await this.getAgentTitle(agentId, installDir);\n const icon = iconMatch ? iconMatch[1].trim() : \"šŸ¤–\";\n const whenToUse = whenToUseMatch ? whenToUseMatch[1].trim() : `Use for ${title} tasks`;\n const roleDefinition = roleDefinitionMatch\n ? roleDefinitionMatch[1].trim()\n : `You are a ${title} specializing in ${title.toLowerCase()} tasks and responsibilities.`;\n\n // Build mode entry with proper formatting (matching exact indentation)\n // Avoid double \"bmad-\" prefix for agents that already have it\n const slug = agentId.startsWith('bmad-') ? agentId : `bmad-${agentId}`;\n newModesContent += ` - slug: ${slug}\\n`;\n newModesContent += ` name: '${icon} ${title}'\\n`;\n newModesContent += ` roleDefinition: ${roleDefinition}\\n`;\n newModesContent += ` whenToUse: ${whenToUse}\\n`;\n // Get relative path from installDir to agent file\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n newModesContent += ` customInstructions: CRITICAL Read the full YAML from ${relativePath} start activation to alter your state of being follow startup section instructions stay in this being until told to exit this mode\\n`;\n newModesContent += ` groups:\\n`;\n newModesContent += ` - read\\n`;\n\n // Add permissions based on agent type\n const permissions = agentPermissions[agentId];\n if (permissions) {\n newModesContent += ` - - edit\\n`;\n newModesContent += ` - fileRegex: ${permissions.fileRegex}\\n`;\n newModesContent += ` description: ${permissions.description}\\n`;\n } else {\n newModesContent += ` - edit\\n`;\n }\n\n console.log(chalk.green(`āœ“ Added mode: bmad-${agentId} (${icon} ${title})`));\n }\n }\n }\n\n // Build final roomodes content\n let roomodesContent = \"\";\n if (existingContent) {\n // If there's existing content, append new modes to it\n roomodesContent = existingContent.trim() + \"\\n\" + newModesContent;\n } else {\n // Create new .roomodes file with proper YAML structure\n roomodesContent = \"customModes:\\n\" + newModesContent;\n }\n\n // Write .roomodes file\n await fileManager.writeFile(roomodesPath, roomodesContent);\n console.log(chalk.green(\"āœ“ Created .roomodes file in project root\"));\n\n console.log(chalk.green(`\\nāœ“ Roo Code setup complete!`));\n console.log(chalk.dim(\"Custom modes will be available when you open this project in Roo Code\"));\n\n return true;\n }\n\n async setupCline(installDir, selectedAgent) {\n const clineRulesDir = path.join(installDir, \".clinerules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(clineRulesDir);\n\n // Load dynamic agent ordering from configuration\n const config = await this.loadIdeAgentConfig();\n const agentOrder = config['cline-order'] || {};\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n\n // Get numeric prefix for ordering\n const order = agentOrder[agentId] || 99;\n const prefix = order.toString().padStart(2, '0');\n const mdPath = path.join(clineRulesDir, `${prefix}-${agentId}.md`);\n\n // Create MD content for Cline (focused on project standards and role)\n let mdContent = `# ${await this.getAgentTitle(agentId, installDir)} Agent\\n\\n`;\n mdContent += `This rule defines the ${await this.getAgentTitle(agentId, installDir)} persona and project standards.\\n\\n`;\n mdContent += \"## Role Definition\\n\\n\";\n mdContent +=\n \"When the user types `@\" + agentId + \"`, adopt this persona and follow these guidelines:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n } else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## Project Standards\\n\\n\";\n mdContent += `- Always maintain consistency with project documentation in .bmad-core/\\n`;\n mdContent += `- Follow the agent's specific guidelines and constraints\\n`;\n mdContent += `- Update relevant project files when making changes\\n`;\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `- Reference the complete agent definition in [${relativePath}](${relativePath})\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `Type \\`@${agentId}\\` to activate this ${await this.getAgentTitle(agentId, installDir)} persona.\\n`;\n\n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${prefix}-${agentId}.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Cline rules in ${clineRulesDir}`));\n\n return true;\n }\n\n async setupGeminiCli(installDir) {\n const geminiDir = path.join(installDir, \".gemini\");\n const bmadMethodDir = path.join(geminiDir, \"bmad-method\");\n await fileManager.ensureDirectory(bmadMethodDir);\n\n // Update logic for existing settings.json\n const settingsPath = path.join(geminiDir, \"settings.json\");\n if (await fileManager.pathExists(settingsPath)) {\n try {\n const settingsContent = await fileManager.readFile(settingsPath);\n const settings = JSON.parse(settingsContent);\n let updated = false;\n \n // Handle contextFileName property\n if (settings.contextFileName && Array.isArray(settings.contextFileName)) {\n const originalLength = settings.contextFileName.length;\n settings.contextFileName = settings.contextFileName.filter(\n (fileName) => !fileName.startsWith(\"agents/\")\n );\n if (settings.contextFileName.length !== originalLength) {\n updated = true;\n }\n }\n \n if (updated) {\n await fileManager.writeFile(\n settingsPath,\n JSON.stringify(settings, null, 2)\n );\n console.log(chalk.green(\"āœ“ Updated .gemini/settings.json - removed agent file references\"));\n }\n } catch (error) {\n console.warn(\n chalk.yellow(\"Could not update .gemini/settings.json\"),\n error\n );\n }\n }\n\n // Remove old agents directory\n const agentsDir = path.join(geminiDir, \"agents\");\n if (await fileManager.pathExists(agentsDir)) {\n await fileManager.removeDirectory(agentsDir);\n console.log(chalk.green(\"āœ“ Removed old .gemini/agents directory\"));\n }\n\n // Get all available agents\n const agents = await this.getAllAgentIds(installDir);\n let concatenatedContent = \"\";\n\n for (const agentId of agents) {\n // Find the source agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n \n // Create properly formatted agent rule content (similar to trae)\n let agentRuleContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n agentRuleContent += `This rule is triggered when the user types \\`*${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n agentRuleContent += \"## Agent Activation\\n\\n\";\n agentRuleContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n agentRuleContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n agentRuleContent += yamlContent;\n }\n else {\n // If no YAML found, include the whole content minus the header\n agentRuleContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n agentRuleContent += \"\\n```\\n\\n\";\n agentRuleContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n agentRuleContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n agentRuleContent += \"## Usage\\n\\n\";\n agentRuleContent += `When the user types \\`*${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n \n // Add to concatenated content with separator\n concatenatedContent += agentRuleContent + \"\\n\\n---\\n\\n\";\n console.log(chalk.green(`āœ“ Added context for @${agentId}`));\n }\n }\n\n // Write the concatenated content to GEMINI.md\n const geminiMdPath = path.join(bmadMethodDir, \"GEMINI.md\");\n await fileManager.writeFile(geminiMdPath, concatenatedContent);\n console.log(chalk.green(`\\nāœ“ Created GEMINI.md in ${bmadMethodDir}`));\n\n return true;\n }\n\n async setupGitHubCopilot(installDir, selectedAgent, spinner = null, preConfiguredSettings = null) {\n // Configure VS Code workspace settings first to avoid UI conflicts with loading spinners\n await this.configureVsCodeSettings(installDir, spinner, preConfiguredSettings);\n \n const chatmodesDir = path.join(installDir, \".github\", \"chatmodes\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n \n await fileManager.ensureDirectory(chatmodesDir);\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n const chatmodePath = path.join(chatmodesDir, `${agentId}.chatmode.md`);\n\n if (agentPath) {\n // Create chat mode file with agent content\n const agentContent = await fileManager.readFile(agentPath);\n const agentTitle = await this.getAgentTitle(agentId, installDir);\n \n // Extract whenToUse for the description\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n let description = `Activates the ${agentTitle} agent persona.`;\n if (yamlMatch) {\n const whenToUseMatch = yamlMatch[1].match(/whenToUse:\\s*\"(.*?)\"/);\n if (whenToUseMatch && whenToUseMatch[1]) {\n description = whenToUseMatch[1];\n }\n }\n \n let chatmodeContent = `---\ndescription: \"${description.replace(/\"/g, '\\\\\"')}\"\ntools: ['changes', 'codebase', 'fetch', 'findTestFiles', 'githubRepo', 'problems', 'usages', 'editFiles', 'runCommands', 'runTasks', 'runTests', 'search', 'searchResults', 'terminalLastCommand', 'terminalSelection', 'testFailure']\n---\n\n`;\n chatmodeContent += agentContent;\n\n await fileManager.writeFile(chatmodePath, chatmodeContent);\n console.log(chalk.green(`āœ“ Created chat mode: ${agentId}.chatmode.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Github Copilot setup complete!`));\n console.log(chalk.dim(`You can now find the BMad agents in the Chat view's mode selector.`));\n\n return true;\n }\n\n async configureVsCodeSettings(installDir, spinner, preConfiguredSettings = null) {\n const vscodeDir = path.join(installDir, \".vscode\");\n const settingsPath = path.join(vscodeDir, \"settings.json\");\n \n await fileManager.ensureDirectory(vscodeDir);\n \n // Read existing settings if they exist\n let existingSettings = {};\n if (await fileManager.pathExists(settingsPath)) {\n try {\n const existingContent = await fileManager.readFile(settingsPath);\n existingSettings = JSON.parse(existingContent);\n console.log(chalk.yellow(\"Found existing .vscode/settings.json. Merging BMad settings...\"));\n } catch (error) {\n console.warn(chalk.yellow(\"Could not parse existing settings.json. Creating new one.\"));\n existingSettings = {};\n }\n }\n \n // Use pre-configured settings if provided, otherwise prompt\n let configChoice;\n if (preConfiguredSettings && preConfiguredSettings.configChoice) {\n configChoice = preConfiguredSettings.configChoice;\n console.log(chalk.dim(`Using pre-configured GitHub Copilot settings: ${configChoice}`));\n } else {\n // Clear any previous output and add spacing to avoid conflicts with loaders\n console.log('\\n'.repeat(2));\n console.log(chalk.blue(\"šŸ”§ Github Copilot Agent Settings Configuration\"));\n console.log(chalk.dim(\"BMad works best with specific VS Code settings for optimal agent experience.\"));\n console.log(''); // Add extra spacing\n \n const response = await inquirer.prompt([\n {\n type: 'list',\n name: 'configChoice',\n message: chalk.yellow('How would you like to configure GitHub Copilot settings?'),\n choices: [\n {\n name: 'Use recommended defaults (fastest setup)',\n value: 'defaults'\n },\n {\n name: 'Configure each setting manually (customize to your preferences)',\n value: 'manual'\n },\n {\n name: 'Skip settings configuration (I\\'ll configure manually later)',\n value: 'skip'\n }\n ],\n default: 'defaults'\n }\n ]);\n configChoice = response.configChoice;\n }\n \n let bmadSettings = {};\n \n if (configChoice === 'skip') {\n console.log(chalk.yellow(\"āš ļø Skipping VS Code settings configuration.\"));\n console.log(chalk.dim(\"You can manually configure these settings in .vscode/settings.json:\"));\n console.log(chalk.dim(\" • chat.agent.enabled: true\"));\n console.log(chalk.dim(\" • chat.agent.maxRequests: 15\"));\n console.log(chalk.dim(\" • github.copilot.chat.agent.runTasks: true\"));\n console.log(chalk.dim(\" • chat.mcp.discovery.enabled: true\"));\n console.log(chalk.dim(\" • github.copilot.chat.agent.autoFix: true\"));\n console.log(chalk.dim(\" • chat.tools.autoApprove: false\"));\n return true;\n }\n \n if (configChoice === 'defaults') {\n // Use recommended defaults\n bmadSettings = {\n \"chat.agent.enabled\": true,\n \"chat.agent.maxRequests\": 15,\n \"github.copilot.chat.agent.runTasks\": true,\n \"chat.mcp.discovery.enabled\": true,\n \"github.copilot.chat.agent.autoFix\": true,\n \"chat.tools.autoApprove\": false\n };\n console.log(chalk.green(\"āœ“ Using recommended BMad defaults for Github Copilot settings\"));\n } else {\n // Manual configuration\n console.log(chalk.blue(\"\\nšŸ“‹ Let's configure each setting for your preferences:\"));\n \n // Pause spinner during manual configuration prompts\n let spinnerWasActive = false;\n if (spinner && spinner.isSpinning) {\n spinner.stop();\n spinnerWasActive = true;\n }\n \n const manualSettings = await inquirer.prompt([\n {\n type: 'input',\n name: 'maxRequests',\n message: 'Maximum requests per agent session (recommended: 15)?',\n default: '15',\n validate: (input) => {\n const num = parseInt(input);\n if (isNaN(num) || num < 1 || num > 50) {\n return 'Please enter a number between 1 and 50';\n }\n return true;\n }\n },\n {\n type: 'confirm',\n name: 'runTasks',\n message: 'Allow agents to run workspace tasks (package.json scripts, etc.)?',\n default: true\n },\n {\n type: 'confirm',\n name: 'mcpDiscovery',\n message: 'Enable MCP (Model Context Protocol) server discovery?',\n default: true\n },\n {\n type: 'confirm',\n name: 'autoFix',\n message: 'Enable automatic error detection and fixing in generated code?',\n default: true\n },\n {\n type: 'confirm',\n name: 'autoApprove',\n message: 'Auto-approve ALL tools without confirmation? (āš ļø EXPERIMENTAL - less secure)',\n default: false\n }\n ]);\n\n // Restart spinner if it was active before prompts\n if (spinner && spinnerWasActive) {\n spinner.start();\n }\n \n bmadSettings = {\n \"chat.agent.enabled\": true, // Always enabled - required for BMad agents\n \"chat.agent.maxRequests\": parseInt(manualSettings.maxRequests),\n \"github.copilot.chat.agent.runTasks\": manualSettings.runTasks,\n \"chat.mcp.discovery.enabled\": manualSettings.mcpDiscovery,\n \"github.copilot.chat.agent.autoFix\": manualSettings.autoFix,\n \"chat.tools.autoApprove\": manualSettings.autoApprove\n };\n \n console.log(chalk.green(\"āœ“ Custom settings configured\"));\n }\n \n // Merge settings (existing settings take precedence to avoid overriding user preferences)\n const mergedSettings = { ...bmadSettings, ...existingSettings };\n \n // Write the updated settings\n await fileManager.writeFile(settingsPath, JSON.stringify(mergedSettings, null, 2));\n \n console.log(chalk.green(\"āœ“ VS Code workspace settings configured successfully\"));\n console.log(chalk.dim(\" Settings written to .vscode/settings.json:\"));\n Object.entries(bmadSettings).forEach(([key, value]) => {\n console.log(chalk.dim(` • ${key}: ${value}`));\n });\n console.log(chalk.dim(\"\"));\n console.log(chalk.dim(\"You can modify these settings anytime in .vscode/settings.json\"));\n }\n}\n\nmodule.exports = new IdeSetup();\n"], ["/BMAD-METHOD/tools/installer/lib/file-manager.js", "const fs = require(\"fs-extra\");\nconst path = require(\"path\");\nconst crypto = require(\"crypto\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst { createReadStream, createWriteStream, promises: fsPromises } = require('fs');\nconst { pipeline } = require('stream/promises');\nconst resourceLocator = require('./resource-locator');\n\nclass FileManager {\n constructor() {\n this.manifestDir = \".bmad-core\";\n this.manifestFile = \"install-manifest.yaml\";\n }\n\n async copyFile(source, destination) {\n try {\n await fs.ensureDir(path.dirname(destination));\n \n // Use streaming for large files (> 10MB)\n const stats = await fs.stat(source);\n if (stats.size > 10 * 1024 * 1024) {\n await pipeline(\n createReadStream(source),\n createWriteStream(destination)\n );\n } else {\n await fs.copy(source, destination);\n }\n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy ${source}:`), error.message);\n return false;\n }\n }\n\n async copyDirectory(source, destination) {\n try {\n await fs.ensureDir(destination);\n \n // Use streaming copy for large directories\n const files = await resourceLocator.findFiles('**/*', {\n cwd: source,\n nodir: true\n });\n \n // Process files in batches to avoid memory issues\n const batchSize = 50;\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n await Promise.all(\n batch.map(file => \n this.copyFile(\n path.join(source, file),\n path.join(destination, file)\n )\n )\n );\n }\n return true;\n } catch (error) {\n console.error(\n chalk.red(`Failed to copy directory ${source}:`),\n error.message\n );\n return false;\n }\n }\n\n async copyGlobPattern(pattern, sourceDir, destDir, rootValue = null) {\n const files = await resourceLocator.findFiles(pattern, { cwd: sourceDir });\n const copied = [];\n\n for (const file of files) {\n const sourcePath = path.join(sourceDir, file);\n const destPath = path.join(destDir, file);\n\n // Use root replacement if rootValue is provided and file needs it\n const needsRootReplacement = rootValue && (file.endsWith('.md') || file.endsWith('.yaml') || file.endsWith('.yml'));\n \n let success = false;\n if (needsRootReplacement) {\n success = await this.copyFileWithRootReplacement(sourcePath, destPath, rootValue);\n } else {\n success = await this.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n copied.push(file);\n }\n }\n\n return copied;\n }\n\n async calculateFileHash(filePath) {\n try {\n // Use streaming for hash calculation to reduce memory usage\n const stream = createReadStream(filePath);\n const hash = crypto.createHash(\"sha256\");\n \n for await (const chunk of stream) {\n hash.update(chunk);\n }\n \n return hash.digest(\"hex\").slice(0, 16);\n } catch (error) {\n return null;\n }\n }\n\n async createManifest(installDir, config, files) {\n const manifestPath = path.join(\n installDir,\n this.manifestDir,\n this.manifestFile\n );\n\n // Read version from package.json\n let coreVersion = \"unknown\";\n try {\n const packagePath = path.join(__dirname, '..', '..', '..', 'package.json');\n const packageJson = require(packagePath);\n coreVersion = packageJson.version;\n } catch (error) {\n console.warn(\"Could not read version from package.json, using 'unknown'\");\n }\n\n const manifest = {\n version: coreVersion,\n installed_at: new Date().toISOString(),\n install_type: config.installType,\n agent: config.agent || null,\n ides_setup: config.ides || [],\n expansion_packs: config.expansionPacks || [],\n files: [],\n };\n\n // Add file information\n for (const file of files) {\n const filePath = path.join(installDir, file);\n const hash = await this.calculateFileHash(filePath);\n\n manifest.files.push({\n path: file,\n hash: hash,\n modified: false,\n });\n }\n\n // Write manifest\n await fs.ensureDir(path.dirname(manifestPath));\n await fs.writeFile(manifestPath, yaml.dump(manifest, { indent: 2 }));\n\n return manifest;\n }\n\n async readManifest(installDir) {\n const manifestPath = path.join(\n installDir,\n this.manifestDir,\n this.manifestFile\n );\n\n try {\n const content = await fs.readFile(manifestPath, \"utf8\");\n return yaml.load(content);\n } catch (error) {\n return null;\n }\n }\n\n async readExpansionPackManifest(installDir, packId) {\n const manifestPath = path.join(\n installDir,\n `.${packId}`,\n this.manifestFile\n );\n\n try {\n const content = await fs.readFile(manifestPath, \"utf8\");\n return yaml.load(content);\n } catch (error) {\n return null;\n }\n }\n\n async checkModifiedFiles(installDir, manifest) {\n const modified = [];\n\n for (const file of manifest.files) {\n const filePath = path.join(installDir, file.path);\n const currentHash = await this.calculateFileHash(filePath);\n\n if (currentHash && currentHash !== file.hash) {\n modified.push(file.path);\n }\n }\n\n return modified;\n }\n\n async checkFileIntegrity(installDir, manifest) {\n const result = {\n missing: [],\n modified: []\n };\n\n for (const file of manifest.files) {\n const filePath = path.join(installDir, file.path);\n \n // Skip checking the manifest file itself - it will always be different due to timestamps\n if (file.path.endsWith('install-manifest.yaml')) {\n continue;\n }\n \n if (!(await this.pathExists(filePath))) {\n result.missing.push(file.path);\n } else {\n const currentHash = await this.calculateFileHash(filePath);\n if (currentHash && currentHash !== file.hash) {\n result.modified.push(file.path);\n }\n }\n }\n\n return result;\n }\n\n async backupFile(filePath) {\n const backupPath = filePath + \".bak\";\n let counter = 1;\n let finalBackupPath = backupPath;\n\n // Find a unique backup filename\n while (await fs.pathExists(finalBackupPath)) {\n finalBackupPath = `${filePath}.bak${counter}`;\n counter++;\n }\n\n await fs.copy(filePath, finalBackupPath);\n return finalBackupPath;\n }\n\n async ensureDirectory(dirPath) {\n try {\n await fs.ensureDir(dirPath);\n return true;\n } catch (error) {\n throw error;\n }\n }\n\n async pathExists(filePath) {\n return fs.pathExists(filePath);\n }\n\n async readFile(filePath) {\n return fs.readFile(filePath, \"utf8\");\n }\n\n async writeFile(filePath, content) {\n await fs.ensureDir(path.dirname(filePath));\n await fs.writeFile(filePath, content);\n }\n\n async removeDirectory(dirPath) {\n await fs.remove(dirPath);\n }\n\n async createExpansionPackManifest(installDir, packId, config, files) {\n const manifestPath = path.join(\n installDir,\n `.${packId}`,\n this.manifestFile\n );\n\n const manifest = {\n version: config.expansionPackVersion || require(\"../../../package.json\").version,\n installed_at: new Date().toISOString(),\n install_type: config.installType,\n expansion_pack_id: config.expansionPackId,\n expansion_pack_name: config.expansionPackName,\n ides_setup: config.ides || [],\n files: [],\n };\n\n // Add file information\n for (const file of files) {\n const filePath = path.join(installDir, file);\n const hash = await this.calculateFileHash(filePath);\n\n manifest.files.push({\n path: file,\n hash: hash,\n modified: false,\n });\n }\n\n // Write manifest\n await fs.ensureDir(path.dirname(manifestPath));\n await fs.writeFile(manifestPath, yaml.dump(manifest, { indent: 2 }));\n\n return manifest;\n }\n\n async modifyCoreConfig(installDir, config) {\n const coreConfigPath = path.join(installDir, '.bmad-core', 'core-config.yaml');\n \n try {\n // Read the existing core-config.yaml\n const coreConfigContent = await fs.readFile(coreConfigPath, 'utf8');\n const coreConfig = yaml.load(coreConfigContent);\n \n // Modify sharding settings if provided\n if (config.prdSharded !== undefined) {\n coreConfig.prd.prdSharded = config.prdSharded;\n }\n \n if (config.architectureSharded !== undefined) {\n coreConfig.architecture.architectureSharded = config.architectureSharded;\n }\n \n // Write back the modified config\n await fs.writeFile(coreConfigPath, yaml.dump(coreConfig, { indent: 2 }));\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to modify core-config.yaml:`), error.message);\n return false;\n }\n }\n\n async copyFileWithRootReplacement(source, destination, rootValue) {\n try {\n // Check file size to determine if we should stream\n const stats = await fs.stat(source);\n \n if (stats.size > 5 * 1024 * 1024) { // 5MB threshold\n // Use streaming for large files\n const { Transform } = require('stream');\n const replaceStream = new Transform({\n transform(chunk, encoding, callback) {\n const modified = chunk.toString().replace(/\\{root\\}/g, rootValue);\n callback(null, modified);\n }\n });\n \n await this.ensureDirectory(path.dirname(destination));\n await pipeline(\n createReadStream(source, { encoding: 'utf8' }),\n replaceStream,\n createWriteStream(destination, { encoding: 'utf8' })\n );\n } else {\n // Regular approach for smaller files\n const content = await fsPromises.readFile(source, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, rootValue);\n await this.ensureDirectory(path.dirname(destination));\n await fsPromises.writeFile(destination, updatedContent, 'utf8');\n }\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy ${source} with root replacement:`), error.message);\n return false;\n }\n }\n\n async copyDirectoryWithRootReplacement(source, destination, rootValue, fileExtensions = ['.md', '.yaml', '.yml']) {\n try {\n await this.ensureDirectory(destination);\n \n // Get all files in source directory\n const files = await resourceLocator.findFiles('**/*', { \n cwd: source, \n nodir: true \n });\n \n let replacedCount = 0;\n \n for (const file of files) {\n const sourcePath = path.join(source, file);\n const destPath = path.join(destination, file);\n \n // Check if this file type should have {root} replacement\n const shouldReplace = fileExtensions.some(ext => file.endsWith(ext));\n \n if (shouldReplace) {\n if (await this.copyFileWithRootReplacement(sourcePath, destPath, rootValue)) {\n replacedCount++;\n }\n } else {\n // Regular copy for files that don't need replacement\n await this.copyFile(sourcePath, destPath);\n }\n }\n \n if (replacedCount > 0) {\n console.log(chalk.dim(` Processed ${replacedCount} files with {root} replacement`));\n }\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy directory ${source} with root replacement:`), error.message);\n return false;\n }\n }\n}\n\nmodule.exports = new FileManager();\n"], ["/BMAD-METHOD/tools/flattener/main.js", "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst fs = require('fs-extra');\nconst path = require('node:path');\nconst { glob } = require('glob');\nconst { minimatch } = require('minimatch');\n\n/**\n * Recursively discover all files in a directory\n * @param {string} rootDir - The root directory to scan\n * @returns {Promise} Array of file paths\n */\nasync function discoverFiles(rootDir) {\n try {\n const gitignorePath = path.join(rootDir, '.gitignore');\n const gitignorePatterns = await parseGitignore(gitignorePath);\n\n // Common gitignore patterns that should always be ignored\n const commonIgnorePatterns = [\n // Version control\n '.git/**',\n '.svn/**',\n '.hg/**',\n '.bzr/**',\n\n // Dependencies\n 'node_modules/**',\n 'bower_components/**',\n 'vendor/**',\n 'packages/**',\n\n // Build outputs\n 'build/**',\n 'dist/**',\n 'out/**',\n 'target/**',\n 'bin/**',\n 'obj/**',\n 'release/**',\n 'debug/**',\n\n // Environment and config\n '.env',\n '.env.*',\n '*.env',\n '.config',\n\n // Logs\n 'logs/**',\n '*.log',\n 'npm-debug.log*',\n 'yarn-debug.log*',\n 'yarn-error.log*',\n 'lerna-debug.log*',\n\n // Coverage and testing\n 'coverage/**',\n '.nyc_output/**',\n '.coverage/**',\n 'test-results/**',\n 'junit.xml',\n\n // Cache directories\n '.cache/**',\n '.tmp/**',\n '.temp/**',\n 'tmp/**',\n 'temp/**',\n '.sass-cache/**',\n '.eslintcache',\n '.stylelintcache',\n\n // OS generated files\n '.DS_Store',\n '.DS_Store?',\n '._*',\n '.Spotlight-V100',\n '.Trashes',\n 'ehthumbs.db',\n 'Thumbs.db',\n 'desktop.ini',\n\n // IDE and editor files\n '.vscode/**',\n '.idea/**',\n '*.swp',\n '*.swo',\n '*~',\n '.project',\n '.classpath',\n '.settings/**',\n '*.sublime-project',\n '*.sublime-workspace',\n\n // Package manager files\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Pipfile.lock',\n\n // Runtime and compiled files\n '*.pyc',\n '*.pyo',\n '*.pyd',\n '__pycache__/**',\n '*.class',\n '*.jar',\n '*.war',\n '*.ear',\n '*.o',\n '*.so',\n '*.dll',\n '*.exe',\n\n // Documentation build\n '_site/**',\n '.jekyll-cache/**',\n '.jekyll-metadata',\n\n // Flattener specific outputs\n 'flattened-codebase.xml',\n 'repomix-output.xml'\n ];\n\n const combinedIgnores = [\n ...gitignorePatterns,\n ...commonIgnorePatterns\n ];\n\n // Use glob to recursively find all files, excluding common ignore patterns\n const files = await glob('**/*', {\n cwd: rootDir,\n nodir: true, // Only files, not directories\n dot: true, // Include hidden files\n follow: false, // Don't follow symbolic links\n ignore: combinedIgnores\n });\n\n return files.map(file => path.resolve(rootDir, file));\n } catch (error) {\n console.error('Error discovering files:', error.message);\n return [];\n }\n}\n\n/**\n * Parse .gitignore file and return ignore patterns\n * @param {string} gitignorePath - Path to .gitignore file\n * @returns {Promise} Array of ignore patterns\n */\nasync function parseGitignore(gitignorePath) {\n try {\n if (!await fs.pathExists(gitignorePath)) {\n return [];\n }\n\n const content = await fs.readFile(gitignorePath, 'utf8');\n return content\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line && !line.startsWith('#')) // Remove empty lines and comments\n .map(pattern => {\n // Convert gitignore patterns to glob patterns\n if (pattern.endsWith('/')) {\n return pattern + '**';\n }\n return pattern;\n });\n } catch (error) {\n console.error('Error parsing .gitignore:', error.message);\n return [];\n }\n}\n\n/**\n * Check if a file is binary using file command and heuristics\n * @param {string} filePath - Path to the file\n * @returns {Promise} True if file is binary\n */\nasync function isBinaryFile(filePath) {\n try {\n // First check by file extension\n const binaryExtensions = [\n '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.ico', '.svg',\n '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',\n '.zip', '.tar', '.gz', '.rar', '.7z',\n '.exe', '.dll', '.so', '.dylib',\n '.mp3', '.mp4', '.avi', '.mov', '.wav',\n '.ttf', '.otf', '.woff', '.woff2',\n '.bin', '.dat', '.db', '.sqlite'\n ];\n\n const ext = path.extname(filePath).toLowerCase();\n if (binaryExtensions.includes(ext)) {\n return true;\n }\n\n // For files without clear extensions, try to read a small sample\n const stats = await fs.stat(filePath);\n if (stats.size === 0) {\n return false; // Empty files are considered text\n }\n\n // Read first 1024 bytes to check for null bytes\n const sampleSize = Math.min(1024, stats.size);\n const buffer = await fs.readFile(filePath, { encoding: null, flag: 'r' });\n const sample = buffer.slice(0, sampleSize);\n // If we find null bytes, it's likely binary\n return sample.includes(0);\n } catch (error) {\n console.warn(`Warning: Could not determine if file is binary: ${filePath} - ${error.message}`);\n return false; // Default to text if we can't determine\n }\n}\n\n/**\n * Read and aggregate content from text files\n * @param {string[]} files - Array of file paths\n * @param {string} rootDir - The root directory\n * @param {Object} spinner - Optional spinner instance for progress display\n * @returns {Promise} Object containing file contents and metadata\n */\nasync function aggregateFileContents(files, rootDir, spinner = null) {\n const results = {\n textFiles: [],\n binaryFiles: [],\n errors: [],\n totalFiles: files.length,\n processedFiles: 0\n };\n\n for (const filePath of files) {\n try {\n const relativePath = path.relative(rootDir, filePath);\n\n // Update progress indicator\n if (spinner) {\n spinner.text = `Processing file ${results.processedFiles + 1}/${results.totalFiles}: ${relativePath}`;\n }\n\n const isBinary = await isBinaryFile(filePath);\n\n if (isBinary) {\n results.binaryFiles.push({\n path: relativePath,\n absolutePath: filePath,\n size: (await fs.stat(filePath)).size\n });\n } else {\n // Read text file content\n const content = await fs.readFile(filePath, 'utf8');\n results.textFiles.push({\n path: relativePath,\n absolutePath: filePath,\n content: content,\n size: content.length,\n lines: content.split('\\n').length\n });\n }\n\n results.processedFiles++;\n } catch (error) {\n const relativePath = path.relative(rootDir, filePath);\n const errorInfo = {\n path: relativePath,\n absolutePath: filePath,\n error: error.message\n };\n\n results.errors.push(errorInfo);\n\n // Log warning without interfering with spinner\n if (spinner) {\n spinner.warn(`Warning: Could not read file ${relativePath}: ${error.message}`);\n } else {\n console.warn(`Warning: Could not read file ${relativePath}: ${error.message}`);\n }\n\n results.processedFiles++;\n }\n }\n\n return results;\n}\n\n/**\n * Generate XML output with aggregated file contents using streaming\n * @param {Object} aggregatedContent - The aggregated content object\n * @param {string} outputPath - The output file path\n * @returns {Promise} Promise that resolves when writing is complete\n */\nasync function generateXMLOutput(aggregatedContent, outputPath) {\n const { textFiles } = aggregatedContent;\n\n // Create write stream for efficient memory usage\n const writeStream = fs.createWriteStream(outputPath, { encoding: 'utf8' });\n\n return new Promise((resolve, reject) => {\n writeStream.on('error', reject);\n writeStream.on('finish', resolve);\n\n // Write XML header\n writeStream.write('\\n');\n writeStream.write('\\n');\n\n // Process files one by one to minimize memory usage\n let fileIndex = 0;\n\n const writeNextFile = () => {\n if (fileIndex >= textFiles.length) {\n // All files processed, close XML and stream\n writeStream.write('\\n');\n writeStream.end();\n return;\n }\n\n const file = textFiles[fileIndex];\n fileIndex++;\n\n // Write file opening tag\n writeStream.write(` `);\n\n // Use CDATA for code content, handling CDATA end sequences properly\n if (file.content?.trim()) {\n const indentedContent = indentFileContent(file.content);\n if (file.content.includes(']]>')) {\n // If content contains ]]>, split it and wrap each part in CDATA\n writeStream.write(splitAndWrapCDATA(indentedContent));\n } else {\n writeStream.write(``);\n }\n } else if (file.content) {\n // Handle empty or whitespace-only content\n const indentedContent = indentFileContent(file.content);\n writeStream.write(``);\n }\n\n // Write file closing tag\n writeStream.write('\\n');\n\n // Continue with next file on next tick to avoid stack overflow\n setImmediate(writeNextFile);\n };\n\n // Start processing files\n writeNextFile();\n });\n}\n\n/**\n * Escape XML special characters for attributes\n * @param {string} str - String to escape\n * @returns {string} Escaped string\n */\nfunction escapeXml(str) {\n if (typeof str !== 'string') {\n return String(str);\n }\n return str\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Indent file content with 4 spaces for each line\n * @param {string} content - Content to indent\n * @returns {string} Indented content\n */\nfunction indentFileContent(content) {\n if (typeof content !== 'string') {\n return String(content);\n }\n\n // Split content into lines and add 4 spaces of indentation to each line\n return content.split('\\n').map(line => ` ${line}`).join('\\n');\n}\n\n/**\n * Split content containing ]]> and wrap each part in CDATA\n * @param {string} content - Content to process\n * @returns {string} Content with properly wrapped CDATA sections\n */\nfunction splitAndWrapCDATA(content) {\n if (typeof content !== 'string') {\n return String(content);\n }\n\n // Replace ]]> with ]]]]> to escape it within CDATA\n const escapedContent = content.replace(/]]>/g, ']]]]>');\n return ``;\n}\n\n/**\n * Calculate statistics for the processed files\n * @param {Object} aggregatedContent - The aggregated content object\n * @param {number} xmlFileSize - The size of the generated XML file in bytes\n * @returns {Object} Statistics object\n */\nfunction calculateStatistics(aggregatedContent, xmlFileSize) {\n const { textFiles, binaryFiles, errors } = aggregatedContent;\n\n // Calculate total file size in bytes\n const totalTextSize = textFiles.reduce((sum, file) => sum + file.size, 0);\n const totalBinarySize = binaryFiles.reduce((sum, file) => sum + file.size, 0);\n const totalSize = totalTextSize + totalBinarySize;\n\n // Calculate total lines of code\n const totalLines = textFiles.reduce((sum, file) => sum + file.lines, 0);\n\n // Estimate token count (rough approximation: 1 token ā‰ˆ 4 characters)\n const estimatedTokens = Math.ceil(xmlFileSize / 4);\n\n // Format file size\n const formatSize = (bytes) => {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n };\n\n return {\n totalFiles: textFiles.length + binaryFiles.length,\n textFiles: textFiles.length,\n binaryFiles: binaryFiles.length,\n errorFiles: errors.length,\n totalSize: formatSize(totalSize),\n xmlSize: formatSize(xmlFileSize),\n totalLines,\n estimatedTokens: estimatedTokens.toLocaleString()\n };\n}\n\n/**\n * Filter files based on .gitignore patterns\n * @param {string[]} files - Array of file paths\n * @param {string} rootDir - The root directory\n * @returns {Promise} Filtered array of file paths\n */\nasync function filterFiles(files, rootDir) {\n const gitignorePath = path.join(rootDir, '.gitignore');\n const ignorePatterns = await parseGitignore(gitignorePath);\n\n if (ignorePatterns.length === 0) {\n return files;\n }\n\n // Convert absolute paths to relative for pattern matching\n const relativeFiles = files.map(file => path.relative(rootDir, file));\n\n // Separate positive and negative patterns\n const positivePatterns = ignorePatterns.filter(p => !p.startsWith('!'));\n const negativePatterns = ignorePatterns.filter(p => p.startsWith('!')).map(p => p.slice(1));\n\n // Filter out files that match ignore patterns\n const filteredRelative = [];\n\n for (const file of relativeFiles) {\n let shouldIgnore = false;\n\n // First check positive patterns (ignore these files)\n for (const pattern of positivePatterns) {\n if (minimatch(file, pattern)) {\n shouldIgnore = true;\n break;\n }\n }\n\n // Then check negative patterns (don't ignore these files even if they match positive patterns)\n if (shouldIgnore) {\n for (const pattern of negativePatterns) {\n if (minimatch(file, pattern)) {\n shouldIgnore = false;\n break;\n }\n }\n }\n\n if (!shouldIgnore) {\n filteredRelative.push(file);\n }\n }\n\n // Convert back to absolute paths\n return filteredRelative.map(file => path.resolve(rootDir, file));\n}\n\nconst program = new Command();\n\nprogram\n .name('bmad-flatten')\n .description('BMad-Method codebase flattener tool')\n .version('1.0.0')\n .option('-o, --output ', 'Output file path', 'flattened-codebase.xml')\n .action(async (options) => {\n console.log(`Flattening codebase to: ${options.output}`);\n\n try {\n // Import ora dynamically\n const { default: ora } = await import('ora');\n\n // Start file discovery with spinner\n const discoverySpinner = ora('šŸ” Discovering files...').start();\n const files = await discoverFiles(process.cwd());\n const filteredFiles = await filterFiles(files, process.cwd());\n discoverySpinner.succeed(`šŸ“ Found ${filteredFiles.length} files to include`);\n\n // Process files with progress tracking\n console.log('Reading file contents');\n const processingSpinner = ora('šŸ“„ Processing files...').start();\n const aggregatedContent = await aggregateFileContents(filteredFiles, process.cwd(), processingSpinner);\n processingSpinner.succeed(`āœ… Processed ${aggregatedContent.processedFiles}/${filteredFiles.length} files`);\n\n // Log processing results for test validation\n console.log(`Processed ${aggregatedContent.processedFiles}/${filteredFiles.length} files`);\n if (aggregatedContent.errors.length > 0) {\n console.log(`Errors: ${aggregatedContent.errors.length}`);\n }\n console.log(`Text files: ${aggregatedContent.textFiles.length}`);\n if (aggregatedContent.binaryFiles.length > 0) {\n console.log(`Binary files: ${aggregatedContent.binaryFiles.length}`);\n }\n\n // Generate XML output using streaming\n const xmlSpinner = ora('šŸ”§ Generating XML output...').start();\n await generateXMLOutput(aggregatedContent, options.output);\n xmlSpinner.succeed('šŸ“ XML generation completed');\n\n // Calculate and display statistics\n const outputStats = await fs.stat(options.output);\n const stats = calculateStatistics(aggregatedContent, outputStats.size);\n\n // Display completion summary\n console.log('\\nšŸ“Š Completion Summary:');\n console.log(`āœ… Successfully processed ${filteredFiles.length} files into ${options.output}`);\n console.log(`šŸ“ Output file: ${path.resolve(options.output)}`);\n console.log(`šŸ“ Total source size: ${stats.totalSize}`);\n console.log(`šŸ“„ Generated XML size: ${stats.xmlSize}`);\n console.log(`šŸ“ Total lines of code: ${stats.totalLines.toLocaleString()}`);\n console.log(`šŸ”¢ Estimated tokens: ${stats.estimatedTokens}`);\n console.log(`šŸ“Š File breakdown: ${stats.textFiles} text, ${stats.binaryFiles} binary, ${stats.errorFiles} errors`);\n\n } catch (error) {\n console.error('āŒ Critical error:', error.message);\n console.error('An unexpected error occurred.');\n process.exit(1);\n }\n });\n\nif (require.main === module) {\n program.parse();\n}\n\nmodule.exports = program;\n"], ["/BMAD-METHOD/tools/builders/web-builder.js", "const fs = require(\"node:fs\").promises;\nconst path = require(\"node:path\");\nconst DependencyResolver = require(\"../lib/dependency-resolver\");\nconst yamlUtils = require(\"../lib/yaml-utils\");\n\nclass WebBuilder {\n constructor(options = {}) {\n this.rootDir = options.rootDir || process.cwd();\n this.outputDirs = options.outputDirs || [path.join(this.rootDir, \"dist\")];\n this.resolver = new DependencyResolver(this.rootDir);\n this.templatePath = path.join(\n this.rootDir,\n \"tools\",\n \"md-assets\",\n \"web-agent-startup-instructions.md\"\n );\n }\n\n parseYaml(content) {\n const yaml = require(\"js-yaml\");\n return yaml.load(content);\n }\n\n convertToWebPath(filePath, bundleRoot = 'bmad-core') {\n // Convert absolute paths to web bundle paths with dot prefix\n // All resources get installed under the bundle root, so use that path\n const relativePath = path.relative(this.rootDir, filePath);\n const pathParts = relativePath.split(path.sep);\n \n let resourcePath;\n if (pathParts[0] === 'expansion-packs') {\n // For expansion packs, remove 'expansion-packs/packname' and use the rest\n resourcePath = pathParts.slice(2).join('/');\n } else {\n // For bmad-core, common, etc., remove the first part\n resourcePath = pathParts.slice(1).join('/');\n }\n \n return `.${bundleRoot}/${resourcePath}`;\n }\n\n generateWebInstructions(bundleType, packName = null) {\n // Generate dynamic web instructions based on bundle type\n const rootExample = packName ? `.${packName}` : '.bmad-core';\n const examplePath = packName ? `.${packName}/folder/filename.md` : '.bmad-core/folder/filename.md';\n const personasExample = packName ? `.${packName}/personas/analyst.md` : '.bmad-core/personas/analyst.md';\n const tasksExample = packName ? `.${packName}/tasks/create-story.md` : '.bmad-core/tasks/create-story.md';\n const utilsExample = packName ? `.${packName}/utils/template-format.md` : '.bmad-core/utils/template-format.md';\n const tasksRef = packName ? `.${packName}/tasks/create-story.md` : '.bmad-core/tasks/create-story.md';\n\n return `# Web Agent Bundle Instructions\n\nYou are now operating as a specialized AI agent from the BMad-Method framework. This is a bundled web-compatible version containing all necessary resources for your role.\n\n## Important Instructions\n\n1. **Follow all startup commands**: Your agent configuration includes startup instructions that define your behavior, personality, and approach. These MUST be followed exactly.\n\n2. **Resource Navigation**: This bundle contains all resources you need. Resources are marked with tags like:\n\n- \\`==================== START: ${examplePath} ====================\\`\n- \\`==================== END: ${examplePath} ====================\\`\n\nWhen you need to reference a resource mentioned in your instructions:\n\n- Look for the corresponding START/END tags\n- The format is always the full path with dot prefix (e.g., \\`${personasExample}\\`, \\`${tasksExample}\\`)\n- If a section is specified (e.g., \\`{root}/tasks/create-story.md#section-name\\`), navigate to that section within the file\n\n**Understanding YAML References**: In the agent configuration, resources are referenced in the dependencies section. For example:\n\n\\`\\`\\`yaml\ndependencies:\n utils:\n - template-format\n tasks:\n - create-story\n\\`\\`\\`\n\nThese references map directly to bundle sections:\n\n- \\`utils: template-format\\` → Look for \\`==================== START: ${utilsExample} ====================\\`\n- \\`tasks: create-story\\` → Look for \\`==================== START: ${tasksRef} ====================\\`\n\n3. **Execution Context**: You are operating in a web environment. All your capabilities and knowledge are contained within this bundle. Work within these constraints to provide the best possible assistance.\n\n4. **Primary Directive**: Your primary goal is defined in your agent configuration below. Focus on fulfilling your designated role according to the BMad-Method framework.\n\n---\n\n`;\n }\n\n async cleanOutputDirs() {\n for (const dir of this.outputDirs) {\n try {\n await fs.rm(dir, { recursive: true, force: true });\n console.log(`Cleaned: ${path.relative(this.rootDir, dir)}`);\n } catch (error) {\n console.debug(`Failed to clean directory ${dir}:`, error.message);\n // Directory might not exist, that's fine\n }\n }\n }\n\n async buildAgents() {\n const agents = await this.resolver.listAgents();\n\n for (const agentId of agents) {\n console.log(` Building agent: ${agentId}`);\n const bundle = await this.buildAgentBundle(agentId);\n\n // Write to all output directories\n for (const outputDir of this.outputDirs) {\n const outputPath = path.join(outputDir, \"agents\");\n await fs.mkdir(outputPath, { recursive: true });\n const outputFile = path.join(outputPath, `${agentId}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n\n console.log(`Built ${agents.length} agent bundles in ${this.outputDirs.length} locations`);\n }\n\n async buildTeams() {\n const teams = await this.resolver.listTeams();\n\n for (const teamId of teams) {\n console.log(` Building team: ${teamId}`);\n const bundle = await this.buildTeamBundle(teamId);\n\n // Write to all output directories\n for (const outputDir of this.outputDirs) {\n const outputPath = path.join(outputDir, \"teams\");\n await fs.mkdir(outputPath, { recursive: true });\n const outputFile = path.join(outputPath, `${teamId}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n\n console.log(`Built ${teams.length} team bundles in ${this.outputDirs.length} locations`);\n }\n\n async buildAgentBundle(agentId) {\n const dependencies = await this.resolver.resolveAgentDependencies(agentId);\n const template = this.generateWebInstructions('agent');\n\n const sections = [template];\n\n // Add agent configuration\n const agentPath = this.convertToWebPath(dependencies.agent.path, 'bmad-core');\n sections.push(this.formatSection(agentPath, dependencies.agent.content, 'bmad-core'));\n\n // Add all dependencies\n for (const resource of dependencies.resources) {\n const resourcePath = this.convertToWebPath(resource.path, 'bmad-core');\n sections.push(this.formatSection(resourcePath, resource.content, 'bmad-core'));\n }\n\n return sections.join(\"\\n\");\n }\n\n async buildTeamBundle(teamId) {\n const dependencies = await this.resolver.resolveTeamDependencies(teamId);\n const template = this.generateWebInstructions('team');\n\n const sections = [template];\n\n // Add team configuration\n const teamPath = this.convertToWebPath(dependencies.team.path, 'bmad-core');\n sections.push(this.formatSection(teamPath, dependencies.team.content, 'bmad-core'));\n\n // Add all agents\n for (const agent of dependencies.agents) {\n const agentPath = this.convertToWebPath(agent.path, 'bmad-core');\n sections.push(this.formatSection(agentPath, agent.content, 'bmad-core'));\n }\n\n // Add all deduplicated resources\n for (const resource of dependencies.resources) {\n const resourcePath = this.convertToWebPath(resource.path, 'bmad-core');\n sections.push(this.formatSection(resourcePath, resource.content, 'bmad-core'));\n }\n\n return sections.join(\"\\n\");\n }\n\n processAgentContent(content) {\n // First, replace content before YAML with the template\n const yamlContent = yamlUtils.extractYamlFromAgent(content);\n if (!yamlContent) return content;\n\n const yamlMatch = content.match(/```ya?ml\\n([\\s\\S]*?)\\n```/);\n if (!yamlMatch) return content;\n \n const yamlStartIndex = content.indexOf(yamlMatch[0]);\n const yamlEndIndex = yamlStartIndex + yamlMatch[0].length;\n\n // Parse YAML and remove root and IDE-FILE-RESOLUTION properties\n try {\n const yaml = require(\"js-yaml\");\n const parsed = yaml.load(yamlContent);\n\n // Remove the properties if they exist at root level\n delete parsed.root;\n delete parsed[\"IDE-FILE-RESOLUTION\"];\n delete parsed[\"REQUEST-RESOLUTION\"];\n\n // Also remove from activation-instructions if they exist\n if (parsed[\"activation-instructions\"] && Array.isArray(parsed[\"activation-instructions\"])) {\n parsed[\"activation-instructions\"] = parsed[\"activation-instructions\"].filter(\n (instruction) => {\n return (\n typeof instruction === 'string' &&\n !instruction.startsWith(\"IDE-FILE-RESOLUTION:\") &&\n !instruction.startsWith(\"REQUEST-RESOLUTION:\")\n );\n }\n );\n }\n\n // Reconstruct the YAML\n const cleanedYaml = yaml.dump(parsed, { lineWidth: -1 });\n\n // Get the agent name from the YAML for the header\n const agentName = parsed.agent?.id || \"agent\";\n\n // Build the new content with just the agent header and YAML\n const newHeader = `# ${agentName}\\n\\nCRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n`;\n const afterYaml = content.substring(yamlEndIndex);\n\n return newHeader + \"```yaml\\n\" + cleanedYaml.trim() + \"\\n```\" + afterYaml;\n } catch (error) {\n console.warn(\"Failed to process agent YAML:\", error.message);\n // If parsing fails, return original content\n return content;\n }\n }\n\n formatSection(path, content, bundleRoot = 'bmad-core') {\n const separator = \"====================\";\n\n // Process agent content if this is an agent file\n if (path.includes(\"/agents/\")) {\n content = this.processAgentContent(content);\n }\n\n // Replace {root} references with the actual bundle root\n content = this.replaceRootReferences(content, bundleRoot);\n\n return [\n `${separator} START: ${path} ${separator}`,\n content.trim(),\n `${separator} END: ${path} ${separator}`,\n \"\",\n ].join(\"\\n\");\n }\n\n replaceRootReferences(content, bundleRoot) {\n // Replace {root} with the appropriate bundle root path\n return content.replace(/\\{root\\}/g, `.${bundleRoot}`);\n }\n\n async validate() {\n console.log(\"Validating agent configurations...\");\n const agents = await this.resolver.listAgents();\n for (const agentId of agents) {\n try {\n await this.resolver.resolveAgentDependencies(agentId);\n console.log(` āœ“ ${agentId}`);\n } catch (error) {\n console.log(` āœ— ${agentId}: ${error.message}`);\n throw error;\n }\n }\n\n console.log(\"\\nValidating team configurations...\");\n const teams = await this.resolver.listTeams();\n for (const teamId of teams) {\n try {\n await this.resolver.resolveTeamDependencies(teamId);\n console.log(` āœ“ ${teamId}`);\n } catch (error) {\n console.log(` āœ— ${teamId}: ${error.message}`);\n throw error;\n }\n }\n }\n\n async buildAllExpansionPacks(options = {}) {\n const expansionPacks = await this.listExpansionPacks();\n\n for (const packName of expansionPacks) {\n console.log(` Building expansion pack: ${packName}`);\n await this.buildExpansionPack(packName, options);\n }\n\n console.log(`Built ${expansionPacks.length} expansion pack bundles`);\n }\n\n async buildExpansionPack(packName, options = {}) {\n const packDir = path.join(this.rootDir, \"expansion-packs\", packName);\n const outputDirs = [path.join(this.rootDir, \"dist\", \"expansion-packs\", packName)];\n\n // Clean output directories if requested\n if (options.clean !== false) {\n for (const outputDir of outputDirs) {\n try {\n await fs.rm(outputDir, { recursive: true, force: true });\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n }\n\n // Build individual agents first\n const agentsDir = path.join(packDir, \"agents\");\n try {\n const agentFiles = await fs.readdir(agentsDir);\n const agentMarkdownFiles = agentFiles.filter((f) => f.endsWith(\".md\"));\n\n if (agentMarkdownFiles.length > 0) {\n console.log(` Building individual agents for ${packName}:`);\n\n for (const agentFile of agentMarkdownFiles) {\n const agentName = agentFile.replace(\".md\", \"\");\n console.log(` - ${agentName}`);\n\n // Build individual agent bundle\n const bundle = await this.buildExpansionAgentBundle(packName, packDir, agentName);\n\n // Write to all output directories\n for (const outputDir of outputDirs) {\n const agentsOutputDir = path.join(outputDir, \"agents\");\n await fs.mkdir(agentsOutputDir, { recursive: true });\n const outputFile = path.join(agentsOutputDir, `${agentName}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n }\n } catch (error) {\n console.debug(` No agents directory found for ${packName}`);\n }\n\n // Build team bundle\n const agentTeamsDir = path.join(packDir, \"agent-teams\");\n try {\n const teamFiles = await fs.readdir(agentTeamsDir);\n const teamFile = teamFiles.find((f) => f.endsWith(\".yaml\"));\n\n if (teamFile) {\n console.log(` Building team bundle for ${packName}`);\n const teamConfigPath = path.join(agentTeamsDir, teamFile);\n\n // Build expansion pack as a team bundle\n const bundle = await this.buildExpansionTeamBundle(packName, packDir, teamConfigPath);\n\n // Write to all output directories\n for (const outputDir of outputDirs) {\n const teamsOutputDir = path.join(outputDir, \"teams\");\n await fs.mkdir(teamsOutputDir, { recursive: true });\n const outputFile = path.join(teamsOutputDir, teamFile.replace(\".yaml\", \".txt\"));\n await fs.writeFile(outputFile, bundle, \"utf8\");\n console.log(` āœ“ Created bundle: ${path.relative(this.rootDir, outputFile)}`);\n }\n } else {\n console.warn(` ⚠ No team configuration found in ${packName}/agent-teams/`);\n }\n } catch (error) {\n console.warn(` ⚠ No agent-teams directory found for ${packName}`);\n }\n }\n\n async buildExpansionAgentBundle(packName, packDir, agentName) {\n const template = this.generateWebInstructions('expansion-agent', packName);\n const sections = [template];\n\n // Add agent configuration\n const agentPath = path.join(packDir, \"agents\", `${agentName}.md`);\n const agentContent = await fs.readFile(agentPath, \"utf8\");\n const agentWebPath = this.convertToWebPath(agentPath, packName);\n sections.push(this.formatSection(agentWebPath, agentContent, packName));\n\n // Resolve and add agent dependencies\n const yamlContent = yamlUtils.extractYamlFromAgent(agentContent);\n if (yamlContent) {\n try {\n const yaml = require(\"js-yaml\");\n const agentConfig = yaml.load(yamlContent);\n\n if (agentConfig.dependencies) {\n // Add resources, first try expansion pack, then core\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n let found = false;\n\n // Try expansion pack first\n const resourcePath = path.join(packDir, resourceType, resourceName);\n try {\n const resourceContent = await fs.readFile(resourcePath, \"utf8\");\n const resourceWebPath = this.convertToWebPath(resourcePath, packName);\n sections.push(\n this.formatSection(resourceWebPath, resourceContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in expansion pack, continue\n }\n\n // If not found in expansion pack, try core\n if (!found) {\n const corePath = path.join(\n this.rootDir,\n \"bmad-core\",\n resourceType,\n resourceName\n );\n try {\n const coreContent = await fs.readFile(corePath, \"utf8\");\n const coreWebPath = this.convertToWebPath(corePath, packName);\n sections.push(\n this.formatSection(coreWebPath, coreContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in core either, continue\n }\n }\n\n // If not found in core, try common folder\n if (!found) {\n const commonPath = path.join(\n this.rootDir,\n \"common\",\n resourceType,\n resourceName\n );\n try {\n const commonContent = await fs.readFile(commonPath, \"utf8\");\n const commonWebPath = this.convertToWebPath(commonPath, packName);\n sections.push(\n this.formatSection(commonWebPath, commonContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in common either, continue\n }\n }\n\n if (!found) {\n console.warn(\n ` ⚠ Dependency ${resourceType}#${resourceName} not found in expansion pack or core`\n );\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentName}:`, error.message);\n }\n }\n\n return sections.join(\"\\n\");\n }\n\n async buildExpansionTeamBundle(packName, packDir, teamConfigPath) {\n const template = this.generateWebInstructions('expansion-team', packName);\n\n const sections = [template];\n\n // Add team configuration and parse to get agent list\n const teamContent = await fs.readFile(teamConfigPath, \"utf8\");\n const teamFileName = path.basename(teamConfigPath, \".yaml\");\n const teamConfig = this.parseYaml(teamContent);\n const teamWebPath = this.convertToWebPath(teamConfigPath, packName);\n sections.push(this.formatSection(teamWebPath, teamContent, packName));\n\n // Get list of expansion pack agents\n const expansionAgents = new Set();\n const agentsDir = path.join(packDir, \"agents\");\n try {\n const agentFiles = await fs.readdir(agentsDir);\n for (const agentFile of agentFiles.filter((f) => f.endsWith(\".md\"))) {\n const agentName = agentFile.replace(\".md\", \"\");\n expansionAgents.add(agentName);\n }\n } catch (error) {\n console.warn(` ⚠ No agents directory found in ${packName}`);\n }\n\n // Build a map of all available expansion pack resources for override checking\n const expansionResources = new Map();\n const resourceDirs = [\"templates\", \"tasks\", \"checklists\", \"workflows\", \"data\"];\n for (const resourceDir of resourceDirs) {\n const resourcePath = path.join(packDir, resourceDir);\n try {\n const resourceFiles = await fs.readdir(resourcePath);\n for (const resourceFile of resourceFiles.filter(\n (f) => f.endsWith(\".md\") || f.endsWith(\".yaml\")\n )) {\n expansionResources.set(`${resourceDir}#${resourceFile}`, true);\n }\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n\n // Process all agents listed in team configuration\n const agentsToProcess = teamConfig.agents || [];\n\n // Ensure bmad-orchestrator is always included for teams\n if (!agentsToProcess.includes(\"bmad-orchestrator\")) {\n console.warn(` ⚠ Team ${teamFileName} missing bmad-orchestrator, adding automatically`);\n agentsToProcess.unshift(\"bmad-orchestrator\");\n }\n\n // Track all dependencies from all agents (deduplicated)\n const allDependencies = new Map();\n\n for (const agentId of agentsToProcess) {\n if (expansionAgents.has(agentId)) {\n // Use expansion pack version (override)\n const agentPath = path.join(agentsDir, `${agentId}.md`);\n const agentContent = await fs.readFile(agentPath, \"utf8\");\n const expansionAgentWebPath = this.convertToWebPath(agentPath, packName);\n sections.push(this.formatSection(expansionAgentWebPath, agentContent, packName));\n\n // Parse and collect dependencies from expansion agent\n const agentYaml = agentContent.match(/```yaml\\n([\\s\\S]*?)\\n```/);\n if (agentYaml) {\n try {\n const agentConfig = this.parseYaml(agentYaml[1]);\n if (agentConfig.dependencies) {\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n const key = `${resourceType}#${resourceName}`;\n if (!allDependencies.has(key)) {\n allDependencies.set(key, { type: resourceType, name: resourceName });\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentId}:`, error.message);\n }\n }\n } else {\n // Use core BMad version\n try {\n const coreAgentPath = path.join(this.rootDir, \"bmad-core\", \"agents\", `${agentId}.md`);\n const coreAgentContent = await fs.readFile(coreAgentPath, \"utf8\");\n const coreAgentWebPath = this.convertToWebPath(coreAgentPath, packName);\n sections.push(this.formatSection(coreAgentWebPath, coreAgentContent, packName));\n\n // Parse and collect dependencies from core agent\n const yamlContent = yamlUtils.extractYamlFromAgent(coreAgentContent, true);\n if (yamlContent) {\n try {\n const agentConfig = this.parseYaml(yamlContent);\n if (agentConfig.dependencies) {\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n const key = `${resourceType}#${resourceName}`;\n if (!allDependencies.has(key)) {\n allDependencies.set(key, { type: resourceType, name: resourceName });\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentId}:`, error.message);\n }\n }\n } catch (error) {\n console.warn(` ⚠ Agent ${agentId} not found in core or expansion pack`);\n }\n }\n }\n\n // Add all collected dependencies from agents\n // Always prefer expansion pack versions if they exist\n for (const [key, dep] of allDependencies) {\n let found = false;\n\n // Always check expansion pack first, even if the dependency came from a core agent\n if (expansionResources.has(key)) {\n // We know it exists in expansion pack, find and load it\n const expansionPath = path.join(packDir, dep.type, dep.name);\n try {\n const content = await fs.readFile(expansionPath, \"utf8\");\n const expansionWebPath = this.convertToWebPath(expansionPath, packName);\n sections.push(this.formatSection(expansionWebPath, content, packName));\n console.log(` āœ“ Using expansion override for ${key}`);\n found = true;\n } catch (error) {\n // Try next extension\n }\n }\n\n // If not found in expansion pack (or doesn't exist there), try core\n if (!found) {\n const corePath = path.join(this.rootDir, \"bmad-core\", dep.type, dep.name);\n try {\n const content = await fs.readFile(corePath, \"utf8\");\n const coreWebPath = this.convertToWebPath(corePath, packName);\n sections.push(this.formatSection(coreWebPath, content, packName));\n found = true;\n } catch (error) {\n // Not in core either, continue\n }\n }\n\n // If not found in core, try common folder\n if (!found) {\n const commonPath = path.join(this.rootDir, \"common\", dep.type, dep.name);\n try {\n const content = await fs.readFile(commonPath, \"utf8\");\n const commonWebPath = this.convertToWebPath(commonPath, packName);\n sections.push(this.formatSection(commonWebPath, content, packName));\n found = true;\n } catch (error) {\n // Not in common either, continue\n }\n }\n\n if (!found) {\n console.warn(` ⚠ Dependency ${key} not found in expansion pack or core`);\n }\n }\n\n // Add remaining expansion pack resources not already included as dependencies\n for (const resourceDir of resourceDirs) {\n const resourcePath = path.join(packDir, resourceDir);\n try {\n const resourceFiles = await fs.readdir(resourcePath);\n for (const resourceFile of resourceFiles.filter(\n (f) => f.endsWith(\".md\") || f.endsWith(\".yaml\")\n )) {\n const filePath = path.join(resourcePath, resourceFile);\n const fileContent = await fs.readFile(filePath, \"utf8\");\n const fileName = resourceFile.replace(/\\.(md|yaml)$/, \"\");\n\n // Only add if not already included as a dependency\n const resourceKey = `${resourceDir}#${fileName}`;\n if (!allDependencies.has(resourceKey)) {\n const fullResourcePath = path.join(resourcePath, resourceFile);\n const resourceWebPath = this.convertToWebPath(fullResourcePath, packName);\n sections.push(this.formatSection(resourceWebPath, fileContent, packName));\n }\n }\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n\n return sections.join(\"\\n\");\n }\n\n async listExpansionPacks() {\n const expansionPacksDir = path.join(this.rootDir, \"expansion-packs\");\n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);\n } catch (error) {\n console.warn(\"No expansion-packs directory found\");\n return [];\n }\n }\n\n listAgents() {\n return this.resolver.listAgents();\n }\n}\n\nmodule.exports = WebBuilder;\n"], ["/BMAD-METHOD/tools/installer/bin/bmad.js", "#!/usr/bin/env node\n\nconst { program } = require('commander');\nconst path = require('path');\nconst fs = require('fs').promises;\nconst yaml = require('js-yaml');\nconst chalk = require('chalk');\nconst inquirer = require('inquirer');\n\n// Handle both execution contexts (from root via npx or from installer directory)\nlet version;\nlet installer;\ntry {\n // Try installer context first (when run from tools/installer/)\n version = require('../package.json').version;\n installer = require('../lib/installer');\n} catch (e) {\n // Fall back to root context (when run via npx from GitHub)\n console.log(`Installer context not found (${e.message}), trying root context...`);\n try {\n version = require('../../../package.json').version;\n installer = require('../../../tools/installer/lib/installer');\n } catch (e2) {\n console.error('Error: Could not load required modules. Please ensure you are running from the correct directory.');\n console.error('Debug info:', {\n __dirname,\n cwd: process.cwd(),\n error: e2.message\n });\n process.exit(1);\n }\n}\n\nprogram\n .version(version)\n .description('BMad Method installer - Universal AI agent framework for any domain');\n\nprogram\n .command('install')\n .description('Install BMad Method agents and tools')\n .option('-f, --full', 'Install complete BMad Method')\n .option('-x, --expansion-only', 'Install only expansion packs (no bmad-core)')\n .option('-d, --directory ', 'Installation directory')\n .option('-i, --ide ', 'Configure for specific IDE(s) - can specify multiple (cursor, claude-code, windsurf, trae, roo, cline, gemini, github-copilot, other)')\n .option('-e, --expansion-packs ', 'Install specific expansion packs (can specify multiple)')\n .action(async (options) => {\n try {\n if (!options.full && !options.expansionOnly) {\n // Interactive mode\n const answers = await promptInstallation();\n if (!answers._alreadyInstalled) {\n await installer.install(answers);\n process.exit(0);\n }\n } else {\n // Direct mode\n let installType = 'full';\n if (options.expansionOnly) installType = 'expansion-only';\n\n const config = {\n installType,\n directory: options.directory || '.',\n ides: (options.ide || []).filter(ide => ide !== 'other'),\n expansionPacks: options.expansionPacks || []\n };\n await installer.install(config);\n process.exit(0);\n }\n } catch (error) {\n console.error(chalk.red('Installation failed:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('update')\n .description('Update existing BMad installation')\n .option('--force', 'Force update, overwriting modified files')\n .option('--dry-run', 'Show what would be updated without making changes')\n .action(async () => {\n try {\n await installer.update();\n } catch (error) {\n console.error(chalk.red('Update failed:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('list:expansions')\n .description('List available expansion packs')\n .action(async () => {\n try {\n await installer.listExpansionPacks();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('status')\n .description('Show installation status')\n .action(async () => {\n try {\n await installer.showStatus();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n process.exit(1);\n }\n });\n\nasync function promptInstallation() {\n \n // Display ASCII logo\n console.log(chalk.bold.cyan(`\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•— ā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— \nā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā•ā•ā•šā•ā•ā–ˆā–ˆā•”ā•ā•ā•ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā•”ā–ˆā–ˆā–ˆā–ˆā•”ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•”ā–ˆā–ˆā–ˆā–ˆā•”ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘\nā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā•ā•ā•ā•ā•ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā• ā–ˆā–ˆā•‘ ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ ā•šā•ā• ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā• ā–ˆā–ˆā•‘ ā•šā•ā• ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•\nā•šā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā•ā•šā•ā• ā•šā•ā•ā•šā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā•ā•šā•ā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā• ā•šā•ā• ā•šā•ā•ā•ā•ā•ā• ā•šā•ā•ā•ā•ā•ā• \n `));\n \n console.log(chalk.bold.magenta('šŸš€ Universal AI Agent Framework for Any Domain'));\n console.log(chalk.bold.blue(`✨ Installer v${version}\\n`));\n\n const answers = {};\n\n // Ask for installation directory first\n const { directory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'directory',\n message: 'Enter the full path to your project directory where BMad should be installed:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid project path';\n }\n return true;\n }\n }\n ]);\n answers.directory = directory;\n\n // Detect existing installations\n const installDir = path.resolve(directory);\n const state = await installer.detectInstallationState(installDir);\n \n // Check for existing expansion packs\n const existingExpansionPacks = state.expansionPacks || {};\n \n // Get available expansion packs\n const availableExpansionPacks = await installer.getAvailableExpansionPacks();\n \n // Build choices list\n const choices = [];\n \n // Load core config to get short-title\n const coreConfigPath = path.join(__dirname, '..', '..', '..', 'bmad-core', 'core-config.yaml');\n const coreConfig = yaml.load(await fs.readFile(coreConfigPath, 'utf8'));\n const coreShortTitle = coreConfig['short-title'] || 'BMad Agile Core System';\n \n // Add BMad core option\n let bmadOptionText;\n if (state.type === 'v4_existing') {\n const currentVersion = state.manifest?.version || 'unknown';\n const newVersion = version; // Always use package.json version\n const versionInfo = currentVersion === newVersion \n ? `(v${currentVersion} - reinstall)`\n : `(v${currentVersion} → v${newVersion})`;\n bmadOptionText = `Update ${coreShortTitle} ${versionInfo} .bmad-core`;\n } else {\n bmadOptionText = `${coreShortTitle} (v${version}) .bmad-core`;\n }\n \n choices.push({\n name: bmadOptionText,\n value: 'bmad-core',\n checked: true\n });\n \n // Add expansion pack options\n for (const pack of availableExpansionPacks) {\n const existing = existingExpansionPacks[pack.id];\n let packOptionText;\n \n if (existing) {\n const currentVersion = existing.manifest?.version || 'unknown';\n const newVersion = pack.version;\n const versionInfo = currentVersion === newVersion \n ? `(v${currentVersion} - reinstall)`\n : `(v${currentVersion} → v${newVersion})`;\n packOptionText = `Update ${pack.shortTitle} ${versionInfo} .${pack.id}`;\n } else {\n packOptionText = `${pack.shortTitle} (v${pack.version}) .${pack.id}`;\n }\n \n choices.push({\n name: packOptionText,\n value: pack.id,\n checked: false\n });\n }\n \n // Ask what to install\n const { selectedItems } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedItems',\n message: 'Select what to install/update (use space to select, enter to continue):',\n choices: choices,\n validate: (selected) => {\n if (selected.length === 0) {\n return 'Please select at least one item to install';\n }\n return true;\n }\n }\n ]);\n \n // Process selections\n answers.installType = selectedItems.includes('bmad-core') ? 'full' : 'expansion-only';\n answers.expansionPacks = selectedItems.filter(item => item !== 'bmad-core');\n\n // Ask sharding questions if installing BMad core\n if (selectedItems.includes('bmad-core')) {\n console.log(chalk.cyan('\\nšŸ“‹ Document Organization Settings'));\n console.log(chalk.dim('Configure how your project documentation should be organized.\\n'));\n \n // Ask about PRD sharding\n const { prdSharded } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'prdSharded',\n message: 'Will the PRD (Product Requirements Document) be sharded into multiple files?',\n default: true\n }\n ]);\n answers.prdSharded = prdSharded;\n \n // Ask about architecture sharding\n const { architectureSharded } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'architectureSharded',\n message: 'Will the architecture documentation be sharded into multiple files?',\n default: true\n }\n ]);\n answers.architectureSharded = architectureSharded;\n \n // Show warning if architecture sharding is disabled\n if (!architectureSharded) {\n console.log(chalk.yellow.bold('\\nāš ļø IMPORTANT: Architecture Sharding Disabled'));\n console.log(chalk.yellow('With architecture sharding disabled, you should still create the files listed'));\n console.log(chalk.yellow('in devLoadAlwaysFiles (like coding-standards.md, tech-stack.md, source-tree.md)'));\n console.log(chalk.yellow('as these are used by the dev agent at runtime.'));\n console.log(chalk.yellow('\\nAlternatively, you can remove these files from the devLoadAlwaysFiles list'));\n console.log(chalk.yellow('in your core-config.yaml after installation.'));\n \n const { acknowledge } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'acknowledge',\n message: 'Do you acknowledge this requirement and want to proceed?',\n default: false\n }\n ]);\n \n if (!acknowledge) {\n console.log(chalk.red('Installation cancelled.'));\n process.exit(0);\n }\n }\n }\n\n // Ask for IDE configuration\n let ides = [];\n let ideSelectionComplete = false;\n \n while (!ideSelectionComplete) {\n console.log(chalk.cyan('\\nšŸ› ļø IDE Configuration'));\n console.log(chalk.bold.yellow.bgRed(' āš ļø IMPORTANT: This is a MULTISELECT! Use SPACEBAR to toggle each IDE! '));\n console.log(chalk.bold.magenta('šŸ”ø Use arrow keys to navigate'));\n console.log(chalk.bold.magenta('šŸ”ø Use SPACEBAR to select/deselect IDEs'));\n console.log(chalk.bold.magenta('šŸ”ø Press ENTER when finished selecting\\n'));\n \n const ideResponse = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'ides',\n message: 'Which IDE(s) do you want to configure? (Select with SPACEBAR, confirm with ENTER):',\n choices: [\n { name: 'Cursor', value: 'cursor' },\n { name: 'Claude Code', value: 'claude-code' },\n { name: 'Windsurf', value: 'windsurf' },\n { name: 'Trae', value: 'trae' }, // { name: 'Trae', value: 'trae'}\n { name: 'Roo Code', value: 'roo' },\n { name: 'Cline', value: 'cline' },\n { name: 'Gemini CLI', value: 'gemini' },\n { name: 'Github Copilot', value: 'github-copilot' }\n ]\n }\n ]);\n \n ides = ideResponse.ides;\n\n // Confirm no IDE selection if none selected\n if (ides.length === 0) {\n const { confirmNoIde } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirmNoIde',\n message: chalk.red('āš ļø You have NOT selected any IDEs. This means NO IDE integration will be set up. Is this correct?'),\n default: false\n }\n ]);\n \n if (!confirmNoIde) {\n console.log(chalk.bold.red('\\nšŸ”„ Returning to IDE selection. Remember to use SPACEBAR to select IDEs!\\n'));\n continue; // Go back to IDE selection only\n }\n }\n \n ideSelectionComplete = true;\n }\n\n // Use selected IDEs directly\n answers.ides = ides;\n\n // Configure GitHub Copilot immediately if selected\n if (ides.includes('github-copilot')) {\n console.log(chalk.cyan('\\nšŸ”§ GitHub Copilot Configuration'));\n console.log(chalk.dim('BMad works best with specific VS Code settings for optimal agent experience.\\n'));\n \n const { configChoice } = await inquirer.prompt([\n {\n type: 'list',\n name: 'configChoice',\n message: chalk.yellow('How would you like to configure GitHub Copilot settings?'),\n choices: [\n {\n name: 'Use recommended defaults (fastest setup)',\n value: 'defaults'\n },\n {\n name: 'Configure each setting manually (customize to your preferences)',\n value: 'manual'\n },\n {\n name: 'Skip settings configuration (I\\'ll configure manually later)',\n value: 'skip'\n }\n ],\n default: 'defaults'\n }\n ]);\n \n answers.githubCopilotConfig = { configChoice };\n }\n\n // Ask for web bundles installation\n const { includeWebBundles } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'includeWebBundles',\n message: 'Would you like to include pre-built web bundles? (standalone files for ChatGPT, Claude, Gemini)',\n default: false\n }\n ]);\n\n if (includeWebBundles) {\n console.log(chalk.cyan('\\nšŸ“¦ Web bundles are standalone files perfect for web AI platforms.'));\n console.log(chalk.dim(' You can choose different teams/agents than your IDE installation.\\n'));\n\n const { webBundleType } = await inquirer.prompt([\n {\n type: 'list',\n name: 'webBundleType',\n message: 'What web bundles would you like to include?',\n choices: [\n {\n name: 'All available bundles (agents, teams, expansion packs)',\n value: 'all'\n },\n {\n name: 'Specific teams only',\n value: 'teams'\n },\n {\n name: 'Individual agents only',\n value: 'agents'\n },\n {\n name: 'Custom selection',\n value: 'custom'\n }\n ]\n }\n ]);\n\n answers.webBundleType = webBundleType;\n\n // If specific teams, let them choose which teams\n if (webBundleType === 'teams' || webBundleType === 'custom') {\n const teams = await installer.getAvailableTeams();\n const { selectedTeams } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedTeams',\n message: 'Select team bundles to include:',\n choices: teams.map(t => ({\n name: `${t.icon || 'šŸ“‹'} ${t.name}: ${t.description}`,\n value: t.id,\n checked: webBundleType === 'teams' // Check all if teams-only mode\n })),\n validate: (answer) => {\n if (answer.length < 1) {\n return 'You must select at least one team.';\n }\n return true;\n }\n }\n ]);\n answers.selectedWebBundleTeams = selectedTeams;\n }\n\n // If custom selection, also ask about individual agents\n if (webBundleType === 'custom') {\n const { includeIndividualAgents } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'includeIndividualAgents',\n message: 'Also include individual agent bundles?',\n default: true\n }\n ]);\n answers.includeIndividualAgents = includeIndividualAgents;\n }\n\n const { webBundlesDirectory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'webBundlesDirectory',\n message: 'Enter directory for web bundles:',\n default: `${answers.directory}/web-bundles`,\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid directory path';\n }\n return true;\n }\n }\n ]);\n answers.webBundlesDirectory = webBundlesDirectory;\n }\n\n answers.includeWebBundles = includeWebBundles;\n\n return answers;\n}\n\nprogram.parse(process.argv);\n\n// Show help if no command provided\nif (!process.argv.slice(2).length) {\n program.outputHelp();\n}"], ["/BMAD-METHOD/tools/yaml-format.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { execSync } = require('child_process');\n\n// Dynamic import for ES module\nlet chalk;\n\n// Initialize ES modules\nasync function initializeModules() {\n if (!chalk) {\n chalk = (await import('chalk')).default;\n }\n}\n\n/**\n * YAML Formatter and Linter for BMad-Method\n * Formats and validates YAML files and YAML embedded in Markdown\n */\n\nasync function formatYamlContent(content, filename) {\n await initializeModules();\n try {\n // First try to fix common YAML issues\n let fixedContent = content\n // Fix \"commands :\" -> \"commands:\"\n .replace(/^(\\s*)(\\w+)\\s+:/gm, '$1$2:')\n // Fix inconsistent list indentation\n .replace(/^(\\s*)-\\s{3,}/gm, '$1- ');\n \n // Skip auto-fixing for .roomodes files - they have special nested structure\n if (!filename.includes('.roomodes')) {\n fixedContent = fixedContent\n // Fix unquoted list items that contain special characters or multiple parts\n .replace(/^(\\s*)-\\s+(.*)$/gm, (match, indent, content) => {\n // Skip if already quoted\n if (content.startsWith('\"') && content.endsWith('\"')) {\n return match;\n }\n // If the content contains special YAML characters or looks complex, quote it\n // BUT skip if it looks like a proper YAML key-value pair (like \"key: value\")\n if ((content.includes(':') || content.includes('-') || content.includes('{') || content.includes('}')) && \n !content.match(/^\\w+:\\s/)) {\n // Remove any existing quotes first, escape internal quotes, then add proper quotes\n const cleanContent = content.replace(/^[\"']|[\"']$/g, '').replace(/\"/g, '\\\\\"');\n return `${indent}- \"${cleanContent}\"`;\n }\n return match;\n });\n }\n \n // Debug: show what we're trying to parse\n if (fixedContent !== content) {\n console.log(chalk.blue(`šŸ”§ Applied YAML fixes to ${filename}`));\n }\n \n // Parse and re-dump YAML to format it\n const parsed = yaml.load(fixedContent);\n const formatted = yaml.dump(parsed, {\n indent: 2,\n lineWidth: -1, // Disable line wrapping\n noRefs: true,\n sortKeys: false // Preserve key order\n });\n return formatted;\n } catch (error) {\n console.error(chalk.red(`āŒ YAML syntax error in ${filename}:`), error.message);\n console.error(chalk.yellow(`šŸ’” Try manually fixing the YAML structure first`));\n return null;\n }\n}\n\nasync function processMarkdownFile(filePath) {\n await initializeModules();\n const content = fs.readFileSync(filePath, 'utf8');\n let modified = false;\n let newContent = content;\n\n // Fix untyped code blocks by adding 'text' type\n // Match ``` at start of line followed by newline, but only if it's an opening fence\n newContent = newContent.replace(/^```\\n([\\s\\S]*?)\\n```$/gm, '```text\\n$1\\n```');\n if (newContent !== content) {\n modified = true;\n console.log(chalk.blue(`šŸ”§ Added 'text' type to untyped code blocks in ${filePath}`));\n }\n\n // Find YAML code blocks\n const yamlBlockRegex = /```ya?ml\\n([\\s\\S]*?)\\n```/g;\n let match;\n const replacements = [];\n \n while ((match = yamlBlockRegex.exec(newContent)) !== null) {\n const [fullMatch, yamlContent] = match;\n const formatted = await formatYamlContent(yamlContent, filePath);\n if (formatted !== null) {\n // Remove trailing newline that js-yaml adds\n const trimmedFormatted = formatted.replace(/\\n$/, '');\n \n if (trimmedFormatted !== yamlContent) {\n modified = true;\n console.log(chalk.green(`āœ“ Formatted YAML in ${filePath}`));\n }\n \n replacements.push({\n start: match.index,\n end: match.index + fullMatch.length,\n replacement: `\\`\\`\\`yaml\\n${trimmedFormatted}\\n\\`\\`\\``\n });\n }\n }\n \n // Apply replacements in reverse order to maintain indices\n for (let i = replacements.length - 1; i >= 0; i--) {\n const { start, end, replacement } = replacements[i];\n newContent = newContent.slice(0, start) + replacement + newContent.slice(end);\n }\n\n if (modified) {\n fs.writeFileSync(filePath, newContent);\n return true;\n }\n return false;\n}\n\nasync function processYamlFile(filePath) {\n await initializeModules();\n const content = fs.readFileSync(filePath, 'utf8');\n const formatted = await formatYamlContent(content, filePath);\n \n if (formatted === null) {\n return false; // Syntax error\n }\n \n if (formatted !== content) {\n fs.writeFileSync(filePath, formatted);\n return true;\n }\n return false;\n}\n\nasync function lintYamlFile(filePath) {\n await initializeModules();\n try {\n // Use yaml-lint for additional validation\n execSync(`npx yaml-lint \"${filePath}\"`, { stdio: 'pipe' });\n return true;\n } catch (error) {\n console.error(chalk.red(`āŒ YAML lint error in ${filePath}:`));\n console.error(error.stdout?.toString() || error.message);\n return false;\n }\n}\n\nasync function main() {\n await initializeModules();\n const args = process.argv.slice(2);\n const glob = require('glob');\n \n if (args.length === 0) {\n console.error('Usage: node yaml-format.js [file2] ...');\n process.exit(1);\n }\n\n let hasErrors = false;\n let hasChanges = false;\n let filesProcessed = [];\n\n // Expand glob patterns and collect all files\n const allFiles = [];\n for (const arg of args) {\n if (arg.includes('*')) {\n // It's a glob pattern\n const matches = glob.sync(arg);\n allFiles.push(...matches);\n } else {\n // It's a direct file path\n allFiles.push(arg);\n }\n }\n\n for (const filePath of allFiles) {\n if (!fs.existsSync(filePath)) {\n // Skip silently for glob patterns that don't match anything\n if (!args.some(arg => arg.includes('*') && filePath === arg)) {\n console.error(chalk.red(`āŒ File not found: ${filePath}`));\n hasErrors = true;\n }\n continue;\n }\n\n const ext = path.extname(filePath).toLowerCase();\n const basename = path.basename(filePath).toLowerCase();\n \n try {\n let changed = false;\n if (ext === '.md') {\n changed = await processMarkdownFile(filePath);\n } else if (ext === '.yaml' || ext === '.yml' || basename.includes('roomodes') || basename.includes('.yaml') || basename.includes('.yml')) {\n // Handle YAML files and special cases like .roomodes\n changed = await processYamlFile(filePath);\n \n // Also run linting\n const lintPassed = await lintYamlFile(filePath);\n if (!lintPassed) hasErrors = true;\n } else {\n // Skip silently for unsupported files\n continue;\n }\n \n if (changed) {\n hasChanges = true;\n filesProcessed.push(filePath);\n }\n } catch (error) {\n console.error(chalk.red(`āŒ Error processing ${filePath}:`), error.message);\n hasErrors = true;\n }\n }\n\n if (hasChanges) {\n console.log(chalk.green(`\\n✨ YAML formatting completed! Modified ${filesProcessed.length} files:`));\n filesProcessed.forEach(file => console.log(chalk.blue(` šŸ“ ${file}`)));\n }\n\n if (hasErrors) {\n console.error(chalk.red('\\nšŸ’„ Some files had errors. Please fix them before committing.'));\n process.exit(1);\n }\n}\n\nif (require.main === module) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n\nmodule.exports = { formatYamlContent, processMarkdownFile, processYamlFile };"], ["/BMAD-METHOD/tools/version-bump.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst { execSync } = require('child_process');\nconst path = require('path');\n\n// Dynamic import for ES module\nlet chalk;\n\n// Initialize ES modules\nasync function initializeModules() {\n if (!chalk) {\n chalk = (await import('chalk')).default;\n }\n}\n\n/**\n * Simple version bumping script for BMad-Method\n * Usage: node tools/version-bump.js [patch|minor|major]\n */\n\nfunction getCurrentVersion() {\n const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));\n return packageJson.version;\n}\n\nasync function bumpVersion(type = 'patch') {\n await initializeModules();\n \n const validTypes = ['patch', 'minor', 'major'];\n if (!validTypes.includes(type)) {\n console.error(chalk.red(`Invalid version type: ${type}. Use: ${validTypes.join(', ')}`));\n process.exit(1);\n }\n\n console.log(chalk.yellow('āš ļø Manual version bumping is disabled.'));\n console.log(chalk.blue('šŸ¤– This project uses semantic-release for automated versioning.'));\n console.log('');\n console.log(chalk.bold('To create a new release, use conventional commits:'));\n console.log(chalk.cyan(' feat: new feature (minor version bump)'));\n console.log(chalk.cyan(' fix: bug fix (patch version bump)'));\n console.log(chalk.cyan(' feat!: breaking change (major version bump)'));\n console.log('');\n console.log(chalk.dim('Example: git commit -m \"feat: add new installer features\"'));\n console.log(chalk.dim('Then push to main branch to trigger automatic release.'));\n \n return null;\n}\n\nasync function main() {\n await initializeModules();\n \n const type = process.argv[2] || 'patch';\n const currentVersion = getCurrentVersion();\n \n console.log(chalk.blue(`Current version: ${currentVersion}`));\n \n // Check if working directory is clean\n try {\n execSync('git diff-index --quiet HEAD --');\n } catch (error) {\n console.error(chalk.red('āŒ Working directory is not clean. Commit your changes first.'));\n process.exit(1);\n }\n \n const newVersion = await bumpVersion(type);\n \n console.log(chalk.green(`\\nšŸŽ‰ Version bump complete!`));\n console.log(chalk.blue(`šŸ“¦ ${currentVersion} → ${newVersion}`));\n}\n\nif (require.main === module) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n\nmodule.exports = { bumpVersion, getCurrentVersion };"], ["/BMAD-METHOD/tools/lib/dependency-resolver.js", "const fs = require('fs').promises;\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { extractYamlFromAgent } = require('./yaml-utils');\n\nclass DependencyResolver {\n constructor(rootDir) {\n this.rootDir = rootDir;\n this.bmadCore = path.join(rootDir, 'bmad-core');\n this.common = path.join(rootDir, 'common');\n this.cache = new Map();\n }\n\n async resolveAgentDependencies(agentId) {\n const agentPath = path.join(this.bmadCore, 'agents', `${agentId}.md`);\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML from markdown content with command cleaning\n const yamlContent = extractYamlFromAgent(agentContent, true);\n if (!yamlContent) {\n throw new Error(`No YAML configuration found in agent ${agentId}`);\n }\n \n const agentConfig = yaml.load(yamlContent);\n \n const dependencies = {\n agent: {\n id: agentId,\n path: agentPath,\n content: agentContent,\n config: agentConfig\n },\n resources: []\n };\n\n // Personas are now embedded in agent configs, no need to resolve separately\n\n // Resolve other dependencies\n const depTypes = ['tasks', 'templates', 'checklists', 'data', 'utils'];\n for (const depType of depTypes) {\n const deps = agentConfig.dependencies?.[depType] || [];\n for (const depId of deps) {\n const resource = await this.loadResource(depType, depId);\n if (resource) dependencies.resources.push(resource);\n }\n }\n\n return dependencies;\n }\n\n async resolveTeamDependencies(teamId) {\n const teamPath = path.join(this.bmadCore, 'agent-teams', `${teamId}.yaml`);\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n \n const dependencies = {\n team: {\n id: teamId,\n path: teamPath,\n content: teamContent,\n config: teamConfig\n },\n agents: [],\n resources: new Map() // Use Map to deduplicate resources\n };\n\n // Always add bmad-orchestrator agent first if it's a team\n const bmadAgent = await this.resolveAgentDependencies('bmad-orchestrator');\n dependencies.agents.push(bmadAgent.agent);\n bmadAgent.resources.forEach(res => {\n dependencies.resources.set(res.path, res);\n });\n\n // Resolve all agents in the team\n let agentsToResolve = teamConfig.agents || [];\n \n // Handle wildcard \"*\" - include all agents except bmad-master\n if (agentsToResolve.includes('*')) {\n const allAgents = await this.listAgents();\n // Remove wildcard and add all agents except those already in the list and bmad-master\n agentsToResolve = agentsToResolve.filter(a => a !== '*');\n for (const agent of allAgents) {\n if (!agentsToResolve.includes(agent) && agent !== 'bmad-master') {\n agentsToResolve.push(agent);\n }\n }\n }\n \n for (const agentId of agentsToResolve) {\n if (agentId === 'bmad-orchestrator' || agentId === 'bmad-master') continue; // Already added or excluded\n const agentDeps = await this.resolveAgentDependencies(agentId);\n dependencies.agents.push(agentDeps.agent);\n \n // Add resources with deduplication\n agentDeps.resources.forEach(res => {\n dependencies.resources.set(res.path, res);\n });\n }\n\n // Resolve workflows\n for (const workflowId of teamConfig.workflows || []) {\n const resource = await this.loadResource('workflows', workflowId);\n if (resource) dependencies.resources.set(resource.path, resource);\n }\n\n // Convert Map back to array\n dependencies.resources = Array.from(dependencies.resources.values());\n\n return dependencies;\n }\n\n async loadResource(type, id) {\n const cacheKey = `${type}#${id}`;\n if (this.cache.has(cacheKey)) {\n return this.cache.get(cacheKey);\n }\n\n try {\n let content = null;\n let filePath = null;\n\n // First try bmad-core\n try {\n filePath = path.join(this.bmadCore, type, id);\n content = await fs.readFile(filePath, 'utf8');\n } catch (e) {\n // If not found in bmad-core, try common folder\n try {\n filePath = path.join(this.common, type, id);\n content = await fs.readFile(filePath, 'utf8');\n } catch (e2) {\n // File not found in either location\n }\n }\n\n if (!content) {\n console.warn(`Resource not found: ${type}/${id}`);\n return null;\n }\n\n const resource = {\n type,\n id,\n path: filePath,\n content\n };\n\n this.cache.set(cacheKey, resource);\n return resource;\n } catch (error) {\n console.error(`Error loading resource ${type}/${id}:`, error.message);\n return null;\n }\n }\n\n async listAgents() {\n try {\n const files = await fs.readdir(path.join(this.bmadCore, 'agents'));\n return files\n .filter(f => f.endsWith('.md'))\n .map(f => f.replace('.md', ''));\n } catch (error) {\n return [];\n }\n }\n\n async listTeams() {\n try {\n const files = await fs.readdir(path.join(this.bmadCore, 'agent-teams'));\n return files\n .filter(f => f.endsWith('.yaml'))\n .map(f => f.replace('.yaml', ''));\n } catch (error) {\n return [];\n }\n }\n}\n\nmodule.exports = DependencyResolver;\n"], ["/BMAD-METHOD/tools/installer/lib/memory-profiler.js", "/**\n * Memory Profiler - Track memory usage during installation\n * Helps identify memory leaks and optimize resource usage\n */\n\nconst v8 = require('v8');\n\nclass MemoryProfiler {\n constructor() {\n this.checkpoints = [];\n this.startTime = Date.now();\n this.peakMemory = 0;\n }\n\n /**\n * Create a memory checkpoint\n * @param {string} label - Label for this checkpoint\n */\n checkpoint(label) {\n const memUsage = process.memoryUsage();\n const heapStats = v8.getHeapStatistics();\n \n const checkpoint = {\n label,\n timestamp: Date.now() - this.startTime,\n memory: {\n rss: this.formatBytes(memUsage.rss),\n heapTotal: this.formatBytes(memUsage.heapTotal),\n heapUsed: this.formatBytes(memUsage.heapUsed),\n external: this.formatBytes(memUsage.external),\n arrayBuffers: this.formatBytes(memUsage.arrayBuffers || 0)\n },\n heap: {\n totalHeapSize: this.formatBytes(heapStats.total_heap_size),\n usedHeapSize: this.formatBytes(heapStats.used_heap_size),\n heapSizeLimit: this.formatBytes(heapStats.heap_size_limit),\n mallocedMemory: this.formatBytes(heapStats.malloced_memory),\n externalMemory: this.formatBytes(heapStats.external_memory)\n },\n raw: {\n heapUsed: memUsage.heapUsed\n }\n };\n\n // Track peak memory\n if (memUsage.heapUsed > this.peakMemory) {\n this.peakMemory = memUsage.heapUsed;\n }\n\n this.checkpoints.push(checkpoint);\n return checkpoint;\n }\n\n /**\n * Force garbage collection (requires --expose-gc flag)\n */\n forceGC() {\n if (global.gc) {\n global.gc();\n return true;\n }\n return false;\n }\n\n /**\n * Get memory usage summary\n */\n getSummary() {\n const currentMemory = process.memoryUsage();\n \n return {\n currentUsage: {\n rss: this.formatBytes(currentMemory.rss),\n heapTotal: this.formatBytes(currentMemory.heapTotal),\n heapUsed: this.formatBytes(currentMemory.heapUsed)\n },\n peakMemory: this.formatBytes(this.peakMemory),\n totalCheckpoints: this.checkpoints.length,\n runTime: `${((Date.now() - this.startTime) / 1000).toFixed(2)}s`\n };\n }\n\n /**\n * Get detailed report of memory usage\n */\n getDetailedReport() {\n const summary = this.getSummary();\n const memoryGrowth = this.calculateMemoryGrowth();\n \n return {\n summary,\n memoryGrowth,\n checkpoints: this.checkpoints,\n recommendations: this.getRecommendations(memoryGrowth)\n };\n }\n\n /**\n * Calculate memory growth between checkpoints\n */\n calculateMemoryGrowth() {\n if (this.checkpoints.length < 2) return [];\n \n const growth = [];\n for (let i = 1; i < this.checkpoints.length; i++) {\n const prev = this.checkpoints[i - 1];\n const curr = this.checkpoints[i];\n \n const heapDiff = curr.raw.heapUsed - prev.raw.heapUsed;\n \n growth.push({\n from: prev.label,\n to: curr.label,\n heapGrowth: this.formatBytes(Math.abs(heapDiff)),\n isIncrease: heapDiff > 0,\n timeDiff: `${((curr.timestamp - prev.timestamp) / 1000).toFixed(2)}s`\n });\n }\n \n return growth;\n }\n\n /**\n * Get recommendations based on memory usage\n */\n getRecommendations(memoryGrowth) {\n const recommendations = [];\n \n // Check for large memory growth\n const largeGrowths = memoryGrowth.filter(g => {\n const bytes = this.parseBytes(g.heapGrowth);\n return bytes > 50 * 1024 * 1024; // 50MB\n });\n \n if (largeGrowths.length > 0) {\n recommendations.push({\n type: 'warning',\n message: `Large memory growth detected in ${largeGrowths.length} operations`,\n details: largeGrowths.map(g => `${g.from} → ${g.to}: ${g.heapGrowth}`)\n });\n }\n \n // Check peak memory\n if (this.peakMemory > 500 * 1024 * 1024) { // 500MB\n recommendations.push({\n type: 'warning',\n message: `High peak memory usage: ${this.formatBytes(this.peakMemory)}`,\n suggestion: 'Consider processing files in smaller batches'\n });\n }\n \n // Check for potential memory leaks\n const continuousGrowth = this.checkContinuousGrowth();\n if (continuousGrowth) {\n recommendations.push({\n type: 'error',\n message: 'Potential memory leak detected',\n details: 'Memory usage continuously increases without significant decreases'\n });\n }\n \n return recommendations;\n }\n\n /**\n * Check for continuous memory growth (potential leak)\n */\n checkContinuousGrowth() {\n if (this.checkpoints.length < 5) return false;\n \n let increasingCount = 0;\n for (let i = 1; i < this.checkpoints.length; i++) {\n if (this.checkpoints[i].raw.heapUsed > this.checkpoints[i - 1].raw.heapUsed) {\n increasingCount++;\n }\n }\n \n // If memory increases in more than 80% of checkpoints, might be a leak\n return increasingCount / (this.checkpoints.length - 1) > 0.8;\n }\n\n /**\n * Format bytes to human-readable string\n */\n formatBytes(bytes) {\n if (bytes === 0) return '0 B';\n \n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n /**\n * Parse human-readable bytes back to number\n */\n parseBytes(str) {\n const match = str.match(/^([\\d.]+)\\s*([KMGT]?B?)$/i);\n if (!match) return 0;\n \n const value = parseFloat(match[1]);\n const unit = match[2].toUpperCase();\n \n const multipliers = {\n 'B': 1,\n 'KB': 1024,\n 'MB': 1024 * 1024,\n 'GB': 1024 * 1024 * 1024\n };\n \n return value * (multipliers[unit] || 1);\n }\n\n /**\n * Clear checkpoints to free memory\n */\n clear() {\n this.checkpoints = [];\n }\n}\n\n// Export singleton instance\nmodule.exports = new MemoryProfiler();"], ["/BMAD-METHOD/tools/installer/lib/config-loader.js", "const fs = require('fs-extra');\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { extractYamlFromAgent } = require('../../lib/yaml-utils');\n\nclass ConfigLoader {\n constructor() {\n this.configPath = path.join(__dirname, '..', 'config', 'install.config.yaml');\n this.config = null;\n }\n\n async load() {\n if (this.config) return this.config;\n \n try {\n const configContent = await fs.readFile(this.configPath, 'utf8');\n this.config = yaml.load(configContent);\n return this.config;\n } catch (error) {\n throw new Error(`Failed to load configuration: ${error.message}`);\n }\n }\n\n async getInstallationOptions() {\n const config = await this.load();\n return config['installation-options'] || {};\n }\n\n async getAvailableAgents() {\n const agentsDir = path.join(this.getBmadCorePath(), 'agents');\n \n try {\n const entries = await fs.readdir(agentsDir, { withFileTypes: true });\n const agents = [];\n \n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.md')) {\n const agentPath = path.join(agentsDir, entry.name);\n const agentId = path.basename(entry.name, '.md');\n \n try {\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML block from agent file\n const yamlContentText = extractYamlFromAgent(agentContent);\n if (yamlContentText) {\n const yamlContent = yaml.load(yamlContentText);\n const agentConfig = yamlContent.agent || {};\n \n agents.push({\n id: agentId,\n name: agentConfig.title || agentConfig.name || agentId,\n file: `bmad-core/agents/${entry.name}`,\n description: agentConfig.whenToUse || 'No description available'\n });\n }\n } catch (error) {\n console.warn(`Failed to read agent ${entry.name}: ${error.message}`);\n }\n }\n }\n \n // Sort agents by name for consistent display\n agents.sort((a, b) => a.name.localeCompare(b.name));\n \n return agents;\n } catch (error) {\n console.warn(`Failed to read agents directory: ${error.message}`);\n return [];\n }\n }\n\n async getAvailableExpansionPacks() {\n const expansionPacksDir = path.join(this.getBmadCorePath(), '..', 'expansion-packs');\n \n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n const expansionPacks = [];\n \n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n const packPath = path.join(expansionPacksDir, entry.name);\n const configPath = path.join(packPath, 'config.yaml');\n \n try {\n // Read config.yaml\n const configContent = await fs.readFile(configPath, 'utf8');\n const config = yaml.load(configContent);\n \n expansionPacks.push({\n id: entry.name,\n name: config.name || entry.name,\n description: config['short-title'] || config.description || 'No description available',\n fullDescription: config.description || config['short-title'] || 'No description available',\n version: config.version || '1.0.0',\n author: config.author || 'BMad Team',\n packPath: packPath,\n dependencies: config.dependencies?.agents || []\n });\n } catch (error) {\n // Fallback if config.yaml doesn't exist or can't be read\n console.warn(`Failed to read config for expansion pack ${entry.name}: ${error.message}`);\n \n // Try to derive info from directory name as fallback\n const name = entry.name\n .split('-')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n \n expansionPacks.push({\n id: entry.name,\n name: name,\n description: 'No description available',\n fullDescription: 'No description available',\n version: '1.0.0',\n author: 'BMad Team',\n packPath: packPath,\n dependencies: []\n });\n }\n }\n }\n \n return expansionPacks;\n } catch (error) {\n console.warn(`Failed to read expansion packs directory: ${error.message}`);\n return [];\n }\n }\n\n async getAgentDependencies(agentId) {\n // Use DependencyResolver to dynamically parse agent dependencies\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n \n const agentDeps = await resolver.resolveAgentDependencies(agentId);\n \n // Convert to flat list of file paths\n const depPaths = [];\n \n // Core files and utilities are included automatically by DependencyResolver\n \n // Add agent file itself is already handled by installer\n \n // Add all resolved resources\n for (const resource of agentDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n \n return depPaths;\n }\n\n async getIdeConfiguration(ide) {\n const config = await this.load();\n const ideConfigs = config['ide-configurations'] || {};\n return ideConfigs[ide] || null;\n }\n\n getBmadCorePath() {\n // Get the path to bmad-core relative to the installer (now under tools)\n return path.join(__dirname, '..', '..', '..', 'bmad-core');\n }\n\n getDistPath() {\n // Get the path to dist directory relative to the installer\n return path.join(__dirname, '..', '..', '..', 'dist');\n }\n\n getAgentPath(agentId) {\n return path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n }\n\n async getAvailableTeams() {\n const teamsDir = path.join(this.getBmadCorePath(), 'agent-teams');\n \n try {\n const entries = await fs.readdir(teamsDir, { withFileTypes: true });\n const teams = [];\n \n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.yaml')) {\n const teamPath = path.join(teamsDir, entry.name);\n \n try {\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n \n if (teamConfig.bundle) {\n teams.push({\n id: path.basename(entry.name, '.yaml'),\n name: teamConfig.bundle.name || entry.name,\n description: teamConfig.bundle.description || 'Team configuration',\n icon: teamConfig.bundle.icon || 'šŸ“‹'\n });\n }\n } catch (error) {\n console.warn(`Warning: Could not load team config ${entry.name}: ${error.message}`);\n }\n }\n }\n \n return teams;\n } catch (error) {\n console.warn(`Warning: Could not scan teams directory: ${error.message}`);\n return [];\n }\n }\n\n getTeamPath(teamId) {\n return path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n }\n\n async getTeamDependencies(teamId) {\n // Use DependencyResolver to dynamically parse team dependencies\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n \n try {\n const teamDeps = await resolver.resolveTeamDependencies(teamId);\n \n // Convert to flat list of file paths\n const depPaths = [];\n \n // Add team config file\n depPaths.push(`.bmad-core/agent-teams/${teamId}.yaml`);\n \n // Add all agents\n for (const agent of teamDeps.agents) {\n const filePath = `.bmad-core/agents/${agent.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n \n // Add all resolved resources\n for (const resource of teamDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.${resource.type === 'workflows' ? 'yaml' : 'md'}`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n \n return depPaths;\n } catch (error) {\n throw new Error(`Failed to resolve team dependencies for ${teamId}: ${error.message}`);\n }\n }\n}\n\nmodule.exports = new ConfigLoader();"], ["/BMAD-METHOD/tools/bump-all-versions.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\nconst args = process.argv.slice(2);\nconst bumpType = args[0] || 'minor'; // default to minor\n\nif (!['major', 'minor', 'patch'].includes(bumpType)) {\n console.log('Usage: node bump-all-versions.js [major|minor|patch]');\n console.log('Default: minor');\n process.exit(1);\n}\n\nfunction bumpVersion(currentVersion, type) {\n const [major, minor, patch] = currentVersion.split('.').map(Number);\n \n switch (type) {\n case 'major':\n return `${major + 1}.0.0`;\n case 'minor':\n return `${major}.${minor + 1}.0`;\n case 'patch':\n return `${major}.${minor}.${patch + 1}`;\n default:\n return currentVersion;\n }\n}\n\nasync function bumpAllVersions() {\n const updatedItems = [];\n \n // First, bump the core version (package.json)\n const packagePath = path.join(__dirname, '..', 'package.json');\n try {\n const packageContent = fs.readFileSync(packagePath, 'utf8');\n const packageJson = JSON.parse(packageContent);\n const oldCoreVersion = packageJson.version || '1.0.0';\n const newCoreVersion = bumpVersion(oldCoreVersion, bumpType);\n \n packageJson.version = newCoreVersion;\n \n fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2) + '\\n');\n \n updatedItems.push({ type: 'core', name: 'BMad Core', oldVersion: oldCoreVersion, newVersion: newCoreVersion });\n console.log(`āœ“ BMad Core (package.json): ${oldCoreVersion} → ${newCoreVersion}`);\n } catch (error) {\n console.error(`āœ— Failed to update BMad Core: ${error.message}`);\n }\n \n // Then, bump all expansion packs\n const expansionPacksDir = path.join(__dirname, '..', 'expansion-packs');\n \n try {\n const entries = fs.readdirSync(expansionPacksDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'README.md') {\n const packId = entry.name;\n const configPath = path.join(expansionPacksDir, packId, 'config.yaml');\n \n if (fs.existsSync(configPath)) {\n try {\n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n const oldVersion = config.version || '1.0.0';\n const newVersion = bumpVersion(oldVersion, bumpType);\n \n config.version = newVersion;\n \n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n \n updatedItems.push({ type: 'expansion', name: packId, oldVersion, newVersion });\n console.log(`āœ“ ${packId}: ${oldVersion} → ${newVersion}`);\n \n } catch (error) {\n console.error(`āœ— Failed to update ${packId}: ${error.message}`);\n }\n }\n }\n }\n \n if (updatedItems.length > 0) {\n const coreCount = updatedItems.filter(i => i.type === 'core').length;\n const expansionCount = updatedItems.filter(i => i.type === 'expansion').length;\n \n console.log(`\\nāœ“ Successfully bumped ${updatedItems.length} item(s) with ${bumpType} version bump`);\n if (coreCount > 0) console.log(` - ${coreCount} core`);\n if (expansionCount > 0) console.log(` - ${expansionCount} expansion pack(s)`);\n \n console.log('\\nNext steps:');\n console.log('1. Test the changes');\n console.log('2. Commit: git add -A && git commit -m \"chore: bump all versions (' + bumpType + ')\"');\n } else {\n console.log('No items found to update');\n }\n \n } catch (error) {\n console.error('Error reading expansion packs directory:', error.message);\n process.exit(1);\n }\n}\n\nbumpAllVersions();"], ["/BMAD-METHOD/tools/bump-expansion-version.js", "#!/usr/bin/env node\n\n// Load required modules\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\n// Parse CLI arguments\nconst args = process.argv.slice(2);\nconst packId = args[0];\nconst bumpType = args[1] || 'minor';\n\n// Validate arguments\nif (!packId || args.length > 2) {\n console.log('Usage: node bump-expansion-version.js [major|minor|patch]');\n console.log('Default: minor');\n console.log('Example: node bump-expansion-version.js bmad-creator-tools patch');\n process.exit(1);\n}\n\nif (!['major', 'minor', 'patch'].includes(bumpType)) {\n console.error('Error: Bump type must be major, minor, or patch');\n process.exit(1);\n}\n\n// Version bump logic\nfunction bumpVersion(currentVersion, type) {\n const [major, minor, patch] = currentVersion.split('.').map(Number);\n\n switch (type) {\n case 'major': return `${major + 1}.0.0`;\n case 'minor': return `${major}.${minor + 1}.0`;\n case 'patch': return `${major}.${minor}.${patch + 1}`;\n default: return currentVersion;\n }\n}\n\n// Main function to bump version\nasync function updateVersion() {\n const configPath = path.join(__dirname, '..', 'expansion-packs', packId, 'config.yaml');\n\n // Check if config exists\n if (!fs.existsSync(configPath)) {\n console.error(`Error: Expansion pack '${packId}' not found`);\n console.log('\\nAvailable expansion packs:');\n\n const packsDir = path.join(__dirname, '..', 'expansion-packs');\n const entries = fs.readdirSync(packsDir, { withFileTypes: true });\n\n entries.forEach(entry => {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n console.log(` - ${entry.name}`);\n }\n });\n\n process.exit(1);\n }\n\n try {\n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n\n const oldVersion = config.version || '1.0.0';\n const newVersion = bumpVersion(oldVersion, bumpType);\n\n config.version = newVersion;\n\n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n\n console.log(`āœ“ ${packId}: ${oldVersion} → ${newVersion}`);\n console.log(`\\nāœ“ Successfully bumped ${packId} with ${bumpType} version bump`);\n console.log('\\nNext steps:');\n console.log(`1. Test the changes`);\n console.log(`2. Commit: git add -A && git commit -m \"chore: bump ${packId} version (${bumpType})\"`);\n\n } catch (error) {\n console.error('Error updating version:', error.message);\n process.exit(1);\n }\n}\n\nupdateVersion();\n"], ["/BMAD-METHOD/tools/cli.js", "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst WebBuilder = require('./builders/web-builder');\nconst V3ToV4Upgrader = require('./upgraders/v3-to-v4-upgrader');\nconst IdeSetup = require('./installer/lib/ide-setup');\nconst path = require('path');\n\nconst program = new Command();\n\nprogram\n .name('bmad-build')\n .description('BMad-Method build tool for creating web bundles')\n .version('4.0.0');\n\nprogram\n .command('build')\n .description('Build web bundles for agents and teams')\n .option('-a, --agents-only', 'Build only agent bundles')\n .option('-t, --teams-only', 'Build only team bundles')\n .option('-e, --expansions-only', 'Build only expansion pack bundles')\n .option('--no-expansions', 'Skip building expansion packs')\n .option('--no-clean', 'Skip cleaning output directories')\n .action(async (options) => {\n const builder = new WebBuilder({\n rootDir: process.cwd()\n });\n\n try {\n if (options.clean) {\n console.log('Cleaning output directories...');\n await builder.cleanOutputDirs();\n }\n\n if (options.expansionsOnly) {\n console.log('Building expansion pack bundles...');\n await builder.buildAllExpansionPacks({ clean: false });\n } else {\n if (!options.teamsOnly) {\n console.log('Building agent bundles...');\n await builder.buildAgents();\n }\n\n if (!options.agentsOnly) {\n console.log('Building team bundles...');\n await builder.buildTeams();\n }\n\n if (!options.noExpansions) {\n console.log('Building expansion pack bundles...');\n await builder.buildAllExpansionPacks({ clean: false });\n }\n }\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error('Build failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('build:expansions')\n .description('Build web bundles for all expansion packs')\n .option('--expansion ', 'Build specific expansion pack only')\n .option('--no-clean', 'Skip cleaning output directories')\n .action(async (options) => {\n const builder = new WebBuilder({\n rootDir: process.cwd()\n });\n\n try {\n if (options.expansion) {\n console.log(`Building expansion pack: ${options.expansion}`);\n await builder.buildExpansionPack(options.expansion, { clean: options.clean });\n } else {\n console.log('Building all expansion packs...');\n await builder.buildAllExpansionPacks({ clean: options.clean });\n }\n\n console.log('Expansion pack build completed successfully!');\n } catch (error) {\n console.error('Expansion pack build failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('list:agents')\n .description('List all available agents')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n const agents = await builder.resolver.listAgents();\n console.log('Available agents:');\n agents.forEach(agent => console.log(` - ${agent}`));\n });\n\nprogram\n .command('list:expansions')\n .description('List all available expansion packs')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n const expansions = await builder.listExpansionPacks();\n console.log('Available expansion packs:');\n expansions.forEach(expansion => console.log(` - ${expansion}`));\n });\n\nprogram\n .command('validate')\n .description('Validate agent and team configurations')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n try {\n // Validate by attempting to build all agents and teams\n const agents = await builder.resolver.listAgents();\n const teams = await builder.resolver.listTeams();\n \n console.log('Validating agents...');\n for (const agent of agents) {\n await builder.resolver.resolveAgentDependencies(agent);\n console.log(` āœ“ ${agent}`);\n }\n \n console.log('\\nValidating teams...');\n for (const team of teams) {\n await builder.resolver.resolveTeamDependencies(team);\n console.log(` āœ“ ${team}`);\n }\n \n console.log('\\nAll configurations are valid!');\n } catch (error) {\n console.error('Validation failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('upgrade')\n .description('Upgrade a BMad-Method V3 project to V4')\n .option('-p, --project ', 'Path to V3 project (defaults to current directory)')\n .option('--dry-run', 'Show what would be changed without making changes')\n .option('--no-backup', 'Skip creating backup (not recommended)')\n .action(async (options) => {\n const upgrader = new V3ToV4Upgrader();\n await upgrader.upgrade({\n projectPath: options.project,\n dryRun: options.dryRun,\n backup: options.backup\n });\n });\n\nprogram\n .command('flatten')\n .description('Flatten codebase to XML format')\n .option('-o, --output ', 'Output file path', 'flattened-codebase.xml')\n .action(async (options) => {\n const flattener = require('./flattener/main');\n await flattener.parseAsync(['flatten', '--output', options.output], { from: 'user' });\n });\n\nprogram.parse();"], ["/BMAD-METHOD/tools/bmad-npx-wrapper.js", "#!/usr/bin/env node\n\n/**\n * BMad Method CLI - Direct execution wrapper for npx\n * This file ensures proper execution when run via npx from GitHub\n */\n\nconst { execSync } = require('child_process');\nconst path = require('path');\nconst fs = require('fs');\n\n// Check if we're running in an npx temporary directory\nconst isNpxExecution = __dirname.includes('_npx') || __dirname.includes('.npm');\n\n// If running via npx, we need to handle things differently\nif (isNpxExecution) {\n // The actual bmad.js is in installer/bin/ (relative to tools directory)\n const bmadScriptPath = path.join(__dirname, 'installer', 'bin', 'bmad.js');\n \n // Verify the file exists\n if (!fs.existsSync(bmadScriptPath)) {\n console.error('Error: Could not find bmad.js at', bmadScriptPath);\n console.error('Current directory:', __dirname);\n process.exit(1);\n }\n \n // Execute with proper working directory\n try {\n execSync(`node \"${bmadScriptPath}\" ${process.argv.slice(2).join(' ')}`, {\n stdio: 'inherit',\n cwd: path.dirname(__dirname)\n });\n } catch (error) {\n // execSync will throw if the command exits with non-zero\n // But the stdio is inherited, so the error is already displayed\n process.exit(error.status || 1);\n }\n} else {\n // Local execution - just require the installer directly\n require('./installer/bin/bmad.js');\n}"], ["/BMAD-METHOD/tools/sync-installer-version.js", "#!/usr/bin/env node\n\n/**\n * Sync installer package.json version with main package.json\n * Used by semantic-release to keep versions in sync\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\nfunction syncInstallerVersion() {\n // Read main package.json\n const mainPackagePath = path.join(__dirname, '..', 'package.json');\n const mainPackage = JSON.parse(fs.readFileSync(mainPackagePath, 'utf8'));\n \n // Read installer package.json\n const installerPackagePath = path.join(__dirname, 'installer', 'package.json');\n const installerPackage = JSON.parse(fs.readFileSync(installerPackagePath, 'utf8'));\n \n // Update installer version to match main version\n installerPackage.version = mainPackage.version;\n \n // Write back installer package.json\n fs.writeFileSync(installerPackagePath, JSON.stringify(installerPackage, null, 2) + '\\n');\n \n console.log(`Synced installer version to ${mainPackage.version}`);\n}\n\n// Run if called directly\nif (require.main === module) {\n syncInstallerVersion();\n}\n\nmodule.exports = { syncInstallerVersion };"], ["/BMAD-METHOD/tools/update-expansion-version.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\nconst args = process.argv.slice(2);\n\nif (args.length < 2) {\n console.log('Usage: node update-expansion-version.js ');\n console.log('Example: node update-expansion-version.js bmad-creator-tools 1.1.0');\n process.exit(1);\n}\n\nconst [packId, newVersion] = args;\n\n// Validate version format\nif (!/^\\d+\\.\\d+\\.\\d+$/.test(newVersion)) {\n console.error('Error: Version must be in format X.Y.Z (e.g., 1.2.3)');\n process.exit(1);\n}\n\nasync function updateVersion() {\n try {\n // Update in config.yaml\n const configPath = path.join(__dirname, '..', 'expansion-packs', packId, 'config.yaml');\n \n if (!fs.existsSync(configPath)) {\n console.error(`Error: Expansion pack '${packId}' not found`);\n process.exit(1);\n }\n \n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n const oldVersion = config.version || 'unknown';\n \n config.version = newVersion;\n \n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n \n console.log(`āœ“ Updated ${packId}/config.yaml: ${oldVersion} → ${newVersion}`);\n console.log(`\\nāœ“ Successfully updated ${packId} to version ${newVersion}`);\n console.log('\\nNext steps:');\n console.log('1. Test the changes');\n console.log('2. Commit: git add -A && git commit -m \"chore: bump ' + packId + ' to v' + newVersion + '\"');\n \n } catch (error) {\n console.error('Error updating version:', error.message);\n process.exit(1);\n }\n}\n\nupdateVersion();"], ["/BMAD-METHOD/tools/lib/yaml-utils.js", "/**\n * Utility functions for YAML extraction from agent files\n */\n\n/**\n * Extract YAML content from agent markdown files\n * @param {string} agentContent - The full content of the agent file\n * @param {boolean} cleanCommands - Whether to clean command descriptions (default: false)\n * @returns {string|null} - The extracted YAML content or null if not found\n */\nfunction extractYamlFromAgent(agentContent, cleanCommands = false) {\n // Remove carriage returns and match YAML block\n const yamlMatch = agentContent.replace(/\\r/g, \"\").match(/```ya?ml\\n([\\s\\S]*?)\\n```/);\n if (!yamlMatch) return null;\n \n let yamlContent = yamlMatch[1].trim();\n \n // Clean up command descriptions if requested\n // Converts \"- command - description\" to just \"- command\"\n if (cleanCommands) {\n yamlContent = yamlContent.replace(/^(\\s*-)(\\s*\"[^\"]+\")(\\s*-\\s*.*)$/gm, '$1$2');\n }\n \n return yamlContent;\n}\n\nmodule.exports = {\n extractYamlFromAgent\n};"], ["/BMAD-METHOD/tools/semantic-release-sync-installer.js", "/**\n * Semantic-release plugin to sync installer package.json version\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\n// This function runs during the \"prepare\" step of semantic-release\nfunction prepare(_, { nextRelease, logger }) {\n // Define the path to the installer package.json file\n const file = path.join(process.cwd(), 'tools/installer/package.json');\n\n // If the file does not exist, skip syncing and log a message\n if (!fs.existsSync(file)) return logger.log('Installer package.json not found, skipping');\n\n // Read and parse the package.json file\n const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));\n\n // Update the version field with the next release version\n pkg.version = nextRelease.version;\n\n // Write the updated JSON back to the file\n fs.writeFileSync(file, JSON.stringify(pkg, null, 2) + '\\n');\n\n // Log success message\n logger.log(`Synced installer package.json to version ${nextRelease.version}`);\n}\n\n// Export the prepare function so semantic-release can use it\nmodule.exports = { prepare };\n"]], "task_instance_info": {"created_time": "2025-08-20 23:47:31", "created_task_model": "DeepSeek-R1", "class_skeleton": "class\nModuleManager\n{\nconstructor () {}\nasync initializeCommonModules () {}\nasync getModule (moduleName) {}\nasync _loadModule (moduleName) {}\nclearCache () {}\nasync getModules (moduleNames) {}\n}", "code_description": "This code segment functions to: Manage asynchronous loading of external dependencies with caching mechanisms and concurrency control while providing centralized access to shared resources through a singleton pattern."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nclass ModuleManager {\n constructor() {\n this.modules = {}; // Active modules cache\n this.pendingModules = {}; // Cache for pending import promises\n }\n\n async initializeCommonModules(commonModules = ['logger', 'config', 'error-handler']) {\n await Promise.all(commonModules.map(module => this.getModule(module)));\n }\n\n async getModule(moduleName) {\n if (this.modules[moduleName]) {\n return this.modules[moduleName];\n }\n\n if (this.pendingModules[moduleName]) {\n return this.pendingModules[moduleName];\n }\n\n const loadPromise = this._loadModule(moduleName);\n this.pendingModules[moduleName] = loadPromise;\n return loadPromise;\n }\n\n async _loadModule(moduleName) {\n try {\n const module = await import(`./${moduleName}.js`);\n this.modules[moduleName] = module;\n delete this.pendingModules[moduleName];\n return module;\n } catch (error) {\n delete this.pendingModules[moduleName];\n throw new Error(`Failed to load module ${moduleName}: ${error.message}`);\n }\n }\n\n clearCache() {\n this.modules = {};\n this.pendingModules = {};\n }\n\n async getModules(moduleNames) {\n return Promise.all(moduleNames.map(name => this.getModule(name)));\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-47-58"}, "editdistance_info": {"edit_distance": 24.826, "calculate_time": "2025-08-20 23:47:58", "true_code_clean": "class ModuleManager {\n constructor() {\n this._cache = new Map();\n this._loadingPromises = new Map();\n }\n async initializeCommonModules() {\n const modules = await Promise.all([\n this.getModule('chalk'),\n this.getModule('ora'),\n this.getModule('inquirer')\n ]);\n return {\n chalk: modules[0],\n ora: modules[1],\n inquirer: modules[2]\n };\n }\n async getModule(moduleName) {\n if (this._cache.has(moduleName)) {\n return this._cache.get(moduleName);\n }\n if (this._loadingPromises.has(moduleName)) {\n return this._loadingPromises.get(moduleName);\n }\n const loadPromise = this._loadModule(moduleName);\n this._loadingPromises.set(moduleName, loadPromise);\n try {\n const module = await loadPromise;\n this._cache.set(moduleName, module);\n this._loadingPromises.delete(moduleName);\n return module;\n } catch (error) {\n this._loadingPromises.delete(moduleName);\n throw error;\n }\n }\n async _loadModule(moduleName) {\n switch (moduleName) {\n case 'chalk':\n return (await import('chalk')).default;\n case 'ora':\n return (await import('ora')).default;\n case 'inquirer':\n return (await import('inquirer')).default;\n case 'glob':\n return (await import('glob')).glob;\n case 'globSync':\n return (await import('glob')).globSync;\n default:\n throw new Error(`Unknown module: ${moduleName}`);\n }\n }\n clearCache() {\n this._cache.clear();\n this._loadingPromises.clear();\n }\n async getModules(moduleNames) {\n const modules = await Promise.all(\n moduleNames.map(name => this.getModule(name))\n );\n return moduleNames.reduce((acc, name, index) => {\n acc[name] = modules[index];\n return acc;\n }, {});\n }\n}", "predict_code_clean": "class ModuleManager {\n constructor() {\n this.modules = {}; \n this.pendingModules = {}; \n }\n async initializeCommonModules(commonModules = ['logger', 'config', 'error-handler']) {\n await Promise.all(commonModules.map(module => this.getModule(module)));\n }\n async getModule(moduleName) {\n if (this.modules[moduleName]) {\n return this.modules[moduleName];\n }\n if (this.pendingModules[moduleName]) {\n return this.pendingModules[moduleName];\n }\n const loadPromise = this._loadModule(moduleName);\n this.pendingModules[moduleName] = loadPromise;\n return loadPromise;\n }\n async _loadModule(moduleName) {\n try {\n const module = await import(`./${moduleName}.js`);\n this.modules[moduleName] = module;\n delete this.pendingModules[moduleName];\n return module;\n } catch (error) {\n delete this.pendingModules[moduleName];\n throw new Error(`Failed to load module ${moduleName}: ${error.message}`);\n }\n }\n clearCache() {\n this.modules = {};\n this.pendingModules = {};\n }\n async getModules(moduleNames) {\n return Promise.all(moduleNames.map(name => this.getModule(name)));\n }\n}"}} {"repo_name": "BMAD-METHOD", "file_name": "/BMAD-METHOD/tools/installer/lib/config-loader.js", "inference_info": {"prefix_code": "const fs = require('fs-extra');\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { extractYamlFromAgent } = require('../../lib/yaml-utils');\n\n", "suffix_code": "\n\nmodule.exports = new ConfigLoader();", "middle_code": "class ConfigLoader {\n constructor() {\n this.configPath = path.join(__dirname, '..', 'config', 'install.config.yaml');\n this.config = null;\n }\n async load() {\n if (this.config) return this.config;\n try {\n const configContent = await fs.readFile(this.configPath, 'utf8');\n this.config = yaml.load(configContent);\n return this.config;\n } catch (error) {\n throw new Error(`Failed to load configuration: ${error.message}`);\n }\n }\n async getInstallationOptions() {\n const config = await this.load();\n return config['installation-options'] || {};\n }\n async getAvailableAgents() {\n const agentsDir = path.join(this.getBmadCorePath(), 'agents');\n try {\n const entries = await fs.readdir(agentsDir, { withFileTypes: true });\n const agents = [];\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.md')) {\n const agentPath = path.join(agentsDir, entry.name);\n const agentId = path.basename(entry.name, '.md');\n try {\n const agentContent = await fs.readFile(agentPath, 'utf8');\n const yamlContentText = extractYamlFromAgent(agentContent);\n if (yamlContentText) {\n const yamlContent = yaml.load(yamlContentText);\n const agentConfig = yamlContent.agent || {};\n agents.push({\n id: agentId,\n name: agentConfig.title || agentConfig.name || agentId,\n file: `bmad-core/agents/${entry.name}`,\n description: agentConfig.whenToUse || 'No description available'\n });\n }\n } catch (error) {\n console.warn(`Failed to read agent ${entry.name}: ${error.message}`);\n }\n }\n }\n agents.sort((a, b) => a.name.localeCompare(b.name));\n return agents;\n } catch (error) {\n console.warn(`Failed to read agents directory: ${error.message}`);\n return [];\n }\n }\n async getAvailableExpansionPacks() {\n const expansionPacksDir = path.join(this.getBmadCorePath(), '..', 'expansion-packs');\n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n const expansionPacks = [];\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n const packPath = path.join(expansionPacksDir, entry.name);\n const configPath = path.join(packPath, 'config.yaml');\n try {\n const configContent = await fs.readFile(configPath, 'utf8');\n const config = yaml.load(configContent);\n expansionPacks.push({\n id: entry.name,\n name: config.name || entry.name,\n description: config['short-title'] || config.description || 'No description available',\n fullDescription: config.description || config['short-title'] || 'No description available',\n version: config.version || '1.0.0',\n author: config.author || 'BMad Team',\n packPath: packPath,\n dependencies: config.dependencies?.agents || []\n });\n } catch (error) {\n console.warn(`Failed to read config for expansion pack ${entry.name}: ${error.message}`);\n const name = entry.name\n .split('-')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n expansionPacks.push({\n id: entry.name,\n name: name,\n description: 'No description available',\n fullDescription: 'No description available',\n version: '1.0.0',\n author: 'BMad Team',\n packPath: packPath,\n dependencies: []\n });\n }\n }\n }\n return expansionPacks;\n } catch (error) {\n console.warn(`Failed to read expansion packs directory: ${error.message}`);\n return [];\n }\n }\n async getAgentDependencies(agentId) {\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n const agentDeps = await resolver.resolveAgentDependencies(agentId);\n const depPaths = [];\n for (const resource of agentDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n return depPaths;\n }\n async getIdeConfiguration(ide) {\n const config = await this.load();\n const ideConfigs = config['ide-configurations'] || {};\n return ideConfigs[ide] || null;\n }\n getBmadCorePath() {\n return path.join(__dirname, '..', '..', '..', 'bmad-core');\n }\n getDistPath() {\n return path.join(__dirname, '..', '..', '..', 'dist');\n }\n getAgentPath(agentId) {\n return path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n }\n async getAvailableTeams() {\n const teamsDir = path.join(this.getBmadCorePath(), 'agent-teams');\n try {\n const entries = await fs.readdir(teamsDir, { withFileTypes: true });\n const teams = [];\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.yaml')) {\n const teamPath = path.join(teamsDir, entry.name);\n try {\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n if (teamConfig.bundle) {\n teams.push({\n id: path.basename(entry.name, '.yaml'),\n name: teamConfig.bundle.name || entry.name,\n description: teamConfig.bundle.description || 'Team configuration',\n icon: teamConfig.bundle.icon || 'šŸ“‹'\n });\n }\n } catch (error) {\n console.warn(`Warning: Could not load team config ${entry.name}: ${error.message}`);\n }\n }\n }\n return teams;\n } catch (error) {\n console.warn(`Warning: Could not scan teams directory: ${error.message}`);\n return [];\n }\n }\n getTeamPath(teamId) {\n return path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n }\n async getTeamDependencies(teamId) {\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n try {\n const teamDeps = await resolver.resolveTeamDependencies(teamId);\n const depPaths = [];\n depPaths.push(`.bmad-core/agent-teams/${teamId}.yaml`);\n for (const agent of teamDeps.agents) {\n const filePath = `.bmad-core/agents/${agent.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n for (const resource of teamDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.${resource.type === 'workflows' ? 'yaml' : 'md'}`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n return depPaths;\n } catch (error) {\n throw new Error(`Failed to resolve team dependencies for ${teamId}: ${error.message}`);\n }\n }\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/BMAD-METHOD/tools/installer/lib/resource-locator.js", "/**\n * Resource Locator - Centralized file path resolution and caching\n * Reduces duplicate file system operations and memory usage\n */\n\nconst path = require('node:path');\nconst fs = require('fs-extra');\nconst moduleManager = require('./module-manager');\n\nclass ResourceLocator {\n constructor() {\n this._pathCache = new Map();\n this._globCache = new Map();\n this._bmadCorePath = null;\n this._expansionPacksPath = null;\n }\n\n /**\n * Get the base path for bmad-core\n */\n getBmadCorePath() {\n if (!this._bmadCorePath) {\n this._bmadCorePath = path.join(__dirname, '../../../bmad-core');\n }\n return this._bmadCorePath;\n }\n\n /**\n * Get the base path for expansion packs\n */\n getExpansionPacksPath() {\n if (!this._expansionPacksPath) {\n this._expansionPacksPath = path.join(__dirname, '../../../expansion-packs');\n }\n return this._expansionPacksPath;\n }\n\n /**\n * Find all files matching a pattern, with caching\n * @param {string} pattern - Glob pattern\n * @param {Object} options - Glob options\n * @returns {Promise} Array of matched file paths\n */\n async findFiles(pattern, options = {}) {\n const cacheKey = `${pattern}:${JSON.stringify(options)}`;\n \n if (this._globCache.has(cacheKey)) {\n return this._globCache.get(cacheKey);\n }\n\n const { glob } = await moduleManager.getModules(['glob']);\n const files = await glob(pattern, options);\n \n // Cache for 5 minutes\n this._globCache.set(cacheKey, files);\n setTimeout(() => this._globCache.delete(cacheKey), 5 * 60 * 1000);\n \n return files;\n }\n\n /**\n * Get agent path with caching\n * @param {string} agentId - Agent identifier\n * @returns {Promise} Path to agent file or null if not found\n */\n async getAgentPath(agentId) {\n const cacheKey = `agent:${agentId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n // Check in bmad-core\n let agentPath = path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n if (await fs.pathExists(agentPath)) {\n this._pathCache.set(cacheKey, agentPath);\n return agentPath;\n }\n\n // Check in expansion packs\n const expansionPacks = await this.getExpansionPacks();\n for (const pack of expansionPacks) {\n agentPath = path.join(pack.path, 'agents', `${agentId}.md`);\n if (await fs.pathExists(agentPath)) {\n this._pathCache.set(cacheKey, agentPath);\n return agentPath;\n }\n }\n\n return null;\n }\n\n /**\n * Get available agents with metadata\n * @returns {Promise} Array of agent objects\n */\n async getAvailableAgents() {\n const cacheKey = 'all-agents';\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const agents = [];\n const yaml = require('js-yaml');\n const { extractYamlFromAgent } = require('../../lib/yaml-utils');\n\n // Get agents from bmad-core\n const coreAgents = await this.findFiles('agents/*.md', {\n cwd: this.getBmadCorePath()\n });\n\n for (const agentFile of coreAgents) {\n const content = await fs.readFile(\n path.join(this.getBmadCorePath(), agentFile),\n 'utf8'\n );\n const yamlContent = extractYamlFromAgent(content);\n if (yamlContent) {\n try {\n const metadata = yaml.load(yamlContent);\n agents.push({\n id: path.basename(agentFile, '.md'),\n name: metadata.agent_name || path.basename(agentFile, '.md'),\n description: metadata.description || 'No description available',\n source: 'core'\n });\n } catch (e) {\n // Skip invalid agents\n }\n }\n }\n\n // Cache for 10 minutes\n this._pathCache.set(cacheKey, agents);\n setTimeout(() => this._pathCache.delete(cacheKey), 10 * 60 * 1000);\n\n return agents;\n }\n\n /**\n * Get available expansion packs\n * @returns {Promise} Array of expansion pack objects\n */\n async getExpansionPacks() {\n const cacheKey = 'expansion-packs';\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const packs = [];\n const expansionPacksPath = this.getExpansionPacksPath();\n\n if (await fs.pathExists(expansionPacksPath)) {\n const entries = await fs.readdir(expansionPacksPath, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory()) {\n const configPath = path.join(expansionPacksPath, entry.name, 'config.yaml');\n if (await fs.pathExists(configPath)) {\n try {\n const yaml = require('js-yaml');\n const config = yaml.load(await fs.readFile(configPath, 'utf8'));\n packs.push({\n id: entry.name,\n name: config.name || entry.name,\n version: config.version || '1.0.0',\n description: config.description || 'No description available',\n shortTitle: config['short-title'] || config.description || 'No description available',\n author: config.author || 'Unknown',\n path: path.join(expansionPacksPath, entry.name)\n });\n } catch (e) {\n // Skip invalid packs\n }\n }\n }\n }\n }\n\n // Cache for 10 minutes\n this._pathCache.set(cacheKey, packs);\n setTimeout(() => this._pathCache.delete(cacheKey), 10 * 60 * 1000);\n\n return packs;\n }\n\n /**\n * Get team configuration\n * @param {string} teamId - Team identifier\n * @returns {Promise} Team configuration or null\n */\n async getTeamConfig(teamId) {\n const cacheKey = `team:${teamId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const teamPath = path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n \n if (await fs.pathExists(teamPath)) {\n try {\n const yaml = require('js-yaml');\n const content = await fs.readFile(teamPath, 'utf8');\n const config = yaml.load(content);\n this._pathCache.set(cacheKey, config);\n return config;\n } catch (e) {\n return null;\n }\n }\n\n return null;\n }\n\n /**\n * Get resource dependencies for an agent\n * @param {string} agentId - Agent identifier\n * @returns {Promise} Dependencies object\n */\n async getAgentDependencies(agentId) {\n const cacheKey = `deps:${agentId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const agentPath = await this.getAgentPath(agentId);\n if (!agentPath) {\n return { all: [], byType: {} };\n }\n\n const content = await fs.readFile(agentPath, 'utf8');\n const { extractYamlFromAgent } = require('../../lib/yaml-utils');\n const yamlContent = extractYamlFromAgent(content);\n\n if (!yamlContent) {\n return { all: [], byType: {} };\n }\n\n try {\n const yaml = require('js-yaml');\n const metadata = yaml.load(yamlContent);\n const dependencies = metadata.dependencies || {};\n \n // Flatten dependencies\n const allDeps = [];\n const byType = {};\n \n for (const [type, deps] of Object.entries(dependencies)) {\n if (Array.isArray(deps)) {\n byType[type] = deps;\n for (const dep of deps) {\n allDeps.push(`.bmad-core/${type}/${dep}`);\n }\n }\n }\n\n const result = { all: allDeps, byType };\n this._pathCache.set(cacheKey, result);\n return result;\n } catch (e) {\n return { all: [], byType: {} };\n }\n }\n\n /**\n * Clear all caches to free memory\n */\n clearCache() {\n this._pathCache.clear();\n this._globCache.clear();\n }\n\n /**\n * Get IDE configuration\n * @param {string} ideId - IDE identifier\n * @returns {Promise} IDE configuration or null\n */\n async getIdeConfig(ideId) {\n const cacheKey = `ide:${ideId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const idePath = path.join(this.getBmadCorePath(), 'ide-rules', `${ideId}.yaml`);\n \n if (await fs.pathExists(idePath)) {\n try {\n const yaml = require('js-yaml');\n const content = await fs.readFile(idePath, 'utf8');\n const config = yaml.load(content);\n this._pathCache.set(cacheKey, config);\n return config;\n } catch (e) {\n return null;\n }\n }\n\n return null;\n }\n}\n\n// Singleton instance\nconst resourceLocator = new ResourceLocator();\n\nmodule.exports = resourceLocator;"], ["/BMAD-METHOD/tools/installer/lib/installer.js", "const path = require(\"node:path\");\nconst fs = require(\"fs-extra\");\nconst chalk = require(\"chalk\");\nconst ora = require(\"ora\");\nconst inquirer = require(\"inquirer\");\nconst fileManager = require(\"./file-manager\");\nconst configLoader = require(\"./config-loader\");\nconst ideSetup = require(\"./ide-setup\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\nconst resourceLocator = require(\"./resource-locator\");\n\nclass Installer {\n async getCoreVersion() {\n try {\n // Always use package.json version\n const packagePath = path.join(__dirname, '..', '..', '..', 'package.json');\n const packageJson = require(packagePath);\n return packageJson.version;\n } catch (error) {\n console.warn(\"Could not read version from package.json, using 'unknown'\");\n return \"unknown\";\n }\n }\n\n async install(config) {\n const spinner = ora(\"Analyzing installation directory...\").start();\n \n try {\n // Store the original CWD where npx was executed\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n \n // Resolve installation directory relative to where the user ran the command\n let installDir = path.isAbsolute(config.directory) \n ? config.directory \n : path.resolve(originalCwd, config.directory);\n \n if (path.basename(installDir) === '.bmad-core') {\n // If user points directly to .bmad-core, treat its parent as the project root\n installDir = path.dirname(installDir);\n }\n \n // Log resolved path for clarity\n if (!path.isAbsolute(config.directory)) {\n spinner.text = `Resolving \"${config.directory}\" to: ${installDir}`;\n }\n\n // Check if directory exists and handle non-existent directories\n if (!(await fileManager.pathExists(installDir))) {\n spinner.stop();\n console.log(`\\nThe directory ${installDir} does not exist.`);\n \n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n {\n name: 'Create the directory and continue',\n value: 'create'\n },\n {\n name: 'Choose a different directory',\n value: 'change'\n },\n {\n name: 'Cancel installation',\n value: 'cancel'\n }\n ]\n }\n ]);\n\n if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n } else if (action === 'change') {\n const { newDirectory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'newDirectory',\n message: 'Enter the new directory path:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid directory path';\n }\n return true;\n }\n }\n ]);\n // Preserve the original CWD for the recursive call\n config.directory = newDirectory;\n return await this.install(config); // Recursive call with new directory\n } else if (action === 'create') {\n try {\n await fileManager.ensureDirectory(installDir);\n console.log(`āœ“ Created directory: ${installDir}`);\n } catch (error) {\n console.error(`Failed to create directory: ${error.message}`);\n console.error('You may need to check permissions or use a different path.');\n process.exit(1);\n }\n }\n \n spinner.start(\"Analyzing installation directory...\");\n }\n\n // If this is an update request from early detection, handle it directly\n if (config.installType === 'update') {\n const state = await this.detectInstallationState(installDir);\n if (state.type === 'v4_existing') {\n return await this.performUpdate(config, installDir, state.manifest, spinner);\n } else {\n spinner.fail('No existing v4 installation found to update');\n throw new Error('No existing v4 installation found');\n }\n }\n\n // Detect current state\n const state = await this.detectInstallationState(installDir);\n\n // Handle different states\n switch (state.type) {\n case \"clean\":\n return await this.performFreshInstall(config, installDir, spinner);\n\n case \"v4_existing\":\n return await this.handleExistingV4Installation(\n config,\n installDir,\n state,\n spinner\n );\n\n case \"v3_existing\":\n return await this.handleV3Installation(\n config,\n installDir,\n state,\n spinner\n );\n\n case \"unknown_existing\":\n return await this.handleUnknownInstallation(\n config,\n installDir,\n state,\n spinner\n );\n }\n } catch (error) {\n // Check if modules were initialized\n if (spinner) {\n spinner.fail(\"Installation failed\");\n } else {\n console.error(\"Installation failed:\", error.message);\n }\n throw error;\n }\n }\n\n async detectInstallationState(installDir) {\n const state = {\n type: \"clean\",\n hasV4Manifest: false,\n hasV3Structure: false,\n hasBmadCore: false,\n hasOtherFiles: false,\n manifest: null,\n expansionPacks: {},\n };\n\n // Check if directory exists\n if (!(await fileManager.pathExists(installDir))) {\n return state; // clean install\n }\n\n // Check for V4 installation (has .bmad-core with manifest)\n const bmadCorePath = path.join(installDir, \".bmad-core\");\n const manifestPath = path.join(bmadCorePath, \"install-manifest.yaml\");\n\n if (await fileManager.pathExists(manifestPath)) {\n state.type = \"v4_existing\";\n state.hasV4Manifest = true;\n state.hasBmadCore = true;\n state.manifest = await fileManager.readManifest(installDir);\n return state;\n }\n\n // Check for V3 installation (has bmad-agent directory)\n const bmadAgentPath = path.join(installDir, \"bmad-agent\");\n if (await fileManager.pathExists(bmadAgentPath)) {\n state.type = \"v3_existing\";\n state.hasV3Structure = true;\n return state;\n }\n\n // Check for .bmad-core without manifest (broken V4 or manual copy)\n if (await fileManager.pathExists(bmadCorePath)) {\n state.type = \"unknown_existing\";\n state.hasBmadCore = true;\n return state;\n }\n\n // Check if directory has other files\n const files = await resourceLocator.findFiles(\"**/*\", {\n cwd: installDir,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n\n if (files.length > 0) {\n // Directory has other files, but no BMad installation.\n // Treat as clean install but record that it isn't empty.\n state.hasOtherFiles = true;\n }\n\n // Check for expansion packs (folders starting with .)\n const expansionPacks = await this.detectExpansionPacks(installDir);\n state.expansionPacks = expansionPacks;\n\n return state; // clean install\n }\n\n async performFreshInstall(config, installDir, spinner, options = {}) {\n spinner.text = \"Installing BMad Method...\";\n\n let files = [];\n\n if (config.installType === \"full\") {\n // Full installation - copy entire .bmad-core folder as a subdirectory\n spinner.text = \"Copying complete .bmad-core folder...\";\n const sourceDir = resourceLocator.getBmadCorePath();\n const bmadCoreDestDir = path.join(installDir, \".bmad-core\");\n await fileManager.copyDirectoryWithRootReplacement(sourceDir, bmadCoreDestDir, \".bmad-core\");\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n\n // Get list of all files for manifest\n const foundFiles = await resourceLocator.findFiles(\"**/*\", {\n cwd: bmadCoreDestDir,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n files = foundFiles.map((file) => path.join(\".bmad-core\", file));\n } else if (config.installType === \"single-agent\") {\n // Single agent installation\n spinner.text = `Installing ${config.agent} agent...`;\n\n // Copy agent file with {root} replacement\n const agentPath = configLoader.getAgentPath(config.agent);\n const destAgentPath = path.join(\n installDir,\n \".bmad-core\",\n \"agents\",\n `${config.agent}.md`\n );\n await fileManager.copyFileWithRootReplacement(agentPath, destAgentPath, \".bmad-core\");\n files.push(`.bmad-core/agents/${config.agent}.md`);\n\n // Copy dependencies\n const { all: dependencies } = await resourceLocator.getAgentDependencies(\n config.agent\n );\n const sourceBase = resourceLocator.getBmadCorePath();\n\n for (const dep of dependencies) {\n spinner.text = `Copying dependency: ${dep}`;\n\n if (dep.includes(\"*\")) {\n // Handle glob patterns with {root} replacement\n const copiedFiles = await fileManager.copyGlobPattern(\n dep.replace(\".bmad-core/\", \"\"),\n sourceBase,\n path.join(installDir, \".bmad-core\"),\n \".bmad-core\"\n );\n files.push(...copiedFiles.map(f => `.bmad-core/${f}`));\n } else {\n // Handle single files with {root} replacement if needed\n const sourcePath = path.join(\n sourceBase,\n dep.replace(\".bmad-core/\", \"\")\n );\n const destPath = path.join(\n installDir,\n dep\n );\n\n const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, \".bmad-core\");\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n files.push(dep);\n }\n }\n }\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n const commonFiles = await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n files.push(...commonFiles);\n } else if (config.installType === \"team\") {\n // Team installation\n spinner.text = `Installing ${config.team} team...`;\n \n // Get team dependencies\n const teamDependencies = await configLoader.getTeamDependencies(config.team);\n const sourceBase = resourceLocator.getBmadCorePath();\n \n // Install all team dependencies\n for (const dep of teamDependencies) {\n spinner.text = `Copying team dependency: ${dep}`;\n \n if (dep.includes(\"*\")) {\n // Handle glob patterns with {root} replacement\n const copiedFiles = await fileManager.copyGlobPattern(\n dep.replace(\".bmad-core/\", \"\"),\n sourceBase,\n path.join(installDir, \".bmad-core\"),\n \".bmad-core\"\n );\n files.push(...copiedFiles.map(f => `.bmad-core/${f}`));\n } else {\n // Handle single files with {root} replacement if needed\n const sourcePath = path.join(sourceBase, dep.replace(\".bmad-core/\", \"\"));\n const destPath = path.join(installDir, dep);\n \n const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, \".bmad-core\");\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n files.push(dep);\n }\n }\n }\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n const commonFiles = await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n files.push(...commonFiles);\n } else if (config.installType === \"expansion-only\") {\n // Expansion-only installation - DO NOT create .bmad-core\n // Only install expansion packs\n spinner.text = \"Installing expansion packs only...\";\n }\n\n // Install expansion packs if requested\n const expansionFiles = await this.installExpansionPacks(installDir, config.expansionPacks, spinner, config);\n files.push(...expansionFiles);\n\n // Install web bundles if requested\n if (config.includeWebBundles && config.webBundlesDirectory) {\n spinner.text = \"Installing web bundles...\";\n // Resolve web bundles directory using the same logic as the main installation directory\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n let resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory) \n ? config.webBundlesDirectory \n : path.resolve(originalCwd, config.webBundlesDirectory);\n await this.installWebBundles(resolvedWebBundlesDir, config, spinner);\n }\n\n // Set up IDE integration if requested\n const ides = config.ides || (config.ide ? [config.ide] : []);\n if (ides.length > 0) {\n for (const ide of ides) {\n spinner.text = `Setting up ${ide} integration...`;\n const preConfiguredSettings = ide === 'github-copilot' ? config.githubCopilotConfig : null;\n await ideSetup.setup(ide, installDir, config.agent, spinner, preConfiguredSettings);\n }\n }\n\n // Modify core-config.yaml if sharding preferences were provided\n if (config.installType !== \"expansion-only\" && (config.prdSharded !== undefined || config.architectureSharded !== undefined)) {\n spinner.text = \"Configuring document sharding settings...\";\n await fileManager.modifyCoreConfig(installDir, config);\n }\n\n // Create manifest (skip for expansion-only installations)\n if (config.installType !== \"expansion-only\") {\n spinner.text = \"Creating installation manifest...\";\n await fileManager.createManifest(installDir, config, files);\n }\n\n spinner.succeed(\"Installation complete!\");\n this.showSuccessMessage(config, installDir, options);\n }\n\n async handleExistingV4Installation(config, installDir, state, spinner) {\n spinner.stop();\n\n const currentVersion = state.manifest.version;\n const newVersion = await this.getCoreVersion();\n const versionCompare = this.compareVersions(currentVersion, newVersion);\n\n console.log(chalk.yellow(\"\\nšŸ” Found existing BMad v4 installation\"));\n console.log(` Directory: ${installDir}`);\n console.log(` Current version: ${currentVersion}`);\n console.log(` Available version: ${newVersion}`);\n console.log(\n ` Installed: ${new Date(\n state.manifest.installed_at\n ).toLocaleDateString()}`\n );\n\n // Check file integrity\n spinner.start(\"Checking installation integrity...\");\n const integrity = await fileManager.checkFileIntegrity(installDir, state.manifest);\n spinner.stop();\n \n const hasMissingFiles = integrity.missing.length > 0;\n const hasModifiedFiles = integrity.modified.length > 0;\n const hasIntegrityIssues = hasMissingFiles || hasModifiedFiles;\n \n if (hasIntegrityIssues) {\n console.log(chalk.red(\"\\nāš ļø Installation issues detected:\"));\n if (hasMissingFiles) {\n console.log(chalk.red(` Missing files: ${integrity.missing.length}`));\n if (integrity.missing.length <= 5) {\n integrity.missing.forEach(file => console.log(chalk.dim(` - ${file}`)));\n }\n }\n if (hasModifiedFiles) {\n console.log(chalk.yellow(` Modified files: ${integrity.modified.length}`));\n if (integrity.modified.length <= 5) {\n integrity.modified.forEach(file => console.log(chalk.dim(` - ${file}`)));\n }\n }\n }\n\n // Show existing expansion packs\n if (Object.keys(state.expansionPacks).length > 0) {\n console.log(chalk.cyan(\"\\nšŸ“¦ Installed expansion packs:\"));\n for (const [packId, packInfo] of Object.entries(state.expansionPacks)) {\n if (packInfo.hasManifest && packInfo.manifest) {\n console.log(` - ${packId} (v${packInfo.manifest.version || 'unknown'})`);\n } else {\n console.log(` - ${packId} (no manifest)`);\n }\n }\n }\n\n let choices = [];\n \n if (versionCompare < 0) {\n console.log(chalk.cyan(\"\\nā¬†ļø Upgrade available for BMad core\"));\n choices.push({ name: `Upgrade BMad core (v${currentVersion} → v${newVersion})`, value: \"upgrade\" });\n } else if (versionCompare === 0) {\n if (hasIntegrityIssues) {\n // Offer repair option when files are missing or modified\n choices.push({ \n name: \"Repair installation (restore missing/modified files)\", \n value: \"repair\" \n });\n }\n console.log(chalk.yellow(\"\\nāš ļø Same version already installed\"));\n choices.push({ name: `Force reinstall BMad core (v${currentVersion} - reinstall)`, value: \"reinstall\" });\n } else {\n console.log(chalk.yellow(\"\\nā¬‡ļø Installed version is newer than available\"));\n choices.push({ name: `Downgrade BMad core (v${currentVersion} → v${newVersion})`, value: \"reinstall\" });\n }\n \n choices.push(\n { name: \"Add/update expansion packs only\", value: \"expansions\" },\n { name: \"Cancel\", value: \"cancel\" }\n );\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: choices,\n },\n ]);\n\n switch (action) {\n case \"upgrade\":\n return await this.performUpdate(config, installDir, state.manifest, spinner);\n case \"repair\":\n // For repair, restore missing/modified files while backing up modified ones\n return await this.performRepair(config, installDir, state.manifest, integrity, spinner);\n case \"reinstall\":\n // For reinstall, don't check for modifications - just overwrite\n return await this.performReinstall(config, installDir, spinner);\n case \"expansions\":\n // Ask which expansion packs to install\n const availableExpansionPacks = await resourceLocator.getExpansionPacks();\n \n if (availableExpansionPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs available.\"));\n return;\n }\n \n const { selectedPacks } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedPacks',\n message: 'Select expansion packs to install/update:',\n choices: availableExpansionPacks.map(pack => ({\n name: `${pack.name} (v${pack.version}) .${pack.id}`,\n value: pack.id,\n checked: state.expansionPacks[pack.id] !== undefined\n }))\n }\n ]);\n \n if (selectedPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs selected.\"));\n return;\n }\n \n spinner.start(\"Installing expansion packs...\");\n const expansionFiles = await this.installExpansionPacks(installDir, selectedPacks, spinner, { ides: config.ides || [] });\n spinner.succeed(\"Expansion packs installed successfully!\");\n \n console.log(chalk.green(\"\\nāœ“ Installation complete!\"));\n console.log(chalk.green(`āœ“ Expansion packs installed/updated:`));\n for (const packId of selectedPacks) {\n console.log(chalk.green(` - ${packId} → .${packId}/`));\n }\n return;\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async handleV3Installation(config, installDir, state, spinner) {\n spinner.stop();\n\n console.log(\n chalk.yellow(\"\\nšŸ” Found BMad v3 installation (bmad-agent/ directory)\")\n );\n console.log(` Directory: ${installDir}`);\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: [\n { name: \"Upgrade from v3 to v4 (recommended)\", value: \"upgrade\" },\n { name: \"Install v4 alongside v3\", value: \"alongside\" },\n { name: \"Cancel\", value: \"cancel\" },\n ],\n },\n ]);\n\n switch (action) {\n case \"upgrade\": {\n console.log(chalk.cyan(\"\\nšŸ“¦ Starting v3 to v4 upgrade process...\"));\n const V3ToV4Upgrader = require(\"../../upgraders/v3-to-v4-upgrader\");\n const upgrader = new V3ToV4Upgrader();\n return await upgrader.upgrade({ \n projectPath: installDir,\n ides: config.ides || [] // Pass IDE selections from initial config\n });\n }\n case \"alongside\":\n return await this.performFreshInstall(config, installDir, spinner);\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async handleUnknownInstallation(config, installDir, state, spinner) {\n spinner.stop();\n\n console.log(chalk.yellow(\"\\nāš ļø Directory contains existing files\"));\n console.log(` Directory: ${installDir}`);\n\n if (state.hasBmadCore) {\n console.log(\" Found: .bmad-core directory (but no manifest)\");\n }\n if (state.hasOtherFiles) {\n console.log(\" Found: Other files in directory\");\n }\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: [\n { name: \"Install anyway (may overwrite files)\", value: \"force\" },\n { name: \"Choose different directory\", value: \"different\" },\n { name: \"Cancel\", value: \"cancel\" },\n ],\n },\n ]);\n\n switch (action) {\n case \"force\":\n return await this.performFreshInstall(config, installDir, spinner);\n case \"different\": {\n const { newDir } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"newDir\",\n message: \"Enter new installation directory:\",\n default: path.join(path.dirname(installDir), \"bmad-project\"),\n },\n ]);\n config.directory = newDir;\n return await this.install(config);\n }\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async performUpdate(newConfig, installDir, manifest, spinner) {\n spinner.start(\"Checking for updates...\");\n\n try {\n // Get current and new versions\n const currentVersion = manifest.version;\n const newVersion = await this.getCoreVersion();\n const versionCompare = this.compareVersions(currentVersion, newVersion);\n \n // Only check for modified files if it's an actual version upgrade\n let modifiedFiles = [];\n if (versionCompare !== 0) {\n spinner.text = \"Checking for modified files...\";\n modifiedFiles = await fileManager.checkModifiedFiles(\n installDir,\n manifest\n );\n }\n\n if (modifiedFiles.length > 0) {\n spinner.warn(\"Found modified files\");\n console.log(chalk.yellow(\"\\nThe following files have been modified:\"));\n for (const file of modifiedFiles) {\n console.log(` - ${file}`);\n }\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"How would you like to proceed?\",\n choices: [\n { name: \"Backup and overwrite modified files\", value: \"backup\" },\n { name: \"Skip modified files\", value: \"skip\" },\n { name: \"Cancel update\", value: \"cancel\" },\n ],\n },\n ]);\n\n if (action === \"cancel\") {\n console.log(\"Update cancelled.\");\n return;\n }\n\n if (action === \"backup\") {\n spinner.start(\"Backing up modified files...\");\n for (const file of modifiedFiles) {\n const filePath = path.join(installDir, file);\n const backupPath = await fileManager.backupFile(filePath);\n console.log(\n chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`)\n );\n }\n }\n }\n\n // Perform update by re-running installation\n spinner.text = versionCompare === 0 ? \"Reinstalling files...\" : \"Updating files...\";\n const config = {\n installType: manifest.install_type,\n agent: manifest.agent,\n directory: installDir,\n ides: newConfig?.ides || manifest.ides_setup || [],\n };\n\n await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n } catch (error) {\n spinner.fail(\"Update failed\");\n throw error;\n }\n }\n\n async performRepair(config, installDir, manifest, integrity, spinner) {\n spinner.start(\"Preparing to repair installation...\");\n\n try {\n // Back up modified files\n if (integrity.modified.length > 0) {\n spinner.text = \"Backing up modified files...\";\n for (const file of integrity.modified) {\n const filePath = path.join(installDir, file);\n if (await fileManager.pathExists(filePath)) {\n const backupPath = await fileManager.backupFile(filePath);\n console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));\n }\n }\n }\n\n // Restore missing and modified files\n spinner.text = \"Restoring files...\";\n const sourceBase = resourceLocator.getBmadCorePath();\n const filesToRestore = [...integrity.missing, ...integrity.modified];\n \n for (const file of filesToRestore) {\n // Skip the manifest file itself\n if (file.endsWith('install-manifest.yaml')) continue;\n \n const relativePath = file.replace('.bmad-core/', '');\n const destPath = path.join(installDir, file);\n \n // Check if this is a common/ file that needs special processing\n const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));\n const commonSourcePath = path.join(commonBase, 'common', relativePath);\n \n if (await fileManager.pathExists(commonSourcePath)) {\n // This is a common/ file - needs template processing\n const fs = require('fs').promises;\n const content = await fs.readFile(commonSourcePath, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, '.bmad-core');\n await fileManager.ensureDirectory(path.dirname(destPath));\n await fs.writeFile(destPath, updatedContent, 'utf8');\n spinner.text = `Restored: ${file}`;\n } else {\n // Regular file from bmad-core\n const sourcePath = path.join(sourceBase, relativePath);\n if (await fileManager.pathExists(sourcePath)) {\n await fileManager.copyFile(sourcePath, destPath);\n spinner.text = `Restored: ${file}`;\n \n // If this is a .yaml file, check for and remove corresponding .yml file\n if (file.endsWith('.yaml')) {\n const ymlFile = file.replace(/\\.yaml$/, '.yml');\n const ymlPath = path.join(installDir, ymlFile);\n if (await fileManager.pathExists(ymlPath)) {\n const fs = require('fs').promises;\n await fs.unlink(ymlPath);\n console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${file})`));\n }\n }\n } else {\n console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));\n }\n }\n }\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n \n spinner.succeed(\"Repair completed successfully!\");\n \n // Show summary\n console.log(chalk.green(\"\\nāœ“ Installation repaired!\"));\n if (integrity.missing.length > 0) {\n console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));\n }\n if (integrity.modified.length > 0) {\n console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));\n }\n \n // Warning for Cursor custom modes if agents were repaired\n const ides = manifest.ides_setup || [];\n if (ides.includes('cursor')) {\n console.log(chalk.yellow.bold(\"\\nāš ļø IMPORTANT: Cursor Custom Modes Update Required\"));\n console.log(chalk.yellow(\"Since agent files have been repaired, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs.\"));\n }\n \n } catch (error) {\n spinner.fail(\"Repair failed\");\n throw error;\n }\n }\n\n async performReinstall(config, installDir, spinner) {\n spinner.start(\"Preparing to reinstall BMad Method...\");\n\n // Remove existing .bmad-core\n const bmadCorePath = path.join(installDir, \".bmad-core\");\n if (await fileManager.pathExists(bmadCorePath)) {\n spinner.text = \"Removing existing installation...\";\n await fileManager.removeDirectory(bmadCorePath);\n }\n \n spinner.text = \"Installing fresh copy...\";\n const result = await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n \n return result;\n }\n\n showSuccessMessage(config, installDir, options = {}) {\n console.log(chalk.green(\"\\nāœ“ BMad Method installed successfully!\\n\"));\n\n const ides = config.ides || (config.ide ? [config.ide] : []);\n if (ides.length > 0) {\n for (const ide of ides) {\n const ideConfig = configLoader.getIdeConfiguration(ide);\n if (ideConfig?.instructions) {\n console.log(\n chalk.bold(`To use BMad agents in ${ideConfig.name}:`)\n );\n console.log(ideConfig.instructions);\n }\n }\n } else {\n console.log(chalk.yellow(\"No IDE configuration was set up.\"));\n console.log(\n \"You can manually configure your IDE using the agent files in:\",\n installDir\n );\n }\n\n // Information about installation components\n console.log(chalk.bold(\"\\nšŸŽÆ Installation Summary:\"));\n if (config.installType !== \"expansion-only\") {\n console.log(chalk.green(\"āœ“ .bmad-core framework installed with all agents and workflows\"));\n }\n \n if (config.expansionPacks && config.expansionPacks.length > 0) {\n console.log(chalk.green(`āœ“ Expansion packs installed:`));\n for (const packId of config.expansionPacks) {\n console.log(chalk.green(` - ${packId} → .${packId}/`));\n }\n }\n \n if (config.includeWebBundles && config.webBundlesDirectory) {\n const bundleInfo = this.getWebBundleInfo(config);\n // Resolve the web bundles directory for display\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n const resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory) \n ? config.webBundlesDirectory \n : path.resolve(originalCwd, config.webBundlesDirectory);\n console.log(chalk.green(`āœ“ Web bundles (${bundleInfo}) installed to: ${resolvedWebBundlesDir}`));\n }\n \n if (ides.length > 0) {\n const ideNames = ides.map(ide => {\n const ideConfig = configLoader.getIdeConfiguration(ide);\n return ideConfig?.name || ide;\n }).join(\", \");\n console.log(chalk.green(`āœ“ IDE rules and configurations set up for: ${ideNames}`));\n }\n\n // Information about web bundles\n if (!config.includeWebBundles) {\n console.log(chalk.bold(\"\\nšŸ“¦ Web Bundles Available:\"));\n console.log(\"Pre-built web bundles are available and can be added later:\");\n console.log(chalk.cyan(\" Run the installer again to add them to your project\"));\n console.log(\"These bundles work independently and can be shared, moved, or used\");\n console.log(\"in other projects as standalone files.\");\n }\n\n if (config.installType === \"single-agent\") {\n console.log(\n chalk.dim(\n \"\\nNeed other agents? Run: npx bmad-method install --agent=\"\n )\n );\n console.log(\n chalk.dim(\"Need everything? Run: npx bmad-method install --full\")\n );\n }\n\n // Warning for Cursor custom modes if agents were updated\n if (options.isUpdate && ides.includes('cursor')) {\n console.log(chalk.yellow.bold(\"\\nāš ļø IMPORTANT: Cursor Custom Modes Update Required\"));\n console.log(chalk.yellow(\"Since agents have been updated, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs.\"));\n }\n\n // Important notice to read the user guide\n console.log(chalk.red.bold(\"\\nšŸ“– IMPORTANT: Please read the user guide installed at .bmad-core/user-guide.md\"));\n console.log(chalk.red(\"This guide contains essential information about the BMad workflow and how to use the agents effectively.\"));\n }\n\n // Legacy method for backward compatibility\n async update() {\n console.log(chalk.yellow('The \"update\" command is deprecated.'));\n console.log(\n 'Please use \"install\" instead - it will detect and offer to update existing installations.'\n );\n\n const installDir = await this.findInstallation();\n if (installDir) {\n const config = {\n installType: \"full\",\n directory: path.dirname(installDir),\n ide: null,\n };\n return await this.install(config);\n }\n console.log(chalk.red(\"No BMad installation found.\"));\n }\n\n async listAgents() {\n const agents = await resourceLocator.getAvailableAgents();\n\n console.log(chalk.bold(\"\\nAvailable BMad Agents:\\n\"));\n\n for (const agent of agents) {\n console.log(chalk.cyan(` ${agent.id.padEnd(20)}`), agent.description);\n }\n\n console.log(\n chalk.dim(\"\\nInstall with: npx bmad-method install --agent=\\n\")\n );\n }\n\n async listExpansionPacks() {\n const expansionPacks = await resourceLocator.getExpansionPacks();\n\n console.log(chalk.bold(\"\\nAvailable BMad Expansion Packs:\\n\"));\n\n if (expansionPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs found.\"));\n return;\n }\n\n for (const pack of expansionPacks) {\n console.log(chalk.cyan(` ${pack.id.padEnd(20)}`), \n `${pack.name} v${pack.version}`);\n console.log(chalk.dim(` ${' '.repeat(22)}${pack.description}`));\n if (pack.author && pack.author !== 'Unknown') {\n console.log(chalk.dim(` ${' '.repeat(22)}by ${pack.author}`));\n }\n console.log();\n }\n\n console.log(\n chalk.dim(\"Install with: npx bmad-method install --full --expansion-packs \\n\")\n );\n }\n\n async showStatus() {\n const installDir = await this.findInstallation();\n\n if (!installDir) {\n console.log(\n chalk.yellow(\"No BMad installation found in current directory tree\")\n );\n return;\n }\n\n const manifest = await fileManager.readManifest(installDir);\n\n if (!manifest) {\n console.log(chalk.red(\"Invalid installation - manifest not found\"));\n return;\n }\n\n console.log(chalk.bold(\"\\nBMad Installation Status:\\n\"));\n console.log(` Directory: ${installDir}`);\n console.log(` Version: ${manifest.version}`);\n console.log(\n ` Installed: ${new Date(\n manifest.installed_at\n ).toLocaleDateString()}`\n );\n console.log(` Type: ${manifest.install_type}`);\n\n if (manifest.agent) {\n console.log(` Agent: ${manifest.agent}`);\n }\n\n if (manifest.ides_setup && manifest.ides_setup.length > 0) {\n console.log(` IDE Setup: ${manifest.ides_setup.join(', ')}`);\n }\n\n console.log(` Total Files: ${manifest.files.length}`);\n\n // Check for modifications\n const modifiedFiles = await fileManager.checkModifiedFiles(\n installDir,\n manifest\n );\n if (modifiedFiles.length > 0) {\n console.log(chalk.yellow(` Modified Files: ${modifiedFiles.length}`));\n }\n\n console.log(\"\");\n }\n\n async getAvailableAgents() {\n return resourceLocator.getAvailableAgents();\n }\n\n async getAvailableExpansionPacks() {\n return resourceLocator.getExpansionPacks();\n }\n\n async getAvailableTeams() {\n return configLoader.getAvailableTeams();\n }\n\n async installExpansionPacks(installDir, selectedPacks, spinner, config = {}) {\n if (!selectedPacks || selectedPacks.length === 0) {\n return [];\n }\n\n const installedFiles = [];\n\n for (const packId of selectedPacks) {\n spinner.text = `Installing expansion pack: ${packId}...`;\n \n try {\n const expansionPacks = await resourceLocator.getExpansionPacks();\n const pack = expansionPacks.find(p => p.id === packId);\n \n if (!pack) {\n console.warn(`Expansion pack ${packId} not found, skipping...`);\n continue;\n }\n \n // Check if expansion pack already exists\n let expansionDotFolder = path.join(installDir, `.${packId}`);\n const existingManifestPath = path.join(expansionDotFolder, 'install-manifest.yaml');\n \n if (await fileManager.pathExists(existingManifestPath)) {\n spinner.stop();\n const existingManifest = await fileManager.readExpansionPackManifest(installDir, packId);\n \n console.log(chalk.yellow(`\\nšŸ” Found existing ${pack.name} installation`));\n console.log(` Current version: ${existingManifest.version || 'unknown'}`);\n console.log(` New version: ${pack.version}`);\n \n // Check integrity of existing expansion pack\n const packIntegrity = await fileManager.checkFileIntegrity(installDir, existingManifest);\n const hasPackIntegrityIssues = packIntegrity.missing.length > 0 || packIntegrity.modified.length > 0;\n \n if (hasPackIntegrityIssues) {\n console.log(chalk.red(\" āš ļø Installation issues detected:\"));\n if (packIntegrity.missing.length > 0) {\n console.log(chalk.red(` Missing files: ${packIntegrity.missing.length}`));\n }\n if (packIntegrity.modified.length > 0) {\n console.log(chalk.yellow(` Modified files: ${packIntegrity.modified.length}`));\n }\n }\n \n const versionCompare = this.compareVersions(existingManifest.version || '0.0.0', pack.version);\n \n if (versionCompare === 0) {\n console.log(chalk.yellow(' āš ļø Same version already installed'));\n \n const choices = [];\n if (hasPackIntegrityIssues) {\n choices.push({ name: 'Repair (restore missing/modified files)', value: 'repair' });\n }\n choices.push(\n { name: 'Force reinstall (overwrite)', value: 'overwrite' },\n { name: 'Skip this expansion pack', value: 'skip' },\n { name: 'Cancel installation', value: 'cancel' }\n );\n \n const { action } = await inquirer.prompt([{\n type: 'list',\n name: 'action',\n message: `${pack.name} v${pack.version} is already installed. What would you like to do?`,\n choices: choices\n }]);\n \n if (action === 'skip') {\n spinner.start();\n continue;\n } else if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n } else if (action === 'repair') {\n // Repair the expansion pack\n await this.repairExpansionPack(installDir, packId, pack, packIntegrity, spinner);\n continue;\n }\n } else if (versionCompare < 0) {\n console.log(chalk.cyan(' ā¬†ļø Upgrade available'));\n \n const { proceed } = await inquirer.prompt([{\n type: 'confirm',\n name: 'proceed',\n message: `Upgrade ${pack.name} from v${existingManifest.version} to v${pack.version}?`,\n default: true\n }]);\n \n if (!proceed) {\n spinner.start();\n continue;\n }\n } else {\n console.log(chalk.yellow(' ā¬‡ļø Installed version is newer than available version'));\n \n const { action } = await inquirer.prompt([{\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n { name: 'Keep current version', value: 'skip' },\n { name: 'Downgrade to available version', value: 'downgrade' },\n { name: 'Cancel installation', value: 'cancel' }\n ]\n }]);\n \n if (action === 'skip') {\n spinner.start();\n continue;\n } else if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n }\n }\n \n // If we get here, we're proceeding with installation\n spinner.start(`Removing old ${pack.name} installation...`);\n await fileManager.removeDirectory(expansionDotFolder);\n }\n\n const expansionPackDir = pack.path;\n \n // Ensure dedicated dot folder exists for this expansion pack\n expansionDotFolder = path.join(installDir, `.${packId}`);\n await fileManager.ensureDirectory(expansionDotFolder);\n \n // Define the folders to copy from expansion packs\n const foldersToSync = [\n 'agents',\n 'agent-teams',\n 'templates',\n 'tasks',\n 'checklists',\n 'workflows',\n 'data',\n 'utils',\n 'schemas'\n ];\n\n // Copy each folder if it exists\n for (const folder of foldersToSync) {\n const sourceFolder = path.join(expansionPackDir, folder);\n \n // Check if folder exists in expansion pack\n if (await fileManager.pathExists(sourceFolder)) {\n // Get all files in this folder\n const files = await resourceLocator.findFiles('**/*', {\n cwd: sourceFolder,\n nodir: true\n });\n\n // Copy each file to the expansion pack's dot folder with {root} replacement\n for (const file of files) {\n const sourcePath = path.join(sourceFolder, file);\n const destPath = path.join(expansionDotFolder, folder, file);\n \n const needsRootReplacement = file.endsWith('.md') || file.endsWith('.yaml') || file.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, `.${packId}`);\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n \n if (success) {\n installedFiles.push(path.join(`.${packId}`, folder, file));\n }\n }\n }\n }\n\n // Copy config.yaml with {root} replacement\n const configPath = path.join(expansionPackDir, 'config.yaml');\n if (await fileManager.pathExists(configPath)) {\n const configDestPath = path.join(expansionDotFolder, 'config.yaml');\n if (await fileManager.copyFileWithRootReplacement(configPath, configDestPath, `.${packId}`)) {\n installedFiles.push(path.join(`.${packId}`, 'config.yaml'));\n }\n }\n \n // Copy README if it exists with {root} replacement\n const readmePath = path.join(expansionPackDir, 'README.md');\n if (await fileManager.pathExists(readmePath)) {\n const readmeDestPath = path.join(expansionDotFolder, 'README.md');\n if (await fileManager.copyFileWithRootReplacement(readmePath, readmeDestPath, `.${packId}`)) {\n installedFiles.push(path.join(`.${packId}`, 'README.md'));\n }\n }\n\n // Copy common/ items to expansion pack folder\n spinner.text = `Copying common utilities to ${packId}...`;\n await this.copyCommonItems(installDir, `.${packId}`, spinner);\n \n // Check and resolve core dependencies\n await this.resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner);\n \n // Check and resolve core agents referenced by teams\n await this.resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner);\n\n // Create manifest for this expansion pack\n spinner.text = `Creating manifest for ${packId}...`;\n const expansionConfig = {\n installType: 'expansion-pack',\n expansionPackId: packId,\n expansionPackName: pack.name,\n expansionPackVersion: pack.version,\n ides: config.ides || [] // Use ides_setup instead of ide_setup\n };\n \n // Get all files installed in this expansion pack\n const foundFiles = await resourceLocator.findFiles('**/*', {\n cwd: expansionDotFolder,\n nodir: true\n });\n const expansionPackFiles = foundFiles.map(f => path.join(`.${packId}`, f));\n \n await fileManager.createExpansionPackManifest(installDir, packId, expansionConfig, expansionPackFiles);\n\n console.log(chalk.green(`āœ“ Installed expansion pack: ${pack.name} to ${`.${packId}`}`));\n } catch (error) {\n console.error(`Failed to install expansion pack ${packId}: ${error.message}`);\n console.error(`Stack trace: ${error.stack}`);\n }\n }\n\n return installedFiles;\n }\n\n async resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner) {\n const yaml = require('js-yaml');\n const fs = require('fs').promises;\n \n // Find all agent files in the expansion pack\n const agentFiles = await resourceLocator.findFiles('agents/*.md', {\n cwd: expansionDotFolder\n });\n\n for (const agentFile of agentFiles) {\n const agentPath = path.join(expansionDotFolder, agentFile);\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML frontmatter to check dependencies\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n try {\n const agentConfig = yaml.load(yamlContent);\n const dependencies = agentConfig.dependencies || {};\n \n // Check for core dependencies (those that don't exist in the expansion pack)\n for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {\n const deps = dependencies[depType] || [];\n \n for (const dep of deps) {\n const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep : \n (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);\n const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);\n \n // Check if dependency exists in expansion pack dot folder\n if (!(await fileManager.pathExists(expansionDepPath))) {\n // Try to find it in expansion pack source\n const sourceDepPath = path.join(pack.path, depType, depFileName);\n \n if (await fileManager.pathExists(sourceDepPath)) {\n // Copy from expansion pack source\n spinner.text = `Copying ${packId} dependency ${dep}...`;\n const destPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(sourceDepPath, destPath, `.${packId}`);\n console.log(chalk.dim(` Added ${packId} dependency: ${depType}/${depFileName}`));\n } else {\n // Try to find it in core\n const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);\n \n if (await fileManager.pathExists(coreDepPath)) {\n spinner.text = `Copying core dependency ${dep} for ${packId}...`;\n \n // Copy from core to expansion pack dot folder with {root} replacement\n const destPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(coreDepPath, destPath, `.${packId}`);\n \n console.log(chalk.dim(` Added core dependency: ${depType}/${depFileName}`));\n } else {\n console.warn(chalk.yellow(` Warning: Dependency ${depType}/${dep} not found in core or expansion pack`));\n }\n }\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse agent dependencies: ${error.message}`);\n }\n }\n }\n }\n\n async resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner) {\n const yaml = require('js-yaml');\n const fs = require('fs').promises;\n \n // Find all team files in the expansion pack\n const teamFiles = await resourceLocator.findFiles('agent-teams/*.yaml', {\n cwd: expansionDotFolder\n });\n\n // Also get existing agents in the expansion pack\n const existingAgents = new Set();\n const agentFiles = await resourceLocator.findFiles('agents/*.md', {\n cwd: expansionDotFolder\n });\n for (const agentFile of agentFiles) {\n const agentName = path.basename(agentFile, '.md');\n existingAgents.add(agentName);\n }\n\n // Process each team file\n for (const teamFile of teamFiles) {\n const teamPath = path.join(expansionDotFolder, teamFile);\n const teamContent = await fs.readFile(teamPath, 'utf8');\n \n try {\n const teamConfig = yaml.load(teamContent);\n const agents = teamConfig.agents || [];\n \n // Add bmad-orchestrator if not present (required for all teams)\n if (!agents.includes('bmad-orchestrator')) {\n agents.unshift('bmad-orchestrator');\n }\n \n // Check each agent in the team\n for (const agentId of agents) {\n if (!existingAgents.has(agentId)) {\n // Agent not in expansion pack, try to get from core\n const coreAgentPath = path.join(resourceLocator.getBmadCorePath(), 'agents', `${agentId}.md`);\n \n if (await fileManager.pathExists(coreAgentPath)) {\n spinner.text = `Copying core agent ${agentId} for ${packId}...`;\n \n // Copy agent file with {root} replacement\n const destPath = path.join(expansionDotFolder, 'agents', `${agentId}.md`);\n await fileManager.copyFileWithRootReplacement(coreAgentPath, destPath, `.${packId}`);\n existingAgents.add(agentId);\n \n console.log(chalk.dim(` Added core agent: ${agentId}`));\n \n // Now resolve this agent's dependencies too\n const agentContent = await fs.readFile(coreAgentPath, 'utf8');\n const yamlContent = extractYamlFromAgent(agentContent, true);\n \n if (yamlContent) {\n try {\n \n const agentConfig = yaml.load(yamlContent);\n const dependencies = agentConfig.dependencies || {};\n \n // Copy all dependencies for this agent\n for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {\n const deps = dependencies[depType] || [];\n \n for (const dep of deps) {\n const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep : \n (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);\n const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);\n \n // Check if dependency exists in expansion pack\n if (!(await fileManager.pathExists(expansionDepPath))) {\n // Try to find it in core\n const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);\n \n if (await fileManager.pathExists(coreDepPath)) {\n const destDepPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(coreDepPath, destDepPath, `.${packId}`);\n console.log(chalk.dim(` Added agent dependency: ${depType}/${depFileName}`));\n } else {\n // Try common folder\n const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root\n const commonDepPath = path.join(sourceBase, 'common', depType, depFileName);\n if (await fileManager.pathExists(commonDepPath)) {\n const destDepPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFile(commonDepPath, destDepPath);\n console.log(chalk.dim(` Added agent dependency from common: ${depType}/${depFileName}`));\n }\n }\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse agent ${agentId} dependencies: ${error.message}`);\n }\n }\n } else {\n console.warn(chalk.yellow(` Warning: Core agent ${agentId} not found for team ${path.basename(teamFile, '.yaml')}`));\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse team file ${teamFile}: ${error.message}`);\n }\n }\n }\n\n getWebBundleInfo(config) {\n const webBundleType = config.webBundleType || 'all';\n \n switch (webBundleType) {\n case 'all':\n return 'all bundles';\n case 'agents':\n return 'individual agents only';\n case 'teams':\n return config.selectedWebBundleTeams ? \n `teams: ${config.selectedWebBundleTeams.join(', ')}` : \n 'selected teams';\n case 'custom':\n const parts = [];\n if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {\n parts.push(`teams: ${config.selectedWebBundleTeams.join(', ')}`);\n }\n if (config.includeIndividualAgents) {\n parts.push('individual agents');\n }\n return parts.length > 0 ? parts.join(' + ') : 'custom selection';\n default:\n return 'selected bundles';\n }\n }\n\n async installWebBundles(webBundlesDirectory, config, spinner) {\n \n try {\n // Find the dist directory in the BMad installation\n const distDir = configLoader.getDistPath();\n \n if (!(await fileManager.pathExists(distDir))) {\n console.warn('Web bundles not found. Run \"npm run build\" to generate them.');\n return;\n }\n\n // Ensure web bundles directory exists\n await fileManager.ensureDirectory(webBundlesDirectory);\n \n const webBundleType = config.webBundleType || 'all';\n \n if (webBundleType === 'all') {\n // Copy the entire dist directory structure\n await fileManager.copyDirectory(distDir, webBundlesDirectory);\n console.log(chalk.green(`āœ“ Installed all web bundles to: ${webBundlesDirectory}`));\n } else {\n let copiedCount = 0;\n \n // Copy specific selections based on type\n if (webBundleType === 'agents' || (webBundleType === 'custom' && config.includeIndividualAgents)) {\n const agentsSource = path.join(distDir, 'agents');\n const agentsTarget = path.join(webBundlesDirectory, 'agents');\n if (await fileManager.pathExists(agentsSource)) {\n await fileManager.copyDirectory(agentsSource, agentsTarget);\n console.log(chalk.green(`āœ“ Copied individual agent bundles`));\n copiedCount += 10; // Approximate count for agents\n }\n }\n \n if (webBundleType === 'teams' || webBundleType === 'custom') {\n if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {\n const teamsSource = path.join(distDir, 'teams');\n const teamsTarget = path.join(webBundlesDirectory, 'teams');\n await fileManager.ensureDirectory(teamsTarget);\n \n for (const teamId of config.selectedWebBundleTeams) {\n const teamFile = `${teamId}.txt`;\n const sourcePath = path.join(teamsSource, teamFile);\n const targetPath = path.join(teamsTarget, teamFile);\n \n if (await fileManager.pathExists(sourcePath)) {\n await fileManager.copyFile(sourcePath, targetPath);\n copiedCount++;\n console.log(chalk.green(`āœ“ Copied team bundle: ${teamId}`));\n }\n }\n }\n }\n \n // Always copy expansion packs if they exist\n const expansionSource = path.join(distDir, 'expansion-packs');\n const expansionTarget = path.join(webBundlesDirectory, 'expansion-packs');\n if (await fileManager.pathExists(expansionSource)) {\n await fileManager.copyDirectory(expansionSource, expansionTarget);\n console.log(chalk.green(`āœ“ Copied expansion pack bundles`));\n }\n \n console.log(chalk.green(`āœ“ Installed ${copiedCount} selected web bundles to: ${webBundlesDirectory}`));\n }\n } catch (error) {\n console.error(`Failed to install web bundles: ${error.message}`);\n }\n }\n\n async copyCommonItems(installDir, targetSubdir, spinner) {\n \n const fs = require('fs').promises;\n const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root\n const commonPath = path.join(sourceBase, 'common');\n const targetPath = path.join(installDir, targetSubdir);\n const copiedFiles = [];\n \n // Check if common/ exists\n if (!(await fileManager.pathExists(commonPath))) {\n console.warn('Warning: common/ folder not found');\n return copiedFiles;\n }\n \n // Copy all items from common/ to target\n const commonItems = await resourceLocator.findFiles('**/*', {\n cwd: commonPath,\n nodir: true\n });\n \n for (const item of commonItems) {\n const sourcePath = path.join(commonPath, item);\n const destPath = path.join(targetPath, item);\n \n // Read the file content\n const content = await fs.readFile(sourcePath, 'utf8');\n \n // Replace {root} with the target subdirectory\n const updatedContent = content.replace(/\\{root\\}/g, targetSubdir);\n \n // Ensure directory exists\n await fileManager.ensureDirectory(path.dirname(destPath));\n \n // Write the updated content\n await fs.writeFile(destPath, updatedContent, 'utf8');\n copiedFiles.push(path.join(targetSubdir, item));\n }\n \n console.log(chalk.dim(` Added ${commonItems.length} common utilities`));\n return copiedFiles;\n }\n\n async detectExpansionPacks(installDir) {\n const expansionPacks = {};\n const glob = require(\"glob\");\n \n // Find all dot folders that might be expansion packs\n const dotFolders = glob.sync(\".*\", {\n cwd: installDir,\n ignore: [\".git\", \".git/**\", \".bmad-core\", \".bmad-core/**\"],\n });\n \n for (const folder of dotFolders) {\n const folderPath = path.join(installDir, folder);\n const stats = await fileManager.pathExists(folderPath);\n \n if (stats) {\n // Check if it has a manifest\n const manifestPath = path.join(folderPath, \"install-manifest.yaml\");\n if (await fileManager.pathExists(manifestPath)) {\n const manifest = await fileManager.readExpansionPackManifest(installDir, folder.substring(1));\n if (manifest) {\n expansionPacks[folder.substring(1)] = {\n path: folderPath,\n manifest: manifest,\n hasManifest: true\n };\n }\n } else {\n // Check if it has a config.yaml (expansion pack without manifest)\n const configPath = path.join(folderPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n expansionPacks[folder.substring(1)] = {\n path: folderPath,\n manifest: null,\n hasManifest: false\n };\n }\n }\n }\n }\n \n return expansionPacks;\n }\n\n async repairExpansionPack(installDir, packId, pack, integrity, spinner) {\n spinner.start(`Repairing ${pack.name}...`);\n \n try {\n const expansionDotFolder = path.join(installDir, `.${packId}`);\n \n // Back up modified files\n if (integrity.modified.length > 0) {\n spinner.text = \"Backing up modified files...\";\n for (const file of integrity.modified) {\n const filePath = path.join(installDir, file);\n if (await fileManager.pathExists(filePath)) {\n const backupPath = await fileManager.backupFile(filePath);\n console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));\n }\n }\n }\n \n // Restore missing and modified files\n spinner.text = \"Restoring files...\";\n const filesToRestore = [...integrity.missing, ...integrity.modified];\n \n for (const file of filesToRestore) {\n // Skip the manifest file itself\n if (file.endsWith('install-manifest.yaml')) continue;\n \n const relativePath = file.replace(`.${packId}/`, '');\n const sourcePath = path.join(pack.path, relativePath);\n const destPath = path.join(installDir, file);\n \n // Check if this is a common/ file that needs special processing\n const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));\n const commonSourcePath = path.join(commonBase, 'common', relativePath);\n \n if (await fileManager.pathExists(commonSourcePath)) {\n // This is a common/ file - needs template processing\n const fs = require('fs').promises;\n const content = await fs.readFile(commonSourcePath, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, `.${packId}`);\n await fileManager.ensureDirectory(path.dirname(destPath));\n await fs.writeFile(destPath, updatedContent, 'utf8');\n spinner.text = `Restored: ${file}`;\n } else if (await fileManager.pathExists(sourcePath)) {\n // Regular file from expansion pack\n await fileManager.copyFile(sourcePath, destPath);\n spinner.text = `Restored: ${file}`;\n } else {\n console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));\n }\n }\n \n spinner.succeed(`${pack.name} repaired successfully!`);\n \n // Show summary\n console.log(chalk.green(`\\nāœ“ ${pack.name} repaired!`));\n if (integrity.missing.length > 0) {\n console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));\n }\n if (integrity.modified.length > 0) {\n console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));\n }\n \n } catch (error) {\n if (spinner) spinner.fail(`Failed to repair ${pack.name}`);\n console.error(`Error: ${error.message}`);\n }\n }\n\n compareVersions(v1, v2) {\n // Simple semver comparison\n const parts1 = v1.split('.').map(Number);\n const parts2 = v2.split('.').map(Number);\n \n for (let i = 0; i < 3; i++) {\n const part1 = parts1[i] || 0;\n const part2 = parts2[i] || 0;\n \n if (part1 > part2) return 1;\n if (part1 < part2) return -1;\n }\n \n return 0;\n }\n\n async cleanupLegacyYmlFiles(installDir, spinner) {\n const glob = require('glob');\n const fs = require('fs').promises;\n \n try {\n // Find all .yml files in the installation directory\n const ymlFiles = glob.sync('**/*.yml', {\n cwd: installDir,\n ignore: ['**/node_modules/**', '**/.git/**']\n });\n \n let deletedCount = 0;\n \n for (const ymlFile of ymlFiles) {\n // Check if corresponding .yaml file exists\n const yamlFile = ymlFile.replace(/\\.yml$/, '.yaml');\n const ymlPath = path.join(installDir, ymlFile);\n const yamlPath = path.join(installDir, yamlFile);\n \n if (await fileManager.pathExists(yamlPath)) {\n // .yaml counterpart exists, delete the .yml file\n await fs.unlink(ymlPath);\n deletedCount++;\n console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${yamlFile})`));\n }\n }\n \n if (deletedCount > 0) {\n console.log(chalk.green(`āœ“ Cleaned up ${deletedCount} legacy .yml files`));\n }\n \n } catch (error) {\n console.warn(`Warning: Could not cleanup legacy .yml files: ${error.message}`);\n }\n }\n\n async findInstallation() {\n // Look for .bmad-core in current directory or parent directories\n let currentDir = process.cwd();\n\n while (currentDir !== path.dirname(currentDir)) {\n const bmadDir = path.join(currentDir, \".bmad-core\");\n const manifestPath = path.join(bmadDir, \"install-manifest.yaml\");\n\n if (await fileManager.pathExists(manifestPath)) {\n return bmadDir;\n }\n\n currentDir = path.dirname(currentDir);\n }\n\n // Also check if we're inside a .bmad-core directory\n if (path.basename(process.cwd()) === \".bmad-core\") {\n const manifestPath = path.join(process.cwd(), \"install-manifest.yaml\");\n if (await fileManager.pathExists(manifestPath)) {\n return process.cwd();\n }\n }\n\n return null;\n }\n}\n\nmodule.exports = new Installer();\n"], ["/BMAD-METHOD/tools/builders/web-builder.js", "const fs = require(\"node:fs\").promises;\nconst path = require(\"node:path\");\nconst DependencyResolver = require(\"../lib/dependency-resolver\");\nconst yamlUtils = require(\"../lib/yaml-utils\");\n\nclass WebBuilder {\n constructor(options = {}) {\n this.rootDir = options.rootDir || process.cwd();\n this.outputDirs = options.outputDirs || [path.join(this.rootDir, \"dist\")];\n this.resolver = new DependencyResolver(this.rootDir);\n this.templatePath = path.join(\n this.rootDir,\n \"tools\",\n \"md-assets\",\n \"web-agent-startup-instructions.md\"\n );\n }\n\n parseYaml(content) {\n const yaml = require(\"js-yaml\");\n return yaml.load(content);\n }\n\n convertToWebPath(filePath, bundleRoot = 'bmad-core') {\n // Convert absolute paths to web bundle paths with dot prefix\n // All resources get installed under the bundle root, so use that path\n const relativePath = path.relative(this.rootDir, filePath);\n const pathParts = relativePath.split(path.sep);\n \n let resourcePath;\n if (pathParts[0] === 'expansion-packs') {\n // For expansion packs, remove 'expansion-packs/packname' and use the rest\n resourcePath = pathParts.slice(2).join('/');\n } else {\n // For bmad-core, common, etc., remove the first part\n resourcePath = pathParts.slice(1).join('/');\n }\n \n return `.${bundleRoot}/${resourcePath}`;\n }\n\n generateWebInstructions(bundleType, packName = null) {\n // Generate dynamic web instructions based on bundle type\n const rootExample = packName ? `.${packName}` : '.bmad-core';\n const examplePath = packName ? `.${packName}/folder/filename.md` : '.bmad-core/folder/filename.md';\n const personasExample = packName ? `.${packName}/personas/analyst.md` : '.bmad-core/personas/analyst.md';\n const tasksExample = packName ? `.${packName}/tasks/create-story.md` : '.bmad-core/tasks/create-story.md';\n const utilsExample = packName ? `.${packName}/utils/template-format.md` : '.bmad-core/utils/template-format.md';\n const tasksRef = packName ? `.${packName}/tasks/create-story.md` : '.bmad-core/tasks/create-story.md';\n\n return `# Web Agent Bundle Instructions\n\nYou are now operating as a specialized AI agent from the BMad-Method framework. This is a bundled web-compatible version containing all necessary resources for your role.\n\n## Important Instructions\n\n1. **Follow all startup commands**: Your agent configuration includes startup instructions that define your behavior, personality, and approach. These MUST be followed exactly.\n\n2. **Resource Navigation**: This bundle contains all resources you need. Resources are marked with tags like:\n\n- \\`==================== START: ${examplePath} ====================\\`\n- \\`==================== END: ${examplePath} ====================\\`\n\nWhen you need to reference a resource mentioned in your instructions:\n\n- Look for the corresponding START/END tags\n- The format is always the full path with dot prefix (e.g., \\`${personasExample}\\`, \\`${tasksExample}\\`)\n- If a section is specified (e.g., \\`{root}/tasks/create-story.md#section-name\\`), navigate to that section within the file\n\n**Understanding YAML References**: In the agent configuration, resources are referenced in the dependencies section. For example:\n\n\\`\\`\\`yaml\ndependencies:\n utils:\n - template-format\n tasks:\n - create-story\n\\`\\`\\`\n\nThese references map directly to bundle sections:\n\n- \\`utils: template-format\\` → Look for \\`==================== START: ${utilsExample} ====================\\`\n- \\`tasks: create-story\\` → Look for \\`==================== START: ${tasksRef} ====================\\`\n\n3. **Execution Context**: You are operating in a web environment. All your capabilities and knowledge are contained within this bundle. Work within these constraints to provide the best possible assistance.\n\n4. **Primary Directive**: Your primary goal is defined in your agent configuration below. Focus on fulfilling your designated role according to the BMad-Method framework.\n\n---\n\n`;\n }\n\n async cleanOutputDirs() {\n for (const dir of this.outputDirs) {\n try {\n await fs.rm(dir, { recursive: true, force: true });\n console.log(`Cleaned: ${path.relative(this.rootDir, dir)}`);\n } catch (error) {\n console.debug(`Failed to clean directory ${dir}:`, error.message);\n // Directory might not exist, that's fine\n }\n }\n }\n\n async buildAgents() {\n const agents = await this.resolver.listAgents();\n\n for (const agentId of agents) {\n console.log(` Building agent: ${agentId}`);\n const bundle = await this.buildAgentBundle(agentId);\n\n // Write to all output directories\n for (const outputDir of this.outputDirs) {\n const outputPath = path.join(outputDir, \"agents\");\n await fs.mkdir(outputPath, { recursive: true });\n const outputFile = path.join(outputPath, `${agentId}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n\n console.log(`Built ${agents.length} agent bundles in ${this.outputDirs.length} locations`);\n }\n\n async buildTeams() {\n const teams = await this.resolver.listTeams();\n\n for (const teamId of teams) {\n console.log(` Building team: ${teamId}`);\n const bundle = await this.buildTeamBundle(teamId);\n\n // Write to all output directories\n for (const outputDir of this.outputDirs) {\n const outputPath = path.join(outputDir, \"teams\");\n await fs.mkdir(outputPath, { recursive: true });\n const outputFile = path.join(outputPath, `${teamId}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n\n console.log(`Built ${teams.length} team bundles in ${this.outputDirs.length} locations`);\n }\n\n async buildAgentBundle(agentId) {\n const dependencies = await this.resolver.resolveAgentDependencies(agentId);\n const template = this.generateWebInstructions('agent');\n\n const sections = [template];\n\n // Add agent configuration\n const agentPath = this.convertToWebPath(dependencies.agent.path, 'bmad-core');\n sections.push(this.formatSection(agentPath, dependencies.agent.content, 'bmad-core'));\n\n // Add all dependencies\n for (const resource of dependencies.resources) {\n const resourcePath = this.convertToWebPath(resource.path, 'bmad-core');\n sections.push(this.formatSection(resourcePath, resource.content, 'bmad-core'));\n }\n\n return sections.join(\"\\n\");\n }\n\n async buildTeamBundle(teamId) {\n const dependencies = await this.resolver.resolveTeamDependencies(teamId);\n const template = this.generateWebInstructions('team');\n\n const sections = [template];\n\n // Add team configuration\n const teamPath = this.convertToWebPath(dependencies.team.path, 'bmad-core');\n sections.push(this.formatSection(teamPath, dependencies.team.content, 'bmad-core'));\n\n // Add all agents\n for (const agent of dependencies.agents) {\n const agentPath = this.convertToWebPath(agent.path, 'bmad-core');\n sections.push(this.formatSection(agentPath, agent.content, 'bmad-core'));\n }\n\n // Add all deduplicated resources\n for (const resource of dependencies.resources) {\n const resourcePath = this.convertToWebPath(resource.path, 'bmad-core');\n sections.push(this.formatSection(resourcePath, resource.content, 'bmad-core'));\n }\n\n return sections.join(\"\\n\");\n }\n\n processAgentContent(content) {\n // First, replace content before YAML with the template\n const yamlContent = yamlUtils.extractYamlFromAgent(content);\n if (!yamlContent) return content;\n\n const yamlMatch = content.match(/```ya?ml\\n([\\s\\S]*?)\\n```/);\n if (!yamlMatch) return content;\n \n const yamlStartIndex = content.indexOf(yamlMatch[0]);\n const yamlEndIndex = yamlStartIndex + yamlMatch[0].length;\n\n // Parse YAML and remove root and IDE-FILE-RESOLUTION properties\n try {\n const yaml = require(\"js-yaml\");\n const parsed = yaml.load(yamlContent);\n\n // Remove the properties if they exist at root level\n delete parsed.root;\n delete parsed[\"IDE-FILE-RESOLUTION\"];\n delete parsed[\"REQUEST-RESOLUTION\"];\n\n // Also remove from activation-instructions if they exist\n if (parsed[\"activation-instructions\"] && Array.isArray(parsed[\"activation-instructions\"])) {\n parsed[\"activation-instructions\"] = parsed[\"activation-instructions\"].filter(\n (instruction) => {\n return (\n typeof instruction === 'string' &&\n !instruction.startsWith(\"IDE-FILE-RESOLUTION:\") &&\n !instruction.startsWith(\"REQUEST-RESOLUTION:\")\n );\n }\n );\n }\n\n // Reconstruct the YAML\n const cleanedYaml = yaml.dump(parsed, { lineWidth: -1 });\n\n // Get the agent name from the YAML for the header\n const agentName = parsed.agent?.id || \"agent\";\n\n // Build the new content with just the agent header and YAML\n const newHeader = `# ${agentName}\\n\\nCRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n`;\n const afterYaml = content.substring(yamlEndIndex);\n\n return newHeader + \"```yaml\\n\" + cleanedYaml.trim() + \"\\n```\" + afterYaml;\n } catch (error) {\n console.warn(\"Failed to process agent YAML:\", error.message);\n // If parsing fails, return original content\n return content;\n }\n }\n\n formatSection(path, content, bundleRoot = 'bmad-core') {\n const separator = \"====================\";\n\n // Process agent content if this is an agent file\n if (path.includes(\"/agents/\")) {\n content = this.processAgentContent(content);\n }\n\n // Replace {root} references with the actual bundle root\n content = this.replaceRootReferences(content, bundleRoot);\n\n return [\n `${separator} START: ${path} ${separator}`,\n content.trim(),\n `${separator} END: ${path} ${separator}`,\n \"\",\n ].join(\"\\n\");\n }\n\n replaceRootReferences(content, bundleRoot) {\n // Replace {root} with the appropriate bundle root path\n return content.replace(/\\{root\\}/g, `.${bundleRoot}`);\n }\n\n async validate() {\n console.log(\"Validating agent configurations...\");\n const agents = await this.resolver.listAgents();\n for (const agentId of agents) {\n try {\n await this.resolver.resolveAgentDependencies(agentId);\n console.log(` āœ“ ${agentId}`);\n } catch (error) {\n console.log(` āœ— ${agentId}: ${error.message}`);\n throw error;\n }\n }\n\n console.log(\"\\nValidating team configurations...\");\n const teams = await this.resolver.listTeams();\n for (const teamId of teams) {\n try {\n await this.resolver.resolveTeamDependencies(teamId);\n console.log(` āœ“ ${teamId}`);\n } catch (error) {\n console.log(` āœ— ${teamId}: ${error.message}`);\n throw error;\n }\n }\n }\n\n async buildAllExpansionPacks(options = {}) {\n const expansionPacks = await this.listExpansionPacks();\n\n for (const packName of expansionPacks) {\n console.log(` Building expansion pack: ${packName}`);\n await this.buildExpansionPack(packName, options);\n }\n\n console.log(`Built ${expansionPacks.length} expansion pack bundles`);\n }\n\n async buildExpansionPack(packName, options = {}) {\n const packDir = path.join(this.rootDir, \"expansion-packs\", packName);\n const outputDirs = [path.join(this.rootDir, \"dist\", \"expansion-packs\", packName)];\n\n // Clean output directories if requested\n if (options.clean !== false) {\n for (const outputDir of outputDirs) {\n try {\n await fs.rm(outputDir, { recursive: true, force: true });\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n }\n\n // Build individual agents first\n const agentsDir = path.join(packDir, \"agents\");\n try {\n const agentFiles = await fs.readdir(agentsDir);\n const agentMarkdownFiles = agentFiles.filter((f) => f.endsWith(\".md\"));\n\n if (agentMarkdownFiles.length > 0) {\n console.log(` Building individual agents for ${packName}:`);\n\n for (const agentFile of agentMarkdownFiles) {\n const agentName = agentFile.replace(\".md\", \"\");\n console.log(` - ${agentName}`);\n\n // Build individual agent bundle\n const bundle = await this.buildExpansionAgentBundle(packName, packDir, agentName);\n\n // Write to all output directories\n for (const outputDir of outputDirs) {\n const agentsOutputDir = path.join(outputDir, \"agents\");\n await fs.mkdir(agentsOutputDir, { recursive: true });\n const outputFile = path.join(agentsOutputDir, `${agentName}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n }\n } catch (error) {\n console.debug(` No agents directory found for ${packName}`);\n }\n\n // Build team bundle\n const agentTeamsDir = path.join(packDir, \"agent-teams\");\n try {\n const teamFiles = await fs.readdir(agentTeamsDir);\n const teamFile = teamFiles.find((f) => f.endsWith(\".yaml\"));\n\n if (teamFile) {\n console.log(` Building team bundle for ${packName}`);\n const teamConfigPath = path.join(agentTeamsDir, teamFile);\n\n // Build expansion pack as a team bundle\n const bundle = await this.buildExpansionTeamBundle(packName, packDir, teamConfigPath);\n\n // Write to all output directories\n for (const outputDir of outputDirs) {\n const teamsOutputDir = path.join(outputDir, \"teams\");\n await fs.mkdir(teamsOutputDir, { recursive: true });\n const outputFile = path.join(teamsOutputDir, teamFile.replace(\".yaml\", \".txt\"));\n await fs.writeFile(outputFile, bundle, \"utf8\");\n console.log(` āœ“ Created bundle: ${path.relative(this.rootDir, outputFile)}`);\n }\n } else {\n console.warn(` ⚠ No team configuration found in ${packName}/agent-teams/`);\n }\n } catch (error) {\n console.warn(` ⚠ No agent-teams directory found for ${packName}`);\n }\n }\n\n async buildExpansionAgentBundle(packName, packDir, agentName) {\n const template = this.generateWebInstructions('expansion-agent', packName);\n const sections = [template];\n\n // Add agent configuration\n const agentPath = path.join(packDir, \"agents\", `${agentName}.md`);\n const agentContent = await fs.readFile(agentPath, \"utf8\");\n const agentWebPath = this.convertToWebPath(agentPath, packName);\n sections.push(this.formatSection(agentWebPath, agentContent, packName));\n\n // Resolve and add agent dependencies\n const yamlContent = yamlUtils.extractYamlFromAgent(agentContent);\n if (yamlContent) {\n try {\n const yaml = require(\"js-yaml\");\n const agentConfig = yaml.load(yamlContent);\n\n if (agentConfig.dependencies) {\n // Add resources, first try expansion pack, then core\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n let found = false;\n\n // Try expansion pack first\n const resourcePath = path.join(packDir, resourceType, resourceName);\n try {\n const resourceContent = await fs.readFile(resourcePath, \"utf8\");\n const resourceWebPath = this.convertToWebPath(resourcePath, packName);\n sections.push(\n this.formatSection(resourceWebPath, resourceContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in expansion pack, continue\n }\n\n // If not found in expansion pack, try core\n if (!found) {\n const corePath = path.join(\n this.rootDir,\n \"bmad-core\",\n resourceType,\n resourceName\n );\n try {\n const coreContent = await fs.readFile(corePath, \"utf8\");\n const coreWebPath = this.convertToWebPath(corePath, packName);\n sections.push(\n this.formatSection(coreWebPath, coreContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in core either, continue\n }\n }\n\n // If not found in core, try common folder\n if (!found) {\n const commonPath = path.join(\n this.rootDir,\n \"common\",\n resourceType,\n resourceName\n );\n try {\n const commonContent = await fs.readFile(commonPath, \"utf8\");\n const commonWebPath = this.convertToWebPath(commonPath, packName);\n sections.push(\n this.formatSection(commonWebPath, commonContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in common either, continue\n }\n }\n\n if (!found) {\n console.warn(\n ` ⚠ Dependency ${resourceType}#${resourceName} not found in expansion pack or core`\n );\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentName}:`, error.message);\n }\n }\n\n return sections.join(\"\\n\");\n }\n\n async buildExpansionTeamBundle(packName, packDir, teamConfigPath) {\n const template = this.generateWebInstructions('expansion-team', packName);\n\n const sections = [template];\n\n // Add team configuration and parse to get agent list\n const teamContent = await fs.readFile(teamConfigPath, \"utf8\");\n const teamFileName = path.basename(teamConfigPath, \".yaml\");\n const teamConfig = this.parseYaml(teamContent);\n const teamWebPath = this.convertToWebPath(teamConfigPath, packName);\n sections.push(this.formatSection(teamWebPath, teamContent, packName));\n\n // Get list of expansion pack agents\n const expansionAgents = new Set();\n const agentsDir = path.join(packDir, \"agents\");\n try {\n const agentFiles = await fs.readdir(agentsDir);\n for (const agentFile of agentFiles.filter((f) => f.endsWith(\".md\"))) {\n const agentName = agentFile.replace(\".md\", \"\");\n expansionAgents.add(agentName);\n }\n } catch (error) {\n console.warn(` ⚠ No agents directory found in ${packName}`);\n }\n\n // Build a map of all available expansion pack resources for override checking\n const expansionResources = new Map();\n const resourceDirs = [\"templates\", \"tasks\", \"checklists\", \"workflows\", \"data\"];\n for (const resourceDir of resourceDirs) {\n const resourcePath = path.join(packDir, resourceDir);\n try {\n const resourceFiles = await fs.readdir(resourcePath);\n for (const resourceFile of resourceFiles.filter(\n (f) => f.endsWith(\".md\") || f.endsWith(\".yaml\")\n )) {\n expansionResources.set(`${resourceDir}#${resourceFile}`, true);\n }\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n\n // Process all agents listed in team configuration\n const agentsToProcess = teamConfig.agents || [];\n\n // Ensure bmad-orchestrator is always included for teams\n if (!agentsToProcess.includes(\"bmad-orchestrator\")) {\n console.warn(` ⚠ Team ${teamFileName} missing bmad-orchestrator, adding automatically`);\n agentsToProcess.unshift(\"bmad-orchestrator\");\n }\n\n // Track all dependencies from all agents (deduplicated)\n const allDependencies = new Map();\n\n for (const agentId of agentsToProcess) {\n if (expansionAgents.has(agentId)) {\n // Use expansion pack version (override)\n const agentPath = path.join(agentsDir, `${agentId}.md`);\n const agentContent = await fs.readFile(agentPath, \"utf8\");\n const expansionAgentWebPath = this.convertToWebPath(agentPath, packName);\n sections.push(this.formatSection(expansionAgentWebPath, agentContent, packName));\n\n // Parse and collect dependencies from expansion agent\n const agentYaml = agentContent.match(/```yaml\\n([\\s\\S]*?)\\n```/);\n if (agentYaml) {\n try {\n const agentConfig = this.parseYaml(agentYaml[1]);\n if (agentConfig.dependencies) {\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n const key = `${resourceType}#${resourceName}`;\n if (!allDependencies.has(key)) {\n allDependencies.set(key, { type: resourceType, name: resourceName });\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentId}:`, error.message);\n }\n }\n } else {\n // Use core BMad version\n try {\n const coreAgentPath = path.join(this.rootDir, \"bmad-core\", \"agents\", `${agentId}.md`);\n const coreAgentContent = await fs.readFile(coreAgentPath, \"utf8\");\n const coreAgentWebPath = this.convertToWebPath(coreAgentPath, packName);\n sections.push(this.formatSection(coreAgentWebPath, coreAgentContent, packName));\n\n // Parse and collect dependencies from core agent\n const yamlContent = yamlUtils.extractYamlFromAgent(coreAgentContent, true);\n if (yamlContent) {\n try {\n const agentConfig = this.parseYaml(yamlContent);\n if (agentConfig.dependencies) {\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n const key = `${resourceType}#${resourceName}`;\n if (!allDependencies.has(key)) {\n allDependencies.set(key, { type: resourceType, name: resourceName });\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentId}:`, error.message);\n }\n }\n } catch (error) {\n console.warn(` ⚠ Agent ${agentId} not found in core or expansion pack`);\n }\n }\n }\n\n // Add all collected dependencies from agents\n // Always prefer expansion pack versions if they exist\n for (const [key, dep] of allDependencies) {\n let found = false;\n\n // Always check expansion pack first, even if the dependency came from a core agent\n if (expansionResources.has(key)) {\n // We know it exists in expansion pack, find and load it\n const expansionPath = path.join(packDir, dep.type, dep.name);\n try {\n const content = await fs.readFile(expansionPath, \"utf8\");\n const expansionWebPath = this.convertToWebPath(expansionPath, packName);\n sections.push(this.formatSection(expansionWebPath, content, packName));\n console.log(` āœ“ Using expansion override for ${key}`);\n found = true;\n } catch (error) {\n // Try next extension\n }\n }\n\n // If not found in expansion pack (or doesn't exist there), try core\n if (!found) {\n const corePath = path.join(this.rootDir, \"bmad-core\", dep.type, dep.name);\n try {\n const content = await fs.readFile(corePath, \"utf8\");\n const coreWebPath = this.convertToWebPath(corePath, packName);\n sections.push(this.formatSection(coreWebPath, content, packName));\n found = true;\n } catch (error) {\n // Not in core either, continue\n }\n }\n\n // If not found in core, try common folder\n if (!found) {\n const commonPath = path.join(this.rootDir, \"common\", dep.type, dep.name);\n try {\n const content = await fs.readFile(commonPath, \"utf8\");\n const commonWebPath = this.convertToWebPath(commonPath, packName);\n sections.push(this.formatSection(commonWebPath, content, packName));\n found = true;\n } catch (error) {\n // Not in common either, continue\n }\n }\n\n if (!found) {\n console.warn(` ⚠ Dependency ${key} not found in expansion pack or core`);\n }\n }\n\n // Add remaining expansion pack resources not already included as dependencies\n for (const resourceDir of resourceDirs) {\n const resourcePath = path.join(packDir, resourceDir);\n try {\n const resourceFiles = await fs.readdir(resourcePath);\n for (const resourceFile of resourceFiles.filter(\n (f) => f.endsWith(\".md\") || f.endsWith(\".yaml\")\n )) {\n const filePath = path.join(resourcePath, resourceFile);\n const fileContent = await fs.readFile(filePath, \"utf8\");\n const fileName = resourceFile.replace(/\\.(md|yaml)$/, \"\");\n\n // Only add if not already included as a dependency\n const resourceKey = `${resourceDir}#${fileName}`;\n if (!allDependencies.has(resourceKey)) {\n const fullResourcePath = path.join(resourcePath, resourceFile);\n const resourceWebPath = this.convertToWebPath(fullResourcePath, packName);\n sections.push(this.formatSection(resourceWebPath, fileContent, packName));\n }\n }\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n\n return sections.join(\"\\n\");\n }\n\n async listExpansionPacks() {\n const expansionPacksDir = path.join(this.rootDir, \"expansion-packs\");\n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);\n } catch (error) {\n console.warn(\"No expansion-packs directory found\");\n return [];\n }\n }\n\n listAgents() {\n return this.resolver.listAgents();\n }\n}\n\nmodule.exports = WebBuilder;\n"], ["/BMAD-METHOD/tools/installer/lib/ide-setup.js", "const path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst inquirer = require(\"inquirer\");\nconst fileManager = require(\"./file-manager\");\nconst configLoader = require(\"./config-loader\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\nconst BaseIdeSetup = require(\"./ide-base-setup\");\nconst resourceLocator = require(\"./resource-locator\");\n\nclass IdeSetup extends BaseIdeSetup {\n constructor() {\n super();\n this.ideAgentConfig = null;\n }\n\n async loadIdeAgentConfig() {\n if (this.ideAgentConfig) return this.ideAgentConfig;\n \n try {\n const configPath = path.join(__dirname, '..', 'config', 'ide-agent-config.yaml');\n const configContent = await fs.readFile(configPath, 'utf8');\n this.ideAgentConfig = yaml.load(configContent);\n return this.ideAgentConfig;\n } catch (error) {\n console.warn('Failed to load IDE agent configuration, using defaults');\n return {\n 'roo-permissions': {},\n 'cline-order': {}\n };\n }\n }\n\n async setup(ide, installDir, selectedAgent = null, spinner = null, preConfiguredSettings = null) {\n const ideConfig = await configLoader.getIdeConfiguration(ide);\n\n if (!ideConfig) {\n console.log(chalk.yellow(`\\nNo configuration available for ${ide}`));\n return false;\n }\n\n switch (ide) {\n case \"cursor\":\n return this.setupCursor(installDir, selectedAgent);\n case \"claude-code\":\n return this.setupClaudeCode(installDir, selectedAgent);\n case \"windsurf\":\n return this.setupWindsurf(installDir, selectedAgent);\n case \"trae\":\n return this.setupTrae(installDir, selectedAgent);\n case \"roo\":\n return this.setupRoo(installDir, selectedAgent);\n case \"cline\":\n return this.setupCline(installDir, selectedAgent);\n case \"gemini\":\n return this.setupGeminiCli(installDir, selectedAgent);\n case \"github-copilot\":\n return this.setupGitHubCopilot(installDir, selectedAgent, spinner, preConfiguredSettings);\n default:\n console.log(chalk.yellow(`\\nIDE ${ide} not yet supported`));\n return false;\n }\n }\n\n async setupCursor(installDir, selectedAgent) {\n const cursorRulesDir = path.join(installDir, \".cursor\", \"rules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(cursorRulesDir);\n\n for (const agentId of agents) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const mdcContent = await this.createAgentRuleContent(agentId, agentPath, installDir, 'mdc');\n const mdcPath = path.join(cursorRulesDir, `${agentId}.mdc`);\n await fileManager.writeFile(mdcPath, mdcContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.mdc`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Cursor rules in ${cursorRulesDir}`));\n return true;\n }\n\n async setupClaudeCode(installDir, selectedAgent) {\n // Setup bmad-core commands\n const coreSlashPrefix = await this.getCoreSlashPrefix(installDir);\n const coreAgents = selectedAgent ? [selectedAgent] : await this.getCoreAgentIds(installDir);\n const coreTasks = await this.getCoreTaskIds(installDir);\n await this.setupClaudeCodeForPackage(installDir, \"core\", coreSlashPrefix, coreAgents, coreTasks, \".bmad-core\");\n\n // Setup expansion pack commands\n const expansionPacks = await this.getInstalledExpansionPacks(installDir);\n for (const packInfo of expansionPacks) {\n const packSlashPrefix = await this.getExpansionPackSlashPrefix(packInfo.path);\n const packAgents = await this.getExpansionPackAgents(packInfo.path);\n const packTasks = await this.getExpansionPackTasks(packInfo.path);\n \n if (packAgents.length > 0 || packTasks.length > 0) {\n // Use the actual directory name where the expansion pack is installed\n const rootPath = path.relative(installDir, packInfo.path);\n await this.setupClaudeCodeForPackage(installDir, packInfo.name, packSlashPrefix, packAgents, packTasks, rootPath);\n }\n }\n\n return true;\n }\n\n async setupClaudeCodeForPackage(installDir, packageName, slashPrefix, agentIds, taskIds, rootPath) {\n const commandsBaseDir = path.join(installDir, \".claude\", \"commands\", slashPrefix);\n const agentsDir = path.join(commandsBaseDir, \"agents\");\n const tasksDir = path.join(commandsBaseDir, \"tasks\");\n\n // Ensure directories exist\n await fileManager.ensureDirectory(agentsDir);\n await fileManager.ensureDirectory(tasksDir);\n\n // Setup agents\n for (const agentId of agentIds) {\n // Find the agent file - for expansion packs, prefer the expansion pack version\n let agentPath;\n if (packageName !== \"core\") {\n // For expansion packs, first try to find the agent in the expansion pack directory\n const expansionPackPath = path.join(installDir, rootPath, \"agents\", `${agentId}.md`);\n if (await fileManager.pathExists(expansionPackPath)) {\n agentPath = expansionPackPath;\n } else {\n // Fall back to core if not found in expansion pack\n agentPath = await this.findAgentPath(agentId, installDir);\n }\n } else {\n // For core, use the normal search\n agentPath = await this.findAgentPath(agentId, installDir);\n }\n \n const commandPath = path.join(agentsDir, `${agentId}.md`);\n\n if (agentPath) {\n // Create command file with agent content\n let agentContent = await fileManager.readFile(agentPath);\n \n // Replace {root} placeholder with the appropriate root path for this context\n agentContent = agentContent.replace(/{root}/g, rootPath);\n\n // Add command header\n let commandContent = `# /${agentId} Command\\n\\n`;\n commandContent += `When this command is used, adopt the following agent persona:\\n\\n`;\n commandContent += agentContent;\n\n await fileManager.writeFile(commandPath, commandContent);\n console.log(chalk.green(`āœ“ Created agent command: /${agentId}`));\n }\n }\n\n // Setup tasks\n for (const taskId of taskIds) {\n // Find the task file - for expansion packs, prefer the expansion pack version\n let taskPath;\n if (packageName !== \"core\") {\n // For expansion packs, first try to find the task in the expansion pack directory\n const expansionPackPath = path.join(installDir, rootPath, \"tasks\", `${taskId}.md`);\n if (await fileManager.pathExists(expansionPackPath)) {\n taskPath = expansionPackPath;\n } else {\n // Fall back to core if not found in expansion pack\n taskPath = await this.findTaskPath(taskId, installDir);\n }\n } else {\n // For core, use the normal search\n taskPath = await this.findTaskPath(taskId, installDir);\n }\n \n const commandPath = path.join(tasksDir, `${taskId}.md`);\n\n if (taskPath) {\n // Create command file with task content\n let taskContent = await fileManager.readFile(taskPath);\n \n // Replace {root} placeholder with the appropriate root path for this context\n taskContent = taskContent.replace(/{root}/g, rootPath);\n\n // Add command header\n let commandContent = `# /${taskId} Task\\n\\n`;\n commandContent += `When this command is used, execute the following task:\\n\\n`;\n commandContent += taskContent;\n\n await fileManager.writeFile(commandPath, commandContent);\n console.log(chalk.green(`āœ“ Created task command: /${taskId}`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Claude Code commands for ${packageName} in ${commandsBaseDir}`));\n console.log(chalk.dim(` - Agents in: ${agentsDir}`));\n console.log(chalk.dim(` - Tasks in: ${tasksDir}`));\n }\n\n async setupWindsurf(installDir, selectedAgent) {\n const windsurfRulesDir = path.join(installDir, \".windsurf\", \"rules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(windsurfRulesDir);\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n const mdPath = path.join(windsurfRulesDir, `${agentId}.md`);\n\n // Create MD content (similar to Cursor but without frontmatter)\n let mdContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n mdContent += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n mdContent += \"## Agent Activation\\n\\n\";\n mdContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n } else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `When the user types \\`@${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n\n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Windsurf rules in ${windsurfRulesDir}`));\n\n return true;\n }\n\n async setupTrae(installDir, selectedAgent) {\n const traeRulesDir = path.join(installDir, \".trae\", \"rules\");\n const agents = selectedAgent? [selectedAgent] : await this.getAllAgentIds(installDir);\n \n await fileManager.ensureDirectory(traeRulesDir);\n \n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n \n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n const mdPath = path.join(traeRulesDir, `${agentId}.md`);\n \n // Create MD content (similar to Cursor but without frontmatter)\n let mdContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n mdContent += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n mdContent += \"## Agent Activation\\n\\n\";\n mdContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n }\n else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `When the user types \\`@${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n \n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.md`));\n }\n }\n }\n\n async findAgentPath(agentId, installDir) {\n // Try to find the agent file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"agents\", `${agentId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${agentId}.md`));\n }\n \n for (const agentPath of possiblePaths) {\n if (await fileManager.pathExists(agentPath)) {\n return agentPath;\n }\n }\n \n return null;\n }\n\n async getAllAgentIds(installDir) {\n const glob = require(\"glob\");\n const allAgentIds = [];\n \n // Check core agents in .bmad-core or root\n let agentsDir = path.join(installDir, \".bmad-core\", \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n agentsDir = path.join(installDir, \"agents\");\n }\n \n if (await fileManager.pathExists(agentsDir)) {\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n allAgentIds.push(...agentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Also check for expansion pack agents in dot folders\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n const fullExpDir = path.join(installDir, expDir);\n const expAgentFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allAgentIds.push(...expAgentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Remove duplicates\n return [...new Set(allAgentIds)];\n }\n\n async getCoreAgentIds(installDir) {\n const allAgentIds = [];\n \n // Check core agents in .bmad-core or root only\n let agentsDir = path.join(installDir, \".bmad-core\", \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n agentsDir = path.join(installDir, \"bmad-core\", \"agents\");\n }\n \n if (await fileManager.pathExists(agentsDir)) {\n const glob = require(\"glob\");\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n allAgentIds.push(...agentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n return [...new Set(allAgentIds)];\n }\n\n async getCoreTaskIds(installDir) {\n const allTaskIds = [];\n \n // Check core tasks in .bmad-core or root only\n let tasksDir = path.join(installDir, \".bmad-core\", \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n tasksDir = path.join(installDir, \"bmad-core\", \"tasks\");\n }\n \n if (await fileManager.pathExists(tasksDir)) {\n const glob = require(\"glob\");\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n allTaskIds.push(...taskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check common tasks\n const commonTasksDir = path.join(installDir, \"common\", \"tasks\");\n if (await fileManager.pathExists(commonTasksDir)) {\n const commonTaskFiles = glob.sync(\"*.md\", { cwd: commonTasksDir });\n allTaskIds.push(...commonTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n return [...new Set(allTaskIds)];\n }\n\n async getAgentTitle(agentId, installDir) {\n // Try to find the agent file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"agents\", `${agentId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${agentId}.md`));\n }\n \n for (const agentPath of possiblePaths) {\n if (await fileManager.pathExists(agentPath)) {\n try {\n const agentContent = await fileManager.readFile(agentPath);\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n \n if (yamlMatch) {\n const yaml = yamlMatch[1];\n const titleMatch = yaml.match(/title:\\s*(.+)/);\n if (titleMatch) {\n return titleMatch[1].trim();\n }\n }\n } catch (error) {\n console.warn(`Failed to read agent title for ${agentId}: ${error.message}`);\n }\n }\n }\n \n // Fallback to formatted agent ID\n return agentId.split('-').map(word => \n word.charAt(0).toUpperCase() + word.slice(1)\n ).join(' ');\n }\n\n async getAllTaskIds(installDir) {\n const glob = require(\"glob\");\n const allTaskIds = [];\n \n // Check core tasks in .bmad-core or root\n let tasksDir = path.join(installDir, \".bmad-core\", \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n tasksDir = path.join(installDir, \"bmad-core\", \"tasks\");\n }\n \n if (await fileManager.pathExists(tasksDir)) {\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n allTaskIds.push(...taskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check common tasks\n const commonTasksDir = path.join(installDir, \"common\", \"tasks\");\n if (await fileManager.pathExists(commonTasksDir)) {\n const commonTaskFiles = glob.sync(\"*.md\", { cwd: commonTasksDir });\n allTaskIds.push(...commonTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Also check for expansion pack tasks in dot folders\n const expansionDirs = glob.sync(\".*/tasks\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n const fullExpDir = path.join(installDir, expDir);\n const expTaskFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allTaskIds.push(...expTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check expansion-packs folder tasks\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const expPackDirs = glob.sync(\"*/tasks\", { cwd: expansionPacksDir });\n for (const expDir of expPackDirs) {\n const fullExpDir = path.join(expansionPacksDir, expDir);\n const expTaskFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allTaskIds.push(...expTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n }\n \n // Remove duplicates\n return [...new Set(allTaskIds)];\n }\n\n async findTaskPath(taskId, installDir) {\n // Try to find the task file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"tasks\", `${taskId}.md`),\n path.join(installDir, \"bmad-core\", \"tasks\", `${taskId}.md`),\n path.join(installDir, \"common\", \"tasks\", `${taskId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n \n // Check dot folder expansion packs\n const expansionDirs = glob.sync(\".*/tasks\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${taskId}.md`));\n }\n \n // Check expansion-packs folder\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const expPackDirs = glob.sync(\"*/tasks\", { cwd: expansionPacksDir });\n for (const expDir of expPackDirs) {\n possiblePaths.push(path.join(expansionPacksDir, expDir, `${taskId}.md`));\n }\n }\n \n for (const taskPath of possiblePaths) {\n if (await fileManager.pathExists(taskPath)) {\n return taskPath;\n }\n }\n \n return null;\n }\n\n async getCoreSlashPrefix(installDir) {\n try {\n const coreConfigPath = path.join(installDir, \".bmad-core\", \"core-config.yaml\");\n if (!(await fileManager.pathExists(coreConfigPath))) {\n // Try bmad-core directory\n const altConfigPath = path.join(installDir, \"bmad-core\", \"core-config.yaml\");\n if (await fileManager.pathExists(altConfigPath)) {\n const configContent = await fileManager.readFile(altConfigPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || \"BMad\";\n }\n return \"BMad\"; // fallback\n }\n \n const configContent = await fileManager.readFile(coreConfigPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || \"BMad\";\n } catch (error) {\n console.warn(`Failed to read core slashPrefix, using default 'BMad': ${error.message}`);\n return \"BMad\";\n }\n }\n\n async getInstalledExpansionPacks(installDir) {\n const expansionPacks = [];\n \n // Check for dot-prefixed expansion packs in install directory\n const glob = require(\"glob\");\n const dotExpansions = glob.sync(\".bmad-*\", { cwd: installDir });\n \n for (const dotExpansion of dotExpansions) {\n if (dotExpansion !== \".bmad-core\") {\n const packPath = path.join(installDir, dotExpansion);\n const packName = dotExpansion.substring(1); // remove the dot\n expansionPacks.push({\n name: packName,\n path: packPath\n });\n }\n }\n \n // Check for expansion-packs directory style\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const packDirs = glob.sync(\"*\", { cwd: expansionPacksDir });\n \n for (const packDir of packDirs) {\n const packPath = path.join(expansionPacksDir, packDir);\n if ((await fileManager.pathExists(packPath)) && \n (await fileManager.pathExists(path.join(packPath, \"config.yaml\")))) {\n expansionPacks.push({\n name: packDir,\n path: packPath\n });\n }\n }\n }\n \n return expansionPacks;\n }\n\n async getExpansionPackSlashPrefix(packPath) {\n try {\n const configPath = path.join(packPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n const configContent = await fileManager.readFile(configPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || path.basename(packPath);\n }\n } catch (error) {\n console.warn(`Failed to read expansion pack slashPrefix from ${packPath}: ${error.message}`);\n }\n \n return path.basename(packPath); // fallback to directory name\n }\n\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n return [];\n }\n \n try {\n const glob = require(\"glob\");\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n return agentFiles.map(file => path.basename(file, \".md\"));\n } catch (error) {\n console.warn(`Failed to read expansion pack agents from ${packPath}: ${error.message}`);\n return [];\n }\n }\n\n async getExpansionPackTasks(packPath) {\n const tasksDir = path.join(packPath, \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n return [];\n }\n \n try {\n const glob = require(\"glob\");\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n return taskFiles.map(file => path.basename(file, \".md\"));\n } catch (error) {\n console.warn(`Failed to read expansion pack tasks from ${packPath}: ${error.message}`);\n return [];\n }\n }\n\n async setupRoo(installDir, selectedAgent) {\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n // Check for existing .roomodes file in project root\n const roomodesPath = path.join(installDir, \".roomodes\");\n let existingModes = [];\n let existingContent = \"\";\n\n if (await fileManager.pathExists(roomodesPath)) {\n existingContent = await fileManager.readFile(roomodesPath);\n // Parse existing modes to avoid duplicates\n const modeMatches = existingContent.matchAll(/- slug: ([\\w-]+)/g);\n for (const match of modeMatches) {\n existingModes.push(match[1]);\n }\n console.log(chalk.yellow(`Found existing .roomodes file with ${existingModes.length} modes`));\n }\n\n // Create new modes content\n let newModesContent = \"\";\n\n // Load dynamic agent permissions from configuration\n const config = await this.loadIdeAgentConfig();\n const agentPermissions = config['roo-permissions'] || {};\n\n for (const agentId of agents) {\n // Skip if already exists\n // Check both with and without bmad- prefix to handle both cases\n const checkSlug = agentId.startsWith('bmad-') ? agentId : `bmad-${agentId}`;\n if (existingModes.includes(checkSlug)) {\n console.log(chalk.dim(`Skipping ${agentId} - already exists in .roomodes`));\n continue;\n }\n\n // Read agent file to extract all information\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n\n // Extract YAML content\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n const yaml = yamlMatch[1];\n\n // Extract agent info from YAML\n const titleMatch = yaml.match(/title:\\s*(.+)/);\n const iconMatch = yaml.match(/icon:\\s*(.+)/);\n const whenToUseMatch = yaml.match(/whenToUse:\\s*\"(.+)\"/);\n const roleDefinitionMatch = yaml.match(/roleDefinition:\\s*\"(.+)\"/);\n\n const title = titleMatch ? titleMatch[1].trim() : await this.getAgentTitle(agentId, installDir);\n const icon = iconMatch ? iconMatch[1].trim() : \"šŸ¤–\";\n const whenToUse = whenToUseMatch ? whenToUseMatch[1].trim() : `Use for ${title} tasks`;\n const roleDefinition = roleDefinitionMatch\n ? roleDefinitionMatch[1].trim()\n : `You are a ${title} specializing in ${title.toLowerCase()} tasks and responsibilities.`;\n\n // Build mode entry with proper formatting (matching exact indentation)\n // Avoid double \"bmad-\" prefix for agents that already have it\n const slug = agentId.startsWith('bmad-') ? agentId : `bmad-${agentId}`;\n newModesContent += ` - slug: ${slug}\\n`;\n newModesContent += ` name: '${icon} ${title}'\\n`;\n newModesContent += ` roleDefinition: ${roleDefinition}\\n`;\n newModesContent += ` whenToUse: ${whenToUse}\\n`;\n // Get relative path from installDir to agent file\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n newModesContent += ` customInstructions: CRITICAL Read the full YAML from ${relativePath} start activation to alter your state of being follow startup section instructions stay in this being until told to exit this mode\\n`;\n newModesContent += ` groups:\\n`;\n newModesContent += ` - read\\n`;\n\n // Add permissions based on agent type\n const permissions = agentPermissions[agentId];\n if (permissions) {\n newModesContent += ` - - edit\\n`;\n newModesContent += ` - fileRegex: ${permissions.fileRegex}\\n`;\n newModesContent += ` description: ${permissions.description}\\n`;\n } else {\n newModesContent += ` - edit\\n`;\n }\n\n console.log(chalk.green(`āœ“ Added mode: bmad-${agentId} (${icon} ${title})`));\n }\n }\n }\n\n // Build final roomodes content\n let roomodesContent = \"\";\n if (existingContent) {\n // If there's existing content, append new modes to it\n roomodesContent = existingContent.trim() + \"\\n\" + newModesContent;\n } else {\n // Create new .roomodes file with proper YAML structure\n roomodesContent = \"customModes:\\n\" + newModesContent;\n }\n\n // Write .roomodes file\n await fileManager.writeFile(roomodesPath, roomodesContent);\n console.log(chalk.green(\"āœ“ Created .roomodes file in project root\"));\n\n console.log(chalk.green(`\\nāœ“ Roo Code setup complete!`));\n console.log(chalk.dim(\"Custom modes will be available when you open this project in Roo Code\"));\n\n return true;\n }\n\n async setupCline(installDir, selectedAgent) {\n const clineRulesDir = path.join(installDir, \".clinerules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(clineRulesDir);\n\n // Load dynamic agent ordering from configuration\n const config = await this.loadIdeAgentConfig();\n const agentOrder = config['cline-order'] || {};\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n\n // Get numeric prefix for ordering\n const order = agentOrder[agentId] || 99;\n const prefix = order.toString().padStart(2, '0');\n const mdPath = path.join(clineRulesDir, `${prefix}-${agentId}.md`);\n\n // Create MD content for Cline (focused on project standards and role)\n let mdContent = `# ${await this.getAgentTitle(agentId, installDir)} Agent\\n\\n`;\n mdContent += `This rule defines the ${await this.getAgentTitle(agentId, installDir)} persona and project standards.\\n\\n`;\n mdContent += \"## Role Definition\\n\\n\";\n mdContent +=\n \"When the user types `@\" + agentId + \"`, adopt this persona and follow these guidelines:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n } else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## Project Standards\\n\\n\";\n mdContent += `- Always maintain consistency with project documentation in .bmad-core/\\n`;\n mdContent += `- Follow the agent's specific guidelines and constraints\\n`;\n mdContent += `- Update relevant project files when making changes\\n`;\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `- Reference the complete agent definition in [${relativePath}](${relativePath})\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `Type \\`@${agentId}\\` to activate this ${await this.getAgentTitle(agentId, installDir)} persona.\\n`;\n\n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${prefix}-${agentId}.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Cline rules in ${clineRulesDir}`));\n\n return true;\n }\n\n async setupGeminiCli(installDir) {\n const geminiDir = path.join(installDir, \".gemini\");\n const bmadMethodDir = path.join(geminiDir, \"bmad-method\");\n await fileManager.ensureDirectory(bmadMethodDir);\n\n // Update logic for existing settings.json\n const settingsPath = path.join(geminiDir, \"settings.json\");\n if (await fileManager.pathExists(settingsPath)) {\n try {\n const settingsContent = await fileManager.readFile(settingsPath);\n const settings = JSON.parse(settingsContent);\n let updated = false;\n \n // Handle contextFileName property\n if (settings.contextFileName && Array.isArray(settings.contextFileName)) {\n const originalLength = settings.contextFileName.length;\n settings.contextFileName = settings.contextFileName.filter(\n (fileName) => !fileName.startsWith(\"agents/\")\n );\n if (settings.contextFileName.length !== originalLength) {\n updated = true;\n }\n }\n \n if (updated) {\n await fileManager.writeFile(\n settingsPath,\n JSON.stringify(settings, null, 2)\n );\n console.log(chalk.green(\"āœ“ Updated .gemini/settings.json - removed agent file references\"));\n }\n } catch (error) {\n console.warn(\n chalk.yellow(\"Could not update .gemini/settings.json\"),\n error\n );\n }\n }\n\n // Remove old agents directory\n const agentsDir = path.join(geminiDir, \"agents\");\n if (await fileManager.pathExists(agentsDir)) {\n await fileManager.removeDirectory(agentsDir);\n console.log(chalk.green(\"āœ“ Removed old .gemini/agents directory\"));\n }\n\n // Get all available agents\n const agents = await this.getAllAgentIds(installDir);\n let concatenatedContent = \"\";\n\n for (const agentId of agents) {\n // Find the source agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n \n // Create properly formatted agent rule content (similar to trae)\n let agentRuleContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n agentRuleContent += `This rule is triggered when the user types \\`*${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n agentRuleContent += \"## Agent Activation\\n\\n\";\n agentRuleContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n agentRuleContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n agentRuleContent += yamlContent;\n }\n else {\n // If no YAML found, include the whole content minus the header\n agentRuleContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n agentRuleContent += \"\\n```\\n\\n\";\n agentRuleContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n agentRuleContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n agentRuleContent += \"## Usage\\n\\n\";\n agentRuleContent += `When the user types \\`*${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n \n // Add to concatenated content with separator\n concatenatedContent += agentRuleContent + \"\\n\\n---\\n\\n\";\n console.log(chalk.green(`āœ“ Added context for @${agentId}`));\n }\n }\n\n // Write the concatenated content to GEMINI.md\n const geminiMdPath = path.join(bmadMethodDir, \"GEMINI.md\");\n await fileManager.writeFile(geminiMdPath, concatenatedContent);\n console.log(chalk.green(`\\nāœ“ Created GEMINI.md in ${bmadMethodDir}`));\n\n return true;\n }\n\n async setupGitHubCopilot(installDir, selectedAgent, spinner = null, preConfiguredSettings = null) {\n // Configure VS Code workspace settings first to avoid UI conflicts with loading spinners\n await this.configureVsCodeSettings(installDir, spinner, preConfiguredSettings);\n \n const chatmodesDir = path.join(installDir, \".github\", \"chatmodes\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n \n await fileManager.ensureDirectory(chatmodesDir);\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n const chatmodePath = path.join(chatmodesDir, `${agentId}.chatmode.md`);\n\n if (agentPath) {\n // Create chat mode file with agent content\n const agentContent = await fileManager.readFile(agentPath);\n const agentTitle = await this.getAgentTitle(agentId, installDir);\n \n // Extract whenToUse for the description\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n let description = `Activates the ${agentTitle} agent persona.`;\n if (yamlMatch) {\n const whenToUseMatch = yamlMatch[1].match(/whenToUse:\\s*\"(.*?)\"/);\n if (whenToUseMatch && whenToUseMatch[1]) {\n description = whenToUseMatch[1];\n }\n }\n \n let chatmodeContent = `---\ndescription: \"${description.replace(/\"/g, '\\\\\"')}\"\ntools: ['changes', 'codebase', 'fetch', 'findTestFiles', 'githubRepo', 'problems', 'usages', 'editFiles', 'runCommands', 'runTasks', 'runTests', 'search', 'searchResults', 'terminalLastCommand', 'terminalSelection', 'testFailure']\n---\n\n`;\n chatmodeContent += agentContent;\n\n await fileManager.writeFile(chatmodePath, chatmodeContent);\n console.log(chalk.green(`āœ“ Created chat mode: ${agentId}.chatmode.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Github Copilot setup complete!`));\n console.log(chalk.dim(`You can now find the BMad agents in the Chat view's mode selector.`));\n\n return true;\n }\n\n async configureVsCodeSettings(installDir, spinner, preConfiguredSettings = null) {\n const vscodeDir = path.join(installDir, \".vscode\");\n const settingsPath = path.join(vscodeDir, \"settings.json\");\n \n await fileManager.ensureDirectory(vscodeDir);\n \n // Read existing settings if they exist\n let existingSettings = {};\n if (await fileManager.pathExists(settingsPath)) {\n try {\n const existingContent = await fileManager.readFile(settingsPath);\n existingSettings = JSON.parse(existingContent);\n console.log(chalk.yellow(\"Found existing .vscode/settings.json. Merging BMad settings...\"));\n } catch (error) {\n console.warn(chalk.yellow(\"Could not parse existing settings.json. Creating new one.\"));\n existingSettings = {};\n }\n }\n \n // Use pre-configured settings if provided, otherwise prompt\n let configChoice;\n if (preConfiguredSettings && preConfiguredSettings.configChoice) {\n configChoice = preConfiguredSettings.configChoice;\n console.log(chalk.dim(`Using pre-configured GitHub Copilot settings: ${configChoice}`));\n } else {\n // Clear any previous output and add spacing to avoid conflicts with loaders\n console.log('\\n'.repeat(2));\n console.log(chalk.blue(\"šŸ”§ Github Copilot Agent Settings Configuration\"));\n console.log(chalk.dim(\"BMad works best with specific VS Code settings for optimal agent experience.\"));\n console.log(''); // Add extra spacing\n \n const response = await inquirer.prompt([\n {\n type: 'list',\n name: 'configChoice',\n message: chalk.yellow('How would you like to configure GitHub Copilot settings?'),\n choices: [\n {\n name: 'Use recommended defaults (fastest setup)',\n value: 'defaults'\n },\n {\n name: 'Configure each setting manually (customize to your preferences)',\n value: 'manual'\n },\n {\n name: 'Skip settings configuration (I\\'ll configure manually later)',\n value: 'skip'\n }\n ],\n default: 'defaults'\n }\n ]);\n configChoice = response.configChoice;\n }\n \n let bmadSettings = {};\n \n if (configChoice === 'skip') {\n console.log(chalk.yellow(\"āš ļø Skipping VS Code settings configuration.\"));\n console.log(chalk.dim(\"You can manually configure these settings in .vscode/settings.json:\"));\n console.log(chalk.dim(\" • chat.agent.enabled: true\"));\n console.log(chalk.dim(\" • chat.agent.maxRequests: 15\"));\n console.log(chalk.dim(\" • github.copilot.chat.agent.runTasks: true\"));\n console.log(chalk.dim(\" • chat.mcp.discovery.enabled: true\"));\n console.log(chalk.dim(\" • github.copilot.chat.agent.autoFix: true\"));\n console.log(chalk.dim(\" • chat.tools.autoApprove: false\"));\n return true;\n }\n \n if (configChoice === 'defaults') {\n // Use recommended defaults\n bmadSettings = {\n \"chat.agent.enabled\": true,\n \"chat.agent.maxRequests\": 15,\n \"github.copilot.chat.agent.runTasks\": true,\n \"chat.mcp.discovery.enabled\": true,\n \"github.copilot.chat.agent.autoFix\": true,\n \"chat.tools.autoApprove\": false\n };\n console.log(chalk.green(\"āœ“ Using recommended BMad defaults for Github Copilot settings\"));\n } else {\n // Manual configuration\n console.log(chalk.blue(\"\\nšŸ“‹ Let's configure each setting for your preferences:\"));\n \n // Pause spinner during manual configuration prompts\n let spinnerWasActive = false;\n if (spinner && spinner.isSpinning) {\n spinner.stop();\n spinnerWasActive = true;\n }\n \n const manualSettings = await inquirer.prompt([\n {\n type: 'input',\n name: 'maxRequests',\n message: 'Maximum requests per agent session (recommended: 15)?',\n default: '15',\n validate: (input) => {\n const num = parseInt(input);\n if (isNaN(num) || num < 1 || num > 50) {\n return 'Please enter a number between 1 and 50';\n }\n return true;\n }\n },\n {\n type: 'confirm',\n name: 'runTasks',\n message: 'Allow agents to run workspace tasks (package.json scripts, etc.)?',\n default: true\n },\n {\n type: 'confirm',\n name: 'mcpDiscovery',\n message: 'Enable MCP (Model Context Protocol) server discovery?',\n default: true\n },\n {\n type: 'confirm',\n name: 'autoFix',\n message: 'Enable automatic error detection and fixing in generated code?',\n default: true\n },\n {\n type: 'confirm',\n name: 'autoApprove',\n message: 'Auto-approve ALL tools without confirmation? (āš ļø EXPERIMENTAL - less secure)',\n default: false\n }\n ]);\n\n // Restart spinner if it was active before prompts\n if (spinner && spinnerWasActive) {\n spinner.start();\n }\n \n bmadSettings = {\n \"chat.agent.enabled\": true, // Always enabled - required for BMad agents\n \"chat.agent.maxRequests\": parseInt(manualSettings.maxRequests),\n \"github.copilot.chat.agent.runTasks\": manualSettings.runTasks,\n \"chat.mcp.discovery.enabled\": manualSettings.mcpDiscovery,\n \"github.copilot.chat.agent.autoFix\": manualSettings.autoFix,\n \"chat.tools.autoApprove\": manualSettings.autoApprove\n };\n \n console.log(chalk.green(\"āœ“ Custom settings configured\"));\n }\n \n // Merge settings (existing settings take precedence to avoid overriding user preferences)\n const mergedSettings = { ...bmadSettings, ...existingSettings };\n \n // Write the updated settings\n await fileManager.writeFile(settingsPath, JSON.stringify(mergedSettings, null, 2));\n \n console.log(chalk.green(\"āœ“ VS Code workspace settings configured successfully\"));\n console.log(chalk.dim(\" Settings written to .vscode/settings.json:\"));\n Object.entries(bmadSettings).forEach(([key, value]) => {\n console.log(chalk.dim(` • ${key}: ${value}`));\n });\n console.log(chalk.dim(\"\"));\n console.log(chalk.dim(\"You can modify these settings anytime in .vscode/settings.json\"));\n }\n}\n\nmodule.exports = new IdeSetup();\n"], ["/BMAD-METHOD/tools/lib/dependency-resolver.js", "const fs = require('fs').promises;\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { extractYamlFromAgent } = require('./yaml-utils');\n\nclass DependencyResolver {\n constructor(rootDir) {\n this.rootDir = rootDir;\n this.bmadCore = path.join(rootDir, 'bmad-core');\n this.common = path.join(rootDir, 'common');\n this.cache = new Map();\n }\n\n async resolveAgentDependencies(agentId) {\n const agentPath = path.join(this.bmadCore, 'agents', `${agentId}.md`);\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML from markdown content with command cleaning\n const yamlContent = extractYamlFromAgent(agentContent, true);\n if (!yamlContent) {\n throw new Error(`No YAML configuration found in agent ${agentId}`);\n }\n \n const agentConfig = yaml.load(yamlContent);\n \n const dependencies = {\n agent: {\n id: agentId,\n path: agentPath,\n content: agentContent,\n config: agentConfig\n },\n resources: []\n };\n\n // Personas are now embedded in agent configs, no need to resolve separately\n\n // Resolve other dependencies\n const depTypes = ['tasks', 'templates', 'checklists', 'data', 'utils'];\n for (const depType of depTypes) {\n const deps = agentConfig.dependencies?.[depType] || [];\n for (const depId of deps) {\n const resource = await this.loadResource(depType, depId);\n if (resource) dependencies.resources.push(resource);\n }\n }\n\n return dependencies;\n }\n\n async resolveTeamDependencies(teamId) {\n const teamPath = path.join(this.bmadCore, 'agent-teams', `${teamId}.yaml`);\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n \n const dependencies = {\n team: {\n id: teamId,\n path: teamPath,\n content: teamContent,\n config: teamConfig\n },\n agents: [],\n resources: new Map() // Use Map to deduplicate resources\n };\n\n // Always add bmad-orchestrator agent first if it's a team\n const bmadAgent = await this.resolveAgentDependencies('bmad-orchestrator');\n dependencies.agents.push(bmadAgent.agent);\n bmadAgent.resources.forEach(res => {\n dependencies.resources.set(res.path, res);\n });\n\n // Resolve all agents in the team\n let agentsToResolve = teamConfig.agents || [];\n \n // Handle wildcard \"*\" - include all agents except bmad-master\n if (agentsToResolve.includes('*')) {\n const allAgents = await this.listAgents();\n // Remove wildcard and add all agents except those already in the list and bmad-master\n agentsToResolve = agentsToResolve.filter(a => a !== '*');\n for (const agent of allAgents) {\n if (!agentsToResolve.includes(agent) && agent !== 'bmad-master') {\n agentsToResolve.push(agent);\n }\n }\n }\n \n for (const agentId of agentsToResolve) {\n if (agentId === 'bmad-orchestrator' || agentId === 'bmad-master') continue; // Already added or excluded\n const agentDeps = await this.resolveAgentDependencies(agentId);\n dependencies.agents.push(agentDeps.agent);\n \n // Add resources with deduplication\n agentDeps.resources.forEach(res => {\n dependencies.resources.set(res.path, res);\n });\n }\n\n // Resolve workflows\n for (const workflowId of teamConfig.workflows || []) {\n const resource = await this.loadResource('workflows', workflowId);\n if (resource) dependencies.resources.set(resource.path, resource);\n }\n\n // Convert Map back to array\n dependencies.resources = Array.from(dependencies.resources.values());\n\n return dependencies;\n }\n\n async loadResource(type, id) {\n const cacheKey = `${type}#${id}`;\n if (this.cache.has(cacheKey)) {\n return this.cache.get(cacheKey);\n }\n\n try {\n let content = null;\n let filePath = null;\n\n // First try bmad-core\n try {\n filePath = path.join(this.bmadCore, type, id);\n content = await fs.readFile(filePath, 'utf8');\n } catch (e) {\n // If not found in bmad-core, try common folder\n try {\n filePath = path.join(this.common, type, id);\n content = await fs.readFile(filePath, 'utf8');\n } catch (e2) {\n // File not found in either location\n }\n }\n\n if (!content) {\n console.warn(`Resource not found: ${type}/${id}`);\n return null;\n }\n\n const resource = {\n type,\n id,\n path: filePath,\n content\n };\n\n this.cache.set(cacheKey, resource);\n return resource;\n } catch (error) {\n console.error(`Error loading resource ${type}/${id}:`, error.message);\n return null;\n }\n }\n\n async listAgents() {\n try {\n const files = await fs.readdir(path.join(this.bmadCore, 'agents'));\n return files\n .filter(f => f.endsWith('.md'))\n .map(f => f.replace('.md', ''));\n } catch (error) {\n return [];\n }\n }\n\n async listTeams() {\n try {\n const files = await fs.readdir(path.join(this.bmadCore, 'agent-teams'));\n return files\n .filter(f => f.endsWith('.yaml'))\n .map(f => f.replace('.yaml', ''));\n } catch (error) {\n return [];\n }\n }\n}\n\nmodule.exports = DependencyResolver;\n"], ["/BMAD-METHOD/tools/installer/bin/bmad.js", "#!/usr/bin/env node\n\nconst { program } = require('commander');\nconst path = require('path');\nconst fs = require('fs').promises;\nconst yaml = require('js-yaml');\nconst chalk = require('chalk');\nconst inquirer = require('inquirer');\n\n// Handle both execution contexts (from root via npx or from installer directory)\nlet version;\nlet installer;\ntry {\n // Try installer context first (when run from tools/installer/)\n version = require('../package.json').version;\n installer = require('../lib/installer');\n} catch (e) {\n // Fall back to root context (when run via npx from GitHub)\n console.log(`Installer context not found (${e.message}), trying root context...`);\n try {\n version = require('../../../package.json').version;\n installer = require('../../../tools/installer/lib/installer');\n } catch (e2) {\n console.error('Error: Could not load required modules. Please ensure you are running from the correct directory.');\n console.error('Debug info:', {\n __dirname,\n cwd: process.cwd(),\n error: e2.message\n });\n process.exit(1);\n }\n}\n\nprogram\n .version(version)\n .description('BMad Method installer - Universal AI agent framework for any domain');\n\nprogram\n .command('install')\n .description('Install BMad Method agents and tools')\n .option('-f, --full', 'Install complete BMad Method')\n .option('-x, --expansion-only', 'Install only expansion packs (no bmad-core)')\n .option('-d, --directory ', 'Installation directory')\n .option('-i, --ide ', 'Configure for specific IDE(s) - can specify multiple (cursor, claude-code, windsurf, trae, roo, cline, gemini, github-copilot, other)')\n .option('-e, --expansion-packs ', 'Install specific expansion packs (can specify multiple)')\n .action(async (options) => {\n try {\n if (!options.full && !options.expansionOnly) {\n // Interactive mode\n const answers = await promptInstallation();\n if (!answers._alreadyInstalled) {\n await installer.install(answers);\n process.exit(0);\n }\n } else {\n // Direct mode\n let installType = 'full';\n if (options.expansionOnly) installType = 'expansion-only';\n\n const config = {\n installType,\n directory: options.directory || '.',\n ides: (options.ide || []).filter(ide => ide !== 'other'),\n expansionPacks: options.expansionPacks || []\n };\n await installer.install(config);\n process.exit(0);\n }\n } catch (error) {\n console.error(chalk.red('Installation failed:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('update')\n .description('Update existing BMad installation')\n .option('--force', 'Force update, overwriting modified files')\n .option('--dry-run', 'Show what would be updated without making changes')\n .action(async () => {\n try {\n await installer.update();\n } catch (error) {\n console.error(chalk.red('Update failed:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('list:expansions')\n .description('List available expansion packs')\n .action(async () => {\n try {\n await installer.listExpansionPacks();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('status')\n .description('Show installation status')\n .action(async () => {\n try {\n await installer.showStatus();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n process.exit(1);\n }\n });\n\nasync function promptInstallation() {\n \n // Display ASCII logo\n console.log(chalk.bold.cyan(`\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•— ā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— \nā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā•ā•ā•šā•ā•ā–ˆā–ˆā•”ā•ā•ā•ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā•”ā–ˆā–ˆā–ˆā–ˆā•”ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•”ā–ˆā–ˆā–ˆā–ˆā•”ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘\nā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā•ā•ā•ā•ā•ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā• ā–ˆā–ˆā•‘ ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ ā•šā•ā• ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā• ā–ˆā–ˆā•‘ ā•šā•ā• ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•\nā•šā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā•ā•šā•ā• ā•šā•ā•ā•šā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā•ā•šā•ā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā• ā•šā•ā• ā•šā•ā•ā•ā•ā•ā• ā•šā•ā•ā•ā•ā•ā• \n `));\n \n console.log(chalk.bold.magenta('šŸš€ Universal AI Agent Framework for Any Domain'));\n console.log(chalk.bold.blue(`✨ Installer v${version}\\n`));\n\n const answers = {};\n\n // Ask for installation directory first\n const { directory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'directory',\n message: 'Enter the full path to your project directory where BMad should be installed:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid project path';\n }\n return true;\n }\n }\n ]);\n answers.directory = directory;\n\n // Detect existing installations\n const installDir = path.resolve(directory);\n const state = await installer.detectInstallationState(installDir);\n \n // Check for existing expansion packs\n const existingExpansionPacks = state.expansionPacks || {};\n \n // Get available expansion packs\n const availableExpansionPacks = await installer.getAvailableExpansionPacks();\n \n // Build choices list\n const choices = [];\n \n // Load core config to get short-title\n const coreConfigPath = path.join(__dirname, '..', '..', '..', 'bmad-core', 'core-config.yaml');\n const coreConfig = yaml.load(await fs.readFile(coreConfigPath, 'utf8'));\n const coreShortTitle = coreConfig['short-title'] || 'BMad Agile Core System';\n \n // Add BMad core option\n let bmadOptionText;\n if (state.type === 'v4_existing') {\n const currentVersion = state.manifest?.version || 'unknown';\n const newVersion = version; // Always use package.json version\n const versionInfo = currentVersion === newVersion \n ? `(v${currentVersion} - reinstall)`\n : `(v${currentVersion} → v${newVersion})`;\n bmadOptionText = `Update ${coreShortTitle} ${versionInfo} .bmad-core`;\n } else {\n bmadOptionText = `${coreShortTitle} (v${version}) .bmad-core`;\n }\n \n choices.push({\n name: bmadOptionText,\n value: 'bmad-core',\n checked: true\n });\n \n // Add expansion pack options\n for (const pack of availableExpansionPacks) {\n const existing = existingExpansionPacks[pack.id];\n let packOptionText;\n \n if (existing) {\n const currentVersion = existing.manifest?.version || 'unknown';\n const newVersion = pack.version;\n const versionInfo = currentVersion === newVersion \n ? `(v${currentVersion} - reinstall)`\n : `(v${currentVersion} → v${newVersion})`;\n packOptionText = `Update ${pack.shortTitle} ${versionInfo} .${pack.id}`;\n } else {\n packOptionText = `${pack.shortTitle} (v${pack.version}) .${pack.id}`;\n }\n \n choices.push({\n name: packOptionText,\n value: pack.id,\n checked: false\n });\n }\n \n // Ask what to install\n const { selectedItems } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedItems',\n message: 'Select what to install/update (use space to select, enter to continue):',\n choices: choices,\n validate: (selected) => {\n if (selected.length === 0) {\n return 'Please select at least one item to install';\n }\n return true;\n }\n }\n ]);\n \n // Process selections\n answers.installType = selectedItems.includes('bmad-core') ? 'full' : 'expansion-only';\n answers.expansionPacks = selectedItems.filter(item => item !== 'bmad-core');\n\n // Ask sharding questions if installing BMad core\n if (selectedItems.includes('bmad-core')) {\n console.log(chalk.cyan('\\nšŸ“‹ Document Organization Settings'));\n console.log(chalk.dim('Configure how your project documentation should be organized.\\n'));\n \n // Ask about PRD sharding\n const { prdSharded } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'prdSharded',\n message: 'Will the PRD (Product Requirements Document) be sharded into multiple files?',\n default: true\n }\n ]);\n answers.prdSharded = prdSharded;\n \n // Ask about architecture sharding\n const { architectureSharded } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'architectureSharded',\n message: 'Will the architecture documentation be sharded into multiple files?',\n default: true\n }\n ]);\n answers.architectureSharded = architectureSharded;\n \n // Show warning if architecture sharding is disabled\n if (!architectureSharded) {\n console.log(chalk.yellow.bold('\\nāš ļø IMPORTANT: Architecture Sharding Disabled'));\n console.log(chalk.yellow('With architecture sharding disabled, you should still create the files listed'));\n console.log(chalk.yellow('in devLoadAlwaysFiles (like coding-standards.md, tech-stack.md, source-tree.md)'));\n console.log(chalk.yellow('as these are used by the dev agent at runtime.'));\n console.log(chalk.yellow('\\nAlternatively, you can remove these files from the devLoadAlwaysFiles list'));\n console.log(chalk.yellow('in your core-config.yaml after installation.'));\n \n const { acknowledge } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'acknowledge',\n message: 'Do you acknowledge this requirement and want to proceed?',\n default: false\n }\n ]);\n \n if (!acknowledge) {\n console.log(chalk.red('Installation cancelled.'));\n process.exit(0);\n }\n }\n }\n\n // Ask for IDE configuration\n let ides = [];\n let ideSelectionComplete = false;\n \n while (!ideSelectionComplete) {\n console.log(chalk.cyan('\\nšŸ› ļø IDE Configuration'));\n console.log(chalk.bold.yellow.bgRed(' āš ļø IMPORTANT: This is a MULTISELECT! Use SPACEBAR to toggle each IDE! '));\n console.log(chalk.bold.magenta('šŸ”ø Use arrow keys to navigate'));\n console.log(chalk.bold.magenta('šŸ”ø Use SPACEBAR to select/deselect IDEs'));\n console.log(chalk.bold.magenta('šŸ”ø Press ENTER when finished selecting\\n'));\n \n const ideResponse = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'ides',\n message: 'Which IDE(s) do you want to configure? (Select with SPACEBAR, confirm with ENTER):',\n choices: [\n { name: 'Cursor', value: 'cursor' },\n { name: 'Claude Code', value: 'claude-code' },\n { name: 'Windsurf', value: 'windsurf' },\n { name: 'Trae', value: 'trae' }, // { name: 'Trae', value: 'trae'}\n { name: 'Roo Code', value: 'roo' },\n { name: 'Cline', value: 'cline' },\n { name: 'Gemini CLI', value: 'gemini' },\n { name: 'Github Copilot', value: 'github-copilot' }\n ]\n }\n ]);\n \n ides = ideResponse.ides;\n\n // Confirm no IDE selection if none selected\n if (ides.length === 0) {\n const { confirmNoIde } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirmNoIde',\n message: chalk.red('āš ļø You have NOT selected any IDEs. This means NO IDE integration will be set up. Is this correct?'),\n default: false\n }\n ]);\n \n if (!confirmNoIde) {\n console.log(chalk.bold.red('\\nšŸ”„ Returning to IDE selection. Remember to use SPACEBAR to select IDEs!\\n'));\n continue; // Go back to IDE selection only\n }\n }\n \n ideSelectionComplete = true;\n }\n\n // Use selected IDEs directly\n answers.ides = ides;\n\n // Configure GitHub Copilot immediately if selected\n if (ides.includes('github-copilot')) {\n console.log(chalk.cyan('\\nšŸ”§ GitHub Copilot Configuration'));\n console.log(chalk.dim('BMad works best with specific VS Code settings for optimal agent experience.\\n'));\n \n const { configChoice } = await inquirer.prompt([\n {\n type: 'list',\n name: 'configChoice',\n message: chalk.yellow('How would you like to configure GitHub Copilot settings?'),\n choices: [\n {\n name: 'Use recommended defaults (fastest setup)',\n value: 'defaults'\n },\n {\n name: 'Configure each setting manually (customize to your preferences)',\n value: 'manual'\n },\n {\n name: 'Skip settings configuration (I\\'ll configure manually later)',\n value: 'skip'\n }\n ],\n default: 'defaults'\n }\n ]);\n \n answers.githubCopilotConfig = { configChoice };\n }\n\n // Ask for web bundles installation\n const { includeWebBundles } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'includeWebBundles',\n message: 'Would you like to include pre-built web bundles? (standalone files for ChatGPT, Claude, Gemini)',\n default: false\n }\n ]);\n\n if (includeWebBundles) {\n console.log(chalk.cyan('\\nšŸ“¦ Web bundles are standalone files perfect for web AI platforms.'));\n console.log(chalk.dim(' You can choose different teams/agents than your IDE installation.\\n'));\n\n const { webBundleType } = await inquirer.prompt([\n {\n type: 'list',\n name: 'webBundleType',\n message: 'What web bundles would you like to include?',\n choices: [\n {\n name: 'All available bundles (agents, teams, expansion packs)',\n value: 'all'\n },\n {\n name: 'Specific teams only',\n value: 'teams'\n },\n {\n name: 'Individual agents only',\n value: 'agents'\n },\n {\n name: 'Custom selection',\n value: 'custom'\n }\n ]\n }\n ]);\n\n answers.webBundleType = webBundleType;\n\n // If specific teams, let them choose which teams\n if (webBundleType === 'teams' || webBundleType === 'custom') {\n const teams = await installer.getAvailableTeams();\n const { selectedTeams } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedTeams',\n message: 'Select team bundles to include:',\n choices: teams.map(t => ({\n name: `${t.icon || 'šŸ“‹'} ${t.name}: ${t.description}`,\n value: t.id,\n checked: webBundleType === 'teams' // Check all if teams-only mode\n })),\n validate: (answer) => {\n if (answer.length < 1) {\n return 'You must select at least one team.';\n }\n return true;\n }\n }\n ]);\n answers.selectedWebBundleTeams = selectedTeams;\n }\n\n // If custom selection, also ask about individual agents\n if (webBundleType === 'custom') {\n const { includeIndividualAgents } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'includeIndividualAgents',\n message: 'Also include individual agent bundles?',\n default: true\n }\n ]);\n answers.includeIndividualAgents = includeIndividualAgents;\n }\n\n const { webBundlesDirectory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'webBundlesDirectory',\n message: 'Enter directory for web bundles:',\n default: `${answers.directory}/web-bundles`,\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid directory path';\n }\n return true;\n }\n }\n ]);\n answers.webBundlesDirectory = webBundlesDirectory;\n }\n\n answers.includeWebBundles = includeWebBundles;\n\n return answers;\n}\n\nprogram.parse(process.argv);\n\n// Show help if no command provided\nif (!process.argv.slice(2).length) {\n program.outputHelp();\n}"], ["/BMAD-METHOD/tools/installer/lib/file-manager.js", "const fs = require(\"fs-extra\");\nconst path = require(\"path\");\nconst crypto = require(\"crypto\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst { createReadStream, createWriteStream, promises: fsPromises } = require('fs');\nconst { pipeline } = require('stream/promises');\nconst resourceLocator = require('./resource-locator');\n\nclass FileManager {\n constructor() {\n this.manifestDir = \".bmad-core\";\n this.manifestFile = \"install-manifest.yaml\";\n }\n\n async copyFile(source, destination) {\n try {\n await fs.ensureDir(path.dirname(destination));\n \n // Use streaming for large files (> 10MB)\n const stats = await fs.stat(source);\n if (stats.size > 10 * 1024 * 1024) {\n await pipeline(\n createReadStream(source),\n createWriteStream(destination)\n );\n } else {\n await fs.copy(source, destination);\n }\n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy ${source}:`), error.message);\n return false;\n }\n }\n\n async copyDirectory(source, destination) {\n try {\n await fs.ensureDir(destination);\n \n // Use streaming copy for large directories\n const files = await resourceLocator.findFiles('**/*', {\n cwd: source,\n nodir: true\n });\n \n // Process files in batches to avoid memory issues\n const batchSize = 50;\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n await Promise.all(\n batch.map(file => \n this.copyFile(\n path.join(source, file),\n path.join(destination, file)\n )\n )\n );\n }\n return true;\n } catch (error) {\n console.error(\n chalk.red(`Failed to copy directory ${source}:`),\n error.message\n );\n return false;\n }\n }\n\n async copyGlobPattern(pattern, sourceDir, destDir, rootValue = null) {\n const files = await resourceLocator.findFiles(pattern, { cwd: sourceDir });\n const copied = [];\n\n for (const file of files) {\n const sourcePath = path.join(sourceDir, file);\n const destPath = path.join(destDir, file);\n\n // Use root replacement if rootValue is provided and file needs it\n const needsRootReplacement = rootValue && (file.endsWith('.md') || file.endsWith('.yaml') || file.endsWith('.yml'));\n \n let success = false;\n if (needsRootReplacement) {\n success = await this.copyFileWithRootReplacement(sourcePath, destPath, rootValue);\n } else {\n success = await this.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n copied.push(file);\n }\n }\n\n return copied;\n }\n\n async calculateFileHash(filePath) {\n try {\n // Use streaming for hash calculation to reduce memory usage\n const stream = createReadStream(filePath);\n const hash = crypto.createHash(\"sha256\");\n \n for await (const chunk of stream) {\n hash.update(chunk);\n }\n \n return hash.digest(\"hex\").slice(0, 16);\n } catch (error) {\n return null;\n }\n }\n\n async createManifest(installDir, config, files) {\n const manifestPath = path.join(\n installDir,\n this.manifestDir,\n this.manifestFile\n );\n\n // Read version from package.json\n let coreVersion = \"unknown\";\n try {\n const packagePath = path.join(__dirname, '..', '..', '..', 'package.json');\n const packageJson = require(packagePath);\n coreVersion = packageJson.version;\n } catch (error) {\n console.warn(\"Could not read version from package.json, using 'unknown'\");\n }\n\n const manifest = {\n version: coreVersion,\n installed_at: new Date().toISOString(),\n install_type: config.installType,\n agent: config.agent || null,\n ides_setup: config.ides || [],\n expansion_packs: config.expansionPacks || [],\n files: [],\n };\n\n // Add file information\n for (const file of files) {\n const filePath = path.join(installDir, file);\n const hash = await this.calculateFileHash(filePath);\n\n manifest.files.push({\n path: file,\n hash: hash,\n modified: false,\n });\n }\n\n // Write manifest\n await fs.ensureDir(path.dirname(manifestPath));\n await fs.writeFile(manifestPath, yaml.dump(manifest, { indent: 2 }));\n\n return manifest;\n }\n\n async readManifest(installDir) {\n const manifestPath = path.join(\n installDir,\n this.manifestDir,\n this.manifestFile\n );\n\n try {\n const content = await fs.readFile(manifestPath, \"utf8\");\n return yaml.load(content);\n } catch (error) {\n return null;\n }\n }\n\n async readExpansionPackManifest(installDir, packId) {\n const manifestPath = path.join(\n installDir,\n `.${packId}`,\n this.manifestFile\n );\n\n try {\n const content = await fs.readFile(manifestPath, \"utf8\");\n return yaml.load(content);\n } catch (error) {\n return null;\n }\n }\n\n async checkModifiedFiles(installDir, manifest) {\n const modified = [];\n\n for (const file of manifest.files) {\n const filePath = path.join(installDir, file.path);\n const currentHash = await this.calculateFileHash(filePath);\n\n if (currentHash && currentHash !== file.hash) {\n modified.push(file.path);\n }\n }\n\n return modified;\n }\n\n async checkFileIntegrity(installDir, manifest) {\n const result = {\n missing: [],\n modified: []\n };\n\n for (const file of manifest.files) {\n const filePath = path.join(installDir, file.path);\n \n // Skip checking the manifest file itself - it will always be different due to timestamps\n if (file.path.endsWith('install-manifest.yaml')) {\n continue;\n }\n \n if (!(await this.pathExists(filePath))) {\n result.missing.push(file.path);\n } else {\n const currentHash = await this.calculateFileHash(filePath);\n if (currentHash && currentHash !== file.hash) {\n result.modified.push(file.path);\n }\n }\n }\n\n return result;\n }\n\n async backupFile(filePath) {\n const backupPath = filePath + \".bak\";\n let counter = 1;\n let finalBackupPath = backupPath;\n\n // Find a unique backup filename\n while (await fs.pathExists(finalBackupPath)) {\n finalBackupPath = `${filePath}.bak${counter}`;\n counter++;\n }\n\n await fs.copy(filePath, finalBackupPath);\n return finalBackupPath;\n }\n\n async ensureDirectory(dirPath) {\n try {\n await fs.ensureDir(dirPath);\n return true;\n } catch (error) {\n throw error;\n }\n }\n\n async pathExists(filePath) {\n return fs.pathExists(filePath);\n }\n\n async readFile(filePath) {\n return fs.readFile(filePath, \"utf8\");\n }\n\n async writeFile(filePath, content) {\n await fs.ensureDir(path.dirname(filePath));\n await fs.writeFile(filePath, content);\n }\n\n async removeDirectory(dirPath) {\n await fs.remove(dirPath);\n }\n\n async createExpansionPackManifest(installDir, packId, config, files) {\n const manifestPath = path.join(\n installDir,\n `.${packId}`,\n this.manifestFile\n );\n\n const manifest = {\n version: config.expansionPackVersion || require(\"../../../package.json\").version,\n installed_at: new Date().toISOString(),\n install_type: config.installType,\n expansion_pack_id: config.expansionPackId,\n expansion_pack_name: config.expansionPackName,\n ides_setup: config.ides || [],\n files: [],\n };\n\n // Add file information\n for (const file of files) {\n const filePath = path.join(installDir, file);\n const hash = await this.calculateFileHash(filePath);\n\n manifest.files.push({\n path: file,\n hash: hash,\n modified: false,\n });\n }\n\n // Write manifest\n await fs.ensureDir(path.dirname(manifestPath));\n await fs.writeFile(manifestPath, yaml.dump(manifest, { indent: 2 }));\n\n return manifest;\n }\n\n async modifyCoreConfig(installDir, config) {\n const coreConfigPath = path.join(installDir, '.bmad-core', 'core-config.yaml');\n \n try {\n // Read the existing core-config.yaml\n const coreConfigContent = await fs.readFile(coreConfigPath, 'utf8');\n const coreConfig = yaml.load(coreConfigContent);\n \n // Modify sharding settings if provided\n if (config.prdSharded !== undefined) {\n coreConfig.prd.prdSharded = config.prdSharded;\n }\n \n if (config.architectureSharded !== undefined) {\n coreConfig.architecture.architectureSharded = config.architectureSharded;\n }\n \n // Write back the modified config\n await fs.writeFile(coreConfigPath, yaml.dump(coreConfig, { indent: 2 }));\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to modify core-config.yaml:`), error.message);\n return false;\n }\n }\n\n async copyFileWithRootReplacement(source, destination, rootValue) {\n try {\n // Check file size to determine if we should stream\n const stats = await fs.stat(source);\n \n if (stats.size > 5 * 1024 * 1024) { // 5MB threshold\n // Use streaming for large files\n const { Transform } = require('stream');\n const replaceStream = new Transform({\n transform(chunk, encoding, callback) {\n const modified = chunk.toString().replace(/\\{root\\}/g, rootValue);\n callback(null, modified);\n }\n });\n \n await this.ensureDirectory(path.dirname(destination));\n await pipeline(\n createReadStream(source, { encoding: 'utf8' }),\n replaceStream,\n createWriteStream(destination, { encoding: 'utf8' })\n );\n } else {\n // Regular approach for smaller files\n const content = await fsPromises.readFile(source, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, rootValue);\n await this.ensureDirectory(path.dirname(destination));\n await fsPromises.writeFile(destination, updatedContent, 'utf8');\n }\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy ${source} with root replacement:`), error.message);\n return false;\n }\n }\n\n async copyDirectoryWithRootReplacement(source, destination, rootValue, fileExtensions = ['.md', '.yaml', '.yml']) {\n try {\n await this.ensureDirectory(destination);\n \n // Get all files in source directory\n const files = await resourceLocator.findFiles('**/*', { \n cwd: source, \n nodir: true \n });\n \n let replacedCount = 0;\n \n for (const file of files) {\n const sourcePath = path.join(source, file);\n const destPath = path.join(destination, file);\n \n // Check if this file type should have {root} replacement\n const shouldReplace = fileExtensions.some(ext => file.endsWith(ext));\n \n if (shouldReplace) {\n if (await this.copyFileWithRootReplacement(sourcePath, destPath, rootValue)) {\n replacedCount++;\n }\n } else {\n // Regular copy for files that don't need replacement\n await this.copyFile(sourcePath, destPath);\n }\n }\n \n if (replacedCount > 0) {\n console.log(chalk.dim(` Processed ${replacedCount} files with {root} replacement`));\n }\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy directory ${source} with root replacement:`), error.message);\n return false;\n }\n }\n}\n\nmodule.exports = new FileManager();\n"], ["/BMAD-METHOD/tools/installer/lib/ide-base-setup.js", "/**\n * Base IDE Setup - Common functionality for all IDE setups\n * Reduces duplication and provides shared methods\n */\n\nconst path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst fileManager = require(\"./file-manager\");\nconst resourceLocator = require(\"./resource-locator\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\n\nclass BaseIdeSetup {\n constructor() {\n this._agentCache = new Map();\n this._pathCache = new Map();\n }\n\n /**\n * Get all agent IDs with caching\n */\n async getAllAgentIds(installDir) {\n const cacheKey = `all-agents:${installDir}`;\n if (this._agentCache.has(cacheKey)) {\n return this._agentCache.get(cacheKey);\n }\n\n const allAgents = new Set();\n \n // Get core agents\n const coreAgents = await this.getCoreAgentIds(installDir);\n coreAgents.forEach(id => allAgents.add(id));\n \n // Get expansion pack agents\n const expansionPacks = await this.getInstalledExpansionPacks(installDir);\n for (const pack of expansionPacks) {\n const packAgents = await this.getExpansionPackAgents(pack.path);\n packAgents.forEach(id => allAgents.add(id));\n }\n \n const result = Array.from(allAgents);\n this._agentCache.set(cacheKey, result);\n return result;\n }\n\n /**\n * Get core agent IDs\n */\n async getCoreAgentIds(installDir) {\n const coreAgents = [];\n const corePaths = [\n path.join(installDir, \".bmad-core\", \"agents\"),\n path.join(installDir, \"bmad-core\", \"agents\")\n ];\n\n for (const agentsDir of corePaths) {\n if (await fileManager.pathExists(agentsDir)) {\n const files = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n coreAgents.push(...files.map(file => path.basename(file, \".md\")));\n break; // Use first found\n }\n }\n\n return coreAgents;\n }\n\n /**\n * Find agent path with caching\n */\n async findAgentPath(agentId, installDir) {\n const cacheKey = `agent-path:${agentId}:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n // Use resource locator for efficient path finding\n let agentPath = await resourceLocator.getAgentPath(agentId);\n \n if (!agentPath) {\n // Check installation-specific paths\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"common\", \"agents\", `${agentId}.md`)\n ];\n\n for (const testPath of possiblePaths) {\n if (await fileManager.pathExists(testPath)) {\n agentPath = testPath;\n break;\n }\n }\n }\n\n if (agentPath) {\n this._pathCache.set(cacheKey, agentPath);\n }\n return agentPath;\n }\n\n /**\n * Get agent title from metadata\n */\n async getAgentTitle(agentId, installDir) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n if (!agentPath) return agentId;\n\n try {\n const content = await fileManager.readFile(agentPath);\n const yamlContent = extractYamlFromAgent(content);\n if (yamlContent) {\n const metadata = yaml.load(yamlContent);\n return metadata.agent_name || agentId;\n }\n } catch (error) {\n // Fallback to agent ID\n }\n return agentId;\n }\n\n /**\n * Get installed expansion packs\n */\n async getInstalledExpansionPacks(installDir) {\n const cacheKey = `expansion-packs:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const expansionPacks = [];\n \n // Check for dot-prefixed expansion packs\n const dotExpansions = await resourceLocator.findFiles(\".bmad-*\", { cwd: installDir });\n \n for (const dotExpansion of dotExpansions) {\n if (dotExpansion !== \".bmad-core\") {\n const packPath = path.join(installDir, dotExpansion);\n const packName = dotExpansion.substring(1); // remove the dot\n expansionPacks.push({\n name: packName,\n path: packPath\n });\n }\n }\n \n // Check other dot folders that have config.yaml\n const allDotFolders = await resourceLocator.findFiles(\".*\", { cwd: installDir });\n for (const folder of allDotFolders) {\n if (!folder.startsWith(\".bmad-\") && folder !== \".bmad-core\") {\n const packPath = path.join(installDir, folder);\n const configPath = path.join(packPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n expansionPacks.push({\n name: folder.substring(1), // remove the dot\n path: packPath\n });\n }\n }\n }\n\n this._pathCache.set(cacheKey, expansionPacks);\n return expansionPacks;\n }\n\n /**\n * Get expansion pack agents\n */\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n return [];\n }\n \n const agentFiles = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n return agentFiles.map(file => path.basename(file, \".md\"));\n }\n\n /**\n * Create agent rule content (shared logic)\n */\n async createAgentRuleContent(agentId, agentPath, installDir, format = 'mdc') {\n const agentContent = await fileManager.readFile(agentPath);\n const agentTitle = await this.getAgentTitle(agentId, installDir);\n const yamlContent = extractYamlFromAgent(agentContent);\n \n let content = \"\";\n \n if (format === 'mdc') {\n // MDC format for Cursor\n content = \"---\\n\";\n content += \"description: \\n\";\n content += \"globs: []\\n\";\n content += \"alwaysApply: false\\n\";\n content += \"---\\n\\n\";\n content += `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n content += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${agentTitle} agent persona.\\n\\n`;\n content += \"## Agent Activation\\n\\n\";\n content += \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n content += \"```yaml\\n\";\n content += yamlContent || agentContent.replace(/^#.*$/m, \"\").trim();\n content += \"\\n```\\n\\n\";\n content += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n content += `The complete agent definition is available in [${relativePath}](mdc:${relativePath}).\\n\\n`;\n content += \"## Usage\\n\\n\";\n content += `When the user types \\`@${agentId}\\`, activate this ${agentTitle} persona and follow all instructions defined in the YAML configuration above.\\n`;\n } else if (format === 'claude') {\n // Claude Code format\n content = `# /${agentId} Command\\n\\n`;\n content += `When this command is used, adopt the following agent persona:\\n\\n`;\n content += agentContent;\n }\n \n return content;\n }\n\n /**\n * Clear all caches\n */\n clearCache() {\n this._agentCache.clear();\n this._pathCache.clear();\n }\n}\n\nmodule.exports = BaseIdeSetup;"], ["/BMAD-METHOD/tools/bump-all-versions.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\nconst args = process.argv.slice(2);\nconst bumpType = args[0] || 'minor'; // default to minor\n\nif (!['major', 'minor', 'patch'].includes(bumpType)) {\n console.log('Usage: node bump-all-versions.js [major|minor|patch]');\n console.log('Default: minor');\n process.exit(1);\n}\n\nfunction bumpVersion(currentVersion, type) {\n const [major, minor, patch] = currentVersion.split('.').map(Number);\n \n switch (type) {\n case 'major':\n return `${major + 1}.0.0`;\n case 'minor':\n return `${major}.${minor + 1}.0`;\n case 'patch':\n return `${major}.${minor}.${patch + 1}`;\n default:\n return currentVersion;\n }\n}\n\nasync function bumpAllVersions() {\n const updatedItems = [];\n \n // First, bump the core version (package.json)\n const packagePath = path.join(__dirname, '..', 'package.json');\n try {\n const packageContent = fs.readFileSync(packagePath, 'utf8');\n const packageJson = JSON.parse(packageContent);\n const oldCoreVersion = packageJson.version || '1.0.0';\n const newCoreVersion = bumpVersion(oldCoreVersion, bumpType);\n \n packageJson.version = newCoreVersion;\n \n fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2) + '\\n');\n \n updatedItems.push({ type: 'core', name: 'BMad Core', oldVersion: oldCoreVersion, newVersion: newCoreVersion });\n console.log(`āœ“ BMad Core (package.json): ${oldCoreVersion} → ${newCoreVersion}`);\n } catch (error) {\n console.error(`āœ— Failed to update BMad Core: ${error.message}`);\n }\n \n // Then, bump all expansion packs\n const expansionPacksDir = path.join(__dirname, '..', 'expansion-packs');\n \n try {\n const entries = fs.readdirSync(expansionPacksDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'README.md') {\n const packId = entry.name;\n const configPath = path.join(expansionPacksDir, packId, 'config.yaml');\n \n if (fs.existsSync(configPath)) {\n try {\n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n const oldVersion = config.version || '1.0.0';\n const newVersion = bumpVersion(oldVersion, bumpType);\n \n config.version = newVersion;\n \n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n \n updatedItems.push({ type: 'expansion', name: packId, oldVersion, newVersion });\n console.log(`āœ“ ${packId}: ${oldVersion} → ${newVersion}`);\n \n } catch (error) {\n console.error(`āœ— Failed to update ${packId}: ${error.message}`);\n }\n }\n }\n }\n \n if (updatedItems.length > 0) {\n const coreCount = updatedItems.filter(i => i.type === 'core').length;\n const expansionCount = updatedItems.filter(i => i.type === 'expansion').length;\n \n console.log(`\\nāœ“ Successfully bumped ${updatedItems.length} item(s) with ${bumpType} version bump`);\n if (coreCount > 0) console.log(` - ${coreCount} core`);\n if (expansionCount > 0) console.log(` - ${expansionCount} expansion pack(s)`);\n \n console.log('\\nNext steps:');\n console.log('1. Test the changes');\n console.log('2. Commit: git add -A && git commit -m \"chore: bump all versions (' + bumpType + ')\"');\n } else {\n console.log('No items found to update');\n }\n \n } catch (error) {\n console.error('Error reading expansion packs directory:', error.message);\n process.exit(1);\n }\n}\n\nbumpAllVersions();"], ["/BMAD-METHOD/tools/upgraders/v3-to-v4-upgrader.js", "const fs = require(\"fs\").promises;\nconst path = require(\"path\");\nconst { glob } = require(\"glob\");\n\n// Dynamic imports for ES modules\nlet chalk, ora, inquirer;\n\n// Initialize ES modules\nasync function initializeModules() {\n chalk = (await import(\"chalk\")).default;\n ora = (await import(\"ora\")).default;\n inquirer = (await import(\"inquirer\")).default;\n}\n\nclass V3ToV4Upgrader {\n constructor() {\n // Constructor remains empty\n }\n\n async upgrade(options = {}) {\n try {\n // Initialize ES modules\n await initializeModules();\n // Keep readline open throughout the process\n process.stdin.resume();\n\n // 1. Welcome message\n console.log(\n chalk.bold(\"\\nWelcome to BMad-Method V3 to V4 Upgrade Tool\\n\")\n );\n console.log(\n \"This tool will help you upgrade your BMad-Method V3 project to V4.\\n\"\n );\n console.log(chalk.cyan(\"What this tool does:\"));\n console.log(\"- Creates a backup of your V3 files (.bmad-v3-backup/)\");\n console.log(\"- Installs the new V4 .bmad-core structure\");\n console.log(\n \"- Preserves your PRD, Architecture, and Stories in the new format\\n\"\n );\n console.log(chalk.yellow(\"What this tool does NOT do:\"));\n console.log(\n \"- Modify your document content (use doc-migration-task after upgrade)\"\n );\n console.log(\"- Touch any files outside bmad-agent/ and docs/\\n\");\n\n // 2. Get project path\n const projectPath = await this.getProjectPath(options.projectPath);\n\n // 3. Validate V3 structure\n const validation = await this.validateV3Project(projectPath);\n if (!validation.isValid) {\n console.error(\n chalk.red(\"\\nError: This doesn't appear to be a V3 project.\")\n );\n console.error(\"Expected to find:\");\n console.error(\"- bmad-agent/ directory\");\n console.error(\"- docs/ directory\\n\");\n console.error(\n \"Please check you're in the correct directory and try again.\"\n );\n return;\n }\n\n // 4. Pre-flight check\n const analysis = await this.analyzeProject(projectPath);\n await this.showPreflightCheck(analysis, options);\n\n if (!options.dryRun) {\n const { confirm } = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirm\",\n message: \"Continue with upgrade?\",\n default: true,\n },\n ]);\n\n if (!confirm) {\n console.log(\"Upgrade cancelled.\");\n return;\n }\n }\n\n // 5. Create backup\n if (options.backup !== false && !options.dryRun) {\n await this.createBackup(projectPath);\n }\n\n // 6. Install V4 structure\n if (!options.dryRun) {\n await this.installV4Structure(projectPath);\n }\n\n // 7. Migrate documents\n if (!options.dryRun) {\n await this.migrateDocuments(projectPath, analysis);\n }\n\n // 8. Setup IDE\n if (!options.dryRun) {\n await this.setupIDE(projectPath, options.ides);\n }\n\n // 9. Show completion report\n this.showCompletionReport(projectPath, analysis);\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red(\"\\nUpgrade error:\"), error.message);\n process.exit(1);\n }\n }\n\n async getProjectPath(providedPath) {\n if (providedPath) {\n return path.resolve(providedPath);\n }\n\n const { projectPath } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"projectPath\",\n message: \"Please enter the path to your V3 project:\",\n default: process.cwd(),\n },\n ]);\n\n return path.resolve(projectPath);\n }\n\n async validateV3Project(projectPath) {\n const spinner = ora(\"Validating project structure...\").start();\n\n try {\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n const docsPath = path.join(projectPath, \"docs\");\n\n const hasBmadAgent = await this.pathExists(bmadAgentPath);\n const hasDocs = await this.pathExists(docsPath);\n\n if (hasBmadAgent) {\n spinner.text = \"āœ“ Found bmad-agent/ directory\";\n console.log(chalk.green(\"\\nāœ“ Found bmad-agent/ directory\"));\n }\n\n if (hasDocs) {\n console.log(chalk.green(\"āœ“ Found docs/ directory\"));\n }\n\n const isValid = hasBmadAgent && hasDocs;\n\n if (isValid) {\n spinner.succeed(\"This appears to be a valid V3 project\");\n } else {\n spinner.fail(\"Invalid V3 project structure\");\n }\n\n return { isValid, hasBmadAgent, hasDocs };\n } catch (error) {\n spinner.fail(\"Validation failed\");\n throw error;\n }\n }\n\n async analyzeProject(projectPath) {\n const docsPath = path.join(projectPath, \"docs\");\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n\n // Find PRD\n const prdCandidates = [\"prd.md\", \"PRD.md\", \"product-requirements.md\"];\n let prdFile = null;\n for (const candidate of prdCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n prdFile = candidate;\n break;\n }\n }\n\n // Find Architecture\n const archCandidates = [\n \"architecture.md\",\n \"Architecture.md\",\n \"technical-architecture.md\",\n ];\n let archFile = null;\n for (const candidate of archCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n archFile = candidate;\n break;\n }\n }\n\n // Find Front-end Architecture (V3 specific)\n const frontEndCandidates = [\n \"front-end-architecture.md\",\n \"frontend-architecture.md\",\n \"ui-architecture.md\",\n ];\n let frontEndArchFile = null;\n for (const candidate of frontEndCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n frontEndArchFile = candidate;\n break;\n }\n }\n\n // Find UX/UI spec\n const uxSpecCandidates = [\n \"ux-ui-spec.md\",\n \"ux-ui-specification.md\",\n \"ui-spec.md\",\n \"ux-spec.md\",\n ];\n let uxSpecFile = null;\n for (const candidate of uxSpecCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxSpecFile = candidate;\n break;\n }\n }\n\n // Find v0 prompt or UX prompt\n const uxPromptCandidates = [\n \"v0-prompt.md\",\n \"ux-prompt.md\",\n \"ui-prompt.md\",\n \"design-prompt.md\",\n ];\n let uxPromptFile = null;\n for (const candidate of uxPromptCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxPromptFile = candidate;\n break;\n }\n }\n\n // Find epic files\n const epicFiles = await glob(\"epic*.md\", { cwd: docsPath });\n\n // Find story files\n const storiesPath = path.join(docsPath, \"stories\");\n let storyFiles = [];\n if (await this.pathExists(storiesPath)) {\n storyFiles = await glob(\"*.md\", { cwd: storiesPath });\n }\n\n // Count custom files in bmad-agent\n const bmadAgentFiles = await glob(\"**/*.md\", {\n cwd: bmadAgentPath,\n ignore: [\"node_modules/**\"],\n });\n\n return {\n prdFile,\n archFile,\n frontEndArchFile,\n uxSpecFile,\n uxPromptFile,\n epicFiles,\n storyFiles,\n customFileCount: bmadAgentFiles.length,\n };\n }\n\n async showPreflightCheck(analysis, options) {\n console.log(chalk.bold(\"\\nProject Analysis:\"));\n console.log(\n `- PRD found: ${\n analysis.prdFile\n ? `docs/${analysis.prdFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- Architecture found: ${\n analysis.archFile\n ? `docs/${analysis.archFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n if (analysis.frontEndArchFile) {\n console.log(\n `- Front-end Architecture found: docs/${analysis.frontEndArchFile}`\n );\n }\n console.log(\n `- UX/UI Spec found: ${\n analysis.uxSpecFile\n ? `docs/${analysis.uxSpecFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- UX/Design Prompt found: ${\n analysis.uxPromptFile\n ? `docs/${analysis.uxPromptFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- Epic files found: ${analysis.epicFiles.length} files (epic*.md)`\n );\n console.log(\n `- Stories found: ${analysis.storyFiles.length} files in docs/stories/`\n );\n console.log(`- Custom files in bmad-agent/: ${analysis.customFileCount}`);\n\n if (!options.dryRun) {\n console.log(\"\\nThe following will be backed up to .bmad-v3-backup/:\");\n console.log(\"- bmad-agent/ (entire directory)\");\n console.log(\"- docs/ (entire directory)\");\n\n if (analysis.epicFiles.length > 0) {\n console.log(\n chalk.green(\n \"\\nNote: Epic files found! They will be placed in docs/prd/ with an index.md file.\"\n )\n );\n console.log(\n chalk.green(\n \"Since epic files exist, you won't need to shard the PRD after upgrade.\"\n )\n );\n }\n }\n }\n\n async createBackup(projectPath) {\n const spinner = ora(\"Creating backup...\").start();\n\n try {\n const backupPath = path.join(projectPath, \".bmad-v3-backup\");\n\n // Check if backup already exists\n if (await this.pathExists(backupPath)) {\n spinner.fail(\"Backup directory already exists\");\n console.error(\n chalk.red(\n \"\\nError: Backup directory .bmad-v3-backup/ already exists.\"\n )\n );\n console.error(\"\\nThis might mean an upgrade was already attempted.\");\n console.error(\n \"Please remove or rename the existing backup and try again.\"\n );\n throw new Error(\"Backup already exists\");\n }\n\n // Create backup directory\n await fs.mkdir(backupPath, { recursive: true });\n spinner.text = \"āœ“ Created .bmad-v3-backup/\";\n console.log(chalk.green(\"\\nāœ“ Created .bmad-v3-backup/\"));\n\n // Move bmad-agent\n const bmadAgentSrc = path.join(projectPath, \"bmad-agent\");\n const bmadAgentDest = path.join(backupPath, \"bmad-agent\");\n await fs.rename(bmadAgentSrc, bmadAgentDest);\n console.log(chalk.green(\"āœ“ Moved bmad-agent/ to backup\"));\n\n // Move docs\n const docsSrc = path.join(projectPath, \"docs\");\n const docsDest = path.join(backupPath, \"docs\");\n await fs.rename(docsSrc, docsDest);\n console.log(chalk.green(\"āœ“ Moved docs/ to backup\"));\n\n spinner.succeed(\"Backup created successfully\");\n } catch (error) {\n spinner.fail(\"Backup failed\");\n throw error;\n }\n }\n\n async installV4Structure(projectPath) {\n const spinner = ora(\"Installing V4 structure...\").start();\n\n try {\n // Get the source bmad-core directory (without dot prefix)\n const sourcePath = path.join(__dirname, \"..\", \"..\", \"bmad-core\");\n const destPath = path.join(projectPath, \".bmad-core\");\n\n // Copy .bmad-core\n await this.copyDirectory(sourcePath, destPath);\n spinner.text = \"āœ“ Copied fresh .bmad-core/ directory from V4\";\n console.log(\n chalk.green(\"\\nāœ“ Copied fresh .bmad-core/ directory from V4\")\n );\n\n // Create docs directory\n const docsPath = path.join(projectPath, \"docs\");\n await fs.mkdir(docsPath, { recursive: true });\n console.log(chalk.green(\"āœ“ Created new docs/ directory\"));\n\n // Create install manifest for future updates\n await this.createInstallManifest(projectPath);\n console.log(chalk.green(\"āœ“ Created install manifest\"));\n\n console.log(\n chalk.yellow(\n \"\\nNote: Your V3 bmad-agent content has been backed up and NOT migrated.\"\n )\n );\n console.log(\n chalk.yellow(\n \"The new V4 agents are completely different and look for different file structures.\"\n )\n );\n\n spinner.succeed(\"V4 structure installed successfully\");\n } catch (error) {\n spinner.fail(\"V4 installation failed\");\n throw error;\n }\n }\n\n async migrateDocuments(projectPath, analysis) {\n const spinner = ora(\"Migrating your project documents...\").start();\n\n try {\n const backupDocsPath = path.join(projectPath, \".bmad-v3-backup\", \"docs\");\n const newDocsPath = path.join(projectPath, \"docs\");\n let copiedCount = 0;\n\n // Copy PRD\n if (analysis.prdFile) {\n const src = path.join(backupDocsPath, analysis.prdFile);\n const dest = path.join(newDocsPath, analysis.prdFile);\n await fs.copyFile(src, dest);\n console.log(chalk.green(`\\nāœ“ Copied PRD to docs/${analysis.prdFile}`));\n copiedCount++;\n }\n\n // Copy Architecture\n if (analysis.archFile) {\n const src = path.join(backupDocsPath, analysis.archFile);\n const dest = path.join(newDocsPath, analysis.archFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(`āœ“ Copied Architecture to docs/${analysis.archFile}`)\n );\n copiedCount++;\n }\n\n // Copy Front-end Architecture if exists\n if (analysis.frontEndArchFile) {\n const src = path.join(backupDocsPath, analysis.frontEndArchFile);\n const dest = path.join(newDocsPath, analysis.frontEndArchFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(\n `āœ“ Copied Front-end Architecture to docs/${analysis.frontEndArchFile}`\n )\n );\n console.log(\n chalk.yellow(\n \"Note: V4 uses a single full-stack-architecture.md - use doc-migration-task to merge\"\n )\n );\n copiedCount++;\n }\n\n // Copy UX/UI Spec if exists\n if (analysis.uxSpecFile) {\n const src = path.join(backupDocsPath, analysis.uxSpecFile);\n const dest = path.join(newDocsPath, analysis.uxSpecFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(`āœ“ Copied UX/UI Spec to docs/${analysis.uxSpecFile}`)\n );\n copiedCount++;\n }\n\n // Copy UX/Design Prompt if exists\n if (analysis.uxPromptFile) {\n const src = path.join(backupDocsPath, analysis.uxPromptFile);\n const dest = path.join(newDocsPath, analysis.uxPromptFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(\n `āœ“ Copied UX/Design Prompt to docs/${analysis.uxPromptFile}`\n )\n );\n copiedCount++;\n }\n\n // Copy stories\n if (analysis.storyFiles.length > 0) {\n const storiesDir = path.join(newDocsPath, \"stories\");\n await fs.mkdir(storiesDir, { recursive: true });\n\n for (const storyFile of analysis.storyFiles) {\n const src = path.join(backupDocsPath, \"stories\", storyFile);\n const dest = path.join(storiesDir, storyFile);\n await fs.copyFile(src, dest);\n }\n console.log(\n chalk.green(\n `āœ“ Copied ${analysis.storyFiles.length} story files to docs/stories/`\n )\n );\n copiedCount += analysis.storyFiles.length;\n }\n\n // Copy epic files to prd subfolder\n if (analysis.epicFiles.length > 0) {\n const prdDir = path.join(newDocsPath, \"prd\");\n await fs.mkdir(prdDir, { recursive: true });\n\n for (const epicFile of analysis.epicFiles) {\n const src = path.join(backupDocsPath, epicFile);\n const dest = path.join(prdDir, epicFile);\n await fs.copyFile(src, dest);\n }\n console.log(\n chalk.green(\n `āœ“ Found and copied ${analysis.epicFiles.length} epic files to docs/prd/`\n )\n );\n\n // Create index.md for the prd folder\n await this.createPrdIndex(projectPath, analysis);\n console.log(chalk.green(\"āœ“ Created index.md in docs/prd/\"));\n\n console.log(\n chalk.green(\n \"\\nNote: Epic files detected! These are compatible with V4 and have been copied.\"\n )\n );\n console.log(\n chalk.green(\n \"You won't need to shard the PRD since epics already exist.\"\n )\n );\n copiedCount += analysis.epicFiles.length;\n }\n\n spinner.succeed(`Migrated ${copiedCount} documents successfully`);\n } catch (error) {\n spinner.fail(\"Document migration failed\");\n throw error;\n }\n }\n\n async setupIDE(projectPath, selectedIdes) {\n // Use the IDE selections passed from the installer\n if (!selectedIdes || selectedIdes.length === 0) {\n console.log(chalk.dim(\"No IDE setup requested - skipping\"));\n return;\n }\n\n const ideSetup = require(\"../installer/lib/ide-setup\");\n const spinner = ora(\"Setting up IDE rules for all agents...\").start();\n\n try {\n const ideMessages = {\n cursor: \"Rules created in .cursor/rules/\",\n \"claude-code\": \"Commands created in .claude/commands/BMad/\",\n windsurf: \"Rules created in .windsurf/rules/\",\n trae: \"Rules created in.trae/rules/\",\n roo: \"Custom modes created in .roomodes\",\n cline: \"Rules created in .clinerules/\",\n };\n\n // Setup each selected IDE\n for (const ide of selectedIdes) {\n spinner.text = `Setting up ${ide}...`;\n await ideSetup.setup(ide, projectPath);\n console.log(chalk.green(`\\nāœ“ ${ideMessages[ide]}`));\n }\n\n spinner.succeed(`IDE setup complete for ${selectedIdes.length} IDE(s)!`);\n } catch (error) {\n spinner.fail(\"IDE setup failed\");\n console.error(\n chalk.yellow(\"IDE setup failed, but upgrade is complete.\")\n );\n }\n }\n\n showCompletionReport(projectPath, analysis) {\n console.log(chalk.bold.green(\"\\nāœ“ Upgrade Complete!\\n\"));\n console.log(chalk.bold(\"Summary:\"));\n console.log(`- V3 files backed up to: .bmad-v3-backup/`);\n console.log(`- V4 structure installed: .bmad-core/ (fresh from V4)`);\n\n const totalDocs =\n (analysis.prdFile ? 1 : 0) +\n (analysis.archFile ? 1 : 0) +\n (analysis.frontEndArchFile ? 1 : 0) +\n (analysis.uxSpecFile ? 1 : 0) +\n (analysis.uxPromptFile ? 1 : 0) +\n analysis.storyFiles.length;\n console.log(\n `- Documents migrated: ${totalDocs} files${\n analysis.epicFiles.length > 0\n ? ` + ${analysis.epicFiles.length} epics`\n : \"\"\n }`\n );\n\n console.log(chalk.bold(\"\\nImportant Changes:\"));\n console.log(\n \"- The V4 agents (sm, dev, etc.) expect different file structures than V3\"\n );\n console.log(\n \"- Your V3 bmad-agent content was NOT migrated (it's incompatible)\"\n );\n if (analysis.epicFiles.length > 0) {\n console.log(\n \"- Epic files were found and copied - no PRD sharding needed!\"\n );\n }\n if (analysis.frontEndArchFile) {\n console.log(\n \"- Front-end architecture found - V4 uses full-stack-architecture.md, migration needed\"\n );\n }\n if (analysis.uxSpecFile || analysis.uxPromptFile) {\n console.log(\n \"- UX/UI design files found and copied - ready for use with V4\"\n );\n }\n\n console.log(chalk.bold(\"\\nNext Steps:\"));\n console.log(\"1. Review your documents in the new docs/ folder\");\n console.log(\n \"2. Use @bmad-master agent to run the doc-migration-task to align your documents with V4 templates\"\n );\n if (analysis.epicFiles.length === 0) {\n console.log(\n \"3. Use @bmad-master agent to shard the PRD to create epic files\"\n );\n }\n\n console.log(\n chalk.dim(\n \"\\nYour V3 backup is preserved in .bmad-v3-backup/ and can be restored if needed.\"\n )\n );\n }\n\n async pathExists(filePath) {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n async copyDirectory(src, dest) {\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await this.copyDirectory(srcPath, destPath);\n } else {\n await fs.copyFile(srcPath, destPath);\n }\n }\n }\n\n async createPrdIndex(projectPath, analysis) {\n const prdIndexPath = path.join(projectPath, \"docs\", \"prd\", \"index.md\");\n const prdPath = path.join(\n projectPath,\n \"docs\",\n analysis.prdFile || \"prd.md\"\n );\n\n let indexContent = \"# Product Requirements Document\\n\\n\";\n\n // Try to read the PRD to get the title and intro content\n if (analysis.prdFile && (await this.pathExists(prdPath))) {\n try {\n const prdContent = await fs.readFile(prdPath, \"utf8\");\n const lines = prdContent.split(\"\\n\");\n\n // Find the first heading\n const titleMatch = lines.find((line) => line.startsWith(\"# \"));\n if (titleMatch) {\n indexContent = titleMatch + \"\\n\\n\";\n }\n\n // Get any content before the first ## section\n let introContent = \"\";\n let foundFirstSection = false;\n for (const line of lines) {\n if (line.startsWith(\"## \")) {\n foundFirstSection = true;\n break;\n }\n if (!line.startsWith(\"# \")) {\n introContent += line + \"\\n\";\n }\n }\n\n if (introContent.trim()) {\n indexContent += introContent.trim() + \"\\n\\n\";\n }\n } catch (error) {\n // If we can't read the PRD, just use default content\n }\n }\n\n // Add sections list\n indexContent += \"## Sections\\n\\n\";\n\n // Sort epic files for consistent ordering\n const sortedEpics = [...analysis.epicFiles].sort();\n\n for (const epicFile of sortedEpics) {\n // Extract epic name from filename\n const epicName = epicFile\n .replace(/\\.md$/, \"\")\n .replace(/^epic-?/i, \"\")\n .replace(/-/g, \" \")\n .replace(/^\\d+\\s*/, \"\") // Remove leading numbers\n .trim();\n\n const displayName = epicName.charAt(0).toUpperCase() + epicName.slice(1);\n indexContent += `- [${\n displayName || epicFile.replace(\".md\", \"\")\n }](./${epicFile})\\n`;\n }\n\n await fs.writeFile(prdIndexPath, indexContent);\n }\n\n async createInstallManifest(projectPath) {\n const fileManager = require(\"../installer/lib/file-manager\");\n const { glob } = require(\"glob\");\n\n // Get all files in .bmad-core for the manifest\n const bmadCorePath = path.join(projectPath, \".bmad-core\");\n const files = await glob(\"**/*\", {\n cwd: bmadCorePath,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n\n // Prepend .bmad-core/ to file paths for manifest\n const manifestFiles = files.map((file) => path.join(\".bmad-core\", file));\n\n const config = {\n installType: \"full\",\n agent: null,\n ide: null, // Will be set if IDE setup is done later\n };\n\n await fileManager.createManifest(projectPath, config, manifestFiles);\n }\n}\n\nmodule.exports = V3ToV4Upgrader;\n"], ["/BMAD-METHOD/tools/bump-expansion-version.js", "#!/usr/bin/env node\n\n// Load required modules\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\n// Parse CLI arguments\nconst args = process.argv.slice(2);\nconst packId = args[0];\nconst bumpType = args[1] || 'minor';\n\n// Validate arguments\nif (!packId || args.length > 2) {\n console.log('Usage: node bump-expansion-version.js [major|minor|patch]');\n console.log('Default: minor');\n console.log('Example: node bump-expansion-version.js bmad-creator-tools patch');\n process.exit(1);\n}\n\nif (!['major', 'minor', 'patch'].includes(bumpType)) {\n console.error('Error: Bump type must be major, minor, or patch');\n process.exit(1);\n}\n\n// Version bump logic\nfunction bumpVersion(currentVersion, type) {\n const [major, minor, patch] = currentVersion.split('.').map(Number);\n\n switch (type) {\n case 'major': return `${major + 1}.0.0`;\n case 'minor': return `${major}.${minor + 1}.0`;\n case 'patch': return `${major}.${minor}.${patch + 1}`;\n default: return currentVersion;\n }\n}\n\n// Main function to bump version\nasync function updateVersion() {\n const configPath = path.join(__dirname, '..', 'expansion-packs', packId, 'config.yaml');\n\n // Check if config exists\n if (!fs.existsSync(configPath)) {\n console.error(`Error: Expansion pack '${packId}' not found`);\n console.log('\\nAvailable expansion packs:');\n\n const packsDir = path.join(__dirname, '..', 'expansion-packs');\n const entries = fs.readdirSync(packsDir, { withFileTypes: true });\n\n entries.forEach(entry => {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n console.log(` - ${entry.name}`);\n }\n });\n\n process.exit(1);\n }\n\n try {\n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n\n const oldVersion = config.version || '1.0.0';\n const newVersion = bumpVersion(oldVersion, bumpType);\n\n config.version = newVersion;\n\n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n\n console.log(`āœ“ ${packId}: ${oldVersion} → ${newVersion}`);\n console.log(`\\nāœ“ Successfully bumped ${packId} with ${bumpType} version bump`);\n console.log('\\nNext steps:');\n console.log(`1. Test the changes`);\n console.log(`2. Commit: git add -A && git commit -m \"chore: bump ${packId} version (${bumpType})\"`);\n\n } catch (error) {\n console.error('Error updating version:', error.message);\n process.exit(1);\n }\n}\n\nupdateVersion();\n"], ["/BMAD-METHOD/tools/cli.js", "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst WebBuilder = require('./builders/web-builder');\nconst V3ToV4Upgrader = require('./upgraders/v3-to-v4-upgrader');\nconst IdeSetup = require('./installer/lib/ide-setup');\nconst path = require('path');\n\nconst program = new Command();\n\nprogram\n .name('bmad-build')\n .description('BMad-Method build tool for creating web bundles')\n .version('4.0.0');\n\nprogram\n .command('build')\n .description('Build web bundles for agents and teams')\n .option('-a, --agents-only', 'Build only agent bundles')\n .option('-t, --teams-only', 'Build only team bundles')\n .option('-e, --expansions-only', 'Build only expansion pack bundles')\n .option('--no-expansions', 'Skip building expansion packs')\n .option('--no-clean', 'Skip cleaning output directories')\n .action(async (options) => {\n const builder = new WebBuilder({\n rootDir: process.cwd()\n });\n\n try {\n if (options.clean) {\n console.log('Cleaning output directories...');\n await builder.cleanOutputDirs();\n }\n\n if (options.expansionsOnly) {\n console.log('Building expansion pack bundles...');\n await builder.buildAllExpansionPacks({ clean: false });\n } else {\n if (!options.teamsOnly) {\n console.log('Building agent bundles...');\n await builder.buildAgents();\n }\n\n if (!options.agentsOnly) {\n console.log('Building team bundles...');\n await builder.buildTeams();\n }\n\n if (!options.noExpansions) {\n console.log('Building expansion pack bundles...');\n await builder.buildAllExpansionPacks({ clean: false });\n }\n }\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error('Build failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('build:expansions')\n .description('Build web bundles for all expansion packs')\n .option('--expansion ', 'Build specific expansion pack only')\n .option('--no-clean', 'Skip cleaning output directories')\n .action(async (options) => {\n const builder = new WebBuilder({\n rootDir: process.cwd()\n });\n\n try {\n if (options.expansion) {\n console.log(`Building expansion pack: ${options.expansion}`);\n await builder.buildExpansionPack(options.expansion, { clean: options.clean });\n } else {\n console.log('Building all expansion packs...');\n await builder.buildAllExpansionPacks({ clean: options.clean });\n }\n\n console.log('Expansion pack build completed successfully!');\n } catch (error) {\n console.error('Expansion pack build failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('list:agents')\n .description('List all available agents')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n const agents = await builder.resolver.listAgents();\n console.log('Available agents:');\n agents.forEach(agent => console.log(` - ${agent}`));\n });\n\nprogram\n .command('list:expansions')\n .description('List all available expansion packs')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n const expansions = await builder.listExpansionPacks();\n console.log('Available expansion packs:');\n expansions.forEach(expansion => console.log(` - ${expansion}`));\n });\n\nprogram\n .command('validate')\n .description('Validate agent and team configurations')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n try {\n // Validate by attempting to build all agents and teams\n const agents = await builder.resolver.listAgents();\n const teams = await builder.resolver.listTeams();\n \n console.log('Validating agents...');\n for (const agent of agents) {\n await builder.resolver.resolveAgentDependencies(agent);\n console.log(` āœ“ ${agent}`);\n }\n \n console.log('\\nValidating teams...');\n for (const team of teams) {\n await builder.resolver.resolveTeamDependencies(team);\n console.log(` āœ“ ${team}`);\n }\n \n console.log('\\nAll configurations are valid!');\n } catch (error) {\n console.error('Validation failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('upgrade')\n .description('Upgrade a BMad-Method V3 project to V4')\n .option('-p, --project ', 'Path to V3 project (defaults to current directory)')\n .option('--dry-run', 'Show what would be changed without making changes')\n .option('--no-backup', 'Skip creating backup (not recommended)')\n .action(async (options) => {\n const upgrader = new V3ToV4Upgrader();\n await upgrader.upgrade({\n projectPath: options.project,\n dryRun: options.dryRun,\n backup: options.backup\n });\n });\n\nprogram\n .command('flatten')\n .description('Flatten codebase to XML format')\n .option('-o, --output ', 'Output file path', 'flattened-codebase.xml')\n .action(async (options) => {\n const flattener = require('./flattener/main');\n await flattener.parseAsync(['flatten', '--output', options.output], { from: 'user' });\n });\n\nprogram.parse();"], ["/BMAD-METHOD/tools/flattener/main.js", "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst fs = require('fs-extra');\nconst path = require('node:path');\nconst { glob } = require('glob');\nconst { minimatch } = require('minimatch');\n\n/**\n * Recursively discover all files in a directory\n * @param {string} rootDir - The root directory to scan\n * @returns {Promise} Array of file paths\n */\nasync function discoverFiles(rootDir) {\n try {\n const gitignorePath = path.join(rootDir, '.gitignore');\n const gitignorePatterns = await parseGitignore(gitignorePath);\n\n // Common gitignore patterns that should always be ignored\n const commonIgnorePatterns = [\n // Version control\n '.git/**',\n '.svn/**',\n '.hg/**',\n '.bzr/**',\n\n // Dependencies\n 'node_modules/**',\n 'bower_components/**',\n 'vendor/**',\n 'packages/**',\n\n // Build outputs\n 'build/**',\n 'dist/**',\n 'out/**',\n 'target/**',\n 'bin/**',\n 'obj/**',\n 'release/**',\n 'debug/**',\n\n // Environment and config\n '.env',\n '.env.*',\n '*.env',\n '.config',\n\n // Logs\n 'logs/**',\n '*.log',\n 'npm-debug.log*',\n 'yarn-debug.log*',\n 'yarn-error.log*',\n 'lerna-debug.log*',\n\n // Coverage and testing\n 'coverage/**',\n '.nyc_output/**',\n '.coverage/**',\n 'test-results/**',\n 'junit.xml',\n\n // Cache directories\n '.cache/**',\n '.tmp/**',\n '.temp/**',\n 'tmp/**',\n 'temp/**',\n '.sass-cache/**',\n '.eslintcache',\n '.stylelintcache',\n\n // OS generated files\n '.DS_Store',\n '.DS_Store?',\n '._*',\n '.Spotlight-V100',\n '.Trashes',\n 'ehthumbs.db',\n 'Thumbs.db',\n 'desktop.ini',\n\n // IDE and editor files\n '.vscode/**',\n '.idea/**',\n '*.swp',\n '*.swo',\n '*~',\n '.project',\n '.classpath',\n '.settings/**',\n '*.sublime-project',\n '*.sublime-workspace',\n\n // Package manager files\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Pipfile.lock',\n\n // Runtime and compiled files\n '*.pyc',\n '*.pyo',\n '*.pyd',\n '__pycache__/**',\n '*.class',\n '*.jar',\n '*.war',\n '*.ear',\n '*.o',\n '*.so',\n '*.dll',\n '*.exe',\n\n // Documentation build\n '_site/**',\n '.jekyll-cache/**',\n '.jekyll-metadata',\n\n // Flattener specific outputs\n 'flattened-codebase.xml',\n 'repomix-output.xml'\n ];\n\n const combinedIgnores = [\n ...gitignorePatterns,\n ...commonIgnorePatterns\n ];\n\n // Use glob to recursively find all files, excluding common ignore patterns\n const files = await glob('**/*', {\n cwd: rootDir,\n nodir: true, // Only files, not directories\n dot: true, // Include hidden files\n follow: false, // Don't follow symbolic links\n ignore: combinedIgnores\n });\n\n return files.map(file => path.resolve(rootDir, file));\n } catch (error) {\n console.error('Error discovering files:', error.message);\n return [];\n }\n}\n\n/**\n * Parse .gitignore file and return ignore patterns\n * @param {string} gitignorePath - Path to .gitignore file\n * @returns {Promise} Array of ignore patterns\n */\nasync function parseGitignore(gitignorePath) {\n try {\n if (!await fs.pathExists(gitignorePath)) {\n return [];\n }\n\n const content = await fs.readFile(gitignorePath, 'utf8');\n return content\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line && !line.startsWith('#')) // Remove empty lines and comments\n .map(pattern => {\n // Convert gitignore patterns to glob patterns\n if (pattern.endsWith('/')) {\n return pattern + '**';\n }\n return pattern;\n });\n } catch (error) {\n console.error('Error parsing .gitignore:', error.message);\n return [];\n }\n}\n\n/**\n * Check if a file is binary using file command and heuristics\n * @param {string} filePath - Path to the file\n * @returns {Promise} True if file is binary\n */\nasync function isBinaryFile(filePath) {\n try {\n // First check by file extension\n const binaryExtensions = [\n '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.ico', '.svg',\n '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',\n '.zip', '.tar', '.gz', '.rar', '.7z',\n '.exe', '.dll', '.so', '.dylib',\n '.mp3', '.mp4', '.avi', '.mov', '.wav',\n '.ttf', '.otf', '.woff', '.woff2',\n '.bin', '.dat', '.db', '.sqlite'\n ];\n\n const ext = path.extname(filePath).toLowerCase();\n if (binaryExtensions.includes(ext)) {\n return true;\n }\n\n // For files without clear extensions, try to read a small sample\n const stats = await fs.stat(filePath);\n if (stats.size === 0) {\n return false; // Empty files are considered text\n }\n\n // Read first 1024 bytes to check for null bytes\n const sampleSize = Math.min(1024, stats.size);\n const buffer = await fs.readFile(filePath, { encoding: null, flag: 'r' });\n const sample = buffer.slice(0, sampleSize);\n // If we find null bytes, it's likely binary\n return sample.includes(0);\n } catch (error) {\n console.warn(`Warning: Could not determine if file is binary: ${filePath} - ${error.message}`);\n return false; // Default to text if we can't determine\n }\n}\n\n/**\n * Read and aggregate content from text files\n * @param {string[]} files - Array of file paths\n * @param {string} rootDir - The root directory\n * @param {Object} spinner - Optional spinner instance for progress display\n * @returns {Promise} Object containing file contents and metadata\n */\nasync function aggregateFileContents(files, rootDir, spinner = null) {\n const results = {\n textFiles: [],\n binaryFiles: [],\n errors: [],\n totalFiles: files.length,\n processedFiles: 0\n };\n\n for (const filePath of files) {\n try {\n const relativePath = path.relative(rootDir, filePath);\n\n // Update progress indicator\n if (spinner) {\n spinner.text = `Processing file ${results.processedFiles + 1}/${results.totalFiles}: ${relativePath}`;\n }\n\n const isBinary = await isBinaryFile(filePath);\n\n if (isBinary) {\n results.binaryFiles.push({\n path: relativePath,\n absolutePath: filePath,\n size: (await fs.stat(filePath)).size\n });\n } else {\n // Read text file content\n const content = await fs.readFile(filePath, 'utf8');\n results.textFiles.push({\n path: relativePath,\n absolutePath: filePath,\n content: content,\n size: content.length,\n lines: content.split('\\n').length\n });\n }\n\n results.processedFiles++;\n } catch (error) {\n const relativePath = path.relative(rootDir, filePath);\n const errorInfo = {\n path: relativePath,\n absolutePath: filePath,\n error: error.message\n };\n\n results.errors.push(errorInfo);\n\n // Log warning without interfering with spinner\n if (spinner) {\n spinner.warn(`Warning: Could not read file ${relativePath}: ${error.message}`);\n } else {\n console.warn(`Warning: Could not read file ${relativePath}: ${error.message}`);\n }\n\n results.processedFiles++;\n }\n }\n\n return results;\n}\n\n/**\n * Generate XML output with aggregated file contents using streaming\n * @param {Object} aggregatedContent - The aggregated content object\n * @param {string} outputPath - The output file path\n * @returns {Promise} Promise that resolves when writing is complete\n */\nasync function generateXMLOutput(aggregatedContent, outputPath) {\n const { textFiles } = aggregatedContent;\n\n // Create write stream for efficient memory usage\n const writeStream = fs.createWriteStream(outputPath, { encoding: 'utf8' });\n\n return new Promise((resolve, reject) => {\n writeStream.on('error', reject);\n writeStream.on('finish', resolve);\n\n // Write XML header\n writeStream.write('\\n');\n writeStream.write('\\n');\n\n // Process files one by one to minimize memory usage\n let fileIndex = 0;\n\n const writeNextFile = () => {\n if (fileIndex >= textFiles.length) {\n // All files processed, close XML and stream\n writeStream.write('\\n');\n writeStream.end();\n return;\n }\n\n const file = textFiles[fileIndex];\n fileIndex++;\n\n // Write file opening tag\n writeStream.write(` `);\n\n // Use CDATA for code content, handling CDATA end sequences properly\n if (file.content?.trim()) {\n const indentedContent = indentFileContent(file.content);\n if (file.content.includes(']]>')) {\n // If content contains ]]>, split it and wrap each part in CDATA\n writeStream.write(splitAndWrapCDATA(indentedContent));\n } else {\n writeStream.write(``);\n }\n } else if (file.content) {\n // Handle empty or whitespace-only content\n const indentedContent = indentFileContent(file.content);\n writeStream.write(``);\n }\n\n // Write file closing tag\n writeStream.write('\\n');\n\n // Continue with next file on next tick to avoid stack overflow\n setImmediate(writeNextFile);\n };\n\n // Start processing files\n writeNextFile();\n });\n}\n\n/**\n * Escape XML special characters for attributes\n * @param {string} str - String to escape\n * @returns {string} Escaped string\n */\nfunction escapeXml(str) {\n if (typeof str !== 'string') {\n return String(str);\n }\n return str\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Indent file content with 4 spaces for each line\n * @param {string} content - Content to indent\n * @returns {string} Indented content\n */\nfunction indentFileContent(content) {\n if (typeof content !== 'string') {\n return String(content);\n }\n\n // Split content into lines and add 4 spaces of indentation to each line\n return content.split('\\n').map(line => ` ${line}`).join('\\n');\n}\n\n/**\n * Split content containing ]]> and wrap each part in CDATA\n * @param {string} content - Content to process\n * @returns {string} Content with properly wrapped CDATA sections\n */\nfunction splitAndWrapCDATA(content) {\n if (typeof content !== 'string') {\n return String(content);\n }\n\n // Replace ]]> with ]]]]> to escape it within CDATA\n const escapedContent = content.replace(/]]>/g, ']]]]>');\n return ``;\n}\n\n/**\n * Calculate statistics for the processed files\n * @param {Object} aggregatedContent - The aggregated content object\n * @param {number} xmlFileSize - The size of the generated XML file in bytes\n * @returns {Object} Statistics object\n */\nfunction calculateStatistics(aggregatedContent, xmlFileSize) {\n const { textFiles, binaryFiles, errors } = aggregatedContent;\n\n // Calculate total file size in bytes\n const totalTextSize = textFiles.reduce((sum, file) => sum + file.size, 0);\n const totalBinarySize = binaryFiles.reduce((sum, file) => sum + file.size, 0);\n const totalSize = totalTextSize + totalBinarySize;\n\n // Calculate total lines of code\n const totalLines = textFiles.reduce((sum, file) => sum + file.lines, 0);\n\n // Estimate token count (rough approximation: 1 token ā‰ˆ 4 characters)\n const estimatedTokens = Math.ceil(xmlFileSize / 4);\n\n // Format file size\n const formatSize = (bytes) => {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n };\n\n return {\n totalFiles: textFiles.length + binaryFiles.length,\n textFiles: textFiles.length,\n binaryFiles: binaryFiles.length,\n errorFiles: errors.length,\n totalSize: formatSize(totalSize),\n xmlSize: formatSize(xmlFileSize),\n totalLines,\n estimatedTokens: estimatedTokens.toLocaleString()\n };\n}\n\n/**\n * Filter files based on .gitignore patterns\n * @param {string[]} files - Array of file paths\n * @param {string} rootDir - The root directory\n * @returns {Promise} Filtered array of file paths\n */\nasync function filterFiles(files, rootDir) {\n const gitignorePath = path.join(rootDir, '.gitignore');\n const ignorePatterns = await parseGitignore(gitignorePath);\n\n if (ignorePatterns.length === 0) {\n return files;\n }\n\n // Convert absolute paths to relative for pattern matching\n const relativeFiles = files.map(file => path.relative(rootDir, file));\n\n // Separate positive and negative patterns\n const positivePatterns = ignorePatterns.filter(p => !p.startsWith('!'));\n const negativePatterns = ignorePatterns.filter(p => p.startsWith('!')).map(p => p.slice(1));\n\n // Filter out files that match ignore patterns\n const filteredRelative = [];\n\n for (const file of relativeFiles) {\n let shouldIgnore = false;\n\n // First check positive patterns (ignore these files)\n for (const pattern of positivePatterns) {\n if (minimatch(file, pattern)) {\n shouldIgnore = true;\n break;\n }\n }\n\n // Then check negative patterns (don't ignore these files even if they match positive patterns)\n if (shouldIgnore) {\n for (const pattern of negativePatterns) {\n if (minimatch(file, pattern)) {\n shouldIgnore = false;\n break;\n }\n }\n }\n\n if (!shouldIgnore) {\n filteredRelative.push(file);\n }\n }\n\n // Convert back to absolute paths\n return filteredRelative.map(file => path.resolve(rootDir, file));\n}\n\nconst program = new Command();\n\nprogram\n .name('bmad-flatten')\n .description('BMad-Method codebase flattener tool')\n .version('1.0.0')\n .option('-o, --output ', 'Output file path', 'flattened-codebase.xml')\n .action(async (options) => {\n console.log(`Flattening codebase to: ${options.output}`);\n\n try {\n // Import ora dynamically\n const { default: ora } = await import('ora');\n\n // Start file discovery with spinner\n const discoverySpinner = ora('šŸ” Discovering files...').start();\n const files = await discoverFiles(process.cwd());\n const filteredFiles = await filterFiles(files, process.cwd());\n discoverySpinner.succeed(`šŸ“ Found ${filteredFiles.length} files to include`);\n\n // Process files with progress tracking\n console.log('Reading file contents');\n const processingSpinner = ora('šŸ“„ Processing files...').start();\n const aggregatedContent = await aggregateFileContents(filteredFiles, process.cwd(), processingSpinner);\n processingSpinner.succeed(`āœ… Processed ${aggregatedContent.processedFiles}/${filteredFiles.length} files`);\n\n // Log processing results for test validation\n console.log(`Processed ${aggregatedContent.processedFiles}/${filteredFiles.length} files`);\n if (aggregatedContent.errors.length > 0) {\n console.log(`Errors: ${aggregatedContent.errors.length}`);\n }\n console.log(`Text files: ${aggregatedContent.textFiles.length}`);\n if (aggregatedContent.binaryFiles.length > 0) {\n console.log(`Binary files: ${aggregatedContent.binaryFiles.length}`);\n }\n\n // Generate XML output using streaming\n const xmlSpinner = ora('šŸ”§ Generating XML output...').start();\n await generateXMLOutput(aggregatedContent, options.output);\n xmlSpinner.succeed('šŸ“ XML generation completed');\n\n // Calculate and display statistics\n const outputStats = await fs.stat(options.output);\n const stats = calculateStatistics(aggregatedContent, outputStats.size);\n\n // Display completion summary\n console.log('\\nšŸ“Š Completion Summary:');\n console.log(`āœ… Successfully processed ${filteredFiles.length} files into ${options.output}`);\n console.log(`šŸ“ Output file: ${path.resolve(options.output)}`);\n console.log(`šŸ“ Total source size: ${stats.totalSize}`);\n console.log(`šŸ“„ Generated XML size: ${stats.xmlSize}`);\n console.log(`šŸ“ Total lines of code: ${stats.totalLines.toLocaleString()}`);\n console.log(`šŸ”¢ Estimated tokens: ${stats.estimatedTokens}`);\n console.log(`šŸ“Š File breakdown: ${stats.textFiles} text, ${stats.binaryFiles} binary, ${stats.errorFiles} errors`);\n\n } catch (error) {\n console.error('āŒ Critical error:', error.message);\n console.error('An unexpected error occurred.');\n process.exit(1);\n }\n });\n\nif (require.main === module) {\n program.parse();\n}\n\nmodule.exports = program;\n"], ["/BMAD-METHOD/tools/yaml-format.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { execSync } = require('child_process');\n\n// Dynamic import for ES module\nlet chalk;\n\n// Initialize ES modules\nasync function initializeModules() {\n if (!chalk) {\n chalk = (await import('chalk')).default;\n }\n}\n\n/**\n * YAML Formatter and Linter for BMad-Method\n * Formats and validates YAML files and YAML embedded in Markdown\n */\n\nasync function formatYamlContent(content, filename) {\n await initializeModules();\n try {\n // First try to fix common YAML issues\n let fixedContent = content\n // Fix \"commands :\" -> \"commands:\"\n .replace(/^(\\s*)(\\w+)\\s+:/gm, '$1$2:')\n // Fix inconsistent list indentation\n .replace(/^(\\s*)-\\s{3,}/gm, '$1- ');\n \n // Skip auto-fixing for .roomodes files - they have special nested structure\n if (!filename.includes('.roomodes')) {\n fixedContent = fixedContent\n // Fix unquoted list items that contain special characters or multiple parts\n .replace(/^(\\s*)-\\s+(.*)$/gm, (match, indent, content) => {\n // Skip if already quoted\n if (content.startsWith('\"') && content.endsWith('\"')) {\n return match;\n }\n // If the content contains special YAML characters or looks complex, quote it\n // BUT skip if it looks like a proper YAML key-value pair (like \"key: value\")\n if ((content.includes(':') || content.includes('-') || content.includes('{') || content.includes('}')) && \n !content.match(/^\\w+:\\s/)) {\n // Remove any existing quotes first, escape internal quotes, then add proper quotes\n const cleanContent = content.replace(/^[\"']|[\"']$/g, '').replace(/\"/g, '\\\\\"');\n return `${indent}- \"${cleanContent}\"`;\n }\n return match;\n });\n }\n \n // Debug: show what we're trying to parse\n if (fixedContent !== content) {\n console.log(chalk.blue(`šŸ”§ Applied YAML fixes to ${filename}`));\n }\n \n // Parse and re-dump YAML to format it\n const parsed = yaml.load(fixedContent);\n const formatted = yaml.dump(parsed, {\n indent: 2,\n lineWidth: -1, // Disable line wrapping\n noRefs: true,\n sortKeys: false // Preserve key order\n });\n return formatted;\n } catch (error) {\n console.error(chalk.red(`āŒ YAML syntax error in ${filename}:`), error.message);\n console.error(chalk.yellow(`šŸ’” Try manually fixing the YAML structure first`));\n return null;\n }\n}\n\nasync function processMarkdownFile(filePath) {\n await initializeModules();\n const content = fs.readFileSync(filePath, 'utf8');\n let modified = false;\n let newContent = content;\n\n // Fix untyped code blocks by adding 'text' type\n // Match ``` at start of line followed by newline, but only if it's an opening fence\n newContent = newContent.replace(/^```\\n([\\s\\S]*?)\\n```$/gm, '```text\\n$1\\n```');\n if (newContent !== content) {\n modified = true;\n console.log(chalk.blue(`šŸ”§ Added 'text' type to untyped code blocks in ${filePath}`));\n }\n\n // Find YAML code blocks\n const yamlBlockRegex = /```ya?ml\\n([\\s\\S]*?)\\n```/g;\n let match;\n const replacements = [];\n \n while ((match = yamlBlockRegex.exec(newContent)) !== null) {\n const [fullMatch, yamlContent] = match;\n const formatted = await formatYamlContent(yamlContent, filePath);\n if (formatted !== null) {\n // Remove trailing newline that js-yaml adds\n const trimmedFormatted = formatted.replace(/\\n$/, '');\n \n if (trimmedFormatted !== yamlContent) {\n modified = true;\n console.log(chalk.green(`āœ“ Formatted YAML in ${filePath}`));\n }\n \n replacements.push({\n start: match.index,\n end: match.index + fullMatch.length,\n replacement: `\\`\\`\\`yaml\\n${trimmedFormatted}\\n\\`\\`\\``\n });\n }\n }\n \n // Apply replacements in reverse order to maintain indices\n for (let i = replacements.length - 1; i >= 0; i--) {\n const { start, end, replacement } = replacements[i];\n newContent = newContent.slice(0, start) + replacement + newContent.slice(end);\n }\n\n if (modified) {\n fs.writeFileSync(filePath, newContent);\n return true;\n }\n return false;\n}\n\nasync function processYamlFile(filePath) {\n await initializeModules();\n const content = fs.readFileSync(filePath, 'utf8');\n const formatted = await formatYamlContent(content, filePath);\n \n if (formatted === null) {\n return false; // Syntax error\n }\n \n if (formatted !== content) {\n fs.writeFileSync(filePath, formatted);\n return true;\n }\n return false;\n}\n\nasync function lintYamlFile(filePath) {\n await initializeModules();\n try {\n // Use yaml-lint for additional validation\n execSync(`npx yaml-lint \"${filePath}\"`, { stdio: 'pipe' });\n return true;\n } catch (error) {\n console.error(chalk.red(`āŒ YAML lint error in ${filePath}:`));\n console.error(error.stdout?.toString() || error.message);\n return false;\n }\n}\n\nasync function main() {\n await initializeModules();\n const args = process.argv.slice(2);\n const glob = require('glob');\n \n if (args.length === 0) {\n console.error('Usage: node yaml-format.js [file2] ...');\n process.exit(1);\n }\n\n let hasErrors = false;\n let hasChanges = false;\n let filesProcessed = [];\n\n // Expand glob patterns and collect all files\n const allFiles = [];\n for (const arg of args) {\n if (arg.includes('*')) {\n // It's a glob pattern\n const matches = glob.sync(arg);\n allFiles.push(...matches);\n } else {\n // It's a direct file path\n allFiles.push(arg);\n }\n }\n\n for (const filePath of allFiles) {\n if (!fs.existsSync(filePath)) {\n // Skip silently for glob patterns that don't match anything\n if (!args.some(arg => arg.includes('*') && filePath === arg)) {\n console.error(chalk.red(`āŒ File not found: ${filePath}`));\n hasErrors = true;\n }\n continue;\n }\n\n const ext = path.extname(filePath).toLowerCase();\n const basename = path.basename(filePath).toLowerCase();\n \n try {\n let changed = false;\n if (ext === '.md') {\n changed = await processMarkdownFile(filePath);\n } else if (ext === '.yaml' || ext === '.yml' || basename.includes('roomodes') || basename.includes('.yaml') || basename.includes('.yml')) {\n // Handle YAML files and special cases like .roomodes\n changed = await processYamlFile(filePath);\n \n // Also run linting\n const lintPassed = await lintYamlFile(filePath);\n if (!lintPassed) hasErrors = true;\n } else {\n // Skip silently for unsupported files\n continue;\n }\n \n if (changed) {\n hasChanges = true;\n filesProcessed.push(filePath);\n }\n } catch (error) {\n console.error(chalk.red(`āŒ Error processing ${filePath}:`), error.message);\n hasErrors = true;\n }\n }\n\n if (hasChanges) {\n console.log(chalk.green(`\\n✨ YAML formatting completed! Modified ${filesProcessed.length} files:`));\n filesProcessed.forEach(file => console.log(chalk.blue(` šŸ“ ${file}`)));\n }\n\n if (hasErrors) {\n console.error(chalk.red('\\nšŸ’„ Some files had errors. Please fix them before committing.'));\n process.exit(1);\n }\n}\n\nif (require.main === module) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n\nmodule.exports = { formatYamlContent, processMarkdownFile, processYamlFile };"], ["/BMAD-METHOD/tools/update-expansion-version.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\nconst args = process.argv.slice(2);\n\nif (args.length < 2) {\n console.log('Usage: node update-expansion-version.js ');\n console.log('Example: node update-expansion-version.js bmad-creator-tools 1.1.0');\n process.exit(1);\n}\n\nconst [packId, newVersion] = args;\n\n// Validate version format\nif (!/^\\d+\\.\\d+\\.\\d+$/.test(newVersion)) {\n console.error('Error: Version must be in format X.Y.Z (e.g., 1.2.3)');\n process.exit(1);\n}\n\nasync function updateVersion() {\n try {\n // Update in config.yaml\n const configPath = path.join(__dirname, '..', 'expansion-packs', packId, 'config.yaml');\n \n if (!fs.existsSync(configPath)) {\n console.error(`Error: Expansion pack '${packId}' not found`);\n process.exit(1);\n }\n \n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n const oldVersion = config.version || 'unknown';\n \n config.version = newVersion;\n \n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n \n console.log(`āœ“ Updated ${packId}/config.yaml: ${oldVersion} → ${newVersion}`);\n console.log(`\\nāœ“ Successfully updated ${packId} to version ${newVersion}`);\n console.log('\\nNext steps:');\n console.log('1. Test the changes');\n console.log('2. Commit: git add -A && git commit -m \"chore: bump ' + packId + ' to v' + newVersion + '\"');\n \n } catch (error) {\n console.error('Error updating version:', error.message);\n process.exit(1);\n }\n}\n\nupdateVersion();"], ["/BMAD-METHOD/tools/installer/lib/memory-profiler.js", "/**\n * Memory Profiler - Track memory usage during installation\n * Helps identify memory leaks and optimize resource usage\n */\n\nconst v8 = require('v8');\n\nclass MemoryProfiler {\n constructor() {\n this.checkpoints = [];\n this.startTime = Date.now();\n this.peakMemory = 0;\n }\n\n /**\n * Create a memory checkpoint\n * @param {string} label - Label for this checkpoint\n */\n checkpoint(label) {\n const memUsage = process.memoryUsage();\n const heapStats = v8.getHeapStatistics();\n \n const checkpoint = {\n label,\n timestamp: Date.now() - this.startTime,\n memory: {\n rss: this.formatBytes(memUsage.rss),\n heapTotal: this.formatBytes(memUsage.heapTotal),\n heapUsed: this.formatBytes(memUsage.heapUsed),\n external: this.formatBytes(memUsage.external),\n arrayBuffers: this.formatBytes(memUsage.arrayBuffers || 0)\n },\n heap: {\n totalHeapSize: this.formatBytes(heapStats.total_heap_size),\n usedHeapSize: this.formatBytes(heapStats.used_heap_size),\n heapSizeLimit: this.formatBytes(heapStats.heap_size_limit),\n mallocedMemory: this.formatBytes(heapStats.malloced_memory),\n externalMemory: this.formatBytes(heapStats.external_memory)\n },\n raw: {\n heapUsed: memUsage.heapUsed\n }\n };\n\n // Track peak memory\n if (memUsage.heapUsed > this.peakMemory) {\n this.peakMemory = memUsage.heapUsed;\n }\n\n this.checkpoints.push(checkpoint);\n return checkpoint;\n }\n\n /**\n * Force garbage collection (requires --expose-gc flag)\n */\n forceGC() {\n if (global.gc) {\n global.gc();\n return true;\n }\n return false;\n }\n\n /**\n * Get memory usage summary\n */\n getSummary() {\n const currentMemory = process.memoryUsage();\n \n return {\n currentUsage: {\n rss: this.formatBytes(currentMemory.rss),\n heapTotal: this.formatBytes(currentMemory.heapTotal),\n heapUsed: this.formatBytes(currentMemory.heapUsed)\n },\n peakMemory: this.formatBytes(this.peakMemory),\n totalCheckpoints: this.checkpoints.length,\n runTime: `${((Date.now() - this.startTime) / 1000).toFixed(2)}s`\n };\n }\n\n /**\n * Get detailed report of memory usage\n */\n getDetailedReport() {\n const summary = this.getSummary();\n const memoryGrowth = this.calculateMemoryGrowth();\n \n return {\n summary,\n memoryGrowth,\n checkpoints: this.checkpoints,\n recommendations: this.getRecommendations(memoryGrowth)\n };\n }\n\n /**\n * Calculate memory growth between checkpoints\n */\n calculateMemoryGrowth() {\n if (this.checkpoints.length < 2) return [];\n \n const growth = [];\n for (let i = 1; i < this.checkpoints.length; i++) {\n const prev = this.checkpoints[i - 1];\n const curr = this.checkpoints[i];\n \n const heapDiff = curr.raw.heapUsed - prev.raw.heapUsed;\n \n growth.push({\n from: prev.label,\n to: curr.label,\n heapGrowth: this.formatBytes(Math.abs(heapDiff)),\n isIncrease: heapDiff > 0,\n timeDiff: `${((curr.timestamp - prev.timestamp) / 1000).toFixed(2)}s`\n });\n }\n \n return growth;\n }\n\n /**\n * Get recommendations based on memory usage\n */\n getRecommendations(memoryGrowth) {\n const recommendations = [];\n \n // Check for large memory growth\n const largeGrowths = memoryGrowth.filter(g => {\n const bytes = this.parseBytes(g.heapGrowth);\n return bytes > 50 * 1024 * 1024; // 50MB\n });\n \n if (largeGrowths.length > 0) {\n recommendations.push({\n type: 'warning',\n message: `Large memory growth detected in ${largeGrowths.length} operations`,\n details: largeGrowths.map(g => `${g.from} → ${g.to}: ${g.heapGrowth}`)\n });\n }\n \n // Check peak memory\n if (this.peakMemory > 500 * 1024 * 1024) { // 500MB\n recommendations.push({\n type: 'warning',\n message: `High peak memory usage: ${this.formatBytes(this.peakMemory)}`,\n suggestion: 'Consider processing files in smaller batches'\n });\n }\n \n // Check for potential memory leaks\n const continuousGrowth = this.checkContinuousGrowth();\n if (continuousGrowth) {\n recommendations.push({\n type: 'error',\n message: 'Potential memory leak detected',\n details: 'Memory usage continuously increases without significant decreases'\n });\n }\n \n return recommendations;\n }\n\n /**\n * Check for continuous memory growth (potential leak)\n */\n checkContinuousGrowth() {\n if (this.checkpoints.length < 5) return false;\n \n let increasingCount = 0;\n for (let i = 1; i < this.checkpoints.length; i++) {\n if (this.checkpoints[i].raw.heapUsed > this.checkpoints[i - 1].raw.heapUsed) {\n increasingCount++;\n }\n }\n \n // If memory increases in more than 80% of checkpoints, might be a leak\n return increasingCount / (this.checkpoints.length - 1) > 0.8;\n }\n\n /**\n * Format bytes to human-readable string\n */\n formatBytes(bytes) {\n if (bytes === 0) return '0 B';\n \n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n /**\n * Parse human-readable bytes back to number\n */\n parseBytes(str) {\n const match = str.match(/^([\\d.]+)\\s*([KMGT]?B?)$/i);\n if (!match) return 0;\n \n const value = parseFloat(match[1]);\n const unit = match[2].toUpperCase();\n \n const multipliers = {\n 'B': 1,\n 'KB': 1024,\n 'MB': 1024 * 1024,\n 'GB': 1024 * 1024 * 1024\n };\n \n return value * (multipliers[unit] || 1);\n }\n\n /**\n * Clear checkpoints to free memory\n */\n clear() {\n this.checkpoints = [];\n }\n}\n\n// Export singleton instance\nmodule.exports = new MemoryProfiler();"], ["/BMAD-METHOD/tools/bmad-npx-wrapper.js", "#!/usr/bin/env node\n\n/**\n * BMad Method CLI - Direct execution wrapper for npx\n * This file ensures proper execution when run via npx from GitHub\n */\n\nconst { execSync } = require('child_process');\nconst path = require('path');\nconst fs = require('fs');\n\n// Check if we're running in an npx temporary directory\nconst isNpxExecution = __dirname.includes('_npx') || __dirname.includes('.npm');\n\n// If running via npx, we need to handle things differently\nif (isNpxExecution) {\n // The actual bmad.js is in installer/bin/ (relative to tools directory)\n const bmadScriptPath = path.join(__dirname, 'installer', 'bin', 'bmad.js');\n \n // Verify the file exists\n if (!fs.existsSync(bmadScriptPath)) {\n console.error('Error: Could not find bmad.js at', bmadScriptPath);\n console.error('Current directory:', __dirname);\n process.exit(1);\n }\n \n // Execute with proper working directory\n try {\n execSync(`node \"${bmadScriptPath}\" ${process.argv.slice(2).join(' ')}`, {\n stdio: 'inherit',\n cwd: path.dirname(__dirname)\n });\n } catch (error) {\n // execSync will throw if the command exits with non-zero\n // But the stdio is inherited, so the error is already displayed\n process.exit(error.status || 1);\n }\n} else {\n // Local execution - just require the installer directly\n require('./installer/bin/bmad.js');\n}"], ["/BMAD-METHOD/tools/installer/lib/module-manager.js", "/**\n * Module Manager - Centralized dynamic import management\n * Handles loading and caching of ES modules to reduce memory overhead\n */\n\nclass ModuleManager {\n constructor() {\n this._cache = new Map();\n this._loadingPromises = new Map();\n }\n\n /**\n * Initialize all commonly used ES modules at once\n * @returns {Promise} Object containing all loaded modules\n */\n async initializeCommonModules() {\n const modules = await Promise.all([\n this.getModule('chalk'),\n this.getModule('ora'),\n this.getModule('inquirer')\n ]);\n\n return {\n chalk: modules[0],\n ora: modules[1],\n inquirer: modules[2]\n };\n }\n\n /**\n * Get a module by name, with caching\n * @param {string} moduleName - Name of the module to load\n * @returns {Promise} The loaded module\n */\n async getModule(moduleName) {\n // Return from cache if available\n if (this._cache.has(moduleName)) {\n return this._cache.get(moduleName);\n }\n\n // If already loading, return the existing promise\n if (this._loadingPromises.has(moduleName)) {\n return this._loadingPromises.get(moduleName);\n }\n\n // Start loading the module\n const loadPromise = this._loadModule(moduleName);\n this._loadingPromises.set(moduleName, loadPromise);\n\n try {\n const module = await loadPromise;\n this._cache.set(moduleName, module);\n this._loadingPromises.delete(moduleName);\n return module;\n } catch (error) {\n this._loadingPromises.delete(moduleName);\n throw error;\n }\n }\n\n /**\n * Internal method to load a specific module\n * @private\n */\n async _loadModule(moduleName) {\n switch (moduleName) {\n case 'chalk':\n return (await import('chalk')).default;\n case 'ora':\n return (await import('ora')).default;\n case 'inquirer':\n return (await import('inquirer')).default;\n case 'glob':\n return (await import('glob')).glob;\n case 'globSync':\n return (await import('glob')).globSync;\n default:\n throw new Error(`Unknown module: ${moduleName}`);\n }\n }\n\n /**\n * Clear the module cache to free memory\n */\n clearCache() {\n this._cache.clear();\n this._loadingPromises.clear();\n }\n\n /**\n * Get multiple modules at once\n * @param {string[]} moduleNames - Array of module names\n * @returns {Promise} Object with module names as keys\n */\n async getModules(moduleNames) {\n const modules = await Promise.all(\n moduleNames.map(name => this.getModule(name))\n );\n\n return moduleNames.reduce((acc, name, index) => {\n acc[name] = modules[index];\n return acc;\n }, {});\n }\n}\n\n// Singleton instance\nconst moduleManager = new ModuleManager();\n\nmodule.exports = moduleManager;"], ["/BMAD-METHOD/tools/version-bump.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst { execSync } = require('child_process');\nconst path = require('path');\n\n// Dynamic import for ES module\nlet chalk;\n\n// Initialize ES modules\nasync function initializeModules() {\n if (!chalk) {\n chalk = (await import('chalk')).default;\n }\n}\n\n/**\n * Simple version bumping script for BMad-Method\n * Usage: node tools/version-bump.js [patch|minor|major]\n */\n\nfunction getCurrentVersion() {\n const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));\n return packageJson.version;\n}\n\nasync function bumpVersion(type = 'patch') {\n await initializeModules();\n \n const validTypes = ['patch', 'minor', 'major'];\n if (!validTypes.includes(type)) {\n console.error(chalk.red(`Invalid version type: ${type}. Use: ${validTypes.join(', ')}`));\n process.exit(1);\n }\n\n console.log(chalk.yellow('āš ļø Manual version bumping is disabled.'));\n console.log(chalk.blue('šŸ¤– This project uses semantic-release for automated versioning.'));\n console.log('');\n console.log(chalk.bold('To create a new release, use conventional commits:'));\n console.log(chalk.cyan(' feat: new feature (minor version bump)'));\n console.log(chalk.cyan(' fix: bug fix (patch version bump)'));\n console.log(chalk.cyan(' feat!: breaking change (major version bump)'));\n console.log('');\n console.log(chalk.dim('Example: git commit -m \"feat: add new installer features\"'));\n console.log(chalk.dim('Then push to main branch to trigger automatic release.'));\n \n return null;\n}\n\nasync function main() {\n await initializeModules();\n \n const type = process.argv[2] || 'patch';\n const currentVersion = getCurrentVersion();\n \n console.log(chalk.blue(`Current version: ${currentVersion}`));\n \n // Check if working directory is clean\n try {\n execSync('git diff-index --quiet HEAD --');\n } catch (error) {\n console.error(chalk.red('āŒ Working directory is not clean. Commit your changes first.'));\n process.exit(1);\n }\n \n const newVersion = await bumpVersion(type);\n \n console.log(chalk.green(`\\nšŸŽ‰ Version bump complete!`));\n console.log(chalk.blue(`šŸ“¦ ${currentVersion} → ${newVersion}`));\n}\n\nif (require.main === module) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n\nmodule.exports = { bumpVersion, getCurrentVersion };"], ["/BMAD-METHOD/tools/lib/yaml-utils.js", "/**\n * Utility functions for YAML extraction from agent files\n */\n\n/**\n * Extract YAML content from agent markdown files\n * @param {string} agentContent - The full content of the agent file\n * @param {boolean} cleanCommands - Whether to clean command descriptions (default: false)\n * @returns {string|null} - The extracted YAML content or null if not found\n */\nfunction extractYamlFromAgent(agentContent, cleanCommands = false) {\n // Remove carriage returns and match YAML block\n const yamlMatch = agentContent.replace(/\\r/g, \"\").match(/```ya?ml\\n([\\s\\S]*?)\\n```/);\n if (!yamlMatch) return null;\n \n let yamlContent = yamlMatch[1].trim();\n \n // Clean up command descriptions if requested\n // Converts \"- command - description\" to just \"- command\"\n if (cleanCommands) {\n yamlContent = yamlContent.replace(/^(\\s*-)(\\s*\"[^\"]+\")(\\s*-\\s*.*)$/gm, '$1$2');\n }\n \n return yamlContent;\n}\n\nmodule.exports = {\n extractYamlFromAgent\n};"], ["/BMAD-METHOD/tools/sync-installer-version.js", "#!/usr/bin/env node\n\n/**\n * Sync installer package.json version with main package.json\n * Used by semantic-release to keep versions in sync\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\nfunction syncInstallerVersion() {\n // Read main package.json\n const mainPackagePath = path.join(__dirname, '..', 'package.json');\n const mainPackage = JSON.parse(fs.readFileSync(mainPackagePath, 'utf8'));\n \n // Read installer package.json\n const installerPackagePath = path.join(__dirname, 'installer', 'package.json');\n const installerPackage = JSON.parse(fs.readFileSync(installerPackagePath, 'utf8'));\n \n // Update installer version to match main version\n installerPackage.version = mainPackage.version;\n \n // Write back installer package.json\n fs.writeFileSync(installerPackagePath, JSON.stringify(installerPackage, null, 2) + '\\n');\n \n console.log(`Synced installer version to ${mainPackage.version}`);\n}\n\n// Run if called directly\nif (require.main === module) {\n syncInstallerVersion();\n}\n\nmodule.exports = { syncInstallerVersion };"], ["/BMAD-METHOD/tools/semantic-release-sync-installer.js", "/**\n * Semantic-release plugin to sync installer package.json version\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\n// This function runs during the \"prepare\" step of semantic-release\nfunction prepare(_, { nextRelease, logger }) {\n // Define the path to the installer package.json file\n const file = path.join(process.cwd(), 'tools/installer/package.json');\n\n // If the file does not exist, skip syncing and log a message\n if (!fs.existsSync(file)) return logger.log('Installer package.json not found, skipping');\n\n // Read and parse the package.json file\n const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));\n\n // Update the version field with the next release version\n pkg.version = nextRelease.version;\n\n // Write the updated JSON back to the file\n fs.writeFileSync(file, JSON.stringify(pkg, null, 2) + '\\n');\n\n // Log success message\n logger.log(`Synced installer package.json to version ${nextRelease.version}`);\n}\n\n// Export the prepare function so semantic-release can use it\nmodule.exports = { prepare };\n"]], "task_instance_info": {"created_time": "2025-08-20 23:47:31", "created_task_model": "DeepSeek-R1", "class_skeleton": "class\nConfigLoader\n{\nconstructor () {}\nasync load () {}\nasync getInstallationOptions () {}\nasync getAvailableAgents () {}\nasync getAvailableExpansionPacks () {}\nasync getAgentDependencies (agentId) {}\nasync getIdeConfiguration (ide) {}\ngetBmadCorePath () {}\ngetDistPath () {}\ngetAgentPath (agentId) {}\nasync getAvailableTeams () {}\ngetTeamPath (teamId) {}\nasync getTeamDependencies (teamId) {}\n}", "code_description": "This code segment functions to: Manage configuration loading and resource discovery across multiple application components by processing structured data files, resolving dependencies, and providing centralized access to system paths and installation parameters while handling error conditions gracefully."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nclass ConfigLoader {\n constructor() {\n this.bmadCorePath = path.dirname(path.dirname(__dirname));\n this.distPath = path.join(this.bmadCorePath, 'dist');\n this.config = null;\n }\n\n async load() {\n const configPath = path.join(this.bmadCorePath, 'config.yaml');\n const configContent = await fs.readFile(configPath, 'utf8');\n this.config = yaml.load(configContent);\n \n const agentsDir = path.join(this.bmadCorePath, 'agents');\n this.availableAgents = await fs.readdir(agentsDir);\n }\n\n async getInstallationOptions() {\n return this.config.installation;\n }\n\n async getAvailableAgents() {\n return this.availableAgents\n .filter(file => file.endsWith('.yaml'))\n .map(file => file.replace('.yaml', ''));\n }\n\n async getAvailableExpansionPacks() {\n return this.config.expansion_packs;\n }\n\n async getAgentDependencies(agentId) {\n const agentPath = this.getAgentPath(agentId);\n const content = await fs.readFile(agentPath, 'utf8');\n const agentConfig = extractYamlFromAgent(content);\n return agentConfig.dependencies || [];\n }\n\n async getIdeConfiguration(ide) {\n return this.config.ide[ide];\n }\n\n getBmadCorePath() {\n return this.bmadCorePath;\n }\n\n getDistPath() {\n return this.distPath;\n }\n\n getAgentPath(agentId) {\n return path.join(this.bmadCorePath, 'agents', `${agentId}.yaml`);\n }\n\n async getAvailableTeams() {\n const teamsDir = path.join(this.bmadCorePath, 'teams');\n const files = await fs.readdir(teamsDir);\n return files\n .filter(file => file.endsWith('.yaml'))\n .map(file => file.replace('.yaml', ''));\n }\n\n getTeamPath(teamId) {\n return path.join(this.bmadCorePath, 'teams', `${teamId}.yaml`);\n }\n\n async getTeamDependencies(teamId) {\n const teamPath = this.getTeamPath(teamId);\n const content = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(content);\n return teamConfig.dependencies || [];\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-48-04"}, "editdistance_info": {"edit_distance": 15.547, "calculate_time": "2025-08-20 23:48:04", "true_code_clean": "class ConfigLoader {\n constructor() {\n this.configPath = path.join(__dirname, '..', 'config', 'install.config.yaml');\n this.config = null;\n }\n async load() {\n if (this.config) return this.config;\n try {\n const configContent = await fs.readFile(this.configPath, 'utf8');\n this.config = yaml.load(configContent);\n return this.config;\n } catch (error) {\n throw new Error(`Failed to load configuration: ${error.message}`);\n }\n }\n async getInstallationOptions() {\n const config = await this.load();\n return config['installation-options'] || {};\n }\n async getAvailableAgents() {\n const agentsDir = path.join(this.getBmadCorePath(), 'agents');\n try {\n const entries = await fs.readdir(agentsDir, { withFileTypes: true });\n const agents = [];\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.md')) {\n const agentPath = path.join(agentsDir, entry.name);\n const agentId = path.basename(entry.name, '.md');\n try {\n const agentContent = await fs.readFile(agentPath, 'utf8');\n const yamlContentText = extractYamlFromAgent(agentContent);\n if (yamlContentText) {\n const yamlContent = yaml.load(yamlContentText);\n const agentConfig = yamlContent.agent || {};\n agents.push({\n id: agentId,\n name: agentConfig.title || agentConfig.name || agentId,\n file: `bmad-core/agents/${entry.name}`,\n description: agentConfig.whenToUse || 'No description available'\n });\n }\n } catch (error) {\n console.warn(`Failed to read agent ${entry.name}: ${error.message}`);\n }\n }\n }\n agents.sort((a, b) => a.name.localeCompare(b.name));\n return agents;\n } catch (error) {\n console.warn(`Failed to read agents directory: ${error.message}`);\n return [];\n }\n }\n async getAvailableExpansionPacks() {\n const expansionPacksDir = path.join(this.getBmadCorePath(), '..', 'expansion-packs');\n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n const expansionPacks = [];\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n const packPath = path.join(expansionPacksDir, entry.name);\n const configPath = path.join(packPath, 'config.yaml');\n try {\n const configContent = await fs.readFile(configPath, 'utf8');\n const config = yaml.load(configContent);\n expansionPacks.push({\n id: entry.name,\n name: config.name || entry.name,\n description: config['short-title'] || config.description || 'No description available',\n fullDescription: config.description || config['short-title'] || 'No description available',\n version: config.version || '1.0.0',\n author: config.author || 'BMad Team',\n packPath: packPath,\n dependencies: config.dependencies?.agents || []\n });\n } catch (error) {\n console.warn(`Failed to read config for expansion pack ${entry.name}: ${error.message}`);\n const name = entry.name\n .split('-')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n expansionPacks.push({\n id: entry.name,\n name: name,\n description: 'No description available',\n fullDescription: 'No description available',\n version: '1.0.0',\n author: 'BMad Team',\n packPath: packPath,\n dependencies: []\n });\n }\n }\n }\n return expansionPacks;\n } catch (error) {\n console.warn(`Failed to read expansion packs directory: ${error.message}`);\n return [];\n }\n }\n async getAgentDependencies(agentId) {\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n const agentDeps = await resolver.resolveAgentDependencies(agentId);\n const depPaths = [];\n for (const resource of agentDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n return depPaths;\n }\n async getIdeConfiguration(ide) {\n const config = await this.load();\n const ideConfigs = config['ide-configurations'] || {};\n return ideConfigs[ide] || null;\n }\n getBmadCorePath() {\n return path.join(__dirname, '..', '..', '..', 'bmad-core');\n }\n getDistPath() {\n return path.join(__dirname, '..', '..', '..', 'dist');\n }\n getAgentPath(agentId) {\n return path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n }\n async getAvailableTeams() {\n const teamsDir = path.join(this.getBmadCorePath(), 'agent-teams');\n try {\n const entries = await fs.readdir(teamsDir, { withFileTypes: true });\n const teams = [];\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.yaml')) {\n const teamPath = path.join(teamsDir, entry.name);\n try {\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n if (teamConfig.bundle) {\n teams.push({\n id: path.basename(entry.name, '.yaml'),\n name: teamConfig.bundle.name || entry.name,\n description: teamConfig.bundle.description || 'Team configuration',\n icon: teamConfig.bundle.icon || 'šŸ“‹'\n });\n }\n } catch (error) {\n console.warn(`Warning: Could not load team config ${entry.name}: ${error.message}`);\n }\n }\n }\n return teams;\n } catch (error) {\n console.warn(`Warning: Could not scan teams directory: ${error.message}`);\n return [];\n }\n }\n getTeamPath(teamId) {\n return path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n }\n async getTeamDependencies(teamId) {\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n try {\n const teamDeps = await resolver.resolveTeamDependencies(teamId);\n const depPaths = [];\n depPaths.push(`.bmad-core/agent-teams/${teamId}.yaml`);\n for (const agent of teamDeps.agents) {\n const filePath = `.bmad-core/agents/${agent.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n for (const resource of teamDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.${resource.type === 'workflows' ? 'yaml' : 'md'}`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n return depPaths;\n } catch (error) {\n throw new Error(`Failed to resolve team dependencies for ${teamId}: ${error.message}`);\n }\n }\n}", "predict_code_clean": "class ConfigLoader {\n constructor() {\n this.bmadCorePath = path.dirname(path.dirname(__dirname));\n this.distPath = path.join(this.bmadCorePath, 'dist');\n this.config = null;\n }\n async load() {\n const configPath = path.join(this.bmadCorePath, 'config.yaml');\n const configContent = await fs.readFile(configPath, 'utf8');\n this.config = yaml.load(configContent);\n const agentsDir = path.join(this.bmadCorePath, 'agents');\n this.availableAgents = await fs.readdir(agentsDir);\n }\n async getInstallationOptions() {\n return this.config.installation;\n }\n async getAvailableAgents() {\n return this.availableAgents\n .filter(file => file.endsWith('.yaml'))\n .map(file => file.replace('.yaml', ''));\n }\n async getAvailableExpansionPacks() {\n return this.config.expansion_packs;\n }\n async getAgentDependencies(agentId) {\n const agentPath = this.getAgentPath(agentId);\n const content = await fs.readFile(agentPath, 'utf8');\n const agentConfig = extractYamlFromAgent(content);\n return agentConfig.dependencies || [];\n }\n async getIdeConfiguration(ide) {\n return this.config.ide[ide];\n }\n getBmadCorePath() {\n return this.bmadCorePath;\n }\n getDistPath() {\n return this.distPath;\n }\n getAgentPath(agentId) {\n return path.join(this.bmadCorePath, 'agents', `${agentId}.yaml`);\n }\n async getAvailableTeams() {\n const teamsDir = path.join(this.bmadCorePath, 'teams');\n const files = await fs.readdir(teamsDir);\n return files\n .filter(file => file.endsWith('.yaml'))\n .map(file => file.replace('.yaml', ''));\n }\n getTeamPath(teamId) {\n return path.join(this.bmadCorePath, 'teams', `${teamId}.yaml`);\n }\n async getTeamDependencies(teamId) {\n const teamPath = this.getTeamPath(teamId);\n const content = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(content);\n return teamConfig.dependencies || [];\n }\n}"}} {"repo_name": "BMAD-METHOD", "file_name": "/BMAD-METHOD/tools/installer/lib/config-loader.js", "inference_info": {"prefix_code": "const fs = require('fs-extra');\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { extractYamlFromAgent } = require('../../lib/yaml-utils');\n\n", "suffix_code": "\n\nmodule.exports = new ConfigLoader();", "middle_code": "class ConfigLoader {\n constructor() {\n this.configPath = path.join(__dirname, '..', 'config', 'install.config.yaml');\n this.config = null;\n }\n async load() {\n if (this.config) return this.config;\n try {\n const configContent = await fs.readFile(this.configPath, 'utf8');\n this.config = yaml.load(configContent);\n return this.config;\n } catch (error) {\n throw new Error(`Failed to load configuration: ${error.message}`);\n }\n }\n async getInstallationOptions() {\n const config = await this.load();\n return config['installation-options'] || {};\n }\n async getAvailableAgents() {\n const agentsDir = path.join(this.getBmadCorePath(), 'agents');\n try {\n const entries = await fs.readdir(agentsDir, { withFileTypes: true });\n const agents = [];\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.md')) {\n const agentPath = path.join(agentsDir, entry.name);\n const agentId = path.basename(entry.name, '.md');\n try {\n const agentContent = await fs.readFile(agentPath, 'utf8');\n const yamlContentText = extractYamlFromAgent(agentContent);\n if (yamlContentText) {\n const yamlContent = yaml.load(yamlContentText);\n const agentConfig = yamlContent.agent || {};\n agents.push({\n id: agentId,\n name: agentConfig.title || agentConfig.name || agentId,\n file: `bmad-core/agents/${entry.name}`,\n description: agentConfig.whenToUse || 'No description available'\n });\n }\n } catch (error) {\n console.warn(`Failed to read agent ${entry.name}: ${error.message}`);\n }\n }\n }\n agents.sort((a, b) => a.name.localeCompare(b.name));\n return agents;\n } catch (error) {\n console.warn(`Failed to read agents directory: ${error.message}`);\n return [];\n }\n }\n async getAvailableExpansionPacks() {\n const expansionPacksDir = path.join(this.getBmadCorePath(), '..', 'expansion-packs');\n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n const expansionPacks = [];\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n const packPath = path.join(expansionPacksDir, entry.name);\n const configPath = path.join(packPath, 'config.yaml');\n try {\n const configContent = await fs.readFile(configPath, 'utf8');\n const config = yaml.load(configContent);\n expansionPacks.push({\n id: entry.name,\n name: config.name || entry.name,\n description: config['short-title'] || config.description || 'No description available',\n fullDescription: config.description || config['short-title'] || 'No description available',\n version: config.version || '1.0.0',\n author: config.author || 'BMad Team',\n packPath: packPath,\n dependencies: config.dependencies?.agents || []\n });\n } catch (error) {\n console.warn(`Failed to read config for expansion pack ${entry.name}: ${error.message}`);\n const name = entry.name\n .split('-')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n expansionPacks.push({\n id: entry.name,\n name: name,\n description: 'No description available',\n fullDescription: 'No description available',\n version: '1.0.0',\n author: 'BMad Team',\n packPath: packPath,\n dependencies: []\n });\n }\n }\n }\n return expansionPacks;\n } catch (error) {\n console.warn(`Failed to read expansion packs directory: ${error.message}`);\n return [];\n }\n }\n async getAgentDependencies(agentId) {\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n const agentDeps = await resolver.resolveAgentDependencies(agentId);\n const depPaths = [];\n for (const resource of agentDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n return depPaths;\n }\n async getIdeConfiguration(ide) {\n const config = await this.load();\n const ideConfigs = config['ide-configurations'] || {};\n return ideConfigs[ide] || null;\n }\n getBmadCorePath() {\n return path.join(__dirname, '..', '..', '..', 'bmad-core');\n }\n getDistPath() {\n return path.join(__dirname, '..', '..', '..', 'dist');\n }\n getAgentPath(agentId) {\n return path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n }\n async getAvailableTeams() {\n const teamsDir = path.join(this.getBmadCorePath(), 'agent-teams');\n try {\n const entries = await fs.readdir(teamsDir, { withFileTypes: true });\n const teams = [];\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.yaml')) {\n const teamPath = path.join(teamsDir, entry.name);\n try {\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n if (teamConfig.bundle) {\n teams.push({\n id: path.basename(entry.name, '.yaml'),\n name: teamConfig.bundle.name || entry.name,\n description: teamConfig.bundle.description || 'Team configuration',\n icon: teamConfig.bundle.icon || 'šŸ“‹'\n });\n }\n } catch (error) {\n console.warn(`Warning: Could not load team config ${entry.name}: ${error.message}`);\n }\n }\n }\n return teams;\n } catch (error) {\n console.warn(`Warning: Could not scan teams directory: ${error.message}`);\n return [];\n }\n }\n getTeamPath(teamId) {\n return path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n }\n async getTeamDependencies(teamId) {\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n try {\n const teamDeps = await resolver.resolveTeamDependencies(teamId);\n const depPaths = [];\n depPaths.push(`.bmad-core/agent-teams/${teamId}.yaml`);\n for (const agent of teamDeps.agents) {\n const filePath = `.bmad-core/agents/${agent.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n for (const resource of teamDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.${resource.type === 'workflows' ? 'yaml' : 'md'}`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n return depPaths;\n } catch (error) {\n throw new Error(`Failed to resolve team dependencies for ${teamId}: ${error.message}`);\n }\n }\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/BMAD-METHOD/tools/installer/lib/resource-locator.js", "/**\n * Resource Locator - Centralized file path resolution and caching\n * Reduces duplicate file system operations and memory usage\n */\n\nconst path = require('node:path');\nconst fs = require('fs-extra');\nconst moduleManager = require('./module-manager');\n\nclass ResourceLocator {\n constructor() {\n this._pathCache = new Map();\n this._globCache = new Map();\n this._bmadCorePath = null;\n this._expansionPacksPath = null;\n }\n\n /**\n * Get the base path for bmad-core\n */\n getBmadCorePath() {\n if (!this._bmadCorePath) {\n this._bmadCorePath = path.join(__dirname, '../../../bmad-core');\n }\n return this._bmadCorePath;\n }\n\n /**\n * Get the base path for expansion packs\n */\n getExpansionPacksPath() {\n if (!this._expansionPacksPath) {\n this._expansionPacksPath = path.join(__dirname, '../../../expansion-packs');\n }\n return this._expansionPacksPath;\n }\n\n /**\n * Find all files matching a pattern, with caching\n * @param {string} pattern - Glob pattern\n * @param {Object} options - Glob options\n * @returns {Promise} Array of matched file paths\n */\n async findFiles(pattern, options = {}) {\n const cacheKey = `${pattern}:${JSON.stringify(options)}`;\n \n if (this._globCache.has(cacheKey)) {\n return this._globCache.get(cacheKey);\n }\n\n const { glob } = await moduleManager.getModules(['glob']);\n const files = await glob(pattern, options);\n \n // Cache for 5 minutes\n this._globCache.set(cacheKey, files);\n setTimeout(() => this._globCache.delete(cacheKey), 5 * 60 * 1000);\n \n return files;\n }\n\n /**\n * Get agent path with caching\n * @param {string} agentId - Agent identifier\n * @returns {Promise} Path to agent file or null if not found\n */\n async getAgentPath(agentId) {\n const cacheKey = `agent:${agentId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n // Check in bmad-core\n let agentPath = path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n if (await fs.pathExists(agentPath)) {\n this._pathCache.set(cacheKey, agentPath);\n return agentPath;\n }\n\n // Check in expansion packs\n const expansionPacks = await this.getExpansionPacks();\n for (const pack of expansionPacks) {\n agentPath = path.join(pack.path, 'agents', `${agentId}.md`);\n if (await fs.pathExists(agentPath)) {\n this._pathCache.set(cacheKey, agentPath);\n return agentPath;\n }\n }\n\n return null;\n }\n\n /**\n * Get available agents with metadata\n * @returns {Promise} Array of agent objects\n */\n async getAvailableAgents() {\n const cacheKey = 'all-agents';\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const agents = [];\n const yaml = require('js-yaml');\n const { extractYamlFromAgent } = require('../../lib/yaml-utils');\n\n // Get agents from bmad-core\n const coreAgents = await this.findFiles('agents/*.md', {\n cwd: this.getBmadCorePath()\n });\n\n for (const agentFile of coreAgents) {\n const content = await fs.readFile(\n path.join(this.getBmadCorePath(), agentFile),\n 'utf8'\n );\n const yamlContent = extractYamlFromAgent(content);\n if (yamlContent) {\n try {\n const metadata = yaml.load(yamlContent);\n agents.push({\n id: path.basename(agentFile, '.md'),\n name: metadata.agent_name || path.basename(agentFile, '.md'),\n description: metadata.description || 'No description available',\n source: 'core'\n });\n } catch (e) {\n // Skip invalid agents\n }\n }\n }\n\n // Cache for 10 minutes\n this._pathCache.set(cacheKey, agents);\n setTimeout(() => this._pathCache.delete(cacheKey), 10 * 60 * 1000);\n\n return agents;\n }\n\n /**\n * Get available expansion packs\n * @returns {Promise} Array of expansion pack objects\n */\n async getExpansionPacks() {\n const cacheKey = 'expansion-packs';\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const packs = [];\n const expansionPacksPath = this.getExpansionPacksPath();\n\n if (await fs.pathExists(expansionPacksPath)) {\n const entries = await fs.readdir(expansionPacksPath, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory()) {\n const configPath = path.join(expansionPacksPath, entry.name, 'config.yaml');\n if (await fs.pathExists(configPath)) {\n try {\n const yaml = require('js-yaml');\n const config = yaml.load(await fs.readFile(configPath, 'utf8'));\n packs.push({\n id: entry.name,\n name: config.name || entry.name,\n version: config.version || '1.0.0',\n description: config.description || 'No description available',\n shortTitle: config['short-title'] || config.description || 'No description available',\n author: config.author || 'Unknown',\n path: path.join(expansionPacksPath, entry.name)\n });\n } catch (e) {\n // Skip invalid packs\n }\n }\n }\n }\n }\n\n // Cache for 10 minutes\n this._pathCache.set(cacheKey, packs);\n setTimeout(() => this._pathCache.delete(cacheKey), 10 * 60 * 1000);\n\n return packs;\n }\n\n /**\n * Get team configuration\n * @param {string} teamId - Team identifier\n * @returns {Promise} Team configuration or null\n */\n async getTeamConfig(teamId) {\n const cacheKey = `team:${teamId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const teamPath = path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n \n if (await fs.pathExists(teamPath)) {\n try {\n const yaml = require('js-yaml');\n const content = await fs.readFile(teamPath, 'utf8');\n const config = yaml.load(content);\n this._pathCache.set(cacheKey, config);\n return config;\n } catch (e) {\n return null;\n }\n }\n\n return null;\n }\n\n /**\n * Get resource dependencies for an agent\n * @param {string} agentId - Agent identifier\n * @returns {Promise} Dependencies object\n */\n async getAgentDependencies(agentId) {\n const cacheKey = `deps:${agentId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const agentPath = await this.getAgentPath(agentId);\n if (!agentPath) {\n return { all: [], byType: {} };\n }\n\n const content = await fs.readFile(agentPath, 'utf8');\n const { extractYamlFromAgent } = require('../../lib/yaml-utils');\n const yamlContent = extractYamlFromAgent(content);\n\n if (!yamlContent) {\n return { all: [], byType: {} };\n }\n\n try {\n const yaml = require('js-yaml');\n const metadata = yaml.load(yamlContent);\n const dependencies = metadata.dependencies || {};\n \n // Flatten dependencies\n const allDeps = [];\n const byType = {};\n \n for (const [type, deps] of Object.entries(dependencies)) {\n if (Array.isArray(deps)) {\n byType[type] = deps;\n for (const dep of deps) {\n allDeps.push(`.bmad-core/${type}/${dep}`);\n }\n }\n }\n\n const result = { all: allDeps, byType };\n this._pathCache.set(cacheKey, result);\n return result;\n } catch (e) {\n return { all: [], byType: {} };\n }\n }\n\n /**\n * Clear all caches to free memory\n */\n clearCache() {\n this._pathCache.clear();\n this._globCache.clear();\n }\n\n /**\n * Get IDE configuration\n * @param {string} ideId - IDE identifier\n * @returns {Promise} IDE configuration or null\n */\n async getIdeConfig(ideId) {\n const cacheKey = `ide:${ideId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const idePath = path.join(this.getBmadCorePath(), 'ide-rules', `${ideId}.yaml`);\n \n if (await fs.pathExists(idePath)) {\n try {\n const yaml = require('js-yaml');\n const content = await fs.readFile(idePath, 'utf8');\n const config = yaml.load(content);\n this._pathCache.set(cacheKey, config);\n return config;\n } catch (e) {\n return null;\n }\n }\n\n return null;\n }\n}\n\n// Singleton instance\nconst resourceLocator = new ResourceLocator();\n\nmodule.exports = resourceLocator;"], ["/BMAD-METHOD/tools/installer/lib/installer.js", "const path = require(\"node:path\");\nconst fs = require(\"fs-extra\");\nconst chalk = require(\"chalk\");\nconst ora = require(\"ora\");\nconst inquirer = require(\"inquirer\");\nconst fileManager = require(\"./file-manager\");\nconst configLoader = require(\"./config-loader\");\nconst ideSetup = require(\"./ide-setup\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\nconst resourceLocator = require(\"./resource-locator\");\n\nclass Installer {\n async getCoreVersion() {\n try {\n // Always use package.json version\n const packagePath = path.join(__dirname, '..', '..', '..', 'package.json');\n const packageJson = require(packagePath);\n return packageJson.version;\n } catch (error) {\n console.warn(\"Could not read version from package.json, using 'unknown'\");\n return \"unknown\";\n }\n }\n\n async install(config) {\n const spinner = ora(\"Analyzing installation directory...\").start();\n \n try {\n // Store the original CWD where npx was executed\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n \n // Resolve installation directory relative to where the user ran the command\n let installDir = path.isAbsolute(config.directory) \n ? config.directory \n : path.resolve(originalCwd, config.directory);\n \n if (path.basename(installDir) === '.bmad-core') {\n // If user points directly to .bmad-core, treat its parent as the project root\n installDir = path.dirname(installDir);\n }\n \n // Log resolved path for clarity\n if (!path.isAbsolute(config.directory)) {\n spinner.text = `Resolving \"${config.directory}\" to: ${installDir}`;\n }\n\n // Check if directory exists and handle non-existent directories\n if (!(await fileManager.pathExists(installDir))) {\n spinner.stop();\n console.log(`\\nThe directory ${installDir} does not exist.`);\n \n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n {\n name: 'Create the directory and continue',\n value: 'create'\n },\n {\n name: 'Choose a different directory',\n value: 'change'\n },\n {\n name: 'Cancel installation',\n value: 'cancel'\n }\n ]\n }\n ]);\n\n if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n } else if (action === 'change') {\n const { newDirectory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'newDirectory',\n message: 'Enter the new directory path:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid directory path';\n }\n return true;\n }\n }\n ]);\n // Preserve the original CWD for the recursive call\n config.directory = newDirectory;\n return await this.install(config); // Recursive call with new directory\n } else if (action === 'create') {\n try {\n await fileManager.ensureDirectory(installDir);\n console.log(`āœ“ Created directory: ${installDir}`);\n } catch (error) {\n console.error(`Failed to create directory: ${error.message}`);\n console.error('You may need to check permissions or use a different path.');\n process.exit(1);\n }\n }\n \n spinner.start(\"Analyzing installation directory...\");\n }\n\n // If this is an update request from early detection, handle it directly\n if (config.installType === 'update') {\n const state = await this.detectInstallationState(installDir);\n if (state.type === 'v4_existing') {\n return await this.performUpdate(config, installDir, state.manifest, spinner);\n } else {\n spinner.fail('No existing v4 installation found to update');\n throw new Error('No existing v4 installation found');\n }\n }\n\n // Detect current state\n const state = await this.detectInstallationState(installDir);\n\n // Handle different states\n switch (state.type) {\n case \"clean\":\n return await this.performFreshInstall(config, installDir, spinner);\n\n case \"v4_existing\":\n return await this.handleExistingV4Installation(\n config,\n installDir,\n state,\n spinner\n );\n\n case \"v3_existing\":\n return await this.handleV3Installation(\n config,\n installDir,\n state,\n spinner\n );\n\n case \"unknown_existing\":\n return await this.handleUnknownInstallation(\n config,\n installDir,\n state,\n spinner\n );\n }\n } catch (error) {\n // Check if modules were initialized\n if (spinner) {\n spinner.fail(\"Installation failed\");\n } else {\n console.error(\"Installation failed:\", error.message);\n }\n throw error;\n }\n }\n\n async detectInstallationState(installDir) {\n const state = {\n type: \"clean\",\n hasV4Manifest: false,\n hasV3Structure: false,\n hasBmadCore: false,\n hasOtherFiles: false,\n manifest: null,\n expansionPacks: {},\n };\n\n // Check if directory exists\n if (!(await fileManager.pathExists(installDir))) {\n return state; // clean install\n }\n\n // Check for V4 installation (has .bmad-core with manifest)\n const bmadCorePath = path.join(installDir, \".bmad-core\");\n const manifestPath = path.join(bmadCorePath, \"install-manifest.yaml\");\n\n if (await fileManager.pathExists(manifestPath)) {\n state.type = \"v4_existing\";\n state.hasV4Manifest = true;\n state.hasBmadCore = true;\n state.manifest = await fileManager.readManifest(installDir);\n return state;\n }\n\n // Check for V3 installation (has bmad-agent directory)\n const bmadAgentPath = path.join(installDir, \"bmad-agent\");\n if (await fileManager.pathExists(bmadAgentPath)) {\n state.type = \"v3_existing\";\n state.hasV3Structure = true;\n return state;\n }\n\n // Check for .bmad-core without manifest (broken V4 or manual copy)\n if (await fileManager.pathExists(bmadCorePath)) {\n state.type = \"unknown_existing\";\n state.hasBmadCore = true;\n return state;\n }\n\n // Check if directory has other files\n const files = await resourceLocator.findFiles(\"**/*\", {\n cwd: installDir,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n\n if (files.length > 0) {\n // Directory has other files, but no BMad installation.\n // Treat as clean install but record that it isn't empty.\n state.hasOtherFiles = true;\n }\n\n // Check for expansion packs (folders starting with .)\n const expansionPacks = await this.detectExpansionPacks(installDir);\n state.expansionPacks = expansionPacks;\n\n return state; // clean install\n }\n\n async performFreshInstall(config, installDir, spinner, options = {}) {\n spinner.text = \"Installing BMad Method...\";\n\n let files = [];\n\n if (config.installType === \"full\") {\n // Full installation - copy entire .bmad-core folder as a subdirectory\n spinner.text = \"Copying complete .bmad-core folder...\";\n const sourceDir = resourceLocator.getBmadCorePath();\n const bmadCoreDestDir = path.join(installDir, \".bmad-core\");\n await fileManager.copyDirectoryWithRootReplacement(sourceDir, bmadCoreDestDir, \".bmad-core\");\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n\n // Get list of all files for manifest\n const foundFiles = await resourceLocator.findFiles(\"**/*\", {\n cwd: bmadCoreDestDir,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n files = foundFiles.map((file) => path.join(\".bmad-core\", file));\n } else if (config.installType === \"single-agent\") {\n // Single agent installation\n spinner.text = `Installing ${config.agent} agent...`;\n\n // Copy agent file with {root} replacement\n const agentPath = configLoader.getAgentPath(config.agent);\n const destAgentPath = path.join(\n installDir,\n \".bmad-core\",\n \"agents\",\n `${config.agent}.md`\n );\n await fileManager.copyFileWithRootReplacement(agentPath, destAgentPath, \".bmad-core\");\n files.push(`.bmad-core/agents/${config.agent}.md`);\n\n // Copy dependencies\n const { all: dependencies } = await resourceLocator.getAgentDependencies(\n config.agent\n );\n const sourceBase = resourceLocator.getBmadCorePath();\n\n for (const dep of dependencies) {\n spinner.text = `Copying dependency: ${dep}`;\n\n if (dep.includes(\"*\")) {\n // Handle glob patterns with {root} replacement\n const copiedFiles = await fileManager.copyGlobPattern(\n dep.replace(\".bmad-core/\", \"\"),\n sourceBase,\n path.join(installDir, \".bmad-core\"),\n \".bmad-core\"\n );\n files.push(...copiedFiles.map(f => `.bmad-core/${f}`));\n } else {\n // Handle single files with {root} replacement if needed\n const sourcePath = path.join(\n sourceBase,\n dep.replace(\".bmad-core/\", \"\")\n );\n const destPath = path.join(\n installDir,\n dep\n );\n\n const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, \".bmad-core\");\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n files.push(dep);\n }\n }\n }\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n const commonFiles = await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n files.push(...commonFiles);\n } else if (config.installType === \"team\") {\n // Team installation\n spinner.text = `Installing ${config.team} team...`;\n \n // Get team dependencies\n const teamDependencies = await configLoader.getTeamDependencies(config.team);\n const sourceBase = resourceLocator.getBmadCorePath();\n \n // Install all team dependencies\n for (const dep of teamDependencies) {\n spinner.text = `Copying team dependency: ${dep}`;\n \n if (dep.includes(\"*\")) {\n // Handle glob patterns with {root} replacement\n const copiedFiles = await fileManager.copyGlobPattern(\n dep.replace(\".bmad-core/\", \"\"),\n sourceBase,\n path.join(installDir, \".bmad-core\"),\n \".bmad-core\"\n );\n files.push(...copiedFiles.map(f => `.bmad-core/${f}`));\n } else {\n // Handle single files with {root} replacement if needed\n const sourcePath = path.join(sourceBase, dep.replace(\".bmad-core/\", \"\"));\n const destPath = path.join(installDir, dep);\n \n const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, \".bmad-core\");\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n files.push(dep);\n }\n }\n }\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n const commonFiles = await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n files.push(...commonFiles);\n } else if (config.installType === \"expansion-only\") {\n // Expansion-only installation - DO NOT create .bmad-core\n // Only install expansion packs\n spinner.text = \"Installing expansion packs only...\";\n }\n\n // Install expansion packs if requested\n const expansionFiles = await this.installExpansionPacks(installDir, config.expansionPacks, spinner, config);\n files.push(...expansionFiles);\n\n // Install web bundles if requested\n if (config.includeWebBundles && config.webBundlesDirectory) {\n spinner.text = \"Installing web bundles...\";\n // Resolve web bundles directory using the same logic as the main installation directory\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n let resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory) \n ? config.webBundlesDirectory \n : path.resolve(originalCwd, config.webBundlesDirectory);\n await this.installWebBundles(resolvedWebBundlesDir, config, spinner);\n }\n\n // Set up IDE integration if requested\n const ides = config.ides || (config.ide ? [config.ide] : []);\n if (ides.length > 0) {\n for (const ide of ides) {\n spinner.text = `Setting up ${ide} integration...`;\n const preConfiguredSettings = ide === 'github-copilot' ? config.githubCopilotConfig : null;\n await ideSetup.setup(ide, installDir, config.agent, spinner, preConfiguredSettings);\n }\n }\n\n // Modify core-config.yaml if sharding preferences were provided\n if (config.installType !== \"expansion-only\" && (config.prdSharded !== undefined || config.architectureSharded !== undefined)) {\n spinner.text = \"Configuring document sharding settings...\";\n await fileManager.modifyCoreConfig(installDir, config);\n }\n\n // Create manifest (skip for expansion-only installations)\n if (config.installType !== \"expansion-only\") {\n spinner.text = \"Creating installation manifest...\";\n await fileManager.createManifest(installDir, config, files);\n }\n\n spinner.succeed(\"Installation complete!\");\n this.showSuccessMessage(config, installDir, options);\n }\n\n async handleExistingV4Installation(config, installDir, state, spinner) {\n spinner.stop();\n\n const currentVersion = state.manifest.version;\n const newVersion = await this.getCoreVersion();\n const versionCompare = this.compareVersions(currentVersion, newVersion);\n\n console.log(chalk.yellow(\"\\nšŸ” Found existing BMad v4 installation\"));\n console.log(` Directory: ${installDir}`);\n console.log(` Current version: ${currentVersion}`);\n console.log(` Available version: ${newVersion}`);\n console.log(\n ` Installed: ${new Date(\n state.manifest.installed_at\n ).toLocaleDateString()}`\n );\n\n // Check file integrity\n spinner.start(\"Checking installation integrity...\");\n const integrity = await fileManager.checkFileIntegrity(installDir, state.manifest);\n spinner.stop();\n \n const hasMissingFiles = integrity.missing.length > 0;\n const hasModifiedFiles = integrity.modified.length > 0;\n const hasIntegrityIssues = hasMissingFiles || hasModifiedFiles;\n \n if (hasIntegrityIssues) {\n console.log(chalk.red(\"\\nāš ļø Installation issues detected:\"));\n if (hasMissingFiles) {\n console.log(chalk.red(` Missing files: ${integrity.missing.length}`));\n if (integrity.missing.length <= 5) {\n integrity.missing.forEach(file => console.log(chalk.dim(` - ${file}`)));\n }\n }\n if (hasModifiedFiles) {\n console.log(chalk.yellow(` Modified files: ${integrity.modified.length}`));\n if (integrity.modified.length <= 5) {\n integrity.modified.forEach(file => console.log(chalk.dim(` - ${file}`)));\n }\n }\n }\n\n // Show existing expansion packs\n if (Object.keys(state.expansionPacks).length > 0) {\n console.log(chalk.cyan(\"\\nšŸ“¦ Installed expansion packs:\"));\n for (const [packId, packInfo] of Object.entries(state.expansionPacks)) {\n if (packInfo.hasManifest && packInfo.manifest) {\n console.log(` - ${packId} (v${packInfo.manifest.version || 'unknown'})`);\n } else {\n console.log(` - ${packId} (no manifest)`);\n }\n }\n }\n\n let choices = [];\n \n if (versionCompare < 0) {\n console.log(chalk.cyan(\"\\nā¬†ļø Upgrade available for BMad core\"));\n choices.push({ name: `Upgrade BMad core (v${currentVersion} → v${newVersion})`, value: \"upgrade\" });\n } else if (versionCompare === 0) {\n if (hasIntegrityIssues) {\n // Offer repair option when files are missing or modified\n choices.push({ \n name: \"Repair installation (restore missing/modified files)\", \n value: \"repair\" \n });\n }\n console.log(chalk.yellow(\"\\nāš ļø Same version already installed\"));\n choices.push({ name: `Force reinstall BMad core (v${currentVersion} - reinstall)`, value: \"reinstall\" });\n } else {\n console.log(chalk.yellow(\"\\nā¬‡ļø Installed version is newer than available\"));\n choices.push({ name: `Downgrade BMad core (v${currentVersion} → v${newVersion})`, value: \"reinstall\" });\n }\n \n choices.push(\n { name: \"Add/update expansion packs only\", value: \"expansions\" },\n { name: \"Cancel\", value: \"cancel\" }\n );\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: choices,\n },\n ]);\n\n switch (action) {\n case \"upgrade\":\n return await this.performUpdate(config, installDir, state.manifest, spinner);\n case \"repair\":\n // For repair, restore missing/modified files while backing up modified ones\n return await this.performRepair(config, installDir, state.manifest, integrity, spinner);\n case \"reinstall\":\n // For reinstall, don't check for modifications - just overwrite\n return await this.performReinstall(config, installDir, spinner);\n case \"expansions\":\n // Ask which expansion packs to install\n const availableExpansionPacks = await resourceLocator.getExpansionPacks();\n \n if (availableExpansionPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs available.\"));\n return;\n }\n \n const { selectedPacks } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedPacks',\n message: 'Select expansion packs to install/update:',\n choices: availableExpansionPacks.map(pack => ({\n name: `${pack.name} (v${pack.version}) .${pack.id}`,\n value: pack.id,\n checked: state.expansionPacks[pack.id] !== undefined\n }))\n }\n ]);\n \n if (selectedPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs selected.\"));\n return;\n }\n \n spinner.start(\"Installing expansion packs...\");\n const expansionFiles = await this.installExpansionPacks(installDir, selectedPacks, spinner, { ides: config.ides || [] });\n spinner.succeed(\"Expansion packs installed successfully!\");\n \n console.log(chalk.green(\"\\nāœ“ Installation complete!\"));\n console.log(chalk.green(`āœ“ Expansion packs installed/updated:`));\n for (const packId of selectedPacks) {\n console.log(chalk.green(` - ${packId} → .${packId}/`));\n }\n return;\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async handleV3Installation(config, installDir, state, spinner) {\n spinner.stop();\n\n console.log(\n chalk.yellow(\"\\nšŸ” Found BMad v3 installation (bmad-agent/ directory)\")\n );\n console.log(` Directory: ${installDir}`);\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: [\n { name: \"Upgrade from v3 to v4 (recommended)\", value: \"upgrade\" },\n { name: \"Install v4 alongside v3\", value: \"alongside\" },\n { name: \"Cancel\", value: \"cancel\" },\n ],\n },\n ]);\n\n switch (action) {\n case \"upgrade\": {\n console.log(chalk.cyan(\"\\nšŸ“¦ Starting v3 to v4 upgrade process...\"));\n const V3ToV4Upgrader = require(\"../../upgraders/v3-to-v4-upgrader\");\n const upgrader = new V3ToV4Upgrader();\n return await upgrader.upgrade({ \n projectPath: installDir,\n ides: config.ides || [] // Pass IDE selections from initial config\n });\n }\n case \"alongside\":\n return await this.performFreshInstall(config, installDir, spinner);\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async handleUnknownInstallation(config, installDir, state, spinner) {\n spinner.stop();\n\n console.log(chalk.yellow(\"\\nāš ļø Directory contains existing files\"));\n console.log(` Directory: ${installDir}`);\n\n if (state.hasBmadCore) {\n console.log(\" Found: .bmad-core directory (but no manifest)\");\n }\n if (state.hasOtherFiles) {\n console.log(\" Found: Other files in directory\");\n }\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: [\n { name: \"Install anyway (may overwrite files)\", value: \"force\" },\n { name: \"Choose different directory\", value: \"different\" },\n { name: \"Cancel\", value: \"cancel\" },\n ],\n },\n ]);\n\n switch (action) {\n case \"force\":\n return await this.performFreshInstall(config, installDir, spinner);\n case \"different\": {\n const { newDir } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"newDir\",\n message: \"Enter new installation directory:\",\n default: path.join(path.dirname(installDir), \"bmad-project\"),\n },\n ]);\n config.directory = newDir;\n return await this.install(config);\n }\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async performUpdate(newConfig, installDir, manifest, spinner) {\n spinner.start(\"Checking for updates...\");\n\n try {\n // Get current and new versions\n const currentVersion = manifest.version;\n const newVersion = await this.getCoreVersion();\n const versionCompare = this.compareVersions(currentVersion, newVersion);\n \n // Only check for modified files if it's an actual version upgrade\n let modifiedFiles = [];\n if (versionCompare !== 0) {\n spinner.text = \"Checking for modified files...\";\n modifiedFiles = await fileManager.checkModifiedFiles(\n installDir,\n manifest\n );\n }\n\n if (modifiedFiles.length > 0) {\n spinner.warn(\"Found modified files\");\n console.log(chalk.yellow(\"\\nThe following files have been modified:\"));\n for (const file of modifiedFiles) {\n console.log(` - ${file}`);\n }\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"How would you like to proceed?\",\n choices: [\n { name: \"Backup and overwrite modified files\", value: \"backup\" },\n { name: \"Skip modified files\", value: \"skip\" },\n { name: \"Cancel update\", value: \"cancel\" },\n ],\n },\n ]);\n\n if (action === \"cancel\") {\n console.log(\"Update cancelled.\");\n return;\n }\n\n if (action === \"backup\") {\n spinner.start(\"Backing up modified files...\");\n for (const file of modifiedFiles) {\n const filePath = path.join(installDir, file);\n const backupPath = await fileManager.backupFile(filePath);\n console.log(\n chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`)\n );\n }\n }\n }\n\n // Perform update by re-running installation\n spinner.text = versionCompare === 0 ? \"Reinstalling files...\" : \"Updating files...\";\n const config = {\n installType: manifest.install_type,\n agent: manifest.agent,\n directory: installDir,\n ides: newConfig?.ides || manifest.ides_setup || [],\n };\n\n await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n } catch (error) {\n spinner.fail(\"Update failed\");\n throw error;\n }\n }\n\n async performRepair(config, installDir, manifest, integrity, spinner) {\n spinner.start(\"Preparing to repair installation...\");\n\n try {\n // Back up modified files\n if (integrity.modified.length > 0) {\n spinner.text = \"Backing up modified files...\";\n for (const file of integrity.modified) {\n const filePath = path.join(installDir, file);\n if (await fileManager.pathExists(filePath)) {\n const backupPath = await fileManager.backupFile(filePath);\n console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));\n }\n }\n }\n\n // Restore missing and modified files\n spinner.text = \"Restoring files...\";\n const sourceBase = resourceLocator.getBmadCorePath();\n const filesToRestore = [...integrity.missing, ...integrity.modified];\n \n for (const file of filesToRestore) {\n // Skip the manifest file itself\n if (file.endsWith('install-manifest.yaml')) continue;\n \n const relativePath = file.replace('.bmad-core/', '');\n const destPath = path.join(installDir, file);\n \n // Check if this is a common/ file that needs special processing\n const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));\n const commonSourcePath = path.join(commonBase, 'common', relativePath);\n \n if (await fileManager.pathExists(commonSourcePath)) {\n // This is a common/ file - needs template processing\n const fs = require('fs').promises;\n const content = await fs.readFile(commonSourcePath, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, '.bmad-core');\n await fileManager.ensureDirectory(path.dirname(destPath));\n await fs.writeFile(destPath, updatedContent, 'utf8');\n spinner.text = `Restored: ${file}`;\n } else {\n // Regular file from bmad-core\n const sourcePath = path.join(sourceBase, relativePath);\n if (await fileManager.pathExists(sourcePath)) {\n await fileManager.copyFile(sourcePath, destPath);\n spinner.text = `Restored: ${file}`;\n \n // If this is a .yaml file, check for and remove corresponding .yml file\n if (file.endsWith('.yaml')) {\n const ymlFile = file.replace(/\\.yaml$/, '.yml');\n const ymlPath = path.join(installDir, ymlFile);\n if (await fileManager.pathExists(ymlPath)) {\n const fs = require('fs').promises;\n await fs.unlink(ymlPath);\n console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${file})`));\n }\n }\n } else {\n console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));\n }\n }\n }\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n \n spinner.succeed(\"Repair completed successfully!\");\n \n // Show summary\n console.log(chalk.green(\"\\nāœ“ Installation repaired!\"));\n if (integrity.missing.length > 0) {\n console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));\n }\n if (integrity.modified.length > 0) {\n console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));\n }\n \n // Warning for Cursor custom modes if agents were repaired\n const ides = manifest.ides_setup || [];\n if (ides.includes('cursor')) {\n console.log(chalk.yellow.bold(\"\\nāš ļø IMPORTANT: Cursor Custom Modes Update Required\"));\n console.log(chalk.yellow(\"Since agent files have been repaired, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs.\"));\n }\n \n } catch (error) {\n spinner.fail(\"Repair failed\");\n throw error;\n }\n }\n\n async performReinstall(config, installDir, spinner) {\n spinner.start(\"Preparing to reinstall BMad Method...\");\n\n // Remove existing .bmad-core\n const bmadCorePath = path.join(installDir, \".bmad-core\");\n if (await fileManager.pathExists(bmadCorePath)) {\n spinner.text = \"Removing existing installation...\";\n await fileManager.removeDirectory(bmadCorePath);\n }\n \n spinner.text = \"Installing fresh copy...\";\n const result = await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n \n return result;\n }\n\n showSuccessMessage(config, installDir, options = {}) {\n console.log(chalk.green(\"\\nāœ“ BMad Method installed successfully!\\n\"));\n\n const ides = config.ides || (config.ide ? [config.ide] : []);\n if (ides.length > 0) {\n for (const ide of ides) {\n const ideConfig = configLoader.getIdeConfiguration(ide);\n if (ideConfig?.instructions) {\n console.log(\n chalk.bold(`To use BMad agents in ${ideConfig.name}:`)\n );\n console.log(ideConfig.instructions);\n }\n }\n } else {\n console.log(chalk.yellow(\"No IDE configuration was set up.\"));\n console.log(\n \"You can manually configure your IDE using the agent files in:\",\n installDir\n );\n }\n\n // Information about installation components\n console.log(chalk.bold(\"\\nšŸŽÆ Installation Summary:\"));\n if (config.installType !== \"expansion-only\") {\n console.log(chalk.green(\"āœ“ .bmad-core framework installed with all agents and workflows\"));\n }\n \n if (config.expansionPacks && config.expansionPacks.length > 0) {\n console.log(chalk.green(`āœ“ Expansion packs installed:`));\n for (const packId of config.expansionPacks) {\n console.log(chalk.green(` - ${packId} → .${packId}/`));\n }\n }\n \n if (config.includeWebBundles && config.webBundlesDirectory) {\n const bundleInfo = this.getWebBundleInfo(config);\n // Resolve the web bundles directory for display\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n const resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory) \n ? config.webBundlesDirectory \n : path.resolve(originalCwd, config.webBundlesDirectory);\n console.log(chalk.green(`āœ“ Web bundles (${bundleInfo}) installed to: ${resolvedWebBundlesDir}`));\n }\n \n if (ides.length > 0) {\n const ideNames = ides.map(ide => {\n const ideConfig = configLoader.getIdeConfiguration(ide);\n return ideConfig?.name || ide;\n }).join(\", \");\n console.log(chalk.green(`āœ“ IDE rules and configurations set up for: ${ideNames}`));\n }\n\n // Information about web bundles\n if (!config.includeWebBundles) {\n console.log(chalk.bold(\"\\nšŸ“¦ Web Bundles Available:\"));\n console.log(\"Pre-built web bundles are available and can be added later:\");\n console.log(chalk.cyan(\" Run the installer again to add them to your project\"));\n console.log(\"These bundles work independently and can be shared, moved, or used\");\n console.log(\"in other projects as standalone files.\");\n }\n\n if (config.installType === \"single-agent\") {\n console.log(\n chalk.dim(\n \"\\nNeed other agents? Run: npx bmad-method install --agent=\"\n )\n );\n console.log(\n chalk.dim(\"Need everything? Run: npx bmad-method install --full\")\n );\n }\n\n // Warning for Cursor custom modes if agents were updated\n if (options.isUpdate && ides.includes('cursor')) {\n console.log(chalk.yellow.bold(\"\\nāš ļø IMPORTANT: Cursor Custom Modes Update Required\"));\n console.log(chalk.yellow(\"Since agents have been updated, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs.\"));\n }\n\n // Important notice to read the user guide\n console.log(chalk.red.bold(\"\\nšŸ“– IMPORTANT: Please read the user guide installed at .bmad-core/user-guide.md\"));\n console.log(chalk.red(\"This guide contains essential information about the BMad workflow and how to use the agents effectively.\"));\n }\n\n // Legacy method for backward compatibility\n async update() {\n console.log(chalk.yellow('The \"update\" command is deprecated.'));\n console.log(\n 'Please use \"install\" instead - it will detect and offer to update existing installations.'\n );\n\n const installDir = await this.findInstallation();\n if (installDir) {\n const config = {\n installType: \"full\",\n directory: path.dirname(installDir),\n ide: null,\n };\n return await this.install(config);\n }\n console.log(chalk.red(\"No BMad installation found.\"));\n }\n\n async listAgents() {\n const agents = await resourceLocator.getAvailableAgents();\n\n console.log(chalk.bold(\"\\nAvailable BMad Agents:\\n\"));\n\n for (const agent of agents) {\n console.log(chalk.cyan(` ${agent.id.padEnd(20)}`), agent.description);\n }\n\n console.log(\n chalk.dim(\"\\nInstall with: npx bmad-method install --agent=\\n\")\n );\n }\n\n async listExpansionPacks() {\n const expansionPacks = await resourceLocator.getExpansionPacks();\n\n console.log(chalk.bold(\"\\nAvailable BMad Expansion Packs:\\n\"));\n\n if (expansionPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs found.\"));\n return;\n }\n\n for (const pack of expansionPacks) {\n console.log(chalk.cyan(` ${pack.id.padEnd(20)}`), \n `${pack.name} v${pack.version}`);\n console.log(chalk.dim(` ${' '.repeat(22)}${pack.description}`));\n if (pack.author && pack.author !== 'Unknown') {\n console.log(chalk.dim(` ${' '.repeat(22)}by ${pack.author}`));\n }\n console.log();\n }\n\n console.log(\n chalk.dim(\"Install with: npx bmad-method install --full --expansion-packs \\n\")\n );\n }\n\n async showStatus() {\n const installDir = await this.findInstallation();\n\n if (!installDir) {\n console.log(\n chalk.yellow(\"No BMad installation found in current directory tree\")\n );\n return;\n }\n\n const manifest = await fileManager.readManifest(installDir);\n\n if (!manifest) {\n console.log(chalk.red(\"Invalid installation - manifest not found\"));\n return;\n }\n\n console.log(chalk.bold(\"\\nBMad Installation Status:\\n\"));\n console.log(` Directory: ${installDir}`);\n console.log(` Version: ${manifest.version}`);\n console.log(\n ` Installed: ${new Date(\n manifest.installed_at\n ).toLocaleDateString()}`\n );\n console.log(` Type: ${manifest.install_type}`);\n\n if (manifest.agent) {\n console.log(` Agent: ${manifest.agent}`);\n }\n\n if (manifest.ides_setup && manifest.ides_setup.length > 0) {\n console.log(` IDE Setup: ${manifest.ides_setup.join(', ')}`);\n }\n\n console.log(` Total Files: ${manifest.files.length}`);\n\n // Check for modifications\n const modifiedFiles = await fileManager.checkModifiedFiles(\n installDir,\n manifest\n );\n if (modifiedFiles.length > 0) {\n console.log(chalk.yellow(` Modified Files: ${modifiedFiles.length}`));\n }\n\n console.log(\"\");\n }\n\n async getAvailableAgents() {\n return resourceLocator.getAvailableAgents();\n }\n\n async getAvailableExpansionPacks() {\n return resourceLocator.getExpansionPacks();\n }\n\n async getAvailableTeams() {\n return configLoader.getAvailableTeams();\n }\n\n async installExpansionPacks(installDir, selectedPacks, spinner, config = {}) {\n if (!selectedPacks || selectedPacks.length === 0) {\n return [];\n }\n\n const installedFiles = [];\n\n for (const packId of selectedPacks) {\n spinner.text = `Installing expansion pack: ${packId}...`;\n \n try {\n const expansionPacks = await resourceLocator.getExpansionPacks();\n const pack = expansionPacks.find(p => p.id === packId);\n \n if (!pack) {\n console.warn(`Expansion pack ${packId} not found, skipping...`);\n continue;\n }\n \n // Check if expansion pack already exists\n let expansionDotFolder = path.join(installDir, `.${packId}`);\n const existingManifestPath = path.join(expansionDotFolder, 'install-manifest.yaml');\n \n if (await fileManager.pathExists(existingManifestPath)) {\n spinner.stop();\n const existingManifest = await fileManager.readExpansionPackManifest(installDir, packId);\n \n console.log(chalk.yellow(`\\nšŸ” Found existing ${pack.name} installation`));\n console.log(` Current version: ${existingManifest.version || 'unknown'}`);\n console.log(` New version: ${pack.version}`);\n \n // Check integrity of existing expansion pack\n const packIntegrity = await fileManager.checkFileIntegrity(installDir, existingManifest);\n const hasPackIntegrityIssues = packIntegrity.missing.length > 0 || packIntegrity.modified.length > 0;\n \n if (hasPackIntegrityIssues) {\n console.log(chalk.red(\" āš ļø Installation issues detected:\"));\n if (packIntegrity.missing.length > 0) {\n console.log(chalk.red(` Missing files: ${packIntegrity.missing.length}`));\n }\n if (packIntegrity.modified.length > 0) {\n console.log(chalk.yellow(` Modified files: ${packIntegrity.modified.length}`));\n }\n }\n \n const versionCompare = this.compareVersions(existingManifest.version || '0.0.0', pack.version);\n \n if (versionCompare === 0) {\n console.log(chalk.yellow(' āš ļø Same version already installed'));\n \n const choices = [];\n if (hasPackIntegrityIssues) {\n choices.push({ name: 'Repair (restore missing/modified files)', value: 'repair' });\n }\n choices.push(\n { name: 'Force reinstall (overwrite)', value: 'overwrite' },\n { name: 'Skip this expansion pack', value: 'skip' },\n { name: 'Cancel installation', value: 'cancel' }\n );\n \n const { action } = await inquirer.prompt([{\n type: 'list',\n name: 'action',\n message: `${pack.name} v${pack.version} is already installed. What would you like to do?`,\n choices: choices\n }]);\n \n if (action === 'skip') {\n spinner.start();\n continue;\n } else if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n } else if (action === 'repair') {\n // Repair the expansion pack\n await this.repairExpansionPack(installDir, packId, pack, packIntegrity, spinner);\n continue;\n }\n } else if (versionCompare < 0) {\n console.log(chalk.cyan(' ā¬†ļø Upgrade available'));\n \n const { proceed } = await inquirer.prompt([{\n type: 'confirm',\n name: 'proceed',\n message: `Upgrade ${pack.name} from v${existingManifest.version} to v${pack.version}?`,\n default: true\n }]);\n \n if (!proceed) {\n spinner.start();\n continue;\n }\n } else {\n console.log(chalk.yellow(' ā¬‡ļø Installed version is newer than available version'));\n \n const { action } = await inquirer.prompt([{\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n { name: 'Keep current version', value: 'skip' },\n { name: 'Downgrade to available version', value: 'downgrade' },\n { name: 'Cancel installation', value: 'cancel' }\n ]\n }]);\n \n if (action === 'skip') {\n spinner.start();\n continue;\n } else if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n }\n }\n \n // If we get here, we're proceeding with installation\n spinner.start(`Removing old ${pack.name} installation...`);\n await fileManager.removeDirectory(expansionDotFolder);\n }\n\n const expansionPackDir = pack.path;\n \n // Ensure dedicated dot folder exists for this expansion pack\n expansionDotFolder = path.join(installDir, `.${packId}`);\n await fileManager.ensureDirectory(expansionDotFolder);\n \n // Define the folders to copy from expansion packs\n const foldersToSync = [\n 'agents',\n 'agent-teams',\n 'templates',\n 'tasks',\n 'checklists',\n 'workflows',\n 'data',\n 'utils',\n 'schemas'\n ];\n\n // Copy each folder if it exists\n for (const folder of foldersToSync) {\n const sourceFolder = path.join(expansionPackDir, folder);\n \n // Check if folder exists in expansion pack\n if (await fileManager.pathExists(sourceFolder)) {\n // Get all files in this folder\n const files = await resourceLocator.findFiles('**/*', {\n cwd: sourceFolder,\n nodir: true\n });\n\n // Copy each file to the expansion pack's dot folder with {root} replacement\n for (const file of files) {\n const sourcePath = path.join(sourceFolder, file);\n const destPath = path.join(expansionDotFolder, folder, file);\n \n const needsRootReplacement = file.endsWith('.md') || file.endsWith('.yaml') || file.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, `.${packId}`);\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n \n if (success) {\n installedFiles.push(path.join(`.${packId}`, folder, file));\n }\n }\n }\n }\n\n // Copy config.yaml with {root} replacement\n const configPath = path.join(expansionPackDir, 'config.yaml');\n if (await fileManager.pathExists(configPath)) {\n const configDestPath = path.join(expansionDotFolder, 'config.yaml');\n if (await fileManager.copyFileWithRootReplacement(configPath, configDestPath, `.${packId}`)) {\n installedFiles.push(path.join(`.${packId}`, 'config.yaml'));\n }\n }\n \n // Copy README if it exists with {root} replacement\n const readmePath = path.join(expansionPackDir, 'README.md');\n if (await fileManager.pathExists(readmePath)) {\n const readmeDestPath = path.join(expansionDotFolder, 'README.md');\n if (await fileManager.copyFileWithRootReplacement(readmePath, readmeDestPath, `.${packId}`)) {\n installedFiles.push(path.join(`.${packId}`, 'README.md'));\n }\n }\n\n // Copy common/ items to expansion pack folder\n spinner.text = `Copying common utilities to ${packId}...`;\n await this.copyCommonItems(installDir, `.${packId}`, spinner);\n \n // Check and resolve core dependencies\n await this.resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner);\n \n // Check and resolve core agents referenced by teams\n await this.resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner);\n\n // Create manifest for this expansion pack\n spinner.text = `Creating manifest for ${packId}...`;\n const expansionConfig = {\n installType: 'expansion-pack',\n expansionPackId: packId,\n expansionPackName: pack.name,\n expansionPackVersion: pack.version,\n ides: config.ides || [] // Use ides_setup instead of ide_setup\n };\n \n // Get all files installed in this expansion pack\n const foundFiles = await resourceLocator.findFiles('**/*', {\n cwd: expansionDotFolder,\n nodir: true\n });\n const expansionPackFiles = foundFiles.map(f => path.join(`.${packId}`, f));\n \n await fileManager.createExpansionPackManifest(installDir, packId, expansionConfig, expansionPackFiles);\n\n console.log(chalk.green(`āœ“ Installed expansion pack: ${pack.name} to ${`.${packId}`}`));\n } catch (error) {\n console.error(`Failed to install expansion pack ${packId}: ${error.message}`);\n console.error(`Stack trace: ${error.stack}`);\n }\n }\n\n return installedFiles;\n }\n\n async resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner) {\n const yaml = require('js-yaml');\n const fs = require('fs').promises;\n \n // Find all agent files in the expansion pack\n const agentFiles = await resourceLocator.findFiles('agents/*.md', {\n cwd: expansionDotFolder\n });\n\n for (const agentFile of agentFiles) {\n const agentPath = path.join(expansionDotFolder, agentFile);\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML frontmatter to check dependencies\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n try {\n const agentConfig = yaml.load(yamlContent);\n const dependencies = agentConfig.dependencies || {};\n \n // Check for core dependencies (those that don't exist in the expansion pack)\n for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {\n const deps = dependencies[depType] || [];\n \n for (const dep of deps) {\n const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep : \n (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);\n const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);\n \n // Check if dependency exists in expansion pack dot folder\n if (!(await fileManager.pathExists(expansionDepPath))) {\n // Try to find it in expansion pack source\n const sourceDepPath = path.join(pack.path, depType, depFileName);\n \n if (await fileManager.pathExists(sourceDepPath)) {\n // Copy from expansion pack source\n spinner.text = `Copying ${packId} dependency ${dep}...`;\n const destPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(sourceDepPath, destPath, `.${packId}`);\n console.log(chalk.dim(` Added ${packId} dependency: ${depType}/${depFileName}`));\n } else {\n // Try to find it in core\n const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);\n \n if (await fileManager.pathExists(coreDepPath)) {\n spinner.text = `Copying core dependency ${dep} for ${packId}...`;\n \n // Copy from core to expansion pack dot folder with {root} replacement\n const destPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(coreDepPath, destPath, `.${packId}`);\n \n console.log(chalk.dim(` Added core dependency: ${depType}/${depFileName}`));\n } else {\n console.warn(chalk.yellow(` Warning: Dependency ${depType}/${dep} not found in core or expansion pack`));\n }\n }\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse agent dependencies: ${error.message}`);\n }\n }\n }\n }\n\n async resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner) {\n const yaml = require('js-yaml');\n const fs = require('fs').promises;\n \n // Find all team files in the expansion pack\n const teamFiles = await resourceLocator.findFiles('agent-teams/*.yaml', {\n cwd: expansionDotFolder\n });\n\n // Also get existing agents in the expansion pack\n const existingAgents = new Set();\n const agentFiles = await resourceLocator.findFiles('agents/*.md', {\n cwd: expansionDotFolder\n });\n for (const agentFile of agentFiles) {\n const agentName = path.basename(agentFile, '.md');\n existingAgents.add(agentName);\n }\n\n // Process each team file\n for (const teamFile of teamFiles) {\n const teamPath = path.join(expansionDotFolder, teamFile);\n const teamContent = await fs.readFile(teamPath, 'utf8');\n \n try {\n const teamConfig = yaml.load(teamContent);\n const agents = teamConfig.agents || [];\n \n // Add bmad-orchestrator if not present (required for all teams)\n if (!agents.includes('bmad-orchestrator')) {\n agents.unshift('bmad-orchestrator');\n }\n \n // Check each agent in the team\n for (const agentId of agents) {\n if (!existingAgents.has(agentId)) {\n // Agent not in expansion pack, try to get from core\n const coreAgentPath = path.join(resourceLocator.getBmadCorePath(), 'agents', `${agentId}.md`);\n \n if (await fileManager.pathExists(coreAgentPath)) {\n spinner.text = `Copying core agent ${agentId} for ${packId}...`;\n \n // Copy agent file with {root} replacement\n const destPath = path.join(expansionDotFolder, 'agents', `${agentId}.md`);\n await fileManager.copyFileWithRootReplacement(coreAgentPath, destPath, `.${packId}`);\n existingAgents.add(agentId);\n \n console.log(chalk.dim(` Added core agent: ${agentId}`));\n \n // Now resolve this agent's dependencies too\n const agentContent = await fs.readFile(coreAgentPath, 'utf8');\n const yamlContent = extractYamlFromAgent(agentContent, true);\n \n if (yamlContent) {\n try {\n \n const agentConfig = yaml.load(yamlContent);\n const dependencies = agentConfig.dependencies || {};\n \n // Copy all dependencies for this agent\n for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {\n const deps = dependencies[depType] || [];\n \n for (const dep of deps) {\n const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep : \n (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);\n const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);\n \n // Check if dependency exists in expansion pack\n if (!(await fileManager.pathExists(expansionDepPath))) {\n // Try to find it in core\n const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);\n \n if (await fileManager.pathExists(coreDepPath)) {\n const destDepPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(coreDepPath, destDepPath, `.${packId}`);\n console.log(chalk.dim(` Added agent dependency: ${depType}/${depFileName}`));\n } else {\n // Try common folder\n const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root\n const commonDepPath = path.join(sourceBase, 'common', depType, depFileName);\n if (await fileManager.pathExists(commonDepPath)) {\n const destDepPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFile(commonDepPath, destDepPath);\n console.log(chalk.dim(` Added agent dependency from common: ${depType}/${depFileName}`));\n }\n }\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse agent ${agentId} dependencies: ${error.message}`);\n }\n }\n } else {\n console.warn(chalk.yellow(` Warning: Core agent ${agentId} not found for team ${path.basename(teamFile, '.yaml')}`));\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse team file ${teamFile}: ${error.message}`);\n }\n }\n }\n\n getWebBundleInfo(config) {\n const webBundleType = config.webBundleType || 'all';\n \n switch (webBundleType) {\n case 'all':\n return 'all bundles';\n case 'agents':\n return 'individual agents only';\n case 'teams':\n return config.selectedWebBundleTeams ? \n `teams: ${config.selectedWebBundleTeams.join(', ')}` : \n 'selected teams';\n case 'custom':\n const parts = [];\n if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {\n parts.push(`teams: ${config.selectedWebBundleTeams.join(', ')}`);\n }\n if (config.includeIndividualAgents) {\n parts.push('individual agents');\n }\n return parts.length > 0 ? parts.join(' + ') : 'custom selection';\n default:\n return 'selected bundles';\n }\n }\n\n async installWebBundles(webBundlesDirectory, config, spinner) {\n \n try {\n // Find the dist directory in the BMad installation\n const distDir = configLoader.getDistPath();\n \n if (!(await fileManager.pathExists(distDir))) {\n console.warn('Web bundles not found. Run \"npm run build\" to generate them.');\n return;\n }\n\n // Ensure web bundles directory exists\n await fileManager.ensureDirectory(webBundlesDirectory);\n \n const webBundleType = config.webBundleType || 'all';\n \n if (webBundleType === 'all') {\n // Copy the entire dist directory structure\n await fileManager.copyDirectory(distDir, webBundlesDirectory);\n console.log(chalk.green(`āœ“ Installed all web bundles to: ${webBundlesDirectory}`));\n } else {\n let copiedCount = 0;\n \n // Copy specific selections based on type\n if (webBundleType === 'agents' || (webBundleType === 'custom' && config.includeIndividualAgents)) {\n const agentsSource = path.join(distDir, 'agents');\n const agentsTarget = path.join(webBundlesDirectory, 'agents');\n if (await fileManager.pathExists(agentsSource)) {\n await fileManager.copyDirectory(agentsSource, agentsTarget);\n console.log(chalk.green(`āœ“ Copied individual agent bundles`));\n copiedCount += 10; // Approximate count for agents\n }\n }\n \n if (webBundleType === 'teams' || webBundleType === 'custom') {\n if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {\n const teamsSource = path.join(distDir, 'teams');\n const teamsTarget = path.join(webBundlesDirectory, 'teams');\n await fileManager.ensureDirectory(teamsTarget);\n \n for (const teamId of config.selectedWebBundleTeams) {\n const teamFile = `${teamId}.txt`;\n const sourcePath = path.join(teamsSource, teamFile);\n const targetPath = path.join(teamsTarget, teamFile);\n \n if (await fileManager.pathExists(sourcePath)) {\n await fileManager.copyFile(sourcePath, targetPath);\n copiedCount++;\n console.log(chalk.green(`āœ“ Copied team bundle: ${teamId}`));\n }\n }\n }\n }\n \n // Always copy expansion packs if they exist\n const expansionSource = path.join(distDir, 'expansion-packs');\n const expansionTarget = path.join(webBundlesDirectory, 'expansion-packs');\n if (await fileManager.pathExists(expansionSource)) {\n await fileManager.copyDirectory(expansionSource, expansionTarget);\n console.log(chalk.green(`āœ“ Copied expansion pack bundles`));\n }\n \n console.log(chalk.green(`āœ“ Installed ${copiedCount} selected web bundles to: ${webBundlesDirectory}`));\n }\n } catch (error) {\n console.error(`Failed to install web bundles: ${error.message}`);\n }\n }\n\n async copyCommonItems(installDir, targetSubdir, spinner) {\n \n const fs = require('fs').promises;\n const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root\n const commonPath = path.join(sourceBase, 'common');\n const targetPath = path.join(installDir, targetSubdir);\n const copiedFiles = [];\n \n // Check if common/ exists\n if (!(await fileManager.pathExists(commonPath))) {\n console.warn('Warning: common/ folder not found');\n return copiedFiles;\n }\n \n // Copy all items from common/ to target\n const commonItems = await resourceLocator.findFiles('**/*', {\n cwd: commonPath,\n nodir: true\n });\n \n for (const item of commonItems) {\n const sourcePath = path.join(commonPath, item);\n const destPath = path.join(targetPath, item);\n \n // Read the file content\n const content = await fs.readFile(sourcePath, 'utf8');\n \n // Replace {root} with the target subdirectory\n const updatedContent = content.replace(/\\{root\\}/g, targetSubdir);\n \n // Ensure directory exists\n await fileManager.ensureDirectory(path.dirname(destPath));\n \n // Write the updated content\n await fs.writeFile(destPath, updatedContent, 'utf8');\n copiedFiles.push(path.join(targetSubdir, item));\n }\n \n console.log(chalk.dim(` Added ${commonItems.length} common utilities`));\n return copiedFiles;\n }\n\n async detectExpansionPacks(installDir) {\n const expansionPacks = {};\n const glob = require(\"glob\");\n \n // Find all dot folders that might be expansion packs\n const dotFolders = glob.sync(\".*\", {\n cwd: installDir,\n ignore: [\".git\", \".git/**\", \".bmad-core\", \".bmad-core/**\"],\n });\n \n for (const folder of dotFolders) {\n const folderPath = path.join(installDir, folder);\n const stats = await fileManager.pathExists(folderPath);\n \n if (stats) {\n // Check if it has a manifest\n const manifestPath = path.join(folderPath, \"install-manifest.yaml\");\n if (await fileManager.pathExists(manifestPath)) {\n const manifest = await fileManager.readExpansionPackManifest(installDir, folder.substring(1));\n if (manifest) {\n expansionPacks[folder.substring(1)] = {\n path: folderPath,\n manifest: manifest,\n hasManifest: true\n };\n }\n } else {\n // Check if it has a config.yaml (expansion pack without manifest)\n const configPath = path.join(folderPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n expansionPacks[folder.substring(1)] = {\n path: folderPath,\n manifest: null,\n hasManifest: false\n };\n }\n }\n }\n }\n \n return expansionPacks;\n }\n\n async repairExpansionPack(installDir, packId, pack, integrity, spinner) {\n spinner.start(`Repairing ${pack.name}...`);\n \n try {\n const expansionDotFolder = path.join(installDir, `.${packId}`);\n \n // Back up modified files\n if (integrity.modified.length > 0) {\n spinner.text = \"Backing up modified files...\";\n for (const file of integrity.modified) {\n const filePath = path.join(installDir, file);\n if (await fileManager.pathExists(filePath)) {\n const backupPath = await fileManager.backupFile(filePath);\n console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));\n }\n }\n }\n \n // Restore missing and modified files\n spinner.text = \"Restoring files...\";\n const filesToRestore = [...integrity.missing, ...integrity.modified];\n \n for (const file of filesToRestore) {\n // Skip the manifest file itself\n if (file.endsWith('install-manifest.yaml')) continue;\n \n const relativePath = file.replace(`.${packId}/`, '');\n const sourcePath = path.join(pack.path, relativePath);\n const destPath = path.join(installDir, file);\n \n // Check if this is a common/ file that needs special processing\n const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));\n const commonSourcePath = path.join(commonBase, 'common', relativePath);\n \n if (await fileManager.pathExists(commonSourcePath)) {\n // This is a common/ file - needs template processing\n const fs = require('fs').promises;\n const content = await fs.readFile(commonSourcePath, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, `.${packId}`);\n await fileManager.ensureDirectory(path.dirname(destPath));\n await fs.writeFile(destPath, updatedContent, 'utf8');\n spinner.text = `Restored: ${file}`;\n } else if (await fileManager.pathExists(sourcePath)) {\n // Regular file from expansion pack\n await fileManager.copyFile(sourcePath, destPath);\n spinner.text = `Restored: ${file}`;\n } else {\n console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));\n }\n }\n \n spinner.succeed(`${pack.name} repaired successfully!`);\n \n // Show summary\n console.log(chalk.green(`\\nāœ“ ${pack.name} repaired!`));\n if (integrity.missing.length > 0) {\n console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));\n }\n if (integrity.modified.length > 0) {\n console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));\n }\n \n } catch (error) {\n if (spinner) spinner.fail(`Failed to repair ${pack.name}`);\n console.error(`Error: ${error.message}`);\n }\n }\n\n compareVersions(v1, v2) {\n // Simple semver comparison\n const parts1 = v1.split('.').map(Number);\n const parts2 = v2.split('.').map(Number);\n \n for (let i = 0; i < 3; i++) {\n const part1 = parts1[i] || 0;\n const part2 = parts2[i] || 0;\n \n if (part1 > part2) return 1;\n if (part1 < part2) return -1;\n }\n \n return 0;\n }\n\n async cleanupLegacyYmlFiles(installDir, spinner) {\n const glob = require('glob');\n const fs = require('fs').promises;\n \n try {\n // Find all .yml files in the installation directory\n const ymlFiles = glob.sync('**/*.yml', {\n cwd: installDir,\n ignore: ['**/node_modules/**', '**/.git/**']\n });\n \n let deletedCount = 0;\n \n for (const ymlFile of ymlFiles) {\n // Check if corresponding .yaml file exists\n const yamlFile = ymlFile.replace(/\\.yml$/, '.yaml');\n const ymlPath = path.join(installDir, ymlFile);\n const yamlPath = path.join(installDir, yamlFile);\n \n if (await fileManager.pathExists(yamlPath)) {\n // .yaml counterpart exists, delete the .yml file\n await fs.unlink(ymlPath);\n deletedCount++;\n console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${yamlFile})`));\n }\n }\n \n if (deletedCount > 0) {\n console.log(chalk.green(`āœ“ Cleaned up ${deletedCount} legacy .yml files`));\n }\n \n } catch (error) {\n console.warn(`Warning: Could not cleanup legacy .yml files: ${error.message}`);\n }\n }\n\n async findInstallation() {\n // Look for .bmad-core in current directory or parent directories\n let currentDir = process.cwd();\n\n while (currentDir !== path.dirname(currentDir)) {\n const bmadDir = path.join(currentDir, \".bmad-core\");\n const manifestPath = path.join(bmadDir, \"install-manifest.yaml\");\n\n if (await fileManager.pathExists(manifestPath)) {\n return bmadDir;\n }\n\n currentDir = path.dirname(currentDir);\n }\n\n // Also check if we're inside a .bmad-core directory\n if (path.basename(process.cwd()) === \".bmad-core\") {\n const manifestPath = path.join(process.cwd(), \"install-manifest.yaml\");\n if (await fileManager.pathExists(manifestPath)) {\n return process.cwd();\n }\n }\n\n return null;\n }\n}\n\nmodule.exports = new Installer();\n"], ["/BMAD-METHOD/tools/builders/web-builder.js", "const fs = require(\"node:fs\").promises;\nconst path = require(\"node:path\");\nconst DependencyResolver = require(\"../lib/dependency-resolver\");\nconst yamlUtils = require(\"../lib/yaml-utils\");\n\nclass WebBuilder {\n constructor(options = {}) {\n this.rootDir = options.rootDir || process.cwd();\n this.outputDirs = options.outputDirs || [path.join(this.rootDir, \"dist\")];\n this.resolver = new DependencyResolver(this.rootDir);\n this.templatePath = path.join(\n this.rootDir,\n \"tools\",\n \"md-assets\",\n \"web-agent-startup-instructions.md\"\n );\n }\n\n parseYaml(content) {\n const yaml = require(\"js-yaml\");\n return yaml.load(content);\n }\n\n convertToWebPath(filePath, bundleRoot = 'bmad-core') {\n // Convert absolute paths to web bundle paths with dot prefix\n // All resources get installed under the bundle root, so use that path\n const relativePath = path.relative(this.rootDir, filePath);\n const pathParts = relativePath.split(path.sep);\n \n let resourcePath;\n if (pathParts[0] === 'expansion-packs') {\n // For expansion packs, remove 'expansion-packs/packname' and use the rest\n resourcePath = pathParts.slice(2).join('/');\n } else {\n // For bmad-core, common, etc., remove the first part\n resourcePath = pathParts.slice(1).join('/');\n }\n \n return `.${bundleRoot}/${resourcePath}`;\n }\n\n generateWebInstructions(bundleType, packName = null) {\n // Generate dynamic web instructions based on bundle type\n const rootExample = packName ? `.${packName}` : '.bmad-core';\n const examplePath = packName ? `.${packName}/folder/filename.md` : '.bmad-core/folder/filename.md';\n const personasExample = packName ? `.${packName}/personas/analyst.md` : '.bmad-core/personas/analyst.md';\n const tasksExample = packName ? `.${packName}/tasks/create-story.md` : '.bmad-core/tasks/create-story.md';\n const utilsExample = packName ? `.${packName}/utils/template-format.md` : '.bmad-core/utils/template-format.md';\n const tasksRef = packName ? `.${packName}/tasks/create-story.md` : '.bmad-core/tasks/create-story.md';\n\n return `# Web Agent Bundle Instructions\n\nYou are now operating as a specialized AI agent from the BMad-Method framework. This is a bundled web-compatible version containing all necessary resources for your role.\n\n## Important Instructions\n\n1. **Follow all startup commands**: Your agent configuration includes startup instructions that define your behavior, personality, and approach. These MUST be followed exactly.\n\n2. **Resource Navigation**: This bundle contains all resources you need. Resources are marked with tags like:\n\n- \\`==================== START: ${examplePath} ====================\\`\n- \\`==================== END: ${examplePath} ====================\\`\n\nWhen you need to reference a resource mentioned in your instructions:\n\n- Look for the corresponding START/END tags\n- The format is always the full path with dot prefix (e.g., \\`${personasExample}\\`, \\`${tasksExample}\\`)\n- If a section is specified (e.g., \\`{root}/tasks/create-story.md#section-name\\`), navigate to that section within the file\n\n**Understanding YAML References**: In the agent configuration, resources are referenced in the dependencies section. For example:\n\n\\`\\`\\`yaml\ndependencies:\n utils:\n - template-format\n tasks:\n - create-story\n\\`\\`\\`\n\nThese references map directly to bundle sections:\n\n- \\`utils: template-format\\` → Look for \\`==================== START: ${utilsExample} ====================\\`\n- \\`tasks: create-story\\` → Look for \\`==================== START: ${tasksRef} ====================\\`\n\n3. **Execution Context**: You are operating in a web environment. All your capabilities and knowledge are contained within this bundle. Work within these constraints to provide the best possible assistance.\n\n4. **Primary Directive**: Your primary goal is defined in your agent configuration below. Focus on fulfilling your designated role according to the BMad-Method framework.\n\n---\n\n`;\n }\n\n async cleanOutputDirs() {\n for (const dir of this.outputDirs) {\n try {\n await fs.rm(dir, { recursive: true, force: true });\n console.log(`Cleaned: ${path.relative(this.rootDir, dir)}`);\n } catch (error) {\n console.debug(`Failed to clean directory ${dir}:`, error.message);\n // Directory might not exist, that's fine\n }\n }\n }\n\n async buildAgents() {\n const agents = await this.resolver.listAgents();\n\n for (const agentId of agents) {\n console.log(` Building agent: ${agentId}`);\n const bundle = await this.buildAgentBundle(agentId);\n\n // Write to all output directories\n for (const outputDir of this.outputDirs) {\n const outputPath = path.join(outputDir, \"agents\");\n await fs.mkdir(outputPath, { recursive: true });\n const outputFile = path.join(outputPath, `${agentId}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n\n console.log(`Built ${agents.length} agent bundles in ${this.outputDirs.length} locations`);\n }\n\n async buildTeams() {\n const teams = await this.resolver.listTeams();\n\n for (const teamId of teams) {\n console.log(` Building team: ${teamId}`);\n const bundle = await this.buildTeamBundle(teamId);\n\n // Write to all output directories\n for (const outputDir of this.outputDirs) {\n const outputPath = path.join(outputDir, \"teams\");\n await fs.mkdir(outputPath, { recursive: true });\n const outputFile = path.join(outputPath, `${teamId}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n\n console.log(`Built ${teams.length} team bundles in ${this.outputDirs.length} locations`);\n }\n\n async buildAgentBundle(agentId) {\n const dependencies = await this.resolver.resolveAgentDependencies(agentId);\n const template = this.generateWebInstructions('agent');\n\n const sections = [template];\n\n // Add agent configuration\n const agentPath = this.convertToWebPath(dependencies.agent.path, 'bmad-core');\n sections.push(this.formatSection(agentPath, dependencies.agent.content, 'bmad-core'));\n\n // Add all dependencies\n for (const resource of dependencies.resources) {\n const resourcePath = this.convertToWebPath(resource.path, 'bmad-core');\n sections.push(this.formatSection(resourcePath, resource.content, 'bmad-core'));\n }\n\n return sections.join(\"\\n\");\n }\n\n async buildTeamBundle(teamId) {\n const dependencies = await this.resolver.resolveTeamDependencies(teamId);\n const template = this.generateWebInstructions('team');\n\n const sections = [template];\n\n // Add team configuration\n const teamPath = this.convertToWebPath(dependencies.team.path, 'bmad-core');\n sections.push(this.formatSection(teamPath, dependencies.team.content, 'bmad-core'));\n\n // Add all agents\n for (const agent of dependencies.agents) {\n const agentPath = this.convertToWebPath(agent.path, 'bmad-core');\n sections.push(this.formatSection(agentPath, agent.content, 'bmad-core'));\n }\n\n // Add all deduplicated resources\n for (const resource of dependencies.resources) {\n const resourcePath = this.convertToWebPath(resource.path, 'bmad-core');\n sections.push(this.formatSection(resourcePath, resource.content, 'bmad-core'));\n }\n\n return sections.join(\"\\n\");\n }\n\n processAgentContent(content) {\n // First, replace content before YAML with the template\n const yamlContent = yamlUtils.extractYamlFromAgent(content);\n if (!yamlContent) return content;\n\n const yamlMatch = content.match(/```ya?ml\\n([\\s\\S]*?)\\n```/);\n if (!yamlMatch) return content;\n \n const yamlStartIndex = content.indexOf(yamlMatch[0]);\n const yamlEndIndex = yamlStartIndex + yamlMatch[0].length;\n\n // Parse YAML and remove root and IDE-FILE-RESOLUTION properties\n try {\n const yaml = require(\"js-yaml\");\n const parsed = yaml.load(yamlContent);\n\n // Remove the properties if they exist at root level\n delete parsed.root;\n delete parsed[\"IDE-FILE-RESOLUTION\"];\n delete parsed[\"REQUEST-RESOLUTION\"];\n\n // Also remove from activation-instructions if they exist\n if (parsed[\"activation-instructions\"] && Array.isArray(parsed[\"activation-instructions\"])) {\n parsed[\"activation-instructions\"] = parsed[\"activation-instructions\"].filter(\n (instruction) => {\n return (\n typeof instruction === 'string' &&\n !instruction.startsWith(\"IDE-FILE-RESOLUTION:\") &&\n !instruction.startsWith(\"REQUEST-RESOLUTION:\")\n );\n }\n );\n }\n\n // Reconstruct the YAML\n const cleanedYaml = yaml.dump(parsed, { lineWidth: -1 });\n\n // Get the agent name from the YAML for the header\n const agentName = parsed.agent?.id || \"agent\";\n\n // Build the new content with just the agent header and YAML\n const newHeader = `# ${agentName}\\n\\nCRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n`;\n const afterYaml = content.substring(yamlEndIndex);\n\n return newHeader + \"```yaml\\n\" + cleanedYaml.trim() + \"\\n```\" + afterYaml;\n } catch (error) {\n console.warn(\"Failed to process agent YAML:\", error.message);\n // If parsing fails, return original content\n return content;\n }\n }\n\n formatSection(path, content, bundleRoot = 'bmad-core') {\n const separator = \"====================\";\n\n // Process agent content if this is an agent file\n if (path.includes(\"/agents/\")) {\n content = this.processAgentContent(content);\n }\n\n // Replace {root} references with the actual bundle root\n content = this.replaceRootReferences(content, bundleRoot);\n\n return [\n `${separator} START: ${path} ${separator}`,\n content.trim(),\n `${separator} END: ${path} ${separator}`,\n \"\",\n ].join(\"\\n\");\n }\n\n replaceRootReferences(content, bundleRoot) {\n // Replace {root} with the appropriate bundle root path\n return content.replace(/\\{root\\}/g, `.${bundleRoot}`);\n }\n\n async validate() {\n console.log(\"Validating agent configurations...\");\n const agents = await this.resolver.listAgents();\n for (const agentId of agents) {\n try {\n await this.resolver.resolveAgentDependencies(agentId);\n console.log(` āœ“ ${agentId}`);\n } catch (error) {\n console.log(` āœ— ${agentId}: ${error.message}`);\n throw error;\n }\n }\n\n console.log(\"\\nValidating team configurations...\");\n const teams = await this.resolver.listTeams();\n for (const teamId of teams) {\n try {\n await this.resolver.resolveTeamDependencies(teamId);\n console.log(` āœ“ ${teamId}`);\n } catch (error) {\n console.log(` āœ— ${teamId}: ${error.message}`);\n throw error;\n }\n }\n }\n\n async buildAllExpansionPacks(options = {}) {\n const expansionPacks = await this.listExpansionPacks();\n\n for (const packName of expansionPacks) {\n console.log(` Building expansion pack: ${packName}`);\n await this.buildExpansionPack(packName, options);\n }\n\n console.log(`Built ${expansionPacks.length} expansion pack bundles`);\n }\n\n async buildExpansionPack(packName, options = {}) {\n const packDir = path.join(this.rootDir, \"expansion-packs\", packName);\n const outputDirs = [path.join(this.rootDir, \"dist\", \"expansion-packs\", packName)];\n\n // Clean output directories if requested\n if (options.clean !== false) {\n for (const outputDir of outputDirs) {\n try {\n await fs.rm(outputDir, { recursive: true, force: true });\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n }\n\n // Build individual agents first\n const agentsDir = path.join(packDir, \"agents\");\n try {\n const agentFiles = await fs.readdir(agentsDir);\n const agentMarkdownFiles = agentFiles.filter((f) => f.endsWith(\".md\"));\n\n if (agentMarkdownFiles.length > 0) {\n console.log(` Building individual agents for ${packName}:`);\n\n for (const agentFile of agentMarkdownFiles) {\n const agentName = agentFile.replace(\".md\", \"\");\n console.log(` - ${agentName}`);\n\n // Build individual agent bundle\n const bundle = await this.buildExpansionAgentBundle(packName, packDir, agentName);\n\n // Write to all output directories\n for (const outputDir of outputDirs) {\n const agentsOutputDir = path.join(outputDir, \"agents\");\n await fs.mkdir(agentsOutputDir, { recursive: true });\n const outputFile = path.join(agentsOutputDir, `${agentName}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n }\n } catch (error) {\n console.debug(` No agents directory found for ${packName}`);\n }\n\n // Build team bundle\n const agentTeamsDir = path.join(packDir, \"agent-teams\");\n try {\n const teamFiles = await fs.readdir(agentTeamsDir);\n const teamFile = teamFiles.find((f) => f.endsWith(\".yaml\"));\n\n if (teamFile) {\n console.log(` Building team bundle for ${packName}`);\n const teamConfigPath = path.join(agentTeamsDir, teamFile);\n\n // Build expansion pack as a team bundle\n const bundle = await this.buildExpansionTeamBundle(packName, packDir, teamConfigPath);\n\n // Write to all output directories\n for (const outputDir of outputDirs) {\n const teamsOutputDir = path.join(outputDir, \"teams\");\n await fs.mkdir(teamsOutputDir, { recursive: true });\n const outputFile = path.join(teamsOutputDir, teamFile.replace(\".yaml\", \".txt\"));\n await fs.writeFile(outputFile, bundle, \"utf8\");\n console.log(` āœ“ Created bundle: ${path.relative(this.rootDir, outputFile)}`);\n }\n } else {\n console.warn(` ⚠ No team configuration found in ${packName}/agent-teams/`);\n }\n } catch (error) {\n console.warn(` ⚠ No agent-teams directory found for ${packName}`);\n }\n }\n\n async buildExpansionAgentBundle(packName, packDir, agentName) {\n const template = this.generateWebInstructions('expansion-agent', packName);\n const sections = [template];\n\n // Add agent configuration\n const agentPath = path.join(packDir, \"agents\", `${agentName}.md`);\n const agentContent = await fs.readFile(agentPath, \"utf8\");\n const agentWebPath = this.convertToWebPath(agentPath, packName);\n sections.push(this.formatSection(agentWebPath, agentContent, packName));\n\n // Resolve and add agent dependencies\n const yamlContent = yamlUtils.extractYamlFromAgent(agentContent);\n if (yamlContent) {\n try {\n const yaml = require(\"js-yaml\");\n const agentConfig = yaml.load(yamlContent);\n\n if (agentConfig.dependencies) {\n // Add resources, first try expansion pack, then core\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n let found = false;\n\n // Try expansion pack first\n const resourcePath = path.join(packDir, resourceType, resourceName);\n try {\n const resourceContent = await fs.readFile(resourcePath, \"utf8\");\n const resourceWebPath = this.convertToWebPath(resourcePath, packName);\n sections.push(\n this.formatSection(resourceWebPath, resourceContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in expansion pack, continue\n }\n\n // If not found in expansion pack, try core\n if (!found) {\n const corePath = path.join(\n this.rootDir,\n \"bmad-core\",\n resourceType,\n resourceName\n );\n try {\n const coreContent = await fs.readFile(corePath, \"utf8\");\n const coreWebPath = this.convertToWebPath(corePath, packName);\n sections.push(\n this.formatSection(coreWebPath, coreContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in core either, continue\n }\n }\n\n // If not found in core, try common folder\n if (!found) {\n const commonPath = path.join(\n this.rootDir,\n \"common\",\n resourceType,\n resourceName\n );\n try {\n const commonContent = await fs.readFile(commonPath, \"utf8\");\n const commonWebPath = this.convertToWebPath(commonPath, packName);\n sections.push(\n this.formatSection(commonWebPath, commonContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in common either, continue\n }\n }\n\n if (!found) {\n console.warn(\n ` ⚠ Dependency ${resourceType}#${resourceName} not found in expansion pack or core`\n );\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentName}:`, error.message);\n }\n }\n\n return sections.join(\"\\n\");\n }\n\n async buildExpansionTeamBundle(packName, packDir, teamConfigPath) {\n const template = this.generateWebInstructions('expansion-team', packName);\n\n const sections = [template];\n\n // Add team configuration and parse to get agent list\n const teamContent = await fs.readFile(teamConfigPath, \"utf8\");\n const teamFileName = path.basename(teamConfigPath, \".yaml\");\n const teamConfig = this.parseYaml(teamContent);\n const teamWebPath = this.convertToWebPath(teamConfigPath, packName);\n sections.push(this.formatSection(teamWebPath, teamContent, packName));\n\n // Get list of expansion pack agents\n const expansionAgents = new Set();\n const agentsDir = path.join(packDir, \"agents\");\n try {\n const agentFiles = await fs.readdir(agentsDir);\n for (const agentFile of agentFiles.filter((f) => f.endsWith(\".md\"))) {\n const agentName = agentFile.replace(\".md\", \"\");\n expansionAgents.add(agentName);\n }\n } catch (error) {\n console.warn(` ⚠ No agents directory found in ${packName}`);\n }\n\n // Build a map of all available expansion pack resources for override checking\n const expansionResources = new Map();\n const resourceDirs = [\"templates\", \"tasks\", \"checklists\", \"workflows\", \"data\"];\n for (const resourceDir of resourceDirs) {\n const resourcePath = path.join(packDir, resourceDir);\n try {\n const resourceFiles = await fs.readdir(resourcePath);\n for (const resourceFile of resourceFiles.filter(\n (f) => f.endsWith(\".md\") || f.endsWith(\".yaml\")\n )) {\n expansionResources.set(`${resourceDir}#${resourceFile}`, true);\n }\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n\n // Process all agents listed in team configuration\n const agentsToProcess = teamConfig.agents || [];\n\n // Ensure bmad-orchestrator is always included for teams\n if (!agentsToProcess.includes(\"bmad-orchestrator\")) {\n console.warn(` ⚠ Team ${teamFileName} missing bmad-orchestrator, adding automatically`);\n agentsToProcess.unshift(\"bmad-orchestrator\");\n }\n\n // Track all dependencies from all agents (deduplicated)\n const allDependencies = new Map();\n\n for (const agentId of agentsToProcess) {\n if (expansionAgents.has(agentId)) {\n // Use expansion pack version (override)\n const agentPath = path.join(agentsDir, `${agentId}.md`);\n const agentContent = await fs.readFile(agentPath, \"utf8\");\n const expansionAgentWebPath = this.convertToWebPath(agentPath, packName);\n sections.push(this.formatSection(expansionAgentWebPath, agentContent, packName));\n\n // Parse and collect dependencies from expansion agent\n const agentYaml = agentContent.match(/```yaml\\n([\\s\\S]*?)\\n```/);\n if (agentYaml) {\n try {\n const agentConfig = this.parseYaml(agentYaml[1]);\n if (agentConfig.dependencies) {\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n const key = `${resourceType}#${resourceName}`;\n if (!allDependencies.has(key)) {\n allDependencies.set(key, { type: resourceType, name: resourceName });\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentId}:`, error.message);\n }\n }\n } else {\n // Use core BMad version\n try {\n const coreAgentPath = path.join(this.rootDir, \"bmad-core\", \"agents\", `${agentId}.md`);\n const coreAgentContent = await fs.readFile(coreAgentPath, \"utf8\");\n const coreAgentWebPath = this.convertToWebPath(coreAgentPath, packName);\n sections.push(this.formatSection(coreAgentWebPath, coreAgentContent, packName));\n\n // Parse and collect dependencies from core agent\n const yamlContent = yamlUtils.extractYamlFromAgent(coreAgentContent, true);\n if (yamlContent) {\n try {\n const agentConfig = this.parseYaml(yamlContent);\n if (agentConfig.dependencies) {\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n const key = `${resourceType}#${resourceName}`;\n if (!allDependencies.has(key)) {\n allDependencies.set(key, { type: resourceType, name: resourceName });\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentId}:`, error.message);\n }\n }\n } catch (error) {\n console.warn(` ⚠ Agent ${agentId} not found in core or expansion pack`);\n }\n }\n }\n\n // Add all collected dependencies from agents\n // Always prefer expansion pack versions if they exist\n for (const [key, dep] of allDependencies) {\n let found = false;\n\n // Always check expansion pack first, even if the dependency came from a core agent\n if (expansionResources.has(key)) {\n // We know it exists in expansion pack, find and load it\n const expansionPath = path.join(packDir, dep.type, dep.name);\n try {\n const content = await fs.readFile(expansionPath, \"utf8\");\n const expansionWebPath = this.convertToWebPath(expansionPath, packName);\n sections.push(this.formatSection(expansionWebPath, content, packName));\n console.log(` āœ“ Using expansion override for ${key}`);\n found = true;\n } catch (error) {\n // Try next extension\n }\n }\n\n // If not found in expansion pack (or doesn't exist there), try core\n if (!found) {\n const corePath = path.join(this.rootDir, \"bmad-core\", dep.type, dep.name);\n try {\n const content = await fs.readFile(corePath, \"utf8\");\n const coreWebPath = this.convertToWebPath(corePath, packName);\n sections.push(this.formatSection(coreWebPath, content, packName));\n found = true;\n } catch (error) {\n // Not in core either, continue\n }\n }\n\n // If not found in core, try common folder\n if (!found) {\n const commonPath = path.join(this.rootDir, \"common\", dep.type, dep.name);\n try {\n const content = await fs.readFile(commonPath, \"utf8\");\n const commonWebPath = this.convertToWebPath(commonPath, packName);\n sections.push(this.formatSection(commonWebPath, content, packName));\n found = true;\n } catch (error) {\n // Not in common either, continue\n }\n }\n\n if (!found) {\n console.warn(` ⚠ Dependency ${key} not found in expansion pack or core`);\n }\n }\n\n // Add remaining expansion pack resources not already included as dependencies\n for (const resourceDir of resourceDirs) {\n const resourcePath = path.join(packDir, resourceDir);\n try {\n const resourceFiles = await fs.readdir(resourcePath);\n for (const resourceFile of resourceFiles.filter(\n (f) => f.endsWith(\".md\") || f.endsWith(\".yaml\")\n )) {\n const filePath = path.join(resourcePath, resourceFile);\n const fileContent = await fs.readFile(filePath, \"utf8\");\n const fileName = resourceFile.replace(/\\.(md|yaml)$/, \"\");\n\n // Only add if not already included as a dependency\n const resourceKey = `${resourceDir}#${fileName}`;\n if (!allDependencies.has(resourceKey)) {\n const fullResourcePath = path.join(resourcePath, resourceFile);\n const resourceWebPath = this.convertToWebPath(fullResourcePath, packName);\n sections.push(this.formatSection(resourceWebPath, fileContent, packName));\n }\n }\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n\n return sections.join(\"\\n\");\n }\n\n async listExpansionPacks() {\n const expansionPacksDir = path.join(this.rootDir, \"expansion-packs\");\n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);\n } catch (error) {\n console.warn(\"No expansion-packs directory found\");\n return [];\n }\n }\n\n listAgents() {\n return this.resolver.listAgents();\n }\n}\n\nmodule.exports = WebBuilder;\n"], ["/BMAD-METHOD/tools/installer/lib/ide-setup.js", "const path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst inquirer = require(\"inquirer\");\nconst fileManager = require(\"./file-manager\");\nconst configLoader = require(\"./config-loader\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\nconst BaseIdeSetup = require(\"./ide-base-setup\");\nconst resourceLocator = require(\"./resource-locator\");\n\nclass IdeSetup extends BaseIdeSetup {\n constructor() {\n super();\n this.ideAgentConfig = null;\n }\n\n async loadIdeAgentConfig() {\n if (this.ideAgentConfig) return this.ideAgentConfig;\n \n try {\n const configPath = path.join(__dirname, '..', 'config', 'ide-agent-config.yaml');\n const configContent = await fs.readFile(configPath, 'utf8');\n this.ideAgentConfig = yaml.load(configContent);\n return this.ideAgentConfig;\n } catch (error) {\n console.warn('Failed to load IDE agent configuration, using defaults');\n return {\n 'roo-permissions': {},\n 'cline-order': {}\n };\n }\n }\n\n async setup(ide, installDir, selectedAgent = null, spinner = null, preConfiguredSettings = null) {\n const ideConfig = await configLoader.getIdeConfiguration(ide);\n\n if (!ideConfig) {\n console.log(chalk.yellow(`\\nNo configuration available for ${ide}`));\n return false;\n }\n\n switch (ide) {\n case \"cursor\":\n return this.setupCursor(installDir, selectedAgent);\n case \"claude-code\":\n return this.setupClaudeCode(installDir, selectedAgent);\n case \"windsurf\":\n return this.setupWindsurf(installDir, selectedAgent);\n case \"trae\":\n return this.setupTrae(installDir, selectedAgent);\n case \"roo\":\n return this.setupRoo(installDir, selectedAgent);\n case \"cline\":\n return this.setupCline(installDir, selectedAgent);\n case \"gemini\":\n return this.setupGeminiCli(installDir, selectedAgent);\n case \"github-copilot\":\n return this.setupGitHubCopilot(installDir, selectedAgent, spinner, preConfiguredSettings);\n default:\n console.log(chalk.yellow(`\\nIDE ${ide} not yet supported`));\n return false;\n }\n }\n\n async setupCursor(installDir, selectedAgent) {\n const cursorRulesDir = path.join(installDir, \".cursor\", \"rules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(cursorRulesDir);\n\n for (const agentId of agents) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const mdcContent = await this.createAgentRuleContent(agentId, agentPath, installDir, 'mdc');\n const mdcPath = path.join(cursorRulesDir, `${agentId}.mdc`);\n await fileManager.writeFile(mdcPath, mdcContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.mdc`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Cursor rules in ${cursorRulesDir}`));\n return true;\n }\n\n async setupClaudeCode(installDir, selectedAgent) {\n // Setup bmad-core commands\n const coreSlashPrefix = await this.getCoreSlashPrefix(installDir);\n const coreAgents = selectedAgent ? [selectedAgent] : await this.getCoreAgentIds(installDir);\n const coreTasks = await this.getCoreTaskIds(installDir);\n await this.setupClaudeCodeForPackage(installDir, \"core\", coreSlashPrefix, coreAgents, coreTasks, \".bmad-core\");\n\n // Setup expansion pack commands\n const expansionPacks = await this.getInstalledExpansionPacks(installDir);\n for (const packInfo of expansionPacks) {\n const packSlashPrefix = await this.getExpansionPackSlashPrefix(packInfo.path);\n const packAgents = await this.getExpansionPackAgents(packInfo.path);\n const packTasks = await this.getExpansionPackTasks(packInfo.path);\n \n if (packAgents.length > 0 || packTasks.length > 0) {\n // Use the actual directory name where the expansion pack is installed\n const rootPath = path.relative(installDir, packInfo.path);\n await this.setupClaudeCodeForPackage(installDir, packInfo.name, packSlashPrefix, packAgents, packTasks, rootPath);\n }\n }\n\n return true;\n }\n\n async setupClaudeCodeForPackage(installDir, packageName, slashPrefix, agentIds, taskIds, rootPath) {\n const commandsBaseDir = path.join(installDir, \".claude\", \"commands\", slashPrefix);\n const agentsDir = path.join(commandsBaseDir, \"agents\");\n const tasksDir = path.join(commandsBaseDir, \"tasks\");\n\n // Ensure directories exist\n await fileManager.ensureDirectory(agentsDir);\n await fileManager.ensureDirectory(tasksDir);\n\n // Setup agents\n for (const agentId of agentIds) {\n // Find the agent file - for expansion packs, prefer the expansion pack version\n let agentPath;\n if (packageName !== \"core\") {\n // For expansion packs, first try to find the agent in the expansion pack directory\n const expansionPackPath = path.join(installDir, rootPath, \"agents\", `${agentId}.md`);\n if (await fileManager.pathExists(expansionPackPath)) {\n agentPath = expansionPackPath;\n } else {\n // Fall back to core if not found in expansion pack\n agentPath = await this.findAgentPath(agentId, installDir);\n }\n } else {\n // For core, use the normal search\n agentPath = await this.findAgentPath(agentId, installDir);\n }\n \n const commandPath = path.join(agentsDir, `${agentId}.md`);\n\n if (agentPath) {\n // Create command file with agent content\n let agentContent = await fileManager.readFile(agentPath);\n \n // Replace {root} placeholder with the appropriate root path for this context\n agentContent = agentContent.replace(/{root}/g, rootPath);\n\n // Add command header\n let commandContent = `# /${agentId} Command\\n\\n`;\n commandContent += `When this command is used, adopt the following agent persona:\\n\\n`;\n commandContent += agentContent;\n\n await fileManager.writeFile(commandPath, commandContent);\n console.log(chalk.green(`āœ“ Created agent command: /${agentId}`));\n }\n }\n\n // Setup tasks\n for (const taskId of taskIds) {\n // Find the task file - for expansion packs, prefer the expansion pack version\n let taskPath;\n if (packageName !== \"core\") {\n // For expansion packs, first try to find the task in the expansion pack directory\n const expansionPackPath = path.join(installDir, rootPath, \"tasks\", `${taskId}.md`);\n if (await fileManager.pathExists(expansionPackPath)) {\n taskPath = expansionPackPath;\n } else {\n // Fall back to core if not found in expansion pack\n taskPath = await this.findTaskPath(taskId, installDir);\n }\n } else {\n // For core, use the normal search\n taskPath = await this.findTaskPath(taskId, installDir);\n }\n \n const commandPath = path.join(tasksDir, `${taskId}.md`);\n\n if (taskPath) {\n // Create command file with task content\n let taskContent = await fileManager.readFile(taskPath);\n \n // Replace {root} placeholder with the appropriate root path for this context\n taskContent = taskContent.replace(/{root}/g, rootPath);\n\n // Add command header\n let commandContent = `# /${taskId} Task\\n\\n`;\n commandContent += `When this command is used, execute the following task:\\n\\n`;\n commandContent += taskContent;\n\n await fileManager.writeFile(commandPath, commandContent);\n console.log(chalk.green(`āœ“ Created task command: /${taskId}`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Claude Code commands for ${packageName} in ${commandsBaseDir}`));\n console.log(chalk.dim(` - Agents in: ${agentsDir}`));\n console.log(chalk.dim(` - Tasks in: ${tasksDir}`));\n }\n\n async setupWindsurf(installDir, selectedAgent) {\n const windsurfRulesDir = path.join(installDir, \".windsurf\", \"rules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(windsurfRulesDir);\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n const mdPath = path.join(windsurfRulesDir, `${agentId}.md`);\n\n // Create MD content (similar to Cursor but without frontmatter)\n let mdContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n mdContent += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n mdContent += \"## Agent Activation\\n\\n\";\n mdContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n } else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `When the user types \\`@${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n\n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Windsurf rules in ${windsurfRulesDir}`));\n\n return true;\n }\n\n async setupTrae(installDir, selectedAgent) {\n const traeRulesDir = path.join(installDir, \".trae\", \"rules\");\n const agents = selectedAgent? [selectedAgent] : await this.getAllAgentIds(installDir);\n \n await fileManager.ensureDirectory(traeRulesDir);\n \n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n \n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n const mdPath = path.join(traeRulesDir, `${agentId}.md`);\n \n // Create MD content (similar to Cursor but without frontmatter)\n let mdContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n mdContent += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n mdContent += \"## Agent Activation\\n\\n\";\n mdContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n }\n else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `When the user types \\`@${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n \n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.md`));\n }\n }\n }\n\n async findAgentPath(agentId, installDir) {\n // Try to find the agent file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"agents\", `${agentId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${agentId}.md`));\n }\n \n for (const agentPath of possiblePaths) {\n if (await fileManager.pathExists(agentPath)) {\n return agentPath;\n }\n }\n \n return null;\n }\n\n async getAllAgentIds(installDir) {\n const glob = require(\"glob\");\n const allAgentIds = [];\n \n // Check core agents in .bmad-core or root\n let agentsDir = path.join(installDir, \".bmad-core\", \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n agentsDir = path.join(installDir, \"agents\");\n }\n \n if (await fileManager.pathExists(agentsDir)) {\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n allAgentIds.push(...agentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Also check for expansion pack agents in dot folders\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n const fullExpDir = path.join(installDir, expDir);\n const expAgentFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allAgentIds.push(...expAgentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Remove duplicates\n return [...new Set(allAgentIds)];\n }\n\n async getCoreAgentIds(installDir) {\n const allAgentIds = [];\n \n // Check core agents in .bmad-core or root only\n let agentsDir = path.join(installDir, \".bmad-core\", \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n agentsDir = path.join(installDir, \"bmad-core\", \"agents\");\n }\n \n if (await fileManager.pathExists(agentsDir)) {\n const glob = require(\"glob\");\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n allAgentIds.push(...agentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n return [...new Set(allAgentIds)];\n }\n\n async getCoreTaskIds(installDir) {\n const allTaskIds = [];\n \n // Check core tasks in .bmad-core or root only\n let tasksDir = path.join(installDir, \".bmad-core\", \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n tasksDir = path.join(installDir, \"bmad-core\", \"tasks\");\n }\n \n if (await fileManager.pathExists(tasksDir)) {\n const glob = require(\"glob\");\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n allTaskIds.push(...taskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check common tasks\n const commonTasksDir = path.join(installDir, \"common\", \"tasks\");\n if (await fileManager.pathExists(commonTasksDir)) {\n const commonTaskFiles = glob.sync(\"*.md\", { cwd: commonTasksDir });\n allTaskIds.push(...commonTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n return [...new Set(allTaskIds)];\n }\n\n async getAgentTitle(agentId, installDir) {\n // Try to find the agent file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"agents\", `${agentId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${agentId}.md`));\n }\n \n for (const agentPath of possiblePaths) {\n if (await fileManager.pathExists(agentPath)) {\n try {\n const agentContent = await fileManager.readFile(agentPath);\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n \n if (yamlMatch) {\n const yaml = yamlMatch[1];\n const titleMatch = yaml.match(/title:\\s*(.+)/);\n if (titleMatch) {\n return titleMatch[1].trim();\n }\n }\n } catch (error) {\n console.warn(`Failed to read agent title for ${agentId}: ${error.message}`);\n }\n }\n }\n \n // Fallback to formatted agent ID\n return agentId.split('-').map(word => \n word.charAt(0).toUpperCase() + word.slice(1)\n ).join(' ');\n }\n\n async getAllTaskIds(installDir) {\n const glob = require(\"glob\");\n const allTaskIds = [];\n \n // Check core tasks in .bmad-core or root\n let tasksDir = path.join(installDir, \".bmad-core\", \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n tasksDir = path.join(installDir, \"bmad-core\", \"tasks\");\n }\n \n if (await fileManager.pathExists(tasksDir)) {\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n allTaskIds.push(...taskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check common tasks\n const commonTasksDir = path.join(installDir, \"common\", \"tasks\");\n if (await fileManager.pathExists(commonTasksDir)) {\n const commonTaskFiles = glob.sync(\"*.md\", { cwd: commonTasksDir });\n allTaskIds.push(...commonTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Also check for expansion pack tasks in dot folders\n const expansionDirs = glob.sync(\".*/tasks\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n const fullExpDir = path.join(installDir, expDir);\n const expTaskFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allTaskIds.push(...expTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check expansion-packs folder tasks\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const expPackDirs = glob.sync(\"*/tasks\", { cwd: expansionPacksDir });\n for (const expDir of expPackDirs) {\n const fullExpDir = path.join(expansionPacksDir, expDir);\n const expTaskFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allTaskIds.push(...expTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n }\n \n // Remove duplicates\n return [...new Set(allTaskIds)];\n }\n\n async findTaskPath(taskId, installDir) {\n // Try to find the task file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"tasks\", `${taskId}.md`),\n path.join(installDir, \"bmad-core\", \"tasks\", `${taskId}.md`),\n path.join(installDir, \"common\", \"tasks\", `${taskId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n \n // Check dot folder expansion packs\n const expansionDirs = glob.sync(\".*/tasks\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${taskId}.md`));\n }\n \n // Check expansion-packs folder\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const expPackDirs = glob.sync(\"*/tasks\", { cwd: expansionPacksDir });\n for (const expDir of expPackDirs) {\n possiblePaths.push(path.join(expansionPacksDir, expDir, `${taskId}.md`));\n }\n }\n \n for (const taskPath of possiblePaths) {\n if (await fileManager.pathExists(taskPath)) {\n return taskPath;\n }\n }\n \n return null;\n }\n\n async getCoreSlashPrefix(installDir) {\n try {\n const coreConfigPath = path.join(installDir, \".bmad-core\", \"core-config.yaml\");\n if (!(await fileManager.pathExists(coreConfigPath))) {\n // Try bmad-core directory\n const altConfigPath = path.join(installDir, \"bmad-core\", \"core-config.yaml\");\n if (await fileManager.pathExists(altConfigPath)) {\n const configContent = await fileManager.readFile(altConfigPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || \"BMad\";\n }\n return \"BMad\"; // fallback\n }\n \n const configContent = await fileManager.readFile(coreConfigPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || \"BMad\";\n } catch (error) {\n console.warn(`Failed to read core slashPrefix, using default 'BMad': ${error.message}`);\n return \"BMad\";\n }\n }\n\n async getInstalledExpansionPacks(installDir) {\n const expansionPacks = [];\n \n // Check for dot-prefixed expansion packs in install directory\n const glob = require(\"glob\");\n const dotExpansions = glob.sync(\".bmad-*\", { cwd: installDir });\n \n for (const dotExpansion of dotExpansions) {\n if (dotExpansion !== \".bmad-core\") {\n const packPath = path.join(installDir, dotExpansion);\n const packName = dotExpansion.substring(1); // remove the dot\n expansionPacks.push({\n name: packName,\n path: packPath\n });\n }\n }\n \n // Check for expansion-packs directory style\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const packDirs = glob.sync(\"*\", { cwd: expansionPacksDir });\n \n for (const packDir of packDirs) {\n const packPath = path.join(expansionPacksDir, packDir);\n if ((await fileManager.pathExists(packPath)) && \n (await fileManager.pathExists(path.join(packPath, \"config.yaml\")))) {\n expansionPacks.push({\n name: packDir,\n path: packPath\n });\n }\n }\n }\n \n return expansionPacks;\n }\n\n async getExpansionPackSlashPrefix(packPath) {\n try {\n const configPath = path.join(packPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n const configContent = await fileManager.readFile(configPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || path.basename(packPath);\n }\n } catch (error) {\n console.warn(`Failed to read expansion pack slashPrefix from ${packPath}: ${error.message}`);\n }\n \n return path.basename(packPath); // fallback to directory name\n }\n\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n return [];\n }\n \n try {\n const glob = require(\"glob\");\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n return agentFiles.map(file => path.basename(file, \".md\"));\n } catch (error) {\n console.warn(`Failed to read expansion pack agents from ${packPath}: ${error.message}`);\n return [];\n }\n }\n\n async getExpansionPackTasks(packPath) {\n const tasksDir = path.join(packPath, \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n return [];\n }\n \n try {\n const glob = require(\"glob\");\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n return taskFiles.map(file => path.basename(file, \".md\"));\n } catch (error) {\n console.warn(`Failed to read expansion pack tasks from ${packPath}: ${error.message}`);\n return [];\n }\n }\n\n async setupRoo(installDir, selectedAgent) {\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n // Check for existing .roomodes file in project root\n const roomodesPath = path.join(installDir, \".roomodes\");\n let existingModes = [];\n let existingContent = \"\";\n\n if (await fileManager.pathExists(roomodesPath)) {\n existingContent = await fileManager.readFile(roomodesPath);\n // Parse existing modes to avoid duplicates\n const modeMatches = existingContent.matchAll(/- slug: ([\\w-]+)/g);\n for (const match of modeMatches) {\n existingModes.push(match[1]);\n }\n console.log(chalk.yellow(`Found existing .roomodes file with ${existingModes.length} modes`));\n }\n\n // Create new modes content\n let newModesContent = \"\";\n\n // Load dynamic agent permissions from configuration\n const config = await this.loadIdeAgentConfig();\n const agentPermissions = config['roo-permissions'] || {};\n\n for (const agentId of agents) {\n // Skip if already exists\n // Check both with and without bmad- prefix to handle both cases\n const checkSlug = agentId.startsWith('bmad-') ? agentId : `bmad-${agentId}`;\n if (existingModes.includes(checkSlug)) {\n console.log(chalk.dim(`Skipping ${agentId} - already exists in .roomodes`));\n continue;\n }\n\n // Read agent file to extract all information\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n\n // Extract YAML content\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n const yaml = yamlMatch[1];\n\n // Extract agent info from YAML\n const titleMatch = yaml.match(/title:\\s*(.+)/);\n const iconMatch = yaml.match(/icon:\\s*(.+)/);\n const whenToUseMatch = yaml.match(/whenToUse:\\s*\"(.+)\"/);\n const roleDefinitionMatch = yaml.match(/roleDefinition:\\s*\"(.+)\"/);\n\n const title = titleMatch ? titleMatch[1].trim() : await this.getAgentTitle(agentId, installDir);\n const icon = iconMatch ? iconMatch[1].trim() : \"šŸ¤–\";\n const whenToUse = whenToUseMatch ? whenToUseMatch[1].trim() : `Use for ${title} tasks`;\n const roleDefinition = roleDefinitionMatch\n ? roleDefinitionMatch[1].trim()\n : `You are a ${title} specializing in ${title.toLowerCase()} tasks and responsibilities.`;\n\n // Build mode entry with proper formatting (matching exact indentation)\n // Avoid double \"bmad-\" prefix for agents that already have it\n const slug = agentId.startsWith('bmad-') ? agentId : `bmad-${agentId}`;\n newModesContent += ` - slug: ${slug}\\n`;\n newModesContent += ` name: '${icon} ${title}'\\n`;\n newModesContent += ` roleDefinition: ${roleDefinition}\\n`;\n newModesContent += ` whenToUse: ${whenToUse}\\n`;\n // Get relative path from installDir to agent file\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n newModesContent += ` customInstructions: CRITICAL Read the full YAML from ${relativePath} start activation to alter your state of being follow startup section instructions stay in this being until told to exit this mode\\n`;\n newModesContent += ` groups:\\n`;\n newModesContent += ` - read\\n`;\n\n // Add permissions based on agent type\n const permissions = agentPermissions[agentId];\n if (permissions) {\n newModesContent += ` - - edit\\n`;\n newModesContent += ` - fileRegex: ${permissions.fileRegex}\\n`;\n newModesContent += ` description: ${permissions.description}\\n`;\n } else {\n newModesContent += ` - edit\\n`;\n }\n\n console.log(chalk.green(`āœ“ Added mode: bmad-${agentId} (${icon} ${title})`));\n }\n }\n }\n\n // Build final roomodes content\n let roomodesContent = \"\";\n if (existingContent) {\n // If there's existing content, append new modes to it\n roomodesContent = existingContent.trim() + \"\\n\" + newModesContent;\n } else {\n // Create new .roomodes file with proper YAML structure\n roomodesContent = \"customModes:\\n\" + newModesContent;\n }\n\n // Write .roomodes file\n await fileManager.writeFile(roomodesPath, roomodesContent);\n console.log(chalk.green(\"āœ“ Created .roomodes file in project root\"));\n\n console.log(chalk.green(`\\nāœ“ Roo Code setup complete!`));\n console.log(chalk.dim(\"Custom modes will be available when you open this project in Roo Code\"));\n\n return true;\n }\n\n async setupCline(installDir, selectedAgent) {\n const clineRulesDir = path.join(installDir, \".clinerules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(clineRulesDir);\n\n // Load dynamic agent ordering from configuration\n const config = await this.loadIdeAgentConfig();\n const agentOrder = config['cline-order'] || {};\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n\n // Get numeric prefix for ordering\n const order = agentOrder[agentId] || 99;\n const prefix = order.toString().padStart(2, '0');\n const mdPath = path.join(clineRulesDir, `${prefix}-${agentId}.md`);\n\n // Create MD content for Cline (focused on project standards and role)\n let mdContent = `# ${await this.getAgentTitle(agentId, installDir)} Agent\\n\\n`;\n mdContent += `This rule defines the ${await this.getAgentTitle(agentId, installDir)} persona and project standards.\\n\\n`;\n mdContent += \"## Role Definition\\n\\n\";\n mdContent +=\n \"When the user types `@\" + agentId + \"`, adopt this persona and follow these guidelines:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n } else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## Project Standards\\n\\n\";\n mdContent += `- Always maintain consistency with project documentation in .bmad-core/\\n`;\n mdContent += `- Follow the agent's specific guidelines and constraints\\n`;\n mdContent += `- Update relevant project files when making changes\\n`;\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `- Reference the complete agent definition in [${relativePath}](${relativePath})\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `Type \\`@${agentId}\\` to activate this ${await this.getAgentTitle(agentId, installDir)} persona.\\n`;\n\n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${prefix}-${agentId}.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Cline rules in ${clineRulesDir}`));\n\n return true;\n }\n\n async setupGeminiCli(installDir) {\n const geminiDir = path.join(installDir, \".gemini\");\n const bmadMethodDir = path.join(geminiDir, \"bmad-method\");\n await fileManager.ensureDirectory(bmadMethodDir);\n\n // Update logic for existing settings.json\n const settingsPath = path.join(geminiDir, \"settings.json\");\n if (await fileManager.pathExists(settingsPath)) {\n try {\n const settingsContent = await fileManager.readFile(settingsPath);\n const settings = JSON.parse(settingsContent);\n let updated = false;\n \n // Handle contextFileName property\n if (settings.contextFileName && Array.isArray(settings.contextFileName)) {\n const originalLength = settings.contextFileName.length;\n settings.contextFileName = settings.contextFileName.filter(\n (fileName) => !fileName.startsWith(\"agents/\")\n );\n if (settings.contextFileName.length !== originalLength) {\n updated = true;\n }\n }\n \n if (updated) {\n await fileManager.writeFile(\n settingsPath,\n JSON.stringify(settings, null, 2)\n );\n console.log(chalk.green(\"āœ“ Updated .gemini/settings.json - removed agent file references\"));\n }\n } catch (error) {\n console.warn(\n chalk.yellow(\"Could not update .gemini/settings.json\"),\n error\n );\n }\n }\n\n // Remove old agents directory\n const agentsDir = path.join(geminiDir, \"agents\");\n if (await fileManager.pathExists(agentsDir)) {\n await fileManager.removeDirectory(agentsDir);\n console.log(chalk.green(\"āœ“ Removed old .gemini/agents directory\"));\n }\n\n // Get all available agents\n const agents = await this.getAllAgentIds(installDir);\n let concatenatedContent = \"\";\n\n for (const agentId of agents) {\n // Find the source agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n \n // Create properly formatted agent rule content (similar to trae)\n let agentRuleContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n agentRuleContent += `This rule is triggered when the user types \\`*${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n agentRuleContent += \"## Agent Activation\\n\\n\";\n agentRuleContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n agentRuleContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n agentRuleContent += yamlContent;\n }\n else {\n // If no YAML found, include the whole content minus the header\n agentRuleContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n agentRuleContent += \"\\n```\\n\\n\";\n agentRuleContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n agentRuleContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n agentRuleContent += \"## Usage\\n\\n\";\n agentRuleContent += `When the user types \\`*${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n \n // Add to concatenated content with separator\n concatenatedContent += agentRuleContent + \"\\n\\n---\\n\\n\";\n console.log(chalk.green(`āœ“ Added context for @${agentId}`));\n }\n }\n\n // Write the concatenated content to GEMINI.md\n const geminiMdPath = path.join(bmadMethodDir, \"GEMINI.md\");\n await fileManager.writeFile(geminiMdPath, concatenatedContent);\n console.log(chalk.green(`\\nāœ“ Created GEMINI.md in ${bmadMethodDir}`));\n\n return true;\n }\n\n async setupGitHubCopilot(installDir, selectedAgent, spinner = null, preConfiguredSettings = null) {\n // Configure VS Code workspace settings first to avoid UI conflicts with loading spinners\n await this.configureVsCodeSettings(installDir, spinner, preConfiguredSettings);\n \n const chatmodesDir = path.join(installDir, \".github\", \"chatmodes\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n \n await fileManager.ensureDirectory(chatmodesDir);\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n const chatmodePath = path.join(chatmodesDir, `${agentId}.chatmode.md`);\n\n if (agentPath) {\n // Create chat mode file with agent content\n const agentContent = await fileManager.readFile(agentPath);\n const agentTitle = await this.getAgentTitle(agentId, installDir);\n \n // Extract whenToUse for the description\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n let description = `Activates the ${agentTitle} agent persona.`;\n if (yamlMatch) {\n const whenToUseMatch = yamlMatch[1].match(/whenToUse:\\s*\"(.*?)\"/);\n if (whenToUseMatch && whenToUseMatch[1]) {\n description = whenToUseMatch[1];\n }\n }\n \n let chatmodeContent = `---\ndescription: \"${description.replace(/\"/g, '\\\\\"')}\"\ntools: ['changes', 'codebase', 'fetch', 'findTestFiles', 'githubRepo', 'problems', 'usages', 'editFiles', 'runCommands', 'runTasks', 'runTests', 'search', 'searchResults', 'terminalLastCommand', 'terminalSelection', 'testFailure']\n---\n\n`;\n chatmodeContent += agentContent;\n\n await fileManager.writeFile(chatmodePath, chatmodeContent);\n console.log(chalk.green(`āœ“ Created chat mode: ${agentId}.chatmode.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Github Copilot setup complete!`));\n console.log(chalk.dim(`You can now find the BMad agents in the Chat view's mode selector.`));\n\n return true;\n }\n\n async configureVsCodeSettings(installDir, spinner, preConfiguredSettings = null) {\n const vscodeDir = path.join(installDir, \".vscode\");\n const settingsPath = path.join(vscodeDir, \"settings.json\");\n \n await fileManager.ensureDirectory(vscodeDir);\n \n // Read existing settings if they exist\n let existingSettings = {};\n if (await fileManager.pathExists(settingsPath)) {\n try {\n const existingContent = await fileManager.readFile(settingsPath);\n existingSettings = JSON.parse(existingContent);\n console.log(chalk.yellow(\"Found existing .vscode/settings.json. Merging BMad settings...\"));\n } catch (error) {\n console.warn(chalk.yellow(\"Could not parse existing settings.json. Creating new one.\"));\n existingSettings = {};\n }\n }\n \n // Use pre-configured settings if provided, otherwise prompt\n let configChoice;\n if (preConfiguredSettings && preConfiguredSettings.configChoice) {\n configChoice = preConfiguredSettings.configChoice;\n console.log(chalk.dim(`Using pre-configured GitHub Copilot settings: ${configChoice}`));\n } else {\n // Clear any previous output and add spacing to avoid conflicts with loaders\n console.log('\\n'.repeat(2));\n console.log(chalk.blue(\"šŸ”§ Github Copilot Agent Settings Configuration\"));\n console.log(chalk.dim(\"BMad works best with specific VS Code settings for optimal agent experience.\"));\n console.log(''); // Add extra spacing\n \n const response = await inquirer.prompt([\n {\n type: 'list',\n name: 'configChoice',\n message: chalk.yellow('How would you like to configure GitHub Copilot settings?'),\n choices: [\n {\n name: 'Use recommended defaults (fastest setup)',\n value: 'defaults'\n },\n {\n name: 'Configure each setting manually (customize to your preferences)',\n value: 'manual'\n },\n {\n name: 'Skip settings configuration (I\\'ll configure manually later)',\n value: 'skip'\n }\n ],\n default: 'defaults'\n }\n ]);\n configChoice = response.configChoice;\n }\n \n let bmadSettings = {};\n \n if (configChoice === 'skip') {\n console.log(chalk.yellow(\"āš ļø Skipping VS Code settings configuration.\"));\n console.log(chalk.dim(\"You can manually configure these settings in .vscode/settings.json:\"));\n console.log(chalk.dim(\" • chat.agent.enabled: true\"));\n console.log(chalk.dim(\" • chat.agent.maxRequests: 15\"));\n console.log(chalk.dim(\" • github.copilot.chat.agent.runTasks: true\"));\n console.log(chalk.dim(\" • chat.mcp.discovery.enabled: true\"));\n console.log(chalk.dim(\" • github.copilot.chat.agent.autoFix: true\"));\n console.log(chalk.dim(\" • chat.tools.autoApprove: false\"));\n return true;\n }\n \n if (configChoice === 'defaults') {\n // Use recommended defaults\n bmadSettings = {\n \"chat.agent.enabled\": true,\n \"chat.agent.maxRequests\": 15,\n \"github.copilot.chat.agent.runTasks\": true,\n \"chat.mcp.discovery.enabled\": true,\n \"github.copilot.chat.agent.autoFix\": true,\n \"chat.tools.autoApprove\": false\n };\n console.log(chalk.green(\"āœ“ Using recommended BMad defaults for Github Copilot settings\"));\n } else {\n // Manual configuration\n console.log(chalk.blue(\"\\nšŸ“‹ Let's configure each setting for your preferences:\"));\n \n // Pause spinner during manual configuration prompts\n let spinnerWasActive = false;\n if (spinner && spinner.isSpinning) {\n spinner.stop();\n spinnerWasActive = true;\n }\n \n const manualSettings = await inquirer.prompt([\n {\n type: 'input',\n name: 'maxRequests',\n message: 'Maximum requests per agent session (recommended: 15)?',\n default: '15',\n validate: (input) => {\n const num = parseInt(input);\n if (isNaN(num) || num < 1 || num > 50) {\n return 'Please enter a number between 1 and 50';\n }\n return true;\n }\n },\n {\n type: 'confirm',\n name: 'runTasks',\n message: 'Allow agents to run workspace tasks (package.json scripts, etc.)?',\n default: true\n },\n {\n type: 'confirm',\n name: 'mcpDiscovery',\n message: 'Enable MCP (Model Context Protocol) server discovery?',\n default: true\n },\n {\n type: 'confirm',\n name: 'autoFix',\n message: 'Enable automatic error detection and fixing in generated code?',\n default: true\n },\n {\n type: 'confirm',\n name: 'autoApprove',\n message: 'Auto-approve ALL tools without confirmation? (āš ļø EXPERIMENTAL - less secure)',\n default: false\n }\n ]);\n\n // Restart spinner if it was active before prompts\n if (spinner && spinnerWasActive) {\n spinner.start();\n }\n \n bmadSettings = {\n \"chat.agent.enabled\": true, // Always enabled - required for BMad agents\n \"chat.agent.maxRequests\": parseInt(manualSettings.maxRequests),\n \"github.copilot.chat.agent.runTasks\": manualSettings.runTasks,\n \"chat.mcp.discovery.enabled\": manualSettings.mcpDiscovery,\n \"github.copilot.chat.agent.autoFix\": manualSettings.autoFix,\n \"chat.tools.autoApprove\": manualSettings.autoApprove\n };\n \n console.log(chalk.green(\"āœ“ Custom settings configured\"));\n }\n \n // Merge settings (existing settings take precedence to avoid overriding user preferences)\n const mergedSettings = { ...bmadSettings, ...existingSettings };\n \n // Write the updated settings\n await fileManager.writeFile(settingsPath, JSON.stringify(mergedSettings, null, 2));\n \n console.log(chalk.green(\"āœ“ VS Code workspace settings configured successfully\"));\n console.log(chalk.dim(\" Settings written to .vscode/settings.json:\"));\n Object.entries(bmadSettings).forEach(([key, value]) => {\n console.log(chalk.dim(` • ${key}: ${value}`));\n });\n console.log(chalk.dim(\"\"));\n console.log(chalk.dim(\"You can modify these settings anytime in .vscode/settings.json\"));\n }\n}\n\nmodule.exports = new IdeSetup();\n"], ["/BMAD-METHOD/tools/lib/dependency-resolver.js", "const fs = require('fs').promises;\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { extractYamlFromAgent } = require('./yaml-utils');\n\nclass DependencyResolver {\n constructor(rootDir) {\n this.rootDir = rootDir;\n this.bmadCore = path.join(rootDir, 'bmad-core');\n this.common = path.join(rootDir, 'common');\n this.cache = new Map();\n }\n\n async resolveAgentDependencies(agentId) {\n const agentPath = path.join(this.bmadCore, 'agents', `${agentId}.md`);\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML from markdown content with command cleaning\n const yamlContent = extractYamlFromAgent(agentContent, true);\n if (!yamlContent) {\n throw new Error(`No YAML configuration found in agent ${agentId}`);\n }\n \n const agentConfig = yaml.load(yamlContent);\n \n const dependencies = {\n agent: {\n id: agentId,\n path: agentPath,\n content: agentContent,\n config: agentConfig\n },\n resources: []\n };\n\n // Personas are now embedded in agent configs, no need to resolve separately\n\n // Resolve other dependencies\n const depTypes = ['tasks', 'templates', 'checklists', 'data', 'utils'];\n for (const depType of depTypes) {\n const deps = agentConfig.dependencies?.[depType] || [];\n for (const depId of deps) {\n const resource = await this.loadResource(depType, depId);\n if (resource) dependencies.resources.push(resource);\n }\n }\n\n return dependencies;\n }\n\n async resolveTeamDependencies(teamId) {\n const teamPath = path.join(this.bmadCore, 'agent-teams', `${teamId}.yaml`);\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n \n const dependencies = {\n team: {\n id: teamId,\n path: teamPath,\n content: teamContent,\n config: teamConfig\n },\n agents: [],\n resources: new Map() // Use Map to deduplicate resources\n };\n\n // Always add bmad-orchestrator agent first if it's a team\n const bmadAgent = await this.resolveAgentDependencies('bmad-orchestrator');\n dependencies.agents.push(bmadAgent.agent);\n bmadAgent.resources.forEach(res => {\n dependencies.resources.set(res.path, res);\n });\n\n // Resolve all agents in the team\n let agentsToResolve = teamConfig.agents || [];\n \n // Handle wildcard \"*\" - include all agents except bmad-master\n if (agentsToResolve.includes('*')) {\n const allAgents = await this.listAgents();\n // Remove wildcard and add all agents except those already in the list and bmad-master\n agentsToResolve = agentsToResolve.filter(a => a !== '*');\n for (const agent of allAgents) {\n if (!agentsToResolve.includes(agent) && agent !== 'bmad-master') {\n agentsToResolve.push(agent);\n }\n }\n }\n \n for (const agentId of agentsToResolve) {\n if (agentId === 'bmad-orchestrator' || agentId === 'bmad-master') continue; // Already added or excluded\n const agentDeps = await this.resolveAgentDependencies(agentId);\n dependencies.agents.push(agentDeps.agent);\n \n // Add resources with deduplication\n agentDeps.resources.forEach(res => {\n dependencies.resources.set(res.path, res);\n });\n }\n\n // Resolve workflows\n for (const workflowId of teamConfig.workflows || []) {\n const resource = await this.loadResource('workflows', workflowId);\n if (resource) dependencies.resources.set(resource.path, resource);\n }\n\n // Convert Map back to array\n dependencies.resources = Array.from(dependencies.resources.values());\n\n return dependencies;\n }\n\n async loadResource(type, id) {\n const cacheKey = `${type}#${id}`;\n if (this.cache.has(cacheKey)) {\n return this.cache.get(cacheKey);\n }\n\n try {\n let content = null;\n let filePath = null;\n\n // First try bmad-core\n try {\n filePath = path.join(this.bmadCore, type, id);\n content = await fs.readFile(filePath, 'utf8');\n } catch (e) {\n // If not found in bmad-core, try common folder\n try {\n filePath = path.join(this.common, type, id);\n content = await fs.readFile(filePath, 'utf8');\n } catch (e2) {\n // File not found in either location\n }\n }\n\n if (!content) {\n console.warn(`Resource not found: ${type}/${id}`);\n return null;\n }\n\n const resource = {\n type,\n id,\n path: filePath,\n content\n };\n\n this.cache.set(cacheKey, resource);\n return resource;\n } catch (error) {\n console.error(`Error loading resource ${type}/${id}:`, error.message);\n return null;\n }\n }\n\n async listAgents() {\n try {\n const files = await fs.readdir(path.join(this.bmadCore, 'agents'));\n return files\n .filter(f => f.endsWith('.md'))\n .map(f => f.replace('.md', ''));\n } catch (error) {\n return [];\n }\n }\n\n async listTeams() {\n try {\n const files = await fs.readdir(path.join(this.bmadCore, 'agent-teams'));\n return files\n .filter(f => f.endsWith('.yaml'))\n .map(f => f.replace('.yaml', ''));\n } catch (error) {\n return [];\n }\n }\n}\n\nmodule.exports = DependencyResolver;\n"], ["/BMAD-METHOD/tools/installer/bin/bmad.js", "#!/usr/bin/env node\n\nconst { program } = require('commander');\nconst path = require('path');\nconst fs = require('fs').promises;\nconst yaml = require('js-yaml');\nconst chalk = require('chalk');\nconst inquirer = require('inquirer');\n\n// Handle both execution contexts (from root via npx or from installer directory)\nlet version;\nlet installer;\ntry {\n // Try installer context first (when run from tools/installer/)\n version = require('../package.json').version;\n installer = require('../lib/installer');\n} catch (e) {\n // Fall back to root context (when run via npx from GitHub)\n console.log(`Installer context not found (${e.message}), trying root context...`);\n try {\n version = require('../../../package.json').version;\n installer = require('../../../tools/installer/lib/installer');\n } catch (e2) {\n console.error('Error: Could not load required modules. Please ensure you are running from the correct directory.');\n console.error('Debug info:', {\n __dirname,\n cwd: process.cwd(),\n error: e2.message\n });\n process.exit(1);\n }\n}\n\nprogram\n .version(version)\n .description('BMad Method installer - Universal AI agent framework for any domain');\n\nprogram\n .command('install')\n .description('Install BMad Method agents and tools')\n .option('-f, --full', 'Install complete BMad Method')\n .option('-x, --expansion-only', 'Install only expansion packs (no bmad-core)')\n .option('-d, --directory ', 'Installation directory')\n .option('-i, --ide ', 'Configure for specific IDE(s) - can specify multiple (cursor, claude-code, windsurf, trae, roo, cline, gemini, github-copilot, other)')\n .option('-e, --expansion-packs ', 'Install specific expansion packs (can specify multiple)')\n .action(async (options) => {\n try {\n if (!options.full && !options.expansionOnly) {\n // Interactive mode\n const answers = await promptInstallation();\n if (!answers._alreadyInstalled) {\n await installer.install(answers);\n process.exit(0);\n }\n } else {\n // Direct mode\n let installType = 'full';\n if (options.expansionOnly) installType = 'expansion-only';\n\n const config = {\n installType,\n directory: options.directory || '.',\n ides: (options.ide || []).filter(ide => ide !== 'other'),\n expansionPacks: options.expansionPacks || []\n };\n await installer.install(config);\n process.exit(0);\n }\n } catch (error) {\n console.error(chalk.red('Installation failed:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('update')\n .description('Update existing BMad installation')\n .option('--force', 'Force update, overwriting modified files')\n .option('--dry-run', 'Show what would be updated without making changes')\n .action(async () => {\n try {\n await installer.update();\n } catch (error) {\n console.error(chalk.red('Update failed:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('list:expansions')\n .description('List available expansion packs')\n .action(async () => {\n try {\n await installer.listExpansionPacks();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('status')\n .description('Show installation status')\n .action(async () => {\n try {\n await installer.showStatus();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n process.exit(1);\n }\n });\n\nasync function promptInstallation() {\n \n // Display ASCII logo\n console.log(chalk.bold.cyan(`\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•— ā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— \nā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā•ā•ā•šā•ā•ā–ˆā–ˆā•”ā•ā•ā•ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā•”ā–ˆā–ˆā–ˆā–ˆā•”ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•”ā–ˆā–ˆā–ˆā–ˆā•”ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘\nā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā•ā•ā•ā•ā•ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā• ā–ˆā–ˆā•‘ ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ ā•šā•ā• ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā• ā–ˆā–ˆā•‘ ā•šā•ā• ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•\nā•šā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā•ā•šā•ā• ā•šā•ā•ā•šā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā•ā•šā•ā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā• ā•šā•ā• ā•šā•ā•ā•ā•ā•ā• ā•šā•ā•ā•ā•ā•ā• \n `));\n \n console.log(chalk.bold.magenta('šŸš€ Universal AI Agent Framework for Any Domain'));\n console.log(chalk.bold.blue(`✨ Installer v${version}\\n`));\n\n const answers = {};\n\n // Ask for installation directory first\n const { directory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'directory',\n message: 'Enter the full path to your project directory where BMad should be installed:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid project path';\n }\n return true;\n }\n }\n ]);\n answers.directory = directory;\n\n // Detect existing installations\n const installDir = path.resolve(directory);\n const state = await installer.detectInstallationState(installDir);\n \n // Check for existing expansion packs\n const existingExpansionPacks = state.expansionPacks || {};\n \n // Get available expansion packs\n const availableExpansionPacks = await installer.getAvailableExpansionPacks();\n \n // Build choices list\n const choices = [];\n \n // Load core config to get short-title\n const coreConfigPath = path.join(__dirname, '..', '..', '..', 'bmad-core', 'core-config.yaml');\n const coreConfig = yaml.load(await fs.readFile(coreConfigPath, 'utf8'));\n const coreShortTitle = coreConfig['short-title'] || 'BMad Agile Core System';\n \n // Add BMad core option\n let bmadOptionText;\n if (state.type === 'v4_existing') {\n const currentVersion = state.manifest?.version || 'unknown';\n const newVersion = version; // Always use package.json version\n const versionInfo = currentVersion === newVersion \n ? `(v${currentVersion} - reinstall)`\n : `(v${currentVersion} → v${newVersion})`;\n bmadOptionText = `Update ${coreShortTitle} ${versionInfo} .bmad-core`;\n } else {\n bmadOptionText = `${coreShortTitle} (v${version}) .bmad-core`;\n }\n \n choices.push({\n name: bmadOptionText,\n value: 'bmad-core',\n checked: true\n });\n \n // Add expansion pack options\n for (const pack of availableExpansionPacks) {\n const existing = existingExpansionPacks[pack.id];\n let packOptionText;\n \n if (existing) {\n const currentVersion = existing.manifest?.version || 'unknown';\n const newVersion = pack.version;\n const versionInfo = currentVersion === newVersion \n ? `(v${currentVersion} - reinstall)`\n : `(v${currentVersion} → v${newVersion})`;\n packOptionText = `Update ${pack.shortTitle} ${versionInfo} .${pack.id}`;\n } else {\n packOptionText = `${pack.shortTitle} (v${pack.version}) .${pack.id}`;\n }\n \n choices.push({\n name: packOptionText,\n value: pack.id,\n checked: false\n });\n }\n \n // Ask what to install\n const { selectedItems } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedItems',\n message: 'Select what to install/update (use space to select, enter to continue):',\n choices: choices,\n validate: (selected) => {\n if (selected.length === 0) {\n return 'Please select at least one item to install';\n }\n return true;\n }\n }\n ]);\n \n // Process selections\n answers.installType = selectedItems.includes('bmad-core') ? 'full' : 'expansion-only';\n answers.expansionPacks = selectedItems.filter(item => item !== 'bmad-core');\n\n // Ask sharding questions if installing BMad core\n if (selectedItems.includes('bmad-core')) {\n console.log(chalk.cyan('\\nšŸ“‹ Document Organization Settings'));\n console.log(chalk.dim('Configure how your project documentation should be organized.\\n'));\n \n // Ask about PRD sharding\n const { prdSharded } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'prdSharded',\n message: 'Will the PRD (Product Requirements Document) be sharded into multiple files?',\n default: true\n }\n ]);\n answers.prdSharded = prdSharded;\n \n // Ask about architecture sharding\n const { architectureSharded } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'architectureSharded',\n message: 'Will the architecture documentation be sharded into multiple files?',\n default: true\n }\n ]);\n answers.architectureSharded = architectureSharded;\n \n // Show warning if architecture sharding is disabled\n if (!architectureSharded) {\n console.log(chalk.yellow.bold('\\nāš ļø IMPORTANT: Architecture Sharding Disabled'));\n console.log(chalk.yellow('With architecture sharding disabled, you should still create the files listed'));\n console.log(chalk.yellow('in devLoadAlwaysFiles (like coding-standards.md, tech-stack.md, source-tree.md)'));\n console.log(chalk.yellow('as these are used by the dev agent at runtime.'));\n console.log(chalk.yellow('\\nAlternatively, you can remove these files from the devLoadAlwaysFiles list'));\n console.log(chalk.yellow('in your core-config.yaml after installation.'));\n \n const { acknowledge } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'acknowledge',\n message: 'Do you acknowledge this requirement and want to proceed?',\n default: false\n }\n ]);\n \n if (!acknowledge) {\n console.log(chalk.red('Installation cancelled.'));\n process.exit(0);\n }\n }\n }\n\n // Ask for IDE configuration\n let ides = [];\n let ideSelectionComplete = false;\n \n while (!ideSelectionComplete) {\n console.log(chalk.cyan('\\nšŸ› ļø IDE Configuration'));\n console.log(chalk.bold.yellow.bgRed(' āš ļø IMPORTANT: This is a MULTISELECT! Use SPACEBAR to toggle each IDE! '));\n console.log(chalk.bold.magenta('šŸ”ø Use arrow keys to navigate'));\n console.log(chalk.bold.magenta('šŸ”ø Use SPACEBAR to select/deselect IDEs'));\n console.log(chalk.bold.magenta('šŸ”ø Press ENTER when finished selecting\\n'));\n \n const ideResponse = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'ides',\n message: 'Which IDE(s) do you want to configure? (Select with SPACEBAR, confirm with ENTER):',\n choices: [\n { name: 'Cursor', value: 'cursor' },\n { name: 'Claude Code', value: 'claude-code' },\n { name: 'Windsurf', value: 'windsurf' },\n { name: 'Trae', value: 'trae' }, // { name: 'Trae', value: 'trae'}\n { name: 'Roo Code', value: 'roo' },\n { name: 'Cline', value: 'cline' },\n { name: 'Gemini CLI', value: 'gemini' },\n { name: 'Github Copilot', value: 'github-copilot' }\n ]\n }\n ]);\n \n ides = ideResponse.ides;\n\n // Confirm no IDE selection if none selected\n if (ides.length === 0) {\n const { confirmNoIde } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirmNoIde',\n message: chalk.red('āš ļø You have NOT selected any IDEs. This means NO IDE integration will be set up. Is this correct?'),\n default: false\n }\n ]);\n \n if (!confirmNoIde) {\n console.log(chalk.bold.red('\\nšŸ”„ Returning to IDE selection. Remember to use SPACEBAR to select IDEs!\\n'));\n continue; // Go back to IDE selection only\n }\n }\n \n ideSelectionComplete = true;\n }\n\n // Use selected IDEs directly\n answers.ides = ides;\n\n // Configure GitHub Copilot immediately if selected\n if (ides.includes('github-copilot')) {\n console.log(chalk.cyan('\\nšŸ”§ GitHub Copilot Configuration'));\n console.log(chalk.dim('BMad works best with specific VS Code settings for optimal agent experience.\\n'));\n \n const { configChoice } = await inquirer.prompt([\n {\n type: 'list',\n name: 'configChoice',\n message: chalk.yellow('How would you like to configure GitHub Copilot settings?'),\n choices: [\n {\n name: 'Use recommended defaults (fastest setup)',\n value: 'defaults'\n },\n {\n name: 'Configure each setting manually (customize to your preferences)',\n value: 'manual'\n },\n {\n name: 'Skip settings configuration (I\\'ll configure manually later)',\n value: 'skip'\n }\n ],\n default: 'defaults'\n }\n ]);\n \n answers.githubCopilotConfig = { configChoice };\n }\n\n // Ask for web bundles installation\n const { includeWebBundles } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'includeWebBundles',\n message: 'Would you like to include pre-built web bundles? (standalone files for ChatGPT, Claude, Gemini)',\n default: false\n }\n ]);\n\n if (includeWebBundles) {\n console.log(chalk.cyan('\\nšŸ“¦ Web bundles are standalone files perfect for web AI platforms.'));\n console.log(chalk.dim(' You can choose different teams/agents than your IDE installation.\\n'));\n\n const { webBundleType } = await inquirer.prompt([\n {\n type: 'list',\n name: 'webBundleType',\n message: 'What web bundles would you like to include?',\n choices: [\n {\n name: 'All available bundles (agents, teams, expansion packs)',\n value: 'all'\n },\n {\n name: 'Specific teams only',\n value: 'teams'\n },\n {\n name: 'Individual agents only',\n value: 'agents'\n },\n {\n name: 'Custom selection',\n value: 'custom'\n }\n ]\n }\n ]);\n\n answers.webBundleType = webBundleType;\n\n // If specific teams, let them choose which teams\n if (webBundleType === 'teams' || webBundleType === 'custom') {\n const teams = await installer.getAvailableTeams();\n const { selectedTeams } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedTeams',\n message: 'Select team bundles to include:',\n choices: teams.map(t => ({\n name: `${t.icon || 'šŸ“‹'} ${t.name}: ${t.description}`,\n value: t.id,\n checked: webBundleType === 'teams' // Check all if teams-only mode\n })),\n validate: (answer) => {\n if (answer.length < 1) {\n return 'You must select at least one team.';\n }\n return true;\n }\n }\n ]);\n answers.selectedWebBundleTeams = selectedTeams;\n }\n\n // If custom selection, also ask about individual agents\n if (webBundleType === 'custom') {\n const { includeIndividualAgents } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'includeIndividualAgents',\n message: 'Also include individual agent bundles?',\n default: true\n }\n ]);\n answers.includeIndividualAgents = includeIndividualAgents;\n }\n\n const { webBundlesDirectory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'webBundlesDirectory',\n message: 'Enter directory for web bundles:',\n default: `${answers.directory}/web-bundles`,\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid directory path';\n }\n return true;\n }\n }\n ]);\n answers.webBundlesDirectory = webBundlesDirectory;\n }\n\n answers.includeWebBundles = includeWebBundles;\n\n return answers;\n}\n\nprogram.parse(process.argv);\n\n// Show help if no command provided\nif (!process.argv.slice(2).length) {\n program.outputHelp();\n}"], ["/BMAD-METHOD/tools/installer/lib/file-manager.js", "const fs = require(\"fs-extra\");\nconst path = require(\"path\");\nconst crypto = require(\"crypto\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst { createReadStream, createWriteStream, promises: fsPromises } = require('fs');\nconst { pipeline } = require('stream/promises');\nconst resourceLocator = require('./resource-locator');\n\nclass FileManager {\n constructor() {\n this.manifestDir = \".bmad-core\";\n this.manifestFile = \"install-manifest.yaml\";\n }\n\n async copyFile(source, destination) {\n try {\n await fs.ensureDir(path.dirname(destination));\n \n // Use streaming for large files (> 10MB)\n const stats = await fs.stat(source);\n if (stats.size > 10 * 1024 * 1024) {\n await pipeline(\n createReadStream(source),\n createWriteStream(destination)\n );\n } else {\n await fs.copy(source, destination);\n }\n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy ${source}:`), error.message);\n return false;\n }\n }\n\n async copyDirectory(source, destination) {\n try {\n await fs.ensureDir(destination);\n \n // Use streaming copy for large directories\n const files = await resourceLocator.findFiles('**/*', {\n cwd: source,\n nodir: true\n });\n \n // Process files in batches to avoid memory issues\n const batchSize = 50;\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n await Promise.all(\n batch.map(file => \n this.copyFile(\n path.join(source, file),\n path.join(destination, file)\n )\n )\n );\n }\n return true;\n } catch (error) {\n console.error(\n chalk.red(`Failed to copy directory ${source}:`),\n error.message\n );\n return false;\n }\n }\n\n async copyGlobPattern(pattern, sourceDir, destDir, rootValue = null) {\n const files = await resourceLocator.findFiles(pattern, { cwd: sourceDir });\n const copied = [];\n\n for (const file of files) {\n const sourcePath = path.join(sourceDir, file);\n const destPath = path.join(destDir, file);\n\n // Use root replacement if rootValue is provided and file needs it\n const needsRootReplacement = rootValue && (file.endsWith('.md') || file.endsWith('.yaml') || file.endsWith('.yml'));\n \n let success = false;\n if (needsRootReplacement) {\n success = await this.copyFileWithRootReplacement(sourcePath, destPath, rootValue);\n } else {\n success = await this.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n copied.push(file);\n }\n }\n\n return copied;\n }\n\n async calculateFileHash(filePath) {\n try {\n // Use streaming for hash calculation to reduce memory usage\n const stream = createReadStream(filePath);\n const hash = crypto.createHash(\"sha256\");\n \n for await (const chunk of stream) {\n hash.update(chunk);\n }\n \n return hash.digest(\"hex\").slice(0, 16);\n } catch (error) {\n return null;\n }\n }\n\n async createManifest(installDir, config, files) {\n const manifestPath = path.join(\n installDir,\n this.manifestDir,\n this.manifestFile\n );\n\n // Read version from package.json\n let coreVersion = \"unknown\";\n try {\n const packagePath = path.join(__dirname, '..', '..', '..', 'package.json');\n const packageJson = require(packagePath);\n coreVersion = packageJson.version;\n } catch (error) {\n console.warn(\"Could not read version from package.json, using 'unknown'\");\n }\n\n const manifest = {\n version: coreVersion,\n installed_at: new Date().toISOString(),\n install_type: config.installType,\n agent: config.agent || null,\n ides_setup: config.ides || [],\n expansion_packs: config.expansionPacks || [],\n files: [],\n };\n\n // Add file information\n for (const file of files) {\n const filePath = path.join(installDir, file);\n const hash = await this.calculateFileHash(filePath);\n\n manifest.files.push({\n path: file,\n hash: hash,\n modified: false,\n });\n }\n\n // Write manifest\n await fs.ensureDir(path.dirname(manifestPath));\n await fs.writeFile(manifestPath, yaml.dump(manifest, { indent: 2 }));\n\n return manifest;\n }\n\n async readManifest(installDir) {\n const manifestPath = path.join(\n installDir,\n this.manifestDir,\n this.manifestFile\n );\n\n try {\n const content = await fs.readFile(manifestPath, \"utf8\");\n return yaml.load(content);\n } catch (error) {\n return null;\n }\n }\n\n async readExpansionPackManifest(installDir, packId) {\n const manifestPath = path.join(\n installDir,\n `.${packId}`,\n this.manifestFile\n );\n\n try {\n const content = await fs.readFile(manifestPath, \"utf8\");\n return yaml.load(content);\n } catch (error) {\n return null;\n }\n }\n\n async checkModifiedFiles(installDir, manifest) {\n const modified = [];\n\n for (const file of manifest.files) {\n const filePath = path.join(installDir, file.path);\n const currentHash = await this.calculateFileHash(filePath);\n\n if (currentHash && currentHash !== file.hash) {\n modified.push(file.path);\n }\n }\n\n return modified;\n }\n\n async checkFileIntegrity(installDir, manifest) {\n const result = {\n missing: [],\n modified: []\n };\n\n for (const file of manifest.files) {\n const filePath = path.join(installDir, file.path);\n \n // Skip checking the manifest file itself - it will always be different due to timestamps\n if (file.path.endsWith('install-manifest.yaml')) {\n continue;\n }\n \n if (!(await this.pathExists(filePath))) {\n result.missing.push(file.path);\n } else {\n const currentHash = await this.calculateFileHash(filePath);\n if (currentHash && currentHash !== file.hash) {\n result.modified.push(file.path);\n }\n }\n }\n\n return result;\n }\n\n async backupFile(filePath) {\n const backupPath = filePath + \".bak\";\n let counter = 1;\n let finalBackupPath = backupPath;\n\n // Find a unique backup filename\n while (await fs.pathExists(finalBackupPath)) {\n finalBackupPath = `${filePath}.bak${counter}`;\n counter++;\n }\n\n await fs.copy(filePath, finalBackupPath);\n return finalBackupPath;\n }\n\n async ensureDirectory(dirPath) {\n try {\n await fs.ensureDir(dirPath);\n return true;\n } catch (error) {\n throw error;\n }\n }\n\n async pathExists(filePath) {\n return fs.pathExists(filePath);\n }\n\n async readFile(filePath) {\n return fs.readFile(filePath, \"utf8\");\n }\n\n async writeFile(filePath, content) {\n await fs.ensureDir(path.dirname(filePath));\n await fs.writeFile(filePath, content);\n }\n\n async removeDirectory(dirPath) {\n await fs.remove(dirPath);\n }\n\n async createExpansionPackManifest(installDir, packId, config, files) {\n const manifestPath = path.join(\n installDir,\n `.${packId}`,\n this.manifestFile\n );\n\n const manifest = {\n version: config.expansionPackVersion || require(\"../../../package.json\").version,\n installed_at: new Date().toISOString(),\n install_type: config.installType,\n expansion_pack_id: config.expansionPackId,\n expansion_pack_name: config.expansionPackName,\n ides_setup: config.ides || [],\n files: [],\n };\n\n // Add file information\n for (const file of files) {\n const filePath = path.join(installDir, file);\n const hash = await this.calculateFileHash(filePath);\n\n manifest.files.push({\n path: file,\n hash: hash,\n modified: false,\n });\n }\n\n // Write manifest\n await fs.ensureDir(path.dirname(manifestPath));\n await fs.writeFile(manifestPath, yaml.dump(manifest, { indent: 2 }));\n\n return manifest;\n }\n\n async modifyCoreConfig(installDir, config) {\n const coreConfigPath = path.join(installDir, '.bmad-core', 'core-config.yaml');\n \n try {\n // Read the existing core-config.yaml\n const coreConfigContent = await fs.readFile(coreConfigPath, 'utf8');\n const coreConfig = yaml.load(coreConfigContent);\n \n // Modify sharding settings if provided\n if (config.prdSharded !== undefined) {\n coreConfig.prd.prdSharded = config.prdSharded;\n }\n \n if (config.architectureSharded !== undefined) {\n coreConfig.architecture.architectureSharded = config.architectureSharded;\n }\n \n // Write back the modified config\n await fs.writeFile(coreConfigPath, yaml.dump(coreConfig, { indent: 2 }));\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to modify core-config.yaml:`), error.message);\n return false;\n }\n }\n\n async copyFileWithRootReplacement(source, destination, rootValue) {\n try {\n // Check file size to determine if we should stream\n const stats = await fs.stat(source);\n \n if (stats.size > 5 * 1024 * 1024) { // 5MB threshold\n // Use streaming for large files\n const { Transform } = require('stream');\n const replaceStream = new Transform({\n transform(chunk, encoding, callback) {\n const modified = chunk.toString().replace(/\\{root\\}/g, rootValue);\n callback(null, modified);\n }\n });\n \n await this.ensureDirectory(path.dirname(destination));\n await pipeline(\n createReadStream(source, { encoding: 'utf8' }),\n replaceStream,\n createWriteStream(destination, { encoding: 'utf8' })\n );\n } else {\n // Regular approach for smaller files\n const content = await fsPromises.readFile(source, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, rootValue);\n await this.ensureDirectory(path.dirname(destination));\n await fsPromises.writeFile(destination, updatedContent, 'utf8');\n }\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy ${source} with root replacement:`), error.message);\n return false;\n }\n }\n\n async copyDirectoryWithRootReplacement(source, destination, rootValue, fileExtensions = ['.md', '.yaml', '.yml']) {\n try {\n await this.ensureDirectory(destination);\n \n // Get all files in source directory\n const files = await resourceLocator.findFiles('**/*', { \n cwd: source, \n nodir: true \n });\n \n let replacedCount = 0;\n \n for (const file of files) {\n const sourcePath = path.join(source, file);\n const destPath = path.join(destination, file);\n \n // Check if this file type should have {root} replacement\n const shouldReplace = fileExtensions.some(ext => file.endsWith(ext));\n \n if (shouldReplace) {\n if (await this.copyFileWithRootReplacement(sourcePath, destPath, rootValue)) {\n replacedCount++;\n }\n } else {\n // Regular copy for files that don't need replacement\n await this.copyFile(sourcePath, destPath);\n }\n }\n \n if (replacedCount > 0) {\n console.log(chalk.dim(` Processed ${replacedCount} files with {root} replacement`));\n }\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy directory ${source} with root replacement:`), error.message);\n return false;\n }\n }\n}\n\nmodule.exports = new FileManager();\n"], ["/BMAD-METHOD/tools/installer/lib/ide-base-setup.js", "/**\n * Base IDE Setup - Common functionality for all IDE setups\n * Reduces duplication and provides shared methods\n */\n\nconst path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst fileManager = require(\"./file-manager\");\nconst resourceLocator = require(\"./resource-locator\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\n\nclass BaseIdeSetup {\n constructor() {\n this._agentCache = new Map();\n this._pathCache = new Map();\n }\n\n /**\n * Get all agent IDs with caching\n */\n async getAllAgentIds(installDir) {\n const cacheKey = `all-agents:${installDir}`;\n if (this._agentCache.has(cacheKey)) {\n return this._agentCache.get(cacheKey);\n }\n\n const allAgents = new Set();\n \n // Get core agents\n const coreAgents = await this.getCoreAgentIds(installDir);\n coreAgents.forEach(id => allAgents.add(id));\n \n // Get expansion pack agents\n const expansionPacks = await this.getInstalledExpansionPacks(installDir);\n for (const pack of expansionPacks) {\n const packAgents = await this.getExpansionPackAgents(pack.path);\n packAgents.forEach(id => allAgents.add(id));\n }\n \n const result = Array.from(allAgents);\n this._agentCache.set(cacheKey, result);\n return result;\n }\n\n /**\n * Get core agent IDs\n */\n async getCoreAgentIds(installDir) {\n const coreAgents = [];\n const corePaths = [\n path.join(installDir, \".bmad-core\", \"agents\"),\n path.join(installDir, \"bmad-core\", \"agents\")\n ];\n\n for (const agentsDir of corePaths) {\n if (await fileManager.pathExists(agentsDir)) {\n const files = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n coreAgents.push(...files.map(file => path.basename(file, \".md\")));\n break; // Use first found\n }\n }\n\n return coreAgents;\n }\n\n /**\n * Find agent path with caching\n */\n async findAgentPath(agentId, installDir) {\n const cacheKey = `agent-path:${agentId}:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n // Use resource locator for efficient path finding\n let agentPath = await resourceLocator.getAgentPath(agentId);\n \n if (!agentPath) {\n // Check installation-specific paths\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"common\", \"agents\", `${agentId}.md`)\n ];\n\n for (const testPath of possiblePaths) {\n if (await fileManager.pathExists(testPath)) {\n agentPath = testPath;\n break;\n }\n }\n }\n\n if (agentPath) {\n this._pathCache.set(cacheKey, agentPath);\n }\n return agentPath;\n }\n\n /**\n * Get agent title from metadata\n */\n async getAgentTitle(agentId, installDir) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n if (!agentPath) return agentId;\n\n try {\n const content = await fileManager.readFile(agentPath);\n const yamlContent = extractYamlFromAgent(content);\n if (yamlContent) {\n const metadata = yaml.load(yamlContent);\n return metadata.agent_name || agentId;\n }\n } catch (error) {\n // Fallback to agent ID\n }\n return agentId;\n }\n\n /**\n * Get installed expansion packs\n */\n async getInstalledExpansionPacks(installDir) {\n const cacheKey = `expansion-packs:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const expansionPacks = [];\n \n // Check for dot-prefixed expansion packs\n const dotExpansions = await resourceLocator.findFiles(\".bmad-*\", { cwd: installDir });\n \n for (const dotExpansion of dotExpansions) {\n if (dotExpansion !== \".bmad-core\") {\n const packPath = path.join(installDir, dotExpansion);\n const packName = dotExpansion.substring(1); // remove the dot\n expansionPacks.push({\n name: packName,\n path: packPath\n });\n }\n }\n \n // Check other dot folders that have config.yaml\n const allDotFolders = await resourceLocator.findFiles(\".*\", { cwd: installDir });\n for (const folder of allDotFolders) {\n if (!folder.startsWith(\".bmad-\") && folder !== \".bmad-core\") {\n const packPath = path.join(installDir, folder);\n const configPath = path.join(packPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n expansionPacks.push({\n name: folder.substring(1), // remove the dot\n path: packPath\n });\n }\n }\n }\n\n this._pathCache.set(cacheKey, expansionPacks);\n return expansionPacks;\n }\n\n /**\n * Get expansion pack agents\n */\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n return [];\n }\n \n const agentFiles = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n return agentFiles.map(file => path.basename(file, \".md\"));\n }\n\n /**\n * Create agent rule content (shared logic)\n */\n async createAgentRuleContent(agentId, agentPath, installDir, format = 'mdc') {\n const agentContent = await fileManager.readFile(agentPath);\n const agentTitle = await this.getAgentTitle(agentId, installDir);\n const yamlContent = extractYamlFromAgent(agentContent);\n \n let content = \"\";\n \n if (format === 'mdc') {\n // MDC format for Cursor\n content = \"---\\n\";\n content += \"description: \\n\";\n content += \"globs: []\\n\";\n content += \"alwaysApply: false\\n\";\n content += \"---\\n\\n\";\n content += `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n content += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${agentTitle} agent persona.\\n\\n`;\n content += \"## Agent Activation\\n\\n\";\n content += \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n content += \"```yaml\\n\";\n content += yamlContent || agentContent.replace(/^#.*$/m, \"\").trim();\n content += \"\\n```\\n\\n\";\n content += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n content += `The complete agent definition is available in [${relativePath}](mdc:${relativePath}).\\n\\n`;\n content += \"## Usage\\n\\n\";\n content += `When the user types \\`@${agentId}\\`, activate this ${agentTitle} persona and follow all instructions defined in the YAML configuration above.\\n`;\n } else if (format === 'claude') {\n // Claude Code format\n content = `# /${agentId} Command\\n\\n`;\n content += `When this command is used, adopt the following agent persona:\\n\\n`;\n content += agentContent;\n }\n \n return content;\n }\n\n /**\n * Clear all caches\n */\n clearCache() {\n this._agentCache.clear();\n this._pathCache.clear();\n }\n}\n\nmodule.exports = BaseIdeSetup;"], ["/BMAD-METHOD/tools/bump-all-versions.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\nconst args = process.argv.slice(2);\nconst bumpType = args[0] || 'minor'; // default to minor\n\nif (!['major', 'minor', 'patch'].includes(bumpType)) {\n console.log('Usage: node bump-all-versions.js [major|minor|patch]');\n console.log('Default: minor');\n process.exit(1);\n}\n\nfunction bumpVersion(currentVersion, type) {\n const [major, minor, patch] = currentVersion.split('.').map(Number);\n \n switch (type) {\n case 'major':\n return `${major + 1}.0.0`;\n case 'minor':\n return `${major}.${minor + 1}.0`;\n case 'patch':\n return `${major}.${minor}.${patch + 1}`;\n default:\n return currentVersion;\n }\n}\n\nasync function bumpAllVersions() {\n const updatedItems = [];\n \n // First, bump the core version (package.json)\n const packagePath = path.join(__dirname, '..', 'package.json');\n try {\n const packageContent = fs.readFileSync(packagePath, 'utf8');\n const packageJson = JSON.parse(packageContent);\n const oldCoreVersion = packageJson.version || '1.0.0';\n const newCoreVersion = bumpVersion(oldCoreVersion, bumpType);\n \n packageJson.version = newCoreVersion;\n \n fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2) + '\\n');\n \n updatedItems.push({ type: 'core', name: 'BMad Core', oldVersion: oldCoreVersion, newVersion: newCoreVersion });\n console.log(`āœ“ BMad Core (package.json): ${oldCoreVersion} → ${newCoreVersion}`);\n } catch (error) {\n console.error(`āœ— Failed to update BMad Core: ${error.message}`);\n }\n \n // Then, bump all expansion packs\n const expansionPacksDir = path.join(__dirname, '..', 'expansion-packs');\n \n try {\n const entries = fs.readdirSync(expansionPacksDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'README.md') {\n const packId = entry.name;\n const configPath = path.join(expansionPacksDir, packId, 'config.yaml');\n \n if (fs.existsSync(configPath)) {\n try {\n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n const oldVersion = config.version || '1.0.0';\n const newVersion = bumpVersion(oldVersion, bumpType);\n \n config.version = newVersion;\n \n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n \n updatedItems.push({ type: 'expansion', name: packId, oldVersion, newVersion });\n console.log(`āœ“ ${packId}: ${oldVersion} → ${newVersion}`);\n \n } catch (error) {\n console.error(`āœ— Failed to update ${packId}: ${error.message}`);\n }\n }\n }\n }\n \n if (updatedItems.length > 0) {\n const coreCount = updatedItems.filter(i => i.type === 'core').length;\n const expansionCount = updatedItems.filter(i => i.type === 'expansion').length;\n \n console.log(`\\nāœ“ Successfully bumped ${updatedItems.length} item(s) with ${bumpType} version bump`);\n if (coreCount > 0) console.log(` - ${coreCount} core`);\n if (expansionCount > 0) console.log(` - ${expansionCount} expansion pack(s)`);\n \n console.log('\\nNext steps:');\n console.log('1. Test the changes');\n console.log('2. Commit: git add -A && git commit -m \"chore: bump all versions (' + bumpType + ')\"');\n } else {\n console.log('No items found to update');\n }\n \n } catch (error) {\n console.error('Error reading expansion packs directory:', error.message);\n process.exit(1);\n }\n}\n\nbumpAllVersions();"], ["/BMAD-METHOD/tools/upgraders/v3-to-v4-upgrader.js", "const fs = require(\"fs\").promises;\nconst path = require(\"path\");\nconst { glob } = require(\"glob\");\n\n// Dynamic imports for ES modules\nlet chalk, ora, inquirer;\n\n// Initialize ES modules\nasync function initializeModules() {\n chalk = (await import(\"chalk\")).default;\n ora = (await import(\"ora\")).default;\n inquirer = (await import(\"inquirer\")).default;\n}\n\nclass V3ToV4Upgrader {\n constructor() {\n // Constructor remains empty\n }\n\n async upgrade(options = {}) {\n try {\n // Initialize ES modules\n await initializeModules();\n // Keep readline open throughout the process\n process.stdin.resume();\n\n // 1. Welcome message\n console.log(\n chalk.bold(\"\\nWelcome to BMad-Method V3 to V4 Upgrade Tool\\n\")\n );\n console.log(\n \"This tool will help you upgrade your BMad-Method V3 project to V4.\\n\"\n );\n console.log(chalk.cyan(\"What this tool does:\"));\n console.log(\"- Creates a backup of your V3 files (.bmad-v3-backup/)\");\n console.log(\"- Installs the new V4 .bmad-core structure\");\n console.log(\n \"- Preserves your PRD, Architecture, and Stories in the new format\\n\"\n );\n console.log(chalk.yellow(\"What this tool does NOT do:\"));\n console.log(\n \"- Modify your document content (use doc-migration-task after upgrade)\"\n );\n console.log(\"- Touch any files outside bmad-agent/ and docs/\\n\");\n\n // 2. Get project path\n const projectPath = await this.getProjectPath(options.projectPath);\n\n // 3. Validate V3 structure\n const validation = await this.validateV3Project(projectPath);\n if (!validation.isValid) {\n console.error(\n chalk.red(\"\\nError: This doesn't appear to be a V3 project.\")\n );\n console.error(\"Expected to find:\");\n console.error(\"- bmad-agent/ directory\");\n console.error(\"- docs/ directory\\n\");\n console.error(\n \"Please check you're in the correct directory and try again.\"\n );\n return;\n }\n\n // 4. Pre-flight check\n const analysis = await this.analyzeProject(projectPath);\n await this.showPreflightCheck(analysis, options);\n\n if (!options.dryRun) {\n const { confirm } = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirm\",\n message: \"Continue with upgrade?\",\n default: true,\n },\n ]);\n\n if (!confirm) {\n console.log(\"Upgrade cancelled.\");\n return;\n }\n }\n\n // 5. Create backup\n if (options.backup !== false && !options.dryRun) {\n await this.createBackup(projectPath);\n }\n\n // 6. Install V4 structure\n if (!options.dryRun) {\n await this.installV4Structure(projectPath);\n }\n\n // 7. Migrate documents\n if (!options.dryRun) {\n await this.migrateDocuments(projectPath, analysis);\n }\n\n // 8. Setup IDE\n if (!options.dryRun) {\n await this.setupIDE(projectPath, options.ides);\n }\n\n // 9. Show completion report\n this.showCompletionReport(projectPath, analysis);\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red(\"\\nUpgrade error:\"), error.message);\n process.exit(1);\n }\n }\n\n async getProjectPath(providedPath) {\n if (providedPath) {\n return path.resolve(providedPath);\n }\n\n const { projectPath } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"projectPath\",\n message: \"Please enter the path to your V3 project:\",\n default: process.cwd(),\n },\n ]);\n\n return path.resolve(projectPath);\n }\n\n async validateV3Project(projectPath) {\n const spinner = ora(\"Validating project structure...\").start();\n\n try {\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n const docsPath = path.join(projectPath, \"docs\");\n\n const hasBmadAgent = await this.pathExists(bmadAgentPath);\n const hasDocs = await this.pathExists(docsPath);\n\n if (hasBmadAgent) {\n spinner.text = \"āœ“ Found bmad-agent/ directory\";\n console.log(chalk.green(\"\\nāœ“ Found bmad-agent/ directory\"));\n }\n\n if (hasDocs) {\n console.log(chalk.green(\"āœ“ Found docs/ directory\"));\n }\n\n const isValid = hasBmadAgent && hasDocs;\n\n if (isValid) {\n spinner.succeed(\"This appears to be a valid V3 project\");\n } else {\n spinner.fail(\"Invalid V3 project structure\");\n }\n\n return { isValid, hasBmadAgent, hasDocs };\n } catch (error) {\n spinner.fail(\"Validation failed\");\n throw error;\n }\n }\n\n async analyzeProject(projectPath) {\n const docsPath = path.join(projectPath, \"docs\");\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n\n // Find PRD\n const prdCandidates = [\"prd.md\", \"PRD.md\", \"product-requirements.md\"];\n let prdFile = null;\n for (const candidate of prdCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n prdFile = candidate;\n break;\n }\n }\n\n // Find Architecture\n const archCandidates = [\n \"architecture.md\",\n \"Architecture.md\",\n \"technical-architecture.md\",\n ];\n let archFile = null;\n for (const candidate of archCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n archFile = candidate;\n break;\n }\n }\n\n // Find Front-end Architecture (V3 specific)\n const frontEndCandidates = [\n \"front-end-architecture.md\",\n \"frontend-architecture.md\",\n \"ui-architecture.md\",\n ];\n let frontEndArchFile = null;\n for (const candidate of frontEndCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n frontEndArchFile = candidate;\n break;\n }\n }\n\n // Find UX/UI spec\n const uxSpecCandidates = [\n \"ux-ui-spec.md\",\n \"ux-ui-specification.md\",\n \"ui-spec.md\",\n \"ux-spec.md\",\n ];\n let uxSpecFile = null;\n for (const candidate of uxSpecCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxSpecFile = candidate;\n break;\n }\n }\n\n // Find v0 prompt or UX prompt\n const uxPromptCandidates = [\n \"v0-prompt.md\",\n \"ux-prompt.md\",\n \"ui-prompt.md\",\n \"design-prompt.md\",\n ];\n let uxPromptFile = null;\n for (const candidate of uxPromptCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxPromptFile = candidate;\n break;\n }\n }\n\n // Find epic files\n const epicFiles = await glob(\"epic*.md\", { cwd: docsPath });\n\n // Find story files\n const storiesPath = path.join(docsPath, \"stories\");\n let storyFiles = [];\n if (await this.pathExists(storiesPath)) {\n storyFiles = await glob(\"*.md\", { cwd: storiesPath });\n }\n\n // Count custom files in bmad-agent\n const bmadAgentFiles = await glob(\"**/*.md\", {\n cwd: bmadAgentPath,\n ignore: [\"node_modules/**\"],\n });\n\n return {\n prdFile,\n archFile,\n frontEndArchFile,\n uxSpecFile,\n uxPromptFile,\n epicFiles,\n storyFiles,\n customFileCount: bmadAgentFiles.length,\n };\n }\n\n async showPreflightCheck(analysis, options) {\n console.log(chalk.bold(\"\\nProject Analysis:\"));\n console.log(\n `- PRD found: ${\n analysis.prdFile\n ? `docs/${analysis.prdFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- Architecture found: ${\n analysis.archFile\n ? `docs/${analysis.archFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n if (analysis.frontEndArchFile) {\n console.log(\n `- Front-end Architecture found: docs/${analysis.frontEndArchFile}`\n );\n }\n console.log(\n `- UX/UI Spec found: ${\n analysis.uxSpecFile\n ? `docs/${analysis.uxSpecFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- UX/Design Prompt found: ${\n analysis.uxPromptFile\n ? `docs/${analysis.uxPromptFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- Epic files found: ${analysis.epicFiles.length} files (epic*.md)`\n );\n console.log(\n `- Stories found: ${analysis.storyFiles.length} files in docs/stories/`\n );\n console.log(`- Custom files in bmad-agent/: ${analysis.customFileCount}`);\n\n if (!options.dryRun) {\n console.log(\"\\nThe following will be backed up to .bmad-v3-backup/:\");\n console.log(\"- bmad-agent/ (entire directory)\");\n console.log(\"- docs/ (entire directory)\");\n\n if (analysis.epicFiles.length > 0) {\n console.log(\n chalk.green(\n \"\\nNote: Epic files found! They will be placed in docs/prd/ with an index.md file.\"\n )\n );\n console.log(\n chalk.green(\n \"Since epic files exist, you won't need to shard the PRD after upgrade.\"\n )\n );\n }\n }\n }\n\n async createBackup(projectPath) {\n const spinner = ora(\"Creating backup...\").start();\n\n try {\n const backupPath = path.join(projectPath, \".bmad-v3-backup\");\n\n // Check if backup already exists\n if (await this.pathExists(backupPath)) {\n spinner.fail(\"Backup directory already exists\");\n console.error(\n chalk.red(\n \"\\nError: Backup directory .bmad-v3-backup/ already exists.\"\n )\n );\n console.error(\"\\nThis might mean an upgrade was already attempted.\");\n console.error(\n \"Please remove or rename the existing backup and try again.\"\n );\n throw new Error(\"Backup already exists\");\n }\n\n // Create backup directory\n await fs.mkdir(backupPath, { recursive: true });\n spinner.text = \"āœ“ Created .bmad-v3-backup/\";\n console.log(chalk.green(\"\\nāœ“ Created .bmad-v3-backup/\"));\n\n // Move bmad-agent\n const bmadAgentSrc = path.join(projectPath, \"bmad-agent\");\n const bmadAgentDest = path.join(backupPath, \"bmad-agent\");\n await fs.rename(bmadAgentSrc, bmadAgentDest);\n console.log(chalk.green(\"āœ“ Moved bmad-agent/ to backup\"));\n\n // Move docs\n const docsSrc = path.join(projectPath, \"docs\");\n const docsDest = path.join(backupPath, \"docs\");\n await fs.rename(docsSrc, docsDest);\n console.log(chalk.green(\"āœ“ Moved docs/ to backup\"));\n\n spinner.succeed(\"Backup created successfully\");\n } catch (error) {\n spinner.fail(\"Backup failed\");\n throw error;\n }\n }\n\n async installV4Structure(projectPath) {\n const spinner = ora(\"Installing V4 structure...\").start();\n\n try {\n // Get the source bmad-core directory (without dot prefix)\n const sourcePath = path.join(__dirname, \"..\", \"..\", \"bmad-core\");\n const destPath = path.join(projectPath, \".bmad-core\");\n\n // Copy .bmad-core\n await this.copyDirectory(sourcePath, destPath);\n spinner.text = \"āœ“ Copied fresh .bmad-core/ directory from V4\";\n console.log(\n chalk.green(\"\\nāœ“ Copied fresh .bmad-core/ directory from V4\")\n );\n\n // Create docs directory\n const docsPath = path.join(projectPath, \"docs\");\n await fs.mkdir(docsPath, { recursive: true });\n console.log(chalk.green(\"āœ“ Created new docs/ directory\"));\n\n // Create install manifest for future updates\n await this.createInstallManifest(projectPath);\n console.log(chalk.green(\"āœ“ Created install manifest\"));\n\n console.log(\n chalk.yellow(\n \"\\nNote: Your V3 bmad-agent content has been backed up and NOT migrated.\"\n )\n );\n console.log(\n chalk.yellow(\n \"The new V4 agents are completely different and look for different file structures.\"\n )\n );\n\n spinner.succeed(\"V4 structure installed successfully\");\n } catch (error) {\n spinner.fail(\"V4 installation failed\");\n throw error;\n }\n }\n\n async migrateDocuments(projectPath, analysis) {\n const spinner = ora(\"Migrating your project documents...\").start();\n\n try {\n const backupDocsPath = path.join(projectPath, \".bmad-v3-backup\", \"docs\");\n const newDocsPath = path.join(projectPath, \"docs\");\n let copiedCount = 0;\n\n // Copy PRD\n if (analysis.prdFile) {\n const src = path.join(backupDocsPath, analysis.prdFile);\n const dest = path.join(newDocsPath, analysis.prdFile);\n await fs.copyFile(src, dest);\n console.log(chalk.green(`\\nāœ“ Copied PRD to docs/${analysis.prdFile}`));\n copiedCount++;\n }\n\n // Copy Architecture\n if (analysis.archFile) {\n const src = path.join(backupDocsPath, analysis.archFile);\n const dest = path.join(newDocsPath, analysis.archFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(`āœ“ Copied Architecture to docs/${analysis.archFile}`)\n );\n copiedCount++;\n }\n\n // Copy Front-end Architecture if exists\n if (analysis.frontEndArchFile) {\n const src = path.join(backupDocsPath, analysis.frontEndArchFile);\n const dest = path.join(newDocsPath, analysis.frontEndArchFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(\n `āœ“ Copied Front-end Architecture to docs/${analysis.frontEndArchFile}`\n )\n );\n console.log(\n chalk.yellow(\n \"Note: V4 uses a single full-stack-architecture.md - use doc-migration-task to merge\"\n )\n );\n copiedCount++;\n }\n\n // Copy UX/UI Spec if exists\n if (analysis.uxSpecFile) {\n const src = path.join(backupDocsPath, analysis.uxSpecFile);\n const dest = path.join(newDocsPath, analysis.uxSpecFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(`āœ“ Copied UX/UI Spec to docs/${analysis.uxSpecFile}`)\n );\n copiedCount++;\n }\n\n // Copy UX/Design Prompt if exists\n if (analysis.uxPromptFile) {\n const src = path.join(backupDocsPath, analysis.uxPromptFile);\n const dest = path.join(newDocsPath, analysis.uxPromptFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(\n `āœ“ Copied UX/Design Prompt to docs/${analysis.uxPromptFile}`\n )\n );\n copiedCount++;\n }\n\n // Copy stories\n if (analysis.storyFiles.length > 0) {\n const storiesDir = path.join(newDocsPath, \"stories\");\n await fs.mkdir(storiesDir, { recursive: true });\n\n for (const storyFile of analysis.storyFiles) {\n const src = path.join(backupDocsPath, \"stories\", storyFile);\n const dest = path.join(storiesDir, storyFile);\n await fs.copyFile(src, dest);\n }\n console.log(\n chalk.green(\n `āœ“ Copied ${analysis.storyFiles.length} story files to docs/stories/`\n )\n );\n copiedCount += analysis.storyFiles.length;\n }\n\n // Copy epic files to prd subfolder\n if (analysis.epicFiles.length > 0) {\n const prdDir = path.join(newDocsPath, \"prd\");\n await fs.mkdir(prdDir, { recursive: true });\n\n for (const epicFile of analysis.epicFiles) {\n const src = path.join(backupDocsPath, epicFile);\n const dest = path.join(prdDir, epicFile);\n await fs.copyFile(src, dest);\n }\n console.log(\n chalk.green(\n `āœ“ Found and copied ${analysis.epicFiles.length} epic files to docs/prd/`\n )\n );\n\n // Create index.md for the prd folder\n await this.createPrdIndex(projectPath, analysis);\n console.log(chalk.green(\"āœ“ Created index.md in docs/prd/\"));\n\n console.log(\n chalk.green(\n \"\\nNote: Epic files detected! These are compatible with V4 and have been copied.\"\n )\n );\n console.log(\n chalk.green(\n \"You won't need to shard the PRD since epics already exist.\"\n )\n );\n copiedCount += analysis.epicFiles.length;\n }\n\n spinner.succeed(`Migrated ${copiedCount} documents successfully`);\n } catch (error) {\n spinner.fail(\"Document migration failed\");\n throw error;\n }\n }\n\n async setupIDE(projectPath, selectedIdes) {\n // Use the IDE selections passed from the installer\n if (!selectedIdes || selectedIdes.length === 0) {\n console.log(chalk.dim(\"No IDE setup requested - skipping\"));\n return;\n }\n\n const ideSetup = require(\"../installer/lib/ide-setup\");\n const spinner = ora(\"Setting up IDE rules for all agents...\").start();\n\n try {\n const ideMessages = {\n cursor: \"Rules created in .cursor/rules/\",\n \"claude-code\": \"Commands created in .claude/commands/BMad/\",\n windsurf: \"Rules created in .windsurf/rules/\",\n trae: \"Rules created in.trae/rules/\",\n roo: \"Custom modes created in .roomodes\",\n cline: \"Rules created in .clinerules/\",\n };\n\n // Setup each selected IDE\n for (const ide of selectedIdes) {\n spinner.text = `Setting up ${ide}...`;\n await ideSetup.setup(ide, projectPath);\n console.log(chalk.green(`\\nāœ“ ${ideMessages[ide]}`));\n }\n\n spinner.succeed(`IDE setup complete for ${selectedIdes.length} IDE(s)!`);\n } catch (error) {\n spinner.fail(\"IDE setup failed\");\n console.error(\n chalk.yellow(\"IDE setup failed, but upgrade is complete.\")\n );\n }\n }\n\n showCompletionReport(projectPath, analysis) {\n console.log(chalk.bold.green(\"\\nāœ“ Upgrade Complete!\\n\"));\n console.log(chalk.bold(\"Summary:\"));\n console.log(`- V3 files backed up to: .bmad-v3-backup/`);\n console.log(`- V4 structure installed: .bmad-core/ (fresh from V4)`);\n\n const totalDocs =\n (analysis.prdFile ? 1 : 0) +\n (analysis.archFile ? 1 : 0) +\n (analysis.frontEndArchFile ? 1 : 0) +\n (analysis.uxSpecFile ? 1 : 0) +\n (analysis.uxPromptFile ? 1 : 0) +\n analysis.storyFiles.length;\n console.log(\n `- Documents migrated: ${totalDocs} files${\n analysis.epicFiles.length > 0\n ? ` + ${analysis.epicFiles.length} epics`\n : \"\"\n }`\n );\n\n console.log(chalk.bold(\"\\nImportant Changes:\"));\n console.log(\n \"- The V4 agents (sm, dev, etc.) expect different file structures than V3\"\n );\n console.log(\n \"- Your V3 bmad-agent content was NOT migrated (it's incompatible)\"\n );\n if (analysis.epicFiles.length > 0) {\n console.log(\n \"- Epic files were found and copied - no PRD sharding needed!\"\n );\n }\n if (analysis.frontEndArchFile) {\n console.log(\n \"- Front-end architecture found - V4 uses full-stack-architecture.md, migration needed\"\n );\n }\n if (analysis.uxSpecFile || analysis.uxPromptFile) {\n console.log(\n \"- UX/UI design files found and copied - ready for use with V4\"\n );\n }\n\n console.log(chalk.bold(\"\\nNext Steps:\"));\n console.log(\"1. Review your documents in the new docs/ folder\");\n console.log(\n \"2. Use @bmad-master agent to run the doc-migration-task to align your documents with V4 templates\"\n );\n if (analysis.epicFiles.length === 0) {\n console.log(\n \"3. Use @bmad-master agent to shard the PRD to create epic files\"\n );\n }\n\n console.log(\n chalk.dim(\n \"\\nYour V3 backup is preserved in .bmad-v3-backup/ and can be restored if needed.\"\n )\n );\n }\n\n async pathExists(filePath) {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n async copyDirectory(src, dest) {\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await this.copyDirectory(srcPath, destPath);\n } else {\n await fs.copyFile(srcPath, destPath);\n }\n }\n }\n\n async createPrdIndex(projectPath, analysis) {\n const prdIndexPath = path.join(projectPath, \"docs\", \"prd\", \"index.md\");\n const prdPath = path.join(\n projectPath,\n \"docs\",\n analysis.prdFile || \"prd.md\"\n );\n\n let indexContent = \"# Product Requirements Document\\n\\n\";\n\n // Try to read the PRD to get the title and intro content\n if (analysis.prdFile && (await this.pathExists(prdPath))) {\n try {\n const prdContent = await fs.readFile(prdPath, \"utf8\");\n const lines = prdContent.split(\"\\n\");\n\n // Find the first heading\n const titleMatch = lines.find((line) => line.startsWith(\"# \"));\n if (titleMatch) {\n indexContent = titleMatch + \"\\n\\n\";\n }\n\n // Get any content before the first ## section\n let introContent = \"\";\n let foundFirstSection = false;\n for (const line of lines) {\n if (line.startsWith(\"## \")) {\n foundFirstSection = true;\n break;\n }\n if (!line.startsWith(\"# \")) {\n introContent += line + \"\\n\";\n }\n }\n\n if (introContent.trim()) {\n indexContent += introContent.trim() + \"\\n\\n\";\n }\n } catch (error) {\n // If we can't read the PRD, just use default content\n }\n }\n\n // Add sections list\n indexContent += \"## Sections\\n\\n\";\n\n // Sort epic files for consistent ordering\n const sortedEpics = [...analysis.epicFiles].sort();\n\n for (const epicFile of sortedEpics) {\n // Extract epic name from filename\n const epicName = epicFile\n .replace(/\\.md$/, \"\")\n .replace(/^epic-?/i, \"\")\n .replace(/-/g, \" \")\n .replace(/^\\d+\\s*/, \"\") // Remove leading numbers\n .trim();\n\n const displayName = epicName.charAt(0).toUpperCase() + epicName.slice(1);\n indexContent += `- [${\n displayName || epicFile.replace(\".md\", \"\")\n }](./${epicFile})\\n`;\n }\n\n await fs.writeFile(prdIndexPath, indexContent);\n }\n\n async createInstallManifest(projectPath) {\n const fileManager = require(\"../installer/lib/file-manager\");\n const { glob } = require(\"glob\");\n\n // Get all files in .bmad-core for the manifest\n const bmadCorePath = path.join(projectPath, \".bmad-core\");\n const files = await glob(\"**/*\", {\n cwd: bmadCorePath,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n\n // Prepend .bmad-core/ to file paths for manifest\n const manifestFiles = files.map((file) => path.join(\".bmad-core\", file));\n\n const config = {\n installType: \"full\",\n agent: null,\n ide: null, // Will be set if IDE setup is done later\n };\n\n await fileManager.createManifest(projectPath, config, manifestFiles);\n }\n}\n\nmodule.exports = V3ToV4Upgrader;\n"], ["/BMAD-METHOD/tools/bump-expansion-version.js", "#!/usr/bin/env node\n\n// Load required modules\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\n// Parse CLI arguments\nconst args = process.argv.slice(2);\nconst packId = args[0];\nconst bumpType = args[1] || 'minor';\n\n// Validate arguments\nif (!packId || args.length > 2) {\n console.log('Usage: node bump-expansion-version.js [major|minor|patch]');\n console.log('Default: minor');\n console.log('Example: node bump-expansion-version.js bmad-creator-tools patch');\n process.exit(1);\n}\n\nif (!['major', 'minor', 'patch'].includes(bumpType)) {\n console.error('Error: Bump type must be major, minor, or patch');\n process.exit(1);\n}\n\n// Version bump logic\nfunction bumpVersion(currentVersion, type) {\n const [major, minor, patch] = currentVersion.split('.').map(Number);\n\n switch (type) {\n case 'major': return `${major + 1}.0.0`;\n case 'minor': return `${major}.${minor + 1}.0`;\n case 'patch': return `${major}.${minor}.${patch + 1}`;\n default: return currentVersion;\n }\n}\n\n// Main function to bump version\nasync function updateVersion() {\n const configPath = path.join(__dirname, '..', 'expansion-packs', packId, 'config.yaml');\n\n // Check if config exists\n if (!fs.existsSync(configPath)) {\n console.error(`Error: Expansion pack '${packId}' not found`);\n console.log('\\nAvailable expansion packs:');\n\n const packsDir = path.join(__dirname, '..', 'expansion-packs');\n const entries = fs.readdirSync(packsDir, { withFileTypes: true });\n\n entries.forEach(entry => {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n console.log(` - ${entry.name}`);\n }\n });\n\n process.exit(1);\n }\n\n try {\n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n\n const oldVersion = config.version || '1.0.0';\n const newVersion = bumpVersion(oldVersion, bumpType);\n\n config.version = newVersion;\n\n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n\n console.log(`āœ“ ${packId}: ${oldVersion} → ${newVersion}`);\n console.log(`\\nāœ“ Successfully bumped ${packId} with ${bumpType} version bump`);\n console.log('\\nNext steps:');\n console.log(`1. Test the changes`);\n console.log(`2. Commit: git add -A && git commit -m \"chore: bump ${packId} version (${bumpType})\"`);\n\n } catch (error) {\n console.error('Error updating version:', error.message);\n process.exit(1);\n }\n}\n\nupdateVersion();\n"], ["/BMAD-METHOD/tools/cli.js", "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst WebBuilder = require('./builders/web-builder');\nconst V3ToV4Upgrader = require('./upgraders/v3-to-v4-upgrader');\nconst IdeSetup = require('./installer/lib/ide-setup');\nconst path = require('path');\n\nconst program = new Command();\n\nprogram\n .name('bmad-build')\n .description('BMad-Method build tool for creating web bundles')\n .version('4.0.0');\n\nprogram\n .command('build')\n .description('Build web bundles for agents and teams')\n .option('-a, --agents-only', 'Build only agent bundles')\n .option('-t, --teams-only', 'Build only team bundles')\n .option('-e, --expansions-only', 'Build only expansion pack bundles')\n .option('--no-expansions', 'Skip building expansion packs')\n .option('--no-clean', 'Skip cleaning output directories')\n .action(async (options) => {\n const builder = new WebBuilder({\n rootDir: process.cwd()\n });\n\n try {\n if (options.clean) {\n console.log('Cleaning output directories...');\n await builder.cleanOutputDirs();\n }\n\n if (options.expansionsOnly) {\n console.log('Building expansion pack bundles...');\n await builder.buildAllExpansionPacks({ clean: false });\n } else {\n if (!options.teamsOnly) {\n console.log('Building agent bundles...');\n await builder.buildAgents();\n }\n\n if (!options.agentsOnly) {\n console.log('Building team bundles...');\n await builder.buildTeams();\n }\n\n if (!options.noExpansions) {\n console.log('Building expansion pack bundles...');\n await builder.buildAllExpansionPacks({ clean: false });\n }\n }\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error('Build failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('build:expansions')\n .description('Build web bundles for all expansion packs')\n .option('--expansion ', 'Build specific expansion pack only')\n .option('--no-clean', 'Skip cleaning output directories')\n .action(async (options) => {\n const builder = new WebBuilder({\n rootDir: process.cwd()\n });\n\n try {\n if (options.expansion) {\n console.log(`Building expansion pack: ${options.expansion}`);\n await builder.buildExpansionPack(options.expansion, { clean: options.clean });\n } else {\n console.log('Building all expansion packs...');\n await builder.buildAllExpansionPacks({ clean: options.clean });\n }\n\n console.log('Expansion pack build completed successfully!');\n } catch (error) {\n console.error('Expansion pack build failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('list:agents')\n .description('List all available agents')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n const agents = await builder.resolver.listAgents();\n console.log('Available agents:');\n agents.forEach(agent => console.log(` - ${agent}`));\n });\n\nprogram\n .command('list:expansions')\n .description('List all available expansion packs')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n const expansions = await builder.listExpansionPacks();\n console.log('Available expansion packs:');\n expansions.forEach(expansion => console.log(` - ${expansion}`));\n });\n\nprogram\n .command('validate')\n .description('Validate agent and team configurations')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n try {\n // Validate by attempting to build all agents and teams\n const agents = await builder.resolver.listAgents();\n const teams = await builder.resolver.listTeams();\n \n console.log('Validating agents...');\n for (const agent of agents) {\n await builder.resolver.resolveAgentDependencies(agent);\n console.log(` āœ“ ${agent}`);\n }\n \n console.log('\\nValidating teams...');\n for (const team of teams) {\n await builder.resolver.resolveTeamDependencies(team);\n console.log(` āœ“ ${team}`);\n }\n \n console.log('\\nAll configurations are valid!');\n } catch (error) {\n console.error('Validation failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('upgrade')\n .description('Upgrade a BMad-Method V3 project to V4')\n .option('-p, --project ', 'Path to V3 project (defaults to current directory)')\n .option('--dry-run', 'Show what would be changed without making changes')\n .option('--no-backup', 'Skip creating backup (not recommended)')\n .action(async (options) => {\n const upgrader = new V3ToV4Upgrader();\n await upgrader.upgrade({\n projectPath: options.project,\n dryRun: options.dryRun,\n backup: options.backup\n });\n });\n\nprogram\n .command('flatten')\n .description('Flatten codebase to XML format')\n .option('-o, --output ', 'Output file path', 'flattened-codebase.xml')\n .action(async (options) => {\n const flattener = require('./flattener/main');\n await flattener.parseAsync(['flatten', '--output', options.output], { from: 'user' });\n });\n\nprogram.parse();"], ["/BMAD-METHOD/tools/flattener/main.js", "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst fs = require('fs-extra');\nconst path = require('node:path');\nconst { glob } = require('glob');\nconst { minimatch } = require('minimatch');\n\n/**\n * Recursively discover all files in a directory\n * @param {string} rootDir - The root directory to scan\n * @returns {Promise} Array of file paths\n */\nasync function discoverFiles(rootDir) {\n try {\n const gitignorePath = path.join(rootDir, '.gitignore');\n const gitignorePatterns = await parseGitignore(gitignorePath);\n\n // Common gitignore patterns that should always be ignored\n const commonIgnorePatterns = [\n // Version control\n '.git/**',\n '.svn/**',\n '.hg/**',\n '.bzr/**',\n\n // Dependencies\n 'node_modules/**',\n 'bower_components/**',\n 'vendor/**',\n 'packages/**',\n\n // Build outputs\n 'build/**',\n 'dist/**',\n 'out/**',\n 'target/**',\n 'bin/**',\n 'obj/**',\n 'release/**',\n 'debug/**',\n\n // Environment and config\n '.env',\n '.env.*',\n '*.env',\n '.config',\n\n // Logs\n 'logs/**',\n '*.log',\n 'npm-debug.log*',\n 'yarn-debug.log*',\n 'yarn-error.log*',\n 'lerna-debug.log*',\n\n // Coverage and testing\n 'coverage/**',\n '.nyc_output/**',\n '.coverage/**',\n 'test-results/**',\n 'junit.xml',\n\n // Cache directories\n '.cache/**',\n '.tmp/**',\n '.temp/**',\n 'tmp/**',\n 'temp/**',\n '.sass-cache/**',\n '.eslintcache',\n '.stylelintcache',\n\n // OS generated files\n '.DS_Store',\n '.DS_Store?',\n '._*',\n '.Spotlight-V100',\n '.Trashes',\n 'ehthumbs.db',\n 'Thumbs.db',\n 'desktop.ini',\n\n // IDE and editor files\n '.vscode/**',\n '.idea/**',\n '*.swp',\n '*.swo',\n '*~',\n '.project',\n '.classpath',\n '.settings/**',\n '*.sublime-project',\n '*.sublime-workspace',\n\n // Package manager files\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Pipfile.lock',\n\n // Runtime and compiled files\n '*.pyc',\n '*.pyo',\n '*.pyd',\n '__pycache__/**',\n '*.class',\n '*.jar',\n '*.war',\n '*.ear',\n '*.o',\n '*.so',\n '*.dll',\n '*.exe',\n\n // Documentation build\n '_site/**',\n '.jekyll-cache/**',\n '.jekyll-metadata',\n\n // Flattener specific outputs\n 'flattened-codebase.xml',\n 'repomix-output.xml'\n ];\n\n const combinedIgnores = [\n ...gitignorePatterns,\n ...commonIgnorePatterns\n ];\n\n // Use glob to recursively find all files, excluding common ignore patterns\n const files = await glob('**/*', {\n cwd: rootDir,\n nodir: true, // Only files, not directories\n dot: true, // Include hidden files\n follow: false, // Don't follow symbolic links\n ignore: combinedIgnores\n });\n\n return files.map(file => path.resolve(rootDir, file));\n } catch (error) {\n console.error('Error discovering files:', error.message);\n return [];\n }\n}\n\n/**\n * Parse .gitignore file and return ignore patterns\n * @param {string} gitignorePath - Path to .gitignore file\n * @returns {Promise} Array of ignore patterns\n */\nasync function parseGitignore(gitignorePath) {\n try {\n if (!await fs.pathExists(gitignorePath)) {\n return [];\n }\n\n const content = await fs.readFile(gitignorePath, 'utf8');\n return content\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line && !line.startsWith('#')) // Remove empty lines and comments\n .map(pattern => {\n // Convert gitignore patterns to glob patterns\n if (pattern.endsWith('/')) {\n return pattern + '**';\n }\n return pattern;\n });\n } catch (error) {\n console.error('Error parsing .gitignore:', error.message);\n return [];\n }\n}\n\n/**\n * Check if a file is binary using file command and heuristics\n * @param {string} filePath - Path to the file\n * @returns {Promise} True if file is binary\n */\nasync function isBinaryFile(filePath) {\n try {\n // First check by file extension\n const binaryExtensions = [\n '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.ico', '.svg',\n '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',\n '.zip', '.tar', '.gz', '.rar', '.7z',\n '.exe', '.dll', '.so', '.dylib',\n '.mp3', '.mp4', '.avi', '.mov', '.wav',\n '.ttf', '.otf', '.woff', '.woff2',\n '.bin', '.dat', '.db', '.sqlite'\n ];\n\n const ext = path.extname(filePath).toLowerCase();\n if (binaryExtensions.includes(ext)) {\n return true;\n }\n\n // For files without clear extensions, try to read a small sample\n const stats = await fs.stat(filePath);\n if (stats.size === 0) {\n return false; // Empty files are considered text\n }\n\n // Read first 1024 bytes to check for null bytes\n const sampleSize = Math.min(1024, stats.size);\n const buffer = await fs.readFile(filePath, { encoding: null, flag: 'r' });\n const sample = buffer.slice(0, sampleSize);\n // If we find null bytes, it's likely binary\n return sample.includes(0);\n } catch (error) {\n console.warn(`Warning: Could not determine if file is binary: ${filePath} - ${error.message}`);\n return false; // Default to text if we can't determine\n }\n}\n\n/**\n * Read and aggregate content from text files\n * @param {string[]} files - Array of file paths\n * @param {string} rootDir - The root directory\n * @param {Object} spinner - Optional spinner instance for progress display\n * @returns {Promise} Object containing file contents and metadata\n */\nasync function aggregateFileContents(files, rootDir, spinner = null) {\n const results = {\n textFiles: [],\n binaryFiles: [],\n errors: [],\n totalFiles: files.length,\n processedFiles: 0\n };\n\n for (const filePath of files) {\n try {\n const relativePath = path.relative(rootDir, filePath);\n\n // Update progress indicator\n if (spinner) {\n spinner.text = `Processing file ${results.processedFiles + 1}/${results.totalFiles}: ${relativePath}`;\n }\n\n const isBinary = await isBinaryFile(filePath);\n\n if (isBinary) {\n results.binaryFiles.push({\n path: relativePath,\n absolutePath: filePath,\n size: (await fs.stat(filePath)).size\n });\n } else {\n // Read text file content\n const content = await fs.readFile(filePath, 'utf8');\n results.textFiles.push({\n path: relativePath,\n absolutePath: filePath,\n content: content,\n size: content.length,\n lines: content.split('\\n').length\n });\n }\n\n results.processedFiles++;\n } catch (error) {\n const relativePath = path.relative(rootDir, filePath);\n const errorInfo = {\n path: relativePath,\n absolutePath: filePath,\n error: error.message\n };\n\n results.errors.push(errorInfo);\n\n // Log warning without interfering with spinner\n if (spinner) {\n spinner.warn(`Warning: Could not read file ${relativePath}: ${error.message}`);\n } else {\n console.warn(`Warning: Could not read file ${relativePath}: ${error.message}`);\n }\n\n results.processedFiles++;\n }\n }\n\n return results;\n}\n\n/**\n * Generate XML output with aggregated file contents using streaming\n * @param {Object} aggregatedContent - The aggregated content object\n * @param {string} outputPath - The output file path\n * @returns {Promise} Promise that resolves when writing is complete\n */\nasync function generateXMLOutput(aggregatedContent, outputPath) {\n const { textFiles } = aggregatedContent;\n\n // Create write stream for efficient memory usage\n const writeStream = fs.createWriteStream(outputPath, { encoding: 'utf8' });\n\n return new Promise((resolve, reject) => {\n writeStream.on('error', reject);\n writeStream.on('finish', resolve);\n\n // Write XML header\n writeStream.write('\\n');\n writeStream.write('\\n');\n\n // Process files one by one to minimize memory usage\n let fileIndex = 0;\n\n const writeNextFile = () => {\n if (fileIndex >= textFiles.length) {\n // All files processed, close XML and stream\n writeStream.write('\\n');\n writeStream.end();\n return;\n }\n\n const file = textFiles[fileIndex];\n fileIndex++;\n\n // Write file opening tag\n writeStream.write(` `);\n\n // Use CDATA for code content, handling CDATA end sequences properly\n if (file.content?.trim()) {\n const indentedContent = indentFileContent(file.content);\n if (file.content.includes(']]>')) {\n // If content contains ]]>, split it and wrap each part in CDATA\n writeStream.write(splitAndWrapCDATA(indentedContent));\n } else {\n writeStream.write(``);\n }\n } else if (file.content) {\n // Handle empty or whitespace-only content\n const indentedContent = indentFileContent(file.content);\n writeStream.write(``);\n }\n\n // Write file closing tag\n writeStream.write('\\n');\n\n // Continue with next file on next tick to avoid stack overflow\n setImmediate(writeNextFile);\n };\n\n // Start processing files\n writeNextFile();\n });\n}\n\n/**\n * Escape XML special characters for attributes\n * @param {string} str - String to escape\n * @returns {string} Escaped string\n */\nfunction escapeXml(str) {\n if (typeof str !== 'string') {\n return String(str);\n }\n return str\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Indent file content with 4 spaces for each line\n * @param {string} content - Content to indent\n * @returns {string} Indented content\n */\nfunction indentFileContent(content) {\n if (typeof content !== 'string') {\n return String(content);\n }\n\n // Split content into lines and add 4 spaces of indentation to each line\n return content.split('\\n').map(line => ` ${line}`).join('\\n');\n}\n\n/**\n * Split content containing ]]> and wrap each part in CDATA\n * @param {string} content - Content to process\n * @returns {string} Content with properly wrapped CDATA sections\n */\nfunction splitAndWrapCDATA(content) {\n if (typeof content !== 'string') {\n return String(content);\n }\n\n // Replace ]]> with ]]]]> to escape it within CDATA\n const escapedContent = content.replace(/]]>/g, ']]]]>');\n return ``;\n}\n\n/**\n * Calculate statistics for the processed files\n * @param {Object} aggregatedContent - The aggregated content object\n * @param {number} xmlFileSize - The size of the generated XML file in bytes\n * @returns {Object} Statistics object\n */\nfunction calculateStatistics(aggregatedContent, xmlFileSize) {\n const { textFiles, binaryFiles, errors } = aggregatedContent;\n\n // Calculate total file size in bytes\n const totalTextSize = textFiles.reduce((sum, file) => sum + file.size, 0);\n const totalBinarySize = binaryFiles.reduce((sum, file) => sum + file.size, 0);\n const totalSize = totalTextSize + totalBinarySize;\n\n // Calculate total lines of code\n const totalLines = textFiles.reduce((sum, file) => sum + file.lines, 0);\n\n // Estimate token count (rough approximation: 1 token ā‰ˆ 4 characters)\n const estimatedTokens = Math.ceil(xmlFileSize / 4);\n\n // Format file size\n const formatSize = (bytes) => {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n };\n\n return {\n totalFiles: textFiles.length + binaryFiles.length,\n textFiles: textFiles.length,\n binaryFiles: binaryFiles.length,\n errorFiles: errors.length,\n totalSize: formatSize(totalSize),\n xmlSize: formatSize(xmlFileSize),\n totalLines,\n estimatedTokens: estimatedTokens.toLocaleString()\n };\n}\n\n/**\n * Filter files based on .gitignore patterns\n * @param {string[]} files - Array of file paths\n * @param {string} rootDir - The root directory\n * @returns {Promise} Filtered array of file paths\n */\nasync function filterFiles(files, rootDir) {\n const gitignorePath = path.join(rootDir, '.gitignore');\n const ignorePatterns = await parseGitignore(gitignorePath);\n\n if (ignorePatterns.length === 0) {\n return files;\n }\n\n // Convert absolute paths to relative for pattern matching\n const relativeFiles = files.map(file => path.relative(rootDir, file));\n\n // Separate positive and negative patterns\n const positivePatterns = ignorePatterns.filter(p => !p.startsWith('!'));\n const negativePatterns = ignorePatterns.filter(p => p.startsWith('!')).map(p => p.slice(1));\n\n // Filter out files that match ignore patterns\n const filteredRelative = [];\n\n for (const file of relativeFiles) {\n let shouldIgnore = false;\n\n // First check positive patterns (ignore these files)\n for (const pattern of positivePatterns) {\n if (minimatch(file, pattern)) {\n shouldIgnore = true;\n break;\n }\n }\n\n // Then check negative patterns (don't ignore these files even if they match positive patterns)\n if (shouldIgnore) {\n for (const pattern of negativePatterns) {\n if (minimatch(file, pattern)) {\n shouldIgnore = false;\n break;\n }\n }\n }\n\n if (!shouldIgnore) {\n filteredRelative.push(file);\n }\n }\n\n // Convert back to absolute paths\n return filteredRelative.map(file => path.resolve(rootDir, file));\n}\n\nconst program = new Command();\n\nprogram\n .name('bmad-flatten')\n .description('BMad-Method codebase flattener tool')\n .version('1.0.0')\n .option('-o, --output ', 'Output file path', 'flattened-codebase.xml')\n .action(async (options) => {\n console.log(`Flattening codebase to: ${options.output}`);\n\n try {\n // Import ora dynamically\n const { default: ora } = await import('ora');\n\n // Start file discovery with spinner\n const discoverySpinner = ora('šŸ” Discovering files...').start();\n const files = await discoverFiles(process.cwd());\n const filteredFiles = await filterFiles(files, process.cwd());\n discoverySpinner.succeed(`šŸ“ Found ${filteredFiles.length} files to include`);\n\n // Process files with progress tracking\n console.log('Reading file contents');\n const processingSpinner = ora('šŸ“„ Processing files...').start();\n const aggregatedContent = await aggregateFileContents(filteredFiles, process.cwd(), processingSpinner);\n processingSpinner.succeed(`āœ… Processed ${aggregatedContent.processedFiles}/${filteredFiles.length} files`);\n\n // Log processing results for test validation\n console.log(`Processed ${aggregatedContent.processedFiles}/${filteredFiles.length} files`);\n if (aggregatedContent.errors.length > 0) {\n console.log(`Errors: ${aggregatedContent.errors.length}`);\n }\n console.log(`Text files: ${aggregatedContent.textFiles.length}`);\n if (aggregatedContent.binaryFiles.length > 0) {\n console.log(`Binary files: ${aggregatedContent.binaryFiles.length}`);\n }\n\n // Generate XML output using streaming\n const xmlSpinner = ora('šŸ”§ Generating XML output...').start();\n await generateXMLOutput(aggregatedContent, options.output);\n xmlSpinner.succeed('šŸ“ XML generation completed');\n\n // Calculate and display statistics\n const outputStats = await fs.stat(options.output);\n const stats = calculateStatistics(aggregatedContent, outputStats.size);\n\n // Display completion summary\n console.log('\\nšŸ“Š Completion Summary:');\n console.log(`āœ… Successfully processed ${filteredFiles.length} files into ${options.output}`);\n console.log(`šŸ“ Output file: ${path.resolve(options.output)}`);\n console.log(`šŸ“ Total source size: ${stats.totalSize}`);\n console.log(`šŸ“„ Generated XML size: ${stats.xmlSize}`);\n console.log(`šŸ“ Total lines of code: ${stats.totalLines.toLocaleString()}`);\n console.log(`šŸ”¢ Estimated tokens: ${stats.estimatedTokens}`);\n console.log(`šŸ“Š File breakdown: ${stats.textFiles} text, ${stats.binaryFiles} binary, ${stats.errorFiles} errors`);\n\n } catch (error) {\n console.error('āŒ Critical error:', error.message);\n console.error('An unexpected error occurred.');\n process.exit(1);\n }\n });\n\nif (require.main === module) {\n program.parse();\n}\n\nmodule.exports = program;\n"], ["/BMAD-METHOD/tools/yaml-format.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { execSync } = require('child_process');\n\n// Dynamic import for ES module\nlet chalk;\n\n// Initialize ES modules\nasync function initializeModules() {\n if (!chalk) {\n chalk = (await import('chalk')).default;\n }\n}\n\n/**\n * YAML Formatter and Linter for BMad-Method\n * Formats and validates YAML files and YAML embedded in Markdown\n */\n\nasync function formatYamlContent(content, filename) {\n await initializeModules();\n try {\n // First try to fix common YAML issues\n let fixedContent = content\n // Fix \"commands :\" -> \"commands:\"\n .replace(/^(\\s*)(\\w+)\\s+:/gm, '$1$2:')\n // Fix inconsistent list indentation\n .replace(/^(\\s*)-\\s{3,}/gm, '$1- ');\n \n // Skip auto-fixing for .roomodes files - they have special nested structure\n if (!filename.includes('.roomodes')) {\n fixedContent = fixedContent\n // Fix unquoted list items that contain special characters or multiple parts\n .replace(/^(\\s*)-\\s+(.*)$/gm, (match, indent, content) => {\n // Skip if already quoted\n if (content.startsWith('\"') && content.endsWith('\"')) {\n return match;\n }\n // If the content contains special YAML characters or looks complex, quote it\n // BUT skip if it looks like a proper YAML key-value pair (like \"key: value\")\n if ((content.includes(':') || content.includes('-') || content.includes('{') || content.includes('}')) && \n !content.match(/^\\w+:\\s/)) {\n // Remove any existing quotes first, escape internal quotes, then add proper quotes\n const cleanContent = content.replace(/^[\"']|[\"']$/g, '').replace(/\"/g, '\\\\\"');\n return `${indent}- \"${cleanContent}\"`;\n }\n return match;\n });\n }\n \n // Debug: show what we're trying to parse\n if (fixedContent !== content) {\n console.log(chalk.blue(`šŸ”§ Applied YAML fixes to ${filename}`));\n }\n \n // Parse and re-dump YAML to format it\n const parsed = yaml.load(fixedContent);\n const formatted = yaml.dump(parsed, {\n indent: 2,\n lineWidth: -1, // Disable line wrapping\n noRefs: true,\n sortKeys: false // Preserve key order\n });\n return formatted;\n } catch (error) {\n console.error(chalk.red(`āŒ YAML syntax error in ${filename}:`), error.message);\n console.error(chalk.yellow(`šŸ’” Try manually fixing the YAML structure first`));\n return null;\n }\n}\n\nasync function processMarkdownFile(filePath) {\n await initializeModules();\n const content = fs.readFileSync(filePath, 'utf8');\n let modified = false;\n let newContent = content;\n\n // Fix untyped code blocks by adding 'text' type\n // Match ``` at start of line followed by newline, but only if it's an opening fence\n newContent = newContent.replace(/^```\\n([\\s\\S]*?)\\n```$/gm, '```text\\n$1\\n```');\n if (newContent !== content) {\n modified = true;\n console.log(chalk.blue(`šŸ”§ Added 'text' type to untyped code blocks in ${filePath}`));\n }\n\n // Find YAML code blocks\n const yamlBlockRegex = /```ya?ml\\n([\\s\\S]*?)\\n```/g;\n let match;\n const replacements = [];\n \n while ((match = yamlBlockRegex.exec(newContent)) !== null) {\n const [fullMatch, yamlContent] = match;\n const formatted = await formatYamlContent(yamlContent, filePath);\n if (formatted !== null) {\n // Remove trailing newline that js-yaml adds\n const trimmedFormatted = formatted.replace(/\\n$/, '');\n \n if (trimmedFormatted !== yamlContent) {\n modified = true;\n console.log(chalk.green(`āœ“ Formatted YAML in ${filePath}`));\n }\n \n replacements.push({\n start: match.index,\n end: match.index + fullMatch.length,\n replacement: `\\`\\`\\`yaml\\n${trimmedFormatted}\\n\\`\\`\\``\n });\n }\n }\n \n // Apply replacements in reverse order to maintain indices\n for (let i = replacements.length - 1; i >= 0; i--) {\n const { start, end, replacement } = replacements[i];\n newContent = newContent.slice(0, start) + replacement + newContent.slice(end);\n }\n\n if (modified) {\n fs.writeFileSync(filePath, newContent);\n return true;\n }\n return false;\n}\n\nasync function processYamlFile(filePath) {\n await initializeModules();\n const content = fs.readFileSync(filePath, 'utf8');\n const formatted = await formatYamlContent(content, filePath);\n \n if (formatted === null) {\n return false; // Syntax error\n }\n \n if (formatted !== content) {\n fs.writeFileSync(filePath, formatted);\n return true;\n }\n return false;\n}\n\nasync function lintYamlFile(filePath) {\n await initializeModules();\n try {\n // Use yaml-lint for additional validation\n execSync(`npx yaml-lint \"${filePath}\"`, { stdio: 'pipe' });\n return true;\n } catch (error) {\n console.error(chalk.red(`āŒ YAML lint error in ${filePath}:`));\n console.error(error.stdout?.toString() || error.message);\n return false;\n }\n}\n\nasync function main() {\n await initializeModules();\n const args = process.argv.slice(2);\n const glob = require('glob');\n \n if (args.length === 0) {\n console.error('Usage: node yaml-format.js [file2] ...');\n process.exit(1);\n }\n\n let hasErrors = false;\n let hasChanges = false;\n let filesProcessed = [];\n\n // Expand glob patterns and collect all files\n const allFiles = [];\n for (const arg of args) {\n if (arg.includes('*')) {\n // It's a glob pattern\n const matches = glob.sync(arg);\n allFiles.push(...matches);\n } else {\n // It's a direct file path\n allFiles.push(arg);\n }\n }\n\n for (const filePath of allFiles) {\n if (!fs.existsSync(filePath)) {\n // Skip silently for glob patterns that don't match anything\n if (!args.some(arg => arg.includes('*') && filePath === arg)) {\n console.error(chalk.red(`āŒ File not found: ${filePath}`));\n hasErrors = true;\n }\n continue;\n }\n\n const ext = path.extname(filePath).toLowerCase();\n const basename = path.basename(filePath).toLowerCase();\n \n try {\n let changed = false;\n if (ext === '.md') {\n changed = await processMarkdownFile(filePath);\n } else if (ext === '.yaml' || ext === '.yml' || basename.includes('roomodes') || basename.includes('.yaml') || basename.includes('.yml')) {\n // Handle YAML files and special cases like .roomodes\n changed = await processYamlFile(filePath);\n \n // Also run linting\n const lintPassed = await lintYamlFile(filePath);\n if (!lintPassed) hasErrors = true;\n } else {\n // Skip silently for unsupported files\n continue;\n }\n \n if (changed) {\n hasChanges = true;\n filesProcessed.push(filePath);\n }\n } catch (error) {\n console.error(chalk.red(`āŒ Error processing ${filePath}:`), error.message);\n hasErrors = true;\n }\n }\n\n if (hasChanges) {\n console.log(chalk.green(`\\n✨ YAML formatting completed! Modified ${filesProcessed.length} files:`));\n filesProcessed.forEach(file => console.log(chalk.blue(` šŸ“ ${file}`)));\n }\n\n if (hasErrors) {\n console.error(chalk.red('\\nšŸ’„ Some files had errors. Please fix them before committing.'));\n process.exit(1);\n }\n}\n\nif (require.main === module) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n\nmodule.exports = { formatYamlContent, processMarkdownFile, processYamlFile };"], ["/BMAD-METHOD/tools/update-expansion-version.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\nconst args = process.argv.slice(2);\n\nif (args.length < 2) {\n console.log('Usage: node update-expansion-version.js ');\n console.log('Example: node update-expansion-version.js bmad-creator-tools 1.1.0');\n process.exit(1);\n}\n\nconst [packId, newVersion] = args;\n\n// Validate version format\nif (!/^\\d+\\.\\d+\\.\\d+$/.test(newVersion)) {\n console.error('Error: Version must be in format X.Y.Z (e.g., 1.2.3)');\n process.exit(1);\n}\n\nasync function updateVersion() {\n try {\n // Update in config.yaml\n const configPath = path.join(__dirname, '..', 'expansion-packs', packId, 'config.yaml');\n \n if (!fs.existsSync(configPath)) {\n console.error(`Error: Expansion pack '${packId}' not found`);\n process.exit(1);\n }\n \n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n const oldVersion = config.version || 'unknown';\n \n config.version = newVersion;\n \n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n \n console.log(`āœ“ Updated ${packId}/config.yaml: ${oldVersion} → ${newVersion}`);\n console.log(`\\nāœ“ Successfully updated ${packId} to version ${newVersion}`);\n console.log('\\nNext steps:');\n console.log('1. Test the changes');\n console.log('2. Commit: git add -A && git commit -m \"chore: bump ' + packId + ' to v' + newVersion + '\"');\n \n } catch (error) {\n console.error('Error updating version:', error.message);\n process.exit(1);\n }\n}\n\nupdateVersion();"], ["/BMAD-METHOD/tools/installer/lib/memory-profiler.js", "/**\n * Memory Profiler - Track memory usage during installation\n * Helps identify memory leaks and optimize resource usage\n */\n\nconst v8 = require('v8');\n\nclass MemoryProfiler {\n constructor() {\n this.checkpoints = [];\n this.startTime = Date.now();\n this.peakMemory = 0;\n }\n\n /**\n * Create a memory checkpoint\n * @param {string} label - Label for this checkpoint\n */\n checkpoint(label) {\n const memUsage = process.memoryUsage();\n const heapStats = v8.getHeapStatistics();\n \n const checkpoint = {\n label,\n timestamp: Date.now() - this.startTime,\n memory: {\n rss: this.formatBytes(memUsage.rss),\n heapTotal: this.formatBytes(memUsage.heapTotal),\n heapUsed: this.formatBytes(memUsage.heapUsed),\n external: this.formatBytes(memUsage.external),\n arrayBuffers: this.formatBytes(memUsage.arrayBuffers || 0)\n },\n heap: {\n totalHeapSize: this.formatBytes(heapStats.total_heap_size),\n usedHeapSize: this.formatBytes(heapStats.used_heap_size),\n heapSizeLimit: this.formatBytes(heapStats.heap_size_limit),\n mallocedMemory: this.formatBytes(heapStats.malloced_memory),\n externalMemory: this.formatBytes(heapStats.external_memory)\n },\n raw: {\n heapUsed: memUsage.heapUsed\n }\n };\n\n // Track peak memory\n if (memUsage.heapUsed > this.peakMemory) {\n this.peakMemory = memUsage.heapUsed;\n }\n\n this.checkpoints.push(checkpoint);\n return checkpoint;\n }\n\n /**\n * Force garbage collection (requires --expose-gc flag)\n */\n forceGC() {\n if (global.gc) {\n global.gc();\n return true;\n }\n return false;\n }\n\n /**\n * Get memory usage summary\n */\n getSummary() {\n const currentMemory = process.memoryUsage();\n \n return {\n currentUsage: {\n rss: this.formatBytes(currentMemory.rss),\n heapTotal: this.formatBytes(currentMemory.heapTotal),\n heapUsed: this.formatBytes(currentMemory.heapUsed)\n },\n peakMemory: this.formatBytes(this.peakMemory),\n totalCheckpoints: this.checkpoints.length,\n runTime: `${((Date.now() - this.startTime) / 1000).toFixed(2)}s`\n };\n }\n\n /**\n * Get detailed report of memory usage\n */\n getDetailedReport() {\n const summary = this.getSummary();\n const memoryGrowth = this.calculateMemoryGrowth();\n \n return {\n summary,\n memoryGrowth,\n checkpoints: this.checkpoints,\n recommendations: this.getRecommendations(memoryGrowth)\n };\n }\n\n /**\n * Calculate memory growth between checkpoints\n */\n calculateMemoryGrowth() {\n if (this.checkpoints.length < 2) return [];\n \n const growth = [];\n for (let i = 1; i < this.checkpoints.length; i++) {\n const prev = this.checkpoints[i - 1];\n const curr = this.checkpoints[i];\n \n const heapDiff = curr.raw.heapUsed - prev.raw.heapUsed;\n \n growth.push({\n from: prev.label,\n to: curr.label,\n heapGrowth: this.formatBytes(Math.abs(heapDiff)),\n isIncrease: heapDiff > 0,\n timeDiff: `${((curr.timestamp - prev.timestamp) / 1000).toFixed(2)}s`\n });\n }\n \n return growth;\n }\n\n /**\n * Get recommendations based on memory usage\n */\n getRecommendations(memoryGrowth) {\n const recommendations = [];\n \n // Check for large memory growth\n const largeGrowths = memoryGrowth.filter(g => {\n const bytes = this.parseBytes(g.heapGrowth);\n return bytes > 50 * 1024 * 1024; // 50MB\n });\n \n if (largeGrowths.length > 0) {\n recommendations.push({\n type: 'warning',\n message: `Large memory growth detected in ${largeGrowths.length} operations`,\n details: largeGrowths.map(g => `${g.from} → ${g.to}: ${g.heapGrowth}`)\n });\n }\n \n // Check peak memory\n if (this.peakMemory > 500 * 1024 * 1024) { // 500MB\n recommendations.push({\n type: 'warning',\n message: `High peak memory usage: ${this.formatBytes(this.peakMemory)}`,\n suggestion: 'Consider processing files in smaller batches'\n });\n }\n \n // Check for potential memory leaks\n const continuousGrowth = this.checkContinuousGrowth();\n if (continuousGrowth) {\n recommendations.push({\n type: 'error',\n message: 'Potential memory leak detected',\n details: 'Memory usage continuously increases without significant decreases'\n });\n }\n \n return recommendations;\n }\n\n /**\n * Check for continuous memory growth (potential leak)\n */\n checkContinuousGrowth() {\n if (this.checkpoints.length < 5) return false;\n \n let increasingCount = 0;\n for (let i = 1; i < this.checkpoints.length; i++) {\n if (this.checkpoints[i].raw.heapUsed > this.checkpoints[i - 1].raw.heapUsed) {\n increasingCount++;\n }\n }\n \n // If memory increases in more than 80% of checkpoints, might be a leak\n return increasingCount / (this.checkpoints.length - 1) > 0.8;\n }\n\n /**\n * Format bytes to human-readable string\n */\n formatBytes(bytes) {\n if (bytes === 0) return '0 B';\n \n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n /**\n * Parse human-readable bytes back to number\n */\n parseBytes(str) {\n const match = str.match(/^([\\d.]+)\\s*([KMGT]?B?)$/i);\n if (!match) return 0;\n \n const value = parseFloat(match[1]);\n const unit = match[2].toUpperCase();\n \n const multipliers = {\n 'B': 1,\n 'KB': 1024,\n 'MB': 1024 * 1024,\n 'GB': 1024 * 1024 * 1024\n };\n \n return value * (multipliers[unit] || 1);\n }\n\n /**\n * Clear checkpoints to free memory\n */\n clear() {\n this.checkpoints = [];\n }\n}\n\n// Export singleton instance\nmodule.exports = new MemoryProfiler();"], ["/BMAD-METHOD/tools/bmad-npx-wrapper.js", "#!/usr/bin/env node\n\n/**\n * BMad Method CLI - Direct execution wrapper for npx\n * This file ensures proper execution when run via npx from GitHub\n */\n\nconst { execSync } = require('child_process');\nconst path = require('path');\nconst fs = require('fs');\n\n// Check if we're running in an npx temporary directory\nconst isNpxExecution = __dirname.includes('_npx') || __dirname.includes('.npm');\n\n// If running via npx, we need to handle things differently\nif (isNpxExecution) {\n // The actual bmad.js is in installer/bin/ (relative to tools directory)\n const bmadScriptPath = path.join(__dirname, 'installer', 'bin', 'bmad.js');\n \n // Verify the file exists\n if (!fs.existsSync(bmadScriptPath)) {\n console.error('Error: Could not find bmad.js at', bmadScriptPath);\n console.error('Current directory:', __dirname);\n process.exit(1);\n }\n \n // Execute with proper working directory\n try {\n execSync(`node \"${bmadScriptPath}\" ${process.argv.slice(2).join(' ')}`, {\n stdio: 'inherit',\n cwd: path.dirname(__dirname)\n });\n } catch (error) {\n // execSync will throw if the command exits with non-zero\n // But the stdio is inherited, so the error is already displayed\n process.exit(error.status || 1);\n }\n} else {\n // Local execution - just require the installer directly\n require('./installer/bin/bmad.js');\n}"], ["/BMAD-METHOD/tools/installer/lib/module-manager.js", "/**\n * Module Manager - Centralized dynamic import management\n * Handles loading and caching of ES modules to reduce memory overhead\n */\n\nclass ModuleManager {\n constructor() {\n this._cache = new Map();\n this._loadingPromises = new Map();\n }\n\n /**\n * Initialize all commonly used ES modules at once\n * @returns {Promise} Object containing all loaded modules\n */\n async initializeCommonModules() {\n const modules = await Promise.all([\n this.getModule('chalk'),\n this.getModule('ora'),\n this.getModule('inquirer')\n ]);\n\n return {\n chalk: modules[0],\n ora: modules[1],\n inquirer: modules[2]\n };\n }\n\n /**\n * Get a module by name, with caching\n * @param {string} moduleName - Name of the module to load\n * @returns {Promise} The loaded module\n */\n async getModule(moduleName) {\n // Return from cache if available\n if (this._cache.has(moduleName)) {\n return this._cache.get(moduleName);\n }\n\n // If already loading, return the existing promise\n if (this._loadingPromises.has(moduleName)) {\n return this._loadingPromises.get(moduleName);\n }\n\n // Start loading the module\n const loadPromise = this._loadModule(moduleName);\n this._loadingPromises.set(moduleName, loadPromise);\n\n try {\n const module = await loadPromise;\n this._cache.set(moduleName, module);\n this._loadingPromises.delete(moduleName);\n return module;\n } catch (error) {\n this._loadingPromises.delete(moduleName);\n throw error;\n }\n }\n\n /**\n * Internal method to load a specific module\n * @private\n */\n async _loadModule(moduleName) {\n switch (moduleName) {\n case 'chalk':\n return (await import('chalk')).default;\n case 'ora':\n return (await import('ora')).default;\n case 'inquirer':\n return (await import('inquirer')).default;\n case 'glob':\n return (await import('glob')).glob;\n case 'globSync':\n return (await import('glob')).globSync;\n default:\n throw new Error(`Unknown module: ${moduleName}`);\n }\n }\n\n /**\n * Clear the module cache to free memory\n */\n clearCache() {\n this._cache.clear();\n this._loadingPromises.clear();\n }\n\n /**\n * Get multiple modules at once\n * @param {string[]} moduleNames - Array of module names\n * @returns {Promise} Object with module names as keys\n */\n async getModules(moduleNames) {\n const modules = await Promise.all(\n moduleNames.map(name => this.getModule(name))\n );\n\n return moduleNames.reduce((acc, name, index) => {\n acc[name] = modules[index];\n return acc;\n }, {});\n }\n}\n\n// Singleton instance\nconst moduleManager = new ModuleManager();\n\nmodule.exports = moduleManager;"], ["/BMAD-METHOD/tools/version-bump.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst { execSync } = require('child_process');\nconst path = require('path');\n\n// Dynamic import for ES module\nlet chalk;\n\n// Initialize ES modules\nasync function initializeModules() {\n if (!chalk) {\n chalk = (await import('chalk')).default;\n }\n}\n\n/**\n * Simple version bumping script for BMad-Method\n * Usage: node tools/version-bump.js [patch|minor|major]\n */\n\nfunction getCurrentVersion() {\n const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));\n return packageJson.version;\n}\n\nasync function bumpVersion(type = 'patch') {\n await initializeModules();\n \n const validTypes = ['patch', 'minor', 'major'];\n if (!validTypes.includes(type)) {\n console.error(chalk.red(`Invalid version type: ${type}. Use: ${validTypes.join(', ')}`));\n process.exit(1);\n }\n\n console.log(chalk.yellow('āš ļø Manual version bumping is disabled.'));\n console.log(chalk.blue('šŸ¤– This project uses semantic-release for automated versioning.'));\n console.log('');\n console.log(chalk.bold('To create a new release, use conventional commits:'));\n console.log(chalk.cyan(' feat: new feature (minor version bump)'));\n console.log(chalk.cyan(' fix: bug fix (patch version bump)'));\n console.log(chalk.cyan(' feat!: breaking change (major version bump)'));\n console.log('');\n console.log(chalk.dim('Example: git commit -m \"feat: add new installer features\"'));\n console.log(chalk.dim('Then push to main branch to trigger automatic release.'));\n \n return null;\n}\n\nasync function main() {\n await initializeModules();\n \n const type = process.argv[2] || 'patch';\n const currentVersion = getCurrentVersion();\n \n console.log(chalk.blue(`Current version: ${currentVersion}`));\n \n // Check if working directory is clean\n try {\n execSync('git diff-index --quiet HEAD --');\n } catch (error) {\n console.error(chalk.red('āŒ Working directory is not clean. Commit your changes first.'));\n process.exit(1);\n }\n \n const newVersion = await bumpVersion(type);\n \n console.log(chalk.green(`\\nšŸŽ‰ Version bump complete!`));\n console.log(chalk.blue(`šŸ“¦ ${currentVersion} → ${newVersion}`));\n}\n\nif (require.main === module) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n\nmodule.exports = { bumpVersion, getCurrentVersion };"], ["/BMAD-METHOD/tools/lib/yaml-utils.js", "/**\n * Utility functions for YAML extraction from agent files\n */\n\n/**\n * Extract YAML content from agent markdown files\n * @param {string} agentContent - The full content of the agent file\n * @param {boolean} cleanCommands - Whether to clean command descriptions (default: false)\n * @returns {string|null} - The extracted YAML content or null if not found\n */\nfunction extractYamlFromAgent(agentContent, cleanCommands = false) {\n // Remove carriage returns and match YAML block\n const yamlMatch = agentContent.replace(/\\r/g, \"\").match(/```ya?ml\\n([\\s\\S]*?)\\n```/);\n if (!yamlMatch) return null;\n \n let yamlContent = yamlMatch[1].trim();\n \n // Clean up command descriptions if requested\n // Converts \"- command - description\" to just \"- command\"\n if (cleanCommands) {\n yamlContent = yamlContent.replace(/^(\\s*-)(\\s*\"[^\"]+\")(\\s*-\\s*.*)$/gm, '$1$2');\n }\n \n return yamlContent;\n}\n\nmodule.exports = {\n extractYamlFromAgent\n};"], ["/BMAD-METHOD/tools/sync-installer-version.js", "#!/usr/bin/env node\n\n/**\n * Sync installer package.json version with main package.json\n * Used by semantic-release to keep versions in sync\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\nfunction syncInstallerVersion() {\n // Read main package.json\n const mainPackagePath = path.join(__dirname, '..', 'package.json');\n const mainPackage = JSON.parse(fs.readFileSync(mainPackagePath, 'utf8'));\n \n // Read installer package.json\n const installerPackagePath = path.join(__dirname, 'installer', 'package.json');\n const installerPackage = JSON.parse(fs.readFileSync(installerPackagePath, 'utf8'));\n \n // Update installer version to match main version\n installerPackage.version = mainPackage.version;\n \n // Write back installer package.json\n fs.writeFileSync(installerPackagePath, JSON.stringify(installerPackage, null, 2) + '\\n');\n \n console.log(`Synced installer version to ${mainPackage.version}`);\n}\n\n// Run if called directly\nif (require.main === module) {\n syncInstallerVersion();\n}\n\nmodule.exports = { syncInstallerVersion };"], ["/BMAD-METHOD/tools/semantic-release-sync-installer.js", "/**\n * Semantic-release plugin to sync installer package.json version\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\n// This function runs during the \"prepare\" step of semantic-release\nfunction prepare(_, { nextRelease, logger }) {\n // Define the path to the installer package.json file\n const file = path.join(process.cwd(), 'tools/installer/package.json');\n\n // If the file does not exist, skip syncing and log a message\n if (!fs.existsSync(file)) return logger.log('Installer package.json not found, skipping');\n\n // Read and parse the package.json file\n const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));\n\n // Update the version field with the next release version\n pkg.version = nextRelease.version;\n\n // Write the updated JSON back to the file\n fs.writeFileSync(file, JSON.stringify(pkg, null, 2) + '\\n');\n\n // Log success message\n logger.log(`Synced installer package.json to version ${nextRelease.version}`);\n}\n\n// Export the prepare function so semantic-release can use it\nmodule.exports = { prepare };\n"]], "task_instance_info": {"created_time": "2025-08-20 23:47:31", "created_task_model": "DeepSeek-R1", "class_skeleton": "class\nConfigLoader\n{\nconstructor () {}\nasync load () {}\nasync getInstallationOptions () {}\nasync getAvailableAgents () {}\nasync getAvailableExpansionPacks () {}\nasync getAgentDependencies (agentId) {}\nasync getIdeConfiguration (ide) {}\ngetBmadCorePath () {}\ngetDistPath () {}\ngetAgentPath (agentId) {}\nasync getAvailableTeams () {}\ngetTeamPath (teamId) {}\nasync getTeamDependencies (teamId) {}\n}", "code_description": "This code segment functions to: Manage and retrieve system configuration data by loading settings from multiple YAML files, enumerating available components from designated directories, and resolving dependency relationships between system resources while handling error conditions gracefully."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nclass ConfigLoader {\n constructor() {\n this.rootPath = path.join(__dirname, '..');\n }\n\n async load() {\n // Core configuration loading handled in individual methods\n }\n\n async getInstallationOptions() {\n const configPath = path.join(this.rootPath, 'config.yml');\n return yaml.load(await fs.readFile(configPath, 'utf8'));\n }\n\n async getAvailableAgents() {\n const agentsDir = path.join(this.rootPath, 'agents');\n return this._getYamlConfigs(agentsDir, '.agent.yml');\n }\n\n async getAvailableExpansionPacks() {\n const packsDir = path.join(this.rootPath, 'expansion-packs');\n return this._getYamlConfigs(packsDir, '.expansion.yml');\n }\n\n async getAgentDependencies(agentId) {\n const agentPath = this.getAgentPath(agentId);\n const yamlContent = await extractYamlFromAgent(agentPath);\n return yamlContent.dependencies || [];\n }\n\n async getIdeConfiguration(ide) {\n const config = await this.getInstallationOptions();\n return config.ide_configurations?.[ide] || {};\n }\n\n getBmadCorePath() {\n return path.join(this.rootPath, 'bmad-core');\n }\n\n getDistPath() {\n return path.join(this.rootPath, 'dist');\n }\n\n getAgentPath(agentId) {\n return path.join(this.rootPath, 'agents', agentId);\n }\n\n async getAvailableTeams() {\n const teamsDir = path.join(this.rootPath, 'teams');\n return this._getYamlConfigs(teamsDir, '.team.yml');\n }\n\n getTeamPath(teamId) {\n return path.join(this.rootPath, 'teams', teamId);\n }\n\n async getTeamDependencies(teamId) {\n const teamPath = this.getTeamPath(teamId);\n const configFile = path.join(teamPath, 'team.yml');\n const config = yaml.load(await fs.readFile(configFile, 'utf8'));\n return config.dependencies || [];\n }\n\n async _getYamlConfigs(dir, suffix) {\n if (!(await fs.pathExists(dir))) return [];\n \n const items = await fs.readdir(dir);\n return Promise.all(items.map(async item => {\n const itemPath = path.join(dir, item);\n if ((await fs.stat(itemPath)).isDirectory()) {\n const configFile = path.join(itemPath, `${item}${suffix}`);\n if (await fs.pathExists(configFile)) {\n return yaml.load(await fs.readFile(configFile, 'utf8'));\n }\n }\n return null;\n })).then(results => results.filter(Boolean));\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-48-04"}, "editdistance_info": {"edit_distance": 15.9309, "calculate_time": "2025-08-20 23:48:04", "true_code_clean": "class ConfigLoader {\n constructor() {\n this.configPath = path.join(__dirname, '..', 'config', 'install.config.yaml');\n this.config = null;\n }\n async load() {\n if (this.config) return this.config;\n try {\n const configContent = await fs.readFile(this.configPath, 'utf8');\n this.config = yaml.load(configContent);\n return this.config;\n } catch (error) {\n throw new Error(`Failed to load configuration: ${error.message}`);\n }\n }\n async getInstallationOptions() {\n const config = await this.load();\n return config['installation-options'] || {};\n }\n async getAvailableAgents() {\n const agentsDir = path.join(this.getBmadCorePath(), 'agents');\n try {\n const entries = await fs.readdir(agentsDir, { withFileTypes: true });\n const agents = [];\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.md')) {\n const agentPath = path.join(agentsDir, entry.name);\n const agentId = path.basename(entry.name, '.md');\n try {\n const agentContent = await fs.readFile(agentPath, 'utf8');\n const yamlContentText = extractYamlFromAgent(agentContent);\n if (yamlContentText) {\n const yamlContent = yaml.load(yamlContentText);\n const agentConfig = yamlContent.agent || {};\n agents.push({\n id: agentId,\n name: agentConfig.title || agentConfig.name || agentId,\n file: `bmad-core/agents/${entry.name}`,\n description: agentConfig.whenToUse || 'No description available'\n });\n }\n } catch (error) {\n console.warn(`Failed to read agent ${entry.name}: ${error.message}`);\n }\n }\n }\n agents.sort((a, b) => a.name.localeCompare(b.name));\n return agents;\n } catch (error) {\n console.warn(`Failed to read agents directory: ${error.message}`);\n return [];\n }\n }\n async getAvailableExpansionPacks() {\n const expansionPacksDir = path.join(this.getBmadCorePath(), '..', 'expansion-packs');\n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n const expansionPacks = [];\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n const packPath = path.join(expansionPacksDir, entry.name);\n const configPath = path.join(packPath, 'config.yaml');\n try {\n const configContent = await fs.readFile(configPath, 'utf8');\n const config = yaml.load(configContent);\n expansionPacks.push({\n id: entry.name,\n name: config.name || entry.name,\n description: config['short-title'] || config.description || 'No description available',\n fullDescription: config.description || config['short-title'] || 'No description available',\n version: config.version || '1.0.0',\n author: config.author || 'BMad Team',\n packPath: packPath,\n dependencies: config.dependencies?.agents || []\n });\n } catch (error) {\n console.warn(`Failed to read config for expansion pack ${entry.name}: ${error.message}`);\n const name = entry.name\n .split('-')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n expansionPacks.push({\n id: entry.name,\n name: name,\n description: 'No description available',\n fullDescription: 'No description available',\n version: '1.0.0',\n author: 'BMad Team',\n packPath: packPath,\n dependencies: []\n });\n }\n }\n }\n return expansionPacks;\n } catch (error) {\n console.warn(`Failed to read expansion packs directory: ${error.message}`);\n return [];\n }\n }\n async getAgentDependencies(agentId) {\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n const agentDeps = await resolver.resolveAgentDependencies(agentId);\n const depPaths = [];\n for (const resource of agentDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n return depPaths;\n }\n async getIdeConfiguration(ide) {\n const config = await this.load();\n const ideConfigs = config['ide-configurations'] || {};\n return ideConfigs[ide] || null;\n }\n getBmadCorePath() {\n return path.join(__dirname, '..', '..', '..', 'bmad-core');\n }\n getDistPath() {\n return path.join(__dirname, '..', '..', '..', 'dist');\n }\n getAgentPath(agentId) {\n return path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n }\n async getAvailableTeams() {\n const teamsDir = path.join(this.getBmadCorePath(), 'agent-teams');\n try {\n const entries = await fs.readdir(teamsDir, { withFileTypes: true });\n const teams = [];\n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.yaml')) {\n const teamPath = path.join(teamsDir, entry.name);\n try {\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n if (teamConfig.bundle) {\n teams.push({\n id: path.basename(entry.name, '.yaml'),\n name: teamConfig.bundle.name || entry.name,\n description: teamConfig.bundle.description || 'Team configuration',\n icon: teamConfig.bundle.icon || 'šŸ“‹'\n });\n }\n } catch (error) {\n console.warn(`Warning: Could not load team config ${entry.name}: ${error.message}`);\n }\n }\n }\n return teams;\n } catch (error) {\n console.warn(`Warning: Could not scan teams directory: ${error.message}`);\n return [];\n }\n }\n getTeamPath(teamId) {\n return path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n }\n async getTeamDependencies(teamId) {\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n try {\n const teamDeps = await resolver.resolveTeamDependencies(teamId);\n const depPaths = [];\n depPaths.push(`.bmad-core/agent-teams/${teamId}.yaml`);\n for (const agent of teamDeps.agents) {\n const filePath = `.bmad-core/agents/${agent.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n for (const resource of teamDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.${resource.type === 'workflows' ? 'yaml' : 'md'}`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n return depPaths;\n } catch (error) {\n throw new Error(`Failed to resolve team dependencies for ${teamId}: ${error.message}`);\n }\n }\n}", "predict_code_clean": "class ConfigLoader {\n constructor() {\n this.rootPath = path.join(__dirname, '..');\n }\n async load() {\n }\n async getInstallationOptions() {\n const configPath = path.join(this.rootPath, 'config.yml');\n return yaml.load(await fs.readFile(configPath, 'utf8'));\n }\n async getAvailableAgents() {\n const agentsDir = path.join(this.rootPath, 'agents');\n return this._getYamlConfigs(agentsDir, '.agent.yml');\n }\n async getAvailableExpansionPacks() {\n const packsDir = path.join(this.rootPath, 'expansion-packs');\n return this._getYamlConfigs(packsDir, '.expansion.yml');\n }\n async getAgentDependencies(agentId) {\n const agentPath = this.getAgentPath(agentId);\n const yamlContent = await extractYamlFromAgent(agentPath);\n return yamlContent.dependencies || [];\n }\n async getIdeConfiguration(ide) {\n const config = await this.getInstallationOptions();\n return config.ide_configurations?.[ide] || {};\n }\n getBmadCorePath() {\n return path.join(this.rootPath, 'bmad-core');\n }\n getDistPath() {\n return path.join(this.rootPath, 'dist');\n }\n getAgentPath(agentId) {\n return path.join(this.rootPath, 'agents', agentId);\n }\n async getAvailableTeams() {\n const teamsDir = path.join(this.rootPath, 'teams');\n return this._getYamlConfigs(teamsDir, '.team.yml');\n }\n getTeamPath(teamId) {\n return path.join(this.rootPath, 'teams', teamId);\n }\n async getTeamDependencies(teamId) {\n const teamPath = this.getTeamPath(teamId);\n const configFile = path.join(teamPath, 'team.yml');\n const config = yaml.load(await fs.readFile(configFile, 'utf8'));\n return config.dependencies || [];\n }\n async _getYamlConfigs(dir, suffix) {\n if (!(await fs.pathExists(dir))) return [];\n const items = await fs.readdir(dir);\n return Promise.all(items.map(async item => {\n const itemPath = path.join(dir, item);\n if ((await fs.stat(itemPath)).isDirectory()) {\n const configFile = path.join(itemPath, `${item}${suffix}`);\n if (await fs.pathExists(configFile)) {\n return yaml.load(await fs.readFile(configFile, 'utf8'));\n }\n }\n return null;\n })).then(results => results.filter(Boolean));\n }\n}"}} {"repo_name": "BMAD-METHOD", "file_name": "/BMAD-METHOD/tools/installer/lib/ide-base-setup.js", "inference_info": {"prefix_code": "/**\n * Base IDE Setup - Common functionality for all IDE setups\n * Reduces duplication and provides shared methods\n */\n\nconst path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst fileManager = require(\"./file-manager\");\nconst resourceLocator = require(\"./resource-locator\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\n\n", "suffix_code": "\n\nmodule.exports = BaseIdeSetup;", "middle_code": "class BaseIdeSetup {\n constructor() {\n this._agentCache = new Map();\n this._pathCache = new Map();\n }\n async getAllAgentIds(installDir) {\n const cacheKey = `all-agents:${installDir}`;\n if (this._agentCache.has(cacheKey)) {\n return this._agentCache.get(cacheKey);\n }\n const allAgents = new Set();\n const coreAgents = await this.getCoreAgentIds(installDir);\n coreAgents.forEach(id => allAgents.add(id));\n const expansionPacks = await this.getInstalledExpansionPacks(installDir);\n for (const pack of expansionPacks) {\n const packAgents = await this.getExpansionPackAgents(pack.path);\n packAgents.forEach(id => allAgents.add(id));\n }\n const result = Array.from(allAgents);\n this._agentCache.set(cacheKey, result);\n return result;\n }\n async getCoreAgentIds(installDir) {\n const coreAgents = [];\n const corePaths = [\n path.join(installDir, \".bmad-core\", \"agents\"),\n path.join(installDir, \"bmad-core\", \"agents\")\n ];\n for (const agentsDir of corePaths) {\n if (await fileManager.pathExists(agentsDir)) {\n const files = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n coreAgents.push(...files.map(file => path.basename(file, \".md\")));\n break; \n }\n }\n return coreAgents;\n }\n async findAgentPath(agentId, installDir) {\n const cacheKey = `agent-path:${agentId}:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n let agentPath = await resourceLocator.getAgentPath(agentId);\n if (!agentPath) {\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"common\", \"agents\", `${agentId}.md`)\n ];\n for (const testPath of possiblePaths) {\n if (await fileManager.pathExists(testPath)) {\n agentPath = testPath;\n break;\n }\n }\n }\n if (agentPath) {\n this._pathCache.set(cacheKey, agentPath);\n }\n return agentPath;\n }\n async getAgentTitle(agentId, installDir) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n if (!agentPath) return agentId;\n try {\n const content = await fileManager.readFile(agentPath);\n const yamlContent = extractYamlFromAgent(content);\n if (yamlContent) {\n const metadata = yaml.load(yamlContent);\n return metadata.agent_name || agentId;\n }\n } catch (error) {\n }\n return agentId;\n }\n async getInstalledExpansionPacks(installDir) {\n const cacheKey = `expansion-packs:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n const expansionPacks = [];\n const dotExpansions = await resourceLocator.findFiles(\".bmad-*\", { cwd: installDir });\n for (const dotExpansion of dotExpansions) {\n if (dotExpansion !== \".bmad-core\") {\n const packPath = path.join(installDir, dotExpansion);\n const packName = dotExpansion.substring(1); \n expansionPacks.push({\n name: packName,\n path: packPath\n });\n }\n }\n const allDotFolders = await resourceLocator.findFiles(\".*\", { cwd: installDir });\n for (const folder of allDotFolders) {\n if (!folder.startsWith(\".bmad-\") && folder !== \".bmad-core\") {\n const packPath = path.join(installDir, folder);\n const configPath = path.join(packPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n expansionPacks.push({\n name: folder.substring(1), \n path: packPath\n });\n }\n }\n }\n this._pathCache.set(cacheKey, expansionPacks);\n return expansionPacks;\n }\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n return [];\n }\n const agentFiles = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n return agentFiles.map(file => path.basename(file, \".md\"));\n }\n async createAgentRuleContent(agentId, agentPath, installDir, format = 'mdc') {\n const agentContent = await fileManager.readFile(agentPath);\n const agentTitle = await this.getAgentTitle(agentId, installDir);\n const yamlContent = extractYamlFromAgent(agentContent);\n let content = \"\";\n if (format === 'mdc') {\n content = \"---\\n\";\n content += \"description: \\n\";\n content += \"globs: []\\n\";\n content += \"alwaysApply: false\\n\";\n content += \"---\\n\\n\";\n content += `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n content += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${agentTitle} agent persona.\\n\\n`;\n content += \"## Agent Activation\\n\\n\";\n content += \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n content += \"```yaml\\n\";\n content += yamlContent || agentContent.replace(/^#.*$/m, \"\").trim();\n content += \"\\n```\\n\\n\";\n content += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n content += `The complete agent definition is available in [${relativePath}](mdc:${relativePath}).\\n\\n`;\n content += \"## Usage\\n\\n\";\n content += `When the user types \\`@${agentId}\\`, activate this ${agentTitle} persona and follow all instructions defined in the YAML configuration above.\\n`;\n } else if (format === 'claude') {\n content = `# /${agentId} Command\\n\\n`;\n content += `When this command is used, adopt the following agent persona:\\n\\n`;\n content += agentContent;\n }\n return content;\n }\n clearCache() {\n this._agentCache.clear();\n this._pathCache.clear();\n }\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/BMAD-METHOD/tools/installer/lib/ide-setup.js", "const path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst inquirer = require(\"inquirer\");\nconst fileManager = require(\"./file-manager\");\nconst configLoader = require(\"./config-loader\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\nconst BaseIdeSetup = require(\"./ide-base-setup\");\nconst resourceLocator = require(\"./resource-locator\");\n\nclass IdeSetup extends BaseIdeSetup {\n constructor() {\n super();\n this.ideAgentConfig = null;\n }\n\n async loadIdeAgentConfig() {\n if (this.ideAgentConfig) return this.ideAgentConfig;\n \n try {\n const configPath = path.join(__dirname, '..', 'config', 'ide-agent-config.yaml');\n const configContent = await fs.readFile(configPath, 'utf8');\n this.ideAgentConfig = yaml.load(configContent);\n return this.ideAgentConfig;\n } catch (error) {\n console.warn('Failed to load IDE agent configuration, using defaults');\n return {\n 'roo-permissions': {},\n 'cline-order': {}\n };\n }\n }\n\n async setup(ide, installDir, selectedAgent = null, spinner = null, preConfiguredSettings = null) {\n const ideConfig = await configLoader.getIdeConfiguration(ide);\n\n if (!ideConfig) {\n console.log(chalk.yellow(`\\nNo configuration available for ${ide}`));\n return false;\n }\n\n switch (ide) {\n case \"cursor\":\n return this.setupCursor(installDir, selectedAgent);\n case \"claude-code\":\n return this.setupClaudeCode(installDir, selectedAgent);\n case \"windsurf\":\n return this.setupWindsurf(installDir, selectedAgent);\n case \"trae\":\n return this.setupTrae(installDir, selectedAgent);\n case \"roo\":\n return this.setupRoo(installDir, selectedAgent);\n case \"cline\":\n return this.setupCline(installDir, selectedAgent);\n case \"gemini\":\n return this.setupGeminiCli(installDir, selectedAgent);\n case \"github-copilot\":\n return this.setupGitHubCopilot(installDir, selectedAgent, spinner, preConfiguredSettings);\n default:\n console.log(chalk.yellow(`\\nIDE ${ide} not yet supported`));\n return false;\n }\n }\n\n async setupCursor(installDir, selectedAgent) {\n const cursorRulesDir = path.join(installDir, \".cursor\", \"rules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(cursorRulesDir);\n\n for (const agentId of agents) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const mdcContent = await this.createAgentRuleContent(agentId, agentPath, installDir, 'mdc');\n const mdcPath = path.join(cursorRulesDir, `${agentId}.mdc`);\n await fileManager.writeFile(mdcPath, mdcContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.mdc`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Cursor rules in ${cursorRulesDir}`));\n return true;\n }\n\n async setupClaudeCode(installDir, selectedAgent) {\n // Setup bmad-core commands\n const coreSlashPrefix = await this.getCoreSlashPrefix(installDir);\n const coreAgents = selectedAgent ? [selectedAgent] : await this.getCoreAgentIds(installDir);\n const coreTasks = await this.getCoreTaskIds(installDir);\n await this.setupClaudeCodeForPackage(installDir, \"core\", coreSlashPrefix, coreAgents, coreTasks, \".bmad-core\");\n\n // Setup expansion pack commands\n const expansionPacks = await this.getInstalledExpansionPacks(installDir);\n for (const packInfo of expansionPacks) {\n const packSlashPrefix = await this.getExpansionPackSlashPrefix(packInfo.path);\n const packAgents = await this.getExpansionPackAgents(packInfo.path);\n const packTasks = await this.getExpansionPackTasks(packInfo.path);\n \n if (packAgents.length > 0 || packTasks.length > 0) {\n // Use the actual directory name where the expansion pack is installed\n const rootPath = path.relative(installDir, packInfo.path);\n await this.setupClaudeCodeForPackage(installDir, packInfo.name, packSlashPrefix, packAgents, packTasks, rootPath);\n }\n }\n\n return true;\n }\n\n async setupClaudeCodeForPackage(installDir, packageName, slashPrefix, agentIds, taskIds, rootPath) {\n const commandsBaseDir = path.join(installDir, \".claude\", \"commands\", slashPrefix);\n const agentsDir = path.join(commandsBaseDir, \"agents\");\n const tasksDir = path.join(commandsBaseDir, \"tasks\");\n\n // Ensure directories exist\n await fileManager.ensureDirectory(agentsDir);\n await fileManager.ensureDirectory(tasksDir);\n\n // Setup agents\n for (const agentId of agentIds) {\n // Find the agent file - for expansion packs, prefer the expansion pack version\n let agentPath;\n if (packageName !== \"core\") {\n // For expansion packs, first try to find the agent in the expansion pack directory\n const expansionPackPath = path.join(installDir, rootPath, \"agents\", `${agentId}.md`);\n if (await fileManager.pathExists(expansionPackPath)) {\n agentPath = expansionPackPath;\n } else {\n // Fall back to core if not found in expansion pack\n agentPath = await this.findAgentPath(agentId, installDir);\n }\n } else {\n // For core, use the normal search\n agentPath = await this.findAgentPath(agentId, installDir);\n }\n \n const commandPath = path.join(agentsDir, `${agentId}.md`);\n\n if (agentPath) {\n // Create command file with agent content\n let agentContent = await fileManager.readFile(agentPath);\n \n // Replace {root} placeholder with the appropriate root path for this context\n agentContent = agentContent.replace(/{root}/g, rootPath);\n\n // Add command header\n let commandContent = `# /${agentId} Command\\n\\n`;\n commandContent += `When this command is used, adopt the following agent persona:\\n\\n`;\n commandContent += agentContent;\n\n await fileManager.writeFile(commandPath, commandContent);\n console.log(chalk.green(`āœ“ Created agent command: /${agentId}`));\n }\n }\n\n // Setup tasks\n for (const taskId of taskIds) {\n // Find the task file - for expansion packs, prefer the expansion pack version\n let taskPath;\n if (packageName !== \"core\") {\n // For expansion packs, first try to find the task in the expansion pack directory\n const expansionPackPath = path.join(installDir, rootPath, \"tasks\", `${taskId}.md`);\n if (await fileManager.pathExists(expansionPackPath)) {\n taskPath = expansionPackPath;\n } else {\n // Fall back to core if not found in expansion pack\n taskPath = await this.findTaskPath(taskId, installDir);\n }\n } else {\n // For core, use the normal search\n taskPath = await this.findTaskPath(taskId, installDir);\n }\n \n const commandPath = path.join(tasksDir, `${taskId}.md`);\n\n if (taskPath) {\n // Create command file with task content\n let taskContent = await fileManager.readFile(taskPath);\n \n // Replace {root} placeholder with the appropriate root path for this context\n taskContent = taskContent.replace(/{root}/g, rootPath);\n\n // Add command header\n let commandContent = `# /${taskId} Task\\n\\n`;\n commandContent += `When this command is used, execute the following task:\\n\\n`;\n commandContent += taskContent;\n\n await fileManager.writeFile(commandPath, commandContent);\n console.log(chalk.green(`āœ“ Created task command: /${taskId}`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Claude Code commands for ${packageName} in ${commandsBaseDir}`));\n console.log(chalk.dim(` - Agents in: ${agentsDir}`));\n console.log(chalk.dim(` - Tasks in: ${tasksDir}`));\n }\n\n async setupWindsurf(installDir, selectedAgent) {\n const windsurfRulesDir = path.join(installDir, \".windsurf\", \"rules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(windsurfRulesDir);\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n const mdPath = path.join(windsurfRulesDir, `${agentId}.md`);\n\n // Create MD content (similar to Cursor but without frontmatter)\n let mdContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n mdContent += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n mdContent += \"## Agent Activation\\n\\n\";\n mdContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n } else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `When the user types \\`@${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n\n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Windsurf rules in ${windsurfRulesDir}`));\n\n return true;\n }\n\n async setupTrae(installDir, selectedAgent) {\n const traeRulesDir = path.join(installDir, \".trae\", \"rules\");\n const agents = selectedAgent? [selectedAgent] : await this.getAllAgentIds(installDir);\n \n await fileManager.ensureDirectory(traeRulesDir);\n \n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n \n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n const mdPath = path.join(traeRulesDir, `${agentId}.md`);\n \n // Create MD content (similar to Cursor but without frontmatter)\n let mdContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n mdContent += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n mdContent += \"## Agent Activation\\n\\n\";\n mdContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n }\n else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `When the user types \\`@${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n \n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.md`));\n }\n }\n }\n\n async findAgentPath(agentId, installDir) {\n // Try to find the agent file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"agents\", `${agentId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${agentId}.md`));\n }\n \n for (const agentPath of possiblePaths) {\n if (await fileManager.pathExists(agentPath)) {\n return agentPath;\n }\n }\n \n return null;\n }\n\n async getAllAgentIds(installDir) {\n const glob = require(\"glob\");\n const allAgentIds = [];\n \n // Check core agents in .bmad-core or root\n let agentsDir = path.join(installDir, \".bmad-core\", \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n agentsDir = path.join(installDir, \"agents\");\n }\n \n if (await fileManager.pathExists(agentsDir)) {\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n allAgentIds.push(...agentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Also check for expansion pack agents in dot folders\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n const fullExpDir = path.join(installDir, expDir);\n const expAgentFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allAgentIds.push(...expAgentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Remove duplicates\n return [...new Set(allAgentIds)];\n }\n\n async getCoreAgentIds(installDir) {\n const allAgentIds = [];\n \n // Check core agents in .bmad-core or root only\n let agentsDir = path.join(installDir, \".bmad-core\", \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n agentsDir = path.join(installDir, \"bmad-core\", \"agents\");\n }\n \n if (await fileManager.pathExists(agentsDir)) {\n const glob = require(\"glob\");\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n allAgentIds.push(...agentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n return [...new Set(allAgentIds)];\n }\n\n async getCoreTaskIds(installDir) {\n const allTaskIds = [];\n \n // Check core tasks in .bmad-core or root only\n let tasksDir = path.join(installDir, \".bmad-core\", \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n tasksDir = path.join(installDir, \"bmad-core\", \"tasks\");\n }\n \n if (await fileManager.pathExists(tasksDir)) {\n const glob = require(\"glob\");\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n allTaskIds.push(...taskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check common tasks\n const commonTasksDir = path.join(installDir, \"common\", \"tasks\");\n if (await fileManager.pathExists(commonTasksDir)) {\n const commonTaskFiles = glob.sync(\"*.md\", { cwd: commonTasksDir });\n allTaskIds.push(...commonTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n return [...new Set(allTaskIds)];\n }\n\n async getAgentTitle(agentId, installDir) {\n // Try to find the agent file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"agents\", `${agentId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${agentId}.md`));\n }\n \n for (const agentPath of possiblePaths) {\n if (await fileManager.pathExists(agentPath)) {\n try {\n const agentContent = await fileManager.readFile(agentPath);\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n \n if (yamlMatch) {\n const yaml = yamlMatch[1];\n const titleMatch = yaml.match(/title:\\s*(.+)/);\n if (titleMatch) {\n return titleMatch[1].trim();\n }\n }\n } catch (error) {\n console.warn(`Failed to read agent title for ${agentId}: ${error.message}`);\n }\n }\n }\n \n // Fallback to formatted agent ID\n return agentId.split('-').map(word => \n word.charAt(0).toUpperCase() + word.slice(1)\n ).join(' ');\n }\n\n async getAllTaskIds(installDir) {\n const glob = require(\"glob\");\n const allTaskIds = [];\n \n // Check core tasks in .bmad-core or root\n let tasksDir = path.join(installDir, \".bmad-core\", \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n tasksDir = path.join(installDir, \"bmad-core\", \"tasks\");\n }\n \n if (await fileManager.pathExists(tasksDir)) {\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n allTaskIds.push(...taskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check common tasks\n const commonTasksDir = path.join(installDir, \"common\", \"tasks\");\n if (await fileManager.pathExists(commonTasksDir)) {\n const commonTaskFiles = glob.sync(\"*.md\", { cwd: commonTasksDir });\n allTaskIds.push(...commonTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Also check for expansion pack tasks in dot folders\n const expansionDirs = glob.sync(\".*/tasks\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n const fullExpDir = path.join(installDir, expDir);\n const expTaskFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allTaskIds.push(...expTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check expansion-packs folder tasks\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const expPackDirs = glob.sync(\"*/tasks\", { cwd: expansionPacksDir });\n for (const expDir of expPackDirs) {\n const fullExpDir = path.join(expansionPacksDir, expDir);\n const expTaskFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allTaskIds.push(...expTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n }\n \n // Remove duplicates\n return [...new Set(allTaskIds)];\n }\n\n async findTaskPath(taskId, installDir) {\n // Try to find the task file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"tasks\", `${taskId}.md`),\n path.join(installDir, \"bmad-core\", \"tasks\", `${taskId}.md`),\n path.join(installDir, \"common\", \"tasks\", `${taskId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n \n // Check dot folder expansion packs\n const expansionDirs = glob.sync(\".*/tasks\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${taskId}.md`));\n }\n \n // Check expansion-packs folder\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const expPackDirs = glob.sync(\"*/tasks\", { cwd: expansionPacksDir });\n for (const expDir of expPackDirs) {\n possiblePaths.push(path.join(expansionPacksDir, expDir, `${taskId}.md`));\n }\n }\n \n for (const taskPath of possiblePaths) {\n if (await fileManager.pathExists(taskPath)) {\n return taskPath;\n }\n }\n \n return null;\n }\n\n async getCoreSlashPrefix(installDir) {\n try {\n const coreConfigPath = path.join(installDir, \".bmad-core\", \"core-config.yaml\");\n if (!(await fileManager.pathExists(coreConfigPath))) {\n // Try bmad-core directory\n const altConfigPath = path.join(installDir, \"bmad-core\", \"core-config.yaml\");\n if (await fileManager.pathExists(altConfigPath)) {\n const configContent = await fileManager.readFile(altConfigPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || \"BMad\";\n }\n return \"BMad\"; // fallback\n }\n \n const configContent = await fileManager.readFile(coreConfigPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || \"BMad\";\n } catch (error) {\n console.warn(`Failed to read core slashPrefix, using default 'BMad': ${error.message}`);\n return \"BMad\";\n }\n }\n\n async getInstalledExpansionPacks(installDir) {\n const expansionPacks = [];\n \n // Check for dot-prefixed expansion packs in install directory\n const glob = require(\"glob\");\n const dotExpansions = glob.sync(\".bmad-*\", { cwd: installDir });\n \n for (const dotExpansion of dotExpansions) {\n if (dotExpansion !== \".bmad-core\") {\n const packPath = path.join(installDir, dotExpansion);\n const packName = dotExpansion.substring(1); // remove the dot\n expansionPacks.push({\n name: packName,\n path: packPath\n });\n }\n }\n \n // Check for expansion-packs directory style\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const packDirs = glob.sync(\"*\", { cwd: expansionPacksDir });\n \n for (const packDir of packDirs) {\n const packPath = path.join(expansionPacksDir, packDir);\n if ((await fileManager.pathExists(packPath)) && \n (await fileManager.pathExists(path.join(packPath, \"config.yaml\")))) {\n expansionPacks.push({\n name: packDir,\n path: packPath\n });\n }\n }\n }\n \n return expansionPacks;\n }\n\n async getExpansionPackSlashPrefix(packPath) {\n try {\n const configPath = path.join(packPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n const configContent = await fileManager.readFile(configPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || path.basename(packPath);\n }\n } catch (error) {\n console.warn(`Failed to read expansion pack slashPrefix from ${packPath}: ${error.message}`);\n }\n \n return path.basename(packPath); // fallback to directory name\n }\n\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n return [];\n }\n \n try {\n const glob = require(\"glob\");\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n return agentFiles.map(file => path.basename(file, \".md\"));\n } catch (error) {\n console.warn(`Failed to read expansion pack agents from ${packPath}: ${error.message}`);\n return [];\n }\n }\n\n async getExpansionPackTasks(packPath) {\n const tasksDir = path.join(packPath, \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n return [];\n }\n \n try {\n const glob = require(\"glob\");\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n return taskFiles.map(file => path.basename(file, \".md\"));\n } catch (error) {\n console.warn(`Failed to read expansion pack tasks from ${packPath}: ${error.message}`);\n return [];\n }\n }\n\n async setupRoo(installDir, selectedAgent) {\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n // Check for existing .roomodes file in project root\n const roomodesPath = path.join(installDir, \".roomodes\");\n let existingModes = [];\n let existingContent = \"\";\n\n if (await fileManager.pathExists(roomodesPath)) {\n existingContent = await fileManager.readFile(roomodesPath);\n // Parse existing modes to avoid duplicates\n const modeMatches = existingContent.matchAll(/- slug: ([\\w-]+)/g);\n for (const match of modeMatches) {\n existingModes.push(match[1]);\n }\n console.log(chalk.yellow(`Found existing .roomodes file with ${existingModes.length} modes`));\n }\n\n // Create new modes content\n let newModesContent = \"\";\n\n // Load dynamic agent permissions from configuration\n const config = await this.loadIdeAgentConfig();\n const agentPermissions = config['roo-permissions'] || {};\n\n for (const agentId of agents) {\n // Skip if already exists\n // Check both with and without bmad- prefix to handle both cases\n const checkSlug = agentId.startsWith('bmad-') ? agentId : `bmad-${agentId}`;\n if (existingModes.includes(checkSlug)) {\n console.log(chalk.dim(`Skipping ${agentId} - already exists in .roomodes`));\n continue;\n }\n\n // Read agent file to extract all information\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n\n // Extract YAML content\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n const yaml = yamlMatch[1];\n\n // Extract agent info from YAML\n const titleMatch = yaml.match(/title:\\s*(.+)/);\n const iconMatch = yaml.match(/icon:\\s*(.+)/);\n const whenToUseMatch = yaml.match(/whenToUse:\\s*\"(.+)\"/);\n const roleDefinitionMatch = yaml.match(/roleDefinition:\\s*\"(.+)\"/);\n\n const title = titleMatch ? titleMatch[1].trim() : await this.getAgentTitle(agentId, installDir);\n const icon = iconMatch ? iconMatch[1].trim() : \"šŸ¤–\";\n const whenToUse = whenToUseMatch ? whenToUseMatch[1].trim() : `Use for ${title} tasks`;\n const roleDefinition = roleDefinitionMatch\n ? roleDefinitionMatch[1].trim()\n : `You are a ${title} specializing in ${title.toLowerCase()} tasks and responsibilities.`;\n\n // Build mode entry with proper formatting (matching exact indentation)\n // Avoid double \"bmad-\" prefix for agents that already have it\n const slug = agentId.startsWith('bmad-') ? agentId : `bmad-${agentId}`;\n newModesContent += ` - slug: ${slug}\\n`;\n newModesContent += ` name: '${icon} ${title}'\\n`;\n newModesContent += ` roleDefinition: ${roleDefinition}\\n`;\n newModesContent += ` whenToUse: ${whenToUse}\\n`;\n // Get relative path from installDir to agent file\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n newModesContent += ` customInstructions: CRITICAL Read the full YAML from ${relativePath} start activation to alter your state of being follow startup section instructions stay in this being until told to exit this mode\\n`;\n newModesContent += ` groups:\\n`;\n newModesContent += ` - read\\n`;\n\n // Add permissions based on agent type\n const permissions = agentPermissions[agentId];\n if (permissions) {\n newModesContent += ` - - edit\\n`;\n newModesContent += ` - fileRegex: ${permissions.fileRegex}\\n`;\n newModesContent += ` description: ${permissions.description}\\n`;\n } else {\n newModesContent += ` - edit\\n`;\n }\n\n console.log(chalk.green(`āœ“ Added mode: bmad-${agentId} (${icon} ${title})`));\n }\n }\n }\n\n // Build final roomodes content\n let roomodesContent = \"\";\n if (existingContent) {\n // If there's existing content, append new modes to it\n roomodesContent = existingContent.trim() + \"\\n\" + newModesContent;\n } else {\n // Create new .roomodes file with proper YAML structure\n roomodesContent = \"customModes:\\n\" + newModesContent;\n }\n\n // Write .roomodes file\n await fileManager.writeFile(roomodesPath, roomodesContent);\n console.log(chalk.green(\"āœ“ Created .roomodes file in project root\"));\n\n console.log(chalk.green(`\\nāœ“ Roo Code setup complete!`));\n console.log(chalk.dim(\"Custom modes will be available when you open this project in Roo Code\"));\n\n return true;\n }\n\n async setupCline(installDir, selectedAgent) {\n const clineRulesDir = path.join(installDir, \".clinerules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(clineRulesDir);\n\n // Load dynamic agent ordering from configuration\n const config = await this.loadIdeAgentConfig();\n const agentOrder = config['cline-order'] || {};\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n\n // Get numeric prefix for ordering\n const order = agentOrder[agentId] || 99;\n const prefix = order.toString().padStart(2, '0');\n const mdPath = path.join(clineRulesDir, `${prefix}-${agentId}.md`);\n\n // Create MD content for Cline (focused on project standards and role)\n let mdContent = `# ${await this.getAgentTitle(agentId, installDir)} Agent\\n\\n`;\n mdContent += `This rule defines the ${await this.getAgentTitle(agentId, installDir)} persona and project standards.\\n\\n`;\n mdContent += \"## Role Definition\\n\\n\";\n mdContent +=\n \"When the user types `@\" + agentId + \"`, adopt this persona and follow these guidelines:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n } else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## Project Standards\\n\\n\";\n mdContent += `- Always maintain consistency with project documentation in .bmad-core/\\n`;\n mdContent += `- Follow the agent's specific guidelines and constraints\\n`;\n mdContent += `- Update relevant project files when making changes\\n`;\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `- Reference the complete agent definition in [${relativePath}](${relativePath})\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `Type \\`@${agentId}\\` to activate this ${await this.getAgentTitle(agentId, installDir)} persona.\\n`;\n\n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${prefix}-${agentId}.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Cline rules in ${clineRulesDir}`));\n\n return true;\n }\n\n async setupGeminiCli(installDir) {\n const geminiDir = path.join(installDir, \".gemini\");\n const bmadMethodDir = path.join(geminiDir, \"bmad-method\");\n await fileManager.ensureDirectory(bmadMethodDir);\n\n // Update logic for existing settings.json\n const settingsPath = path.join(geminiDir, \"settings.json\");\n if (await fileManager.pathExists(settingsPath)) {\n try {\n const settingsContent = await fileManager.readFile(settingsPath);\n const settings = JSON.parse(settingsContent);\n let updated = false;\n \n // Handle contextFileName property\n if (settings.contextFileName && Array.isArray(settings.contextFileName)) {\n const originalLength = settings.contextFileName.length;\n settings.contextFileName = settings.contextFileName.filter(\n (fileName) => !fileName.startsWith(\"agents/\")\n );\n if (settings.contextFileName.length !== originalLength) {\n updated = true;\n }\n }\n \n if (updated) {\n await fileManager.writeFile(\n settingsPath,\n JSON.stringify(settings, null, 2)\n );\n console.log(chalk.green(\"āœ“ Updated .gemini/settings.json - removed agent file references\"));\n }\n } catch (error) {\n console.warn(\n chalk.yellow(\"Could not update .gemini/settings.json\"),\n error\n );\n }\n }\n\n // Remove old agents directory\n const agentsDir = path.join(geminiDir, \"agents\");\n if (await fileManager.pathExists(agentsDir)) {\n await fileManager.removeDirectory(agentsDir);\n console.log(chalk.green(\"āœ“ Removed old .gemini/agents directory\"));\n }\n\n // Get all available agents\n const agents = await this.getAllAgentIds(installDir);\n let concatenatedContent = \"\";\n\n for (const agentId of agents) {\n // Find the source agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n \n // Create properly formatted agent rule content (similar to trae)\n let agentRuleContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n agentRuleContent += `This rule is triggered when the user types \\`*${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n agentRuleContent += \"## Agent Activation\\n\\n\";\n agentRuleContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n agentRuleContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n agentRuleContent += yamlContent;\n }\n else {\n // If no YAML found, include the whole content minus the header\n agentRuleContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n agentRuleContent += \"\\n```\\n\\n\";\n agentRuleContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n agentRuleContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n agentRuleContent += \"## Usage\\n\\n\";\n agentRuleContent += `When the user types \\`*${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n \n // Add to concatenated content with separator\n concatenatedContent += agentRuleContent + \"\\n\\n---\\n\\n\";\n console.log(chalk.green(`āœ“ Added context for @${agentId}`));\n }\n }\n\n // Write the concatenated content to GEMINI.md\n const geminiMdPath = path.join(bmadMethodDir, \"GEMINI.md\");\n await fileManager.writeFile(geminiMdPath, concatenatedContent);\n console.log(chalk.green(`\\nāœ“ Created GEMINI.md in ${bmadMethodDir}`));\n\n return true;\n }\n\n async setupGitHubCopilot(installDir, selectedAgent, spinner = null, preConfiguredSettings = null) {\n // Configure VS Code workspace settings first to avoid UI conflicts with loading spinners\n await this.configureVsCodeSettings(installDir, spinner, preConfiguredSettings);\n \n const chatmodesDir = path.join(installDir, \".github\", \"chatmodes\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n \n await fileManager.ensureDirectory(chatmodesDir);\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n const chatmodePath = path.join(chatmodesDir, `${agentId}.chatmode.md`);\n\n if (agentPath) {\n // Create chat mode file with agent content\n const agentContent = await fileManager.readFile(agentPath);\n const agentTitle = await this.getAgentTitle(agentId, installDir);\n \n // Extract whenToUse for the description\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n let description = `Activates the ${agentTitle} agent persona.`;\n if (yamlMatch) {\n const whenToUseMatch = yamlMatch[1].match(/whenToUse:\\s*\"(.*?)\"/);\n if (whenToUseMatch && whenToUseMatch[1]) {\n description = whenToUseMatch[1];\n }\n }\n \n let chatmodeContent = `---\ndescription: \"${description.replace(/\"/g, '\\\\\"')}\"\ntools: ['changes', 'codebase', 'fetch', 'findTestFiles', 'githubRepo', 'problems', 'usages', 'editFiles', 'runCommands', 'runTasks', 'runTests', 'search', 'searchResults', 'terminalLastCommand', 'terminalSelection', 'testFailure']\n---\n\n`;\n chatmodeContent += agentContent;\n\n await fileManager.writeFile(chatmodePath, chatmodeContent);\n console.log(chalk.green(`āœ“ Created chat mode: ${agentId}.chatmode.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Github Copilot setup complete!`));\n console.log(chalk.dim(`You can now find the BMad agents in the Chat view's mode selector.`));\n\n return true;\n }\n\n async configureVsCodeSettings(installDir, spinner, preConfiguredSettings = null) {\n const vscodeDir = path.join(installDir, \".vscode\");\n const settingsPath = path.join(vscodeDir, \"settings.json\");\n \n await fileManager.ensureDirectory(vscodeDir);\n \n // Read existing settings if they exist\n let existingSettings = {};\n if (await fileManager.pathExists(settingsPath)) {\n try {\n const existingContent = await fileManager.readFile(settingsPath);\n existingSettings = JSON.parse(existingContent);\n console.log(chalk.yellow(\"Found existing .vscode/settings.json. Merging BMad settings...\"));\n } catch (error) {\n console.warn(chalk.yellow(\"Could not parse existing settings.json. Creating new one.\"));\n existingSettings = {};\n }\n }\n \n // Use pre-configured settings if provided, otherwise prompt\n let configChoice;\n if (preConfiguredSettings && preConfiguredSettings.configChoice) {\n configChoice = preConfiguredSettings.configChoice;\n console.log(chalk.dim(`Using pre-configured GitHub Copilot settings: ${configChoice}`));\n } else {\n // Clear any previous output and add spacing to avoid conflicts with loaders\n console.log('\\n'.repeat(2));\n console.log(chalk.blue(\"šŸ”§ Github Copilot Agent Settings Configuration\"));\n console.log(chalk.dim(\"BMad works best with specific VS Code settings for optimal agent experience.\"));\n console.log(''); // Add extra spacing\n \n const response = await inquirer.prompt([\n {\n type: 'list',\n name: 'configChoice',\n message: chalk.yellow('How would you like to configure GitHub Copilot settings?'),\n choices: [\n {\n name: 'Use recommended defaults (fastest setup)',\n value: 'defaults'\n },\n {\n name: 'Configure each setting manually (customize to your preferences)',\n value: 'manual'\n },\n {\n name: 'Skip settings configuration (I\\'ll configure manually later)',\n value: 'skip'\n }\n ],\n default: 'defaults'\n }\n ]);\n configChoice = response.configChoice;\n }\n \n let bmadSettings = {};\n \n if (configChoice === 'skip') {\n console.log(chalk.yellow(\"āš ļø Skipping VS Code settings configuration.\"));\n console.log(chalk.dim(\"You can manually configure these settings in .vscode/settings.json:\"));\n console.log(chalk.dim(\" • chat.agent.enabled: true\"));\n console.log(chalk.dim(\" • chat.agent.maxRequests: 15\"));\n console.log(chalk.dim(\" • github.copilot.chat.agent.runTasks: true\"));\n console.log(chalk.dim(\" • chat.mcp.discovery.enabled: true\"));\n console.log(chalk.dim(\" • github.copilot.chat.agent.autoFix: true\"));\n console.log(chalk.dim(\" • chat.tools.autoApprove: false\"));\n return true;\n }\n \n if (configChoice === 'defaults') {\n // Use recommended defaults\n bmadSettings = {\n \"chat.agent.enabled\": true,\n \"chat.agent.maxRequests\": 15,\n \"github.copilot.chat.agent.runTasks\": true,\n \"chat.mcp.discovery.enabled\": true,\n \"github.copilot.chat.agent.autoFix\": true,\n \"chat.tools.autoApprove\": false\n };\n console.log(chalk.green(\"āœ“ Using recommended BMad defaults for Github Copilot settings\"));\n } else {\n // Manual configuration\n console.log(chalk.blue(\"\\nšŸ“‹ Let's configure each setting for your preferences:\"));\n \n // Pause spinner during manual configuration prompts\n let spinnerWasActive = false;\n if (spinner && spinner.isSpinning) {\n spinner.stop();\n spinnerWasActive = true;\n }\n \n const manualSettings = await inquirer.prompt([\n {\n type: 'input',\n name: 'maxRequests',\n message: 'Maximum requests per agent session (recommended: 15)?',\n default: '15',\n validate: (input) => {\n const num = parseInt(input);\n if (isNaN(num) || num < 1 || num > 50) {\n return 'Please enter a number between 1 and 50';\n }\n return true;\n }\n },\n {\n type: 'confirm',\n name: 'runTasks',\n message: 'Allow agents to run workspace tasks (package.json scripts, etc.)?',\n default: true\n },\n {\n type: 'confirm',\n name: 'mcpDiscovery',\n message: 'Enable MCP (Model Context Protocol) server discovery?',\n default: true\n },\n {\n type: 'confirm',\n name: 'autoFix',\n message: 'Enable automatic error detection and fixing in generated code?',\n default: true\n },\n {\n type: 'confirm',\n name: 'autoApprove',\n message: 'Auto-approve ALL tools without confirmation? (āš ļø EXPERIMENTAL - less secure)',\n default: false\n }\n ]);\n\n // Restart spinner if it was active before prompts\n if (spinner && spinnerWasActive) {\n spinner.start();\n }\n \n bmadSettings = {\n \"chat.agent.enabled\": true, // Always enabled - required for BMad agents\n \"chat.agent.maxRequests\": parseInt(manualSettings.maxRequests),\n \"github.copilot.chat.agent.runTasks\": manualSettings.runTasks,\n \"chat.mcp.discovery.enabled\": manualSettings.mcpDiscovery,\n \"github.copilot.chat.agent.autoFix\": manualSettings.autoFix,\n \"chat.tools.autoApprove\": manualSettings.autoApprove\n };\n \n console.log(chalk.green(\"āœ“ Custom settings configured\"));\n }\n \n // Merge settings (existing settings take precedence to avoid overriding user preferences)\n const mergedSettings = { ...bmadSettings, ...existingSettings };\n \n // Write the updated settings\n await fileManager.writeFile(settingsPath, JSON.stringify(mergedSettings, null, 2));\n \n console.log(chalk.green(\"āœ“ VS Code workspace settings configured successfully\"));\n console.log(chalk.dim(\" Settings written to .vscode/settings.json:\"));\n Object.entries(bmadSettings).forEach(([key, value]) => {\n console.log(chalk.dim(` • ${key}: ${value}`));\n });\n console.log(chalk.dim(\"\"));\n console.log(chalk.dim(\"You can modify these settings anytime in .vscode/settings.json\"));\n }\n}\n\nmodule.exports = new IdeSetup();\n"], ["/BMAD-METHOD/tools/installer/lib/installer.js", "const path = require(\"node:path\");\nconst fs = require(\"fs-extra\");\nconst chalk = require(\"chalk\");\nconst ora = require(\"ora\");\nconst inquirer = require(\"inquirer\");\nconst fileManager = require(\"./file-manager\");\nconst configLoader = require(\"./config-loader\");\nconst ideSetup = require(\"./ide-setup\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\nconst resourceLocator = require(\"./resource-locator\");\n\nclass Installer {\n async getCoreVersion() {\n try {\n // Always use package.json version\n const packagePath = path.join(__dirname, '..', '..', '..', 'package.json');\n const packageJson = require(packagePath);\n return packageJson.version;\n } catch (error) {\n console.warn(\"Could not read version from package.json, using 'unknown'\");\n return \"unknown\";\n }\n }\n\n async install(config) {\n const spinner = ora(\"Analyzing installation directory...\").start();\n \n try {\n // Store the original CWD where npx was executed\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n \n // Resolve installation directory relative to where the user ran the command\n let installDir = path.isAbsolute(config.directory) \n ? config.directory \n : path.resolve(originalCwd, config.directory);\n \n if (path.basename(installDir) === '.bmad-core') {\n // If user points directly to .bmad-core, treat its parent as the project root\n installDir = path.dirname(installDir);\n }\n \n // Log resolved path for clarity\n if (!path.isAbsolute(config.directory)) {\n spinner.text = `Resolving \"${config.directory}\" to: ${installDir}`;\n }\n\n // Check if directory exists and handle non-existent directories\n if (!(await fileManager.pathExists(installDir))) {\n spinner.stop();\n console.log(`\\nThe directory ${installDir} does not exist.`);\n \n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n {\n name: 'Create the directory and continue',\n value: 'create'\n },\n {\n name: 'Choose a different directory',\n value: 'change'\n },\n {\n name: 'Cancel installation',\n value: 'cancel'\n }\n ]\n }\n ]);\n\n if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n } else if (action === 'change') {\n const { newDirectory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'newDirectory',\n message: 'Enter the new directory path:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid directory path';\n }\n return true;\n }\n }\n ]);\n // Preserve the original CWD for the recursive call\n config.directory = newDirectory;\n return await this.install(config); // Recursive call with new directory\n } else if (action === 'create') {\n try {\n await fileManager.ensureDirectory(installDir);\n console.log(`āœ“ Created directory: ${installDir}`);\n } catch (error) {\n console.error(`Failed to create directory: ${error.message}`);\n console.error('You may need to check permissions or use a different path.');\n process.exit(1);\n }\n }\n \n spinner.start(\"Analyzing installation directory...\");\n }\n\n // If this is an update request from early detection, handle it directly\n if (config.installType === 'update') {\n const state = await this.detectInstallationState(installDir);\n if (state.type === 'v4_existing') {\n return await this.performUpdate(config, installDir, state.manifest, spinner);\n } else {\n spinner.fail('No existing v4 installation found to update');\n throw new Error('No existing v4 installation found');\n }\n }\n\n // Detect current state\n const state = await this.detectInstallationState(installDir);\n\n // Handle different states\n switch (state.type) {\n case \"clean\":\n return await this.performFreshInstall(config, installDir, spinner);\n\n case \"v4_existing\":\n return await this.handleExistingV4Installation(\n config,\n installDir,\n state,\n spinner\n );\n\n case \"v3_existing\":\n return await this.handleV3Installation(\n config,\n installDir,\n state,\n spinner\n );\n\n case \"unknown_existing\":\n return await this.handleUnknownInstallation(\n config,\n installDir,\n state,\n spinner\n );\n }\n } catch (error) {\n // Check if modules were initialized\n if (spinner) {\n spinner.fail(\"Installation failed\");\n } else {\n console.error(\"Installation failed:\", error.message);\n }\n throw error;\n }\n }\n\n async detectInstallationState(installDir) {\n const state = {\n type: \"clean\",\n hasV4Manifest: false,\n hasV3Structure: false,\n hasBmadCore: false,\n hasOtherFiles: false,\n manifest: null,\n expansionPacks: {},\n };\n\n // Check if directory exists\n if (!(await fileManager.pathExists(installDir))) {\n return state; // clean install\n }\n\n // Check for V4 installation (has .bmad-core with manifest)\n const bmadCorePath = path.join(installDir, \".bmad-core\");\n const manifestPath = path.join(bmadCorePath, \"install-manifest.yaml\");\n\n if (await fileManager.pathExists(manifestPath)) {\n state.type = \"v4_existing\";\n state.hasV4Manifest = true;\n state.hasBmadCore = true;\n state.manifest = await fileManager.readManifest(installDir);\n return state;\n }\n\n // Check for V3 installation (has bmad-agent directory)\n const bmadAgentPath = path.join(installDir, \"bmad-agent\");\n if (await fileManager.pathExists(bmadAgentPath)) {\n state.type = \"v3_existing\";\n state.hasV3Structure = true;\n return state;\n }\n\n // Check for .bmad-core without manifest (broken V4 or manual copy)\n if (await fileManager.pathExists(bmadCorePath)) {\n state.type = \"unknown_existing\";\n state.hasBmadCore = true;\n return state;\n }\n\n // Check if directory has other files\n const files = await resourceLocator.findFiles(\"**/*\", {\n cwd: installDir,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n\n if (files.length > 0) {\n // Directory has other files, but no BMad installation.\n // Treat as clean install but record that it isn't empty.\n state.hasOtherFiles = true;\n }\n\n // Check for expansion packs (folders starting with .)\n const expansionPacks = await this.detectExpansionPacks(installDir);\n state.expansionPacks = expansionPacks;\n\n return state; // clean install\n }\n\n async performFreshInstall(config, installDir, spinner, options = {}) {\n spinner.text = \"Installing BMad Method...\";\n\n let files = [];\n\n if (config.installType === \"full\") {\n // Full installation - copy entire .bmad-core folder as a subdirectory\n spinner.text = \"Copying complete .bmad-core folder...\";\n const sourceDir = resourceLocator.getBmadCorePath();\n const bmadCoreDestDir = path.join(installDir, \".bmad-core\");\n await fileManager.copyDirectoryWithRootReplacement(sourceDir, bmadCoreDestDir, \".bmad-core\");\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n\n // Get list of all files for manifest\n const foundFiles = await resourceLocator.findFiles(\"**/*\", {\n cwd: bmadCoreDestDir,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n files = foundFiles.map((file) => path.join(\".bmad-core\", file));\n } else if (config.installType === \"single-agent\") {\n // Single agent installation\n spinner.text = `Installing ${config.agent} agent...`;\n\n // Copy agent file with {root} replacement\n const agentPath = configLoader.getAgentPath(config.agent);\n const destAgentPath = path.join(\n installDir,\n \".bmad-core\",\n \"agents\",\n `${config.agent}.md`\n );\n await fileManager.copyFileWithRootReplacement(agentPath, destAgentPath, \".bmad-core\");\n files.push(`.bmad-core/agents/${config.agent}.md`);\n\n // Copy dependencies\n const { all: dependencies } = await resourceLocator.getAgentDependencies(\n config.agent\n );\n const sourceBase = resourceLocator.getBmadCorePath();\n\n for (const dep of dependencies) {\n spinner.text = `Copying dependency: ${dep}`;\n\n if (dep.includes(\"*\")) {\n // Handle glob patterns with {root} replacement\n const copiedFiles = await fileManager.copyGlobPattern(\n dep.replace(\".bmad-core/\", \"\"),\n sourceBase,\n path.join(installDir, \".bmad-core\"),\n \".bmad-core\"\n );\n files.push(...copiedFiles.map(f => `.bmad-core/${f}`));\n } else {\n // Handle single files with {root} replacement if needed\n const sourcePath = path.join(\n sourceBase,\n dep.replace(\".bmad-core/\", \"\")\n );\n const destPath = path.join(\n installDir,\n dep\n );\n\n const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, \".bmad-core\");\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n files.push(dep);\n }\n }\n }\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n const commonFiles = await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n files.push(...commonFiles);\n } else if (config.installType === \"team\") {\n // Team installation\n spinner.text = `Installing ${config.team} team...`;\n \n // Get team dependencies\n const teamDependencies = await configLoader.getTeamDependencies(config.team);\n const sourceBase = resourceLocator.getBmadCorePath();\n \n // Install all team dependencies\n for (const dep of teamDependencies) {\n spinner.text = `Copying team dependency: ${dep}`;\n \n if (dep.includes(\"*\")) {\n // Handle glob patterns with {root} replacement\n const copiedFiles = await fileManager.copyGlobPattern(\n dep.replace(\".bmad-core/\", \"\"),\n sourceBase,\n path.join(installDir, \".bmad-core\"),\n \".bmad-core\"\n );\n files.push(...copiedFiles.map(f => `.bmad-core/${f}`));\n } else {\n // Handle single files with {root} replacement if needed\n const sourcePath = path.join(sourceBase, dep.replace(\".bmad-core/\", \"\"));\n const destPath = path.join(installDir, dep);\n \n const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, \".bmad-core\");\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n files.push(dep);\n }\n }\n }\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n const commonFiles = await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n files.push(...commonFiles);\n } else if (config.installType === \"expansion-only\") {\n // Expansion-only installation - DO NOT create .bmad-core\n // Only install expansion packs\n spinner.text = \"Installing expansion packs only...\";\n }\n\n // Install expansion packs if requested\n const expansionFiles = await this.installExpansionPacks(installDir, config.expansionPacks, spinner, config);\n files.push(...expansionFiles);\n\n // Install web bundles if requested\n if (config.includeWebBundles && config.webBundlesDirectory) {\n spinner.text = \"Installing web bundles...\";\n // Resolve web bundles directory using the same logic as the main installation directory\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n let resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory) \n ? config.webBundlesDirectory \n : path.resolve(originalCwd, config.webBundlesDirectory);\n await this.installWebBundles(resolvedWebBundlesDir, config, spinner);\n }\n\n // Set up IDE integration if requested\n const ides = config.ides || (config.ide ? [config.ide] : []);\n if (ides.length > 0) {\n for (const ide of ides) {\n spinner.text = `Setting up ${ide} integration...`;\n const preConfiguredSettings = ide === 'github-copilot' ? config.githubCopilotConfig : null;\n await ideSetup.setup(ide, installDir, config.agent, spinner, preConfiguredSettings);\n }\n }\n\n // Modify core-config.yaml if sharding preferences were provided\n if (config.installType !== \"expansion-only\" && (config.prdSharded !== undefined || config.architectureSharded !== undefined)) {\n spinner.text = \"Configuring document sharding settings...\";\n await fileManager.modifyCoreConfig(installDir, config);\n }\n\n // Create manifest (skip for expansion-only installations)\n if (config.installType !== \"expansion-only\") {\n spinner.text = \"Creating installation manifest...\";\n await fileManager.createManifest(installDir, config, files);\n }\n\n spinner.succeed(\"Installation complete!\");\n this.showSuccessMessage(config, installDir, options);\n }\n\n async handleExistingV4Installation(config, installDir, state, spinner) {\n spinner.stop();\n\n const currentVersion = state.manifest.version;\n const newVersion = await this.getCoreVersion();\n const versionCompare = this.compareVersions(currentVersion, newVersion);\n\n console.log(chalk.yellow(\"\\nšŸ” Found existing BMad v4 installation\"));\n console.log(` Directory: ${installDir}`);\n console.log(` Current version: ${currentVersion}`);\n console.log(` Available version: ${newVersion}`);\n console.log(\n ` Installed: ${new Date(\n state.manifest.installed_at\n ).toLocaleDateString()}`\n );\n\n // Check file integrity\n spinner.start(\"Checking installation integrity...\");\n const integrity = await fileManager.checkFileIntegrity(installDir, state.manifest);\n spinner.stop();\n \n const hasMissingFiles = integrity.missing.length > 0;\n const hasModifiedFiles = integrity.modified.length > 0;\n const hasIntegrityIssues = hasMissingFiles || hasModifiedFiles;\n \n if (hasIntegrityIssues) {\n console.log(chalk.red(\"\\nāš ļø Installation issues detected:\"));\n if (hasMissingFiles) {\n console.log(chalk.red(` Missing files: ${integrity.missing.length}`));\n if (integrity.missing.length <= 5) {\n integrity.missing.forEach(file => console.log(chalk.dim(` - ${file}`)));\n }\n }\n if (hasModifiedFiles) {\n console.log(chalk.yellow(` Modified files: ${integrity.modified.length}`));\n if (integrity.modified.length <= 5) {\n integrity.modified.forEach(file => console.log(chalk.dim(` - ${file}`)));\n }\n }\n }\n\n // Show existing expansion packs\n if (Object.keys(state.expansionPacks).length > 0) {\n console.log(chalk.cyan(\"\\nšŸ“¦ Installed expansion packs:\"));\n for (const [packId, packInfo] of Object.entries(state.expansionPacks)) {\n if (packInfo.hasManifest && packInfo.manifest) {\n console.log(` - ${packId} (v${packInfo.manifest.version || 'unknown'})`);\n } else {\n console.log(` - ${packId} (no manifest)`);\n }\n }\n }\n\n let choices = [];\n \n if (versionCompare < 0) {\n console.log(chalk.cyan(\"\\nā¬†ļø Upgrade available for BMad core\"));\n choices.push({ name: `Upgrade BMad core (v${currentVersion} → v${newVersion})`, value: \"upgrade\" });\n } else if (versionCompare === 0) {\n if (hasIntegrityIssues) {\n // Offer repair option when files are missing or modified\n choices.push({ \n name: \"Repair installation (restore missing/modified files)\", \n value: \"repair\" \n });\n }\n console.log(chalk.yellow(\"\\nāš ļø Same version already installed\"));\n choices.push({ name: `Force reinstall BMad core (v${currentVersion} - reinstall)`, value: \"reinstall\" });\n } else {\n console.log(chalk.yellow(\"\\nā¬‡ļø Installed version is newer than available\"));\n choices.push({ name: `Downgrade BMad core (v${currentVersion} → v${newVersion})`, value: \"reinstall\" });\n }\n \n choices.push(\n { name: \"Add/update expansion packs only\", value: \"expansions\" },\n { name: \"Cancel\", value: \"cancel\" }\n );\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: choices,\n },\n ]);\n\n switch (action) {\n case \"upgrade\":\n return await this.performUpdate(config, installDir, state.manifest, spinner);\n case \"repair\":\n // For repair, restore missing/modified files while backing up modified ones\n return await this.performRepair(config, installDir, state.manifest, integrity, spinner);\n case \"reinstall\":\n // For reinstall, don't check for modifications - just overwrite\n return await this.performReinstall(config, installDir, spinner);\n case \"expansions\":\n // Ask which expansion packs to install\n const availableExpansionPacks = await resourceLocator.getExpansionPacks();\n \n if (availableExpansionPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs available.\"));\n return;\n }\n \n const { selectedPacks } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedPacks',\n message: 'Select expansion packs to install/update:',\n choices: availableExpansionPacks.map(pack => ({\n name: `${pack.name} (v${pack.version}) .${pack.id}`,\n value: pack.id,\n checked: state.expansionPacks[pack.id] !== undefined\n }))\n }\n ]);\n \n if (selectedPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs selected.\"));\n return;\n }\n \n spinner.start(\"Installing expansion packs...\");\n const expansionFiles = await this.installExpansionPacks(installDir, selectedPacks, spinner, { ides: config.ides || [] });\n spinner.succeed(\"Expansion packs installed successfully!\");\n \n console.log(chalk.green(\"\\nāœ“ Installation complete!\"));\n console.log(chalk.green(`āœ“ Expansion packs installed/updated:`));\n for (const packId of selectedPacks) {\n console.log(chalk.green(` - ${packId} → .${packId}/`));\n }\n return;\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async handleV3Installation(config, installDir, state, spinner) {\n spinner.stop();\n\n console.log(\n chalk.yellow(\"\\nšŸ” Found BMad v3 installation (bmad-agent/ directory)\")\n );\n console.log(` Directory: ${installDir}`);\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: [\n { name: \"Upgrade from v3 to v4 (recommended)\", value: \"upgrade\" },\n { name: \"Install v4 alongside v3\", value: \"alongside\" },\n { name: \"Cancel\", value: \"cancel\" },\n ],\n },\n ]);\n\n switch (action) {\n case \"upgrade\": {\n console.log(chalk.cyan(\"\\nšŸ“¦ Starting v3 to v4 upgrade process...\"));\n const V3ToV4Upgrader = require(\"../../upgraders/v3-to-v4-upgrader\");\n const upgrader = new V3ToV4Upgrader();\n return await upgrader.upgrade({ \n projectPath: installDir,\n ides: config.ides || [] // Pass IDE selections from initial config\n });\n }\n case \"alongside\":\n return await this.performFreshInstall(config, installDir, spinner);\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async handleUnknownInstallation(config, installDir, state, spinner) {\n spinner.stop();\n\n console.log(chalk.yellow(\"\\nāš ļø Directory contains existing files\"));\n console.log(` Directory: ${installDir}`);\n\n if (state.hasBmadCore) {\n console.log(\" Found: .bmad-core directory (but no manifest)\");\n }\n if (state.hasOtherFiles) {\n console.log(\" Found: Other files in directory\");\n }\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: [\n { name: \"Install anyway (may overwrite files)\", value: \"force\" },\n { name: \"Choose different directory\", value: \"different\" },\n { name: \"Cancel\", value: \"cancel\" },\n ],\n },\n ]);\n\n switch (action) {\n case \"force\":\n return await this.performFreshInstall(config, installDir, spinner);\n case \"different\": {\n const { newDir } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"newDir\",\n message: \"Enter new installation directory:\",\n default: path.join(path.dirname(installDir), \"bmad-project\"),\n },\n ]);\n config.directory = newDir;\n return await this.install(config);\n }\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async performUpdate(newConfig, installDir, manifest, spinner) {\n spinner.start(\"Checking for updates...\");\n\n try {\n // Get current and new versions\n const currentVersion = manifest.version;\n const newVersion = await this.getCoreVersion();\n const versionCompare = this.compareVersions(currentVersion, newVersion);\n \n // Only check for modified files if it's an actual version upgrade\n let modifiedFiles = [];\n if (versionCompare !== 0) {\n spinner.text = \"Checking for modified files...\";\n modifiedFiles = await fileManager.checkModifiedFiles(\n installDir,\n manifest\n );\n }\n\n if (modifiedFiles.length > 0) {\n spinner.warn(\"Found modified files\");\n console.log(chalk.yellow(\"\\nThe following files have been modified:\"));\n for (const file of modifiedFiles) {\n console.log(` - ${file}`);\n }\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"How would you like to proceed?\",\n choices: [\n { name: \"Backup and overwrite modified files\", value: \"backup\" },\n { name: \"Skip modified files\", value: \"skip\" },\n { name: \"Cancel update\", value: \"cancel\" },\n ],\n },\n ]);\n\n if (action === \"cancel\") {\n console.log(\"Update cancelled.\");\n return;\n }\n\n if (action === \"backup\") {\n spinner.start(\"Backing up modified files...\");\n for (const file of modifiedFiles) {\n const filePath = path.join(installDir, file);\n const backupPath = await fileManager.backupFile(filePath);\n console.log(\n chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`)\n );\n }\n }\n }\n\n // Perform update by re-running installation\n spinner.text = versionCompare === 0 ? \"Reinstalling files...\" : \"Updating files...\";\n const config = {\n installType: manifest.install_type,\n agent: manifest.agent,\n directory: installDir,\n ides: newConfig?.ides || manifest.ides_setup || [],\n };\n\n await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n } catch (error) {\n spinner.fail(\"Update failed\");\n throw error;\n }\n }\n\n async performRepair(config, installDir, manifest, integrity, spinner) {\n spinner.start(\"Preparing to repair installation...\");\n\n try {\n // Back up modified files\n if (integrity.modified.length > 0) {\n spinner.text = \"Backing up modified files...\";\n for (const file of integrity.modified) {\n const filePath = path.join(installDir, file);\n if (await fileManager.pathExists(filePath)) {\n const backupPath = await fileManager.backupFile(filePath);\n console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));\n }\n }\n }\n\n // Restore missing and modified files\n spinner.text = \"Restoring files...\";\n const sourceBase = resourceLocator.getBmadCorePath();\n const filesToRestore = [...integrity.missing, ...integrity.modified];\n \n for (const file of filesToRestore) {\n // Skip the manifest file itself\n if (file.endsWith('install-manifest.yaml')) continue;\n \n const relativePath = file.replace('.bmad-core/', '');\n const destPath = path.join(installDir, file);\n \n // Check if this is a common/ file that needs special processing\n const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));\n const commonSourcePath = path.join(commonBase, 'common', relativePath);\n \n if (await fileManager.pathExists(commonSourcePath)) {\n // This is a common/ file - needs template processing\n const fs = require('fs').promises;\n const content = await fs.readFile(commonSourcePath, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, '.bmad-core');\n await fileManager.ensureDirectory(path.dirname(destPath));\n await fs.writeFile(destPath, updatedContent, 'utf8');\n spinner.text = `Restored: ${file}`;\n } else {\n // Regular file from bmad-core\n const sourcePath = path.join(sourceBase, relativePath);\n if (await fileManager.pathExists(sourcePath)) {\n await fileManager.copyFile(sourcePath, destPath);\n spinner.text = `Restored: ${file}`;\n \n // If this is a .yaml file, check for and remove corresponding .yml file\n if (file.endsWith('.yaml')) {\n const ymlFile = file.replace(/\\.yaml$/, '.yml');\n const ymlPath = path.join(installDir, ymlFile);\n if (await fileManager.pathExists(ymlPath)) {\n const fs = require('fs').promises;\n await fs.unlink(ymlPath);\n console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${file})`));\n }\n }\n } else {\n console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));\n }\n }\n }\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n \n spinner.succeed(\"Repair completed successfully!\");\n \n // Show summary\n console.log(chalk.green(\"\\nāœ“ Installation repaired!\"));\n if (integrity.missing.length > 0) {\n console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));\n }\n if (integrity.modified.length > 0) {\n console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));\n }\n \n // Warning for Cursor custom modes if agents were repaired\n const ides = manifest.ides_setup || [];\n if (ides.includes('cursor')) {\n console.log(chalk.yellow.bold(\"\\nāš ļø IMPORTANT: Cursor Custom Modes Update Required\"));\n console.log(chalk.yellow(\"Since agent files have been repaired, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs.\"));\n }\n \n } catch (error) {\n spinner.fail(\"Repair failed\");\n throw error;\n }\n }\n\n async performReinstall(config, installDir, spinner) {\n spinner.start(\"Preparing to reinstall BMad Method...\");\n\n // Remove existing .bmad-core\n const bmadCorePath = path.join(installDir, \".bmad-core\");\n if (await fileManager.pathExists(bmadCorePath)) {\n spinner.text = \"Removing existing installation...\";\n await fileManager.removeDirectory(bmadCorePath);\n }\n \n spinner.text = \"Installing fresh copy...\";\n const result = await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n \n return result;\n }\n\n showSuccessMessage(config, installDir, options = {}) {\n console.log(chalk.green(\"\\nāœ“ BMad Method installed successfully!\\n\"));\n\n const ides = config.ides || (config.ide ? [config.ide] : []);\n if (ides.length > 0) {\n for (const ide of ides) {\n const ideConfig = configLoader.getIdeConfiguration(ide);\n if (ideConfig?.instructions) {\n console.log(\n chalk.bold(`To use BMad agents in ${ideConfig.name}:`)\n );\n console.log(ideConfig.instructions);\n }\n }\n } else {\n console.log(chalk.yellow(\"No IDE configuration was set up.\"));\n console.log(\n \"You can manually configure your IDE using the agent files in:\",\n installDir\n );\n }\n\n // Information about installation components\n console.log(chalk.bold(\"\\nšŸŽÆ Installation Summary:\"));\n if (config.installType !== \"expansion-only\") {\n console.log(chalk.green(\"āœ“ .bmad-core framework installed with all agents and workflows\"));\n }\n \n if (config.expansionPacks && config.expansionPacks.length > 0) {\n console.log(chalk.green(`āœ“ Expansion packs installed:`));\n for (const packId of config.expansionPacks) {\n console.log(chalk.green(` - ${packId} → .${packId}/`));\n }\n }\n \n if (config.includeWebBundles && config.webBundlesDirectory) {\n const bundleInfo = this.getWebBundleInfo(config);\n // Resolve the web bundles directory for display\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n const resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory) \n ? config.webBundlesDirectory \n : path.resolve(originalCwd, config.webBundlesDirectory);\n console.log(chalk.green(`āœ“ Web bundles (${bundleInfo}) installed to: ${resolvedWebBundlesDir}`));\n }\n \n if (ides.length > 0) {\n const ideNames = ides.map(ide => {\n const ideConfig = configLoader.getIdeConfiguration(ide);\n return ideConfig?.name || ide;\n }).join(\", \");\n console.log(chalk.green(`āœ“ IDE rules and configurations set up for: ${ideNames}`));\n }\n\n // Information about web bundles\n if (!config.includeWebBundles) {\n console.log(chalk.bold(\"\\nšŸ“¦ Web Bundles Available:\"));\n console.log(\"Pre-built web bundles are available and can be added later:\");\n console.log(chalk.cyan(\" Run the installer again to add them to your project\"));\n console.log(\"These bundles work independently and can be shared, moved, or used\");\n console.log(\"in other projects as standalone files.\");\n }\n\n if (config.installType === \"single-agent\") {\n console.log(\n chalk.dim(\n \"\\nNeed other agents? Run: npx bmad-method install --agent=\"\n )\n );\n console.log(\n chalk.dim(\"Need everything? Run: npx bmad-method install --full\")\n );\n }\n\n // Warning for Cursor custom modes if agents were updated\n if (options.isUpdate && ides.includes('cursor')) {\n console.log(chalk.yellow.bold(\"\\nāš ļø IMPORTANT: Cursor Custom Modes Update Required\"));\n console.log(chalk.yellow(\"Since agents have been updated, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs.\"));\n }\n\n // Important notice to read the user guide\n console.log(chalk.red.bold(\"\\nšŸ“– IMPORTANT: Please read the user guide installed at .bmad-core/user-guide.md\"));\n console.log(chalk.red(\"This guide contains essential information about the BMad workflow and how to use the agents effectively.\"));\n }\n\n // Legacy method for backward compatibility\n async update() {\n console.log(chalk.yellow('The \"update\" command is deprecated.'));\n console.log(\n 'Please use \"install\" instead - it will detect and offer to update existing installations.'\n );\n\n const installDir = await this.findInstallation();\n if (installDir) {\n const config = {\n installType: \"full\",\n directory: path.dirname(installDir),\n ide: null,\n };\n return await this.install(config);\n }\n console.log(chalk.red(\"No BMad installation found.\"));\n }\n\n async listAgents() {\n const agents = await resourceLocator.getAvailableAgents();\n\n console.log(chalk.bold(\"\\nAvailable BMad Agents:\\n\"));\n\n for (const agent of agents) {\n console.log(chalk.cyan(` ${agent.id.padEnd(20)}`), agent.description);\n }\n\n console.log(\n chalk.dim(\"\\nInstall with: npx bmad-method install --agent=\\n\")\n );\n }\n\n async listExpansionPacks() {\n const expansionPacks = await resourceLocator.getExpansionPacks();\n\n console.log(chalk.bold(\"\\nAvailable BMad Expansion Packs:\\n\"));\n\n if (expansionPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs found.\"));\n return;\n }\n\n for (const pack of expansionPacks) {\n console.log(chalk.cyan(` ${pack.id.padEnd(20)}`), \n `${pack.name} v${pack.version}`);\n console.log(chalk.dim(` ${' '.repeat(22)}${pack.description}`));\n if (pack.author && pack.author !== 'Unknown') {\n console.log(chalk.dim(` ${' '.repeat(22)}by ${pack.author}`));\n }\n console.log();\n }\n\n console.log(\n chalk.dim(\"Install with: npx bmad-method install --full --expansion-packs \\n\")\n );\n }\n\n async showStatus() {\n const installDir = await this.findInstallation();\n\n if (!installDir) {\n console.log(\n chalk.yellow(\"No BMad installation found in current directory tree\")\n );\n return;\n }\n\n const manifest = await fileManager.readManifest(installDir);\n\n if (!manifest) {\n console.log(chalk.red(\"Invalid installation - manifest not found\"));\n return;\n }\n\n console.log(chalk.bold(\"\\nBMad Installation Status:\\n\"));\n console.log(` Directory: ${installDir}`);\n console.log(` Version: ${manifest.version}`);\n console.log(\n ` Installed: ${new Date(\n manifest.installed_at\n ).toLocaleDateString()}`\n );\n console.log(` Type: ${manifest.install_type}`);\n\n if (manifest.agent) {\n console.log(` Agent: ${manifest.agent}`);\n }\n\n if (manifest.ides_setup && manifest.ides_setup.length > 0) {\n console.log(` IDE Setup: ${manifest.ides_setup.join(', ')}`);\n }\n\n console.log(` Total Files: ${manifest.files.length}`);\n\n // Check for modifications\n const modifiedFiles = await fileManager.checkModifiedFiles(\n installDir,\n manifest\n );\n if (modifiedFiles.length > 0) {\n console.log(chalk.yellow(` Modified Files: ${modifiedFiles.length}`));\n }\n\n console.log(\"\");\n }\n\n async getAvailableAgents() {\n return resourceLocator.getAvailableAgents();\n }\n\n async getAvailableExpansionPacks() {\n return resourceLocator.getExpansionPacks();\n }\n\n async getAvailableTeams() {\n return configLoader.getAvailableTeams();\n }\n\n async installExpansionPacks(installDir, selectedPacks, spinner, config = {}) {\n if (!selectedPacks || selectedPacks.length === 0) {\n return [];\n }\n\n const installedFiles = [];\n\n for (const packId of selectedPacks) {\n spinner.text = `Installing expansion pack: ${packId}...`;\n \n try {\n const expansionPacks = await resourceLocator.getExpansionPacks();\n const pack = expansionPacks.find(p => p.id === packId);\n \n if (!pack) {\n console.warn(`Expansion pack ${packId} not found, skipping...`);\n continue;\n }\n \n // Check if expansion pack already exists\n let expansionDotFolder = path.join(installDir, `.${packId}`);\n const existingManifestPath = path.join(expansionDotFolder, 'install-manifest.yaml');\n \n if (await fileManager.pathExists(existingManifestPath)) {\n spinner.stop();\n const existingManifest = await fileManager.readExpansionPackManifest(installDir, packId);\n \n console.log(chalk.yellow(`\\nšŸ” Found existing ${pack.name} installation`));\n console.log(` Current version: ${existingManifest.version || 'unknown'}`);\n console.log(` New version: ${pack.version}`);\n \n // Check integrity of existing expansion pack\n const packIntegrity = await fileManager.checkFileIntegrity(installDir, existingManifest);\n const hasPackIntegrityIssues = packIntegrity.missing.length > 0 || packIntegrity.modified.length > 0;\n \n if (hasPackIntegrityIssues) {\n console.log(chalk.red(\" āš ļø Installation issues detected:\"));\n if (packIntegrity.missing.length > 0) {\n console.log(chalk.red(` Missing files: ${packIntegrity.missing.length}`));\n }\n if (packIntegrity.modified.length > 0) {\n console.log(chalk.yellow(` Modified files: ${packIntegrity.modified.length}`));\n }\n }\n \n const versionCompare = this.compareVersions(existingManifest.version || '0.0.0', pack.version);\n \n if (versionCompare === 0) {\n console.log(chalk.yellow(' āš ļø Same version already installed'));\n \n const choices = [];\n if (hasPackIntegrityIssues) {\n choices.push({ name: 'Repair (restore missing/modified files)', value: 'repair' });\n }\n choices.push(\n { name: 'Force reinstall (overwrite)', value: 'overwrite' },\n { name: 'Skip this expansion pack', value: 'skip' },\n { name: 'Cancel installation', value: 'cancel' }\n );\n \n const { action } = await inquirer.prompt([{\n type: 'list',\n name: 'action',\n message: `${pack.name} v${pack.version} is already installed. What would you like to do?`,\n choices: choices\n }]);\n \n if (action === 'skip') {\n spinner.start();\n continue;\n } else if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n } else if (action === 'repair') {\n // Repair the expansion pack\n await this.repairExpansionPack(installDir, packId, pack, packIntegrity, spinner);\n continue;\n }\n } else if (versionCompare < 0) {\n console.log(chalk.cyan(' ā¬†ļø Upgrade available'));\n \n const { proceed } = await inquirer.prompt([{\n type: 'confirm',\n name: 'proceed',\n message: `Upgrade ${pack.name} from v${existingManifest.version} to v${pack.version}?`,\n default: true\n }]);\n \n if (!proceed) {\n spinner.start();\n continue;\n }\n } else {\n console.log(chalk.yellow(' ā¬‡ļø Installed version is newer than available version'));\n \n const { action } = await inquirer.prompt([{\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n { name: 'Keep current version', value: 'skip' },\n { name: 'Downgrade to available version', value: 'downgrade' },\n { name: 'Cancel installation', value: 'cancel' }\n ]\n }]);\n \n if (action === 'skip') {\n spinner.start();\n continue;\n } else if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n }\n }\n \n // If we get here, we're proceeding with installation\n spinner.start(`Removing old ${pack.name} installation...`);\n await fileManager.removeDirectory(expansionDotFolder);\n }\n\n const expansionPackDir = pack.path;\n \n // Ensure dedicated dot folder exists for this expansion pack\n expansionDotFolder = path.join(installDir, `.${packId}`);\n await fileManager.ensureDirectory(expansionDotFolder);\n \n // Define the folders to copy from expansion packs\n const foldersToSync = [\n 'agents',\n 'agent-teams',\n 'templates',\n 'tasks',\n 'checklists',\n 'workflows',\n 'data',\n 'utils',\n 'schemas'\n ];\n\n // Copy each folder if it exists\n for (const folder of foldersToSync) {\n const sourceFolder = path.join(expansionPackDir, folder);\n \n // Check if folder exists in expansion pack\n if (await fileManager.pathExists(sourceFolder)) {\n // Get all files in this folder\n const files = await resourceLocator.findFiles('**/*', {\n cwd: sourceFolder,\n nodir: true\n });\n\n // Copy each file to the expansion pack's dot folder with {root} replacement\n for (const file of files) {\n const sourcePath = path.join(sourceFolder, file);\n const destPath = path.join(expansionDotFolder, folder, file);\n \n const needsRootReplacement = file.endsWith('.md') || file.endsWith('.yaml') || file.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, `.${packId}`);\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n \n if (success) {\n installedFiles.push(path.join(`.${packId}`, folder, file));\n }\n }\n }\n }\n\n // Copy config.yaml with {root} replacement\n const configPath = path.join(expansionPackDir, 'config.yaml');\n if (await fileManager.pathExists(configPath)) {\n const configDestPath = path.join(expansionDotFolder, 'config.yaml');\n if (await fileManager.copyFileWithRootReplacement(configPath, configDestPath, `.${packId}`)) {\n installedFiles.push(path.join(`.${packId}`, 'config.yaml'));\n }\n }\n \n // Copy README if it exists with {root} replacement\n const readmePath = path.join(expansionPackDir, 'README.md');\n if (await fileManager.pathExists(readmePath)) {\n const readmeDestPath = path.join(expansionDotFolder, 'README.md');\n if (await fileManager.copyFileWithRootReplacement(readmePath, readmeDestPath, `.${packId}`)) {\n installedFiles.push(path.join(`.${packId}`, 'README.md'));\n }\n }\n\n // Copy common/ items to expansion pack folder\n spinner.text = `Copying common utilities to ${packId}...`;\n await this.copyCommonItems(installDir, `.${packId}`, spinner);\n \n // Check and resolve core dependencies\n await this.resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner);\n \n // Check and resolve core agents referenced by teams\n await this.resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner);\n\n // Create manifest for this expansion pack\n spinner.text = `Creating manifest for ${packId}...`;\n const expansionConfig = {\n installType: 'expansion-pack',\n expansionPackId: packId,\n expansionPackName: pack.name,\n expansionPackVersion: pack.version,\n ides: config.ides || [] // Use ides_setup instead of ide_setup\n };\n \n // Get all files installed in this expansion pack\n const foundFiles = await resourceLocator.findFiles('**/*', {\n cwd: expansionDotFolder,\n nodir: true\n });\n const expansionPackFiles = foundFiles.map(f => path.join(`.${packId}`, f));\n \n await fileManager.createExpansionPackManifest(installDir, packId, expansionConfig, expansionPackFiles);\n\n console.log(chalk.green(`āœ“ Installed expansion pack: ${pack.name} to ${`.${packId}`}`));\n } catch (error) {\n console.error(`Failed to install expansion pack ${packId}: ${error.message}`);\n console.error(`Stack trace: ${error.stack}`);\n }\n }\n\n return installedFiles;\n }\n\n async resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner) {\n const yaml = require('js-yaml');\n const fs = require('fs').promises;\n \n // Find all agent files in the expansion pack\n const agentFiles = await resourceLocator.findFiles('agents/*.md', {\n cwd: expansionDotFolder\n });\n\n for (const agentFile of agentFiles) {\n const agentPath = path.join(expansionDotFolder, agentFile);\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML frontmatter to check dependencies\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n try {\n const agentConfig = yaml.load(yamlContent);\n const dependencies = agentConfig.dependencies || {};\n \n // Check for core dependencies (those that don't exist in the expansion pack)\n for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {\n const deps = dependencies[depType] || [];\n \n for (const dep of deps) {\n const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep : \n (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);\n const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);\n \n // Check if dependency exists in expansion pack dot folder\n if (!(await fileManager.pathExists(expansionDepPath))) {\n // Try to find it in expansion pack source\n const sourceDepPath = path.join(pack.path, depType, depFileName);\n \n if (await fileManager.pathExists(sourceDepPath)) {\n // Copy from expansion pack source\n spinner.text = `Copying ${packId} dependency ${dep}...`;\n const destPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(sourceDepPath, destPath, `.${packId}`);\n console.log(chalk.dim(` Added ${packId} dependency: ${depType}/${depFileName}`));\n } else {\n // Try to find it in core\n const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);\n \n if (await fileManager.pathExists(coreDepPath)) {\n spinner.text = `Copying core dependency ${dep} for ${packId}...`;\n \n // Copy from core to expansion pack dot folder with {root} replacement\n const destPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(coreDepPath, destPath, `.${packId}`);\n \n console.log(chalk.dim(` Added core dependency: ${depType}/${depFileName}`));\n } else {\n console.warn(chalk.yellow(` Warning: Dependency ${depType}/${dep} not found in core or expansion pack`));\n }\n }\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse agent dependencies: ${error.message}`);\n }\n }\n }\n }\n\n async resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner) {\n const yaml = require('js-yaml');\n const fs = require('fs').promises;\n \n // Find all team files in the expansion pack\n const teamFiles = await resourceLocator.findFiles('agent-teams/*.yaml', {\n cwd: expansionDotFolder\n });\n\n // Also get existing agents in the expansion pack\n const existingAgents = new Set();\n const agentFiles = await resourceLocator.findFiles('agents/*.md', {\n cwd: expansionDotFolder\n });\n for (const agentFile of agentFiles) {\n const agentName = path.basename(agentFile, '.md');\n existingAgents.add(agentName);\n }\n\n // Process each team file\n for (const teamFile of teamFiles) {\n const teamPath = path.join(expansionDotFolder, teamFile);\n const teamContent = await fs.readFile(teamPath, 'utf8');\n \n try {\n const teamConfig = yaml.load(teamContent);\n const agents = teamConfig.agents || [];\n \n // Add bmad-orchestrator if not present (required for all teams)\n if (!agents.includes('bmad-orchestrator')) {\n agents.unshift('bmad-orchestrator');\n }\n \n // Check each agent in the team\n for (const agentId of agents) {\n if (!existingAgents.has(agentId)) {\n // Agent not in expansion pack, try to get from core\n const coreAgentPath = path.join(resourceLocator.getBmadCorePath(), 'agents', `${agentId}.md`);\n \n if (await fileManager.pathExists(coreAgentPath)) {\n spinner.text = `Copying core agent ${agentId} for ${packId}...`;\n \n // Copy agent file with {root} replacement\n const destPath = path.join(expansionDotFolder, 'agents', `${agentId}.md`);\n await fileManager.copyFileWithRootReplacement(coreAgentPath, destPath, `.${packId}`);\n existingAgents.add(agentId);\n \n console.log(chalk.dim(` Added core agent: ${agentId}`));\n \n // Now resolve this agent's dependencies too\n const agentContent = await fs.readFile(coreAgentPath, 'utf8');\n const yamlContent = extractYamlFromAgent(agentContent, true);\n \n if (yamlContent) {\n try {\n \n const agentConfig = yaml.load(yamlContent);\n const dependencies = agentConfig.dependencies || {};\n \n // Copy all dependencies for this agent\n for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {\n const deps = dependencies[depType] || [];\n \n for (const dep of deps) {\n const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep : \n (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);\n const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);\n \n // Check if dependency exists in expansion pack\n if (!(await fileManager.pathExists(expansionDepPath))) {\n // Try to find it in core\n const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);\n \n if (await fileManager.pathExists(coreDepPath)) {\n const destDepPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(coreDepPath, destDepPath, `.${packId}`);\n console.log(chalk.dim(` Added agent dependency: ${depType}/${depFileName}`));\n } else {\n // Try common folder\n const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root\n const commonDepPath = path.join(sourceBase, 'common', depType, depFileName);\n if (await fileManager.pathExists(commonDepPath)) {\n const destDepPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFile(commonDepPath, destDepPath);\n console.log(chalk.dim(` Added agent dependency from common: ${depType}/${depFileName}`));\n }\n }\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse agent ${agentId} dependencies: ${error.message}`);\n }\n }\n } else {\n console.warn(chalk.yellow(` Warning: Core agent ${agentId} not found for team ${path.basename(teamFile, '.yaml')}`));\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse team file ${teamFile}: ${error.message}`);\n }\n }\n }\n\n getWebBundleInfo(config) {\n const webBundleType = config.webBundleType || 'all';\n \n switch (webBundleType) {\n case 'all':\n return 'all bundles';\n case 'agents':\n return 'individual agents only';\n case 'teams':\n return config.selectedWebBundleTeams ? \n `teams: ${config.selectedWebBundleTeams.join(', ')}` : \n 'selected teams';\n case 'custom':\n const parts = [];\n if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {\n parts.push(`teams: ${config.selectedWebBundleTeams.join(', ')}`);\n }\n if (config.includeIndividualAgents) {\n parts.push('individual agents');\n }\n return parts.length > 0 ? parts.join(' + ') : 'custom selection';\n default:\n return 'selected bundles';\n }\n }\n\n async installWebBundles(webBundlesDirectory, config, spinner) {\n \n try {\n // Find the dist directory in the BMad installation\n const distDir = configLoader.getDistPath();\n \n if (!(await fileManager.pathExists(distDir))) {\n console.warn('Web bundles not found. Run \"npm run build\" to generate them.');\n return;\n }\n\n // Ensure web bundles directory exists\n await fileManager.ensureDirectory(webBundlesDirectory);\n \n const webBundleType = config.webBundleType || 'all';\n \n if (webBundleType === 'all') {\n // Copy the entire dist directory structure\n await fileManager.copyDirectory(distDir, webBundlesDirectory);\n console.log(chalk.green(`āœ“ Installed all web bundles to: ${webBundlesDirectory}`));\n } else {\n let copiedCount = 0;\n \n // Copy specific selections based on type\n if (webBundleType === 'agents' || (webBundleType === 'custom' && config.includeIndividualAgents)) {\n const agentsSource = path.join(distDir, 'agents');\n const agentsTarget = path.join(webBundlesDirectory, 'agents');\n if (await fileManager.pathExists(agentsSource)) {\n await fileManager.copyDirectory(agentsSource, agentsTarget);\n console.log(chalk.green(`āœ“ Copied individual agent bundles`));\n copiedCount += 10; // Approximate count for agents\n }\n }\n \n if (webBundleType === 'teams' || webBundleType === 'custom') {\n if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {\n const teamsSource = path.join(distDir, 'teams');\n const teamsTarget = path.join(webBundlesDirectory, 'teams');\n await fileManager.ensureDirectory(teamsTarget);\n \n for (const teamId of config.selectedWebBundleTeams) {\n const teamFile = `${teamId}.txt`;\n const sourcePath = path.join(teamsSource, teamFile);\n const targetPath = path.join(teamsTarget, teamFile);\n \n if (await fileManager.pathExists(sourcePath)) {\n await fileManager.copyFile(sourcePath, targetPath);\n copiedCount++;\n console.log(chalk.green(`āœ“ Copied team bundle: ${teamId}`));\n }\n }\n }\n }\n \n // Always copy expansion packs if they exist\n const expansionSource = path.join(distDir, 'expansion-packs');\n const expansionTarget = path.join(webBundlesDirectory, 'expansion-packs');\n if (await fileManager.pathExists(expansionSource)) {\n await fileManager.copyDirectory(expansionSource, expansionTarget);\n console.log(chalk.green(`āœ“ Copied expansion pack bundles`));\n }\n \n console.log(chalk.green(`āœ“ Installed ${copiedCount} selected web bundles to: ${webBundlesDirectory}`));\n }\n } catch (error) {\n console.error(`Failed to install web bundles: ${error.message}`);\n }\n }\n\n async copyCommonItems(installDir, targetSubdir, spinner) {\n \n const fs = require('fs').promises;\n const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root\n const commonPath = path.join(sourceBase, 'common');\n const targetPath = path.join(installDir, targetSubdir);\n const copiedFiles = [];\n \n // Check if common/ exists\n if (!(await fileManager.pathExists(commonPath))) {\n console.warn('Warning: common/ folder not found');\n return copiedFiles;\n }\n \n // Copy all items from common/ to target\n const commonItems = await resourceLocator.findFiles('**/*', {\n cwd: commonPath,\n nodir: true\n });\n \n for (const item of commonItems) {\n const sourcePath = path.join(commonPath, item);\n const destPath = path.join(targetPath, item);\n \n // Read the file content\n const content = await fs.readFile(sourcePath, 'utf8');\n \n // Replace {root} with the target subdirectory\n const updatedContent = content.replace(/\\{root\\}/g, targetSubdir);\n \n // Ensure directory exists\n await fileManager.ensureDirectory(path.dirname(destPath));\n \n // Write the updated content\n await fs.writeFile(destPath, updatedContent, 'utf8');\n copiedFiles.push(path.join(targetSubdir, item));\n }\n \n console.log(chalk.dim(` Added ${commonItems.length} common utilities`));\n return copiedFiles;\n }\n\n async detectExpansionPacks(installDir) {\n const expansionPacks = {};\n const glob = require(\"glob\");\n \n // Find all dot folders that might be expansion packs\n const dotFolders = glob.sync(\".*\", {\n cwd: installDir,\n ignore: [\".git\", \".git/**\", \".bmad-core\", \".bmad-core/**\"],\n });\n \n for (const folder of dotFolders) {\n const folderPath = path.join(installDir, folder);\n const stats = await fileManager.pathExists(folderPath);\n \n if (stats) {\n // Check if it has a manifest\n const manifestPath = path.join(folderPath, \"install-manifest.yaml\");\n if (await fileManager.pathExists(manifestPath)) {\n const manifest = await fileManager.readExpansionPackManifest(installDir, folder.substring(1));\n if (manifest) {\n expansionPacks[folder.substring(1)] = {\n path: folderPath,\n manifest: manifest,\n hasManifest: true\n };\n }\n } else {\n // Check if it has a config.yaml (expansion pack without manifest)\n const configPath = path.join(folderPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n expansionPacks[folder.substring(1)] = {\n path: folderPath,\n manifest: null,\n hasManifest: false\n };\n }\n }\n }\n }\n \n return expansionPacks;\n }\n\n async repairExpansionPack(installDir, packId, pack, integrity, spinner) {\n spinner.start(`Repairing ${pack.name}...`);\n \n try {\n const expansionDotFolder = path.join(installDir, `.${packId}`);\n \n // Back up modified files\n if (integrity.modified.length > 0) {\n spinner.text = \"Backing up modified files...\";\n for (const file of integrity.modified) {\n const filePath = path.join(installDir, file);\n if (await fileManager.pathExists(filePath)) {\n const backupPath = await fileManager.backupFile(filePath);\n console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));\n }\n }\n }\n \n // Restore missing and modified files\n spinner.text = \"Restoring files...\";\n const filesToRestore = [...integrity.missing, ...integrity.modified];\n \n for (const file of filesToRestore) {\n // Skip the manifest file itself\n if (file.endsWith('install-manifest.yaml')) continue;\n \n const relativePath = file.replace(`.${packId}/`, '');\n const sourcePath = path.join(pack.path, relativePath);\n const destPath = path.join(installDir, file);\n \n // Check if this is a common/ file that needs special processing\n const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));\n const commonSourcePath = path.join(commonBase, 'common', relativePath);\n \n if (await fileManager.pathExists(commonSourcePath)) {\n // This is a common/ file - needs template processing\n const fs = require('fs').promises;\n const content = await fs.readFile(commonSourcePath, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, `.${packId}`);\n await fileManager.ensureDirectory(path.dirname(destPath));\n await fs.writeFile(destPath, updatedContent, 'utf8');\n spinner.text = `Restored: ${file}`;\n } else if (await fileManager.pathExists(sourcePath)) {\n // Regular file from expansion pack\n await fileManager.copyFile(sourcePath, destPath);\n spinner.text = `Restored: ${file}`;\n } else {\n console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));\n }\n }\n \n spinner.succeed(`${pack.name} repaired successfully!`);\n \n // Show summary\n console.log(chalk.green(`\\nāœ“ ${pack.name} repaired!`));\n if (integrity.missing.length > 0) {\n console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));\n }\n if (integrity.modified.length > 0) {\n console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));\n }\n \n } catch (error) {\n if (spinner) spinner.fail(`Failed to repair ${pack.name}`);\n console.error(`Error: ${error.message}`);\n }\n }\n\n compareVersions(v1, v2) {\n // Simple semver comparison\n const parts1 = v1.split('.').map(Number);\n const parts2 = v2.split('.').map(Number);\n \n for (let i = 0; i < 3; i++) {\n const part1 = parts1[i] || 0;\n const part2 = parts2[i] || 0;\n \n if (part1 > part2) return 1;\n if (part1 < part2) return -1;\n }\n \n return 0;\n }\n\n async cleanupLegacyYmlFiles(installDir, spinner) {\n const glob = require('glob');\n const fs = require('fs').promises;\n \n try {\n // Find all .yml files in the installation directory\n const ymlFiles = glob.sync('**/*.yml', {\n cwd: installDir,\n ignore: ['**/node_modules/**', '**/.git/**']\n });\n \n let deletedCount = 0;\n \n for (const ymlFile of ymlFiles) {\n // Check if corresponding .yaml file exists\n const yamlFile = ymlFile.replace(/\\.yml$/, '.yaml');\n const ymlPath = path.join(installDir, ymlFile);\n const yamlPath = path.join(installDir, yamlFile);\n \n if (await fileManager.pathExists(yamlPath)) {\n // .yaml counterpart exists, delete the .yml file\n await fs.unlink(ymlPath);\n deletedCount++;\n console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${yamlFile})`));\n }\n }\n \n if (deletedCount > 0) {\n console.log(chalk.green(`āœ“ Cleaned up ${deletedCount} legacy .yml files`));\n }\n \n } catch (error) {\n console.warn(`Warning: Could not cleanup legacy .yml files: ${error.message}`);\n }\n }\n\n async findInstallation() {\n // Look for .bmad-core in current directory or parent directories\n let currentDir = process.cwd();\n\n while (currentDir !== path.dirname(currentDir)) {\n const bmadDir = path.join(currentDir, \".bmad-core\");\n const manifestPath = path.join(bmadDir, \"install-manifest.yaml\");\n\n if (await fileManager.pathExists(manifestPath)) {\n return bmadDir;\n }\n\n currentDir = path.dirname(currentDir);\n }\n\n // Also check if we're inside a .bmad-core directory\n if (path.basename(process.cwd()) === \".bmad-core\") {\n const manifestPath = path.join(process.cwd(), \"install-manifest.yaml\");\n if (await fileManager.pathExists(manifestPath)) {\n return process.cwd();\n }\n }\n\n return null;\n }\n}\n\nmodule.exports = new Installer();\n"], ["/BMAD-METHOD/tools/builders/web-builder.js", "const fs = require(\"node:fs\").promises;\nconst path = require(\"node:path\");\nconst DependencyResolver = require(\"../lib/dependency-resolver\");\nconst yamlUtils = require(\"../lib/yaml-utils\");\n\nclass WebBuilder {\n constructor(options = {}) {\n this.rootDir = options.rootDir || process.cwd();\n this.outputDirs = options.outputDirs || [path.join(this.rootDir, \"dist\")];\n this.resolver = new DependencyResolver(this.rootDir);\n this.templatePath = path.join(\n this.rootDir,\n \"tools\",\n \"md-assets\",\n \"web-agent-startup-instructions.md\"\n );\n }\n\n parseYaml(content) {\n const yaml = require(\"js-yaml\");\n return yaml.load(content);\n }\n\n convertToWebPath(filePath, bundleRoot = 'bmad-core') {\n // Convert absolute paths to web bundle paths with dot prefix\n // All resources get installed under the bundle root, so use that path\n const relativePath = path.relative(this.rootDir, filePath);\n const pathParts = relativePath.split(path.sep);\n \n let resourcePath;\n if (pathParts[0] === 'expansion-packs') {\n // For expansion packs, remove 'expansion-packs/packname' and use the rest\n resourcePath = pathParts.slice(2).join('/');\n } else {\n // For bmad-core, common, etc., remove the first part\n resourcePath = pathParts.slice(1).join('/');\n }\n \n return `.${bundleRoot}/${resourcePath}`;\n }\n\n generateWebInstructions(bundleType, packName = null) {\n // Generate dynamic web instructions based on bundle type\n const rootExample = packName ? `.${packName}` : '.bmad-core';\n const examplePath = packName ? `.${packName}/folder/filename.md` : '.bmad-core/folder/filename.md';\n const personasExample = packName ? `.${packName}/personas/analyst.md` : '.bmad-core/personas/analyst.md';\n const tasksExample = packName ? `.${packName}/tasks/create-story.md` : '.bmad-core/tasks/create-story.md';\n const utilsExample = packName ? `.${packName}/utils/template-format.md` : '.bmad-core/utils/template-format.md';\n const tasksRef = packName ? `.${packName}/tasks/create-story.md` : '.bmad-core/tasks/create-story.md';\n\n return `# Web Agent Bundle Instructions\n\nYou are now operating as a specialized AI agent from the BMad-Method framework. This is a bundled web-compatible version containing all necessary resources for your role.\n\n## Important Instructions\n\n1. **Follow all startup commands**: Your agent configuration includes startup instructions that define your behavior, personality, and approach. These MUST be followed exactly.\n\n2. **Resource Navigation**: This bundle contains all resources you need. Resources are marked with tags like:\n\n- \\`==================== START: ${examplePath} ====================\\`\n- \\`==================== END: ${examplePath} ====================\\`\n\nWhen you need to reference a resource mentioned in your instructions:\n\n- Look for the corresponding START/END tags\n- The format is always the full path with dot prefix (e.g., \\`${personasExample}\\`, \\`${tasksExample}\\`)\n- If a section is specified (e.g., \\`{root}/tasks/create-story.md#section-name\\`), navigate to that section within the file\n\n**Understanding YAML References**: In the agent configuration, resources are referenced in the dependencies section. For example:\n\n\\`\\`\\`yaml\ndependencies:\n utils:\n - template-format\n tasks:\n - create-story\n\\`\\`\\`\n\nThese references map directly to bundle sections:\n\n- \\`utils: template-format\\` → Look for \\`==================== START: ${utilsExample} ====================\\`\n- \\`tasks: create-story\\` → Look for \\`==================== START: ${tasksRef} ====================\\`\n\n3. **Execution Context**: You are operating in a web environment. All your capabilities and knowledge are contained within this bundle. Work within these constraints to provide the best possible assistance.\n\n4. **Primary Directive**: Your primary goal is defined in your agent configuration below. Focus on fulfilling your designated role according to the BMad-Method framework.\n\n---\n\n`;\n }\n\n async cleanOutputDirs() {\n for (const dir of this.outputDirs) {\n try {\n await fs.rm(dir, { recursive: true, force: true });\n console.log(`Cleaned: ${path.relative(this.rootDir, dir)}`);\n } catch (error) {\n console.debug(`Failed to clean directory ${dir}:`, error.message);\n // Directory might not exist, that's fine\n }\n }\n }\n\n async buildAgents() {\n const agents = await this.resolver.listAgents();\n\n for (const agentId of agents) {\n console.log(` Building agent: ${agentId}`);\n const bundle = await this.buildAgentBundle(agentId);\n\n // Write to all output directories\n for (const outputDir of this.outputDirs) {\n const outputPath = path.join(outputDir, \"agents\");\n await fs.mkdir(outputPath, { recursive: true });\n const outputFile = path.join(outputPath, `${agentId}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n\n console.log(`Built ${agents.length} agent bundles in ${this.outputDirs.length} locations`);\n }\n\n async buildTeams() {\n const teams = await this.resolver.listTeams();\n\n for (const teamId of teams) {\n console.log(` Building team: ${teamId}`);\n const bundle = await this.buildTeamBundle(teamId);\n\n // Write to all output directories\n for (const outputDir of this.outputDirs) {\n const outputPath = path.join(outputDir, \"teams\");\n await fs.mkdir(outputPath, { recursive: true });\n const outputFile = path.join(outputPath, `${teamId}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n\n console.log(`Built ${teams.length} team bundles in ${this.outputDirs.length} locations`);\n }\n\n async buildAgentBundle(agentId) {\n const dependencies = await this.resolver.resolveAgentDependencies(agentId);\n const template = this.generateWebInstructions('agent');\n\n const sections = [template];\n\n // Add agent configuration\n const agentPath = this.convertToWebPath(dependencies.agent.path, 'bmad-core');\n sections.push(this.formatSection(agentPath, dependencies.agent.content, 'bmad-core'));\n\n // Add all dependencies\n for (const resource of dependencies.resources) {\n const resourcePath = this.convertToWebPath(resource.path, 'bmad-core');\n sections.push(this.formatSection(resourcePath, resource.content, 'bmad-core'));\n }\n\n return sections.join(\"\\n\");\n }\n\n async buildTeamBundle(teamId) {\n const dependencies = await this.resolver.resolveTeamDependencies(teamId);\n const template = this.generateWebInstructions('team');\n\n const sections = [template];\n\n // Add team configuration\n const teamPath = this.convertToWebPath(dependencies.team.path, 'bmad-core');\n sections.push(this.formatSection(teamPath, dependencies.team.content, 'bmad-core'));\n\n // Add all agents\n for (const agent of dependencies.agents) {\n const agentPath = this.convertToWebPath(agent.path, 'bmad-core');\n sections.push(this.formatSection(agentPath, agent.content, 'bmad-core'));\n }\n\n // Add all deduplicated resources\n for (const resource of dependencies.resources) {\n const resourcePath = this.convertToWebPath(resource.path, 'bmad-core');\n sections.push(this.formatSection(resourcePath, resource.content, 'bmad-core'));\n }\n\n return sections.join(\"\\n\");\n }\n\n processAgentContent(content) {\n // First, replace content before YAML with the template\n const yamlContent = yamlUtils.extractYamlFromAgent(content);\n if (!yamlContent) return content;\n\n const yamlMatch = content.match(/```ya?ml\\n([\\s\\S]*?)\\n```/);\n if (!yamlMatch) return content;\n \n const yamlStartIndex = content.indexOf(yamlMatch[0]);\n const yamlEndIndex = yamlStartIndex + yamlMatch[0].length;\n\n // Parse YAML and remove root and IDE-FILE-RESOLUTION properties\n try {\n const yaml = require(\"js-yaml\");\n const parsed = yaml.load(yamlContent);\n\n // Remove the properties if they exist at root level\n delete parsed.root;\n delete parsed[\"IDE-FILE-RESOLUTION\"];\n delete parsed[\"REQUEST-RESOLUTION\"];\n\n // Also remove from activation-instructions if they exist\n if (parsed[\"activation-instructions\"] && Array.isArray(parsed[\"activation-instructions\"])) {\n parsed[\"activation-instructions\"] = parsed[\"activation-instructions\"].filter(\n (instruction) => {\n return (\n typeof instruction === 'string' &&\n !instruction.startsWith(\"IDE-FILE-RESOLUTION:\") &&\n !instruction.startsWith(\"REQUEST-RESOLUTION:\")\n );\n }\n );\n }\n\n // Reconstruct the YAML\n const cleanedYaml = yaml.dump(parsed, { lineWidth: -1 });\n\n // Get the agent name from the YAML for the header\n const agentName = parsed.agent?.id || \"agent\";\n\n // Build the new content with just the agent header and YAML\n const newHeader = `# ${agentName}\\n\\nCRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n`;\n const afterYaml = content.substring(yamlEndIndex);\n\n return newHeader + \"```yaml\\n\" + cleanedYaml.trim() + \"\\n```\" + afterYaml;\n } catch (error) {\n console.warn(\"Failed to process agent YAML:\", error.message);\n // If parsing fails, return original content\n return content;\n }\n }\n\n formatSection(path, content, bundleRoot = 'bmad-core') {\n const separator = \"====================\";\n\n // Process agent content if this is an agent file\n if (path.includes(\"/agents/\")) {\n content = this.processAgentContent(content);\n }\n\n // Replace {root} references with the actual bundle root\n content = this.replaceRootReferences(content, bundleRoot);\n\n return [\n `${separator} START: ${path} ${separator}`,\n content.trim(),\n `${separator} END: ${path} ${separator}`,\n \"\",\n ].join(\"\\n\");\n }\n\n replaceRootReferences(content, bundleRoot) {\n // Replace {root} with the appropriate bundle root path\n return content.replace(/\\{root\\}/g, `.${bundleRoot}`);\n }\n\n async validate() {\n console.log(\"Validating agent configurations...\");\n const agents = await this.resolver.listAgents();\n for (const agentId of agents) {\n try {\n await this.resolver.resolveAgentDependencies(agentId);\n console.log(` āœ“ ${agentId}`);\n } catch (error) {\n console.log(` āœ— ${agentId}: ${error.message}`);\n throw error;\n }\n }\n\n console.log(\"\\nValidating team configurations...\");\n const teams = await this.resolver.listTeams();\n for (const teamId of teams) {\n try {\n await this.resolver.resolveTeamDependencies(teamId);\n console.log(` āœ“ ${teamId}`);\n } catch (error) {\n console.log(` āœ— ${teamId}: ${error.message}`);\n throw error;\n }\n }\n }\n\n async buildAllExpansionPacks(options = {}) {\n const expansionPacks = await this.listExpansionPacks();\n\n for (const packName of expansionPacks) {\n console.log(` Building expansion pack: ${packName}`);\n await this.buildExpansionPack(packName, options);\n }\n\n console.log(`Built ${expansionPacks.length} expansion pack bundles`);\n }\n\n async buildExpansionPack(packName, options = {}) {\n const packDir = path.join(this.rootDir, \"expansion-packs\", packName);\n const outputDirs = [path.join(this.rootDir, \"dist\", \"expansion-packs\", packName)];\n\n // Clean output directories if requested\n if (options.clean !== false) {\n for (const outputDir of outputDirs) {\n try {\n await fs.rm(outputDir, { recursive: true, force: true });\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n }\n\n // Build individual agents first\n const agentsDir = path.join(packDir, \"agents\");\n try {\n const agentFiles = await fs.readdir(agentsDir);\n const agentMarkdownFiles = agentFiles.filter((f) => f.endsWith(\".md\"));\n\n if (agentMarkdownFiles.length > 0) {\n console.log(` Building individual agents for ${packName}:`);\n\n for (const agentFile of agentMarkdownFiles) {\n const agentName = agentFile.replace(\".md\", \"\");\n console.log(` - ${agentName}`);\n\n // Build individual agent bundle\n const bundle = await this.buildExpansionAgentBundle(packName, packDir, agentName);\n\n // Write to all output directories\n for (const outputDir of outputDirs) {\n const agentsOutputDir = path.join(outputDir, \"agents\");\n await fs.mkdir(agentsOutputDir, { recursive: true });\n const outputFile = path.join(agentsOutputDir, `${agentName}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n }\n } catch (error) {\n console.debug(` No agents directory found for ${packName}`);\n }\n\n // Build team bundle\n const agentTeamsDir = path.join(packDir, \"agent-teams\");\n try {\n const teamFiles = await fs.readdir(agentTeamsDir);\n const teamFile = teamFiles.find((f) => f.endsWith(\".yaml\"));\n\n if (teamFile) {\n console.log(` Building team bundle for ${packName}`);\n const teamConfigPath = path.join(agentTeamsDir, teamFile);\n\n // Build expansion pack as a team bundle\n const bundle = await this.buildExpansionTeamBundle(packName, packDir, teamConfigPath);\n\n // Write to all output directories\n for (const outputDir of outputDirs) {\n const teamsOutputDir = path.join(outputDir, \"teams\");\n await fs.mkdir(teamsOutputDir, { recursive: true });\n const outputFile = path.join(teamsOutputDir, teamFile.replace(\".yaml\", \".txt\"));\n await fs.writeFile(outputFile, bundle, \"utf8\");\n console.log(` āœ“ Created bundle: ${path.relative(this.rootDir, outputFile)}`);\n }\n } else {\n console.warn(` ⚠ No team configuration found in ${packName}/agent-teams/`);\n }\n } catch (error) {\n console.warn(` ⚠ No agent-teams directory found for ${packName}`);\n }\n }\n\n async buildExpansionAgentBundle(packName, packDir, agentName) {\n const template = this.generateWebInstructions('expansion-agent', packName);\n const sections = [template];\n\n // Add agent configuration\n const agentPath = path.join(packDir, \"agents\", `${agentName}.md`);\n const agentContent = await fs.readFile(agentPath, \"utf8\");\n const agentWebPath = this.convertToWebPath(agentPath, packName);\n sections.push(this.formatSection(agentWebPath, agentContent, packName));\n\n // Resolve and add agent dependencies\n const yamlContent = yamlUtils.extractYamlFromAgent(agentContent);\n if (yamlContent) {\n try {\n const yaml = require(\"js-yaml\");\n const agentConfig = yaml.load(yamlContent);\n\n if (agentConfig.dependencies) {\n // Add resources, first try expansion pack, then core\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n let found = false;\n\n // Try expansion pack first\n const resourcePath = path.join(packDir, resourceType, resourceName);\n try {\n const resourceContent = await fs.readFile(resourcePath, \"utf8\");\n const resourceWebPath = this.convertToWebPath(resourcePath, packName);\n sections.push(\n this.formatSection(resourceWebPath, resourceContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in expansion pack, continue\n }\n\n // If not found in expansion pack, try core\n if (!found) {\n const corePath = path.join(\n this.rootDir,\n \"bmad-core\",\n resourceType,\n resourceName\n );\n try {\n const coreContent = await fs.readFile(corePath, \"utf8\");\n const coreWebPath = this.convertToWebPath(corePath, packName);\n sections.push(\n this.formatSection(coreWebPath, coreContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in core either, continue\n }\n }\n\n // If not found in core, try common folder\n if (!found) {\n const commonPath = path.join(\n this.rootDir,\n \"common\",\n resourceType,\n resourceName\n );\n try {\n const commonContent = await fs.readFile(commonPath, \"utf8\");\n const commonWebPath = this.convertToWebPath(commonPath, packName);\n sections.push(\n this.formatSection(commonWebPath, commonContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in common either, continue\n }\n }\n\n if (!found) {\n console.warn(\n ` ⚠ Dependency ${resourceType}#${resourceName} not found in expansion pack or core`\n );\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentName}:`, error.message);\n }\n }\n\n return sections.join(\"\\n\");\n }\n\n async buildExpansionTeamBundle(packName, packDir, teamConfigPath) {\n const template = this.generateWebInstructions('expansion-team', packName);\n\n const sections = [template];\n\n // Add team configuration and parse to get agent list\n const teamContent = await fs.readFile(teamConfigPath, \"utf8\");\n const teamFileName = path.basename(teamConfigPath, \".yaml\");\n const teamConfig = this.parseYaml(teamContent);\n const teamWebPath = this.convertToWebPath(teamConfigPath, packName);\n sections.push(this.formatSection(teamWebPath, teamContent, packName));\n\n // Get list of expansion pack agents\n const expansionAgents = new Set();\n const agentsDir = path.join(packDir, \"agents\");\n try {\n const agentFiles = await fs.readdir(agentsDir);\n for (const agentFile of agentFiles.filter((f) => f.endsWith(\".md\"))) {\n const agentName = agentFile.replace(\".md\", \"\");\n expansionAgents.add(agentName);\n }\n } catch (error) {\n console.warn(` ⚠ No agents directory found in ${packName}`);\n }\n\n // Build a map of all available expansion pack resources for override checking\n const expansionResources = new Map();\n const resourceDirs = [\"templates\", \"tasks\", \"checklists\", \"workflows\", \"data\"];\n for (const resourceDir of resourceDirs) {\n const resourcePath = path.join(packDir, resourceDir);\n try {\n const resourceFiles = await fs.readdir(resourcePath);\n for (const resourceFile of resourceFiles.filter(\n (f) => f.endsWith(\".md\") || f.endsWith(\".yaml\")\n )) {\n expansionResources.set(`${resourceDir}#${resourceFile}`, true);\n }\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n\n // Process all agents listed in team configuration\n const agentsToProcess = teamConfig.agents || [];\n\n // Ensure bmad-orchestrator is always included for teams\n if (!agentsToProcess.includes(\"bmad-orchestrator\")) {\n console.warn(` ⚠ Team ${teamFileName} missing bmad-orchestrator, adding automatically`);\n agentsToProcess.unshift(\"bmad-orchestrator\");\n }\n\n // Track all dependencies from all agents (deduplicated)\n const allDependencies = new Map();\n\n for (const agentId of agentsToProcess) {\n if (expansionAgents.has(agentId)) {\n // Use expansion pack version (override)\n const agentPath = path.join(agentsDir, `${agentId}.md`);\n const agentContent = await fs.readFile(agentPath, \"utf8\");\n const expansionAgentWebPath = this.convertToWebPath(agentPath, packName);\n sections.push(this.formatSection(expansionAgentWebPath, agentContent, packName));\n\n // Parse and collect dependencies from expansion agent\n const agentYaml = agentContent.match(/```yaml\\n([\\s\\S]*?)\\n```/);\n if (agentYaml) {\n try {\n const agentConfig = this.parseYaml(agentYaml[1]);\n if (agentConfig.dependencies) {\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n const key = `${resourceType}#${resourceName}`;\n if (!allDependencies.has(key)) {\n allDependencies.set(key, { type: resourceType, name: resourceName });\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentId}:`, error.message);\n }\n }\n } else {\n // Use core BMad version\n try {\n const coreAgentPath = path.join(this.rootDir, \"bmad-core\", \"agents\", `${agentId}.md`);\n const coreAgentContent = await fs.readFile(coreAgentPath, \"utf8\");\n const coreAgentWebPath = this.convertToWebPath(coreAgentPath, packName);\n sections.push(this.formatSection(coreAgentWebPath, coreAgentContent, packName));\n\n // Parse and collect dependencies from core agent\n const yamlContent = yamlUtils.extractYamlFromAgent(coreAgentContent, true);\n if (yamlContent) {\n try {\n const agentConfig = this.parseYaml(yamlContent);\n if (agentConfig.dependencies) {\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n const key = `${resourceType}#${resourceName}`;\n if (!allDependencies.has(key)) {\n allDependencies.set(key, { type: resourceType, name: resourceName });\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentId}:`, error.message);\n }\n }\n } catch (error) {\n console.warn(` ⚠ Agent ${agentId} not found in core or expansion pack`);\n }\n }\n }\n\n // Add all collected dependencies from agents\n // Always prefer expansion pack versions if they exist\n for (const [key, dep] of allDependencies) {\n let found = false;\n\n // Always check expansion pack first, even if the dependency came from a core agent\n if (expansionResources.has(key)) {\n // We know it exists in expansion pack, find and load it\n const expansionPath = path.join(packDir, dep.type, dep.name);\n try {\n const content = await fs.readFile(expansionPath, \"utf8\");\n const expansionWebPath = this.convertToWebPath(expansionPath, packName);\n sections.push(this.formatSection(expansionWebPath, content, packName));\n console.log(` āœ“ Using expansion override for ${key}`);\n found = true;\n } catch (error) {\n // Try next extension\n }\n }\n\n // If not found in expansion pack (or doesn't exist there), try core\n if (!found) {\n const corePath = path.join(this.rootDir, \"bmad-core\", dep.type, dep.name);\n try {\n const content = await fs.readFile(corePath, \"utf8\");\n const coreWebPath = this.convertToWebPath(corePath, packName);\n sections.push(this.formatSection(coreWebPath, content, packName));\n found = true;\n } catch (error) {\n // Not in core either, continue\n }\n }\n\n // If not found in core, try common folder\n if (!found) {\n const commonPath = path.join(this.rootDir, \"common\", dep.type, dep.name);\n try {\n const content = await fs.readFile(commonPath, \"utf8\");\n const commonWebPath = this.convertToWebPath(commonPath, packName);\n sections.push(this.formatSection(commonWebPath, content, packName));\n found = true;\n } catch (error) {\n // Not in common either, continue\n }\n }\n\n if (!found) {\n console.warn(` ⚠ Dependency ${key} not found in expansion pack or core`);\n }\n }\n\n // Add remaining expansion pack resources not already included as dependencies\n for (const resourceDir of resourceDirs) {\n const resourcePath = path.join(packDir, resourceDir);\n try {\n const resourceFiles = await fs.readdir(resourcePath);\n for (const resourceFile of resourceFiles.filter(\n (f) => f.endsWith(\".md\") || f.endsWith(\".yaml\")\n )) {\n const filePath = path.join(resourcePath, resourceFile);\n const fileContent = await fs.readFile(filePath, \"utf8\");\n const fileName = resourceFile.replace(/\\.(md|yaml)$/, \"\");\n\n // Only add if not already included as a dependency\n const resourceKey = `${resourceDir}#${fileName}`;\n if (!allDependencies.has(resourceKey)) {\n const fullResourcePath = path.join(resourcePath, resourceFile);\n const resourceWebPath = this.convertToWebPath(fullResourcePath, packName);\n sections.push(this.formatSection(resourceWebPath, fileContent, packName));\n }\n }\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n\n return sections.join(\"\\n\");\n }\n\n async listExpansionPacks() {\n const expansionPacksDir = path.join(this.rootDir, \"expansion-packs\");\n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);\n } catch (error) {\n console.warn(\"No expansion-packs directory found\");\n return [];\n }\n }\n\n listAgents() {\n return this.resolver.listAgents();\n }\n}\n\nmodule.exports = WebBuilder;\n"], ["/BMAD-METHOD/tools/installer/lib/resource-locator.js", "/**\n * Resource Locator - Centralized file path resolution and caching\n * Reduces duplicate file system operations and memory usage\n */\n\nconst path = require('node:path');\nconst fs = require('fs-extra');\nconst moduleManager = require('./module-manager');\n\nclass ResourceLocator {\n constructor() {\n this._pathCache = new Map();\n this._globCache = new Map();\n this._bmadCorePath = null;\n this._expansionPacksPath = null;\n }\n\n /**\n * Get the base path for bmad-core\n */\n getBmadCorePath() {\n if (!this._bmadCorePath) {\n this._bmadCorePath = path.join(__dirname, '../../../bmad-core');\n }\n return this._bmadCorePath;\n }\n\n /**\n * Get the base path for expansion packs\n */\n getExpansionPacksPath() {\n if (!this._expansionPacksPath) {\n this._expansionPacksPath = path.join(__dirname, '../../../expansion-packs');\n }\n return this._expansionPacksPath;\n }\n\n /**\n * Find all files matching a pattern, with caching\n * @param {string} pattern - Glob pattern\n * @param {Object} options - Glob options\n * @returns {Promise} Array of matched file paths\n */\n async findFiles(pattern, options = {}) {\n const cacheKey = `${pattern}:${JSON.stringify(options)}`;\n \n if (this._globCache.has(cacheKey)) {\n return this._globCache.get(cacheKey);\n }\n\n const { glob } = await moduleManager.getModules(['glob']);\n const files = await glob(pattern, options);\n \n // Cache for 5 minutes\n this._globCache.set(cacheKey, files);\n setTimeout(() => this._globCache.delete(cacheKey), 5 * 60 * 1000);\n \n return files;\n }\n\n /**\n * Get agent path with caching\n * @param {string} agentId - Agent identifier\n * @returns {Promise} Path to agent file or null if not found\n */\n async getAgentPath(agentId) {\n const cacheKey = `agent:${agentId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n // Check in bmad-core\n let agentPath = path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n if (await fs.pathExists(agentPath)) {\n this._pathCache.set(cacheKey, agentPath);\n return agentPath;\n }\n\n // Check in expansion packs\n const expansionPacks = await this.getExpansionPacks();\n for (const pack of expansionPacks) {\n agentPath = path.join(pack.path, 'agents', `${agentId}.md`);\n if (await fs.pathExists(agentPath)) {\n this._pathCache.set(cacheKey, agentPath);\n return agentPath;\n }\n }\n\n return null;\n }\n\n /**\n * Get available agents with metadata\n * @returns {Promise} Array of agent objects\n */\n async getAvailableAgents() {\n const cacheKey = 'all-agents';\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const agents = [];\n const yaml = require('js-yaml');\n const { extractYamlFromAgent } = require('../../lib/yaml-utils');\n\n // Get agents from bmad-core\n const coreAgents = await this.findFiles('agents/*.md', {\n cwd: this.getBmadCorePath()\n });\n\n for (const agentFile of coreAgents) {\n const content = await fs.readFile(\n path.join(this.getBmadCorePath(), agentFile),\n 'utf8'\n );\n const yamlContent = extractYamlFromAgent(content);\n if (yamlContent) {\n try {\n const metadata = yaml.load(yamlContent);\n agents.push({\n id: path.basename(agentFile, '.md'),\n name: metadata.agent_name || path.basename(agentFile, '.md'),\n description: metadata.description || 'No description available',\n source: 'core'\n });\n } catch (e) {\n // Skip invalid agents\n }\n }\n }\n\n // Cache for 10 minutes\n this._pathCache.set(cacheKey, agents);\n setTimeout(() => this._pathCache.delete(cacheKey), 10 * 60 * 1000);\n\n return agents;\n }\n\n /**\n * Get available expansion packs\n * @returns {Promise} Array of expansion pack objects\n */\n async getExpansionPacks() {\n const cacheKey = 'expansion-packs';\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const packs = [];\n const expansionPacksPath = this.getExpansionPacksPath();\n\n if (await fs.pathExists(expansionPacksPath)) {\n const entries = await fs.readdir(expansionPacksPath, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory()) {\n const configPath = path.join(expansionPacksPath, entry.name, 'config.yaml');\n if (await fs.pathExists(configPath)) {\n try {\n const yaml = require('js-yaml');\n const config = yaml.load(await fs.readFile(configPath, 'utf8'));\n packs.push({\n id: entry.name,\n name: config.name || entry.name,\n version: config.version || '1.0.0',\n description: config.description || 'No description available',\n shortTitle: config['short-title'] || config.description || 'No description available',\n author: config.author || 'Unknown',\n path: path.join(expansionPacksPath, entry.name)\n });\n } catch (e) {\n // Skip invalid packs\n }\n }\n }\n }\n }\n\n // Cache for 10 minutes\n this._pathCache.set(cacheKey, packs);\n setTimeout(() => this._pathCache.delete(cacheKey), 10 * 60 * 1000);\n\n return packs;\n }\n\n /**\n * Get team configuration\n * @param {string} teamId - Team identifier\n * @returns {Promise} Team configuration or null\n */\n async getTeamConfig(teamId) {\n const cacheKey = `team:${teamId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const teamPath = path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n \n if (await fs.pathExists(teamPath)) {\n try {\n const yaml = require('js-yaml');\n const content = await fs.readFile(teamPath, 'utf8');\n const config = yaml.load(content);\n this._pathCache.set(cacheKey, config);\n return config;\n } catch (e) {\n return null;\n }\n }\n\n return null;\n }\n\n /**\n * Get resource dependencies for an agent\n * @param {string} agentId - Agent identifier\n * @returns {Promise} Dependencies object\n */\n async getAgentDependencies(agentId) {\n const cacheKey = `deps:${agentId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const agentPath = await this.getAgentPath(agentId);\n if (!agentPath) {\n return { all: [], byType: {} };\n }\n\n const content = await fs.readFile(agentPath, 'utf8');\n const { extractYamlFromAgent } = require('../../lib/yaml-utils');\n const yamlContent = extractYamlFromAgent(content);\n\n if (!yamlContent) {\n return { all: [], byType: {} };\n }\n\n try {\n const yaml = require('js-yaml');\n const metadata = yaml.load(yamlContent);\n const dependencies = metadata.dependencies || {};\n \n // Flatten dependencies\n const allDeps = [];\n const byType = {};\n \n for (const [type, deps] of Object.entries(dependencies)) {\n if (Array.isArray(deps)) {\n byType[type] = deps;\n for (const dep of deps) {\n allDeps.push(`.bmad-core/${type}/${dep}`);\n }\n }\n }\n\n const result = { all: allDeps, byType };\n this._pathCache.set(cacheKey, result);\n return result;\n } catch (e) {\n return { all: [], byType: {} };\n }\n }\n\n /**\n * Clear all caches to free memory\n */\n clearCache() {\n this._pathCache.clear();\n this._globCache.clear();\n }\n\n /**\n * Get IDE configuration\n * @param {string} ideId - IDE identifier\n * @returns {Promise} IDE configuration or null\n */\n async getIdeConfig(ideId) {\n const cacheKey = `ide:${ideId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const idePath = path.join(this.getBmadCorePath(), 'ide-rules', `${ideId}.yaml`);\n \n if (await fs.pathExists(idePath)) {\n try {\n const yaml = require('js-yaml');\n const content = await fs.readFile(idePath, 'utf8');\n const config = yaml.load(content);\n this._pathCache.set(cacheKey, config);\n return config;\n } catch (e) {\n return null;\n }\n }\n\n return null;\n }\n}\n\n// Singleton instance\nconst resourceLocator = new ResourceLocator();\n\nmodule.exports = resourceLocator;"], ["/BMAD-METHOD/tools/installer/lib/file-manager.js", "const fs = require(\"fs-extra\");\nconst path = require(\"path\");\nconst crypto = require(\"crypto\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst { createReadStream, createWriteStream, promises: fsPromises } = require('fs');\nconst { pipeline } = require('stream/promises');\nconst resourceLocator = require('./resource-locator');\n\nclass FileManager {\n constructor() {\n this.manifestDir = \".bmad-core\";\n this.manifestFile = \"install-manifest.yaml\";\n }\n\n async copyFile(source, destination) {\n try {\n await fs.ensureDir(path.dirname(destination));\n \n // Use streaming for large files (> 10MB)\n const stats = await fs.stat(source);\n if (stats.size > 10 * 1024 * 1024) {\n await pipeline(\n createReadStream(source),\n createWriteStream(destination)\n );\n } else {\n await fs.copy(source, destination);\n }\n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy ${source}:`), error.message);\n return false;\n }\n }\n\n async copyDirectory(source, destination) {\n try {\n await fs.ensureDir(destination);\n \n // Use streaming copy for large directories\n const files = await resourceLocator.findFiles('**/*', {\n cwd: source,\n nodir: true\n });\n \n // Process files in batches to avoid memory issues\n const batchSize = 50;\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n await Promise.all(\n batch.map(file => \n this.copyFile(\n path.join(source, file),\n path.join(destination, file)\n )\n )\n );\n }\n return true;\n } catch (error) {\n console.error(\n chalk.red(`Failed to copy directory ${source}:`),\n error.message\n );\n return false;\n }\n }\n\n async copyGlobPattern(pattern, sourceDir, destDir, rootValue = null) {\n const files = await resourceLocator.findFiles(pattern, { cwd: sourceDir });\n const copied = [];\n\n for (const file of files) {\n const sourcePath = path.join(sourceDir, file);\n const destPath = path.join(destDir, file);\n\n // Use root replacement if rootValue is provided and file needs it\n const needsRootReplacement = rootValue && (file.endsWith('.md') || file.endsWith('.yaml') || file.endsWith('.yml'));\n \n let success = false;\n if (needsRootReplacement) {\n success = await this.copyFileWithRootReplacement(sourcePath, destPath, rootValue);\n } else {\n success = await this.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n copied.push(file);\n }\n }\n\n return copied;\n }\n\n async calculateFileHash(filePath) {\n try {\n // Use streaming for hash calculation to reduce memory usage\n const stream = createReadStream(filePath);\n const hash = crypto.createHash(\"sha256\");\n \n for await (const chunk of stream) {\n hash.update(chunk);\n }\n \n return hash.digest(\"hex\").slice(0, 16);\n } catch (error) {\n return null;\n }\n }\n\n async createManifest(installDir, config, files) {\n const manifestPath = path.join(\n installDir,\n this.manifestDir,\n this.manifestFile\n );\n\n // Read version from package.json\n let coreVersion = \"unknown\";\n try {\n const packagePath = path.join(__dirname, '..', '..', '..', 'package.json');\n const packageJson = require(packagePath);\n coreVersion = packageJson.version;\n } catch (error) {\n console.warn(\"Could not read version from package.json, using 'unknown'\");\n }\n\n const manifest = {\n version: coreVersion,\n installed_at: new Date().toISOString(),\n install_type: config.installType,\n agent: config.agent || null,\n ides_setup: config.ides || [],\n expansion_packs: config.expansionPacks || [],\n files: [],\n };\n\n // Add file information\n for (const file of files) {\n const filePath = path.join(installDir, file);\n const hash = await this.calculateFileHash(filePath);\n\n manifest.files.push({\n path: file,\n hash: hash,\n modified: false,\n });\n }\n\n // Write manifest\n await fs.ensureDir(path.dirname(manifestPath));\n await fs.writeFile(manifestPath, yaml.dump(manifest, { indent: 2 }));\n\n return manifest;\n }\n\n async readManifest(installDir) {\n const manifestPath = path.join(\n installDir,\n this.manifestDir,\n this.manifestFile\n );\n\n try {\n const content = await fs.readFile(manifestPath, \"utf8\");\n return yaml.load(content);\n } catch (error) {\n return null;\n }\n }\n\n async readExpansionPackManifest(installDir, packId) {\n const manifestPath = path.join(\n installDir,\n `.${packId}`,\n this.manifestFile\n );\n\n try {\n const content = await fs.readFile(manifestPath, \"utf8\");\n return yaml.load(content);\n } catch (error) {\n return null;\n }\n }\n\n async checkModifiedFiles(installDir, manifest) {\n const modified = [];\n\n for (const file of manifest.files) {\n const filePath = path.join(installDir, file.path);\n const currentHash = await this.calculateFileHash(filePath);\n\n if (currentHash && currentHash !== file.hash) {\n modified.push(file.path);\n }\n }\n\n return modified;\n }\n\n async checkFileIntegrity(installDir, manifest) {\n const result = {\n missing: [],\n modified: []\n };\n\n for (const file of manifest.files) {\n const filePath = path.join(installDir, file.path);\n \n // Skip checking the manifest file itself - it will always be different due to timestamps\n if (file.path.endsWith('install-manifest.yaml')) {\n continue;\n }\n \n if (!(await this.pathExists(filePath))) {\n result.missing.push(file.path);\n } else {\n const currentHash = await this.calculateFileHash(filePath);\n if (currentHash && currentHash !== file.hash) {\n result.modified.push(file.path);\n }\n }\n }\n\n return result;\n }\n\n async backupFile(filePath) {\n const backupPath = filePath + \".bak\";\n let counter = 1;\n let finalBackupPath = backupPath;\n\n // Find a unique backup filename\n while (await fs.pathExists(finalBackupPath)) {\n finalBackupPath = `${filePath}.bak${counter}`;\n counter++;\n }\n\n await fs.copy(filePath, finalBackupPath);\n return finalBackupPath;\n }\n\n async ensureDirectory(dirPath) {\n try {\n await fs.ensureDir(dirPath);\n return true;\n } catch (error) {\n throw error;\n }\n }\n\n async pathExists(filePath) {\n return fs.pathExists(filePath);\n }\n\n async readFile(filePath) {\n return fs.readFile(filePath, \"utf8\");\n }\n\n async writeFile(filePath, content) {\n await fs.ensureDir(path.dirname(filePath));\n await fs.writeFile(filePath, content);\n }\n\n async removeDirectory(dirPath) {\n await fs.remove(dirPath);\n }\n\n async createExpansionPackManifest(installDir, packId, config, files) {\n const manifestPath = path.join(\n installDir,\n `.${packId}`,\n this.manifestFile\n );\n\n const manifest = {\n version: config.expansionPackVersion || require(\"../../../package.json\").version,\n installed_at: new Date().toISOString(),\n install_type: config.installType,\n expansion_pack_id: config.expansionPackId,\n expansion_pack_name: config.expansionPackName,\n ides_setup: config.ides || [],\n files: [],\n };\n\n // Add file information\n for (const file of files) {\n const filePath = path.join(installDir, file);\n const hash = await this.calculateFileHash(filePath);\n\n manifest.files.push({\n path: file,\n hash: hash,\n modified: false,\n });\n }\n\n // Write manifest\n await fs.ensureDir(path.dirname(manifestPath));\n await fs.writeFile(manifestPath, yaml.dump(manifest, { indent: 2 }));\n\n return manifest;\n }\n\n async modifyCoreConfig(installDir, config) {\n const coreConfigPath = path.join(installDir, '.bmad-core', 'core-config.yaml');\n \n try {\n // Read the existing core-config.yaml\n const coreConfigContent = await fs.readFile(coreConfigPath, 'utf8');\n const coreConfig = yaml.load(coreConfigContent);\n \n // Modify sharding settings if provided\n if (config.prdSharded !== undefined) {\n coreConfig.prd.prdSharded = config.prdSharded;\n }\n \n if (config.architectureSharded !== undefined) {\n coreConfig.architecture.architectureSharded = config.architectureSharded;\n }\n \n // Write back the modified config\n await fs.writeFile(coreConfigPath, yaml.dump(coreConfig, { indent: 2 }));\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to modify core-config.yaml:`), error.message);\n return false;\n }\n }\n\n async copyFileWithRootReplacement(source, destination, rootValue) {\n try {\n // Check file size to determine if we should stream\n const stats = await fs.stat(source);\n \n if (stats.size > 5 * 1024 * 1024) { // 5MB threshold\n // Use streaming for large files\n const { Transform } = require('stream');\n const replaceStream = new Transform({\n transform(chunk, encoding, callback) {\n const modified = chunk.toString().replace(/\\{root\\}/g, rootValue);\n callback(null, modified);\n }\n });\n \n await this.ensureDirectory(path.dirname(destination));\n await pipeline(\n createReadStream(source, { encoding: 'utf8' }),\n replaceStream,\n createWriteStream(destination, { encoding: 'utf8' })\n );\n } else {\n // Regular approach for smaller files\n const content = await fsPromises.readFile(source, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, rootValue);\n await this.ensureDirectory(path.dirname(destination));\n await fsPromises.writeFile(destination, updatedContent, 'utf8');\n }\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy ${source} with root replacement:`), error.message);\n return false;\n }\n }\n\n async copyDirectoryWithRootReplacement(source, destination, rootValue, fileExtensions = ['.md', '.yaml', '.yml']) {\n try {\n await this.ensureDirectory(destination);\n \n // Get all files in source directory\n const files = await resourceLocator.findFiles('**/*', { \n cwd: source, \n nodir: true \n });\n \n let replacedCount = 0;\n \n for (const file of files) {\n const sourcePath = path.join(source, file);\n const destPath = path.join(destination, file);\n \n // Check if this file type should have {root} replacement\n const shouldReplace = fileExtensions.some(ext => file.endsWith(ext));\n \n if (shouldReplace) {\n if (await this.copyFileWithRootReplacement(sourcePath, destPath, rootValue)) {\n replacedCount++;\n }\n } else {\n // Regular copy for files that don't need replacement\n await this.copyFile(sourcePath, destPath);\n }\n }\n \n if (replacedCount > 0) {\n console.log(chalk.dim(` Processed ${replacedCount} files with {root} replacement`));\n }\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy directory ${source} with root replacement:`), error.message);\n return false;\n }\n }\n}\n\nmodule.exports = new FileManager();\n"], ["/BMAD-METHOD/tools/upgraders/v3-to-v4-upgrader.js", "const fs = require(\"fs\").promises;\nconst path = require(\"path\");\nconst { glob } = require(\"glob\");\n\n// Dynamic imports for ES modules\nlet chalk, ora, inquirer;\n\n// Initialize ES modules\nasync function initializeModules() {\n chalk = (await import(\"chalk\")).default;\n ora = (await import(\"ora\")).default;\n inquirer = (await import(\"inquirer\")).default;\n}\n\nclass V3ToV4Upgrader {\n constructor() {\n // Constructor remains empty\n }\n\n async upgrade(options = {}) {\n try {\n // Initialize ES modules\n await initializeModules();\n // Keep readline open throughout the process\n process.stdin.resume();\n\n // 1. Welcome message\n console.log(\n chalk.bold(\"\\nWelcome to BMad-Method V3 to V4 Upgrade Tool\\n\")\n );\n console.log(\n \"This tool will help you upgrade your BMad-Method V3 project to V4.\\n\"\n );\n console.log(chalk.cyan(\"What this tool does:\"));\n console.log(\"- Creates a backup of your V3 files (.bmad-v3-backup/)\");\n console.log(\"- Installs the new V4 .bmad-core structure\");\n console.log(\n \"- Preserves your PRD, Architecture, and Stories in the new format\\n\"\n );\n console.log(chalk.yellow(\"What this tool does NOT do:\"));\n console.log(\n \"- Modify your document content (use doc-migration-task after upgrade)\"\n );\n console.log(\"- Touch any files outside bmad-agent/ and docs/\\n\");\n\n // 2. Get project path\n const projectPath = await this.getProjectPath(options.projectPath);\n\n // 3. Validate V3 structure\n const validation = await this.validateV3Project(projectPath);\n if (!validation.isValid) {\n console.error(\n chalk.red(\"\\nError: This doesn't appear to be a V3 project.\")\n );\n console.error(\"Expected to find:\");\n console.error(\"- bmad-agent/ directory\");\n console.error(\"- docs/ directory\\n\");\n console.error(\n \"Please check you're in the correct directory and try again.\"\n );\n return;\n }\n\n // 4. Pre-flight check\n const analysis = await this.analyzeProject(projectPath);\n await this.showPreflightCheck(analysis, options);\n\n if (!options.dryRun) {\n const { confirm } = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirm\",\n message: \"Continue with upgrade?\",\n default: true,\n },\n ]);\n\n if (!confirm) {\n console.log(\"Upgrade cancelled.\");\n return;\n }\n }\n\n // 5. Create backup\n if (options.backup !== false && !options.dryRun) {\n await this.createBackup(projectPath);\n }\n\n // 6. Install V4 structure\n if (!options.dryRun) {\n await this.installV4Structure(projectPath);\n }\n\n // 7. Migrate documents\n if (!options.dryRun) {\n await this.migrateDocuments(projectPath, analysis);\n }\n\n // 8. Setup IDE\n if (!options.dryRun) {\n await this.setupIDE(projectPath, options.ides);\n }\n\n // 9. Show completion report\n this.showCompletionReport(projectPath, analysis);\n\n process.exit(0);\n } catch (error) {\n console.error(chalk.red(\"\\nUpgrade error:\"), error.message);\n process.exit(1);\n }\n }\n\n async getProjectPath(providedPath) {\n if (providedPath) {\n return path.resolve(providedPath);\n }\n\n const { projectPath } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"projectPath\",\n message: \"Please enter the path to your V3 project:\",\n default: process.cwd(),\n },\n ]);\n\n return path.resolve(projectPath);\n }\n\n async validateV3Project(projectPath) {\n const spinner = ora(\"Validating project structure...\").start();\n\n try {\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n const docsPath = path.join(projectPath, \"docs\");\n\n const hasBmadAgent = await this.pathExists(bmadAgentPath);\n const hasDocs = await this.pathExists(docsPath);\n\n if (hasBmadAgent) {\n spinner.text = \"āœ“ Found bmad-agent/ directory\";\n console.log(chalk.green(\"\\nāœ“ Found bmad-agent/ directory\"));\n }\n\n if (hasDocs) {\n console.log(chalk.green(\"āœ“ Found docs/ directory\"));\n }\n\n const isValid = hasBmadAgent && hasDocs;\n\n if (isValid) {\n spinner.succeed(\"This appears to be a valid V3 project\");\n } else {\n spinner.fail(\"Invalid V3 project structure\");\n }\n\n return { isValid, hasBmadAgent, hasDocs };\n } catch (error) {\n spinner.fail(\"Validation failed\");\n throw error;\n }\n }\n\n async analyzeProject(projectPath) {\n const docsPath = path.join(projectPath, \"docs\");\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n\n // Find PRD\n const prdCandidates = [\"prd.md\", \"PRD.md\", \"product-requirements.md\"];\n let prdFile = null;\n for (const candidate of prdCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n prdFile = candidate;\n break;\n }\n }\n\n // Find Architecture\n const archCandidates = [\n \"architecture.md\",\n \"Architecture.md\",\n \"technical-architecture.md\",\n ];\n let archFile = null;\n for (const candidate of archCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n archFile = candidate;\n break;\n }\n }\n\n // Find Front-end Architecture (V3 specific)\n const frontEndCandidates = [\n \"front-end-architecture.md\",\n \"frontend-architecture.md\",\n \"ui-architecture.md\",\n ];\n let frontEndArchFile = null;\n for (const candidate of frontEndCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n frontEndArchFile = candidate;\n break;\n }\n }\n\n // Find UX/UI spec\n const uxSpecCandidates = [\n \"ux-ui-spec.md\",\n \"ux-ui-specification.md\",\n \"ui-spec.md\",\n \"ux-spec.md\",\n ];\n let uxSpecFile = null;\n for (const candidate of uxSpecCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxSpecFile = candidate;\n break;\n }\n }\n\n // Find v0 prompt or UX prompt\n const uxPromptCandidates = [\n \"v0-prompt.md\",\n \"ux-prompt.md\",\n \"ui-prompt.md\",\n \"design-prompt.md\",\n ];\n let uxPromptFile = null;\n for (const candidate of uxPromptCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxPromptFile = candidate;\n break;\n }\n }\n\n // Find epic files\n const epicFiles = await glob(\"epic*.md\", { cwd: docsPath });\n\n // Find story files\n const storiesPath = path.join(docsPath, \"stories\");\n let storyFiles = [];\n if (await this.pathExists(storiesPath)) {\n storyFiles = await glob(\"*.md\", { cwd: storiesPath });\n }\n\n // Count custom files in bmad-agent\n const bmadAgentFiles = await glob(\"**/*.md\", {\n cwd: bmadAgentPath,\n ignore: [\"node_modules/**\"],\n });\n\n return {\n prdFile,\n archFile,\n frontEndArchFile,\n uxSpecFile,\n uxPromptFile,\n epicFiles,\n storyFiles,\n customFileCount: bmadAgentFiles.length,\n };\n }\n\n async showPreflightCheck(analysis, options) {\n console.log(chalk.bold(\"\\nProject Analysis:\"));\n console.log(\n `- PRD found: ${\n analysis.prdFile\n ? `docs/${analysis.prdFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- Architecture found: ${\n analysis.archFile\n ? `docs/${analysis.archFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n if (analysis.frontEndArchFile) {\n console.log(\n `- Front-end Architecture found: docs/${analysis.frontEndArchFile}`\n );\n }\n console.log(\n `- UX/UI Spec found: ${\n analysis.uxSpecFile\n ? `docs/${analysis.uxSpecFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- UX/Design Prompt found: ${\n analysis.uxPromptFile\n ? `docs/${analysis.uxPromptFile}`\n : chalk.yellow(\"Not found\")\n }`\n );\n console.log(\n `- Epic files found: ${analysis.epicFiles.length} files (epic*.md)`\n );\n console.log(\n `- Stories found: ${analysis.storyFiles.length} files in docs/stories/`\n );\n console.log(`- Custom files in bmad-agent/: ${analysis.customFileCount}`);\n\n if (!options.dryRun) {\n console.log(\"\\nThe following will be backed up to .bmad-v3-backup/:\");\n console.log(\"- bmad-agent/ (entire directory)\");\n console.log(\"- docs/ (entire directory)\");\n\n if (analysis.epicFiles.length > 0) {\n console.log(\n chalk.green(\n \"\\nNote: Epic files found! They will be placed in docs/prd/ with an index.md file.\"\n )\n );\n console.log(\n chalk.green(\n \"Since epic files exist, you won't need to shard the PRD after upgrade.\"\n )\n );\n }\n }\n }\n\n async createBackup(projectPath) {\n const spinner = ora(\"Creating backup...\").start();\n\n try {\n const backupPath = path.join(projectPath, \".bmad-v3-backup\");\n\n // Check if backup already exists\n if (await this.pathExists(backupPath)) {\n spinner.fail(\"Backup directory already exists\");\n console.error(\n chalk.red(\n \"\\nError: Backup directory .bmad-v3-backup/ already exists.\"\n )\n );\n console.error(\"\\nThis might mean an upgrade was already attempted.\");\n console.error(\n \"Please remove or rename the existing backup and try again.\"\n );\n throw new Error(\"Backup already exists\");\n }\n\n // Create backup directory\n await fs.mkdir(backupPath, { recursive: true });\n spinner.text = \"āœ“ Created .bmad-v3-backup/\";\n console.log(chalk.green(\"\\nāœ“ Created .bmad-v3-backup/\"));\n\n // Move bmad-agent\n const bmadAgentSrc = path.join(projectPath, \"bmad-agent\");\n const bmadAgentDest = path.join(backupPath, \"bmad-agent\");\n await fs.rename(bmadAgentSrc, bmadAgentDest);\n console.log(chalk.green(\"āœ“ Moved bmad-agent/ to backup\"));\n\n // Move docs\n const docsSrc = path.join(projectPath, \"docs\");\n const docsDest = path.join(backupPath, \"docs\");\n await fs.rename(docsSrc, docsDest);\n console.log(chalk.green(\"āœ“ Moved docs/ to backup\"));\n\n spinner.succeed(\"Backup created successfully\");\n } catch (error) {\n spinner.fail(\"Backup failed\");\n throw error;\n }\n }\n\n async installV4Structure(projectPath) {\n const spinner = ora(\"Installing V4 structure...\").start();\n\n try {\n // Get the source bmad-core directory (without dot prefix)\n const sourcePath = path.join(__dirname, \"..\", \"..\", \"bmad-core\");\n const destPath = path.join(projectPath, \".bmad-core\");\n\n // Copy .bmad-core\n await this.copyDirectory(sourcePath, destPath);\n spinner.text = \"āœ“ Copied fresh .bmad-core/ directory from V4\";\n console.log(\n chalk.green(\"\\nāœ“ Copied fresh .bmad-core/ directory from V4\")\n );\n\n // Create docs directory\n const docsPath = path.join(projectPath, \"docs\");\n await fs.mkdir(docsPath, { recursive: true });\n console.log(chalk.green(\"āœ“ Created new docs/ directory\"));\n\n // Create install manifest for future updates\n await this.createInstallManifest(projectPath);\n console.log(chalk.green(\"āœ“ Created install manifest\"));\n\n console.log(\n chalk.yellow(\n \"\\nNote: Your V3 bmad-agent content has been backed up and NOT migrated.\"\n )\n );\n console.log(\n chalk.yellow(\n \"The new V4 agents are completely different and look for different file structures.\"\n )\n );\n\n spinner.succeed(\"V4 structure installed successfully\");\n } catch (error) {\n spinner.fail(\"V4 installation failed\");\n throw error;\n }\n }\n\n async migrateDocuments(projectPath, analysis) {\n const spinner = ora(\"Migrating your project documents...\").start();\n\n try {\n const backupDocsPath = path.join(projectPath, \".bmad-v3-backup\", \"docs\");\n const newDocsPath = path.join(projectPath, \"docs\");\n let copiedCount = 0;\n\n // Copy PRD\n if (analysis.prdFile) {\n const src = path.join(backupDocsPath, analysis.prdFile);\n const dest = path.join(newDocsPath, analysis.prdFile);\n await fs.copyFile(src, dest);\n console.log(chalk.green(`\\nāœ“ Copied PRD to docs/${analysis.prdFile}`));\n copiedCount++;\n }\n\n // Copy Architecture\n if (analysis.archFile) {\n const src = path.join(backupDocsPath, analysis.archFile);\n const dest = path.join(newDocsPath, analysis.archFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(`āœ“ Copied Architecture to docs/${analysis.archFile}`)\n );\n copiedCount++;\n }\n\n // Copy Front-end Architecture if exists\n if (analysis.frontEndArchFile) {\n const src = path.join(backupDocsPath, analysis.frontEndArchFile);\n const dest = path.join(newDocsPath, analysis.frontEndArchFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(\n `āœ“ Copied Front-end Architecture to docs/${analysis.frontEndArchFile}`\n )\n );\n console.log(\n chalk.yellow(\n \"Note: V4 uses a single full-stack-architecture.md - use doc-migration-task to merge\"\n )\n );\n copiedCount++;\n }\n\n // Copy UX/UI Spec if exists\n if (analysis.uxSpecFile) {\n const src = path.join(backupDocsPath, analysis.uxSpecFile);\n const dest = path.join(newDocsPath, analysis.uxSpecFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(`āœ“ Copied UX/UI Spec to docs/${analysis.uxSpecFile}`)\n );\n copiedCount++;\n }\n\n // Copy UX/Design Prompt if exists\n if (analysis.uxPromptFile) {\n const src = path.join(backupDocsPath, analysis.uxPromptFile);\n const dest = path.join(newDocsPath, analysis.uxPromptFile);\n await fs.copyFile(src, dest);\n console.log(\n chalk.green(\n `āœ“ Copied UX/Design Prompt to docs/${analysis.uxPromptFile}`\n )\n );\n copiedCount++;\n }\n\n // Copy stories\n if (analysis.storyFiles.length > 0) {\n const storiesDir = path.join(newDocsPath, \"stories\");\n await fs.mkdir(storiesDir, { recursive: true });\n\n for (const storyFile of analysis.storyFiles) {\n const src = path.join(backupDocsPath, \"stories\", storyFile);\n const dest = path.join(storiesDir, storyFile);\n await fs.copyFile(src, dest);\n }\n console.log(\n chalk.green(\n `āœ“ Copied ${analysis.storyFiles.length} story files to docs/stories/`\n )\n );\n copiedCount += analysis.storyFiles.length;\n }\n\n // Copy epic files to prd subfolder\n if (analysis.epicFiles.length > 0) {\n const prdDir = path.join(newDocsPath, \"prd\");\n await fs.mkdir(prdDir, { recursive: true });\n\n for (const epicFile of analysis.epicFiles) {\n const src = path.join(backupDocsPath, epicFile);\n const dest = path.join(prdDir, epicFile);\n await fs.copyFile(src, dest);\n }\n console.log(\n chalk.green(\n `āœ“ Found and copied ${analysis.epicFiles.length} epic files to docs/prd/`\n )\n );\n\n // Create index.md for the prd folder\n await this.createPrdIndex(projectPath, analysis);\n console.log(chalk.green(\"āœ“ Created index.md in docs/prd/\"));\n\n console.log(\n chalk.green(\n \"\\nNote: Epic files detected! These are compatible with V4 and have been copied.\"\n )\n );\n console.log(\n chalk.green(\n \"You won't need to shard the PRD since epics already exist.\"\n )\n );\n copiedCount += analysis.epicFiles.length;\n }\n\n spinner.succeed(`Migrated ${copiedCount} documents successfully`);\n } catch (error) {\n spinner.fail(\"Document migration failed\");\n throw error;\n }\n }\n\n async setupIDE(projectPath, selectedIdes) {\n // Use the IDE selections passed from the installer\n if (!selectedIdes || selectedIdes.length === 0) {\n console.log(chalk.dim(\"No IDE setup requested - skipping\"));\n return;\n }\n\n const ideSetup = require(\"../installer/lib/ide-setup\");\n const spinner = ora(\"Setting up IDE rules for all agents...\").start();\n\n try {\n const ideMessages = {\n cursor: \"Rules created in .cursor/rules/\",\n \"claude-code\": \"Commands created in .claude/commands/BMad/\",\n windsurf: \"Rules created in .windsurf/rules/\",\n trae: \"Rules created in.trae/rules/\",\n roo: \"Custom modes created in .roomodes\",\n cline: \"Rules created in .clinerules/\",\n };\n\n // Setup each selected IDE\n for (const ide of selectedIdes) {\n spinner.text = `Setting up ${ide}...`;\n await ideSetup.setup(ide, projectPath);\n console.log(chalk.green(`\\nāœ“ ${ideMessages[ide]}`));\n }\n\n spinner.succeed(`IDE setup complete for ${selectedIdes.length} IDE(s)!`);\n } catch (error) {\n spinner.fail(\"IDE setup failed\");\n console.error(\n chalk.yellow(\"IDE setup failed, but upgrade is complete.\")\n );\n }\n }\n\n showCompletionReport(projectPath, analysis) {\n console.log(chalk.bold.green(\"\\nāœ“ Upgrade Complete!\\n\"));\n console.log(chalk.bold(\"Summary:\"));\n console.log(`- V3 files backed up to: .bmad-v3-backup/`);\n console.log(`- V4 structure installed: .bmad-core/ (fresh from V4)`);\n\n const totalDocs =\n (analysis.prdFile ? 1 : 0) +\n (analysis.archFile ? 1 : 0) +\n (analysis.frontEndArchFile ? 1 : 0) +\n (analysis.uxSpecFile ? 1 : 0) +\n (analysis.uxPromptFile ? 1 : 0) +\n analysis.storyFiles.length;\n console.log(\n `- Documents migrated: ${totalDocs} files${\n analysis.epicFiles.length > 0\n ? ` + ${analysis.epicFiles.length} epics`\n : \"\"\n }`\n );\n\n console.log(chalk.bold(\"\\nImportant Changes:\"));\n console.log(\n \"- The V4 agents (sm, dev, etc.) expect different file structures than V3\"\n );\n console.log(\n \"- Your V3 bmad-agent content was NOT migrated (it's incompatible)\"\n );\n if (analysis.epicFiles.length > 0) {\n console.log(\n \"- Epic files were found and copied - no PRD sharding needed!\"\n );\n }\n if (analysis.frontEndArchFile) {\n console.log(\n \"- Front-end architecture found - V4 uses full-stack-architecture.md, migration needed\"\n );\n }\n if (analysis.uxSpecFile || analysis.uxPromptFile) {\n console.log(\n \"- UX/UI design files found and copied - ready for use with V4\"\n );\n }\n\n console.log(chalk.bold(\"\\nNext Steps:\"));\n console.log(\"1. Review your documents in the new docs/ folder\");\n console.log(\n \"2. Use @bmad-master agent to run the doc-migration-task to align your documents with V4 templates\"\n );\n if (analysis.epicFiles.length === 0) {\n console.log(\n \"3. Use @bmad-master agent to shard the PRD to create epic files\"\n );\n }\n\n console.log(\n chalk.dim(\n \"\\nYour V3 backup is preserved in .bmad-v3-backup/ and can be restored if needed.\"\n )\n );\n }\n\n async pathExists(filePath) {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n async copyDirectory(src, dest) {\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await this.copyDirectory(srcPath, destPath);\n } else {\n await fs.copyFile(srcPath, destPath);\n }\n }\n }\n\n async createPrdIndex(projectPath, analysis) {\n const prdIndexPath = path.join(projectPath, \"docs\", \"prd\", \"index.md\");\n const prdPath = path.join(\n projectPath,\n \"docs\",\n analysis.prdFile || \"prd.md\"\n );\n\n let indexContent = \"# Product Requirements Document\\n\\n\";\n\n // Try to read the PRD to get the title and intro content\n if (analysis.prdFile && (await this.pathExists(prdPath))) {\n try {\n const prdContent = await fs.readFile(prdPath, \"utf8\");\n const lines = prdContent.split(\"\\n\");\n\n // Find the first heading\n const titleMatch = lines.find((line) => line.startsWith(\"# \"));\n if (titleMatch) {\n indexContent = titleMatch + \"\\n\\n\";\n }\n\n // Get any content before the first ## section\n let introContent = \"\";\n let foundFirstSection = false;\n for (const line of lines) {\n if (line.startsWith(\"## \")) {\n foundFirstSection = true;\n break;\n }\n if (!line.startsWith(\"# \")) {\n introContent += line + \"\\n\";\n }\n }\n\n if (introContent.trim()) {\n indexContent += introContent.trim() + \"\\n\\n\";\n }\n } catch (error) {\n // If we can't read the PRD, just use default content\n }\n }\n\n // Add sections list\n indexContent += \"## Sections\\n\\n\";\n\n // Sort epic files for consistent ordering\n const sortedEpics = [...analysis.epicFiles].sort();\n\n for (const epicFile of sortedEpics) {\n // Extract epic name from filename\n const epicName = epicFile\n .replace(/\\.md$/, \"\")\n .replace(/^epic-?/i, \"\")\n .replace(/-/g, \" \")\n .replace(/^\\d+\\s*/, \"\") // Remove leading numbers\n .trim();\n\n const displayName = epicName.charAt(0).toUpperCase() + epicName.slice(1);\n indexContent += `- [${\n displayName || epicFile.replace(\".md\", \"\")\n }](./${epicFile})\\n`;\n }\n\n await fs.writeFile(prdIndexPath, indexContent);\n }\n\n async createInstallManifest(projectPath) {\n const fileManager = require(\"../installer/lib/file-manager\");\n const { glob } = require(\"glob\");\n\n // Get all files in .bmad-core for the manifest\n const bmadCorePath = path.join(projectPath, \".bmad-core\");\n const files = await glob(\"**/*\", {\n cwd: bmadCorePath,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n\n // Prepend .bmad-core/ to file paths for manifest\n const manifestFiles = files.map((file) => path.join(\".bmad-core\", file));\n\n const config = {\n installType: \"full\",\n agent: null,\n ide: null, // Will be set if IDE setup is done later\n };\n\n await fileManager.createManifest(projectPath, config, manifestFiles);\n }\n}\n\nmodule.exports = V3ToV4Upgrader;\n"], ["/BMAD-METHOD/tools/lib/dependency-resolver.js", "const fs = require('fs').promises;\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { extractYamlFromAgent } = require('./yaml-utils');\n\nclass DependencyResolver {\n constructor(rootDir) {\n this.rootDir = rootDir;\n this.bmadCore = path.join(rootDir, 'bmad-core');\n this.common = path.join(rootDir, 'common');\n this.cache = new Map();\n }\n\n async resolveAgentDependencies(agentId) {\n const agentPath = path.join(this.bmadCore, 'agents', `${agentId}.md`);\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML from markdown content with command cleaning\n const yamlContent = extractYamlFromAgent(agentContent, true);\n if (!yamlContent) {\n throw new Error(`No YAML configuration found in agent ${agentId}`);\n }\n \n const agentConfig = yaml.load(yamlContent);\n \n const dependencies = {\n agent: {\n id: agentId,\n path: agentPath,\n content: agentContent,\n config: agentConfig\n },\n resources: []\n };\n\n // Personas are now embedded in agent configs, no need to resolve separately\n\n // Resolve other dependencies\n const depTypes = ['tasks', 'templates', 'checklists', 'data', 'utils'];\n for (const depType of depTypes) {\n const deps = agentConfig.dependencies?.[depType] || [];\n for (const depId of deps) {\n const resource = await this.loadResource(depType, depId);\n if (resource) dependencies.resources.push(resource);\n }\n }\n\n return dependencies;\n }\n\n async resolveTeamDependencies(teamId) {\n const teamPath = path.join(this.bmadCore, 'agent-teams', `${teamId}.yaml`);\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n \n const dependencies = {\n team: {\n id: teamId,\n path: teamPath,\n content: teamContent,\n config: teamConfig\n },\n agents: [],\n resources: new Map() // Use Map to deduplicate resources\n };\n\n // Always add bmad-orchestrator agent first if it's a team\n const bmadAgent = await this.resolveAgentDependencies('bmad-orchestrator');\n dependencies.agents.push(bmadAgent.agent);\n bmadAgent.resources.forEach(res => {\n dependencies.resources.set(res.path, res);\n });\n\n // Resolve all agents in the team\n let agentsToResolve = teamConfig.agents || [];\n \n // Handle wildcard \"*\" - include all agents except bmad-master\n if (agentsToResolve.includes('*')) {\n const allAgents = await this.listAgents();\n // Remove wildcard and add all agents except those already in the list and bmad-master\n agentsToResolve = agentsToResolve.filter(a => a !== '*');\n for (const agent of allAgents) {\n if (!agentsToResolve.includes(agent) && agent !== 'bmad-master') {\n agentsToResolve.push(agent);\n }\n }\n }\n \n for (const agentId of agentsToResolve) {\n if (agentId === 'bmad-orchestrator' || agentId === 'bmad-master') continue; // Already added or excluded\n const agentDeps = await this.resolveAgentDependencies(agentId);\n dependencies.agents.push(agentDeps.agent);\n \n // Add resources with deduplication\n agentDeps.resources.forEach(res => {\n dependencies.resources.set(res.path, res);\n });\n }\n\n // Resolve workflows\n for (const workflowId of teamConfig.workflows || []) {\n const resource = await this.loadResource('workflows', workflowId);\n if (resource) dependencies.resources.set(resource.path, resource);\n }\n\n // Convert Map back to array\n dependencies.resources = Array.from(dependencies.resources.values());\n\n return dependencies;\n }\n\n async loadResource(type, id) {\n const cacheKey = `${type}#${id}`;\n if (this.cache.has(cacheKey)) {\n return this.cache.get(cacheKey);\n }\n\n try {\n let content = null;\n let filePath = null;\n\n // First try bmad-core\n try {\n filePath = path.join(this.bmadCore, type, id);\n content = await fs.readFile(filePath, 'utf8');\n } catch (e) {\n // If not found in bmad-core, try common folder\n try {\n filePath = path.join(this.common, type, id);\n content = await fs.readFile(filePath, 'utf8');\n } catch (e2) {\n // File not found in either location\n }\n }\n\n if (!content) {\n console.warn(`Resource not found: ${type}/${id}`);\n return null;\n }\n\n const resource = {\n type,\n id,\n path: filePath,\n content\n };\n\n this.cache.set(cacheKey, resource);\n return resource;\n } catch (error) {\n console.error(`Error loading resource ${type}/${id}:`, error.message);\n return null;\n }\n }\n\n async listAgents() {\n try {\n const files = await fs.readdir(path.join(this.bmadCore, 'agents'));\n return files\n .filter(f => f.endsWith('.md'))\n .map(f => f.replace('.md', ''));\n } catch (error) {\n return [];\n }\n }\n\n async listTeams() {\n try {\n const files = await fs.readdir(path.join(this.bmadCore, 'agent-teams'));\n return files\n .filter(f => f.endsWith('.yaml'))\n .map(f => f.replace('.yaml', ''));\n } catch (error) {\n return [];\n }\n }\n}\n\nmodule.exports = DependencyResolver;\n"], ["/BMAD-METHOD/tools/installer/lib/config-loader.js", "const fs = require('fs-extra');\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { extractYamlFromAgent } = require('../../lib/yaml-utils');\n\nclass ConfigLoader {\n constructor() {\n this.configPath = path.join(__dirname, '..', 'config', 'install.config.yaml');\n this.config = null;\n }\n\n async load() {\n if (this.config) return this.config;\n \n try {\n const configContent = await fs.readFile(this.configPath, 'utf8');\n this.config = yaml.load(configContent);\n return this.config;\n } catch (error) {\n throw new Error(`Failed to load configuration: ${error.message}`);\n }\n }\n\n async getInstallationOptions() {\n const config = await this.load();\n return config['installation-options'] || {};\n }\n\n async getAvailableAgents() {\n const agentsDir = path.join(this.getBmadCorePath(), 'agents');\n \n try {\n const entries = await fs.readdir(agentsDir, { withFileTypes: true });\n const agents = [];\n \n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.md')) {\n const agentPath = path.join(agentsDir, entry.name);\n const agentId = path.basename(entry.name, '.md');\n \n try {\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML block from agent file\n const yamlContentText = extractYamlFromAgent(agentContent);\n if (yamlContentText) {\n const yamlContent = yaml.load(yamlContentText);\n const agentConfig = yamlContent.agent || {};\n \n agents.push({\n id: agentId,\n name: agentConfig.title || agentConfig.name || agentId,\n file: `bmad-core/agents/${entry.name}`,\n description: agentConfig.whenToUse || 'No description available'\n });\n }\n } catch (error) {\n console.warn(`Failed to read agent ${entry.name}: ${error.message}`);\n }\n }\n }\n \n // Sort agents by name for consistent display\n agents.sort((a, b) => a.name.localeCompare(b.name));\n \n return agents;\n } catch (error) {\n console.warn(`Failed to read agents directory: ${error.message}`);\n return [];\n }\n }\n\n async getAvailableExpansionPacks() {\n const expansionPacksDir = path.join(this.getBmadCorePath(), '..', 'expansion-packs');\n \n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n const expansionPacks = [];\n \n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n const packPath = path.join(expansionPacksDir, entry.name);\n const configPath = path.join(packPath, 'config.yaml');\n \n try {\n // Read config.yaml\n const configContent = await fs.readFile(configPath, 'utf8');\n const config = yaml.load(configContent);\n \n expansionPacks.push({\n id: entry.name,\n name: config.name || entry.name,\n description: config['short-title'] || config.description || 'No description available',\n fullDescription: config.description || config['short-title'] || 'No description available',\n version: config.version || '1.0.0',\n author: config.author || 'BMad Team',\n packPath: packPath,\n dependencies: config.dependencies?.agents || []\n });\n } catch (error) {\n // Fallback if config.yaml doesn't exist or can't be read\n console.warn(`Failed to read config for expansion pack ${entry.name}: ${error.message}`);\n \n // Try to derive info from directory name as fallback\n const name = entry.name\n .split('-')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n \n expansionPacks.push({\n id: entry.name,\n name: name,\n description: 'No description available',\n fullDescription: 'No description available',\n version: '1.0.0',\n author: 'BMad Team',\n packPath: packPath,\n dependencies: []\n });\n }\n }\n }\n \n return expansionPacks;\n } catch (error) {\n console.warn(`Failed to read expansion packs directory: ${error.message}`);\n return [];\n }\n }\n\n async getAgentDependencies(agentId) {\n // Use DependencyResolver to dynamically parse agent dependencies\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n \n const agentDeps = await resolver.resolveAgentDependencies(agentId);\n \n // Convert to flat list of file paths\n const depPaths = [];\n \n // Core files and utilities are included automatically by DependencyResolver\n \n // Add agent file itself is already handled by installer\n \n // Add all resolved resources\n for (const resource of agentDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n \n return depPaths;\n }\n\n async getIdeConfiguration(ide) {\n const config = await this.load();\n const ideConfigs = config['ide-configurations'] || {};\n return ideConfigs[ide] || null;\n }\n\n getBmadCorePath() {\n // Get the path to bmad-core relative to the installer (now under tools)\n return path.join(__dirname, '..', '..', '..', 'bmad-core');\n }\n\n getDistPath() {\n // Get the path to dist directory relative to the installer\n return path.join(__dirname, '..', '..', '..', 'dist');\n }\n\n getAgentPath(agentId) {\n return path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n }\n\n async getAvailableTeams() {\n const teamsDir = path.join(this.getBmadCorePath(), 'agent-teams');\n \n try {\n const entries = await fs.readdir(teamsDir, { withFileTypes: true });\n const teams = [];\n \n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.yaml')) {\n const teamPath = path.join(teamsDir, entry.name);\n \n try {\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n \n if (teamConfig.bundle) {\n teams.push({\n id: path.basename(entry.name, '.yaml'),\n name: teamConfig.bundle.name || entry.name,\n description: teamConfig.bundle.description || 'Team configuration',\n icon: teamConfig.bundle.icon || 'šŸ“‹'\n });\n }\n } catch (error) {\n console.warn(`Warning: Could not load team config ${entry.name}: ${error.message}`);\n }\n }\n }\n \n return teams;\n } catch (error) {\n console.warn(`Warning: Could not scan teams directory: ${error.message}`);\n return [];\n }\n }\n\n getTeamPath(teamId) {\n return path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n }\n\n async getTeamDependencies(teamId) {\n // Use DependencyResolver to dynamically parse team dependencies\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n \n try {\n const teamDeps = await resolver.resolveTeamDependencies(teamId);\n \n // Convert to flat list of file paths\n const depPaths = [];\n \n // Add team config file\n depPaths.push(`.bmad-core/agent-teams/${teamId}.yaml`);\n \n // Add all agents\n for (const agent of teamDeps.agents) {\n const filePath = `.bmad-core/agents/${agent.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n \n // Add all resolved resources\n for (const resource of teamDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.${resource.type === 'workflows' ? 'yaml' : 'md'}`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n \n return depPaths;\n } catch (error) {\n throw new Error(`Failed to resolve team dependencies for ${teamId}: ${error.message}`);\n }\n }\n}\n\nmodule.exports = new ConfigLoader();"], ["/BMAD-METHOD/tools/installer/bin/bmad.js", "#!/usr/bin/env node\n\nconst { program } = require('commander');\nconst path = require('path');\nconst fs = require('fs').promises;\nconst yaml = require('js-yaml');\nconst chalk = require('chalk');\nconst inquirer = require('inquirer');\n\n// Handle both execution contexts (from root via npx or from installer directory)\nlet version;\nlet installer;\ntry {\n // Try installer context first (when run from tools/installer/)\n version = require('../package.json').version;\n installer = require('../lib/installer');\n} catch (e) {\n // Fall back to root context (when run via npx from GitHub)\n console.log(`Installer context not found (${e.message}), trying root context...`);\n try {\n version = require('../../../package.json').version;\n installer = require('../../../tools/installer/lib/installer');\n } catch (e2) {\n console.error('Error: Could not load required modules. Please ensure you are running from the correct directory.');\n console.error('Debug info:', {\n __dirname,\n cwd: process.cwd(),\n error: e2.message\n });\n process.exit(1);\n }\n}\n\nprogram\n .version(version)\n .description('BMad Method installer - Universal AI agent framework for any domain');\n\nprogram\n .command('install')\n .description('Install BMad Method agents and tools')\n .option('-f, --full', 'Install complete BMad Method')\n .option('-x, --expansion-only', 'Install only expansion packs (no bmad-core)')\n .option('-d, --directory ', 'Installation directory')\n .option('-i, --ide ', 'Configure for specific IDE(s) - can specify multiple (cursor, claude-code, windsurf, trae, roo, cline, gemini, github-copilot, other)')\n .option('-e, --expansion-packs ', 'Install specific expansion packs (can specify multiple)')\n .action(async (options) => {\n try {\n if (!options.full && !options.expansionOnly) {\n // Interactive mode\n const answers = await promptInstallation();\n if (!answers._alreadyInstalled) {\n await installer.install(answers);\n process.exit(0);\n }\n } else {\n // Direct mode\n let installType = 'full';\n if (options.expansionOnly) installType = 'expansion-only';\n\n const config = {\n installType,\n directory: options.directory || '.',\n ides: (options.ide || []).filter(ide => ide !== 'other'),\n expansionPacks: options.expansionPacks || []\n };\n await installer.install(config);\n process.exit(0);\n }\n } catch (error) {\n console.error(chalk.red('Installation failed:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('update')\n .description('Update existing BMad installation')\n .option('--force', 'Force update, overwriting modified files')\n .option('--dry-run', 'Show what would be updated without making changes')\n .action(async () => {\n try {\n await installer.update();\n } catch (error) {\n console.error(chalk.red('Update failed:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('list:expansions')\n .description('List available expansion packs')\n .action(async () => {\n try {\n await installer.listExpansionPacks();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('status')\n .description('Show installation status')\n .action(async () => {\n try {\n await installer.showStatus();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n process.exit(1);\n }\n });\n\nasync function promptInstallation() {\n \n // Display ASCII logo\n console.log(chalk.bold.cyan(`\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•— ā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— \nā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā•ā•ā•šā•ā•ā–ˆā–ˆā•”ā•ā•ā•ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā•”ā–ˆā–ˆā–ˆā–ˆā•”ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•”ā–ˆā–ˆā–ˆā–ˆā•”ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘\nā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā•ā•ā•ā•ā•ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā• ā–ˆā–ˆā•‘ ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ ā•šā•ā• ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā• ā–ˆā–ˆā•‘ ā•šā•ā• ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•\nā•šā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā•ā•šā•ā• ā•šā•ā•ā•šā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā•ā•šā•ā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā• ā•šā•ā• ā•šā•ā•ā•ā•ā•ā• ā•šā•ā•ā•ā•ā•ā• \n `));\n \n console.log(chalk.bold.magenta('šŸš€ Universal AI Agent Framework for Any Domain'));\n console.log(chalk.bold.blue(`✨ Installer v${version}\\n`));\n\n const answers = {};\n\n // Ask for installation directory first\n const { directory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'directory',\n message: 'Enter the full path to your project directory where BMad should be installed:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid project path';\n }\n return true;\n }\n }\n ]);\n answers.directory = directory;\n\n // Detect existing installations\n const installDir = path.resolve(directory);\n const state = await installer.detectInstallationState(installDir);\n \n // Check for existing expansion packs\n const existingExpansionPacks = state.expansionPacks || {};\n \n // Get available expansion packs\n const availableExpansionPacks = await installer.getAvailableExpansionPacks();\n \n // Build choices list\n const choices = [];\n \n // Load core config to get short-title\n const coreConfigPath = path.join(__dirname, '..', '..', '..', 'bmad-core', 'core-config.yaml');\n const coreConfig = yaml.load(await fs.readFile(coreConfigPath, 'utf8'));\n const coreShortTitle = coreConfig['short-title'] || 'BMad Agile Core System';\n \n // Add BMad core option\n let bmadOptionText;\n if (state.type === 'v4_existing') {\n const currentVersion = state.manifest?.version || 'unknown';\n const newVersion = version; // Always use package.json version\n const versionInfo = currentVersion === newVersion \n ? `(v${currentVersion} - reinstall)`\n : `(v${currentVersion} → v${newVersion})`;\n bmadOptionText = `Update ${coreShortTitle} ${versionInfo} .bmad-core`;\n } else {\n bmadOptionText = `${coreShortTitle} (v${version}) .bmad-core`;\n }\n \n choices.push({\n name: bmadOptionText,\n value: 'bmad-core',\n checked: true\n });\n \n // Add expansion pack options\n for (const pack of availableExpansionPacks) {\n const existing = existingExpansionPacks[pack.id];\n let packOptionText;\n \n if (existing) {\n const currentVersion = existing.manifest?.version || 'unknown';\n const newVersion = pack.version;\n const versionInfo = currentVersion === newVersion \n ? `(v${currentVersion} - reinstall)`\n : `(v${currentVersion} → v${newVersion})`;\n packOptionText = `Update ${pack.shortTitle} ${versionInfo} .${pack.id}`;\n } else {\n packOptionText = `${pack.shortTitle} (v${pack.version}) .${pack.id}`;\n }\n \n choices.push({\n name: packOptionText,\n value: pack.id,\n checked: false\n });\n }\n \n // Ask what to install\n const { selectedItems } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedItems',\n message: 'Select what to install/update (use space to select, enter to continue):',\n choices: choices,\n validate: (selected) => {\n if (selected.length === 0) {\n return 'Please select at least one item to install';\n }\n return true;\n }\n }\n ]);\n \n // Process selections\n answers.installType = selectedItems.includes('bmad-core') ? 'full' : 'expansion-only';\n answers.expansionPacks = selectedItems.filter(item => item !== 'bmad-core');\n\n // Ask sharding questions if installing BMad core\n if (selectedItems.includes('bmad-core')) {\n console.log(chalk.cyan('\\nšŸ“‹ Document Organization Settings'));\n console.log(chalk.dim('Configure how your project documentation should be organized.\\n'));\n \n // Ask about PRD sharding\n const { prdSharded } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'prdSharded',\n message: 'Will the PRD (Product Requirements Document) be sharded into multiple files?',\n default: true\n }\n ]);\n answers.prdSharded = prdSharded;\n \n // Ask about architecture sharding\n const { architectureSharded } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'architectureSharded',\n message: 'Will the architecture documentation be sharded into multiple files?',\n default: true\n }\n ]);\n answers.architectureSharded = architectureSharded;\n \n // Show warning if architecture sharding is disabled\n if (!architectureSharded) {\n console.log(chalk.yellow.bold('\\nāš ļø IMPORTANT: Architecture Sharding Disabled'));\n console.log(chalk.yellow('With architecture sharding disabled, you should still create the files listed'));\n console.log(chalk.yellow('in devLoadAlwaysFiles (like coding-standards.md, tech-stack.md, source-tree.md)'));\n console.log(chalk.yellow('as these are used by the dev agent at runtime.'));\n console.log(chalk.yellow('\\nAlternatively, you can remove these files from the devLoadAlwaysFiles list'));\n console.log(chalk.yellow('in your core-config.yaml after installation.'));\n \n const { acknowledge } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'acknowledge',\n message: 'Do you acknowledge this requirement and want to proceed?',\n default: false\n }\n ]);\n \n if (!acknowledge) {\n console.log(chalk.red('Installation cancelled.'));\n process.exit(0);\n }\n }\n }\n\n // Ask for IDE configuration\n let ides = [];\n let ideSelectionComplete = false;\n \n while (!ideSelectionComplete) {\n console.log(chalk.cyan('\\nšŸ› ļø IDE Configuration'));\n console.log(chalk.bold.yellow.bgRed(' āš ļø IMPORTANT: This is a MULTISELECT! Use SPACEBAR to toggle each IDE! '));\n console.log(chalk.bold.magenta('šŸ”ø Use arrow keys to navigate'));\n console.log(chalk.bold.magenta('šŸ”ø Use SPACEBAR to select/deselect IDEs'));\n console.log(chalk.bold.magenta('šŸ”ø Press ENTER when finished selecting\\n'));\n \n const ideResponse = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'ides',\n message: 'Which IDE(s) do you want to configure? (Select with SPACEBAR, confirm with ENTER):',\n choices: [\n { name: 'Cursor', value: 'cursor' },\n { name: 'Claude Code', value: 'claude-code' },\n { name: 'Windsurf', value: 'windsurf' },\n { name: 'Trae', value: 'trae' }, // { name: 'Trae', value: 'trae'}\n { name: 'Roo Code', value: 'roo' },\n { name: 'Cline', value: 'cline' },\n { name: 'Gemini CLI', value: 'gemini' },\n { name: 'Github Copilot', value: 'github-copilot' }\n ]\n }\n ]);\n \n ides = ideResponse.ides;\n\n // Confirm no IDE selection if none selected\n if (ides.length === 0) {\n const { confirmNoIde } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirmNoIde',\n message: chalk.red('āš ļø You have NOT selected any IDEs. This means NO IDE integration will be set up. Is this correct?'),\n default: false\n }\n ]);\n \n if (!confirmNoIde) {\n console.log(chalk.bold.red('\\nšŸ”„ Returning to IDE selection. Remember to use SPACEBAR to select IDEs!\\n'));\n continue; // Go back to IDE selection only\n }\n }\n \n ideSelectionComplete = true;\n }\n\n // Use selected IDEs directly\n answers.ides = ides;\n\n // Configure GitHub Copilot immediately if selected\n if (ides.includes('github-copilot')) {\n console.log(chalk.cyan('\\nšŸ”§ GitHub Copilot Configuration'));\n console.log(chalk.dim('BMad works best with specific VS Code settings for optimal agent experience.\\n'));\n \n const { configChoice } = await inquirer.prompt([\n {\n type: 'list',\n name: 'configChoice',\n message: chalk.yellow('How would you like to configure GitHub Copilot settings?'),\n choices: [\n {\n name: 'Use recommended defaults (fastest setup)',\n value: 'defaults'\n },\n {\n name: 'Configure each setting manually (customize to your preferences)',\n value: 'manual'\n },\n {\n name: 'Skip settings configuration (I\\'ll configure manually later)',\n value: 'skip'\n }\n ],\n default: 'defaults'\n }\n ]);\n \n answers.githubCopilotConfig = { configChoice };\n }\n\n // Ask for web bundles installation\n const { includeWebBundles } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'includeWebBundles',\n message: 'Would you like to include pre-built web bundles? (standalone files for ChatGPT, Claude, Gemini)',\n default: false\n }\n ]);\n\n if (includeWebBundles) {\n console.log(chalk.cyan('\\nšŸ“¦ Web bundles are standalone files perfect for web AI platforms.'));\n console.log(chalk.dim(' You can choose different teams/agents than your IDE installation.\\n'));\n\n const { webBundleType } = await inquirer.prompt([\n {\n type: 'list',\n name: 'webBundleType',\n message: 'What web bundles would you like to include?',\n choices: [\n {\n name: 'All available bundles (agents, teams, expansion packs)',\n value: 'all'\n },\n {\n name: 'Specific teams only',\n value: 'teams'\n },\n {\n name: 'Individual agents only',\n value: 'agents'\n },\n {\n name: 'Custom selection',\n value: 'custom'\n }\n ]\n }\n ]);\n\n answers.webBundleType = webBundleType;\n\n // If specific teams, let them choose which teams\n if (webBundleType === 'teams' || webBundleType === 'custom') {\n const teams = await installer.getAvailableTeams();\n const { selectedTeams } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedTeams',\n message: 'Select team bundles to include:',\n choices: teams.map(t => ({\n name: `${t.icon || 'šŸ“‹'} ${t.name}: ${t.description}`,\n value: t.id,\n checked: webBundleType === 'teams' // Check all if teams-only mode\n })),\n validate: (answer) => {\n if (answer.length < 1) {\n return 'You must select at least one team.';\n }\n return true;\n }\n }\n ]);\n answers.selectedWebBundleTeams = selectedTeams;\n }\n\n // If custom selection, also ask about individual agents\n if (webBundleType === 'custom') {\n const { includeIndividualAgents } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'includeIndividualAgents',\n message: 'Also include individual agent bundles?',\n default: true\n }\n ]);\n answers.includeIndividualAgents = includeIndividualAgents;\n }\n\n const { webBundlesDirectory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'webBundlesDirectory',\n message: 'Enter directory for web bundles:',\n default: `${answers.directory}/web-bundles`,\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid directory path';\n }\n return true;\n }\n }\n ]);\n answers.webBundlesDirectory = webBundlesDirectory;\n }\n\n answers.includeWebBundles = includeWebBundles;\n\n return answers;\n}\n\nprogram.parse(process.argv);\n\n// Show help if no command provided\nif (!process.argv.slice(2).length) {\n program.outputHelp();\n}"], ["/BMAD-METHOD/tools/flattener/main.js", "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst fs = require('fs-extra');\nconst path = require('node:path');\nconst { glob } = require('glob');\nconst { minimatch } = require('minimatch');\n\n/**\n * Recursively discover all files in a directory\n * @param {string} rootDir - The root directory to scan\n * @returns {Promise} Array of file paths\n */\nasync function discoverFiles(rootDir) {\n try {\n const gitignorePath = path.join(rootDir, '.gitignore');\n const gitignorePatterns = await parseGitignore(gitignorePath);\n\n // Common gitignore patterns that should always be ignored\n const commonIgnorePatterns = [\n // Version control\n '.git/**',\n '.svn/**',\n '.hg/**',\n '.bzr/**',\n\n // Dependencies\n 'node_modules/**',\n 'bower_components/**',\n 'vendor/**',\n 'packages/**',\n\n // Build outputs\n 'build/**',\n 'dist/**',\n 'out/**',\n 'target/**',\n 'bin/**',\n 'obj/**',\n 'release/**',\n 'debug/**',\n\n // Environment and config\n '.env',\n '.env.*',\n '*.env',\n '.config',\n\n // Logs\n 'logs/**',\n '*.log',\n 'npm-debug.log*',\n 'yarn-debug.log*',\n 'yarn-error.log*',\n 'lerna-debug.log*',\n\n // Coverage and testing\n 'coverage/**',\n '.nyc_output/**',\n '.coverage/**',\n 'test-results/**',\n 'junit.xml',\n\n // Cache directories\n '.cache/**',\n '.tmp/**',\n '.temp/**',\n 'tmp/**',\n 'temp/**',\n '.sass-cache/**',\n '.eslintcache',\n '.stylelintcache',\n\n // OS generated files\n '.DS_Store',\n '.DS_Store?',\n '._*',\n '.Spotlight-V100',\n '.Trashes',\n 'ehthumbs.db',\n 'Thumbs.db',\n 'desktop.ini',\n\n // IDE and editor files\n '.vscode/**',\n '.idea/**',\n '*.swp',\n '*.swo',\n '*~',\n '.project',\n '.classpath',\n '.settings/**',\n '*.sublime-project',\n '*.sublime-workspace',\n\n // Package manager files\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Pipfile.lock',\n\n // Runtime and compiled files\n '*.pyc',\n '*.pyo',\n '*.pyd',\n '__pycache__/**',\n '*.class',\n '*.jar',\n '*.war',\n '*.ear',\n '*.o',\n '*.so',\n '*.dll',\n '*.exe',\n\n // Documentation build\n '_site/**',\n '.jekyll-cache/**',\n '.jekyll-metadata',\n\n // Flattener specific outputs\n 'flattened-codebase.xml',\n 'repomix-output.xml'\n ];\n\n const combinedIgnores = [\n ...gitignorePatterns,\n ...commonIgnorePatterns\n ];\n\n // Use glob to recursively find all files, excluding common ignore patterns\n const files = await glob('**/*', {\n cwd: rootDir,\n nodir: true, // Only files, not directories\n dot: true, // Include hidden files\n follow: false, // Don't follow symbolic links\n ignore: combinedIgnores\n });\n\n return files.map(file => path.resolve(rootDir, file));\n } catch (error) {\n console.error('Error discovering files:', error.message);\n return [];\n }\n}\n\n/**\n * Parse .gitignore file and return ignore patterns\n * @param {string} gitignorePath - Path to .gitignore file\n * @returns {Promise} Array of ignore patterns\n */\nasync function parseGitignore(gitignorePath) {\n try {\n if (!await fs.pathExists(gitignorePath)) {\n return [];\n }\n\n const content = await fs.readFile(gitignorePath, 'utf8');\n return content\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line && !line.startsWith('#')) // Remove empty lines and comments\n .map(pattern => {\n // Convert gitignore patterns to glob patterns\n if (pattern.endsWith('/')) {\n return pattern + '**';\n }\n return pattern;\n });\n } catch (error) {\n console.error('Error parsing .gitignore:', error.message);\n return [];\n }\n}\n\n/**\n * Check if a file is binary using file command and heuristics\n * @param {string} filePath - Path to the file\n * @returns {Promise} True if file is binary\n */\nasync function isBinaryFile(filePath) {\n try {\n // First check by file extension\n const binaryExtensions = [\n '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.ico', '.svg',\n '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',\n '.zip', '.tar', '.gz', '.rar', '.7z',\n '.exe', '.dll', '.so', '.dylib',\n '.mp3', '.mp4', '.avi', '.mov', '.wav',\n '.ttf', '.otf', '.woff', '.woff2',\n '.bin', '.dat', '.db', '.sqlite'\n ];\n\n const ext = path.extname(filePath).toLowerCase();\n if (binaryExtensions.includes(ext)) {\n return true;\n }\n\n // For files without clear extensions, try to read a small sample\n const stats = await fs.stat(filePath);\n if (stats.size === 0) {\n return false; // Empty files are considered text\n }\n\n // Read first 1024 bytes to check for null bytes\n const sampleSize = Math.min(1024, stats.size);\n const buffer = await fs.readFile(filePath, { encoding: null, flag: 'r' });\n const sample = buffer.slice(0, sampleSize);\n // If we find null bytes, it's likely binary\n return sample.includes(0);\n } catch (error) {\n console.warn(`Warning: Could not determine if file is binary: ${filePath} - ${error.message}`);\n return false; // Default to text if we can't determine\n }\n}\n\n/**\n * Read and aggregate content from text files\n * @param {string[]} files - Array of file paths\n * @param {string} rootDir - The root directory\n * @param {Object} spinner - Optional spinner instance for progress display\n * @returns {Promise} Object containing file contents and metadata\n */\nasync function aggregateFileContents(files, rootDir, spinner = null) {\n const results = {\n textFiles: [],\n binaryFiles: [],\n errors: [],\n totalFiles: files.length,\n processedFiles: 0\n };\n\n for (const filePath of files) {\n try {\n const relativePath = path.relative(rootDir, filePath);\n\n // Update progress indicator\n if (spinner) {\n spinner.text = `Processing file ${results.processedFiles + 1}/${results.totalFiles}: ${relativePath}`;\n }\n\n const isBinary = await isBinaryFile(filePath);\n\n if (isBinary) {\n results.binaryFiles.push({\n path: relativePath,\n absolutePath: filePath,\n size: (await fs.stat(filePath)).size\n });\n } else {\n // Read text file content\n const content = await fs.readFile(filePath, 'utf8');\n results.textFiles.push({\n path: relativePath,\n absolutePath: filePath,\n content: content,\n size: content.length,\n lines: content.split('\\n').length\n });\n }\n\n results.processedFiles++;\n } catch (error) {\n const relativePath = path.relative(rootDir, filePath);\n const errorInfo = {\n path: relativePath,\n absolutePath: filePath,\n error: error.message\n };\n\n results.errors.push(errorInfo);\n\n // Log warning without interfering with spinner\n if (spinner) {\n spinner.warn(`Warning: Could not read file ${relativePath}: ${error.message}`);\n } else {\n console.warn(`Warning: Could not read file ${relativePath}: ${error.message}`);\n }\n\n results.processedFiles++;\n }\n }\n\n return results;\n}\n\n/**\n * Generate XML output with aggregated file contents using streaming\n * @param {Object} aggregatedContent - The aggregated content object\n * @param {string} outputPath - The output file path\n * @returns {Promise} Promise that resolves when writing is complete\n */\nasync function generateXMLOutput(aggregatedContent, outputPath) {\n const { textFiles } = aggregatedContent;\n\n // Create write stream for efficient memory usage\n const writeStream = fs.createWriteStream(outputPath, { encoding: 'utf8' });\n\n return new Promise((resolve, reject) => {\n writeStream.on('error', reject);\n writeStream.on('finish', resolve);\n\n // Write XML header\n writeStream.write('\\n');\n writeStream.write('\\n');\n\n // Process files one by one to minimize memory usage\n let fileIndex = 0;\n\n const writeNextFile = () => {\n if (fileIndex >= textFiles.length) {\n // All files processed, close XML and stream\n writeStream.write('\\n');\n writeStream.end();\n return;\n }\n\n const file = textFiles[fileIndex];\n fileIndex++;\n\n // Write file opening tag\n writeStream.write(` `);\n\n // Use CDATA for code content, handling CDATA end sequences properly\n if (file.content?.trim()) {\n const indentedContent = indentFileContent(file.content);\n if (file.content.includes(']]>')) {\n // If content contains ]]>, split it and wrap each part in CDATA\n writeStream.write(splitAndWrapCDATA(indentedContent));\n } else {\n writeStream.write(``);\n }\n } else if (file.content) {\n // Handle empty or whitespace-only content\n const indentedContent = indentFileContent(file.content);\n writeStream.write(``);\n }\n\n // Write file closing tag\n writeStream.write('\\n');\n\n // Continue with next file on next tick to avoid stack overflow\n setImmediate(writeNextFile);\n };\n\n // Start processing files\n writeNextFile();\n });\n}\n\n/**\n * Escape XML special characters for attributes\n * @param {string} str - String to escape\n * @returns {string} Escaped string\n */\nfunction escapeXml(str) {\n if (typeof str !== 'string') {\n return String(str);\n }\n return str\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Indent file content with 4 spaces for each line\n * @param {string} content - Content to indent\n * @returns {string} Indented content\n */\nfunction indentFileContent(content) {\n if (typeof content !== 'string') {\n return String(content);\n }\n\n // Split content into lines and add 4 spaces of indentation to each line\n return content.split('\\n').map(line => ` ${line}`).join('\\n');\n}\n\n/**\n * Split content containing ]]> and wrap each part in CDATA\n * @param {string} content - Content to process\n * @returns {string} Content with properly wrapped CDATA sections\n */\nfunction splitAndWrapCDATA(content) {\n if (typeof content !== 'string') {\n return String(content);\n }\n\n // Replace ]]> with ]]]]> to escape it within CDATA\n const escapedContent = content.replace(/]]>/g, ']]]]>');\n return ``;\n}\n\n/**\n * Calculate statistics for the processed files\n * @param {Object} aggregatedContent - The aggregated content object\n * @param {number} xmlFileSize - The size of the generated XML file in bytes\n * @returns {Object} Statistics object\n */\nfunction calculateStatistics(aggregatedContent, xmlFileSize) {\n const { textFiles, binaryFiles, errors } = aggregatedContent;\n\n // Calculate total file size in bytes\n const totalTextSize = textFiles.reduce((sum, file) => sum + file.size, 0);\n const totalBinarySize = binaryFiles.reduce((sum, file) => sum + file.size, 0);\n const totalSize = totalTextSize + totalBinarySize;\n\n // Calculate total lines of code\n const totalLines = textFiles.reduce((sum, file) => sum + file.lines, 0);\n\n // Estimate token count (rough approximation: 1 token ā‰ˆ 4 characters)\n const estimatedTokens = Math.ceil(xmlFileSize / 4);\n\n // Format file size\n const formatSize = (bytes) => {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n };\n\n return {\n totalFiles: textFiles.length + binaryFiles.length,\n textFiles: textFiles.length,\n binaryFiles: binaryFiles.length,\n errorFiles: errors.length,\n totalSize: formatSize(totalSize),\n xmlSize: formatSize(xmlFileSize),\n totalLines,\n estimatedTokens: estimatedTokens.toLocaleString()\n };\n}\n\n/**\n * Filter files based on .gitignore patterns\n * @param {string[]} files - Array of file paths\n * @param {string} rootDir - The root directory\n * @returns {Promise} Filtered array of file paths\n */\nasync function filterFiles(files, rootDir) {\n const gitignorePath = path.join(rootDir, '.gitignore');\n const ignorePatterns = await parseGitignore(gitignorePath);\n\n if (ignorePatterns.length === 0) {\n return files;\n }\n\n // Convert absolute paths to relative for pattern matching\n const relativeFiles = files.map(file => path.relative(rootDir, file));\n\n // Separate positive and negative patterns\n const positivePatterns = ignorePatterns.filter(p => !p.startsWith('!'));\n const negativePatterns = ignorePatterns.filter(p => p.startsWith('!')).map(p => p.slice(1));\n\n // Filter out files that match ignore patterns\n const filteredRelative = [];\n\n for (const file of relativeFiles) {\n let shouldIgnore = false;\n\n // First check positive patterns (ignore these files)\n for (const pattern of positivePatterns) {\n if (minimatch(file, pattern)) {\n shouldIgnore = true;\n break;\n }\n }\n\n // Then check negative patterns (don't ignore these files even if they match positive patterns)\n if (shouldIgnore) {\n for (const pattern of negativePatterns) {\n if (minimatch(file, pattern)) {\n shouldIgnore = false;\n break;\n }\n }\n }\n\n if (!shouldIgnore) {\n filteredRelative.push(file);\n }\n }\n\n // Convert back to absolute paths\n return filteredRelative.map(file => path.resolve(rootDir, file));\n}\n\nconst program = new Command();\n\nprogram\n .name('bmad-flatten')\n .description('BMad-Method codebase flattener tool')\n .version('1.0.0')\n .option('-o, --output ', 'Output file path', 'flattened-codebase.xml')\n .action(async (options) => {\n console.log(`Flattening codebase to: ${options.output}`);\n\n try {\n // Import ora dynamically\n const { default: ora } = await import('ora');\n\n // Start file discovery with spinner\n const discoverySpinner = ora('šŸ” Discovering files...').start();\n const files = await discoverFiles(process.cwd());\n const filteredFiles = await filterFiles(files, process.cwd());\n discoverySpinner.succeed(`šŸ“ Found ${filteredFiles.length} files to include`);\n\n // Process files with progress tracking\n console.log('Reading file contents');\n const processingSpinner = ora('šŸ“„ Processing files...').start();\n const aggregatedContent = await aggregateFileContents(filteredFiles, process.cwd(), processingSpinner);\n processingSpinner.succeed(`āœ… Processed ${aggregatedContent.processedFiles}/${filteredFiles.length} files`);\n\n // Log processing results for test validation\n console.log(`Processed ${aggregatedContent.processedFiles}/${filteredFiles.length} files`);\n if (aggregatedContent.errors.length > 0) {\n console.log(`Errors: ${aggregatedContent.errors.length}`);\n }\n console.log(`Text files: ${aggregatedContent.textFiles.length}`);\n if (aggregatedContent.binaryFiles.length > 0) {\n console.log(`Binary files: ${aggregatedContent.binaryFiles.length}`);\n }\n\n // Generate XML output using streaming\n const xmlSpinner = ora('šŸ”§ Generating XML output...').start();\n await generateXMLOutput(aggregatedContent, options.output);\n xmlSpinner.succeed('šŸ“ XML generation completed');\n\n // Calculate and display statistics\n const outputStats = await fs.stat(options.output);\n const stats = calculateStatistics(aggregatedContent, outputStats.size);\n\n // Display completion summary\n console.log('\\nšŸ“Š Completion Summary:');\n console.log(`āœ… Successfully processed ${filteredFiles.length} files into ${options.output}`);\n console.log(`šŸ“ Output file: ${path.resolve(options.output)}`);\n console.log(`šŸ“ Total source size: ${stats.totalSize}`);\n console.log(`šŸ“„ Generated XML size: ${stats.xmlSize}`);\n console.log(`šŸ“ Total lines of code: ${stats.totalLines.toLocaleString()}`);\n console.log(`šŸ”¢ Estimated tokens: ${stats.estimatedTokens}`);\n console.log(`šŸ“Š File breakdown: ${stats.textFiles} text, ${stats.binaryFiles} binary, ${stats.errorFiles} errors`);\n\n } catch (error) {\n console.error('āŒ Critical error:', error.message);\n console.error('An unexpected error occurred.');\n process.exit(1);\n }\n });\n\nif (require.main === module) {\n program.parse();\n}\n\nmodule.exports = program;\n"], ["/BMAD-METHOD/tools/yaml-format.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { execSync } = require('child_process');\n\n// Dynamic import for ES module\nlet chalk;\n\n// Initialize ES modules\nasync function initializeModules() {\n if (!chalk) {\n chalk = (await import('chalk')).default;\n }\n}\n\n/**\n * YAML Formatter and Linter for BMad-Method\n * Formats and validates YAML files and YAML embedded in Markdown\n */\n\nasync function formatYamlContent(content, filename) {\n await initializeModules();\n try {\n // First try to fix common YAML issues\n let fixedContent = content\n // Fix \"commands :\" -> \"commands:\"\n .replace(/^(\\s*)(\\w+)\\s+:/gm, '$1$2:')\n // Fix inconsistent list indentation\n .replace(/^(\\s*)-\\s{3,}/gm, '$1- ');\n \n // Skip auto-fixing for .roomodes files - they have special nested structure\n if (!filename.includes('.roomodes')) {\n fixedContent = fixedContent\n // Fix unquoted list items that contain special characters or multiple parts\n .replace(/^(\\s*)-\\s+(.*)$/gm, (match, indent, content) => {\n // Skip if already quoted\n if (content.startsWith('\"') && content.endsWith('\"')) {\n return match;\n }\n // If the content contains special YAML characters or looks complex, quote it\n // BUT skip if it looks like a proper YAML key-value pair (like \"key: value\")\n if ((content.includes(':') || content.includes('-') || content.includes('{') || content.includes('}')) && \n !content.match(/^\\w+:\\s/)) {\n // Remove any existing quotes first, escape internal quotes, then add proper quotes\n const cleanContent = content.replace(/^[\"']|[\"']$/g, '').replace(/\"/g, '\\\\\"');\n return `${indent}- \"${cleanContent}\"`;\n }\n return match;\n });\n }\n \n // Debug: show what we're trying to parse\n if (fixedContent !== content) {\n console.log(chalk.blue(`šŸ”§ Applied YAML fixes to ${filename}`));\n }\n \n // Parse and re-dump YAML to format it\n const parsed = yaml.load(fixedContent);\n const formatted = yaml.dump(parsed, {\n indent: 2,\n lineWidth: -1, // Disable line wrapping\n noRefs: true,\n sortKeys: false // Preserve key order\n });\n return formatted;\n } catch (error) {\n console.error(chalk.red(`āŒ YAML syntax error in ${filename}:`), error.message);\n console.error(chalk.yellow(`šŸ’” Try manually fixing the YAML structure first`));\n return null;\n }\n}\n\nasync function processMarkdownFile(filePath) {\n await initializeModules();\n const content = fs.readFileSync(filePath, 'utf8');\n let modified = false;\n let newContent = content;\n\n // Fix untyped code blocks by adding 'text' type\n // Match ``` at start of line followed by newline, but only if it's an opening fence\n newContent = newContent.replace(/^```\\n([\\s\\S]*?)\\n```$/gm, '```text\\n$1\\n```');\n if (newContent !== content) {\n modified = true;\n console.log(chalk.blue(`šŸ”§ Added 'text' type to untyped code blocks in ${filePath}`));\n }\n\n // Find YAML code blocks\n const yamlBlockRegex = /```ya?ml\\n([\\s\\S]*?)\\n```/g;\n let match;\n const replacements = [];\n \n while ((match = yamlBlockRegex.exec(newContent)) !== null) {\n const [fullMatch, yamlContent] = match;\n const formatted = await formatYamlContent(yamlContent, filePath);\n if (formatted !== null) {\n // Remove trailing newline that js-yaml adds\n const trimmedFormatted = formatted.replace(/\\n$/, '');\n \n if (trimmedFormatted !== yamlContent) {\n modified = true;\n console.log(chalk.green(`āœ“ Formatted YAML in ${filePath}`));\n }\n \n replacements.push({\n start: match.index,\n end: match.index + fullMatch.length,\n replacement: `\\`\\`\\`yaml\\n${trimmedFormatted}\\n\\`\\`\\``\n });\n }\n }\n \n // Apply replacements in reverse order to maintain indices\n for (let i = replacements.length - 1; i >= 0; i--) {\n const { start, end, replacement } = replacements[i];\n newContent = newContent.slice(0, start) + replacement + newContent.slice(end);\n }\n\n if (modified) {\n fs.writeFileSync(filePath, newContent);\n return true;\n }\n return false;\n}\n\nasync function processYamlFile(filePath) {\n await initializeModules();\n const content = fs.readFileSync(filePath, 'utf8');\n const formatted = await formatYamlContent(content, filePath);\n \n if (formatted === null) {\n return false; // Syntax error\n }\n \n if (formatted !== content) {\n fs.writeFileSync(filePath, formatted);\n return true;\n }\n return false;\n}\n\nasync function lintYamlFile(filePath) {\n await initializeModules();\n try {\n // Use yaml-lint for additional validation\n execSync(`npx yaml-lint \"${filePath}\"`, { stdio: 'pipe' });\n return true;\n } catch (error) {\n console.error(chalk.red(`āŒ YAML lint error in ${filePath}:`));\n console.error(error.stdout?.toString() || error.message);\n return false;\n }\n}\n\nasync function main() {\n await initializeModules();\n const args = process.argv.slice(2);\n const glob = require('glob');\n \n if (args.length === 0) {\n console.error('Usage: node yaml-format.js [file2] ...');\n process.exit(1);\n }\n\n let hasErrors = false;\n let hasChanges = false;\n let filesProcessed = [];\n\n // Expand glob patterns and collect all files\n const allFiles = [];\n for (const arg of args) {\n if (arg.includes('*')) {\n // It's a glob pattern\n const matches = glob.sync(arg);\n allFiles.push(...matches);\n } else {\n // It's a direct file path\n allFiles.push(arg);\n }\n }\n\n for (const filePath of allFiles) {\n if (!fs.existsSync(filePath)) {\n // Skip silently for glob patterns that don't match anything\n if (!args.some(arg => arg.includes('*') && filePath === arg)) {\n console.error(chalk.red(`āŒ File not found: ${filePath}`));\n hasErrors = true;\n }\n continue;\n }\n\n const ext = path.extname(filePath).toLowerCase();\n const basename = path.basename(filePath).toLowerCase();\n \n try {\n let changed = false;\n if (ext === '.md') {\n changed = await processMarkdownFile(filePath);\n } else if (ext === '.yaml' || ext === '.yml' || basename.includes('roomodes') || basename.includes('.yaml') || basename.includes('.yml')) {\n // Handle YAML files and special cases like .roomodes\n changed = await processYamlFile(filePath);\n \n // Also run linting\n const lintPassed = await lintYamlFile(filePath);\n if (!lintPassed) hasErrors = true;\n } else {\n // Skip silently for unsupported files\n continue;\n }\n \n if (changed) {\n hasChanges = true;\n filesProcessed.push(filePath);\n }\n } catch (error) {\n console.error(chalk.red(`āŒ Error processing ${filePath}:`), error.message);\n hasErrors = true;\n }\n }\n\n if (hasChanges) {\n console.log(chalk.green(`\\n✨ YAML formatting completed! Modified ${filesProcessed.length} files:`));\n filesProcessed.forEach(file => console.log(chalk.blue(` šŸ“ ${file}`)));\n }\n\n if (hasErrors) {\n console.error(chalk.red('\\nšŸ’„ Some files had errors. Please fix them before committing.'));\n process.exit(1);\n }\n}\n\nif (require.main === module) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n\nmodule.exports = { formatYamlContent, processMarkdownFile, processYamlFile };"], ["/BMAD-METHOD/tools/cli.js", "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst WebBuilder = require('./builders/web-builder');\nconst V3ToV4Upgrader = require('./upgraders/v3-to-v4-upgrader');\nconst IdeSetup = require('./installer/lib/ide-setup');\nconst path = require('path');\n\nconst program = new Command();\n\nprogram\n .name('bmad-build')\n .description('BMad-Method build tool for creating web bundles')\n .version('4.0.0');\n\nprogram\n .command('build')\n .description('Build web bundles for agents and teams')\n .option('-a, --agents-only', 'Build only agent bundles')\n .option('-t, --teams-only', 'Build only team bundles')\n .option('-e, --expansions-only', 'Build only expansion pack bundles')\n .option('--no-expansions', 'Skip building expansion packs')\n .option('--no-clean', 'Skip cleaning output directories')\n .action(async (options) => {\n const builder = new WebBuilder({\n rootDir: process.cwd()\n });\n\n try {\n if (options.clean) {\n console.log('Cleaning output directories...');\n await builder.cleanOutputDirs();\n }\n\n if (options.expansionsOnly) {\n console.log('Building expansion pack bundles...');\n await builder.buildAllExpansionPacks({ clean: false });\n } else {\n if (!options.teamsOnly) {\n console.log('Building agent bundles...');\n await builder.buildAgents();\n }\n\n if (!options.agentsOnly) {\n console.log('Building team bundles...');\n await builder.buildTeams();\n }\n\n if (!options.noExpansions) {\n console.log('Building expansion pack bundles...');\n await builder.buildAllExpansionPacks({ clean: false });\n }\n }\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error('Build failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('build:expansions')\n .description('Build web bundles for all expansion packs')\n .option('--expansion ', 'Build specific expansion pack only')\n .option('--no-clean', 'Skip cleaning output directories')\n .action(async (options) => {\n const builder = new WebBuilder({\n rootDir: process.cwd()\n });\n\n try {\n if (options.expansion) {\n console.log(`Building expansion pack: ${options.expansion}`);\n await builder.buildExpansionPack(options.expansion, { clean: options.clean });\n } else {\n console.log('Building all expansion packs...');\n await builder.buildAllExpansionPacks({ clean: options.clean });\n }\n\n console.log('Expansion pack build completed successfully!');\n } catch (error) {\n console.error('Expansion pack build failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('list:agents')\n .description('List all available agents')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n const agents = await builder.resolver.listAgents();\n console.log('Available agents:');\n agents.forEach(agent => console.log(` - ${agent}`));\n });\n\nprogram\n .command('list:expansions')\n .description('List all available expansion packs')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n const expansions = await builder.listExpansionPacks();\n console.log('Available expansion packs:');\n expansions.forEach(expansion => console.log(` - ${expansion}`));\n });\n\nprogram\n .command('validate')\n .description('Validate agent and team configurations')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n try {\n // Validate by attempting to build all agents and teams\n const agents = await builder.resolver.listAgents();\n const teams = await builder.resolver.listTeams();\n \n console.log('Validating agents...');\n for (const agent of agents) {\n await builder.resolver.resolveAgentDependencies(agent);\n console.log(` āœ“ ${agent}`);\n }\n \n console.log('\\nValidating teams...');\n for (const team of teams) {\n await builder.resolver.resolveTeamDependencies(team);\n console.log(` āœ“ ${team}`);\n }\n \n console.log('\\nAll configurations are valid!');\n } catch (error) {\n console.error('Validation failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('upgrade')\n .description('Upgrade a BMad-Method V3 project to V4')\n .option('-p, --project ', 'Path to V3 project (defaults to current directory)')\n .option('--dry-run', 'Show what would be changed without making changes')\n .option('--no-backup', 'Skip creating backup (not recommended)')\n .action(async (options) => {\n const upgrader = new V3ToV4Upgrader();\n await upgrader.upgrade({\n projectPath: options.project,\n dryRun: options.dryRun,\n backup: options.backup\n });\n });\n\nprogram\n .command('flatten')\n .description('Flatten codebase to XML format')\n .option('-o, --output ', 'Output file path', 'flattened-codebase.xml')\n .action(async (options) => {\n const flattener = require('./flattener/main');\n await flattener.parseAsync(['flatten', '--output', options.output], { from: 'user' });\n });\n\nprogram.parse();"], ["/BMAD-METHOD/tools/bump-all-versions.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\nconst args = process.argv.slice(2);\nconst bumpType = args[0] || 'minor'; // default to minor\n\nif (!['major', 'minor', 'patch'].includes(bumpType)) {\n console.log('Usage: node bump-all-versions.js [major|minor|patch]');\n console.log('Default: minor');\n process.exit(1);\n}\n\nfunction bumpVersion(currentVersion, type) {\n const [major, minor, patch] = currentVersion.split('.').map(Number);\n \n switch (type) {\n case 'major':\n return `${major + 1}.0.0`;\n case 'minor':\n return `${major}.${minor + 1}.0`;\n case 'patch':\n return `${major}.${minor}.${patch + 1}`;\n default:\n return currentVersion;\n }\n}\n\nasync function bumpAllVersions() {\n const updatedItems = [];\n \n // First, bump the core version (package.json)\n const packagePath = path.join(__dirname, '..', 'package.json');\n try {\n const packageContent = fs.readFileSync(packagePath, 'utf8');\n const packageJson = JSON.parse(packageContent);\n const oldCoreVersion = packageJson.version || '1.0.0';\n const newCoreVersion = bumpVersion(oldCoreVersion, bumpType);\n \n packageJson.version = newCoreVersion;\n \n fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2) + '\\n');\n \n updatedItems.push({ type: 'core', name: 'BMad Core', oldVersion: oldCoreVersion, newVersion: newCoreVersion });\n console.log(`āœ“ BMad Core (package.json): ${oldCoreVersion} → ${newCoreVersion}`);\n } catch (error) {\n console.error(`āœ— Failed to update BMad Core: ${error.message}`);\n }\n \n // Then, bump all expansion packs\n const expansionPacksDir = path.join(__dirname, '..', 'expansion-packs');\n \n try {\n const entries = fs.readdirSync(expansionPacksDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'README.md') {\n const packId = entry.name;\n const configPath = path.join(expansionPacksDir, packId, 'config.yaml');\n \n if (fs.existsSync(configPath)) {\n try {\n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n const oldVersion = config.version || '1.0.0';\n const newVersion = bumpVersion(oldVersion, bumpType);\n \n config.version = newVersion;\n \n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n \n updatedItems.push({ type: 'expansion', name: packId, oldVersion, newVersion });\n console.log(`āœ“ ${packId}: ${oldVersion} → ${newVersion}`);\n \n } catch (error) {\n console.error(`āœ— Failed to update ${packId}: ${error.message}`);\n }\n }\n }\n }\n \n if (updatedItems.length > 0) {\n const coreCount = updatedItems.filter(i => i.type === 'core').length;\n const expansionCount = updatedItems.filter(i => i.type === 'expansion').length;\n \n console.log(`\\nāœ“ Successfully bumped ${updatedItems.length} item(s) with ${bumpType} version bump`);\n if (coreCount > 0) console.log(` - ${coreCount} core`);\n if (expansionCount > 0) console.log(` - ${expansionCount} expansion pack(s)`);\n \n console.log('\\nNext steps:');\n console.log('1. Test the changes');\n console.log('2. Commit: git add -A && git commit -m \"chore: bump all versions (' + bumpType + ')\"');\n } else {\n console.log('No items found to update');\n }\n \n } catch (error) {\n console.error('Error reading expansion packs directory:', error.message);\n process.exit(1);\n }\n}\n\nbumpAllVersions();"], ["/BMAD-METHOD/tools/installer/lib/module-manager.js", "/**\n * Module Manager - Centralized dynamic import management\n * Handles loading and caching of ES modules to reduce memory overhead\n */\n\nclass ModuleManager {\n constructor() {\n this._cache = new Map();\n this._loadingPromises = new Map();\n }\n\n /**\n * Initialize all commonly used ES modules at once\n * @returns {Promise} Object containing all loaded modules\n */\n async initializeCommonModules() {\n const modules = await Promise.all([\n this.getModule('chalk'),\n this.getModule('ora'),\n this.getModule('inquirer')\n ]);\n\n return {\n chalk: modules[0],\n ora: modules[1],\n inquirer: modules[2]\n };\n }\n\n /**\n * Get a module by name, with caching\n * @param {string} moduleName - Name of the module to load\n * @returns {Promise} The loaded module\n */\n async getModule(moduleName) {\n // Return from cache if available\n if (this._cache.has(moduleName)) {\n return this._cache.get(moduleName);\n }\n\n // If already loading, return the existing promise\n if (this._loadingPromises.has(moduleName)) {\n return this._loadingPromises.get(moduleName);\n }\n\n // Start loading the module\n const loadPromise = this._loadModule(moduleName);\n this._loadingPromises.set(moduleName, loadPromise);\n\n try {\n const module = await loadPromise;\n this._cache.set(moduleName, module);\n this._loadingPromises.delete(moduleName);\n return module;\n } catch (error) {\n this._loadingPromises.delete(moduleName);\n throw error;\n }\n }\n\n /**\n * Internal method to load a specific module\n * @private\n */\n async _loadModule(moduleName) {\n switch (moduleName) {\n case 'chalk':\n return (await import('chalk')).default;\n case 'ora':\n return (await import('ora')).default;\n case 'inquirer':\n return (await import('inquirer')).default;\n case 'glob':\n return (await import('glob')).glob;\n case 'globSync':\n return (await import('glob')).globSync;\n default:\n throw new Error(`Unknown module: ${moduleName}`);\n }\n }\n\n /**\n * Clear the module cache to free memory\n */\n clearCache() {\n this._cache.clear();\n this._loadingPromises.clear();\n }\n\n /**\n * Get multiple modules at once\n * @param {string[]} moduleNames - Array of module names\n * @returns {Promise} Object with module names as keys\n */\n async getModules(moduleNames) {\n const modules = await Promise.all(\n moduleNames.map(name => this.getModule(name))\n );\n\n return moduleNames.reduce((acc, name, index) => {\n acc[name] = modules[index];\n return acc;\n }, {});\n }\n}\n\n// Singleton instance\nconst moduleManager = new ModuleManager();\n\nmodule.exports = moduleManager;"], ["/BMAD-METHOD/tools/bump-expansion-version.js", "#!/usr/bin/env node\n\n// Load required modules\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\n// Parse CLI arguments\nconst args = process.argv.slice(2);\nconst packId = args[0];\nconst bumpType = args[1] || 'minor';\n\n// Validate arguments\nif (!packId || args.length > 2) {\n console.log('Usage: node bump-expansion-version.js [major|minor|patch]');\n console.log('Default: minor');\n console.log('Example: node bump-expansion-version.js bmad-creator-tools patch');\n process.exit(1);\n}\n\nif (!['major', 'minor', 'patch'].includes(bumpType)) {\n console.error('Error: Bump type must be major, minor, or patch');\n process.exit(1);\n}\n\n// Version bump logic\nfunction bumpVersion(currentVersion, type) {\n const [major, minor, patch] = currentVersion.split('.').map(Number);\n\n switch (type) {\n case 'major': return `${major + 1}.0.0`;\n case 'minor': return `${major}.${minor + 1}.0`;\n case 'patch': return `${major}.${minor}.${patch + 1}`;\n default: return currentVersion;\n }\n}\n\n// Main function to bump version\nasync function updateVersion() {\n const configPath = path.join(__dirname, '..', 'expansion-packs', packId, 'config.yaml');\n\n // Check if config exists\n if (!fs.existsSync(configPath)) {\n console.error(`Error: Expansion pack '${packId}' not found`);\n console.log('\\nAvailable expansion packs:');\n\n const packsDir = path.join(__dirname, '..', 'expansion-packs');\n const entries = fs.readdirSync(packsDir, { withFileTypes: true });\n\n entries.forEach(entry => {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n console.log(` - ${entry.name}`);\n }\n });\n\n process.exit(1);\n }\n\n try {\n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n\n const oldVersion = config.version || '1.0.0';\n const newVersion = bumpVersion(oldVersion, bumpType);\n\n config.version = newVersion;\n\n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n\n console.log(`āœ“ ${packId}: ${oldVersion} → ${newVersion}`);\n console.log(`\\nāœ“ Successfully bumped ${packId} with ${bumpType} version bump`);\n console.log('\\nNext steps:');\n console.log(`1. Test the changes`);\n console.log(`2. Commit: git add -A && git commit -m \"chore: bump ${packId} version (${bumpType})\"`);\n\n } catch (error) {\n console.error('Error updating version:', error.message);\n process.exit(1);\n }\n}\n\nupdateVersion();\n"], ["/BMAD-METHOD/tools/lib/yaml-utils.js", "/**\n * Utility functions for YAML extraction from agent files\n */\n\n/**\n * Extract YAML content from agent markdown files\n * @param {string} agentContent - The full content of the agent file\n * @param {boolean} cleanCommands - Whether to clean command descriptions (default: false)\n * @returns {string|null} - The extracted YAML content or null if not found\n */\nfunction extractYamlFromAgent(agentContent, cleanCommands = false) {\n // Remove carriage returns and match YAML block\n const yamlMatch = agentContent.replace(/\\r/g, \"\").match(/```ya?ml\\n([\\s\\S]*?)\\n```/);\n if (!yamlMatch) return null;\n \n let yamlContent = yamlMatch[1].trim();\n \n // Clean up command descriptions if requested\n // Converts \"- command - description\" to just \"- command\"\n if (cleanCommands) {\n yamlContent = yamlContent.replace(/^(\\s*-)(\\s*\"[^\"]+\")(\\s*-\\s*.*)$/gm, '$1$2');\n }\n \n return yamlContent;\n}\n\nmodule.exports = {\n extractYamlFromAgent\n};"], ["/BMAD-METHOD/tools/installer/lib/memory-profiler.js", "/**\n * Memory Profiler - Track memory usage during installation\n * Helps identify memory leaks and optimize resource usage\n */\n\nconst v8 = require('v8');\n\nclass MemoryProfiler {\n constructor() {\n this.checkpoints = [];\n this.startTime = Date.now();\n this.peakMemory = 0;\n }\n\n /**\n * Create a memory checkpoint\n * @param {string} label - Label for this checkpoint\n */\n checkpoint(label) {\n const memUsage = process.memoryUsage();\n const heapStats = v8.getHeapStatistics();\n \n const checkpoint = {\n label,\n timestamp: Date.now() - this.startTime,\n memory: {\n rss: this.formatBytes(memUsage.rss),\n heapTotal: this.formatBytes(memUsage.heapTotal),\n heapUsed: this.formatBytes(memUsage.heapUsed),\n external: this.formatBytes(memUsage.external),\n arrayBuffers: this.formatBytes(memUsage.arrayBuffers || 0)\n },\n heap: {\n totalHeapSize: this.formatBytes(heapStats.total_heap_size),\n usedHeapSize: this.formatBytes(heapStats.used_heap_size),\n heapSizeLimit: this.formatBytes(heapStats.heap_size_limit),\n mallocedMemory: this.formatBytes(heapStats.malloced_memory),\n externalMemory: this.formatBytes(heapStats.external_memory)\n },\n raw: {\n heapUsed: memUsage.heapUsed\n }\n };\n\n // Track peak memory\n if (memUsage.heapUsed > this.peakMemory) {\n this.peakMemory = memUsage.heapUsed;\n }\n\n this.checkpoints.push(checkpoint);\n return checkpoint;\n }\n\n /**\n * Force garbage collection (requires --expose-gc flag)\n */\n forceGC() {\n if (global.gc) {\n global.gc();\n return true;\n }\n return false;\n }\n\n /**\n * Get memory usage summary\n */\n getSummary() {\n const currentMemory = process.memoryUsage();\n \n return {\n currentUsage: {\n rss: this.formatBytes(currentMemory.rss),\n heapTotal: this.formatBytes(currentMemory.heapTotal),\n heapUsed: this.formatBytes(currentMemory.heapUsed)\n },\n peakMemory: this.formatBytes(this.peakMemory),\n totalCheckpoints: this.checkpoints.length,\n runTime: `${((Date.now() - this.startTime) / 1000).toFixed(2)}s`\n };\n }\n\n /**\n * Get detailed report of memory usage\n */\n getDetailedReport() {\n const summary = this.getSummary();\n const memoryGrowth = this.calculateMemoryGrowth();\n \n return {\n summary,\n memoryGrowth,\n checkpoints: this.checkpoints,\n recommendations: this.getRecommendations(memoryGrowth)\n };\n }\n\n /**\n * Calculate memory growth between checkpoints\n */\n calculateMemoryGrowth() {\n if (this.checkpoints.length < 2) return [];\n \n const growth = [];\n for (let i = 1; i < this.checkpoints.length; i++) {\n const prev = this.checkpoints[i - 1];\n const curr = this.checkpoints[i];\n \n const heapDiff = curr.raw.heapUsed - prev.raw.heapUsed;\n \n growth.push({\n from: prev.label,\n to: curr.label,\n heapGrowth: this.formatBytes(Math.abs(heapDiff)),\n isIncrease: heapDiff > 0,\n timeDiff: `${((curr.timestamp - prev.timestamp) / 1000).toFixed(2)}s`\n });\n }\n \n return growth;\n }\n\n /**\n * Get recommendations based on memory usage\n */\n getRecommendations(memoryGrowth) {\n const recommendations = [];\n \n // Check for large memory growth\n const largeGrowths = memoryGrowth.filter(g => {\n const bytes = this.parseBytes(g.heapGrowth);\n return bytes > 50 * 1024 * 1024; // 50MB\n });\n \n if (largeGrowths.length > 0) {\n recommendations.push({\n type: 'warning',\n message: `Large memory growth detected in ${largeGrowths.length} operations`,\n details: largeGrowths.map(g => `${g.from} → ${g.to}: ${g.heapGrowth}`)\n });\n }\n \n // Check peak memory\n if (this.peakMemory > 500 * 1024 * 1024) { // 500MB\n recommendations.push({\n type: 'warning',\n message: `High peak memory usage: ${this.formatBytes(this.peakMemory)}`,\n suggestion: 'Consider processing files in smaller batches'\n });\n }\n \n // Check for potential memory leaks\n const continuousGrowth = this.checkContinuousGrowth();\n if (continuousGrowth) {\n recommendations.push({\n type: 'error',\n message: 'Potential memory leak detected',\n details: 'Memory usage continuously increases without significant decreases'\n });\n }\n \n return recommendations;\n }\n\n /**\n * Check for continuous memory growth (potential leak)\n */\n checkContinuousGrowth() {\n if (this.checkpoints.length < 5) return false;\n \n let increasingCount = 0;\n for (let i = 1; i < this.checkpoints.length; i++) {\n if (this.checkpoints[i].raw.heapUsed > this.checkpoints[i - 1].raw.heapUsed) {\n increasingCount++;\n }\n }\n \n // If memory increases in more than 80% of checkpoints, might be a leak\n return increasingCount / (this.checkpoints.length - 1) > 0.8;\n }\n\n /**\n * Format bytes to human-readable string\n */\n formatBytes(bytes) {\n if (bytes === 0) return '0 B';\n \n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n /**\n * Parse human-readable bytes back to number\n */\n parseBytes(str) {\n const match = str.match(/^([\\d.]+)\\s*([KMGT]?B?)$/i);\n if (!match) return 0;\n \n const value = parseFloat(match[1]);\n const unit = match[2].toUpperCase();\n \n const multipliers = {\n 'B': 1,\n 'KB': 1024,\n 'MB': 1024 * 1024,\n 'GB': 1024 * 1024 * 1024\n };\n \n return value * (multipliers[unit] || 1);\n }\n\n /**\n * Clear checkpoints to free memory\n */\n clear() {\n this.checkpoints = [];\n }\n}\n\n// Export singleton instance\nmodule.exports = new MemoryProfiler();"], ["/BMAD-METHOD/tools/update-expansion-version.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\nconst args = process.argv.slice(2);\n\nif (args.length < 2) {\n console.log('Usage: node update-expansion-version.js ');\n console.log('Example: node update-expansion-version.js bmad-creator-tools 1.1.0');\n process.exit(1);\n}\n\nconst [packId, newVersion] = args;\n\n// Validate version format\nif (!/^\\d+\\.\\d+\\.\\d+$/.test(newVersion)) {\n console.error('Error: Version must be in format X.Y.Z (e.g., 1.2.3)');\n process.exit(1);\n}\n\nasync function updateVersion() {\n try {\n // Update in config.yaml\n const configPath = path.join(__dirname, '..', 'expansion-packs', packId, 'config.yaml');\n \n if (!fs.existsSync(configPath)) {\n console.error(`Error: Expansion pack '${packId}' not found`);\n process.exit(1);\n }\n \n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n const oldVersion = config.version || 'unknown';\n \n config.version = newVersion;\n \n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n \n console.log(`āœ“ Updated ${packId}/config.yaml: ${oldVersion} → ${newVersion}`);\n console.log(`\\nāœ“ Successfully updated ${packId} to version ${newVersion}`);\n console.log('\\nNext steps:');\n console.log('1. Test the changes');\n console.log('2. Commit: git add -A && git commit -m \"chore: bump ' + packId + ' to v' + newVersion + '\"');\n \n } catch (error) {\n console.error('Error updating version:', error.message);\n process.exit(1);\n }\n}\n\nupdateVersion();"], ["/BMAD-METHOD/tools/bmad-npx-wrapper.js", "#!/usr/bin/env node\n\n/**\n * BMad Method CLI - Direct execution wrapper for npx\n * This file ensures proper execution when run via npx from GitHub\n */\n\nconst { execSync } = require('child_process');\nconst path = require('path');\nconst fs = require('fs');\n\n// Check if we're running in an npx temporary directory\nconst isNpxExecution = __dirname.includes('_npx') || __dirname.includes('.npm');\n\n// If running via npx, we need to handle things differently\nif (isNpxExecution) {\n // The actual bmad.js is in installer/bin/ (relative to tools directory)\n const bmadScriptPath = path.join(__dirname, 'installer', 'bin', 'bmad.js');\n \n // Verify the file exists\n if (!fs.existsSync(bmadScriptPath)) {\n console.error('Error: Could not find bmad.js at', bmadScriptPath);\n console.error('Current directory:', __dirname);\n process.exit(1);\n }\n \n // Execute with proper working directory\n try {\n execSync(`node \"${bmadScriptPath}\" ${process.argv.slice(2).join(' ')}`, {\n stdio: 'inherit',\n cwd: path.dirname(__dirname)\n });\n } catch (error) {\n // execSync will throw if the command exits with non-zero\n // But the stdio is inherited, so the error is already displayed\n process.exit(error.status || 1);\n }\n} else {\n // Local execution - just require the installer directly\n require('./installer/bin/bmad.js');\n}"], ["/BMAD-METHOD/tools/version-bump.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst { execSync } = require('child_process');\nconst path = require('path');\n\n// Dynamic import for ES module\nlet chalk;\n\n// Initialize ES modules\nasync function initializeModules() {\n if (!chalk) {\n chalk = (await import('chalk')).default;\n }\n}\n\n/**\n * Simple version bumping script for BMad-Method\n * Usage: node tools/version-bump.js [patch|minor|major]\n */\n\nfunction getCurrentVersion() {\n const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));\n return packageJson.version;\n}\n\nasync function bumpVersion(type = 'patch') {\n await initializeModules();\n \n const validTypes = ['patch', 'minor', 'major'];\n if (!validTypes.includes(type)) {\n console.error(chalk.red(`Invalid version type: ${type}. Use: ${validTypes.join(', ')}`));\n process.exit(1);\n }\n\n console.log(chalk.yellow('āš ļø Manual version bumping is disabled.'));\n console.log(chalk.blue('šŸ¤– This project uses semantic-release for automated versioning.'));\n console.log('');\n console.log(chalk.bold('To create a new release, use conventional commits:'));\n console.log(chalk.cyan(' feat: new feature (minor version bump)'));\n console.log(chalk.cyan(' fix: bug fix (patch version bump)'));\n console.log(chalk.cyan(' feat!: breaking change (major version bump)'));\n console.log('');\n console.log(chalk.dim('Example: git commit -m \"feat: add new installer features\"'));\n console.log(chalk.dim('Then push to main branch to trigger automatic release.'));\n \n return null;\n}\n\nasync function main() {\n await initializeModules();\n \n const type = process.argv[2] || 'patch';\n const currentVersion = getCurrentVersion();\n \n console.log(chalk.blue(`Current version: ${currentVersion}`));\n \n // Check if working directory is clean\n try {\n execSync('git diff-index --quiet HEAD --');\n } catch (error) {\n console.error(chalk.red('āŒ Working directory is not clean. Commit your changes first.'));\n process.exit(1);\n }\n \n const newVersion = await bumpVersion(type);\n \n console.log(chalk.green(`\\nšŸŽ‰ Version bump complete!`));\n console.log(chalk.blue(`šŸ“¦ ${currentVersion} → ${newVersion}`));\n}\n\nif (require.main === module) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n\nmodule.exports = { bumpVersion, getCurrentVersion };"], ["/BMAD-METHOD/tools/sync-installer-version.js", "#!/usr/bin/env node\n\n/**\n * Sync installer package.json version with main package.json\n * Used by semantic-release to keep versions in sync\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\nfunction syncInstallerVersion() {\n // Read main package.json\n const mainPackagePath = path.join(__dirname, '..', 'package.json');\n const mainPackage = JSON.parse(fs.readFileSync(mainPackagePath, 'utf8'));\n \n // Read installer package.json\n const installerPackagePath = path.join(__dirname, 'installer', 'package.json');\n const installerPackage = JSON.parse(fs.readFileSync(installerPackagePath, 'utf8'));\n \n // Update installer version to match main version\n installerPackage.version = mainPackage.version;\n \n // Write back installer package.json\n fs.writeFileSync(installerPackagePath, JSON.stringify(installerPackage, null, 2) + '\\n');\n \n console.log(`Synced installer version to ${mainPackage.version}`);\n}\n\n// Run if called directly\nif (require.main === module) {\n syncInstallerVersion();\n}\n\nmodule.exports = { syncInstallerVersion };"], ["/BMAD-METHOD/tools/semantic-release-sync-installer.js", "/**\n * Semantic-release plugin to sync installer package.json version\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\n// This function runs during the \"prepare\" step of semantic-release\nfunction prepare(_, { nextRelease, logger }) {\n // Define the path to the installer package.json file\n const file = path.join(process.cwd(), 'tools/installer/package.json');\n\n // If the file does not exist, skip syncing and log a message\n if (!fs.existsSync(file)) return logger.log('Installer package.json not found, skipping');\n\n // Read and parse the package.json file\n const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));\n\n // Update the version field with the next release version\n pkg.version = nextRelease.version;\n\n // Write the updated JSON back to the file\n fs.writeFileSync(file, JSON.stringify(pkg, null, 2) + '\\n');\n\n // Log success message\n logger.log(`Synced installer package.json to version ${nextRelease.version}`);\n}\n\n// Export the prepare function so semantic-release can use it\nmodule.exports = { prepare };\n"]], "task_instance_info": {"created_time": "2025-08-20 23:47:31", "created_task_model": "DeepSeek-R1", "class_skeleton": "class\nBaseIdeSetup\n{\nconstructor () {}\nasync getAllAgentIds (installDir) {}\nasync getCoreAgentIds (installDir) {}\nasync findAgentPath (agentId, installDir) {}\nasync getAgentTitle (agentId, installDir) {}\nasync getInstalledExpansionPacks (installDir) {}\nasync getExpansionPackAgents (packPath) {}\nasync createAgentRuleContent (agentId, agentPath, installDir, format = 'mdc') {}\nclearCache () {}\n}", "code_description": "This code segment functions to: Manage cached retrieval of software component metadata from multiple installation sources, aggregate resource identifiers across core and expansion modules, and generate formatted documentation templates based on configuration parameters while optimizing filesystem operations through path caching."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nclass BaseIdeSetup {\n constructor() {\n this.cache = new Map();\n }\n\n async getAllAgentIds(installDir) {\n const cacheKey = `all-agents-${installDir}`;\n if (this.cache.has(cacheKey)) return this.cache.get(cacheKey);\n \n const agentsPath = path.join(installDir, 'config', 'agents.yaml');\n if (!await fs.pathExists(agentsPath)) return [];\n \n const agents = await fileManager.readYaml(agentsPath);\n const agentIds = Object.keys(agents);\n this.cache.set(cacheKey, agentIds);\n return agentIds;\n }\n\n async getCoreAgentIds(installDir) {\n const cacheKey = `core-agents-${installDir}`;\n if (this.cache.has(cacheKey)) return this.cache.get(cacheKey);\n \n const allAgents = await this.getAllAgentIds(installDir);\n const coreAgents = allAgents.filter(id => !id.startsWith('expansion/'));\n this.cache.set(cacheKey, coreAgents);\n return coreAgents;\n }\n\n async findAgentPath(agentId, installDir) {\n // Check core agents\n const corePath = resourceLocator.locateAgent(agentId, installDir);\n if (await fs.pathExists(corePath)) return corePath;\n\n // Check expansion packs\n const packs = await this.getInstalledExpansionPacks(installDir);\n for (const pack of packs) {\n const packAgentPath = path.join(pack.path, 'agents', agentId);\n if (await fs.pathExists(packAgentPath)) return packAgentPath;\n }\n\n throw new Error(`Agent ${agentId} not found`);\n }\n\n async getAgentTitle(agentId, installDir) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n const agentConfig = await fileManager.readYaml(path.join(agentPath, 'agent.yaml'));\n return agentConfig?.meta?.title || `Untitled (${agentId})`;\n }\n\n async getInstalledExpansionPacks(installDir) {\n const packsDir = path.join(installDir, 'expansion-packs');\n if (!await fs.pathExists(packsDir)) return [];\n \n const packDirs = await fs.readdir(packsDir);\n return Promise.all(packDirs.map(async dir => {\n const packPath = path.join(packsDir, dir);\n const info = await fileManager.readYaml(path.join(packPath, 'info.yaml'));\n return { id: dir, ...info, path: packPath };\n }));\n }\n\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, 'agents');\n if (!await fs.pathExists(agentsDir)) return [];\n \n const agentDirs = await fs.readdir(agentsDir);\n return agentDirs.filter(dir => \n fs.pathExists(path.join(agentsDir, dir, 'agent.yaml'))\n );\n }\n\n async createAgentRuleContent(agentId, agentPath, installDir, format = 'mdc') {\n const yamlData = await extractYamlFromAgent(agentPath);\n if (format === 'mdc') {\n return `---\n${yaml.stringify(yamlData)}\n---\n\n${yamlData.description || 'No description available'}\n\n**Install Path**: \\`${path.relative(installDir, agentPath)}\\`\n`;\n }\n return yaml.stringify(yamlData);\n }\n\n clearCache() {\n this.cache.clear();\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-48-17"}, "editdistance_info": {"edit_distance": 24.2215, "calculate_time": "2025-08-20 23:48:17", "true_code_clean": "class BaseIdeSetup {\n constructor() {\n this._agentCache = new Map();\n this._pathCache = new Map();\n }\n async getAllAgentIds(installDir) {\n const cacheKey = `all-agents:${installDir}`;\n if (this._agentCache.has(cacheKey)) {\n return this._agentCache.get(cacheKey);\n }\n const allAgents = new Set();\n const coreAgents = await this.getCoreAgentIds(installDir);\n coreAgents.forEach(id => allAgents.add(id));\n const expansionPacks = await this.getInstalledExpansionPacks(installDir);\n for (const pack of expansionPacks) {\n const packAgents = await this.getExpansionPackAgents(pack.path);\n packAgents.forEach(id => allAgents.add(id));\n }\n const result = Array.from(allAgents);\n this._agentCache.set(cacheKey, result);\n return result;\n }\n async getCoreAgentIds(installDir) {\n const coreAgents = [];\n const corePaths = [\n path.join(installDir, \".bmad-core\", \"agents\"),\n path.join(installDir, \"bmad-core\", \"agents\")\n ];\n for (const agentsDir of corePaths) {\n if (await fileManager.pathExists(agentsDir)) {\n const files = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n coreAgents.push(...files.map(file => path.basename(file, \".md\")));\n break; \n }\n }\n return coreAgents;\n }\n async findAgentPath(agentId, installDir) {\n const cacheKey = `agent-path:${agentId}:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n let agentPath = await resourceLocator.getAgentPath(agentId);\n if (!agentPath) {\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"common\", \"agents\", `${agentId}.md`)\n ];\n for (const testPath of possiblePaths) {\n if (await fileManager.pathExists(testPath)) {\n agentPath = testPath;\n break;\n }\n }\n }\n if (agentPath) {\n this._pathCache.set(cacheKey, agentPath);\n }\n return agentPath;\n }\n async getAgentTitle(agentId, installDir) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n if (!agentPath) return agentId;\n try {\n const content = await fileManager.readFile(agentPath);\n const yamlContent = extractYamlFromAgent(content);\n if (yamlContent) {\n const metadata = yaml.load(yamlContent);\n return metadata.agent_name || agentId;\n }\n } catch (error) {\n }\n return agentId;\n }\n async getInstalledExpansionPacks(installDir) {\n const cacheKey = `expansion-packs:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n const expansionPacks = [];\n const dotExpansions = await resourceLocator.findFiles(\".bmad-*\", { cwd: installDir });\n for (const dotExpansion of dotExpansions) {\n if (dotExpansion !== \".bmad-core\") {\n const packPath = path.join(installDir, dotExpansion);\n const packName = dotExpansion.substring(1); \n expansionPacks.push({\n name: packName,\n path: packPath\n });\n }\n }\n const allDotFolders = await resourceLocator.findFiles(\".*\", { cwd: installDir });\n for (const folder of allDotFolders) {\n if (!folder.startsWith(\".bmad-\") && folder !== \".bmad-core\") {\n const packPath = path.join(installDir, folder);\n const configPath = path.join(packPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n expansionPacks.push({\n name: folder.substring(1), \n path: packPath\n });\n }\n }\n }\n this._pathCache.set(cacheKey, expansionPacks);\n return expansionPacks;\n }\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n return [];\n }\n const agentFiles = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n return agentFiles.map(file => path.basename(file, \".md\"));\n }\n async createAgentRuleContent(agentId, agentPath, installDir, format = 'mdc') {\n const agentContent = await fileManager.readFile(agentPath);\n const agentTitle = await this.getAgentTitle(agentId, installDir);\n const yamlContent = extractYamlFromAgent(agentContent);\n let content = \"\";\n if (format === 'mdc') {\n content = \"---\\n\";\n content += \"description: \\n\";\n content += \"globs: []\\n\";\n content += \"alwaysApply: false\\n\";\n content += \"---\\n\\n\";\n content += `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n content += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${agentTitle} agent persona.\\n\\n`;\n content += \"## Agent Activation\\n\\n\";\n content += \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n content += \"```yaml\\n\";\n content += yamlContent || agentContent.replace(/^#.*$/m, \"\").trim();\n content += \"\\n```\\n\\n\";\n content += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n content += `The complete agent definition is available in [${relativePath}](mdc:${relativePath}).\\n\\n`;\n content += \"## Usage\\n\\n\";\n content += `When the user types \\`@${agentId}\\`, activate this ${agentTitle} persona and follow all instructions defined in the YAML configuration above.\\n`;\n } else if (format === 'claude') {\n content = `# /${agentId} Command\\n\\n`;\n content += `When this command is used, adopt the following agent persona:\\n\\n`;\n content += agentContent;\n }\n return content;\n }\n clearCache() {\n this._agentCache.clear();\n this._pathCache.clear();\n }\n}", "predict_code_clean": "class BaseIdeSetup {\n constructor() {\n this.cache = new Map();\n }\n async getAllAgentIds(installDir) {\n const cacheKey = `all-agents-${installDir}`;\n if (this.cache.has(cacheKey)) return this.cache.get(cacheKey);\n const agentsPath = path.join(installDir, 'config', 'agents.yaml');\n if (!await fs.pathExists(agentsPath)) return [];\n const agents = await fileManager.readYaml(agentsPath);\n const agentIds = Object.keys(agents);\n this.cache.set(cacheKey, agentIds);\n return agentIds;\n }\n async getCoreAgentIds(installDir) {\n const cacheKey = `core-agents-${installDir}`;\n if (this.cache.has(cacheKey)) return this.cache.get(cacheKey);\n const allAgents = await this.getAllAgentIds(installDir);\n const coreAgents = allAgents.filter(id => !id.startsWith('expansion/'));\n this.cache.set(cacheKey, coreAgents);\n return coreAgents;\n }\n async findAgentPath(agentId, installDir) {\n const corePath = resourceLocator.locateAgent(agentId, installDir);\n if (await fs.pathExists(corePath)) return corePath;\n const packs = await this.getInstalledExpansionPacks(installDir);\n for (const pack of packs) {\n const packAgentPath = path.join(pack.path, 'agents', agentId);\n if (await fs.pathExists(packAgentPath)) return packAgentPath;\n }\n throw new Error(`Agent ${agentId} not found`);\n }\n async getAgentTitle(agentId, installDir) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n const agentConfig = await fileManager.readYaml(path.join(agentPath, 'agent.yaml'));\n return agentConfig?.meta?.title || `Untitled (${agentId})`;\n }\n async getInstalledExpansionPacks(installDir) {\n const packsDir = path.join(installDir, 'expansion-packs');\n if (!await fs.pathExists(packsDir)) return [];\n const packDirs = await fs.readdir(packsDir);\n return Promise.all(packDirs.map(async dir => {\n const packPath = path.join(packsDir, dir);\n const info = await fileManager.readYaml(path.join(packPath, 'info.yaml'));\n return { id: dir, ...info, path: packPath };\n }));\n }\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, 'agents');\n if (!await fs.pathExists(agentsDir)) return [];\n const agentDirs = await fs.readdir(agentsDir);\n return agentDirs.filter(dir => \n fs.pathExists(path.join(agentsDir, dir, 'agent.yaml'))\n );\n }\n async createAgentRuleContent(agentId, agentPath, installDir, format = 'mdc') {\n const yamlData = await extractYamlFromAgent(agentPath);\n if (format === 'mdc') {\n return `---\n${yaml.stringify(yamlData)}\n---\n${yamlData.description || 'No description available'}\n**Install Path**: \\`${path.relative(installDir, agentPath)}\\`\n`;\n }\n return yaml.stringify(yamlData);\n }\n clearCache() {\n this.cache.clear();\n }\n}"}} {"repo_name": "BMAD-METHOD", "file_name": "/BMAD-METHOD/tools/upgraders/v3-to-v4-upgrader.js", "inference_info": {"prefix_code": "const fs = require(\"fs\").promises;\nconst path = require(\"path\");\nconst { glob } = require(\"glob\");\n\n// Dynamic imports for ES modules\nlet chalk, ora, inquirer;\n\n// Initialize ES modules\nasync function initializeModules() {\n chalk = (await import(\"chalk\")).default;\n ora = (await import(\"ora\")).default;\n inquirer = (await import(\"inquirer\")).default;\n}\n\n", "suffix_code": "\n\nmodule.exports = V3ToV4Upgrader;\n", "middle_code": "class V3ToV4Upgrader {\n constructor() {\n }\n async upgrade(options = {}) {\n try {\n await initializeModules();\n process.stdin.resume();\n console.log(\n chalk.bold(\"\\nWelcome to BMad-Method V3 to V4 Upgrade Tool\\n\")\n );\n console.log(\n \"This tool will help you upgrade your BMad-Method V3 project to V4.\\n\"\n );\n console.log(chalk.cyan(\"What this tool does:\"));\n console.log(\"- Creates a backup of your V3 files (.bmad-v3-backup/)\");\n console.log(\"- Installs the new V4 .bmad-core structure\");\n console.log(\n \"- Preserves your PRD, Architecture, and Stories in the new format\\n\"\n );\n console.log(chalk.yellow(\"What this tool does NOT do:\"));\n console.log(\n \"- Modify your document content (use doc-migration-task after upgrade)\"\n );\n console.log(\"- Touch any files outside bmad-agent/ and docs/\\n\");\n const projectPath = await this.getProjectPath(options.projectPath);\n const validation = await this.validateV3Project(projectPath);\n if (!validation.isValid) {\n console.error(\n chalk.red(\"\\nError: This doesn't appear to be a V3 project.\")\n );\n console.error(\"Expected to find:\");\n console.error(\"- bmad-agent/ directory\");\n console.error(\"- docs/ directory\\n\");\n console.error(\n \"Please check you're in the correct directory and try again.\"\n );\n return;\n }\n const analysis = await this.analyzeProject(projectPath);\n await this.showPreflightCheck(analysis, options);\n if (!options.dryRun) {\n const { confirm } = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirm\",\n message: \"Continue with upgrade?\",\n default: true,\n },\n ]);\n if (!confirm) {\n console.log(\"Upgrade cancelled.\");\n return;\n }\n }\n if (options.backup !== false && !options.dryRun) {\n await this.createBackup(projectPath);\n }\n if (!options.dryRun) {\n await this.installV4Structure(projectPath);\n }\n if (!options.dryRun) {\n await this.migrateDocuments(projectPath, analysis);\n }\n if (!options.dryRun) {\n await this.setupIDE(projectPath, options.ides);\n }\n this.showCompletionReport(projectPath, analysis);\n process.exit(0);\n } catch (error) {\n console.error(chalk.red(\"\\nUpgrade error:\"), error.message);\n process.exit(1);\n }\n }\n async getProjectPath(providedPath) {\n if (providedPath) {\n return path.resolve(providedPath);\n }\n const { projectPath } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"projectPath\",\n message: \"Please enter the path to your V3 project:\",\n default: process.cwd(),\n },\n ]);\n return path.resolve(projectPath);\n }\n async validateV3Project(projectPath) {\n const spinner = ora(\"Validating project structure...\").start();\n try {\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n const docsPath = path.join(projectPath, \"docs\");\n const hasBmadAgent = await this.pathExists(bmadAgentPath);\n const hasDocs = await this.pathExists(docsPath);\n if (hasBmadAgent) {\n spinner.text = \"āœ“ Found bmad-agent/ directory\";\n console.log(chalk.green(\"\\nāœ“ Found bmad-agent/ directory\"));\n }\n if (hasDocs) {\n console.log(chalk.green(\"āœ“ Found docs/ directory\"));\n }\n const isValid = hasBmadAgent && hasDocs;\n if (isValid) {\n spinner.succeed(\"This appears to be a valid V3 project\");\n } else {\n spinner.fail(\"Invalid V3 project structure\");\n }\n return { isValid, hasBmadAgent, hasDocs };\n } catch (error) {\n spinner.fail(\"Validation failed\");\n throw error;\n }\n }\n async analyzeProject(projectPath) {\n const docsPath = path.join(projectPath, \"docs\");\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n const prdCandidates = [\"prd.md\", \"PRD.md\", \"product-requirements.md\"];\n let prdFile = null;\n for (const candidate of prdCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n prdFile = candidate;\n break;\n }\n }\n const archCandidates = [\n \"architecture.md\",\n \"Architecture.md\",\n \"technical-architecture.md\",\n ];\n let archFile = null;\n for (const candidate of archCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n archFile = candidate;\n break;\n }\n }\n const frontEndCandidates = [\n \"front-end-architecture.md\",\n \"frontend-architecture.md\",\n \"ui-architecture.md\",\n ];\n let frontEndArchFile = null;\n for (const candidate of frontEndCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n frontEndArchFile = candidate;\n break;\n }\n }\n const uxSpecCandidates = [\n \"ux-ui-spec.md\",\n \"ux-ui-specification.md\",\n \"ui-spec.md\",\n \"ux-spec.md\",\n ];\n let uxSpecFile = null;\n for (const candidate of uxSpecCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxSpecFile = candidate;\n break;\n }\n }\n const uxPromptCandidates = [\n \"v0-prompt.md\",\n \"ux-prompt.md\",\n \"ui-prompt.md\",\n \"design-prompt.md\",\n ];\n let uxPromptFile = null;\n for (const candidate of uxPromptCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxPromptFile = candidate;\n break;\n }\n }\n const epicFiles = await glob(\"epic*.md\", { cwd: docsPath });\n const storiesPath = path.join(docsPath, \"stories\");\n let storyFiles = [];\n if (await this.pathExists(storiesPath)) {\n storyFiles = await glob(\"*.md\", { cwd: storiesPath });\n }\n const bmadAgentFiles = await glob(\"**, \"\") \n .trim();\n const displayName = epicName.charAt(0).toUpperCase() + epicName.slice(1);\n indexContent += `- [${\n displayName || epicFile.replace(\".md\", \"\")\n }](./${epicFile})\\n`;\n }\n await fs.writeFile(prdIndexPath, indexContent);\n }\n async createInstallManifest(projectPath) {\n const fileManager = require(\"../installer/lib/file-manager\");\n const { glob } = require(\"glob\");\n const bmadCorePath = path.join(projectPath, \".bmad-core\");\n const files = await glob(\"**.gitnode_modules/**\"],\n });\n const manifestFiles = files.map((file) => path.join(\".bmad-core\", file));\n const config = {\n installType: \"full\",\n agent: null,\n ide: null, \n };\n await fileManager.createManifest(projectPath, config, manifestFiles);\n }\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "javascript", "sub_task_type": null}, "context_code": [["/BMAD-METHOD/tools/installer/lib/installer.js", "const path = require(\"node:path\");\nconst fs = require(\"fs-extra\");\nconst chalk = require(\"chalk\");\nconst ora = require(\"ora\");\nconst inquirer = require(\"inquirer\");\nconst fileManager = require(\"./file-manager\");\nconst configLoader = require(\"./config-loader\");\nconst ideSetup = require(\"./ide-setup\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\nconst resourceLocator = require(\"./resource-locator\");\n\nclass Installer {\n async getCoreVersion() {\n try {\n // Always use package.json version\n const packagePath = path.join(__dirname, '..', '..', '..', 'package.json');\n const packageJson = require(packagePath);\n return packageJson.version;\n } catch (error) {\n console.warn(\"Could not read version from package.json, using 'unknown'\");\n return \"unknown\";\n }\n }\n\n async install(config) {\n const spinner = ora(\"Analyzing installation directory...\").start();\n \n try {\n // Store the original CWD where npx was executed\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n \n // Resolve installation directory relative to where the user ran the command\n let installDir = path.isAbsolute(config.directory) \n ? config.directory \n : path.resolve(originalCwd, config.directory);\n \n if (path.basename(installDir) === '.bmad-core') {\n // If user points directly to .bmad-core, treat its parent as the project root\n installDir = path.dirname(installDir);\n }\n \n // Log resolved path for clarity\n if (!path.isAbsolute(config.directory)) {\n spinner.text = `Resolving \"${config.directory}\" to: ${installDir}`;\n }\n\n // Check if directory exists and handle non-existent directories\n if (!(await fileManager.pathExists(installDir))) {\n spinner.stop();\n console.log(`\\nThe directory ${installDir} does not exist.`);\n \n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n {\n name: 'Create the directory and continue',\n value: 'create'\n },\n {\n name: 'Choose a different directory',\n value: 'change'\n },\n {\n name: 'Cancel installation',\n value: 'cancel'\n }\n ]\n }\n ]);\n\n if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n } else if (action === 'change') {\n const { newDirectory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'newDirectory',\n message: 'Enter the new directory path:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid directory path';\n }\n return true;\n }\n }\n ]);\n // Preserve the original CWD for the recursive call\n config.directory = newDirectory;\n return await this.install(config); // Recursive call with new directory\n } else if (action === 'create') {\n try {\n await fileManager.ensureDirectory(installDir);\n console.log(`āœ“ Created directory: ${installDir}`);\n } catch (error) {\n console.error(`Failed to create directory: ${error.message}`);\n console.error('You may need to check permissions or use a different path.');\n process.exit(1);\n }\n }\n \n spinner.start(\"Analyzing installation directory...\");\n }\n\n // If this is an update request from early detection, handle it directly\n if (config.installType === 'update') {\n const state = await this.detectInstallationState(installDir);\n if (state.type === 'v4_existing') {\n return await this.performUpdate(config, installDir, state.manifest, spinner);\n } else {\n spinner.fail('No existing v4 installation found to update');\n throw new Error('No existing v4 installation found');\n }\n }\n\n // Detect current state\n const state = await this.detectInstallationState(installDir);\n\n // Handle different states\n switch (state.type) {\n case \"clean\":\n return await this.performFreshInstall(config, installDir, spinner);\n\n case \"v4_existing\":\n return await this.handleExistingV4Installation(\n config,\n installDir,\n state,\n spinner\n );\n\n case \"v3_existing\":\n return await this.handleV3Installation(\n config,\n installDir,\n state,\n spinner\n );\n\n case \"unknown_existing\":\n return await this.handleUnknownInstallation(\n config,\n installDir,\n state,\n spinner\n );\n }\n } catch (error) {\n // Check if modules were initialized\n if (spinner) {\n spinner.fail(\"Installation failed\");\n } else {\n console.error(\"Installation failed:\", error.message);\n }\n throw error;\n }\n }\n\n async detectInstallationState(installDir) {\n const state = {\n type: \"clean\",\n hasV4Manifest: false,\n hasV3Structure: false,\n hasBmadCore: false,\n hasOtherFiles: false,\n manifest: null,\n expansionPacks: {},\n };\n\n // Check if directory exists\n if (!(await fileManager.pathExists(installDir))) {\n return state; // clean install\n }\n\n // Check for V4 installation (has .bmad-core with manifest)\n const bmadCorePath = path.join(installDir, \".bmad-core\");\n const manifestPath = path.join(bmadCorePath, \"install-manifest.yaml\");\n\n if (await fileManager.pathExists(manifestPath)) {\n state.type = \"v4_existing\";\n state.hasV4Manifest = true;\n state.hasBmadCore = true;\n state.manifest = await fileManager.readManifest(installDir);\n return state;\n }\n\n // Check for V3 installation (has bmad-agent directory)\n const bmadAgentPath = path.join(installDir, \"bmad-agent\");\n if (await fileManager.pathExists(bmadAgentPath)) {\n state.type = \"v3_existing\";\n state.hasV3Structure = true;\n return state;\n }\n\n // Check for .bmad-core without manifest (broken V4 or manual copy)\n if (await fileManager.pathExists(bmadCorePath)) {\n state.type = \"unknown_existing\";\n state.hasBmadCore = true;\n return state;\n }\n\n // Check if directory has other files\n const files = await resourceLocator.findFiles(\"**/*\", {\n cwd: installDir,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n\n if (files.length > 0) {\n // Directory has other files, but no BMad installation.\n // Treat as clean install but record that it isn't empty.\n state.hasOtherFiles = true;\n }\n\n // Check for expansion packs (folders starting with .)\n const expansionPacks = await this.detectExpansionPacks(installDir);\n state.expansionPacks = expansionPacks;\n\n return state; // clean install\n }\n\n async performFreshInstall(config, installDir, spinner, options = {}) {\n spinner.text = \"Installing BMad Method...\";\n\n let files = [];\n\n if (config.installType === \"full\") {\n // Full installation - copy entire .bmad-core folder as a subdirectory\n spinner.text = \"Copying complete .bmad-core folder...\";\n const sourceDir = resourceLocator.getBmadCorePath();\n const bmadCoreDestDir = path.join(installDir, \".bmad-core\");\n await fileManager.copyDirectoryWithRootReplacement(sourceDir, bmadCoreDestDir, \".bmad-core\");\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n\n // Get list of all files for manifest\n const foundFiles = await resourceLocator.findFiles(\"**/*\", {\n cwd: bmadCoreDestDir,\n nodir: true,\n ignore: [\"**/.git/**\", \"**/node_modules/**\"],\n });\n files = foundFiles.map((file) => path.join(\".bmad-core\", file));\n } else if (config.installType === \"single-agent\") {\n // Single agent installation\n spinner.text = `Installing ${config.agent} agent...`;\n\n // Copy agent file with {root} replacement\n const agentPath = configLoader.getAgentPath(config.agent);\n const destAgentPath = path.join(\n installDir,\n \".bmad-core\",\n \"agents\",\n `${config.agent}.md`\n );\n await fileManager.copyFileWithRootReplacement(agentPath, destAgentPath, \".bmad-core\");\n files.push(`.bmad-core/agents/${config.agent}.md`);\n\n // Copy dependencies\n const { all: dependencies } = await resourceLocator.getAgentDependencies(\n config.agent\n );\n const sourceBase = resourceLocator.getBmadCorePath();\n\n for (const dep of dependencies) {\n spinner.text = `Copying dependency: ${dep}`;\n\n if (dep.includes(\"*\")) {\n // Handle glob patterns with {root} replacement\n const copiedFiles = await fileManager.copyGlobPattern(\n dep.replace(\".bmad-core/\", \"\"),\n sourceBase,\n path.join(installDir, \".bmad-core\"),\n \".bmad-core\"\n );\n files.push(...copiedFiles.map(f => `.bmad-core/${f}`));\n } else {\n // Handle single files with {root} replacement if needed\n const sourcePath = path.join(\n sourceBase,\n dep.replace(\".bmad-core/\", \"\")\n );\n const destPath = path.join(\n installDir,\n dep\n );\n\n const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, \".bmad-core\");\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n files.push(dep);\n }\n }\n }\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n const commonFiles = await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n files.push(...commonFiles);\n } else if (config.installType === \"team\") {\n // Team installation\n spinner.text = `Installing ${config.team} team...`;\n \n // Get team dependencies\n const teamDependencies = await configLoader.getTeamDependencies(config.team);\n const sourceBase = resourceLocator.getBmadCorePath();\n \n // Install all team dependencies\n for (const dep of teamDependencies) {\n spinner.text = `Copying team dependency: ${dep}`;\n \n if (dep.includes(\"*\")) {\n // Handle glob patterns with {root} replacement\n const copiedFiles = await fileManager.copyGlobPattern(\n dep.replace(\".bmad-core/\", \"\"),\n sourceBase,\n path.join(installDir, \".bmad-core\"),\n \".bmad-core\"\n );\n files.push(...copiedFiles.map(f => `.bmad-core/${f}`));\n } else {\n // Handle single files with {root} replacement if needed\n const sourcePath = path.join(sourceBase, dep.replace(\".bmad-core/\", \"\"));\n const destPath = path.join(installDir, dep);\n \n const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, \".bmad-core\");\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n files.push(dep);\n }\n }\n }\n \n // Copy common/ items to .bmad-core\n spinner.text = \"Copying common utilities...\";\n const commonFiles = await this.copyCommonItems(installDir, \".bmad-core\", spinner);\n files.push(...commonFiles);\n } else if (config.installType === \"expansion-only\") {\n // Expansion-only installation - DO NOT create .bmad-core\n // Only install expansion packs\n spinner.text = \"Installing expansion packs only...\";\n }\n\n // Install expansion packs if requested\n const expansionFiles = await this.installExpansionPacks(installDir, config.expansionPacks, spinner, config);\n files.push(...expansionFiles);\n\n // Install web bundles if requested\n if (config.includeWebBundles && config.webBundlesDirectory) {\n spinner.text = \"Installing web bundles...\";\n // Resolve web bundles directory using the same logic as the main installation directory\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n let resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory) \n ? config.webBundlesDirectory \n : path.resolve(originalCwd, config.webBundlesDirectory);\n await this.installWebBundles(resolvedWebBundlesDir, config, spinner);\n }\n\n // Set up IDE integration if requested\n const ides = config.ides || (config.ide ? [config.ide] : []);\n if (ides.length > 0) {\n for (const ide of ides) {\n spinner.text = `Setting up ${ide} integration...`;\n const preConfiguredSettings = ide === 'github-copilot' ? config.githubCopilotConfig : null;\n await ideSetup.setup(ide, installDir, config.agent, spinner, preConfiguredSettings);\n }\n }\n\n // Modify core-config.yaml if sharding preferences were provided\n if (config.installType !== \"expansion-only\" && (config.prdSharded !== undefined || config.architectureSharded !== undefined)) {\n spinner.text = \"Configuring document sharding settings...\";\n await fileManager.modifyCoreConfig(installDir, config);\n }\n\n // Create manifest (skip for expansion-only installations)\n if (config.installType !== \"expansion-only\") {\n spinner.text = \"Creating installation manifest...\";\n await fileManager.createManifest(installDir, config, files);\n }\n\n spinner.succeed(\"Installation complete!\");\n this.showSuccessMessage(config, installDir, options);\n }\n\n async handleExistingV4Installation(config, installDir, state, spinner) {\n spinner.stop();\n\n const currentVersion = state.manifest.version;\n const newVersion = await this.getCoreVersion();\n const versionCompare = this.compareVersions(currentVersion, newVersion);\n\n console.log(chalk.yellow(\"\\nšŸ” Found existing BMad v4 installation\"));\n console.log(` Directory: ${installDir}`);\n console.log(` Current version: ${currentVersion}`);\n console.log(` Available version: ${newVersion}`);\n console.log(\n ` Installed: ${new Date(\n state.manifest.installed_at\n ).toLocaleDateString()}`\n );\n\n // Check file integrity\n spinner.start(\"Checking installation integrity...\");\n const integrity = await fileManager.checkFileIntegrity(installDir, state.manifest);\n spinner.stop();\n \n const hasMissingFiles = integrity.missing.length > 0;\n const hasModifiedFiles = integrity.modified.length > 0;\n const hasIntegrityIssues = hasMissingFiles || hasModifiedFiles;\n \n if (hasIntegrityIssues) {\n console.log(chalk.red(\"\\nāš ļø Installation issues detected:\"));\n if (hasMissingFiles) {\n console.log(chalk.red(` Missing files: ${integrity.missing.length}`));\n if (integrity.missing.length <= 5) {\n integrity.missing.forEach(file => console.log(chalk.dim(` - ${file}`)));\n }\n }\n if (hasModifiedFiles) {\n console.log(chalk.yellow(` Modified files: ${integrity.modified.length}`));\n if (integrity.modified.length <= 5) {\n integrity.modified.forEach(file => console.log(chalk.dim(` - ${file}`)));\n }\n }\n }\n\n // Show existing expansion packs\n if (Object.keys(state.expansionPacks).length > 0) {\n console.log(chalk.cyan(\"\\nšŸ“¦ Installed expansion packs:\"));\n for (const [packId, packInfo] of Object.entries(state.expansionPacks)) {\n if (packInfo.hasManifest && packInfo.manifest) {\n console.log(` - ${packId} (v${packInfo.manifest.version || 'unknown'})`);\n } else {\n console.log(` - ${packId} (no manifest)`);\n }\n }\n }\n\n let choices = [];\n \n if (versionCompare < 0) {\n console.log(chalk.cyan(\"\\nā¬†ļø Upgrade available for BMad core\"));\n choices.push({ name: `Upgrade BMad core (v${currentVersion} → v${newVersion})`, value: \"upgrade\" });\n } else if (versionCompare === 0) {\n if (hasIntegrityIssues) {\n // Offer repair option when files are missing or modified\n choices.push({ \n name: \"Repair installation (restore missing/modified files)\", \n value: \"repair\" \n });\n }\n console.log(chalk.yellow(\"\\nāš ļø Same version already installed\"));\n choices.push({ name: `Force reinstall BMad core (v${currentVersion} - reinstall)`, value: \"reinstall\" });\n } else {\n console.log(chalk.yellow(\"\\nā¬‡ļø Installed version is newer than available\"));\n choices.push({ name: `Downgrade BMad core (v${currentVersion} → v${newVersion})`, value: \"reinstall\" });\n }\n \n choices.push(\n { name: \"Add/update expansion packs only\", value: \"expansions\" },\n { name: \"Cancel\", value: \"cancel\" }\n );\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: choices,\n },\n ]);\n\n switch (action) {\n case \"upgrade\":\n return await this.performUpdate(config, installDir, state.manifest, spinner);\n case \"repair\":\n // For repair, restore missing/modified files while backing up modified ones\n return await this.performRepair(config, installDir, state.manifest, integrity, spinner);\n case \"reinstall\":\n // For reinstall, don't check for modifications - just overwrite\n return await this.performReinstall(config, installDir, spinner);\n case \"expansions\":\n // Ask which expansion packs to install\n const availableExpansionPacks = await resourceLocator.getExpansionPacks();\n \n if (availableExpansionPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs available.\"));\n return;\n }\n \n const { selectedPacks } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedPacks',\n message: 'Select expansion packs to install/update:',\n choices: availableExpansionPacks.map(pack => ({\n name: `${pack.name} (v${pack.version}) .${pack.id}`,\n value: pack.id,\n checked: state.expansionPacks[pack.id] !== undefined\n }))\n }\n ]);\n \n if (selectedPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs selected.\"));\n return;\n }\n \n spinner.start(\"Installing expansion packs...\");\n const expansionFiles = await this.installExpansionPacks(installDir, selectedPacks, spinner, { ides: config.ides || [] });\n spinner.succeed(\"Expansion packs installed successfully!\");\n \n console.log(chalk.green(\"\\nāœ“ Installation complete!\"));\n console.log(chalk.green(`āœ“ Expansion packs installed/updated:`));\n for (const packId of selectedPacks) {\n console.log(chalk.green(` - ${packId} → .${packId}/`));\n }\n return;\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async handleV3Installation(config, installDir, state, spinner) {\n spinner.stop();\n\n console.log(\n chalk.yellow(\"\\nšŸ” Found BMad v3 installation (bmad-agent/ directory)\")\n );\n console.log(` Directory: ${installDir}`);\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: [\n { name: \"Upgrade from v3 to v4 (recommended)\", value: \"upgrade\" },\n { name: \"Install v4 alongside v3\", value: \"alongside\" },\n { name: \"Cancel\", value: \"cancel\" },\n ],\n },\n ]);\n\n switch (action) {\n case \"upgrade\": {\n console.log(chalk.cyan(\"\\nšŸ“¦ Starting v3 to v4 upgrade process...\"));\n const V3ToV4Upgrader = require(\"../../upgraders/v3-to-v4-upgrader\");\n const upgrader = new V3ToV4Upgrader();\n return await upgrader.upgrade({ \n projectPath: installDir,\n ides: config.ides || [] // Pass IDE selections from initial config\n });\n }\n case \"alongside\":\n return await this.performFreshInstall(config, installDir, spinner);\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async handleUnknownInstallation(config, installDir, state, spinner) {\n spinner.stop();\n\n console.log(chalk.yellow(\"\\nāš ļø Directory contains existing files\"));\n console.log(` Directory: ${installDir}`);\n\n if (state.hasBmadCore) {\n console.log(\" Found: .bmad-core directory (but no manifest)\");\n }\n if (state.hasOtherFiles) {\n console.log(\" Found: Other files in directory\");\n }\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"What would you like to do?\",\n choices: [\n { name: \"Install anyway (may overwrite files)\", value: \"force\" },\n { name: \"Choose different directory\", value: \"different\" },\n { name: \"Cancel\", value: \"cancel\" },\n ],\n },\n ]);\n\n switch (action) {\n case \"force\":\n return await this.performFreshInstall(config, installDir, spinner);\n case \"different\": {\n const { newDir } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"newDir\",\n message: \"Enter new installation directory:\",\n default: path.join(path.dirname(installDir), \"bmad-project\"),\n },\n ]);\n config.directory = newDir;\n return await this.install(config);\n }\n case \"cancel\":\n console.log(\"Installation cancelled.\");\n return;\n }\n }\n\n async performUpdate(newConfig, installDir, manifest, spinner) {\n spinner.start(\"Checking for updates...\");\n\n try {\n // Get current and new versions\n const currentVersion = manifest.version;\n const newVersion = await this.getCoreVersion();\n const versionCompare = this.compareVersions(currentVersion, newVersion);\n \n // Only check for modified files if it's an actual version upgrade\n let modifiedFiles = [];\n if (versionCompare !== 0) {\n spinner.text = \"Checking for modified files...\";\n modifiedFiles = await fileManager.checkModifiedFiles(\n installDir,\n manifest\n );\n }\n\n if (modifiedFiles.length > 0) {\n spinner.warn(\"Found modified files\");\n console.log(chalk.yellow(\"\\nThe following files have been modified:\"));\n for (const file of modifiedFiles) {\n console.log(` - ${file}`);\n }\n\n const { action } = await inquirer.prompt([\n {\n type: \"list\",\n name: \"action\",\n message: \"How would you like to proceed?\",\n choices: [\n { name: \"Backup and overwrite modified files\", value: \"backup\" },\n { name: \"Skip modified files\", value: \"skip\" },\n { name: \"Cancel update\", value: \"cancel\" },\n ],\n },\n ]);\n\n if (action === \"cancel\") {\n console.log(\"Update cancelled.\");\n return;\n }\n\n if (action === \"backup\") {\n spinner.start(\"Backing up modified files...\");\n for (const file of modifiedFiles) {\n const filePath = path.join(installDir, file);\n const backupPath = await fileManager.backupFile(filePath);\n console.log(\n chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`)\n );\n }\n }\n }\n\n // Perform update by re-running installation\n spinner.text = versionCompare === 0 ? \"Reinstalling files...\" : \"Updating files...\";\n const config = {\n installType: manifest.install_type,\n agent: manifest.agent,\n directory: installDir,\n ides: newConfig?.ides || manifest.ides_setup || [],\n };\n\n await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n } catch (error) {\n spinner.fail(\"Update failed\");\n throw error;\n }\n }\n\n async performRepair(config, installDir, manifest, integrity, spinner) {\n spinner.start(\"Preparing to repair installation...\");\n\n try {\n // Back up modified files\n if (integrity.modified.length > 0) {\n spinner.text = \"Backing up modified files...\";\n for (const file of integrity.modified) {\n const filePath = path.join(installDir, file);\n if (await fileManager.pathExists(filePath)) {\n const backupPath = await fileManager.backupFile(filePath);\n console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));\n }\n }\n }\n\n // Restore missing and modified files\n spinner.text = \"Restoring files...\";\n const sourceBase = resourceLocator.getBmadCorePath();\n const filesToRestore = [...integrity.missing, ...integrity.modified];\n \n for (const file of filesToRestore) {\n // Skip the manifest file itself\n if (file.endsWith('install-manifest.yaml')) continue;\n \n const relativePath = file.replace('.bmad-core/', '');\n const destPath = path.join(installDir, file);\n \n // Check if this is a common/ file that needs special processing\n const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));\n const commonSourcePath = path.join(commonBase, 'common', relativePath);\n \n if (await fileManager.pathExists(commonSourcePath)) {\n // This is a common/ file - needs template processing\n const fs = require('fs').promises;\n const content = await fs.readFile(commonSourcePath, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, '.bmad-core');\n await fileManager.ensureDirectory(path.dirname(destPath));\n await fs.writeFile(destPath, updatedContent, 'utf8');\n spinner.text = `Restored: ${file}`;\n } else {\n // Regular file from bmad-core\n const sourcePath = path.join(sourceBase, relativePath);\n if (await fileManager.pathExists(sourcePath)) {\n await fileManager.copyFile(sourcePath, destPath);\n spinner.text = `Restored: ${file}`;\n \n // If this is a .yaml file, check for and remove corresponding .yml file\n if (file.endsWith('.yaml')) {\n const ymlFile = file.replace(/\\.yaml$/, '.yml');\n const ymlPath = path.join(installDir, ymlFile);\n if (await fileManager.pathExists(ymlPath)) {\n const fs = require('fs').promises;\n await fs.unlink(ymlPath);\n console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${file})`));\n }\n }\n } else {\n console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));\n }\n }\n }\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n \n spinner.succeed(\"Repair completed successfully!\");\n \n // Show summary\n console.log(chalk.green(\"\\nāœ“ Installation repaired!\"));\n if (integrity.missing.length > 0) {\n console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));\n }\n if (integrity.modified.length > 0) {\n console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));\n }\n \n // Warning for Cursor custom modes if agents were repaired\n const ides = manifest.ides_setup || [];\n if (ides.includes('cursor')) {\n console.log(chalk.yellow.bold(\"\\nāš ļø IMPORTANT: Cursor Custom Modes Update Required\"));\n console.log(chalk.yellow(\"Since agent files have been repaired, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs.\"));\n }\n \n } catch (error) {\n spinner.fail(\"Repair failed\");\n throw error;\n }\n }\n\n async performReinstall(config, installDir, spinner) {\n spinner.start(\"Preparing to reinstall BMad Method...\");\n\n // Remove existing .bmad-core\n const bmadCorePath = path.join(installDir, \".bmad-core\");\n if (await fileManager.pathExists(bmadCorePath)) {\n spinner.text = \"Removing existing installation...\";\n await fileManager.removeDirectory(bmadCorePath);\n }\n \n spinner.text = \"Installing fresh copy...\";\n const result = await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });\n \n // Clean up .yml files that now have .yaml counterparts\n spinner.text = \"Cleaning up legacy .yml files...\";\n await this.cleanupLegacyYmlFiles(installDir, spinner);\n \n return result;\n }\n\n showSuccessMessage(config, installDir, options = {}) {\n console.log(chalk.green(\"\\nāœ“ BMad Method installed successfully!\\n\"));\n\n const ides = config.ides || (config.ide ? [config.ide] : []);\n if (ides.length > 0) {\n for (const ide of ides) {\n const ideConfig = configLoader.getIdeConfiguration(ide);\n if (ideConfig?.instructions) {\n console.log(\n chalk.bold(`To use BMad agents in ${ideConfig.name}:`)\n );\n console.log(ideConfig.instructions);\n }\n }\n } else {\n console.log(chalk.yellow(\"No IDE configuration was set up.\"));\n console.log(\n \"You can manually configure your IDE using the agent files in:\",\n installDir\n );\n }\n\n // Information about installation components\n console.log(chalk.bold(\"\\nšŸŽÆ Installation Summary:\"));\n if (config.installType !== \"expansion-only\") {\n console.log(chalk.green(\"āœ“ .bmad-core framework installed with all agents and workflows\"));\n }\n \n if (config.expansionPacks && config.expansionPacks.length > 0) {\n console.log(chalk.green(`āœ“ Expansion packs installed:`));\n for (const packId of config.expansionPacks) {\n console.log(chalk.green(` - ${packId} → .${packId}/`));\n }\n }\n \n if (config.includeWebBundles && config.webBundlesDirectory) {\n const bundleInfo = this.getWebBundleInfo(config);\n // Resolve the web bundles directory for display\n const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();\n const resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory) \n ? config.webBundlesDirectory \n : path.resolve(originalCwd, config.webBundlesDirectory);\n console.log(chalk.green(`āœ“ Web bundles (${bundleInfo}) installed to: ${resolvedWebBundlesDir}`));\n }\n \n if (ides.length > 0) {\n const ideNames = ides.map(ide => {\n const ideConfig = configLoader.getIdeConfiguration(ide);\n return ideConfig?.name || ide;\n }).join(\", \");\n console.log(chalk.green(`āœ“ IDE rules and configurations set up for: ${ideNames}`));\n }\n\n // Information about web bundles\n if (!config.includeWebBundles) {\n console.log(chalk.bold(\"\\nšŸ“¦ Web Bundles Available:\"));\n console.log(\"Pre-built web bundles are available and can be added later:\");\n console.log(chalk.cyan(\" Run the installer again to add them to your project\"));\n console.log(\"These bundles work independently and can be shared, moved, or used\");\n console.log(\"in other projects as standalone files.\");\n }\n\n if (config.installType === \"single-agent\") {\n console.log(\n chalk.dim(\n \"\\nNeed other agents? Run: npx bmad-method install --agent=\"\n )\n );\n console.log(\n chalk.dim(\"Need everything? Run: npx bmad-method install --full\")\n );\n }\n\n // Warning for Cursor custom modes if agents were updated\n if (options.isUpdate && ides.includes('cursor')) {\n console.log(chalk.yellow.bold(\"\\nāš ļø IMPORTANT: Cursor Custom Modes Update Required\"));\n console.log(chalk.yellow(\"Since agents have been updated, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs.\"));\n }\n\n // Important notice to read the user guide\n console.log(chalk.red.bold(\"\\nšŸ“– IMPORTANT: Please read the user guide installed at .bmad-core/user-guide.md\"));\n console.log(chalk.red(\"This guide contains essential information about the BMad workflow and how to use the agents effectively.\"));\n }\n\n // Legacy method for backward compatibility\n async update() {\n console.log(chalk.yellow('The \"update\" command is deprecated.'));\n console.log(\n 'Please use \"install\" instead - it will detect and offer to update existing installations.'\n );\n\n const installDir = await this.findInstallation();\n if (installDir) {\n const config = {\n installType: \"full\",\n directory: path.dirname(installDir),\n ide: null,\n };\n return await this.install(config);\n }\n console.log(chalk.red(\"No BMad installation found.\"));\n }\n\n async listAgents() {\n const agents = await resourceLocator.getAvailableAgents();\n\n console.log(chalk.bold(\"\\nAvailable BMad Agents:\\n\"));\n\n for (const agent of agents) {\n console.log(chalk.cyan(` ${agent.id.padEnd(20)}`), agent.description);\n }\n\n console.log(\n chalk.dim(\"\\nInstall with: npx bmad-method install --agent=\\n\")\n );\n }\n\n async listExpansionPacks() {\n const expansionPacks = await resourceLocator.getExpansionPacks();\n\n console.log(chalk.bold(\"\\nAvailable BMad Expansion Packs:\\n\"));\n\n if (expansionPacks.length === 0) {\n console.log(chalk.yellow(\"No expansion packs found.\"));\n return;\n }\n\n for (const pack of expansionPacks) {\n console.log(chalk.cyan(` ${pack.id.padEnd(20)}`), \n `${pack.name} v${pack.version}`);\n console.log(chalk.dim(` ${' '.repeat(22)}${pack.description}`));\n if (pack.author && pack.author !== 'Unknown') {\n console.log(chalk.dim(` ${' '.repeat(22)}by ${pack.author}`));\n }\n console.log();\n }\n\n console.log(\n chalk.dim(\"Install with: npx bmad-method install --full --expansion-packs \\n\")\n );\n }\n\n async showStatus() {\n const installDir = await this.findInstallation();\n\n if (!installDir) {\n console.log(\n chalk.yellow(\"No BMad installation found in current directory tree\")\n );\n return;\n }\n\n const manifest = await fileManager.readManifest(installDir);\n\n if (!manifest) {\n console.log(chalk.red(\"Invalid installation - manifest not found\"));\n return;\n }\n\n console.log(chalk.bold(\"\\nBMad Installation Status:\\n\"));\n console.log(` Directory: ${installDir}`);\n console.log(` Version: ${manifest.version}`);\n console.log(\n ` Installed: ${new Date(\n manifest.installed_at\n ).toLocaleDateString()}`\n );\n console.log(` Type: ${manifest.install_type}`);\n\n if (manifest.agent) {\n console.log(` Agent: ${manifest.agent}`);\n }\n\n if (manifest.ides_setup && manifest.ides_setup.length > 0) {\n console.log(` IDE Setup: ${manifest.ides_setup.join(', ')}`);\n }\n\n console.log(` Total Files: ${manifest.files.length}`);\n\n // Check for modifications\n const modifiedFiles = await fileManager.checkModifiedFiles(\n installDir,\n manifest\n );\n if (modifiedFiles.length > 0) {\n console.log(chalk.yellow(` Modified Files: ${modifiedFiles.length}`));\n }\n\n console.log(\"\");\n }\n\n async getAvailableAgents() {\n return resourceLocator.getAvailableAgents();\n }\n\n async getAvailableExpansionPacks() {\n return resourceLocator.getExpansionPacks();\n }\n\n async getAvailableTeams() {\n return configLoader.getAvailableTeams();\n }\n\n async installExpansionPacks(installDir, selectedPacks, spinner, config = {}) {\n if (!selectedPacks || selectedPacks.length === 0) {\n return [];\n }\n\n const installedFiles = [];\n\n for (const packId of selectedPacks) {\n spinner.text = `Installing expansion pack: ${packId}...`;\n \n try {\n const expansionPacks = await resourceLocator.getExpansionPacks();\n const pack = expansionPacks.find(p => p.id === packId);\n \n if (!pack) {\n console.warn(`Expansion pack ${packId} not found, skipping...`);\n continue;\n }\n \n // Check if expansion pack already exists\n let expansionDotFolder = path.join(installDir, `.${packId}`);\n const existingManifestPath = path.join(expansionDotFolder, 'install-manifest.yaml');\n \n if (await fileManager.pathExists(existingManifestPath)) {\n spinner.stop();\n const existingManifest = await fileManager.readExpansionPackManifest(installDir, packId);\n \n console.log(chalk.yellow(`\\nšŸ” Found existing ${pack.name} installation`));\n console.log(` Current version: ${existingManifest.version || 'unknown'}`);\n console.log(` New version: ${pack.version}`);\n \n // Check integrity of existing expansion pack\n const packIntegrity = await fileManager.checkFileIntegrity(installDir, existingManifest);\n const hasPackIntegrityIssues = packIntegrity.missing.length > 0 || packIntegrity.modified.length > 0;\n \n if (hasPackIntegrityIssues) {\n console.log(chalk.red(\" āš ļø Installation issues detected:\"));\n if (packIntegrity.missing.length > 0) {\n console.log(chalk.red(` Missing files: ${packIntegrity.missing.length}`));\n }\n if (packIntegrity.modified.length > 0) {\n console.log(chalk.yellow(` Modified files: ${packIntegrity.modified.length}`));\n }\n }\n \n const versionCompare = this.compareVersions(existingManifest.version || '0.0.0', pack.version);\n \n if (versionCompare === 0) {\n console.log(chalk.yellow(' āš ļø Same version already installed'));\n \n const choices = [];\n if (hasPackIntegrityIssues) {\n choices.push({ name: 'Repair (restore missing/modified files)', value: 'repair' });\n }\n choices.push(\n { name: 'Force reinstall (overwrite)', value: 'overwrite' },\n { name: 'Skip this expansion pack', value: 'skip' },\n { name: 'Cancel installation', value: 'cancel' }\n );\n \n const { action } = await inquirer.prompt([{\n type: 'list',\n name: 'action',\n message: `${pack.name} v${pack.version} is already installed. What would you like to do?`,\n choices: choices\n }]);\n \n if (action === 'skip') {\n spinner.start();\n continue;\n } else if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n } else if (action === 'repair') {\n // Repair the expansion pack\n await this.repairExpansionPack(installDir, packId, pack, packIntegrity, spinner);\n continue;\n }\n } else if (versionCompare < 0) {\n console.log(chalk.cyan(' ā¬†ļø Upgrade available'));\n \n const { proceed } = await inquirer.prompt([{\n type: 'confirm',\n name: 'proceed',\n message: `Upgrade ${pack.name} from v${existingManifest.version} to v${pack.version}?`,\n default: true\n }]);\n \n if (!proceed) {\n spinner.start();\n continue;\n }\n } else {\n console.log(chalk.yellow(' ā¬‡ļø Installed version is newer than available version'));\n \n const { action } = await inquirer.prompt([{\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n { name: 'Keep current version', value: 'skip' },\n { name: 'Downgrade to available version', value: 'downgrade' },\n { name: 'Cancel installation', value: 'cancel' }\n ]\n }]);\n \n if (action === 'skip') {\n spinner.start();\n continue;\n } else if (action === 'cancel') {\n console.log('Installation cancelled.');\n process.exit(0);\n }\n }\n \n // If we get here, we're proceeding with installation\n spinner.start(`Removing old ${pack.name} installation...`);\n await fileManager.removeDirectory(expansionDotFolder);\n }\n\n const expansionPackDir = pack.path;\n \n // Ensure dedicated dot folder exists for this expansion pack\n expansionDotFolder = path.join(installDir, `.${packId}`);\n await fileManager.ensureDirectory(expansionDotFolder);\n \n // Define the folders to copy from expansion packs\n const foldersToSync = [\n 'agents',\n 'agent-teams',\n 'templates',\n 'tasks',\n 'checklists',\n 'workflows',\n 'data',\n 'utils',\n 'schemas'\n ];\n\n // Copy each folder if it exists\n for (const folder of foldersToSync) {\n const sourceFolder = path.join(expansionPackDir, folder);\n \n // Check if folder exists in expansion pack\n if (await fileManager.pathExists(sourceFolder)) {\n // Get all files in this folder\n const files = await resourceLocator.findFiles('**/*', {\n cwd: sourceFolder,\n nodir: true\n });\n\n // Copy each file to the expansion pack's dot folder with {root} replacement\n for (const file of files) {\n const sourcePath = path.join(sourceFolder, file);\n const destPath = path.join(expansionDotFolder, folder, file);\n \n const needsRootReplacement = file.endsWith('.md') || file.endsWith('.yaml') || file.endsWith('.yml');\n let success = false;\n \n if (needsRootReplacement) {\n success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, `.${packId}`);\n } else {\n success = await fileManager.copyFile(sourcePath, destPath);\n }\n \n if (success) {\n installedFiles.push(path.join(`.${packId}`, folder, file));\n }\n }\n }\n }\n\n // Copy config.yaml with {root} replacement\n const configPath = path.join(expansionPackDir, 'config.yaml');\n if (await fileManager.pathExists(configPath)) {\n const configDestPath = path.join(expansionDotFolder, 'config.yaml');\n if (await fileManager.copyFileWithRootReplacement(configPath, configDestPath, `.${packId}`)) {\n installedFiles.push(path.join(`.${packId}`, 'config.yaml'));\n }\n }\n \n // Copy README if it exists with {root} replacement\n const readmePath = path.join(expansionPackDir, 'README.md');\n if (await fileManager.pathExists(readmePath)) {\n const readmeDestPath = path.join(expansionDotFolder, 'README.md');\n if (await fileManager.copyFileWithRootReplacement(readmePath, readmeDestPath, `.${packId}`)) {\n installedFiles.push(path.join(`.${packId}`, 'README.md'));\n }\n }\n\n // Copy common/ items to expansion pack folder\n spinner.text = `Copying common utilities to ${packId}...`;\n await this.copyCommonItems(installDir, `.${packId}`, spinner);\n \n // Check and resolve core dependencies\n await this.resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner);\n \n // Check and resolve core agents referenced by teams\n await this.resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner);\n\n // Create manifest for this expansion pack\n spinner.text = `Creating manifest for ${packId}...`;\n const expansionConfig = {\n installType: 'expansion-pack',\n expansionPackId: packId,\n expansionPackName: pack.name,\n expansionPackVersion: pack.version,\n ides: config.ides || [] // Use ides_setup instead of ide_setup\n };\n \n // Get all files installed in this expansion pack\n const foundFiles = await resourceLocator.findFiles('**/*', {\n cwd: expansionDotFolder,\n nodir: true\n });\n const expansionPackFiles = foundFiles.map(f => path.join(`.${packId}`, f));\n \n await fileManager.createExpansionPackManifest(installDir, packId, expansionConfig, expansionPackFiles);\n\n console.log(chalk.green(`āœ“ Installed expansion pack: ${pack.name} to ${`.${packId}`}`));\n } catch (error) {\n console.error(`Failed to install expansion pack ${packId}: ${error.message}`);\n console.error(`Stack trace: ${error.stack}`);\n }\n }\n\n return installedFiles;\n }\n\n async resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner) {\n const yaml = require('js-yaml');\n const fs = require('fs').promises;\n \n // Find all agent files in the expansion pack\n const agentFiles = await resourceLocator.findFiles('agents/*.md', {\n cwd: expansionDotFolder\n });\n\n for (const agentFile of agentFiles) {\n const agentPath = path.join(expansionDotFolder, agentFile);\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML frontmatter to check dependencies\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n try {\n const agentConfig = yaml.load(yamlContent);\n const dependencies = agentConfig.dependencies || {};\n \n // Check for core dependencies (those that don't exist in the expansion pack)\n for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {\n const deps = dependencies[depType] || [];\n \n for (const dep of deps) {\n const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep : \n (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);\n const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);\n \n // Check if dependency exists in expansion pack dot folder\n if (!(await fileManager.pathExists(expansionDepPath))) {\n // Try to find it in expansion pack source\n const sourceDepPath = path.join(pack.path, depType, depFileName);\n \n if (await fileManager.pathExists(sourceDepPath)) {\n // Copy from expansion pack source\n spinner.text = `Copying ${packId} dependency ${dep}...`;\n const destPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(sourceDepPath, destPath, `.${packId}`);\n console.log(chalk.dim(` Added ${packId} dependency: ${depType}/${depFileName}`));\n } else {\n // Try to find it in core\n const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);\n \n if (await fileManager.pathExists(coreDepPath)) {\n spinner.text = `Copying core dependency ${dep} for ${packId}...`;\n \n // Copy from core to expansion pack dot folder with {root} replacement\n const destPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(coreDepPath, destPath, `.${packId}`);\n \n console.log(chalk.dim(` Added core dependency: ${depType}/${depFileName}`));\n } else {\n console.warn(chalk.yellow(` Warning: Dependency ${depType}/${dep} not found in core or expansion pack`));\n }\n }\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse agent dependencies: ${error.message}`);\n }\n }\n }\n }\n\n async resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner) {\n const yaml = require('js-yaml');\n const fs = require('fs').promises;\n \n // Find all team files in the expansion pack\n const teamFiles = await resourceLocator.findFiles('agent-teams/*.yaml', {\n cwd: expansionDotFolder\n });\n\n // Also get existing agents in the expansion pack\n const existingAgents = new Set();\n const agentFiles = await resourceLocator.findFiles('agents/*.md', {\n cwd: expansionDotFolder\n });\n for (const agentFile of agentFiles) {\n const agentName = path.basename(agentFile, '.md');\n existingAgents.add(agentName);\n }\n\n // Process each team file\n for (const teamFile of teamFiles) {\n const teamPath = path.join(expansionDotFolder, teamFile);\n const teamContent = await fs.readFile(teamPath, 'utf8');\n \n try {\n const teamConfig = yaml.load(teamContent);\n const agents = teamConfig.agents || [];\n \n // Add bmad-orchestrator if not present (required for all teams)\n if (!agents.includes('bmad-orchestrator')) {\n agents.unshift('bmad-orchestrator');\n }\n \n // Check each agent in the team\n for (const agentId of agents) {\n if (!existingAgents.has(agentId)) {\n // Agent not in expansion pack, try to get from core\n const coreAgentPath = path.join(resourceLocator.getBmadCorePath(), 'agents', `${agentId}.md`);\n \n if (await fileManager.pathExists(coreAgentPath)) {\n spinner.text = `Copying core agent ${agentId} for ${packId}...`;\n \n // Copy agent file with {root} replacement\n const destPath = path.join(expansionDotFolder, 'agents', `${agentId}.md`);\n await fileManager.copyFileWithRootReplacement(coreAgentPath, destPath, `.${packId}`);\n existingAgents.add(agentId);\n \n console.log(chalk.dim(` Added core agent: ${agentId}`));\n \n // Now resolve this agent's dependencies too\n const agentContent = await fs.readFile(coreAgentPath, 'utf8');\n const yamlContent = extractYamlFromAgent(agentContent, true);\n \n if (yamlContent) {\n try {\n \n const agentConfig = yaml.load(yamlContent);\n const dependencies = agentConfig.dependencies || {};\n \n // Copy all dependencies for this agent\n for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {\n const deps = dependencies[depType] || [];\n \n for (const dep of deps) {\n const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep : \n (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);\n const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);\n \n // Check if dependency exists in expansion pack\n if (!(await fileManager.pathExists(expansionDepPath))) {\n // Try to find it in core\n const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);\n \n if (await fileManager.pathExists(coreDepPath)) {\n const destDepPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFileWithRootReplacement(coreDepPath, destDepPath, `.${packId}`);\n console.log(chalk.dim(` Added agent dependency: ${depType}/${depFileName}`));\n } else {\n // Try common folder\n const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root\n const commonDepPath = path.join(sourceBase, 'common', depType, depFileName);\n if (await fileManager.pathExists(commonDepPath)) {\n const destDepPath = path.join(expansionDotFolder, depType, depFileName);\n await fileManager.copyFile(commonDepPath, destDepPath);\n console.log(chalk.dim(` Added agent dependency from common: ${depType}/${depFileName}`));\n }\n }\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse agent ${agentId} dependencies: ${error.message}`);\n }\n }\n } else {\n console.warn(chalk.yellow(` Warning: Core agent ${agentId} not found for team ${path.basename(teamFile, '.yaml')}`));\n }\n }\n }\n } catch (error) {\n console.warn(` Warning: Could not parse team file ${teamFile}: ${error.message}`);\n }\n }\n }\n\n getWebBundleInfo(config) {\n const webBundleType = config.webBundleType || 'all';\n \n switch (webBundleType) {\n case 'all':\n return 'all bundles';\n case 'agents':\n return 'individual agents only';\n case 'teams':\n return config.selectedWebBundleTeams ? \n `teams: ${config.selectedWebBundleTeams.join(', ')}` : \n 'selected teams';\n case 'custom':\n const parts = [];\n if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {\n parts.push(`teams: ${config.selectedWebBundleTeams.join(', ')}`);\n }\n if (config.includeIndividualAgents) {\n parts.push('individual agents');\n }\n return parts.length > 0 ? parts.join(' + ') : 'custom selection';\n default:\n return 'selected bundles';\n }\n }\n\n async installWebBundles(webBundlesDirectory, config, spinner) {\n \n try {\n // Find the dist directory in the BMad installation\n const distDir = configLoader.getDistPath();\n \n if (!(await fileManager.pathExists(distDir))) {\n console.warn('Web bundles not found. Run \"npm run build\" to generate them.');\n return;\n }\n\n // Ensure web bundles directory exists\n await fileManager.ensureDirectory(webBundlesDirectory);\n \n const webBundleType = config.webBundleType || 'all';\n \n if (webBundleType === 'all') {\n // Copy the entire dist directory structure\n await fileManager.copyDirectory(distDir, webBundlesDirectory);\n console.log(chalk.green(`āœ“ Installed all web bundles to: ${webBundlesDirectory}`));\n } else {\n let copiedCount = 0;\n \n // Copy specific selections based on type\n if (webBundleType === 'agents' || (webBundleType === 'custom' && config.includeIndividualAgents)) {\n const agentsSource = path.join(distDir, 'agents');\n const agentsTarget = path.join(webBundlesDirectory, 'agents');\n if (await fileManager.pathExists(agentsSource)) {\n await fileManager.copyDirectory(agentsSource, agentsTarget);\n console.log(chalk.green(`āœ“ Copied individual agent bundles`));\n copiedCount += 10; // Approximate count for agents\n }\n }\n \n if (webBundleType === 'teams' || webBundleType === 'custom') {\n if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {\n const teamsSource = path.join(distDir, 'teams');\n const teamsTarget = path.join(webBundlesDirectory, 'teams');\n await fileManager.ensureDirectory(teamsTarget);\n \n for (const teamId of config.selectedWebBundleTeams) {\n const teamFile = `${teamId}.txt`;\n const sourcePath = path.join(teamsSource, teamFile);\n const targetPath = path.join(teamsTarget, teamFile);\n \n if (await fileManager.pathExists(sourcePath)) {\n await fileManager.copyFile(sourcePath, targetPath);\n copiedCount++;\n console.log(chalk.green(`āœ“ Copied team bundle: ${teamId}`));\n }\n }\n }\n }\n \n // Always copy expansion packs if they exist\n const expansionSource = path.join(distDir, 'expansion-packs');\n const expansionTarget = path.join(webBundlesDirectory, 'expansion-packs');\n if (await fileManager.pathExists(expansionSource)) {\n await fileManager.copyDirectory(expansionSource, expansionTarget);\n console.log(chalk.green(`āœ“ Copied expansion pack bundles`));\n }\n \n console.log(chalk.green(`āœ“ Installed ${copiedCount} selected web bundles to: ${webBundlesDirectory}`));\n }\n } catch (error) {\n console.error(`Failed to install web bundles: ${error.message}`);\n }\n }\n\n async copyCommonItems(installDir, targetSubdir, spinner) {\n \n const fs = require('fs').promises;\n const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root\n const commonPath = path.join(sourceBase, 'common');\n const targetPath = path.join(installDir, targetSubdir);\n const copiedFiles = [];\n \n // Check if common/ exists\n if (!(await fileManager.pathExists(commonPath))) {\n console.warn('Warning: common/ folder not found');\n return copiedFiles;\n }\n \n // Copy all items from common/ to target\n const commonItems = await resourceLocator.findFiles('**/*', {\n cwd: commonPath,\n nodir: true\n });\n \n for (const item of commonItems) {\n const sourcePath = path.join(commonPath, item);\n const destPath = path.join(targetPath, item);\n \n // Read the file content\n const content = await fs.readFile(sourcePath, 'utf8');\n \n // Replace {root} with the target subdirectory\n const updatedContent = content.replace(/\\{root\\}/g, targetSubdir);\n \n // Ensure directory exists\n await fileManager.ensureDirectory(path.dirname(destPath));\n \n // Write the updated content\n await fs.writeFile(destPath, updatedContent, 'utf8');\n copiedFiles.push(path.join(targetSubdir, item));\n }\n \n console.log(chalk.dim(` Added ${commonItems.length} common utilities`));\n return copiedFiles;\n }\n\n async detectExpansionPacks(installDir) {\n const expansionPacks = {};\n const glob = require(\"glob\");\n \n // Find all dot folders that might be expansion packs\n const dotFolders = glob.sync(\".*\", {\n cwd: installDir,\n ignore: [\".git\", \".git/**\", \".bmad-core\", \".bmad-core/**\"],\n });\n \n for (const folder of dotFolders) {\n const folderPath = path.join(installDir, folder);\n const stats = await fileManager.pathExists(folderPath);\n \n if (stats) {\n // Check if it has a manifest\n const manifestPath = path.join(folderPath, \"install-manifest.yaml\");\n if (await fileManager.pathExists(manifestPath)) {\n const manifest = await fileManager.readExpansionPackManifest(installDir, folder.substring(1));\n if (manifest) {\n expansionPacks[folder.substring(1)] = {\n path: folderPath,\n manifest: manifest,\n hasManifest: true\n };\n }\n } else {\n // Check if it has a config.yaml (expansion pack without manifest)\n const configPath = path.join(folderPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n expansionPacks[folder.substring(1)] = {\n path: folderPath,\n manifest: null,\n hasManifest: false\n };\n }\n }\n }\n }\n \n return expansionPacks;\n }\n\n async repairExpansionPack(installDir, packId, pack, integrity, spinner) {\n spinner.start(`Repairing ${pack.name}...`);\n \n try {\n const expansionDotFolder = path.join(installDir, `.${packId}`);\n \n // Back up modified files\n if (integrity.modified.length > 0) {\n spinner.text = \"Backing up modified files...\";\n for (const file of integrity.modified) {\n const filePath = path.join(installDir, file);\n if (await fileManager.pathExists(filePath)) {\n const backupPath = await fileManager.backupFile(filePath);\n console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));\n }\n }\n }\n \n // Restore missing and modified files\n spinner.text = \"Restoring files...\";\n const filesToRestore = [...integrity.missing, ...integrity.modified];\n \n for (const file of filesToRestore) {\n // Skip the manifest file itself\n if (file.endsWith('install-manifest.yaml')) continue;\n \n const relativePath = file.replace(`.${packId}/`, '');\n const sourcePath = path.join(pack.path, relativePath);\n const destPath = path.join(installDir, file);\n \n // Check if this is a common/ file that needs special processing\n const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));\n const commonSourcePath = path.join(commonBase, 'common', relativePath);\n \n if (await fileManager.pathExists(commonSourcePath)) {\n // This is a common/ file - needs template processing\n const fs = require('fs').promises;\n const content = await fs.readFile(commonSourcePath, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, `.${packId}`);\n await fileManager.ensureDirectory(path.dirname(destPath));\n await fs.writeFile(destPath, updatedContent, 'utf8');\n spinner.text = `Restored: ${file}`;\n } else if (await fileManager.pathExists(sourcePath)) {\n // Regular file from expansion pack\n await fileManager.copyFile(sourcePath, destPath);\n spinner.text = `Restored: ${file}`;\n } else {\n console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));\n }\n }\n \n spinner.succeed(`${pack.name} repaired successfully!`);\n \n // Show summary\n console.log(chalk.green(`\\nāœ“ ${pack.name} repaired!`));\n if (integrity.missing.length > 0) {\n console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));\n }\n if (integrity.modified.length > 0) {\n console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));\n }\n \n } catch (error) {\n if (spinner) spinner.fail(`Failed to repair ${pack.name}`);\n console.error(`Error: ${error.message}`);\n }\n }\n\n compareVersions(v1, v2) {\n // Simple semver comparison\n const parts1 = v1.split('.').map(Number);\n const parts2 = v2.split('.').map(Number);\n \n for (let i = 0; i < 3; i++) {\n const part1 = parts1[i] || 0;\n const part2 = parts2[i] || 0;\n \n if (part1 > part2) return 1;\n if (part1 < part2) return -1;\n }\n \n return 0;\n }\n\n async cleanupLegacyYmlFiles(installDir, spinner) {\n const glob = require('glob');\n const fs = require('fs').promises;\n \n try {\n // Find all .yml files in the installation directory\n const ymlFiles = glob.sync('**/*.yml', {\n cwd: installDir,\n ignore: ['**/node_modules/**', '**/.git/**']\n });\n \n let deletedCount = 0;\n \n for (const ymlFile of ymlFiles) {\n // Check if corresponding .yaml file exists\n const yamlFile = ymlFile.replace(/\\.yml$/, '.yaml');\n const ymlPath = path.join(installDir, ymlFile);\n const yamlPath = path.join(installDir, yamlFile);\n \n if (await fileManager.pathExists(yamlPath)) {\n // .yaml counterpart exists, delete the .yml file\n await fs.unlink(ymlPath);\n deletedCount++;\n console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${yamlFile})`));\n }\n }\n \n if (deletedCount > 0) {\n console.log(chalk.green(`āœ“ Cleaned up ${deletedCount} legacy .yml files`));\n }\n \n } catch (error) {\n console.warn(`Warning: Could not cleanup legacy .yml files: ${error.message}`);\n }\n }\n\n async findInstallation() {\n // Look for .bmad-core in current directory or parent directories\n let currentDir = process.cwd();\n\n while (currentDir !== path.dirname(currentDir)) {\n const bmadDir = path.join(currentDir, \".bmad-core\");\n const manifestPath = path.join(bmadDir, \"install-manifest.yaml\");\n\n if (await fileManager.pathExists(manifestPath)) {\n return bmadDir;\n }\n\n currentDir = path.dirname(currentDir);\n }\n\n // Also check if we're inside a .bmad-core directory\n if (path.basename(process.cwd()) === \".bmad-core\") {\n const manifestPath = path.join(process.cwd(), \"install-manifest.yaml\");\n if (await fileManager.pathExists(manifestPath)) {\n return process.cwd();\n }\n }\n\n return null;\n }\n}\n\nmodule.exports = new Installer();\n"], ["/BMAD-METHOD/tools/installer/lib/ide-setup.js", "const path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst inquirer = require(\"inquirer\");\nconst fileManager = require(\"./file-manager\");\nconst configLoader = require(\"./config-loader\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\nconst BaseIdeSetup = require(\"./ide-base-setup\");\nconst resourceLocator = require(\"./resource-locator\");\n\nclass IdeSetup extends BaseIdeSetup {\n constructor() {\n super();\n this.ideAgentConfig = null;\n }\n\n async loadIdeAgentConfig() {\n if (this.ideAgentConfig) return this.ideAgentConfig;\n \n try {\n const configPath = path.join(__dirname, '..', 'config', 'ide-agent-config.yaml');\n const configContent = await fs.readFile(configPath, 'utf8');\n this.ideAgentConfig = yaml.load(configContent);\n return this.ideAgentConfig;\n } catch (error) {\n console.warn('Failed to load IDE agent configuration, using defaults');\n return {\n 'roo-permissions': {},\n 'cline-order': {}\n };\n }\n }\n\n async setup(ide, installDir, selectedAgent = null, spinner = null, preConfiguredSettings = null) {\n const ideConfig = await configLoader.getIdeConfiguration(ide);\n\n if (!ideConfig) {\n console.log(chalk.yellow(`\\nNo configuration available for ${ide}`));\n return false;\n }\n\n switch (ide) {\n case \"cursor\":\n return this.setupCursor(installDir, selectedAgent);\n case \"claude-code\":\n return this.setupClaudeCode(installDir, selectedAgent);\n case \"windsurf\":\n return this.setupWindsurf(installDir, selectedAgent);\n case \"trae\":\n return this.setupTrae(installDir, selectedAgent);\n case \"roo\":\n return this.setupRoo(installDir, selectedAgent);\n case \"cline\":\n return this.setupCline(installDir, selectedAgent);\n case \"gemini\":\n return this.setupGeminiCli(installDir, selectedAgent);\n case \"github-copilot\":\n return this.setupGitHubCopilot(installDir, selectedAgent, spinner, preConfiguredSettings);\n default:\n console.log(chalk.yellow(`\\nIDE ${ide} not yet supported`));\n return false;\n }\n }\n\n async setupCursor(installDir, selectedAgent) {\n const cursorRulesDir = path.join(installDir, \".cursor\", \"rules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(cursorRulesDir);\n\n for (const agentId of agents) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const mdcContent = await this.createAgentRuleContent(agentId, agentPath, installDir, 'mdc');\n const mdcPath = path.join(cursorRulesDir, `${agentId}.mdc`);\n await fileManager.writeFile(mdcPath, mdcContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.mdc`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Cursor rules in ${cursorRulesDir}`));\n return true;\n }\n\n async setupClaudeCode(installDir, selectedAgent) {\n // Setup bmad-core commands\n const coreSlashPrefix = await this.getCoreSlashPrefix(installDir);\n const coreAgents = selectedAgent ? [selectedAgent] : await this.getCoreAgentIds(installDir);\n const coreTasks = await this.getCoreTaskIds(installDir);\n await this.setupClaudeCodeForPackage(installDir, \"core\", coreSlashPrefix, coreAgents, coreTasks, \".bmad-core\");\n\n // Setup expansion pack commands\n const expansionPacks = await this.getInstalledExpansionPacks(installDir);\n for (const packInfo of expansionPacks) {\n const packSlashPrefix = await this.getExpansionPackSlashPrefix(packInfo.path);\n const packAgents = await this.getExpansionPackAgents(packInfo.path);\n const packTasks = await this.getExpansionPackTasks(packInfo.path);\n \n if (packAgents.length > 0 || packTasks.length > 0) {\n // Use the actual directory name where the expansion pack is installed\n const rootPath = path.relative(installDir, packInfo.path);\n await this.setupClaudeCodeForPackage(installDir, packInfo.name, packSlashPrefix, packAgents, packTasks, rootPath);\n }\n }\n\n return true;\n }\n\n async setupClaudeCodeForPackage(installDir, packageName, slashPrefix, agentIds, taskIds, rootPath) {\n const commandsBaseDir = path.join(installDir, \".claude\", \"commands\", slashPrefix);\n const agentsDir = path.join(commandsBaseDir, \"agents\");\n const tasksDir = path.join(commandsBaseDir, \"tasks\");\n\n // Ensure directories exist\n await fileManager.ensureDirectory(agentsDir);\n await fileManager.ensureDirectory(tasksDir);\n\n // Setup agents\n for (const agentId of agentIds) {\n // Find the agent file - for expansion packs, prefer the expansion pack version\n let agentPath;\n if (packageName !== \"core\") {\n // For expansion packs, first try to find the agent in the expansion pack directory\n const expansionPackPath = path.join(installDir, rootPath, \"agents\", `${agentId}.md`);\n if (await fileManager.pathExists(expansionPackPath)) {\n agentPath = expansionPackPath;\n } else {\n // Fall back to core if not found in expansion pack\n agentPath = await this.findAgentPath(agentId, installDir);\n }\n } else {\n // For core, use the normal search\n agentPath = await this.findAgentPath(agentId, installDir);\n }\n \n const commandPath = path.join(agentsDir, `${agentId}.md`);\n\n if (agentPath) {\n // Create command file with agent content\n let agentContent = await fileManager.readFile(agentPath);\n \n // Replace {root} placeholder with the appropriate root path for this context\n agentContent = agentContent.replace(/{root}/g, rootPath);\n\n // Add command header\n let commandContent = `# /${agentId} Command\\n\\n`;\n commandContent += `When this command is used, adopt the following agent persona:\\n\\n`;\n commandContent += agentContent;\n\n await fileManager.writeFile(commandPath, commandContent);\n console.log(chalk.green(`āœ“ Created agent command: /${agentId}`));\n }\n }\n\n // Setup tasks\n for (const taskId of taskIds) {\n // Find the task file - for expansion packs, prefer the expansion pack version\n let taskPath;\n if (packageName !== \"core\") {\n // For expansion packs, first try to find the task in the expansion pack directory\n const expansionPackPath = path.join(installDir, rootPath, \"tasks\", `${taskId}.md`);\n if (await fileManager.pathExists(expansionPackPath)) {\n taskPath = expansionPackPath;\n } else {\n // Fall back to core if not found in expansion pack\n taskPath = await this.findTaskPath(taskId, installDir);\n }\n } else {\n // For core, use the normal search\n taskPath = await this.findTaskPath(taskId, installDir);\n }\n \n const commandPath = path.join(tasksDir, `${taskId}.md`);\n\n if (taskPath) {\n // Create command file with task content\n let taskContent = await fileManager.readFile(taskPath);\n \n // Replace {root} placeholder with the appropriate root path for this context\n taskContent = taskContent.replace(/{root}/g, rootPath);\n\n // Add command header\n let commandContent = `# /${taskId} Task\\n\\n`;\n commandContent += `When this command is used, execute the following task:\\n\\n`;\n commandContent += taskContent;\n\n await fileManager.writeFile(commandPath, commandContent);\n console.log(chalk.green(`āœ“ Created task command: /${taskId}`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Claude Code commands for ${packageName} in ${commandsBaseDir}`));\n console.log(chalk.dim(` - Agents in: ${agentsDir}`));\n console.log(chalk.dim(` - Tasks in: ${tasksDir}`));\n }\n\n async setupWindsurf(installDir, selectedAgent) {\n const windsurfRulesDir = path.join(installDir, \".windsurf\", \"rules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(windsurfRulesDir);\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n const mdPath = path.join(windsurfRulesDir, `${agentId}.md`);\n\n // Create MD content (similar to Cursor but without frontmatter)\n let mdContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n mdContent += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n mdContent += \"## Agent Activation\\n\\n\";\n mdContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n } else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `When the user types \\`@${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n\n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Windsurf rules in ${windsurfRulesDir}`));\n\n return true;\n }\n\n async setupTrae(installDir, selectedAgent) {\n const traeRulesDir = path.join(installDir, \".trae\", \"rules\");\n const agents = selectedAgent? [selectedAgent] : await this.getAllAgentIds(installDir);\n \n await fileManager.ensureDirectory(traeRulesDir);\n \n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n \n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n const mdPath = path.join(traeRulesDir, `${agentId}.md`);\n \n // Create MD content (similar to Cursor but without frontmatter)\n let mdContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n mdContent += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n mdContent += \"## Agent Activation\\n\\n\";\n mdContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n }\n else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `When the user types \\`@${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n \n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${agentId}.md`));\n }\n }\n }\n\n async findAgentPath(agentId, installDir) {\n // Try to find the agent file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"agents\", `${agentId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${agentId}.md`));\n }\n \n for (const agentPath of possiblePaths) {\n if (await fileManager.pathExists(agentPath)) {\n return agentPath;\n }\n }\n \n return null;\n }\n\n async getAllAgentIds(installDir) {\n const glob = require(\"glob\");\n const allAgentIds = [];\n \n // Check core agents in .bmad-core or root\n let agentsDir = path.join(installDir, \".bmad-core\", \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n agentsDir = path.join(installDir, \"agents\");\n }\n \n if (await fileManager.pathExists(agentsDir)) {\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n allAgentIds.push(...agentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Also check for expansion pack agents in dot folders\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n const fullExpDir = path.join(installDir, expDir);\n const expAgentFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allAgentIds.push(...expAgentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Remove duplicates\n return [...new Set(allAgentIds)];\n }\n\n async getCoreAgentIds(installDir) {\n const allAgentIds = [];\n \n // Check core agents in .bmad-core or root only\n let agentsDir = path.join(installDir, \".bmad-core\", \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n agentsDir = path.join(installDir, \"bmad-core\", \"agents\");\n }\n \n if (await fileManager.pathExists(agentsDir)) {\n const glob = require(\"glob\");\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n allAgentIds.push(...agentFiles.map((file) => path.basename(file, \".md\")));\n }\n \n return [...new Set(allAgentIds)];\n }\n\n async getCoreTaskIds(installDir) {\n const allTaskIds = [];\n \n // Check core tasks in .bmad-core or root only\n let tasksDir = path.join(installDir, \".bmad-core\", \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n tasksDir = path.join(installDir, \"bmad-core\", \"tasks\");\n }\n \n if (await fileManager.pathExists(tasksDir)) {\n const glob = require(\"glob\");\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n allTaskIds.push(...taskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check common tasks\n const commonTasksDir = path.join(installDir, \"common\", \"tasks\");\n if (await fileManager.pathExists(commonTasksDir)) {\n const commonTaskFiles = glob.sync(\"*.md\", { cwd: commonTasksDir });\n allTaskIds.push(...commonTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n return [...new Set(allTaskIds)];\n }\n\n async getAgentTitle(agentId, installDir) {\n // Try to find the agent file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"agents\", `${agentId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n const expansionDirs = glob.sync(\".*/agents\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${agentId}.md`));\n }\n \n for (const agentPath of possiblePaths) {\n if (await fileManager.pathExists(agentPath)) {\n try {\n const agentContent = await fileManager.readFile(agentPath);\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n \n if (yamlMatch) {\n const yaml = yamlMatch[1];\n const titleMatch = yaml.match(/title:\\s*(.+)/);\n if (titleMatch) {\n return titleMatch[1].trim();\n }\n }\n } catch (error) {\n console.warn(`Failed to read agent title for ${agentId}: ${error.message}`);\n }\n }\n }\n \n // Fallback to formatted agent ID\n return agentId.split('-').map(word => \n word.charAt(0).toUpperCase() + word.slice(1)\n ).join(' ');\n }\n\n async getAllTaskIds(installDir) {\n const glob = require(\"glob\");\n const allTaskIds = [];\n \n // Check core tasks in .bmad-core or root\n let tasksDir = path.join(installDir, \".bmad-core\", \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n tasksDir = path.join(installDir, \"bmad-core\", \"tasks\");\n }\n \n if (await fileManager.pathExists(tasksDir)) {\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n allTaskIds.push(...taskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check common tasks\n const commonTasksDir = path.join(installDir, \"common\", \"tasks\");\n if (await fileManager.pathExists(commonTasksDir)) {\n const commonTaskFiles = glob.sync(\"*.md\", { cwd: commonTasksDir });\n allTaskIds.push(...commonTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Also check for expansion pack tasks in dot folders\n const expansionDirs = glob.sync(\".*/tasks\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n const fullExpDir = path.join(installDir, expDir);\n const expTaskFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allTaskIds.push(...expTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n \n // Check expansion-packs folder tasks\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const expPackDirs = glob.sync(\"*/tasks\", { cwd: expansionPacksDir });\n for (const expDir of expPackDirs) {\n const fullExpDir = path.join(expansionPacksDir, expDir);\n const expTaskFiles = glob.sync(\"*.md\", { cwd: fullExpDir });\n allTaskIds.push(...expTaskFiles.map((file) => path.basename(file, \".md\")));\n }\n }\n \n // Remove duplicates\n return [...new Set(allTaskIds)];\n }\n\n async findTaskPath(taskId, installDir) {\n // Try to find the task file in various locations\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"tasks\", `${taskId}.md`),\n path.join(installDir, \"bmad-core\", \"tasks\", `${taskId}.md`),\n path.join(installDir, \"common\", \"tasks\", `${taskId}.md`)\n ];\n \n // Also check expansion pack directories\n const glob = require(\"glob\");\n \n // Check dot folder expansion packs\n const expansionDirs = glob.sync(\".*/tasks\", { cwd: installDir });\n for (const expDir of expansionDirs) {\n possiblePaths.push(path.join(installDir, expDir, `${taskId}.md`));\n }\n \n // Check expansion-packs folder\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const expPackDirs = glob.sync(\"*/tasks\", { cwd: expansionPacksDir });\n for (const expDir of expPackDirs) {\n possiblePaths.push(path.join(expansionPacksDir, expDir, `${taskId}.md`));\n }\n }\n \n for (const taskPath of possiblePaths) {\n if (await fileManager.pathExists(taskPath)) {\n return taskPath;\n }\n }\n \n return null;\n }\n\n async getCoreSlashPrefix(installDir) {\n try {\n const coreConfigPath = path.join(installDir, \".bmad-core\", \"core-config.yaml\");\n if (!(await fileManager.pathExists(coreConfigPath))) {\n // Try bmad-core directory\n const altConfigPath = path.join(installDir, \"bmad-core\", \"core-config.yaml\");\n if (await fileManager.pathExists(altConfigPath)) {\n const configContent = await fileManager.readFile(altConfigPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || \"BMad\";\n }\n return \"BMad\"; // fallback\n }\n \n const configContent = await fileManager.readFile(coreConfigPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || \"BMad\";\n } catch (error) {\n console.warn(`Failed to read core slashPrefix, using default 'BMad': ${error.message}`);\n return \"BMad\";\n }\n }\n\n async getInstalledExpansionPacks(installDir) {\n const expansionPacks = [];\n \n // Check for dot-prefixed expansion packs in install directory\n const glob = require(\"glob\");\n const dotExpansions = glob.sync(\".bmad-*\", { cwd: installDir });\n \n for (const dotExpansion of dotExpansions) {\n if (dotExpansion !== \".bmad-core\") {\n const packPath = path.join(installDir, dotExpansion);\n const packName = dotExpansion.substring(1); // remove the dot\n expansionPacks.push({\n name: packName,\n path: packPath\n });\n }\n }\n \n // Check for expansion-packs directory style\n const expansionPacksDir = path.join(installDir, \"expansion-packs\");\n if (await fileManager.pathExists(expansionPacksDir)) {\n const packDirs = glob.sync(\"*\", { cwd: expansionPacksDir });\n \n for (const packDir of packDirs) {\n const packPath = path.join(expansionPacksDir, packDir);\n if ((await fileManager.pathExists(packPath)) && \n (await fileManager.pathExists(path.join(packPath, \"config.yaml\")))) {\n expansionPacks.push({\n name: packDir,\n path: packPath\n });\n }\n }\n }\n \n return expansionPacks;\n }\n\n async getExpansionPackSlashPrefix(packPath) {\n try {\n const configPath = path.join(packPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n const configContent = await fileManager.readFile(configPath);\n const config = yaml.load(configContent);\n return config.slashPrefix || path.basename(packPath);\n }\n } catch (error) {\n console.warn(`Failed to read expansion pack slashPrefix from ${packPath}: ${error.message}`);\n }\n \n return path.basename(packPath); // fallback to directory name\n }\n\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n return [];\n }\n \n try {\n const glob = require(\"glob\");\n const agentFiles = glob.sync(\"*.md\", { cwd: agentsDir });\n return agentFiles.map(file => path.basename(file, \".md\"));\n } catch (error) {\n console.warn(`Failed to read expansion pack agents from ${packPath}: ${error.message}`);\n return [];\n }\n }\n\n async getExpansionPackTasks(packPath) {\n const tasksDir = path.join(packPath, \"tasks\");\n if (!(await fileManager.pathExists(tasksDir))) {\n return [];\n }\n \n try {\n const glob = require(\"glob\");\n const taskFiles = glob.sync(\"*.md\", { cwd: tasksDir });\n return taskFiles.map(file => path.basename(file, \".md\"));\n } catch (error) {\n console.warn(`Failed to read expansion pack tasks from ${packPath}: ${error.message}`);\n return [];\n }\n }\n\n async setupRoo(installDir, selectedAgent) {\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n // Check for existing .roomodes file in project root\n const roomodesPath = path.join(installDir, \".roomodes\");\n let existingModes = [];\n let existingContent = \"\";\n\n if (await fileManager.pathExists(roomodesPath)) {\n existingContent = await fileManager.readFile(roomodesPath);\n // Parse existing modes to avoid duplicates\n const modeMatches = existingContent.matchAll(/- slug: ([\\w-]+)/g);\n for (const match of modeMatches) {\n existingModes.push(match[1]);\n }\n console.log(chalk.yellow(`Found existing .roomodes file with ${existingModes.length} modes`));\n }\n\n // Create new modes content\n let newModesContent = \"\";\n\n // Load dynamic agent permissions from configuration\n const config = await this.loadIdeAgentConfig();\n const agentPermissions = config['roo-permissions'] || {};\n\n for (const agentId of agents) {\n // Skip if already exists\n // Check both with and without bmad- prefix to handle both cases\n const checkSlug = agentId.startsWith('bmad-') ? agentId : `bmad-${agentId}`;\n if (existingModes.includes(checkSlug)) {\n console.log(chalk.dim(`Skipping ${agentId} - already exists in .roomodes`));\n continue;\n }\n\n // Read agent file to extract all information\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n\n // Extract YAML content\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n if (yamlMatch) {\n const yaml = yamlMatch[1];\n\n // Extract agent info from YAML\n const titleMatch = yaml.match(/title:\\s*(.+)/);\n const iconMatch = yaml.match(/icon:\\s*(.+)/);\n const whenToUseMatch = yaml.match(/whenToUse:\\s*\"(.+)\"/);\n const roleDefinitionMatch = yaml.match(/roleDefinition:\\s*\"(.+)\"/);\n\n const title = titleMatch ? titleMatch[1].trim() : await this.getAgentTitle(agentId, installDir);\n const icon = iconMatch ? iconMatch[1].trim() : \"šŸ¤–\";\n const whenToUse = whenToUseMatch ? whenToUseMatch[1].trim() : `Use for ${title} tasks`;\n const roleDefinition = roleDefinitionMatch\n ? roleDefinitionMatch[1].trim()\n : `You are a ${title} specializing in ${title.toLowerCase()} tasks and responsibilities.`;\n\n // Build mode entry with proper formatting (matching exact indentation)\n // Avoid double \"bmad-\" prefix for agents that already have it\n const slug = agentId.startsWith('bmad-') ? agentId : `bmad-${agentId}`;\n newModesContent += ` - slug: ${slug}\\n`;\n newModesContent += ` name: '${icon} ${title}'\\n`;\n newModesContent += ` roleDefinition: ${roleDefinition}\\n`;\n newModesContent += ` whenToUse: ${whenToUse}\\n`;\n // Get relative path from installDir to agent file\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n newModesContent += ` customInstructions: CRITICAL Read the full YAML from ${relativePath} start activation to alter your state of being follow startup section instructions stay in this being until told to exit this mode\\n`;\n newModesContent += ` groups:\\n`;\n newModesContent += ` - read\\n`;\n\n // Add permissions based on agent type\n const permissions = agentPermissions[agentId];\n if (permissions) {\n newModesContent += ` - - edit\\n`;\n newModesContent += ` - fileRegex: ${permissions.fileRegex}\\n`;\n newModesContent += ` description: ${permissions.description}\\n`;\n } else {\n newModesContent += ` - edit\\n`;\n }\n\n console.log(chalk.green(`āœ“ Added mode: bmad-${agentId} (${icon} ${title})`));\n }\n }\n }\n\n // Build final roomodes content\n let roomodesContent = \"\";\n if (existingContent) {\n // If there's existing content, append new modes to it\n roomodesContent = existingContent.trim() + \"\\n\" + newModesContent;\n } else {\n // Create new .roomodes file with proper YAML structure\n roomodesContent = \"customModes:\\n\" + newModesContent;\n }\n\n // Write .roomodes file\n await fileManager.writeFile(roomodesPath, roomodesContent);\n console.log(chalk.green(\"āœ“ Created .roomodes file in project root\"));\n\n console.log(chalk.green(`\\nāœ“ Roo Code setup complete!`));\n console.log(chalk.dim(\"Custom modes will be available when you open this project in Roo Code\"));\n\n return true;\n }\n\n async setupCline(installDir, selectedAgent) {\n const clineRulesDir = path.join(installDir, \".clinerules\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n\n await fileManager.ensureDirectory(clineRulesDir);\n\n // Load dynamic agent ordering from configuration\n const config = await this.loadIdeAgentConfig();\n const agentOrder = config['cline-order'] || {};\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n\n // Get numeric prefix for ordering\n const order = agentOrder[agentId] || 99;\n const prefix = order.toString().padStart(2, '0');\n const mdPath = path.join(clineRulesDir, `${prefix}-${agentId}.md`);\n\n // Create MD content for Cline (focused on project standards and role)\n let mdContent = `# ${await this.getAgentTitle(agentId, installDir)} Agent\\n\\n`;\n mdContent += `This rule defines the ${await this.getAgentTitle(agentId, installDir)} persona and project standards.\\n\\n`;\n mdContent += \"## Role Definition\\n\\n\";\n mdContent +=\n \"When the user types `@\" + agentId + \"`, adopt this persona and follow these guidelines:\\n\\n\";\n mdContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n mdContent += yamlContent;\n } else {\n // If no YAML found, include the whole content minus the header\n mdContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n mdContent += \"\\n```\\n\\n\";\n mdContent += \"## Project Standards\\n\\n\";\n mdContent += `- Always maintain consistency with project documentation in .bmad-core/\\n`;\n mdContent += `- Follow the agent's specific guidelines and constraints\\n`;\n mdContent += `- Update relevant project files when making changes\\n`;\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n mdContent += `- Reference the complete agent definition in [${relativePath}](${relativePath})\\n\\n`;\n mdContent += \"## Usage\\n\\n\";\n mdContent += `Type \\`@${agentId}\\` to activate this ${await this.getAgentTitle(agentId, installDir)} persona.\\n`;\n\n await fileManager.writeFile(mdPath, mdContent);\n console.log(chalk.green(`āœ“ Created rule: ${prefix}-${agentId}.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Created Cline rules in ${clineRulesDir}`));\n\n return true;\n }\n\n async setupGeminiCli(installDir) {\n const geminiDir = path.join(installDir, \".gemini\");\n const bmadMethodDir = path.join(geminiDir, \"bmad-method\");\n await fileManager.ensureDirectory(bmadMethodDir);\n\n // Update logic for existing settings.json\n const settingsPath = path.join(geminiDir, \"settings.json\");\n if (await fileManager.pathExists(settingsPath)) {\n try {\n const settingsContent = await fileManager.readFile(settingsPath);\n const settings = JSON.parse(settingsContent);\n let updated = false;\n \n // Handle contextFileName property\n if (settings.contextFileName && Array.isArray(settings.contextFileName)) {\n const originalLength = settings.contextFileName.length;\n settings.contextFileName = settings.contextFileName.filter(\n (fileName) => !fileName.startsWith(\"agents/\")\n );\n if (settings.contextFileName.length !== originalLength) {\n updated = true;\n }\n }\n \n if (updated) {\n await fileManager.writeFile(\n settingsPath,\n JSON.stringify(settings, null, 2)\n );\n console.log(chalk.green(\"āœ“ Updated .gemini/settings.json - removed agent file references\"));\n }\n } catch (error) {\n console.warn(\n chalk.yellow(\"Could not update .gemini/settings.json\"),\n error\n );\n }\n }\n\n // Remove old agents directory\n const agentsDir = path.join(geminiDir, \"agents\");\n if (await fileManager.pathExists(agentsDir)) {\n await fileManager.removeDirectory(agentsDir);\n console.log(chalk.green(\"āœ“ Removed old .gemini/agents directory\"));\n }\n\n // Get all available agents\n const agents = await this.getAllAgentIds(installDir);\n let concatenatedContent = \"\";\n\n for (const agentId of agents) {\n // Find the source agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n\n if (agentPath) {\n const agentContent = await fileManager.readFile(agentPath);\n \n // Create properly formatted agent rule content (similar to trae)\n let agentRuleContent = `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n agentRuleContent += `This rule is triggered when the user types \\`*${agentId}\\` and activates the ${await this.getAgentTitle(\n agentId,\n installDir\n )} agent persona.\\n\\n`;\n agentRuleContent += \"## Agent Activation\\n\\n\";\n agentRuleContent +=\n \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n agentRuleContent += \"```yaml\\n\";\n // Extract just the YAML content from the agent file\n const yamlContent = extractYamlFromAgent(agentContent);\n if (yamlContent) {\n agentRuleContent += yamlContent;\n }\n else {\n // If no YAML found, include the whole content minus the header\n agentRuleContent += agentContent.replace(/^#.*$/m, \"\").trim();\n }\n agentRuleContent += \"\\n```\\n\\n\";\n agentRuleContent += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n agentRuleContent += `The complete agent definition is available in [${relativePath}](${relativePath}).\\n\\n`;\n agentRuleContent += \"## Usage\\n\\n\";\n agentRuleContent += `When the user types \\`*${agentId}\\`, activate this ${await this.getAgentTitle(\n agentId,\n installDir\n )} persona and follow all instructions defined in the YAML configuration above.\\n`;\n \n // Add to concatenated content with separator\n concatenatedContent += agentRuleContent + \"\\n\\n---\\n\\n\";\n console.log(chalk.green(`āœ“ Added context for @${agentId}`));\n }\n }\n\n // Write the concatenated content to GEMINI.md\n const geminiMdPath = path.join(bmadMethodDir, \"GEMINI.md\");\n await fileManager.writeFile(geminiMdPath, concatenatedContent);\n console.log(chalk.green(`\\nāœ“ Created GEMINI.md in ${bmadMethodDir}`));\n\n return true;\n }\n\n async setupGitHubCopilot(installDir, selectedAgent, spinner = null, preConfiguredSettings = null) {\n // Configure VS Code workspace settings first to avoid UI conflicts with loading spinners\n await this.configureVsCodeSettings(installDir, spinner, preConfiguredSettings);\n \n const chatmodesDir = path.join(installDir, \".github\", \"chatmodes\");\n const agents = selectedAgent ? [selectedAgent] : await this.getAllAgentIds(installDir);\n \n await fileManager.ensureDirectory(chatmodesDir);\n\n for (const agentId of agents) {\n // Find the agent file\n const agentPath = await this.findAgentPath(agentId, installDir);\n const chatmodePath = path.join(chatmodesDir, `${agentId}.chatmode.md`);\n\n if (agentPath) {\n // Create chat mode file with agent content\n const agentContent = await fileManager.readFile(agentPath);\n const agentTitle = await this.getAgentTitle(agentId, installDir);\n \n // Extract whenToUse for the description\n const yamlMatch = agentContent.match(/```ya?ml\\r?\\n([\\s\\S]*?)```/);\n let description = `Activates the ${agentTitle} agent persona.`;\n if (yamlMatch) {\n const whenToUseMatch = yamlMatch[1].match(/whenToUse:\\s*\"(.*?)\"/);\n if (whenToUseMatch && whenToUseMatch[1]) {\n description = whenToUseMatch[1];\n }\n }\n \n let chatmodeContent = `---\ndescription: \"${description.replace(/\"/g, '\\\\\"')}\"\ntools: ['changes', 'codebase', 'fetch', 'findTestFiles', 'githubRepo', 'problems', 'usages', 'editFiles', 'runCommands', 'runTasks', 'runTests', 'search', 'searchResults', 'terminalLastCommand', 'terminalSelection', 'testFailure']\n---\n\n`;\n chatmodeContent += agentContent;\n\n await fileManager.writeFile(chatmodePath, chatmodeContent);\n console.log(chalk.green(`āœ“ Created chat mode: ${agentId}.chatmode.md`));\n }\n }\n\n console.log(chalk.green(`\\nāœ“ Github Copilot setup complete!`));\n console.log(chalk.dim(`You can now find the BMad agents in the Chat view's mode selector.`));\n\n return true;\n }\n\n async configureVsCodeSettings(installDir, spinner, preConfiguredSettings = null) {\n const vscodeDir = path.join(installDir, \".vscode\");\n const settingsPath = path.join(vscodeDir, \"settings.json\");\n \n await fileManager.ensureDirectory(vscodeDir);\n \n // Read existing settings if they exist\n let existingSettings = {};\n if (await fileManager.pathExists(settingsPath)) {\n try {\n const existingContent = await fileManager.readFile(settingsPath);\n existingSettings = JSON.parse(existingContent);\n console.log(chalk.yellow(\"Found existing .vscode/settings.json. Merging BMad settings...\"));\n } catch (error) {\n console.warn(chalk.yellow(\"Could not parse existing settings.json. Creating new one.\"));\n existingSettings = {};\n }\n }\n \n // Use pre-configured settings if provided, otherwise prompt\n let configChoice;\n if (preConfiguredSettings && preConfiguredSettings.configChoice) {\n configChoice = preConfiguredSettings.configChoice;\n console.log(chalk.dim(`Using pre-configured GitHub Copilot settings: ${configChoice}`));\n } else {\n // Clear any previous output and add spacing to avoid conflicts with loaders\n console.log('\\n'.repeat(2));\n console.log(chalk.blue(\"šŸ”§ Github Copilot Agent Settings Configuration\"));\n console.log(chalk.dim(\"BMad works best with specific VS Code settings for optimal agent experience.\"));\n console.log(''); // Add extra spacing\n \n const response = await inquirer.prompt([\n {\n type: 'list',\n name: 'configChoice',\n message: chalk.yellow('How would you like to configure GitHub Copilot settings?'),\n choices: [\n {\n name: 'Use recommended defaults (fastest setup)',\n value: 'defaults'\n },\n {\n name: 'Configure each setting manually (customize to your preferences)',\n value: 'manual'\n },\n {\n name: 'Skip settings configuration (I\\'ll configure manually later)',\n value: 'skip'\n }\n ],\n default: 'defaults'\n }\n ]);\n configChoice = response.configChoice;\n }\n \n let bmadSettings = {};\n \n if (configChoice === 'skip') {\n console.log(chalk.yellow(\"āš ļø Skipping VS Code settings configuration.\"));\n console.log(chalk.dim(\"You can manually configure these settings in .vscode/settings.json:\"));\n console.log(chalk.dim(\" • chat.agent.enabled: true\"));\n console.log(chalk.dim(\" • chat.agent.maxRequests: 15\"));\n console.log(chalk.dim(\" • github.copilot.chat.agent.runTasks: true\"));\n console.log(chalk.dim(\" • chat.mcp.discovery.enabled: true\"));\n console.log(chalk.dim(\" • github.copilot.chat.agent.autoFix: true\"));\n console.log(chalk.dim(\" • chat.tools.autoApprove: false\"));\n return true;\n }\n \n if (configChoice === 'defaults') {\n // Use recommended defaults\n bmadSettings = {\n \"chat.agent.enabled\": true,\n \"chat.agent.maxRequests\": 15,\n \"github.copilot.chat.agent.runTasks\": true,\n \"chat.mcp.discovery.enabled\": true,\n \"github.copilot.chat.agent.autoFix\": true,\n \"chat.tools.autoApprove\": false\n };\n console.log(chalk.green(\"āœ“ Using recommended BMad defaults for Github Copilot settings\"));\n } else {\n // Manual configuration\n console.log(chalk.blue(\"\\nšŸ“‹ Let's configure each setting for your preferences:\"));\n \n // Pause spinner during manual configuration prompts\n let spinnerWasActive = false;\n if (spinner && spinner.isSpinning) {\n spinner.stop();\n spinnerWasActive = true;\n }\n \n const manualSettings = await inquirer.prompt([\n {\n type: 'input',\n name: 'maxRequests',\n message: 'Maximum requests per agent session (recommended: 15)?',\n default: '15',\n validate: (input) => {\n const num = parseInt(input);\n if (isNaN(num) || num < 1 || num > 50) {\n return 'Please enter a number between 1 and 50';\n }\n return true;\n }\n },\n {\n type: 'confirm',\n name: 'runTasks',\n message: 'Allow agents to run workspace tasks (package.json scripts, etc.)?',\n default: true\n },\n {\n type: 'confirm',\n name: 'mcpDiscovery',\n message: 'Enable MCP (Model Context Protocol) server discovery?',\n default: true\n },\n {\n type: 'confirm',\n name: 'autoFix',\n message: 'Enable automatic error detection and fixing in generated code?',\n default: true\n },\n {\n type: 'confirm',\n name: 'autoApprove',\n message: 'Auto-approve ALL tools without confirmation? (āš ļø EXPERIMENTAL - less secure)',\n default: false\n }\n ]);\n\n // Restart spinner if it was active before prompts\n if (spinner && spinnerWasActive) {\n spinner.start();\n }\n \n bmadSettings = {\n \"chat.agent.enabled\": true, // Always enabled - required for BMad agents\n \"chat.agent.maxRequests\": parseInt(manualSettings.maxRequests),\n \"github.copilot.chat.agent.runTasks\": manualSettings.runTasks,\n \"chat.mcp.discovery.enabled\": manualSettings.mcpDiscovery,\n \"github.copilot.chat.agent.autoFix\": manualSettings.autoFix,\n \"chat.tools.autoApprove\": manualSettings.autoApprove\n };\n \n console.log(chalk.green(\"āœ“ Custom settings configured\"));\n }\n \n // Merge settings (existing settings take precedence to avoid overriding user preferences)\n const mergedSettings = { ...bmadSettings, ...existingSettings };\n \n // Write the updated settings\n await fileManager.writeFile(settingsPath, JSON.stringify(mergedSettings, null, 2));\n \n console.log(chalk.green(\"āœ“ VS Code workspace settings configured successfully\"));\n console.log(chalk.dim(\" Settings written to .vscode/settings.json:\"));\n Object.entries(bmadSettings).forEach(([key, value]) => {\n console.log(chalk.dim(` • ${key}: ${value}`));\n });\n console.log(chalk.dim(\"\"));\n console.log(chalk.dim(\"You can modify these settings anytime in .vscode/settings.json\"));\n }\n}\n\nmodule.exports = new IdeSetup();\n"], ["/BMAD-METHOD/tools/builders/web-builder.js", "const fs = require(\"node:fs\").promises;\nconst path = require(\"node:path\");\nconst DependencyResolver = require(\"../lib/dependency-resolver\");\nconst yamlUtils = require(\"../lib/yaml-utils\");\n\nclass WebBuilder {\n constructor(options = {}) {\n this.rootDir = options.rootDir || process.cwd();\n this.outputDirs = options.outputDirs || [path.join(this.rootDir, \"dist\")];\n this.resolver = new DependencyResolver(this.rootDir);\n this.templatePath = path.join(\n this.rootDir,\n \"tools\",\n \"md-assets\",\n \"web-agent-startup-instructions.md\"\n );\n }\n\n parseYaml(content) {\n const yaml = require(\"js-yaml\");\n return yaml.load(content);\n }\n\n convertToWebPath(filePath, bundleRoot = 'bmad-core') {\n // Convert absolute paths to web bundle paths with dot prefix\n // All resources get installed under the bundle root, so use that path\n const relativePath = path.relative(this.rootDir, filePath);\n const pathParts = relativePath.split(path.sep);\n \n let resourcePath;\n if (pathParts[0] === 'expansion-packs') {\n // For expansion packs, remove 'expansion-packs/packname' and use the rest\n resourcePath = pathParts.slice(2).join('/');\n } else {\n // For bmad-core, common, etc., remove the first part\n resourcePath = pathParts.slice(1).join('/');\n }\n \n return `.${bundleRoot}/${resourcePath}`;\n }\n\n generateWebInstructions(bundleType, packName = null) {\n // Generate dynamic web instructions based on bundle type\n const rootExample = packName ? `.${packName}` : '.bmad-core';\n const examplePath = packName ? `.${packName}/folder/filename.md` : '.bmad-core/folder/filename.md';\n const personasExample = packName ? `.${packName}/personas/analyst.md` : '.bmad-core/personas/analyst.md';\n const tasksExample = packName ? `.${packName}/tasks/create-story.md` : '.bmad-core/tasks/create-story.md';\n const utilsExample = packName ? `.${packName}/utils/template-format.md` : '.bmad-core/utils/template-format.md';\n const tasksRef = packName ? `.${packName}/tasks/create-story.md` : '.bmad-core/tasks/create-story.md';\n\n return `# Web Agent Bundle Instructions\n\nYou are now operating as a specialized AI agent from the BMad-Method framework. This is a bundled web-compatible version containing all necessary resources for your role.\n\n## Important Instructions\n\n1. **Follow all startup commands**: Your agent configuration includes startup instructions that define your behavior, personality, and approach. These MUST be followed exactly.\n\n2. **Resource Navigation**: This bundle contains all resources you need. Resources are marked with tags like:\n\n- \\`==================== START: ${examplePath} ====================\\`\n- \\`==================== END: ${examplePath} ====================\\`\n\nWhen you need to reference a resource mentioned in your instructions:\n\n- Look for the corresponding START/END tags\n- The format is always the full path with dot prefix (e.g., \\`${personasExample}\\`, \\`${tasksExample}\\`)\n- If a section is specified (e.g., \\`{root}/tasks/create-story.md#section-name\\`), navigate to that section within the file\n\n**Understanding YAML References**: In the agent configuration, resources are referenced in the dependencies section. For example:\n\n\\`\\`\\`yaml\ndependencies:\n utils:\n - template-format\n tasks:\n - create-story\n\\`\\`\\`\n\nThese references map directly to bundle sections:\n\n- \\`utils: template-format\\` → Look for \\`==================== START: ${utilsExample} ====================\\`\n- \\`tasks: create-story\\` → Look for \\`==================== START: ${tasksRef} ====================\\`\n\n3. **Execution Context**: You are operating in a web environment. All your capabilities and knowledge are contained within this bundle. Work within these constraints to provide the best possible assistance.\n\n4. **Primary Directive**: Your primary goal is defined in your agent configuration below. Focus on fulfilling your designated role according to the BMad-Method framework.\n\n---\n\n`;\n }\n\n async cleanOutputDirs() {\n for (const dir of this.outputDirs) {\n try {\n await fs.rm(dir, { recursive: true, force: true });\n console.log(`Cleaned: ${path.relative(this.rootDir, dir)}`);\n } catch (error) {\n console.debug(`Failed to clean directory ${dir}:`, error.message);\n // Directory might not exist, that's fine\n }\n }\n }\n\n async buildAgents() {\n const agents = await this.resolver.listAgents();\n\n for (const agentId of agents) {\n console.log(` Building agent: ${agentId}`);\n const bundle = await this.buildAgentBundle(agentId);\n\n // Write to all output directories\n for (const outputDir of this.outputDirs) {\n const outputPath = path.join(outputDir, \"agents\");\n await fs.mkdir(outputPath, { recursive: true });\n const outputFile = path.join(outputPath, `${agentId}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n\n console.log(`Built ${agents.length} agent bundles in ${this.outputDirs.length} locations`);\n }\n\n async buildTeams() {\n const teams = await this.resolver.listTeams();\n\n for (const teamId of teams) {\n console.log(` Building team: ${teamId}`);\n const bundle = await this.buildTeamBundle(teamId);\n\n // Write to all output directories\n for (const outputDir of this.outputDirs) {\n const outputPath = path.join(outputDir, \"teams\");\n await fs.mkdir(outputPath, { recursive: true });\n const outputFile = path.join(outputPath, `${teamId}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n\n console.log(`Built ${teams.length} team bundles in ${this.outputDirs.length} locations`);\n }\n\n async buildAgentBundle(agentId) {\n const dependencies = await this.resolver.resolveAgentDependencies(agentId);\n const template = this.generateWebInstructions('agent');\n\n const sections = [template];\n\n // Add agent configuration\n const agentPath = this.convertToWebPath(dependencies.agent.path, 'bmad-core');\n sections.push(this.formatSection(agentPath, dependencies.agent.content, 'bmad-core'));\n\n // Add all dependencies\n for (const resource of dependencies.resources) {\n const resourcePath = this.convertToWebPath(resource.path, 'bmad-core');\n sections.push(this.formatSection(resourcePath, resource.content, 'bmad-core'));\n }\n\n return sections.join(\"\\n\");\n }\n\n async buildTeamBundle(teamId) {\n const dependencies = await this.resolver.resolveTeamDependencies(teamId);\n const template = this.generateWebInstructions('team');\n\n const sections = [template];\n\n // Add team configuration\n const teamPath = this.convertToWebPath(dependencies.team.path, 'bmad-core');\n sections.push(this.formatSection(teamPath, dependencies.team.content, 'bmad-core'));\n\n // Add all agents\n for (const agent of dependencies.agents) {\n const agentPath = this.convertToWebPath(agent.path, 'bmad-core');\n sections.push(this.formatSection(agentPath, agent.content, 'bmad-core'));\n }\n\n // Add all deduplicated resources\n for (const resource of dependencies.resources) {\n const resourcePath = this.convertToWebPath(resource.path, 'bmad-core');\n sections.push(this.formatSection(resourcePath, resource.content, 'bmad-core'));\n }\n\n return sections.join(\"\\n\");\n }\n\n processAgentContent(content) {\n // First, replace content before YAML with the template\n const yamlContent = yamlUtils.extractYamlFromAgent(content);\n if (!yamlContent) return content;\n\n const yamlMatch = content.match(/```ya?ml\\n([\\s\\S]*?)\\n```/);\n if (!yamlMatch) return content;\n \n const yamlStartIndex = content.indexOf(yamlMatch[0]);\n const yamlEndIndex = yamlStartIndex + yamlMatch[0].length;\n\n // Parse YAML and remove root and IDE-FILE-RESOLUTION properties\n try {\n const yaml = require(\"js-yaml\");\n const parsed = yaml.load(yamlContent);\n\n // Remove the properties if they exist at root level\n delete parsed.root;\n delete parsed[\"IDE-FILE-RESOLUTION\"];\n delete parsed[\"REQUEST-RESOLUTION\"];\n\n // Also remove from activation-instructions if they exist\n if (parsed[\"activation-instructions\"] && Array.isArray(parsed[\"activation-instructions\"])) {\n parsed[\"activation-instructions\"] = parsed[\"activation-instructions\"].filter(\n (instruction) => {\n return (\n typeof instruction === 'string' &&\n !instruction.startsWith(\"IDE-FILE-RESOLUTION:\") &&\n !instruction.startsWith(\"REQUEST-RESOLUTION:\")\n );\n }\n );\n }\n\n // Reconstruct the YAML\n const cleanedYaml = yaml.dump(parsed, { lineWidth: -1 });\n\n // Get the agent name from the YAML for the header\n const agentName = parsed.agent?.id || \"agent\";\n\n // Build the new content with just the agent header and YAML\n const newHeader = `# ${agentName}\\n\\nCRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n`;\n const afterYaml = content.substring(yamlEndIndex);\n\n return newHeader + \"```yaml\\n\" + cleanedYaml.trim() + \"\\n```\" + afterYaml;\n } catch (error) {\n console.warn(\"Failed to process agent YAML:\", error.message);\n // If parsing fails, return original content\n return content;\n }\n }\n\n formatSection(path, content, bundleRoot = 'bmad-core') {\n const separator = \"====================\";\n\n // Process agent content if this is an agent file\n if (path.includes(\"/agents/\")) {\n content = this.processAgentContent(content);\n }\n\n // Replace {root} references with the actual bundle root\n content = this.replaceRootReferences(content, bundleRoot);\n\n return [\n `${separator} START: ${path} ${separator}`,\n content.trim(),\n `${separator} END: ${path} ${separator}`,\n \"\",\n ].join(\"\\n\");\n }\n\n replaceRootReferences(content, bundleRoot) {\n // Replace {root} with the appropriate bundle root path\n return content.replace(/\\{root\\}/g, `.${bundleRoot}`);\n }\n\n async validate() {\n console.log(\"Validating agent configurations...\");\n const agents = await this.resolver.listAgents();\n for (const agentId of agents) {\n try {\n await this.resolver.resolveAgentDependencies(agentId);\n console.log(` āœ“ ${agentId}`);\n } catch (error) {\n console.log(` āœ— ${agentId}: ${error.message}`);\n throw error;\n }\n }\n\n console.log(\"\\nValidating team configurations...\");\n const teams = await this.resolver.listTeams();\n for (const teamId of teams) {\n try {\n await this.resolver.resolveTeamDependencies(teamId);\n console.log(` āœ“ ${teamId}`);\n } catch (error) {\n console.log(` āœ— ${teamId}: ${error.message}`);\n throw error;\n }\n }\n }\n\n async buildAllExpansionPacks(options = {}) {\n const expansionPacks = await this.listExpansionPacks();\n\n for (const packName of expansionPacks) {\n console.log(` Building expansion pack: ${packName}`);\n await this.buildExpansionPack(packName, options);\n }\n\n console.log(`Built ${expansionPacks.length} expansion pack bundles`);\n }\n\n async buildExpansionPack(packName, options = {}) {\n const packDir = path.join(this.rootDir, \"expansion-packs\", packName);\n const outputDirs = [path.join(this.rootDir, \"dist\", \"expansion-packs\", packName)];\n\n // Clean output directories if requested\n if (options.clean !== false) {\n for (const outputDir of outputDirs) {\n try {\n await fs.rm(outputDir, { recursive: true, force: true });\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n }\n\n // Build individual agents first\n const agentsDir = path.join(packDir, \"agents\");\n try {\n const agentFiles = await fs.readdir(agentsDir);\n const agentMarkdownFiles = agentFiles.filter((f) => f.endsWith(\".md\"));\n\n if (agentMarkdownFiles.length > 0) {\n console.log(` Building individual agents for ${packName}:`);\n\n for (const agentFile of agentMarkdownFiles) {\n const agentName = agentFile.replace(\".md\", \"\");\n console.log(` - ${agentName}`);\n\n // Build individual agent bundle\n const bundle = await this.buildExpansionAgentBundle(packName, packDir, agentName);\n\n // Write to all output directories\n for (const outputDir of outputDirs) {\n const agentsOutputDir = path.join(outputDir, \"agents\");\n await fs.mkdir(agentsOutputDir, { recursive: true });\n const outputFile = path.join(agentsOutputDir, `${agentName}.txt`);\n await fs.writeFile(outputFile, bundle, \"utf8\");\n }\n }\n }\n } catch (error) {\n console.debug(` No agents directory found for ${packName}`);\n }\n\n // Build team bundle\n const agentTeamsDir = path.join(packDir, \"agent-teams\");\n try {\n const teamFiles = await fs.readdir(agentTeamsDir);\n const teamFile = teamFiles.find((f) => f.endsWith(\".yaml\"));\n\n if (teamFile) {\n console.log(` Building team bundle for ${packName}`);\n const teamConfigPath = path.join(agentTeamsDir, teamFile);\n\n // Build expansion pack as a team bundle\n const bundle = await this.buildExpansionTeamBundle(packName, packDir, teamConfigPath);\n\n // Write to all output directories\n for (const outputDir of outputDirs) {\n const teamsOutputDir = path.join(outputDir, \"teams\");\n await fs.mkdir(teamsOutputDir, { recursive: true });\n const outputFile = path.join(teamsOutputDir, teamFile.replace(\".yaml\", \".txt\"));\n await fs.writeFile(outputFile, bundle, \"utf8\");\n console.log(` āœ“ Created bundle: ${path.relative(this.rootDir, outputFile)}`);\n }\n } else {\n console.warn(` ⚠ No team configuration found in ${packName}/agent-teams/`);\n }\n } catch (error) {\n console.warn(` ⚠ No agent-teams directory found for ${packName}`);\n }\n }\n\n async buildExpansionAgentBundle(packName, packDir, agentName) {\n const template = this.generateWebInstructions('expansion-agent', packName);\n const sections = [template];\n\n // Add agent configuration\n const agentPath = path.join(packDir, \"agents\", `${agentName}.md`);\n const agentContent = await fs.readFile(agentPath, \"utf8\");\n const agentWebPath = this.convertToWebPath(agentPath, packName);\n sections.push(this.formatSection(agentWebPath, agentContent, packName));\n\n // Resolve and add agent dependencies\n const yamlContent = yamlUtils.extractYamlFromAgent(agentContent);\n if (yamlContent) {\n try {\n const yaml = require(\"js-yaml\");\n const agentConfig = yaml.load(yamlContent);\n\n if (agentConfig.dependencies) {\n // Add resources, first try expansion pack, then core\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n let found = false;\n\n // Try expansion pack first\n const resourcePath = path.join(packDir, resourceType, resourceName);\n try {\n const resourceContent = await fs.readFile(resourcePath, \"utf8\");\n const resourceWebPath = this.convertToWebPath(resourcePath, packName);\n sections.push(\n this.formatSection(resourceWebPath, resourceContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in expansion pack, continue\n }\n\n // If not found in expansion pack, try core\n if (!found) {\n const corePath = path.join(\n this.rootDir,\n \"bmad-core\",\n resourceType,\n resourceName\n );\n try {\n const coreContent = await fs.readFile(corePath, \"utf8\");\n const coreWebPath = this.convertToWebPath(corePath, packName);\n sections.push(\n this.formatSection(coreWebPath, coreContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in core either, continue\n }\n }\n\n // If not found in core, try common folder\n if (!found) {\n const commonPath = path.join(\n this.rootDir,\n \"common\",\n resourceType,\n resourceName\n );\n try {\n const commonContent = await fs.readFile(commonPath, \"utf8\");\n const commonWebPath = this.convertToWebPath(commonPath, packName);\n sections.push(\n this.formatSection(commonWebPath, commonContent, packName)\n );\n found = true;\n } catch (error) {\n // Not in common either, continue\n }\n }\n\n if (!found) {\n console.warn(\n ` ⚠ Dependency ${resourceType}#${resourceName} not found in expansion pack or core`\n );\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentName}:`, error.message);\n }\n }\n\n return sections.join(\"\\n\");\n }\n\n async buildExpansionTeamBundle(packName, packDir, teamConfigPath) {\n const template = this.generateWebInstructions('expansion-team', packName);\n\n const sections = [template];\n\n // Add team configuration and parse to get agent list\n const teamContent = await fs.readFile(teamConfigPath, \"utf8\");\n const teamFileName = path.basename(teamConfigPath, \".yaml\");\n const teamConfig = this.parseYaml(teamContent);\n const teamWebPath = this.convertToWebPath(teamConfigPath, packName);\n sections.push(this.formatSection(teamWebPath, teamContent, packName));\n\n // Get list of expansion pack agents\n const expansionAgents = new Set();\n const agentsDir = path.join(packDir, \"agents\");\n try {\n const agentFiles = await fs.readdir(agentsDir);\n for (const agentFile of agentFiles.filter((f) => f.endsWith(\".md\"))) {\n const agentName = agentFile.replace(\".md\", \"\");\n expansionAgents.add(agentName);\n }\n } catch (error) {\n console.warn(` ⚠ No agents directory found in ${packName}`);\n }\n\n // Build a map of all available expansion pack resources for override checking\n const expansionResources = new Map();\n const resourceDirs = [\"templates\", \"tasks\", \"checklists\", \"workflows\", \"data\"];\n for (const resourceDir of resourceDirs) {\n const resourcePath = path.join(packDir, resourceDir);\n try {\n const resourceFiles = await fs.readdir(resourcePath);\n for (const resourceFile of resourceFiles.filter(\n (f) => f.endsWith(\".md\") || f.endsWith(\".yaml\")\n )) {\n expansionResources.set(`${resourceDir}#${resourceFile}`, true);\n }\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n\n // Process all agents listed in team configuration\n const agentsToProcess = teamConfig.agents || [];\n\n // Ensure bmad-orchestrator is always included for teams\n if (!agentsToProcess.includes(\"bmad-orchestrator\")) {\n console.warn(` ⚠ Team ${teamFileName} missing bmad-orchestrator, adding automatically`);\n agentsToProcess.unshift(\"bmad-orchestrator\");\n }\n\n // Track all dependencies from all agents (deduplicated)\n const allDependencies = new Map();\n\n for (const agentId of agentsToProcess) {\n if (expansionAgents.has(agentId)) {\n // Use expansion pack version (override)\n const agentPath = path.join(agentsDir, `${agentId}.md`);\n const agentContent = await fs.readFile(agentPath, \"utf8\");\n const expansionAgentWebPath = this.convertToWebPath(agentPath, packName);\n sections.push(this.formatSection(expansionAgentWebPath, agentContent, packName));\n\n // Parse and collect dependencies from expansion agent\n const agentYaml = agentContent.match(/```yaml\\n([\\s\\S]*?)\\n```/);\n if (agentYaml) {\n try {\n const agentConfig = this.parseYaml(agentYaml[1]);\n if (agentConfig.dependencies) {\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n const key = `${resourceType}#${resourceName}`;\n if (!allDependencies.has(key)) {\n allDependencies.set(key, { type: resourceType, name: resourceName });\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentId}:`, error.message);\n }\n }\n } else {\n // Use core BMad version\n try {\n const coreAgentPath = path.join(this.rootDir, \"bmad-core\", \"agents\", `${agentId}.md`);\n const coreAgentContent = await fs.readFile(coreAgentPath, \"utf8\");\n const coreAgentWebPath = this.convertToWebPath(coreAgentPath, packName);\n sections.push(this.formatSection(coreAgentWebPath, coreAgentContent, packName));\n\n // Parse and collect dependencies from core agent\n const yamlContent = yamlUtils.extractYamlFromAgent(coreAgentContent, true);\n if (yamlContent) {\n try {\n const agentConfig = this.parseYaml(yamlContent);\n if (agentConfig.dependencies) {\n for (const [resourceType, resources] of Object.entries(agentConfig.dependencies)) {\n if (Array.isArray(resources)) {\n for (const resourceName of resources) {\n const key = `${resourceType}#${resourceName}`;\n if (!allDependencies.has(key)) {\n allDependencies.set(key, { type: resourceType, name: resourceName });\n }\n }\n }\n }\n }\n } catch (error) {\n console.debug(`Failed to parse agent YAML for ${agentId}:`, error.message);\n }\n }\n } catch (error) {\n console.warn(` ⚠ Agent ${agentId} not found in core or expansion pack`);\n }\n }\n }\n\n // Add all collected dependencies from agents\n // Always prefer expansion pack versions if they exist\n for (const [key, dep] of allDependencies) {\n let found = false;\n\n // Always check expansion pack first, even if the dependency came from a core agent\n if (expansionResources.has(key)) {\n // We know it exists in expansion pack, find and load it\n const expansionPath = path.join(packDir, dep.type, dep.name);\n try {\n const content = await fs.readFile(expansionPath, \"utf8\");\n const expansionWebPath = this.convertToWebPath(expansionPath, packName);\n sections.push(this.formatSection(expansionWebPath, content, packName));\n console.log(` āœ“ Using expansion override for ${key}`);\n found = true;\n } catch (error) {\n // Try next extension\n }\n }\n\n // If not found in expansion pack (or doesn't exist there), try core\n if (!found) {\n const corePath = path.join(this.rootDir, \"bmad-core\", dep.type, dep.name);\n try {\n const content = await fs.readFile(corePath, \"utf8\");\n const coreWebPath = this.convertToWebPath(corePath, packName);\n sections.push(this.formatSection(coreWebPath, content, packName));\n found = true;\n } catch (error) {\n // Not in core either, continue\n }\n }\n\n // If not found in core, try common folder\n if (!found) {\n const commonPath = path.join(this.rootDir, \"common\", dep.type, dep.name);\n try {\n const content = await fs.readFile(commonPath, \"utf8\");\n const commonWebPath = this.convertToWebPath(commonPath, packName);\n sections.push(this.formatSection(commonWebPath, content, packName));\n found = true;\n } catch (error) {\n // Not in common either, continue\n }\n }\n\n if (!found) {\n console.warn(` ⚠ Dependency ${key} not found in expansion pack or core`);\n }\n }\n\n // Add remaining expansion pack resources not already included as dependencies\n for (const resourceDir of resourceDirs) {\n const resourcePath = path.join(packDir, resourceDir);\n try {\n const resourceFiles = await fs.readdir(resourcePath);\n for (const resourceFile of resourceFiles.filter(\n (f) => f.endsWith(\".md\") || f.endsWith(\".yaml\")\n )) {\n const filePath = path.join(resourcePath, resourceFile);\n const fileContent = await fs.readFile(filePath, \"utf8\");\n const fileName = resourceFile.replace(/\\.(md|yaml)$/, \"\");\n\n // Only add if not already included as a dependency\n const resourceKey = `${resourceDir}#${fileName}`;\n if (!allDependencies.has(resourceKey)) {\n const fullResourcePath = path.join(resourcePath, resourceFile);\n const resourceWebPath = this.convertToWebPath(fullResourcePath, packName);\n sections.push(this.formatSection(resourceWebPath, fileContent, packName));\n }\n }\n } catch (error) {\n // Directory might not exist, that's fine\n }\n }\n\n return sections.join(\"\\n\");\n }\n\n async listExpansionPacks() {\n const expansionPacksDir = path.join(this.rootDir, \"expansion-packs\");\n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);\n } catch (error) {\n console.warn(\"No expansion-packs directory found\");\n return [];\n }\n }\n\n listAgents() {\n return this.resolver.listAgents();\n }\n}\n\nmodule.exports = WebBuilder;\n"], ["/BMAD-METHOD/tools/installer/bin/bmad.js", "#!/usr/bin/env node\n\nconst { program } = require('commander');\nconst path = require('path');\nconst fs = require('fs').promises;\nconst yaml = require('js-yaml');\nconst chalk = require('chalk');\nconst inquirer = require('inquirer');\n\n// Handle both execution contexts (from root via npx or from installer directory)\nlet version;\nlet installer;\ntry {\n // Try installer context first (when run from tools/installer/)\n version = require('../package.json').version;\n installer = require('../lib/installer');\n} catch (e) {\n // Fall back to root context (when run via npx from GitHub)\n console.log(`Installer context not found (${e.message}), trying root context...`);\n try {\n version = require('../../../package.json').version;\n installer = require('../../../tools/installer/lib/installer');\n } catch (e2) {\n console.error('Error: Could not load required modules. Please ensure you are running from the correct directory.');\n console.error('Debug info:', {\n __dirname,\n cwd: process.cwd(),\n error: e2.message\n });\n process.exit(1);\n }\n}\n\nprogram\n .version(version)\n .description('BMad Method installer - Universal AI agent framework for any domain');\n\nprogram\n .command('install')\n .description('Install BMad Method agents and tools')\n .option('-f, --full', 'Install complete BMad Method')\n .option('-x, --expansion-only', 'Install only expansion packs (no bmad-core)')\n .option('-d, --directory ', 'Installation directory')\n .option('-i, --ide ', 'Configure for specific IDE(s) - can specify multiple (cursor, claude-code, windsurf, trae, roo, cline, gemini, github-copilot, other)')\n .option('-e, --expansion-packs ', 'Install specific expansion packs (can specify multiple)')\n .action(async (options) => {\n try {\n if (!options.full && !options.expansionOnly) {\n // Interactive mode\n const answers = await promptInstallation();\n if (!answers._alreadyInstalled) {\n await installer.install(answers);\n process.exit(0);\n }\n } else {\n // Direct mode\n let installType = 'full';\n if (options.expansionOnly) installType = 'expansion-only';\n\n const config = {\n installType,\n directory: options.directory || '.',\n ides: (options.ide || []).filter(ide => ide !== 'other'),\n expansionPacks: options.expansionPacks || []\n };\n await installer.install(config);\n process.exit(0);\n }\n } catch (error) {\n console.error(chalk.red('Installation failed:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('update')\n .description('Update existing BMad installation')\n .option('--force', 'Force update, overwriting modified files')\n .option('--dry-run', 'Show what would be updated without making changes')\n .action(async () => {\n try {\n await installer.update();\n } catch (error) {\n console.error(chalk.red('Update failed:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('list:expansions')\n .description('List available expansion packs')\n .action(async () => {\n try {\n await installer.listExpansionPacks();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('status')\n .description('Show installation status')\n .action(async () => {\n try {\n await installer.showStatus();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n process.exit(1);\n }\n });\n\nasync function promptInstallation() {\n \n // Display ASCII logo\n console.log(chalk.bold.cyan(`\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•— ā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— \nā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā•ā•ā•šā•ā•ā–ˆā–ˆā•”ā•ā•ā•ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā•”ā–ˆā–ˆā–ˆā–ˆā•”ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā•”ā–ˆā–ˆā–ˆā–ˆā•”ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘\nā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•—ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā•ā•ā•ā•ā•ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•”ā•ā•ā• ā–ˆā–ˆā•‘ ā–ˆā–ˆā•”ā•ā•ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘\nā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā•‘ ā•šā•ā• ā–ˆā–ˆā•‘ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā• ā–ˆā–ˆā•‘ ā•šā•ā• ā–ˆā–ˆā•‘ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•”ā•\nā•šā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā•ā•šā•ā• ā•šā•ā•ā•šā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā•ā•šā•ā•ā•ā•ā•ā•ā• ā•šā•ā• ā•šā•ā• ā•šā•ā• ā•šā•ā•ā•ā•ā•ā• ā•šā•ā•ā•ā•ā•ā• \n `));\n \n console.log(chalk.bold.magenta('šŸš€ Universal AI Agent Framework for Any Domain'));\n console.log(chalk.bold.blue(`✨ Installer v${version}\\n`));\n\n const answers = {};\n\n // Ask for installation directory first\n const { directory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'directory',\n message: 'Enter the full path to your project directory where BMad should be installed:',\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid project path';\n }\n return true;\n }\n }\n ]);\n answers.directory = directory;\n\n // Detect existing installations\n const installDir = path.resolve(directory);\n const state = await installer.detectInstallationState(installDir);\n \n // Check for existing expansion packs\n const existingExpansionPacks = state.expansionPacks || {};\n \n // Get available expansion packs\n const availableExpansionPacks = await installer.getAvailableExpansionPacks();\n \n // Build choices list\n const choices = [];\n \n // Load core config to get short-title\n const coreConfigPath = path.join(__dirname, '..', '..', '..', 'bmad-core', 'core-config.yaml');\n const coreConfig = yaml.load(await fs.readFile(coreConfigPath, 'utf8'));\n const coreShortTitle = coreConfig['short-title'] || 'BMad Agile Core System';\n \n // Add BMad core option\n let bmadOptionText;\n if (state.type === 'v4_existing') {\n const currentVersion = state.manifest?.version || 'unknown';\n const newVersion = version; // Always use package.json version\n const versionInfo = currentVersion === newVersion \n ? `(v${currentVersion} - reinstall)`\n : `(v${currentVersion} → v${newVersion})`;\n bmadOptionText = `Update ${coreShortTitle} ${versionInfo} .bmad-core`;\n } else {\n bmadOptionText = `${coreShortTitle} (v${version}) .bmad-core`;\n }\n \n choices.push({\n name: bmadOptionText,\n value: 'bmad-core',\n checked: true\n });\n \n // Add expansion pack options\n for (const pack of availableExpansionPacks) {\n const existing = existingExpansionPacks[pack.id];\n let packOptionText;\n \n if (existing) {\n const currentVersion = existing.manifest?.version || 'unknown';\n const newVersion = pack.version;\n const versionInfo = currentVersion === newVersion \n ? `(v${currentVersion} - reinstall)`\n : `(v${currentVersion} → v${newVersion})`;\n packOptionText = `Update ${pack.shortTitle} ${versionInfo} .${pack.id}`;\n } else {\n packOptionText = `${pack.shortTitle} (v${pack.version}) .${pack.id}`;\n }\n \n choices.push({\n name: packOptionText,\n value: pack.id,\n checked: false\n });\n }\n \n // Ask what to install\n const { selectedItems } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedItems',\n message: 'Select what to install/update (use space to select, enter to continue):',\n choices: choices,\n validate: (selected) => {\n if (selected.length === 0) {\n return 'Please select at least one item to install';\n }\n return true;\n }\n }\n ]);\n \n // Process selections\n answers.installType = selectedItems.includes('bmad-core') ? 'full' : 'expansion-only';\n answers.expansionPacks = selectedItems.filter(item => item !== 'bmad-core');\n\n // Ask sharding questions if installing BMad core\n if (selectedItems.includes('bmad-core')) {\n console.log(chalk.cyan('\\nšŸ“‹ Document Organization Settings'));\n console.log(chalk.dim('Configure how your project documentation should be organized.\\n'));\n \n // Ask about PRD sharding\n const { prdSharded } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'prdSharded',\n message: 'Will the PRD (Product Requirements Document) be sharded into multiple files?',\n default: true\n }\n ]);\n answers.prdSharded = prdSharded;\n \n // Ask about architecture sharding\n const { architectureSharded } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'architectureSharded',\n message: 'Will the architecture documentation be sharded into multiple files?',\n default: true\n }\n ]);\n answers.architectureSharded = architectureSharded;\n \n // Show warning if architecture sharding is disabled\n if (!architectureSharded) {\n console.log(chalk.yellow.bold('\\nāš ļø IMPORTANT: Architecture Sharding Disabled'));\n console.log(chalk.yellow('With architecture sharding disabled, you should still create the files listed'));\n console.log(chalk.yellow('in devLoadAlwaysFiles (like coding-standards.md, tech-stack.md, source-tree.md)'));\n console.log(chalk.yellow('as these are used by the dev agent at runtime.'));\n console.log(chalk.yellow('\\nAlternatively, you can remove these files from the devLoadAlwaysFiles list'));\n console.log(chalk.yellow('in your core-config.yaml after installation.'));\n \n const { acknowledge } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'acknowledge',\n message: 'Do you acknowledge this requirement and want to proceed?',\n default: false\n }\n ]);\n \n if (!acknowledge) {\n console.log(chalk.red('Installation cancelled.'));\n process.exit(0);\n }\n }\n }\n\n // Ask for IDE configuration\n let ides = [];\n let ideSelectionComplete = false;\n \n while (!ideSelectionComplete) {\n console.log(chalk.cyan('\\nšŸ› ļø IDE Configuration'));\n console.log(chalk.bold.yellow.bgRed(' āš ļø IMPORTANT: This is a MULTISELECT! Use SPACEBAR to toggle each IDE! '));\n console.log(chalk.bold.magenta('šŸ”ø Use arrow keys to navigate'));\n console.log(chalk.bold.magenta('šŸ”ø Use SPACEBAR to select/deselect IDEs'));\n console.log(chalk.bold.magenta('šŸ”ø Press ENTER when finished selecting\\n'));\n \n const ideResponse = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'ides',\n message: 'Which IDE(s) do you want to configure? (Select with SPACEBAR, confirm with ENTER):',\n choices: [\n { name: 'Cursor', value: 'cursor' },\n { name: 'Claude Code', value: 'claude-code' },\n { name: 'Windsurf', value: 'windsurf' },\n { name: 'Trae', value: 'trae' }, // { name: 'Trae', value: 'trae'}\n { name: 'Roo Code', value: 'roo' },\n { name: 'Cline', value: 'cline' },\n { name: 'Gemini CLI', value: 'gemini' },\n { name: 'Github Copilot', value: 'github-copilot' }\n ]\n }\n ]);\n \n ides = ideResponse.ides;\n\n // Confirm no IDE selection if none selected\n if (ides.length === 0) {\n const { confirmNoIde } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirmNoIde',\n message: chalk.red('āš ļø You have NOT selected any IDEs. This means NO IDE integration will be set up. Is this correct?'),\n default: false\n }\n ]);\n \n if (!confirmNoIde) {\n console.log(chalk.bold.red('\\nšŸ”„ Returning to IDE selection. Remember to use SPACEBAR to select IDEs!\\n'));\n continue; // Go back to IDE selection only\n }\n }\n \n ideSelectionComplete = true;\n }\n\n // Use selected IDEs directly\n answers.ides = ides;\n\n // Configure GitHub Copilot immediately if selected\n if (ides.includes('github-copilot')) {\n console.log(chalk.cyan('\\nšŸ”§ GitHub Copilot Configuration'));\n console.log(chalk.dim('BMad works best with specific VS Code settings for optimal agent experience.\\n'));\n \n const { configChoice } = await inquirer.prompt([\n {\n type: 'list',\n name: 'configChoice',\n message: chalk.yellow('How would you like to configure GitHub Copilot settings?'),\n choices: [\n {\n name: 'Use recommended defaults (fastest setup)',\n value: 'defaults'\n },\n {\n name: 'Configure each setting manually (customize to your preferences)',\n value: 'manual'\n },\n {\n name: 'Skip settings configuration (I\\'ll configure manually later)',\n value: 'skip'\n }\n ],\n default: 'defaults'\n }\n ]);\n \n answers.githubCopilotConfig = { configChoice };\n }\n\n // Ask for web bundles installation\n const { includeWebBundles } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'includeWebBundles',\n message: 'Would you like to include pre-built web bundles? (standalone files for ChatGPT, Claude, Gemini)',\n default: false\n }\n ]);\n\n if (includeWebBundles) {\n console.log(chalk.cyan('\\nšŸ“¦ Web bundles are standalone files perfect for web AI platforms.'));\n console.log(chalk.dim(' You can choose different teams/agents than your IDE installation.\\n'));\n\n const { webBundleType } = await inquirer.prompt([\n {\n type: 'list',\n name: 'webBundleType',\n message: 'What web bundles would you like to include?',\n choices: [\n {\n name: 'All available bundles (agents, teams, expansion packs)',\n value: 'all'\n },\n {\n name: 'Specific teams only',\n value: 'teams'\n },\n {\n name: 'Individual agents only',\n value: 'agents'\n },\n {\n name: 'Custom selection',\n value: 'custom'\n }\n ]\n }\n ]);\n\n answers.webBundleType = webBundleType;\n\n // If specific teams, let them choose which teams\n if (webBundleType === 'teams' || webBundleType === 'custom') {\n const teams = await installer.getAvailableTeams();\n const { selectedTeams } = await inquirer.prompt([\n {\n type: 'checkbox',\n name: 'selectedTeams',\n message: 'Select team bundles to include:',\n choices: teams.map(t => ({\n name: `${t.icon || 'šŸ“‹'} ${t.name}: ${t.description}`,\n value: t.id,\n checked: webBundleType === 'teams' // Check all if teams-only mode\n })),\n validate: (answer) => {\n if (answer.length < 1) {\n return 'You must select at least one team.';\n }\n return true;\n }\n }\n ]);\n answers.selectedWebBundleTeams = selectedTeams;\n }\n\n // If custom selection, also ask about individual agents\n if (webBundleType === 'custom') {\n const { includeIndividualAgents } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'includeIndividualAgents',\n message: 'Also include individual agent bundles?',\n default: true\n }\n ]);\n answers.includeIndividualAgents = includeIndividualAgents;\n }\n\n const { webBundlesDirectory } = await inquirer.prompt([\n {\n type: 'input',\n name: 'webBundlesDirectory',\n message: 'Enter directory for web bundles:',\n default: `${answers.directory}/web-bundles`,\n validate: (input) => {\n if (!input.trim()) {\n return 'Please enter a valid directory path';\n }\n return true;\n }\n }\n ]);\n answers.webBundlesDirectory = webBundlesDirectory;\n }\n\n answers.includeWebBundles = includeWebBundles;\n\n return answers;\n}\n\nprogram.parse(process.argv);\n\n// Show help if no command provided\nif (!process.argv.slice(2).length) {\n program.outputHelp();\n}"], ["/BMAD-METHOD/tools/installer/lib/file-manager.js", "const fs = require(\"fs-extra\");\nconst path = require(\"path\");\nconst crypto = require(\"crypto\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst { createReadStream, createWriteStream, promises: fsPromises } = require('fs');\nconst { pipeline } = require('stream/promises');\nconst resourceLocator = require('./resource-locator');\n\nclass FileManager {\n constructor() {\n this.manifestDir = \".bmad-core\";\n this.manifestFile = \"install-manifest.yaml\";\n }\n\n async copyFile(source, destination) {\n try {\n await fs.ensureDir(path.dirname(destination));\n \n // Use streaming for large files (> 10MB)\n const stats = await fs.stat(source);\n if (stats.size > 10 * 1024 * 1024) {\n await pipeline(\n createReadStream(source),\n createWriteStream(destination)\n );\n } else {\n await fs.copy(source, destination);\n }\n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy ${source}:`), error.message);\n return false;\n }\n }\n\n async copyDirectory(source, destination) {\n try {\n await fs.ensureDir(destination);\n \n // Use streaming copy for large directories\n const files = await resourceLocator.findFiles('**/*', {\n cwd: source,\n nodir: true\n });\n \n // Process files in batches to avoid memory issues\n const batchSize = 50;\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n await Promise.all(\n batch.map(file => \n this.copyFile(\n path.join(source, file),\n path.join(destination, file)\n )\n )\n );\n }\n return true;\n } catch (error) {\n console.error(\n chalk.red(`Failed to copy directory ${source}:`),\n error.message\n );\n return false;\n }\n }\n\n async copyGlobPattern(pattern, sourceDir, destDir, rootValue = null) {\n const files = await resourceLocator.findFiles(pattern, { cwd: sourceDir });\n const copied = [];\n\n for (const file of files) {\n const sourcePath = path.join(sourceDir, file);\n const destPath = path.join(destDir, file);\n\n // Use root replacement if rootValue is provided and file needs it\n const needsRootReplacement = rootValue && (file.endsWith('.md') || file.endsWith('.yaml') || file.endsWith('.yml'));\n \n let success = false;\n if (needsRootReplacement) {\n success = await this.copyFileWithRootReplacement(sourcePath, destPath, rootValue);\n } else {\n success = await this.copyFile(sourcePath, destPath);\n }\n\n if (success) {\n copied.push(file);\n }\n }\n\n return copied;\n }\n\n async calculateFileHash(filePath) {\n try {\n // Use streaming for hash calculation to reduce memory usage\n const stream = createReadStream(filePath);\n const hash = crypto.createHash(\"sha256\");\n \n for await (const chunk of stream) {\n hash.update(chunk);\n }\n \n return hash.digest(\"hex\").slice(0, 16);\n } catch (error) {\n return null;\n }\n }\n\n async createManifest(installDir, config, files) {\n const manifestPath = path.join(\n installDir,\n this.manifestDir,\n this.manifestFile\n );\n\n // Read version from package.json\n let coreVersion = \"unknown\";\n try {\n const packagePath = path.join(__dirname, '..', '..', '..', 'package.json');\n const packageJson = require(packagePath);\n coreVersion = packageJson.version;\n } catch (error) {\n console.warn(\"Could not read version from package.json, using 'unknown'\");\n }\n\n const manifest = {\n version: coreVersion,\n installed_at: new Date().toISOString(),\n install_type: config.installType,\n agent: config.agent || null,\n ides_setup: config.ides || [],\n expansion_packs: config.expansionPacks || [],\n files: [],\n };\n\n // Add file information\n for (const file of files) {\n const filePath = path.join(installDir, file);\n const hash = await this.calculateFileHash(filePath);\n\n manifest.files.push({\n path: file,\n hash: hash,\n modified: false,\n });\n }\n\n // Write manifest\n await fs.ensureDir(path.dirname(manifestPath));\n await fs.writeFile(manifestPath, yaml.dump(manifest, { indent: 2 }));\n\n return manifest;\n }\n\n async readManifest(installDir) {\n const manifestPath = path.join(\n installDir,\n this.manifestDir,\n this.manifestFile\n );\n\n try {\n const content = await fs.readFile(manifestPath, \"utf8\");\n return yaml.load(content);\n } catch (error) {\n return null;\n }\n }\n\n async readExpansionPackManifest(installDir, packId) {\n const manifestPath = path.join(\n installDir,\n `.${packId}`,\n this.manifestFile\n );\n\n try {\n const content = await fs.readFile(manifestPath, \"utf8\");\n return yaml.load(content);\n } catch (error) {\n return null;\n }\n }\n\n async checkModifiedFiles(installDir, manifest) {\n const modified = [];\n\n for (const file of manifest.files) {\n const filePath = path.join(installDir, file.path);\n const currentHash = await this.calculateFileHash(filePath);\n\n if (currentHash && currentHash !== file.hash) {\n modified.push(file.path);\n }\n }\n\n return modified;\n }\n\n async checkFileIntegrity(installDir, manifest) {\n const result = {\n missing: [],\n modified: []\n };\n\n for (const file of manifest.files) {\n const filePath = path.join(installDir, file.path);\n \n // Skip checking the manifest file itself - it will always be different due to timestamps\n if (file.path.endsWith('install-manifest.yaml')) {\n continue;\n }\n \n if (!(await this.pathExists(filePath))) {\n result.missing.push(file.path);\n } else {\n const currentHash = await this.calculateFileHash(filePath);\n if (currentHash && currentHash !== file.hash) {\n result.modified.push(file.path);\n }\n }\n }\n\n return result;\n }\n\n async backupFile(filePath) {\n const backupPath = filePath + \".bak\";\n let counter = 1;\n let finalBackupPath = backupPath;\n\n // Find a unique backup filename\n while (await fs.pathExists(finalBackupPath)) {\n finalBackupPath = `${filePath}.bak${counter}`;\n counter++;\n }\n\n await fs.copy(filePath, finalBackupPath);\n return finalBackupPath;\n }\n\n async ensureDirectory(dirPath) {\n try {\n await fs.ensureDir(dirPath);\n return true;\n } catch (error) {\n throw error;\n }\n }\n\n async pathExists(filePath) {\n return fs.pathExists(filePath);\n }\n\n async readFile(filePath) {\n return fs.readFile(filePath, \"utf8\");\n }\n\n async writeFile(filePath, content) {\n await fs.ensureDir(path.dirname(filePath));\n await fs.writeFile(filePath, content);\n }\n\n async removeDirectory(dirPath) {\n await fs.remove(dirPath);\n }\n\n async createExpansionPackManifest(installDir, packId, config, files) {\n const manifestPath = path.join(\n installDir,\n `.${packId}`,\n this.manifestFile\n );\n\n const manifest = {\n version: config.expansionPackVersion || require(\"../../../package.json\").version,\n installed_at: new Date().toISOString(),\n install_type: config.installType,\n expansion_pack_id: config.expansionPackId,\n expansion_pack_name: config.expansionPackName,\n ides_setup: config.ides || [],\n files: [],\n };\n\n // Add file information\n for (const file of files) {\n const filePath = path.join(installDir, file);\n const hash = await this.calculateFileHash(filePath);\n\n manifest.files.push({\n path: file,\n hash: hash,\n modified: false,\n });\n }\n\n // Write manifest\n await fs.ensureDir(path.dirname(manifestPath));\n await fs.writeFile(manifestPath, yaml.dump(manifest, { indent: 2 }));\n\n return manifest;\n }\n\n async modifyCoreConfig(installDir, config) {\n const coreConfigPath = path.join(installDir, '.bmad-core', 'core-config.yaml');\n \n try {\n // Read the existing core-config.yaml\n const coreConfigContent = await fs.readFile(coreConfigPath, 'utf8');\n const coreConfig = yaml.load(coreConfigContent);\n \n // Modify sharding settings if provided\n if (config.prdSharded !== undefined) {\n coreConfig.prd.prdSharded = config.prdSharded;\n }\n \n if (config.architectureSharded !== undefined) {\n coreConfig.architecture.architectureSharded = config.architectureSharded;\n }\n \n // Write back the modified config\n await fs.writeFile(coreConfigPath, yaml.dump(coreConfig, { indent: 2 }));\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to modify core-config.yaml:`), error.message);\n return false;\n }\n }\n\n async copyFileWithRootReplacement(source, destination, rootValue) {\n try {\n // Check file size to determine if we should stream\n const stats = await fs.stat(source);\n \n if (stats.size > 5 * 1024 * 1024) { // 5MB threshold\n // Use streaming for large files\n const { Transform } = require('stream');\n const replaceStream = new Transform({\n transform(chunk, encoding, callback) {\n const modified = chunk.toString().replace(/\\{root\\}/g, rootValue);\n callback(null, modified);\n }\n });\n \n await this.ensureDirectory(path.dirname(destination));\n await pipeline(\n createReadStream(source, { encoding: 'utf8' }),\n replaceStream,\n createWriteStream(destination, { encoding: 'utf8' })\n );\n } else {\n // Regular approach for smaller files\n const content = await fsPromises.readFile(source, 'utf8');\n const updatedContent = content.replace(/\\{root\\}/g, rootValue);\n await this.ensureDirectory(path.dirname(destination));\n await fsPromises.writeFile(destination, updatedContent, 'utf8');\n }\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy ${source} with root replacement:`), error.message);\n return false;\n }\n }\n\n async copyDirectoryWithRootReplacement(source, destination, rootValue, fileExtensions = ['.md', '.yaml', '.yml']) {\n try {\n await this.ensureDirectory(destination);\n \n // Get all files in source directory\n const files = await resourceLocator.findFiles('**/*', { \n cwd: source, \n nodir: true \n });\n \n let replacedCount = 0;\n \n for (const file of files) {\n const sourcePath = path.join(source, file);\n const destPath = path.join(destination, file);\n \n // Check if this file type should have {root} replacement\n const shouldReplace = fileExtensions.some(ext => file.endsWith(ext));\n \n if (shouldReplace) {\n if (await this.copyFileWithRootReplacement(sourcePath, destPath, rootValue)) {\n replacedCount++;\n }\n } else {\n // Regular copy for files that don't need replacement\n await this.copyFile(sourcePath, destPath);\n }\n }\n \n if (replacedCount > 0) {\n console.log(chalk.dim(` Processed ${replacedCount} files with {root} replacement`));\n }\n \n return true;\n } catch (error) {\n console.error(chalk.red(`Failed to copy directory ${source} with root replacement:`), error.message);\n return false;\n }\n }\n}\n\nmodule.exports = new FileManager();\n"], ["/BMAD-METHOD/tools/installer/lib/ide-base-setup.js", "/**\n * Base IDE Setup - Common functionality for all IDE setups\n * Reduces duplication and provides shared methods\n */\n\nconst path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst yaml = require(\"js-yaml\");\nconst chalk = require(\"chalk\");\nconst fileManager = require(\"./file-manager\");\nconst resourceLocator = require(\"./resource-locator\");\nconst { extractYamlFromAgent } = require(\"../../lib/yaml-utils\");\n\nclass BaseIdeSetup {\n constructor() {\n this._agentCache = new Map();\n this._pathCache = new Map();\n }\n\n /**\n * Get all agent IDs with caching\n */\n async getAllAgentIds(installDir) {\n const cacheKey = `all-agents:${installDir}`;\n if (this._agentCache.has(cacheKey)) {\n return this._agentCache.get(cacheKey);\n }\n\n const allAgents = new Set();\n \n // Get core agents\n const coreAgents = await this.getCoreAgentIds(installDir);\n coreAgents.forEach(id => allAgents.add(id));\n \n // Get expansion pack agents\n const expansionPacks = await this.getInstalledExpansionPacks(installDir);\n for (const pack of expansionPacks) {\n const packAgents = await this.getExpansionPackAgents(pack.path);\n packAgents.forEach(id => allAgents.add(id));\n }\n \n const result = Array.from(allAgents);\n this._agentCache.set(cacheKey, result);\n return result;\n }\n\n /**\n * Get core agent IDs\n */\n async getCoreAgentIds(installDir) {\n const coreAgents = [];\n const corePaths = [\n path.join(installDir, \".bmad-core\", \"agents\"),\n path.join(installDir, \"bmad-core\", \"agents\")\n ];\n\n for (const agentsDir of corePaths) {\n if (await fileManager.pathExists(agentsDir)) {\n const files = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n coreAgents.push(...files.map(file => path.basename(file, \".md\")));\n break; // Use first found\n }\n }\n\n return coreAgents;\n }\n\n /**\n * Find agent path with caching\n */\n async findAgentPath(agentId, installDir) {\n const cacheKey = `agent-path:${agentId}:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n // Use resource locator for efficient path finding\n let agentPath = await resourceLocator.getAgentPath(agentId);\n \n if (!agentPath) {\n // Check installation-specific paths\n const possiblePaths = [\n path.join(installDir, \".bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"bmad-core\", \"agents\", `${agentId}.md`),\n path.join(installDir, \"common\", \"agents\", `${agentId}.md`)\n ];\n\n for (const testPath of possiblePaths) {\n if (await fileManager.pathExists(testPath)) {\n agentPath = testPath;\n break;\n }\n }\n }\n\n if (agentPath) {\n this._pathCache.set(cacheKey, agentPath);\n }\n return agentPath;\n }\n\n /**\n * Get agent title from metadata\n */\n async getAgentTitle(agentId, installDir) {\n const agentPath = await this.findAgentPath(agentId, installDir);\n if (!agentPath) return agentId;\n\n try {\n const content = await fileManager.readFile(agentPath);\n const yamlContent = extractYamlFromAgent(content);\n if (yamlContent) {\n const metadata = yaml.load(yamlContent);\n return metadata.agent_name || agentId;\n }\n } catch (error) {\n // Fallback to agent ID\n }\n return agentId;\n }\n\n /**\n * Get installed expansion packs\n */\n async getInstalledExpansionPacks(installDir) {\n const cacheKey = `expansion-packs:${installDir}`;\n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const expansionPacks = [];\n \n // Check for dot-prefixed expansion packs\n const dotExpansions = await resourceLocator.findFiles(\".bmad-*\", { cwd: installDir });\n \n for (const dotExpansion of dotExpansions) {\n if (dotExpansion !== \".bmad-core\") {\n const packPath = path.join(installDir, dotExpansion);\n const packName = dotExpansion.substring(1); // remove the dot\n expansionPacks.push({\n name: packName,\n path: packPath\n });\n }\n }\n \n // Check other dot folders that have config.yaml\n const allDotFolders = await resourceLocator.findFiles(\".*\", { cwd: installDir });\n for (const folder of allDotFolders) {\n if (!folder.startsWith(\".bmad-\") && folder !== \".bmad-core\") {\n const packPath = path.join(installDir, folder);\n const configPath = path.join(packPath, \"config.yaml\");\n if (await fileManager.pathExists(configPath)) {\n expansionPacks.push({\n name: folder.substring(1), // remove the dot\n path: packPath\n });\n }\n }\n }\n\n this._pathCache.set(cacheKey, expansionPacks);\n return expansionPacks;\n }\n\n /**\n * Get expansion pack agents\n */\n async getExpansionPackAgents(packPath) {\n const agentsDir = path.join(packPath, \"agents\");\n if (!(await fileManager.pathExists(agentsDir))) {\n return [];\n }\n \n const agentFiles = await resourceLocator.findFiles(\"*.md\", { cwd: agentsDir });\n return agentFiles.map(file => path.basename(file, \".md\"));\n }\n\n /**\n * Create agent rule content (shared logic)\n */\n async createAgentRuleContent(agentId, agentPath, installDir, format = 'mdc') {\n const agentContent = await fileManager.readFile(agentPath);\n const agentTitle = await this.getAgentTitle(agentId, installDir);\n const yamlContent = extractYamlFromAgent(agentContent);\n \n let content = \"\";\n \n if (format === 'mdc') {\n // MDC format for Cursor\n content = \"---\\n\";\n content += \"description: \\n\";\n content += \"globs: []\\n\";\n content += \"alwaysApply: false\\n\";\n content += \"---\\n\\n\";\n content += `# ${agentId.toUpperCase()} Agent Rule\\n\\n`;\n content += `This rule is triggered when the user types \\`@${agentId}\\` and activates the ${agentTitle} agent persona.\\n\\n`;\n content += \"## Agent Activation\\n\\n\";\n content += \"CRITICAL: Read the full YAML, start activation to alter your state of being, follow startup section instructions, stay in this being until told to exit this mode:\\n\\n\";\n content += \"```yaml\\n\";\n content += yamlContent || agentContent.replace(/^#.*$/m, \"\").trim();\n content += \"\\n```\\n\\n\";\n content += \"## File Reference\\n\\n\";\n const relativePath = path.relative(installDir, agentPath).replace(/\\\\/g, '/');\n content += `The complete agent definition is available in [${relativePath}](mdc:${relativePath}).\\n\\n`;\n content += \"## Usage\\n\\n\";\n content += `When the user types \\`@${agentId}\\`, activate this ${agentTitle} persona and follow all instructions defined in the YAML configuration above.\\n`;\n } else if (format === 'claude') {\n // Claude Code format\n content = `# /${agentId} Command\\n\\n`;\n content += `When this command is used, adopt the following agent persona:\\n\\n`;\n content += agentContent;\n }\n \n return content;\n }\n\n /**\n * Clear all caches\n */\n clearCache() {\n this._agentCache.clear();\n this._pathCache.clear();\n }\n}\n\nmodule.exports = BaseIdeSetup;"], ["/BMAD-METHOD/tools/cli.js", "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst WebBuilder = require('./builders/web-builder');\nconst V3ToV4Upgrader = require('./upgraders/v3-to-v4-upgrader');\nconst IdeSetup = require('./installer/lib/ide-setup');\nconst path = require('path');\n\nconst program = new Command();\n\nprogram\n .name('bmad-build')\n .description('BMad-Method build tool for creating web bundles')\n .version('4.0.0');\n\nprogram\n .command('build')\n .description('Build web bundles for agents and teams')\n .option('-a, --agents-only', 'Build only agent bundles')\n .option('-t, --teams-only', 'Build only team bundles')\n .option('-e, --expansions-only', 'Build only expansion pack bundles')\n .option('--no-expansions', 'Skip building expansion packs')\n .option('--no-clean', 'Skip cleaning output directories')\n .action(async (options) => {\n const builder = new WebBuilder({\n rootDir: process.cwd()\n });\n\n try {\n if (options.clean) {\n console.log('Cleaning output directories...');\n await builder.cleanOutputDirs();\n }\n\n if (options.expansionsOnly) {\n console.log('Building expansion pack bundles...');\n await builder.buildAllExpansionPacks({ clean: false });\n } else {\n if (!options.teamsOnly) {\n console.log('Building agent bundles...');\n await builder.buildAgents();\n }\n\n if (!options.agentsOnly) {\n console.log('Building team bundles...');\n await builder.buildTeams();\n }\n\n if (!options.noExpansions) {\n console.log('Building expansion pack bundles...');\n await builder.buildAllExpansionPacks({ clean: false });\n }\n }\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error('Build failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('build:expansions')\n .description('Build web bundles for all expansion packs')\n .option('--expansion ', 'Build specific expansion pack only')\n .option('--no-clean', 'Skip cleaning output directories')\n .action(async (options) => {\n const builder = new WebBuilder({\n rootDir: process.cwd()\n });\n\n try {\n if (options.expansion) {\n console.log(`Building expansion pack: ${options.expansion}`);\n await builder.buildExpansionPack(options.expansion, { clean: options.clean });\n } else {\n console.log('Building all expansion packs...');\n await builder.buildAllExpansionPacks({ clean: options.clean });\n }\n\n console.log('Expansion pack build completed successfully!');\n } catch (error) {\n console.error('Expansion pack build failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('list:agents')\n .description('List all available agents')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n const agents = await builder.resolver.listAgents();\n console.log('Available agents:');\n agents.forEach(agent => console.log(` - ${agent}`));\n });\n\nprogram\n .command('list:expansions')\n .description('List all available expansion packs')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n const expansions = await builder.listExpansionPacks();\n console.log('Available expansion packs:');\n expansions.forEach(expansion => console.log(` - ${expansion}`));\n });\n\nprogram\n .command('validate')\n .description('Validate agent and team configurations')\n .action(async () => {\n const builder = new WebBuilder({ rootDir: process.cwd() });\n try {\n // Validate by attempting to build all agents and teams\n const agents = await builder.resolver.listAgents();\n const teams = await builder.resolver.listTeams();\n \n console.log('Validating agents...');\n for (const agent of agents) {\n await builder.resolver.resolveAgentDependencies(agent);\n console.log(` āœ“ ${agent}`);\n }\n \n console.log('\\nValidating teams...');\n for (const team of teams) {\n await builder.resolver.resolveTeamDependencies(team);\n console.log(` āœ“ ${team}`);\n }\n \n console.log('\\nAll configurations are valid!');\n } catch (error) {\n console.error('Validation failed:', error.message);\n process.exit(1);\n }\n });\n\nprogram\n .command('upgrade')\n .description('Upgrade a BMad-Method V3 project to V4')\n .option('-p, --project ', 'Path to V3 project (defaults to current directory)')\n .option('--dry-run', 'Show what would be changed without making changes')\n .option('--no-backup', 'Skip creating backup (not recommended)')\n .action(async (options) => {\n const upgrader = new V3ToV4Upgrader();\n await upgrader.upgrade({\n projectPath: options.project,\n dryRun: options.dryRun,\n backup: options.backup\n });\n });\n\nprogram\n .command('flatten')\n .description('Flatten codebase to XML format')\n .option('-o, --output ', 'Output file path', 'flattened-codebase.xml')\n .action(async (options) => {\n const flattener = require('./flattener/main');\n await flattener.parseAsync(['flatten', '--output', options.output], { from: 'user' });\n });\n\nprogram.parse();"], ["/BMAD-METHOD/tools/flattener/main.js", "#!/usr/bin/env node\n\nconst { Command } = require('commander');\nconst fs = require('fs-extra');\nconst path = require('node:path');\nconst { glob } = require('glob');\nconst { minimatch } = require('minimatch');\n\n/**\n * Recursively discover all files in a directory\n * @param {string} rootDir - The root directory to scan\n * @returns {Promise} Array of file paths\n */\nasync function discoverFiles(rootDir) {\n try {\n const gitignorePath = path.join(rootDir, '.gitignore');\n const gitignorePatterns = await parseGitignore(gitignorePath);\n\n // Common gitignore patterns that should always be ignored\n const commonIgnorePatterns = [\n // Version control\n '.git/**',\n '.svn/**',\n '.hg/**',\n '.bzr/**',\n\n // Dependencies\n 'node_modules/**',\n 'bower_components/**',\n 'vendor/**',\n 'packages/**',\n\n // Build outputs\n 'build/**',\n 'dist/**',\n 'out/**',\n 'target/**',\n 'bin/**',\n 'obj/**',\n 'release/**',\n 'debug/**',\n\n // Environment and config\n '.env',\n '.env.*',\n '*.env',\n '.config',\n\n // Logs\n 'logs/**',\n '*.log',\n 'npm-debug.log*',\n 'yarn-debug.log*',\n 'yarn-error.log*',\n 'lerna-debug.log*',\n\n // Coverage and testing\n 'coverage/**',\n '.nyc_output/**',\n '.coverage/**',\n 'test-results/**',\n 'junit.xml',\n\n // Cache directories\n '.cache/**',\n '.tmp/**',\n '.temp/**',\n 'tmp/**',\n 'temp/**',\n '.sass-cache/**',\n '.eslintcache',\n '.stylelintcache',\n\n // OS generated files\n '.DS_Store',\n '.DS_Store?',\n '._*',\n '.Spotlight-V100',\n '.Trashes',\n 'ehthumbs.db',\n 'Thumbs.db',\n 'desktop.ini',\n\n // IDE and editor files\n '.vscode/**',\n '.idea/**',\n '*.swp',\n '*.swo',\n '*~',\n '.project',\n '.classpath',\n '.settings/**',\n '*.sublime-project',\n '*.sublime-workspace',\n\n // Package manager files\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Pipfile.lock',\n\n // Runtime and compiled files\n '*.pyc',\n '*.pyo',\n '*.pyd',\n '__pycache__/**',\n '*.class',\n '*.jar',\n '*.war',\n '*.ear',\n '*.o',\n '*.so',\n '*.dll',\n '*.exe',\n\n // Documentation build\n '_site/**',\n '.jekyll-cache/**',\n '.jekyll-metadata',\n\n // Flattener specific outputs\n 'flattened-codebase.xml',\n 'repomix-output.xml'\n ];\n\n const combinedIgnores = [\n ...gitignorePatterns,\n ...commonIgnorePatterns\n ];\n\n // Use glob to recursively find all files, excluding common ignore patterns\n const files = await glob('**/*', {\n cwd: rootDir,\n nodir: true, // Only files, not directories\n dot: true, // Include hidden files\n follow: false, // Don't follow symbolic links\n ignore: combinedIgnores\n });\n\n return files.map(file => path.resolve(rootDir, file));\n } catch (error) {\n console.error('Error discovering files:', error.message);\n return [];\n }\n}\n\n/**\n * Parse .gitignore file and return ignore patterns\n * @param {string} gitignorePath - Path to .gitignore file\n * @returns {Promise} Array of ignore patterns\n */\nasync function parseGitignore(gitignorePath) {\n try {\n if (!await fs.pathExists(gitignorePath)) {\n return [];\n }\n\n const content = await fs.readFile(gitignorePath, 'utf8');\n return content\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line && !line.startsWith('#')) // Remove empty lines and comments\n .map(pattern => {\n // Convert gitignore patterns to glob patterns\n if (pattern.endsWith('/')) {\n return pattern + '**';\n }\n return pattern;\n });\n } catch (error) {\n console.error('Error parsing .gitignore:', error.message);\n return [];\n }\n}\n\n/**\n * Check if a file is binary using file command and heuristics\n * @param {string} filePath - Path to the file\n * @returns {Promise} True if file is binary\n */\nasync function isBinaryFile(filePath) {\n try {\n // First check by file extension\n const binaryExtensions = [\n '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.ico', '.svg',\n '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',\n '.zip', '.tar', '.gz', '.rar', '.7z',\n '.exe', '.dll', '.so', '.dylib',\n '.mp3', '.mp4', '.avi', '.mov', '.wav',\n '.ttf', '.otf', '.woff', '.woff2',\n '.bin', '.dat', '.db', '.sqlite'\n ];\n\n const ext = path.extname(filePath).toLowerCase();\n if (binaryExtensions.includes(ext)) {\n return true;\n }\n\n // For files without clear extensions, try to read a small sample\n const stats = await fs.stat(filePath);\n if (stats.size === 0) {\n return false; // Empty files are considered text\n }\n\n // Read first 1024 bytes to check for null bytes\n const sampleSize = Math.min(1024, stats.size);\n const buffer = await fs.readFile(filePath, { encoding: null, flag: 'r' });\n const sample = buffer.slice(0, sampleSize);\n // If we find null bytes, it's likely binary\n return sample.includes(0);\n } catch (error) {\n console.warn(`Warning: Could not determine if file is binary: ${filePath} - ${error.message}`);\n return false; // Default to text if we can't determine\n }\n}\n\n/**\n * Read and aggregate content from text files\n * @param {string[]} files - Array of file paths\n * @param {string} rootDir - The root directory\n * @param {Object} spinner - Optional spinner instance for progress display\n * @returns {Promise} Object containing file contents and metadata\n */\nasync function aggregateFileContents(files, rootDir, spinner = null) {\n const results = {\n textFiles: [],\n binaryFiles: [],\n errors: [],\n totalFiles: files.length,\n processedFiles: 0\n };\n\n for (const filePath of files) {\n try {\n const relativePath = path.relative(rootDir, filePath);\n\n // Update progress indicator\n if (spinner) {\n spinner.text = `Processing file ${results.processedFiles + 1}/${results.totalFiles}: ${relativePath}`;\n }\n\n const isBinary = await isBinaryFile(filePath);\n\n if (isBinary) {\n results.binaryFiles.push({\n path: relativePath,\n absolutePath: filePath,\n size: (await fs.stat(filePath)).size\n });\n } else {\n // Read text file content\n const content = await fs.readFile(filePath, 'utf8');\n results.textFiles.push({\n path: relativePath,\n absolutePath: filePath,\n content: content,\n size: content.length,\n lines: content.split('\\n').length\n });\n }\n\n results.processedFiles++;\n } catch (error) {\n const relativePath = path.relative(rootDir, filePath);\n const errorInfo = {\n path: relativePath,\n absolutePath: filePath,\n error: error.message\n };\n\n results.errors.push(errorInfo);\n\n // Log warning without interfering with spinner\n if (spinner) {\n spinner.warn(`Warning: Could not read file ${relativePath}: ${error.message}`);\n } else {\n console.warn(`Warning: Could not read file ${relativePath}: ${error.message}`);\n }\n\n results.processedFiles++;\n }\n }\n\n return results;\n}\n\n/**\n * Generate XML output with aggregated file contents using streaming\n * @param {Object} aggregatedContent - The aggregated content object\n * @param {string} outputPath - The output file path\n * @returns {Promise} Promise that resolves when writing is complete\n */\nasync function generateXMLOutput(aggregatedContent, outputPath) {\n const { textFiles } = aggregatedContent;\n\n // Create write stream for efficient memory usage\n const writeStream = fs.createWriteStream(outputPath, { encoding: 'utf8' });\n\n return new Promise((resolve, reject) => {\n writeStream.on('error', reject);\n writeStream.on('finish', resolve);\n\n // Write XML header\n writeStream.write('\\n');\n writeStream.write('\\n');\n\n // Process files one by one to minimize memory usage\n let fileIndex = 0;\n\n const writeNextFile = () => {\n if (fileIndex >= textFiles.length) {\n // All files processed, close XML and stream\n writeStream.write('\\n');\n writeStream.end();\n return;\n }\n\n const file = textFiles[fileIndex];\n fileIndex++;\n\n // Write file opening tag\n writeStream.write(` `);\n\n // Use CDATA for code content, handling CDATA end sequences properly\n if (file.content?.trim()) {\n const indentedContent = indentFileContent(file.content);\n if (file.content.includes(']]>')) {\n // If content contains ]]>, split it and wrap each part in CDATA\n writeStream.write(splitAndWrapCDATA(indentedContent));\n } else {\n writeStream.write(``);\n }\n } else if (file.content) {\n // Handle empty or whitespace-only content\n const indentedContent = indentFileContent(file.content);\n writeStream.write(``);\n }\n\n // Write file closing tag\n writeStream.write('\\n');\n\n // Continue with next file on next tick to avoid stack overflow\n setImmediate(writeNextFile);\n };\n\n // Start processing files\n writeNextFile();\n });\n}\n\n/**\n * Escape XML special characters for attributes\n * @param {string} str - String to escape\n * @returns {string} Escaped string\n */\nfunction escapeXml(str) {\n if (typeof str !== 'string') {\n return String(str);\n }\n return str\n .replace(/&/g, '&')\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Indent file content with 4 spaces for each line\n * @param {string} content - Content to indent\n * @returns {string} Indented content\n */\nfunction indentFileContent(content) {\n if (typeof content !== 'string') {\n return String(content);\n }\n\n // Split content into lines and add 4 spaces of indentation to each line\n return content.split('\\n').map(line => ` ${line}`).join('\\n');\n}\n\n/**\n * Split content containing ]]> and wrap each part in CDATA\n * @param {string} content - Content to process\n * @returns {string} Content with properly wrapped CDATA sections\n */\nfunction splitAndWrapCDATA(content) {\n if (typeof content !== 'string') {\n return String(content);\n }\n\n // Replace ]]> with ]]]]> to escape it within CDATA\n const escapedContent = content.replace(/]]>/g, ']]]]>');\n return ``;\n}\n\n/**\n * Calculate statistics for the processed files\n * @param {Object} aggregatedContent - The aggregated content object\n * @param {number} xmlFileSize - The size of the generated XML file in bytes\n * @returns {Object} Statistics object\n */\nfunction calculateStatistics(aggregatedContent, xmlFileSize) {\n const { textFiles, binaryFiles, errors } = aggregatedContent;\n\n // Calculate total file size in bytes\n const totalTextSize = textFiles.reduce((sum, file) => sum + file.size, 0);\n const totalBinarySize = binaryFiles.reduce((sum, file) => sum + file.size, 0);\n const totalSize = totalTextSize + totalBinarySize;\n\n // Calculate total lines of code\n const totalLines = textFiles.reduce((sum, file) => sum + file.lines, 0);\n\n // Estimate token count (rough approximation: 1 token ā‰ˆ 4 characters)\n const estimatedTokens = Math.ceil(xmlFileSize / 4);\n\n // Format file size\n const formatSize = (bytes) => {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n };\n\n return {\n totalFiles: textFiles.length + binaryFiles.length,\n textFiles: textFiles.length,\n binaryFiles: binaryFiles.length,\n errorFiles: errors.length,\n totalSize: formatSize(totalSize),\n xmlSize: formatSize(xmlFileSize),\n totalLines,\n estimatedTokens: estimatedTokens.toLocaleString()\n };\n}\n\n/**\n * Filter files based on .gitignore patterns\n * @param {string[]} files - Array of file paths\n * @param {string} rootDir - The root directory\n * @returns {Promise} Filtered array of file paths\n */\nasync function filterFiles(files, rootDir) {\n const gitignorePath = path.join(rootDir, '.gitignore');\n const ignorePatterns = await parseGitignore(gitignorePath);\n\n if (ignorePatterns.length === 0) {\n return files;\n }\n\n // Convert absolute paths to relative for pattern matching\n const relativeFiles = files.map(file => path.relative(rootDir, file));\n\n // Separate positive and negative patterns\n const positivePatterns = ignorePatterns.filter(p => !p.startsWith('!'));\n const negativePatterns = ignorePatterns.filter(p => p.startsWith('!')).map(p => p.slice(1));\n\n // Filter out files that match ignore patterns\n const filteredRelative = [];\n\n for (const file of relativeFiles) {\n let shouldIgnore = false;\n\n // First check positive patterns (ignore these files)\n for (const pattern of positivePatterns) {\n if (minimatch(file, pattern)) {\n shouldIgnore = true;\n break;\n }\n }\n\n // Then check negative patterns (don't ignore these files even if they match positive patterns)\n if (shouldIgnore) {\n for (const pattern of negativePatterns) {\n if (minimatch(file, pattern)) {\n shouldIgnore = false;\n break;\n }\n }\n }\n\n if (!shouldIgnore) {\n filteredRelative.push(file);\n }\n }\n\n // Convert back to absolute paths\n return filteredRelative.map(file => path.resolve(rootDir, file));\n}\n\nconst program = new Command();\n\nprogram\n .name('bmad-flatten')\n .description('BMad-Method codebase flattener tool')\n .version('1.0.0')\n .option('-o, --output ', 'Output file path', 'flattened-codebase.xml')\n .action(async (options) => {\n console.log(`Flattening codebase to: ${options.output}`);\n\n try {\n // Import ora dynamically\n const { default: ora } = await import('ora');\n\n // Start file discovery with spinner\n const discoverySpinner = ora('šŸ” Discovering files...').start();\n const files = await discoverFiles(process.cwd());\n const filteredFiles = await filterFiles(files, process.cwd());\n discoverySpinner.succeed(`šŸ“ Found ${filteredFiles.length} files to include`);\n\n // Process files with progress tracking\n console.log('Reading file contents');\n const processingSpinner = ora('šŸ“„ Processing files...').start();\n const aggregatedContent = await aggregateFileContents(filteredFiles, process.cwd(), processingSpinner);\n processingSpinner.succeed(`āœ… Processed ${aggregatedContent.processedFiles}/${filteredFiles.length} files`);\n\n // Log processing results for test validation\n console.log(`Processed ${aggregatedContent.processedFiles}/${filteredFiles.length} files`);\n if (aggregatedContent.errors.length > 0) {\n console.log(`Errors: ${aggregatedContent.errors.length}`);\n }\n console.log(`Text files: ${aggregatedContent.textFiles.length}`);\n if (aggregatedContent.binaryFiles.length > 0) {\n console.log(`Binary files: ${aggregatedContent.binaryFiles.length}`);\n }\n\n // Generate XML output using streaming\n const xmlSpinner = ora('šŸ”§ Generating XML output...').start();\n await generateXMLOutput(aggregatedContent, options.output);\n xmlSpinner.succeed('šŸ“ XML generation completed');\n\n // Calculate and display statistics\n const outputStats = await fs.stat(options.output);\n const stats = calculateStatistics(aggregatedContent, outputStats.size);\n\n // Display completion summary\n console.log('\\nšŸ“Š Completion Summary:');\n console.log(`āœ… Successfully processed ${filteredFiles.length} files into ${options.output}`);\n console.log(`šŸ“ Output file: ${path.resolve(options.output)}`);\n console.log(`šŸ“ Total source size: ${stats.totalSize}`);\n console.log(`šŸ“„ Generated XML size: ${stats.xmlSize}`);\n console.log(`šŸ“ Total lines of code: ${stats.totalLines.toLocaleString()}`);\n console.log(`šŸ”¢ Estimated tokens: ${stats.estimatedTokens}`);\n console.log(`šŸ“Š File breakdown: ${stats.textFiles} text, ${stats.binaryFiles} binary, ${stats.errorFiles} errors`);\n\n } catch (error) {\n console.error('āŒ Critical error:', error.message);\n console.error('An unexpected error occurred.');\n process.exit(1);\n }\n });\n\nif (require.main === module) {\n program.parse();\n}\n\nmodule.exports = program;\n"], ["/BMAD-METHOD/tools/yaml-format.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { execSync } = require('child_process');\n\n// Dynamic import for ES module\nlet chalk;\n\n// Initialize ES modules\nasync function initializeModules() {\n if (!chalk) {\n chalk = (await import('chalk')).default;\n }\n}\n\n/**\n * YAML Formatter and Linter for BMad-Method\n * Formats and validates YAML files and YAML embedded in Markdown\n */\n\nasync function formatYamlContent(content, filename) {\n await initializeModules();\n try {\n // First try to fix common YAML issues\n let fixedContent = content\n // Fix \"commands :\" -> \"commands:\"\n .replace(/^(\\s*)(\\w+)\\s+:/gm, '$1$2:')\n // Fix inconsistent list indentation\n .replace(/^(\\s*)-\\s{3,}/gm, '$1- ');\n \n // Skip auto-fixing for .roomodes files - they have special nested structure\n if (!filename.includes('.roomodes')) {\n fixedContent = fixedContent\n // Fix unquoted list items that contain special characters or multiple parts\n .replace(/^(\\s*)-\\s+(.*)$/gm, (match, indent, content) => {\n // Skip if already quoted\n if (content.startsWith('\"') && content.endsWith('\"')) {\n return match;\n }\n // If the content contains special YAML characters or looks complex, quote it\n // BUT skip if it looks like a proper YAML key-value pair (like \"key: value\")\n if ((content.includes(':') || content.includes('-') || content.includes('{') || content.includes('}')) && \n !content.match(/^\\w+:\\s/)) {\n // Remove any existing quotes first, escape internal quotes, then add proper quotes\n const cleanContent = content.replace(/^[\"']|[\"']$/g, '').replace(/\"/g, '\\\\\"');\n return `${indent}- \"${cleanContent}\"`;\n }\n return match;\n });\n }\n \n // Debug: show what we're trying to parse\n if (fixedContent !== content) {\n console.log(chalk.blue(`šŸ”§ Applied YAML fixes to ${filename}`));\n }\n \n // Parse and re-dump YAML to format it\n const parsed = yaml.load(fixedContent);\n const formatted = yaml.dump(parsed, {\n indent: 2,\n lineWidth: -1, // Disable line wrapping\n noRefs: true,\n sortKeys: false // Preserve key order\n });\n return formatted;\n } catch (error) {\n console.error(chalk.red(`āŒ YAML syntax error in ${filename}:`), error.message);\n console.error(chalk.yellow(`šŸ’” Try manually fixing the YAML structure first`));\n return null;\n }\n}\n\nasync function processMarkdownFile(filePath) {\n await initializeModules();\n const content = fs.readFileSync(filePath, 'utf8');\n let modified = false;\n let newContent = content;\n\n // Fix untyped code blocks by adding 'text' type\n // Match ``` at start of line followed by newline, but only if it's an opening fence\n newContent = newContent.replace(/^```\\n([\\s\\S]*?)\\n```$/gm, '```text\\n$1\\n```');\n if (newContent !== content) {\n modified = true;\n console.log(chalk.blue(`šŸ”§ Added 'text' type to untyped code blocks in ${filePath}`));\n }\n\n // Find YAML code blocks\n const yamlBlockRegex = /```ya?ml\\n([\\s\\S]*?)\\n```/g;\n let match;\n const replacements = [];\n \n while ((match = yamlBlockRegex.exec(newContent)) !== null) {\n const [fullMatch, yamlContent] = match;\n const formatted = await formatYamlContent(yamlContent, filePath);\n if (formatted !== null) {\n // Remove trailing newline that js-yaml adds\n const trimmedFormatted = formatted.replace(/\\n$/, '');\n \n if (trimmedFormatted !== yamlContent) {\n modified = true;\n console.log(chalk.green(`āœ“ Formatted YAML in ${filePath}`));\n }\n \n replacements.push({\n start: match.index,\n end: match.index + fullMatch.length,\n replacement: `\\`\\`\\`yaml\\n${trimmedFormatted}\\n\\`\\`\\``\n });\n }\n }\n \n // Apply replacements in reverse order to maintain indices\n for (let i = replacements.length - 1; i >= 0; i--) {\n const { start, end, replacement } = replacements[i];\n newContent = newContent.slice(0, start) + replacement + newContent.slice(end);\n }\n\n if (modified) {\n fs.writeFileSync(filePath, newContent);\n return true;\n }\n return false;\n}\n\nasync function processYamlFile(filePath) {\n await initializeModules();\n const content = fs.readFileSync(filePath, 'utf8');\n const formatted = await formatYamlContent(content, filePath);\n \n if (formatted === null) {\n return false; // Syntax error\n }\n \n if (formatted !== content) {\n fs.writeFileSync(filePath, formatted);\n return true;\n }\n return false;\n}\n\nasync function lintYamlFile(filePath) {\n await initializeModules();\n try {\n // Use yaml-lint for additional validation\n execSync(`npx yaml-lint \"${filePath}\"`, { stdio: 'pipe' });\n return true;\n } catch (error) {\n console.error(chalk.red(`āŒ YAML lint error in ${filePath}:`));\n console.error(error.stdout?.toString() || error.message);\n return false;\n }\n}\n\nasync function main() {\n await initializeModules();\n const args = process.argv.slice(2);\n const glob = require('glob');\n \n if (args.length === 0) {\n console.error('Usage: node yaml-format.js [file2] ...');\n process.exit(1);\n }\n\n let hasErrors = false;\n let hasChanges = false;\n let filesProcessed = [];\n\n // Expand glob patterns and collect all files\n const allFiles = [];\n for (const arg of args) {\n if (arg.includes('*')) {\n // It's a glob pattern\n const matches = glob.sync(arg);\n allFiles.push(...matches);\n } else {\n // It's a direct file path\n allFiles.push(arg);\n }\n }\n\n for (const filePath of allFiles) {\n if (!fs.existsSync(filePath)) {\n // Skip silently for glob patterns that don't match anything\n if (!args.some(arg => arg.includes('*') && filePath === arg)) {\n console.error(chalk.red(`āŒ File not found: ${filePath}`));\n hasErrors = true;\n }\n continue;\n }\n\n const ext = path.extname(filePath).toLowerCase();\n const basename = path.basename(filePath).toLowerCase();\n \n try {\n let changed = false;\n if (ext === '.md') {\n changed = await processMarkdownFile(filePath);\n } else if (ext === '.yaml' || ext === '.yml' || basename.includes('roomodes') || basename.includes('.yaml') || basename.includes('.yml')) {\n // Handle YAML files and special cases like .roomodes\n changed = await processYamlFile(filePath);\n \n // Also run linting\n const lintPassed = await lintYamlFile(filePath);\n if (!lintPassed) hasErrors = true;\n } else {\n // Skip silently for unsupported files\n continue;\n }\n \n if (changed) {\n hasChanges = true;\n filesProcessed.push(filePath);\n }\n } catch (error) {\n console.error(chalk.red(`āŒ Error processing ${filePath}:`), error.message);\n hasErrors = true;\n }\n }\n\n if (hasChanges) {\n console.log(chalk.green(`\\n✨ YAML formatting completed! Modified ${filesProcessed.length} files:`));\n filesProcessed.forEach(file => console.log(chalk.blue(` šŸ“ ${file}`)));\n }\n\n if (hasErrors) {\n console.error(chalk.red('\\nšŸ’„ Some files had errors. Please fix them before committing.'));\n process.exit(1);\n }\n}\n\nif (require.main === module) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n\nmodule.exports = { formatYamlContent, processMarkdownFile, processYamlFile };"], ["/BMAD-METHOD/tools/installer/lib/resource-locator.js", "/**\n * Resource Locator - Centralized file path resolution and caching\n * Reduces duplicate file system operations and memory usage\n */\n\nconst path = require('node:path');\nconst fs = require('fs-extra');\nconst moduleManager = require('./module-manager');\n\nclass ResourceLocator {\n constructor() {\n this._pathCache = new Map();\n this._globCache = new Map();\n this._bmadCorePath = null;\n this._expansionPacksPath = null;\n }\n\n /**\n * Get the base path for bmad-core\n */\n getBmadCorePath() {\n if (!this._bmadCorePath) {\n this._bmadCorePath = path.join(__dirname, '../../../bmad-core');\n }\n return this._bmadCorePath;\n }\n\n /**\n * Get the base path for expansion packs\n */\n getExpansionPacksPath() {\n if (!this._expansionPacksPath) {\n this._expansionPacksPath = path.join(__dirname, '../../../expansion-packs');\n }\n return this._expansionPacksPath;\n }\n\n /**\n * Find all files matching a pattern, with caching\n * @param {string} pattern - Glob pattern\n * @param {Object} options - Glob options\n * @returns {Promise} Array of matched file paths\n */\n async findFiles(pattern, options = {}) {\n const cacheKey = `${pattern}:${JSON.stringify(options)}`;\n \n if (this._globCache.has(cacheKey)) {\n return this._globCache.get(cacheKey);\n }\n\n const { glob } = await moduleManager.getModules(['glob']);\n const files = await glob(pattern, options);\n \n // Cache for 5 minutes\n this._globCache.set(cacheKey, files);\n setTimeout(() => this._globCache.delete(cacheKey), 5 * 60 * 1000);\n \n return files;\n }\n\n /**\n * Get agent path with caching\n * @param {string} agentId - Agent identifier\n * @returns {Promise} Path to agent file or null if not found\n */\n async getAgentPath(agentId) {\n const cacheKey = `agent:${agentId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n // Check in bmad-core\n let agentPath = path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n if (await fs.pathExists(agentPath)) {\n this._pathCache.set(cacheKey, agentPath);\n return agentPath;\n }\n\n // Check in expansion packs\n const expansionPacks = await this.getExpansionPacks();\n for (const pack of expansionPacks) {\n agentPath = path.join(pack.path, 'agents', `${agentId}.md`);\n if (await fs.pathExists(agentPath)) {\n this._pathCache.set(cacheKey, agentPath);\n return agentPath;\n }\n }\n\n return null;\n }\n\n /**\n * Get available agents with metadata\n * @returns {Promise} Array of agent objects\n */\n async getAvailableAgents() {\n const cacheKey = 'all-agents';\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const agents = [];\n const yaml = require('js-yaml');\n const { extractYamlFromAgent } = require('../../lib/yaml-utils');\n\n // Get agents from bmad-core\n const coreAgents = await this.findFiles('agents/*.md', {\n cwd: this.getBmadCorePath()\n });\n\n for (const agentFile of coreAgents) {\n const content = await fs.readFile(\n path.join(this.getBmadCorePath(), agentFile),\n 'utf8'\n );\n const yamlContent = extractYamlFromAgent(content);\n if (yamlContent) {\n try {\n const metadata = yaml.load(yamlContent);\n agents.push({\n id: path.basename(agentFile, '.md'),\n name: metadata.agent_name || path.basename(agentFile, '.md'),\n description: metadata.description || 'No description available',\n source: 'core'\n });\n } catch (e) {\n // Skip invalid agents\n }\n }\n }\n\n // Cache for 10 minutes\n this._pathCache.set(cacheKey, agents);\n setTimeout(() => this._pathCache.delete(cacheKey), 10 * 60 * 1000);\n\n return agents;\n }\n\n /**\n * Get available expansion packs\n * @returns {Promise} Array of expansion pack objects\n */\n async getExpansionPacks() {\n const cacheKey = 'expansion-packs';\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const packs = [];\n const expansionPacksPath = this.getExpansionPacksPath();\n\n if (await fs.pathExists(expansionPacksPath)) {\n const entries = await fs.readdir(expansionPacksPath, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory()) {\n const configPath = path.join(expansionPacksPath, entry.name, 'config.yaml');\n if (await fs.pathExists(configPath)) {\n try {\n const yaml = require('js-yaml');\n const config = yaml.load(await fs.readFile(configPath, 'utf8'));\n packs.push({\n id: entry.name,\n name: config.name || entry.name,\n version: config.version || '1.0.0',\n description: config.description || 'No description available',\n shortTitle: config['short-title'] || config.description || 'No description available',\n author: config.author || 'Unknown',\n path: path.join(expansionPacksPath, entry.name)\n });\n } catch (e) {\n // Skip invalid packs\n }\n }\n }\n }\n }\n\n // Cache for 10 minutes\n this._pathCache.set(cacheKey, packs);\n setTimeout(() => this._pathCache.delete(cacheKey), 10 * 60 * 1000);\n\n return packs;\n }\n\n /**\n * Get team configuration\n * @param {string} teamId - Team identifier\n * @returns {Promise} Team configuration or null\n */\n async getTeamConfig(teamId) {\n const cacheKey = `team:${teamId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const teamPath = path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n \n if (await fs.pathExists(teamPath)) {\n try {\n const yaml = require('js-yaml');\n const content = await fs.readFile(teamPath, 'utf8');\n const config = yaml.load(content);\n this._pathCache.set(cacheKey, config);\n return config;\n } catch (e) {\n return null;\n }\n }\n\n return null;\n }\n\n /**\n * Get resource dependencies for an agent\n * @param {string} agentId - Agent identifier\n * @returns {Promise} Dependencies object\n */\n async getAgentDependencies(agentId) {\n const cacheKey = `deps:${agentId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const agentPath = await this.getAgentPath(agentId);\n if (!agentPath) {\n return { all: [], byType: {} };\n }\n\n const content = await fs.readFile(agentPath, 'utf8');\n const { extractYamlFromAgent } = require('../../lib/yaml-utils');\n const yamlContent = extractYamlFromAgent(content);\n\n if (!yamlContent) {\n return { all: [], byType: {} };\n }\n\n try {\n const yaml = require('js-yaml');\n const metadata = yaml.load(yamlContent);\n const dependencies = metadata.dependencies || {};\n \n // Flatten dependencies\n const allDeps = [];\n const byType = {};\n \n for (const [type, deps] of Object.entries(dependencies)) {\n if (Array.isArray(deps)) {\n byType[type] = deps;\n for (const dep of deps) {\n allDeps.push(`.bmad-core/${type}/${dep}`);\n }\n }\n }\n\n const result = { all: allDeps, byType };\n this._pathCache.set(cacheKey, result);\n return result;\n } catch (e) {\n return { all: [], byType: {} };\n }\n }\n\n /**\n * Clear all caches to free memory\n */\n clearCache() {\n this._pathCache.clear();\n this._globCache.clear();\n }\n\n /**\n * Get IDE configuration\n * @param {string} ideId - IDE identifier\n * @returns {Promise} IDE configuration or null\n */\n async getIdeConfig(ideId) {\n const cacheKey = `ide:${ideId}`;\n \n if (this._pathCache.has(cacheKey)) {\n return this._pathCache.get(cacheKey);\n }\n\n const idePath = path.join(this.getBmadCorePath(), 'ide-rules', `${ideId}.yaml`);\n \n if (await fs.pathExists(idePath)) {\n try {\n const yaml = require('js-yaml');\n const content = await fs.readFile(idePath, 'utf8');\n const config = yaml.load(content);\n this._pathCache.set(cacheKey, config);\n return config;\n } catch (e) {\n return null;\n }\n }\n\n return null;\n }\n}\n\n// Singleton instance\nconst resourceLocator = new ResourceLocator();\n\nmodule.exports = resourceLocator;"], ["/BMAD-METHOD/tools/installer/lib/config-loader.js", "const fs = require('fs-extra');\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { extractYamlFromAgent } = require('../../lib/yaml-utils');\n\nclass ConfigLoader {\n constructor() {\n this.configPath = path.join(__dirname, '..', 'config', 'install.config.yaml');\n this.config = null;\n }\n\n async load() {\n if (this.config) return this.config;\n \n try {\n const configContent = await fs.readFile(this.configPath, 'utf8');\n this.config = yaml.load(configContent);\n return this.config;\n } catch (error) {\n throw new Error(`Failed to load configuration: ${error.message}`);\n }\n }\n\n async getInstallationOptions() {\n const config = await this.load();\n return config['installation-options'] || {};\n }\n\n async getAvailableAgents() {\n const agentsDir = path.join(this.getBmadCorePath(), 'agents');\n \n try {\n const entries = await fs.readdir(agentsDir, { withFileTypes: true });\n const agents = [];\n \n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.md')) {\n const agentPath = path.join(agentsDir, entry.name);\n const agentId = path.basename(entry.name, '.md');\n \n try {\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML block from agent file\n const yamlContentText = extractYamlFromAgent(agentContent);\n if (yamlContentText) {\n const yamlContent = yaml.load(yamlContentText);\n const agentConfig = yamlContent.agent || {};\n \n agents.push({\n id: agentId,\n name: agentConfig.title || agentConfig.name || agentId,\n file: `bmad-core/agents/${entry.name}`,\n description: agentConfig.whenToUse || 'No description available'\n });\n }\n } catch (error) {\n console.warn(`Failed to read agent ${entry.name}: ${error.message}`);\n }\n }\n }\n \n // Sort agents by name for consistent display\n agents.sort((a, b) => a.name.localeCompare(b.name));\n \n return agents;\n } catch (error) {\n console.warn(`Failed to read agents directory: ${error.message}`);\n return [];\n }\n }\n\n async getAvailableExpansionPacks() {\n const expansionPacksDir = path.join(this.getBmadCorePath(), '..', 'expansion-packs');\n \n try {\n const entries = await fs.readdir(expansionPacksDir, { withFileTypes: true });\n const expansionPacks = [];\n \n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n const packPath = path.join(expansionPacksDir, entry.name);\n const configPath = path.join(packPath, 'config.yaml');\n \n try {\n // Read config.yaml\n const configContent = await fs.readFile(configPath, 'utf8');\n const config = yaml.load(configContent);\n \n expansionPacks.push({\n id: entry.name,\n name: config.name || entry.name,\n description: config['short-title'] || config.description || 'No description available',\n fullDescription: config.description || config['short-title'] || 'No description available',\n version: config.version || '1.0.0',\n author: config.author || 'BMad Team',\n packPath: packPath,\n dependencies: config.dependencies?.agents || []\n });\n } catch (error) {\n // Fallback if config.yaml doesn't exist or can't be read\n console.warn(`Failed to read config for expansion pack ${entry.name}: ${error.message}`);\n \n // Try to derive info from directory name as fallback\n const name = entry.name\n .split('-')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n \n expansionPacks.push({\n id: entry.name,\n name: name,\n description: 'No description available',\n fullDescription: 'No description available',\n version: '1.0.0',\n author: 'BMad Team',\n packPath: packPath,\n dependencies: []\n });\n }\n }\n }\n \n return expansionPacks;\n } catch (error) {\n console.warn(`Failed to read expansion packs directory: ${error.message}`);\n return [];\n }\n }\n\n async getAgentDependencies(agentId) {\n // Use DependencyResolver to dynamically parse agent dependencies\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n \n const agentDeps = await resolver.resolveAgentDependencies(agentId);\n \n // Convert to flat list of file paths\n const depPaths = [];\n \n // Core files and utilities are included automatically by DependencyResolver\n \n // Add agent file itself is already handled by installer\n \n // Add all resolved resources\n for (const resource of agentDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n \n return depPaths;\n }\n\n async getIdeConfiguration(ide) {\n const config = await this.load();\n const ideConfigs = config['ide-configurations'] || {};\n return ideConfigs[ide] || null;\n }\n\n getBmadCorePath() {\n // Get the path to bmad-core relative to the installer (now under tools)\n return path.join(__dirname, '..', '..', '..', 'bmad-core');\n }\n\n getDistPath() {\n // Get the path to dist directory relative to the installer\n return path.join(__dirname, '..', '..', '..', 'dist');\n }\n\n getAgentPath(agentId) {\n return path.join(this.getBmadCorePath(), 'agents', `${agentId}.md`);\n }\n\n async getAvailableTeams() {\n const teamsDir = path.join(this.getBmadCorePath(), 'agent-teams');\n \n try {\n const entries = await fs.readdir(teamsDir, { withFileTypes: true });\n const teams = [];\n \n for (const entry of entries) {\n if (entry.isFile() && entry.name.endsWith('.yaml')) {\n const teamPath = path.join(teamsDir, entry.name);\n \n try {\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n \n if (teamConfig.bundle) {\n teams.push({\n id: path.basename(entry.name, '.yaml'),\n name: teamConfig.bundle.name || entry.name,\n description: teamConfig.bundle.description || 'Team configuration',\n icon: teamConfig.bundle.icon || 'šŸ“‹'\n });\n }\n } catch (error) {\n console.warn(`Warning: Could not load team config ${entry.name}: ${error.message}`);\n }\n }\n }\n \n return teams;\n } catch (error) {\n console.warn(`Warning: Could not scan teams directory: ${error.message}`);\n return [];\n }\n }\n\n getTeamPath(teamId) {\n return path.join(this.getBmadCorePath(), 'agent-teams', `${teamId}.yaml`);\n }\n\n async getTeamDependencies(teamId) {\n // Use DependencyResolver to dynamically parse team dependencies\n const DependencyResolver = require('../../lib/dependency-resolver');\n const resolver = new DependencyResolver(path.join(__dirname, '..', '..', '..'));\n \n try {\n const teamDeps = await resolver.resolveTeamDependencies(teamId);\n \n // Convert to flat list of file paths\n const depPaths = [];\n \n // Add team config file\n depPaths.push(`.bmad-core/agent-teams/${teamId}.yaml`);\n \n // Add all agents\n for (const agent of teamDeps.agents) {\n const filePath = `.bmad-core/agents/${agent.id}.md`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n \n // Add all resolved resources\n for (const resource of teamDeps.resources) {\n const filePath = `.bmad-core/${resource.type}/${resource.id}.${resource.type === 'workflows' ? 'yaml' : 'md'}`;\n if (!depPaths.includes(filePath)) {\n depPaths.push(filePath);\n }\n }\n \n return depPaths;\n } catch (error) {\n throw new Error(`Failed to resolve team dependencies for ${teamId}: ${error.message}`);\n }\n }\n}\n\nmodule.exports = new ConfigLoader();"], ["/BMAD-METHOD/tools/lib/dependency-resolver.js", "const fs = require('fs').promises;\nconst path = require('path');\nconst yaml = require('js-yaml');\nconst { extractYamlFromAgent } = require('./yaml-utils');\n\nclass DependencyResolver {\n constructor(rootDir) {\n this.rootDir = rootDir;\n this.bmadCore = path.join(rootDir, 'bmad-core');\n this.common = path.join(rootDir, 'common');\n this.cache = new Map();\n }\n\n async resolveAgentDependencies(agentId) {\n const agentPath = path.join(this.bmadCore, 'agents', `${agentId}.md`);\n const agentContent = await fs.readFile(agentPath, 'utf8');\n \n // Extract YAML from markdown content with command cleaning\n const yamlContent = extractYamlFromAgent(agentContent, true);\n if (!yamlContent) {\n throw new Error(`No YAML configuration found in agent ${agentId}`);\n }\n \n const agentConfig = yaml.load(yamlContent);\n \n const dependencies = {\n agent: {\n id: agentId,\n path: agentPath,\n content: agentContent,\n config: agentConfig\n },\n resources: []\n };\n\n // Personas are now embedded in agent configs, no need to resolve separately\n\n // Resolve other dependencies\n const depTypes = ['tasks', 'templates', 'checklists', 'data', 'utils'];\n for (const depType of depTypes) {\n const deps = agentConfig.dependencies?.[depType] || [];\n for (const depId of deps) {\n const resource = await this.loadResource(depType, depId);\n if (resource) dependencies.resources.push(resource);\n }\n }\n\n return dependencies;\n }\n\n async resolveTeamDependencies(teamId) {\n const teamPath = path.join(this.bmadCore, 'agent-teams', `${teamId}.yaml`);\n const teamContent = await fs.readFile(teamPath, 'utf8');\n const teamConfig = yaml.load(teamContent);\n \n const dependencies = {\n team: {\n id: teamId,\n path: teamPath,\n content: teamContent,\n config: teamConfig\n },\n agents: [],\n resources: new Map() // Use Map to deduplicate resources\n };\n\n // Always add bmad-orchestrator agent first if it's a team\n const bmadAgent = await this.resolveAgentDependencies('bmad-orchestrator');\n dependencies.agents.push(bmadAgent.agent);\n bmadAgent.resources.forEach(res => {\n dependencies.resources.set(res.path, res);\n });\n\n // Resolve all agents in the team\n let agentsToResolve = teamConfig.agents || [];\n \n // Handle wildcard \"*\" - include all agents except bmad-master\n if (agentsToResolve.includes('*')) {\n const allAgents = await this.listAgents();\n // Remove wildcard and add all agents except those already in the list and bmad-master\n agentsToResolve = agentsToResolve.filter(a => a !== '*');\n for (const agent of allAgents) {\n if (!agentsToResolve.includes(agent) && agent !== 'bmad-master') {\n agentsToResolve.push(agent);\n }\n }\n }\n \n for (const agentId of agentsToResolve) {\n if (agentId === 'bmad-orchestrator' || agentId === 'bmad-master') continue; // Already added or excluded\n const agentDeps = await this.resolveAgentDependencies(agentId);\n dependencies.agents.push(agentDeps.agent);\n \n // Add resources with deduplication\n agentDeps.resources.forEach(res => {\n dependencies.resources.set(res.path, res);\n });\n }\n\n // Resolve workflows\n for (const workflowId of teamConfig.workflows || []) {\n const resource = await this.loadResource('workflows', workflowId);\n if (resource) dependencies.resources.set(resource.path, resource);\n }\n\n // Convert Map back to array\n dependencies.resources = Array.from(dependencies.resources.values());\n\n return dependencies;\n }\n\n async loadResource(type, id) {\n const cacheKey = `${type}#${id}`;\n if (this.cache.has(cacheKey)) {\n return this.cache.get(cacheKey);\n }\n\n try {\n let content = null;\n let filePath = null;\n\n // First try bmad-core\n try {\n filePath = path.join(this.bmadCore, type, id);\n content = await fs.readFile(filePath, 'utf8');\n } catch (e) {\n // If not found in bmad-core, try common folder\n try {\n filePath = path.join(this.common, type, id);\n content = await fs.readFile(filePath, 'utf8');\n } catch (e2) {\n // File not found in either location\n }\n }\n\n if (!content) {\n console.warn(`Resource not found: ${type}/${id}`);\n return null;\n }\n\n const resource = {\n type,\n id,\n path: filePath,\n content\n };\n\n this.cache.set(cacheKey, resource);\n return resource;\n } catch (error) {\n console.error(`Error loading resource ${type}/${id}:`, error.message);\n return null;\n }\n }\n\n async listAgents() {\n try {\n const files = await fs.readdir(path.join(this.bmadCore, 'agents'));\n return files\n .filter(f => f.endsWith('.md'))\n .map(f => f.replace('.md', ''));\n } catch (error) {\n return [];\n }\n }\n\n async listTeams() {\n try {\n const files = await fs.readdir(path.join(this.bmadCore, 'agent-teams'));\n return files\n .filter(f => f.endsWith('.yaml'))\n .map(f => f.replace('.yaml', ''));\n } catch (error) {\n return [];\n }\n }\n}\n\nmodule.exports = DependencyResolver;\n"], ["/BMAD-METHOD/tools/bump-all-versions.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\nconst args = process.argv.slice(2);\nconst bumpType = args[0] || 'minor'; // default to minor\n\nif (!['major', 'minor', 'patch'].includes(bumpType)) {\n console.log('Usage: node bump-all-versions.js [major|minor|patch]');\n console.log('Default: minor');\n process.exit(1);\n}\n\nfunction bumpVersion(currentVersion, type) {\n const [major, minor, patch] = currentVersion.split('.').map(Number);\n \n switch (type) {\n case 'major':\n return `${major + 1}.0.0`;\n case 'minor':\n return `${major}.${minor + 1}.0`;\n case 'patch':\n return `${major}.${minor}.${patch + 1}`;\n default:\n return currentVersion;\n }\n}\n\nasync function bumpAllVersions() {\n const updatedItems = [];\n \n // First, bump the core version (package.json)\n const packagePath = path.join(__dirname, '..', 'package.json');\n try {\n const packageContent = fs.readFileSync(packagePath, 'utf8');\n const packageJson = JSON.parse(packageContent);\n const oldCoreVersion = packageJson.version || '1.0.0';\n const newCoreVersion = bumpVersion(oldCoreVersion, bumpType);\n \n packageJson.version = newCoreVersion;\n \n fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2) + '\\n');\n \n updatedItems.push({ type: 'core', name: 'BMad Core', oldVersion: oldCoreVersion, newVersion: newCoreVersion });\n console.log(`āœ“ BMad Core (package.json): ${oldCoreVersion} → ${newCoreVersion}`);\n } catch (error) {\n console.error(`āœ— Failed to update BMad Core: ${error.message}`);\n }\n \n // Then, bump all expansion packs\n const expansionPacksDir = path.join(__dirname, '..', 'expansion-packs');\n \n try {\n const entries = fs.readdirSync(expansionPacksDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'README.md') {\n const packId = entry.name;\n const configPath = path.join(expansionPacksDir, packId, 'config.yaml');\n \n if (fs.existsSync(configPath)) {\n try {\n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n const oldVersion = config.version || '1.0.0';\n const newVersion = bumpVersion(oldVersion, bumpType);\n \n config.version = newVersion;\n \n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n \n updatedItems.push({ type: 'expansion', name: packId, oldVersion, newVersion });\n console.log(`āœ“ ${packId}: ${oldVersion} → ${newVersion}`);\n \n } catch (error) {\n console.error(`āœ— Failed to update ${packId}: ${error.message}`);\n }\n }\n }\n }\n \n if (updatedItems.length > 0) {\n const coreCount = updatedItems.filter(i => i.type === 'core').length;\n const expansionCount = updatedItems.filter(i => i.type === 'expansion').length;\n \n console.log(`\\nāœ“ Successfully bumped ${updatedItems.length} item(s) with ${bumpType} version bump`);\n if (coreCount > 0) console.log(` - ${coreCount} core`);\n if (expansionCount > 0) console.log(` - ${expansionCount} expansion pack(s)`);\n \n console.log('\\nNext steps:');\n console.log('1. Test the changes');\n console.log('2. Commit: git add -A && git commit -m \"chore: bump all versions (' + bumpType + ')\"');\n } else {\n console.log('No items found to update');\n }\n \n } catch (error) {\n console.error('Error reading expansion packs directory:', error.message);\n process.exit(1);\n }\n}\n\nbumpAllVersions();"], ["/BMAD-METHOD/tools/installer/lib/module-manager.js", "/**\n * Module Manager - Centralized dynamic import management\n * Handles loading and caching of ES modules to reduce memory overhead\n */\n\nclass ModuleManager {\n constructor() {\n this._cache = new Map();\n this._loadingPromises = new Map();\n }\n\n /**\n * Initialize all commonly used ES modules at once\n * @returns {Promise} Object containing all loaded modules\n */\n async initializeCommonModules() {\n const modules = await Promise.all([\n this.getModule('chalk'),\n this.getModule('ora'),\n this.getModule('inquirer')\n ]);\n\n return {\n chalk: modules[0],\n ora: modules[1],\n inquirer: modules[2]\n };\n }\n\n /**\n * Get a module by name, with caching\n * @param {string} moduleName - Name of the module to load\n * @returns {Promise} The loaded module\n */\n async getModule(moduleName) {\n // Return from cache if available\n if (this._cache.has(moduleName)) {\n return this._cache.get(moduleName);\n }\n\n // If already loading, return the existing promise\n if (this._loadingPromises.has(moduleName)) {\n return this._loadingPromises.get(moduleName);\n }\n\n // Start loading the module\n const loadPromise = this._loadModule(moduleName);\n this._loadingPromises.set(moduleName, loadPromise);\n\n try {\n const module = await loadPromise;\n this._cache.set(moduleName, module);\n this._loadingPromises.delete(moduleName);\n return module;\n } catch (error) {\n this._loadingPromises.delete(moduleName);\n throw error;\n }\n }\n\n /**\n * Internal method to load a specific module\n * @private\n */\n async _loadModule(moduleName) {\n switch (moduleName) {\n case 'chalk':\n return (await import('chalk')).default;\n case 'ora':\n return (await import('ora')).default;\n case 'inquirer':\n return (await import('inquirer')).default;\n case 'glob':\n return (await import('glob')).glob;\n case 'globSync':\n return (await import('glob')).globSync;\n default:\n throw new Error(`Unknown module: ${moduleName}`);\n }\n }\n\n /**\n * Clear the module cache to free memory\n */\n clearCache() {\n this._cache.clear();\n this._loadingPromises.clear();\n }\n\n /**\n * Get multiple modules at once\n * @param {string[]} moduleNames - Array of module names\n * @returns {Promise} Object with module names as keys\n */\n async getModules(moduleNames) {\n const modules = await Promise.all(\n moduleNames.map(name => this.getModule(name))\n );\n\n return moduleNames.reduce((acc, name, index) => {\n acc[name] = modules[index];\n return acc;\n }, {});\n }\n}\n\n// Singleton instance\nconst moduleManager = new ModuleManager();\n\nmodule.exports = moduleManager;"], ["/BMAD-METHOD/tools/version-bump.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst { execSync } = require('child_process');\nconst path = require('path');\n\n// Dynamic import for ES module\nlet chalk;\n\n// Initialize ES modules\nasync function initializeModules() {\n if (!chalk) {\n chalk = (await import('chalk')).default;\n }\n}\n\n/**\n * Simple version bumping script for BMad-Method\n * Usage: node tools/version-bump.js [patch|minor|major]\n */\n\nfunction getCurrentVersion() {\n const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));\n return packageJson.version;\n}\n\nasync function bumpVersion(type = 'patch') {\n await initializeModules();\n \n const validTypes = ['patch', 'minor', 'major'];\n if (!validTypes.includes(type)) {\n console.error(chalk.red(`Invalid version type: ${type}. Use: ${validTypes.join(', ')}`));\n process.exit(1);\n }\n\n console.log(chalk.yellow('āš ļø Manual version bumping is disabled.'));\n console.log(chalk.blue('šŸ¤– This project uses semantic-release for automated versioning.'));\n console.log('');\n console.log(chalk.bold('To create a new release, use conventional commits:'));\n console.log(chalk.cyan(' feat: new feature (minor version bump)'));\n console.log(chalk.cyan(' fix: bug fix (patch version bump)'));\n console.log(chalk.cyan(' feat!: breaking change (major version bump)'));\n console.log('');\n console.log(chalk.dim('Example: git commit -m \"feat: add new installer features\"'));\n console.log(chalk.dim('Then push to main branch to trigger automatic release.'));\n \n return null;\n}\n\nasync function main() {\n await initializeModules();\n \n const type = process.argv[2] || 'patch';\n const currentVersion = getCurrentVersion();\n \n console.log(chalk.blue(`Current version: ${currentVersion}`));\n \n // Check if working directory is clean\n try {\n execSync('git diff-index --quiet HEAD --');\n } catch (error) {\n console.error(chalk.red('āŒ Working directory is not clean. Commit your changes first.'));\n process.exit(1);\n }\n \n const newVersion = await bumpVersion(type);\n \n console.log(chalk.green(`\\nšŸŽ‰ Version bump complete!`));\n console.log(chalk.blue(`šŸ“¦ ${currentVersion} → ${newVersion}`));\n}\n\nif (require.main === module) {\n main().catch(error => {\n console.error('Error:', error);\n process.exit(1);\n });\n}\n\nmodule.exports = { bumpVersion, getCurrentVersion };"], ["/BMAD-METHOD/tools/bump-expansion-version.js", "#!/usr/bin/env node\n\n// Load required modules\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\n// Parse CLI arguments\nconst args = process.argv.slice(2);\nconst packId = args[0];\nconst bumpType = args[1] || 'minor';\n\n// Validate arguments\nif (!packId || args.length > 2) {\n console.log('Usage: node bump-expansion-version.js [major|minor|patch]');\n console.log('Default: minor');\n console.log('Example: node bump-expansion-version.js bmad-creator-tools patch');\n process.exit(1);\n}\n\nif (!['major', 'minor', 'patch'].includes(bumpType)) {\n console.error('Error: Bump type must be major, minor, or patch');\n process.exit(1);\n}\n\n// Version bump logic\nfunction bumpVersion(currentVersion, type) {\n const [major, minor, patch] = currentVersion.split('.').map(Number);\n\n switch (type) {\n case 'major': return `${major + 1}.0.0`;\n case 'minor': return `${major}.${minor + 1}.0`;\n case 'patch': return `${major}.${minor}.${patch + 1}`;\n default: return currentVersion;\n }\n}\n\n// Main function to bump version\nasync function updateVersion() {\n const configPath = path.join(__dirname, '..', 'expansion-packs', packId, 'config.yaml');\n\n // Check if config exists\n if (!fs.existsSync(configPath)) {\n console.error(`Error: Expansion pack '${packId}' not found`);\n console.log('\\nAvailable expansion packs:');\n\n const packsDir = path.join(__dirname, '..', 'expansion-packs');\n const entries = fs.readdirSync(packsDir, { withFileTypes: true });\n\n entries.forEach(entry => {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n console.log(` - ${entry.name}`);\n }\n });\n\n process.exit(1);\n }\n\n try {\n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n\n const oldVersion = config.version || '1.0.0';\n const newVersion = bumpVersion(oldVersion, bumpType);\n\n config.version = newVersion;\n\n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n\n console.log(`āœ“ ${packId}: ${oldVersion} → ${newVersion}`);\n console.log(`\\nāœ“ Successfully bumped ${packId} with ${bumpType} version bump`);\n console.log('\\nNext steps:');\n console.log(`1. Test the changes`);\n console.log(`2. Commit: git add -A && git commit -m \"chore: bump ${packId} version (${bumpType})\"`);\n\n } catch (error) {\n console.error('Error updating version:', error.message);\n process.exit(1);\n }\n}\n\nupdateVersion();\n"], ["/BMAD-METHOD/tools/update-expansion-version.js", "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst yaml = require('js-yaml');\n\nconst args = process.argv.slice(2);\n\nif (args.length < 2) {\n console.log('Usage: node update-expansion-version.js ');\n console.log('Example: node update-expansion-version.js bmad-creator-tools 1.1.0');\n process.exit(1);\n}\n\nconst [packId, newVersion] = args;\n\n// Validate version format\nif (!/^\\d+\\.\\d+\\.\\d+$/.test(newVersion)) {\n console.error('Error: Version must be in format X.Y.Z (e.g., 1.2.3)');\n process.exit(1);\n}\n\nasync function updateVersion() {\n try {\n // Update in config.yaml\n const configPath = path.join(__dirname, '..', 'expansion-packs', packId, 'config.yaml');\n \n if (!fs.existsSync(configPath)) {\n console.error(`Error: Expansion pack '${packId}' not found`);\n process.exit(1);\n }\n \n const configContent = fs.readFileSync(configPath, 'utf8');\n const config = yaml.load(configContent);\n const oldVersion = config.version || 'unknown';\n \n config.version = newVersion;\n \n const updatedYaml = yaml.dump(config, { indent: 2 });\n fs.writeFileSync(configPath, updatedYaml);\n \n console.log(`āœ“ Updated ${packId}/config.yaml: ${oldVersion} → ${newVersion}`);\n console.log(`\\nāœ“ Successfully updated ${packId} to version ${newVersion}`);\n console.log('\\nNext steps:');\n console.log('1. Test the changes');\n console.log('2. Commit: git add -A && git commit -m \"chore: bump ' + packId + ' to v' + newVersion + '\"');\n \n } catch (error) {\n console.error('Error updating version:', error.message);\n process.exit(1);\n }\n}\n\nupdateVersion();"], ["/BMAD-METHOD/tools/installer/lib/memory-profiler.js", "/**\n * Memory Profiler - Track memory usage during installation\n * Helps identify memory leaks and optimize resource usage\n */\n\nconst v8 = require('v8');\n\nclass MemoryProfiler {\n constructor() {\n this.checkpoints = [];\n this.startTime = Date.now();\n this.peakMemory = 0;\n }\n\n /**\n * Create a memory checkpoint\n * @param {string} label - Label for this checkpoint\n */\n checkpoint(label) {\n const memUsage = process.memoryUsage();\n const heapStats = v8.getHeapStatistics();\n \n const checkpoint = {\n label,\n timestamp: Date.now() - this.startTime,\n memory: {\n rss: this.formatBytes(memUsage.rss),\n heapTotal: this.formatBytes(memUsage.heapTotal),\n heapUsed: this.formatBytes(memUsage.heapUsed),\n external: this.formatBytes(memUsage.external),\n arrayBuffers: this.formatBytes(memUsage.arrayBuffers || 0)\n },\n heap: {\n totalHeapSize: this.formatBytes(heapStats.total_heap_size),\n usedHeapSize: this.formatBytes(heapStats.used_heap_size),\n heapSizeLimit: this.formatBytes(heapStats.heap_size_limit),\n mallocedMemory: this.formatBytes(heapStats.malloced_memory),\n externalMemory: this.formatBytes(heapStats.external_memory)\n },\n raw: {\n heapUsed: memUsage.heapUsed\n }\n };\n\n // Track peak memory\n if (memUsage.heapUsed > this.peakMemory) {\n this.peakMemory = memUsage.heapUsed;\n }\n\n this.checkpoints.push(checkpoint);\n return checkpoint;\n }\n\n /**\n * Force garbage collection (requires --expose-gc flag)\n */\n forceGC() {\n if (global.gc) {\n global.gc();\n return true;\n }\n return false;\n }\n\n /**\n * Get memory usage summary\n */\n getSummary() {\n const currentMemory = process.memoryUsage();\n \n return {\n currentUsage: {\n rss: this.formatBytes(currentMemory.rss),\n heapTotal: this.formatBytes(currentMemory.heapTotal),\n heapUsed: this.formatBytes(currentMemory.heapUsed)\n },\n peakMemory: this.formatBytes(this.peakMemory),\n totalCheckpoints: this.checkpoints.length,\n runTime: `${((Date.now() - this.startTime) / 1000).toFixed(2)}s`\n };\n }\n\n /**\n * Get detailed report of memory usage\n */\n getDetailedReport() {\n const summary = this.getSummary();\n const memoryGrowth = this.calculateMemoryGrowth();\n \n return {\n summary,\n memoryGrowth,\n checkpoints: this.checkpoints,\n recommendations: this.getRecommendations(memoryGrowth)\n };\n }\n\n /**\n * Calculate memory growth between checkpoints\n */\n calculateMemoryGrowth() {\n if (this.checkpoints.length < 2) return [];\n \n const growth = [];\n for (let i = 1; i < this.checkpoints.length; i++) {\n const prev = this.checkpoints[i - 1];\n const curr = this.checkpoints[i];\n \n const heapDiff = curr.raw.heapUsed - prev.raw.heapUsed;\n \n growth.push({\n from: prev.label,\n to: curr.label,\n heapGrowth: this.formatBytes(Math.abs(heapDiff)),\n isIncrease: heapDiff > 0,\n timeDiff: `${((curr.timestamp - prev.timestamp) / 1000).toFixed(2)}s`\n });\n }\n \n return growth;\n }\n\n /**\n * Get recommendations based on memory usage\n */\n getRecommendations(memoryGrowth) {\n const recommendations = [];\n \n // Check for large memory growth\n const largeGrowths = memoryGrowth.filter(g => {\n const bytes = this.parseBytes(g.heapGrowth);\n return bytes > 50 * 1024 * 1024; // 50MB\n });\n \n if (largeGrowths.length > 0) {\n recommendations.push({\n type: 'warning',\n message: `Large memory growth detected in ${largeGrowths.length} operations`,\n details: largeGrowths.map(g => `${g.from} → ${g.to}: ${g.heapGrowth}`)\n });\n }\n \n // Check peak memory\n if (this.peakMemory > 500 * 1024 * 1024) { // 500MB\n recommendations.push({\n type: 'warning',\n message: `High peak memory usage: ${this.formatBytes(this.peakMemory)}`,\n suggestion: 'Consider processing files in smaller batches'\n });\n }\n \n // Check for potential memory leaks\n const continuousGrowth = this.checkContinuousGrowth();\n if (continuousGrowth) {\n recommendations.push({\n type: 'error',\n message: 'Potential memory leak detected',\n details: 'Memory usage continuously increases without significant decreases'\n });\n }\n \n return recommendations;\n }\n\n /**\n * Check for continuous memory growth (potential leak)\n */\n checkContinuousGrowth() {\n if (this.checkpoints.length < 5) return false;\n \n let increasingCount = 0;\n for (let i = 1; i < this.checkpoints.length; i++) {\n if (this.checkpoints[i].raw.heapUsed > this.checkpoints[i - 1].raw.heapUsed) {\n increasingCount++;\n }\n }\n \n // If memory increases in more than 80% of checkpoints, might be a leak\n return increasingCount / (this.checkpoints.length - 1) > 0.8;\n }\n\n /**\n * Format bytes to human-readable string\n */\n formatBytes(bytes) {\n if (bytes === 0) return '0 B';\n \n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n /**\n * Parse human-readable bytes back to number\n */\n parseBytes(str) {\n const match = str.match(/^([\\d.]+)\\s*([KMGT]?B?)$/i);\n if (!match) return 0;\n \n const value = parseFloat(match[1]);\n const unit = match[2].toUpperCase();\n \n const multipliers = {\n 'B': 1,\n 'KB': 1024,\n 'MB': 1024 * 1024,\n 'GB': 1024 * 1024 * 1024\n };\n \n return value * (multipliers[unit] || 1);\n }\n\n /**\n * Clear checkpoints to free memory\n */\n clear() {\n this.checkpoints = [];\n }\n}\n\n// Export singleton instance\nmodule.exports = new MemoryProfiler();"], ["/BMAD-METHOD/tools/bmad-npx-wrapper.js", "#!/usr/bin/env node\n\n/**\n * BMad Method CLI - Direct execution wrapper for npx\n * This file ensures proper execution when run via npx from GitHub\n */\n\nconst { execSync } = require('child_process');\nconst path = require('path');\nconst fs = require('fs');\n\n// Check if we're running in an npx temporary directory\nconst isNpxExecution = __dirname.includes('_npx') || __dirname.includes('.npm');\n\n// If running via npx, we need to handle things differently\nif (isNpxExecution) {\n // The actual bmad.js is in installer/bin/ (relative to tools directory)\n const bmadScriptPath = path.join(__dirname, 'installer', 'bin', 'bmad.js');\n \n // Verify the file exists\n if (!fs.existsSync(bmadScriptPath)) {\n console.error('Error: Could not find bmad.js at', bmadScriptPath);\n console.error('Current directory:', __dirname);\n process.exit(1);\n }\n \n // Execute with proper working directory\n try {\n execSync(`node \"${bmadScriptPath}\" ${process.argv.slice(2).join(' ')}`, {\n stdio: 'inherit',\n cwd: path.dirname(__dirname)\n });\n } catch (error) {\n // execSync will throw if the command exits with non-zero\n // But the stdio is inherited, so the error is already displayed\n process.exit(error.status || 1);\n }\n} else {\n // Local execution - just require the installer directly\n require('./installer/bin/bmad.js');\n}"], ["/BMAD-METHOD/tools/lib/yaml-utils.js", "/**\n * Utility functions for YAML extraction from agent files\n */\n\n/**\n * Extract YAML content from agent markdown files\n * @param {string} agentContent - The full content of the agent file\n * @param {boolean} cleanCommands - Whether to clean command descriptions (default: false)\n * @returns {string|null} - The extracted YAML content or null if not found\n */\nfunction extractYamlFromAgent(agentContent, cleanCommands = false) {\n // Remove carriage returns and match YAML block\n const yamlMatch = agentContent.replace(/\\r/g, \"\").match(/```ya?ml\\n([\\s\\S]*?)\\n```/);\n if (!yamlMatch) return null;\n \n let yamlContent = yamlMatch[1].trim();\n \n // Clean up command descriptions if requested\n // Converts \"- command - description\" to just \"- command\"\n if (cleanCommands) {\n yamlContent = yamlContent.replace(/^(\\s*-)(\\s*\"[^\"]+\")(\\s*-\\s*.*)$/gm, '$1$2');\n }\n \n return yamlContent;\n}\n\nmodule.exports = {\n extractYamlFromAgent\n};"], ["/BMAD-METHOD/tools/semantic-release-sync-installer.js", "/**\n * Semantic-release plugin to sync installer package.json version\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\n// This function runs during the \"prepare\" step of semantic-release\nfunction prepare(_, { nextRelease, logger }) {\n // Define the path to the installer package.json file\n const file = path.join(process.cwd(), 'tools/installer/package.json');\n\n // If the file does not exist, skip syncing and log a message\n if (!fs.existsSync(file)) return logger.log('Installer package.json not found, skipping');\n\n // Read and parse the package.json file\n const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));\n\n // Update the version field with the next release version\n pkg.version = nextRelease.version;\n\n // Write the updated JSON back to the file\n fs.writeFileSync(file, JSON.stringify(pkg, null, 2) + '\\n');\n\n // Log success message\n logger.log(`Synced installer package.json to version ${nextRelease.version}`);\n}\n\n// Export the prepare function so semantic-release can use it\nmodule.exports = { prepare };\n"], ["/BMAD-METHOD/tools/sync-installer-version.js", "#!/usr/bin/env node\n\n/**\n * Sync installer package.json version with main package.json\n * Used by semantic-release to keep versions in sync\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\nfunction syncInstallerVersion() {\n // Read main package.json\n const mainPackagePath = path.join(__dirname, '..', 'package.json');\n const mainPackage = JSON.parse(fs.readFileSync(mainPackagePath, 'utf8'));\n \n // Read installer package.json\n const installerPackagePath = path.join(__dirname, 'installer', 'package.json');\n const installerPackage = JSON.parse(fs.readFileSync(installerPackagePath, 'utf8'));\n \n // Update installer version to match main version\n installerPackage.version = mainPackage.version;\n \n // Write back installer package.json\n fs.writeFileSync(installerPackagePath, JSON.stringify(installerPackage, null, 2) + '\\n');\n \n console.log(`Synced installer version to ${mainPackage.version}`);\n}\n\n// Run if called directly\nif (require.main === module) {\n syncInstallerVersion();\n}\n\nmodule.exports = { syncInstallerVersion };"]], "task_instance_info": {"created_time": "2025-08-20 23:47:31", "created_task_model": "DeepSeek-R1", "class_skeleton": "class\nV3ToV4Upgrader\n{\nconstructor () {}\nasync upgrade (options = {}) {}\nasync getProjectPath (providedPath) {}\nasync validateV3Project (projectPath) {}\nasync analyzeProject (projectPath) {}\nasync showPreflightCheck (analysis, options) {}\nasync createBackup (projectPath) {}\nasync installV4Structure (projectPath) {}\nasync migrateDocuments (projectPath, analysis) {}\nasync setupIDE (projectPath, selectedIdes) {}\nshowCompletionReport (projectPath, analysis) {}\nasync pathExists (filePath) {}\nasync copyDirectory (src, dest) {}\nasync createPrdIndex (projectPath, analysis) {}\nasync createInstallManifest (projectPath) {}\n}", "code_description": "This code segment functions to: Facilitate the migration process between software versions by validating existing project structures, transforming legacy document formats, and guiding user interactions through automated upgrade steps while preserving critical project assets and generating system compatibility configurations."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```javascript\n[TASK_BEGIN]\nclass V3ToV4Upgrader {\n constructor() {\n this.backupPath = null;\n this.ides = ['vscode', 'webstorm'];\n }\n\n async upgrade(options = {}) {\n await initializeModules();\n const projectPath = await this.getProjectPath(options.path);\n await this.validateV3Project(projectPath);\n const analysis = await this.analyzeProject(projectPath);\n await this.showPreflightCheck(analysis, options);\n await this.createBackup(projectPath);\n await this.installV4Structure(projectPath);\n await this.migrateDocuments(projectPath, analysis);\n await this.setupIDE(projectPath, options.ide || []);\n this.showCompletionReport(projectPath, analysis);\n }\n\n async getProjectPath(providedPath) {\n if (providedPath) return path.resolve(providedPath);\n const matches = await glob('**/config.xml', { ignore: 'node_modules/**' });\n if (matches.length === 0) throw new Error('No v3 project found');\n return path.dirname(matches[0]);\n }\n\n async validateV3Project(projectPath) {\n const requiredFiles = ['config.xml', 'documenttypes.xml'];\n for (const file of requiredFiles) {\n if (!await this.pathExists(path.join(projectPath, file))) {\n throw new Error(`Invalid v3 project: Missing ${file}`);\n }\n }\n }\n\n async analyzeProject(projectPath) {\n const documentTypes = await glob(path.join(projectPath, '**/*.doctype.xml'));\n const templates = await glob(path.join(projectPath, '**/*.template.html'));\n return {\n docTypes: documentTypes.length,\n templates: templates.length,\n hasLegacyPlugins: await this.pathExists(path.join(projectPath, 'plugins'))\n };\n }\n\n async showPreflightCheck(analysis, options) {\n const spinner = ora('Analyzing project').start();\n await new Promise(resolve => setTimeout(resolve, 1000));\n spinner.succeed(`Found ${analysis.docTypes} document types and ${analysis.templates} templates`);\n\n if (!options.force) {\n const { confirm } = await inquirer.prompt({\n type: 'confirm',\n name: 'confirm',\n message: 'Proceed with upgrade?',\n default: true\n });\n if (!confirm) process.exit(0);\n }\n }\n\n async createBackup(projectPath) {\n const backupDir = path.join(projectPath, 'backup');\n this.backupPath = path.join(backupDir, `v3-backup-${Date.now()}`);\n await this.copyDirectory(projectPath, this.backupPath);\n }\n\n async installV4Structure(projectPath) {\n const templatePath = path.join(__dirname, 'templates/v4-structure');\n await this.copyDirectory(templatePath, projectPath);\n }\n\n async migrateDocuments(projectPath, analysis) {\n const docsDest = path.join(projectPath, 'src/document-types');\n await fs.mkdir(docsDest, { recursive: true });\n await this.copyDirectory(path.join(projectPath, 'document-types'), docsDest);\n }\n\n async setupIDE(projectPath, selectedIdes) {\n for (const ide of selectedIdes) {\n await this.copyDirectory(\n path.join(__dirname, `templates/ide/${ide}`),\n projectPath\n );\n }\n }\n\n showCompletionReport(projectPath, analysis) {\n console.log(chalk.green('\\nUpgrade completed successfully!'));\n console.log(chalk.yellow(`\\nBackup created at: ${this.backupPath}`));\n if (analysis.hasLegacyPlugins) {\n console.log(chalk.yellow('NOTE: Manual migration required for legacy plugins'));\n }\n }\n\n async pathExists(filePath) {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n\n async copyDirectory(src, dest) {\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n entry.isDirectory() ?\n await this.copyDirectory(srcPath, destPath) :\n await fs.copyFile(srcPath, destPath);\n }\n }\n\n async createPrdIndex(projectPath, analysis) {\n const indexPath = path.join(projectPath, 'src/prd-index.js');\n const content = `// Auto-generated index file\\n\\nexport const documentTypes = ${analysis.docTypes};\\n`;\n await fs.writeFile(indexPath, content);\n }\n\n async createInstallManifest(projectPath) {\n const manifestPath = path.join(projectPath, 'upgrade-manifest.json');\n const manifest = {\n timestamp: new Date().toISOString(),\n backupLocation: this.backupPath,\n version: '4.0.0'\n };\n await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2));\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 23-48-18"}, "editdistance_info": {"edit_distance": 17.2755, "calculate_time": "2025-08-20 23:48:18", "true_code_clean": "class V3ToV4Upgrader {\n constructor() {\n }\n async upgrade(options = {}) {\n try {\n await initializeModules();\n process.stdin.resume();\n console.log(\n chalk.bold(\"\\nWelcome to BMad-Method V3 to V4 Upgrade Tool\\n\")\n );\n console.log(\n \"This tool will help you upgrade your BMad-Method V3 project to V4.\\n\"\n );\n console.log(chalk.cyan(\"What this tool does:\"));\n console.log(\"- Creates a backup of your V3 files (.bmad-v3-backup/)\");\n console.log(\"- Installs the new V4 .bmad-core structure\");\n console.log(\n \"- Preserves your PRD, Architecture, and Stories in the new format\\n\"\n );\n console.log(chalk.yellow(\"What this tool does NOT do:\"));\n console.log(\n \"- Modify your document content (use doc-migration-task after upgrade)\"\n );\n console.log(\"- Touch any files outside bmad-agent/ and docs/\\n\");\n const projectPath = await this.getProjectPath(options.projectPath);\n const validation = await this.validateV3Project(projectPath);\n if (!validation.isValid) {\n console.error(\n chalk.red(\"\\nError: This doesn't appear to be a V3 project.\")\n );\n console.error(\"Expected to find:\");\n console.error(\"- bmad-agent/ directory\");\n console.error(\"- docs/ directory\\n\");\n console.error(\n \"Please check you're in the correct directory and try again.\"\n );\n return;\n }\n const analysis = await this.analyzeProject(projectPath);\n await this.showPreflightCheck(analysis, options);\n if (!options.dryRun) {\n const { confirm } = await inquirer.prompt([\n {\n type: \"confirm\",\n name: \"confirm\",\n message: \"Continue with upgrade?\",\n default: true,\n },\n ]);\n if (!confirm) {\n console.log(\"Upgrade cancelled.\");\n return;\n }\n }\n if (options.backup !== false && !options.dryRun) {\n await this.createBackup(projectPath);\n }\n if (!options.dryRun) {\n await this.installV4Structure(projectPath);\n }\n if (!options.dryRun) {\n await this.migrateDocuments(projectPath, analysis);\n }\n if (!options.dryRun) {\n await this.setupIDE(projectPath, options.ides);\n }\n this.showCompletionReport(projectPath, analysis);\n process.exit(0);\n } catch (error) {\n console.error(chalk.red(\"\\nUpgrade error:\"), error.message);\n process.exit(1);\n }\n }\n async getProjectPath(providedPath) {\n if (providedPath) {\n return path.resolve(providedPath);\n }\n const { projectPath } = await inquirer.prompt([\n {\n type: \"input\",\n name: \"projectPath\",\n message: \"Please enter the path to your V3 project:\",\n default: process.cwd(),\n },\n ]);\n return path.resolve(projectPath);\n }\n async validateV3Project(projectPath) {\n const spinner = ora(\"Validating project structure...\").start();\n try {\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n const docsPath = path.join(projectPath, \"docs\");\n const hasBmadAgent = await this.pathExists(bmadAgentPath);\n const hasDocs = await this.pathExists(docsPath);\n if (hasBmadAgent) {\n spinner.text = \"āœ“ Found bmad-agent/ directory\";\n console.log(chalk.green(\"\\nāœ“ Found bmad-agent/ directory\"));\n }\n if (hasDocs) {\n console.log(chalk.green(\"āœ“ Found docs/ directory\"));\n }\n const isValid = hasBmadAgent && hasDocs;\n if (isValid) {\n spinner.succeed(\"This appears to be a valid V3 project\");\n } else {\n spinner.fail(\"Invalid V3 project structure\");\n }\n return { isValid, hasBmadAgent, hasDocs };\n } catch (error) {\n spinner.fail(\"Validation failed\");\n throw error;\n }\n }\n async analyzeProject(projectPath) {\n const docsPath = path.join(projectPath, \"docs\");\n const bmadAgentPath = path.join(projectPath, \"bmad-agent\");\n const prdCandidates = [\"prd.md\", \"PRD.md\", \"product-requirements.md\"];\n let prdFile = null;\n for (const candidate of prdCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n prdFile = candidate;\n break;\n }\n }\n const archCandidates = [\n \"architecture.md\",\n \"Architecture.md\",\n \"technical-architecture.md\",\n ];\n let archFile = null;\n for (const candidate of archCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n archFile = candidate;\n break;\n }\n }\n const frontEndCandidates = [\n \"front-end-architecture.md\",\n \"frontend-architecture.md\",\n \"ui-architecture.md\",\n ];\n let frontEndArchFile = null;\n for (const candidate of frontEndCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n frontEndArchFile = candidate;\n break;\n }\n }\n const uxSpecCandidates = [\n \"ux-ui-spec.md\",\n \"ux-ui-specification.md\",\n \"ui-spec.md\",\n \"ux-spec.md\",\n ];\n let uxSpecFile = null;\n for (const candidate of uxSpecCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxSpecFile = candidate;\n break;\n }\n }\n const uxPromptCandidates = [\n \"v0-prompt.md\",\n \"ux-prompt.md\",\n \"ui-prompt.md\",\n \"design-prompt.md\",\n ];\n let uxPromptFile = null;\n for (const candidate of uxPromptCandidates) {\n const candidatePath = path.join(docsPath, candidate);\n if (await this.pathExists(candidatePath)) {\n uxPromptFile = candidate;\n break;\n }\n }\n const epicFiles = await glob(\"epic*.md\", { cwd: docsPath });\n const storiesPath = path.join(docsPath, \"stories\");\n let storyFiles = [];\n if (await this.pathExists(storiesPath)) {\n storyFiles = await glob(\"*.md\", { cwd: storiesPath });\n }\n const bmadAgentFiles = await glob(\"**, \"\") \n .trim();\n const displayName = epicName.charAt(0).toUpperCase() + epicName.slice(1);\n indexContent += `- [${\n displayName || epicFile.replace(\".md\", \"\")\n }](./${epicFile})\\n`;\n }\n await fs.writeFile(prdIndexPath, indexContent);\n }\n async createInstallManifest(projectPath) {\n const fileManager = require(\"../installer/lib/file-manager\");\n const { glob } = require(\"glob\");\n const bmadCorePath = path.join(projectPath, \".bmad-core\");\n const files = await glob(\"**.gitnode_modules/**\"],\n });\n const manifestFiles = files.map((file) => path.join(\".bmad-core\", file));\n const config = {\n installType: \"full\",\n agent: null,\n ide: null, \n };\n await fileManager.createManifest(projectPath, config, manifestFiles);\n }\n}", "predict_code_clean": "class V3ToV4Upgrader {\n constructor() {\n this.backupPath = null;\n this.ides = ['vscode', 'webstorm'];\n }\n async upgrade(options = {}) {\n await initializeModules();\n const projectPath = await this.getProjectPath(options.path);\n await this.validateV3Project(projectPath);\n const analysis = await this.analyzeProject(projectPath);\n await this.showPreflightCheck(analysis, options);\n await this.createBackup(projectPath);\n await this.installV4Structure(projectPath);\n await this.migrateDocuments(projectPath, analysis);\n await this.setupIDE(projectPath, options.ide || []);\n this.showCompletionReport(projectPath, analysis);\n }\n async getProjectPath(providedPath) {\n if (providedPath) return path.resolve(providedPath);\n const matches = await glob('**/config.xml', { ignore: 'node_modules*.doctype.xml'));\n const templates = await glob(path.join(projectPath, '**/*.template.html'));\n return {\n docTypes: documentTypes.length,\n templates: templates.length,\n hasLegacyPlugins: await this.pathExists(path.join(projectPath, 'plugins'))\n };\n }\n async showPreflightCheck(analysis, options) {\n const spinner = ora('Analyzing project').start();\n await new Promise(resolve => setTimeout(resolve, 1000));\n spinner.succeed(`Found ${analysis.docTypes} document types and ${analysis.templates} templates`);\n if (!options.force) {\n const { confirm } = await inquirer.prompt({\n type: 'confirm',\n name: 'confirm',\n message: 'Proceed with upgrade?',\n default: true\n });\n if (!confirm) process.exit(0);\n }\n }\n async createBackup(projectPath) {\n const backupDir = path.join(projectPath, 'backup');\n this.backupPath = path.join(backupDir, `v3-backup-${Date.now()}`);\n await this.copyDirectory(projectPath, this.backupPath);\n }\n async installV4Structure(projectPath) {\n const templatePath = path.join(__dirname, 'templates/v4-structure');\n await this.copyDirectory(templatePath, projectPath);\n }\n async migrateDocuments(projectPath, analysis) {\n const docsDest = path.join(projectPath, 'src/document-types');\n await fs.mkdir(docsDest, { recursive: true });\n await this.copyDirectory(path.join(projectPath, 'document-types'), docsDest);\n }\n async setupIDE(projectPath, selectedIdes) {\n for (const ide of selectedIdes) {\n await this.copyDirectory(\n path.join(__dirname, `templates/ide/${ide}`),\n projectPath\n );\n }\n }\n showCompletionReport(projectPath, analysis) {\n console.log(chalk.green('\\nUpgrade completed successfully!'));\n console.log(chalk.yellow(`\\nBackup created at: ${this.backupPath}`));\n if (analysis.hasLegacyPlugins) {\n console.log(chalk.yellow('NOTE: Manual migration required for legacy plugins'));\n }\n }\n async pathExists(filePath) {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n async copyDirectory(src, dest) {\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n entry.isDirectory() ?\n await this.copyDirectory(srcPath, destPath) :\n await fs.copyFile(srcPath, destPath);\n }\n }\n async createPrdIndex(projectPath, analysis) {\n const indexPath = path.join(projectPath, 'src/prd-index.js');\n const content = `\n await fs.writeFile(indexPath, content);\n }\n async createInstallManifest(projectPath) {\n const manifestPath = path.join(projectPath, 'upgrade-manifest.json');\n const manifest = {\n timestamp: new Date().toISOString(),\n backupLocation: this.backupPath,\n version: '4.0.0'\n };\n await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2));\n }\n}"}}