moflo 4.9.13 → 4.9.15

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 (29) hide show
  1. package/.claude/guidance/shipped/moflo-core-guidance.md +1 -0
  2. package/.claude/guidance/shipped/moflo-verbose-command-filtering.md +45 -0
  3. package/.claude/helpers/gate.cjs +21 -5
  4. package/.claude/helpers/simplify-classify.cjs +211 -0
  5. package/.claude/skills/eldar/SKILL.md +13 -8
  6. package/.claude/skills/fl/phases.md +18 -2
  7. package/.claude/skills/guidance/SKILL.md +1 -1
  8. package/.claude/skills/simplify/SKILL.md +35 -48
  9. package/.claude/skills/spell-schedule/SKILL.md +1 -1
  10. package/bin/gate.cjs +21 -5
  11. package/bin/session-start-launcher.mjs +1 -1
  12. package/bin/simplify-classify.cjs +211 -0
  13. package/dist/src/cli/commands/doctor-checks-config.js +246 -0
  14. package/dist/src/cli/commands/doctor-checks-deep.js +40 -2
  15. package/dist/src/cli/commands/doctor-checks-intelligence.js +197 -0
  16. package/dist/src/cli/commands/doctor-checks-memory.js +207 -0
  17. package/dist/src/cli/commands/doctor-checks-platform.js +138 -0
  18. package/dist/src/cli/commands/doctor-checks-runtime.js +170 -0
  19. package/dist/src/cli/commands/doctor-fixes.js +165 -0
  20. package/dist/src/cli/commands/doctor-registry.js +109 -0
  21. package/dist/src/cli/commands/doctor-render.js +203 -0
  22. package/dist/src/cli/commands/doctor-types.js +9 -0
  23. package/dist/src/cli/commands/doctor-version.js +134 -0
  24. package/dist/src/cli/commands/doctor-zombies.js +201 -0
  25. package/dist/src/cli/commands/doctor.js +35 -1706
  26. package/dist/src/cli/init/helpers-generator.js +21 -5
  27. package/dist/src/cli/version.js +1 -1
  28. package/package.json +2 -2
  29. package/scripts/post-install-bootstrap.mjs +1 -0
