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(); });