From 59c3b583deb944f738f0a4d5ada686b5a29c12f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Fri, 13 Nov 2026 14:49:24 +0500 Subject: [PATCH] =?UTF-8?q?PEP-57:=20CD=20=E2=80=94=20deploy=20workflow,?= =?UTF-8?q?=20preview/staging/prod,=20health=20check=20and=20rollback,=20r?= =?UTF-8?q?eleases?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + apps/bot/src/render.ts | 2 +- apps/web/app/(app)/actions.ts | 11 +- apps/web/app/(app)/help/page.tsx | 24 +- apps/web/app/(app)/p/[key]/page.tsx | 48 +- openspec/changes/pep-57-ci-cd/design.md | 16 + openspec/changes/pep-57-ci-cd/tasks.md | 8 +- packages/cli/src/index.ts | 17 +- packages/core/src/tasks.ts | 7 + .../db/migrations/0013_pep57_releases.sql | 20 + .../db/migrations/meta/0013_snapshot.json | 2189 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 22 + packages/mcp/src/manager.ts | 23 +- packages/runner/src/ci-feedback.ts | 22 + packages/runner/src/ci.ts | 7 +- packages/runner/src/deploy.ts | 167 ++ packages/runner/src/index.ts | 1 + packages/runner/src/sessions.ts | 3 + packages/testkit/bin/mock-docker | 35 + packages/testkit/src/mock-gitea.ts | 7 +- packages/testkit/test/deploy.test.ts | 241 ++ template/.gitea/peppa-deploy.sh | 116 + template/.gitea/workflows/deploy.yml | 35 + template/RULES.md | 18 + template/deploy/Dockerfile.node | 16 + template/deploy/Dockerfile.python | 10 + template/deploy/compose.yml | 21 + 28 files changed, 3079 insertions(+), 15 deletions(-) create mode 100644 packages/db/migrations/0013_pep57_releases.sql create mode 100644 packages/db/migrations/meta/0013_snapshot.json create mode 100644 packages/runner/src/deploy.ts create mode 100755 packages/testkit/bin/mock-docker create mode 100644 packages/testkit/test/deploy.test.ts create mode 100644 template/.gitea/peppa-deploy.sh create mode 100644 template/.gitea/workflows/deploy.yml create mode 100644 template/deploy/Dockerfile.node create mode 100644 template/deploy/Dockerfile.python create mode 100644 template/deploy/compose.yml diff --git a/AGENTS.md b/AGENTS.md index b0a35ab1..a23dcfda 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,6 +31,7 @@ - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (`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 пройдены») +- **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 не трогаем - `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate) diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts index d1a7fc8c..890c9fdd 100644 --- a/apps/bot/src/render.ts +++ b/apps/bot/src/render.ts @@ -22,7 +22,7 @@ export function renderQuestion( q: Question, ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string }, ): Rendered { - const head = [`${esc(ctx.taskKey ?? `Сессия ${q.sessionId ?? "?"}`)}`, ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null] + const head = [`${esc(ctx.taskKey ?? (q.sessionId ? `Сессия ${q.sessionId}` : "Релизы проекта"))}`, ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null] .filter(Boolean) .join(" · "); const body = esc(clip(q.text, 3300)); diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 66a05cca..2aca86d1 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -15,12 +15,13 @@ import { getSetting, unpairTelegram, getIncident, + getProject as getProjectByKey, updateIncidentSettings, type IncidentPolicy, } from "@peppa/core"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; -import { bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, grantRepoAccess, moveTask, provisionProject, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; +import { deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, grantRepoAccess, moveTask, provisionProject, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { requireUser } from "@/lib/auth"; @@ -140,6 +141,14 @@ export async function createProjectAction(f: FormData) { }); } +export async function deployProdAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const p = await projectForUser(db, user.id, (await getProjectByKey(db, str(f, "projectKey"))).id); + await deployProd(db, p, user.login); + }); +} + export async function moveTaskCard(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 431fdee9..21c302e8 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -10,7 +10,8 @@ const TOOLS: Array<[string, string]> = [ ["create_task / update_task", "завести задачу (в Бэклог); поправить название, описание, цель"], ["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"], ["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"], - ["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept)"], + ["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept — мержит PR, только при зелёных проверках)"], + ["list_releases / deploy", "что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод"], ["list_incidents / get_incident", "ошибки из прода (Bugsink): статус, место, релиз, частота, стек"], ["decide_incident / resolve_incident", "решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной"], ["get_incident_policy / set_incident_policy", "политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра"], @@ -29,6 +30,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [ { title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" }, { title: "Ошибки из прода", say: "Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу", how: "list_incidents → decide_incident. Подключение — на странице проекта «Подключить отслеживание ошибок»" }, { title: "Политика инцидентов", say: "В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси", how: "set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram" }, + { title: "Выкатить в прод", say: "Что сейчас на staging в PAY? · Выкати PAY в прод", how: "list_releases → deploy. Тот же образ, что прошёл staging; не поднялся — Пеппа сама откатит и напишет" }, { title: "Закрыть цель", say: "Отметь цель #5 достигнутой", how: "update_goal status=done" }, ]; @@ -82,6 +84,26 @@ export default async function Help() { +

CI/CD

+

+ Каждый PR агента проверяет Gitea Actions: install, lint,{" "} + typecheck, test, build. Команды — + в .peppa/project.json → checks (заполняет агент на первой задаче), workflow приходит из + шаблона; в старый проект — командой peppa ci connect KEY (PR от Пеппы). Результат виден в + карточке задачи («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных + прогонов подряд Пеппа спросит вас. В ревью задача попадает и «Принять» мержит PR только с зелёными проверками и без + конфликтов. PR, меняющий конвейер (.gitea/, checks,{" "} + deploy), сам не мержится никогда. +

+

+ Деплой — deploy в project.json и Dockerfile (заготовки в{" "} + deploy/): PR получает preview slug-prN.telecom.quest (удаляется при + закрытии), мерж выкатывает staging slug-staging.telecom.quest, прод{" "} + slug-prod.telecom.quest — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP{" "} + deploy). После каждого деплоя — проверка /healthz до 2 минут; не + прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта. +

+

Telegram

Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index c05afd36..154de0aa 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -2,14 +2,22 @@ import { notFound } from "next/navigation"; import { AutoRefresh } from "@/components/AutoRefresh"; import { Flash, Notice, SessionCard } from "@/components/ui"; import { Board, type Card } from "@/components/Board"; -import { columnOf, describeRepo } from "@peppa/runner"; +import { columnOf, currentReleases, describeRepo, listReleases, type Release } from "@peppa/runner"; import { requireUser } from "@/lib/auth"; import { board, projectForUserByKey, projectSessions } from "@/lib/queries"; import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core"; import { bugsinkWebhookBase } from "@peppa/runner"; import { IncidentsSection } from "@/components/Incidents"; import { db } from "@/lib/db"; -import { addGoal, addProjectMember, addTask, grantRepoAccessToMembers, removeProjectMember } from "../../actions"; +import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions"; + +const RELEASE_STATUS: Record = { + deploying: "⏳ выкатывается", + healthy: "✅ работает", + rolled_back: "↩️ откат", + failed: "❌ не поднялся", + removed: "🗑 удалён", +}; export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string }> }) { const user = await requireUser(); @@ -17,7 +25,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr const { error, created } = await searchParams; const p = await projectForUserByKey(user.id, key).catch(() => null); if (!p) notFound(); - const [{ goals, tasks }, sessions, team, repo, incidentSettings, sources, incidents] = await Promise.all([ + const [{ goals, tasks }, sessions, team, repo, incidentSettings, sources, incidents, releases, current] = await Promise.all([ board(p.id), projectSessions(p.id), listMembers(db, p), @@ -25,6 +33,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr getIncidentSettings(db, p.id), listErrorSources(db, p.id), listIncidents(db, p.id), + listReleases(db, p.id, 15), + currentReleases(db, p.id), ]); const collaborators = new Set((repo.collaborators ?? []).map((l) => l.toLowerCase())); // Members who are not repo collaborators (only known when Gitea listed them; owners of the namespace see it anyway). @@ -88,6 +98,38 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr +

+

Релизы

+

+ Staging: {current.staging ? <>{current.staging.sha.slice(0, 7)}{current.staging.host && <> · {current.staging.host}} : нет} + {" · "}Прод: {current.prod ? <>{current.prod.sha.slice(0, 7)}{current.prod.host && <> · {current.prod.host}} : нет} +

+ {current.staging && current.staging.sha !== current.prod?.sha && ( +
+ + + +
+ )} + {releases.length === 0 ? ( +

Деплоев ещё не было. Настройка — deploy в .peppa/project.json (см. «Помощь → CI/CD»).

+ ) : ( + + + {releases.map((r) => ( + + + + + + + + ))} + +
{r.env}{r.prNumber ? ` #${r.prNumber}` : ""}{r.sha.slice(0, 7)}{RELEASE_STATUS[r.status]}{r.reason ? — {r.reason} : null}{r.tasks.join(", ")}{r.deployedBy} · {r.createdAt.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" })}
+ )} +
+ -pr.telecom.quest`, + `-staging.telecom.quest`, `-prod.telecom.quest` (можно переопределить в + `deploy.hosts`). Многоуровневые `pr-N.slug.preview.telecom.quest` из proposal не проходят TLS: + универсальный сертификат Cloudflare покрывает только `*.telecom.quest`. Прод не на + `.telecom.quest`, чтобы проект не перехватил существующий хост (проект Пеппы — `peppa`). + Маршруты — docker-метками (провайдер docker Traefik), файлы в `dynamic/` не нужны. +- **Прод — тег `deploy-prod-<время>`** на коммит здорового staging-релиза, его ставит Пеппа от + имени peppa-bot: в Gitea 1.22 нет API `workflow_dispatch`. Тот же образ (`peppa/:` + уже собран staging'ом), сборки нет. +- **Health** — изнутри сети `traefik_default` по имени контейнера `<проект>-<сервис>-1`, до + `PEPPA_HEALTH_TIMEOUT` (120 с). Откат — `compose up` с образом, который работал в окружении до + деплоя (из `docker inspect`), не из таблицы `releases`: так откат работает и без Пеппы. +- **Задачи релиза** — ключи `-N` из сообщений коммитов между предыдущим и новым SHA (шаг + присылает их); для прода по кнопке — задачи staging-релизов с прошлого прода. +- **Сообщения PM** — вопросы без задачи (`askPmProject`): «staging обновлён» с кнопкой + «🚀 Выкатить в прод» (прежние такие предложения закрываются), откат/провал, прод выкачен. diff --git a/openspec/changes/pep-57-ci-cd/tasks.md b/openspec/changes/pep-57-ci-cd/tasks.md index 5cc94c2f..3638fdc1 100644 --- a/openspec/changes/pep-57-ci-cd/tasks.md +++ b/openspec/changes/pep-57-ci-cd/tasks.md @@ -21,10 +21,10 @@ ## 3. CD -- [ ] 3.1 Шаблон: `Dockerfile`-заготовки (node, python), `deploy/compose.yml` с метками Traefik, `deploy.yml` (build → staging → smoke); `releases` в БД -- [ ] 3.2 Preview на PR и удаление при закрытии; staging на мерж; прод по кнопке (веб, Telegram, MCP `deploy`) через `workflow_dispatch` -- [ ] 3.3 Проверка здоровья и авто-откат; блок «Релизы» на странице проекта; сообщения PM -- [ ] 3.4 Тесты сценариев «Деплой» и «Откат» (деплой — на моке: compose-команда подменяется mock-скриптом) +- [x] 3.1 Шаблон: `Dockerfile`-заготовки (node, python), `deploy/compose.yml` с метками Traefik, `deploy.yml` (build → staging → smoke); `releases` в БД +- [x] 3.2 Preview на PR и удаление при закрытии; staging на мерж; прод по кнопке (веб, Telegram, MCP `deploy`) через `workflow_dispatch` +- [x] 3.3 Проверка здоровья и авто-откат; блок «Релизы» на странице проекта; сообщения PM +- [x] 3.4 Тесты сценариев «Деплой» и «Откат» (деплой — на моке: compose-команда подменяется mock-скриптом) ## 4. Пеппа на собственном конвейере diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 0714401e..4635b0ef 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -39,7 +39,7 @@ import { type TaskStatus, } from "@peppa/core"; import { createDb } from "@peppa/db"; -import { answerAndDeliver, connectCi, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; +import { answerAndDeliver, connectCi, deployProd, listReleases, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner"; import { spawnSync } from "node:child_process"; import { loadEnv } from "@peppa/shared"; @@ -49,6 +49,8 @@ const USAGE = `peppa — Peppa software factory CLI peppa project add [--owner peppa] [--repo ] [--path ] (register only) peppa project owner peppa project list + peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button) + peppa release list [KEY] peppa ci connect [KEY] (runner + secret + PR with the CI workflow from the template) peppa goal add [KEY] [-d <description>] peppa goal list [KEY] @@ -176,6 +178,19 @@ async function main(): Promise<void> { console.log(`${p.key}: runner=${r.runner}, ${r.prUrl ? `PR ${r.prUrl}` : "workflow already on the default branch"}`); break; } + case "deploy prod": { + const [key] = withKey(args, 0); + const p = await getProject(db, key); + const r = await deployProd(db, p, process.env.USER ?? "cli"); + console.log(`${p.key}: ${r.sha.slice(0, 7)} → prod (release #${r.id}, tasks: ${r.tasks.join(", ") || "—"})`); + break; + } + case "release list": { + const [key] = withKey(args, 0); + const p = await getProject(db, key); + for (const r of await listReleases(db, p.id)) console.log(`#${r.id} ${r.env.padEnd(8)} ${r.sha.slice(0, 7)} ${r.status.padEnd(11)} ${r.tasks.join(",")} ${r.deployedBy} ${r.reason ?? ""}`); + break; + } case "goal add": { const [key, [title]] = withKey(args, 1); if (!title) throw new PeppaError("usage: peppa goal add [KEY] <title>"); diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index 15d397f5..f392e3e1 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -155,6 +155,13 @@ export async function askPm(db: Db, ref: TaskRef, q: NewQuestion): Promise<Quest return row!; } +/** A message for the PM about the project as a whole (releases), not about a task. */ +export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[] }): Promise<Question> { + const [row] = await db.insert(questions).values({ projectId: project.id, ...q }).returning(); + await notify(db, { type: "question", questionId: row!.id }); + return row!; +} + export async function pendingQuestions(db: Db, projectId?: number): Promise<Question[]> { return db .select() diff --git a/packages/db/migrations/0013_pep57_releases.sql b/packages/db/migrations/0013_pep57_releases.sql new file mode 100644 index 00000000..9f82d934 --- /dev/null +++ b/packages/db/migrations/0013_pep57_releases.sql @@ -0,0 +1,20 @@ +CREATE TABLE "releases" ( + "id" serial PRIMARY KEY NOT NULL, + "project_id" integer NOT NULL, + "env" text NOT NULL, + "sha" text NOT NULL, + "previous_sha" text, + "image" text, + "host" text, + "pr_number" integer, + "tasks" jsonb DEFAULT '[]'::jsonb NOT NULL, + "status" text DEFAULT 'deploying' NOT NULL, + "deployed_by" text DEFAULT 'ci' NOT NULL, + "reason" text, + "run_url" text, + "log_tail" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "releases" ADD CONSTRAINT "releases_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action; \ No newline at end of file diff --git a/packages/db/migrations/meta/0013_snapshot.json b/packages/db/migrations/meta/0013_snapshot.json new file mode 100644 index 00000000..56cb70cd --- /dev/null +++ b/packages/db/migrations/meta/0013_snapshot.json @@ -0,0 +1,2189 @@ +{ + "id": "82ed94db-27de-4e8f-81c1-5440cb5f4011", + "prevId": "ca89d235-ea51-4284-95fe-50b24621c88a", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.check_runs": { + "name": "check_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sha", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "check", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.error_sources": { + "name": "error_sources", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "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": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "nullsNotDistinct": false, + "columns": [ + "bugsink_project_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.goals": { + "name": "goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "goal_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.incident_settings": { + "name": "incident_settings", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "environments": { + "name": "environments", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[\"prod\",\"production\"]'::jsonb" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "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": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "nullsNotDistinct": false, + "columns": [ + "hook_secret" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.incidents": { + "name": "incidents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_seen": { + "name": "last_seen", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "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": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "nullsNotDistinct": false, + "columns": [ + "bugsink_issue_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_clients": { + "name": "oauth_clients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_codes": { + "name": "oauth_codes", + "schema": "", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": 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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_tokens": { + "name": "oauth_tokens", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": 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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_invites": { + "name": "project_invites", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": { + "name": "project_invites_project_id_login_pk", + "columns": [ + "project_id", + "login" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_members": { + "name": "project_members", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": { + "name": "project_members_project_id_user_id_pk", + "columns": [ + "project_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "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" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "projects_key_unique": { + "name": "projects_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.questions": { + "name": "questions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": 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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.releases": { + "name": "releases", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tasks": { + "name": "tasks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude'" + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "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" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "nullsNotDistinct": false, + "columns": [ + "tmux_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "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": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_outbox": { + "name": "telegram_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "params": { + "name": "params", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "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": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_updates": { + "name": "telegram_updates", + "schema": "", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "nullsNotDistinct": false, + "columns": [ + "gitea_id" + ] + }, + "users_login_unique": { + "name": "users_login_unique", + "nullsNotDistinct": false, + "columns": [ + "login" + ] + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "nullsNotDistinct": false, + "columns": [ + "telegram_chat_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.goal_status": { + "name": "goal_status", + "schema": "public", + "values": [ + "open", + "done", + "archived" + ] + }, + "public.session_status": { + "name": "session_status", + "schema": "public", + "values": [ + "starting", + "running", + "waiting_input", + "idle", + "stalled", + "rate_limited", + "done", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "backlog", + "proposing", + "awaiting_approval", + "in_progress", + "review", + "done", + "blocked" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 7c258cac..108d9a85 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -92,6 +92,13 @@ "when": 1794562626634, "tag": "0012_faithful_matthew_murdock", "breakpoints": true + }, + { + "idx": 13, + "version": "7", + "when": 1794562970727, + "tag": "0013_pep57_releases", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index a055a2bd..3e6194fc 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -118,6 +118,28 @@ export const tasks = pgTable( (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)], ); +/** PEP-57: one deployment of a project to an environment (and its outcome). */ +export const releases = pgTable("releases", { + id: serial("id").primaryKey(), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + env: text("env", { enum: ["preview", "staging", "prod"] }).notNull(), + sha: text("sha").notNull(), + previousSha: text("previous_sha"), + image: text("image"), + host: text("host"), + prNumber: integer("pr_number"), + // Task keys in the release ("PAY-7"), from the merged commits. + tasks: jsonb("tasks").$type<string[]>().notNull().default([]), + status: text("status", { enum: ["deploying", "healthy", "rolled_back", "failed", "removed"] }).notNull().default("deploying"), + // "ci" for automatic deploys, the PM's login for prod by the button. + deployedBy: text("deployed_by").notNull().default("ci"), + reason: text("reason"), + runUrl: text("run_url"), + logTail: text("log_tail"), + createdAt: createdAt(), + updatedAt: updatedAt(), +}); + /** PEP-57: one CI check (lint/typecheck/test/build/install) of one commit of a project. */ export const checkRuns = pgTable( "check_runs", diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index 0f9d0fb3..c5f59784 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -32,7 +32,7 @@ import { } from "@peppa/core"; import { questions, projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey, loadEnv } from "@peppa/shared"; -import { decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner"; +import { currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner"; import { and, asc, eq, inArray, isNull } from "drizzle-orm"; import { z } from "zod"; import { formatIncident, formatTask } from "./format.ts"; @@ -54,6 +54,7 @@ Good habits: - Only move a task to in_progress when the user asks to start the work. - Statuses: get_task for details, list_tasks for the board, list_inbox for what needs the user. - Projects can be shared: add_member / remove_member (owner only); members can do everything else. +- CI/CD: every PR is checked (get_task shows the checks; red ones go back to the agent; "accept" merges the PR only when they are green). A merge deploys to staging; list_releases shows what runs where; deploy puts the healthy staging release into prod — only when the user asks. - Production errors (Bugsink) arrive as incidents: list_incidents. What happens to a new one is the project's incident policy (get_incident_policy / set_incident_policy: notify, backlog — default, start, ask, triage with the user's mini-prompt). Pending ones wait for decide_incident (backlog / start / ignore); resolve_incident marks one fixed.`; export function createManagerServer(db: Db, user: User, webUrl: string): McpServer { @@ -251,6 +252,26 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ }, ); + tool("list_releases", "Deployments of a project: what runs on staging and prod, and the latest releases (env, commit, status, tasks, who deployed).", { project: projectArg }, true, async ({ project }) => { + const p = await ownedProject(project); + const [cur, rows] = await Promise.all([currentReleases(db, p.id), listReleases(db, p.id, 15)]); + const head = (["staging", "prod"] as const).map((e) => `${e}: ${cur[e] ? `${cur[e]!.sha.slice(0, 7)}${cur[e]!.host ? ` https://${cur[e]!.host}` : ""}` : "—"}`).join(" · "); + if (!rows.length) return `${head}\nNo deployments yet (deploy is configured in .peppa/project.json → "deploy").`; + return [head, ...rows.map((r) => `- ${r.env}${r.prNumber ? ` #${r.prNumber}` : ""} ${r.sha.slice(0, 7)} ${r.status}${r.reason ? ` (${r.reason})` : ""}${r.tasks.length ? ` · ${r.tasks.join(", ")}` : ""} · ${r.deployedBy} · ${r.createdAt.toISOString().slice(0, 16)}`)].join("\n"); + }); + + tool( + "deploy", + "Deploy the project's healthy staging release to prod (the same image). Only when the user asks; the result arrives as a release (list_releases) and a message.", + { project: projectArg, env: z.enum(["prod"]).default("prod") }, + false, + async ({ project }) => { + const p = await ownedProject(project); + const r = await deployProd(db, p, user.login); + return `${p.key}: ${r.sha.slice(0, 7)} is being deployed to prod${r.tasks.length ? ` (tasks ${r.tasks.join(", ")})` : ""}. Check list_releases in a minute or two.`; + }, + ); + tool("list_inbox", "Open questions from agents waiting for the user (approvals, questions, permissions, ready-for-review), oldest first.", {}, true, async () => { const ids = await userProjectIds(db, user.id); if (!ids.length) return "Inbox is empty — agents need nothing from you."; diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 0c76c0ec..030cc42f 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -23,6 +23,7 @@ import { checkRuns, projects, tasks, type Db } from "@peppa/db"; import { and, eq, sql } from "drizzle-orm"; import { sendToSession } from "./sessions.ts"; import { moveTask } from "./flow.ts"; +import { recordRelease } from "./deploy.ts"; /** Red runs in a row after which the PM is asked instead of the agent. */ export const MAX_CI_ATTEMPTS = 3; @@ -149,6 +150,27 @@ export async function handleGiteaHook(db: Db, req: HookRequest): Promise<{ statu }); return { status: 200, body: { ok: true, ...out } }; } + if (req.event === "deploy") { + const env = String(payload.env); + const status = String(payload.status); + if (!["preview", "staging", "prod"].includes(env) || !["deploying", "healthy", "rolled_back", "failed", "removed"].includes(status) || typeof payload.sha !== "string") { + return { status: 400, body: { error: "bad deploy report" } }; + } + const rel = await recordRelease(db, project, { + env: env as "preview", + sha: payload.sha, + previousSha: (payload.previous_sha as string) || null, + image: (payload.image as string) ?? null, + host: (payload.host as string) ?? null, + prNumber: typeof payload.pr === "number" ? payload.pr : null, + status: status as "healthy", + reason: (payload.reason as string) ?? null, + runUrl: (payload.run_url as string) ?? null, + commits: Array.isArray(payload.commits) ? payload.commits.map(String) : [], + logTail: (payload.log_tail as string) ?? null, + }); + return { status: 200, body: { ok: true, release: rel.id, status: rel.status } }; + } for (const h of eventHandlers) await h(db, project, req.event, payload); return { status: 200, body: { ok: true } }; } diff --git a/packages/runner/src/ci.ts b/packages/runner/src/ci.ts index 652132ed..976dc050 100644 --- a/packages/runner/src/ci.ts +++ b/packages/runner/src/ci.ts @@ -12,7 +12,9 @@ import { repoAdmins } from "./share.ts"; import { git, run, templateRepoUrl } from "./git.ts"; /** Files of the CI contract, copied from the template into project repos. */ -export const CI_FILES = [".gitea/workflows/ci.yml", ".gitea/peppa-check.sh"]; +export const CI_FILES = [".gitea/workflows/ci.yml", ".gitea/peppa-check.sh", ".gitea/workflows/deploy.yml", ".gitea/peppa-deploy.sh"]; +/** Starting points copied only when the project has none yet (the project owns them after). */ +export const CD_SCAFFOLD = ["deploy/compose.yml", "deploy/Dockerfile.node", "deploy/Dockerfile.python"]; export const CI_BRANCH = "peppa/ci"; export const CI_SECRET_NAME = "PEPPA_CI_SECRET"; @@ -93,7 +95,7 @@ export async function connectCi(db: Db, project: Project, o: { templateUrl?: str await git(work, "clone", "-q", repo.clone_url, dest); await git(work, "clone", "-q", "--depth", "1", templateRepoUrl(o.templateUrl), tpl); await git(dest, "checkout", "-q", "-B", CI_BRANCH, `origin/${base}`); - for (const f of CI_FILES) { + for (const f of [...CI_FILES, ...CD_SCAFFOLD.filter((f) => !existsSync(join(dest, f)))]) { mkdirSync(dirname(join(dest, f)), { recursive: true }); cpSync(join(tpl, f), join(dest, f)); } @@ -122,6 +124,7 @@ export async function connectCi(db: Db, project: Project, o: { templateUrl?: str "", `- ${CI_FILES.map((f) => `\`${f}\``).join(", ")} — из шаблона, под стек не меняются;`, "- команды проверок — в `.peppa/project.json` → `checks` (`install`, `lint`, `typecheck`, `test`, `build`); пустая команда = шаг пропущен.", + "- деплой (preview на PR, staging на мерж, прод по кнопке PM) — `.peppa/project.json` → `deploy` + `Dockerfile` (заготовки в `deploy/`); без `deploy` шаг пропускается.", "", "Заполнить `checks` — первая задача агента в проекте. Изменение конвейера требует ревью PM.", ].join("\n"), diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts new file mode 100644 index 00000000..0ed7364f --- /dev/null +++ b/packages/runner/src/deploy.ts @@ -0,0 +1,167 @@ +// Deployments of factory projects (PEP-57). The project's deploy workflow does the work on +// the host (docker compose behind Traefik, health check, rollback) and reports each step +// here; Peppa keeps the releases, tells the PM, and starts prod by the PM's button — a +// `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API). +import { answerQuestion, askPmProject, giteaForBot, PeppaError, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; +import { projects, questions, releases, type Db } from "@peppa/db"; +import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; + +export type Release = typeof releases.$inferSelect; +export type ReleaseEnv = Release["env"]; +export type ReleaseStatus = Release["status"]; + +/** The option of the "staging updated" message that sends the release to prod. */ +export const PROD_OPTION = "🚀 Выкатить в прод"; + +export interface DeployReport { + env: ReleaseEnv; + sha: string; + previousSha?: string | null; + image?: string | null; + host?: string | null; + prNumber?: number | null; + status: ReleaseStatus; + reason?: string | null; + runUrl?: string | null; + commits?: string[]; + logTail?: string | null; +} + +/** Task keys of the project mentioned in commit subjects ("…from task/PAY-7 into main"). */ +export function tasksInCommits(project: Project, commits: string[]): string[] { + const re = new RegExp(`\\b${project.key}-(\\d+)\\b`, "gi"); + const out = new Set<string>(); + for (const c of commits) for (const m of c.matchAll(re)) out.add(`${project.key}-${Number(m[1])}`); + return [...out].sort((a, b) => Number(a.split("-")[1]) - Number(b.split("-")[1])); +} + +export async function listReleases(db: Db, projectId: number, limit = 20): Promise<Release[]> { + return db.select().from(releases).where(eq(releases.projectId, projectId)).orderBy(desc(releases.id)).limit(limit); +} + +/** What runs in each environment now: the latest healthy (or rolled back to) release. */ +export async function currentReleases(db: Db, projectId: number): Promise<Partial<Record<ReleaseEnv, Release>>> { + const out: Partial<Record<ReleaseEnv, Release>> = {}; + for (const env of ["staging", "prod"] as const) { + const [r] = await db + .select() + .from(releases) + .where(and(eq(releases.projectId, projectId), eq(releases.env, env), eq(releases.status, "healthy"))) + .orderBy(desc(releases.id)) + .limit(1); + if (r) out[env] = r; + } + return out; +} + +const short = (sha: string | null | undefined) => (sha ? sha.slice(0, 7) : "—"); + +/** Closes earlier unanswered "deploy to prod?" offers of the project: a newer staging is up. */ +async function expireProdOffers(db: Db, projectId: number) { + const open = await db + .select() + .from(questions) + .where(and(eq(questions.projectId, projectId), isNull(questions.taskId), isNull(questions.answeredAt), sql`${questions.options} @> ${JSON.stringify([PROD_OPTION])}::jsonb`)); + for (const q of open) await answerQuestion(db, q.id, "(неактуально: на staging новый релиз)", "system").catch(() => {}); +} + +/** Records one step of a deploy and tells the PM what they need to know. */ +export async function recordRelease(db: Db, project: Project, r: DeployReport): Promise<Release> { + const sameRun = and( + eq(releases.projectId, project.id), + eq(releases.env, r.env), + eq(releases.sha, r.sha), + eq(releases.status, "deploying"), + r.env === "preview" && r.prNumber ? eq(releases.prNumber, r.prNumber) : undefined, + ); + const [open] = await db.select().from(releases).where(sameRun).orderBy(desc(releases.id)).limit(1); + const fromCommits = tasksInCommits(project, r.commits ?? []); + const values = { + previousSha: r.previousSha ?? open?.previousSha ?? null, + image: r.image ?? open?.image ?? null, + host: r.host ?? open?.host ?? null, + prNumber: r.prNumber ?? open?.prNumber ?? null, + tasks: open?.tasks.length ? open.tasks : fromCommits, + status: r.status, + reason: r.reason ?? null, + runUrl: r.runUrl ?? open?.runUrl ?? null, + logTail: r.logTail ?? open?.logTail ?? null, + }; + let rel: Release; + if (r.status === "removed") { + // Preview torn down: every release of that PR's stand is gone. + await db + .update(releases) + .set({ status: "removed" }) + .where(and(eq(releases.projectId, project.id), eq(releases.env, "preview"), eq(releases.prNumber, r.prNumber ?? -1), inArray(releases.status, ["deploying", "healthy"]))); + [rel] = await db.select().from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, "preview"), eq(releases.prNumber, r.prNumber ?? -1))).orderBy(desc(releases.id)).limit(1); + if (rel!) return rel; + } + [rel] = open + ? await db.update(releases).set(values).where(eq(releases.id, open.id)).returning() + : await db.insert(releases).values({ projectId: project.id, env: r.env, sha: r.sha, ...values }).returning(); + await notifyRelease(db, project, rel!); + return rel!; +} + +async function notifyRelease(db: Db, project: Project, rel: Release) { + const tasks = rel.tasks.length ? ` · задачи: ${rel.tasks.join(", ")}` : ""; + const log = runLink(rel.runUrl); + if (rel.status === "rolled_back" || rel.status === "failed") { + const back = rel.status === "rolled_back" ? ` — возвращён ${short(rel.previousSha)}` : ""; + await askPmProject(db, project, { + kind: "attention", + text: `❌ ${project.name}: релиз ${short(rel.sha)} в ${rel.env} не прошёл${back}.\nПричина: ${rel.reason ?? "неизвестна"}${log ? `\nЛог: ${log}` : ""}`, + }); + } else if (rel.status === "healthy" && rel.env === "staging") { + await expireProdOffers(db, project.id); + await askPmProject(db, project, { + kind: "question", + options: [PROD_OPTION], + text: `✅ ${project.name}: staging обновлён — ${short(rel.sha)}${tasks}${rel.host ? `\nhttps://${rel.host}` : ""}\nВыкатить этот релиз в прод?`, + }); + } else if (rel.status === "healthy" && rel.env === "prod") { + await askPmProject(db, project, { kind: "attention", text: `🚀 ${project.name} в проде: ${short(rel.sha)}${tasks}${rel.host ? `\nhttps://${rel.host}` : ""}` }); + } +} + +/** + * "Deploy to prod" (web, Telegram, MCP): the image of the latest healthy staging release + * goes to prod — Peppa tags that commit `deploy-prod-<time>` and the workflow deploys it. + */ +export async function deployProd(db: Db, project: Project, by: string, gitea: GiteaClient = giteaForBot()): Promise<Release> { + const { staging, prod } = await currentReleases(db, project.id); + if (!staging) throw new PeppaError(`${project.key}: на staging нет здорового релиза — выкатывать нечего`); + const [running] = await db + .select() + .from(releases) + .where(and(eq(releases.projectId, project.id), eq(releases.env, "prod"), eq(releases.status, "deploying"))) + .limit(1); + if (running) throw new PeppaError(`${project.key}: прод уже выкатывается (${short(running.sha)})`); + // Tasks since the last prod release: every healthy staging release after it. + const since = await db + .select() + .from(releases) + .where(and(eq(releases.projectId, project.id), eq(releases.env, "staging"), eq(releases.status, "healthy"), prod ? sql`${releases.id} > ${prod.id}` : undefined)); + const taskKeys = [...new Set([...since.flatMap((r) => r.tasks), ...staging.tasks])].sort(); + const tag = `deploy-prod-${new Date().toISOString().replace(/\D/g, "").slice(0, 17)}`; + await gitea.createTag(project.giteaOwner, project.giteaRepo, tag, staging.sha, `Прод по кнопке: ${by}`); + const [rel] = await db + .insert(releases) + .values({ projectId: project.id, env: "prod", sha: staging.sha, previousSha: prod?.sha ?? null, image: staging.image, tasks: taskKeys, status: "deploying", deployedBy: by }) + .returning(); + return rel!; +} + +/** The PM pressed "deploy to prod" on a "staging updated" message (any channel). */ +export async function onReleaseAnswer(db: Db, q: Question, answer: string, by: string): Promise<boolean> { + if (q.taskId || q.sessionId || !(q.options ?? []).includes(PROD_OPTION) || answer.trim() !== PROD_OPTION) return false; + const [project] = await db.select().from(projects).where(eq(projects.id, q.projectId)); + if (!project) return false; + try { + await deployProd(db, project, by); + } catch (e) { + await askPmProject(db, project, { kind: "attention", text: `Прод не запущен: ${(e as Error).message}` }); + } + return true; +} diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 7f457f98..71e8ed88 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -14,3 +14,4 @@ export * from "./ci.ts"; export * from "./incidents.ts"; export * from "./triage.ts"; export * from "./ci-feedback.ts"; +export * from "./deploy.ts"; diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index 8fa5bdcd..86601e24 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -22,6 +22,7 @@ import { trustWorkspace } from "./claude-config.ts"; import { buildCommand, type Provider } from "./providers.ts"; import { runDir } from "./run-settings.ts"; import * as tmux from "./tmux.ts"; +import { onReleaseAnswer } from "./deploy.ts"; export interface StartOptions { /** Extra instructions appended to the default "work on <task>" prompt. */ @@ -179,6 +180,8 @@ export async function answerAndDeliver( message = `Ответ PM на вопрос #${q.id}: ${answer}`; } + // "Deploy to prod" on a "staging updated" message (PEP-57). + if (await onReleaseAnswer(db, q, answer, `PM (${via})`)) return { delivered: true, question: q }; if (!q.sessionId) return { delivered: false, question: q }; const s = await getSession(db, q.sessionId); if (!(await tmux.hasSession(s.tmuxName))) return { delivered: false, question: q }; diff --git a/packages/testkit/bin/mock-docker b/packages/testkit/bin/mock-docker new file mode 100755 index 00000000..0a37532d --- /dev/null +++ b/packages/testkit/bin/mock-docker @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# mock-docker — stands in for the docker CLI in .gitea/peppa-deploy.sh tests (first on PATH). +# Same calls and exit codes as the script uses from real docker; state lives in +# $MOCK_DOCKER_STATE: images (one tag per line), containers/<name> (its image), calls.log. +# MOCK_DOCKER_BUILD_FAIL=1 makes `docker build` fail. +set -uo pipefail +st="${MOCK_DOCKER_STATE:?MOCK_DOCKER_STATE is required}" +mkdir -p "$st/containers" +touch "$st/images" +echo "docker $*" >> "$st/calls.log" +case "$1" in + inspect) # docker inspect -f '{{.Config.Image}}' <container> + c="${@: -1}" + [[ -f "$st/containers/$c" ]] || { echo "Error: No such object: $c" >&2; exit 1; } + cat "$st/containers/$c" ;; + image) + case "$2" in + inspect) grep -qxF "$3" "$st/images" || { echo "Error: No such image: $3" >&2; exit 1; }; echo "[{}]" ;; + prune) exit 0 ;; + esac ;; + build) # docker build -t <image> ... + [[ -n "${MOCK_DOCKER_BUILD_FAIL:-}" ]] && { echo "mock build failed" >&2; exit 1; } + shift; while [[ $# -gt 0 ]]; do [[ $1 == -t ]] && { echo "$2" >> "$st/images"; break; }; shift; done + echo "Successfully built" ;; + compose) # docker compose -p <project> -f <file> <up|down|run> ... + shift; project=""; while [[ $# -gt 0 ]]; do case "$1" in -p) project="$2"; shift 2 ;; -f) shift 2 ;; *) break ;; esac; done + svc="${MOCK_DOCKER_SERVICE:-web}" + case "$1" in + up) grep -qxF "$IMAGE" "$st/images" || { echo "pull access denied for $IMAGE" >&2; exit 1; } + echo "$IMAGE" > "$st/containers/$project-$svc-1"; echo "Container $project-$svc-1 Started" ;; + down) rm -f "$st/containers/$project-"*; echo "Removed $project" ;; + run) echo "ran in $IMAGE: ${*: -1}" ;; + esac ;; + *) echo "mock-docker: unsupported: $*" >&2; exit 1 ;; +esac diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index e587790d..1fa3591f 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -60,7 +60,12 @@ export class MockGitea { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { - const r = this.handle(req.method!, req.url!, req.headers.authorization ?? "", body ? JSON.parse(body) : {}); + let r: { status: number; body?: unknown }; + 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]}` } }; + } res.writeHead(r.status, { "Content-Type": "application/json" }); res.end(r.body === undefined ? "" : JSON.stringify(r.body)); }); diff --git a/packages/testkit/test/deploy.test.ts b/packages/testkit/test/deploy.test.ts new file mode 100644 index 00000000..4b4edc3f --- /dev/null +++ b/packages/testkit/test/deploy.test.ts @@ -0,0 +1,241 @@ +// PEP-57, spec delivery-pipeline: «Деплой по окружениям» и «Проверка здоровья и откат». +// The template's .gitea/peppa-deploy.sh runs for real against mock-docker (docker CLI on +// PATH) and a mock health endpoint; it reports to Peppa through handleGiteaHook. +import assert from "node:assert/strict"; +import { execFile, execFileSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +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 } from "./helpers.ts"; +import { MockGitea } from "../src/mock-gitea.ts"; + +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); +const TMP = mkdtempSync(join(tmpdir(), "peppa-deploy-")); +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const gitea = new MockGitea(join(TMP, "gitea")); +const BOT = { id: 81, login: "peppa-bot", token: "mock-token-bot" }; +const SCRIPT = join(ROOT, "template/.gitea/peppa-deploy.sh"); + +// docker → mock-docker, first on PATH for the script. +const BIN = join(TMP, "bin"); +mkdirSync(BIN); +symlinkSync(join(ROOT, "packages/testkit/bin/mock-docker"), join(BIN, "docker")); + +let server: Server; +let base = ""; +/** Images whose app fails its health check. */ +const badImages = new Set<string>(); + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + gitea.addUser(BOT); + // One server: Peppa's /api/hooks/gitea and the deployed apps' /<project>/healthz. + server = createServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", async () => { + if (req.url === "/api/hooks/gitea") { + const r = await runner.handleGiteaHook(db, { event: String(req.headers["x-peppa-event"]), signature: String(req.headers["x-gitea-signature"]), body }); + res.writeHead(r.status).end(JSON.stringify(r.body)); + return; + } + const [, stateDir, proj] = decodeURIComponent(req.url ?? "").match(/^\/state:([^:]+):([^/]+)\/healthz$/) ?? []; + const f = stateDir && join(stateDir, "containers", `${proj}-web-1`); + const image = f && existsSync(f) ? readFileSync(f, "utf8").trim() : null; + res.writeHead(image && !badImages.has(image) ? 200 : 503).end(); + }); + }); + await new Promise<void>((r) => server.listen(0, "127.0.0.1", r)); + base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); +after(async () => { + server.close(); + await gitea.stop(); + await teardown(); +}); + +/** A project with deploy settings, its repo checked out as the CI job sees it. */ +async function deployable(deploy: object | null = { compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz" }) { + const p = await project({ turns: [] }); + const proj = await core.getProject(db, p.key); + const work = join(TMP, `work-${p.key}`); + const state = join(TMP, `docker-${p.key}`); + mkdirSync(join(work, ".peppa"), { recursive: true }); + mkdirSync(join(work, "deploy")); + writeFileSync(join(work, "deploy/compose.yml"), readFileSync(join(ROOT, "template/deploy/compose.yml"))); + writeFileSync(join(work, "Dockerfile"), "FROM scratch\n"); + writeFileSync(join(work, ".peppa/project.json"), JSON.stringify({ slug: proj.slug, key: p.key, name: p.key, peppaUrl: base, ...(deploy ? { deploy } : {}) })); + const git = (...a: string[]) => execFileSync("git", ["-C", work, "-c", "user.name=t", "-c", "user.email=t@t", ...a], { encoding: "utf8" }).trim(); + git("init", "-q", "-b", "main"); + git("add", "-A"); + git("commit", "-qm", "init"); + const repo = gitea.addRepo(proj.giteaOwner, proj.giteaRepo); + repo.collaborators[BOT.login] = "write"; + /** A merge of a task branch into main, pushed to Gitea; returns its SHA. */ + const merge = (task: string) => { + writeFileSync(join(work, `${task}.txt`), task); + git("add", "-A"); + git("commit", "-qm", `Merge pull request '${task}' (#1) from task/${task} into main`); + git("push", "-q", repo.path, "main"); + return git("rev-parse", "HEAD"); + }; + const run = (mode: string, sha: string, extra: Record<string, string> = {}) => + new Promise<{ code: number; out: string }>((done) => { + git("checkout", "-q", sha); + const env = { + ...process.env, + PATH: `${BIN}:${process.env.PATH}`, + MOCK_DOCKER_STATE: state, + PEPPA_SHA: sha, + PEPPA_CI_SECRET: core.projectHookSecret(proj.id), + PEPPA_HEALTH_BASE: `${base}/state:${state}:{project}`, + PEPPA_HEALTH_TIMEOUT: "2", + PEPPA_HEALTH_INTERVAL: "0.3", + GITHUB_REPOSITORY: `${proj.giteaOwner}/${proj.giteaRepo}`, + GITHUB_RUN_NUMBER: "5", + ...extra, + }; + execFile("bash", [SCRIPT, mode], { cwd: work, env, encoding: "utf8" }, (err, stdout, stderr) => { + git("checkout", "-q", "main"); + done({ code: err ? Number((err as { code?: number }).code ?? 1) : 0, out: stdout + stderr }); + }); + }); + const container = (env: string) => { + const f = join(state, "containers", `${proj.slug}-${env}-web-1`); + return existsSync(f) ? readFileSync(f, "utf8").trim() : null; + }; + const calls = () => (existsSync(join(state, "calls.log")) ? readFileSync(join(state, "calls.log"), "utf8") : ""); + return { p, proj, merge, run, container, calls }; +} + +async function releases(projectId: number) { + return (await runner.listReleases(db, projectId, 50)).reverse(); +} + +describe("Деплой по окружениям", () => { + test("Scenario: Staging после мержа — образ с тегом коммита на staging, релиз со списком задач", async () => { + const d = await deployable(); + const sha = d.merge(`${d.p.key}-7`); + const r = await d.run("staging", sha); + assert.equal(r.code, 0, r.out); + assert.equal(d.container("staging"), `peppa/${d.proj.slug}:${sha}`); + const [rel] = await releases(d.proj.id); + assert.equal(rel!.env, "staging"); + assert.equal(rel!.status, "healthy"); + assert.equal(rel!.sha, sha); + assert.equal(rel!.host, `${d.proj.slug}-staging.telecom.quest`); + assert.deepEqual(rel!.tasks, [`${d.p.key}-7`]); + const offer = (await core.pendingQuestions(db, d.proj.id)).find((q) => q.options?.includes(runner.PROD_OPTION)); + assert.ok(offer, "the PM is offered to deploy to prod"); + assert.equal(offer.taskId, null); + }); + + test("Scenario: Прод по кнопке — тот же образ в проде, релиз прода с автором PM", async () => { + const d = await deployable(); + const sha = d.merge(`${d.p.key}-7`); + assert.equal((await d.run("staging", sha)).code, 0); + const rel = await runner.deployProd(db, d.proj, "mock-pm"); + assert.equal(rel.status, "deploying"); + const tag = gitea.repo(d.proj.giteaOwner, d.proj.giteaRepo).tags.at(-1)!; + assert.match(tag.name, /^deploy-prod-\d{17}$/); + assert.equal(tag.target, sha, "Peppa tags the healthy staging commit"); + // The tag starts the deploy workflow in prod mode. + const r = await d.run("prod", sha, { GITHUB_REF: `refs/tags/${tag.name}` }); + assert.equal(r.code, 0, r.out); + assert.equal(d.container("prod"), `peppa/${d.proj.slug}:${sha}`); + assert.equal(d.calls().match(/docker build/g)?.length, 1, "prod reuses the staging image"); + const prod = (await releases(d.proj.id)).filter((x) => x.env === "prod"); + assert.equal(prod.length, 1); + assert.equal(prod[0]!.status, "healthy"); + assert.equal(prod[0]!.deployedBy, "mock-pm"); + assert.deepEqual(prod[0]!.tasks, [`${d.p.key}-7`]); + await assert.rejects(runner.deployProd(db, d.proj, "mock-pm").then(() => runner.deployProd(db, d.proj, "mock-pm")), /уже выкатывается/); + }); + + test("Telegram button: answering the staging message with «Выкатить в прод» starts prod", async () => { + const d = await deployable(); + assert.equal((await d.run("staging", d.merge(`${d.p.key}-2`))).code, 0); + const offer = (await core.pendingQuestions(db, d.proj.id)).find((q) => q.options?.includes(runner.PROD_OPTION))!; + await runner.answerAndDeliver(db, offer.id, runner.PROD_OPTION, "telegram"); + const [prod] = (await releases(d.proj.id)).filter((x) => x.env === "prod"); + assert.equal(prod?.status, "deploying"); + assert.equal(prod?.deployedBy, "PM (telegram)"); + }); + + test("no healthy staging: nothing to deploy to prod", async () => { + const d = await deployable(); + await assert.rejects(runner.deployProd(db, d.proj, "mock-pm"), /на staging нет здорового релиза/); + }); + + test("preview on a PR, removed when the PR is closed", async () => { + const d = await deployable(); + const sha = d.merge(`${d.p.key}-3`); + assert.equal((await d.run("preview", sha, { PEPPA_PR: "3" })).code, 0); + assert.equal(d.container("pr3"), `peppa/${d.proj.slug}:${sha}`); + let [rel] = await releases(d.proj.id); + assert.equal(rel!.host, `${d.proj.slug}-pr3.telecom.quest`); + assert.equal(rel!.status, "healthy"); + assert.equal((await d.run("preview-down", sha, { PEPPA_PR: "3" })).code, 0); + assert.equal(d.container("pr3"), null); + [rel] = await releases(d.proj.id); + assert.equal(rel!.status, "removed"); + }); + + test("project without deploy settings: the step is skipped", async () => { + const d = await deployable(null); + const r = await d.run("staging", d.merge("x")); + assert.equal(r.code, 0); + assert.match(r.out, /деплой не настроен/); + assert.equal((await releases(d.proj.id)).length, 0); + }); +}); + +describe("Проверка здоровья и откат", () => { + test("Scenario: Неудачный релиз — прод возвращён на предыдущий, релиз помечен «откат», PM получает причину и лог", async () => { + const d = await deployable(); + const good = d.merge(`${d.p.key}-1`); + assert.equal((await d.run("prod", good)).code, 0); + const bad = d.merge(`${d.p.key}-2`); + badImages.add(`peppa/${d.proj.slug}:${bad}`); + const r = await d.run("prod", bad); + assert.equal(r.code, 1); + assert.equal(d.container("prod"), `peppa/${d.proj.slug}:${good}`, "prod is back on the previous release"); + const rel = (await releases(d.proj.id)).find((x) => x.sha === bad)!; + assert.equal(rel.status, "rolled_back"); + assert.equal(rel.previousSha, good); + assert.match(rel.reason ?? "", /проверка \/healthz не прошла за 2 с/); + assert.deepEqual(rel.tasks, [`${d.p.key}-2`], "only what was merged since the previous release"); + const msg = (await core.pendingQuestions(db, d.proj.id)).find((q) => q.text.includes(bad.slice(0, 7)) && q.text.includes("не прошёл"))!; + assert.ok(msg, "the PM got a message"); + assert.match(msg.text, new RegExp(`возвращён ${good.slice(0, 7)}`)); + assert.match(msg.text, /Причина: проверка \/healthz/); + assert.match(msg.text, new RegExp(`Лог: ${gitea.url}/test/${d.proj.giteaRepo}/actions/runs/5`)); + assert.equal((await runner.currentReleases(db, d.proj.id)).prod?.sha, good); + }); + + test("first release fails its health check: nothing to roll back to, release failed", async () => { + const d = await deployable(); + const sha = d.merge("first"); + badImages.add(`peppa/${d.proj.slug}:${sha}`); + assert.equal((await d.run("staging", sha)).code, 1); + const [rel] = await releases(d.proj.id); + assert.equal(rel!.status, "failed"); + assert.match(rel!.reason ?? "", /откатывать не на что/); + }); + + test("image build fails: release failed, the running stand is untouched", async () => { + const d = await deployable(); + const good = d.merge("a"); + assert.equal((await d.run("staging", good)).code, 0); + const r = await d.run("staging", d.merge("b"), { MOCK_DOCKER_BUILD_FAIL: "1" }); + assert.equal(r.code, 1); + assert.equal(d.container("staging"), `peppa/${d.proj.slug}:${good}`); + assert.equal((await releases(d.proj.id)).at(-1)!.reason, "сборка образа не удалась"); + }); +}); diff --git a/template/.gitea/peppa-deploy.sh b/template/.gitea/peppa-deploy.sh new file mode 100644 index 00000000..98eabe51 --- /dev/null +++ b/template/.gitea/peppa-deploy.sh @@ -0,0 +1,116 @@ +#!/usr/bin/env bash +# Деплой проекта Пеппы: bash .gitea/peppa-deploy.sh <preview|staging|prod|preview-down> +# Образ peppa/<slug>:<sha> собирается из Dockerfile (deploy.dockerfile) на docker хоста, +# поднимается `docker compose -p <slug>-<окружение>` за Traefik, затем проверка здоровья +# (deploy.health, по умолчанию /healthz, PEPPA_HEALTH_TIMEOUT секунд, по умолчанию 120). +# Не прошла — откат на образ, который работал до этого. Итог уходит в Пеппу (подпись +# PEPPA_CI_SECRET): окружение, SHA, предыдущий SHA, коммиты (для списка задач), хвост лога. +set -uo pipefail +mode="$1" +cfg=.peppa/project.json +compose=$(jq -r '.deploy.compose // empty' "$cfg" 2>/dev/null) +if [[ -z "$compose" || ! -f "$compose" ]]; then + echo "peppa: деплой не настроен (.peppa/project.json → deploy.compose) — пропуск" + exit 0 +fi +slug=$(jq -r '.slug' "$cfg") +service=$(jq -r '.deploy.service // "web"' "$cfg") +port=$(jq -r '.deploy.port // 3000' "$cfg") +health=$(jq -r '.deploy.health // "/healthz"' "$cfg") +migrate=$(jq -r '.deploy.migrate // empty' "$cfg") +dockerfile=$(jq -r '.deploy.dockerfile // "Dockerfile"' "$cfg") +domain="${PEPPA_DEPLOY_DOMAIN:-telecom.quest}" +timeout="${PEPPA_HEALTH_TIMEOUT:-120}" +sha="${PEPPA_SHA:-${GITHUB_SHA:-$(git rev-parse HEAD)}}" +pr="${PEPPA_PR:-}" + +env_name="$mode" +[[ $mode == preview-down ]] && env_name=preview +# Один уровень поддомена: сертификат Cloudflare покрывает только *.telecom.quest. +case "$env_name" in + preview) project="$slug-pr$pr"; host="$slug-pr$pr.$domain" ;; + staging) project="$slug-staging"; host="$slug-staging.$domain" ;; + prod) project="$slug-prod"; host="$slug-prod.$domain" ;; + *) echo "usage: peppa-deploy.sh <preview|staging|prod|preview-down>" >&2; exit 2 ;; +esac +custom=$(jq -r --arg e "$env_name" '.deploy.hosts[$e] // empty' "$cfg") +[[ -n "$custom" ]] && host="${custom//\{pr\}/$pr}" +image="peppa/$slug:$sha" +router=$(tr -c 'a-zA-Z0-9\n' - <<<"$project") +container="$project-$service-1" +log=$(mktemp) +exec > >(tee -a "$log") 2>&1 + +prev_image=$(docker inspect -f '{{.Config.Image}}' "$container" 2>/dev/null || true) +prev_sha="" +[[ $prev_image == peppa/$slug:* ]] && prev_sha="${prev_image##*:}" + +report() { # report <status> [reason] + local status="$1" reason="${2:-}" peppa_url commits body sig + echo "peppa: $env_name $status${reason:+ — $reason}" + peppa_url=$(jq -r '.peppaUrl // empty' "$cfg") + [[ -n "$peppa_url" && -n "${PEPPA_CI_SECRET:-}" ]] || return 0 + if [[ -n "$prev_sha" ]] && git cat-file -e "$prev_sha^{commit}" 2>/dev/null; then + commits=$(git log --format=%s "$prev_sha..$sha" 2>/dev/null | head -n 200 | jq -Rsc 'split("\n") | map(select(. != ""))') + else + commits=$(git log --format=%s -n 20 "$sha" 2>/dev/null | jq -Rsc 'split("\n") | map(select(. != ""))') + fi + body=$(tail -n 200 "$log" | jq -Rs --arg repo "${GITHUB_REPOSITORY:-}" --arg env "$env_name" --arg sha "$sha" \ + --arg prev "$prev_sha" --arg image "$image" --arg host "$host" --arg pr "$pr" --arg status "$status" \ + --arg reason "$reason" --arg url "/${GITHUB_REPOSITORY:-}/actions/runs/${GITHUB_RUN_NUMBER:-0}" --arg ref "${GITHUB_REF:-}" \ + --argjson commits "${commits:-[]}" \ + '{repository:$repo, env:$env, sha:$sha, previous_sha:(if $prev == "" then null else $prev end), image:$image, host:$host, + pr:($pr|tonumber? // null), status:$status, reason:(if $reason == "" then null else $reason end), run_url:$url, ref:$ref, + commits:$commits, log_tail:.}') + sig=$(printf '%s' "$body" | openssl dgst -sha256 -hmac "$PEPPA_CI_SECRET" | awk '{print $NF}') + curl -fsS -o /dev/null -m 20 -X POST "$peppa_url/api/hooks/gitea" -H "Content-Type: application/json" \ + -H "X-Peppa-Event: deploy" -H "X-Gitea-Signature: $sig" --data-binary "$body" || + echo "peppa: Пеппа недоступна — релиз не записан" +} + +dc() { # dc <image> <compose args…> + local img="$1"; shift + IMAGE="$img" HOST="$host" ROUTER="$router" APP_PORT="$port" docker compose -p "$project" -f "$compose" "$@" +} + +healthy() { + local url="${PEPPA_HEALTH_BASE:-http://$container:$port}" deadline=$((SECONDS + timeout)) + url="${url//\{project\}/$project}$health" + while ((SECONDS < deadline)); do + curl -fsS -o /dev/null -m 5 "$url" && return 0 + sleep "${PEPPA_HEALTH_INTERVAL:-3}" + done + return 1 +} + +if [[ $mode == preview-down ]]; then + dc "$image" down --remove-orphans || true + report removed + exit 0 +fi + +report deploying +if ! docker image inspect "$image" >/dev/null 2>&1; then + docker build -t "$image" --label "peppa.project=$slug" -f "$dockerfile" . || { report failed "сборка образа не удалась"; exit 1; } +fi +if [[ -n "$migrate" ]]; then + dc "$image" run --rm "$service" sh -c "$migrate" || { report failed "миграция не удалась"; exit 1; } +fi +dc "$image" up -d --remove-orphans || { report failed "docker compose up не удался"; exit 1; } +if healthy; then + report healthy + docker image prune -af --filter "label=peppa.project=$slug" --filter "until=336h" >/dev/null 2>&1 || true + exit 0 +fi +why="проверка $health не прошла за ${timeout} с" +if [[ -n "$prev_image" && "$prev_image" != "$image" ]]; then + echo "peppa: $why — откат на $prev_image" + if dc "$prev_image" up -d --remove-orphans && healthy; then + report rolled_back "$why" + else + report failed "$why; откат на $prev_image тоже не поднялся" + fi +else + report failed "$why; откатывать не на что" +fi +exit 1 diff --git a/template/.gitea/workflows/deploy.yml b/template/.gitea/workflows/deploy.yml new file mode 100644 index 00000000..7400926c --- /dev/null +++ b/template/.gitea/workflows/deploy.yml @@ -0,0 +1,35 @@ +# CD проекта Пеппы (PEP-57): preview на PR (удаляется при закрытии), staging на мерж в main, +# прод — тег deploy-prod-* (его ставит Пеппа по кнопке PM). Настройки — .peppa/project.json → +# "deploy"; без них шаг пропускается. Изменение файла PM видит отдельно. +name: deploy +on: + push: + branches: [main] + tags: ["deploy-prod-*"] + pull_request: + types: [opened, synchronize, reopened, closed] +env: + PEPPA_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + PEPPA_BRANCH: ${{ github.head_ref || github.ref_name }} + PEPPA_PR: ${{ github.event.pull_request.number }} + PEPPA_PR_ACTION: ${{ github.event.action }} + PEPPA_CI_SECRET: ${{ secrets.PEPPA_CI_SECRET }} + GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} +jobs: + deploy: + # Раннер с docker.sock хоста: только ветки этого репозитория, PR из форков не запускаются. + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: peppa-trusted + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.PEPPA_SHA }} + fetch-depth: 0 + - name: deploy + run: | + if [[ "$GITHUB_EVENT_NAME" == pull_request ]]; then + [[ "$PEPPA_PR_ACTION" == closed ]] && exec bash .gitea/peppa-deploy.sh preview-down + exec bash .gitea/peppa-deploy.sh preview + fi + [[ "$GITHUB_REF" == refs/tags/deploy-prod-* ]] && exec bash .gitea/peppa-deploy.sh prod + exec bash .gitea/peppa-deploy.sh staging diff --git a/template/RULES.md b/template/RULES.md index 84829fae..dd7c0e47 100644 --- a/template/RULES.md +++ b/template/RULES.md @@ -86,6 +86,24 @@ PM отвечает только на **архитектурные стоппе отдельно, такой PR не мержится автоматически — опиши в PR, зачем это нужно. - Задача попадает в ревью и мержится только с зелёными проверками последнего коммита. +## CD: деплой + +Деплой описывает `.peppa/project.json` → `deploy` и `Dockerfile` в корне (заготовки — +`deploy/Dockerfile.node`, `deploy/Dockerfile.python`; стенд — `deploy/compose.yml`): + +```json +{ "deploy": { "compose": "deploy/compose.yml", "service": "web", "port": 3000, + "health": "/healthz", "migrate": "pnpm db:migrate" } } +``` + +- Приложение слушает `$PORT` и отвечает 200 на `GET /healthz` (`deploy.health`) — без этого + деплой считается неудачным и откатывается. +- PR получает preview `<slug>-pr<N>.telecom.quest`, мерж в main — staging + `<slug>-staging.telecom.quest`, прод `<slug>-prod.telecom.quest` выкатывает только PM. +- Проверить локально: `docker build .` и запуск образа с `PORT=3000`, затем `curl /healthz`. +- Секреты приложения — не в репозиторий: попроси PM через `ask_pm` завести их в secrets + Actions репозитория и передай в `deploy/compose.yml` через `environment`. + ## Спецификации — сценарии в формате Gherkin Требования в `specs/**/spec.md` пиши как раньше (`### Requirement:` + текст с SHALL), а diff --git a/template/deploy/Dockerfile.node b/template/deploy/Dockerfile.node new file mode 100644 index 00000000..5854142d --- /dev/null +++ b/template/deploy/Dockerfile.node @@ -0,0 +1,16 @@ +# Заготовка для Node.js (pnpm). Скопируй в ./Dockerfile и поправь под проект. +# Приложение слушает $PORT и отвечает 200 на GET /healthz (deploy.health). +FROM node:22-bookworm-slim AS build +WORKDIR /app +RUN corepack enable +COPY package.json pnpm-lock.yaml* ./ +RUN pnpm install --frozen-lockfile +COPY . . +RUN pnpm build + +FROM node:22-bookworm-slim +WORKDIR /app +ENV NODE_ENV=production PORT=3000 +COPY --from=build /app ./ +EXPOSE 3000 +CMD ["node", "dist/index.js"] diff --git a/template/deploy/Dockerfile.python b/template/deploy/Dockerfile.python new file mode 100644 index 00000000..b2dbc0ec --- /dev/null +++ b/template/deploy/Dockerfile.python @@ -0,0 +1,10 @@ +# Заготовка для Python. Скопируй в ./Dockerfile и поправь под проект. +# Приложение слушает $PORT и отвечает 200 на GET /healthz (deploy.health). +FROM python:3.12-slim +WORKDIR /app +ENV PYTHONUNBUFFERED=1 PORT=3000 +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt +COPY . . +EXPOSE 3000 +CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT}"] diff --git a/template/deploy/compose.yml b/template/deploy/compose.yml new file mode 100644 index 00000000..01936ba5 --- /dev/null +++ b/template/deploy/compose.yml @@ -0,0 +1,21 @@ +# Стенд проекта Пеппы (PEP-57). Деплой: docker compose -p <slug>-<env> -f deploy/compose.yml up -d +# с переменными IMAGE (образ peppa/<slug>:<sha>), HOST, ROUTER, APP_PORT — их задаёт +# .gitea/peppa-deploy.sh. Сервис и порт — .peppa/project.json → deploy.service / deploy.port. +# Секреты приложения — в secrets Actions репозитория, сюда только через environment. +services: + web: + image: ${IMAGE} + restart: unless-stopped + environment: + PORT: "${APP_PORT:-3000}" + networks: + - traefik_default + labels: + - traefik.enable=true + - traefik.docker.network=traefik_default + - traefik.http.routers.${ROUTER}.rule=Host(`${HOST}`) + - traefik.http.routers.${ROUTER}.entrypoints=web + - traefik.http.services.${ROUTER}.loadbalancer.server.port=${APP_PORT:-3000} +networks: + traefik_default: + external: true