Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions src/commands/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@ import type {
DiagnosticReport,
DiagnosticResult,
DiagnosticSummary,
DiagnosticReportJSON,
} from '../diagnostics/types.js';
import { DIAGNOSTIC_SCHEMA_VERSION } from '../diagnostics/types.js';
import { EXIT_CODES } from '../errors/errors.js';
import { TerminalOutput } from '../output/terminal.js';

export interface DoctorCommandOptions {
readonly checks?: readonly DiagnosticCheck[];
readonly output?: TerminalOutput;
readonly setExitCode?: (code: number) => void;
readonly json?: boolean;
}

// Exported bounds for diagnostic text rendering.
Expand Down Expand Up @@ -66,6 +69,27 @@ function formatResult(result: DiagnosticResult): string {
return `[${result.status.toUpperCase()}] ${label}: ${message}`;
}

function renderJSONReport(report: DiagnosticReport): DiagnosticReportJSON {
return {
schemaVersion: DIAGNOSTIC_SCHEMA_VERSION,
checks: report.results.map((result) => ({
id: result.id,
label: result.label,
status: result.status,
message: sanitizeText(result.message, MAX_MESSAGE_LENGTH),
...(result.remediation === undefined
? {}
: { remediation: sanitizeText(result.remediation, MAX_REMEDIATION_LENGTH) }),
})),
summary: {
pass: report.summary.pass,
warn: report.summary.warn,
fail: report.summary.fail,
total: report.summary.total,
},
};
}

