import test from 'node:test'; import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import path from 'node:path'; import { makeConfig, tempDir, writeCard } from './helpers.mjs'; const cli = path.join(import.meta.dirname, '..', 'src', 'cli.ts'); function fixture(options = {}) { const root = tempDir(); const backlog = path.join(root, 'backlog'); writeCard(backlog, { id: 'T-1', title: 'Контроль жизненного цикла задач трекера', description: 'Задачи накапливаются, и дубликаты не видно.', }); writeCard(backlog, { id: 'T-2', title: 'Контроль жизненного цикла задач трекера', description: 'Задачи накапливаются, и дубликаты не видно.', }); writeCard(backlog, { id: 'T-3', title: 'Сверка контрольных сумм доказательств в отчётах', description: 'Отчёты записывают SHA-256, сумму надо сверять с фактическими байтами файла.', }); writeCard(backlog, { id: 'T-4', title: 'Настроить резервное копирование каталога результатов', description: 'Выводы копируются на внешний носитель.', status: 'Done', }); return makeConfig(root, { dimensions: 64, ...options }); } function run(configPath, ...args) { const proc = spawnSync(process.execPath, [cli, ...args, '--config', configPath], { encoding: 'utf8', }); return { code: proc.status, stdout: proc.stdout, json: () => JSON.parse(proc.stdout) }; } test('index sync builds the index and reports counters', () => { const { configPath } = fixture(); const result = run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); assert.equal(result.code, 0); const envelope = result.json(); assert.equal(envelope.ok, true); assert.equal(envelope.data.cards, 4); assert.equal(envelope.data.embedded, 4); assert.equal(envelope.data.metadataOnly, 0); assert.equal(envelope.data.removed, 0); }); test('a second sync reuses stored embeddings and reports zero requests', () => { const { configPath } = fixture(); run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); const again = run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); const data = again.json().data; assert.equal(data.embedded, 0); assert.equal(data.reused, 4); assert.equal(data.requests, 0); }); test('index status reports provider, schema and reuse numbers', () => { const { configPath } = fixture(); run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); const result = run(configPath, 'index', 'status', '--json'); assert.equal(result.code, 0); const data = result.json().data; assert.equal(data.cards, 4); assert.equal(data.stale, 0); assert.equal(data.missingFromIndex, 0); assert.equal(data.modelId, 'mock-hash-v1'); assert.equal(data.dimensions, 64); assert.equal(data.indexVersion, 1); }); test('index status works without the provider flag because the config selects mock', () => { const { configPath } = fixture(); run(configPath, 'index', 'sync', '--json'); const result = run(configPath, 'index', 'status', '--json'); assert.equal(result.code, 0); assert.equal(result.json().data.cards, 4); }); test('similar returns neighbours of a stored card without the card itself', () => { const { configPath } = fixture(); run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); const result = run(configPath, 'similar', 'T-1', '--top-k', '3', '--json'); assert.equal(result.code, 0); const hits = result.json().data.hits; assert.ok(hits.length > 0); assert.equal( hits.some((hit) => hit.id === 'T-1'), false, ); assert.equal(hits[0].id, 'T-2'); assert.equal(hits[0].signal, 'SEM001'); for (const hit of hits) { assert.ok( hit.signal === null || typeof hit.signal === 'string', 'каждая находка несёт категорию сигнала', ); assert.ok( typeof hit.title === 'string' && typeof hit.status === 'string' && typeof hit.path === 'string', ); } }); test('similar on an unknown identifier is a usage error', () => { const { configPath } = fixture(); run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); const result = run(configPath, 'similar', 'T-99', '--json'); assert.equal(result.code, 2); assert.equal(result.json().error.code, 'NOT_FOUND'); }); test('search embeds an unseen query text', () => { const { configPath } = fixture(); run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); const result = run( configPath, 'search', 'Сверка SHA-256 доказательств в отчётах', '--top-k', '2', '--json', ); assert.equal(result.code, 0); const hits = result.json().data.hits; assert.equal(hits[0].id, 'T-3'); assert.ok(hits[0].signal === null || typeof hits[0].signal === 'string'); }); test('search without a query is a usage error', () => { const { configPath } = fixture(); run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); assert.equal(run(configPath, 'search', '--json').code, 2); }); test('duplicates lists candidate pairs above the threshold', () => { const { configPath } = fixture(); run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); const result = run(configPath, 'duplicates', '--threshold', '0.9', '--json'); assert.equal(result.code, 0); const pairs = result.json().data.pairs; assert.deepEqual( pairs.map((pair) => [pair.left, pair.right]), [['T-1', 'T-2']], ); assert.equal(pairs[0].signal, 'SEM001'); const none = run(configPath, 'duplicates', '--threshold', '1.01', '--json'); assert.deepEqual(none.json().data.pairs, []); }); test('a parent and its own subtask carry no duplicate signal in similar output', () => { const root = tempDir(); const backlog = path.join(root, 'backlog'); writeCard(backlog, { id: 'T-6', title: 'Построить индекс бэклога', description: 'Карточки читаются, векторы хранятся, поиск локальный.', }); writeCard(backlog, { id: 'T-7', title: 'Построить индекс бэклога', description: 'Карточки читаются, векторы хранятся, поиск локальный.', parent: 'T-6', }); const { configPath } = makeConfig(root, { dimensions: 64 }); run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); const hits = run(configPath, 'similar', 'T-6', '--json').json().data.hits; const child = hits.find((hit) => hit.id === 'T-7'); assert.ok(child !== undefined); assert.ok(child.score > 0.99, 'содержание идентично, сходство близко к единице'); assert.equal(child.signal, null, 'структурное включение не сигнал дубликата'); }); test('lint exits with findings when the deterministic layer sees a duplicate', () => { const { configPath } = fixture(); const result = run(configPath, 'lint', '--json'); assert.equal(result.code, 1); const data = result.json().data; assert.equal(data.semantic, false); assert.ok(data.diagnostics.some((item) => item.rule === 'DUP001')); }); test('lint --semantic uses the index and stays offline with the mock provider', () => { const { configPath } = fixture(); const before = run(configPath, 'lint', '--semantic', '--json'); assert.equal(before.json().data.semantic_unavailable, true); run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); const after = run(configPath, 'lint', '--semantic', '--json'); const data = after.json().data; assert.equal(data.semantic, true); assert.equal(data.semantic_unavailable, false); assert.ok(data.diagnostics.some((item) => item.rule === 'SEM001')); }); test('lint text output is human readable and not JSON', () => { const { configPath } = fixture(); const result = run(configPath, 'lint'); assert.equal(result.code, 1); assert.ok(result.stdout.includes('DUP001')); assert.throws(() => JSON.parse(result.stdout)); }); test('metrics reports coverage and reuse of stored embeddings', () => { const { configPath } = fixture(); run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); const result = run(configPath, 'metrics', '--json'); assert.equal(result.code, 0); const data = result.json().data; assert.equal(data.cards, 4); assert.equal(data.lastRun.embedded, 4); assert.ok(data.sizeBytes > 0); }); test('audit reserves exit code three for the unimplemented L2 layer', () => { const { configPath } = fixture(); const result = run(configPath, 'audit', '--duplicates', '--json'); assert.equal(result.code, 3); assert.equal(result.json().error.code, 'NOT_IMPLEMENTED'); }); test('unknown flags and commands are usage errors', () => { const { configPath } = fixture(); assert.equal(run(configPath, 'lint', '--bogus').code, 2); assert.equal(run(configPath, 'frobnicate').code, 2); const proc = spawnSync(process.execPath, [cli], { encoding: 'utf8' }); assert.equal(proc.status, 2); assert.ok(proc.stdout.includes('bidx ')); }); test('a configured provider without an api key fails instead of guessing', () => { const { configPath } = fixture({ providerKind: 'openai-compatible', endpoint: 'https://example.invalid/v1', model: 'some-model', apiKeySources: [{ kind: 'env', name: 'BIDX_DEFINITELY_UNSET' }], }); const result = run(configPath, 'index', 'sync', '--json'); assert.equal(result.code, 4); assert.equal(result.json().error.code, 'API_KEY_MISSING'); }); test('a missing configuration file is reported as a configuration error', () => { const root = tempDir(); const proc = spawnSync( process.execPath, [cli, 'metrics', '--json', '--config', path.join(root, 'none.json')], { encoding: 'utf8', }, ); assert.equal(proc.status, 4); assert.equal(JSON.parse(proc.stdout).error.code, 'CONFIG_MISSING'); }); test('the same command produces byte-identical output twice', () => { const { configPath } = fixture(); run(configPath, 'index', 'sync', '--provider', 'mock', '--json'); const first = run(configPath, 'duplicates', '--threshold', '0.5', '--json'); const second = run(configPath, 'duplicates', '--threshold', '0.5', '--json'); assert.equal(first.stdout, second.stdout); const firstLint = run(configPath, 'lint', '--semantic', '--json'); const secondLint = run(configPath, 'lint', '--semantic', '--json'); assert.equal(firstLint.stdout, secondLint.stdout); }); test('commands that need an index fail with a clear error when it is absent', () => { const { configPath } = fixture(); const result = run(configPath, 'similar', 'T-1', '--json'); assert.equal(result.code, 4); assert.equal(result.json().error.code, 'INDEX_MISSING'); });