Эксперимент backlog-index: семантический индекс бэклога с отдельным CLI bidx (BHL-077.02…BHL-077.07)

This commit is contained in:
Suslov-MD
2026-12-01 07:48:20 +03:00
parent 84e2b57b3c
commit 4f4791f990
31 changed files with 8181 additions and 0 deletions
@@ -0,0 +1,91 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { readCards } from '../src/reader.ts';
const root = path.resolve(import.meta.dirname, '..', '..', '..');
const backlogDir = path.join(root, 'backlog');
const backlogBin = path.join(root, 'node_modules', '.bin', 'backlog');
function trackerList() {
return spawnSync(backlogBin, ['task', 'list', '--json'], { cwd: root, encoding: 'utf8' });
}
test('the card reader parses every live tracker file', { skip: !existsSync(backlogDir) }, () => {
const read = readCards({ repoRoot: root, backlogDir });
assert.deepEqual(read.errors, []);
assert.ok(read.cards.length > 10);
for (const card of read.cards) {
assert.ok(card.id !== '');
assert.ok(card.title !== '');
assert.ok(card.path.startsWith('backlog/'));
assert.match(card.fileHash, /^[0-9a-f]{64}$/u);
}
});
test(
'the reader sees the same cards and fields as the tracker CLI',
{ skip: !existsSync(backlogBin) },
() => {
const proc = trackerList();
assert.equal(proc.status, 0, `backlog task list не запустился: ${proc.stderr}`);
const listed = JSON.parse(proc.stdout).tasks;
const read = readCards({ repoRoot: root, backlogDir });
const byId = new Map(read.cards.map((card) => [card.id, card]));
const listedIds = new Set(listed.map((task) => task.id));
const readIds = new Set(read.cards.filter((card) => !card.archived).map((card) => card.id));
assert.deepEqual(
[...listedIds].sort(),
[...readIds].sort(),
'набор карточек в файлах расходится с набором трекера',
);
for (const task of listed) {
const card = byId.get(task.id);
assert.notEqual(card, undefined, `карточка ${task.id} не прочитана из файла`);
assert.equal(card.title, task.title, `заголовок ${task.id} расходится`);
assert.equal(card.status, task.status, `статус ${task.id} расходится`);
assert.deepEqual(card.labels, task.labels ?? [], `метки ${task.id} расходятся`);
assert.deepEqual(
card.dependencies,
task.dependencies ?? [],
`зависимости ${task.id} расходятся`,
);
assert.equal(card.milestone, task.milestone ?? null, `веха ${task.id} расходится`);
assert.equal(card.parentId, task.parentTaskId ?? null, `родитель ${task.id} расходится`);
assert.equal(card.project, task.project ?? null, `проект ${task.id} расходится`);
assert.equal(
card.acceptanceCriteria.length,
task.acceptanceCriteriaCount,
`число критериев ${task.id} расходится`,
);
}
},
);
test(
'the reader keeps Done cards so repeats of past work stay visible',
{
skip: !existsSync(backlogDir),
},
() => {
const read = readCards({ repoRoot: root, backlogDir });
assert.ok(read.cards.some((card) => card.status === 'Done'));
const archivedOnDisk = read.cards.filter((card) => card.archived);
if (archivedOnDisk.length > 0) {
assert.ok(archivedOnDisk.every((card) => card.path.startsWith('backlog/archive/')));
}
},
);
test('reading the tracker does not change any file', { skip: !existsSync(backlogDir) }, () => {
const before = readCards({ repoRoot: root, backlogDir });
readCards({ repoRoot: root, backlogDir });
const after = readCards({ repoRoot: root, backlogDir });
assert.deepEqual(
before.cards.map((card) => [card.id, card.fileHash]),
after.cards.map((card) => [card.id, card.fileHash]),
);
});
@@ -0,0 +1,280 @@
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 <command>'));
});
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');
});
@@ -0,0 +1,168 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { createMockProvider } from '../src/provider.ts';
import { loadConfig } from '../src/config.ts';
import { buildCorpus, runEval } from '../src/eval.ts';
import { makeConfig, tempDir } from './helpers.mjs';
const provider = createMockProvider(128);
function syntheticSet() {
return {
version: 1,
cards: [
{
id: 'E-1',
source: 'inline',
title: 'Сверка контрольных сумм доказательств в отчётах',
description: 'Отчёты записывают SHA-256, сумму надо сверять с фактическими байтами файла.',
acceptanceCriteria: ['Сумма сверяется с файлом', 'Расхождение останавливает проверку'],
},
{
id: 'E-2',
source: 'inline',
title: 'Сверить контрольные суммы доказательств в отчётах с реальными файлами',
description: 'Отчёты записывают SHA-256, сумму надо сверять с фактическими байтами файла.',
acceptanceCriteria: ['Сумма сверяется с файлом', 'Расхождение останавливает проверку'],
},
{
id: 'E-3',
source: 'inline',
title: 'Настроить резервное копирование каталога результатов',
description:
'Выводы копируются на внешний носитель, чтобы они не терялись при отказе диска.',
},
],
pairs: [
{ a: 'E-1', b: 'E-2', label: 'duplicate' },
{ a: 'E-1', b: 'E-3', label: 'unrelated' },
{ a: 'E-2', b: 'E-3', label: 'unrelated' },
],
queries: [{ text: 'сверить SHA-256 доказательств в отчётах', relevant: ['E-1', 'E-2'] }],
};
}
test('inline eval cards keep description and acceptance criteria', () => {
const root = tempDir();
const config = loadConfig(makeConfig(root, { dimensions: 128 }).configPath);
const corpus = buildCorpus(syntheticSet(), config);
assert.deepEqual(corpus.errors, []);
const card = corpus.cards.find((item) => item.id === 'E-1');
assert.ok(card.description.includes('SHA-256'));
assert.equal(card.acceptanceCriteria.length, 2);
});
test('missing backlog cards are reported instead of silently dropped', () => {
const root = tempDir();
const config = loadConfig(makeConfig(root, { dimensions: 128 }).configPath);
const corpus = buildCorpus(
{ version: 1, cards: [{ id: 'X-1', source: 'backlog' }], pairs: [], queries: [] },
config,
);
assert.equal(corpus.cards.length, 0);
assert.equal(corpus.errors.length, 1);
});
test('evaluation scores labelled pairs and sweeps calibration thresholds', async () => {
const root = tempDir();
const config = loadConfig(makeConfig(root, { dimensions: 128 }).configPath);
const report = await runEval(syntheticSet(), provider, config, { topK: 2 });
assert.equal(report.cards, 3);
assert.equal(report.pairs.length, 3);
const duplicate = report.pairs.find((pair) => pair.label === 'duplicate');
const unrelated = report.pairs.filter((pair) => pair.label === 'unrelated');
assert.ok(duplicate.score > Math.max(...unrelated.map((pair) => pair.score)));
assert.equal(report.boundaries.length, 3);
for (const boundary of report.boundaries) {
assert.equal(boundary.curve.length, 50);
assert.ok(boundary.best.threshold >= 0.5 && boundary.best.threshold <= 0.99);
assert.ok(boundary.best.f1 > 0);
}
const duplicateBoundary = report.boundaries.find((item) => item.boundary === 'duplicate');
assert.ok(duplicateBoundary.best.precision === 1);
assert.ok(duplicateBoundary.best.recall === 1);
});
test('evaluation reports query precision and recall at k', async () => {
const root = tempDir();
const config = loadConfig(makeConfig(root, { dimensions: 128 }).configPath);
const report = await runEval(syntheticSet(), provider, config, { topK: 2 });
assert.equal(report.queries.length, 1);
const query = report.queries[0];
assert.equal(query.recall, 1);
assert.equal(query.precision, 1);
assert.deepEqual(
query.hits
.map((hit) => hit.id)
.slice(0, 2)
.sort(),
['E-1', 'E-2'],
);
assert.equal(report.averages.recallAtK, 1);
});
test('evaluation can skip query ranking for a calibration-only run', async () => {
const root = tempDir();
const config = loadConfig(makeConfig(root, { dimensions: 128 }).configPath);
const report = await runEval(syntheticSet(), provider, config, { topK: 2, queries: false });
assert.deepEqual(report.queries, []);
assert.equal(report.averages.precisionAtK, null);
assert.equal(report.boundaries.length, 3);
});
test('the shipped eval set is internally consistent', () => {
const file = path.join(import.meta.dirname, '..', 'eval', 'labels.json');
const set = JSON.parse(readFileSync(file, 'utf8'));
const ids = new Set(set.cards.map((card) => card.id));
assert.equal(ids.size, set.cards.length);
for (const pair of set.pairs) {
assert.ok(ids.has(pair.a), `pair ${pair.a} отсутствует в списке карточек`);
assert.ok(ids.has(pair.b), `pair ${pair.b} отсутствует в списке карточек`);
assert.ok(['duplicate', 'overlap', 'related', 'unrelated'].includes(pair.label));
assert.notEqual(pair.a, pair.b);
}
const keys = new Set(set.pairs.map((pair) => [pair.a, pair.b].sort().join('|')));
assert.equal(keys.size, set.pairs.length);
for (const query of set.queries) {
assert.ok(query.id !== undefined || typeof query.text === 'string');
if (query.id !== undefined) {
assert.ok(ids.has(query.id));
}
for (const relevant of query.relevant) {
assert.ok(ids.has(relevant), `relevant ${relevant} отсутствует в списке карточек`);
}
}
const labels = new Set(set.pairs.map((pair) => pair.label));
for (const expected of ['duplicate', 'overlap', 'related', 'unrelated']) {
assert.ok(labels.has(expected), `в наборе нет метки ${expected}`);
}
});
test('the shipped eval set references real backlog cards', () => {
const file = path.join(import.meta.dirname, '..', 'eval', 'labels.json');
const set = JSON.parse(readFileSync(file, 'utf8'));
const root = path.resolve(import.meta.dirname, '..', '..', '..');
const backlogDir = path.join(root, 'backlog');
const cards = set.cards.filter((card) => card.source === 'backlog').map((card) => card.id);
const listing = (directory) => {
try {
return readdirSync(directory, { encoding: 'utf8' });
} catch {
return [];
}
};
const files = [
...listing(path.join(backlogDir, 'tasks')),
...listing(path.join(backlogDir, 'archive', 'tasks')),
].map((name) => name.toLowerCase());
for (const id of cards) {
const prefix = id.toLowerCase();
assert.ok(
files.some((name) => name.startsWith(prefix)),
`карточка ${id} не найдена в бэклоге`,
);
}
});
+163
View File
@@ -0,0 +1,163 @@
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
export function tempDir(prefix = 'bidx-') {
return mkdtempSync(path.join(os.tmpdir(), prefix));
}
/** Minimal card writer producing the tracker's own on-disk format. */
export function writeCard(backlogDir, spec) {
const lines = [
'---',
`id: ${spec.id}`,
`title: ${spec.title}`,
`status: ${spec.status ?? 'To Do'}`,
'assignee: []',
`created_date: '${spec.createdDate ?? '2026-11-30T00:00:00Z'}'`,
`labels: [${(spec.labels ?? []).map((label) => JSON.stringify(label)).join(', ')}]`,
`milestone: ${spec.milestone ?? 'm-1'}`,
`parent_task_id: ${spec.parent ?? 'none'}`,
`dependencies: [${(spec.dependencies ?? []).join(', ')}]`,
`priority: ${spec.priority ?? 'medium'}`,
`project: ${spec.project ?? 'lab'}`,
`ordinal: ${spec.ordinal ?? 1000}`,
...(spec.type === undefined ? [] : [`type: ${spec.type}`]),
'---',
'',
'## Description',
'',
'<!-- SECTION:DESCRIPTION:BEGIN -->',
spec.description ?? '',
'<!-- SECTION:DESCRIPTION:END -->',
'',
];
if (spec.acceptanceCriteria !== undefined && spec.acceptanceCriteria.length > 0) {
lines.push('## Acceptance Criteria', '<!-- AC:BEGIN -->');
spec.acceptanceCriteria.forEach((item, index) => {
const checked = item.checked === true ? 'x' : ' ';
lines.push(`- [${checked}] #${String(index + 1)} ${item.text}`);
});
lines.push('<!-- AC:END -->', '');
}
lines.push('## Definition of Done', '<!-- DOD:BEGIN -->');
for (const item of spec.definitionOfDone ?? ['Общая Definition of Done лаборатории']) {
lines.push(`- [ ] #1 ${item}`);
}
lines.push('<!-- DOD:END -->', '');
if (spec.comments !== undefined) {
lines.push(
'## Comments',
'<!-- COMMENTS:BEGIN -->',
spec.comments,
'<!-- COMMENTS:END -->',
'',
);
}
if (spec.notes !== undefined) {
lines.push(
'## Implementation Notes',
'<!-- SECTION:NOTES:BEGIN -->',
spec.notes,
'<!-- SECTION:NOTES:END -->',
'',
);
}
const directory =
spec.archived === true
? path.join(backlogDir, 'archive', 'tasks')
: path.join(backlogDir, 'tasks');
mkdirSync(directory, { recursive: true });
const file = path.join(directory, `${spec.id.toLowerCase()}.md`);
writeFileSync(file, lines.join('\n'), 'utf8');
return file;
}
export function writeRawCard(backlogDir, id, text, archived = false) {
const directory = archived
? path.join(backlogDir, 'archive', 'tasks')
: path.join(backlogDir, 'tasks');
mkdirSync(directory, { recursive: true });
const file = path.join(directory, `${id.toLowerCase()}.md`);
writeFileSync(file, text, 'utf8');
return file;
}
export function readText(file) {
return readFileSync(file, 'utf8');
}
export function makeConfig(root, options = {}) {
const config = {
repoRoot: root,
backlogDir: path.join(root, 'backlog'),
indexFile: path.join(root, 'index.sqlite'),
topK: options.topK ?? 10,
provider: {
kind: options.providerKind ?? 'mock',
endpoint: options.endpoint ?? '',
model: options.model ?? 'mock-hash-v1',
dimensions: options.dimensions ?? 64,
batchSize: options.batchSize ?? 4,
timeoutMs: 1000,
retries: options.retries ?? 2,
concurrency: options.concurrency ?? 2,
retryDelayMs: 1,
apiKeySources: options.apiKeySources ?? [{ kind: 'env', name: 'BIDX_TEST_KEY' }],
},
thresholds: options.thresholds ?? { duplicate: 0.9, overlap: 0.8, related: 0.7 },
statusClasses: options.statusClasses ?? {
active: ['To Do', 'In Progress'],
done: ['Done'],
skipped: [],
},
};
const file = path.join(root, 'config.json');
writeFileSync(file, JSON.stringify(config, null, 2), 'utf8');
return { configPath: file, config };
}
export function fakeTransport(handler) {
const calls = [];
let inFlight = 0;
let maxInFlight = 0;
const transport = async (request) => {
calls.push(request);
inFlight += 1;
maxInFlight = Math.max(maxInFlight, inFlight);
try {
return await handler(request, calls.length);
} finally {
inFlight -= 1;
}
};
return {
transport,
calls,
get maxInFlight() {
return maxInFlight;
},
};
}
export function embeddingsResponse(vectors, model = 'test-model') {
return {
status: 200,
body: JSON.stringify({
model,
data: vectors.map((vector, index) => ({ index, embedding: vector })),
usage: { prompt_tokens: 10 },
}),
};
}
export function vector(seed, dimensions) {
const out = [];
let value = seed;
for (let index = 0; index < dimensions; index += 1) {
value = (value * 1103515245 + 12345) % 2147483648;
out.push((value % 1000) / 1000 - 0.5);
}
const norm = Math.sqrt(out.reduce((sum, item) => sum + item * item, 0));
return out.map((item) => item / norm);
}
@@ -0,0 +1,265 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { rmSync } from 'node:fs';
import path from 'node:path';
import { createMockProvider, ProviderError } from '../src/provider.ts';
import { runIndex } from '../src/index-manager.ts';
import { loadConfig } from '../src/config.ts';
import { openStore } from '../src/store.ts';
import { readCards } from '../src/reader.ts';
import { makeConfig, tempDir, writeCard } from './helpers.mjs';
function setup(options = {}) {
const root = tempDir();
const written = makeConfig(root, options);
const config = loadConfig(written.configPath);
const store = openStore({ file: config.indexFile });
return { root, config, store, backlog: path.join(root, 'backlog') };
}
function countingProvider(dimensions = 64) {
const inner = createMockProvider(dimensions);
const state = { texts: 0, calls: 0 };
return {
provider: {
id: inner.id,
model: inner.model,
dimensions: inner.dimensions,
embed: async (texts) => {
state.calls += 1;
state.texts += texts.length;
return await inner.embed(texts);
},
},
state,
};
}
function seedCards(backlog) {
writeCard(backlog, {
id: 'T-1',
title: 'Контроль жизненного цикла задач',
description: 'Задачи накапливаются.',
});
writeCard(backlog, {
id: 'T-2',
title: 'Сверка контрольных сумм доказательств',
description: 'Отчёты записывают SHA-256.',
});
writeCard(backlog, {
id: 'T-3',
title: 'Публикация продуктов лаборатории',
description: 'Публикация по решению владельца.',
});
}
test('initial indexing embeds every card once', async () => {
const { config, store, backlog } = setup();
seedCards(backlog);
const { provider, state } = countingProvider(64);
const result = await runIndex({ kind: 'sync', config, provider, store });
assert.equal(result.cards, 3);
assert.equal(result.embedded, 3);
assert.equal(result.reused, 0);
assert.equal(state.texts, 3);
assert.equal(store.loadCards().length, 3);
store.close();
});
test('re-indexing unchanged cards performs no provider request', async () => {
const { config, store, backlog } = setup();
seedCards(backlog);
const first = countingProvider(64);
await runIndex({ kind: 'sync', config, provider: first.provider, store });
const second = countingProvider(64);
const result = await runIndex({ kind: 'sync', config, provider: second.provider, store });
assert.equal(result.embedded, 0);
assert.equal(result.reused, 3);
assert.equal(second.state.calls, 0);
store.close();
});
test('a status change refreshes metadata without re-embedding', async () => {
const { config, store, backlog } = setup();
seedCards(backlog);
const first = countingProvider(64);
await runIndex({ kind: 'sync', config, provider: first.provider, store });
writeCard(backlog, {
id: 'T-1',
title: 'Контроль жизненного цикла задач',
status: 'Done',
description: 'Задачи накапливаются.',
});
const second = countingProvider(64);
const result = await runIndex({ kind: 'sync', config, provider: second.provider, store });
assert.equal(result.metadataOnly, 1);
assert.equal(result.embedded, 0);
assert.equal(second.state.calls, 0);
assert.equal(store.loadCard('T-1').metadata.status, 'Done');
store.close();
});
test('checking an acceptance criterion refreshes metadata only', async () => {
const { config, store, backlog } = setup();
writeCard(backlog, {
id: 'T-1',
title: 'Критерии приёмки',
description: 'Описание',
acceptanceCriteria: [{ text: 'Первый' }, { text: 'Второй' }],
});
const first = countingProvider(64);
await runIndex({ kind: 'sync', config, provider: first.provider, store });
writeCard(backlog, {
id: 'T-1',
title: 'Критерии приёмки',
description: 'Описание',
acceptanceCriteria: [{ text: 'Первый', checked: true }, { text: 'Второй' }],
});
const second = countingProvider(64);
const result = await runIndex({ kind: 'sync', config, provider: second.provider, store });
assert.equal(result.metadataOnly, 1);
assert.equal(second.state.calls, 0);
store.close();
});
test('a wording change re-embeds only the changed card', async () => {
const { config, store, backlog } = setup();
seedCards(backlog);
const first = countingProvider(64);
await runIndex({ kind: 'sync', config, provider: first.provider, store });
writeCard(backlog, {
id: 'T-2',
title: 'Сверка контрольных сумм доказательств',
description: 'Сумма должна совпадать с байтами файла.',
});
const second = countingProvider(64);
const result = await runIndex({ kind: 'sync', config, provider: second.provider, store });
assert.equal(result.embedded, 1);
assert.equal(second.state.texts, 1);
store.close();
});
test('a removed card drops its index row and nothing else', async () => {
const { config, store, backlog } = setup();
seedCards(backlog);
const provider = countingProvider(64);
await runIndex({ kind: 'sync', config, provider: provider.provider, store });
rmSync(path.join(backlog, 'tasks', 't-2.md'));
const result = await runIndex({ kind: 'sync', config, provider: provider.provider, store });
assert.equal(result.removed, 1);
assert.equal(store.loadCards().length, 2);
assert.equal(store.loadCard('T-2'), undefined);
store.close();
});
test('switching the embedding model invalidates and re-embeds stored vectors', async () => {
const { config, store, backlog } = setup();
seedCards(backlog);
const first = countingProvider(64);
await runIndex({ kind: 'sync', config, provider: first.provider, store });
const second = countingProvider(32);
const result = await runIndex({ kind: 'sync', config, provider: second.provider, store });
assert.equal(result.embedded, 3);
assert.equal(second.state.texts, 3);
const rows = store.loadCards();
assert.equal(rows[0].dimensions, 32);
assert.equal(
rows.every((row) => row.providerId === second.provider.id),
true,
);
store.close();
});
test('an interrupted run resumes and finishes without re-embedding stored cards', async () => {
const { config, store, backlog } = setup({ batchSize: 1 });
seedCards(backlog);
const inner = createMockProvider(64);
let served = 0;
const failing = {
id: inner.id,
model: inner.model,
dimensions: inner.dimensions,
embed: async (texts) => {
served += 1;
if (served > 2) {
throw new ProviderError('PROVIDER_UNAVAILABLE', 'endpoint упал');
}
return await inner.embed(texts);
},
};
await assert.rejects(() => runIndex({ kind: 'sync', config, provider: failing, store }));
const stored = store.loadCards();
assert.equal(stored.length, 2);
const resume = countingProvider(64);
const result = await runIndex({ kind: 'sync', config, provider: resume.provider, store });
assert.equal(result.embedded, 1);
assert.equal(resume.state.texts, 1);
assert.equal(store.loadCards().length, 3);
store.close();
});
test('rebuild recomputes every vector even when nothing changed', async () => {
const { config, store, backlog } = setup();
seedCards(backlog);
const first = countingProvider(64);
await runIndex({ kind: 'sync', config, provider: first.provider, store });
const second = countingProvider(64);
const result = await runIndex({ kind: 'rebuild', config, provider: second.provider, store });
assert.equal(result.embedded, 3);
assert.equal(second.state.texts, 3);
store.close();
});
test('deleting the index leaves the tracker files untouched', async () => {
const { config, store, backlog } = setup();
seedCards(backlog);
const provider = countingProvider(64);
await runIndex({ kind: 'sync', config, provider: provider.provider, store });
const before = readCards({ repoRoot: config.repoRoot, backlogDir: config.backlogDir });
store.close();
rmSync(config.indexFile, { force: true });
const after = readCards({ repoRoot: config.repoRoot, backlogDir: config.backlogDir });
assert.deepEqual(
before.cards.map((card) => [card.id, card.fileHash]),
after.cards.map((card) => [card.id, card.fileHash]),
);
});
test('concurrent writers and a reader share the index without corruption', async () => {
const { config, store, backlog } = setup();
seedCards(backlog);
const provider = countingProvider(64);
await runIndex({ kind: 'sync', config, provider: provider.provider, store });
const writerA = openStore({ file: config.indexFile, busyTimeoutMs: 4000 });
const writerB = openStore({ file: config.indexFile, busyTimeoutMs: 4000 });
const base = store.loadCard('T-1');
const makeRow = (id, title) => ({ ...base, id, metadata: { ...base.metadata, title } });
writerA.upsertCard(makeRow('A-1', 'Первая'));
writerB.upsertCard(makeRow('B-1', 'Вторая'));
writerA.upsertCard(makeRow('A-2', 'Третья'));
writerB.upsertCard(makeRow('B-2', 'Четвёртая'));
const ids = store.loadCards().map((card) => card.id);
assert.deepEqual(ids, ['A-1', 'A-2', 'B-1', 'B-2', 'T-1', 'T-2', 'T-3']);
writerA.close();
writerB.close();
store.close();
});
test('index metadata records the provider, model and schema versions', async () => {
const { config, store, backlog } = setup();
seedCards(backlog);
const provider = countingProvider(64);
await runIndex({ kind: 'sync', config, provider: provider.provider, store });
const meta = store.meta();
assert.equal(meta.cardCount, 3);
assert.equal(meta.providerId, provider.provider.id);
assert.equal(meta.modelId, 'mock-hash-v1');
assert.equal(meta.dimensions, 64);
assert.equal(meta.normVersion, 1);
assert.equal(meta.indexVersion, 1);
assert.ok(meta.lastSyncAt !== null);
const runs = store.runs(5);
assert.equal(runs[0].embedded, 3);
store.close();
});
@@ -0,0 +1,265 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { createMockProvider } from '../src/provider.ts';
import { runIndex } from '../src/index-manager.ts';
import { loadConfig } from '../src/config.ts';
import { openStore } from '../src/store.ts';
import { deterministicDiagnostics, runLint } from '../src/lint.ts';
import { readCards } from '../src/reader.ts';
import { makeConfig, tempDir, writeCard } from './helpers.mjs';
const provider = createMockProvider(128);
const SKIPPED = { active: ['To Do', 'In Progress'], done: ['Done'], skipped: ['Skipped'] };
function corpus(backlog) {
const shared = 'Задачи накапливаются, и повторы не видно.';
const hashes = 'Отчёты записывают SHA-256, сумму надо сверять с фактическими байтами файла.';
writeCard(backlog, {
id: 'T-1',
title: 'Контроль жизненного цикла задач трекера',
description: shared,
acceptanceCriteria: [
{ text: 'Повторы находятся до записи' },
{ text: 'Карточки не изменяются' },
],
});
writeCard(backlog, {
id: 'T-2',
title: 'Контроль жизненного цикла задач трекера',
description: shared,
acceptanceCriteria: [
{ text: 'Повторы находятся до записи' },
{ text: 'Карточки не изменяются' },
],
});
writeCard(backlog, {
id: 'T-3',
title: 'Сверка контрольных сумм доказательств в отчётах',
description: hashes,
});
writeCard(backlog, {
id: 'T-4',
title: 'Сверить контрольные суммы доказательств в отчётах с реальными файлами',
description: hashes,
});
writeCard(backlog, {
id: 'T-5',
title: 'Настроить резервное копирование каталога результатов',
description: 'Выводы копируются на внешний носитель, чтобы они не терялись при отказе диска.',
});
writeCard(backlog, {
id: 'T-6',
title: 'Добавить диагностику трекера в общий прогон проверок качества',
description: 'Диагностика трекера находит повторяющиеся идентификаторы и циклы зависимостей.',
status: 'Done',
});
writeCard(backlog, {
id: 'T-7',
title: 'Добавить диагностику трекера в общий прогон проверок качества',
description: 'Диагностика трекера находит повторяющиеся идентификаторы и циклы зависимостей.',
});
writeCard(backlog, {
id: 'T-8',
title: 'Отменить эксперимент по кешу спецификаций',
description: 'Кеш загружаемых версий спецификации больше не нужен лаборатории.',
status: 'Skipped',
});
writeCard(backlog, {
id: 'T-9',
title: 'Отменить эксперимент по кешу спецификаций',
description: 'Кеш загружаемых версий спецификации больше не нужен лаборатории.',
});
const nested = 'Копия каталога выводов выводится на внешний носитель по одной команде.';
writeCard(backlog, {
id: 'T-10',
title: 'Настроить резервное копирование каталога выводов',
description: nested,
});
writeCard(backlog, {
id: 'T-11',
title: 'Настроить резервное копирование каталога выводов',
description: nested,
parent: 'T-10',
});
}
async function setup(options = {}, semantic = false) {
const root = tempDir();
const written = makeConfig(root, { dimensions: 128, ...options });
const config = loadConfig(written.configPath);
const backlog = path.join(root, 'backlog');
corpus(backlog);
const store = openStore({ file: config.indexFile });
if (semantic) {
await runIndex({ kind: 'sync', config, provider, store });
}
return { config, store, backlog, root };
}
const rule = (result, name) => result.diagnostics.find((item) => item.rule === name);
const idsOf = (diagnostic) =>
diagnostic === undefined ? [] : diagnostic.findings.map((item) => item.id);
test('deterministic layer reports identical normalized content as an error', async () => {
const { config, store } = await setup();
const result = await runLint({ config, semantic: false, store });
const dup001 = rule(result, 'DUP001');
assert.equal(dup001.level, 'error');
assert.ok(idsOf(dup001).includes('T-1') && idsOf(dup001).includes('T-2'));
assert.equal(result.ok, false);
store.close();
});
test('deterministic layer reports a repeated normalized title as a warning', async () => {
const { config, store } = await setup();
const result = await runLint({ config, semantic: false, store });
const dup002 = rule(result, 'DUP002');
assert.equal(dup002.level, 'warning');
assert.ok(idsOf(dup002).includes('T-1') && idsOf(dup002).includes('T-2'));
assert.ok(!idsOf(dup002).includes('T-3'));
store.close();
});
test('regular lint needs no index and produces no semantic rules', async () => {
const { config, store } = await setup();
const result = await runLint({ config, semantic: false, store });
assert.equal(result.semantic, false);
assert.equal(result.semanticUnavailable, false);
assert.equal(
result.diagnostics.some((item) => item.rule.startsWith('SEM')),
false,
);
store.close();
});
test('deterministic layer works from injected cards without any file access', () => {
const cards = readCards({ repoRoot: '/nonexistent', backlogDir: '/nonexistent' }).cards;
assert.deepEqual(deterministicDiagnostics(cards), []);
});
test('semantic layer flags potential duplicates among active cards', async () => {
const { config, store } = await setup({}, true);
const result = await runLint({ config, semantic: true, store });
const sem001 = rule(result, 'SEM001');
assert.equal(sem001.level, 'warning');
assert.ok(idsOf(sem001).includes('T-1') && idsOf(sem001).includes('T-2'));
assert.equal(result.semantic, true);
store.close();
});
test('semantic layer reports a reworded card as an overlap when below the duplicate threshold', async () => {
const { config, store } = await setup({}, true);
const result = await runLint({ config, semantic: true, store });
const overlap = [rule(result, 'SEM001'), rule(result, 'SEM002')].filter(
(item) => item !== undefined,
);
const flagged = overlap.some(
(item) => idsOf(item).includes('T-3') && idsOf(item).includes('T-4'),
);
assert.equal(flagged, true);
store.close();
});
test('semantic layer separates a repeat of a completed task', async () => {
const { config, store } = await setup({}, true);
const result = await runLint({ config, semantic: true, store });
const sem003 = rule(result, 'SEM003');
assert.equal(sem003.level, 'recommendation');
assert.ok(idsOf(sem003).includes('T-6') && idsOf(sem003).includes('T-7'));
store.close();
});
test('semantic layer separates a repeat of a skipped task', async () => {
const { config, store } = await setup({ statusClasses: SKIPPED }, true);
const result = await runLint({ config, semantic: true, store });
const sem004 = rule(result, 'SEM004');
assert.equal(sem004.level, 'recommendation');
assert.ok(idsOf(sem004).includes('T-8') && idsOf(sem004).includes('T-9'));
store.close();
});
test('semantic findings never turn the lint result into an error', async () => {
const { config, store } = await setup({ statusClasses: SKIPPED }, true);
const withSemantic = await runLint({ config, semantic: true, store });
const semanticRules = withSemantic.diagnostics.filter((item) => item.rule.startsWith('SEM'));
assert.ok(semanticRules.length > 0);
assert.equal(
semanticRules.every((item) => item.level === 'warning' || item.level === 'recommendation'),
true,
);
const withoutSemantic = await runLint({ config, semantic: false, store });
const errorsOnlyFromL0 = (result) =>
result.diagnostics.filter((item) => item.level === 'error').map((item) => item.rule);
assert.deepEqual(errorsOnlyFromL0(withSemantic), errorsOnlyFromL0(withoutSemantic));
store.close();
});
test('a missing index is reported as a stale index diagnostic, not a failure', async () => {
const { config, store } = await setup();
const result = await runLint({ config, semantic: true, store });
assert.equal(result.semanticUnavailable, true);
assert.equal(result.semantic, false);
const sem005 = rule(result, 'SEM005');
assert.equal(sem005.level, 'warning');
store.close();
});
test('cards absent from the index are listed as stale coverage', async () => {
const { config, store, backlog } = await setup({}, true);
writeCard(backlog, {
id: 'T-12',
title: 'Новая карточка после индексации',
description: 'Описание новой карточки.',
});
const result = await runLint({ config, semantic: true, store });
const sem005 = rule(result, 'SEM005');
assert.ok(idsOf(sem005).includes('T-12'));
store.close();
});
test('records incompatible with the index metadata are reported as SEM006', async () => {
const { config, store } = await setup({}, true);
store.setMeta({ provider_id: 'mock:hash-v1:64', model_id: 'other-model', dimensions: '64' });
const result = await runLint({ config, semantic: true, store });
const sem006 = rule(result, 'SEM006');
assert.ok(sem006.findings.length >= 1);
assert.equal(rule(result, 'SEM001'), undefined);
store.close();
});
test('a parent card and its own subtask are not reported as duplicates', async () => {
const { config, store } = await setup({}, true);
const result = await runLint({ config, semantic: true, store });
const semanticIds = result.diagnostics
.filter((item) => item.rule.startsWith('SEM'))
.flatMap((item) => item.findings.map((finding) => finding.id));
assert.equal(semanticIds.includes('T-11'), false);
assert.equal(semanticIds.includes('T-10'), false);
assert.ok(semanticIds.includes('T-1'));
store.close();
});
test('lint output is deterministic for identical input', async () => {
const { config, store } = await setup({ statusClasses: SKIPPED }, true);
const first = await runLint({ config, semantic: true, store });
const second = await runLint({ config, semantic: true, store });
assert.deepEqual(first, second);
store.close();
});
test('lint does not modify tracker files', async () => {
const { config, store, backlog } = await setup({}, true);
const directory = path.join(backlog, 'tasks');
const snapshot = () =>
readdirSync(directory)
.sort()
.map((name) => `${name}:${readFileSync(path.join(directory, name), 'utf8')}`);
const before = snapshot();
await runLint({ config, semantic: true, store });
assert.deepEqual(snapshot(), before);
store.close();
});
@@ -0,0 +1,219 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { writeFileSync } from 'node:fs';
import path from 'node:path';
import {
createMockProvider,
createOpenAICompatibleProvider,
ProviderError,
resolveApiKey,
} from '../src/provider.ts';
import { embeddingsResponse, fakeTransport, tempDir, vector } from './helpers.mjs';
function settings(overrides = {}) {
return {
endpoint: 'https://example.invalid/v1',
model: 'test-model',
apiKey: 'secret',
dimensions: 4,
batchSize: 4,
timeoutMs: 1000,
retries: 2,
concurrency: 2,
retryDelayMs: 1,
...overrides,
};
}
function cosine(left, right) {
return left.reduce((sum, value, index) => sum + value * right[index], 0);
}
test('mock provider is deterministic and separates similar from unrelated text', async () => {
const provider = createMockProvider(64);
const first = await provider.embed([
'Контроль жизненного цикла задач трекера',
'Контроль жизненного цикла задач трекера',
'Сверка контрольных сумм доказательств в отчётах',
]);
const second = await provider.embed(['Контроль жизненного цикла задач трекера']);
assert.deepEqual(first.vectors[0], second.vectors[0]);
const same = cosine(first.vectors[0], first.vectors[1]);
const different = cosine(first.vectors[0], first.vectors[2]);
assert.ok(Math.abs(same - 1) < 1e-9);
assert.ok(different < 0.8);
});
test('mock provider reports near-identical wording above reworded text', async () => {
const provider = createMockProvider(128);
const call = await provider.embed([
'Построить конвейер публикации продуктов с предпросмотром и гейтами',
'Построить конвейер публикации продуктов с предпросмотром и обязательными гейтами',
'Настроить резервное копирование каталога результатов на внешний носитель',
]);
const near = cosine(call.vectors[0], call.vectors[1]);
const far = cosine(call.vectors[0], call.vectors[2]);
assert.ok(near > far);
assert.ok(near > 0.8);
});
test('openai-compatible provider batches requests by configured size', async () => {
const sizes = [];
const probe = fakeTransport(async (request) => {
const input = JSON.parse(request.body).input;
sizes.push(input.length);
return embeddingsResponse(input.map((_item, index) => vector(index + 1, 4)));
});
const provider = createOpenAICompatibleProvider(settings({ batchSize: 4 }), probe.transport);
const texts = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
const call = await provider.embed(texts);
assert.equal(call.vectors.length, texts.length);
assert.deepEqual(sizes, [4, 4, 2]);
assert.equal(call.requests, 3);
assert.equal(call.inputTokens, 30);
});
test('a single query text produces exactly one request', async () => {
const sizes = [];
const probe = fakeTransport(async (request) => {
const input = JSON.parse(request.body).input;
sizes.push(input.length);
return embeddingsResponse(input.map((_item, index) => vector(index + 1, 4)));
});
const provider = createOpenAICompatibleProvider(settings({ batchSize: 16 }), probe.transport);
const call = await provider.embed(['Сверка контрольных сумм доказательств в отчётах']);
assert.deepEqual(sizes, [1], 'поисковый запрос отправляется одним обращением');
assert.equal(call.requests, 1);
assert.equal(call.vectors.length, 1);
});
test('provider retries a server error and then succeeds', async () => {
let attempt = 0;
const probe = fakeTransport(async () => {
attempt += 1;
return attempt === 1 ? { status: 503, body: 'busy' } : embeddingsResponse([vector(1, 4)]);
});
const provider = createOpenAICompatibleProvider(settings({ retries: 2 }), probe.transport);
const call = await provider.embed(['текст']);
assert.equal(call.vectors.length, 1);
assert.equal(call.requests, 2);
});
test('provider gives up after the configured retries', async () => {
const probe = fakeTransport(async () => ({ status: 429, body: 'rate limited' }));
const provider = createOpenAICompatibleProvider(settings({ retries: 1 }), probe.transport);
await assert.rejects(
() => provider.embed(['текст']),
(error) => error instanceof ProviderError && error.code === 'PROVIDER_UNAVAILABLE',
);
});
test('provider distinguishes a rejected request from an unavailable endpoint', async () => {
const probe = fakeTransport(async () => ({ status: 401, body: 'unauthorized' }));
const provider = createOpenAICompatibleProvider(settings(), probe.transport);
await assert.rejects(
() => provider.embed(['текст']),
(error) => error instanceof ProviderError && error.code === 'PROVIDER_REJECTED',
);
});
test('a transport failure is reported as an unavailable endpoint', async () => {
const probe = fakeTransport(async () => {
throw new Error('connect ECONNREFUSED');
});
const provider = createOpenAICompatibleProvider(settings({ retries: 1 }), probe.transport);
await assert.rejects(
() => provider.embed(['текст']),
(error) => error instanceof ProviderError && error.code === 'PROVIDER_UNAVAILABLE',
);
});
test('a wrong vector length is reported as a dimension mismatch', async () => {
const probe = fakeTransport(async () => embeddingsResponse([[1, 2, 3]]));
const provider = createOpenAICompatibleProvider(
settings({ dimensions: 4, retries: 0 }),
probe.transport,
);
await assert.rejects(
() => provider.embed(['текст']),
(error) => error instanceof ProviderError && error.code === 'DIMENSION_MISMATCH',
);
});
test('provider respects the configured concurrency limit', async () => {
const probe = fakeTransport(async () => {
await new Promise((resolve) => {
setTimeout(resolve, 10);
});
return embeddingsResponse([vector(1, 4), vector(2, 4), vector(3, 4), vector(4, 4)]);
});
const provider = createOpenAICompatibleProvider(
settings({ batchSize: 1, concurrency: 3, retries: 0 }),
probe.transport,
);
await provider.embed(['a', 'b', 'c', 'd', 'e', 'f']);
assert.ok(probe.maxInFlight <= 3);
assert.ok(probe.maxInFlight >= 2);
});
test('an empty request does not touch the network', async () => {
const probe = fakeTransport(async () => embeddingsResponse([]));
const provider = createOpenAICompatibleProvider(settings(), probe.transport);
const call = await provider.embed([]);
assert.equal(call.requests, 0);
assert.equal(probe.calls.length, 0);
});
test('the default transport posts the payload body to the embeddings endpoint', async () => {
const seen = [];
const original = globalThis.fetch;
globalThis.fetch = async (url, init) => {
seen.push({ url, init });
return new Response(
JSON.stringify({
data: [{ index: 0, embedding: [1, 0, 0, 0] }],
usage: { prompt_tokens: 3 },
}),
{ status: 200 },
);
};
try {
const call = await createOpenAICompatibleProvider(settings()).embed(['текст']);
assert.equal(call.vectors.length, 1);
} finally {
globalThis.fetch = original;
}
assert.equal(seen.length, 1);
const request = seen[0];
assert.equal(request.url, 'https://example.invalid/v1/embeddings');
assert.equal(request.init.method, 'POST');
assert.equal(request.init.headers['content-type'], 'application/json');
assert.equal(request.init.headers.authorization, 'Bearer secret');
assert.deepEqual(JSON.parse(request.init.body).input, ['текст']);
assert.ok(request.init.signal instanceof AbortSignal);
});
test('api key resolves from environment then from a json file selector', () => {
const root = tempDir();
const file = path.join(root, 'models.json');
writeFileSync(file, JSON.stringify({ providers: { demo: { apiKey: 'file-key' } } }), 'utf8');
process.env.BIDX_TEST_KEY = 'env-key';
assert.equal(resolveApiKey([{ kind: 'env', name: 'BIDX_TEST_KEY' }], root), 'env-key');
assert.equal(
resolveApiKey([{ kind: 'json-file', path: file, selector: 'providers.demo.apiKey' }], root),
'file-key',
);
delete process.env.BIDX_TEST_KEY;
assert.equal(
resolveApiKey(
[
{ kind: 'env', name: 'BIDX_TEST_KEY' },
{ kind: 'json-file', path: file, selector: 'providers.demo.apiKey' },
],
root,
),
'file-key',
);
assert.equal(resolveApiKey([{ kind: 'env', name: 'BIDX_MISSING' }], root), null);
});
@@ -0,0 +1,153 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { NORM_VERSION, normalizeIntent, normalizeTitle } from '../src/normalize.ts';
import { readCards } from '../src/reader.ts';
import { makeConfig, tempDir, writeCard, writeRawCard } from './helpers.mjs';
function card(overrides = {}) {
return {
id: 'T-1',
title: 'Контроль жизненного цикла задач',
status: 'To Do',
archived: false,
path: 'backlog/tasks/t-1.md',
type: null,
priority: null,
project: 'lab',
labels: [],
milestone: null,
parentId: null,
dependencies: [],
description: 'Задачи накапливаются, и дубликаты не видно.',
acceptanceCriteria: ['Поиск находит похожие карточки', 'Карточки не изменяются'],
fileHash: 'x',
...overrides,
};
}
test('intent ignores status, dates, metadata and checkbox state', () => {
const base = normalizeIntent(card());
const statusChanged = normalizeIntent(card({ status: 'Done' }));
const dated = normalizeIntent(card({ priority: 'high', labels: ['post-mvp'], milestone: 'm-9' }));
assert.equal(base.hash, statusChanged.hash);
assert.equal(base.hash, dated.hash);
assert.equal(base.normVersion, NORM_VERSION);
});
test('checking an acceptance criterion does not change the intent hash', () => {
const root = tempDir();
const backlog = `${root}/backlog`;
writeCard(backlog, {
id: 'T-10',
title: 'Индекс бэклога',
description: 'Описание',
acceptanceCriteria: [{ text: 'Первый критерий' }, { text: 'Второй критерий' }],
});
const first = readCards({ repoRoot: root, backlogDir: backlog });
const intentBefore = normalizeIntent(first.cards[0]);
writeCard(backlog, {
id: 'T-10',
title: 'Индекс бэклога',
description: 'Описание',
acceptanceCriteria: [{ text: 'Первый критерий', checked: true }, { text: 'Второй критерий' }],
});
const second = readCards({ repoRoot: root, backlogDir: backlog });
const intentAfter = normalizeIntent(second.cards[0]);
assert.equal(intentBefore.hash, intentAfter.hash);
assert.notEqual(first.cards[0].fileHash, second.cards[0].fileHash);
});
test('changing criterion text changes the intent hash', () => {
const intent = normalizeIntent(card({ acceptanceCriteria: ['Первый критерий'] }));
const changed = normalizeIntent(card({ acceptanceCriteria: ['Первый критерий изменён'] }));
assert.notEqual(intent.hash, changed.hash);
});
test('reader drops list markers and criterion index prefixes but keeps order', () => {
const root = tempDir();
const backlog = `${root}/backlog`;
writeCard(backlog, {
id: 'T-11',
title: 'Чтение карточек',
description: 'Первая строка\n\n Вторая строка ',
acceptanceCriteria: [{ text: 'А' }, { text: 'Б' }],
});
const result = readCards({ repoRoot: root, backlogDir: backlog });
assert.equal(result.errors.length, 0);
const read = result.cards[0];
assert.deepEqual(read.acceptanceCriteria, ['А', 'Б']);
const intent = normalizeIntent(read);
assert.ok(intent.text.includes('Первая строка\nВторая строка'));
assert.ok(!intent.text.includes('#1'));
assert.ok(!intent.text.includes('[ ]'));
});
test('reader excludes Definition of Done, comments and notes from the intent', () => {
const root = tempDir();
const backlog = `${root}/backlog`;
writeCard(backlog, {
id: 'T-12',
title: 'Только намерение',
description: 'Полезное описание',
acceptanceCriteria: [{ text: 'Критерий' }],
definitionOfDone: ['npm run check пройден'],
comments: 'Обсуждение реализации',
notes: 'Заметки исполнения',
});
const read = readCards({ repoRoot: root, backlogDir: backlog }).cards[0];
const intent = normalizeIntent(read);
assert.ok(!intent.text.includes('npm run check'));
assert.ok(!intent.text.includes('Обсуждение реализации'));
assert.ok(!intent.text.includes('Заметки исполнения'));
});
test('reader reads archived cards and marks them archived', () => {
const root = tempDir();
const backlog = `${root}/backlog`;
writeCard(backlog, { id: 'T-20', title: 'Активная', description: 'А' });
writeCard(backlog, { id: 'T-21', title: 'Архивная', description: 'Б', archived: true });
const result = readCards({ repoRoot: root, backlogDir: backlog });
assert.equal(result.cards.length, 2);
const archived = result.cards.find((item) => item.id === 'T-21');
assert.equal(archived.archived, true);
assert.ok(archived.path.startsWith('backlog/archive/tasks/'));
});
test('reader reports an unparseable card instead of failing silently', () => {
const root = tempDir();
const backlog = `${root}/backlog`;
writeCard(backlog, { id: 'T-30', title: 'Нормальная', description: 'А' });
writeRawCard(backlog, 'T-31', 'Просто текст без frontmatter\n');
const result = readCards({ repoRoot: root, backlogDir: backlog });
assert.equal(result.cards.length, 1);
assert.equal(result.errors.length, 1);
});
test('reader output is sorted by id and stable across runs', () => {
const root = tempDir();
const backlog = `${root}/backlog`;
writeCard(backlog, { id: 'T-40', title: 'Б', description: 'Б' });
writeCard(backlog, { id: 'T-39', title: 'А', description: 'А' });
const first = readCards({ repoRoot: root, backlogDir: backlog }).cards.map((item) => item.id);
const second = readCards({ repoRoot: root, backlogDir: backlog }).cards.map((item) => item.id);
assert.deepEqual(first, ['T-39', 'T-40']);
assert.deepEqual(first, second);
});
test('title normalization is language-aware and punctuation-insensitive', () => {
assert.equal(normalizeTitle(' Контроль -- жизненного цикла! '), 'контроль жизненного цикла');
assert.equal(
normalizeTitle('Контроль жизненного цикла'),
normalizeTitle('контроль — жизненного цикла'),
);
});
test('config loader resolves paths relative to the config file', async () => {
const root = tempDir();
const { configPath } = makeConfig(root);
const { loadConfig } = await import('../src/config.ts');
const config = loadConfig(configPath);
assert.equal(config.backlogDir, `${root}/backlog`);
assert.equal(config.provider.dimensions, 64);
});
@@ -0,0 +1,207 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import path from 'node:path';
import { createMockProvider } from '../src/provider.ts';
import { runIndex } from '../src/index-manager.ts';
import { loadConfig } from '../src/config.ts';
import { openStore } from '../src/store.ts';
import { candidatePairs, cosine, matches, topSimilar } from '../src/similarity.ts';
import { makeConfig, tempDir, writeCard } from './helpers.mjs';
const provider = createMockProvider(128);
async function indexed() {
const root = tempDir();
const written = makeConfig(root, { dimensions: 128 });
const config = loadConfig(written.configPath);
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',
});
writeCard(backlog, {
id: 'T-5',
title: 'Сверка контрольных сумм доказательств в отчётах',
description: 'Отчёты записывают SHA-256, сумму надо сверять с фактическими байтами файла.',
});
const store = openStore({ file: config.indexFile });
await runIndex({ kind: 'sync', config, provider, store });
return { config, store };
}
test('top similar excludes filtered cards and sorts by score descending', async () => {
const { store } = await indexed();
const source = store.loadCard('T-3');
const hits = topSimilar(store.loadCards(), source.vector, {
topK: 4,
filters: { excludeIds: ['T-3'] },
});
assert.equal(hits[0].id, 'T-5');
assert.equal(
hits.some((hit) => hit.id === 'T-3'),
false,
);
const scores = hits.map((hit) => hit.score);
assert.deepEqual(
scores,
[...scores].sort((left, right) => right - left),
);
store.close();
});
test('ties break deterministically by identifier', async () => {
const { store } = await indexed();
const source = store.loadCard('T-1');
const first = topSimilar(store.loadCards(), source.vector, {
topK: 5,
filters: { excludeIds: ['T-1'] },
});
const second = topSimilar(store.loadCards(), source.vector, {
topK: 5,
filters: { excludeIds: ['T-1'] },
});
assert.deepEqual(
first.map((hit) => [hit.id, hit.score]),
second.map((hit) => [hit.id, hit.score]),
);
const positions = first.map((hit) => hit.id);
assert.ok(positions.includes('T-3') && positions.includes('T-5'));
assert.ok(positions.indexOf('T-3') < positions.indexOf('T-5'));
const scoreOf = (id) => first.find((hit) => hit.id === id)?.score;
assert.equal(scoreOf('T-3'), scoreOf('T-5'));
store.close();
});
test('filters select by status, project and archived state', async () => {
const { store } = await indexed();
const source = store.loadCard('T-4');
const active = topSimilar(store.loadCards(), source.vector, {
topK: 5,
filters: { statuses: ['To Do', 'In Progress'], excludeArchived: true },
});
assert.equal(
active.some((hit) => hit.metadata.status === 'Done'),
false,
);
const done = topSimilar(store.loadCards(), source.vector, {
topK: 5,
filters: { statuses: ['Done'] },
});
assert.deepEqual(
done.map((hit) => hit.id),
['T-4'],
);
assert.equal(matches(store.loadCard('T-1'), { projects: ['other'] }), false);
assert.equal(matches(store.loadCard('T-1'), { projects: ['lab'] }), true);
store.close();
});
test('filters select by task type', async () => {
const root = tempDir();
const written = makeConfig(root, { dimensions: 128 });
const config = loadConfig(written.configPath);
const backlog = path.join(root, 'backlog');
writeCard(backlog, {
id: 'T-1',
title: 'Контроль жизненного цикла задач трекера',
description: 'Задачи накапливаются, и дубликаты не видно.',
type: 'feature',
});
writeCard(backlog, {
id: 'T-2',
title: 'Контроль жизненного цикла задач трекера',
description: 'Задачи накапливаются, и повторы не видно.',
type: 'feature',
});
writeCard(backlog, {
id: 'T-3',
title: 'Контроль жизненного цикла задач трекера',
description: 'Задачи накапливаются, и дубликаты не видно.',
type: 'chore',
});
const store = openStore({ file: config.indexFile });
await runIndex({ kind: 'sync', config, provider, store });
const cards = store.loadCards();
const source = cards.find((card) => card.id === 'T-1');
const features = topSimilar(cards, source.vector, {
topK: 5,
filters: { types: ['feature'], excludeIds: ['T-1'] },
});
assert.deepEqual(
features.map((hit) => hit.id),
['T-2'],
);
const chores = topSimilar(cards, source.vector, {
topK: 5,
filters: { types: ['chore'], excludeIds: ['T-1'] },
});
assert.deepEqual(
chores.map((hit) => hit.id),
['T-3'],
);
store.close();
});
test('candidate pairs are emitted once per unordered pair and ordered by score', async () => {
const { store } = await indexed();
const result = candidatePairs(store.loadCards(), { threshold: 0.5 });
const keys = result.map((pair) => `${pair.left}|${pair.right}`);
assert.equal(new Set(keys).size, keys.length);
for (const pair of result) {
assert.ok(pair.left < pair.right);
}
const scores = result.map((pair) => pair.score);
assert.deepEqual(
scores,
[...scores].sort((left, right) => right - left),
);
assert.ok(result[0].score >= result[result.length - 1].score);
store.close();
});
test('candidate pairs respect the threshold and the limit', async () => {
const { store } = await indexed();
const all = candidatePairs(store.loadCards(), { threshold: 0.1 });
const strict = candidatePairs(store.loadCards(), { threshold: 0.999 });
assert.ok(all.length > strict.length);
assert.equal(
strict.every((pair) => pair.score >= 0.999),
true,
);
const limited = candidatePairs(store.loadCards(), { threshold: 0.1, limit: 3 });
assert.equal(limited.length, 3);
assert.deepEqual(
limited.map((pair) => pair.score),
all.slice(0, 3).map((pair) => pair.score),
);
store.close();
});
test('cosine of unit vectors is their dot product and is bounded', async () => {
const call = await provider.embed(['текст о контрольных суммах', 'другой текст о публикации']);
const left = new Float32Array(call.vectors[0]);
const right = new Float32Array(call.vectors[1]);
const self = cosine(left, left);
assert.ok(Math.abs(self - 1) < 1e-6);
const cross = cosine(left, right);
assert.ok(cross > -1.000001 && cross < 1.000001);
assert.ok(cross < 0.9);
});