@@ -2,1279 +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 moflo.yaml exists and contains all required top-level sections (#895).
777
- // Catches three failure modes:
778
- // 1. File missing — session-start should have created it; warn user that
779
- // defaults are invisible/untunable.
780
- // 2. File empty / unreadable — corrupted by half-write or filesystem error.
781
- // 3. Top-level sections missing — partial yaml from manual edit or stale
782
- // copy from a moflo version that didn't ship a section yet. The
783
- // session-start yaml-upgrader would normally backfill these, but the
784
- // diagnostic surfaces it for users who never restarted.
785
- //
786
- // Exported so tests can exercise it end-to-end against a temp project root
787
- // without mutating process.cwd() (which fights vitest's parallel test runner).
788
- export async function checkMofloYamlCompliance(cwd = process.cwd()) {
789
- const yamlPath = join(cwd, 'moflo.yaml');
790
- // Lazy-import the validator so doctor doesn't pull in fs walks on the
791
- // happy path of unrelated checks.
792
- const { validateMofloYaml } = await import('../init/moflo-yaml-template.js');
793
- const result = validateMofloYaml(yamlPath);
794
- if (!result.exists) {
795
- return {
796
- name: 'moflo.yaml',
797
- status: 'warn',
798
- message: 'moflo.yaml not found — defaults are in effect but not visible/tunable',
799
- fix: 'Restart Claude Code (session-start auto-creates) or run `npx moflo init`',
800
- };
801
- }
802
- if (result.valid) {
803
- return { name: 'moflo.yaml', status: 'pass', message: `Compliant (${yamlPath})` };
804
- }
805
- const parseIssue = result.issues.find((i) => i.kind !== 'missing-section');
806
- if (parseIssue) {
807
- return {
808
- name: 'moflo.yaml',
809
- status: 'fail',
810
- message: `${parseIssue.kind}: ${parseIssue.detail}`,
811
- fix: 'Inspect/repair moflo.yaml, or `mv moflo.yaml moflo.yaml.bak && npx moflo init`',
812
- };
813
- }
814
- // Missing sections — recoverable on next session-start via yaml-upgrader.
815
- return {
816
- name: 'moflo.yaml',
817
- status: 'warn',
818
- message: `Missing sections: ${result.missingSections.join(', ')}`,
819
- fix: 'Restart Claude Code (yaml-upgrader auto-appends) or `npx moflo init --force`',
820
- };
821
- }
822
- // Check test directories configured in moflo.yaml
823
- async function checkTestDirs() {
824
- const yamlPath = join(process.cwd(), 'moflo.yaml');
825
- if (!existsSync(yamlPath)) {
826
- return { name: 'Test Directories', status: 'warn', message: 'No moflo.yaml — test indexing unconfigured', fix: 'npx moflo init' };
827
- }
828
- try {
829
- const content = readFileSync(yamlPath, 'utf-8');
830
- // Check if tests section exists
831
- const testsBlock = content.match(/tests:\s*\n\s+directories:\s*\n((?:\s+-\s+.+\n?)+)/);
832
- if (!testsBlock) {
833
- return { name: 'Test Directories', status: 'warn', message: 'No tests section in moflo.yaml', fix: 'npx moflo init --force' };
834
- }
835
- // Extract configured directories
836
- const items = testsBlock[1].match(/-\s+(.+)/g);
837
- if (!items || items.length === 0) {
838
- return { name: 'Test Directories', status: 'warn', message: 'Empty test directories list' };
839
- }
840
- const dirs = items.map(item => item.replace(/^-\s+/, '').trim());
841
- const existing = dirs.filter(d => existsSync(join(process.cwd(), d)));
842
- const missing = dirs.filter(d => !existsSync(join(process.cwd(), d)));
843
- // Check auto_index.tests flag
844
- const autoIndexMatch = content.match(/auto_index:\s*\n(?:.*\n)*?\s+tests:\s*(true|false)/);
845
- const autoIndexEnabled = !autoIndexMatch || autoIndexMatch[1] !== 'false';
846
- const indexLabel = autoIndexEnabled ? 'auto-index: on' : 'auto-index: off';
847
- if (missing.length > 0 && existing.length === 0) {
848
- return {
849
- name: 'Test Directories',
850
- status: 'warn',
851
- message: `No configured test dirs exist: ${missing.join(', ')} (${indexLabel})`,
852
- };
853
- }
854
- if (missing.length > 0) {
855
- return {
856
- name: 'Test Directories',
857
- status: 'warn',
858
- message: `${existing.length} OK, ${missing.length} missing: ${missing.join(', ')} (${indexLabel})`,
859
- };
860
- }
861
- return { name: 'Test Directories', status: 'pass', message: `${existing.length} directories: ${existing.join(', ')} (${indexLabel})` };
862
- }
863
- catch (e) {
864
- return { name: 'Test Directories', status: 'warn', message: `Unable to parse moflo.yaml: ${errorDetail(e)}` };
865
- }
866
- }
867
- // Check semantic search quality — verify no 0.500 keyword fallback scores
868
- async function checkSemanticQuality() {
869
- try {
870
- const { searchEntries } = await import('../memory/memory-initializer.js');
871
- const result = await searchEntries({
872
- query: 'test infrastructure health check',
873
- namespace: 'patterns',
874
- limit: 5,
875
- threshold: 0.1
876
- });
877
- if (!result.success || result.results.length === 0) {
878
- return {
879
- name: 'Semantic Quality',
880
- status: 'warn',
881
- message: 'No search results (empty database or no patterns namespace)',
882
- };
883
- }
884
- const scores = result.results.map((r) => r.score);
885
- const allSame = scores.every((s) => s === scores[0]);
886
- const hasFallback = scores.some((s) => s === 0.5);
887
- if (hasFallback) {
888
- return {
889
- name: 'Semantic Quality',
890
- status: 'fail',
891
- message: `${scores.length} results, scores include 0.500 fallback (keyword-only, no embeddings)`,
892
- fix: 'Re-index with: npx moflo embeddings build --force'
893
- };
894
- }
895
- if (allSame && scores.length > 1) {
896
- return {
897
- name: 'Semantic Quality',
898
- status: 'warn',
899
- message: `${scores.length} results, all scores identical (${scores[0].toFixed(3)}) — degraded search`,
900
- };
901
- }
902
- const topScore = Math.max(...scores);
903
- return {
904
- name: 'Semantic Quality',
905
- status: topScore >= 0.3 ? 'pass' : 'warn',
906
- message: `${scores.length} results, top ${topScore.toFixed(3)}, varied (semantic search active)`,
907
- };
908
- }
909
- catch (e) {
910
- return {
911
- name: 'Semantic Quality',
912
- status: 'warn',
913
- message: `Check failed: ${e instanceof Error ? e.message.split(/\r?\n/)[0] : 'error'}`,
914
- };
915
- }
916
- }
917
- // Check memory-backed patterns (populated by pretrain) as a fallback for neural checks.
918
- // Uses the same pattern-search handler that pretrain writes to.
919
- async function checkMemoryPatterns(_namespace) {
920
- try {
921
- // Use the pattern-search handler (same store pretrain writes to)
922
- const hooksMod = await import('../mcp-tools/hooks-tools.js');
923
- if (hooksMod.hooksPatternSearch) {
924
- const result = await hooksMod.hooksPatternSearch.handler({
925
- query: 'pretrain',
926
- topK: 1,
927
- minConfidence: 0.1,
928
- });
929
- const matches = result?.results;
930
- if (Array.isArray(matches))
931
- return matches.length;
932
- }
933
- }
934
- catch {
935
- // hooks module not available
936
- }
937
- // Secondary fallback: check the memory DB file exists
938
- try {
939
- const { existsSync } = await import('fs');
940
- const { join } = await import('path');
941
- const dbPath = join(process.cwd(), '.claude', 'memory.db');
942
- if (existsSync(dbPath))
943
- return 1;
944
- }
945
- catch {
946
- // fs not available
947
- }
948
- return 0;
949
- }
950
- // Check intelligence layer: SONA, EWC++, LoRA, Flash Attention, ReasoningBank
951
- // Exercises each component with a lightweight functional test rather than just checking "loaded".
952
- async function checkIntelligence() {
953
- try {
954
- const neural = await import('../neural/index.js');
955
- const results = [];
956
- const failures = [];
957
- // 1. SONA — create manager, run trajectory lifecycle
958
- try {
959
- const sona = neural.createSONAManager('balanced');
960
- await sona.initialize();
961
- const tid = sona.beginTrajectory('doctor-check', 'general');
962
- const embedding = new Float32Array(64).fill(0.1);
963
- sona.recordStep(tid, 'test-action', 0.8, embedding);
964
- const traj = sona.completeTrajectory(tid, 0.9);
965
- if (traj && traj.steps.length > 0) {
966
- results.push('SONA');
967
- }
968
- else {
969
- failures.push('SONA (no trajectory output)');
970
- }
971
- await sona.cleanup();
972
- }
973
- catch (e) {
974
- failures.push(`SONA (${e instanceof Error ? e.message : 'error'})`);
975
- }
976
- // 2. ReasoningBank — verify instantiation and trajectory store/distill lifecycle
977
- try {
978
- const rb = neural.createReasoningBank();
979
- const stateAfter = new Float32Array(64).fill(0.2);
980
- const trajectory = {
981
- trajectoryId: 'doctor-test',
982
- context: 'health check',
983
- domain: 'general',
984
- steps: [{ stepId: 's1', action: 'test', reward: 1, stateBefore: stateAfter, stateAfter, timestamp: Date.now() }],
985
- startTime: Date.now(),
986
- endTime: Date.now(),
987
- qualityScore: 0.9,
988
- isComplete: true,
989
- verdict: {
990
- success: true,
991
- confidence: 0.9,
992
- strengths: ['health check passed'],
993
- weaknesses: [],
994
- improvements: [],
995
- relevanceScore: 0.9,
996
- },
997
- };
998
- rb.storeTrajectory(trajectory);
999
- // distill() populates memories (storeTrajectory alone does not)
1000
- const distilled = await rb.distill(trajectory);
1001
- if (distilled || rb.getTrajectories().length > 0) {
1002
- results.push('ReasoningBank');
1003
- }
1004
- else {
1005
- // Fallback: check memory-backed patterns from pretrain
1006
- const memoryPatterns = await checkMemoryPatterns('patterns');
1007
- if (memoryPatterns > 0) {
1008
- results.push('ReasoningBank(memory)');
1009
- }
1010
- else {
1011
- failures.push('ReasoningBank (distill returned no data)');
1012
- }
1013
- }
1014
- }
1015
- catch (e) {
1016
- failures.push(`ReasoningBank (${e instanceof Error ? e.message : 'error'})`);
1017
- }
1018
- // 3. PatternLearner — extract + match
1019
- try {
1020
- const pl = neural.createPatternLearner();
1021
- const embedding = new Float32Array(64).fill(0.3);
1022
- const now = Date.now();
1023
- pl.extractPattern({
1024
- trajectoryId: 'doctor-pl', context: 'test', domain: 'general',
1025
- steps: [{ stepId: 's1', action: 'test', reward: 1, stateBefore: embedding, stateAfter: embedding, timestamp: now }],
1026
- startTime: now, endTime: now, qualityScore: 1, isComplete: true,
1027
- }, { memoryId: 'doctor-pl-mem', trajectoryId: 'doctor-pl', strategy: 'health-check', keyLearnings: ['test'], embedding, quality: 1, usageCount: 0, lastUsed: now });
1028
- const matches = pl.findMatches(embedding, 1);
1029
- if (matches.length > 0) {
1030
- results.push('PatternLearner');
1031
- }
1032
- else {
1033
- // Fallback: check memory-backed patterns from pretrain
1034
- const memoryPatterns = await checkMemoryPatterns('patterns');
1035
- if (memoryPatterns > 0) {
1036
- results.push('PatternLearner(memory)');
1037
- }
1038
- else {
1039
- failures.push('PatternLearner (no matches)');
1040
- }
1041
- }
1042
- }
1043
- catch (e) {
1044
- failures.push(`PatternLearner (${e instanceof Error ? e.message : 'error'})`);
1045
- }
1046
- // 4. SONALearningEngine (MicroLoRA + EWC++)
1047
- try {
1048
- const engine = neural.createSONALearningEngine();
1049
- const ctx = { domain: 'general', queryEmbedding: new Float32Array(768).fill(0.1) };
1050
- const adapted = await engine.adapt(ctx);
1051
- const components = [];
1052
- if (adapted && adapted.transformedQuery)
1053
- components.push('LoRA');
1054
- if (adapted && adapted.patterns !== undefined)
1055
- components.push('EWC++');
1056
- if (components.length > 0) {
1057
- results.push(...components);
1058
- }
1059
- else {
1060
- failures.push('LoRA/EWC++ (adapt returned no data)');
1061
- }
1062
- }
1063
- catch (e) {
1064
- // Gracefully handle cold/uninitialized state
1065
- const msg = e instanceof Error ? e.message : 'error';
1066
- if (msg.includes('undefined') || msg.includes('not initialized')) {
1067
- results.push('LoRA/EWC++(cold)');
1068
- }
1069
- else {
1070
- failures.push(`LoRA/EWC++ (${msg})`);
1071
- }
1072
- }
1073
- // 5. RL Algorithms — quick instantiation check
1074
- try {
1075
- const algNames = [];
1076
- const ppo = neural.createPPO();
1077
- if (ppo)
1078
- algNames.push('PPO');
1079
- const dqn = neural.createDQN();
1080
- if (dqn)
1081
- algNames.push('DQN');
1082
- const ql = neural.createQLearning();
1083
- if (ql)
1084
- algNames.push('Q-Learn');
1085
- if (algNames.length > 0) {
1086
- results.push(`RL(${algNames.join('+')})`);
1087
- }
1088
- }
1089
- catch (e) {
1090
- failures.push(`RL (${e instanceof Error ? e.message : 'error'})`);
1091
- }
1092
- if (failures.length > 0) {
1093
- return {
1094
- name: 'Intelligence',
1095
- status: results.length > 0 ? 'warn' : 'fail',
1096
- message: `${results.join(', ')} OK; FAILED: ${failures.join(', ')}`,
1097
- fix: 'Check neural module imports and dependencies',
1098
- };
1099
- }
1100
- return {
1101
- name: 'Intelligence',
1102
- status: 'pass',
1103
- message: results.join(', '),
1104
- };
1105
- }
1106
- catch (e) {
1107
- return {
1108
- name: 'Intelligence',
1109
- status: 'warn',
1110
- message: `Module unavailable: ${e instanceof Error ? e.message.split(/\r?\n/)[0] : 'import failed'}`,
1111
- fix: 'Ensure moflo is built (npm run build)',
1112
- };
1113
- }
1114
- }
1115
- // Check whether a given PID is still running.
1116
- // Uses signal 0 which works cross-platform (Windows, Linux, macOS) without
1117
- // needing PowerShell or /proc — Node handles the platform abstraction.
1118
- function isProcessAlive(pid) {
1119
- try {
1120
- process.kill(pid, 0);
1121
- return true;
1122
- }
1123
- catch {
1124
- return false;
1125
- }
1126
- }
1127
- // Fast path: kill processes tracked in the shared ProcessManager registry.
1128
- // This avoids the expensive OS-level process scan for known background tasks.
1129
- function killTrackedProcesses() {
1130
- const registryFile = join(process.cwd(), '.moflo', 'background-pids.json');
1131
- const lockFile = join(process.cwd(), '.moflo', 'spawn.lock');
1132
- let killed = 0;
1133
- try {
1134
- if (existsSync(registryFile)) {
1135
- const entries = JSON.parse(readFileSync(registryFile, 'utf-8'));
1136
- for (const entry of entries) {
1137
- if (!isProcessAlive(entry.pid))
1138
- continue;
1139
- try {
1140
- if (process.platform === 'win32') {
1141
- execSync(`taskkill /F /PID ${entry.pid}`, { timeout: 5000, windowsHide: true });
1142
- }
1143
- else {
1144
- process.kill(entry.pid, 'SIGKILL');
1145
- }
1146
- killed++;
1147
- }
1148
- catch { /* already gone */ }
1149
- }
1150
- // Clear registry
1151
- writeFileSync(registryFile, '[]');
1152
- }
1153
- }
1154
- catch { /* non-fatal */ }
1155
- // Remove spawn lock
1156
- try {
1157
- if (existsSync(lockFile))
1158
- unlinkSync(lockFile);
1159
- }
1160
- catch { /* ok */ }
1161
- return killed;
1162
- }
1163
- // Read the set of moflo background PIDs registered with the shared
1164
- // ProcessManager (.moflo/background-pids.json). These are legitimate tracked
1165
- // background tasks (sequential indexer chain, daemon, MCP servers spawned by
1166
- // session-start) — they are detached:true by design so their parents have
1167
- // already exited, but they are NOT orphans. Without this allow-set,
1168
- // findZombieProcesses() flags every running indexer step as a zombie.
1169
- function readTrackedBackgroundPids() {
1170
- const result = new Set();
1171
- const registryFile = join(process.cwd(), '.moflo', 'background-pids.json');
1172
- try {
1173
- if (!existsSync(registryFile))
1174
- return result;
1175
- const entries = JSON.parse(readFileSync(registryFile, 'utf-8'));
1176
- if (!Array.isArray(entries))
1177
- return result;
1178
- for (const entry of entries) {
1179
- if (entry && typeof entry.pid === 'number' && entry.pid > 0) {
1180
- result.add(entry.pid);
1181
- }
1182
- }
1183
- }
1184
- catch { /* malformed or unreadable — treat as empty */ }
1185
- return result;
1186
- }
1187
- // Find and optionally kill orphaned moflo/claude-flow node processes.
1188
- // A process is only "orphaned" if its parent is no longer alive — meaning
1189
- // nothing will clean it up. MCP servers spawned by a live Claude Code session
1190
- // have a live parent (claude.exe) and must not be flagged.
1191
- async function findZombieProcesses(kill = false) {
1192
- const legitimatePid = getDaemonLockHolder(process.cwd());
1193
- const trackedPids = readTrackedBackgroundPids();
1194
- const currentPid = process.pid;
1195
- const parentPid = process.ppid;
1196
- const found = [];
1197
- let killed = 0;
1198
- // Collect candidates as { pid, ppid } so we can check parent liveness
1199
- const candidates = [];
1200
- try {
1201
- if (process.platform === 'win32') {
1202
- // Windows: include ParentProcessId so we can verify orphan status
1203
- 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 });
1204
- const lines = result.split(/\r?\n/);
1205
- for (const line of lines) {
1206
- if (/moflo|claude-flow|flo\s+(hooks|gate|mcp|daemon)/i.test(line)) {
1207
- // Format-Table columns: ProcessId ParentProcessId CommandLine...
1208
- const match = line.match(/^\s*(\d+)\s+(\d+)/);
1209
- if (match) {
1210
- candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
1211
- }
1212
- }
1213
- }
1214
- }
1215
- else {
1216
- // Unix/macOS: use ps with explicit PID+PPID columns for reliable parsing
1217
- const result = execSync('ps -eo pid,ppid,command | grep -E "node.*(moflo|claude-flow)" | grep -v grep', { encoding: 'utf-8', timeout: 5000 });
1218
- const lines = result.trim().split(/\r?\n/);
1219
- for (const line of lines) {
1220
- const match = line.trim().match(/^(\d+)\s+(\d+)/);
1221
- if (match) {
1222
- candidates.push({ pid: parseInt(match[1], 10), ppid: parseInt(match[2], 10) });
1223
- }
1224
- }
1225
- }
1226
- }
1227
- catch {
1228
- // No matches found (grep exits non-zero) or command failed
1229
- }
1230
- // Filter: skip known-good PIDs and processes whose parent is still alive.
1231
- // A live parent (e.g. claude.exe for MCP servers) means the process is managed, not orphaned.
1232
- for (const { pid, ppid } of candidates) {
1233
- if (pid === currentPid || pid === parentPid || pid === legitimatePid)
1234
- continue;
1235
- // Tracked background tasks (indexer chain, etc.) are detached:true so their
1236
- // parent is dead by design. The ProcessManager registry tells us they are
1237
- // legitimate, not orphaned.
1238
- if (trackedPids.has(pid))
1239
- continue;
1240
- if (isProcessAlive(ppid))
1241
- continue;
1242
- // Defense-in-depth: detached daemons have dead parents by design.
1243
- // Even if the lock file is missing/corrupted, don't kill a running daemon.
1244
- if (isDaemonProcess(pid))
1245
- continue;
1246
- found.push(pid);
1247
- }
1248
- if (kill && found.length > 0) {
1249
- for (const pid of found) {
1250
- try {
1251
- if (process.platform === 'win32') {
1252
- execSync(`taskkill /F /PID ${pid}`, { timeout: 5000, windowsHide: true });
1253
- }
1254
- else {
1255
- process.kill(pid, 'SIGKILL');
1256
- }
1257
- killed++;
1258
- }
1259
- catch {
1260
- // Process may have already exited
1261
- }
1262
- }
1263
- // Clean up stale daemon lock if we killed the holder
1264
- if (legitimatePid && found.includes(legitimatePid)) {
1265
- releaseDaemonLock(process.cwd(), legitimatePid, true);
1266
- }
1267
- }
1268
- return { found: found.length, killed, pids: found };
1269
- }
1270
- // Format health check result
1271
- function formatCheck(check) {
1272
- const icon = check.status === 'pass' ? output.success('✓') :
1273
- check.status === 'warn' ? output.warning('⚠') :
1274
- output.error('✗');
1275
- return `${icon} ${check.name}: ${check.message}`;
1276
- }
1277
- // 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 };
1278
21
  export const doctorCommand = {
1279
22
  name: 'doctor',
1280
23
  aliases: ['healer'],
@@ -1285,34 +28,34 @@ export const doctorCommand = {
1285
28
  short: 'f',
1286
29
  description: 'Automatically fix issues where possible',
1287
30
  type: 'boolean',
1288
- default: false
31
+ default: false,
1289
32
  },
1290
33
  {
1291
34
  name: 'install',
1292
35
  short: 'i',
1293
36
  description: 'Auto-install missing dependencies (Claude Code CLI)',
1294
37
  type: 'boolean',
1295
- default: false
38
+ default: false,
1296
39
  },
1297
40
  {
1298
41
  name: 'component',
1299
42
  short: 'c',
1300
43
  description: 'Check specific component (version, node, npm, config, daemon, memory, embeddings, git, mcp, claude, disk, typescript, semantic, intelligence, swarm, hive-mind)',
1301
- type: 'string'
44
+ type: 'string',
1302
45
  },
1303
46
  {
1304
47
  name: 'verbose',
1305
48
  short: 'v',
1306
49
  description: 'Verbose output',
1307
50
  type: 'boolean',
1308
- default: false
51
+ default: false,
1309
52
  },
1310
53
  {
1311
54
  name: 'kill-zombies',
1312
55
  short: 'k',
1313
56
  description: 'Find and kill orphaned moflo/claude-flow node processes',
1314
57
  type: 'boolean',
1315
- default: false
58
+ default: false,
1316
59
  },
1317
60
  {
1318
61
  // Issue #784: fail on warnings. Used by consumer-install-smoke so a
@@ -1321,7 +64,7 @@ export const doctorCommand = {
1321
64
  name: 'strict',
1322
65
  description: 'Treat warnings as failures (non-zero exit). Used by CI.',
1323
66
  type: 'boolean',
1324
- default: false
67
+ default: false,
1325
68
  },
1326
69
  {
1327
70
  // Companion to --strict. CI-legitimate warnings (e.g. "Sandbox Tier"
@@ -1330,7 +73,7 @@ export const doctorCommand = {
1330
73
  // `name` field of each check (case-sensitive substring).
1331
74
  name: 'allow-warn',
1332
75
  description: 'In --strict mode, comma-separated check names whose warnings are tolerated.',
1333
- type: 'string'
76
+ type: 'string',
1334
77
  },
1335
78
  {
1336
79
  // Issue #818: machine-readable output. Suppresses banner/spinner/auto-fix
@@ -1339,8 +82,8 @@ export const doctorCommand = {
1339
82
  name: 'json',
1340
83
  description: 'Emit a single JSON document with per-check + per-subcheck details. Suppresses formatted output.',
1341
84
  type: 'boolean',
1342
- default: false
1343
- }
85
+ default: false,
86
+ },
1344
87
  ],
1345
88
  examples: [
1346
89
  { command: 'claude-flow doctor', description: 'Run full health check' },
@@ -1352,13 +95,12 @@ export const doctorCommand = {
1352
95
  { command: 'claude-flow doctor --strict', description: 'Fail (exit 1) on any warning — used by CI' },
1353
96
  { command: 'claude-flow doctor --json', description: 'Emit a single JSON doc with per-check + per-subcheck details (for CI/smoke gates)' },
1354
97
  { command: 'claude-flow doctor -c swarm', description: 'Run only the swarm + agent + task coordinator-path tripwire (epic #798)' },
1355
- { 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' },
1356
99
  ],
1357
100
  action: async (ctx) => {
1358
101
  const showFix = ctx.flags.fix;
1359
102
  const autoInstall = ctx.flags.install;
1360
103
  const component = ctx.flags.component;
1361
- const verbose = ctx.flags.verbose;
1362
104
  const killZombies = ctx.flags.killZombies;
1363
105
  const strict = ctx.flags.strict;
1364
106
  // Parser normalises kebab-case flag names to camelCase: `--allow-warn`
@@ -1383,286 +125,12 @@ export const doctorCommand = {
1383
125
  output.writeln(output.warning('--allow-warn requires --strict; ignoring (warnings are tolerated by default).'));
1384
126
  output.writeln();
1385
127
  }
1386
- // Handle --kill-zombies early
1387
128
  if (killZombies) {
1388
- output.writeln(output.bold('Zombie Process Scan'));
1389
- output.writeln();
1390
- // Fast path: kill tracked processes from the shared registry first
1391
- const registryKilled = killTrackedProcesses();
1392
- if (registryKilled > 0) {
1393
- output.writeln(output.success(` Killed ${registryKilled} tracked background process(es) from registry`));
1394
- }
1395
- // Slow path: OS-level scan for any remaining orphans
1396
- const scan = await findZombieProcesses(false);
1397
- if (scan.found === 0) {
1398
- if (registryKilled === 0) {
1399
- output.writeln(output.success(' No orphaned moflo processes found'));
1400
- }
1401
- }
1402
- else {
1403
- output.writeln(output.warning(` Found ${scan.found} additional orphaned process(es): PIDs ${scan.pids.join(', ')}`));
1404
- // Kill them
1405
- const result = await findZombieProcesses(true);
1406
- if (result.killed > 0) {
1407
- output.writeln(output.success(` Killed ${result.killed} zombie process(es)`));
1408
- }
1409
- if (result.killed < result.found) {
1410
- output.writeln(output.warning(` ${result.found - result.killed} process(es) could not be killed`));
1411
- }
1412
- }
1413
- output.writeln();
1414
- output.writeln(output.dim('─'.repeat(50)));
1415
- output.writeln();
1416
- }
1417
- const checkZombieProcesses = async () => {
1418
- try {
1419
- const scan = await findZombieProcesses(false);
1420
- if (scan.found === 0) {
1421
- return { name: 'Zombie Processes', status: 'pass', message: 'No orphaned processes' };
1422
- }
1423
- return {
1424
- name: 'Zombie Processes',
1425
- status: 'warn',
1426
- message: `${scan.found} orphaned process(es) (PIDs: ${scan.pids.join(', ')})`,
1427
- fix: 'moflo doctor --kill-zombies'
1428
- };
1429
- }
1430
- catch {
1431
- return { name: 'Zombie Processes', status: 'pass', message: 'Check skipped' };
1432
- }
1433
- };
1434
- // Check Spell Engine health — validates core modules, built output, and step commands
1435
- async function checkSpellEngine() {
1436
- try {
1437
- // Resolve relative to the moflo package root (works in both dev and consumer)
1438
- const mofloRoot = getMofloRoot();
1439
- if (!mofloRoot) {
1440
- return { name: 'Spell Engine', status: 'warn', message: 'Could not locate moflo package root', fix: 'npm run build' };
1441
- }
1442
- // Post-#586 workspace collapse: spell engine lives at src/cli/spells/
1443
- // (source) and dist/src/cli/spells/ (compiled). The legacy
1444
- // src/modules/spells/{src,dist}/ tree was deleted.
1445
- const distDir = join(mofloRoot, 'dist', 'src', 'cli', 'spells');
1446
- const srcDir = join(mofloRoot, 'src', 'cli', 'spells');
1447
- const hasDistDir = existsSync(distDir);
1448
- const hasSrcDir = existsSync(srcDir);
1449
- if (!hasDistDir && !hasSrcDir) {
1450
- return { name: 'Spell Engine', status: 'warn', message: 'Spell engine not found', fix: 'npm run build' };
1451
- }
1452
- // Core compiled modules that must exist
1453
- const coreModules = [
1454
- 'core/runner',
1455
- 'core/step-executor',
1456
- 'core/step-command-registry',
1457
- 'core/interpolation',
1458
- 'core/credential-masker',
1459
- 'registry/spell-registry',
1460
- 'factory/runner-factory',
1461
- 'schema',
1462
- 'types',
1463
- 'credentials',
1464
- 'scheduler',
1465
- ];
1466
- const baseDir = hasDistDir ? distDir : srcDir;
1467
- const ext = hasDistDir ? '.js' : '.ts';
1468
- // Directories don't need an extension check
1469
- const dirModules = ['schema', 'types', 'credentials', 'scheduler'];
1470
- const missing = coreModules.filter(m => dirModules.includes(m)
1471
- ? !existsSync(join(baseDir, m))
1472
- : !existsSync(join(baseDir, m + ext)));
1473
- if (missing.length > 0) {
1474
- return {
1475
- name: 'Spell Engine',
1476
- status: 'warn',
1477
- message: `Missing modules: ${missing.join(', ')}`,
1478
- fix: 'npm run build',
1479
- };
1480
- }
1481
- // Check for step commands directory
1482
- const commandsDir = join(baseDir, 'commands');
1483
- const hasCommands = existsSync(commandsDir);
1484
- // Check for spell definition loaders
1485
- const loadersDir = join(baseDir, 'loaders');
1486
- const hasLoaders = existsSync(loadersDir);
1487
- // Check for index entry point
1488
- const hasIndex = existsSync(join(baseDir, 'index' + ext));
1489
- const parts = [];
1490
- parts.push(`${coreModules.length} core modules`);
1491
- if (hasCommands)
1492
- parts.push('step commands');
1493
- if (hasLoaders)
1494
- parts.push('loaders');
1495
- if (hasIndex)
1496
- parts.push('index');
1497
- return {
1498
- name: 'Spell Engine',
1499
- status: 'pass',
1500
- message: parts.join(', '),
1501
- };
1502
- }
1503
- catch (e) {
1504
- return { name: 'Spell Engine', status: 'warn', message: `Unable to check spell engine: ${errorDetail(e)}` };
1505
- }
1506
- }
1507
- // Check sandbox tier — reports OS sandbox capability AND, if the project
1508
- // has `sandbox.enabled: true`, whether the effective sandbox would
1509
- // actually start (e.g. Windows Docker image pulled and configured).
1510
- async function checkSandboxTier() {
1511
- try {
1512
- const { detectSandboxCapability, loadSandboxConfigFromProject, resolveEffectiveSandbox, } = await import('../spells/index.js');
1513
- const cap = await detectSandboxCapability();
1514
- const config = await loadSandboxConfigFromProject(process.cwd());
1515
- // If sandboxing isn't enabled in moflo.yaml, just report capability.
1516
- if (!config.enabled) {
1517
- if (cap.available) {
1518
- return {
1519
- name: 'Sandbox Tier',
1520
- status: 'pass',
1521
- message: `${cap.tool} available (${cap.platform}) — sandboxing off in moflo.yaml`,
1522
- };
1523
- }
1524
- const offHint = {
1525
- win32: 'Install Docker Desktop and set sandbox.dockerImage in moflo.yaml to enable sandboxing',
1526
- linux: 'Install bubblewrap: sudo apt install bubblewrap',
1527
- darwin: 'sandbox-exec should be available on macOS — check /usr/bin/sandbox-exec',
1528
- };
1529
- return {
1530
- name: 'Sandbox Tier',
1531
- status: 'pass',
1532
- message: `sandboxing off (${cap.platform}, denylist active)`,
1533
- fix: offHint[cap.platform],
1534
- };
1535
- }
1536
- // Sandboxing is enabled — run the real resolver and surface any error.
1537
- try {
1538
- const effective = await resolveEffectiveSandbox(config);
1539
- if (effective.useOsSandbox) {
1540
- const imageHint = effective.config.dockerImage ? `, ${effective.config.dockerImage}` : '';
1541
- return {
1542
- name: 'Sandbox Tier',
1543
- status: 'pass',
1544
- message: `${cap.tool} ready (${cap.platform}${imageHint})`,
1545
- };
1546
- }
1547
- return {
1548
- name: 'Sandbox Tier',
1549
- status: 'warn',
1550
- message: `denylist only (${cap.platform})`,
1551
- };
1552
- }
1553
- catch (err) {
1554
- return {
1555
- name: 'Sandbox Tier',
1556
- status: 'warn',
1557
- message: `sandboxing enabled but not ready (${cap.platform})`,
1558
- fix: errorDetail(err),
1559
- };
1560
- }
1561
- }
1562
- catch (err) {
1563
- return {
1564
- name: 'Sandbox Tier',
1565
- status: 'warn',
1566
- message: `Unable to detect: ${err instanceof Error ? err.message : 'unknown error'}`,
1567
- };
1568
- }
1569
- }
1570
- const allChecks = [
1571
- checkVersionFreshness,
1572
- checkNodeVersion,
1573
- checkNpmVersion,
1574
- checkClaudeCode,
1575
- checkGit,
1576
- checkGitRepo,
1577
- checkConfigFile,
1578
- checkMofloYamlCompliance,
1579
- checkStatusLine,
1580
- checkDaemonStatus,
1581
- checkMemoryDatabase,
1582
- checkEmbeddings,
1583
- checkEmbeddingHygiene,
1584
- checkTestDirs,
1585
- checkMcpServers,
1586
- checkDiskSpace,
1587
- checkBuildTools,
1588
- checkSemanticQuality,
1589
- checkIntelligence,
1590
- checkSpellEngine,
1591
- checkZombieProcesses,
1592
- checkSubagentHealth,
1593
- checkSpellExecution,
1594
- checkMcpToolInvocation,
1595
- checkMcpSpellIntegration,
1596
- checkHookExecution,
1597
- checkGateHealth,
1598
- checkHookBlockDrift,
1599
- checkMofloDbBridge,
1600
- // Issue #818 / epic #798 — coordinator-path tripwires. They share the
1601
- // singleton coordinator with checkSubagentHealth above and assert by
1602
- // agent-id (not absolute counts) so they tolerate the parallel batch.
1603
- checkSwarmFunctional,
1604
- checkHiveMindFunctional,
1605
- // Issue #844 — memory_store + memory_search round-trip across subagent,
1606
- // swarm-agent, and hive-mind contexts. Catches the failure classes from
1607
- // #837 (threshold:0 ignored), #838/#842 (per-actor gating), and embedder
1608
- // wiring regressions (hash fallback) that the coordinator-only checks
1609
- // above would miss.
1610
- checkMemoryAccessFunctional,
1611
- checkSandboxTier,
1612
- ];
1613
- const componentMap = {
1614
- 'version': checkVersionFreshness,
1615
- 'freshness': checkVersionFreshness,
1616
- 'node': checkNodeVersion,
1617
- 'npm': checkNpmVersion,
1618
- 'claude': checkClaudeCode,
1619
- 'config': checkConfigFile,
1620
- 'yaml': checkMofloYamlCompliance,
1621
- 'moflo-yaml': checkMofloYamlCompliance,
1622
- 'statusline': checkStatusLine,
1623
- 'status-line': checkStatusLine,
1624
- 'daemon': checkDaemonStatus,
1625
- 'memory': checkMemoryDatabase,
1626
- 'embeddings': checkEmbeddings,
1627
- 'embedding-hygiene': checkEmbeddingHygiene,
1628
- 'hygiene': checkEmbeddingHygiene,
1629
- 'git': checkGit,
1630
- 'mcp': checkMcpServers,
1631
- 'disk': checkDiskSpace,
1632
- 'typescript': checkBuildTools,
1633
- 'tests': checkTestDirs,
1634
- 'semantic': checkSemanticQuality,
1635
- 'quality': checkSemanticQuality,
1636
- 'intelligence': checkIntelligence,
1637
- 'workflows': checkSpellEngine,
1638
- 'workflow': checkSpellEngine,
1639
- 'subagent': checkSubagentHealth,
1640
- 'subagents': checkSubagentHealth,
1641
- 'agents': checkSubagentHealth,
1642
- 'spell-exec': checkSpellExecution,
1643
- 'mcp-tools': checkMcpToolInvocation,
1644
- 'mcp-spell': checkMcpSpellIntegration,
1645
- 'hooks': checkHookExecution,
1646
- 'gates': checkGateHealth,
1647
- 'gate': checkGateHealth,
1648
- 'hook-drift': checkHookBlockDrift,
1649
- 'drift': checkHookBlockDrift,
1650
- 'sandbox': checkSandboxTier,
1651
- 'sandbox-tier': checkSandboxTier,
1652
- 'moflodb': checkMofloDbBridge,
1653
- 'bridge': checkMofloDbBridge,
1654
- 'swarm': checkSwarmFunctional,
1655
- 'swarm-functional': checkSwarmFunctional,
1656
- 'hive': checkHiveMindFunctional,
1657
- 'hive-mind': checkHiveMindFunctional,
1658
- 'hive-mind-functional': checkHiveMindFunctional,
1659
- 'memory-access': checkMemoryAccessFunctional,
1660
- 'memory-functional': checkMemoryAccessFunctional,
1661
- };
1662
- let checksToRun = allChecks;
1663
- if (component && componentMap[component]) {
1664
- checksToRun = [componentMap[component]];
129
+ await runKillZombiesBanner();
1665
130
  }
131
+ const checksToRun = component && componentMap[component]
132
+ ? [componentMap[component]]
133
+ : allChecks;
1666
134
  const results = [];
1667
135
  const fixes = [];
1668
136
  // OPTIMIZATION: Run all checks in parallel for 3-5x faster execution
@@ -1686,7 +154,6 @@ export const doctorCommand = {
1686
154
  (..._args) => true;
1687
155
  }
1688
156
  try {
1689
- // Execute all checks concurrently
1690
157
  let checkResults;
1691
158
  try {
1692
159
  checkResults = await Promise.allSettled(checksToRun.map(check => check()));
@@ -1695,7 +162,6 @@ export const doctorCommand = {
1695
162
  spinner?.stop();
1696
163
  restoreStdout();
1697
164
  }
1698
- // Process results in order
1699
165
  for (const settledResult of checkResults) {
1700
166
  if (settledResult.status === 'fulfilled') {
1701
167
  const result = settledResult.value;
@@ -1710,7 +176,7 @@ export const doctorCommand = {
1710
176
  const errorResult = {
1711
177
  name: 'Check',
1712
178
  status: 'fail',
1713
- message: settledResult.reason?.message || 'Unknown error'
179
+ message: settledResult.reason?.message || 'Unknown error',
1714
180
  };
1715
181
  results.push(errorResult);
1716
182
  if (!jsonOutput)
@@ -1718,165 +184,28 @@ export const doctorCommand = {
1718
184
  }
1719
185
  }
1720
186
  }
1721
- catch (error) {
187
+ catch {
1722
188
  spinner?.stop();
1723
189
  restoreStdout();
1724
190
  if (!jsonOutput)
1725
191
  output.writeln(output.error('Failed to run health checks'));
1726
192
  }
1727
- // Issue #818: machine-readable output. Emits a single JSON document with
1728
- // per-check fields (and any FunctionalCheckDetail entries from the swarm/
1729
- // hive checks) and exits with the right code. Skips auto-fix entirely —
1730
- // --json is read-only by intent so CI gates can consume it without
1731
- // mutating the working tree.
1732
193
  if (jsonOutput) {
1733
- const passed = results.filter(r => r.status === 'pass').length;
1734
- const warnings = results.filter(r => r.status === 'warn').length;
1735
- const failed = results.filter(r => r.status === 'fail').length;
1736
- const allowSet = new Set(allowWarnList);
1737
- const strictWarningFailures = strict
1738
- ? results.filter(r => r.status === 'warn' && !allowSet.has(r.name)).map(r => r.name)
1739
- : [];
1740
- const exitCode = failed > 0 || strictWarningFailures.length > 0 ? 1 : 0;
1741
- process.stdout.write(JSON.stringify({
1742
- summary: { passed, warnings, failed },
1743
- strict: strict ? { strictMode: true, warningsTriggeringFail: strictWarningFailures } : { strictMode: false },
1744
- results,
1745
- }, null, 2) + '\n');
1746
- return { success: exitCode === 0, exitCode, data: { passed, warnings, failed, results } };
194
+ return emitJsonOutput({ results, strict, allowWarnList });
1747
195
  }
1748
- // Auto-install missing dependencies if requested
1749
196
  if (autoInstall) {
1750
- const claudeCodeResult = results.find(r => r.name === 'Claude Code CLI');
1751
- if (claudeCodeResult && claudeCodeResult.status !== 'pass') {
1752
- const installed = await installClaudeCode();
1753
- if (installed) {
1754
- // Re-check Claude Code after installation
1755
- const newCheck = await checkClaudeCode();
1756
- const idx = results.findIndex(r => r.name === 'Claude Code CLI');
1757
- if (idx !== -1) {
1758
- results[idx] = newCheck;
1759
- // Update fixes list
1760
- const fixIdx = fixes.findIndex(f => f.startsWith('Claude Code CLI:'));
1761
- if (fixIdx !== -1 && newCheck.status === 'pass') {
1762
- fixes.splice(fixIdx, 1);
1763
- }
1764
- }
1765
- output.writeln(formatCheck(newCheck));
1766
- }
1767
- }
197
+ await maybeAutoInstallClaudeCode(results, fixes);
1768
198
  }
1769
- // Summary
1770
- const passed = results.filter(r => r.status === 'pass').length;
1771
- const warnings = results.filter(r => r.status === 'warn').length;
1772
- const failed = results.filter(r => r.status === 'fail').length;
1773
- output.writeln();
1774
- output.writeln(output.dim('─'.repeat(50)));
1775
- output.writeln();
1776
- const summaryParts = [
1777
- output.success(`${passed} passed`),
1778
- warnings > 0 ? output.warning(`${warnings} warnings`) : null,
1779
- failed > 0 ? output.error(`${failed} failed`) : null
1780
- ].filter(Boolean);
1781
- output.writeln(`Summary: ${summaryParts.join(', ')}`);
1782
- // Auto-fix or show fixes
199
+ renderSummary(results);
1783
200
  if (showFix && fixes.length > 0) {
1784
- output.writeln();
1785
- output.writeln(output.bold('Auto-fixing issues...'));
1786
- output.writeln();
1787
- const fixableResults = results.filter(r => r.fix && (r.status === 'fail' || r.status === 'warn'));
1788
- let fixed = 0;
1789
- const unfixed = [];
1790
- for (const check of fixableResults) {
1791
- const success = await autoFixCheck(check);
1792
- if (success) {
1793
- fixed++;
1794
- }
1795
- else {
1796
- unfixed.push(`${check.name}: ${check.fix}`);
1797
- }
1798
- }
1799
- if (fixed > 0) {
1800
- output.writeln();
1801
- output.writeln(output.success(`Auto-fixed ${fixed} issue${fixed > 1 ? 's' : ''}`));
1802
- }
1803
- if (unfixed.length > 0) {
1804
- output.writeln();
1805
- output.writeln(output.bold('Manual fixes needed:'));
1806
- for (const fix of unfixed) {
1807
- output.writeln(output.dim(` ${fix}`));
1808
- }
1809
- }
1810
- // Re-run checks to show updated status
1811
- if (fixed > 0) {
1812
- output.writeln();
1813
- output.writeln(output.dim('Re-checking...'));
1814
- output.writeln();
1815
- const reResults = await Promise.allSettled(checksToRun.map(check => check()));
1816
- let rePassed = 0, reWarnings = 0, reFailed = 0;
1817
- for (const sr of reResults) {
1818
- if (sr.status === 'fulfilled') {
1819
- output.writeln(formatCheck(sr.value));
1820
- if (sr.value.status === 'pass')
1821
- rePassed++;
1822
- else if (sr.value.status === 'warn')
1823
- reWarnings++;
1824
- else
1825
- reFailed++;
1826
- }
1827
- }
1828
- output.writeln();
1829
- output.writeln(output.dim('─'.repeat(50)));
1830
- const reSummary = [
1831
- output.success(`${rePassed} passed`),
1832
- reWarnings > 0 ? output.warning(`${reWarnings} warnings`) : null,
1833
- reFailed > 0 ? output.error(`${reFailed} failed`) : null
1834
- ].filter(Boolean);
1835
- output.writeln(`After fix: ${reSummary.join(', ')}`);
1836
- }
201
+ await runAutoFix(results, fixes, checksToRun);
1837
202
  }
1838
203
  else if (fixes.length > 0 && !showFix) {
1839
204
  output.writeln();
1840
205
  output.writeln(output.dim(`Run with --fix to auto-fix ${fixes.length} issue${fixes.length > 1 ? 's' : ''}`));
1841
206
  }
1842
- // Overall result
1843
- if (failed > 0) {
1844
- output.writeln();
1845
- output.writeln(output.error('Some checks failed. Please address the issues above.'));
1846
- return { success: false, exitCode: 1, data: { passed, warnings, failed, results } };
1847
- }
1848
- else if (warnings > 0) {
1849
- // Issue #784: in strict mode any non-allowlisted warning fails the run.
1850
- // Equality (not substring) match — an allowlist entry tolerates exactly
1851
- // that check, never accidentally suppresses neighboring checks like
1852
- // "Git" allowlisting "Git Repository".
1853
- if (strict) {
1854
- const warnResults = results.filter((r) => r.status === 'warn');
1855
- const allowSet = new Set(allowWarnList);
1856
- const offending = warnResults.filter((r) => !r.name || !allowSet.has(r.name));
1857
- if (offending.length > 0) {
1858
- output.writeln();
1859
- output.writeln(output.error(`--strict: ${offending.length} warning${offending.length > 1 ? 's' : ''} not allowlisted ` +
1860
- `(use --allow-warn "<name>,<name>" to tolerate intentional warnings):`));
1861
- for (const r of offending) {
1862
- output.writeln(output.error(` ✗ ${r.name}: ${r.message ?? ''}`));
1863
- }
1864
- return { success: false, exitCode: 1, data: { passed, warnings, failed, results } };
1865
- }
1866
- output.writeln();
1867
- output.writeln(output.success(`--strict: ${warnResults.length} warning${warnResults.length > 1 ? 's' : ''} all allowlisted (--allow-warn).`));
1868
- return { success: true, data: { passed, warnings, failed, results } };
1869
- }
1870
- output.writeln();
1871
- output.writeln(output.warning('All checks passed with some warnings.'));
1872
- return { success: true, data: { passed, warnings, failed, results } };
1873
- }
1874
- else {
1875
- output.writeln();
1876
- output.writeln(output.success('All checks passed! System is healthy.'));
1877
- return { success: true, data: { passed, warnings, failed, results } };
1878
- }
1879
- }
207
+ return finalize({ results, strict, allowWarnList });
208
+ },
1880
209
  };
1881
210
  export default doctorCommand;
1882
211
  //# sourceMappingURL=doctor.js.map