From 0b448a8b8aebcfd89957cf9f71a2e18d856c80ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 05:46:05 +0500 Subject: [PATCH 1/9] PEP-34/42/52: OpenSpec changes (board order, epic planner, command palette) Co-Authored-By: Claude Opus 5.5 --- openspec/changes/pep-34-board-order/design.md | 25 +++++++++++++ .../changes/pep-34-board-order/proposal.md | 32 +++++++++++++++++ .../specs/project-autonomy/spec.md | 10 ++++++ .../specs/web-workspace/spec.md | 35 ++++++++++++++++++ openspec/changes/pep-34-board-order/tasks.md | 19 ++++++++++ .../changes/pep-42-epic-planner/design.md | 29 +++++++++++++++ .../changes/pep-42-epic-planner/proposal.md | 36 +++++++++++++++++++ .../specs/project-autonomy/spec.md | 10 ++++++ .../specs/story-planning/spec.md | 31 ++++++++++++++++ openspec/changes/pep-42-epic-planner/tasks.md | 19 ++++++++++ .../changes/pep-52-command-palette/design.md | 14 ++++++++ .../pep-52-command-palette/proposal.md | 25 +++++++++++++ .../specs/web-workspace/spec.md | 23 ++++++++++++ .../changes/pep-52-command-palette/tasks.md | 12 +++++++ 14 files changed, 320 insertions(+) create mode 100644 openspec/changes/pep-34-board-order/design.md create mode 100644 openspec/changes/pep-34-board-order/proposal.md create mode 100644 openspec/changes/pep-34-board-order/specs/project-autonomy/spec.md create mode 100644 openspec/changes/pep-34-board-order/specs/web-workspace/spec.md create mode 100644 openspec/changes/pep-34-board-order/tasks.md create mode 100644 openspec/changes/pep-42-epic-planner/design.md create mode 100644 openspec/changes/pep-42-epic-planner/proposal.md create mode 100644 openspec/changes/pep-42-epic-planner/specs/project-autonomy/spec.md create mode 100644 openspec/changes/pep-42-epic-planner/specs/story-planning/spec.md create mode 100644 openspec/changes/pep-42-epic-planner/tasks.md create mode 100644 openspec/changes/pep-52-command-palette/design.md create mode 100644 openspec/changes/pep-52-command-palette/proposal.md create mode 100644 openspec/changes/pep-52-command-palette/specs/web-workspace/spec.md create mode 100644 openspec/changes/pep-52-command-palette/tasks.md diff --git a/openspec/changes/pep-34-board-order/design.md b/openspec/changes/pep-34-board-order/design.md new file mode 100644 index 00000000..8d4b90bf --- /dev/null +++ b/openspec/changes/pep-34-board-order/design.md @@ -0,0 +1,25 @@ +# Design: PEP-34 + +## Порядок +- `position REAL`: вставка между соседями — среднее арифметическое, без перенумерации. Если + разрыв стал меньше 1e-6 — перенумеровать колонку проекта (1, 2, 3 …) в одной транзакции. +- Порядок общий для проекта, а не по колонке: карточка, ушедшая в работу и вернувшаяся, + сохраняет место. Перетаскивание считает соседей только внутри видимой колонки. +- Приоритет = порядок (как в описании стори): отдельного поля «приоритет» нет — две оси + сортировки путали бы и PM, и диспетчер. +- Новая стори: `max(position)+1` по проекту (в той же транзакции, где выдаётся номер). + +## Архив, а не удаление +- Удаление каскадом стёрло бы события, вопросы и связь с инцидентами — история важнее. + `archived_at` скрывает стори везде, где идёт выбор работы (доска, диспетчер, пуш простоя, + прогресс, `list_tasks`), но `get_task`/страница стори работают. +- Архивирование останавливает активные сессии стори (`moveTask(..., "backlog")` если не + done/review) — агент не должен работать над невидимой карточкой. + +## Прогресс эпика +- `epicProgress(db, projectId)` → `Map` по неархивным стори. + +## Веб +- Перетаскивание: drop на карточку = поставить перед ней (в нижнюю половину — после неё); + drop на пустое место своей колонки = в конец. Server action `reorderTaskCard`. +- Сворачивание «Готово»: `localStorage` `peppa.board.doneCollapsed`, по умолчанию развёрнуто. diff --git a/openspec/changes/pep-34-board-order/proposal.md b/openspec/changes/pep-34-board-order/proposal.md new file mode 100644 index 00000000..82eca4e2 --- /dev/null +++ b/openspec/changes/pep-34-board-order/proposal.md @@ -0,0 +1,32 @@ +# PEP-34: Доска — порядок (приоритет), прогресс эпика, архив, свёрнутое «Готово» + +## Why +На доске нельзя задать, что важнее: карточки стоят по номеру, и диспетчер бэклога (PEP-24) +берёт самую старую стори. Не видно, насколько продвинулся эпик. Колонка «Готово» растёт +бесконечно, а ненужную стори нельзя убрать с доски. + +## What Changes +- Порядок стори внутри колонки = приоритет: поле `tasks.position` (REAL, меньше = выше). + Перетаскивание карточки внутри колонки (над другой карточкой) ставит её между соседями; + кнопки «Наверх»/«Вниз» в меню карточки. Новая стори встаёт в конец бэклога. +- Диспетчер (PEP-24), пуш «Агенты простаивают» и `list_tasks` идут в этом порядке + (позиция, затем номер). Существующие стори получают позицию = номер (порядок не меняется). +- Прогресс эпика: «готово/всего» (готово = `done`) и полоса — в фильтре эпиков над доской и в + блоке «Эпики» настроек; MCP `list_epics` показывает то же. +- Архив стори: `tasks.archived_at`. Архивная стори пропадает с доски, из диспетчера и прогресса + эпика, её агент останавливается; вернуть можно на странице стори. Удаления нет — история + (события, вопросы, сессии) остаётся. +- Колонка «Готово» сворачивается (запоминается в браузере); в свёрнутом виде видна только + шапка со счётчиком. +- MCP (удалённый и агента): `reorder_task` (top/bottom/before/after), `archive_task` + (archive/restore); `/help` описывает их. + +## Capabilities +### Modified Capabilities +- `web-workspace`: порядок карточек, прогресс эпика, архив, сворачивание «Готово». +- `project-autonomy`: диспетчер берёт стори по порядку на доске. + +## Impact +- Миграция: `tasks.position` (REAL NOT NULL DEFAULT 0, заполняется номером), `tasks.archived_at`. +- core/tasks.ts (`reorderTask`, `archiveTask`, `epicProgress`, сортировка `listTasks`), + runner/autonomy.ts, web Board/страница проекта/стори, MCP manager + agent, `/help`. diff --git a/openspec/changes/pep-34-board-order/specs/project-autonomy/spec.md b/openspec/changes/pep-34-board-order/specs/project-autonomy/spec.md new file mode 100644 index 00000000..5eed1a93 --- /dev/null +++ b/openspec/changes/pep-34-board-order/specs/project-autonomy/spec.md @@ -0,0 +1,10 @@ +## ADDED Requirements + +### Requirement: Диспетчер берёт стори по порядку доски +Диспетчер бэклога и пуш «Агенты простаивают» SHALL выбирать стори в порядке доски (позиция, +затем номер), пропуская архивные. + +#### Scenario: Поднятая стори идёт первой +- **GIVEN** автономность «авто», WIP 1, бэклог PAY-1, PAY-2, PM поднял PAY-2 наверх +- **WHEN** вачдог запускает диспетчер +- **THEN** агент запускается на PAY-2 diff --git a/openspec/changes/pep-34-board-order/specs/web-workspace/spec.md b/openspec/changes/pep-34-board-order/specs/web-workspace/spec.md new file mode 100644 index 00000000..1d87e16c --- /dev/null +++ b/openspec/changes/pep-34-board-order/specs/web-workspace/spec.md @@ -0,0 +1,35 @@ +## ADDED Requirements + +### Requirement: Порядок стори на доске +Стори проекта SHALL иметь порядок (приоритет), общий для проекта: карточки в колонке идут по +нему, PM меняет его перетаскиванием внутри колонки или командами «Наверх»/«Вниз», MCP +`reorder_task`. Новая стори встаёт в конец. + +#### Scenario: Поднять стори +- **GIVEN** в бэклоге PAY-1, PAY-2, PAY-3 +- **WHEN** PM перетаскивает PAY-3 на PAY-1 +- **THEN** порядок бэклога — PAY-3, PAY-1, PAY-2, и он сохраняется после перезагрузки + +### Requirement: Прогресс эпика +Веб и MCP SHALL показывать для каждого открытого эпика «готово/всего» по его неархивным стори +и полосу прогресса. + +#### Scenario: Эпик наполовину готов +- **GIVEN** у эпика «Оплата» 4 стори, 2 из них в «Готово» +- **THEN** фильтр эпиков показывает «Оплата 2/4» с полосой на 50% + +### Requirement: Архив стори +PM SHALL уметь убрать стори в архив и вернуть её. Архивная стори не видна на доске, не +считается в прогрессе, её не берёт диспетчер, её агент останавливается; история сохраняется. + +#### Scenario: Убрать ненужную стори +- **GIVEN** стори PAY-5 в бэклоге +- **WHEN** PM нажимает «В архив» на странице стори +- **THEN** PAY-5 пропадает с доски, страница стори показывает «в архиве» и кнопку «Вернуть» + +### Requirement: Свёрнутая колонка «Готово» +Колонку «Готово» SHALL можно свернуть до шапки со счётчиком; выбор запоминается в браузере. + +#### Scenario: Свернуть +- **WHEN** PM сворачивает «Готово» +- **THEN** карточки колонки скрыты, видно «Готово 12», после перезагрузки колонка свёрнута diff --git a/openspec/changes/pep-34-board-order/tasks.md b/openspec/changes/pep-34-board-order/tasks.md new file mode 100644 index 00000000..ee5dc3b8 --- /dev/null +++ b/openspec/changes/pep-34-board-order/tasks.md @@ -0,0 +1,19 @@ +## 1. Данные +- [ ] 1.1 Схема: `tasks.position`, `tasks.archived_at`; миграция с заполнением position = number +- [ ] 1.2 core: `listTasks` по позиции, без архивных (флаг `includeArchived`); `createTask` в конец +- [ ] 1.3 core: `reorderTask` (top/bottom/before/after, перенумерация), `archiveTask`/`restoreTask`, `epicProgress` + +## 2. Диспетчер +- [ ] 2.1 runner/autonomy: бэклог по позиции (уже через `listTasks`), архив стори останавливает агента + +## 3. Веб +- [ ] 3.1 Board: перетаскивание внутри колонки, «Наверх/Вниз», сворачивание «Готово» +- [ ] 3.2 Прогресс эпика в фильтре и в блоке «Эпики» +- [ ] 3.3 Архив/возврат на странице стори + +## 4. MCP и справка +- [ ] 4.1 `reorder_task`, `archive_task` (удалённый и агента), прогресс в `list_epics` +- [ ] 4.2 `/help` + +## 5. Тесты +- [ ] 5.1 e2e: порядок, диспетчер берёт верхнюю, архив, прогресс diff --git a/openspec/changes/pep-42-epic-planner/design.md b/openspec/changes/pep-42-epic-planner/design.md new file mode 100644 index 00000000..e83373d7 --- /dev/null +++ b/openspec/changes/pep-42-epic-planner/design.md @@ -0,0 +1,29 @@ +# Design: PEP-42 + +## Зависимости +- `task_deps(task_id, blocked_by_id)` — PK пары, оба FK на `tasks` с `ON DELETE CASCADE`. +- «Разблокирована» = все предшественники в `review`/`done` или в архиве. `review` — как в + постановке стори: предшественник готов к приёмке, его PR уже есть; ждать мержа значило бы + простаивать при ручном мерже. +- Проверка цикла — обход графа от нового предшественника назад к стори (графы маленькие). +- `setDependencies(ref, keys[])` заменяет весь список; `addDependency`/`removeDependency` — + точечно. События `task_updated` с `blockedBy` для журнала. + +## Планировщик +- Тот же путь, что у триажа и ревьюера: `claudePrint` (пустой cwd, токен подписки пула + проекта, `--max-turns 1`). Таймаут `PEPPA_PLANNER_TIMEOUT_MS` (по умолчанию 180 с). +- Формат ответа — одна строка JSON: + `{"stories":[{"title":"…","description":"…","depends_on":[1,"PAY-3"]}]}`; номера — с 1 по + плану. Парсер берёт первый JSON-объект с `stories`, отбрасывает пустые названия, ссылки + вперёд допускает (цикл в плане — ошибка при утверждении), не больше 15 стори. +- Почему черновик, а не сразу стори: PM правит и утверждает (постановка); черновик в + `settings` — без новой таблицы, один на эпик, перезаписывается следующим запуском. +- `applyPlan` создаёт стори последовательно, затем зависимости; при ошибке зависимостей + созданные стори остаются (их видно на доске) — сообщение говорит, что не так. +- MCP `plan_epic` синхронный (до ~3 мин) — для удалённых клиентов это допустимо; веб + запускает его в server action с индикатором. + +## Мок +`mock-planner` (testkit) — контракт `claude -p --output-format json`: читает промпт, отвечает +конвертом с `result` = JSON плана из `MOCK_PLANNER_SCENARIO` (`stories`, `fail`, `hang`, +`garbage`); лог вызовов в `.log.jsonl`. diff --git a/openspec/changes/pep-42-epic-planner/proposal.md b/openspec/changes/pep-42-epic-planner/proposal.md new file mode 100644 index 00000000..5dc6e04c --- /dev/null +++ b/openspec/changes/pep-42-epic-planner/proposal.md @@ -0,0 +1,36 @@ +# PEP-42: Планировщик — разбить эпик на стори с зависимостями + +## Why +PM пишет эпик (цель) и сам придумывает стори. Нужно, чтобы Пеппа предлагала разбивку со +стори, критериями готовности и зависимостями, а диспетчер не брал стори, чей предшественник +ещё не сделан. + +## What Changes +- Зависимости стори: таблица `task_deps` («PAY-3 ждёт PAY-2»). Стори заблокирована, пока хоть + один предшественник не в `review`/`done` (архивный предшественник не блокирует). Циклы и + зависимость от стори другого проекта отклоняются. +- Диспетчер (PEP-24) и пуш «Агенты простаивают» пропускают заблокированные стори. PM руками + запустить может (доска не мешает), но карточка показывает «ждёт PAY-2». +- Планировщик: `planEpic` (runner/planner.ts) — один короткий `claude -p --output-format json` + (`$PEPPA_PLANNER_BIN`, модель `${PEPPA_PLANNER_MODEL:-sonnet}`) на подписке пула проекта, по + мини-промпту: эпик, его описание, уже существующие стори эпика, пожелания PM → JSON-список + стори (название, описание с «Критериями готовности», зависимости по номеру в плане или + ключу существующей стори). Ответ не по формату / ошибка — сообщение PM, ничего не создано. +- Черновик плана хранится в `settings` (`planner.draft:`); PM правит его в вебе + (страница «Спланировать эпик»: снять галочку, поправить название/описание/зависимости) и + утверждает — стори создаются в бэклоге под эпиком в порядке плана, с зависимостями. +- Веб: на карточке — «ждёт PAY-2», на странице стори — блок «Зависимости» (добавить/убрать). +- MCP (удалённый): `plan_epic`, `apply_plan`, `set_dependencies`; `create_task`/`update_task` + принимают `blocked_by`; `get_task`/`list_tasks` показывают зависимости. Агентский MCP: + `create_task` с `blocked_by`, `get_task` с зависимостями. `/help`. + +## Capabilities +### New Capabilities +- `story-planning`: зависимости стори и планировщик эпика. +### Modified Capabilities +- `project-autonomy`: диспетчер не берёт заблокированные стори. + +## Impact +- Миграция: таблица `task_deps`. +- core/deps.ts, runner/planner.ts, mock-planner (testkit), web страница плана, карточка, стори, + MCP, `/help`. diff --git a/openspec/changes/pep-42-epic-planner/specs/project-autonomy/spec.md b/openspec/changes/pep-42-epic-planner/specs/project-autonomy/spec.md new file mode 100644 index 00000000..be906ae8 --- /dev/null +++ b/openspec/changes/pep-42-epic-planner/specs/project-autonomy/spec.md @@ -0,0 +1,10 @@ +## ADDED Requirements + +### Requirement: Диспетчер ждёт предшественников +Диспетчер бэклога и пуш «Агенты простаивают» SHALL пропускать заблокированные стори и брать +следующую разблокированную по порядку доски. + +#### Scenario: Сначала предшественник +- **GIVEN** автономность «авто», WIP 1, PAY-1 ждёт PAY-2, PAY-1 выше в бэклоге +- **WHEN** вачдог запускает диспетчер +- **THEN** агент запускается на PAY-2, PAY-1 остаётся в бэклоге до ревью PAY-2 diff --git a/openspec/changes/pep-42-epic-planner/specs/story-planning/spec.md b/openspec/changes/pep-42-epic-planner/specs/story-planning/spec.md new file mode 100644 index 00000000..42207b8c --- /dev/null +++ b/openspec/changes/pep-42-epic-planner/specs/story-planning/spec.md @@ -0,0 +1,31 @@ +## ADDED Requirements + +### Requirement: Зависимости стори +Стори SHALL могут зависеть от других стори того же проекта. Стори заблокирована, пока хоть +один её предшественник не в «Ревью»/«Готово» и не в архиве. Циклы и межпроектные зависимости +отклоняются. Карточка и страница стори показывают, чего она ждёт. + +#### Scenario: Цикл отклонён +- **GIVEN** PAY-3 ждёт PAY-2 +- **WHEN** PM делает PAY-2 зависимой от PAY-3 +- **THEN** ошибка «цикл зависимостей», зависимости не меняются + +#### Scenario: Карточка показывает блокировку +- **GIVEN** PAY-3 ждёт PAY-2, PAY-2 в бэклоге +- **THEN** на карточке PAY-3 видно «ждёт PAY-2» + +### Requirement: Планировщик эпика +По кнопке «Спланировать» (веб) или MCP `plan_epic` Пеппа SHALL одним коротким запуском +Claude на подписке пула проекта предлагать список стори эпика с описанием, критериями +готовности и зависимостями. План — черновик: PM правит и утверждает его, после чего стори +создаются в бэклоге под эпиком в порядке плана, с зависимостями. Ошибка или ответ не по +формату ничего не создают и показываются PM. + +#### Scenario: Разбить эпик +- **GIVEN** эпик «Оплата картой» без стори +- **WHEN** PM нажимает «Спланировать», снимает одну стори из трёх и утверждает +- **THEN** в бэклоге две новые стори с эпиком «Оплата картой» и зависимостями из плана + +#### Scenario: Планировщик ответил мусором +- **WHEN** ответ планировщика не JSON со списком стори +- **THEN** PM видит «планировщик ответил не по формату», стори не созданы diff --git a/openspec/changes/pep-42-epic-planner/tasks.md b/openspec/changes/pep-42-epic-planner/tasks.md new file mode 100644 index 00000000..690b5ada --- /dev/null +++ b/openspec/changes/pep-42-epic-planner/tasks.md @@ -0,0 +1,19 @@ +## 1. Зависимости +- [ ] 1.1 Схема `task_deps` + миграция +- [ ] 1.2 core/deps.ts: add/remove/set, цикл, `blockersOf`, `isBlocked`, `blockedMap` +- [ ] 1.3 Диспетчер и пуш простоя пропускают заблокированные + +## 2. Планировщик +- [ ] 2.1 runner/planner.ts: промпт, парсер, `planEpic` (черновик в settings), `applyPlan` +- [ ] 2.2 mock-planner (testkit) + +## 3. Веб +- [ ] 3.1 Страница «Спланировать эпик» (запуск, правка, утверждение) +- [ ] 3.2 Карточка «ждёт …», блок «Зависимости» на странице стори + +## 4. MCP и справка +- [ ] 4.1 `plan_epic`, `apply_plan`, `set_dependencies`, `blocked_by` в create/update_task, вывод в get_task/list_tasks +- [ ] 4.2 `/help` + +## 5. Тесты +- [ ] 5.1 e2e: циклы, диспетчер ждёт предшественника, планировщик на моке (успех, мусор, ошибка), applyPlan diff --git a/openspec/changes/pep-52-command-palette/design.md b/openspec/changes/pep-52-command-palette/design.md new file mode 100644 index 00000000..94ddba64 --- /dev/null +++ b/openspec/changes/pep-52-command-palette/design.md @@ -0,0 +1,14 @@ +# Design: PEP-52 + +- Палитра — клиентский компонент в раскладке `(app)`; при первом открытии грузит + `/api/palette` (проекты, неархивные стори до 500 последних, активные/последние раннеры до 50, + открытые вопросы) и кэширует на 30 с. Фильтр — на клиенте: все слова запроса должны входить + в строку (ключ, название, проект), ранжирование: совпадение с ключом, затем начало слова. +- Действие «В работу» — тот же server action `moveTaskCard`, что у доски (проверка доступа + там же); после — `router.refresh()`. +- Горячие клавиши — один `keydown` на document; игнорируются в `input/textarea/select/ + [contenteditable]` и с модификаторами (кроме ⌘K). Последовательности `g x` — окно 1 с. +- `j`/`k` на «Раннерах»: ссылки раннеров помечены `data-hotkey-item`; переход — по ссылке. +- `a`: поле с `data-hotkey-answer` получает фокус. +- Список сочетаний — один массив `SHORTCUTS` в `lib/shortcuts.ts`: его рисуют и окно `?`, и + страница `/help/shortcuts` — не разъедутся. diff --git a/openspec/changes/pep-52-command-palette/proposal.md b/openspec/changes/pep-52-command-palette/proposal.md new file mode 100644 index 00000000..3d4329ee --- /dev/null +++ b/openspec/changes/pep-52-command-palette/proposal.md @@ -0,0 +1,25 @@ +# PEP-52: Командная палитра ⌘K и горячие клавиши + +## Why +Чтобы перейти к стори, раннеру или ответить на вопрос, PM кликает через меню. Нужен быстрый +поиск-переход с клавиатуры и сочетания клавиш, как в привычных инструментах. + +## What Changes +- Палитра ⌘K / Ctrl+K (и кнопка «Поиск ⌘K» в сайдбаре): поиск по проектам, стори, раннерам, + открытым вопросам и разделам; действия — «Открыть», «В работу» для стори из бэклога, + «Ответить» (переход к вопросу). Стрелки, Enter, Esc. Данные — `GET /api/palette` + (только проекты пользователя, `userProjectIds`). +- Горячие клавиши (вне полей ввода): `/` — фокус в поиск списка на странице (поле с + `data-hotkey-search`), `g h` / `g p` / `g r` / `g s` — Главная / Проекты / Раннеры / + Настройки, `j`/`k` — следующий/предыдущий раннер на странице раннеров, `a` — фокус в поле + ответа на странице вопроса/стори, `?` — список сочетаний. +- Страница `/help/shortcuts` со списком сочетаний (и окно по `?`). +- Без новых зависимостей: палитра — свой компонент поверх ``. + +## Capabilities +### Modified Capabilities +- `web-workspace`: палитра команд и горячие клавиши. + +## Impact +- apps/web: `components/CommandPalette.tsx`, `components/Hotkeys.tsx`, `app/api/palette`, + `/help/shortcuts`, Sidebar; поле поиска с `data-hotkey-search` в списках. diff --git a/openspec/changes/pep-52-command-palette/specs/web-workspace/spec.md b/openspec/changes/pep-52-command-palette/specs/web-workspace/spec.md new file mode 100644 index 00000000..ce859237 --- /dev/null +++ b/openspec/changes/pep-52-command-palette/specs/web-workspace/spec.md @@ -0,0 +1,23 @@ +## ADDED Requirements + +### Requirement: Командная палитра +Веб SHALL открывать по ⌘K / Ctrl+K палитру поиска по проектам, стори, раннерам, открытым +вопросам и разделам пользователя с действиями «Открыть», «В работу» (стори из бэклога) и +«Ответить». Чужие проекты в палитру не попадают. + +#### Scenario: Перейти к стори +- **WHEN** PM нажимает ⌘K, печатает «PAY-3» и Enter +- **THEN** открывается страница стори PAY-3 + +#### Scenario: Чужой проект +- **GIVEN** пользователь не участник проекта OPS +- **THEN** `/api/palette` не возвращает ни проект OPS, ни его стори + +### Requirement: Горячие клавиши +Веб SHALL поддерживать сочетания: `/` — поиск в списке, `g h`/`g p`/`g r`/`g s` — разделы, +`j`/`k` — соседний раннер, `a` — поле ответа, `?` — список сочетаний; вне полей ввода. Список +сочетаний есть на странице `/help/shortcuts`. + +#### Scenario: Список сочетаний +- **WHEN** PM нажимает `?` вне поля ввода +- **THEN** открывается окно со списком сочетаний, тот же список — на `/help/shortcuts` diff --git a/openspec/changes/pep-52-command-palette/tasks.md b/openspec/changes/pep-52-command-palette/tasks.md new file mode 100644 index 00000000..b06033c0 --- /dev/null +++ b/openspec/changes/pep-52-command-palette/tasks.md @@ -0,0 +1,12 @@ +## 1. Палитра +- [ ] 1.1 `GET /api/palette` (доступ по проектам пользователя) +- [ ] 1.2 `CommandPalette`: поиск, стрелки, Enter, действия «Открыть», «В работу», «Ответить» +- [ ] 1.3 Кнопка в сайдбаре, подключение в раскладке + +## 2. Горячие клавиши +- [ ] 2.1 `lib/shortcuts.ts` + `Hotkeys` (/, g-последовательности, j/k, a, ?) +- [ ] 2.2 Метки `data-hotkey-*` в списках, раннерах, полях ответа +- [ ] 2.3 Страница `/help/shortcuts`, ссылка из `/help` + +## 3. Тесты +- [ ] 3.1 e2e: `/api/palette` отдаёт только свои проекты; ранжирование поиска (юнит) From f6e3725e5ff3f187a5356c9f169541cd3fdb0c75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 05:50:35 +0500 Subject: [PATCH 2/9] PEP-34/42: board order, archive, epic progress, story dependencies, epic planner (core, runner, MCP) Co-Authored-By: Claude Opus 5.5 --- .../changes/pep-34-board-order/proposal.md | 5 +- openspec/changes/pep-34-board-order/tasks.md | 2 +- packages/core/src/deps.ts | 126 + packages/core/src/index.ts | 1 + packages/core/src/tasks.ts | 106 +- .../db/migrations/0008_board_order_deps.sql | 13 + .../db/migrations/meta/0008_snapshot.json | 3087 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 17 +- packages/mcp/src/format.ts | 6 + packages/mcp/src/index.ts | 22 +- packages/mcp/src/manager.ts | 114 +- packages/runner/src/autonomy.ts | 23 +- packages/runner/src/flow.ts | 26 +- packages/runner/src/index.ts | 1 + packages/runner/src/planner.ts | 196 ++ packages/testkit/bin/mock-planner | 3 + packages/testkit/src/mock-planner.ts | 44 + packages/testkit/test/oauth.test.ts | 2 +- 19 files changed, 3771 insertions(+), 30 deletions(-) create mode 100644 packages/core/src/deps.ts create mode 100644 packages/db/migrations/0008_board_order_deps.sql create mode 100644 packages/db/migrations/meta/0008_snapshot.json create mode 100644 packages/runner/src/planner.ts create mode 100755 packages/testkit/bin/mock-planner create mode 100644 packages/testkit/src/mock-planner.ts diff --git a/openspec/changes/pep-34-board-order/proposal.md b/openspec/changes/pep-34-board-order/proposal.md index 82eca4e2..55258dc4 100644 --- a/openspec/changes/pep-34-board-order/proposal.md +++ b/openspec/changes/pep-34-board-order/proposal.md @@ -18,8 +18,9 @@ (события, вопросы, сессии) остаётся. - Колонка «Готово» сворачивается (запоминается в браузере); в свёрнутом виде видна только шапка со счётчиком. -- MCP (удалённый и агента): `reorder_task` (top/bottom/before/after), `archive_task` - (archive/restore); `/help` описывает их. +- MCP PM (удалённый): `reorder_task` (top/bottom/before/after), `archive_task` + (archive/restore); агентский MCP порядок не меняет (приоритеты — решение PM), но `list_tasks` + идёт в порядке доски; `/help` описывает их. ## Capabilities ### Modified Capabilities diff --git a/openspec/changes/pep-34-board-order/tasks.md b/openspec/changes/pep-34-board-order/tasks.md index ee5dc3b8..bf93ecd9 100644 --- a/openspec/changes/pep-34-board-order/tasks.md +++ b/openspec/changes/pep-34-board-order/tasks.md @@ -12,7 +12,7 @@ - [ ] 3.3 Архив/возврат на странице стори ## 4. MCP и справка -- [ ] 4.1 `reorder_task`, `archive_task` (удалённый и агента), прогресс в `list_epics` +- [ ] 4.1 `reorder_task`, `archive_task` (удалённый MCP), прогресс в `list_epics` - [ ] 4.2 `/help` ## 5. Тесты diff --git a/packages/core/src/deps.ts b/packages/core/src/deps.ts new file mode 100644 index 00000000..1f8f311f --- /dev/null +++ b/packages/core/src/deps.ts @@ -0,0 +1,126 @@ +// PEP-42: story dependencies. "PAY-3 waits for PAY-2": PAY-3 is blocked until every +// predecessor reaches review/done (an archived predecessor doesn't block). Same project only, +// no cycles. The backlog dispatcher (PEP-24) skips blocked stories. +import { events, projects, taskDeps, tasks, type Db } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { and, eq, inArray } from "drizzle-orm"; +import { PeppaError } from "./errors.ts"; +import { notify } from "./notify.ts"; +import { resolveTask, type Task, type TaskRef, type TaskStatus } from "./tasks.ts"; + +/** A predecessor in these statuses no longer blocks its successors. */ +export const UNBLOCKING: TaskStatus[] = ["review", "done"]; + +export interface Blocker { + id: number; + key: string; + title: string; + status: TaskStatus; + /** Still holds the story back (not in review/done, not archived). */ + open: boolean; +} + +const isOpen = (t: Pick) => !t.archivedAt && !UNBLOCKING.includes(t.status); + +/** Predecessors of each of the given stories (all of a project when `projectId` is given). */ +export async function blockersMap(db: Db, projectId: number): Promise> { + const projectTasks = await db.select({ id: tasks.id, number: tasks.number, title: tasks.title, status: tasks.status, archivedAt: tasks.archivedAt, projectId: tasks.projectId }).from(tasks).where(eq(tasks.projectId, projectId)); + const byId = new Map(projectTasks.map((t) => [t.id, t])); + if (!projectTasks.length) return new Map(); + const deps = await db.select().from(taskDeps).where(inArray(taskDeps.taskId, projectTasks.map((t) => t.id))); + const [project] = await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId)); + if (!project) return new Map(); + const out = new Map(); + for (const d of deps) { + const b = byId.get(d.blockedById); + if (!b) continue; + const list = out.get(d.taskId) ?? []; + list.push({ id: b.id, key: formatTaskKey(project.key, b.number), title: b.title, status: b.status, open: isOpen(b) }); + out.set(d.taskId, list); + } + for (const list of out.values()) list.sort((a, b) => a.id - b.id); + return out; +} + +export async function blockersOf(db: Db, ref: TaskRef): Promise { + return (await blockersMap(db, ref.project.id)).get(ref.task.id) ?? []; +} + +/** Stories that wait for this one. */ +export async function dependentsOf(db: Db, ref: TaskRef): Promise> { + const rows = await db + .select({ id: tasks.id, number: tasks.number, title: tasks.title, status: tasks.status }) + .from(taskDeps) + .innerJoin(tasks, eq(taskDeps.taskId, tasks.id)) + .where(eq(taskDeps.blockedById, ref.task.id)); + return rows.map((r) => ({ id: r.id, key: formatTaskKey(ref.project.key, r.number), title: r.title, status: r.status })); +} + +/** Ids of the project's stories that are blocked right now. */ +export async function blockedTaskIds(db: Db, projectId: number): Promise> { + const out = new Set(); + for (const [id, list] of await blockersMap(db, projectId)) if (list.some((b) => b.open)) out.add(id); + return out; +} + +/** True when `from` can reach `to` following "waits for" edges. */ +async function reaches(db: Db, from: number, to: number): Promise { + const seen = new Set(); + let frontier = [from]; + while (frontier.length) { + if (frontier.includes(to)) return true; + frontier.forEach((x) => seen.add(x)); + const rows = await db.select({ next: taskDeps.blockedById }).from(taskDeps).where(inArray(taskDeps.taskId, frontier)); + frontier = [...new Set(rows.map((r) => r.next))].filter((x) => !seen.has(x)); + } + return false; +} + +/** Makes `ref` wait for `blocker`. Idempotent; rejects other projects, itself and cycles. */ +export async function addDependency(db: Db, ref: TaskRef, blocker: TaskRef): Promise { + if (blocker.project.id !== ref.project.id) throw new PeppaError(`${blocker.key} из другого проекта — зависимости только внутри проекта`); + if (blocker.task.id === ref.task.id) throw new PeppaError(`${ref.key} не может зависеть от самой себя`); + if (await reaches(db, blocker.task.id, ref.task.id)) throw new PeppaError(`Цикл зависимостей: ${blocker.key} уже ждёт ${ref.key}`); + const r = await db.insert(taskDeps).values({ taskId: ref.task.id, blockedById: blocker.task.id }).onConflictDoNothing().returning(); + if (r.length) await logDeps(db, ref, { added: blocker.key }); +} + +export async function removeDependency(db: Db, ref: TaskRef, blocker: TaskRef): Promise { + const r = await db.delete(taskDeps).where(and(eq(taskDeps.taskId, ref.task.id), eq(taskDeps.blockedById, blocker.task.id))).returning(); + if (r.length) await logDeps(db, ref, { removed: blocker.key }); +} + +/** Replaces the whole list of predecessors ("PAY-2", "2"). Validates everything before changing anything. */ +export async function setDependencies(db: Db, ref: TaskRef, keys: string[]): Promise { + const wanted: TaskRef[] = []; + for (const k of [...new Set(keys.map((x) => x.trim()).filter(Boolean))]) wanted.push(await resolveTask(db, k, ref.project.key)); + const current = await blockersOf(db, ref); + const keep = new Set(wanted.map((w) => w.task.id)); + for (const c of current) if (!keep.has(c.id)) await db.delete(taskDeps).where(and(eq(taskDeps.taskId, ref.task.id), eq(taskDeps.blockedById, c.id))); + const have = new Set(current.map((c) => c.id)); + const added: string[] = []; + try { + for (const w of wanted) { + if (have.has(w.task.id)) continue; + await addDependency(db, ref, w); + added.push(w.key); + } + } catch (e) { + // Roll back to the previous list: either all of it applies or none. + await db.delete(taskDeps).where(eq(taskDeps.taskId, ref.task.id)); + if (current.length) await db.insert(taskDeps).values(current.map((c) => ({ taskId: ref.task.id, blockedById: c.id }))); + throw e; + } + return blockersOf(db, ref); +} + +async function logDeps(db: Db, ref: TaskRef, payload: Record) { + await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: "task_deps", payload }); + await notify(db, { type: "task_updated", taskId: ref.task.id }); +} + +/** "ждёт PAY-2, PAY-5" for the open blockers, or null. */ +export function blockedLabel(list: Blocker[] | undefined): string | null { + const open = (list ?? []).filter((b) => b.open); + return open.length ? `ждёт ${open.map((b) => b.key).join(", ")}` : null; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4f411fd0..12e8c9d7 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -29,3 +29,4 @@ export * from "./autonomy.ts"; export * from "./openspec.ts"; export * from "./steps.ts"; export * from "./preview.ts"; +export * from "./deps.ts"; diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index 745d158b..b3fa2f28 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -9,6 +9,7 @@ import { taskCiSummary, type CiSummary } from "./ci.ts"; import { latestReview, type CodeReview } from "./reviews.ts"; import { getAutonomy, type AutonomySettings } from "./autonomy.ts"; import { reviewPreview, type ReviewPreview } from "./preview.ts"; +import { blockersOf, dependentsOf, type Blocker } from "./deps.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -61,9 +62,15 @@ export async function createTask(db: Db, t: NewTask): Promise { .returning() .all(); if (!project) throw new PeppaError(`Project #${t.projectId} not found`); + // PEP-34: a new story goes to the end of the board order. + const last = tx + .select({ max: sql`max(${tasks.position})` }) + .from(tasks) + .where(eq(tasks.projectId, t.projectId)) + .get(); const task = tx .insert(tasks) - .values({ ...t, number: project.nextTaskNumber - 1 }) + .values({ ...t, number: project.nextTaskNumber - 1, position: Math.floor(last?.max ?? 0) + 1 }) .returning() .get(); return { project, task, key: formatTaskKey(project.key, task.number) }; @@ -76,6 +83,8 @@ export interface TaskFilter { projectId?: number; goalId?: number; statuses?: TaskStatus[]; + /** PEP-34: archived stories are left out unless asked for. */ + includeArchived?: boolean; } export async function listTasks(db: Db, f: TaskFilter = {}): Promise> { @@ -83,15 +92,103 @@ export async function listTasks(db: Db, f: TaskFilter = {}): Promise ({ ...r.task, key: formatTaskKey(r.projectKey, r.task.number) })); } +// ── PEP-34: board order (= priority), archive, epic progress ─────────────────── + +export type ReorderTo = { to: "top" | "bottom" } | { to: "before" | "after"; other: TaskRef }; + +/** + * Moves a story in the project's board order. The order is shared by the whole project + * (a card that went to work and came back keeps its place); "top"/"bottom" are relative to the + * story's own column. Positions are reals: the new one is the midpoint between neighbours, + * the project is renumbered when the gap gets too small. + */ +export async function reorderTask(db: Db, ref: TaskRef, r: ReorderTo, columnOf: (s: TaskStatus) => string = (s) => s): Promise { + if ("other" in r && r.other.project.id !== ref.project.id) throw new PeppaError("Стори из разных проектов"); + if ("other" in r && r.other.task.id === ref.task.id) return ref.task; + const all = (await listTasks(db, { projectId: ref.project.id })).filter((t) => t.id !== ref.task.id); + const col = all.filter((t) => columnOf(t.status) === columnOf(ref.task.status)); + let prev: Task | undefined; + let next: Task | undefined; + if (r.to === "top") next = col[0]; + else if (r.to === "bottom") prev = col.at(-1); + else if ("other" in r) { + const i = all.findIndex((t) => t.id === r.other.task.id); + if (i < 0) throw new PeppaError(`${r.other.key} в архиве или не найдена`); + if (r.to === "before") [prev, next] = [all[i - 1], all[i]]; + else [prev, next] = [all[i], all[i + 1]]; + } + let position: number; + if (prev && next) position = (prev.position + next.position) / 2; + else if (next) position = next.position - 1; + else if (prev) position = prev.position + 1; + else position = ref.task.position; + if (prev && next && next.position - prev.position < 1e-6) { + // Renumber the project 1, 2, 3 … with the story in its new place. + const order = [...all]; + const at = next ? order.findIndex((t) => t.id === next!.id) : order.length; + order.splice(at, 0, ref.task as Task & { key: string }); + db.transaction((tx) => { + order.forEach((t, i) => tx.update(tasks).set({ position: i + 1 }).where(eq(tasks.id, t.id)).run()); + }, { behavior: "immediate" }); + position = at + 1; + } + const [task] = await db.update(tasks).set({ position }).where(eq(tasks.id, ref.task.id)).returning(); + await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: "task_reordered", payload: { to: r.to, other: "other" in r ? r.other.key : null } }); + await notify(db, { type: "task_updated", taskId: ref.task.id }); + return task!; +} + +/** PEP-34: archive (hide everywhere work is picked) or restore a story. History stays. */ +export async function setTaskArchived(db: Db, ref: TaskRef, archived: boolean): Promise { + const [task] = await db + .update(tasks) + .set({ archivedAt: archived ? new Date() : null, ...(archived ? {} : { position: await nextPosition(db, ref.project.id) }) }) + .where(eq(tasks.id, ref.task.id)) + .returning(); + await db.insert(events).values({ projectId: ref.project.id, taskId: ref.task.id, type: archived ? "task_archived" : "task_restored", payload: {} }); + await notify(db, { type: "task_updated", taskId: ref.task.id }); + return task!; +} + +async function nextPosition(db: Db, projectId: number): Promise { + const [r] = await db.select({ max: sql`max(${tasks.position})` }).from(tasks).where(eq(tasks.projectId, projectId)); + return Math.floor(r?.max ?? 0) + 1; +} + +export interface EpicProgress { + done: number; + total: number; +} + +/** PEP-34: done/total of each epic over its non-archived stories. */ +export async function epicProgress(db: Db, projectId: number): Promise> { + const rows = await db + .select({ goalId: tasks.goalId, status: tasks.status }) + .from(tasks) + .where(and(eq(tasks.projectId, projectId), isNull(tasks.archivedAt))); + const out = new Map(); + for (const r of rows) { + if (r.goalId == null) continue; + const p = out.get(r.goalId) ?? { done: 0, total: 0 }; + p.total++; + if (r.status === "done") p.done++; + out.set(r.goalId, p); + } + return out; +} + +export const progressLabel = (p: EpicProgress | undefined) => (p ? `${p.done}/${p.total}` : "0/0"); + export interface TaskPatch { status?: TaskStatus; title?: string; @@ -140,6 +237,9 @@ export interface TaskDetails { comments: StoryComment[]; /** Preview stand, diff, checks, screenshots, Gitea issue (PEP-44/46). */ preview: ReviewPreview; + /** PEP-42: stories this one waits for, and stories that wait for it. */ + blockers: Blocker[]; + dependents: Array<{ id: number; key: string; title: string; status: TaskStatus }>; } export const COMMENT_EVENT = "pm_comment"; @@ -181,7 +281,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise .orderBy(desc(events.id)) .limit(20); const incident = await incidentForTask(db, ref.task.id); - return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id), preview: await reviewPreview(db, ref) }; + return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref), review: await latestReview(db, ref.task.id), autonomy: await getAutonomy(db, ref.project.id), comments: await storyComments(db, ref.task.id), preview: await reviewPreview(db, ref), blockers: await blockersOf(db, ref), dependents: await dependentsOf(db, ref) }; } export interface NewQuestion { diff --git a/packages/db/migrations/0008_board_order_deps.sql b/packages/db/migrations/0008_board_order_deps.sql new file mode 100644 index 00000000..f6430608 --- /dev/null +++ b/packages/db/migrations/0008_board_order_deps.sql @@ -0,0 +1,13 @@ +CREATE TABLE `task_deps` ( + `task_id` integer NOT NULL, + `blocked_by_id` integer NOT NULL, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + PRIMARY KEY(`task_id`, `blocked_by_id`), + FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`blocked_by_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE INDEX `task_deps_blocked_by` ON `task_deps` (`blocked_by_id`);--> statement-breakpoint +ALTER TABLE `tasks` ADD `position` real DEFAULT 0 NOT NULL;--> statement-breakpoint +ALTER TABLE `tasks` ADD `archived_at` integer;--> statement-breakpoint +UPDATE `tasks` SET `position` = `number`; \ No newline at end of file diff --git a/packages/db/migrations/meta/0008_snapshot.json b/packages/db/migrations/meta/0008_snapshot.json new file mode 100644 index 00000000..b02c6fbe --- /dev/null +++ b/packages/db/migrations/meta/0008_snapshot.json @@ -0,0 +1,3087 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "355ff9b4-7edf-4d71-9556-9681cf85209a", + "prevId": "d8e80765-8ce2-47d6-b112-53bf26c85f84", + "tables": { + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "code_reviews": { + "name": "code_reviews", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "verdict": { + "name": "verdict", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "findings": { + "name": "findings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "code_reviews_project_id_projects_id_fk": { + "name": "code_reviews_project_id_projects_id_fk", + "tableFrom": "code_reviews", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "code_reviews_task_id_tasks_id_fk": { + "name": "code_reviews_task_id_tasks_id_fk", + "tableFrom": "code_reviews", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_outbox": { + "name": "push_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "urgency": { + "name": "urgency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_outbox_dedupe_key_unique": { + "name": "push_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_outbox_subscription_id_push_subscriptions_id_fk": { + "name": "push_outbox_subscription_id_push_subscriptions_id_fk", + "tableFrom": "push_outbox", + "tableTo": "push_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_ok_at": { + "name": "last_ok_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "review_settings": { + "name": "review_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "max_iterations": { + "name": "max_iterations", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "rules": { + "name": "rules", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "review_settings_project_id_projects_id_fk": { + "name": "review_settings_project_id_projects_id_fk", + "tableFrom": "review_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rotate_reason": { + "name": "rotate_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "task_deps": { + "name": "task_deps", + "columns": { + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blocked_by_id": { + "name": "blocked_by_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "task_deps_blocked_by": { + "name": "task_deps_blocked_by", + "columns": [ + "blocked_by_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "task_deps_task_id_tasks_id_fk": { + "name": "task_deps_task_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_deps_blocked_by_id_tasks_id_fk": { + "name": "task_deps_blocked_by_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "blocked_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_deps_task_id_blocked_by_id_pk": { + "columns": [ + "task_id", + "blocked_by_id" + ], + "name": "task_deps_task_id_blocked_by_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_issue": { + "name": "gitea_issue", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "archived_at": { + "name": "archived_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + }, + "tasks_project_issue": { + "name": "tasks_project_issue", + "columns": [ + "project_id", + "gitea_issue" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_iin": { + "name": "egov_iin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_linked_at": { + "name": "egov_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_set_at": { + "name": "password_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_login_at": { + "name": "last_login_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "columns": [ + "gitea_id" + ], + "isUnique": true + }, + "users_login_unique": { + "name": "users_login_unique", + "columns": [ + "login" + ], + "isUnique": true + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "columns": [ + "telegram_chat_id" + ], + "isUnique": true + }, + "users_egov_iin_unique": { + "name": "users_egov_iin_unique", + "columns": [ + "egov_iin" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 900dcfed..4827b6d2 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -57,6 +57,13 @@ "when": 1794617253656, "tag": "0007_calm_anthem", "breakpoints": true + }, + { + "idx": 8, + "version": "6", + "when": 1794619727659, + "tag": "0008_board_order_deps", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 84b5c49c..12e8cc9f 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -1,6 +1,6 @@ import { relations } from "drizzle-orm"; import { sql } from "drizzle-orm"; -import { integer, primaryKey, sqliteTable, text, uniqueIndex, type AnySQLiteColumn } from "drizzle-orm/sqlite-core"; +import { index, integer, primaryKey, real, sqliteTable, text, uniqueIndex, type AnySQLiteColumn } from "drizzle-orm/sqlite-core"; // SQLite (PEP-36): timestamps are epoch milliseconds (drizzle maps them to Date), JSON is // text (mapped to objects), booleans are 0/1, enums are checked by TypeScript only. @@ -129,12 +129,27 @@ export const tasks = sqliteTable( ciFailedSha: text("ci_failed_sha"), // PEP-46: the Gitea issue of the project's repo this story came from (or is linked to). giteaIssue: integer("gitea_issue"), + // PEP-34: order on the board = priority for the dispatcher (lower first; shared by the project). + position: real("position").notNull().default(0), + // PEP-34: archived stories are hidden from the board, the dispatcher and epic progress. + archivedAt: integer("archived_at", { mode: "timestamp_ms" }), createdAt: createdAt(), updatedAt: updatedAt(), }, (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number), uniqueIndex("tasks_project_issue").on(t.projectId, t.giteaIssue)], ); +/** PEP-42: "task waits for blocked_by" — a story is blocked until its predecessors reach review/done. */ +export const taskDeps = sqliteTable( + "task_deps", + { + taskId: integer("task_id").notNull().references(() => tasks.id, { onDelete: "cascade" }), + blockedById: integer("blocked_by_id").notNull().references(() => tasks.id, { onDelete: "cascade" }), + createdAt: createdAt(), + }, + (t) => [primaryKey({ columns: [t.taskId, t.blockedById] }), index("task_deps_blocked_by").on(t.blockedById)], +); + /** PEP-57: one deployment of a project to an environment (and its outcome). */ export const releases = sqliteTable("releases", { id: integer("id").primaryKey({ autoIncrement: true }), diff --git a/packages/mcp/src/format.ts b/packages/mcp/src/format.ts index 93244ddd..9cc4ca1b 100644 --- a/packages/mcp/src/format.ts +++ b/packages/mcp/src/format.ts @@ -23,6 +23,12 @@ export function formatTask(d: TaskDetails): string { if (task.prUrl) lines.push(`- PR: ${task.prUrl}`); if (d.preview?.issueUrl) lines.push(`- Issue Gitea: ${d.preview.issueUrl}`); if (d.preview?.previewUrl) lines.push(`- Превью: ${d.preview.previewUrl}${d.preview.screenshots.length ? ` (скриншотов: ${d.preview.screenshots.length})` : ""}`); + if (task.archivedAt) lines.push(`- В архиве с ${task.archivedAt.toISOString().slice(0, 10)} (не видна на доске, диспетчер её не берёт)`); + if (d.blockers?.length) { + const open = d.blockers.filter((b) => b.open); + lines.push(`- Ждёт: ${d.blockers.map((b) => `${b.key} [${b.status}]${b.open ? "" : " ✓"}`).join(", ")}${open.length ? " — заблокирована, пока они не в review/done" : " — разблокирована"}`); + } + if (d.dependents?.length) lines.push(`- Её ждут: ${d.dependents.map((t) => `${t.key} [${t.status}]`).join(", ")}`); lines.push(`- ${d.ci.label.charAt(0).toUpperCase()}${d.ci.label.slice(1)}${d.ci.sha ? ` (коммит ${d.ci.sha.slice(0, 7)})` : ""}${d.ci.runUrl ? ` · ${d.ci.runUrl}` : ""}`); for (const f of d.ci.failed) lines.push(` - ❌ ${f.check}${f.runUrl ? ` · ${f.runUrl}` : ""}`); if (d.review) { diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index c20943e4..05978725 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -14,6 +14,11 @@ import { listIncidents, listEpics, listTasks, + blockedLabel, + blockersMap, + epicProgress, + progressLabel, + setDependencies, loadSharedRules, PeppaError, reportProgress, @@ -79,13 +84,17 @@ tool("get_task", "Get a Peppa story (one business story = one OpenSpec change): tool( "list_tasks", - "List stories in a project, optionally filtered by status or epic.", + "List stories in a project in board order (top = highest priority), optionally filtered by status or epic; \"waits for\" marks stories blocked by unfinished predecessors.", { project: projectArg, status: z.enum(TASK_STATUSES).optional(), epic_id: z.number().int().optional(), goal_id: z.number().int().optional().describe("Alias of epic_id") }, async ({ project, status, epic_id, goal_id }) => { const p = await projectOrDefault(project); const rows = await listTasks(db, { projectId: p.id, goalId: epic_id ?? goal_id, statuses: status ? [status] : undefined }); if (!rows.length) return "No stories."; - return rows.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}`).join("\n"); + const deps = await blockersMap(db, p.id); + return rows.map((t) => { + const b = blockedLabel(deps.get(t.id))?.replace("ждёт", "waits for"); + return `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}${b ? ` — ${b}` : ""}`; + }).join("\n"); }, ); @@ -93,7 +102,8 @@ const listEpicsText = async ({ project }: { project?: string }) => { const p = await projectOrDefault(project); const rows = await listEpics(db, p.id); if (!rows.length) return "No open epics."; - return rows.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n"); + const progress = await epicProgress(db, p.id); + return rows.map((g) => `- #${g.id} ${g.title} (done ${progressLabel(progress.get(g.id))})${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n"); }; tool("list_epics", "List the open epics of a project (labels that group stories).", { project: projectArg }, listEpicsText); tool("list_goals", "Alias of list_epics (goals were renamed to epics).", { project: projectArg }, listEpicsText); @@ -106,12 +116,14 @@ tool( description: z.string().optional(), epic_id: z.number().int().optional(), goal_id: z.number().int().optional().describe("Alias of epic_id"), + blocked_by: z.array(z.string()).optional().describe("Stories this one waits for (keys); it won't be started automatically until they are in review/done"), project: projectArg, }, - async ({ title, description, epic_id, goal_id, project }) => { + async ({ title, description, epic_id, goal_id, blocked_by, project }) => { const p = await projectOrDefault(project); const ref = await createTask(db, { projectId: p.id, goalId: epic_id ?? goal_id, title, description }); - return `Created ${ref.key}: ${title}`; + const deps = blocked_by?.length ? await setDependencies(db, ref, blocked_by).catch((e: Error) => { throw new PeppaError(`Created ${ref.key}, but dependencies were not set: ${e.message}`); }) : []; + return `Created ${ref.key}: ${title}${deps.length ? ` (waits for ${deps.map((d) => d.key).join(", ")})` : ""}`; }, ); diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index 89a9d150..bccb9ce9 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -30,11 +30,16 @@ import { listIncidents, POLICY_RU, updateIncidentSettings, + blockedLabel, + blockersMap, + epicProgress, + progressLabel, + setDependencies, type User, } from "@peppa/core"; import { questions, projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey, loadEnv } from "@peppa/shared"; -import { currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner"; +import { applyPlan, archiveTask, planEpic, reorderBoardTask, type PlannedStory, currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner"; import { and, asc, eq, inArray, isNull } from "drizzle-orm"; import { z } from "zod"; import { formatIncident, formatTask } from "./format.ts"; @@ -54,6 +59,9 @@ Good habits: - Before creating, look: list_projects, list_epics, list_tasks. Don't duplicate — fix with update_task / update_epic. - Label stories with an epic (epic_id) when one fits. Write story descriptions with context and a "Definition of done" list; the agent works from them. - Only move a story to in_progress when the user asks to start the work. +- Board order = priority: list_tasks shows each column top-down; reorder_task moves a story (the backlog dispatcher takes from the top). archive_task hides a story without deleting it. +- Dependencies: a story can wait for others (blocked_by in create_task/update_task, set_dependencies); blocked stories are not started by the dispatcher until predecessors are in review/done. +- Planning: plan_epic breaks an epic into stories with dependencies and returns a draft; after the user agrees (edit freely), apply_plan creates them. - Statuses: get_task for details, list_tasks for the board, list_inbox for what needs the user. - Projects can be shared: add_member / remove_member (owner only); members can do everything else. Repos are public by default; set_project_visibility (owner only) makes one private or public again. - CI/CD: every PR is checked (get_task shows the checks; red ones go back to the agent; "accept" merges the PR only when they are green). A merge deploys to staging; list_releases shows what runs where; deploy puts the healthy staging release into prod — only when the user asks. @@ -132,7 +140,8 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ const listEpicsText = async ({ project }: { project: string }) => { const p = await ownedProject(project); const gs = await listEpics(db, p.id); - return gs.length ? gs.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open epics."; + const progress = await epicProgress(db, p.id); + return gs.length ? gs.map((g) => `- #${g.id} ${g.title} (done ${progressLabel(progress.get(g.id))})${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open epics."; }; const createEpicShape = { project: projectArg, title: z.string().trim().min(3), description: z.string().optional().describe("What the epic is about; agents get it with every story of the epic") }; const createEpicText = async ({ project, title, description }: { project: string; title: string; description?: string }) => { @@ -238,16 +247,23 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ tool( "list_tasks", - "List stories of a project as a board (Backlog / In progress / Review / Done), optionally one column.", + "List stories of a project as a board (Backlog / In progress / Review / Done), optionally one column. Each column is in board order (top = highest priority; the backlog dispatcher takes from the top); \"waits for\" marks stories blocked by unfinished predecessors.", { project: projectArg, column: z.enum(COLUMNS).optional() }, true, async ({ project, column }) => { const p = await ownedProject(project); const ts = await listTasks(db, { projectId: p.id }); + const deps = await blockersMap(db, p.id); const out: string[] = []; for (const c of column ? [column] : COLUMNS) { const inCol = ts.filter((t) => columnOf(t.status) === c); - out.push(`## ${COLUMN_NAME[c]} (${inCol.length})`, ...inCol.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}`)); + out.push( + `## ${COLUMN_NAME[c]} (${inCol.length})`, + ...inCol.map((t) => { + const b = blockedLabel(deps.get(t.id))?.replace("ждёт", "waits for"); + return `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}${b ? ` — ${b}` : ""}`; + }), + ); } return out.join("\n"); }, @@ -267,31 +283,35 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ description: z.string().optional(), epic_id: z.number().int().optional().describe("Epic of the same project (list_epics)"), goal_id: z.number().int().optional().describe("Alias of epic_id"), + blocked_by: z.array(z.string()).optional().describe("Stories of the same project this one waits for (keys like PEP-3); the dispatcher won't start it until they are in review/done"), }, false, - async ({ project, title, description, epic_id, goal_id }) => { + async ({ project, title, description, epic_id, goal_id, blocked_by }) => { const p = await ownedProject(project); const ref = await createTask(db, { projectId: p.id, title, description, goalId: epic_id ?? goal_id }); - return `Created ${ref.key}: ${title} (Backlog). ${webUrl}/t/${ref.key}`; + const deps = blocked_by?.length ? await setDependencies(db, ref, blocked_by).catch((e: Error) => { throw new PeppaError(`Created ${ref.key}, but dependencies were not set: ${e.message}`); }) : []; + return `Created ${ref.key}: ${title} (Backlog, bottom of the board)${deps.length ? ` · waits for ${deps.map((d) => d.key).join(", ")}` : ""}. ${webUrl}/t/${ref.key}`; }, ); tool( "update_task", - "Edit a story: title, description and/or epic (each optional, at least one). Status and everything else stay as they are; no agent is started or stopped. Returns the updated card.", + "Edit a story: title, description, epic and/or dependencies (each optional, at least one). Status and everything else stay as they are; no agent is started or stopped. Returns the updated card.", { task: taskArg, title: z.string().trim().min(3).optional().describe("New title"), description: z.string().optional().describe("New description (replaces the old one; Markdown is fine)"), epic_id: z.number().int().nullable().optional().describe("Label with this epic of the same project; null removes the epic"), goal_id: z.number().int().nullable().optional().describe("Alias of epic_id"), + blocked_by: z.array(z.string()).optional().describe("Replaces the stories this one waits for (keys like PEP-3); [] removes all dependencies"), }, false, - async ({ task, title, description, epic_id, goal_id }) => { + async ({ task, title, description, epic_id, goal_id, blocked_by }) => { const epic = epic_id !== undefined ? epic_id : goal_id; - if (title === undefined && description === undefined && epic === undefined) throw new PeppaError("Nothing to update: pass title, description and/or epic_id"); + if (title === undefined && description === undefined && epic === undefined && blocked_by === undefined) throw new PeppaError("Nothing to update: pass title, description, epic_id and/or blocked_by"); const ref = await ownedTask(task); - await updateTask(db, ref, { title, description, goalId: epic }); + if (blocked_by !== undefined) await setDependencies(db, ref, blocked_by); + if (title !== undefined || description !== undefined || epic !== undefined) await updateTask(db, ref, { title, description, goalId: epic }); const updated = await resolveTask(db, ref.key); return `${formatTask(await getTaskDetails(db, updated))}\n\nWeb: ${webUrl}/t/${ref.key}`; }, @@ -309,6 +329,80 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ }, ); + tool( + "reorder_task", + "Change a story's place on the board (= priority: the backlog dispatcher and idle pushes take from the top). top/bottom are within the story's column; before/after put it next to another story of the same project.", + { task: taskArg, position: z.enum(["top", "bottom", "before", "after"]), other: z.string().optional().describe("For before/after: the story key to put it next to") }, + false, + async ({ task, position, other }) => { + const ref = await ownedTask(task); + if ((position === "before" || position === "after") && !other) throw new PeppaError("Pass `other` for before/after"); + const r = position === "top" || position === "bottom" ? { to: position } : { to: position, other: await ownedTask(other!) }; + await reorderBoardTask(db, ref, r as never); + const col = columnOf(ref.task.status); + const inCol = (await listTasks(db, { projectId: ref.project.id })).filter((t) => columnOf(t.status) === col); + return `${COLUMN_NAME[col]}: ${inCol.map((t) => t.key).join(", ")}`; + }, + ); + + tool( + "archive_task", + "Archive a story (hide it from the board, the dispatcher and epic progress; its agent stops; history stays) or restore it to the bottom of the board. There is no hard delete.", + { task: taskArg, archived: z.boolean().default(true).describe("false restores the story") }, + false, + async ({ task, archived }) => { + const ref = await ownedTask(task); + const r = await archiveTask(db, ref, archived); + return archived ? `${ref.key} archived${r.stopped ? ` · ${r.stopped} session(s) stopped` : ""}` : `${ref.key} restored to the board`; + }, + ); + + tool( + "set_dependencies", + "Set the stories a story waits for (replaces the list; [] clears it). A story is blocked until every predecessor is in review/done; the dispatcher skips blocked stories. Same project only, no cycles.", + { task: taskArg, blocked_by: z.array(z.string()).describe("Story keys like PEP-3") }, + false, + async ({ task, blocked_by }) => { + const ref = await ownedTask(task); + const list = await setDependencies(db, ref, blocked_by); + return list.length ? `${ref.key} waits for ${list.map((b) => `${b.key} [${b.status}]`).join(", ")}` : `${ref.key} has no dependencies`; + }, + ); + + const planStory = z.object({ + title: z.string().trim().min(3), + description: z.string().default(""), + depends_on: z.array(z.union([z.number().int().positive(), z.string()])).default([]).describe("1-based numbers of other stories in this plan, or keys of existing stories"), + }); + const planText = (stories: PlannedStory[]) => + stories.map((s, i) => `${i + 1}. ${s.title}${s.dependsOn.length ? ` (after ${s.dependsOn.join(", ")})` : ""}\n${s.description.replace(/^/gm, " ")}`).join("\n\n"); + + tool( + "plan_epic", + "Ask Peppa's planner (a short Claude run on the project's subscription, up to ~3 min) to break an epic into stories with acceptance criteria and dependencies. Returns a DRAFT — nothing is created. Show it to the user, edit as they wish, then apply_plan.", + { project: projectArg, epic_id: z.number().int(), wishes: z.string().optional().describe("Extra guidance for the planner from the user") }, + false, + async ({ project, epic_id, wishes }) => { + const p = await ownedProject(project); + const r = await planEpic(db, p, epic_id, { wishes, by: user.login }); + if (!r.ok) throw new PeppaError(`Planner failed: ${r.error}`); + const json = JSON.stringify(r.draft.stories.map((s) => ({ title: s.title, description: s.description, depends_on: s.dependsOn }))); + return `Draft plan for epic #${epic_id} (${r.draft.stories.length} stories; also editable at ${webUrl}/p/${p.key}/plan/${epic_id}):\n\n${planText(r.draft.stories)}\n\nTo create: apply_plan with these stories (edited if needed):\n${json}`; + }, + ); + + tool( + "apply_plan", + "Create stories from an approved plan: in the backlog under the epic, in plan order (bottom of the board), with dependencies (depends_on: plan numbers from 1 or existing story keys).", + { project: projectArg, epic_id: z.number().int(), stories: z.array(planStory).min(1).max(15) }, + false, + async ({ project, epic_id, stories }) => { + const p = await ownedProject(project); + const created = await applyPlan(db, p, epic_id, stories.map((s) => ({ title: s.title, description: s.description, dependsOn: s.depends_on.map((d) => (typeof d === "string" ? d.toUpperCase() : d)) }))); + return `Created ${created.length} stories: ${created.map((r) => r.key).join(", ")}. ${webUrl}/p/${p.key}?epic=${epic_id}`; + }, + ); + tool("list_releases", "Deployments of a project: what runs on staging and prod, and the latest releases (env, commit, status, stories, who deployed).", { project: projectArg }, true, async ({ project }) => { const p = await ownedProject(project); const [cur, rows] = await Promise.all([currentReleases(db, p.id), listReleases(db, p.id, 15)]); diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index af6f7ed8..d18d8d91 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -7,6 +7,7 @@ import { answerQuestion, askPm, askPmProject, + blockedTaskIds, enqueueTelegram, getAutonomy, getSetting, @@ -223,6 +224,8 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date const sessions = (await listSessions(db, { active: true })).filter((s) => s.projectId === project.id); const working = await workingSessions(db, sessions); const backlog = await listTasks(db, { projectId: project.id, statuses: ["backlog"] }); + // PEP-42: only stories whose predecessors are in review/done; PEP-34: in board order. + const ready = await readyBacklog(db, project.id, backlog); const state = await getIdle(db, project.id); // Someone works or nothing is left: an open "agents are idle" question is moot. @@ -241,7 +244,7 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date if (a.pick === "auto") { if (limited || (state.failUntil ?? 0) > now.getTime()) return; let slots = a.wipLimit - working.length; - for (const task of backlog) { + for (const task of ready) { if (slots <= 0) break; const ref = refOf(project, task); try { @@ -268,12 +271,19 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date return; } - if (!a.idlePush || working.length > 0 || !backlog.length || limited || state.questionId) return; + if (!a.idlePush || working.length > 0 || !ready.length || limited || state.questionId) return; if (inAutonomyQuietHours(a, now)) return; if ((state.snoozeUntil ?? 0) > now.getTime()) return; if (state.at && now.getTime() - state.at < a.idlePushHours * 3_600_000) return; - await offerStory(db, project, backlog[0]!, now); - log(`${project.key}: idle push (${formatTaskKey(project.key, backlog[0]!.number)})`); + await offerStory(db, project, ready[0]!, now); + log(`${project.key}: idle push (${formatTaskKey(project.key, ready[0]!.number)})`); +} + +/** Backlog stories that can start now: not blocked by a predecessor (PEP-42), in board order (PEP-34). */ +export async function readyBacklog(db: Db, projectId: number, backlog?: T[]): Promise { + const list = backlog ?? ((await listTasks(db, { projectId, statuses: ["backlog"] })) as unknown as T[]); + const blocked = await blockedTaskIds(db, projectId); + return list.filter((t) => !blocked.has(t.id)); } /** Sessions that hold a WIP slot: their story is being worked on (not in review). */ @@ -309,8 +319,9 @@ export async function onIdleAnswer(db: Db, q: Question, answer: string): Promise const now = Date.now(); const text = answer.trim(); if (text.startsWith(IDLE_NEXT)) { - const backlog = await listTasks(db, { projectId: q.projectId, statuses: ["backlog"] }); - const next = backlog.find((t) => t.number > ref.task.number) ?? backlog[0]; + const backlog = await readyBacklog(db, q.projectId); + const at = backlog.findIndex((t) => t.id === ref.task.id); + const next = (at >= 0 ? backlog[at + 1] : backlog.find((t) => t.position > ref.task.position)) ?? backlog.find((t) => t.id !== ref.task.id); await setIdle(db, q.projectId, { ...state, questionId: null }); if (next) await offerStory(db, ref.project, next, new Date(now)); return true; diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts index 932910ad..38751cbf 100644 --- a/packages/runner/src/flow.ts +++ b/packages/runner/src/flow.ts @@ -1,5 +1,5 @@ // PM-side moves on the task board and review acceptance (web and Telegram use these). -import { answerQuestion, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, resolveTask, updateTask, type Question, type TaskRef } from "@peppa/core"; +import { answerQuestion, getQuestion, listSessions, PeppaError, pendingQuestions, prGate, reorderTask, resolveTask, setTaskArchived, updateTask, type Question, type ReorderTo, type TaskRef } from "@peppa/core"; import { tasks, projects, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { eq } from "drizzle-orm"; @@ -66,6 +66,30 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta return { stopped }; } +/** + * PEP-34: archive a story (hidden from the board, dispatcher and epic progress) or restore it. + * Its agents stop: nobody should work on an invisible card; a story at work goes back to the + * backlog first. + */ +export async function archiveTask(db: Db, ref: TaskRef, archived: boolean): Promise<{ stopped: number }> { + let stopped = 0; + if (archived) { + for (const s of await activeSessions(db, ref.task.id)) { + await stopSession(db, s.id); + stopped++; + } + if (columnOf(ref.task.status) === "in_progress") await updateTask(db, ref, { status: "backlog" }); + } + await setTaskArchived(db, ref, archived); + return { stopped }; +} + +/** PEP-34: board order within the story's column (= priority for the dispatcher). */ +export async function reorderBoardTask(db: Db, ref: TaskRef, r: ReorderTo) { + if (ref.task.archivedAt) throw new PeppaError(`${ref.key} в архиве`); + return reorderTask(db, ref, r, columnOf); +} + /** * "Accept" on a ready-for-review message: the task's PR is merged (green checks, no * conflicts — otherwise nothing changes and the PM sees why; Gitea deletes the branch), diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 3d6ab1fd..7a613c2a 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -26,3 +26,4 @@ export * from "./workspace-sync.ts"; export * from "./rotation.ts"; export * from "./live.ts"; export * from "./gitea-events.ts"; +export * from "./planner.ts"; diff --git a/packages/runner/src/planner.ts b/packages/runner/src/planner.ts new file mode 100644 index 00000000..6b084bda --- /dev/null +++ b/packages/runner/src/planner.ts @@ -0,0 +1,196 @@ +// Epic planner (PEP-42): one short non-interactive Claude call that breaks an epic into +// stories with acceptance criteria and dependencies. The result is a draft (settings +// `planner.draft:`) the PM edits and approves; approval creates the stories in the +// backlog under the epic, in plan order, with their dependencies. Tests use mock-planner. +import { + addDependency, + createTask, + deleteSetting, + getGoal, + getSetting, + listTasks, + PeppaError, + resolveTask, + setSetting, + type Goal, + type Project, + type TaskRef, +} from "@peppa/core"; +import type { Db } from "@peppa/db"; +import { claudePrint } from "./claude-print.ts"; + +/** A dependency: 1-based number of another story in the plan, or the key of an existing story. */ +export type PlanDep = number | string; + +export interface PlannedStory { + title: string; + description: string; + dependsOn: PlanDep[]; +} + +export interface PlanDraft { + epicId: number; + stories: PlannedStory[]; + /** The PM's wishes passed to the planner, if any. */ + wishes: string | null; + createdAt: string; + createdBy: string; +} + +export const PLAN_MAX_STORIES = 15; +const draftKey = (epicId: number) => `planner.draft:${epicId}`; + +export function plannerPrompt(project: Pick, epic: Pick, existing: Array<{ key: string; title: string; status: string }>, wishes?: string | null): string { + return [ + "Ты — планировщик софтвейр-фабрики Пеппа. Разбей эпик проекта на стори для AI-агентов.", + "Стори — одна законченная бизнес-история, которую агент делает за один PR (одна OpenSpec change):", + "не слишком мелкая (не «добавить поле»), не слишком крупная (не «сделать всё»). Обычно 3–8 стори, не больше " + PLAN_MAX_STORIES + ".", + "Для каждой стори: короткое название (до 80 символов), описание — кому и зачем, что сделать,", + "и раздел «Критерии готовности» списком; зависимости — какие стори должны быть готовы раньше.", + "Не повторяй уже существующие стори эпика; можешь зависеть от них по ключу.", + "", + `Проект: ${project.key} — ${project.name}`, + `Эпик: ${epic.title}`, + "Описание эпика:", + epic.description?.trim() || "(нет описания)", + "", + "Уже есть стори эпика:", + existing.length ? existing.map((t) => `- ${t.key} [${t.status}] ${t.title}`).join("\n") : "(нет)", + ...(wishes?.trim() ? ["", "Пожелания PM:", wishes.trim()] : []), + "", + 'Ответь ОДНОЙ строкой JSON без пояснений: {"stories":[{"title":"…","description":"…","depends_on":[1,"' + project.key + '-3"]}]}', + "depends_on — номера стори этого плана (с 1) или ключи существующих стори; пустой список, если зависимостей нет.", + ].join("\n"); +} + +/** Extracts the plan from the CLI's text answer (bare JSON or JSON inside prose/code fences). */ +export function parsePlannerOutput(text: string): PlannedStory[] | null { + const start = text.indexOf("{"); + if (start < 0) return null; + // The first balanced JSON object that has "stories". + for (let i = start; i >= 0 && i < text.length; i = text.indexOf("{", i + 1)) { + let depth = 0; + let inStr = false; + for (let j = i; j < text.length; j++) { + const c = text[j]; + if (inStr) { + if (c === "\\") j++; + else if (c === '"') inStr = false; + continue; + } + if (c === '"') inStr = true; + else if (c === "{") depth++; + else if (c === "}" && --depth === 0) { + try { + const o = JSON.parse(text.slice(i, j + 1)) as { stories?: unknown }; + if (Array.isArray(o.stories)) return normalizePlan(o.stories); + } catch {} + break; + } + } + } + return null; +} + +function normalizePlan(raw: unknown[]): PlannedStory[] | null { + const out: PlannedStory[] = []; + for (const r of raw.slice(0, PLAN_MAX_STORIES)) { + if (!r || typeof r !== "object") continue; + const o = r as { title?: unknown; description?: unknown; depends_on?: unknown; dependsOn?: unknown }; + const title = String(o.title ?? "").trim().slice(0, 200); + if (title.length < 3) continue; + const deps = (Array.isArray(o.depends_on) ? o.depends_on : Array.isArray(o.dependsOn) ? o.dependsOn : []) + .map((d) => (typeof d === "number" ? d : /^\d+$/.test(String(d).trim()) ? Number(d) : String(d).trim().toUpperCase())) + .filter((d) => (typeof d === "number" ? Number.isInteger(d) && d > 0 : d.length > 0)); + out.push({ title, description: String(o.description ?? "").trim().slice(0, 8000), dependsOn: [...new Set(deps)] }); + } + return out.length ? out : null; +} + +export type PlanResult = { ok: true; draft: PlanDraft } | { ok: false; error: string }; + +/** Runs `$PEPPA_PLANNER_BIN -p` (default `claude`) on a Claude subscription of the project's pool; saves the draft. */ +export async function planEpic(db: Db, project: Project, epicId: number, o: { wishes?: string | null; by: string }): Promise { + const epic = await getGoal(db, project.id, epicId); + const existing = await listTasks(db, { projectId: project.id, goalId: epic.id }); + const out = await claudePrint(db, project, { + bin: process.env.PEPPA_PLANNER_BIN ?? "claude", + model: process.env.PEPPA_PLANNER_MODEL ?? "sonnet", + timeoutMs: Number(process.env.PEPPA_PLANNER_TIMEOUT_MS ?? 180_000), + prompt: plannerPrompt(project, epic, existing.map((t) => ({ key: t.key, title: t.title, status: t.status })), o.wishes), + who: "планировщик", + }); + if (!out.ok) return out; + const stories = parsePlannerOutput(out.text); + if (!stories) return { ok: false, error: "планировщик ответил не по формату — попробуйте ещё раз или уточните описание эпика" }; + const draft: PlanDraft = { epicId: epic.id, stories, wishes: o.wishes?.trim() || null, createdAt: new Date().toISOString(), createdBy: o.by }; + await setSetting(db, draftKey(epic.id), draft); + return { ok: true, draft }; +} + +export async function getPlanDraft(db: Db, epicId: number): Promise { + return getSetting(db, draftKey(epicId)); +} + +export async function discardPlanDraft(db: Db, epicId: number): Promise { + await deleteSetting(db, draftKey(epicId)); +} + +/** Plan numbers must point inside the plan and the plan must have no cycles. */ +export function validatePlan(stories: PlannedStory[]): string | null { + if (!stories.length) return "в плане нет стори"; + if (stories.length > PLAN_MAX_STORIES) return `не больше ${PLAN_MAX_STORIES} стори за раз`; + for (const [i, s] of stories.entries()) { + if (s.title.trim().length < 3) return `стори ${i + 1}: нужно название`; + for (const d of s.dependsOn) { + if (typeof d === "number" && (d < 1 || d > stories.length)) return `стори ${i + 1}: нет стори №${d} в плане`; + if (d === i + 1) return `стори ${i + 1} зависит от самой себя`; + } + } + const state = new Array(stories.length).fill(0); + const visit = (i: number): boolean => { + if (state[i] === 1) return false; + if (state[i] === 2) return true; + state[i] = 1; + for (const d of stories[i]!.dependsOn) if (typeof d === "number" && !visit(d - 1)) return false; + state[i] = 2; + return true; + }; + for (let i = 0; i < stories.length; i++) if (!visit(i)) return "цикл зависимостей в плане"; + return null; +} + +/** + * Creates the approved plan: stories in the backlog under the epic, in plan order, then the + * dependencies. References to existing stories are checked before anything is created. + */ +export async function applyPlan(db: Db, project: Project, epicId: number, stories: PlannedStory[]): Promise { + const epic = await getGoal(db, project.id, epicId); + const bad = validatePlan(stories); + if (bad) throw new PeppaError(`План не принят: ${bad}`); + const existing = new Map(); + for (const s of stories) { + for (const d of s.dependsOn) { + if (typeof d !== "string" || existing.has(d)) continue; + const ref = await resolveTask(db, d, project.key).catch(() => null); + if (!ref || ref.project.id !== project.id) throw new PeppaError(`План не принят: стори ${d} нет в проекте ${project.key}`); + existing.set(d, ref); + } + } + const created: TaskRef[] = []; + for (const s of stories) created.push(await createTask(db, { projectId: project.id, goalId: epic.id, title: s.title.trim(), description: s.description.trim() || undefined })); + for (const [i, s] of stories.entries()) { + for (const d of s.dependsOn) await addDependency(db, created[i]!, typeof d === "number" ? created[d - 1]! : existing.get(d)!); + } + await discardPlanDraft(db, epic.id); + return created; +} + +/** "PAY-3, 2" → deps for a planned story (numbers stay plan numbers). */ +export function parseDepsInput(s: string): PlanDep[] { + return s + .split(/[\s,;]+/) + .map((x) => x.trim()) + .filter(Boolean) + .map((x) => (/^\d+$/.test(x) ? Number(x) : x.toUpperCase())); +} diff --git a/packages/testkit/bin/mock-planner b/packages/testkit/bin/mock-planner new file mode 100755 index 00000000..480c327c --- /dev/null +++ b/packages/testkit/bin/mock-planner @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" +exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-planner.ts" "$@" diff --git a/packages/testkit/src/mock-planner.ts b/packages/testkit/src/mock-planner.ts new file mode 100644 index 00000000..3a9b3750 --- /dev/null +++ b/packages/testkit/src/mock-planner.ts @@ -0,0 +1,44 @@ +// mock-planner (PEP-42): stands in for `claude -p --output-format json` as the epic planner. +// Reads the prompt on stdin, answers with the CLI's JSON envelope whose `result` is the plan +// line. Behaviour comes from MOCK_PLANNER_SCENARIO (a JSON file): +// { "stories": [{ "title": "…", "description": "…", "depends_on": [1] }], +// "garbage": false, "fail": false, "hang": false, "prose": false } +// Without a scenario: three stories derived from the epic title, each depending on the previous. +// Every call is appended to .log.jsonl (epic, wishes, existing stories, token, args). +import { appendFileSync, existsSync, readFileSync } from "node:fs"; + +interface Scenario { + stories?: Array<{ title: string; description?: string; depends_on?: Array }>; + garbage?: boolean; + fail?: boolean; + hang?: boolean; + /** Wrap the JSON in prose and a code fence, like a chatty model. */ + prose?: boolean; +} + +const file = process.env.MOCK_PLANNER_SCENARIO; +const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {}; +const prompt = readFileSync(0, "utf8"); +const epic = /^Эпик: (.*)$/m.exec(prompt)?.[1] ?? ""; +const wishes = /Пожелания PM:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null; +const existing = /Уже есть стори эпика:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? ""; +if (file) { + appendFileSync(`${file}.log.jsonl`, JSON.stringify({ args: process.argv.slice(2), epic, wishes, existing, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n"); +} +if (!process.argv.includes("-p")) { + console.error("mock-planner: expected -p (non-interactive print mode)"); + process.exit(2); +} +if (sc.hang) await new Promise(() => setInterval(() => {}, 1000)); +if (sc.fail) { + console.error("mock-planner: API Error: 529 overloaded"); + process.exit(1); +} +const stories = sc.stories ?? [ + { title: `${epic}: модель данных`, description: "Схема и миграция.\n\nКритерии готовности:\n- миграция применяется", depends_on: [] }, + { title: `${epic}: API`, description: "Эндпоинты.\n\nКритерии готовности:\n- тесты зелёные", depends_on: [1] }, + { title: `${epic}: экран`, description: "UI.\n\nКритерии готовности:\n- экран открывается", depends_on: [2] }, +]; +const json = JSON.stringify({ stories }); +const result = sc.garbage ? "Извините, я не могу составить план." : sc.prose ? `Вот план:\n\`\`\`json\n${json}\n\`\`\`\nУдачи!` : json; +process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result, session_id: "mock-planner" }) + "\n"); diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts index 60641496..421b3323 100644 --- a/packages/testkit/test/oauth.test.ts +++ b/packages/testkit/test/oauth.test.ts @@ -99,7 +99,7 @@ describe("PM tools over MCP", () => { await core.setProjectOwner(db, proj.id, owner.id); const { client, call } = await mcpAs(owner); const tools = (await client.listTools()).tools; - assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_project_settings", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_project_settings", "update_task"]); + assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "apply_plan", "archive_task", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_project_settings", "get_task", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_tasks", "move_task", "plan_epic", "remove_member", "reorder_task", "resolve_incident", "set_dependencies", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_project_settings", "update_task"]); assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true); assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false); From 4fdd3afd92326cfa28b658e326f28fa6003355cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 05:51:58 +0500 Subject: [PATCH 3/9] PEP-34/42: e2e tests for board order, archive, dependencies, planner Co-Authored-By: Claude Opus 5.5 --- packages/testkit/test/board-planner.test.ts | 228 ++++++++++++++++++++ 1 file changed, 228 insertions(+) create mode 100644 packages/testkit/test/board-planner.test.ts diff --git a/packages/testkit/test/board-planner.test.ts b/packages/testkit/test/board-planner.test.ts new file mode 100644 index 00000000..df4ddf16 --- /dev/null +++ b/packages/testkit/test/board-planner.test.ts @@ -0,0 +1,228 @@ +// PEP-34 (board order = priority, archive, epic progress) and PEP-42 (story dependencies, +// dispatcher waits for predecessors, epic planner on mock-planner). +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, describe, test } from "node:test"; +import { core, db, project, runner, teardown } from "./helpers.ts"; + +after(teardown); + +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); +const keysOf = async (projectId: number, status?: "backlog") => (await core.listTasks(db, { projectId, statuses: status ? [status] : undefined })).map((t) => t.key); +const refOf = (key: string) => core.resolveTask(db, key); +const projectOf = async () => { + const tp = await project({ turns: [] }); + return { tp, p: await core.getProject(db, tp.key) }; +}; + +describe("board order (PEP-34)", () => { + test("new stories go to the bottom; reorder top/bottom/before/after; order survives work and back", async () => { + const { tp, p } = await projectOf(); + const b = await core.createTask(db, { projectId: p.id, title: "вторая" }); + const c = await core.createTask(db, { projectId: p.id, title: "третья" }); + const a = tp.taskKey; + assert.deepEqual(await keysOf(p.id), [a, b.key, c.key]); + + await runner.reorderBoardTask(db, await refOf(c.key), { to: "before", other: await refOf(a) }); + assert.deepEqual(await keysOf(p.id), [c.key, a, b.key]); + await runner.reorderBoardTask(db, await refOf(c.key), { to: "after", other: await refOf(a) }); + assert.deepEqual(await keysOf(p.id), [a, c.key, b.key]); + await runner.reorderBoardTask(db, await refOf(b.key), { to: "top" }); + assert.deepEqual(await keysOf(p.id), [b.key, a, c.key]); + await runner.reorderBoardTask(db, await refOf(b.key), { to: "bottom" }); + assert.deepEqual(await keysOf(p.id), [a, c.key, b.key]); + + // "top" is within the column: a story in review doesn't count for the backlog. + await core.updateTask(db, await refOf(a), { status: "review" }); + await runner.reorderBoardTask(db, await refOf(b.key), { to: "top" }); + assert.deepEqual(await keysOf(p.id, "backlog"), [b.key, c.key]); + await core.updateTask(db, await refOf(a), { status: "backlog" }); + assert.deepEqual(await keysOf(p.id), [b.key, a, c.key], "a keeps its project-wide place; b, raised in the backlog, is above it"); + }); + + test("tiny gaps renumber the project without losing the order", async () => { + const { tp, p } = await projectOf(); + const b = await core.createTask(db, { projectId: p.id, title: "b" }); + const c = await core.createTask(db, { projectId: p.id, title: "c" }); + // Squeeze c between a and b many times: the midpoint halves the gap every time. + for (let i = 0; i < 30; i++) { + await runner.reorderBoardTask(db, await refOf(c.key), { to: "after", other: await refOf(tp.taskKey) }); + await runner.reorderBoardTask(db, await refOf(b.key), { to: "after", other: await refOf(tp.taskKey) }); + } + assert.deepEqual(await keysOf(p.id), [tp.taskKey, b.key, c.key]); + const positions = (await core.listTasks(db, { projectId: p.id })).map((t) => t.position); + assert.ok(positions[1]! - positions[0]! > 1e-7, `positions stay apart: ${positions}`); + }); + + test("other projects are refused", async () => { + const one = await projectOf(); + const two = await projectOf(); + await assert.rejects(runner.reorderBoardTask(db, await refOf(one.tp.taskKey), { to: "before", other: await refOf(two.tp.taskKey) }), /разных проектов/); + }); + + test("archive hides a story from the board, the dispatcher and epic progress; restore puts it at the bottom", async () => { + const { tp, p } = await projectOf(); + const epic = await core.createEpic(db, p.id, "Оплата"); + const s1 = await core.createTask(db, { projectId: p.id, title: "s1", goalId: epic.id }); + const s2 = await core.createTask(db, { projectId: p.id, title: "s2", goalId: epic.id }); + const s3 = await core.createTask(db, { projectId: p.id, title: "s3", goalId: epic.id }); + await core.updateTask(db, s1, { status: "done" }); + assert.deepEqual((await core.epicProgress(db, p.id)).get(epic.id), { done: 1, total: 3 }); + + await runner.archiveTask(db, await refOf(s3.key), true); + assert.deepEqual(await keysOf(p.id), [tp.taskKey, s1.key, s2.key]); + assert.deepEqual((await core.epicProgress(db, p.id)).get(epic.id), { done: 1, total: 2 }); + assert.equal(core.progressLabel((await core.epicProgress(db, p.id)).get(epic.id)), "1/2"); + assert.ok((await refOf(s3.key)).task.archivedAt, "the story page still resolves"); + assert.deepEqual((await core.listTasks(db, { projectId: p.id, includeArchived: true })).length, 4); + await assert.rejects(runner.reorderBoardTask(db, await refOf(s3.key), { to: "top" }), /в архиве/); + + await runner.reorderBoardTask(db, await refOf(s2.key), { to: "top" }); + await runner.archiveTask(db, await refOf(s3.key), false); + assert.equal((await keysOf(p.id)).at(-1), s3.key); + }); + + test("archiving a story at work stops its agent and returns it to the backlog", async () => { + const tp = await project({ turns: [[{ say: "работаю" }]] }); + const sid = await tp.start(); + await core.updateTask(db, await refOf(tp.taskKey), { status: "in_progress" }); + const r = await runner.archiveTask(db, await refOf(tp.taskKey), true); + assert.equal(r.stopped, 1); + assert.equal((await tp.task()).status, "backlog"); + assert.equal((await core.getSession(db, sid)).status, "done"); + }); +}); + +describe("dependencies (PEP-42)", () => { + test("blocked until predecessors are in review/done; no self, cycles or other projects; set replaces atomically", async () => { + const { tp, p } = await projectOf(); + const a = await refOf(tp.taskKey); + const b = await core.createTask(db, { projectId: p.id, title: "b" }); + const c = await core.createTask(db, { projectId: p.id, title: "c" }); + await core.addDependency(db, c, b); + await core.addDependency(db, b, a); + assert.deepEqual([...(await core.blockedTaskIds(db, p.id))].sort(), [b.task.id, c.task.id].sort()); + assert.equal(core.blockedLabel(await core.blockersOf(db, c)), `ждёт ${b.key}`); + assert.deepEqual((await core.dependentsOf(db, a)).map((d) => d.key), [b.key]); + + await assert.rejects(core.addDependency(db, a, c), /Цикл/); + await assert.rejects(core.addDependency(db, a, a), /самой себя/); + const other = await projectOf(); + await assert.rejects(core.addDependency(db, a, await refOf(other.tp.taskKey)), /другого проекта/); + // setDependencies: one bad key → nothing changes. + await assert.rejects(core.setDependencies(db, a, [c.key]), /Цикл/); + assert.deepEqual(await core.blockersOf(db, a), []); + await assert.rejects(core.setDependencies(db, c, [a.key, c.key]), /самой себя/); + assert.deepEqual((await core.blockersOf(db, c)).map((x) => x.key), [b.key], "previous list restored"); + assert.deepEqual((await core.setDependencies(db, c, [String(a.task.number)])).map((x) => x.key), [a.key], "bare numbers are this project's stories"); + + await core.updateTask(db, a, { status: "review" }); + assert.deepEqual([...(await core.blockedTaskIds(db, p.id))], [], "review unblocks b and c"); + const details = await core.getTaskDetails(db, await refOf(c.key)); + assert.deepEqual(details.blockers.map((x) => [x.key, x.open]), [[a.key, false]]); + }); + + test("an archived predecessor doesn't block", async () => { + const { tp, p } = await projectOf(); + const b = await core.createTask(db, { projectId: p.id, title: "b" }); + await core.addDependency(db, b, await refOf(tp.taskKey)); + assert.equal((await core.blockedTaskIds(db, p.id)).has(b.task.id), true); + await runner.archiveTask(db, await refOf(tp.taskKey), true); + assert.equal((await core.blockedTaskIds(db, p.id)).has(b.task.id), false); + }); + + test("auto dispatcher takes the top unblocked story; a raised story goes first", async () => { + const { tp, p } = await projectOf(); + const second = await core.createTask(db, { projectId: p.id, title: "предшественник" }); + const third = await core.createTask(db, { projectId: p.id, title: "поднятая" }); + // The first story waits for the second. + await core.addDependency(db, await refOf(tp.taskKey), second); + assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.key), [second.key, third.key]); + await runner.reorderBoardTask(db, third, { to: "top" }); + assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.key), [third.key, second.key]); + + await core.setAutonomy(db, p.id, { level: "auto", quietFrom: null, quietTo: null, wipLimit: 2 }); + await runner.autonomyTick(db, { now: new Date() }); + const active = (await core.listSessions(db, { active: true })).filter((s) => s.projectId === p.id); + assert.deepEqual(active.map((s) => s.taskKey).sort(), [second.key, third.key].sort(), "WIP 2: the blocked first story waits"); + assert.equal((await tp.task()).status, "backlog"); + for (const s of active) await runner.stopSession(db, s.id); + }); +}); + +describe("epic planner (PEP-42)", () => { + const dir = mkdtempSync(join(tmpdir(), "peppa-planner-")); + const scenario = join(dir, "scenario.json"); + process.env.PEPPA_PLANNER_BIN = join(ROOT, "packages/testkit/bin/mock-planner"); + process.env.MOCK_PLANNER_SCENARIO = scenario; + const calls = () => readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { args: string[]; epic: string; wishes: string | null; existing: string }); + + test("plan → draft → edit → apply: stories in the epic, plan order, dependencies", async () => { + writeFileSync(scenario, "{}"); + const { tp, p } = await projectOf(); + const epic = await core.createEpic(db, p.id, "Оплата картой", "Платёжная форма и вебхуки"); + await core.updateTask(db, await refOf(tp.taskKey), { goalId: epic.id }); + const r = await runner.planEpic(db, p, epic.id, { wishes: "без Stripe", by: "pm" }); + assert.ok(r.ok, !r.ok ? r.error : ""); + assert.equal(r.draft.stories.length, 3); + assert.deepEqual(r.draft.stories.map((s) => s.dependsOn), [[], [1], [2]]); + const call = calls().at(-1)!; + assert.equal(call.epic, "Оплата картой"); + assert.equal(call.wishes, "без Stripe"); + assert.match(call.existing, new RegExp(tp.taskKey), "existing stories of the epic go into the prompt"); + assert.ok(call.args.includes("--model") && call.args.includes("sonnet")); + assert.deepEqual((await runner.getPlanDraft(db, epic.id))?.stories.length, 3); + + // The PM drops the middle story and makes the last one wait for the first and an existing story. + const edited = [r.draft.stories[0]!, { ...r.draft.stories[2]!, dependsOn: [1, tp.taskKey] }]; + const created = await runner.applyPlan(db, p, epic.id, edited); + assert.equal(created.length, 2); + assert.deepEqual((await keysOf(p.id)).slice(-2), created.map((c) => c.key), "bottom of the board, plan order"); + assert.ok(created.every((c) => c.task.goalId === epic.id)); + assert.deepEqual((await core.blockersOf(db, created[1]!)).map((b) => b.key), [tp.taskKey, created[0]!.key]); + assert.equal(await runner.getPlanDraft(db, epic.id), null, "the draft is gone after approval"); + }); + + test("bad plans are refused before anything is created", async () => { + const { p } = await projectOf(); + const epic = await core.createEpic(db, p.id, "Эпик"); + const before = (await keysOf(p.id)).length; + const s = (title: string, dependsOn: Array = []) => ({ title, description: "", dependsOn }); + await assert.rejects(runner.applyPlan(db, p, epic.id, [s("первая", [2]), s("вторая", [1])]), /цикл/); + await assert.rejects(runner.applyPlan(db, p, epic.id, [s("первая", [5])]), /нет стори №5/); + await assert.rejects(runner.applyPlan(db, p, epic.id, [s("первая", ["ZZ-1"])]), /ZZ-1/); + await assert.rejects(runner.applyPlan(db, p, epic.id, []), /нет стори/); + assert.equal((await keysOf(p.id)).length, before); + }); + + test("prose around the JSON is fine; garbage and a failing CLI create nothing", async () => { + const { p } = await projectOf(); + const epic = await core.createEpic(db, p.id, "Отчёты"); + writeFileSync(scenario, JSON.stringify({ prose: true, stories: [{ title: "Отчёт по продажам", description: "{фигурные} скобки", depends_on: [] }] })); + const ok = await runner.planEpic(db, p, epic.id, { by: "pm" }); + assert.ok(ok.ok); + assert.equal(ok.draft.stories[0]!.description, "{фигурные} скобки"); + + writeFileSync(scenario, JSON.stringify({ garbage: true })); + const bad = await runner.planEpic(db, p, epic.id, { by: "pm" }); + assert.ok(!bad.ok); + assert.match(bad.error, /не по формату/); + + writeFileSync(scenario, JSON.stringify({ fail: true })); + const failed = await runner.planEpic(db, p, epic.id, { by: "pm" }); + assert.ok(!failed.ok); + assert.match(failed.error, /кодом 1/); + }); + + test("parser: depends_on as strings, caps, empty titles", () => { + const text = JSON.stringify({ stories: [{ title: "ok story", depends_on: ["2", "pep-7"] }, { title: "" }, ...Array.from({ length: 20 }, (_, i) => ({ title: `s${i} story` }))] }); + const plan = runner.parsePlannerOutput(text)!; + assert.equal(plan.length, runner.PLAN_MAX_STORIES - 1, "cut to the cap, the empty title dropped"); + assert.deepEqual(plan[0]!.dependsOn, [2, "PEP-7"]); + assert.equal(runner.parsePlannerOutput("нет плана"), null); + assert.deepEqual(runner.parseDepsInput("1, pep-3 ;2"), [1, "PEP-3", 2]); + }); +}); From 3b86c00768d00dab56debf0cd175421da38c679c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 05:54:05 +0500 Subject: [PATCH 4/9] =?UTF-8?q?PEP-34/42:=20web=20=E2=80=94=20board=20drag?= =?UTF-8?q?=20order,=20collapsed=20Done,=20epic=20progress,=20archive,=20d?= =?UTF-8?q?ependencies,=20plan=20page?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/board-actions.ts | 122 +++++++++++ apps/web/app/(app)/p/[key]/page.tsx | 24 ++- .../app/(app)/p/[key]/plan/[epic]/page.tsx | 102 +++++++++ apps/web/app/(app)/p/[key]/tabs.tsx | 29 ++- apps/web/app/(app)/t/[key]/page.tsx | 55 ++++- apps/web/components/Board.tsx | 201 +++++++++++++----- apps/web/components/PendingButton.tsx | 14 ++ apps/web/lib/queries.ts | 3 +- 8 files changed, 478 insertions(+), 72 deletions(-) create mode 100644 apps/web/app/(app)/board-actions.ts create mode 100644 apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx create mode 100644 apps/web/components/PendingButton.tsx diff --git a/apps/web/app/(app)/board-actions.ts b/apps/web/app/(app)/board-actions.ts new file mode 100644 index 00000000..7556b808 --- /dev/null +++ b/apps/web/app/(app)/board-actions.ts @@ -0,0 +1,122 @@ +"use server"; +// Board order and archive (PEP-34), story dependencies and the epic planner (PEP-42). +// Thin wrappers over core/runner with the owner/member check, like actions.ts. + +import { getEpic, PeppaError, projectForUser, resolveTask, setDependencies, type TaskRef } from "@peppa/core"; +import { applyPlan, archiveTask, discardPlanDraft, parseDepsInput, planEpic, reorderBoardTask, type PlanDep, type PlannedStory } from "@peppa/runner"; +import { revalidatePath } from "next/cache"; +import { redirect } from "next/navigation"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; + +const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim(); + +async function attempt(f: FormData, fn: () => Promise): Promise { + let target = str(f, "back") || "/"; + try { + target = (await fn()) || target; + } catch (e) { + const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`; + const [path, query] = target.split("?"); + const params = new URLSearchParams(query); + params.set("error", msg.slice(0, 300)); + target = `${path}?${params}`; + } + revalidatePath("/", "layout"); + redirect(target); +} + +async function ownedTask(userId: number, key: string): Promise { + const ref = await resolveTask(db, key); + await projectForUser(db, userId, ref.project.id); + return ref; +} + +/** Drag within a column (before/after another card) or the card menu (top/bottom). */ +export async function reorderTaskCard(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const ref = await ownedTask(user.id, str(f, "taskKey")); + const to = str(f, "to"); + if (to === "top" || to === "bottom") await reorderBoardTask(db, ref, { to }); + else if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, str(f, "other")) }); + else throw new PeppaError("Неизвестное место"); + }); +} + +/** Called from the board without a page reload (drag and drop); errors are returned. */ +export async function reorderTaskInline(taskKey: string, to: "top" | "bottom" | "before" | "after", other?: string): Promise { + const user = await requireUser(); + try { + const ref = await ownedTask(user.id, taskKey); + if (to === "before" || to === "after") await reorderBoardTask(db, ref, { to, other: await ownedTask(user.id, other ?? "") }); + else await reorderBoardTask(db, ref, { to }); + revalidatePath("/", "layout"); + return null; + } catch (e) { + return e instanceof PeppaError ? e.message : (e as Error).message; + } +} + +export async function archiveTaskAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const ref = await ownedTask(user.id, str(f, "taskKey")); + await archiveTask(db, ref, str(f, "archived") !== "0"); + }); +} + +export async function setDependenciesAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const ref = await ownedTask(user.id, str(f, "taskKey")); + const keys = str(f, "blockedBy").split(/[\s,;]+/).filter(Boolean); + // "remove" drops one key from the current list; otherwise the field adds to it. + const current = (f.getAll("current") as string[]).map(String); + const remove = str(f, "remove"); + await setDependencies(db, ref, remove ? current.filter((k) => k !== remove) : [...current, ...keys]); + }); +} + +export async function planEpicAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); + const epic = await getEpic(db, p.id, Number(str(f, "epicId"))); + const r = await planEpic(db, p, epic.id, { wishes: str(f, "wishes") || null, by: user.login }); + if (!r.ok) throw new PeppaError(`Планировщик: ${r.error}`); + }); +} + +export async function applyPlanAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); + const epicId = Number(str(f, "epicId")); + const n = Number(str(f, "count")); + // Plan numbers in the form refer to the full draft; renumber them for the kept stories. + const kept: number[] = []; + for (let i = 1; i <= n; i++) if (f.get(`keep_${i}`)) kept.push(i); + if (!kept.length) throw new PeppaError("Не выбрано ни одной стори"); + const renum = new Map(kept.map((orig, i) => [orig, i + 1])); + const stories: PlannedStory[] = kept.map((i) => { + const deps = parseDepsInput(str(f, `deps_${i}`)).map((d): PlanDep => { + if (typeof d !== "number") return d; + if (!renum.has(d)) throw new PeppaError(`Стори ${i} зависит от №${d}, которую вы сняли — уберите зависимость или оставьте стори`); + return renum.get(d)!; + }); + return { title: str(f, `title_${i}`), description: str(f, `description_${i}`), dependsOn: deps }; + }); + await applyPlan(db, p, epicId, stories); + return `/p/${p.key}?epic=${epicId}`; + }); +} + +export async function discardPlanAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); + const epic = await getEpic(db, p.id, Number(str(f, "epicId"))); + await discardPlanDraft(db, epic.id); + }); +} diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index c2ac9c13..c9acaee2 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -1,7 +1,7 @@ import { notFound } from "next/navigation"; import { ExternalLink, Plus, Rocket } from "lucide-react"; import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner"; -import { taskProgress, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core"; +import { blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core"; import { LiveRefresh } from "@/components/LiveRefresh"; import { PanelSection } from "@/components/ActivityAside"; import { Board, type Card } from "@/components/Board"; @@ -19,7 +19,7 @@ import { cn } from "@/lib/utils"; import { db } from "@/lib/db"; import { board, projectForUserByKey, projectSessions } from "@/lib/queries"; import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction } from "../../actions"; -import { CodeTab, EpicsPanel, PullsTab, SpecsTab } from "./tabs"; +import { CodeTab, EpicsPanel, ProgressBar, PullsTab, SpecsTab } from "./tabs"; import { setProjectPoolAction } from "../../subscriptions/actions"; const RELEASE_STATUS: Record = { @@ -67,7 +67,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board"; const p = await projectForUserByKey(user.id, key).catch(() => null); if (!p) notFound(); - const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer] = await Promise.all([ + const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps] = await Promise.all([ board(p.id), listEpics(db, p.id), projectSessions(p.id), @@ -79,6 +79,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr listReleases(db, p.id, 15), currentReleases(db, p.id), getReviewSettings(db, p.id), + epicProgress(db, p.id), + blockersMap(db, p.id), ]); // Peppa itself has no staging: its prod candidate is the newest green main (PEP-18). const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null); @@ -108,6 +110,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr epic: t.goalId ? (epicTitle.get(t.goalId) ?? null) : null, // PEP-33: tasks.md progress of stories in work. progress: pr && { done: pr.done, total: pr.total, current: pr.current }, + blocked: t.status === "backlog" ? blockedLabel(deps.get(t.id)) : null, }; }); // Gitea and the working copy are read only for the open tab. @@ -159,7 +162,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr - + @@ -347,12 +350,23 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr key={e.id} href={boardHref(e.id || undefined)} aria-current={active ? "page" : undefined} - className={cn("rounded-full border px-2.5 py-0.5 text-xs hover:no-underline", active ? "border-primary bg-primary/12 text-primary" : "text-muted-foreground hover:text-foreground")} + className={cn("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs hover:no-underline", active ? "border-primary bg-primary/12 text-primary" : "text-muted-foreground hover:text-foreground")} > {e.title} + {e.id > 0 && ( + + + {progressLabel(progress.get(e.id))} + + )} ); })} + {epicFilter && ( + + Спланировать стори эпика → + + )} )} diff --git a/apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx b/apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx new file mode 100644 index 00000000..9a85053a --- /dev/null +++ b/apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx @@ -0,0 +1,102 @@ +// PEP-42: plan an epic — the planner proposes stories with dependencies; the PM edits and approves. +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { Sparkles } from "lucide-react"; +import { getEpic, listTasks } from "@peppa/core"; +import { getPlanDraft } from "@peppa/runner"; +import { Hidden } from "@/components/cards"; +import { Empty, Flash, PageHeader, Section } from "@/components/common"; +import { PendingButton } from "@/components/PendingButton"; +import { Button } from "@/components/ui/button"; +import { Input, Textarea } from "@/components/ui/input"; +import { Workspace } from "@/components/Workspace"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { projectForUserByKey } from "@/lib/queries"; +import { applyPlanAction, discardPlanAction, planEpicAction } from "../../../../board-actions"; + +export default async function PlanEpicPage({ params, searchParams }: { params: Promise<{ key: string; epic: string }>; searchParams: Promise<{ error?: string }> }) { + const user = await requireUser(); + const { key, epic: epicParam } = await params; + const { error } = await searchParams; + const p = await projectForUserByKey(user.id, key).catch(() => null); + if (!p) notFound(); + const epic = await getEpic(db, p.id, Number(epicParam)).catch(() => null); + if (!epic) notFound(); + const [draft, existing] = await Promise.all([getPlanDraft(db, epic.id), listTasks(db, { projectId: p.id, goalId: epic.id })]); + const back = `/p/${p.key}/plan/${epic.id}`; + + return ( + + + + {p.name} + / + эпик «{epic.title}» + + } + title={<>Спланировать эпик «{epic.title}»} + > + Планировщик (короткая сессия Claude на подписке пула проекта) предложит стори с критериями готовности и зависимостями. Ничего не создаётся, пока вы не утвердите план. + + +
+
{epic.description || Без описания — опишите эпик в «⋯ Настройки проекта → Эпики», так план будет точнее.}
+ {existing.length > 0 && ( +

+ Уже есть стори: {existing.map((t) => t.key).join(", ")} — планировщик их не повторит и может от них зависеть. +

+ )} +
+ +