moflo 4.8.32 → 4.8.34

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 (40) hide show
  1. package/bin/generate-code-map.mjs +955 -955
  2. package/bin/index-guidance.mjs +905 -905
  3. package/bin/index-tests.mjs +728 -728
  4. package/bin/setup-project.mjs +252 -252
  5. package/package.json +10 -5
  6. package/src/@claude-flow/cli/dist/src/commands/doctor.js +1339 -1107
  7. package/src/@claude-flow/cli/dist/src/index.js +2 -18
  8. package/src/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.js +17 -0
  9. package/src/@claude-flow/cli/dist/src/memory/memory-initializer.js +4 -7
  10. package/src/@claude-flow/cli/dist/src/version.js +6 -0
  11. package/src/@claude-flow/cli/package.json +1 -1
  12. package/src/@claude-flow/neural/README.md +260 -0
  13. package/src/@claude-flow/neural/dist/algorithms/a2c.js +361 -0
  14. package/src/@claude-flow/neural/dist/algorithms/curiosity.js +392 -0
  15. package/src/@claude-flow/neural/dist/algorithms/decision-transformer.js +415 -0
  16. package/src/@claude-flow/neural/dist/algorithms/dqn.js +303 -0
  17. package/src/@claude-flow/neural/dist/algorithms/index.js +74 -0
  18. package/src/@claude-flow/neural/dist/algorithms/ppo.js +331 -0
  19. package/src/@claude-flow/neural/dist/algorithms/q-learning.js +259 -0
  20. package/src/@claude-flow/neural/dist/algorithms/sarsa.js +297 -0
  21. package/src/@claude-flow/neural/dist/application/index.js +7 -0
  22. package/src/@claude-flow/neural/dist/application/services/neural-application-service.js +161 -0
  23. package/src/@claude-flow/neural/dist/domain/entities/pattern.js +134 -0
  24. package/src/@claude-flow/neural/dist/domain/index.js +8 -0
  25. package/src/@claude-flow/neural/dist/domain/services/learning-service.js +195 -0
  26. package/src/@claude-flow/neural/dist/index.js +201 -0
  27. package/src/@claude-flow/neural/dist/modes/balanced.js +234 -0
  28. package/src/@claude-flow/neural/dist/modes/base.js +77 -0
  29. package/src/@claude-flow/neural/dist/modes/batch.js +316 -0
  30. package/src/@claude-flow/neural/dist/modes/edge.js +310 -0
  31. package/src/@claude-flow/neural/dist/modes/index.js +13 -0
  32. package/src/@claude-flow/neural/dist/modes/real-time.js +196 -0
  33. package/src/@claude-flow/neural/dist/modes/research.js +389 -0
  34. package/src/@claude-flow/neural/dist/pattern-learner.js +603 -0
  35. package/src/@claude-flow/neural/dist/reasoning-bank.js +993 -0
  36. package/src/@claude-flow/neural/dist/reasoningbank-adapter.js +463 -0
  37. package/src/@claude-flow/neural/dist/sona-integration.js +326 -0
  38. package/src/@claude-flow/neural/dist/sona-manager.js +695 -0
  39. package/src/@claude-flow/neural/dist/types.js +11 -0
  40. package/src/@claude-flow/neural/package.json +26 -0
