ktx/packages/cli/src/doctor.test.ts

399 lines
12 KiB
TypeScript
Raw Normal View History

2026-05-10 23:12:26 +02:00
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2026-05-10 23:12:26 +02:00
import {
formatDoctorReport,
2026-05-10 23:51:24 +02:00
runKtxDoctor,
2026-05-10 23:12:26 +02:00
runSetupDoctorChecks,
type DoctorCheck,
} from './doctor.js';
function makeIo() {
let stdout = '';
let stderr = '';
return {
io: {
stdout: {
write: (chunk: string) => {
stdout += chunk;
},
},
stderr: {
write: (chunk: string) => {
stderr += chunk;
},
},
},
stdout: () => stdout,
stderr: () => stderr,
};
}
describe('formatDoctorReport', () => {
it('shows the failing check and its fix in plain output', () => {
2026-05-10 23:12:26 +02:00
const checks: DoctorCheck[] = [
{ id: 'node', label: 'Node 22+', status: 'pass', detail: 'v22.16.0 ABI 127', group: 'toolchain' },
2026-05-10 23:12:26 +02:00
{
id: 'native-sqlite',
label: 'Native SQLite',
status: 'fail',
detail: 'Cannot load better-sqlite3',
fix: 'Run: pnpm run native:rebuild',
group: 'toolchain',
2026-05-10 23:12:26 +02:00
},
];
const output = formatDoctorReport({ title: 'KTX status', checks });
expect(output).toContain('KTX status');
expect(output).toContain('✗ Environment');
expect(output).toContain('1 of 2 need attention');
expect(output).toContain('✗ Native SQLite: Cannot load better-sqlite3');
expect(output).toContain('→ Run: pnpm run native:rebuild');
expect(output).toContain('1 issue to fix.');
});
it('lists what was checked when a group has all passing checks', () => {
const checks: DoctorCheck[] = [
{ id: 'node', label: 'Node 22+', status: 'pass', detail: 'v22.16.0', group: 'toolchain' },
{ id: 'pnpm', label: 'pnpm 10.20+', status: 'pass', detail: '10.28.0', group: 'toolchain' },
];
const output = formatDoctorReport({ title: 'KTX status', checks });
expect(output).toContain('✓ Environment');
expect(output).toContain('Node 22+ · pnpm 10.20+');
expect(output).not.toContain('v22.16.0');
expect(output).toContain('Everything ready.');
});
it('shows the underlying detail for a single-check group on the group line', () => {
const checks: DoctorCheck[] = [
{
id: 'semantic-search-embeddings',
label: 'Semantic search embeddings',
status: 'pass',
detail: 'openai/text-embedding-3-small (1536d) probe succeeded',
group: 'search',
},
];
const output = formatDoctorReport({ title: 'KTX status', checks });
expect(output).toContain('✓ Semantic search');
expect(output).toContain('openai/text-embedding-3-small (1536d) probe succeeded');
});
it('lists every check in verbose mode', () => {
const checks: DoctorCheck[] = [
{ id: 'node', label: 'Node 22+', status: 'pass', detail: 'v22.16.0', group: 'toolchain' },
];
const output = formatDoctorReport({ title: 'KTX status', checks }, { verbose: true });
expect(output).toContain('✓ Node 22+: v22.16.0');
2026-05-10 23:12:26 +02:00
});
});
describe('runSetupDoctorChecks', () => {
it('returns pass checks when injected commands and file checks succeed', async () => {
const checks = await runSetupDoctorChecks({
env: { PATH: '/bin' },
2026-05-10 23:51:24 +02:00
workspaceRoot: '/workspace/ktx',
2026-05-10 23:12:26 +02:00
execText: async (command, args) => {
if (command === 'pnpm' && args[0] === '--version') return '10.28.0';
if (command === 'corepack' && args[0] === '--version') return '0.32.0';
if (command === 'uv' && args[0] === '--version') return 'uv 0.9.5';
2026-05-10 23:51:24 +02:00
if (command === process.execPath && args.includes('--version')) return '@ktx/cli 0.0.0-private';
2026-05-10 23:12:26 +02:00
throw new Error(`${command} ${args.join(' ')}`);
},
pathExists: async () => true,
importBetterSqlite3: async () => ({ default: function Database() {} }),
});
expect(checks.map((check) => [check.id, check.status])).toEqual([
['node', 'pass'],
['pnpm', 'pass'],
['corepack', 'pass'],
['uv', 'pass'],
['native-sqlite', 'pass'],
['package-build', 'pass'],
['workspace-cli', 'pass'],
]);
});
it('returns exact fixes when setup checks fail', async () => {
const checks = await runSetupDoctorChecks({
env: {},
2026-05-10 23:51:24 +02:00
workspaceRoot: '/workspace/ktx',
2026-05-10 23:12:26 +02:00
execText: async (command) => {
throw new Error(`${command} not found`);
},
pathExists: async () => false,
importBetterSqlite3: async () => {
throw new Error('Cannot find module better-sqlite3');
},
});
expect(checks).toContainEqual({
id: 'pnpm',
label: 'pnpm 10.20+',
status: 'fail',
detail: 'pnpm not found',
fix: 'Run: corepack enable && corepack prepare pnpm@10.28.0 --activate',
group: 'toolchain',
2026-05-10 23:12:26 +02:00
});
expect(checks).toContainEqual({
id: 'package-build',
label: 'TypeScript package build',
status: 'fail',
detail: 'Missing packages/cli/dist/bin.js',
fix: 'Run: pnpm run build',
group: 'toolchain',
2026-05-10 23:12:26 +02:00
});
});
it('treats missing corepack as a warning so setup doctor can still pass', async () => {
const checks = await runSetupDoctorChecks({
env: { PATH: '/bin' },
2026-05-10 23:51:24 +02:00
workspaceRoot: '/workspace/ktx',
2026-05-10 23:12:26 +02:00
execText: async (command, args) => {
if (command === 'pnpm' && args[0] === '--version') return '10.28.0';
if (command === 'corepack' && args[0] === '--version') throw new Error('spawn corepack ENOENT');
if (command === 'uv' && args[0] === '--version') return 'uv 0.9.5';
2026-05-10 23:51:24 +02:00
if (command === process.execPath && args.includes('--version')) return '@ktx/cli 0.0.0-private';
2026-05-10 23:12:26 +02:00
throw new Error(`${command} ${args.join(' ')}`);
},
pathExists: async () => true,
importBetterSqlite3: async () => ({ default: function Database() {} }),
});
const testIo = makeIo();
await expect(
runKtxDoctor(
{ command: 'setup', outputMode: 'plain', inputMode: 'disabled', verbose: true },
testIo.io,
{ runSetupChecks: async () => checks },
),
2026-05-10 23:12:26 +02:00
).resolves.toBe(0);
expect(checks).toContainEqual({
id: 'corepack',
label: 'Corepack',
status: 'warn',
detail: 'spawn corepack ENOENT',
fix: 'Run: corepack enable',
group: 'toolchain',
2026-05-10 23:12:26 +02:00
});
expect(testIo.stdout()).toContain('⚠ Corepack: spawn corepack ENOENT');
2026-05-10 23:12:26 +02:00
expect(testIo.stderr()).toBe('');
});
});
2026-05-10 23:51:24 +02:00
describe('runKtxDoctor', () => {
2026-05-10 23:12:26 +02:00
let tempDir: string;
beforeEach(async () => {
2026-05-10 23:51:24 +02:00
tempDir = await mkdtemp(join(tmpdir(), 'ktx-doctor-'));
2026-05-10 23:12:26 +02:00
});
afterEach(async () => {
await rm(tempDir, { recursive: true, force: true });
});
it('prints setup report and exits nonzero when a check fails', async () => {
const testIo = makeIo();
await expect(
2026-05-10 23:51:24 +02:00
runKtxDoctor(
2026-05-10 23:12:26 +02:00
{ command: 'setup', outputMode: 'plain', inputMode: 'disabled' },
testIo.io,
{
runSetupChecks: async () => [
{ id: 'node', label: 'Node 22+', status: 'pass', detail: 'v22.16.0 ABI 127' },
{
id: 'package-build',
label: 'TypeScript package build',
status: 'fail',
detail: 'Missing packages/cli/dist/bin.js',
fix: 'Run: pnpm run build',
},
],
},
),
).resolves.toBe(1);
expect(testIo.stdout()).toContain('KTX status');
expect(testIo.stdout()).toContain('No project here yet.');
expect(testIo.stdout()).toContain('Before you can run');
expect(testIo.stdout()).toContain('✗ TypeScript package build: Missing packages/cli/dist/bin.js');
expect(testIo.stdout()).toContain('→ Run: pnpm run build');
2026-05-10 23:12:26 +02:00
expect(testIo.stderr()).toBe('');
});
it('leads with `ktx setup` and hides toolchain warnings when no project exists', async () => {
const testIo = makeIo();
await expect(
runKtxDoctor(
{ command: 'setup', outputMode: 'plain', inputMode: 'disabled' },
testIo.io,
{
runSetupChecks: async () => [
{ id: 'node', label: 'Node 22+', status: 'pass', detail: 'v22.16.0', group: 'toolchain' },
{
id: 'corepack',
label: 'Corepack',
status: 'warn',
detail: 'spawn corepack ENOENT',
fix: 'Run: corepack enable',
group: 'toolchain',
},
],
},
),
).resolves.toBe(0);
const out = testIo.stdout();
expect(out).toContain('No project here yet.');
expect(out).toContain('Run');
expect(out).toContain('ktx setup');
expect(out).not.toContain('Corepack');
expect(out).not.toContain('Node 22+');
});
2026-05-10 23:12:26 +02:00
it('prints JSON setup report', async () => {
const testIo = makeIo();
await expect(
2026-05-10 23:51:24 +02:00
runKtxDoctor(
2026-05-10 23:12:26 +02:00
{ command: 'setup', outputMode: 'json', inputMode: 'disabled' },
testIo.io,
{
runSetupChecks: async () => [
{ id: 'node', label: 'Node 22+', status: 'pass', detail: 'v22.16.0 ABI 127' },
],
},
),
).resolves.toBe(0);
expect(JSON.parse(testIo.stdout())).toEqual({
title: 'KTX status',
2026-05-10 23:12:26 +02:00
checks: [{ id: 'node', label: 'Node 22+', status: 'pass', detail: 'v22.16.0 ABI 127' }],
});
});
2026-05-10 23:51:24 +02:00
it('runs project checks against a valid ktx.yaml', async () => {
process.env.ANTHROPIC_API_KEY = 'test-key';
2026-05-10 23:12:26 +02:00
await writeFile(
2026-05-10 23:51:24 +02:00
join(tempDir, 'ktx.yaml'),
2026-05-10 23:12:26 +02:00
[
'project: warehouse',
'connections:',
' warehouse:',
' driver: sqlite',
' path: ./warehouse.db',
'llm:',
' provider:',
' backend: anthropic',
' models:',
' default: claude-sonnet-4-5',
2026-05-10 23:12:26 +02:00
'ingest:',
' adapters:',
' - live-database',
' embeddings:',
' backend: openai',
' model: text-embedding-3-small',
' dimensions: 1536',
2026-05-10 23:12:26 +02:00
'',
].join('\n'),
'utf-8',
);
process.env.OPENAI_API_KEY = 'test-key';
2026-05-10 23:12:26 +02:00
const testIo = makeIo();
await expect(
2026-05-10 23:51:24 +02:00
runKtxDoctor(
2026-05-10 23:12:26 +02:00
{ command: 'project', projectDir: tempDir, outputMode: 'plain', inputMode: 'disabled' },
testIo.io,
{},
2026-05-10 23:12:26 +02:00
),
).resolves.toBe(0);
const out = testIo.stdout();
expect(out).toContain('KTX status');
expect(out).toContain('· warehouse');
expect(out).toContain('Connections (1)');
expect(out).toContain('LLM');
expect(out).toContain('anthropic');
expect(out).toContain('Embeddings');
expect(out).toContain('Ready.');
delete process.env.ANTHROPIC_API_KEY;
delete process.env.OPENAI_API_KEY;
2026-05-10 23:12:26 +02:00
});
it('returns blocked verdict when LLM is not configured', async () => {
2026-05-10 23:12:26 +02:00
await writeFile(
2026-05-10 23:51:24 +02:00
join(tempDir, 'ktx.yaml'),
2026-05-10 23:12:26 +02:00
[
'project: warehouse',
'connections:',
' warehouse:',
' driver: sqlite',
' path: ./warehouse.db',
2026-05-10 23:12:26 +02:00
'',
].join('\n'),
'utf-8',
);
const testIo = makeIo();
await expect(
2026-05-10 23:51:24 +02:00
runKtxDoctor(
2026-05-10 23:12:26 +02:00
{ command: 'project', projectDir: tempDir, outputMode: 'plain', inputMode: 'disabled' },
testIo.io,
{},
2026-05-10 23:12:26 +02:00
),
).resolves.toBe(1);
2026-05-10 23:12:26 +02:00
expect(testIo.stdout()).toContain('no LLM configured');
expect(testIo.stdout()).toContain('ktx setup');
2026-05-10 23:12:26 +02:00
});
it('warns when semantic-search embeddings are not configured', async () => {
process.env.ANTHROPIC_API_KEY = 'test-key';
await writeFile(
join(tempDir, 'ktx.yaml'),
[
'project: warehouse',
'connections:',
' warehouse:',
' driver: sqlite',
' path: ./warehouse.db',
'llm:',
' provider:',
' backend: anthropic',
'ingest:',
' adapters:',
' - live-database',
' embeddings:',
' backend: deterministic',
' model: deterministic',
' dimensions: 8',
'',
].join('\n'),
'utf-8',
2026-05-10 23:12:26 +02:00
);
const testIo = makeIo();
await expect(
2026-05-10 23:51:24 +02:00
runKtxDoctor(
2026-05-10 23:12:26 +02:00
{ command: 'project', projectDir: tempDir, outputMode: 'plain', inputMode: 'disabled' },
testIo.io,
{},
2026-05-10 23:12:26 +02:00
),
).resolves.toBe(0);
expect(testIo.stdout()).toContain('Embeddings');
expect(testIo.stdout()).toContain('deterministic');
expect(testIo.stdout()).toContain('semantic search degraded');
delete process.env.ANTHROPIC_API_KEY;
2026-05-10 23:12:26 +02:00
});
});