208 lines
7.6 KiB
JavaScript
208 lines
7.6 KiB
JavaScript
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);
|
|
});
|