bmad-method 6.2.2 → 6.2.3-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/.claude-plugin/marketplace.json +78 -0
  2. package/package.json +8 -8
  3. package/src/core-skills/bmad-distillator/resources/distillate-format-reference.md +1 -1
  4. package/src/core-skills/bmad-init/scripts/bmad_init.py +35 -4
  5. package/src/core-skills/bmad-init/scripts/tests/test_bmad_init.py +64 -0
  6. package/tools/{cli → installer}/bmad-cli.js +3 -1
  7. package/tools/{cli/lib → installer}/cli-utils.js +3 -4
  8. package/tools/{cli → installer}/commands/install.js +3 -3
  9. package/tools/{cli → installer}/commands/status.js +4 -4
  10. package/tools/{cli → installer}/commands/uninstall.js +5 -5
  11. package/tools/installer/core/config.js +52 -0
  12. package/tools/{cli/installers/lib → installer}/core/custom-module-cache.js +1 -1
  13. package/tools/installer/core/existing-install.js +127 -0
  14. package/tools/installer/core/install-paths.js +129 -0
  15. package/tools/installer/core/installer.js +1790 -0
  16. package/tools/{cli/installers/lib → installer}/core/manifest-generator.js +3 -3
  17. package/tools/{cli/installers/lib → installer}/core/manifest.js +2 -2
  18. package/tools/{cli/installers/lib/custom/handler.js → installer/custom-handler.js} +1 -1
  19. package/tools/{cli/installers/lib → installer}/ide/_config-driven.js +30 -397
  20. package/tools/{cli/installers/lib → installer}/ide/manager.js +1 -53
  21. package/tools/installer/ide/platform-codes.js +37 -0
  22. package/tools/installer/ide/platform-codes.yaml +190 -0
  23. package/tools/{cli/installers/lib → installer}/ide/shared/module-injections.js +1 -1
  24. package/tools/{cli/installers/lib → installer}/message-loader.js +2 -2
  25. package/tools/installer/modules/custom-modules.js +197 -0
  26. package/tools/installer/modules/external-manager.js +323 -0
  27. package/tools/{cli/installers/lib/core/config-collector.js → installer/modules/official-modules.js} +714 -43
  28. package/tools/{cli/lib → installer}/ui.js +65 -299
  29. package/tools/javascript-conventions.md +5 -0
  30. package/tools/bmad-npx-wrapper.js +0 -38
  31. package/tools/cli/installers/lib/core/dependency-resolver.js +0 -743
  32. package/tools/cli/installers/lib/core/detector.js +0 -223
  33. package/tools/cli/installers/lib/core/ide-config-manager.js +0 -157
  34. package/tools/cli/installers/lib/core/installer.js +0 -3002
  35. package/tools/cli/installers/lib/ide/_base-ide.js +0 -657
  36. package/tools/cli/installers/lib/ide/platform-codes.js +0 -100
  37. package/tools/cli/installers/lib/ide/platform-codes.yaml +0 -341
  38. package/tools/cli/installers/lib/modules/external-manager.js +0 -136
  39. package/tools/cli/installers/lib/modules/manager.js +0 -928
  40. package/tools/cli/lib/config.js +0 -213
  41. package/tools/cli/lib/platform-codes.js +0 -116
  42. package/tools/lib/xml-utils.js +0 -13
  43. /package/tools/{cli → installer}/README.md +0 -0
  44. /package/tools/{cli → installer}/external-official-modules.yaml +0 -0
  45. /package/tools/{cli/lib → installer}/file-ops.js +0 -0
  46. /package/tools/{cli/installers/lib → installer}/ide/shared/agent-command-generator.js +0 -0
  47. /package/tools/{cli/installers/lib → installer}/ide/shared/bmad-artifacts.js +0 -0
  48. /package/tools/{cli/installers/lib → installer}/ide/shared/path-utils.js +0 -0
  49. /package/tools/{cli/installers/lib → installer}/ide/shared/skill-manifest.js +0 -0
  50. /package/tools/{cli/installers/lib → installer}/ide/templates/agent-command-template.md +0 -0
  51. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/antigravity.md +0 -0
  52. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/default-agent.md +0 -0
  53. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/default-task.md +0 -0
  54. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/default-tool.md +0 -0
  55. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/default-workflow.md +0 -0
  56. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/gemini-agent.toml +0 -0
  57. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/gemini-task.toml +0 -0
  58. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/gemini-tool.toml +0 -0
  59. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/gemini-workflow-yaml.toml +0 -0
  60. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/gemini-workflow.toml +0 -0
  61. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/kiro-agent.md +0 -0
  62. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/kiro-task.md +0 -0
  63. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/kiro-tool.md +0 -0
  64. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/kiro-workflow.md +0 -0
  65. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/opencode-agent.md +0 -0
  66. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/opencode-task.md +0 -0
  67. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/opencode-tool.md +0 -0
  68. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/opencode-workflow-yaml.md +0 -0
  69. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/opencode-workflow.md +0 -0
  70. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/rovodev.md +0 -0
  71. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/trae.md +0 -0
  72. /package/tools/{cli/installers/lib → installer}/ide/templates/combined/windsurf-workflow.md +0 -0
  73. /package/tools/{cli/installers/lib → installer}/ide/templates/split/.gitkeep +0 -0
  74. /package/tools/{cli/installers → installer}/install-messages.yaml +0 -0
  75. /package/tools/{cli/lib → installer}/project-root.js +0 -0
  76. /package/tools/{cli/lib → installer}/prompts.js +0 -0
  77. /package/tools/{cli/lib → installer}/yaml-format.js +0 -0
