moflo 4.9.12 → 4.9.14

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 (33) hide show
  1. package/.claude/helpers/gate.cjs +21 -5
  2. package/.claude/skills/eldar/SKILL.md +305 -0
  3. package/.claude/skills/fl/phases.md +18 -2
  4. package/.claude/skills/simplify/SKILL.md +35 -48
  5. package/README.md +25 -0
  6. package/bin/gate.cjs +21 -5
  7. package/bin/hooks.mjs +2 -2
  8. package/bin/index-guidance.mjs +14 -24
  9. package/bin/index-patterns.mjs +13 -10
  10. package/bin/session-start-launcher.mjs +64 -10
  11. package/bin/simplify-classify.cjs +211 -0
  12. package/dist/src/cli/commands/doctor-checks-config.js +246 -0
  13. package/dist/src/cli/commands/doctor-checks-deep.js +14 -0
  14. package/dist/src/cli/commands/doctor-checks-intelligence.js +197 -0
  15. package/dist/src/cli/commands/doctor-checks-memory.js +207 -0
  16. package/dist/src/cli/commands/doctor-checks-platform.js +138 -0
  17. package/dist/src/cli/commands/doctor-checks-runtime.js +170 -0
  18. package/dist/src/cli/commands/doctor-fixes.js +165 -0
  19. package/dist/src/cli/commands/doctor-registry.js +109 -0
  20. package/dist/src/cli/commands/doctor-render.js +203 -0
  21. package/dist/src/cli/commands/doctor-types.js +9 -0
  22. package/dist/src/cli/commands/doctor-version.js +134 -0
  23. package/dist/src/cli/commands/doctor-zombies.js +201 -0
  24. package/dist/src/cli/commands/doctor.js +35 -1657
  25. package/dist/src/cli/init/helpers-generator.js +21 -5
  26. package/dist/src/cli/init/moflo-init.js +20 -268
  27. package/dist/src/cli/init/moflo-yaml-template.js +370 -0
  28. package/dist/src/cli/mcp-tools/hooks-tools.js +3 -1
  29. package/dist/src/cli/movector/model-router.js +66 -20
  30. package/dist/src/cli/services/hook-block-hash.js +23 -2
  31. package/dist/src/cli/version.js +1 -1
  32. package/package.json +2 -2
  33. package/scripts/post-install-bootstrap.mjs +1 -0
@@ -2,1233 +2,22 @@
2
2
  * V3 CLI Doctor Command
3
3
  * System diagnostics, dependency checks, config validation
4
4
  *
5
+ * The check implementations live in focused sibling modules
6
+ * (`doctor-checks-*.ts`, `doctor-zombies.ts`, `doctor-version.ts`,
7
+ * `doctor-fixes.ts`); the registry of which checks run lives in
8
+ * `doctor-registry.ts`; rendering helpers live in `doctor-render.ts`.
9
+ * This file is orchestration only.
10
+ *
5
11
  * Created with motailz.com
6
12
  */
7
13
  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 os from 'os';
