Сообщение агента пользователю собирается из полей 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>
307 lines
19 KiB
TypeScript
307 lines
19 KiB
TypeScript
// PEP-152, spec agent-messages: the format of an agent's message for the person — the gist, «Что
|
||
// нужно от вас», «Где посмотреть», technical details under «Подробнее» — and the check of the
|
||
// main text when the message is taken. Tests are named after the scenarios of the spec.
|
||
import assert from "node:assert/strict";
|
||
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { join, resolve } 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 { events, questions, telegramOutbox, users } from "@peppa/db";
|
||
import { and, eq } from "drizzle-orm";
|
||
import { core, db, project, runner, teardown } from "./helpers.ts";
|
||
import { localizeText, stripAsIs } from "@peppa/shared/i18n";
|
||
import { MockGitea } from "../src/mock-gitea.ts";
|
||
|
||
// PEP-139: the agent's own words are stored with invisible free-text marks — the reader strips them.
|
||
const plain = (t: string | null | undefined) => stripAsIs(t ?? "");
|
||
|
||
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 } = await import("@peppa/bot/render");
|
||
|
||
const ROOT = resolve(import.meta.dirname, "../../..");
|
||
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-fmt-")), "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();
|
||
});
|
||
|
||
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<string, unknown> = {}) => {
|
||
const r = await client.callTool({ name, arguments: args });
|
||
return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
|
||
};
|
||
}
|
||
|
||
/** A story in work and an agent's MCP client for it. */
|
||
async function story() {
|
||
const tp = await project({ turns: [] });
|
||
const p = await core.getProject(db, tp.key);
|
||
await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" });
|
||
const task = await tp.task();
|
||
const call = await agent(tp.key);
|
||
const progress = () => db.select().from(events).where(and(eq(events.taskId, task.id), eq(events.type, "progress")));
|
||
const thread = async () => {
|
||
await core.syncChats(db);
|
||
const chat = await core.ensureProjectChat(db, p.id);
|
||
return (await core.chatMessagesView(db, chat.id, { threadKey: `task:${task.id}` })).filter((m) => m.authorKind === "agent");
|
||
};
|
||
return { tp, p, task, call, progress, thread };
|
||
}
|
||
|
||
const TECH = "tasks.md, task/pep-1, pnpm lint, PR #137, in_progress";
|
||
|
||
describe("Формат сообщения агента", () => {
|
||
test("Ход работы с подробностями", async () => {
|
||
const s = await story();
|
||
const r = await s.call("report_progress", { task: "1", summary: "Форма входа готова, проверяю её на телефоне", details: "pnpm lint зелёный, ветка task/demo-1" });
|
||
assert.equal(r.isError, false, r.text);
|
||
const [m] = (await s.thread()).filter((x) => x.text.includes("Форма входа готова"));
|
||
assert.ok(m, "the note is in the story thread");
|
||
const shown = core.splitForDisplay(plain(m.text), plain(m.details));
|
||
assert.match(shown.main, /Форма входа готова, проверяю её на телефоне\nЧто нужно от вас: ничего$/);
|
||
assert.ok(shown.main.split("\n").length <= core.MAIN_MAX_LINES);
|
||
assert.ok(!shown.main.includes("pnpm lint"), "details are not in the main text");
|
||
assert.equal(shown.more, "pnpm lint зелёный, ветка task/demo-1");
|
||
});
|
||
|
||
test("Длинное сообщение в чате", () => {
|
||
const text = Array.from({ length: 12 }, (_, i) => `Строка ${i + 1}`).join("\n");
|
||
const shown = core.splitForDisplay(text);
|
||
assert.equal(shown.main, "Строка 1\nСтрока 2\nСтрока 3\nСтрока 4\nСтрока 5");
|
||
assert.match(shown.more!, /^Строка 6\n[\s\S]*Строка 12$/);
|
||
// One very long line is cut as well.
|
||
assert.ok(core.splitForDisplay("я".repeat(3000)).main.length < 800);
|
||
});
|
||
|
||
test("Ссылка — отдельной строкой «Где посмотреть»", () => {
|
||
assert.equal(
|
||
plain(core.renderMain({ summary: "Страница оплаты готова", need: "посмотрите её", link: "https://shop-pr3.telecom.quest", details: "x" })),
|
||
"Страница оплаты готова\nЧто нужно от вас: посмотрите её\nГде посмотреть: https://shop-pr3.telecom.quest",
|
||
);
|
||
});
|
||
|
||
test("На другом языке переводятся строки платформы, слова агента остаются как написаны", () => {
|
||
const text = core.renderMain({ summary: "Форма входа готова", link: "https://shop-pr3.telecom.quest" });
|
||
assert.equal(localizeText("en", text), "Форма входа готова\nWhat we need from you: nothing\nWhere to look: https://shop-pr3.telecom.quest");
|
||
assert.match(localizeText("kk", text), /^Форма входа готова\nСізден не керек: ештеңе\n/);
|
||
});
|
||
|
||
test("Реплика конца хода: понятная идёт как есть, техническая — под «Подробнее»", () => {
|
||
assert.deepEqual(core.fitAgentText("Жду проверок"), { summary: "Жду проверок" });
|
||
// The agent's words are marked free text; the factory's line around them is not (it is translated).
|
||
assert.equal(core.renderMain({ summary: "Жду проверок" }), "\u2068Жду проверок\u2069\nЧто нужно от вас: ничего");
|
||
assert.equal(core.renderMain(core.fitAgentText("см. tasks.md")), "Агент закончил шаг работы над задачей.\nЧто нужно от вас: ничего");
|
||
const raw = "Запушил ветку task/pep-1, проверки 0 из 4, update_task(status: review) пока нельзя.";
|
||
const fit = core.fitAgentText(raw);
|
||
assert.equal(fit.summary, "Агент закончил шаг работы над задачей.");
|
||
assert.equal(fit.details, raw);
|
||
});
|
||
});
|
||
|
||
describe("Проверка основного текста при приёме", () => {
|
||
for (const [summary, violation] of [
|
||
["Обновил tasks.md", "file name"],
|
||
["Работаю в task/pep-1", "branch"],
|
||
["Запустил pnpm lint", "command"],
|
||
["Открыл PR #137", "pull request number"],
|
||
["Задача в in_progress", "status or identifier"],
|
||
["Раннер упал, перезапускаю", "раннер"],
|
||
] as const) {
|
||
test(`Техническое обозначение в сути: «${summary}»`, async () => {
|
||
const s = await story();
|
||
const r = await s.call("report_progress", { task: "1", summary });
|
||
assert.equal(r.isError, true);
|
||
assert.match(r.text, /^Not sent/);
|
||
assert.ok(r.text.toLowerCase().includes(violation), r.text);
|
||
assert.deepEqual(await s.progress(), [], "nothing is sent");
|
||
assert.deepEqual(await s.thread(), []);
|
||
});
|
||
}
|
||
|
||
test("Те же слова в подробностях", async () => {
|
||
const s = await story();
|
||
const r = await s.call("report_progress", { task: "1", summary: "Проверки пройдены, жду решения", details: TECH });
|
||
assert.equal(r.isError, false, r.text);
|
||
const [m] = await s.thread();
|
||
assert.match(plain(m!.text), /Проверки пройдены, жду решения/);
|
||
assert.equal(plain(m!.details), TECH);
|
||
// The check itself: all five in the gist — five kinds of violations; in the details — none.
|
||
const bad = core.checkAgentMessage({ summary: `Готово: ${TECH}` });
|
||
for (const what of ["file name", "branch", "command", "pull request number", "status or identifier"]) assert.ok(bad.some((v) => v.includes(what)), `${what}: ${bad.join(" | ")}`);
|
||
assert.deepEqual(core.checkAgentMessage({ summary: "Проверки пройдены, жду решения", details: TECH }), []);
|
||
});
|
||
|
||
test("Вопрос с запрещённым словом", async () => {
|
||
const s = await story();
|
||
const r = await s.call("ask_pm", { task: "1", question: "Делать ли деплой сегодня?", options: ["Да", "Нет"], default: "Да" });
|
||
assert.equal(r.isError, true);
|
||
assert.match(r.text, /«деплой»/);
|
||
assert.match(r.text, /показать всем/, "what to write instead, from the glossary");
|
||
assert.deepEqual(await db.select().from(questions).where(eq(questions.projectId, s.p.id)), []);
|
||
|
||
// Plain words: the question goes, its details are kept apart.
|
||
const ok = await s.call("ask_pm", { task: "1", question: "Показывать ли новую версию всем сегодня?", options: ["Да", "Нет"], default: "Да", details: "PR #12, ветка task/demo-1" });
|
||
assert.equal(ok.isError, false, ok.text);
|
||
const [q] = await db.select().from(questions).where(eq(questions.projectId, s.p.id));
|
||
assert.equal(plain(q!.text), "Показывать ли новую версию всем сегодня?\nЧто нужно от вас: выберите вариант ответа");
|
||
assert.equal(plain((await core.messageDetails(db, [q!.id])).get(q!.id)), "PR #12, ветка task/demo-1");
|
||
});
|
||
|
||
test("Обычные слова не отклоняются", () => {
|
||
for (const summary of [
|
||
"Задача PEP-42 готова на две трети: осталась страница оплаты",
|
||
"Добавил вход по почте — письмо с кодом приходит за минуту",
|
||
"Сделал 3 из 5 экранов, и/или фильтр по дате работает 24/7",
|
||
"Проверки пройдены, версия для проверки открывается",
|
||
]) assert.deepEqual(core.checkAgentMessage({ summary }), [], summary);
|
||
assert.ok(core.checkAgentMessage({ summary: "Первая строка\nВторая строка" }).some((v) => v.includes("lines")));
|
||
assert.ok(core.checkAgentMessage({ summary: "Готово", link: "см. в чате" }).some((v) => v.startsWith("link")));
|
||
assert.ok(core.checkAgentMessage({ summary: "Готово, смотрите https://example.com" }).some((v) => v.includes("`link`")));
|
||
});
|
||
});
|
||
|
||
describe("Три отказа подряд", () => {
|
||
test("Четвёртая попытка", async () => {
|
||
const s = await story();
|
||
const admin = await core.upsertUserFromGitea(db, { id: 1520, login: "mock-admin-1520" }, { access_token: "x" });
|
||
await db.update(users).set({ telegramChatId: 1520 }).where(eq(users.id, admin.id));
|
||
await core.setPlatformAdmins(db, [admin.login]);
|
||
try {
|
||
for (let i = 1; i <= 3; i++) {
|
||
const r = await s.call("report_progress", { task: "1", summary: "Обновил tasks.md" });
|
||
assert.equal(r.isError, true);
|
||
assert.match(r.text, new RegExp(`Not sent \\(${i} of 3\\)`));
|
||
}
|
||
assert.deepEqual(await s.progress(), []);
|
||
const r = await s.call("report_progress", { task: "1", summary: "Обновил tasks.md" });
|
||
assert.equal(r.isError, false, r.text);
|
||
assert.match(r.text, /neutral first line/);
|
||
const [m] = await s.thread();
|
||
const shown = core.splitForDisplay(plain(m!.text), plain(m!.details));
|
||
assert.match(shown.main, /Агент продолжает работу над задачей/);
|
||
assert.ok(!shown.main.includes("tasks.md"));
|
||
assert.equal(shown.more, "Обновил tasks.md");
|
||
// The superadmin's mark: an event and one message.
|
||
const [failed] = await db.select().from(events).where(and(eq(events.taskId, s.task.id), eq(events.type, "message_format_failed")));
|
||
assert.ok(failed);
|
||
const out = (await db.select().from(telegramOutbox)).filter((o) => String((o.params as { text?: string }).text).includes("не смог написать сообщение понятно"));
|
||
assert.equal(out.length, 1, "one message for the superadmin");
|
||
assert.equal((out[0]!.params as { chat_id: number }).chat_id, 1520);
|
||
} finally {
|
||
await core.setPlatformAdmins(db, null);
|
||
}
|
||
});
|
||
|
||
test("Удачное сообщение сбрасывает счёт", async () => {
|
||
const s = await story();
|
||
for (let i = 0; i < 2; i++) assert.equal((await s.call("report_progress", { task: "1", summary: "Обновил tasks.md" })).isError, true);
|
||
assert.equal((await s.call("report_progress", { task: "1", summary: "Форма входа готова" })).isError, false);
|
||
for (let i = 1; i <= 3; i++) {
|
||
const r = await s.call("report_progress", { task: "1", summary: "Обновил tasks.md" });
|
||
assert.equal(r.isError, true, "counted from one again");
|
||
assert.match(r.text, new RegExp(`\\(${i} of 3\\)`));
|
||
}
|
||
assert.equal((await s.progress()).length, 1);
|
||
});
|
||
});
|
||
|
||
describe("Карточка «готово» в том же формате", () => {
|
||
/** A story with an open PR and green checks in mock Gitea. */
|
||
async function prStory(turns: Parameters<typeof project>[0]["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}`;
|
||
for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${c}`, "success");
|
||
return { tp, proj, prUrl };
|
||
}
|
||
|
||
test("Задача готова", async () => {
|
||
const t = await prStory([]);
|
||
const turns = [[{ mcp: "update_task", args: { task: "1", status: "review", pr_url: t.prUrl, summary: "Добавил вход по почте", details: "ветка task/demo-1, pnpm test зелёный" } }, { say: "Готово, PR открыт." }]];
|
||
writeFileSync(join(t.tp.dir, ".peppa/mock-scenario.json"), JSON.stringify({ turns }));
|
||
await core.updateTask(db, await core.resolveTask(db, t.tp.taskKey), { status: "in_progress" });
|
||
const sid = await t.tp.start();
|
||
await t.tp.waitStatus(sid, "waiting_input");
|
||
const [q] = await db.select().from(questions).where(eq(questions.projectId, t.proj.id));
|
||
assert.ok(q, "«готово» is sent");
|
||
assert.equal(q.msgType, "done");
|
||
assert.deepEqual(plain(q.text).split("\n"), [
|
||
`✅ Задача ${t.tp.taskKey} готова к ревью`,
|
||
"Добавил вход по почте",
|
||
"Что нужно от вас: посмотрите результат и нажмите «Принять» — или напишите, что поправить",
|
||
`Где посмотреть: http://peppa.test/t/${t.tp.taskKey}`,
|
||
]);
|
||
const details = plain((await core.messageDetails(db, [q.id])).get(q.id));
|
||
assert.ok(details.includes(t.prUrl), "the result address is under «Подробнее»");
|
||
assert.match(details, /ветка task\/demo-1, pnpm test зелёный/);
|
||
assert.match(details, /Готово, PR открыт\./, "the agent's last reply too");
|
||
assert.ok(!q.text.includes(t.prUrl));
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
|
||
test("Итог с техническим обозначением", async () => {
|
||
const t = await prStory([]);
|
||
await core.updateTask(db, await core.resolveTask(db, t.tp.taskKey), { status: "in_progress" });
|
||
const call = await agent(t.tp.key);
|
||
const r = await call("update_task", { task: "1", status: "review", pr_url: t.prUrl, summary: "Смержил ветку task/demo-1" });
|
||
assert.equal(r.isError, true);
|
||
assert.match(r.text, /branch/);
|
||
assert.equal((await t.tp.task()).status, "in_progress");
|
||
});
|
||
});
|
||
|
||
describe("Подробности в Telegram", () => {
|
||
const ctx = { taskKey: "DEMO-1", taskTitle: "Вход", taskStatus: "in_progress", session: null, webUrl: "http://peppa.test" };
|
||
const q = { id: 7, projectId: 1, taskId: 1, sessionId: null, kind: "question", text: "Какой цвет кнопки?\nЧто нужно от вас: выберите вариант ответа", options: ["Синий", "Зелёный"], msgType: "question", defaultOption: "Синий", answer: null, answeredVia: null, telegramMessageId: null, awaitingHook: false, reminders: 0, createdAt: new Date(), answeredAt: null } as Parameters<typeof renderQuestion>[0];
|
||
|
||
test("Вопрос с подробностями", () => {
|
||
const r = renderQuestion(q, { ...ctx, details: true });
|
||
assert.ok(!r.text.includes("design.md"));
|
||
assert.deepEqual(r.buttons.at(-1), [{ text: "Подробнее", url: "http://peppa.test/t/DEMO-1?more=1" }]);
|
||
// A long old message: five lines in Telegram, the rest by the button.
|
||
const long = renderQuestion({ ...q, text: Array.from({ length: 9 }, (_, i) => `Строка ${i + 1}`).join("\n") }, ctx);
|
||
assert.ok(long.text.includes("Строка 5") && !long.text.includes("Строка 6"));
|
||
assert.equal(long.buttons.at(-1)?.[0]?.url, "http://peppa.test/t/DEMO-1?more=1");
|
||
});
|
||
|
||
test("Вопрос без подробностей", () => {
|
||
const r = renderQuestion(q, ctx);
|
||
assert.ok(r.buttons.every((row) => row.every((b) => !b.url)), "no «Подробнее» button");
|
||
assert.equal(r.buttons.length, 2);
|
||
});
|
||
});
|
||
|
||
describe("Правила для агентов", () => {
|
||
test("template/RULES.md описывает формат с примерами «плохо / хорошо»", () => {
|
||
const rules = readFileSync(join(ROOT, "template/RULES.md"), "utf8");
|
||
for (const part of ["`summary`", "`need`", "`link`", "`details`", "Что нужно от вас", "Где посмотреть", "Подробнее", "Плохо", "Хорошо"]) assert.ok(rules.includes(part), part);
|
||
// The «хорошо» examples of the rules pass the check, the «плохо» ones do not.
|
||
const examples = [...rules.matchAll(/^- (Плохо|Хорошо): «(.+)»/gm)];
|
||
assert.ok(examples.length >= 4);
|
||
for (const [, kind, text] of examples) assert.equal(core.checkAgentMessage({ summary: text! }).length === 0, kind === "Хорошо", `${kind}: ${text}`);
|
||
});
|
||
});
|