π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(doctor): add versioned JSON health check output (#4228)
bbansca31fc52bec9
diff --git a/docs/doctor-json.md b/docs/doctor-json.mdnew file mode 100644index 0000000000..5926e68c0c--- /dev/null+++ b/docs/doctor-json.md@@ -0,0 +1,30 @@+# Machine-readable doctor checks++Use `ruflo doctor --json` for CI and editor integrations. To select one component,+use `ruflo doctor --json --component node` (or `-c node`).++Standard output contains one JSON object, without banners, progress spinners,+ANSI styling, or startup update notifications:++```json+{"schemaVersion":1,"checks":[{"id":"node","status":"pass","name":"Node.js Version","detail":"v24.18.0 (>= 20 required)"}]}+```++`schemaVersion` identifies the output contract. Each check has a stable `id`,+`status` (`pass`, `warn`, or `fail`), a display `name`, and a human-readable+`detail`. Checks may include `fix` with a suggested command. Use IDs and statuses+for automation; display names and details can change. Component aliases share+IDs. Grouped components such as `memory` and `proxy` return multiple checks with+distinct IDs. Native AgentDB integrity IDs use `memory-native:<database path>`+with forward slashes to distinguish simultaneously present database files.++The exit code is 1 when any check fails, and 0 for passing or warning-only+results. An invalid component returns exit code 1 and a JSON object with+`schemaVersion: 1`, `checks: []`, and an `error` string.++JSON mode cannot be combined with `--fix`, `--install`, or `--fix-handles`.+These combinations return the same JSON error shape before performing repairs.+Run repairs separately, then repeat the JSON health check. Suggested `fix`+commands are included in JSON without requiring `--fix`.++Without `--json`, doctor retains its existing text output and repair behavior.diff --git a/v3/@claude-flow/cli/__tests__/doctor-json-cli.test.ts b/v3/@claude-flow/cli/__tests__/doctor-json-cli.test.tsnew file mode 100644index 0000000000..4312ff4791--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/doctor-json-cli.test.ts@@ -0,0 +1,51 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createRequire } from 'node:module';+import { spawnSync } from 'node:child_process';+import { pathToFileURL } from 'node:url';++const require = createRequire(import.meta.url);+const entry = new URL('../src/index.ts', import.meta.url).href;++describe('doctor JSON through CLI.run', () => {+ let project: string;+ beforeAll(() => {+ project = mkdtempSync(join(tmpdir(), 'doctor-json-cli-'));+ mkdirSync(join(project, 'home'));+ writeFileSync(join(project, 'broken.json'), '{ invalid json');+ });+ afterAll(() => rmSync(project, { recursive: true, force: true }));++ function run(component: string, extra: string[] = [], env: Record<string, string> = {}) {+ const args = ['doctor', '--json', '-c', component, '--verbose', ...extra];+ return spawnSync(process.execPath, [+ '--import', pathToFileURL(require.resolve('tsx')).href, '--input-type=module', '-e',+ `import { CLI } from ${JSON.stringify(entry)}; await new CLI({interactive:false}).run(${JSON.stringify(args)});`,+ ], {+ cwd: project, encoding: 'utf8', timeout: 30_000,+ env: { ...process.env, HOME: join(project, 'home'), USERPROFILE: join(project, 'home'),+ DEBUG: '1', RUFLO_DAEMON_AUTOSTART: '0', CLAUDE_FLOW_ENCRYPT_AT_REST: '0',+ CLAUDE_FLOW_ENCRYPTION_KEY: '', ...env },+ });+ }++ it('keeps verbose and config diagnostics off stdout', () => {+ const child = run('node', ['--config', join(project, 'broken.json')]);+ expect(child.error, child.stderr).toBeUndefined();+ expect(child.status, child.stderr).toBe(0);+ expect(JSON.parse(child.stdout)).toEqual({ schemaVersion: 1, checks: [{+ id: 'node', name: 'Node.js Version', status: 'pass', detail: `${process.version} (>= 20 required)`,+ }] });+ expect(child.stdout).not.toContain('\x1b');+ expect(child.stderr).toContain('Executing: doctor');+ });++ it('exits 1 with parseable JSON on a failed real check', () => {+ const child = run('encryption', [], { CLAUDE_FLOW_ENCRYPT_AT_REST: '1' });+ expect(child.error, child.stderr).toBeUndefined();+ expect(child.status, child.stderr).toBe(1);+ expect(JSON.parse(child.stdout).checks[0]).toMatchObject({ id: 'encryption', status: 'fail' });+ });+});diff --git a/v3/@claude-flow/cli/__tests__/doctor-json.test.ts b/v3/@claude-flow/cli/__tests__/doctor-json.test.tsnew file mode 100644index 0000000000..cb17d0c4e6--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/doctor-json.test.ts@@ -0,0 +1,111 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { doctorCommand } from '../src/commands/doctor.js';+import { CommandParser } from '../src/parser.js';+import { output } from '../src/output.js';+import * as nativeAddon from '../src/commands/doctor-native-addon.js';++describe('doctor --json (#3416)', () => {+ let stdout: string;++ beforeEach(() => {+ stdout = '';+ vi.spyOn(process.stdout, 'write').mockImplementation((chunk: any) => {+ stdout += String(chunk);+ return true;+ });+ vi.spyOn(output, 'createSpinner');+ vi.stubEnv('CLAUDE_FLOW_ENCRYPT_AT_REST', '0');+ vi.stubEnv('CLAUDE_FLOW_ENCRYPTION_KEY', '');+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+ });++ async function run(args: string[]) {+ const parser = new CommandParser();+ parser.registerCommand(doctorCommand);+ const parsed = parser.parse(['doctor', ...args]);+ expect(parser.validateFlags(parsed.flags, doctorCommand)).toEqual([]);+ const result = await doctorCommand.action!({+ flags: parsed.flags, args: parsed.positional, cwd: process.cwd(), interactive: false,+ });+ return { result, document: JSON.parse(stdout) };+ }++ it('prints exactly one JSON document with the real Node check and a stable ID', async () => {+ const { result, document } = await run(['--json', '-c', 'node', '--verbose']);+ expect(result).toMatchObject({ success: true, exitCode: 0 });+ expect(document).toEqual({ schemaVersion: 1, checks: [{+ id: 'node', name: 'Node.js Version', status: 'pass',+ detail: `${process.version} (>= 20 required)`,+ }] });+ expect(stdout).not.toContain('\x1b');+ expect(output.createSpinner).not.toHaveBeenCalled();+ });++ it('keeps warning-only checks successful and includes suggested fixes', async () => {+ const { result, document } = await run(['--json', '-c', 'encryption']);+ expect(result).toMatchObject({ success: true, exitCode: 0 });+ expect(document.checks[0]).toMatchObject({ id: 'encryption', status: 'warn' });+ expect(document.checks[0].fix).toContain('CLAUDE_FLOW_ENCRYPT_AT_REST=1');+ });++ it('preserves failed health-check exit status with valid JSON', async () => {+ vi.stubEnv('CLAUDE_FLOW_ENCRYPT_AT_REST', '1');+ const { result, document } = await run(['--json', '-c', 'encryption']);+ expect(result).toMatchObject({ success: false, exitCode: 1 });+ expect(document.checks[0]).toMatchObject({ id: 'encryption', status: 'fail' });+ expect(document.checks[0].detail).toContain('unset');+ });++ it('retains the check ID when a health check rejects', async () => {+ vi.spyOn(nativeAddon, 'checkNativeAddonHeaders').mockRejectedValue(new Error('probe failed'));+ const { result, document } = await run(['--json', '-c', 'native-addon']);+ expect(result).toMatchObject({ success: false, exitCode: 1 });+ expect(document.checks).toEqual([{+ id: 'native-addon', name: 'Check', status: 'fail', detail: 'probe failed',+ }]);+ });++ it.each(['missing', 'toString', '__proto__', ''])('reports invalid component %j as JSON', async component => {+ const { result, document } = await run(['--json', '-c', component]);+ expect(result).toMatchObject({ success: false, exitCode: 1 });+ expect(document).toMatchObject({ schemaVersion: 1, checks: [], error: expect.stringContaining('Unknown doctor component') });+ });++ it.each(['--fix', '--install', '--fix-handles'])('rejects %s before taking repair actions', async flag => {+ const { result, document } = await run(['--json', flag]);+ expect(result).toMatchObject({ success: false, exitCode: 1 });+ expect(document).toMatchObject({ schemaVersion: 1, checks: [], error: expect.stringContaining('cannot be combined') });+ expect(output.createSpinner).not.toHaveBeenCalled();+ });++ it('expands grouped checks with distinct stable IDs', async () => {+ const { document } = await run(['--json', '-c', 'proxy']);+ expect(document.checks.map((check: { id: string }) => check.id)).toEqual([+ 'proxy-consent', 'proxy-binary', 'proxy-process', 'proxy-bind',+ ]);+ expect(document.checks.every((check: { detail: unknown }) => typeof check.detail === 'string')).toBe(true);+ });++ it('uses the same canonical ID for component aliases', async () => {+ const first = await run(['--json', '-c', 'learning']);+ stdout = '';+ const second = await run(['--json', '-c', 'learning-bridge']);+ expect(first.document.checks[0].id).toBe('learning');+ expect(second.document.checks[0].id).toBe('learning');+ });++ it('keeps the default human-readable renderer', async () => {+ const result = await doctorCommand.action!({+ flags: { _: [], component: 'node' }, args: [], cwd: process.cwd(), interactive: false,+ });+ expect(result.success).toBe(true);+ expect(stdout).toContain('RuFlo Doctor');+ expect(stdout).toContain('Node.js Version');+ expect(stdout).toContain('Summary:');+ expect(stdout).not.toContain('schemaVersion');+ });+});diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.tsindex 4959ebb45f..03878123d1 100644--- a/v3/@claude-flow/cli/src/commands/doctor.ts+++ b/v3/@claude-flow/cli/src/commands/doctor.ts@@ -2578,6 +2578,12 @@ export const doctorCommand: Command = {name: 'doctor',description: 'System diagnostics and health checks',options: [+ {+ name: 'json',+ description: 'Emit versioned JSON health checks (cannot be combined with repair flags)',+ type: 'boolean',+ default: false+ },{name: 'fix',short: 'f',@@ -2624,6 +2630,7 @@ export const doctorCommand: Command = {}],examples: [+ { command: 'claude-flow doctor --json -c node', description: 'Emit machine-readable health checks' },{ command: 'claude-flow doctor', description: 'Run full health check' },{ command: 'claude-flow doctor --fix', description: 'Print suggested fix commands (does not auto-apply)' },{ command: 'claude-flow doctor --install', description: 'Auto-install missing dependencies' },@@ -2638,6 +2645,20 @@ export const doctorCommand: Command = {const verbose = ctx.flags.verbose as boolean;// Parser camelCases kebab-case flag names β read via `fixHandles`, not `['fix-handles']`.const fixHandles = ctx.flags.fixHandles as boolean;+ const json = ctx.flags.json as boolean;+ const reportError = (message: string): CommandResult => {+ if (json) output.writeln(JSON.stringify({ schemaVersion: 1, checks: [], error: message }));+ else output.printError(message);+ return { success: false, exitCode: 1, message };+ };+ if (json && (showFix || autoInstall || fixHandles)) {+ return reportError('--json cannot be combined with --fix, --install, or --fix-handles');+ }++ // Reuse the same callable for anonymous checks so their IDs do not depend+ // on display names or on whether the full or component suite was selected.+ const helperCheck = () => checkHelperIntegrity();+ const nativeAddonCheck = () => checkNativeAddonHeaders();// #2677: `--component memory` now runs the whole memory-health suite,// not just the existence check. Values can be a single check or an@@ -2656,7 +2677,7 @@ export const doctorCommand: Command = {'browser': checkAgentBrowserVersion,'config': checkConfigFile,'stale-settings': checkStaleSettingsNpx, // #2448- 'helpers': () => checkHelperIntegrity(), // #3565+ 'helpers': helperCheck, // #3565'daemon': checkDaemonStatus,get memory() { return [checkMemoryDatabase, // existing: exists + statable (unchanged)@@ -2670,7 +2691,7 @@ export const doctorCommand: Command = {checkMemoryCritiqueCoverage, // #2677 check 6: feedback carries lessons]; },'memory-package': checkMemoryPackageVersion, // #3392- 'native-addon': () => checkNativeAddonHeaders(), // #4055+ 'native-addon': nativeAddonCheck, // #4055'learning': checkLearningBridge, // #2545'learning-bridge': checkLearningBridge, // #2545'api': checkApiKeys,@@ -2697,8 +2718,7 @@ export const doctorCommand: Command = {if (component !== undefined && !Object.hasOwn(componentMap, component)) {const message = `Unknown doctor component: ${JSON.stringify(component)}. Valid components: ${Object.keys(componentMap).join(', ')}`;- output.printError(message);- return { success: false, exitCode: 1, message };+ return reportError(message);}// Early-return short-circuit: `--fix-handles` is a targeted mitigation, not@@ -2769,13 +2789,16 @@ export const doctorCommand: Command = {return { success: true };}- output.writeln();- output.writeln(output.bold('RuFlo Doctor'));- output.writeln(output.dim('System diagnostics and health check'));- output.writeln(output.dim('β'.repeat(50)));- output.writeln();+ if (!json) {+ output.writeln();+ output.writeln(output.bold('RuFlo Doctor'));+ output.writeln(output.dim('System diagnostics and health check'));+ output.writeln(output.dim('β'.repeat(50)));+ output.writeln();+ }- const nativeAgentDbChecks = (await existingNativeAgentDbPaths())+ const nativeAgentDbPaths = await existingNativeAgentDbPaths();+ const nativeAgentDbChecks = nativeAgentDbPaths.map((dbPath) => () => checkNativeAgentDbStructuralIntegrity(dbPath));const allChecks: (() => Promise<HealthCheck>)[] = [@@ -2788,7 +2811,7 @@ export const doctorCommand: Command = {checkGitRepo,checkConfigFile,checkStaleSettingsNpx, // #2448/#2677 β runaway `npx @latest` in settings- () => checkHelperIntegrity(), // #3565 β installed signed helpers vs manifest+ helperCheck, // #3565 β installed signed helpers vs manifestcheckDaemonStatus,checkMemoryDatabase,checkMemoryStructuralIntegrity, // #2737 β bounded, native quick_check on every default run@@ -2796,7 +2819,7 @@ export const doctorCommand: Command = {checkMemoryPersistenceDriver, // #2968/#3321 β read-only native capability probecheckLearningBridge, // #2545 β can the auto-memory hook actually load @claude-flow/memory?checkMemoryPackageVersion, // #3392 β loaded @claude-flow/memory must satisfy the CLI's declared range- () => checkNativeAddonHeaders(), // #4055 β better-sqlite3 built against Node 24.19+ headers on 24.19-24.21+ nativeAddonCheck, // #4055 β better-sqlite3 built against Node 24.19+ headers on 24.19-24.21checkApiKeys,checkMcpServers,checkMcpSchemaOverhead, // #2726 β fixed tools/list prompt cost@@ -2821,24 +2844,62 @@ export const doctorCommand: Command = {checksToRun = Array.isArray(entry) ? entry : [entry];}+ // These are API identifiers: keep them stable even when user-facing names+ // change. Grouped components have a distinct ID for each individual check.+ const checkIds = new Map<() => Promise<HealthCheck>, string>([+ [checkVersionFreshness, 'version'], [checkNodeVersion, 'node'],+ [checkNpmVersion, 'npm'], [checkClaudeCode, 'claude'],+ [checkAgentBrowserVersion, 'browser'], [checkGit, 'git'],+ [checkGitRepo, 'git-repo'], [checkConfigFile, 'config'],+ [checkStaleSettingsNpx, 'stale-settings'], [helperCheck, 'helpers'],+ [checkDaemonStatus, 'daemon'], [checkMemoryDatabase, 'memory-presence'],+ [checkMemoryStructuralIntegrity, 'memory-structural'],+ [checkMemoryIntegrity, 'memory-integrity'],+ [checkMemoryPersistenceDriver, 'memory-driver'],+ [checkMemoryPackageVersion, 'memory-package'],+ [checkMemoryContent, 'memory-content'],+ [checkMemoryEmbeddingCoverage, 'memory-embeddings'],+ [checkMemoryReflexionCoverage, 'memory-reflexion'],+ [checkMemoryCritiqueCoverage, 'memory-critique'],+ [checkLearningBridge, 'learning'], [nativeAddonCheck, 'native-addon'],+ [checkApiKeys, 'api'], [checkMcpServers, 'mcp'],+ [checkMcpSchemaOverhead, 'mcp-overhead'], [checkAIDefence, 'aidefence'],+ [checkDiskSpace, 'disk'], [checkBuildTools, 'typescript'],+ [checkAgenticFlow, 'agentic-flow'], [checkEncryptionAtRest, 'encryption'],+ [checkFederationBreaker, 'federation'], [checkMetaharness, 'metaharness'],+ [checkMetaharnessDeclaredPackages, 'metaharness-packages'],+ [checkMetaharnessIntegration, 'metaharness-integration'],+ [checkFunnel, 'funnel'], [checkProxySponsoredConsent, 'proxy-consent'],+ [checkProxyBinary, 'proxy-binary'], [checkProxyProcess, 'proxy-process'],+ [checkProxyBindAddress, 'proxy-bind'], [checkAuth, 'auth'],+ [checkTypesafeRouter, 'typesafe'], [checkMods, 'mods'],+ ]);+ nativeAgentDbChecks.forEach((check, index) => {+ // The path distinguishes simultaneous authority files; normalize separators.+ checkIds.set(check, `memory-native:${nativeAgentDbPaths[index].replace(/\\/g, '/')}`);+ });+ if (json && checksToRun.some(check => !checkIds.has(check))) {+ return reportError('Doctor check is missing a stable JSON ID');+ }+const results: HealthCheck[] = [];const fixes: string[] = [];// OPTIMIZATION: Run all checks in parallel for 3-5x faster execution- const spinner = output.createSpinner({ text: 'Running health checks in parallel...', spinner: 'dots' });- spinner.start();+ const spinner = json ? undefined : output.createSpinner({ text: 'Running health checks in parallel...', spinner: 'dots' });+ spinner?.start();try {// Execute all checks concurrentlyconst checkResults = await Promise.allSettled(checksToRun.map(check => check()));- spinner.stop();+ spinner?.stop();// Process results in orderfor (const settledResult of checkResults) {if (settledResult.status === 'fulfilled') {const result = settledResult.value;results.push(result);- output.writeln(formatCheck(result));+ if (!json) output.writeln(formatCheck(result));if (result.fix && (result.status === 'fail' || result.status === 'warn')) {fixes.push(`${result.name}: ${result.fix}`);@@ -2850,11 +2911,12 @@ export const doctorCommand: Command = {message: settledResult.reason?.message || 'Unknown error'};results.push(errorResult);- output.writeln(formatCheck(errorResult));+ if (!json) output.writeln(formatCheck(errorResult));}}} catch (error) {- spinner.stop();+ spinner?.stop();+ if (json) return reportError(`Failed to run health checks: ${error instanceof Error ? error.message : String(error)}`);output.writeln(output.error('Failed to run health checks'));}@@ -2905,6 +2967,19 @@ export const doctorCommand: Command = {const warnings = results.filter(r => r.status === 'warn').length;const failed = results.filter(r => r.status === 'fail').length;+ if (json) {+ const checks = results.map((result, index) => ({+ id: checkIds.get(checksToRun[index])!,+ status: result.status,+ name: result.name,+ detail: result.message,+ ...(result.fix ? { fix: result.fix } : {}),+ }));+ const data = { schemaVersion: 1, checks };+ output.writeln(JSON.stringify(data));+ return { success: failed === 0, exitCode: failed > 0 ? 1 : 0, data };+ }+output.writeln();output.writeln(output.dim('β'.repeat(50)));output.writeln();diff --git a/v3/@claude-flow/cli/src/index.ts b/v3/@claude-flow/cli/src/index.tsindex 775ddda413..a417b95c1f 100644--- a/v3/@claude-flow/cli/src/index.ts+++ b/v3/@claude-flow/cli/src/index.ts@@ -133,7 +133,7 @@ export class CLI {}// Run startup update check (non-blocking, silent on skip)- if (!flags.noUpdate && commandPath[0] !== 'update') {+ if (!flags.noUpdate && commandPath[0] !== 'update' && !(commandPath[0] === 'doctor' && flags.json)) {this.checkForUpdatesOnStartup().catch(() => {/* silent */});}@@ -587,7 +587,7 @@ export class CLI {} catch (error) {// Config loading is optional - don't fail if it doesn't existif (process.env.DEBUG) {- this.output.writeln(+ this.output.writeErrorln(this.output.dim(`Config loading failed: ${(error as Error).message}`));}