function formatOverallHealth(summary: DiagnosticSummary): string {
if (summary.total === 0) {
return 'Overall health: no diagnostics registered.';
Expand Down Expand Up @@ -130,12 +154,22 @@ export function createDoctorCommand(
const output = options.output ?? new TerminalOutput();
const setExitCode =
options.setExitCode ?? ((code) => (process.exitCode = code));
const isJsonMode = options.json ?? false;

return new Command('doctor')
.description('Check the local StellarForge development environment.')
.action(() => {
.option('--json', 'Output as JSON')
.action((cmdOptions) => {
const report = runDiagnostics(checks);
renderDiagnosticReport(report, output);
const jsonMode = isJsonMode || cmdOptions.json;

if (jsonMode) {
const jsonReport = renderJSONReport(report);
console.log(JSON.stringify(jsonReport, null, 2));
} else {
renderDiagnosticReport(report, output);
}

setExitCode(
report.summary.fail > 0 ? EXIT_CODES.diagnostic : EXIT_CODES.success,
);
Expand Down
22 changes: 22 additions & 0 deletions src/diagnostics/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,25 @@ export interface DiagnosticReport {
readonly results: readonly DiagnosticResult[];
readonly summary: DiagnosticSummary;
}

// JSON output schema (versioned and stable)
export const DIAGNOSTIC_SCHEMA_VERSION = '1.0.0';

export interface DiagnosticCheckJSON {
readonly id: string;
readonly label: string;
readonly status: DiagnosticStatus;
readonly message: string;
readonly remediation?: string;
}

export interface DiagnosticReportJSON {
readonly schemaVersion: string;
readonly checks: readonly DiagnosticCheckJSON[];
readonly summary: {
readonly pass: number;
readonly warn: number;
readonly fail: number;
readonly total: number;
};
}
200 changes: 200 additions & 0 deletions tests/doctor-output-conformance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import type {
DiagnosticCheck,
DiagnosticReport,
DiagnosticStatus,
DiagnosticReportJSON,
} from '../src/diagnostics/types.js';
import { DIAGNOSTIC_SCHEMA_VERSION } from '../src/diagnostics/types.js';
import { EXIT_CODES } from '../src/errors/errors.js';
import { createCapturedTerminalOutput } from './helpers/captured-output.js';

Expand Down Expand Up @@ -61,6 +63,43 @@ function runDoctorWithChecks(checks: readonly DiagnosticCheck[]): {
};
}

function runDoctorJsonWithChecks(checks: readonly DiagnosticCheck[]): {
exitCode: number;
stdout: string;
stderr: string;
json: DiagnosticReportJSON | null;
} {
const captured = createCapturedTerminalOutput();
let exitCode = -1;
const command = createDoctorCommand({
checks,
output: captured.output,
setExitCode: (code) => {
exitCode = code;
},
json: true,
});

command.parse(['node', 'doctor']);

let json: DiagnosticReportJSON | null = null;
try {
const stdout = captured.stdoutText().trim();
if (stdout) {
json = JSON.parse(stdout) as DiagnosticReportJSON;
}
} catch {
// Invalid JSON
}

return {
exitCode,
stdout: captured.stdoutText(),
stderr: captured.stderrText(),
json,
};
}

describe('SW-001: Doctor output snapshot conformance tests', () => {
it('matches output snapshot and contract for all-pass diagnostics', () => {
const checks: readonly DiagnosticCheck[] = [
Expand Down Expand Up @@ -221,3 +260,164 @@ describe('SW-001: Doctor output snapshot conformance tests', () => {
]);
});
});

describe('SW-002: Doctor JSON output schema and determinism tests', () => {
it('outputs valid JSON with stable schema version', () => {
const checks: readonly DiagnosticCheck[] = [
mockCheck('node', 'Node.js', 'pass', 'Supported version 22.13.0 detected.'),
mockCheck('npm', 'npm', 'pass', 'Supported version 10.9.2 detected.'),
];

const result = runDoctorJsonWithChecks(checks);

expect(result.exitCode).toBe(EXIT_CODES.success);
expect(result.stderr).toBe('');
expect(result.json).not.toBeNull();
expect(result.json?.schemaVersion).toBe(DIAGNOSTIC_SCHEMA_VERSION);
expect(result.json?.schemaVersion).toBe('1.0.0');
});

it('JSON output includes check id, label, status, message, and optional remediation', () => {
const checks: readonly DiagnosticCheck[] = [
mockCheck(
'node',
'Node.js',
'pass',
'Supported version 22.13.0 detected.',
),
mockCheck(
'docker',
'Docker',
'warn',
'Docker daemon is unavailable.',
'Start Docker Desktop when needed.',
),
];

const result = runDoctorJsonWithChecks(checks);

expect(result.json?.checks).toEqual([
{
id: 'node',
label: 'Node.js',
status: 'pass',
message: 'Supported version 22.13.0 detected.',
},
{
id: 'docker',
label: 'Docker',
status: 'warn',
message: 'Docker daemon is unavailable.',
remediation: 'Start Docker Desktop when needed.',
},
]);
});

it('JSON output excludes remediation field when not present', () => {
const checks: readonly DiagnosticCheck[] = [
mockCheck('node', 'Node.js', 'pass', 'Supported version 22.13.0 detected.'),
];

const result = runDoctorJsonWithChecks(checks);

expect(result.json?.checks[0]).toHaveProperty('id');
expect(result.json?.checks[0]).toHaveProperty('status');
expect(result.json?.checks[0]).not.toHaveProperty('remediation');
});

it('JSON output includes accurate summary counts', () => {
const checks: readonly DiagnosticCheck[] = [
mockCheck('node', 'Node.js', 'pass', 'Supported version 22.13.0 detected.'),
mockCheck('npm', 'npm', 'pass', 'Supported version 10.9.2 detected.'),
mockCheck('docker', 'Docker', 'warn', 'Docker daemon is unavailable.'),
mockCheck('stellar', 'Stellar CLI', 'fail', 'Stellar CLI not found.'),
];

const result = runDoctorJsonWithChecks(checks);

expect(result.json?.summary).toEqual({
pass: 2,
warn: 1,
fail: 1,
total: 4,
});
});

it('JSON output is deterministic across multiple runs', () => {
const checks: readonly DiagnosticCheck[] = [
mockCheck('node', 'Node.js', 'pass', 'Supported version 22.13.0 detected.'),
mockCheck('npm', 'npm', 'pass', 'Supported version 10.9.2 detected.'),
mockCheck('docker', 'Docker', 'warn', 'Docker daemon is unavailable.', 'Start Docker.'),
];

const result1 = runDoctorJsonWithChecks(checks);
const result2 = runDoctorJsonWithChecks(checks);

expect(JSON.stringify(result1.json)).toBe(JSON.stringify(result2.json));
});

it('JSON output maintains check registration order (not sorted)', () => {
const checks: readonly DiagnosticCheck[] = [
mockCheck('z-tool', 'Z Tool', 'pass', 'Z is available.'),
mockCheck('a-tool', 'A Tool', 'fail', 'A is not available.'),
mockCheck('m-tool', 'M Tool', 'warn', 'M is available but degraded.'),
];

const result = runDoctorJsonWithChecks(checks);

const ids = result.json?.checks.map((c) => c.id) ?? [];
expect(ids).toEqual(['z-tool', 'a-tool', 'm-tool']);
});

it('JSON exit code semantics match human output: fail returns diagnostic exit code', () => {
const checks: readonly DiagnosticCheck[] = [
mockCheck('node', 'Node.js', 'pass', 'Supported version 22.13.0 detected.'),
mockCheck('stellar', 'Stellar CLI', 'fail', 'Stellar CLI not found.'),
];

const result = runDoctorJsonWithChecks(checks);

expect(result.exitCode).toBe(EXIT_CODES.diagnostic);
});

it('JSON exit code semantics match human output: warning+pass returns success', () => {
const checks: readonly DiagnosticCheck[] = [
mockCheck('node', 'Node.js', 'pass', 'Supported version 22.13.0 detected.'),
mockCheck('docker', 'Docker', 'warn', 'Docker daemon is unavailable.'),
];

const result = runDoctorJsonWithChecks(checks);

expect(result.exitCode).toBe(EXIT_CODES.success);
});

it('JSON output is clean on stdout (no progress/banner noise)', () => {
const checks: readonly DiagnosticCheck[] = [
mockCheck('node', 'Node.js', 'pass', 'Supported version 22.13.0 detected.'),
];

const result = runDoctorJsonWithChecks(checks);

// stdout should be valid JSON only
const stdout = result.stdout.trim();
expect(() => JSON.parse(stdout)).not.toThrow();
expect(stdout).toMatch(/^{\s*"schemaVersion"/);
});

it('JSON output redacts secrets from messages and remediation', () => {
const checks: readonly DiagnosticCheck[] = [
mockCheck(
'token-test',
'Token Test',
'fail',
'Token ghp_1234567890abcdefghijklmnop is invalid.',
'Use a valid token like ghp_abcdefghijklmnopqrstuvwxyz123456.',
),
];

const result = runDoctorJsonWithChecks(checks);

expect(result.json?.checks[0].message).toContain('[REDACTED]');
expect(result.json?.checks[0].remediation).toContain('[REDACTED]');
});
});