claude-flow-novice 1.5.3 → 1.5.4

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.
@@ -0,0 +1,1896 @@
1
+ // init/index.js - Initialize Claude Code integration files
2
+ import { printSuccess, printError, printWarning, exit } from '../../utils.js';
3
+ import { existsSync } from 'fs';
4
+ import { promises as fs } from 'fs';
5
+ import { fileURLToPath } from 'url';
6
+ import { dirname, join } from 'path';
7
+ import process from 'process';
8
+ import { spawn, execSync } from 'child_process';
9
+ import { promisify } from 'util';
10
+
11
+ // Helper to replace Deno.Command
12
+ function runCommand(command, args, options = {}) {
13
+ return new Promise((resolve, reject) => {
14
+ const child = spawn(command, args, {
15
+ cwd: options.cwd,
16
+ env: { ...process.env, ...options.env },
17
+ stdio: options.stdout === 'inherit' ? 'inherit' : 'pipe',
18
+ });
19
+
20
+ let stdout = '';
21
+ let stderr = '';
22
+
23
+ if (options.stdout !== 'inherit') {
24
+ child.stdout.on('data', (data) => {
25
+ stdout += data;
26
+ });
27
+ child.stderr.on('data', (data) => {
28
+ stderr += data;
29
+ });
30
+ }
31
+
32
+ child.on('close', (code) => {
33
+ if (code === 0) {
34
+ resolve({ success: true, code, stdout, stderr });
35
+ } else {
36
+ reject(new Error(`Command failed with exit code ${code}`));
37
+ }
38
+ });
39
+
40
+ child.on('error', reject);
41
+ });
42
+ }
43
+ import { createLocalExecutable } from './executable-wrapper.js';
44
+ import { createSparcStructureManually } from './sparc-structure.js';
45
+ import { createClaudeSlashCommands } from './claude-commands/slash-commands.js';
46
+ import { createOptimizedClaudeSlashCommands } from './claude-commands/optimized-slash-commands.js';
47
+ // execSync imported above as execSyncOriginal\nconst execSync = execSyncOriginal;
48
+ import { promises as fs } from 'fs';
49
+ import { copyTemplates } from './template-copier.js';
50
+ import { copyRevisedTemplates, validateTemplatesExist } from './copy-revised-templates.js';
51
+ import {
52
+ copyAgentFiles,
53
+ createAgentDirectories,
54
+ validateAgentSystem,
55
+ copyCommandFiles,
56
+ } from './agent-copier.js';
57
+ import { showInitHelp } from './help.js';
58
+ import { batchInitCommand, batchInitFromConfig, validateBatchOptions } from './batch-init.js';
59
+ import { ValidationSystem, runFullValidation } from './validation/index.js';
60
+ import { RollbackSystem, createAtomicOperation } from './rollback/index.js';
61
+ import {
62
+ createEnhancedClaudeMd,
63
+ createEnhancedSettingsJson,
64
+ createWrapperScript,
65
+ createCommandDoc,
66
+ createHelperScript,
67
+ COMMAND_STRUCTURE,
68
+ } from './templates/enhanced-templates.js';
69
+ import { createOptimizedSparcClaudeMd } from './templates/claude-md.js';
70
+ import { getIsolatedNpxEnv } from '../../../utils/npx-isolated-cache.js';
71
+ import { updateGitignore, needsGitignoreUpdate } from './gitignore-updater.js';
72
+ import {
73
+ createFullClaudeMd,
74
+ createSparcClaudeMd,
75
+ createMinimalClaudeMd,
76
+ } from './templates/claude-md.js';
77
+ import {
78
+ createVerificationClaudeMd,
79
+ createVerificationSettingsJson,
80
+ } from './templates/verification-claude-md.js';
81
+ import { createFullMemoryBankMd, createMinimalMemoryBankMd } from './templates/memory-bank-md.js';
82
+ import {
83
+ createFullCoordinationMd,
84
+ createMinimalCoordinationMd,
85
+ } from './templates/coordination-md.js';
86
+ import { createAgentsReadme, createSessionsReadme } from './templates/readme-files.js';
87
+ import { initializeHiveMind, getHiveMindStatus, rollbackHiveMindInit } from './hive-mind-init.js';
88
+
89
+ // Get the directory path of this module for resolving template files
90
+ const __filename = fileURLToPath(import.meta.url);
91
+ const __dirname = dirname(__filename);
92
+
93
+ /**
94
+ * Read the CLAUDE.md template file
95
+ * @returns {Promise<string>} The template content
96
+ */
97
+ async function readClaudeMdTemplate() {
98
+ // In source: templates/CLAUDE.md
99
+ // In dist: the files are copied directly to init/ directory (not templates/)
100
+ const possiblePaths = [
101
+ join(__dirname, 'templates', 'CLAUDE.md'), // Source location
102
+ join(__dirname, 'CLAUDE.md'), // Dist location (files copied directly)
103
+ ];
104
+
105
+ for (const templatePath of possiblePaths) {
106
+ try {
107
+ const content = await fs.readFile(templatePath, 'utf8');
108
+ return content;
109
+ } catch (error) {
110
+ // Try next path
111
+ continue;
112
+ }
113
+ }
114
+
115
+ // Fallback to generating if template file is not found in any location
116
+ console.warn('Warning: Template file not found in any location, using generated content');
117
+ return createOptimizedSparcClaudeMd();
118
+ }
119
+
120
+ /**
121
+ * Check if Claude Code CLI is installed
122
+ */
123
+ function isClaudeCodeInstalled() {
124
+ try {
125
+ execSync('which claude', { stdio: 'ignore' });
126
+ return true;
127
+ } catch {
128
+ return false;
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Set up MCP servers in Claude Code (Legacy - replaced by bulletproof system)
134
+ */
135
+ async function setupMcpServers(dryRun = false) {
136
+ console.log('\nšŸ”Œ Setting up MCP servers for Claude Code...');
137
+
138
+ const servers = [
139
+ {
140
+ name: 'claude-flow-novice',
141
+ command: 'node dist/mcp/mcp-server-sdk.js',
142
+ description: 'Claude Flow Novice MCP server with 30 essential tools',
143
+ },
144
+ ];
145
+
146
+ for (const server of servers) {
147
+ try {
148
+ if (!dryRun) {
149
+ console.log(` šŸ”„ Adding ${server.name}...`);
150
+ execSync(`claude mcp add ${server.name} ${server.command}`, { stdio: 'inherit' });
151
+ console.log(` āœ… Added ${server.name} - ${server.description}`);
152
+ } else {
153
+ console.log(` [DRY RUN] Would add ${server.name} - ${server.description}`);
154
+ }
155
+ } catch (err) {
156
+ console.log(` āš ļø Failed to add ${server.name}: ${err.message}`);
157
+ console.log(
158
+ ` You can add it manually with: claude mcp add ${server.name} ${server.command}`,
159
+ );
160
+ }
161
+ }
162
+
163
+ if (!dryRun) {
164
+ console.log('\n šŸ“‹ Verifying MCP servers...');
165
+ try {
166
+ execSync('claude mcp list', { stdio: 'inherit' });
167
+ } catch (err) {
168
+ console.log(' āš ļø Could not verify MCP servers');
169
+ }
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Bulletproof MCP setup using the new configuration manager
175
+ */
176
+ async function setupBulletproofMcp(options = {}) {
177
+ console.log('\nšŸ›”ļø Setting up bulletproof MCP configuration...');
178
+
179
+ try {
180
+ // Import the MCP configuration manager
181
+ const { enhancedMcpInit } = await import('../../mcp/mcp-config-manager.js');
182
+
183
+ const result = await enhancedMcpInit({
184
+ verbose: options.verbose || false,
185
+ autoFix: options.autoFix !== false, // Default to true
186
+ dryRun: options.dryRun || false,
187
+ enhancedUx: true, // Enable enhanced user experience
188
+ showEducation: options.showEducation || false // Show educational content for first-time users
189
+ });
190
+
191
+ if (result.success) {
192
+ console.log('āœ… Bulletproof MCP configuration completed successfully');
193
+
194
+ // Display additional success information
195
+ if (result.details) {
196
+ console.log(` • Issues Fixed: ${result.details.issuesFixed || 0}`);
197
+ console.log(` • Health Score: ${result.details.healthScore || 'N/A'}/100`);
198
+ console.log(` • Duration: ${result.duration || 'N/A'}ms`);
199
+ }
200
+
201
+ return true;
202
+ } else {
203
+ console.log(`āš ļø MCP configuration had issues: ${result.error}`);
204
+
205
+ // Display recovery information if available
206
+ if (result.rollbackAvailable) {
207
+ console.log(' šŸ”„ Automatic rollback was performed');
208
+ }
209
+
210
+ if (result.recovery && result.recovery.recommendedActions) {
211
+ console.log('\n šŸ› ļø Recommended actions:');
212
+ result.recovery.recommendedActions.slice(0, 3).forEach((action, i) => {
213
+ console.log(` ${i + 1}. ${action}`);
214
+ });
215
+ }
216
+
217
+ return false;
218
+ }
219
+ } catch (error) {
220
+ console.log(`āš ļø Bulletproof MCP setup failed: ${error.message}`);
221
+ console.log(' This may be due to missing dependencies or system configuration.');
222
+
223
+ // Check if it's a dependency issue
224
+ if (error.message.includes('Cannot find module') || error.message.includes('import')) {
225
+ console.log(' šŸ’” Try installing dependencies: npm install');
226
+ }
227
+
228
+ console.log(' šŸ“ž Falling back to legacy MCP setup...');
229
+
230
+ // Fallback to legacy setup
231
+ await setupMcpServers(options.dryRun);
232
+ return false;
233
+ }
234
+ }
235
+
236
+ export async function initCommand(subArgs, flags) {
237
+ // Show help if requested
238
+ if (flags.help || flags.h || subArgs.includes('--help') || subArgs.includes('-h')) {
239
+ showInitHelp();
240
+ return;
241
+ }
242
+
243
+ // Check for verification flags first
244
+ const hasVerificationFlags =
245
+ subArgs.includes('--verify') || subArgs.includes('--pair') || flags.verify || flags.pair;
246
+
247
+ // Flow-nexus mode removed
248
+
249
+ // Default to enhanced Claude Flow v2 init unless other modes are specified
250
+ // Use --basic flag for old behavior, or verification flags for verification mode
251
+ if (!flags.basic && !flags.minimal && !flags.sparc && !hasVerificationFlags) {
252
+ return await enhancedClaudeFlowInit(flags, subArgs);
253
+ }
254
+
255
+ // Check for validation and rollback commands
256
+ if (subArgs.includes('--validate') || subArgs.includes('--validate-only')) {
257
+ return handleValidationCommand(subArgs, flags);
258
+ }
259
+
260
+ if (subArgs.includes('--rollback')) {
261
+ return handleRollbackCommand(subArgs, flags);
262
+ }
263
+
264
+ if (subArgs.includes('--list-backups')) {
265
+ return handleListBackups(subArgs, flags);
266
+ }
267
+
268
+ // Check for batch operations
269
+ const batchInitFlag = flags['batch-init'] || subArgs.includes('--batch-init');
270
+ const configFlag = flags.config || subArgs.includes('--config');
271
+
272
+ if (batchInitFlag || configFlag) {
273
+ return handleBatchInit(subArgs, flags);
274
+ }
275
+
276
+ // For novice package, always use enhanced initialization with agent system
277
+ const useEnhanced = true; // Always enhanced for novice users
278
+
279
+ if (useEnhanced) {
280
+ return enhancedInitCommand(subArgs, flags);
281
+ }
282
+
283
+ // Parse init options
284
+ const initForce = subArgs.includes('--force') || subArgs.includes('-f') || flags.force;
285
+ const initMinimal = subArgs.includes('--minimal') || subArgs.includes('-m') || flags.minimal;
286
+ const initSparc = flags.roo || (subArgs && subArgs.includes('--roo')); // SPARC only with --roo flag
287
+ const initDryRun = subArgs.includes('--dry-run') || subArgs.includes('-d') || flags.dryRun;
288
+ const initOptimized = initSparc && initForce; // Use optimized templates when both flags are present
289
+ const selectedModes = flags.modes ? flags.modes.split(',') : null; // Support selective mode initialization
290
+
291
+ // Check for verification and pair programming flags
292
+ const initVerify = subArgs.includes('--verify') || flags.verify;
293
+ const initPair = subArgs.includes('--pair') || flags.pair;
294
+
295
+ // Get the actual working directory (where the command was run from)
296
+ // Use PWD environment variable which preserves the original directory
297
+ const workingDir = process.env.PWD || cwd();
298
+ console.log(`šŸ“ Initializing in: ${workingDir}`);
299
+
300
+ // Change to the working directory to ensure all file operations happen there
301
+ try {
302
+ process.chdir(workingDir);
303
+ } catch (err) {
304
+ printWarning(`Could not change to directory ${workingDir}: ${err.message}`);
305
+ }
306
+
307
+ try {
308
+ printSuccess('Initializing Claude Code integration files...');
309
+
310
+ // Check if files already exist in the working directory
311
+ const files = ['CLAUDE.md', 'memory-bank.md', 'coordination.md'];
312
+ const existingFiles = [];
313
+
314
+ for (const file of files) {
315
+ try {
316
+ await fs.stat(`${workingDir}/${file}`);
317
+ existingFiles.push(file);
318
+ } catch {
319
+ // File doesn't exist, which is what we want
320
+ }
321
+ }
322
+
323
+ if (existingFiles.length > 0 && !initForce) {
324
+ printWarning(`The following files already exist: ${existingFiles.join(', ')}`);
325
+ console.log('Use --force to overwrite existing files');
326
+ return;
327
+ }
328
+
329
+ // Use template copier to copy all template files
330
+ const templateOptions = {
331
+ sparc: initSparc,
332
+ minimal: initMinimal,
333
+ optimized: initOptimized,
334
+ dryRun: initDryRun,
335
+ force: initForce,
336
+ selectedModes: selectedModes,
337
+ verify: initVerify,
338
+ pair: initPair,
339
+ };
340
+
341
+ // If verification flags are set, always use generated templates for CLAUDE.md and settings.json
342
+ if (initVerify || initPair) {
343
+ console.log(' šŸ“ Creating verification-focused configuration...');
344
+
345
+ // Create verification CLAUDE.md
346
+ if (!initDryRun) {
347
+ const { createVerificationClaudeMd, createVerificationSettingsJson } = await import(
348
+ './templates/verification-claude-md.js'
349
+ );
350
+ await fs.writeFile(`${workingDir}/CLAUDE.md`, createVerificationClaudeMd(), 'utf8');
351
+
352
+ // Create .claude directory and settings
353
+ await fs.mkdir(`${workingDir}/.claude`, { recursive: true });
354
+ await fs.writeFile(
355
+ `${workingDir}/.claude/settings.json`,
356
+ createVerificationSettingsJson(),
357
+ 'utf8',
358
+ );
359
+ console.log(' āœ… Created verification-focused CLAUDE.md and settings.json');
360
+ } else {
361
+ console.log(' [DRY RUN] Would create verification-focused CLAUDE.md and settings.json');
362
+ }
363
+
364
+ // Copy other template files from repository if available
365
+ const validation = validateTemplatesExist();
366
+ if (validation.valid) {
367
+ const revisedResults = await copyRevisedTemplates(workingDir, {
368
+ force: initForce,
369
+ dryRun: initDryRun,
370
+ verbose: false,
371
+ sparc: initSparc,
372
+ });
373
+ }
374
+
375
+ // Also create standard memory and coordination files
376
+ const copyResults = await copyTemplates(workingDir, {
377
+ ...templateOptions,
378
+ skipClaudeMd: true, // Don't overwrite the verification CLAUDE.md
379
+ skipSettings: true, // Don't overwrite the verification settings.json
380
+ });
381
+ } else {
382
+ // Standard template copying logic
383
+ const validation = validateTemplatesExist();
384
+ if (validation.valid) {
385
+ console.log(' šŸ“ Copying revised template files...');
386
+ const revisedResults = await copyRevisedTemplates(workingDir, {
387
+ force: initForce,
388
+ dryRun: initDryRun,
389
+ verbose: true,
390
+ sparc: initSparc,
391
+ });
392
+
393
+ if (revisedResults.success) {
394
+ console.log(` āœ… Copied ${revisedResults.copiedFiles.length} template files`);
395
+ if (revisedResults.skippedFiles.length > 0) {
396
+ console.log(` ā­ļø Skipped ${revisedResults.skippedFiles.length} existing files`);
397
+ }
398
+ } else {
399
+ console.log(' āš ļø Some template files could not be copied:');
400
+ revisedResults.errors.forEach((err) => console.log(` - ${err}`));
401
+ }
402
+ } else {
403
+ // Fall back to generated templates
404
+ console.log(' āš ļø Revised templates not available, using generated templates');
405
+ const copyResults = await copyTemplates(workingDir, templateOptions);
406
+
407
+ if (!copyResults.success) {
408
+ printError('Failed to copy templates:');
409
+ copyResults.errors.forEach((err) => console.log(` āŒ ${err}`));
410
+ return;
411
+ }
412
+ }
413
+ }
414
+
415
+ // Agent setup moved to end of function where execution is guaranteed
416
+
417
+ // Directory structure is created by template copier
418
+
419
+ // SPARC files are created by template copier when --sparc flag is used
420
+
421
+ // Memory README files and persistence database are created by template copier
422
+
423
+ // Create local claude-flow-novice executable wrapper
424
+ if (!initDryRun) {
425
+ await createLocalExecutable(workingDir);
426
+ } else {
427
+ console.log(' [DRY RUN] Would create local claude-flow-novice executable wrapper');
428
+ }
429
+
430
+ // SPARC initialization
431
+ if (initSparc) {
432
+ console.log('\nšŸš€ Initializing SPARC development environment...');
433
+
434
+ if (initDryRun) {
435
+ console.log(' [DRY RUN] Would run: npx -y create-sparc init --force');
436
+ console.log(' [DRY RUN] Would create SPARC environment with all modes');
437
+ console.log(
438
+ ' [DRY RUN] Would create Claude slash commands' +
439
+ (initOptimized ? ' (Batchtools-optimized)' : ''),
440
+ );
441
+ if (selectedModes) {
442
+ console.log(
443
+ ` [DRY RUN] Would create commands for selected modes: ${selectedModes.join(', ')}`,
444
+ );
445
+ }
446
+ } else {
447
+ // Check if create-sparc exists and run it
448
+ let sparcInitialized = false;
449
+ try {
450
+ // Use isolated NPX cache to prevent concurrent conflicts
451
+ console.log(' šŸ”„ Running: npx -y create-sparc init --force');
452
+ const createSparcResult = await runCommand(
453
+ 'npx',
454
+ ['-y', 'create-sparc', 'init', '--force'],
455
+ {
456
+ cwd: workingDir,
457
+ stdout: 'inherit',
458
+ stderr: 'inherit',
459
+ env: getIsolatedNpxEnv({
460
+ PWD: workingDir,
461
+ }),
462
+ },
463
+ );
464
+
465
+ if (createSparcResult.success) {
466
+ console.log(' āœ… SPARC environment initialized successfully');
467
+ sparcInitialized = true;
468
+ } else {
469
+ printWarning('create-sparc failed, creating basic SPARC structure manually...');
470
+
471
+ // Fallback: create basic SPARC structure manually
472
+ await createSparcStructureManually();
473
+ sparcInitialized = true; // Manual creation still counts as initialized
474
+ }
475
+ } catch (err) {
476
+ printWarning('create-sparc not available, creating basic SPARC structure manually...');
477
+
478
+ // Fallback: create basic SPARC structure manually
479
+ await createSparcStructureManually();
480
+ sparcInitialized = true; // Manual creation still counts as initialized
481
+ }
482
+
483
+ // Always create Claude slash commands after SPARC initialization
484
+ if (sparcInitialized) {
485
+ try {
486
+ if (initOptimized) {
487
+ await createOptimizedClaudeSlashCommands(workingDir, selectedModes);
488
+ } else {
489
+ await createClaudeSlashCommands(workingDir);
490
+ }
491
+ } catch (err) {
492
+ // Legacy slash command creation - silently skip if it fails
493
+ // SPARC slash commands are already created successfully above
494
+ }
495
+ }
496
+ }
497
+ }
498
+
499
+ if (initDryRun) {
500
+ printSuccess("šŸ” Dry run completed! Here's what would be created:");
501
+ console.log('\nšŸ“‹ Summary of planned initialization:');
502
+ console.log(
503
+ ` • Configuration: ${initOptimized ? 'Batchtools-optimized SPARC' : initSparc ? 'SPARC-enhanced' : 'Standard'}`,
504
+ );
505
+ console.log(
506
+ ` • Template type: ${initOptimized ? 'Optimized for parallel processing' : 'Standard'}`,
507
+ );
508
+ console.log(' • Core files: CLAUDE.md, memory-bank.md, coordination.md');
509
+ console.log(' • Directory structure: memory/, coordination/, .claude/');
510
+ console.log(' • Local executable: ./claude-flow');
511
+ if (initSparc) {
512
+ console.log(
513
+ ` • Claude Code slash commands: ${selectedModes ? selectedModes.length : 'All'} SPARC mode commands`,
514
+ );
515
+ console.log(' • SPARC environment with all development modes');
516
+ }
517
+ if (initOptimized) {
518
+ console.log(' • Batchtools optimization: Enabled for parallel processing');
519
+ console.log(' • Performance enhancements: Smart batching, concurrent operations');
520
+ }
521
+ console.log('\nšŸš€ To proceed with initialization, run the same command without --dry-run');
522
+ } else {
523
+ printSuccess('šŸŽ‰ Claude Code integration files initialized successfully!');
524
+
525
+ if (initOptimized) {
526
+ console.log('\n⚔ Batchtools Optimization Enabled!');
527
+ console.log(' • Parallel processing capabilities activated');
528
+ console.log(' • Performance improvements: 250-500% faster operations');
529
+ console.log(' • Smart batching and concurrent operations available');
530
+ }
531
+
532
+ console.log('\nšŸ“‹ What was created:');
533
+ console.log(
534
+ ` āœ… CLAUDE.md (${initOptimized ? 'Batchtools-optimized' : initSparc ? 'SPARC-enhanced' : 'Standard configuration'})`,
535
+ );
536
+ console.log(
537
+ ` āœ… memory-bank.md (${initOptimized ? 'With parallel processing' : 'Standard memory system'})`,
538
+ );
539
+ console.log(
540
+ ` āœ… coordination.md (${initOptimized ? 'Enhanced with batchtools' : 'Standard coordination'})`,
541
+ );
542
+ console.log(' āœ… Directory structure with memory/ and coordination/');
543
+ console.log(' āœ… Local executable at ./claude-flow');
544
+ console.log(' āœ… Persistence database at memory/claude-flow-data.json');
545
+ console.log(' āœ… Agent system with 64 specialized agents in .claude/agents/');
546
+
547
+ if (initSparc) {
548
+ const modeCount = selectedModes ? selectedModes.length : '20+';
549
+ console.log(` āœ… Claude Code slash commands (${modeCount} SPARC modes)`);
550
+ console.log(' āœ… Complete SPARC development environment');
551
+ }
552
+
553
+ console.log('\nšŸš€ Next steps:');
554
+ console.log('1. Review and customize the generated files for your project');
555
+ console.log("2. Run './claude-flow-novice start' to begin the orchestration system");
556
+ console.log("3. Use './claude-flow' instead of 'npx claude-flow' for all commands");
557
+ console.log("4. Use 'claude --dangerously-skip-permissions' for unattended operation");
558
+
559
+ if (initSparc) {
560
+ console.log(
561
+ '5. Use Claude Code slash commands: /sparc, /sparc-architect, /sparc-tdd, etc.',
562
+ );
563
+ console.log("6. Explore SPARC modes with './claude-flow-novice sparc modes'");
564
+ console.log('7. Try TDD workflow with \'./claude-flow-novice sparc tdd "your task"\'');
565
+
566
+ if (initOptimized) {
567
+ console.log('8. Use batchtools commands: /batchtools, /performance for optimization');
568
+ console.log('9. Enable parallel processing with --parallel flags');
569
+ console.log("10. Monitor performance with './claude-flow-novice performance monitor'");
570
+ }
571
+ }
572
+
573
+ // Update .gitignore
574
+ const gitignoreResult = await updateGitignore(workingDir, initForce, initDryRun);
575
+ if (gitignoreResult.success) {
576
+ if (!initDryRun) {
577
+ console.log(` āœ… ${gitignoreResult.message}`);
578
+ } else {
579
+ console.log(` ${gitignoreResult.message}`);
580
+ }
581
+ } else {
582
+ console.log(` āš ļø ${gitignoreResult.message}`);
583
+ }
584
+
585
+ console.log('\nšŸ’” Tips:');
586
+ console.log(" • Type '/' in Claude Code to see all available slash commands");
587
+ console.log(" • Use './claude-flow-novice status' to check system health");
588
+ console.log(" • Store important context with './claude-flow-novice memory store'");
589
+
590
+ if (initOptimized) {
591
+ console.log(' • Use --parallel flags for concurrent operations');
592
+ console.log(' • Enable batch processing for multiple related tasks');
593
+ console.log(' • Monitor performance with real-time metrics');
594
+ }
595
+
596
+ // Initialize hive-mind system for standard init
597
+ console.log('\n🧠 Initializing basic hive-mind system...');
598
+ try {
599
+ const hiveMindOptions = {
600
+ config: {
601
+ integration: {
602
+ claudeCode: { enabled: isClaudeCodeInstalled() },
603
+ mcpTools: { enabled: true },
604
+ },
605
+ monitoring: { enabled: false }, // Basic setup for standard init
606
+ },
607
+ };
608
+
609
+ const hiveMindResult = await initializeHiveMind(workingDir, hiveMindOptions, false);
610
+
611
+ if (hiveMindResult.success) {
612
+ console.log(' āœ… Basic hive-mind system initialized');
613
+ console.log(' šŸ’” Use "npx claude-flow-novice hive-mind" for advanced features');
614
+ } else {
615
+ console.log(` āš ļø Hive-mind setup skipped: ${hiveMindResult.error}`);
616
+ }
617
+ } catch (err) {
618
+ console.log(` āš ļø Hive-mind setup skipped: ${err.message}`);
619
+ }
620
+
621
+ // Check for Claude Code and set up MCP servers (always enabled by default)
622
+ if (!initDryRun && isClaudeCodeInstalled()) {
623
+ console.log('\nšŸ” Claude Code CLI detected!');
624
+ const skipMcp = subArgs && subArgs.includes && subArgs.includes('--skip-mcp');
625
+
626
+ if (!skipMcp) {
627
+ // Use bulletproof MCP setup instead of legacy
628
+ const mcpSuccess = await setupBulletproofMcp({
629
+ verbose: false,
630
+ autoFix: true,
631
+ dryRun: initDryRun
632
+ });
633
+
634
+ if (!mcpSuccess) {
635
+ console.log(' šŸ’” If you encounter issues, run: claude mcp remove claude-flow-novice -s local');
636
+ }
637
+ } else {
638
+ console.log(' ā„¹ļø Skipping MCP setup (--skip-mcp flag used)');
639
+ }
640
+ } else if (!initDryRun && !isClaudeCodeInstalled()) {
641
+ console.log('\nāš ļø Claude Code CLI not detected!');
642
+ console.log(' šŸ“„ Install with: npm install -g @anthropic-ai/claude-code');
643
+ console.log(' šŸ“‹ Then add MCP servers manually with:');
644
+ console.log(' claude mcp add claude-flow-novice claude-flow-novice mcp start');
645
+ console.log(' claude mcp add ruv-swarm npx ruv-swarm mcp start');
646
+ // Flow-nexus integration removed
647
+ }
648
+ }
649
+ } catch (err) {
650
+ printError(`Failed to initialize files: ${err.message}`);
651
+ }
652
+ }
653
+
654
+ // Handle batch initialization
655
+ async function handleBatchInit(subArgs, flags) {
656
+ try {
657
+ // Options parsing from flags and subArgs
658
+ const options = {
659
+ parallel: !flags['no-parallel'] && flags.parallel !== false,
660
+ sparc: flags.sparc || flags.s,
661
+ minimal: flags.minimal || flags.m,
662
+ force: flags.force || flags.f,
663
+ maxConcurrency: flags['max-concurrent'] || 5,
664
+ progressTracking: true,
665
+ template: flags.template,
666
+ environments: flags.environments
667
+ ? flags.environments.split(',').map((env) => env.trim())
668
+ : ['dev'],
669
+ };
670
+
671
+ // Validate options
672
+ const validationErrors = validateBatchOptions(options);
673
+ if (validationErrors.length > 0) {
674
+ printError('Batch options validation failed:');
675
+ validationErrors.forEach((error) => console.error(` - ${error}`));
676
+ return;
677
+ }
678
+
679
+ // Config file mode
680
+ if (flags.config) {
681
+ const configFile = flags.config;
682
+ printSuccess(`Loading batch configuration from: ${configFile}`);
683
+ const results = await batchInitFromConfig(configFile, options);
684
+ if (results) {
685
+ printSuccess('Batch initialization from config completed');
686
+ }
687
+ return;
688
+ }
689
+
690
+ // Batch init mode
691
+ if (flags['batch-init']) {
692
+ const projectsString = flags['batch-init'];
693
+ const projects = projectsString.split(',').map((project) => project.trim());
694
+
695
+ if (projects.length === 0) {
696
+ printError('No projects specified for batch initialization');
697
+ return;
698
+ }
699
+
700
+ printSuccess(`Initializing ${projects.length} projects in batch mode`);
701
+ const results = await batchInitCommand(projects, options);
702
+
703
+ if (results) {
704
+ const successful = results.filter((r) => r.success).length;
705
+ const failed = results.filter((r) => !r.success).length;
706
+
707
+ if (failed === 0) {
708
+ printSuccess(`All ${successful} projects initialized successfully`);
709
+ } else {
710
+ printWarning(`${successful} projects succeeded, ${failed} failed`);
711
+ }
712
+ }
713
+ return;
714
+ }
715
+
716
+ printError('No batch operation specified. Use --batch-init <projects> or --config <file>');
717
+ } catch (err) {
718
+ printError(`Batch initialization failed: ${err.message}`);
719
+ }
720
+ }
721
+
722
+ /**
723
+ * Enhanced initialization command with validation and rollback
724
+ */
725
+ async function enhancedInitCommand(subArgs, flags) {
726
+ console.log('šŸ›”ļø Starting enhanced initialization with validation and rollback...');
727
+
728
+ // Store parameters to avoid scope issues in async context
729
+ const args = subArgs || [];
730
+ const options = flags || {};
731
+
732
+ // Get the working directory
733
+ const workingDir = process.env.PWD || process.cwd();
734
+
735
+ // Initialize systems
736
+ const rollbackSystem = new RollbackSystem(workingDir);
737
+ const validationSystem = new ValidationSystem(workingDir);
738
+
739
+ let atomicOp = null;
740
+
741
+ try {
742
+ // Parse options
743
+ const initOptions = {
744
+ force: args.includes('--force') || args.includes('-f') || options.force,
745
+ minimal: args.includes('--minimal') || args.includes('-m') || options.minimal,
746
+ sparc: args.includes('--sparc') || args.includes('-s') || options.sparc,
747
+ skipPreValidation: args.includes('--skip-pre-validation'),
748
+ skipBackup: args.includes('--skip-backup'),
749
+ validateOnly: args.includes('--validate-only'),
750
+ };
751
+
752
+ // Phase 1: Pre-initialization validation
753
+ if (!initOptions.skipPreValidation) {
754
+ console.log('\nšŸ” Phase 1: Pre-initialization validation...');
755
+ const preValidation = await validationSystem.validatePreInit(initOptions);
756
+
757
+ if (!preValidation.success) {
758
+ printError('Pre-initialization validation failed:');
759
+ preValidation.errors.forEach((error) => console.error(` āŒ ${error}`));
760
+ return;
761
+ }
762
+
763
+ if (preValidation.warnings.length > 0) {
764
+ printWarning('Pre-initialization warnings:');
765
+ preValidation.warnings.forEach((warning) => console.warn(` āš ļø ${warning}`));
766
+ }
767
+
768
+ printSuccess('Pre-initialization validation passed');
769
+ }
770
+
771
+ // Stop here if validation-only mode
772
+ if (options.validateOnly) {
773
+ console.log('\nāœ… Validation-only mode completed');
774
+ return;
775
+ }
776
+
777
+ // Phase 2: Create backup
778
+ if (!options.skipBackup) {
779
+ console.log('\nšŸ’¾ Phase 2: Creating backup...');
780
+ const backupResult = await rollbackSystem.createPreInitBackup();
781
+
782
+ if (!backupResult.success) {
783
+ printError('Backup creation failed:');
784
+ backupResult.errors.forEach((error) => console.error(` āŒ ${error}`));
785
+ return;
786
+ }
787
+ }
788
+
789
+ // Phase 3: Initialize with atomic operations
790
+ console.log('\nšŸ”§ Phase 3: Atomic initialization...');
791
+ atomicOp = createAtomicOperation(rollbackSystem, 'enhanced-init');
792
+
793
+ const atomicBegin = await atomicOp.begin();
794
+ if (!atomicBegin) {
795
+ printError('Failed to begin atomic operation');
796
+ return;
797
+ }
798
+
799
+ // Perform initialization steps with checkpoints
800
+ await performInitializationWithCheckpoints(rollbackSystem, options, workingDir, dryRun);
801
+
802
+ // Phase 4: Post-initialization validation
803
+ console.log('\nāœ… Phase 4: Post-initialization validation...');
804
+ const postValidation = await validationSystem.validatePostInit();
805
+
806
+ if (!postValidation.success) {
807
+ printError('Post-initialization validation failed:');
808
+ postValidation.errors.forEach((error) => console.error(` āŒ ${error}`));
809
+
810
+ // Attempt automatic rollback
811
+ console.log('\nšŸ”„ Attempting automatic rollback...');
812
+ await atomicOp.rollback();
813
+ printWarning('Initialization rolled back due to validation failure');
814
+ return;
815
+ }
816
+
817
+ // Phase 5: Configuration validation
818
+ console.log('\nšŸ”§ Phase 5: Configuration validation...');
819
+ const configValidation = await validationSystem.validateConfiguration();
820
+
821
+ if (configValidation.warnings.length > 0) {
822
+ printWarning('Configuration warnings:');
823
+ configValidation.warnings.forEach((warning) => console.warn(` āš ļø ${warning}`));
824
+ }
825
+
826
+ // Phase 6: Health checks
827
+ console.log('\nšŸ„ Phase 6: System health checks...');
828
+ const healthChecks = await validationSystem.runHealthChecks();
829
+
830
+ if (healthChecks.warnings.length > 0) {
831
+ printWarning('Health check warnings:');
832
+ healthChecks.warnings.forEach((warning) => console.warn(` āš ļø ${warning}`));
833
+ }
834
+
835
+ // Commit atomic operation
836
+ await atomicOp.commit();
837
+
838
+ // Generate and display validation report
839
+ const fullValidation = await runFullValidation(workingDir, {
840
+ postInit: true,
841
+ skipPreInit: options.skipPreValidation,
842
+ });
843
+
844
+ console.log('\nšŸ“Š Validation Report:');
845
+ console.log(fullValidation.report);
846
+
847
+ printSuccess('šŸŽ‰ Enhanced initialization completed successfully!');
848
+ console.log('\n✨ Your SPARC environment is fully validated and ready to use');
849
+ } catch (error) {
850
+ printError(`Enhanced initialization failed: ${error.message}`);
851
+
852
+ // Attempt rollback if atomic operation is active
853
+ if (atomicOp && !atomicOp.completed) {
854
+ console.log('\nšŸ”„ Performing emergency rollback...');
855
+ try {
856
+ await atomicOp.rollback();
857
+ printWarning('Emergency rollback completed');
858
+ } catch (rollbackError) {
859
+ printError(`Rollback also failed: ${rollbackError.message}`);
860
+ }
861
+ }
862
+ }
863
+ }
864
+
865
+ /**
866
+ * Handle validation commands
867
+ */
868
+ async function handleValidationCommand(subArgs, flags) {
869
+ const workingDir = process.env.PWD || process.cwd();
870
+
871
+ console.log('šŸ” Running validation checks...');
872
+
873
+ const options = {
874
+ skipPreInit: subArgs.includes('--skip-pre-init'),
875
+ skipConfig: subArgs.includes('--skip-config'),
876
+ skipModeTest: subArgs.includes('--skip-mode-test'),
877
+ postInit: !subArgs.includes('--pre-init-only'),
878
+ };
879
+
880
+ try {
881
+ const validationResults = await runFullValidation(workingDir, options);
882
+
883
+ console.log('\nšŸ“Š Validation Results:');
884
+ console.log(validationResults.report);
885
+
886
+ if (validationResults.success) {
887
+ printSuccess('āœ… All validation checks passed');
888
+ } else {
889
+ printError('āŒ Some validation checks failed');
890
+ process.exit(1);
891
+ }
892
+ } catch (error) {
893
+ printError(`Validation failed: ${error.message}`);
894
+ process.exit(1);
895
+ }
896
+ }
897
+
898
+ /**
899
+ * Handle rollback commands
900
+ */
901
+ async function handleRollbackCommand(subArgs, flags) {
902
+ const workingDir = process.env.PWD || process.cwd();
903
+ const rollbackSystem = new RollbackSystem(workingDir);
904
+
905
+ try {
906
+ // Check for specific rollback options
907
+ if (subArgs.includes('--full')) {
908
+ console.log('šŸ”„ Performing full rollback...');
909
+ const result = await rollbackSystem.performFullRollback();
910
+
911
+ if (result.success) {
912
+ printSuccess('Full rollback completed successfully');
913
+ } else {
914
+ printError('Full rollback failed:');
915
+ result.errors.forEach((error) => console.error(` āŒ ${error}`));
916
+ }
917
+ } else if (subArgs.includes('--partial')) {
918
+ const phaseIndex = subArgs.findIndex((arg) => arg === '--phase');
919
+ if (phaseIndex !== -1 && subArgs[phaseIndex + 1]) {
920
+ const phase = subArgs[phaseIndex + 1];
921
+ console.log(`šŸ”„ Performing partial rollback for phase: ${phase}`);
922
+
923
+ const result = await rollbackSystem.performPartialRollback(phase);
924
+
925
+ if (result.success) {
926
+ printSuccess(`Partial rollback completed for phase: ${phase}`);
927
+ } else {
928
+ printError(`Partial rollback failed for phase: ${phase}`);
929
+ result.errors.forEach((error) => console.error(` āŒ ${error}`));
930
+ }
931
+ } else {
932
+ printError('Partial rollback requires --phase <phase-name>');
933
+ }
934
+ } else {
935
+ // Interactive rollback point selection
936
+ const rollbackPoints = await rollbackSystem.listRollbackPoints();
937
+
938
+ if (rollbackPoints.rollbackPoints.length === 0) {
939
+ printWarning('No rollback points available');
940
+ return;
941
+ }
942
+
943
+ console.log('\nšŸ“‹ Available rollback points:');
944
+ rollbackPoints.rollbackPoints.forEach((point, index) => {
945
+ const date = new Date(point.timestamp).toLocaleString();
946
+ console.log(` ${index + 1}. ${point.type} - ${date}`);
947
+ });
948
+
949
+ // For now, rollback to the most recent point
950
+ const latest = rollbackPoints.rollbackPoints[0];
951
+ if (latest) {
952
+ console.log(
953
+ `\nšŸ”„ Rolling back to: ${latest.type} (${new Date(latest.timestamp).toLocaleString()})`,
954
+ );
955
+ const result = await rollbackSystem.performFullRollback(latest.backupId);
956
+
957
+ if (result.success) {
958
+ printSuccess('Rollback completed successfully');
959
+ } else {
960
+ printError('Rollback failed');
961
+ }
962
+ }
963
+ }
964
+ } catch (error) {
965
+ printError(`Rollback operation failed: ${error.message}`);
966
+ }
967
+ }
968
+
969
+ /**
970
+ * Handle list backups command
971
+ */
972
+ async function handleListBackups(subArgs, flags) {
973
+ const workingDir = process.env.PWD || process.cwd();
974
+ const rollbackSystem = new RollbackSystem(workingDir);
975
+
976
+ try {
977
+ const rollbackPoints = await rollbackSystem.listRollbackPoints();
978
+
979
+ console.log('\nšŸ“‹ Rollback Points and Backups:');
980
+
981
+ if (rollbackPoints.rollbackPoints.length === 0) {
982
+ console.log(' No rollback points available');
983
+ } else {
984
+ console.log('\nšŸ”„ Rollback Points:');
985
+ rollbackPoints.rollbackPoints.forEach((point, index) => {
986
+ const date = new Date(point.timestamp).toLocaleString();
987
+ console.log(` ${index + 1}. ${point.type} - ${date} (${point.backupId || 'No backup'})`);
988
+ });
989
+ }
990
+
991
+ if (rollbackPoints.checkpoints.length > 0) {
992
+ console.log('\nšŸ“ Checkpoints:');
993
+ rollbackPoints.checkpoints.slice(-5).forEach((checkpoint, index) => {
994
+ const date = new Date(checkpoint.timestamp).toLocaleString();
995
+ console.log(` ${index + 1}. ${checkpoint.phase} - ${date} (${checkpoint.status})`);
996
+ });
997
+ }
998
+ } catch (error) {
999
+ printError(`Failed to list backups: ${error.message}`);
1000
+ }
1001
+ }
1002
+
1003
+ /**
1004
+ * Perform initialization with checkpoints
1005
+ */
1006
+ async function performInitializationWithCheckpoints(
1007
+ rollbackSystem,
1008
+ options,
1009
+ workingDir,
1010
+ dryRun = false,
1011
+ ) {
1012
+ const phases = [
1013
+ { name: 'file-creation', action: () => createInitialFiles(options, workingDir, dryRun) },
1014
+ { name: 'directory-structure', action: () => createDirectoryStructure(workingDir, dryRun) },
1015
+ { name: 'memory-setup', action: () => setupMemorySystem(workingDir, dryRun) },
1016
+ { name: 'agent-system', action: () => setupAgentSystem(workingDir, dryRun, options) },
1017
+ { name: 'mcp-config', action: () => setupMcpConfiguration(workingDir, dryRun) },
1018
+ { name: 'hooks-system', action: () => setupHooksSystem(workingDir, dryRun) },
1019
+ { name: 'coordination-setup', action: () => setupCoordinationSystem(workingDir, dryRun) },
1020
+ { name: 'executable-creation', action: () => createLocalExecutable(workingDir, dryRun) },
1021
+ ];
1022
+
1023
+ if (options.sparc) {
1024
+ phases.push(
1025
+ { name: 'sparc-init', action: () => createSparcStructureManually() },
1026
+ { name: 'claude-commands', action: () => createClaudeSlashCommands(workingDir) },
1027
+ );
1028
+ }
1029
+
1030
+ for (const phase of phases) {
1031
+ console.log(` šŸ”§ ${phase.name}...`);
1032
+
1033
+ // Create checkpoint before phase
1034
+ await rollbackSystem.createCheckpoint(phase.name, {
1035
+ timestamp: Date.now(),
1036
+ phase: phase.name,
1037
+ });
1038
+
1039
+ try {
1040
+ await phase.action();
1041
+ console.log(` āœ… ${phase.name} completed`);
1042
+ } catch (error) {
1043
+ console.error(` āŒ ${phase.name} failed: ${error.message}`);
1044
+ throw error;
1045
+ }
1046
+ }
1047
+ }
1048
+
1049
+ // Helper functions for atomic initialization
1050
+ async function createInitialFiles(options, workingDir, dryRun = false) {
1051
+ if (!dryRun) {
1052
+ const claudeMd = options.sparc
1053
+ ? createSparcClaudeMd()
1054
+ : options.minimal
1055
+ ? createMinimalClaudeMd()
1056
+ : createFullClaudeMd();
1057
+ await fs.writeFile(`${workingDir}/CLAUDE.md`, claudeMd, 'utf8');
1058
+
1059
+ const memoryBankMd = options.minimal ? createMinimalMemoryBankMd() : createFullMemoryBankMd();
1060
+ await fs.writeFile(`${workingDir}/memory-bank.md`, memoryBankMd, 'utf8');
1061
+
1062
+ const coordinationMd = options.minimal
1063
+ ? createMinimalCoordinationMd()
1064
+ : createFullCoordinationMd();
1065
+ await fs.writeFile(`${workingDir}/coordination.md`, coordinationMd, 'utf8');
1066
+ }
1067
+ }
1068
+
1069
+ async function createDirectoryStructure(workingDir, dryRun = false) {
1070
+ const directories = [
1071
+ 'memory',
1072
+ 'memory/agents',
1073
+ 'memory/sessions',
1074
+ 'coordination',
1075
+ 'coordination/memory_bank',
1076
+ 'coordination/subtasks',
1077
+ 'coordination/orchestration',
1078
+ '.claude',
1079
+ '.claude/commands',
1080
+ '.claude/logs',
1081
+ ];
1082
+
1083
+ if (!dryRun) {
1084
+ for (const dir of directories) {
1085
+ await fs.mkdir(`${workingDir}/${dir}`, { recursive: true });
1086
+ }
1087
+ }
1088
+ }
1089
+
1090
+ async function setupMemorySystem(workingDir, dryRun = false) {
1091
+ if (!dryRun) {
1092
+ const initialData = { agents: [], tasks: [], lastUpdated: Date.now() };
1093
+ await fs.writeFile(
1094
+ `${workingDir}/memory/claude-flow-data.json`,
1095
+ JSON.stringify(initialData, null, 2),
1096
+ 'utf8',
1097
+ );
1098
+
1099
+ await fs.writeFile(`${workingDir}/memory/agents/README.md`, createAgentsReadme(), 'utf8');
1100
+ await fs.writeFile(`${workingDir}/memory/sessions/README.md`, createSessionsReadme(), 'utf8');
1101
+ }
1102
+ }
1103
+
1104
+ async function setupAgentSystem(workingDir, dryRun = false, options = {}) {
1105
+ if (!dryRun) {
1106
+ console.log('šŸ¤– Setting up agent system...');
1107
+
1108
+ // Create agent directories
1109
+ await createAgentDirectories(workingDir, dryRun);
1110
+
1111
+ // Copy all agent files (80+ agents)
1112
+ const agentResult = await copyAgentFiles(workingDir, {
1113
+ force: options.force || false,
1114
+ dryRun: dryRun,
1115
+ });
1116
+
1117
+ if (agentResult.success) {
1118
+ await validateAgentSystem(workingDir);
1119
+
1120
+ // Copy command files
1121
+ const commandResult = await copyCommandFiles(workingDir, {
1122
+ force: options.force || false,
1123
+ dryRun: dryRun,
1124
+ });
1125
+
1126
+ if (commandResult.success) {
1127
+ console.log(' āœ… Agent system setup complete with 80+ specialized agents');
1128
+ } else {
1129
+ console.log(' āš ļø Command system setup failed:', commandResult.error);
1130
+ }
1131
+ } else {
1132
+ console.log(' āš ļø Agent system setup failed:', agentResult.error);
1133
+ }
1134
+ }
1135
+ }
1136
+
1137
+ async function setupMcpConfiguration(workingDir, dryRun = false) {
1138
+ if (!dryRun) {
1139
+ console.log('šŸ”Œ Setting up MCP configuration...');
1140
+
1141
+ const mcpConfig = {
1142
+ "mcpServers": {
1143
+ "claude-flow-novice": {
1144
+ "command": "npx",
1145
+ "args": ["claude-flow-novice", "mcp", "start"],
1146
+ "env": {
1147
+ "CLAUDE_FLOW_NOVICE_MODE": "novice",
1148
+ "CLAUDE_FLOW_NOVICE_SIMPLIFIED": "true"
1149
+ }
1150
+ }
1151
+ }
1152
+ };
1153
+
1154
+ await fs.writeFile(
1155
+ `${workingDir}/.mcp.json`,
1156
+ JSON.stringify(mcpConfig, null, 2),
1157
+ 'utf8'
1158
+ );
1159
+ console.log(' āœ… Created .mcp.json configuration');
1160
+ }
1161
+ }
1162
+
1163
+ async function setupHooksSystem(workingDir, dryRun = false) {
1164
+ if (!dryRun) {
1165
+ console.log('šŸŖ Setting up hooks system...');
1166
+
1167
+ // Create .claude/settings.json with hooks configuration
1168
+ const settingsConfig = {
1169
+ "hooks": {
1170
+ "pre-tool": {
1171
+ "command": "npx claude-flow-novice hooks pre-task --description \"{{description}}\"",
1172
+ "enabled": true
1173
+ },
1174
+ "post-tool": {
1175
+ "command": "npx claude-flow-novice hooks post-task --task-id \"{{taskId}}\"",
1176
+ "enabled": true
1177
+ },
1178
+ "pre-edit": {
1179
+ "command": "npx claude-flow-novice hooks pre-edit --file \"{{file}}\"",
1180
+ "enabled": true
1181
+ },
1182
+ "post-edit": {
1183
+ "command": "npx claude-flow-novice hooks post-edit --file \"{{file}}\" --memory-key \"swarm/{{agent}}/{{step}}\"",
1184
+ "enabled": true
1185
+ }
1186
+ },
1187
+ "coordination": {
1188
+ "autoSpawn": true,
1189
+ "memoryPersistence": true,
1190
+ "swarmOrchestration": true
1191
+ }
1192
+ };
1193
+
1194
+ await fs.writeFile(
1195
+ `${workingDir}/.claude/settings.json`,
1196
+ JSON.stringify(settingsConfig, null, 2),
1197
+ 'utf8'
1198
+ );
1199
+ console.log(' āœ… Created hooks configuration');
1200
+ }
1201
+ }
1202
+
1203
+ async function setupCoordinationSystem(workingDir, dryRun = false) {
1204
+ // Coordination system is already set up by createDirectoryStructure
1205
+ // This is a placeholder for future coordination setup logic
1206
+ }
1207
+
1208
+ /**
1209
+ * Setup monitoring and telemetry for token tracking
1210
+ */
1211
+ async function setupMonitoring(workingDir) {
1212
+ console.log(' šŸ“ˆ Configuring token usage tracking...');
1213
+
1214
+ const fs = await import('fs/promises');
1215
+ const path = await import('path');
1216
+
1217
+ try {
1218
+ // Create .claude-flow-novice directory for tracking data
1219
+ const trackingDir = path.join(workingDir, '.claude-flow');
1220
+ await fs.mkdir(trackingDir, { recursive: true });
1221
+
1222
+ // Create initial token usage file
1223
+ const tokenUsageFile = path.join(trackingDir, 'token-usage.json');
1224
+ const initialData = {
1225
+ total: 0,
1226
+ input: 0,
1227
+ output: 0,
1228
+ byAgent: {},
1229
+ lastUpdated: new Date().toISOString(),
1230
+ };
1231
+
1232
+ await fs.writeFile(tokenUsageFile, JSON.stringify(initialData, null, 2));
1233
+ printSuccess(' āœ“ Created token usage tracking file');
1234
+
1235
+ // Add telemetry configuration to .claude/settings.json if it exists
1236
+ const settingsPath = path.join(workingDir, '.claude', 'settings.json');
1237
+ try {
1238
+ const settingsContent = await fs.readFile(settingsPath, 'utf8');
1239
+ const settings = JSON.parse(settingsContent);
1240
+
1241
+ // Add telemetry hook
1242
+ if (!settings.hooks) settings.hooks = {};
1243
+ if (!settings.hooks['post-task']) settings.hooks['post-task'] = [];
1244
+
1245
+ // Add token tracking hook
1246
+ const tokenTrackingHook =
1247
+ 'npx claude-flow-novice internal track-tokens --session-id {{session_id}} --tokens {{token_usage}}';
1248
+ if (!settings.hooks['post-task'].includes(tokenTrackingHook)) {
1249
+ settings.hooks['post-task'].push(tokenTrackingHook);
1250
+ }
1251
+
1252
+ await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));
1253
+ printSuccess(' āœ“ Added token tracking hooks to settings');
1254
+ } catch (err) {
1255
+ console.log(' āš ļø Could not update settings.json:', err.message);
1256
+ }
1257
+
1258
+ // Create monitoring configuration
1259
+ const monitoringConfig = {
1260
+ enabled: true,
1261
+ telemetry: {
1262
+ claudeCode: {
1263
+ env: 'CLAUDE_CODE_ENABLE_TELEMETRY',
1264
+ value: '1',
1265
+ description: 'Enable Claude Code OpenTelemetry metrics',
1266
+ },
1267
+ },
1268
+ tracking: {
1269
+ tokens: true,
1270
+ costs: true,
1271
+ agents: true,
1272
+ sessions: true,
1273
+ },
1274
+ storage: {
1275
+ location: '.claude-flow/token-usage.json',
1276
+ format: 'json',
1277
+ rotation: 'monthly',
1278
+ },
1279
+ };
1280
+
1281
+ const configPath = path.join(trackingDir, 'monitoring.config.json');
1282
+ await fs.writeFile(configPath, JSON.stringify(monitoringConfig, null, 2));
1283
+ printSuccess(' āœ“ Created monitoring configuration');
1284
+
1285
+ // Create shell profile snippet for environment variable
1286
+ const envSnippet = `
1287
+ # Claude Flow Token Tracking
1288
+ # Add this to your shell profile (.bashrc, .zshrc, etc.)
1289
+ export CLAUDE_CODE_ENABLE_TELEMETRY=1
1290
+
1291
+ # Optional: Set custom metrics path
1292
+ # export CLAUDE_METRICS_PATH="$HOME/.claude/metrics"
1293
+ `;
1294
+
1295
+ const envPath = path.join(trackingDir, 'env-setup.sh');
1296
+ await fs.writeFile(envPath, envSnippet.trim());
1297
+ printSuccess(' āœ“ Created environment setup script');
1298
+
1299
+ console.log('\n šŸ“‹ To enable Claude Code telemetry:');
1300
+ console.log(' 1. Add to your shell profile: export CLAUDE_CODE_ENABLE_TELEMETRY=1');
1301
+ console.log(' 2. Or run: source .claude-flow/env-setup.sh');
1302
+ console.log('\n šŸ’” Token usage will be tracked in .claude-flow/token-usage.json');
1303
+ console.log(' Run: claude-flow-novice analysis token-usage --breakdown --cost-analysis');
1304
+ } catch (err) {
1305
+ printError(` Failed to setup monitoring: ${err.message}`);
1306
+ }
1307
+ }
1308
+
1309
+ /**
1310
+ * Enhanced Claude Flow v2.0.0 initialization
1311
+ */
1312
+ async function enhancedClaudeFlowInit(flags, subArgs = []) {
1313
+ console.log('šŸš€ Initializing Claude Flow v2.0.0 with enhanced features...');
1314
+
1315
+ const workingDir = process.cwd();
1316
+ const force = flags.force || flags.f;
1317
+ const dryRun = flags.dryRun || flags['dry-run'] || flags.d;
1318
+ const initSparc = flags.roo || (subArgs && subArgs.includes('--roo')); // SPARC only with --roo flag
1319
+
1320
+ // Store parameters to avoid scope issues in async context
1321
+ const args = subArgs || [];
1322
+ const options = flags || {};
1323
+
1324
+ // Import fs module for Node.js
1325
+ const fs = await import('fs/promises');
1326
+ const { chmod } = fs;
1327
+
1328
+ try {
1329
+ // Check existing files
1330
+ const existingFiles = [];
1331
+ const filesToCheck = [
1332
+ 'CLAUDE.md',
1333
+ '.claude/settings.json',
1334
+ '.mcp.json',
1335
+ 'claude-flow.config.json',
1336
+ ];
1337
+
1338
+ for (const file of filesToCheck) {
1339
+ if (existsSync(`${workingDir}/${file}`)) {
1340
+ existingFiles.push(file);
1341
+ }
1342
+ }
1343
+
1344
+ if (existingFiles.length > 0 && !force) {
1345
+ printWarning(`The following files already exist: ${existingFiles.join(', ')}`);
1346
+ console.log('Use --force to overwrite existing files');
1347
+ return;
1348
+ }
1349
+
1350
+ // Create CLAUDE.md from template
1351
+ if (!dryRun) {
1352
+ const claudeMdContent = await readClaudeMdTemplate();
1353
+ await fs.writeFile(`${workingDir}/CLAUDE.md`, claudeMdContent, 'utf8');
1354
+ printSuccess('āœ“ Created CLAUDE.md (Claude Flow v2.0.0 - Optimized Template)');
1355
+ } else {
1356
+ console.log('[DRY RUN] Would create CLAUDE.md (Claude Flow v2.0.0 - Optimized Template)');
1357
+ }
1358
+
1359
+ // Create .claude directory structure
1360
+ const claudeDir = `${workingDir}/.claude`;
1361
+ if (!dryRun) {
1362
+ await fs.mkdir(claudeDir, { recursive: true });
1363
+ await fs.mkdir(`${claudeDir}/commands`, { recursive: true });
1364
+ await fs.mkdir(`${claudeDir}/helpers`, { recursive: true });
1365
+ printSuccess('āœ“ Created .claude directory structure');
1366
+ } else {
1367
+ console.log('[DRY RUN] Would create .claude directory structure');
1368
+ }
1369
+
1370
+ // Create settings.json
1371
+ if (!dryRun) {
1372
+ await fs.writeFile(`${claudeDir}/settings.json`, createEnhancedSettingsJson(), 'utf8');
1373
+ printSuccess('āœ“ Created .claude/settings.json with hooks and MCP configuration');
1374
+ } else {
1375
+ console.log('[DRY RUN] Would create .claude/settings.json');
1376
+ }
1377
+
1378
+ // Create settings.local.json with default MCP permissions
1379
+ const settingsLocal = {
1380
+ permissions: {
1381
+ allow: ['mcp__ruv-swarm', 'mcp__claude-flow'],
1382
+ deny: [],
1383
+ },
1384
+ };
1385
+
1386
+ if (!dryRun) {
1387
+ await fs.writeFile(
1388
+ `${claudeDir}/settings.local.json`,
1389
+ JSON.stringify(settingsLocal, null, 2, 'utf8'),
1390
+ );
1391
+ printSuccess('āœ“ Created .claude/settings.local.json with default MCP permissions');
1392
+ } else {
1393
+ console.log(
1394
+ '[DRY RUN] Would create .claude/settings.local.json with default MCP permissions',
1395
+ );
1396
+ }
1397
+
1398
+ // Setup bulletproof MCP configuration instead of legacy approach
1399
+ console.log('\nšŸ›”ļø Setting up bulletproof MCP configuration...');
1400
+
1401
+ const mcpOptions = {
1402
+ verbose: flags.verbose || false,
1403
+ autoFix: flags['auto-fix'] !== false && !flags['no-auto-fix'], // Default true unless explicitly disabled
1404
+ dryRun: dryRun,
1405
+ enhancedUx: true, // Enable enhanced user experience
1406
+ showEducation: flags['show-education'] || false,
1407
+ serverConfig: {
1408
+ mcpServers: {
1409
+ 'claude-flow-novice': {
1410
+ command: 'npx',
1411
+ args: ['claude-flow-novice', 'mcp', 'start'],
1412
+ env: {
1413
+ NODE_ENV: 'production',
1414
+ CLAUDE_FLOW_NOVICE_MODE: 'novice'
1415
+ }
1416
+ }
1417
+ }
1418
+ }
1419
+ };
1420
+
1421
+ let mcpSuccess = false;
1422
+ try {
1423
+ const { enhancedMcpInit } = await import('../../mcp/mcp-config-manager.js');
1424
+ const result = await enhancedMcpInit(mcpOptions);
1425
+
1426
+ if (result.success) {
1427
+ printSuccess('āœ“ Bulletproof MCP configuration completed successfully');
1428
+ if (result.details) {
1429
+ console.log(` • Issues Fixed: ${result.details.issuesFixed || 0}`);
1430
+ console.log(` • Health Score: ${result.details.healthScore || 'N/A'}/100`);
1431
+ }
1432
+ mcpSuccess = true;
1433
+ } else {
1434
+ printWarning(`āš ļø MCP configuration had issues: ${result.error || 'Unknown error'}`);
1435
+ if (result.rollbackAvailable) {
1436
+ console.log(' šŸ”„ Automatic rollback was performed');
1437
+ }
1438
+ }
1439
+ } catch (error) {
1440
+ printWarning(`āš ļø Bulletproof MCP setup failed: ${error.message}`);
1441
+ printWarning(' šŸ“ž Falling back to legacy MCP configuration...');
1442
+
1443
+ // Fallback to legacy config creation
1444
+ const mcpConfig = {
1445
+ mcpServers: {
1446
+ 'claude-flow-novice': {
1447
+ command: 'npx',
1448
+ args: ['claude-flow-novice', 'mcp', 'start'],
1449
+ env: {
1450
+ NODE_ENV: 'production',
1451
+ CLAUDE_FLOW_NOVICE_MODE: 'novice'
1452
+ }
1453
+ }
1454
+ }
1455
+ };
1456
+
1457
+ if (!dryRun) {
1458
+ await fs.writeFile(`${workingDir}/.mcp.json`, JSON.stringify(mcpConfig, null, 2), 'utf8');
1459
+ printSuccess('āœ“ Created .mcp.json with legacy configuration');
1460
+ } else {
1461
+ console.log('[DRY RUN] Would create .mcp.json with legacy configuration');
1462
+ }
1463
+ mcpSuccess = true; // Consider legacy success for continuation
1464
+ }
1465
+
1466
+ // Create claude-flow.config.json for Claude Flow specific settings
1467
+ const claudeFlowConfig = {
1468
+ features: {
1469
+ autoTopologySelection: true,
1470
+ parallelExecution: true,
1471
+ neuralTraining: true,
1472
+ bottleneckAnalysis: true,
1473
+ smartAutoSpawning: true,
1474
+ selfHealingWorkflows: true,
1475
+ crossSessionMemory: true,
1476
+ githubIntegration: true,
1477
+ },
1478
+ performance: {
1479
+ maxAgents: 10,
1480
+ defaultTopology: 'hierarchical',
1481
+ executionStrategy: 'parallel',
1482
+ tokenOptimization: true,
1483
+ cacheEnabled: true,
1484
+ telemetryLevel: 'detailed',
1485
+ },
1486
+ };
1487
+
1488
+ if (!dryRun) {
1489
+ await fs.writeFile(
1490
+ `${workingDir}/claude-flow.config.json`,
1491
+ JSON.stringify(claudeFlowConfig, null, 2, 'utf8'),
1492
+ );
1493
+ printSuccess('āœ“ Created claude-flow.config.json for Claude Flow settings');
1494
+ } else {
1495
+ console.log('[DRY RUN] Would create claude-flow.config.json for Claude Flow settings');
1496
+ }
1497
+
1498
+ // Create command documentation
1499
+ for (const [category, commands] of Object.entries(COMMAND_STRUCTURE)) {
1500
+ const categoryDir = `${claudeDir}/commands/${category}`;
1501
+
1502
+ if (!dryRun) {
1503
+ await fs.mkdir(categoryDir, { recursive: true });
1504
+
1505
+ // Create category README
1506
+ const categoryReadme = `# ${category.charAt(0).toUpperCase() + category.slice(1)} Commands
1507
+
1508
+ Commands for ${category} operations in Claude Flow.
1509
+
1510
+ ## Available Commands
1511
+
1512
+ ${commands.map((cmd) => `- [${cmd}](./${cmd}.md)`).join('\n')}
1513
+ `;
1514
+ await fs.writeFile(`${categoryDir}/README.md`, categoryReadme, 'utf8');
1515
+
1516
+ // Create individual command docs
1517
+ for (const command of commands) {
1518
+ const doc = createCommandDoc(category, command);
1519
+ if (doc) {
1520
+ await fs.writeFile(`${categoryDir}/${command}.md`, doc, 'utf8');
1521
+ }
1522
+ }
1523
+
1524
+ console.log(` āœ“ Created ${commands.length} ${category} command docs`);
1525
+ } else {
1526
+ console.log(`[DRY RUN] Would create ${commands.length} ${category} command docs`);
1527
+ }
1528
+ }
1529
+
1530
+ // Create wrapper scripts
1531
+ if (!dryRun) {
1532
+ // Unix wrapper - now uses universal ES module compatible wrapper
1533
+ const unixWrapper = createWrapperScript('unix');
1534
+ await fs.writeFile(`${workingDir}/claude-flow`, unixWrapper, 'utf8');
1535
+ await fs.chmod(`${workingDir}/claude-flow`, 0o755);
1536
+
1537
+ // Windows wrapper
1538
+ await fs.writeFile(`${workingDir}/claude-flow.bat`, createWrapperScript('windows', 'utf8'));
1539
+
1540
+ // PowerShell wrapper
1541
+ await fs.writeFile(
1542
+ `${workingDir}/claude-flow.ps1`,
1543
+ createWrapperScript('powershell', 'utf8'),
1544
+ );
1545
+
1546
+ printSuccess('āœ“ Created platform-specific wrapper scripts');
1547
+ } else {
1548
+ console.log('[DRY RUN] Would create wrapper scripts');
1549
+ }
1550
+
1551
+ // Create helper scripts
1552
+ const helpers = [
1553
+ 'setup-mcp.sh',
1554
+ 'quick-start.sh',
1555
+ 'github-setup.sh',
1556
+ 'github-safe.js',
1557
+ 'standard-checkpoint-hooks.sh',
1558
+ 'checkpoint-manager.sh',
1559
+ ];
1560
+ for (const helper of helpers) {
1561
+ if (!dryRun) {
1562
+ const content = createHelperScript(helper);
1563
+ if (content) {
1564
+ await fs.writeFile(`${claudeDir}/helpers/${helper}`, content, 'utf8');
1565
+ await fs.chmod(`${claudeDir}/helpers/${helper}`, 0o755);
1566
+ }
1567
+ }
1568
+ }
1569
+
1570
+ if (!dryRun) {
1571
+ printSuccess(`āœ“ Created ${helpers.length} helper scripts`);
1572
+ } else {
1573
+ console.log(`[DRY RUN] Would create ${helpers.length} helper scripts`);
1574
+ }
1575
+
1576
+ // Create standard directories from original init
1577
+ const standardDirs = [
1578
+ 'memory',
1579
+ 'memory/agents',
1580
+ 'memory/sessions',
1581
+ 'coordination',
1582
+ 'coordination/memory_bank',
1583
+ 'coordination/subtasks',
1584
+ 'coordination/orchestration',
1585
+ '.swarm', // Add .swarm directory for shared memory
1586
+ '.hive-mind', // Add .hive-mind directory for hive-mind system
1587
+ '.claude/checkpoints', // Add checkpoints directory for Git checkpoint system
1588
+ ];
1589
+
1590
+ for (const dir of standardDirs) {
1591
+ if (!dryRun) {
1592
+ await fs.mkdir(`${workingDir}/${dir}`, { recursive: true });
1593
+ }
1594
+ }
1595
+
1596
+ if (!dryRun) {
1597
+ printSuccess('āœ“ Created standard directory structure');
1598
+
1599
+ // Initialize memory system
1600
+ const initialData = { agents: [], tasks: [], lastUpdated: Date.now() };
1601
+ await fs.writeFile(
1602
+ `${workingDir}/memory/claude-flow-data.json`,
1603
+ JSON.stringify(initialData, null, 2, 'utf8'),
1604
+ );
1605
+
1606
+ // Create README files
1607
+ await fs.writeFile(`${workingDir}/memory/agents/README.md`, createAgentsReadme(), 'utf8');
1608
+ await fs.writeFile(`${workingDir}/memory/sessions/README.md`, createSessionsReadme(), 'utf8');
1609
+
1610
+ printSuccess('āœ“ Initialized memory system');
1611
+
1612
+ // Initialize memory database with fallback support
1613
+ try {
1614
+ // Import and initialize FallbackMemoryStore to create the database
1615
+ const { FallbackMemoryStore } = await import('../../../memory/fallback-store.js');
1616
+ const memoryStore = new FallbackMemoryStore();
1617
+ await memoryStore.initialize();
1618
+
1619
+ if (memoryStore.isUsingFallback()) {
1620
+ printSuccess('āœ“ Initialized memory system (in-memory fallback for npx compatibility)');
1621
+ console.log(
1622
+ ' šŸ’” For persistent storage, install locally: npm install claude-flow@alpha',
1623
+ );
1624
+ } else {
1625
+ printSuccess('āœ“ Initialized memory database (.swarm/memory.db)');
1626
+ }
1627
+
1628
+ memoryStore.close();
1629
+ } catch (err) {
1630
+ console.log(` āš ļø Could not initialize memory system: ${err.message}`);
1631
+ console.log(' Memory will be initialized on first use');
1632
+ }
1633
+
1634
+ // Initialize comprehensive hive-mind system
1635
+ console.log('\n🧠 Initializing Hive Mind System...');
1636
+ try {
1637
+ const hiveMindOptions = {
1638
+ config: {
1639
+ integration: {
1640
+ claudeCode: { enabled: isClaudeCodeInstalled() },
1641
+ mcpTools: { enabled: true },
1642
+ },
1643
+ monitoring: { enabled: flags.monitoring || false },
1644
+ },
1645
+ };
1646
+
1647
+ const hiveMindResult = await initializeHiveMind(workingDir, hiveMindOptions, dryRun);
1648
+
1649
+ if (hiveMindResult.success) {
1650
+ printSuccess(
1651
+ `āœ“ Hive Mind System initialized with ${hiveMindResult.features.length} features`,
1652
+ );
1653
+
1654
+ // Log individual features
1655
+ hiveMindResult.features.forEach((feature) => {
1656
+ console.log(` • ${feature}`);
1657
+ });
1658
+ } else {
1659
+ console.log(` āš ļø Hive Mind initialization failed: ${hiveMindResult.error}`);
1660
+ if (hiveMindResult.rollbackRequired) {
1661
+ console.log(' šŸ”„ Automatic rollback may be required');
1662
+ }
1663
+ }
1664
+ } catch (err) {
1665
+ console.log(` āš ļø Could not initialize hive-mind system: ${err.message}`);
1666
+ }
1667
+ }
1668
+
1669
+ // Update .gitignore with Claude Flow entries
1670
+ const gitignoreResult = await updateGitignore(workingDir, force, dryRun);
1671
+ if (gitignoreResult.success) {
1672
+ if (!dryRun) {
1673
+ printSuccess(`āœ“ ${gitignoreResult.message}`);
1674
+ } else {
1675
+ console.log(gitignoreResult.message);
1676
+ }
1677
+ } else {
1678
+ console.log(` āš ļø ${gitignoreResult.message}`);
1679
+ }
1680
+
1681
+ // SPARC initialization (only with --roo flag)
1682
+ let sparcInitialized = false;
1683
+ if (initSparc) {
1684
+ console.log('\nšŸš€ Initializing SPARC development environment...');
1685
+ try {
1686
+ // Run create-sparc
1687
+ console.log(' šŸ”„ Running: npx -y create-sparc init --force');
1688
+ execSync('npx -y create-sparc init --force', {
1689
+ cwd: workingDir,
1690
+ stdio: 'inherit',
1691
+ });
1692
+ sparcInitialized = true;
1693
+ printSuccess('āœ… SPARC environment initialized successfully');
1694
+ } catch (err) {
1695
+ console.log(` āš ļø Could not run create-sparc: ${err.message}`);
1696
+ console.log(' SPARC features will be limited to basic functionality');
1697
+ }
1698
+ }
1699
+
1700
+ // Create Claude slash commands for SPARC
1701
+ if (sparcInitialized && !dryRun) {
1702
+ console.log('\nšŸ“ Creating Claude Code slash commands...');
1703
+ await createClaudeSlashCommands(workingDir);
1704
+ }
1705
+
1706
+ // Check for Claude Code and set up MCP servers (always enabled by default)
1707
+ if (!dryRun && isClaudeCodeInstalled()) {
1708
+ console.log('\nšŸ” Claude Code CLI detected!');
1709
+ const skipMcp =
1710
+ (options && options['skip-mcp']) ||
1711
+ (subArgs && subArgs.includes && subArgs.includes('--skip-mcp'));
1712
+
1713
+ if (!skipMcp) {
1714
+ // Use bulletproof MCP setup for enhanced init
1715
+ const mcpSuccess = await setupBulletproofMcp({
1716
+ verbose: true,
1717
+ autoFix: true,
1718
+ dryRun: dryRun
1719
+ });
1720
+
1721
+ if (!mcpSuccess) {
1722
+ console.log(' šŸ’” If you encounter issues, run: claude mcp remove claude-flow-novice -s local');
1723
+ }
1724
+ } else {
1725
+ console.log(' ā„¹ļø Skipping MCP setup (--skip-mcp flag used)');
1726
+ console.log('\n šŸ“‹ To add MCP servers manually:');
1727
+ console.log(' claude mcp add claude-flow-novice npx claude-flow-novice mcp start');
1728
+ console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');
1729
+ // Flow-nexus integration removed
1730
+ console.log('\n šŸ’” MCP servers are defined in .mcp.json (project scope)');
1731
+ }
1732
+ } else if (!dryRun && !isClaudeCodeInstalled()) {
1733
+ console.log('\nāš ļø Claude Code CLI not detected!');
1734
+ console.log('\n šŸ“„ To install Claude Code:');
1735
+ console.log(' npm install -g @anthropic-ai/claude-code');
1736
+ console.log('\n šŸ“‹ After installing, add MCP servers:');
1737
+ console.log(' claude mcp add claude-flow-novice npx claude-flow-novice mcp start');
1738
+ console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');
1739
+ // Flow-nexus integration removed
1740
+ console.log('\n šŸ’” MCP servers are defined in .mcp.json (project scope)');
1741
+ }
1742
+
1743
+ // Create agent directories and copy all agent files
1744
+ console.log('\nšŸ¤– Setting up agent system...');
1745
+ if (!dryRun) {
1746
+ await createAgentDirectories(workingDir, dryRun);
1747
+ const agentResult = await copyAgentFiles(workingDir, {
1748
+ force: force,
1749
+ dryRun: dryRun,
1750
+ });
1751
+
1752
+ if (agentResult.success) {
1753
+ await validateAgentSystem(workingDir);
1754
+
1755
+ // Copy command files including Flow Nexus commands
1756
+ console.log('\nšŸ“š Setting up command system...');
1757
+ const commandResult = await copyCommandFiles(workingDir, {
1758
+ force: force,
1759
+ dryRun: dryRun,
1760
+ });
1761
+
1762
+ if (commandResult.success) {
1763
+ console.log('āœ… āœ“ Command system setup complete with Flow Nexus integration');
1764
+ } else {
1765
+ console.log('āš ļø Command system setup failed:', commandResult.error);
1766
+ }
1767
+
1768
+ console.log('āœ… āœ“ Agent system setup complete with 64 specialized agents');
1769
+ } else {
1770
+ console.log('āš ļø Agent system setup failed:', agentResult.error);
1771
+ }
1772
+
1773
+ // Setup hooks system for novice users
1774
+ console.log('\nšŸŖ Setting up hooks system...');
1775
+ const hooksConfig = {
1776
+ hooks: {
1777
+ pre_task: {
1778
+ enabled: true,
1779
+ command: "npx claude-flow-novice hooks pre-task --description \"$TASK_DESCRIPTION\"",
1780
+ description: "Pre-task coordination hook"
1781
+ },
1782
+ post_edit: {
1783
+ enabled: true,
1784
+ command: "npx claude-flow-novice hooks post-edit --file \"$FILE_PATH\" --memory-key \"swarm/$AGENT_ID/$STEP\"",
1785
+ description: "Post-edit memory storage hook"
1786
+ },
1787
+ post_task: {
1788
+ enabled: true,
1789
+ command: "npx claude-flow-novice hooks post-task --task-id \"$TASK_ID\"",
1790
+ description: "Post-task completion hook"
1791
+ }
1792
+ },
1793
+ memory: {
1794
+ enabled: true,
1795
+ persistence: "local",
1796
+ namespace: "claude-flow-novice"
1797
+ }
1798
+ };
1799
+
1800
+ const hooksConfigPath = `${claudeDir}/hooks.json`;
1801
+ await fs.writeFile(hooksConfigPath, JSON.stringify(hooksConfig, null, 2), 'utf8');
1802
+ console.log('āœ… āœ“ Hooks system setup complete with automated coordination');
1803
+
1804
+ } else {
1805
+ console.log(' [DRY RUN] Would create agent system with 64 specialized agents');
1806
+ console.log(' [DRY RUN] Would create hooks system with automated coordination');
1807
+ }
1808
+
1809
+ // Optional: Setup monitoring and telemetry
1810
+ const enableMonitoring = flags.monitoring || flags['enable-monitoring'];
1811
+ if (enableMonitoring && !dryRun) {
1812
+ console.log('\nšŸ“Š Setting up monitoring and telemetry...');
1813
+ await setupMonitoring(workingDir);
1814
+ }
1815
+
1816
+ // Final instructions with hive-mind status
1817
+ console.log('\nšŸŽ‰ Claude Flow v2.0.0 initialization complete!');
1818
+
1819
+ // Display MCP setup status prominently
1820
+ if (mcpSuccess) {
1821
+ console.log('\nšŸ›”ļø Bulletproof MCP Configuration Status:');
1822
+ console.log(' āœ… MCP server successfully configured with auto-recovery');
1823
+ console.log(' āœ… Conflict detection and resolution enabled');
1824
+ console.log(' āœ… Automatic backup and rollback capability active');
1825
+ console.log(' āœ… Project-specific configuration created (.mcp.json)');
1826
+ } else {
1827
+ console.log('\nāš ļø MCP Configuration Status:');
1828
+ console.log(' āš ļø MCP setup completed with fallback configuration');
1829
+ console.log(' šŸ’” Run health check: npx claude-flow-novice mcp health');
1830
+ }
1831
+
1832
+ // Display hive-mind status
1833
+ const hiveMindStatus = getHiveMindStatus(workingDir);
1834
+ console.log('\n🧠 Hive Mind System Status:');
1835
+ console.log(` Configuration: ${hiveMindStatus.configured ? 'āœ… Ready' : 'āŒ Missing'}`);
1836
+ console.log(
1837
+ ` Database: ${hiveMindStatus.database === 'sqlite' ? 'āœ… SQLite' : hiveMindStatus.database === 'fallback' ? 'āš ļø JSON Fallback' : 'āŒ Not initialized'}`,
1838
+ );
1839
+ console.log(
1840
+ ` Directory Structure: ${hiveMindStatus.directories ? 'āœ… Created' : 'āŒ Missing'}`,
1841
+ );
1842
+
1843
+ console.log('\nšŸ“š Quick Start:');
1844
+ if (isClaudeCodeInstalled()) {
1845
+ console.log('1. Verify MCP setup: claude mcp list');
1846
+ console.log('2. View available commands: ls .claude/commands/');
1847
+ console.log('3. Start a swarm: npx claude-flow-novice swarm "your objective" --claude');
1848
+ console.log('4. Use hive-mind: npx claude-flow-novice hive-mind spawn "command" --claude');
1849
+ console.log('5. Use enhanced MCP tools in Claude Code for bulletproof coordination');
1850
+ if (hiveMindStatus.configured) {
1851
+ console.log('5. Initialize first swarm: npx claude-flow-novice hive-mind init');
1852
+ }
1853
+ } else {
1854
+ console.log('1. Install Claude Code: npm install -g @anthropic-ai/claude-code');
1855
+ console.log('2. Add MCP servers (see instructions above)');
1856
+ console.log('3. View available commands: ls .claude/commands/');
1857
+ console.log('4. Start a swarm: npx claude-flow-novice swarm "your objective" --claude');
1858
+ console.log('5. Use hive-mind: npx claude-flow-novice hive-mind spawn "command" --claude');
1859
+ if (hiveMindStatus.configured) {
1860
+ console.log('6. Initialize first swarm: npx claude-flow-novice hive-mind init');
1861
+ }
1862
+ }
1863
+ console.log('\nšŸ’” Tips:');
1864
+ console.log('• Check .claude/commands/ for detailed documentation');
1865
+ console.log('• Use --help with any command for options');
1866
+ console.log('• Run commands with --claude flag for best Claude Code integration');
1867
+ if (mcpSuccess) {
1868
+ console.log('• MCP health check: npx claude-flow-novice mcp health');
1869
+ console.log('• Configuration backups are automatically created for safety');
1870
+ console.log('• Project-specific .mcp.json prevents conflicts with other projects');
1871
+ }
1872
+ console.log('• Enable GitHub integration with .claude/helpers/github-setup.sh');
1873
+ console.log('• Git checkpoints are automatically enabled in settings.json');
1874
+ console.log('• Use .claude/helpers/checkpoint-manager.sh for easy rollback');
1875
+ } catch (err) {
1876
+ printError(`Failed to initialize Claude Flow v2.0.0: ${err.message}`);
1877
+
1878
+ // Attempt hive-mind rollback if it was partially initialized
1879
+ try {
1880
+ const hiveMindStatus = getHiveMindStatus(workingDir);
1881
+ if (hiveMindStatus.directories || hiveMindStatus.configured) {
1882
+ console.log('\nšŸ”„ Attempting hive-mind system rollback...');
1883
+ const rollbackResult = await rollbackHiveMindInit(workingDir);
1884
+ if (rollbackResult.success) {
1885
+ console.log(' āœ… Hive-mind rollback completed');
1886
+ } else {
1887
+ console.log(` āš ļø Hive-mind rollback failed: ${rollbackResult.error}`);
1888
+ }
1889
+ }
1890
+ } catch (rollbackErr) {
1891
+ console.log(` āš ļø Rollback error: ${rollbackErr.message}`);
1892
+ }
1893
+ }
1894
+ }
1895
+
1896
+ // Flow Nexus initialization removed