14
- import { getDaemonLockHolder, releaseDaemonLock, isDaemonProcess } from '../services/daemon-lock.js';
15
- import { checkSubagentHealth, checkSpellExecution, checkMcpToolInvocation, checkHookExecution, checkMcpSpellIntegration, checkGateHealth, checkHookBlockDrift, checkMofloDbBridge, getMofloRoot, } from './doctor-checks-deep.js';
16
- import { checkEmbeddingHygiene } from './doctor-embedding-hygiene.js';
17
- import { checkSwarmFunctional, checkHiveMindFunctional, } from './doctor-checks-swarm.js';
18
- import { checkMemoryAccessFunctional } from './doctor-checks-memory-access.js';
19
- import { repairHookWiring } from '../services/hook-wiring.js';
20
- import { legacyMemoryDbPath, memoryDbCandidatePaths, memoryDbPath, } from '../services/moflo-paths.js';
21
- import { errorDetail } from '../shared/utils/error-detail.js';
22
- // Promisified exec with proper shell and env inheritance for cross-platform support
23
- const execAsync = promisify(exec);
24
- /**
25
- * Execute command asynchronously with proper environment inheritance
26
- * Critical for Windows where PATH may not be inherited properly
27
- */
28
- async function runCommand(command, timeoutMs = 5000) {
29
- const opts = {
30
- encoding: 'utf8',
31
- timeout: timeoutMs,
32
- shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/sh', // Use proper shell per platform
33
- env: { ...process.env }, // Explicitly inherit full environment
34
- windowsHide: true, // Hide window on Windows
35
- };
36
- const { stdout } = await execAsync(command, opts);
37
- const out = stdout.trim();
38
- // Windows parallel exec occasionally returns empty stdout under shell contention — retry once serially
39
- if (!out && process.platform === 'win32') {
40
- const retry = await execAsync(command, opts);
41
- return retry.stdout.trim();
42
- }
43
- return out;
44
- }
45
- // Check Node.js version
46
- async function checkNodeVersion() {
47
- const requiredMajor = 20;
48
- const version = process.version;
49
- const major = parseInt(version.slice(1).split('.')[0], 10);
50
- if (major >= requiredMajor) {
51
- return { name: 'Node.js Version', status: 'pass', message: `${version} (>= ${requiredMajor} required)` };
52
- }
53
- else if (major >= 18) {
54
- return { name: 'Node.js Version', status: 'warn', message: `${version} (>= ${requiredMajor} recommended)`, fix: 'nvm install 20 && nvm use 20' };
55
- }
56
- else {
57
- return { name: 'Node.js Version', status: 'fail', message: `${version} (>= ${requiredMajor} required)`, fix: 'nvm install 20 && nvm use 20' };
58
- }
59
- }
60
- // Check npm version (async with proper env inheritance)
61
- async function checkNpmVersion() {
62
- try {
63
- const version = await runCommand('npm --version');
64
- const major = parseInt(version.split('.')[0], 10);
65
- if (major >= 9) {
66
- return { name: 'npm Version', status: 'pass', message: `v${version}` };
67
- }
68
- else {
69
- return { name: 'npm Version', status: 'warn', message: `v${version} (>= 9 recommended)`, fix: 'npm install -g npm@latest' };
70
- }
71
- }
72
- catch {
73
- return { name: 'npm Version', status: 'fail', message: 'npm not found', fix: 'Install Node.js from https://nodejs.org' };
74
- }
75
- }
76
- // Check config file
77
- async function checkConfigFile() {
78
- // JSON configs (parse-validated). LEGACY-CONFIG: `.claude-flow.json` and
79
- // `claude-flow.config.json` filenames are still recognised so consumers
80
- // upgrading from pre-#699 moflo builds (upstream Ruflo) keep working
81
- // without manual rename. Drift guard exempts these via LEGACY-CONFIG marker.
82
- const jsonPaths = [
83
- '.moflo/config.json',
84
- 'moflo.config.json',
85
- 'claude-flow.config.json', // LEGACY-CONFIG: pre-#699 fallback
86
- '.claude-flow.json', // LEGACY-CONFIG: pre-#699 fallback
87
- ];
88
- for (const configPath of jsonPaths) {
89
- if (existsSync(configPath)) {
90
- try {
91
- const content = readFileSync(configPath, 'utf8');
92
- JSON.parse(content);
93
- return { name: 'Config File', status: 'pass', message: `Found: ${configPath}` };
94
- }
95
- catch (e) {
96
- return { name: 'Config File', status: 'fail', message: `Invalid JSON: ${configPath}`, fix: 'Fix JSON syntax in config file' };
97
- }
98
- }
99
- }
100
- // YAML configs (existence-checked only — no heavy yaml parser dependency).
101
- const yamlPaths = [
102
- '.moflo/config.yaml',
103
- '.moflo/config.yml',
104
- 'moflo.config.yaml',
105
- 'claude-flow.config.yaml', // LEGACY-CONFIG: pre-#699 fallback
106
- ];
107
- for (const configPath of yamlPaths) {
108
- if (existsSync(configPath)) {
109
- return { name: 'Config File', status: 'pass', message: `Found: ${configPath}` };
110
- }
111
- }
112
- return { name: 'Config File', status: 'warn', message: 'No config file (using defaults)', fix: 'claude-flow config init' };
113
- }
114
- // Check statusLine is wired in settings.json
115
- async function checkStatusLine() {
116
- const settingsPath = join(process.cwd(), '.claude', 'settings.json');
117
- if (!existsSync(settingsPath)) {
118
- return { name: 'Status Line', status: 'warn', message: 'No .claude/settings.json found', fix: 'npx moflo init' };
119
- }
120
- try {
121
- const settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
122
- if (settings.statusLine && settings.statusLine.command) {
123
- if (settings.statusLine.command.includes('statusline.cjs')) {
124
- return { name: 'Status Line', status: 'pass', message: 'Wired in settings.json' };
125
- }
126
- return { name: 'Status Line', status: 'pass', message: 'Custom statusLine configured' };
127
- }
128
- return { name: 'Status Line', status: 'fail', message: 'statusLine not configured in settings.json', fix: 'Add statusLine config to .claude/settings.json' };
129
- }
130
- catch {
131
- return { name: 'Status Line', status: 'fail', message: 'Failed to parse .claude/settings.json', fix: 'Fix JSON syntax in .claude/settings.json' };
132
- }
133
- }
134
- // Check daemon status — delegates to daemon-lock module for proper
135
- // PID + command-line verification (avoids Windows PID-recycling false positives).
136
- async function checkDaemonStatus() {
137
- try {
138
- // Retry up to 5 times with 1s delay — the daemon starts in the background
139
- // during session-start and may not have acquired its lock file yet.
140
- const MAX_RETRIES = 5;
141
- const RETRY_DELAY_MS = 1000;
142
- let holderPid = null;
143
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
144
- holderPid = getDaemonLockHolder(process.cwd());
145
- if (holderPid)
146
- break;
147
- if (attempt < MAX_RETRIES - 1) {
148
- await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
149
- }
150
- }
151
- if (holderPid) {
152
- return { name: 'Daemon Status', status: 'pass', message: `Running (PID: ${holderPid})` };
153
- }
154
- // getDaemonLockHolder auto-cleans stale locks, but check for legacy PID file
155
- const lockFile = '.moflo/daemon.lock';
156
- if (existsSync(lockFile)) {
157
- // Lock exists but holder is null — getDaemonLockHolder already cleaned it,
158
- // but if it persists it means cleanup failed (permissions, etc.)
159
- return { name: 'Daemon Status', status: 'warn', message: 'Stale lock file', fix: 'rm .moflo/daemon.lock && claude-flow daemon start' };
160
- }
161
- // Also check legacy PID file
162
- const pidFile = '.moflo/daemon.pid';
163
- if (existsSync(pidFile)) {
164
- return { name: 'Daemon Status', status: 'warn', message: 'Legacy PID file found', fix: 'rm .moflo/daemon.pid && claude-flow daemon start' };
165
- }
166
- return { name: 'Daemon Status', status: 'warn', message: 'Not running', fix: 'claude-flow daemon start' };
167
- }
168
- catch (e) {
169
- return { name: 'Daemon Status', status: 'warn', message: `Unable to check: ${errorDetail(e)}`, fix: 'claude-flow daemon status' };
170
- }
171
- }
172
- // Check memory database
173
- async function checkMemoryDatabase() {
174
- const root = process.cwd();
175
- const canonical = memoryDbPath(root);
176
- for (const dbPath of memoryDbCandidatePaths(root)) {
177
- let stats;
178
- try {
179
- stats = statSync(dbPath);
180
- }
181
- catch {
182
- continue;
183
- }
184
- const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
185
- if (dbPath === canonical) {
186
- let message = `.moflo/moflo.db (${sizeMB} MB)`;
187
- // Unfinished migration tail: source still present means the launcher's
188
- // rename-to-.bak step failed (Windows lock most often). Flag so the user
189
- // knows to clear the stale source.
190
- if (existsSync(legacyMemoryDbPath(root))) {
191
- message += ' — legacy .swarm/memory.db still present (delete it after confirming canonical is healthy)';
192
- }
193
- return { name: 'Memory Database', status: 'pass', message };
194
- }
195
- return {
196
- name: 'Memory Database',
197
- status: 'warn',
198
- message: `${dbPath} (${sizeMB} MB) — legacy location, will migrate to .moflo/moflo.db on next session start`,
199
- fix: 'restart claude code session',
200
- };
201
- }
202
- return { name: 'Memory Database', status: 'warn', message: 'Not initialized', fix: 'claude-flow memory configure --backend hybrid' };
203
- }
204
- // Check git (async with proper env inheritance)
205
- async function checkGit() {
206
- try {
207
- const version = await runCommand('git --version');
208
- return { name: 'Git', status: 'pass', message: version.replace('git version ', 'v') };
209
- }
210
- catch (e) {
211
- return { name: 'Git', status: 'warn', message: `Not installed (${errorDetail(e, { firstLineOnly: true })})`, fix: 'Install git from https://git-scm.com' };
212
- }
213
- }
214
- // Check if in git repo (async with proper env inheritance)
215
- async function checkGitRepo() {
216
- try {
217
- await runCommand('git rev-parse --git-dir');
218
- return { name: 'Git Repository', status: 'pass', message: 'In a git repository' };
219
- }
220
- catch (e) {
221
- return { name: 'Git Repository', status: 'warn', message: `Not a git repository (${errorDetail(e, { firstLineOnly: true })})`, fix: 'git init' };
222
- }
223
- }
224
- // Check MCP servers
225
- async function checkMcpServers() {
226
- const mcpConfigPaths = [
227
- join(os.homedir(), '.claude/claude_desktop_config.json'),
228
- join(os.homedir(), '.config/claude/mcp.json'),
229
- '.mcp.json',
230
- // Windows: Claude Desktop stores config under %APPDATA%\Claude\
231
- ...(process.platform === 'win32' && process.env.APPDATA
232
- ? [join(process.env.APPDATA, 'Claude', 'claude_desktop_config.json')]
233
- : []),
234
- ];
235
- for (const configPath of mcpConfigPaths) {
236
- if (existsSync(configPath)) {
237
- try {
238
- const content = JSON.parse(readFileSync(configPath, 'utf8'));
239
- const servers = content.mcpServers || content.servers || {};
240
- const count = Object.keys(servers).length;
241
- const hasClaudeFlow = 'moflo' in servers || 'claude-flow' in servers || 'claude-flow_alpha' in servers || 'ruflo' in servers || 'ruflo_alpha' in servers;
242
- if (hasClaudeFlow) {
243
- return { name: 'MCP Servers', status: 'pass', message: `${count} servers (flo configured)` };
244
- }
245
- else {
246
- return { name: 'MCP Servers', status: 'warn', message: `${count} servers (flo not found)`, fix: 'claude mcp add ruflo -- npx -y ruflo@latest mcp start' };
247
- }
248
- }
249
- catch {
250
- // continue to next path
251
- }
252
- }
253
- }
254
- return { name: 'MCP Servers', status: 'warn', message: 'No MCP config found', fix: 'claude mcp add moflo npx moflo mcp start' };
255
- }
256
- // Check disk space (async with proper env inheritance)
257
- async function checkDiskSpace() {
258
- try {
259
- if (process.platform === 'win32') {
260
- try {
261
- const driveLetter = process.cwd().match(/^([A-Z]):/i)?.[1]?.toUpperCase() || 'C';
262
- const psOutput = await runCommand(`powershell -NoProfile -Command "Get-PSDrive ${driveLetter} | Select-Object -ExpandProperty Free; Get-PSDrive ${driveLetter} | Select-Object -ExpandProperty Used"`);
263
- const vals = psOutput.split(/\r?\n/).filter(l => l.trim());
264
- const freeBytes = parseInt(vals[0] || '0', 10);
265
- const usedBytes = parseInt(vals[1] || '0', 10);
266
- const totalBytes = freeBytes + usedBytes || 1;
267
- const freeGB = (freeBytes / (1024 ** 3)).toFixed(1);
268
- const usePercent = Math.round(((totalBytes - freeBytes) / totalBytes) * 100);
269
- if (usePercent > 90) {
270
- return { name: 'Disk Space', status: 'fail', message: `${freeGB}G available (${usePercent}% used)`, fix: 'Free up disk space' };
271
- }
272
- else if (usePercent > 80) {
273
- return { name: 'Disk Space', status: 'warn', message: `${freeGB}G available (${usePercent}% used)` };
274
- }
275
- return { name: 'Disk Space', status: 'pass', message: `${freeGB}G available` };
276
- }
277
- catch {
278
- return { name: 'Disk Space', status: 'pass', message: 'Check skipped (PowerShell unavailable)' };
279
- }
280
- }
281
- // Use df -Ph for POSIX mode (guarantees single-line output even with long device names)
282
- const output_str = await runCommand('df -Ph . | tail -1');
283
- const parts = output_str.split(/\s+/);
284
- // POSIX format: Filesystem Size Used Avail Capacity Mounted
285
- const available = parts[3];
286
- const usePercent = parseInt(parts[4]?.replace('%', '') || '0', 10);
287
- if (isNaN(usePercent)) {
288
- return { name: 'Disk Space', status: 'warn', message: `${available || 'unknown'} available (unable to parse usage)` };
289
- }
290
- if (usePercent > 90) {
291
- return { name: 'Disk Space', status: 'fail', message: `${available} available (${usePercent}% used)`, fix: 'Free up disk space' };
292
- }
293
- else if (usePercent > 80) {
294
- return { name: 'Disk Space', status: 'warn', message: `${available} available (${usePercent}% used)` };
295
- }
296
- return { name: 'Disk Space', status: 'pass', message: `${available} available` };
297
- }
298
- catch (e) {
299
- return { name: 'Disk Space', status: 'warn', message: `Unable to check: ${errorDetail(e, { firstLineOnly: true })}` };
300
- }
301
- }
302
- // Check TypeScript/build (async with proper env inheritance)
303
- async function checkBuildTools() {
304
- try {
305
- const tscVersion = await runCommand('npx tsc --version', 10000); // tsc can be slow
306
- if (!tscVersion || tscVersion.includes('not found')) {
307
- return { name: 'TypeScript', status: 'warn', message: 'Not installed locally', fix: 'npm install -D typescript' };
308
- }
309
- return { name: 'TypeScript', status: 'pass', message: tscVersion.replace('Version ', 'v') };
310
- }
311
- catch (e) {
312
- return { name: 'TypeScript', status: 'warn', message: `Not installed locally (${errorDetail(e, { firstLineOnly: true })})`, fix: 'npm install -D typescript' };
313
- }
314
- }
315
- // Check for stale npx cache (version freshness)
316
- async function checkVersionFreshness() {
317
- try {
318
- // Get current CLI version from package.json
319
- // Use import.meta.url to reliably locate our own package.json,
320
- // regardless of how deep the compiled file sits (e.g. dist/src/commands/).
321
- let currentVersion = '0.0.0';
322
- try {
323
- const thisFile = fileURLToPath(import.meta.url);
324
- let dir = dirname(thisFile);
325
- // Walk up from the current file's directory until we find the moflo
326
- // package.json (or a tolerated legacy upstream name during migration).
327
- // Walk until dirname(dir) === dir (filesystem root on any platform).
328
- for (;;) {
329
- const candidate = join(dir, 'package.json');
330
- try {
331
- if (existsSync(candidate)) {
332
- const pkg = JSON.parse(readFileSync(candidate, 'utf8'));
333
- if (pkg.version &&
334
- typeof pkg.name === 'string' &&
335
- (pkg.name === 'moflo' || pkg.name === 'claude-flow' || pkg.name === 'ruflo')) {
336
- currentVersion = pkg.version;
337
- break;
338
- }
339
- }
340
- }
341
- catch {
342
- // Unreadable/invalid JSON -- skip and keep walking up
343
- }
344
- const parent = dirname(dir);
345
- if (parent === dir)
346
- break; // reached root
347
- dir = parent;
348
- }
349
- }
350
- catch {
351
- // Fall back to a default
352
- currentVersion = '0.0.0';
353
- }
354
- // Check if running via npx (look for _npx in process path or argv)
355
- const isNpx = process.argv[1]?.includes('_npx') ||
356
- process.env.npm_execpath?.includes('npx') ||
357
- process.cwd().includes('_npx');
358
- // Query npm for latest version (using alpha tag since that's what we publish to)
359
- let latestVersion = currentVersion;
360
- try {
361
- const npmInfo = await runCommand('npm view moflo version', 5000);
362
- latestVersion = npmInfo.trim();
363
- }
364
- catch (e) {
365
- // Can't reach npm registry - skip check
366
- return {
367
- name: 'Version Freshness',
368
- status: 'warn',
369
- message: `v${currentVersion} (cannot check registry: ${errorDetail(e, { firstLineOnly: true })})`
370
- };
371
- }
372
- // Parse version numbers for comparison (handle prerelease like 3.0.0-alpha.84)
373
- const parseVersion = (v) => {
374
- const match = v.match(/^(\d+)\.(\d+)\.(\d+)(?:-[a-zA-Z]+\.(\d+))?/);
375
- if (!match)
376
- return { major: 0, minor: 0, patch: 0, prerelease: 0 };
377
- return {
378
- major: parseInt(match[1], 10) || 0,
379
- minor: parseInt(match[2], 10) || 0,
380
- patch: parseInt(match[3], 10) || 0,
381
- prerelease: parseInt(match[4], 10) || 0
382
- };
383
- };
384
- const current = parseVersion(currentVersion);
385
- const latest = parseVersion(latestVersion);
386
- // Compare versions (including prerelease number)
387
- const isOutdated = (latest.major > current.major ||
388
- (latest.major === current.major && latest.minor > current.minor) ||
389
- (latest.major === current.major && latest.minor === current.minor && latest.patch > current.patch) ||
390
- (latest.major === current.major && latest.minor === current.minor && latest.patch === current.patch && latest.prerelease > current.prerelease));
391
- if (isOutdated) {
392
- const fix = isNpx
393
- ? (process.platform === 'win32'
394
- ? 'npx -y moflo (or clear %LocalAppData%\\npm-cache\\_npx manually)'
395
- : 'rm -rf ~/.npm/_npx/* && npx -y moflo')
396
- : 'npm update moflo';
397
- return {
398
- name: 'Version Freshness',
399
- status: 'warn',
400
- message: `v${currentVersion} (latest: v${latestVersion})${isNpx ? ' [npx cache stale]' : ''}`,
401
- fix
402
- };
403
- }
404
- return {
405
- name: 'Version Freshness',
406
- status: 'pass',
407
- message: `v${currentVersion} (up to date)`
408
- };
409
- }
410
- catch (error) {
411
- return {
412
- name: 'Version Freshness',
413
- status: 'warn',
414
- message: `Unable to check version freshness: ${errorDetail(error)}`
415
- };
416
- }
417
- }
418
- // Check Claude Code CLI (async with proper env inheritance)
419
- async function checkClaudeCode() {
420
- try {
421
- const version = await runCommand('claude --version');
422
- // Parse version from output like "claude 1.0.0" or "Claude Code v1.0.0"
423
- const versionMatch = version.match(/v?(\d+\.\d+\.\d+)/);
424
- const versionStr = versionMatch ? `v${versionMatch[1]}` : version;
425
- return { name: 'Claude Code CLI', status: 'pass', message: versionStr };
426
- }
427
- catch (e) {
428
- return {
429
- name: 'Claude Code CLI',
430
- status: 'warn',
431
- message: `Not installed (${errorDetail(e, { firstLineOnly: true })})`,
432
- fix: 'npm install -g @anthropic-ai/claude-code'
433
- };
434
- }
435
- }
436
- // Install Claude Code CLI
437
- async function installClaudeCode() {
438
- try {
439
- output.writeln();
440
- output.writeln(output.bold('Installing Claude Code CLI...'));
441
- execSync('npm install -g @anthropic-ai/claude-code', {
442
- encoding: 'utf8',
443
- stdio: 'inherit',
444
- windowsHide: true
445
- });
446
- output.writeln(output.success('Claude Code CLI installed successfully!'));
447
- return true;
448
- }
449
- catch (error) {
450
- output.writeln(output.error('Failed to install Claude Code CLI'));
451
- if (error instanceof Error) {
452
- output.writeln(output.dim(error.message));
453
- }
454
- return false;
455
- }
456
- }
457
- /**
458
- * Open `dbPath` via moflo's bundled sql.js and return the count of memory_entries
459
- * rows that have an embedding. Returns null if sql.js can't be loaded, the file
460
- * isn't a v3 schema, or the query fails — every error is treated as "unknown
461
- * truth", letting the caller fall back to the cached stats rather than masking
462
- * a healthy DB as broken.
463
- */
464
- async function countEmbeddedRowsFromDb(dbPath) {
465
- try {
466
- const { mofloImport } = await import('../services/moflo-require.js');
467
- const initSqlJs = (await mofloImport('sql.js'))?.default;
468
- if (!initSqlJs)
469
- return null;
470
- const SQL = await initSqlJs();
471
- const buffer = readFileSync(dbPath);
472
- const db = new SQL.Database(buffer);
473
- try {
474
- const res = db.exec("SELECT COUNT(*) FROM memory_entries WHERE embedding IS NOT NULL AND embedding != ''");
475
- const cell = res?.[0]?.values?.[0]?.[0];
476
- return typeof cell === 'number' ? cell : Number(cell ?? 0);
477
- }
478
- finally {
479
- db.close();
480
- }
481
- }
482
- catch {
483
- return null;
484
- }
485
- }
486
- /** Skew (cached / live count delta) above which the cache is treated as stale. */
487
- const VECTOR_STATS_SKEW_WARN_THRESHOLD = 0.2;
488
- // Check embeddings / vector index health.
489
- // Exported so the #639 stale-cache regression test can invoke it directly.
490
- export async function checkEmbeddings() {
491
- const liveDbPath = memoryDbCandidatePaths(process.cwd()).find((p) => existsSync(p));
492
- // 1. Fast path: read cached vector-stats.json if available
493
- const statsPath = join(process.cwd(), '.moflo', 'vector-stats.json');
494
- try {
495
- if (existsSync(statsPath)) {
496
- const stats = JSON.parse(readFileSync(statsPath, 'utf8'));
497
- const count = stats.vectorCount ?? 0;
498
- const updatedAt = typeof stats.updatedAt === 'number' ? stats.updatedAt : 0;
499
- const hasHnsw = stats.hasHnsw ?? false;
500
- const dbSizeKB = stats.dbSizeKB ?? 0;
501
- // Skew check (#639): the cache can drift out of sync with the live DB
502
- // when a writer clobbers it with zeros (#639) or when an external tool
503
- // mutates memory.db without going through the bridge. Cross-check the
504
- // cached vectorCount against the actual DB; if they differ by more than
505
- // VECTOR_STATS_SKEW_WARN_THRESHOLD, surface a stale-cache warning rather
506
- // than displaying a wrong number on the statusline.
507
- //
508
- // Cheap signals first — opening memory.db via sql.js loads the whole
509
- // file. Skip the open when the cache was clearly written after the last
510
- // DB mutation (mtime check) AND the cached count is non-zero. The
511
- // count===0 case keeps the open because that's the observed #639 failure
512
- // mode (cache silently clobbered to zero).
513
- let dbMtimeMs = 0;
514
- if (liveDbPath) {
515
- try {
516
- dbMtimeMs = statSync(liveDbPath).mtimeMs;
517
- }
518
- catch { /* missing — handled below */ }
519
- }
520
- const cacheNewerThanDb = updatedAt > 0 && dbMtimeMs > 0 && updatedAt >= dbMtimeMs;
521
- if (liveDbPath && (count === 0 || !cacheNewerThanDb)) {
522
- const liveCount = await countEmbeddedRowsFromDb(liveDbPath);
523
- if (liveCount !== null) {
524
- const denom = Math.max(liveCount, 1);
525
- const skew = Math.abs(liveCount - count) / denom;
526
- if (skew > VECTOR_STATS_SKEW_WARN_THRESHOLD) {
527
- return {
528
- name: 'Embeddings',
529
- status: 'warn',
530
- message: `vector-stats cache is stale (cached ${count}, DB has ${liveCount} embedded rows — ${Math.round(skew * 100)}% skew)`,
531
- fix: 'node node_modules/moflo/bin/build-embeddings.mjs',
532
- };
533
- }
534
- }
535
- }
536
- if (count === 0) {
537
- return {
538
- name: 'Embeddings',
539
- status: 'warn',
540
- message: `Memory DB exists (${dbSizeKB} KB) but 0 vectors indexed — documents not embedded`,
541
- fix: 'npx moflo memory init --force && npx moflo embeddings init'
542
- };
543
- }
544
- const hnswLabel = hasHnsw ? ', HNSW' : '';
545
- return {
546
- name: 'Embeddings',
547
- status: 'pass',
548
- message: `${count} vectors indexed (${dbSizeKB} KB${hnswLabel})`
549
- };
550
- }
551
- }
552
- catch {
553
- // Stats file unreadable — fall through to DB check
554
- }
555
- // 2. Check if memory DB file exists at all (reuse liveDbPath from above)
556
- const foundDbPath = liveDbPath ?? null;
557
- if (!foundDbPath) {
558
- return {
559
- name: 'Embeddings',
560
- status: 'warn',
561
- message: 'No memory database — embeddings not initialized',
562
- fix: 'npx moflo memory init --force'
563
- };
564
- }
565
- // 3. DB exists but no stats cache — try querying the DB for entry count
566
- try {
567
- const { checkMemoryInitialization } = await import('../memory/memory-initializer.js');
568
- const info = await checkMemoryInitialization(foundDbPath);
569
- if (!info.initialized) {
570
- return {
571
- name: 'Embeddings',
572
- status: 'warn',
573
- message: 'Memory DB exists but not properly initialized',
574
- fix: 'npx moflo memory init --force'
575
- };
576
- }
577
- const hasVectors = info.features?.vectorEmbeddings ?? false;
578
- if (!hasVectors) {
579
- return {
580
- name: 'Embeddings',
581
- status: 'warn',
582
- message: `Memory DB initialized (v${info.version}) but no vector_indexes table`,
583
- fix: 'npx moflo memory init --force && npx moflo embeddings init'
584
- };
585
- }
586
- return {
587
- name: 'Embeddings',
588
- status: 'pass',
589
- message: `Memory DB initialized (v${info.version}, vectors enabled)`
590
- };
591
- }
592
- catch (sqlJsError) {
593
- // sql.js not available — fall back to file-size heuristic
594
- const sqlDetail = errorDetail(sqlJsError);
595
- try {
596
- const stats = statSync(foundDbPath);
597
- const sizeMB = (stats.size / 1024 / 1024).toFixed(2);
598
- return {
599
- name: 'Embeddings',
600
- status: 'warn',
601
- message: `Memory DB exists (${sizeMB} MB) — cannot verify vectors (sql.js not available: ${sqlDetail})`,
602
- fix: 'npm install sql.js && npx moflo embeddings init'
603
- };
604
- }
605
- catch (statError) {
606
- return { name: 'Embeddings', status: 'warn', message: `Unable to check: sql.js failed (${sqlDetail}), stat failed (${errorDetail(statError)})` };
607
- }
608
- }
609
- }
610
- /**
611
- * Auto-fix: execute fix commands for a failed/warned health check.
612
- * Returns true if the fix succeeded (re-check should pass).
613
- */
614
- async function autoFixCheck(check) {
615
- if (!check.fix)
616
- return false;
617
- // Map checks to programmatic fixes (not just shell commands)
618
- const fixActions = {
619
- 'Memory Database': async () => {
620
- try {
621
- const swarmDir = join(process.cwd(), '.swarm');
622
- if (!existsSync(swarmDir))
623
- mkdirSync(swarmDir, { recursive: true });
624
- const { initializeMemoryDatabase } = await import('../memory/memory-initializer.js');
625
- const result = await initializeMemoryDatabase({ force: true, verbose: false });
626
- return result.success;
627
- }
628
- catch {
629
- // Fall back to CLI
630
- return runFixCommand('npx moflo memory init --force');
631
- }
632
- },
633
- 'Embeddings': async () => {
634
- try {
635
- // Step 1: ensure memory DB exists
636
- const swarmDir = join(process.cwd(), '.swarm');
637
- if (!existsSync(swarmDir))
638
- mkdirSync(swarmDir, { recursive: true });
639
- const dbPath = join(swarmDir, 'memory.db');
640
- if (!existsSync(dbPath)) {
641
- const { initializeMemoryDatabase } = await import('../memory/memory-initializer.js');
642
- await initializeMemoryDatabase({ force: true, verbose: false });
643
- }
644
- // Step 2: attempt embeddings init via CLI
645
- return runFixCommand('npx moflo embeddings init --force');
646
- }
647
- catch {
648
- return runFixCommand('npx moflo memory init --force');
649
- }
650
- },
651
- 'Config File': async () => {
652
- try {
653
- const cfDir = join(process.cwd(), '.moflo');
654
- if (!existsSync(cfDir))
655
- mkdirSync(cfDir, { recursive: true });
656
- return runFixCommand('npx moflo config init');
657
- }
658
- catch {
659
- return false;
660
- }
661
- },
662
- 'Daemon Status': async () => {
663
- // Clean stale locks, then try to start daemon
664
- const lockFile = join(process.cwd(), '.moflo', 'daemon.lock');
665
- const pidFile = join(process.cwd(), '.moflo', 'daemon.pid');
666
- try {
667
- if (existsSync(lockFile)) {
668
- const { unlinkSync } = await import('fs');
669
- unlinkSync(lockFile);
670
- }
671
- if (existsSync(pidFile)) {
672
- const { unlinkSync } = await import('fs');
673
- unlinkSync(pidFile);
674
- }
675
- }
676
- catch { /* best effort */ }
677
- return runFixCommand('npx moflo daemon start');
678
- },
679
- 'MCP Servers': async () => {
680
- return runFixCommand('claude mcp add moflo -- npx -y moflo mcp start');
681
- },
682
- 'Claude Code CLI': async () => {
683
- return installClaudeCode();
684
- },
685
- 'Zombie Processes': async () => {
686
- const result = await findZombieProcesses(true);
687
- return result.killed > 0 || result.found === 0;
688
- },
689
- 'Gate Health': async () => {
690
- return fixGateHealthHooks();
691
- },
692
- 'Status Line': async () => {
693
- const settingsPath = join(process.cwd(), '.claude', 'settings.json');
694
- if (!existsSync(settingsPath))
695
- return false;
696
- try {
697
- const settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
698
- if (!settings.statusLine) {
699
- settings.statusLine = {
700
- type: 'command',
701
- command: 'node "$CLAUDE_PROJECT_DIR/.claude/helpers/statusline.cjs" --compact',
702
- };
703
- writeFileSync(settingsPath, JSON.stringify(settings, null, 2), 'utf-8');
704
- }
705
- return true;
706
- }
707
- catch {
708
- return false;
709
- }
710
- },
711
- };
712
- const fixFn = fixActions[check.name];
713
- if (fixFn) {
714
- try {
715
- output.writeln(output.dim(` Fixing: ${check.name}...`));
716
- const success = await fixFn();
717
- if (success) {
718
- output.writeln(output.success(` Fixed: ${check.name}`));
719
- }
720
- else {
721
- output.writeln(output.warning(` Fix attempted but may need manual action: ${check.fix}`));
722
- }
723
- return success;
724
- }
725
- catch (e) {
726
- output.writeln(output.warning(` Fix failed: ${errorDetail(e)}`));
727
- return false;
728
- }
729
- }
730
- // Generic: try running the fix command directly if it looks like a shell command
731
- if (check.fix.startsWith('npx ') || check.fix.startsWith('npm ') || check.fix.startsWith('claude ')) {
732
- return runFixCommand(check.fix);
733
- }
734
- return false;
735
- }
736
- /**
737
- * Run a shell command as a fix action. Returns true on exit code 0.
738
- */
739
- async function runFixCommand(cmd) {
740
- try {
741
- await execAsync(cmd, {
742
- encoding: 'utf8',
743
- timeout: 30000,
744
- shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/sh',
745
- env: { ...process.env },
746
- windowsHide: true,
747
- });
748
- return true;
749
- }
750
- catch {
751
- return false;
752
- }
753
- }
754
- /**
755
- * Fix missing hook wiring in settings.json by patching in entries for
756
- * any REQUIRED_HOOK_WIRING patterns that aren't present.
757
- * Delegates to shared repairHookWiring() to stay DRY with the upgrade path.
758
- */
759
- async function fixGateHealthHooks() {
760
- const settingsPath = join(process.cwd(), '.claude', 'settings.json');
761
- if (!existsSync(settingsPath))
762
- return false;
763
- try {
764
- const raw = readFileSync(settingsPath, 'utf8');
765
- const settings = JSON.parse(raw);
766
- const { repaired } = repairHookWiring(settings);
767
- if (repaired.length === 0)
768
- return true; // nothing to fix
769
- writeFileSync(settingsPath, JSON.stringify(settings, null, 2), 'utf-8');
770
- return true;
771
- }
772
- catch {
773
- return false;
774
- }
775
- }
776
- // Check test directories configured in moflo.yaml
777
- async function checkTestDirs() {
778
- const yamlPath = join(process.cwd(), 'moflo.yaml');
779
- if (!existsSync(yamlPath)) {
780
- return { name: 'Test Directories', status: 'warn', message: 'No moflo.yaml — test indexing unconfigured', fix: 'npx moflo init' };
781
- }
782
- try {
783
- const content = readFileSync(yamlPath, 'utf-8');
784
- // Check if tests section exists
785
- const testsBlock = content.match(/tests:\s*\n\s+directories:\s*\n((?:\s+-\s+.+\n?)+)/);
786
- if (!testsBlock) {
787
- return { name: 'Test Directories', status: 'warn', message: 'No tests section in moflo.yaml', fix: 'npx moflo init --force' };
788
- }
789
- // Extract configured directories
790
- const items = testsBlock[1].match(/-\s+(.+)/g);
791
- if (!items || items.length === 0) {
792
- return { name: 'Test Directories', status: 'warn', message: 'Empty test directories list' };
793
- }
794
- const dirs = items.map(item => item.replace(/^-\s+/, '').trim());
795
- const existing = dirs.filter(d => existsSync(join(process.cwd(), d)));
796
- const missing = dirs.filter(d => !existsSync(join(process.cwd(), d)));
797
- // Check auto_index.tests flag
798
- const autoIndexMatch = content.match(/auto_index:\s*\n(?:.*\n)*?\s+tests:\s*(true|false)/);
799
- const autoIndexEnabled = !autoIndexMatch || autoIndexMatch[1] !== 'false';
800
- const indexLabel = autoIndexEnabled ? 'auto-index: on' : 'auto-index: off';
801
- if (missing.length > 0 && existing.length === 0) {
802
- return {
803
- name: 'Test Directories',
804
- status: 'warn',
805
- message: `No configured test dirs exist: ${missing.join(', ')} (${indexLabel})`,
806
- };
807
- }
808
- if (missing.length > 0) {
809
- return {
810
- name: 'Test Directories',
811
- status: 'warn',
812
- message: `${existing.length} OK, ${missing.length} missing: ${missing.join(', ')} (${indexLabel})`,
813
- };
814
- }
815
- return { name: 'Test Directories', status: 'pass', message: `${existing.length} directories: ${existing.join(', ')} (${indexLabel})` };
816
- }
817
- catch (e) {
818
- return { name: 'Test Directories', status: 'warn', message: `Unable to parse moflo.yaml: ${errorDetail(e)}` };
819
- }
820
- }
821
- // Check semantic search quality — verify no 0.500 keyword fallback scores
822
- async function checkSemanticQuality() {
823
- try {
824
- const { searchEntries } = await import('../memory/memory-initializer.js');
825
- const result = await searchEntries({
826
- query: 'test infrastructure health check',
827
- namespace: 'patterns',
828
- limit: 5,
829
- threshold: 0.1
830
- });
831
- if (!result.success || result.results.length === 0) {
832
- return {
833
- name: 'Semantic Quality',
834
- status: 'warn',
835
- message: 'No search results (empty database or no patterns namespace)',
836
- };
837
- }
838
- const scores = result.results.map((r) => r.score);
839
- const allSame = scores.every((s) => s === scores[0]);
840
- const hasFallback = scores.some((s) => s === 0.5);
841
- if (hasFallback) {
842
- return {
843
- name: 'Semantic Quality',
844
- status: 'fail',
845
- message: `${scores.length} results, scores include 0.500 fallback (keyword-only, no embeddings)`,
846
- fix: 'Re-index with: npx moflo embeddings build --force'
847
- };
848
- }
849
- if (allSame && scores.length > 1) {
850
- return {
851
- name: 'Semantic Quality',
852
- status: 'warn',
853
- message: `${scores.length} results, all scores identical (${scores[0].toFixed(3)}) — degraded search`,
854
- };
855
- }
856
- const topScore = Math.max(...scores);
857
- return {
858
- name: 'Semantic Quality',
859
- status: topScore >= 0.3 ? 'pass' : 'warn',
860
- message: `${scores.length} results, top ${topScore.toFixed(3)}, varied (semantic search active)`,
861
- };
862
- }
863
- catch (e) {
864
- return {
865
- name: 'Semantic Quality',
866
- status: 'warn',
867
- message: `Check failed: ${e instanceof Error ? e.message.split(/\r?\n/)[0] : 'error'}`,
868
- };
869
- }
870
- }
871
- // Check memory-backed patterns (populated by pretrain) as a fallback for neural checks.
872
- // Uses the same pattern-search handler that pretrain writes to.
873
- async function checkMemoryPatterns(_namespace) {
874
- try {
875
- // Use the pattern-search handler (same store pretrain writes to)
876
- const hooksMod = await import('../mcp-tools/hooks-tools.js');
877
- if (hooksMod.hooksPatternSearch) {
878
- const result = await hooksMod.hooksPatternSearch.handler({
879
- query: 'pretrain',
880
- topK: 1,
881
- minConfidence: 0.1,
882
- });
883
- const matches = result?.results;
884
- if (Array.isArray(matches))
885
- return matches.length;
886
- }
887
- }
888
- catch {
889
- // hooks module not available
890
- }
891
- // Secondary fallback: check the memory DB file exists
892
- try {
893
- const { existsSync } = await import('fs');
894
- const { join } = await import('path');
895
- const dbPath = join(process.cwd(), '.claude', 'memory.db');
896
- if (existsSync(dbPath))
897
- return 1;
898
- }
899
- catch {
900
- // fs not available
901
- }
902
- return 0;
903
- }
904
- // Check intelligence layer: SONA, EWC++, LoRA, Flash Attention, ReasoningBank
905
- // Exercises each component with a lightweight functional test rather than just checking "loaded".
906
- async function checkIntelligence() {
907
- try {
908
- const neural = await import('../neural/index.js');
909
- const results = [];
910
- const failures = [];
911
- // 1. SONA — create manager, run trajectory lifecycle
912
- try {
913
- const sona = neural.createSONAManager('balanced');
914
- await sona.initialize();
915
- const tid = sona.beginTrajectory('doctor-check', 'general');
916
- const embedding = new Float32Array(64).fill(0.1);
917
- sona.recordStep(tid, 'test-action', 0.8, embedding);
918
- const traj = sona.completeTrajectory(tid, 0.9);
919
- if (traj && traj.steps.length > 0) {
920
- results.push('SONA');
921
- }
922
- else {
923
- failures.push('SONA (no trajectory output)');
924
- }
925
- await sona.cleanup();
926
- }
927
- catch (e) {
928
- failures.push(`SONA (${e instanceof Error ? e.message : 'error'})`);
929
- }
930
- // 2. ReasoningBank — verify instantiation and trajectory store/distill lifecycle
931
- try {
932
- const rb = neural.createReasoningBank();
933
- const stateAfter = new Float32Array(64).fill(0.2);
934
- const trajectory = {
935
- trajectoryId: 'doctor-test',
936
- context: 'health check',
937
- domain: 'general',
938
- steps: [{ stepId: 's1', action: 'test', reward: 1, stateBefore: stateAfter, stateAfter, timestamp: Date.now() }],
939
- startTime: Date.now(),
940
- endTime: Date.now(),
941
- qualityScore: 0.9,
942
- isComplete: true,
943
- verdict: {
944
- success: true,
945
- confidence: 0.9,
946
- strengths: ['health check passed'],
947
- weaknesses: [],
948
- improvements: [],
949
- relevanceScore: 0.9,
950
- },
951
- };
952
- rb.storeTrajectory(trajectory);
953
- // distill() populates memories (storeTrajectory alone does not)
954
- const distilled = await rb.distill(trajectory);
955
- if (distilled || rb.getTrajectories().length > 0) {
956
- results.push('ReasoningBank');
957
- }
958
- else {
959
- // Fallback: check memory-backed patterns from pretrain
960
- const memoryPatterns = await checkMemoryPatterns('patterns');
961
- if (memoryPatterns > 0) {
962
- results.push('ReasoningBank(memory)');
963
- }
964
- else {
965
- failures.push('ReasoningBank (distill returned no data)');
966
- }
967
- }
968
- }
969
- catch (e) {
970
- failures.push(`ReasoningBank (${e instanceof Error ? e.message : 'error'})`);
971
- }
972
- // 3. PatternLearner — extract + match
973
- try {
974
- const pl = neural.createPatternLearner();
975
- const embedding = new Float32Array(64).fill(0.3);
976
- const now = Date.now();
977
- pl.extractPattern({
978
- trajectoryId: 'doctor-pl', context: 'test', domain: 'general',
979
- steps: [{ stepId: 's1', action: 'test', reward: 1, stateBefore: embedding, stateAfter: embedding, timestamp: now }],
980
- startTime: now, endTime: now, qualityScore: 1, isComplete: true,
981
- }, { memoryId: 'doctor-pl-mem', trajectoryId: 'doctor-pl', strategy: 'health-check', keyLearnings: ['test'], embedding, quality: 1, usageCount: 0, lastUsed: now });
982
- const matches = pl.findMatches(embedding, 1);
983
- if (matches.length > 0) {
984
- results.push('PatternLearner');
985
- }
986
- else {
987
- // Fallback: check memory-backed patterns from pretrain
988
- const memoryPatterns = await checkMemoryPatterns('patterns');
989
- if (memoryPatterns > 0) {
990
- results.push('PatternLearner(memory)');
991
- }
992
- else {
993
- failures.push('PatternLearner (no matches)');
994
- }
995
- }
996
- }
997
- catch (e) {
998
- failures.push(`PatternLearner (${e instanceof Error ? e.message : 'error'})`);
999
- }
1000
- // 4. SONALearningEngine (MicroLoRA + EWC++)
1001
- try {
1002
- const engine = neural.createSONALearningEngine();
1003
- const ctx = { domain: 'general', queryEmbedding: new Float32Array(768).fill(0.1) };
1004
- const adapted = await engine.adapt(ctx);
1005
- const components = [];
1006
- if (adapted && adapted.transformedQuery)
1007
- components.push('LoRA');
1008
- if (adapted && adapted.patterns !== undefined)
1009
- components.push('EWC++');
1010
- if (components.length > 0) {
1011
- results.push(...components);
1012
- }
1013
- else {
1014
- failures.push('LoRA/EWC++ (adapt returned no data)');
1015
- }
1016
- }
1017
- catch (e) {
1018
- // Gracefully handle cold/uninitialized state
1019
- const msg = e instanceof Error ? e.message : 'error';
1020
- if (msg.includes('undefined') || msg.includes('not initialized')) {
1021
- results.push('LoRA/EWC++(cold)');
1022
- }
1023
- else {
1024
- failures.push(`LoRA/EWC++ (${msg})`);
1025
- }
1026
- }
1027
- // 5. RL Algorithms — quick instantiation check
1028
- try {
1029
- const algNames = [];
1030
- const ppo = neural.createPPO();
1031
- if (ppo)
1032
- algNames.push('PPO');
1033
- const dqn = neural.createDQN();
1034
- if (dqn)
1035
- algNames.push('DQN');
1036
- const ql = neural.createQLearning();
1037
- if (ql)
1038
- algNames.push('Q-Learn');
1039
- if (algNames.length > 0) {
1040
- results.push(`RL(${algNames.join('+')})`);
1041
- }
1042
- }
1043
- catch (e) {
1044
- failures.push(`RL (${e instanceof Error ? e.message : 'error'})`);
1045
- }
1046
- if (failures.length > 0) {
1047
- return {
1048
- name: 'Intelligence',
1049
- status: results.length > 0 ? 'warn' : 'fail',
1050
- message: `${results.join(', ')} OK; FAILED: ${failures.join(', ')}`,
1051
- fix: 'Check neural module imports and dependencies',
1052
- };
1053
- }
1054
- return {
1055
- name: 'Intelligence',
1056
- status: 'pass',
1057
- message: results.join(', '),
1058
- };
1059
- }
1060
- catch (e) {
1061
- return {
1062
- name: 'Intelligence',
1063
- status: 'warn',
1064
- message: `Module unavailable: ${e instanceof Error ? e.message.split(/\r?\n/)[0] : 'import failed'}`,
1065
- fix: 'Ensure moflo is built (npm run build)',
1066
- };
1067
- }
1068
- }
1069
- // Check whether a given PID is still running.
1070
- // Uses signal 0 which works cross-platform (Windows, Linux, macOS) without
1071
- // needing PowerShell or /proc — Node handles the platform abstraction.
1072
- function isProcessAlive(pid) {
1073
- try {
1074
- process.kill(pid, 0);
1075
- return true;
1076
- }
1077
- catch {
1078
- return false;
1079
- }
1080
- }
1081
- // Fast path: kill processes tracked in the shared ProcessManager registry.
1082
- // This avoids the expensive OS-level process scan for known background tasks.
1083
- function killTrackedProcesses() {
1084
- const registryFile = join(process.cwd(), '.moflo', 'background-pids.json');
1085
- const lockFile = join(process.cwd(), '.moflo', 'spawn.lock');
1086
- let killed = 0;
1087
- try {
1088
- if (existsSync(registryFile)) {
1089
- const entries = JSON.parse(readFileSync(registryFile, 'utf-8'));
1090
- for (const entry of entries) {
1091
- if (!isProcessAlive(entry.pid))
1092
- continue;
1093
- try {
1094
- if (process.platform === 'win32') {
1095
- execSync(`taskkill /F /PID ${entry.pid}`, { timeout: 5000, windowsHide: true });
1096
- }
1097
- else {
1098
- process.kill(entry.pid, 'SIGKILL');
1099
- }
1100
- killed++;
1101
- }
1102
- catch { /* already gone */ }
1103
- }
1104
- // Clear registry
1105
- writeFileSync(registryFile, '[]');
1106
- }
1107
- }
1108
- catch { /* non-fatal */ }
1109
- // Remove spawn lock
1110
- try {
1111
- if (existsSync(lockFile))
1112
- unlinkSync(lockFile);
1113
- }
1114
- catch { /* ok */ }
1115
- return killed;
1116
- }
1117
- // Read the set of moflo background PIDs registered with the shared
1118
- // ProcessManager (.moflo/background-pids.json). These are legitimate tracked
1119
- // background tasks (sequential indexer chain, daemon, MCP servers spawned by
1120
- // session-start) — they are detached:true by design so their parents have
1121
- // already exited, but they are NOT orphans. Without this allow-set,
1122
- // findZombieProcesses() flags every running indexer step as a zombie.
1123
- function readTrackedBackgroundPids() {
1124
- const result = new Set();
1125
- const registryFile = join(process.cwd(), '.moflo', 'background-pids.json');
1126
- try {
1127
- if (!existsSync(registryFile))
1128
- return result;
1129
- const entries = JSON.parse(readFileSync(registryFile, 'utf-8'));
1130
- if (!Array.isArray(entries))
1131
- return result;
1132
- for (const entry of entries) {
1133
- if (entry && typeof entry.pid === 'number' && entry.pid > 0) {
1134
- result.add(entry.pid);
1135
- }
1136
- }
1137
- }
1138
- catch { /* malformed or unreadable — treat as empty */ }
1139
- return result;
1140
- }
1141
- // Find and optionally kill orphaned moflo/claude-flow node processes.
1142
- // A process is only "orphaned" if its parent is no longer alive — meaning
1143
- // nothing will clean it up. MCP servers spawned by a live Claude Code session
1144
- // have a live parent (claude.exe) and must not be flagged.
1145
- async function findZombieProcesses(kill = false) {
1146
- const legitimatePid = getDaemonLockHolder(process.cwd());
1147
- const trackedPids = readTrackedBackgroundPids();
1148
- const currentPid = process.pid;
1149
- const parentPid = process.ppid;
1150
- const found = [];
1151
- let killed = 0;
1152
- // Collect candidates as { pid, ppid } so we can check parent liveness
1153
- const candidates = [];
1154
- try {
1155
- if (process.platform === 'win32') {
1156
- // Windows: include ParentProcessId so we can verify orphan status
1157
- 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 });
1158
- const lines = result.split(/\r?\n/);
1159
- for (const line of lines) {
1160
- if (/moflo|claude-flow|flo\s+(hooks|gate|mcp|daemon)/i.test(line)) {
1161
- // Format-Table columns: ProcessId ParentProcessId CommandLine...
1162
- const match = line.match(/^\s*(\d+)\s+(\d+)/);
1163
- if (match) {
1164
- candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
1165
- }
1166
- }
1167
- }
1168
- }
1169
- else {
1170
- // Unix/macOS: use ps with explicit PID+PPID columns for reliable parsing
1171
- const result = execSync('ps -eo pid,ppid,command | grep -E "node.*(moflo|claude-flow)" | grep -v grep', { encoding: 'utf-8', timeout: 5000 });
1172
- const lines = result.trim().split(/\r?\n/);
1173
- for (const line of lines) {
1174
- const match = line.trim().match(/^(\d+)\s+(\d+)/);
1175
- if (match) {
1176
- candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
1177
- }
1178
- }
1179
- }
1180
- }
1181
- catch {
1182
- // No matches found (grep exits non-zero) or command failed
1183
- }
1184
- // Filter: skip known-good PIDs and processes whose parent is still alive.
1185
- // A live parent (e.g. claude.exe for MCP servers) means the process is managed, not orphaned.
1186
- for (const { pid, ppid } of candidates) {
1187
- if (pid === currentPid || pid === parentPid || pid === legitimatePid)
1188
- continue;
1189
- // Tracked background tasks (indexer chain, etc.) are detached:true so their
1190
- // parent is dead by design. The ProcessManager registry tells us they are
1191
- // legitimate, not orphaned.
1192
- if (trackedPids.has(pid))
1193
- continue;
1194
- if (isProcessAlive(ppid))
1195
- continue;
1196
- // Defense-in-depth: detached daemons have dead parents by design.
1197
- // Even if the lock file is missing/corrupted, don't kill a running daemon.
1198
- if (isDaemonProcess(pid))
1199
- continue;
1200
- found.push(pid);
1201
- }
1202
- if (kill && found.length > 0) {
1203
- for (const pid of found) {
1204
- try {
1205
- if (process.platform === 'win32') {
1206
- execSync(`taskkill /F /PID ${pid}`, { timeout: 5000, windowsHide: true });
1207
- }
1208
- else {
1209
- process.kill(pid, 'SIGKILL');
1210
- }
1211
- killed++;
1212
- }
1213
- catch {
1214
- // Process may have already exited
1215
- }
1216
- }
1217
- // Clean up stale daemon lock if we killed the holder
1218
- if (legitimatePid && found.includes(legitimatePid)) {
1219
- releaseDaemonLock(process.cwd(), legitimatePid, true);
1220
- }
1221
- }
1222
- return { found: found.length, killed, pids: found };
1223
- }
1224
- // Format health check result
1225
- function formatCheck(check) {
1226
- const icon = check.status === 'pass' ? output.success('✓') :
1227
- check.status === 'warn' ? output.warning('⚠') :
1228
- output.error('✗');
1229
- return `${icon} ${check.name}: ${check.message}`;
1230
- }
1231
- // Main doctor command
14
+ import { allChecks, componentMap } from './doctor-registry.js';
15
+ import { emitJsonOutput, finalize, formatCheck, maybeAutoInstallClaudeCode, renderSummary, runAutoFix, runKillZombiesBanner, } from './doctor-render.js';
16
+ import { checkEmbeddings } from './doctor-checks-memory.js';
17
+ import { checkMofloYamlCompliance } from './doctor-checks-config.js';
18
+ // Re-export for tests + external consumers (#639 stale-vector-stats test
19
+ // imports `checkEmbeddings`; init/upgrade flows import `checkMofloYamlCompliance`).
20
+ export { checkEmbeddings, checkMofloYamlCompliance };
1232
21
  export const doctorCommand = {
1233
22
  name: 'doctor',
1234
23
  aliases: ['healer'],
@@ -1239,34 +28,34 @@ export const doctorCommand = {
1239
28
  short: 'f',
1240
29
  description: 'Automatically fix issues where possible',
1241
30
  type: 'boolean',
1242
- default: false
31
+ default: false,
1243
32
  },
1244
33
  {
1245
34
  name: 'install',
1246
35
  short: 'i',
1247
36
  description: 'Auto-install missing dependencies (Claude Code CLI)',
1248
37
  type: 'boolean',
1249
- default: false
38
+ default: false,
1250
39
  },
1251
40
  {
1252
41
  name: 'component',
1253
42
  short: 'c',
1254
43
  description: 'Check specific component (version, node, npm, config, daemon, memory, embeddings, git, mcp, claude, disk, typescript, semantic, intelligence, swarm, hive-mind)',
1255
- type: 'string'
44
+ type: 'string',
1256
45
  },
1257
46
  {
1258
47
  name: 'verbose',
1259
48
  short: 'v',
1260
49
  description: 'Verbose output',
1261
50
  type: 'boolean',
1262
- default: false
51
+ default: false,
1263
52
  },
1264
53
  {
1265
54
  name: 'kill-zombies',
1266
55
  short: 'k',
1267
56
  description: 'Find and kill orphaned moflo/claude-flow node processes',
1268
57
  type: 'boolean',
1269
- default: false
58
+ default: false,
1270
59
  },
1271
60
  {
1272
61
  // Issue #784: fail on warnings. Used by consumer-install-smoke so a
@@ -1275,7 +64,7 @@ export const doctorCommand = {
1275
64
  name: 'strict',
1276
65
  description: 'Treat warnings as failures (non-zero exit). Used by CI.',
1277
66
  type: 'boolean',
1278
- default: false
67
+ default: false,
1279
68
  },
1280
69
  {
1281
70
  // Companion to --strict. CI-legitimate warnings (e.g. "Sandbox Tier"
@@ -1284,7 +73,7 @@ export const doctorCommand = {
1284
73
  // `name` field of each check (case-sensitive substring).
1285
74
  name: 'allow-warn',
1286
75
  description: 'In --strict mode, comma-separated check names whose warnings are tolerated.',
1287
- type: 'string'
76
+ type: 'string',
1288
77
  },
1289
78
  {
1290
79
  // Issue #818: machine-readable output. Suppresses banner/spinner/auto-fix
@@ -1293,8 +82,8 @@ export const doctorCommand = {
1293
82
  name: 'json',
1294
83
  description: 'Emit a single JSON document with per-check + per-subcheck details. Suppresses formatted output.',
1295
84
  type: 'boolean',
1296
- default: false
1297
- }
85
+ default: false,
86
+ },
1298
87
  ],
1299
88
  examples: [
1300
89
  { command: 'claude-flow doctor', description: 'Run full health check' },
@@ -1306,13 +95,12 @@ export const doctorCommand = {
1306
95
  { command: 'claude-flow doctor --strict', description: 'Fail (exit 1) on any warning — used by CI' },
1307
96
  { command: 'claude-flow doctor --json', description: 'Emit a single JSON doc with per-check + per-subcheck details (for CI/smoke gates)' },
1308
97
  { command: 'claude-flow doctor -c swarm', description: 'Run only the swarm + agent + task coordinator-path tripwire (epic #798)' },
1309
- { command: 'claude-flow doctor -c hive-mind', description: 'Run only the hive-mind MessageBus + shared-coordinator tripwire' }
98
+ { command: 'claude-flow doctor -c hive-mind', description: 'Run only the hive-mind MessageBus + shared-coordinator tripwire' },
1310
99
  ],
1311
100
  action: async (ctx) => {
1312
101
  const showFix = ctx.flags.fix;
1313
102
  const autoInstall = ctx.flags.install;
1314
103
  const component = ctx.flags.component;
1315
- const verbose = ctx.flags.verbose;
1316
104
  const killZombies = ctx.flags.killZombies;
1317
105
  const strict = ctx.flags.strict;
1318
106
  // Parser normalises kebab-case flag names to camelCase: `--allow-warn`
@@ -1337,283 +125,12 @@ export const doctorCommand = {
1337
125
  output.writeln(output.warning('--allow-warn requires --strict; ignoring (warnings are tolerated by default).'));
1338
126
  output.writeln();
1339
127
  }
1340
- // Handle --kill-zombies early
1341
128
  if (killZombies) {
1342
- output.writeln(output.bold('Zombie Process Scan'));
1343
- output.writeln();
1344
- // Fast path: kill tracked processes from the shared registry first
1345
- const registryKilled = killTrackedProcesses();
1346
- if (registryKilled > 0) {
1347
- output.writeln(output.success(` Killed ${registryKilled} tracked background process(es) from registry`));
1348
- }
1349
- // Slow path: OS-level scan for any remaining orphans
1350
- const scan = await findZombieProcesses(false);
1351
- if (scan.found === 0) {
1352
- if (registryKilled === 0) {
1353
- output.writeln(output.success(' No orphaned moflo processes found'));
1354
- }
1355
- }
1356
- else {
1357
- output.writeln(output.warning(` Found ${scan.found} additional orphaned process(es): PIDs ${scan.pids.join(', ')}`));
1358
- // Kill them
1359
- const result = await findZombieProcesses(true);
1360
- if (result.killed > 0) {
1361
- output.writeln(output.success(` Killed ${result.killed} zombie process(es)`));
1362
- }
1363
- if (result.killed < result.found) {
1364
- output.writeln(output.warning(` ${result.found - result.killed} process(es) could not be killed`));
1365
- }
1366
- }
1367
- output.writeln();
1368
- output.writeln(output.dim('─'.repeat(50)));
1369
- output.writeln();
1370
- }
1371
- const checkZombieProcesses = async () => {
1372
- try {
1373
- const scan = await findZombieProcesses(false);
1374
- if (scan.found === 0) {
1375
- return { name: 'Zombie Processes', status: 'pass', message: 'No orphaned processes' };
1376
- }
1377
- return {
1378
- name: 'Zombie Processes',
1379
- status: 'warn',
1380
- message: `${scan.found} orphaned process(es) (PIDs: ${scan.pids.join(', ')})`,
1381
- fix: 'moflo doctor --kill-zombies'
1382
- };
1383
- }
1384
- catch {
1385
- return { name: 'Zombie Processes', status: 'pass', message: 'Check skipped' };
1386
- }
1387
- };
1388
- // Check Spell Engine health — validates core modules, built output, and step commands
1389
- async function checkSpellEngine() {
1390
- try {
1391
- // Resolve relative to the moflo package root (works in both dev and consumer)
1392
- const mofloRoot = getMofloRoot();
1393
- if (!mofloRoot) {
1394
- return { name: 'Spell Engine', status: 'warn', message: 'Could not locate moflo package root', fix: 'npm run build' };
1395
- }
1396
- // Post-#586 workspace collapse: spell engine lives at src/cli/spells/
1397
- // (source) and dist/src/cli/spells/ (compiled). The legacy
1398
- // src/modules/spells/{src,dist}/ tree was deleted.
1399
- const distDir = join(mofloRoot, 'dist', 'src', 'cli', 'spells');
1400
- const srcDir = join(mofloRoot, 'src', 'cli', 'spells');
1401
- const hasDistDir = existsSync(distDir);
1402
- const hasSrcDir = existsSync(srcDir);
1403
- if (!hasDistDir && !hasSrcDir) {
1404
- return { name: 'Spell Engine', status: 'warn', message: 'Spell engine not found', fix: 'npm run build' };
1405
- }
1406
- // Core compiled modules that must exist
1407
- const coreModules = [
1408
- 'core/runner',
1409
- 'core/step-executor',
1410
- 'core/step-command-registry',
1411
- 'core/interpolation',
1412
- 'core/credential-masker',
1413
- 'registry/spell-registry',
1414
- 'factory/runner-factory',
1415
- 'schema',
1416
- 'types',
1417
- 'credentials',
1418
- 'scheduler',
1419
- ];
1420
- const baseDir = hasDistDir ? distDir : srcDir;
1421
- const ext = hasDistDir ? '.js' : '.ts';
1422
- // Directories don't need an extension check
1423
- const dirModules = ['schema', 'types', 'credentials', 'scheduler'];
1424
- const missing = coreModules.filter(m => dirModules.includes(m)
1425
- ? !existsSync(join(baseDir, m))
1426
- : !existsSync(join(baseDir, m + ext)));
1427
- if (missing.length > 0) {
1428
- return {
1429
- name: 'Spell Engine',
1430
- status: 'warn',
1431
- message: `Missing modules: ${missing.join(', ')}`,
1432
- fix: 'npm run build',
1433
- };
1434
- }
1435
- // Check for step commands directory
1436
- const commandsDir = join(baseDir, 'commands');
1437
- const hasCommands = existsSync(commandsDir);
1438
- // Check for spell definition loaders
1439
- const loadersDir = join(baseDir, 'loaders');
1440
- const hasLoaders = existsSync(loadersDir);
1441
- // Check for index entry point
1442
- const hasIndex = existsSync(join(baseDir, 'index' + ext));
1443
- const parts = [];
1444
- parts.push(`${coreModules.length} core modules`);
1445
- if (hasCommands)
1446
- parts.push('step commands');
1447
- if (hasLoaders)
1448
- parts.push('loaders');
1449
- if (hasIndex)
1450
- parts.push('index');
1451
- return {
1452
- name: 'Spell Engine',
1453
- status: 'pass',
1454
- message: parts.join(', '),
1455
- };
1456
- }
1457
- catch (e) {
1458
- return { name: 'Spell Engine', status: 'warn', message: `Unable to check spell engine: ${errorDetail(e)}` };
1459
- }
1460
- }
1461
- // Check sandbox tier — reports OS sandbox capability AND, if the project
1462
- // has `sandbox.enabled: true`, whether the effective sandbox would
1463
- // actually start (e.g. Windows Docker image pulled and configured).
1464
- async function checkSandboxTier() {
1465
- try {
1466
- const { detectSandboxCapability, loadSandboxConfigFromProject, resolveEffectiveSandbox, } = await import('../spells/index.js');
1467
- const cap = await detectSandboxCapability();
1468
- const config = await loadSandboxConfigFromProject(process.cwd());
1469
- // If sandboxing isn't enabled in moflo.yaml, just report capability.
1470
- if (!config.enabled) {
1471
- if (cap.available) {
1472
- return {
1473
- name: 'Sandbox Tier',
1474
- status: 'pass',
1475
- message: `${cap.tool} available (${cap.platform}) — sandboxing off in moflo.yaml`,
1476
- };
1477
- }
1478
- const offHint = {
1479
- win32: 'Install Docker Desktop and set sandbox.dockerImage in moflo.yaml to enable sandboxing',
1480
- linux: 'Install bubblewrap: sudo apt install bubblewrap',
1481
- darwin: 'sandbox-exec should be available on macOS — check /usr/bin/sandbox-exec',
1482
- };
1483
- return {
1484
- name: 'Sandbox Tier',
1485
- status: 'pass',
1486
- message: `sandboxing off (${cap.platform}, denylist active)`,
1487
- fix: offHint[cap.platform],
1488
- };
1489
- }
1490
- // Sandboxing is enabled — run the real resolver and surface any error.
1491
- try {
1492
- const effective = await resolveEffectiveSandbox(config);
1493
- if (effective.useOsSandbox) {
1494
- const imageHint = effective.config.dockerImage ? `, ${effective.config.dockerImage}` : '';
1495
- return {
1496
- name: 'Sandbox Tier',
1497
- status: 'pass',
1498
- message: `${cap.tool} ready (${cap.platform}${imageHint})`,
1499
- };
1500
- }
1501
- return {
1502
- name: 'Sandbox Tier',
1503
- status: 'warn',
1504
- message: `denylist only (${cap.platform})`,
1505
- };
1506
- }
1507
- catch (err) {
1508
- return {
1509
- name: 'Sandbox Tier',
1510
- status: 'warn',
1511
- message: `sandboxing enabled but not ready (${cap.platform})`,
1512
- fix: errorDetail(err),
1513
- };
1514
- }
1515
- }
1516
- catch (err) {
1517
- return {
1518
- name: 'Sandbox Tier',
1519
- status: 'warn',
1520
- message: `Unable to detect: ${err instanceof Error ? err.message : 'unknown error'}`,
1521
- };
1522
- }
1523
- }
1524
- const allChecks = [
1525
- checkVersionFreshness,
1526
- checkNodeVersion,
1527
- checkNpmVersion,
1528
- checkClaudeCode,
1529
- checkGit,
1530
- checkGitRepo,
1531
- checkConfigFile,
1532
- checkStatusLine,
1533
- checkDaemonStatus,
1534
- checkMemoryDatabase,
1535
- checkEmbeddings,
1536
- checkEmbeddingHygiene,
1537
- checkTestDirs,
1538
- checkMcpServers,
1539
- checkDiskSpace,
1540
- checkBuildTools,
1541
- checkSemanticQuality,
1542
- checkIntelligence,
1543
- checkSpellEngine,
1544
- checkZombieProcesses,
1545
- checkSubagentHealth,
1546
- checkSpellExecution,
1547
- checkMcpToolInvocation,
1548
- checkMcpSpellIntegration,
1549
- checkHookExecution,
1550
- checkGateHealth,
1551
- checkHookBlockDrift,
1552
- checkMofloDbBridge,
1553
- // Issue #818 / epic #798 — coordinator-path tripwires. They share the
1554
- // singleton coordinator with checkSubagentHealth above and assert by
1555
- // agent-id (not absolute counts) so they tolerate the parallel batch.
1556
- checkSwarmFunctional,
1557
- checkHiveMindFunctional,
1558
- // Issue #844 — memory_store + memory_search round-trip across subagent,
1559
- // swarm-agent, and hive-mind contexts. Catches the failure classes from
1560
- // #837 (threshold:0 ignored), #838/#842 (per-actor gating), and embedder
1561
- // wiring regressions (hash fallback) that the coordinator-only checks
1562
- // above would miss.
1563
- checkMemoryAccessFunctional,
1564
- checkSandboxTier,
1565
- ];
1566
- const componentMap = {
1567
- 'version': checkVersionFreshness,
1568
- 'freshness': checkVersionFreshness,
1569
- 'node': checkNodeVersion,
1570
- 'npm': checkNpmVersion,
1571
- 'claude': checkClaudeCode,
1572
- 'config': checkConfigFile,
1573
- 'statusline': checkStatusLine,
1574
- 'status-line': checkStatusLine,
1575
- 'daemon': checkDaemonStatus,
1576
- 'memory': checkMemoryDatabase,
1577
- 'embeddings': checkEmbeddings,
1578
- 'embedding-hygiene': checkEmbeddingHygiene,
1579
- 'hygiene': checkEmbeddingHygiene,
1580
- 'git': checkGit,
1581
- 'mcp': checkMcpServers,
1582
- 'disk': checkDiskSpace,
1583
- 'typescript': checkBuildTools,
1584
- 'tests': checkTestDirs,
1585
- 'semantic': checkSemanticQuality,
1586
- 'quality': checkSemanticQuality,
1587
- 'intelligence': checkIntelligence,
1588
- 'workflows': checkSpellEngine,
1589
- 'workflow': checkSpellEngine,
1590
- 'subagent': checkSubagentHealth,
1591
- 'subagents': checkSubagentHealth,
1592
- 'agents': checkSubagentHealth,
1593
- 'spell-exec': checkSpellExecution,
1594
- 'mcp-tools': checkMcpToolInvocation,
1595
- 'mcp-spell': checkMcpSpellIntegration,
1596
- 'hooks': checkHookExecution,
1597
- 'gates': checkGateHealth,
1598
- 'gate': checkGateHealth,
1599
- 'hook-drift': checkHookBlockDrift,
1600
- 'drift': checkHookBlockDrift,
1601
- 'sandbox': checkSandboxTier,
1602
- 'sandbox-tier': checkSandboxTier,
1603
- 'moflodb': checkMofloDbBridge,
1604
- 'bridge': checkMofloDbBridge,
1605
- 'swarm': checkSwarmFunctional,
1606
- 'swarm-functional': checkSwarmFunctional,
1607
- 'hive': checkHiveMindFunctional,
1608
- 'hive-mind': checkHiveMindFunctional,
1609
- 'hive-mind-functional': checkHiveMindFunctional,
1610
- 'memory-access': checkMemoryAccessFunctional,
1611
- 'memory-functional': checkMemoryAccessFunctional,
1612
- };
1613
- let checksToRun = allChecks;
1614
- if (component && componentMap[component]) {
1615
- checksToRun = [componentMap[component]];
129
+ await runKillZombiesBanner();
1616
130
  }
131
+ const checksToRun = component && componentMap[component]
132
+ ? [componentMap[component]]
133
+ : allChecks;
1617
134
  const results = [];
1618
135
  const fixes = [];
1619
136
  // OPTIMIZATION: Run all checks in parallel for 3-5x faster execution
@@ -1637,7 +154,6 @@ export const doctorCommand = {
1637
154
  (..._args) => true;
1638
155
  }
1639
156
  try {
1640
- // Execute all checks concurrently
1641
157
  let checkResults;
1642
158
  try {
1643
159
  checkResults = await Promise.allSettled(checksToRun.map(check => check()));
@@ -1646,7 +162,6 @@ export const doctorCommand = {
1646
162
  spinner?.stop();
1647
163
  restoreStdout();
1648
164
  }
1649
- // Process results in order
1650
165
  for (const settledResult of checkResults) {
1651
166
  if (settledResult.status === 'fulfilled') {
1652
167
  const result = settledResult.value;
@@ -1661,7 +176,7 @@ export const doctorCommand = {
1661
176
  const errorResult = {
1662
177
  name: 'Check',
1663
178
  status: 'fail',
1664
- message: settledResult.reason?.message || 'Unknown error'
179
+ message: settledResult.reason?.message || 'Unknown error',
1665
180
  };
1666
181
  results.push(errorResult);
1667
182
  if (!jsonOutput)
@@ -1669,165 +184,28 @@ export const doctorCommand = {
1669
184
  }
1670
185
  }
1671
186
  }
1672
- catch (error) {
187
+ catch {
1673
188
  spinner?.stop();
1674
189
  restoreStdout();
1675
190
  if (!jsonOutput)
1676
191
  output.writeln(output.error('Failed to run health checks'));
1677
192
  }
1678
- // Issue #818: machine-readable output. Emits a single JSON document with
1679
- // per-check fields (and any FunctionalCheckDetail entries from the swarm/
1680
- // hive checks) and exits with the right code. Skips auto-fix entirely —
1681
- // --json is read-only by intent so CI gates can consume it without
1682
- // mutating the working tree.
1683
193
  if (jsonOutput) {
1684
- const passed = results.filter(r => r.status === 'pass').length;
1685
- const warnings = results.filter(r => r.status === 'warn').length;
1686
- const failed = results.filter(r => r.status === 'fail').length;
1687
- const allowSet = new Set(allowWarnList);
1688
- const strictWarningFailures = strict
1689
- ? results.filter(r => r.status === 'warn' && !allowSet.has(r.name)).map(r => r.name)
1690
- : [];
1691
- const exitCode = failed > 0 || strictWarningFailures.length > 0 ? 1 : 0;
1692
- process.stdout.write(JSON.stringify({
1693
- summary: { passed, warnings, failed },
1694
- strict: strict ? { strictMode: true, warningsTriggeringFail: strictWarningFailures } : { strictMode: false },
1695
- results,
1696
- }, null, 2) + '\n');
1697
- return { success: exitCode === 0, exitCode, data: { passed, warnings, failed, results } };
194
+ return emitJsonOutput({ results, strict, allowWarnList });
1698
195
  }
1699
- // Auto-install missing dependencies if requested
1700
196
  if (autoInstall) {
1701
- const claudeCodeResult = results.find(r => r.name === 'Claude Code CLI');
1702
- if (claudeCodeResult && claudeCodeResult.status !== 'pass') {
1703
- const installed = await installClaudeCode();
1704
- if (installed) {
1705
- // Re-check Claude Code after installation
1706
- const newCheck = await checkClaudeCode();
1707
- const idx = results.findIndex(r => r.name === 'Claude Code CLI');
1708
- if (idx !== -1) {
1709
- results[idx] = newCheck;
1710
- // Update fixes list
1711
- const fixIdx = fixes.findIndex(f => f.startsWith('Claude Code CLI:'));
1712
- if (fixIdx !== -1 && newCheck.status === 'pass') {
1713
- fixes.splice(fixIdx, 1);
1714
- }
1715
- }
1716
- output.writeln(formatCheck(newCheck));
1717
- }
1718
- }
197
+ await maybeAutoInstallClaudeCode(results, fixes);
1719
198
  }
1720
- // Summary
1721
- const passed = results.filter(r => r.status === 'pass').length;
1722
- const warnings = results.filter(r => r.status === 'warn').length;
1723
- const failed = results.filter(r => r.status === 'fail').length;
1724
- output.writeln();
1725
- output.writeln(output.dim('─'.repeat(50)));
1726
- output.writeln();
1727
- const summaryParts = [
1728
- output.success(`${passed} passed`),
1729
- warnings > 0 ? output.warning(`${warnings} warnings`) : null,
1730
- failed > 0 ? output.error(`${failed} failed`) : null
1731
- ].filter(Boolean);
1732
- output.writeln(`Summary: ${summaryParts.join(', ')}`);
1733
- // Auto-fix or show fixes
199
+ renderSummary(results);
1734
200
  if (showFix && fixes.length > 0) {
1735
- output.writeln();
1736
- output.writeln(output.bold('Auto-fixing issues...'));
1737
- output.writeln();
1738
- const fixableResults = results.filter(r => r.fix && (r.status === 'fail' || r.status === 'warn'));
1739
- let fixed = 0;
1740
- const unfixed = [];
1741
- for (const check of fixableResults) {
1742
- const success = await autoFixCheck(check);
1743
- if (success) {
1744
- fixed++;
1745
- }
1746
- else {
1747
- unfixed.push(`${check.name}: ${check.fix}`);
1748
- }
1749
- }
1750
- if (fixed > 0) {
1751
- output.writeln();
1752
- output.writeln(output.success(`Auto-fixed ${fixed} issue${fixed > 1 ? 's' : ''}`));
1753
- }
1754
- if (unfixed.length > 0) {
1755
- output.writeln();
1756
- output.writeln(output.bold('Manual fixes needed:'));
1757
- for (const fix of unfixed) {
1758
- output.writeln(output.dim(` ${fix}`));
1759
- }
1760
- }
1761
- // Re-run checks to show updated status
1762
- if (fixed > 0) {
1763
- output.writeln();
1764
- output.writeln(output.dim('Re-checking...'));
1765
- output.writeln();
1766
- const reResults = await Promise.allSettled(checksToRun.map(check => check()));
1767
- let rePassed = 0, reWarnings = 0, reFailed = 0;
1768
- for (const sr of reResults) {
1769
- if (sr.status === 'fulfilled') {
1770
- output.writeln(formatCheck(sr.value));
1771
- if (sr.value.status === 'pass')
1772
- rePassed++;
1773
- else if (sr.value.status === 'warn')
1774
- reWarnings++;
1775
- else
1776
- reFailed++;
1777
- }
1778
- }
1779
- output.writeln();
1780
- output.writeln(output.dim('─'.repeat(50)));
1781
- const reSummary = [
1782
- output.success(`${rePassed} passed`),
1783
- reWarnings > 0 ? output.warning(`${reWarnings} warnings`) : null,
1784
- reFailed > 0 ? output.error(`${reFailed} failed`) : null
1785
- ].filter(Boolean);
1786
- output.writeln(`After fix: ${reSummary.join(', ')}`);
1787
- }
201
+ await runAutoFix(results, fixes, checksToRun);
1788
202
  }
1789
203
  else if (fixes.length > 0 && !showFix) {
1790
204
  output.writeln();
1791
205
  output.writeln(output.dim(`Run with --fix to auto-fix ${fixes.length} issue${fixes.length > 1 ? 's' : ''}`));
1792
206
  }
1793
- // Overall result
1794
- if (failed > 0) {
1795
- output.writeln();
1796
- output.writeln(output.error('Some checks failed. Please address the issues above.'));
1797
- return { success: false, exitCode: 1, data: { passed, warnings, failed, results } };
1798
- }
1799
- else if (warnings > 0) {
1800
- // Issue #784: in strict mode any non-allowlisted warning fails the run.
1801
- // Equality (not substring) match — an allowlist entry tolerates exactly
1802
- // that check, never accidentally suppresses neighboring checks like
1803
- // "Git" allowlisting "Git Repository".
1804
- if (strict) {
1805
- const warnResults = results.filter((r) => r.status === 'warn');
1806
- const allowSet = new Set(allowWarnList);
1807
- const offending = warnResults.filter((r) => !r.name || !allowSet.has(r.name));
1808
- if (offending.length > 0) {
1809
- output.writeln();
1810
- output.writeln(output.error(`--strict: ${offending.length} warning${offending.length > 1 ? 's' : ''} not allowlisted ` +
1811
- `(use --allow-warn "<name>,<name>" to tolerate intentional warnings):`));
1812
- for (const r of offending) {
1813
- output.writeln(output.error(` ✗ ${r.name}: ${r.message ?? ''}`));
1814
- }
1815
- return { success: false, exitCode: 1, data: { passed, warnings, failed, results } };
1816
- }
1817
- output.writeln();
1818
- output.writeln(output.success(`--strict: ${warnResults.length} warning${warnResults.length > 1 ? 's' : ''} all allowlisted (--allow-warn).`));
1819
- return { success: true, data: { passed, warnings, failed, results } };
1820
- }
1821
- output.writeln();
1822
- output.writeln(output.warning('All checks passed with some warnings.'));
1823
- return { success: true, data: { passed, warnings, failed, results } };
1824
- }
1825
- else {
1826
- output.writeln();
1827
- output.writeln(output.success('All checks passed! System is healthy.'));
1828
- return { success: true, data: { passed, warnings, failed, results } };
1829
- }
1830
- }
207
+ return finalize({ results, strict, allowWarnList });
208
+ },
1831
209
  };
1832
210
  export default doctorCommand;
1833
211
  //# sourceMappingURL=doctor.js.map