peppa/packages/testkit/test/reviewer.test.ts
Асель 094ab632cc PEP-152: формат сообщения агента — суть, что нужно от вас, где посмотреть, подробности под «Подробнее»
Сообщение агента пользователю собирается из полей summary / need / link / details
(core/agent-message.ts); основной текст проверяется при приёме (длина, словарь, файлы,
ветки, команды, номера PR, статусы из кода) — нарушение возвращается агенту, после трёх
отказов подряд сообщение уходит с нейтральной первой строкой. Разбор словаря — общий
модуль @peppa/shared/glossary. Сайт и Telegram показывают основной текст, details — под
«Подробнее». Карточка «готово» и реплика конца хода — в том же формате. Правила агентам,
переводы en/kk, тесты по сценариям, change pep-152-agent-message-format в архиве.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 17:38:04 +05:00

240 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-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<ReturnType<typeof core.getProject>>;
ref: () => ReturnType<typeof core.resolveTask>;
prUrl: string;
/** Pushes a commit to the story branch with green checks; returns its SHA. */
pushGreen(files?: Record<string, string>): 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<typeof core.setReviewSettings>[2]): Promise<ReviewTask> {
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<string, string> = { "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) ?? "";
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"));
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");
assert.match(stripAsIs(await cardDetails(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");
assert.match(await cardDetails(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");
assert.match(await cardDetails(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");
assert.match(await cardDetails((await readyQuestions(t))[0]!), /Ревьюер не отработал: ревьюер ответил не по формату/);
// 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]);
});
});