peppa/packages/testkit/test/bot.test.ts
Асель 00c8f79a36 PEP-7: autonomous mode — board moves start agents, PM only for stoppers
- web board (Backlog / In progress / Review / Done) with drag-and-drop and
  buttons; moveTask starts an agent on In progress, stops on Backlog/Done
- routine proposals go straight to apply; request_approval/ask_pm only for
  architectural stoppers (RULES.md, MCP hints, template pushed to Gitea)
- Stop hook keeps the agent going (decision: block, max 2 in a row,
  sessions.auto_nudges reset by a human answer) instead of pinging the PM
- review: ready-for-review message with Accept (acceptTask → done, session
  stopped) in Telegram and web; a text reply goes back to the agent
- mock-claude honours Stop-hook block; 6 new e2e tests (48 total, green)
- OpenSpec: pep-7 archived (task-autonomy, web-workspace board)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:21:11 +05:00

229 lines
12 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.

// Telegram journeys: the real bot against mock-telegram, with mock agents in tmux.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
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, project, runner, teardown, tick, waitFor } from "./helpers.ts";
import { MockTelegram, type MockTgMessage } from "../src/mock-telegram.ts";
import type { Bot } from "@peppa/bot";
const { createBot } = await import("@peppa/bot");
const { TelegramApi } = await import("@peppa/bot/telegram");
const tg = await new MockTelegram().start();
const PM = { id: 501, chatId: 501, username: "pm" };
const STRANGER = { id: 777, chatId: 777, username: "stranger" };
let bot: Bot;
before(async () => {
bot = createBot({
db,
api: new TelegramApi(tg.token, tg.url),
secret: tg.token,
webUrl: "http://peppa.test",
pollTimeoutSec: 1,
outboxIntervalMs: 100,
reconcileIntervalMs: 400,
});
await bot.start();
});
after(async () => {
await bot.stop();
await tg.stop();
await teardown();
});
const isPrompt = (needle: string) => (e: { ev: string; prompt?: unknown }) => e.ev === "prompt" && String(e.prompt).includes(needle);
/** Waits for the bot message about a question (sent to the PM's chat). */
async function messageFor(questionId: number): Promise<MockTgMessage> {
const q = await waitFor(`telegram message for question #${questionId}`, async () => {
const row = await core.getQuestion(db, questionId);
return row.telegramMessageId ? row : null;
});
return tg.messages.get(q.telegramMessageId!)!;
}
const lastReplyTo = (chatId: number) => tg.botMessages(chatId).at(-1);
describe("pairing", () => {
test("only the /start code holder gets bound; strangers are ignored", async () => {
tg.userSends(STRANGER, "/status");
tg.userSends(PM, "/start wrong-code");
await waitFor("wrong code reply", async () => tg.botMessages(PM.chatId).some((m) => /неверный или истёк/.test(m.text)));
assert.equal(tg.botMessages(STRANGER.chatId).length, 0);
const code = await core.createPairingCode(db, tg.token);
tg.userSends(PM, `/start ${code}`);
await waitFor("paired", async () => tg.botMessages(PM.chatId).some((m) => /Привязано/.test(m.text)));
const b = await core.getBinding(db);
assert.equal(b?.chatId, PM.chatId);
// The code is single-use; a stranger can't take over with it.
tg.userSends(STRANGER, `/start ${code}`);
await waitFor("stranger refused", async () => tg.botMessages(STRANGER.chatId).some((m) => /неверный/.test(m.text)));
assert.equal((await core.getBinding(db))?.userId, PM.id);
tg.userSends(PM, "/status");
await waitFor("status", async () => tg.botMessages(PM.chatId).some((m) => /Активные сессии/.test(m.text)));
});
});
describe("answering from Telegram", () => {
test("question with options: button press reaches the agent, message is closed", async () => {
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"] } }, { say: "Жду." }], [{ say: "Ок." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
assert.match(m.text, /Какую БД взять/);
assert.match(m.text, new RegExp(p.taskKey));
assert.deepEqual(m.reply_markup!.inline_keyboard.map((r) => r[0]!.text), ["Postgres", "SQLite"]);
const cb = tg.userClicks(PM, m.message_id, `q:${q.id}:o0`);
await p.waitLog("answer delivered", isPrompt(`Ответ PM на вопрос #${q.id}: Postgres`));
await waitFor("toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /Отправлено/.test(a.text ?? "")));
await waitFor("message closed", async () => /Ответ в Telegram: <b>Postgres<\/b>/.test(m.text) && m.reply_markup?.inline_keyboard.length === 0);
await runner.stopSession(db, sid);
});
test("approve button moves the task to in_progress", async () => {
const p = await project({ turns: [[{ mcp: "request_approval", args: { task: "1", summary: "План: сделать X. Риски: нет." } }], [{ say: "Делаю." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "approval");
const m = await messageFor(q.id);
tg.userClicks(PM, m.message_id, `q:${q.id}:approve`);
await p.waitLog("approval delivered", isPrompt("одобрил proposal"));
assert.equal((await p.task()).status, "in_progress");
await runner.stopSession(db, sid);
});
test("reply with a comment rejects the proposal", async () => {
const p = await project({ turns: [[{ mcp: "request_approval", args: { task: "1", summary: "План Б для проверки реплая." } }], [{ say: "Переделываю." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "approval");
const m = await messageFor(q.id);
tg.userSends(PM, "нет, без новых зависимостей", m.message_id);
await p.waitLog("rejection delivered", isPrompt("без новых зависимостей"));
assert.equal((await p.task()).status, "proposing");
await waitFor("ack reply", async () => tg.botMessages(PM.chatId).some((x) => x.reply_to && x.text.includes("Отправлено")));
await runner.stopSession(db, sid);
});
test("permission buttons answer the waiting hook", async () => {
const p = await project({ turns: [[{ permission: { tool: "Bash", input: { command: "npm publish" } } }, { say: "Опубликовал." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "permission");
const m = await messageFor(q.id);
assert.match(m.text, /npm publish/);
tg.userClicks(PM, m.message_id, `q:${q.id}:always`);
const e = await p.waitLog("hook decision", (x) => x.ev === "permission");
assert.equal(e.via, "hook");
assert.equal(e.behavior, "allow");
assert.equal(e.updatedPermissions, true);
await runner.stopSession(db, sid);
});
test("free-text reply to a 'session is waiting' alert is typed into the session", async () => {
const p = await project({ turns: [[{ say: "Сделал черновик. Что дальше?" }], [{ say: "Понял." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "attention");
const m = await messageFor(q.id);
assert.match(m.text, /Что дальше/);
tg.userSends(PM, "добавь тесты\nи README", m.message_id);
const e = await p.waitLog("reply delivered", isPrompt("добавь тесты"));
assert.equal(e.prompt, "добавь тесты\nи README");
await runner.stopSession(db, sid);
});
});
describe("review", () => {
test("ready-for-review message: Accept closes the task", async () => {
const p = await project({ turns: [[{ mcp: "update_task", args: { task: "1", status: "review", pr_url: "https://git.example/pr/9" } }, { say: "PR открыт." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "attention");
const m = await messageFor(q.id);
assert.match(m.text, /Готово к ревью/);
const accept = m.reply_markup!.inline_keyboard.flat().find((b) => b.callback_data === `q:${q.id}:accept`);
assert.ok(accept, "accept button");
const cb = tg.userClicks(PM, m.message_id, accept.callback_data!);
await waitFor("accepted toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /принята/.test(a.text ?? "")));
assert.equal((await p.task()).status, "done");
await p.waitStatus(sid, "done");
await waitFor("message closed", async () => /Принято/.test(m.text));
});
});
describe("staleness and reliability", () => {
test("answered in the terminal: Telegram message is closed and old buttons do nothing", async () => {
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Порт сервиса?", options: ["8080", "3000"] } }], [{ say: "Ок." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
await runner.sendToSession(db, sid, "порт 9000");
await waitFor("closed as answered in terminal", async () => /Ответ в терминале/.test(m.text));
const cb = tg.userClicks(PM, m.message_id, `q:${q.id}:o0`);
await waitFor("stale toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /Уже отвечено/.test(a.text ?? "")));
assert.equal(p.log().filter((e) => e.ev === "prompt").length, 2, "no extra prompt from the stale button");
await runner.stopSession(db, sid);
});
test("an update re-delivered after a restart is not replayed", async () => {
const p = await project({ turns: [[{ say: "Жду указаний." }], [{ say: "Ок." }], [{ say: "лишний ход" }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "attention");
const m = await messageFor(q.id);
const updateId = tg.userSends(PM, "сделай раз", m.message_id);
await p.waitLog("delivered once", isPrompt("сделай раз"));
// Simulate a crash before the offset was saved: Telegram sends the update again.
await core.setOffset(db, updateId);
await new Promise((r) => setTimeout(r, 2500));
assert.equal(p.log().filter(isPrompt("сделай раз")).length, 1);
await runner.stopSession(db, sid);
});
test("outbox retries after 429 (retry_after) and 5xx", async () => {
tg.failNext("sendMessage", 429, 1);
tg.failNext("sendMessage", 500);
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Проверка ретраев?" } }], [{ say: "Ок." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
assert.match(m.text, /Проверка ретраев/);
const row = await core.getOutbox(db, `q:${q.id}`);
assert.ok(row && row.attempts >= 2, `expected retries, got ${row?.attempts}`);
await runner.stopSession(db, sid);
});
test("crash alert offers Resume; the button relaunches the session", async () => {
const p = await project({ turns: [[{ crash: 7 }]], resumeTurns: [[{ say: "Поднялся после падения." }]] });
const sid = await p.start();
await p.waitLog("crashed", (e) => e.ev === "exit");
await waitFor("failed", async () => {
await tick();
return (await p.session(sid)).status === "failed";
});
const q = await p.waitQuestion(sid, "attention");
const m = await messageFor(q.id);
assert.match(m.text, /код 7/);
const resume = m.reply_markup!.inline_keyboard[0]!.find((b) => b.callback_data === `s:${sid}:resume`);
assert.ok(resume, "resume button");
const cb = tg.userClicks(PM, m.message_id, resume.callback_data!);
await waitFor("resumed toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /Перезапущено/.test(a.text ?? "")));
await p.waitLog("gen 2 running", (e) => e.ev === "turn_end" && e.gen === "2");
// The old alert is closed as no longer relevant.
await waitFor("old alert closed", async () => /неактуально/.test(m.text));
await runner.stopSession(db, sid);
});
test("tmux killed while waiting: answer is saved, PM told the session is down", async () => {
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Что с API?" } }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await p.session(sid)).tmuxName}`]);
tg.userSends(PM, "используй v2", m.message_id);
await waitFor("down notice", async () => lastReplyTo(PM.chatId)?.text.includes("сессия сейчас не запущена"));
assert.equal((await core.getQuestion(db, q.id)).answer, "используй v2");
});
});