// PEP-149, spec agent-messages: four kinds of agent messages — question, done, progress, blocker — // and where each of them goes. mock-claude runners, mock Gitea. import assert from "node:assert/strict"; import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { after, before, describe, test } from "node:test"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { chatMessages, events, questions } from "@peppa/db"; import { and, eq } from "drizzle-orm"; import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; import { stripAsIs } from "@peppa/shared/i18n"; import { MockGitea } from "../src/mock-gitea.ts"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; process.env.PEPPA_WEB_URL = "http://peppa.test"; const { createAgentServer } = await import("@peppa/mcp/agent"); const { renderQuestion, choiceToAnswer } = await import("@peppa/bot/render"); const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-msg-")), "gitea")); const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" }; const CHECKS = { typecheck: "pnpm typecheck", 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 Turns = Parameters[0]["turns"]; /** A story with an open PR (task/-1) in mock Gitea; checks are set by the test. */ async function prTask(turns: Turns) { const tp = await project({ turns }); const proj = await core.getProject(db, tp.key); const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: CHECKS }); writeFileSync(join(tp.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 sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { "f.txt": "1" }); const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`); const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`; const set = (check: string, state: string) => gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${check}`, state); const ref = () => core.resolveTask(db, tp.taskKey); return { tp, proj, sha, prUrl, set, ref }; } async function agent(projectKey: string, sessionId?: number) { const [a, b] = InMemoryTransport.createLinkedPair(); await createAgentServer(db, { defaultKey: projectKey, sessionId }).connect(a); const client = new Client({ name: "mock-agent", version: "0" }); await client.connect(b); return async (name: string, args: Record = {}) => { const r = await client.callTool({ name, arguments: args }); return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError }; }; } const projectQuestions = (projectId: number) => db.select().from(questions).where(eq(questions.projectId, projectId)); const taskEvents = (taskId: number, type: string) => db.select().from(events).where(and(eq(events.taskId, taskId), eq(events.type, type))); describe("Конец хода — это ход работы, а не вопрос", () => { test("Агент закончил ход, статус задачи тот же", async () => { const tp = await project({ turns: [[{ say: "Начал." }], [{ say: "Продолжаю." }], [{ say: "Жду проверок" }]] }); const p = await core.getProject(db, tp.key); await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" }); const sid = await tp.start(); // Two nudges of the Stop hook, then the turn really ends. await tp.waitStatus(sid, "idle"); const task = await tp.task(); assert.equal(task.status, "in_progress"); // Nothing for the person: no message at all (the bot sends to Telegram only what is in `questions`). assert.deepEqual(await projectQuestions(p.id), [], "no question, nothing in «Ждут вашего ответа» or Telegram"); // «События агентов»: a record in the story thread. const progress = await taskEvents(task.id, "progress"); assert.equal(progress.length, 1); // PEP-152: a plain reply goes as it is, in the common format. assert.equal(stripAsIs((progress[0]!.payload as { text: string }).text), "Жду проверок\nЧто нужно от вас: ничего"); await core.syncChats(db); const chat = await core.ensureProjectChat(db, p.id); const thread = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, chat.id), eq(chatMessages.threadKey, `task:${task.id}`))); const record = thread.find((m) => m.text.includes("Жду проверок")); assert.ok(record, "the reply is in the story thread"); assert.equal(record.kind, "event"); assert.equal(record.important, false, "not in the master feed"); assert.equal(record.questionId, null); await runner.stopSession(db, sid); }); test("У агента есть открытый вопрос", async () => { const tp = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какой цвет кнопки?", options: ["Синий", "Зелёный"], default: "Синий" } }, { say: "Спросил." }]] }); const p = await core.getProject(db, tp.key); await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" }); const sid = await tp.start(); await tp.waitStatus(sid, "waiting_input"); const qs = await projectQuestions(p.id); assert.equal(qs.length, 1); assert.equal(core.questionType(qs[0]!, "in_progress"), "question"); assert.deepEqual(await taskEvents((await tp.task()).id, "progress"), [], "no progress record on top of the question"); await runner.stopSession(db, sid); }); }); describe("Тип сообщения определяет маршрут", () => { const base = { taskId: 1, sessionId: 1, msgType: null, options: null } as const; test("Вопрос попадает в «Ждут вашего ответа»", () => { assert.equal(core.questionType({ ...base, kind: "question", options: ["Синий", "Зелёный"] }, "in_progress"), "question"); assert.equal(core.questionType({ ...base, kind: "permission", options: ["allow", "always", "deny"] }), "question"); assert.equal(core.questionType({ ...base, kind: "attention", options: ["🚀 Выкатить"] }), "question", "a factory message with answers to choose from"); assert.equal(core.needsPerson({ ...base, kind: "question" }, "in_progress"), true); assert.equal(core.questionEvent({ ...base, kind: "question" }, { taskStatus: "in_progress" }), "questions"); }); test("Сообщение о сбое не попадает в «Ждут вашего ответа»", () => { const failure = { ...base, kind: "attention" as const }; assert.equal(core.questionType(failure, "in_progress"), null); assert.equal(core.needsPerson(failure, "in_progress"), false); assert.equal(core.questionEvent(failure, { taskStatus: "in_progress", sessionStatus: "failed" }), "failures"); // «Готово» — отдельным блоком: ждёт «Принять», но это не вопрос. assert.equal(core.questionType({ ...failure, msgType: "done" }, "review"), "done"); assert.equal(core.questionType(failure, "review"), "done", "rows before PEP-149"); assert.equal(core.needsPerson(failure, "review"), true); assert.equal(core.questionEvent(failure, { taskStatus: "review" }), "review"); }); test("Сообщения «продукт обновлён» и «бэклог пуст» — не вопросы", async () => { const tp = await project({ turns: [] }); const p = await core.getProject(db, tp.key); for (const text of ["🚀 Shop: ваш продукт обновлён и открыт для всех", "📭 Shop: все задачи сделаны, бэклог пуст — агентам нечего делать."]) { const q = await core.askPmProject(db, p, { kind: "attention", text }); assert.equal(q.msgType, null); assert.equal(core.needsPerson(q), false, "not in «Ждут вашего ответа», not counted, no push"); // Telegram: a plain notice — no buttons to press. assert.deepEqual(renderQuestion(q, { taskKey: null, taskTitle: null, session: null, webUrl: "http://peppa.test" }).buttons, []); } // The offer to release has an answer to choose: it is a question. const offer = await core.askPmProject(db, p, { kind: "question", text: "Показать всем?", options: ["🚀 Показать всем"] }); assert.equal(core.needsPerson(offer), true); }); test("Счётчик открытых вопросов чата считает только вопросы", async () => { const tp = await project({ turns: [] }); const p = await core.getProject(db, tp.key); const ref = await core.resolveTask(db, tp.taskKey); await core.askPm(db, ref, { kind: "attention", text: "агент остановился с ошибкой" }); await core.askPm(db, ref, { kind: "question", text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"], defaultOption: "Синий" }); const u = await core.upsertUserFromGitea(db, { id: 9149, login: "mock-pm-149" }, { access_token: "a" }); await core.setProjectOwner(db, p.id, u.id); const chat = (await core.listChats(db, u)).find((c) => c.projectId === p.id)!; assert.equal(chat.open, 1); }); }); describe("«Готово» шлёт платформа после проверок", () => { test("Проверки ещё идут", async () => { const t = await prTask([]); t.set("typecheck", "success"); t.set("test", "pending"); await core.updateTask(db, await t.ref(), { prUrl: t.prUrl }); const sent = await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью"); assert.equal(sent, null, "held"); assert.deepEqual(await projectQuestions(t.proj.id), [], "the owner got nothing"); assert.ok(await core.getReviewHold(db, (await t.ref()).task.id)); // Red checks: still nothing. t.set("test", "failure"); assert.equal(await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью"), null); assert.deepEqual(await projectQuestions(t.proj.id), []); }); test("Проверки прошли", async () => { const t = await prTask([]); t.set("typecheck", "success"); t.set("test", "success"); await core.updateTask(db, await t.ref(), { status: "review", prUrl: t.prUrl }); const sent = await core.sendReviewCard(db, await t.ref(), `✅ Задача ${t.tp.taskKey} готова к ревью · Результат: ${t.prUrl}`); assert.ok(sent); assert.equal(sent.msgType, "done"); assert.ok(sent.text.includes(t.prUrl), "the link to the result"); assert.equal(core.questionType(sent, "review"), "done"); // A card without any link gets the link to the task page. const bare = await core.sendReviewCard(db, await t.ref(), "✅ Готово"); assert.match(bare!.text, new RegExp(`http://peppa\\.test/t/${t.tp.taskKey}`)); }); }); describe("Платформа будит агента, когда проверки прошли", () => { test("Проверки прошли, агент ждал; повторный отчёт о том же коммите", async () => { const t = await prTask([[{ say: "PR открыт." }], [{ say: "Жду." }], [{ say: "Жду проверок" }], [{ say: "Перевожу." }], [{ say: "Ок." }], [{ say: "Ок." }]]); await core.updateTask(db, await t.ref(), { status: "in_progress" }); t.set("typecheck", "pending"); t.set("test", "pending"); const sid = await t.tp.start(); await t.tp.waitStatus(sid, "idle"); const woke = () => t.tp.log().filter((e) => e.ev === "prompt" && String(e.prompt).includes("Проверки PR")); // One check of two passed: not yet. t.set("typecheck", "success"); await runner.recordCheck(db, t.proj, { sha: t.sha, branch: `task/${t.tp.taskKey}`, check: "typecheck", state: "success" }); assert.equal(woke().length, 0); t.set("test", "success"); await runner.recordCheck(db, t.proj, { sha: t.sha, branch: `task/${t.tp.taskKey}`, check: "test", state: "success" }); await waitFor("the agent is told the checks passed", async () => woke().length || undefined); assert.match(String(woke()[0]!.prompt), /прошли/); assert.deepEqual(await projectQuestions(t.proj.id), [], "the person is not involved"); await t.tp.waitStatus(sid, "idle"); assert.equal(await runner.wakeOnGreen(db, await t.ref(), { sha: t.sha, branch: `task/${t.tp.taskKey}` }), false, "once per commit"); assert.equal(woke().length, 1); await runner.stopSession(db, sid); }); }); describe("Зелёные проверки, но PR конфликтует (PEP-196)", () => { test("агент, ждущий проверок, получает просьбу обновить ветку; страховка находит PR по ветке", async () => { const t = await prTask([[{ say: "PR открыт." }], [{ say: "Жду проверок" }], [{ say: "Обновляю ветку." }], [{ say: "Ок." }]]); await core.updateTask(db, await t.ref(), { status: "in_progress" }); const sid = await t.tp.start(); await t.tp.waitStatus(sid, "idle"); const woke = () => t.tp.log().filter((e) => e.ev === "prompt" && String(e.prompt).includes("смержить PR")); t.set("typecheck", "success"); t.set("test", "success"); gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls.at(-1)!.mergeable = false; // The report came while nobody listened: the minute sweep finds the PR by the branch (no pr_url on the task). assert.equal((await core.resolveTask(db, t.tp.taskKey)).task.prUrl, null); assert.equal(await runner.wakeIdleOnGreen(db), 1); await waitFor("the agent is told to update its branch", async () => woke().length || undefined); assert.match(String(woke()[0]!.prompt), /конфликты с основной веткой.*rebase/s); assert.deepEqual(await projectQuestions(t.proj.id), [], "the person is not involved"); await t.tp.waitStatus(sid, "idle"); assert.equal(await runner.wakeIdleOnGreen(db), 0, "once per commit"); await runner.stopSession(db, sid); }); }); describe("Вопрос агента — с вариантами и вариантом по умолчанию", () => { test("Вопрос с вариантами принят", async () => { const tp = await project({ turns: [] }); const p = await core.getProject(db, tp.key); const call = await agent(tp.key); const r = await call("ask_pm", { task: tp.taskKey, question: "Показывать цену сразу?", options: ["Нет", "Да"], default: "Да" }); assert.equal(r.isError, false, r.text); const [q] = await projectQuestions(p.id); assert.equal(q!.msgType, "question"); assert.equal(q!.defaultOption, "Да"); assert.deepEqual(q!.options, ["Да", "Нет"], "the default goes first"); }); for (const [name, args, why] of [ ["без вариантов", {}, /2–4 answer options/], ["один вариант", { options: ["Да"], default: "Да" }, /2–4 answer options/], ["пять вариантов", { options: ["1", "2", "3", "4", "5"], default: "1" }, /2–4 answer options/], ["без варианта по умолчанию", { options: ["Да", "Нет"] }, /`default`/], ["вариант по умолчанию не из списка", { options: ["Да", "Нет"], default: "Может быть" }, /one of `options`/], ] as const) { test(`Вопрос без вариантов отклонён: ${name}`, async () => { const tp = await project({ turns: [] }); const p = await core.getProject(db, tp.key); const r = await (await agent(tp.key))("ask_pm", { task: tp.taskKey, question: "Показывать цену сразу?", ...args }); assert.equal(r.isError, true); assert.match(r.text, why); assert.deepEqual(await projectQuestions(p.id), [], "no question"); }); } }); describe("Блокер идёт по своему маршруту", () => { test("Непродуктовый блокер", async () => { const tp = await project({ turns: [] }); const p = await core.getProject(db, tp.key); const r = await (await agent(tp.key))("report_blocker", { task: tp.taskKey, what: "нет доступа к серверу сборки", tried: "повторил три раза" }); assert.equal(r.isError, false, r.text); assert.deepEqual(await projectQuestions(p.id), [], "the owner is not asked"); const task = await tp.task(); assert.equal((await taskEvents(task.id, "blocker")).length, 1); await core.syncChats(db); const chat = await core.ensureProjectChat(db, p.id); const thread = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, chat.id), eq(chatMessages.threadKey, `task:${task.id}`))); const record = thread.find((m) => m.text.includes("нет доступа к серверу сборки")); assert.ok(record); assert.equal(record.important, false); // PEP-152: what the agent tried is technical — it opens under «Подробнее». assert.doesNotMatch(record.text, /повторил три раза/); const [view] = (await core.chatMessagesView(db, chat.id, { threadKey: `task:${task.id}` })).filter((m) => m.id === record.id); assert.match(stripAsIs(view!.details ?? ""), /Что уже пробовал: повторил три раза/); }); test("Продуктовый блокер без вариантов; с вариантами — вопрос", async () => { const tp = await project({ turns: [] }); const p = await core.getProject(db, tp.key); const call = await agent(tp.key); const refused = await call("report_blocker", { task: tp.taskKey, what: "Нужен аккаунт платёжного сервиса", tried: "сделал на моке", product: true }); assert.equal(refused.isError, true); assert.match(refused.text, /2–4 answer options/); assert.deepEqual(await projectQuestions(p.id), []); const ok = await call("report_blocker", { task: tp.taskKey, what: "Нужен аккаунт платёжного сервиса", tried: "сделал на моке", product: true, options: ["Оставить демо", "Дам аккаунт"], default: "Оставить демо" }); assert.equal(ok.isError, false, ok.text); const [q] = await projectQuestions(p.id); assert.equal(core.questionType(q!), "question"); assert.equal(q!.defaultOption, "Оставить демо"); }); }); describe("Нет кнопки «Продолжай»", () => { const q = (over: Record) => ({ id: 7, projectId: 1, taskId: 1, sessionId: null, kind: "attention", text: "агент остановился с ошибкой", options: null, msgType: null, defaultOption: null, answer: null, answeredVia: null, telegramMessageId: null, awaitingHook: false, reminders: 0, createdAt: new Date(), answeredAt: null, ...over }) as never; const ctx = { taskKey: "PEP-1", taskTitle: "t", taskStatus: "in_progress", session: null, webUrl: "http://peppa.test" }; test("Сообщение фабрики в Telegram", () => { const r = renderQuestion(q({}), ctx); assert.deepEqual(r.buttons, [], "no buttons at all"); assert.doesNotMatch(r.text, /Продолжай/); }); test("Вопрос — кнопки вариантов и вариант по умолчанию", () => { const r = renderQuestion(q({ kind: "question", text: "Какой цвет?", options: ["Синий", "Зелёный"], msgType: "question", defaultOption: "Синий" }), ctx); assert.deepEqual(r.buttons.flat().map((b) => b.text), ["Синий", "Зелёный"]); assert.match(r.text, /продолжит по варианту «Синий»/); assert.match(r.text, /своим текстом/); }); test("Старая кнопка «Продолжай»", () => { assert.equal(choiceToAnswer(q({}), "cont"), null, "nothing goes to the agent"); }); test("В вебе и боте кнопки нет", () => { const root = join(import.meta.dirname, "../../.."); for (const f of ["apps/web/components/cards.tsx", "apps/bot/src/render.ts"]) { assert.doesNotMatch(readFileSync(join(root, f), "utf8").replace(/\/\/.*|\{\/\*.*?\*\/\}/g, ""), /Продолжай|"cont"/, f); } }); });