From 6ab17456af4e36360c25425bd0d93a2f7461f5f7 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:53:23 +0500 Subject: [PATCH 001/463] PEP-44, PEP-46: review preview with screenshots; Gitea issues, PR comments, manual merge Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/t/[key]/page.tsx | 4 + .../app/api/releases/[id]/shots/[n]/route.ts | 18 + apps/web/components/ReviewPreview.tsx | 46 + .../changes/pep-44-review-preview/proposal.md | 28 + .../specs/delivery-pipeline/spec.md | 18 + .../changes/pep-44-review-preview/tasks.md | 8 + openspec/changes/pep-45-bot-story/proposal.md | 29 + .../specs/telegram-notifications/spec.md | 28 + openspec/changes/pep-45-bot-story/tasks.md | 6 + .../pep-46-gitea-integration/design.md | 20 + .../pep-46-gitea-integration/proposal.md | 35 + .../specs/gitea-integration/spec.md | 41 + .../changes/pep-46-gitea-integration/tasks.md | 8 + packages/cli/src/index.ts | 11 +- packages/core/src/gitea.ts | 28 + packages/core/src/index.ts | 1 + packages/core/src/preview.ts | 55 + packages/core/src/tasks.ts | 5 +- packages/db/migrations/0007_calm_anthem.sql | 3 + .../db/migrations/meta/0007_snapshot.json | 2997 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 6 +- packages/mcp/src/format.ts | 2 + packages/runner/src/ci-feedback.ts | 16 +- packages/runner/src/ci.ts | 5 +- packages/runner/src/deploy.ts | 55 + packages/runner/src/flow.ts | 11 +- packages/runner/src/gitea-events.ts | 203 ++ packages/runner/src/hook.ts | 9 +- packages/runner/src/index.ts | 1 + packages/runner/src/reviewer.ts | 5 +- packages/shared/src/env.ts | 2 + packages/testkit/bin/mock-docker | 8 +- packages/testkit/src/mock-gitea.ts | 47 + packages/testkit/test/deploy.test.ts | 66 + packages/testkit/test/gitea-events.test.ts | 190 ++ template/.gitea/peppa-deploy.sh | 34 + 37 files changed, 4044 insertions(+), 12 deletions(-) create mode 100644 apps/web/app/api/releases/[id]/shots/[n]/route.ts create mode 100644 apps/web/components/ReviewPreview.tsx create mode 100644 openspec/changes/pep-44-review-preview/proposal.md create mode 100644 openspec/changes/pep-44-review-preview/specs/delivery-pipeline/spec.md create mode 100644 openspec/changes/pep-44-review-preview/tasks.md create mode 100644 openspec/changes/pep-45-bot-story/proposal.md create mode 100644 openspec/changes/pep-45-bot-story/specs/telegram-notifications/spec.md create mode 100644 openspec/changes/pep-45-bot-story/tasks.md create mode 100644 openspec/changes/pep-46-gitea-integration/design.md create mode 100644 openspec/changes/pep-46-gitea-integration/proposal.md create mode 100644 openspec/changes/pep-46-gitea-integration/specs/gitea-integration/spec.md create mode 100644 openspec/changes/pep-46-gitea-integration/tasks.md create mode 100644 packages/core/src/preview.ts create mode 100644 packages/db/migrations/0007_calm_anthem.sql create mode 100644 packages/db/migrations/meta/0007_snapshot.json create mode 100644 packages/runner/src/gitea-events.ts create mode 100644 packages/testkit/test/gitea-events.test.ts diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index f9413c46..f65c6347 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -17,6 +17,7 @@ import { PROVIDER_NAMES, readChange, reviewLabel, + reviewPreview, sessionSteps, storyComments, taskCiSummary, @@ -31,6 +32,7 @@ import { LiveRefresh } from "@/components/LiveRefresh"; import { Button } from "@/components/ui/button"; import { Input, NativeSelect, Textarea } from "@/components/ui/input"; import { Workspace } from "@/components/Workspace"; +import { ReviewPreview } from "@/components/ReviewPreview"; import { requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; import { taskActivity, taskForUser } from "@/lib/queries"; @@ -64,6 +66,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom const tab: StoryTab = STORY_TABS.find((t) => t.id === sp.tab)?.id ?? (change ? "proposal" : "comments"); const tabHref = (id: StoryTab) => `/t/${ref.key}?tab=${id}`; const back = tabHref(tab); + const preview = await reviewPreview(db, ref); // PEP-67: superadmins choose the subscriptions a runner may take; others run on the project's pool. const superadmin = await isSuperadmin(db, user); const pool = await projectPool(db, project.id); @@ -86,6 +89,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom const aside = (
+ {CI_ICON[ci.state as keyof typeof CI_ICON]} diff --git a/apps/web/app/api/releases/[id]/shots/[n]/route.ts b/apps/web/app/api/releases/[id]/shots/[n]/route.ts new file mode 100644 index 00000000..c507ccdc --- /dev/null +++ b/apps/web/app/api/releases/[id]/shots/[n]/route.ts @@ -0,0 +1,18 @@ +// Screenshots of a preview stand (PEP-44), taken by the project's CI step: only the +// project's owner and members see them. +import { projectForUser } from "@peppa/core"; +import { releaseScreenshot } from "@peppa/runner"; +import { currentUser } from "@/lib/auth"; +import { db } from "@/lib/db"; + +export const dynamic = "force-dynamic"; + +export async function GET(_req: Request, { params }: { params: Promise<{ id: string; n: string }> }) { + const user = await currentUser(); + if (!user) return new Response("Нужен вход", { status: 401 }); + const { id, n } = await params; + const shot = await releaseScreenshot(db, Number(id), Number(n)); + const allowed = shot && (await projectForUser(db, user.id, shot.projectId).then(() => true, () => false)); + if (!shot || !allowed) return new Response("Не найдено", { status: 404 }); + return new Response(new Uint8Array(shot.png), { headers: { "Content-Type": "image/png", "Cache-Control": "private, max-age=3600" } }); +} diff --git a/apps/web/components/ReviewPreview.tsx b/apps/web/components/ReviewPreview.tsx new file mode 100644 index 00000000..87e0a513 --- /dev/null +++ b/apps/web/components/ReviewPreview.tsx @@ -0,0 +1,46 @@ +// PEP-44/46: what the PM needs to review a story — the preview stand of its PR, the diff, +// the screenshots taken by CI, and the Gitea issue it came from. +import { Eye, FileDiff, CircleDot } from "lucide-react"; +import type { ReviewPreview as Preview } from "@peppa/core"; +import { PanelSection } from "@/components/ActivityAside"; + +export function ReviewPreview({ preview }: { preview: Preview }) { + if (!preview.previewUrl && !preview.diffUrl && !preview.issueUrl) return null; + return ( + +
+ {preview.previewUrl ? ( + + Посмотреть{preview.sha && {preview.sha.slice(0, 7)}} + + ) : ( + preview.diffUrl && Стенда PR ещё нет (деплой превью не настроен или не прошёл). + )} + {preview.diffUrl && ( + + Дифф + + )} + {preview.issueUrl && ( + + Issue в Gitea + + )} +
+ {preview.releaseId != null && preview.screenshots.length > 0 && ( +
+ {preview.screenshots.map((s) => { + const src = `/api/releases/${preview.releaseId}/shots/${s.n}`; + return ( + + {/* eslint-disable-next-line @next/next/no-img-element */} + {`Скриншот + {s.path} + + ); + })} +
+ )} +
+ ); +} diff --git a/openspec/changes/pep-44-review-preview/proposal.md b/openspec/changes/pep-44-review-preview/proposal.md new file mode 100644 index 00000000..ccfe7fb8 --- /dev/null +++ b/openspec/changes/pep-44-review-preview/proposal.md @@ -0,0 +1,28 @@ +# PEP-44: Превью результата на ревью — ссылка на стенд и скриншоты + +## Зачем +PM принимает стори вслепую по тексту агента. CD (PEP-57) уже поднимает стенд PR +`-pr.telecom.quest` и пишет его в `releases`, но ни сообщение «готово к ревью», +ни карточка стори об этом не говорят. + +## Что меняется +- **Сводка ревью** (`reviewPreview` в core): последний здоровый превью-стенд PR стори + («👀 Посмотреть»), дифф (`/files`), итог проверок (`taskCiSummary`), скриншоты. + Добавляется в «готово к ревью» (Stop-хук и агент-ревьюер), в карточку стори и в + MCP `get_task`. +- **Скриншоты в CI-шаге, не на хосте.** `peppa-deploy.sh preview` после здорового стенда + снимает страницы `deploy.screenshots` (по умолчанию `["/"]`) headless Chromium в + контейнере (`PEPPA_SCREENSHOT_IMAGE`, по умолчанию `zenika/alpine-chrome`) в сети + Traefik — PNG через stdout (base64), без томов, т.к. job сам в контейнере. Отчёт + `X-Peppa-Event: screenshots` (подпись как у deploy). Сбой скриншотов деплой не валит. +- **Пеппа хранит** PNG в `$PEPPA_HOME/screenshots//` (≤ 6 штук, ≤ 3 МБ, + проверка сигнатуры PNG), список — в `releases.screenshots`. Веб отдаёт их по + `/api/releases//shots/` только владельцу и участникам проекта. +- Превью поднялся после «готово к ревью» — ссылка есть в карточке (сообщение не редактируется). + +## Влияние +- БД: `releases.screenshots` (миграция). core: `reviewPreview`; runner: `recordScreenshots`, + хук, ревьюер; веб: маршрут скриншотов и блок в карточке; шаблон: `peppa-deploy.sh`. +- testkit: `mock-docker run` отдаёт PNG; `deploy.test.ts`. +- Реальная интеграция: `scripts/push-template.sh` и обновить `.gitea/peppa-deploy.sh` в + репо проектов; первый прогон скачает образ Chromium на docker хоста. diff --git a/openspec/changes/pep-44-review-preview/specs/delivery-pipeline/spec.md b/openspec/changes/pep-44-review-preview/specs/delivery-pipeline/spec.md new file mode 100644 index 00000000..42b1cd45 --- /dev/null +++ b/openspec/changes/pep-44-review-preview/specs/delivery-pipeline/spec.md @@ -0,0 +1,18 @@ +## ADDED Requirements + +### Requirement: Превью на ревью +Сообщение «готово к ревью» и карточка стори SHALL показывать ссылку на здоровый превью-стенд PR стори, ссылку на дифф и итог проверок; карточка SHALL показывать скриншоты стенда, снятые CI-шагом деплоя превью. + +#### Scenario: Стенд поднят +- **GIVEN** стори PAY-7 с PR #3 и здоровым превью `pay-pr3.telecom.quest` +- **WHEN** PAY-7 уходит в «Ревью» +- **THEN** «готово к ревью» содержит «Посмотреть: https://pay-pr3.telecom.quest», ссылку на дифф и итог проверок + +#### Scenario: Скриншоты +- **GIVEN** проект с `deploy.screenshots: ["/"]` +- **WHEN** превью PR #3 поднялось здоровым +- **THEN** CI-шаг присылает скриншот, он виден в карточке стори PAY-7 + +#### Scenario: Скриншоты не сняты +- **WHEN** снять скриншот не удалось +- **THEN** превью всё равно здоровое, карточка показывает ссылку без скриншотов diff --git a/openspec/changes/pep-44-review-preview/tasks.md b/openspec/changes/pep-44-review-preview/tasks.md new file mode 100644 index 00000000..b40db685 --- /dev/null +++ b/openspec/changes/pep-44-review-preview/tasks.md @@ -0,0 +1,8 @@ +# Tasks: PEP-44 + +- [ ] 1.1 Схема `releases.screenshots` + миграция; core `reviewPreview` +- [ ] 1.2 runner `recordScreenshots` + событие `screenshots` в хуке; сводка в Stop-хуке и ревьюере +- [ ] 1.3 Шаблон `peppa-deploy.sh`: скриншоты превью в контейнере, отчёт +- [ ] 1.4 Веб: маршрут скриншотов, блок «Превью» в карточке; MCP `get_task` +- [ ] 1.5 testkit: `mock-docker run`, `deploy.test.ts` +- [ ] 1.6 AGENTS.md, «Помощь», `openspec validate` diff --git a/openspec/changes/pep-45-bot-story/proposal.md b/openspec/changes/pep-45-bot-story/proposal.md new file mode 100644 index 00000000..f299b7d1 --- /dev/null +++ b/openspec/changes/pep-45-bot-story/proposal.md @@ -0,0 +1,29 @@ +# PEP-45: Создать стори сообщением боту — текст или голос + +## Зачем +Стори заводятся только в вебе или через MCP. PM в дороге хочет написать или наговорить +боту «в PAY: добавить экспорт в CSV» и сразу отдать агенту. + +## Что меняется +- **Текст.** Обычное сообщение привязанного пользователя (не команда и не реплай на вопрос) + — черновик стори. Префикс `KEY:` / `в KEY:` выбирает проект (только из доступных + пользователю). Иначе: один проект — он, несколько — кнопки проектов. +- **Эпик.** Есть открытые эпики — кнопки эпиков и «Без эпика»; нет — «✅ Создать» / + «Отмена». Шаг с кнопками — подтверждение: случайное сообщение не создаёт стори само. +- **Создание.** Первая строка — название (≤ 120 символов), остальное и пометка «из Telegram + (логин)» — описание. Ответ: «Создал PAY-12» с кнопками «▶️ Взять в работу» (`moveTask` → + агент) и «Оставить в бэклоге». +- **Голос.** Голосовое/аудио → файл из Bot API (`getFile`) → расшифровка по + OpenAI-совместимому API `POST $PEPPA_TRANSCRIBE_URL/audio/transcriptions` (multipart: + `file`, `model` = `$PEPPA_TRANSCRIBE_MODEL` (whisper-1), `language` = + `$PEPPA_TRANSCRIBE_LANG` (ru); `Authorization: Bearer $PEPPA_TRANSCRIBE_KEY`; ответ + `{text}`) → бот показывает расшифровку и дальше как текст. Не настроено — бот просит + написать текстом. Подходит OpenAI, Groq, локальный faster-whisper/speaches. +- Черновики — в `settings` (`bot.draft:`, сутки), без новых таблиц. + +## Влияние +- apps/bot: `drafts.ts`, `transcribe.ts`, `telegram.ts` (`getFile`, скачивание файла). +- testkit: `mock-telegram` (голосовые, `getFile`, `/file/…`), `mock-transcribe` + (контракт OpenAI audio API), тесты в `bot.test.ts`. +- На моке: расшифровка. Для настоящей — ключ OpenAI-совместимого сервиса в `.env` + (`PEPPA_TRANSCRIBE_URL`, `PEPPA_TRANSCRIBE_KEY`) и перезапуск бота. diff --git a/openspec/changes/pep-45-bot-story/specs/telegram-notifications/spec.md b/openspec/changes/pep-45-bot-story/specs/telegram-notifications/spec.md new file mode 100644 index 00000000..44253b8e --- /dev/null +++ b/openspec/changes/pep-45-bot-story/specs/telegram-notifications/spec.md @@ -0,0 +1,28 @@ +## ADDED Requirements + +### Requirement: Стори из сообщения боту +Привязанный пользователь SHALL создавать стори сообщением боту — текстом или голосом. Бот SHALL уточнять проект (если не указан и проектов несколько) и эпик кнопками, создавать стори только после нажатия кнопки и предлагать сразу взять её в работу. Проект SHALL выбираться только из доступных пользователю. + +#### Scenario: Текст с проектом +- **GIVEN** PM с привязанным Telegram и проектом «PAY» без эпиков +- **WHEN** PM пишет боту «в PAY: добавить экспорт в CSV» и нажимает «Создать» +- **THEN** в бэклоге PAY появляется стори «добавить экспорт в CSV» +- **AND** бот предлагает «Взять в работу» + +#### Scenario: Выбор проекта и эпика +- **GIVEN** у PM два проекта, в «PAY» есть эпик «Отчёты» +- **WHEN** PM пишет боту «экспорт в CSV», выбирает «PAY», затем «Отчёты» +- **THEN** стори создана в PAY с эпиком «Отчёты» + +#### Scenario: Взять в работу +- **WHEN** PM нажимает «Взять в работу» под созданной стори +- **THEN** стори «В работе», агент запущен + +#### Scenario: Голосовое +- **GIVEN** расшифровка голоса настроена +- **WHEN** PM присылает голосовое «в PAY добавить экспорт» +- **THEN** бот показывает расшифровку и предлагает создать стори в PAY + +#### Scenario: Чужой проект +- **WHEN** пользователь пишет «в SEC: …», а к проекту SEC у него нет доступа +- **THEN** проект SEC не предлагается и стори в нём не создаётся diff --git a/openspec/changes/pep-45-bot-story/tasks.md b/openspec/changes/pep-45-bot-story/tasks.md new file mode 100644 index 00000000..5394cc67 --- /dev/null +++ b/openspec/changes/pep-45-bot-story/tasks.md @@ -0,0 +1,6 @@ +# Tasks: PEP-45 + +- [ ] 1.1 Бот: черновик из текста (разбор `KEY:`), кнопки проекта/эпика, создание, «Взять в работу» +- [ ] 1.2 Голос: `getFile` + скачивание, `transcribe.ts` (OpenAI-совместимый API, env) +- [ ] 1.3 testkit: голос и файлы в `mock-telegram`, `mock-transcribe`, тесты в `bot.test.ts` +- [ ] 1.4 AGENTS.md, «Помощь», HELP бота, `openspec validate` diff --git a/openspec/changes/pep-46-gitea-integration/design.md b/openspec/changes/pep-46-gitea-integration/design.md new file mode 100644 index 00000000..04118a5f --- /dev/null +++ b/openspec/changes/pep-46-gitea-integration/design.md @@ -0,0 +1,20 @@ +# Design: PEP-46 + +## Определение события +`/api/hooks/gitea` передаёт `X-Gitea-Event`. Обработчик смотрит на payload, а не на имя: +- `comment` + `issue` → комментарий (`issue.pull_request` или `is_pull` → комментарий в PR); +- `review` + `pull_request` → ревью (`review.type` содержит `approved` → игнор); +- `pull_request` + `action` → событие PR (`closed` + `merged` → мерж); +- `issue` без `comment` → событие issue (`opened`/`reopened` → импорт). + +## Доступ +Отправитель (`sender.login`) сопоставляется с пользователем Пеппы по логину Gitea +(`users.gitea_id > 0`), затем `projectForUser`. Локальные пользователи (PEP-68) логина +Gitea не имеют. peppa-bot (`GITEA_BOT_LOGIN`, по умолчанию `peppa-bot`) — всегда игнор, +чтобы собственные комментарии Пеппы не возвращались агенту петлёй. + +## Мерж руками и гонка с «Принять» +`acceptTask` мержит PR сам, и вебхук `closed/merged` может прийти раньше, чем +`acceptTask` закроет вопрос. Обработчик закрывает только стори не в `done`, ответ на +вопрос «готово к ревью» — `answerQuestion(...).catch()`; в `acceptTask` закрытие вопроса +после мержа тоже терпит «уже отвечено». diff --git a/openspec/changes/pep-46-gitea-integration/proposal.md b/openspec/changes/pep-46-gitea-integration/proposal.md new file mode 100644 index 00000000..67610026 --- /dev/null +++ b/openspec/changes/pep-46-gitea-integration/proposal.md @@ -0,0 +1,35 @@ +# PEP-46: Интеграция с Gitea — вебхуки, issues и комментарии в PR + +## Зачем +Пеппа не знает, что происходит в Gitea, кроме проверок CI (PEP-57): комментарий человека +в PR агент не видит, мерж руками не закрывает стори, issues живут отдельно от бэклога. + +## Что меняется +- **Вебхук проекта** подписан ещё на `issues`, `issue_comment`, `pull_request_comment`, + `pull_request_review` (`setupCi` обновляет существующий хук). Обработчики — через + `onGiteaEvent` (runner/gitea-events.ts); тип события определяется по форме payload + (Gitea 1.22 шлёт одно и то же имя `pull_request_comment` и для комментария, и для ревью). +- **Issue → стори.** Открытый issue от пользователя с доступом к проекту (владелец или + участник, логин Gitea) становится стори в бэклоге (`tasks.gitea_issue`, идемпотентно); + peppa-bot пишет в issue комментарий со ссылкой на стори. Чужие issues (публичный репо) + игнорируются — иначе любой аккаунт Gitea заводил бы стори, а авто-режим брал бы их в работу. + Разовый импорт уже открытых issues — `peppa project import-issues ` (решение PM = + доверие, без проверки автора). +- **Стори готова → issue закрыт** с комментарием (PR стори), best effort. +- **Комментарий/ревью «нужны изменения» в PR стори** от человека с доступом уходит агенту + стори: в живой раннер или новым раннером (как красный CI), стори из «Ревью» возвращается + «В работу». Одобрение и комментарии peppa-bot игнорируются. Комментарий в issue стори — + только в живой раннер. +- **PR стори смержен руками в Gitea** → стори «Готово», раннер остановлен, «готово к + ревью» закрыт, рабочая копия синхронизирована. `acceptTask` терпит, что вебхук закрыл + вопрос раньше. +- **Красный CI → агенту** — уже есть (PEP-57). +- Карточка стори и MCP `get_task` показывают ссылку на issue. + +## Влияние +- БД: `tasks.gitea_issue` (миграция). Gitea-клиент: issues (список, комментарий, закрытие). +- runner: `gitea-events.ts`, `flow.ts` (done → закрыть issue; acceptTask), `ci.ts` (события хука). +- CLI `peppa project import-issues`. testkit: issues и комментарии в `mock-gitea`, + `gitea-events.test.ts`. +- Реальная интеграция: после выкатки — `peppa ci connect ` (или пересоздание проекта), + чтобы обновить подписку вебхука на новые события. diff --git a/openspec/changes/pep-46-gitea-integration/specs/gitea-integration/spec.md b/openspec/changes/pep-46-gitea-integration/specs/gitea-integration/spec.md new file mode 100644 index 00000000..e0333aa1 --- /dev/null +++ b/openspec/changes/pep-46-gitea-integration/specs/gitea-integration/spec.md @@ -0,0 +1,41 @@ +## ADDED Requirements + +### Requirement: Issues становятся стори +Открытый в репозитории проекта issue от пользователя с доступом к проекту SHALL становиться стори в бэклоге со ссылкой на issue, а issue SHALL получать комментарий со ссылкой на стори. Issue от пользователя без доступа SHALL игнорироваться. Когда стори готова, связанный issue SHALL закрываться. + +#### Scenario: Участник открыл issue +- **GIVEN** проект «PAY», владелец которого вошёл через Gitea как «pm» +- **WHEN** «pm» открывает issue «Экспорт в CSV» в репозитории PAY +- **THEN** в бэклоге PAY появляется стори «Экспорт в CSV» со ссылкой на issue +- **AND** в issue появляется комментарий со ссылкой на стори + +#### Scenario: Чужой issue +- **GIVEN** публичный репозиторий проекта «PAY» +- **WHEN** issue открывает пользователь Gitea без доступа к PAY +- **THEN** стори не создаётся + +#### Scenario: Стори готова +- **GIVEN** стори PAY-7, созданная из issue #3 +- **WHEN** PAY-7 переходит в «Готово» +- **THEN** issue #3 закрыт с комментарием + +### Requirement: Комментарии в PR уходят агенту +Комментарий или ревью «нужны изменения» в PR стори от пользователя с доступом SHALL доставляться агенту стори; стори из «Ревью» SHALL возвращаться «В работу». Одобрения и комментарии самой Пеппы SHALL игнорироваться. + +#### Scenario: Комментарий в PR +- **GIVEN** стори PAY-7 в «Ревью» с открытым PR +- **WHEN** «pm» пишет в PR комментарий «Переименуй кнопку» +- **THEN** агент PAY-7 получает текст комментария +- **AND** PAY-7 снова «В работе» + +#### Scenario: Комментарий бота +- **WHEN** комментарий в PR оставляет peppa-bot +- **THEN** агенту ничего не уходит + +### Requirement: Мерж руками закрывает стори +Мерж PR стори в Gitea вручную SHALL переводить стори в «Готово» и останавливать её раннер. + +#### Scenario: PM смержил PR в Gitea +- **GIVEN** стори PAY-7 в «Ревью» с открытым PR +- **WHEN** PR смержен в интерфейсе Gitea +- **THEN** PAY-7 в «Готово», сообщение «готово к ревью» закрыто diff --git a/openspec/changes/pep-46-gitea-integration/tasks.md b/openspec/changes/pep-46-gitea-integration/tasks.md new file mode 100644 index 00000000..10548620 --- /dev/null +++ b/openspec/changes/pep-46-gitea-integration/tasks.md @@ -0,0 +1,8 @@ +# Tasks: PEP-46 + +- [ ] 1.1 Схема `tasks.gitea_issue` + миграция; Gitea-клиент: issues, комментарий, закрытие; `GITEA_BOT_LOGIN` +- [ ] 1.2 runner `gitea-events.ts`: issue → стори, комментарий/ревью → агенту, мерж руками → done; регистрация через `onGiteaEvent` +- [ ] 1.3 `moveTask(done)` закрывает issue; `acceptTask` терпит закрытый вебхуком вопрос; события вебхука в `setupCi` +- [ ] 1.4 `importIssues` + CLI `peppa project import-issues`; issue в карточке и `get_task` +- [ ] 1.5 testkit: issues/комментарии в `mock-gitea`, `gitea-events.test.ts` по сценариям +- [ ] 1.6 AGENTS.md, «Помощь», `openspec validate` diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 4d4663df..6c5a20fb 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -52,7 +52,7 @@ import { type TaskStatus, } from "@peppa/core"; import { createDb, migrateDb } from "@peppa/db"; -import { answerAndDeliver, connectCi, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; +import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; import { readFileSync } from "node:fs"; import { loadEnv } from "@peppa/shared"; @@ -64,6 +64,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa project owner peppa project autonomy [manual|assisted|auto] [key=value…] (PEP-23: who takes stories, merge, closing, idle pushes) peppa project visibility public|private (repo visibility in Gitea: owner's client, then peppa-bot) + peppa project import-issues (PEP-46: open Gitea issues of the repo → backlog stories, linked back) peppa project list peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button) peppa release list [KEY] @@ -232,6 +233,14 @@ async function main(): Promise { console.log(`${p.key} owner → ${u?.login ?? "none"}`); break; } + case "project import-issues": { + if (!args[0]) throw new PeppaError("usage: peppa project import-issues "); + const p = await getProject(db, args[0]); + const out = await importIssues(db, p); + for (const r of out) console.log(`${r.key}${r.created ? " (new)" : ""}`); + console.log(`${out.filter((r) => r.created).length} imported, ${out.filter((r) => !r.created).length} already linked`); + break; + } case "project visibility": { const [first, second] = args; const keys = opts.all ? (await listProjects(db)).map((p) => p.key) : first ? [first] : []; diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts index 7d192808..b6ad2e06 100644 --- a/packages/core/src/gitea.ts +++ b/packages/core/src/gitea.ts @@ -58,6 +58,15 @@ export interface GiteaCombinedStatus { sha: string; statuses: GiteaCommitStatus[] | null; } +export interface GiteaIssue { + number: number; + title: string; + body?: string; + state: "open" | "closed"; + html_url: string; + user?: { login: string }; + pull_request?: unknown; +} export interface GiteaHook { id: number; type: string; @@ -271,6 +280,25 @@ export class GiteaClient { return this.request("POST", `${this.repoPath(owner, repo)}/hooks`, body); } + /** Open issues (not pull requests), oldest first. */ + async listOpenIssues(owner: string, repo: string): Promise { + const out: GiteaIssue[] = []; + for (let page = 1; page <= 10; page++) { + const batch = await this.request("GET", `${this.repoPath(owner, repo)}/issues?state=open&type=issues&limit=50&page=${page}`); + out.push(...batch.filter((i) => !i.pull_request)); + if (batch.length < 50) break; + } + return out.sort((a, b) => a.number - b.number); + } + + commentIssue(owner: string, repo: string, n: number, body: string) { + return this.request<{ id: number }>("POST", `${this.repoPath(owner, repo)}/issues/${n}/comments`, { body }); + } + + closeIssue(owner: string, repo: string, n: number) { + return this.request("PATCH", `${this.repoPath(owner, repo)}/issues/${n}`, { state: "closed" }); + } + createTag(owner: string, repo: string, tag: string, target: string, message?: string) { return this.request<{ name: string }>("POST", `${this.repoPath(owner, repo)}/tags`, { tag_name: tag, target, message }); } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c67f3061..4f411fd0 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -28,3 +28,4 @@ export * from "./digest.ts"; export * from "./autonomy.ts"; export * from "./openspec.ts"; export * from "./steps.ts"; +export * from "./preview.ts"; diff --git a/packages/core/src/preview.ts b/packages/core/src/preview.ts new file mode 100644 index 00000000..50481552 --- /dev/null +++ b/packages/core/src/preview.ts @@ -0,0 +1,55 @@ +// What the PM needs to review a story without a terminal (PEP-44): the preview stand of its +// PR (deployed by the project's CD, PEP-57), the diff, the checks and the screenshots the CI +// step took of the stand. Also the Gitea issue the story came from (PEP-46). +import { releases, type Db } from "@peppa/db"; +import { loadEnv } from "@peppa/shared"; +import { and, desc, eq } from "drizzle-orm"; +import { taskCiSummary, taskPrNumber } from "./ci.ts"; +import type { TaskRef } from "./tasks.ts"; + +export interface ReviewPreview { + /** https URL of the healthy preview stand of the story's PR. */ + previewUrl: string | null; + /** The release behind it (screenshots are served by its id). */ + releaseId: number | null; + /** Commit deployed to the stand. */ + sha: string | null; + diffUrl: string | null; + /** "Проверки: 4 из 4 пройдены". */ + checks: string; + screenshots: Array<{ n: number; path: string }>; + issueUrl: string | null; +} + +export async function reviewPreview(db: Db, ref: TaskRef): Promise { + const pr = taskPrNumber(ref.project, ref.task.prUrl); + const [rel] = pr + ? await db + .select() + .from(releases) + .where(and(eq(releases.projectId, ref.project.id), eq(releases.env, "preview"), eq(releases.prNumber, pr), eq(releases.status, "healthy"))) + .orderBy(desc(releases.id)) + .limit(1) + : []; + const issueUrl = ref.task.giteaIssue + ? `${loadEnv().GITEA_URL.replace(/\/$/, "")}/${ref.project.giteaOwner}/${ref.project.giteaRepo}/issues/${ref.task.giteaIssue}` + : null; + return { + previewUrl: rel?.host ? `https://${rel.host}` : null, + releaseId: rel?.id ?? null, + sha: rel?.sha ?? null, + diffUrl: ref.task.prUrl ? `${ref.task.prUrl.replace(/\/$/, "")}/files` : null, + checks: (await taskCiSummary(db, ref)).label, + screenshots: (rel?.screenshots ?? []).map((s, n) => ({ n, path: s.path })), + issueUrl, + }; +} + +/** Lines for the "ready for review" message: look, diff, checks (empty parts left out). */ +export function reviewPreviewNote(p: ReviewPreview): string { + const lines: string[] = []; + if (p.previewUrl) lines.push(`👀 Посмотреть: ${p.previewUrl}${p.screenshots.length ? ` (скриншотов: ${p.screenshots.length} — в карточке)` : ""}`); + if (p.diffUrl) lines.push(`📄 Дифф: ${p.diffUrl}`); + if (p.checks) lines.push(`🧪 ${p.checks.charAt(0).toUpperCase()}${p.checks.slice(1)}`); + return lines.join("\n"); +} diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index 12b6cfdb..745d158b 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -8,6 +8,7 @@ import { incidentForTask, type Incident } from "./incidents.ts"; 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"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -137,6 +138,8 @@ export interface TaskDetails { autonomy: AutonomySettings; /** PM comments on the story (PEP-32), oldest first: the agent reads them in get_task. */ comments: StoryComment[]; + /** Preview stand, diff, checks, screenshots, Gitea issue (PEP-44/46). */ + preview: ReviewPreview; } export const COMMENT_EVENT = "pm_comment"; @@ -178,7 +181,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) }; + 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) }; } export interface NewQuestion { diff --git a/packages/db/migrations/0007_calm_anthem.sql b/packages/db/migrations/0007_calm_anthem.sql new file mode 100644 index 00000000..31aca708 --- /dev/null +++ b/packages/db/migrations/0007_calm_anthem.sql @@ -0,0 +1,3 @@ +ALTER TABLE `releases` ADD `screenshots` text DEFAULT '[]' NOT NULL;--> statement-breakpoint +ALTER TABLE `tasks` ADD `gitea_issue` integer;--> statement-breakpoint +CREATE UNIQUE INDEX `tasks_project_issue` ON `tasks` (`project_id`,`gitea_issue`); \ No newline at end of file diff --git a/packages/db/migrations/meta/0007_snapshot.json b/packages/db/migrations/meta/0007_snapshot.json new file mode 100644 index 00000000..e739eee2 --- /dev/null +++ b/packages/db/migrations/meta/0007_snapshot.json @@ -0,0 +1,2997 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "d8e80765-8ce2-47d6-b112-53bf26c85f84", + "prevId": "b6495e1a-6087-42fb-a94f-3e6942582651", + "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": {} + }, + "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 + }, + "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 d8790d22..900dcfed 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -50,6 +50,13 @@ "when": 1794615712278, "tag": "0006_rotation", "breakpoints": true + }, + { + "idx": 7, + "version": "6", + "when": 1794617253656, + "tag": "0007_calm_anthem", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 85de53c7..84b5c49c 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -127,10 +127,12 @@ export const tasks = sqliteTable( // PEP-57: red CI runs in a row (distinct head SHAs) since the last green one. ciAttempts: integer("ci_attempts").notNull().default(0), 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"), createdAt: createdAt(), updatedAt: updatedAt(), }, - (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)], + (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number), uniqueIndex("tasks_project_issue").on(t.projectId, t.giteaIssue)], ); /** PEP-57: one deployment of a project to an environment (and its outcome). */ @@ -151,6 +153,8 @@ export const releases = sqliteTable("releases", { reason: text("reason"), runUrl: text("run_url"), logTail: text("log_tail"), + // PEP-44: screenshots of a preview taken by the CI step (files under $PEPPA_HOME/screenshots). + screenshots: text("screenshots", { mode: "json" }).$type>().notNull().default([]), createdAt: createdAt(), updatedAt: updatedAt(), }); diff --git a/packages/mcp/src/format.ts b/packages/mcp/src/format.ts index 6c489bc0..93244ddd 100644 --- a/packages/mcp/src/format.ts +++ b/packages/mcp/src/format.ts @@ -21,6 +21,8 @@ export function formatTask(d: TaskDetails): string { `- OpenSpec change: ${task.openspecChange ? `\`openspec/changes/${task.openspecChange}/\`` : "ещё нет"}`, ]; 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})` : ""}`); 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/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 8bf13aff..0c61d5fb 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -23,8 +23,9 @@ import { checkRuns, projects, tasks, type Db } from "@peppa/db"; import { and, eq, sql } from "drizzle-orm"; import { sendToSession } from "./sessions.ts"; import { moveTask } from "./flow.ts"; -import { recordRelease } from "./deploy.ts"; +import { recordRelease, recordScreenshots } from "./deploy.ts"; import { offerPlatformRelease } from "./platform-release.ts"; +import { handleGiteaEvent } from "./gitea-events.ts"; /** Red runs in a row after which the PM is asked instead of the agent. */ export const MAX_CI_ATTEMPTS = 3; @@ -174,8 +175,19 @@ export async function handleGiteaHook(db: Db, req: HookRequest): Promise<{ statu }); return { status: 200, body: { ok: true, release: rel.id, status: rel.status } }; } + if (req.event === "screenshots") { + if (typeof payload.sha !== "string" || !Array.isArray(payload.shots)) return { status: 400, body: { error: "bad screenshots report" } }; + const out = await recordScreenshots(db, project, { + sha: payload.sha, + prNumber: typeof payload.pr === "number" ? payload.pr : null, + shots: (payload.shots as Array<{ path?: unknown; png?: unknown }>).map((s) => ({ path: String(s.path ?? "/"), png: String(s.png ?? "") })), + }); + return { status: 200, body: { ok: true, ...out } }; + } + // PEP-46: issues, comments and reviews in PRs, PRs merged by hand. + const out = await handleGiteaEvent(db, project, payload); for (const h of eventHandlers) await h(db, project, req.event, payload); - return { status: 200, body: { ok: true } }; + return { status: 200, body: { ok: true, ...out } }; } /** diff --git a/packages/runner/src/ci.ts b/packages/runner/src/ci.ts index 805d1854..acf82742 100644 --- a/packages/runner/src/ci.ts +++ b/packages/runner/src/ci.ts @@ -18,6 +18,9 @@ export const CD_SCAFFOLD = ["deploy/compose.yml", "deploy/Dockerfile.node", "dep export const CI_BRANCH = "peppa/ci"; export const CI_SECRET_NAME = "PEPPA_CI_SECRET"; +/** Events the project webhook gets: PRs and pushes (PEP-57), issues, comments, reviews (PEP-46). */ +export const GITEA_HOOK_EVENTS = ["pull_request", "push", "issues", "issue_comment", "pull_request_comment", "pull_request_review"]; + /** Where Gitea webhooks and CI reports reach Peppa. */ export const giteaHookUrl = () => `${loadEnv().PEPPA_WEB_URL.replace(/\/$/, "")}/api/hooks/gitea`; @@ -66,7 +69,7 @@ export async function setupCi(db: Db, project: Project): Promise { const secret = projectHookSecret(project.id); await asAdmin(clients, `Секрет ${CI_SECRET_NAME}`, (c) => c.setActionsSecret(project.giteaOwner, project.giteaRepo, CI_SECRET_NAME, secret)); // PR and push events (preview stands, merges) — signed with the same secret. - await asAdmin(clients, "Вебхук", (c) => c.upsertHook(project.giteaOwner, project.giteaRepo, giteaHookUrl(), secret, ["pull_request", "push"])); + await asAdmin(clients, "Вебхук", (c) => c.upsertHook(project.giteaOwner, project.giteaRepo, giteaHookUrl(), secret, GITEA_HOOK_EVENTS)); return { runner }; } diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts index b516cf09..6771c999 100644 --- a/packages/runner/src/deploy.ts +++ b/packages/runner/src/deploy.ts @@ -6,6 +6,9 @@ import { answerQuestion, askPmProject, giteaForBot, PeppaError, runLink, type Gi import { projects, questions, releases, type Db } from "@peppa/db"; import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; import { deployPlatform, isPlatform } from "./platform-release.ts"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { peppaHome } from "@peppa/shared"; export type Release = typeof releases.$inferSelect; export type ReleaseEnv = Release["env"]; @@ -169,3 +172,55 @@ export async function onReleaseAnswer(db: Db, q: Question, answer: string, by: s } return true; } + +/** PEP-44: limits for screenshots sent by the CI step. */ +export const MAX_SCREENSHOTS = 6; +export const MAX_SCREENSHOT_BYTES = 3 * 1024 * 1024; +const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + +export interface ScreenshotReport { + sha: string; + prNumber: number | null; + shots: Array<{ path: string; png: string }>; +} + +const screenshotDir = (projectId: number) => join(peppaHome(), "screenshots", String(projectId)); + +/** + * Screenshots of a preview stand (CI step after a healthy preview): PNG files under + * $PEPPA_HOME/screenshots//, listed on the preview release of that PR and commit. + * Not PNG, too big or too many → skipped. Returns how many were kept. + */ +export async function recordScreenshots(db: Db, project: Project, r: ScreenshotReport): Promise<{ release: number | null; saved: number }> { + const [rel] = await db + .select() + .from(releases) + .where(and(eq(releases.projectId, project.id), eq(releases.env, "preview"), eq(releases.sha, r.sha), r.prNumber ? eq(releases.prNumber, r.prNumber) : undefined)) + .orderBy(desc(releases.id)) + .limit(1); + if (!rel) return { release: null, saved: 0 }; + const dir = screenshotDir(project.id); + mkdirSync(dir, { recursive: true }); + const kept: Array<{ path: string; file: string }> = []; + for (const [i, s] of r.shots.slice(0, MAX_SCREENSHOTS).entries()) { + const buf = Buffer.from(s.png ?? "", "base64"); + if (buf.length < PNG_MAGIC.length || buf.length > MAX_SCREENSHOT_BYTES || !buf.subarray(0, 8).equals(PNG_MAGIC)) continue; + const file = `r${rel.id}-${i}.png`; + writeFileSync(join(dir, file), buf); + kept.push({ path: String(s.path ?? "/").slice(0, 200), file }); + } + await db.update(releases).set({ screenshots: kept }).where(eq(releases.id, rel.id)); + return { release: rel.id, saved: kept.length }; +} + +/** PNG bytes of screenshot `n` of a release (null when absent). Access is checked by the caller. */ +export async function releaseScreenshot(db: Db, releaseId: number, n: number): Promise<{ projectId: number; png: Buffer } | null> { + const [rel] = await db.select().from(releases).where(eq(releases.id, releaseId)); + const s = rel?.screenshots[n]; + if (!rel || !s || !/^r\d+-\d+\.png$/.test(s.file)) return null; + try { + return { projectId: rel.projectId, png: readFileSync(join(screenshotDir(rel.projectId), s.file)) }; + } catch { + return null; + } +} diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts index abc9cf9e..932910ad 100644 --- a/packages/runner/src/flow.ts +++ b/packages/runner/src/flow.ts @@ -6,6 +6,8 @@ import { eq } from "drizzle-orm"; import { startSession, stopSession, type StartOptions } from "./sessions.ts"; import { mergeTaskPr } from "./ci-feedback.ts"; import { syncWorkspace } from "./workspace-sync.ts"; +import { closeLinkedIssue } from "./gitea-events.ts"; +import type { GiteaClient } from "@peppa/core"; export type BoardColumn = "backlog" | "in_progress" | "review" | "done"; @@ -35,7 +37,7 @@ export async function reviewGate(ref: TaskRef): Promise { * started unless one is running. Into "review": only past the CI gate. Into * "backlog"/"done": active sessions are stopped. */ -export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: StartOptions = {}): Promise<{ started?: number; stopped: number }> { +export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: StartOptions = {}, gitea?: GiteaClient): Promise<{ started?: number; stopped: number }> { const from = columnOf(ref.task.status); let stopped = 0; if (to === "in_progress") { @@ -56,7 +58,11 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta stopped++; } } + // Fresh status: a webhook (PEP-46) may have finished the story since `ref` was read. + const [now] = to === "done" ? await db.select({ status: tasks.status }).from(tasks).where(eq(tasks.id, ref.task.id)) : []; if (from !== to || ref.task.status !== to) await updateTask(db, ref, { status: to }); + // PEP-46: a finished story closes the Gitea issue it came from. + if (to === "done" && now && now.status !== "done") await closeLinkedIssue(ref, gitea); return { stopped }; } @@ -77,7 +83,8 @@ export async function acceptTask(db: Db, questionId: number, via: NonNullable {}); await moveTask(db, ref, "done"); // PEP-25: the merged main lands in the working copy (best effort, never fails the accept). await syncWorkspace(db, ref).catch(() => {}); diff --git a/packages/runner/src/gitea-events.ts b/packages/runner/src/gitea-events.ts new file mode 100644 index 00000000..f1030338 --- /dev/null +++ b/packages/runner/src/gitea-events.ts @@ -0,0 +1,203 @@ +// Gitea → Peppa (PEP-46): issues become stories, comments and "changes requested" reviews in +// a story's PR go to its agent, a PR merged by hand in Gitea closes the story; a finished +// story closes its issue. CI results are handled in ci-feedback.ts (PEP-57). +// +// Gitea 1.22 names review events and PR comments alike (`pull_request_comment`), so the kind +// of event is taken from the payload shape, not from the header. +import { answerQuestion, createTask, giteaForBot, listSessions, taskForCheck, type GiteaClient, type Project, type TaskRef } from "@peppa/core"; +import { events, projectMembers, questions, tasks, users, type Db } from "@peppa/db"; +import { formatTaskKey, loadEnv } from "@peppa/shared"; +import { and, eq, gt, isNull, sql } from "drizzle-orm"; +import { sendToSession } from "./sessions.ts"; +import { moveTask } from "./flow.ts"; +import { syncWorkspace } from "./workspace-sync.ts"; + +type Payload = Record; +interface GUser { + login?: string; + username?: string; +} +interface GIssue { + number: number; + title?: string; + body?: string; + html_url?: string; + user?: GUser; + pull_request?: unknown; +} +interface GPull { + number: number; + merged?: boolean; + html_url?: string; + head?: { ref?: string }; +} + +export type GiteaEventKind = "issue" | "issue_comment" | "pr_comment" | "review" | "pull_request" | "other"; + +/** What a webhook is about, from the payload shape (Gitea 1.22 reuses event names). */ +export function giteaEventKind(p: Payload): GiteaEventKind { + if (p.comment && p.issue) return (p.issue as GIssue).pull_request || p.is_pull ? "pr_comment" : "issue_comment"; + if (p.review && p.pull_request) return "review"; + if (p.pull_request && p.action) return "pull_request"; + if (p.issue && p.action) return "issue"; + return "other"; +} + +const loginOf = (u: GUser | undefined) => (u?.login ?? u?.username ?? "").trim(); +const isBot = (login: string) => login.toLowerCase() === loadEnv().GITEA_BOT_LOGIN.toLowerCase(); +const webUrl = () => loadEnv().PEPPA_WEB_URL.replace(/\/$/, ""); + +/** True when the Gitea login is a Peppa user (Gitea account) who owns or shares the project. */ +export async function giteaLoginHasAccess(db: Db, project: Project, login: string): Promise { + if (!login) return false; + const [u] = await db + .select({ id: users.id, disabledAt: users.disabledAt }) + .from(users) + .where(and(sql`lower(${users.login}) = ${login.toLowerCase()}`, gt(users.giteaId, 0))); + if (!u || u.disabledAt) return false; + if (project.ownerId === u.id) return true; + const [m] = await db + .select({ id: projectMembers.userId }) + .from(projectMembers) + .where(and(eq(projectMembers.projectId, project.id), eq(projectMembers.userId, u.id))); + return !!m; +} + +async function logProjectEvent(db: Db, project: Project, type: string, payload: Record, taskId?: number) { + await db.insert(events).values({ projectId: project.id, taskId, type, payload }); +} + +export interface IssueImport { + key: string; + created: boolean; +} + +/** Story for an issue (idempotent by issue number); peppa-bot links back from the issue. */ +export async function importIssue(db: Db, project: Project, issue: GIssue, gitea?: GiteaClient): Promise { + const [have] = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.giteaIssue, issue.number))); + if (have) return { key: formatTaskKey(project.key, have.number), created: false }; + const title = (issue.title ?? "").trim().slice(0, 200) || `Issue #${issue.number}`; + const body = (issue.body ?? "").trim(); + const link = issue.html_url ?? `${loadEnv().GITEA_URL.replace(/\/$/, "")}/${project.giteaOwner}/${project.giteaRepo}/issues/${issue.number}`; + const ref = await createTask(db, { projectId: project.id, title, description: `${body ? `${body}\n\n` : ""}Issue Gitea: ${link}` }); + await db.update(tasks).set({ giteaIssue: issue.number }).where(eq(tasks.id, ref.task.id)); + await logProjectEvent(db, project, "issue_imported", { issue: issue.number, author: loginOf(issue.user) }, ref.task.id); + try { + await (gitea ?? giteaForBot()).commentIssue(project.giteaOwner, project.giteaRepo, issue.number, `Стори ${ref.key} в Пеппе: ${webUrl()}/t/${ref.key}`); + } catch {} + return { key: ref.key, created: true }; +} + +/** One-time import of the repo's open issues (the PM asked: no author check). */ +export async function importIssues(db: Db, project: Project, gitea: GiteaClient = giteaForBot()): Promise { + const out: IssueImport[] = []; + for (const i of await gitea.listOpenIssues(project.giteaOwner, project.giteaRepo)) out.push(await importIssue(db, project, i, gitea)); + return out; +} + +/** A finished story closes its issue with a comment (best effort). */ +export async function closeLinkedIssue(ref: TaskRef, gitea?: GiteaClient): Promise { + if (!ref.task.giteaIssue) return false; + try { + const c = gitea ?? giteaForBot(); + await c.commentIssue(ref.project.giteaOwner, ref.project.giteaRepo, ref.task.giteaIssue, `✅ Стори ${ref.key} готова${ref.task.prUrl ? `: ${ref.task.prUrl}` : ""}.`); + await c.closeIssue(ref.project.giteaOwner, ref.project.giteaRepo, ref.task.giteaIssue); + return true; + } catch { + return false; + } +} + +const ACTIVE = ["proposing", "in_progress", "review", "blocked"]; + +/** Text from a human in Gitea → the story's agent: live runner, else a new one (story back in work). */ +async function toAgent(db: Db, ref: TaskRef, text: string, restart: boolean): Promise<"agent" | "restarted" | "none"> { + const [s] = await listSessions(db, { active: true, taskId: ref.task.id }); + if (s) { + try { + await sendToSession(db, s.id, text); + if (ref.task.status === "review") await moveTask(db, ref, "in_progress"); + return "agent"; + } catch {} + } + if (!restart) return "none"; + await moveTask(db, ref, "in_progress", { prompt: text }); + return "restarted"; +} + +async function taskByIssue(db: Db, project: Project, n: number): Promise { + const [t] = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.giteaIssue, n))); + return t ? { project, task: t, key: formatTaskKey(project.key, t.number) } : null; +} + +export interface GiteaEventOutcome { + kind: GiteaEventKind; + task?: string | null; + action: string; +} + +/** Dispatches a Gitea webhook (other than CI reports) for a project. */ +export async function handleGiteaEvent(db: Db, project: Project, payload: Payload, gitea?: GiteaClient): Promise { + const kind = giteaEventKind(payload); + const sender = loginOf(payload.sender as GUser); + const action = String(payload.action ?? ""); + + if (kind === "issue") { + const issue = payload.issue as GIssue; + if (action !== "opened" && action !== "reopened") return { kind, action: "none" }; + const author = loginOf(issue.user) || sender; + if (isBot(author)) return { kind, action: "none" }; + if (!(await giteaLoginHasAccess(db, project, author))) return { kind, action: "no_access" }; + const r = await importIssue(db, project, issue, gitea); + return { kind, task: r.key, action: r.created ? "imported" : "exists" }; + } + + if (kind === "pull_request") { + const pull = payload.pull_request as GPull; + if (action !== "closed" || !pull.merged) return { kind, action: "none" }; + const ref = await taskForCheck(db, project, pull.head?.ref, pull.number ?? (payload.number as number)); + if (!ref || ref.task.status === "done") return { kind, task: ref?.key ?? null, action: "none" }; + // Merged by hand in Gitea (Peppa's own merges move the story to done right after). + for (const q of await db.select().from(questions).where(and(eq(questions.taskId, ref.task.id), isNull(questions.answeredAt), eq(questions.kind, "attention")))) { + await answerQuestion(db, q.id, `✅ PR смержен в Gitea${sender ? ` (${sender})` : ""}`, "system").catch(() => {}); + } + await moveTask(db, ref, "done", {}, gitea); // also closes the story's issue + await syncWorkspace(db, ref).catch(() => {}); + await logProjectEvent(db, project, "pr_merged_in_gitea", { pr: pull.number, by: sender }, ref.task.id); + return { kind, task: ref.key, action: "done" }; + } + + if (kind === "pr_comment" || kind === "review" || kind === "issue_comment") { + if (!sender || isBot(sender)) return { kind, action: "none" }; + let ref: TaskRef | null; + let text: string; + if (kind === "review") { + const pull = payload.pull_request as GPull; + const review = payload.review as { type?: string; content?: string }; + const type = `${review.type ?? ""} ${action}`.toLowerCase(); + if (type.includes("approved")) return { kind, action: "none" }; + const content = (review.content ?? "").trim(); + if (!content) return { kind, action: "none" }; + ref = await taskForCheck(db, project, pull.head?.ref, pull.number); + const verdict = type.includes("rejected") ? "просит изменений" : "оставил ревью"; + text = `💬 ${sender} ${verdict} в PR #${pull.number}${pull.html_url ? ` (${pull.html_url}/files)` : ""}:\n\n${content}\n\nРазбери замечания (комментарии к строкам — в PR), исправь и запушь в ту же ветку.`; + } else { + if (action && action !== "created") return { kind, action: "none" }; + const issue = payload.issue as GIssue; + const comment = payload.comment as { body?: string; html_url?: string }; + const body = (comment.body ?? "").trim(); + if (!body) return { kind, action: "none" }; + ref = kind === "pr_comment" ? await taskForCheck(db, project, null, issue.number) : await taskByIssue(db, project, issue.number); + text = + kind === "pr_comment" + ? `💬 ${sender} в PR #${issue.number}${comment.html_url ? ` (${comment.html_url})` : ""}:\n\n${body}\n\nЭто замечание к стори: исправь и запушь в ту же ветку (или ответь, почему не нужно).` + : `💬 ${sender} в issue #${issue.number}:\n\n${body}`; + } + if (!ref || !ACTIVE.includes(ref.task.status)) return { kind, task: ref?.key ?? null, action: "none" }; + if (!(await giteaLoginHasAccess(db, project, sender))) return { kind, task: ref.key, action: "no_access" }; + const out = await toAgent(db, ref, text, kind !== "issue_comment"); + await logProjectEvent(db, project, "gitea_comment", { from: sender, kind, delivered: out }, ref.task.id); + return { kind, task: ref.key, action: out }; + } + return { kind, action: "none" }; +} diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts index aeaf5104..7e3388ce 100644 --- a/packages/runner/src/hook.ts +++ b/packages/runner/src/hook.ts @@ -15,6 +15,8 @@ import { latestReview, pendingReview, reviewNote, + reviewPreview, + reviewPreviewNote, reviewRejections, getSession, logSessionEvent, @@ -26,7 +28,7 @@ import { type Question, type SessionView, } from "@peppa/core"; -import { createDb, tasks, type Db } from "@peppa/db"; +import { createDb, projects, tasks, type Db } from "@peppa/db"; import { eq } from "drizzle-orm"; import { peppaHome } from "@peppa/shared"; import { HOOK_WAIT_SEC, MAX_AUTO_NUDGES } from "./run-settings.ts"; @@ -204,7 +206,10 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: // PEP-26: what the reviewer agent said (approved, findings left after the limit, failed). const settings = await getReviewSettings(db, task.projectId); const note = settings.enabled ? reviewNote(await latestReview(db, task.id), (await reviewRejections(db, task.id)) >= settings.maxIterations) : ""; - await raiseSessionQuestion(db, s, "attention", clip(`✅ Стори ${s.taskKey} готова к ревью${task.prUrl ? ` · PR: ${task.prUrl}` : ""}\n\n${note ? `${note}\n\n` : ""}${text ?? ""}`.trim())); + // PEP-44: the preview stand, the diff and the checks — the PM reviews without a terminal. + const [project] = await db.select().from(projects).where(eq(projects.id, task.projectId)); + const look = project ? reviewPreviewNote(await reviewPreview(db, { project, task, key: s.taskKey ?? "" }).catch(() => ({ previewUrl: null, releaseId: null, sha: null, diffUrl: null, checks: "", screenshots: [], issueUrl: null }))) : ""; + await raiseSessionQuestion(db, s, "attention", clip(`✅ Стори ${s.taskKey} готова к ревью${task.prUrl ? ` · PR: ${task.prUrl}` : ""}\n\n${look ? `${look}\n\n` : ""}${note ? `${note}\n\n` : ""}${text ?? ""}`.trim())); await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() }); return null; } diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 361dd829..3d6ab1fd 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -25,3 +25,4 @@ export * from "./autonomy.ts"; export * from "./workspace-sync.ts"; export * from "./rotation.ts"; export * from "./live.ts"; +export * from "./gitea-events.ts"; diff --git a/packages/runner/src/reviewer.ts b/packages/runner/src/reviewer.ts index 4ef8f12e..c12cc2f4 100644 --- a/packages/runner/src/reviewer.ts +++ b/packages/runner/src/reviewer.ts @@ -16,6 +16,8 @@ import { raiseSessionQuestion, resolveTask, reviewNote, + reviewPreview, + reviewPreviewNote, reviewRejections, reviewsToRun, taskPrNumber, @@ -208,7 +210,8 @@ export async function processReview(db: Db, id: number, gitea: GiteaClient = git } await updateTask(db, fresh, { status: "review" }); - const msg = `✅ Стори ${fresh.key} готова к ревью${fresh.task.prUrl ? ` · PR: ${fresh.task.prUrl}` : ""}\n\n${reviewNote(review)}`.slice(0, 3500); + const look = reviewPreviewNote(await reviewPreview(db, fresh)); + const msg = `✅ Стори ${fresh.key} готова к ревью${fresh.task.prUrl ? ` · PR: ${fresh.task.prUrl}` : ""}\n\n${look ? `${look}\n\n` : ""}${reviewNote(review)}`.slice(0, 3500); const [s] = sessionId ? await listSessions(db, { active: true, taskId: fresh.task.id }) : []; // Still in the turn that asked for review: its Stop hook sends "ready for review" with this // note (OpenCode has no turn hooks — it gets the message now). diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts index c89a733b..0a5c8877 100644 --- a/packages/shared/src/env.ts +++ b/packages/shared/src/env.ts @@ -9,6 +9,8 @@ const schema = z.object({ GITEA_URL: z.string().url().default("https://git.telecom.quest"), GITEA_TOKEN: z.string().optional(), GITEA_TEMPLATE_REPO: z.string().default("peppa-bot/template"), + // PEP-46: Peppa's own Gitea account — its comments in PRs/issues never go back to agents. + GITEA_BOT_LOGIN: z.string().default("peppa-bot"), PEPPA_WORKSPACES: z.string().default("~/peppa/workspaces"), TELEGRAM_BOT_TOKEN: z.string().optional(), TELEGRAM_PM_CHAT_ID: z.string().optional(), diff --git a/packages/testkit/bin/mock-docker b/packages/testkit/bin/mock-docker index 0a37532d..eef55e1b 100755 --- a/packages/testkit/bin/mock-docker +++ b/packages/testkit/bin/mock-docker @@ -2,7 +2,7 @@ # mock-docker — stands in for the docker CLI in .gitea/peppa-deploy.sh tests (first on PATH). # Same calls and exit codes as the script uses from real docker; state lives in # $MOCK_DOCKER_STATE: images (one tag per line), containers/ (its image), calls.log. -# MOCK_DOCKER_BUILD_FAIL=1 makes `docker build` fail. +# MOCK_DOCKER_BUILD_FAIL=1 makes `docker build` fail; MOCK_DOCKER_SCREENSHOT_FAIL=1 — `docker run` (screenshot). set -uo pipefail st="${MOCK_DOCKER_STATE:?MOCK_DOCKER_STATE is required}" mkdir -p "$st/containers" @@ -31,5 +31,11 @@ case "$1" in down) rm -f "$st/containers/$project-"*; echo "Removed $project" ;; run) echo "ran in $IMAGE: ${*: -1}" ;; esac ;; + run) # PEP-44: docker run … -c '' _ → base64 PNG on stdout + url="${@: -1}" + echo "$url" >> "$st/screenshots.log" + [[ -n "${MOCK_DOCKER_SCREENSHOT_FAIL:-}" ]] && { echo "mock screenshot failed" >&2; exit 1; } + # 1x1 transparent PNG + printf '%s' 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=' ;; *) echo "mock-docker: unsupported: $*" >&2; exit 1 ;; esac diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index 112c52b6..acdc608c 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -22,6 +22,17 @@ interface MockRepo { secrets: Record; hooks: Array<{ id: number; url: string; secret: string; events: string[] }>; tags: Array<{ name: string; target: string }>; + issues: MockIssue[]; +} + +/** PEP-46: an issue with its comments (by login). */ +export interface MockIssue { + number: number; + title: string; + body: string; + state: "open" | "closed"; + author: string; + comments: Array<{ body: string; author: string }>; } export interface MockPull { @@ -116,6 +127,7 @@ export class MockGitea { secrets: {}, hooks: [], tags: [], + issues: [], private: opts.private ?? true, }; this.repos.set(`${owner}/${name}`, repo); @@ -173,6 +185,18 @@ export class MockGitea { return pr; } + /** An issue opened by `author` (numbers start at 100: apart from PR numbers). */ + addIssue(owner: string, name: string, title: string, author: string, body = ""): MockIssue { + const r = this.repo(owner, name); + const i: MockIssue = { number: 100 + r.issues.length, title, body, state: "open", author, comments: [] }; + r.issues.push(i); + return i; + } + + issueJson(r: MockRepo, i: MockIssue) { + return { number: i.number, title: i.title, body: i.body, state: i.state, html_url: `${this.url}/${r.owner}/${r.name}/issues/${i.number}`, user: { login: i.author } }; + } + /** Records a commit status, like a CI job does. */ setStatus(owner: string, name: string, sha: string, context: string, status: string, extra: { target_url?: string; description?: string } = {}) { const r = this.repo(owner, name); @@ -433,6 +457,29 @@ export class MockGitea { return { status: 404, body: { message: "not found" } }; } } + if (method === "GET" && sub === "issues") { + const page = Number(q.get("page") ?? 1); + const limit = Number(q.get("limit") ?? 30); + const list = r.issues.filter((i) => (q.get("state") ?? "open") === "all" || i.state === (q.get("state") ?? "open")); + return { status: 200, body: list.slice((page - 1) * limit, page * limit).map((i) => this.issueJson(r, i)) }; + } + if ((m = sub.match(/^issues\/(\d+)(\/comments)?$/))) { + const n = Number(m[1]); + const i = r.issues.find((x) => x.number === n); + const isPull = r.pulls.some((p) => p.number === n); + if (!i && !isPull) return { status: 404, body: { message: "issue not found" } }; + if (method === "POST" && m[2]) { + const c = { body: String(body.body), author: me.login }; + if (i) i.comments.push(c); + return { status: 201, body: { id: this.seq++, body: c.body, user: { login: me.login } } }; + } + if (method === "PATCH" && !m[2] && i) { + if (!canWrite) return { status: 403, body: { message: "forbidden" } }; + if (body.state === "closed" || body.state === "open") i.state = body.state; + return { status: 201, body: this.issueJson(r, i) }; + } + if (method === "GET" && !m[2] && i) return { status: 200, body: this.issueJson(r, i) }; + } if (method === "POST" && sub === "tags") { if (!canWrite) return { status: 403, body: { message: "forbidden" } }; const target = this.sha(r.owner, r.name, String(body.target)); diff --git a/packages/testkit/test/deploy.test.ts b/packages/testkit/test/deploy.test.ts index 4b4edc3f..71d0d69e 100644 --- a/packages/testkit/test/deploy.test.ts +++ b/packages/testkit/test/deploy.test.ts @@ -239,3 +239,69 @@ describe("Проверка здоровья и откат", () => { assert.equal((await releases(d.proj.id)).at(-1)!.reason, "сборка образа не удалась"); }); }); + +// PEP-44, spec delivery-pipeline: «Превью на ревью». +describe("Превью на ревью", () => { + async function storyWithPr(d: Awaited>, pr: number) { + const ref = await core.resolveTask(db, d.p.taskKey); + await core.updateTask(db, ref, { prUrl: `${gitea.url}/${d.proj.giteaOwner}/${d.proj.giteaRepo}/pulls/${pr}` }); + return core.resolveTask(db, d.p.taskKey); + } + + test("Scenario: Стенд поднят — ссылка «Посмотреть», дифф и проверки; Scenario: Скриншоты — снимок в карточке", async () => { + const d = await deployable(); + const ref = await storyWithPr(d, 3); + const sha = d.merge(`${d.p.key}-1`); + const r = await d.run("preview", sha, { PEPPA_PR: "3" }); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /скриншот \/ снят/); + const [rel] = await releases(d.proj.id); + assert.equal(rel!.status, "healthy"); + assert.equal(rel!.screenshots.length, 1); + assert.equal(rel!.screenshots[0]!.path, "/"); + const shot = await runner.releaseScreenshot(db, rel!.id, 0); + assert.ok(shot && shot.png.subarray(1, 4).toString() === "PNG", "a PNG is kept"); + assert.equal(shot!.projectId, d.proj.id); + assert.equal(await runner.releaseScreenshot(db, rel!.id, 5), null); + + const p = await core.reviewPreview(db, ref); + assert.equal(p.previewUrl, `https://${d.proj.slug}-pr3.telecom.quest`); + assert.equal(p.releaseId, rel!.id); + assert.deepEqual(p.screenshots, [{ n: 0, path: "/" }]); + assert.match(p.diffUrl!, /\/pulls\/3\/files$/); + const note = core.reviewPreviewNote(p); + assert.match(note, new RegExp(`Посмотреть: https://${d.proj.slug}-pr3\\.telecom\\.quest`)); + assert.match(note, /Дифф: .*\/pulls\/3\/files/); + assert.match(note, /Проверки/); + // The card (getTaskDetails) carries the same summary. + assert.equal((await core.getTaskDetails(db, ref)).preview.previewUrl, p.previewUrl); + }); + + test("Scenario: Скриншоты не сняты — превью здоровое, ссылка без скриншотов", async () => { + const d = await deployable(); + const ref = await storyWithPr(d, 4); + const r = await d.run("preview", d.merge(`${d.p.key}-1`), { PEPPA_PR: "4", MOCK_DOCKER_SCREENSHOT_FAIL: "1" }); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /скриншот \/ не снят/); + const [rel] = await releases(d.proj.id); + assert.equal(rel!.status, "healthy"); + assert.deepEqual(rel!.screenshots, []); + const p = await core.reviewPreview(db, ref); + assert.ok(p.previewUrl); + assert.deepEqual(p.screenshots, []); + }); + + test("screenshots are opt-out (deploy.screenshots: []) and only for previews; junk is not stored", async () => { + const d = await deployable({ compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz", screenshots: [] }); + const sha = d.merge(`${d.p.key}-1`); + assert.equal((await d.run("preview", sha, { PEPPA_PR: "5" })).code, 0); + assert.equal((await d.run("staging", sha)).code, 0); + assert.ok(!d.calls().includes("docker run"), "no screenshot container started"); + const [rel] = (await releases(d.proj.id)).filter((x) => x.env === "preview"); + const out = await runner.recordScreenshots(db, d.proj, { sha, prNumber: 5, shots: [{ path: "/", png: Buffer.from("not a png").toString("base64") }] }); + assert.deepEqual(out, { release: rel!.id, saved: 0 }); + // Unsigned report is refused. + const bad = await runner.handleGiteaHook(db, { event: "screenshots", signature: "x", body: JSON.stringify({ repository: `${d.proj.giteaOwner}/${d.proj.giteaRepo}`, sha, shots: [] }) }); + assert.equal(bad.status, 401); + }); +}); diff --git a/packages/testkit/test/gitea-events.test.ts b/packages/testkit/test/gitea-events.test.ts new file mode 100644 index 00000000..7735e55a --- /dev/null +++ b/packages/testkit/test/gitea-events.test.ts @@ -0,0 +1,190 @@ +// PEP-46, spec gitea-integration: «Issues становятся стори», «Комментарии в PR уходят агенту», +// «Мерж руками закрывает стори» — Gitea webhooks (signed like Gitea) against mock Gitea and +// mock-claude runners. +import assert from "node:assert/strict"; +import { createHmac } from "node:crypto"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, setDefaultOwner, teardown, type TestProject } from "./helpers.ts"; +import { MockGitea } from "../src/mock-gitea.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-gev-")), "gitea")); +const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" }; +let pm: Awaited>; + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + gitea.addUser(BOT); + pm = await core.upsertUserFromGitea(db, { id: 61, login: "mock-pm" }, { access_token: "x" }); + setDefaultOwner(pm.id); +}); +after(async () => { + await gitea.stop(); + await teardown(); +}); + +interface GitTask { + p: TestProject; + proj: Awaited>; + ref: () => ReturnType; + pr: number; + repo: string; + hook(event: string, payload: Record): ReturnType; +} + +/** Project (owned by mock-pm) with a repo in mock Gitea and a story with an open PR. */ +async function gitTask(turns: Parameters[0]["turns"] = []): Promise { + const p = await project({ turns }); + const proj = await core.getProject(db, p.key); + const pj = JSON.stringify({ slug: proj.slug, key: p.key, name: p.key, peppaUrl: "http://test" }); + writeFileSync(join(p.dir, ".peppa/project.json"), pj); + gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } }); + gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write"; + const branch = `task/${p.taskKey}`; + gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { "a.txt": "a" }); + const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch); + const ref = () => core.resolveTask(db, p.taskKey); + await core.updateTask(db, await ref(), { status: "in_progress", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` }); + const repo = `${proj.giteaOwner}/${proj.giteaRepo}`; + return { + p, + proj, + ref, + pr: pr.number, + repo, + hook(event, payload) { + const body = JSON.stringify({ repository: { full_name: repo }, ...payload }); + const signature = createHmac("sha256", core.projectHookSecret(proj.id)).update(body).digest("hex"); + return runner.handleGiteaHook(db, { event, signature, body }); + }, + }; +} + +const issuePayload = (t: GitTask, i: { number: number; title: string; body: string; author: string }, action = "opened") => ({ + action, + number: i.number, + issue: { number: i.number, title: i.title, body: i.body, html_url: `${gitea.url}/${t.repo}/issues/${i.number}`, user: { login: i.author } }, + sender: { login: i.author }, +}); + +const prComment = (t: GitTask, from: string, body: string) => ({ + action: "created", + is_pull: true, + issue: { number: t.pr, title: "PR", pull_request: { merged: false } }, + comment: { body, user: { login: from }, html_url: `${gitea.url}/${t.repo}/pulls/${t.pr}#issuecomment-1` }, + sender: { login: from }, +}); + +const action = (r: Awaited>) => (r.body as { action: string }).action; + +describe("Issues становятся стори", () => { + test("Scenario: Участник открыл issue — стори в бэклоге со ссылкой, комментарий в issue", async () => { + const t = await gitTask(); + const issue = gitea.addIssue(t.proj.giteaOwner, t.proj.giteaRepo, "Экспорт в CSV", "mock-pm", "Нужна кнопка"); + const r = await t.hook("issues", issuePayload(t, { ...issue, author: "mock-pm" })); + assert.equal(r.status, 200); + assert.equal(action(r), "imported"); + const key = (r.body as { task: string }).task; + const story = await core.resolveTask(db, key); + assert.equal(story.task.title, "Экспорт в CSV"); + assert.equal(story.task.status, "backlog"); + assert.equal(story.task.giteaIssue, issue.number); + assert.match(story.task.description!, /Нужна кнопка[\s\S]*issues\/100/); + assert.equal(issue.comments.length, 1); + assert.equal(issue.comments[0]!.author, BOT.login); + assert.match(issue.comments[0]!.body, new RegExp(`Стори ${key} в Пеппе: .*/t/${key}`)); + assert.match((await core.reviewPreview(db, story)).issueUrl!, /\/issues\/100$/); + // Redelivery (or "reopened") doesn't duplicate. + assert.equal(action(await t.hook("issues", issuePayload(t, { ...issue, author: "mock-pm" }, "reopened"))), "exists"); + assert.equal(issue.comments.length, 1); + }); + + test("Scenario: Чужой issue — стори не создаётся; бот и подделка подписи тоже", async () => { + const t = await gitTask(); + const before = (await core.listTasks(db, { projectId: t.proj.id })).length; + assert.equal(action(await t.hook("issues", issuePayload(t, { number: 100, title: "spam", body: "", author: "random-user" }))), "no_access"); + assert.equal(action(await t.hook("issues", issuePayload(t, { number: 101, title: "bot", body: "", author: BOT.login }))), "none"); + const forged = await runner.handleGiteaHook(db, { event: "issues", signature: "deadbeef", body: JSON.stringify({ repository: { full_name: t.repo }, ...issuePayload(t, { number: 102, title: "x", body: "", author: "mock-pm" }) }) }); + assert.equal(forged.status, 401); + assert.equal((await core.listTasks(db, { projectId: t.proj.id })).length, before); + }); + + test("Scenario: Стори готова — issue закрыт с комментарием; разовый импорт открытых issues", async () => { + const t = await gitTask(); + const a = gitea.addIssue(t.proj.giteaOwner, t.proj.giteaRepo, "Старый баг", "someone"); + const b = gitea.addIssue(t.proj.giteaOwner, t.proj.giteaRepo, "Ещё один", "mock-pm"); + const out = await runner.importIssues(db, t.proj); + assert.deepEqual(out.map((x) => x.created), [true, true]); + assert.deepEqual((await runner.importIssues(db, t.proj)).map((x) => x.created), [false, false]); + const story = await core.resolveTask(db, out[0]!.key); + await runner.moveTask(db, story, "done"); + assert.equal(a.state, "closed"); + assert.match(a.comments.at(-1)!.body, new RegExp(`Стори ${out[0]!.key} готова`)); + assert.equal(b.state, "open"); + }); +}); + +describe("Комментарии в PR уходят агенту", () => { + test("Scenario: Комментарий в PR — агент получает текст, стори снова в работе", async () => { + const t = await gitTask([[{ say: "PR открыт" }], [{ say: "исправляю" }]]); + const id = await t.p.start(); + await t.p.waitLog("agent started", (e) => e.ev === "prompt"); + await core.updateTask(db, await t.ref(), { status: "review" }); + const r = await t.hook("issue_comment", prComment(t, "mock-pm", "Переименуй кнопку")); + assert.equal(action(r), "agent"); + await t.p.waitLog("comment delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("Переименуй кнопку") && String(e.prompt).includes("mock-pm")); + assert.equal((await t.ref()).task.status, "in_progress"); + await runner.stopSession(db, id); + }); + + test("review «changes requested» with no live runner starts the agent; approval is ignored", async () => { + const t = await gitTask([[{ say: "чиню" }]]); + await core.updateTask(db, await t.ref(), { status: "review" }); + const pull = { number: t.pr, merged: false, html_url: `${gitea.url}/${t.repo}/pulls/${t.pr}`, head: { ref: `task/${t.p.taskKey}` } }; + assert.equal(action(await t.hook("pull_request_approved", { action: "reviewed", pull_request: pull, review: { type: "pull_request_review_approved", content: "LGTM" }, sender: { login: "mock-pm" } })), "none"); + assert.equal((await t.ref()).task.status, "review"); + const r = await t.hook("pull_request_rejected", { action: "reviewed", pull_request: pull, review: { type: "pull_request_review_rejected", content: "Нет тестов" }, sender: { login: "mock-pm" } }); + assert.equal(action(r), "restarted"); + await t.p.waitLog("review delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("Нет тестов") && String(e.prompt).includes("просит изменений")); + assert.equal((await t.ref()).task.status, "in_progress"); + for (const s of await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })) await runner.stopSession(db, s.id); + }); + + test("Scenario: Комментарий бота — агенту ничего; чужой комментатор тоже", async () => { + const t = await gitTask(); + await core.updateTask(db, await t.ref(), { status: "review" }); + assert.equal(action(await t.hook("issue_comment", prComment(t, BOT.login, "Стори готова"))), "none"); + assert.equal(action(await t.hook("issue_comment", prComment(t, "random-user", "сделай мне ещё"))), "no_access"); + assert.equal((await t.ref()).task.status, "review"); + assert.equal((await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })).length, 0); + }); +}); + +describe("Мерж руками закрывает стори", () => { + test("Scenario: PM смержил PR в Gitea — стори «Готово», «готово к ревью» закрыто", async () => { + const t = await gitTask(); + const ref = await t.ref(); + await core.updateTask(db, ref, { status: "review" }); + const q = await core.askPm(db, ref, { kind: "attention", text: `✅ Стори ${ref.key} готова к ревью` }); + const pull = { number: t.pr, merged: true, html_url: `${gitea.url}/${t.repo}/pulls/${t.pr}`, head: { ref: `task/${t.p.taskKey}` } }; + assert.equal(action(await t.hook("pull_request", { action: "closed", number: t.pr, pull_request: { ...pull, merged: false }, sender: { login: "mock-pm" } })), "none"); + assert.equal((await t.ref()).task.status, "review"); + const r = await t.hook("pull_request", { action: "closed", number: t.pr, pull_request: pull, sender: { login: "mock-pm" } }); + assert.equal(action(r), "done"); + assert.equal((await t.ref()).task.status, "done"); + const closed = await core.getQuestion(db, q.id); + assert.ok(closed.answeredAt); + assert.match(closed.answer!, /смержен в Gitea/); + // A redelivery does nothing. + assert.equal(action(await t.hook("pull_request", { action: "closed", number: t.pr, pull_request: pull, sender: { login: "mock-pm" } })), "none"); + }); + + test("the project webhook subscribes to issues, comments and reviews", () => { + for (const e of ["issues", "issue_comment", "pull_request_comment", "pull_request_review", "pull_request", "push"]) assert.ok(runner.GITEA_HOOK_EVENTS.includes(e), e); + }); +}); diff --git a/template/.gitea/peppa-deploy.sh b/template/.gitea/peppa-deploy.sh index 98eabe51..2586968f 100644 --- a/template/.gitea/peppa-deploy.sh +++ b/template/.gitea/peppa-deploy.sh @@ -83,6 +83,39 @@ healthy() { return 1 } +# PEP-44: скриншоты превью для ревью PM. Headless Chromium в контейнере в сети Traefik +# (job сам в контейнере — PNG идёт через stdout в base64, без томов). Страницы — +# deploy.screenshots (по умолчанию ["/"], [] — выключить). Сбой не валит деплой. +screenshots() { + local peppa_url paths shots=() p url png body sig file + peppa_url=$(jq -r '.peppaUrl // empty' "$cfg") + [[ -n "$peppa_url" && -n "${PEPPA_CI_SECRET:-}" ]] || return 0 + paths=() + while IFS= read -r p; do [[ -n "$p" ]] && paths+=("$p"); done < <(jq -r '(.deploy.screenshots // ["/"])[:6][]' "$cfg" 2>/dev/null) + ((${#paths[@]})) || return 0 + local limit=() + command -v timeout >/dev/null && limit=(timeout "${PEPPA_SCREENSHOT_TIMEOUT:-90}") + local base="${PEPPA_SCREENSHOT_BASE:-${PEPPA_HEALTH_BASE:-http://$container:$port}}" + base="${base//\{project\}/$project}" + file=$(mktemp) + echo '[]' > "$file" + for p in "${paths[@]}"; do + url="$base$p" + png=$(${limit[@]+"${limit[@]}"} docker run --rm --network "${PEPPA_SCREENSHOT_NETWORK:-traefik_default}" --entrypoint sh \ + "${PEPPA_SCREENSHOT_IMAGE:-zenika/alpine-chrome:124}" -c \ + 'chromium-browser --headless --no-sandbox --disable-gpu --hide-scrollbars --window-size=1280,800 --virtual-time-budget=5000 --screenshot=/tmp/s.png "$1" >/dev/null 2>&1 && base64 /tmp/s.png | tr -d "\n"' _ "$url" 2>/dev/null) || png="" + if [[ -z "$png" ]]; then echo "peppa: скриншот $p не снят"; continue; fi + jq --arg path "$p" --rawfile png <(printf '%s' "$png") '. + [{path:$path, png:$png}]' "$file" > "$file.n" && mv "$file.n" "$file" + echo "peppa: скриншот $p снят" + done + [[ $(jq length "$file") -gt 0 ]] || return 0 + body=$(jq -c --arg repo "${GITHUB_REPOSITORY:-}" --arg sha "$sha" --arg pr "$pr" '{repository:$repo, sha:$sha, pr:($pr|tonumber? // null), shots:.}' "$file") + sig=$(printf '%s' "$body" | openssl dgst -sha256 -hmac "$PEPPA_CI_SECRET" | awk '{print $NF}') + printf '%s' "$body" | curl -fsS -o /dev/null -m 60 -X POST "$peppa_url/api/hooks/gitea" -H "Content-Type: application/json" \ + -H "X-Peppa-Event: screenshots" -H "X-Gitea-Signature: $sig" --data-binary @- || echo "peppa: скриншоты не отправлены" + rm -f "$file" +} + if [[ $mode == preview-down ]]; then dc "$image" down --remove-orphans || true report removed @@ -99,6 +132,7 @@ fi dc "$image" up -d --remove-orphans || { report failed "docker compose up не удался"; exit 1; } if healthy; then report healthy + [[ $env_name == preview ]] && screenshots docker image prune -af --filter "label=peppa.project=$slug" --filter "until=336h" >/dev/null 2>&1 || true exit 0 fi -- 2.45.2 From db822a570cd994a812d2c5317b25db27ac9668e8 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 06:00:38 +0500 Subject: [PATCH 002/463] PEP-45: stories from a Telegram message (text or voice); docs; archive PEP-44/45/46 changes Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- apps/bot/src/bot.ts | 163 +++++++++++++++++- apps/bot/src/drafts.ts | 74 ++++++++ apps/bot/src/telegram.ts | 20 +++ apps/bot/src/transcribe.ts | 52 ++++++ apps/web/app/(app)/help/page.tsx | 15 ++ .../proposal.md | 0 .../specs/delivery-pipeline/spec.md | 0 .../2026-11-14-pep-44-review-preview/tasks.md | 8 + .../2026-11-14-pep-45-bot-story}/proposal.md | 0 .../specs/telegram-notifications/spec.md | 0 .../2026-11-14-pep-45-bot-story/tasks.md | 6 + .../design.md | 0 .../proposal.md | 0 .../specs/gitea-integration/spec.md | 0 .../tasks.md | 12 +- .../changes/pep-44-review-preview/tasks.md | 8 - openspec/changes/pep-45-bot-story/tasks.md | 6 - openspec/specs/delivery-pipeline/spec.md | 17 ++ openspec/specs/gitea-integration/spec.md | 46 +++++ openspec/specs/telegram-notifications/spec.md | 27 +++ packages/testkit/src/mock-telegram.ts | 27 +++ packages/testkit/src/mock-transcribe.ts | 51 ++++++ packages/testkit/test/bot.test.ts | 114 ++++++++++++ 24 files changed, 624 insertions(+), 26 deletions(-) create mode 100644 apps/bot/src/drafts.ts create mode 100644 apps/bot/src/transcribe.ts rename openspec/changes/{pep-44-review-preview => archive/2026-11-14-pep-44-review-preview}/proposal.md (100%) rename openspec/changes/{pep-44-review-preview => archive/2026-11-14-pep-44-review-preview}/specs/delivery-pipeline/spec.md (100%) create mode 100644 openspec/changes/archive/2026-11-14-pep-44-review-preview/tasks.md rename openspec/changes/{pep-45-bot-story => archive/2026-11-14-pep-45-bot-story}/proposal.md (100%) rename openspec/changes/{pep-45-bot-story => archive/2026-11-14-pep-45-bot-story}/specs/telegram-notifications/spec.md (100%) create mode 100644 openspec/changes/archive/2026-11-14-pep-45-bot-story/tasks.md rename openspec/changes/{pep-46-gitea-integration => archive/2026-11-14-pep-46-gitea-integration}/design.md (100%) rename openspec/changes/{pep-46-gitea-integration => archive/2026-11-14-pep-46-gitea-integration}/proposal.md (100%) rename openspec/changes/{pep-46-gitea-integration => archive/2026-11-14-pep-46-gitea-integration}/specs/gitea-integration/spec.md (100%) rename openspec/changes/{pep-46-gitea-integration => archive/2026-11-14-pep-46-gitea-integration}/tasks.md (52%) delete mode 100644 openspec/changes/pep-44-review-preview/tasks.md delete mode 100644 openspec/changes/pep-45-bot-story/tasks.md create mode 100644 openspec/specs/gitea-integration/spec.md create mode 100644 packages/testkit/src/mock-transcribe.ts diff --git a/AGENTS.md b/AGENTS.md index 5fb61cbf..36872b68 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ ## Структура - `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Подписки (только суперадмин) · Помощь; проект как в GitHub (PEP-66): вкладки Доска (фильтр `?epic=`) · Код (`repoOverview`: README, ветки, коммиты из Gitea, кэш минута) · Спеки (`listSpecs`, `openspec/specs` рабочей копии) · PR (`openPulls` + `taskCiSummary`) · Релизы · Баги · Сессии (`?tab=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (PEP-32): шапка (статус, эпик, прогресс tasks.md, «Изменить» — название/описание/эпик, агент и живая сессия с терминалом и лентой шагов) и вкладки `?tab=` Proposal · Design (свой безопасный рендер `components/Markdown.tsx`) · Specs (дельта-спеки change) · Tasks · Comments (вопросы + комментарии PM: событие `pm_comment`, агент видит в `get_task`, флажок «Отправить агенту сейчас») · Tests · Merge request («Принять и смержить» = `acceptStory` в runner/flow.ts) · Activity (с авторами: `payload.login` / сессия / система); change читает `core/openspec.ts` (`readChange`, `parseTasks`, `taskProgress`, и архивный); новый проект. **Живые страницы (PEP-37)**: `LiveRefresh` (вместо `AutoRefresh`, он остался только у подписок) слушает SSE `GET /api/live?scope=home|runners|project:|task:|steps:` и делает `router.refresh()` (ждёт, пока пользователь печатает), индикатор связи, откат на опрос 5 с; хаб `runner/live.ts` (`globalThis`) будят `notify()` (подписчик `web`, сокет `$PEPPA_HOME/web.events.sock`) и `PRAGMA data_version` + `total_changes()` раз в секунду, отпечаток области — один SQL без `last_activity_at`/шагов; заголовки `no-cache, no-transform`, `X-Accel-Buffering: no`, пинг 15 с **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один OpenSpec change; «задачи» — пункты tasks.md), цели — «эпики» (метки стори; хранятся в таблице `goals`, `tasks.goal_id`; MCP `*_epic(s)`/`epic_id`, `*_goal(s)`/`goal_id` — алиасы); имена MCP-инструментов и кода (`create_task`, `tasks`) не меняем. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже) -- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта +- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта. **Стори из сообщения (PEP-45)**: любой другой текст привязанного пользователя — черновик (`apps/bot/src/drafts.ts`, `settings` `bot.draft:`, сутки): префикс `KEY:`/`в KEY:` (только свои проекты) или кнопки проекта → кнопки эпика/«Создать» → `createTask` → «▶️ Взять в работу» (`moveTask`); кнопки `d::p|g|x`, `t::start|keep`. Голос: `getFile` → `transcribe.ts` — OpenAI-совместимый `POST $PEPPA_TRANSCRIBE_URL/audio/transcriptions` (`PEPPA_TRANSCRIBE_KEY`, `_MODEL`=whisper-1, `_LANG`=ru); без env — просит текстом. Моки: `mock-transcribe`, голос и `/file/` в `mock-telegram` - `packages/db` — Drizzle-схема и клиент: **SQLite** (`node:sqlite`, WAL) в файле `PEPPA_DB` (по умолчанию `~/.peppa/peppa.db`); каждый процесс открывает файл сам (`busy_timeout` первой командой, `BEGIN IMMEDIATE`). Прослойка `src/client.ts` даёт сессии drizzle `better-sqlite3` API `node:sqlite`. **Транзакции только синхронные** (`db.transaction((tx) => …)` без `await`; async-колбэк драйвер отклоняет). JSON-поля — `json_extract`/`json_each`, не `->>`/`@>`. Миграции — `drizzle-kit generate` (`packages/db/migrations`, база 0000), применение — `peppa db migrate` (PEP-36) - `packages/shared` — env, ключи задач (`PEP-42`) - `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM); живые обновления — `notify()` будит подписчика (бота) через unix-сокет `$PEPPA_HOME/bot.events.sock`, бот вдобавок раз в секунду смотрит `PRAGMA data_version`; ежедневная копия базы (`backupDb`, `VACUUM INTO`, `~/.peppa/backups`, 7 штук) из вачдога; всё ходит через неё @@ -36,6 +36,8 @@ - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) - Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью) + - **Gitea → Пеппа (PEP-46)**: вебхук подписан на `GITEA_HOOK_EVENTS` (+ issues, issue_comment, pull_request_comment, pull_request_review; обновить у существующих — `peppa ci connect `); `handleGiteaEvent` (runner/gitea-events.ts) определяет событие по форме payload (Gitea 1.22 зовёт и ревью, и комментарий `pull_request_comment`). Issue от владельца/участника (логин Gitea, `users.gitea_id > 0`) → стори в бэклоге (`tasks.gitea_issue`, идемпотентно) + комментарий-ссылка от peppa-bot; чужие игнор; `moveTask(done)` закрывает issue; разовый импорт `peppa project import-issues ` (без проверки автора). Комментарий/ревью «нужны изменения» в PR стори → агенту (живой раннер или новый, из «Ревью» — в работу); одобрения и `GITEA_BOT_LOGIN` (peppa-bot) — игнор. PR смержен руками → стори done, «готово к ревью» закрыт (`acceptTask` терпит гонку с вебхуком) + - **Превью на ревью (PEP-44)**: `reviewPreview` (core/preview.ts) — здоровый превью-стенд PR стори из `releases`, дифф `/files`, итог проверок, скриншоты, issue; в «готово к ревью» (Stop-хук, ревьюер), карточке (`components/ReviewPreview.tsx`) и `get_task`. Скриншоты снимает `peppa-deploy.sh preview` (headless Chromium в контейнере `PEPPA_SCREENSHOT_IMAGE`, сеть Traefik, base64 через stdout; страницы `deploy.screenshots`, по умолчанию `["/"]`) → `X-Peppa-Event: screenshots` → `recordScreenshots` (`$PEPPA_HOME/screenshots//`, ≤6×3 МБ, PNG) → `releases.screenshots`; веб `/api/releases//shots/` (владелец/участник) - Гейты (`prGate` в core/ci.ts): в ревью (`moveTask`, MCP `update_task`) и «Принять» (`acceptTask` → `mergeTaskPr`, мержит PR) — только зелёные проверки головного SHA PR и без конфликтов; без PR или без `checks` гейт открыт. `autoMergeTask` (для авто-режима PEP-23/25) не мержит PR, меняющий `.gitea/` или `checks`/`deploy`, и задаёт PM вопрос. Карточка задачи и MCP `get_task` показывают `taskCiSummary` («Проверки: 4 из 4 пройдены») - **Агент-ревьюер (PEP-26)**: настройка проекта `review_settings` (вкл/выкл, по умолчанию выкл; `max_iterations` = 2; `rules` PM) — веб «⋯ Настройки проекта → Ревьюер». Агент зовёт MCP `update_task(status: review)`, гейт PEP-57 пройден → `requestReview` (runner/reviewer.ts): ставит `code_reviews` (queued, головной SHA PR) и сразу запускает в процессе MCP, агенту — «закончи ход» (стори остаётся `in_progress`; Stop-хук не подгоняет, пока `pendingReview`). Ревью: дифф `GiteaClient.pullDiff` → `$PEPPA_REVIEW_BIN -p --output-format json --model ${PEPPA_REVIEW_MODEL:-sonnet}` (общий запуск `runner/claude-print.ts`, токен пула проекта, как триаж). `changes` → замечания агенту (`sendToSession` или новый раннер), `ok`/ошибка → стори в `review` и «готово к ревью» с резюме (если ход агента ещё идёт — его шлёт Stop-хук с той же заметкой `reviewNote`). Тот же одобренный SHA не ревьюится повторно; после `max_iterations` возвратов — к PM с последними замечаниями. Зависшие/непринятые — `reviewTick` в вачдоге (раз в минуту). Карточка и `get_task` — последнее ревью. PM, двигающий карточку сам, ревьюера не зовёт. Мок `mock-reviewer` (`MOCK_REVIEW_SCENARIO`) - **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/:` на docker хоста, `docker compose -p -`, хосты `-pr` / `-staging` / `-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index e4c85b05..8181a1eb 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -34,16 +34,26 @@ import { questionByTelegramMessage, setOffset, setSetting, + createTask, + getGoal, + listGoals, + listUserProjects, + type Project, type OutboxRow, type Question, type SessionView, } from "@peppa/core"; import { projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; -import { acceptTask, answerAndDeliver, decideIncident, resumeSession, stopSession } from "@peppa/runner"; -import { eq } from "drizzle-orm"; +import { acceptTask, answerAndDeliver, decideIncident, moveTask, resumeSession, stopSession } from "@peppa/runner"; +import { eq, sql } from "drizzle-orm"; import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts"; -import { TelegramApi, TelegramError, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts"; +import { TelegramApi, TelegramError, type InlineButton, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts"; +import { dropDraft, loadDraft, parseStoryText, saveDraft, splitStory, updateDraft, type Draft } from "./drafts.ts"; +import { transcribe, transcribeConfig, TranscribeError } from "./transcribe.ts"; + +/** Longest voice note the bot transcribes (seconds). */ +const VOICE_MAX_SEC = 5 * 60; export interface BotOptions { db: Db; @@ -65,6 +75,7 @@ const HELP = `Я бот Пеппы. Присылаю вопросы от аге • Кнопки под сообщением — быстрый ответ. • Ответ реплаем на сообщение — свой текст, он уйдёт прямо в сессию. +• Просто напиши (или наговори голосом) задачу — я заведу стори: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу. • /status — активные сессии и открытые вопросы. • /digest — сводка за сутки по твоим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`; @@ -231,6 +242,133 @@ export function createBot(o: BotOptions) { return lines.join("\n"); } + // ── stories from messages (PEP-45) ───────────────────────────────────────────── + const cancelRow = (d: Draft): InlineButton[] => [{ text: "✖️ Отмена", callback_data: `d:${d.id}:x` }]; + const rows = (buttons: InlineButton[], per = 2) => buttons.reduce((acc, b, i) => (i % per ? acc[acc.length - 1]!.push(b) : acc.push([b]), acc), []); + const storyLine = (d: Draft) => `«${esc(splitStory(d.text).title)}»`; + + /** Send (or, for a button press, edit in place) a bot message with buttons. */ + async function show(chatId: number, text: string, buttons: InlineButton[][], editId?: number) { + const params = { chat_id: chatId, text, parse_mode: "HTML", reply_markup: { inline_keyboard: buttons }, link_preview_options: { is_disabled: true } }; + if (editId) await api.call("editMessageText", { ...params, message_id: editId }).catch((e) => log(`edit: ${(e as Error).message}`)); + else await api.call("sendMessage", params).catch((e) => log(`send: ${(e as Error).message}`)); + } + + async function askProject(d: Draft, projects: Project[], editId?: number) { + // Most recently active first (the latest story touched), then newest projects. + const touched = new Map(); + for (const r of await db.select({ projectId: tasks.projectId, at: sql`max(${tasks.updatedAt})` }).from(tasks).groupBy(tasks.projectId)) touched.set(r.projectId, Number(r.at) || 0); + projects = [...projects].sort((a, b) => (touched.get(b.id) ?? 0) - (touched.get(a.id) ?? 0) || b.id - a.id); + const buttons = projects.slice(0, 12).map((p) => ({ text: p.key, callback_data: `d:${d.id}:p:${p.id}` })); + const more = projects.length > 12 ? "\nНет нужного — напиши заново с ключом: «KEY: …»." : ""; + await show(d.chatId, `📝 Новая стори ${storyLine(d)}\nВ какой проект?${more}`, [...rows(buttons, 3), cancelRow(d)], editId); + } + + async function askEpic(d: Draft, project: Project, editId?: number) { + const epics = (await listGoals(db, project.id)).slice(0, 10); + const buttons = epics.length + ? [...epics.map((g) => ({ text: g.title.slice(0, 40), callback_data: `d:${d.id}:g:${g.id}` })), { text: "Без эпика", callback_data: `d:${d.id}:g:0` }] + : [{ text: `✅ Создать в ${project.key}`, callback_data: `d:${d.id}:g:0` }]; + await show(d.chatId, `📝 Новая стори в ${esc(project.key)}: ${storyLine(d)}${epics.length ? "\nЭпик?" : ""}`, [...rows(buttons), cancelRow(d)], editId); + } + + /** A plain message (or a transcribed voice note) → a draft and the next question. */ + async function startStory(user: User, chatId: number, text: string, voice: boolean) { + const projects = await listUserProjects(db, user.id); + if (!projects.length) return reply(chatId, `У тебя пока нет проектов — создай первый: ${esc(o.webUrl)}/projects/new`); + const parsed = parseStoryText(text, projects); + if (!parsed.body) return reply(chatId, "Пустая стори — напиши, что сделать."); + const project = parsed.project ?? (projects.length === 1 ? projects[0]! : null); + const d = await saveDraft(db, { userId: user.id, chatId, text: parsed.body, projectId: project?.id ?? null, voice }); + if (project) await askEpic(d, project); + else await askProject(d, projects); + } + + async function onVoice(user: User, m: TgMessage) { + const f = m.voice ?? m.audio!; + const cfg = transcribeConfig(); + if (!cfg) return reply(m.chat.id, "Голосовые пока не настроены — напиши задачу текстом.", m.message_id); + if ((f.duration ?? 0) > VOICE_MAX_SEC) return reply(m.chat.id, `Слишком длинное голосовое (больше ${VOICE_MAX_SEC / 60} минут) — запиши короче или напиши текстом.`, m.message_id); + let text: string; + try { + const file = await api.getFile(f.file_id); + if (!file.file_path) throw new TranscribeError("Telegram не отдал файл"); + const audio = await api.downloadFile(file.file_path); + text = await transcribe(cfg, audio, file.file_path.split("/").pop() || "voice.ogg", f.mime_type ?? "audio/ogg"); + } catch (e) { + log(`voice: ${(e as Error).message}`); + return reply(m.chat.id, `Не получилось расшифровать голосовое (${esc((e as Error).message)}). Напиши текстом.`, m.message_id); + } + if (!text) return reply(m.chat.id, "Не разобрал ни слова — попробуй ещё раз или напиши текстом.", m.message_id); + await reply(m.chat.id, `🎙 Расслышал: «${esc(text)}»`, m.message_id); + await startStory(user, m.chat.id, text, true); + } + + /** Buttons of a draft (`d::p:` / `d::g:` / `d::x`) and of a new story (`t::start|keep`). */ + async function onStoryButton(user: User, c: TgCallbackQuery, parts: string[]): Promise { + const msgId = c.message?.message_id; + const chatId = c.message!.chat.id; + if (parts[0] === "t") { + const [t] = await db.select().from(tasks).where(eq(tasks.id, Number(parts[1]))); + if (!t || !(await canAccess(user, t.projectId))) return "Стори не найдена"; + const [project] = await db.select().from(projects).where(eq(projects.id, t.projectId)); + const ref = { project: project!, task: t, key: formatTaskKey(project!.key, t.number) }; + const head = `📥 ${esc(ref.key)}: ${esc(t.title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}`; + if (parts[2] === "keep") { + await show(chatId, `${head}\nВ бэклоге.`, [], msgId); + return "Оставил в бэклоге"; + } + if (parts[2] !== "start") return "Неизвестная кнопка"; + if (t.status !== "backlog") { + await show(chatId, `${head}\nУже не в бэклоге (${esc(t.status)}).`, [], msgId); + return `${ref.key} уже ${t.status}`; + } + try { + await moveTask(db, ref, "in_progress"); + } catch (e) { + return (e as Error).message; + } + await show(chatId, `${head}\n▶️ В работе — агент взялся.`, [], msgId); + return `${ref.key}: агент взялся ▶️`; + } + const d = await loadDraft(db, Number(parts[1]), user.id); + if (!d) { + await show(chatId, "Черновик не найден или устарел — напиши заново.", [], msgId); + return "Черновик устарел"; + } + if (parts[2] === "x") { + await dropDraft(db, d.id); + await show(chatId, `✖️ Отменено: ${storyLine(d)}`, [], msgId); + return "Отменено"; + } + if (parts[2] === "p") { + const projectId = Number(parts[3]); + const project = await projectForUser(db, user.id, projectId).catch(() => null); + if (!project) return "Проект не найден"; + await updateDraft(db, { ...d, projectId }); + await askEpic(d, project, msgId); + return project.key; + } + if (parts[2] === "g" && d.projectId) { + const project = await projectForUser(db, user.id, d.projectId).catch(() => null); + if (!project) return "Проект не найден"; + const goalId = Number(parts[3]) || undefined; + if (goalId && !(await getGoal(db, project.id, goalId).catch(() => null))) return "Эпик не найден"; + const { title, rest } = splitStory(d.text); + const from = `Создано из Telegram (${user.login}${d.voice ? ", расшифровка голосового" : ""}).`; + const ref = await createTask(db, { projectId: project.id, goalId, title, description: `${rest ? `${rest}\n\n` : ""}${from}` }); + await dropDraft(db, d.id); + await show( + chatId, + `📥 Создал ${esc(ref.key)}: ${esc(title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}\nВзять в работу сейчас?`, + [[{ text: "▶️ Взять в работу", callback_data: `t:${ref.task.id}:start` }, { text: "Оставить в бэклоге", callback_data: `t:${ref.task.id}:keep` }]], + msgId, + ); + return `Создал ${ref.key}`; + } + return "Неизвестная кнопка"; + } + async function onMessage(m: TgMessage): Promise<"done" | "ignored"> { const text = m.text?.trim() ?? ""; const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text); @@ -264,7 +402,16 @@ export function createBot(o: BotOptions) { await reply(m.chat.id, esc(await answer(q, text)), m.message_id); return "done"; } - await reply(m.chat.id, "Чтобы ответить агенту, ответь реплаем на его сообщение. /status — что сейчас происходит."); + if (m.voice || m.audio) { + await onVoice(user, m); + return "done"; + } + if (!text || text.startsWith("/")) { + await reply(m.chat.id, "Чтобы ответить агенту, ответь реплаем на его сообщение. Чтобы завести стори — просто напиши её. /help — что я умею."); + return "done"; + } + // PEP-45: any other text is a new story (created only after a button press). + await startStory(user, m.chat.id, text, false); return "done"; } @@ -274,7 +421,13 @@ export function createBot(o: BotOptions) { await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {}); return "ignored"; } - const [kind, idStr, choice] = (c.data ?? "").split(":"); + const parts = (c.data ?? "").split(":"); + if (parts[0] === "d" || parts[0] === "t") { + const toast = await onStoryButton(user, c, parts).catch((e) => (log(`story: ${(e as Error).stack ?? e}`), "Ошибка")); + await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`)); + return "done"; + } + const [kind, idStr, choice] = parts; const id = Number(idStr); let toast = "Неизвестная кнопка"; const q0 = kind === "q" ? await getQuestion(db, id).catch(() => null) : null; diff --git a/apps/bot/src/drafts.ts b/apps/bot/src/drafts.ts new file mode 100644 index 00000000..99ea1b66 --- /dev/null +++ b/apps/bot/src/drafts.ts @@ -0,0 +1,74 @@ +// Stories from a message to the bot (PEP-45): a draft waits for the project/epic buttons, so +// a stray message never creates a story by itself. Drafts live in `settings` for a day. +import { deleteSetting, getSetting, setSetting, type Project } from "@peppa/core"; +import type { Db } from "@peppa/db"; + +export const DRAFT_TTL_MS = 24 * 3600_000; +export const TITLE_MAX = 120; + +export interface Draft { + id: number; + userId: number; + chatId: number; + text: string; + projectId: number | null; + voice: boolean; + createdAt: number; +} + +const key = (id: number) => `bot.draft:${id}`; + +export async function saveDraft(db: Db, d: Omit): Promise { + const id = ((await getSetting(db, "bot.draft.seq")) ?? 0) + 1; + await setSetting(db, "bot.draft.seq", id); + const draft: Draft = { ...d, id, createdAt: Date.now() }; + await setSetting(db, key(id), draft); + return draft; +} + +/** The user's own, not expired draft. */ +export async function loadDraft(db: Db, id: number, userId: number): Promise { + const d = await getSetting(db, key(id)); + if (!d || d.userId !== userId) return null; + if (Date.now() - d.createdAt > DRAFT_TTL_MS) { + await deleteSetting(db, key(id)); + return null; + } + return d; +} + +export async function updateDraft(db: Db, d: Draft): Promise { + await setSetting(db, key(d.id), d); +} + +export async function dropDraft(db: Db, id: number): Promise { + await deleteSetting(db, key(id)); +} + +/** + * "в PAY: экспорт в CSV", "PAY: …", "PAY — …", or (voice, no punctuation) "в PAY экспорт…". + * The key counts only if it is one of the user's projects; otherwise the whole text is the story. + */ +export function parseStoryText(text: string, projects: Project[]): { project: Project | null; body: string } { + const t = text.trim(); + const byKey = (k: string) => projects.find((p) => p.key.toLowerCase() === k.toLowerCase()) ?? null; + const withSep = /^(?:(?:в|во|для|in|to)\s+)?([A-Za-z][A-Za-z0-9]{1,9})\s*[::—–-]\s*([\s\S]+)$/i.exec(t); + if (withSep && byKey(withSep[1]!)) return { project: byKey(withSep[1]!), body: withSep[2]!.trim() }; + const spoken = /^(?:в|во|для|in|to)\s+([A-Za-z][A-Za-z0-9]{1,9})[,.]?\s+([\s\S]+)$/i.exec(t); + if (spoken && byKey(spoken[1]!)) return { project: byKey(spoken[1]!), body: spoken[2]!.trim() }; + return { project: null, body: t }; +} + +/** Title (first line, at most TITLE_MAX chars, cut at a word) and the rest as description. */ +export function splitStory(body: string): { title: string; rest: string } { + const [first = "", ...lines] = body.trim().split("\n"); + let title = first.trim(); + let rest = lines.join("\n").trim(); + if (title.length > TITLE_MAX) { + const cut = title.lastIndexOf(" ", TITLE_MAX - 1); + const at = cut > TITLE_MAX / 2 ? cut : TITLE_MAX - 1; + rest = `${title}${rest ? `\n\n${rest}` : ""}`; + title = `${title.slice(0, at).trim()}…`; + } + return { title, rest }; +} diff --git a/apps/bot/src/telegram.ts b/apps/bot/src/telegram.ts index fad604cc..b8039146 100644 --- a/apps/bot/src/telegram.ts +++ b/apps/bot/src/telegram.ts @@ -12,6 +12,15 @@ export interface TgMessage { from?: TgUser; text?: string; reply_to_message?: TgMessage; + /** PEP-45: voice notes and audio files become stories after transcription. */ + voice?: TgFileRef; + audio?: TgFileRef; +} +export interface TgFileRef { + file_id: string; + duration?: number; + mime_type?: string; + file_size?: number; } export interface TgCallbackQuery { id: string; @@ -96,6 +105,17 @@ export class TelegramApi { return this.call("answerCallbackQuery", { callback_query_id: id, text }); } + getFile(fileId: string) { + return this.call<{ file_id: string; file_path?: string; file_size?: number }>("getFile", { file_id: fileId }); + } + + /** Bytes of a file from getFile (Bot API: GET /file/bot/, up to 20 MB). */ + async downloadFile(filePath: string): Promise { + const res = await fetch(`${this.baseUrl}/file/bot${this.token}/${filePath}`, { signal: AbortSignal.timeout(60_000) }); + if (!res.ok) throw new TelegramError("downloadFile", res.status, res.statusText); + return Buffer.from(await res.arrayBuffer()); + } + sendMessage(chatId: number, text: string, extra: Record = {}) { return this.call("sendMessage", { chat_id: chatId, text, parse_mode: "HTML", ...extra }); } diff --git a/apps/bot/src/transcribe.ts b/apps/bot/src/transcribe.ts new file mode 100644 index 00000000..11bfe038 --- /dev/null +++ b/apps/bot/src/transcribe.ts @@ -0,0 +1,52 @@ +// Speech to text for voice notes (PEP-45): any OpenAI-compatible audio API — +// POST $PEPPA_TRANSCRIBE_URL/audio/transcriptions (multipart: file, model, language, +// response_format=json) with "Authorization: Bearer $PEPPA_TRANSCRIBE_KEY" → {"text": "…"}. +// OpenAI (https://api.openai.com/v1, whisper-1), Groq (https://api.groq.com/openai/v1, +// whisper-large-v3), a local faster-whisper/speaches server — all speak this. Tests use +// mock-transcribe (packages/testkit). + +export interface TranscribeConfig { + url: string; + key: string | null; + model: string; + language: string | null; +} + +/** From env; null when voice is not set up (the bot asks for text then). */ +export function transcribeConfig(env: NodeJS.ProcessEnv = process.env): TranscribeConfig | null { + const url = env.PEPPA_TRANSCRIBE_URL?.trim(); + if (!url) return null; + return { + url: url.replace(/\/$/, ""), + key: env.PEPPA_TRANSCRIBE_KEY?.trim() || null, + model: env.PEPPA_TRANSCRIBE_MODEL?.trim() || "whisper-1", + language: env.PEPPA_TRANSCRIBE_LANG === "" ? null : (env.PEPPA_TRANSCRIBE_LANG?.trim() || "ru"), + }; +} + +export class TranscribeError extends Error {} + +export async function transcribe(cfg: TranscribeConfig, audio: Buffer, filename = "voice.ogg", mime = "audio/ogg"): Promise { + const form = new FormData(); + form.set("file", new Blob([new Uint8Array(audio)], { type: mime }), filename); + form.set("model", cfg.model); + form.set("response_format", "json"); + if (cfg.language) form.set("language", cfg.language); + let res: Response; + try { + res = await fetch(`${cfg.url}/audio/transcriptions`, { + method: "POST", + headers: cfg.key ? { Authorization: `Bearer ${cfg.key}` } : {}, + body: form, + signal: AbortSignal.timeout(120_000), + }); + } catch (e) { + throw new TranscribeError(`сервис расшифровки недоступен: ${(e as Error).message}`); + } + const body = (await res.json().catch(() => ({}))) as { text?: string; error?: { message?: string } | string }; + if (!res.ok) { + const msg = typeof body.error === "string" ? body.error : body.error?.message; + throw new TranscribeError(`расшифровка не удалась: ${res.status}${msg ? ` ${msg}` : ""}`); + } + return (body.text ?? "").trim(); +} diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index ac9331ae..b671b5ce 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -137,6 +137,17 @@ export default async function Help() { deploy). После каждого деплоя — проверка /healthz до 2 минут; не прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта.

+

+ Превью на ревью: «готово к ревью» и карточка стори (блок «Превью») показывают «Посмотреть» — стенд PR, ссылку на + дифф и итог проверок. Шаг деплоя превью снимает скриншоты страниц из deploy.screenshots{" "} + (по умолчанию главная, [] — выключить) — они в карточке стори. +

+

+ Gitea знает о Пеппе: issue, открытый вами или участником проекта, становится стори в бэклоге (в issue появится + ссылка; стори готова — issue закроется), старые открытые issues переносит{" "} + peppa project import-issues KEY. Комментарий или ревью «нужны изменения» в PR стори + уходит её агенту (стори из «Ревью» вернётся в работу), а мерж PR руками в Gitea переводит стори в «Готово». +

Сама Пеппа (проект PEP) выкатывается так же по кнопке, но без staging: после зелёных проверок{" "} main приходит предложение «Выкатить в прод»; релиз собирается на хосте рядом с @@ -152,6 +163,10 @@ export default async function Help() { проекта: сообщением, стори или с кнопками «В бэклог / В работу / Игнорировать». Команды бота: /status — что сейчас происходит, /digest — сводка за сутки.

+

+ Новую стори можно просто написать или наговорить боту: «в PAY: экспорт в CSV». Бот уточнит проект (если не указан) и + эпик кнопками, создаст стори и предложит «Взять в работу». Голосовые работают, если на сервере настроена расшифровка. +

diff --git a/openspec/changes/pep-44-review-preview/proposal.md b/openspec/changes/archive/2026-11-14-pep-44-review-preview/proposal.md similarity index 100% rename from openspec/changes/pep-44-review-preview/proposal.md rename to openspec/changes/archive/2026-11-14-pep-44-review-preview/proposal.md diff --git a/openspec/changes/pep-44-review-preview/specs/delivery-pipeline/spec.md b/openspec/changes/archive/2026-11-14-pep-44-review-preview/specs/delivery-pipeline/spec.md similarity index 100% rename from openspec/changes/pep-44-review-preview/specs/delivery-pipeline/spec.md rename to openspec/changes/archive/2026-11-14-pep-44-review-preview/specs/delivery-pipeline/spec.md diff --git a/openspec/changes/archive/2026-11-14-pep-44-review-preview/tasks.md b/openspec/changes/archive/2026-11-14-pep-44-review-preview/tasks.md new file mode 100644 index 00000000..1da4d21b --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-44-review-preview/tasks.md @@ -0,0 +1,8 @@ +# Tasks: PEP-44 + +- [x] 1.1 Схема `releases.screenshots` + миграция; core `reviewPreview` +- [x] 1.2 runner `recordScreenshots` + событие `screenshots` в хуке; сводка в Stop-хуке и ревьюере +- [x] 1.3 Шаблон `peppa-deploy.sh`: скриншоты превью в контейнере, отчёт +- [x] 1.4 Веб: маршрут скриншотов, блок «Превью» в карточке; MCP `get_task` +- [x] 1.5 testkit: `mock-docker run`, `deploy.test.ts` +- [x] 1.6 AGENTS.md, «Помощь», `openspec validate` diff --git a/openspec/changes/pep-45-bot-story/proposal.md b/openspec/changes/archive/2026-11-14-pep-45-bot-story/proposal.md similarity index 100% rename from openspec/changes/pep-45-bot-story/proposal.md rename to openspec/changes/archive/2026-11-14-pep-45-bot-story/proposal.md diff --git a/openspec/changes/pep-45-bot-story/specs/telegram-notifications/spec.md b/openspec/changes/archive/2026-11-14-pep-45-bot-story/specs/telegram-notifications/spec.md similarity index 100% rename from openspec/changes/pep-45-bot-story/specs/telegram-notifications/spec.md rename to openspec/changes/archive/2026-11-14-pep-45-bot-story/specs/telegram-notifications/spec.md diff --git a/openspec/changes/archive/2026-11-14-pep-45-bot-story/tasks.md b/openspec/changes/archive/2026-11-14-pep-45-bot-story/tasks.md new file mode 100644 index 00000000..c32f67cf --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-45-bot-story/tasks.md @@ -0,0 +1,6 @@ +# Tasks: PEP-45 + +- [x] 1.1 Бот: черновик из текста (разбор `KEY:`), кнопки проекта/эпика, создание, «Взять в работу» +- [x] 1.2 Голос: `getFile` + скачивание, `transcribe.ts` (OpenAI-совместимый API, env) +- [x] 1.3 testkit: голос и файлы в `mock-telegram`, `mock-transcribe`, тесты в `bot.test.ts` +- [x] 1.4 AGENTS.md, «Помощь», HELP бота, `openspec validate` diff --git a/openspec/changes/pep-46-gitea-integration/design.md b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/design.md similarity index 100% rename from openspec/changes/pep-46-gitea-integration/design.md rename to openspec/changes/archive/2026-11-14-pep-46-gitea-integration/design.md diff --git a/openspec/changes/pep-46-gitea-integration/proposal.md b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/proposal.md similarity index 100% rename from openspec/changes/pep-46-gitea-integration/proposal.md rename to openspec/changes/archive/2026-11-14-pep-46-gitea-integration/proposal.md diff --git a/openspec/changes/pep-46-gitea-integration/specs/gitea-integration/spec.md b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/specs/gitea-integration/spec.md similarity index 100% rename from openspec/changes/pep-46-gitea-integration/specs/gitea-integration/spec.md rename to openspec/changes/archive/2026-11-14-pep-46-gitea-integration/specs/gitea-integration/spec.md diff --git a/openspec/changes/pep-46-gitea-integration/tasks.md b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/tasks.md similarity index 52% rename from openspec/changes/pep-46-gitea-integration/tasks.md rename to openspec/changes/archive/2026-11-14-pep-46-gitea-integration/tasks.md index 10548620..3fbd9771 100644 --- a/openspec/changes/pep-46-gitea-integration/tasks.md +++ b/openspec/changes/archive/2026-11-14-pep-46-gitea-integration/tasks.md @@ -1,8 +1,8 @@ # Tasks: PEP-46 -- [ ] 1.1 Схема `tasks.gitea_issue` + миграция; Gitea-клиент: issues, комментарий, закрытие; `GITEA_BOT_LOGIN` -- [ ] 1.2 runner `gitea-events.ts`: issue → стори, комментарий/ревью → агенту, мерж руками → done; регистрация через `onGiteaEvent` -- [ ] 1.3 `moveTask(done)` закрывает issue; `acceptTask` терпит закрытый вебхуком вопрос; события вебхука в `setupCi` -- [ ] 1.4 `importIssues` + CLI `peppa project import-issues`; issue в карточке и `get_task` -- [ ] 1.5 testkit: issues/комментарии в `mock-gitea`, `gitea-events.test.ts` по сценариям -- [ ] 1.6 AGENTS.md, «Помощь», `openspec validate` +- [x] 1.1 Схема `tasks.gitea_issue` + миграция; Gitea-клиент: issues, комментарий, закрытие; `GITEA_BOT_LOGIN` +- [x] 1.2 runner `gitea-events.ts`: issue → стори, комментарий/ревью → агенту, мерж руками → done; регистрация через `onGiteaEvent` +- [x] 1.3 `moveTask(done)` закрывает issue; `acceptTask` терпит закрытый вебхуком вопрос; события вебхука в `setupCi` +- [x] 1.4 `importIssues` + CLI `peppa project import-issues`; issue в карточке и `get_task` +- [x] 1.5 testkit: issues/комментарии в `mock-gitea`, `gitea-events.test.ts` по сценариям +- [x] 1.6 AGENTS.md, «Помощь», `openspec validate` diff --git a/openspec/changes/pep-44-review-preview/tasks.md b/openspec/changes/pep-44-review-preview/tasks.md deleted file mode 100644 index b40db685..00000000 --- a/openspec/changes/pep-44-review-preview/tasks.md +++ /dev/null @@ -1,8 +0,0 @@ -# Tasks: PEP-44 - -- [ ] 1.1 Схема `releases.screenshots` + миграция; core `reviewPreview` -- [ ] 1.2 runner `recordScreenshots` + событие `screenshots` в хуке; сводка в Stop-хуке и ревьюере -- [ ] 1.3 Шаблон `peppa-deploy.sh`: скриншоты превью в контейнере, отчёт -- [ ] 1.4 Веб: маршрут скриншотов, блок «Превью» в карточке; MCP `get_task` -- [ ] 1.5 testkit: `mock-docker run`, `deploy.test.ts` -- [ ] 1.6 AGENTS.md, «Помощь», `openspec validate` diff --git a/openspec/changes/pep-45-bot-story/tasks.md b/openspec/changes/pep-45-bot-story/tasks.md deleted file mode 100644 index 5394cc67..00000000 --- a/openspec/changes/pep-45-bot-story/tasks.md +++ /dev/null @@ -1,6 +0,0 @@ -# Tasks: PEP-45 - -- [ ] 1.1 Бот: черновик из текста (разбор `KEY:`), кнопки проекта/эпика, создание, «Взять в работу» -- [ ] 1.2 Голос: `getFile` + скачивание, `transcribe.ts` (OpenAI-совместимый API, env) -- [ ] 1.3 testkit: голос и файлы в `mock-telegram`, `mock-transcribe`, тесты в `bot.test.ts` -- [ ] 1.4 AGENTS.md, «Помощь», HELP бота, `openspec validate` diff --git a/openspec/specs/delivery-pipeline/spec.md b/openspec/specs/delivery-pipeline/spec.md index 9216d26f..a8478a75 100644 --- a/openspec/specs/delivery-pipeline/spec.md +++ b/openspec/specs/delivery-pipeline/spec.md @@ -111,3 +111,20 @@ - **GIVEN** проект, где PM не включал ревьюер - **WHEN** агент переводит стори с зелёными проверками в «Ревью» - **THEN** стори сразу в «Ревью», ревьюер не вызывается + +### Requirement: Превью на ревью +Сообщение «готово к ревью» и карточка стори SHALL показывать ссылку на здоровый превью-стенд PR стори, ссылку на дифф и итог проверок; карточка SHALL показывать скриншоты стенда, снятые CI-шагом деплоя превью. + +#### Scenario: Стенд поднят +- **GIVEN** стори PAY-7 с PR #3 и здоровым превью `pay-pr3.telecom.quest` +- **WHEN** PAY-7 уходит в «Ревью» +- **THEN** «готово к ревью» содержит «Посмотреть: https://pay-pr3.telecom.quest», ссылку на дифф и итог проверок + +#### Scenario: Скриншоты +- **GIVEN** проект с `deploy.screenshots: ["/"]` +- **WHEN** превью PR #3 поднялось здоровым +- **THEN** CI-шаг присылает скриншот, он виден в карточке стори PAY-7 + +#### Scenario: Скриншоты не сняты +- **WHEN** снять скриншот не удалось +- **THEN** превью всё равно здоровое, карточка показывает ссылку без скриншотов diff --git a/openspec/specs/gitea-integration/spec.md b/openspec/specs/gitea-integration/spec.md new file mode 100644 index 00000000..c7931608 --- /dev/null +++ b/openspec/specs/gitea-integration/spec.md @@ -0,0 +1,46 @@ +# gitea-integration Specification + +## Purpose +Как Пеппа узнаёт о событиях в Gitea: issues становятся стори, комментарии и ревью в PR уходят агенту, мерж PR руками закрывает стори. + +## Requirements + +### Requirement: Issues становятся стори +Открытый в репозитории проекта issue от пользователя с доступом к проекту SHALL становиться стори в бэклоге со ссылкой на issue, а issue SHALL получать комментарий со ссылкой на стори. Issue от пользователя без доступа SHALL игнорироваться. Когда стори готова, связанный issue SHALL закрываться. + +#### Scenario: Участник открыл issue +- **GIVEN** проект «PAY», владелец которого вошёл через Gitea как «pm» +- **WHEN** «pm» открывает issue «Экспорт в CSV» в репозитории PAY +- **THEN** в бэклоге PAY появляется стори «Экспорт в CSV» со ссылкой на issue +- **AND** в issue появляется комментарий со ссылкой на стори + +#### Scenario: Чужой issue +- **GIVEN** публичный репозиторий проекта «PAY» +- **WHEN** issue открывает пользователь Gitea без доступа к PAY +- **THEN** стори не создаётся + +#### Scenario: Стори готова +- **GIVEN** стори PAY-7, созданная из issue #3 +- **WHEN** PAY-7 переходит в «Готово» +- **THEN** issue #3 закрыт с комментарием + +### Requirement: Комментарии в PR уходят агенту +Комментарий или ревью «нужны изменения» в PR стори от пользователя с доступом SHALL доставляться агенту стори; стори из «Ревью» SHALL возвращаться «В работу». Одобрения и комментарии самой Пеппы SHALL игнорироваться. + +#### Scenario: Комментарий в PR +- **GIVEN** стори PAY-7 в «Ревью» с открытым PR +- **WHEN** «pm» пишет в PR комментарий «Переименуй кнопку» +- **THEN** агент PAY-7 получает текст комментария +- **AND** PAY-7 снова «В работе» + +#### Scenario: Комментарий бота +- **WHEN** комментарий в PR оставляет peppa-bot +- **THEN** агенту ничего не уходит + +### Requirement: Мерж руками закрывает стори +Мерж PR стори в Gitea вручную SHALL переводить стори в «Готово» и останавливать её раннер. + +#### Scenario: PM смержил PR в Gitea +- **GIVEN** стори PAY-7 в «Ревью» с открытым PR +- **WHEN** PR смержен в интерфейсе Gitea +- **THEN** PAY-7 в «Готово», сообщение «готово к ревью» закрыто diff --git a/openspec/specs/telegram-notifications/spec.md b/openspec/specs/telegram-notifications/spec.md index 0d25f8fe..51fe5e13 100644 --- a/openspec/specs/telegram-notifications/spec.md +++ b/openspec/specs/telegram-notifications/spec.md @@ -37,3 +37,30 @@ Telegram, и никому больше. #### Scenario: Нет доступа - **WHEN** пользователь без доступа к проекту присылает нажатие кнопки чужого вопроса - **THEN** вопрос остаётся без ответа + +### Requirement: Стори из сообщения боту +Привязанный пользователь SHALL создавать стори сообщением боту — текстом или голосом. Бот SHALL уточнять проект (если не указан и проектов несколько) и эпик кнопками, создавать стори только после нажатия кнопки и предлагать сразу взять её в работу. Проект SHALL выбираться только из доступных пользователю. + +#### Scenario: Текст с проектом +- **GIVEN** PM с привязанным Telegram и проектом «PAY» без эпиков +- **WHEN** PM пишет боту «в PAY: добавить экспорт в CSV» и нажимает «Создать» +- **THEN** в бэклоге PAY появляется стори «добавить экспорт в CSV» +- **AND** бот предлагает «Взять в работу» + +#### Scenario: Выбор проекта и эпика +- **GIVEN** у PM два проекта, в «PAY» есть эпик «Отчёты» +- **WHEN** PM пишет боту «экспорт в CSV», выбирает «PAY», затем «Отчёты» +- **THEN** стори создана в PAY с эпиком «Отчёты» + +#### Scenario: Взять в работу +- **WHEN** PM нажимает «Взять в работу» под созданной стори +- **THEN** стори «В работе», агент запущен + +#### Scenario: Голосовое +- **GIVEN** расшифровка голоса настроена +- **WHEN** PM присылает голосовое «в PAY добавить экспорт» +- **THEN** бот показывает расшифровку и предлагает создать стори в PAY + +#### Scenario: Чужой проект +- **WHEN** пользователь пишет «в SEC: …», а к проекту SEC у него нет доступа +- **THEN** проект SEC не предлагается и стори в нём не создаётся diff --git a/packages/testkit/src/mock-telegram.ts b/packages/testkit/src/mock-telegram.ts index aad39524..9b177f04 100644 --- a/packages/testkit/src/mock-telegram.ts +++ b/packages/testkit/src/mock-telegram.ts @@ -30,6 +30,8 @@ export class MockTelegram { private waiters: Array<() => void> = []; private failures: Array<{ method: string; code: number; retryAfter?: number }> = []; private server: Server | null = null; + /** PEP-45: uploaded voice files by file_id (served at /file/bot/). */ + private files = new Map(); url = ""; async start(port = 0): Promise { @@ -37,6 +39,12 @@ export class MockTelegram { let body = ""; req.on("data", (c) => (body += c)); req.on("end", async () => { + if (req.method === "GET" && req.url!.startsWith(`/file/bot${this.token}/`)) { + const path = decodeURIComponent(req.url!.slice(`/file/bot${this.token}/`.length)); + const f = [...this.files.values()].find((x) => x.path === path); + res.writeHead(f ? 200 : 404, { "Content-Type": "application/octet-stream" }); + return res.end(f?.data ?? ""); + } if (req.url!.startsWith("/_mock/")) { const r = this.inspect(req.method!, req.url!, body ? JSON.parse(body) : {}); res.writeHead(r.status, { "Content-Type": "application/json" }); @@ -107,6 +115,11 @@ export class MockTelegram { m.edits++; return { ok: true, result: { message_id: m.message_id } }; } + case "getFile": { + const f = this.files.get(String(p.file_id)); + if (!f) return { ok: false, error_code: 400, description: "Bad Request: invalid file_id" }; + return { ok: true, result: { file_id: p.file_id, file_unique_id: `u-${p.file_id}`, file_size: f.data.length, file_path: f.path } }; + } case "answerCallbackQuery": this.callbackAnswers.push({ id: String(p.callback_query_id), text: p.text as string | undefined }); return { ok: true, result: true }; @@ -135,6 +148,20 @@ export class MockTelegram { }); } + /** User sends a voice note (OGG/Opus in real Telegram; any bytes here). */ + userSendsVoice(user: MockTgUser, audio: Buffer, duration = 3) { + const fileId = `mock-voice-${this.nextMessageId}`; + this.files.set(fileId, { path: `voice/file_${this.nextMessageId}.oga`, data: audio }); + return this.push({ + message: { + message_id: this.nextMessageId++, + chat: { id: user.chatId, type: "private" }, + from: { id: user.id, username: user.username, first_name: user.username ?? "user" }, + voice: { file_id: fileId, file_unique_id: `u-${fileId}`, duration, mime_type: "audio/ogg", file_size: audio.length }, + }, + }); + } + /** User presses an inline button on a bot message. */ userClicks(user: MockTgUser, messageId: number, data: string) { const id = `cb-${this.nextUpdateId}`; diff --git a/packages/testkit/src/mock-transcribe.ts b/packages/testkit/src/mock-transcribe.ts new file mode 100644 index 00000000..73af06d4 --- /dev/null +++ b/packages/testkit/src/mock-transcribe.ts @@ -0,0 +1,51 @@ +// Mock OpenAI-compatible speech-to-text (PEP-45): POST /v1/audio/transcriptions, multipart +// `file` + `model` (+ `language`, `response_format`), Bearer key → {"text": "…"}, errors as +// {"error": {"message"}} with 400/401 like OpenAI. "Speech" is the audio bytes as UTF-8 +// prefixed "MOCK-SPEECH:"; anything else transcribes to "" (silence). +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; + +export class MockTranscribe { + readonly key = "mock-transcribe-key"; + readonly requests: Array<{ model: string; language: string | null; filename: string; bytes: number }> = []; + private server: Server | null = null; + url = ""; + + /** Audio that the mock "hears" as `text`. */ + static speech(text: string): Buffer { + return Buffer.from(`MOCK-SPEECH:${text}`, "utf8"); + } + + async start(port = 0): Promise { + this.server = createServer(async (req, res) => { + const send = (status: number, body: unknown) => { + res.writeHead(status, { "Content-Type": "application/json" }); + res.end(JSON.stringify(body)); + }; + if (req.method !== "POST" || req.url !== "/v1/audio/transcriptions") return send(404, { error: { message: "not found" } }); + if (req.headers.authorization !== `Bearer ${this.key}`) return send(401, { error: { message: "Incorrect API key provided" } }); + const chunks: Buffer[] = []; + for await (const c of req) chunks.push(c as Buffer); + let form: FormData; + try { + form = await new Request("http://x", { method: "POST", headers: { "content-type": String(req.headers["content-type"]) }, body: Buffer.concat(chunks) }).formData(); + } catch { + return send(400, { error: { message: "Could not parse multipart form" } }); + } + const file = form.get("file"); + const model = form.get("model"); + if (!(file instanceof Blob) || typeof model !== "string" || !model) return send(400, { error: { message: "file and model are required" } }); + const bytes = Buffer.from(await file.arrayBuffer()); + this.requests.push({ model, language: (form.get("language") as string | null) ?? null, filename: (file as File).name ?? "", bytes: bytes.length }); + const s = bytes.toString("utf8"); + send(200, { text: s.startsWith("MOCK-SPEECH:") ? s.slice("MOCK-SPEECH:".length) : "" }); + }); + await new Promise((r) => this.server!.listen(port, "127.0.0.1", r)); + this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/v1`; + return this; + } + + async stop() { + await new Promise((r) => this.server?.close(() => r()) ?? r()); + } +} diff --git a/packages/testkit/test/bot.test.ts b/packages/testkit/test/bot.test.ts index 41081929..8c736c12 100644 --- a/packages/testkit/test/bot.test.ts +++ b/packages/testkit/test/bot.test.ts @@ -5,6 +5,7 @@ import { after, before, describe, test } from "node:test"; // helpers must load first: it sets the isolated test env that runner modules read on load. import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor } from "./helpers.ts"; import { MockTelegram, type MockTgMessage } from "../src/mock-telegram.ts"; +import { MockTranscribe } from "../src/mock-transcribe.ts"; import type { Bot } from "@peppa/bot"; const { createBot } = await import("@peppa/bot"); @@ -264,3 +265,116 @@ describe("staleness and reliability", () => { assert.equal((await core.getQuestion(db, q.id)).answer, "используй v2"); }); }); + +// PEP-45, spec telegram-notifications: «Стори из сообщения боту». +describe("Стори из сообщения боту", () => { + const botMsg = (re: RegExp) => waitFor(`bot message ${re}`, async () => tg.botMessages(PM.chatId).filter((m) => re.test(m.text)).at(-1)); + const button = (m: MockTgMessage, re: RegExp) => { + const b = m.reply_markup?.inline_keyboard.flat().find((x) => re.test(x.text)); + assert.ok(b, `button ${re} in ${JSON.stringify(m.reply_markup)}`); + return b.callback_data!; + }; + const storyByTitle = async (projectKey: string, title: string) => { + const proj = await core.getProject(db, projectKey); + return (await core.listTasks(db, { projectId: proj.id })).find((t) => t.title === title); + }; + + test("Scenario: Текст с проектом — «Создать», стори в бэклоге, предложение взять в работу", async () => { + const p = await project({ turns: [] }); + tg.userSends(PM, `в ${p.key}: добавить экспорт в CSV`); + const ask = await botMsg(new RegExp(`Новая стори в ${p.key}: «добавить экспорт в CSV»`)); + assert.equal(await storyByTitle(p.key, "добавить экспорт в CSV"), undefined, "nothing is created before the button"); + tg.userClicks(PM, ask.message_id, button(ask, new RegExp(`Создать в ${p.key}`))); + await waitFor("created", async () => /Создал /.test(ask.text)); + const t = await storyByTitle(p.key, "добавить экспорт в CSV"); + assert.ok(t); + assert.equal(t.status, "backlog"); + assert.match(t.description!, /Создано из Telegram \(mock-pm\)/); + assert.match(ask.text, new RegExp(`${t.key}`)); + button(ask, /Взять в работу/); + tg.userClicks(PM, ask.message_id, button(ask, /Оставить в бэклоге/)); + await waitFor("kept", async () => /В бэклоге/.test(ask.text) && ask.reply_markup?.inline_keyboard.length === 0); + assert.equal((await core.resolveTask(db, t.key)).task.status, "backlog"); + }); + + test("Scenario: Выбор проекта и эпика", async () => { + await project({ turns: [] }); + const p = await project({ turns: [] }); + const proj = await core.getProject(db, p.key); + const epic = await core.createGoal(db, proj.id, "Отчёты"); + tg.userSends(PM, "экспорт отчётов в xlsx"); + const ask = await botMsg(/Новая стори «экспорт отчётов в xlsx»\nВ какой проект\?/); + tg.userClicks(PM, ask.message_id, button(ask, new RegExp(`^${p.key}$`))); + await waitFor("epic asked", async () => /Эпик\?/.test(ask.text)); + button(ask, /Без эпика/); + tg.userClicks(PM, ask.message_id, button(ask, /^Отчёты$/)); + await waitFor("created", async () => /Создал/.test(ask.text)); + const t = await storyByTitle(p.key, "экспорт отчётов в xlsx"); + assert.equal(t?.goalId, epic.id); + }); + + test("Scenario: Взять в работу — стори в работе, агент запущен", async () => { + const p = await project({ turns: [[{ say: "Беру стори." }]] }); + tg.userSends(PM, `${p.key}: поправить опечатку`); + const ask = await botMsg(new RegExp(`Новая стори в ${p.key}: «поправить опечатку»`)); + tg.userClicks(PM, ask.message_id, button(ask, /Создать/)); + await waitFor("created", async () => /Создал/.test(ask.text)); + const cb = tg.userClicks(PM, ask.message_id, button(ask, /Взять в работу/)); + await waitFor("taken", async () => tg.callbackAnswers.find((a) => a.id === cb && /агент взялся/.test(a.text ?? ""))); + const t = (await storyByTitle(p.key, "поправить опечатку"))!; + assert.equal(t.status, "in_progress"); + const sessions = await core.listSessions(db, { active: true, taskId: t.id }); + assert.equal(sessions.length, 1); + for (const s of sessions) await runner.stopSession(db, s.id); + }); + + test("Scenario: Голосовое — расшифровка и предложение создать стори; без настройки — просьба написать текстом", async () => { + const p = await project({ turns: [] }); + tg.userSendsVoice(PM, MockTranscribe.speech(`в ${p.key} добавить экспорт`)); + await botMsg(/Голосовые пока не настроены/); + + const stt = await new MockTranscribe().start(); + Object.assign(process.env, { PEPPA_TRANSCRIBE_URL: stt.url, PEPPA_TRANSCRIBE_KEY: stt.key }); + try { + tg.userSendsVoice(PM, MockTranscribe.speech(`в ${p.key} добавить экспорт`)); + await botMsg(new RegExp(`Расслышал: «в ${p.key} добавить экспорт»`)); + const ask = await botMsg(new RegExp(`Новая стори в ${p.key}: «добавить экспорт»`)); + assert.deepEqual(stt.requests.at(-1), { model: "whisper-1", language: "ru", filename: stt.requests.at(-1)!.filename, bytes: MockTranscribe.speech(`в ${p.key} добавить экспорт`).length }); + tg.userClicks(PM, ask.message_id, button(ask, /Создать/)); + await waitFor("created", async () => /Создал/.test(ask.text)); + assert.match((await storyByTitle(p.key, "добавить экспорт"))!.description!, /расшифровка голосового/); + // Silence → nothing to create. + tg.userSendsVoice(PM, Buffer.from("ogg-opus-noise")); + await botMsg(/Не разобрал ни слова/); + // Wrong key → the service error is shown, no draft. + process.env.PEPPA_TRANSCRIBE_KEY = "wrong"; + tg.userSendsVoice(PM, MockTranscribe.speech("что-то")); + await botMsg(/Не получилось расшифровать голосовое \(расшифровка не удалась: 401/); + } finally { + delete process.env.PEPPA_TRANSCRIBE_URL; + delete process.env.PEPPA_TRANSCRIBE_KEY; + await stt.stop(); + } + }); + + test("Scenario: Чужой проект — не предлагается и не создаётся", async () => { + setDefaultOwner(bobUser.id); + const sec = await project({ turns: [] }); + setDefaultOwner(pmUser.id); + const secProj = await core.getProject(db, sec.key); + tg.userSends(PM, `в ${sec.key}: украсть данные`); + // The key isn't one of the PM's projects: the whole text is the story, the project is asked. + const ask = await botMsg(new RegExp(`Новая стори «в ${sec.key}: украсть данные»`)); + assert.ok(!ask.reply_markup!.inline_keyboard.flat().some((b) => b.text === sec.key), "someone else's project is not offered"); + const draft = button(ask, /Отмена/).split(":")[1]; + const cb = tg.userClicks(PM, ask.message_id, `d:${draft}:p:${secProj.id}`); + await waitFor("refused", async () => tg.callbackAnswers.find((a) => a.id === cb && /Проект не найден/.test(a.text ?? ""))); + tg.userClicks(PM, ask.message_id, button(ask, /Отмена/)); + await waitFor("cancelled", async () => /Отменено/.test(ask.text)); + assert.equal((await core.listTasks(db, { projectId: secProj.id })).length, 1, "only the helper's own story"); + // A stranger's message is ignored altogether. + tg.userSends(STRANGER, "в PAY: что-нибудь"); + await new Promise((r) => setTimeout(r, 500)); + assert.ok(!tg.botMessages(STRANGER.chatId).some((m) => /Новая стори/.test(m.text))); + }); +}); -- 2.45.2 From 53dd8a1f19489fd3800ec5799cae315fff645e80 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 06:06:26 +0500 Subject: [PATCH 003/463] PEP-46: ci test expects the extended webhook events Co-Authored-By: Claude Opus 5.5 --- packages/testkit/test/ci.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/testkit/test/ci.test.ts b/packages/testkit/test/ci.test.ts index 0e7db66c..83c93d59 100644 --- a/packages/testkit/test/ci.test.ts +++ b/packages/testkit/test/ci.test.ts @@ -65,7 +65,7 @@ describe("CI: connect a project", () => { assert.equal(registrations().length, before, "no per-repo runner for peppa-bot's repos"); const repo = gitea.repo(BOT.login, p.giteaRepo); assert.equal(repo.secrets.PEPPA_CI_SECRET, core.projectHookSecret(p.id)); - assert.deepEqual(repo.hooks.map((h) => [h.url, h.secret, h.events]), [[runner.giteaHookUrl(), core.projectHookSecret(p.id), ["pull_request", "push"]]]); + assert.deepEqual(repo.hooks.map((h) => [h.url, h.secret, h.events]), [[runner.giteaHookUrl(), core.projectHookSecret(p.id), runner.GITEA_HOOK_EVENTS]]); assert.match(runner.giteaHookUrl(), /\/api\/hooks\/gitea$/); assert.ok(r.prUrl?.endsWith("/pulls/1")); const pr = repo.pulls[0]!; -- 2.45.2 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 004/463] 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` отдаёт только свои проекты; ранжирование поиска (юнит) -- 2.45.2 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 005/463] 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); -- 2.45.2 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 006/463] 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]); + }); +}); -- 2.45.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 007/463] =?UTF-8?q?PEP-34/42:=20web=20=E2=80=94=20board=20?= =?UTF-8?q?drag=20order,=20collapsed=20Done,=20epic=20progress,=20archive,?= =?UTF-8?q?=20dependencies,=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(", ")} — планировщик их не повторит и может от них зависеть. +

+ )} +
+ +