@@ -1,3002 +0,0 @@
1
- const path = require('node:path');
2
- const fs = require('fs-extra');
3
- const { Detector } = require('./detector');
4
- const { Manifest } = require('./manifest');
5
- const { ModuleManager } = require('../modules/manager');
6
- const { IdeManager } = require('../ide/manager');
7
- const { FileOps } = require('../../../lib/file-ops');
8
- const { Config } = require('../../../lib/config');
9
- const { DependencyResolver } = require('./dependency-resolver');
10
- const { ConfigCollector } = require('./config-collector');
11
- const { getProjectRoot, getSourcePath, getModulePath } = require('../../../lib/project-root');
12
- const { CLIUtils } = require('../../../lib/cli-utils');
13
- const { ManifestGenerator } = require('./manifest-generator');
14
- const { IdeConfigManager } = require('./ide-config-manager');
15
- const { CustomHandler } = require('../custom/handler');
16
- const prompts = require('../../../lib/prompts');
17
- const { BMAD_FOLDER_NAME } = require('../ide/shared/path-utils');
18
-
19
- class Installer {
20
- constructor() {
21
- this.detector = new Detector();
22
- this.manifest = new Manifest();
23
- this.moduleManager = new ModuleManager();
24
- this.ideManager = new IdeManager();
25
- this.fileOps = new FileOps();
26
- this.config = new Config();
27
- this.dependencyResolver = new DependencyResolver();
28
- this.configCollector = new ConfigCollector();
29
- this.ideConfigManager = new IdeConfigManager();
30
- this.installedFiles = new Set(); // Track all installed files
31
- this.bmadFolderName = BMAD_FOLDER_NAME;
32
- }
33
-
34
- /**
35
- * Find the bmad installation directory in a project
36
- * Always uses the standard _bmad folder name
37
- * Also checks for legacy _cfg folder for migration
38
- * @param {string} projectDir - Project directory
39
- * @returns {Promise<Object>} { bmadDir: string, hasLegacyCfg: boolean }
40
- */
41
- async findBmadDir(projectDir) {
42
- const bmadDir = path.join(projectDir, BMAD_FOLDER_NAME);
43
-
44
- // Check if project directory exists
45
- if (!(await fs.pathExists(projectDir))) {
46
- // Project doesn't exist yet, return default
47
- return { bmadDir, hasLegacyCfg: false };
48
- }
49
-
50
- // Check for legacy _cfg folder if bmad directory exists
51
- let hasLegacyCfg = false;
52
- if (await fs.pathExists(bmadDir)) {
53
- const legacyCfgPath = path.join(bmadDir, '_cfg');
54
- if (await fs.pathExists(legacyCfgPath)) {
55
- hasLegacyCfg = true;
56
- }
57
- }
58
-
59
- return { bmadDir, hasLegacyCfg };
60
- }
61
-
62
- /**
63
- * @function copyFileWithPlaceholderReplacement
64
- * @intent Copy files from BMAD source to installation directory with dynamic content transformation
65
- * @why Enables installation-time customization: _bmad replacement
66
- * @param {string} sourcePath - Absolute path to source file in BMAD repository
67
- * @param {string} targetPath - Absolute path to destination file in user's project
68
- * @param {string} bmadFolderName - User's chosen bmad folder name (default: 'bmad')
69
- * @returns {Promise<void>} Resolves when file copy and transformation complete
70
- * @sideeffects Writes transformed file to targetPath, creates parent directories if needed
71
- * @edgecases Binary files bypass transformation, falls back to raw copy if UTF-8 read fails
72
- * @calledby installCore(), installModule(), IDE installers during file vendoring
73
- * @calls fs.readFile(), fs.writeFile(), fs.copy()
74
- *
75
-
76
- *
77
- * 3. Document marker in instructions.md (if applicable)
78
- */
79
- async copyFileWithPlaceholderReplacement(sourcePath, targetPath) {
80
- // List of text file extensions that should have placeholder replacement
81
- const textExtensions = ['.md', '.yaml', '.yml', '.txt', '.json', '.js', '.ts', '.html', '.css', '.sh', '.bat', '.csv', '.xml'];
82
- const ext = path.extname(sourcePath).toLowerCase();
83
-
84
- // Check if this is a text file that might contain placeholders
85
- if (textExtensions.includes(ext)) {
86
- try {
87
- // Read the file content
88
- let content = await fs.readFile(sourcePath, 'utf8');
89
-
90
- // Write to target with replaced content
91
- await fs.ensureDir(path.dirname(targetPath));
92
- await fs.writeFile(targetPath, content, 'utf8');
93
- } catch {
94
- // If reading as text fails (might be binary despite extension), fall back to regular copy
95
- await fs.copy(sourcePath, targetPath, { overwrite: true });
96
- }
97
- } else {
98
- // Binary file or other file type - just copy directly
99
- await fs.copy(sourcePath, targetPath, { overwrite: true });
100
- }
101
- }
102
-
103
- /**
104
- * Collect Tool/IDE configurations after module configuration
105
- * @param {string} projectDir - Project directory
106
- * @param {Array} selectedModules - Selected modules from configuration
107
- * @param {boolean} isFullReinstall - Whether this is a full reinstall
108
- * @param {Array} previousIdes - Previously configured IDEs (for reinstalls)
109
- * @param {Array} preSelectedIdes - Pre-selected IDEs from early prompt (optional)
110
- * @param {boolean} skipPrompts - Skip prompts and use defaults (for --yes flag)
111
- * @returns {Object} Tool/IDE selection and configurations
112
- */
113
- async collectToolConfigurations(
114
- projectDir,
115
- selectedModules,
116
- isFullReinstall = false,
117
- previousIdes = [],
118
- preSelectedIdes = null,
119
- skipPrompts = false,
120
- ) {
121
- // Use pre-selected IDEs if provided, otherwise prompt
122
- let toolConfig;
123
- if (preSelectedIdes === null) {
124
- // Fallback: prompt for tool selection (backwards compatibility)
125
- const { UI } = require('../../../lib/ui');
126
- const ui = new UI();
127
- toolConfig = await ui.promptToolSelection(projectDir);
128
- } else {
129
- // IDEs were already selected during initial prompts
130
- toolConfig = {
131
- ides: preSelectedIdes,
132
- skipIde: !preSelectedIdes || preSelectedIdes.length === 0,
133
- };
134
- }
135
-
136
- // Check for already configured IDEs
137
- const { Detector } = require('./detector');
138
- const detector = new Detector();
139
- const bmadDir = path.join(projectDir, BMAD_FOLDER_NAME);
140
-
141
- // During full reinstall, use the saved previous IDEs since bmad dir was deleted
142
- // Otherwise detect from existing installation
143
- let previouslyConfiguredIdes;
144
- if (isFullReinstall) {
145
- // During reinstall, treat all IDEs as new (need configuration)
146
- previouslyConfiguredIdes = [];
147
- } else {
148
- const existingInstall = await detector.detect(bmadDir);
149
- previouslyConfiguredIdes = existingInstall.ides || [];
150
- }
151
-
152
- // Load saved IDE configurations for already-configured IDEs
153
- const savedIdeConfigs = await this.ideConfigManager.loadAllIdeConfigs(bmadDir);
154
-
155
- // Collect IDE-specific configurations if any were selected
156
- const ideConfigurations = {};
157
-
158
- // First, add saved configs for already-configured IDEs
159
- for (const ide of toolConfig.ides || []) {
160
- if (previouslyConfiguredIdes.includes(ide) && savedIdeConfigs[ide]) {
161
- ideConfigurations[ide] = savedIdeConfigs[ide];
162
- }
163
- }
164
-
165
- if (!toolConfig.skipIde && toolConfig.ides && toolConfig.ides.length > 0) {
166
- // Ensure IDE manager is initialized
167
- await this.ideManager.ensureInitialized();
168
-
169
- // Determine which IDEs are newly selected (not previously configured)
170
- const newlySelectedIdes = toolConfig.ides.filter((ide) => !previouslyConfiguredIdes.includes(ide));
171
-
172
- if (newlySelectedIdes.length > 0) {
173
- // Collect configuration for IDEs that support it
174
- for (const ide of newlySelectedIdes) {
175
- try {
176
- const handler = this.ideManager.handlers.get(ide);
177
-
178
- if (!handler) {
179
- await prompts.log.warn(`Warning: IDE '${ide}' handler not found`);
180
- continue;
181
- }
182
-
183
- // Check if this IDE handler has a collectConfiguration method
184
- // (custom installers like Codex, Kilo may have this)
185
- if (typeof handler.collectConfiguration === 'function') {
186
- await prompts.log.info(`Configuring ${ide}...`);
187
- ideConfigurations[ide] = await handler.collectConfiguration({
188
- selectedModules: selectedModules || [],
189
- projectDir,
190
- bmadDir,
191
- skipPrompts,
192
- });
193
- } else {
194
- // Config-driven IDEs don't need configuration - mark as ready
195
- ideConfigurations[ide] = { _noConfigNeeded: true };
196
- }
197
- } catch (error) {
198
- // IDE doesn't support configuration or has an error
199
- await prompts.log.warn(`Warning: Could not load configuration for ${ide}: ${error.message}`);
200
- }
201
- }
202
- }
203
-
204
- // Log which IDEs are already configured and being kept
205
- const keptIdes = toolConfig.ides.filter((ide) => previouslyConfiguredIdes.includes(ide));
206
- if (keptIdes.length > 0) {
207
- await prompts.log.message(`Keeping existing configuration for: ${keptIdes.join(', ')}`);
208
- }
209
- }
210
-
211
- return {
212
- ides: toolConfig.ides,
213
- skipIde: toolConfig.skipIde,
214
- configurations: ideConfigurations,
215
- };
216
- }
217
-
218
- /**
219
- * Main installation method
220
- * @param {Object} config - Installation configuration
221
- * @param {string} config.directory - Target directory
222
- * @param {boolean} config.installCore - Whether to install core
223
- * @param {string[]} config.modules - Modules to install
224
- * @param {string[]} config.ides - IDEs to configure
225
- * @param {boolean} config.skipIde - Skip IDE configuration
226
- */
227
- async install(originalConfig) {
228
- // Clone config to avoid mutating the caller's object
229
- const config = { ...originalConfig };
230
-
231
- // Check if core config was already collected in UI
232
- const hasCoreConfig = config.coreConfig && Object.keys(config.coreConfig).length > 0;
233
-
234
- // Only display logo if core config wasn't already collected (meaning we're not continuing from UI)
235
- if (!hasCoreConfig) {
236
- // Display BMAD logo
237
- await CLIUtils.displayLogo();
238
-
239
- // Display welcome message
240
- await CLIUtils.displaySection('BMad™ Installation', 'Version ' + require(path.join(getProjectRoot(), 'package.json')).version);
241
- }
242
-
243
- // Note: Legacy V4 detection now happens earlier in UI.promptInstall()
244
- // before any config collection, so we don't need to check again here
245
-
246
- const projectDir = path.resolve(config.directory);
247
- const bmadDir = path.join(projectDir, BMAD_FOLDER_NAME);
248
-
249
- // If core config was pre-collected (from interactive mode), use it
250
- if (config.coreConfig && Object.keys(config.coreConfig).length > 0) {
251
- this.configCollector.collectedConfig.core = config.coreConfig;
252
- // Also store in allAnswers for cross-referencing
253
- this.configCollector.allAnswers = {};
254
- for (const [key, value] of Object.entries(config.coreConfig)) {
255
- this.configCollector.allAnswers[`core_${key}`] = value;
256
- }
257
- }
258
-
259
- // Collect configurations for modules (skip if quick update already collected them)
260
- let moduleConfigs;
261
- let customModulePaths = new Map();
262
-
263
- if (config._quickUpdate) {
264
- // Quick update already collected all configs, use them directly
265
- moduleConfigs = this.configCollector.collectedConfig;
266
-
267
- // For quick update, populate customModulePaths from _customModuleSources
268
- if (config._customModuleSources) {
269
- for (const [moduleId, customInfo] of config._customModuleSources) {
270
- customModulePaths.set(moduleId, customInfo.sourcePath);
271
- }
272
- }
273
- } else {
274
- // For regular updates (modify flow), check manifest for custom module sources
275
- if (config._isUpdate && config._existingInstall && config._existingInstall.customModules) {
276
- for (const customModule of config._existingInstall.customModules) {
277
- // Ensure we have an absolute sourcePath
278
- let absoluteSourcePath = customModule.sourcePath;
279
-
280
- // Check if sourcePath is a cache-relative path (starts with _config)
281
- if (absoluteSourcePath && absoluteSourcePath.startsWith('_config')) {
282
- // Convert cache-relative path to absolute path
283
- absoluteSourcePath = path.join(bmadDir, absoluteSourcePath);
284
- }
285
- // If no sourcePath but we have relativePath, convert it
286
- else if (!absoluteSourcePath && customModule.relativePath) {
287
- // relativePath is relative to the project root (parent of bmad dir)
288
- absoluteSourcePath = path.resolve(projectDir, customModule.relativePath);
289
- }
290
- // Ensure sourcePath is absolute for anything else
291
- else if (absoluteSourcePath && !path.isAbsolute(absoluteSourcePath)) {
292
- absoluteSourcePath = path.resolve(absoluteSourcePath);
293
- }
294
-
295
- if (absoluteSourcePath) {
296
- customModulePaths.set(customModule.id, absoluteSourcePath);
297
- }
298
- }
299
- }
300
-
301
- // Build custom module paths map from customContent
302
-
303
- // Handle selectedFiles (from existing install path or manual directory input)
304
- if (config.customContent && config.customContent.selected && config.customContent.selectedFiles) {
305
- const customHandler = new CustomHandler();
306
- for (const customFile of config.customContent.selectedFiles) {
307
- const customInfo = await customHandler.getCustomInfo(customFile, path.resolve(config.directory));
308
- if (customInfo && customInfo.id) {
309
- customModulePaths.set(customInfo.id, customInfo.path);
310
- }
311
- }
312
- }
313
-
314
- // Handle new custom content sources from UI
315
- if (config.customContent && config.customContent.sources) {
316
- for (const source of config.customContent.sources) {
317
- customModulePaths.set(source.id, source.path);
318
- }
319
- }
320
-
321
- // Handle cachedModules (from new install path where modules are cached)
322
- // Only include modules that were actually selected for installation
323
- if (config.customContent && config.customContent.cachedModules) {
324
- // Get selected cached module IDs (if available)
325
- const selectedCachedIds = config.customContent.selectedCachedModules || [];
326
- // If no selection info, include all cached modules (for backward compatibility)
327
- const shouldIncludeAll = selectedCachedIds.length === 0 && config.customContent.selected;
328
-
329
- for (const cachedModule of config.customContent.cachedModules) {
330
- // For cached modules, the path is the cachePath which contains the module.yaml
331
- if (
332
- cachedModule.id &&
333
- cachedModule.cachePath && // Include if selected or if we should include all
334
- (shouldIncludeAll || selectedCachedIds.includes(cachedModule.id))
335
- ) {
336
- customModulePaths.set(cachedModule.id, cachedModule.cachePath);
337
- }
338
- }
339
- }
340
-
341
- // Get list of all modules including custom modules
342
- // Order: core first, then official modules, then custom modules
343
- const allModulesForConfig = ['core'];
344
-
345
- // Add official modules (excluding core and any custom modules)
346
- const officialModules = (config.modules || []).filter((m) => m !== 'core' && !customModulePaths.has(m));
347
- allModulesForConfig.push(...officialModules);
348
-
349
- // Add custom modules at the end
350
- for (const [moduleId] of customModulePaths) {
351
- if (!allModulesForConfig.includes(moduleId)) {
352
- allModulesForConfig.push(moduleId);
353
- }
354
- }
355
-
356
- // Check if core was already collected in UI
357
- if (config.coreConfig && Object.keys(config.coreConfig).length > 0) {
358
- // Core already collected, skip it in config collection
359
- const modulesWithoutCore = allModulesForConfig.filter((m) => m !== 'core');
360
- moduleConfigs = await this.configCollector.collectAllConfigurations(modulesWithoutCore, path.resolve(config.directory), {
361
- customModulePaths,
362
- skipPrompts: config.skipPrompts,
363
- });
364
- } else {
365
- // Core not collected yet, include it
366
- moduleConfigs = await this.configCollector.collectAllConfigurations(allModulesForConfig, path.resolve(config.directory), {
367
- customModulePaths,
368
- skipPrompts: config.skipPrompts,
369
- });
370
- }
371
- }
372
-
373
- // Set bmad folder name on module manager and IDE manager for placeholder replacement
374
- this.moduleManager.setBmadFolderName(BMAD_FOLDER_NAME);
375
- this.moduleManager.setCoreConfig(moduleConfigs.core || {});
376
- this.moduleManager.setCustomModulePaths(customModulePaths);
377
- this.ideManager.setBmadFolderName(BMAD_FOLDER_NAME);
378
-
379
- // Tool selection will be collected after we determine if it's a reinstall/update/new install
380
-
381
- const spinner = await prompts.spinner();
382
- spinner.start('Preparing installation...');
383
-
384
- try {
385
- // Create a project directory if it doesn't exist (user already confirmed)
386
- if (!(await fs.pathExists(projectDir))) {
387
- spinner.message('Creating installation directory...');
388
- try {
389
- // fs.ensureDir handles platform-specific directory creation
390
- // It will recursively create all necessary parent directories
391
- await fs.ensureDir(projectDir);
392
- } catch (error) {
393
- spinner.error('Failed to create installation directory');
394
- await prompts.log.error(`Error: ${error.message}`);
395
- // More detailed error for common issues
396
- if (error.code === 'EACCES') {
397
- await prompts.log.error('Permission denied. Check parent directory permissions.');
398
- } else if (error.code === 'ENOSPC') {
399
- await prompts.log.error('No space left on device.');
400
- }
401
- throw new Error(`Cannot create directory: ${projectDir}`);
402
- }
403
- }
404
-
405
- // Check existing installation
406
- spinner.message('Checking for existing installation...');
407
- const existingInstall = await this.detector.detect(bmadDir);
408
-
409
- if (existingInstall.installed && !config.force && !config._quickUpdate) {
410
- spinner.stop('Existing installation detected');
411
-
412
- // Check if user already decided what to do (from early menu in ui.js)
413
- let action = null;
414
- if (config.actionType === 'update') {
415
- action = 'update';
416
- } else if (config.skipPrompts) {
417
- // Non-interactive mode: default to update
418
- action = 'update';
419
- } else {
420
- // Fallback: Ask the user (backwards compatibility for other code paths)
421
- await prompts.log.warn('Existing BMAD installation detected');
422
- await prompts.log.message(` Location: ${bmadDir}`);
423
- await prompts.log.message(` Version: ${existingInstall.version}`);
424
-
425
- const promptResult = await this.promptUpdateAction();
426
- action = promptResult.action;
427
- }
428
-
429
- if (action === 'update') {
430
- // Store that we're updating for later processing
431
- config._isUpdate = true;
432
- config._existingInstall = existingInstall;
433
-
434
- // Detect modules that were previously installed but are NOT in the new selection (to be removed)
435
- const previouslyInstalledModules = new Set(existingInstall.modules.map((m) => m.id));
436
- const newlySelectedModules = new Set(config.modules || []);
437
-
438
- // Find modules to remove (installed but not in new selection)
439
- // Exclude 'core' from being removable
440
- const modulesToRemove = [...previouslyInstalledModules].filter((m) => !newlySelectedModules.has(m) && m !== 'core');
441
-
442
- // If there are modules to remove, ask for confirmation
443
- if (modulesToRemove.length > 0) {
444
- if (config.skipPrompts) {
445
- // Non-interactive mode: preserve modules (matches prompt default: false)
446
- for (const moduleId of modulesToRemove) {
447
- if (!config.modules) config.modules = [];
448
- config.modules.push(moduleId);
449
- }
450
- spinner.start('Preparing update...');
451
- } else {
452
- if (spinner.isSpinning) {
453
- spinner.stop('Module changes reviewed');
454
- }
455
-
456
- await prompts.log.warn('Modules to be removed:');
457
- for (const moduleId of modulesToRemove) {
458
- const moduleInfo = existingInstall.modules.find((m) => m.id === moduleId);
459
- const displayName = moduleInfo?.name || moduleId;
460
- const modulePath = path.join(bmadDir, moduleId);
461
- await prompts.log.error(` - ${displayName} (${modulePath})`);
462
- }
463
-
464
- const confirmRemoval = await prompts.confirm({
465
- message: `Remove ${modulesToRemove.length} module(s) from BMAD installation?`,
466
- default: false,
467
- });
468
-
469
- if (confirmRemoval) {
470
- // Remove module folders
471
- for (const moduleId of modulesToRemove) {
472
- const modulePath = path.join(bmadDir, moduleId);
473
- try {
474
- if (await fs.pathExists(modulePath)) {
475
- await fs.remove(modulePath);
476
- await prompts.log.message(` Removed: ${moduleId}`);
477
- }
478
- } catch (error) {
479
- await prompts.log.warn(` Warning: Failed to remove ${moduleId}: ${error.message}`);
480
- }
481
- }
482
- await prompts.log.success(` Removed ${modulesToRemove.length} module(s)`);
483
- } else {
484
- await prompts.log.message(' Module removal cancelled');
485
- // Add the modules back to the selection since user cancelled removal
486
- for (const moduleId of modulesToRemove) {
487
- if (!config.modules) config.modules = [];
488
- config.modules.push(moduleId);
489
- }
490
- }
491
-
492
- spinner.start('Preparing update...');
493
- }
494
- }
495
-
496
- // Detect custom and modified files BEFORE updating (compare current files vs files-manifest.csv)
497
- const existingFilesManifest = await this.readFilesManifest(bmadDir);
498
- const { customFiles, modifiedFiles } = await this.detectCustomFiles(bmadDir, existingFilesManifest);
499
-
500
- config._customFiles = customFiles;
501
- config._modifiedFiles = modifiedFiles;
502
-
503
- // Preserve existing core configuration during updates
504
- // Read the current core config.yaml to maintain user's settings
505
- const coreConfigPath = path.join(bmadDir, 'core', 'config.yaml');
506
- if ((await fs.pathExists(coreConfigPath)) && (!config.coreConfig || Object.keys(config.coreConfig).length === 0)) {
507
- try {
508
- const yaml = require('yaml');
509
- const coreConfigContent = await fs.readFile(coreConfigPath, 'utf8');
510
- const existingCoreConfig = yaml.parse(coreConfigContent);
511
-
512
- // Store in config.coreConfig so it's preserved through the installation
513
- config.coreConfig = existingCoreConfig;
514
-
515
- // Also store in configCollector for use during config collection
516
- this.configCollector.collectedConfig.core = existingCoreConfig;
517
- } catch (error) {
518
- await prompts.log.warn(`Warning: Could not read existing core config: ${error.message}`);
519
- }
520
- }
521
-
522
- // Also check cache directory for custom modules (like quick update does)
523
- const cacheDir = path.join(bmadDir, '_config', 'custom');
524
- if (await fs.pathExists(cacheDir)) {
525
- const cachedModules = await fs.readdir(cacheDir, { withFileTypes: true });
526
-
527
- for (const cachedModule of cachedModules) {
528
- const moduleId = cachedModule.name;
529
- const cachedPath = path.join(cacheDir, moduleId);
530
-
531
- // Skip if path doesn't exist (broken symlink, deleted dir) - avoids lstat ENOENT
532
- if (!(await fs.pathExists(cachedPath)) || !cachedModule.isDirectory()) {
533
- continue;
534
- }
535
-
536
- // Skip if we already have this module from manifest
537
- if (customModulePaths.has(moduleId)) {
538
- continue;
539
- }
540
-
541
- // Check if this is an external official module - skip cache for those
542
- const isExternal = await this.moduleManager.isExternalModule(moduleId);
543
- if (isExternal) {
544
- // External modules are handled via cloneExternalModule, not from cache
545
- continue;
546
- }
547
-
548
- // Check if this is actually a custom module (has module.yaml)
549
- const moduleYamlPath = path.join(cachedPath, 'module.yaml');
550
- if (await fs.pathExists(moduleYamlPath)) {
551
- customModulePaths.set(moduleId, cachedPath);
552
- }
553
- }
554
-
555
- // Update module manager with the new custom module paths from cache
556
- this.moduleManager.setCustomModulePaths(customModulePaths);
557
- }
558
-
559
- // If there are custom files, back them up temporarily
560
- if (customFiles.length > 0) {
561
- const tempBackupDir = path.join(projectDir, '_bmad-custom-backup-temp');
562
- await fs.ensureDir(tempBackupDir);
563
-
564
- spinner.start(`Backing up ${customFiles.length} custom files...`);
565
- for (const customFile of customFiles) {
566
- const relativePath = path.relative(bmadDir, customFile);
567
- const backupPath = path.join(tempBackupDir, relativePath);
568
- await fs.ensureDir(path.dirname(backupPath));
569
- await fs.copy(customFile, backupPath);
570
- }
571
- spinner.stop(`Backed up ${customFiles.length} custom files`);
572
-
573
- config._tempBackupDir = tempBackupDir;
574
- }
575
-
576
- // For modified files, back them up to temp directory (will be restored as .bak files after install)
577
- if (modifiedFiles.length > 0) {
578
- const tempModifiedBackupDir = path.join(projectDir, '_bmad-modified-backup-temp');
579
- await fs.ensureDir(tempModifiedBackupDir);
580
-
581
- spinner.start(`Backing up ${modifiedFiles.length} modified files...`);
582
- for (const modifiedFile of modifiedFiles) {
583
- const relativePath = path.relative(bmadDir, modifiedFile.path);
584
- const tempBackupPath = path.join(tempModifiedBackupDir, relativePath);
585
- await fs.ensureDir(path.dirname(tempBackupPath));
586
- await fs.copy(modifiedFile.path, tempBackupPath, { overwrite: true });
587
- }
588
- spinner.stop(`Backed up ${modifiedFiles.length} modified files`);
589
-
590
- config._tempModifiedBackupDir = tempModifiedBackupDir;
591
- }
592
- }
593
- } else if (existingInstall.installed && config._quickUpdate) {
594
- // Quick update mode - automatically treat as update without prompting
595
- spinner.message('Preparing quick update...');
596
- config._isUpdate = true;
597
- config._existingInstall = existingInstall;
598
-
599
- // Detect custom and modified files BEFORE updating
600
- const existingFilesManifest = await this.readFilesManifest(bmadDir);
601
- const { customFiles, modifiedFiles } = await this.detectCustomFiles(bmadDir, existingFilesManifest);
602
-
603
- config._customFiles = customFiles;
604
- config._modifiedFiles = modifiedFiles;
605
-
606
- // Also check cache directory for custom modules (like quick update does)
607
- const cacheDir = path.join(bmadDir, '_config', 'custom');
608
- if (await fs.pathExists(cacheDir)) {
609
- const cachedModules = await fs.readdir(cacheDir, { withFileTypes: true });
610
-
611
- for (const cachedModule of cachedModules) {
612
- const moduleId = cachedModule.name;
613
- const cachedPath = path.join(cacheDir, moduleId);
614
-
615
- // Skip if path doesn't exist (broken symlink, deleted dir) - avoids lstat ENOENT
616
- if (!(await fs.pathExists(cachedPath)) || !cachedModule.isDirectory()) {
617
- continue;
618
- }
619
-
620
- // Skip if we already have this module from manifest
621
- if (customModulePaths.has(moduleId)) {
622
- continue;
623
- }
624
-
625
- // Check if this is an external official module - skip cache for those
626
- const isExternal = await this.moduleManager.isExternalModule(moduleId);
627
- if (isExternal) {
628
- // External modules are handled via cloneExternalModule, not from cache
629
- continue;
630
- }
631
-
632
- // Check if this is actually a custom module (has module.yaml)
633
- const moduleYamlPath = path.join(cachedPath, 'module.yaml');
634
- if (await fs.pathExists(moduleYamlPath)) {
635
- customModulePaths.set(moduleId, cachedPath);
636
- }
637
- }
638
-
639
- // Update module manager with the new custom module paths from cache
640
- this.moduleManager.setCustomModulePaths(customModulePaths);
641
- }
642
-
643
- // Back up custom files
644
- if (customFiles.length > 0) {
645
- const tempBackupDir = path.join(projectDir, '_bmad-custom-backup-temp');
646
- await fs.ensureDir(tempBackupDir);
647
-
648
- spinner.start(`Backing up ${customFiles.length} custom files...`);
649
- for (const customFile of customFiles) {
650
- const relativePath = path.relative(bmadDir, customFile);
651
- const backupPath = path.join(tempBackupDir, relativePath);
652
- await fs.ensureDir(path.dirname(backupPath));
653
- await fs.copy(customFile, backupPath);
654
- }
655
- spinner.stop(`Backed up ${customFiles.length} custom files`);
656
- config._tempBackupDir = tempBackupDir;
657
- }
658
-
659
- // Back up modified files
660
- if (modifiedFiles.length > 0) {
661
- const tempModifiedBackupDir = path.join(projectDir, '_bmad-modified-backup-temp');
662
- await fs.ensureDir(tempModifiedBackupDir);
663
-
664
- spinner.start(`Backing up ${modifiedFiles.length} modified files...`);
665
- for (const modifiedFile of modifiedFiles) {
666
- const relativePath = path.relative(bmadDir, modifiedFile.path);
667
- const tempBackupPath = path.join(tempModifiedBackupDir, relativePath);
668
- await fs.ensureDir(path.dirname(tempBackupPath));
669
- await fs.copy(modifiedFile.path, tempBackupPath, { overwrite: true });
670
- }
671
- spinner.stop(`Backed up ${modifiedFiles.length} modified files`);
672
- config._tempModifiedBackupDir = tempModifiedBackupDir;
673
- }
674
- }
675
-
676
- // Now collect tool configurations after we know if it's a reinstall
677
- // Skip for quick update since we already have the IDE list
678
- spinner.stop('Pre-checks complete');
679
- let toolSelection;
680
- if (config._quickUpdate) {
681
- // Quick update already has IDEs configured, use saved configurations
682
- const preConfiguredIdes = {};
683
- const savedIdeConfigs = config._savedIdeConfigs || {};
684
-
685
- for (const ide of config.ides || []) {
686
- // Use saved config if available, otherwise mark as already configured (legacy)
687
- if (savedIdeConfigs[ide]) {
688
- preConfiguredIdes[ide] = savedIdeConfigs[ide];
689
- } else {
690
- preConfiguredIdes[ide] = { _alreadyConfigured: true };
691
- }
692
- }
693
- toolSelection = {
694
- ides: config.ides || [],
695
- skipIde: !config.ides || config.ides.length === 0,
696
- configurations: preConfiguredIdes,
697
- };
698
- } else {
699
- // Pass pre-selected IDEs from early prompt (if available)
700
- // This allows IDE selection to happen before file copying, improving UX
701
- // Use config.ides if it's an array (even if empty), null means prompt
702
- const preSelectedIdes = Array.isArray(config.ides) ? config.ides : null;
703
- toolSelection = await this.collectToolConfigurations(
704
- path.resolve(config.directory),
705
- config.modules,
706
- config._isFullReinstall || false,
707
- config._previouslyConfiguredIdes || [],
708
- preSelectedIdes,
709
- config.skipPrompts || false,
710
- );
711
- }
712
-
713
- // Merge tool selection into config (for both quick update and regular flow)
714
- // Normalize IDE keys to lowercase so they match handler map keys consistently
715
- config.ides = (toolSelection.ides || []).map((ide) => ide.toLowerCase());
716
- config.skipIde = toolSelection.skipIde;
717
- const ideConfigurations = toolSelection.configurations;
718
-
719
- // Early check: fail fast if ALL selected IDEs are suspended
720
- if (config.ides && config.ides.length > 0) {
721
- await this.ideManager.ensureInitialized();
722
- const suspendedIdes = config.ides.filter((ide) => {
723
- const handler = this.ideManager.handlers.get(ide);
724
- return handler?.platformConfig?.suspended;
725
- });
726
-
727
- if (suspendedIdes.length > 0 && suspendedIdes.length === config.ides.length) {
728
- for (const ide of suspendedIdes) {
729
- const handler = this.ideManager.handlers.get(ide);
730
- await prompts.log.error(`${handler.displayName || ide}: ${handler.platformConfig.suspended}`);
731
- }
732
- throw new Error(
733
- `All selected tool(s) are suspended: ${suspendedIdes.join(', ')}. Installation aborted to prevent upgrading _bmad/ without a working IDE configuration.`,
734
- );
735
- }
736
- }
737
-
738
- // Detect IDEs that were previously installed but are NOT in the new selection (to be removed)
739
- if (config._isUpdate && config._existingInstall) {
740
- const previouslyInstalledIdes = new Set(config._existingInstall.ides || []);
741
- const newlySelectedIdes = new Set(config.ides || []);
742
-
743
- const idesToRemove = [...previouslyInstalledIdes].filter((ide) => !newlySelectedIdes.has(ide));
744
-
745
- if (idesToRemove.length > 0) {
746
- if (config.skipPrompts) {
747
- // Non-interactive mode: silently preserve existing IDE configs
748
- if (!config.ides) config.ides = [];
749
- const savedIdeConfigs = await this.ideConfigManager.loadAllIdeConfigs(bmadDir);
750
- for (const ide of idesToRemove) {
751
- config.ides.push(ide);
752
- if (savedIdeConfigs[ide] && !ideConfigurations[ide]) {
753
- ideConfigurations[ide] = savedIdeConfigs[ide];
754
- }
755
- }
756
- } else {
757
- if (spinner.isSpinning) {
758
- spinner.stop('IDE changes reviewed');
759
- }
760
-
761
- await prompts.log.warn('IDEs to be removed:');
762
- for (const ide of idesToRemove) {
763
- await prompts.log.error(` - ${ide}`);
764
- }
765
-
766
- const confirmRemoval = await prompts.confirm({
767
- message: `Remove BMAD configuration for ${idesToRemove.length} IDE(s)?`,
768
- default: false,
769
- });
770
-
771
- if (confirmRemoval) {
772
- await this.ideManager.ensureInitialized();
773
- for (const ide of idesToRemove) {
774
- try {
775
- const handler = this.ideManager.handlers.get(ide);
776
- if (handler) {
777
- await handler.cleanup(projectDir);
778
- }
779
- await this.ideConfigManager.deleteIdeConfig(bmadDir, ide);
780
- await prompts.log.message(` Removed: ${ide}`);
781
- } catch (error) {
782
- await prompts.log.warn(` Warning: Failed to remove ${ide}: ${error.message}`);
783
- }
784
- }
785
- await prompts.log.success(` Removed ${idesToRemove.length} IDE(s)`);
786
- } else {
787
- await prompts.log.message(' IDE removal cancelled');
788
- // Add IDEs back to selection and restore their saved configurations
789
- if (!config.ides) config.ides = [];
790
- const savedIdeConfigs = await this.ideConfigManager.loadAllIdeConfigs(bmadDir);
791
- for (const ide of idesToRemove) {
792
- config.ides.push(ide);
793
- if (savedIdeConfigs[ide] && !ideConfigurations[ide]) {
794
- ideConfigurations[ide] = savedIdeConfigs[ide];
795
- }
796
- }
797
- }
798
-
799
- spinner.start('Preparing installation...');
800
- }
801
- }
802
- }
803
-
804
- // Results collector for consolidated summary
805
- const results = [];
806
- const addResult = (step, status, detail = '') => results.push({ step, status, detail });
807
-
808
- if (spinner.isSpinning) {
809
- spinner.message('Preparing installation...');
810
- } else {
811
- spinner.start('Preparing installation...');
812
- }
813
-
814
- // Create bmad directory structure
815
- spinner.message('Creating directory structure...');
816
- await this.createDirectoryStructure(bmadDir);
817
-
818
- // Cache custom modules if any
819
- if (customModulePaths && customModulePaths.size > 0) {
820
- spinner.message('Caching custom modules...');
821
- const { CustomModuleCache } = require('./custom-module-cache');
822
- const customCache = new CustomModuleCache(bmadDir);
823
-
824
- for (const [moduleId, sourcePath] of customModulePaths) {
825
- const cachedInfo = await customCache.cacheModule(moduleId, sourcePath, {
826
- sourcePath: sourcePath, // Store original path for updates
827
- });
828
-
829
- // Update the customModulePaths to use the cached location
830
- customModulePaths.set(moduleId, cachedInfo.cachePath);
831
- }
832
-
833
- // Update module manager with the cached paths
834
- this.moduleManager.setCustomModulePaths(customModulePaths);
835
- addResult('Custom modules cached', 'ok');
836
- }
837
-
838
- const projectRoot = getProjectRoot();
839
-
840
- // Custom content is already handled in UI before module selection
841
- const finalCustomContent = config.customContent;
842
-
843
- // Prepare modules list including cached custom modules
844
- let allModules = [...(config.modules || [])];
845
-
846
- // During quick update, we might have custom module sources from the manifest
847
- if (config._customModuleSources) {
848
- // Add custom modules from stored sources
849
- for (const [moduleId, customInfo] of config._customModuleSources) {
850
- if (!allModules.includes(moduleId) && (await fs.pathExists(customInfo.sourcePath))) {
851
- allModules.push(moduleId);
852
- }
853
- }
854
- }
855
-
856
- // Add cached custom modules
857
- if (finalCustomContent && finalCustomContent.cachedModules) {
858
- for (const cachedModule of finalCustomContent.cachedModules) {
859
- if (!allModules.includes(cachedModule.id)) {
860
- allModules.push(cachedModule.id);
861
- }
862
- }
863
- }
864
-
865
- // Regular custom content from user input (non-cached)
866
- if (finalCustomContent && finalCustomContent.selected && finalCustomContent.selectedFiles) {
867
- // Add custom modules to the installation list
868
- const customHandler = new CustomHandler();
869
- for (const customFile of finalCustomContent.selectedFiles) {
870
- const customInfo = await customHandler.getCustomInfo(customFile, projectDir);
871
- if (customInfo && customInfo.id) {
872
- allModules.push(customInfo.id);
873
- }
874
- }
875
- }
876
-
877
- // Don't include core again if already installed
878
- if (config.installCore) {
879
- allModules = allModules.filter((m) => m !== 'core');
880
- }
881
-
882
- // For dependency resolution, we only need regular modules (not custom modules)
883
- // Custom modules are already installed in _bmad and don't need dependency resolution from source
884
- const regularModulesForResolution = allModules.filter((module) => {
885
- // Check if this is a custom module
886
- const isCustom =
887
- customModulePaths.has(module) ||
888
- (finalCustomContent && finalCustomContent.cachedModules && finalCustomContent.cachedModules.some((cm) => cm.id === module)) ||
889
- (finalCustomContent &&
890
- finalCustomContent.selected &&
891
- finalCustomContent.selectedFiles &&
892
- finalCustomContent.selectedFiles.some((f) => f.includes(module)));
893
- return !isCustom;
894
- });
895
-
896
- // Stop spinner before tasks() takes over progress display
897
- spinner.stop('Preparation complete');
898
-
899
- // ─────────────────────────────────────────────────────────────────────────
900
- // FIRST TASKS BLOCK: Core installation through manifests (non-interactive)
901
- // ─────────────────────────────────────────────────────────────────────────
902
- const isQuickUpdate = config._quickUpdate || false;
903
-
904
- // Shared resolution result across task callbacks (closure-scoped, not on `this`)
905
- let taskResolution;
906
-
907
- // Collect directory creation results for output after tasks() completes
908
- const dirResults = { createdDirs: [], movedDirs: [], createdWdsFolders: [] };
909
-
910
- // Build task list conditionally
911
- const installTasks = [];
912
-
913
- // Core installation task
914
- if (config.installCore) {
915
- installTasks.push({
916
- title: isQuickUpdate ? 'Updating BMAD core' : 'Installing BMAD core',
917
- task: async (message) => {
918
- await this.installCoreWithDependencies(bmadDir, { core: {} });
919
- addResult('Core', 'ok', isQuickUpdate ? 'updated' : 'installed');
920
- await this.generateModuleConfigs(bmadDir, { core: config.coreConfig || {} });
921
- return isQuickUpdate ? 'Core updated' : 'Core installed';
922
- },
923
- });
924
- }
925
-
926
- // Dependency resolution task
927
- installTasks.push({
928
- title: 'Resolving dependencies',
929
- task: async (message) => {
930
- // Create a temporary module manager that knows about custom content locations
931
- const tempModuleManager = new ModuleManager({
932
- bmadDir: bmadDir,
933
- });
934
-
935
- taskResolution = await this.dependencyResolver.resolve(projectRoot, regularModulesForResolution, {
936
- verbose: config.verbose,
937
- moduleManager: tempModuleManager,
938
- });
939
- return 'Dependencies resolved';
940
- },
941
- });
942
-
943
- // Module installation task
944
- if (allModules && allModules.length > 0) {
945
- installTasks.push({
946
- title: isQuickUpdate ? `Updating ${allModules.length} module(s)` : `Installing ${allModules.length} module(s)`,
947
- task: async (message) => {
948
- const resolution = taskResolution;
949
- const installedModuleNames = new Set();
950
-
951
- for (const moduleName of allModules) {
952
- if (installedModuleNames.has(moduleName)) continue;
953
- installedModuleNames.add(moduleName);
954
-
955
- message(`${isQuickUpdate ? 'Updating' : 'Installing'} ${moduleName}...`);
956
-
957
- // Check if this is a custom module
958
- let isCustomModule = false;
959
- let customInfo = null;
960
-
961
- // First check if we have a cached version
962
- if (finalCustomContent && finalCustomContent.cachedModules) {
963
- const cachedModule = finalCustomContent.cachedModules.find((m) => m.id === moduleName);
964
- if (cachedModule) {
965
- isCustomModule = true;
966
- customInfo = { id: moduleName, path: cachedModule.cachePath, config: {} };
967
- }
968
- }
969
-
970
- // Then check custom module sources from manifest (for quick update)
971
- if (!isCustomModule && config._customModuleSources && config._customModuleSources.has(moduleName)) {
972
- customInfo = config._customModuleSources.get(moduleName);
973
- isCustomModule = true;
974
- if (customInfo.sourcePath && !customInfo.path) {
975
- customInfo.path = path.isAbsolute(customInfo.sourcePath)
976
- ? customInfo.sourcePath
977
- : path.join(bmadDir, customInfo.sourcePath);
978
- }
979
- }
980
-
981
- // Finally check regular custom content
982
- if (!isCustomModule && finalCustomContent && finalCustomContent.selected && finalCustomContent.selectedFiles) {
983
- const customHandler = new CustomHandler();
984
- for (const customFile of finalCustomContent.selectedFiles) {
985
- const info = await customHandler.getCustomInfo(customFile, projectDir);
986
- if (info && info.id === moduleName) {
987
- isCustomModule = true;
988
- customInfo = info;
989
- break;
990
- }
991
- }
992
- }
993
-
994
- if (isCustomModule && customInfo) {
995
- if (!customModulePaths.has(moduleName) && customInfo.path) {
996
- customModulePaths.set(moduleName, customInfo.path);
997
- this.moduleManager.setCustomModulePaths(customModulePaths);
998
- }
999
-
1000
- const collectedModuleConfig = moduleConfigs[moduleName] || {};
1001
- await this.moduleManager.install(
1002
- moduleName,
1003
- bmadDir,
1004
- (filePath) => {
1005
- this.installedFiles.add(filePath);
1006
- },
1007
- {
1008
- isCustom: true,
1009
- moduleConfig: collectedModuleConfig,
1010
- isQuickUpdate: isQuickUpdate,
1011
- installer: this,
1012
- silent: true,
1013
- },
1014
- );
1015
- await this.generateModuleConfigs(bmadDir, {
1016
- [moduleName]: { ...config.coreConfig, ...customInfo.config, ...collectedModuleConfig },
1017
- });
1018
- } else {
1019
- if (!resolution || !resolution.byModule) {
1020
- addResult(`Module: ${moduleName}`, 'warn', 'skipped (no resolution data)');
1021
- continue;
1022
- }
1023
- if (moduleName === 'core') {
1024
- await this.installCoreWithDependencies(bmadDir, resolution.byModule[moduleName]);
1025
- } else {
1026
- await this.installModuleWithDependencies(moduleName, bmadDir, resolution.byModule[moduleName]);
1027
- }
1028
- }
1029
-
1030
- addResult(`Module: ${moduleName}`, 'ok', isQuickUpdate ? 'updated' : 'installed');
1031
- }
1032
-
1033
- // Install partial modules (only dependencies)
1034
- if (!resolution || !resolution.byModule) {
1035
- return `${allModules.length} module(s) ${isQuickUpdate ? 'updated' : 'installed'}`;
1036
- }
1037
- for (const [module, files] of Object.entries(resolution.byModule)) {
1038
- if (!allModules.includes(module) && module !== 'core') {
1039
- const totalFiles =
1040
- files.agents.length +
1041
- files.tasks.length +
1042
- files.tools.length +
1043
- files.templates.length +
1044
- files.data.length +
1045
- files.other.length;
1046
- if (totalFiles > 0) {
1047
- message(`Installing ${module} dependencies...`);
1048
- await this.installPartialModule(module, bmadDir, files);
1049
- }
1050
- }
1051
- }
1052
-
1053
- return `${allModules.length} module(s) ${isQuickUpdate ? 'updated' : 'installed'}`;
1054
- },
1055
- });
1056
- }
1057
-
1058
- // Module directory creation task
1059
- installTasks.push({
1060
- title: 'Creating module directories',
1061
- task: async (message) => {
1062
- const resolution = taskResolution;
1063
- if (!resolution || !resolution.byModule) {
1064
- addResult('Module directories', 'warn', 'no resolution data');
1065
- return 'Module directories skipped (no resolution data)';
1066
- }
1067
- const verboseMode = process.env.BMAD_VERBOSE_INSTALL === 'true' || config.verbose;
1068
- const moduleLogger = {
1069
- log: async (msg) => (verboseMode ? await prompts.log.message(msg) : undefined),
1070
- error: async (msg) => await prompts.log.error(msg),
1071
- warn: async (msg) => await prompts.log.warn(msg),
1072
- };
1073
-
1074
- // Core module directories
1075
- if (config.installCore || resolution.byModule.core) {
1076
- const result = await this.moduleManager.createModuleDirectories('core', bmadDir, {
1077
- installedIDEs: config.ides || [],
1078
- moduleConfig: moduleConfigs.core || {},
1079
- existingModuleConfig: this.configCollector.existingConfig?.core || {},
1080
- coreConfig: moduleConfigs.core || {},
1081
- logger: moduleLogger,
1082
- silent: true,
1083
- });
1084
- if (result) {
1085
- dirResults.createdDirs.push(...result.createdDirs);
1086
- dirResults.movedDirs.push(...(result.movedDirs || []));
1087
- dirResults.createdWdsFolders.push(...result.createdWdsFolders);
1088
- }
1089
- }
1090
-
1091
- // User-selected module directories
1092
- if (config.modules && config.modules.length > 0) {
1093
- for (const moduleName of config.modules) {
1094
- message(`Setting up ${moduleName}...`);
1095
- const result = await this.moduleManager.createModuleDirectories(moduleName, bmadDir, {
1096
- installedIDEs: config.ides || [],
1097
- moduleConfig: moduleConfigs[moduleName] || {},
1098
- existingModuleConfig: this.configCollector.existingConfig?.[moduleName] || {},
1099
- coreConfig: moduleConfigs.core || {},
1100
- logger: moduleLogger,
1101
- silent: true,
1102
- });
1103
- if (result) {
1104
- dirResults.createdDirs.push(...result.createdDirs);
1105
- dirResults.movedDirs.push(...(result.movedDirs || []));
1106
- dirResults.createdWdsFolders.push(...result.createdWdsFolders);
1107
- }
1108
- }
1109
- }
1110
-
1111
- addResult('Module directories', 'ok');
1112
- return 'Module directories created';
1113
- },
1114
- });
1115
-
1116
- // Configuration generation task (stored as named reference for deferred execution)
1117
- const configTask = {
1118
- title: 'Generating configurations',
1119
- task: async (message) => {
1120
- // Generate clean config.yaml files for each installed module
1121
- await this.generateModuleConfigs(bmadDir, moduleConfigs);
1122
- addResult('Configurations', 'ok', 'generated');
1123
-
1124
- // Pre-register manifest files
1125
- const cfgDir = path.join(bmadDir, '_config');
1126
- this.installedFiles.add(path.join(cfgDir, 'manifest.yaml'));
1127
- this.installedFiles.add(path.join(cfgDir, 'agent-manifest.csv'));
1128
-
1129
- // Generate CSV manifests for agents, skills AND ALL FILES with hashes
1130
- // This must happen BEFORE mergeModuleHelpCatalogs because it depends on agent-manifest.csv
1131
- message('Generating manifests...');
1132
- const manifestGen = new ManifestGenerator();
1133
-
1134
- const allModulesForManifest = config._quickUpdate
1135
- ? config._existingModules || allModules || []
1136
- : config._preserveModules
1137
- ? [...allModules, ...config._preserveModules]
1138
- : allModules || [];
1139
-
1140
- let modulesForCsvPreserve;
1141
- if (config._quickUpdate) {
1142
- modulesForCsvPreserve = config._existingModules || allModules || [];
1143
- } else {
1144
- modulesForCsvPreserve = config._preserveModules ? [...allModules, ...config._preserveModules] : allModules;
1145
- }
1146
-
1147
- const manifestStats = await manifestGen.generateManifests(bmadDir, allModulesForManifest, [...this.installedFiles], {
1148
- ides: config.ides || [],
1149
- preservedModules: modulesForCsvPreserve,
1150
- });
1151
-
1152
- // Merge help catalogs
1153
- message('Generating help catalog...');
1154
- await this.mergeModuleHelpCatalogs(bmadDir);
1155
- addResult('Help catalog', 'ok');
1156
-
1157
- return 'Configurations generated';
1158
- },
1159
- };
1160
- installTasks.push(configTask);
1161
-
1162
- // Run all tasks except config (which runs after directory output)
1163
- const mainTasks = installTasks.filter((t) => t !== configTask);
1164
- await prompts.tasks(mainTasks);
1165
-
1166
- // Render directory creation output right after directory task
1167
- const color = await prompts.getColor();
1168
- if (dirResults.movedDirs.length > 0) {
1169
- const lines = dirResults.movedDirs.map((d) => ` ${d}`).join('\n');
1170
- await prompts.log.message(color.cyan(`Moved directories:\n${lines}`));
1171
- }
1172
- if (dirResults.createdDirs.length > 0) {
1173
- const lines = dirResults.createdDirs.map((d) => ` ${d}`).join('\n');
1174
- await prompts.log.message(color.yellow(`Created directories:\n${lines}`));
1175
- }
1176
- if (dirResults.createdWdsFolders.length > 0) {
1177
- const lines = dirResults.createdWdsFolders.map((f) => color.dim(` \u2713 ${f}/`)).join('\n');
1178
- await prompts.log.message(color.cyan(`Created WDS folder structure:\n${lines}`));
1179
- }
1180
-
1181
- // Now run configuration generation
1182
- await prompts.tasks([configTask]);
1183
-
1184
- // Resolution is now available via closure-scoped taskResolution
1185
- const resolution = taskResolution;
1186
-
1187
- // ─────────────────────────────────────────────────────────────────────────
1188
- // IDE SETUP: Keep as spinner since it may prompt for user input
1189
- // ─────────────────────────────────────────────────────────────────────────
1190
- if (!config.skipIde && config.ides && config.ides.length > 0) {
1191
- await this.ideManager.ensureInitialized();
1192
- const validIdes = config.ides.filter((ide) => ide && typeof ide === 'string');
1193
-
1194
- if (validIdes.length === 0) {
1195
- addResult('IDE configuration', 'warn', 'no valid IDEs selected');
1196
- } else {
1197
- const needsPrompting = validIdes.some((ide) => !ideConfigurations[ide]);
1198
- const ideSpinner = await prompts.spinner();
1199
- ideSpinner.start('Configuring tools...');
1200
-
1201
- try {
1202
- for (const ide of validIdes) {
1203
- if (!needsPrompting || ideConfigurations[ide]) {
1204
- ideSpinner.message(`Configuring ${ide}...`);
1205
- } else {
1206
- if (ideSpinner.isSpinning) {
1207
- ideSpinner.stop('Ready for IDE configuration');
1208
- }
1209
- }
1210
-
1211
- // Suppress stray console output for pre-configured IDEs (no user interaction)
1212
- const ideHasConfig = Boolean(ideConfigurations[ide]);
1213
- const originalLog = console.log;
1214
- if (!config.verbose && ideHasConfig) {
1215
- console.log = () => {};
1216
- }
1217
- try {
1218
- const setupResult = await this.ideManager.setup(ide, projectDir, bmadDir, {
1219
- selectedModules: allModules || [],
1220
- preCollectedConfig: ideConfigurations[ide] || null,
1221
- verbose: config.verbose,
1222
- silent: ideHasConfig,
1223
- });
1224
-
1225
- if (ideConfigurations[ide] && !ideConfigurations[ide]._alreadyConfigured) {
1226
- await this.ideConfigManager.saveIdeConfig(bmadDir, ide, ideConfigurations[ide]);
1227
- }
1228
-
1229
- if (setupResult.success) {
1230
- addResult(ide, 'ok', setupResult.detail || '');
1231
- } else {
1232
- addResult(ide, 'error', setupResult.error || 'failed');
1233
- }
1234
- } finally {
1235
- console.log = originalLog;
1236
- }
1237
-
1238
- if (needsPrompting && !ideSpinner.isSpinning) {
1239
- ideSpinner.start('Configuring tools...');
1240
- }
1241
- }
1242
- } finally {
1243
- if (ideSpinner.isSpinning) {
1244
- ideSpinner.stop('Tool configuration complete');
1245
- }
1246
- }
1247
- }
1248
- }
1249
-
1250
- // ─────────────────────────────────────────────────────────────────────────
1251
- // SECOND TASKS BLOCK: Post-IDE operations (non-interactive)
1252
- // ─────────────────────────────────────────────────────────────────────────
1253
- const postIdeTasks = [];
1254
-
1255
- // File restoration task (only for updates)
1256
- if (
1257
- config._isUpdate &&
1258
- ((config._customFiles && config._customFiles.length > 0) || (config._modifiedFiles && config._modifiedFiles.length > 0))
1259
- ) {
1260
- postIdeTasks.push({
1261
- title: 'Finalizing installation',
1262
- task: async (message) => {
1263
- let customFiles = [];
1264
- let modifiedFiles = [];
1265
-
1266
- if (config._customFiles && config._customFiles.length > 0) {
1267
- message(`Restoring ${config._customFiles.length} custom files...`);
1268
-
1269
- for (const originalPath of config._customFiles) {
1270
- const relativePath = path.relative(bmadDir, originalPath);
1271
- const backupPath = path.join(config._tempBackupDir, relativePath);
1272
-
1273
- if (await fs.pathExists(backupPath)) {
1274
- await fs.ensureDir(path.dirname(originalPath));
1275
- await fs.copy(backupPath, originalPath, { overwrite: true });
1276
- }
1277
- }
1278
-
1279
- if (config._tempBackupDir && (await fs.pathExists(config._tempBackupDir))) {
1280
- await fs.remove(config._tempBackupDir);
1281
- }
1282
-
1283
- customFiles = config._customFiles;
1284
- }
1285
-
1286
- if (config._modifiedFiles && config._modifiedFiles.length > 0) {
1287
- modifiedFiles = config._modifiedFiles;
1288
-
1289
- if (config._tempModifiedBackupDir && (await fs.pathExists(config._tempModifiedBackupDir))) {
1290
- message(`Restoring ${modifiedFiles.length} modified files as .bak...`);
1291
-
1292
- for (const modifiedFile of modifiedFiles) {
1293
- const relativePath = path.relative(bmadDir, modifiedFile.path);
1294
- const tempBackupPath = path.join(config._tempModifiedBackupDir, relativePath);
1295
- const bakPath = modifiedFile.path + '.bak';
1296
-
1297
- if (await fs.pathExists(tempBackupPath)) {
1298
- await fs.ensureDir(path.dirname(bakPath));
1299
- await fs.copy(tempBackupPath, bakPath, { overwrite: true });
1300
- }
1301
- }
1302
-
1303
- await fs.remove(config._tempModifiedBackupDir);
1304
- }
1305
- }
1306
-
1307
- // Store for summary access
1308
- config._restoredCustomFiles = customFiles;
1309
- config._restoredModifiedFiles = modifiedFiles;
1310
-
1311
- return 'Installation finalized';
1312
- },
1313
- });
1314
- }
1315
-
1316
- await prompts.tasks(postIdeTasks);
1317
-
1318
- // Retrieve restored file info for summary
1319
- const customFiles = config._restoredCustomFiles || [];
1320
- const modifiedFiles = config._restoredModifiedFiles || [];
1321
-
1322
- // Render consolidated summary
1323
- await this.renderInstallSummary(results, {
1324
- bmadDir,
1325
- modules: config.modules,
1326
- ides: config.ides,
1327
- customFiles: customFiles.length > 0 ? customFiles : undefined,
1328
- modifiedFiles: modifiedFiles.length > 0 ? modifiedFiles : undefined,
1329
- });
1330
-
1331
- return {
1332
- success: true,
1333
- path: bmadDir,
1334
- modules: config.modules,
1335
- ides: config.ides,
1336
- projectDir: projectDir,
1337
- };
1338
- } catch (error) {
1339
- try {
1340
- if (spinner.isSpinning) {
1341
- spinner.error('Installation failed');
1342
- } else {
1343
- await prompts.log.error('Installation failed');
1344
- }
1345
- } catch {
1346
- // Ensure the original error is never swallowed by a logging failure
1347
- }
1348
-
1349
- // Clean up any temp backup directories that were created before the failure
1350
- try {
1351
- if (config._tempBackupDir && (await fs.pathExists(config._tempBackupDir))) {
1352
- await fs.remove(config._tempBackupDir);
1353
- }
1354
- if (config._tempModifiedBackupDir && (await fs.pathExists(config._tempModifiedBackupDir))) {
1355
- await fs.remove(config._tempModifiedBackupDir);
1356
- }
1357
- } catch {
1358
- // Best-effort cleanup — don't mask the original error
1359
- }
1360
-
1361
- throw error;
1362
- }
1363
- }
1364
-
1365
- /**
1366
- * Render a consolidated install summary using prompts.note()
1367
- * @param {Array} results - Array of {step, status: 'ok'|'error'|'warn', detail}
1368
- * @param {Object} context - {bmadDir, modules, ides, customFiles, modifiedFiles}
1369
- */
1370
- async renderInstallSummary(results, context = {}) {
1371
- const color = await prompts.getColor();
1372
- const selectedIdes = new Set((context.ides || []).map((ide) => String(ide).toLowerCase()));
1373
-
1374
- // Build step lines with status indicators
1375
- const lines = [];
1376
- for (const r of results) {
1377
- let stepLabel = null;
1378
-
1379
- if (r.status !== 'ok') {
1380
- stepLabel = r.step;
1381
- } else if (r.step === 'Core') {
1382
- stepLabel = 'BMAD';
1383
- } else if (r.step.startsWith('Module: ')) {
1384
- stepLabel = r.step;
1385
- } else if (selectedIdes.has(String(r.step).toLowerCase())) {
1386
- stepLabel = r.step;
1387
- }
1388
-
1389
- if (!stepLabel) {
1390
- continue;
1391
- }
1392
-
1393
- let icon;
1394
- if (r.status === 'ok') {
1395
- icon = color.green('\u2713');
1396
- } else if (r.status === 'warn') {
1397
- icon = color.yellow('!');
1398
- } else {
1399
- icon = color.red('\u2717');
1400
- }
1401
- const detail = r.detail ? color.dim(` (${r.detail})`) : '';
1402
- lines.push(` ${icon} ${stepLabel}${detail}`);
1403
- }
1404
-
1405
- if ((context.ides || []).length === 0) {
1406
- lines.push(` ${color.green('\u2713')} No IDE selected ${color.dim('(installed in _bmad only)')}`);
1407
- }
1408
-
1409
- // Context and warnings
1410
- lines.push('');
1411
- if (context.bmadDir) {
1412
- lines.push(` Installed to: ${color.dim(context.bmadDir)}`);
1413
- }
1414
- if (context.customFiles && context.customFiles.length > 0) {
1415
- lines.push(` ${color.cyan(`Custom files preserved: ${context.customFiles.length}`)}`);
1416
- }
1417
- if (context.modifiedFiles && context.modifiedFiles.length > 0) {
1418
- lines.push(` ${color.yellow(`Modified files backed up (.bak): ${context.modifiedFiles.length}`)}`);
1419
- }
1420
-
1421
- // Next steps
1422
- lines.push(
1423
- '',
1424
- ' Next steps:',
1425
- ` Read our new Docs Site: ${color.dim('https://docs.bmad-method.org/')}`,
1426
- ` Join our Discord: ${color.dim('https://discord.gg/gk8jAdXWmj')}`,
1427
- ` Star us on GitHub: ${color.dim('https://github.com/bmad-code-org/BMAD-METHOD/')}`,
1428
- ` Subscribe on YouTube: ${color.dim('https://www.youtube.com/@BMadCode')}`,
1429
- );
1430
- if (context.ides && context.ides.length > 0) {
1431
- lines.push(` Invoke the ${color.cyan('bmad-help')} skill in your IDE Agent to get started`);
1432
- }
1433
-
1434
- await prompts.note(lines.join('\n'), 'BMAD is ready to use!');
1435
- }
1436
-
1437
- /**
1438
- * Update existing installation
1439
- */
1440
- async update(config) {
1441
- const spinner = await prompts.spinner();
1442
- spinner.start('Checking installation...');
1443
-
1444
- try {
1445
- const projectDir = path.resolve(config.directory);
1446
- const { bmadDir } = await this.findBmadDir(projectDir);
1447
- const existingInstall = await this.detector.detect(bmadDir);
1448
-
1449
- if (!existingInstall.installed) {
1450
- spinner.stop('No BMAD installation found');
1451
- throw new Error(`No BMAD installation found at ${bmadDir}`);
1452
- }
1453
-
1454
- spinner.message('Analyzing update requirements...');
1455
-
1456
- // Compare versions and determine what needs updating
1457
- const currentVersion = existingInstall.version;
1458
- const newVersion = require(path.join(getProjectRoot(), 'package.json')).version;
1459
-
1460
- // Check for custom modules with missing sources before update
1461
- const customModuleSources = new Map();
1462
-
1463
- // Check manifest for backward compatibility
1464
- if (existingInstall.customModules) {
1465
- for (const customModule of existingInstall.customModules) {
1466
- customModuleSources.set(customModule.id, customModule);
1467
- }
1468
- }
1469
-
1470
- // Also check cache directory
1471
- const cacheDir = path.join(bmadDir, '_config', 'custom');
1472
- if (await fs.pathExists(cacheDir)) {
1473
- const cachedModules = await fs.readdir(cacheDir, { withFileTypes: true });
1474
-
1475
- for (const cachedModule of cachedModules) {
1476
- if (cachedModule.isDirectory()) {
1477
- const moduleId = cachedModule.name;
1478
-
1479
- // Skip if we already have this module
1480
- if (customModuleSources.has(moduleId)) {
1481
- continue;
1482
- }
1483
-
1484
- // Check if this is an external official module - skip cache for those
1485
- const isExternal = await this.moduleManager.isExternalModule(moduleId);
1486
- if (isExternal) {
1487
- // External modules are handled via cloneExternalModule, not from cache
1488
- continue;
1489
- }
1490
-
1491
- const cachedPath = path.join(cacheDir, moduleId);
1492
-
1493
- // Check if this is actually a custom module (has module.yaml)
1494
- const moduleYamlPath = path.join(cachedPath, 'module.yaml');
1495
- if (await fs.pathExists(moduleYamlPath)) {
1496
- customModuleSources.set(moduleId, {
1497
- id: moduleId,
1498
- name: moduleId,
1499
- sourcePath: path.join('_config', 'custom', moduleId), // Relative path
1500
- cached: true,
1501
- });
1502
- }
1503
- }
1504
- }
1505
- }
1506
-
1507
- if (customModuleSources.size > 0) {
1508
- spinner.stop('Update analysis complete');
1509
- await prompts.log.warn('Checking custom module sources before update...');
1510
-
1511
- const projectRoot = getProjectRoot();
1512
- await this.handleMissingCustomSources(
1513
- customModuleSources,
1514
- bmadDir,
1515
- projectRoot,
1516
- 'update',
1517
- existingInstall.modules.map((m) => m.id),
1518
- config.skipPrompts || false,
1519
- );
1520
-
1521
- spinner.start('Preparing update...');
1522
- }
1523
-
1524
- if (config.dryRun) {
1525
- spinner.stop('Dry run analysis complete');
1526
- let dryRunContent = `Current version: ${currentVersion}\n`;
1527
- dryRunContent += `New version: ${newVersion}\n`;
1528
- dryRunContent += `Core: ${existingInstall.hasCore ? 'Will be updated' : 'Not installed'}`;
1529
-
1530
- if (existingInstall.modules.length > 0) {
1531
- dryRunContent += '\n\nModules to update:';
1532
- for (const mod of existingInstall.modules) {
1533
- dryRunContent += `\n - ${mod.id}`;
1534
- }
1535
- }
1536
- await prompts.note(dryRunContent, 'Update Preview (Dry Run)');
1537
- return;
1538
- }
1539
-
1540
- // Perform actual update
1541
- if (existingInstall.hasCore) {
1542
- spinner.message('Updating core...');
1543
- await this.updateCore(bmadDir, config.force);
1544
- }
1545
-
1546
- for (const module of existingInstall.modules) {
1547
- spinner.message(`Updating module: ${module.id}...`);
1548
- await this.moduleManager.update(module.id, bmadDir, config.force, { installer: this });
1549
- }
1550
-
1551
- // Update manifest
1552
- spinner.message('Updating manifest...');
1553
- await this.manifest.update(bmadDir, {
1554
- version: newVersion,
1555
- updateDate: new Date().toISOString(),
1556
- });
1557
-
1558
- spinner.stop('Update complete');
1559
- return { success: true };
1560
- } catch (error) {
1561
- spinner.error('Update failed');
1562
- throw error;
1563
- }
1564
- }
1565
-
1566
- /**
1567
- * Get installation status
1568
- */
1569
- async getStatus(directory) {
1570
- const projectDir = path.resolve(directory);
1571
- const { bmadDir } = await this.findBmadDir(projectDir);
1572
- return await this.detector.detect(bmadDir);
1573
- }
1574
-
1575
- /**
1576
- * Get available modules
1577
- */
1578
- async getAvailableModules() {
1579
- return await this.moduleManager.listAvailable();
1580
- }
1581
-
1582
- /**
1583
- * Uninstall BMAD with selective removal options
1584
- * @param {string} directory - Project directory
1585
- * @param {Object} options - Uninstall options
1586
- * @param {boolean} [options.removeModules=true] - Remove _bmad/ directory
1587
- * @param {boolean} [options.removeIdeConfigs=true] - Remove IDE configurations
1588
- * @param {boolean} [options.removeOutputFolder=false] - Remove user artifacts output folder
1589
- * @returns {Object} Result with success status and removed components
1590
- */
1591
- async uninstall(directory, options = {}) {
1592
- const projectDir = path.resolve(directory);
1593
- const { bmadDir } = await this.findBmadDir(projectDir);
1594
-
1595
- if (!(await fs.pathExists(bmadDir))) {
1596
- return { success: false, reason: 'not-installed' };
1597
- }
1598
-
1599
- // 1. DETECT: Read state BEFORE deleting anything
1600
- const existingInstall = await this.detector.detect(bmadDir);
1601
- const outputFolder = await this._readOutputFolder(bmadDir);
1602
-
1603
- const removed = { modules: false, ideConfigs: false, outputFolder: false };
1604
-
1605
- // 2. IDE CLEANUP (before _bmad/ deletion so configs are accessible)
1606
- if (options.removeIdeConfigs !== false) {
1607
- await this.uninstallIdeConfigs(projectDir, existingInstall, { silent: options.silent });
1608
- removed.ideConfigs = true;
1609
- }
1610
-
1611
- // 3. OUTPUT FOLDER (only if explicitly requested)
1612
- if (options.removeOutputFolder === true && outputFolder) {
1613
- removed.outputFolder = await this.uninstallOutputFolder(projectDir, outputFolder);
1614
- }
1615
-
1616
- // 4. BMAD DIRECTORY (last, after everything that needs it)
1617
- if (options.removeModules !== false) {
1618
- removed.modules = await this.uninstallModules(projectDir);
1619
- }
1620
-
1621
- return { success: true, removed, version: existingInstall.version };
1622
- }
1623
-
1624
- /**
1625
- * Uninstall IDE configurations only
1626
- * @param {string} projectDir - Project directory
1627
- * @param {Object} existingInstall - Detection result from detector.detect()
1628
- * @param {Object} [options] - Options (e.g. { silent: true })
1629
- * @returns {Promise<Object>} Results from IDE cleanup
1630
- */
1631
- async uninstallIdeConfigs(projectDir, existingInstall, options = {}) {
1632
- await this.ideManager.ensureInitialized();
1633
- const cleanupOptions = { isUninstall: true, silent: options.silent };
1634
- const ideList = existingInstall.ides || [];
1635
- if (ideList.length > 0) {
1636
- return this.ideManager.cleanupByList(projectDir, ideList, cleanupOptions);
1637
- }
1638
- return this.ideManager.cleanup(projectDir, cleanupOptions);
1639
- }
1640
-
1641
- /**
1642
- * Remove user artifacts output folder
1643
- * @param {string} projectDir - Project directory
1644
- * @param {string} outputFolder - Output folder name (relative)
1645
- * @returns {Promise<boolean>} Whether the folder was removed
1646
- */
1647
- async uninstallOutputFolder(projectDir, outputFolder) {
1648
- if (!outputFolder) return false;
1649
- const resolvedProject = path.resolve(projectDir);
1650
- const outputPath = path.resolve(resolvedProject, outputFolder);
1651
- if (!outputPath.startsWith(resolvedProject + path.sep)) {
1652
- return false;
1653
- }
1654
- if (await fs.pathExists(outputPath)) {
1655
- await fs.remove(outputPath);
1656
- return true;
1657
- }
1658
- return false;
1659
- }
1660
-
1661
- /**
1662
- * Remove the _bmad/ directory
1663
- * @param {string} projectDir - Project directory
1664
- * @returns {Promise<boolean>} Whether the directory was removed
1665
- */
1666
- async uninstallModules(projectDir) {
1667
- const { bmadDir } = await this.findBmadDir(projectDir);
1668
- if (await fs.pathExists(bmadDir)) {
1669
- await fs.remove(bmadDir);
1670
- return true;
1671
- }
1672
- return false;
1673
- }
1674
-
1675
- /**
1676
- * Get the configured output folder name for a project
1677
- * Resolves bmadDir internally from projectDir
1678
- * @param {string} projectDir - Project directory
1679
- * @returns {string} Output folder name (relative, default: '_bmad-output')
1680
- */
1681
- async getOutputFolder(projectDir) {
1682
- const { bmadDir } = await this.findBmadDir(projectDir);
1683
- return this._readOutputFolder(bmadDir);
1684
- }
1685
-
1686
- /**
1687
- * Read the output_folder setting from module config files
1688
- * Checks bmm/config.yaml first, then other module configs
1689
- * @param {string} bmadDir - BMAD installation directory
1690
- * @returns {string} Output folder path or default
1691
- */
1692
- async _readOutputFolder(bmadDir) {
1693
- const yaml = require('yaml');
1694
-
1695
- // Check bmm/config.yaml first (most common)
1696
- const bmmConfigPath = path.join(bmadDir, 'bmm', 'config.yaml');
1697
- if (await fs.pathExists(bmmConfigPath)) {
1698
- try {
1699
- const content = await fs.readFile(bmmConfigPath, 'utf8');
1700
- const config = yaml.parse(content);
1701
- if (config && config.output_folder) {
1702
- // Strip {project-root}/ prefix if present
1703
- return config.output_folder.replace(/^\{project-root\}[/\\]/, '');
1704
- }
1705
- } catch {
1706
- // Fall through to other modules
1707
- }
1708
- }
1709
-
1710
- // Scan other module config.yaml files
1711
- try {
1712
- const entries = await fs.readdir(bmadDir, { withFileTypes: true });
1713
- for (const entry of entries) {
1714
- if (!entry.isDirectory() || entry.name === 'bmm' || entry.name.startsWith('_')) continue;
1715
- const configPath = path.join(bmadDir, entry.name, 'config.yaml');
1716
- if (await fs.pathExists(configPath)) {
1717
- try {
1718
- const content = await fs.readFile(configPath, 'utf8');
1719
- const config = yaml.parse(content);
1720
- if (config && config.output_folder) {
1721
- return config.output_folder.replace(/^\{project-root\}[/\\]/, '');
1722
- }
1723
- } catch {
1724
- // Continue scanning
1725
- }
1726
- }
1727
- }
1728
- } catch {
1729
- // Directory scan failed
1730
- }
1731
-
1732
- // Default fallback
1733
- return '_bmad-output';
1734
- }
1735
-
1736
- /**
1737
- * Private: Create directory structure
1738
- */
1739
- /**
1740
- * Merge all module-help.csv files into a single bmad-help.csv
1741
- * Scans all installed modules for module-help.csv and merges them
1742
- * Enriches agent info from agent-manifest.csv
1743
- * Output is written to _bmad/_config/bmad-help.csv
1744
- * @param {string} bmadDir - BMAD installation directory
1745
- */
1746
- async mergeModuleHelpCatalogs(bmadDir) {
1747
- const allRows = [];
1748
- const headerRow =
1749
- 'module,phase,name,code,sequence,workflow-file,command,required,agent-name,agent-command,agent-display-name,agent-title,options,description,output-location,outputs';
1750
-
1751
- // Load agent manifest for agent info lookup
1752
- const agentManifestPath = path.join(bmadDir, '_config', 'agent-manifest.csv');
1753
- const agentInfo = new Map(); // agent-name -> {command, displayName, title+icon}
1754
-
1755
- if (await fs.pathExists(agentManifestPath)) {
1756
- const manifestContent = await fs.readFile(agentManifestPath, 'utf8');
1757
- const lines = manifestContent.split('\n').filter((line) => line.trim());
1758
-
1759
- for (const line of lines) {
1760
- if (line.startsWith('name,')) continue; // Skip header
1761
-
1762
- const cols = line.split(',');
1763
- if (cols.length >= 4) {
1764
- const agentName = cols[0].replaceAll('"', '').trim();
1765
- const displayName = cols[1].replaceAll('"', '').trim();
1766
- const title = cols[2].replaceAll('"', '').trim();
1767
- const icon = cols[3].replaceAll('"', '').trim();
1768
- const module = cols[10] ? cols[10].replaceAll('"', '').trim() : '';
1769
-
1770
- // Build agent command: bmad:module:agent:name
1771
- const agentCommand = module ? `bmad:${module}:agent:${agentName}` : `bmad:agent:${agentName}`;
1772
-
1773
- agentInfo.set(agentName, {
1774
- command: agentCommand,
1775
- displayName: displayName || agentName,
1776
- title: icon && title ? `${icon} ${title}` : title || agentName,
1777
- });
1778
- }
1779
- }
1780
- }
1781
-
1782
- // Get all installed module directories
1783
- const entries = await fs.readdir(bmadDir, { withFileTypes: true });
1784
- const installedModules = entries
1785
- .filter((entry) => entry.isDirectory() && entry.name !== '_config' && entry.name !== 'docs' && entry.name !== '_memory')
1786
- .map((entry) => entry.name);
1787
-
1788
- // Add core module to scan (it's installed at root level as _config, but we check src/core-skills)
1789
- const coreModulePath = getSourcePath('core-skills');
1790
- const modulePaths = new Map();
1791
-
1792
- // Map all module source paths
1793
- if (await fs.pathExists(coreModulePath)) {
1794
- modulePaths.set('core', coreModulePath);
1795
- }
1796
-
1797
- // Map installed module paths
1798
- for (const moduleName of installedModules) {
1799
- const modulePath = path.join(bmadDir, moduleName);
1800
- modulePaths.set(moduleName, modulePath);
1801
- }
1802
-
1803
- // Scan each module for module-help.csv
1804
- for (const [moduleName, modulePath] of modulePaths) {
1805
- const helpFilePath = path.join(modulePath, 'module-help.csv');
1806
-
1807
- if (await fs.pathExists(helpFilePath)) {
1808
- try {
1809
- const content = await fs.readFile(helpFilePath, 'utf8');
1810
- const lines = content.split('\n').filter((line) => line.trim() && !line.startsWith('#'));
1811
-
1812
- for (const line of lines) {
1813
- // Skip header row
1814
- if (line.startsWith('module,')) {
1815
- continue;
1816
- }
1817
-
1818
- // Parse the line - handle quoted fields with commas
1819
- const columns = this.parseCSVLine(line);
1820
- if (columns.length >= 12) {
1821
- // Map old schema to new schema
1822
- // Old: module,phase,name,code,sequence,workflow-file,command,required,agent,options,description,output-location,outputs
1823
- // New: module,phase,name,code,sequence,workflow-file,command,required,agent-name,agent-command,agent-display-name,agent-title,options,description,output-location,outputs
1824
-
1825
- const [
1826
- module,
1827
- phase,
1828
- name,
1829
- code,
1830
- sequence,
1831
- workflowFile,
1832
- command,
1833
- required,
1834
- agentName,
1835
- options,
1836
- description,
1837
- outputLocation,
1838
- outputs,
1839
- ] = columns;
1840
-
1841
- // If module column is empty, set it to this module's name (except for core which stays empty for universal tools)
1842
- const finalModule = (!module || module.trim() === '') && moduleName !== 'core' ? moduleName : module || '';
1843
-
1844
- // Lookup agent info
1845
- const cleanAgentName = agentName ? agentName.trim() : '';
1846
- const agentData = agentInfo.get(cleanAgentName) || { command: '', displayName: '', title: '' };
1847
-
1848
- // Build new row with agent info
1849
- const newRow = [
1850
- finalModule,
1851
- phase || '',
1852
- name || '',
1853
- code || '',
1854
- sequence || '',
1855
- workflowFile || '',
1856
- command || '',
1857
- required || 'false',
1858
- cleanAgentName,
1859
- agentData.command,
1860
- agentData.displayName,
1861
- agentData.title,
1862
- options || '',
1863
- description || '',
1864
- outputLocation || '',
1865
- outputs || '',
1866
- ];
1867
-
1868
- allRows.push(newRow.map((c) => this.escapeCSVField(c)).join(','));
1869
- }
1870
- }
1871
-
1872
- if (process.env.BMAD_VERBOSE_INSTALL === 'true') {
1873
- await prompts.log.message(` Merged module-help from: ${moduleName}`);
1874
- }
1875
- } catch (error) {
1876
- await prompts.log.warn(` Warning: Failed to read module-help.csv from ${moduleName}: ${error.message}`);
1877
- }
1878
- }
1879
- }
1880
-
1881
- // Sort by module, then phase, then sequence
1882
- allRows.sort((a, b) => {
1883
- const colsA = this.parseCSVLine(a);
1884
- const colsB = this.parseCSVLine(b);
1885
-
1886
- // Module comparison (empty module/universal tools come first)
1887
- const moduleA = (colsA[0] || '').toLowerCase();
1888
- const moduleB = (colsB[0] || '').toLowerCase();
1889
- if (moduleA !== moduleB) {
1890
- return moduleA.localeCompare(moduleB);
1891
- }
1892
-
1893
- // Phase comparison
1894
- const phaseA = colsA[1] || '';
1895
- const phaseB = colsB[1] || '';
1896
- if (phaseA !== phaseB) {
1897
- return phaseA.localeCompare(phaseB);
1898
- }
1899
-
1900
- // Sequence comparison
1901
- const seqA = parseInt(colsA[4] || '0', 10);
1902
- const seqB = parseInt(colsB[4] || '0', 10);
1903
- return seqA - seqB;
1904
- });
1905
-
1906
- // Write merged catalog
1907
- const outputDir = path.join(bmadDir, '_config');
1908
- await fs.ensureDir(outputDir);
1909
- const outputPath = path.join(outputDir, 'bmad-help.csv');
1910
-
1911
- const mergedContent = [headerRow, ...allRows].join('\n');
1912
- await fs.writeFile(outputPath, mergedContent, 'utf8');
1913
-
1914
- // Track the installed file
1915
- this.installedFiles.add(outputPath);
1916
-
1917
- if (process.env.BMAD_VERBOSE_INSTALL === 'true') {
1918
- await prompts.log.message(` Generated bmad-help.csv: ${allRows.length} workflows`);
1919
- }
1920
- }
1921
-
1922
- /**
1923
- * Parse a CSV line, handling quoted fields
1924
- * @param {string} line - CSV line to parse
1925
- * @returns {Array} Array of field values
1926
- */
1927
- parseCSVLine(line) {
1928
- const result = [];
1929
- let current = '';
1930
- let inQuotes = false;
1931
-
1932
- for (let i = 0; i < line.length; i++) {
1933
- const char = line[i];
1934
- const nextChar = line[i + 1];
1935
-
1936
- if (char === '"') {
1937
- if (inQuotes && nextChar === '"') {
1938
- // Escaped quote
1939
- current += '"';
1940
- i++; // Skip next quote
1941
- } else {
1942
- // Toggle quote mode
1943
- inQuotes = !inQuotes;
1944
- }
1945
- } else if (char === ',' && !inQuotes) {
1946
- result.push(current);
1947
- current = '';
1948
- } else {
1949
- current += char;
1950
- }
1951
- }
1952
- result.push(current);
1953
- return result;
1954
- }
1955
-
1956
- /**
1957
- * Escape a CSV field if it contains special characters
1958
- * @param {string} field - Field value to escape
1959
- * @returns {string} Escaped field
1960
- */
1961
- escapeCSVField(field) {
1962
- if (field === null || field === undefined) {
1963
- return '';
1964
- }
1965
- const str = String(field);
1966
- // If field contains comma, quote, or newline, wrap in quotes and escape inner quotes
1967
- if (str.includes(',') || str.includes('"') || str.includes('\n')) {
1968
- return `"${str.replaceAll('"', '""')}"`;
1969
- }
1970
- return str;
1971
- }
1972
-
1973
- async createDirectoryStructure(bmadDir) {
1974
- await fs.ensureDir(bmadDir);
1975
- await fs.ensureDir(path.join(bmadDir, '_config'));
1976
- await fs.ensureDir(path.join(bmadDir, '_config', 'agents'));
1977
- await fs.ensureDir(path.join(bmadDir, '_config', 'custom'));
1978
- }
1979
-
1980
- /**
1981
- * Generate clean config.yaml files for each installed module
1982
- * @param {string} bmadDir - BMAD installation directory
1983
- * @param {Object} moduleConfigs - Collected configuration values
1984
- */
1985
- async generateModuleConfigs(bmadDir, moduleConfigs) {
1986
- const yaml = require('yaml');
1987
-
1988
- // Extract core config values to share with other modules
1989
- const coreConfig = moduleConfigs.core || {};
1990
-
1991
- // Get all installed module directories
1992
- const entries = await fs.readdir(bmadDir, { withFileTypes: true });
1993
- const installedModules = entries
1994
- .filter((entry) => entry.isDirectory() && entry.name !== '_config' && entry.name !== 'docs')
1995
- .map((entry) => entry.name);
1996
-
1997
- // Generate config.yaml for each installed module
1998
- for (const moduleName of installedModules) {
1999
- const modulePath = path.join(bmadDir, moduleName);
2000
-
2001
- // Get module-specific config or use empty object if none
2002
- const config = moduleConfigs[moduleName] || {};
2003
-
2004
- if (await fs.pathExists(modulePath)) {
2005
- const configPath = path.join(modulePath, 'config.yaml');
2006
-
2007
- // Create header
2008
- const packageJson = require(path.join(getProjectRoot(), 'package.json'));
2009
- const header = `# ${moduleName.toUpperCase()} Module Configuration
2010
- # Generated by BMAD installer
2011
- # Version: ${packageJson.version}
2012
- # Date: ${new Date().toISOString()}
2013
-
2014
- `;
2015
-
2016
- // For non-core modules, add core config values directly
2017
- let finalConfig = { ...config };
2018
- let coreSection = '';
2019
-
2020
- if (moduleName !== 'core' && coreConfig && Object.keys(coreConfig).length > 0) {
2021
- // Add core values directly to the module config
2022
- // These will be available for reference in the module
2023
- finalConfig = {
2024
- ...config,
2025
- ...coreConfig, // Spread core config values directly into the module config
2026
- };
2027
-
2028
- // Create a comment section to identify core values
2029
- coreSection = '\n# Core Configuration Values\n';
2030
- }
2031
-
2032
- // Clean the config to remove any non-serializable values (like functions)
2033
- const cleanConfig = structuredClone(finalConfig);
2034
-
2035
- // Convert config to YAML
2036
- let yamlContent = yaml.stringify(cleanConfig, {
2037
- indent: 2,
2038
- lineWidth: 0,
2039
- minContentWidth: 0,
2040
- });
2041
-
2042
- // If we have core values, reorganize the YAML to group them with their comment
2043
- if (coreSection && moduleName !== 'core') {
2044
- // Split the YAML into lines
2045
- const lines = yamlContent.split('\n');
2046
- const moduleConfigLines = [];
2047
- const coreConfigLines = [];
2048
-
2049
- // Separate module-specific and core config lines
2050
- for (const line of lines) {
2051
- const key = line.split(':')[0].trim();
2052
- if (Object.prototype.hasOwnProperty.call(coreConfig, key)) {
2053
- coreConfigLines.push(line);
2054
- } else {
2055
- moduleConfigLines.push(line);
2056
- }
2057
- }
2058
-
2059
- // Rebuild YAML with module config first, then core config with comment
2060
- yamlContent = moduleConfigLines.join('\n');
2061
- if (coreConfigLines.length > 0) {
2062
- yamlContent += coreSection + coreConfigLines.join('\n');
2063
- }
2064
- }
2065
-
2066
- // Write the clean config file with POSIX-compliant final newline
2067
- const content = header + yamlContent;
2068
- await fs.writeFile(configPath, content.endsWith('\n') ? content : content + '\n', 'utf8');
2069
-
2070
- // Track the config file in installedFiles
2071
- this.installedFiles.add(configPath);
2072
- }
2073
- }
2074
- }
2075
-
2076
- /**
2077
- * Install core with resolved dependencies
2078
- * @param {string} bmadDir - BMAD installation directory
2079
- * @param {Object} coreFiles - Core files to install
2080
- */
2081
- async installCoreWithDependencies(bmadDir, coreFiles) {
2082
- const sourcePath = getModulePath('core');
2083
- const targetPath = path.join(bmadDir, 'core');
2084
- await this.installCore(bmadDir);
2085
- }
2086
-
2087
- /**
2088
- * Install module with resolved dependencies
2089
- * @param {string} moduleName - Module name
2090
- * @param {string} bmadDir - BMAD installation directory
2091
- * @param {Object} moduleFiles - Module files to install
2092
- */
2093
- async installModuleWithDependencies(moduleName, bmadDir, moduleFiles) {
2094
- // Get module configuration for conditional installation
2095
- const moduleConfig = this.configCollector.collectedConfig[moduleName] || {};
2096
-
2097
- // Use existing module manager for full installation with file tracking
2098
- // Note: Module-specific installers are called separately after IDE setup
2099
- await this.moduleManager.install(
2100
- moduleName,
2101
- bmadDir,
2102
- (filePath) => {
2103
- this.installedFiles.add(filePath);
2104
- },
2105
- {
2106
- skipModuleInstaller: true, // We'll run it later after IDE setup
2107
- moduleConfig: moduleConfig, // Pass module config for conditional filtering
2108
- installer: this,
2109
- silent: true,
2110
- },
2111
- );
2112
-
2113
- // Dependencies are already included in full module install
2114
- }
2115
-
2116
- /**
2117
- * Install partial module (only dependencies needed by other modules)
2118
- */
2119
- async installPartialModule(moduleName, bmadDir, files) {
2120
- const sourceBase = getModulePath(moduleName);
2121
- const targetBase = path.join(bmadDir, moduleName);
2122
-
2123
- // Create module directory
2124
- await fs.ensureDir(targetBase);
2125
-
2126
- // Copy only the required dependency files
2127
- if (files.agents && files.agents.length > 0) {
2128
- const agentsDir = path.join(targetBase, 'agents');
2129
- await fs.ensureDir(agentsDir);
2130
-
2131
- for (const agentPath of files.agents) {
2132
- const fileName = path.basename(agentPath);
2133
- const sourcePath = path.join(sourceBase, 'agents', fileName);
2134
- const targetPath = path.join(agentsDir, fileName);
2135
-
2136
- if (await fs.pathExists(sourcePath)) {
2137
- await this.copyFileWithPlaceholderReplacement(sourcePath, targetPath);
2138
- this.installedFiles.add(targetPath);
2139
- }
2140
- }
2141
- }
2142
-
2143
- if (files.tasks && files.tasks.length > 0) {
2144
- const tasksDir = path.join(targetBase, 'tasks');
2145
- await fs.ensureDir(tasksDir);
2146
-
2147
- for (const taskPath of files.tasks) {
2148
- const fileName = path.basename(taskPath);
2149
- const sourcePath = path.join(sourceBase, 'tasks', fileName);
2150
- const targetPath = path.join(tasksDir, fileName);
2151
-
2152
- if (await fs.pathExists(sourcePath)) {
2153
- await this.copyFileWithPlaceholderReplacement(sourcePath, targetPath);
2154
- this.installedFiles.add(targetPath);
2155
- }
2156
- }
2157
- }
2158
-
2159
- if (files.tools && files.tools.length > 0) {
2160
- const toolsDir = path.join(targetBase, 'tools');
2161
- await fs.ensureDir(toolsDir);
2162
-
2163
- for (const toolPath of files.tools) {
2164
- const fileName = path.basename(toolPath);
2165
- const sourcePath = path.join(sourceBase, 'tools', fileName);
2166
- const targetPath = path.join(toolsDir, fileName);
2167
-
2168
- if (await fs.pathExists(sourcePath)) {
2169
- await this.copyFileWithPlaceholderReplacement(sourcePath, targetPath);
2170
- this.installedFiles.add(targetPath);
2171
- }
2172
- }
2173
- }
2174
-
2175
- if (files.templates && files.templates.length > 0) {
2176
- const templatesDir = path.join(targetBase, 'templates');
2177
- await fs.ensureDir(templatesDir);
2178
-
2179
- for (const templatePath of files.templates) {
2180
- const fileName = path.basename(templatePath);
2181
- const sourcePath = path.join(sourceBase, 'templates', fileName);
2182
- const targetPath = path.join(templatesDir, fileName);
2183
-
2184
- if (await fs.pathExists(sourcePath)) {
2185
- await this.copyFileWithPlaceholderReplacement(sourcePath, targetPath);
2186
- this.installedFiles.add(targetPath);
2187
- }
2188
- }
2189
- }
2190
-
2191
- if (files.data && files.data.length > 0) {
2192
- for (const dataPath of files.data) {
2193
- // Preserve directory structure for data files
2194
- const relative = path.relative(sourceBase, dataPath);
2195
- const targetPath = path.join(targetBase, relative);
2196
-
2197
- await fs.ensureDir(path.dirname(targetPath));
2198
-
2199
- if (await fs.pathExists(dataPath)) {
2200
- await this.copyFileWithPlaceholderReplacement(dataPath, targetPath);
2201
- this.installedFiles.add(targetPath);
2202
- }
2203
- }
2204
- }
2205
-
2206
- // Create a marker file to indicate this is a partial installation
2207
- const markerPath = path.join(targetBase, '.partial');
2208
- await fs.writeFile(
2209
- markerPath,
2210
- `This module contains only dependencies required by other modules.\nInstalled: ${new Date().toISOString()}\n`,
2211
- );
2212
- }
2213
-
2214
- /**
2215
- * Private: Install core
2216
- * @param {string} bmadDir - BMAD installation directory
2217
- */
2218
- async installCore(bmadDir) {
2219
- const sourcePath = getModulePath('core');
2220
- const targetPath = path.join(bmadDir, 'core');
2221
-
2222
- // Copy core files
2223
- await this.copyCoreFiles(sourcePath, targetPath);
2224
- }
2225
-
2226
- /**
2227
- * Copy core files (similar to copyModuleWithFiltering but for core)
2228
- * @param {string} sourcePath - Source path
2229
- * @param {string} targetPath - Target path
2230
- */
2231
- async copyCoreFiles(sourcePath, targetPath) {
2232
- // Get all files in source
2233
- const files = await this.getFileList(sourcePath);
2234
-
2235
- for (const file of files) {
2236
- // Skip sub-modules directory - these are IDE-specific and handled separately
2237
- if (file.startsWith('sub-modules/')) {
2238
- continue;
2239
- }
2240
-
2241
- // Skip module.yaml at root - it's only needed at install time
2242
- if (file === 'module.yaml') {
2243
- continue;
2244
- }
2245
-
2246
- // Skip config.yaml templates - we'll generate clean ones with actual values
2247
- if (file === 'config.yaml' || file.endsWith('/config.yaml') || file === 'custom.yaml' || file.endsWith('/custom.yaml')) {
2248
- continue;
2249
- }
2250
-
2251
- const sourceFile = path.join(sourcePath, file);
2252
- const targetFile = path.join(targetPath, file);
2253
-
2254
- // Copy the file with placeholder replacement
2255
- await fs.ensureDir(path.dirname(targetFile));
2256
- await this.copyFileWithPlaceholderReplacement(sourceFile, targetFile);
2257
-
2258
- // Track the installed file
2259
- this.installedFiles.add(targetFile);
2260
- }
2261
- }
2262
-
2263
- /**
2264
- * Get list of all files in a directory recursively
2265
- * @param {string} dir - Directory path
2266
- * @param {string} baseDir - Base directory for relative paths
2267
- * @returns {Array} List of relative file paths
2268
- */
2269
- async getFileList(dir, baseDir = dir) {
2270
- const files = [];
2271
- const entries = await fs.readdir(dir, { withFileTypes: true });
2272
-
2273
- for (const entry of entries) {
2274
- const fullPath = path.join(dir, entry.name);
2275
-
2276
- if (entry.isDirectory()) {
2277
- const subFiles = await this.getFileList(fullPath, baseDir);
2278
- files.push(...subFiles);
2279
- } else {
2280
- files.push(path.relative(baseDir, fullPath));
2281
- }
2282
- }
2283
-
2284
- return files;
2285
- }
2286
-
2287
- /**
2288
- * Private: Update core
2289
- */
2290
- async updateCore(bmadDir, force = false) {
2291
- const sourcePath = getModulePath('core');
2292
- const targetPath = path.join(bmadDir, 'core');
2293
-
2294
- if (force) {
2295
- await fs.remove(targetPath);
2296
- await this.installCore(bmadDir);
2297
- } else {
2298
- // Selective update - preserve user modifications
2299
- await this.fileOps.syncDirectory(sourcePath, targetPath);
2300
- }
2301
- }
2302
-
2303
- /**
2304
- * Quick update method - preserves all settings and only prompts for new config fields
2305
- * @param {Object} config - Configuration with directory
2306
- * @returns {Object} Update result
2307
- */
2308
- async quickUpdate(config) {
2309
- const spinner = await prompts.spinner();
2310
- spinner.start('Starting quick update...');
2311
-
2312
- try {
2313
- const projectDir = path.resolve(config.directory);
2314
- const { bmadDir } = await this.findBmadDir(projectDir);
2315
-
2316
- // Check if bmad directory exists
2317
- if (!(await fs.pathExists(bmadDir))) {
2318
- spinner.stop('No BMAD installation found');
2319
- throw new Error(`BMAD not installed at ${bmadDir}. Use regular install for first-time setup.`);
2320
- }
2321
-
2322
- spinner.message('Detecting installed modules and configuration...');
2323
-
2324
- // Detect existing installation
2325
- const existingInstall = await this.detector.detect(bmadDir);
2326
- const installedModules = existingInstall.modules.map((m) => m.id);
2327
- const configuredIdes = existingInstall.ides || [];
2328
- const projectRoot = path.dirname(bmadDir);
2329
-
2330
- // Get custom module sources: first from --custom-content (re-cache from source), then from cache
2331
- const customModuleSources = new Map();
2332
- if (config.customContent?.sources?.length > 0) {
2333
- for (const source of config.customContent.sources) {
2334
- if (source.id && source.path && (await fs.pathExists(source.path))) {
2335
- customModuleSources.set(source.id, {
2336
- id: source.id,
2337
- name: source.name || source.id,
2338
- sourcePath: source.path,
2339
- cached: false, // From CLI, will be re-cached
2340
- });
2341
- }
2342
- }
2343
- }
2344
- const cacheDir = path.join(bmadDir, '_config', 'custom');
2345
- if (await fs.pathExists(cacheDir)) {
2346
- const cachedModules = await fs.readdir(cacheDir, { withFileTypes: true });
2347
-
2348
- for (const cachedModule of cachedModules) {
2349
- const moduleId = cachedModule.name;
2350
- const cachedPath = path.join(cacheDir, moduleId);
2351
-
2352
- // Skip if path doesn't exist (broken symlink, deleted dir) - avoids lstat ENOENT
2353
- if (!(await fs.pathExists(cachedPath))) {
2354
- continue;
2355
- }
2356
- if (!cachedModule.isDirectory()) {
2357
- continue;
2358
- }
2359
-
2360
- // Skip if we already have this module from manifest
2361
- if (customModuleSources.has(moduleId)) {
2362
- continue;
2363
- }
2364
-
2365
- // Check if this is an external official module - skip cache for those
2366
- const isExternal = await this.moduleManager.isExternalModule(moduleId);
2367
- if (isExternal) {
2368
- // External modules are handled via cloneExternalModule, not from cache
2369
- continue;
2370
- }
2371
-
2372
- // Check if this is actually a custom module (has module.yaml)
2373
- const moduleYamlPath = path.join(cachedPath, 'module.yaml');
2374
- if (await fs.pathExists(moduleYamlPath)) {
2375
- // For quick update, we always rebuild from cache
2376
- customModuleSources.set(moduleId, {
2377
- id: moduleId,
2378
- name: moduleId, // We'll read the actual name if needed
2379
- sourcePath: cachedPath,
2380
- cached: true, // Flag to indicate this is from cache
2381
- });
2382
- }
2383
- }
2384
- }
2385
-
2386
- // Load saved IDE configurations
2387
- const savedIdeConfigs = await this.ideConfigManager.loadAllIdeConfigs(bmadDir);
2388
-
2389
- // Get available modules (what we have source for)
2390
- const availableModulesData = await this.moduleManager.listAvailable();
2391
- const availableModules = [...availableModulesData.modules, ...availableModulesData.customModules];
2392
-
2393
- // Add external official modules to available modules
2394
- // These can always be obtained by cloning from their remote URLs
2395
- const { ExternalModuleManager } = require('../modules/external-manager');
2396
- const externalManager = new ExternalModuleManager();
2397
- const externalModules = await externalManager.listAvailable();
2398
- for (const externalModule of externalModules) {
2399
- // Only add if not already in the list and is installed
2400
- if (installedModules.includes(externalModule.code) && !availableModules.some((m) => m.id === externalModule.code)) {
2401
- availableModules.push({
2402
- id: externalModule.code,
2403
- name: externalModule.name,
2404
- isExternal: true,
2405
- fromExternal: true,
2406
- });
2407
- }
2408
- }
2409
-
2410
- // Add custom modules from manifest if their sources exist
2411
- for (const [moduleId, customModule] of customModuleSources) {
2412
- // Use the absolute sourcePath
2413
- const sourcePath = customModule.sourcePath;
2414
-
2415
- // Check if source exists at the recorded path
2416
- if (
2417
- sourcePath &&
2418
- (await fs.pathExists(sourcePath)) && // Add to available modules if not already there
2419
- !availableModules.some((m) => m.id === moduleId)
2420
- ) {
2421
- availableModules.push({
2422
- id: moduleId,
2423
- name: customModule.name || moduleId,
2424
- path: sourcePath,
2425
- isCustom: true,
2426
- fromManifest: true,
2427
- });
2428
- }
2429
- }
2430
-
2431
- // Handle missing custom module sources using shared method
2432
- const customModuleResult = await this.handleMissingCustomSources(
2433
- customModuleSources,
2434
- bmadDir,
2435
- projectRoot,
2436
- 'update',
2437
- installedModules,
2438
- config.skipPrompts || false,
2439
- );
2440
-
2441
- const { validCustomModules, keptModulesWithoutSources } = customModuleResult;
2442
-
2443
- const customModulesFromManifest = validCustomModules.map((m) => ({
2444
- ...m,
2445
- isCustom: true,
2446
- hasUpdate: true,
2447
- }));
2448
-
2449
- const allAvailableModules = [...availableModules, ...customModulesFromManifest];
2450
- const availableModuleIds = new Set(allAvailableModules.map((m) => m.id));
2451
-
2452
- // Core module is special - never include it in update flow
2453
- const nonCoreInstalledModules = installedModules.filter((id) => id !== 'core');
2454
-
2455
- // Only update modules that are BOTH installed AND available (we have source for)
2456
- const modulesToUpdate = nonCoreInstalledModules.filter((id) => availableModuleIds.has(id));
2457
- const skippedModules = nonCoreInstalledModules.filter((id) => !availableModuleIds.has(id));
2458
-
2459
- // Add custom modules that were kept without sources to the skipped modules
2460
- // This ensures their agents are preserved in the manifest
2461
- for (const keptModule of keptModulesWithoutSources) {
2462
- if (!skippedModules.includes(keptModule)) {
2463
- skippedModules.push(keptModule);
2464
- }
2465
- }
2466
-
2467
- spinner.stop(`Found ${modulesToUpdate.length} module(s) to update and ${configuredIdes.length} configured tool(s)`);
2468
-
2469
- if (skippedModules.length > 0) {
2470
- await prompts.log.warn(`Skipping ${skippedModules.length} module(s) - no source available: ${skippedModules.join(', ')}`);
2471
- }
2472
-
2473
- // Load existing configs and collect new fields (if any)
2474
- await prompts.log.info('Checking for new configuration options...');
2475
- await this.configCollector.loadExistingConfig(projectDir);
2476
-
2477
- let promptedForNewFields = false;
2478
-
2479
- // Check core config for new fields
2480
- const corePrompted = await this.configCollector.collectModuleConfigQuick('core', projectDir, true);
2481
- if (corePrompted) {
2482
- promptedForNewFields = true;
2483
- }
2484
-
2485
- // Check each module we're updating for new fields (NOT skipped modules)
2486
- for (const moduleName of modulesToUpdate) {
2487
- const modulePrompted = await this.configCollector.collectModuleConfigQuick(moduleName, projectDir, true);
2488
- if (modulePrompted) {
2489
- promptedForNewFields = true;
2490
- }
2491
- }
2492
-
2493
- if (!promptedForNewFields) {
2494
- await prompts.log.success('All configuration is up to date, no new options to configure');
2495
- }
2496
-
2497
- // Add metadata
2498
- this.configCollector.collectedConfig._meta = {
2499
- version: require(path.join(getProjectRoot(), 'package.json')).version,
2500
- installDate: new Date().toISOString(),
2501
- lastModified: new Date().toISOString(),
2502
- };
2503
-
2504
- // Build the config object for the installer
2505
- const installConfig = {
2506
- directory: projectDir,
2507
- installCore: true,
2508
- modules: modulesToUpdate, // Only update modules we have source for
2509
- ides: configuredIdes,
2510
- skipIde: configuredIdes.length === 0,
2511
- coreConfig: this.configCollector.collectedConfig.core,
2512
- actionType: 'install', // Use regular install flow
2513
- _quickUpdate: true, // Flag to skip certain prompts
2514
- _preserveModules: skippedModules, // Preserve these in manifest even though we didn't update them
2515
- _savedIdeConfigs: savedIdeConfigs, // Pass saved IDE configs to installer
2516
- _customModuleSources: customModuleSources, // Pass custom module sources for updates
2517
- _existingModules: installedModules, // Pass all installed modules for manifest generation
2518
- customContent: config.customContent, // Pass through for re-caching from source
2519
- };
2520
-
2521
- // Call the standard install method
2522
- const result = await this.install(installConfig);
2523
-
2524
- // Only succeed the spinner if it's still spinning
2525
- // (install method might have stopped it if folder name changed)
2526
- if (spinner.isSpinning) {
2527
- spinner.stop('Quick update complete!');
2528
- }
2529
-
2530
- return {
2531
- success: true,
2532
- moduleCount: modulesToUpdate.length + 1, // +1 for core
2533
- hadNewFields: promptedForNewFields,
2534
- modules: ['core', ...modulesToUpdate],
2535
- skippedModules: skippedModules,
2536
- ides: configuredIdes,
2537
- };
2538
- } catch (error) {
2539
- spinner.error('Quick update failed');
2540
- throw error;
2541
- }
2542
- }
2543
-
2544
- /**
2545
- * Private: Prompt for update action
2546
- */
2547
- async promptUpdateAction() {
2548
- const action = await prompts.select({
2549
- message: 'What would you like to do?',
2550
- choices: [{ name: 'Update existing installation', value: 'update' }],
2551
- });
2552
- return { action };
2553
- }
2554
-
2555
- /**
2556
- * Handle legacy BMAD v4 detection with simple warning
2557
- * @param {string} _projectDir - Project directory (unused in simplified version)
2558
- * @param {Object} _legacyV4 - Legacy V4 detection result (unused in simplified version)
2559
- */
2560
- async handleLegacyV4Migration(_projectDir, _legacyV4) {
2561
- await prompts.note(
2562
- 'Found .bmad-method folder from BMAD v4 installation.\n\n' +
2563
- 'Before continuing with installation, we recommend:\n' +
2564
- ' 1. Remove the .bmad-method folder, OR\n' +
2565
- ' 2. Back it up by renaming it to another name (e.g., bmad-method-backup)\n\n' +
2566
- 'If your v4 installation set up rules or commands, you should remove those as well.',
2567
- 'Legacy BMAD v4 detected',
2568
- );
2569
-
2570
- const proceed = await prompts.select({
2571
- message: 'What would you like to do?',
2572
- choices: [
2573
- {
2574
- name: 'Exit and clean up manually (recommended)',
2575
- value: 'exit',
2576
- hint: 'Exit installation',
2577
- },
2578
- {
2579
- name: 'Continue with installation anyway',
2580
- value: 'continue',
2581
- hint: 'Continue',
2582
- },
2583
- ],
2584
- default: 'exit',
2585
- });
2586
-
2587
- if (proceed === 'exit') {
2588
- await prompts.log.info('Please remove the .bmad-method folder and any v4 rules/commands, then run the installer again.');
2589
- // Allow event loop to flush pending I/O before exit
2590
- setImmediate(() => process.exit(0));
2591
- return;
2592
- }
2593
-
2594
- await prompts.log.warn('Proceeding with installation despite legacy v4 folder');
2595
- }
2596
-
2597
- /**
2598
- * Read files-manifest.csv
2599
- * @param {string} bmadDir - BMAD installation directory
2600
- * @returns {Array} Array of file entries from files-manifest.csv
2601
- */
2602
- async readFilesManifest(bmadDir) {
2603
- const filesManifestPath = path.join(bmadDir, '_config', 'files-manifest.csv');
2604
- if (!(await fs.pathExists(filesManifestPath))) {
2605
- return [];
2606
- }
2607
-
2608
- try {
2609
- const content = await fs.readFile(filesManifestPath, 'utf8');
2610
- const lines = content.split('\n');
2611
- const files = [];
2612
-
2613
- for (let i = 1; i < lines.length; i++) {
2614
- // Skip header
2615
- const line = lines[i].trim();
2616
- if (!line) continue;
2617
-
2618
- // Parse CSV line properly handling quoted values
2619
- const parts = [];
2620
- let current = '';
2621
- let inQuotes = false;
2622
-
2623
- for (const char of line) {
2624
- if (char === '"') {
2625
- inQuotes = !inQuotes;
2626
- } else if (char === ',' && !inQuotes) {
2627
- parts.push(current);
2628
- current = '';
2629
- } else {
2630
- current += char;
2631
- }
2632
- }
2633
- parts.push(current); // Add last part
2634
-
2635
- if (parts.length >= 4) {
2636
- files.push({
2637
- type: parts[0],
2638
- name: parts[1],
2639
- module: parts[2],
2640
- path: parts[3],
2641
- hash: parts[4] || null, // Hash may not exist in old manifests
2642
- });
2643
- }
2644
- }
2645
-
2646
- return files;
2647
- } catch (error) {
2648
- await prompts.log.warn('Could not read files-manifest.csv: ' + error.message);
2649
- return [];
2650
- }
2651
- }
2652
-
2653
- /**
2654
- * Detect custom and modified files
2655
- * @param {string} bmadDir - BMAD installation directory
2656
- * @param {Array} existingFilesManifest - Previous files from files-manifest.csv
2657
- * @returns {Object} Object with customFiles and modifiedFiles arrays
2658
- */
2659
- async detectCustomFiles(bmadDir, existingFilesManifest) {
2660
- const customFiles = [];
2661
- const modifiedFiles = [];
2662
-
2663
- // Memory is always in _bmad/_memory
2664
- const bmadMemoryPath = '_memory';
2665
-
2666
- // Check if the manifest has hashes - if not, we can't detect modifications
2667
- let manifestHasHashes = false;
2668
- if (existingFilesManifest && existingFilesManifest.length > 0) {
2669
- manifestHasHashes = existingFilesManifest.some((f) => f.hash);
2670
- }
2671
-
2672
- // Build map of previously installed files from files-manifest.csv with their hashes
2673
- const installedFilesMap = new Map();
2674
- for (const fileEntry of existingFilesManifest) {
2675
- if (fileEntry.path) {
2676
- const absolutePath = path.join(bmadDir, fileEntry.path);
2677
- installedFilesMap.set(path.normalize(absolutePath), {
2678
- hash: fileEntry.hash,
2679
- relativePath: fileEntry.path,
2680
- });
2681
- }
2682
- }
2683
-
2684
- // Recursively scan bmadDir for all files
2685
- const scanDirectory = async (dir) => {
2686
- try {
2687
- const entries = await fs.readdir(dir, { withFileTypes: true });
2688
- for (const entry of entries) {
2689
- const fullPath = path.join(dir, entry.name);
2690
-
2691
- if (entry.isDirectory()) {
2692
- // Skip certain directories
2693
- if (entry.name === 'node_modules' || entry.name === '.git') {
2694
- continue;
2695
- }
2696
- await scanDirectory(fullPath);
2697
- } else if (entry.isFile()) {
2698
- const normalizedPath = path.normalize(fullPath);
2699
- const fileInfo = installedFilesMap.get(normalizedPath);
2700
-
2701
- // Skip certain system files that are auto-generated
2702
- const relativePath = path.relative(bmadDir, fullPath);
2703
- const fileName = path.basename(fullPath);
2704
-
2705
- // Skip _config directory EXCEPT for modified agent customizations
2706
- if (relativePath.startsWith('_config/') || relativePath.startsWith('_config\\')) {
2707
- // Special handling for .customize.yaml files - only preserve if modified
2708
- if (relativePath.includes('/agents/') && fileName.endsWith('.customize.yaml')) {
2709
- // Check if the customization file has been modified from manifest
2710
- const manifestPath = path.join(bmadDir, '_config', 'manifest.yaml');
2711
- if (await fs.pathExists(manifestPath)) {
2712
- const crypto = require('node:crypto');
2713
- const currentContent = await fs.readFile(fullPath, 'utf8');
2714
- const currentHash = crypto.createHash('sha256').update(currentContent).digest('hex');
2715
-
2716
- const yaml = require('yaml');
2717
- const manifestContent = await fs.readFile(manifestPath, 'utf8');
2718
- const manifestData = yaml.parse(manifestContent);
2719
- const originalHash = manifestData.agentCustomizations?.[relativePath];
2720
-
2721
- // Only add to customFiles if hash differs (user modified)
2722
- if (originalHash && currentHash !== originalHash) {
2723
- customFiles.push(fullPath);
2724
- }
2725
- }
2726
- }
2727
- continue;
2728
- }
2729
-
2730
- if (relativePath.startsWith(bmadMemoryPath + '/') && path.dirname(relativePath).includes('-sidecar')) {
2731
- continue;
2732
- }
2733
-
2734
- // Skip config.yaml files - these are regenerated on each install/update
2735
- if (fileName === 'config.yaml') {
2736
- continue;
2737
- }
2738
-
2739
- if (!fileInfo) {
2740
- // File not in manifest = custom file
2741
- // EXCEPT: Agent .md files in module folders are generated files, not custom
2742
- // Only treat .md files under _config/agents/ as custom
2743
- if (!(fileName.endsWith('.md') && relativePath.includes('/agents/') && !relativePath.startsWith('_config/'))) {
2744
- customFiles.push(fullPath);
2745
- }
2746
- } else if (manifestHasHashes && fileInfo.hash) {
2747
- // File in manifest with hash - check if it was modified
2748
- const currentHash = await this.manifest.calculateFileHash(fullPath);
2749
- if (currentHash && currentHash !== fileInfo.hash) {
2750
- // Hash changed = file was modified
2751
- modifiedFiles.push({
2752
- path: fullPath,
2753
- relativePath: fileInfo.relativePath,
2754
- });
2755
- }
2756
- }
2757
- }
2758
- }
2759
- } catch {
2760
- // Ignore errors scanning directories
2761
- }
2762
- };
2763
-
2764
- await scanDirectory(bmadDir);
2765
- return { customFiles, modifiedFiles };
2766
- }
2767
-
2768
- /**
2769
- * Handle missing custom module sources interactively
2770
- * @param {Map} customModuleSources - Map of custom module ID to info
2771
- * @param {string} bmadDir - BMAD directory
2772
- * @param {string} projectRoot - Project root directory
2773
- * @param {string} operation - Current operation ('update', 'compile', etc.)
2774
- * @param {Array} installedModules - Array of installed module IDs (will be modified)
2775
- * @param {boolean} [skipPrompts=false] - Skip interactive prompts and keep all modules with missing sources
2776
- * @returns {Object} Object with validCustomModules array and keptModulesWithoutSources array
2777
- */
2778
- async handleMissingCustomSources(customModuleSources, bmadDir, projectRoot, operation, installedModules, skipPrompts = false) {
2779
- const validCustomModules = [];
2780
- const keptModulesWithoutSources = []; // Track modules kept without sources
2781
- const customModulesWithMissingSources = [];
2782
-
2783
- // Check which sources exist
2784
- for (const [moduleId, customInfo] of customModuleSources) {
2785
- if (await fs.pathExists(customInfo.sourcePath)) {
2786
- validCustomModules.push({
2787
- id: moduleId,
2788
- name: customInfo.name,
2789
- path: customInfo.sourcePath,
2790
- info: customInfo,
2791
- });
2792
- } else {
2793
- // For cached modules that are missing, we just skip them without prompting
2794
- if (customInfo.cached) {
2795
- // Skip cached modules without prompting
2796
- keptModulesWithoutSources.push({
2797
- id: moduleId,
2798
- name: customInfo.name,
2799
- cached: true,
2800
- });
2801
- } else {
2802
- customModulesWithMissingSources.push({
2803
- id: moduleId,
2804
- name: customInfo.name,
2805
- sourcePath: customInfo.sourcePath,
2806
- relativePath: customInfo.relativePath,
2807
- info: customInfo,
2808
- });
2809
- }
2810
- }
2811
- }
2812
-
2813
- // If no missing sources, return immediately
2814
- if (customModulesWithMissingSources.length === 0) {
2815
- return {
2816
- validCustomModules,
2817
- keptModulesWithoutSources: [],
2818
- };
2819
- }
2820
-
2821
- // Non-interactive mode: keep all modules with missing sources
2822
- if (skipPrompts) {
2823
- for (const missing of customModulesWithMissingSources) {
2824
- keptModulesWithoutSources.push(missing.id);
2825
- }
2826
- return { validCustomModules, keptModulesWithoutSources };
2827
- }
2828
-
2829
- await prompts.log.warn(`Found ${customModulesWithMissingSources.length} custom module(s) with missing sources:`);
2830
-
2831
- let keptCount = 0;
2832
- let updatedCount = 0;
2833
- let removedCount = 0;
2834
-
2835
- for (const missing of customModulesWithMissingSources) {
2836
- await prompts.log.message(
2837
- `${missing.name} (${missing.id})\n Original source: ${missing.relativePath}\n Full path: ${missing.sourcePath}`,
2838
- );
2839
-
2840
- const choices = [
2841
- {
2842
- name: 'Keep installed (will not be processed)',
2843
- value: 'keep',
2844
- hint: 'Keep',
2845
- },
2846
- {
2847
- name: 'Specify new source location',
2848
- value: 'update',
2849
- hint: 'Update',
2850
- },
2851
- ];
2852
-
2853
- // Only add remove option if not just compiling agents
2854
- if (operation !== 'compile-agents') {
2855
- choices.push({
2856
- name: '⚠️ REMOVE module completely (destructive!)',
2857
- value: 'remove',
2858
- hint: 'Remove',
2859
- });
2860
- }
2861
-
2862
- const action = await prompts.select({
2863
- message: `How would you like to handle "${missing.name}"?`,
2864
- choices,
2865
- });
2866
-
2867
- switch (action) {
2868
- case 'update': {
2869
- // Use sync validation because @clack/prompts doesn't support async validate
2870
- const newSourcePath = await prompts.text({
2871
- message: 'Enter the new path to the custom module:',
2872
- default: missing.sourcePath,
2873
- validate: (input) => {
2874
- if (!input || input.trim() === '') {
2875
- return 'Please enter a path';
2876
- }
2877
- const expandedPath = path.resolve(input.trim());
2878
- if (!fs.pathExistsSync(expandedPath)) {
2879
- return 'Path does not exist';
2880
- }
2881
- // Check if it looks like a valid module
2882
- const moduleYamlPath = path.join(expandedPath, 'module.yaml');
2883
- const agentsPath = path.join(expandedPath, 'agents');
2884
- const workflowsPath = path.join(expandedPath, 'workflows');
2885
-
2886
- if (!fs.pathExistsSync(moduleYamlPath) && !fs.pathExistsSync(agentsPath) && !fs.pathExistsSync(workflowsPath)) {
2887
- return 'Path does not appear to contain a valid custom module';
2888
- }
2889
- return; // clack expects undefined for valid input
2890
- },
2891
- });
2892
-
2893
- // Defensive: handleCancel should have exited, but guard against symbol propagation
2894
- if (typeof newSourcePath !== 'string') {
2895
- keptCount++;
2896
- keptModulesWithoutSources.push(missing.id);
2897
- continue;
2898
- }
2899
-
2900
- // Update the source in manifest
2901
- const resolvedPath = path.resolve(newSourcePath.trim());
2902
- missing.info.sourcePath = resolvedPath;
2903
- // Remove relativePath - we only store absolute sourcePath now
2904
- delete missing.info.relativePath;
2905
- await this.manifest.addCustomModule(bmadDir, missing.info);
2906
-
2907
- validCustomModules.push({
2908
- id: missing.id,
2909
- name: missing.name,
2910
- path: resolvedPath,
2911
- info: missing.info,
2912
- });
2913
-
2914
- updatedCount++;
2915
- await prompts.log.success('Updated source location');
2916
-
2917
- break;
2918
- }
2919
- case 'remove': {
2920
- // Extra confirmation for destructive remove
2921
- await prompts.log.error(
2922
- `WARNING: This will PERMANENTLY DELETE "${missing.name}" and all its files!\n Module location: ${path.join(bmadDir, missing.id)}`,
2923
- );
2924
-
2925
- const confirmDelete = await prompts.confirm({
2926
- message: 'Are you absolutely sure you want to delete this module?',
2927
- default: false,
2928
- });
2929
-
2930
- if (confirmDelete) {
2931
- const typedConfirm = await prompts.text({
2932
- message: 'Type "DELETE" to confirm permanent deletion:',
2933
- validate: (input) => {
2934
- if (input !== 'DELETE') {
2935
- return 'You must type "DELETE" exactly to proceed';
2936
- }
2937
- return; // clack expects undefined for valid input
2938
- },
2939
- });
2940
-
2941
- if (typedConfirm === 'DELETE') {
2942
- // Remove the module from filesystem and manifest
2943
- const modulePath = path.join(bmadDir, missing.id);
2944
- if (await fs.pathExists(modulePath)) {
2945
- const fsExtra = require('fs-extra');
2946
- await fsExtra.remove(modulePath);
2947
- await prompts.log.warn(`Deleted module directory: ${path.relative(projectRoot, modulePath)}`);
2948
- }
2949
-
2950
- await this.manifest.removeModule(bmadDir, missing.id);
2951
- await this.manifest.removeCustomModule(bmadDir, missing.id);
2952
- await prompts.log.warn('Removed from manifest');
2953
-
2954
- // Also remove from installedModules list
2955
- if (installedModules && installedModules.includes(missing.id)) {
2956
- const index = installedModules.indexOf(missing.id);
2957
- if (index !== -1) {
2958
- installedModules.splice(index, 1);
2959
- }
2960
- }
2961
-
2962
- removedCount++;
2963
- await prompts.log.error(`"${missing.name}" has been permanently removed`);
2964
- } else {
2965
- await prompts.log.message('Removal cancelled - module will be kept');
2966
- keptCount++;
2967
- }
2968
- } else {
2969
- await prompts.log.message('Removal cancelled - module will be kept');
2970
- keptCount++;
2971
- }
2972
-
2973
- break;
2974
- }
2975
- case 'keep': {
2976
- keptCount++;
2977
- keptModulesWithoutSources.push(missing.id);
2978
- await prompts.log.message('Module will be kept as-is');
2979
-
2980
- break;
2981
- }
2982
- // No default
2983
- }
2984
- }
2985
-
2986
- // Show summary
2987
- if (keptCount > 0 || updatedCount > 0 || removedCount > 0) {
2988
- let summary = 'Summary for custom modules with missing sources:';
2989
- if (keptCount > 0) summary += `\n • ${keptCount} module(s) kept as-is`;
2990
- if (updatedCount > 0) summary += `\n • ${updatedCount} module(s) updated with new sources`;
2991
- if (removedCount > 0) summary += `\n • ${removedCount} module(s) permanently deleted`;
2992
- await prompts.log.message(summary);
2993
- }
2994
-
2995
- return {
2996
- validCustomModules,
2997
- keptModulesWithoutSources,
2998
- };
2999
- }
3000
- }
3001
-
3002
- module.exports = { Installer };