peppa/packages/testkit/test/ci-feedback.test.ts
Асель b5c0e704a5 PEP-150: сбои не идут пользователю — задержка на стороне платформы, одно сообщение суперадмину
platformDelay/sessionDelay вместо attention владельцу: падения и зависания агентов, лимиты,
красные и зависшие проверки, запуск агента, обновление версии, приёмка; guard конвейера —
вопрос суперадмину в платформенном проекте; строка задержки в задаче и на карточке;
список задержек на Главной суперадмина.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 14:09:30 +05:00

317 lines
19 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, execFileSync } 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, superadmin, 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: Три неудачи подряд — суперадмин получает сообщение, агент продолжает; шесть — агент остановлен", async () => {
const sent = await superadmin();
const t = await ciTask({ checks: CHECKS, turns: [[{ say: "1" }], [{ say: "2" }], [{ say: "3" }], [{ say: "4" }], [{ say: "5" }], [{ say: "6" }], [{ say: "7" }], [{ say: "8" }]] });
const id = await t.p.start();
await t.p.waitLog("agent started", (e) => e.ev === "prompt");
const taskId = (await t.ref()).task.id;
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", "agent"], "the agent keeps fixing");
assert.equal((await core.pendingQuestions(db, t.proj.id)).filter((x) => x.kind === "question").length, 0, "PEP-150: the owner is not asked");
assert.equal((await sent()).length, 1, "one message for the superadmin");
assert.match((await sent())[0]!, new RegExp(`не проходят 3 раза подряд[\\s\\S]*Подробности: ${gitea.url}/`));
assert.equal(await core.taskDelayed(db, taskId), true, "the story shows the delay line");
await t.p.waitLog("the agent got the third log", (e) => e.ev === "prompt" && String(e.prompt).includes("fail #2"));
// Attempts 4 and 5: nothing new for the superadmin; the 6th stops the agent.
for (let i = 3; i < 5; i++) assert.equal(((await t.report(t.push(), "test", "failure", `fail #${i}`)).body as { action: string }).action, "agent");
assert.equal((await sent()).length, 1);
assert.equal(((await t.report(t.push(), "test", "failure", "fail #5")).body as { action: string }).action, "admin");
assert.equal((await sent()).length, 2, "the attempts ran out — one more");
await t.p.waitLog("runner told to stop", (e) => e.ev === "prompt" && String(e.prompt).includes("Не пушь новых попыток"));
assert.equal((await core.pendingQuestions(db, t.proj.id)).filter((x) => x.kind === "question").length, 0);
// Green again → the counter starts over, the delay is gone.
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);
assert.equal(await core.taskDelayed(db, taskId), false);
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("PEP-93: PR already in main (a later story's branch grew from it and was merged) — closed with a note, story done", async () => {
const t = await ciTask({ checks: CHECKS });
const sha = t.push();
t.statuses(sha, "success");
const q = await toReview(t);
// The next story's PR carried this branch's commits into main first.
const r = gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo);
execFileSync("git", ["--git-dir", r.path, "update-ref", "refs/heads/main", sha]);
await runner.acceptTask(db, q.id, "web");
const pr = r.pulls[0]!;
assert.equal(pr.merged, false);
assert.equal(pr.state, "closed");
assert.equal((await t.ref()).task.status, "done");
});
test("PEP-101: Gitea compares branch names only (a SHA → 404) — «Принять» still merges", async () => {
const t = await ciTask({ checks: CHECKS });
const sha = t.push();
t.statuses(sha, "success");
const r = gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo);
const client = core.giteaForBot();
await assert.rejects(client.commitsAhead(t.proj.giteaOwner, t.proj.giteaRepo, "main", sha), /404|couldn't be found/);
await toReview(t);
assert.equal(await runner.mergeTaskPr(await t.ref(), client), "merged");
assert.equal(r.pulls[0]!.merged, true);
assert.equal(gitea.sha(t.proj.giteaOwner, t.proj.giteaRepo, "main"), sha);
});
test("PEP-101: a failing compare never blocks the merge", async () => {
const t = await ciTask({ checks: CHECKS });
const sha = t.push();
t.statuses(sha, "success");
await toReview(t);
const client = core.giteaForBot();
client.commitsAhead = async () => { throw new Error("Gitea 404: The target couldn't be found."); };
assert.equal(await runner.mergeTaskPr(await t.ref(), client), "merged");
assert.equal(gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.merged, true);
assert.equal(gitea.sha(t.proj.giteaOwner, t.proj.giteaRepo, "main"), sha);
});
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);
});
});
/** PEP-150: the superadmin is asked in the platform project. */
async function platformProject() {
const plat = await project({ turns: [] });
process.env.PEPPA_PLATFORM_KEY = plat.key;
const p = await core.getProject(db, plat.key);
return async () => (await core.pendingQuestions(db, p.id)).filter((q) => q.text.includes("затрагивают проверки"));
}
describe("Изменение конвейера требует ревью", () => {
test("Scenario: Агент отключил тесты — PR не мержится автоматически, суперадмин получает вопрос с описанием изменения", async () => {
const guard = await platformProject();
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 guard())[0]);
assert.match(q.text, /checks: .*"test":"pnpm test".* → .*"test":"true"/);
assert.match(q.text.replace(/[\u2068\u2069]/g, ""), new RegExp(`${t.p.taskKey} \\(${t.proj.name}\\)`), "the story and its project are named");
assert.deepEqual(q.options, [runner.GUARD_ACCEPT, runner.GUARD_RETURN]);
assert.equal((await core.pendingQuestions(db, t.proj.id)).length, 0, "PEP-150: the owner gets nothing");
// The same head commit is not asked about twice.
await runner.autoMergeTask(db, await t.ref());
assert.equal((await guard()).length, 1);
});
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 });
});
});