From b9faeb5948504223ddd4072fe5128fdc3df358c8 Mon Sep 17 00:00:00 2001 From: abbaskachia Date: Mon, 23 Nov 2026 09:41:09 +0100 Subject: [PATCH 1/2] feat: add machine-readable JSON output mode for doctor command --- src/commands/doctor.ts | 38 ++++- src/diagnostics/types.ts | 22 +++ tests/doctor-output-conformance.test.ts | 200 ++++++++++++++++++++++++ 3 files changed, 258 insertions(+), 2 deletions(-) diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts index d2bb42fb..80ae5a77 100644 --- a/src/commands/doctor.ts +++ b/src/commands/doctor.ts @@ -13,7 +13,9 @@ 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'; @@ -21,6 +23,7 @@ export interface DoctorCommandOptions { readonly checks?: readonly DiagnosticCheck[]; readonly output?: TerminalOutput; readonly setExitCode?: (code: number) => void; + readonly json?: boolean; } // Exported bounds for diagnostic text rendering. @@ -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.'; @@ -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, ); diff --git a/src/diagnostics/types.ts b/src/diagnostics/types.ts index c5d2ce70..1772bea7 100644 --- a/src/diagnostics/types.ts +++ b/src/diagnostics/types.ts @@ -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; + }; +} diff --git a/tests/doctor-output-conformance.test.ts b/tests/doctor-output-conformance.test.ts index 7cd33253..e1e380bc 100644 --- a/tests/doctor-output-conformance.test.ts +++ b/tests/doctor-output-conformance.test.ts @@ -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'; @@ -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[] = [ @@ -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]'); + }); +}); From 48379b85b3c0a1e9fd927a25b75a3566bb347741 Mon Sep 17 00:00:00 2001 From: abbaskachia Date: Mon, 23 Nov 2026 10:04:20 +0100 Subject: [PATCH 2/2] feat(ux): add color selection following NO_COLOR convention --- src/output/index.ts | 1 + src/output/terminal.ts | 44 ++++++++++ tests/terminal-output.test.ts | 148 +++++++++++++++++++++++++++++++++- 3 files changed, 192 insertions(+), 1 deletion(-) diff --git a/src/output/index.ts b/src/output/index.ts index 1545a693..8e43d315 100644 --- a/src/output/index.ts +++ b/src/output/index.ts @@ -2,6 +2,7 @@ export { redactSecretLikeText, REDACTED_PLACEHOLDER } from './redaction.js'; export { getStringDisplayWidth, sanitizeTerminalText, + shouldUseColor, TerminalOutput, wrapTerminalText, type TerminalOutputOptions, diff --git a/src/output/terminal.ts b/src/output/terminal.ts index 7ac4e7ac..523a872c 100644 --- a/src/output/terminal.ts +++ b/src/output/terminal.ts @@ -24,6 +24,12 @@ export interface TerminalOutputOptions { * the output stream explicitly provides a positive `columns` property. */ readonly columns?: number; + /** + * Whether to use ANSI color codes in output. + * When omitted, determined by: NO_COLOR env var (disables), TTY detection, + * and FORCE_COLOR env var (enables only if NO_COLOR is not set). + */ + readonly useColor?: boolean; } export interface WrapOptions { @@ -45,6 +51,33 @@ const BEL = 0x07; const BACKSLASH = 0x5c; const MAX_CONTROL_SEQUENCE_LENGTH = 4096; +/** + * Determines whether ANSI color codes should be used in output based on: + * - NO_COLOR environment variable (disables colors) + * - TTY detection (enables colors if connected to terminal) + * - FORCE_COLOR environment variable (enables colors if NO_COLOR not set) + * + * NO_COLOR takes precedence over TTY and FORCE_COLOR, following the convention. + * @see https://no-color.org/ + */ +export function shouldUseColor( + stream?: TextOutputStream, + environment: NodeJS.ProcessEnv = process.env, +): boolean { + // NO_COLOR disables colors regardless of other factors + if (environment.NO_COLOR !== undefined && environment.NO_COLOR !== '') { + return false; + } + + // FORCE_COLOR enables colors (unless NO_COLOR is set, which we checked above) + if (environment.FORCE_COLOR !== undefined && environment.FORCE_COLOR !== '') { + return true; + } + + // TTY detection: check if connected to interactive terminal + return stream?.isTTY === true; +} + function isTerminalControlCharacter(code: number): boolean { return ( code <= 0x08 || @@ -443,6 +476,7 @@ export function wrapTerminalText( export class TerminalOutput { readonly #streams: TerminalOutputStreams; readonly #columns: number | undefined; + readonly #useColor: boolean; constructor( streams: TerminalOutputStreams = { @@ -453,6 +487,12 @@ export class TerminalOutput { ) { this.#streams = streams; this.#columns = options.columns; + this.#useColor = + options.useColor ?? + shouldUseColor( + this.#streams.stdout, + typeof process !== 'undefined' ? process.env : {}, + ); } // Returns whether the destination stream can accept more data immediately @@ -475,6 +515,10 @@ export class TerminalOutput { return this.#write(this.#streams.stderr, message); } + get useColor(): boolean { + return this.#useColor; + } + onceStdoutDrained(listener: () => void): void { this.#onceDrained(this.#streams.stdout, listener); } diff --git a/tests/terminal-output.test.ts b/tests/terminal-output.test.ts index 8e0763a5..83fa617b 100644 --- a/tests/terminal-output.test.ts +++ b/tests/terminal-output.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, afterEach } from 'vitest'; import { REDACTED_PLACEHOLDER, redactSecretLikeText, @@ -6,6 +6,7 @@ import { import { sanitizeTerminalText, TerminalOutput, + shouldUseColor, type TextOutputStream, } from '../src/output/terminal.js'; import { TERMINAL_FIXTURES } from './fixtures/terminal-output-fixtures.js'; @@ -168,3 +169,148 @@ describe('sanitizeTerminalText', () => { expect(stdout[0]).not.toContain('\r'); }); }); + +describe('shouldUseColor', () => { + const originalEnv = { ...process.env }; + + afterEach(() => { + process.env.NO_COLOR = originalEnv.NO_COLOR; + process.env.FORCE_COLOR = originalEnv.FORCE_COLOR; + }); + + it('disables color when NO_COLOR is set', () => { + const result = shouldUseColor(undefined, { NO_COLOR: '1' }); + expect(result).toBe(false); + }); + + it('disables color when NO_COLOR is set to any non-empty value', () => { + const result = shouldUseColor(undefined, { NO_COLOR: 'true' }); + expect(result).toBe(false); + }); + + it('enables color when NO_COLOR is empty string', () => { + const result = shouldUseColor( + { write: () => true, isTTY: true }, + { NO_COLOR: '', FORCE_COLOR: undefined }, + ); + expect(result).toBe(true); + }); + + it('disables color for non-TTY output by default', () => { + const result = shouldUseColor( + { write: () => true, isTTY: false }, + { NO_COLOR: undefined, FORCE_COLOR: undefined }, + ); + expect(result).toBe(false); + }); + + it('enables color for TTY output by default', () => { + const result = shouldUseColor( + { write: () => true, isTTY: true }, + { NO_COLOR: undefined, FORCE_COLOR: undefined }, + ); + expect(result).toBe(true); + }); + + it('enables color when FORCE_COLOR is set and NO_COLOR is not', () => { + const result = shouldUseColor( + { write: () => true, isTTY: false }, + { NO_COLOR: undefined, FORCE_COLOR: '1' }, + ); + expect(result).toBe(true); + }); + + it('disables color when NO_COLOR is set even if FORCE_COLOR is set', () => { + const result = shouldUseColor( + { write: () => true, isTTY: true }, + { NO_COLOR: '1', FORCE_COLOR: '1' }, + ); + expect(result).toBe(false); + }); + + it('defaults to false when stream is undefined and no color env vars are set', () => { + const result = shouldUseColor(undefined, { + NO_COLOR: undefined, + FORCE_COLOR: undefined, + }); + expect(result).toBe(false); + }); + + it('detects TTY from stream isTTY property', () => { + const ttyStream: TextOutputStream = { write: () => true, isTTY: true }; + const result = shouldUseColor(ttyStream, { + NO_COLOR: undefined, + FORCE_COLOR: undefined, + }); + expect(result).toBe(true); + }); + + it('respects NO_COLOR over TTY detection', () => { + const ttyStream: TextOutputStream = { write: () => true, isTTY: true }; + const result = shouldUseColor(ttyStream, { NO_COLOR: '1' }); + expect(result).toBe(false); + }); +}); + +describe('TerminalOutput color selection', () => { + const originalEnv = { ...process.env }; + + afterEach(() => { + process.env.NO_COLOR = originalEnv.NO_COLOR; + process.env.FORCE_COLOR = originalEnv.FORCE_COLOR; + }); + + it('enables color for TTY streams', () => { + const output = new TerminalOutput( + { + stdout: { write: () => true, isTTY: true }, + stderr: { write: () => true }, + }, + {}, + ); + + expect(output.useColor).toBe(true); + }); + + it('disables color for non-TTY streams', () => { + const output = new TerminalOutput( + { + stdout: { write: () => true, isTTY: false }, + stderr: { write: () => true }, + }, + {}, + ); + + expect(output.useColor).toBe(false); + }); + + it('allows explicit color override', () => { + const output = new TerminalOutput( + { + stdout: { write: () => true, isTTY: true }, + stderr: { write: () => true }, + }, + { useColor: false }, + ); + + expect(output.useColor).toBe(false); + }); + + it('status remains understandable without color', () => { + const stdout: string[] = []; + const output = new TerminalOutput( + { + stdout: { write: (s) => stdout.push(s) }, + stderr: { write: () => true }, + }, + { useColor: false }, + ); + + output.success('Operation completed'); + output.info('All systems operational'); + + const allOutput = stdout.join(''); + expect(allOutput).toContain('Operation completed'); + expect(allOutput).toContain('All systems operational'); + }); +});