peppa/packages/testkit/test/ci-feedback.test.ts
Асель cae49d5b54 PEP-57: CI feedback — check runs, red checks back to the agent, review/merge gates
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:37:10 +05:00

252 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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