@@ -1,1108 +1,1340 @@
1
- /**
2
- * V3 CLI Doctor Command
3
- * System diagnostics, dependency checks, config validation
4
- *
5
- * Created with motailz.com
6
- */
7
- import { output } from '../output.js';
8
- import { existsSync, readFileSync, writeFileSync, unlinkSync, statSync, mkdirSync } from 'fs';
9
- import { join, dirname } from 'path';
10
- import { fileURLToPath } from 'url';
11
- import { execSync, exec } from 'child_process';
12
- import { promisify } from 'util';
13
- import { getDaemonLockHolder, releaseDaemonLock, isDaemonProcess } from '../services/daemon-lock.js';
14
- // Promisified exec with proper shell and env inheritance for cross-platform support
15
- const execAsync = promisify(exec);
16
- /**
17
- * Execute command asynchronously with proper environment inheritance
18
- * Critical for Windows where PATH may not be inherited properly
19
- */
20
- async function runCommand(command, timeoutMs = 5000) {
21
- const { stdout } = await execAsync(command, {
22
- encoding: 'utf8',
23
- timeout: timeoutMs,
24
- shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/sh', // Use proper shell per platform
25
- env: { ...process.env }, // Explicitly inherit full environment
26
- windowsHide: true, // Hide window on Windows
27
- });
28
- return stdout.trim();
29
- }
30
- // Check Node.js version
31
- async function checkNodeVersion() {
32
- const requiredMajor = 20;
33
- const version = process.version;
34
- const major = parseInt(version.slice(1).split('.')[0], 10);
35
- if (major >= requiredMajor) {
36
- return { name: 'Node.js Version', status: 'pass', message: `${version} (>= ${requiredMajor} required)` };
37
- }
38
- else if (major >= 18) {
39
- return { name: 'Node.js Version', status: 'warn', message: `${version} (>= ${requiredMajor} recommended)`, fix: 'nvm install 20 && nvm use 20' };
40
- }
41
- else {
42
- return { name: 'Node.js Version', status: 'fail', message: `${version} (>= ${requiredMajor} required)`, fix: 'nvm install 20 && nvm use 20' };
43
- }
44
- }
45
- // Check npm version (async with proper env inheritance)
46
- async function checkNpmVersion() {
47
- try {
48
- const version = await runCommand('npm --version');
49
- const major = parseInt(version.split('.')[0], 10);
50
- if (major >= 9) {
51
- return { name: 'npm Version', status: 'pass', message: `v${version}` };
52
- }
53
- else {
54
- return { name: 'npm Version', status: 'warn', message: `v${version} (>= 9 recommended)`, fix: 'npm install -g npm@latest' };
55
- }
56
- }
57
- catch {
58
- return { name: 'npm Version', status: 'fail', message: 'npm not found', fix: 'Install Node.js from https://nodejs.org' };
59
- }
60
- }
61
- // Check config file
62
- async function checkConfigFile() {
63
- // JSON configs (parse-validated)
64
- const jsonPaths = [
65
- '.claude-flow/config.json',
66
- 'claude-flow.config.json',
67
- '.claude-flow.json'
68
- ];
69
- for (const configPath of jsonPaths) {
70
- if (existsSync(configPath)) {
71
- try {
72
- const content = readFileSync(configPath, 'utf8');
73
- JSON.parse(content);
74
- return { name: 'Config File', status: 'pass', message: `Found: ${configPath}` };
75
- }
76
- catch (e) {
77
- return { name: 'Config File', status: 'fail', message: `Invalid JSON: ${configPath}`, fix: 'Fix JSON syntax in config file' };
78
- }
79
- }
80
- }
81
- // YAML configs (existence-checked only — no heavy yaml parser dependency)
82
- const yamlPaths = [
83
- '.claude-flow/config.yaml',
84
- '.claude-flow/config.yml',
85
- 'claude-flow.config.yaml'
86
- ];
87
- for (const configPath of yamlPaths) {
88
- if (existsSync(configPath)) {
89
- return { name: 'Config File', status: 'pass', message: `Found: ${configPath}` };
90
- }
91
- }
92
- return { name: 'Config File', status: 'warn', message: 'No config file (using defaults)', fix: 'claude-flow config init' };
93
- }
94
- // Check daemon status — delegates to daemon-lock module for proper
95
- // PID + command-line verification (avoids Windows PID-recycling false positives).
96
- async function checkDaemonStatus() {
97
- try {
98
- // Retry up to 5 times with 1s delay — the daemon starts in the background
99
- // during session-start and may not have acquired its lock file yet.
100
- const MAX_RETRIES = 5;
101
- const RETRY_DELAY_MS = 1000;
102
- let holderPid = null;
103
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
104
- holderPid = getDaemonLockHolder(process.cwd());
105
- if (holderPid)
106
- break;
107
- if (attempt < MAX_RETRIES - 1) {
108
- await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
109
- }
110
- }
111
- if (holderPid) {
112
- return { name: 'Daemon Status', status: 'pass', message: `Running (PID: ${holderPid})` };
113
- }
114
- // getDaemonLockHolder auto-cleans stale locks, but check for legacy PID file
115
- const lockFile = '.claude-flow/daemon.lock';
116
- if (existsSync(lockFile)) {
117
- // Lock exists but holder is null — getDaemonLockHolder already cleaned it,
118
- // but if it persists it means cleanup failed (permissions, etc.)
119
- return { name: 'Daemon Status', status: 'warn', message: 'Stale lock file', fix: 'rm .claude-flow/daemon.lock && claude-flow daemon start' };
120
- }
121
- // Also check legacy PID file
122
- const pidFile = '.claude-flow/daemon.pid';
123
- if (existsSync(pidFile)) {
124
- return { name: 'Daemon Status', status: 'warn', message: 'Legacy PID file found', fix: 'rm .claude-flow/daemon.pid && claude-flow daemon start' };
125
- }
126
- return { name: 'Daemon Status', status: 'warn', message: 'Not running', fix: 'claude-flow daemon start' };
127
- }
128
- catch {
129
- return { name: 'Daemon Status', status: 'warn', message: 'Unable to check', fix: 'claude-flow daemon status' };
130
- }
131
- }
132
- // Check memory database
133
- async function checkMemoryDatabase() {
134
- const dbPaths = [
135
- '.claude-flow/memory.db',
136
- '.swarm/memory.db',
137
- 'data/memory.db'
138
- ];
139
- for (const dbPath of dbPaths) {
140
- if (existsSync(dbPath)) {
141
- try {
142
- const stats = statSync(dbPath);
143
- const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
144
- return { name: 'Memory Database', status: 'pass', message: `${dbPath} (${sizeMB} MB)` };
145
- }
146
- catch {
147
- return { name: 'Memory Database', status: 'warn', message: `${dbPath} (unable to stat)` };
148
- }
149
- }
150
- }
151
- return { name: 'Memory Database', status: 'warn', message: 'Not initialized', fix: 'claude-flow memory configure --backend hybrid' };
152
- }
153
- // Check git (async with proper env inheritance)
154
- async function checkGit() {
155
- try {
156
- const version = await runCommand('git --version');
157
- return { name: 'Git', status: 'pass', message: version.replace('git version ', 'v') };
158
- }
159
- catch {
160
- return { name: 'Git', status: 'warn', message: 'Not installed', fix: 'Install git from https://git-scm.com' };
161
- }
162
- }
163
- // Check if in git repo (async with proper env inheritance)
164
- async function checkGitRepo() {
165
- try {
166
- await runCommand('git rev-parse --git-dir');
167
- return { name: 'Git Repository', status: 'pass', message: 'In a git repository' };
168
- }
169
- catch {
170
- return { name: 'Git Repository', status: 'warn', message: 'Not a git repository', fix: 'git init' };
171
- }
172
- }
173
- // Check MCP servers
174
- async function checkMcpServers() {
175
- const mcpConfigPaths = [
176
- join(process.env.HOME || '', '.claude/claude_desktop_config.json'),
177
- join(process.env.HOME || '', '.config/claude/mcp.json'),
178
- '.mcp.json'
179
- ];
180
- for (const configPath of mcpConfigPaths) {
181
- if (existsSync(configPath)) {
182
- try {
183
- const content = JSON.parse(readFileSync(configPath, 'utf8'));
184
- const servers = content.mcpServers || content.servers || {};
185
- const count = Object.keys(servers).length;
186
- const hasClaudeFlow = 'moflo' in servers || 'claude-flow' in servers || 'claude-flow_alpha' in servers || 'ruflo' in servers || 'ruflo_alpha' in servers;
187
- if (hasClaudeFlow) {
188
- return { name: 'MCP Servers', status: 'pass', message: `${count} servers (flo configured)` };
189
- }
190
- else {
191
- return { name: 'MCP Servers', status: 'warn', message: `${count} servers (flo not found)`, fix: 'claude mcp add ruflo -- npx -y ruflo@latest mcp start' };
192
- }
193
- }
194
- catch {
195
- // continue to next path
196
- }
197
- }
198
- }
199
- return { name: 'MCP Servers', status: 'warn', message: 'No MCP config found', fix: 'claude mcp add moflo npx moflo mcp start' };
200
- }
201
- // Check disk space (async with proper env inheritance)
202
- async function checkDiskSpace() {
203
- try {
204
- if (process.platform === 'win32') {
205
- return { name: 'Disk Space', status: 'pass', message: 'Check skipped on Windows' };
206
- }
207
- // Use df -Ph for POSIX mode (guarantees single-line output even with long device names)
208
- const output_str = await runCommand('df -Ph . | tail -1');
209
- const parts = output_str.split(/\s+/);
210
- // POSIX format: Filesystem Size Used Avail Capacity Mounted
211
- const available = parts[3];
212
- const usePercent = parseInt(parts[4]?.replace('%', '') || '0', 10);
213
- if (isNaN(usePercent)) {
214
- return { name: 'Disk Space', status: 'warn', message: `${available || 'unknown'} available (unable to parse usage)` };
215
- }
216
- if (usePercent > 90) {
217
- return { name: 'Disk Space', status: 'fail', message: `${available} available (${usePercent}% used)`, fix: 'Free up disk space' };
218
- }
219
- else if (usePercent > 80) {
220
- return { name: 'Disk Space', status: 'warn', message: `${available} available (${usePercent}% used)` };
221
- }
222
- return { name: 'Disk Space', status: 'pass', message: `${available} available` };
223
- }
224
- catch {
225
- return { name: 'Disk Space', status: 'warn', message: 'Unable to check' };
226
- }
227
- }
228
- // Check TypeScript/build (async with proper env inheritance)
229
- async function checkBuildTools() {
230
- try {
231
- const tscVersion = await runCommand('npx tsc --version', 10000); // tsc can be slow
232
- if (!tscVersion || tscVersion.includes('not found')) {
233
- return { name: 'TypeScript', status: 'warn', message: 'Not installed locally', fix: 'npm install -D typescript' };
234
- }
235
- return { name: 'TypeScript', status: 'pass', message: tscVersion.replace('Version ', 'v') };
236
- }
237
- catch {
238
- return { name: 'TypeScript', status: 'warn', message: 'Not installed locally', fix: 'npm install -D typescript' };
239
- }
240
- }
241
- // Check for stale npx cache (version freshness)
242
- async function checkVersionFreshness() {
243
- try {
244
- // Get current CLI version from package.json
245
- // Use import.meta.url to reliably locate our own package.json,
246
- // regardless of how deep the compiled file sits (e.g. dist/src/commands/).
247
- let currentVersion = '0.0.0';
248
- try {
249
- const thisFile = fileURLToPath(import.meta.url);
250
- let dir = dirname(thisFile);
251
- // Walk up from the current file's directory until we find the
252
- // package.json that belongs to @claude-flow/cli (or claude-flow/cli).
253
- // Walk until dirname(dir) === dir (filesystem root on any platform).
254
- for (;;) {
255
- const candidate = join(dir, 'package.json');
256
- try {
257
- if (existsSync(candidate)) {
258
- const pkg = JSON.parse(readFileSync(candidate, 'utf8'));
259
- if (pkg.version &&
260
- typeof pkg.name === 'string' &&
261
- (pkg.name === '@claude-flow/cli' || pkg.name === 'claude-flow' || pkg.name === 'ruflo' || pkg.name === 'moflo' || pkg.name === '@moflo/cli')) {
262
- currentVersion = pkg.version;
263
- break;
264
- }
265
- }
266
- }
267
- catch {
268
- // Unreadable/invalid JSON -- skip and keep walking up
269
- }
270
- const parent = dirname(dir);
271
- if (parent === dir)
272
- break; // reached root
273
- dir = parent;
274
- }
275
- }
276
- catch {
277
- // Fall back to a default
278
- currentVersion = '0.0.0';
279
- }
280
- // Check if running via npx (look for _npx in process path or argv)
281
- const isNpx = process.argv[1]?.includes('_npx') ||
282
- process.env.npm_execpath?.includes('npx') ||
283
- process.cwd().includes('_npx');
284
- // Query npm for latest version (using alpha tag since that's what we publish to)
285
- let latestVersion = currentVersion;
286
- try {
287
- const npmInfo = await runCommand('npm view moflo version', 5000);
288
- latestVersion = npmInfo.trim();
289
- }
290
- catch {
291
- // Can't reach npm registry - skip check
292
- return {
293
- name: 'Version Freshness',
294
- status: 'warn',
295
- message: `v${currentVersion} (cannot check registry)`
296
- };
297
- }
298
- // Parse version numbers for comparison (handle prerelease like 3.0.0-alpha.84)
299
- const parseVersion = (v) => {
300
- const match = v.match(/^(\d+)\.(\d+)\.(\d+)(?:-[a-zA-Z]+\.(\d+))?/);
301
- if (!match)
302
- return { major: 0, minor: 0, patch: 0, prerelease: 0 };
303
- return {
304
- major: parseInt(match[1], 10) || 0,
305
- minor: parseInt(match[2], 10) || 0,
306
- patch: parseInt(match[3], 10) || 0,
307
- prerelease: parseInt(match[4], 10) || 0
308
- };
309
- };
310
- const current = parseVersion(currentVersion);
311
- const latest = parseVersion(latestVersion);
312
- // Compare versions (including prerelease number)
313
- const isOutdated = (latest.major > current.major ||
314
- (latest.major === current.major && latest.minor > current.minor) ||
315
- (latest.major === current.major && latest.minor === current.minor && latest.patch > current.patch) ||
316
- (latest.major === current.major && latest.minor === current.minor && latest.patch === current.patch && latest.prerelease > current.prerelease));
317
- if (isOutdated) {
318
- const fix = isNpx
319
- ? 'rm -rf ~/.npm/_npx/* && npx -y moflo'
320
- : 'npm update moflo';
321
- return {
322
- name: 'Version Freshness',
323
- status: 'warn',
324
- message: `v${currentVersion} (latest: v${latestVersion})${isNpx ? ' [npx cache stale]' : ''}`,
325
- fix
326
- };
327
- }
328
- return {
329
- name: 'Version Freshness',
330
- status: 'pass',
331
- message: `v${currentVersion} (up to date)`
332
- };
333
- }
334
- catch (error) {
335
- return {
336
- name: 'Version Freshness',
337
- status: 'warn',
338
- message: 'Unable to check version freshness'
339
- };
340
- }
341
- }
342
- // Check Claude Code CLI (async with proper env inheritance)
343
- async function checkClaudeCode() {
344
- try {
345
- const version = await runCommand('claude --version');
346
- // Parse version from output like "claude 1.0.0" or "Claude Code v1.0.0"
347
- const versionMatch = version.match(/v?(\d+\.\d+\.\d+)/);
348
- const versionStr = versionMatch ? `v${versionMatch[1]}` : version;
349
- return { name: 'Claude Code CLI', status: 'pass', message: versionStr };
350
- }
351
- catch {
352
- return {
353
- name: 'Claude Code CLI',
354
- status: 'warn',
355
- message: 'Not installed',
356
- fix: 'npm install -g @anthropic-ai/claude-code'
357
- };
358
- }
359
- }
360
- // Install Claude Code CLI
361
- async function installClaudeCode() {
362
- try {
363
- output.writeln();
364
- output.writeln(output.bold('Installing Claude Code CLI...'));
365
- execSync('npm install -g @anthropic-ai/claude-code', {
366
- encoding: 'utf8',
367
- stdio: 'inherit',
368
- windowsHide: true
369
- });
370
- output.writeln(output.success('Claude Code CLI installed successfully!'));
371
- return true;
372
- }
373
- catch (error) {
374
- output.writeln(output.error('Failed to install Claude Code CLI'));
375
- if (error instanceof Error) {
376
- output.writeln(output.dim(error.message));
377
- }
378
- return false;
379
- }
380
- }
381
- // Check embeddings / vector index health
382
- async function checkEmbeddings() {
383
- const dbPaths = [
384
- join(process.cwd(), '.swarm', 'memory.db'),
385
- join(process.cwd(), '.claude-flow', 'memory.db'),
386
- join(process.cwd(), 'data', 'memory.db'),
387
- ];
388
- // 1. Fast path: read cached vector-stats.json if available
389
- const statsPath = join(process.cwd(), '.claude-flow', 'vector-stats.json');
390
- try {
391
- if (existsSync(statsPath)) {
392
- const stats = JSON.parse(readFileSync(statsPath, 'utf8'));
393
- const count = stats.vectorCount ?? 0;
394
- const hasHnsw = stats.hasHnsw ?? false;
395
- const dbSizeKB = stats.dbSizeKB ?? 0;
396
- if (count === 0) {
397
- return {
398
- name: 'Embeddings',
399
- status: 'warn',
400
- message: `Memory DB exists (${dbSizeKB} KB) but 0 vectors indexed — documents not embedded`,
401
- fix: 'npx moflo memory init --force && npx moflo embeddings init'
402
- };
403
- }
404
- const hnswLabel = hasHnsw ? ', HNSW' : '';
405
- return {
406
- name: 'Embeddings',
407
- status: 'pass',
408
- message: `${count} vectors indexed (${dbSizeKB} KB${hnswLabel})`
409
- };
410
- }
411
- }
412
- catch {
413
- // Stats file unreadable — fall through to DB check
414
- }
415
- // 2. Check if memory DB file exists at all
416
- let foundDbPath = null;
417
- for (const p of dbPaths) {
418
- if (existsSync(p)) {
419
- foundDbPath = p;
420
- break;
421
- }
422
- }
423
- if (!foundDbPath) {
424
- return {
425
- name: 'Embeddings',
426
- status: 'warn',
427
- message: 'No memory database — embeddings not initialized',
428
- fix: 'npx moflo memory init --force'
429
- };
430
- }
431
- // 3. DB exists but no stats cache — try querying the DB for entry count
432
- try {
433
- const { checkMemoryInitialization } = await import('../memory/memory-initializer.js');
434
- const info = await checkMemoryInitialization(foundDbPath);
435
- if (!info.initialized) {
436
- return {
437
- name: 'Embeddings',
438
- status: 'warn',
439
- message: 'Memory DB exists but not properly initialized',
440
- fix: 'npx moflo memory init --force'
441
- };
442
- }
443
- const hasVectors = info.features?.vectorEmbeddings ?? false;
444
- if (!hasVectors) {
445
- return {
446
- name: 'Embeddings',
447
- status: 'warn',
448
- message: `Memory DB initialized (v${info.version}) but no vector_indexes table`,
449
- fix: 'npx moflo memory init --force && npx moflo embeddings init'
450
- };
451
- }
452
- return {
453
- name: 'Embeddings',
454
- status: 'pass',
455
- message: `Memory DB initialized (v${info.version}, vectors enabled)`
456
- };
457
- }
458
- catch {
459
- // sql.js not available — fall back to file-size heuristic
460
- try {
461
- const stats = statSync(foundDbPath);
462
- const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
463
- return {
464
- name: 'Embeddings',
465
- status: 'warn',
466
- message: `Memory DB exists (${sizeMB} MB) — cannot verify vectors (sql.js not available)`,
467
- fix: 'npm install sql.js && npx moflo embeddings init'
468
- };
469
- }
470
- catch {
471
- return { name: 'Embeddings', status: 'warn', message: 'Unable to check' };
472
- }
473
- }
474
- }
475
- /**
476
- * Auto-fix: execute fix commands for a failed/warned health check.
477
- * Returns true if the fix succeeded (re-check should pass).
478
- */
479
- async function autoFixCheck(check) {
480
- if (!check.fix)
481
- return false;
482
- // Map checks to programmatic fixes (not just shell commands)
483
- const fixActions = {
484
- 'Memory Database': async () => {
485
- try {
486
- const swarmDir = join(process.cwd(), '.swarm');
487
- if (!existsSync(swarmDir))
488
- mkdirSync(swarmDir, { recursive: true });
489
- const { initializeMemoryDatabase } = await import('../memory/memory-initializer.js');
490
- const result = await initializeMemoryDatabase({ force: true, verbose: false });
491
- return result.success;
492
- }
493
- catch {
494
- // Fall back to CLI
495
- return runFixCommand('npx moflo memory init --force');
496
- }
497
- },
498
- 'Embeddings': async () => {
499
- try {
500
- // Step 1: ensure memory DB exists
501
- const swarmDir = join(process.cwd(), '.swarm');
502
- if (!existsSync(swarmDir))
503
- mkdirSync(swarmDir, { recursive: true });
504
- const dbPath = join(swarmDir, 'memory.db');
505
- if (!existsSync(dbPath)) {
506
- const { initializeMemoryDatabase } = await import('../memory/memory-initializer.js');
507
- await initializeMemoryDatabase({ force: true, verbose: false });
508
- }
509
- // Step 2: attempt embeddings init via CLI
510
- return runFixCommand('npx moflo embeddings init --force');
511
- }
512
- catch {
513
- return runFixCommand('npx moflo memory init --force');
514
- }
515
- },
516
- 'Config File': async () => {
517
- try {
518
- const cfDir = join(process.cwd(), '.claude-flow');
519
- if (!existsSync(cfDir))
520
- mkdirSync(cfDir, { recursive: true });
521
- return runFixCommand('npx moflo config init');
522
- }
523
- catch {
524
- return false;
525
- }
526
- },
527
- 'Daemon Status': async () => {
528
- // Clean stale locks, then try to start daemon
529
- const lockFile = join(process.cwd(), '.claude-flow', 'daemon.lock');
530
- const pidFile = join(process.cwd(), '.claude-flow', 'daemon.pid');
531
- try {
532
- if (existsSync(lockFile)) {
533
- const { unlinkSync } = await import('fs');
534
- unlinkSync(lockFile);
535
- }
536
- if (existsSync(pidFile)) {
537
- const { unlinkSync } = await import('fs');
538
- unlinkSync(pidFile);
539
- }
540
- }
541
- catch { /* best effort */ }
542
- return runFixCommand('npx moflo daemon start');
543
- },
544
- 'MCP Servers': async () => {
545
- return runFixCommand('claude mcp add moflo -- npx -y moflo mcp start');
546
- },
547
- 'Claude Code CLI': async () => {
548
- return installClaudeCode();
549
- },
550
- 'Zombie Processes': async () => {
551
- const result = await findZombieProcesses(true);
552
- return result.killed > 0 || result.found === 0;
553
- },
554
- };
555
- const fixFn = fixActions[check.name];
556
- if (fixFn) {
557
- try {
558
- output.writeln(output.dim(` Fixing: ${check.name}...`));
559
- const success = await fixFn();
560
- if (success) {
561
- output.writeln(output.success(` Fixed: ${check.name}`));
562
- }
563
- else {
564
- output.writeln(output.warning(` Fix attempted but may need manual action: ${check.fix}`));
565
- }
566
- return success;
567
- }
568
- catch (e) {
569
- output.writeln(output.warning(` Fix failed: ${e instanceof Error ? e.message : String(e)}`));
570
- return false;
571
- }
572
- }
573
- // Generic: try running the fix command directly if it looks like a shell command
574
- if (check.fix.startsWith('npx ') || check.fix.startsWith('npm ') || check.fix.startsWith('claude ')) {
575
- return runFixCommand(check.fix);
576
- }
577
- return false;
578
- }
579
- /**
580
- * Run a shell command as a fix action. Returns true on exit code 0.
581
- */
582
- async function runFixCommand(cmd) {
583
- try {
584
- await execAsync(cmd, {
585
- encoding: 'utf8',
586
- timeout: 30000,
587
- shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/sh',
588
- env: { ...process.env },
589
- windowsHide: true,
590
- });
591
- return true;
592
- }
593
- catch {
594
- return false;
595
- }
596
- }
597
- // Check test directories configured in moflo.yaml
598
- async function checkTestDirs() {
599
- const yamlPath = join(process.cwd(), 'moflo.yaml');
600
- if (!existsSync(yamlPath)) {
601
- return { name: 'Test Directories', status: 'warn', message: 'No moflo.yaml — test indexing unconfigured', fix: 'npx moflo init' };
602
- }
603
- try {
604
- const content = readFileSync(yamlPath, 'utf-8');
605
- // Check if tests section exists
606
- const testsBlock = content.match(/tests:\s*\n\s+directories:\s*\n((?:\s+-\s+.+\n?)+)/);
607
- if (!testsBlock) {
608
- return { name: 'Test Directories', status: 'warn', message: 'No tests section in moflo.yaml', fix: 'npx moflo init --force' };
609
- }
610
- // Extract configured directories
611
- const items = testsBlock[1].match(/-\s+(.+)/g);
612
- if (!items || items.length === 0) {
613
- return { name: 'Test Directories', status: 'warn', message: 'Empty test directories list' };
614
- }
615
- const dirs = items.map(item => item.replace(/^-\s+/, '').trim());
616
- const existing = dirs.filter(d => existsSync(join(process.cwd(), d)));
617
- const missing = dirs.filter(d => !existsSync(join(process.cwd(), d)));
618
- // Check auto_index.tests flag
619
- const autoIndexMatch = content.match(/auto_index:\s*\n(?:.*\n)*?\s+tests:\s*(true|false)/);
620
- const autoIndexEnabled = !autoIndexMatch || autoIndexMatch[1] !== 'false';
621
- const indexLabel = autoIndexEnabled ? 'auto-index: on' : 'auto-index: off';
622
- if (missing.length > 0 && existing.length === 0) {
623
- return {
624
- name: 'Test Directories',
625
- status: 'warn',
626
- message: `No configured test dirs exist: ${missing.join(', ')} (${indexLabel})`,
627
- };
628
- }
629
- if (missing.length > 0) {
630
- return {
631
- name: 'Test Directories',
632
- status: 'warn',
633
- message: `${existing.length} OK, ${missing.length} missing: ${missing.join(', ')} (${indexLabel})`,
634
- };
635
- }
636
- return { name: 'Test Directories', status: 'pass', message: `${existing.length} directories: ${existing.join(', ')} (${indexLabel})` };
637
- }
638
- catch {
639
- return { name: 'Test Directories', status: 'warn', message: 'Unable to parse moflo.yaml' };
640
- }
641
- }
642
- // Check agentic-flow v3 integration (filesystem-based to avoid slow WASM/DB init)
643
- async function checkAgenticFlow() {
644
- try {
645
- // Walk common node_modules paths to find agentic-flow/package.json
646
- const candidates = [
647
- join(process.cwd(), 'node_modules', 'agentic-flow', 'package.json'),
648
- join(process.cwd(), '..', 'node_modules', 'agentic-flow', 'package.json'),
649
- ];
650
- let pkgJsonPath = null;
651
- for (const p of candidates) {
652
- if (existsSync(p)) {
653
- pkgJsonPath = p;
654
- break;
655
- }
656
- }
657
- if (!pkgJsonPath) {
658
- return {
659
- name: 'agentic-flow',
660
- status: 'warn',
661
- message: 'Not installed (optional — embeddings/routing will use fallbacks)',
662
- fix: 'npm install agentic-flow@latest'
663
- };
664
- }
665
- const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8'));
666
- const version = pkg.version || 'unknown';
667
- const exports = pkg.exports || {};
668
- const features = [
669
- exports['./reasoningbank'] ? 'ReasoningBank' : null,
670
- exports['./router'] ? 'Router' : null,
671
- exports['./transport/quic'] ? 'QUIC' : null,
672
- ].filter(Boolean);
673
- return {
674
- name: 'agentic-flow',
675
- status: 'pass',
676
- message: `v${version} (${features.join(', ')})`
677
- };
678
- }
679
- catch {
680
- return { name: 'agentic-flow', status: 'warn', message: 'Check failed' };
681
- }
682
- }
683
- // Check whether a given PID is still running.
684
- // Uses signal 0 which works cross-platform (Windows, Linux, macOS) without
685
- // needing PowerShell or /proc — Node handles the platform abstraction.
686
- function isProcessAlive(pid) {
687
- try {
688
- process.kill(pid, 0);
689
- return true;
690
- }
691
- catch {
692
- return false;
693
- }
694
- }
695
- // Fast path: kill processes tracked in the shared ProcessManager registry.
696
- // This avoids the expensive OS-level process scan for known background tasks.
697
- function killTrackedProcesses() {
698
- const registryFile = join(process.cwd(), '.claude-flow', 'background-pids.json');
699
- const lockFile = join(process.cwd(), '.claude-flow', 'spawn.lock');
700
- let killed = 0;
701
- try {
702
- if (existsSync(registryFile)) {
703
- const entries = JSON.parse(readFileSync(registryFile, 'utf-8'));
704
- for (const entry of entries) {
705
- if (!isProcessAlive(entry.pid))
706
- continue;
707
- try {
708
- if (process.platform === 'win32') {
709
- execSync(`taskkill /F /PID ${entry.pid}`, { timeout: 5000, windowsHide: true });
710
- }
711
- else {
712
- process.kill(entry.pid, 'SIGKILL');
713
- }
714
- killed++;
715
- }
716
- catch { /* already gone */ }
717
- }
718
- // Clear registry
719
- writeFileSync(registryFile, '[]');
720
- }
721
- }
722
- catch { /* non-fatal */ }
723
- // Remove spawn lock
724
- try {
725
- if (existsSync(lockFile))
726
- unlinkSync(lockFile);
727
- }
728
- catch { /* ok */ }
729
- return killed;
730
- }
731
- // Find and optionally kill orphaned moflo/claude-flow node processes.
732
- // A process is only "orphaned" if its parent is no longer alive — meaning
733
- // nothing will clean it up. MCP servers spawned by a live Claude Code session
734
- // have a live parent (claude.exe) and must not be flagged.
735
- async function findZombieProcesses(kill = false) {
736
- const legitimatePid = getDaemonLockHolder(process.cwd());
737
- const currentPid = process.pid;
738
- const parentPid = process.ppid;
739
- const found = [];
740
- let killed = 0;
741
- // Collect candidates as { pid, ppid } so we can check parent liveness
742
- const candidates = [];
743
- try {
744
- if (process.platform === 'win32') {
745
- // Windows: include ParentProcessId so we can verify orphan status
746
- const result = execSync('powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"Name=\'node.exe\'\\" | Select-Object ProcessId,ParentProcessId,CommandLine | Format-Table -AutoSize -Wrap"', { encoding: 'utf-8', timeout: 10000, windowsHide: true });
747
- const lines = result.split('\n');
748
- for (const line of lines) {
749
- if (/moflo|claude-flow|flo\s+(hooks|gate|mcp|daemon)/i.test(line)) {
750
- // Format-Table columns: ProcessId ParentProcessId CommandLine...
751
- const match = line.match(/^\s*(\d+)\s+(\d+)/);
752
- if (match) {
753
- candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
754
- }
755
- }
756
- }
757
- }
758
- else {
759
- // Unix/macOS: use ps with explicit PID+PPID columns for reliable parsing
760
- const result = execSync('ps -eo pid,ppid,command | grep -E "node.*(moflo|claude-flow)" | grep -v grep', { encoding: 'utf-8', timeout: 5000 });
761
- const lines = result.trim().split('\n');
762
- for (const line of lines) {
763
- const match = line.trim().match(/^(\d+)\s+(\d+)/);
764
- if (match) {
765
- candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
766
- }
767
- }
768
- }
769
- }
770
- catch {
771
- // No matches found (grep exits non-zero) or command failed
772
- }
773
- // Filter: skip known-good PIDs and processes whose parent is still alive.
774
- // A live parent (e.g. claude.exe for MCP servers) means the process is managed, not orphaned.
775
- for (const { pid, ppid } of candidates) {
776
- if (pid === currentPid || pid === parentPid || pid === legitimatePid)
777
- continue;
778
- if (isProcessAlive(ppid))
779
- continue;
780
- // Defense-in-depth: detached daemons have dead parents by design.
781
- // Even if the lock file is missing/corrupted, don't kill a running daemon.
782
- if (isDaemonProcess(pid))
783
- continue;
784
- found.push(pid);
785
- }
786
- if (kill && found.length > 0) {
787
- for (const pid of found) {
788
- try {
789
- if (process.platform === 'win32') {
790
- execSync(`taskkill /F /PID ${pid}`, { timeout: 5000, windowsHide: true });
791
- }
792
- else {
793
- process.kill(pid, 'SIGKILL');
794
- }
795
- killed++;
796
- }
797
- catch {
798
- // Process may have already exited
799
- }
800
- }
801
- // Clean up stale daemon lock if we killed the holder
802
- if (legitimatePid && found.includes(legitimatePid)) {
803
- releaseDaemonLock(process.cwd(), legitimatePid, true);
804
- }
805
- }
806
- return { found: found.length, killed, pids: found };
807
- }
808
- // Format health check result
809
- function formatCheck(check) {
810
- const icon = check.status === 'pass' ? output.success('✓') :
811
- check.status === 'warn' ? output.warning('⚠') :
812
- output.error('');
813
- return `${icon} ${check.name}: ${check.message}`;
814
- }
815
- // Main doctor command
816
- export const doctorCommand = {
817
- name: 'doctor',
818
- description: 'System diagnostics and health checks',
819
- options: [
820
- {
821
- name: 'fix',
822
- short: 'f',
823
- description: 'Automatically fix issues where possible',
824
- type: 'boolean',
825
- default: false
826
- },
827
- {
828
- name: 'install',
829
- short: 'i',
830
- description: 'Auto-install missing dependencies (Claude Code CLI)',
831
- type: 'boolean',
832
- default: false
833
- },
834
- {
835
- name: 'component',
836
- short: 'c',
837
- description: 'Check specific component (version, node, npm, config, daemon, memory, embeddings, git, mcp, claude, disk, typescript)',
838
- type: 'string'
839
- },
840
- {
841
- name: 'verbose',
842
- short: 'v',
843
- description: 'Verbose output',
844
- type: 'boolean',
845
- default: false
846
- },
847
- {
848
- name: 'kill-zombies',
849
- short: 'k',
850
- description: 'Find and kill orphaned moflo/claude-flow node processes',
851
- type: 'boolean',
852
- default: false
853
- }
854
- ],
855
- examples: [
856
- { command: 'claude-flow doctor', description: 'Run full health check' },
857
- { command: 'claude-flow doctor --fix', description: 'Show fixes for issues' },
858
- { command: 'claude-flow doctor --install', description: 'Auto-install missing dependencies' },
859
- { command: 'claude-flow doctor --kill-zombies', description: 'Find and kill zombie processes' },
860
- { command: 'claude-flow doctor -c version', description: 'Check for stale npx cache' },
861
- { command: 'claude-flow doctor -c claude', description: 'Check Claude Code CLI only' }
862
- ],
863
- action: async (ctx) => {
864
- const showFix = ctx.flags.fix;
865
- const autoInstall = ctx.flags.install;
866
- const component = ctx.flags.component;
867
- const verbose = ctx.flags.verbose;
868
- const killZombies = ctx.flags['kill-zombies'];
869
- output.writeln();
870
- output.writeln(output.bold('MoFlo Doctor'));
871
- output.writeln(output.dim('System diagnostics and health check'));
872
- output.writeln(output.dim('─'.repeat(50)));
873
- output.writeln();
874
- // Handle --kill-zombies early
875
- if (killZombies) {
876
- output.writeln(output.bold('Zombie Process Scan'));
877
- output.writeln();
878
- // Fast path: kill tracked processes from the shared registry first
879
- const registryKilled = killTrackedProcesses();
880
- if (registryKilled > 0) {
881
- output.writeln(output.success(` Killed ${registryKilled} tracked background process(es) from registry`));
882
- }
883
- // Slow path: OS-level scan for any remaining orphans
884
- const scan = await findZombieProcesses(false);
885
- if (scan.found === 0) {
886
- if (registryKilled === 0) {
887
- output.writeln(output.success(' No orphaned moflo processes found'));
888
- }
889
- }
890
- else {
891
- output.writeln(output.warning(` Found ${scan.found} additional orphaned process(es): PIDs ${scan.pids.join(', ')}`));
892
- // Kill them
893
- const result = await findZombieProcesses(true);
894
- if (result.killed > 0) {
895
- output.writeln(output.success(` Killed ${result.killed} zombie process(es)`));
896
- }
897
- if (result.killed < result.found) {
898
- output.writeln(output.warning(` ${result.found - result.killed} process(es) could not be killed`));
899
- }
900
- }
901
- output.writeln();
902
- output.writeln(output.dim('─'.repeat(50)));
903
- output.writeln();
904
- }
905
- const checkZombieProcesses = async () => {
906
- try {
907
- const scan = await findZombieProcesses(false);
908
- if (scan.found === 0) {
909
- return { name: 'Zombie Processes', status: 'pass', message: 'No orphaned processes' };
910
- }
911
- return {
912
- name: 'Zombie Processes',
913
- status: 'warn',
914
- message: `${scan.found} orphaned process(es) (PIDs: ${scan.pids.join(', ')})`,
915
- fix: 'moflo doctor --kill-zombies'
916
- };
917
- }
918
- catch {
919
- return { name: 'Zombie Processes', status: 'pass', message: 'Check skipped' };
920
- }
921
- };
922
- const allChecks = [
923
- checkVersionFreshness,
924
- checkNodeVersion,
925
- checkNpmVersion,
926
- checkClaudeCode,
927
- checkGit,
928
- checkGitRepo,
929
- checkConfigFile,
930
- checkDaemonStatus,
931
- checkMemoryDatabase,
932
- checkEmbeddings,
933
- checkTestDirs,
934
- checkMcpServers,
935
- checkDiskSpace,
936
- checkBuildTools,
937
- checkAgenticFlow,
938
- checkZombieProcesses
939
- ];
940
- const componentMap = {
941
- 'version': checkVersionFreshness,
942
- 'freshness': checkVersionFreshness,
943
- 'node': checkNodeVersion,
944
- 'npm': checkNpmVersion,
945
- 'claude': checkClaudeCode,
946
- 'config': checkConfigFile,
947
- 'daemon': checkDaemonStatus,
948
- 'memory': checkMemoryDatabase,
949
- 'embeddings': checkEmbeddings,
950
- 'git': checkGit,
951
- 'mcp': checkMcpServers,
952
- 'disk': checkDiskSpace,
953
- 'typescript': checkBuildTools,
954
- 'tests': checkTestDirs,
955
- 'agentic-flow': checkAgenticFlow
956
- };
957
- let checksToRun = allChecks;
958
- if (component && componentMap[component]) {
959
- checksToRun = [componentMap[component]];
960
- }
961
- const results = [];
962
- const fixes = [];
963
- // OPTIMIZATION: Run all checks in parallel for 3-5x faster execution
964
- const spinner = output.createSpinner({ text: 'Running health checks in parallel...', spinner: 'dots' });
965
- spinner.start();
966
- try {
967
- // Execute all checks concurrently
968
- const checkResults = await Promise.allSettled(checksToRun.map(check => check()));
969
- spinner.stop();
970
- // Process results in order
971
- for (const settledResult of checkResults) {
972
- if (settledResult.status === 'fulfilled') {
973
- const result = settledResult.value;
974
- results.push(result);
975
- output.writeln(formatCheck(result));
976
- if (result.fix && (result.status === 'fail' || result.status === 'warn')) {
977
- fixes.push(`${result.name}: ${result.fix}`);
978
- }
979
- }
980
- else {
981
- const errorResult = {
982
- name: 'Check',
983
- status: 'fail',
984
- message: settledResult.reason?.message || 'Unknown error'
985
- };
986
- results.push(errorResult);
987
- output.writeln(formatCheck(errorResult));
988
- }
989
- }
990
- }
991
- catch (error) {
992
- spinner.stop();
993
- output.writeln(output.error('Failed to run health checks'));
994
- }
995
- // Auto-install missing dependencies if requested
996
- if (autoInstall) {
997
- const claudeCodeResult = results.find(r => r.name === 'Claude Code CLI');
998
- if (claudeCodeResult && claudeCodeResult.status !== 'pass') {
999
- const installed = await installClaudeCode();
1000
- if (installed) {
1001
- // Re-check Claude Code after installation
1002
- const newCheck = await checkClaudeCode();
1003
- const idx = results.findIndex(r => r.name === 'Claude Code CLI');
1004
- if (idx !== -1) {
1005
- results[idx] = newCheck;
1006
- // Update fixes list
1007
- const fixIdx = fixes.findIndex(f => f.startsWith('Claude Code CLI:'));
1008
- if (fixIdx !== -1 && newCheck.status === 'pass') {
1009
- fixes.splice(fixIdx, 1);
1010
- }
1011
- }
1012
- output.writeln(formatCheck(newCheck));
1013
- }
1014
- }
1015
- }
1016
- // Summary
1017
- const passed = results.filter(r => r.status === 'pass').length;
1018
- const warnings = results.filter(r => r.status === 'warn').length;
1019
- const failed = results.filter(r => r.status === 'fail').length;
1020
- output.writeln();
1021
- output.writeln(output.dim('─'.repeat(50)));
1022
- output.writeln();
1023
- const summaryParts = [
1024
- output.success(`${passed} passed`),
1025
- warnings > 0 ? output.warning(`${warnings} warnings`) : null,
1026
- failed > 0 ? output.error(`${failed} failed`) : null
1027
- ].filter(Boolean);
1028
- output.writeln(`Summary: ${summaryParts.join(', ')}`);
1029
- // Auto-fix or show fixes
1030
- if (showFix && fixes.length > 0) {
1031
- output.writeln();
1032
- output.writeln(output.bold('Auto-fixing issues...'));
1033
- output.writeln();
1034
- const fixableResults = results.filter(r => r.fix && (r.status === 'fail' || r.status === 'warn'));
1035
- let fixed = 0;
1036
- const unfixed = [];
1037
- for (const check of fixableResults) {
1038
- const success = await autoFixCheck(check);
1039
- if (success) {
1040
- fixed++;
1041
- }
1042
- else {
1043
- unfixed.push(`${check.name}: ${check.fix}`);
1044
- }
1045
- }
1046
- if (fixed > 0) {
1047
- output.writeln();
1048
- output.writeln(output.success(`Auto-fixed ${fixed} issue${fixed > 1 ? 's' : ''}`));
1049
- }
1050
- if (unfixed.length > 0) {
1051
- output.writeln();
1052
- output.writeln(output.bold('Manual fixes needed:'));
1053
- for (const fix of unfixed) {
1054
- output.writeln(output.dim(` ${fix}`));
1055
- }
1056
- }
1057
- // Re-run checks to show updated status
1058
- if (fixed > 0) {
1059
- output.writeln();
1060
- output.writeln(output.dim('Re-checking...'));
1061
- output.writeln();
1062
- const reResults = await Promise.allSettled(checksToRun.map(check => check()));
1063
- let rePassed = 0, reWarnings = 0, reFailed = 0;
1064
- for (const sr of reResults) {
1065
- if (sr.status === 'fulfilled') {
1066
- output.writeln(formatCheck(sr.value));
1067
- if (sr.value.status === 'pass')
1068
- rePassed++;
1069
- else if (sr.value.status === 'warn')
1070
- reWarnings++;
1071
- else
1072
- reFailed++;
1073
- }
1074
- }
1075
- output.writeln();
1076
- output.writeln(output.dim(''.repeat(50)));
1077
- const reSummary = [
1078
- output.success(`${rePassed} passed`),
1079
- reWarnings > 0 ? output.warning(`${reWarnings} warnings`) : null,
1080
- reFailed > 0 ? output.error(`${reFailed} failed`) : null
1081
- ].filter(Boolean);
1082
- output.writeln(`After fix: ${reSummary.join(', ')}`);
1083
- }
1084
- }
1085
- else if (fixes.length > 0 && !showFix) {
1086
- output.writeln();
1087
- output.writeln(output.dim(`Run with --fix to auto-fix ${fixes.length} issue${fixes.length > 1 ? 's' : ''}`));
1088
- }
1089
- // Overall result
1090
- if (failed > 0) {
1091
- output.writeln();
1092
- output.writeln(output.error('Some checks failed. Please address the issues above.'));
1093
- return { success: false, exitCode: 1, data: { passed, warnings, failed, results } };
1094
- }
1095
- else if (warnings > 0) {
1096
- output.writeln();
1097
- output.writeln(output.warning('All checks passed with some warnings.'));
1098
- return { success: true, data: { passed, warnings, failed, results } };
1099
- }
1100
- else {
1101
- output.writeln();
1102
- output.writeln(output.success('All checks passed! System is healthy.'));
1103
- return { success: true, data: { passed, warnings, failed, results } };
1104
- }
1105
- }
1106
- };
1107
- export default doctorCommand;
1
+ /**
2
+ * V3 CLI Doctor Command
3
+ * System diagnostics, dependency checks, config validation
4
+ *
5
+ * Created with motailz.com
6
+ */
7
+ import { output } from '../output.js';
8
+ import { existsSync, readFileSync, writeFileSync, unlinkSync, statSync, mkdirSync } from 'fs';
9
+ import { join, dirname } from 'path';
10
+ import { fileURLToPath } from 'url';
11
+ import { execSync, exec } from 'child_process';
12
+ import { promisify } from 'util';
13
+ import { getDaemonLockHolder, releaseDaemonLock, isDaemonProcess } from '../services/daemon-lock.js';
14
+ // Promisified exec with proper shell and env inheritance for cross-platform support
15
+ const execAsync = promisify(exec);
16
+ /**
17
+ * Execute command asynchronously with proper environment inheritance
18
+ * Critical for Windows where PATH may not be inherited properly
19
+ */
20
+ async function runCommand(command, timeoutMs = 5000) {
21
+ const { stdout } = await execAsync(command, {
22
+ encoding: 'utf8',
23
+ timeout: timeoutMs,
24
+ shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/sh', // Use proper shell per platform
25
+ env: { ...process.env }, // Explicitly inherit full environment
26
+ windowsHide: true, // Hide window on Windows
27
+ });
28
+ return stdout.trim();
29
+ }
30
+ // Check Node.js version
31
+ async function checkNodeVersion() {
32
+ const requiredMajor = 20;
33
+ const version = process.version;
34
+ const major = parseInt(version.slice(1).split('.')[0], 10);
35
+ if (major >= requiredMajor) {
36
+ return { name: 'Node.js Version', status: 'pass', message: `${version} (>= ${requiredMajor} required)` };
37
+ }
38
+ else if (major >= 18) {
39
+ return { name: 'Node.js Version', status: 'warn', message: `${version} (>= ${requiredMajor} recommended)`, fix: 'nvm install 20 && nvm use 20' };
40
+ }
41
+ else {
42
+ return { name: 'Node.js Version', status: 'fail', message: `${version} (>= ${requiredMajor} required)`, fix: 'nvm install 20 && nvm use 20' };
43
+ }
44
+ }
45
+ // Check npm version (async with proper env inheritance)
46
+ async function checkNpmVersion() {
47
+ try {
48
+ const version = await runCommand('npm --version');
49
+ const major = parseInt(version.split('.')[0], 10);
50
+ if (major >= 9) {
51
+ return { name: 'npm Version', status: 'pass', message: `v${version}` };
52
+ }
53
+ else {
54
+ return { name: 'npm Version', status: 'warn', message: `v${version} (>= 9 recommended)`, fix: 'npm install -g npm@latest' };
55
+ }
56
+ }
57
+ catch {
58
+ return { name: 'npm Version', status: 'fail', message: 'npm not found', fix: 'Install Node.js from https://nodejs.org' };
59
+ }
60
+ }
61
+ // Check config file
62
+ async function checkConfigFile() {
63
+ // JSON configs (parse-validated)
64
+ const jsonPaths = [
65
+ '.claude-flow/config.json',
66
+ 'claude-flow.config.json',
67
+ '.claude-flow.json'
68
+ ];
69
+ for (const configPath of jsonPaths) {
70
+ if (existsSync(configPath)) {
71
+ try {
72
+ const content = readFileSync(configPath, 'utf8');
73
+ JSON.parse(content);
74
+ return { name: 'Config File', status: 'pass', message: `Found: ${configPath}` };
75
+ }
76
+ catch (e) {
77
+ return { name: 'Config File', status: 'fail', message: `Invalid JSON: ${configPath}`, fix: 'Fix JSON syntax in config file' };
78
+ }
79
+ }
80
+ }
81
+ // YAML configs (existence-checked only — no heavy yaml parser dependency)
82
+ const yamlPaths = [
83
+ '.claude-flow/config.yaml',
84
+ '.claude-flow/config.yml',
85
+ 'claude-flow.config.yaml'
86
+ ];
87
+ for (const configPath of yamlPaths) {
88
+ if (existsSync(configPath)) {
89
+ return { name: 'Config File', status: 'pass', message: `Found: ${configPath}` };
90
+ }
91
+ }
92
+ return { name: 'Config File', status: 'warn', message: 'No config file (using defaults)', fix: 'claude-flow config init' };
93
+ }
94
+ // Check daemon status — delegates to daemon-lock module for proper
95
+ // PID + command-line verification (avoids Windows PID-recycling false positives).
96
+ async function checkDaemonStatus() {
97
+ try {
98
+ // Retry up to 5 times with 1s delay — the daemon starts in the background
99
+ // during session-start and may not have acquired its lock file yet.
100
+ const MAX_RETRIES = 5;
101
+ const RETRY_DELAY_MS = 1000;
102
+ let holderPid = null;
103
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
104
+ holderPid = getDaemonLockHolder(process.cwd());
105
+ if (holderPid)
106
+ break;
107
+ if (attempt < MAX_RETRIES - 1) {
108
+ await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
109
+ }
110
+ }
111
+ if (holderPid) {
112
+ return { name: 'Daemon Status', status: 'pass', message: `Running (PID: ${holderPid})` };
113
+ }
114
+ // getDaemonLockHolder auto-cleans stale locks, but check for legacy PID file
115
+ const lockFile = '.claude-flow/daemon.lock';
116
+ if (existsSync(lockFile)) {
117
+ // Lock exists but holder is null — getDaemonLockHolder already cleaned it,
118
+ // but if it persists it means cleanup failed (permissions, etc.)
119
+ return { name: 'Daemon Status', status: 'warn', message: 'Stale lock file', fix: 'rm .claude-flow/daemon.lock && claude-flow daemon start' };
120
+ }
121
+ // Also check legacy PID file
122
+ const pidFile = '.claude-flow/daemon.pid';
123
+ if (existsSync(pidFile)) {
124
+ return { name: 'Daemon Status', status: 'warn', message: 'Legacy PID file found', fix: 'rm .claude-flow/daemon.pid && claude-flow daemon start' };
125
+ }
126
+ return { name: 'Daemon Status', status: 'warn', message: 'Not running', fix: 'claude-flow daemon start' };
127
+ }
128
+ catch {
129
+ return { name: 'Daemon Status', status: 'warn', message: 'Unable to check', fix: 'claude-flow daemon status' };
130
+ }
131
+ }
132
+ // Check memory database
133
+ async function checkMemoryDatabase() {
134
+ const dbPaths = [
135
+ '.claude-flow/memory.db',
136
+ '.swarm/memory.db',
137
+ 'data/memory.db'
138
+ ];
139
+ for (const dbPath of dbPaths) {
140
+ if (existsSync(dbPath)) {
141
+ try {
142
+ const stats = statSync(dbPath);
143
+ const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
144
+ return { name: 'Memory Database', status: 'pass', message: `${dbPath} (${sizeMB} MB)` };
145
+ }
146
+ catch {
147
+ return { name: 'Memory Database', status: 'warn', message: `${dbPath} (unable to stat)` };
148
+ }
149
+ }
150
+ }
151
+ return { name: 'Memory Database', status: 'warn', message: 'Not initialized', fix: 'claude-flow memory configure --backend hybrid' };
152
+ }
153
+ // Check git (async with proper env inheritance)
154
+ async function checkGit() {
155
+ try {
156
+ const version = await runCommand('git --version');
157
+ return { name: 'Git', status: 'pass', message: version.replace('git version ', 'v') };
158
+ }
159
+ catch {
160
+ return { name: 'Git', status: 'warn', message: 'Not installed', fix: 'Install git from https://git-scm.com' };
161
+ }
162
+ }
163
+ // Check if in git repo (async with proper env inheritance)
164
+ async function checkGitRepo() {
165
+ try {
166
+ await runCommand('git rev-parse --git-dir');
167
+ return { name: 'Git Repository', status: 'pass', message: 'In a git repository' };
168
+ }
169
+ catch {
170
+ return { name: 'Git Repository', status: 'warn', message: 'Not a git repository', fix: 'git init' };
171
+ }
172
+ }
173
+ // Check MCP servers
174
+ async function checkMcpServers() {
175
+ const mcpConfigPaths = [
176
+ join(process.env.HOME || '', '.claude/claude_desktop_config.json'),
177
+ join(process.env.HOME || '', '.config/claude/mcp.json'),
178
+ '.mcp.json'
179
+ ];
180
+ for (const configPath of mcpConfigPaths) {
181
+ if (existsSync(configPath)) {
182
+ try {
183
+ const content = JSON.parse(readFileSync(configPath, 'utf8'));
184
+ const servers = content.mcpServers || content.servers || {};
185
+ const count = Object.keys(servers).length;
186
+ const hasClaudeFlow = 'moflo' in servers || 'claude-flow' in servers || 'claude-flow_alpha' in servers || 'ruflo' in servers || 'ruflo_alpha' in servers;
187
+ if (hasClaudeFlow) {
188
+ return { name: 'MCP Servers', status: 'pass', message: `${count} servers (flo configured)` };
189
+ }
190
+ else {
191
+ return { name: 'MCP Servers', status: 'warn', message: `${count} servers (flo not found)`, fix: 'claude mcp add ruflo -- npx -y ruflo@latest mcp start' };
192
+ }
193
+ }
194
+ catch {
195
+ // continue to next path
196
+ }
197
+ }
198
+ }
199
+ return { name: 'MCP Servers', status: 'warn', message: 'No MCP config found', fix: 'claude mcp add moflo npx moflo mcp start' };
200
+ }
201
+ // Check disk space (async with proper env inheritance)
202
+ async function checkDiskSpace() {
203
+ try {
204
+ if (process.platform === 'win32') {
205
+ return { name: 'Disk Space', status: 'pass', message: 'Check skipped on Windows' };
206
+ }
207
+ // Use df -Ph for POSIX mode (guarantees single-line output even with long device names)
208
+ const output_str = await runCommand('df -Ph . | tail -1');
209
+ const parts = output_str.split(/\s+/);
210
+ // POSIX format: Filesystem Size Used Avail Capacity Mounted
211
+ const available = parts[3];
212
+ const usePercent = parseInt(parts[4]?.replace('%', '') || '0', 10);
213
+ if (isNaN(usePercent)) {
214
+ return { name: 'Disk Space', status: 'warn', message: `${available || 'unknown'} available (unable to parse usage)` };
215
+ }
216
+ if (usePercent > 90) {
217
+ return { name: 'Disk Space', status: 'fail', message: `${available} available (${usePercent}% used)`, fix: 'Free up disk space' };
218
+ }
219
+ else if (usePercent > 80) {
220
+ return { name: 'Disk Space', status: 'warn', message: `${available} available (${usePercent}% used)` };
221
+ }
222
+ return { name: 'Disk Space', status: 'pass', message: `${available} available` };
223
+ }
224
+ catch {
225
+ return { name: 'Disk Space', status: 'warn', message: 'Unable to check' };
226
+ }
227
+ }
228
+ // Check TypeScript/build (async with proper env inheritance)
229
+ async function checkBuildTools() {
230
+ try {
231
+ const tscVersion = await runCommand('npx tsc --version', 10000); // tsc can be slow
232
+ if (!tscVersion || tscVersion.includes('not found')) {
233
+ return { name: 'TypeScript', status: 'warn', message: 'Not installed locally', fix: 'npm install -D typescript' };
234
+ }
235
+ return { name: 'TypeScript', status: 'pass', message: tscVersion.replace('Version ', 'v') };
236
+ }
237
+ catch {
238
+ return { name: 'TypeScript', status: 'warn', message: 'Not installed locally', fix: 'npm install -D typescript' };
239
+ }
240
+ }
241
+ // Check for stale npx cache (version freshness)
242
+ async function checkVersionFreshness() {
243
+ try {
244
+ // Get current CLI version from package.json
245
+ // Use import.meta.url to reliably locate our own package.json,
246
+ // regardless of how deep the compiled file sits (e.g. dist/src/commands/).
247
+ let currentVersion = '0.0.0';
248
+ try {
249
+ const thisFile = fileURLToPath(import.meta.url);
250
+ let dir = dirname(thisFile);
251
+ // Walk up from the current file's directory until we find the
252
+ // package.json that belongs to @claude-flow/cli (or claude-flow/cli).
253
+ // Walk until dirname(dir) === dir (filesystem root on any platform).
254
+ for (;;) {
255
+ const candidate = join(dir, 'package.json');
256
+ try {
257
+ if (existsSync(candidate)) {
258
+ const pkg = JSON.parse(readFileSync(candidate, 'utf8'));
259
+ if (pkg.version &&
260
+ typeof pkg.name === 'string' &&
261
+ (pkg.name === '@claude-flow/cli' || pkg.name === 'claude-flow' || pkg.name === 'ruflo' || pkg.name === 'moflo' || pkg.name === '@moflo/cli')) {
262
+ currentVersion = pkg.version;
263
+ break;
264
+ }
265
+ }
266
+ }
267
+ catch {
268
+ // Unreadable/invalid JSON -- skip and keep walking up
269
+ }
270
+ const parent = dirname(dir);
271
+ if (parent === dir)
272
+ break; // reached root
273
+ dir = parent;
274
+ }
275
+ }
276
+ catch {
277
+ // Fall back to a default
278
+ currentVersion = '0.0.0';
279
+ }
280
+ // Check if running via npx (look for _npx in process path or argv)
281
+ const isNpx = process.argv[1]?.includes('_npx') ||
282
+ process.env.npm_execpath?.includes('npx') ||
283
+ process.cwd().includes('_npx');
284
+ // Query npm for latest version (using alpha tag since that's what we publish to)
285
+ let latestVersion = currentVersion;
286
+ try {
287
+ const npmInfo = await runCommand('npm view moflo version', 5000);
288
+ latestVersion = npmInfo.trim();
289
+ }
290
+ catch {
291
+ // Can't reach npm registry - skip check
292
+ return {
293
+ name: 'Version Freshness',
294
+ status: 'warn',
295
+ message: `v${currentVersion} (cannot check registry)`
296
+ };
297
+ }
298
+ // Parse version numbers for comparison (handle prerelease like 3.0.0-alpha.84)
299
+ const parseVersion = (v) => {
300
+ const match = v.match(/^(\d+)\.(\d+)\.(\d+)(?:-[a-zA-Z]+\.(\d+))?/);
301
+ if (!match)
302
+ return { major: 0, minor: 0, patch: 0, prerelease: 0 };
303
+ return {
304
+ major: parseInt(match[1], 10) || 0,
305
+ minor: parseInt(match[2], 10) || 0,
306
+ patch: parseInt(match[3], 10) || 0,
307
+ prerelease: parseInt(match[4], 10) || 0
308
+ };
309
+ };
310
+ const current = parseVersion(currentVersion);
311
+ const latest = parseVersion(latestVersion);
312
+ // Compare versions (including prerelease number)
313
+ const isOutdated = (latest.major > current.major ||
314
+ (latest.major === current.major && latest.minor > current.minor) ||
315
+ (latest.major === current.major && latest.minor === current.minor && latest.patch > current.patch) ||
316
+ (latest.major === current.major && latest.minor === current.minor && latest.patch === current.patch && latest.prerelease > current.prerelease));
317
+ if (isOutdated) {
318
+ const fix = isNpx
319
+ ? 'rm -rf ~/.npm/_npx/* && npx -y moflo'
320
+ : 'npm update moflo';
321
+ return {
322
+ name: 'Version Freshness',
323
+ status: 'warn',
324
+ message: `v${currentVersion} (latest: v${latestVersion})${isNpx ? ' [npx cache stale]' : ''}`,
325
+ fix
326
+ };
327
+ }
328
+ return {
329
+ name: 'Version Freshness',
330
+ status: 'pass',
331
+ message: `v${currentVersion} (up to date)`
332
+ };
333
+ }
334
+ catch (error) {
335
+ return {
336
+ name: 'Version Freshness',
337
+ status: 'warn',
338
+ message: 'Unable to check version freshness'
339
+ };
340
+ }
341
+ }
342
+ // Check Claude Code CLI (async with proper env inheritance)
343
+ async function checkClaudeCode() {
344
+ try {
345
+ const version = await runCommand('claude --version');
346
+ // Parse version from output like "claude 1.0.0" or "Claude Code v1.0.0"
347
+ const versionMatch = version.match(/v?(\d+\.\d+\.\d+)/);
348
+ const versionStr = versionMatch ? `v${versionMatch[1]}` : version;
349
+ return { name: 'Claude Code CLI', status: 'pass', message: versionStr };
350
+ }
351
+ catch {
352
+ return {
353
+ name: 'Claude Code CLI',
354
+ status: 'warn',
355
+ message: 'Not installed',
356
+ fix: 'npm install -g @anthropic-ai/claude-code'
357
+ };
358
+ }
359
+ }
360
+ // Install Claude Code CLI
361
+ async function installClaudeCode() {
362
+ try {
363
+ output.writeln();
364
+ output.writeln(output.bold('Installing Claude Code CLI...'));
365
+ execSync('npm install -g @anthropic-ai/claude-code', {
366
+ encoding: 'utf8',
367
+ stdio: 'inherit',
368
+ windowsHide: true
369
+ });
370
+ output.writeln(output.success('Claude Code CLI installed successfully!'));
371
+ return true;
372
+ }
373
+ catch (error) {
374
+ output.writeln(output.error('Failed to install Claude Code CLI'));
375
+ if (error instanceof Error) {
376
+ output.writeln(output.dim(error.message));
377
+ }
378
+ return false;
379
+ }
380
+ }
381
+ // Check embeddings / vector index health
382
+ async function checkEmbeddings() {
383
+ const dbPaths = [
384
+ join(process.cwd(), '.swarm', 'memory.db'),
385
+ join(process.cwd(), '.claude-flow', 'memory.db'),
386
+ join(process.cwd(), 'data', 'memory.db'),
387
+ ];
388
+ // 1. Fast path: read cached vector-stats.json if available
389
+ const statsPath = join(process.cwd(), '.claude-flow', 'vector-stats.json');
390
+ try {
391
+ if (existsSync(statsPath)) {
392
+ const stats = JSON.parse(readFileSync(statsPath, 'utf8'));
393
+ const count = stats.vectorCount ?? 0;
394
+ const hasHnsw = stats.hasHnsw ?? false;
395
+ const dbSizeKB = stats.dbSizeKB ?? 0;
396
+ if (count === 0) {
397
+ return {
398
+ name: 'Embeddings',
399
+ status: 'warn',
400
+ message: `Memory DB exists (${dbSizeKB} KB) but 0 vectors indexed — documents not embedded`,
401
+ fix: 'npx moflo memory init --force && npx moflo embeddings init'
402
+ };
403
+ }
404
+ const hnswLabel = hasHnsw ? ', HNSW' : '';
405
+ return {
406
+ name: 'Embeddings',
407
+ status: 'pass',
408
+ message: `${count} vectors indexed (${dbSizeKB} KB${hnswLabel})`
409
+ };
410
+ }
411
+ }
412
+ catch {
413
+ // Stats file unreadable — fall through to DB check
414
+ }
415
+ // 2. Check if memory DB file exists at all
416
+ let foundDbPath = null;
417
+ for (const p of dbPaths) {
418
+ if (existsSync(p)) {
419
+ foundDbPath = p;
420
+ break;
421
+ }
422
+ }
423
+ if (!foundDbPath) {
424
+ return {
425
+ name: 'Embeddings',
426
+ status: 'warn',
427
+ message: 'No memory database — embeddings not initialized',
428
+ fix: 'npx moflo memory init --force'
429
+ };
430
+ }
431
+ // 3. DB exists but no stats cache — try querying the DB for entry count
432
+ try {
433
+ const { checkMemoryInitialization } = await import('../memory/memory-initializer.js');
434
+ const info = await checkMemoryInitialization(foundDbPath);
435
+ if (!info.initialized) {
436
+ return {
437
+ name: 'Embeddings',
438
+ status: 'warn',
439
+ message: 'Memory DB exists but not properly initialized',
440
+ fix: 'npx moflo memory init --force'
441
+ };
442
+ }
443
+ const hasVectors = info.features?.vectorEmbeddings ?? false;
444
+ if (!hasVectors) {
445
+ return {
446
+ name: 'Embeddings',
447
+ status: 'warn',
448
+ message: `Memory DB initialized (v${info.version}) but no vector_indexes table`,
449
+ fix: 'npx moflo memory init --force && npx moflo embeddings init'
450
+ };
451
+ }
452
+ return {
453
+ name: 'Embeddings',
454
+ status: 'pass',
455
+ message: `Memory DB initialized (v${info.version}, vectors enabled)`
456
+ };
457
+ }
458
+ catch {
459
+ // sql.js not available — fall back to file-size heuristic
460
+ try {
461
+ const stats = statSync(foundDbPath);
462
+ const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
463
+ return {
464
+ name: 'Embeddings',
465
+ status: 'warn',
466
+ message: `Memory DB exists (${sizeMB} MB) — cannot verify vectors (sql.js not available)`,
467
+ fix: 'npm install sql.js && npx moflo embeddings init'
468
+ };
469
+ }
470
+ catch {
471
+ return { name: 'Embeddings', status: 'warn', message: 'Unable to check' };
472
+ }
473
+ }
474
+ }
475
+ /**
476
+ * Auto-fix: execute fix commands for a failed/warned health check.
477
+ * Returns true if the fix succeeded (re-check should pass).
478
+ */
479
+ async function autoFixCheck(check) {
480
+ if (!check.fix)
481
+ return false;
482
+ // Map checks to programmatic fixes (not just shell commands)
483
+ const fixActions = {
484
+ 'Memory Database': async () => {
485
+ try {
486
+ const swarmDir = join(process.cwd(), '.swarm');
487
+ if (!existsSync(swarmDir))
488
+ mkdirSync(swarmDir, { recursive: true });
489
+ const { initializeMemoryDatabase } = await import('../memory/memory-initializer.js');
490
+ const result = await initializeMemoryDatabase({ force: true, verbose: false });
491
+ return result.success;
492
+ }
493
+ catch {
494
+ // Fall back to CLI
495
+ return runFixCommand('npx moflo memory init --force');
496
+ }
497
+ },
498
+ 'Embeddings': async () => {
499
+ try {
500
+ // Step 1: ensure memory DB exists
501
+ const swarmDir = join(process.cwd(), '.swarm');
502
+ if (!existsSync(swarmDir))
503
+ mkdirSync(swarmDir, { recursive: true });
504
+ const dbPath = join(swarmDir, 'memory.db');
505
+ if (!existsSync(dbPath)) {
506
+ const { initializeMemoryDatabase } = await import('../memory/memory-initializer.js');
507
+ await initializeMemoryDatabase({ force: true, verbose: false });
508
+ }
509
+ // Step 2: attempt embeddings init via CLI
510
+ return runFixCommand('npx moflo embeddings init --force');
511
+ }
512
+ catch {
513
+ return runFixCommand('npx moflo memory init --force');
514
+ }
515
+ },
516
+ 'Config File': async () => {
517
+ try {
518
+ const cfDir = join(process.cwd(), '.claude-flow');
519
+ if (!existsSync(cfDir))
520
+ mkdirSync(cfDir, { recursive: true });
521
+ return runFixCommand('npx moflo config init');
522
+ }
523
+ catch {
524
+ return false;
525
+ }
526
+ },
527
+ 'Daemon Status': async () => {
528
+ // Clean stale locks, then try to start daemon
529
+ const lockFile = join(process.cwd(), '.claude-flow', 'daemon.lock');
530
+ const pidFile = join(process.cwd(), '.claude-flow', 'daemon.pid');
531
+ try {
532
+ if (existsSync(lockFile)) {
533
+ const { unlinkSync } = await import('fs');
534
+ unlinkSync(lockFile);
535
+ }
536
+ if (existsSync(pidFile)) {
537
+ const { unlinkSync } = await import('fs');
538
+ unlinkSync(pidFile);
539
+ }
540
+ }
541
+ catch { /* best effort */ }
542
+ return runFixCommand('npx moflo daemon start');
543
+ },
544
+ 'MCP Servers': async () => {
545
+ return runFixCommand('claude mcp add moflo -- npx -y moflo mcp start');
546
+ },
547
+ 'Claude Code CLI': async () => {
548
+ return installClaudeCode();
549
+ },
550
+ 'Zombie Processes': async () => {
551
+ const result = await findZombieProcesses(true);
552
+ return result.killed > 0 || result.found === 0;
553
+ },
554
+ };
555
+ const fixFn = fixActions[check.name];
556
+ if (fixFn) {
557
+ try {
558
+ output.writeln(output.dim(` Fixing: ${check.name}...`));
559
+ const success = await fixFn();
560
+ if (success) {
561
+ output.writeln(output.success(` Fixed: ${check.name}`));
562
+ }
563
+ else {
564
+ output.writeln(output.warning(` Fix attempted but may need manual action: ${check.fix}`));
565
+ }
566
+ return success;
567
+ }
568
+ catch (e) {
569
+ output.writeln(output.warning(` Fix failed: ${e instanceof Error ? e.message : String(e)}`));
570
+ return false;
571
+ }
572
+ }
573
+ // Generic: try running the fix command directly if it looks like a shell command
574
+ if (check.fix.startsWith('npx ') || check.fix.startsWith('npm ') || check.fix.startsWith('claude ')) {
575
+ return runFixCommand(check.fix);
576
+ }
577
+ return false;
578
+ }
579
+ /**
580
+ * Run a shell command as a fix action. Returns true on exit code 0.
581
+ */
582
+ async function runFixCommand(cmd) {
583
+ try {
584
+ await execAsync(cmd, {
585
+ encoding: 'utf8',
586
+ timeout: 30000,
587
+ shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/sh',
588
+ env: { ...process.env },
589
+ windowsHide: true,
590
+ });
591
+ return true;
592
+ }
593
+ catch {
594
+ return false;
595
+ }
596
+ }
597
+ // Check test directories configured in moflo.yaml
598
+ async function checkTestDirs() {
599
+ const yamlPath = join(process.cwd(), 'moflo.yaml');
600
+ if (!existsSync(yamlPath)) {
601
+ return { name: 'Test Directories', status: 'warn', message: 'No moflo.yaml — test indexing unconfigured', fix: 'npx moflo init' };
602
+ }
603
+ try {
604
+ const content = readFileSync(yamlPath, 'utf-8');
605
+ // Check if tests section exists
606
+ const testsBlock = content.match(/tests:\s*\n\s+directories:\s*\n((?:\s+-\s+.+\n?)+)/);
607
+ if (!testsBlock) {
608
+ return { name: 'Test Directories', status: 'warn', message: 'No tests section in moflo.yaml', fix: 'npx moflo init --force' };
609
+ }
610
+ // Extract configured directories
611
+ const items = testsBlock[1].match(/-\s+(.+)/g);
612
+ if (!items || items.length === 0) {
613
+ return { name: 'Test Directories', status: 'warn', message: 'Empty test directories list' };
614
+ }
615
+ const dirs = items.map(item => item.replace(/^-\s+/, '').trim());
616
+ const existing = dirs.filter(d => existsSync(join(process.cwd(), d)));
617
+ const missing = dirs.filter(d => !existsSync(join(process.cwd(), d)));
618
+ // Check auto_index.tests flag
619
+ const autoIndexMatch = content.match(/auto_index:\s*\n(?:.*\n)*?\s+tests:\s*(true|false)/);
620
+ const autoIndexEnabled = !autoIndexMatch || autoIndexMatch[1] !== 'false';
621
+ const indexLabel = autoIndexEnabled ? 'auto-index: on' : 'auto-index: off';
622
+ if (missing.length > 0 && existing.length === 0) {
623
+ return {
624
+ name: 'Test Directories',
625
+ status: 'warn',
626
+ message: `No configured test dirs exist: ${missing.join(', ')} (${indexLabel})`,
627
+ };
628
+ }
629
+ if (missing.length > 0) {
630
+ return {
631
+ name: 'Test Directories',
632
+ status: 'warn',
633
+ message: `${existing.length} OK, ${missing.length} missing: ${missing.join(', ')} (${indexLabel})`,
634
+ };
635
+ }
636
+ return { name: 'Test Directories', status: 'pass', message: `${existing.length} directories: ${existing.join(', ')} (${indexLabel})` };
637
+ }
638
+ catch {
639
+ return { name: 'Test Directories', status: 'warn', message: 'Unable to parse moflo.yaml' };
640
+ }
641
+ }
642
+ // Check agentic-flow v3 integration (filesystem-based to avoid slow WASM/DB init)
643
+ async function checkAgenticFlow() {
644
+ try {
645
+ // Walk common node_modules paths to find agentic-flow/package.json
646
+ const candidates = [
647
+ join(process.cwd(), 'node_modules', 'agentic-flow', 'package.json'),
648
+ join(process.cwd(), '..', 'node_modules', 'agentic-flow', 'package.json'),
649
+ ];
650
+ let pkgJsonPath = null;
651
+ for (const p of candidates) {
652
+ if (existsSync(p)) {
653
+ pkgJsonPath = p;
654
+ break;
655
+ }
656
+ }
657
+ if (!pkgJsonPath) {
658
+ return {
659
+ name: 'agentic-flow',
660
+ status: 'warn',
661
+ message: 'Not installed (optional — embeddings/routing will use fallbacks)',
662
+ fix: 'npm install agentic-flow@latest'
663
+ };
664
+ }
665
+ const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8'));
666
+ const version = pkg.version || 'unknown';
667
+ const exports = pkg.exports || {};
668
+ const features = [
669
+ exports['./reasoningbank'] ? 'ReasoningBank' : null,
670
+ exports['./router'] ? 'Router' : null,
671
+ exports['./transport/quic'] ? 'QUIC' : null,
672
+ ].filter(Boolean);
673
+ return {
674
+ name: 'agentic-flow',
675
+ status: 'pass',
676
+ message: `v${version} (${features.join(', ')})`
677
+ };
678
+ }
679
+ catch {
680
+ return { name: 'agentic-flow', status: 'warn', message: 'Check failed' };
681
+ }
682
+ }
683
+ // Check semantic search quality verify no 0.500 keyword fallback scores
684
+ async function checkSemanticQuality() {
685
+ try {
686
+ const { searchEntries } = await import('../memory/memory-initializer.js');
687
+ const result = await searchEntries({
688
+ query: 'test infrastructure health check',
689
+ namespace: 'patterns',
690
+ limit: 5,
691
+ threshold: 0.1
692
+ });
693
+ if (!result.success || result.results.length === 0) {
694
+ return {
695
+ name: 'Semantic Quality',
696
+ status: 'warn',
697
+ message: 'No search results (empty database or no patterns namespace)',
698
+ };
699
+ }
700
+ const scores = result.results.map((r) => r.score);
701
+ const allSame = scores.every((s) => s === scores[0]);
702
+ const hasFallback = scores.some((s) => s === 0.5);
703
+ if (hasFallback) {
704
+ return {
705
+ name: 'Semantic Quality',
706
+ status: 'fail',
707
+ message: `${scores.length} results, scores include 0.500 fallback (keyword-only, no embeddings)`,
708
+ fix: 'Re-index with: npx moflo embeddings build --force'
709
+ };
710
+ }
711
+ if (allSame && scores.length > 1) {
712
+ return {
713
+ name: 'Semantic Quality',
714
+ status: 'warn',
715
+ message: `${scores.length} results, all scores identical (${scores[0].toFixed(3)}) — degraded search`,
716
+ };
717
+ }
718
+ const topScore = Math.max(...scores);
719
+ return {
720
+ name: 'Semantic Quality',
721
+ status: topScore >= 0.3 ? 'pass' : 'warn',
722
+ message: `${scores.length} results, top ${topScore.toFixed(3)}, varied (semantic search active)`,
723
+ };
724
+ }
725
+ catch (e) {
726
+ return {
727
+ name: 'Semantic Quality',
728
+ status: 'warn',
729
+ message: `Check failed: ${e instanceof Error ? e.message.split('\n')[0] : 'error'}`,
730
+ };
731
+ }
732
+ }
733
+ // Check memory-backed patterns (populated by pretrain) as a fallback for neural checks
734
+ async function checkMemoryPatterns(namespace) {
735
+ try {
736
+ // @ts-ignore memory is not in tsconfig project references but is available at runtime
737
+ const memoryMod = await import('../../../../memory/dist/index.js');
738
+ if (memoryMod.search) {
739
+ const results = await memoryMod.search({ query: 'pattern', namespace, limit: 1 });
740
+ return results?.length ?? 0;
741
+ }
742
+ // Fallback: try AgentDB route
743
+ if (memoryMod.getStore) {
744
+ const store = memoryMod.getStore();
745
+ const entries = store?.list?.(namespace) ?? [];
746
+ return entries.length;
747
+ }
748
+ }
749
+ catch {
750
+ // Memory module not available
751
+ }
752
+ return 0;
753
+ }
754
+ // Check intelligence layer: SONA, EWC++, LoRA, Flash Attention, ReasoningBank
755
+ // Exercises each component with a lightweight functional test rather than just checking "loaded".
756
+ async function checkIntelligence() {
757
+ try {
758
+ // @ts-ignore — neural is not in tsconfig project references but is available at runtime
759
+ // Import neural module path is relative to compiled output at dist/src/commands/
760
+ const neural = await import('../../../../neural/dist/index.js');
761
+ const results = [];
762
+ const failures = [];
763
+ // 1. SONA — create manager, run trajectory lifecycle
764
+ try {
765
+ const sona = neural.createSONAManager('balanced');
766
+ await sona.initialize();
767
+ const tid = sona.beginTrajectory('doctor-check', 'general');
768
+ const embedding = new Float32Array(64).fill(0.1);
769
+ sona.recordStep(tid, 'test-action', 0.8, embedding);
770
+ const traj = sona.completeTrajectory(tid, 0.9);
771
+ if (traj && traj.steps.length > 0) {
772
+ results.push('SONA');
773
+ }
774
+ else {
775
+ failures.push('SONA (no trajectory output)');
776
+ }
777
+ await sona.cleanup();
778
+ }
779
+ catch (e) {
780
+ failures.push(`SONA (${e instanceof Error ? e.message : 'error'})`);
781
+ }
782
+ // 2. ReasoningBank — store + retrieve
783
+ try {
784
+ const rb = neural.createReasoningBank();
785
+ const embedding = new Float32Array(64).fill(0.2);
786
+ rb.storeTrajectory({
787
+ id: 'doctor-test',
788
+ context: 'health check',
789
+ domain: 'general',
790
+ mode: 'balanced',
791
+ steps: [{ action: 'test', reward: 1, embedding, timestamp: Date.now() }],
792
+ startTime: Date.now(),
793
+ endTime: Date.now(),
794
+ quality: 1,
795
+ });
796
+ const retrieved = rb.retrieve(embedding, 1);
797
+ if (retrieved.length > 0) {
798
+ results.push('ReasoningBank');
799
+ }
800
+ else {
801
+ // Fallback: check memory-backed patterns from pretrain
802
+ const memoryPatterns = await checkMemoryPatterns('patterns');
803
+ if (memoryPatterns > 0) {
804
+ results.push('ReasoningBank(memory)');
805
+ }
806
+ else {
807
+ failures.push('ReasoningBank (retrieve failed)');
808
+ }
809
+ }
810
+ }
811
+ catch (e) {
812
+ failures.push(`ReasoningBank (${e instanceof Error ? e.message : 'error'})`);
813
+ }
814
+ // 3. PatternLearner — extract + match
815
+ try {
816
+ const pl = neural.createPatternLearner();
817
+ const embedding = new Float32Array(64).fill(0.3);
818
+ pl.extractPattern({
819
+ id: 'doctor-pl', context: 'test', domain: 'general', mode: 'balanced',
820
+ steps: [{ action: 'test', reward: 1, embedding, timestamp: Date.now() }],
821
+ startTime: Date.now(), endTime: Date.now(), quality: 1,
822
+ }, { trajectoryId: 'doctor-pl', keyInsights: ['test'], compressedEmbedding: embedding, timestamp: Date.now() });
823
+ const matches = pl.findMatches(embedding, 1);
824
+ if (matches.length > 0) {
825
+ results.push('PatternLearner');
826
+ }
827
+ else {
828
+ // Fallback: check memory-backed patterns from pretrain
829
+ const memoryPatterns = await checkMemoryPatterns('patterns');
830
+ if (memoryPatterns > 0) {
831
+ results.push('PatternLearner(memory)');
832
+ }
833
+ else {
834
+ failures.push('PatternLearner (no matches)');
835
+ }
836
+ }
837
+ }
838
+ catch (e) {
839
+ failures.push(`PatternLearner (${e instanceof Error ? e.message : 'error'})`);
840
+ }
841
+ // 4. SONALearningEngine (MicroLoRA + EWC++)
842
+ try {
843
+ const engine = neural.createSONALearningEngine();
844
+ const ctx = { domain: 'general', queryEmbedding: new Float32Array(768).fill(0.1) };
845
+ const adapted = await engine.adapt(ctx);
846
+ const components = [];
847
+ if (adapted && adapted.transformedQuery)
848
+ components.push('LoRA');
849
+ if (adapted && adapted.patterns !== undefined)
850
+ components.push('EWC++');
851
+ if (components.length > 0) {
852
+ results.push(...components);
853
+ }
854
+ else {
855
+ failures.push('LoRA/EWC++ (adapt returned no data)');
856
+ }
857
+ }
858
+ catch (e) {
859
+ // Gracefully handle cold/uninitialized state
860
+ const msg = e instanceof Error ? e.message : 'error';
861
+ if (msg.includes('undefined') || msg.includes('not initialized')) {
862
+ results.push('LoRA/EWC++(cold)');
863
+ }
864
+ else {
865
+ failures.push(`LoRA/EWC++ (${msg})`);
866
+ }
867
+ }
868
+ // 5. RL Algorithms — quick instantiation check
869
+ try {
870
+ const algNames = [];
871
+ const ppo = neural.createPPO();
872
+ if (ppo)
873
+ algNames.push('PPO');
874
+ const dqn = neural.createDQN();
875
+ if (dqn)
876
+ algNames.push('DQN');
877
+ const ql = neural.createQLearning();
878
+ if (ql)
879
+ algNames.push('Q-Learn');
880
+ if (algNames.length > 0) {
881
+ results.push(`RL(${algNames.join('+')})`);
882
+ }
883
+ }
884
+ catch (e) {
885
+ failures.push(`RL (${e instanceof Error ? e.message : 'error'})`);
886
+ }
887
+ if (failures.length > 0) {
888
+ return {
889
+ name: 'Intelligence',
890
+ status: results.length > 0 ? 'warn' : 'fail',
891
+ message: `${results.join(', ')} OK; FAILED: ${failures.join(', ')}`,
892
+ fix: 'Check neural module imports and dependencies',
893
+ };
894
+ }
895
+ return {
896
+ name: 'Intelligence',
897
+ status: 'pass',
898
+ message: results.join(', '),
899
+ };
900
+ }
901
+ catch (e) {
902
+ return {
903
+ name: 'Intelligence',
904
+ status: 'warn',
905
+ message: `Module unavailable: ${e instanceof Error ? e.message.split('\n')[0] : 'import failed'}`,
906
+ fix: 'Ensure @claude-flow/neural is built (npm run build)',
907
+ };
908
+ }
909
+ }
910
+ // Check whether a given PID is still running.
911
+ // Uses signal 0 which works cross-platform (Windows, Linux, macOS) without
912
+ // needing PowerShell or /proc — Node handles the platform abstraction.
913
+ function isProcessAlive(pid) {
914
+ try {
915
+ process.kill(pid, 0);
916
+ return true;
917
+ }
918
+ catch {
919
+ return false;
920
+ }
921
+ }
922
+ // Fast path: kill processes tracked in the shared ProcessManager registry.
923
+ // This avoids the expensive OS-level process scan for known background tasks.
924
+ function killTrackedProcesses() {
925
+ const registryFile = join(process.cwd(), '.claude-flow', 'background-pids.json');
926
+ const lockFile = join(process.cwd(), '.claude-flow', 'spawn.lock');
927
+ let killed = 0;
928
+ try {
929
+ if (existsSync(registryFile)) {
930
+ const entries = JSON.parse(readFileSync(registryFile, 'utf-8'));
931
+ for (const entry of entries) {
932
+ if (!isProcessAlive(entry.pid))
933
+ continue;
934
+ try {
935
+ if (process.platform === 'win32') {
936
+ execSync(`taskkill /F /PID ${entry.pid}`, { timeout: 5000, windowsHide: true });
937
+ }
938
+ else {
939
+ process.kill(entry.pid, 'SIGKILL');
940
+ }
941
+ killed++;
942
+ }
943
+ catch { /* already gone */ }
944
+ }
945
+ // Clear registry
946
+ writeFileSync(registryFile, '[]');
947
+ }
948
+ }
949
+ catch { /* non-fatal */ }
950
+ // Remove spawn lock
951
+ try {
952
+ if (existsSync(lockFile))
953
+ unlinkSync(lockFile);
954
+ }
955
+ catch { /* ok */ }
956
+ return killed;
957
+ }
958
+ // Find and optionally kill orphaned moflo/claude-flow node processes.
959
+ // A process is only "orphaned" if its parent is no longer alive — meaning
960
+ // nothing will clean it up. MCP servers spawned by a live Claude Code session
961
+ // have a live parent (claude.exe) and must not be flagged.
962
+ async function findZombieProcesses(kill = false) {
963
+ const legitimatePid = getDaemonLockHolder(process.cwd());
964
+ const currentPid = process.pid;
965
+ const parentPid = process.ppid;
966
+ const found = [];
967
+ let killed = 0;
968
+ // Collect candidates as { pid, ppid } so we can check parent liveness
969
+ const candidates = [];
970
+ try {
971
+ if (process.platform === 'win32') {
972
+ // Windows: include ParentProcessId so we can verify orphan status
973
+ const result = execSync('powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"Name=\'node.exe\'\\" | Select-Object ProcessId,ParentProcessId,CommandLine | Format-Table -AutoSize -Wrap"', { encoding: 'utf-8', timeout: 10000, windowsHide: true });
974
+ const lines = result.split('\n');
975
+ for (const line of lines) {
976
+ if (/moflo|claude-flow|flo\s+(hooks|gate|mcp|daemon)/i.test(line)) {
977
+ // Format-Table columns: ProcessId ParentProcessId CommandLine...
978
+ const match = line.match(/^\s*(\d+)\s+(\d+)/);
979
+ if (match) {
980
+ candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
981
+ }
982
+ }
983
+ }
984
+ }
985
+ else {
986
+ // Unix/macOS: use ps with explicit PID+PPID columns for reliable parsing
987
+ const result = execSync('ps -eo pid,ppid,command | grep -E "node.*(moflo|claude-flow)" | grep -v grep', { encoding: 'utf-8', timeout: 5000 });
988
+ const lines = result.trim().split('\n');
989
+ for (const line of lines) {
990
+ const match = line.trim().match(/^(\d+)\s+(\d+)/);
991
+ if (match) {
992
+ candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
993
+ }
994
+ }
995
+ }
996
+ }
997
+ catch {
998
+ // No matches found (grep exits non-zero) or command failed
999
+ }
1000
+ // Filter: skip known-good PIDs and processes whose parent is still alive.
1001
+ // A live parent (e.g. claude.exe for MCP servers) means the process is managed, not orphaned.
1002
+ for (const { pid, ppid } of candidates) {
1003
+ if (pid === currentPid || pid === parentPid || pid === legitimatePid)
1004
+ continue;
1005
+ if (isProcessAlive(ppid))
1006
+ continue;
1007
+ // Defense-in-depth: detached daemons have dead parents by design.
1008
+ // Even if the lock file is missing/corrupted, don't kill a running daemon.
1009
+ if (isDaemonProcess(pid))
1010
+ continue;
1011
+ found.push(pid);
1012
+ }
1013
+ if (kill && found.length > 0) {
1014
+ for (const pid of found) {
1015
+ try {
1016
+ if (process.platform === 'win32') {
1017
+ execSync(`taskkill /F /PID ${pid}`, { timeout: 5000, windowsHide: true });
1018
+ }
1019
+ else {
1020
+ process.kill(pid, 'SIGKILL');
1021
+ }
1022
+ killed++;
1023
+ }
1024
+ catch {
1025
+ // Process may have already exited
1026
+ }
1027
+ }
1028
+ // Clean up stale daemon lock if we killed the holder
1029
+ if (legitimatePid && found.includes(legitimatePid)) {
1030
+ releaseDaemonLock(process.cwd(), legitimatePid, true);
1031
+ }
1032
+ }
1033
+ return { found: found.length, killed, pids: found };
1034
+ }
1035
+ // Format health check result
1036
+ function formatCheck(check) {
1037
+ const icon = check.status === 'pass' ? output.success('✓') :
1038
+ check.status === 'warn' ? output.warning('⚠') :
1039
+ output.error('✗');
1040
+ return `${icon} ${check.name}: ${check.message}`;
1041
+ }
1042
+ // Main doctor command
1043
+ export const doctorCommand = {
1044
+ name: 'doctor',
1045
+ description: 'System diagnostics and health checks',
1046
+ options: [
1047
+ {
1048
+ name: 'fix',
1049
+ short: 'f',
1050
+ description: 'Automatically fix issues where possible',
1051
+ type: 'boolean',
1052
+ default: false
1053
+ },
1054
+ {
1055
+ name: 'install',
1056
+ short: 'i',
1057
+ description: 'Auto-install missing dependencies (Claude Code CLI)',
1058
+ type: 'boolean',
1059
+ default: false
1060
+ },
1061
+ {
1062
+ name: 'component',
1063
+ short: 'c',
1064
+ description: 'Check specific component (version, node, npm, config, daemon, memory, embeddings, git, mcp, claude, disk, typescript, semantic, intelligence)',
1065
+ type: 'string'
1066
+ },
1067
+ {
1068
+ name: 'verbose',
1069
+ short: 'v',
1070
+ description: 'Verbose output',
1071
+ type: 'boolean',
1072
+ default: false
1073
+ },
1074
+ {
1075
+ name: 'kill-zombies',
1076
+ short: 'k',
1077
+ description: 'Find and kill orphaned moflo/claude-flow node processes',
1078
+ type: 'boolean',
1079
+ default: false
1080
+ }
1081
+ ],
1082
+ examples: [
1083
+ { command: 'claude-flow doctor', description: 'Run full health check' },
1084
+ { command: 'claude-flow doctor --fix', description: 'Show fixes for issues' },
1085
+ { command: 'claude-flow doctor --install', description: 'Auto-install missing dependencies' },
1086
+ { command: 'claude-flow doctor --kill-zombies', description: 'Find and kill zombie processes' },
1087
+ { command: 'claude-flow doctor -c version', description: 'Check for stale npx cache' },
1088
+ { command: 'claude-flow doctor -c claude', description: 'Check Claude Code CLI only' }
1089
+ ],
1090
+ action: async (ctx) => {
1091
+ const showFix = ctx.flags.fix;
1092
+ const autoInstall = ctx.flags.install;
1093
+ const component = ctx.flags.component;
1094
+ const verbose = ctx.flags.verbose;
1095
+ const killZombies = ctx.flags['kill-zombies'];
1096
+ output.writeln();
1097
+ output.writeln(output.bold('MoFlo Doctor'));
1098
+ output.writeln(output.dim('System diagnostics and health check'));
1099
+ output.writeln(output.dim('─'.repeat(50)));
1100
+ output.writeln();
1101
+ // Handle --kill-zombies early
1102
+ if (killZombies) {
1103
+ output.writeln(output.bold('Zombie Process Scan'));
1104
+ output.writeln();
1105
+ // Fast path: kill tracked processes from the shared registry first
1106
+ const registryKilled = killTrackedProcesses();
1107
+ if (registryKilled > 0) {
1108
+ output.writeln(output.success(` Killed ${registryKilled} tracked background process(es) from registry`));
1109
+ }
1110
+ // Slow path: OS-level scan for any remaining orphans
1111
+ const scan = await findZombieProcesses(false);
1112
+ if (scan.found === 0) {
1113
+ if (registryKilled === 0) {
1114
+ output.writeln(output.success(' No orphaned moflo processes found'));
1115
+ }
1116
+ }
1117
+ else {
1118
+ output.writeln(output.warning(` Found ${scan.found} additional orphaned process(es): PIDs ${scan.pids.join(', ')}`));
1119
+ // Kill them
1120
+ const result = await findZombieProcesses(true);
1121
+ if (result.killed > 0) {
1122
+ output.writeln(output.success(` Killed ${result.killed} zombie process(es)`));
1123
+ }
1124
+ if (result.killed < result.found) {
1125
+ output.writeln(output.warning(` ${result.found - result.killed} process(es) could not be killed`));
1126
+ }
1127
+ }
1128
+ output.writeln();
1129
+ output.writeln(output.dim('─'.repeat(50)));
1130
+ output.writeln();
1131
+ }
1132
+ const checkZombieProcesses = async () => {
1133
+ try {
1134
+ const scan = await findZombieProcesses(false);
1135
+ if (scan.found === 0) {
1136
+ return { name: 'Zombie Processes', status: 'pass', message: 'No orphaned processes' };
1137
+ }
1138
+ return {
1139
+ name: 'Zombie Processes',
1140
+ status: 'warn',
1141
+ message: `${scan.found} orphaned process(es) (PIDs: ${scan.pids.join(', ')})`,
1142
+ fix: 'moflo doctor --kill-zombies'
1143
+ };
1144
+ }
1145
+ catch {
1146
+ return { name: 'Zombie Processes', status: 'pass', message: 'Check skipped' };
1147
+ }
1148
+ };
1149
+ const allChecks = [
1150
+ checkVersionFreshness,
1151
+ checkNodeVersion,
1152
+ checkNpmVersion,
1153
+ checkClaudeCode,
1154
+ checkGit,
1155
+ checkGitRepo,
1156
+ checkConfigFile,
1157
+ checkDaemonStatus,
1158
+ checkMemoryDatabase,
1159
+ checkEmbeddings,
1160
+ checkTestDirs,
1161
+ checkMcpServers,
1162
+ checkDiskSpace,
1163
+ checkBuildTools,
1164
+ checkAgenticFlow,
1165
+ checkSemanticQuality,
1166
+ checkIntelligence,
1167
+ checkZombieProcesses
1168
+ ];
1169
+ const componentMap = {
1170
+ 'version': checkVersionFreshness,
1171
+ 'freshness': checkVersionFreshness,
1172
+ 'node': checkNodeVersion,
1173
+ 'npm': checkNpmVersion,
1174
+ 'claude': checkClaudeCode,
1175
+ 'config': checkConfigFile,
1176
+ 'daemon': checkDaemonStatus,
1177
+ 'memory': checkMemoryDatabase,
1178
+ 'embeddings': checkEmbeddings,
1179
+ 'git': checkGit,
1180
+ 'mcp': checkMcpServers,
1181
+ 'disk': checkDiskSpace,
1182
+ 'typescript': checkBuildTools,
1183
+ 'tests': checkTestDirs,
1184
+ 'agentic-flow': checkAgenticFlow,
1185
+ 'semantic': checkSemanticQuality,
1186
+ 'quality': checkSemanticQuality,
1187
+ 'intelligence': checkIntelligence
1188
+ };
1189
+ let checksToRun = allChecks;
1190
+ if (component && componentMap[component]) {
1191
+ checksToRun = [componentMap[component]];
1192
+ }
1193
+ const results = [];
1194
+ const fixes = [];
1195
+ // OPTIMIZATION: Run all checks in parallel for 3-5x faster execution
1196
+ const spinner = output.createSpinner({ text: 'Running health checks in parallel...', spinner: 'dots' });
1197
+ spinner.start();
1198
+ try {
1199
+ // Execute all checks concurrently
1200
+ const checkResults = await Promise.allSettled(checksToRun.map(check => check()));
1201
+ spinner.stop();
1202
+ // Process results in order
1203
+ for (const settledResult of checkResults) {
1204
+ if (settledResult.status === 'fulfilled') {
1205
+ const result = settledResult.value;
1206
+ results.push(result);
1207
+ output.writeln(formatCheck(result));
1208
+ if (result.fix && (result.status === 'fail' || result.status === 'warn')) {
1209
+ fixes.push(`${result.name}: ${result.fix}`);
1210
+ }
1211
+ }
1212
+ else {
1213
+ const errorResult = {
1214
+ name: 'Check',
1215
+ status: 'fail',
1216
+ message: settledResult.reason?.message || 'Unknown error'
1217
+ };
1218
+ results.push(errorResult);
1219
+ output.writeln(formatCheck(errorResult));
1220
+ }
1221
+ }
1222
+ }
1223
+ catch (error) {
1224
+ spinner.stop();
1225
+ output.writeln(output.error('Failed to run health checks'));
1226
+ }
1227
+ // Auto-install missing dependencies if requested
1228
+ if (autoInstall) {
1229
+ const claudeCodeResult = results.find(r => r.name === 'Claude Code CLI');
1230
+ if (claudeCodeResult && claudeCodeResult.status !== 'pass') {
1231
+ const installed = await installClaudeCode();
1232
+ if (installed) {
1233
+ // Re-check Claude Code after installation
1234
+ const newCheck = await checkClaudeCode();
1235
+ const idx = results.findIndex(r => r.name === 'Claude Code CLI');
1236
+ if (idx !== -1) {
1237
+ results[idx] = newCheck;
1238
+ // Update fixes list
1239
+ const fixIdx = fixes.findIndex(f => f.startsWith('Claude Code CLI:'));
1240
+ if (fixIdx !== -1 && newCheck.status === 'pass') {
1241
+ fixes.splice(fixIdx, 1);
1242
+ }
1243
+ }
1244
+ output.writeln(formatCheck(newCheck));
1245
+ }
1246
+ }
1247
+ }
1248
+ // Summary
1249
+ const passed = results.filter(r => r.status === 'pass').length;
1250
+ const warnings = results.filter(r => r.status === 'warn').length;
1251
+ const failed = results.filter(r => r.status === 'fail').length;
1252
+ output.writeln();
1253
+ output.writeln(output.dim('─'.repeat(50)));
1254
+ output.writeln();
1255
+ const summaryParts = [
1256
+ output.success(`${passed} passed`),
1257
+ warnings > 0 ? output.warning(`${warnings} warnings`) : null,
1258
+ failed > 0 ? output.error(`${failed} failed`) : null
1259
+ ].filter(Boolean);
1260
+ output.writeln(`Summary: ${summaryParts.join(', ')}`);
1261
+ // Auto-fix or show fixes
1262
+ if (showFix && fixes.length > 0) {
1263
+ output.writeln();
1264
+ output.writeln(output.bold('Auto-fixing issues...'));
1265
+ output.writeln();
1266
+ const fixableResults = results.filter(r => r.fix && (r.status === 'fail' || r.status === 'warn'));
1267
+ let fixed = 0;
1268
+ const unfixed = [];
1269
+ for (const check of fixableResults) {
1270
+ const success = await autoFixCheck(check);
1271
+ if (success) {
1272
+ fixed++;
1273
+ }
1274
+ else {
1275
+ unfixed.push(`${check.name}: ${check.fix}`);
1276
+ }
1277
+ }
1278
+ if (fixed > 0) {
1279
+ output.writeln();
1280
+ output.writeln(output.success(`Auto-fixed ${fixed} issue${fixed > 1 ? 's' : ''}`));
1281
+ }
1282
+ if (unfixed.length > 0) {
1283
+ output.writeln();
1284
+ output.writeln(output.bold('Manual fixes needed:'));
1285
+ for (const fix of unfixed) {
1286
+ output.writeln(output.dim(` ${fix}`));
1287
+ }
1288
+ }
1289
+ // Re-run checks to show updated status
1290
+ if (fixed > 0) {
1291
+ output.writeln();
1292
+ output.writeln(output.dim('Re-checking...'));
1293
+ output.writeln();
1294
+ const reResults = await Promise.allSettled(checksToRun.map(check => check()));
1295
+ let rePassed = 0, reWarnings = 0, reFailed = 0;
1296
+ for (const sr of reResults) {
1297
+ if (sr.status === 'fulfilled') {
1298
+ output.writeln(formatCheck(sr.value));
1299
+ if (sr.value.status === 'pass')
1300
+ rePassed++;
1301
+ else if (sr.value.status === 'warn')
1302
+ reWarnings++;
1303
+ else
1304
+ reFailed++;
1305
+ }
1306
+ }
1307
+ output.writeln();
1308
+ output.writeln(output.dim('─'.repeat(50)));
1309
+ const reSummary = [
1310
+ output.success(`${rePassed} passed`),
1311
+ reWarnings > 0 ? output.warning(`${reWarnings} warnings`) : null,
1312
+ reFailed > 0 ? output.error(`${reFailed} failed`) : null
1313
+ ].filter(Boolean);
1314
+ output.writeln(`After fix: ${reSummary.join(', ')}`);
1315
+ }
1316
+ }
1317
+ else if (fixes.length > 0 && !showFix) {
1318
+ output.writeln();
1319
+ output.writeln(output.dim(`Run with --fix to auto-fix ${fixes.length} issue${fixes.length > 1 ? 's' : ''}`));
1320
+ }
1321
+ // Overall result
1322
+ if (failed > 0) {
1323
+ output.writeln();
1324
+ output.writeln(output.error('Some checks failed. Please address the issues above.'));
1325
+ return { success: false, exitCode: 1, data: { passed, warnings, failed, results } };
1326
+ }
1327
+ else if (warnings > 0) {
1328
+ output.writeln();
1329
+ output.writeln(output.warning('All checks passed with some warnings.'));
1330
+ return { success: true, data: { passed, warnings, failed, results } };
1331
+ }
1332
+ else {
1333
+ output.writeln();
1334
+ output.writeln(output.success('All checks passed! System is healthy.'));
1335
+ return { success: true, data: { passed, warnings, failed, results } };
1336
+ }
1337
+ }
1338
+ };
1339
+ export default doctorCommand;
1108
1340
  //# sourceMappingURL=doctor.js.map