diff --git a/AGENTS.md b/AGENTS.md
index 7c072d3e..5d496303 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -35,6 +35,7 @@
- **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 задач в работе/ревью)
- Гейты (`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
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
- Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 80de86f2..c43aca28 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -17,6 +17,7 @@ import {
getIncident,
getProject as getProjectByKey,
updateIncidentSettings,
+ setReviewSettings,
type IncidentPolicy,
changeOwnPassword,
createLocalUser,
@@ -285,6 +286,20 @@ export async function saveIncidentSettings(f: FormData) {
});
}
+// ── reviewer agent (PEP-26) ──────────────────────────────────────────────────────
+
+export async function saveReviewSettingsAction(f: FormData) {
+ const user = await requireUser();
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ await setReviewSettings(db, p.id, {
+ enabled: f.get("enabled") === "on",
+ maxIterations: Number(str(f, "maxIterations") || 2),
+ rules: str(f, "rules") || null,
+ });
+ });
+}
+
export async function decideIncidentAction(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 3d4ee315..4df796e6 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -107,6 +107,13 @@ export default async function Help() {
конфликтов. PR, меняющий конвейер (.gitea/, checks,{" "}
deploy), сам не мержится никогда.
+
+ Агент-ревьюер (по умолчанию выключен; «⋯ Настройки проекта → Ревьюер»): когда проверки PR зелёные и агент отдаёт стори в ревью,
+ короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу — сделано ли то, что просила стори, баги,
+ безопасность, тесты, мусор — и ваши дополнительные правила. Замечания уходят агенту, стори остаётся «В работе»; «ок» — стори
+ приходит вам с резюме ревьюера. После лимита возвратов (по умолчанию 2) стори приходит с незакрытыми замечаниями; если
+ ревьюер упал — с пометкой. Последнее ревью видно в карточке стори.
+
Деплой — deploy в project.json и Dockerfile (заготовки в{" "}
deploy/): PR получает preview slug-prN.telecom.quest (удаляется при
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 41018ed0..8972c29e 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 { getIncidentSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
+import { getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { AutoRefresh } from "@/components/AutoRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@@ -17,7 +17,7 @@ import { requireUser } from "@/lib/auth";
import { cn } from "@/lib/utils";
import { db } from "@/lib/db";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
-import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, setProjectVisibilityAction } from "../../actions";
+import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction } from "../../actions";
import { CodeTab, EpicsPanel, PullsTab, SpecsTab } from "./tabs";
import { setProjectPoolAction } from "../../subscriptions/actions";
@@ -66,7 +66,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] = await Promise.all([
+ const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer] = await Promise.all([
board(p.id),
listEpics(db, p.id),
projectSessions(p.id),
@@ -77,6 +77,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
listIncidents(db, p.id),
listReleases(db, p.id, 15),
currentReleases(db, p.id),
+ getReviewSettings(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);
@@ -151,6 +152,31 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
+
+
+
+ Когда проверки PR зелёные и агент отдаёт стори в ревью, короткая сессия Claude (sonnet, на подписке пула проекта) читает дифф по чек-листу. Замечания уходят агенту, «ок» — стори к вам с резюме ревьюера. После лимита возвратов стори приходит к вам с незакрытыми замечаниями.
+
+
+
!FINISHED_SESSION_STATUSES.includes(s.status))?.id;
const artifacts = openspecArtifacts(project, task.openspecChange);
const ci = await taskCiSummary(db, ref);
+ const review = await latestReview(db, task.id);
const epic = task.goalId ? await getEpic(db, project.id, task.goalId).catch(() => null) : null;
const back = `/t/${ref.key}`;
// PEP-67: superadmins choose the subscriptions a runner may take; others run on the project's pool.
@@ -58,6 +59,26 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
))}
+ {review && (
+
+
+ {review.verdict === "ok" ? : review.verdict === "changes" || review.state === "error" ? : }
+ {reviewLabel(review)}
+ {review.sha.slice(0, 7)}
+
+ {review.findings.length > 0 && (
+
+ {review.findings.map((f, i) => (
+ -
+ {f.file && {f.file}{f.line ? `:${f.line}` : ""} — }
+ {f.text}
+
+ ))}
+
+ )}
+ {ago(review.updatedAt)}
+
+ )}
{events.length === 0 ? (
Событий нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/design.md b/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/design.md
new file mode 100644
index 00000000..af65f67b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/design.md
@@ -0,0 +1,56 @@
+# Design: PEP-26 агент-ревьюер
+
+## Где включается
+Только переход в ревью **агентом** (MCP `update_task(status: review)`) после прохождения
+гейта PEP-57 (`reviewGate`). PM, двигающий карточку в «Ревью» сам, ревьюера не зовёт — он
+уже решил. Без PR (нечего ревьюить) — ревьюер пропускается.
+
+## Асинхронно, а не внутри вызова инструмента
+`claude -p` по диффу идёт 30–120 с. У Codex таймаут MCP-инструмента 60 с, поэтому
+`update_task` не ждёт ревьюера: ставит строку `code_reviews` (state `queued`, коммит головы
+PR) и сразу отвечает агенту «ревьюер проверяет, закончи ход». Запуск — сразу же
+фоновым промисом в процессе MCP; вачдог раз в тик подбирает `queued` и зависшие `running`
+(старше таймаута ×2) — если процесс MCP умер. Захват строки — атомарный `UPDATE … WHERE
+state = 'queued'`, двойного запуска нет.
+
+Пока ревью в очереди или идёт, Stop-хук не подгоняет агента («продолжай») и не шлёт PM
+«сессия ждёт» — сессия просто `waiting_input`.
+
+## Итог ревью
+- `ok`: стори → `review` (если всё ещё `in_progress`/`proposing`), вопрос `attention`
+ «✅ готово к ревью» с резюме ревьюера, привязанный к активной сессии (кнопка «Принять»
+ работает как раньше — `isReviewQuestion`).
+- `changes`: сообщение агенту со списком замечаний (`sendToSession`), без живой сессии —
+ `moveTask(in_progress, {prompt})`. Повторный `update_task(review)` после правок и
+ зелёного CI запустит ревью нового коммита.
+- лимит: число ревью с вердиктом `changes` по стори ≥ `max_iterations` → следующий
+ `update_task(review)` пускает к PM без ревьюера, в «готово к ревью» — «ревьюер: лимит
+ итераций, последние замечания …».
+- ошибка ревьюера: стори к PM с «ревьюер не отработал: <причина>».
+- Ревью уже есть для этого же коммита (`ok`) — повтор не запускается, сразу в ревью.
+- Стори ушла из работы (PM перетащил) до окончания — результат записывается, но стори не
+ двигается.
+
+## Промпт и модель
+`$PEPPA_REVIEW_BIN` (по умолчанию `claude`) `-p --output-format json --max-turns 1
+--model $PEPPA_REVIEW_MODEL` (по умолчанию `sonnet`: заметно дешевле opus, haiku для
+ревью кода слабоват), пустой временный cwd, токен — `claudeTokenForProject` (подписка пула
+проекта, PEP-67). Дифф PR — `GET /repos/{o}/{r}/pulls/{n}.diff` (обрезается до 120 КБ с
+пометкой). Чек-лист: соответствие описанию стори, баги/краевые случаи, безопасность
+(секреты, инъекции, доступ), тесты на новое поведение, мусор (отладка, закомментированный
+код). Только блокирующие проблемы — `changes`; стиль и вкус — не повод. Правила PM из
+настроек добавляются в промпт.
+
+Общий запуск `claude -p` (spawn, свой process group, таймаут, разбор JSON-конверта) вынесен
+в `runner/claude-print.ts` и используется триажом и ревьюером.
+
+## Данные
+- `review_settings(project_id PK, enabled, max_iterations, rules, updated_at)` — нет строки
+ = выключено.
+- `code_reviews(id, project_id, task_id, pr_number, sha, state queued|running|done|error,
+ verdict ok|changes|null, summary, findings json, error, started_at, created_at,
+ updated_at)`.
+
+## Не делаем
+- Комментарии ревьюера в Gitea PR (только карточка и агент).
+- Ротацию подписок на лимите ревьюера (PEP-39).
diff --git a/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/proposal.md b/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/proposal.md
new file mode 100644
index 00000000..424b76fc
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/proposal.md
@@ -0,0 +1,37 @@
+# PEP-26: Проверки качества до ревью — тесты, линт, сборка и агент-ревьюер
+
+## Зачем
+Агент сам говорит «готово». Механические проверки (lint/typecheck/test/build из `checks`
+в `.peppa/project.json`) уже есть с PEP-57: CI гоняет их на каждый PR, красное
+возвращается агенту, в ревью с красными проверками не пустит гейт. Не хватает второго
+взгляда на сам дифф: пропущенные пункты стори, явные баги, дыры в безопасности, тесты,
+которые ничего не проверяют. Это должен ловить не PM, а дешёвый агент-ревьюер до PM.
+
+## Что меняется
+- **Агент-ревьюер.** Когда агент стори просит `update_task(status: review)`, PR есть и
+ проверки его последнего коммита зелёные, а в проекте включён ревьюер — стори не идёт к
+ PM сразу. Пеппа ставит в очередь короткое ревью: один вызов `claude -p` (модель
+ подешевле, по умолчанию `sonnet`, на подписке пула проекта, как триаж PEP-58) по
+ мини-промпту с описанием стори, чек-листом и диффом PR. Ответ — JSON
+ `{verdict: ok|changes, summary, findings[]}`.
+ - `changes` → замечания уходят агенту стори (как красный CI: в живой раннер или новым
+ раннером), стори остаётся «В работе».
+ - `ok` → стори уходит в «Ревью», PM получает «готово к ревью» с резюме ревьюера.
+ - Ревьюер упал/не по формату/таймаут → стори уходит к PM с пометкой (fail open, как гейт).
+ - Лимит итераций (по умолчанию 2 возврата): дальше стори уходит к PM с незакрытыми
+ замечаниями.
+- **Настройка проекта** «⋯ Настройки проекта → Ревьюер»: вкл/выкл (по умолчанию выкл —
+ не тратить подписки без решения PM), лимит итераций, дополнительные правила
+ ревьюера от PM.
+- **Карточка стори** и MCP `get_task` показывают последнее ревью: вердикт, резюме,
+ замечания, коммит.
+- **Шаблон**: пример `lint` в `checks` шаблонного `.peppa/project.json` (линт уже работает
+ через CI, если команда есть).
+
+## Влияние
+- БД: таблицы `review_settings`, `code_reviews` (миграция).
+- core: `reviews.ts`; runner: `reviewer.ts` (запуск, очередь, вачдог), общий запуск
+ `claude -p` вынесен из триажа; MCP `update_task`; хук Stop не подгоняет агента, пока ждёт
+ ревьюер; Gitea-клиент: дифф PR.
+- testkit: `mock-reviewer`, `mock-gitea` отдаёт `.diff`, тесты `reviewer.test.ts`.
+- Внешних зависимостей нет: настоящий `claude -p` с токеном пула проекта, как триаж.
diff --git a/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/specs/delivery-pipeline/spec.md b/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/specs/delivery-pipeline/spec.md
new file mode 100644
index 00000000..39b331c1
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/specs/delivery-pipeline/spec.md
@@ -0,0 +1,31 @@
+## ADDED Requirements
+
+### Requirement: Агент-ревьюер до ревью PM
+Если в проекте включён ревьюер, переход стори агентом в «Ревью» при зелёных проверках PR SHALL сначала проходить ревью диффа отдельным коротким агентом; замечания SHALL возвращаться агенту стори, а одобренная стори — попадать к PM с резюме ревьюера. По умолчанию ревьюер выключен.
+
+#### Scenario: Ревьюер нашёл проблемы
+- **GIVEN** проект «PAY» с включённым ревьюером и стори PAY-7 с зелёными проверками PR
+- **WHEN** агент переводит PAY-7 в «Ревью», а ревьюер отвечает замечаниями
+- **THEN** агент PAY-7 получает сообщение с замечаниями ревьюера
+- **AND** PAY-7 остаётся «В работе», PM ничего не получает
+
+#### Scenario: Ревьюер одобрил
+- **GIVEN** проект «PAY» с включённым ревьюером и стори PAY-7 с зелёными проверками PR
+- **WHEN** агент переводит PAY-7 в «Ревью», а ревьюер отвечает «ок»
+- **THEN** PAY-7 в «Ревью», PM получает «готово к ревью» с резюме ревьюера
+- **AND** в карточке PAY-7 видно вердикт и резюме ревьюера
+
+#### Scenario: Лимит итераций
+- **GIVEN** ревьюер уже дважды вернул PAY-7 агенту при лимите 2
+- **WHEN** агент снова переводит PAY-7 в «Ревью»
+- **THEN** PAY-7 уходит к PM без нового ревью, с последними замечаниями ревьюера
+
+#### Scenario: Ревьюер не отработал
+- **GIVEN** проект с включённым ревьюером
+- **WHEN** ревьюер падает или отвечает не по формату
+- **THEN** стори уходит к PM с пометкой «ревьюер не отработал» и причиной
+
+#### Scenario: Ревьюер выключен
+- **GIVEN** проект, где PM не включал ревьюер
+- **WHEN** агент переводит стори с зелёными проверками в «Ревью»
+- **THEN** стори сразу в «Ревью», ревьюер не вызывается
diff --git a/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/tasks.md b/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/tasks.md
new file mode 100644
index 00000000..f98ec3f2
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-26-code-reviewer/tasks.md
@@ -0,0 +1,10 @@
+# Tasks: PEP-26
+
+- [x] 1.1 Схема: `review_settings`, `code_reviews`; миграция `pnpm db:generate`
+- [x] 1.2 core `reviews.ts`: настройки ревьюера, очередь и захват ревью, последнее ревью стори, число итераций; Gitea `pullDiff`
+- [x] 1.3 runner: `claude-print.ts` (общий запуск `claude -p`, триаж на нём), `reviewer.ts` — промпт, разбор, `runCodeReview`, `requestReview` (решение при `update_task(review)`), применение итога, `reviewTick` в вачдоге
+- [x] 1.4 MCP `update_task(review)` через ревьюер; Stop-хук не подгоняет при ожидающем ревью; `get_task` показывает ревью
+- [x] 1.5 Веб: «⋯ Настройки проекта → Ревьюер» (вкл/выкл, лимит, правила), ревью в карточке стори
+- [x] 1.6 Шаблон: пример `lint` в `checks`
+- [x] 1.7 testkit: `mock-reviewer`, `.diff` в `mock-gitea`, `reviewer.test.ts` по сценариям спеки
+- [x] 1.8 AGENTS.md, «Помощь», `openspec validate`
diff --git a/openspec/specs/delivery-pipeline/spec.md b/openspec/specs/delivery-pipeline/spec.md
index b143d246..9216d26f 100644
--- a/openspec/specs/delivery-pipeline/spec.md
+++ b/openspec/specs/delivery-pipeline/spec.md
@@ -81,3 +81,33 @@
- **WHEN** PR агента меняет команду «test» в настройках проверок
- **THEN** PR не мержится автоматически
- **AND** PM получает вопрос с описанием изменения конвейера
+
+### Requirement: Агент-ревьюер до ревью PM
+Если в проекте включён ревьюер, переход стори агентом в «Ревью» при зелёных проверках PR SHALL сначала проходить ревью диффа отдельным коротким агентом; замечания SHALL возвращаться агенту стори, а одобренная стори — попадать к PM с резюме ревьюера. По умолчанию ревьюер выключен.
+
+#### Scenario: Ревьюер нашёл проблемы
+- **GIVEN** проект «PAY» с включённым ревьюером и стори PAY-7 с зелёными проверками PR
+- **WHEN** агент переводит PAY-7 в «Ревью», а ревьюер отвечает замечаниями
+- **THEN** агент PAY-7 получает сообщение с замечаниями ревьюера
+- **AND** PAY-7 остаётся «В работе», PM ничего не получает
+
+#### Scenario: Ревьюер одобрил
+- **GIVEN** проект «PAY» с включённым ревьюером и стори PAY-7 с зелёными проверками PR
+- **WHEN** агент переводит PAY-7 в «Ревью», а ревьюер отвечает «ок»
+- **THEN** PAY-7 в «Ревью», PM получает «готово к ревью» с резюме ревьюера
+- **AND** в карточке PAY-7 видно вердикт и резюме ревьюера
+
+#### Scenario: Лимит итераций
+- **GIVEN** ревьюер уже дважды вернул PAY-7 агенту при лимите 2
+- **WHEN** агент снова переводит PAY-7 в «Ревью»
+- **THEN** PAY-7 уходит к PM без нового ревью, с последними замечаниями ревьюера
+
+#### Scenario: Ревьюер не отработал
+- **GIVEN** проект с включённым ревьюером
+- **WHEN** ревьюер падает или отвечает не по формату
+- **THEN** стори уходит к PM с пометкой «ревьюер не отработал» и причиной
+
+#### Scenario: Ревьюер выключен
+- **GIVEN** проект, где PM не включал ревьюер
+- **WHEN** агент переводит стори с зелёными проверками в «Ревью»
+- **THEN** стори сразу в «Ревью», ревьюер не вызывается
diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts
index e5a77367..7d192808 100644
--- a/packages/core/src/gitea.ts
+++ b/packages/core/src/gitea.ts
@@ -220,6 +220,15 @@ export class GiteaClient {
return files.map((f) => f.filename);
}
+ /** Unified diff of a pull request (text, not JSON). */
+ async pullDiff(owner: string, repo: string, n: number): Promise {
+ const path = `${this.repoPath(owner, repo)}/pulls/${n}.diff`;
+ const res = await fetch(`${this.baseUrl}/api/v1${path}`, { headers: { Authorization: `token ${this.token}` }, signal: AbortSignal.timeout(30_000) });
+ const text = await res.text();
+ if (!res.ok) throw new GiteaError(res.status, `Gitea GET ${path}: ${res.status} ${text}`.slice(0, 400));
+ return text;
+ }
+
/** Merges a PR; `sha` guards against merging a head that changed since the checks. */
mergePullRequest(owner: string, repo: string, n: number, sha?: string) {
return this.request("POST", `${this.repoPath(owner, repo)}/pulls/${n}/merge`, { Do: "merge", head_commit_id: sha, delete_branch_after_merge: true });
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 840698bf..e42317b0 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -21,3 +21,4 @@ export * from "./egov.ts";
export * from "./local-users.ts";
export * from "./specs.ts";
export * from "./subscriptions.ts";
+export * from "./reviews.ts";
diff --git a/packages/core/src/reviews.ts b/packages/core/src/reviews.ts
new file mode 100644
index 00000000..4ad5f060
--- /dev/null
+++ b/packages/core/src/reviews.ts
@@ -0,0 +1,123 @@
+// Reviewer agent of a project (PEP-26): settings, the review queue and what the task card shows.
+// Running the reviewer itself lives in the runner (runner/reviewer.ts).
+import { codeReviews, reviewSettings, type Db, type ReviewFinding } from "@peppa/db";
+import { and, count, desc, eq, inArray, isNull, lt, or, sql } from "drizzle-orm";
+import { PeppaError } from "./errors.ts";
+
+export type ReviewSettings = typeof reviewSettings.$inferSelect;
+export type CodeReview = typeof codeReviews.$inferSelect;
+export type { ReviewFinding };
+
+export const DEFAULT_REVIEW_ITERATIONS = 2;
+export const MAX_REVIEW_ITERATIONS = 10;
+
+/** Settings of a project's reviewer; a project that never turned it on gets the defaults (off). */
+export async function getReviewSettings(db: Db, projectId: number): Promise {
+ const [row] = await db.select().from(reviewSettings).where(eq(reviewSettings.projectId, projectId));
+ return row ?? { projectId, enabled: false, maxIterations: DEFAULT_REVIEW_ITERATIONS, rules: null, updatedAt: new Date(0) };
+}
+
+export interface ReviewSettingsPatch {
+ enabled?: boolean;
+ maxIterations?: number;
+ rules?: string | null;
+}
+
+export async function setReviewSettings(db: Db, projectId: number, patch: ReviewSettingsPatch): Promise {
+ if (patch.maxIterations !== undefined && (!Number.isInteger(patch.maxIterations) || patch.maxIterations < 1 || patch.maxIterations > MAX_REVIEW_ITERATIONS)) {
+ throw new PeppaError(`Лимит итераций ревьюера — от 1 до ${MAX_REVIEW_ITERATIONS}`);
+ }
+ const values = {
+ ...(patch.enabled !== undefined ? { enabled: patch.enabled } : {}),
+ ...(patch.maxIterations !== undefined ? { maxIterations: patch.maxIterations } : {}),
+ ...(patch.rules !== undefined ? { rules: patch.rules?.trim() || null } : {}),
+ };
+ const [row] = await db
+ .insert(reviewSettings)
+ .values({ projectId, ...values })
+ .onConflictDoUpdate({ target: reviewSettings.projectId, set: { ...values, updatedAt: new Date() } })
+ .returning();
+ return row!;
+}
+
+/** Latest review of a task (any state), for the card and MCP. */
+export async function latestReview(db: Db, taskId: number): Promise {
+ const [row] = await db.select().from(codeReviews).where(eq(codeReviews.taskId, taskId)).orderBy(desc(codeReviews.id)).limit(1);
+ return row ?? null;
+}
+
+/** A review of the task that is queued or running (the agent waits for it). */
+export async function pendingReview(db: Db, taskId: number): Promise {
+ const [row] = await db
+ .select()
+ .from(codeReviews)
+ .where(and(eq(codeReviews.taskId, taskId), inArray(codeReviews.state, ["queued", "running"])))
+ .orderBy(desc(codeReviews.id))
+ .limit(1);
+ return row ?? null;
+}
+
+/** Times the reviewer sent the task back to its agent. */
+export async function reviewRejections(db: Db, taskId: number): Promise {
+ const [row] = await db.select({ n: count() }).from(codeReviews).where(and(eq(codeReviews.taskId, taskId), eq(codeReviews.verdict, "changes")));
+ return row?.n ?? 0;
+}
+
+export async function queueReview(db: Db, r: { projectId: number; taskId: number; prNumber: number; sha: string }): Promise {
+ const [row] = await db.insert(codeReviews).values(r).returning();
+ return row!;
+}
+
+/**
+ * Claims a review to run: a queued one, or one stuck in `running` since before `staleBefore`
+ * (the process running it died). Atomic — two claimers never get the same review.
+ */
+export async function claimReview(db: Db, id: number, staleBefore: Date): Promise {
+ const [row] = await db
+ .update(codeReviews)
+ .set({ state: "running", startedAt: new Date() })
+ .where(and(eq(codeReviews.id, id), or(eq(codeReviews.state, "queued"), and(eq(codeReviews.state, "running"), or(isNull(codeReviews.startedAt), lt(codeReviews.startedAt, staleBefore))))))
+ .returning();
+ return row ?? null;
+}
+
+/** Reviews waiting to run (queued, or running and stale), oldest first. */
+export async function reviewsToRun(db: Db, staleBefore: Date): Promise {
+ return db
+ .select()
+ .from(codeReviews)
+ .where(or(eq(codeReviews.state, "queued"), and(eq(codeReviews.state, "running"), sql`coalesce(${codeReviews.startedAt}, 0) < ${staleBefore.getTime()}`)))
+ .orderBy(codeReviews.id);
+}
+
+export async function finishReview(
+ db: Db,
+ id: number,
+ r: { verdict: "ok" | "changes"; summary: string; findings: ReviewFinding[] } | { error: string },
+): Promise {
+ const values = "error" in r ? { state: "error" as const, error: r.error.slice(0, 1000) } : { state: "done" as const, verdict: r.verdict, summary: r.summary, findings: r.findings };
+ const [row] = await db.update(codeReviews).set(values).where(eq(codeReviews.id, id)).returning();
+ return row!;
+}
+
+/** Findings as a list for the agent / the PM ("• file:line — text"). */
+export function formatFindings(findings: ReviewFinding[]): string {
+ return findings
+ .map((f) => `• ${f.file ? `${f.file}${f.line ? `:${f.line}` : ""} — ` : ""}${f.severity && f.severity !== "blocker" ? `[${f.severity}] ` : ""}${f.text}`)
+ .join("\n");
+}
+
+/** One line for the task card: "Ревьюер: ок — …" / "Ревьюер: 2 замечания" / "Ревьюер проверяет…". */
+export function reviewLabel(r: CodeReview): string {
+ if (r.state === "queued" || r.state === "running") return "Ревьюер проверяет PR…";
+ if (r.state === "error") return `Ревьюер не отработал: ${r.error ?? "неизвестная ошибка"}`;
+ if (r.verdict === "ok") return `Ревьюер: ок${r.summary ? ` — ${r.summary}` : ""}`;
+ return `Ревьюер: замечаний ${r.findings.length}${r.summary ? ` — ${r.summary}` : ""}`;
+}
+
+/** Text about the latest review for the PM's "ready for review" message (empty when there is none). */
+export function reviewNote(r: CodeReview | null, limitReached = false): string {
+ if (!r || r.state === "queued" || r.state === "running") return "";
+ const head = limitReached ? `🔎 Ревьюер: лимит итераций исчерпан, последние замечания (коммит ${r.sha.slice(0, 7)}):` : `🔎 ${reviewLabel(r)}`;
+ return r.verdict === "changes" && r.findings.length ? `${head}\n${formatFindings(r.findings)}` : head;
+}
diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts
index 40f1b93d..fd9c116b 100644
--- a/packages/core/src/tasks.ts
+++ b/packages/core/src/tasks.ts
@@ -6,6 +6,7 @@ import { notify } from "./notify.ts";
import { getGoal, getProject, type Goal, type Project } from "./projects.ts";
import { incidentForTask, type Incident } from "./incidents.ts";
import { taskCiSummary, type CiSummary } from "./ci.ts";
+import { latestReview, type CodeReview } from "./reviews.ts";
export type Task = typeof tasks.$inferSelect;
export type TaskStatus = (typeof taskStatus.enumValues)[number];
@@ -128,6 +129,8 @@ export interface TaskDetails {
incident: Incident | null;
/** CI checks of the task's latest commit (PEP-57). */
ci: CiSummary;
+ /** Latest review by the project's reviewer agent (PEP-26), if any. */
+ review: CodeReview | null;
}
export async function getTaskDetails(db: Db, ref: TaskRef): Promise {
@@ -140,7 +143,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) };
+ 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) };
}
export interface NewQuestion {
diff --git a/packages/db/migrations/0004_code_reviewer.sql b/packages/db/migrations/0004_code_reviewer.sql
new file mode 100644
index 00000000..91a5c0be
--- /dev/null
+++ b/packages/db/migrations/0004_code_reviewer.sql
@@ -0,0 +1,26 @@
+CREATE TABLE `code_reviews` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `task_id` integer NOT NULL,
+ `pr_number` integer NOT NULL,
+ `sha` text NOT NULL,
+ `state` text DEFAULT 'queued' NOT NULL,
+ `verdict` text,
+ `summary` text,
+ `findings` text DEFAULT '[]' NOT NULL,
+ `error` text,
+ `started_at` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE TABLE `review_settings` (
+ `project_id` integer PRIMARY KEY NOT NULL,
+ `enabled` integer DEFAULT false NOT NULL,
+ `max_iterations` integer DEFAULT 2 NOT NULL,
+ `rules` text,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade
+);
diff --git a/packages/db/migrations/meta/0004_snapshot.json b/packages/db/migrations/meta/0004_snapshot.json
new file mode 100644
index 00000000..63dcde75
--- /dev/null
+++ b/packages/db/migrations/meta/0004_snapshot.json
@@ -0,0 +1,2764 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "e01baa2c-52bb-40aa-b39c-2490acbcd458",
+ "prevId": "922324fb-4f7c-4dd7-9cb7-7cb03780a882",
+ "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": {}
+ },
+ "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
+ },
+ "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
+ },
+ "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
+ },
+ "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
+ }
+ },
+ "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 bee3921a..3345217f 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -29,6 +29,13 @@
"when": 1794608984819,
"tag": "0003_subscriptions",
"breakpoints": true
+ },
+ {
+ "idx": 4,
+ "version": "6",
+ "when": 1794613008393,
+ "tag": "0004_code_reviewer",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index a7e88503..e0bd7cb7 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -358,6 +358,36 @@ export const oauthTokens = sqliteTable("oauth_tokens", {
lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }),
});
+/** PEP-26: the reviewer agent of a project (no row = off). */
+export const reviewSettings = sqliteTable("review_settings", {
+ projectId: integer("project_id").primaryKey().references(() => projects.id, { onDelete: "cascade" }),
+ enabled: integer("enabled", { mode: "boolean" }).notNull().default(false),
+ // Times the reviewer may send a story back before it goes to the PM as is.
+ maxIterations: integer("max_iterations").notNull().default(2),
+ // Extra rules of the PM for the reviewer, appended to the checklist.
+ rules: text("rules"),
+ updatedAt: updatedAt(),
+});
+
+export type ReviewFinding = { file?: string; line?: number; severity?: string; text: string };
+
+/** PEP-26: one review of a story's PR head by the reviewer agent. */
+export const codeReviews = sqliteTable("code_reviews", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ taskId: integer("task_id").notNull().references(() => tasks.id, { onDelete: "cascade" }),
+ prNumber: integer("pr_number").notNull(),
+ sha: text("sha").notNull(),
+ state: text("state", { enum: ["queued", "running", "done", "error"] }).notNull().default("queued"),
+ verdict: text("verdict", { enum: ["ok", "changes"] }),
+ summary: text("summary"),
+ findings: text("findings", { mode: "json" }).$type().notNull().default([]),
+ error: text("error"),
+ startedAt: integer("started_at", { mode: "timestamp_ms" }),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+});
+
export const incidentPolicies = ["notify", "backlog", "start", "ask", "triage"] as const;
export type IncidentPolicy = (typeof incidentPolicies)[number];
diff --git a/packages/mcp/src/format.ts b/packages/mcp/src/format.ts
index c30e92c7..a57631eb 100644
--- a/packages/mcp/src/format.ts
+++ b/packages/mcp/src/format.ts
@@ -1,4 +1,4 @@
-import { INCIDENT_STATUS_RU, type Incident, type TaskDetails, type TaskStatus } from "@peppa/core";
+import { formatFindings, INCIDENT_STATUS_RU, reviewLabel, type Incident, type TaskDetails, type TaskStatus } from "@peppa/core";
const NEXT_STEP: Record = {
backlog: "Proposal (workflow openspec-propose) → update_task(status: proposing, openspec_change) → если нет архитектурных решений, сразу update_task(status: in_progress) и Apply в этом же ходе.",
@@ -23,6 +23,10 @@ export function formatTask(d: TaskDetails): string {
if (task.prUrl) lines.push(`- PR: ${task.prUrl}`);
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) {
+ lines.push(`- ${reviewLabel(d.review)} (коммит ${d.review.sha.slice(0, 7)})`);
+ if (d.review.verdict === "changes") lines.push(formatFindings(d.review.findings).replace(/^/gm, " "));
+ }
lines.push("", "## Описание", "", task.description?.trim() || "_нет описания_");
if (goal?.description) lines.push("", `## Эпик #${goal.id}: ${goal.title}`, "", goal.description.trim());
if (d.incident) lines.push("", "## Инцидент", "", formatIncident(d.incident));
diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts
index ad0e3937..be92198b 100644
--- a/packages/mcp/src/index.ts
+++ b/packages/mcp/src/index.ts
@@ -21,7 +21,7 @@ import {
updateTask,
} from "@peppa/core";
import { createDb } from "@peppa/db";
-import { reviewGate } from "@peppa/runner";
+import { requestReview, reviewGate } from "@peppa/runner";
import { z } from "zod";
import { formatIncident, formatTask } from "./format.ts";
@@ -139,6 +139,15 @@ tool(
throw new PeppaError(`Not moved to review: ${reason}. Wait for the CI checks of the PR's last commit to pass (red ones come back to you with the log), then set status: review again.`);
}
}
+ if (status === "review" && ref.task.status !== "review") {
+ // PEP-26: the project's reviewer agent reads the diff before the PM (when turned on).
+ const withPr = { ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } };
+ const r = await requestReview(db, withPr).catch(() => ({ action: "review" as const }));
+ if (r.action === "queued") {
+ await updateTask(db, ref, { openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
+ return `${ref.key}: the reviewer agent is checking PR commit ${r.review.sha.slice(0, 7)} (review #${r.review.id}); the story stays in_progress. End your turn now — findings come back to you as a message; if the review is fine the story goes to the PM's review by itself.`;
+ }
+ }
const t = await updateTask(db, ref, { status, openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
return `${ref.key} updated: status=${t.status}${t.openspecChange ? `, change=${t.openspecChange}` : ""}${t.prUrl ? `, pr=${t.prUrl}` : ""}`;
},
diff --git a/packages/runner/src/claude-print.ts b/packages/runner/src/claude-print.ts
new file mode 100644
index 00000000..d77fe847
--- /dev/null
+++ b/packages/runner/src/claude-print.ts
@@ -0,0 +1,72 @@
+// One short non-interactive Claude call (`claude -p --output-format json`) on a Claude
+// subscription of the project's pool (PEP-67). Used by the incident triager (PEP-58) and the
+// reviewer agent (PEP-26); tests point `bin` at mock-triage / mock-reviewer.
+import { spawn } from "node:child_process";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { claudeTokenForProject, type Project } from "@peppa/core";
+import type { Db } from "@peppa/db";
+
+export interface ClaudePrintOptions {
+ bin: string;
+ model: string;
+ prompt: string;
+ timeoutMs: number;
+ /** For error messages: "триажёр", "ревьюер". */
+ who: string;
+}
+
+export type ClaudePrintResult = { ok: true; text: string } | { ok: false; error: string };
+
+/** Text answer from the CLI's JSON envelope (or the raw output when it isn't one); null on an error envelope. */
+export function envelopeText(stdout: string): string | null {
+ const text = stdout.trim();
+ try {
+ const env = JSON.parse(text) as { result?: unknown; is_error?: boolean };
+ if (env && typeof env === "object" && "result" in env) return env.is_error ? null : String(env.result ?? "");
+ } catch {}
+ return text;
+}
+
+export async function claudePrint(db: Db, project: Pick, o: ClaudePrintOptions): Promise {
+ const token = await claudeTokenForProject(db, project).catch(() => null);
+ // An empty cwd: no project CLAUDE.md, MCP servers or hooks get pulled in.
+ const cwd = mkdtempSync(join(tmpdir(), "peppa-print-"));
+ try {
+ const out = await new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
+ const child = spawn(o.bin, ["-p", "--output-format", "json", "--max-turns", "1", "--model", o.model], {
+ cwd,
+ env: { ...process.env, ...(token ? { CLAUDE_CODE_OAUTH_TOKEN: token } : {}) },
+ stdio: ["pipe", "pipe", "pipe"],
+ // Own process group: a timeout kills the CLI with whatever it spawned.
+ detached: true,
+ });
+ let stdout = "";
+ let stderr = "";
+ const timer = setTimeout(() => {
+ try {
+ process.kill(-child.pid!, "SIGKILL");
+ } catch {
+ child.kill("SIGKILL");
+ }
+ child.stdout.destroy();
+ child.stderr.destroy();
+ reject(new Error(`${o.who} не ответил за ${Math.round(o.timeoutMs / 1000)} с`));
+ }, o.timeoutMs);
+ child.stdout.on("data", (d) => (stdout += d));
+ child.stderr.on("data", (d) => (stderr += d));
+ child.on("error", (e) => (clearTimeout(timer), reject(e)));
+ child.on("close", (code) => (clearTimeout(timer), resolve({ code, stdout, stderr })));
+ child.stdin.on("error", () => {}); // the CLI may exit before reading a large prompt
+ child.stdin.end(o.prompt);
+ });
+ if (out.code !== 0) return { ok: false, error: `${o.who} завершился с кодом ${out.code}: ${out.stderr.trim().slice(0, 200)}` };
+ const text = envelopeText(out.stdout);
+ return text === null ? { ok: false, error: `${o.who} ответил ошибкой` } : { ok: true, text };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ } finally {
+ rmSync(cwd, { recursive: true, force: true });
+ }
+}
diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts
index bcd29c6b..ba974385 100644
--- a/packages/runner/src/hook.ts
+++ b/packages/runner/src/hook.ts
@@ -8,6 +8,11 @@ import { join } from "node:path";
import {
answerQuestion,
getQuestion,
+ getReviewSettings,
+ latestReview,
+ pendingReview,
+ reviewNote,
+ reviewRejections,
getSession,
logSessionEvent,
peppaInputSentAt,
@@ -180,11 +185,20 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
}
const [task] = s.taskId ? await db.select().from(tasks).where(eq(tasks.id, s.taskId)) : [];
if (task?.status === "review") {
- await raiseSessionQuestion(db, s, "attention", clip(`✅ Стори ${s.taskKey} готова к ревью${task.prUrl ? ` · PR: ${task.prUrl}` : ""}\n\n${text ?? ""}`.trim()));
+ // 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()));
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
const working = task && ["proposing", "in_progress"].includes(task.status);
+ // PEP-26: the reviewer agent is checking the PR — its result comes to the agent or the PM by itself.
+ if (working && (await pendingReview(db, task.id))) {
+ await logSessionEvent(db, s, "awaiting_review", {});
+ await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
+ return null;
+ }
if (canContinue && working && s.autoNudges < MAX_AUTO_NUDGES) {
await updateSession(db, s.id, { autoNudges: s.autoNudges + 1, status: "running", lastActivityAt: new Date() });
await logSessionEvent(db, s, "auto_continue", { n: s.autoNudges + 1 });
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index 6bddf50f..783e6467 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -19,3 +19,5 @@ export * from "./deploy.ts";
export * from "./platform-release.ts";
export * from "./code.ts";
export * from "./terminal.ts";
+export * from "./claude-print.ts";
+export * from "./reviewer.ts";
diff --git a/packages/runner/src/reviewer.ts b/packages/runner/src/reviewer.ts
new file mode 100644
index 00000000..4ef8f12e
--- /dev/null
+++ b/packages/runner/src/reviewer.ts
@@ -0,0 +1,219 @@
+// Reviewer agent (PEP-26): before a story with green checks reaches the PM, one short
+// `claude -p` call reviews the PR diff. Findings go back to the story's agent like a red CI
+// run; "ok" moves the story to review with the reviewer's summary. Off unless the PM turns it
+// on in the project settings. Tests use mock-reviewer (same contract as the CLI).
+import {
+ askPm,
+ claimReview,
+ finishReview,
+ formatFindings,
+ getReviewSettings,
+ giteaForBot,
+ latestReview,
+ listSessions,
+ pendingReview,
+ queueReview,
+ raiseSessionQuestion,
+ resolveTask,
+ reviewNote,
+ reviewRejections,
+ reviewsToRun,
+ taskPrNumber,
+ updateTask,
+ type CodeReview,
+ type GiteaClient,
+ type ReviewFinding,
+ type TaskRef,
+} from "@peppa/core";
+import { projects, tasks, type Db } from "@peppa/db";
+import { formatTaskKey } from "@peppa/shared";
+import { eq } from "drizzle-orm";
+import { claudePrint } from "./claude-print.ts";
+import { sendToSession } from "./sessions.ts";
+import { moveTask } from "./flow.ts";
+
+export interface ReviewVerdict {
+ verdict: "ok" | "changes";
+ summary: string;
+ findings: ReviewFinding[];
+}
+
+/** The diff the reviewer sees is cut to this many characters. */
+export const REVIEW_DIFF_LIMIT = 120_000;
+const reviewTimeoutMs = () => Number(process.env.PEPPA_REVIEW_TIMEOUT_MS ?? 300_000);
+
+export function reviewPrompt(ref: Pick & { task: { title: string; description: string | null } }, diff: string, rules: string | null): string {
+ const cut = diff.length > REVIEW_DIFF_LIMIT;
+ return [
+ "Ты — ревьюер кода софтвейр-фабрики Пеппа. Агент сделал стори и открыл PR; автоматические проверки (lint, typecheck, test, build) уже зелёные.",
+ "Прочитай дифф и реши, можно ли отдавать стори PM на приёмку. Чек-лист:",
+ "1. Сделано то, что просит стори (ничего важного не пропущено и не сделано лишнего).",
+ "2. Нет явных багов: краевые случаи, ошибки, гонки, потеря данных.",
+ "3. Безопасность: нет секретов в коде, инъекций, обхода проверок доступа.",
+ "4. Новое поведение покрыто тестами, тесты действительно что-то проверяют.",
+ "5. Нет мусора: отладочного вывода, закомментированного кода, временных файлов.",
+ 'Вердикт "changes" — только при проблемах, которые надо исправить до приёмки. Стиль, вкус и мелкие улучшения — не повод: при них "ok" (можешь упомянуть в summary).',
+ ...(rules?.trim() ? ["", "Дополнительные правила PM:", rules.trim()] : []),
+ "",
+ `Проект: ${ref.project.key} — ${ref.project.name}`,
+ `Стори ${ref.key}: ${ref.task.title}`,
+ "Описание стори:",
+ ref.task.description?.trim() || "(нет)",
+ "",
+ `Дифф PR${cut ? ` (обрезан до ${REVIEW_DIFF_LIMIT} символов)` : ""}:`,
+ "```diff",
+ cut ? diff.slice(0, REVIEW_DIFF_LIMIT) : diff,
+ "```",
+ "",
+ 'Ответь ОДНИМ JSON без пояснений: {"verdict":"ok|changes","summary":"1–2 предложения по-русски","findings":[{"file":"путь","line":12,"severity":"blocker|major|minor","text":"что не так и как исправить"}]}',
+ ].join("\n");
+}
+
+/** The verdict from the reviewer's answer (bare JSON, or JSON inside text / a code fence). */
+export function parseReviewOutput(text: string): ReviewVerdict | null {
+ const start = text.indexOf("{");
+ const end = text.lastIndexOf("}");
+ if (start < 0 || end <= start) return null;
+ try {
+ const d = JSON.parse(text.slice(start, end + 1)) as { verdict?: unknown; summary?: unknown; findings?: unknown };
+ if (d.verdict !== "ok" && d.verdict !== "changes") return null;
+ const findings: ReviewFinding[] = (Array.isArray(d.findings) ? d.findings : [])
+ .filter((f): f is Record => !!f && typeof f === "object" && typeof (f as { text?: unknown }).text === "string")
+ .slice(0, 30)
+ .map((f) => ({
+ text: String(f.text).slice(0, 1000),
+ ...(typeof f.file === "string" && f.file ? { file: f.file.slice(0, 300) } : {}),
+ ...(Number.isInteger(f.line) && (f.line as number) > 0 ? { line: f.line as number } : {}),
+ ...(typeof f.severity === "string" ? { severity: f.severity.slice(0, 20) } : {}),
+ }));
+ // "changes" without anything to fix is not actionable for the agent.
+ if (d.verdict === "changes" && !findings.length) return null;
+ return { verdict: d.verdict, summary: String(d.summary ?? "").slice(0, 500), findings };
+ } catch {
+ return null;
+ }
+}
+
+/** Runs `$PEPPA_REVIEW_BIN -p` (default `claude`, model `sonnet`) on the project's pool subscription. */
+export async function runReviewer(db: Db, ref: TaskRef, diff: string, rules: string | null): Promise<{ ok: true; verdict: ReviewVerdict } | { ok: false; error: string }> {
+ const out = await claudePrint(db, ref.project, {
+ bin: process.env.PEPPA_REVIEW_BIN ?? "claude",
+ model: process.env.PEPPA_REVIEW_MODEL ?? "sonnet",
+ timeoutMs: reviewTimeoutMs(),
+ prompt: reviewPrompt(ref, diff, rules),
+ who: "ревьюер",
+ });
+ if (!out.ok) return out;
+ const verdict = parseReviewOutput(out.text);
+ return verdict ? { ok: true, verdict } : { ok: false, error: "ревьюер ответил не по формату" };
+}
+
+export type ReviewRequest =
+ /** Go to review now; `note` — what to tell the PM about the reviewer. */
+ | { action: "review"; note?: string }
+ /** A review is queued/running: the story stays in work, the agent ends its turn. */
+ | { action: "queued"; review: CodeReview };
+
+/**
+ * The agent asks for review and the CI gate passed: decides whether the reviewer runs first.
+ * Off, no PR, Gitea unreachable → review now. Same head already approved → review now.
+ * Rejected `maxIterations` times already → review now with the last findings.
+ */
+export async function requestReview(db: Db, ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise {
+ const settings = await getReviewSettings(db, ref.project.id);
+ if (!settings.enabled) return { action: "review" };
+ const n = taskPrNumber(ref.project, ref.task.prUrl);
+ if (!n) return { action: "review" };
+ let sha: string;
+ try {
+ const pull = await gitea.getPullRequest(ref.project.giteaOwner, ref.project.giteaRepo, n);
+ if (pull.merged) return { action: "review" };
+ sha = pull.head.sha;
+ } catch (e) {
+ return { action: "review", note: `🔎 Ревьюер не запускался: Gitea недоступна (${(e as Error).message.slice(0, 120)})` };
+ }
+ const pending = await pendingReview(db, ref.task.id);
+ if (pending?.sha === sha) return { action: "queued", review: pending };
+ const last = await latestReview(db, ref.task.id);
+ if (last?.sha === sha && last.state === "done" && last.verdict === "ok") return { action: "review", note: reviewNote(last) };
+ if ((await reviewRejections(db, ref.task.id)) >= settings.maxIterations) return { action: "review", note: reviewNote(last, true) };
+ const review = await queueReview(db, { projectId: ref.project.id, taskId: ref.task.id, prNumber: n, sha });
+ startReview(db, review.id);
+ return { action: "queued", review };
+}
+
+const inFlight = new Set();
+
+/** Runs a review in the background of this process (MCP server or watchdog). */
+export function startReview(db: Db, id: number, log: (m: string) => void = () => {}): void {
+ if (inFlight.has(id)) return;
+ inFlight.add(id);
+ processReview(db, id)
+ .catch((e) => log(`review #${id}: ${(e as Error).message}`))
+ .finally(() => inFlight.delete(id));
+}
+
+/** Watchdog: queued reviews whose process never ran them, and runs stuck past twice the timeout. */
+export async function reviewTick(db: Db, log: (m: string) => void = () => {}): Promise {
+ const rows = await reviewsToRun(db, new Date(Date.now() - 2 * reviewTimeoutMs()));
+ for (const r of rows) startReview(db, r.id, log);
+ return rows.length;
+}
+
+async function taskRef(db: Db, taskId: number): Promise {
+ const [t] = await db.select({ key: projects.key, number: tasks.number }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, taskId));
+ return t ? resolveTask(db, formatTaskKey(t.key, t.number)) : null;
+}
+
+/**
+ * Claims and runs one review, then acts on it: findings → the agent; ok or a broken reviewer
+ * → the story goes to review and the PM gets "ready for review". A story the PM moved out of
+ * work meanwhile is left where it is (the result is still on the card).
+ */
+export async function processReview(db: Db, id: number, gitea: GiteaClient = giteaForBot()): Promise {
+ const claimed = await claimReview(db, id, new Date(Date.now() - 2 * reviewTimeoutMs()));
+ if (!claimed) return null;
+ const ref = await taskRef(db, claimed.taskId);
+ if (!ref) return finishReview(db, id, { error: "стори не найдена" });
+ const settings = await getReviewSettings(db, ref.project.id);
+ let diff: string | null = null;
+ let error: string | null = null;
+ try {
+ diff = await gitea.pullDiff(ref.project.giteaOwner, ref.project.giteaRepo, claimed.prNumber);
+ } catch (e) {
+ error = `не удалось получить дифф PR: ${(e as Error).message.slice(0, 200)}`;
+ }
+ const res = diff !== null ? await runReviewer(db, ref, diff, settings.rules) : { ok: false as const, error: error! };
+ const review = await finishReview(db, id, res.ok ? res.verdict : { error: res.error });
+
+ const fresh = await taskRef(db, claimed.taskId);
+ if (!fresh || !["proposing", "in_progress"].includes(fresh.task.status)) return review;
+ const sessionId = (await listSessions(db, { active: true, taskId: fresh.task.id }))[0]?.id ?? null;
+
+ if (review.verdict === "changes") {
+ const iteration = await reviewRejections(db, fresh.task.id);
+ const text = [
+ `🔎 Ревьюер вернул ${fresh.key} (коммит ${review.sha.slice(0, 7)}, итерация ${iteration} из ${settings.maxIterations}): ${review.summary}`,
+ formatFindings(review.findings),
+ "Исправь замечания, запушь в ту же ветку, дождись зелёных проверок и снова update_task(status: review). Если замечание неверно — объясни это в описании PR и всё равно снова update_task(status: review).",
+ ].join("\n\n");
+ if (sessionId) {
+ try {
+ await sendToSession(db, sessionId, text);
+ return review;
+ } catch {}
+ }
+ await moveTask(db, fresh, "in_progress", { prompt: text });
+ return review;
+ }
+
+ 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 [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).
+ if (s && s.provider !== "opencode" && (s.status === "running" || s.status === "starting")) return review;
+ if (s) await raiseSessionQuestion(db, s, "attention", msg);
+ else await askPm(db, fresh, { kind: "attention", text: msg });
+ return review;
+}
diff --git a/packages/runner/src/triage.ts b/packages/runner/src/triage.ts
index 0d804496..f0f0e1f7 100644
--- a/packages/runner/src/triage.ts
+++ b/packages/runner/src/triage.ts
@@ -1,11 +1,8 @@
// Incident triage agent (PEP-58): one short non-interactive Claude call that picks what to
// do with a new error, following the PM's mini-prompt. Tests use mock-triage (same contract).
-import { spawn } from "node:child_process";
-import { mkdtempSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { claudeTokenForProject, type Incident, type Project } from "@peppa/core";
+import type { Incident, Project } from "@peppa/core";
import type { Db } from "@peppa/db";
+import { claudePrint } from "./claude-print.ts";
export interface TriageDecision {
action: "notify" | "backlog" | "start" | "ignore" | "ask";
@@ -67,44 +64,14 @@ export function parseTriageOutput(stdout: string): TriageDecision | null {
/** Runs `$PEPPA_TRIAGE_BIN -p` (default `claude`) on a Claude subscription of the project's pool (PEP-67). */
export async function runTriage(db: Db, project: Project, i: Incident, pmPrompt: string): Promise {
- const bin = process.env.PEPPA_TRIAGE_BIN ?? "claude";
- const TIMEOUT_MS = Number(process.env.PEPPA_TRIAGE_TIMEOUT_MS ?? 90_000);
- const token = await claudeTokenForProject(db, project).catch(() => null);
- // An empty cwd: no project CLAUDE.md, MCP servers or hooks get pulled in.
- const cwd = mkdtempSync(join(tmpdir(), "peppa-triage-"));
- try {
- const out = await new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
- const child = spawn(bin, ["-p", "--output-format", "json", "--max-turns", "1", "--model", process.env.PEPPA_TRIAGE_MODEL ?? "haiku"], {
- cwd,
- env: { ...process.env, ...(token ? { CLAUDE_CODE_OAUTH_TOKEN: token } : {}) },
- stdio: ["pipe", "pipe", "pipe"],
- // Own process group: a timeout kills the CLI with whatever it spawned.
- detached: true,
- });
- let stdout = "";
- let stderr = "";
- const timer = setTimeout(() => {
- try {
- process.kill(-child.pid!, "SIGKILL");
- } catch {
- child.kill("SIGKILL");
- }
- child.stdout.destroy();
- child.stderr.destroy();
- reject(new Error(`триажёр не ответил за ${Math.round(TIMEOUT_MS / 1000)} с`));
- }, TIMEOUT_MS);
- child.stdout.on("data", (d) => (stdout += d));
- child.stderr.on("data", (d) => (stderr += d));
- child.on("error", (e) => (clearTimeout(timer), reject(e)));
- child.on("close", (code) => (clearTimeout(timer), resolve({ code, stdout, stderr })));
- child.stdin.end(triagePrompt(project, i, pmPrompt));
- });
- if (out.code !== 0) return { ok: false, error: `триажёр завершился с кодом ${out.code}: ${out.stderr.trim().slice(0, 200)}` };
- const decision = parseTriageOutput(out.stdout);
- return decision ? { ok: true, decision } : { ok: false, error: "триажёр ответил не по формату" };
- } catch (e) {
- return { ok: false, error: (e as Error).message };
- } finally {
- rmSync(cwd, { recursive: true, force: true });
- }
+ const out = await claudePrint(db, project, {
+ bin: process.env.PEPPA_TRIAGE_BIN ?? "claude",
+ model: process.env.PEPPA_TRIAGE_MODEL ?? "haiku",
+ timeoutMs: Number(process.env.PEPPA_TRIAGE_TIMEOUT_MS ?? 90_000),
+ prompt: triagePrompt(project, i, pmPrompt),
+ who: "триажёр",
+ });
+ if (!out.ok) return out;
+ const decision = parseTriageOutput(out.text);
+ return decision ? { ok: true, decision } : { ok: false, error: "триажёр ответил не по формату" };
}
diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts
index 82ab5781..6c985242 100644
--- a/packages/runner/src/watchdog.ts
+++ b/packages/runner/src/watchdog.ts
@@ -18,6 +18,7 @@ import { resumeSession } from "./sessions.ts";
import { monitorTick } from "./monitor.ts";
import { incidentTick } from "./incidents.ts";
import { pollChecks } from "./ci-feedback.ts";
+import { reviewTick } from "./reviewer.ts";
export interface WatchdogOptions {
/** Current time (tests move it instead of waiting). */
@@ -136,6 +137,8 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
if (Date.now() - lastCiPoll >= 60_000) {
lastCiPoll = Date.now();
await pollChecks(db).catch((e) => log(`ci poll failed: ${(e as Error).message}`));
+ // Reviews whose MCP process died before running them (PEP-26).
+ await reviewTick(db, log).catch((e) => log(`review tick failed: ${(e as Error).message}`));
}
// Daily copy of the SQLite database (PEP-36); a no-op until a day has passed.
await backupDb(db, { log }).catch((e) => log(`backup failed: ${(e as Error).message}`));
diff --git a/packages/testkit/bin/mock-reviewer b/packages/testkit/bin/mock-reviewer
new file mode 100755
index 00000000..27b80095
--- /dev/null
+++ b/packages/testkit/bin/mock-reviewer
@@ -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-reviewer.ts" "$@"
diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts
index eb9e85a6..112c52b6 100644
--- a/packages/testkit/src/mock-gitea.ts
+++ b/packages/testkit/src/mock-gitea.ts
@@ -62,12 +62,17 @@ export class MockGitea {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
- let r: { status: number; body?: unknown };
+ let r: { status: number; body?: unknown; text?: string };
try {
r = this.handle(req.method!, req.url!, req.headers.authorization ?? "", body ? JSON.parse(body) : {});
} catch (e) {
r = { status: 422, body: { message: `mock-gitea: ${(e as Error).message.split("\n")[0]}` } };
}
+ if (r.text !== undefined) {
+ res.writeHead(r.status, { "Content-Type": "text/plain; charset=utf-8" });
+ res.end(r.text);
+ return;
+ }
res.writeHead(r.status, { "Content-Type": "application/json" });
res.end(r.body === undefined ? "" : JSON.stringify(r.body));
});
@@ -256,7 +261,7 @@ export class MockGitea {
};
}
- private handle(method: string, url: string, auth: string, body: Record): { status: number; body?: unknown } {
+ private handle(method: string, url: string, auth: string, body: Record): { status: number; body?: unknown; text?: string } {
const path = url.split("?")[0]!;
if (method === "POST" && path === "/login/oauth/access_token") {
const token = this.oauthCodes.get(String(body.code));
@@ -332,7 +337,7 @@ export class MockGitea {
return { status: 404, body: { message: `mock-gitea: ${method} ${path}` } };
}
- private handleRepo(r: MockRepo, me: MockGiteaUser, method: string, sub: string, url: string, body: Record): { status: number; body?: unknown } | null {
+ private handleRepo(r: MockRepo, me: MockGiteaUser, method: string, sub: string, url: string, body: Record): { status: number; body?: unknown; text?: string } | null {
const isAdmin = r.admins.has(me.login);
const canWrite = isAdmin || r.owner === me.login || r.collaborators[me.login] === "write" || r.collaborators[me.login] === "admin";
const q = new URLSearchParams(url.split("?")[1] ?? "");
@@ -366,6 +371,11 @@ export class MockGitea {
const state = q.get("state") ?? "open";
return { status: 200, body: r.pulls.filter((p) => state === "all" || p.state === state).map((p) => this.pullJson(r, p)) };
}
+ if (method === "GET" && (m = sub.match(/^pulls\/(\d+)\.diff$/))) {
+ const p = r.pulls.find((x) => x.number === Number(m![1]));
+ if (!p) return { status: 404, body: { message: "pull not found" } };
+ return { status: 200, text: execFileSync("git", ["--git-dir", r.path, "diff", `${p.base}...${p.head}`], { encoding: "utf8" }) };
+ }
if ((m = sub.match(/^pulls\/(\d+)(\/files|\/merge)?$/))) {
const p = r.pulls.find((x) => x.number === Number(m![1]));
if (!p) return { status: 404, body: { message: "pull not found" } };
diff --git a/packages/testkit/src/mock-reviewer.ts b/packages/testkit/src/mock-reviewer.ts
new file mode 100644
index 00000000..75e4acab
--- /dev/null
+++ b/packages/testkit/src/mock-reviewer.ts
@@ -0,0 +1,47 @@
+// mock-reviewer (PEP-26): stands in for `claude -p --output-format json` as the reviewer agent.
+// Reads the prompt (story + checklist + PR diff) on stdin, answers with the CLI's JSON envelope
+// whose `result` is the verdict. Behaviour comes from MOCK_REVIEW_SCENARIO (a JSON file):
+// { "responses": [{ "verdict": "changes", "summary": "…", "findings": [{ "file": "a.ts", "line": 3, "text": "…" }] },
+// { "verdict": "ok", "summary": "…" }], // n-th call → n-th response (last one repeats)
+// "fail": false, "hang": false, "garbage": false }
+// Every call is appended to .log.jsonl (args, story, whether the diff and PM rules came through, token).
+import { appendFileSync, existsSync, readFileSync } from "node:fs";
+
+interface Scenario {
+ responses?: Array<{ verdict: string; summary?: string; findings?: unknown[] }>;
+ fail?: boolean;
+ hang?: boolean;
+ garbage?: boolean;
+}
+
+const file = process.env.MOCK_REVIEW_SCENARIO;
+const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
+const prompt = readFileSync(0, "utf8");
+const logFile = `${file}.log.jsonl`;
+const calls = file && existsSync(logFile) ? readFileSync(logFile, "utf8").trim().split("\n").filter(Boolean).length : 0;
+if (file) {
+ appendFileSync(
+ logFile,
+ JSON.stringify({
+ args: process.argv.slice(2),
+ story: /^Стори (\S+):/m.exec(prompt)?.[1] ?? null,
+ diff: /```diff\n[\s\S]*diff --git/.test(prompt),
+ diffText: /```diff\n([\s\S]*?)\n```/.exec(prompt)?.[1] ?? "",
+ rules: /Дополнительные правила PM:\n([\s\S]*?)\n\nПроект:/.exec(prompt)?.[1] ?? null,
+ token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null,
+ }) + "\n",
+ );
+}
+if (!process.argv.includes("-p")) {
+ console.error("mock-reviewer: expected -p (non-interactive print mode)");
+ process.exit(2);
+}
+if (sc.hang) await new Promise(() => setInterval(() => {}, 1000)); // never answers
+if (sc.fail) {
+ console.error("mock-reviewer: API Error: 529 overloaded");
+ process.exit(1);
+}
+const responses = sc.responses?.length ? sc.responses : [{ verdict: "ok", summary: "mock: замечаний нет" }];
+const verdict = responses[Math.min(calls, responses.length - 1)]!;
+const result = sc.garbage ? "Выглядит неплохо, но я не уверен." : `Вот результат ревью:\n\`\`\`json\n${JSON.stringify({ findings: [], ...verdict })}\n\`\`\``;
+process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result, session_id: "mock-reviewer" }) + "\n");
diff --git a/packages/testkit/test/reviewer.test.ts b/packages/testkit/test/reviewer.test.ts
new file mode 100644
index 00000000..7d9cd837
--- /dev/null
+++ b/packages/testkit/test/reviewer.test.ts
@@ -0,0 +1,236 @@
+// PEP-26, spec delivery-pipeline «Агент-ревьюер до ревью PM» — one test per scenario, against
+// mock Gitea (PR, diff, commit statuses), mock-claude runners calling the real peppa MCP server
+// and mock-reviewer as the reviewer agent.
+import assert from "node:assert/strict";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { after, before, describe, test } from "node:test";
+import { core, db, project, runner, teardown, waitFor, type TestProject } from "./helpers.ts";
+import { MockGitea } from "../src/mock-gitea.ts";
+import type { Action } from "../src/scenario.ts";
+
+const TMP = mkdtempSync(join(tmpdir(), "peppa-review-"));
+const SCENARIO = join(TMP, "mock-review.json");
+// Set before the first runner starts: the tmux server (and the MCP servers under it) keep this env.
+Object.assign(process.env, {
+ PEPPA_SECRET: "mock-secret-for-tests",
+ PEPPA_REVIEW_BIN: resolve(fileURLToPath(import.meta.url), "../../bin/mock-reviewer"),
+ MOCK_REVIEW_SCENARIO: SCENARIO,
+ PEPPA_REVIEW_TIMEOUT_MS: "20000",
+});
+const gitea = new MockGitea(join(TMP, "gitea"));
+const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
+const CHECKS = { test: "pnpm test" };
+
+before(async () => {
+ await gitea.start();
+ process.env.GITEA_URL = gitea.url;
+ process.env.GITEA_TOKEN = BOT.token;
+ gitea.addUser(BOT);
+});
+after(async () => {
+ await gitea.stop();
+ await teardown();
+});
+
+type Review = { verdict: string; summary?: string; findings?: Array<{ file?: string; line?: number; text: string }> };
+
+/** Scenario of the mock reviewer for the next calls; returns a reader of its call log. */
+function reviewer(sc: { responses?: Review[]; fail?: boolean; garbage?: boolean }) {
+ writeFileSync(SCENARIO, JSON.stringify(sc));
+ rmSync(`${SCENARIO}.log.jsonl`, { force: true });
+ return () =>
+ existsSync(`${SCENARIO}.log.jsonl`)
+ ? readFileSync(`${SCENARIO}.log.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l) as { story: string; diff: boolean; diffText: string; rules: string | null; args: string[] })
+ : [];
+}
+
+interface ReviewTask {
+ p: TestProject;
+ proj: Awaited>;
+ ref: () => ReturnType;
+ prUrl: string;
+ /** Pushes a commit to the story branch with green checks; returns its SHA. */
+ pushGreen(files?: Record): string;
+}
+
+/** Project with a repo in mock Gitea, a story with an open PR (green checks) and a runner scenario. */
+async function reviewTask(turns: Action[][], settings?: Parameters[2]): 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", checks: CHECKS });
+ 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}`;
+ const pushGreen = (files: Record = { "src/divide.ts": "export const divide = (a: number, b: number) => a / b;\n" }) => {
+ const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, files);
+ for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${c}`, "success", { target_url: "/x/actions/runs/1" });
+ return sha;
+ };
+ pushGreen();
+ const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch);
+ const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`;
+ const ref = () => core.resolveTask(db, p.taskKey);
+ await core.updateTask(db, await ref(), { status: "in_progress", title: "Деление в калькуляторе", description: "Добавить деление; на ноль — понятная ошибка" });
+ if (settings) await core.setReviewSettings(db, proj.id, settings);
+ writeFileSync(join(p.dir, ".peppa/mock-scenario.json"), JSON.stringify({ turns: turns.map((t) => t.map((a) => ("mcp" in a && a.mcp === "update_task" ? { ...a, args: { ...a.args, pr_url: prUrl } } : a))) }));
+ return { p, proj, ref, prUrl, pushGreen };
+}
+
+const toReview: Action = { mcp: "update_task", args: { task: "1", status: "review" } };
+const readyQuestions = async (t: ReviewTask) => (await core.pendingQuestions(db, t.proj.id)).filter((q) => q.kind === "attention" && q.text.includes("готова к ревью"));
+const stopAll = async (t: ReviewTask) => {
+ for (const s of await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })) await runner.stopSession(db, s.id);
+};
+
+describe("Агент-ревьюер до ревью PM", () => {
+ test("Scenario: Ревьюер нашёл проблемы — агент получает замечания, стори в работе, PM ничего не получает", async () => {
+ const calls = reviewer({ responses: [{ verdict: "changes", summary: "нет проверки деления на ноль", findings: [{ file: "src/divide.ts", line: 1, text: "деление на ноль возвращает Infinity вместо ошибки" }] }] });
+ const t = await reviewTask([[toReview, { say: "PR открыт, жду ревьюера" }], [{ say: "чиню" }], [{ say: "ещё" }], [{ say: "и ещё" }]], { enabled: true, rules: "без новых зависимостей" });
+ await t.p.start();
+ const tool = await t.p.waitLog("update_task answered", (e) => e.ev === "mcp" && e.tool === "update_task");
+ assert.match(String(tool.text), /reviewer agent is checking/);
+ await t.p.waitLog("findings delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("деление на ноль возвращает Infinity") && String(e.prompt).includes("src/divide.ts:1"));
+ const [call] = calls();
+ assert.equal(call?.story, t.p.taskKey);
+ assert.ok(call?.diff, "the reviewer got the PR diff");
+ assert.match(call!.diffText, /export const divide/);
+ assert.equal(call?.rules, "без новых зависимостей");
+ assert.ok(call?.args.includes("--model") && call.args.includes("sonnet"), "a cheaper model");
+ assert.equal((await t.ref()).task.status, "in_progress");
+ assert.equal((await readyQuestions(t)).length, 0, "PM got no ready-for-review");
+ assert.equal((await core.pendingQuestions(db, t.proj.id)).filter((q) => q.kind !== "attention").length, 0);
+ const d = await core.getTaskDetails(db, await t.ref());
+ assert.equal(d.review?.verdict, "changes");
+ const { formatTask } = await import("../../mcp/src/format.ts");
+ assert.match(formatTask(d), /Ревьюер: замечаний 1[\s\S]*src\/divide\.ts:1 — деление на ноль/);
+ await stopAll(t);
+ });
+
+ test("Scenario: Ревьюер одобрил — стори в «Ревью», PM получает «готово к ревью» с резюме ревьюера", async () => {
+ const calls = reviewer({ responses: [{ verdict: "ok", summary: "деление и ошибка на ноль сделаны, тесты есть" }] });
+ const t = await reviewTask([[toReview, { say: "PR открыт" }], [{ say: "ок" }]], { enabled: true });
+ await t.p.start();
+ const [q] = await waitFor("ready for review", async () => {
+ const qs = await readyQuestions(t);
+ return qs.length ? qs : null;
+ });
+ assert.equal((await t.ref()).task.status, "review");
+ assert.match(q!.text, /Ревьюер: ок — деление и ошибка на ноль сделаны, тесты есть/);
+ assert.ok(await runner.isReviewQuestion(db, q!), "«Принять» works on it");
+ // Exactly one ready-for-review, whichever finished first (the agent's turn or the reviewer).
+ await new Promise((r) => setTimeout(r, 1500));
+ assert.equal((await readyQuestions(t)).length, 1);
+ assert.equal(calls().length, 1);
+ const d = await core.getTaskDetails(db, await t.ref());
+ assert.equal(d.review?.verdict, "ok");
+ assert.equal(core.reviewLabel(d.review!), "Ревьюер: ок — деление и ошибка на ноль сделаны, тесты есть");
+ await stopAll(t);
+ });
+
+ test("Scenario: Лимит итераций — стори уходит к PM без нового ревью, с последними замечаниями", async () => {
+ const calls = reviewer({ responses: [{ verdict: "ok" }] });
+ const t = await reviewTask([[toReview, { say: "PR снова открыт" }], [{ say: "ок" }]], { enabled: true, maxIterations: 2 });
+ const task = (await t.ref()).task;
+ for (let i = 0; i < 2; i++) {
+ const r = await core.queueReview(db, { projectId: t.proj.id, taskId: task.id, prNumber: 1, sha: `old${i}` });
+ await core.finishReview(db, r.id, { verdict: "changes", summary: `итерация ${i + 1}`, findings: [{ file: "src/divide.ts", text: `замечание ${i + 1}` }] });
+ }
+ await t.p.start();
+ const [q] = await waitFor("ready for review", async () => {
+ const qs = await readyQuestions(t);
+ return qs.length ? qs : null;
+ });
+ assert.equal((await t.ref()).task.status, "review");
+ assert.match(q!.text, /лимит итераций исчерпан[\s\S]*src\/divide\.ts — замечание 2/);
+ assert.equal(calls().length, 0, "the reviewer was not called again");
+ await stopAll(t);
+ });
+
+ test("Scenario: Ревьюер не отработал — стори к PM с пометкой и причиной", async () => {
+ reviewer({ fail: true });
+ const t = await reviewTask([[toReview, { say: "PR открыт" }], [{ say: "ок" }]], { enabled: true });
+ await t.p.start();
+ const [q] = await waitFor("ready for review", async () => {
+ const qs = await readyQuestions(t);
+ return qs.length ? qs : null;
+ });
+ assert.equal((await t.ref()).task.status, "review");
+ assert.match(q!.text, /Ревьюер не отработал: ревьюер завершился с кодом 1/);
+ assert.equal((await core.latestReview(db, (await t.ref()).task.id))?.state, "error");
+ await stopAll(t);
+ });
+
+ test("Scenario: Ревьюер выключен — стори сразу в «Ревью», ревьюер не вызывается", async () => {
+ const calls = reviewer({});
+ const t = await reviewTask([[toReview, { say: "PR открыт" }], [{ say: "ок" }]]);
+ await t.p.start();
+ const tool = await t.p.waitLog("update_task answered", (e) => e.ev === "mcp" && e.tool === "update_task");
+ assert.match(String(tool.text), /status=review/);
+ assert.equal((await t.ref()).task.status, "review");
+ assert.equal(calls().length, 0);
+ assert.equal(await core.latestReview(db, (await t.ref()).task.id), null);
+ await stopAll(t);
+ });
+});
+
+describe("reviewer details", () => {
+ test("parseReviewOutput: fenced JSON, garbage, «changes» without findings", () => {
+ assert.deepEqual(runner.parseReviewOutput('Итог:\n```json\n{"verdict":"ok","summary":"хорошо","findings":[]}\n```'), { verdict: "ok", summary: "хорошо", findings: [] });
+ assert.equal(runner.parseReviewOutput("всё хорошо"), null);
+ assert.equal(runner.parseReviewOutput('{"verdict":"changes","summary":"плохо","findings":[]}'), null);
+ assert.equal(runner.parseReviewOutput('{"verdict":"maybe"}'), null);
+ const v = runner.parseReviewOutput('{"verdict":"changes","summary":"s","findings":[{"file":"a.ts","line":"x","text":"t"},{"nope":1}]}');
+ assert.deepEqual(v?.findings, [{ file: "a.ts", text: "t" }]);
+ });
+
+ test("an answer not in the format is a broken reviewer; the same approved commit is not reviewed twice", async () => {
+ reviewer({ garbage: true });
+ const t = await reviewTask([], { enabled: true });
+ const ref = { ...(await t.ref()), task: { ...(await t.ref()).task, prUrl: t.prUrl } };
+ await core.updateTask(db, await t.ref(), { prUrl: t.prUrl });
+ const r = await runner.requestReview(db, ref);
+ assert.equal(r.action, "queued");
+ const done = await waitFor("review finished", async () => {
+ const x = await core.latestReview(db, ref.task.id);
+ return x && x.state !== "queued" && x.state !== "running" ? x : null;
+ });
+ assert.equal(done.error, "ревьюер ответил не по формату");
+ // No runner: the PM gets "ready for review" directly.
+ assert.equal((await t.ref()).task.status, "review");
+ assert.match((await readyQuestions(t))[0]!.text, /Ревьюер не отработал: ревьюер ответил не по формату/);
+
+ // Approved head → asking again goes straight to review with the note.
+ await core.updateTask(db, await t.ref(), { status: "in_progress" });
+ await core.finishReview(db, done.id, { verdict: "ok", summary: "ок", findings: [] });
+ const again = await runner.requestReview(db, { ...(await t.ref()) });
+ assert.deepEqual(again, { action: "review", note: "🔎 Ревьюер: ок — ок" });
+ });
+
+ test("no runner and findings: the agent is started with the findings; the watchdog runs queued reviews", async () => {
+ reviewer({ responses: [{ verdict: "changes", summary: "дыра", findings: [{ text: "нет проверки доступа к /admin" }] }] });
+ const t = await reviewTask([[{ say: "чиню доступ" }]], { enabled: true });
+ await core.updateTask(db, await t.ref(), { prUrl: t.prUrl });
+ const head = t.pushGreen({ "src/admin.ts": "export const admin = 1;\n" });
+ // Queued by an MCP process that died: the watchdog's tick picks it up.
+ const q = await core.queueReview(db, { projectId: t.proj.id, taskId: (await t.ref()).task.id, prNumber: 1, sha: head });
+ assert.equal(await runner.reviewTick(db), 1);
+ await t.p.waitLog("agent started with the findings", (e) => e.ev === "prompt" && String(e.prompt).includes("нет проверки доступа к /admin"));
+ assert.equal((await core.latestReview(db, (await t.ref()).task.id))?.id, q.id);
+ assert.equal((await t.ref()).task.status, "in_progress");
+ await stopAll(t);
+ });
+
+ test("settings: off by default, iteration limit validated", async () => {
+ const t = await reviewTask([]);
+ const s = await core.getReviewSettings(db, t.proj.id);
+ assert.equal(s.enabled, false);
+ assert.equal(s.maxIterations, 2);
+ await assert.rejects(core.setReviewSettings(db, t.proj.id, { maxIterations: 0 }), /от 1 до 10/);
+ const saved = await core.setReviewSettings(db, t.proj.id, { enabled: true, maxIterations: 3, rules: " " });
+ assert.deepEqual([saved.enabled, saved.maxIterations, saved.rules], [true, 3, null]);
+ });
+});
diff --git a/template/RULES.md b/template/RULES.md
index 2e81a7fe..664746c9 100644
--- a/template/RULES.md
+++ b/template/RULES.md
@@ -78,6 +78,10 @@ PM отвечает только на **архитектурные стоппе
- `checks` пустой — заполни его на первой стори проекта под его стек. Нет команды —
шаг пропущен; проект без команд в Пеппе виден как «проверки не настроены».
+- `lint` — обязательно, если у стека есть линтер: `"lint": "pnpm exec eslint ."` или
+ `"pnpm exec biome check ."` (JS/TS), `"ruff check . && ruff format --check ."` (Python),
+ `"go vet ./... && gofmt -l . | (! grep .)"` (Go). Настрой его в репо (конфиг, скрипт
+ `lint` в package.json), а не отключай правила, чтобы пройти.
- **Перед PR запусти проверки локально** тем же скриптом, что и CI:
`bash .gitea/peppa-check.sh <проверка>` для каждой из них. Красное не пушь.
- Красная проверка в PR вернётся к тебе сообщением с именем шага и хвостом лога — почини
@@ -85,6 +89,11 @@ PM отвечает только на **архитектурные стоппе
- Не «чини» CI, ослабляя проверки. Изменения `checks`, `deploy` и `.gitea/` PM видит
отдельно, такой PR не мержится автоматически — опиши в PR, зачем это нужно.
- Стори попадает в ревью и мержится только с зелёными проверками последнего коммита.
+- **Агент-ревьюер** (если PM включил его в настройках проекта): после зелёных проверок
+ `update_task(status: review)` сначала отдаёт дифф PR ревьюеру — стори остаётся «в работе»,
+ закончи ход. Замечания придут сообщением: исправь, запушь, дождись зелёного CI и снова
+ `update_task(status: review)`. Несогласен с замечанием — объясни в описании PR. «Ок» —
+ стори уходит к PM сама.
## CD: деплой