diff --git a/AGENTS.md b/AGENTS.md index b8cbc6b6..b0a35ab1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,6 +29,8 @@ - **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (`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 пройдены») - `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/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index ef33e308..c46919d0 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -6,6 +6,7 @@ import { requireUser } from "@/lib/auth"; import { openspecArtifacts, taskActivity, taskForUser } from "@/lib/queries"; import { db } from "@/lib/db"; import { goals } from "@peppa/db"; +import { taskCiSummary } from "@peppa/core"; import { eq } from "drizzle-orm"; import { startTaskSession } from "../../actions"; @@ -19,6 +20,7 @@ export default async function TaskPage({ params, searchParams }: { params: Promi const [goal] = task.goalId ? await db.select().from(goals).where(eq(goals.id, task.goalId)) : []; const { questions, sessions, events } = await taskActivity(task.id); const artifacts = openspecArtifacts(project, task.openspecChange); + const ci = await taskCiSummary(db, ref); const back = `/t/${ref.key}`; return ( <> @@ -32,6 +34,23 @@ export default async function TaskPage({ params, searchParams }: { params: Promi {ref.key} {task.title} {task.prUrl &&

PR

} +
+

Проверки

+

+ {ci.state === "success" ? "✅ " : ci.state === "failure" ? "❌ " : ci.state === "pending" ? "⏳ " : ""} + {ci.runUrl ? {ci.label} : ci.label} + {ci.sha && · {ci.sha.slice(0, 7)}} + {task.ciAttempts > 0 && · красных подряд: {task.ciAttempts}} +

+ {ci.failed.map((f) => ( +
+ + ❌ {f.check} {f.runUrl && лог} + + {f.logTail &&
{f.logTail.split("\n").slice(-60).join("\n")}
} +
+ ))} +

{task.description || Без описания}

diff --git a/apps/web/app/api/hooks/gitea/route.ts b/apps/web/app/api/hooks/gitea/route.ts new file mode 100644 index 00000000..ffb6c599 --- /dev/null +++ b/apps/web/app/api/hooks/gitea/route.ts @@ -0,0 +1,18 @@ +import { handleGiteaHook } from "@peppa/runner"; +import { db } from "@/lib/db"; + +export const dynamic = "force-dynamic"; + +/** + * Gitea webhooks and CI step reports of project repos (PEP-57). No login: each request is + * signed (X-Gitea-Signature, HMAC-SHA256 of the body) with the project's secret. + */ +export async function POST(req: Request) { + const body = await req.text(); + const r = await handleGiteaHook(db, { + event: req.headers.get("x-peppa-event") ?? req.headers.get("x-gitea-event") ?? "", + signature: req.headers.get("x-gitea-signature"), + body, + }); + return Response.json(r.body, { status: r.status }); +} diff --git a/openspec/changes/pep-57-ci-cd/design.md b/openspec/changes/pep-57-ci-cd/design.md index e7334f63..49185f5f 100644 --- a/openspec/changes/pep-57-ci-cd/design.md +++ b/openspec/changes/pep-57-ci-cd/design.md @@ -66,3 +66,11 @@ Gitea 1.22 на `git.telecom.quest`, Actions в конфиге явно не н хранится). Тот же секрет — у вебхука Gitea проекта. - **Статусы**: `install` сообщает только о провале; «N из N» считается по статусам `peppa/*` головного SHA. +- **Вебхуки Gitea**: `pull_request` и `push` (события `status` в 1.22 нет); статусы проверок + приходят отчётом шага CI, запасной путь — опрос статусов вачдогом раз в минуту. +- **Попытка** = красный прогон нового головного SHA; несколько красных проверок одного коммита — + одна попытка. Зелёный прогон обнуляет счётчик. +- **Гейт ревью открыт при недоступной Gitea** (иначе агент застрянет); мерж по «Принять» в этом + случае всё равно не пройдёт. Задача без PR и проект без `checks` гейт не проходят — он выключен. +- **Автомерж** (`autoMergeTask`) готов, но не подключён к триггеру — режим авто-мержа проекта + появится в PEP-23/25. diff --git a/openspec/changes/pep-57-ci-cd/tasks.md b/openspec/changes/pep-57-ci-cd/tasks.md index 768d3037..5cc94c2f 100644 --- a/openspec/changes/pep-57-ci-cd/tasks.md +++ b/openspec/changes/pep-57-ci-cd/tasks.md @@ -10,14 +10,14 @@ - [x] 1.1 `infra/`: act_runner в docker (метка `peppa-trusted`), включить Actions в Gitea; проверка: тестовый workflow в `peppa-bot/sandbox` зелёный - [x] 1.2 Шаблон: `.gitea/workflows/ci.yml` (читает `checks` из `.peppa/project.json`), поля `checks`/`deploy` в project.json, раздел в RULES.md «перед PR запусти checks локально»; залить шаблон -- [ ] 1.3 Команда «подключить CI к существующему проекту» (PR от Пеппы); применить к SBX +- [x] 1.3 Команда «подключить CI к существующему проекту» (PR от Пеппы); применить к SBX ## 2. Обратная связь и гейты -- [ ] 2.1 `check_runs` + приём статусов: вебхук Gitea с подписью (общая часть с PEP-46) и опрос статуса как запасной путь; mock-gitea: статусы коммитов и вебхуки -- [ ] 2.2 Возврат красного CI раннеру (шаг + хвост лога), счётчик 3 попыток, вопрос PM; гейты в `moveTask`/`acceptTask`; правило «изменение конвейера требует ревью» -- [ ] 2.3 Веб: проверки в карточке задачи (вкладка Tests из PEP-32 или блок до неё); MCP `get_task` показывает статус проверок -- [ ] 2.4 Тесты: по одному на каждый сценарий спецификации разделов «Проверки», «Красные проверки», «Гейт» +- [x] 2.1 `check_runs` + приём статусов: вебхук Gitea с подписью (общая часть с PEP-46) и опрос статуса как запасной путь; mock-gitea: статусы коммитов и вебхуки +- [x] 2.2 Возврат красного CI раннеру (шаг + хвост лога), счётчик 3 попыток, вопрос PM; гейты в `moveTask`/`acceptTask`; правило «изменение конвейера требует ревью» +- [x] 2.3 Веб: проверки в карточке задачи (вкладка Tests из PEP-32 или блок до неё); MCP `get_task` показывает статус проверок +- [x] 2.4 Тесты: по одному на каждый сценарий спецификации разделов «Проверки», «Красные проверки», «Гейт» ## 3. CD diff --git a/packages/core/src/ci.ts b/packages/core/src/ci.ts new file mode 100644 index 00000000..06a5a5cb --- /dev/null +++ b/packages/core/src/ci.ts @@ -0,0 +1,191 @@ +// CI results of factory projects (PEP-57): check runs per commit, the summary shown on the +// task card and the gate for review and merge (green checks of the PR head, no conflicts). +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { checkRuns, tasks, type Db } from "@peppa/db"; +import { CHECK_NAMES, formatTaskKey, loadEnv, type CheckName, type PeppaProjectFile } from "@peppa/shared"; +import { and, desc, eq } from "drizzle-orm"; +import type { GiteaClient, GiteaPull } from "./gitea.ts"; +import { giteaForBot } from "./users.ts"; +import type { Project } from "./projects.ts"; +import type { TaskRef } from "./tasks.ts"; + +export type CheckRun = typeof checkRuns.$inferSelect; +export type CheckState = CheckRun["state"]; + +export interface CheckReport { + sha: string; + branch?: string | null; + prNumber?: number | null; + check: string; + state: CheckState; + runUrl?: string | null; + logTail?: string | null; + durationSec?: number | null; + source?: CheckRun["source"]; +} + +/** Commands configured in a project file (JSON text); missing/empty ones are skipped by CI. */ +export function configuredChecks(projectJson: string | null | undefined): CheckName[] { + if (!projectJson) return []; + try { + const checks = (JSON.parse(projectJson) as PeppaProjectFile).checks ?? {}; + return CHECK_NAMES.filter((c) => typeof checks[c] === "string" && checks[c]!.trim() !== ""); + } catch { + return []; + } +} + +/** Full link to a run: CI reports relative `/owner/repo/actions/runs/N`. */ +export function runLink(url: string | null | undefined): string | null { + if (!url) return null; + return url.startsWith("/") ? `${loadEnv().GITEA_URL}${url}` : url; +} + +export interface CiSummary { + state: "not_configured" | "none" | "pending" | "success" | "failure"; + passed: number; + total: number; + sha: string | null; + runUrl: string | null; + failed: Array<{ check: string; runUrl: string | null; logTail?: string | null }>; + /** One line for the task card, e.g. "Проверки: 4 из 4 пройдены". */ + label: string; +} + +type RunLike = { check: string; state: CheckState; runUrl?: string | null; logTail?: string | null }; + +export function summarizeChecks(configured: string[], runs: RunLike[], sha: string | null): CiSummary { + const total = configured.length; + const base = { sha, total, runUrl: runLink(runs.find((r) => r.runUrl)?.runUrl) }; + if (!total) return { ...base, state: "not_configured", passed: 0, failed: [], label: "проверки не настроены" }; + // `install` is not a check of its own, but when it fails nothing else ran. + const failed = runs.filter((r) => r.state === "failure" || r.state === "error").map((r) => ({ check: r.check, runUrl: runLink(r.runUrl), logTail: r.logTail })); + const passed = configured.filter((c) => runs.some((r) => r.check === c && r.state === "success")).length; + if (failed.length) return { ...base, state: "failure", passed, failed, label: `Проверки: ${passed} из ${total} пройдены, упало: ${failed.map((f) => f.check).join(", ")}` }; + if (passed === total) return { ...base, state: "success", passed, failed, label: `Проверки: ${passed} из ${total} пройдены` }; + if (!runs.length) return { ...base, state: "none", passed, failed, label: "Проверки ещё не запускались" }; + return { ...base, state: "pending", passed, failed, label: `Проверки идут: ${passed} из ${total}` }; +} + +/** Stores a CI result (one row per project/commit/check). `changed` — the state is new. */ +export async function upsertCheckRun(db: Db, project: Project, taskId: number | null, r: CheckReport): Promise<{ run: CheckRun; changed: boolean }> { + const [prev] = await db + .select() + .from(checkRuns) + .where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.sha, r.sha), eq(checkRuns.check, r.check))); + const values = { + taskId: taskId ?? prev?.taskId ?? null, + branch: r.branch ?? prev?.branch ?? null, + prNumber: r.prNumber ?? prev?.prNumber ?? null, + state: r.state, + runUrl: r.runUrl ?? prev?.runUrl ?? null, + // A poll carries no log: keep the one the CI step sent. + logTail: r.logTail ?? prev?.logTail ?? null, + durationSec: r.durationSec ?? prev?.durationSec ?? null, + source: r.source ?? "report", + }; + const [run] = prev + ? await db.update(checkRuns).set(values).where(eq(checkRuns.id, prev.id)).returning() + : await db.insert(checkRuns).values({ projectId: project.id, sha: r.sha, check: r.check, ...values }).returning(); + return { run: run!, changed: prev?.state !== r.state }; +} + +/** PR number of a task's pr_url when it points at the project's repo. */ +export function taskPrNumber(project: Project, prUrl: string | null | undefined): number | null { + const m = prUrl?.match(/\/([^/]+)\/([^/]+)\/pulls\/(\d+)/); + if (!m || m[1]!.toLowerCase() !== project.giteaOwner.toLowerCase() || m[2]!.toLowerCase() !== project.giteaRepo.toLowerCase()) return null; + return Number(m[3]); +} + +/** Task of a CI result: its branch `task/-…`, or the task whose PR it is. */ +export async function taskForCheck(db: Db, project: Project, branch: string | null | undefined, prNumber: number | null | undefined): Promise { + const m = branch?.match(new RegExp(`^task/${project.key}-(\\d+)`, "i")); + if (m) { + const [task] = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.number, Number(m[1])))); + if (task) return { project, task, key: formatTaskKey(project.key, task.number) }; + } + if (prNumber) { + for (const task of await db.select().from(tasks).where(eq(tasks.projectId, project.id))) { + if (taskPrNumber(project, task.prUrl) === prNumber) return { project, task, key: formatTaskKey(project.key, task.number) }; + } + } + return null; +} + +function workspaceProjectJson(project: Project): string | null { + const f = join(project.workspacePath, ".peppa/project.json"); + return existsSync(f) ? readFileSync(f, "utf8") : null; +} + +/** For the task card and MCP (no Gitea calls): checks of the task's latest commit. */ +export async function taskCiSummary(db: Db, ref: TaskRef): Promise { + const runs = await db.select().from(checkRuns).where(eq(checkRuns.taskId, ref.task.id)).orderBy(desc(checkRuns.updatedAt)); + const sha = runs[0]?.sha ?? null; + return summarizeChecks(configuredChecks(workspaceProjectJson(ref.project)), runs.filter((r) => r.sha === sha), sha); +} + +export interface GateResult { + ok: boolean; + /** Why not, for the PM: "проверки не пройдены", conflicts… */ + reason?: string; + summary: CiSummary | null; + pull: GiteaPull | null; +} + +/** + * Gate for review and merge: the task's PR head has green checks and no conflicts. A task + * without a PR or a project without checks passes (the card says "проверки не настроены"). + */ +export async function prGate(ref: TaskRef, client?: GiteaClient): Promise { + const n = taskPrNumber(ref.project, ref.task.prUrl); + if (!n) return { ok: true, summary: null, pull: null }; + const gitea = client ?? giteaForBot(); + const { giteaOwner: o, giteaRepo: r } = ref.project; + const pull = await gitea.getPullRequest(o, r, n); + if (pull.merged) return { ok: true, summary: null, pull }; + const [projectJson, status] = await Promise.all([gitea.fileText(o, r, ".peppa/project.json", pull.head.sha), gitea.combinedStatus(o, r, pull.head.sha)]); + const runs = (status.statuses ?? []) + .filter((s) => s.context.startsWith("peppa/")) + .map((s) => ({ check: s.context.slice(6), state: (s.status === "error" || s.status === "failure" ? "failure" : s.status === "success" ? "success" : "pending") as CheckState, runUrl: s.target_url })); + const summary = summarizeChecks(configuredChecks(projectJson), runs, pull.head.sha); + if (summary.state === "failure") return { ok: false, reason: `проверки не пройдены (${summary.failed.map((f) => f.check).join(", ")})`, summary, pull }; + if (summary.state === "pending" || summary.state === "none") return { ok: false, reason: `проверки ещё идут (${summary.passed} из ${summary.total})`, summary, pull }; + if (pull.state === "open" && pull.mergeable === false) return { ok: false, reason: "есть конфликты с основной веткой", summary, pull }; + return { ok: true, summary, pull }; +} + +/** Files that define the pipeline: changing them needs the PM's review even in auto mode. */ +export function isPipelineFile(path: string): boolean { + return path.startsWith(".gitea/") || path === ".peppa/project.json"; +} + +/** + * Pipeline changes in a PR: workflow files, or `checks`/`deploy` in .peppa/project.json + * (other fields of the project file are not the pipeline). Empty = none. + */ +export async function pipelineChanges(ref: TaskRef, pull: GiteaPull, gitea: GiteaClient = giteaForBot()): Promise { + const { giteaOwner: o, giteaRepo: r } = ref.project; + const out: string[] = []; + for (const f of (await gitea.pullFiles(o, r, pull.number)).filter(isPipelineFile)) { + if (f !== ".peppa/project.json") { + out.push(f); + continue; + } + const [before, after] = await Promise.all([gitea.fileText(o, r, f, pull.base.ref), gitea.fileText(o, r, f, pull.head.sha)]); + const pick = (t: string | null) => { + try { + const j = JSON.parse(t ?? "{}") as PeppaProjectFile; + return { checks: j.checks ?? {}, deploy: j.deploy ?? {} }; + } catch { + return null; + } + }; + const a = pick(before); + const b = pick(after); + for (const k of ["checks", "deploy"] as const) { + if (JSON.stringify(a?.[k]) !== JSON.stringify(b?.[k])) out.push(`${f} → ${k}: ${JSON.stringify(a?.[k] ?? null)} → ${JSON.stringify(b?.[k] ?? null)}`); + } + } + return out; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d01c9289..c224e041 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -15,3 +15,4 @@ export * from "./access.ts"; export * from "./monitor.ts"; export * from "./repo-info.ts"; export * from "./incidents.ts"; +export * from "./ci.ts"; diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index 10610281..15d397f5 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -5,6 +5,7 @@ import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import { getGoal, getProject, type Goal, type Project } from "./projects.ts"; import { incidentForTask, type Incident } from "./incidents.ts"; +import { taskCiSummary, type CiSummary } from "./ci.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -119,6 +120,8 @@ export interface TaskDetails { recentEvents: Array; /** The production error this task fixes (PEP-58), if any. */ incident: Incident | null; + /** CI checks of the task's latest commit (PEP-57). */ + ci: CiSummary; } export async function getTaskDetails(db: Db, ref: TaskRef): Promise { @@ -131,7 +134,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise .orderBy(desc(events.id)) .limit(20); const incident = await incidentForTask(db, ref.task.id); - return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident }; + return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref) }; } export interface NewQuestion { diff --git a/packages/db/migrations/0012_faithful_matthew_murdock.sql b/packages/db/migrations/0012_faithful_matthew_murdock.sql new file mode 100644 index 00000000..8e8e5e30 --- /dev/null +++ b/packages/db/migrations/0012_faithful_matthew_murdock.sql @@ -0,0 +1,22 @@ +CREATE TABLE "check_runs" ( + "id" serial PRIMARY KEY NOT NULL, + "project_id" integer NOT NULL, + "task_id" integer, + "sha" text NOT NULL, + "branch" text, + "pr_number" integer, + "check" text NOT NULL, + "state" text NOT NULL, + "run_url" text, + "log_tail" text, + "duration_sec" integer, + "source" text DEFAULT 'report' NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "tasks" ADD COLUMN "ci_attempts" integer DEFAULT 0 NOT NULL;--> statement-breakpoint +ALTER TABLE "tasks" ADD COLUMN "ci_failed_sha" text;--> statement-breakpoint +ALTER TABLE "check_runs" ADD CONSTRAINT "check_runs_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "check_runs" ADD CONSTRAINT "check_runs_task_id_tasks_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."tasks"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "check_runs_project_sha_check" ON "check_runs" USING btree ("project_id","sha","check"); \ No newline at end of file diff --git a/packages/db/migrations/meta/0012_snapshot.json b/packages/db/migrations/meta/0012_snapshot.json new file mode 100644 index 00000000..c30f3501 --- /dev/null +++ b/packages/db/migrations/meta/0012_snapshot.json @@ -0,0 +1,2061 @@ +{ + "id": "ca89d235-ea51-4284-95fe-50b24621c88a", + "prevId": "47a9fc06-6fdb-42ad-8a5f-d80e76193258", + "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.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 309369cd..7c258cac 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -85,6 +85,13 @@ "when": 1794561166402, "tag": "0011_pep58_incidents", "breakpoints": true + }, + { + "idx": 12, + "version": "7", + "when": 1794562626634, + "tag": "0012_faithful_matthew_murdock", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index d05ef5cb..a055a2bd 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -109,12 +109,38 @@ export const tasks = pgTable( // OpenSpec change id under openspec/changes/, e.g. "pep-42-add-auth" openspecChange: text("openspec_change"), prUrl: text("pr_url"), + // PEP-57: red CI runs in a row (distinct head SHAs) since the last green one. + ciAttempts: integer("ci_attempts").notNull().default(0), + ciFailedSha: text("ci_failed_sha"), createdAt: createdAt(), updatedAt: updatedAt(), }, (t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)], ); +/** PEP-57: one CI check (lint/typecheck/test/build/install) of one commit of a project. */ +export const checkRuns = pgTable( + "check_runs", + { + id: serial("id").primaryKey(), + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), + sha: text("sha").notNull(), + branch: text("branch"), + prNumber: integer("pr_number"), + check: text("check").notNull(), + state: text("state", { enum: ["pending", "success", "failure", "error"] }).notNull(), + runUrl: text("run_url"), + logTail: text("log_tail"), + durationSec: integer("duration_sec"), + // "report" — the CI step itself (with the log), "poll" — commit status read by the watchdog. + source: text("source", { enum: ["report", "poll"] }).notNull().default("report"), + createdAt: createdAt(), + updatedAt: updatedAt(), + }, + (t) => [uniqueIndex("check_runs_project_sha_check").on(t.projectId, t.sha, t.check)], +); + export const sessionStatus = pgEnum("session_status", [ "starting", "running", diff --git a/packages/mcp/src/format.ts b/packages/mcp/src/format.ts index fcb28d51..a076ca01 100644 --- a/packages/mcp/src/format.ts +++ b/packages/mcp/src/format.ts @@ -21,6 +21,8 @@ export function formatTask(d: TaskDetails): string { `- OpenSpec change: ${task.openspecChange ? `\`openspec/changes/${task.openspecChange}/\`` : "ещё нет"}`, ]; if (task.prUrl) lines.push(`- PR: ${task.prUrl}`); + lines.push(`- ${d.ci.label.charAt(0).toUpperCase()}${d.ci.label.slice(1)}${d.ci.sha ? ` (коммит ${d.ci.sha.slice(0, 7)})` : ""}${d.ci.runUrl ? ` · ${d.ci.runUrl}` : ""}`); + for (const f of d.ci.failed) lines.push(` - ❌ ${f.check}${f.runUrl ? ` · ${f.runUrl}` : ""}`); lines.push("", "## Описание", "", task.description?.trim() || "_нет описания_"); if (goal?.description) lines.push("", `## Цель #${goal.id}: ${goal.title}`, "", goal.description.trim()); if (d.incident) lines.push("", "## Инцидент", "", formatIncident(d.incident)); diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index fa0c9088..e44a540d 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -21,6 +21,7 @@ import { updateTask, } from "@peppa/core"; import { createDb } from "@peppa/db"; +import { reviewGate } from "@peppa/runner"; import { z } from "zod"; import { formatIncident, formatTask } from "./format.ts"; @@ -128,6 +129,13 @@ tool( if (status === "in_progress" && ref.task.status === "awaiting_approval") { throw new PeppaError("The proposal is awaiting the PM's approval; only the PM can move it to in_progress."); } + if (status === "review" && ref.task.status !== "review") { + // PEP-57: review only with green checks of the PR head (the PR given now counts). + const reason = await reviewGate({ ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } }); + if (reason) { + throw new PeppaError(`Not moved to review: ${reason}. Wait for the CI checks of the PR's last commit to pass (red ones come back to you with the log), then set status: review again.`); + } + } const t = await updateTask(db, ref, { status, openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId); return `${ref.key} updated: status=${t.status}${t.openspecChange ? `, change=${t.openspecChange}` : ""}${t.prUrl ? `, pr=${t.prUrl}` : ""}`; }, diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index 5f05522b..0f9d0fb3 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -272,7 +272,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ tool( "answer_question", - "Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' closes the task, any other text goes back to the agent.", + "Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' merges the task's PR (only with green CI checks and no conflicts, otherwise the reason is returned) and closes the task, any other text goes back to the agent.", { question_id: z.number().int(), answer: z.string().min(1) }, false, async ({ question_id, answer }) => { diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts new file mode 100644 index 00000000..0c76c0ec --- /dev/null +++ b/packages/runner/src/ci-feedback.ts @@ -0,0 +1,216 @@ +// CI feedback (PEP-57): results come from the CI step itself (signed report with the log), +// from Gitea webhooks, and from the watchdog polling commit statuses as a fallback. A red +// check goes back to the agent with the step and the log tail; 3 red runs in a row → the PM. +import { + askPm, + giteaForBot, + listSessions, + listTasks, + PeppaError, + prGate, + pipelineChanges, + runLink, + taskForCheck, + taskPrNumber, + upsertCheckRun, + verifyHookSignature, + type CheckReport, + type GiteaClient, + type Project, + type TaskRef, +} from "@peppa/core"; +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"; + +/** Red runs in a row after which the PM is asked instead of the agent. */ +export const MAX_CI_ATTEMPTS = 3; +const LOG_LINES = 100; + +const tail = (log: string | null | undefined, n = LOG_LINES) => (log ?? "").trimEnd().split("\n").slice(-n).join("\n"); + +async function activeSessionId(db: Db, taskId: number): Promise { + return (await listSessions(db, { active: true, taskId }))[0]?.id ?? null; +} + +export interface CheckOutcome { + task: string | null; + /** What Peppa did: nothing, told the agent, restarted it, asked the PM, reset the counter. */ + action: "none" | "agent" | "restarted" | "pm" | "green"; +} + +/** Records one CI result and reacts to it for the task of that branch/PR. */ +export async function recordCheck(db: Db, project: Project, r: CheckReport): Promise { + const ref = await taskForCheck(db, project, r.branch, r.prNumber); + const { changed } = await upsertCheckRun(db, project, ref?.task.id ?? null, r); + if (!ref || !changed) return { task: ref?.key ?? null, action: "none" }; + if (!["proposing", "in_progress", "review", "blocked"].includes(ref.task.status)) return { task: ref.key, action: "none" }; + + if (r.state === "success") { + const [red] = await db + .select({ id: checkRuns.id }) + .from(checkRuns) + .where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.sha, r.sha), sql`${checkRuns.state} in ('failure','error')`)); + if (red || ref.task.ciAttempts === 0) return { task: ref.key, action: "none" }; + await db.update(tasks).set({ ciAttempts: 0, ciFailedSha: null }).where(eq(tasks.id, ref.task.id)); + return { task: ref.key, action: "green" }; + } + if (r.state !== "failure" && r.state !== "error") return { task: ref.key, action: "none" }; + + // Several red checks of one commit are one attempt. + const newRun = ref.task.ciFailedSha !== r.sha; + const attempts = newRun ? ref.task.ciAttempts + 1 : ref.task.ciAttempts; + if (newRun) await db.update(tasks).set({ ciAttempts: attempts, ciFailedSha: r.sha }).where(eq(tasks.id, ref.task.id)); + const link = runLink(r.runUrl); + const sessionId = await activeSessionId(db, ref.task.id); + + if (attempts >= MAX_CI_ATTEMPTS) { + if (!newRun) return { task: ref.key, action: "none" }; // the PM already has this commit + await askPm(db, ref, { + kind: "question", + sessionId: sessionId ?? undefined, + text: `❌ ${ref.key}: проверки PR красные ${attempts} раза подряд — агент не справился сам. Упала «${r.check}» (коммит ${r.sha.slice(0, 7)}).${link ? `\nЛог: ${link}` : ""}\n\nЧто делать? Ответ уйдёт агенту.`, + }); + if (sessionId) { + await sendToSession(db, sessionId, `Проверки PR ${ref.key} красные ${attempts} раза подряд — я спросил PM. Не пушь новых попыток, закончи ход и жди ответа PM.`).catch(() => {}); + } + return { task: ref.key, action: "pm" }; + } + + const text = [ + `❌ CI по ${ref.key}: упала проверка «${r.check}» (коммит ${r.sha.slice(0, 7)}, попытка ${attempts} из ${MAX_CI_ATTEMPTS}).${link ? ` Лог: ${link}` : ""}`, + r.logTail ? `Последние строки лога:\n${tail(r.logTail)}` : "Лога в отчёте нет — открой ссылку.", + `Почини (локально: bash .gitea/peppa-check.sh ${r.check}) и запушь в ту же ветку; не ослабляй проверки.`, + ].join("\n\n"); + if (sessionId) { + await sendToSession(db, sessionId, text); + // The work is not done: a task that already went to review goes back. + if (ref.task.status === "review") await moveTask(db, ref, "in_progress"); + return { task: ref.key, action: "agent" }; + } + await moveTask(db, ref, "in_progress", { prompt: text }); + return { task: ref.key, action: "restarted" }; +} + +/** Project of a repository "owner/name" (case-insensitive). */ +export async function projectByRepo(db: Db, fullName: string): Promise { + const [owner, name] = fullName.split("/"); + if (!owner || !name) return null; + const [p] = await db + .select() + .from(projects) + .where(and(sql`lower(${projects.giteaOwner}) = ${owner.toLowerCase()}`, sql`lower(${projects.giteaRepo}) = ${name.toLowerCase()}`)); + return p ?? null; +} + +export interface HookRequest { + /** X-Gitea-Event (Gitea webhooks) or X-Peppa-Event (the CI step). */ + event: string; + signature: string | null; + body: string; +} + +/** Handlers for Gitea events other than CI checks (deploys hook in here). */ +export type GiteaEventHandler = (db: Db, project: Project, event: string, payload: Record) => Promise; +const eventHandlers: GiteaEventHandler[] = []; +export function onGiteaEvent(h: GiteaEventHandler) { + eventHandlers.push(h); +} + +/** POST /api/hooks/gitea: verifies the project's signature, then records/dispatches. */ +export async function handleGiteaHook(db: Db, req: HookRequest): Promise<{ status: number; body: Record }> { + let payload: Record; + try { + payload = JSON.parse(req.body) as Record; + } catch { + return { status: 400, body: { error: "invalid json" } }; + } + const repo = typeof payload.repository === "string" ? payload.repository : ((payload.repository as { full_name?: string } | undefined)?.full_name ?? ""); + const project = await projectByRepo(db, repo); + if (!project) return { status: 404, body: { error: "unknown repository" } }; + if (!verifyHookSignature(project.id, req.body, req.signature)) return { status: 401, body: { error: "bad signature" } }; + + if (req.event === "check") { + const state = String(payload.state); + if (!["success", "failure", "error", "pending"].includes(state) || typeof payload.sha !== "string" || typeof payload.check !== "string") { + return { status: 400, body: { error: "bad check report" } }; + } + const out = await recordCheck(db, project, { + sha: payload.sha, + branch: (payload.branch as string) || null, + prNumber: typeof payload.pr === "number" ? payload.pr : null, + check: payload.check, + state: state as CheckReport["state"], + runUrl: (payload.run_url as string) ?? null, + logTail: (payload.log_tail as string) ?? null, + durationSec: typeof payload.duration_sec === "number" ? payload.duration_sec : null, + source: "report", + }); + return { status: 200, body: { ok: true, ...out } }; + } + for (const h of eventHandlers) await h(db, project, req.event, payload); + return { status: 200, body: { ok: true } }; +} + +/** + * Fallback when reports/webhooks are lost: commit statuses `peppa/*` of the PR heads of + * tasks in work or review (the watchdog calls this about once a minute). + */ +export async function pollChecks(db: Db, gitea: GiteaClient = giteaForBot()): Promise { + let seen = 0; + for (const t of await listTasks(db, { statuses: ["in_progress", "review"] })) { + if (!t.prUrl) continue; + const [p] = await db.select().from(projects).where(eq(projects.id, t.projectId)); + const n = p && taskPrNumber(p, t.prUrl); + if (!p || !n) continue; + try { + const pull = await gitea.getPullRequest(p.giteaOwner, p.giteaRepo, n); + if (pull.state !== "open") continue; + const st = await gitea.combinedStatus(p.giteaOwner, p.giteaRepo, pull.head.sha); + for (const s of st.statuses ?? []) { + if (!s.context.startsWith("peppa/")) continue; + const state = s.status === "warning" ? "pending" : s.status; + await recordCheck(db, p, { sha: pull.head.sha, branch: pull.head.ref, prNumber: n, check: s.context.slice(6), state, runUrl: s.target_url ?? null, source: "poll" }); + seen++; + } + } catch {} + } + return seen; +} + +/** + * Merge on "Accept" (PEP-57): only with green checks of the PR head and no conflicts. + * Throws with the reason for the PM; a task without a PR has nothing to merge. + */ +export async function mergeTaskPr(ref: TaskRef, client?: GiteaClient): Promise<"merged" | "already" | "no_pr"> { + if (!taskPrNumber(ref.project, ref.task.prUrl)) return "no_pr"; + const gitea = client ?? giteaForBot(); + const gate = await prGate(ref, gitea); + if (!gate.pull) return "no_pr"; + if (gate.pull.merged) return "already"; + if (!gate.ok) throw new PeppaError(`Мерж не выполнен: ${gate.reason}`); + await gitea.mergePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, gate.pull.number, gate.pull.head.sha); + return "merged"; +} + +/** + * Automatic merge (auto mode of a project, PEP-23/25): the same gate, and a PR that changes + * the pipeline is never merged automatically — the PM gets a question describing the change. + */ +export async function autoMergeTask(db: Db, ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise<{ merged: boolean; reason?: string }> { + const gate = await prGate(ref, gitea); + if (!gate.pull) return { merged: false, reason: "нет PR" }; + if (gate.pull.merged) return { merged: true }; + if (!gate.ok) return { merged: false, reason: gate.reason }; + const changes = await pipelineChanges(ref, gate.pull, gitea); + if (changes.length) { + await askPm(db, ref, { + kind: "question", + text: `⚠️ ${ref.key}: PR меняет конвейер — автомерж отключён, нужно ваше ревью.\n${changes.map((c) => `• ${c}`).join("\n")}\nPR: ${gate.pull.html_url}`, + }); + return { merged: false, reason: "изменение конвейера требует ревью PM" }; + } + await gitea.mergePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, gate.pull.number, gate.pull.head.sha); + return { merged: true }; +} diff --git a/packages/runner/src/ci.ts b/packages/runner/src/ci.ts index c1bfc310..652132ed 100644 --- a/packages/runner/src/ci.ts +++ b/packages/runner/src/ci.ts @@ -16,6 +16,9 @@ export const CI_FILES = [".gitea/workflows/ci.yml", ".gitea/peppa-check.sh"]; export const CI_BRANCH = "peppa/ci"; export const CI_SECRET_NAME = "PEPPA_CI_SECRET"; +/** Where Gitea webhooks and CI reports reach Peppa. */ +export const giteaHookUrl = () => `${loadEnv().PEPPA_WEB_URL.replace(/\/$/, "")}/api/hooks/gitea`; + const botLogin = () => process.env.GITEA_BOT_USER ?? "peppa-bot"; /** @@ -48,7 +51,7 @@ export interface CiSetup { runner: "bot" | "repo"; } -/** Runner coverage and the Actions secret for CI reports. Idempotent. */ +/** Runner coverage, the Actions secret for CI reports and the webhook. Idempotent. */ export async function setupCi(db: Db, project: Project): Promise { const clients = await repoAdmins(db, project); if (!clients.length) throw new PeppaError("Нет доступа к Gitea"); @@ -58,7 +61,10 @@ export async function setupCi(db: Db, project: Project): Promise { await registerCiRunner(`repo-${project.giteaOwner}--${project.giteaRepo}`, token); runner = "repo"; } - await asAdmin(clients, `Секрет ${CI_SECRET_NAME}`, (c) => c.setActionsSecret(project.giteaOwner, project.giteaRepo, CI_SECRET_NAME, projectHookSecret(project.id))); + const secret = projectHookSecret(project.id); + await asAdmin(clients, `Секрет ${CI_SECRET_NAME}`, (c) => c.setActionsSecret(project.giteaOwner, project.giteaRepo, CI_SECRET_NAME, secret)); + // PR and push events (preview stands, merges) — signed with the same secret. + await asAdmin(clients, "Вебхук", (c) => c.upsertHook(project.giteaOwner, project.giteaRepo, giteaHookUrl(), secret, ["pull_request", "push"])); return { runner }; } diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts index 1e74e265..5858cf4d 100644 --- a/packages/runner/src/flow.ts +++ b/packages/runner/src/flow.ts @@ -1,9 +1,10 @@ // PM-side moves on the task board and review acceptance (web and Telegram use these). -import { answerQuestion, getQuestion, listSessions, PeppaError, resolveTask, updateTask, type Question, type TaskRef } from "@peppa/core"; +import { answerQuestion, getQuestion, listSessions, PeppaError, prGate, resolveTask, updateTask, type Question, type TaskRef } from "@peppa/core"; import { tasks, projects, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { eq } from "drizzle-orm"; import { startSession, stopSession, type StartOptions } from "./sessions.ts"; +import { mergeTaskPr } from "./ci-feedback.ts"; export type BoardColumn = "backlog" | "in_progress" | "review" | "done"; @@ -19,9 +20,19 @@ async function activeSessions(db: Db, taskId: number) { return (await listSessions(db, { active: true, taskId })); } +/** + * Review gate (PEP-57): the task's PR head must have green checks and no conflicts. Fails + * open when Gitea can't be reached — merging is gated again on "Accept". + */ +export async function reviewGate(ref: TaskRef): Promise { + const gate = await prGate(ref).catch(() => null); + return gate && !gate.ok ? gate.reason ?? "проверки не пройдены" : null; +} + /** * Moves a task card. Into "in progress": status in_progress and an agent session is - * started unless one is running. Into "backlog"/"done": active sessions are stopped. + * started unless one is running. Into "review": only past the CI gate. Into + * "backlog"/"done": active sessions are stopped. */ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: StartOptions = {}): Promise<{ started?: number; stopped: number }> { const from = columnOf(ref.task.status); @@ -34,6 +45,10 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta } return { stopped }; } + if (to === "review" && from !== "review") { + const reason = await reviewGate(ref); + if (reason) throw new PeppaError(`${ref.key} нельзя в ревью: ${reason}`); + } if (to === "backlog" || to === "done") { for (const s of await activeSessions(db, ref.task.id)) { await stopSession(db, s.id); @@ -44,7 +59,10 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta return { stopped }; } -/** "Accept" on a ready-for-review message: task done, session stopped, question closed. */ +/** + * "Accept" on a ready-for-review message: the task's PR is merged (green checks, no + * conflicts — otherwise nothing changes and the PM sees why), task done, session stopped. + */ export async function acceptTask(db: Db, questionId: number, via: NonNullable): Promise { const q = await getQuestion(db, questionId); if (!q.taskId) throw new PeppaError("Вопрос не привязан к задаче"); @@ -56,6 +74,7 @@ export async function acceptTask(db: Db, questionId: number, via: NonNullable { const log = opts.log ?? (() => {}); log(`watchdog started: every ${opts.intervalMs / 1000}s, stall after ${opts.stallMs / 60000}m`); @@ -128,6 +131,11 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS await tick(db, opts).catch((e) => log(`tick failed: ${(e as Error).message}`)); // Heartbeat and the check on the bot and the web (PEP-20). await monitorTick(db, { log }).catch((e) => log(`monitor failed: ${(e as Error).message}`)); + // CI results lost on the way (PEP-57): poll commit statuses about once a minute. + if (Date.now() - lastCiPoll >= 60_000) { + lastCiPoll = Date.now(); + await pollChecks(db).catch((e) => log(`ci poll failed: ${(e as Error).message}`)); + } await new Promise((r) => setTimeout(r, opts.intervalMs)); } } diff --git a/packages/testkit/test/ci-feedback.test.ts b/packages/testkit/test/ci-feedback.test.ts new file mode 100644 index 00000000..bdea79c1 --- /dev/null +++ b/packages/testkit/test/ci-feedback.test.ts @@ -0,0 +1,251 @@ +// PEP-57, spec delivery-pipeline: «Проверки на каждый PR», «Красные проверки возвращаются +// агенту», «Гейт ревью и мержа», «Изменение конвейера требует ревью» — one test per scenario, +// against mock Gitea (commit statuses, PRs, webhooks) and mock-claude runners. +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { createHmac } from "node:crypto"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, teardown, waitFor, type TestProject } from "./helpers.ts"; +import { MockGitea } from "../src/mock-gitea.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-cifb-")), "gitea")); +const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" }; +const CHECKS = { lint: "pnpm lint", typecheck: "pnpm typecheck", test: "pnpm test", build: "pnpm build" }; + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + gitea.addUser(BOT); +}); +after(async () => { + await gitea.stop(); + await teardown(); +}); + +interface CiTask { + p: TestProject; + proj: Awaited>; + ref: () => ReturnType; + branch: string; + /** Pushes a commit to the task branch, returns its SHA. */ + push(files?: Record): string; + /** CI result of one check, as the CI step reports it (signed webhook). */ + report(sha: string, check: string, state: string, log?: string): ReturnType; + statuses(sha: string, state: string, checks?: string[]): void; +} + +/** Project with a repo in mock Gitea and a task with an open PR from task/-1. */ +async function ciTask(opts: { checks?: Record; turns?: Parameters[0]["turns"] } = {}): Promise { + const p = await project({ turns: opts.turns ?? [] }); + const proj = await core.getProject(db, p.key); + const pj = JSON.stringify({ slug: proj.slug, key: p.key, name: p.key, peppaUrl: "http://test", ...(opts.checks ? { checks: opts.checks } : {}) }); + writeFileSync(join(p.dir, ".peppa/project.json"), pj); + gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } }); + gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write"; + const branch = `task/${p.taskKey}`; + let n = 0; + const push = (files: Record = {}) => gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { [`f${n++}.txt`]: String(n), ...files }); + push(); + const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch); + const ref = () => core.resolveTask(db, p.taskKey); + await core.updateTask(db, await ref(), { status: "in_progress", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` }); + const repo = `${proj.giteaOwner}/${proj.giteaRepo}`; + return { + p, + proj, + ref, + branch, + push, + report(sha, check, state, log = "") { + const body = JSON.stringify({ repository: repo, sha, branch, pr: pr.number, check, state, run_url: `/${repo}/actions/runs/${sha.slice(0, 4)}`, duration_sec: 3, log_tail: log }); + const signature = createHmac("sha256", core.projectHookSecret(proj.id)).update(body).digest("hex"); + return runner.handleGiteaHook(db, { event: "check", signature, body }); + }, + statuses(sha, state, checks = Object.keys(CHECKS)) { + for (const c of checks) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${c}`, state, { target_url: `/${repo}/actions/runs/1` }); + }, + }; +} + +async function toReview(t: CiTask) { + await core.updateTask(db, await t.ref(), { status: "review" }); + return core.askPm(db, await t.ref(), { kind: "attention", text: "готова к ревью" }); +} + +describe("Проверки на каждый PR", () => { + test("Scenario: Зелёные проверки — в карточке «Проверки: 4 из 4 пройдены» со ссылкой на прогон", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + for (const c of Object.keys(CHECKS)) assert.equal((await t.report(sha, c, "success")).status, 200); + const d = await core.getTaskDetails(db, await t.ref()); + assert.equal(d.ci.label, "Проверки: 4 из 4 пройдены"); + assert.equal(d.ci.runUrl, `${gitea.url}/${t.proj.giteaOwner}/${t.proj.giteaRepo}/actions/runs/${sha.slice(0, 4)}`); + const { formatTask } = await import("../../mcp/src/format.ts"); + assert.match(formatTask(d), /Проверки: 4 из 4 пройдены \(коммит [0-9a-f]{7}\)/, "MCP get_task shows the checks"); + }); + + test("Scenario: Проверки не настроены — видно «проверки не настроены», переход в «Ревью» не блокируется", async () => { + const t = await ciTask(); + t.push(); + assert.equal((await core.getTaskDetails(db, await t.ref())).ci.label, "проверки не настроены"); + await runner.moveTask(db, await t.ref(), "review"); + assert.equal((await t.ref()).task.status, "review"); + }); +}); + +describe("Красные проверки возвращаются агенту", () => { + test("Scenario: Агент чинит сам — раннер получает шаг «test» и хвост лога, задача в работе, PM ничего не получает", async () => { + const t = await ciTask({ checks: CHECKS, turns: [[{ say: "PR открыт" }], [{ say: "чиню" }], [{ say: "ещё" }], [{ say: "и ещё" }]] }); + const id = await t.p.start(); + await t.p.waitLog("agent started", (e) => e.ev === "prompt"); + const sha = t.push(); + const r = await t.report(sha, "test", "failure", "ok 1 - adds\nnot ok 2 - divides by zero\n# fail 1"); + assert.equal((r.body as { action: string }).action, "agent"); + await t.p.waitLog("failure delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("«test»") && String(e.prompt).includes("not ok 2 - divides by zero")); + assert.equal((await t.ref()).task.status, "in_progress"); + assert.equal((await core.pendingQuestions(db, t.proj.id)).filter((q) => q.kind !== "attention").length, 0); + const task = (await t.ref()).task; + assert.equal(task.ciAttempts, 1); + // A second red check of the same commit is the same attempt. + await t.report(sha, "lint", "failure", "lint error"); + assert.equal((await t.ref()).task.ciAttempts, 1); + await runner.stopSession(db, id); + }); + + test("Scenario: Три неудачи подряд — PM получает вопрос со ссылкой на лог", async () => { + const t = await ciTask({ checks: CHECKS, turns: [[{ say: "1" }], [{ say: "2" }], [{ say: "3" }], [{ say: "4" }], [{ say: "5" }]] }); + const id = await t.p.start(); + await t.p.waitLog("agent started", (e) => e.ev === "prompt"); + const actions: string[] = []; + for (let i = 0; i < 3; i++) actions.push(((await t.report(t.push(), "test", "failure", `fail #${i}`)).body as { action: string }).action); + assert.deepEqual(actions, ["agent", "agent", "pm"]); + const q = (await core.pendingQuestions(db, t.proj.id)).find((x) => x.kind === "question"); + assert.ok(q, "PM got a question"); + assert.equal(q.taskId, (await t.ref()).task.id); + assert.match(q.text, new RegExp(`красные 3 раза подряд[\\s\\S]*Лог: ${gitea.url}/`)); + await t.p.waitLog("runner told to wait", (e) => e.ev === "prompt" && String(e.prompt).includes("жди ответа PM")); + // Green again → the counter starts over. + const sha = t.push(); + for (const c of Object.keys(CHECKS)) await t.report(sha, c, "success"); + assert.equal((await t.ref()).task.ciAttempts, 0); + await runner.stopSession(db, id); + }); + + test("no runner: a red check sends a task in review back to work and starts the agent with the log", async () => { + const t = await ciTask({ checks: CHECKS, turns: [[{ say: "чиню" }]] }); + const sha = t.push(); + await core.updateTask(db, await t.ref(), { status: "review" }); + const r = await t.report(sha, "build", "failure", "error TS2304: Cannot find name 'x'"); + assert.equal((r.body as { action: string }).action, "restarted"); + assert.equal((await t.ref()).task.status, "in_progress"); + await t.p.waitLog("agent started with the failure", (e) => e.ev === "prompt" && String(e.prompt).includes("Cannot find name 'x'")); + for (const s of await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })) await runner.stopSession(db, s.id); + }); + + test("the template's CI step reports to Peppa: signature accepted, log tail stored", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + // Peppa's POST /api/hooks/gitea, as the web route does it. + const server = createServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", async () => { + 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)); + }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const job = mkdtempSync(join(tmpdir(), "peppa-job-")); + mkdirSync(join(job, ".peppa")); + writeFileSync(join(job, ".peppa/project.json"), JSON.stringify({ peppaUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, checks: { test: "echo 'not ok 1 - кириллица и \"кавычки\"'; exit 1" } })); + const script = resolve(fileURLToPath(import.meta.url), "../../../../template/.gitea/peppa-check.sh"); + const env = { ...process.env, GITHUB_ACTIONS: "true", GITHUB_SERVER_URL: gitea.url, GITHUB_REPOSITORY: `${t.proj.giteaOwner}/${t.proj.giteaRepo}`, GITHUB_RUN_NUMBER: "9", PEPPA_SHA: sha, PEPPA_BRANCH: t.branch, PEPPA_PR: "1", GITEA_TOKEN: BOT.token, PEPPA_CI_SECRET: core.projectHookSecret(t.proj.id) }; + const out = await new Promise((done) => execFile("bash", [script, "test"], { cwd: job, env, encoding: "utf8" }, (_e, stdout) => done(stdout))); + server.close(); + assert.doesNotMatch(out, /недоступна/); + const d = await core.getTaskDetails(db, await t.ref()); + assert.equal(d.ci.failed[0]?.check, "test"); + assert.match(d.ci.failed[0]?.logTail ?? "", /not ok 1 - кириллица и "кавычки"/); + assert.equal(d.ci.failed[0]?.runUrl, `${gitea.url}/${t.proj.giteaOwner}/${t.proj.giteaRepo}/actions/runs/9`); + assert.equal((await t.ref()).task.ciAttempts, 1); + }); + + test("webhook: wrong signature and unknown repo are rejected; polling picks up lost results", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + const body = JSON.stringify({ repository: `${t.proj.giteaOwner}/${t.proj.giteaRepo}`, sha, check: "test", state: "success" }); + assert.equal((await runner.handleGiteaHook(db, { event: "check", signature: "00", body })).status, 401); + assert.equal((await runner.handleGiteaHook(db, { event: "check", signature: "00", body: JSON.stringify({ repository: "nobody/nothing" }) })).status, 404); + t.statuses(sha, "success"); + assert.ok((await runner.pollChecks(db)) >= 4); + assert.equal((await core.getTaskDetails(db, await t.ref())).ci.label, "Проверки: 4 из 4 пройдены"); + }); +}); + +describe("Гейт ревью и мержа", () => { + test("Scenario: Мерж при красных проверках — мерж не выполняется, PM видит «проверки не пройдены»", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + t.statuses(sha, "success", ["lint", "typecheck", "build"]); + t.statuses(sha, "failure", ["test"]); + const q = await toReview(t); + await assert.rejects(runner.acceptTask(db, q.id, "web"), /Мерж не выполнен: проверки не пройдены \(test\)/); + assert.equal(gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.merged, false); + assert.equal((await t.ref()).task.status, "review"); + assert.equal((await core.getQuestion(db, q.id)).answeredAt, null, "the review question stays open"); + }); + + test("Scenario: Приёмка — PR смержен в основную ветку, задача в «Готово»", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + t.statuses(sha, "success"); + const q = await toReview(t); + await runner.acceptTask(db, q.id, "web"); + const pr = gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!; + assert.equal(pr.merged, true); + assert.equal(gitea.sha(t.proj.giteaOwner, t.proj.giteaRepo, "main"), sha); + assert.equal((await t.ref()).task.status, "done"); + }); + + test("review gate: the agent can't move a task to review with red or running checks", async () => { + const t = await ciTask({ checks: CHECKS }); + const sha = t.push(); + t.statuses(sha, "success", ["lint"]); + assert.match((await runner.reviewGate(await t.ref())) ?? "", /проверки ещё идут \(1 из 4\)/); + await assert.rejects(runner.moveTask(db, await t.ref(), "review"), /нельзя в ревью: проверки ещё идут/); + t.statuses(sha, "success"); + gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.mergeable = false; + assert.equal(await runner.reviewGate(await t.ref()), "есть конфликты с основной веткой"); + gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.mergeable = true; + assert.equal(await runner.reviewGate(await t.ref()), null); + }); +}); + +describe("Изменение конвейера требует ревью", () => { + test("Scenario: Агент отключил тесты — PR не мержится автоматически, PM получает вопрос с описанием изменения", async () => { + const t = await ciTask({ checks: CHECKS }); + const pj = JSON.stringify({ slug: t.proj.slug, key: t.p.key, name: t.p.key, peppaUrl: "http://test", checks: { ...CHECKS, test: "true" } }); + const sha = t.push({ ".peppa/project.json": pj }); + t.statuses(sha, "success"); + const r = await runner.autoMergeTask(db, await t.ref()); + assert.deepEqual(r, { merged: false, reason: "изменение конвейера требует ревью PM" }); + assert.equal(gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.merged, false); + const q = await waitFor("pipeline question", async () => (await core.pendingQuestions(db, t.proj.id)).find((x) => x.text.includes("меняет конвейер"))); + assert.match(q.text, /checks: .*"test":"pnpm test".* → .*"test":"true"/); + }); + + test("auto-merge without pipeline changes merges a green PR", async () => { + const t = await ciTask({ checks: CHECKS }); + t.statuses(t.push(), "success"); + assert.deepEqual(await runner.autoMergeTask(db, await t.ref()), { merged: true }); + }); +}); diff --git a/packages/testkit/test/ci.test.ts b/packages/testkit/test/ci.test.ts index 9143d755..0e7db66c 100644 --- a/packages/testkit/test/ci.test.ts +++ b/packages/testkit/test/ci.test.ts @@ -65,6 +65,8 @@ describe("CI: connect a project", () => { assert.equal(registrations().length, before, "no per-repo runner for peppa-bot's repos"); const repo = gitea.repo(BOT.login, p.giteaRepo); assert.equal(repo.secrets.PEPPA_CI_SECRET, core.projectHookSecret(p.id)); + assert.deepEqual(repo.hooks.map((h) => [h.url, h.secret, h.events]), [[runner.giteaHookUrl(), core.projectHookSecret(p.id), ["pull_request", "push"]]]); + assert.match(runner.giteaHookUrl(), /\/api\/hooks\/gitea$/); assert.ok(r.prUrl?.endsWith("/pulls/1")); const pr = repo.pulls[0]!; assert.equal(pr.head, runner.CI_BRANCH);