Merge pull request 'PEP-57 (этап 2): обратная связь CI и гейты ревью/мержа' (#21) from task/PEP-57-feedback into main

This commit is contained in:
peppa-bot 2026-11-13 14:41:36 +05:00
commit 0c0e3fe41c
22 changed files with 2883 additions and 12 deletions

View File

@ -29,6 +29,8 @@
- **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u<id>` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины
- **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:<service>`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon:<service>:…`. Упал бот — вачдог шлёт алерт прямо в 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 <KEY>` (ещё 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)

View File

@ -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
<span className="mono">{ref.key}</span> {task.title} <Badge status={task.status} />
</h1>
{task.prUrl && <p><a href={task.prUrl}>PR</a></p>}
<section className="checks">
<h2>Проверки</h2>
<p>
{ci.state === "success" ? "✅ " : ci.state === "failure" ? "❌ " : ci.state === "pending" ? "⏳ " : ""}
{ci.runUrl ? <a href={ci.runUrl}>{ci.label}</a> : ci.label}
{ci.sha && <span className="mono muted"> · {ci.sha.slice(0, 7)}</span>}
{task.ciAttempts > 0 && <span className="muted"> · красных подряд: {task.ciAttempts}</span>}
</p>
{ci.failed.map((f) => (
<details key={f.check}>
<summary>
❌ <span className="mono">{f.check}</span> {f.runUrl && <a href={f.runUrl}>лог</a>}
</summary>
{f.logTail && <pre className="md">{f.logTail.split("\n").slice(-60).join("\n")}</pre>}
</details>
))}
</section>
<p className="desc">{task.description || <span className="muted">Без описания</span>}</p>
<section>

View File

@ -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 });
}

View File

@ -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.

View File

@ -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

191
packages/core/src/ci.ts Normal file
View File

@ -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/<KEY>-<n>…`, or the task whose PR it is. */
export async function taskForCheck(db: Db, project: Project, branch: string | null | undefined, prNumber: number | null | undefined): Promise<TaskRef | null> {
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<CiSummary> {
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<GateResult> {
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<string[]> {
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;
}

View File

@ -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";

View File

@ -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<typeof events.$inferSelect>;
/** 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<TaskDetails> {
@ -131,7 +134,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise<TaskDetails>
.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 {

View File

@ -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");

File diff suppressed because it is too large Load Diff

View File

@ -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
}
]
}

View File

@ -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",

View File

@ -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));

View File

@ -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}` : ""}`;
},

View File

@ -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 }) => {

View File

@ -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<number | null> {
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<CheckOutcome> {
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<Project | null> {
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<string, unknown>) => Promise<unknown>;
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<string, unknown> }> {
let payload: Record<string, unknown>;
try {
payload = JSON.parse(req.body) as Record<string, unknown>;
} 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<number> {
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 };
}

View File

@ -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<CiSetup> {
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<CiSetup> {
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 };
}

View File

@ -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<string | null> {
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<Question["answeredVia"]>): Promise<TaskRef> {
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<Qu
.where(eq(tasks.id, q.taskId));
const ref = await resolveTask(db, formatTaskKey(t!.key, t!.number));
if (ref.task.status !== "review") throw new PeppaError(`${ref.key} не в ревью (сейчас ${ref.task.status})`);
await mergeTaskPr(ref);
await answerQuestion(db, q.id, "✅ Принято", via);
await moveTask(db, ref, "done");
return ref;

View File

@ -13,3 +13,4 @@ export * from "./monitor.ts";
export * from "./ci.ts";
export * from "./incidents.ts";
export * from "./triage.ts";
export * from "./ci-feedback.ts";

View File

@ -16,6 +16,7 @@ import { recordLimit } from "./limits.ts";
import { resumeSession } from "./sessions.ts";
import { monitorTick } from "./monitor.ts";
import { incidentTick } from "./incidents.ts";
import { pollChecks } from "./ci-feedback.ts";
export interface WatchdogOptions {
/** Current time (tests move it instead of waiting). */
@ -121,6 +122,8 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log:
}
}
let lastCiPoll = 0;
export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortSignal): Promise<void> {
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));
}
}

View File

@ -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<ReturnType<typeof core.getProject>>;
ref: () => ReturnType<typeof core.resolveTask>;
branch: string;
/** Pushes a commit to the task branch, returns its SHA. */
push(files?: Record<string, string>): string;
/** CI result of one check, as the CI step reports it (signed webhook). */
report(sha: string, check: string, state: string, log?: string): ReturnType<typeof runner.handleGiteaHook>;
statuses(sha: string, state: string, checks?: string[]): void;
}
/** Project with a repo in mock Gitea and a task with an open PR from task/<KEY>-1. */
async function ciTask(opts: { checks?: Record<string, string>; turns?: Parameters<typeof project>[0]["turns"] } = {}): Promise<CiTask> {
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<string, string> = {}) => 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<void>((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<string>((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 });
});
});

View File

@ -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);