peppa/packages/testkit/test/no-repeats.test.ts
peppa-bot f3d10a4c25 PEP-243: платформа называется FORGE — название во всех текстах для людей и подсказках агентам, адрес forge.telecom.quest
«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках
агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя».
Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 11:18:49 +05:00

235 lines
16 KiB
TypeScript
Raw Permalink 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-151: one state — one message. The same state of a story reported again does not make a
// new question, chat message or Telegram message: the earlier one is refreshed. A changed state
// (another commit, checks, status) makes a new one. Tests are named after the spec scenarios.
import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
// helpers must load first: it sets the isolated test env that runner modules read on load.
import { core, db, runner, teardown, waitFor } from "./helpers.ts";
import { MockTelegram } from "../src/mock-telegram.ts";
import { questions, sessions, users } from "@peppa/db";
import { eq } from "drizzle-orm";
import type { Bot } from "@peppa/bot";
const { createBot } = await import("@peppa/bot");
const { TelegramApi } = await import("@peppa/bot/telegram");
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const tg = await new MockTelegram().start();
const PM = { id: 901, chatId: 901, username: "pm" };
const EDIT_MS = 2500;
let bot: Bot;
let pm: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let seq = 0;
// What the agent of PEP-147 told the user nine times in 18 minutes (questions #404–#421).
const PEP_147 = [
"PEP-147 готова и открыта как PR #137: https://git.telecom.quest/peppa/peppa/pulls/137. Статус `review` поставить пока не удалось: проверки PR ещё идут (0 из 4), а на `review` FORGE пускает только при зелёных.",
"PR #137 по PEP-147 открыт, но в `review` я его пока не перевёл. FORGE пускает в `review` только при зелёных проверках, а они ещё идут (было 0 из 4).\n\nПроверю статус снова примерно через 10 минут.",
"Проверки PR #137 всё ещё показывают 0 из 4, поэтому `review` поставить нельзя: FORGE его отклоняет. Больше я ничего не менял.\n\nПроверю снова примерно через 15 минут.",
"Стори PEP-147 остаётся в `in_progress`: FORGE не принимает `review`, потому что проверки PR #137 показывают 0 из 4.\n\nВся работа по `tasks.md` сделана и запушена. Через 20 минут уже стоит запланированная повторная проверка.",
"Стори PEP-147 так и не в `review`: проверки PR #137 по-прежнему показывают 0 из 4.\n\nКак только проверки пройдут, достаточно вызвать `update_task(status: review)`.",
"PEP-147 всё ещё не в `review`: проверки PR #137 по-прежнему на 0 из 4, FORGE отклоняет перевод.\n\nПроверки не стартуют: возможно, раннер `peppa-trusted` не подхватил PR #137 или не дошёл вебхук.",
"PEP-147 остаётся в `in_progress`: проверки PR #137 по-прежнему на 0 из 4, и FORGE не принимает `review`.\n\nКогда проверки станут зелёными, достаточно вызвать `update_task(status: review)`.",
"Стори PEP-147 по-прежнему не в `review`: проверки PR #137 на 0 из 4, и FORGE отклоняет перевод.\n\nРабота по `tasks.md` сделана и запушена, конфликтов с main нет.",
"PEP-147 пока не в `review`: проверки PR #137 по-прежнему на 0 из 4, и FORGE отклоняет перевод.\n\nПродвинуть проверки из этой сессии нельзя, а раннер `peppa-trusted` и вебхук мне не видны.",
];
/** A story at work with its agent's session (no tmux: the messages are raised as the Stop hook does). */
async function story(status: "in_progress" | "review" = "in_progress") {
const key = `N${String.fromCharCode(65 + seq++)}`;
const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id });
const created = await core.createTask(db, { projectId: p.id, title: "Telegram по желанию" });
await core.updateTask(db, await core.resolveTask(db, created.key), { status });
const [s] = await db.insert(sessions).values({ projectId: p.id, taskId: created.task.id, tmuxName: `mock-${key}`, status: "waiting_input" }).returning();
const ref = () => core.resolveTask(db, created.key);
const session = () => core.getSession(db, s!.id);
return {
project: p,
taskId: created.task.id,
ref,
session,
/** The agent ended its turn with this text (the last branch of the Stop hook). */
turnEnd: async (text: string) => core.raiseSessionQuestion(db, await session(), "attention", text, undefined, false, { topic: "turn" }),
asked: () => db.select().from(questions).where(eq(questions.taskId, created.task.id)).orderBy(questions.id),
check: (sha: string, state: "pending" | "success" | "failure") => core.upsertCheckRun(db, p, created.task.id, { sha, check: "test", state }),
thread: async () => {
await core.syncChats(db);
return core.chatMessagesView(db, (await core.ensureProjectChat(db, p.id)).id, { threadKey: `task:${created.task.id}` });
},
};
}
const go = (questionId: number) => core.answerQuestion(db, questionId, "Продолжай.", "telegram");
const tgAbout = (key: string) => tg.botMessages(PM.chatId).filter((m) => m.text.includes(`<b>${key}-1</b>`));
before(async () => {
pm = await core.upsertUserFromGitea(db, { id: 91, login: "mock-pm" }, { access_token: "x" });
await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id));
bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, repeatEditMs: EDIT_MS });
await bot.start();
});
after(async () => {
await bot?.stop();
await tg.stop();
await teardown();
});
describe("Одно состояние — одно сообщение", () => {
test("Агент девять раз сообщает одно и то же; Telegram: девять повторов — одно сообщение", async () => {
const t = await story();
const first = await t.turnEnd(PEP_147[0]!);
await waitFor("the message in Telegram", async () => tgAbout(t.project.key).length === 1);
for (const text of PEP_147.slice(1)) {
await go(first.id);
const again = await t.turnEnd(text);
assert.equal(again.id, first.id, "the same message, not a new one");
}
const asked = await t.asked();
assert.equal(asked.length, 1);
assert.equal(asked[0]!.text, PEP_147.at(-1));
assert.equal(asked[0]!.answeredAt, null, "waits for an answer again");
const st = await core.questionState(db, first.id);
assert.equal(st?.repeats, 8);
assert.ok(st?.updatedAt);
// «Ждут вашего ответа» and the story's thread: one message.
assert.equal((await core.pendingQuestions(db, t.project.id)).length, 1);
const inThread = (await t.thread()).filter((m) => m.kind === "question");
assert.equal(inThread.length, 1);
assert.equal(inThread[0]!.repeats, 8);
assert.ok(inThread[0]!.updatedAt);
// Telegram: still one message, with the last text; PEP-149: no «Продолжай» button any more.
const msg = await waitFor("the Telegram message refreshed", async () => {
const [m] = tgAbout(t.project.key);
return m && m.text.includes("Продвинуть проверки из этой сессии нельзя") && !m.reply_markup?.inline_keyboard.flat().some((b) => /Продолжай/.test(b.text)) ? m : null;
});
assert.equal(tgAbout(t.project.key).length, 1);
assert.ok(msg.edits >= 1);
});
test("Правки чаще раза в 5 минут", async () => {
const t = await story();
const q = await t.turnEnd("Проверки ещё идут.");
await waitFor("sent", async () => tgAbout(t.project.key).length === 1);
await t.turnEnd("Проверки всё ещё идут — жду.");
const at = Date.now();
await waitFor("first refresh", async () => tgAbout(t.project.key)[0]!.text.includes("всё ещё идут"));
await t.turnEnd("Проверки по-прежнему идут, ничего нового.");
await new Promise((r) => setTimeout(r, 900));
assert.ok(!tgAbout(t.project.key)[0]!.text.includes("ничего нового"), "too early for another edit");
await waitFor("second refresh after the pause", async () => tgAbout(t.project.key)[0]!.text.includes("ничего нового"));
assert.ok(Date.now() - at >= EDIT_MS - 400, "not earlier than the pause");
assert.equal(tgAbout(t.project.key).length, 1);
assert.equal((await core.getQuestion(db, q.id)).answeredAt, null);
});
for (const [name, change] of [
["у результата появился новый коммит", async (t: Awaited<ReturnType<typeof story>>) => void (await t.check("bbb2222", "pending"))],
["проверки прошли", async (t: Awaited<ReturnType<typeof story>>) => void (await t.check("aaa1111", "success"))],
["задача перешла в другой статус", async (t: Awaited<ReturnType<typeof story>>) => void (await core.updateTask(db, await t.ref(), { status: "proposing" }))],
] as const) {
test(`Состояние изменилось: ${name}`, async () => {
const t = await story();
await t.check("aaa1111", "pending");
const first = await t.turnEnd("Проверки ещё идут.");
await waitFor("the first Telegram message", async () => tgAbout(t.project.key).length === 1);
await go(first.id);
await change(t);
const next = await t.turnEnd("Проверки ещё идут.");
assert.notEqual(next.id, first.id);
assert.equal((await t.asked()).length, 2);
assert.ok((await core.getQuestion(db, first.id)).answeredAt, "the earlier message stays answered");
await waitFor("a new Telegram message", async () => tgAbout(t.project.key).length === 2);
});
}
test("Повторное «готово» для того же результата", async () => {
const t = await story("review");
await t.check("abc1230", "success");
const card = await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью");
assert.ok(card);
// Remarks send it back to work; a note of FORGE lands in between; back to review, no new commit.
await core.answerQuestion(db, card.id, "Поправьте заголовок", "web");
await core.updateTask(db, await t.ref(), { status: "in_progress" });
await t.turnEnd("Заголовок уже такой, как вы просили.");
await core.updateTask(db, await t.ref(), { status: "review" });
const again = await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью\n\nЗаголовок проверил.", await t.session());
assert.equal(again?.id, card.id);
assert.equal(again?.answeredAt, null);
assert.equal((await t.asked()).filter((q) => /готова к ревью/.test(q.text)).length, 1);
// A new commit is a new result: a new message.
await core.answerQuestion(db, card.id, "Ещё раз поправьте", "web");
await t.check("def4560", "success");
const fresh = await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью");
assert.notEqual(fresh?.id, card.id);
});
test("Старое сообщение", async () => {
const t = await story();
// Created before the rule: a question without a remembered state.
const [old] = await db.insert(questions).values({ projectId: t.project.id, taskId: t.taskId, sessionId: (await t.session()).id, kind: "attention", text: "Проверки ещё идут." }).returning();
const next = await t.turnEnd("Проверки ещё идут.");
assert.notEqual(next.id, old!.id);
const kept = await core.getQuestion(db, old!.id);
assert.equal(kept.text, "Проверки ещё идут.");
assert.equal(await core.questionState(db, old!.id), null);
});
test("Вопрос агента: второй открытый с тем же текстом не заводится, после ответа — новый", async () => {
const t = await story();
const q = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой разделитель в файле?", options: [";", ","] });
const same = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой разделитель в файле?", options: [";", ","] });
assert.equal(same.id, q.id);
const other = await core.askPm(db, await t.ref(), { kind: "question", text: "Какая кодировка файла?" });
assert.notEqual(other.id, q.id);
await core.answerQuestion(db, q.id, ";", "web");
const later = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой разделитель в файле?", options: [";", ","] });
assert.notEqual(later.id, q.id, "asked again after an answer — a new question");
});
test("Сообщение фабрики по шаблону: то же — одно, другое — новое", async () => {
const t = await story();
const s = await t.session();
const a = await core.raiseSessionQuestion(db, s, "attention", "NA-1: лимит, свободных подписок нет — продолжит в 15:00 сам.");
const b = await core.raiseSessionQuestion(db, s, "attention", "NA-1: лимит, свободных подписок нет — продолжит в 17:30 сам.");
assert.equal(b.id, a.id, "only the time differs");
const c = await core.raiseSessionQuestion(db, s, "attention", "NA-1: ход оборвался с ошибкой overloaded.");
assert.notEqual(c.id, a.id);
});
});
describe("Одинаковые события подряд — одна строка", () => {
test("Десять «агент продолжает работу»; между повторами другое событие", async () => {
const t = await story();
const s = await t.session();
await core.logSessionEvent(db, s, "resumed", {});
assert.equal((await t.thread()).filter((m) => /продолжает работу/.test(m.text)).length, 1);
for (let i = 0; i < 4; i++) await core.logSessionEvent(db, s, "resumed", {});
await t.thread();
for (let i = 0; i < 5; i++) await core.logSessionEvent(db, s, "resumed", {});
await core.syncChats(db);
let lines = (await t.thread()).filter((m) => /продолжает работу/.test(m.text));
assert.equal(lines.length, 1);
assert.equal(lines[0]!.repeats, 9, "×10");
assert.ok(lines[0]!.updatedAt);
await core.logSessionEvent(db, s, "stopped", {});
await core.logSessionEvent(db, s, "resumed", {});
lines = (await t.thread()).filter((m) => /продолжает работу/.test(m.text));
assert.equal(lines.length, 2);
assert.equal(lines[1]!.repeats, 0);
});
});
describe("Напоминание обновляет сообщение", () => {
test("Вопрос без ответа 30 минут; вопрос уже отвечен", async () => {
const t = await story();
const q = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой цвет кнопки?" });
const done = await core.askPm(db, await t.ref(), { kind: "question", text: "Какой шрифт?" });
await core.answerQuestion(db, done.id, "Обычный", "web");
await runner.remindTick(db, { now: new Date(q.createdAt.getTime() + 31 * 60_000), cfg: { ...runner.WATCHDOG_DEFAULTS, remindMin: 30, workFrom: 0, workTo: 24, workDays: [1, 2, 3, 4, 5, 6, 7] }, log: () => {} });
const msgs = (await t.thread()).filter((m) => m.kind === "question");
assert.equal(msgs.length, 2, "no new chat message");
assert.ok(msgs.find((m) => m.question?.id === q.id)!.updatedAt);
assert.equal(msgs.find((m) => m.question?.id === done.id)!.updatedAt, null);
});
});