@zeyue0329/xiaoma-cli 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/.releaserc.json +18 -0
  2. package/.vscode/settings.json +44 -0
  3. package/CONTRIBUTING.md +209 -0
  4. package/LICENSE +21 -0
  5. package/QUICK-START.md +173 -0
  6. package/README.md +532 -0
  7. package/common/tasks/create-doc.md +101 -0
  8. package/common/tasks/execute-checklist.md +93 -0
  9. package/common/utils/bmad-doc-template.md +325 -0
  10. package/common/utils/workflow-management.md +69 -0
  11. package/dist/agents/analyst.txt +2882 -0
  12. package/dist/agents/architect.txt +3543 -0
  13. package/dist/agents/dev.txt +428 -0
  14. package/dist/agents/pm.txt +2229 -0
  15. package/dist/agents/po.txt +1364 -0
  16. package/dist/agents/qa.txt +386 -0
  17. package/dist/agents/sm.txt +668 -0
  18. package/dist/agents/ux-expert.txt +701 -0
  19. package/dist/agents/xiaoma-master.txt +8756 -0
  20. package/dist/agents/xiaoma-orchestrator.txt +1490 -0
  21. package/dist/teams/team-all.txt +11062 -0
  22. package/dist/teams/team-fullstack.txt +10392 -0
  23. package/dist/teams/team-ide-minimal.txt +3507 -0
  24. package/dist/teams/team-no-ui.txt +8951 -0
  25. package/docs/GUIDING-PRINCIPLES.md +91 -0
  26. package/docs/core-architecture.md +219 -0
  27. package/docs/expansion-packs.md +280 -0
  28. package/docs/versioning-and-releases.md +77 -0
  29. package/docs/versions.md +48 -0
  30. package/expansion-packs/README.md +3 -0
  31. package/package.json +80 -0
  32. package/tools/bmad-npx-wrapper.js +39 -0
  33. package/tools/builders/web-builder.js +681 -0
  34. package/tools/bump-all-versions.js +106 -0
  35. package/tools/bump-expansion-version.js +83 -0
  36. package/tools/cli.js +152 -0
  37. package/tools/flattener/main.js +570 -0
  38. package/tools/installer/README.md +8 -0
  39. package/tools/installer/bin/xiaoma.js +326 -0
  40. package/tools/installer/config/ide-agent-config.yaml +58 -0
  41. package/tools/installer/config/install.config.yaml +113 -0
  42. package/tools/installer/lib/config-loader.js +253 -0
  43. package/tools/installer/lib/file-manager.js +411 -0
  44. package/tools/installer/lib/ide-base-setup.js +227 -0
  45. package/tools/installer/lib/ide-setup.js +1302 -0
  46. package/tools/installer/lib/installer.js +1772 -0
  47. package/tools/installer/lib/memory-profiler.js +224 -0
  48. package/tools/installer/lib/module-manager.js +110 -0
  49. package/tools/installer/lib/resource-locator.js +310 -0
  50. package/tools/installer/package-lock.json +906 -0
  51. package/tools/installer/package.json +43 -0
  52. package/tools/lib/dependency-resolver.js +179 -0
  53. package/tools/lib/yaml-utils.js +29 -0
  54. package/tools/md-assets/web-agent-startup-instructions.md +39 -0
  55. package/tools/semantic-release-sync-installer.js +30 -0
  56. package/tools/sync-installer-version.js +34 -0
  57. package/tools/update-expansion-version.js +54 -0
  58. package/tools/upgraders/v3-to-v4-upgrader.js +763 -0
  59. package/tools/version-bump.js +79 -0
  60. package/tools/xiaoma-npx-wrapper.js +39 -0
  61. package/tools/yaml-format.js +240 -0
  62. package/xiaoma-core/agent-teams/team-all.yaml +14 -0
  63. package/xiaoma-core/agent-teams/team-fullstack.yaml +18 -0
  64. package/xiaoma-core/agent-teams/team-ide-minimal.yaml +10 -0
  65. package/xiaoma-core/agent-teams/team-no-ui.yaml +13 -0
  66. package/xiaoma-core/agents/analyst.md +81 -0
  67. package/xiaoma-core/agents/architect.md +84 -0
  68. package/xiaoma-core/agents/dev.md +76 -0
  69. package/xiaoma-core/agents/pm.md +81 -0
  70. package/xiaoma-core/agents/po.md +76 -0
  71. package/xiaoma-core/agents/qa.md +69 -0
  72. package/xiaoma-core/agents/sm.md +62 -0
  73. package/xiaoma-core/agents/ux-expert.md +66 -0
  74. package/xiaoma-core/agents/xiaoma-master.md +108 -0
  75. package/xiaoma-core/agents/xiaoma-orchestrator.md +150 -0
  76. package/xiaoma-core/bmad-core/user-guide.md +0 -0
  77. package/xiaoma-core/checklists/architect-checklist.md +443 -0
  78. package/xiaoma-core/checklists/change-checklist.md +182 -0
  79. package/xiaoma-core/checklists/pm-checklist.md +375 -0
  80. package/xiaoma-core/checklists/po-master-checklist.md +441 -0
  81. package/xiaoma-core/checklists/story-dod-checklist.md +101 -0
  82. package/xiaoma-core/checklists/story-draft-checklist.md +156 -0
  83. package/xiaoma-core/core-config.yaml +20 -0
  84. package/xiaoma-core/data/brainstorming-techniques.md +36 -0
  85. package/xiaoma-core/data/elicitation-methods.md +134 -0
  86. package/xiaoma-core/data/technical-preferences.md +3 -0
  87. package/xiaoma-core/data/xiaoma-kb.md +803 -0
  88. package/xiaoma-core/enhanced-ide-development-workflow.md +43 -0
  89. package/xiaoma-core/tasks/advanced-elicitation.md +117 -0
  90. package/xiaoma-core/tasks/brownfield-create-epic.md +160 -0
  91. package/xiaoma-core/tasks/brownfield-create-story.md +147 -0
  92. package/xiaoma-core/tasks/correct-course.md +70 -0
  93. package/xiaoma-core/tasks/create-brownfield-story.md +304 -0
  94. package/xiaoma-core/tasks/create-deep-research-prompt.md +289 -0
  95. package/xiaoma-core/tasks/create-next-story.md +112 -0
  96. package/xiaoma-core/tasks/document-project.md +341 -0
  97. package/xiaoma-core/tasks/facilitate-brainstorming-session.md +136 -0
  98. package/xiaoma-core/tasks/generate-ai-frontend-prompt.md +51 -0
  99. package/xiaoma-core/tasks/index-docs.md +179 -0
  100. package/xiaoma-core/tasks/kb-mode-interaction.md +75 -0
  101. package/xiaoma-core/tasks/review-story.md +145 -0
  102. package/xiaoma-core/tasks/shard-doc.md +187 -0
  103. package/xiaoma-core/tasks/validate-next-story.md +134 -0
  104. package/xiaoma-core/templates/architecture-tmpl.yaml +650 -0
  105. package/xiaoma-core/templates/brainstorming-output-tmpl.yaml +156 -0
  106. package/xiaoma-core/templates/brownfield-architecture-tmpl.yaml +476 -0
  107. package/xiaoma-core/templates/brownfield-prd-tmpl.yaml +280 -0
  108. package/xiaoma-core/templates/competitor-analysis-tmpl.yaml +293 -0
  109. package/xiaoma-core/templates/front-end-architecture-tmpl.yaml +206 -0
  110. package/xiaoma-core/templates/front-end-spec-tmpl.yaml +349 -0
  111. package/xiaoma-core/templates/fullstack-architecture-tmpl.yaml +805 -0
  112. package/xiaoma-core/templates/market-research-tmpl.yaml +252 -0
  113. package/xiaoma-core/templates/prd-tmpl.yaml +202 -0
  114. package/xiaoma-core/templates/project-brief-tmpl.yaml +221 -0
  115. package/xiaoma-core/templates/story-tmpl.yaml +137 -0
  116. package/xiaoma-core/user-guide.md +251 -0
  117. package/xiaoma-core/workflows/brownfield-fullstack.yaml +297 -0
  118. package/xiaoma-core/workflows/brownfield-service.yaml +187 -0
  119. package/xiaoma-core/workflows/brownfield-ui.yaml +197 -0
  120. package/xiaoma-core/workflows/greenfield-fullstack.yaml +240 -0
  121. package/xiaoma-core/workflows/greenfield-service.yaml +206 -0
  122. package/xiaoma-core/workflows/greenfield-ui.yaml +235 -0
  123. package/xiaoma-core/working-in-the-brownfield.md +364 -0
