Эксперимент backlog-index: семантический индекс бэклога с отдельным CLI bidx (BHL-077.02…BHL-077.07)
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"printWidth": 100,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
# Backlog Index
|
||||
|
||||
Это эксперимент лаборатории, ещё не принятый инструмент. Реализация — `src/`, тесты — `tests/`, размеченный набор — `eval/`, зависимости и настройки — в этом каталоге. Сохраняй [профиль качества](QUALITY.md): strict TypeScript, typed ESLint, Prettier, пределы 80 строк и сложности 10, отсутствие подавлений ради зелёного результата.
|
||||
|
||||
Из каталога модуля: `npm ci --ignore-scripts`, затем `npm run quality`. Быстрые проверки кода без тестов — `npm run check`. Основные тесты не обращаются к сети: они работают на mock-поставщике и временных копиях карточек.
|
||||
|
||||
Сохраняй границы эксперимента (D-059…D-064):
|
||||
|
||||
- Backlog.md — единственный источник истины о задачах. Индекс производный и выбрасываемый, лежит в `.artifacts/backlog-index/` лаборатории, в Git не попадает и не должен содержать управленческих данных, которых нет в трекере.
|
||||
- Ни одна команда не пишет в карточки: ни удаления, ни объединения, ни смены статуса, ни правки текста. Чтение трекера только для чтения.
|
||||
- Обычная диагностика `lint` без `--semantic` не должна требовать ни индекса, ни сети. Семантические находки не получают уровень `error`.
|
||||
- Сеть допускается только при явной конфигурации реального поставщика; секрет берётся из переменной окружения или внешнего JSON-файла и в репозиторий не записывается. Тесты и оценка по умолчанию работают на mock.
|
||||
- Векторы хранятся в `node:sqlite` с точным косинусным поиском; отдельная векторная база не подключена. Смена поставщика, модели, размерности или версии схемы пересчитывает векторы, правка статуса и отметки критерия — нет.
|
||||
- `bhl` не затрагивается: он остаётся детерминированным CLI без сети, LLM и базы данных (D-012). Перенос команд в `bhl` — отдельное решение владельца (BHL-078).
|
||||
|
||||
Новые зависимости — только в этот каталог, в корень лаборатории их не добавляй. Пороги сходства меняй по данным калибровки, а не по впечатлению от выдачи, и записывай основание в результаты.
|
||||
@@ -0,0 +1,64 @@
|
||||
# Контроль качества Backlog Index
|
||||
|
||||
Профиль внедрён 2026-11-30 по поручению владельца о построении семантического индекса бэклога. Основа — [образец work-harness](../../library/code-quality-practices/typescript/work-harness.md) и [общий стандарт](../../library/code-quality-practices/STANDARD.md), адаптированный здесь так же, как в `products/bhl-cli` и `experiments/pi-supervisor`: библиотечный образец сохраняет статус `draft`, React/Redux/SCSS-правила к этому модулю неприменимы.
|
||||
|
||||
## Один полный запуск
|
||||
|
||||
Из каталога этого эксперимента (`experiments/backlog-index/`):
|
||||
|
||||
```text
|
||||
npm ci --ignore-scripts
|
||||
npm run quality
|
||||
```
|
||||
|
||||
`quality` последовательно выполняет `check` и `test`. `check` — форматирование без исправлений, затем ESLint с информацией о типах, затем TypeScript в режиме `noEmit`. Ошибка любого обязательного шага даёт ненулевой результат. Тесты не обращаются к сети и к реальной модели: поставщик embeddings подменяется детерминированным mock, карточки создаются во временном каталоге.
|
||||
|
||||
Отдельные шаги — `npm run check`, `npm run lint`, `npm run typecheck`, `npm test`; осознанное исправление формата — `npm run format`, проверки сами файлы не исправляют. Используются локальные версии из package/lock этого каталога; глобальные инструменты не участвуют. Реальные обращения к endpoint выполняются только явным запуском `index sync`, `index rebuild`, `search`, `eval` или `calibrate` с настроенным поставщиком — это не часть gate.
|
||||
|
||||
## Область
|
||||
|
||||
| Файлы | Проверки |
|
||||
|---|---|
|
||||
| `src/**/*.ts` | Prettier, ESLint с информацией о типах, TypeScript strict; поведение — тестами |
|
||||
| `tests/**/*.mjs` | Prettier, базовые ESLint-правила, исполнение Node test runner |
|
||||
| `eslint.config.mjs`, `tsconfig.json`, `.prettierrc.json`, `backlog-index.config.json`, `eval/labels.json` | Формат; конфиг ESLint также проверяется линтером |
|
||||
| `../../backlog/**` | Только чтение: тест сверки с трекером сравнивает прочитанные карточки с выводом `backlog task list --json` |
|
||||
|
||||
Индекс в `.artifacts/` в проверки не входит: он производный и может отсутствовать. Тесты создают собственные временные базы SQLite и не зависят от состояния лаборатории.
|
||||
|
||||
## Правила и исключения
|
||||
|
||||
- TypeScript `strict`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `noImplicitReturns`, запрет неиспользуемых переменных и параметров. Сборки нет: `noEmit`, стираемый синтаксис, TypeScript исполняется Node.
|
||||
- ESLint **9.39.5**, typescript-eslint **8.65.0**, TypeScript **5.9.3**, sonarjs **4.2.0**: strictTypeChecked, import-x и SonarJS. Запрещены явный `any`, небезопасные операции с ним, non-null assertions и type assertions; внешний JSON сначала получает тип `unknown` и проверяется во время исполнения (eval-набор, ответ поставщика, frontmatter карточек).
|
||||
- Необработанный Promise — ошибка, `void` её не скрывает. Точка входа CLI использует верхнеуровневое `await` под условием «запущен как исполняемый файл», поэтому импорт модуля тестами не запускает команду.
|
||||
- Максимум **80** непустых строк без комментариев на функцию, cognitive complexity — **10**. Для тестовых сценариев снят только лимит длины функции, чтобы подготовка, действие и проверки оставались вместе. Исключений для конкретных файлов production-кода и увеличенных порогов нет; `noInlineConfig` запрещает менять политику комментарием, ESLint запускается с `--max-warnings 0`.
|
||||
- `no-console` действует везде, кроме `src/cli.ts`: только CLI пишет в stdout envelope команды.
|
||||
- Prettier **3.6.2** отвечает за форматирование. Зависимость от `yaml` нужна для чтения frontmatter карточек; она единственная runtime-зависимость модуля.
|
||||
|
||||
Для тестов нужен Node **22.19+**: он исполняет TypeScript напрямую и предоставляет встроенный `node:sqlite`. На Node 22.19 модуль `node:sqlite` помечен как экспериментальный и печатает предупреждение; на Node 24 предупреждения нет. Проверки и CLI на этой машине выполнялись под Node 24.18.
|
||||
|
||||
## Что доказывают проверки
|
||||
|
||||
[Чтение и нормализация](tests/reader.test.mjs) проверяют, что intent строится из заголовка, описания и текстов критериев приёмки; статус, даты, метки, веха, приоритет, Definition of Done, комментарии, заметки и состояние чекбоксов в вектор не попадают; маркеры списка и префикс `#N` удаляются, порядок сохраняется; читаются архивные карточки; неразобранная карточка сообщается как ошибка чтения, а не пропадает молча; вывод отсортирован и устойчив.
|
||||
|
||||
[Поставщик](tests/provider.test.mjs) проверяет детерминированность mock и разделение похожего и несвязного текста, пакетирование по `batchSize`, лимит параллельности, повторы при 429/5xx, различие «endpoint отклонил» и «endpoint недоступен», несовпадение размерности, пустой запрос без сети и разрешение API key из окружения и внешнего JSON. Отдельный тест подменяет `fetch` и проверяет, что транспорт по умолчанию отправляет тело, заголовок авторизации и сигнал таймаута — регрессия на пустом теле запроса.
|
||||
|
||||
[Индексация](tests/index.test.mjs) проверяет первичную загрузку, отсутствие обращений к поставщику при повторной синхронизации, обновление метаданных без пересчёта при смене статуса и отметки критерия, пересчёт только изменённой карточки, удаление строк за пропавшими карточками, пересчёт при смене модели, продолжение прерванного прогона без пересчёта сохранённых векторов, полный пересчёт при `rebuild`, неизменность файлов трекера после удаления индекса, совместную работу нескольких писателей и читателя с одной базой и запись метаданных индекса.
|
||||
|
||||
[Similarity Engine](tests/similarity.test.mjs) проверяет исключение самой карточки из находок, сортировку по сходству и детерминированное разрешение равенства по идентификатору, фильтры по статусу, проекту, типу задачи и архивности, однократную выдачу неупорядоченной пары, ограничение по порогу и лимиту, а также границы классов сходства.
|
||||
|
||||
[Диагностика](tests/lint.test.mjs) проверяет `DUP001` и `DUP002` без индекса и без сети, отсутствие семантических правил в обычном прогоне, `SEM001`…`SEM004` на индексе, отделение повтора завершённой и пропущенной задачи, отсутствие сигналов для пары родитель–подзадача, `SEM005` при пустом или неполном индексе, `SEM006` при несовместимых записях, то, что семантические находки не создают уровень `error`, детерминированность вывода и неизменность файлов трекера.
|
||||
|
||||
[CLI](tests/cli.test.mjs) запускает настоящий `src/cli.ts` подпроцессом и проверяет коды выхода `0/1/2/3/4`, машиночитаемый envelope, одинаковый состав полей, категорию сигнала у каждой находки `similar`, `search` и `duplicates` (включая отсутствие сигнала для пары родитель–подзадача), отсутствие сети при mock-поставщике, отказ работать без API key вместо обращения к endpoint наугад, резервирование кода `3` за нереализованным L2 и побайтовую идентичность повторного вывода.
|
||||
|
||||
[Оценка](tests/eval.test.mjs) проверяет, что inline-карточки набора сохраняют описание и критерии, отсутствующие карточки бэклога сообщаются, а не молча выпадают, кривые калибровки и точки best-F1 построены, precision@k и recall@k посчитаны, режим без запросов работает, и что поставляемый `eval/labels.json` внутренне согласован: метки из разрешённого списка, пары и находки ссылаются на объявленные карточки, каждая карточка бэклога действительно существует в трекере.
|
||||
|
||||
[Сверка с трекером](tests/backlog-drift.test.mjs) читает живой бэклог лаборатории и сравнивает его с выводом `backlog task list --json`: тот же набор идентификаторов, те же заголовки, статусы, метки, зависимости, вехи и родители, пустой список ошибок чтения. Тест пропускается, если каталога трекера или бинарника трекера нет.
|
||||
|
||||
## Что проверки не доказывают
|
||||
|
||||
Тесты на mock-поставщике проверяют механику, а не качество семантического поиска: mock построен на хешированных признаках текста и не заменяет измерение на рабочей модели. Качество поиска, пороги границ и эксплуатационные метрики (время сборки, доля переиспользования, размер индекса, время поиска) измеряются отдельно прогоном `calibrate` и `metrics` — см. [результаты](../../results/backlog-index/README.md).
|
||||
|
||||
Прохождения gate недостаточно, чтобы считать гипотезу полезной: сколько дубликатов реально не создано благодаря проверке, измеряется только наблюдением за несколькими сессиями создания задач. L2-классификация не реализована, поэтому находки L1 остаются кандидатами, а не классифицированными суждениями.
|
||||
|
||||
Самостоятельность модуля проверяется его собственным package/lock и отсутствием импортов из корня, соседних экспериментов и `library/`: исполняемый код их не имеет. Документационные ссылки на другие части лаборатории допускаются.
|
||||
@@ -0,0 +1,71 @@
|
||||
# Backlog Index — семантический индекс бэклога и поиск дубликатов
|
||||
|
||||
**Статус: эксперимент, MVP реализован и измерен; инструмент ещё не принят владельцем.** Проверяемая гипотеза: производный семантический индекс поверх файлов трекера находит переформулированные дубликаты и пересечения требований, не превращаясь во второй источник истины и не замедляя обычную детерминированную диагностику.
|
||||
|
||||
Задачи создают человек и ИИ-агенты, включая параллельных субагентов. Штатный поиск трекера нечёткий по тексту и не находит переформулировку, `backlog doctor` проверяет только идентификаторы и циклы зависимостей. Эксперимент добавляет третий слой: детерминированные совпадения, косинусное сходство intent-векторов и размеченную оценку качества поиска.
|
||||
|
||||
Решения по границам зафиксированы отдельно: D-059 (размещение и отдельный CLI), D-060 (чтение карточек и производность индекса), D-061 (intent-нормализация и версии схемы), D-062 (хранение и правила инвалидации), D-063 (заменяемый поставщик embeddings), D-064 (уровни обнаружения и классы сигналов). Задачи итерации: BHL-077 и подзадачи, план переноса в продукт — BHL-078.
|
||||
|
||||
## Что считается источником истины
|
||||
|
||||
Backlog.md остаётся единственным хранилищем задач. Индекс — производный артефакт: он строится из файлов карточек, полностью восстанавливается удалением файла индекса и не содержит управленческих данных, которых нет в трекере. Ни одна команда эксперимента не пишет в карточки: нет удаления, объединения, смены статуса и правки текста. Удаление индекса не меняет ни одного файла трекера — это проверено тестом.
|
||||
|
||||
Индекс лежит в `.artifacts/backlog-index/index.sqlite` (вне Git, вне корневых проверок). Файл можно удалить в любой момент; `bidx index sync` строит его заново за один прогон.
|
||||
|
||||
## Команды
|
||||
|
||||
Из каталога эксперимента (`npm run bidx -- …` или `node src/cli.ts …`):
|
||||
|
||||
| Команда | Назначение | Сеть |
|
||||
|---|---|---|
|
||||
| `index sync` | довести индекс до состояния трекера | только новые или изменённые по смыслу карточки |
|
||||
| `index rebuild` | пересчитать все векторы | да, при реальном поставщике |
|
||||
| `index status` | модель, размерность, версии схем, покрытие, доля переиспользования | нет |
|
||||
| `similar <ID> [--top-k N] [--status S] [--project P] [--label L] [--type T] [--include-archived]` | ближайшие карточки к уже существующей | нет |
|
||||
| `search "<текст>" [--top-k N] [--status S] [--project P] [--label L] [--type T]` | поиск по тексту запроса, которого нет в бэклоге | один запрос на запрос пользователя |
|
||||
| `duplicates [--threshold X] [--limit N]` | пары-кандидаты по всему индексу | нет |
|
||||
| `lint [--semantic]` | диагностика L0; `--semantic` добавляет L1 | нет |
|
||||
| `metrics` | покрытие, размер, время и переиспользование последнего прогона | нет |
|
||||
| `eval` / `calibrate [--set <path>] [--top-k N]` | оценка качества поиска и подбор порогов по размеченному набору | по конфигу поставщика |
|
||||
| `audit --duplicates` | L2-классификация пересечений: запланирована, не реализована | нет |
|
||||
|
||||
Коды выхода: `0` — успех, `1` — есть находки, `2` — ошибка использования, `3` — слой не реализован, `4` — ошибка конфигурации, поставщика или внутренняя. Все команды принимают `--json`: envelope `{ok, command, data}` либо `{ok: false, command, error}` с кодом и сообщением. Человекочитаемый и машиночитаемый вывод содержат одинаковый набор полей; повторный запуск той же команды даёт побайтово одинаковый вывод.
|
||||
|
||||
Каждая находка `similar`, `search` и `duplicates` несёт категорию сигнала из тех же правил, что и диагностика: `SEM001`…`SEM004` либо `null`, когда сходство есть, но сигнала нет (нижний порог или структурное включение). Для `search` запрос трактуется как намерение новой активной задачи, поэтому категория считается по статусу найденной карточки.
|
||||
|
||||
## Конфигурация
|
||||
|
||||
`backlog-index.config.json` в каталоге эксперимента; относительные пути разрешаются от файла конфигурации, `--config <path>` выбирает другой файл.
|
||||
|
||||
- `provider.kind` — `mock` (детерминированный, без сети) или `openai-compatible` (`POST {endpoint}/embeddings`).
|
||||
- `provider.endpoint`, `provider.model`, `provider.dimensions` — адрес, модель и ожидаемая размерность; несоответствие размерности останавливает прогон, а не тихо подменяется.
|
||||
- `provider.apiKeySources` — список источников ключа: переменная окружения или JSON-файл с селектором. Секрет не хранится в репозитории; при отсутствии ключа команда сообщает `API_KEY_MISSING`, а не обращается к endpoint наугад.
|
||||
- `provider.batchSize`, `timeoutMs`, `retries`, `concurrency`, `retryDelayMs`, `modelParams` — пакетирование и политика повторов; `modelParams` добавляет модельные параметры без правки кода.
|
||||
- `thresholds.duplicate`, `overlap`, `related` — пороги сигналов; значения измерены на рабочей модели, см. [результаты](../../results/backlog-index/README.md).
|
||||
- `statusClasses.active`, `done`, `skipped` — какие статусы считать активными, завершёнными и пропущенными; архивные карточки всегда относятся к пропущенным.
|
||||
|
||||
Смена поставщика, модели, размерности или версии схемы делает сохранённые векторы несовместимыми: они пересчитываются. Правка статуса, приоритета, меток, вехи, зависимостей, Definition of Done, комментариев, заметок исполнения и отметки критерия приёмки вектор не пересчитывает — обновляются только метаданные записи.
|
||||
|
||||
## Что проверяется перед созданием задачи
|
||||
|
||||
`lint` без `--semantic` работает без индекса и без сети: `DUP001` — полностью совпадающее нормализованное содержание карточек, `DUP002` — повтор нормализованного названия. С `--semantic` добавляются сигналы L1, и они никогда не становятся ошибками: `SEM001` — потенциальный дубликат активных задач, `SEM002` — существенное пересечение требований, `SEM003` — возможное повторение завершённой задачи, `SEM004` — возможное повторение пропущенной или архивной, `SEM005` — индекс устарел или не покрывает карточки, `SEM006` — записи индекса несовместимы с текущей конфигурацией.
|
||||
|
||||
Пара родитель–собственная подзадача не считается дубликатом: это структурное включение, оно известно из метаданных трекера. Такие пары остаются в выдаче `similar` и `duplicates` как близкие, но категорию сигнала не получают. Пары выдаются один раз для неупорядоченной пары и упорядочены по сходству, при равенстве — по идентификатору, поэтому вывод детерминирован.
|
||||
|
||||
Порядок действий агента перед созданием карточки описан навыком [backlog-duplicate-check](../../.agents/skills/backlog-duplicate-check/SKILL.md): сформулировать намерение, проверить детерминированно, при доступном индексе выполнить семантический поиск, разобрать находки и решить о создании. AGENTS.md и системные промты ради этого не расширялись.
|
||||
|
||||
## Оценка
|
||||
|
||||
`eval/labels.json` — размеченный набор: пары классов `duplicate`, `overlap`, `related`, `unrelated` и запросы с ожидаемыми находками. Часть карточек читается из живого бэклога, часть описана внутри набора; карточки трекера набор не изменяет. `calibrate` строит кривые precision/recall для трёх границ и выдаёт наилучшие точки по F1; `eval` добавляет precision@k и recall@k по запросам. Оценка с `--provider mock` не требует сети.
|
||||
|
||||
## Пределы
|
||||
|
||||
- L2-классификация (дубликат, пересечение, включение, related, конфликт) не реализована: `audit --duplicates` возвращает код `3`. Пороги калибруются по сходству, а не по смыслу, поэтому SEM001 — сигнал к проверке, а не доказательство дубликата.
|
||||
- Пороги относятся к конкретной модели и конкретному набору. Измеренные значения записаны в результатах; гипотеза поручения 0.90/0.80/0.70 для рабочей модели не подтвердилась.
|
||||
- Индекс не в Git и не переносится между машинами: на новой машине нужен один прогон `index sync`.
|
||||
- В `bhl` команды не перенесены: `bhl` остаётся детерминированным CLI без сети и базы данных (D-012). Перенос возможен только после принятия эксперимента владельцем и описан в BHL-078.
|
||||
- Метрики полезности — сколько дубликатов реально не создано — требуют наблюдения за несколькими сессиями и пока не измерены.
|
||||
|
||||
## Контроль качества
|
||||
|
||||
Локальный профиль описан в [QUALITY.md](QUALITY.md), местные правила — в [AGENTS.md](AGENTS.md). Из каталога эксперимента: `npm ci --ignore-scripts`, затем `npm run quality`. Основные тесты проходят без реальной embedding-модели: сеть не нужна ни тестам, ни обычной диагностике.
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"repoRoot": "../..",
|
||||
"backlogDir": "../../backlog",
|
||||
"indexFile": "../../.artifacts/backlog-index/index.sqlite",
|
||||
"topK": 10,
|
||||
"provider": {
|
||||
"kind": "openai-compatible",
|
||||
"endpoint": "https://llm.bulkoneer.ru/v1",
|
||||
"model": "Qwen3-Embedding-0.6B",
|
||||
"dimensions": 1024,
|
||||
"batchSize": 16,
|
||||
"timeoutMs": 60000,
|
||||
"retries": 3,
|
||||
"concurrency": 2,
|
||||
"retryDelayMs": 500,
|
||||
"apiKeySources": [
|
||||
{ "kind": "env", "name": "BHL_EMBEDDINGS_API_KEY" },
|
||||
{
|
||||
"kind": "json-file",
|
||||
"path": "../../.pi/agent/models.json",
|
||||
"selector": "providers.bulkoneer-llm.apiKey"
|
||||
}
|
||||
]
|
||||
},
|
||||
"thresholds": {
|
||||
"duplicate": 0.78,
|
||||
"overlap": 0.6,
|
||||
"related": 0.5
|
||||
},
|
||||
"statusClasses": {
|
||||
"active": ["To Do", "In Progress"],
|
||||
"done": ["Done"],
|
||||
"skipped": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import js from '@eslint/js';
|
||||
import { defineConfig } from 'eslint/config';
|
||||
import importX from 'eslint-plugin-import-x';
|
||||
import sonarjs from 'eslint-plugin-sonarjs';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
// Adapted from ../../library/code-quality-practices/typescript/work-harness.md
|
||||
// via products/bhl-cli/eslint.config.mjs. Adoption scope: this experiment only.
|
||||
const files = ['src/**/*.ts', 'tests/**/*.{ts,mjs}', 'eslint.config.mjs'];
|
||||
const typedFiles = ['src/**/*.ts', 'tests/**/*.ts'];
|
||||
|
||||
export default defineConfig(
|
||||
{
|
||||
files,
|
||||
extends: [js.configs.recommended],
|
||||
languageOptions: { globals: globals.node },
|
||||
linterOptions: {
|
||||
noInlineConfig: true,
|
||||
reportUnusedDisableDirectives: 'error',
|
||||
reportUnusedInlineConfigs: 'error',
|
||||
},
|
||||
rules: {
|
||||
'array-callback-return': ['error', { checkForEach: true }],
|
||||
eqeqeq: ['error', 'always'],
|
||||
curly: ['error', 'all'],
|
||||
'no-console': 'error',
|
||||
'no-eval': 'error',
|
||||
'no-implicit-coercion': 'error',
|
||||
'no-promise-executor-return': 'error',
|
||||
'no-return-assign': ['error', 'always'],
|
||||
'no-unmodified-loop-condition': 'error',
|
||||
'no-unreachable-loop': 'error',
|
||||
'no-unsafe-optional-chaining': 'error',
|
||||
'prefer-const': 'error',
|
||||
'prefer-promise-reject-errors': 'error',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: typedFiles,
|
||||
extends: [
|
||||
tseslint.configs.strictTypeChecked,
|
||||
importX.flatConfigs.recommended,
|
||||
importX.flatConfigs.typescript,
|
||||
sonarjs.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname },
|
||||
},
|
||||
settings: {
|
||||
'import-x/resolver': { typescript: { project: './tsconfig.json' } },
|
||||
},
|
||||
rules: {
|
||||
'@typescript-eslint/consistent-type-imports': [
|
||||
'error',
|
||||
{ fixStyle: 'separate-type-imports' },
|
||||
],
|
||||
'@typescript-eslint/consistent-type-exports': 'error',
|
||||
'@typescript-eslint/consistent-type-assertions': ['error', { assertionStyle: 'never' }],
|
||||
'@typescript-eslint/no-floating-promises': [
|
||||
'error',
|
||||
{ ignoreVoid: false, ignoreIIFE: false },
|
||||
],
|
||||
'@typescript-eslint/no-misused-promises': 'error',
|
||||
'@typescript-eslint/strict-boolean-expressions': 'error',
|
||||
'@typescript-eslint/switch-exhaustiveness-check': 'error',
|
||||
'@typescript-eslint/no-shadow': 'error',
|
||||
'@typescript-eslint/return-await': ['error', 'error-handling-correctness-only'],
|
||||
'max-lines-per-function': [
|
||||
'error',
|
||||
{ max: 80, IIFEs: true, skipBlankLines: true, skipComments: true },
|
||||
],
|
||||
'sonarjs/cognitive-complexity': ['error', 10],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['tests/**/*.ts', 'tests/**/*.mjs'],
|
||||
rules: {
|
||||
// A scenario keeps setup, action and assertions together; production stays at 80.
|
||||
'max-lines-per-function': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['src/cli.ts'],
|
||||
rules: {
|
||||
// The CLI is the only place allowed to write the process stdout envelope.
|
||||
'no-console': 'off',
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,197 @@
|
||||
{
|
||||
"version": 1,
|
||||
"cards": [
|
||||
{ "id": "BHL-001", "source": "backlog" },
|
||||
{ "id": "BHL-009", "source": "backlog" },
|
||||
{ "id": "BHL-017", "source": "backlog" },
|
||||
{ "id": "BHL-021", "source": "backlog" },
|
||||
{ "id": "BHL-028", "source": "backlog" },
|
||||
{ "id": "BHL-029", "source": "backlog" },
|
||||
{ "id": "BHL-034", "source": "backlog" },
|
||||
{ "id": "BHL-042", "source": "backlog" },
|
||||
{ "id": "BHL-043", "source": "backlog" },
|
||||
{ "id": "BHL-046", "source": "backlog" },
|
||||
{ "id": "BHL-048", "source": "backlog" },
|
||||
{ "id": "BHL-049", "source": "backlog" },
|
||||
{ "id": "BHL-062", "source": "backlog" },
|
||||
{ "id": "BHL-063", "source": "backlog" },
|
||||
{ "id": "BHL-065", "source": "backlog" },
|
||||
{ "id": "BHL-070", "source": "backlog" },
|
||||
{ "id": "BHL-071", "source": "backlog" },
|
||||
{ "id": "BHL-073", "source": "backlog" },
|
||||
{ "id": "BHL-074", "source": "backlog" },
|
||||
{ "id": "BHL-076", "source": "backlog" },
|
||||
{ "id": "BHL-077", "source": "backlog" },
|
||||
{ "id": "BHL-077.02", "source": "backlog" },
|
||||
{
|
||||
"id": "EVAL-01",
|
||||
"source": "inline",
|
||||
"status": "To Do",
|
||||
"title": "Сверить контрольные суммы доказательств в отчётах с реальными файлами",
|
||||
"description": "Отчёты записывают SHA-256 доказательств. Нужна проверка, что записанная сумма совпадает с фактическими байтами файла, иначе вывод нельзя воспроизвести.",
|
||||
"acceptanceCriteria": [
|
||||
"Команда сверяет сумму из отчёта с фактическим файлом",
|
||||
"Расхождение останавливает проверку и называется в выводе"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "EVAL-02",
|
||||
"source": "inline",
|
||||
"status": "To Do",
|
||||
"title": "Check that evidence hashes recorded in reports match the actual bytes",
|
||||
"description": "Reports record SHA-256 fingerprints of evidence. A check must compare the recorded hash with the bytes of the file so a finding stays reproducible.",
|
||||
"acceptanceCriteria": [
|
||||
"The tool compares a recorded hash with the file bytes",
|
||||
"A mismatch fails the check and is reported"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "EVAL-03",
|
||||
"source": "inline",
|
||||
"status": "To Do",
|
||||
"title": "Построить конвейер публикации продуктов с предпросмотром и обязательными гейтами",
|
||||
"description": "Продукты публикуются механизмом: экспорт, проверки, предпросмотр и явная авторизация. Нужен единый конвейер, который не пишет в публичные репозитории без подтверждения человека.",
|
||||
"acceptanceCriteria": [
|
||||
"Конвейер показывает предпросмотр до записи",
|
||||
"Запись выполняется только после явного подтверждения"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "EVAL-04",
|
||||
"source": "inline",
|
||||
"status": "To Do",
|
||||
"title": "Реализовать локальный кеш загружаемых артефактов с проверкой контрольных сумм",
|
||||
"description": "Загруженные версии спецификации должны переиспользоваться локально, а их подлинность проверяться по SHA-256 без повторной загрузки.",
|
||||
"acceptanceCriteria": [
|
||||
"Повторная загрузка того же артефакта не требует сети",
|
||||
"Несовпадение суммы останавливает использование артефакта"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "EVAL-05",
|
||||
"source": "inline",
|
||||
"status": "To Do",
|
||||
"title": "Индексировать тексты задач для поиска по смыслу",
|
||||
"description": "Задачи переформулируются от сессии к сессии, и точный поиск их не находит. Нужен индекс текстов карточек с поиском по смыслу поверх трекера.",
|
||||
"acceptanceCriteria": [
|
||||
"Поиск возвращает карточки по переформулированному запросу",
|
||||
"Индекс строится из карточек трекера и не хранит уникальных данных"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "EVAL-06",
|
||||
"source": "inline",
|
||||
"status": "To Do",
|
||||
"title": "Настроить резервное копирование каталога результатов",
|
||||
"description": "Каталог результатов содержит датированные выводы. Нужна периодическая копия на внешний носитель, чтобы выводы не терялись при отказе диска.",
|
||||
"acceptanceCriteria": [
|
||||
"Копия создаётся одной командой",
|
||||
"Восстановление проверено на контрольном каталоге"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "EVAL-07",
|
||||
"source": "inline",
|
||||
"status": "To Do",
|
||||
"title": "Add a changelog for the supervisor experiment",
|
||||
"description": "The supervisor prototype changes behaviour between runs. A short changelog should record behaviour changes so a reader knows what changed and why.",
|
||||
"acceptanceCriteria": [
|
||||
"The changelog lists behaviour changes per version",
|
||||
"The format matches the lab documentation style"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "EVAL-08",
|
||||
"source": "inline",
|
||||
"status": "To Do",
|
||||
"title": "Проверять границы продуктовых деревьев и согласованность реестра продуктов",
|
||||
"description": "Реестр продуктов описывает деревья и публичные репозитории. Нужна автоматическая проверка, что объявленное дерево существует, а идентификаторы не повторяются.",
|
||||
"acceptanceCriteria": [
|
||||
"Проверка находит отсутствующее объявленное дерево",
|
||||
"Проверка находит повторяющийся идентификатор продукта"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "EVAL-09",
|
||||
"source": "inline",
|
||||
"status": "To Do",
|
||||
"title": "Провести повторный аудит лаборатории и записать отчёт",
|
||||
"description": "После исправлений нужно снова прогнать детерминированные и семантические проверки и сохранить отчёт с найденными расхождениями.",
|
||||
"acceptanceCriteria": [
|
||||
"Отчёт содержит результат каждой проверки",
|
||||
"Найденные расхождения связаны с задачами"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "EVAL-10",
|
||||
"source": "inline",
|
||||
"status": "To Do",
|
||||
"title": "Добавить диагностику трекера в общий прогон проверок качества",
|
||||
"description": "Диагностика трекера находит повторяющиеся идентификаторы и циклы зависимостей. Её нужно запускать вместе с остальными проверками лаборатории, а не отдельно.",
|
||||
"acceptanceCriteria": [
|
||||
"Общая команда качества запускает диагностику трекера",
|
||||
"Находки диагностики блокируют прогон"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "EVAL-11",
|
||||
"source": "inline",
|
||||
"status": "To Do",
|
||||
"title": "Run the tracker diagnosis as part of the quality gate",
|
||||
"description": "The tracker diagnosis reports duplicate identifiers and dependency cycles. It should run with the other repository checks instead of being invoked by hand.",
|
||||
"acceptanceCriteria": [
|
||||
"The quality gate command runs the tracker diagnosis",
|
||||
"Diagnosis findings fail the gate"
|
||||
]
|
||||
}
|
||||
],
|
||||
"pairs": [
|
||||
{ "a": "EVAL-01", "b": "BHL-063", "label": "duplicate" },
|
||||
{ "a": "EVAL-02", "b": "BHL-063", "label": "duplicate" },
|
||||
{ "a": "EVAL-03", "b": "BHL-070", "label": "duplicate" },
|
||||
{ "a": "EVAL-04", "b": "BHL-021", "label": "duplicate" },
|
||||
{ "a": "EVAL-08", "b": "BHL-071", "label": "duplicate" },
|
||||
{ "a": "EVAL-10", "b": "BHL-009", "label": "duplicate" },
|
||||
{ "a": "EVAL-11", "b": "BHL-009", "label": "duplicate" },
|
||||
{ "a": "BHL-062", "b": "BHL-070", "label": "overlap" },
|
||||
{ "a": "BHL-065", "b": "BHL-071", "label": "overlap" },
|
||||
{ "a": "BHL-042", "b": "BHL-043", "label": "overlap" },
|
||||
{ "a": "EVAL-05", "b": "BHL-077", "label": "overlap" },
|
||||
{ "a": "EVAL-09", "b": "BHL-042", "label": "overlap" },
|
||||
{ "a": "BHL-077", "b": "BHL-077.02", "label": "overlap" },
|
||||
{ "a": "BHL-046", "b": "BHL-073", "label": "overlap" },
|
||||
{ "a": "BHL-048", "b": "BHL-077", "label": "related" },
|
||||
{ "a": "BHL-029", "b": "BHL-077", "label": "related" },
|
||||
{ "a": "BHL-076", "b": "BHL-077", "label": "related" },
|
||||
{ "a": "BHL-001", "b": "BHL-077", "label": "related" },
|
||||
{ "a": "BHL-048", "b": "BHL-049", "label": "related" },
|
||||
{ "a": "BHL-029", "b": "BHL-042", "label": "related" },
|
||||
{ "a": "BHL-070", "b": "BHL-074", "label": "related" },
|
||||
{ "a": "EVAL-06", "b": "BHL-063", "label": "unrelated" },
|
||||
{ "a": "EVAL-06", "b": "BHL-070", "label": "unrelated" },
|
||||
{ "a": "EVAL-07", "b": "BHL-070", "label": "unrelated" },
|
||||
{ "a": "EVAL-07", "b": "BHL-017", "label": "unrelated" },
|
||||
{ "a": "BHL-028", "b": "BHL-001", "label": "unrelated" },
|
||||
{ "a": "BHL-034", "b": "BHL-017", "label": "unrelated" },
|
||||
{ "a": "BHL-048", "b": "BHL-028", "label": "unrelated" },
|
||||
{ "a": "EVAL-02", "b": "BHL-028", "label": "unrelated" }
|
||||
],
|
||||
"queries": [
|
||||
{
|
||||
"text": "проверить, что записанные в отчётах контрольные суммы соответствуют фактическим файлам",
|
||||
"relevant": ["BHL-063", "EVAL-01", "EVAL-02"]
|
||||
},
|
||||
{
|
||||
"text": "publish products through a pipeline with dry-run and mandatory gates",
|
||||
"relevant": ["BHL-070", "EVAL-03", "BHL-062"]
|
||||
},
|
||||
{
|
||||
"id": "BHL-077",
|
||||
"relevant": ["EVAL-05", "BHL-077.02", "BHL-048", "BHL-029"]
|
||||
},
|
||||
{
|
||||
"text": "сверить согласованные направления проверок с содержимым репозитория",
|
||||
"relevant": ["BHL-076"]
|
||||
}
|
||||
]
|
||||
}
|
||||
+2378
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@harness-lab/backlog-index",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Семантический индекс бэклога: intent-embeddings, инкрементальная индексация и обнаружение дубликатов задач",
|
||||
"engines": {
|
||||
"node": ">=22.19.0"
|
||||
},
|
||||
"scripts": {
|
||||
"bidx": "node src/cli.ts",
|
||||
"check": "npm run format:check && npm run lint && npm run typecheck",
|
||||
"test": "node --test \"tests/*.test.mjs\"",
|
||||
"lint": "eslint --max-warnings 0 \"src/**/*.ts\" \"tests/**/*.{ts,mjs}\" eslint.config.mjs",
|
||||
"typecheck": "tsc --project tsconfig.json",
|
||||
"format:check": "prettier --check \"src/**/*.ts\" \"tests/**/*.{ts,mjs}\" eslint.config.mjs tsconfig.json backlog-index.config.json eval/labels.json",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"tests/**/*.{ts,mjs}\" eslint.config.mjs tsconfig.json backlog-index.config.json eval/labels.json",
|
||||
"quality": "npm run check && npm test",
|
||||
"index": "node src/cli.ts index sync",
|
||||
"duplicates": "node src/cli.ts duplicates"
|
||||
},
|
||||
"dependencies": {
|
||||
"yaml": "2.9.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "9.39.5",
|
||||
"@types/node": "22.19.19",
|
||||
"eslint": "9.39.5",
|
||||
"eslint-import-resolver-typescript": "4.4.5",
|
||||
"eslint-plugin-import-x": "4.17.1",
|
||||
"eslint-plugin-sonarjs": "4.2.0",
|
||||
"globals": "16.5.0",
|
||||
"prettier": "3.6.2",
|
||||
"typescript": "5.9.3",
|
||||
"typescript-eslint": "8.65.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { ConfigError, loadConfig } from './config.ts';
|
||||
import { EvalSetError, parseEvalSet, runEval } from './eval.ts';
|
||||
import { runIndex } from './index-manager.ts';
|
||||
import { runLint, signalFor, statusClass, structuralPair } from './lint.ts';
|
||||
import { collectMetrics } from './metrics.ts';
|
||||
import {
|
||||
createMockProvider,
|
||||
createOpenAICompatibleProvider,
|
||||
ProviderError,
|
||||
resolveApiKey,
|
||||
} from './provider.ts';
|
||||
import { candidatePairs, topSimilar } from './similarity.ts';
|
||||
import { openStore } from './store.ts';
|
||||
import type { IndexConfig } from './config.ts';
|
||||
import type { IndexRunResult } from './index-manager.ts';
|
||||
import type { EvalReport, EvalSet } from './eval.ts';
|
||||
import type { EmbeddingProvider } from './provider.ts';
|
||||
import type { StatusClass } from './lint.ts';
|
||||
import type { Filters } from './similarity.ts';
|
||||
import type { Store } from './store.ts';
|
||||
import type { CardMetadata, IndexedCard, LintResult, SimilarHit } from './types.ts';
|
||||
|
||||
export const ExitCode = {
|
||||
Ok: 0,
|
||||
Findings: 1,
|
||||
Usage: 2,
|
||||
NotImplemented: 3,
|
||||
Internal: 4,
|
||||
} as const;
|
||||
|
||||
interface Parsed {
|
||||
positional: string[];
|
||||
values: Record<string, string[]>;
|
||||
flags: Set<string>;
|
||||
}
|
||||
|
||||
const VALUE_FLAGS = new Set([
|
||||
'--config',
|
||||
'--provider',
|
||||
'--top-k',
|
||||
'--threshold',
|
||||
'--limit',
|
||||
'--status',
|
||||
'--set',
|
||||
'--project',
|
||||
'--label',
|
||||
'--type',
|
||||
]);
|
||||
const BOOL_FLAGS = new Set(['--json', '--semantic', '--include-archived', '--duplicates']);
|
||||
|
||||
function parseArgs(argv: readonly string[]): Parsed | { error: string } {
|
||||
const parsed: Parsed = { positional: [], values: {}, flags: new Set<string>() };
|
||||
let index = 0;
|
||||
while (index < argv.length) {
|
||||
const arg = argv[index] ?? '';
|
||||
if (VALUE_FLAGS.has(arg)) {
|
||||
const value = argv[index + 1];
|
||||
if (value === undefined) {
|
||||
return { error: `Флаг ${arg} требует значения.` };
|
||||
}
|
||||
const bucket = parsed.values[arg] ?? [];
|
||||
bucket.push(value);
|
||||
parsed.values[arg] = bucket;
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
if (BOOL_FLAGS.has(arg)) {
|
||||
parsed.flags.add(arg);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--')) {
|
||||
return { error: `Неизвестный флаг ${arg}.` };
|
||||
}
|
||||
parsed.positional.push(arg);
|
||||
index += 1;
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function one(parsed: Parsed, flag: string, fallback: string): string {
|
||||
return parsed.values[flag]?.[0] ?? fallback;
|
||||
}
|
||||
|
||||
type FlagValue = { ok: true; value: number } | { ok: false; error: string };
|
||||
|
||||
function numberFlag(parsed: Parsed, flag: string, fallback: number): FlagValue {
|
||||
const raw = parsed.values[flag]?.[0];
|
||||
if (raw === undefined) {
|
||||
return { ok: true, value: fallback };
|
||||
}
|
||||
const value = Number(raw);
|
||||
if (Number.isFinite(value)) {
|
||||
return { ok: true, value };
|
||||
}
|
||||
return { ok: false, error: `Флаг ${flag} требует числа.` };
|
||||
}
|
||||
|
||||
function usageError(command: string, message: string): number {
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({ ok: false, command, error: { code: 'USAGE', message } }, null, 2)}\n`,
|
||||
);
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
|
||||
function emitError(command: string, code: string, message: string): void {
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({ ok: false, command, error: { code, message } }, null, 2)}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
function output(command: string, data: unknown, text: string, json: boolean): void {
|
||||
if (json) {
|
||||
process.stdout.write(`${JSON.stringify({ ok: true, command, data }, null, 2)}\n`);
|
||||
return;
|
||||
}
|
||||
process.stdout.write(`${text}\n`);
|
||||
}
|
||||
|
||||
function percent(value: number | null): string {
|
||||
return value === null ? '—' : `${(value * 100).toFixed(1)}%`;
|
||||
}
|
||||
|
||||
function optional(value: string | number | null): string {
|
||||
return value === null ? '—' : String(value);
|
||||
}
|
||||
|
||||
function usageText(): string {
|
||||
return [
|
||||
'bidx <command> [args]',
|
||||
' index sync|rebuild|status [--provider mock|configured] [--json]',
|
||||
' similar <ID> [--top-k N] [--status S] [--project P] [--label L] [--type T] [--include-archived] [--json]',
|
||||
' search "<text>" [--top-k N] [--status S] [--project P] [--label L] [--type T] [--provider mock|configured] [--json]',
|
||||
' duplicates [--threshold X] [--limit N] [--json]',
|
||||
' lint [--semantic] [--json]',
|
||||
' metrics [--json]',
|
||||
' eval [--top-k N] [--provider mock|configured] [--set <path>] [--json]',
|
||||
' calibrate [--provider mock|configured] [--set <path>] [--json]',
|
||||
' audit --duplicates L2-классификация: запланирована, не реализована',
|
||||
' --config <path> файл конфигурации (по умолчанию backlog-index.config.json)',
|
||||
'exit codes: 0 ok, 1 findings, 2 usage, 3 not implemented, 4 internal',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function buildProvider(config: IndexConfig, kind: string): EmbeddingProvider {
|
||||
if (kind === 'mock' || config.provider.kind === 'mock') {
|
||||
return createMockProvider(config.provider.dimensions);
|
||||
}
|
||||
const apiKey = resolveApiKey(config.provider.apiKeySources, config.baseDir);
|
||||
if (apiKey === null) {
|
||||
throw new ProviderError(
|
||||
'API_KEY_MISSING',
|
||||
'API key не найден: задайте переменную окружения или apiKeySources в конфигурации.',
|
||||
);
|
||||
}
|
||||
return createOpenAICompatibleProvider({
|
||||
endpoint: config.provider.endpoint,
|
||||
model: config.provider.model,
|
||||
apiKey,
|
||||
dimensions: config.provider.dimensions,
|
||||
batchSize: config.provider.batchSize,
|
||||
timeoutMs: config.provider.timeoutMs,
|
||||
retries: config.provider.retries,
|
||||
concurrency: config.provider.concurrency,
|
||||
retryDelayMs: config.provider.retryDelayMs,
|
||||
modelParams: config.provider.modelParams,
|
||||
});
|
||||
}
|
||||
|
||||
function openIndex(config: IndexConfig): Store {
|
||||
if (!existsSync(config.indexFile)) {
|
||||
throw new ProviderError('INDEX_MISSING', `Индекс не построен: ${config.indexFile}`);
|
||||
}
|
||||
return openStore({ file: config.indexFile });
|
||||
}
|
||||
|
||||
function filtersFrom(parsed: Parsed, includeArchived: boolean): Filters {
|
||||
const statuses = parsed.values['--status'] ?? [];
|
||||
const projects = parsed.values['--project'] ?? [];
|
||||
const labels = parsed.values['--label'] ?? [];
|
||||
const types = parsed.values['--type'] ?? [];
|
||||
const filters: Filters = {};
|
||||
if (statuses.length > 0) {
|
||||
filters.statuses = statuses;
|
||||
}
|
||||
if (projects.length > 0) {
|
||||
filters.projects = projects;
|
||||
}
|
||||
if (labels.length > 0) {
|
||||
filters.labels = labels;
|
||||
}
|
||||
if (types.length > 0) {
|
||||
filters.types = types;
|
||||
}
|
||||
if (!includeArchived) {
|
||||
filters.excludeArchived = true;
|
||||
}
|
||||
return filters;
|
||||
}
|
||||
|
||||
function classOf(metadata: CardMetadata, config: IndexConfig): StatusClass {
|
||||
return statusClass(metadata.status, metadata.archived, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Signal class of each hit, using the same rules as lint (D-064). A text search
|
||||
* has no card of its own, so the query is treated as a new active intent.
|
||||
*/
|
||||
function hitSignals(
|
||||
config: IndexConfig,
|
||||
cards: readonly IndexedCard[],
|
||||
hits: readonly SimilarHit[],
|
||||
source: IndexedCard | null,
|
||||
): (string | null)[] {
|
||||
const byId = new Map(cards.map((card) => [card.id, card]));
|
||||
return hits.map((hit) => {
|
||||
const other = byId.get(hit.id);
|
||||
if (other === undefined) {
|
||||
return null;
|
||||
}
|
||||
const classes: StatusClass[] = [
|
||||
source === null ? 'active' : classOf(source.metadata, config),
|
||||
classOf(other.metadata, config),
|
||||
];
|
||||
const structural =
|
||||
source !== null &&
|
||||
structuralPair(source.id, source.metadata.parentId, other.id, other.metadata.parentId);
|
||||
return signalFor(hit.score, classes, structural, config);
|
||||
});
|
||||
}
|
||||
|
||||
function hitsData(
|
||||
hits: readonly SimilarHit[],
|
||||
signals: readonly (string | null)[],
|
||||
): Record<string, unknown>[] {
|
||||
return hits.map((hit, index) => ({
|
||||
id: hit.id,
|
||||
title: hit.metadata.title,
|
||||
status: hit.metadata.status,
|
||||
score: hit.score,
|
||||
signal: signals[index] ?? null,
|
||||
path: hit.metadata.path,
|
||||
}));
|
||||
}
|
||||
|
||||
function hitLines(hits: readonly SimilarHit[], signals: readonly (string | null)[]): string {
|
||||
if (hits.length === 0) {
|
||||
return 'Совпадений нет.';
|
||||
}
|
||||
return hits
|
||||
.map((hit, index) => {
|
||||
const signal = signals[index] ?? null;
|
||||
return `${hit.score.toFixed(4)} ${hit.id} ${signal ?? '—'} ${hit.metadata.status} ${hit.metadata.title}`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function statusLines(config: IndexConfig, metrics: ReturnType<typeof collectMetrics>): string[] {
|
||||
return [
|
||||
`Индекс: ${config.indexFile}`,
|
||||
`Карточек: ${String(metrics.cards)} (актуальных ${String(metrics.current)}, устаревших ${String(metrics.stale)})`,
|
||||
`Вне индекса: ${String(metrics.missingFromIndex)}`,
|
||||
`Поставщик: ${optional(metrics.providerId)} / модель ${optional(metrics.modelId)} / размерность ${optional(metrics.dimensions ?? 0)}`,
|
||||
`Схемы: индекс ${String(metrics.indexVersion)}, нормализация ${optional(metrics.normVersion ?? 0)}`,
|
||||
`Размер: ${String(metrics.sizeBytes)} байт`,
|
||||
`Последняя синхронизация: ${optional(metrics.lastSyncAt)}`,
|
||||
`Переиспользовано embeddings: ${percent(metrics.reuseRatio)}`,
|
||||
];
|
||||
}
|
||||
|
||||
function renderStatus(config: IndexConfig, metrics: ReturnType<typeof collectMetrics>): string {
|
||||
return statusLines(config, metrics).join('\n');
|
||||
}
|
||||
|
||||
function renderSync(result: IndexRunResult): string {
|
||||
return [
|
||||
'Индекс синхронизирован.',
|
||||
`Карточек: ${String(result.cards)}`,
|
||||
`Пересчитано embeddings: ${String(result.embedded)}`,
|
||||
`Без изменений: ${String(result.reused)}`,
|
||||
`Только метаданные: ${String(result.metadataOnly)}`,
|
||||
`Удалено записей: ${String(result.removed)}`,
|
||||
`Запросов к поставщику: ${String(result.requests)}`,
|
||||
`Токенов входа: ${String(result.inputTokens)}`,
|
||||
`Время: ${String(result.durationMs)} мс`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function renderLint(result: LintResult): string {
|
||||
const lines: string[] = [];
|
||||
if (result.diagnostics.length === 0) {
|
||||
lines.push('Находок нет.');
|
||||
}
|
||||
for (const diagnostic of result.diagnostics) {
|
||||
lines.push(`${diagnostic.rule} [${diagnostic.level}] ${diagnostic.message}`);
|
||||
for (const item of diagnostic.findings) {
|
||||
const score = item.score === null ? '—' : item.score.toFixed(4);
|
||||
lines.push(` ${item.id} ${item.status} ${score} ${item.title}`);
|
||||
}
|
||||
}
|
||||
if (result.semanticUnavailable) {
|
||||
lines.push(`Семантический слой не выполнялся: ${result.semanticError ?? ''}`);
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
async function runIndexCommand(
|
||||
parsed: Parsed,
|
||||
config: IndexConfig,
|
||||
kind: 'sync' | 'rebuild' | 'status',
|
||||
): Promise<number> {
|
||||
if (kind === 'status') {
|
||||
const store = openIndex(config);
|
||||
const metrics = collectMetrics(store, config);
|
||||
store.close();
|
||||
output('index', metrics, renderStatus(config, metrics), parsed.flags.has('--json'));
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
const store = openStore({ file: config.indexFile });
|
||||
try {
|
||||
const provider = buildProvider(config, one(parsed, '--provider', 'configured'));
|
||||
const result = await runIndex({ kind, config, provider, store });
|
||||
output('index', result, renderSync(result), parsed.flags.has('--json'));
|
||||
return ExitCode.Ok;
|
||||
} finally {
|
||||
store.close();
|
||||
}
|
||||
}
|
||||
|
||||
function runLintCommand(parsed: Parsed, config: IndexConfig): number {
|
||||
const semantic = parsed.flags.has('--semantic');
|
||||
const store =
|
||||
semantic && existsSync(config.indexFile) ? openStore({ file: config.indexFile }) : undefined;
|
||||
const result = runLint({ config, semantic, store });
|
||||
store?.close();
|
||||
output(
|
||||
'lint',
|
||||
{
|
||||
semantic: result.semantic,
|
||||
semantic_unavailable: result.semanticUnavailable,
|
||||
semantic_error: result.semanticError,
|
||||
diagnostics: result.diagnostics,
|
||||
},
|
||||
renderLint(result),
|
||||
parsed.flags.has('--json'),
|
||||
);
|
||||
return result.ok ? ExitCode.Ok : ExitCode.Findings;
|
||||
}
|
||||
|
||||
function runDuplicates(parsed: Parsed, config: IndexConfig): number {
|
||||
const threshold = numberFlag(parsed, '--threshold', config.thresholds.duplicate);
|
||||
if (!threshold.ok) {
|
||||
return usageError('duplicates', threshold.error);
|
||||
}
|
||||
const limit = numberFlag(parsed, '--limit', 50);
|
||||
if (!limit.ok) {
|
||||
return usageError('duplicates', limit.error);
|
||||
}
|
||||
const store = openIndex(config);
|
||||
const cards = store.loadCards();
|
||||
store.close();
|
||||
const pairs = candidatePairs(cards, { threshold: threshold.value, limit: limit.value });
|
||||
const pairsOut = pairs.map((pair) => ({
|
||||
...pair,
|
||||
signal: signalFor(
|
||||
pair.score,
|
||||
[classOf(pair.leftMetadata, config), classOf(pair.rightMetadata, config)],
|
||||
structuralPair(
|
||||
pair.left,
|
||||
pair.leftMetadata.parentId,
|
||||
pair.right,
|
||||
pair.rightMetadata.parentId,
|
||||
),
|
||||
config,
|
||||
),
|
||||
}));
|
||||
const lines = pairsOut.map(
|
||||
(pair) =>
|
||||
`${pair.score.toFixed(4)} ${pair.signal ?? '—'} ${pair.left} (${pair.leftMetadata.status}) ↔ ${pair.right} (${pair.rightMetadata.status})`,
|
||||
);
|
||||
output(
|
||||
'duplicates',
|
||||
{ threshold: threshold.value, limit: limit.value, pairs: pairsOut },
|
||||
lines.length === 0 ? `Пар выше порога ${threshold.value.toFixed(2)} нет.` : lines.join('\n'),
|
||||
parsed.flags.has('--json'),
|
||||
);
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
async function runSearch(parsed: Parsed, config: IndexConfig): Promise<number> {
|
||||
const query = parsed.positional[0];
|
||||
if (query === undefined) {
|
||||
return usageError('search', 'search требует текст запроса.');
|
||||
}
|
||||
const topK = numberFlag(parsed, '--top-k', config.topK);
|
||||
if (!topK.ok) {
|
||||
return usageError('search', topK.error);
|
||||
}
|
||||
const store = openIndex(config);
|
||||
try {
|
||||
const provider = buildProvider(config, one(parsed, '--provider', 'configured'));
|
||||
const call = await provider.embed([query]);
|
||||
const vector = new Float32Array(call.vectors[0] ?? []);
|
||||
const cards = store.loadCards();
|
||||
const hits = topSimilar(cards, vector, {
|
||||
topK: topK.value,
|
||||
filters: filtersFrom(parsed, parsed.flags.has('--include-archived')),
|
||||
});
|
||||
const signals = hitSignals(config, cards, hits, null);
|
||||
output(
|
||||
'search',
|
||||
{ query, top_k: topK.value, hits: hitsData(hits, signals) },
|
||||
hitLines(hits, signals),
|
||||
parsed.flags.has('--json'),
|
||||
);
|
||||
return ExitCode.Ok;
|
||||
} finally {
|
||||
store.close();
|
||||
}
|
||||
}
|
||||
|
||||
function runSimilar(parsed: Parsed, config: IndexConfig): number {
|
||||
const id = parsed.positional[0];
|
||||
if (id === undefined) {
|
||||
return usageError('similar', 'similar требует идентификатор карточки.');
|
||||
}
|
||||
const topK = numberFlag(parsed, '--top-k', config.topK);
|
||||
if (!topK.ok) {
|
||||
return usageError('similar', topK.error);
|
||||
}
|
||||
const store = openIndex(config);
|
||||
const source = store.loadCard(id);
|
||||
if (source === undefined) {
|
||||
store.close();
|
||||
emitError('similar', 'NOT_FOUND', `Карточка ${id} не найдена в индексе.`);
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const filters = filtersFrom(parsed, parsed.flags.has('--include-archived'));
|
||||
filters.excludeIds = [id];
|
||||
const cards = store.loadCards();
|
||||
const hits = topSimilar(cards, source.vector, { topK: topK.value, filters });
|
||||
const signals = hitSignals(config, cards, hits, source);
|
||||
store.close();
|
||||
output(
|
||||
'similar',
|
||||
{ id, top_k: topK.value, hits: hitsData(hits, signals) },
|
||||
hitLines(hits, signals),
|
||||
parsed.flags.has('--json'),
|
||||
);
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function runMetrics(parsed: Parsed, config: IndexConfig): number {
|
||||
const store = openIndex(config);
|
||||
const metrics = collectMetrics(store, config);
|
||||
store.close();
|
||||
const last = metrics.lastRun;
|
||||
const duration = last === null ? null : `${String(last.durationMs)} мс`;
|
||||
const requests = last === null ? null : last.requests;
|
||||
const tokens = last === null ? null : last.inputTokens;
|
||||
const lines = statusLines(config, metrics);
|
||||
lines.push(`Последний прогон: ${optional(last === null ? null : last.kind)}`);
|
||||
lines.push(`Время прогона: ${optional(duration)}`);
|
||||
lines.push(`Запросов к поставщику: ${optional(requests)}`);
|
||||
lines.push(`Токенов входа: ${optional(tokens)}`);
|
||||
output('metrics', metrics, lines.join('\n'), parsed.flags.has('--json'));
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function readEvalSet(file: string): EvalSet | { error: string } {
|
||||
if (!existsSync(file)) {
|
||||
return { error: `Файл eval-набора не найден: ${file}` };
|
||||
}
|
||||
let text: string;
|
||||
try {
|
||||
text = readFileSync(file, 'utf8');
|
||||
} catch (cause) {
|
||||
return { error: `Eval-набор не читается: ${cause instanceof Error ? cause.message : file}` };
|
||||
}
|
||||
try {
|
||||
return parseEvalSet(JSON.parse(text));
|
||||
} catch (cause) {
|
||||
if (cause instanceof EvalSetError) {
|
||||
return { error: cause.message };
|
||||
}
|
||||
return { error: `Eval-набор не является JSON: ${file}` };
|
||||
}
|
||||
}
|
||||
|
||||
function boundaryLine(report: EvalReport, index: number): string {
|
||||
const boundary = report.boundaries[index];
|
||||
if (boundary === undefined) {
|
||||
return '';
|
||||
}
|
||||
const best = boundary.best;
|
||||
return [
|
||||
`Граница ${boundary.boundary}: порог ${best.threshold.toFixed(2)}`,
|
||||
`precision ${best.precision.toFixed(3)}`,
|
||||
`recall ${best.recall.toFixed(3)}`,
|
||||
`F1 ${best.f1.toFixed(3)}`,
|
||||
].join(', ');
|
||||
}
|
||||
|
||||
function boundaryText(report: EvalReport): string {
|
||||
return [
|
||||
`Набор: ${String(report.cards)} карточек, поставщик ${report.provider.model}`,
|
||||
boundaryLine(report, 0),
|
||||
boundaryLine(report, 1),
|
||||
boundaryLine(report, 2),
|
||||
`Precision@k: ${optional(report.averages.precisionAtK)}`,
|
||||
`Recall@k: ${optional(report.averages.recallAtK)}`,
|
||||
]
|
||||
.filter((item) => item !== '')
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
async function runEvalCommand(
|
||||
parsed: Parsed,
|
||||
config: IndexConfig,
|
||||
command: string,
|
||||
): Promise<number> {
|
||||
const topK = numberFlag(parsed, '--top-k', config.topK);
|
||||
if (!topK.ok) {
|
||||
return usageError(command, topK.error);
|
||||
}
|
||||
const setPath = one(parsed, '--set', path.join(import.meta.dirname, '..', 'eval', 'labels.json'));
|
||||
const evalSet = readEvalSet(
|
||||
path.isAbsolute(setPath) ? setPath : path.resolve(process.cwd(), setPath),
|
||||
);
|
||||
if ('error' in evalSet) {
|
||||
emitError(command, 'EVAL_SET', evalSet.error);
|
||||
return ExitCode.Internal;
|
||||
}
|
||||
const provider = buildProvider(config, one(parsed, '--provider', 'mock'));
|
||||
const report = await runEval(evalSet, provider, config, { topK: topK.value });
|
||||
output(command, report, boundaryText(report), parsed.flags.has('--json'));
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
export async function run(argv: readonly string[]): Promise<number> {
|
||||
const [command, ...rest] = argv;
|
||||
if (command === undefined) {
|
||||
process.stdout.write(`${usageText()}\n`);
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const parsed = parseArgs(rest);
|
||||
if ('error' in parsed) {
|
||||
emitError(command, 'USAGE', parsed.error);
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
try {
|
||||
const config = loadConfig(parsed.values['--config']?.[0]);
|
||||
switch (command) {
|
||||
case 'index': {
|
||||
const kind = parsed.positional[0];
|
||||
if (kind !== 'sync' && kind !== 'rebuild' && kind !== 'status') {
|
||||
return usageError(command, 'index требует sync, rebuild или status.');
|
||||
}
|
||||
return await runIndexCommand(parsed, config, kind);
|
||||
}
|
||||
case 'similar':
|
||||
return runSimilar(parsed, config);
|
||||
case 'search':
|
||||
return await runSearch(parsed, config);
|
||||
case 'duplicates':
|
||||
return runDuplicates(parsed, config);
|
||||
case 'lint':
|
||||
return runLintCommand(parsed, config);
|
||||
case 'metrics':
|
||||
return runMetrics(parsed, config);
|
||||
case 'eval':
|
||||
case 'calibrate':
|
||||
return await runEvalCommand(parsed, config, command);
|
||||
case 'audit':
|
||||
emitError(
|
||||
command,
|
||||
'NOT_IMPLEMENTED',
|
||||
'L2-классификация пересечений запланирована и не реализована.',
|
||||
);
|
||||
return ExitCode.NotImplemented;
|
||||
default:
|
||||
process.stdout.write(`${usageText()}\n`);
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
} catch (cause) {
|
||||
return reportError(command, cause);
|
||||
}
|
||||
}
|
||||
|
||||
function reportError(command: string, cause: unknown): number {
|
||||
if (cause instanceof ProviderError || cause instanceof ConfigError) {
|
||||
emitError(command, cause.code, cause.message);
|
||||
return ExitCode.Internal;
|
||||
}
|
||||
const message = cause instanceof Error ? cause.message : 'неизвестная ошибка';
|
||||
emitError(command, 'INTERNAL', message);
|
||||
return ExitCode.Internal;
|
||||
}
|
||||
|
||||
export function isMainModule(): boolean {
|
||||
return process.argv[1] !== undefined && path.resolve(process.argv[1]) === import.meta.filename;
|
||||
}
|
||||
|
||||
if (isMainModule()) {
|
||||
process.exitCode = await run(process.argv.slice(2));
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import type { ApiKeySource } from './provider.ts';
|
||||
|
||||
export class ConfigError extends Error {
|
||||
readonly code: string;
|
||||
constructor(code: string, message: string) {
|
||||
super(message);
|
||||
this.name = 'ConfigError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ProviderConfig {
|
||||
kind: 'mock' | 'openai-compatible';
|
||||
endpoint: string;
|
||||
model: string;
|
||||
apiKeySources: ApiKeySource[];
|
||||
dimensions: number;
|
||||
batchSize: number;
|
||||
timeoutMs: number;
|
||||
retries: number;
|
||||
concurrency: number;
|
||||
retryDelayMs: number;
|
||||
modelParams: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface Thresholds {
|
||||
duplicate: number;
|
||||
overlap: number;
|
||||
related: number;
|
||||
}
|
||||
|
||||
export interface StatusClasses {
|
||||
active: string[];
|
||||
done: string[];
|
||||
skipped: string[];
|
||||
}
|
||||
|
||||
export interface IndexConfig {
|
||||
/** Directory the config was read from; relative paths resolve against it. */
|
||||
baseDir: string;
|
||||
repoRoot: string;
|
||||
backlogDir: string;
|
||||
indexFile: string;
|
||||
provider: ProviderConfig;
|
||||
thresholds: Thresholds;
|
||||
topK: number;
|
||||
statusClasses: StatusClasses;
|
||||
}
|
||||
|
||||
export const DEFAULT_CONFIG_FILE = 'backlog-index.config.json';
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string, fallback: string): string {
|
||||
const value = source[key];
|
||||
if (typeof value === 'string' && value !== '') {
|
||||
return value;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function readNumber(source: Record<string, unknown>, key: string, fallback: number): number {
|
||||
const value = source[key];
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return value;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function readStringList(
|
||||
source: Record<string, unknown>,
|
||||
key: string,
|
||||
fallback: string[],
|
||||
): string[] {
|
||||
const value = source[key];
|
||||
if (Array.isArray(value)) {
|
||||
return value.filter((item): item is string => typeof item === 'string' && item !== '');
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function readApiKeySources(value: unknown): ApiKeySource[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return [{ kind: 'env', name: 'BHL_EMBEDDINGS_API_KEY' }];
|
||||
}
|
||||
const sources: ApiKeySource[] = [];
|
||||
for (const item of value) {
|
||||
if (!isRecord(item)) {
|
||||
continue;
|
||||
}
|
||||
if (item['kind'] === 'env' && typeof item['name'] === 'string') {
|
||||
sources.push({ kind: 'env', name: item['name'] });
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
item['kind'] === 'json-file' &&
|
||||
typeof item['path'] === 'string' &&
|
||||
typeof item['selector'] === 'string'
|
||||
) {
|
||||
sources.push({ kind: 'json-file', path: item['path'], selector: item['selector'] });
|
||||
}
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
|
||||
function resolvePath(baseDir: string, value: string): string {
|
||||
return path.isAbsolute(value) ? path.normalize(value) : path.resolve(baseDir, value);
|
||||
}
|
||||
|
||||
/** Reads the experiment configuration; every value has a documented default. */
|
||||
export function loadConfig(explicitPath?: string): IndexConfig {
|
||||
const defaultDir = path.resolve(import.meta.dirname, '..');
|
||||
const file =
|
||||
explicitPath === undefined
|
||||
? path.join(defaultDir, DEFAULT_CONFIG_FILE)
|
||||
: resolvePath(process.cwd(), explicitPath);
|
||||
if (!existsSync(file)) {
|
||||
throw new ConfigError('CONFIG_MISSING', `Файл конфигурации не найден: ${file}`);
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(file, 'utf8'));
|
||||
} catch {
|
||||
throw new ConfigError('CONFIG_MALFORMED', `Файл конфигурации не является JSON: ${file}`);
|
||||
}
|
||||
if (!isRecord(parsed)) {
|
||||
throw new ConfigError('CONFIG_MALFORMED', 'Файл конфигурации должен быть объектом.');
|
||||
}
|
||||
const baseDir = path.dirname(path.resolve(file));
|
||||
const providerRaw = isRecord(parsed['provider']) ? parsed['provider'] : {};
|
||||
const thresholdsRaw = isRecord(parsed['thresholds']) ? parsed['thresholds'] : {};
|
||||
const statusRaw = isRecord(parsed['statusClasses']) ? parsed['statusClasses'] : {};
|
||||
const kind = readString(providerRaw, 'kind', 'openai-compatible');
|
||||
if (kind !== 'mock' && kind !== 'openai-compatible') {
|
||||
throw new ConfigError(
|
||||
'CONFIG_MALFORMED',
|
||||
'provider.kind должен быть mock или openai-compatible.',
|
||||
);
|
||||
}
|
||||
const modelParams = isRecord(providerRaw['modelParams']) ? providerRaw['modelParams'] : {};
|
||||
return {
|
||||
baseDir,
|
||||
repoRoot: resolvePath(baseDir, readString(parsed, 'repoRoot', '../..')),
|
||||
backlogDir: resolvePath(baseDir, readString(parsed, 'backlogDir', '../../backlog')),
|
||||
indexFile: resolvePath(
|
||||
baseDir,
|
||||
readString(parsed, 'indexFile', '../../.artifacts/backlog-index/index.sqlite'),
|
||||
),
|
||||
provider: {
|
||||
kind,
|
||||
endpoint: readString(providerRaw, 'endpoint', ''),
|
||||
model: readString(providerRaw, 'model', ''),
|
||||
apiKeySources: readApiKeySources(providerRaw['apiKeySources']),
|
||||
dimensions: readNumber(providerRaw, 'dimensions', 1024),
|
||||
batchSize: readNumber(providerRaw, 'batchSize', 16),
|
||||
timeoutMs: readNumber(providerRaw, 'timeoutMs', 30000),
|
||||
retries: readNumber(providerRaw, 'retries', 3),
|
||||
concurrency: readNumber(providerRaw, 'concurrency', 2),
|
||||
retryDelayMs: readNumber(providerRaw, 'retryDelayMs', 500),
|
||||
modelParams,
|
||||
},
|
||||
thresholds: {
|
||||
duplicate: readNumber(thresholdsRaw, 'duplicate', 0.9),
|
||||
overlap: readNumber(thresholdsRaw, 'overlap', 0.8),
|
||||
related: readNumber(thresholdsRaw, 'related', 0.7),
|
||||
},
|
||||
topK: readNumber(parsed, 'topK', 10),
|
||||
statusClasses: {
|
||||
active: readStringList(statusRaw, 'active', ['To Do', 'In Progress']),
|
||||
done: readStringList(statusRaw, 'done', ['Done']),
|
||||
skipped: readStringList(statusRaw, 'skipped', []),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
import { openStore } from './store.ts';
|
||||
import { runIndex } from './index-manager.ts';
|
||||
import { hashText } from './normalize.ts';
|
||||
import { readCards } from './reader.ts';
|
||||
import { cosine, topSimilar } from './similarity.ts';
|
||||
import type { EmbeddingProvider } from './provider.ts';
|
||||
import type { IndexConfig } from './config.ts';
|
||||
import type { IndexedCard, TaskCard } from './types.ts';
|
||||
|
||||
export type PairLabel = 'duplicate' | 'overlap' | 'related' | 'unrelated';
|
||||
|
||||
export interface EvalCardSpec {
|
||||
id: string;
|
||||
/** `backlog` reads the live card; `inline` keeps the text inside the set. */
|
||||
source: 'backlog' | 'inline';
|
||||
title?: string;
|
||||
description?: string;
|
||||
acceptanceCriteria?: string[];
|
||||
status?: string;
|
||||
}
|
||||
|
||||
export interface EvalPair {
|
||||
a: string;
|
||||
b: string;
|
||||
label: PairLabel;
|
||||
}
|
||||
|
||||
export interface EvalQuery {
|
||||
id?: string;
|
||||
text?: string;
|
||||
relevant: string[];
|
||||
}
|
||||
|
||||
export interface EvalSet {
|
||||
version: number;
|
||||
cards: EvalCardSpec[];
|
||||
pairs: EvalPair[];
|
||||
queries: EvalQuery[];
|
||||
}
|
||||
|
||||
export interface PairScore {
|
||||
a: string;
|
||||
b: string;
|
||||
label: PairLabel;
|
||||
score: number;
|
||||
}
|
||||
|
||||
export interface BoundaryPoint {
|
||||
threshold: number;
|
||||
precision: number;
|
||||
recall: number;
|
||||
f1: number;
|
||||
}
|
||||
|
||||
export type BoundaryName = 'duplicate' | 'overlap' | 'related';
|
||||
|
||||
export interface BoundaryReport {
|
||||
boundary: BoundaryName;
|
||||
positives: PairLabel[];
|
||||
best: BoundaryPoint;
|
||||
curve: BoundaryPoint[];
|
||||
}
|
||||
|
||||
export interface QueryHit {
|
||||
id: string;
|
||||
score: number;
|
||||
label: PairLabel | null;
|
||||
}
|
||||
|
||||
export interface QueryReport {
|
||||
query: string;
|
||||
topK: number;
|
||||
relevant: string[];
|
||||
hits: QueryHit[];
|
||||
precision: number;
|
||||
recall: number;
|
||||
}
|
||||
|
||||
export interface EvalReport {
|
||||
provider: { id: string; model: string; dimensions: number };
|
||||
cards: number;
|
||||
pairs: PairScore[];
|
||||
boundaries: BoundaryReport[];
|
||||
queries: QueryReport[];
|
||||
averages: { precisionAtK: number | null; recallAtK: number | null };
|
||||
}
|
||||
|
||||
const BOUNDARIES: { boundary: BoundaryName; positives: PairLabel[] }[] = [
|
||||
{ boundary: 'duplicate', positives: ['duplicate'] },
|
||||
{ boundary: 'overlap', positives: ['duplicate', 'overlap'] },
|
||||
{ boundary: 'related', positives: ['duplicate', 'overlap', 'related'] },
|
||||
];
|
||||
|
||||
function pairKey(a: string, b: string): string {
|
||||
return a <= b ? `${a}\u0000${b}` : `${b}\u0000${a}`;
|
||||
}
|
||||
|
||||
interface InlineSpec {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string | undefined;
|
||||
acceptanceCriteria?: string[] | undefined;
|
||||
status?: string | undefined;
|
||||
}
|
||||
|
||||
function inlineCard(spec: InlineSpec): TaskCard {
|
||||
const title = spec.title;
|
||||
const description = spec.description ?? '';
|
||||
const acceptanceCriteria = spec.acceptanceCriteria ?? [];
|
||||
const text = [title, description, ...acceptanceCriteria].join('\n');
|
||||
return {
|
||||
id: spec.id,
|
||||
title,
|
||||
status: spec.status ?? 'To Do',
|
||||
archived: false,
|
||||
path: `eval/${spec.id}`,
|
||||
type: null,
|
||||
priority: null,
|
||||
project: 'eval',
|
||||
labels: ['eval'],
|
||||
milestone: null,
|
||||
parentId: null,
|
||||
dependencies: [],
|
||||
description,
|
||||
acceptanceCriteria,
|
||||
fileHash: hashText(text),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildCorpus(
|
||||
evalSet: EvalSet,
|
||||
config: IndexConfig,
|
||||
): { cards: TaskCard[]; errors: string[] } {
|
||||
const backlog = readCards({ repoRoot: config.repoRoot, backlogDir: config.backlogDir });
|
||||
const byId = new Map(backlog.cards.map((card) => [card.id, card]));
|
||||
const cards: TaskCard[] = [];
|
||||
const errors: string[] = [];
|
||||
for (const spec of evalSet.cards) {
|
||||
if (spec.source === 'inline') {
|
||||
cards.push(
|
||||
inlineCard({
|
||||
id: spec.id,
|
||||
title: spec.title ?? '',
|
||||
description: spec.description,
|
||||
acceptanceCriteria: spec.acceptanceCriteria,
|
||||
status: spec.status,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const card = byId.get(spec.id);
|
||||
if (card === undefined) {
|
||||
errors.push(`Карточка ${spec.id} из eval-набора не найдена в бэклоге.`);
|
||||
continue;
|
||||
}
|
||||
cards.push(card);
|
||||
}
|
||||
return { cards, errors };
|
||||
}
|
||||
|
||||
function boundaryPoint(
|
||||
scores: readonly PairScore[],
|
||||
positives: readonly PairLabel[],
|
||||
threshold: number,
|
||||
): BoundaryPoint {
|
||||
let truePositive = 0;
|
||||
let falsePositive = 0;
|
||||
let falseNegative = 0;
|
||||
for (const pair of scores) {
|
||||
const predicted = pair.score >= threshold;
|
||||
const actual = positives.includes(pair.label);
|
||||
if (predicted && actual) {
|
||||
truePositive += 1;
|
||||
} else if (predicted) {
|
||||
falsePositive += 1;
|
||||
} else if (actual) {
|
||||
falseNegative += 1;
|
||||
}
|
||||
}
|
||||
const precision = precisionOf(truePositive, falsePositive);
|
||||
const recall = recallOf(truePositive, falseNegative);
|
||||
return {
|
||||
threshold,
|
||||
precision,
|
||||
recall,
|
||||
f1:
|
||||
precision + recall === 0
|
||||
? 0
|
||||
: Number(((2 * precision * recall) / (precision + recall)).toFixed(4)),
|
||||
};
|
||||
}
|
||||
|
||||
function precisionOf(truePositive: number, falsePositive: number): number {
|
||||
return truePositive + falsePositive === 0
|
||||
? 0
|
||||
: Number((truePositive / (truePositive + falsePositive)).toFixed(4));
|
||||
}
|
||||
|
||||
function recallOf(truePositive: number, falseNegative: number): number {
|
||||
return truePositive + falseNegative === 0
|
||||
? 0
|
||||
: Number((truePositive / (truePositive + falseNegative)).toFixed(4));
|
||||
}
|
||||
|
||||
function bestPoint(curve: readonly BoundaryPoint[]): BoundaryPoint {
|
||||
let best = curve[0] ?? { threshold: 0.5, precision: 0, recall: 0, f1: 0 };
|
||||
for (const point of curve) {
|
||||
if (point.f1 > best.f1 || (point.f1 === best.f1 && point.threshold > best.threshold)) {
|
||||
best = point;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function sweep(
|
||||
scores: readonly PairScore[],
|
||||
positives: readonly PairLabel[],
|
||||
): { best: BoundaryPoint; curve: BoundaryPoint[] } {
|
||||
const curve: BoundaryPoint[] = [];
|
||||
for (let step = 50; step <= 99; step += 1) {
|
||||
curve.push(boundaryPoint(scores, positives, step / 100));
|
||||
}
|
||||
return { best: bestPoint(curve), curve };
|
||||
}
|
||||
|
||||
function scorePairs(pairs: readonly EvalPair[], byId: Map<string, IndexedCard>): PairScore[] {
|
||||
const scores: PairScore[] = [];
|
||||
for (const pair of pairs) {
|
||||
const left = byId.get(pair.a);
|
||||
const right = byId.get(pair.b);
|
||||
if (left === undefined || right === undefined) {
|
||||
continue;
|
||||
}
|
||||
scores.push({
|
||||
a: pair.a,
|
||||
b: pair.b,
|
||||
label: pair.label,
|
||||
score: Number(cosine(left.vector, right.vector).toFixed(6)),
|
||||
});
|
||||
}
|
||||
return scores;
|
||||
}
|
||||
|
||||
async function embedQuery(query: EvalQuery, provider: EmbeddingProvider): Promise<Float32Array> {
|
||||
const call = await provider.embed([query.text ?? '']);
|
||||
return new Float32Array(call.vectors[0] ?? []);
|
||||
}
|
||||
|
||||
function queryReport(
|
||||
query: EvalQuery,
|
||||
vector: Float32Array,
|
||||
indexed: readonly IndexedCard[],
|
||||
labels: Map<string, PairLabel>,
|
||||
topK: number,
|
||||
): QueryReport {
|
||||
const hits = topSimilar(indexed, vector, {
|
||||
topK,
|
||||
filters: { excludeIds: query.id === undefined ? [] : [query.id] },
|
||||
});
|
||||
const relevant = new Set(query.relevant);
|
||||
const reportHits: QueryHit[] = [];
|
||||
let matched = 0;
|
||||
for (const hit of hits) {
|
||||
const label = query.id === undefined ? null : (labels.get(pairKey(query.id, hit.id)) ?? null);
|
||||
if (relevant.has(hit.id)) {
|
||||
matched += 1;
|
||||
}
|
||||
reportHits.push({ id: hit.id, score: hit.score, label });
|
||||
}
|
||||
return {
|
||||
query: query.id ?? query.text ?? '',
|
||||
topK,
|
||||
relevant: query.relevant,
|
||||
hits: reportHits,
|
||||
precision: precisionOf(matched, hits.length - matched),
|
||||
recall: recallOf(matched, query.relevant.length - matched),
|
||||
};
|
||||
}
|
||||
|
||||
async function runQueries(
|
||||
evalSet: EvalSet,
|
||||
byId: Map<string, IndexedCard>,
|
||||
indexed: readonly IndexedCard[],
|
||||
provider: EmbeddingProvider,
|
||||
labels: Map<string, PairLabel>,
|
||||
topK: number,
|
||||
): Promise<QueryReport[]> {
|
||||
const reports: QueryReport[] = [];
|
||||
for (const query of evalSet.queries) {
|
||||
const source = query.id === undefined ? undefined : byId.get(query.id);
|
||||
const vector = source !== undefined ? source.vector : await embedQuery(query, provider);
|
||||
reports.push(queryReport(query, vector, indexed, labels, topK));
|
||||
}
|
||||
return reports;
|
||||
}
|
||||
|
||||
export interface EvalOptions {
|
||||
topK: number;
|
||||
/** Set to false to skip query ranking and keep only the calibration sweep. */
|
||||
queries?: boolean | undefined;
|
||||
}
|
||||
|
||||
export async function runEval(
|
||||
evalSet: EvalSet,
|
||||
provider: EmbeddingProvider,
|
||||
config: IndexConfig,
|
||||
options: EvalOptions,
|
||||
): Promise<EvalReport> {
|
||||
const corpus = buildCorpus(evalSet, config);
|
||||
const store = openStore({ file: ':memory:' });
|
||||
await runIndex({ kind: 'rebuild', config, provider, store, cards: corpus.cards });
|
||||
const indexed = store.loadCards();
|
||||
store.close();
|
||||
const byId = new Map<string, IndexedCard>(indexed.map((card) => [card.id, card]));
|
||||
const labels = new Map<string, PairLabel>();
|
||||
for (const pair of evalSet.pairs) {
|
||||
labels.set(pairKey(pair.a, pair.b), pair.label);
|
||||
}
|
||||
const scores = scorePairs(evalSet.pairs, byId);
|
||||
const boundaries: BoundaryReport[] = BOUNDARIES.map((entry) => {
|
||||
const result = sweep(scores, entry.positives);
|
||||
return {
|
||||
boundary: entry.boundary,
|
||||
positives: entry.positives,
|
||||
best: result.best,
|
||||
curve: result.curve,
|
||||
};
|
||||
});
|
||||
const queries =
|
||||
options.queries === false
|
||||
? []
|
||||
: await runQueries(evalSet, byId, indexed, provider, labels, options.topK);
|
||||
const average = (values: number[]): number | null =>
|
||||
values.length === 0
|
||||
? null
|
||||
: Number((values.reduce((sum, value) => sum + value, 0) / values.length).toFixed(4));
|
||||
return {
|
||||
provider: { id: provider.id, model: provider.model, dimensions: provider.dimensions },
|
||||
cards: indexed.length,
|
||||
pairs: scores,
|
||||
boundaries,
|
||||
queries,
|
||||
averages: {
|
||||
precisionAtK: average(queries.map((item) => item.precision)),
|
||||
recallAtK: average(queries.map((item) => item.recall)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export class EvalSetError extends Error {
|
||||
readonly code: string;
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'EvalSetError';
|
||||
this.code = 'EVAL_SET';
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isLabel(value: unknown): value is PairLabel {
|
||||
return (
|
||||
value === 'duplicate' || value === 'overlap' || value === 'related' || value === 'unrelated'
|
||||
);
|
||||
}
|
||||
|
||||
function isStringArray(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every((item): item is string => typeof item === 'string');
|
||||
}
|
||||
|
||||
function requireRecord(value: unknown, what: string): Record<string, unknown> {
|
||||
if (!isRecord(value)) {
|
||||
throw new EvalSetError(`${what} должен быть объектом.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function requireString(value: unknown, what: string): string {
|
||||
if (typeof value !== 'string' || value === '') {
|
||||
throw new EvalSetError(`${what} должен быть непустой строкой.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function optionalString(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value !== '' ? value : undefined;
|
||||
}
|
||||
|
||||
function parseCard(raw: unknown): EvalCardSpec {
|
||||
const item = requireRecord(raw, 'карточка eval-набора');
|
||||
const source = item['source'];
|
||||
if (source !== 'backlog' && source !== 'inline') {
|
||||
throw new EvalSetError('source карточки eval-набора должен быть backlog или inline.');
|
||||
}
|
||||
const spec: EvalCardSpec = { id: requireString(item['id'], 'id карточки eval-набора'), source };
|
||||
const title = optionalString(item['title']);
|
||||
if (title !== undefined) {
|
||||
spec.title = title;
|
||||
}
|
||||
const description = optionalString(item['description']);
|
||||
if (description !== undefined) {
|
||||
spec.description = description;
|
||||
}
|
||||
const status = optionalString(item['status']);
|
||||
if (status !== undefined) {
|
||||
spec.status = status;
|
||||
}
|
||||
if (isStringArray(item['acceptanceCriteria'])) {
|
||||
spec.acceptanceCriteria = item['acceptanceCriteria'];
|
||||
}
|
||||
return spec;
|
||||
}
|
||||
|
||||
function parsePair(raw: unknown): EvalPair {
|
||||
const item = requireRecord(raw, 'пара eval-набора');
|
||||
const label = item['label'];
|
||||
if (!isLabel(label)) {
|
||||
throw new EvalSetError(
|
||||
'label пары eval-набора должен быть duplicate, overlap, related или unrelated.',
|
||||
);
|
||||
}
|
||||
return { a: requireString(item['a'], 'a пары'), b: requireString(item['b'], 'b пары'), label };
|
||||
}
|
||||
|
||||
function parseQuery(raw: unknown): EvalQuery {
|
||||
const item = requireRecord(raw, 'запрос eval-набора');
|
||||
if (!isStringArray(item['relevant'])) {
|
||||
throw new EvalSetError('relevant запроса eval-набора должен быть списком идентификаторов.');
|
||||
}
|
||||
const query: EvalQuery = { relevant: item['relevant'] };
|
||||
const id = optionalString(item['id']);
|
||||
if (id !== undefined) {
|
||||
query.id = id;
|
||||
}
|
||||
const text = optionalString(item['text']);
|
||||
if (text !== undefined) {
|
||||
query.text = text;
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
/** Validates an eval set read from disk without trusting its JSON shape. */
|
||||
export function parseEvalSet(value: unknown): EvalSet {
|
||||
const root = requireRecord(value, 'eval-набор');
|
||||
const version = root['version'];
|
||||
if (typeof version !== 'number' || !Number.isInteger(version)) {
|
||||
throw new EvalSetError('version eval-набора должен быть целым числом.');
|
||||
}
|
||||
const { cards, pairs, queries } = {
|
||||
cards: root['cards'],
|
||||
pairs: root['pairs'],
|
||||
queries: root['queries'],
|
||||
};
|
||||
if (!Array.isArray(cards) || !Array.isArray(pairs) || !Array.isArray(queries)) {
|
||||
throw new EvalSetError('cards, pairs и queries eval-набора должны быть списками.');
|
||||
}
|
||||
return {
|
||||
version,
|
||||
cards: cards.map(parseCard),
|
||||
pairs: pairs.map(parsePair),
|
||||
queries: queries.map(parseQuery),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { NORM_VERSION, normalizeIntent } from './normalize.ts';
|
||||
import { readCards } from './reader.ts';
|
||||
import { INDEX_VERSION } from './store.ts';
|
||||
import type { EmbeddingProvider } from './provider.ts';
|
||||
import type { Store } from './store.ts';
|
||||
import type { IndexConfig } from './config.ts';
|
||||
import type { IndexedCard, SyncCounters, TaskCard } from './types.ts';
|
||||
|
||||
export interface IndexRunOptions {
|
||||
kind: 'sync' | 'rebuild';
|
||||
config: IndexConfig;
|
||||
provider: EmbeddingProvider;
|
||||
store: Store;
|
||||
/** Injectable clock so tests stay deterministic. */
|
||||
now?: () => Date;
|
||||
/** Injected corpus; used by the evaluation harness instead of the tracker. */
|
||||
cards?: readonly TaskCard[];
|
||||
}
|
||||
|
||||
export interface IndexRunResult extends SyncCounters {
|
||||
kind: 'sync' | 'rebuild';
|
||||
cards: number;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
interface Pending {
|
||||
card: TaskCard;
|
||||
intent: ReturnType<typeof normalizeIntent>;
|
||||
}
|
||||
|
||||
function compatible(existing: IndexedCard, provider: EmbeddingProvider): boolean {
|
||||
return (
|
||||
existing.providerId === provider.id &&
|
||||
existing.normVersion === NORM_VERSION &&
|
||||
existing.indexVersion === INDEX_VERSION &&
|
||||
existing.dimensions === provider.dimensions
|
||||
);
|
||||
}
|
||||
|
||||
function buildCard(
|
||||
card: TaskCard,
|
||||
intent: { text: string; hash: string; normVersion: number },
|
||||
vector: Float32Array,
|
||||
provider: EmbeddingProvider,
|
||||
indexedAt: string,
|
||||
): IndexedCard {
|
||||
return {
|
||||
id: card.id,
|
||||
contentHash: intent.hash,
|
||||
fileHash: card.fileHash,
|
||||
providerId: provider.id,
|
||||
modelId: provider.model,
|
||||
normVersion: intent.normVersion,
|
||||
indexVersion: INDEX_VERSION,
|
||||
dimensions: provider.dimensions,
|
||||
vector,
|
||||
indexedAt,
|
||||
metadata: {
|
||||
path: card.path,
|
||||
title: card.title,
|
||||
status: card.status,
|
||||
archived: card.archived,
|
||||
type: card.type,
|
||||
priority: card.priority,
|
||||
project: card.project,
|
||||
labels: card.labels,
|
||||
milestone: card.milestone,
|
||||
parentId: card.parentId,
|
||||
dependencies: card.dependencies,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function unitVector(values: readonly number[]): Float32Array {
|
||||
let total = 0;
|
||||
for (const value of values) {
|
||||
total += value * value;
|
||||
}
|
||||
const length = Math.sqrt(total);
|
||||
const vector = new Float32Array(values.length);
|
||||
for (let index = 0; index < values.length; index += 1) {
|
||||
vector[index] = length === 0 ? 0 : (values[index] ?? 0) / length;
|
||||
}
|
||||
return vector;
|
||||
}
|
||||
|
||||
interface Plan {
|
||||
reused: number;
|
||||
metadataOnly: Pending[];
|
||||
pending: Pending[];
|
||||
}
|
||||
|
||||
/** Splits the corpus into what must be embedded and what can be reused (D-062). */
|
||||
function planRun(
|
||||
cards: readonly TaskCard[],
|
||||
store: Store,
|
||||
provider: EmbeddingProvider,
|
||||
rebuild: boolean,
|
||||
): Plan {
|
||||
const stored = new Map<string, IndexedCard>();
|
||||
for (const card of store.loadCards()) {
|
||||
stored.set(card.id, card);
|
||||
}
|
||||
const plan: Plan = { reused: 0, metadataOnly: [], pending: [] };
|
||||
for (const card of cards) {
|
||||
const intent = normalizeIntent(card);
|
||||
const existing = stored.get(card.id);
|
||||
if (existing === undefined || !compatible(existing, provider) || rebuild) {
|
||||
plan.pending.push({ card, intent });
|
||||
continue;
|
||||
}
|
||||
if (existing.fileHash === card.fileHash) {
|
||||
plan.reused += 1;
|
||||
} else if (existing.contentHash === intent.hash) {
|
||||
plan.metadataOnly.push({ card, intent });
|
||||
} else {
|
||||
plan.pending.push({ card, intent });
|
||||
}
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
function refreshMetadata(
|
||||
store: Store,
|
||||
items: readonly Pending[],
|
||||
provider: EmbeddingProvider,
|
||||
now: () => Date,
|
||||
): void {
|
||||
for (const item of items) {
|
||||
store.updateMetadataOnly(
|
||||
item.card.id,
|
||||
buildCard(item.card, item.intent, new Float32Array(0), provider, now().toISOString()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
interface EmbedOutcome {
|
||||
embedded: number;
|
||||
requests: number;
|
||||
inputTokens: number;
|
||||
}
|
||||
|
||||
/** Embeds only the changed cards and commits each batch as it arrives. */
|
||||
async function embedPending(
|
||||
store: Store,
|
||||
pending: readonly Pending[],
|
||||
provider: EmbeddingProvider,
|
||||
batchSize: number,
|
||||
now: () => Date,
|
||||
): Promise<EmbedOutcome> {
|
||||
let requests = 0;
|
||||
let inputTokens = 0;
|
||||
const commitSize = Math.max(1, batchSize);
|
||||
for (let start = 0; start < pending.length; start += commitSize) {
|
||||
const group = pending.slice(start, start + commitSize);
|
||||
const call = await provider.embed(group.map((item) => item.intent.text));
|
||||
requests += call.requests;
|
||||
inputTokens += call.inputTokens;
|
||||
const indexedAt = now().toISOString();
|
||||
for (let index = 0; index < group.length; index += 1) {
|
||||
const item = group[index];
|
||||
if (item === undefined) {
|
||||
continue;
|
||||
}
|
||||
store.upsertCard(
|
||||
buildCard(item.card, item.intent, unitVector(vectorOf(call, index)), provider, indexedAt),
|
||||
);
|
||||
}
|
||||
}
|
||||
return { embedded: pending.length, requests, inputTokens };
|
||||
}
|
||||
|
||||
function vectorOf(call: { vectors: number[][] }, index: number): number[] {
|
||||
return call.vectors[index] ?? [];
|
||||
}
|
||||
|
||||
function stamp(store: Store, provider: EmbeddingProvider, now: () => Date): void {
|
||||
const created = store.meta().createdAt;
|
||||
store.setMeta({
|
||||
index_version: String(INDEX_VERSION),
|
||||
norm_version: String(NORM_VERSION),
|
||||
provider_id: provider.id,
|
||||
model_id: provider.model,
|
||||
dimensions: String(provider.dimensions),
|
||||
created_at: created === '' ? now().toISOString() : created,
|
||||
last_sync_at: now().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings the index in line with the tracker (D-062). Only cards whose
|
||||
* normalized intent changed reach the provider; everything else is a metadata
|
||||
* refresh or no work at all.
|
||||
*/
|
||||
export async function runIndex(options: IndexRunOptions): Promise<IndexRunResult> {
|
||||
const startedAt = Date.now();
|
||||
const clock = options.now ?? (() => new Date());
|
||||
const { store, provider, config } = options;
|
||||
const read =
|
||||
options.cards === undefined
|
||||
? readCards({ repoRoot: config.repoRoot, backlogDir: config.backlogDir })
|
||||
: { cards: options.cards, errors: [] };
|
||||
if (store.meta().indexVersion !== INDEX_VERSION) {
|
||||
store.dropAll();
|
||||
}
|
||||
const plan = planRun(read.cards, store, provider, options.kind === 'rebuild');
|
||||
refreshMetadata(store, plan.metadataOnly, provider, clock);
|
||||
const embedded = await embedPending(
|
||||
store,
|
||||
plan.pending,
|
||||
provider,
|
||||
config.provider.batchSize,
|
||||
clock,
|
||||
);
|
||||
const removed = store.deleteCardsNotIn(read.cards.map((card) => card.id));
|
||||
stamp(store, provider, clock);
|
||||
const result: IndexRunResult = {
|
||||
kind: options.kind,
|
||||
cards: read.cards.length,
|
||||
embedded: embedded.embedded,
|
||||
reused: plan.reused,
|
||||
metadataOnly: plan.metadataOnly.length,
|
||||
removed,
|
||||
requests: embedded.requests,
|
||||
inputTokens: embedded.inputTokens,
|
||||
durationMs: Date.now() - startedAt,
|
||||
errors: read.errors,
|
||||
};
|
||||
store.recordRun({
|
||||
kind: options.kind,
|
||||
startedAt: new Date(startedAt).toISOString(),
|
||||
finishedAt: clock().toISOString(),
|
||||
cardsTotal: result.cards,
|
||||
embedded: result.embedded,
|
||||
reused: result.reused,
|
||||
metadataOnly: result.metadataOnly,
|
||||
removed: result.removed,
|
||||
requests: result.requests,
|
||||
inputTokens: result.inputTokens,
|
||||
durationMs: result.durationMs,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
|
||||
import { normalizeIntent, normalizeTitle } from './normalize.ts';
|
||||
import { readCards } from './reader.ts';
|
||||
import { candidatePairs } from './similarity.ts';
|
||||
import type { IndexConfig, Thresholds } from './config.ts';
|
||||
import type { Store } from './store.ts';
|
||||
import type {
|
||||
CandidatePair,
|
||||
Diagnostic,
|
||||
DiagnosticFinding,
|
||||
IndexedCard,
|
||||
LintResult,
|
||||
TaskCard,
|
||||
} from './types.ts';
|
||||
|
||||
export interface LintOptions {
|
||||
config: IndexConfig;
|
||||
/** L1 runs only when asked explicitly; L0 never needs the index or network. */
|
||||
semantic: boolean;
|
||||
store?: Store | undefined;
|
||||
cards?: readonly TaskCard[] | undefined;
|
||||
}
|
||||
|
||||
export type StatusClass = 'active' | 'done' | 'skipped' | 'other';
|
||||
|
||||
/** Status class used by the semantic rules; archive always counts as skipped. */
|
||||
export function statusClass(status: string, archived: boolean, config: IndexConfig): StatusClass {
|
||||
if (config.statusClasses.done.includes(status)) {
|
||||
return 'done';
|
||||
}
|
||||
if (config.statusClasses.skipped.includes(status) || archived) {
|
||||
return 'skipped';
|
||||
}
|
||||
if (config.statusClasses.active.includes(status)) {
|
||||
return 'active';
|
||||
}
|
||||
return 'other';
|
||||
}
|
||||
|
||||
function finding(
|
||||
id: string,
|
||||
card: { title: string; status: string; path: string },
|
||||
score: number | null,
|
||||
): DiagnosticFinding {
|
||||
return { id, title: card.title, status: card.status, score, path: card.path };
|
||||
}
|
||||
|
||||
/** L0: exact matches by hash, no embeddings, no network (D-064). */
|
||||
export function deterministicDiagnostics(cards: readonly TaskCard[]): Diagnostic[] {
|
||||
const byContent = new Map<string, TaskCard[]>();
|
||||
const byTitle = new Map<string, TaskCard[]>();
|
||||
for (const card of cards) {
|
||||
const contentKey = normalizeIntent(card).hash;
|
||||
const titleKey = normalizeTitle(card.title);
|
||||
for (const [map, key] of [
|
||||
[byContent, contentKey],
|
||||
[byTitle, titleKey],
|
||||
] as const) {
|
||||
const group = map.get(key);
|
||||
if (group === undefined) {
|
||||
map.set(key, [card]);
|
||||
} else {
|
||||
group.push(card);
|
||||
}
|
||||
}
|
||||
}
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
const groups = [...byContent.values()].filter((group) => group.length > 1);
|
||||
if (groups.length > 0) {
|
||||
diagnostics.push({
|
||||
rule: 'DUP001',
|
||||
level: 'error',
|
||||
message: 'Нормализованное содержание карточек совпадает полностью.',
|
||||
findings: groups
|
||||
.flat()
|
||||
.sort((left, right) => (left.id < right.id ? -1 : 1))
|
||||
.map((card) => finding(card.id, card, null)),
|
||||
});
|
||||
}
|
||||
const titleGroups = [...byTitle.values()].filter((group) => group.length > 1);
|
||||
if (titleGroups.length > 0) {
|
||||
diagnostics.push({
|
||||
rule: 'DUP002',
|
||||
level: 'warning',
|
||||
message: 'Нормализованное название карточки повторяется.',
|
||||
findings: titleGroups
|
||||
.flat()
|
||||
.sort((left, right) => (left.id < right.id ? -1 : 1))
|
||||
.map((card) => finding(card.id, card, null)),
|
||||
});
|
||||
}
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
interface Classified {
|
||||
rule: RuleName;
|
||||
level: 'warning' | 'recommendation';
|
||||
pair: CandidatePair;
|
||||
}
|
||||
|
||||
function structural(left: IndexedCard, right: IndexedCard): boolean {
|
||||
return structuralPair(left.id, left.metadata.parentId, right.id, right.metadata.parentId);
|
||||
}
|
||||
|
||||
/** A parent and its own subtask: structural subsumption, known from the tracker. */
|
||||
export function structuralPair(
|
||||
leftId: string,
|
||||
leftParentId: string | null,
|
||||
rightId: string,
|
||||
rightParentId: string | null,
|
||||
): boolean {
|
||||
return leftParentId === rightId || rightParentId === leftId;
|
||||
}
|
||||
|
||||
export type RuleName = 'SEM001' | 'SEM002' | 'SEM003' | 'SEM004';
|
||||
|
||||
const RULE_LEVEL: Record<RuleName, 'warning' | 'recommendation'> = {
|
||||
SEM001: 'warning',
|
||||
SEM002: 'warning',
|
||||
SEM003: 'recommendation',
|
||||
SEM004: 'recommendation',
|
||||
};
|
||||
|
||||
function activeRule(
|
||||
score: number,
|
||||
classes: readonly StatusClass[],
|
||||
thresholds: Thresholds,
|
||||
): RuleName | null {
|
||||
if (!classes.every((item) => item === 'active')) {
|
||||
return null;
|
||||
}
|
||||
if (score >= thresholds.duplicate) {
|
||||
return 'SEM001';
|
||||
}
|
||||
return score >= thresholds.overlap ? 'SEM002' : null;
|
||||
}
|
||||
|
||||
function historyRule(
|
||||
score: number,
|
||||
classes: readonly StatusClass[],
|
||||
overlap: number,
|
||||
): RuleName | null {
|
||||
if (score < overlap || !classes.includes('active')) {
|
||||
return null;
|
||||
}
|
||||
if (classes.includes('done')) {
|
||||
return 'SEM003';
|
||||
}
|
||||
return classes.includes('skipped') ? 'SEM004' : null;
|
||||
}
|
||||
|
||||
/** Signal class of one comparison; structural pairs carry no duplicate signal. */
|
||||
export function signalFor(
|
||||
score: number,
|
||||
classes: readonly StatusClass[],
|
||||
isStructural: boolean,
|
||||
config: IndexConfig,
|
||||
): RuleName | null {
|
||||
if (isStructural) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
activeRule(score, classes, config.thresholds) ??
|
||||
historyRule(score, classes, config.thresholds.overlap)
|
||||
);
|
||||
}
|
||||
|
||||
function classify(
|
||||
pair: CandidatePair,
|
||||
config: IndexConfig,
|
||||
left: IndexedCard,
|
||||
right: IndexedCard,
|
||||
): Classified | null {
|
||||
// A parent and its own subtask are structural subsumption, not duplication.
|
||||
const classes = [
|
||||
statusClass(left.metadata.status, left.metadata.archived, config),
|
||||
statusClass(right.metadata.status, right.metadata.archived, config),
|
||||
];
|
||||
const rule = signalFor(pair.score, classes, structural(left, right), config);
|
||||
return rule === null ? null : { rule, level: RULE_LEVEL[rule], pair };
|
||||
}
|
||||
|
||||
const RULE_MESSAGES: Record<string, string> = {
|
||||
SEM001: 'Потенциальный семантический дубликат активных задач.',
|
||||
SEM002: 'Существенное пересечение требований активных задач.',
|
||||
SEM003: 'Возможное повторение завершённой задачи.',
|
||||
SEM004: 'Возможное повторение пропущенной или архивной задачи.',
|
||||
};
|
||||
|
||||
function groupByRule(items: readonly Classified[], cards: Map<string, IndexedCard>): Diagnostic[] {
|
||||
const byRule = new Map<string, Classified[]>();
|
||||
for (const item of items) {
|
||||
const group = byRule.get(item.rule);
|
||||
if (group === undefined) {
|
||||
byRule.set(item.rule, [item]);
|
||||
} else {
|
||||
group.push(item);
|
||||
}
|
||||
}
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
for (const rule of Object.keys(RULE_MESSAGES)) {
|
||||
const group = byRule.get(rule);
|
||||
if (group === undefined || group.length === 0) {
|
||||
continue;
|
||||
}
|
||||
diagnostics.push(diagnosticForRule(rule, group, cards));
|
||||
}
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
function diagnosticForRule(
|
||||
rule: string,
|
||||
group: readonly Classified[],
|
||||
cards: Map<string, IndexedCard>,
|
||||
): Diagnostic {
|
||||
const findings: DiagnosticFinding[] = [];
|
||||
for (const item of group) {
|
||||
const left = cards.get(item.pair.left);
|
||||
const right = cards.get(item.pair.right);
|
||||
if (left === undefined || right === undefined) {
|
||||
continue;
|
||||
}
|
||||
findings.push(finding(item.pair.left, left.metadata, item.pair.score));
|
||||
findings.push(finding(item.pair.right, right.metadata, item.pair.score));
|
||||
}
|
||||
return {
|
||||
rule,
|
||||
level: group[0]?.level ?? 'warning',
|
||||
message: RULE_MESSAGES[rule] ?? '',
|
||||
findings,
|
||||
};
|
||||
}
|
||||
|
||||
export interface SemanticOutcome {
|
||||
diagnostics: Diagnostic[];
|
||||
unavailable: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/** L1: cosine screening of the stored index. Never touches the network. */
|
||||
export function semanticDiagnostics(
|
||||
store: Store,
|
||||
backlogCards: readonly TaskCard[],
|
||||
config: IndexConfig,
|
||||
): SemanticOutcome {
|
||||
const indexed = store.loadCards();
|
||||
const meta = store.meta();
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
if (indexed.length === 0) {
|
||||
return {
|
||||
diagnostics: [
|
||||
{
|
||||
rule: 'SEM005',
|
||||
level: 'warning',
|
||||
message: 'Семантический индекс не построен: выполните bidx index sync.',
|
||||
findings: [],
|
||||
},
|
||||
],
|
||||
unavailable: true,
|
||||
error: 'Индекс пуст или отсутствует.',
|
||||
};
|
||||
}
|
||||
const incompatible = indexed.filter(
|
||||
(card) =>
|
||||
card.indexVersion !== meta.indexVersion ||
|
||||
card.normVersion !== meta.normVersion ||
|
||||
card.providerId !== meta.providerId ||
|
||||
card.dimensions !== meta.dimensions,
|
||||
);
|
||||
if (incompatible.length > 0) {
|
||||
diagnostics.push({
|
||||
rule: 'SEM006',
|
||||
level: 'warning',
|
||||
message: `Записи индекса несовместимы с текущей конфигурацией: ${String(incompatible.length)}.`,
|
||||
findings: incompatible.map((card) => finding(card.id, card.metadata, null)),
|
||||
});
|
||||
}
|
||||
const known = new Set(indexed.map((card) => card.id));
|
||||
const missing = backlogCards.filter((card) => !known.has(card.id));
|
||||
if (missing.length > 0) {
|
||||
diagnostics.push({
|
||||
rule: 'SEM005',
|
||||
level: 'warning',
|
||||
message: `Индекс не покрывает ${String(missing.length)} карточек: выполните bidx index sync.`,
|
||||
findings: missing.map((card) => finding(card.id, card, null)),
|
||||
});
|
||||
}
|
||||
const compatible = indexed.filter(
|
||||
(card) =>
|
||||
card.indexVersion === meta.indexVersion &&
|
||||
card.normVersion === meta.normVersion &&
|
||||
card.providerId === meta.providerId &&
|
||||
card.dimensions === meta.dimensions,
|
||||
);
|
||||
const cards = new Map(indexed.map((card) => [card.id, card]));
|
||||
const pairs = candidatePairs(compatible, { threshold: config.thresholds.overlap });
|
||||
const classified: Classified[] = [];
|
||||
for (const pair of pairs) {
|
||||
const left = cards.get(pair.left);
|
||||
const right = cards.get(pair.right);
|
||||
if (left === undefined || right === undefined) {
|
||||
continue;
|
||||
}
|
||||
const item = classify(pair, config, left, right);
|
||||
if (item !== null) {
|
||||
classified.push(item);
|
||||
}
|
||||
}
|
||||
diagnostics.push(...groupByRule(classified, cards));
|
||||
return { diagnostics, unavailable: false, error: null };
|
||||
}
|
||||
|
||||
/** Runs the backlog diagnostics. Semantic findings never become errors (D-064). */
|
||||
export function runLint(options: LintOptions): LintResult {
|
||||
const { config } = options;
|
||||
const cards =
|
||||
options.cards ?? readCards({ repoRoot: config.repoRoot, backlogDir: config.backlogDir }).cards;
|
||||
const base = deterministicDiagnostics(cards);
|
||||
if (!options.semantic) {
|
||||
return {
|
||||
ok: !hasError(base),
|
||||
semantic: false,
|
||||
semanticUnavailable: false,
|
||||
semanticError: null,
|
||||
diagnostics: base,
|
||||
};
|
||||
}
|
||||
if (options.store === undefined || !existsSync(config.indexFile)) {
|
||||
return {
|
||||
ok: !hasError(base),
|
||||
semantic: false,
|
||||
semanticUnavailable: true,
|
||||
semanticError: `Индекс не найден: ${config.indexFile}`,
|
||||
diagnostics: [...base, missingIndexDiagnostic(config.indexFile)],
|
||||
};
|
||||
}
|
||||
const semantic = semanticDiagnostics(options.store, cards, config);
|
||||
const all = [...base, ...semantic.diagnostics];
|
||||
return {
|
||||
ok: !hasError(all),
|
||||
semantic: !semantic.unavailable,
|
||||
semanticUnavailable: semantic.unavailable,
|
||||
semanticError: semantic.error,
|
||||
diagnostics: all,
|
||||
};
|
||||
}
|
||||
|
||||
function hasError(diagnostics: readonly Diagnostic[]): boolean {
|
||||
return diagnostics.some((item) => item.level === 'error');
|
||||
}
|
||||
|
||||
function missingIndexDiagnostic(indexFile: string): Diagnostic {
|
||||
return {
|
||||
rule: 'SEM005',
|
||||
level: 'warning',
|
||||
message: `Семантический индекс отсутствует: выполните bidx index sync (${indexFile}).`,
|
||||
findings: [],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { readCards } from './reader.ts';
|
||||
import type { IndexConfig } from './config.ts';
|
||||
import type { Store, RunRecord } from './store.ts';
|
||||
|
||||
export interface IndexMetrics {
|
||||
cards: number;
|
||||
current: number;
|
||||
stale: number;
|
||||
missingFromIndex: number;
|
||||
sizeBytes: number;
|
||||
providerId: string | null;
|
||||
modelId: string | null;
|
||||
dimensions: number | null;
|
||||
normVersion: number | null;
|
||||
indexVersion: number;
|
||||
lastSyncAt: string | null;
|
||||
lastRun: RunRecord | null;
|
||||
reuseRatio: number | null;
|
||||
searchMs: number | null;
|
||||
}
|
||||
|
||||
/** Operational numbers for judging usefulness, not target quotas. */
|
||||
export function collectMetrics(store: Store, config: IndexConfig): IndexMetrics {
|
||||
const meta = store.meta();
|
||||
const rows = store.loadCards();
|
||||
const backlog = readCards({ repoRoot: config.repoRoot, backlogDir: config.backlogDir });
|
||||
const known = new Set(rows.map((card) => card.id));
|
||||
const current = rows.filter(
|
||||
(row) =>
|
||||
row.indexVersion === meta.indexVersion &&
|
||||
row.normVersion === (meta.normVersion ?? -1) &&
|
||||
row.providerId === (meta.providerId ?? '') &&
|
||||
row.dimensions === (meta.dimensions ?? -1),
|
||||
).length;
|
||||
const missing = backlog.cards.filter((card) => !known.has(card.id)).length;
|
||||
const last = store.runs(1)[0] ?? null;
|
||||
const decided = last === null ? 0 : last.reused + last.embedded + last.metadataOnly;
|
||||
const reuseRatio = last === null || decided === 0 ? null : last.reused / decided;
|
||||
return {
|
||||
cards: rows.length,
|
||||
current,
|
||||
stale: rows.length - current,
|
||||
missingFromIndex: missing,
|
||||
sizeBytes: store.sizeBytes(),
|
||||
providerId: meta.providerId,
|
||||
modelId: meta.modelId,
|
||||
dimensions: meta.dimensions,
|
||||
normVersion: meta.normVersion,
|
||||
indexVersion: meta.indexVersion,
|
||||
lastSyncAt: meta.lastSyncAt,
|
||||
lastRun: last,
|
||||
reuseRatio,
|
||||
searchMs: null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
import type { NormalizedIntent, TaskCard } from './types.ts';
|
||||
|
||||
// Schema version of the intent representation. Any change to the card fields
|
||||
// below or to the canonicalization rules must bump this number: stored vectors
|
||||
// of different schema versions are never compared (D-061).
|
||||
export const NORM_VERSION = 1;
|
||||
|
||||
const CHECKBOX_PREFIX = /^\s*(?:[-*+]|\d+[.)])\s*(?:\[[^\]]*\])?\s*(?:#\d+\s+)?/u;
|
||||
|
||||
function collapse(value: string): string {
|
||||
return value
|
||||
.normalize('NFKC')
|
||||
.replaceAll('\r\n', '\n')
|
||||
.split('\n')
|
||||
.map((line) => line.replace(/\s+/gu, ' ').trim())
|
||||
.filter((line) => line !== '')
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
/** Drops list markers, checkbox state and the `#N` criterion index prefix. */
|
||||
export function stripListMarker(value: string): string {
|
||||
return value.replace(CHECKBOX_PREFIX, '');
|
||||
}
|
||||
|
||||
function join(parts: readonly string[]): string {
|
||||
const lines = parts.map((part) => collapse(part)).filter((part) => part !== '');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function sha256(value: string): string {
|
||||
return createHash('sha256').update(value, 'utf8').digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Intent representation of a card (D-061): title, description and acceptance
|
||||
* criterion texts. Everything operational — status, dates, priorities, labels,
|
||||
* dependencies, Definition of Done, comments, notes and checkbox state — is
|
||||
* metadata, not vector content.
|
||||
*/
|
||||
export function normalizeIntent(card: TaskCard): NormalizedIntent {
|
||||
const text = join([
|
||||
stripListMarker(card.title),
|
||||
...card.description.split('\n').map((line) => stripListMarker(line)),
|
||||
...card.acceptanceCriteria.map((line) => stripListMarker(line)),
|
||||
]);
|
||||
return { text, hash: sha256(text), normVersion: NORM_VERSION };
|
||||
}
|
||||
|
||||
/** Deterministic title form for the exact-match rule DUP002. */
|
||||
export function normalizeTitle(title: string): string {
|
||||
return title
|
||||
.normalize('NFKC')
|
||||
.toLowerCase()
|
||||
.replace(/[^\p{L}\p{N}]+/gu, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Deterministic content form used by the exact-match rule DUP001. */
|
||||
export function contentHash(intent: NormalizedIntent): string {
|
||||
return intent.hash;
|
||||
}
|
||||
|
||||
export function hashText(value: string): string {
|
||||
return sha256(value);
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
export interface EmbeddingCallResult {
|
||||
vectors: number[][];
|
||||
requests: number;
|
||||
inputTokens: number;
|
||||
}
|
||||
|
||||
/** Minimal replaceable provider contract (D-063). */
|
||||
export interface EmbeddingProvider {
|
||||
/** Identity used to invalidate stored vectors when it changes. */
|
||||
readonly id: string;
|
||||
readonly model: string;
|
||||
readonly dimensions: number;
|
||||
embed(texts: readonly string[]): Promise<EmbeddingCallResult>;
|
||||
}
|
||||
|
||||
export class ProviderError extends Error {
|
||||
readonly code: string;
|
||||
constructor(code: string, message: string) {
|
||||
super(message);
|
||||
this.name = 'ProviderError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ApiKeySource {
|
||||
kind: 'env' | 'json-file';
|
||||
name?: string;
|
||||
path?: string;
|
||||
selector?: string;
|
||||
}
|
||||
|
||||
export interface OpenAICompatibleSettings {
|
||||
endpoint: string;
|
||||
model: string;
|
||||
apiKey: string;
|
||||
dimensions: number;
|
||||
batchSize: number;
|
||||
timeoutMs: number;
|
||||
retries: number;
|
||||
concurrency: number;
|
||||
retryDelayMs: number;
|
||||
modelParams?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isList(value: unknown): value is readonly unknown[] {
|
||||
return Array.isArray(value);
|
||||
}
|
||||
|
||||
function nonEmptyString(value: unknown): string | null {
|
||||
return typeof value === 'string' && value !== '' ? value : null;
|
||||
}
|
||||
|
||||
function dig(value: unknown, selector: string): unknown {
|
||||
let current: unknown = value;
|
||||
for (const part of selector.split('.').filter((segment) => segment !== '')) {
|
||||
if (isList(current)) {
|
||||
const index = Number(part);
|
||||
if (!Number.isInteger(index) || index < 0 || index >= current.length) {
|
||||
return undefined;
|
||||
}
|
||||
current = current[index];
|
||||
continue;
|
||||
}
|
||||
if (!isRecord(current)) {
|
||||
return undefined;
|
||||
}
|
||||
current = current[part];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function keyFromEnv(source: ApiKeySource): string | null {
|
||||
if (source.name === undefined) {
|
||||
return null;
|
||||
}
|
||||
return nonEmptyString(process.env[source.name]);
|
||||
}
|
||||
|
||||
function keyFromFile(source: ApiKeySource, baseDir: string): string | null {
|
||||
const relative = source.path;
|
||||
const selector = source.selector;
|
||||
if (relative === undefined || selector === undefined) {
|
||||
return null;
|
||||
}
|
||||
const file = path.isAbsolute(relative) ? relative : path.resolve(baseDir, relative);
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(file, 'utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return nonEmptyString(dig(parsed, selector));
|
||||
}
|
||||
|
||||
/** Resolves the first available API key source; secrets never enter the repo. */
|
||||
export function resolveApiKey(sources: readonly ApiKeySource[], baseDir: string): string | null {
|
||||
for (const source of sources) {
|
||||
const value = source.kind === 'env' ? keyFromEnv(source) : keyFromFile(source, baseDir);
|
||||
if (value !== null) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
|
||||
/** Runs workers with a fixed group size and keeps the result order stable. */
|
||||
async function mapInGroups<T, R>(
|
||||
items: readonly T[],
|
||||
limit: number,
|
||||
worker: (item: T, index: number) => Promise<R>,
|
||||
): Promise<R[]> {
|
||||
const results: R[] = [];
|
||||
const size = Math.max(1, limit);
|
||||
for (let start = 0; start < items.length; start += size) {
|
||||
const group = items.slice(start, Math.min(start + size, items.length));
|
||||
const settled = await Promise.all(
|
||||
group.map((item, offset) => {
|
||||
return worker(item, start + offset);
|
||||
}),
|
||||
);
|
||||
for (const value of settled) {
|
||||
results.push(value);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
function chunk(values: readonly string[], size: number): string[][] {
|
||||
const batches: string[][] = [];
|
||||
for (let start = 0; start < values.length; start += size) {
|
||||
batches.push(values.slice(start, Math.min(start + size, values.length)));
|
||||
}
|
||||
return batches;
|
||||
}
|
||||
|
||||
function parseVector(value: readonly unknown[], expected: number): number[] {
|
||||
if (value.length !== expected) {
|
||||
throw new ProviderError(
|
||||
'DIMENSION_MISMATCH',
|
||||
`Поставщик вернул вектор длиной ${String(value.length)}, ожидалась ${String(expected)}.`,
|
||||
);
|
||||
}
|
||||
const vector: number[] = [];
|
||||
for (const item of value) {
|
||||
if (typeof item !== 'number' || !Number.isFinite(item)) {
|
||||
throw new ProviderError('PROVIDER_MALFORMED', 'Вектор содержит нечисловое значение.');
|
||||
}
|
||||
vector.push(item);
|
||||
}
|
||||
return vector;
|
||||
}
|
||||
|
||||
function rowIndex(row: Record<string, unknown>, fallback: number): number {
|
||||
const value = row['index'];
|
||||
if (typeof value === 'number' && Number.isInteger(value) && value >= 0) {
|
||||
return value;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function rowVector(
|
||||
row: unknown,
|
||||
expected: number,
|
||||
fallback: number,
|
||||
): { index: number; vector: number[] } {
|
||||
if (!isRecord(row) || !isList(row['embedding'])) {
|
||||
throw new ProviderError('PROVIDER_MALFORMED', 'В ответе поставщика нет поля embedding.');
|
||||
}
|
||||
const index = rowIndex(row, fallback);
|
||||
return { index, vector: parseVector(row['embedding'], expected) };
|
||||
}
|
||||
|
||||
function inputTokensOf(payload: Record<string, unknown>): number {
|
||||
const usage = payload['usage'];
|
||||
if (!isRecord(usage) || typeof usage['prompt_tokens'] !== 'number') {
|
||||
return 0;
|
||||
}
|
||||
return usage['prompt_tokens'];
|
||||
}
|
||||
|
||||
function parseEmbeddings(
|
||||
payload: unknown,
|
||||
expected: number,
|
||||
): { vectors: number[][]; inputTokens: number } {
|
||||
if (!isRecord(payload) || !isList(payload['data'])) {
|
||||
throw new ProviderError('PROVIDER_MALFORMED', 'Поставщик вернул ответ без поля data.');
|
||||
}
|
||||
const ordered: (number[] | undefined)[] = [];
|
||||
for (const row of payload['data']) {
|
||||
const item = rowVector(row, expected, ordered.length);
|
||||
while (ordered.length <= item.index) {
|
||||
ordered.push(undefined);
|
||||
}
|
||||
ordered[item.index] = item.vector;
|
||||
}
|
||||
const vectors: number[][] = [];
|
||||
for (const vector of ordered) {
|
||||
if (vector === undefined) {
|
||||
throw new ProviderError('PROVIDER_MALFORMED', 'В ответе поставщика пропущен элемент.');
|
||||
}
|
||||
vectors.push(vector);
|
||||
}
|
||||
return { vectors, inputTokens: inputTokensOf(payload) };
|
||||
}
|
||||
|
||||
export interface TransportRequest {
|
||||
url: string;
|
||||
apiKey: string;
|
||||
body: string;
|
||||
timeoutMs: number;
|
||||
}
|
||||
|
||||
export interface TransportResponse {
|
||||
status: number;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export type Transport = (request: TransportRequest) => Promise<TransportResponse>;
|
||||
|
||||
export const fetchTransport: Transport = async (request) => {
|
||||
const response = await fetch(request.url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${request.apiKey}`,
|
||||
},
|
||||
body: request.body,
|
||||
signal: AbortSignal.timeout(request.timeoutMs),
|
||||
});
|
||||
return { status: response.status, body: await response.text() };
|
||||
};
|
||||
|
||||
function snippet(body: string): string {
|
||||
const flat = body.replaceAll('\r', ' ').replaceAll('\n', ' ').trim();
|
||||
return flat.length <= 240 ? flat : `${flat.slice(0, 240)}…`;
|
||||
}
|
||||
|
||||
function retryable(status: number): boolean {
|
||||
return status === 429 || status >= 500;
|
||||
}
|
||||
|
||||
function succeeded(status: number): boolean {
|
||||
return status >= 200 && status < 300;
|
||||
}
|
||||
|
||||
function endpointUrl(endpoint: string): string {
|
||||
let base = endpoint;
|
||||
while (base.endsWith('/')) {
|
||||
base = base.slice(0, -1);
|
||||
}
|
||||
return `${base}/embeddings`;
|
||||
}
|
||||
|
||||
function batchPayload(settings: OpenAICompatibleSettings, batch: readonly string[]): string {
|
||||
const payload: Record<string, unknown> = { model: settings.model, input: batch };
|
||||
if (settings.modelParams !== undefined) {
|
||||
Object.assign(payload, settings.modelParams);
|
||||
}
|
||||
return JSON.stringify(payload);
|
||||
}
|
||||
|
||||
function unavailable(detail: string, status?: number): ProviderError {
|
||||
if (status === undefined) {
|
||||
return new ProviderError('PROVIDER_UNAVAILABLE', `Endpoint недоступен: ${detail}`);
|
||||
}
|
||||
return new ProviderError(
|
||||
'PROVIDER_UNAVAILABLE',
|
||||
`Endpoint отклонил запрос с кодом ${String(status)} после повторов.`,
|
||||
);
|
||||
}
|
||||
|
||||
interface BatchOutcome {
|
||||
vectors: number[][];
|
||||
requests: number;
|
||||
inputTokens: number;
|
||||
}
|
||||
|
||||
/** Sends one batch with the configured retry policy (D-063). */
|
||||
async function sendBatch(
|
||||
settings: OpenAICompatibleSettings,
|
||||
url: string,
|
||||
transport: Transport,
|
||||
batch: readonly string[],
|
||||
): Promise<BatchOutcome> {
|
||||
const body = batchPayload(settings, batch);
|
||||
let requests = 0;
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
const outcome = await attemptBatch(settings, url, transport, body, attempt);
|
||||
requests += 1;
|
||||
if (outcome !== null) {
|
||||
return { ...outcome, requests };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function attemptBatch(
|
||||
settings: OpenAICompatibleSettings,
|
||||
url: string,
|
||||
transport: Transport,
|
||||
body: string,
|
||||
attempt: number,
|
||||
): Promise<{ vectors: number[][]; inputTokens: number } | null> {
|
||||
let response: TransportResponse;
|
||||
try {
|
||||
response = await transport({
|
||||
url,
|
||||
apiKey: settings.apiKey,
|
||||
body,
|
||||
timeoutMs: settings.timeoutMs,
|
||||
});
|
||||
} catch (cause) {
|
||||
if (attempt > settings.retries) {
|
||||
const detail = cause instanceof Error ? cause.message : 'network error';
|
||||
throw unavailable(detail);
|
||||
}
|
||||
await sleep(settings.retryDelayMs * attempt);
|
||||
return null;
|
||||
}
|
||||
if (succeeded(response.status)) {
|
||||
return parseResponse(response.body, settings.dimensions);
|
||||
}
|
||||
if (retryable(response.status)) {
|
||||
if (attempt <= settings.retries) {
|
||||
await sleep(settings.retryDelayMs * attempt);
|
||||
return null;
|
||||
}
|
||||
throw unavailable('повторы исчерпаны', response.status);
|
||||
}
|
||||
throw new ProviderError(
|
||||
'PROVIDER_REJECTED',
|
||||
`Endpoint отклонил запрос с кодом ${String(response.status)}: ${snippet(response.body)}`,
|
||||
);
|
||||
}
|
||||
|
||||
function parseResponse(
|
||||
body: string,
|
||||
dimensions: number,
|
||||
): { vectors: number[][]; inputTokens: number } {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(body);
|
||||
} catch {
|
||||
throw new ProviderError('PROVIDER_MALFORMED', 'Ответ endpoint не является JSON.');
|
||||
}
|
||||
return parseEmbeddings(parsed, dimensions);
|
||||
}
|
||||
|
||||
/** OpenAI-compatible `POST {endpoint}/embeddings` (D-063). */
|
||||
export function createOpenAICompatibleProvider(
|
||||
settings: OpenAICompatibleSettings,
|
||||
transport: Transport = fetchTransport,
|
||||
): EmbeddingProvider {
|
||||
const url = endpointUrl(settings.endpoint);
|
||||
const embed = async (texts: readonly string[]): Promise<EmbeddingCallResult> => {
|
||||
if (texts.length === 0) {
|
||||
return { vectors: [], requests: 0, inputTokens: 0 };
|
||||
}
|
||||
const batches = chunk(texts, Math.max(1, settings.batchSize));
|
||||
const outcomes = await mapInGroups(batches, settings.concurrency, async (batch) => {
|
||||
return await sendBatch(settings, url, transport, batch);
|
||||
});
|
||||
const vectors: number[][] = [];
|
||||
let requests = 0;
|
||||
let inputTokens = 0;
|
||||
for (const outcome of outcomes) {
|
||||
vectors.push(...outcome.vectors);
|
||||
requests += outcome.requests;
|
||||
inputTokens += outcome.inputTokens;
|
||||
}
|
||||
return { vectors, requests, inputTokens };
|
||||
};
|
||||
return {
|
||||
id: `openai-compatible:${settings.model}`,
|
||||
model: settings.model,
|
||||
dimensions: settings.dimensions,
|
||||
embed,
|
||||
};
|
||||
}
|
||||
|
||||
function fnv1a(value: string): number {
|
||||
let hash = 0x811c9dc5;
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
hash ^= value.charCodeAt(index);
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
return hash >>> 0;
|
||||
}
|
||||
|
||||
function grams(word: string, out: string[]): void {
|
||||
for (let start = 0; start + 4 <= word.length; start += 1) {
|
||||
out.push(`g:${word.slice(start, start + 4)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function features(text: string): string[] {
|
||||
const normalized = text.normalize('NFKC').toLowerCase();
|
||||
const words = normalized.split(/[^\p{L}\p{N}]+/u).filter((word) => word !== '');
|
||||
const out: string[] = [];
|
||||
for (const word of words) {
|
||||
out.push(`w:${word}`);
|
||||
grams(word, out);
|
||||
}
|
||||
for (let index = 0; index + 1 < words.length; index += 1) {
|
||||
const left = words[index];
|
||||
const right = words[index + 1];
|
||||
if (left !== undefined && right !== undefined) {
|
||||
out.push(`b:${left}=${right}`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function featureVector(text: string, dimensions: number): number[] {
|
||||
const accumulator = new Float64Array(dimensions);
|
||||
for (const feature of features(text)) {
|
||||
const slot = fnv1a(feature) % dimensions;
|
||||
accumulator[slot] = (accumulator[slot] ?? 0) + 1;
|
||||
}
|
||||
let total = 0;
|
||||
for (const value of accumulator) {
|
||||
total += value * value;
|
||||
}
|
||||
const length = Math.sqrt(total);
|
||||
const vector: number[] = [];
|
||||
for (const value of accumulator) {
|
||||
vector.push(length === 0 ? 0 : value / length);
|
||||
}
|
||||
return vector;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministic stand-in used by the automated tests: vectors come from hashed
|
||||
* token, bigram and character-gram features, so near-identical texts score
|
||||
* higher than unrelated ones without any network access.
|
||||
*/
|
||||
export function createMockProvider(dimensions = 128): EmbeddingProvider {
|
||||
const embed = async (texts: readonly string[]): Promise<EmbeddingCallResult> => {
|
||||
const vectors: number[][] = [];
|
||||
for (const text of texts) {
|
||||
vectors.push(await Promise.resolve(featureVector(text, dimensions)));
|
||||
}
|
||||
return { vectors, requests: texts.length === 0 ? 0 : 1, inputTokens: 0 };
|
||||
};
|
||||
return {
|
||||
id: `mock:hash-v1:${String(dimensions)}`,
|
||||
model: 'mock-hash-v1',
|
||||
dimensions,
|
||||
embed,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { parseDocument, isMap } from 'yaml';
|
||||
|
||||
import type { TaskCard } from './types.ts';
|
||||
|
||||
export interface ReadResult {
|
||||
cards: TaskCard[];
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
export interface ReaderOptions {
|
||||
/** Repository root: card paths are reported relative to it. */
|
||||
repoRoot: string;
|
||||
/** Directory holding the tracker files, relative to repoRoot or absolute. */
|
||||
backlogDir: string;
|
||||
}
|
||||
|
||||
const FRONTMATTER = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u;
|
||||
|
||||
function sectionBody(text: string, marker: string): string {
|
||||
const begin = `<!-- ${marker}:BEGIN -->`;
|
||||
const end = `<!-- ${marker}:END -->`;
|
||||
const start = text.indexOf(begin);
|
||||
if (start === -1) {
|
||||
return '';
|
||||
}
|
||||
const rest = text.slice(start + begin.length);
|
||||
const stop = rest.indexOf(end);
|
||||
return stop === -1 ? '' : rest.slice(0, stop).trim();
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | null {
|
||||
if (typeof value === 'string' && value.trim() !== '') {
|
||||
return value.trim();
|
||||
}
|
||||
if (typeof value === 'number' || typeof value === 'boolean') {
|
||||
return String(value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function asStringList(value: unknown): string[] {
|
||||
if (Array.isArray(value)) {
|
||||
return value.filter((item): item is string => typeof item === 'string' && item !== '');
|
||||
}
|
||||
if (typeof value === 'string' && value.trim() !== '') {
|
||||
return [value.trim()];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function parseFrontmatter(text: string): Record<string, unknown> | null {
|
||||
const match = FRONTMATTER.exec(text);
|
||||
if (match === null) {
|
||||
return null;
|
||||
}
|
||||
const doc = parseDocument(match[1] ?? '', { prettyErrors: false, uniqueKeys: true });
|
||||
if (doc.errors.length > 0 || !isMap(doc.contents)) {
|
||||
return null;
|
||||
}
|
||||
const value: unknown = doc.toJS({ maxAliasCount: 50 });
|
||||
return isRecord(value) ? value : null;
|
||||
}
|
||||
|
||||
/** Acceptance criterion texts only: `- [x] #3 text` becomes `text`. */
|
||||
function acceptanceCriteria(body: string): string[] {
|
||||
const lines: string[] = [];
|
||||
for (const raw of body.split(/\r?\n/u)) {
|
||||
const line = raw.trim();
|
||||
if (!/^[-*+]\s*\[[ xX]\]/u.test(line)) {
|
||||
continue;
|
||||
}
|
||||
const text = line.replace(/^[-*+]\s*\[[ xX]\]\s*(?:#\d+\s+)?/u, '').trim();
|
||||
if (text !== '') {
|
||||
lines.push(text);
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function listMarkdownFiles(directory: string): string[] {
|
||||
let entries;
|
||||
try {
|
||||
entries = readdirSync(directory, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return entries
|
||||
.filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith('.md'))
|
||||
.map((entry) => path.join(directory, entry.name))
|
||||
.sort((left, right) => (left < right ? -1 : 1));
|
||||
}
|
||||
|
||||
function relativePosix(repoRoot: string, absolute: string): string {
|
||||
return path.relative(repoRoot, absolute).split(path.sep).join('/');
|
||||
}
|
||||
|
||||
interface Identity {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
function identity(meta: Record<string, unknown>): Identity | null {
|
||||
const id = asString(meta['id']);
|
||||
const title = asString(meta['title']);
|
||||
const status = asString(meta['status']);
|
||||
if (id === null || title === null || status === null) {
|
||||
return null;
|
||||
}
|
||||
return { id, title, status };
|
||||
}
|
||||
|
||||
function parentOf(meta: Record<string, unknown>): string | null {
|
||||
return asString(meta['parent_task_id']) ?? asString(meta['parent']);
|
||||
}
|
||||
|
||||
function readCard(
|
||||
repoRoot: string,
|
||||
absolute: string,
|
||||
archivedByLocation: boolean,
|
||||
): TaskCard | null {
|
||||
const bytes = readFileSync(absolute);
|
||||
const text = bytes.toString('utf8');
|
||||
const meta = parseFrontmatter(text);
|
||||
if (meta === null) {
|
||||
return null;
|
||||
}
|
||||
const who = identity(meta);
|
||||
if (who === null) {
|
||||
return null;
|
||||
}
|
||||
const dependencies = asStringList(meta['dependencies']);
|
||||
return {
|
||||
...who,
|
||||
archived: archivedByLocation || meta['archived'] === true,
|
||||
path: relativePosix(repoRoot, absolute),
|
||||
type: asString(meta['type']),
|
||||
priority: asString(meta['priority']),
|
||||
project: asString(meta['project']),
|
||||
labels: asStringList(meta['labels']),
|
||||
milestone: asString(meta['milestone']),
|
||||
parentId: parentOf(meta),
|
||||
dependencies,
|
||||
description: sectionBody(text, 'SECTION:DESCRIPTION'),
|
||||
acceptanceCriteria: acceptanceCriteria(sectionBody(text, 'AC')),
|
||||
fileHash: createHash('sha256').update(bytes).digest('hex'),
|
||||
};
|
||||
}
|
||||
|
||||
function compareIds(left: string, right: string): number {
|
||||
if (left < right) {
|
||||
return -1;
|
||||
}
|
||||
if (left > right) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
interface Source {
|
||||
directory: string;
|
||||
archived: boolean;
|
||||
}
|
||||
|
||||
function readSource(source: Source, repoRoot: string): { cards: TaskCard[]; errors: string[] } {
|
||||
const cards: TaskCard[] = [];
|
||||
const errors: string[] = [];
|
||||
if (!statSyncExists(source.directory)) {
|
||||
return { cards, errors };
|
||||
}
|
||||
for (const file of listMarkdownFiles(source.directory)) {
|
||||
const card = readCard(repoRoot, file, source.archived);
|
||||
if (card === null) {
|
||||
errors.push(`Не разобрана карточка ${relativePosix(repoRoot, file)}.`);
|
||||
continue;
|
||||
}
|
||||
cards.push(card);
|
||||
}
|
||||
return { cards, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads task cards straight from the tracker files (D-060). Read-only: the
|
||||
* tracker stays the only source of truth and nothing here writes to it.
|
||||
*/
|
||||
export function readCards(options: ReaderOptions): ReadResult {
|
||||
const repoRoot = path.resolve(options.repoRoot);
|
||||
const backlogDir = path.isAbsolute(options.backlogDir)
|
||||
? path.resolve(options.backlogDir)
|
||||
: path.resolve(repoRoot, options.backlogDir);
|
||||
const sources: Source[] = [
|
||||
{ directory: path.join(backlogDir, 'tasks'), archived: false },
|
||||
{ directory: path.join(backlogDir, 'archive', 'tasks'), archived: true },
|
||||
];
|
||||
const cards: TaskCard[] = [];
|
||||
const errors: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const source of sources) {
|
||||
const read = readSource(source, repoRoot);
|
||||
errors.push(...read.errors);
|
||||
for (const card of read.cards) {
|
||||
if (seen.has(card.id)) {
|
||||
errors.push(`Идентификатор ${card.id} повторяется в прочитанных файлах.`);
|
||||
continue;
|
||||
}
|
||||
seen.add(card.id);
|
||||
cards.push(card);
|
||||
}
|
||||
}
|
||||
cards.sort((left, right) => compareIds(left.id, right.id));
|
||||
return { cards, errors };
|
||||
}
|
||||
|
||||
function statSyncExists(directory: string): boolean {
|
||||
try {
|
||||
return statSync(directory).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import type { CandidatePair, IndexedCard, SimilarHit } from './types.ts';
|
||||
|
||||
export interface Filters {
|
||||
statuses?: readonly string[];
|
||||
archivedOnly?: boolean;
|
||||
excludeArchived?: boolean;
|
||||
types?: readonly string[];
|
||||
projects?: readonly string[];
|
||||
labels?: readonly string[];
|
||||
requireAllLabels?: boolean;
|
||||
excludeIds?: readonly string[];
|
||||
}
|
||||
|
||||
interface CardMetadata {
|
||||
archived: boolean;
|
||||
type: string | null;
|
||||
project: string | null;
|
||||
labels: string[];
|
||||
}
|
||||
|
||||
function oneOf(list: readonly string[] | undefined, value: string | null): boolean {
|
||||
if (list === undefined || list.length === 0) {
|
||||
return true;
|
||||
}
|
||||
return value !== null && list.includes(value);
|
||||
}
|
||||
|
||||
function labelsOk(metadata: CardMetadata, filters: Filters): boolean {
|
||||
const wanted = filters.labels;
|
||||
if (wanted === undefined || wanted.length === 0) {
|
||||
return true;
|
||||
}
|
||||
const shared = wanted.filter((label) => metadata.labels.includes(label)).length;
|
||||
return filters.requireAllLabels === true ? shared === wanted.length : shared > 0;
|
||||
}
|
||||
|
||||
export function matches(card: IndexedCard, filters: Filters): boolean {
|
||||
const metadata = card.metadata;
|
||||
if (filters.archivedOnly === true && !metadata.archived) {
|
||||
return false;
|
||||
}
|
||||
if (filters.excludeArchived === true && metadata.archived) {
|
||||
return false;
|
||||
}
|
||||
if (!oneOf(filters.statuses, metadata.status)) {
|
||||
return false;
|
||||
}
|
||||
if (!oneOf(filters.types, metadata.type) || !oneOf(filters.projects, metadata.project)) {
|
||||
return false;
|
||||
}
|
||||
if (!labelsOk(metadata, filters)) {
|
||||
return false;
|
||||
}
|
||||
const excluded = filters.excludeIds;
|
||||
return excluded === undefined || !excluded.includes(card.id);
|
||||
}
|
||||
|
||||
/** Cosine similarity of two unit-length vectors: their dot product. */
|
||||
export function cosine(left: Float32Array, right: Float32Array): number {
|
||||
if (left.length !== right.length) {
|
||||
throw new Error('Несовпадающая размерность векторов.');
|
||||
}
|
||||
let total = 0;
|
||||
for (let index = 0; index < left.length; index += 1) {
|
||||
total += (left[index] ?? 0) * (right[index] ?? 0);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function roundScore(value: number): number {
|
||||
return Math.round(value * 1e6) / 1e6;
|
||||
}
|
||||
|
||||
function compareStrings(left: string, right: string): number {
|
||||
if (left < right) {
|
||||
return -1;
|
||||
}
|
||||
if (left > right) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Ties break on the card id so a repeated run produces identical output. */
|
||||
function compareHits(left: SimilarHit, right: SimilarHit): number {
|
||||
if (left.score !== right.score) {
|
||||
return right.score - left.score;
|
||||
}
|
||||
return compareStrings(left.id, right.id);
|
||||
}
|
||||
|
||||
export interface SimilarOptions {
|
||||
topK: number;
|
||||
filters?: Filters;
|
||||
}
|
||||
|
||||
export function topSimilar(
|
||||
cards: readonly IndexedCard[],
|
||||
query: Float32Array,
|
||||
options: SimilarOptions,
|
||||
): SimilarHit[] {
|
||||
const filters = options.filters ?? {};
|
||||
const hits: SimilarHit[] = [];
|
||||
for (const card of cards) {
|
||||
if (card.dimensions !== query.length || !matches(card, filters)) {
|
||||
continue;
|
||||
}
|
||||
hits.push({
|
||||
id: card.id,
|
||||
score: roundScore(cosine(query, card.vector)),
|
||||
metadata: card.metadata,
|
||||
});
|
||||
}
|
||||
hits.sort(compareHits);
|
||||
return hits.slice(0, Math.max(0, options.topK));
|
||||
}
|
||||
|
||||
function comparePairs(left: CandidatePair, right: CandidatePair): number {
|
||||
if (left.score !== right.score) {
|
||||
return right.score - left.score;
|
||||
}
|
||||
const first = compareStrings(left.left, right.left);
|
||||
if (first !== 0) {
|
||||
return first;
|
||||
}
|
||||
return compareStrings(left.right, right.right);
|
||||
}
|
||||
|
||||
function pairBetween(
|
||||
first: IndexedCard,
|
||||
second: IndexedCard,
|
||||
threshold: number,
|
||||
): CandidatePair | null {
|
||||
if (second.dimensions !== first.dimensions) {
|
||||
return null;
|
||||
}
|
||||
const score = roundScore(cosine(first.vector, second.vector));
|
||||
if (score < threshold) {
|
||||
return null;
|
||||
}
|
||||
const ordered = first.id <= second.id ? [first, second] : [second, first];
|
||||
const left = ordered[0];
|
||||
const right = ordered[1];
|
||||
if (left === undefined || right === undefined) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
left: left.id,
|
||||
right: right.id,
|
||||
score,
|
||||
leftMetadata: left.metadata,
|
||||
rightMetadata: right.metadata,
|
||||
};
|
||||
}
|
||||
|
||||
export interface PairOptions {
|
||||
threshold: number;
|
||||
filters?: Filters;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every distinct unordered pair above the threshold. A pair is emitted once,
|
||||
* ordered by identifier, so symmetric duplicates cannot appear twice.
|
||||
*/
|
||||
function pairsAfter(
|
||||
first: IndexedCard,
|
||||
eligible: readonly IndexedCard[],
|
||||
from: number,
|
||||
threshold: number,
|
||||
): CandidatePair[] {
|
||||
const out: CandidatePair[] = [];
|
||||
for (let index = from; index < eligible.length; index += 1) {
|
||||
const second = eligible[index];
|
||||
if (second === undefined) {
|
||||
continue;
|
||||
}
|
||||
const pair = pairBetween(first, second, threshold);
|
||||
if (pair !== null) {
|
||||
out.push(pair);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function candidatePairs(
|
||||
cards: readonly IndexedCard[],
|
||||
options: PairOptions,
|
||||
): CandidatePair[] {
|
||||
const eligible = cards.filter((card) => matches(card, options.filters ?? {}));
|
||||
const pairs: CandidatePair[] = [];
|
||||
for (let index = 0; index < eligible.length; index += 1) {
|
||||
const first = eligible[index];
|
||||
if (first === undefined) {
|
||||
continue;
|
||||
}
|
||||
pairs.push(...pairsAfter(first, eligible, index + 1, options.threshold));
|
||||
}
|
||||
pairs.sort(comparePairs);
|
||||
return options.limit === undefined ? pairs : pairs.slice(0, Math.max(0, options.limit));
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
import { mkdirSync, statSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
|
||||
import type { SQLOutputValue } from 'node:sqlite';
|
||||
|
||||
import type { IndexedCard, IndexMeta } from './types.ts';
|
||||
|
||||
// Schema version of the index itself. A mismatch forces a full rebuild because
|
||||
// the stored rows no longer describe the same thing (D-062).
|
||||
export const INDEX_VERSION = 1;
|
||||
|
||||
const SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
key TEXT NOT NULL PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS cards (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
path TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
archived INTEGER NOT NULL,
|
||||
type TEXT,
|
||||
priority TEXT,
|
||||
project TEXT,
|
||||
labels TEXT NOT NULL,
|
||||
milestone TEXT,
|
||||
parent_id TEXT,
|
||||
dependencies TEXT NOT NULL,
|
||||
content_hash TEXT NOT NULL,
|
||||
file_hash TEXT NOT NULL,
|
||||
provider_id TEXT NOT NULL,
|
||||
model_id TEXT NOT NULL,
|
||||
norm_version INTEGER NOT NULL,
|
||||
index_version INTEGER NOT NULL,
|
||||
dimensions INTEGER NOT NULL,
|
||||
vector BLOB NOT NULL,
|
||||
indexed_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
kind TEXT NOT NULL,
|
||||
started_at TEXT NOT NULL,
|
||||
finished_at TEXT NOT NULL,
|
||||
cards_total INTEGER NOT NULL,
|
||||
embedded INTEGER NOT NULL,
|
||||
reused INTEGER NOT NULL,
|
||||
metadata_only INTEGER NOT NULL,
|
||||
removed INTEGER NOT NULL,
|
||||
requests INTEGER NOT NULL,
|
||||
input_tokens INTEGER NOT NULL,
|
||||
duration_ms INTEGER NOT NULL
|
||||
);
|
||||
`;
|
||||
|
||||
type Row = Record<string, SQLOutputValue>;
|
||||
|
||||
export interface RunRecord {
|
||||
kind: string;
|
||||
startedAt: string;
|
||||
finishedAt: string;
|
||||
cardsTotal: number;
|
||||
embedded: number;
|
||||
reused: number;
|
||||
metadataOnly: number;
|
||||
removed: number;
|
||||
requests: number;
|
||||
inputTokens: number;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
export interface Store {
|
||||
readonly file: string;
|
||||
meta(): IndexMeta;
|
||||
setMeta(values: Record<string, string>): void;
|
||||
loadCards(): IndexedCard[];
|
||||
loadCard(id: string): IndexedCard | undefined;
|
||||
upsertCard(card: IndexedCard): void;
|
||||
updateMetadataOnly(id: string, card: IndexedCard): void;
|
||||
deleteCardsNotIn(ids: readonly string[]): number;
|
||||
clearCards(): number;
|
||||
dropAll(): void;
|
||||
recordRun(run: RunRecord): void;
|
||||
runs(limit?: number): RunRecord[];
|
||||
sizeBytes(): number;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
function text(row: Row, key: string): string {
|
||||
const value = row[key];
|
||||
if (typeof value !== 'string') {
|
||||
throw new Error(`Столбец ${key} отсутствует или не является текстом.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function optionalText(row: Row, key: string): string | null {
|
||||
const value = row[key];
|
||||
if (value === null || value === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (typeof value !== 'string') {
|
||||
throw new Error(`Столбец ${key} не является текстом.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function integer(row: Row, key: string): number {
|
||||
const value = row[key];
|
||||
if (typeof value === 'number') {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'bigint') {
|
||||
return Number(value);
|
||||
}
|
||||
throw new Error(`Столбец ${key} не является числом.`);
|
||||
}
|
||||
|
||||
function bytes(row: Row, key: string): Uint8Array {
|
||||
const value = row[key];
|
||||
if (!(value instanceof Uint8Array)) {
|
||||
throw new Error(`Столбец ${key} не является BLOB.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function stringList(row: Row, key: string): string[] {
|
||||
const parsed: unknown = JSON.parse(text(row, key));
|
||||
if (!Array.isArray(parsed)) {
|
||||
return [];
|
||||
}
|
||||
return parsed.filter((item): item is string => typeof item === 'string');
|
||||
}
|
||||
|
||||
function encodeVector(vector: Float32Array): Uint8Array {
|
||||
const copy = new Float32Array(vector.length);
|
||||
copy.set(vector);
|
||||
return new Uint8Array(copy.buffer);
|
||||
}
|
||||
|
||||
function decodeVector(blob: Uint8Array): Float32Array {
|
||||
const copy = new Uint8Array(blob.byteLength);
|
||||
copy.set(blob);
|
||||
return new Float32Array(copy.buffer);
|
||||
}
|
||||
|
||||
function toCard(row: Row): IndexedCard {
|
||||
return {
|
||||
id: text(row, 'id'),
|
||||
contentHash: text(row, 'content_hash'),
|
||||
fileHash: text(row, 'file_hash'),
|
||||
providerId: text(row, 'provider_id'),
|
||||
modelId: text(row, 'model_id'),
|
||||
normVersion: integer(row, 'norm_version'),
|
||||
indexVersion: integer(row, 'index_version'),
|
||||
dimensions: integer(row, 'dimensions'),
|
||||
vector: decodeVector(bytes(row, 'vector')),
|
||||
indexedAt: text(row, 'indexed_at'),
|
||||
metadata: {
|
||||
path: text(row, 'path'),
|
||||
title: text(row, 'title'),
|
||||
status: text(row, 'status'),
|
||||
archived: integer(row, 'archived') !== 0,
|
||||
type: optionalText(row, 'type'),
|
||||
priority: optionalText(row, 'priority'),
|
||||
project: optionalText(row, 'project'),
|
||||
labels: stringList(row, 'labels'),
|
||||
milestone: optionalText(row, 'milestone'),
|
||||
parentId: optionalText(row, 'parent_id'),
|
||||
dependencies: stringList(row, 'dependencies'),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const UPSERT = `INSERT INTO cards (id, path, title, status, archived, type, priority, project, labels,
|
||||
milestone, parent_id, dependencies, content_hash, file_hash, provider_id, model_id,
|
||||
norm_version, index_version, dimensions, vector, indexed_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
path = excluded.path, title = excluded.title, status = excluded.status,
|
||||
archived = excluded.archived, type = excluded.type, priority = excluded.priority,
|
||||
project = excluded.project, labels = excluded.labels, milestone = excluded.milestone,
|
||||
parent_id = excluded.parent_id, dependencies = excluded.dependencies,
|
||||
content_hash = excluded.content_hash, file_hash = excluded.file_hash,
|
||||
provider_id = excluded.provider_id, model_id = excluded.model_id,
|
||||
norm_version = excluded.norm_version, index_version = excluded.index_version,
|
||||
dimensions = excluded.dimensions, vector = excluded.vector,
|
||||
indexed_at = excluded.indexed_at`;
|
||||
|
||||
const METADATA_UPDATE = `UPDATE cards SET path = ?, title = ?, status = ?, archived = ?, type = ?,
|
||||
priority = ?, project = ?, labels = ?, milestone = ?, parent_id = ?, dependencies = ?,
|
||||
file_hash = ?, indexed_at = ?
|
||||
WHERE id = ?`;
|
||||
|
||||
const INSERT_RUN = `INSERT INTO runs (kind, started_at, finished_at, cards_total, embedded, reused,
|
||||
metadata_only, removed, requests, input_tokens, duration_ms)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
|
||||
|
||||
interface Statements {
|
||||
selectCards: ReturnType<DatabaseSync['prepare']>;
|
||||
selectCard: ReturnType<DatabaseSync['prepare']>;
|
||||
selectIds: ReturnType<DatabaseSync['prepare']>;
|
||||
selectMeta: ReturnType<DatabaseSync['prepare']>;
|
||||
writeMeta: ReturnType<DatabaseSync['prepare']>;
|
||||
upsert: ReturnType<DatabaseSync['prepare']>;
|
||||
metadataUpdate: ReturnType<DatabaseSync['prepare']>;
|
||||
deleteCard: ReturnType<DatabaseSync['prepare']>;
|
||||
clearCards: ReturnType<DatabaseSync['prepare']>;
|
||||
countCards: ReturnType<DatabaseSync['prepare']>;
|
||||
insertRun: ReturnType<DatabaseSync['prepare']>;
|
||||
selectRuns: ReturnType<DatabaseSync['prepare']>;
|
||||
}
|
||||
|
||||
function prepareStatements(db: DatabaseSync): Statements {
|
||||
return {
|
||||
selectCards: db.prepare('SELECT * FROM cards ORDER BY id'),
|
||||
selectCard: db.prepare('SELECT * FROM cards WHERE id = ?'),
|
||||
selectIds: db.prepare('SELECT id FROM cards ORDER BY id'),
|
||||
selectMeta: db.prepare('SELECT key, value FROM meta'),
|
||||
writeMeta: db.prepare(
|
||||
'INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
|
||||
),
|
||||
upsert: db.prepare(UPSERT),
|
||||
metadataUpdate: db.prepare(METADATA_UPDATE),
|
||||
deleteCard: db.prepare('DELETE FROM cards WHERE id = ?'),
|
||||
clearCards: db.prepare('DELETE FROM cards'),
|
||||
countCards: db.prepare('SELECT COUNT(*) AS total FROM cards'),
|
||||
insertRun: db.prepare(INSERT_RUN),
|
||||
selectRuns: db.prepare('SELECT * FROM runs ORDER BY id DESC LIMIT ?'),
|
||||
};
|
||||
}
|
||||
|
||||
function transaction<T>(db: DatabaseSync, body: () => T): T {
|
||||
db.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
const result = body();
|
||||
db.exec('COMMIT');
|
||||
return result;
|
||||
} catch (cause) {
|
||||
db.exec('ROLLBACK');
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
|
||||
function metaValues(statements: Statements): Record<string, string> {
|
||||
const values: Record<string, string> = {};
|
||||
for (const row of statements.selectMeta.all()) {
|
||||
values[text(row, 'key')] = text(row, 'value');
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function metaOf(statements: Statements): IndexMeta {
|
||||
const values = metaValues(statements);
|
||||
const number = (key: string): number | null => {
|
||||
const raw = values[key];
|
||||
if (raw === undefined || raw === '') {
|
||||
return null;
|
||||
}
|
||||
const parsed = Number(raw);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
};
|
||||
const countRow = statements.countCards.get();
|
||||
return {
|
||||
indexVersion: number('index_version') ?? 0,
|
||||
normVersion: number('norm_version'),
|
||||
providerId: values['provider_id'] ?? null,
|
||||
modelId: values['model_id'] ?? null,
|
||||
dimensions: number('dimensions'),
|
||||
createdAt: values['created_at'] ?? '',
|
||||
lastSyncAt: values['last_sync_at'] ?? null,
|
||||
cardCount: countRow === undefined ? 0 : integer(countRow, 'total'),
|
||||
};
|
||||
}
|
||||
|
||||
function cardParameters(card: IndexedCard): (string | number | Uint8Array | null)[] {
|
||||
return [
|
||||
card.id,
|
||||
card.metadata.path,
|
||||
card.metadata.title,
|
||||
card.metadata.status,
|
||||
card.metadata.archived ? 1 : 0,
|
||||
card.metadata.type,
|
||||
card.metadata.priority,
|
||||
card.metadata.project,
|
||||
JSON.stringify(card.metadata.labels),
|
||||
card.metadata.milestone,
|
||||
card.metadata.parentId,
|
||||
JSON.stringify(card.metadata.dependencies),
|
||||
card.contentHash,
|
||||
card.fileHash,
|
||||
card.providerId,
|
||||
card.modelId,
|
||||
card.normVersion,
|
||||
card.indexVersion,
|
||||
card.dimensions,
|
||||
encodeVector(card.vector),
|
||||
card.indexedAt,
|
||||
];
|
||||
}
|
||||
|
||||
function metadataParameters(card: IndexedCard): (string | number | null)[] {
|
||||
return [
|
||||
card.metadata.path,
|
||||
card.metadata.title,
|
||||
card.metadata.status,
|
||||
card.metadata.archived ? 1 : 0,
|
||||
card.metadata.type,
|
||||
card.metadata.priority,
|
||||
card.metadata.project,
|
||||
JSON.stringify(card.metadata.labels),
|
||||
card.metadata.milestone,
|
||||
card.metadata.parentId,
|
||||
JSON.stringify(card.metadata.dependencies),
|
||||
card.fileHash,
|
||||
card.indexedAt,
|
||||
];
|
||||
}
|
||||
|
||||
function toRunRecord(row: Row): RunRecord {
|
||||
return {
|
||||
kind: text(row, 'kind'),
|
||||
startedAt: text(row, 'started_at'),
|
||||
finishedAt: text(row, 'finished_at'),
|
||||
cardsTotal: integer(row, 'cards_total'),
|
||||
embedded: integer(row, 'embedded'),
|
||||
reused: integer(row, 'reused'),
|
||||
metadataOnly: integer(row, 'metadata_only'),
|
||||
removed: integer(row, 'removed'),
|
||||
requests: integer(row, 'requests'),
|
||||
inputTokens: integer(row, 'input_tokens'),
|
||||
durationMs: integer(row, 'duration_ms'),
|
||||
};
|
||||
}
|
||||
|
||||
function sizeOnDisk(file: string, inMemory: boolean): number {
|
||||
if (inMemory) {
|
||||
return 0;
|
||||
}
|
||||
let total = 0;
|
||||
for (const suffix of ['', '-wal', '-shm']) {
|
||||
try {
|
||||
total += statSync(`${file}${suffix}`).size;
|
||||
} catch {
|
||||
// Absent side files are normal for a checkpointed database.
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
export interface StoreOptions {
|
||||
/** Database file path, or `:memory:` for a throwaway store. */
|
||||
file: string;
|
||||
busyTimeoutMs?: number;
|
||||
}
|
||||
|
||||
interface Handle {
|
||||
db: DatabaseSync;
|
||||
statements: Statements;
|
||||
options: StoreOptions;
|
||||
}
|
||||
|
||||
function deleteStale(handle: Handle, ids: readonly string[]): number {
|
||||
const wanted = new Set(ids);
|
||||
const doomed = handle.statements.selectIds
|
||||
.all()
|
||||
.map((row) => text(row, 'id'))
|
||||
.filter((id) => !wanted.has(id));
|
||||
if (doomed.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
transaction(handle.db, () => {
|
||||
for (const id of doomed) {
|
||||
handle.statements.deleteCard.run(id);
|
||||
}
|
||||
});
|
||||
return doomed.length;
|
||||
}
|
||||
|
||||
function createStore(handle: Handle): Store {
|
||||
const { db, statements, options } = handle;
|
||||
const inMemory = options.file === ':memory:';
|
||||
return {
|
||||
file: options.file,
|
||||
meta: () => metaOf(statements),
|
||||
setMeta: (values: Record<string, string>) => {
|
||||
transaction(db, () => {
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
statements.writeMeta.run(key, value);
|
||||
}
|
||||
});
|
||||
},
|
||||
loadCards: () => statements.selectCards.all().map((row) => toCard(row)),
|
||||
loadCard: (id: string) => {
|
||||
const row = statements.selectCard.get(id);
|
||||
return row === undefined ? undefined : toCard(row);
|
||||
},
|
||||
upsertCard: (card: IndexedCard) => {
|
||||
transaction(db, () => {
|
||||
statements.upsert.run(...cardParameters(card));
|
||||
});
|
||||
},
|
||||
updateMetadataOnly: (id: string, card: IndexedCard) => {
|
||||
transaction(db, () => {
|
||||
statements.metadataUpdate.run(...metadataParameters(card), id);
|
||||
});
|
||||
},
|
||||
deleteCardsNotIn: (ids: readonly string[]) => deleteStale(handle, ids),
|
||||
clearCards: () => Number(statements.clearCards.run().changes),
|
||||
dropAll: () => {
|
||||
db.exec('DROP TABLE IF EXISTS cards;');
|
||||
db.exec('DROP TABLE IF EXISTS runs;');
|
||||
db.exec('DROP TABLE IF EXISTS meta;');
|
||||
db.exec(SCHEMA);
|
||||
},
|
||||
recordRun: (run: RunRecord) => {
|
||||
statements.insertRun.run(
|
||||
run.kind,
|
||||
run.startedAt,
|
||||
run.finishedAt,
|
||||
run.cardsTotal,
|
||||
run.embedded,
|
||||
run.reused,
|
||||
run.metadataOnly,
|
||||
run.removed,
|
||||
run.requests,
|
||||
run.inputTokens,
|
||||
run.durationMs,
|
||||
);
|
||||
},
|
||||
runs: (limit = 20) => statements.selectRuns.all(limit).map((row) => toRunRecord(row)),
|
||||
sizeBytes: () => sizeOnDisk(options.file, inMemory),
|
||||
close: () => {
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Vector store on the built-in SQLite module (D-062): WAL plus a busy timeout
|
||||
* so several agents can read and write one index without corrupting it, and one
|
||||
* transaction per card so an interrupted run simply resumes (D-062).
|
||||
*/
|
||||
export function openStore(options: StoreOptions): Store {
|
||||
const inMemory = options.file === ':memory:';
|
||||
if (!inMemory) {
|
||||
mkdirSync(path.dirname(path.resolve(options.file)), { recursive: true });
|
||||
}
|
||||
const db = new DatabaseSync(options.file);
|
||||
db.exec('PRAGMA journal_mode = WAL;');
|
||||
db.exec(`PRAGMA busy_timeout = ${String(options.busyTimeoutMs ?? 5000)};`);
|
||||
db.exec('PRAGMA synchronous = NORMAL;');
|
||||
db.exec(SCHEMA);
|
||||
const statements = prepareStatements(db);
|
||||
const handle = { db, statements, options };
|
||||
// Bootstrap the schema marker so an interrupted run is resumed, not reset.
|
||||
if (metaValues(statements)['index_version'] === undefined) {
|
||||
transaction(db, () => {
|
||||
statements.writeMeta.run('index_version', String(INDEX_VERSION));
|
||||
});
|
||||
}
|
||||
return createStore(handle);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Shared shapes of the backlog index. Backlog.md stays the only source of
|
||||
// truth: everything here is derived and rebuildable (D-060).
|
||||
|
||||
/** A task card as read from the tracker files. Checkbox state is dropped here. */
|
||||
export interface TaskCard {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
archived: boolean;
|
||||
/** Repository-relative POSIX path of the card file. */
|
||||
path: string;
|
||||
type: string | null;
|
||||
priority: string | null;
|
||||
project: string | null;
|
||||
labels: string[];
|
||||
milestone: string | null;
|
||||
parentId: string | null;
|
||||
dependencies: string[];
|
||||
description: string;
|
||||
/** Acceptance criterion texts in document order, without checkbox markers. */
|
||||
acceptanceCriteria: string[];
|
||||
/** SHA-256 of the raw card bytes: cheap "did the file change" detector. */
|
||||
fileHash: string;
|
||||
}
|
||||
|
||||
/** Canonical intent text plus the hash that decides whether to re-embed. */
|
||||
export interface NormalizedIntent {
|
||||
text: string;
|
||||
hash: string;
|
||||
normVersion: number;
|
||||
}
|
||||
|
||||
/** Metadata kept beside the vector; never part of the vector itself. */
|
||||
export interface CardMetadata {
|
||||
path: string;
|
||||
title: string;
|
||||
status: string;
|
||||
archived: boolean;
|
||||
type: string | null;
|
||||
priority: string | null;
|
||||
project: string | null;
|
||||
labels: string[];
|
||||
milestone: string | null;
|
||||
parentId: string | null;
|
||||
dependencies: string[];
|
||||
}
|
||||
|
||||
export interface IndexedCard {
|
||||
id: string;
|
||||
contentHash: string;
|
||||
fileHash: string;
|
||||
providerId: string;
|
||||
modelId: string;
|
||||
normVersion: number;
|
||||
indexVersion: number;
|
||||
dimensions: number;
|
||||
/** Unit-length vector, Float32 little-endian. */
|
||||
vector: Float32Array;
|
||||
metadata: CardMetadata;
|
||||
indexedAt: string;
|
||||
}
|
||||
|
||||
export interface IndexMeta {
|
||||
indexVersion: number;
|
||||
normVersion: number | null;
|
||||
providerId: string | null;
|
||||
modelId: string | null;
|
||||
dimensions: number | null;
|
||||
createdAt: string;
|
||||
lastSyncAt: string | null;
|
||||
cardCount: number;
|
||||
}
|
||||
|
||||
export interface SimilarHit {
|
||||
id: string;
|
||||
score: number;
|
||||
metadata: CardMetadata;
|
||||
}
|
||||
|
||||
export interface CandidatePair {
|
||||
left: string;
|
||||
right: string;
|
||||
score: number;
|
||||
leftMetadata: CardMetadata;
|
||||
rightMetadata: CardMetadata;
|
||||
}
|
||||
|
||||
export type DiagnosticLevel = 'error' | 'warning' | 'recommendation';
|
||||
|
||||
export interface DiagnosticFinding {
|
||||
id: string;
|
||||
status: string;
|
||||
title: string;
|
||||
score: number | null;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface Diagnostic {
|
||||
rule: string;
|
||||
level: DiagnosticLevel;
|
||||
message: string;
|
||||
findings: DiagnosticFinding[];
|
||||
}
|
||||
|
||||
export interface LintResult {
|
||||
ok: boolean;
|
||||
semantic: boolean;
|
||||
/** True when the semantic layer could not run and reported why. */
|
||||
semanticUnavailable: boolean;
|
||||
semanticError: string | null;
|
||||
diagnostics: Diagnostic[];
|
||||
}
|
||||
|
||||
export interface SyncCounters {
|
||||
cards: number;
|
||||
embedded: number;
|
||||
reused: number;
|
||||
metadataOnly: number;
|
||||
removed: number;
|
||||
requests: number;
|
||||
inputTokens: number;
|
||||
durationMs: number;
|
||||
}
|
||||
@@ -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} не найдена в бэклоге`,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2024",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "tests/**/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user