// PEP-26, spec delivery-pipeline «Агент-ревьюер до ревью PM» — one test per scenario, against // mock Gitea (PR, diff, commit statuses), mock-claude runners calling the real peppa MCP server // and mock-reviewer as the reviewer agent. import { stripAsIs } from "@peppa/shared/i18n"; import assert from "node:assert/strict"; import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { after, before, describe, test } from "node:test"; import { core, db, project, runner, teardown, waitFor, type TestProject } from "./helpers.ts"; import { MockGitea } from "../src/mock-gitea.ts"; import type { Action } from "../src/scenario.ts"; const TMP = mkdtempSync(join(tmpdir(), "peppa-review-")); const SCENARIO = join(TMP, "mock-review.json"); // Set before the first runner starts: the tmux server (and the MCP servers under it) keep this env. Object.assign(process.env, { PEPPA_SECRET: "mock-secret-for-tests", PEPPA_REVIEW_BIN: resolve(fileURLToPath(import.meta.url), "../../bin/mock-reviewer"), MOCK_REVIEW_SCENARIO: SCENARIO, PEPPA_REVIEW_TIMEOUT_MS: "20000", }); const gitea = new MockGitea(join(TMP, "gitea")); const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" }; const CHECKS = { test: "pnpm test" }; 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(); }); type Review = { verdict: string; summary?: string; findings?: Array<{ file?: string; line?: number; text: string }> }; /** Scenario of the mock reviewer for the next calls; returns a reader of its call log. */ function reviewer(sc: { responses?: Review[]; fail?: boolean; garbage?: boolean }) { writeFileSync(SCENARIO, JSON.stringify(sc)); rmSync(`${SCENARIO}.log.jsonl`, { force: true }); return () => existsSync(`${SCENARIO}.log.jsonl`) ? readFileSync(`${SCENARIO}.log.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l) as { story: string; diff: boolean; diffText: string; rules: string | null; args: string[] }) : []; } interface ReviewTask { p: TestProject; proj: Awaited>; ref: () => ReturnType; prUrl: string; /** Pushes a commit to the story branch with green checks; returns its SHA. */ pushGreen(files?: Record): string; } /** Project with a repo in mock Gitea, a story with an open PR (green checks) and a runner scenario. */ async function reviewTask(turns: Action[][], settings?: Parameters[2]): Promise { const p = await project({ 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", checks: 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}`; const pushGreen = (files: Record = { "src/divide.ts": "export const divide = (a: number, b: number) => a / b;\n" }) => { const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, files); for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${c}`, "success", { target_url: "/x/actions/runs/1" }); return sha; }; pushGreen(); const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch); const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`; const ref = () => core.resolveTask(db, p.taskKey); await core.updateTask(db, await ref(), { status: "in_progress", title: "Деление в калькуляторе", description: "Добавить деление; на ноль — понятная ошибка" }); if (settings) await core.setReviewSettings(db, proj.id, settings); writeFileSync(join(p.dir, ".peppa/mock-scenario.json"), JSON.stringify({ turns: turns.map((t) => t.map((a) => ("mcp" in a && a.mcp === "update_task" ? { ...a, args: { ...a.args, pr_url: prUrl } } : a))) })); return { p, proj, ref, prUrl, pushGreen }; } const toReview: Action = { mcp: "update_task", args: { task: "1", status: "review" } }; /** PEP-152: the reviewer's note is technical — it is in the details of «готово», not in its main text. */ const cardDetails = async (q: { id: number }) => (await core.messageDetails(db, [q.id])).get(q.id) ?? ""; /** The details are written right after the message (by the agent's MCP process): wait for them, then check. */ const cardDetailsMatch = async (q: { id: number }, re: RegExp) => { let last = ""; await waitFor("card details", async () => re.test((last = stripAsIs(await cardDetails(q)))), 10000).catch(() => {}); assert.match(last, re); }; const readyQuestions = async (t: ReviewTask) => (await core.pendingQuestions(db, t.proj.id)).filter((q) => q.kind === "attention" && q.text.includes("готова к ревью")); const stopAll = async (t: ReviewTask) => { for (const s of await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })) await runner.stopSession(db, s.id); }; describe("Агент-ревьюер до ревью PM", () => { test("Scenario: Ревьюер нашёл проблемы — агент получает замечания, стори в работе, PM ничего не получает", async () => { const calls = reviewer({ responses: [{ verdict: "changes", summary: "нет проверки деления на ноль", findings: [{ file: "src/divide.ts", line: 1, text: "деление на ноль возвращает Infinity вместо ошибки" }] }] }); const t = await reviewTask([[toReview, { say: "PR открыт, жду ревьюера" }], [{ say: "чиню" }], [{ say: "ещё" }], [{ say: "и ещё" }]], { enabled: true, rules: "без новых зависимостей" }); await t.p.start(); const tool = await t.p.waitLog("update_task answered", (e) => e.ev === "mcp" && e.tool === "update_task"); assert.match(String(tool.text), /reviewer agent is checking/); await t.p.waitLog("findings delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("деление на ноль возвращает Infinity") && String(e.prompt).includes("src/divide.ts:1")); // PEP-295: the reviewer's remarks go to the agent; no story is filed. assert.deepEqual((await core.listTasks(db, { projectId: t.proj.id, includeArchived: true })).map((x) => x.id), [(await t.ref()).task.id], "the reviewer files no story"); const [call] = calls(); assert.equal(call?.story, t.p.taskKey); assert.ok(call?.diff, "the reviewer got the PR diff"); assert.match(call!.diffText, /export const divide/); assert.equal(call?.rules, "без новых зависимостей"); assert.ok(call?.args.includes("--model") && call.args.includes("sonnet"), "a cheaper model"); assert.equal((await t.ref()).task.status, "in_progress"); assert.equal((await readyQuestions(t)).length, 0, "PM got no ready-for-review"); assert.equal((await core.pendingQuestions(db, t.proj.id)).filter((q) => q.kind !== "attention").length, 0); const d = await core.getTaskDetails(db, await t.ref()); assert.equal(d.review?.verdict, "changes"); const { formatTask } = await import("../../mcp/src/format.ts"); assert.match(formatTask(d), /Ревьюер: замечаний 1[\s\S]*src\/divide\.ts:1 — деление на ноль/); await stopAll(t); }); test("Scenario: Ревьюер одобрил — стори в «Ревью», PM получает «готово к ревью» с резюме ревьюера", async () => { const calls = reviewer({ responses: [{ verdict: "ok", summary: "деление и ошибка на ноль сделаны, тесты есть" }] }); const t = await reviewTask([[toReview, { say: "PR открыт" }], [{ say: "ок" }]], { enabled: true }); await t.p.start(); const [q] = await waitFor("ready for review", async () => { const qs = await readyQuestions(t); return qs.length ? qs : null; }); assert.equal((await t.ref()).task.status, "review"); await cardDetailsMatch(q!, /Ревьюер: ок — деление и ошибка на ноль сделаны, тесты есть/); assert.ok(await runner.isReviewQuestion(db, q!), "«Принять» works on it"); // Exactly one ready-for-review, whichever finished first (the agent's turn or the reviewer). await new Promise((r) => setTimeout(r, 1500)); assert.equal((await readyQuestions(t)).length, 1); assert.equal(calls().length, 1); const d = await core.getTaskDetails(db, await t.ref()); assert.equal(d.review?.verdict, "ok"); assert.equal(stripAsIs(core.reviewLabel(d.review!)), "Ревьюер: ок — деление и ошибка на ноль сделаны, тесты есть"); await stopAll(t); }); test("Scenario: Лимит итераций — стори уходит к PM без нового ревью, с последними замечаниями", async () => { const calls = reviewer({ responses: [{ verdict: "ok" }] }); const t = await reviewTask([[toReview, { say: "PR снова открыт" }], [{ say: "ок" }]], { enabled: true, maxIterations: 2 }); const task = (await t.ref()).task; for (let i = 0; i < 2; i++) { const r = await core.queueReview(db, { projectId: t.proj.id, taskId: task.id, prNumber: 1, sha: `old${i}` }); await core.finishReview(db, r.id, { verdict: "changes", summary: `итерация ${i + 1}`, findings: [{ file: "src/divide.ts", text: `замечание ${i + 1}` }] }); } await t.p.start(); const [q] = await waitFor("ready for review", async () => { const qs = await readyQuestions(t); return qs.length ? qs : null; }); assert.equal((await t.ref()).task.status, "review"); await cardDetailsMatch(q!, /лимит итераций исчерпан[\s\S]*src\/divide\.ts — замечание 2/); assert.equal(calls().length, 0, "the reviewer was not called again"); await stopAll(t); }); test("Scenario: Ревьюер не отработал — стори к PM с пометкой и причиной", async () => { reviewer({ fail: true }); const t = await reviewTask([[toReview, { say: "PR открыт" }], [{ say: "ок" }]], { enabled: true }); await t.p.start(); const [q] = await waitFor("ready for review", async () => { const qs = await readyQuestions(t); return qs.length ? qs : null; }); assert.equal((await t.ref()).task.status, "review"); await cardDetailsMatch(q!, /Ревьюер не отработал: ревьюер завершился с кодом 1/); assert.equal((await core.latestReview(db, (await t.ref()).task.id))?.state, "error"); await stopAll(t); }); test("Scenario: Ревьюер выключен — стори сразу в «Ревью», ревьюер не вызывается", async () => { const calls = reviewer({}); const t = await reviewTask([[toReview, { say: "PR открыт" }], [{ say: "ок" }]]); await t.p.start(); const tool = await t.p.waitLog("update_task answered", (e) => e.ev === "mcp" && e.tool === "update_task"); assert.match(String(tool.text), /status=review/); assert.equal((await t.ref()).task.status, "review"); assert.equal(calls().length, 0); assert.equal(await core.latestReview(db, (await t.ref()).task.id), null); await stopAll(t); }); }); describe("reviewer details", () => { test("parseReviewOutput: fenced JSON, garbage, «changes» without findings", () => { assert.deepEqual(runner.parseReviewOutput('Итог:\n```json\n{"verdict":"ok","summary":"хорошо","findings":[]}\n```'), { verdict: "ok", summary: "хорошо", findings: [] }); assert.equal(runner.parseReviewOutput("всё хорошо"), null); assert.equal(runner.parseReviewOutput('{"verdict":"changes","summary":"плохо","findings":[]}'), null); assert.equal(runner.parseReviewOutput('{"verdict":"maybe"}'), null); const v = runner.parseReviewOutput('{"verdict":"changes","summary":"s","findings":[{"file":"a.ts","line":"x","text":"t"},{"nope":1}]}'); assert.deepEqual(v?.findings, [{ file: "a.ts", text: "t" }]); }); test("an answer not in the format is a broken reviewer; the same approved commit is not reviewed twice", async () => { reviewer({ garbage: true }); const t = await reviewTask([], { enabled: true }); const ref = { ...(await t.ref()), task: { ...(await t.ref()).task, prUrl: t.prUrl } }; await core.updateTask(db, await t.ref(), { prUrl: t.prUrl }); const r = await runner.requestReview(db, ref); assert.equal(r.action, "queued"); const done = await waitFor("review finished", async () => { const x = await core.latestReview(db, ref.task.id); return x && x.state !== "queued" && x.state !== "running" ? x : null; }); assert.equal(done.error, "ревьюер ответил не по формату"); // No runner: the PM gets "ready for review" directly. assert.equal((await t.ref()).task.status, "review"); // The status goes before the card is sent: wait for the card itself. const card = await waitFor("ready for review", async () => (await readyQuestions(t))[0] ?? null); await cardDetailsMatch(card, /Ревьюер не отработал: ревьюер ответил не по формату/); // Approved head → asking again goes straight to review with the note. await core.updateTask(db, await t.ref(), { status: "in_progress" }); await core.finishReview(db, done.id, { verdict: "ok", summary: "ок", findings: [] }); const again = await runner.requestReview(db, { ...(await t.ref()) }); assert.deepEqual(again.action === "review" ? { ...again, note: stripAsIs(again.note ?? "") } : again, { action: "review", note: "🔎 Ревьюер: ок — ок" }); }); test("no runner and findings: the agent is started with the findings; the watchdog runs queued reviews", async () => { reviewer({ responses: [{ verdict: "changes", summary: "дыра", findings: [{ text: "нет проверки доступа к /admin" }] }] }); const t = await reviewTask([[{ say: "чиню доступ" }]], { enabled: true }); await core.updateTask(db, await t.ref(), { prUrl: t.prUrl }); const head = t.pushGreen({ "src/admin.ts": "export const admin = 1;\n" }); // Queued by an MCP process that died: the watchdog's tick picks it up. const q = await core.queueReview(db, { projectId: t.proj.id, taskId: (await t.ref()).task.id, prNumber: 1, sha: head }); assert.equal(await runner.reviewTick(db), 1); await t.p.waitLog("agent started with the findings", (e) => e.ev === "prompt" && String(e.prompt).includes("нет проверки доступа к /admin")); assert.equal((await core.latestReview(db, (await t.ref()).task.id))?.id, q.id); assert.equal((await t.ref()).task.status, "in_progress"); await stopAll(t); }); test("settings: off by default, iteration limit validated", async () => { const t = await reviewTask([]); const s = await core.getReviewSettings(db, t.proj.id); assert.equal(s.enabled, false); assert.equal(s.maxIterations, 2); await assert.rejects(core.setReviewSettings(db, t.proj.id, { maxIterations: 0 }), /от 1 до 10/); const saved = await core.setReviewSettings(db, t.proj.id, { enabled: true, maxIterations: 3, rules: " " }); assert.deepEqual([saved.enabled, saved.maxIterations, saved.rules], [true, 3, null]); }); });