@@ -0,0 +1,1772 @@
1
+ const path = require("node:path");
2
+ const fs = require("fs-extra");
3
+ const chalk = require("chalk");
4
+ const ora = require("ora");
5
+ const inquirer = require("inquirer");
6
+ const fileManager = require("./file-manager");
7
+ const configLoader = require("./config-loader");
8
+ const ideSetup = require("./ide-setup");
9
+ const { extractYamlFromAgent } = require("../../lib/yaml-utils");
10
+ const resourceLocator = require("./resource-locator");
11
+
12
+ class Installer {
13
+ async getCoreVersion() {
14
+ try {
15
+ // Always use package.json version
16
+ const packagePath = path.join(__dirname, '..', '..', '..', 'package.json');
17
+ const packageJson = require(packagePath);
18
+ return packageJson.version;
19
+ } catch (error) {
20
+ console.warn("Could not read version from package.json, using 'unknown'");
21
+ return "unknown";
22
+ }
23
+ }
24
+
25
+ async install(config) {
26
+ const spinner = ora("Analyzing installation directory...").start();
27
+
28
+ try {
29
+ // Store the original CWD where npx was executed
30
+ const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();
31
+
32
+ // Resolve installation directory relative to where the user ran the command
33
+ let installDir = path.isAbsolute(config.directory)
34
+ ? config.directory
35
+ : path.resolve(originalCwd, config.directory);
36
+
37
+ if (path.basename(installDir) === '.xiaoma-core') {
38
+ // If user points directly to .xiaoma-core, treat its parent as the project root
39
+ installDir = path.dirname(installDir);
40
+ }
41
+
42
+ // Log resolved path for clarity
43
+ if (!path.isAbsolute(config.directory)) {
44
+ spinner.text = `Resolving "${config.directory}" to: ${installDir}`;
45
+ }
46
+
47
+ // Check if directory exists and handle non-existent directories
48
+ if (!(await fileManager.pathExists(installDir))) {
49
+ spinner.stop();
50
+ console.log(`\nThe directory ${installDir} does not exist.`);
51
+
52
+ const { action } = await inquirer.prompt([
53
+ {
54
+ type: 'list',
55
+ name: 'action',
56
+ message: 'What would you like to do?',
57
+ choices: [
58
+ {
59
+ name: 'Create the directory and continue',
60
+ value: 'create'
61
+ },
62
+ {
63
+ name: 'Choose a different directory',
64
+ value: 'change'
65
+ },
66
+ {
67
+ name: 'Cancel installation',
68
+ value: 'cancel'
69
+ }
70
+ ]
71
+ }
72
+ ]);
73
+
74
+ if (action === 'cancel') {
75
+ console.log('Installation cancelled.');
76
+ process.exit(0);
77
+ } else if (action === 'change') {
78
+ const { newDirectory } = await inquirer.prompt([
79
+ {
80
+ type: 'input',
81
+ name: 'newDirectory',
82
+ message: 'Enter the new directory path:',
83
+ validate: (input) => {
84
+ if (!input.trim()) {
85
+ return 'Please enter a valid directory path';
86
+ }
87
+ return true;
88
+ }
89
+ }
90
+ ]);
91
+ // Preserve the original CWD for the recursive call
92
+ config.directory = newDirectory;
93
+ return await this.install(config); // Recursive call with new directory
94
+ } else if (action === 'create') {
95
+ try {
96
+ await fileManager.ensureDirectory(installDir);
97
+ console.log(`✓ Created directory: ${installDir}`);
98
+ } catch (error) {
99
+ console.error(`Failed to create directory: ${error.message}`);
100
+ console.error('You may need to check permissions or use a different path.');
101
+ process.exit(1);
102
+ }
103
+ }
104
+
105
+ spinner.start("Analyzing installation directory...");
106
+ }
107
+
108
+ // If this is an update request from early detection, handle it directly
109
+ if (config.installType === 'update') {
110
+ const state = await this.detectInstallationState(installDir);
111
+ if (state.type === 'v4_existing') {
112
+ return await this.performUpdate(config, installDir, state.manifest, spinner);
113
+ } else {
114
+ spinner.fail('No existing v4 installation found to update');
115
+ throw new Error('No existing v4 installation found');
116
+ }
117
+ }
118
+
119
+ // Detect current state
120
+ const state = await this.detectInstallationState(installDir);
121
+
122
+ // Handle different states
123
+ switch (state.type) {
124
+ case "clean":
125
+ return await this.performFreshInstall(config, installDir, spinner);
126
+
127
+ case "v4_existing":
128
+ return await this.handleExistingV4Installation(
129
+ config,
130
+ installDir,
131
+ state,
132
+ spinner
133
+ );
134
+
135
+ case "v3_existing":
136
+ return await this.handleV3Installation(
137
+ config,
138
+ installDir,
139
+ state,
140
+ spinner
141
+ );
142
+
143
+ case "unknown_existing":
144
+ return await this.handleUnknownInstallation(
145
+ config,
146
+ installDir,
147
+ state,
148
+ spinner
149
+ );
150
+ }
151
+ } catch (error) {
152
+ // Check if modules were initialized
153
+ if (spinner) {
154
+ spinner.fail("Installation failed");
155
+ } else {
156
+ console.error("Installation failed:", error.message);
157
+ }
158
+ throw error;
159
+ }
160
+ }
161
+
162
+ async detectInstallationState(installDir) {
163
+ const state = {
164
+ type: "clean",
165
+ hasV4Manifest: false,
166
+ hasV3Structure: false,
167
+ hasBmadCore: false,
168
+ hasOtherFiles: false,
169
+ manifest: null,
170
+ expansionPacks: {},
171
+ };
172
+
173
+ // Check if directory exists
174
+ if (!(await fileManager.pathExists(installDir))) {
175
+ return state; // clean install
176
+ }
177
+
178
+ // Check for V4 installation (has .xiaoma-core with manifest)
179
+ const bmadCorePath = path.join(installDir, ".xiaoma-core");
180
+ const manifestPath = path.join(bmadCorePath, "install-manifest.yaml");
181
+
182
+ if (await fileManager.pathExists(manifestPath)) {
183
+ state.type = "v4_existing";
184
+ state.hasV4Manifest = true;
185
+ state.hasBmadCore = true;
186
+ state.manifest = await fileManager.readManifest(installDir);
187
+ return state;
188
+ }
189
+
190
+ // Check for V3 installation (has bmad-agent directory)
191
+ const bmadAgentPath = path.join(installDir, "bmad-agent");
192
+ if (await fileManager.pathExists(bmadAgentPath)) {
193
+ state.type = "v3_existing";
194
+ state.hasV3Structure = true;
195
+ return state;
196
+ }
197
+
198
+ // Check for .xiaoma-core without manifest (broken V4 or manual copy)
199
+ if (await fileManager.pathExists(bmadCorePath)) {
200
+ state.type = "unknown_existing";
201
+ state.hasBmadCore = true;
202
+ return state;
203
+ }
204
+
205
+ // Check if directory has other files
206
+ const files = await resourceLocator.findFiles("**/*", {
207
+ cwd: installDir,
208
+ nodir: true,
209
+ ignore: ["**/.git/**", "**/node_modules/**"],
210
+ });
211
+
212
+ if (files.length > 0) {
213
+ // Directory has other files, but no XiaoMa installation.
214
+ // Treat as clean install but record that it isn't empty.
215
+ state.hasOtherFiles = true;
216
+ }
217
+
218
+ // Check for expansion packs (folders starting with .)
219
+ const expansionPacks = await this.detectExpansionPacks(installDir);
220
+ state.expansionPacks = expansionPacks;
221
+
222
+ return state; // clean install
223
+ }
224
+
225
+ async performFreshInstall(config, installDir, spinner, options = {}) {
226
+ spinner.text = "Installing XiaoMa Web...";
227
+
228
+ let files = [];
229
+
230
+ if (config.installType === "full") {
231
+ // Full installation - copy entire .xiaoma-core folder as a subdirectory
232
+ spinner.text = "Copying complete .xiaoma-core folder...";
233
+ const sourceDir = resourceLocator.getBmadCorePath();
234
+ const bmadCoreDestDir = path.join(installDir, ".xiaoma-core");
235
+ await fileManager.copyDirectoryWithRootReplacement(sourceDir, bmadCoreDestDir, ".xiaoma-core");
236
+
237
+ // Copy common/ items to .xiaoma-core
238
+ spinner.text = "Copying common utilities...";
239
+ await this.copyCommonItems(installDir, ".xiaoma-core", spinner);
240
+
241
+ // Get list of all files for manifest
242
+ const foundFiles = await resourceLocator.findFiles("**/*", {
243
+ cwd: bmadCoreDestDir,
244
+ nodir: true,
245
+ ignore: ["**/.git/**", "**/node_modules/**"],
246
+ });
247
+ files = foundFiles.map((file) => path.join(".xiaoma-core", file));
248
+ } else if (config.installType === "single-agent") {
249
+ // Single agent installation
250
+ spinner.text = `Installing ${config.agent} agent...`;
251
+
252
+ // Copy agent file with {root} replacement
253
+ const agentPath = configLoader.getAgentPath(config.agent);
254
+ const destAgentPath = path.join(
255
+ installDir,
256
+ ".xiaoma-core",
257
+ "agents",
258
+ `${config.agent}.md`
259
+ );
260
+ await fileManager.copyFileWithRootReplacement(agentPath, destAgentPath, ".xiaoma-core");
261
+ files.push(`.xiaoma-core/agents/${config.agent}.md`);
262
+
263
+ // Copy dependencies
264
+ const { all: dependencies } = await resourceLocator.getAgentDependencies(
265
+ config.agent
266
+ );
267
+ const sourceBase = resourceLocator.getBmadCorePath();
268
+
269
+ for (const dep of dependencies) {
270
+ spinner.text = `Copying dependency: ${dep}`;
271
+
272
+ if (dep.includes("*")) {
273
+ // Handle glob patterns with {root} replacement
274
+ const copiedFiles = await fileManager.copyGlobPattern(
275
+ dep.replace(".xiaoma-core/", ""),
276
+ sourceBase,
277
+ path.join(installDir, ".xiaoma-core"),
278
+ ".xiaoma-core"
279
+ );
280
+ files.push(...copiedFiles.map(f => `.xiaoma-core/${f}`));
281
+ } else {
282
+ // Handle single files with {root} replacement if needed
283
+ const sourcePath = path.join(
284
+ sourceBase,
285
+ dep.replace(".xiaoma-core/", "")
286
+ );
287
+ const destPath = path.join(
288
+ installDir,
289
+ dep
290
+ );
291
+
292
+ const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');
293
+ let success = false;
294
+
295
+ if (needsRootReplacement) {
296
+ success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, ".xiaoma-core");
297
+ } else {
298
+ success = await fileManager.copyFile(sourcePath, destPath);
299
+ }
300
+
301
+ if (success) {
302
+ files.push(dep);
303
+ }
304
+ }
305
+ }
306
+
307
+ // Copy common/ items to .xiaoma-core
308
+ spinner.text = "Copying common utilities...";
309
+ const commonFiles = await this.copyCommonItems(installDir, ".xiaoma-core", spinner);
310
+ files.push(...commonFiles);
311
+ } else if (config.installType === "team") {
312
+ // Team installation
313
+ spinner.text = `Installing ${config.team} team...`;
314
+
315
+ // Get team dependencies
316
+ const teamDependencies = await configLoader.getTeamDependencies(config.team);
317
+ const sourceBase = resourceLocator.getBmadCorePath();
318
+
319
+ // Install all team dependencies
320
+ for (const dep of teamDependencies) {
321
+ spinner.text = `Copying team dependency: ${dep}`;
322
+
323
+ if (dep.includes("*")) {
324
+ // Handle glob patterns with {root} replacement
325
+ const copiedFiles = await fileManager.copyGlobPattern(
326
+ dep.replace(".xiaoma-core/", ""),
327
+ sourceBase,
328
+ path.join(installDir, ".xiaoma-core"),
329
+ ".xiaoma-core"
330
+ );
331
+ files.push(...copiedFiles.map(f => `.xiaoma-core/${f}`));
332
+ } else {
333
+ // Handle single files with {root} replacement if needed
334
+ const sourcePath = path.join(sourceBase, dep.replace(".xiaoma-core/", ""));
335
+ const destPath = path.join(installDir, dep);
336
+
337
+ const needsRootReplacement = dep.endsWith('.md') || dep.endsWith('.yaml') || dep.endsWith('.yml');
338
+ let success = false;
339
+
340
+ if (needsRootReplacement) {
341
+ success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, ".xiaoma-core");
342
+ } else {
343
+ success = await fileManager.copyFile(sourcePath, destPath);
344
+ }
345
+
346
+ if (success) {
347
+ files.push(dep);
348
+ }
349
+ }
350
+ }
351
+
352
+ // Copy common/ items to .xiaoma-core
353
+ spinner.text = "Copying common utilities...";
354
+ const commonFiles = await this.copyCommonItems(installDir, ".xiaoma-core", spinner);
355
+ files.push(...commonFiles);
356
+ } else if (config.installType === "expansion-only") {
357
+ // Expansion-only installation - DO NOT create .xiaoma-core
358
+ // Only install expansion packs
359
+ spinner.text = "Installing expansion packs only...";
360
+ }
361
+
362
+ // Install expansion packs if requested
363
+ const expansionFiles = await this.installExpansionPacks(installDir, config.expansionPacks, spinner, config);
364
+ files.push(...expansionFiles);
365
+
366
+ // Install web bundles if requested
367
+ if (config.includeWebBundles && config.webBundlesDirectory) {
368
+ spinner.text = "Installing web bundles...";
369
+ // Resolve web bundles directory using the same logic as the main installation directory
370
+ const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();
371
+ let resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory)
372
+ ? config.webBundlesDirectory
373
+ : path.resolve(originalCwd, config.webBundlesDirectory);
374
+ await this.installWebBundles(resolvedWebBundlesDir, config, spinner);
375
+ }
376
+
377
+ // Set up IDE integration if requested
378
+ const ides = config.ides || (config.ide ? [config.ide] : []);
379
+ if (ides.length > 0) {
380
+ for (const ide of ides) {
381
+ spinner.text = `Setting up ${ide} integration...`;
382
+ const preConfiguredSettings = ide === 'github-copilot' ? config.githubCopilotConfig : null;
383
+ await ideSetup.setup(ide, installDir, config.agent, spinner, preConfiguredSettings);
384
+ }
385
+ }
386
+
387
+ // Modify core-config.yaml if sharding preferences were provided
388
+ if (config.installType !== "expansion-only" && (config.prdSharded !== undefined || config.architectureSharded !== undefined)) {
389
+ spinner.text = "Configuring document sharding settings...";
390
+ await fileManager.modifyCoreConfig(installDir, config);
391
+ }
392
+
393
+ // Create manifest (skip for expansion-only installations)
394
+ if (config.installType !== "expansion-only") {
395
+ spinner.text = "Creating installation manifest...";
396
+ await fileManager.createManifest(installDir, config, files);
397
+ }
398
+
399
+ spinner.succeed("Installation complete!");
400
+ this.showSuccessMessage(config, installDir, options);
401
+ }
402
+
403
+ async handleExistingV4Installation(config, installDir, state, spinner) {
404
+ spinner.stop();
405
+
406
+ const currentVersion = state.manifest.version;
407
+ const newVersion = await this.getCoreVersion();
408
+ const versionCompare = this.compareVersions(currentVersion, newVersion);
409
+
410
+ console.log(chalk.yellow("\n🔍 Found existing XiaoMa v4 installation"));
411
+ console.log(` Directory: ${installDir}`);
412
+ console.log(` Current version: ${currentVersion}`);
413
+ console.log(` Available version: ${newVersion}`);
414
+ console.log(
415
+ ` Installed: ${new Date(
416
+ state.manifest.installed_at
417
+ ).toLocaleDateString()}`
418
+ );
419
+
420
+ // Check file integrity
421
+ spinner.start("Checking installation integrity...");
422
+ const integrity = await fileManager.checkFileIntegrity(installDir, state.manifest);
423
+ spinner.stop();
424
+
425
+ const hasMissingFiles = integrity.missing.length > 0;
426
+ const hasModifiedFiles = integrity.modified.length > 0;
427
+ const hasIntegrityIssues = hasMissingFiles || hasModifiedFiles;
428
+
429
+ if (hasIntegrityIssues) {
430
+ console.log(chalk.red("\n⚠️ Installation issues detected:"));
431
+ if (hasMissingFiles) {
432
+ console.log(chalk.red(` Missing files: ${integrity.missing.length}`));
433
+ if (integrity.missing.length <= 5) {
434
+ integrity.missing.forEach(file => console.log(chalk.dim(` - ${file}`)));
435
+ }
436
+ }
437
+ if (hasModifiedFiles) {
438
+ console.log(chalk.yellow(` Modified files: ${integrity.modified.length}`));
439
+ if (integrity.modified.length <= 5) {
440
+ integrity.modified.forEach(file => console.log(chalk.dim(` - ${file}`)));
441
+ }
442
+ }
443
+ }
444
+
445
+ // Show existing expansion packs
446
+ if (Object.keys(state.expansionPacks).length > 0) {
447
+ console.log(chalk.cyan("\n📦 Installed expansion packs:"));
448
+ for (const [packId, packInfo] of Object.entries(state.expansionPacks)) {
449
+ if (packInfo.hasManifest && packInfo.manifest) {
450
+ console.log(` - ${packId} (v${packInfo.manifest.version || 'unknown'})`);
451
+ } else {
452
+ console.log(` - ${packId} (no manifest)`);
453
+ }
454
+ }
455
+ }
456
+
457
+ let choices = [];
458
+
459
+ if (versionCompare < 0) {
460
+ console.log(chalk.cyan("\n⬆️ Upgrade available for XiaoMa core"));
461
+ choices.push({ name: `Upgrade XiaoMa core (v${currentVersion} → v${newVersion})`, value: "upgrade" });
462
+ } else if (versionCompare === 0) {
463
+ if (hasIntegrityIssues) {
464
+ // Offer repair option when files are missing or modified
465
+ choices.push({
466
+ name: "Repair installation (restore missing/modified files)",
467
+ value: "repair"
468
+ });
469
+ }
470
+ console.log(chalk.yellow("\n⚠️ Same version already installed"));
471
+ choices.push({ name: `Force reinstall XiaoMa core (v${currentVersion} - reinstall)`, value: "reinstall" });
472
+ } else {
473
+ console.log(chalk.yellow("\n⬇️ Installed version is newer than available"));
474
+ choices.push({ name: `Downgrade XiaoMa core (v${currentVersion} → v${newVersion})`, value: "reinstall" });
475
+ }
476
+
477
+ choices.push(
478
+ { name: "Add/update expansion packs only", value: "expansions" },
479
+ { name: "Cancel", value: "cancel" }
480
+ );
481
+
482
+ const { action } = await inquirer.prompt([
483
+ {
484
+ type: "list",
485
+ name: "action",
486
+ message: "What would you like to do?",
487
+ choices: choices,
488
+ },
489
+ ]);
490
+
491
+ switch (action) {
492
+ case "upgrade":
493
+ return await this.performUpdate(config, installDir, state.manifest, spinner);
494
+ case "repair":
495
+ // For repair, restore missing/modified files while backing up modified ones
496
+ return await this.performRepair(config, installDir, state.manifest, integrity, spinner);
497
+ case "reinstall":
498
+ // For reinstall, don't check for modifications - just overwrite
499
+ return await this.performReinstall(config, installDir, spinner);
500
+ case "expansions": {
501
+ // Ask which expansion packs to install
502
+ const availableExpansionPacks = await resourceLocator.getExpansionPacks();
503
+
504
+ if (availableExpansionPacks.length === 0) {
505
+ console.log(chalk.yellow("No expansion packs available."));
506
+ return;
507
+ }
508
+
509
+ const { selectedPacks } = await inquirer.prompt([
510
+ {
511
+ type: 'checkbox',
512
+ name: 'selectedPacks',
513
+ message: 'Select expansion packs to install/update:',
514
+ choices: availableExpansionPacks.map(pack => ({
515
+ name: `${pack.name} (v${pack.version}) .${pack.id}`,
516
+ value: pack.id,
517
+ checked: state.expansionPacks[pack.id] !== undefined
518
+ }))
519
+ }
520
+ ]);
521
+
522
+ if (selectedPacks.length === 0) {
523
+ console.log(chalk.yellow("No expansion packs selected."));
524
+ return;
525
+ }
526
+
527
+ spinner.start("Installing expansion packs...");
528
+ const expansionFiles = await this.installExpansionPacks(installDir, selectedPacks, spinner, { ides: config.ides || [] });
529
+ spinner.succeed("Expansion packs installed successfully!");
530
+
531
+ console.log(chalk.green("\n✓ Installation complete!"));
532
+ console.log(chalk.green(`✓ Expansion packs installed/updated:`));
533
+ for (const packId of selectedPacks) {
534
+ console.log(chalk.green(` - ${packId} → .${packId}/`));
535
+ }
536
+ return;
537
+ }
538
+ case "cancel":
539
+ console.log("Installation cancelled.");
540
+ return;
541
+ }
542
+ }
543
+
544
+ async handleV3Installation(config, installDir, state, spinner) {
545
+ spinner.stop();
546
+
547
+ console.log(
548
+ chalk.yellow("\n🔍 Found XiaoMa v3 installation (bmad-agent/ directory)")
549
+ );
550
+ console.log(` Directory: ${installDir}`);
551
+
552
+ const { action } = await inquirer.prompt([
553
+ {
554
+ type: "list",
555
+ name: "action",
556
+ message: "What would you like to do?",
557
+ choices: [
558
+ { name: "Upgrade from v3 to v4 (recommended)", value: "upgrade" },
559
+ { name: "Install v4 alongside v3", value: "alongside" },
560
+ { name: "Cancel", value: "cancel" },
561
+ ],
562
+ },
563
+ ]);
564
+
565
+ switch (action) {
566
+ case "upgrade": {
567
+ console.log(chalk.cyan("\n📦 Starting v3 to v4 upgrade process..."));
568
+ const V3ToV4Upgrader = require("../../upgraders/v3-to-v4-upgrader");
569
+ const upgrader = new V3ToV4Upgrader();
570
+ return await upgrader.upgrade({
571
+ projectPath: installDir,
572
+ ides: config.ides || [] // Pass IDE selections from initial config
573
+ });
574
+ }
575
+ case "alongside":
576
+ return await this.performFreshInstall(config, installDir, spinner);
577
+ case "cancel":
578
+ console.log("Installation cancelled.");
579
+ return;
580
+ }
581
+ }
582
+
583
+ async handleUnknownInstallation(config, installDir, state, spinner) {
584
+ spinner.stop();
585
+
586
+ console.log(chalk.yellow("\n⚠️ Directory contains existing files"));
587
+ console.log(` Directory: ${installDir}`);
588
+
589
+ if (state.hasBmadCore) {
590
+ console.log(" Found: .xiaoma-core directory (but no manifest)");
591
+ }
592
+ if (state.hasOtherFiles) {
593
+ console.log(" Found: Other files in directory");
594
+ }
595
+
596
+ const { action } = await inquirer.prompt([
597
+ {
598
+ type: "list",
599
+ name: "action",
600
+ message: "What would you like to do?",
601
+ choices: [
602
+ { name: "Install anyway (may overwrite files)", value: "force" },
603
+ { name: "Choose different directory", value: "different" },
604
+ { name: "Cancel", value: "cancel" },
605
+ ],
606
+ },
607
+ ]);
608
+
609
+ switch (action) {
610
+ case "force":
611
+ return await this.performFreshInstall(config, installDir, spinner);
612
+ case "different": {
613
+ const { newDir } = await inquirer.prompt([
614
+ {
615
+ type: "input",
616
+ name: "newDir",
617
+ message: "Enter new installation directory:",
618
+ default: path.join(path.dirname(installDir), "bmad-project"),
619
+ },
620
+ ]);
621
+ config.directory = newDir;
622
+ return await this.install(config);
623
+ }
624
+ case "cancel":
625
+ console.log("Installation cancelled.");
626
+ return;
627
+ }
628
+ }
629
+
630
+ async performUpdate(newConfig, installDir, manifest, spinner) {
631
+ spinner.start("Checking for updates...");
632
+
633
+ try {
634
+ // Get current and new versions
635
+ const currentVersion = manifest.version;
636
+ const newVersion = await this.getCoreVersion();
637
+ const versionCompare = this.compareVersions(currentVersion, newVersion);
638
+
639
+ // Only check for modified files if it's an actual version upgrade
640
+ let modifiedFiles = [];
641
+ if (versionCompare !== 0) {
642
+ spinner.text = "Checking for modified files...";
643
+ modifiedFiles = await fileManager.checkModifiedFiles(
644
+ installDir,
645
+ manifest
646
+ );
647
+ }
648
+
649
+ if (modifiedFiles.length > 0) {
650
+ spinner.warn("Found modified files");
651
+ console.log(chalk.yellow("\nThe following files have been modified:"));
652
+ for (const file of modifiedFiles) {
653
+ console.log(` - ${file}`);
654
+ }
655
+
656
+ const { action } = await inquirer.prompt([
657
+ {
658
+ type: "list",
659
+ name: "action",
660
+ message: "How would you like to proceed?",
661
+ choices: [
662
+ { name: "Backup and overwrite modified files", value: "backup" },
663
+ { name: "Skip modified files", value: "skip" },
664
+ { name: "Cancel update", value: "cancel" },
665
+ ],
666
+ },
667
+ ]);
668
+
669
+ if (action === "cancel") {
670
+ console.log("Update cancelled.");
671
+ return;
672
+ }
673
+
674
+ if (action === "backup") {
675
+ spinner.start("Backing up modified files...");
676
+ for (const file of modifiedFiles) {
677
+ const filePath = path.join(installDir, file);
678
+ const backupPath = await fileManager.backupFile(filePath);
679
+ console.log(
680
+ chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`)
681
+ );
682
+ }
683
+ }
684
+ }
685
+
686
+ // Perform update by re-running installation
687
+ spinner.text = versionCompare === 0 ? "Reinstalling files..." : "Updating files...";
688
+ const config = {
689
+ installType: manifest.install_type,
690
+ agent: manifest.agent,
691
+ directory: installDir,
692
+ ides: newConfig?.ides || manifest.ides_setup || [],
693
+ };
694
+
695
+ await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });
696
+
697
+ // Clean up .yml files that now have .yaml counterparts
698
+ spinner.text = "Cleaning up legacy .yml files...";
699
+ await this.cleanupLegacyYmlFiles(installDir, spinner);
700
+ } catch (error) {
701
+ spinner.fail("Update failed");
702
+ throw error;
703
+ }
704
+ }
705
+
706
+ async performRepair(config, installDir, manifest, integrity, spinner) {
707
+ spinner.start("Preparing to repair installation...");
708
+
709
+ try {
710
+ // Back up modified files
711
+ if (integrity.modified.length > 0) {
712
+ spinner.text = "Backing up modified files...";
713
+ for (const file of integrity.modified) {
714
+ const filePath = path.join(installDir, file);
715
+ if (await fileManager.pathExists(filePath)) {
716
+ const backupPath = await fileManager.backupFile(filePath);
717
+ console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));
718
+ }
719
+ }
720
+ }
721
+
722
+ // Restore missing and modified files
723
+ spinner.text = "Restoring files...";
724
+ const sourceBase = resourceLocator.getBmadCorePath();
725
+ const filesToRestore = [...integrity.missing, ...integrity.modified];
726
+
727
+ for (const file of filesToRestore) {
728
+ // Skip the manifest file itself
729
+ if (file.endsWith('install-manifest.yaml')) continue;
730
+
731
+ const relativePath = file.replace('.xiaoma-core/', '');
732
+ const destPath = path.join(installDir, file);
733
+
734
+ // Check if this is a common/ file that needs special processing
735
+ const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));
736
+ const commonSourcePath = path.join(commonBase, 'common', relativePath);
737
+
738
+ if (await fileManager.pathExists(commonSourcePath)) {
739
+ // This is a common/ file - needs template processing
740
+ const fs = require('fs').promises;
741
+ const content = await fs.readFile(commonSourcePath, 'utf8');
742
+ const updatedContent = content.replace(/\{root\}/g, '.xiaoma-core');
743
+ await fileManager.ensureDirectory(path.dirname(destPath));
744
+ await fs.writeFile(destPath, updatedContent, 'utf8');
745
+ spinner.text = `Restored: ${file}`;
746
+ } else {
747
+ // Regular file from xiaoma-core
748
+ const sourcePath = path.join(sourceBase, relativePath);
749
+ if (await fileManager.pathExists(sourcePath)) {
750
+ await fileManager.copyFile(sourcePath, destPath);
751
+ spinner.text = `Restored: ${file}`;
752
+
753
+ // If this is a .yaml file, check for and remove corresponding .yml file
754
+ if (file.endsWith('.yaml')) {
755
+ const ymlFile = file.replace(/\.yaml$/, '.yml');
756
+ const ymlPath = path.join(installDir, ymlFile);
757
+ if (await fileManager.pathExists(ymlPath)) {
758
+ const fs = require('fs').promises;
759
+ await fs.unlink(ymlPath);
760
+ console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${file})`));
761
+ }
762
+ }
763
+ } else {
764
+ console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));
765
+ }
766
+ }
767
+ }
768
+
769
+ // Clean up .yml files that now have .yaml counterparts
770
+ spinner.text = "Cleaning up legacy .yml files...";
771
+ await this.cleanupLegacyYmlFiles(installDir, spinner);
772
+
773
+ spinner.succeed("Repair completed successfully!");
774
+
775
+ // Show summary
776
+ console.log(chalk.green("\n✓ Installation repaired!"));
777
+ if (integrity.missing.length > 0) {
778
+ console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));
779
+ }
780
+ if (integrity.modified.length > 0) {
781
+ console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));
782
+ }
783
+
784
+ // Warning for Cursor custom modes if agents were repaired
785
+ const ides = manifest.ides_setup || [];
786
+ if (ides.includes('cursor')) {
787
+ console.log(chalk.yellow.bold("\n⚠️ IMPORTANT: Cursor Custom Modes Update Required"));
788
+ console.log(chalk.yellow("Since agent files have been repaired, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs."));
789
+ }
790
+
791
+ } catch (error) {
792
+ spinner.fail("Repair failed");
793
+ throw error;
794
+ }
795
+ }
796
+
797
+ async performReinstall(config, installDir, spinner) {
798
+ spinner.start("Preparing to reinstall XiaoMa Web...");
799
+
800
+ // Remove existing .xiaoma-core
801
+ const bmadCorePath = path.join(installDir, ".xiaoma-core");
802
+ if (await fileManager.pathExists(bmadCorePath)) {
803
+ spinner.text = "Removing existing installation...";
804
+ await fileManager.removeDirectory(bmadCorePath);
805
+ }
806
+
807
+ spinner.text = "Installing fresh copy...";
808
+ const result = await this.performFreshInstall(config, installDir, spinner, { isUpdate: true });
809
+
810
+ // Clean up .yml files that now have .yaml counterparts
811
+ spinner.text = "Cleaning up legacy .yml files...";
812
+ await this.cleanupLegacyYmlFiles(installDir, spinner);
813
+
814
+ return result;
815
+ }
816
+
817
+ showSuccessMessage(config, installDir, options = {}) {
818
+ console.log(chalk.green("\n✓ XiaoMa Web installed successfully!\n"));
819
+
820
+ const ides = config.ides || (config.ide ? [config.ide] : []);
821
+ if (ides.length > 0) {
822
+ for (const ide of ides) {
823
+ const ideConfig = configLoader.getIdeConfiguration(ide);
824
+ if (ideConfig?.instructions) {
825
+ console.log(
826
+ chalk.bold(`To use XiaoMa agents in ${ideConfig.name}:`)
827
+ );
828
+ console.log(ideConfig.instructions);
829
+ }
830
+ }
831
+ } else {
832
+ console.log(chalk.yellow("No IDE configuration was set up."));
833
+ console.log(
834
+ "You can manually configure your IDE using the agent files in:",
835
+ installDir
836
+ );
837
+ }
838
+
839
+ // Information about installation components
840
+ console.log(chalk.bold("\n🎯 Installation Summary:"));
841
+ if (config.installType !== "expansion-only") {
842
+ console.log(chalk.green("✓ .xiaoma-core framework installed with all agents and workflows"));
843
+ }
844
+
845
+ if (config.expansionPacks && config.expansionPacks.length > 0) {
846
+ console.log(chalk.green(`✓ Expansion packs installed:`));
847
+ for (const packId of config.expansionPacks) {
848
+ console.log(chalk.green(` - ${packId} → .${packId}/`));
849
+ }
850
+ }
851
+
852
+ if (config.includeWebBundles && config.webBundlesDirectory) {
853
+ const bundleInfo = this.getWebBundleInfo(config);
854
+ // Resolve the web bundles directory for display
855
+ const originalCwd = process.env.INIT_CWD || process.env.PWD || process.cwd();
856
+ const resolvedWebBundlesDir = path.isAbsolute(config.webBundlesDirectory)
857
+ ? config.webBundlesDirectory
858
+ : path.resolve(originalCwd, config.webBundlesDirectory);
859
+ console.log(chalk.green(`✓ Web bundles (${bundleInfo}) installed to: ${resolvedWebBundlesDir}`));
860
+ }
861
+
862
+ if (ides.length > 0) {
863
+ const ideNames = ides.map(ide => {
864
+ const ideConfig = configLoader.getIdeConfiguration(ide);
865
+ return ideConfig?.name || ide;
866
+ }).join(", ");
867
+ console.log(chalk.green(`✓ IDE rules and configurations set up for: ${ideNames}`));
868
+ }
869
+
870
+
871
+
872
+ // Information about web bundles
873
+ if (!config.includeWebBundles) {
874
+ console.log(chalk.bold("\n📦 Web Bundles Available:"));
875
+ console.log("Pre-built web bundles are available and can be added later:");
876
+ console.log(chalk.cyan(" Run the installer again to add them to your project"));
877
+ console.log("These bundles work independently and can be shared, moved, or used");
878
+ console.log("in other projects as standalone files.");
879
+ }
880
+
881
+ if (config.installType === "single-agent") {
882
+ console.log(
883
+ chalk.dim(
884
+ "\nNeed other agents? Run: npx xiaoma-web install --agent=<name>"
885
+ )
886
+ );
887
+ console.log(
888
+ chalk.dim("Need everything? Run: npx xiaoma-web install --full")
889
+ );
890
+ }
891
+
892
+ // Warning for Cursor custom modes if agents were updated
893
+ if (options.isUpdate && ides.includes('cursor')) {
894
+ console.log(chalk.yellow.bold("\n⚠️ IMPORTANT: Cursor Custom Modes Update Required"));
895
+ console.log(chalk.yellow("Since agents have been updated, you need to update any custom agent modes configured in the Cursor custom agent GUI per the Cursor docs."));
896
+ }
897
+
898
+ // Important notice to read the user guide
899
+ console.log(chalk.red.bold("\n📖 IMPORTANT: Please read the user guide installed at .xiaoma-core/user-guide.md"));
900
+ console.log(chalk.red("This guide contains essential information about the XiaoMa workflow and how to use the agents effectively."));
901
+ }
902
+
903
+ // Legacy method for backward compatibility
904
+ async update() {
905
+ console.log(chalk.yellow('The "update" command is deprecated.'));
906
+ console.log(
907
+ 'Please use "install" instead - it will detect and offer to update existing installations.'
908
+ );
909
+
910
+ const installDir = await this.findInstallation();
911
+ if (installDir) {
912
+ const config = {
913
+ installType: "full",
914
+ directory: path.dirname(installDir),
915
+ ide: null,
916
+ };
917
+ return await this.install(config);
918
+ }
919
+ console.log(chalk.red("No XiaoMa installation found."));
920
+ }
921
+
922
+ async listAgents() {
923
+ const agents = await resourceLocator.getAvailableAgents();
924
+
925
+ console.log(chalk.bold("\nAvailable XiaoMa Agents:\n"));
926
+
927
+ for (const agent of agents) {
928
+ console.log(chalk.cyan(` ${agent.id.padEnd(20)}`), agent.description);
929
+ }
930
+
931
+ console.log(
932
+ chalk.dim("\nInstall with: npx xiaoma-web install --agent=<id>\n")
933
+ );
934
+ }
935
+
936
+ async listExpansionPacks() {
937
+ const expansionPacks = await resourceLocator.getExpansionPacks();
938
+
939
+ console.log(chalk.bold("\nAvailable XiaoMa Expansion Packs:\n"));
940
+
941
+ if (expansionPacks.length === 0) {
942
+ console.log(chalk.yellow("No expansion packs found."));
943
+ return;
944
+ }
945
+
946
+ for (const pack of expansionPacks) {
947
+ console.log(chalk.cyan(` ${pack.id.padEnd(20)}`),
948
+ `${pack.name} v${pack.version}`);
949
+ console.log(chalk.dim(` ${' '.repeat(22)}${pack.description}`));
950
+ if (pack.author && pack.author !== 'Unknown') {
951
+ console.log(chalk.dim(` ${' '.repeat(22)}by ${pack.author}`));
952
+ }
953
+ console.log();
954
+ }
955
+
956
+ console.log(
957
+ chalk.dim("Install with: npx xiaoma-web install --full --expansion-packs <id>\n")
958
+ );
959
+ }
960
+
961
+ async showStatus() {
962
+ const installDir = await this.findInstallation();
963
+
964
+ if (!installDir) {
965
+ console.log(
966
+ chalk.yellow("No XiaoMa installation found in current directory tree")
967
+ );
968
+ return;
969
+ }
970
+
971
+ const manifest = await fileManager.readManifest(installDir);
972
+
973
+ if (!manifest) {
974
+ console.log(chalk.red("Invalid installation - manifest not found"));
975
+ return;
976
+ }
977
+
978
+ console.log(chalk.bold("\nXiaoMa Installation Status:\n"));
979
+ console.log(` Directory: ${installDir}`);
980
+ console.log(` Version: ${manifest.version}`);
981
+ console.log(
982
+ ` Installed: ${new Date(
983
+ manifest.installed_at
984
+ ).toLocaleDateString()}`
985
+ );
986
+ console.log(` Type: ${manifest.install_type}`);
987
+
988
+ if (manifest.agent) {
989
+ console.log(` Agent: ${manifest.agent}`);
990
+ }
991
+
992
+ if (manifest.ides_setup && manifest.ides_setup.length > 0) {
993
+ console.log(` IDE Setup: ${manifest.ides_setup.join(', ')}`);
994
+ }
995
+
996
+ console.log(` Total Files: ${manifest.files.length}`);
997
+
998
+ // Check for modifications
999
+ const modifiedFiles = await fileManager.checkModifiedFiles(
1000
+ installDir,
1001
+ manifest
1002
+ );
1003
+ if (modifiedFiles.length > 0) {
1004
+ console.log(chalk.yellow(` Modified Files: ${modifiedFiles.length}`));
1005
+ }
1006
+
1007
+ console.log("");
1008
+ }
1009
+
1010
+ async getAvailableAgents() {
1011
+ return resourceLocator.getAvailableAgents();
1012
+ }
1013
+
1014
+ async getAvailableExpansionPacks() {
1015
+ return resourceLocator.getExpansionPacks();
1016
+ }
1017
+
1018
+ async getAvailableTeams() {
1019
+ return configLoader.getAvailableTeams();
1020
+ }
1021
+
1022
+ async installExpansionPacks(installDir, selectedPacks, spinner, config = {}) {
1023
+ if (!selectedPacks || selectedPacks.length === 0) {
1024
+ return [];
1025
+ }
1026
+
1027
+ const installedFiles = [];
1028
+
1029
+ for (const packId of selectedPacks) {
1030
+ spinner.text = `Installing expansion pack: ${packId}...`;
1031
+
1032
+ try {
1033
+ const expansionPacks = await resourceLocator.getExpansionPacks();
1034
+ const pack = expansionPacks.find(p => p.id === packId);
1035
+
1036
+ if (!pack) {
1037
+ console.warn(`Expansion pack ${packId} not found, skipping...`);
1038
+ continue;
1039
+ }
1040
+
1041
+ // Check if expansion pack already exists
1042
+ let expansionDotFolder = path.join(installDir, `.${packId}`);
1043
+ const existingManifestPath = path.join(expansionDotFolder, 'install-manifest.yaml');
1044
+
1045
+ if (await fileManager.pathExists(existingManifestPath)) {
1046
+ spinner.stop();
1047
+ const existingManifest = await fileManager.readExpansionPackManifest(installDir, packId);
1048
+
1049
+ console.log(chalk.yellow(`\n🔍 Found existing ${pack.name} installation`));
1050
+ console.log(` Current version: ${existingManifest.version || 'unknown'}`);
1051
+ console.log(` New version: ${pack.version}`);
1052
+
1053
+ // Check integrity of existing expansion pack
1054
+ const packIntegrity = await fileManager.checkFileIntegrity(installDir, existingManifest);
1055
+ const hasPackIntegrityIssues = packIntegrity.missing.length > 0 || packIntegrity.modified.length > 0;
1056
+
1057
+ if (hasPackIntegrityIssues) {
1058
+ console.log(chalk.red(" ⚠️ Installation issues detected:"));
1059
+ if (packIntegrity.missing.length > 0) {
1060
+ console.log(chalk.red(` Missing files: ${packIntegrity.missing.length}`));
1061
+ }
1062
+ if (packIntegrity.modified.length > 0) {
1063
+ console.log(chalk.yellow(` Modified files: ${packIntegrity.modified.length}`));
1064
+ }
1065
+ }
1066
+
1067
+ const versionCompare = this.compareVersions(existingManifest.version || '0.0.0', pack.version);
1068
+
1069
+ if (versionCompare === 0) {
1070
+ console.log(chalk.yellow(' ⚠️ Same version already installed'));
1071
+
1072
+ const choices = [];
1073
+ if (hasPackIntegrityIssues) {
1074
+ choices.push({ name: 'Repair (restore missing/modified files)', value: 'repair' });
1075
+ }
1076
+ choices.push(
1077
+ { name: 'Force reinstall (overwrite)', value: 'overwrite' },
1078
+ { name: 'Skip this expansion pack', value: 'skip' },
1079
+ { name: 'Cancel installation', value: 'cancel' }
1080
+ );
1081
+
1082
+ const { action } = await inquirer.prompt([{
1083
+ type: 'list',
1084
+ name: 'action',
1085
+ message: `${pack.name} v${pack.version} is already installed. What would you like to do?`,
1086
+ choices: choices
1087
+ }]);
1088
+
1089
+ if (action === 'skip') {
1090
+ spinner.start();
1091
+ continue;
1092
+ } else if (action === 'cancel') {
1093
+ console.log('Installation cancelled.');
1094
+ process.exit(0);
1095
+ } else if (action === 'repair') {
1096
+ // Repair the expansion pack
1097
+ await this.repairExpansionPack(installDir, packId, pack, packIntegrity, spinner);
1098
+ continue;
1099
+ }
1100
+ } else if (versionCompare < 0) {
1101
+ console.log(chalk.cyan(' ⬆️ Upgrade available'));
1102
+
1103
+ const { proceed } = await inquirer.prompt([{
1104
+ type: 'confirm',
1105
+ name: 'proceed',
1106
+ message: `Upgrade ${pack.name} from v${existingManifest.version} to v${pack.version}?`,
1107
+ default: true
1108
+ }]);
1109
+
1110
+ if (!proceed) {
1111
+ spinner.start();
1112
+ continue;
1113
+ }
1114
+ } else {
1115
+ console.log(chalk.yellow(' ⬇️ Installed version is newer than available version'));
1116
+
1117
+ const { action } = await inquirer.prompt([{
1118
+ type: 'list',
1119
+ name: 'action',
1120
+ message: 'What would you like to do?',
1121
+ choices: [
1122
+ { name: 'Keep current version', value: 'skip' },
1123
+ { name: 'Downgrade to available version', value: 'downgrade' },
1124
+ { name: 'Cancel installation', value: 'cancel' }
1125
+ ]
1126
+ }]);
1127
+
1128
+ if (action === 'skip') {
1129
+ spinner.start();
1130
+ continue;
1131
+ } else if (action === 'cancel') {
1132
+ console.log('Installation cancelled.');
1133
+ process.exit(0);
1134
+ }
1135
+ }
1136
+
1137
+ // If we get here, we're proceeding with installation
1138
+ spinner.start(`Removing old ${pack.name} installation...`);
1139
+ await fileManager.removeDirectory(expansionDotFolder);
1140
+ }
1141
+
1142
+ const expansionPackDir = pack.path;
1143
+
1144
+ // Ensure dedicated dot folder exists for this expansion pack
1145
+ expansionDotFolder = path.join(installDir, `.${packId}`);
1146
+ await fileManager.ensureDirectory(expansionDotFolder);
1147
+
1148
+ // Define the folders to copy from expansion packs
1149
+ const foldersToSync = [
1150
+ 'agents',
1151
+ 'agent-teams',
1152
+ 'templates',
1153
+ 'tasks',
1154
+ 'checklists',
1155
+ 'workflows',
1156
+ 'data',
1157
+ 'utils',
1158
+ 'schemas'
1159
+ ];
1160
+
1161
+ // Copy each folder if it exists
1162
+ for (const folder of foldersToSync) {
1163
+ const sourceFolder = path.join(expansionPackDir, folder);
1164
+
1165
+ // Check if folder exists in expansion pack
1166
+ if (await fileManager.pathExists(sourceFolder)) {
1167
+ // Get all files in this folder
1168
+ const files = await resourceLocator.findFiles('**/*', {
1169
+ cwd: sourceFolder,
1170
+ nodir: true
1171
+ });
1172
+
1173
+ // Copy each file to the expansion pack's dot folder with {root} replacement
1174
+ for (const file of files) {
1175
+ const sourcePath = path.join(sourceFolder, file);
1176
+ const destPath = path.join(expansionDotFolder, folder, file);
1177
+
1178
+ const needsRootReplacement = file.endsWith('.md') || file.endsWith('.yaml') || file.endsWith('.yml');
1179
+ let success = false;
1180
+
1181
+ if (needsRootReplacement) {
1182
+ success = await fileManager.copyFileWithRootReplacement(sourcePath, destPath, `.${packId}`);
1183
+ } else {
1184
+ success = await fileManager.copyFile(sourcePath, destPath);
1185
+ }
1186
+
1187
+ if (success) {
1188
+ installedFiles.push(path.join(`.${packId}`, folder, file));
1189
+ }
1190
+ }
1191
+ }
1192
+ }
1193
+
1194
+ // Copy config.yaml with {root} replacement
1195
+ const configPath = path.join(expansionPackDir, 'config.yaml');
1196
+ if (await fileManager.pathExists(configPath)) {
1197
+ const configDestPath = path.join(expansionDotFolder, 'config.yaml');
1198
+ if (await fileManager.copyFileWithRootReplacement(configPath, configDestPath, `.${packId}`)) {
1199
+ installedFiles.push(path.join(`.${packId}`, 'config.yaml'));
1200
+ }
1201
+ }
1202
+
1203
+ // Copy README if it exists with {root} replacement
1204
+ const readmePath = path.join(expansionPackDir, 'README.md');
1205
+ if (await fileManager.pathExists(readmePath)) {
1206
+ const readmeDestPath = path.join(expansionDotFolder, 'README.md');
1207
+ if (await fileManager.copyFileWithRootReplacement(readmePath, readmeDestPath, `.${packId}`)) {
1208
+ installedFiles.push(path.join(`.${packId}`, 'README.md'));
1209
+ }
1210
+ }
1211
+
1212
+ // Copy common/ items to expansion pack folder
1213
+ spinner.text = `Copying common utilities to ${packId}...`;
1214
+ await this.copyCommonItems(installDir, `.${packId}`, spinner);
1215
+
1216
+ // Check and resolve core dependencies
1217
+ await this.resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner);
1218
+
1219
+ // Check and resolve core agents referenced by teams
1220
+ await this.resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner);
1221
+
1222
+ // Create manifest for this expansion pack
1223
+ spinner.text = `Creating manifest for ${packId}...`;
1224
+ const expansionConfig = {
1225
+ installType: 'expansion-pack',
1226
+ expansionPackId: packId,
1227
+ expansionPackName: pack.name,
1228
+ expansionPackVersion: pack.version,
1229
+ ides: config.ides || [] // Use ides_setup instead of ide_setup
1230
+ };
1231
+
1232
+ // Get all files installed in this expansion pack
1233
+ const foundFiles = await resourceLocator.findFiles('**/*', {
1234
+ cwd: expansionDotFolder,
1235
+ nodir: true
1236
+ });
1237
+ const expansionPackFiles = foundFiles.map(f => path.join(`.${packId}`, f));
1238
+
1239
+ await fileManager.createExpansionPackManifest(installDir, packId, expansionConfig, expansionPackFiles);
1240
+
1241
+ console.log(chalk.green(`✓ Installed expansion pack: ${pack.name} to ${`.${packId}`}`));
1242
+ } catch (error) {
1243
+ console.error(`Failed to install expansion pack ${packId}: ${error.message}`);
1244
+ console.error(`Stack trace: ${error.stack}`);
1245
+ }
1246
+ }
1247
+
1248
+ return installedFiles;
1249
+ }
1250
+
1251
+ async resolveExpansionPackCoreDependencies(installDir, expansionDotFolder, packId, pack, spinner) {
1252
+ const yaml = require('js-yaml');
1253
+ const fs = require('fs').promises;
1254
+
1255
+ // Find all agent files in the expansion pack
1256
+ const agentFiles = await resourceLocator.findFiles('agents/*.md', {
1257
+ cwd: expansionDotFolder
1258
+ });
1259
+
1260
+ for (const agentFile of agentFiles) {
1261
+ const agentPath = path.join(expansionDotFolder, agentFile);
1262
+ const agentContent = await fs.readFile(agentPath, 'utf8');
1263
+
1264
+ // Extract YAML frontmatter to check dependencies
1265
+ const yamlContent = extractYamlFromAgent(agentContent);
1266
+ if (yamlContent) {
1267
+ try {
1268
+ const agentConfig = yaml.load(yamlContent);
1269
+ const dependencies = agentConfig.dependencies || {};
1270
+
1271
+ // Check for core dependencies (those that don't exist in the expansion pack)
1272
+ for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {
1273
+ const deps = dependencies[depType] || [];
1274
+
1275
+ for (const dep of deps) {
1276
+ const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep :
1277
+ (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);
1278
+ const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);
1279
+
1280
+ // Check if dependency exists in expansion pack dot folder
1281
+ if (!(await fileManager.pathExists(expansionDepPath))) {
1282
+ // Try to find it in expansion pack source
1283
+ const sourceDepPath = path.join(pack.path, depType, depFileName);
1284
+
1285
+ if (await fileManager.pathExists(sourceDepPath)) {
1286
+ // Copy from expansion pack source
1287
+ spinner.text = `Copying ${packId} dependency ${dep}...`;
1288
+ const destPath = path.join(expansionDotFolder, depType, depFileName);
1289
+ await fileManager.copyFileWithRootReplacement(sourceDepPath, destPath, `.${packId}`);
1290
+ console.log(chalk.dim(` Added ${packId} dependency: ${depType}/${depFileName}`));
1291
+ } else {
1292
+ // Try to find it in core
1293
+ const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);
1294
+
1295
+ if (await fileManager.pathExists(coreDepPath)) {
1296
+ spinner.text = `Copying core dependency ${dep} for ${packId}...`;
1297
+
1298
+ // Copy from core to expansion pack dot folder with {root} replacement
1299
+ const destPath = path.join(expansionDotFolder, depType, depFileName);
1300
+ await fileManager.copyFileWithRootReplacement(coreDepPath, destPath, `.${packId}`);
1301
+
1302
+ console.log(chalk.dim(` Added core dependency: ${depType}/${depFileName}`));
1303
+ } else {
1304
+ console.warn(chalk.yellow(` Warning: Dependency ${depType}/${dep} not found in core or expansion pack`));
1305
+ }
1306
+ }
1307
+ }
1308
+ }
1309
+ }
1310
+ } catch (error) {
1311
+ console.warn(` Warning: Could not parse agent dependencies: ${error.message}`);
1312
+ }
1313
+ }
1314
+ }
1315
+ }
1316
+
1317
+ async resolveExpansionPackCoreAgents(installDir, expansionDotFolder, packId, spinner) {
1318
+ const yaml = require('js-yaml');
1319
+ const fs = require('fs').promises;
1320
+
1321
+ // Find all team files in the expansion pack
1322
+ const teamFiles = await resourceLocator.findFiles('agent-teams/*.yaml', {
1323
+ cwd: expansionDotFolder
1324
+ });
1325
+
1326
+ // Also get existing agents in the expansion pack
1327
+ const existingAgents = new Set();
1328
+ const agentFiles = await resourceLocator.findFiles('agents/*.md', {
1329
+ cwd: expansionDotFolder
1330
+ });
1331
+ for (const agentFile of agentFiles) {
1332
+ const agentName = path.basename(agentFile, '.md');
1333
+ existingAgents.add(agentName);
1334
+ }
1335
+
1336
+ // Process each team file
1337
+ for (const teamFile of teamFiles) {
1338
+ const teamPath = path.join(expansionDotFolder, teamFile);
1339
+ const teamContent = await fs.readFile(teamPath, 'utf8');
1340
+
1341
+ try {
1342
+ const teamConfig = yaml.load(teamContent);
1343
+ const agents = teamConfig.agents || [];
1344
+
1345
+ // Add bmad-orchestrator if not present (required for all teams)
1346
+ if (!agents.includes('bmad-orchestrator')) {
1347
+ agents.unshift('bmad-orchestrator');
1348
+ }
1349
+
1350
+ // Check each agent in the team
1351
+ for (const agentId of agents) {
1352
+ if (!existingAgents.has(agentId)) {
1353
+ // Agent not in expansion pack, try to get from core
1354
+ const coreAgentPath = path.join(resourceLocator.getBmadCorePath(), 'agents', `${agentId}.md`);
1355
+
1356
+ if (await fileManager.pathExists(coreAgentPath)) {
1357
+ spinner.text = `Copying core agent ${agentId} for ${packId}...`;
1358
+
1359
+ // Copy agent file with {root} replacement
1360
+ const destPath = path.join(expansionDotFolder, 'agents', `${agentId}.md`);
1361
+ await fileManager.copyFileWithRootReplacement(coreAgentPath, destPath, `.${packId}`);
1362
+ existingAgents.add(agentId);
1363
+
1364
+ console.log(chalk.dim(` Added core agent: ${agentId}`));
1365
+
1366
+ // Now resolve this agent's dependencies too
1367
+ const agentContent = await fs.readFile(coreAgentPath, 'utf8');
1368
+ const yamlContent = extractYamlFromAgent(agentContent, true);
1369
+
1370
+ if (yamlContent) {
1371
+ try {
1372
+
1373
+ const agentConfig = yaml.load(yamlContent);
1374
+ const dependencies = agentConfig.dependencies || {};
1375
+
1376
+ // Copy all dependencies for this agent
1377
+ for (const depType of ['tasks', 'templates', 'checklists', 'workflows', 'utils', 'data']) {
1378
+ const deps = dependencies[depType] || [];
1379
+
1380
+ for (const dep of deps) {
1381
+ const depFileName = dep.endsWith('.md') || dep.endsWith('.yaml') ? dep :
1382
+ (depType === 'templates' ? `${dep}.yaml` : `${dep}.md`);
1383
+ const expansionDepPath = path.join(expansionDotFolder, depType, depFileName);
1384
+
1385
+ // Check if dependency exists in expansion pack
1386
+ if (!(await fileManager.pathExists(expansionDepPath))) {
1387
+ // Try to find it in core
1388
+ const coreDepPath = path.join(resourceLocator.getBmadCorePath(), depType, depFileName);
1389
+
1390
+ if (await fileManager.pathExists(coreDepPath)) {
1391
+ const destDepPath = path.join(expansionDotFolder, depType, depFileName);
1392
+ await fileManager.copyFileWithRootReplacement(coreDepPath, destDepPath, `.${packId}`);
1393
+ console.log(chalk.dim(` Added agent dependency: ${depType}/${depFileName}`));
1394
+ } else {
1395
+ // Try common folder
1396
+ const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root
1397
+ const commonDepPath = path.join(sourceBase, 'common', depType, depFileName);
1398
+ if (await fileManager.pathExists(commonDepPath)) {
1399
+ const destDepPath = path.join(expansionDotFolder, depType, depFileName);
1400
+ await fileManager.copyFile(commonDepPath, destDepPath);
1401
+ console.log(chalk.dim(` Added agent dependency from common: ${depType}/${depFileName}`));
1402
+ }
1403
+ }
1404
+ }
1405
+ }
1406
+ }
1407
+ } catch (error) {
1408
+ console.warn(` Warning: Could not parse agent ${agentId} dependencies: ${error.message}`);
1409
+ }
1410
+ }
1411
+ } else {
1412
+ console.warn(chalk.yellow(` Warning: Core agent ${agentId} not found for team ${path.basename(teamFile, '.yaml')}`));
1413
+ }
1414
+ }
1415
+ }
1416
+ } catch (error) {
1417
+ console.warn(` Warning: Could not parse team file ${teamFile}: ${error.message}`);
1418
+ }
1419
+ }
1420
+ }
1421
+
1422
+ getWebBundleInfo(config) {
1423
+ const webBundleType = config.webBundleType || 'all';
1424
+
1425
+ switch (webBundleType) {
1426
+ case 'all':
1427
+ return 'all bundles';
1428
+ case 'agents':
1429
+ return 'individual agents only';
1430
+ case 'teams':
1431
+ return config.selectedWebBundleTeams ?
1432
+ `teams: ${config.selectedWebBundleTeams.join(', ')}` :
1433
+ 'selected teams';
1434
+ case 'custom': {
1435
+ const parts = [];
1436
+ if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {
1437
+ parts.push(`teams: ${config.selectedWebBundleTeams.join(', ')}`);
1438
+ }
1439
+ if (config.includeIndividualAgents) {
1440
+ parts.push('individual agents');
1441
+ }
1442
+ return parts.length > 0 ? parts.join(' + ') : 'custom selection';
1443
+ }
1444
+ default:
1445
+ return 'selected bundles';
1446
+ }
1447
+ }
1448
+
1449
+ async installWebBundles(webBundlesDirectory, config, spinner) {
1450
+
1451
+ try {
1452
+ // Find the dist directory in the XiaoMa installation
1453
+ const distDir = configLoader.getDistPath();
1454
+
1455
+ if (!(await fileManager.pathExists(distDir))) {
1456
+ console.warn('Web bundles not found. Run "npm run build" to generate them.');
1457
+ return;
1458
+ }
1459
+
1460
+ // Ensure web bundles directory exists
1461
+ await fileManager.ensureDirectory(webBundlesDirectory);
1462
+
1463
+ const webBundleType = config.webBundleType || 'all';
1464
+
1465
+ if (webBundleType === 'all') {
1466
+ // Copy the entire dist directory structure
1467
+ await fileManager.copyDirectory(distDir, webBundlesDirectory);
1468
+ console.log(chalk.green(`✓ Installed all web bundles to: ${webBundlesDirectory}`));
1469
+ } else {
1470
+ let copiedCount = 0;
1471
+
1472
+ // Copy specific selections based on type
1473
+ if (webBundleType === 'agents' || (webBundleType === 'custom' && config.includeIndividualAgents)) {
1474
+ const agentsSource = path.join(distDir, 'agents');
1475
+ const agentsTarget = path.join(webBundlesDirectory, 'agents');
1476
+ if (await fileManager.pathExists(agentsSource)) {
1477
+ await fileManager.copyDirectory(agentsSource, agentsTarget);
1478
+ console.log(chalk.green(`✓ Copied individual agent bundles`));
1479
+ copiedCount += 10; // Approximate count for agents
1480
+ }
1481
+ }
1482
+
1483
+ if (webBundleType === 'teams' || webBundleType === 'custom') {
1484
+ if (config.selectedWebBundleTeams && config.selectedWebBundleTeams.length > 0) {
1485
+ const teamsSource = path.join(distDir, 'teams');
1486
+ const teamsTarget = path.join(webBundlesDirectory, 'teams');
1487
+ await fileManager.ensureDirectory(teamsTarget);
1488
+
1489
+ for (const teamId of config.selectedWebBundleTeams) {
1490
+ const teamFile = `${teamId}.txt`;
1491
+ const sourcePath = path.join(teamsSource, teamFile);
1492
+ const targetPath = path.join(teamsTarget, teamFile);
1493
+
1494
+ if (await fileManager.pathExists(sourcePath)) {
1495
+ await fileManager.copyFile(sourcePath, targetPath);
1496
+ copiedCount++;
1497
+ console.log(chalk.green(`✓ Copied team bundle: ${teamId}`));
1498
+ }
1499
+ }
1500
+ }
1501
+ }
1502
+
1503
+ // Always copy expansion packs if they exist
1504
+ const expansionSource = path.join(distDir, 'expansion-packs');
1505
+ const expansionTarget = path.join(webBundlesDirectory, 'expansion-packs');
1506
+ if (await fileManager.pathExists(expansionSource)) {
1507
+ await fileManager.copyDirectory(expansionSource, expansionTarget);
1508
+ console.log(chalk.green(`✓ Copied expansion pack bundles`));
1509
+ }
1510
+
1511
+ console.log(chalk.green(`✓ Installed ${copiedCount} selected web bundles to: ${webBundlesDirectory}`));
1512
+ }
1513
+ } catch (error) {
1514
+ console.error(`Failed to install web bundles: ${error.message}`);
1515
+ }
1516
+ }
1517
+
1518
+ async copyCommonItems(installDir, targetSubdir, spinner) {
1519
+
1520
+ const fs = require('fs').promises;
1521
+ const sourceBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename)))); // Go up to project root
1522
+ const commonPath = path.join(sourceBase, 'common');
1523
+ const targetPath = path.join(installDir, targetSubdir);
1524
+ const copiedFiles = [];
1525
+
1526
+ // Check if common/ exists
1527
+ if (!(await fileManager.pathExists(commonPath))) {
1528
+ console.warn('Warning: common/ folder not found');
1529
+ return copiedFiles;
1530
+ }
1531
+
1532
+ // Copy all items from common/ to target
1533
+ const commonItems = await resourceLocator.findFiles('**/*', {
1534
+ cwd: commonPath,
1535
+ nodir: true
1536
+ });
1537
+
1538
+ for (const item of commonItems) {
1539
+ const sourcePath = path.join(commonPath, item);
1540
+ const destPath = path.join(targetPath, item);
1541
+
1542
+ // Read the file content
1543
+ const content = await fs.readFile(sourcePath, 'utf8');
1544
+
1545
+ // Replace {root} with the target subdirectory
1546
+ const updatedContent = content.replace(/\{root\}/g, targetSubdir);
1547
+
1548
+ // Ensure directory exists
1549
+ await fileManager.ensureDirectory(path.dirname(destPath));
1550
+
1551
+ // Write the updated content
1552
+ await fs.writeFile(destPath, updatedContent, 'utf8');
1553
+ copiedFiles.push(path.join(targetSubdir, item));
1554
+ }
1555
+
1556
+ console.log(chalk.dim(` Added ${commonItems.length} common utilities`));
1557
+ return copiedFiles;
1558
+ }
1559
+
1560
+ async detectExpansionPacks(installDir) {
1561
+ const expansionPacks = {};
1562
+ const glob = require("glob");
1563
+
1564
+ // Find all dot folders that might be expansion packs
1565
+ const dotFolders = glob.sync(".*", {
1566
+ cwd: installDir,
1567
+ ignore: [".git", ".git/**", ".xiaoma-core", ".xiaoma-core/**"],
1568
+ });
1569
+
1570
+ for (const folder of dotFolders) {
1571
+ const folderPath = path.join(installDir, folder);
1572
+ const stats = await fileManager.pathExists(folderPath);
1573
+
1574
+ if (stats) {
1575
+ // Check if it has a manifest
1576
+ const manifestPath = path.join(folderPath, "install-manifest.yaml");
1577
+ if (await fileManager.pathExists(manifestPath)) {
1578
+ const manifest = await fileManager.readExpansionPackManifest(installDir, folder.substring(1));
1579
+ if (manifest) {
1580
+ expansionPacks[folder.substring(1)] = {
1581
+ path: folderPath,
1582
+ manifest: manifest,
1583
+ hasManifest: true
1584
+ };
1585
+ }
1586
+ } else {
1587
+ // Check if it has a config.yaml (expansion pack without manifest)
1588
+ const configPath = path.join(folderPath, "config.yaml");
1589
+ if (await fileManager.pathExists(configPath)) {
1590
+ expansionPacks[folder.substring(1)] = {
1591
+ path: folderPath,
1592
+ manifest: null,
1593
+ hasManifest: false
1594
+ };
1595
+ }
1596
+ }
1597
+ }
1598
+ }
1599
+
1600
+ return expansionPacks;
1601
+ }
1602
+
1603
+ async repairExpansionPack(installDir, packId, pack, integrity, spinner) {
1604
+ spinner.start(`Repairing ${pack.name}...`);
1605
+
1606
+ try {
1607
+ const expansionDotFolder = path.join(installDir, `.${packId}`);
1608
+
1609
+ // Back up modified files
1610
+ if (integrity.modified.length > 0) {
1611
+ spinner.text = "Backing up modified files...";
1612
+ for (const file of integrity.modified) {
1613
+ const filePath = path.join(installDir, file);
1614
+ if (await fileManager.pathExists(filePath)) {
1615
+ const backupPath = await fileManager.backupFile(filePath);
1616
+ console.log(chalk.dim(` Backed up: ${file} → ${path.basename(backupPath)}`));
1617
+ }
1618
+ }
1619
+ }
1620
+
1621
+ // Restore missing and modified files
1622
+ spinner.text = "Restoring files...";
1623
+ const filesToRestore = [...integrity.missing, ...integrity.modified];
1624
+
1625
+ for (const file of filesToRestore) {
1626
+ // Skip the manifest file itself
1627
+ if (file.endsWith('install-manifest.yaml')) continue;
1628
+
1629
+ const relativePath = file.replace(`.${packId}/`, '');
1630
+ const sourcePath = path.join(pack.path, relativePath);
1631
+ const destPath = path.join(installDir, file);
1632
+
1633
+ // Check if this is a common/ file that needs special processing
1634
+ const commonBase = path.dirname(path.dirname(path.dirname(path.dirname(__filename))));
1635
+ const commonSourcePath = path.join(commonBase, 'common', relativePath);
1636
+
1637
+ if (await fileManager.pathExists(commonSourcePath)) {
1638
+ // This is a common/ file - needs template processing
1639
+ const fs = require('fs').promises;
1640
+ const content = await fs.readFile(commonSourcePath, 'utf8');
1641
+ const updatedContent = content.replace(/\{root\}/g, `.${packId}`);
1642
+ await fileManager.ensureDirectory(path.dirname(destPath));
1643
+ await fs.writeFile(destPath, updatedContent, 'utf8');
1644
+ spinner.text = `Restored: ${file}`;
1645
+ } else if (await fileManager.pathExists(sourcePath)) {
1646
+ // Regular file from expansion pack
1647
+ await fileManager.copyFile(sourcePath, destPath);
1648
+ spinner.text = `Restored: ${file}`;
1649
+ } else {
1650
+ console.warn(chalk.yellow(` Warning: Source file not found: ${file}`));
1651
+ }
1652
+ }
1653
+
1654
+ spinner.succeed(`${pack.name} repaired successfully!`);
1655
+
1656
+ // Show summary
1657
+ console.log(chalk.green(`\n✓ ${pack.name} repaired!`));
1658
+ if (integrity.missing.length > 0) {
1659
+ console.log(chalk.green(` Restored ${integrity.missing.length} missing files`));
1660
+ }
1661
+ if (integrity.modified.length > 0) {
1662
+ console.log(chalk.green(` Restored ${integrity.modified.length} modified files (backups created)`));
1663
+ }
1664
+
1665
+ } catch (error) {
1666
+ if (spinner) spinner.fail(`Failed to repair ${pack.name}`);
1667
+ console.error(`Error: ${error.message}`);
1668
+ }
1669
+ }
1670
+
1671
+ compareVersions(v1, v2) {
1672
+ // Simple semver comparison
1673
+ const parts1 = v1.split('.').map(Number);
1674
+ const parts2 = v2.split('.').map(Number);
1675
+
1676
+ for (let i = 0; i < 3; i++) {
1677
+ const part1 = parts1[i] || 0;
1678
+ const part2 = parts2[i] || 0;
1679
+
1680
+ if (part1 > part2) return 1;
1681
+ if (part1 < part2) return -1;
1682
+ }
1683
+
1684
+ return 0;
1685
+ }
1686
+
1687
+ async cleanupLegacyYmlFiles(installDir, spinner) {
1688
+ const glob = require('glob');
1689
+ const fs = require('fs').promises;
1690
+
1691
+ try {
1692
+ // Find all .yml files in the installation directory
1693
+ const ymlFiles = glob.sync('**/*.yml', {
1694
+ cwd: installDir,
1695
+ ignore: ['**/node_modules/**', '**/.git/**']
1696
+ });
1697
+
1698
+ let deletedCount = 0;
1699
+
1700
+ for (const ymlFile of ymlFiles) {
1701
+ // Check if corresponding .yaml file exists
1702
+ const yamlFile = ymlFile.replace(/\.yml$/, '.yaml');
1703
+ const ymlPath = path.join(installDir, ymlFile);
1704
+ const yamlPath = path.join(installDir, yamlFile);
1705
+
1706
+ if (await fileManager.pathExists(yamlPath)) {
1707
+ // .yaml counterpart exists, delete the .yml file
1708
+ await fs.unlink(ymlPath);
1709
+ deletedCount++;
1710
+ console.log(chalk.dim(` Removed legacy: ${ymlFile} (replaced by ${yamlFile})`));
1711
+ }
1712
+ }
1713
+
1714
+ if (deletedCount > 0) {
1715
+ console.log(chalk.green(`✓ Cleaned up ${deletedCount} legacy .yml files`));
1716
+ }
1717
+
1718
+ } catch (error) {
1719
+ console.warn(`Warning: Could not cleanup legacy .yml files: ${error.message}`);
1720
+ }
1721
+ }
1722
+
1723
+ async findInstallation() {
1724
+ // Look for .xiaoma-core in current directory or parent directories
1725
+ let currentDir = process.cwd();
1726
+
1727
+ while (currentDir !== path.dirname(currentDir)) {
1728
+ const bmadDir = path.join(currentDir, ".xiaoma-core");
1729
+ const manifestPath = path.join(bmadDir, "install-manifest.yaml");
1730
+
1731
+ if (await fileManager.pathExists(manifestPath)) {
1732
+ return bmadDir;
1733
+ }
1734
+
1735
+ currentDir = path.dirname(currentDir);
1736
+ }
1737
+
1738
+ // Also check if we're inside a .xiaoma-core directory
1739
+ if (path.basename(process.cwd()) === ".xiaoma-core") {
1740
+ const manifestPath = path.join(process.cwd(), "install-manifest.yaml");
1741
+ if (await fileManager.pathExists(manifestPath)) {
1742
+ return process.cwd();
1743
+ }
1744
+ }
1745
+
1746
+ return null;
1747
+ }
1748
+
1749
+ async flatten(options) {
1750
+ const { spawn } = require('child_process');
1751
+ const flattenerPath = path.join(__dirname, '..', '..', 'flattener', 'main.js');
1752
+
1753
+ const args = [];
1754
+ if (options.input) {
1755
+ args.push('--input', options.input);
1756
+ }
1757
+ if (options.output) {
1758
+ args.push('--output', options.output);
1759
+ }
1760
+
1761
+ const child = spawn('node', [flattenerPath, ...args], {
1762
+ stdio: 'inherit',
1763
+ cwd: process.cwd()
1764
+ });
1765
+
1766
+ child.on('exit', (code) => {
1767
+ process.exit(code);
1768
+ });
1769
+ }
1770
+ }
1771
+
1772
+ module.exports = new Installer();